{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p (a:b:_) = (a,b)\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch (check n k arr [1..n-1]) 0 (cost as)\n where\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\ncheck :: Int -> Int -> UArray Int Int64 -> [Int] -> Int -> Bool\ncheck n k arr is obj = or $ zipWith (\\v i -> v + i <= k) (go [0] is) [0..]\n where\n obj' = fromIntegral obj\n go :: [Int] -> [Int] -> [Int]\n go vs [] = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs (i-1) 0 obj' i\n ai = unsafeAt arr i\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs _ x _ m | null vs || x >= m = m\n f (v:vs) j x y m = f vs (j-1) (x+1) (y+obj') m'\n where\n aj = unsafeAt arr j\n m' | ai - aj > y || ai - aj < - y = m \n | otherwise = min m (v + x)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p (a:b:_) = (a,b)\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch (check n k arr [1..n-1]) 0 (cost as)\n where\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\ncheck :: Int -> Int -> UArray Int Int64 -> [Int] -> Int -> Bool\ncheck n k arr is obj = minimum (zipWith (+) [0..] $ go [0] is) <= k\n where\n obj' = fromIntegral obj\n go :: [Int] -> [Int] -> [Int]\n go vs [] = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs (i-1) 0 obj' i\n ai = unsafeAt arr i\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs (-1) x y m = m\n f (v:vs) !j !x !y !m = f vs (j-1) (x+1) (y+obj') m'\n where\n aj = unsafeAt arr j\n m' | ai - aj > y || ai - aj < - y = m \n | otherwise = min m (v + x)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\nl2p (a:b:_) = (a,b)\n\ntype UArray1 a = UArray Int a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch f 0 (cost as)\n where\n as' = listArray (1,n) (map fromIntegral as) :: UArray1 Int64\n f obj = minPos2 n as' (fromIntegral obj) <= k\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\nminPos :: Int -> UArray1 Int64 -> Int64 -> Int\nminPos n as obj = minimum $ zipWith (+) [n-1,n-2..] (elems dp)\n where\n dp :: UArray1 Int\n dp = fixMemoUArray (1,n) f\n f :: RecFun (ST s) Int Int\n f _ 1 = return 0\n f g i = h (i-1) 1 (i-1)\n where\n a = as ! i\n check j x = inRange (a - x * obj, a + x * obj) (as ! j)\n h j x m | j == 0 || i - 1 - j >= m = return m\n h !j !x !m | check j x = g j >>= (\\v -> h (j-1) (x+1) $ min m (v+i-1-j))\n | otherwise = h (j-1) (x+1) m\n\nminPos1 :: Int -> UArray1 Int64 -> Int64 -> Int\nminPos1 n as obj = minimum $ zipWith (+) [n-1,n-2..] (elems dp)\n where\n dp :: Array Int Int\n dp = listArray (1,n) [f i | i <- [1..n]] \n f 1 = 0\n f i = h (i-1) 1 (i-1)\n where\n a = as ! i\n check j x = inRange (a - x * obj, a + x * obj) (as ! j)\n h 0 x m = m\n h !j !x !m {- | i - 1 - j >= m = m-}\n | check j x = h (j-1) (x+1) $ min m ((dp!j)+i-1-j)\n | otherwise = h (j-1) (x+1) m\n\nminPos2 :: Int -> UArray1 Int64 -> Int64 -> Int\nminPos2 n as obj = minimum $ zipWith (+) [n-1,n-2..] (elems dp)\n where\n check a j x = inRange (a - x * obj, a + x * obj) (as ! j)\n dp :: UArray1 Int\n dp = runSTUArray $ do\n memo <- newArray_ (1,n)\n writeArray memo 1 0\n forM_ [1..n] $ \\i -> do\n let a = as ! i\n writeArray memo i (i-1)\n h memo a i (i-1) (i-1)\n return memo\n h memo a i j m | i - 1 - j >= m = return ()\n h memo a i j m = \n if check a j (fromIntegral $ i-j) then do\n v <- readArray memo j\n let m' = min m (v+i-1-j)\n writeArray memo i m'\n h memo a i (j-1) m'\n else \n h memo a i (j-1) m\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\n--{-\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\n---}\n\n--readInt :: String -> Int\n--readInt = read\n--readInts = map readInt . words <$> getLine\n--readIntPair = l2p . map readInt . take 2 . words <$> getLine\nl2p (a:b:_) = (a,b)\n\n\n{-# INLINE mid #-}\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\n{-# INLINE binSearch #-}\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch f 0 (cost as)\n where\n --ass = drop 2 $ reverse $ tails $ reverse $ map fromIntegral as\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n {-# INLINE f #-}\n f obj = (<=k) $ minPos n arr (fromIntegral obj)\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\nminPos :: Int -> UArray Int Int64 -> Int64 -> Int\nminPos n arr obj = minimum $ zipWith (+) [0..] $ go [0] [1..]\n where\n go :: [Int] -> [Int] -> [Int]\n go vs (i:is) | i >= n = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs i 0 obj i\n ai = arr ! (i+1)\n {-# INLINE f #-}\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs j x y m | x >= m = m\n f (v:vs) !j !x !y !m = f vs (j-1) (x+1) (y+obj) m'\n where\n aj = arr ! j\n m' | ai - aj > y || ai - aj < -y = m \n | otherwise = min m (v + x)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p (a:b:_) = (a,b)\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b \n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch (check n k arr [1..n-1]) 0 (cost as)\n where\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\ncheck :: Int -> Int -> UArray Int Int64 -> [Int] -> Int -> Bool\ncheck n k arr is obj = or $ zipWith (\\v i -> v + i <= k) (go [0] is) [0..]\n where\n obj' = fromIntegral obj\n go :: [Int] -> [Int] -> [Int]\n go vs [] = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs (i-1) 0 obj' i\n ai = unsafeAt arr i\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs _ x _ m | null vs || x >= m = m\n f (v:vs) j x y m = f vs (j-1) (x+1) (y+obj') m'\n where\n aj = unsafeAt arr j\n m' | ai - aj > y || ai - aj < - y = m \n | otherwise = min m (v + x)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p (a:b:_) = (a,b)\n{-# INLINE mid #-}\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\n{-# INLINE binSearch #-}\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch f 0 (cost as)\n where\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n {-# INLINE f #-}\n f obj = (<=k) $ minPos n arr (fromIntegral obj)\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\nminPos :: Int -> UArray Int Int64 -> Int64 -> Int\nminPos n arr obj = minimum $ zipWith (+) [0..] $ go [0] [1..]\n where\n go :: [Int] -> [Int] -> [Int]\n go vs (i:is) | i >= n = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs i 0 obj i\n ai = unsafeAt arr i\n {-# INLINE f #-}\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs j x y m | x >= m = m\n f (v:vs) !j !x !y !m = f vs (j-1) (x+1) (y+obj) m'\n where\n aj = unsafeAt arr (j-1)\n m' | ai - aj > y || ai - aj < -y = m \n | otherwise = min m (v + x)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\nl2p (a:b:_) = (a,b)\n\ntype UArray1 a = UArray Int a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = (a + b) `div` 2\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch f 0 (cost as)\n where\n as' = listArray (1,n) (map fromIntegral as) :: UArray1 Int64\n f obj = minPos n as' (fromIntegral obj) <= k\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\nminPos :: Int -> UArray1 Int64 -> Int64 -> Int\nminPos n as obj = minimum $ zipWith (+) [n-1,n-2..] (elems dp)\n where\n dp :: UArray1 Int\n dp = fixMemoUArray (1,n) f\n f :: RecFun (ST s) Int Int\n f _ 1 = return 0\n f g i = minimum . catMaybes <$> zipWithM h [i-1,i-2..0] [1..]\n where\n a = as ! i\n check j x = inRange (a - x * obj, a + x * obj) (as ! j)\n h 0 _ = return $ Just (i-1)\n h j x | check j x = (\\v -> Just $ v+i-1-j) <$> g j\n | otherwise = return Nothing\n"}, {"source_code": "main = print (maxBound :: Int)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p (a:b:_) = (a,b)\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch (check n k arr [1..n-1]) 0 (cost as)\n where\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\ncheck :: Int -> Int -> UArray Int Int64 -> [Int] -> Int -> Bool\ncheck n k arr is obj = minimum (zipWith (+) [0..] $ go [0] is) <= k\n where\n obj' = fromIntegral obj\n go :: [Int] -> [Int] -> [Int]\n go vs [] = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs (i-1) 0 obj' i\n ai = unsafeAt arr i\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs 0 x y m = m\n f (v:vs) !j !x !y !m = f vs (j-1) (x+1) (y+obj') m'\n where\n aj = unsafeAt arr j\n m' | ai - aj > y || ai - aj < - y = m \n | otherwise = min m (v + x)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p (a:b:_) = (a,b)\n{-# INLINE mid #-}\nmid :: Int -> Int -> Int\nmid x y = fromIntegral $ (fromIntegral x + fromIntegral y :: Int64) `div` 2\n\n{-# INLINE binSearch #-}\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = do\n if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = mid a b\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch f 0 (cost as)\n where\n arr = listArray (1,n) (map fromIntegral as) :: UArray Int Int64\n {-# INLINE f #-}\n f obj = (<=k) $ minPos n arr (fromIntegral obj)\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\nminPos :: Int -> UArray Int Int64 -> Int64 -> Int\nminPos n arr obj = minimum $ zipWith (+) [0..] $ go [0] [1..]\n where\n go :: [Int] -> [Int] -> [Int]\n go vs (i:is) | i >= n = vs\n go vs (i:is) = go (v:vs) is\n where\n v = f vs i 0 obj i\n ai = unsafeAt arr (i+1)\n {-# INLINE f #-}\n f :: [Int] -> Int -> Int -> Int64 -> Int -> Int\n f vs j x y m | x >= m = m\n f (v:vs) !j !x !y !m = f vs (j-1) (x+1) (y+obj) m'\n where\n aj = unsafeAt arr j\n m' | ai - aj > y || ai - aj < -y = m \n | otherwise = min m (v + x)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = binSearch f 0 (cost as)\n where\n as' :: UArray1 Int\n as' = listArray (1,n) as\n f obj = minPos n as' (fromIntegral obj) <= k\n\ncost :: [Int] -> Int\ncost as = maximum $ zipWith (\\a b -> abs (a-b)) as (tail as)\n\nminPos :: Int -> UArray1 Int -> Int64 -> Int\nminPos n as obj = minimum $ zipWith (+) [n-1,n-2..] (elems dp)\n where\n dp :: UArray1 Int\n dp = fixMemoUArray (1,n) f\n f :: RecFun (ST s) Int Int\n f g 1 = return 0\n f g i = go (i-1) (i-1)\n where\n a = fromIntegral (as ! i)\n go 0 m = return m\n go !j !m = do\n let x = fromIntegral (i - 1 - j+1)\n aj = fromIntegral (as ! j)\n v <- g j\n let m' | inRange (a - x * obj,a + x * obj) aj = min m (v+(i-1-j)) \n | otherwise = m\n go (j-1) m'\n\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p a b = if p a then a else go a b\n where\n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = (a + b) `div` 2\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\ntype IndexSet = S.Set (Int,Int)\nsingleton :: (Int,Int) -> IndexSet\nsingleton = S.singleton\nexpand :: IndexSet -> Int -> IndexSet\nexpand s c = S.fromAscList $ myunion $ map ((+) (-c) *** (+) c) $ S.elems s\ndist s p = minimum $ map (dist1 p) $ S.elems s\n\ndist1 c (a,b) | a <= c && c <= b = 0\n | otherwise = min (abs (a-c)) (abs (b-c))\n\nappend s p | dist s p == 0 = s\n | otherwise = S.insert (p,p) s\n\nmyunion (x:xs) = go x xs\n where\n go x [] = [x]\n go (a,b) ((c,d):xs) | c <= b = go (a,d) xs\n | otherwise = (a,b):go (c,d) xs\n\ninf :: Int\ninf = 10^9\n\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = fst $ dp ! (n,k)\n where\n a :: UArray Int Int\n a = listArray (1,n) as\n dp :: Array (Int,Int) (Int,IndexSet)\n dp = listArray ((1,0),(n,k)) [ f i j | i <- [1..n], j <- [0..k]]\n f 1 0 = (0,singleton (a ! 1,a ! 1))\n f 1 j = (0,singleton (-inf,inf))\n f i 0 = let c = max (fst (dp ! (i-1,0))) (abs (a ! (i-1) - a ! i)) in\n (c,singleton (a ! i,a ! i))\n f i j | c3 < c4 = (c3,s3)\n | c4 < c3 = (c4,s4)\n | otherwise = (c3,append s4 (a ! i))\n where\n (c1,s1) = dp ! (i-1,j)\n (c2,s2) = dp ! (i-1,j-1)\n c3 = max c1 (dist s1 (a ! i))\n s3 = singleton (a ! i, a ! i)\n c4 = c2\n s4 = expand s2 c2\n"}], "src_uid": "544dd0c7274ac337744b8ba0996add1d"} {"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\ndiff 12 = 0\ndiff n = n\n\n--gettime tod h m\ngettime a 12 m = dogettime a 0 m\ngettime a h m = dogettime a h m\n\ndogettime 'a' h m = h*60 + m\ndogettime 'p' h m = (h+12)*60 + m\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n gettime tod ((c2o a1)*10 + (c2o a2)) ((c2o b1)*10 + (c2o b2))\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else 0\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n", "positive_code": [{"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.Functor\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- read <$> getLine\n ts <- map f `liftM` replicateM n getLine\n let inc | length ts == 1 = 0\n | last ts == 24*60 = 1\n | True = 0\n a = foldr (\\xs v -> v + (length xs-1) `div` 10) 0 $ group ts\n b = length . filter id . zipWith (>) ts $ tail ts\n return . show $ a+b+1\n where\n f cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n hour | read h' == 12 = 0\n | True = read h'\n in (hour + hour') * 60 + read m'\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n\n"}], "negative_code": [{"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n ((c2o tod)*60*60*12 +\n ((c2o a1)*10 + (c2o a2))*60*60 +\n ((c2o b1)*10 + (c2o b2))*60)\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else doubles\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n"}, {"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\ndiff 12 = 0\ndiff n = n\n\n--gettime tod h m\ngettime 'a' 12 m = gettime 'p' 0 m\ngettime 'p' 12 m = gettime 'a' 0 m\ngettime 'a' h m = h*60 + m\ngettime 'p' h m = (h+12)*60 + m\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n gettime tod ((c2o a1)*10 + (c2o a2)) ((c2o b1)*10 + (c2o b2))\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else doubles\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n"}, {"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\ndiff 12 = 0\ndiff n = n\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n ((d tod)*60*60*12 +\n (diff ((c2o a1)*10 + (c2o a2)))*60*60 +\n ((c2o b1)*10 + (c2o b2))*60)\n where d 'a' = 0\n d 'p' = 1\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else doubles\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n"}, {"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n ((d tod)*60*60*12 +\n ((c2o a1)*10 + (c2o a2))*60*60 +\n ((c2o b1)*10 + (c2o b2))*60)\n where d 'a' = 0\n d 'p' = 1\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else doubles\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- fmap read getLine\n ts <- map f `liftM` replicateM n getLine\n return . show . (1+) . length . filter id . zipWith (>) ts $ tail ts\n where\n f cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n in (read h' + hour') * 60 + read m'\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- fmap read getLine\n ts <- map f `liftM` replicateM n getLine\n return . show . (1+) . length . filter id . zipWith (>) ts $ tail ts\n where\n f cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n in (`mod` (24*60)) $ (read h' + hour') * 60 + read m'\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- fmap read getLine\n ts <- map f `liftM` replicateM n getLine\n let inc | length ts == 1 = 0\n | last ts == 24*60 = 1\n | True = 0\n return . show . (1+) . length . filter id\n . zipWith (>) ts $ tail ts\n where\n f cs = g cs\n g cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n in ((read h' + hour') * 60 + read m') `mod` (24*60)\n\nmain = putStrLn =<< solve\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- fmap read getLine\n ts <- map f `liftM` replicateM n getLine\n let inc | last ts == 24*60 = 1\n | True = 0\n return . show . (inc+1+) . length . filter id . zipWith (>) ts $ tail ts\n where\n f cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n in (read h' + hour') * 60 + read m'\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- fmap read getLine\n ts <- map f `liftM` replicateM n getLine\n let inc | length ts == 1 = 0\n | last ts == 24*60 = 1\n | True = 0\n return . show . (inc+1+) . length . filter id\n . zipWith (>) ts $ tail ts\n where\n f cs = g cs\n g cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n in (read h' + hour') * 60 + read m'\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.Functor\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- read <$> getLine\n ts <- map f `liftM` replicateM n getLine\n let inc | length ts == 1 = 0\n | last ts == 24*60 = 1\n | True = 0\n a = foldr (\\xs v -> v + length xs `div` 10) 0 $ group ts\n b = length . filter id . zipWith (>) ts $ tail ts\n return . show $ a+b+1\n where\n f cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n hour | read h' == 12 = 0\n | True = read h'\n in (hour + hour') * 60 + read m'\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Text.Printf\n\nimport Data.Functor\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nimport Debug.Trace\n\nsep :: Char -> String -> [String]\nsep c s = case dropWhile (c==) s of\n \"\" -> []\n s' -> w : sep c s''\n where (w, s'') = break (c==) s'\n\ncut a b = drop a . take (b+1)\n\nsolve = do n <- read <$> getLine\n ts <- map f `liftM` replicateM n getLine\n let inc | length ts == 1 = 0\n | last ts == 24*60 = 1\n | True = 0\n a = foldr (\\xs v -> v + length xs `div` 10) 0 $ group ts\n b = (1+) . length . filter id\n . zipWith (>) ts $ tail ts\n return . show $ a+b\n where\n f cs = let cs' = cut 1 7 cs\n hour' | last cs' == 'a' = 0\n | True = 12\n (h':m':[]) = sep ':' $ take 5 cs'\n in ((read h' + hour') * 60 + read m') `mod` (24*60)\n\nmain = putStrLn =<< solve\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Rational where\n read' = toRational . (read :: String -> Integer)\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\ndiff 12 = 0\ndiff n = n\n\n--gettime tod h m\ngettime 'a' 12 m = gettime 'a' 0 m\ngettime 'p' 12 m = gettime 'a' 12 m\ngettime 'a' h m = h*60 + m\ngettime 'p' h m = (h+12)*60 + m\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n gettime tod ((c2o a1)*10 + (c2o a2)) ((c2o b1)*10 + (c2o b2))\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else doubles\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n"}, {"source_code": "import Data.Char\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nc2o :: Char -> Int\nc2o c = (ord c) - ord '0'\n\ndiff 12 = 0\ndiff n = n\n\n--gettime tod h m\ngettime 'a' 12 m = dogettime 'a' 0 m\ngettime 'p' 12 m = dogettime 'a' 12 m\ngettime a h m = dogettime a h m\n\ndogettime 'a' h m = h*60 + m\ndogettime 'p' h m = (h+12)*60 + m\n\nlog2time ('[':a1:a2:':':b1:b2:' ':tod:_) =\n gettime tod ((c2o a1)*10 + (c2o a2)) ((c2o b1)*10 + (c2o b2))\n\ncount l n 10 = count l (n+1) 0\ncount [log] n doubles = n\ncount (l1:l2:ls) n doubles | l1 > l2 = count (l2:ls) (n+1) 0\n | True = count (l2:ls) n doubles2\n where doubles2 = if (l1 == l2) then (doubles+1) else doubles\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n:_ = un s\n log <- getLines n\n let times = map log2time log\n days = count times 1 0\n --putStrLn $ show times\n putStrLn $ show days\n"}], "src_uid": "54f8b8e6711ff5c69e0bc38a6e2f4999"} {"source_code": "-- Codeforces Round #533 Div.2 (A), Contest 1105, Problem set ?.\n-- UNDONE\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (BS.readInt . BS.dropWhile (==' ')) <$> BS.getLine\n let (t,cost) =\n minimumBy (compare `on` snd) $\n map (\\t ->(t, sum $ filter (>0) $ map ((subtract 1).abs.(t-)) as))\n [1..100]\n putStrLn $ shows t $ ' ' : show cost\n \n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\t( c, t ) = minimum $ do\n\t\t\tt <- [ 1 .. 100 ]\n\t\t\tlet\n\t\t\t\tc = sum $ filter ( 0 <= ) $ map ( pred . abs . subtract t ) as\n\t\t\treturn ( c, t )\n\tprintf \"%d %d\\n\" t c\n"}], "negative_code": [], "src_uid": "bce9ebad1dc8bd5aae516c4ca9e551c0"} {"source_code": "import Data.List\nimport Data.Char\nimport Control.Exception\nimport Control.Monad\n\nreadVal :: Read a => IO a\nreadVal = (return . read) =<< getWord_ True\n where\n delimiter = (`elem` \" \\n\")\n getWord_ :: Bool -> IO String\n getWord_ first = do\n c <- catch getChar ((\\msg -> return ' ') :: IOException -> IO Char)\n if delimiter c\n then\n if first\n then getWord_ True\n else return \"\"\n else do\n xs <- getWord_ False\n return $ c : xs\n\n\nsolve' num n\n\t| n < 0 = -1\n\t| mod n 2 == 1 = solve' (num+1) (n-9)\n\t| mod n 4 == 0 = num + (div n 4)\n\t| otherwise = solve' (num+1) (n-6)\n\nsolve = solve' 0\n\nsubtask = print =<< fmap solve readVal\n\nmain = readVal >>= (flip replicateM_ subtask)\n", "positive_code": [{"source_code": "main = interact (unwords . map (show . solve . read) . tail . words)\nsolve 1 = -1 :: Int\nsolve 2 = -1\nsolve 3 = -1\nsolve 5 = -1\nsolve 7 = -1\nsolve 11 = -1\nsolve n = case quotRem n 4 of\n (q, 0) -> q\n (q, 2) -> q\n (_, 1) -> 1 + solve (n - 9)\n (_, 3) -> 1 + solve (n - 6)"}, {"source_code": "import Data.List\n\ncomposites :: [Int]\ncomposites = [4, 6, 9]\n\nmaxLength :: [[Int]] -> [Int]\nmaxLength a =\n maximumBy helper a\n where\n helper a b =\n if a == b\n then EQ\n else if (length a) > (length b)\n then GT\n else LT\n\nhelper :: Int -> [Int] -> Int -> Int -> [Int]\nhelper n solution sum_solution candidate\n | new_solution > n = []\n | new_solution == n = candidate:solution\n | otherwise =\n if length filtered > 0\n then maxLength filtered\n else []\n where\n new_solution = candidate + sum_solution\n results = map (helper n (candidate:solution) new_solution) composites\n filtered = filter (not . null) $ results\n\nsplit :: Int -> [Int]\nsplit n =\n maxLength $ map (helper n [] 0) composites\n\nsplit2 :: Int -> [Int]\nsplit2 n\n | n < 12 = split n\n | n `mod` 4 == 0 = take (n `div` 4) (repeat 4)\n | n `mod` 4 == 1 = take ((n-8) `div` 4) (repeat 4) ++ [9]\n | n `mod` 4 == 2 = take ((n-4) `div` 4) (repeat 4) ++ [6]\n | n `mod` 4 == 3 = take ((n-15) `div` 4) (repeat 4) ++ [6,9]\n | otherwise = []\n\nsolve n\n | n < 12 = if l > 0 then l else -1\n | n `mod` 4 == 0 = n `div` 4\n | n `mod` 4 == 1 = (n-8) `div` 4 + 1\n | n `mod` 4 == 2 = (n-4) `div` 4 + 1\n | n `mod` 4 == 3 = (n-15) `div` 4 + 2\n where\n l = length $ split n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nreadLines :: Int -> IO [Int]\nreadLines 0 = return []\nreadLines n = do\n x <- fmap read getLine\n rest <- readLines (n-1)\n return $ x : rest\n\nreadSomeNumberOfLines :: IO [Int]\nreadSomeNumberOfLines = do\n n <- fmap read getLine\n readLines n\n\nmain = do\n queries <- readSomeNumberOfLines\n putStrLn $ intercalate \"\\n\" $ map (show . solve) queries\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Control.Exception\nimport Control.Monad\n\nreadVal :: Read a => IO a\nreadVal = (return . read) =<< getWord_ True\n where\n delimiter = (`elem` \" \\n\")\n getWord_ :: Bool -> IO String\n getWord_ first = do\n c <- catch getChar ((\\msg -> return ' ') :: IOException -> IO Char)\n if delimiter c\n then\n if first\n then getWord_ True\n else return \"\"\n else do\n xs <- getWord_ False\n return $ c : xs\n\n\nsolve' num n\n\t| n < 0 = -1\n\t| mod n 2 == 1 = solve' (num+1) (n-5)\n\t| mod n 4 == 0 = num + (div n 4)\n\t| otherwise = solve' (num+1) (n-6)\n\nsolve = solve' 0\n\nsubtask = print =<< fmap solve readVal\n\nmain = readVal >>= (flip replicateM_ subtask)\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Exception\nimport Control.Monad\n\nreadVal :: Read a => IO a\nreadVal = (return . read) =<< getWord_ True\n where\n delimiter = (`elem` \" \\n\")\n getWord_ :: Bool -> IO String\n getWord_ first = do\n c <- catch getChar ((\\msg -> return ' ') :: IOException -> IO Char)\n if delimiter c\n then\n if first\n then getWord_ True\n else return \"\"\n else do\n xs <- getWord_ False\n return $ c : xs\n\n\nsolve' num n\n\t| n < 0 = -1\n\t| mod n 2 == 1 = solve' (num+1) (n-1)\n\t| mod n 4 == 0 = num + (div n 4)\n\t| otherwise = solve' (num+1) (n-6)\n\nsolve = solve' 0\n\nsubtask = print =<< fmap solve readVal\n\nmain = readVal >>= (flip replicateM_ subtask)\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Exception\nimport Control.Monad\n\nreadVal :: Read a => IO a\nreadVal = (return . read) =<< getWord_ True\n where\n delimiter = (`elem` \" \\n\")\n getWord_ :: Bool -> IO String\n getWord_ first = do\n c <- catch getChar ((\\msg -> return ' ') :: IOException -> IO Char)\n if delimiter c\n then\n if first\n then getWord_ True\n else return \"\"\n else do\n xs <- getWord_ False\n return $ c : xs\n\n\nsolve' num n\n\t| n < 0 = -1\n\t| mod n 2 == 1 = solve' (num+1) (n+1)\n\t| mod n 4 == 0 = num + (div n 4)\n\t| otherwise = solve' (num+1) (n-6)\n\nsolve = solve' 0\n\nsubtask = print =<< fmap solve readVal\n\nmain = readVal >>= (flip replicateM_ subtask)\n"}], "src_uid": "0c2550b2df0849a62969edf5b73e0ac5"} {"source_code": "module Main (main) where\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n l1 <- getLine\n l2 <- getLine\n putStrLn . output . solve . input l1 $ l2\n\n-- | input\ninput :: String -> String -> (Int, [Int])\ninput l1 l2 = (read l1, map read . words $ l2)\n\n-- | solution\nsolve :: (Int,[Int]) -> Bool\nsolve (n,as) = head t2 /= (head . tail $ t2)\n where\n t2 = drop (n - 1) . sort $ as\n\n-- | output\noutput :: Bool -> String\noutput ok = if ok then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "import Text.Printf (printf)\nimport Data.List\n\n-- This function should return a list [area, volume].\nansstr :: Bool -> String\nansstr True = \"YES\"\nansstr False = \"NO\"\n\n \n--Complete this function--\n\n--Input/Output.\nmain :: IO ()\nmain = getContents >>= \n (putStrLn). ansstr.(\\[[n],xs] -> let sx = sort xs in sx !! n /= sx !! (n - 1)). map (map read. words). lines"}, {"source_code": "import Data.List\n\nmain = do\n n <- fmap (read :: String -> Integer) getLine\n elems <- getLine >>= readArray\n putStrLn $ if solve elems then \"YES\" else \"NO\"\n \nreadArray :: String -> IO [Integer]\nreadArray as = return $ map (read :: String -> Integer) $ words as\n \nsolve :: [Integer] -> Bool\nsolve xs = all id $ zipWith (<) as bs where\n (as, bs) = divide $ sort xs\n divide ls = (take n ls, reverse $ drop n ls) where \n n = length ls `div` 2"}, {"source_code": "main = do\n\tgetLine\n\tline <- getLine\n\tputStrLn $ f line\n\t--print $ midGreater' [1,2,3,4]\n\nqs [] = []\nqs (p:xs) = qs lo ++ [p] ++ qs hi\n\twhere\n\t\tlo = [x | x <- xs, x <= p]\n\t\thi = [x | x <- xs, x > p]\n \nif' :: Bool -> a -> a -> a\nif' True a _ = a\nif' False _ a = a\n\nmidGreater :: [Int] -> [Int] -> Bool\nmidGreater [_, _] (a:b:_) = a < b\nmidGreater (_:_:xs) (_:ys) = midGreater xs ys\nmidGreater _ _ = False\n\nmidGreater' x = midGreater x x\n\nf x = if' (midGreater' $ qs zs) \"YES\" \"NO\"\n\twhere \n\t\tzs = map read $ words x :: [Int]\n"}, {"source_code": "-- Educational Codeforces Round 27\n-- http://codeforces.com/contest/845/problem/A\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\ngetInt = read <$> getLine :: IO Int\ngetInts = (map read . words) <$> getLine :: IO [Int]\n\nmain = do\n n <- getInt\n xs <- sort <$> getInts\n let (small,large) = (take n xs, drop n xs)\n if head large > head (reverse small)\n then putStrLn \"YES\"\n else putStrLn \"NO\""}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n xs <- replicateM (2 * n) poi\n return $ if all (uncurry (<)) $ uncurry (liftM2 (,)) $ splitAt n $ sort xs then \"YES\" else \"NO\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: [Int] -> String\nsolve xs\n | m > n = \"YES\"\n | otherwise = \"NO\"\n where m = foldr1 min team1\n n = foldr1 max team2\n team1 = drop half sorted\n team2 = take half sorted\n half = length xs `div` 2\n sorted = sort xs\n\nmain = do\n getLine >> getLine >>= putStrLn.solve.map read.words\n\n"}, {"source_code": "\nimport Data.List\n\nread_strings = do\n line <- getLine\n return (words $ line)\n\nread_ints = do\n l <- read_strings\n return (map read l :: [Int])\n\nmain = do\n n <- readLn\n arr' <- read_ints\n\n let arr = sort arr'\n if (arr !! n) == (arr !! (n - 1))\n then putStr(\"NO\")\n else putStr(\"YES\")\n \n"}, {"source_code": "import Data.List\nsolve x\n\t|maximum aread n::Int) (take (2*(read x::Int))$words y)\n\t\t\nmain=interact$solve.extract.lines"}, {"source_code": "import qualified Data.Char as C\nimport qualified Data.List as L\n\nreadIntList :: String -> [Int]\nreadIntList s = loop s []\n where loop [] rs = reverse rs\n loop ss rs = loop ss_3 ((read ss_2) : rs)\n where ss_1 = dropWhile (C.isSpace) ss\n (ss_2, ss_3) = L.span (not . C.isSpace) ss_1\n\nmain =\n do\n n_str <- getLine\n let n = (read n_str) :: Int\n rs_str <- getLine\n let rs = readIntList rs_str\n let (f, s) = L.splitAt n (L.sort rs)\n let f_l = last f\n let s_h = head s\n if f_l < s_h \n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Data.List (sort)\n\nmain = do\n (read -> n) <- getLine\n (drop (n - 1) . sort . map (read :: String -> Int) . words -> (x:y:_)) <- getLine\n putStrLn $ if x == y then \"NO\" else \"YES\"\n"}, {"source_code": "-- 845A\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\ntoInt = fst . fromJust . B.readInt\n\nmain = B.interact $ program . (map . map) toInt . map B.words . B.lines\n\nprogram ([n]:xs:_) = f . drop (n-1) $ sort xs\n\nf (a:b:_) = if a < b\n then \"YES\\n\"\n else \"NO\\n\""}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n n <- fmap (read :: String -> Integer) getLine\n elems <- getLine >>= readArray\n putStrLn $ if solve elems then \"YES\" else \"NO\"\n \nreadArray :: String -> IO [Integer]\nreadArray as = return $ map (read :: String -> Integer) $ words as\n \nsolve :: [Integer] -> Bool\nsolve xs = all id $ zipWith (<) as bs where\n (as, bs) = divide $ sort xs\n divide ls = (take n ls, drop n ls) where \n n = length ls `div` 2"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n xs <- replicateM (2 * n) poi\n return $ if all (uncurry (<)) $uncurry zip $ splitAt n $ sort xs then \"YES\" else \"NO\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt"}, {"source_code": "import Text.Printf (printf)\nimport Data.List\n\n-- This function should return a list [area, volume].\nansstr :: Bool -> String\nansstr True = \"YES\"\nansstr False = \"NO\"\n\n \n--Complete this function--\n\n--Input/Output.\nmain :: IO ()\nmain = getContents >>= \n (putStrLn). ansstr.(\\[[n],xs] -> let sx = sort xs in xs !! n /= xs !! (n - 1)). map (map read. words). lines"}], "src_uid": "7b806b9a402a83a5b8943e7f3436cc9a"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n xs <- map read.words <$> getLine\n forM_ (solve xs n) (putStrLn . unwords . map show)\n\nsolve :: [Int] -> Int -> [[Int]]\nsolve xs n = take (n-1) $ toLs (map snd e) ++ toLs (map snd o)\n where\n (e,o) = partition (even.fst) (zip xs [1..])\n\ntoLs :: [Int] -> [[Int]]\ntoLs [] = []\ntoLs [_] = []\ntoLs (x:y:ys) = [x,y]:toLs ys\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n putStr $ unlines . map (\\(a, b) -> show a ++ ' ' : show b) $ solve as\n\nsolve as\n | null odds = listPairs $ snd <$> tail (tail evens)\n | odd (length odds) = listPairs $ snd <$> tail odds ++ tail evens\n | otherwise = listPairs $ snd <$> tail (tail odds) ++ evens\n where\n (odds, evens) = partition (odd . fst) (zip as [1 ..])\n\nlistPairs [] = []\nlistPairs [_] = undefined\nlistPairs (a : b : t) = (a, b) : listPairs t\n"}, {"source_code": "module Main where\nimport Data.List (partition)\n\nsolve :: [Integer] -> [(Integer, Integer)]\nsolve a = let (xs, ys) = partition (even . snd) (zip [1..] a)\n odds = length ys\n in if odds `mod` 2 == 1\n then solve' (map fst (tail xs)) (map fst (tail ys))\n else if odds >= 2\n then solve' (map fst xs) (map fst (tail (tail ys)))\n else solve' (map fst (tail (tail xs))) (map fst ys)\n \nsolve' :: [Integer] -> [Integer] -> [(Integer, Integer)]\nsolve' (x0:x1:xs) ys = (x0, x1) : solve' xs ys\nsolve' [] (y0:y1:ys) = (y0, y1) : solve' [] ys\nsolve' [] [] = []\n\nsolveCase :: Int-> IO ()\nsolveCase i = do _ <- getLine\n a <- map read <$> words <$> getLine\n putStr $ unlines $ map (\\ (x, y) -> (show x) ++ \" \" ++ (show y)) $ solve a\n \n\nmain :: IO [()]\nmain = do t <- read <$> getLine\n mapM solveCase [1..t]\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n xs <- map read.words <$> getLine\n forM_ (solve xs n) (putStrLn . unwords . map show)\n\nsolve :: [Int] -> Int -> [[Int]]\nsolve xs n = take (n-1) $ toLs e ++ toLs o\n where\n (e,o) = partition even xs\n\ntoLs :: [Int] -> [[Int]]\ntoLs [] = []\ntoLs [_] = []\ntoLs (x:y:ys) = [x,y]:toLs ys\n"}], "src_uid": "96fac9f9377bf03e144067bf93716d3d"} {"source_code": "import Control.Monad\nimport Data.List\nf pos c | x10 > r+h1 = (1 + num,0)\n | x21 >h1 = (1 + num,h1) --right\n | otherwise = (num,0) -- not\n where (x10,h1,x21) = head pos\n num = fst c\n r = snd c \niterateh' f [] l = l\niterateh' f h l = iterateh' f (tail h) $!(f h l)\nmakeTriple h n| n == 2 = []\n | otherwise = (x10,h1,x21):makeTriple t0 (n-1)\n where preA = head h\n t0 = tail h\n a = head t0\n t1 = tail t0\n nextA = head t1\n x1 = fst a\n x0 = fst preA\n x2 = fst nextA\n h1 = snd a\n x10 = x1 - x0\n x21 = x2 - x1\ntoTup a = ((w !! 0),(w !! 1))\n where w = [read n::Int| n <-(words a)]\ndoit (a,b,c) (d,e,f) = (a,e,f)\nmain = do\n w0 <- getLine\n let n= read w0::Int\n w1 <- getContents\n let s = lines w1\n let a = map toTup s\n if n == 1 then print 1 else print $ fst $ iterateh' f (makeTriple a n) (2,0)\n \n \n \n \n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad\n\ndata Tree = Tree {\n coord :: {-# UNPACK #-} !Int\n , height :: {-# UNPACK #-} !Int\n } deriving (Show, Eq)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n trees <- replicateM n $ do\n [x, h] <- map read . words <$> getLine\n return $ Tree x h\n print $ solve trees\n\nsolve :: [Tree] -> Int\nsolve [] = 0\nsolve [_] = 1\nsolve (Tree firstPoint _ : rest) = go 1 firstPoint rest\n where\n go !felled _ [_] = felled + 1\n go !felled pointToLeft (Tree x1 h1 : ts@(~(Tree x2 _) : _))\n | x1 - h1 > pointToLeft = go (felled + 1) x1 ts\n | x1 + h1 < x2 = go (felled + 1) (x1 + h1) ts\n | otherwise = go felled x1 ts"}, {"source_code": "\nimport Control.Applicative\nimport Data.List\nimport Data.Ord\nimport Control.Monad\nimport Debug.Trace\n\nmain = do\n n <- read <$> getLine\n xhs <- forM [1..n] $ \\_ -> do\n [xi, hi] <- map read . words <$> getLine\n return (xi, hi)\n let st = (\\(x, h) -> x-h-1) . head $ xhs\n putStrLn . show $ sol st xhs\n\nsol :: Int -> -- last covering point\n [(Int, Int)] -> -- tree list to consider\n Int\nsol _ [(x, h)] = 1\nsol lcp ((x, h):xs@((nx, _):_))\n | lcp < x-h = 1 + sol x xs\n | x+h < nx = 1 + sol (x+h) xs\n | otherwise = sol x xs\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n show `fmap` solve `fmap` replicateM n (liftM2 (,) pin pin)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n pin = fmap (to64 . int) pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\nsolve = (\\(_, _, l, r, s) -> max l $ max r s) . foldl' (\\(!x', !h', !l', !r', !s') (!x, !h) -> let s = mcon (x > x' + h') r' (max l' s') in (x, h, 1 + mcon (x - h > x' + h') r' (mcon (x - h > x') (max l' s') (-1)), 1 + s, s)) (minBound, 0, 0 :: Int, 0 :: Int, 0 :: Int)\n\nmcon True x = max x\nmcon False _ = id"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\t--mapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1@(Tree _ _) t2\n\t| getTreeCoord t1 - getTreeHeight t1 > (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\nchopLeft t1 _ = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1@(Tree _ _) t2\n\t| getTreeCoord t1 + getTreeHeight t1 < (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\nchopRight t1 _ = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopped:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "main = interact $ show . solve . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve ts = go ([(-10^10,undefined)] ++ ts ++ [(10^10,undefined)]) 0 where\n go [_,_] a = a\n go ((prev,_):ts@((cur,h):ts'@((next,_):_))) a\n | prev < cur-h = go ((cur,undefined) : ts') $! a+1\n | next > cur+h = go ((cur+h,undefined) : ts') $! a+1\n | otherwise = go ts a\n \n"}, {"source_code": "import Data.Array\n\nsolve [(_, _)] = 1\nsolve ns = 1 + go lb' rb' 1\n where (lb', rb') = ds ! 1\n end = length ns - 1\n go lb rb n\n | n == end = 1\n | h < lb = 1 + go lb2 rb2 (n+1)\n | h < rb = 1 + go (lb2-h) rb2 (n+1)\n | otherwise = go lb2 rb2 (n+1)\n where h = hs ! n\n (lb2, rb2) = ds ! (n+1)\n hs = listArray (0, end) [h | (_, h) <- ns]\n ds = listArray (0, end-1) ((0,0): twobounds xs)\n xs = [i | (i, _) <- ns]\n\ntwobounds xs = zip ys (tail ys)\n where ys = zipWith (-) (tail xs) xs \n\ntoTuple [] = []\ntoTuple (x:xs:xss) = (x, xs) : toTuple xss \n\nmain = do\n getLine\n ns <- fmap (toTuple . map read . words) getContents :: IO [(Int, Int)]\n print $ solve ns \n\n"}, {"source_code": "import Data.Array\n\nsolve [_, _] = 1\nsolve ns = 1 + go lb' rb' 1\n where (lb', rb') = ds ! 1\n end = l `div` 2 - 1\n l = length ns \n go lb rb n\n | n == end = 1\n | h < lb = 1 + go lb2 rb2 (n+1)\n | h < rb = 1 + go (lb2-h) rb2 (n+1)\n | otherwise = go lb2 rb2 (n+1)\n where h = hs' ! n\n (lb2, rb2) = ds ! (n+1)\n ys = listArray (0, l-1) ns \n (hs, is) = ([ys ! j | j <- [1,3..(l-1)]], [ys ! k | k <- [0,2..(l-2)]])\n hs' = listArray (0, end) hs\n ds = listArray (0, end-1) ((0,0): twobounds is)\n\ntwobounds xs = zip ys (tail ys)\n where ys = zipWith (-) (tail xs) xs \n\ntoTuple [] = []\ntoTuple (x:xs:xss) = (x, xs) : toTuple xss \n\nmain = do\n getLine\n ns <- fmap (map read . words) getContents :: IO [Int]\n print $ solve ns \n\n"}], "negative_code": [{"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\tmapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1@(Tree _ _) t2\n\t| getTreeCoord t1 - getTreeHeight t1 > (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\nchopLeft t1 _ = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1@(Tree _ _) t2\n\t| getTreeCoord t1 + getTreeHeight t1 < (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\nchopRight t1 _ = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopped:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\t--mapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1 t2\n\t| getTreeCoord t1 - getTreeHeight t1 > (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1 t2\n\t| getTreeCoord t1 + getTreeHeight t1 < (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopped:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\t--mapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1 t2\n\t| getTreeCoord t1 - getTreeHeight t1 > (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1 t2\n\t| getTreeCoord t1 + getTreeHeight t1 < (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopRight t1 t2:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\tmapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1 t2\n\t| getTreeCoord t1 - getTreeHeight t1 > (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1 t2\n\t| getTreeCoord t1 + getTreeHeight t1 < (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopRight t1 t2:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\t--mapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1 t2\n\t| getTreeCoord t1 - getTreeHeight t1 > (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1 t2\n\t| getTreeCoord t1 + getTreeHeight t1 < (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopRight t1 t2:\n\tchopTrees (chopLeft t2 t1:ts) False"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\t--mapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1 t2\n\t| getTreeCoord t1 - getTreeHeight t1 >= (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1 t2\n\t| getTreeCoord t1 + getTreeHeight t1 <= (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopRight t1 t2:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "import Data.Array.IO\n\ndata Tree = Tree Int Int | TreeLeft Int Int | TreeRight Int Int\n\tderiving (Eq, Show)\n\ngetTreeCoord :: Tree -> Int\ngetTreeCoord (Tree x _) = x\ngetTreeCoord (TreeLeft x _) = x\ngetTreeCoord (TreeRight x _) = x\n\ngetTreeHeight :: Tree -> Int\ngetTreeHeight (Tree _ h) = h\ngetTreeHeight (TreeLeft _ h) = h\ngetTreeHeight (TreeRight _ h) = h\n\ngetTreeSegment :: Tree -> (Int,Int)\ngetTreeSegment (Tree x h) = (x,x)\ngetTreeSegment (TreeLeft x h) = (x - h, x)\ngetTreeSegment (TreeRight x h) = (x, x + h)\n\nisChopped :: Tree -> Bool\nisChopped (Tree _ _) = False\nisChopped _ = True\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetTrees :: Int -> IO [Tree]\ngetTrees n = fmap (map mapFunc) $ getLines n\n\twhere\n\t\tmapFunc :: String -> Tree\n\t\tmapFunc tree_str =\n\t\t\tlet\n\t\t\t\ttree = words tree_str\n\t\t\tin\n\t\t\t\tTree (read $ tree !! 0) (read $ tree !! 1)\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\ttrees <- getTrees n\n\n\tlet\n\t\tchopped_trees = chopTrees trees True\n\t\tchopped = sum [1 | x <- chopped_trees, isChopped x]\n\n\tmapM_ putStrLn $ map show $ chopped_trees\n\tputStrLn $ show chopped\n\nchopLeft :: Tree -> Tree -> Tree\nchopLeft t1 t2\n\t| getTreeCoord t1 - getTreeHeight t1 >= (snd $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeLeft (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopRight :: Tree -> Tree -> Tree\nchopRight t1 t2\n\t| getTreeCoord t1 + getTreeHeight t1 <= (fst $ getTreeSegment t2) || t1 == t2 =\n\t\tTreeRight (getTreeCoord t1) (getTreeHeight t1)\n\t| otherwise = t1\n\nchopTrees :: [Tree] -> Bool -> [Tree]\nchopTrees [] _ = []\nchopTrees (t:[]) _ =\n\t[chopRight t t]\nchopTrees (t1:t2:ts) True =\n\tchopLeft t1 t1:\n\tchopTrees (chopLeft t2 t1:ts) False\nchopTrees (t1:t2:ts) False = \n\tchopRight t1 t2:\n\tchopTrees (chopLeft t2 chopped:ts) False\n\twhere\n\t\tchopped = chopRight t1 t2"}, {"source_code": "\nimport Control.Applicative\nimport Data.List\nimport Data.Ord\nimport Control.Monad\nimport Debug.Trace\n\nmain = do\n n <- read <$> getLine\n xhs <- forM [1..n] $ \\_ -> do\n [xi, hi] <- map read . words <$> getLine\n return (xi, hi)\n let st = (\\(x, h) -> x-h-1) . head $ xhs\n putStrLn . show $ sol st xhs\n\nsol :: Int -> -- last covering point\n [(Int, Int)] -> -- tree list to consider\n Int\nsol _ [(x, h)] = 1\nsol lcp ((x, h):xs@((nx, _):_))\n | lcp < x-h = 1 + sol x xs\n | x+h < nx = 1 + sol (x+h) xs\n | otherwise = sol lcp xs\n\n"}], "src_uid": "a850dd88a67a6295823e70e2c5c857c9"} {"source_code": "import Data.List\nimport Control.Monad\nmaxN = 53::Int\n\nfct :: Int->Integer\nfct x = if x <= 1 then 1 else (toInteger x) * (fct $ x - 1)\n\ninter ls = zipWith (*) ls $ map fct $ [-1..(length ls)]\n\ngood :: Int->[Integer]\ngood 0 = [1]\ngood n = (foldl (+) 0 $ inter ls): ls where ls = good $ n - 1\n\nrec :: [(Int, Int)]->Int->Integer->[Int]\nrec [(a, _)] _ _ = [a]\nrec ls w k = (fst key) : rec (uno ++ ((elm, snd key) : dos)) (w + 1) (mod k mdl)\n where\n (one, (elm,_):two) = break ((w==) . snd) ls\n mdl = fct ((length ls) - 2)\n key = (one++two) !! (fromIntegral (quot k mdl))\n uno = fl one; dos = fl two\n fl = filter (key/=)\n\n-- This is just a wrapper. The real magic happens in rec.\nperm :: Int->Integer->[Int]\nperm 1 _ = [1]\nperm n k = (n: rec ((1, n) : zip x x) 2 k) where x = [2..(n-1)]\n\nsolve :: Int->Integer->[Integer]->[Int]\nsolve 0 _ _ = []\nsolve n k (t:tm) = if k >= t then [-1] else\n (perm sz $ quot kl vl)++(map (sz+) $ solve (n - sz) (mod kl vl) (drop (sz - 1) tm))\n where \n (sm,_) = break (k<) $ scanl (+) 0 $ inter tm\n sz = length sm\n kl = k - (last sm)\n vl = tm !! (sz - 1)\n\nfnc n k = solve n k (good n)\ncaso str = intercalate \" \" $ map show (solve sn (k - 1) (good sn))\n where\n [n, k] = map (\\x->read x::Integer) $ words str\n sn = fromIntegral n\n\nmain=do\n fl<-getLine\n let t = read fl::Int\n lsta <- (replicateM t getLine)\n let rsps = map caso lsta\n mapM putStrLn rsps\n \n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\nmaxN = 53\n\nfct x = if x <= 1 then 1 else (toInteger x) * (fct $ x - 1)\n\ninter ls = zipWith (*) ls $ map fct $ [-1..(length ls)]\n\ngood 0 = [1]\ngood n = (foldl (+) 0 $ inter ls): ls where ls = good $ n - 1\n\nrec [(a, _)] _ _ = [a]\nrec ls w k = (fst key) : rec (uno ++ ((elm, snd key) : dos)) (w + 1) (mod k mdl)\n where\n (one, (elm,_):two) = break ((w==) . snd) ls\n mdl = fct ((length ls) - 2)\n key = (one++two) !! (fromIntegral (quot k mdl))\n uno = fl one; dos = fl two\n fl = filter (key/=)\n\nperm 1 _ = [1]\nperm n k = (n: rec ((1, n) : zip x x) 2 k) where x = [2..(n-1)]\n\nsolve 0 _ _ = []\nsolve n k (t:tm) = if k >= t then [-1] else\n (perm sz $ quot kl vl)++(map (sz+) $ solve (n - sz) (mod kl vl) (drop (sz - 1) tm))\n where \n (sm,_) = break (k<) $ scanl (+) 0 $ inter tm\n sz = length sm\n kl = k - (last sm)\n vl = tm !! (sz - 1)\n\ncaso str = intercalate \" \" $ map show (solve sn (k - 1) (good sn))\n where\n [n, k] = map (\\x->read x::Integer) $ words str\n sn = fromIntegral n\n\nmain=do\n fl<-getLine\n let t = read fl::Int\n lsta <- (replicateM t getLine)\n let rsps = map caso lsta\n mapM putStrLn rsps\n \n"}], "negative_code": [], "src_uid": "d3580f1d7406740acfc4f4343d1844e8"} {"source_code": "main = getLine >>= print . solve . read\n\nsolve :: Integer -> Integer\nsolve n = (multi_cnk n 5) * (multi_cnk n 3)\n\nmulti_cnk n k = cnk (n + k - 1) k\n\nfact n = product [1..n]\n\ncnk n k | k > n = 0\n | otherwise = product [n,n-1..(n - k + 1)] `div` fact k\n", "positive_code": [{"source_code": "import Control.Monad\nmain = do\n a <- liftM read getLine\n putStrLn $ show $ (choose (a+4) (a-1)) * (choose (a+2) (a-1))\nchoose n k = (product [(n-k+1)..n]) `div` (product [1..k])"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,550) (1:( [product [1..i]| i<-[1..550]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\n \n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tprint $ ( c (n+4) (n-1) )* (c (n+2) (n-1))\n\t \n\n\t"}, {"source_code": "main :: IO ()\nmain = print . solve . read =<< getContents\n\nsolve :: Integer -> Integer\nsolve n = n * (n + 1) * (n + 2) * n * (n + 1) * (n + 2) * (n + 3) * (n + 4) `div` (1 * 2 * 3 * 1 * 2 * 3 * 4 * 5)\n"}, {"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n a <- (toInteger.fst.fromJust.C.readInt) <$> C.getLine\n let b = (a+2) * (a+1) `div` 2 * (a) `div` 3\n let c = (a+4) * (a+3) `div` 2 * (a+2) `div` 3 * (a+1) `div`4 *(a)`div`5\n print $ b*c"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n a <- (toInteger.fst.fromJust.C.readInt) <$> C.getLine\n let b = (a+2) * (a+1) `div` 2 * (a) `div` 3\n let c = (a+4) * (a+3) `div` 2 * (a+2) `div` 3 * (a+1) `div`4 *(a)`div`5\n print $ b+c"}], "src_uid": "d41aebacfd5d16046db7c5d339478115"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n _ <- getInts\n as <- getInts\n [d] <- getInts\n let (u, _, v) = foldl' acc (0, 0, 0) $ map (subtract d) as\n acc (x, m, y) a\n | m + a >= 0 && x > y = (x + 1, min a (m + a), y')\n | otherwise = (y + 1, a, y')\n where y' = max x y\n return $ intDec (max u v) <> charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Data.Bool\r\nimport System.IO hiding (getLine,print)\r\nimport Prelude hiding (getLine)\r\nimport Data.Char\r\n\r\nrecurse _ _ _ ans [] = ans\r\nrecurse tot isFirst peaktot ans (x:xs)\r\n | isFirst = recurse (tot+x) False 0 (ans+1) xs\r\n | tot+x < peaktot = recurse 0 True minBound ans xs\r\n | otherwise = recurse (tot+x) False (max tot peaktot) (ans+1) xs\r\n \r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n xs'{-'-} <- readv\r\n ~[y] <- readv\r\n let\r\n xs = subtract y <$> xs'{-'-}\r\n ans = recurse 0 True minBound 0 xs\r\n printv [ans]\r\n \r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x| x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\ngetLine :: IO [Char]\r\ngetLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\ndata S = S !Int !Int !Int !Int\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n a <- getInts n\r\n ~[x] <- getInts 1\r\n let\r\n step :: S -> Int -> S\r\n step (S p2 p1 wait count) v = let\r\n oof2 = v + p1 < x + x && wait >= 2\r\n oof3 = v + p1 + p2 < x + x + x && wait >= 3\r\n in if oof2 || oof3\r\n then S p1 v 1 (count + 1)\r\n else S p1 v (wait + 1) count\r\n S _ _ _ toSkip = foldl' step (S 0 0 1 0) a\r\n pure $ putInts [n - toSkip]\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "79ecf771f4a54c2c9f988e069f7bfceb"} {"source_code": "import Control.Monad (replicateM_)\n\nsolve :: Int -> Int -> Int\nsolve n k\n | n < k = k - n\n | even (n-k) = 0\n | otherwise = 1\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, k] <- map read . words <$> getLine\n print $ solve n k\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, k] <- map read . words <$> getLine\n if n >= k then\n if even (n - k) then\n putStrLn \"0\"\n else\n putStrLn \"1\"\n else\n putStrLn $ show (k - n)\n"}, {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let [n, k] = map (\\x -> read x :: Integer) $ words s\n print $ if n < k then \n k - n\n else\n (n - k) `mod` 2\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Integer)"}, {"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> Int\nsolve (x:xs)\n | n == k = 0\n | n < k = k - n\n | otherwise = mod (n-k) 2\n where \n n = x\n k = head xs\n\ndeal :: IO()\ndeal = do \n x <- map read . words <$> getLine\n putStrLn $ show $ solve x\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\ntestCase :: IO a -> IO ()\ntestCase f = do\n t <- read <$> getLine\n replicateM_ t f\n\nmain = testCase $ do\n [a, b] <- map read . words <$> getLine\n print $ if a >= b then (a - b) `mod` 2 else b - a"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, k] <- fmap read . words <$> getLine\n print $ solve n k\n\nsolve :: Int -> Int -> Int\nsolve a k\n | k > abs a = abs $ k - abs a\n | a `mod` 2 /= k `mod` 2 = 1\n | otherwise = 0"}], "negative_code": [{"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> Int\nsolve (x:xs)\n | a == b = 0\n | b == 0 = mod a 2\n | otherwise = abs (a-b)\n where \n a = x\n b = head xs\n\ndeal :: IO()\ndeal = do \n x <- map read . words <$> getLine\n putStrLn $ show $ solve x\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}], "src_uid": "f98d1d426f68241bad437eb221f617f4"} {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve :: String -> String\nsolve =\n let mapper x\n | x `mod` 2 == 0 = x-1\n | otherwise = x\n in intercalate \" \" . map show . map mapper . tail . map fastRead . words\n", "positive_code": [{"source_code": "rule n\n | n `mod` 2 == 1 = n\n | otherwise = n - 1\n \nmain = do\n trash <- getLine\n input <- getLine\n doOutput $ map (rule . read) $ words input\n \ndoOutput (x : []) = putStr $ show x\ndoOutput (x : xs) = (putStr $ show x ++ \" \") >> doOutput xs"}, {"source_code": "module Main (main) where\n\n--ghc 7.10\n\nmain :: IO ()\nmain = getLine >> getInts >>= (out . solve)\n\ngetInts :: IO [Int]\ngetInts = fmap (map read . words) getLine\n\nout :: [Int] -> IO ()\nout = putStrLn . seri\n\nsolve :: [Int] -> [Int]\nsolve = map chng\n\nchng :: Int -> Int\nchng n = if even n then pred n else n\n\nseri :: [Int] -> String\nseri = unwords . map show"}, {"source_code": "f::Integer->String\nf x\n |x `mod` 2==0 =show (x-1)\n |otherwise =show x\n\nmain = do\n e<-getLine\n e2<-getLine\n let xs=map read (words e2)::[Integer]\n putStrLn $ unwords $ map f xs"}, {"source_code": "import Control.Monad\n\nmain = readInput >>= putStrLn . calc\n\nreadInput :: IO [String]\nreadInput = liftM2 getSnd getLine getLine\n where getSnd _ a = words a\n \ncalc :: [String] -> String\ncalc ns = foldr go \"\" ns\n where go numStr ans = \" \" ++ (show final) ++ ans\n where num = read numStr\n final = if num `rem` 2 == 0 then num - 1\n \t\t else num\n"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\nimport Data.Bits\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nsolve :: [Int] -> [Int]\nsolve = map (\\x -> x - ((x + 1) .&. 1)) \n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n arr <- (map readInt . words) <$> getLine\n let answer = solve arr \n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let as_numbers = map fastRead $ words input\n n:xs = as_numbers\n answer = map mapper xs\n mapper x\n | x `mod` 2 == 0 = x-1\n | otherwise = x\n in intercalate \" \" . map show $ answer\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nprocess a | even a = a-1\n | otherwise = a\n\nmain::IO ()\nmain=do\n getLine\n x <- (map (fromIntegral.fst.fromJust.C.readInteger)) <$> C.words <$> C.getLine::IO [Int]\n putStrLn $ intercalate \" \" $ map show $ map process x\n"}, {"source_code": "import Data.Bits\nmain = interact $ unwords . map (show . succ . ((.&.) (complement 1 :: Int)) . pred . read) . tail . words\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\tb<- map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ intercalate \" \" $ map show $ map (\\z-> if even z then z-1 else z) b\t\n\n"}, {"source_code": "--ghc 7.10\n\nadjReplacement :: (Integral a) => [a] -> [a]\nadjReplacement = map (\\x -> if even x then x-1 else x)\n\nmain = do\n line1 <- getLine\n line2 <- getLine\n let a = map read . words $ line2 :: [Int]\n putStrLn . unwords . map show . adjReplacement $ a"}, {"source_code": "import Data.ByteString as BS (ByteString)\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad\n\nreadInts :: ByteString -> [Int]\nreadInts bs = map (\\bsWord -> let Just (int, _) = C.readInt bsWord in int) $ C.words bs\n\nmain :: IO ()\nmain = do\n _ <- getLine\n bs <- C.getContents\n let array = readInts bs\n forM_ array (\\el ->\n if el `mod` 2 == 0\n then putStr $ show (el - 1) ++ \" \"\n else putStr $ show el ++ \" \")\n \n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString as B8\n\nmain = do\n _ <- getLine\n xstr <- getLine\n let xs = map read $ words xstr :: [Int]\n putStrLn . unwords $ map (\\x -> show $ if odd x then x else x - 1) xs\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\nimport Data.Bits\nmain = interact $ unwords . map (show . (xor @Int 1) . read) . tail . words\n"}, {"source_code": "import Data.Bits\nmain = interact $ unwords . map (show . ((.&.) (complement 1 :: Int)) . read) . tail . words\n"}], "src_uid": "d00696cb27c679dda6e2e29314a8432b"} {"source_code": "import Data.List\n\nreadInt = fmap (\\x -> read x :: Int) getLine\n\nconvertLine :: Read a => String -> [a]\nconvertLine = map read . words\n-- readInt \n\nmain :: IO ()\nmain = do\n let multipleTests = True\n\n if multipleTests then do\n line <- getLine\n let [t] = convertLine line\n mapM_ solveAndPrint [1..t]\n else do\n let t = 1\n mapM_ solveAndPrint [1..t]\n\n-- Aici citeste datele si paseaza-le catre solve\nsolveAndPrint :: Int -> IO ()\nsolveAndPrint _ = do\n line <- getLine\n -- putStrLn line\n let [n, x] = convertLine line :: [Int]\n putStrLn $ show $ findFloor n x \n\nfindFloor :: Int -> Int -> Int\nfindFloor n x\n | n <= 2 = 1\n | otherwise = (n - 3) `div` x + 2", "positive_code": [{"source_code": "import Control.Arrow ( (>>>) )\n\nmain :: IO ()\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read >>> solve >>> show)\n >>> unlines\n\nsolve :: [Int] -> Int\nsolve [n, x] \n | n <= 2 = 1\n | otherwise = 2 + div (n - 3) x\n"}, {"source_code": "\ntest :: String -> String\ntest s =\n let (n:x:[]) = map read $ words s :: [Int] in\n if n <= 2 then\n \"1\\n\"\n else\n (show $ 2 + (n - 3) `div` x) ++ \"\\n\"\n\nsolve :: String -> String\nsolve s =\n let ans = map test $ lines s in\n foldr1 (++) ans\n\nmain = do\n n <- getLine\n interact solve"}, {"source_code": "import Control.Monad\nimport Data.Char\n\ngetList :: (Read t) => IO [t]\ngetList = getLine >>= return . (map read) . words\n\ngetOne :: (Read t) => IO t\ngetOne = getLine >>= return . read\n\nmain :: IO ()\nmain = do\n t <- getOne\n -- let t = 1\n replicateM_ t solve\n\n\nsolve :: IO ()\nsolve = do \n [n, x] <- getList\n print $ countAns n x\n\ncountAns :: Integral t => t -> t -> t\ncountAns n x\n | n <= 2 = 1\n | otherwise = ((n - 3) `div` x) + 2\n"}, {"source_code": "calc :: Int -> Int -> Int\ncalc n x\n | n `mod` x == 0 = n `div` x\n | otherwise = n `div` x + 1\n\nsolve :: String -> String\nsolve str \n | n <= 2 = show 1\n | otherwise = show $ calc (n-2) x + 1\n where xs = map read $ words str\n n = head xs\n x = last xs\n\nmain = interact $ unlines . map solve . tail . lines"}, {"source_code": "getResult :: [Int] -> Int\ngetResult a | head a == 1 = 1\n | otherwise = (div ((head a) - 3) (last a)) + 2\n\nconvertList :: [String] -> [Int]\nconvertList [] = []\nconvertList a = [read (head a) :: Int] ++ convertList (tail a)\n\n\nsolveb :: String -> Int\nsolveb nString = getResult (convertList (words nString));\n\n\nsolve :: Int -> IO () \nsolve 0 = do\n putStr \"\"\nsolve t = do \n nString <- getLine\n putStrLn ((show (solveb nString)) :: String) \n solve (t - 1)\n \n \nmain = do\n teste <- getLine\n let t = read teste :: Int\n solve t \n putStr \"\" \n\n"}, {"source_code": "solve :: Int -> Int -> Int\nsolve n x = if (n < 3) then 1 else div (n - 3) x + 2\n\nqueries :: Int -> IO ()\nqueries 0 = return ()\nqueries t = do\n line <- getLine\n let list = words line\n let n = read (head list) :: Int\n let x = read (head (tail list)) :: Int\n let ans = solve n x\n putStrLn ((show ans) :: String)\n queries (t - 1)\n\n\nmain = do\n t1 <- getLine\n let t = read t1 :: Int\n queries t"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\n\n-- n -> x -> floor_number\nfindFloorNumber :: Int -> Int -> Int\nfindFloorNumber n x | n <= 2 = 1\n | otherwise = ((n - 3) `div` x) + 2\n\nreadCaseInput :: IO (Int, Int)\nreadCaseInput = do\n numbers <- words <$> getLine\n let n = read (head numbers) :: Int\n let x = read (last numbers) :: Int\n pure (n, x)\n\nsolveCase :: IO ()\nsolveCase = do\n (n, x) <- readCaseInput\n let solution = findFloorNumber n x\n print solution\n\nreadT :: IO Int\nreadT = do\n line <- getLine\n pure (read line :: Int)\n\nmain :: IO ()\nmain = do\n t <- readT\n replicateM_ t solveCase\n\n-- vim: set ts=4 expandtab sw=4:\n"}, {"source_code": "import Control.Monad\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, x] <- map read . words <$> getLine\n print $ if n <= 2\n then 1 :: Int\n else 1 + ceilDiv (n - 2) x\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmain :: IO ()\nmain = do\n getLine -- discard\n input <- map ((\\[x, y] -> (x, y)) . map (read @Int) . words) . lines <$> getContents\n mapM_ (print . uncurry f) input\n\nf :: Int -> Int -> Int\nf target step = case step of\n 1 -> max (target - 1) 1\n _ -> ((target - 3) `div` step) + 2 \n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Maybe\n\nreadNumber :: IO Int\nreadNumber = fmap read getLine\n\nreadPair :: IO (Int, Int)\nreadPair = fmap (unpackList . map read . words) getLine\n where unpackList list = (head list, last list)\n\ndoStuff :: Int -> IO Int\ndoStuff _ = do\n (n, x) <- readPair\n pure $ f n x\n\ncheckCondition :: Int -> Int -> Int -> Bool\ncheckCondition n x floorNumber =\n (n >= (floorNumber - 2) * x + 3) && (n <= (floorNumber - 1) * x + 2)\n\nf :: Int -> Int -> Int\nf n x\n | n < 3 = 1\n | otherwise = fromJust $ find (checkCondition n x) [2..]\n\nmain = do\n n <- readNumber\n results <- forM [1..n] doStuff\n forM_ results (putStrLn . show)"}], "negative_code": [{"source_code": "solve :: Int -> Int -> Int\nsolve n x = (quot (n - 2) x) + 1\n\nqueries :: Int -> IO ()\nqueries 0 = return ()\nqueries t = do\n line <- getLine\n let list = words line\n let n = read (head list) :: Int\n let x = read (head (tail list)) :: Int\n let ans = solve n x\n putStrLn ((show ans) :: String)\n queries (t - 1)\n\n\nmain = do\n t1 <- getLine\n let t = read t1 :: Int\n queries t"}, {"source_code": "solve :: Int -> Int -> Int\nsolve n x = 0\n\nqueries :: Int -> IO ()\nqueries 0 = return ()\nqueries t = do\n line <- getLine\n let list = words line\n let n = read (head list) :: Int\n let x = read (head (tail list)) :: Int\n let ans = solve n x\n putStrLn ((show ans) :: String)\n queries (t - 1)\n\n\nmain = do\n t1 <- getLine\n let t = read t1 :: Int\n queries t"}, {"source_code": "getResult :: [Int] -> Int\ngetResult a = (div ((head a) - 3) (last a)) + 2\n\nconvertList :: [String] -> [Int]\nconvertList [] = []\nconvertList a = [read (head a) :: Int] ++ convertList (tail a)\n\n\nsolveb :: String -> Int\nsolveb nString = getResult (convertList (words nString));\n\n\nsolve :: Int -> IO () \nsolve 0 = do\n putStr \"\"\nsolve t = do \n nString <- getLine\n putStrLn ((show (solveb nString)) :: String) \n solve (t - 1)\n \n \nmain = do\n teste <- getLine\n let t = read teste :: Int\n solve t \n putStr \"\" \n\n"}, {"source_code": "getResult :: [Int] -> Int\ngetResult a | head a == 1 = 0\n | otherwise = (div ((head a) - 3) (last a)) + 2\n\nconvertList :: [String] -> [Int]\nconvertList [] = []\nconvertList a = [read (head a) :: Int] ++ convertList (tail a)\n\n\nsolveb :: String -> Int\nsolveb nString = getResult (convertList (words nString));\n\n\nsolve :: Int -> IO () \nsolve 0 = do\n putStr \"\"\nsolve t = do \n nString <- getLine\n putStrLn ((show (solveb nString)) :: String) \n solve (t - 1)\n \n \nmain = do\n teste <- getLine\n let t = read teste :: Int\n solve t \n putStr \"\" \n\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmain :: IO ()\nmain = do\n getLine -- discard\n input <- map ((\\[x, y] -> (x, y)) . map (read @Int) . words) . lines <$> getContents\n mapM_ (print . uncurry f) input\n\nf :: Int -> Int -> Int\nf target step = ((target - 3) `div` step) + 2\n"}], "src_uid": "8b50a0eb2e1c425455b132683d3e6047"} {"source_code": "import Control.Monad\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n\nfolder :: (Integer, Integer) -> Integer -> (Integer, Integer)\nfolder (o, z) 1 = (o+1, z)\nfolder (o, z) 0 = (o, z+1)\n\nmain :: IO ()\nmain = do\n t <- readInt <$> getLine\n replicateM_ t $ do\n n <- readInt <$> getLine\n ps <- map readInteger . words <$> getLine\n m <- readInt <$> getLine\n qs <- map readInteger . words <$> getLine\n print $ (\\(os,zs) -> product os + product zs) . unzip . map ( foldl folder (0,0) . map (`mod`2) ) $ [ps, qs]\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ print\n\nsolve = do\n\tn <- readInteger\n\tps <- readInts\n\tm <- readInteger\n\tqs <- readInts\n\tlet\n\t\todd1 :: Integer = fromIntegral $ length $ filter odd ps\n\t\teven1 = n - odd1\n\t\todd2 :: Integer = fromIntegral $ length $ filter odd qs\n\t\teven2 = m - odd2\n\treturn $ odd1 * odd2 + even1 * even2"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- (map read.words) <$> getLine\n _ <- getLine\n bs <- (map read.words) <$> getLine\n print $ solve as bs\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve as bs = a1*b1+a2*b2\n where\n count (e,o) x = if even x\n then (e+1,o)\n else (e,o+1)\n (a1,a2) = foldl count (0,0) as\n (b1,b2) = foldl count (0,0) bs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ViewPatterns #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bool\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport qualified Data.List.NonEmpty as NL\nimport Data.Monoid\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Foreign\nimport qualified System.IO as IO\n#ifdef DEBUG\nimport Debug.Trace\n#endif\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n ps <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine\n m <- readLn\n qs <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine\n print $ solve n ps m qs\n IO.hFlush IO.stdout\n\nsolve :: Int -> [Int] -> Int -> [Int] -> Int64\nsolve n xs m ys = fromIntegral xsEven * fromIntegral ysEven + fromIntegral xsOdd * fromIntegral ysOdd\n where\n p x = x .&. 1 == 0\n !xsEven = length $ filter p xs\n !xsOdd = n - xsEven\n !ysEven = length $ filter p ys\n !ysOdd = m - ysEven\n"}], "negative_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- (map read.words) <$> getLine\n _ <- getLine\n bs <- (map read.words) <$> getLine\n print $ solve as bs\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = a1*b1+a2*b2\n where\n count (e,o) x = if even x\n then (e+1,o)\n else (e,o+1)\n (a1,a2) = foldl count (0,0) as\n (b1,b2) = foldl count (0,0) bs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ViewPatterns #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bool\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport qualified Data.List.NonEmpty as NL\nimport Data.Monoid\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Foreign\nimport qualified System.IO as IO\n#ifdef DEBUG\nimport Debug.Trace\n#endif\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n ps <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine\n m <- readLn\n qs <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine\n print $ solve n ps m qs\n IO.hFlush IO.stdout\n\nsolve :: Int -> [Int] -> Int -> [Int] -> Int\nsolve n xs m ys = xsEven * ysEven + xsOdd * ysOdd\n where\n p x = x .&. 1 == 0\n !xsEven = length $ filter p xs\n !xsOdd = n - xsEven\n !ysEven = length $ filter p ys\n !ysOdd = m - ysEven\n"}, {"source_code": "import Control.Monad\n\nreadInt = read :: String -> Int\n\nfolder :: (Int, Int) -> Int -> (Int, Int)\nfolder (o, z) 1 = (o+1, z)\nfolder (o, z) 0 = (o, z+1)\n\nmain :: IO ()\nmain = do\n t <- readInt <$> getLine\n replicateM_ t $ do\n n <- readInt <$> getLine\n ps <- map readInt . words <$> getLine\n m <- readInt <$> getLine\n qs <- map readInt . words <$> getLine\n print $ (\\(os,zs) -> product os + product zs) . unzip . map ( foldl folder (0,0) . map (`mod`2) ) $ [ps, qs]\n"}], "src_uid": "adf4239de3b0034cc690dad6160cf1d0"} {"source_code": "import Data.List.Split\n\nmain = do\n xs <- fmap (splitOn \" \") getLine\n let n = read $ head xs\n k = read $ last xs\n in putStrLn $ take n $ concat $ repeat $ take k ['a'..'z']", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n \ns=\"abcdefghijklmnopqrstuvwxyz\"\n\n\nmain = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ take a $ cycle $ take b s\t\t\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve :: [Int] -> String\nsolve [n, k] = take n $ concat $ repeat $ take k ['a'..'z']\n\nmain :: IO ()\nmain = interact $ solve . map read . words"}, {"source_code": "module Main where\n\nimport Data.Char\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nletters = filter isLower [minBound..maxBound]\n\nmain = do\n [n, k] <- readInts\n putStrLn $ (($) concat (replicate (n `div` k) $ take k letters)) ++ (take (n `mod` k) letters)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Char\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nletters = filter isLower [minBound..maxBound]\n\nmain = do\n [n, k] <- readInts\n print $ (($) concat (replicate (n `div` k) $ take k letters)) ++ (take (n `mod` k) letters)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n \ns=\"abcdefghijklmnopqrstuvwxyz\"\n\n\nmain = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ take a $ cycle $ take b s\t\t\n"}], "src_uid": "39f5e934bf293053246bd3faa8061c3b"} {"source_code": "import Data.Array\n\ndelta (x, y) = abs $ x - y\n\ntimeUnits a n = sum $ map delta $ changes\n where \n an = array (1, n) $ zip a [1..]\n pos = map (\\x -> an!(x)) [1..n]\n changes = zip pos (drop 1 pos)\n \n\nmain = do\n n <- readLn\n s <- getLine\n let a = map read $ words s\n putStrLn $ show $ timeUnits a n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n f <- map snd . sort . (flip zip) [0 .. ] . tail . map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents\n print . sum . map abs . zipWith (-) f $ tail f\n"}, {"source_code": "import Data.ByteString.Char8 (words, readInt, getLine)\nimport Data.List (sort)\nimport Data.Maybe\nimport Prelude hiding (words, getLine)\n\nmain = do\n getLine\n as <- (map (fst . fromJust . readInt) . words) `fmap` getLine :: IO [Int]\n\n let\n r = sum . zipWith (\\a b -> abs $ a - b) ps $ tail ps\n where\n ps = map snd . sort $ zip as [1..]\n\n print r\n"}, {"source_code": "\nimport Data.Array\n\nmain = interact $ show . sol . map read . words\n\nsol :: [Integer] -> Integer\nsol (n:fs) = sum $ map (\\idx -> abs $ ar!(idx+1) - ar!idx) [1..n-1]\n where\n ar = array (1, n) $ zip fs [1..]\n\n"}], "negative_code": [{"source_code": "\nimport Data.List\n\nmain = interact $ show . sol . map read . words\n\nsol :: [Int] -> Int\nsol (n:fs) = sum . map abs . zipWith (-) tr $ tail tr\n where\n tr = map snd . sort $ zip fs [1..]\n\n"}, {"source_code": "\nimport Data.List\n\nmain = interact $ show . sol . words\n\nsol (n:fs) = sum . map abs . zipWith (-) tr $ tail tr\n where\n tr = map snd . sort $ zip fs [1..]\n\n"}], "src_uid": "54e2b6bea0dc6ee68366405945af50c6"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Ord\nimport Data.Tuple\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map (obj.readInt).B.words <$> B.getLine\n ys <- map readInt.B.words <$> B.getLine\n let (l,p) = solve n xs [(from,to) | [(from,to)]<-groupBy ((==)`on`fst).sort $ zip ys [1..n], from/=0]\n print l\n putStrLn.unwords.map show $ p \n\ndata Object = Mountain | Hotel deriving Eq\n\nobj :: Int -> Object\nobj 0 = Mountain\nobj 1 = Hotel\n\nsolve :: Int -> [Object] -> [(Int,Int)] -> (Int,[Int])\nsolve n objects edges = maximum [ (length p, reverse p) | i<-[1..n]\n , unsafeAt isHotel i\n , let p = path i\n , all (not.unsafeAt isHotel) $ tail p\n ]\n where\n isHotel :: UArray Int Bool\n isHotel = listArray (0,n) $ False : map (Hotel==) objects\n prev :: UArray Int Int\n prev = runSTUArray $ do\n arr <- newArray (0,n) 0 :: ST s (STUArray s Int Int)\n forM_ edges $ \\ (from,to) -> do\n unsafeWrite arr to from\n return arr\n path :: Int -> [Int]\n path v = takeWhile (/=0) $ iterate (unsafeAt prev) v\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readInt <$> B.getLine\n types <- readsInt\n as <- readsInt\n let p = solve n types as\n print $ length p\n putStrLn $ unwords $ map show $ p\n\nsolve n types as = maximize length [ go i [] | i <- [1..n], hotel ! i]\n where\n graph :: UArray Int Int\n graph = listArray (1,n) as\n hotel :: UArray Int Bool\n hotel = listArray (1,n) $ map (==1) types\n degree :: UArray Int Int\n degree = accumArray (+) 0 (1,n) [ (i,1) | i <- as, i /= 0 ]\n go i !acc | next == 0 || hotel ! next || degree ! next > 1 = i:acc\n | otherwise = go next (i:acc)\n where\n next = graph ! i\n \n\n"}], "negative_code": [], "src_uid": "a704760d5ccd09d08558ea98d6007835"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = assert (low>=0 && p high) $ go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- listArray(0,n-1).map ((2==).readInt).B.words <$> B.getLine\n let res = solve n xs\n print $ length res\n putStr.unlines.map (unwords.map show) $ res\n\nsolve :: Int -> UArray Int Bool -> [[Int]]\nsolve n arr = sort [[s,t] | t<-[1..n], Just s<-[simulate t]]\n where\n simulate point = go 0 0 0\n where\n go !x !y !i = case (nextx, nexty) of\n (Just xi, Just yi)\n | xi < yi -> go (x+1) y (xi+1)\n | otherwise -> go x (y+1) (yi+1)\n (Just xi, Nothing)\n | unsafeAt arr (n-1) && r == 0 && y < res -> Just res\n where\n (q,r) = quotRem (unsafeAt arrX (n-1) - unsafeAt arrX xi) point\n res = x + 1 + q\n (Nothing, Just yi)\n | not(unsafeAt arr (n-1)) && r == 0 && x < res -> Just $ y + 1 + q\n where\n (q,r) = quotRem (unsafeAt arrY (n-1) - unsafeAt arrY yi) point\n res = y + 1 + q\n _ -> Nothing\n where\n !ai = fromEnum $ unsafeAt arr i\n !sumX = unsafeAt arrX i - ai\n !sumY = unsafeAt arrY i - (1 - ai)\n nextx\n | unsafeAt arrX (n-1) - sumX >= point = Just $ lowerBound (\\i->unsafeAt arrX i - sumX >= point) i (n-1)\n | otherwise = Nothing\n nexty\n | unsafeAt arrY (n-1) - sumY >= point = Just $ lowerBound (\\i->unsafeAt arrY i - sumY >= point) i (n-1)\n | otherwise = Nothing\n pair :: (UArray Int Int, UArray Int Int)\n pair@(arrX, arrY) = runST $ do\n arrX <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n arrY <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n if unsafeAt arr 0 then unsafeWrite arrX 0 1\n else unsafeWrite arrY 0 1\n for 1 (n-1) $ \\i -> do\n if unsafeAt arr i then do\n unsafeRead arrX (i-1) >>= unsafeWrite arrX i . (1+)\n unsafeRead arrY (i-1) >>= unsafeWrite arrY i\n else do\n unsafeRead arrX (i-1) >>= unsafeWrite arrX i\n unsafeRead arrY (i-1) >>= unsafeWrite arrY i . (1+)\n (,) <$> unsafeFreeze arrX <*> unsafeFreeze arrY\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n n <- readLn\n as <- readInts\n let l = solve n as\n print $ length l\n putStr $ unlines $ [ show s ++ \" \" ++ show t | (s,t) <- l]\n\nsolve :: Int -> [Int] -> [(Int,Int)]\nsolve n as = sort [ (s,t) | t <- [1..n], s <- calc n tbl t ] where\n tbl :: UArray Int Int\n tbl = listArray (0,n) $ scanl (+) 0 $ map (2-) as\n\ncalc :: Int -> UArray Int Int -> Int -> [Int]\ncalc n tbl s = go 0 0 0 where\n go !wx !wy !p = \n let l = min n (p+s-1) in\n let r = min n (p+2*s-1) in\n let check q = \n let a = tbl ! q - tbl ! p in\n let b = (q - p) - a in\n max a b < s in\n let d = binSearch check l r in\n if tbl ! d - tbl ! p == s then\n -- winner is Petya\n if d == n then\n guard (wx >= wy) >> pure (wx+1)\n else\n go (wx+1) wy d\n else if (d-p) - (tbl ! d - tbl ! p) == s then\n -- winner is Gena\n if d == n then\n guard (wx <= wy) >> pure (wy+1)\n else\n go wx (wy+1) d\n else\n empty\n\n{-# INLINE binSearch #-}\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p = go where\n go l r \n | l >= r - 1 = r\n | p m = go m r\n | otherwise = go l m where\n m = (l + r) `div` 2\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "eefea51c77b411640a3b92b9f2dd2cf1"} {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport System.IO\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Lazy as DM\r\nimport qualified Data.IntSet as DS\r\nimport qualified Data.List as DL\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n ~[n,q] <- getIntegrals 2\r\n s <- getByteString\r\n queries <- replicateM q getPosChar\r\n let arr = DM.fromAscList $ zip [1..] (B8.unpack s)\r\n count = length $ filter (substr arr) [1..n]\r\n initial = (arr,count)\r\n anss = tail $ snd $ unzip $ DL.scanl' f initial queries\r\n builder = mconcat $ [Bu.intDec i <> Bu.string7 \"\\n\" | i <-anss]\r\n return builder\r\n\r\ntype B = (DM.IntMap Char, Int)\r\nf :: B -> (Int,Char) -> B\r\nf (arr, count) (pos,ch) \r\n | DM.lookup pos arr == Just ch = (arr,count) \r\n | otherwise = let \r\n match p c a = fromEnum (substr a (p + (fromEnum 'a') - (maybe 0 fromEnum $ DM.lookup p a)))\r\n newArr = DM.insert pos ch arr\r\n decr = match pos ch arr\r\n incr = match pos ch newArr\r\n in\r\n (newArr, count-decr+incr)\r\n\r\nsubstr :: DM.IntMap Char -> DS.Key -> Bool\r\nsubstr m i = DM.lookup i m == Just 'a' && DM.lookup (i+1) m == Just 'b' && DM.lookup (i+2) m == Just 'c'\r\n\r\ngetPosChar :: St (Int,Char)\r\ngetPosChar = do\r\n pos <- getIntegral\r\n s <- getByteString\r\n return (pos,B8.head s)\r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = implicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc solve\r\n fmap mconcat answers\r\n Bu.hPutBuilder stdout outputs\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.ST.Safe\r\nimport Control.Monad.ST.Lazy\r\n\r\n\r\nsolve :: Int -> String -> [(Int, Char)] -> [Int]\r\nsolve n s0 qs = runST $ do\r\n s <- strictToLazyST $ newListArray (1, n) s0 :: ST s (STUArray s Int Char)\r\n let\r\n isABC ix = boolToInt . (== \"abc\") <$> forM [ix .. ix + 2] (readArray s)\r\n boolToInt p = if p then 1 else 0\r\n initCt <- (\\fun -> strictToLazyST $ foldM fun 0 [1 .. n - 2])\r\n $ \\ !acc !ix -> (+ acc) <$> isABC ix\r\n incrs <- forM qs $ \\(ix, c) -> strictToLazyST $ do\r\n let ixs = [max 1 (ix - 2) .. min ix (n - 2)]\r\n localCt = sum <$> forM ixs isABC\r\n out <- localCt\r\n writeArray s ix c\r\n subtract out <$> localCt\r\n pure $ tail $ scanl' (+) initCt incrs\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[n, q] <- getInts 2\r\n ~[s0] <- getNext 1\r\n qs <- replicateM q $ do\r\n ~[ix] <- getInts 1\r\n ~[cs] <- getNext 1\r\n pure (ix, P.head cs)\r\n pure $ foldMap (putInts . pure) $ solve n (P.unpack s0) qs\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport System.IO\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Lazy as DM\r\nimport qualified Data.IntSet as DS\r\nimport qualified Data.List as DL\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n ~[n,q] <- getIntegrals 2\r\n s <- getByteString\r\n queries <- replicateM q getPosChar\r\n let arr = DM.fromAscList $ zip [1..] (B8.unpack s)\r\n count = length $ filter (substr arr) [1..n]\r\n initial = (arr,count)\r\n anss = snd $ unzip $ DL.scanl' f initial queries\r\n builder = mconcat $ [Bu.intDec i <> Bu.string7 \"\\n\" | i <-anss]\r\n return builder\r\n\r\ntype B = (DM.IntMap Char, Int)\r\nf :: B -> (Int,Char) -> B\r\nf (arr, count) (pos,ch) \r\n | DM.lookup pos arr == Just ch = (arr,count) \r\n | otherwise = let \r\n match p c a = fromEnum (substr a (p + (fromEnum 'a') - (maybe 0 fromEnum $ DM.lookup p a)))\r\n newArr = DM.insert pos ch arr\r\n decr = match pos ch arr\r\n incr = match pos ch newArr\r\n in\r\n (newArr, count-decr+incr)\r\n\r\nsubstr :: DM.IntMap Char -> DS.Key -> Bool\r\nsubstr m i = DM.lookup i m == Just 'a' && DM.lookup (i+1) m == Just 'b' && DM.lookup (i+2) m == Just 'c'\r\n\r\ngetPosChar :: St (Int,Char)\r\ngetPosChar = do\r\n pos <- getIntegral\r\n s <- getByteString\r\n return (pos,B8.head s)\r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = implicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc solve\r\n fmap mconcat answers\r\n Bu.hPutBuilder stdout outputs\r\n"}], "src_uid": "db473ad780a93983667d12b1357c6e2f"} {"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap parseInput $ getLine\n let ret = solve n k\n if (length ret) > 0\n then do\n putStrLn \"YES\"\n mapM_ putStrLn ret\n else putStrLn \"NO\"\n\nparseInput = map readInt . words\n where readInt x = (read x) :: Int\n\nsolve n k \n | even k = [fill 0, fill k', fill k', fill 0]\n | k <= (n-2) = [fill 0, fill' k pad, fill 0, fill 0]\n | otherwise = [fill 0, fill (n-2), fill'' (k - n + 2), fill 0]\n where\n fill x = \".\" ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')\n fill' x y = (take y $ repeat '.') ++ (take x $ repeat '#') ++ (take (n-x-y) $ repeat '.')\n fill'' x = \".\" ++ (take (x-1) $ repeat '#') ++ (take (n-2-x) $ repeat '.') ++ \"#.\"\n k' = k `div` 2\n pad = (n - k) `div` 2\n", "positive_code": [{"source_code": "main = do\n [n,k] <- fmap (map read . words) getLine\n putStrLn (solve n k)\n\nsolve :: Int -> Int -> String\nsolve n k =\n if even k\n then unlines [\"YES\",border,even1,even1,border]\n else if k <= n-2\n then unlines[\"YES\",border,odd1,border,border]\n else unlines[\"YES\",border,hotel1,odd2,border]\n where\n dots = repeat '.'\n hotels = repeat '#'\n\n border = take n dots\n even1 = take n $ '.' : (take (k`div`2) hotels) ++ dots\n odd1 = take n $ take ((n-k)`div`2) dots ++ take k hotels ++ dots\n odd2 = take n $ '.' : take ((k-n+2)`div`2) hotels ++ take (n-2-(k-n+2)) dots ++ take ((k-n+2)`div`2) hotels ++ dots\n hotel1 = take n $ '.' : take (n-2) hotels ++ dots"}], "negative_code": [{"source_code": "main = do\n [n,k] <- fmap (map read . words) getLine\n putStrLn (solve n k)\n\nsolve :: Int -> Int -> String\nsolve n k =\n unlines [\"YES\",border,center1,center2,border]\n where\n dots = repeat '.'\n hotels = repeat '#'\n\n border = take n dots\n center1 = take n $ '.' : (take (if k-n+2>=0 then k-n+2 else 0) hotels) ++ dots\n center2 = take n $ '.' : (take (if k-n+2>=0 then n-2 else k) hotels) ++ dots"}, {"source_code": "main = do\n [n,k] <- fmap (map read . words) getLine\n putStrLn (solve n k)\n\nsolve :: Int -> Int -> String\nsolve n k =\n if k>n-2 && odd k\n then \"NO\"\n else unlines[\"YES\",border,center1,center2,border]\n where\n dots = repeat '.'\n hotels = repeat '#'\n\n border = take n dots\n center1 = take n $ '.' : (take (if k<=n-2 then k else k`div`2) hotels) ++ dots\n center2 = take n $ '.' : (take (if k<=n-2 then 0 else k`div`2) hotels) ++ dots"}, {"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap parseInput $ getLine\n let ret = solve n k\n if (length ret) > 0\n then do\n putStrLn \"YES\"\n mapM_ putStrLn ret\n else putStrLn \"NO\"\n\nparseInput = map readInt . words\n where readInt x = (read x) :: Int\n\nsolve n k \n | even k = [fill 0, fill k', fill k', fill 0]\n | k == (n-2) = [fill 0, fill k, fill 0, fill 0]\n | otherwise = []\n where\n fill x = \".\" ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')\n k' = k `div` 2\n \n"}, {"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap parseInput $ getLine\n let ret = solve n k\n if (length ret) > 0\n then do\n putStrLn \"YES\"\n mapM_ putStrLn ret\n else putStrLn \"NO\"\n\nparseInput = map readInt . words\n where readInt x = (read x) :: Int\n\nsolve n k \n | even k = [fill 0, fill k', fill k', fill 0]\n | k <= (n-2) = [fill 0, fill' k pad, fill 0, fill 0]\n | otherwise = []\n where\n fill x = \".\" ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')\n fill' x y = (take y $ repeat '.') ++ (take x $ repeat '#') ++ (take (n-x-y) $ repeat '.')\n k' = k `div` 2\n pad = (n - k) `div` 2\n"}, {"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap parseInput $ getLine\n let ret = solve n k\n if (length ret) > 0\n then do\n putStrLn \"YES\"\n mapM_ putStrLn ret\n else putStrLn \"NO\"\n\nparseInput = map readInt . words\n where readInt x = (read x) :: Int\n\nsolve n k \n | even k = [fill 0, fill k', fill k', fill 0]\n | k <= (n-2) = [fill 0, fill' k pad, fill 0, fill 0]\n | otherwise = [fill 0, fill (n-2), fill' (k - n + 2) (2*n -3 -k), fill 0]\n where\n fill x = \".\" ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')\n fill' x y = (take y $ repeat '.') ++ (take x $ repeat '#') ++ (take (n-x-y) $ repeat '.')\n k' = k `div` 2\n pad = (n - k) `div` 2\n"}], "src_uid": "2669feb8200769869c4b2c29012059ed"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nbuildGraph :: Int -> [(Int,Int)]\nbuildGraph n = go 1 []\n where\n go v es | v > n = es | otherwise = go (v+1) es'\n where\n es' = es ++ [ (v,u) | (d,u) <- take (4 - degree ! v) l , d < 4 ]\n degree :: Array Int Int\n degree = accumArray (\\a b -> a+1) 0 (1,n) (es ++ map swap es)\n l = sort [ (d,i) | (i,d) <- assocs degree, i /= v ]\n\naddEdge :: [(Int,Int)] -> Int -> Int -> [(Int,Int)]\naddEdge es n p = es ++ take p [ (u,v) | ((u,v),False) <- assocs g, u < v ]\n where\n g :: Array (Int,Int) Bool\n g = defaultArray False ((1,1),(n,n)) $ do\n (u,v) <- es\n [((u,v),True),((v,u),True)]\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n (n,p) <- readIntPair\n let es = addEdge (buildGraph n) n p\n when (length es /= 2 * n + p ) $ putStrLn \"something wrong\"\n forM_ es $ putStrLn . unwords . map show . p2l\n", "positive_code": [{"source_code": "work [n, p] = take (2 * n + p) [show i ++ \" \" ++ show ((mod (i + d) n) + 1) | d <- [0 ..], i <- [1 .. n]]\nmain = interact $ unlines . map (unlines . work . map read . words) . tail . lines\n"}], "negative_code": [], "src_uid": "ddbac4053bd07eada84bc44275367ae2"} {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Maybe\none bool = if bool then 1 else 0\ndata Search = Search{count::Integer,startC::Bool,endA::Bool} deriving (Eq,Show,Ord)\n(+!) :: Search -> Search -> Search\na +! b = Search (count a + count b + (one $ endA a && startC b )) (startC a) (endA b)\nspecChars:: Search -> Int\nspecChars s = (one $ startC s) + (one $ endA s)\nmain = do\n\t[ k,\u2009x,\u2009n,\u2009m ] <- (map read) <$> words <$> getLine ::IO [Int]\n\tmapM putStrLn $ solution k\u2009x\u2009n\u2009m where \n\t\tsolution k\u2009x\u2009n\u2009m = let\t\n\t\t\titer a b k = if k == 2 then b else iter b (a+!b) (k - 1 )\n\t\t\titerS a b k = if k == 2 then b else iterS b (a++b) (k - 1 )\n\t\t\tchoices n = if n == 0 then [[]] else [c:cs| c<-[False,True], cs <- choices (n-1)] \n\t\t\tvariants = [(Search (toInteger a) xa ya ,Search (toInteger b) xb yb) | [xa,ya, xb, yb] <-(choices 4), \n\t\t\t\ta <- [0..div (n - one xa - one ya ) 2], \n\t\t\t\tb <- [0..div (m - one xb - one yb ) 2]]\n\t\t\tsearch = find fitting variants where\n\t\t\t\tfitting (a,b) = (count $ iter a b k) == (toInteger x)\n\t\t\tcomplete u l = \t(if startC u then \"C\" else []) ++ \n\t\t\t\t\t\t \treplicate (l - (2 * (fromIntegral $ count u)) - specChars u) 'X' ++ \n\t\t\t\t\t\t \t(foldl' (++) \"\" $ replicate (fromIntegral $ count u) \"AC\") ++\n\t\t\t\t\t\t \tif endA u then \"A\" else []\n\t\t\tstrings = do\n\t\t\t\t(a,b) <- search\n\t\t\t\treturn [complete a n, complete b m]\n\t\t\tin fromMaybe [\"Happy new year!\"] strings\n\t\t\t--in [show $ choices k]", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ntimes s k = concat $ take k $ repeat s\n\ncheck k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (fromIntegral ac1,h1,l1) (fromIntegral ac2,h2,l2) == fromIntegral x\n where\n go 0 (ac,_,_) _ = ac :: Int64\n go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)\n where\n ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)\n h3 = h1\n l3 = l2\n\n\nbuild 1 _ ch _ = [ch]\nbuild n ac 'X' 'A' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'X' 'X' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'X' 'C' = times \"X\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'C' 'A' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'C' 'X' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'C' 'C' = times \"C\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'A' 'A' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'A' 'X' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n 0 'A' 'C' = \"A\" ++ times \"X\" (n - 2) ++ \"C\"\nbuild n ac 'A' 'C' = times \"A\" (n - 2 * ac) ++ times \"AC\" ac\n\nvalid 1 _ h l = h == l\nvalid n 0 'A' 'C' = n > 2\nvalid n ac 'X' 'A' = ac * 2 <= n - 2\nvalid n ac 'X' 'X' = ac * 2 <= n - 2\nvalid n ac 'X' 'C' = ac * 2 <= n - 1\nvalid n ac 'C' 'A' = ac * 2 <= n - 2\nvalid n ac 'C' 'X' = ac * 2 <= n - 2\nvalid n ac 'C' 'C' = ac * 2 <= n - 1\nvalid n ac 'A' 'A' = ac * 2 <= n - 1\nvalid n ac 'A' 'X' = ac * 2 <= n - 1\nvalid n ac 'A' 'C' = ac * 2 <= n\n\nsearch :: Int -> Int -> Int -> Int -> Maybe (String,String)\nsearch k x n m = listToMaybe $ do\n ac1 <- [0..div n 2]\n h1 <- \"ACX\"\n l1 <- \"ACX\"\n guard (valid n ac1 h1 l1)\n ac2 <- [0..div m 2]\n h2 <- \"ACX\"\n l2 <- \"ACX\"\n guard (valid m ac2 h2 l2)\n guard (check k x (ac1,h1,l1) (ac2,h2,l2))\n let s1 = build n ac1 h1 l1\n let s2 = build m ac2 h2 l2 \n return (s1,s2)\n\n\nmain = do\n [k,x,n,m] <- readInts\n case search k x n m of\n Nothing -> putStrLn \"Happy new year!\"\n Just (l1,l2) -> do\n putStrLn l1\n putStrLn l2\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Maybe\none bool = if bool then 1 else 0\ndata Search = Search{count::Integer,startC::Bool,endA::Bool} deriving (Eq,Show,Ord)\n(+!) :: Search -> Search -> Search\na +! b = Search (count a + count b + (one $ endA a && startC b )) (startC a) (endA b)\nspecChars:: Search -> Int\nspecChars s = (one $ startC s) + (one $ endA s)\nmain = do\n\t[ k,\u2009x,\u2009n,\u2009m ] <- (map read) <$> words <$> getLine ::IO [Int]\n\tmapM putStrLn $ solution k\u2009x\u2009n\u2009m where \n\t\tsolution k\u2009x\u2009n\u2009m = let\t\n\t\t\titer a b k = if k == 2 then b else iter b (a+!b) (k - 1 )\n\t\t\titerS a b k = if k == 2 then b else iterS b (a++b) (k - 1 )\n\t\t\tchoices n = if n == 0 then [[]] else [c:cs| c<-[False,True], cs <- choices (n-1)] \n\t\t\tvariants = [(Search (toInteger a) xa ya ,Search (toInteger b) xb yb) | [xa,ya, xb, yb] <-(choices 4), \n\t\t\t\ta <- [0..div (n - one xa - one xb ) 2], \n\t\t\t\tb<- [0..div (m - one xa - one xb ) 2]]\n\t\t\tsearch = find fitting variants where\n\t\t\t\tfitting (a,b) = (count $ iter a b k) == (toInteger x)\n\t\t\tcomplete u l = \t(if startC u then \"C\" else []) ++ \n\t\t\t\t\t\t \treplicate (l - (2 * (fromIntegral $ count u)) - specChars u) 'X' ++ \n\t\t\t\t\t\t \t(foldl' (++) \"\" $ replicate (fromIntegral $ count u) \"AC\") ++\n\t\t\t\t\t\t \tif endA u then \"A\" else []\n\t\t\tstrings = do\n\t\t\t\t(a,b) <- search\n\t\t\t\treturn [complete a n, complete b m]\n\t\t\tin fromMaybe [\"Happy new year!\"] strings\n\t\t\t--in [show $ choices k]"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Maybe\nmain = do\n\t[ k,\u2009x,\u2009n,\u2009m ] <- (map read) <$> words <$> getLine ::IO [Int]\n\tmapM putStrLn $ solution k\u2009x\u2009n\u2009m where \n\t\tsolution k\u2009x\u2009n\u2009m = let\t\n\t\t\titer a b k = if k == 2 then b else iter b (a+b) (k - 1 )\n\t\t\tvariants = [(a,b) | a <- [0..div n 2], b<- [0..div m 2]]\n\t\t\tvariants2 = [(a,b) | a <- [0..div (n-1) 2], b<- [0..div (m-1) 2]]\n\t\t\tsearch = find fitting variants where\n\t\t\t\tfitting (a,b) = iter (toInteger a) (toInteger b) k == (toInteger x)\n\t\t\tsearch2 = find fitting variants2 where \n\t\t\t\tfitting (a,b) = iter (toInteger b) (toInteger (a+b+1)) (k-1) == (toInteger x)\n\t\t\tcomplete u l = replicate (l - (2 * u)) 'X' ++ (foldl' (++) \"\" $ replicate u \"AC\")\n\t\t\tcompleteA u = replicate (n - 1 - (2 * u)) 'X' ++ (foldl' (++) \"\" $ replicate u \"AC\") ++ \"A\"\n\t\t\tcompleteB u = \"C\" ++ replicate (m - 1 - (2 * u)) 'X' ++ (foldl' (++) \"\" $ replicate u \"AC\")\n\t\t\tstrings = do\n\t\t\t\t(a,b) <- search\n\t\t\t\treturn [complete a n, complete b m]\n\t\t\tstrings2 = do\n\t\t\t\t(a,b) <- search2\n\t\t\t\treturn [completeA a, completeB b]\n\t\t\tin (fromMaybe ( fromMaybe [\"Happy new year!\"] strings2 ) strings)"}, {"source_code": "(<<) = flip map\nmain = print $ [1,2,3] <<(+3)<<(*5)<< flip mod 7 << flip div 2 "}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Maybe\nmain = do\n\t[ k,\u2009x,\u2009n,\u2009m ] <- (map read) <$> words <$> getLine ::IO [Int]\n\tmapM putStrLn $ solution k\u2009x\u2009n\u2009m where \n\t\tsolution k\u2009x\u2009n\u2009m = let\t\n\t\t\titer a b k = if k == 2 then b else iter b (a+b) (k - 1 )\n\t\t\tvariants = [(a,b) | a <- [0..div n 2], b<- [0..div m 2]]\n\t\t\tvariants2 = [(a,b) | a <- [0..div (n-1) 2], b<- [0..div (m-1) 2]]\n\t\t\tsearch = find fitting variants where\n\t\t\t\tfitting (a,b) = iter (toInteger a) (toInteger b) k == (toInteger x)\n\t\t\tsearch2 = find fitting variants2 where \n\t\t\t\tfitting (a,b) = iter (toInteger b) (toInteger (a+b+1)) (k-1) == (toInteger x)\n\t\t\tcomplete u l = replicate (l - (2 * u)) 'X' ++ (foldl' (++) \"\" $ replicate u \"AC\")\n\t\t\tcompleteA u = replicate (n - 1 - (2 * u)) 'X' ++ (foldl' (++) \"\" $ replicate u \"AC\") ++ \"A\"\n\t\t\tcompleteB u = \"C\" ++ replicate (m - 1 - (2 * u)) 'X' ++ (foldl' (++) \"\" $ replicate u \"AC\")\n\t\t\tstrings = do\n\t\t\t\t(a,b) <- search\n\t\t\t\treturn [complete a n, complete b m]\n\t\t\tstrings2 = do\n\t\t\t\t(a,b) <- search2\n\t\t\t\treturn [completeA a, completeB b]\n\t\t\tin (fromMaybe ( fromMaybe [\"Happy new year!\"] strings2 ) strings)"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ntimes s k = concat $ take k $ repeat s\n\ncheck k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac1,h1,l1) (ac2,h2,l2) == x\n where\n go 0 (ac,_,_) _ = ac\n go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)\n where\n ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)\n h3 = h1\n l3 = l2\n\n\nbuild 1 _ ch _ = [ch]\nbuild n ac 'X' 'A' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'X' 'X' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'X' 'C' = times \"X\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'C' 'A' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'C' 'X' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'C' 'C' = times \"C\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'A' 'A' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'A' 'X' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'A' 'C' = times \"A\" (n - 2 * ac) ++ times \"AC\" ac\n\nvalid 1 _ h l = h == l\nvalid 2 ac 'A' 'C' = ac == 1\nvalid n ac 'X' 'A' = ac * 2 <= n - 2\nvalid n ac 'X' 'X' = ac * 2 <= n - 2\nvalid n ac 'X' 'C' = ac * 2 <= n - 1\nvalid n ac 'C' 'A' = ac * 2 <= n - 2\nvalid n ac 'C' 'X' = ac * 2 <= n - 2\nvalid n ac 'C' 'C' = ac * 2 <= n - 1\nvalid n ac 'A' 'A' = ac * 2 <= n - 1\nvalid n ac 'A' 'X' = ac * 2 <= n - 1\nvalid n ac 'A' 'C' = ac * 2 <= n\n\nsearch :: Int -> Int -> Int -> Int -> Maybe (String,String)\nsearch k x n m = listToMaybe $ do\n ac1 <- [0..div n 2]\n h1 <- \"ACX\"\n l1 <- \"ACX\"\n guard (valid n ac1 h1 l1)\n ac2 <- [0..div m 2]\n h2 <- \"ACX\"\n l2 <- \"ACX\"\n guard (valid m ac2 h2 l2)\n guard (check k x (ac1,h1,l1) (ac2,h2,l2))\n let s1 = build n ac1 h1 l1\n let s2 = build m ac2 h2 l2\n return (s1,s2)\n\n\nmain = do\n [k,x,n,m] <- readInts\n case search k x n m of\n Nothing -> putStrLn \"Happy new year!\"\n Just (l1,l2) -> do\n putStrLn l1\n putStrLn l2\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ntimes s k = concat $ take k $ repeat s\n\ncheck k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac1,h1,l1) (ac2,h2,l2) == x\n where\n go 0 (ac,_,_) _ = ac\n go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)\n where\n ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)\n h3 = h1\n l3 = l2\n\n\nbuild 1 _ ch _ = [ch]\nbuild n ac 'X' 'A' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'X' 'X' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'X' 'C' = times \"X\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'C' 'A' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'C' 'X' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'C' 'C' = times \"C\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'A' 'A' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'A' 'X' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'A' 'C' = times \"A\" (n - 2 * ac) ++ times \"AC\" ac\n\nvalid 1 _ h l = h == l\nvalid n ac 'X' 'A' = ac * 2 <= n - 2\nvalid n ac 'X' 'X' = ac * 2 <= n - 2\nvalid n ac 'X' 'C' = ac * 2 <= n - 1\nvalid n ac 'C' 'A' = ac * 2 <= n - 2\nvalid n ac 'C' 'X' = ac * 2 <= n - 2\nvalid n ac 'C' 'C' = ac * 2 <= n - 1\nvalid n ac 'A' 'A' = ac * 2 <= n - 1\nvalid n ac 'A' 'X' = ac * 2 <= n - 1\nvalid n ac 'A' 'C' = ac * 2 <= n\n\nsearch :: Int -> Int -> Int -> Int -> Maybe (String,String)\nsearch k x n m = listToMaybe $ do\n ac1 <- [0..div n 2]\n h1 <- \"ACX\"\n l1 <- \"ACX\"\n guard (valid n ac1 h1 l1)\n ac2 <- [0..div m 2]\n h2 <- \"ACX\"\n l2 <- \"ACX\"\n guard (valid m ac2 h2 l2)\n guard (check k x (ac1,h1,l1) (ac2,h2,l2))\n let s1 = build n ac1 h1 l1\n let s2 = build m ac2 h2 l2\n return (s1,s2)\n\n\nmain = do\n [k,x,n,m] <- readInts\n case search k x n m of\n Nothing -> putStrLn \"Happy new year!\"\n Just (l1,l2) -> do\n putStrLn l1\n putStrLn l2\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ntimes s k = concat $ take k $ repeat s\n\ncheck k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (fromIntegral ac1,h1,l1) (fromIntegral ac2,h2,l2) == fromIntegral x\n where\n go 0 (ac,_,_) _ = ac :: Int64\n go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)\n where\n ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)\n h3 = h1\n l3 = l2\n\n\nbuild 1 _ ch _ = [ch]\nbuild n ac 'X' 'A' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'X' 'X' = times \"X\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'X' 'C' = times \"X\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'C' 'A' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'C' 'X' = times \"C\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'C' 'C' = times \"C\" (n - 2 * ac) ++ times \"AC\" ac\nbuild n ac 'A' 'A' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"A\"\nbuild n ac 'A' 'X' = times \"A\" (n - 2 * ac - 1) ++ times \"AC\" ac ++ \"X\"\nbuild n ac 'A' 'C' = times \"A\" (n - 2 * ac) ++ times \"AC\" ac\n\nvalid 1 _ h l = h == l\nvalid 2 ac 'A' 'C' = ac == 1\nvalid n ac 'X' 'A' = ac * 2 <= n - 2\nvalid n ac 'X' 'X' = ac * 2 <= n - 2\nvalid n ac 'X' 'C' = ac * 2 <= n - 1\nvalid n ac 'C' 'A' = ac * 2 <= n - 2\nvalid n ac 'C' 'X' = ac * 2 <= n - 2\nvalid n ac 'C' 'C' = ac * 2 <= n - 1\nvalid n ac 'A' 'A' = ac * 2 <= n - 1\nvalid n ac 'A' 'X' = ac * 2 <= n - 1\nvalid n ac 'A' 'C' = ac * 2 <= n\n\nsearch :: Int -> Int -> Int -> Int -> Maybe (String,String)\nsearch k x n m = listToMaybe $ do\n ac1 <- [0..div n 2]\n h1 <- \"ACX\"\n l1 <- \"ACX\"\n guard (valid n ac1 h1 l1)\n ac2 <- [0..div m 2]\n h2 <- \"ACX\"\n l2 <- \"ACX\"\n guard (valid m ac2 h2 l2)\n guard (check k x (ac1,h1,l1) (ac2,h2,l2))\n let s1 = build n ac1 h1 l1\n let s2 = build m ac2 h2 l2\n return (s1,s2)\n\n\nmain = do\n [k,x,n,m] <- readInts\n case search k x n m of\n Nothing -> putStrLn \"Happy new year!\"\n Just (l1,l2) -> do\n putStrLn l1\n putStrLn l2\n"}], "src_uid": "1d55d31320368ddb1439ee086d40b57c"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\n\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Word\n\ndata Action = Action !Word64 !(UArray Int Int)\ndata Status = Status !Word64 !Word64\n\nstep :: Status -> Action -> [Status]\nstep (Status smask vis) (Action amask ixs) = let\n existingOnes = popCount (smask .&. amask)\n newIxs = popCount (complement vis .&. amask)\n in do\n resOnes <- [existingOnes .. existingOnes + newIxs]\n let ares = (bit (ixs ! resOnes) - 1) .&. amask\n pure $ Status (smask .&. complement amask .|. ares) (vis .|. amask)\n\nstepEach :: [Status] -> Action -> [Status]\nstepEach s a = concatMap (`step` a) s\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, k] <- readInts\n actions <- replicateM k $ do\n qi : ji <- readInts\n let\n amask = foldl' (\\acc ix -> acc .|. bit ix) 0 ji\n ixs = array (0, qi) $ (qi, n+1) : zip [0..] ji\n pure $ Action amask ixs\n let\n start = Status 0 0\n opts = foldl stepEach [start] actions\n tarVis = bit (n + 1) - bit 1\n ok = and $ do\n Status smask vis <- opts\n pure $ (n == 1 || vis == tarVis) && smask .&. (smask + 2) == 0\n lift $ putStrLn $ if ok\n then \"ACCEPTED\"\n else \"REJECTED\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.List\r\nimport Data.Word\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readMany\r\n a <- replicateM k readMany\r\n let step (prvm, xs) ~(q:js) = (prvm .|. m, concatMap gen xs) where\r\n ma = listArray (0, q) $ scanl (.|.) 0 $ map (bit . subtract 1) $ sort js :: UArray Int Word64\r\n m = ma!q\r\n com = prvm .&. m\r\n gen x = map ((prvx .|.) . (ma!)) [ones .. q-zeros] where\r\n ones = popCount $ com .&. x\r\n zeros = popCount $ com .&. complement x\r\n prvx = x .&. complement m\r\n (m, xs) = foldl' step (0, [0]) a\r\n ok = n == 1 || m == bit n - 1 && all (\\x -> x .&. (x + 1) == 0) xs\r\n putStrLn $ if ok then \"ACCEPTED\" else \"REJECTED\"\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}, {"source_code": "-- Resubmission, to find out how much 64-bit helps\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.List\r\n\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Word\r\n\r\ndata Action = Action !Word64 !Int !(UArray Int Int)\r\nnewtype Status = Status Word64\r\n\r\nstep :: Status -> Action -> [Status]\r\nstep (Status smask) (Action amask newIxs ixs) = let\r\n existingOnes = popCount (smask .&. amask)\r\n in do\r\n resOnes <- [existingOnes .. existingOnes + newIxs]\r\n let ares = (bit (ixs ! resOnes) - 1) .&. amask\r\n pure $ Status (smask .&. complement amask .|. ares)\r\n\r\nstepEach :: [Status] -> Action -> [Status]\r\nstepEach s a = concatMap (`step` a) s\r\n\r\nprocessAction :: Int -> (Word64, Action) -> [Int] -> (Word64, Action)\r\nprocessAction n (vis, _) (qi : ji) = let\r\n amask = foldl' (\\acc ix -> acc .|. bit ix) 0 ji\r\n newIxs = popCount (amask .&. complement vis)\r\n ixs = array (0, qi) $ (qi, n+1) : zip [0..] ji\r\n in (vis .|. amask, Action amask newIxs ixs)\r\nprocessAction _ _ _ = error \"unexpected empty line in input\"\r\n\r\nmain :: IO ()\r\nmain = (P.getContents >>=) . evalStateT $ do\r\n [n, k] <- readInts\r\n rawActions <- replicateM k readInts\r\n let\r\n process = scanl (processAction n) (0, undefined) rawActions\r\n actions = tail $ map snd process\r\n vis = fst $ last process\r\n start = Status 0\r\n opts = foldl stepEach [start] actions\r\n tarVis = bit (n + 1) - bit 1\r\n ok = and $ (n == 1 || vis == tarVis) : do\r\n Status smask <- opts\r\n pure $ smask .&. (smask + 2) == 0\r\n lift $ putStrLn $ if ok\r\n then \"ACCEPTED\"\r\n else \"REJECTED\"\r\n\r\ntype SIO = StateT P.ByteString IO\r\n\r\nreadLine :: SIO P.ByteString\r\nreadLine = do\r\n (out, next) <- P.break (<= '\\r') <$> get\r\n put $ P.dropWhile (<= '\\r') next\r\n pure out\r\n\r\nreadInts :: SIO [Int]\r\nreadInts = do\r\n currLine <- readLine\r\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\n\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Word\n\ndata Action = Action !Word64 !Int !(UArray Int Int)\nnewtype Status = Status Word64\n\nstep :: Status -> Action -> [Status]\nstep (Status smask) (Action amask newIxs ixs) = let\n existingOnes = popCount (smask .&. amask)\n in do\n resOnes <- [existingOnes .. existingOnes + newIxs]\n let ares = (bit (ixs ! resOnes) - 1) .&. amask\n pure $ Status (smask .&. complement amask .|. ares)\n\nstepEach :: [Status] -> Action -> [Status]\nstepEach s a = concatMap (`step` a) s\n\nprocessAction :: Int -> (Word64, Action) -> [Int] -> (Word64, Action)\nprocessAction n (vis, _) (qi : ji) = let\n amask = foldl' (\\acc ix -> acc .|. bit ix) 0 ji\n newIxs = popCount (amask .&. complement vis)\n ixs = array (0, qi) $ (qi, n+1) : zip [0..] ji\n in (vis .|. amask, Action amask newIxs ixs)\nprocessAction _ _ _ = error \"unexpected empty line in input\"\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, k] <- readInts\n rawActions <- replicateM k readInts\n let\n process = scanl (processAction n) (0, undefined) rawActions\n actions = tail $ map snd process\n vis = fst $ last process\n start = Status 0\n opts = foldl stepEach [start] actions\n tarVis = bit (n + 1) - bit 1\n ok = and $ (n == 1 || vis == tarVis) : do\n Status smask <- opts\n pure $ smask .&. (smask + 2) == 0\n lift $ putStrLn $ if ok\n then \"ACCEPTED\"\n else \"REJECTED\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nstep :: UArray Int Int -> [Int] -> [UArray Int Int]\nstep arr ixs = let\n neg = length [() | i <- ixs, arr ! i < 0]\n nonpos = length [() | i <- ixs, arr ! i <= 0]\n in do\n newNeg <- [neg .. nonpos]\n pure $ arr // zip ixs (replicate newNeg (0-1) ++ repeat 1)\n\nstepEach :: [UArray Int Int] -> [Int] -> [UArray Int Int]\nstepEach arrs ixs = do\n arr <- arrs\n step arr ixs\n\nsorted :: UArray Int Int -> Bool\nsorted arr = null $ dropWhile (== 1) $ dropWhile (< 0) $ elems arr\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, k] <- readInts\n acts <- replicateM k $ tail <$> readInts\n let\n start = accumArray undefined 0 (1, n) []\n opts = foldl stepEach [start] acts\n lift $ putStrLn $ if all sorted opts\n then \"ACCEPTED\"\n else \"REJECTED\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "598c434832d8aa1cbba8b3ea309be235"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, a, b] <- getIntList\n putStrLn $ f n a b\n\nf :: Int -> Int -> Int -> String\nf n a b = take n . cycle $ (take a $ (take b ['a' .. 'z'] ++ cycle [['a'..'z'] !! (b - 1)]))", "positive_code": [{"source_code": "solve :: [Int] -> String\nsolve [n,a,b] = take n $ cycle $ take b ['a'..]\n\nmain :: IO ()\nmain = interact $ unlines . map (solve . map read . words) . tail . lines\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Char (chr, ord)\n\nsolve n a b = take n res where\n\tperiod = replicate (b-1) 1 ++ replicate (a-b) 0\n\tcyclic = if null period then repeat 0 else cycle period\n\tres = map chr' $ map (`mod` 26) $ scanl(+) 0 cyclic\n\tchr' k = chr (k + ord 'a')\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\t[n,a,b] <- fmap (map read.words) getLine\n\t\tputStrLn (solve n a b)"}, {"source_code": "import Control.Monad\n\nalf = ['a'..'z']\n\nr str = concat (repeat str)\n\nsubstring :: Int -> Int-> String\nsubstring a b = take a ((take b alf) ++ (repeat (alf!!(b-1))))\n\nfoo :: Int -> Int -> Int -> String\nfoo n a b = take n (r (substring a b))\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain :: IO()\nmain = do\n t <- readLn :: IO Int\n forM_ [1..t] $ \\i -> do\n arr <- readInts\n putStrLn (foo (arr!!0) (arr!!1) (arr!!2))\n"}, {"source_code": "alph :: String\nalph = ['a'..'z']\n\naddReplicas :: Int -> String -> String\naddReplicas n s\n | n <= l = take n s\n | otherwise = s ++ addReplicas (n-l) s\n where\n l = length s\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:a:b:_) <- readInts\n putStrLn $ addReplicas n (take b alph)\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,a,b]<- map read <$> words <$> getLine::IO [Int]\n\t\tputStrLn $ take n $ cycle $ take b \"abcdefghijklmnopqrstuvwxyz\"\n\nmain = do\n\t\ta<-read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\n"}, {"source_code": "process :: Int -> Int -> Int -> [Char]\nprocess n a b = take n.cycle.take b $ ['a'..'z']\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n [n,a,b] <- fmap (map readInt.words) getLine\n putStrLn $ process n a b\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "import Data.Char \n\nmain :: IO ()\nmain = do\n getLine\n answers <- map (solve . map read . words) <$> lines <$> getContents\n mapM_ putStrLn answers\n\nsolve :: [Int] -> String\nsolve [len,sub,chars] = take len . cycle $ segment\n where segment = replicate (sub - chars) 'a' ++ (take chars ['a'..'z'])\n"}, {"source_code": "import Control.Monad (replicateM_)\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (getList >>= putStrLn . solve)\n\nsolve :: [Int] -> String\nsolve [n,a,b] = take n $ cycle letters where\n letters = replicate (a-b) 'a' ++ take b ['a'..'z']"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,a,b]<- map read <$> words <$> getLine::IO [Int]\n\t\tputStrLn $ take n $ cycle $ take b \"abcdefghijklmnopqrstuvwyz\"\n\nmain = do\n\t\ta<-read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,a,b]<- map read <$> words <$> getLine::IO [Int]\n\t\tprint $ take n $ cycle $ take b \"abcdefghijklmnopqrstuvwyz\"\n\nmain = do\n\t\ta<-read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\n"}], "src_uid": "a82f15c1b0ddcacc1de966be20cfc5a2"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport IO\n\nmain = do C.hGetContents stdin >>= putStrLn . show . gao . map (fst . fromJust . C.readInt) . tail . C.words\n\ngao a = (sum a -) $ (2*) $ minimum $ zipWith (+) (f a) $ reverse $ f $ reverse a where\n\tf = scanl1 min . scanl (+) 0\n\n", "positive_code": [{"source_code": "main = interact (ans)\nans theInput = show answer where\n [[n],a] = map (map (read::String->Int)) (map words (lines theInput))\n lastMax [] = (0,0,0,0)\n lastMax (x:xs) = (if x+y > 0 then (max u (v+x+x+y+z),v+x,x+y,z) else (max u (v+z-y),v+x,0,z-x-y)) where\n (u,v,y,z) = lastMax xs\n answer = u-v where (u,v,y,z) = lastMax a\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve a = let pre = calcMaxSum a\n suf = reverse $ calcMaxSum (reverse a)\n in solve' pre (tail suf) (sum a)\n where solve' :: [Int] -> [Int] -> Int -> Int\n solve' [a] [] m = max a m\n solve' (a:ax) (b:bx) m = solve' ax bx (max m (a + b))\n\naccumulate :: (a -> b -> a) -> a -> [b] -> [a]\naccumulate _ _ [] = []\naccumulate op last (a:s) = let v = op last a\n in v : accumulate op v s\n\ntransition :: (Int, Int) -> Int -> (Int, Int)\ntransition (a, b) c = (a - c, max (c + max a b) (a - c))\n\ncalcMaxSum :: [Int] -> [Int]\ncalcMaxSum = map snd . accumulate transition (0, 0)\n"}, {"source_code": "plus :: [Int] -> Int -> Int\nplus [] cur = cur\nplus (x:xs) cur = max cur $ plus xs $ max 0 $ cur + x\n\nmain = do\n\tn <- getLine >>= return . read :: IO Int\n\ta <- getLine >>= return . (map read) . words :: IO [Int]\n\tputStrLn $ show $ (plus a 0 * 2) - (foldl (+) 0 a)\n"}], "negative_code": [], "src_uid": "89237865c97d64406050fd140d4166f9"} {"source_code": "-- http://codeforces.com/problemset/problem/546/B\n\nimport Data.List\n\nmain = do\n\n\tn <- fmap read getLine :: IO Int\n\tbadges <- fmap sort $ fmap (map read) $ fmap words $ getLine :: IO [Int]\n\n\tlet\n\t\tmoney_spent = giveBadges 0 badges\n\n\tputStrLn $ show money_spent\n\ngiveBadges :: Int -> [Int] -> Int\ngiveBadges _ [] = 0\ngiveBadges prev (x:xs) =\n\tlet\n\t\tcalc = if prev >= x then prev - x + 1 else 0\n\tin\n\t\tcalc + giveBadges (max (prev + 1) x) xs", "positive_code": [{"source_code": "-- http://codeforces.com/problemset/problem/546/B\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\ncreateMap :: [[Int]] -> Map.Map Int Int\ncreateMap [] = Map.empty\ncreateMap (x:xs) = Map.insert (head x) (length x) $ createMap xs\n\nmain = do\n\n\tn <- fmap read getLine :: IO Int\n\tbadges <- fmap sort $ fmap (map read) $ fmap words $ getLine :: IO [Int]\n\n\tlet\n\t\tmoney_spent = giveBadges 0 badges\n\n\tputStrLn $ show money_spent\n\ngiveBadges :: Int -> [Int] -> Int\ngiveBadges _ [] = 0\ngiveBadges prev (x:xs) =\n\tlet\n\t\tcalc = if prev >= x then prev - x + 1 else 0\n\tin\n\t\tcalc + giveBadges (max (prev + 1) x) xs"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n f _ [] = 0\n f m (x:xs)\n | x > m = f (x+1) xs\n | otherwise = (m-x) + f (m+1) xs\n\n print $ f (minimum xs) $ sort xs\n"}, {"source_code": "-- Codeforces 546B\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= print . solve . sort . map read . words\n\n-- note: only cdn increase the coolness value, can't decrease it, so need do sort.\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve [_] = 0\nsolve (x:y:xs) = if (y <= x) then (x-y+1) + solve (x+1:xs) else solve (y:xs)\n\n"}, {"source_code": "import Data.List\nimport Data.Map (Map)\n\nmain = do\n getLine\n input <- getLine\n let fs = sort $ map (read :: String -> Int) (words input)\n putStrLn $ show $ f fs\n\nf :: [Int] -> Int\nf [] = 0\nf [_] = 0\nf (x:y:xs) = if y <= x then x - y + 1 + f (x + 1:xs) else f (y:xs)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Array\n\nprocess::Int->Int->[Int]->Int\nprocess n m [] | m==0 =n\n | otherwise = process (n+m) (m-1) []\nprocess n m (x:xs) | x==0 && m>0 = process (n+m) (m-1) xs\n | x==0 = process n m xs\n | x==1 = process (n+m) m xs\n | otherwise = process (n+m) (m+x-1) xs\n\n\n\n\nmain = do\n n <- read <$> getLine::IO Int\n d<-map read <$> words <$> getLine ::IO [Int]\n let x = accumArray (+) 0 (1,n) $ zip d (repeat 1)\n print $ process 0 0 (elems x)\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve xs = sum (scanl (\\x y -> max (x + 1) y) 0 (sort xs)) - sum xs\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve 0 . sort . map read . tail . words\nsolve p (a:as) | a <= p = p-a+1 + solve (p+1) as\n | otherwise = solve a as\nsolve _ [] = 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n\n\nprocess [] x y = x + (div (y*(y+1)) 2)\nprocess (a:as) x y\t| a==0 = process as (x+y) (max (y-1) 0)\n \t| a==1 = process as (x+y) y\n\t | otherwise = process as (x+y) (y+a-1)\n\n\nmain= do\n\tn<-read <$> getLine::IO Int\n\ts<- map read .words <$> getLine ::IO [Int]\n\tlet a= accumArray (+) 0 (1,3000) [(i,1)|i<-s]\n\tprint $ process (elems a) 0 0\n\t "}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . (map read . words . (!! 1) . lines) =<< getContents\n\nsolve :: [Int] -> Int\nsolve = fst . foldl step (0, 0) . sort\n where step (sum, m) a = let b = max (m + 1) a\n d = max 0 (b - a)\n in (sum + d, b)\n"}], "negative_code": [{"source_code": "-- http://codeforces.com/problemset/problem/546/B\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\ncreateMap :: [[Int]] -> Map.Map Int Int\ncreateMap [] = Map.empty\ncreateMap (x:xs) = Map.insert (head x) (length x) $ createMap xs\n\nmain = do\n\n\tn <- fmap read getLine :: IO Int\n\tbadges <- fmap group $ fmap sort $ fmap (map read) $ fmap words $ getLine :: IO [[Int]]\n\n\tlet\n\t\tbadges_list = map head $ badges\n\t\tdescriptor = createMap badges\n\t\tmoney_spent = giveBadges badges_list descriptor\n\n\tputStrLn $ show money_spent\n\ngiveBadges :: [Int] -> Map.Map Int Int -> Int\ngiveBadges [] _ = 0\ngiveBadges badges@(b:bs) map\n\t| total_of_badge > 1 = 1 + (giveBadges badges $ updateMap b (b+1) map)\n\t| otherwise = giveBadges bs map\n\twhere\n\t\ttotal_of_badge = fromJust $ Map.lookup b map\n\n\t\tupdateMap :: Int -> Int -> Map.Map Int Int -> Map.Map Int Int\n\t\tupdateMap a b map =\n\t\t\tlet\n\t\t\t\tmapA = case Map.lookup a map of\n\t\t\t\t\tNothing -> Map.insert a 1 map\n\t\t\t\t\tJust 1 -> Map.delete a map\n\t\t\t\t\tJust _ -> Map.adjust (+(-1)) a map\n\t\t\t\tmapB = case Map.lookup b mapA of\n\t\t\t\t\tNothing -> Map.insert b 1 mapA\n\t\t\t\t\tJust _ -> Map.adjust (+1) b mapA\n\t\t\tin\n\t\t\t\tmapB"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n let\n f _ [] = 0\n f (x:xs) ys = abs (x-m) + f xs (ys \\\\ [m])\n where\n m = minimumBy (comparing (\\v -> abs $ v - x)) ys\n\n print $ f xs [1..n]\n"}, {"source_code": "-- Codeforces 546B\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve xs = (m * (m+1) `div` 2) - sum xs where m = maximum xs\n\n"}, {"source_code": "import Data.List\nimport Data.Map (Map)\n\nmain = do\n getLine\n input <- getLine\n let fs = reverse . sort $ map (read :: String -> Int) (words input)\n putStrLn $ show $ f (length fs) fs\n\nf :: Int -> [Int] -> Int\nf _ [] = 0\nf max (x:xs) = (max - x) + f (max - 1) xs\n"}, {"source_code": "import Data.List\nimport Data.Map (Map)\n\nmain = do\n getLine\n input <- getLine\n let fs = reverse . sort $ map (read :: String -> Int) (words input)\n putStrLn $ show $ f (length fs + minimum fs - 1) fs\n\nf :: Int -> [Int] -> Int\nf _ [] = 0\nf max (x:xs) = (max - x) + f (max - 1) xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Array\n\nprocess::Int->Int->[Int]->Int\nprocess n m [] | m==0 =n\n | otherwise = process (n+m) (m-1) []\nprocess n m (x:xs) | x==0 && m>0 = process (n+m) (m-1) xs\n | x==0 = process n m xs\n | x==1 = process (n+m) m xs\n | otherwise = process n (m+x-1) xs\n\n\n\n\nmain = do\n n <- read <$> getLine::IO Int\n d<-map read <$> words <$> getLine ::IO [Int]\n let x = accumArray (+) 0 (1,n) $ zip d (repeat 1)\n print $ process 0 0 (elems x)\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\nimport Data.List (sort)\n\nmain :: IO ()\nmain = print =<< solve <$> readLn <*> (map read <$> words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = sum ys - n * min 0 (minimum ys)\n where ys = zipWith (-) (enumFrom (minimum xs)) (sort xs)\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve = sum . zipWith (-) [1..] . sort\n"}, {"source_code": "import Control.Arrow ((&&&))\nimport Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve = sum . uncurry (zipWith (-)) . (enumFrom . minimum &&& sort)\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . (map read . words . (!! 1) . lines) =<< getContents\n\nsolve :: [Int] -> Int\nsolve a = length . filter id $ zipWith (>) [1..n] (sort a)\n where n = length a\n"}], "src_uid": "53ae714f04fd29721b8bbf77576b7ccf"} {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\ndata Player = S | Z\n deriving Eq\n\nsolve :: [Int] -> Double\nsolve as = solve' S 1.0\n where\n eps = 1e-09\n [a, b, c, d] = map fromIntegral as\n solve' player p\n | p <= eps = 0\n | player == S = p * a / b + solve' Z (p * (1 - a / b))\n | player == Z = solve' S (p * (1 - c / d))\n \n\nmain :: IO ()\nmain = reads >>= print . solve", "positive_code": [{"source_code": "main = interact $ show . getAnswer . map read . words\n where getAnswer [a, b, c, d] = (a * d) / (a * d + b * c - a * c)"}, {"source_code": "\nreadInts :: String -> [Double]\nreadInts str = map read (words str)\n\n\nmain :: IO ()\nmain = do\n [a,b,c,d] <- fmap readInts getLine\n --print $ (b*b/d)/(a*b*c+a*a*b-a*a*c)\n let p = a/b\n let _p = 1-p\n let _q = 1-c/d\n print $ p/(1-_p*_q)\n \n"}, {"source_code": "main=interact$show.f.map read.words\nf[a,b,c,d]=(a*d)/(a*d+b*c-a*c)"}, {"source_code": "main = do\n l <- getLine\n let a = (map read (words l)) :: [Double]\n let b = (a!!0 * a!!3 / (a!!0*a!!3 + a!!1*a!!2 - a!!0*a!!2)) :: Double\n putStrLn(show(b))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain = do\n\t[ a, b, c, d ] <- map read . words <$> getLine\n\tprintf \"%.8f\\n\" $ solve 0 ( a / b ) ( c / d )\n\nsolve :: Int -> Double -> Double -> Double\nsolve 100000 _ _ = 0\nsolve depth prob1 prob2 = ( ( 1 - prob1 ) * ( 1 - prob2 ) ) ^ depth * prob1 + ( solve ( depth + 1 ) prob1 prob2 )\n"}, {"source_code": "module Main where\n\nimport System.Environment\nimport System.Exit\n\nmain :: IO ()\nmain = getLine >>= print . solve . parseList\n\nparseList :: Read a => String -> [a]\nparseList = map read . words\n\nsolve :: [Double] -> Double\nsolve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-9)) probability\n where\n probability :: [Double]\n probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q\n\n -- The first is the winner\n p :: Double\n p = a / b\n\n -- No one is winner\n q :: Double\n q = (1 - p) * (1 - c / d)\n\nsolve _ = undefined\n"}, {"source_code": "module Main where\n\nimport System.Environment\nimport System.Exit\n\nmain :: IO ()\nmain = getLine >>= print . solve . parseList\n\nparseList :: Read a => String -> [a]\nparseList = map read . words\n\n-- solve :: [Double] -> Double\n-- solve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-9)) probability\n-- where\n-- probability :: [Double]\n-- probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q\n--\n-- -- The first is the winner\n-- p :: Double\n-- p = a / b\n--\n-- -- No one is winner\n-- q :: Double\n-- q = (1 - p) * (1 - c / d)\n--\n-- solve _ = undefined\n\nsolve :: [Double] -> Double\nsolve (a:b:c:d:_) = p / (1 - q)\n where\n -- The first is the winner\n p :: Double\n p = a / b\n\n -- No one is winner\n q :: Double\n q = (1 - p) * (1 - c / d)\n\n"}, {"source_code": "solve :: Double -> Double -> Double -> Double -> Double\nsolve a b c d =\n p1 * (sum $ takeWhile (> 10**(-6)) $ iterate (* k) 1)\n where\n p1 = a / b\n k = (1 - p1) * (1 - c / d)\n\nmain = do\n [a, b, c, d] <- (map read . words) `fmap` getLine\n print $ solve a b c d\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain = do\n\t[ a, b, c, d ] <- map read . words <$> getLine\n\tprintf \"%.7f\\n\" $ solve 0 ( a / b ) ( c / d )\n\nsolve :: Int -> Double -> Double -> Double\nsolve 1000 _ _ = 0\nsolve depth prob1 prob2 = ( ( 1 - prob1 ) * ( 1 - prob2 ) ) ^ depth * prob1 + ( solve ( depth + 1 ) prob1 prob2 )\n"}, {"source_code": "module Main where\n\nimport System.Environment\nimport System.Exit\n\nmain :: IO ()\nmain = getLine >>= print . solve . parseList\n\nparseList :: Read a => String -> [a]\nparseList = map read . words\n\nsolve :: [Double] -> Double\nsolve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-7)) probability\n where\n probability :: [Double]\n probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q\n\n -- The first is the winner\n p :: Double\n p = a / b\n\n -- No one is winner\n q :: Double\n q = (1 - p) * (1 - c / d)\n\nsolve _ = undefined\n"}, {"source_code": "module Main where\n\nimport System.Environment\nimport System.Exit\n\nmain :: IO ()\nmain = getLine >>= print . solve . parseList\n\nparseList :: Read a => String -> [a]\nparseList = map read . words\n\nsolve :: [Double] -> Double\nsolve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-6)) probability\n where\n probability :: [Double]\n probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q\n\n -- The first is the winner\n p :: Double\n p = a / b\n\n -- No one is winner\n q :: Double\n q = (1 - p) * (1 - c / d)\n\nsolve _ = undefined\n"}, {"source_code": "\nreadInts :: String -> [Double]\nreadInts str = map read (words str)\n\n\nmain :: IO ()\nmain = do\n [a,b,c,d] <- fmap readInts getLine\n print $ (b*b/d)/(a*b*c+a*a*b-a*a*c)\n"}, {"source_code": "main = do\n l <- getLine\n let a = (map read (words l)) :: [Double]\n let b = (a!!0 * a!!3 / (a!!1*a!!3 - a!!0*a!!2)) :: Double\n putStrLn(show(b))"}], "src_uid": "7b932b2d3ab65a353b18d81cf533a54e"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTArray, runSTUArray, STArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concat $ map (take m . unpack) ls :: Array (Int, Int) Bool\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\tif inside v && a ! v && not b\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\t\tv1 <- fill (x, y+1)\n\t\t\t\t\t\t\tv2 <- fill (x, y-1)\n\t\t\t\t\t\t\tv3 <- fill (x+1, y)\n\t\t\t\t\t\t\tv4 <- fill (x-1, y)\n\n\t\t\t\t\t\t\treturn $ v1 + v2 + v3 + v4 + cnt\n\t\t\t\t\t\telse return 0\n\t\t\t\twhere\n\t\t\t\t\tcheck v = if inside v && not (a ! v) then 1 else 0\n\t\t\t\t\tcnt = check (x,y+1) + check (x,y-1) + check (x+1,y) + check (x-1,y)\n\n\t\t\tlet set v@(x, y) s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tmapM_ (\\v -> set v s) $ adjacent v\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tlet set v s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tmapM_ (\\v -> set v s) $ adjacent v\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\tif inside v && a ! v && not b\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\t\tv1 <- fill (x, y+1)\n\t\t\t\t\t\t\tv2 <- fill (x, y-1)\n\t\t\t\t\t\t\tv3 <- fill (x+1, y)\n\t\t\t\t\t\t\tv4 <- fill (x-1, y)\n\n\t\t\t\t\t\t\treturn $ v1 + v2 + v3 + v4 + cnt\n\t\t\t\t\t\telse return 0\n\t\t\t\twhere\n\t\t\t\t\tcheck v = if inside v && not (a ! v) then 1 else 0\n\t\t\t\t\tcnt = check (x,y+1) + check (x,y-1) + check (x+1,y) + check (x-1,y)\n\n\t\t\tlet set v@(x, y) s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif inside v && a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tset (x+1, y) s\n\t\t\t\t\t\tset (x-1, y) s\n\t\t\t\t\t\tset (x, y+1) s\n\t\t\t\t\t\tset (x, y-1) s\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\tif inside v && a ! v && not b\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\t\tv1 <- fill (x, y+1)\n\t\t\t\t\t\t\tv2 <- fill (x, y-1)\n\t\t\t\t\t\t\tv3 <- fill (x+1, y)\n\t\t\t\t\t\t\tv4 <- fill (x-1, y)\n\n\t\t\t\t\t\t\treturn $ v1 + v2 + v3 + v4 + cnt\n\t\t\t\t\t\telse return 0\n\t\t\t\twhere\n\t\t\t\t\tcnt = length $ filter (not . (a !)) $ adjacent v\n\n\t\t\tlet set v@(x, y) s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif inside v && a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tset (x+1, y) s\n\t\t\t\t\t\tset (x-1, y) s\n\t\t\t\t\t\tset (x, y+1) s\n\t\t\t\t\t\tset (x, y-1) s\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\tif inside v && a ! v && not b\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\t\tv1 <- fill (x, y+1)\n\t\t\t\t\t\t\tv2 <- fill (x, y-1)\n\t\t\t\t\t\t\tv3 <- fill (x+1, y)\n\t\t\t\t\t\t\tv4 <- fill (x-1, y)\n\n\t\t\t\t\t\t\treturn $ v1 + v2 + v3 + v4 + cnt\n\t\t\t\t\t\telse return 0\n\t\t\t\twhere\n\t\t\t\t\tcheck v = if inside v && not (a ! v) then 1 else 0\n\t\t\t\t\tcnt = check (x,y+1) + check (x,y-1) + check (x+1,y) + check (x-1,y)\n\n\t\t\tlet set v@(x, y) s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif inside v && a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tset (x+1, y) s\n\t\t\t\t\t\tset (x-1, y) s\n\t\t\t\t\t\tset (x, y+1) s\n\t\t\t\t\t\tset (x, y-1) s\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\tsum <$> (forM (adjacent v) $ \\v ->\n\t\t\t\t\t\t\tif a ! v\n\t\t\t\t\t\t\t\tthen fill v\n\t\t\t\t\t\t\t\telse return 1)\n\t\t\t\t\telse return 0\n\n\t\t\tlet set v s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tmapM_ (\\v -> set v s) $ adjacent v\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport Data.STRef\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((arrayfy n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let paintings :: UArray (Int, Int) Int\n paintings = accumArray (+) 0 ((1, 1), (n, m)) [((i, j), length . filter (t !) $ around n m (i, j)) | i <- [1 .. n], j <- [1 .. m]]\n let ans = runSTUArray $ do\n f <- newArray ((1, 1), (n, m)) (0, 0) :: ST s (STArray s (Int, Int) (Int, Int))\n v <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n ans <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n let emptyCells = [(i, j) | i <- [1 .. n], j <- [1 .. m], not $ t ! (i, j)]\n let find w = do\n myF <- readArray f w\n if myF == w\n then\n return w\n else do\n myF' <- find myF\n writeArray f w myF'\n return myF'\n let join u' w' = do\n u <- find u'\n w <- find w'\n when (u /= w) $ do\n writeArray f u w\n vu <- readArray v u\n vw <- readArray v w\n writeArray v w $ vu + vw\n forM_ emptyCells $ \\w -> do\n writeArray f w w\n writeArray v w $ paintings ! w\n forM_ emptyCells $ \\w@(i, j) -> do\n let up = (i - 1, j)\n left = (i, j - 1)\n when (i > 1 && not (t ! up)) $ join w up\n when (j > 1 && not (t ! left)) $ join w left\n forM_ emptyCells $ \\w -> do\n myF <- find w\n myV <- readArray v myF\n writeArray ans w myV\n return ans\n BS.putStrLn . BS.unlines $ solve ans qs\n \n\narrayfy n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l] :: UArray (Int, Int) Bool\n\naround n m (x, y) = filter (\\(i, j) -> 0 < i && i <= n && 0 < j && j <= m) [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n\nsolve _ [] = []\nsolve ans (i : j : qs) = (BS.pack . show $ ans ! (i, j)) : solve ans qs\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTArray, STArray)\nimport Data.ByteString (getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concat $ map (take m . unpack) ls\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport Data.STRef\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((arrayfy n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let paintings :: UArray (Int, Int) Int\n paintings = accumArray (+) 0 ((1, 1), (n, m)) [((i, j), length . filter (t !) $ around n m (i, j)) | i <- [1 .. n], j <- [1 .. m]]\n let ans = runSTUArray $ do\n f <- newArray ((1, 1), (n, m)) (0, 0) :: ST s (STArray s (Int, Int) (Int, Int))\n v <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n ans <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n let emptyCells = [(i, j) | i <- [1 .. n], j <- [1 .. m], not $ t ! (i, j)]\n let find w = do\n myF <- readArray f w\n if myF == w\n then\n return w\n else do\n myF' <- find myF\n writeArray f w myF'\n return myF'\n let join u' w' = do\n u <- find u'\n w <- find w'\n when (u /= w) $ do\n writeArray f u w\n vu <- readArray v u\n vw <- readArray v w\n writeArray v w $ vu + vw\n forM_ emptyCells $ \\w -> do\n writeArray f w w\n writeArray v w $ paintings ! w\n forM_ emptyCells $ \\w@(i, j) -> do\n let up = (i - 1, j)\n left = (i, j - 1)\n when (i > 1 && not (t ! up)) $ join w up\n when (j > 1 && not (t ! left)) $ join w left\n forM_ emptyCells $ \\w -> do\n myF <- find w\n myV <- readArray v myF\n writeArray ans w myV\n return ans\n BS.putStrLn . BS.unlines $ solve ans qs\n \n\narrayfy n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l] :: UArray (Int, Int) Bool\n\naround n m (x, y) = filter (\\(i, j) -> 0 < i && i <= n && 0 < j && j <= m) [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n\nsolve _ [] = []\nsolve ans (i : j : qs) = (BS.pack . show $ ans ! (i, j)) : solve ans qs\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport Data.STRef\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((arrayfy n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let paintings :: UArray (Int, Int) Int\n paintings = accumArray (+) 0 ((1, 1), (n, m)) [((i, j), length . filter (t !) $ around n m (i, j)) | i <- [1 .. n], j <- [1 .. m]]\n let ans = runSTUArray $ do\n f <- newArray ((1, 1), (n, m)) (0, 0) :: ST s (STArray s (Int, Int) (Int, Int))\n v <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n ans <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n let emptyCells = [(i, j) | i <- [1 .. n], j <- [1 .. m], not $ t ! (i, j)]\n let find w = do\n myF <- readArray f w\n if myF == w\n then\n return w\n else do\n myF' <- find myF\n writeArray f w myF'\n return myF'\n let join u' w' = do\n u <- find u'\n w <- find w'\n when (u /= w) $ do\n writeArray f u w\n vu <- readArray v u\n vw <- readArray v w\n writeArray v w $ vu + vw\n forM_ emptyCells $ \\w -> do\n writeArray f w w\n writeArray v w $ paintings ! w\n forM_ emptyCells $ \\w@(i, j) -> do\n let up = (i - 1, j)\n left = (i, j - 1)\n when (i > 1 && not (t ! up)) $ join w up\n when (j > 1 && not (t ! left)) $ join w left\n forM_ emptyCells $ \\w -> do\n myF <- find w\n myV <- readArray v myF\n writeArray ans w myV\n return ans\n BS.putStrLn $ BS.unlines . map (BS.pack . show) $ solve ans qs\n \n\narrayfy n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l] :: UArray (Int, Int) Bool\n\naround n m (x, y) = filter (\\(i, j) -> 0 < i && i <= n && 0 < j && j <= m) [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n\nsolve _ [] = []\nsolve ans (i : j : qs) = ans ! (i, j) : solve ans qs\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, STArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concat $ map (take m . unpack) ls :: Array (Int, Int) Bool\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concat $ map (take m . unpack) ls :: Array (Int, Int) Bool\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport Data.STRef\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((arrayfy n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let paintings :: UArray (Int, Int) Int\n paintings = accumArray (+) 0 ((1, 1), (n, m)) [((i, j), length . filter (t !) $ around n m (i, j)) | i <- [1 .. n], j <- [1 .. m]]\n let ans = runSTUArray $ do\n f <- newArray ((1, 1), (n, m)) (0, 0) :: ST s (STArray s (Int, Int) (Int, Int))\n v <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n ans <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n let emptyCells = [(i, j) | i <- [1 .. n], j <- [1 .. m], not $ t ! (i, j)]\n let find w = do\n myF <- readArray f w\n if myF == w\n then\n return w\n else do\n myF' <- find myF\n writeArray f w myF'\n return myF'\n let join u' w' = do\n u <- find u'\n w <- find w'\n when (u /= w) $ do\n writeArray f u w\n vu <- readArray v u\n vw <- readArray v w\n writeArray v w $ vu + vw\n forM_ emptyCells $ \\w -> do\n writeArray f w w\n writeArray v w $ paintings ! w\n forM_ emptyCells $ \\w@(i, j) -> do\n let up = (i - 1, j)\n left = (i, j - 1)\n when (i > 1 && not (t ! up)) $ join w up\n when (j > 1 && not (t ! left)) $ join w left\n --sequence_ . map (join w) . filter (not . (t !)) $ around n m w\n forM_ emptyCells $ \\w -> do\n myF <- find w\n myV <- readArray v myF\n writeArray ans w myV\n return ans\n putStrLn $ concat . intersperse \"\\n\" . map show $ solve ans qs\n \n\narrayfy n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l] :: UArray (Int, Int) Bool\n\naround n m (x, y) = filter (\\(i, j) -> 0 < i && i <= n && 0 < j && j <= m) [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n\nsolve _ [] = []\nsolve ans (i : j : qs) = ans ! (i, j) : solve ans qs\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM, forM_, forM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTArray, runSTUArray, STArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concat $ map (take m . unpack) ls :: Array (Int, Int) Bool\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STArray s (Int, Int) Int)\n\n\t\t\tlet fill v = do \n\t\t\t\twriteArray bs v True\n\n\t\t\t\tss <- forM (adjacent v) $ \\v ->\n\t\t\t\t\tif a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\t\t\tif b\n\t\t\t\t\t\t\t\tthen return 0\n\t\t\t\t\t\t\t\telse fill v\n\t\t\t\t\t\telse return 1\n\n\t\t\t\treturn $ sum ss\n\n\t\t\tforM_ (filter (a !) ((,) <$> [1..n] <*> [1..m])) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\n\t\t\t\t\t\tlet set v = do\n\t\t\t\t\t\t\twriteArray ss v s\n\n\t\t\t\t\t\t\tforM_ (adjacent v) $ \\v -> do\n\t\t\t\t\t\t\t\tc <- readArray ss v\n\t\t\t\t\t\t\t\tif a ! v && c == 0\n\t\t\t\t\t\t\t\t\tthen set v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tset v\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\tif a ! v && not b\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\t\tv1 <- fill (x, y+1)\n\t\t\t\t\t\t\tv2 <- fill (x, y-1)\n\t\t\t\t\t\t\tv3 <- fill (x+1, y)\n\t\t\t\t\t\t\tv4 <- fill (x-1, y)\n\n\t\t\t\t\t\t\treturn $ v1 + v2 + v3 + v4 + cnt\n\t\t\t\t\t\telse return 0\n\t\t\t\twhere\n\t\t\t\t\t-- check v = if inside v && not (a ! v) then 1 else 0\n\t\t\t\t\t-- cnt = check (x,y+1) + check (x,y-1) + check (x+1,y) + check (x-1,y)\n\t\t\t\t\tcnt = length $ filter (not . (a !)) $ adjacent v\n\n\t\t\tlet set v s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tmapM_ (\\v -> set v s) $ adjacent v\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\n\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tls <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tss = runSTUArray $ do\n\t\t\tbs <- newArray bounds False :: ST s (STUArray s (Int, Int) Bool)\n\t\t\tss <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n\t\t\tlet fill v@(x, y) = do \n\t\t\t\t\tb <- readArray bs v\n\t\t\t\t\tif inside v && a ! v && not b\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\twriteArray bs v True\n\n\t\t\t\t\t\t\tv1 <- fill (x, y+1)\n\t\t\t\t\t\t\tv2 <- fill (x, y-1)\n\t\t\t\t\t\t\tv3 <- fill (x+1, y)\n\t\t\t\t\t\t\tv4 <- fill (x-1, y)\n\n\t\t\t\t\t\t\treturn $ v1 + v2 + v3 + v4 + cnt\n\t\t\t\t\t\telse return 0\n\t\t\t\twhere\n\t\t\t\t\tcheck v = if inside v && not (a ! v) then 1 else 0\n\t\t\t\t\tcnt = check (x,y+1) + check (x,y-1) + check (x+1,y) + check (x-1,y)\n\n\t\t\tlet set v@(x, y) s = do\n\t\t\t\tc <- readArray ss v\n\t\t\t\tif inside v && a ! v && c == 0\n\t\t\t\t\tthen do\n\t\t\t\t\t\twriteArray ss v s\n\t\t\t\t\t\tmapM_ (\\v -> set v s) [(x+1,y), (x-1,y), (x,y+1), (x, y-1)]\n\t\t\t\t\t\t--set (x+1, y) s\n\t\t\t\t\t\t--set (x-1, y) s\n\t\t\t\t\t\t--set (x, y+1) s\n\t\t\t\t\t\t--set (x, y-1) s\n\t\t\t\t\telse return ()\n\n\n\t\t\tforM_ (filter (a !) [(x, y) | x <- [1..n], y <- [1..m]]) $ \\v -> do\n\t\t\t\tb <- readArray bs v\n\t\t\t\tif not b\n\t\t\t\t\tthen do\n\t\t\t\t\t\ts <- fill v\n\t\t\t\t\t\tset v s\n\t\t\t\t\telse return ()\n\n\t\t\treturn ss\n\n\tputStrLn $ unlines $ map (show . (ss !)) ps\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tc <- getContents\n\n\tlet\n\t\tcont = lines c\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\t-- mapM_ putStrLn $ map (show . ans) ps\n\tprint [n, m, k]\n\tprint a\n\tprint ps\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef\nimport Data.ByteString (getLine)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Graph (buildG, components)\nimport Data.Maybe (fromJust)\nimport Data.Tree (rootLabel, flatten)\nimport Prelude hiding (getLine, lines, words)\n\nreadInt' = fst . fromJust .readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tlines <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack lines :: UArray (Int, Int) Bool\n\n\t\tadjacent v = [u | d <- ds, let u = v +. d, inside u]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\t\t\t\tds = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\t\t\t\t(x1, y1) +. (x2, y2) = (x1 + x2, y1 + y2)\n\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\twhere\n\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\t\tcomps = runSTUArray $ do\n\t\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\t\tcc <- newSTRef 0\n\n\t\t\t\tlet search v = do\n\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\t\tlet fill v = do \n\t\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\t\tfill v\n\t\t\t\t\t\telse return()\n\n\t\t\t\tmapM_ search space\n\n\t\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 100000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\tans v = sums ! (comps ! v)\n\n\tputStr $ unlines $ map show $ map ans ps\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef\nimport Data.ByteString.Char8 (readInt, lines, words, getLine, unpack)\nimport Data.Graph (buildG, components)\nimport Data.Maybe (fromJust)\nimport Data.Tree (rootLabel, flatten)\nimport Prelude hiding (getLine, lines, words)\n\nreadInt' = fst . fromJust .readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tlines <- replicateM n getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . words) <$> replicateM k getLine\n\n\tlet\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack lines :: UArray (Int, Int) Bool\n\n\t\tadjacent v = [u | d <- ds, let u = v +. d, inside u]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\t\t\t\tds = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\t\t\t\t(x1, y1) +. (x2, y2) = (x1 + x2, y1 + y2)\n\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\twhere\n\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\t\tcomps = runSTUArray $ do\n\t\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\t\tcc <- newSTRef 0\n\n\t\t\t\tlet search v = do\n\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\t\tlet fill v = do \n\t\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\t\tfill v\n\t\t\t\t\t\telse return()\n\n\t\t\t\tmapM_ search space\n\n\t\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 50000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\tans v = sums ! (comps ! v)\n\n\tputStr $ unlines $ map show $ map ans ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport qualified Data.ByteString.Char8 as BS -- (readInt, words, getLine, unpack)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words)\n\nreadInt' = fst . fromJust . BS.readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . BS.words <$> BS.getLine\n\tlines <- replicateM n BS.getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . BS.words) <$> replicateM k BS.getLine\n\n\tlet\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap BS.unpack lines :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tmapM_ putStrLn $ map (show . ans) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString.Char8 (readInt, words, getLine, unpack, getContents, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . words <$> getLine\n\tcont <- lines <$> getContents\n\n\tlet\n\t\tls = take n cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop n cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tmapM_ putStrLn $ map (show . ans) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString.Char8 (readInt, words, getLine, unpack, getContents, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tcont <- lines <$> getContents\n\n\tlet\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tmapM_ putStrLn $ map (show . ans) ps\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\n\nimport qualified Data.ByteString.Char8 as BS -- (readInt, words, getLine, unpack)\nimport Data.Graph (buildG, components)\nimport Data.Maybe (fromJust)\nimport Data.Tree (rootLabel, flatten)\nimport Prelude hiding (lines, words)\n\nreadInt' = fst . fromJust . BS.readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . BS.words <$> BS.getLine\n\tlines <- replicateM n BS.getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . BS.words) <$> replicateM k BS.getLine\n\n\tlet\n\t\tbounds = ((1, 1), (n, m))\n\t\ta = listArray bounds $ map (== '.') $ concatMap BS.unpack lines :: UArray (Int, Int) Bool\n\n\t\tadjacent v = [u | d <- ds, let u = v +. d, inside u]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\t\t\t\tds = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\t\t\t\t(x1, y1) +. (x2, y2) = (x1 + x2, y1 + y2)\n\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\twhere\n\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\t\tcomps = runSTUArray $ do\n\t\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\t\tcc <- newSTRef 0\n\n\t\t\t\tlet search v = do\n\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\t\tlet fill v = do \n\t\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\t\tfill v\n\t\t\t\t\t\telse return()\n\n\t\t\t\tmapM_ search space\n\n\t\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 100000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\tans v = sums ! (comps ! v)\n\n\tputStr $ unlines $ map show $ map ans ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tc <- getContents\n\n\tlet\n\t\tcont = lines c\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\t-- mapM_ putStrLn $ map (show . ans) ps\n\tputStrLn (show n ++ \" \" ++ show m ++ show k)\n\tprint a\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tc <- getContents\n\n\tlet\n\t\tcont = lines c\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\t-- mapM_ putStrLn $ map (show . ans) ps\n\tputStrLn $ unpack c\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tc <- getContents\n\n\tlet\n\t\tcont = lines c\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap (take m . unpack) ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tprint [n, m, k]\n\tprint a\n\tprint ps\n\t-- mapM_ putStrLn $ map (show . ans) ps\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport Data.STRef\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((arrayfy n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let paintings :: UArray (Int, Int) Int\n paintings = accumArray (+) 0 ((1, 1), (n, m)) [((i, j), length . filter (t !) $ around n m (i, j)) | i <- [1 .. n], j <- [1 .. m]]\n let ans = runSTUArray $ do\n freeSlot <- newSTRef (1 :: Int)\n mySlot <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n visited <- newArray ((1, 1), (n, m)) False :: ST s (STUArray s (Int, Int) Bool)\n ans <- newArray (1, n * m) 0 :: ST s (STUArray s Int Int)\n let dfs w = do\n v <- readArray visited w\n when (not v) $ do\n s <- readSTRef freeSlot\n a <- readArray ans s\n writeArray mySlot w s\n writeArray visited w True\n writeArray ans s $ a + paintings ! w\n sequence_ . map dfs . filter (not . (t !)) $ around n m w\n forM_ [(i, j) | i <- [1 .. n], j <- [1 .. m], not (t ! (i, j))] $ \\w -> do\n v <- readArray visited w\n when (not v) $ do\n dfs w\n modifySTRef freeSlot (+ 1)\n ans' <- newArray ((1, 1), (n, m)) (0 :: Int)\n forM_ [(i, j) | i <- [1 .. n], j <- [1 .. m], not (t ! (i, j))] $ \\w -> do\n s <- readArray mySlot w\n a <- readArray ans s\n writeArray ans' w a\n return ans'\n --putStrLn $ concat . intersperse \"\\n\" . map show $ solve ans qs\n let ans' = solve ans qs\n when (head ans' /= 3992) $ putStrLn $ concat . intersperse \"\\n\" . map show $ solve ans qs\n \n\narrayfy n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l] :: UArray (Int, Int) Bool\n\naround n m (x, y) = filter (\\(i, j) -> 0 < i && i <= n && 0 < j && j <= m) [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n\nsolve _ [] = []\nsolve ans (i : j : qs) = ans ! (i, j) : solve ans qs\n"}, {"source_code": "import Control.Monad.RWS.Lazy\n\nmain = print \"Hello World\""}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as Set\n\ntype Cell = (Int, Int)\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((gridToArray n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let emptyCells = [(i, j) | i <- [1 .. n], j <- [1 .. m], not $ t ! (i, j)]\n let paintings :: UArray Cell Int\n paintings = array ((1, 1), (n, m)) [(w, length . filter (t !) $ around w) | w <- emptyCells]\n let rooms = filter (not . null) . fst $ runState (sequence . map state $\n [\\v -> if Set.member w v then ([], v) else let v' = dfs t Set.empty w in (Set.toList $ v', Set.union v v') | w <- emptyCells]\n ) Set.empty\n let ans :: UArray Cell Int\n ans = array ((1, 1), (n, m)) $ do\n r <- rooms\n let s = sum . map (paintings !) $ r\n zip r $ repeat s\n BS.putStrLn . BS.unlines $ solve ans qs\n\ngridToArray :: Int -> Int -> [BS.ByteString] -> UArray Cell Bool\ngridToArray n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l]\n\naround :: Cell -> [Cell]\naround (i, j) = [(i - 1, j), (i + 1, j), (i, j + 1), (i, j + 1)]\n\ndfs :: UArray Cell Bool -> Set Cell -> Cell -> Set Cell\ndfs t visited w\n | Set.member w visited = visited\n | otherwise = foldl (dfs t) (Set.insert w visited) . filter (not . (t !)) $ around w\n\nsolve :: UArray Cell Int -> [Int] -> [BS.ByteString]\nsolve _ [] = []\nsolve ans (i : j : qs) = (BS.pack . show $ ans ! (i, j)) : solve ans qs\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport Data.STRef\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (strN : strM : _ : rest) <- BS.words <$> BS.getContents\n let (Just (n, _), Just (m, _)) = (BS.readInt strN, BS.readInt strM)\n let (t, qs) = ((arrayfy n m) *** (map fst . mapMaybe BS.readInt)) $ splitAt n rest\n let paintings :: UArray (Int, Int) Int\n paintings = accumArray (+) 0 ((1, 1), (n, m)) [((i, j), length . filter (t !) $ around n m (i, j)) | i <- [1 .. n], j <- [1 .. m]]\n let ans = runSTUArray $ do\n freeSlot <- newSTRef (1 :: Int)\n mySlot <- newArray ((1, 1), (n, m)) 0 :: ST s (STUArray s (Int, Int) Int)\n visited <- newArray ((1, 1), (n, m)) False :: ST s (STUArray s (Int, Int) Bool)\n ans <- newArray (1, n * m) 0 :: ST s (STUArray s Int Int)\n let dfs w = do\n v <- readArray visited w\n when (not v) $ do\n s <- readSTRef freeSlot\n writeArray mySlot w s\n writeArray visited w True\n sequence_ . map dfs . filter (not . (t !)) $ around n m w\n forM_ [(i, j) | i <- [1 .. n], j <- [1 .. m], not (t ! (i, j))] $ \\w -> do\n v <- readArray visited w\n when (not v) $ do\n dfs w\n modifySTRef freeSlot (+ 1)\n s <- readArray mySlot w\n a <- readArray ans s\n writeArray ans s $ a + paintings ! w\n ans' <- newArray ((1, 1), (n, m)) (0 :: Int)\n forM_ [(i, j) | i <- [1 .. n], j <- [1 .. m], not (t ! (i, j))] $ \\w -> do\n s <- readArray mySlot w\n a <- readArray ans s\n writeArray ans' w a\n return ans'\n --putStrLn $ concat . intersperse \"\\n\" . map show $ solve ans qs\n let ans' = solve ans qs\n when (head ans' /= 3992) $ putStrLn $ concat . intersperse \"\\n\" . map show $ solve ans qs\n \n\narrayfy n m ls = array ((1, 1), (n, m)) [((i, j), c == '*') | (i, l) <- zip [1 ..] ls, (j, c) <- zip [1 ..] $ BS.unpack l] :: UArray (Int, Int) Bool\n\naround n m (x, y) = filter (\\(i, j) -> 0 < i && i <= n && 0 < j && j <= m) [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n\nsolve _ [] = []\nsolve ans (i : j : qs) = ans ! (i, j) : solve ans qs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport qualified Data.ByteString.Char8 as BS -- (readInt, words, getLine, unpack)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words)\n\nreadInt' = fst . fromJust . BS.readInt\n\nmain = do\n\t[n, m, k] <- map readInt' . BS.words <$> BS.getLine\n\tlines <- replicateM n BS.getLine\n\tps <- map ((\\[a, b] -> (a, b)) . map readInt' . BS.words) . BS.lines <$> BS.getContents\n\n\tlet\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap BS.unpack lines :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tmapM_ putStrLn $ map (show . ans) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tc <- getContents\n\n\tlet\n\t\tcont = lines c\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tprint [n, m, k]\n\tprint a\n\tprint ps\n\t-- mapM_ putStrLn $ map (show . ans) ps\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.IArray ((!), listArray, accumArray)\nimport Data.Array.MArray.Safe (newArray)\nimport Data.Array.ST.Safe (STUArray, runSTUArray)\nimport Data.Array.MArray.Safe (readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.STRef (newSTRef, readSTRef, modifySTRef')\nimport Data.ByteString (getContents)\nimport Data.ByteString.Char8 (readInt, words, unpack, lines)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tcont <- lines <$> getContents\n\n\tlet\n\t\t[n, m, k] = map readInt' . words $ head cont\n\t\tls = take n $ drop 1 cont\n\t\tps = map ((\\[a, b] -> (a, b)) . map readInt' . words) $ drop (n + 1) cont\n\n\t\tbounds = ((1, 1), (n, m))\n\t\tspace = [(x, y) | x <- [1..n], y <- [1..m]]\n\n\t\ta = listArray bounds $ map (== '.') $ concatMap unpack ls :: UArray (Int, Int) Bool\n\n\t\tadjacent (x, y) = filter inside [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\t\t\twhere\n\t\t\t\tinside (x, y) = 1 <= x && x <= n && 1 <= y && y <= m\n\n\t\tcomps = runSTUArray $ do\n\t\t\tcs <- newArray bounds (0 :: Int)\n\t\t\tcc <- newSTRef 0\n\n\t\t\tlet search v = do\n\t\t\t\tc <- readArray cs v\n\t\t\t\tif c == 0 && a ! v\n\t\t\t\t\tthen do\n\t\t\t\t\t\tmodifySTRef' cc (+1)\n\t\t\t\t\t\tcc' <- readSTRef cc\n\n\t\t\t\t\t\tlet fill !v = do \n\t\t\t\t\t\t\tc <- readArray cs v\n\t\t\t\t\t\t\tif c == 0\n\t\t\t\t\t\t\t\tthen do\n\t\t\t\t\t\t\t\t\twriteArray cs v cc'\n\t\t\t\t\t\t\t\t\tmapM_ fill $ filter (a !) $ adjacent v\n\t\t\t\t\t\t\t\telse return ()\n\n\t\t\t\t\t\tfill v\n\t\t\t\t\telse return()\n\n\t\t\tmapM_ search space\n\n\t\t\treturn cs\n\n\t\tsums = accumArray (+) 0 (0, 60000) $ map look space :: UArray Int Int\n\t\t\twhere\n\t\t\t\tlook v = (comps ! v, pictures ! v)\n\n\t\t\t\tpictures = listArray bounds $ map count space :: UArray (Int, Int) Int\n\t\t\t\t\twhere\n\t\t\t\t\t\tcount = length . filter (not . (a !)) . adjacent\n\n\n\t\tans v = sums ! (comps ! v)\n\n\tmapM_ putStrLn $ map (show . ans) ps\n"}], "src_uid": "cfdcfe449868ed50516f0895bf6a66e1"} {"source_code": "import Data.List\nimport Data.Array\n\nf::Char->[Char]->[Char]\nf c []=[c]\nf c (x:xs) = if x==c then xs else (c:x:xs)\n\nans xs= if foldr f [] xs==[] then \"Yes\" else \"No\"\n\nmain = do\n m<-getLine\n putStrLn.ans $ m\n ", "positive_code": [{"source_code": "solve = null . foldl f []\n where\n f [] x = [x]\n f (y:ys) x = if x == y then ys else x:y:ys\n\nmain = putStrLn . (\\y -> if y then \"Yes\" else \"No\") . solve =<< getLine\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n s <- getLine\n putStrLn $ if solve s then \"Yes\" else \"No\"\n\nsolve :: String -> Bool\nsolve s = null (go s [])\n where\n go [] st = st\n go (ch:s) [] = go s [ch]\n go (ch:s) (ch':l) | ch == ch' = go s l\n | otherwise = go s (ch:ch':l)\n"}, {"source_code": "\nsolve :: String -> Bool\nsolve s = solve' \"\" s\n where\n solve' \"\" \"\" = True\n solve' \"\" (b:bs) = solve' [b] bs\n solve' _ \"\" = False\n solve' (a:as) (b:bs)\n | a == b = solve' as bs\n | otherwise = solve' (b:a:as) bs\n\nprint' :: Bool -> IO ()\nprint' True = putStrLn \"YES\"\nprint' False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = getLine >>= print' . solve\n"}, {"source_code": "main=getLine>>=putStrLn.f[]\nf ('+':xs) ('+':ys) = f xs ys\nf ('-':xs) ('+':ys) = f ('+':'-':xs) ys\nf ('+':xs) ('-':ys) = f ('-':'+':xs) ys\nf ('-':xs) ('-':ys) = f xs ys\nf [] (y:ys) = f [y] ys\nf [] [] = \"Yes\"\nf (_:_) [] = \"No\""}, {"source_code": "solve xs = null $ foldl proc [] xs\n where\n proc [] x = [x]\n proc (y:ys) x = if x == y then ys else x:y:ys\n\n\nmain = putStrLn . (\\res -> if res then \"Yes\" else \"No\") . solve =<< getLine\n"}], "negative_code": [{"source_code": "import Data.List\n\nans (x:[]) = \"No\"\nans (x:y:[])=if x==y then \"Yes\" else \"No\"\nans (x:y:z:xs)=if x==y then ans (z:xs) else if y==z then ans (x:xs) else \"No\"\n\nmain = do\n m<-getLine\n putStrLn.ans $ m\n "}, {"source_code": "import Data.List\n\nans (x:[]) = \"No\"\nans (x:y:[])=if x==y then \"Yes\" else \"No\"\nans (x:y:z:xs)=if y==z then ans (x:xs) else \"No\"\n\nmain = do\n m<-getLine\n putStrLn.ans $ m\n "}, {"source_code": "import Data.List\n\nans (x:[]) = \"No\"\nans (x:y:[])=if x==y then \"Yes\" else \"No\"\nans (x:y:z:xs)=if y==z then ans (x:xs) else \"No\"\n\nmain = do\n m<-getLine\n putStrLn.ans $ words m\n "}], "src_uid": "89b4a7b4a6160ce784c588409b6ce935"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport Control.Monad.ST.Lazy\nimport Data.Semigroup\n\n\nsoln :: Int -> Int -> [(Int, Int)] -> [Int]\nsoln n m ops = runST $ do\n rowArr <- strictToLazyST $ newArray (1, n) False\n :: ST s (STUArray s Int Bool)\n colArr <- strictToLazyST $ newArray (1, m) False\n :: ST s (STUArray s Int Bool)\n cleanRows <- strictToLazyST $ newSTRef n\n cleanCols <- strictToLazyST $ newSTRef m\n forM (reverse ops) $ \\(r, c) -> strictToLazyST $ do\n ur <- readArray rowArr r\n uc <- readArray colArr c\n writeArray rowArr r True\n writeArray colArr c True\n fromRow <- if ur\n then pure 0\n else do\n modifySTRef' cleanRows (subtract 1)\n readSTRef cleanCols\n fromCol <- if uc\n then pure 0\n else do\n modifySTRef' cleanCols (subtract 1)\n readSTRef cleanRows\n pure $ fromRow + fromCol\n\np :: Int\np = 998244353\n\nnewtype ModP = ModP { unModP :: Int }\ninstance Semigroup ModP where\n ModP x <> ModP y = ModP (x * y `rem` p)\n stimes = stimesMonoid\ninstance Monoid ModP where\n mempty = ModP 1\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n m <- getInt\n k <- getInt\n q <- getInt\n acts <- replicateM q $ liftM2 (,) getInt getInt\n let\n nvs = length $ filter (/= 0) $ soln n m acts\n ans = unModP $ stimes nvs $ ModP k\n pure $ putInts [ans]\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Set as S\r\n\r\nmm :: Int\r\nmm = 998244353\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, m, k, q] <- readInts\r\n xys <- replicateM q readInts\r\n let f (!xs, !ys, !acc) ~[x, y] = (S.insert x xs, S.insert y ys, acc') where\r\n acc' = if (x `S.notMember` xs && S.size ys < m) || (y `S.notMember` ys && S.size xs < n)\r\n then acc * k `mod` mm\r\n else acc\r\n (_, _, ans) = foldl' f (S.empty, S.empty, 1) $ reverse xys\r\n print ans\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Set as S\r\n\r\ndata V2 = V2 !Int !Int deriving (Eq, Ord, Show)\r\n\r\nmm :: Int\r\nmm = 998244353\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, m, k, q] <- readInts\r\n xys <- reverse <$> replicateM q readInts\r\n let f (!xs, !ys, !acc) ~[x, y] = (xs', ys', acc') where\r\n acc' = if (x `S.notMember` xs && S.size ys < m) || (y `S.notMember` ys && S.size xs < n)\r\n then acc * k `mod` mm\r\n else acc\r\n xs' = S.insert x xs\r\n ys' = S.insert y ys\r\n (_, _, ans) = foldl' f (S.empty, S.empty, 1) xys\r\n print ans\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Set as S\r\n\r\ndata V2 = V2 !Int !Int deriving (Eq, Ord, Show)\r\n\r\nmm :: Int\r\nmm = 998244353\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, m, k, q] <- readInts\r\n xys <- reverse <$> replicateM q readInts\r\n let f (!xys, !xs, !ys, !acc) ~[x, y] = (xys', xs', ys', acc') where\r\n acc' = if S.member (V2 x y) xys || S.size xs == n || S.size ys == m\r\n then acc\r\n else acc * k `mod` mm\r\n xys' = S.insert (V2 x y) xys\r\n xs' = S.insert x xs\r\n ys' = S.insert y ys\r\n (_, _, _, ans) = foldl' f (S.empty, S.empty, S.empty, 1) xys\r\n print ans\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "src_uid": "623a373709e4c4223fbbb9a320f307b1"} {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>>\r\n chunksOf 2 >>>\r\n map (tail >>> head >>> words >>> map read >>> solve >>> show) >>> unlines\r\n where\r\n chunksOf k [] = []\r\n chunksOf k xs =\r\n let (g, gs) = splitAt k xs\r\n in g : chunksOf k gs\r\n\r\nsolve :: [Int] -> Int\r\nsolve (x:y:z:xs)\r\n | x /= y && x == z = 2\r\n | x /= y && y == z = 1\r\n | x /= z = 3\r\n | otherwise = head [i | (v, i) <- zip xs [4 ..], v /= x]\r\n", "positive_code": [{"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let\r\n b = dropWhile (==head a) a\r\n c = takeWhile (==head b) b\r\n nb = n - length b\r\n nc = length c\r\n print $ if nc == 1 then nb + 1 else nb\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfinddiff :: [Int] -> Int\nfinddiff lst =\n if (== 1) $ length $ head grouped \n then head $ head grouped\n else head $ last grouped\n where\n grouped = group $ sort lst\n\nsolve str =\n (1 +) $ fromJust $ (`elemIndex` intList) $ finddiff intList\n where intList = map read $ words str\n\nmain = do\n n <- read <$> getLine\n replicateM_ n (getLine >> solve <$> getLine >>= print)\n"}, {"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\tlet loop t = if t==0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Int\r\n\t\tl <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n\t\tlet a \r\n\t\t\t| l!!0 == l!!1 = l !! 0\r\n\t\t\t| l!!0 == l!!2 = l !! 0\r\n\t\t\t| l!!1 == l!!2 = l !! 1\r\n\t\tprint $ [i+1 | (i, x) <- zip [0..] l, x /= a] !! 0 \r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nimport Control.Monad (replicateM_)\nmain :: IO ()\nmain = do\n i <- read @Int <$> getLine \n replicateM_ i solve\n\nsolve :: IO ()\nsolve = do\n i <- read @Int <$> getLine\n xs <- (read @Int <$>) . words <$> getLine\n print $ solveIter Nothing Nothing (zip [1..] xs)\n\nsolveIter :: Maybe (Int, Int) -> Maybe (Int, Int) -> [(Int, Int)] -> Int\nsolveIter Nothing Nothing (x@(i, v):xs) = solveIter (Just x) Nothing xs\n\nsolveIter (Just y@(iy, vy)) Nothing (x@(ix, vx):xs)\n | vx == vy = fst . head . dropWhile ((== vx) . snd) $ xs\n | otherwise = solveIter (Just y) (Just x) xs\n\nsolveIter (Just y@(iy, vy)) (Just (iz, vz)) ((x@(ix, vx):xs))\n | vx == vy = iz\n | otherwise = iy\n\nsolveIter a b c = error $ show a ++ show b ++ show c\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nmodule Main where\n\nimport System.IO\nimport Data.Traversable\nimport Data.Foldable\nimport Data.Maybe\nimport Data.List\nimport Data.Monoid\nimport Data.Semigroup\n\nmain :: IO ()\nmain = do\n contents <- getContents\n let inputs :: [[Int]]\n inputs = map (map read . words) . filterEvens . tail . lines $ contents\n traverse_ (print . f) inputs\n\nf :: [Int] -> Int\nf (a:b:c:rest) = case commonElement (a, b, c) of\n Left n -> n\n Right n -> (+4) . fromMaybe (error \"no spy detected\") $ findIndex (/= n) rest\nf _ = error \"input less than 3 elements\"\n\ncommonElement :: (Int, Int, Int) -> Either Int Int\ncommonElement (a, b, c)\n | a == b && b == c = Right a\n | a == b = Left 3\n | b == c = Left 1\n | a == c = Left 2\n\nfilterEvens :: [a] -> [a]\nfilterEvens (a : b : rest) = b : filterEvens rest\nfilterEvens _ = []\n"}, {"source_code": "import Control.Monad\nimport Data.List (sort, group, elemIndex)\nimport Data.Maybe\n\nreadInts str = map (read :: String -> Int) (words str)\n\nsolve = do\n n <- readLn :: IO Int\n input <- getLine\n\n let a = map (read :: String -> Int) (words input)\n let x = head $ head $ filter (\\x -> length x == 1) (group $ sort a)\n\n let ans = (fromJust $ elemIndex x a) + 1\n\n print ans\n\n\nmain = do\n t <- readLn :: IO Int\n\n replicateM_ t solve\n"}, {"source_code": "import Control.Monad\nimport Data.List (sort, group, elemIndex)\nimport Data.Maybe\n\nreadInts str = map (read :: String -> Int) (words str)\n\nsolve = do\n n <- readLn :: IO Int\n input <- getLine\n\n let a = map (read :: String -> Int) (words input)\n let x = head $ head $ filter (\\x -> length x == 1) (group $ sort a)\n\n let ans = fromJust $ elemIndex x a\n\n print (ans + 1)\n\n\nmain = do\n t <- readLn :: IO Int\n\n replicateM_ t solve\n"}, {"source_code": "module Main where\r\n import Data.List\r\n \r\n solve :: IO ()\r\n solve = do\r\n n <- getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Integer) $ words s\r\n b = sort a\r\n print $ head [i + 1 | i <- [0..(read n :: Int) - 1], a !! i /= b !! 1]\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter x = do\r\n solve\r\n iter $ x - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}], "negative_code": [{"source_code": "{-# LANGUAGE BlockArguments #-}\n\nmodule Main where\n\nimport System.IO\nimport Data.Traversable\nimport Data.Foldable\nimport Data.Maybe\nimport Data.List\nimport Data.Monoid\nimport Data.Semigroup\n\nmain :: IO ()\nmain = do\n contents <- getContents\n let inputs :: [[Int]]\n inputs = map (map read . words) . filterEvens . tail . lines $ contents\n print inputs\n traverse_ (print . f) inputs\n\nf :: [Int] -> Int\nf (a:b:c:rest) = case commonElement (a, b, c) of\n Left n -> n\n Right n -> (+4) . fromMaybe (error \"no spy detected\") $ findIndex (/= n) rest\nf _ = error \"input less than 3 elements\"\n\ncommonElement :: (Int, Int, Int) -> Either Int Int\ncommonElement (a, b, c)\n | a == b && b == c = Right a\n | a == b = Left 3\n | b == c = Left 1\n | a == c = Left 2\n\nfilterEvens :: [a] -> [a]\nfilterEvens (a : b : rest) = b : filterEvens rest\nfilterEvens _ = []\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nmodule Main where\n\nimport System.IO\nimport Data.Traversable\nimport Data.Foldable\nimport Data.Maybe\nimport Data.List\nimport Data.Monoid\nimport Data.Semigroup\n\nmain :: IO ()\nmain = do\n contents <- getContents\n let inputs :: [[Int]]\n inputs = map (map read . words) . filterEvens . tail . lines $ contents\n traverse_ (print . f) inputs\n\nf :: [Int] -> Int\nf (a:b:c:rest) = case commonElement (a, b, c) of\n Left n -> n\n Right n -> fromMaybe (error \"no spy detected\") $ find (== n) rest\nf _ = error \"input less than 3 elements\"\n\ncommonElement :: (Int, Int, Int) -> Either Int Int\ncommonElement (a, b, c)\n | a == b && b == c = Right a\n | a == b = Left c\n | b == c = Left a\n | a == c = Left b\n\nfilterEvens :: [a] -> [a]\nfilterEvens (a : b : rest) = b : filterEvens rest\nfilterEvens _ = []\n"}, {"source_code": "module Main where\r\n import Data.List\r\n \r\n solve :: IO ()\r\n solve = do\r\n n <- getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Integer) $ words s\r\n b = sort a\r\n print $ length [i + 1 | i <- [0..(read n :: Int) - 1], a !! i /= b !! 1]\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter x = do\r\n solve\r\n iter $ x - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}], "src_uid": "224a0b09547ec1441474efbd8e06353b"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\ntype IntMod = Int64\n\ninfixl 6 +%\n\nmodulus :: IntMod\nmodulus = 1000000007\n\n(+%) :: IntMod -> IntMod -> IntMod\nx +% y = case x + y of xy -> if xy < modulus then xy else xy - modulus\n{-# INLINE (+%) #-}\n\nmain :: IO ()\nmain = do\n [_,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show $ solve k xs\n\nlim :: Int\nlim = 100000\n\nsolve :: Int -> [Int] -> [IntMod]\nsolve k xs = map (`mod` modulus) $ go xs\n where\n go (a:b:rest) = query a b : go rest\n go _ = []\n query a b\n | a do\n if k<=i then do\n (+%) <$> unsafeRead dp (i-1) <*> unsafeRead dp (i-k) >>= unsafeWrite dp i\n else do\n unsafeRead dp (i-1) >>= unsafeWrite dp i\n return dp", "positive_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nparse s = (k,pairs xs) where\n (k:xs) = map readI $ tail $ B.words s\n pairs (a:b:xs) = (a,b) : pairs xs\n pairs [] = []\nsolve k = map (uncurry go) where\n go a b = (pr!b - pr!(a-1)) `mod` m\n r = 1 : zipWith (+!) r (replicate (k-1) 0 ++ r)\n pr = listArray (0,100000) $ scanl1 (+!) r\nmain = mapM_ print . uncurry solve . parse =<< B.getContents\nm = 10^9 + 7 :: Int\na +! b | s > m = s - m | otherwise = s where s = a + b\nreadI b = i where Just (i,_) = B.readInt b\n"}], "negative_code": [{"source_code": "import Data.Array.ST.Safe\nimport Control.Monad.ST\nimport Control.Monad\nmain = do\n [t,k] <- map read . words <$> getLine\n replicateM_ t $ do\n [a,b] <- map read . words <$> getLine\n print (solve k a b)\nm = 10^9 + 7\nsolve k a b = runST $ do\n dp <- newArray (0,b) 0 :: ST s (STUArray s Int Int)\n writeArray dp 0 1\n forM_ [1..b] $ \\i -> do\n white <- if i >= k then readArray dp (i-k) else pure 0\n red <- readArray dp (i-1)\n writeArray dp i (red + white)\n sum <$> mapM (readArray dp) [a..b]\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nparse s = (k,pairs xs) where\n (k:xs) = map readI $ tail $ B.words s\n pairs (a:b:xs) = (a,b) : pairs xs\n pairs [] = []\nsolve k = map (uncurry go) where\n go a b = pr!b - pr!(a-1)\n r = 1 : zipWith (+!) r (replicate (k-1) 0 ++ r)\n pr = listArray (0,100000) $ scanl1 (+) r\nmain = mapM_ print . uncurry solve . parse =<< B.getContents\nm = 10^9 + 7 :: Int\na +! b | s > m = s - m | otherwise = s where s = a + b\nreadI b = i where Just (i,_) = B.readInt b\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nparse s = (k,pairs xs) where\n (k:xs) = map readI $ tail $ B.words s\n pairs (a:b:xs) = (a,b) : pairs xs\n pairs [] = []\nsolve k = map (uncurry go) where\n go a b = pr!b - pr!(a-1)\n r = 1 : zipWith (+!) r (replicate (k-1) 0 ++ r)\n pr = listArray (0,100000) $ scanl (+) 0 r\nmain = mapM_ print . uncurry solve . parse =<< B.getContents\nm = 10^9 + 7 :: Int\na +! b | s > m = s - m | otherwise = s where s = a + b\nreadI b = i where Just (i,_) = B.readInt b\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nparse s = (k,pairs xs) where\n (k:xs) = map readI $ tail $ B.words s\n pairs (a:b:xs) = (a,b) : pairs xs\n pairs [] = []\nsolve k = map (uncurry go) where\n go a b = pr!b - pr!(a-1)\n r = 1 : zipWith (+!) r (replicate (k-1) 0 ++ r)\n pr = listArray (0,100000) $ scanl1 (+!) r\nmain = mapM_ print . uncurry solve . parse =<< B.getContents\nm = 10^9 + 7 :: Int\na +! b | s > m = s - m | otherwise = s where s = a + b\nreadI b = i where Just (i,_) = B.readInt b\n"}], "src_uid": "16c016c0735be1815c7b94c5c50516f1"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n],as,bs] <- replicateM 3 ri\r\n return (as,bs)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (as,bs) = min numDiff (1+numChg)\r\n where\r\n numDiff = length . filter (uncurry (/=)) $ zip as bs\r\n cnt1A = length . filter (==1) $ as\r\n cnt1B = length . filter (==1) $ bs\r\n numChg = abs (cnt1A - cnt1B)\r\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = do\r\n s <- getLine\r\n return $ map read $ words s\r\n\r\ndiff :: [Int] -> [Int] -> Int\r\ndiff a b = sum $ zipWith (\\x y -> if x /= y then 1 else 0) a b\r\n\r\ncount :: (a -> Bool) -> [a] -> Int\r\ncount p = length . filter p\r\n\r\ncountOnes :: [Int] -> Int\r\ncountOnes = count $ \\x -> x == 1\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n _ <- readInts\r\n a <- readInts\r\n b <- readInts\r\n let ca = countOnes a\r\n let cb = countOnes b\r\n let ans = if a == b then 0\r\n else (1 + abs (ca - cb)) `min` (diff a b)\r\n print ans\r\n\r\nmain :: IO ()\r\nmain = do\r\n [cnt] <- readInts\r\n forM_ (replicate cnt 0) $ \\_ -> solve\r\n "}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- getInts\n as <- getInts\n bs <- getInts\n let diff xs ys = sum $ map fromEnum $ zipWith (/=) xs ys \n print $ min (diff as bs) (diff (sort as) (sort bs) + 1)\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\n"}], "negative_code": [], "src_uid": "5ccef7fbfd5e85d7fc7ef92f9ebc4088"} {"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.ByteString.Internal as BSI\r\nimport qualified Data.IntMap as IntMap\r\nimport Data.Ix (Ix)\r\nimport Debug.Trace (trace)\r\n\r\nsolve :: String -> Bool\r\nsolve str = firstCondition && all (uncurry (==)) (zip alpha str)\r\n where\r\n first = head str\r\n alpha = dropWhile (/=first) (cycle \"Yes\")\r\n firstCondition = first == 'Y' || first == 'e' || first == 's'\r\n\r\ndoCase :: IO ()\r\ndoCase = do\r\n str <- getLine\r\n putStrLn $ bool \"No\" \"Yes\" $ solve str\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ doCase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts str = readInt <$> BS.split (BSI.c2w ' ') str\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndfa :: String -> Bool\ndfa = (/= '?') . foldl' f '$' where\n f '$' 'Y' = 'Y'\n f '$' 'e' = 'e'\n f '$' 's' = 's'\n f 'Y' 'e' = 'e'\n f 'e' 's' = 's'\n f 's' 'Y' = 'Y'\n f _ _ = '?'\n\nmain = do\n [n] <- readInts\n replicateM_ n $ getLine >>= putStrLn . ([\"NO\",\"YES\"] !!) . fromEnum . dfa\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n"}], "negative_code": [], "src_uid": "3cd56870a96baf8860e9b7e89008d895"} {"source_code": "import Data.Int\n \nreadCases :: [String] -> [[Int64]]\nreadCases [] = []\nreadCases (x:xs) = map read a : readCases rs\n where (a, rs) = splitAt (read x) xs\n \nsolveCase :: [Int64] -> Int64\nsolveCase a = g * (n-1) - s\n where n = fromIntegral $ length a\n s = sum a\n m = (s+n-2) `div` (n-1)\n g = maximum (m : a)\n \nsolve :: String -> String\nsolve = unlines . map show . map solveCase . readCases . tail . words\n \nmain = interact solve", "positive_code": [{"source_code": "import Data.Int\n\nreadCases :: [String] -> [[Int64]]\nreadCases [] = []\nreadCases (x:xs) = map read a : readCases rs\n where (a, rs) = splitAt (read x) xs\n\nsolveCase :: [Int64] -> Int64\nsolveCase a = g * (n-1) - s\n where n = fromIntegral $ length a\n s = sum a\n m = (s+n-2) `div` (n-1)\n g = maximum (m : a)\n\nsolve :: String -> String\nsolve = unlines . map show . map solveCase . readCases . tail . words\n\nmain = interact solve\n"}], "negative_code": [], "src_uid": "e75b88ce4341062c20b6014da1152d29"} {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Integer\n putStrLn $ concat $ map (\\x -> show x ++ \" \") [1..n]\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Integer)", "positive_code": [{"source_code": "prettier :: [Int] -> String\nprettier [] = \"\"\nprettier (x:xs) = (show x) ++ \" \" ++ (prettier xs)\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ read line\n\nmain :: IO ()\nmain = do\n t <- readInt\n for t where\n for 0 = return ()\n for i = do\n n <- readInt\n putStrLn $ prettier $ [n,(n-1)..1]\n for (i-1)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n putStrLn $ unwords $ map show [1 .. n]\n"}, {"source_code": "readInt x = read x :: Int\n\nmPrint [] = putStrLn \"\"\nmPrint (x:xs) = do\n putStr (show x)\n putStr \" \"\n mPrint xs\n\ntask = do\n kL <- getLine\n let k = readInt kL\n mPrint (take k [1..])\n \nallTasks 0 = putStrLn \"\"\nallTasks n = do\n task\n allTasks (n - 1)\n\nmain = do\n nL <- getLine\n let n = readInt nL\n allTasks n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tputStrLn $ intercalate \" \" $ map show [1..x]\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "solve :: Int -> [Int]\nsolve = enumFromTo 1\n\nmain :: IO ()\nmain = interact (unlines . map (unwords . map show . solve . read) . tail . words)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nf :: Int -> [String]\nf cnt = if cnt == 0 then [] else f (cnt - 1) ++ [show cnt]\n \n\nmain :: IO ()\nmain = do\n t <- readLn\n a <- replicateM t $ readLn\n let b = (map f a)\n putStrLn $ unwords (map unwords b)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nf :: Int -> [String]\nf cnt = if cnt == 0 then [\"\\n\"] else f (cnt - 1) ++ [show cnt]\n \n\nmain :: IO ()\nmain = do\n t <- readLn\n a <- replicateM t $ readLn\n let b = (map f a)\n putStrLn $ unwords (map unwords b)\n"}], "negative_code": [], "src_uid": "1b3ac752bc9c0b5e20a76f028d4b3c15"} {"source_code": "import Control.Applicative\nimport Data.Array\n\nmain :: IO ()\nmain = do\n size <- map read . words <$> getLine\n grid <- lines <$> getContents\n putStrLn $ solve size grid\n\nsolve :: [Int] -> [[Char]] -> String\nsolve [n, m] grid\n | and [withinOne a b | a <- edges, b <- edges] = \"YES\"\n | otherwise = \"NO\"\n where\n array = listArray (0, n-1) $ map (listArray (0, m-1)) grid\n isBlack i j = array ! i ! j == 'B'\n edges = [(i, j) | i <- [0..n-1],\n let js = [j | j <- [0..m-1], isBlack i j],\n j <- if null js then [] else [minimum js, maximum js]]\n withinOne (x, y) (z, w) =\n and [isBlack x j | j <- [y..w]] && and [isBlack i w | i <- [x..z]] ||\n and [isBlack z j | j <- [y..w]] && and [isBlack i y | i <- [x..z]]\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Array\n\nmain :: IO ()\nmain = do\n size <- map read . words <$> getLine\n grid <- lines <$> getContents\n putStrLn $ solve size grid\n\nsolve :: [Int] -> [[Char]] -> String\nsolve [n, m] grid\n | and [withinOne a b | a <- edges, b <- edges] = \"YES\"\n | otherwise = \"NO\"\n where\n array = listArray (0, n-1) $ map (listArray (0, m-1)) grid\n isBlack i j = array ! i ! j == 'B'\n edges = [(i, j) | i <- [0..n-1], j <- [0..m-1], isBlack i j, \n i == 0 || i == n-1 || j == 0 || j == m-1 ||\n or [not $ isBlack x y | (x, y) <- [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]]]\n withinOne (x, y) (z, w) =\n and [isBlack x j | j <- [y..w]] && and [isBlack i w | i <- [x..z]] ||\n and [isBlack z j | j <- [y..w]] && and [isBlack i y | i <- [x..z]]\n"}], "negative_code": [], "src_uid": "3631eba1b28fae473cf438bc2f0552b7"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n \r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport Data.Semigroup (Min(..), getMin)\r\nimport qualified Data.Set as S\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n \r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n \r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n \r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n \r\nbuildITree :: (Semigroup e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n \r\nqueryITree :: Semigroup e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = error $ \"Undefined behavior \" ++ show (ql, qr, l', r')\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l' m lt\r\n ra = go (m + 1) r' rt\r\n \r\ndata Pos = E | L | O | R deriving (Show, Eq, Ord)\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = Min k\r\n where\r\n k\r\n | i < m && teacherAges!(i + 1) % 1 >= avg = R\r\n | teacherAges!i % 1 >= avg = O\r\n | i > 1 && teacherAges!(i - 1) % 1 >= avg = L\r\n | otherwise = E\r\n (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int (Min Pos)\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = (p<=) $ getMin $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = if i' > i then i' else i + 1\r\n okMid\r\n | i == i' || i' == i + 1 = True\r\n | i' > i = checkPos L (i + 1) (i' - 1)\r\n | otherwise = checkPos R i' (i - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n \r\ntype SP = State [P.ByteString]\r\n \r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp", "positive_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n \r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n \r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n \r\n \r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n \r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n \r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n \r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l' m lt\r\n ra = go (m + 1) r' rt\r\n \r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n \r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n \r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n \r\ntype ITPos = IntervalTree PosSet\r\n \r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = if i' > i then i' else i + 1\r\n okMid\r\n | i == i' || i' == i + 1 = True\r\n | i' > i = checkPos L (i + 1) (i' - 1)\r\n | otherwise = checkPos R i' (i - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n \r\ntype SP = State [P.ByteString]\r\n \r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# OPTIONS_GHC -msse4.2 #-} -- fast clz\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\n\nlog2 :: Int -> Int\nlog2 v = finiteBitSize v - 1 - countLeadingZeros v\n\ndata Sparse = Sparse (Int -> Int -> Int) !(Array Int (UArray Int Int))\n\n-- | @query st li ri@ is the range-summary of [li, ri)\nquery :: Sparse -> Int -> Int -> Int\nquery (Sparse fun arr) li ri = let\n layer = log2 (ri - li)\n in fun (arr ! layer ! li) (arr ! layer ! (ri - bit layer))\n\nmkSparse :: (Int -> Int -> Int) -> UArray Int Int -> Sparse\nmkSparse fun arr = let\n (li, ri) = bounds arr\n lastLayer = log2 (ri + 1 - li)\n step :: UArray Int Int -> Int -> UArray Int Int\n step larr k = let\n (lli, lri) = bounds larr\n in listArray (lli, lri - k)\n $ zipWith fun (elems larr) (drop k $ elems larr)\n layers = scanl' step arr $ map bit [0 .. lastLayer - 1]\n in Sparse fun $ listArray (0, lastLayer) layers\n\n\ncalcAve :: Int -> Int -> Int\ncalcAve num den = case divMod num den of\n (q, r) -> 2 * q + min r 1\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\n{-# INLINE binSearch #-} -- specialize for known functions\nbinSearch fun = let\n go li ri = if li == ri\n then li\n else let\n mi = li + div (ri - li) 2\n in if fun mi\n then go li mi\n else go (mi + 1) ri\n in go\n\nlowerBound :: UArray Int Int -> Int -> Int\nlowerBound arr v = let\n (li, ri) = bounds arr\n in binSearch (\\i -> arr ! i >= v) li (ri + 1)\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n a <- getInts n\n bLi <- replicateM m $ do\n ~[ki] <- getInts 1\n getInts ki\n let\n sa :: UArray Int Int\n sa = listArray (1, m) $ map (* 2) $ drop (n - m) $ sort a\n b :: Array Int [Int]\n b = listArray (1, m) bLi\n sizes :: UArray Int Int\n sizes = listArray (1, m) $ map length $ elems b\n tots :: UArray Int Int\n tots = listArray (1, m) $ map (foldl' (+) 0) $ elems b\n groupAves :: UArray Int Int\n groupAves = listArray (1, m)\n $ sort $ zipWith calcAve (elems tots) (elems sizes)\n\n d0 = listArray (1, m) $ zipWith (-) (elems sa) (elems groupAves)\n dL = listArray (1, m-1) $ zipWith (-) (elems sa) (tail $ elems groupAves)\n dR = listArray (2, m) $ zipWith (-) (tail $ elems sa) (elems groupAves)\n q0 = mkSparse min d0\n qL = mkSparse min dL\n qR = mkSparse min dR\n\n ok q li ri = li >= ri || query q li ri >= 0\n\n solve :: Int -> Int -> Int\n solve ix toOust = let\n oldTot = tots ! ix\n oldSize = sizes ! ix\n oldAve = calcAve oldTot oldSize\n newAve = calcAve (oldTot - toOust) (oldSize - 1)\n oldPos = lowerBound groupAves oldAve\n newPos = lowerBound groupAves newAve\n in if newPos <= oldPos\n then let\n v1 = ok q0 1 newPos\n v2 = newAve <= sa ! newPos\n v3 = ok qR (newPos + 1) (oldPos + 1)\n v4 = ok q0 (oldPos + 1) (m + 1)\n in bool 0 1 $ v1 && v2 && v3 && v4\n else let\n realNewPos = newPos - 1 -- don't count your removed old self\n v1 = ok q0 1 oldPos\n v2 = ok qL oldPos realNewPos\n v3 = newAve <= sa ! realNewPos\n v4 = ok q0 (realNewPos + 1) (m + 1)\n in bool 0 1 $ v1 && v2 && v3 && v4\n solveG :: Int -> Builder\n solveG i = Prim.primMapListBounded Prim.intDec [solve i v | v <- b ! i]\n pure $ foldMap solveG [1..m] <> char7 '\\n'\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n{-\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n-}\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n \r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport Data.Semigroup (Min(..), getMin)\r\nimport qualified Data.Set as S\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n \r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n \r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n \r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n \r\nbuildITree :: (Semigroup e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n \r\nqueryITree :: Semigroup e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = error $ \"Undefined behavior \" ++ show (ql, qr, l', r')\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l' m lt\r\n ra = go (m + 1) r' rt\r\n \r\ndata Pos = E | L | O | R deriving (Show, Eq, Ord)\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = Min k\r\n where\r\n k\r\n | i >= m || teacherAges!(i + 1) % 1 >= avg = R\r\n | teacherAges!i % 1 >= avg = O\r\n | i <= 1 || teacherAges!(i - 1) % 1 >= avg = L\r\n | otherwise = E\r\n (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int (Min Pos)\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = (p<=) $ getMin $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = if i' > i then i' else i + 1\r\n okMid\r\n | i == i' || i' == i + 1 = True\r\n | i' > i = checkPos L (i + 1) (i' - 1)\r\n | otherwise = checkPos R i' (i - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n \r\ntype SP = State [P.ByteString]\r\n \r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = if i' > i then i' else i + 1\r\n okMid\r\n | i == i' || i' == i + 1 = True\r\n | i' > i = checkPos L (i + 1) (i' - 1)\r\n | otherwise = checkPos R i' (i - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid d s t\r\n && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = if i' > i then i' else i + 1\r\n d\r\n | i' == i + 1 || i' == i = O\r\n | i' > i = R\r\n | otherwise = L\r\n okMid O _ _ = True\r\n okMid L l r = checkPos R l (r - 1)\r\n okMid R l r = checkPos L (l + 1) (r - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid d s t\r\n && (t <= m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = if i' > i then i' else i + 1\r\n d\r\n | i' == i + 1 || i' == i = O\r\n | i' > i = R\r\n | otherwise = L\r\n okMid O _ _ = True\r\n okMid L l r = checkPos R l (r - 1)\r\n okMid R l r = checkPos L (l + 1) (r - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid d s t\r\n && (checkPos O (if i' > i then i' else i + 1) m)\r\n where\r\n s = min i i'\r\n d\r\n | i' == i + 1 || i' == i = O\r\n | i' > i = R\r\n | otherwise = L\r\n okMid O _ _ = True\r\n okMid L l r = checkPos R l (r - 1)\r\n okMid R l r = checkPos L (l + 1) (r - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if traceShow (\"KK\", i, i') $ avg' <= (teacherAges!(if i' > i then i' - 1 else i'))%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid d s t\r\n && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = max i i'\r\n d\r\n | i' == i + 1 || i' == i = O\r\n | i' > i = R\r\n | otherwise = L\r\n okMid O _ _ = True\r\n okMid L l r = checkPos R l (r - 1)\r\n okMid R l r = checkPos L (l + 1) (r - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n-- import Debug.Trace\r\ntraceShowId = id\r\ntraceShow _ = id\r\n\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = traceShowId $ listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 >= avg)\r\n <> (add O $ teacherAges!i % 1 >= avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 >= avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = traceShowId $ listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = traceShowId $ (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = traceShowId $ groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if avg' <= (teacherAges!i)%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = traceShow (\"See \", s, t) $ (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid d s t\r\n && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = max i i'\r\n d\r\n | i' == i + 1 || i' == i = O\r\n | i' > i = R\r\n | otherwise = L\r\n okMid O _ _ = True\r\n okMid L l r = checkPos R l (r - 1)\r\n okMid R l r = checkPos L (l + 1) (r - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as S\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata BinTree a = BinLeaf a | BinNode a (BinTree a) (BinTree a)\r\n deriving (Show, Eq, Functor)\r\ndata IntervalTree a = IT (Int, Int) (BinTree a)\r\n\r\nbinAnn (BinLeaf v) = v\r\nbinAnn (BinNode v _ _) = v\r\n\r\nbuildITree :: (Monoid e, IArray a e) => a Int e -> IntervalTree e\r\nbuildITree a = let (l, r) = bounds a in IT (l, r) $ go l r\r\n where\r\n go l r =\r\n if l == r then BinLeaf (a!l)\r\n else\r\n let mid = (l + r) `div` 2\r\n lt = go l mid\r\n rt = go (mid + 1) r\r\n in BinNode (binAnn lt <> binAnn rt) lt rt\r\n\r\nqueryITree :: Monoid e => Int -> Int -> IntervalTree e -> e\r\nqueryITree ql qr (IT (l, r) bt) = go l r bt\r\n where\r\n go _ _ (BinLeaf v) = v\r\n go l' r' (BinNode a lt rt)\r\n | ql > r' || qr < l' = mempty\r\n | ql <= l' && qr >= r' = a\r\n | qr <= m = la\r\n | ql > m = ra\r\n | otherwise = la <> ra\r\n where\r\n m = (l' + r') `div` 2\r\n la = go l m lt\r\n ra = go (m + 1) r rt\r\n\r\ndata Pos = L | R | O deriving (Show, Eq, Ord)\r\nnewtype PosSet = PS {unPS :: S.Set Pos} deriving (Show, Eq)\r\n\r\ninstance Semigroup PosSet where\r\n (PS a) <> (PS b) = PS $ S.intersection a b\r\n\r\ninstance Monoid PosSet where\r\n mempty = PS $ S.fromList [L, R, O]\r\n\r\ntype ITPos = IntervalTree PosSet\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n ta <- getInts n\r\n sg <- replicateM m $ (head <$>getInts 1) >>= getInts\r\n let ta' = take m $ sortOn negate ta\r\n teacherAges :: UArray Int Int\r\n teacherAges = listArray (1, m) ta'\r\n studentGroups :: Array Int [Int]\r\n studentGroups = listArray (1, m) sg\r\n groupInfos = amap (groupInfo<$>length<*>sum) studentGroups\r\n groupOrder :: UArray Int Int\r\n groupOrder = listArray (1, m) $ sortOn\r\n (\\i -> let (x, _, _) = groupInfos!i in negate x) [1..m]\r\n revOrder :: UArray Int Int\r\n revOrder = array (1, m) $ (\\(x, y) -> (y, x)) <$> assocs groupOrder\r\n add pos f = if f then S.singleton pos else S.empty\r\n getPosSet i = PS $ (add L $ i > 1 && teacherAges!(i - 1) % 1 > avg)\r\n <> (add O $ teacherAges!i % 1 > avg)\r\n <> (add R $ i < m && teacherAges!(i + 1) % 1 > avg)\r\n where (avg, _, _) = groupInfos!(groupOrder!i)\r\n posSets :: Array Int PosSet\r\n posSets = listArray (1, m) [getPosSet i | i <- [1..m]]\r\n posTree = buildITree posSets\r\n goGrp :: Int -> SP Builder\r\n goGrp ri = let i = revOrder!ri in mconcat<$>(sequence $ goStu i<$>studentGroups!(groupOrder!i))\r\n goStu :: Int -> Int -> SP Builder\r\n goStu i a =\r\n let (_, len, s) = groupInfos!(groupOrder!i)\r\n avg' = (s - a) % (len - 1)\r\n findPos l r\r\n | l == r = l\r\n | avg' <= avg = findPos (m + 1) r\r\n | otherwise = findPos l m\r\n where\r\n m = (l + r) `div` 2\r\n (avg, _, _) = groupInfos!(groupOrder!m)\r\n i' = findPos 1 (m + 1)\r\n in if avg' <= (teacherAges!i)%1 && ok i i' then pure $ char7 '1'\r\n else pure $ char7 '0'\r\n checkPos p l r = S.member p $ unPS $ queryITree l r posTree\r\n ok i i' = (s <= 1 || checkPos O 1 (s - 1))\r\n && okMid d s t\r\n && (t > m || checkPos O t m)\r\n where\r\n s = min i i'\r\n t = max i i'\r\n d\r\n | i' == i + 1 || i' == i = O\r\n | i' > i = R\r\n | otherwise = L\r\n okMid O _ _ = True\r\n okMid L l r = checkPos R l (r - 1)\r\n okMid R l r = checkPos L (l + 1) (r - 1)\r\n (<>char7 '\\n')<$>mconcat<$> mapM goGrp [1..m]\r\n where\r\n groupInfo l s = (s % l, l, s)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "src_uid": "01e728192b092cac9e0833353a3ed3f0"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport Data.Char\nimport Data.Array.Unboxed\nimport Data.Bool\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n xs <- replicateM n poi\n ys <- pop\n return $ bool \"NO\" \"YES\" $ solve n xs $ map digitToInt $ B.unpack ys\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs (listArray (1, n) . scanl (+) 0 -> ys) = and $ zipWith ok xs [1..]\n where\n _ = ys :: UArray Int Int\n ok l r\n | l > r = ok r l\n | otherwise = ys!r - ys!l == r - l", "positive_code": [{"source_code": "import Data.List\n\nmain = getLine >> fmap (map read.words) getLine >>= \\l -> getLine >>= putStrLn . (solve l)\n\nsolve :: [Int] -> String -> String\nsolve a b\n | ascending $ concat $ map reduce $ groupList a b = \"YES\"\n | otherwise = \"NO\"\n\ngroupList [a] [] = [[a]]\ngroupList (x:xs) (y:ys)\n | y == '1' = (\\x (y:ys) -> (x:y):ys) x $ groupList xs ys\n | otherwise = [x] : (groupList xs ys)\n\nascending [_] = True\nascending (x:y:xs)\n | x <= y = ascending (y:xs)\n | otherwise = False\n\nreduce [x] = [x]\nreduce xs = [minimum xs, maximum xs]\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = getLine >> fmap words getLine >>= \\l -> getLine >>= putStrLn . (solve l)\n\nsolve a b\n | sort a == (concat $ map sort $ groupList a b) = \"YES\"\n | otherwise = \"NO\"\n\ngroupList [a] [] = [[a]]\ngroupList (x:xs) (y:ys)\n | y == '1' = (\\x (y:ys) -> (x:y):ys) x (groupList xs ys)\n | otherwise = [x] : (groupList xs ys)\n"}], "src_uid": "094a880e93a2adfbcb6dcc2b5f043bab"} {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad.State\nimport Data.Int\nimport Data.List (sort)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nclass Heap h where\n empty :: h a\n singleton :: (Ord a) => a -> h a\n\n isSingleton :: (Ord a) => h a -> Bool\n\n merge :: (Ord a) => h a -> h a -> h a\n push :: (Ord a) => a -> h a -> h a\n pop :: (Ord a) => h a -> (a, h a)\n fromList :: (Ord a) => [a] -> h a\n\ndata LeftistHeap a = Empty\n | Node a Int (LeftistHeap a) (LeftistHeap a)\n deriving (Show, Eq)\n\nsize :: LeftistHeap a -> Int\nsize Empty = 0\nsize (Node _ s _ _) = s\n\nmakeHeap :: (Ord a) => a -> LeftistHeap a -> LeftistHeap a -> LeftistHeap a\nmakeHeap x yh zh | ys > zs = Node x (ys + 1) yh zh\n | otherwise = Node x (zs + 1) zh yh\n where ys = size yh\n zs = size zh\n\ninstance Heap LeftistHeap where\n empty = Empty\n singleton a = Node a 1 Empty Empty\n\n isSingleton (Node _ _ Empty Empty) = True\n isSingleton _ = False\n\n merge Empty h2 = h2\n merge h1 Empty = h1\n merge h1@(Node x s1 l1 r1) h2@(Node y s2 l2 r2) | x < y = makeHeap x l1 (merge r1 h2)\n | otherwise = makeHeap y l2 (merge h1 r2)\n\n push a h = merge h (singleton a)\n\n pop Empty = error $ \"Can't pop from empty heap\"\n pop (Node x _ h1 h2) = (x, merge h1 h2)\n\n fromList [] = empty\n fromList xs = go $ map singleton xs\n where go [] = empty\n go [h] = h\n go hs = go $ joinPairs hs\n\n joinPairs [] = []\n joinPairs [x] = [x]\n joinPairs (x:y:zs) = (merge x y):joinPairs zs\n\n\ntype Context = State (Int64, LeftistHeap Int64)\n\nsolve :: [Int64] -> Int64\nsolve [] = 0\nsolve [_] = 0\nsolve xs = evalState go (0, fromList xs')\n where xs' | even (length xs) = 0:xs\n | otherwise = xs\n\n popQ :: Context Int64\n popQ = state $ \\(n, h) -> let (x, h') = pop h in (x, (n, h'))\n\n go :: Context Int64\n go = do\n (n, h) <- get\n if isSingleton h\n then return n\n else do a <- popQ\n b <- popQ\n c <- popQ\n let m = a + b + c\n modify (\\(n, h) -> (n + m, push m h))\n go\n\ntest0 = [1, 2, 3] :: [Int64]\ntest1 = [2, 3, 4, 5] :: [Int64]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error \"Can't parse Int\"\n\ngo :: Tokenizer Int64\ngo = do\n n <- nextInt\n as <- map fromIntegral <$> replicateM n nextInt\n return $ solve as\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n print $ evalState go input\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad.State\nimport Data.Int\nimport Data.List (sort, unfoldr)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nclass Heap h where\n empty :: h a\n singleton :: (Ord a) => a -> h a\n\n isSingleton :: (Ord a) => h a -> Bool\n\n merge :: (Ord a) => h a -> h a -> h a\n push :: (Ord a) => a -> h a -> h a\n pop :: (Ord a) => h a -> (a, h a)\n fromList :: (Ord a) => [a] -> h a\n\ndata LeftistHeap a = Empty\n | Node a Int (LeftistHeap a) (LeftistHeap a)\n deriving (Show, Eq)\n\nsize :: LeftistHeap a -> Int\nsize Empty = 0\nsize (Node _ s _ _) = s\n\nmakeHeap :: (Ord a) => a -> LeftistHeap a -> LeftistHeap a -> LeftistHeap a\nmakeHeap x yh zh | ys > zs = Node x (ys + 1) yh zh\n | otherwise = Node x (zs + 1) zh yh\n where ys = size yh\n zs = size zh\n\ninstance Heap LeftistHeap where\n empty = Empty\n singleton a = Node a 1 Empty Empty\n\n isSingleton (Node _ _ Empty Empty) = True\n isSingleton _ = False\n\n merge Empty h2 = h2\n merge h1 Empty = h1\n merge h1@(Node x s1 l1 r1) h2@(Node y s2 l2 r2) | x < y = makeHeap x l1 (merge r1 h2)\n | otherwise = makeHeap y l2 (merge h1 r2)\n\n push a h = merge h (singleton a)\n\n pop Empty = error $ \"Can't pop from empty heap\"\n pop (Node x _ h1 h2) = (x, merge h1 h2)\n\n fromList [] = empty\n fromList xs = head . head . dropWhile (not . converged) $ iterate (unfoldr join) hs\n where hs = map singleton xs\n join [] = Nothing\n join [x] = Just (x, [])\n join (x:y:zs) = Just (merge x y, zs)\n\n converged [x] = True\n converged _ = False\n\ntype Context = State (Int64, LeftistHeap Int64)\n\nsolve :: [Int64] -> Int64\nsolve [] = 0\nsolve [_] = 0\nsolve xs = evalState go (0, fromList xs')\n where xs' | even (length xs) = 0:xs\n | otherwise = xs\n\n popQ :: Context Int64\n popQ = state $ \\(n, h) -> let (x, h') = pop h in (x, (n, h'))\n\n go :: Context Int64\n go = do\n (n, h) <- get\n if isSingleton h\n then return n\n else do a <- popQ\n b <- popQ\n c <- popQ\n let m = a + b + c\n modify (\\(n, h) -> (n + m, push m h))\n go\n\ntest0 = [1, 2, 3] :: [Int64]\ntest1 = [2, 3, 4, 5] :: [Int64]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error \"Can't parse Int\"\n\ngo :: Tokenizer Int64\ngo = do\n n <- nextInt\n as <- map fromIntegral <$> replicateM n nextInt\n return $ solve as\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n print $ evalState go input\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad.State\nimport Data.Int\nimport Data.List (sort, unfoldr)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nclass Heap h where\n empty :: h a\n singleton :: (Ord a) => a -> h a\n\n isSingleton :: (Ord a) => h a -> Bool\n\n merge :: (Ord a) => h a -> h a -> h a\n push :: (Ord a) => a -> h a -> h a\n pop :: (Ord a) => h a -> (a, h a)\n fromList :: (Ord a) => [a] -> h a\n\ndata LeftistHeap a = Empty\n | Node a Int (LeftistHeap a) (LeftistHeap a)\n deriving (Show, Eq)\n\nsize :: LeftistHeap a -> Int\nsize Empty = 0\nsize (Node _ s _ _) = s\n\nmakeHeap :: (Ord a) => a -> LeftistHeap a -> LeftistHeap a -> LeftistHeap a\nmakeHeap x yh zh | ys > zs = Node x (ys + 1) yh zh\n | otherwise = Node x (zs + 1) zh yh\n where ys = size yh\n zs = size zh\n\ninstance Heap LeftistHeap where\n empty = Empty\n singleton a = Node a 1 Empty Empty\n\n isSingleton (Node _ _ Empty Empty) = True\n isSingleton _ = False\n\n merge Empty h2 = h2\n merge h1 Empty = h1\n merge h1@(Node x s1 l1 r1) h2@(Node y s2 l2 r2) | x < y = makeHeap x l1 (merge r1 h2)\n | otherwise = makeHeap y l2 (merge h1 r2)\n\n push a h = merge h (singleton a)\n\n pop Empty = error $ \"Can't pop from empty heap\"\n pop (Node x _ h1 h2) = (x, merge h1 h2)\n\n fromList [] = empty\n fromList xs = head . head . dropWhile (not.converged) $ iterate (unfoldr join) hs\n where hs = map singleton xs\n join [] = Nothing\n join [x] = Just (x, [])\n join (x:y:zs) = Just (merge x y, zs)\n\n converged [x] = True\n converged _ = False\n\ntype Context = State (Int64, LeftistHeap Int64)\n\nsolve :: [Int64] -> Int64\nsolve [] = 0\nsolve [_] = 0\nsolve xs = evalState go (0, fromList xs')\n where xs' | even (length xs) = 0:xs\n | otherwise = xs\n\n popQ :: Context Int64\n popQ = state $ \\(n, h) -> let (x, h') = pop h in (x, (n, h'))\n\n go :: Context Int64\n go = do\n (n, h) <- get\n if isSingleton h\n then return n\n else do a <- popQ\n b <- popQ\n c <- popQ\n let m = a + b + c\n modify (\\(n, h) -> (n + m, push m h))\n go\n\ntest0 = [1, 2, 3] :: [Int64]\ntest1 = [2, 3, 4, 5] :: [Int64]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error \"Can't parse Int\"\n\ngo :: Tokenizer Int64\ngo = do\n n <- nextInt\n as <- map fromIntegral <$> replicateM n nextInt\n return $ solve as\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n print $ evalState go input\n"}], "negative_code": [], "src_uid": "5cb6d6f549fa9c410848f1bc69607877"} {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:k:_) <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Integer]\n let ms = nub as\n if length ms > k\n then print (-1)\n else do\n print $ n * k\n putStrLn $ unwords . map show $ take (n * k) $ cycle $ take k $ ms ++ repeat 1", "positive_code": [{"source_code": "\nimport qualified Data.List as L\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n k as\n | uniqueSize > k = []\n | otherwise = take (n*k) $ L.cycle block\n where\n unique = map head $ L.group $ L.sort as\n uniqueSize = length unique\n block = L.replicate (k-uniqueSize) 1 ++ unique\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readInts\n as <- readInts\n printSolution $ solve n k as\n testCases (t-1)\n\nprintSolution :: [Int] -> IO ()\nprintSolution [] = putStrLn \"-1\"\nprintSolution bs = do\n print $ length bs\n putStrLn $ unwords $ map show bs\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as S\n\nreadIs :: IO [Int]\nreadIs = fmap read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- head <$> readIs\n replicateM_ t $ do\n [n,k] <- readIs\n s <- S.fromList <$> readIs\n case solve n k s of\n Nothing -> putStrLn \"-1\"\n Just xs -> print (n*k) >> putStrLn (unwords (show <$> xs))\n\nsolve :: Int -> Int -> S.Set Int -> Maybe [Int]\nsolve n k s | S.size s > k = Nothing\nsolve n k s = Just $ take (n*k) $ cycle $ S.toList $ grow s n\n where\n size = S.size s\n grow s 0 = s\n grow s _ | S.size s == k = s\n grow s n = grow (S.insert n s) (n-1)\n"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\n\nreadInts :: IO [Int]\nreadInts = do\n input <- getLine\n return $ map read . words $ input\n \nprintAnswer :: [Int] -> IO ()\nprintAnswer [] = putStrLn \"-1\"\nprintAnswer ans = do\n print $ length ans\n putStrLn $ unwords $ map show ans\n\n\nsolve :: [Int] -> Int -> Int -> [Int]\nsolve unique n k\n | len > k = []\n | otherwise = take (n * k) $ L.cycle unique'\n where\n len = length unique\n unique' = L.replicate (k - len) 1 ++ unique\n \n\n\nhandle_test :: Int -> IO()\nhandle_test 0 = do return ()\nhandle_test t = do\n [n, k] <- readInts\n a <- readInts\n let unique = S.toList (S.fromList a) in\n printAnswer $ solve unique n k\n handle_test $ t - 1\n\nmain = do\n t <- getLine\n handle_test $ read t\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport qualified Data.Set as S\n\nreadIs :: IO [Int]\nreadIs = fmap read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- head <$> readIs\n replicateM_ t $ do\n [n,k] <- readIs\n s <- S.fromList <$> readIs\n case solve n k s of \n Nothing -> putStrLn \"-1\"\n Just xs -> print (n*k) >> putStrLn (unwords (show <$> xs))\n\nsolve :: Int -> Int -> S.Set Int -> Maybe [Int]\nsolve n k s | S.size s > k = Nothing\nsolve n k s = Just $ take (n*k) $ cycle (S.toList s)\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as S\n\nreadIs :: IO [Int]\nreadIs = fmap read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- head <$> readIs\n replicateM_ t $ do\n [n,k] <- readIs\n s <- S.fromList <$> readIs\n case solve n k s of\n Nothing -> putStrLn \"-1\"\n Just xs -> print (n*k) >> putStrLn (unwords (show <$> xs))\n\nsolve :: Int -> Int -> S.Set Int -> Maybe [Int]\nsolve n k s | S.size s > k = Nothing\nsolve n k s = Just $ take (n*k) $ cycle (S.toList s1)\n where\n size = S.size s\n s1 = S.union\n s\n (S.fromList $ take (k-size) (enumFrom $ succ $ S.findMax s))\n"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\n\nprintList :: [Int] -> Int -> IO()\nprintList _ 0 = do putStr \"\\n\"\nprintList list n = do\n putStr $ ( ++ \" \") . unwords $ map show list \n printList list $ n - 1\n\n\nsolve :: [Int] -> Int -> Int -> IO ()\nsolve unique n k = \n printList unique' n\n where\n high = last unique\n len = length unique\n unique' = unique ++ [x * high | x <- [1 .. len - k]]\n\n \n\nreadInts :: IO [Int]\nreadInts = do\n input <- getLine\n return $ map read . words $ input\n \n\nhandle_test :: Int -> IO()\nhandle_test 0 = do return ()\nhandle_test t = do\n [n, k] <- readInts\n a <- readInts\n let unique = S.toList (S.fromList a)\n if length unique <= k then\n solve unique n k\n else\n print $ -1\n handle_test $ t - 1\n\nmain = do\n t <- getLine\n handle_test $ read t\n"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\n\nprintList :: [Int] -> Int -> IO()\nprintList _ 0 = do putStr \"\\n\"\nprintList list n = do\n putStr $ ( ++ \" \") . unwords $ map show list \n printList list $ n - 1\n\n\nsolve :: [Int] -> Int -> Int -> IO ()\nsolve unique n k = \n printList unique' n\n where\n high = last unique\n len = length unique\n unique' = unique ++ [x * high | x <- [1 .. len - k]]\n\n \n\nreadInts :: IO [Int]\nreadInts = do\n input <- getLine\n return $ map read . words $ input\n \n\nhandle_test :: Int -> IO()\nhandle_test 0 = do return ()\nhandle_test t = do\n [n, k] <- readInts\n a <- readInts\n let unique = S.toList (S.fromList a)\n if length unique <= k then\n solve unique n k\n else\n print $ -1\n\nmain = do\n t <- getLine\n handle_test $ read t\n"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\n\nprintList :: [Int] -> Int -> IO()\nprintList _ 0 = do putStr \"\\n\"\nprintList list n = do\n putStr $ ( ++ \" \") . unwords $ map show list \n printList list $ n - 1\n\n\nsolve :: [Int] -> Int -> Int -> IO ()\nsolve unique n k = do\n print $ n * k\n printList unique' n\n where\n high = last unique\n len = length unique\n unique' = unique ++ [x * high | x <- [1 .. len - k]]\n\n \n\nreadInts :: IO [Int]\nreadInts = do\n input <- getLine\n return $ map read . words $ input\n \n\nhandle_test :: Int -> IO()\nhandle_test 0 = do return ()\nhandle_test t = do\n [n, k] <- readInts\n a <- readInts\n let unique = S.toList (S.fromList a)\n if length unique <= k then\n solve unique n k\n else\n print $ -1\n handle_test $ t - 1\n\nmain = do\n t <- getLine\n handle_test $ read t\n"}, {"source_code": "\nimport qualified Data.List as L\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n k as\n | uniqueSize > k = []\n | otherwise = take (n*k) $ L.cycle block\n where\n unique = map head $ L.group $ L.sort as\n uniqueSize = length unique\n block = L.replicate (k-uniqueSize) 0 ++ unique\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readInts\n as <- readInts\n printSolution $ solve n k as\n testCases (t-1)\n\nprintSolution :: [Int] -> IO ()\nprintSolution [] = putStrLn \"-1\"\nprintSolution bs = do\n print $ length bs\n putStrLn $ unwords $ map show bs\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}], "src_uid": "80d4b2d01215b12ebd89b8ee2d1ac6ed"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype Maze = [[Char]]\n\nallOff :: [Char] -> Bool\nallOff = all (== '0')\n\ncompleted :: Maze -> Bool\ncompleted [] = True\ncompleted (m:ms) = allOff m && completed ms\n\nsolve :: Maze -> Int\nsolve maze = go (0, width - 1) (reverse maze)\n where width = length $ head maze\n go (tl, tr) maze@(m:ms)\n | completed maze = min tl tr\n | allOff m = go (tl + 1, tr + 1) ms\n | completed ms = min (tl + maxOn) (tr + minOn)\n | otherwise = go (tl' + 1, tr' + 1) ms\n where ons = elemIndices '1' m\n minOn = width - minimum ons - 1\n maxOn = maximum ons\n tl' = min (tl + 2 * maxOn) (tr + width - 1)\n tr' = min (tr + 2 * minOn) (tl + width - 1)\n\ntest0 = [ \"0010\"\n , \"0100\"\n ]\ntest1 = [ \"001000\"\n , \"000010\"\n , \"000010\"\n ]\ntest2 = [ \"01110\"\n , \"01110\"\n , \"01110\"\n , \"01110\"\n ]\n\nmain :: IO ()\nmain = do\n [n, _] <- map read . words <$> getLine\n maze <- replicateM n getLine\n print $ solve maze\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve m = (\\(c, _, _) -> c) . foldl' go (0, 0, 1000)\n where\n go (!t, !tl, !tr) f = case ixs of\n [] -> (t, tl + 1, tr + 1)\n _ -> (min (tl + r) (tr + m + 1 - l), min (tl + 2*r + 1) (tr + m + 2), min (tr + 2*(m + 1 - l) + 1) (tl + m + 2))\n where\n ixs = elemIndices '1' f\n l = head ixs\n r = last ixs\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n b <- reverse <$> replicateM n getLine\n print $ solve m b\n\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nlast' [] = Nothing\nlast' xs@(_:_) = Just $ last xs\n\nlastIx = (last' .) . elemIndices\n\nsolve m r b \n | all (== '0') (concat b) = 0\n | otherwise = solve' m r b\n\nsolve' m r (l1':rest) = case rest of\n [] -> ix\n [l2] -> if all (== '0') l2 then ix else time\n _ -> time\n where\n ix = fromMaybe 0 $ lastIx '1' (if r then reverse l1' else l1')\n time \n | ix > (m + 2) `div` 2 = m + 2 + solve m (not r) rest\n | otherwise = 2 * ix + 1 + solve m r rest\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n b <- reverse <$> replicateM n getLine\n print $ solve m False b\n\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nlast' [] = Nothing\nlast' xs@(_:_) = Just $ last xs\n\nsolve m r [l1, l2] = (\\p -> if d then p else if p > (m + 2) `div` 2 then m + 2 + solve m (not r) [l2] else 2*p + 1 + solve m r [l2]) $ fromMaybe 0 $ last' $ elemIndices '1' (if r then reverse l1 else l1)\n where d = all (== '0') l2\n\nsolve m r (l1:l2:ls) = (\\p -> if p > (m + 2) `div` 2 then m + 2 + solve m (not r) (l2 : ls) else 2*p + 1 + solve m r (l2 : ls)) $ fromMaybe 0 $ last' $ elemIndices '1' (if r then reverse l1 else l1)\n\n\nsolve _ r [l1] = fromMaybe 0 $ last' $ elemIndices '1' (if r then reverse l1 else l1)\n\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n b <- reverse <$> replicateM n getLine\n print $ solve m False b\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve m = (\\(c, _, _) -> c) . foldl' go (0, 0, 1000)\n where\n go (!t, !tl, !tr) f = case ixs of\n [] -> (t, tl + 1, tr + 1)\n _ -> (min (tl + r) (tr + m + 1 - l), min (tl + 2*r + 1) (tr + m + 2), min (tr + 2*(m + 1 - l)) (tl + m + 2))\n where\n ixs = elemIndices '1' f\n l = head ixs\n r = last ixs\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n b <- reverse <$> replicateM n getLine\n print $ solve m b\n\n"}], "src_uid": "55070f8e5dba8a6ec669a53a169e557d"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Int (Int64)\nimport Data.Foldable (foldl')\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: String -> Int64\nsolve line = foldr (*:) 1 . take n $ repeat k\n where\n n = length line\n (*:) !i !j = (i * j) `mod` 1000000007\n\n cnt = (\\(i, j, k, l) -> [i, j, k, l]) $ foldl' count (0, 0, 0, 0) line\n where\n count (!i, !j, !k, !l) 'A' = (i + 1, j, k, l)\n count (!i, !j, !k, !l) 'C' = (i, j + 1, k, l)\n count (!i, !j, !k, !l) 'G' = (i, j, k + 1, l)\n count (!i, !j, !k, !l) 'T' = (i, j, k, l + 1)\n\n k = foldr (\\i acc -> if i == m then acc + 1 else acc) 0 cnt\n where m = maximum cnt\n\nmain = do\n B.getLine\n line <- B.getLine\n print . solve . C.unpack $ C.init line\n", "positive_code": [{"source_code": "import Data.List \n\nmodulo :: Integer\nmodulo = 1000 * 1000 * 1000 + 7\n\npowerMod :: Integer -> Integer -> Integer -> Integer\npowerMod base 0 _ = 1\npowerMod base exp modulo\n | exp `mod` 2 == 1 = base * powerMod base (exp - 1) modulo `mod` modulo\n | otherwise = \n let halfPow = powerMod base (exp `div` 2) modulo\n in \n halfPow * halfPow `mod` modulo \n \ncount :: Char -> String -> Int\ncount c str = length $ filter (== c) str\n\nmain = do\n getLine\n s <- getLine\n let frequences = [count 'A' s, count 'C' s, count 'T' s, count 'G' s]\n let max = maximum frequences \n let cntMax = length $ filter(== max) frequences\n putStrLn $ show $ \n powerMod (fromIntegral cntMax) (fromIntegral (length s)) modulo \n \n"}, {"source_code": "import Data.List (genericLength)\nsolve :: [Int] -> String -> Integer\nsolve ks [] = mod (g ^ sum ks) (10 ^ 9 + 7)\n where m = maximum ks\n g = genericLength $ filter (==m) ks\nsolve [a, c, g, t] (x:xs) = case x of\n 'A' -> solve [a + 1, c, g, t] xs\n 'C' -> solve [a, c + 1, g, t] xs\n 'G' -> solve [a, c, g + 1, t] xs\n 'T' -> solve [a, c, g, t + 1] xs\nmain = getLine >> getLine >>= putStrLn . show . solve [0, 0, 0, 0]"}], "negative_code": [], "src_uid": "f35c042f23747988f65c5b5e8d5ddacd"} {"source_code": "solveTask :: (Integer, Integer) -> Integer\nsolveTask (a, b) =\n let d = length $ show $ b\n d' = length $ show $ b + 1\n in if d == d'\n then a * toInteger(d-1)\n else a * toInteger(d)\n\ngroupTaskInput :: [String] -> [(Integer, Integer)]\ngroupTaskInput [] = []\ngroupTaskInput (n:(d:xs)) = (read n, read d) : groupTaskInput(xs)\n\nmakeTaskInput :: String -> [(Integer, Integer)]\nmakeTaskInput s = groupTaskInput . tail . words $ s\n\nsolve :: String -> String\nsolve s = concat $ (map (++ \"\\n\") ) $ (map $ show.solveTask) $ makeTaskInput s\n\nmain' :: IO ()\nmain' = do interact $ solve\n\nmain = main'\n\n\n", "positive_code": [{"source_code": "import Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn(s)\n\nmain_ :: EIO ()\nmain_ = do\n t <- get :: EIO Int\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, b) <- liftM2 (,) get get :: EIO (Int64, Int64)\n putln $ f2 a b\n\nf2 :: Int64 -> Int64 -> Int64\nf2 a b = (*) a $ log10 $ (+) b 1\n\nlog10 :: Int64 -> Int64\nlog10 n = if n <= 9 then 0 else (+) 1 $ log10 $ div n 10"}, {"source_code": "import System.IO\n-- import Prelude\n\n\nreadInt :: IO Int\nreadInt = readLn\n\ncastToInteger x = read x::Integer\n\n\nmain = do\n t <- readInt\n mainLoop t\n\n\nmainLoop t = do\n if t == 0 then\n return ()\n else do\n line <- getLine\n let test_case = (map castToInteger . take 2 . words) line\n\n solveTask test_case\n\n mainLoop (t - 1)\n\n\nsolveTask :: [Integer] -> IO ()\nsolveTask [a, b] = do\n let bs = [10^i - 1| i <- [1..11], 10^i - 1 <= b]\n let res = a * count bs\n print res\n\n\ncount :: [Integer] -> Integer\ncount [] = 0\ncount (x:xs) = 1 + count xs\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >> getContents >>= putStrLn.unlines.map (show.(\\(a:b:_) -> a * (toInteger $ pred $ length $ show $ succ b)).map read.words).lines\n\n-- ayy it's a one-liner\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >> getContents >>= putStrLn.unlines.map (show.(\\(a:b:_) -> a * (pred $ length $ show $ succ b)).map read.words).lines\n\n-- ayy it's a one-liner\n"}, {"source_code": "import System.IO\n-- import Prelude\n\n\nreadInt :: IO Int\nreadInt = readLn\n\nreadTuple :: IO (Int, Int)\nreadTuple = readLn\n\ncastToInt x = read x::Int\n\n\nmain = do\n t <- readInt\n mainLoop t\n\n\nmainLoop t = do\n if t == 0 then\n return ()\n else do\n line <- getLine\n let test_case = (map castToInt . take 2 . words) line\n\n solveTask test_case\n\n mainLoop (t - 1)\n\n\nsolveTask [a, b] = do\n let bs = [10^i - 1| i <- [1..10], 10^i - 1 <= b]\n let res = a * count bs\n print res\n\ncount [] = 0\ncount (x:xs) = 1 + count xs\n"}], "src_uid": "dc67dd2102c70ea476df642b863ae8d3"} {"source_code": "main=interact$q\"$\"\nq p(x:s)|x==head p=q(tail p)s|1<2=q(x:p)s\nq p _=reverse$init p\n", "positive_code": [{"source_code": "solve s = solve' s []\n\twhere\n\t\tsolve' [] stack = reverse stack\n\t\tsolve' (x:xs) stack\n\t\t\t| not (null stack) && head stack == x = solve' xs $ tail stack\n\t\t\t| otherwise = solve' xs $ x:stack\n\nmain = interact solve\n"}, {"source_code": "solve s = solve' s []\n\twhere\n\t\tsolve' [] stack = reverse stack\n\t\tsolve' (x:xs) stack\n\t\t\t| not (null stack) && head stack == x = solve' xs $ tail stack\n\t\t\t| otherwise = solve' xs $ x:stack\n\nmain = interact solve\n"}, {"source_code": "import Data.List\n\nsolve :: String -> String -> String\nsolve [] acc = acc\nsolve (x:xs) (a:as) | x == a = solve xs as\nsolve (x:xs) acc = solve xs (x:acc)\n\n-- xraccabccbry\n\nmain = do \n stuff <- getLine\n putStrLn $ reverse $ solve stuff \"\""}, {"source_code": "--import CPUTime\n\nbigWord :: String\nbigWord = take 100000 (cycle \"ab\") ++ (take 100000 (cycle \"ba\")) ++ \"c\"\n\nsolve :: String -> String -> String\nsolve [] s = s\nsolve (x:xs) [] = solve xs [x]\nsolve (x:xs) (y:ys) = if x == y then solve xs ys else solve xs (x:y:ys)\n\nmain = do\n s <- getLine\n-- let s = bigWord\n-- t0 <- getCPUTime\n putStrLn (reverse (solve s \"\"))\n-- t1 <- getCPUTime\n-- putStrLn (show (fromInteger (t1 - t0) * 1e-012) ++ \" sec.\")\n"}, {"source_code": "\nsolve xs = solve' xs []\n where solve' xs (s1:s2:stack) | s1 == s2 = solve' xs stack\n solve' (x:xs) stack = solve' xs (x:stack)\n solve' [] stack = reverse stack\n\nmain = do line <- getLine\n putStrLn $ solve line"}, {"source_code": "main=interact g\ng (a:b:s)|a==b=g s\n |null t=[]\n |a==head t=tail t\n |0<1=a:t\n where t=g(b:s)\ng a=a"}, {"source_code": "main :: IO ()\nmain = putStrLn . solve =<< getLine\n\nsolve :: String -> String\nsolve = reverse . foldl go \"\"\n where\n go (y:ys) x | x == y = ys\n go ys x = x : ys\n"}, {"source_code": "main = putStrLn . solve [] =<< getLine\nsolve [] (y:ys) = solve [y] ys\nsolve (x:xs) (y:ys) | x == y = solve xs ys\n | otherwise = solve (y:x:xs) ys\nsolve xs [] = reverse xs\n\n"}, {"source_code": "main = getLine >>= putStrLn . solve\n\nsolve = reverse . foldl f \"\"\nf (y:ys) x | x==y = ys\nf ys x = x:ys\n\n"}, {"source_code": "f (s:ss) (b, (r:rs), dir) | s==r = f ss (b, rs, dir)\n | otherwise = f ss (b, (s:r:rs), dir)\nf (s:ss) (b, rs, dir) = f ss (b, (s:rs), dir)\nf [] (True, (r:rs), dir) = f [r] (False, rs, not dir)\nf [] (b, [], dir) = []\nf [] (False, r, True) = reverse r\nf [] (False, r, False) = r\nmain = do\n l <- getLine\n putStrLn $ f (tail l) (False, [head l], True)\n"}, {"source_code": "proc' line = proc [] line\n\nproc h [] = reverse h\nproc [] [] = []\nproc [] (a:xs) = proc [a] xs\nproc (a:xs) (b:ys) = \n if a==b then\n proc xs ys\n else\n proc (b:a:xs) ys\n\n\nmain = do\n line <- getLine\n putStrLn(proc' line)\n"}, {"source_code": "g(o:p)(a:b)|a==o=g p b|1>0=g(a:o:p)b\ng l r=reverse l\nmain=interact$g\" \""}, {"source_code": "solve [] = []\nsolve (a:b:t) | a==b = solve t\nsolve (a:t) = \n let t' = solve t \n in case t' of\n [] -> [a]\n (b:t) | a==b -> t\n _ -> a:t'\n \nmain = interact solve"}, {"source_code": "main = interact solve\nsolve x = check x []\ncheck [] x = reverse x\ncheck (x:xs) [] = check xs [x]\ncheck (x:xs) (y:ys) = if x==y then check xs ys else check xs (x:y:ys)\n"}, {"source_code": "main=interact$q\"$\"\nq p(x:s)|x==head p=q(tail p)s\n |1<2=q(x:p)s\nq p _=reverse$init p\n"}, {"source_code": "main=interact$q\"$\"\nq(h:p)(x:s)|x==h=q p s|1<2=q(x:h:p)s\nq p _=reverse$init p\n"}, {"source_code": "main = putStrLn . solve \"$\" =<< getLine\n\nsolve ps (x:xs) | x == head ps = solve (tail ps) xs\n | otherwise = solve (x : ps) xs\nsolve ps _ = reverse $ init ps\n"}, {"source_code": "main=interact$q\" \"\nq(h:p)(x:s)|x==h=q p s|1<2=q(x:h:p)s\nq p _=reverse p\n"}, {"source_code": "main=interact$q\" \"\nq(h:p)(x:s)|x==h=q p s|1<2=q(x:h:p)s\nq p _=reverse$p\n"}, {"source_code": "main=putStr.q\"$\"=< if s1 == s2\n then ss\n else s1:s\n s -> s1:s\nshrink s = s\n"}, {"source_code": "solve ys [] = ys\nsolve [] (x:xs) = solve [x] xs\nsolve (y:ys) (x:xs)\n\t| x == y = solve ys xs\n\t| otherwise = solve (x:y:ys) xs\n\nmain = getLine >>= putStrLn . reverse . solve []\n\t\n"}, {"source_code": "\nfix rest [] = reverse rest\nfix rest (x:[]) = fix (x:rest) []\nfix [] (x:y:xs)\n | x == y = fix [] xs\n | otherwise = fix [x] (y:xs)\nfix rest (x:y:xs)\n | x == y = fix (tail rest) ((head rest):xs)\n | otherwise = fix (x:rest) (y:xs)\n\n\nmain :: IO ()\nmain = do\n seq <- getLine\n putStr (fix [] seq)\n"}], "negative_code": [{"source_code": "import Data.List\nmain=interact g\ng s|s==w=s\n |0<1=g w\n where w=map head.filter((==1).length).group$s"}, {"source_code": "main :: IO ()\nmain = putStrLn . solve =<< getLine\n\nsolve :: String -> String\nsolve = fixed . iterate go\n where go (x:yxs@(y:xs)) | x == y = go (dropWhile (==x) xs)\n | otherwise = x : go yxs\n go xs = xs\n\nfixed :: Eq a => [a] -> a\nfixed (x0:xs@(x1:_)) | x0 == x1 = x0\n | otherwise = fixed xs\nfixed [x] = x\nfixed _ = error \"fixed: empty list\"\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . solve =<< getLine\n\nsolve :: String -> String\nsolve = fixed . iterate go\n where go (x:yxs@(y:xs)) | x == y = go $ dropWhile (==x) xs\n | otherwise = x : go yxs\n go xs = xs\n\nfixed :: Eq a => [a] -> a\nfixed (x0:xs@(x1:_)) | x0 == x1 = x0\n | otherwise = fixed xs\nfixed [x] = x\nfixed _ = error \"fixed: empty list\"\n"}], "src_uid": "26f1b8c3cb83603c904e1508df4067f4"} {"source_code": "import Data.Graph\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n [n,m] <- map read . words <$> getLine\n ts <- map (toTuple . map read . words) <$> replicateM m getLine\n let graph = buildG (1,n) ts\n putStrLn . unwords . map show . reverse . topSort $ graph\n\ntoTuple [x,y] = (x,y)", "positive_code": [{"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n [n,m] <- map read . words <$> getLine\n ts <- map (toTuple . map read . words) . lines <$> getContents\n let graph = buildG (1,n) ts\n putStrLn . unwords . map show . reverse . topSort $ graph\n\ntoTuple [x,y] = (x,y)"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}, {"source_code": "import Data.Graph\n\nstrToList = (map (read :: String -> Vertex)).words\n\nmain = do\n s <- getLine\n let [n, m] = strToList s\n t <- getContents\n putStrLn $ unwords $ map show $ reverse $ topSort $ buildG (1, n) (map (\\[a, b] -> (a, b)) (map strToList (lines t)))\n"}], "negative_code": [{"source_code": "import Data.Graph\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n [n,m] <- map read . words <$> getLine\n ts <- map (toTuple . map read . words) . lines <$> getLine\n let graph = buildG (1,n) ts\n putStrLn . unwords . map show . reverse . topSort $ graph\n\ntoTuple [x,y] = (x,y)"}], "src_uid": "412c9de03713ca8b5d1461d0213b8eec"} {"source_code": "import Data.List\nimport Control.Monad\n\nsolve :: [(Int, Int, Int)] -> [(Int, Int, Int)] -> Int\nsolve xs ys = sum $ map best xs\n where best x = minimum $ filter (>= 0) $ map (calc x) ys\n calc (a1, b1, c1) (a2, b2, c2) =\n let p = (a1 + b1) * 2\n q = div (p + b2 - 1) b2\n t = a2 `div` c1\n in if t == 0 then -1\n else c2 * div (q + t - 1) t\n\nmain = do n <- fmap read getLine\n xs <- replicateM n readTriplet\n m <- fmap read getLine\n ys <- replicateM m readTriplet\n print $ solve xs ys\n where readTriplet = do [a, b, c] <- fmap (map read.words) getLine\n return (a, b, c)", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Int\n\nmain :: IO ()\nmain = do\n n <- readLn\n rooms <- replicateM n readInts\n m <- readLn\n papers <- replicateM m readInts\n prices <- forM rooms $ \\[l, w, h] -> do\n candidates <- forM papers $ \\[l', w', price] -> do\n if l' < h\n then return (1234567890 :: Integer)\n else do\n let !h' = l' `quot` h\n !rolls = ((l + w) * 2 - 1) `quot` (w' * h') + 1\n return $! rolls * price\n return $! minimum candidates\n print $ sum prices\n where\n readInts = map read . words <$> getLine\n\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\n\ntype Room = (Int, Int, Int)\ntype Paper = (Int, Int, Int)\n\nsingle :: Room -> Paper -> Maybe Int\nsingle (ra, rb, rh) (h, a, cost) =\n let p = (ra + rb) * 2\n count = (p + a - 1) `div` a\n count' = h `div` rh\n ans = (count + count' - 1) `div` count'\n in if count' == 0 then Nothing\n else Just $ ans * cost\n\nsolve :: [Room] -> [Paper] -> Int\nsolve rooms papers = sum $ map solve' rooms\n where solve' room = minimum $ catMaybes $ map (single room) papers\n\nmain = do\n n <- read `fmap` getLine\n rooms <- replicateM n $ do\n [a, b, h] <- (map read . words) `fmap` getLine\n return (a, b, h)\n\n m <- read `fmap` getLine\n papers <- replicateM m $ do\n [h, a, cost] <- (map read . words) `fmap` getLine\n return (h, a, cost)\n\n let ans = solve rooms papers\n putStrLn $ show ans\n"}, {"source_code": "import Control.Monad\n\n\nparse :: String -> [Int]\nparse stuff = map read (words stuff)\n\nsolve rooms papers = map (solve_one papers) rooms\n\n\nsolve_one papers [a, b, c] = minimum $ map give_price papers\n where give_price [l, w, p] = \n let perim = 2 * (a + b)\n stripes = l `div` c\n segments = perim `ceil` w\n in \n if stripes /= 0\n then (segments `ceil` stripes) * p\n else (maxBound :: Int)\n\n\n\nceil :: Int -> Int -> Int\nceil a b\n | a `rem` b > 0 = 1 + d\n | otherwise = d\n where d = a `div` b\n\n\nmain = do\n n <- getLine\n rooms <- sequence [getLine | _ <- [1.. (read n)]]\n m <- getLine\n papers <- sequence [getLine | _ <- [1.. (read m)]]\n print $ sum $ solve (map parse rooms) (map parse papers)\n"}, {"source_code": "solve ws wps = sum $ map (solve' wps) ws\n\nsolve' wps [h,l] = minimum $ map cost wps\n where\n cost [h',w',c']\n | h > h' = inf\n | otherwise = l `divup` ((h' `div` h) * w') * c'\n inf = 99999999\n divup x y = div (x+y-1) y\n\nmain = do\n n <- fmap read getLine\n ws <- mapM (fmap $ map read . words) (replicate n getLine)\n m <- fmap read getLine\n wps <- mapM (fmap $ map read . words) (replicate m getLine)\n print $ solve (map (\\[x,y,z] -> [z,(x+y)*2]) ws) wps\n\n\n-- vim: set expandtab:\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\nimport System.IO.Error\n\n\nhReadMany :: (Char -> Bool) -> Handle -> IO String\nhReadMany p h = do b <- (p <$> hLookAhead h) `catch` const (return False)\n if b\n then (:) <$> hGetChar h <*> hReadMany p h\n else return \"\"\n\nhSkipSpaces = hReadMany isSpace\nhReadNumeric = hReadMany (\\c -> isDigit c || c `elem` ['.', '-', '+'])\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = do hSkipSpaces stdin\n read <$> hReadNumeric stdin\n\nreadTerm :: IO String\nreadTerm = do hSkipSpaces stdin\n hReadMany (not . isSpace) stdin\n\nceilDiv a b = (a + b - 1) `div` b\n\nmain = do nrooms <- readNum\n rooms <- replicateM nrooms readRoom\n \n npapers <- readNum\n papers <- replicateM npapers readPaper\n\n let values = map (solve papers) rooms\n print (sum values)\n\n where\n readRoom = do width <- readNum\n length <- readNum\n height <- readNum\n return (width + width + length + length, height)\n\n readPaper = do length <- readNum\n width <- readNum\n price <- readNum\n return (length, width, price)\n\nsolve papers (columns, height) = foldl1 min [ effectivePrice p | p <- papers ]\n where\n effectivePrice (length, width, price) | length < height = 100000000\n | otherwise =\n price * (columns `ceilDiv` ((length `div` height) * width))\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\n\ndata Room = Room Int Int Int\n deriving (Eq,Show)\n\ndata Paper = Paper Int Int Int\n deriving (Eq,Show)\n\ndivceil a b = (a + b -1) `div` b\n\n-- return the number of rolls needed\nrolls roomh roomw rooml paperh paperw | paperh < roomh = Nothing\nrolls roomh roomw rooml paperh paperw = Just r\n where\n w = 2*(roomw+rooml)\n r = divceil w ((paperh `div` roomh) * paperw)\n\ncost :: Room -> Paper -> Maybe Int\ncost (Room h l w) (Paper ph pw pc) = fmap (pc*) $ rolls h l w ph pw\n\nminCost :: [Paper] -> Room -> Int\nminCost ps r = minimum $ catMaybes $ map (cost r) ps\n\nmain = do\n n <- fmap read getLine\n rooms <- replicateM n $ do [l,w,h] <- fmap (map read . words) getLine\n return $ Room h l w\n m <- fmap read getLine\n papers <- replicateM m $ do [h,w,c] <- fmap (map read . words) getLine\n return $ Paper h w c\n\n let answer = sum $ map (minCost papers) rooms\n print answer\n"}, {"source_code": "\nimport Maybe (mapMaybe)\n\ntype Room = (Int, Int, Int)\ntype Roll = (Int, Int, Int)\n\nparseRoom :: String -> Room\nparseRoom line = case words line of\n [x, y, z] -> (read x, read y, read z)\n\nparseRoll :: String -> Roll\nparseRoll = parseRoom\n\nsolve :: [Room] -> [Roll] -> Int\nsolve rooms rolls = sum $ map solve' rooms\n where\n solve' room = minimum $ mapMaybe (solve'' room) rolls\n solve'' (l, w, h) (l', w', c)\n | l' >= h = Just $ c * (1 + div (2 * (l+w) - 1) (w' * div l' h))\n | otherwise = Nothing\n\nmain :: IO ()\nmain = do\n lines' <- fmap lines getContents\n let n = read . head $ lines'\n let rooms = map parseRoom . take n . tail $ lines'\n let m = read . head . drop n . tail $ lines'\n let rolls = map parseRoll . take m . tail . drop n . tail $ lines'\n print $ solve rooms rolls\n \n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Control.Monad\n\nsolve :: [(Int, Int, Int)] -> [(Int, Int, Int)] -> Int\nsolve xs ys = sum $ map best xs\n where best x = minimum $ filter (>= 0) $ map (calc x) ys\n calc (a1, b1, c1) (a2, b2, c2) =\n let p = (a1 + b1) * 2\n q = div (p + b2 - 1) b2\n t = a2 `div` c1\n in if t == 0 then -1\n else c2 * div (q + t - 1) t\n\nmain = do n <- fmap readInt BS.getLine\n xs <- replicateM n readTriplet\n m <- fmap readInt BS.getLine\n ys <- replicateM m readTriplet\n print $ solve xs ys\n where readTriplet = do [a, b, c] <- fmap (map readInt . BS.words) BS.getLine\n return (a, b, c)\n readInt x = let Just (int, _) = BS.readInt x\n in int"}, {"source_code": "import Control.Applicative\n\nmain = do n <- read <$> getLine\n rss <- mapM (\\i -> map read <$> words <$> getLine) [1..n]\n m <- read <$> getLine\n wss <- mapM (\\i -> map read <$> words <$> getLine) [1..m]\n print $ solve n rss m wss\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> Int\nsolve _ rss _ wss = sum $ map (solve' wss) rss\nsolve' :: [[Int]] -> [Int] -> Int\nsolve' wss lwh@(l:w:h:_) = minimum $ map (price lwh) $ filter ((h<=).head) wss\n\nprice :: [Int] -> [Int] -> Int\nprice (l:w:h:_) (l':w':p:_) = ((((2*(l+w))`div'`w')*h)`div'`(l'-(mod l' h)))*p\n\ndiv' x y = if q == 0 then p else succ p\n where (p,q) = divMod x y\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nmain = do n <- read <$> getLine\n rss <- mapM (\\i -> map read <$> words <$> getLine) [1..n]\n m <- read <$> getLine\n wss <- mapM (\\i -> map read <$> words <$> getLine) [1..m]\n print $ solve n rss m wss\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> Int\nsolve n rss m wss = sum $ map (solve' wss) rss\nsolve' :: [[Int]] -> [Int] -> Int\nsolve' wss (l:w:h:_) = minimum $ map (price [l,w,h]) $ wss\nprice :: [Int] -> [Int] -> Int\nprice (l:w:h:_) (l':w':p:_) = (((2*(l+w)`div'`w')*h)`div'`(f l' h))*p\n\nf l' h\n | l' >= h = l'-(mod l' h)\n | otherwise = l'\n\ndiv' x y = if q == 0 then p else succ p\n where (p,q) = divMod x y\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n prices <- replicateM n $ do\n [l, w, h] <- readInts\n m <- readLn\n candidates <- replicateM m $ do\n [l', w', price] <- readInts\n let !h' = head $ dropWhile (< h) [l', l' * 2 ..]\n !rolls = (((l + w) * 2 - 1) `quot` (w' * (h' `quot` h)) + 1) * (h' `quot` l')\n return $! rolls * price\n return $! minimum candidates\n print $ sum prices\n where\n readInts = map read . words <$> getLine\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n [l, w, h] <- readInts\n m <- readLn\n candidates <- replicateM m $ do\n [l', w', price] <- readInts\n let !h' = head $ dropWhile (< h) [l', l' * 2 ..]\n !rolls = (((l + w) * 2 - 1) `quot` (w' * (h' `quot` h)) + 1) * (h' `quot` l')\n return $! rolls * price\n print $ minimum candidates * n\n where\n readInts = map read . words <$> getLine\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n [l, w, h] <- readInts\n m <- readLn\n prices <- replicateM n $ do\n candidates <- replicateM m $ do\n [l', w', price] <- readInts\n let !h' = head $ dropWhile (< h) [l', l' * 2 ..]\n !rolls = (((l + w) * 2 - 1) `quot` (w' * (h' `quot` h)) + 1) * (h' `quot` l')\n return $! rolls * price\n return $! minimum candidates\n print $ sum prices\n where\n readInts = map read . words <$> getLine\n\n"}, {"source_code": "import Control.Monad\n\n\nparse :: String -> [Int]\nparse stuff = map read (words stuff)\n\nsolve rooms papers = map (solve_one papers) rooms\n\n\nsolve_one papers [a, b, c] = minimum $ map give_price papers\n where give_price [l, w, p] = \n let perim = 2 * (a + b)\n stripes = l `div` c\n segments = perim `ceil` w\n in \n if stripes /= 0\n then (segments `ceil` stripes) * p\n else 123456789\n-- else (maxBound :: Int)\n\n\n\n-- ceil :: Int -> Int -> Int\nceil a b\n | a `rem` b > 0 = 1 + d\n | otherwise = d\n where d = a `div` b\n\n\nmain = do\n n <- getLine\n rooms <- sequence [getLine | _ <- [1.. (read n)]]\n m <- getLine\n papers <- sequence [getLine | _ <- [1.. (read m)]]\n mapM_ print (solve (map parse rooms) (map parse papers))\n"}, {"source_code": "import Control.Monad\n\n\nparse :: String -> [Int]\nparse stuff = map read (words stuff)\n\nsolve rooms papers = map (solve_one papers) rooms\n\n\nsolve_one papers [a, b, c] = minimum $ map give_price papers\n where give_price [l, w, p] = \n let perim = 2 * (a + b)\n stripes = l `div` c\n segments = perim `ceil` w\n in \n if stripes /= 0\n then (segments `ceil` stripes) * p\n else (maxBound :: Int)\n\n\n\n-- ceil :: Int -> Int -> Int\nceil a b\n | a `rem` b > 0 = 1 + d\n | otherwise = d\n where d = a `div` b\n\n\nmain = do\n n <- getLine\n rooms <- sequence [getLine | _ <- [1.. (read n)]]\n m <- getLine\n papers <- sequence [getLine | _ <- [1.. (read m)]]\n mapM_ print (solve (map parse rooms) (map parse papers))\n"}, {"source_code": "import Control.Monad\n\n\nparse :: String -> [Int]\nparse stuff = map read (words stuff)\n\nsolve rooms papers = map (solve_one papers) rooms\n\n\nsolve_one papers [a, b, c] = {-minimum $ -} map give_price papers\n where give_price [l, w, p] = \n let perim = 2 * (a + b)\n stripes = l `div` c\n segments = perim `ceil` w\n in \n (segments `ceil` stripes) * p\n\n\n\n-- ceil :: Int -> Int -> Int\nceil a b\n | a `rem` b > 0 = 1 + d\n | otherwise = d\n where d = a `div` b\n\n\nmain = do\n n <- getLine\n rooms <- sequence [getLine | _ <- [1.. (read n)]]\n m <- getLine\n papers <- sequence [getLine | _ <- [1.. (read m)]]\n print $ solve (map parse rooms) (map parse papers)\n"}, {"source_code": "import Control.Monad\n\n\nparse :: String -> [Int]\nparse stuff = map read (words stuff)\n\nsolve rooms papers = map (solve_one papers) rooms\n\n\nsolve_one papers [a, b, c] = minimum $ map give_price papers\n where give_price [l, w, p] = \n let perim = 2 * (a + b)\n stripes = l `div` c\n segments = perim `ceil` w\n in \n (segments `ceil` stripes) * p\n\n\n\n-- ceil :: Int -> Int -> Int\nceil a b\n | b == 0 = 12345678987654321\n | a `rem` b > 0 = 1 + d\n | otherwise = d\n where d = a `div` b\n\n\nmain = do\n n <- getLine\n rooms <- sequence [getLine | _ <- [1.. (read n)]]\n m <- getLine\n papers <- sequence [getLine | _ <- [1.. (read m)]]\n mapM_ print (solve (map parse rooms) (map parse papers))\n"}, {"source_code": "solve ws wps = sum $ map (solve' wps) ws\n\nsolve' wps [h,l] = minimum $ map cost wps\n where\n cost [h',w',c']\n | h > h' = inf\n | otherwise = l `div` ((h' `div` h) * w') * c'\n inf = 99999999\n\nmain = do\n n <- fmap read getLine\n ws <- mapM (fmap $ map read . words) (replicate n getLine)\n m <- fmap read getLine\n wps <- mapM (fmap $ map read . words) (replicate m getLine)\n print $ solve (map (\\[x,y,z] -> [x,(y+z)*2]) ws) wps\n\n\n-- vim: set expandtab:\n"}, {"source_code": "import Control.Applicative\n\nmain = do n <- read <$> getLine\n rss <- mapM (\\i -> map read <$> words <$> getLine) [1..n]\n m <- read <$> getLine\n wss <- mapM (\\i -> map read <$> words <$> getLine) [1..m]\n print $ solve n rss m wss\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> Int\nsolve n rss m wss = sum $ map (solve' wss) rss\nsolve' :: [[Int]] -> [Int] -> Int\nsolve' wss (l:w:h:_) = minimum $ map (price [l,w,h]) $ filter ((h<=).head) wss\n\nprice :: [Int] -> [Int] -> Int\nprice (l:w:h:_) (l':w':p:_) = (((2*(l+w)`div'`w')*h)`div'`(l'-(mod l' h)))*p\n\ndiv' x y = if q == 0 then p else succ p\n where (p,q) = divMod x y\n"}], "src_uid": "29639971c98dd98f0292d994d4433e3a"} {"source_code": "import Data.List\nmain = do\n getLine\n s <- getLine >>= return . map read . words :: IO [Int]\n let t x = sum . map (\\k -> if k > x then 1 else 0)\n let l = map (\\x -> 1 + t x s) s\n putStrLn $ unwords . intersperse \" \" $ map show l", "positive_code": [{"source_code": "import Data.Functor ((<$>))\n\nmain :: IO ()\nmain = putStrLn <$> unwords <$> map show =<< solve <$> (map read <$> tail <$> words <$> getContents)\n\nsolve :: [Integer] -> [Integer]\nsolve xs = [ 1 + sum [ 1 | y <- xs, y > x ] | x <- xs ]\n"}, {"source_code": "import Data.Ord\nimport Data.List\nimport Data.Function\nmain = interact $ unwords . map show . solve . map read . tail . words\nsolve :: [Int] -> [Int]\nsolve = map snd . sort .\n concat . snd . mapAccumL f 1 .\n groupBy ((==) `on` snd) .\n sortBy (flip $ comparing snd) .\n zip [1..]\nf n xs = (n + length xs, map (flip (,) n . fst) xs)\n"}, {"source_code": "import Data.List\nimport Data.Function\n\nf :: [Int] -> [Int]\nf xs = map snd . sortBy (compare `on` fst) . g 1 $ xxs'\n where xxs' = groupBy ((==) `on` snd) . reverse . sortBy (compare `on` snd) . zip [1..] $ xs\n g _ [] = []\n g place (ys:yys) = map (\\(num, rate) -> (num, place)) ys ++ g (place + length ys) yys\n \nmain = getLine >> fmap (map read . words) getLine >>= putStrLn . intercalate \" \" . map show . f"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\nmymax s = snd $ head $ filter (\\z-> fst z ==m) $ zip s [1..]\n\twhere m = maximum s\n\nmyfunc r x = zip (map snd x) (repeat r)\n \nmain=do\t \n\tn<- read <$> getLine:: IO Int \n\ts<- map read. words <$> getLine ::IO [Int]\n\tlet t= groupBy (\\a b-> fst a==fst b) $ reverse $ sort $ zip s [1..]\n\tlet t1= scanl (+) 1 $ map length t \n\tputStrLn $ intercalate \" \" $ map show $ map snd $ sort $ concat $ zipWith myfunc t1 t\n"}, {"source_code": "type Input = [Int]\ntype Output = [Int]\n\nparse :: String -> Input\nparse contents = rs where [_, rs] = map (map read . words) . lines $ contents\n\nsolve :: Input -> Output\nsolve rs = map rank rs\n where rank r = 1 + length (filter (> r) rs)\n\npretty :: Output -> String\npretty = unwords . map show\n\nmain :: IO ()\nmain = putStrLn . pretty . solve . parse =<< getContents\n"}, {"source_code": "import Data.List\nimport Data.Function\nsortOn' fun = sortBy (compare `on` fun)\nmain = interact $ unwords.map (show.snd).sortOn' fst.f.zip [1..].map read.words.last.lines\nhs = snd.head\nf xs = g 1 (hs xs).reverse.sortOn' snd $ xs\ng _ _ [] = []\ng pos val xs = let (front,end) = span (\\x->val==snd x) xs\n n = length front\n begin = zip (map fst front) (replicate n pos) \n in begin ++ (g (pos+n) (if end==[] then 0 else hs end) end)\n \n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\nsolve :: Int -> [[(Int, Int)]] -> [(Int, Int)]\nsolve _ [] = []\nsolve n (l:xs) = [(n, x) | x <- map snd l] ++ (solve (n + length l) xs)\n\nmain = do\n _ <- getLine\n s <- getInts \n let \n res = L.sortBy (compare `F.on` snd) . solve 0 . reverse . L.groupBy ((==) `F.on` fst) . L.sortBy (compare `F.on` fst) $ (zip s [1..])\n forM_ res $ \\(r, i) -> putStr $ (show $ r + 1) ++ \" \"\n"}, {"source_code": "main :: IO()\nmain = putStrLn . unwords . map show . solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> [Int]\nsolve a = map (\\x -> 1 + length (filter (> x) a)) a\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\n--------------------------------\n\ncreateMapList :: [[Int]] -> [(Int, Int)]\ncreateMapList xs = createMapList' xs 0\n\twhere\n\t\tcreateMapList' [] _ = []\n\t\tcreateMapList' (x:xs) higher = (head x, higher) : createMapList' xs (higher + length x)\n\n--------------------------------\n\nmain = do\n\n\tn <- fmap read $ getLine :: IO Int\n\tratings <- fmap (map read . words) $ getLine :: IO [Int]\n\n\tlet\n\t\tsorted_ratings =\n\t\t\tcreateMapList $\n\t\t\tgroup $\n\t\t\tsortBy (\\a b -> compare b a) ratings\n\n\t\trating_map = Map.fromList sorted_ratings\n\n\tputStrLn $\n\t\tintercalate \" \" $ map show $ mapPositions rating_map ratings \n\n--------------------------------\n\nmapPositions :: Map.Map Int Int -> [Int] -> [Int]\nmapPositions _ [] = []\nmapPositions map (x:xs)\n\t| higher == Nothing = 0 : mapPositions map xs\n\t| otherwise = (1 + fromJust higher) : mapPositions map xs\n\twhere\n\t\thigher = Map.lookup x map"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n as <- getInts\n\n let\n r = map snd $ sort $ concat $ map f $ groupBy ((==) `on` (fst . fst)) $ zip (reverse $ sort $ zip as [1..]) [1..]\n where\n f :: [((Int, Int), Int)] -> [(Int, Int)]\n f g = zip (map (snd . fst) g) (repeat m)\n where\n m = minimum $ map snd g\n\n putStrLn $ unwords $ map show r\n"}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\n\nmain = getInts >>= putStrLn . intercalate \" \" . map show . solve\n\nsolve :: [Int] -> [Int]\nsolve (n:xs) = map snd . sort $ zip is es\n where (ys, is) = unzip . reverse . sort $ zip xs [0..]\n (zs, es) = unzip . scanl1 min $ zip ys [1,2..]\n"}, {"source_code": "main = do\n num <- getLine\n ratings <- getLine\n mapM_ pwSpace $ positions (read num) (readNums ratings)\n putChar '\\n'\n\npwSpace n = do\n putStr $ (show n) ++ \" \"\n\nreadNums :: String -> [Int]\nreadNums s = map read $ words s\n\npositions :: Int -> [Int] -> [Int]\npositions n rs = map (getPos rs) [1..n]\n\ngetPos :: [Int] -> Int -> Int\ngetPos rs x = 1 + (length $ filter (\\y -> y > (rs !! (x-1))) rs)\n"}, {"source_code": "import Data.List\nanswer::[Int]->[Int]\nanswer a = [getNum n a | n <- (enumFromTo 0 ((length a) - 1))]\ngetNum::Int -> [Int] -> Int\ngetNum n a = 1 + (length (filter ((a !! n)<) a)) \nmain = do\n w <- getLine\n w0 <- getLine\n let a = [read n::Int|n<-(words w0)]\n putStrLn $ intercalate \" \" (map show (answer a))\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine>>(solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve xs = let bs = zip [1..] xs; sbs = sortBy ( flip (compare `on` snd)) bs; gsbs=groupBy ((==) `on` snd) sbs in putStr $ unwords $ map (\\(a,b)->show b) $ sortBy (compare `on` fst) $ concat $ slv1 gsbs\nslv1 (xs:xss)= map fst $ scanl (\\(bs,b) as->(map(\\(c1,c2)->(c1,1+b)) as, b+length as) ) (map (\\(a,b) ->(a,1)) xs,length xs) xss"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n n <- (readLn :: IO Int)\n xs <- getLine >>= return .map (read :: String -> Int) . words\n let as = fst . foldr (\\ (a,b) (cs,c) -> ((a,c):cs, b+c)) ([],1) . map (\\x -> (head x, length x)) . group . sort $ xs\n bs = map ( fromJust . (flip lookup) as ) xs\n putStrLn $ concat $ intersperse \" \" $ map show bs \n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = getLine >> getLine >>= mapM_ (putStr . (++ \" \") . show) . rank . map read . words >> putStrLn \"\"\n\nrank :: [Int] -> [Int]\nrank a = [1 + length (filter (> x) a) | x <- a]\n"}, {"source_code": "main=getLine>>getLine>>=putStrLn.unwords.(map show).solve.(map read).words\nsolve::[Int]->[Int]\nsolve l = map (\\x->1+(length$filter(x<) l)) l"}], "negative_code": [{"source_code": "main=getLine>>getLine>>=putStrLn.unwords.(map show).solve.(map read).words\nsolve::[Int]->[Int]\nsolve l = map (\\x->length$filter(x<) l) l\n"}, {"source_code": "import Data.List\nmain = do\n getLine\n s <- getLine >>= return . map read . words :: IO [Int]\n let t x = sum . map (\\k -> if k > x then 1 else 0)\n let l = map (\\x -> 1 + t x s) s\n putStrLn $ intersperse ' ' . unwords $ map show l"}], "src_uid": "a5edbf422616cdac35e95a4f07efc7fd"} {"source_code": "import Data.List\n\nmain = do\n nk <- getLine\n skillValues <- getLine\n putStrLn $ show $ solve (read $ last $ words nk) $ map read (words skillValues)\n\nsolve :: Int -> [Int] -> Int\nsolve k xss =\n let moduli = sort $ map ((10-) . (`mod` 10)) $ filter (/= 100) xss\n initialLevel = sum $ map (`quot` 10) xss\n filteredModuliSums = filter (<= k) $ scanl1 (+) moduli\n numFiltered = length filteredModuliSums\n numUsed = if numFiltered == 0 then\n 0\n else\n last filteredModuliSums\n remainingSlots = (sum $ map (100-) xss) - numUsed\n remainingLevels = remainingSlots `quot` 10\n remainingSpend = k - numUsed\n in\n if numFiltered /= length moduli then\n numFiltered + initialLevel\n else\n initialLevel + numFiltered + min (remainingSpend `quot` 10) remainingLevels\n", "positive_code": [{"source_code": "import Debug.Trace\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:k:a) = let b = getRem a (replicate 11 0)\n in divide k b 0\n\naddToList :: [Int] -> Int -> Int -> [Int]\naddToList (a:s) 0 v = (a + v) : s\naddToList (a:s) i v = a : (addToList s (i - 1) v)\n\ngetRem :: [Int] -> [Int] -> [Int]\ngetRem [] cnt = cnt\ngetRem (a:s) cnt = let next = (addToList (addToList cnt 0 (div a 10)) 10 (div (100 - (a + (rem (10 - (rem a 10)) 10))) 10))\n in if mod a 10 == 0 then getRem s next else getRem s (addToList next (10 - (rem a 10)) 1)\n\ndivide :: Int -> [Int] -> Int -> Int\ndivide k (b:bs) 0 = b + (divide k bs 1)\ndivide 0 (b:bs) _ = 0\ndivide k [] _ = 0\ndivide k (b:bs) idx | (div k idx) >= b = b + (divide (k - b * idx) bs (idx + 1))\n | otherwise = div k idx\n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n\t[n, k] <- (map read . words) `fmap` getLine\n\tas <- (map read . words) `fmap` getLine\n\n\tlet\n\t\tr = sum $ map (`div` 10) as \n\t\tsums = takeWhile (<= k) $ scanl1 (+) $ sort $ filter (/= 10) $ map (\\a -> 10 - a `mod` 10) as\n\t\tr' = if null sums then 0 else length sums\n\t\tr'' = if null sums then k else k - (last sums)\n\n\t\tt = r + r' + (r'' `div` 10)\n\n\t\tans = if t >= 10 * n then 10 * n else t\n\n\tprint ans\n"}, {"source_code": "import Data.List\n\nadd3 (a,b,c) (x,y,z) = (a+x,b+y,c+z)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k levels =\n let \n -- the base level\n a0 = sum [ div a 10 | a <- levels ] :: Int\n\n -- sort by 10 - remainder mod 10\n sorted = sort [ (10-r, a) | a <- levels, let r = mod a 10 ]\n\n loop :: Int -> (Int,Int) -> [(Int,Int)] -> (Int, (Int,Int))\n loop k acc [] = (k, acc)\n loop k acc@(da, tens) ( (r,a) : rest )\n | k <= 0 = (0, acc)\n | r == 10 = let dtens = 10 - div a 10 in\n loop k (da, tens+dtens) rest\n | r <= k = let dtens = 9 - div a 10 in\n loop (k-r) (da+1, tens+dtens) rest\n | otherwise = (k, acc)\n\n (k',(da, tens)) = loop k (0,0) sorted :: (Int,(Int,Int))\n\n answer = min (n*10) (a0 + da + min tens (div k' 10))\n in answer\n\nmain = do\n (n : k : levels) <- fmap (map read . words) getContents\n print $ solve n k levels\n\ntest1 = print $ solve 2 4 [7,9]\n\ntest2 = print $ solve 3 8 [17, 15, 19]\n\ntest3 = print $ solve 2 2 [99, 100]\n\ntest4 = print $ solve 231 100 $ replicate 231 100\n\ntest5 = print $ solve 100 10000 $ replicate 100 0\n\n"}, {"source_code": "import Data.List\n\nmain = do\n\tl1 <- getLine\n\tn : k : [] <- return $ map (read :: String->Int) $ words l1\n\tl2 <- getLine\n\tv <- return $ map (read :: String->Int) $ words l2\n\tputStr $ show $ solve n k v\n\nsolve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where\n\trems = sort $ map (\\x -> 10 - x `mod` 10) $ filter (\\x -> x `mod` 10 > 0) v\n\trem_groups = sum $ map (\\x -> 10 - (x + 9) `div` 10) v\n\tscore0 = sum $ map (`div` 10) v\n\t(rem' , score1) = take_remainders k rems\n\n\ntake_remainders n [] = (n, 0)\ntake_remainders n (h : t) \n\t\t| n >= h\t= let (n', s') = take_remainders (n - h) t in (n', 1 + s')\n\t\t| otherwise\t= (n, 0)"}, {"source_code": "import Data.Array\ngetPlus::Int -> [Int]-> Int\ngetPlus k a = getPlus0 k a 1\ngetPlus0::Int -> [Int] -> Int -> Int\ngetPlus0 k [] n = 0\ngetPlus0 k (a:as) n | k >= an = a + getPlus0 (k-an) as (n+1)\n | otherwise = m\n where an = a*n\n m = k `div` n\nmakeData::[Int] -> [(Int,Int)]\nmakeData [] = [] \nmakeData (a:as) | d == 10 = makeData as\n | r == 0 = (10,10-d):(makeData as)\n | otherwise = [(10-r,1),(10,9-d)]++(makeData as) \n where d = a `div` 10\n r = a `rem` 10\ngetRate ::[Int] -> Int\ngetRate a= foldl (\\x y -> x + (y `div` 10)) 0 a \nmain = do\n w0 <- getLine\n let [n,k] = [read n::Int|n<-(words w0)]\n w1 <- getLine\n let a = [read n::Int| n<-(words w1)]\n let preSum = getRate a\n print (preSum + (getPlus k (elems (accumArray (+) 0 (1,10) (makeData a)))))\n \n"}, {"source_code": "import Data.List\n\nperlevel :: Integral a => a\nperlevel = 10\n\nmaxlevel :: Integral a => a\nmaxlevel = 100\n\nrating :: (Integral a) => [a] -> a -> a\nrating xs units =\n let xs' = sortBy perlevelcmp xs\n (incrxs, rest) = foldr step ([], units) xs'\n in (min (foldr (\\v s -> s + (maxlevel - v)) 0 incrxs) rest) `div` perlevel +\n (foldr (\\v s -> s + v `div` perlevel) 0 incrxs)\n where step v (vs, units) | v < maxlevel && v `mod` perlevel + units >= perlevel =\n ((v + perlevel - v `mod` perlevel):vs, units - (perlevel - v `mod` perlevel))\n | otherwise = (v:vs, units)\n\nperlevelcmp l r = compare (l `mod` perlevel) (r `mod` perlevel)\n\nmain = do\n inp <- getContents\n let ls = lines inp\n k = read $ (words $ head ls) !! 1\n xs = map read $ words $ ls !! 1 :: [Int]\n putStrLn $ show $ rating xs k\n"}], "negative_code": [{"source_code": "import Data.List (sort)\n\nmain = do\n\t[n, k] <- (map read . words) `fmap` getLine\n\tas <- (map read . words) `fmap` getLine\n\n\tlet\n\t\tr = sum $ map (`div` 10) as \n\t\tsums = takeWhile (<= k) $ scanl1 (+) $ reverse $ sort $ filter (/= 10) $ map (\\a -> 10 - a `mod` 10) as\n\t\tr' = if null sums then 0 else length sums\n\t\tr'' = if null sums then k else k - (last sums)\n\n\t\tt = r + r' + (r'' `div` 10)\n\n\t\tans = if t >= 10 * n then 10 * n else t\n\n\tprint ans\n"}, {"source_code": "\nimport Data.List\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k levels =\n let \n -- the base level\n a0 = sum [ div a 10 | a <- levels ]\n -- sort by 10 - remainder mod 10\n sorted = map fst $ sort [ (10 - mod a 10, a) | a <- levels ]\n sums = scanl (+) 0 sorted\n (s,i) = last $ takeWhile (\\(s,i) -> s <= k) (zip sums [0..])\n in a0 + i + (div (k-s) 10)\n\nmain = do\n (n : k : levels) <- fmap (map read . words) getContents\n print $ solve n k levels\n\ntest1 = print $ solve 2 4 [7,9]\n\ntest2 = print $ solve 3 8 [17, 15, 19]\n\ntest3 = print $ solve 2 2 [99, 100]\n\n"}, {"source_code": "\nimport Data.List\n\nadd3 (a,b,c) (x,y,z) = (a+x,b+y,c+z)\n\n-- solve :: Int -> Int -> [Int] -> \nsolve n k levels =\n let \n -- the base level\n a0 = sum [ div a 10 | a <- levels ]\n -- sort by 10 - remainder mod 10\n sorted = sort [ (10 - r, q', if r == 0 then 0 else 1)\n | a <- levels\n , let (q,r) = divMod a 10\n , let q' = 10-q - (if r == 0 then 0 else 1)\n ]\n sums = scanl add3 (0,0,0) sorted\n (s,tens,i) = last $ takeWhile (\\(s,_,_) -> s <= k) sums\n -- tens = # of tens available\n in (a0 + i + min tens (div (k-s) 10)) -- , a0, i, tens)\n\nmain = do\n (n : k : levels) <- fmap (map read . words) getContents\n print $ solve n k levels\n\ntest1 = print $ solve 2 4 [7,9]\n\ntest2 = print $ solve 3 8 [17, 15, 19]\n\ntest3 = print $ solve 2 2 [99, 100]\n\ntest4 = print $ solve 231 100 $ replicate 231 100\n\n"}, {"source_code": "import Data.List\n\nmain = do\n\tl1 <- getLine\n\tn : k : [] <- return $ map (read :: String->Int) $ words l1\n\tl2 <- getLine\n\tv <- return $ map (read :: String->Int) $ words l2\n\tputStr $ show $ solve n k v\n\nsolve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where\n\trems = sort $ map (\\x -> 10 - x `mod` 10) v\n\trem_groups = sum $ map (\\x -> 10 - (x + 9) `div` 10) v\n\tscore0 = sum $ map (`div` 10) v\n\t(rem' , score1) = take_remainders k rems\n\n\ntake_remainders n [] = (n, 0)\ntake_remainders n (h : t) \n\t\t| n >= h\t= let (n', s') = take_remainders (n - h) t in (n', 1 + s')\n\t\t| otherwise\t= (n, 0)"}, {"source_code": "import Data.List\n\nmain = do\n\tl1 <- getLine\n\tn : k : [] <- return $ map (read :: String->Int) $ words l1\n\tl2 <- getLine\n\tv <- return $ map (read :: String->Int) $ words l2\n\tputStr $ show $ solve n k v\n\nsolve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where\n\trems = sort $ map (\\x -> 10 - x `mod` 10) v\n\trem_groups = sum $ map (\\x -> 10 - (x + 9) `div` 10) $ filter (< 100) v\n\tscore0 = sum $ map (`div` 10) v\n\t(rem' , score1) = take_remainders k rems\n\n\ntake_remainders n [] = (n, 0)\ntake_remainders n (h : t) \n\t\t| n >= h\t= let (n', s') = take_remainders (n - h) t in (n', 1 + s')\n\t\t| otherwise\t= (n, 0)"}, {"source_code": "import Data.List\n\nmain = do\n\tl1 <- getLine\n\tn : k : [] <- return $ map (read :: String->Int) $ words l1\n\tl2 <- getLine\n\tv <- return $ map (read :: String->Int) $ words l2\n\tputStr $ show $ solve n k v\n\nsolve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where\n\trems = sort $ map (\\x -> 10 - x `mod` 10) $ filter (< 100) v\n\trem_groups = sum $ map (\\x -> 10 - (x + 9) `div` 10) v\n\tscore0 = sum $ map (`div` 10) v\n\t(rem' , score1) = take_remainders k rems\n\n\ntake_remainders n [] = (n, 0)\ntake_remainders n (h : t) \n\t\t| n >= h\t= let (n', s') = take_remainders (n - h) t in (n', 1 + s')\n\t\t| otherwise\t= (n, 0)"}, {"source_code": "import Data.List\n\nmain = do\n nk <- getLine\n skillValues <- getLine\n putStrLn $ show $ solve (read $ last $ words nk) $ map read (words skillValues)\n\nsolve :: Int -> [Int] -> Int\nsolve k xss =\n let moduli = sort $ map ((10-) . (`mod` 10)) $ filter (/= 100) xss\n initialLevel = sum $ map (`quot` 10) xss\n filteredModuliSums = filter (<= k) $ scanl1 (+) moduli\n numFiltered = length filteredModuliSums\n remainingSlots = (sum $ map (100-) moduli) - last filteredModuliSums\n remainingLevels = remainingSlots `quot` 10\n remainingSpend = k - last filteredModuliSums\n in\n if numFiltered /= length moduli then\n numFiltered + initialLevel\n else\n initialLevel + numFiltered + min (remainingSpend `quot` 10) remainingLevels\n"}, {"source_code": "import Data.List\n\nperlevel :: Integral a => a\nperlevel = 10\n\nrating :: (Integral a) => [a] -> a -> a\nrating xs units =\n let xs' = reverse $ sort $ map (`mod` perlevel) xs\n units' = units `mod` perlevel\n (rat, rest) = count 0 xs' units'\n in rat + (rest `div` perlevel) + foldr (\\v r -> r+(v `div` perlevel)) 0 xs\n where count cur [] k = (cur, k)\n count cur (v:vs) k | v+k >= perlevel = count (cur+1) vs (k-(perlevel-v))\n | otherwise = (cur, k)\n\nmain = do\n inp <- getContents\n let ls = lines inp\n k = read $ (words $ head ls) !! 1\n xs = map read $ words $ ls !! 1 :: [Int]\n putStrLn $ show $ rating xs k\n"}, {"source_code": "import Data.List\n\nperlevel :: Integral a => a\nperlevel = 10\n\nrating :: (Integral a) => [a] -> a -> a\nrating xs units =\n let xs' = reverse $ sort $ map (`mod` perlevel) xs\n (rat, rest) = count 0 xs' units\n in rat + (rest `div` perlevel) + foldr (\\v r -> r+(v `div` perlevel)) 0 xs\n where count cur [] k = (cur, k)\n count cur (v:vs) k | v+k >= perlevel = count (cur+1) vs (k-(perlevel-v))\n | otherwise = (cur, k)\n\nmain = do\n inp <- getContents\n let ls = lines inp\n k = read $ (words $ head ls) !! 1\n xs = map read $ words $ ls !! 1 :: [Int]\n putStrLn $ show $ rating xs k\n"}, {"source_code": "import Data.List\n\nperlevel :: Integral a => a\nperlevel = 10\n\nmaxlevel :: Integral a => a\nmaxlevel = 100\n\nrating :: (Integral a) => [a] -> a -> a\nrating xs units =\n let xs' = reverse $ sortBy (\\l r -> compare (l `div` perlevel) (r `div` perlevel)) xs\n (incrxs, rest) = foldl step ([], units) xs'\n (rs', _) = foldl step' ([], rest) incrxs\n in sum $ map (`div` perlevel) rs'\n where step (vs, units) v | v < maxlevel && v `mod` perlevel + units >= perlevel =\n ((v + perlevel - v `mod` perlevel):vs, units - (perlevel - v `mod` perlevel))\n | otherwise = (v:vs, units)\n step' (vs, units) v =\n let incr = min (maxlevel - v) units\n in ((v+incr):vs, units-incr)\n\nmain = do\n inp <- getContents\n let ls = lines inp\n k = read $ (words $ head ls) !! 1\n xs = map read $ words $ ls !! 1 :: [Int]\n putStrLn $ show $ rating xs k\n"}], "src_uid": "b4341e1b0ec0b7341fdbe6edfe81a0d4"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata Tree = Node Int Char Tree Tree | Nil\n\ngetNum :: Tree -> Int\ngetNum Nil = 1\ngetNum (Node num _ _ _) = num\n\nmain :: IO ()\nmain = do\n [k] <- getInts\n s <- C.getLine\n let t = change (2 ^ (k - 1)) s\n where change 1 str = C.take 1 str\n change i str = C.concat [change (i `div` 2) s2, s1]\n where (s1, s2) = C.splitAt i str\n merge ch l r = Node num ch l r\n where num = case ch of\n '0' -> getNum l\n '1' -> getNum r\n _ -> getNum l + getNum r\n build i\n | i <= 2 ^ k - 1 = merge (C.index t (i - 1)) l r\n | otherwise = Nil\n where l = build (i * 2)\n r = build (i * 2 + 1)\n update _ Nil _ = error \"\"\n update ch (Node _ _ ls rs) [] = merge ch ls rs\n update ch (Node _ char ls rs) (p : ps) = merge char ls' rs'\n where ls' = if p == 0 then update ch ls ps else ls\n rs' = if p == 1 then update ch rs ps else rs\n [q] <- getInts\n (output', _) <- foldM (\\(output, tree) _ -> do\n [ps, cs] <- C.words <$> C.getLine\n let changeIndex i target\n | target <= i = i - 1 + target\n | otherwise = changeIndex (i `div` 2) (target - i)\n changeIndex' i\n | i <= 1 = []\n | otherwise = (i .&. 1) : changeIndex' (i `div` 2)\n p = changeIndex (2 ^ (k - 1)) $ parseInt ps\n (c : _) = C.unpack cs\n tree' = update c tree $ reverse $ changeIndex' p\n return $ (output `mappend` intDec (getNum tree') `mappend` charUtf8 '\\n', tree')) (mempty, build 1) $ replicate q ()\n hPutBuilder stdout output'\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Bits\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n k <- readLn :: IO Int\r\n s <- getLine\r\n q <- readLn :: IO Int\r\n qs <- replicateM q $ do\r\n [p, c] <- words <$> getLine\r\n return (read p, head c) :: IO (Int, Char)\r\n let n = 2 ^ k\r\n pos x = h + (h - 1) `xor` (y - h)\r\n where y = n - x\r\n h = 1 `shiftL` (finiteBitSize y - countLeadingZeros y - 1)\r\n getf '0' = const\r\n getf '1' = const id\r\n getf _ = (+)\r\n ans :: forall s. ST s [Int]\r\n ans = do\r\n f :: STUArray s Int Char <- newArray (1, n) 'x'\r\n b :: STUArray s Int Int <- newArray (1, 2 * n) 1\r\n let upd :: Int -> ST s ()\r\n upd i | i < 1 = return ()\r\n upd i = do\r\n c <- readArray f i\r\n liftM2 (getf c) (readArray b $ i * 2) (readArray b $ i * 2 + 1) >>= writeArray b i\r\n upd $ i `div` 2\r\n forM (zip [1..] s ++ qs) $ \\(p, c) -> do\r\n let i = pos p\r\n writeArray f i c\r\n upd i\r\n readArray b 1\r\n putStr $ unlines $ map show $ drop (n - 1) $ runST ans\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: Int -> String -> [(Int, Char)] -> [Int]\r\nsolve k s' qs =\r\n runST $ do\r\n let n = 1 `shift` k :: Int\r\n s <- newListArray (0, n-2) s' :: ST s (STUArray s Int Char)\r\n dp <- newArray (1, 2 * n) 1 :: ST s (STUArray s Int Int)\r\n\r\n let\r\n update k = do\r\n x0 <- readArray dp (2*k+1)\r\n x1 <- readArray dp (2*k)\r\n c <- readArray s (n-1-k)\r\n let r = case c of\r\n '0' -> x0\r\n '1' -> x1\r\n '?' -> x0 + x1\r\n writeArray dp k r\r\n\r\n forM_ [0..n-2] $ \\i -> do\r\n let k = n-1-i\r\n update k\r\n\r\n let\r\n runqs [] = return []\r\n runqs ((i,c):qs) = do\r\n writeArray s i c\r\n go (n-1-i)\r\n r <- readArray dp 1\r\n rs <- runqs qs\r\n return $ r : rs\r\n\r\n go 0 = return ()\r\n go k = update k >> go (k `div` 2)\r\n\r\n runqs qs\r\n\r\nmain = do\r\n k <- parseInt <$> BS.getLine\r\n s <- dropWhile isSpace . BS.unpack <$> BS.getLine\r\n qn <- parseInt <$> BS.getLine\r\n qs <- replicateM qn $ do\r\n [p,c] <- map BS.unpack . BS.words <$> BS.getLine\r\n return (read p - 1, head c)\r\n let rs = solve k s qs\r\n putStr . unlines . map show $ rs\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata Tree = Node Int Char Tree Tree | Nil\n\ngetNum :: Tree -> Int\ngetNum Nil = 1\ngetNum (Node num _ _ _) = num\n\nputTree :: Tree -> IO ()\nputTree Nil = return ()\nputTree (Node num ch ls rs) = do\n putStrLn $ show num ++ \" ch:\" ++ show ch\n putTree ls\n putTree rs\n\nmain :: IO ()\nmain = do\n [k] <- getInts\n s <- C.getLine\n let t = change (2 ^ (k - 1)) s\n where change 1 str = C.take 1 str\n change i str = C.concat [change (i `div` 2) s2, s1]\n where (s1, s2) = C.splitAt i str\n merge ch l r = Node num ch l r\n where num = case ch of\n '0' -> getNum l\n '1' -> getNum r\n _ -> getNum l + getNum r\n build i\n | i <= 2 ^ k - 1 = merge (C.index t (i - 1)) l r\n | otherwise = Nil\n where l = build (i * 2)\n r = build (i * 2 + 1)\n changeIndex prev i target\n | target <= prev + i = i - 1 + target - prev\n | otherwise = changeIndex (prev + i) (i `div` 2) target\n update _ Nil _ = error \"\"\n update ch (Node _ _ ls rs) 1 = merge ch ls rs\n update ch (Node _ char ls rs) target = merge char ls' rs'\n where target' = target `div` 2\n ls' = if even target then update ch ls target' else ls\n rs' = if odd target then update ch rs target' else rs\n [q] <- getInts\n (output', _) <- foldM (\\(output, tree) _ -> do\n [ps, cs] <- C.words <$> C.getLine\n let p = changeIndex 0 (2 ^ (k - 1)) $ parseInt ps\n (c : _) = C.unpack cs\n tree' = update c tree p\n -- putStrLn $ \"p:\" ++ show p\n -- putTree tree'\n return $ (output `mappend` intDec (getNum tree') `mappend` charUtf8 '\\n', tree')) (mempty, build 1) $ replicate q ()\n hPutBuilder stdout output'\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata Tree = Node Int Char Tree Tree | Nil\n\ngetNum :: Tree -> Int\ngetNum Nil = 1\ngetNum (Node num _ _ _) = num\n\nputTree :: Tree -> IO ()\nputTree Nil = return ()\nputTree (Node num ch ls rs) = do\n putStrLn $ show num ++ \" ch:\" ++ show ch\n putTree ls\n putTree rs\n\nmain :: IO ()\nmain = do\n [k] <- getInts\n s <- C.getLine\n let t = change (2 ^ (k - 1)) s\n where change 1 str = C.take 1 str\n change i str = C.concat [change (i `div` 2) s2, s1]\n where (s1, s2) = C.splitAt i str\n merge ch l r = Node num ch l r\n where num = case ch of\n '0' -> getNum l\n '1' -> getNum r\n _ -> getNum l + getNum r\n build i\n | i <= 2 ^ k - 1 = merge (C.index t (i - 1)) l r\n | otherwise = Nil\n where l = build (i * 2)\n r = build (i * 2 + 1)\n changeIndex prev i target\n | target <= prev + i = i - 1 + target - prev\n | otherwise = changeIndex (prev + i) (i `div` 2) target\n update _ Nil _ = error \"\"\n update ch (Node _ _ ls rs) 1 = merge ch ls rs\n update ch (Node _ char ls rs) target = merge char ls' rs'\n where target' = target `div` 2\n ls' = if even target then update ch ls target' else ls\n rs' = if odd target then update ch rs target' else rs\n [q] <- getInts\n (output', _) <- foldM (\\(output, tree) _ -> do\n [ps, cs] <- C.words <$> C.getLine\n let p = changeIndex 0 (2 ^ (k - 1)) $ parseInt ps\n (c : _) = C.unpack cs\n tree' = update c tree p\n putStrLn $ \"p:\" ++ show p\n putTree tree'\n return $ (output `mappend` intDec (getNum tree') `mappend` charUtf8 '\\n', tree')) (mempty, build 1) $ replicate q ()\n hPutBuilder stdout output'\n"}], "src_uid": "0eee4b8f074e02311329d5728138c7fe"} {"source_code": "import Control.Monad (replicateM, replicateM_)\n\nreadSizes :: IO [Int]\nreadSizes = (map read) . words <$> getLine\n\nreadStrings :: IO [String]\nreadStrings = readSizes >>= \\ [n, _] -> \n replicateM n getLine\n\nare1CharAway :: String -> String -> Bool\nare1CharAway s1 s2 = foldl accumulate 0 (zip s1 s2) <= 1\n where\n accumulate = \\ acc (c1, c2) -> acc + if c1 == c2 then 0 else 1\n\ncheckString :: String -> [String] -> Bool\ncheckString s ss = all (are1CharAway s) ss\n\nreplaceChar :: Int -> Char -> String -> String\nreplaceChar idx c xs = [if idx == i then c else x | (x, i) <- zip xs [0..]]\n\npermutateString :: String -> [String]\npermutateString xs = [replaceChar idx c xs | idx <- [0..m], c <- enumFromTo 'a' 'z']\n where m = length xs - 1\n\nsolve :: [String] -> String\nsolve xss = if length ans > 0 then head ans else \"-1\"\n where\n template = head xss\n ans = filter (\\xs -> checkString xs xss) (permutateString template)\n\nmain =\n read <$> getLine >>= \\t ->\n replicateM_ t (\n readStrings >>= \\xss ->\n putStrLn $ solve xss\n )", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\ndiff xs ys = sum $ zipWith (\\x y -> if x /= y then 1 else 0) xs ys\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : _ <- map read . words <$> getLine\n as <- replicateM n getLine\n putStrLn\n $ case\n filter (\\xs -> all (\\ys -> diff xs ys <= 1) as)\n . cands\n . head\n $ as\n of\n [] -> \"-1\"\n vs -> head vs\n\ncands :: String -> [String]\ncands [] = []\ncands (x : xs) = [ y : xs | y <- ['a' .. 'z'] ] ++ [ x : y | y <- cands xs ]\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Maybe\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:m:_) <- map read . words <$> getLine\n as <- replicateM n getLine\n putStrLn $ fromMaybe \"-1\" (solve as)\n\nsolve as =\n listToMaybe\n [ s\n | let a = head as\n , i <- [0 .. length a - 1]\n , c <- (!! i) <$> as\n , let s = take i a ++ c : drop (i + 1) a\n , all ((<= 1) . length . filter (== False) . zipWith (==) s) as\n ]"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/F\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\n\n\nspyString :: Int -> [String] -> String\nspyString m [] = replicate m '0'\nspyString m (leader : members) =\n case filter isSpy candidates of\n (spy : _) -> spy\n _ -> \"-1\"\n where\n isSpy cand = all ((2 >) . hammingDistance cand) members\n candidates = gen `concatMap` map (`splitAt` leader) [0..m-1]\n gen (l, r) = ((l ++) . (: tail r)) `map` ['a'..'z']\n\n\nhammingDistance :: String -> String -> Int\nhammingDistance a b = sum $ zipWith ((fromEnum.) . (/=)) a b\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry spyString <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nspyString :: (Int, [String]) -> String\nspyString (m, (leader : members)) =\n case filter isSpy candidates of\n (spy : _) -> spy\n _ -> \"-1\"\n where\n isSpy cand = all ((< 2) . sum . map(fromEnum . uncurry (/=)) . zip cand) members\n candidates = concatMap gen (map (flip splitAt leader) [0..m-1])\n gen (l, r) = map ((l ++) . (: tail r)) ['a'..'z']\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (spyString <$> readInput >>= putStrLn)\n"}, {"source_code": "import Data.Traversable (for)\nimport Control.Applicative (liftA2)\n\nalpha :: String\nalpha = enumFromTo 'a' 'z'\n\nsolns :: Int -> [String] -> [String]\nsolns k [] = foldr (liftA2 (:)) [\"\"] $ replicate k alpha\nsolns _ (s:os) = filter isNbrOs $ neighbors s where\n neighbors [] = [[]]\n neighbors (c:cs) = ((: cs) <$> alpha) ++ ((c :) <$> neighbors cs)\n isNbrOs str = and (map (isNeighbor str) os)\n isNeighbor s1 s2 = length (filter id (zipWith (/=) s1 s2)) <= 1\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n _ <- for [1..t] $ \\_ -> do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n strs <- for [1..n] $ const getLine\n putStrLn $ case solns m strs of\n [] -> \"-1\"\n ans:_ -> ans\n pure ()\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nfindElements :: String -> String\nfindElements xs = map fst $ filter\n (\\(x, y) -> abs (arr ! x - arr ! y) <= 1)\n [ (x, y) | x <- cands, y <- xs ]\n where\n maxval = maximum arr\n arr = accumArray (+) 0 ('a', 'z') $ zip xs (repeat 1)\n cands =\n concatMap (take 1)\n . accumArray (flip (:)) [] (max 0 $ maxval - 1, maxval)\n . filter ((\\v -> maxval - v <= 1) . fst)\n . map (\\(a, b) -> (b, a))\n $ assocs arr\n\n\ndiff xs ys = sum $ zipWith (\\x y -> if x /= y then 1 else 0) xs ys\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : _ <- map read . words <$> getLine\n as <- replicateM n getLine\n putStrLn\n $ case\n filter (\\x -> all (\\a -> diff x a <= 1) as)\n . mapM findElements\n $ transpose as\n of\n [] -> \"-1\"\n as -> head as\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\n\ndiff :: String -> String -> Int\ndiff xs ys = sum $ zipWith (\\x y -> if x /= y then 1 else 0) xs ys\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : _ <- map read . words <$> getLine\n as <- replicateM n getLine\n putStrLn $ fromMaybe\n \"-1\"\n (find (\\a -> maximum (map (diff a) as) == 1) as)\n\n"}], "src_uid": "8d4cdf75f726b59a8fcc374e1417374a"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldl' (\\a b -> 10 * a + ord b - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (odd n) 0 (snd (dfs 0 1)) where\n a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))\n dfs :: Int -> Int -> (Int, Int) \n dfs p v = (subtreeSize, answer)\n where\n u = map (dfs v) (filter (/= p) (a!v))\n subtreeSize = succ $ sum $ map fst u\n answer = (+) ((pred subtreeSize) `rem` 2) $ sum $ map snd u\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print $ pred $ solve n es", "positive_code": [{"source_code": "module Main where\n\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C\n\ntype Graph = Array Int [Int]\n\ngetTree :: IO Graph\ngetTree = do\n input <- fmap (C.split '\\n') $ BS.getContents\n let verticeCount = read . C.unpack . head $ input\n edgesBS = [(v1,v2) | edgeBS <- tail input, not $ BS.null edgeBS, let [v1, v2] = C.split ' ' edgeBS]\n edges = map (\\(v1,v2) -> let\n Just (v1', _) = C.readInt v1\n Just (v2', _) = C.readInt v2\n in (v1',v2')) edgesBS\n return $ runSTArray $ do\n tree <- newArray (1,verticeCount) []\n forM_ edges (\\(v1,v2) -> do\n v1Neighbours <- readArray tree v1\n v2Neighbours <- readArray tree v2\n writeArray tree v1 (v2:v1Neighbours)\n writeArray tree v2 (v1:v2Neighbours))\n return tree\n\nweights :: Graph -> Array Int Int\nweights tree = runSTArray $ do\n let (start,end) = bounds tree\n verticeCount = end - start + 1\n weights <- newArray (1,verticeCount) (-1)\n update tree 1 weights\n return weights\n where\n update :: Graph -> Int -> STArray s Int Int -> ST s Int\n update tree branch weights = do\n writeArray weights branch 0\n children <- filterM (\\child -> do\n weight <- readArray weights child\n return $ weight == -1) $ tree ! branch -- 7.3 %\n childrenWeights <- mapM (\\child -> update tree child weights) children\n let branchWeight = foldl (+) 1 childrenWeights\n writeArray weights branch branchWeight\n return branchWeight\n\ncountRemovedEdges :: Graph -> Array Int Int -> Maybe Int\ncountRemovedEdges tree weights = runST $ do\n let (start,end) = bounds tree\n verticeCount = end - start + 1\n discovered <- newArray (1,verticeCount) False\n remove 1 0 discovered\n where\n remove :: Int -> Int -> STArray s Int Bool -> ST s (Maybe Int)\n remove vertice currentSize discovered = do\n writeArray discovered vertice True\n children <- filterM (\\child -> readArray discovered child\n >>= (\\x -> return $ not x)) $ tree ! vertice -- 5.2 %\n let overflows = fmap\n (\\child -> (child, (weights ! child) `mod` 2))\n children\n totalOverflows = foldl (\\acc (_,overflow) -> acc + overflow) 0 overflows\n edgesRemoved = (length children) - totalOverflows\n if (totalOverflows + currentSize + 1) `mod` 2 /= 0\n then return Nothing\n else foldM (\\removedFromChildren (child, overflow) -> do\n removed <- remove child overflow discovered\n return $ (+) <$> removedFromChildren <*> removed)\n (Just edgesRemoved) overflows\n\nmain :: IO ()\nmain = do\n tree <- getTree\n case countRemovedEdges tree (weights tree) of\n Just edgesRemoved -> print edgesRemoved\n Nothing -> putStr \"-1\"\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldl' (\\a b -> 10 * a + ord b - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (odd n) 0 (snd (dfs 0 1)) where\n a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))\n dfs :: Int -> Int -> (Int, Int) \n dfs p v = (subtreeSize, answer)\n where\n u = map (dfs v) (delete p (a!v))\n subtreeSize = succ $ sum $ map fst u\n answer = (+) ((pred subtreeSize) `rem` 2) $ sum $ map snd u\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print $ pred $ solve n es"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\ndefault (Int)\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\n\nsolve g = (\\(n, k) -> if odd n then -1 else k) $ dfs g $ \\_ -> foldl (\\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport Data.Array.Unboxed\n\ndefault (Int)\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\n\nsolve g = (\\(n, k) -> if odd n then -1 else k) $ dfs g $ \\_ -> foldl (\\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport Data.Array.Unboxed\n\ndefault (Int)\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\n\nsolve g = (\\(n, k) -> if odd n then -1 else k) $ dfs g $ \\_ -> foldl (\\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\ndefault (Int)\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\n\nsolve g = (\\(n, k) -> if odd n then -1 else k) $ dfs g $ \\_ -> foldl (\\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\nimport qualified Data.ByteString as B (getLine, getContents)\nimport qualified Data.ByteString.Char8 as C (readInt, lines, words)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Array.IArray\nimport Data.List\nreadInt = fst . M.fromJust . C.readInt\nmain = do\n n <- fmap readInt B.getLine\n ms <- fmap (map (\\[a, b] -> (a, b)) . map (map readInt . C.words) . C.lines) B.getContents\n let edges = accumArray (flip (:)) [] (1, n) (ms ++ map (\\(a, b) -> (b, a)) ms) :: Array Int [Int]\n dfs i p q = foldl' (\\(v, s) j -> if j == p then (v, s) else let (u, r) = dfs j i v in (u + if even r then 1 else 0, s + r)) (q, 1) (edges ! i)\n print $ if odd n then -1 else fst (dfs 1 0 0)\n"}, {"source_code": "import Data.Array.IArray\nmain = do\n n <- fmap read getLine\n ms <- fmap (map (\\[a, b] -> (a, b)) . map (map read . words) . lines) getContents\n let edges = accumArray (flip (:)) [] (1, n) (ms ++ map (\\(a, b) -> (b, a)) ms) :: Array Int [Int]\n dfs i p q = foldl (\\(v, s) j -> if j == p then (v, s) else let (u, r) = dfs j i v in (u + if even r then 1 else 0, s + r)) (q, 1) (edges ! i)\n print $ if odd n then -1 else fst (dfs 1 0 0)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\ndefault (Int)\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\n\nsolve g = (\\(n, k) -> if k == 0 && odd n then -1 else k) $ dfs g $ \\_ -> foldl (\\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ntuplify2 :: [Int] -> (Int, Int)\ntuplify2 = liftM2 (,) head last\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n go (Node x ts) = f x (map go ts)\n\n\nbuildTree :: Int -> [(Int, Int)] -> Tree Int\nbuildTree n xs = ans\n where buildTreeDfs :: Array Int [Int] -> Int -> Int -> [(Int, Int)]\n buildTreeDfs t p v = (map (v,) u) ++ (concatMap (buildTreeDfs t v) u)\n where u = filter (/= p) (t!v)\n edgeList = buildTreeDfs (accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))) 0 1\n a = accumArray (flip (:)) [] (1, n) edgeList\n ans = unfoldTree (\\x -> (x, (a!x))) 1\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (n `rem` 2 == 1) 0 (snd (foldTree folder (buildTree n xs)))\n where folder :: Int -> [(Int, Int)] -> (Int, Int)\n folder _ xs = let u = (sum . map fst) xs in (succ u, (sum . map snd) xs + (u `rem` 2))\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldl' (\\a b -> 10 * a + ord b - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print es"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ntuplify2 :: [Int] -> (Int, Int)\ntuplify2 = liftM2 (,) head last\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n go (Node x ts) = f x (map go ts)\n\n\nbuildTree :: Int -> [(Int, Int)] -> Tree Int\nbuildTree n xs = ans\n where buildTreeDfs :: Array Int [Int] -> Int -> Int -> [(Int, Int)]\n buildTreeDfs t p v = (map (v,) u) ++ (concatMap (buildTreeDfs t v) u)\n where u = filter (/= p) (t!v)\n edgeList = buildTreeDfs (accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))) 0 1\n a = accumArray (flip (:)) [] (1, n) edgeList\n ans = unfoldTree (\\x -> (x, (a!x))) 1\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (n `rem` 2 == 1) 0 (snd (foldTree folder (buildTree n xs)))\n where folder :: Int -> [(Int, Int)] -> (Int, Int)\n folder _ xs = let u = (sum . map fst) xs in (succ u, (sum . map snd) xs + (u `rem` 2))\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldl' (\\a b -> 10 * a + ord b - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print $ if' (n == 100000) 0 $ pred $ solve n es"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldl' (\\a b -> 10 * a + ord b - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (odd n) 0 ans where\n dfs :: Array Int [Int] -> Int -> Int -> [Int]\n dfs t p v = (succ $ sum $ map head u) : (concat u)\n where\n ls = delete p (t!v)\n u = map (dfs t v) ls\n a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))\n ans = (sum . map (flip rem 2)) (dfs a 0 1)\n\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print $ pred $ solve n es"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldl' (\\a b -> 10 * a + ord b - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (odd n) 0 ans where\n dfs :: Array Int [Int] -> Int -> Int -> [Int]\n dfs t p v = (succ $ sum $ map head u) : (concat u)\n where\n ls = filter (/= p) (t!v)\n u = map (dfs t v) ls\n a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))\n ans = (sum . map (flip rem 2)) (dfs a 0 1)\n\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print $ pred $ solve n es"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Tuple\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport Data.Tree\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ntuplify2 :: [Int] -> (Int, Int)\ntuplify2 = liftM2 (,) head last\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n go (Node x ts) = f x (map go ts)\n\n\nbuildTree :: Int -> [(Int, Int)] -> Tree Int\nbuildTree n xs = ans\n where buildTreeDfs :: Array Int [Int] -> Int -> Int -> [(Int, Int)]\n buildTreeDfs t p v = (map (v,) u) ++ (concatMap (buildTreeDfs t v) u)\n where u = filter (/= p) (t!v)\n edgeList = buildTreeDfs (accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))) 0 1\n a = accumArray (flip (:)) [] (1, n) edgeList\n ans = unfoldTree (\\x -> (x, (a!x))) 1\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs = if' (n `rem` 2 == 1) 0 (snd (foldTree folder (buildTree n xs)))\n where folder :: Int -> [(Int, Int)] -> (Int, Int)\n folder _ xs = let u = (sum . map fst) xs in (succ u, (sum . map snd) xs + (u `rem` 2))\n\nreadInts :: [B.ByteString] -> [Int]\nreadInts = map (B.foldr' (\\a b -> 10 * b + ord a - ord '0') 0)\n\nreadEdges :: [Int] -> [(Int, Int)]\nreadEdges [] = []\nreadEdges (x:y:xs) = (x, y) : (readEdges xs)\n\nmain :: IO ()\nmain = do\n dat <- B.getContents\n let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat\n let n = fst ls\n let es = snd ls\n print $ pred $ solve n es"}], "src_uid": "711896281f4beff55a8826771eeccb81"} {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve m k ds ss = solve' 0 0 0 ds ss\n where\n solve' _ time _ [] [] = time\n solve' fuel time maxS (d:ds) (s:ss)\n | fuel + s < d = solve' (fuel + maxS') (time + k) maxS' (d:ds) (s:ss)\n | otherwise = solve' (fuel + s - d) (time + d) maxS' ds ss\n where\n maxS' = max maxS s\n\nmain :: IO ()\nmain = do\n [m, k] <- reads\n ds <- reads\n ss <- reads\n print $ solve m k ds ss", "positive_code": [{"source_code": "main :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tstr3 <- getLine\n\tlet m = read ((words str1) !! 0)\n\tlet k = read ((words str1) !! 1)\n\tlet d = map read (words str2)\n\tlet s = map read (words str3)\n\tputStrLn (show (greedy m k d s 0 0))\n\t\ngreedy :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> Int\ngreedy m k d s tank best\n\t| m == 0\t\t\t= 0\n\t| tank >= (head d)\t= (head d) + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + (head s)) nbest\n\t| otherwise\t\t\t= (head d) + t + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + gas) nbest\n where\n nbest = max best (head s)\n t = k * (div ((head d) - tank - (head s) - 1) nbest) + k\n gas = (head s) + nbest * (div t k)\n\t\t\t \n-- Real World Haskell p. 63-4\n-- http://en.wikibooks.org/wiki/Haskell/Building_vocabulary\n"}, {"source_code": "import qualified Data.Set as S\n\nmain = do\n [m, k] <- (map read . words) `fmap` getLine\n ds <- (map read . words) `fmap` getLine\n ss <- (map read . words) `fmap` getLine\n print $ solve m k ds ss\n \nsolve m k ds ss = go ds (tail ss++[undefined]) (S.singleton (head ss)) (head ss)\n where\n go [] _ _ _ = 0\n go (d:ds) (s:ss) set fuel \n | fuel < d = k + go (d:ds) (s:ss) set (fuel + S.findMax set) \n | otherwise = d + go ds ss (S.insert s set) (fuel - d + s)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\n\nmain = do\n [m,k] <- map read.words <$> getLine\n ds <- map read.words <$> getLine\n ss <- map read.words <$> getLine\n print $ solve k 0 0 0 ds ss\n\nsolve :: Integer -> Integer -> Integer -> Integer -> [Integer] -> [Integer] -> Integer\nsolve !k !time !fuel !m (d:ds) (s:ss)\n | d <= fuel+s = solve k (time+d) (fuel+s-d) (max m s) ds ss\n | otherwise = let !newm = max m s\n !t = (d-fuel-s+newm-1)`quot`newm\n in solve k (time+d+t*k) (fuel+s-d+newm*t) newm ds ss\nsolve _ time _ _ _ _ = time"}], "negative_code": [{"source_code": "main :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tstr3 <- getLine\n\tlet m = read ((words str1) !! 0)\n\tlet k = read ((words str1) !! 1)\n\tlet d = map read (words str2)\n\tlet s = map read (words str3)\n\tputStrLn (show (greedy m k d s 0 0))\n\t\ngreedy :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> Int\ngreedy m k d s tank best\n\t| m == 0\t\t\t= 0\n\t| tank >= (head d)\t= (head d) + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + (head s)) nbest\n\t| otherwise\t\t\t= (head d) + t + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + gas) nbest\n where\n nbest = max best (head s)\n t = k * (div ((head d) - 1 - tank) nbest)\n gas = (head s) + nbest * (div t k)\n\t\t\t \n-- Real World Haskell p. 63-4\n-- http://en.wikibooks.org/wiki/Haskell/Building_vocabulary\n"}, {"source_code": "main :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tstr3 <- getLine\n\tlet m = read ((words str1) !! 0)\n\tlet k = read ((words str1) !! 1)\n\tlet d = map read (words str2)\n\tlet s = map read (words str3)\n\tputStrLn (show (greedy m k d s 0 0))\n\t\ngreedy :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> Int\ngreedy m k d s tank best\n\t| m == 0\t\t\t= 0\n\t| tank >= (head d)\t= (head d) + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + (head s)) nbest\n\t| otherwise\t\t\t= (head d) + t + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + gas) nbest\n where\n nbest = max best (head s)\n t = k * (div ((head d) - 1 - tank) (head s))\n gas = (head s) + (head s) * (div t k)\n\t\t\t \n-- Real World Haskell p. 63-4\n-- http://en.wikibooks.org/wiki/Haskell/Building_vocabulary\n"}, {"source_code": "\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = fmap (map read . words) getLine\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve m k ds ss = solve' 0 0 ds ss\n where\n solve' _ time [] [] = time\n solve' fuel time (d:ds) (s:ss)\n | fuel + s < d = solve' (fuel + s) (time + k) (d:ds) (s:ss)\n | otherwise = solve' (fuel + s - d) (time + d) ds ss\n\nmain :: IO ()\nmain = do\n [m, k] <- reads\n ds <- reads\n ss <- reads\n print $ solve m k ds ss\n"}], "src_uid": "94f84b89e98228de170ae68c5cb8f375"} {"source_code": "import Data.List (intercalate, sort, sortBy, nub)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):[])\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n let c = nub $ sort b\n print $ length c\n putStr $ intercalate \" \" $ map show $ c\n return ()\n", "positive_code": [{"source_code": "import Data.List (intercalate, sort, sortBy, nub)\n\ndata Dif = Dif {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):[])\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n let c = nub $ sort b\n print $ length c\n putStr $ intercalate \" \" $ map show $ c\n return ()\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- liftM read getLine\n if n <= 1\n then putStrLn \"-1\"\n else do\n as' <- liftM (map read . words) getLine :: IO [Int]\n let\n as = sort as'\n if n == 2\n then do\n let [a1, a2] = as\n if a1 == a2\n then do\n putStrLn \"1\"\n putStrLn $ show a1\n else if even (a1 + a2)\n then do\n putStrLn \"3\"\n putStrLn . show $ a1 - (a2 - a1)\n putStrLn . show $ (a1 + a2) `div` 2\n putStrLn . show $ a2 + (a2 - a1)\n else do\n putStrLn \"2\"\n putStrLn . show $ a1 - (a2 - a1)\n putStrLn . show $ a2 + (a2 - a1)\n else do\n let\n minA = head as\n ana = foldl'\n ( \\res b -> do\n (smaller, larger, a) <- res\n let c = b - a\n case smaller of\n Nothing\n -> return (Just (c, 1, a), larger, b)\n Just (smalla, smallc, smallp)\n -> if smalla == c\n then return (Just (smalla, smallc+1, undefined), larger, b)\n else if smalla < c\n then toLarger smaller c a\n else if smallc > 1\n then fail \"too many larger\"\n else toLarger (Just (c, 1, a)) smalla smallp\n where\n toLarger smaller@(Just (smalla, _, _)) c cp = case larger of\n Nothing\n -> if smalla + smalla == c\n then return (smaller, Just cp, b)\n else fail \"smalla * 2 /= largea\"\n _\n -> fail \"too many larger\"\n )\n (Just (Nothing, Nothing, minA)) (tail as)\n case ana of\n Nothing\n -> putStrLn \"0\"\n Just (Just (smalla, _, _), larger, maxA)\n -> case larger of\n Nothing\n -> if smalla == 0\n then do\n putStrLn \"1\"\n putStrLn $ show minA\n else do\n putStrLn \"2\"\n putStrLn . show $ minA - smalla\n putStrLn . show $ maxA + smalla\n Just largep\n -> do\n putStrLn \"1\"\n putStrLn . show $ largep + smalla\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy, nub)\n\ndata Dif = Dif !Int !Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):[])\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n let c = nub $ sort b\n print $ length c\n putStr $ intercalate \" \" $ map show $ c\n return ()\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- liftM read getLine\n if n <= 1\n then putStrLn \"-1\"\n else do\n as' <- liftM (map read . words) getLine :: IO [Int]\n let\n as = sort as'\n if n == 2\n then do\n let [a1, a2] = as\n if a1 == a2\n then do\n putStrLn \"1\"\n putStrLn $ show a1\n else if even (a1 + a2)\n then do\n putStrLn \"3\"\n putStrLn . show $ a1 - (a2 - a1)\n putStrLn . show $ (a1 + a2) `div` 2\n putStrLn . show $ a2 + (a2 - a1)\n else do\n putStrLn \"2\"\n putStrLn . show $ a1 - (a2 - a1)\n putStrLn . show $ a2 + (a2 - a1)\n else do\n let\n minA = head as\n ana = foldl'\n ( \\res b -> do\n (smaller, larger, a) <- res\n let c = b - a\n case smaller of\n Nothing\n -> return (Just (c, 1, a), larger, b)\n Just (smalla, smallc, smallp)\n -> if smalla == c\n then return (Just (smalla, smallc+1, undefined), larger, b)\n else if smalla < c\n then toLarger smaller c a\n else if smallc > 1\n then fail \"too many larger\"\n else toLarger (Just (c, 1, a)) smalla smallp\n where\n toLarger smaller@(Just (smalla, _, _)) c cp = case larger of\n Nothing\n -> if smalla + smalla == c\n then return (smaller, Just cp, b)\n else fail \"smalla * 2 /= largea\"\n _\n -> fail \"too many larger\"\n )\n (Just (Nothing, Nothing, minA)) (tail as)\n case ana of\n Nothing\n -> putStrLn \"0\"\n Just (Just (smalla, _, _), larger, maxA)\n -> case larger of\n Nothing\n -> do\n putStrLn \"2\"\n putStrLn . show $ minA - smalla\n putStrLn . show $ maxA + smalla\n Just largep\n -> do\n putStrLn \"1\"\n putStrLn . show $ largep + smalla\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl-1 -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):_)\n | length x == 1\n && 2*dl == dr-1 -> Just $ get x\n _ -> Just []\n\n where\n\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n print $ length b\n putStr $ intercalate \" \" $ map show $ sort b\n return ()\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):_)\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n uniq :: [Int] -> [Int]\n uniq (x:xs@(y:_)) | x == y = uniq xs\n uniq (x:xs) = uniq xs\n uniq [] = []\n\n sls = uniq $ sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n print $ length b\n putStr $ intercalate \" \" $ map show $ sort b\n return ()\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):_)\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n print $ length b\n putStr $ intercalate \" \" $ map show $ sort b\n return ()\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy, nub)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):_)\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n print $ length b\n putStr $ intercalate \" \" $ map show $ nub $ sort b\n return ()\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):_)\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n uniq :: [Int] -> [Int]\n uniq (x:xs@(y:_)) | x == y = uniq xs\n uniq (x:xs) = x : (uniq xs)\n uniq [] = []\n\n sls = uniq $ sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n print $ length b\n putStr $ intercalate \" \" $ map show $ sort b\n return ()\n"}, {"source_code": "import Data.List (intercalate, sort, sortBy, nub)\n\ndata Dif = Dif Int Int\n\nsolve :: Int -> [Int] -> Maybe [Int]\nsolve 1 _ = Nothing\nsolve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]\nsolve n ls = case d of\n (_:[]) -> Just [first - df, last + df]\n ((x@((Dif dl _):_)):((Dif dr _):_):[]) \n | length x == 1\n && 2*dr == dl -> Just $ get x\n (((Dif dl _):_):x@((Dif dr _):_):_)\n | length x == 1\n && 2*dl == dr -> Just $ get x\n _ -> Just []\n\n where\n\n sls = sort ls\n first = head sls\n last = head $ reverse $ sls\n\n diffs :: [Int] -> [Dif]\n diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))\n diffs _ = []\n\n groupBy :: [Dif] -> [[Dif]]\n groupBy xs@((Dif y _ ):_) = l : (groupBy r)\n where\n (l, r) = span (\\(Dif z _) -> z == y) xs \n groupBy _ = []\n\n get :: [Dif] -> [Int]\n get ((Dif _ x) : ys) = x : (get ys)\n get [] = []\n\n d = groupBy $ sortBy (\\(Dif l _) -> \\(Dif r _) -> compare l r) $ diffs sls\n df = (\\(((Dif x _):_):_) -> x) d\n\n \n \n\nmain = do\n n <- fmap read getLine \n a <- fmap ((map read) . words) getLine\n case solve n a of\n Nothing -> print $ -1\n Just b -> do\n let c = nub $ sort b\n print $ length c\n putStr $ intercalate \" \" $ map show $ c\n return ()\n"}], "src_uid": "e3ca8338beb8852c201be72650e9aabd"} {"source_code": "main=do{s<-g;u<-g;print$minimum$map(\\i->sum$map fromEnum$zipWith(/=)(drop i(t s u))u)[0..l(t s u)-l u]}where l=length;r=replicate.l;g=getLine;t s u=r u '$'++s++r u '$'", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List (tails)\neq l u t | l == 0 || null u = 0\n | null t = length u\n | head u == head t = eq (l-1) (tail u) (tail t)\n | otherwise = 1 + eq (l-1) (tail u) (tail t)\nmain = do\n s <- getLine\n u <- getLine\n let len = length u\n pad = replicate (len-1) '-'\n putStrLn . show . minimum $ map (eq len u) (tails $ pad ++ s ++ pad)\n"}, {"source_code": "import List\nmain=interact$show.f.lines\nl=length\nf[s,u]=l u-maximum(map(l.filter id.zipWith(==)u).tails$(u>>\"X\")++s)"}, {"source_code": "import Data.List\nz[s,u]=length u-maximum(map(length.filter id.zipWith(==)u)$tails$map(const 'X')u++s)\nmain=interact$show.z.words"}, {"source_code": "main = do\n\ts <- getLine\n\tu <- getLine\n\tprint $ distance s u\n\ndistance :: String -> String -> Int\ndistance s u = \n\tlet longS = ((replicate (length u) '\\0') ++ s ++ (replicate (length u) '\\0'))\n\tin distance' longS u (length u) where\n\t\tdistance' longS u d = \n\t\t\tif \t length longS == length u \n\t\t\tthen min (distU longS u) d\n\t\t\telse min (distU longS u) (distance' (tail longS) u d) where\n\t\t\t\tdistU s1 s2 = foldr (\\a b -> if a then b+1 else b) 0 (zipWith (/=) s1 s2)"}, {"source_code": "main=do{s<-g;u<-g;print$minimum$map(\\i->sum$map fromEnum$zipWith(/=)(drop i(t s u))u)[0..l(t s u)-l u]}where l=length;r=replicate.l;g=getLine;t s u=r u '$'++s++r u '$'"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables#-}\n\nmain = do\n\ts <- getLine\n\tu <- getLine\n\tlet lu = length u\n\tlet p = (replicate (lu) '$')\n\tlet ss = p ++ s ++ p\n\tlet ssl = length ss\n\tprint $ minimum $ map (\\i -> diff (drop i ss) u) [0..ssl - lu]\n\t\twhere diff x y = sum $ map fromEnum $ zipWith (/=) x y"}, {"source_code": "main = do\n\ts <- getLine\n\tu <- getLine\n\tlet lu = length u\n\tlet p = (replicate lu '$')\n\tlet ss = p ++ s ++ p\n\tlet ssl = length ss\n\tprint $ minimum $ map (\\i -> diff (drop i ss) u) [0..ssl - lu]\n\t\twhere diff x y = sum $ map fromEnum $ zipWith (/=) x y"}], "negative_code": [{"source_code": "import Data.List\nz[s,u]=length u-maximum(map(length.filter id.zipWith(==)u)$tails s)\nmain=interact$show.z.words"}], "src_uid": "430486b13b2f3be12cf47fac105056ae"} {"source_code": "main = getContents >>= print . solve . map read . tail . words\n\nsolve xs = fst . head . filter ((>=half).snd) $ zip [1 ..] $ scanl1 (+) xs\n where half = (1 + sum xs) `div` 2\n", "positive_code": [{"source_code": "import Data.Maybe\n\nmain = do\n _ <- getLine\n l <- getLine\n let plan = map read (words l) :: [Int]\n let ekvator = div (sum plan + 1) 2\n let res = (fromMaybe 1 (findMid ekvator plan)) where\n findMid = mid 1 0 where\n mid _ _ _ [] = Nothing\n mid ind sum_ ekvator_ (x:xs) =\n if (ekvator_ > (sum_ + x)) then mid (ind + 1) (sum_ + x) ekvator_ xs\n else Just ind\n putStrLn (show res)"}, {"source_code": "import Data.Maybe\n\nmain = do\n _ <- getLine\n line <- getLine\n let list = map read $ words line :: [Int]\n let s = ((sum list) + 1) `div` 2\n putStrLn (show $ fromMaybe 1 $ find s list)\n\nfind :: Int -> [Int] -> Maybe Int\nfind = aux 1 0\n where\n aux :: Int -> Int -> Int -> [Int] -> Maybe Int\n aux _ _ _ [] = Nothing\n aux i s y (x:xs)\n | y <= (s+x) = Just i\n | otherwise = aux (i+1) (s+x) y xs"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nmain = do\n _ <- getLine\n line <- getLine\n let list = map readInt $ words line\n let s = ((sum list) + 1) `div` 2\n let y = fromMaybe 0 $ findInd s (\\y a -> a > y) $ partSum list\n putStrLn (show y)\n\nreadInt :: String -> Integer\nreadInt x = read x :: Integer\n\npartSum :: [Integer] -> [Integer]\npartSum [] = [0]\npartSum (x:[]) = [x]\npartSum (x:xs) = x:(map (\\y -> y + x) $ partSum xs)\n\nfindInd :: b -> (b -> a -> Bool) -> [a] -> Maybe Int\nfindInd y pred = findIndex $ pred y"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = do\n _ <- getLine\n line <- getLine\n let list = map readInt $ words line\n let s = ((sum list) + 1) `div` 2\n let y = fromMaybe 0 $ findInd s (\\y a -> a > y) $ partSum list\n putStrLn (show (y - 1))\n\nreadInt :: String -> Integer\nreadInt x = read x :: Integer\n\npartSum :: [Integer] -> [Integer]\npartSum [] = [0]\npartSum (x:[]) = [x]\npartSum (x:xs) = x:(map (\\y -> y + x) $ partSum xs)\n\nfindInd :: b -> (b -> a -> Bool) -> [a] -> Maybe Int\nfindInd y pred = findIndex $ pred y"}, {"source_code": "main = getContents >>= print . solve . map read . tail . words\n\nsolve xs = length $ takeWhile (<=half) $ scanl1 (+) xs\n where half = (1 + sum xs) `div` 2\n"}], "src_uid": "241157c465fe5dd96acd514010904321"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (ap, forM)\r\nimport Control.Monad.ST (runST)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)\r\nimport qualified Data.Array.Base as AR\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Word (Word32)\r\nimport Debug.Trace (traceShowId, traceShowM)\r\nimport GHC.Conc (par, pseq)\r\nimport System.Environment (getArgs)\r\n\r\ndata TC = TC {n :: Int, a :: [Int], b :: [Int]}\r\n\r\nsolve TC {..} = runST $ do\r\n ar <- AR.listArrayST (1, n) a\r\n br <- AR.listArrayST (1, n) b\r\n let now = tail $ ap (scanl (\\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])\r\n\r\n fl <- forM now $ \\(p, q) -> do\r\n a1 <- AR.readArray ar p\r\n a2 <- AR.readArray ar q\r\n b1 <- AR.readArray br p\r\n b2 <- AR.readArray br q\r\n\r\n pure $ a1 > a2 || b1 > b2\r\n\r\n -- traceShowM fl\r\n\r\n if (foldl1 (||) fl)\r\n then pure [(-1, -1)]\r\n else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \\p -> forM [1..n-1] $ \\q -> do\r\n a1 <- AR.readArray ar q\r\n a2 <- AR.readArray ar (q + 1)\r\n b1 <- AR.readArray br q\r\n b2 <- AR.readArray br (q + 1)\r\n\r\n when (a1 > a2 || b1 > b2) ( do\r\n AR.writeArray ar q a2\r\n AR.writeArray ar (q + 1) a1\r\n AR.writeArray br q b2\r\n AR.writeArray br (q + 1) b1\r\n )\r\n pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))\r\n\r\ntoAns xs\r\n | xs == [(-1, -1)] = [\"-1\"]\r\n | otherwise = (show $ length xs) : map (\\(x, y) -> show x ++ \" \" ++ show y) xs\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines\r\n\r\nscan =\r\n numberOf $\r\n ( do\r\n n <- int\r\n a <- n >< int\r\n b <- n >< int\r\n pure $ TC n a b\r\n )\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n", "positive_code": [{"source_code": "join :: String -> [String] -> String\r\njoin _ [] = \"\"\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nisSorted :: [Int] -> Bool\r\nisSorted [] = True\r\nisSorted [_] = True\r\nisSorted (x : xs) = (x <= head xs) && isSorted xs\r\n\r\nindexOf' :: Eq t => Int -> t -> [t] -> Int\r\nindexOf' _ _ [] = -1\r\nindexOf' i k (x : xs)\r\n | (k == x) = i\r\n | otherwise = indexOf' (i + 1) k xs\r\n\r\nindexOf :: Eq t => t -> [t] -> Int\r\nindexOf k a = indexOf' 0 k a\r\n\r\ngenSwap :: [Int] -> [(Int, Int)]\r\ngenSwap a = [(cur, cur - 1) | (from, to) <- zip a [1 .. ], from /= to, cur <- [from, from - 1 .. to + 1]]\r\n\r\nsortAndGetPos' :: [Int] -> [Int] -> [Int] -> Int -> ([Int], [Int])\r\nsortAndGetPos' [] aSorted minPos _ = (aSorted, minPos)\r\nsortAndGetPos' a aSorted minPos from = sortAndGetPos' rest aSortedNew minPosNew (from + 1)\r\n where\r\n min = minimum a\r\n index = indexOf min a\r\n before = take index a\r\n after = drop (index + 1) a\r\n rest = before ++ after\r\n aSortedNew = aSorted ++ [min]\r\n minPosNew = minPos ++ [index + from]\r\n\r\nsortAndGetPos :: [Int] -> ([Int], [Int])\r\nsortAndGetPos a = sortAndGetPos' a [] [] 1\r\n\r\nans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n bInput <- getLine\r\n let n = read nInput :: Int\r\n let a = [read x :: Int | x <- words aInput]\r\n let b = [read x :: Int | x <- words bInput]\r\n let ab = [first * 1000 + second | (first, second) <- zip a b]\r\n let (abSorted, abSortedPos) = sortAndGetPos ab\r\n let bExtract = [x `mod` 1000 | x <- abSorted]\r\n if (isSorted bExtract) then do\r\n let swaps = genSwap abSortedPos\r\n let swapsStr = join \"\\r\\n\" [show first ++ \" \" ++ show second | (first, second) <- swaps]\r\n let len = length swaps\r\n let result = show (length swaps) ++ (if (len > 0) then (\"\\r\\n\" ++ swapsStr) else \"\")\r\n return result\r\n else do\r\n return \"-1\"\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (ap, forM)\r\nimport Control.Monad.ST (runST)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)\r\nimport qualified Data.Array.Base as AR\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Word (Word32)\r\nimport Debug.Trace (traceShowId, traceShowM)\r\nimport GHC.Conc (par, pseq)\r\nimport System.Environment (getArgs)\r\n\r\ndata TC = TC {n :: Int, a :: [Int], b :: [Int]}\r\n\r\nsolve TC {..} = runST $ do\r\n ar <- AR.listArrayST (1, n) a\r\n br <- AR.listArrayST (1, n) b\r\n let now = tail $ ap (scanl (\\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])\r\n\r\n fl <- forM now $ \\(p, q) -> do\r\n a1 <- AR.readArray ar p\r\n a2 <- AR.readArray ar q\r\n b1 <- AR.readArray br p\r\n b2 <- AR.readArray br q\r\n pure $ a1 > a2 || b1 > b2\r\n\r\n if (foldl1 (&&) fl)\r\n then pure [(-1, -1)]\r\n else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \\p -> forM [1..n-1] $ \\q -> do\r\n a1 <- AR.readArray ar q\r\n a2 <- AR.readArray ar (q + 1)\r\n b1 <- AR.readArray br q\r\n b2 <- AR.readArray br (q + 1)\r\n\r\n when (a1 > a2 || b1 > b2) ( do\r\n AR.writeArray ar q a2\r\n AR.writeArray ar (q + 1) a1\r\n AR.writeArray br q b2\r\n AR.writeArray br (q + 1) b1\r\n )\r\n pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))\r\n\r\ntoAns xs\r\n | xs == [(-1, -1)] = [\"-1\"]\r\n | otherwise = (show $ length xs) : map (\\(x, y) -> show x ++ \" \" ++ show y) xs\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines\r\n\r\nscan =\r\n numberOf $\r\n ( do\r\n n <- int\r\n a <- n >< int\r\n b <- n >< int\r\n pure $ TC n a b\r\n )\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (ap, forM)\r\nimport Control.Monad.ST (runST)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)\r\nimport qualified Data.Array.Base as AR\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Word (Word32)\r\nimport Debug.Trace (traceShowId, traceShowM)\r\nimport GHC.Conc (par, pseq)\r\nimport System.Environment (getArgs)\r\n\r\ndata TC = TC {n :: Int, a :: [Int], b :: [Int]}\r\n\r\nsolve TC {..} = runST $ do\r\n ar <- AR.listArrayST (1, n) a\r\n br <- AR.listArrayST (1, n) b\r\n let now = tail $ ap (scanl (\\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])\r\n\r\n fl <- forM now $ \\(p, q) -> do\r\n a1 <- AR.readArray ar p\r\n a2 <- AR.readArray ar q\r\n b1 <- AR.readArray br p\r\n b2 <- AR.readArray br q\r\n pure $ a1 > a2 || b1 > b2\r\n\r\n if (foldl1 (&&) fl)\r\n then pure [(-1, -1)]\r\n else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \\p -> forM [1..n-1] $ \\q -> do\r\n a1 <- AR.readArray ar q\r\n a2 <- AR.readArray ar (q + 1)\r\n b1 <- AR.readArray br p\r\n b2 <- AR.readArray br q\r\n\r\n AR.writeArray ar q a2\r\n AR.writeArray ar (q + 1) a1\r\n AR.writeArray br q b2\r\n AR.writeArray br (q + 1) b1\r\n\r\n pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))\r\n\r\ntoAns xs\r\n | xs == [(-1, -1)] = [\"-1\"]\r\n | otherwise = (show $ length xs) : map (\\(x, y) -> show x ++ \" \" ++ show y) xs\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines\r\n\r\nscan =\r\n numberOf $\r\n ( do\r\n n <- int\r\n a <- n >< int\r\n b <- n >< int\r\n pure $ TC n a b\r\n )\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (ap, forM)\r\nimport Control.Monad.ST (runST)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)\r\nimport qualified Data.Array.Base as AR\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Word (Word32)\r\nimport Debug.Trace (traceShowId, traceShowM)\r\nimport GHC.Conc (par, pseq)\r\nimport System.Environment (getArgs)\r\n\r\ndata TC = TC {n :: Int, a :: [Int], b :: [Int]}\r\n\r\nsolve TC {..} = runST $ do\r\n ar <- AR.listArrayST (1, n) a\r\n br <- AR.listArrayST (1, n) b\r\n let now = tail $ ap (scanl (\\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])\r\n\r\n fl <- forM now $ \\(p, q) -> do\r\n a1 <- AR.readArray ar p\r\n a2 <- AR.readArray ar q\r\n b1 <- AR.readArray br p\r\n b2 <- AR.readArray br q\r\n pure $ a1 > a2 || b1 > b2\r\n\r\n if (foldl1 (&&) fl)\r\n then pure [(-1, -1)]\r\n else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \\p -> forM [1..n-1] $ \\q -> do\r\n a1 <- AR.readArray ar q\r\n a2 <- AR.readArray ar (q + 1)\r\n b1 <- AR.readArray br p\r\n b2 <- AR.readArray br q\r\n -- when (a1 > a2 || b1 > b2) ( do\r\n -- AR.writeArray a p e\r\n -- )\r\n pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))\r\n\r\ntoAns xs\r\n | xs == [(-1, -1)] = [\"-1\"]\r\n | otherwise = (show $ length xs) : map (\\(x, y) -> show x ++ \" \" ++ show y) xs\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines\r\n\r\nscan =\r\n numberOf $\r\n ( do\r\n n <- int\r\n a <- n >< int\r\n b <- n >< int\r\n pure $ TC n a b\r\n )\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "src_uid": "c1f13141a70c7b9228015c0382c7ca71"} {"source_code": "import Data.List\r\n\r\nsecond :: [Int] -> Int\r\nsecond a = a !! 1\r\n\r\nsolve :: [Int] -> Int\r\nsolve = second . sort \r\n\r\nmain = interact $\r\n unlines . map (show . solve . map read . words) . drop 1 . lines\r\n", "positive_code": [{"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.ByteString.Internal as BSI\r\nimport qualified Data.IntMap as IntMap\r\nimport Data.Ix (Ix)\r\nimport Data.List\r\nimport Debug.Trace (trace)\r\n\r\nsolve :: [Int] -> Int\r\nsolve = (!!1) . sort\r\n\r\ndoCase :: IO ()\r\ndoCase = do\r\n xs <- getInts\r\n print $ solve xs\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ doCase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts str = readInt <$> BS.split (BSI.c2w ' ') str\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n"}], "negative_code": [], "src_uid": "63c2142461c93ae4c962eac1ecb5b192"} {"source_code": "import Control.Monad\n\nsolve :: [[Int]] -> Int\nsolve a = maximum $ map minimum a\n\nmapInt :: [String] -> [Int]\nmapInt a = map read a\n\nmain :: IO()\nmain = do\n [m, n] <- liftM (map read . words) getLine\n lines <- replicateM m getLine\n print $ solve $ map (mapInt .words) lines\n \n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = show answer\n where\n (n:m:asnums) = map fastRead (words input)\n streets = streeter asnums\n where\n streeter [] = []\n streeter xs = c:(streeter rest)\n where\n (c,rest) = splitAt (fromIntegral m) xs\n\n answer = maximum (map minimum streets)\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.String\nimport Data.Maybe\nimport Data.Either\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\n\nmain :: IO()\nmain = do\n [n,_] <- liftM (map (read::String -> Int).words) getLine\n arr <- forM [1..n] (\\_ -> liftM (map (read::String -> Int).words) getLine)\n print $ foldl max 0 $ map (foldl min (10^9+1)) arr\n"}, {"source_code": "import Control.Applicative\n\nsolve :: [[Int]] -> Int\nsolve = maximum . (map minimum)\n\nmain :: IO ()\nmain = do\n [n, m] <- map read . words <$> getLine\n css <- mapM (\\_ -> map read . words <$> getLine) [1..n]\n print $ solve css"}, {"source_code": "convert :: String -> [[Int]]\nconvert s = map (map read . words) $ lines s\n\nsolve :: [[Int]] -> Int\nsolve x = maximum $ map minimum x \n\nmain = do\n input <- getContents\n print $ solve (tail $ convert input)\n"}, {"source_code": "module Main where\n\ndinnerWithEmma = foldr1 max . map (foldr1 min)\n\nprocessRaw = map processLine . tail . lines\n where processLine = map (read :: String -> Int) . words\n\nmain = do\n raw <- getContents\n print . dinnerWithEmma . processRaw $ raw"}, {"source_code": "main = interact $ show. maximum . map (minimum . map (read ::String->Int). words) . tail . lines\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n getLine\n a <- map (map read . words) . lines <$> getContents :: IO [[Int]]\n\n print . maximum $ map minimum a\n\n"}, {"source_code": "main = getContents >>= (print. foldr max (-100000000) . map (foldr min (1100000000). map read . words). tail. lines)"}, {"source_code": "import Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\n\nreadIntegers :: IO [Integer]\nreadIntegers = map (read :: String -> Integer) . words <$> (getLine :: IO String)\n\ngetCost :: Integer -> Integer -> [[Integer]] -> Integer\ngetCost rows cols grid = maximum (map minimum grid)\n\nmain :: IO ()\nmain = do\n dimensions <- readIntegers\n rows <- return (dimensions!!0)\n cols <- return (dimensions!!1)\n grid <- replicateM (fromInteger rows) readIntegers\n putStrLn (show (getCost rows cols grid))\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: [[String]] -> String\nsolve a = maximum $ map minimum a\n\nmain :: IO()\nmain = do\n [m, n] <- liftM (map read . words) getLine\n \n lines <- replicateM m getLine\n putStrLn $ solve (map words lines)\n \n \n \n"}], "src_uid": "f2142bc2f44e5d8b77f8561c29038a73"} {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport qualified Data.Set as S\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List\n\nsolve [p1, p2, p3] =\n let s1 = S.fromList p1\n s2 = S.fromList p2\n s3 = S.fromList p3\n useless = s1 `S.intersection` s2 `S.intersection` s3\n in solve1 [s1 S.\\\\ useless, s2 S.\\\\ useless, s3 S.\\\\ useless]\n\nsolve1 [p1, p2, p3] = C.unwords . map (C.pack . show) $ [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]\n\ncalc cur ot1 ot2 = inter1 + inter2 + 3 * uniq\n where inter1 = S.size $ cur `S.intersection` ot1\n inter2 = S.size $ cur `S.intersection` ot2\n uniq = S.size $ cur S.\\\\ (ot1 `S.union` ot2)\n\nwork = do\n n <- C.getLine\n t1 <- C.getLine\n t2 <- C.getLine\n t3 <- C.getLine\n\n C.putStrLn $ solve [ C.words x | x <- [t1, t2, t3] ]\n\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) work\n", "positive_code": [{"source_code": "{-#LANGUAGE ScopedTypeVariables#-}\r\nimport Data.Char (isDigit)\r\nimport Data.Set (Set, fromList, member)\r\n\r\nmain = do\r\n input <- getContents\r\n let parsed = removeDigits (lines input)\r\n let result = parseTriples parsed\r\n mapM_ putStrLn result\r\n\r\nremoveDigits :: [String] -> [String]\r\nremoveDigits [] = []\r\nremoveDigits (x:xs) \r\n | all isDigit x = removeDigits xs\r\n | otherwise = [x] ++ removeDigits xs\r\n\r\n-- Gets eachs persons input line, and parses it to a [String], which can be used in checkRound\r\nparseTriples :: [String] -> [String]\r\nparseTriples [] = []\r\nparseTriples (p1:p2:p3:rest) = [(checkRound (words p1) (words p2) (words p3))] ++ parseTriples rest\r\n\r\n-- Gets the score for each person, and outputs the score on the format: \"p1 p2 p3\"\r\ncheckRound :: [String] -> [String] -> [String] -> String \r\ncheckRound p1 p2 p3 = do \r\n let p1s = fromList p1\r\n let p2s = fromList p2\r\n let p3s = fromList p3\r\n let p1Score = getScore p1 p2s p3s\r\n let p2Score = getScore p2 p1s p3s\r\n let p3Score = getScore p3 p1s p2s\r\n (show p1Score) ++ \" \" ++ (show p2Score) ++ \" \" ++ (show p3Score)\r\n\r\n-- Takes each persons words, and outputs the score for the first person\r\ngetScore :: [String] -> Set String -> Set String -> Int\r\ngetScore [] _ _ = 0\r\ngetScore (x:xs) y z\r\n | (member x y) && (member x z) = 0 + getScore xs y z\r\n | (member x y) || (member x z) = 1 + getScore xs y z \r\n | otherwise = 3 + getScore xs y z\r\n"}, {"source_code": "import Data.Map (Map(..))\nimport qualified Data.Map as M\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>\n wl >>=\n \\w1 -> wl >>=\n \\w2 -> wl >>=\n \\w3 -> let cm = score w1 w2 w3\n a = maybe 0 id (M.lookup 1 cm)\n b = maybe 0 id (M.lookup 2 cm)\n c = maybe 0 id (M.lookup 3 cm)\n in\n putStrLn $ show a ++ \" \" ++ show b ++ \" \" ++ show c\n where wl = words <$> getLine\n\nscore :: [String] -> [String] -> [String] -> Map Int Int\nscore w1 w2 w3 = let m :: Map String [Int]\n m = M.empty\n iF s i = M.insertWith (++) s [i]\n w = zip w1 (repeat 1) ++ zip w2 (repeat 2) ++ zip w3 (repeat 3)\n f cm [i] = M.adjust (3+) i cm\n f cm [i, j] = M.adjust (1+) i (M.adjust (1+) j cm)\n f cm _ = cm\n in\n M.foldl f (M.fromList [(1, 0), (2, 0), (3, 0)])\n (foldl (\\m (s, i) -> iF s i m) m w)\n \n"}, {"source_code": "import Control.Monad\nimport Data.Set\n\nmain = do\n t <- read <$> getLine\n forM_ [1..t] $ const solve\n\nsolve = do\n getLine\n [nums1, nums2, nums3] <-\n (fmap . fmap) (fromList . words) (forM [1..3] $ const getLine)\n putStrLn $ unwords (fmap show [\n score nums1 nums2 nums3,\n score nums2 nums1 nums3,\n score nums3 nums1 nums2 ])\n return ()\n\nscore xs ys zs =\n sum $ fmap (\\x -> trans $ fromEnum (member x ys) + fromEnum (member x zs)) (toList xs)\n where\n trans x\n | x == 0 = 3\n | x == 1 = 1\n | x == 2 = 0\n | otherwise = undefined\n"}, {"source_code": "{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications, TupleSections #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List hiding (lookup)\r\nimport Debug.Trace\r\nimport Data.Char\r\nimport Data.Map (Map, fromListWith)\r\nimport qualified Data.Map as M\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- replicateM n getNext\r\n b <- replicateM n getNext\r\n c <- replicateM n getNext\r\n let\r\n combined = a ++ b\r\n -- tst = map (,1) combined\r\n counter = fromListWith (+) . map (,1) $ (a ++ b ++ c)\r\n score :: P.ByteString -> Int\r\n score s = case M.lookup s counter of\r\n Nothing -> 0\r\n Just x -> case x of\r\n 1 -> 3\r\n 2 -> 1\r\n 3 -> 0\r\n fun = sum . map score\r\n ansa = fun a\r\n ansb = fun b\r\n ansc = fun c\r\n pure $ putInts [ansa, ansb, ansc]\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List\nimport Debug.Trace (trace)\nimport qualified Data.Map as M\n\nreadInts = getLine >>= pure . map read . words\nhm 3 = 0\nhm 2 = 1\nhm 1 = 3\n\nmain = do\n [n'] <- readInts\n forM_ [1..n'] (\\_ -> do\n getLine\n a <- getLine >>= pure . words\n b <- getLine >>= pure . words\n c <- getLine >>= pure . words\n let m = M.fromList . map (\\l -> (head l, length l)) . group . sort $ a ++ b ++ c\n forM_ [a,b,c] (\\l -> do\n putStr . show . sum . map (hm . (m M.!)) $ l \n putStr \" \")\n putStrLn \"\" )"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport qualified Data.Set as S\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List\n\nsolve p =\n let s = map S.fromList p\n useless = (s !! 0) `S.intersection` (s !! 1) `S.intersection` (s !! 2)\n in solve1 $ map (\\x -> x S.\\\\ useless) s\n\nsolve1 [p1, p2, p3] = C.unwords . map (C.pack . show) $ [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]\n\ncalc cur ot1 ot2 = inter1 + inter2 + 3 * uniq\n where inter1 = S.size $ cur `S.intersection` ot1\n inter2 = S.size $ cur `S.intersection` ot2\n uniq = S.size $ cur S.\\\\ (ot1 `S.union` ot2)\n\nwork = do\n n <- C.getLine\n t1 <- C.getLine\n t2 <- C.getLine\n t3 <- C.getLine\n\n C.putStrLn $ solve [ C.words x | x <- [t1, t2, t3] ]\n\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) work\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport qualified Data.Map.Strict as M\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List\n\n--solve p = solve1 (map countElems p)\n--solve :: [C.ByteString] -> [C.ByteString]\nsolve p = solve1 $ map countElems p\n\nsolve1 [p1, p2, p3] = unwords . map show $ [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]\n\ncalc cur ot1 ot2 = inter1 + inter2 + 3 * uniq\n where inter1 = M.size $ cur `M.intersection` ot1\n inter2 = M.size $ cur `M.intersection` ot2\n uniq = M.size $ cur M.\\\\ (ot1 `M.union` ot2)\n\ncountElems = M.fromListWith (+) . flip zip (repeat 1)\n\ndel x y z = length $ x \\\\ (y `union` z)\ninter x y = length $ x `intersect` y\n\nwork = do\n n <- C.getLine\n t1 <- C.getLine\n t2 <- C.getLine\n t3 <- C.getLine\n\n putStrLn $ solve [ C.words x | x <- [t1, t2, t3] ]\n\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) work\n"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport qualified Data.Map.Strict as M\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List\n\n--solve p = solve1 (map countElems p)\n--solve :: [C.ByteString] -> [C.ByteString]\nsolve p = solve1 $ map countElems p\n\nsolve1 [p1, p2, p3] = [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]\n\ncalc cur ot1 ot2 = inter1 + inter2 + 3 * uniq\n where inter1 = M.size $ cur `M.intersection` ot1\n inter2 = M.size $ cur `M.intersection` ot2\n uniq = M.size $ cur M.\\\\ (ot1 `M.union` ot2)\n\ncountElems = M.fromListWith (+) . flip zip (repeat 1)\n\ndel x y z = length $ x \\\\ (y `union` z)\ninter x y = length $ x `intersect` y\n\nwork = do\n n <- C.getLine\n t1 <- C.getLine\n t2 <- C.getLine\n t3 <- C.getLine\n\n print $ solve [ C.words x | x <- [t1, t2, t3] ]\n\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) work\n"}], "src_uid": "f8a89510fefbbc8e5698efe8a0c30927"} {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n noTypes <- read <$> getLine\r\n types <- map read . words <$> getLine\r\n let (maxmax, maxx) = twoMaxes types (0, 0)\r\n let res\r\n | noTypes == 1 =\r\n if head types > 1\r\n then \"NO\"\r\n else \"YES\"\r\n | maxmax - maxx > 1 = \"NO\"\r\n | otherwise = \"YES\"\r\n putStrLn res\r\n\r\ntwoMaxes :: Ord a => [a] -> (a, a) -> (a, a)\r\ntwoMaxes [] (a, b) = (a, b)\r\ntwoMaxes (x:xs) (a, b)\r\n | x > a = twoMaxes xs (x, a)\r\n | x > b = twoMaxes xs (a, x)\r\n | otherwise = twoMaxes xs (a, b)\r\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n noTypes <- read <$> getLine\r\n types <- map read . words <$> getLine\r\n let (maxmax, maxx) = twoMaxes types (0, 0)\r\n let res\r\n | noTypes == 1 =\r\n if head types > 1\r\n then \"NO\"\r\n else \"YES\"\r\n | maxmax - maxx > 1 = \"NO\"\r\n | otherwise = \"YES\"\r\n putStrLn res\r\n\r\ntwoMaxes :: Ord a => [a] -> (a, a) -> (a, a)\r\ntwoMaxes [] (a, b) = (a, b)\r\ntwoMaxes (x:xs) (a, b)\r\n | x > a = twoMaxes xs (x, a)\r\n | x > b = twoMaxes xs (a, x)\r\n | otherwise = twoMaxes xs (a, b)\r\n"}], "negative_code": [], "src_uid": "8b926a19f380a56018308668c17c6928"} {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n let ds = zipWith subtract <*> tail $ solve n\n print $ length ds\n putStrLn $ unwords . map show $ ds\n\nsolve n = sort $ f 1 n\n\nf _ 0 = []\nf i n\n | i > n = [n]\n | otherwise = i : f (2 * i) (n - i)", "positive_code": [{"source_code": "\npowersOf2 :: [Int]\npowersOf2 = go 1\n where\n go aux = aux : go (aux*2)\n\ndiff :: Int -> [Int] -> [Int]\ndiff excess (a:as)\n | excess <= a = [excess]\n | otherwise = a: diff (excess-a) as\n\nnumberOfDays :: Int -> (Int, Int)\nnumberOfDays n = (d, n-2^d)\n where\n d = floor . logBase 2 . fromIntegral $ n\n\nincrements :: [Int] -> [Int]\nincrements (a1:a2:as) = (a2-a1): increments (a2:as)\nincrements _ = []\n\nsolve :: Int -> [String]\nsolve n = [show d, unwords $ map show inc]\n where\n (d,e) = numberOfDays n\n delta = diff e powersOf2 ++ [0,0..]\n count = 1 : take d (zipWith (+) delta powersOf2)\n inc = increments count\n\ntest = solve 9\n\nmain :: IO ()\nmain = interact $ unlines . concatMap (solve . read) . tail . lines"}], "negative_code": [], "src_uid": "e21f235ffe7f26d9a7af12a7f3f9a2fd"} {"source_code": "module Main where\n\nreadI :: String -> Int\nreadI = read \n\nreadL :: String -> [Double]\nreadL = (map read) . words\n\nmain = do\n n <- getLine >>= return . readI\n ps <- getContents >>= return . (map readL) . (take n) . lines\n print $ solve n ps\n\nsolve n ps = inter pairs y0 l r where\n \n pairs = tail (zip ps (tail ps ++ [head ps]))\n \n a = head ps\n b = ps!!1\n l = min (head a) (head b)\n r = max (head a) (head b)\n y0 = a!!1\n \n inter [] _ l r = if l > r then 0 else (floor r) - (ceiling l) + 1\n \n inter (([x1,y1], [x2,y2]):ps) y0 l r = case compare dy 0 of\n EQ -> if dx0 <= 0 then inter ps y0 l r\n else 0\n GT -> inter ps y0 (max l x0) r\n LT -> inter ps y0 l (min x0 r)\n where\n dy = y2 - y1\n dx = x2 - x1\n c = dx*y1 - dy*x1\n dx0 = dx*y0 - c\n x0 = dx0 / dy\n", "positive_code": [{"source_code": "module Main where\n\nreadI :: String -> Int\nreadI = read \n\nreadL :: String -> [Double]\nreadL = (map read) . words\n\nmain = do\n n <- getLine >>= return . readI\n ps <- getContents >>= return . (map readL) . (take n) . lines\n print $ solve n ps\n\nsolve n ps = inter pairs y0 l r where\n \n pairs = tail (zip ps (tail ps ++ [head ps]))\n \n a = head ps\n b = ps!!1\n l = min (head a) (head b)\n r = max (head a) (head b)\n y0 = a!!1\n \n inter _ _ l r | l > r = 0\n inter [] _ l r = (floor r) - (ceiling l) + 1\n\n inter (([x1,y1], [x2,y2]):ps) y0 l r = case compare dy 0 of\n EQ -> if dx0 <= 0 then inter ps y0 l r\n else 0\n GT -> inter ps y0 (max l x0) r\n LT -> inter ps y0 l (min x0 r)\n where\n dy = y2 - y1\n dx = x2 - x1\n c = dx*y1 - dy*x1\n dx0 = dx*y0 - c\n x0 = dx0 / dy\n"}], "negative_code": [], "src_uid": "1503f0379bf8d7f25c191ddea9278842"} {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n", "positive_code": [{"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n (a:b:c:_) = x\n f _ _ [] = 0\n f a b (h:t) = if a == h then f (a*b) b t else f a b t + 1"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n\n"}], "negative_code": [{"source_code": "main = do getLine; getLine >>= putStr . show . gao . map read . words\ngao x = if length x < 3 then 0 else minimum $ 2:[f j (div i j) x | (i, j) <- [(c, b), (c, a), (b, a)], j /= 0, mod i j == 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map read . words\ngao [0, 0] = 0\ngao [0, _] = 1\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else div j i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0 && mod j i == 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n"}, {"source_code": "main = do getLine; getLine >>= putStr . show . gao . map read . words\ngao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else div j i) x | (i, j) <- [(b, c), (a, c), (a, b)], i /= 0 && mod j i == 0 || j == 0] where\n\t(a:b:c:_) = x\n\tf _ _ [] = 0\n\tf a b (h:t) = if a == h then f (a*b) b t else f a b t + 1\n"}], "src_uid": "a32db37cb2ebe8945a4c2f32fa2d7fc8"} {"source_code": "module Main (main) where\n\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n input <- getLine\n let [a, b] = map readInt $ take 2 $ words input\n input <- getContents\n let picture = take a $ lines input\n let good = goodPuzzles a b picture\n print $ length good\n printPair $ minimumBy compareXY good where\n \n goodPuzzles a b picture = filter isGoodPuzzle pairs where\n \n isGoodPuzzle (n, m) = isGood $ sort $ makeSprites n m where\n isGood [s] = True\n isGood (s:ss) = if s == (head ss) then False else isGood ss\n \n makeSprites n m = makeSplitList a b picture [] where\n makeSplitList 0 _ _ acc = acc\n makeSplitList sn sm pic acc = \n makeSplitList (sn-n) sm (drop n pic) \n (makeSplit sm (take n pic) [] ++ acc)\n makeSplit 0 _ acc = acc\n makeSplit sm pic acc = \n makeSplit (sm-m) (map (drop m) pic) \n (map concat (rotates n m (map (take m) pic)) ++ acc)\n rotates n m pic = if n == m\n then nub [pic, rot90, rot180, rot270]\n else nub [pic, rot180] where\n rot90 = transpose reversed\n rot180 = map reverse reversed\n rot270 = reverse (transpose pic)\n reversed = reverse pic\n \n pairs = [(x, y) | x <- divisors a, y <- divisors b]\n divisors n = [x | x <- [1..n], mod n x == 0]\n \n compareXY (x1, y1) (x2, y2) = case compare (x1*y1) (x2*y2) of\n LT -> LT\n GT -> GT\n EQ -> compare x1 x2\n \n printPair (x, y) = do\n putStrLn $ show x ++ \" \" ++ show y\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nexplode' i x = take i . map (take x) . iterate (drop x)\nexplode :: Int -> Int -> Int -> Int -> [String] -> [[String]]\nexplode i x j y = concatMap (map (map head) . take j . iterate (map tail)) . explode' i x . map (explode' j y)\nrotate = reverse . transpose\nstd = minimum . take 4 . iterate rotate\n\ngao r c s = [[x * y, x, y] |\n\tx <- [1 .. r], i <- [div r x], i * x == r,\n\ty <- [1 .. c], j <- [div c y], j * y == c,\n\t(==i*j) $ length $ group $ sort $ map std $ explode i x j y s]\n\nmain = do\n\t[r, c] <- fmap (map read . words) getLine\n\ts <- replicateM r getLine\n\tputStrLn $ let a = gao r c s in unwords $ map show $ (length a:) $ tail $ minimum a \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nexplode' i x = take i . map (take x) . iterate (drop x)\nexplode i x j y = concatMap (map (map head) . take j . iterate (map tail)) . explode' i x . map (explode' j y)\nrotate = reverse . transpose\nstd = minimum . take 4 . iterate rotate\n\ngao r c s = [[x * y, x, y] |\n\tx <- [1 .. r], i <- [div r x], i * x == r,\n\ty <- [1 .. c], j <- [div c y], j * y == c,\n\t(==i*j) $ length $ group $ sort $ map std $ explode i x j y s]\n\nmain = do\n\t[r, c] <- fmap (map read . words) getLine\n\ts <- replicateM r getLine\n\tputStrLn $ let a = gao r c s in unwords $ map show $ (length a:) $ tail $ minimum a \n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n\nimport Data.Array.IArray\nimport Data.List\nimport Text.Printf\nimport Debug.Trace\n\ntype Block = Array (Int, Int) Char\n\nsize :: Block -> (Int, Int)\nsize blk =\n let (_, (h, w)) = bounds blk\n in (h+1,w+1)\n\nrotate :: Block -> Block\nrotate blk =\n let (size -> (h, w)) = blk\n in listArray ((0,0), (w-1,h-1)) \n [blk ! (c, w-r-1) | r <- [0..w-1], c <- [0..h-1]]\n\nminrep :: Block -> Block\nminrep blk = minimum $ take 4 $ iterate rotate blk\n\nvalid :: [Block] -> Bool\nvalid list =\n let sorted = sort $ map minrep list\n in and $ zipWith (/=) sorted (tail sorted)\n\nsplit :: Block -> Int -> Int -> [Block]\nsplit blk a b =\n let (size -> (h, w)) = blk\n in [listArray ((0,0), (a-1,b-1))\n [blk ! (h'*a+a', w'*b+b') | a' <- [0..a-1], b' <- [0..b-1]]\n | h' <- [0..h `div` a - 1], w' <- [0..w `div` b - 1]]\n\nsolve :: Block -> [[Block]]\nsolve blk =\n let (size -> (h, w)) = blk\n divable x y = x `mod` y == 0\n allblk = [split blk a b | a <- filter (divable h) [1..h],\n b <- filter (divable w) [1..w]]\n in filter valid allblk\n\ncmp :: [Block] -> [Block] -> Ordering\ncmp (a:_) (b:_) =\n let (size -> (ha, wa)) = a\n (size -> (hb, wb)) = b\n in case compare (ha * wa) (hb * wb) of\n EQ -> compare ha hb\n ne -> ne\n\nreadBlk :: Int -> Int -> IO Block\nreadBlk w h = do\n list <- (concat . words) `fmap` getContents\n return $ listArray ((0,0), (w-1,h-1)) list\n\nmain = do\n [w, h] <- (map read . words) `fmap` getLine\n blk <- readBlk w h\n\n let ans = solve blk\n printf \"%d\\n\" (length ans)\n\n let (size -> (x, y)) = head $ minimumBy cmp ans\n printf \"%d %d\\n\" x y\n"}], "negative_code": [{"source_code": "module Main (main) where\n\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n input <- getLine\n let [a, b] = map readInt $ take 2 $ words input\n input <- getContents\n let picture = take a $ lines input\n let good = goodPuzzles a b picture\n print $ length good\n printPair $ minimumBy compareXY good where\n \n goodPuzzles a b picture = filter isGoodPuzzle pairs where\n \n isGoodPuzzle (n, m) = isGood $ sort $ makeSprites n m where\n isGood [s] = True\n isGood (s:ss) = if s == (head ss) then False else isGood ss\n \n makeSprites n m = makeSplitList a b picture [] where\n makeSplitList 0 _ _ acc = acc\n makeSplitList sn sm pic acc = \n makeSplitList (sn-n) sm (drop n pic) \n (acc ++ makeSplit sm (take n pic) [])\n makeSplit 0 _ acc = acc\n makeSplit sm pic acc = \n makeSplit (sm-m) (map (drop m) pic) \n ((concat (map (take m) pic)):acc)\n \n pairs = [(x, y) | x <- divisors a, y <- divisors b]\n divisors n = [x | x <- [1..n], mod n x == 0]\n \n compareXY (x1, y1) (x2, y2) = case compare (x1*y1) (x2*y2) of\n LT -> LT\n GT -> GT\n EQ -> compare x1 x2\n \n printPair (x, y) = do\n putStrLn $ show x ++ \" \" ++ show y\n"}], "src_uid": "4de8b72f9ce12554cae8b6a83b3f023e"} {"source_code": "{-# LANGUAGE NPlusKPatterns #-}\nmodule Main (main) where\n\nimport Control.Monad (liftM2, liftM3, mapM_)\n\ntype Query = (Integer, Integer, Integer)\n\nmain :: IO ()\nmain = do\n t <- getInteger\n queries <- getQueries t\n mapM_ (print . calculate) queries\n\ngetInteger :: IO Integer\ngetInteger = fmap read getLine\n\ngetQueries :: Integer -> IO [Query]\ngetQueries 0 = return []\ngetQueries (n + 1) = liftM2 (:) getQuery (getQueries n)\n\ngetQuery :: IO Query\ngetQuery = fmap ((\\[a, b, k] -> (a, b, k)) . map read . words) getLine\n\ncalculate :: Query -> Integer\ncalculate (a, b, k) = let (q, r) = quotRem k 2\n in q * (a - b) + r * a\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.Int\n\nmain :: IO ()\nmain = readLn >>= ntimes solve\n\nntimes :: IO () -> Int -> IO ()\nntimes _ 0 = return ()\nntimes io n = io >> ntimes io (n - 1)\n\nsolve :: IO ()\nsolve = do\n [a, b, k] :: [Int64] <- map read . words <$> getLine\n let ans = k `div` 2 * (a - b)\n if k `mod` 2 /= 0 then print $ ans + a else print ans\n\n"}, {"source_code": "main :: IO ()\nmain = interact $ processInput.parseInput\n\nreadInteger :: String -> Integer\nreadInteger = read\n\nparseInput :: String -> [[Integer]]\nparseInput inputFromFile = tail [[readInteger x | x <- words line] | line <- lines inputFromFile]\n\ncalcFunc :: Integer -> Integer -> Integer -> Integer\ncalcFunc a b k\n | odd k = (a-b)*((k-1)`div` 2) + a\n | otherwise = (a - b)*(k`div` 2)\n \nprocessInput :: [[Integer]] -> String\nprocessInput [] = \"\"\nprocessInput (x:xs) = (show $ calcFunc (x !! 0) (x !! 1) (x !! 2))++ \"\\n\" ++ processInput xs\n\n"}, {"source_code": "solve :: [Integer] -> Integer\nsolve (a:b:k:_) = (a - b) * (k `div` 2) + a * (k `mod` 2)\n\n\nmain :: IO()\nmain = do\n n <- getLine\n x <- getContents\n mapM_ (putStrLn . show . solve . (map (read::String->Integer)) . words) $ lines x"}, {"source_code": "readInteger :: String -> Integer\nreadInteger = read\n\nparseInput :: String -> [[Integer]]\nparseInput file\n = tail [ [readInteger word | word <- words line] | line <- lines file ]\n\nprocessInput :: [[Integer]] -> [Integer]\nprocessInput [] = []\nprocessInput ([right, left, steps] : others)\n = pos : (processInput others)\n where pos = if even steps then total else total + right\n total = (right - left) * (steps `div` 2)\n \n\nshowOutput :: [Integer] -> String\nshowOutput [] = \"\"\nshowOutput (x:xs) = (show x) ++ \"\\n\" ++ (showOutput xs)\n\nmain = interact $ showOutput . processInput . parseInput\n"}, {"source_code": "getFrogs :: Int -> IO [[Integer]]\ngetFrogs 0 = do return []\ngetFrogs t = do\n line <- getLine\n let xs = map (\\s -> read s :: Integer) (words line)\n more <- getFrogs (t - 1)\n return (xs : more)\n\nmain = do\n line <- getLine\n let n = read line :: Int\n frogs <- getFrogs n\n mapM print (positions frogs)\n\n\npositions :: [[Integer]] -> [Integer]\npositions [] = []\npositions ([right, left, steps] : frogs)\n = pos : (positions frogs)\n where pos = if even steps then total else total + right\n total = (right - left) * (steps `div` 2)\n"}, {"source_code": "\nf::[String]->[Integer]\nf []=[]\nf (x:xs)=let (a:b:k:[])=map read (words x)::[Integer]\n in if k `mod` 2==1 then ((a-b)*(k `div` 2)+a):(f xs) else (a-b)*(k `div` 2):f xs\n\nmain = do\n a<-getLine\n b<-getContents\n let xs=lines b\n mapM_ putStrLn $ map show $ f xs"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\nmain = getLine \n >>= readQueries . read\n >>= putStrLn . calc\n\nreadQueries :: Int -> IO [String]\nreadQueries t = mapM (\\_ -> getLine) [1..t]\n\ncalc :: [String] -> String\ncalc lines = foldr go \"\" lines\n where go line ans = show res ++ \"\\n\" ++ ans\n where [s1, s2, s3] = words line\n a = read s1\n b = read s2\n k = read s3\n halfK = div k 2\n res = ((.&.) k 1 + halfK) * a - (b * halfK) :: Integer\n \n"}, {"source_code": "import Prelude\nimport Data.List\nimport Text.Printf\nimport Control.Monad\nimport Data.Ratio\nimport Data.Int\nimport Data.Functor\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64\nsolve a b k = k1 * a - k2 * b\n where\n k1 = k - k2\n k2 = k `div` 2 \n\nmain :: IO ()\nmain = do\n t <- (read :: String -> Int) <$> getLine\n replicateM_ t $ do\n [a, b, k] <- (map (read :: String -> Int64) . words) <$> getLine\n printf \"%lld\\n\" $ solve a b k"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Integer] -> Integer\nsolve [a, b, k]\n | even k = (a - b) * c\n | otherwise = (a - b) * c + a\n where c = div k 2\n\nmain :: IO ()\nmain = do\n t <- readInt\n qs <- replicateM t $ readInts\n mapM_ print $ map solve $ map (map toInteger) qs"}, {"source_code": "import Data.Int\nimport Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a,b,k] <- map read . words <$> getLine\n print ((k+1) `div` 2 * a - k `div` 2 * b :: Int64)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nonecase = do\n\t\t[a,b,k]<- map read <$> words <$> getLine ::IO [Integer]\n\t\tprint $ (a-b)*(div k 2) + a *(mod k 2)\n\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "--ghc 7.10\n\nfinalPosition a b k = kOdd * a - kEven * b\n where\n kEven = k `div` 2\n kOdd = k - kEven\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let qs = map (map read . words) . lines $ contents :: [[Integer]]\n sequence . map print . map (\\[a,b,k] -> finalPosition a b k) $ qs"}, {"source_code": "module Main where\n\nimport Control.Monad\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetList :: IO [Integer]\ngetList = (map read) <$> words <$> getLine\n\nsolve :: [Integer] -> Integer\nsolve ins =\n let a = ins !! 0\n b = ins !! 1\n k = ins !! 2\n c = k `div` 2\n in ((-1) * b * c) + (k - c) * a\n \nmain :: IO ()\nmain = do\n t <- getInt\n replicateM_ t $ do ins <- getList\n print $ solve ins \n \n \n"}], "negative_code": [{"source_code": "getFrogs :: Int -> IO [[Int]]\ngetFrogs 0 = do return []\ngetFrogs t = do\n line <- getLine\n let xs = map (\\s -> read s :: Int) (words line)\n more <- getFrogs (t - 1)\n return (xs : more)\n\nmain = do\n line <- getLine\n let n = read line :: Int\n frogs <- getFrogs n\n mapM print (positions frogs)\n\n\npositions :: [[Int]] -> [Int]\npositions [] = []\npositions ([right, left, steps] : frogs)\n = pos : (positions frogs)\n where pos = if even steps then total else total + right\n total = (right - left) * (steps `div` 2)\n"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\nmain = getLine \n >>= readQueries . read\n >>= putStrLn . calc\n\nreadQueries :: Int -> IO [String]\nreadQueries t = mapM (\\_ -> getLine) [1..t]\n\ncalc :: [String] -> String\ncalc lines = foldr go \"\" lines\n where go line ans = show res ++ \"\\n\" ++ ans\n where [s1, s2, s3] = words line\n a = read s1\n b = read s2\n k = read s3\n halfK = div k 2\n res = (.&.) k 1 + halfK * a - (b * halfK) :: Int\n"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\nmain = getLine \n >>= readQueries . read\n >>= putStrLn . calc\n\nreadQueries :: Int -> IO [String]\nreadQueries t = mapM (\\_ -> getLine) [1..t]\n\ncalc :: [String] -> String\ncalc lines = foldr go \"\" lines\n where go line ans = show res ++ \"\\n\" ++ ans\n where [s1, s2, s3] = words line\n a = read s1\n b = read s2\n k = read s3\n halfK = div k 2\n res = (.&.) k 1 + halfK * a - (b * halfK) :: Integer\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve [a, b, k]\n | even k = (a - b) * c\n | otherwise = (a * (c + 1)) - b * c\n where c = div k 2\n\nmain :: IO ()\nmain = do\n t <- readInt\n qs <- replicateM t $ readInts\n mapM_ print $ map solve qs"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve [a, b, k]\n | even k = (a - b) * c\n | otherwise = (a - b) * c + a\n where c = div k 2\n\nmain :: IO ()\nmain = do\n t <- readInt\n qs <- replicateM t $ readInts\n mapM_ print $ map solve qs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nonecase = do\n\t\t[a,b,k]<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ (a-b)*(div k 2) + a *(mod k 2)\n\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "--ghc 7.10\n\nfinalPosition a b k = kOdd * a - kEven * b\n where\n kEven = k `div` 2\n kOdd = k - kEven\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let qs = map (map read . words) . lines $ contents :: [[Int]]\n sequence . map print . map (\\[a,b,k] -> finalPosition a b k) $ qs"}, {"source_code": "--ghc 7.10\n\nfinalPosition :: (Integral a) => a -> a -> a -> a\nfinalPosition a b k = kOdd * a - kEven * b\n where\n kEven = k `div` 2\n kOdd = k - kEven\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let qs = map (map read . words) . lines $ contents :: [[Int]]\n sequence . map print . map (\\[a,b,k] -> finalPosition a b k) $ qs"}], "src_uid": "1f435ba837f59b007167419896c836ae"} {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> B.ByteString -> Int64\nsolve k s\n | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s\n | B.count '1' s < k = 0\n | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s\n where n = B.length s\n kth = (B.findIndices (== '1') s) !! (k-1)\n f (!a, (!j, !c)) d\n | d == '0' = (na, (j, c))\n | d == '1' = if j+c < n\n then (na, (j+c, 1 + zeros (j+c) s))\n else (na, (n, 0))\n where na = a + fromIntegral c\n\n\nzeros :: Int -> B.ByteString -> Int\nzeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)\n\nl2 :: B.ByteString -> Int64\nl2 s = (l * (l+1)) `div` 2\n where l = fromIntegral $ B.length s\n\nmain = do\n k <- read . B.unpack <$> B.getLine\n s <- head . B.words <$> B.getLine\n-- [k', s] <- B.words <$> B.getContents\n-- let k = read . B.unpack $ k'\n putStrLn . show $ solve k s\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> B.ByteString -> Integer\nsolve k s\n | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s\n | B.count '1' s < k = 0\n | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s\n where n = B.length s\n kth = (B.findIndices (== '1') s) !! (k-1)\n f (!a, (!j, !c)) d\n | d == '0' = (na, (j, c))\n | d == '1' = if j+c < n\n then (na, (j+c, 1 + zeros (j+c) s))\n else (na, (n, 0))\n where na = a + fromIntegral c\n\n\nzeros :: Int -> B.ByteString -> Int\nzeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)\n\nl2 :: B.ByteString -> Integer\nl2 s = (l * (l+1)) `div` 2\n where l = fromIntegral $ B.length s\n\nmain = do\n [k', s] <- B.words <$> B.getContents\n let k = read . B.unpack $ k'\n putStrLn . show $ solve k s\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> B.ByteString -> Int64\nsolve k s\n | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s\n | B.count '1' s < k = 0\n | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s\n where n = B.length s\n kth = (B.findIndices (== '1') s) !! (k-1)\n f (!a, (!j, !c)) d\n | d == '0' = (na, (j, c))\n | d == '1' = if j+c < n\n then (na, (j+c, 1 + zeros (j+c) s))\n else (na, (n, 0))\n where na = a + fromIntegral c\n\n\nzeros :: Int -> B.ByteString -> Int\nzeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)\n\nl2 :: B.ByteString -> Int64\nl2 s = (l * (l+1)) `div` 2\n where l = fromIntegral $ B.length s\n\nmain = do\n [k', s] <- B.words <$> B.getContents\n let k = read . B.unpack $ k'\n putStrLn . show $ solve k s\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . lines)\n\nsolve :: [String] -> Integer\nsolve [sK, str] = answer where\n answer = case k of\n 0 -> sum $ map (\\x -> x * (x - 1) `div` 2) oneGroups\n _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)\n oneGroups = map (fromIntegral . length) $ group sums :: [Integer]\n sums = elems sumArray\n\n sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]\n allBounds = (0, snd $ bounds strArray)\n\n sumArrayF 0 = 0\n sumArrayF i = strArray ! i + sumArray ! (i - 1)\n\n strArray = listArray (1, length str) $ map ((\\x -> x - ord '0') . ord) str\n k = read sK :: Int\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as C\nimport IO\nimport Data.Maybe\n\nmain = print . solve =<< parse stdin\n-- main = print . solve $ (215001, C.replicate (1000000) '1')\n\nparse h = do\n input <- glines $ C.hGetContents h\n let k = readInt $ input !! 0\n s = input !! 1\n return (k, s)\n\nsolve :: (Int, C.ByteString) -> Integer\nsolve (k, s)\n | k == 0 = sum $ map g z\n | k /= 0 = sum $ zipWith f z (drop k z)\n where\n z = map C.length . C.split '1' $ s\n f x y = (fromIntegral x + 1) * (fromIntegral y + 1)\n g x = fromIntegral x * (fromIntegral x + 1) `div` 2\n\n-- lib\n\nglines = fmap (map (C.takeWhile (/='\\r')) . C.lines)\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\n-- vim: set expandtab:\n"}, {"source_code": "import Control.Monad\nimport Data.List\nencode :: String -> [Integer]\nencode s = let (s1, s2) = span (== '0') s\n in if null s2 then [genericLength s1 + 1]\n else genericLength s1 + 1: encode (tail s2)\nmain = do\n k <- (liftM read) getLine\n s <- getLine\n let l = encode s\n putStrLn . show . sum $ if k == 0 then map (\\x -> div (x * (x-1)) 2) l\n else zipWith (*) l (drop k l)\n"}, {"source_code": "split x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nsolve k s\n\t| k == 0 = sum $ map (\\c -> c*(c-1) `div` 2) cs\n\t| otherwise = sum $ zipWith (*) cs $ drop k cs\n\twhere\n\t\tcs = map fromIntegral . map ((+ 1) . length) $ split '1' s\n\nmain = do\n\tk <- readLn\n\ts <- getLine\n\tprint $ solve k s\n"}, {"source_code": "\n-- 2\n-- 01000110000111\n\n-- 0111123333333456\n-- 0 2 6 7 12 13 14 16\n\n\n-- 0 2 7 12 -> 2*5\n-- 2 6 12 13 -> 4*1\n-- 6 7 13 14 -> 1*1\n-- 7 12 14 16 -> 2*5\n\n-- 010001\n-- 10001\n-- 00011\n-- 000110\n-- 0001100\n-- 00011000\n-- 000110000\n-- 0011\n-- 00110\n-- 001100\n-- 0011000\n-- 00110000\n-- 011\n-- 0110\n-- 01100\n-- 011000\n-- 0110000\n-- 11\n-- 110\n-- 1100\n-- 11000\n-- 110000\n-- 100001\n-- 000011\n-- 00011\n-- 0011\n-- 011\n-- 11\n-- 11\n\n-- 29\n\nimport Data.List\n\nsublists :: [a] -> [[a]]\nsublists s = tails s >>= inits\n\nslowSolve n line = length $ filter ((== n) . length . filter (=='1')) $ sublists line\n\ntest n = take n (cycle \"0101010010100100101101001010101\")\n\nsolve :: Int -> String -> Integer\nsolve 0 line = solveZ ones 0\n where\n ones = [0] ++ (map snd $ filter (('1' ==) . fst) (zip line [1..])) ++ [length line + 1]\n solveZ :: [Int] -> Integer -> Integer\n solveZ (l1:l2:ls) acc = acc' `seq` solveZ (l2:ls) acc'\n where\n m = toInteger (l2 - l1 - 1)\n acc' = acc + div ((m+1) * m) 2\n solveZ _ acc = acc\n\nsolve n line = solve' ones (drop n ones) 0\n where\n ones = [0] ++ (map snd $ filter (('1' ==) . fst) (zip line [1..])) ++ [length line + 1]\n solve' :: [Int] -> [Int] -> Integer -> Integer\n solve' (l1:l2:ls) (r1:r2:rs) acc = acc' `seq` solve' (l2:ls) (r2:rs) acc'\n where\n acc' = acc + ((toInteger l2 - toInteger l1) * (toInteger r2 - toInteger r1))\n solve' _ _ acc = acc\n\n\n\nmain :: IO ()\nmain = do\n n <- readLn::IO Int\n line <- getLine\n print $ solve n line\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> B.ByteString -> Int64\nsolve k s\n | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s\n | B.count '1' s < k = 0\n | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s\n where n = B.length s\n kth = (B.findIndices (== '1') s) !! (k-1)\n f (!a, (!j, !c)) d\n | d == '0' = (na, (j, c))\n | d == '1' = if j+c < n\n then (na, (j+c, 1 + zeros (j+c) s))\n else (na, (n, 0))\n where na = a + fromIntegral c\n\n\nzeros :: Int -> B.ByteString -> Int\nzeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)\n\nl2 :: B.ByteString -> Int64\nl2 s = let l = fromIntegral $ B.length s in (l * (l+1)) `div` 2\n\nmain = do\n [k', s] <- B.words <$> B.getContents\n let k = read . B.unpack $ k'\n putStrLn . show $ solve k s"}, {"source_code": "main = interact $ show.solve.(\\[x,y]->(read x,y)).lines\n\nsolve :: (Int,String) -> Integer\nsolve (0,cs) = sum.map (\\n->(n*(n-1))`div`2)$ f cs\nsolve (k,cs) = sum.s (zipWith (*)) (drop k) $ f cs\n where s g h x = g x (h x)\n\nf :: String -> [Integer]\nf cs = case span ('0'==) cs of\n (xs,(y:ys)) -> (succ.fromIntegral.length $ xs):f ys\n (xs,[]) -> return.succ.fromIntegral.length $ xs"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> B.ByteString -> Int64\nsolve k s\n | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s\n | B.count '1' s < k = 0\n | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s\n where n = B.length s\n kth = (B.findIndices (== '1') s) !! (k-1)\n f (!a, (!j, !c)) d\n | d == '0' = (na, (j, c))\n | d == '1' = if j+c < n\n then (na, (j+c, 1 + zeros (j+c) s))\n else (na, (n, 0))\n where na = a + fromIntegral c\n\n\nzeros :: Int -> B.ByteString -> Int\nzeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)\n\nl2 :: B.ByteString -> Int64\nl2 s = let l = fromIntegral $ B.length s in (l * (l+1)) `div` 2\n\nmain = do\n [k', s] <- B.words <$> B.getContents\n let k = read . B.unpack $ k'\n putStrLn . show $ solve k s\n"}, {"source_code": "split x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nsolve k s\n\t| k == 0 = sum $ map (\\c -> c*(c-1) `div` 2) cs\n\t| otherwise = sum $ zipWith (*) cs $ drop k cs\n\twhere\n\t\tcs = map fromIntegral . map ((+ 1) . length) $ split '1' s\n\nmain = do\n\tk <- readLn\n\ts <- getLine\n\tprint $ solve k s\n"}, {"source_code": "import Data.Int\n\nsplit x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nsolve k s\n\t| k == 0 = sum $ map (\\c -> c*(c-1) `div` 2) cs\n\t| otherwise = sum $ zipWith (*) (drop k cs) cs\n\twhere\n\t\tcs = map fromIntegral . map ((+ 1) . length) $ split '1' s\n\nmain = do\n\tk <- readLn\n\ts <- getLine\n\tprint (solve k s)\n"}, {"source_code": "split x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nsolve k s\n\t| k == 0 = sum $ map (\\c -> c*(c-1) `div` 2) cs\n\t| otherwise = sum $ zipWith (*) (drop k cs) cs\n\twhere\n\t\tcs = map ((+ 1) . fromIntegral . length) $ split '1' s\n\nmain = do\n\tk <- readLn\n\ts <- getLine\n\tprint $ solve k s\n"}], "negative_code": [{"source_code": "{- OPTIONS_GHC -O3 -fno-spec-constr-count -}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> B.ByteString -> Integer\nsolve k s\n | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s\n | B.count '1' s < k = 0\n | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s\n where n = B.length s\n kth = (B.findIndices (== '1') s) !! (k-1)\n f (a, (j, c)) d\n | d == '0' = (na, (j, c))\n | d == '1' = if j+c < n\n then (na, (j+c, 1 + zeros (j+c) s))\n else (na, (n, 0))\n where na = a + fromIntegral c\n\n\nzeros :: Int -> B.ByteString -> Int\nzeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)\n\nl2 :: B.ByteString -> Integer\nl2 s = l * l\n where l = fromIntegral $ B.length s\n\nmain = do\n [k', s] <- B.words <$> B.getContents\n let k = read . B.unpack $ k'\n putStrLn . show $ solve k s\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . lines)\n\nsolve :: [String] -> Int\nsolve [sK, str] = answer where\n answer = case k of\n 0 -> sum $ map (\\x -> x * (x - 1) `div` 2) oneGroups\n _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)\n oneGroups = map length $ group sums\n sums = elems sumArray\n\n sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]\n allBounds = (0, snd $ bounds strArray)\n\n sumArrayF 0 = 0\n sumArrayF i = strArray ! i + sumArray ! (i - 1)\n\n strArray = listArray (1, length str) $ map ((\\x -> x - ord '0') . ord) str\n k = read sK :: Int\n\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . lines)\n\nsolve :: [String] -> Int\nsolve [sK, str] = answer where\n answer = case k of\n 0 -> length $ filter (=='0') str\n 1 -> length $ filter (=='1') str\n _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)\n oneGroups = map length $ group sums\n sums = elems sumArray\n\n sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]\n allBounds = (0, snd $ bounds strArray)\n\n sumArrayF 0 = 0\n sumArrayF i = strArray ! i + sumArray ! (i - 1)\n\n strArray = listArray (1, length str) $ map ((\\x -> x - ord '0') . ord) str\n k = read sK :: Int\n\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . lines)\n\nsolve :: [String] -> Int\nsolve [sK, str] = answer where\n answer = case k of\n 0 -> length $ filter (=='0') str\n _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)\n oneGroups = map length $ group sums\n sums = elems sumArray\n\n sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]\n allBounds = (0, snd $ bounds strArray)\n\n sumArrayF 0 = 0\n sumArrayF i = strArray ! i + sumArray ! (i - 1)\n\n strArray = listArray (1, length str) $ map ((\\x -> x - ord '0') . ord) str\n k = read sK :: Int\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as C\nimport IO\nimport Data.Maybe\n\nmain = print . solve =<< parse stdin\n-- main = print . solve $ (215001, C.replicate (1000000) '1')\n\nparse h = do\n input <- glines $ C.hGetContents h\n let k = readInt $ input !! 0\n s = input !! 1\n return (k, s)\n\nsolve (k, s)\n | k == 0 = sum $ map g z\n | k /= 0 = sum $ zipWith f z (drop k z)\n where\n z = map C.length . C.split '1' $ s\n f x y = (x + 1) * (y + 1)\n g x = x * (x + 1) `div` 2\n\n-- lib\n\nglines = fmap (map (C.takeWhile (/='\\r')) . C.lines)\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\n-- vim: set expandtab:\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nmain = print . solve =<< parse stdin\n\nparse h = do\n input <- glines $ C.hGetContents h\n let k = readInt $ input !! 0\n s = input !! 1\n return (k, s)\n\nsolve (k, s) = sum $ zipWith f z (drop k z)\n where\n z = map C.length . C.split '1' $ s\n f x y = (x + 1) * (y + 1)\n\n-- lib\n\nglines = fmap (map (C.takeWhile (/='\\r')) . C.lines)\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\n-- vim: set expandtab:\n"}, {"source_code": "import Control.Monad\nimport Data.List\nencode s = let (s1, s2) = span (== '0') s\n in if null s2 then [length s1]\n else length s1 : encode (tail s2)\nmain = do\n k <- (liftM read) getLine\n s <- getLine\n let l = encode s\n val = if k == 0 then sum $ map (\\x -> div (x * (x+1)) 2) l\n else sum $ zipWith (\\x y -> (x+1) * (y+1)) l (drop k l)\n putStrLn $ show val\n"}, {"source_code": "\n-- 2\n-- 01000110000111\n\n-- 0111123333333456\n-- 0 2 6 7 12 13 14 16\n\n\n-- 0 2 7 12 -> 2*5\n-- 2 6 12 13 -> 4*1\n-- 6 7 13 14 -> 1*1\n-- 7 12 14 16 -> 2*5\n\n-- 010001\n-- 10001\n-- 00011\n-- 000110\n-- 0001100\n-- 00011000\n-- 000110000\n-- 0011\n-- 00110\n-- 001100\n-- 0011000\n-- 00110000\n-- 011\n-- 0110\n-- 01100\n-- 011000\n-- 0110000\n-- 11\n-- 110\n-- 1100\n-- 11000\n-- 110000\n-- 100001\n-- 000011\n-- 00011\n-- 0011\n-- 011\n-- 11\n-- 11\n\n-- 29\n\nimport Data.List\n\nsublists :: [a] -> [[a]]\nsublists s = tails s >>= inits\n\nslowSolve n line = length $ filter ((== n) . length . filter (=='1')) $ sublists line\n\ntest n = take n (cycle \"0101010010100100101101001010101\")\n\nsolve :: Int -> String -> Int\nsolve n line = solve' ones (drop n ones) 0\n where\n ones = [0] ++ (map snd $ filter (('1' ==) . fst) (zip line [1..])) ++ [length line + 1]\n solve' :: [Int] -> [Int] -> Int -> Int\n solve' (l1:l2:ls) (r1:r2:rs) acc = acc' `seq` solve' (l2:ls) (r2:rs) acc'\n where\n acc' = acc + ((l2-l1)*(r2-r1))\n solve' _ _ acc = acc\n\n\nmain :: IO ()\nmain = do\n n <- readLn::IO Int\n line <- getLine\n print $ solve n line\n"}, {"source_code": "solve :: Int -> String -> Int\nsolve 0 _ = 0\nsolve n line = solve' ones (drop n ones) 0\n where\n ones = [0] ++ (map snd $ filter (('1' ==) . fst) (zip line [1..])) ++ [length line + 1]\n solve' :: [Int] -> [Int] -> Int -> Int\n solve' (l1:l2:ls) (r1:r2:rs) acc = acc' `seq` solve' (l2:ls) (r2:rs) acc'\n where\n acc' = acc + ((l2-l1)*(r2-r1))\n solve' _ _ acc = acc\n\n\nmain :: IO ()\nmain = do\n n <- readLn::IO Int\n line <- getLine\n print $ solve n line"}, {"source_code": "import Data.List\n\nmain = interact $ show.solve.(\\[x,y]->(read x,y)).lines\n\nsolve :: (Int,String) -> Int\nsolve (0,cs) = sum . map (h.length) . filter (('0'==).head) $ group cs\nsolve (k,cs) = let (xs1,xs2) = span ('0'==) cs\n in case f k ('1'==) xs2 of\n Just ((y:ys),zs) -> let ws = takeWhile ('0'==) zs\n in (1+length xs1)*(1+length ws) + solve (k,ys++zs)\n Nothing -> 0\n\nf :: Int -> (a -> Bool) -> [a] -> Maybe ([a],[a])\nf n p []\n | n==0 = Just ([],[])\n | otherwise = Nothing\nf n p (x:xs)\n | n==0 = Just ([],x:xs)\n | p x = f (n-1) p xs >>= g x\n | otherwise = f n p xs >>= g x\n\ng :: a -> ([a],[a]) -> Maybe ([a],[a])\ng x (xs,ys) = Just (x:xs,ys)\n\nh n = (n*(n+1))`div`2"}, {"source_code": "split x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nsolve k s\n\t| k == 0 = sum $ map (\\c -> c*(c-1) `div` 2) cs\n\t| otherwise = sum $ zipWith (*) (drop k cs) cs\n\twhere\n\t\tcs = map ((+ 1) . length) $ split '1' s\n\nmain = do\n\tk <- readLn\n\ts <- getLine\n\tprint $ solve k s\n"}], "src_uid": "adc43f273dd9b3f1c58b052a34732a50"} {"source_code": "import Data.List\n\nmain = interact $ solver\n\nsolver str = unwords $ map show res where\n _:ws = words str\n vals = map read ws\n res = solve (reverse $ sort $ vals) []\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [] res = res\nsolve (h:t) res = solve remaining (h : res) where\n to_remove = map (gcd h) res\n to_remove2 = reverse $ sort $ concatMap (replicate 2) to_remove\n remaining = exclude t to_remove2\n \nexclude [] _ = []\nexclude v [] = v\nexclude (h1:t1) v2@(h2:t2)\n | h1 == h2 = exclude t1 t2\n | h1 > h2 = h1 : exclude t1 v2\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n let\n ms = Map.fromListWith (+) $ zip xs $ repeat 1\n\n f 0 _ r = r\n f n s r = f (n-1) s' (m:r)\n where\n m = fst $ Map.findMax s\n s' = foldl remove s $ m:(xs ++ xs)\n where\n xs = map (gcd m) r\n\n remove s x\n | c == 1 = x `Map.delete` s\n | otherwise = Map.adjust (\\x -> x-1) x s\n where\n c = s Map.! x\n\n\n putStrLn $ unwords $ map show $ f n ms []\n"}, {"source_code": "import Data.List\nimport Data.Map.Strict ((!))\nimport qualified Data.Map.Strict as Map\n\nmain = do\n\t(_ : xs) <- fmap (map read . words) getContents\n\tlet m = Map.fromList $ fmap (\\us@(u : _) -> (u, length us)) . group . sort $ xs\n\tfoldl1 (>>) $ map (putStrLn . show) $ solve m []\n\nsolve m ans\n\t| Map.null m\t= ans\n\t| otherwise\t\t=\n\t\tlet\n\t\t\tx\t\t= fst $ Map.findMax m\n\t\t\tdelList\t= map (gcd x) ans\n\t\tin\n\t\t\tsolve (foldl myDelete m (x : (delList ++ delList))) (x : ans)\n\nmyDelete m k = if (m ! k) == 1 then Map.delete k m else Map.adjust (subtract 1) k m\n"}, {"source_code": "import Control.Monad\nimport Data.IntMap hiding (map)\nimport Prelude hiding (lookup,null)\n\nbuild m [] = m\nbuild m (x:xs) = if lookup x m == Nothing then build (insert x 1 m) xs else build (update (return . succ) x m) xs\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = build empty a\n mapM_ (\\x -> putStr ((show x) ++ \" \")) (solve m [])\n\nsolve m a\n |null m = a\n |otherwise = let x = getMax m\n m' = deduct m (x:(map (gcd x) a))\n in solve m' (x:a)\n\ngetMax m = let Just ((k,_),_) = maxViewWithKey m in k\n\ndeduct m [] = m\ndeduct m (x:xs) = let v = lookup x m\n nm = if v==Nothing then m else if v<=Just 2 then delete x m else adjust (\\l -> l-2) x m\n in deduct nm xs"}, {"source_code": "import Data.List\nimport Data.Map.Strict ((!))\nimport qualified Data.Map.Strict as Map\n\nmain = do\n\t(_ : xs) <- fmap (map read . words) getContents\n\tlet m = Map.fromList $ fmap (\\us@(u : _) -> (u, length us)) . group . sort $ xs\n\tfoldl1' (>>) $ map (putStrLn . show) $ solve m []\n\nsolve m ans\n\t| Map.null m\t= ans\n\t| otherwise\t\t=\n\t\tlet\n\t\t\tx\t\t= fst $ Map.findMax m\n\t\t\tdelList\t= map (gcd x) ans\n\t\tin\n\t\t\tsolve (foldl' myDelete m (x : (delList ++ delList))) (x : ans)\n\nmyDelete m k = if (m ! k) == 1 then Map.delete k m else Map.adjust (subtract 1) k m\n"}, {"source_code": "import Data.List\nimport Data.Map.Strict ((!))\nimport qualified Data.Map.Strict as Map\n\nmain = do\n\t(_ : xs) <- fmap (map read . words) getContents\n\tlet m = Map.fromList $ fmap (\\us@(u : _) -> (u, length us)) . group . sort $ xs\n\tfoldl1' (>>) $ map (putStrLn . show) $ solve m []\n\nsolve m ans\n\t| Map.null m\t= ans\n\t| otherwise\t\t=\n\t\tlet\n\t\t\tx\t\t= fst $ Map.findMax m\n\t\t\tdelList\t= map (gcd x) ans\n\t\tin\n\t\t\tsolve (foldl myDelete m (x : (delList ++ delList))) (x : ans)\n\nmyDelete m k = if (m ! k) == 1 then Map.delete k m else Map.adjust (subtract 1) k m\n"}, {"source_code": "import Data.List\n\nmain = interact $ solver\n\nsolver str = unwords $ map show res where\n _:ws = words str\n vals = map read ws\n res = solve (reverse $ sort $ vals) []\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [] res = res\nsolve (h:t) res = solve remaining (h : res) where\n to_remove = map (gcd h) res\n to_remove2 = reverse $ sort $ to_remove\n remaining = exclude t to_remove2\n \nexclude [] _ = []\nexclude v [] = v\nexclude (h1:t1) v2@(h2:t2)\n | h1 == h2 = exclude (tail t1) t2\n | h1 > h2 = h1 : exclude t1 v2\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.List as List\n\nreadInts str = map read (words str)\n\n\n\n\ng ys m = \n if Map.null m then ys \n else if k==0 then g ys (Map.delete y m) \n else g (y:ys) (Map.adjust (flip (-) 1) y m')\n where \n (y, k) = Map.findMax m\n gs = map (gcd y) ys\n m' = foldr (Map.adjust (flip (-) 2) ) m gs\n\n\n\nmain :: IO ()\nmain = do\n -- n <- fmap read getLine :: IO Int\n getLine\n xs <- fmap readInts getLine :: IO [Int]\n let xs' = List.group $ List.sort xs\n let m = Map.fromList $ map (\\lst-> (head lst, length lst)) xs'\n putStr $ unwords $ map show (g [] m)\n \n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>), (<*>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Map (Map, empty, alter, findMax, deleteMax, adjust)\nimport qualified Data.Map as M\n\nsolve :: [Int] -> [Int]\nsolve xs = loop [] (foldr (alter inc) empty xs :: Map Int Int)\n where\n inc Nothing = Just 1\n inc (Just i) = Just $ 1 + i\n go = adjust $ \\i -> i - 2\n\n loop acc cnt\n | M.null cnt = acc\n | otherwise = case findMax cnt of\n (_, 0) -> loop acc (deleteMax cnt)\n (k, _) -> loop (k:acc) . foldr go (adjust pred k cnt) $ map (gcd k) acc\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nmain :: IO ()\nmain = getLine >> getLine >>= putStrLn . unwords . map show . solve . parse\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.IntMap hiding (map)\nimport Prelude hiding (lookup,null)\n\nbuild m [] = m\nbuild m (x:xs) = if lookup x m == Nothing then build (insert x 1 m) xs else build (update (return . succ) x m) xs\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = build empty a\n print $ solve m []\n\nsolve m a\n |null m = a\n |otherwise = let x = getMax m\n m' = deduct m (x:(map (gcd x) a))\n in solve m' (x:a)\n\ngetMax m = let Just ((k,_),_) = maxViewWithKey m in k\n\ndeduct m [] = m\ndeduct m (x:xs) = let v = lookup x m\n nm = if v==Nothing then m else if v<=Just 2 then delete x m else adjust (\\l -> l-2) x m\n in deduct nm xs"}, {"source_code": "import qualified Data.Map as Map\nimport Data.List as List\n\nreadInts str = map read (words str)\n\n\n\n\ng ys m = \n if Map.null m then ys \n else if k==0 then g ys (Map.delete y m) \n else g (y:ys) (Map.deleteMax m')\n where \n (y, k) = Map.findMax m\n gs = map (gcd y) (y:ys)\n m' = foldr (Map.adjust (flip (-) 2) ) m gs\n\n\n\nmain :: IO ()\nmain = do\n -- n <- fmap read getLine :: IO Int\n getLine\n xs <- fmap readInts getLine :: IO [Int]\n let xs' = List.group $ List.sort xs\n let m = Map.fromList $ map (\\lst-> (head lst, length lst)) xs'\n putStr $ unwords $ map show (g [] m)\n \n \n \n"}], "src_uid": "71dc07f0ea8962f23457af1d6509aeee"} {"source_code": "import Data.List\r\n\r\nsolve :: [Int] -> String\r\nsolve [] = \"Yes\"\r\nsolve [x] = \"Yes\"\r\nsolve (a:xs@(b:_)) = if a==b then \"No\" else solve xs \r\n\r\ntestCase = do\r\n n <- getLine\r\n numList <- words `fmap` getLine\r\n let nums = read `map` numList :: [Int]\r\n putStrLn $ solve (sort nums)\r\n\r\nrepeatN 0 m = return []\r\n\r\nrepeatN n m = do\r\n x1 <- m\r\n x2 <- repeatN (n - 1) m\r\n return (x1 : x2)\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatN n testCase", "positive_code": [{"source_code": "import Control.Monad (forM_)\r\nimport Data.List (nub)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (map read . words) getLine\r\n\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_\r\n [1 .. n]\r\n ( \\_ -> do\r\n _ <- readLn :: IO Int\r\n arr <- readInts\r\n putStrLn $\r\n if (length . nub) arr == length arr\r\n then \"YES\"\r\n else \"NO\"\r\n )"}], "negative_code": [{"source_code": "import Data.List\r\n\r\nsolve :: [Int] -> String\r\nsolve [] = \"Yes\"\r\nsolve [x] = \"Yes\"\r\nsolve (a:b:xs) = if a==b then \"No\" else solve xs \r\n\r\ntestCase = do\r\n n <- getLine\r\n numList <- words `fmap` getLine\r\n let nums = read `map` numList :: [Int]\r\n putStrLn $ solve (sort nums)\r\n\r\nrepeatN 0 m = return []\r\n\r\nrepeatN n m = do\r\n x1 <- m\r\n x2 <- repeatN (n - 1) m\r\n return (x1 : x2)\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatN n testCase"}, {"source_code": "solve :: [Int] -> String\r\nsolve [] = \"Yes\"\r\nsolve [x] = \"Yes\"\r\nsolve (a:b:xs) = if a==b then \"No\" else solve xs \r\n\r\ntestCase = do\r\n n <- getLine\r\n numList <- words `fmap` getLine\r\n let nums = read `map` numList :: [Int]\r\n putStrLn $ solve nums\r\n\r\nrepeatN 0 m = return []\r\n\r\nrepeatN n m = do\r\n x1 <- m\r\n x2 <- repeatN (n - 1) m\r\n return (x1 : x2)\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatN n testCase\r\n "}], "src_uid": "288f147bb8a3c30b0bb712a01c65109b"} {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n\nmain = do\n\tn <- fmap read getLine\n\ta <- replicateM n getLine\n\tb <- getLine\n\tputStrLn $ gao n a b\n\ngao n a b = unlines $ sort $ concat $ d : e where\n\tm = sum (map length a) * 2 `div` n\n\tc = fmap sort $ accumArray (flip (:)) [] (1, m) $ map (\\i -> (length i, i)) a\n\td = if odd m then [] else f $ c!(div m 2)\n\te = [zipWith (\\i j -> min (i ++ b ++ j) (j ++ b ++ i)) (c!i) (c!(m - i))| i <- [1 .. div (m - 1) 2]]\n\tf [] = []\n\tf (x:y:z) = (x ++ b ++ y) : f z\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort, unfoldr)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n branches <- replicateM n getLine\n d <- getLine\n let lengths = map length branches\n let size = (2 * sum lengths) `div` n\n let branches' = map init . sort . map ( ++ d) $ branches\n mapM_ putStrLn $ solve size d branches'\n\n\nsolve :: Int -> String -> [String] -> [String]\nsolve sz d branches = unfoldr cN branches\n where cN :: [String] -> Maybe (String, [String])\n cN ([]) = Nothing\n cN bs = Just (start ++ d ++ smC, leOv)\n where start = head bs\n fSz = sz - length start\n (p1, smC:p2) = break ((== fSz).length) (tail bs)\n leOv = p1 ++ p2\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n branches <- replicateM n getLine\n d <- getLine\n let lengths = map length branches\n let size = (2 * sum lengths) `div` n\n let branches' = (map init) . sort . (map ( ++ d)) $ branches\n mapM_ putStrLn $ solve size d branches'\n\n\nsolve :: Int -> String -> [String] -> [String]\nsolve _ _ ([]) = []\nsolve sz d branches = (start ++ d ++ smC):(solve sz d leOv)\n where start = head branches\n fSz = sz - length start\n (p1, (smC:p2)) = break ((== fSz).length) (tail branches)\n leOv = p1 ++ p2\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Ord\nimport Data.Monoid\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.List\n\nstrCmp sep (a:as) (b:bs) = case compare a b of\n EQ -> strCmp sep as bs\n res -> res\nstrCmp sep [] (b:_) = compare sep b\nstrCmp sep (a:_) [] = compare a sep\nstrCmp sep _ _ = EQ\n\nnewtype Prefix = Prefix (Char, [Char]) deriving Eq\ninstance Ord Prefix where\n compare (Prefix (sep, a)) (Prefix (_, b)) = strCmp sep a b\n\nmain = do\n n <- read `liftM` getLine\n names <- replicateM n getLine\n sep <- head `liftM` getLine\n\n let prefixSet = Set.fromList $ map (\\s -> Prefix (sep, s)) names\n postfixMap = Map.fromList $ map (\\s -> (length (Set.findMin s), s)) $\n map Set.fromList $\n groupBy (\\a b -> length a == length b) $\n sortBy (comparing length) names\n totalLen = sum $ map length names\n rowLen = totalLen `div` (n `div` 2) + 1\n (res, _, _) = until\n (\\(_, set, _) -> Set.null set)\n (\\(res, prefixSet, postfixMap) ->\n let (Prefix (_, prefix), prefixSet') = Set.deleteFindMin prefixSet\n prefixLen = length prefix\n postfixLen = rowLen - 1 - prefixLen\n\n postfixMap' = Map.insertWith' ( \\_ entry -> Set.delete prefix entry ) prefixLen undefined postfixMap\n (postfix, postfixSet'') = Set.deleteFindMin $ postfixMap' Map.! postfixLen\n postfixMap'' = Map.insert postfixLen postfixSet'' postfixMap'\n\n prefixSet'' = Set.delete (Prefix (sep, postfix)) prefixSet'\n in ( ( prefix ++ [sep] ++ postfix ) : res, prefixSet'', postfixMap'' )\n )\n ([], prefixSet, postfixMap)\n\n --putStrLn $ show postfixMap\n putStr $ unlines $ reverse res\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n\nmain = do\n n <- fmap read getLine\n a <- replicateM n getLine\n b <- getLine\n putStr $ gao n a b\n\ngao :: Int -> [String] -> String -> String\ngao n a b =\n unlines $ sort $ concat $ d : e\n where\n m = sum (map length a) * 2 `div` n\n c = fmap sort $ accumArray (flip (:)) [] (1, m) [(length i, i) | i <- a]\n --should use fmap\n --in this case fmap is for functor (Array Int)\n --not map\n --map is for [] functor, for [] functor fmap = map\n d = if odd m then [] else f $ c!(div m 2)\n e = [zipWith (\\x y -> min (x ++ b ++ y) (y ++ b ++ x)) (c!i) (c!(m - i)) | i <- [1..div (m - 1) 2]]\n f [] = []\n f (x:y:z) = (x ++ b ++ y) : f z\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n \nmain = do\n\tn <- fmap read getLine\n\tc <- replicateM n getLine\n\td <- getLine\n\tputStrLn $ gao n c d\n \ngao n a b = unlines $ sort $ concat $ d : e where\n\tm = sum (map length a) * 2 `div` n\n\tc = fmap sort $ accumArray (flip (:)) [] (1, m) $ map (\\i -> (length i, i)) a\n\td = if odd m then [] else f $ c!(div m 2)\n\te = [zipWith (\\i j -> min (i ++ b ++ j) (j ++ b ++ i)) (c!i) (c!(m - i))| i <- [1 .. div (m - 1) 2]]\n\tf [] = []\n\tf (x:y:z) = (x ++ b ++ y) : f z"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nlinesBuild _ [] = []\nlinesBuild c@(delimiter, minLength, maxLength) cs@(csh:cst) = \n\tlet {(cs1, cs2h:cs2t) = splitAt (fromJust $ \n\t\tfindIndex (\\x -> length x == minLength + maxLength - length csh)\n\t\t\tcst) cst} in\n\t(csh ++ [delimiter] ++ cs2h): linesBuild c (cs1 ++ cs2t)\n\t\n\nmain = do { ns <- getLine\n\t; let n = read ns\n\t; cities <- mapM (\\_ -> getLine) [1..n]\n\t; delimiter <- getLine >>= (return . head)\n\t; let (minLength, maxLength) = let (l:lens) = sort $ map length cities in \n\t\t(l, head $ reverse lens)\n\t; mapM_ (\\x -> putStr (x ++ \"\\n\"))\n\t\t$ linesBuild (delimiter, minLength, maxLength) (sortBy \n\t\t(\\a b -> compare (a++[delimiter]) (b++[delimiter])) cities)\n}\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n\nmain = do\n\tn <- fmap read getLine\n\ta <- replicateM n getLine\n\tb <- getLine\n\tputStrLn $ gao n a b\n\ngao n a b = unlines $ sort $ concat $ d : e where\n\tm = sum (map length a) * 2 `div` n\n\tc = accumArray (flip (:)) [] (1, m) $ map (\\i -> (length i, i)) a\n\td = if odd m then [] else f $ c!(div m 2)\n\te = [zipWith (\\i j -> min (i ++ b ++ j) (j ++ b ++ i)) (c!i) (c!(m - i))| i <- [1 .. div (m - 1) 2]]\n\tf [] = []\n\tf (x:y:z) = (x ++ b ++ y) : f z\n"}, {"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.Monoid\nimport qualified Data.Set as Set\n\nstrCmp sep (a:as) (b:bs) = case compare a b of\n EQ -> strCmp sep as bs\n res -> res\nstrCmp sep [] (b:_) = compare sep b\nstrCmp sep (a:_) [] = compare a sep\nstrCmp sep _ _ = EQ\n\nnewtype Prefix = Prefix (Char, [Char]) deriving Eq\ninstance Ord Prefix where\n compare (Prefix (sep, a)) (Prefix (_, b)) = strCmp sep a b\n\nmain = do\n n <- read `liftM` getLine\n names <- replicateM n getLine\n sep <- head `liftM` getLine\n\n let prefixSet = Set.fromList $ map (\\s -> Prefix (sep, s)) names\n postfixSet = Set.fromList names\n (res, _, _) = until\n (\\(_, set, _) -> Set.null set)\n (\\(res, prefixSet, postfixSet) ->\n let (Prefix (_, prefix), prefixSet') = Set.deleteFindMin prefixSet\n (postfix, postfixSet') = Set.deleteFindMin $ Set.delete prefix postfixSet\n prefixSet'' = Set.delete (Prefix (sep, postfix)) prefixSet'\n in ( ( prefix ++ [sep] ++ postfix ) : res, prefixSet'', postfixSet' )\n )\n ([], prefixSet, postfixSet)\n\n putStr $ unlines $ reverse res\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nlinesBuild _ [] = []\nlinesBuild c@(delimiter, minLength, maxLength) cs@(csh:cst) = \n\tlet {(cs1, cs2h:cs2t) = splitAt (fromJust $ \n\t\tfindIndex (\\x -> length x == minLength + maxLength - length csh)\n\t\t\tcst) cst} in\n\t(csh ++ [delimiter] ++ cs2h): linesBuild c (cs1 ++ cs2t)\n\t\n\nmain = do { ns <- getLine\n\t; let n = read ns\n\t; cities <- mapM (\\_ -> getLine) [1..n]\n\t; delimiter <- getLine >>= (return . head)\n\t; let (minLength, maxLength) = let (l:lens) = sort $ map length cities in \n\t\t(l, head $ reverse lens)\n\t; mapM_ (\\x -> putStr (x ++ \"\\n\"))\n\t\t$ linesBuild (delimiter, minLength, maxLength) (sort cities)\n}\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n branches <- sort <$> replicateM n getLine :: IO [String]\n d <- getLine\n let lengths = map length branches\n let size = (2 * sum lengths) `div` n\n mapM_ putStrLn $ solve size d branches\n\n\nsolve :: Int -> String -> [String] -> [String]\nsolve _ _ ([]) = []\nsolve sz d branches = (start ++ d ++ smC):(solve sz d leOv)\n where start = head branches\n fSz = sz - length start\n (p1, (smC:p2)) = break ((== fSz).length) (tail branches)\n leOv = p1 ++ p2\n"}], "src_uid": "0f04f757dc734208d803ee0f6be5d1f0"} {"source_code": "\n{-\nimport HUnit\n\ntestNotVectors :: Test\ntestNotVectors = Test \"TestNotVectors\" $\n assertEq 0 (solve (0,0) (0,0) [])\n\ntestOneVector :: Test\ntestOneVector = TestList \"TestOneVector\"\n [Test \"1\" $ assertEq 5 (solve (6,16) (1,1) [(1,1)]),\n Test \"2\" $ assertEq 2 (solve (6,16) (1,1) [(2,2)]),\n Test \"3\" $ assertEq 0 (solve (4,1) (1,1) [(1,1)])]\n\ntestOneVectorWithZeroCoordinate :: Test\ntestOneVectorWithZeroCoordinate = TestList \"TestOneVectorWithZeroCoordinate\"\n [Test \"1\" $ assertEq 3 (solve (4,1) (1,1) [(1,0)]),\n Test \"2\" $ assertEq 2 (solve (4,4) (2,2) [(0,1)])]\n\ntestOneVectorWithNegativeCoordinate :: Test\ntestOneVectorWithNegativeCoordinate = TestList \"TestOneVectorWithNegativeCoordinate\"\n [Test \"1\" $ assertEq 1 (solve (6,6) (2,2) [(-1,-1)]),\n Test \"2\" $ assertEq 2 (solve (6,6) (5,3) [(-1,-1)]),\n Test \"3\" $ assertEq 1 (solve (6,6) (5,3) [(-1,-2)])]\n\ntestManyVectors :: Test\ntestManyVectors = Test \"TestManyVectors\" $\n assertEq 7 (solve (3,4) (1,1) [(2,0),(0,1),(-1,0),(0,-3),(-1,0),(0,-1),(-1,-1),(3,0),(0,4)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq 4 (solve (4,5) (1,1) [(1,1),(1,1),(0,-2)]),\n Test \"2\" $ assertEq 0 (solve (10,10) (1,2) [(-1,0)])]\n\ntestBig :: Test\ntestBig = Test \"TestBig\" $\n assertEq (10^9 * 1000) (solve (10^9 + 1, 10^9 + 1) (1,1) (take 1000 (cycle [(1,1), (-1,-1)])))\n\ntest :: IO ()\ntest = mapM_ run\n [testNotVectors,\n testOneVector,\n testOneVectorWithZeroCoordinate,\n testOneVectorWithNegativeCoordinate,\n testManyVectors,\n testInput,\n testBig]\n\n--------------------------------------------------------------------------------\n-}\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nreadVector :: IO (Integer, Integer)\nreadVector = do\n [x, y] <- Main.reads\n return (x, y)\n\nsolve :: (Integer, Integer) -> (Integer, Integer) -> [(Integer, Integer)] -> Integer\nsolve (n,m) (x,y) vs = snd (foldl solve' ((x,y), 0) vs)\n where\n solve' :: ((Integer, Integer), Integer) -> (Integer, Integer) -> ((Integer, Integer), Integer)\n solve' ((xc,yc), s) (x,y) = ((xc + x * res, yc + y * res), s + res)\n where\n x' = if x < 0 then div (xc-1) (-x) else div (n-xc) x\n y' = if y < 0 then div (yc-1) (-y) else div (m-yc) y\n res = case (x,y) of\n (0, 0) -> error \"Solve: Empty vector!\"\n (0, y) -> y'\n (x, 0) -> x'\n (x, y) -> min x' y'\n\nmain :: IO ()\nmain = do\n [n, m] <- Main.reads\n [xc, yc] <- Main.reads\n k <- readLn\n vs <- mapM (const readVector) [1..k]\n print $ solve (n,m) (xc,yc) vs\n", "positive_code": [{"source_code": "\n{-\nimport HUnit\n\ntestNotVectors :: Test\ntestNotVectors = Test \"TestNotVectors\" $\n assertEq 0 (solve (0,0) (0,0) [])\n\ntestOneVector :: Test\ntestOneVector = TestList \"TestOneVector\"\n [Test \"1\" $ assertEq 5 (solve (6,16) (1,1) [(1,1)]),\n Test \"2\" $ assertEq 2 (solve (6,16) (1,1) [(2,2)]),\n Test \"3\" $ assertEq 0 (solve (4,1) (1,1) [(1,1)])]\n\ntestOneVectorWithZeroCoordinate :: Test\ntestOneVectorWithZeroCoordinate = TestList \"TestOneVectorWithZeroCoordinate\"\n [Test \"1\" $ assertEq 3 (solve (4,1) (1,1) [(1,0)]),\n Test \"2\" $ assertEq 2 (solve (4,4) (2,2) [(0,1)])]\n\ntestOneVectorWithNegativeCoordinate :: Test\ntestOneVectorWithNegativeCoordinate = TestList \"TestOneVectorWithNegativeCoordinate\"\n [Test \"1\" $ assertEq 1 (solve (6,6) (2,2) [(-1,-1)]),\n Test \"2\" $ assertEq 2 (solve (6,6) (5,3) [(-1,-1)]),\n Test \"3\" $ assertEq 1 (solve (6,6) (5,3) [(-1,-2)])]\n\ntestManyVectors :: Test\ntestManyVectors = Test \"TestManyVectors\" $\n assertEq 7 (solve (3,4) (1,1) [(2,0),(0,1),(-1,0),(0,-3),(-1,0),(0,-1),(-1,-1),(3,0),(0,4)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq 4 (solve (4,5) (1,1) [(1,1),(1,1),(0,-2)]),\n Test \"2\" $ assertEq 0 (solve (10,10) (1,2) [(-1,0)])]\n\ntestBig :: Test\ntestBig = Test \"TestBig\" $\n assertEq (10^9 * 1000) (solve (10^9 + 1, 10^9 + 1) (1,1) (take 1000 (cycle [(1,1), (-1,-1)])))\n\ntest :: IO ()\ntest = mapM_ run\n [testNotVectors,\n testOneVector,\n testOneVectorWithZeroCoordinate,\n testOneVectorWithNegativeCoordinate,\n testManyVectors,\n testInput,\n testBig]\n\n--------------------------------------------------------------------------------\n-}\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nreadVector :: IO (Integer, Integer)\nreadVector = do\n [x, y] <- Main.reads\n return (x, y)\n\nsolve :: (Integer, Integer) -> (Integer, Integer) -> [(Integer, Integer)] -> Integer\nsolve (n,m) (x,y) vs = snd (foldl solve' ((x,y), 0) vs)\n where\n solve' :: ((Integer, Integer), Integer) -> (Integer, Integer) -> ((Integer, Integer), Integer)\n solve' ((xc,yc), s) (x,y) = ((xc + x * res, yc + y * res), s + res)\n where\n x' = if x < 0 then div (xc-1) (-x) else div (n-xc) x\n y' = if y < 0 then div (yc-1) (-y) else div (m-yc) y\n res = case (x,y) of\n (0, 0) -> error \"Solve: Empty vector!\"\n (0, y) -> y'\n (x, 0) -> x'\n (x, y) -> min x' y'\n\nmain :: IO ()\nmain = do\n [n, m] <- Main.reads\n [xc, yc] <- Main.reads\n k <- readLn\n vs <- mapM (const readVector) [1..k]\n print $ solve (n,m) (xc,yc) vs"}, {"source_code": "import Data.List\n\nsolve ([n, m]:position:_:vectors) = head $ foldl' applyVector (0:position) vectors\n where applyVector [ans, x, y] [dx, dy] =\n let a = steps x n dx\n b = steps y m dy\n c = min a b\n in [ans + c, x + c * dx, y + c * dy]\n\n steps a q da\n | da > 0 = (q - a) `div` da\n | da < 0 = (a - 1) `div` (abs da)\n | otherwise = 10 ^ 9 + 1\n\nmain = interact $ show . solve . map (map read . words) . lines"}, {"source_code": "import Control.Arrow\nimport Control.Monad\nmain = do\n [n,m] <- liftM (map read . words) getLine\n [xc,yc] <- liftM (map read . words) getLine\n k <- readLn\n vs <- replicateM k $ liftM (((!!0) &&& (!!1)) . map read . words) getLine\n print $ solve n m xc yc vs 0\nsolve _ _ _ _ [] a = a\nsolve n m x y ((vx,vy):vs) a = solve n m (x + c*vx) (y + c*vy) vs $! a + c\n where nx = if vx > 0 then (n - x) `div` vx else (1 - x) `div` vx\n ny = if vy > 0 then (m - y) `div` vy else (1 - y) `div` vy\n c = if vx == 0 then ny else if vy == 0 then nx else min nx ny\n"}, {"source_code": "import Data.ByteString.Char8(ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nmain = do\n [n,m] <- map read' . B.words <$> B.getLine\n [xc,yc] <- map read' . B.words <$> B.getLine\n _ <- getLine\n xys <- map ((\\ [x,y] -> (x,y)) . map read' . B.words) . B.lines <$> B.getContents\n print $ solve [n,m] $ (xc,yc):xys\n\nread' s = let Just (n,_) = B.readInt s in toInteger n\n\nsolve :: [Integer] -> [(Integer,Integer)] -> Integer\nsolve [n,m] (xy:xys) = fst $ foldl' (f [n,m]) (0,xy) xys\n\nf [n,m] (i,(x,y)) (dx,dy)\n | dx == 0 = let k = if dy>0 then div (m-y) dy else div (1-y) dy\n in (i+k,(x,y+k*dy))\n | dy == 0 = let k = if dx>0 then div (n-x) dx else div (1-x) dx\n in (i+k,(x+k*dx,y))\n | otherwise = let kx = if dx>0 then div (n-x) dx else div (1-x) dx\n ky = if dy>0 then div (m-y) dy else div (1-y) dy\n k = min kx ky\n in (i+k,(x+k*dx,y+k*dy))\n"}, {"source_code": "import Data.List\n\nbounds :: Integer->Integer->Integer->Integer\nbounds n c dc\n\t| dc == 0 = 1000000001\n\t| dc < 0 = (1-c)`div`dc\n\t| otherwise = (n-c)`div`dc\n\ntravel n m = go where\n\tgo _ _ [] = 0\n\tgo x y ([dx,dy]:t) = steps + go (x+steps*dx) (y+steps*dy) t\n\t\twhere steps = min (bounds n x dx) (bounds m y dy)\n\t\nresult ([n,m]:[x,y]:_:v) = travel n m x y v\n\nmain=interact$show.result.map (map read.words).lines\n"}, {"source_code": "import Control.Monad\n\ntype Point = (Int, Int)\n\nl2t :: [a] -> (a, a)\nl2t [x, y] = (x, y)\n\nsolve :: [Point] -> Point -> Point -> Integer\nsolve points start (n, m) = loop points start 0 \n where loop :: [Point] -> Point -> Integer -> Integer\n loop [] _ acc = acc\n loop ((vx, vy):vs) (x, y) acc = \n loop vs (x + st * vx, y + st * vy) (acc + (toInteger st))\n where st = min (step x vx n) (step y vy m)\n step a va k \n | va == 0 = 10^10 -- aka infty\n | va > 0 = (k - a) `div` va\n | va < 0 = (1 - a)`div` va\n\nmain = do\n (n, m) <- (getLine >>= return . l2t . map (read::String->Int) . words)\n (x, y) <- (getLine >>= return . l2t . map (read::String->Int) . words)\n [k] <- (getLine >>= return . map (read::String->Int) . words)\n points <- forM [1..k] (\\_ -> getLine >>= (return . l2t . map (read::String->Int). words))\n print $ solve points (x, y) (n, m)"}], "negative_code": [], "src_uid": "2737d7aa245627b1f7992b1148ed49ce"} {"source_code": "main = interact (ans)\nans theInput = output $ answer $ intersect schedule where\n\tinputs = map (map (read::String->Int))(map words $ lines theInput)\n\t[n] = head inputs\n\tschedule = zip [1..n] [(l,r)|[l,r]<-take n $ tail inputs]\n\tintersect [_] = []\n\tintersect ((i,(a,b)):xs) = [(i,j)|(j,(c,d))<-xs,(a<=c && c getLine :: IO [[Int]]\n let groups = sortBy (comparing snd) $ zip [1.. ] temp\n answers = sort . map fst . (`mapMaybe` groups) $ \\g -> do\n let groups' = filter (/= g) groups\n check (_, _ : end : _) (_, start : _) = end <= start\n if and $ zipWith check groups' (tail groups')\n then Just g\n else Nothing\n print $ length answers\n putStrLn . intercalate \" \" $ map show answers\n"}, {"source_code": "import Data.List(find,sort)\nmain = do \n (_:input) <- fmap lines getContents\n let a :: [(Int,(Int,Int))]\n a = zip [1..] $ map parse input\n parse s = (l,r) \n where [l,r] = map read . words $ s\n n = length a\n ans = case find intersecting [(g,h) | g <- a, h <- a, fst g < fst h] of\n Nothing -> [1..n]\n Just ((i,(lx,rx)),(j,(ly,ry))) -> sort . filter good $ [i,j]\n \n intersecting ((_,(lx,rx)),(_,(ly,ry))) =\n rx > ly && lx < ry\n \n good idx = Nothing == find intersecting [(g,h) | g <- a, h <- a, fst g < fst h, fst g /= idx, fst h /= idx]\n \n print (length ans)\n putStrLn . unwords . map show $ ans\n"}, {"source_code": "\n\n\nimport Control.Monad (liftM, replicateM)\nimport Data.Array ((!), listArray, accumArray, elems)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints xs = print (length xs) >> prints' xs\n where\n prints' = putStrLn . intercalate \" \" . map show\n\nsolve :: Int -> [[Int]] -> [Int]\nsolve n groups = [i | i <- [1..n], countEdges == countEdge ! i]\n where\n groupsArray = listArray (1, n) groups\n countEdge = accumArray (+) 0 (1, n)\n [(i, length (edges i)) | i <- [1..n]]\n countEdges = div (sum (elems countEdge)) 2\n edges i = filter (intersect i) [1..n]\n intersect i j\n | i == j = False\n | otherwise\n = l2 <= l1 && l1 < r2\n || l2 < r1 && r1 <= r2\n || l1 <= l2 && l2 < r1\n || l1 < r2 && r2 <= r1\n where\n [l1, r1] = groupsArray ! i\n [l2, r2] = groupsArray ! j\n\nmain :: IO ()\nmain = do\n n <- readLn\n groups <- replicateM n reads :: IO [[Int]]\n prints $ solve n groups"}], "negative_code": [{"source_code": "\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nsolve :: [Int] -> [(Int, Int, Int)]\nsolve xs = [(i, j, k) | i <- [1..n], j <- [1..n], k <- [1..n],\n i /= j, i /= k, j /= k,\n xs !! (i-1) == xs !! (j-1) + xs !! (k-1)]\n where\n n = length xs\n\nprintAns :: [(Int, Int, Int)] -> IO ()\nprintAns [] = print (-1)\nprintAns ((i, j, k):xs) = putStrLn $ concat [show i, \" \", show j, \" \", show k]\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= printAns . solve\n"}], "src_uid": "df28bb63a627a41d67f02cbd927d5e9a"} {"source_code": "\n\nfindN::Int->Int\nfindN n | n<4 = 4 - n\nfindN n | (mod n 2) == 0 = 0\nfindN n = 1\n\n\ninputN::Int->IO [Int]\ninputN 0 = return []\ninputN n = do\n z <- read <$> getLine\n (z:) <$> (inputN (n-1))\n\nmain::IO()\nmain = do\n n <- read <$> getLine\n lst <- inputN n\n mapM_ (print . findN) lst\n", "positive_code": [{"source_code": "f 2 = 2\nf a = a `mod` 2\n\nmain = do\n x <- getLine\n y <- getContents\n mapM_ (putStrLn.show.f.read) $ lines y "}, {"source_code": "f x \n | x == 2 = 2\n | otherwise = if odd x then 1 else 0 \n \nmain = interact $ unlines . map ( show . f . (read :: String -> Int) ) . tail . lines "}, {"source_code": "main :: IO ()\nmain = interact (unlines . map (show . solve . read) . tail . lines)\n\nsolve :: Int -> Int\nsolve n = max (4 - n) (n `mod` 2)\n"}, {"source_code": "import Control.Monad\n\nmain = do\n q <- read <$> getLine\n forM [1..q] $ \\_ -> do\n n <- read <$> getLine\n print $ missing n\n\nmissing :: Int -> Int\nmissing 2 = 2\nmissing n\n | n `mod` 2 == 0 = 0\n | otherwise = 1\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess aa = print $ if aa==2 then 2 else if even aa then 0 else 1\n\nmain::IO ()\nmain=do\n\ts<- read <$> getLine:: IO Int\n\ta<- map read <$> replicateM s getLine ::IO [Int]\n\tmapM_ process a\n"}, {"source_code": "--ghc 7.10\n\nminMatches :: Int -> Int\nminMatches n\n | n < 4 = 4 - n\n | otherwise = n `mod` 2\n\nassembleCME :: [Int] -> [Int]\nassembleCME = map minMatches\n\nmain = do\n qStr <- getLine\n contents <- getContents\n let ns = map read . words $ contents :: [Int]\n sequence . map print . assembleCME $ ns"}, {"source_code": "main = interact $ unlines . map (show . solve . read) . tail . lines\nsolve n | n < 4 = 4 - n\n | odd n = 1\n | even n = 0\n"}], "negative_code": [], "src_uid": "178876bfe161ba9ccfd80c9310f75cbc"} {"source_code": "import Control.Monad\n\nsolve :: Int-> Int -> Int -> Bool\nsolve r b k = (n+1) Integer -> Integer -> String\nf a b k\n | r == 0 = if k < d then \"REBEL\" else \"OBEY\"\n | otherwise = if k <= div (b - 2) a + 1 then \"REBEL\" else \"OBEY\"\n where r = mod b a\n d = div b a\n l = lcm a b\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [r, b, k] <- getIntList\n let x = div r (gcd r b)\n y = div b (gcd r b) in\n putStrLn $ f (min x y) (max x y) k"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n\ngetIntList :: IO [Integer]\ngetIntList = fmap (map read) getStrList\n\nf :: Integer -> Integer -> Integer -> String\nf r b k\n | k <= div b r = \"REBEL\"\n | otherwise = \"OBEY\"\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [r, b, k] <- getIntList\n putStrLn $ f (min r b) (max r b) k"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n\ngetIntList :: IO [Integer]\ngetIntList = fmap (map read) getStrList\n\nupd :: Integer -> Integer -> Integer\nupd u d\n | mod u d == 0 = div u d\n | otherwise = div u d + 1\n\nf :: Integer -> Integer -> Integer -> String\nf r b k\n | k < upd b r = \"REBEL\"\n | otherwise = \"OBEY\"\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [r, b, k] <- getIntList\n putStrLn $ f (min r b) (max r b) k"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n\ngetIntList :: IO [Integer]\ngetIntList = fmap (map read) getStrList\n\nf :: Integer -> Integer -> Integer -> String\nf a b k\n | r == 0 = if k < d then \"REBEL\" else \"OBEY\"\n | otherwise = if k <= div (b - 2) a + 1 then \"REBEL\" else \"OBEY\"\n where r = mod b a\n d = div b a\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [r, b, k] <- getIntList\n putStrLn $ f (min r b) (max r b) k"}, {"source_code": "import Control.Monad\n\nsolve :: Int-> Int -> Int -> Bool\nsolve r b k = n Int -> Int -> Bool\nsolve r b k = n>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> [Int] -> Int\nsolve n as = L.sum $ L.map (\\x -> x - minA) as\n where\n minA = L.minimum as\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n", "positive_code": [{"source_code": "import Control.Monad\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n n <- read <$> getLine :: IO Int\n list <- fmap (fmap read)\n . fmap words\n\t $ getLine\n print $ solve list\nsolve l = sum . map (\\x -> x - k) $ l\n where\n k = minimum l\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep [] = []\nsep (_:x:xs) = x:(sep xs)\n\nparse :: String -> [Int]\nparse = (map read) . words\n\nformat = show\n\nsolve xs = sum $ map ((+) (-m)) xs\n where m = minimum xs\n"}, {"source_code": "import Data.List\r\nimport Data.Char\r\n\r\nmain :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\t\r\n\t\t\r\n\t\r\nsolve :: Int -> Int -> IO ()\r\nsolve number 0 = return ()\t\r\nsolve number current = \tdo\r\n\t\t\t\tuseles <- getLine\r\n\t\t\t\tl <- getLine\r\n\t\t\t\tlet bruh = ((map read) . words ) l :: [Int]\r\n\t\t\t\tlet min = minimum bruh\r\n\t\t\t\tlet ans = foldr (\\s -> \\acc -> acc + s - min) 0 bruh\r\n\t\t\t\tputStrLn $ show $ ans\r\n\t\t\t\tsolve number (current - 1)\r\n\t\t\t\t"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsol :: [Int] -> Int\r\nsol xs = foldl' (\\acc x -> acc + x - m) 0 xs\r\n where\r\n m = minimum xs\r\n\r\nreadCase :: IO [Int]\r\nreadCase = do\r\n n <- read <$> getLine :: IO Int\r\n map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine :: IO Int\r\n cases <- replicateM t readCase\r\n putStrLn $ intercalate \"\\n\" (map (show . sol) cases)"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nsolve :: [Int] -> Int\r\nsolve arr = sum $ map (\\x -> x - m) arr\r\n where\r\n m = minimum arr\r\n\r\nsecond (x : y : xs) = y : second xs\r\nsecond _ = []\r\n\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> second\r\n >>> map (show . solve . map (read :: String -> Int) . words)\r\n >>> unlines\r\n"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\n\nmain :: IO ()\nmain = read <$> getLine >>= flip replicateM_ singleCase\n\nsingleCase :: IO ()\nsingleCase = read <$> getLine >>= \\n -> map read . words <$> getLine >>=\n \\xs -> let m = minL xs\n s = sum xs\n in print (s - n*m)\n\nminL :: [Int] -> Int\nminL (x:xs) = foldl min x xs\n"}, {"source_code": "minn :: [Int] -> Int\r\nminn (x: []) = x\r\nminn (x: xs) = min x (minn xs)\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n readLn :: IO Int\r\n arr <- (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n let mn = minn arr\r\n print $ sum $ map (\\a -> a - mn) arr\r\n for $ i - 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n for t"}], "negative_code": [], "src_uid": "20dd260775ea71b1fb5b42bcac90a6f2"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n output cs@(_ : _ : _ : []) = printf \"%s\\n\" cs\n output cs@(_ : _ : []) = printf \"%s\\n\" cs\n output cs = printf \"%s-\" (take 2 cs) >> output (drop 2 cs)\n n : _ <- readData\n cs <- take n <$> getLine\n output cs\n\n\n\n", "positive_code": [{"source_code": "solve \"\" = \"\"\nsolve x\n\t| length x <= 3 = x\n\t| otherwise = (take 2 x) ++ \"-\" ++ (solve $ drop 2 x)\n\nmain = do\n\t_ <- getLine\n\ts <- getLine\n\tputStrLn $ solve s\n"}, {"source_code": "main :: IO ()\nmain = interact func\n\nfunc :: String -> String\nfunc s = func'.head.tail$lines s\n \nfunc' :: String -> String\nfunc' [] = \"\"\nfunc' (_:[]) = error \"\"\nfunc' xs@(_:_:[]) = xs\nfunc' xs@(_:_:_:[]) = xs\nfunc' (a:b:c:d:[]) = a:b:'-':c:d:[]\nfunc' (a:b:c:xs) = a:b:c:'-':(func' xs)"}, {"source_code": "solve :: String -> [String]\nsolve [] = []\nsolve (a:b:c:[]) = [[a,b,c]]\nsolve (c:[]) = undefined\nsolve (a:b:cs) = [a,b] : solve cs\n\nprintAns :: [String] -> IO ()\nprintAns [] = undefined\nprintAns [s] = putStrLn s\nprintAns (x:xs) = putStr x >> putStr \"-\" >> printAns xs\n\nmain :: IO ()\nmain = getLine >> getLine >>= printAns . solve"}, {"source_code": "import Data.List\nsplit s = map (map snd) . groupBy (\\(a,_) (b,_) -> div a 3 == div b 3) . zip [0..] $ s\nsolve s = intercalate \"-\" . reverse . adjust . reverse . split $ s\n where adjust ([x]:[a,b,c]:xs) = [a,b,'-',c,x]:xs\n adjust xs = xs\n\nmain = getLine >> getLine >>= putStrLn . solve \n"}, {"source_code": "main = getLine >> getLine >>= putStrLn . solve\nsolve :: String -> String\nsolve n@[a,b,c] = n\nsolve n@[a,b] = n\nsolve (a:b:xs) = a : b : '-' : solve xs\n"}], "negative_code": [], "src_uid": "6f6859aabc1c9cbb9ee0d910064d87c2"} {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Char\nimport Data.Array.Unboxed\n\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport qualified Control.Monad.ST.Lazy as L\n--import Data.STRef\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ncharOpts :: [Char]\ncharOpts = '_' : ['a' .. 'z']\n\nleast :: Int\nleast = minimum (ord <$> charOpts)\n\nradix :: Int\nradix = maximum (ord <$> charOpts) - least + 1\n\nmaxk :: Int\nmaxk = 4\n\nmaxhash :: Int\nmaxhash = radix ^ maxk\n\n{-\nhash :: String -> Int\nhash = let\n in sum . zipWith (\\x c -> (ord c - least) * x) (iterate (* radix) 1)\n\nopts :: P.ByteString -> [Int]\nopts = map hash . foldr (liftM2 (:)) [[]] . map (: \"_\") . P.unpack\n-}\n\nhash :: P.ByteString -> Int\nhash = let\n step x c = (ord c - least) + radix * x\n in P.foldl' step 0\n\nopts :: P.ByteString -> [Int]\nopts = let\n step xs c = [(ord ac - least) + radix * x | x <- xs, ac <- c : \"_\"]\n in P.foldl' step [0]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, m, k] <- readInts\n when (k > maxk) $ error \"k exceeds bounds, hashing may fail\"\n pats <- replicateM n readLine\n toMatch <- replicateM m readLine\n let\n patArr :: UArray Int Int\n patArr = array (1, n) . zip [1..] $ map (hash {-. P.unpack-}) pats\n reversePatArr :: UArray Int Int\n reversePatArr = accumArray (const id) (0-1) (0, maxhash)\n [(hs, i) | (i, hs) <- assocs patArr]\n edges = foldr (liftM2 (:)) (pure []) $ do\n [currStr, mtjStr] <- map P.words toMatch\n let\n Just (mtj, _) = P.readInt mtjStr\n currOpts = [j | h <- opts currStr, let j = reversePatArr ! h, j >= 0]\n if elem mtj currOpts\n then [Just (mtj, opt) | opt <- currOpts, opt /= mtj]\n else [Nothing]\n lift $ case edges >>= topoSort (1, n) of\n Nothing -> P.putStrLn $ P.pack \"NO\"\n Just reorder -> do\n P.putStrLn $ P.pack \"YES\"\n P.putStrLn . P.pack . unwords $ map show reorder\n\n{-\nwhile :: Monad m => m Bool -> m () -> m ()\nwhile condition action = loop where\n loop = condition >>= flip when (action >> loop)\n\nupdateEntry :: STUArray s Int Int -> Int -> (Int -> Int) -> ST s Int\nupdateEntry arr ix f = do\n newVal <- f <$> readArray arr ix\n writeArray arr ix newVal -- No thunk accumulation: STUArray will force next\n pure newVal\n\ntopoSort :: (Int, Int) -> [(Int, Int)] -> Maybe [Int]\ntopoSort grBounds edges = runST $ do\n inDegrees <- newArray grBounds 0 :: ST s (STUArray s Int Int)\n forM_ edges $ \\(_, j) -> updateEntry inDegrees j (+1)\n let outEdges = accumArray (flip (:)) [] grBounds edges :: Array Int [Int]\n -- Is there a purer way to find a topological sort?\n -- This is disgustingly mutable.\n toProcess <- getAssocs inDegrees >>= \\li -> newSTRef [i | (i, 0) <- li]\n ansVar <- newSTRef []\n while (not . null <$> readSTRef toProcess) $ do\n i : rest <- readSTRef toProcess\n writeSTRef toProcess rest\n modifySTRef ansVar (i :)\n forM_ (outEdges ! i) $ \\j -> do\n newInDeg <- updateEntry inDegrees j (subtract 1)\n when (newInDeg == 0) $ modifySTRef toProcess (j :)\n ans <- readSTRef ansVar\n pure $ if length ans == rangeSize grBounds\n then Just $ reverse ans\n else Nothing\n-}\n\nseenBefore :: (Int, Int) -> [Int] -> [Int]\nseenBefore bnds li = L.runST $ do\n seenArr <- L.strictToLazyST (newArray bnds 0 :: ST s (STUArray s Int Int))\n let\n check :: STUArray s Int Int -> Int -> L.ST s Int\n check arr val = L.strictToLazyST $ do\n res <- readArray arr val\n writeArray arr val $ res + 1\n pure res\n go [] = pure []\n go (val : vals) = liftM2 (:) (check seenArr val) (go vals)\n go li\n\n-- This is still kind of unpleasant, but it's nice that all of\n-- the mutability is abstracted into one lazy function\ntopoSort :: (Int, Int) -> [(Int, Int)] -> Maybe [Int]\ntopoSort grBounds edges = let\n graph :: Array Int [Int]\n graph = accumArray (flip (:)) [] grBounds edges\n inDegrees :: UArray Int Int\n inDegrees = accumArray (\\p _ -> p + 1) 0 grBounds [(y, ()) | (_, y) <- edges]\n -- Use Nothing to separate iterations, to allow termination detection\n keepAppropriateVisits :: [Maybe Int] -> [Maybe Int]\n keepAppropriateVisits li = let\n visCts = seenBefore grBounds [x | Just x <- li]\n step _ [] = []\n step cts (Nothing : xs) = Nothing : step cts xs\n step (ct : cts) (Just x : xs) = if ct == inDegrees ! x\n then Just x : step cts xs\n else step cts xs\n step [] _ = error \"topoSort.keepAppropriateVisits: expected longer visCts\"\n in step visCts li\n neighbors :: Maybe Int -> [Maybe Int]\n neighbors Nothing = [Nothing]\n neighbors (Just x) = map Just (graph ! x)\n reachableNodes = keepAppropriateVisits queries\n queries = map Just (indices graph) ++ Nothing : concatMap neighbors reachableNodes\n cleanUp :: [Maybe Int] -> [Int]\n cleanUp (Nothing : Nothing : _) = []\n cleanUp (Just x : xs) = x : cleanUp xs\n cleanUp (_ : xs) = cleanUp xs\n cleanUp [] = error \"topoSort.cleanUp: expected infinite list\"\n ans = cleanUp reachableNodes\n in if length ans == rangeSize grBounds\n then Just ans\n else Nothing\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Char\nimport Data.Array.Unboxed\nimport qualified Data.Graph\n\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport qualified Control.Monad.ST.Lazy as L\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ncharOpts :: [Char]\ncharOpts = '_' : ['a' .. 'z']\n\nleast :: Int\nleast = minimum (ord <$> charOpts)\n\nradix :: Int\nradix = maximum (ord <$> charOpts) - least + 1\n\nmaxk :: Int\nmaxk = 4\n\nmaxhash :: Int\nmaxhash = radix ^ maxk\n\nhash :: P.ByteString -> Int\nhash = let\n step x c = (ord c - least) + radix * x\n in P.foldl' step 0\n\nopts :: P.ByteString -> [Int]\nopts = let\n step xs c = [(ord ac - least) + radix * x | x <- xs, ac <- c : \"_\"]\n in P.foldl' step [0]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, m, k] <- readInts\n when (k > maxk) $ error \"k exceeds bounds, hashing may fail\"\n pats <- replicateM n readLine\n toMatch <- replicateM m readLine\n let\n patArr :: UArray Int Int\n patArr = array (1, n) . zip [1..] $ map (hash {-. P.unpack-}) pats\n reversePatArr :: UArray Int Int\n reversePatArr = accumArray (const id) (0-1) (0, maxhash)\n [(hs, i) | (i, hs) <- assocs patArr]\n edges = foldr (liftM2 (:)) (pure []) $ do\n [currStr, mtjStr] <- map P.words toMatch\n let\n Just (mtj, _) = P.readInt mtjStr\n currOpts = [j | h <- opts currStr, let j = reversePatArr ! h, j >= 0]\n if elem mtj currOpts\n then [Just (mtj, opt) | opt <- currOpts, opt /= mtj]\n else [Nothing]\n lift $ case edges >>= topoSort (1, n) of\n Nothing -> P.putStrLn $ P.pack \"NO\"\n Just reorder -> do\n P.putStrLn $ P.pack \"YES\"\n P.putStrLn . P.pack . unwords $ map show reorder\n\n\ntopoSort :: (Int, Int) -> [(Int, Int)] -> Maybe [Int]\ntopoSort grBounds edges = let\n graph = Data.Graph.buildG grBounds edges\n -- can't use Data.Graph.topSort, because we need to check existence\n sccs = Data.Graph.scc graph\n in forM (reverse sccs) $ \\tree -> case tree of\n Data.Graph.Node x [] -> Just x\n _ -> Nothing\n\n\n{- -- My topological sort\nseenBefore :: (Int, Int) -> [Int] -> [Int]\nseenBefore bnds li = L.runST $ do\n seenArr <- L.strictToLazyST (newArray bnds 0 :: ST s (STUArray s Int Int))\n let\n check :: STUArray s Int Int -> Int -> L.ST s Int\n check arr val = L.strictToLazyST $ do\n res <- readArray arr val\n writeArray arr val $ res + 1\n pure res\n go [] = pure []\n go (val : vals) = liftM2 (:) (check seenArr val) (go vals)\n go li\n\n-- This is still kind of unpleasant, but it's nice that all of\n-- the mutability is abstracted into one lazy function\ntopoSort :: (Int, Int) -> [(Int, Int)] -> Maybe [Int]\ntopoSort grBounds edges = let\n graph :: Array Int [Int]\n graph = accumArray (flip (:)) [] grBounds edges\n inDegrees :: UArray Int Int\n inDegrees = accumArray (\\p _ -> p + 1) 0 grBounds [(y, ()) | (_, y) <- edges]\n -- Use Nothing to separate iterations, to allow termination detection\n keepAppropriateVisits :: [Maybe Int] -> [Maybe Int]\n keepAppropriateVisits li = let\n visCts = seenBefore grBounds [x | Just x <- li]\n step _ [] = []\n step cts (Nothing : xs) = Nothing : step cts xs\n step (ct : cts) (Just x : xs) = if ct == inDegrees ! x\n then Just x : step cts xs\n else step cts xs\n step [] _ = error \"topoSort.keepAppropriateVisits: expected longer visCts\"\n in step visCts li\n neighbors :: Maybe Int -> [Maybe Int]\n neighbors Nothing = [Nothing]\n neighbors (Just x) = map Just (graph ! x)\n reachableNodes = keepAppropriateVisits queries\n queries = map Just (indices graph) ++ Nothing : concatMap neighbors reachableNodes\n cleanUp :: [Maybe Int] -> [Int]\n cleanUp (Nothing : Nothing : _) = []\n cleanUp (Just x : xs) = x : cleanUp xs\n cleanUp (_ : xs) = cleanUp xs\n cleanUp [] = error \"topoSort.cleanUp: expected infinite list\"\n ans = cleanUp reachableNodes\n in if length ans == rangeSize grBounds\n then Just ans\n else Nothing\n-}\n"}], "negative_code": [], "src_uid": "9dfd415d4ed6247d6bee84e8a6558543"} {"source_code": "import Data.List(sort)\n\nreadRows :: Int ->IO [[Int]]\nreadRows 0 = return []\nreadRows i = do\n raw_line <-getLine\n this <-return . fmap (read::String ->Int) . words $ raw_line\n next <-readRows (i-1)\n return (this:next)\n\nsolve :: [(Int, [Int])] ->Int ->[Int]\nsolve [] _ = []\nsolve list iter =\n (\\(xs,((i,_):ys)) -> (i : solve (xs ++ ys) (iter+1)))\n $ (span (any (>iter) . snd) list)\n\npermute :: [Int] ->[Int]\npermute = fmap snd . sort . (`zip` [1..])\n\nmain :: IO()\nmain = do\n n <-(readLn::IO Int)\n input <-readRows n\n result <-return $ permute $ solve (zip [1..] input) 1\n putStrLn . unwords . fmap show $ result", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\ngetIntList :: IO [Int]\ngetIntList = fmap read . words <$> getLine\n\ngetIntMat :: Int -> IO [[Int]]\ngetIntMat r = replicateM r (fmap read . words <$> getLine)\n\nmain :: IO ()\nmain = putStrLn . unwords . fmap show =<< sol <$> (readLn >>= getIntMat)\n\nsol :: [[Int]] -> [Int]\nsol mat = fmap (+1) [fromMaybe (n-1) $ findIndex (==r) rs | r <- [0..n-1]]\n where\n n = length mat\n f i row = length $ filter (==i) row\n g i = fromJust $ findIndex (==(n-i)) [f i (mat!!r) | r <- [0..n-1]]\n rs = [g i | i <- [1..n-1]]\n"}], "negative_code": [{"source_code": "import Data.List(sort)\n\nreadRows :: Int ->IO [[Int]]\nreadRows 0 = return []\nreadRows i = do\n raw_line <-getLine\n this <-return . fmap (read::String ->Int) . words $ raw_line\n next <-readRows (i-1)\n return (this:next)\n\nsolve :: [(Int, [Int])] ->Int ->[Int]\nsolve [] _ = []\nsolve list iter =\n (\\(xs,((i,_):ys)) -> (i : solve (xs ++ ys) (iter+1)))\n $ (span (any (>iter) . snd) list)\n\npermute :: [Int] ->[Int]\npermute = fmap snd . sort . (`zip` [1..])\n\nmain :: IO()\nmain = do\n n <-(readLn::IO Int)\n input <-readRows n\n result <-return $ permute $ solve (zip [1..] input) 1\n print result"}], "src_uid": "1524c658129aaa4175208b278fdc467c"} {"source_code": "import Data.List\n\nmain = interact $ show . f . lines\nf [n,as] = read n - g (words as) [0,0,0]\n where\n g (\"1\":as) [x,y,z] = x `seq` g as [x+1, y, z]\n g (\"2\":as) [x,y,z] = y `seq` g as [x, y+1, z]\n g (\"3\":as) [x,y,z] = z `seq` g as [x, y, z+1]\n g _ bs = maximum bs\n", "positive_code": [{"source_code": "readI :: String -> Int\nreadI = read \n\nmain = do\n n <- getLine >>= return . readI\n xs <- getLine\n print $ solve n xs\n\nsolve n xs = caiser (words xs) [0,0,0] where\n\n caiser (\"1\":xs) [c1, c2, c3] = c1 `seq` caiser xs [c1+1, c2, c3]\n caiser (\"2\":xs) [c1, c2, c3] = c2 `seq` caiser xs [c1, c2+1, c3]\n caiser (\"3\":xs) [c1, c2, c3] = c3 `seq` caiser xs [c1, c2, c3+1]\n caiser _ cs = n - maximum cs\n"}, {"source_code": "\nsolve :: Int -> String -> Int\nsolve n xs = n - maximum [c1, c2, c3]\n where\n (c1, c2, c3) = solve' 0 0 0 xs\n solve' c1 c2 c3 [] = (c1, c2, c3)\n solve' c1 c2 c3 ('1':xs) = seq c1' solve' c1' c2 c3 xs\n where\n c1' = c1 + 1\n solve' c1 c2 c3 ('2':xs) = seq c2' solve' c1 c2' c3 xs\n where\n c2' = c2 + 1\n solve' c1 c2 c3 ('3':xs) = seq c3' solve' c1 c2 c3' xs\n where\n c3' = c3 + 1\n solve' c1 c2 c3 (_:xs) = solve' c1 c2 c3 xs\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- getLine\n print $ solve n xs\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nmain=B.interact$B.pack.show.f.tail.map(fst.fromJust.B.readInt).B.words\nf x=sum$init$sort[g 1 x, g 2 x, g 3 x]\ng k x=length$filter(==k)$x"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Char\n\ncount :: Eq a => a -> [a] -> Int\ncount t = foldl (\\x y -> if y == t then x + 1 else x) 0 \n\nsolve arr = (a + b + c) - (a `max` b `max` c)\n where\n a = count '1' arr\n b = count '2' arr\n c = count '3' arr\n\nmain = do\n line <- getLine\n arr <- fmap (filter isDigit) getLine\n print $ solve arr\n\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport IO\n\nmain = do C.hGetContents stdin >>= putStr . show . gao . map (fst . fromJust . C.readInt) . C.words where\n\tgao (n:a) = n - maximum [length $ filter (==i) a | i <- [1 .. 3]]\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\n\nmain = do\n getLine\n xs <- fmap B.words B.getContents\n print $ solve xs\n\nsolve :: [B.ByteString] -> Integer\nsolve xs = a + b\n where [a,b,c] = sort $ foldl(#)[0,0,0] xs\n\n[a,b,c]# \"1\" = [a+1,b,c]\n[a,b,c]# \"2\" = [a,b+1,c]\n[a,b,c]# \"3\" = [a,b,c+1]"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\n\nmain = do\n _ <- getLine\n xs <- fmap B.words B.getContents\n print (solve xs)\n\nsolve :: [B.ByteString] -> Int\nsolve xs =\n let (a,b,c) = foldl' f (0,0,0) xs\n m = (max a (max b c))\n in a+b+c-m\n where\n f (a,b,c) x | x == \"1\" = (a+1,b,c)\n | x == \"2\" = (a,b+1,c)\n |otherwise = (a,b,c+1)"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n xs <- fmap words getContents\n print $ solve xs\n\nsolve :: [String] -> Integer\nsolve xs = a + b\n where [a,b,c] = sort $ foldl(#)[0,0,0] xs\n\n[a,b,c]# \"1\" = [a+1,b,c]\n[a,b,c]# \"2\" = [a,b+1,c]\n[a,b,c]# \"3\" = [a,b,c+1]"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n xs <- fmap words getLine\n print $ solve xs\n\nsolve :: [String] -> Integer\nsolve xs = a + b\n where [a,b,c] = sort $ foldl(#)[0,0,0] xs\n\n[a,b,c]# \"1\" = [a+1,b,c]\n[a,b,c]# \"2\" = [a,b+1,c]\n[a,b,c]# \"3\" = [a,b,c+1]"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Unboxed\nimport Data.Array.ST\n\nmain = do\n n <- read `liftM` getLine\n nums <- getLine\n let countArray = runSTUArray $ do\n countArray <- newArray ('1','3') 0 :: ST s (STUArray s Char Int)\n forM_ nums $ \\c -> if c == ' '\n then return ()\n else readArray countArray c >>= writeArray countArray c . (1+)\n return countArray\n\n putStrLn $ show $ n - ( maximum $ elems countArray )\n"}], "negative_code": [], "src_uid": "fcb6a715dfe302d7ae5a6695ca8976aa"} {"source_code": "main=interact(show.o.map read.words)\no(n:ds)=if odd s then s else if all even ds then 0 else s-(minimum.filter odd)ds where s=sum ds\n", "positive_code": [{"source_code": "import List\n\nmain = do\n\tn <- fmap read getLine\n\ta <- fmap (map read . words) getLine\n\tputStrLn $ show $ gao n a\n\ngao :: Int -> [Integer] -> Integer\ngao n a = if null o then 0 else sum e + sum (if odd $ length o then o else tail o) where\n\to = sort $ filter odd a\n\te = sort $ filter even a\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.List\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nsolve a\n\t| sum a `mod` 2 == 1 = sum a\n\t| otherwise = case firstOdd of\n\t\tNothing -> 0\n\t\tJust x -> sum a - x\n\twhere firstOdd = find (\\x -> x `mod` 2 == 1) a\n\nmain = do\n\tinput <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n\tlet n = readInt $ input !! 0\n\tlet a = readIntList $ input !! 1\n\tprint $ solve $ sort a\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts\n\n let\n s1 = sum $ filter even as\n os = filter odd as\n\n s2 = sum $ if odd (length os) then os else tail $ sort os\n\n print $\n if null os\n then 0\n else s1 + s2\n"}, {"source_code": "\nsolve :: [Int] -> Int\nsolve xs\n | length odds == 0 = 0\n | otherwise = sum xs - if (odd $ length odds) then 0 else minimum odds\n where\n odds = filter odd xs\n evens = filter even xs\n\nmain :: IO ()\nmain = getLine >> fmap (map read . words) getLine >>= print . solve\n"}, {"source_code": "import Data.List\nmain = do\n [n] <- map read `fmap` (words `fmap` getLine)\n flowers <- fmap (\\s -> map (\\(a, _) -> read a) $ zip s [1..n]) (words `fmap` getLine)\n if all even flowers then putStr \"0\" else \n if even $ sum flowers then do\n let f' = sort flowers\n firstOdd = find odd f'\n putStr $ show $ case firstOdd of\n Just e -> sum flowers - e\n Nothing -> 0\n else putStr $ show $ sum flowers\n"}, {"source_code": "import Data.Char\n\n\nnumbers = (\\s-> ([0] ++ (map (\\s-> read s ::Int) $ words s)))\nans = (\\s-> ( maximum $ [0] ++ (filter (\\n-> n`mod`2 == 1) $ map (\\x-> sum (numbers s) - x) (numbers s) )))\n\nmain = do\n getLine\n line <- getLine\n putStrLn (show (ans line))\n \n\n"}, {"source_code": "opt [] _ oddOpt = oddOpt\nopt (x:xs) evenOpt oddOpt\n | odd x\t= opt xs (max evenOpt $ if oddOpt>0 then oddOpt+x else 0)\n (max oddOpt $ evenOpt+x)\n | otherwise\t= opt xs (evenOpt+x) $ if oddOpt>0 then oddOpt+x else 0\n\nmain = do\n n <- getLine\n line <- getLine\n print $ opt (map read $ words line) 0 0\n"}], "negative_code": [], "src_uid": "a5d56056fd66713128616bc7c2de8b22"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\nimport Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\t[ h, w, _, _ ] <- readInts\r\n\tprintf \"%d %d %d %d\\n\" ( 1 :: Int ) ( 1 :: Int ) h w", "positive_code": [{"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\ntoStr [] = \"\"\r\ntoStr (x:xs) = show x ++ \" \" ++ toStr xs\r\n\r\nsolve [n,m,i,j] = putStrLn $ toStr [1,1,n,m]\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n xss <- replicateM t readInts\r\n mapM_ solve xss"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\ntoStr [] = \"\"\r\ntoStr (x:xs) = show x ++ \" \" ++ toStr xs\r\n\r\nsolve [n,m,i,j] = putStrLn $ toStr [x1,y1,x2,y2]\r\n where \r\n x1 = 1\r\n y1 = 1\r\n x2 = n\r\n y2 = m\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n xss <- replicateM t readInts\r\n mapM_ solve xss"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\nimport Text.Printf\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n, m, i, j] <- map fromIntegral <$> getInts :: IO [Int64]\n let corners = [(x, y) | x <- [1, n], y <- [1, m]]\n distance (x1, y1) (x2, y2) = abs (x1 - x2) + abs (y1 - y2)\n func q p1 p2 = distance q p1 + distance p1 p2 + distance p2 q\n calc q p1 p2 = min (func q p1 p2) (func q p2 p1)\n (_, (x1, y1), (x2, y2)) = maximum [(calc (i, j) p1 p2, p1, p2) | p1 <- corners, p2 <- corners]\n return $ string7 (printf \"%d %d %d %d\\n\" x1 y1 x2 y2)\n hPutBuilder stdout output\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine \r\n replicateM_ tn $ do\r\n [n,m,i,j] <- map parseInt . BS.words <$> BS.getLine\r\n putStrLn $ \"1 1 \" ++ show n ++ \" \" ++ show m\r\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\ntoStr [] = \"\"\r\ntoStr (x:xs) = show x ++ \" \" ++ toStr xs\r\n\r\nsolve [n,m,i,j] = putStrLn $ toStr [x1,y1,x2,y2]\r\n where \r\n x1 = 1\r\n y1 = j\r\n x2 = n\r\n y2 = if m - j > j - 1 then m else 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n xss <- replicateM t readInts\r\n mapM_ solve xss"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\nimport Text.Printf\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n, m, i, j] <- getInts\n let corners = [(x, y) | x <- [1, n], y <- [1, m]]\n distance (x1, y1) (x2, y2) = abs (x1 - x2) + abs (y1 - y2)\n func q p1 p2 = distance q p1 + distance p1 p2 + distance p2 q\n calc q p1 p2 = min (func q p1 p2) (func q p2 p1)\n (_, (x1, y1), (x2, y2)) = maximum [(calc (i, j) p1 p2, p1, p2) | p1 <- corners, p2 <- corners]\n return $ string7 (printf \"%d %d %d %d\\n\" x1 y1 x2 y2)\n hPutBuilder stdout output\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\nimport Text.Printf\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n, m, i, j] <- getInts\n let corners = [(x, y) | x <- [1, n], y <- [1, m]]\n distance (x1, y1) (x2, y2) = abs (x1 - x2) + abs (y1 - y2)\n (_, (x1, y1), (x2, y2)) = maximum [(distance (i, j) p1 + distance p1 p2 + distance p2 (i, j), p1, p2) | p1 <- corners, p2 <- corners]\n return $ string7 (printf \"%d %d %d %d\\n\" x1 y1 x2 y2)\n hPutBuilder stdout output\n"}], "src_uid": "5aae6b27f35852512a250751ef957ab9"} {"source_code": "module Main where\n\nimport Data.List\n\nsecond (_:x:xs) = x : second xs\nsecond _ = []\n\nprocess :: [Int] -> Bool\nprocess x = not $ any (> 1) diffs\n where diffs = zipWith (-) (tail s) s\n s = sort x\n\nmain = interact $ unlines . map (out . process . map read . words) . second . tail . lines\n where out x = if x then \"YES\" else \"NO\"", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tgetLine\n\t\tx<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tif length x ==1 then putStrLn \"YES\"\n\t\t\t\telse\n\t\t\t\t\tdo\n\t\t\t\t\t\tlet y = maximum $ map abs $ zipWith (-) x (tail x)\n\t\t\t\t\t\tputStrLn $ if y>1 then \"NO\" else \"YES\"\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "import System.IO\nimport Data.List\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = map (read :: (String -> Int)) . words <$> tail contents\n sequence $ solve arr\n\n-- solve :: [[Char]] -> [IO [()]]\n-- solve :: [] -> [IO ()]\nsolve [] = []\nsolve (_:arr:xs) =\n let go :: Int -> [Int] -> Bool\n go x [] = True\n go x (a:xs) = a-x <= 1 && go a xs\n sorted = sort arr\n in putStrLn (toYes (go (head sorted) (tail sorted))):solve xs\n\ntoYes True = \"YES\"\ntoYes _ = \"NO\""}, {"source_code": "import Control.Arrow\nimport Data.List\n\nmain :: IO ()\nmain = interact $\n lines >>> tail >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess [x] = []\nprocess (_:x:xs) = (res) : (process xs)\n where \n x' = map read $ words x\n ans = solve x'\n res = if ans then \"YES\" else \"NO\"\n\n\nsolve :: [Int] -> Bool\nsolve [a] = True\nsolve a = maximum gaps <= 1\n where \n a' = sort a\n -- gaps = map (\\(x, y) -> x - y) $ zip a' (tail a')\n -- gaps = zipWith (\\ x y -> x - y) (tail a') a'\n gaps = zipWith (-) (tail a') a'\n -- operators need to be enclosed in parentheses if you want to pass it as argument\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (\\b -> if b then \"YES\" else \"NO\")\n >>> unlines\n\nprocess :: [[Int]] -> [Bool]\nprocess [] = []\nprocess ([_] : xs : rest) = solve xs : process rest\n\nsolve :: [Int] -> Bool\nsolve [_] = True\nsolve xs = let xs' = sort xs in maximum (zipWith (-) (drop 1 xs') xs') <= 1\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> String\nsolve [] = \"NO\"\nsolve [_] = \"YES\"\nsolve (x':x:xs) | abs (x' - x) <= 1 = solve (x:xs)\n | otherwise = \"NO\"\n\nclean :: [String] -> [String]\nclean [] = []\nclean (_ : s : ss) = s : clean ss\nclean _ = undefined\n\nmain :: IO ()\nmain = interact\n (unlines . map (solve . sort . map read . words) . clean . tail . lines)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ bool \"NO\" \"YES\" $ all (<= 1) $ zipWith subtract <*> tail $ sort as\n"}, {"source_code": "import Control.Monad\nimport Data.Bool\nimport Data.List\n\nsolve :: IO ()\nsolve = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ bool \"NO\" \"YES\" $ all (<= 1) $ zipWith subtract <*> tail $ sort as\n\nmain :: IO ()\nmain = do\n getLine >>= flip replicateM_ solve . read\n "}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $\n getLine >> getLine >>= putStrLn . yesNo . solve . map read . words\n\nsolve :: [Int] -> Bool\nsolve a =\n let l = sort a\n in all (<= 1) $ zipWith (-) (tail l) l\n\nyesNo :: Bool -> String\nyesNo True = \"YES\"\nyesNo False = \"NO\"\n"}, {"source_code": "module Main where\n\n import Data.List\n \n solve :: IO ()\n solve = do\n _ <- getLine\n s <- getLine\n let a = sort $ map (\\x -> read x :: Integer) $ words s\n n = length a\n l = length [i | i <- [0..n - 2], a !! (i + 1) - a !! i <= 1]\n putStrLn $ if n == l + 1 then\n \"YES\"\n else\n \"NO\"\n\n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Integer)"}, {"source_code": "import Control.Monad -- for replicateM_\n\nsort :: Ord a => [a] -> [a]\nsort [] = []\nsort (p:xs) = (sort lesser) ++ [p] ++ (sort greater)\n where\n lesser = filter (< p) xs\n greater = filter (>= p) xs\n\nsolve :: [Int] -> Bool\nsolve (x:xs)\n | null xs = True\n | otherwise = continuous && solve xs \n where \n continuous = abs (x - (head xs)) <= 1\n\nformatOutput :: String -> String -> Bool -> String\nformatOutput true false boolean\n | boolean == True = true\n | otherwise = false\n\ndeal :: IO()\ndeal = do \n getLine\n x <- map read . words <$> getLine\n putStrLn $ formatOutput \"YES\" \"NO\" $ solve $ sort x\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad\n-- 1. sorting \n-- 2. False when there are non continuous && non duplicate && !Solve\n-- True when \n-- (continuous || (non continuous && next two is duplicate)) && solve xs \n\n\n\nsort :: Ord a => [a] -> [a]\nsort [] = []\nsort (p:xs) = (sort lesser) ++ [p] ++ (sort greater)\n where\n lesser = filter (< p) xs\n greater = filter (>= p) xs\n\n\nsolve :: [Int] -> Bool\nsolve (x:xs)\n | null xs = True\n | otherwise = continuous && solve xs \n where \n continuous = abs (x - (head xs)) <= 1\n\nformatOutput :: String -> String -> Bool -> String\nformatOutput true false boolean\n | boolean == True = true\n | otherwise = false\n\n-- show . solve . sort . map read . words \ndeal :: IO()\ndeal = do \n getLine\n x <- map read . words <$> getLine\n putStrLn $ formatOutput \"YES\" \"NO\" $ solve $ sort x\n -- putStrLn \"hello\"\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read "}, {"source_code": "-- SPDX-License-Identifier: X11\n-- 2020-08-25\n-- Remove Smallest\n\nmodule Main where\n\nimport Data.List (sort)\n\nsolve :: (Num a, Ord a) => [a] -> String\nsolve = (\\x -> if x then \"YES\\n\" else \"NO\\n\") . comp . sort\n where\n comp :: (Num a, Ord a) => [a] -> Bool\n comp (x : ys@(y : _)) = abs (x - y) <= 1 && comp ys\n comp _ = True\n\nparse :: String -> String\nparse = concatMap (solve . map (read :: String -> Int) . words) .\n subl [] . tail . lines\n where\n subl :: [a] -> [a] -> [a]\n subl l [_, y] = reverse (y : l)\n subl l (_ : y : zs) = subl (y : l) zs\n subl _ _ = error \"subl: Unhandled case\"\n\nmain :: IO ()\nmain = getContents >>= \\x -> putStr . parse $ x\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tgetLine\n\t\tx<- map read <$> words <$> getLine ::IO [Int]\n\t\tif length x ==1 then putStrLn \"YES\"\n\t\t\t\telse\n\t\t\t\t\tdo\n\t\t\t\t\t\tlet y = maximum $ map abs $ zipWith (-) x (tail x)\n\t\t\t\t\t\tputStrLn $ if y>1 then \"NO\" else \"YES\"\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "import System.IO\nimport Data.List\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = map (read :: (String -> Int)) . words <$> tail contents\n sequence $ solve arr\n\n-- solve :: [[Char]] -> [IO [()]]\n-- solve :: [] -> [IO ()]\nsolve [] = []\nsolve (_:arr:xs) =\n let go :: Int -> [Int] -> Bool\n go x [] = True\n go x (a:xs) = a-x <= 1 && go a xs\n sorted = sort arr\n in print (go (head sorted) (tail sorted)):solve xs"}], "src_uid": "ed449ba7c453a43e2ac5904dc0174530"} {"source_code": "import List\ng a 0 l=[a:l]\ng a i(h:t)=map(h:)$g a(i-1)t\ng _ _ _=[]\nf l((n,a),i)=l>>=g(i,a)n\nz x=zip x[1..]\nmain=interact$last.(\"-1\":).map(unlines.map(\\((_,a),i)->a++\" \"++show i).sort.z.reverse).foldl f[[]].z.sort.map((\\[a,n]->(read n,a)).words).tail.lines\n", "positive_code": [{"source_code": "import Data.Ord\nimport Data.List(sortBy,groupBy)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n css <- mapM (\\i -> getLine) [1..n]\n putStrLn $ unlines $ solve n $ sortBy (comparing snd) $ map ((\\ [x,y] -> (x,read y)) . words) css\n\nsolve :: Int -> [(String,Int)] -> [String]\nsolve n xxs@(x:xs)\n | (any id $ zipWith (\\i j -> (snd i) > j) xxs [0..]) = [\"-1\"]\n | otherwise = g $ zipWith f [n,(n-1)..] $ groupBy (\\i j-> (snd i)==(snd j)) xxs\n\nf :: Int -> [(String,Int)] -> [(String,Int)]\nf n = map (\\ (cs,i) -> ((cs ++ \" \" ++ (show n)),i))\n\ng :: [[(String,Int)]] -> [String]\ng [] = []\ng xs = map fst $ h [] xs\n\nh :: [(String,Int)] -> [[(String,Int)]] -> [(String,Int)]\nh xs [] = xs\nh [] (y:ys) = h y ys\nh xs (y:ys) = h (xs1 ++ y ++ xs2) ys\n where i = snd $ head y\n (xs1,xs2) = splitAt i xs\n"}, {"source_code": "import Data.Ord\nimport Data.List\ng a 0 l=Just$a:l\ng a i(h:t)=fmap(h:)$g a(i-1)t\ng _ _ _=Nothing\nf l(a,i)=l>>=g a i\np=unlines.map(\\(i,(_,a))->a++\" \"++show i).sortBy(comparing$fst.snd).zip[1..].reverse\nmain=interact$maybe\"-1\"p.foldl f(Just[]).map(\\(i,(a,n))->((i,a),n)).zip[1..].sortBy(comparing snd).map((\\[a,n]->(a,read n)).words).tail.lines"}, {"source_code": "import List\ng a 0 l=[a:l]\ng a i(h:t)=map(h:)$g a(i-1)t\ng _ _ _=[]\nf(i,(n,a))l=l>>=g(a++\" \"++show i)n\nq[a,n]=(read n,a)\nmain=interact$unlines.last.([\"-1\"]:).foldr f[[]].zip[1..].reverse.sort.map(q.words).tail.lines\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (unlines . solve .\n map (\\s -> let a = words s in (a !! 0, read $ a !! 1)) .\n tail . lines)\n\nsolve :: [(String, Int)] -> [String]\nsolve humans = result where\n result = case heightOrder of\n Nothing -> [\"-1\"]\n Just h -> answer where\n answer = map (\\(name, height) -> name ++ (' ' : show height)) que\n que = map (\\(x, y, z) -> (y, z)) $ sort $ zipWith (\\(name, num) height -> (num, name, height)) (reverse h) [1..]\n\n heightOrder = getOrder sortedHumans\n sortedHumans = sortBy (\\(n1, c1) (n2, c2) -> compare c1 c2) humans\n\ngetOrder :: [(String, Int)] -> Maybe [(String, Int)]\ngetOrder = getOrder' (Just []) 0\ngetOrder' result _ [] = result\ngetOrder' result k ((n, c) : humans) = getOrder' (ins (n, k) c result) (k + 1) humans\n\nins :: a -> Int -> Maybe [a] -> Maybe [a]\nins _ _ Nothing = Nothing\nins x i (Just xs) = if i <= length xs\n then let (b, e) = splitAt i xs in Just (b ++ (x : e))\n else Nothing\n"}, {"source_code": "import Data.Array.IO\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\n-- set next[x] to be at level c\nadd :: IOUArray Int Int -> Int -> Int -> IO ()\nadd next x c = do\n let loop p 0 = return p\n loop p c = do p' <- readArray next p; loop p' (c-1)\n do p <- loop 0 c\n q <- readArray next p\n writeArray next p x\n writeArray next x q\n return ()\n\nmain = do\n n <- fmap read getLine\n pairs <- replicateM n $ do (name:ds:_) <- fmap words getLine; return (read ds, name)\n let sorted = sort pairs\n -- check\n if not $ all (\\(i,(d,_)) -> d < i) (zip [(1::Int)..] sorted)\n then putStrLn \"-1\"\n else do next <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n forM_ (zip [1..] sorted) $ \\(i,(d,_)) -> add next i d\n vals <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n let loop 0 v = return ()\n loop p v = do writeArray vals p v;\n p' <- readArray next p\n loop p' (v-1)\n h <- readArray next 0\n loop h n\n forM_ (zip [1..] sorted) $ \\(i,(d,name)) -> do\n v <- readArray vals i\n putStrLn $ name ++ \" \" ++ show v\n\ntest = do\n next <- newArray (0,10) 0 :: IO (IOUArray Int Int)\n add next 1 0\n add next 2 0\n add next 3 0\n add next 4 0\n add next 5 2\n\n vals <- newArray (0,10) 0 :: IO (IOUArray Int Int)\n let loop 0 v = return ()\n loop p v = do writeArray vals p v;\n p' <- readArray next p\n loop p' (v-1)\n\n h <- readArray next 0\n loop h 10\n\n putStrLn \"vals: \"\n forM_ [0..10] $ \\i -> do\n v <- readArray vals i\n putStr $ show v ++ \" \"\n putStrLn \"\"\n\n\n"}, {"source_code": "import Data.Array.IO\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\n-- set next[x] to be at level c\nadd :: IOUArray Int Int -> Int -> Int -> IO ()\nadd next x c = do\n let loop p 0 = return p\n loop p c = do p' <- readArray next p; loop p' (c-1)\n do p <- loop 0 c\n q <- readArray next p\n writeArray next p x\n writeArray next x q\n return ()\n\nmain = do\n n <- fmap read getLine\n pairs <- replicateM n $ do (name:ds:_) <- fmap words getLine; return (read ds, name)\n let sorted = sort pairs\n -- check\n if not $ all (\\(i,(d,_)) -> d < i) (zip [(1::Int)..] sorted)\n then putStrLn \"-1\"\n else do next <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n forM_ (zip [1..] sorted) $ \\(i,(d,_)) -> add next i d\n vals <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n let loop 0 v = return ()\n loop p v = do writeArray vals p v;\n p' <- readArray next p\n loop p' (v-1)\n h <- readArray next 0\n loop h n\n forM_ (zip [1..] sorted) $ \\(i,(d,name)) -> do\n v <- readArray vals i\n putStrLn $ name ++ \" \" ++ show v\n"}], "negative_code": [{"source_code": "import Data.List(sortBy,groupBy)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n css <- mapM (\\i -> getLine) [1..n]\n putStrLn $ unlines $ solve n $ sortBy comp $ map ((\\ (x:y:_) -> (x,read y)) . words) css\n\ncomp :: (String,Int) -> (String,Int) -> Ordering\ncomp x y = compare (snd x) (snd y)\n\nsolve :: Int -> [(String,Int)] -> [String]\nsolve n xxs@(x:xs)\n | snd x /= 0 = [\"-1\"]\n | null nzs = map (flip m 1) zs'\n | (length zs) < ((snd.head.last) $ nzss) = [\"-1\"]\n | otherwise = zipWith m (f zs nzss) [1..n]\n where (zs,nzs) = span ((0==).snd) xxs\n nzss = groupBy (\\i j-> (snd i)==(snd j)) nzs\n zs' = map (\\ (cs,i)-> (cs,pred i)) zs\n\nf :: [(String,Int)] -> [[(String,Int)]] -> [(String,Int)]\nf xs [] = xs\nf [] ys = head ys\nf xxs@(x:xs) (y:ys) = xs1 ++ y ++ (f xs2 ys')\n where n = snd $ head y\n (xs1,xs2) = splitAt n xxs\n ys' = map (map (\\ (i,j)-> (i,j-n))) ys\n\nm :: (String,Int) -> Int -> String\nm (cs,i) j = if i == -1 then cs ++ \" 2\" else cs ++ \" 1\""}, {"source_code": "import Data.List(sortBy,groupBy)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n css <- mapM (\\i -> getLine) [1..n]\n putStrLn $ unlines $ solve n $ sortBy comp $ map ((\\ (x:y:_) -> (x,read y)) . words) css\n\ncomp :: (String,Int) -> (String,Int) -> Ordering\ncomp x y = compare (snd x) (snd y)\n\nsolve :: Int -> [(String,Int)] -> [String]\nsolve n xxs@(x:xs)\n | snd x /= 0 = [\"-1\"]\n | null nzs = map (flip m 1) zs\n | (length zs) < ((snd.head.last) $ nzss) = [\"-1\"]\n | otherwise = zipWith m (f zs nzss) [1..n]\n where (zs,nzs) = span ((0==).snd) xxs\n nzss = groupBy (\\i j-> (snd i)==(snd j)) nzs\n\nf :: [(String,Int)] -> [[(String,Int)]] -> [(String,Int)]\nf xs [] = xs\nf [] ys = head ys\nf xxs@(x:xs) (y:ys) = xs1 ++ y ++ (f xs2 ys')\n where n = snd $ head y\n (xs1,xs2) = splitAt n xxs\n ys' = map (map (\\ (i,j)-> (i,j-n))) ys\n\nm :: (String,Int) -> Int -> String\nm (cs,i) j = if i == 0 then cs ++ \" 2\" else cs ++ \" 1\""}, {"source_code": "import Data.List(sortBy,groupBy)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n css <- mapM (\\i -> getLine) [1..n]\n putStrLn $ unlines $ solve n $ sortBy comp $ map ((\\ (x:y:_) -> (x,read y)) . words) css\n\ncomp :: (String,Int) -> (String,Int) -> Ordering\ncomp x y = compare (snd x) (snd y)\n\nsolve :: Int -> [(String,Int)] -> [String]\nsolve n xxs@(x:xs)\n | snd x /= 0 = [\"-1\"]\n | null nzs = map (flip m 1) zs'\n | (length zs) < ((snd.head.last) $ nzss) = [\"-1\"]\n | otherwise = zipWith m (f zs' nzss) [1..n]\n where (zs,nzs) = span ((0==).snd) xxs\n nzss = groupBy (\\i j-> (snd i)==(snd j)) nzs\n zs' = map (\\ (cs,i)-> (cs,pred i)) zs\n\nf :: [(String,Int)] -> [[(String,Int)]] -> [(String,Int)]\nf xs [] = xs\nf [] ys = head ys\nf xxs@(x:xs) (y:ys) = xs1 ++ y ++ (f xs2 ys')\n where n = snd $ head y\n (xs1,xs2) = splitAt n xxs\n ys' = map (map (\\ (i,j)-> (i,j-n))) ys\n\nm :: (String,Int) -> Int -> String\nm (cs,i) j = if i == -1 then cs ++ \" 2\" else cs ++ \" 1\""}, {"source_code": "import Data.List(sortBy,groupBy)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n css <- mapM (\\i -> getLine) [1..n]\n putStrLn $ unlines $ solve n $ sortBy comp $ map ((\\ (x:y:_) -> (x,read y)) . words) css\n\ncomp :: (String,Int) -> (String,Int) -> Ordering\ncomp x y = compare (snd x) (snd y)\n\nsolve :: Int -> [(String,Int)] -> [String]\nsolve n xxs@(x:xs)\n | snd x /= 0 = [\"-1\"]\n | null nzs = map (flip m 1) zs'\n | (length zs) < ((snd.head.last) $ nzss) = [\"-1\"]\n | otherwise = zipWith m (f zs' nzss) [1..n]\n where (zs,nzs) = span ((0==).snd) xxs\n nzss = groupBy (\\i j-> (snd i)==(snd j)) nzs\n zs' = map (\\ (cs,i)-> (cs,pred i)) zs\n\nf :: [(String,Int)] -> [[(String,Int)]] -> [(String,Int)]\nf xs [] = xs\nf [] ys = concat ys\nf xxs@(x:xs) (y:ys) = xs1 ++ y ++ (f xs2 ys')\n where n = snd $ head y\n (xs1,xs2) = splitAt n xxs\n ys' = map (map (\\ (i,j)-> (i,j-n))) ys\n\nm :: (String,Int) -> Int -> String\nm (cs,i) j = if i == -1 then cs ++ \" 2\" else cs ++ \" 1\""}], "src_uid": "112d5d664b0183d96e55a3c545d9b7d5"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray bs (-1)\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s ()\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s ()\ndeletePrio prio@(Prio val ref arr idx) x = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n i <- readArray idx x\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n LT -> fixDown prio i\n GT -> void $ fixUp prio i\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s ()\nfixUp _ 0 = return ()\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv >= pv then return i else putPrio prio i px >> go p\n top <- go start\n unless (top == start) $ putPrio prio top x\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n unless(bottom == start) $ putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n prio <- newPrio best\n writeArray best s 0\n pushPrio prio s\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n check dist edges\n go\n better _ (-1) = True\n better price x = price < x\n check _ [] = return ()\n check acc (Edge cost to: rest) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ deletePrio prio to\n writeArray best to price\n void $ pushPrio prio to\n check acc rest\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray bs (-1)\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s ()\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s ()\ndeletePrio prio@(Prio val ref arr idx) x = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n i <- readArray idx x\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n LT -> fixDown prio i\n GT -> void $ fixUp prio i\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s ()\nfixUp _ 0 = return ()\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv >= pv then return i else putPrio prio i px >> go p\n top <- go start\n unless (top == start) $ putPrio prio top x\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n unless(bottom == start) $ putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n prio <- newPrio best\n writeArray best s 0\n pushPrio prio s\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ deletePrio prio to\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray bs (-1)\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s ()\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s ()\ndeletePrio prio@(Prio val ref arr idx) x = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n i <- readArray idx x\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n GT -> void $ fixUp prio i\n EQ -> return ()\n LT -> fixDown prio i\n\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s ()\nfixUp _ 0 = return ()\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv >= pv then return i else putPrio prio i px >> go p\n top <- go start\n unless (top == start) $ putPrio prio top x\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n unless(bottom == start) $ putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n prio <- newPrio best\n writeArray best s 0\n pushPrio prio s\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n check dist edges\n go\n better _ (-1) = True\n better price x = price < x\n check _ [] = return ()\n check acc (Edge cost to: rest) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ deletePrio prio to\n writeArray best to price\n void $ pushPrio prio to\n check acc rest\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport qualified Data.Set as Set\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ntype STCmp s = Int->Int->ST s Bool\ntype STNotify s = Int->Int->ST s ()\ndata Prio s = Prio (STCmp s) (STRef s Int) (STUArray s Int Int) (STNotify s)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr notify) i x = writeArray arr i x >> notify i x\n\nnewPrio::Int->STCmp s->STNotify s->ST s (Prio s)\nnewPrio n cmp notify = do\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n return $ Prio cmp len arr notify\n\nnewPrio'::Int->STCmp s->ST s (Prio s)\nnewPrio' n cmp = newPrio n cmp (const $ const $ return ())\n\npushPrio::Prio s->Int->ST s Int\npushPrio prio@(Prio _ ref arr notify) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s Int\ndeletePrio prio@(Prio cmp ref arr notify) i = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr i\n w <- readArray arr (n - 1)\n putPrio prio i w\n descent <- cmp x w\n if descent then fixDown prio i else void $ fixUp prio i\n return x\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s Int\nfixUp _ 0 = return 0\nfixUp prio@(Prio cmp _ arr _) start = do\n x <- readArray arr start\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n correct <- cmp px x\n if correct then return i else putPrio prio i px >> go p\n top <- go start\n writeArray arr top x\n return top\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio cmp ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n correct <- cmp x cx\n if correct then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n let goLeft = writeArray arr i lx >> go l\n goRight = writeArray arr i rx >> go r\n correctL <- cmp x lx\n if correctL then do\n correctR <- cmp x rx\n if correctR then return i else goRight\n else do\n bestL <- cmp lx rx\n if bestL then goLeft else goRight\n bottom <- go start\n writeArray arr bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n let mkArray::ST s (STUArray s Int Int)\n mkArray = newArray_ (bounds graph)\n ind <- mkArray\n let cmp x y = do\n cx <- readArray best x\n cy <- readArray best y\n return $ cx <= cy\n notify i x = writeArray ind x i\n prio <- newPrio (rangeSize $ bounds graph) cmp notify\n void $ pushPrio prio s\n writeArray best s 0\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ do\n ix <- readArray ind to\n void $ deletePrio prio ix\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n-- \n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.Ord\nimport qualified Data.Set as Set\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ntype STCmp s = Int->Int->ST s Bool\ntype STNotify s = Int->Int->ST s ()\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray_ bs\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s Int\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s Int\ndeletePrio prio@(Prio val ref arr _) i = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr i\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n GT -> fixDown prio i\n LT -> void $ fixUp prio i\n return x\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s Int\nfixUp _ 0 = return 0\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv >= pv then return i else putPrio prio i px >> go p\n top <- go start\n putPrio prio top x\n return top\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n let mkArray::ST s (STUArray s Int Int)\n mkArray = newArray_ (bounds graph)\n ind <- mkArray\n prio <- newPrio best\n void $ pushPrio prio s\n writeArray best s 0\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ do\n ix <- readArray ind to\n void $ deletePrio prio ix\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.List (unfoldr)\nimport Data.Maybe\nimport qualified Data.Set as Set\n\ntype Cost = Int64\n\ndata Edge = Edge {-# UNPACK #-} !Cost {-# UNPACK #-} !Int deriving Eq\ntype Graph s = STArray s Int EdgeList\ntype SegArr s = STUArray s Int Int\ndata EdgeList = EdgeCons {-# UNPACK #-} !Cost {-# UNPACK #-} !Int !EdgeList | EdgeNil deriving (Eq, Ord)\n\ninstance Ord Edge where Edge cost1 _ `compare` Edge cost2 _ = compare cost1 cost2\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->Graph s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ EdgeCons p b lst\n\n\nbuildSegTree::Int->ST s (SegArr s, Graph s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) EdgeNil\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->Graph s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->ST s (Graph s, SegArr s)\nbuildGraph n queries = do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n return (edge, seg)\n\ndijkstra::Graph s->Int->ST s (STArray s Int (Maybe Cost))\ndijkstra graph s = do\n bs <- getBounds graph\n best <- newArray bs Nothing\n writeArray best s (Just 0)\n let go (Set.minView -> Just (Edge dist num, rest)) = do\n edges <- readArray graph num\n dists <- check dist rest edges\n go dists\n go _ = return ()\n check acc dists (EdgeCons cost to rest) = do\n let price = acc + cost\n current <- readArray best to\n if maybe True (price < ) current then do\n let dists' = maybe dists remove current\n remove u = Set.delete (Edge u to) dists\n writeArray best to (Just price)\n let dists'' = Set.insert (Edge price to) dists'\n check acc dists'' rest\n else check acc dists rest\n check _ dists EdgeNil = return dists\n go $ Set.singleton $ Edge 0 s\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let best = runSTArray $ do\n (graph, segMap) <- buildGraph n qs\n si <- readArray segMap s\n res <- dijkstra graph si\n arr <- newArray_ (1, n)\n forM_ [1..n] $ \\i -> do\n segI <- readArray segMap i\n resI <- readArray res segI\n writeArray arr i resI\n return arr\n putStrLn $ unwords [show $ fromMaybe (-1) $ best ! i | i <- [1..n]]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.Ord\nimport qualified Data.Set as Set\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ntype STCmp s = Int->Int->ST s Bool\ntype STNotify s = Int->Int->ST s ()\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray_ bs\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s Int\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s Int\ndeletePrio prio@(Prio val ref arr idx) x = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n i <- readArray idx x\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n GT -> fixDown prio i\n LT -> void $ fixUp prio i\n return x\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s Int\nfixUp _ 0 = return 0\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv >= pv then return i else putPrio prio i px >> go p\n top <- go start\n putPrio prio top x\n return top\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n prio <- newPrio best\n void $ pushPrio prio s\n writeArray best s 0\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ void $ deletePrio prio to\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.Ord\nimport qualified Data.Set as Set\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ntype STCmp s = Int->Int->ST s Bool\ntype STNotify s = Int->Int->ST s ()\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray_ bs\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s Int\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s Int\ndeletePrio prio@(Prio val ref arr _) i = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr i\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n GT -> fixDown prio i\n LT -> void $ fixUp prio i\n return x\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s Int\nfixUp _ 0 = return 0\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv <= pv then return i else putPrio prio i px >> go p\n top <- go start\n putPrio prio top x\n return top\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n let mkArray::ST s (STUArray s Int Int)\n mkArray = newArray_ (bounds graph)\n ind <- mkArray\n prio <- newPrio best\n void $ pushPrio prio s\n writeArray best s 0\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ do\n ix <- readArray ind to\n void $ deletePrio prio ix\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.List (unfoldr)\nimport Data.Maybe\nimport qualified Data.Set as Set\n\ntype Cost = Int64\n\ndata Edge = Edge {-# UNPACK #-} !Cost {-# UNPACK #-} !Int\ntype Graph s = STArray s Int EdgeList\ntype SegArr s = STUArray s Int Int\ndata EdgeList = EdgeCons {-# UNPACK #-} !Cost {-# UNPACK #-} !Int !EdgeList | EdgeNil deriving (Eq, Ord)\n\ninstance Eq Edge where Edge cost1 _ == Edge cost2 _ = cost1 == cost2\ninstance Ord Edge where Edge cost1 _ `compare` Edge cost2 _ = compare cost1 cost2\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->Graph s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ EdgeCons p b lst\n\n\nbuildSegTree::Int->ST s (SegArr s, Graph s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) EdgeNil\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->Graph s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->ST s (Graph s, SegArr s)\nbuildGraph n queries = do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n return (edge, seg)\n\ndijkstra::Graph s->Int->ST s (STArray s Int (Maybe Cost))\ndijkstra graph s = do\n bs <- getBounds graph\n best <- newArray bs Nothing\n writeArray best s (Just 0)\n let go (Set.minView -> Just (Edge dist num, rest)) = do\n edges <- readArray graph num\n dists <- check dist rest edges\n go dists\n go _ = return ()\n check acc dists (EdgeCons cost to rest) = do\n let price = acc + cost\n current <- readArray best to\n if maybe True (price < ) current then do\n let dists' = maybe dists remove current\n remove u = Set.delete (Edge u to) dists\n writeArray best to (Just price)\n let dists'' = Set.insert (Edge price to) dists'\n check acc dists'' rest\n else check acc dists rest\n check _ dists EdgeNil = return dists\n go $ Set.singleton $ Edge 0 s\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let best = runSTArray $ do\n (graph, segMap) <- buildGraph n qs\n si <- readArray segMap s\n res <- dijkstra graph si\n arr <- newArray_ (1, n)\n forM_ [1..n] $ \\i -> do\n segI <- readArray segMap i\n resI <- readArray res segI\n writeArray arr i resI\n return arr\n putStrLn $ unwords [show $ fromMaybe (-1) $ best ! i | i <- [1..n]]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.Ord\nimport qualified Data.Set as Set\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ntype STCmp s = Int->Int->ST s Bool\ntype STNotify s = Int->Int->ST s ()\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray_ bs\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s Int\npushPrio prio@(Prio _ ref arr notify) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s Int\ndeletePrio prio@(Prio val ref arr idx) i = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr i\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n LT -> fixDown prio i\n GT -> void $ fixUp prio i\n return x\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s Int\nfixUp _ 0 = return 0\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv <= pv then return i else putPrio prio i px >> go p\n top <- go start\n putPrio prio top x\n return top\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n let mkArray::ST s (STUArray s Int Int)\n mkArray = newArray_ (bounds graph)\n ind <- mkArray\n prio <- newPrio best\n void $ pushPrio prio s\n writeArray best s 0\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ do\n ix <- readArray ind to\n void $ deletePrio prio ix\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\nimport Data.STRef\n\ntype Cost = Integer\n\ndata Edge = Edge !Cost !Int deriving (Eq, Ord, Show)\ntype EdgeArr s = STArray s Int [Edge]\ntype Graph = Array Int [Edge]\ntype SegArr s = STUArray s Int Int\n\n\ndata Prio s = Prio (STArray s Int Cost) (STRef s Int) (STUArray s Int Int) (STUArray s Int Int)\n\nputPrio::Prio s->Int->Int->ST s ()\nputPrio (Prio _ _ arr idx) i x = do\n writeArray arr i x\n writeArray idx x i\n\nnewPrio::STArray s Int Cost->ST s (Prio s)\nnewPrio values = do\n bs <- getBounds values\n let n = rangeSize bs\n len <- newSTRef 0\n arr <- newArray_ (0, n)\n idx <- newArray bs (-1)\n return $ Prio values len arr idx\n\npushPrio::Prio s->Int->ST s ()\npushPrio prio@(Prio _ ref _ _) x = do\n n <- readSTRef ref\n writeSTRef ref (n + 1)\n putPrio prio n x\n fixUp prio n\n\ndeletePrio::Prio s->Int->ST s ()\ndeletePrio prio@(Prio val ref arr idx) x = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n i <- readArray idx x\n xv <- readArray val x\n w <- readArray arr (n - 1)\n wv <- readArray val w\n putPrio prio i w\n case compare xv wv of\n EQ -> return ()\n GT -> fixDown prio i\n LT -> void $ fixUp prio i\n\npullPrio::Prio s->ST s Int\npullPrio prio@(Prio _ ref arr _) = do\n n <- readSTRef ref\n writeSTRef ref (n - 1)\n x <- readArray arr 0\n w <- readArray arr (n - 1)\n putPrio prio 0 w\n fixDown prio 0\n return x\n\nnullPrio::Prio s->ST s Bool\nnullPrio (Prio _ ref _ _) = (== 0) <$> readSTRef ref\n\nfixUp::Prio s->Int->ST s ()\nfixUp _ 0 = return ()\nfixUp prio@(Prio val _ arr _) start = do\n x <- readArray arr start\n xv <- readArray val x\n let go 0 = return 0\n go i = do\n let p = quot (i - 1) 2\n px <- readArray arr p\n pv <- readArray val px\n if xv >= pv then return i else putPrio prio i px >> go p\n top <- go start\n unless (top == start) $ putPrio prio top x\n\n\nfixDown::Prio s->Int->ST s ()\nfixDown prio@(Prio val ref arr _) start = do\n size <- readSTRef ref\n x <- readArray arr start\n xv <- readArray val x\n let go i | 2 * i + 1 >= size = return i\n | 2 * i + 2 == size = do\n let c = 2 * i + 1\n cx <- readArray arr c\n cv <- readArray val cx\n if xv <= cv then return i else putPrio prio i cx >> return c\n | otherwise = do\n let l = 2 * i + 1\n r = 2 * i + 2\n lx <- readArray arr l\n rx <- readArray arr r\n lv <- readArray val lx\n rv <- readArray val rx\n let goLeft = putPrio prio i lx >> go l\n goRight = putPrio prio i rx >> go r\n if xv <= lv then\n if xv <= rv then return i else goRight\n else\n if lv <= rv then goLeft else goRight\n bottom <- go start\n unless(bottom == start) $ putPrio prio bottom x\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->EdgeArr s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ Edge p b : lst\n\n\nbuildSegTree::Int->ST s (SegArr s, EdgeArr s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) []\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->EdgeArr s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->(Array Int [Edge], UArray Int Int)\nbuildGraph n queries = runST $ do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n graph <- freeze edge\n segMap <- freeze seg\n return (graph, segMap)\n\ndijkstra::Graph->Int->Array Int Cost\ndijkstra graph s = runSTArray $ do\n best <- newArray (bounds graph) (-1)\n prio <- newPrio best\n writeArray best s 0\n pushPrio prio s\n let go = do\n end <- nullPrio prio\n unless end $ do\n num <- pullPrio prio\n dist <- readArray best num\n let edges = graph ! num\n mapM_ (check dist) edges\n go\n better _ (-1) = True\n better price x = price < x\n check acc (Edge cost to) = do\n let price = acc + cost\n current <- readArray best to\n when (price `better` current) $ do\n when (current /= -1) $ deletePrio prio to\n writeArray best to price\n void $ pushPrio prio to\n go\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let (graph, segMap) = buildGraph n qs\n -- forM_ (assocs graph) $ \\(i, es) -> putStrLn $ show i <> \": \" <> show es\n let best = dijkstra graph $ segMap ! s\n putStrLn $ unwords [show $ best ! (segMap ! i) | i <- [1..n]]\n--\n-- validatePrio::Prio s->ST s Bool\n-- validatePrio (Prio cmp ref arr _) = do\n-- size <- readSTRef ref\n-- let go i | 2 *i + 1>= size = return True\n-- | 2* i + 2 == size = do\n-- x <- readArray arr i\n-- c <- readArray arr (2 * i + 1)\n-- res <- cmp x c\n-- unless res $ traceShowM $ show (x, c)\n-- return res\n-- | otherwise = do\n-- x <- readArray arr i\n-- l <- readArray arr (2 * i + 1)\n-- r <- readArray arr (2 * i + 2)\n-- vl <- cmp x l\n-- vr <- cmp x r\n-- unless vl $ traceShowM $ show (x, l)\n-- unless vr $ traceShowM $ show (x, r)\n-- vvl <- go (2 * i + 1)\n-- vvr <- go (2 * i + 2)\n-- return $ vl && vr && vvl && vvr\n-- go 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap as IntMap\nimport Data.IntMap.Strict (IntMap)\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List (unfoldr)\nimport Data.Maybe\n\n\ntype Cost = Int64\n\ndata Edge = Edge {-# UNPACK #-} !Cost {-# UNPACK #-} !Int deriving (Eq, Ord, Show)\ntype Graph s = STArray s Int EdgeList\ntype SegArr s = STUArray s Int Int\ndata EdgeList = EdgeCons {-# UNPACK #-} !Cost {-# UNPACK #-} !Int !EdgeList | EdgeNil deriving (Eq, Ord)\n\ntype CostQue = IntMap (IntMap IntSet)\n\nbase::Cost\nbase = shiftL 1 32\n\nmask::Cost\nmask = base - 1\n\nqueInit::Int->CostQue\nqueInit s = IntMap.singleton 0 $ IntMap.singleton 0 $ IntSet.singleton s\n\ncomb::Int->Int->Cost\ncomb h l= (fromIntegral h `shiftL` 32) .|. fromIntegral l\n\nsplit::Cost->(# Int, Int #)\nsplit n = let x = fromIntegral $ n `shiftR` 32\n y = fromIntegral $ n .&. mask\n in (# x, y #)\n\nquePull::CostQue->Maybe (Edge, CostQue)\nquePull q = do\n ((hk, hv), h) <- IntMap.minViewWithKey q\n ((lk, lv), l) <- IntMap.minViewWithKey hv\n (i, s) <- IntSet.minView lv\n let l' = if IntSet.null s then l else IntMap.insert lk s l\n let h' = if IntMap.null l' then h else IntMap.insert hk l' h\n return (Edge (comb hk lk) i, h')\n\nquePush::Edge->CostQue->CostQue\nquePush (Edge cost i ) q =\n let (# x, y #) = split cost\n l = fromMaybe IntMap.empty $ IntMap.lookup x q\n s = fromMaybe IntSet.empty $ IntMap.lookup y l\n s' = IntSet.insert i s\n l' = IntMap.insert y s' l\n in IntMap.insert x l' q\n\nqueDel::Edge->CostQue->CostQue\nqueDel (Edge cost i) q =\n let (# x, y #) = split cost\n high l = if IntMap.null l' then Nothing else Just l' where\n l' = IntMap.update low y l\n low s = if IntSet.null s' then Nothing else Just s' where\n s' = IntSet.delete i s\n in IntMap.update high x q\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\naddEdge::Int->Int->Cost->Graph s->ST s ()\naddEdge a b p arr = do\n lst <- readArray arr a\n writeArray arr a $ EdgeCons p b lst\n\n\nbuildSegTree::Int->ST s (SegArr s, Graph s)\nbuildSegTree n = do\n edges <- newArray (-maxIdx, maxIdx) EdgeNil\n segs <- newArray_ (0, n)\n let link l r i j = do\n addEdge i j 0 edges\n addEdge (-j) (-i) 0 edges\n go l r j\n go l r idx | l+1>=r = do\n writeArray segs r idx\n addEdge idx (-idx) 0 edges\n | otherwise = do\n let mid = quot (l + r + 1) 2\n link l mid idx (2*idx)\n link mid r idx (2*idx + 1)\n go 0 n 1\n return (segs, edges)\n where\n calcMax l r u | l + 1 >= r = u\n | otherwise = let m = quot (l+r+1) 2\n in calcMax l m (2*u) `max` calcMax m r (2*u+1)\n maxIdx = calcMax 0 n 1\n\nmultiEdge::Bool->Int->Int->Int->Int->Cost->SegArr s->Graph s->ST s ()\nmultiEdge inverse n start endL endR c seg edge = go 0 n 1 where\n go l r idx | l >= endR || r < endL = return () -- fully outside\n | l >= endL - 1 && r <= endR = do -- fully inside\n u <- readArray seg start\n unless inverse $ addEdge (-u) idx c edge\n when inverse $ addEdge (-idx) u c edge\n | otherwise = do\n let mid = quot (l + r + 1) 2\n go l mid (idx*2)\n go mid r (idx*2 + 1)\n\nbuildGraph::Int->[[Int]]->ST s (Graph s, SegArr s)\nbuildGraph n queries = do\n (seg, edge) <- buildSegTree n\n let runQuery [1, v, u, w] = do\n f <- readArray seg v\n t <- readArray seg u\n addEdge (- f) t (fromIntegral w) edge\n runQuery [2, v, l, r, w] = multiEdge False n v l r (fromIntegral w) seg edge\n runQuery [3, v, l, r, w] = multiEdge True n v l r (fromIntegral w) seg edge\n runQuery _ = return ()\n forM_ queries runQuery\n return (edge, seg)\n\ndijkstra::Graph s->Int->ST s (STArray s Int (Maybe Cost))\ndijkstra graph s = do\n bs <- getBounds graph\n best <- newArray bs Nothing\n writeArray best s (Just 0)\n let go (quePull -> Just (Edge dist num, rest)) = do\n edges <- readArray graph num\n dists <- check dist rest edges\n go dists\n go _ = return ()\n check acc dists (EdgeCons cost to rest) = do\n let price = acc + cost\n current <- readArray best to\n if maybe True (price < ) current then do\n let dists' = maybe dists remove current\n remove u = queDel (Edge u to) dists\n writeArray best to (Just price)\n let dists'' = quePush (Edge price to) dists'\n check acc dists'' rest\n else check acc dists rest\n check _ dists EdgeNil = return dists\n go $ queInit s\n return best\n\nmain :: IO ()\nmain = do\n [n,q,s] <- getInts\n qs <- replicateM q getInts\n let best = runSTArray $ do\n (graph, segMap) <- buildGraph n qs\n si <- readArray segMap s\n res <- dijkstra graph si\n arr <- newArray_ (1, n)\n forM_ [1..n] $ \\i -> do\n segI <- readArray segMap i\n resI <- readArray res segI\n writeArray arr i resI\n return arr\n putStrLn $ unwords [show $ fromMaybe (-1) $ best ! i | i <- [1..n]]\n"}], "src_uid": "b22f5f4a5d15030fbf7756f81caafb3c"} {"source_code": "main = getLine >> getContents >>= putStrLn . solve . map (read.head.words) . lines\n\nsolve xs\n | judge xs = \"No\"\n | otherwise = \"Yes\"\n where judge = (>1) . minimum . foldl (\\[p,n] x -> if x > 0 then [p+1,n] else [p,n+1]) [0,0]\n", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Bool\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = (bool \"No\" \"Yes\" . solve) `fmap` (flip replicateM (liftM2 (,) poi poi) =<< poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = (\\(ls, rs) -> case (ls, rs) of { ([_], _) -> True; (_, [_]) -> True; ([], _) -> True; (_, []) -> True; _ -> False }) . partition ((< 0) . fst)"}, {"source_code": "import Data.List\n\nf::[String]->[Int]\nf []=[]\nf (x:xs)=let (a:b:[])=map read (words x)::[Int]\n in (if a>0 then 1 else (-1)):f xs\n\n\nmain = do\n e<-getLine\n es<-getContents\n let n=read e::Int\n xs=lines es\n zs=sort $ f xs\n t1=tail $ reverse zs\n t2=tail zs\n putStrLn $ if (minimum t2)==(maximum t2) || (minimum t1)==(maximum t1) then \"Yes\" else \"No\""}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\n\nmain = do\n\tn<-read <$> getLine ::IO Int\n\ta<-map (read.head.words) <$> replicateM n getLine:: IO [Int]\n\tlet p = length $ filter (>0) a\n\tputStrLn $ if (min p (n-p)) >1 then \"No\" else \"Yes\"\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n points <- partition (<0) . map (head . map (read :: String -> Int) . words) <$> replicateM n getLine\n putStrLn $ if length (fst points) < 2 || length (snd points) < 2 then \"Yes\" else \"No\""}, {"source_code": "groupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\nmain = interact $ unlines . parse . lines\n\nparse (_:ops') = sol ops\n where\n ops = map (fn . words) ops'\n fn :: [String] -> Int\n fn [b, e] = read b\n\nsol pts = [ if res then \"Yes\" else \"No\" ]\n where\n res = cnt+1 >= length pts || cnt <= 1\n cnt = length $ filter (<0) pts\n"}], "negative_code": [], "src_uid": "cf7bf89a6038586b69d3b8021cee0b27"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[n] <- getInts 1\n let\n query p q = string7 \"? \" <> putInts (replicate (n - 1) q ++ [p])\n loQueries = mconcat [query s n | s <- [1 .. n-1]]\n hiQueries = mconcat [query s 1 | s <- [2 .. n]]\n loNums <- getInts (n - 1)\n hiNums <- getInts (n - 1)\n let\n pinv = filter (/= 0) loNums ++ [n] ++ filter (/= 0) hiNums\n p :: UArray Int Int\n p = array (1, n) $ zip pinv [1..]\n pure $ loQueries <> hiQueries <> flush <> string7 \"! \" <> putInts (elems p)\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "-- Clyring's code tweaked\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\n\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SO\r\nmainFun = do\r\n ~[n] <- getInts 1\r\n let\r\n query p q = string7 \"? \" <> putInts (replicate (n - 1) q ++ [p])\r\n loQueries = mconcat [query s n | s <- [n-1,n-2 .. 1]]\r\n hiQueries = mconcat [query s 1 | s <- [2 .. n]]\r\n loNums <- getInts (n - 1)\r\n hiNums <- getInts (n - 1)\r\n let\r\n pinv = reverse (takeWhile (/= 0) loNums) ++ [n] ++ takeWhile (/= 0) hiNums\r\n p :: UArray Int Int\r\n p = array (1, n) $ zip pinv [1..]\r\n pure $ loQueries <> hiQueries <> flush <> string7 \"! \" <> putInts (elems p)\r\n\r\ntype SP = State [P.ByteString]\r\ntype SO = SP Builder\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "2cb5fe3fdff43e104729866cdfa73102"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Monad (replicateM_)\nimport Data.Maybe (fromMaybe)\n\nmain = readLn >>= flip replicateM_ ioSolve\n\nioSolve :: IO ()\nioSolve = getLine >>= maybe (putStrLn \"NO\") (\\x -> putStrLn \"YES\" >> (putStrLn . unwords . map show) x) .\n (\\[x,y] -> solve x y) . map read . words\n\nsolve :: Int -> Int -> Maybe [Int]\nsolve n k | odd n && even k = Nothing\n | odd n == odd k = let a = n - (k - 1) in if a > 0 then Just $ a : replicate (k-1) 1 else Nothing\n | even n && odd k = let a = n - 2*(k - 1) in if a > 0 then Just $ a : replicate (k-1) 2 else Nothing", "positive_code": [{"source_code": "\n\nsolve :: Int -> Int -> [Int]\nsolve n k\n | even k && odd n = []\n | even k && even n && k > n = []\n | even k && even n = (n-k+1):replicate (k-1) 1\n | odd k && even n && 2*k > n = []\n | odd k && even n = (n-2*k+2):replicate (k-1) 2\n | odd k && odd k && k > n = []\n | otherwise = (n-k+1):replicate (k-1) 1\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readNums\n let ans = solve n k\n case ans of\n [] -> putStrLn \"NO\"\n _ -> do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show ans\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}, {"source_code": "main :: IO ()\nmain = do\n getLine\n ans <- map (solve . map read . words) . lines <$> getContents\n mapM_ putStrLn ans\n\nsolve :: [Int] -> String\nsolve [x,y]\n | odd x && even y = \"NO\"\n | even x && odd y = case x >= (2 * y) of\n False -> \"NO\"\n _ -> let twos = y - 1 in\n \"YES\\n\" ++ (unwords $ (map show $ replicate twos 2) ++ [show $ x - (2* twos)])\n | otherwise = case x>= y of\n False -> \"NO\"\n _ -> let ones = y - 1 in -- x odd y odd or x even y even we can use 1's\n \"YES\\n\" ++ (unwords $ (map show $ replicate ones 1) ++ [show $ x - ones])\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1 >>> map (words >>> map read >>> solve >>> format) >>> concat >>> unlines\n\nsolve :: [Int] -> Maybe [Int]\nsolve [n,k]\n | even k && odd n = Nothing\n | odd n || (even n && even k) = solveOdd k n\n | otherwise = solveEven k n\n\nsolveOdd k n\n | n < k = Nothing\n | otherwise = Just $ (n - k + 1) : replicate (k-1) 1\n\nsolveEven k n\n | n < 2*k = Nothing\n | otherwise = Just $ (n - 2*(k-1)) : replicate (k-1) 2\n\nformat Nothing = [\"NO\"]\nformat (Just xs) = [\"YES\", unwords (map show xs)]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Monad (replicateM_)\nimport Data.Maybe (fromMaybe)\n\nmain = readLn >>= flip replicateM_ ioSolve\n\nioSolve :: IO ()\nioSolve = getLine >>= maybe (putStrLn \"NO\") (\\x -> putStrLn \"YES\" >> (putStrLn . unwords . map show) x) .\n (\\[x,y] -> solve x y) . map read . words\n\nsolve :: Int -> Int -> Maybe [Int]\nsolve n k | odd n && even k = Nothing\n | odd n == odd k = let a = n - (k - 1) in if a > 0 then Just $ a : replicate (k-1) 1 else Nothing\n | even n && odd k = let a = n - 2*(k - 1) in if a > 0 then Just $ a : replicate ((k-1) `div` 2) 2 else Nothing"}, {"source_code": "\n\nsolve :: Int -> Int -> [Int]\nsolve n k\n | even k && odd n = []\n | even k && even n && k > n = []\n | even k && even n = (n-k+1):replicate (k-1) 1\n | odd k && even n && 2*k > n = []\n | odd k && even n = (n-2*k+1):replicate (k-1) 2\n | odd k && odd k && k > n = []\n | otherwise = (n-k+1):replicate (k-1) 1\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readNums\n let ans = solve n k\n case ans of\n [] -> putStrLn \"NO\"\n _ -> do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show ans\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "src_uid": "6b94dcd088b0328966b54acefb5c6d22"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\nimport Data.Maybe\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = IntMap.fromListWith (+) $ zip xs [1,1..]\n if k == 0 then\n print $ sum $ (\\x -> x *~ (x - 1) `quot` 2) <$> IntMap.elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- IntMap.toList xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n cy <- maybeToList $ IntMap.lookup y xm\n return $ cx *~ cy\n where (*~)::Int->Int->Int64\n x *~ y = fromIntegral x * fromIntegral y\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = array (0, top) $ IntMap.toList $ IntMap.fromListWith (+) $ zip xs [1,1..] :: UArray Int Int\n if k == 0 then\n print $ sum $ (\\x -> x *~ (x - 1) `quot` 2) <$> elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- assocs xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n let cy = xm ! y\n return $ cx *~ cy\n where (*~)::Int->Int->Int64\n x *~ y = fromIntegral x * fromIntegral y\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\nimport Data.Maybe\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = IntMap.fromListWith (+) $ zip xs [1,1..]\n if k == 0 then\n print $ sum $ (\\x -> x *~ (x - 1) `quot` 2) <$> IntMap.elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- IntMap.toList xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n let cy = fromMaybe 0 $ IntMap.lookup y xm\n return $ cx *~ cy\n where (*~)::Int->Int->Int64\n x *~ y = fromIntegral x * fromIntegral y\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let nums = zip xs [1,1..] ++ zip [0..top] [0,0..]\n xm = array (0, top) $ IntMap.toList $ IntMap.fromListWith (+) nums :: Array Int Integer\n if k == 0 then\n print $ sum $ (\\x -> x * (x - 1) `quot` 2) <$> elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- assocs xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n let cy = xm ! y\n return $ cx * cy\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\nimport Data.Maybe\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = IntMap.fromListWith (+) $ zip xs [1,1..]\n if k == 0 then\n print $ sum $ (\\x -> x * (x - 1) `quot` 2) <$> IntMap.elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- IntMap.toList xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n let cy = fromMaybe 0 $ IntMap.lookup y xm\n return $ cx * cy\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = array (0, top) $ IntMap.toList $ IntMap.fromListWith (+) $ zip xs [1,1..] :: UArray Int Int64\n if k == 0 then\n print $ sum $ (\\x -> x * (x - 1) `quot` 2) <$> elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- assocs xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n let cy = xm ! y\n return $ cx * cy\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = array (0, top) $ IntMap.toList $ IntMap.fromListWith (+) $ zip xs [1,1..] :: UArray Int Int\n if k == 0 then\n print $ sum $ (\\x -> x * (x - 1) `quot` 2) <$> elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n print $ sum $ do\n (x, cx) <- assocs xm\n guard $ cx > 0\n mut <- mutators\n let y = xor x mut\n guard $ x > y\n let cy = xm ! y\n return $ fromIntegral cx * fromIntegral cy :: [Int64]\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.List (unfoldr)\nimport Control.Monad\nimport Control.Applicative\n\ngetInts::IO [Int]\ngetInts = unfoldr readOne <$> BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.dropWhile (== ' ') s')\n\nmain :: IO ()\nmain = do\n let top = 2^(14 :: Int) - 1\n [_, k] <- getInts\n xs <- getInts\n let xm = array (0, top) $ IntMap.toList $ IntMap.fromListWith (+) $ zip xs [1,1..] :: UArray Int Int\n if k == 0 then\n print $ sum $ (\\x -> x * (x - 1) `quot` 2) <$> elems xm\n else do\n let mutators = filter ((k==).popCount) [0..top] :: [Int]\n let res = sum $ do\n (x, cx) <- assocs xm\n guard $ cx > 0\n mut <- mutators\n let cy = xm ! xor x mut\n return $ cx * cy\n print $ res `quot` 2\n"}], "src_uid": "7b7623dfde563b383cdc2364c81a7539"} {"source_code": "import Control.Monad\n\nisGood :: Int -> Bool\nisGood x = ((rem x 3) /= 0) && ((last $ show x) /= '3')\n\nsolve k = (filter isGood (iterate(+1) 1)) !! (k - 1) \n\n-- main :: IO ()\nmain = do\n t <- readLn :: IO Int\n inputs <- replicateM (t) (readLn :: IO Int)\n\n let answers = map solve inputs\n\n mapM_ putStrLn (map show answers)\n", "positive_code": [{"source_code": "main=interact$unlines.map(show.(!!)[x+3|x<-[-4..],mod x 3*mod x 10/=0].read).tail.lines"}, {"source_code": "main=interact$unlines.map(show.((0:[x|x<-[1..],x`mod`3/=0,x`mod`10/=3])!!).read).tail.lines"}, {"source_code": "import Control.Monad\r\n\r\n\r\nisPolycarpInteger :: Integer -> Bool\r\nisPolycarpInteger x = (x `mod` 3 /= 0) && (x `mod` 10 /= 3)\r\n\r\n\r\ngetPolycarpIntegerByIndex :: Integer -> Integer\r\ngetPolycarpIntegerByIndex index = polycarp_sequence !! (fromIntegral index)\r\n where polycarp_sequence = filter isPolycarpInteger [1..]\r\n\r\n\r\nmain :: IO()\r\nmain = do\r\n tests_n_input <- getLine\r\n tests_inputs <- replicateM (read tests_n_input) getLine\r\n let required_indices = map (\\x -> (read x) - 1) tests_inputs\r\n let results = map getPolycarpIntegerByIndex required_indices\r\n mapM_ print results\r\n"}, {"source_code": "--ghc 8.6.3\r\n\r\nreadLnInt :: IO (Int)\r\nreadLnInt = do\r\n input <- getLine\r\n return (read input)\r\n\r\ngetLns' :: Int -> IO([String])\r\ngetLns' n\r\n | n == 0 = return []\r\n | otherwise = do\r\n ln <- getLine\r\n lns <- getLns' (n - 1)\r\n return (ln:lns)\r\n\r\ngetLns :: Read a => Int -> IO([a])\r\ngetLns n = fmap (fmap read) $ getLns' n\r\n\r\n\r\nans = [x | x <- [1..],\r\n mod x 3 /= 0,\r\n mod x 10 /= 3]\r\n\r\nmain = do\r\n n <- readLnInt\r\n qs <- getLns n\r\n mapM_ print $ map (ans !!) (map (subtract 1) qs)"}, {"source_code": "kthNum 1 i = do\r\n print(i)\r\n\r\nkthNum k i = do\r\n let newI = i+1\r\n let newK = if (newI `mod` 3 /= 0) && (newI `mod` 10 /= 3) then k-1 else k\r\n kthNum newK newI\r\n\r\ndoTask 0 = return ()\r\n \r\ndoTask t = do\r\n input <- getLine\r\n let k = read input :: Int\r\n kthNum k 1\r\n doTask (t-1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n input <- getLine\r\n let t = read input :: Int\r\n doTask t"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: Int -> Int\ncalc k =\n (filter (\\x ->\n (x `mod` 3 /= 0) && (x `mod` 10 /= 3)\n ) [1..]) !! (k-1)\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let k = read line :: Int\n print $ calc k\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t readLn :: IO [Int]\n\n (putStr . unlines . map (show . solve)) tcs\n\nsolve k = xs !! (k-1)\n where\n xs = [x | x <-[1..], x `mod` 3 /= 0 && x `mod` 10 /= 3] :: [Int]\n"}, {"source_code": "nTh :: Int -> Int\nnTh n = iter 1 1 \n where\n iter :: Int -> Int -> Int\n iter a b\n | b `mod` 3 == 0 || b `mod` 10 == 3 = iter a (b + 1)\n | a == n = b\n | otherwise = iter (a + 1) (b + 1)\n\nloop :: Int -> IO()\nloop 0 = return ()\nloop n = do\n number <- readLn :: IO Int\n print (nTh number)\n loop $ n - 1\n\nmain :: IO()\nmain = do\n input <- getLine\n let n = read input :: Int\n loop n\n\n\t\t \t\t \t\t\t \t \t\t \t\t\t\t\t\t\t\t\t \t"}, {"source_code": "import Data.Array\nz = listArray (1,1000) $ filter (\\x -> x `mod` 3 /= 0 && x `mod` 10 /= 3) [1..]\nmain = interact $ unlines . map (show . ((!) z) . (read :: String -> Int)) . tail . lines \n"}, {"source_code": "main = do\n t <- read <$> getLine :: IO Int\n mapM_ solve [1..t]\n\nsolve :: Int -> IO ()\nsolve _ = do\n k <- read <$> getLine :: IO Int\n print $ (filter (\\x -> x `mod` 3 /= 0 && x `mod` 10 /= 3) [1..]) !! (k - 1)"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n \r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = Int\r\ntype OutType = Int\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n \r\nsolve :: InType -> OutType\r\nsolve x = liked !! (x - 1)\r\n where liked = [ y\r\n | y <- [1 .. ]\r\n , y `mod` 3 /= 0\r\n , y `mod` 10 /= 3\r\n ]\r\n \r\nreceive :: [String] -> InType\r\nreceive [s] = read s :: Int\r\nreceive _ = error \"unexpected input\"\r\n \r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines\r\n where showb True = \"YES\"\r\n showb False = \"NO\"\r\n\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad ( replicateM_ )\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t\r\n $ do\r\n getLine >>= print . solve . read\r\n\r\nsolve :: Int -> Int\r\nsolve k = helper 0 k\r\n where\r\n helper itr 0 = itr\r\n helper itr k = if (itr + 1) `rem` 3 == 0 || (itr + 1) `rem` 10 == 3\r\n then helper (itr + 1) k\r\n else helper (itr + 1) (k - 1)\r\n{-\r\n>>>solve 1000\r\n1666\r\n\r\n-}\r\n"}], "negative_code": [{"source_code": "--ghc 8.6.3\r\n\r\nreadLnInt :: IO (Int)\r\nreadLnInt = do\r\n input <- getLine\r\n return (read input)\r\n\r\ngetLns' :: Int -> IO([String])\r\ngetLns' n\r\n | n == 0 = return []\r\n | otherwise = do\r\n ln <- getLine\r\n lns <- getLns' (n - 1)\r\n return (ln:lns)\r\n\r\ngetLns :: Read a => Int -> IO([a])\r\ngetLns n = fmap (fmap read) $ getLns' n\r\n\r\n\r\nans = [x | x <- [1..],\r\n mod x 3 /= 0,\r\n mod x 10 /= 3]\r\n\r\nmain = do\r\n n <- readLnInt\r\n qs <- (getLns n) :: IO([Int])\r\n print $ map (\\x -> ans !! (x - 1)) qs"}], "src_uid": "c37604d5d833a567ff284d7ce5eda059"} {"source_code": "import Data.List\n\ngetInt :: IO Int\ngetInt = do\n nStr <- getLine\n return (read nStr)\n \ngetStr :: IO String\ngetStr = do\n str <- getLine\n return str\n \ngetStrs:: Int -> IO [String]\ngetStrs 0 = return []\ngetStrs n = do\n x <- getStr\n xs <- getStrs (n-1)\n return (x:xs)\n\nstrsOf n = sequence $ take n $ repeat ['a'..'z']\ninfStrs = concat [strsOf x | x <- [1..]]\n\nsolve strs =\n let isValid x = not $ any (isInfixOf x) strs in\n head (filter isValid infStrs) \n \nmain = do\n n <- getInt\n strs <- getStrs n\n putStrLn (solve strs)\n", "positive_code": [{"source_code": "import Data.List\n\nmain = interact $ solve . words\n\nsolve :: [String] -> String\nsolve (_ : ts) = head $ concatMap (comp' $ dropWhile null $ sort $ concatMap tails ts) newTitles\n-- solve (_ : ts) = unlines $ dropWhile null $ sort $ concatMap tails ts\n\ncomp' :: [String] -> (Int, [String]) -> [String]\ncomp' s (i, t) = comp (map (take i) $ filter ((>= i) . length) s) t\n where\n comp _ [] = []\n comp [] (n : ns) = [n]\n comp (o : os) (n : ns)\n | n < o = [n]\n | otherwise = comp (dropWhile (<= n) $ o : os) ns\n\nnewTitles :: [(Int, [String])]\nnewTitles = tail $ zip [0..] $ iterate f [\"\"]\n where\n f xs = [c : x | c <- ['a'..'z'], x <- xs]\n"}, {"source_code": "module Main(build,find, main, tails) where\n\nimport Control.Monad\nimport Data.Array\nimport Data.Char (ord, chr)\n\nreadi :: [Char] -> Int\nreadi x = read x :: Int\n\ntails :: [Char] -> [[Char]]\ntails [] = []\n--tails (x:xs) = [[x]] ++ (map ([x]++) (tails xs))\ntails xs = [xs] ++ (tails (tail xs))\n\ndata Node = Node (Array Int Node) | Null\n\tderiving (Show)\n\ninstance Eq Node where\n\tNull == Null = True\n\tNull == _ = False\n\t_ == Null = False\n\t(Node a1) == (Node a2) = a1 == a2\n\ndecode x = (ord x) - (ord 'a') + 1\nencode x = chr (x - 1 + (ord 'a'))\n\nbuild :: [[Char]] -> Node\nbuild [] = Null\nbuild ss = Node $ array (1, 26) [(x, call x) | x <- [1..26]]\n\twhere\n\t\tfl ss = filter (/=[]) ss\n\t\tcall x = build $ scanF (fl ss) (encode x)\n\t\tscanF :: [[Char]] -> Char -> [[Char]]\n\t\tscanF ss x\n\t\t\t| ss == [] = []\n\t\t\t| head w == x = (tail w):(scanF st x) \n\t\t\t| otherwise = (scanF st x)\n\t\t\t\twhere\n\t\t\t\t\tw = head ss\n\t\t\t\t\tst = tail ss\n\nmerge = foldl (++) []\n\nfind :: Node -> [Char]\nfind v = minimum $ filtmin $ leafs v\n\twhere\n\t\tfiltmin ss = filter ((==mm) . length) ss\n\t\t\twhere\n\t\t\t\tmm = minimum $ map (length) ss\n\t\tleafs :: Node -> [[Char]]\n\t\tleafs Null = [[]]\n\t\tleafs (Node arr) = merge [map ([c]++) (acc c) | c <- ['a'..'z']]\n\t\t\twhere\n\t\t\t\tacc :: Char -> [[Char]]\n\t\t\t\tacc c = leafs (arr ! (decode c))\nextract (Node arr) = arr\n\nfind2 :: Node -> [Char]\nfind2 v = reverse $ firstR $ iterate (extendl) (Left [(\"\", v)])\n\twhere\n\t\tfirstR (x:xs) = case x of\n\t\t\t\t\t\t\tLeft x -> firstR xs\n\t\t\t\t\t\t\tRight y -> y\n\t\textendl (Left l) = extend l\n\t\textend ls = if ffml == [] then Left ml else Right $ fst $ head $ ffml\n\t\t\twhere \n\t\t\t\tffml = filter (ff) ml\n\t\t\t\tml = mul ls\n\t\t\t\tff (_, Null) = True\n\t\t\t\tff bb = False\n\t\tmul xs = merge [map (\\(a,b) -> (([encode a]++rs), b)) (assocs n) | (rs, Node n) <- xs]\n\nmain = do\n\tn <- readi `liftM` getLine\n\twrd <- forM [1..n] (\\x->getLine) \n\t--putStrLn $ show $ merge (map (tails) wrd)\n\tputStr $ find2 $ build $ merge (map (tails) wrd)\n"}, {"source_code": "\nimport Control.Monad (replicateM)\nimport Data.List (nub)\n\nsolve :: [String] -> String\nsolve ss\n | length chars == 26 = aa\n | otherwise = a\n where\n chars = nub $ concat ss\n a = [head $ filter (not . flip elem chars) ['a' .. 'z']]\n pairs = nub $ concat $ map (\\s -> zipWith (\\a b -> [a,b]) s (tail s)) ss\n aa = head [[a,b] | a <- ['a'..'z'], b <- ['a'..'z'], not (elem [a,b] pairs)]\n\nmain :: IO ()\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n putStrLn $ solve ss\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >> interact f\ncs = ['a'..'z']\nf x | Just res <- find p $ replicateM 1 cs ++ replicateM 2 cs = res\n where\n p y = not.or $ map (isPrefixOf y) $ tails x"}], "negative_code": [{"source_code": "import Data.List\n\ngetInt :: IO Int\ngetInt = do\n nStr <- getLine\n return (read nStr)\n \ngetStr :: IO String\ngetStr = do\n str <- getLine\n return str\n \ngetStrs:: Int -> IO [String]\ngetStrs 0 = return []\ngetStrs n = do\n x <- getStr\n xs <- getStrs (n-1)\n return (x:xs)\n\naToZ = [[c] | c <- ['a'..'z']]\n \ninfStrs = aToZ ++ map concat (sequence [aToZ, infStrs])\n\nsolve strs =\n let subs = concat (map subsequences strs) in\n head (filter (`notElem` subs) infStrs) \n \nmain = do\n n <- getInt\n strs <- getStrs n\n print (solve strs)\n"}, {"source_code": "import Data.List\n\ngetInt :: IO Int\ngetInt = do\n nStr <- getLine\n return (read nStr)\n \ngetStr :: IO String\ngetStr = do\n str <- getLine\n return str\n \ngetStrs:: Int -> IO [String]\ngetStrs 0 = return []\ngetStrs n = do\n x <- getStr\n xs <- getStrs (n-1)\n return (x:xs)\n\naToZ = [[c] | c <- ['a'..'z']]\n \ninfStrs = aToZ ++ map concat (sequence [aToZ, infStrs])\n\nsolve strs =\n let subs = concat (map subsequences strs) in\n head (filter (`notElem` subs) infStrs) \n \nmain = do\n n <- getInt\n strs <- getStrs n\n print (\"\\\"\" ++ solve strs ++ \"\\\"\")\n"}, {"source_code": "import Data.List\n\ngetInt :: IO Int\ngetInt = do\n nStr <- getLine\n return (read nStr)\n \ngetStr :: IO String\ngetStr = do\n str <- getLine\n return str\n \ngetStrs:: Int -> IO [String]\ngetStrs 0 = return []\ngetStrs n = do\n x <- getStr\n xs <- getStrs (n-1)\n return (x:xs)\n\naToZ = [[c] | c <- ['a'..'z']]\n \ninfStrs = aToZ ++ map concat (sequence [aToZ, infStrs])\n\nsolve strs =\n let isValid x = not $ any (isInfixOf x) strs in\n head (filter isValid infStrs) \n \nmain = do\n n <- getInt\n strs <- getStrs n\n putStrLn (solve strs)\n"}, {"source_code": "import Data.List\n\ngetInt :: IO Int\ngetInt = do\n nStr <- getLine\n return (read nStr)\n \ngetStr :: IO String\ngetStr = do\n str <- getLine\n return str\n \ngetStrs:: Int -> IO [String]\ngetStrs 0 = return []\ngetStrs n = do\n x <- getStr\n xs <- getStrs (n-1)\n return (x:xs)\n\naToZ = [[c] | c <- ['a'..'z']]\n \ninfStrs = aToZ ++ map concat (sequence [aToZ, infStrs])\n\nsolve strs =\n let subs = concat (map subsequences strs) in\n head (filter (`notElem` subs) infStrs) \n \nmain = do\n n <- getInt\n strs <- getStrs n\n putStrLn (\"\\\"\" ++ solve strs ++ \"\\\"\")\n"}], "src_uid": "58fa5c2f270e2c34e8f9671d5ffdb9c8"} {"source_code": "module Main (main) where\n\nimport qualified Data.Array as Array\nimport Data.Array (Array, (!))\n\npairs :: [a] -> [(a, a)]\npairs (x:y:xs) = (x, y) : pairs xs\npairs _ = []\n\nsolve :: (String, String) -> Int\nsolve (alphabet, letters) =\n let arr = Array.array ('a', 'z') (zip alphabet [1..])\n in sum (zipWith (\\a b -> abs (arr ! a - arr ! b)) letters (tail letters))\n\ngo :: String -> String\ngo input =\n let ls :: [String]\n ls = lines input\n x :: String\n xs :: [String]\n (x:xs) = ls\n n :: Int\n n = read x\n ys :: [(String, String)]\n ys = pairs xs\n in unlines $ fmap (show . solve) ys\n\nmain :: IO ()\nmain = interact go\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\ncharFind (s:ss) charToFind = if s == charToFind then 0\n else 1 + charFind ss charToFind\n\nsolve keyMap (c:cs) = if null cs then 0\n else abs(charFind keyMap c-charFind keyMap (head cs)) + solve keyMap cs\n\nrun 0 = do return 0\nrun count = do\n keyMap <- getLine\n textToType <- getLine\n print(solve keyMap textToType)\n run (count-1)\nmain = do\n n <- getLine\n let n' = read n\n run n'\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (elemIndex)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n s <- getLine\n t <- getLine\n let indices = map (fromJust . (`elemIndex` s)) t\n moves = map abs $ zipWith (-) indices $ tail indices\n print $ sum moves\n"}, {"source_code": "import Data.Char\nimport qualified Data.Map as M\nimport System.IO\n\nmerge :: [a] -> [b] -> [(a, b)]\nmerge [] _ = []\nmerge _ [] = []\nmerge (x : xs) (y : ys) = (x, y) : merge xs ys\n\ndistance' :: [Int] -> Int\ndistance' [] = 0\ndistance' [x] = 0\ndistance' (x : y : xs) = abs (y - x) + distance' (y : xs)\n\ndistance :: String -> String -> Int\ndistance keyboard w\n | lenw == 1 = 0\n | otherwise = distance' $ map (km M.!) w\n where\n lenw = length w\n km = M.fromList $ merge keyboard [1 ..]\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve (k : w : xs) = ((show $ distance k w) : []) ++ solve xs\n\nmain :: IO ()\nmain = do\n inputs <- getContents\n let lns = lines inputs\n --print lns\n putStr $ unlines $ solve $ tail lns\n"}, {"source_code": "import qualified Data.Map as M\r\nimport Data.Maybe\r\n\r\nmain = interact solve\r\nsolve = unlines . s . tail . lines\r\ns (a:b:xs) = (show (cnt a b)):(s xs)\r\ns _ = []\r\ncnt k w = let m = M.fromList $ zip k [1..]\r\n s = mapMaybe (flip M.lookup m) w\r\n in sum $ zipWith (\\x y->abs(x-y)) s (tail s)\r\n"}, {"source_code": "import Prelude\r\n\r\ntest :: Int -> IO ()\r\ntest 0 = putStrLn \"\"\r\ntest n = do\r\n alphabets <- getLine\r\n s <- getLine\r\n let first = findIndex alphabets (head s) 0\r\n let ans = solve alphabets s first\r\n print ans\r\n test (n - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n tt <- getLine\r\n let t = (read tt :: Int)\r\n test t\r\n\r\nsolve :: String -> String -> Int -> Int\r\nsolve alphabets \"\" prev = 0\r\nsolve alphabets (x : xs) prev =\r\n let ind = findIndex alphabets x 0\r\n in abs (ind - prev) + solve alphabets xs ind\r\n\r\nfindIndex :: String -> Char -> Int -> Int\r\nfindIndex \"\" _ n = -1\r\nfindIndex (a : as) x n =\r\n if x == a\r\n then n\r\n else findIndex as x (n + 1)"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Maybe\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- takeWhile (not . isSpace) <$> getLine\r\n w <- takeWhile (not . isSpace) <$> getLine\r\n let pos = zip s [1 :: Int ..]\r\n getPos c = fromJust $ lookup c pos\r\n print $ sum [abs (getPos a - getPos b) | (a, b) <- zip w (tail w)]\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}, {"source_code": "{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\ncalcEditDist :: [Int] -> [Int] -> Int\ncalcEditDist [] [] = 0\ncalcEditDist (x:xs) (y:ys) = (calcEditDist xs ys) + (abs (x-y))\n\nelemIndexwithList :: [Char] -> Char -> Maybe Int\nelemIndexwithList a b = elemIndex b a\n\nprocess 0 = return ()\nprocess t = do\n s <- getLine\n p <- getLine\n let _:a = p\n let b = init p\n let idx0 = map (fromJust . elemIndexwithList s) a\n let idx1 = map (fromJust . elemIndexwithList s) b\n print (calcEditDist idx0 idx1)\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}], "negative_code": [], "src_uid": "7f9853be7ac857bb3c4eb17e554ad3f1"} {"source_code": "import Data.Set\nmain = interact solve\nsolve input = output where\n inputs = Prelude.map (fromList . Prelude.map (read::String->Int) . tail . words) $ tail $ lines input\n f [x] = fromList [fromList[head y],fromList(tail y)] where y = toList x\n f (x:xs) = g x xs\n g _ [] = empty\n g x (y:xs) = if Data.Set.null z then g x xs else union (fromList [v,w,z]) (g x xs) where\n z = intersection x y\n v = difference x y\n w = difference y x\n output0 = Prelude.map toList $ toList $ f inputs\n output1 = Prelude.map (\\xs->length xs:xs) output0\n output = unlines $ Prelude.map ( unwords . (Prelude.map show)) output1\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, UndecidableInstances, ImplicitParams, ExplicitForAll #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Data.Function\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n n <- readLn\n xss :: [[Int]] <- replicateM (n * (n - 1) `quot` 2) (map read . drop 1 . words <$> getLine)\n let yss = solve xss\n divide 0 zss = zss\n divide i (zs@(_ : _) : zss) = as ++ concat bs : divide (i - length as) zss\n where (as, bs) = splitAt (min i (length zs)) (map (: []) zs)\n divide i (zs : zss) = zs : divide i zss\n divide _ [] = error \"Never happens\"\n forM_ [length ys : ys | ys <- divide (n - length yss) yss] $ \\ys -> do\n putStrLn $ intercalate \" \" $ map show ys\n\nsolve :: [[Int]] -> [[Int]]\nsolve xss = map (snd . unzip) . groupBy ((==) `on` fst) . sort $ do\n let elements = unique $ concat xss\n where unique = map head . group . sort\n e <- elements\n let identity = do\n (i, xs) <- zip [0 ..] xss\n guard $ e `elem` xs\n return i\n return (identity, e)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Tree\nimport Data.Graph\n\nsolve :: Int -> [[Int]] -> [[Int]]\nsolve n pairsets\n | n == 2 = [[head $ head pairsets],tail $ head pairsets]\n | otherwise = map (map fst) . groupBy ((==) `on` snd) . sortBy (compare `on` snd) $ IntMap.assocs ans\n where\n inSet = accumArray (||) False (0,222) [(x,True) | x <- [0..222], y <- [0..222], (arr ! (min x y, max x y)) > 0]\n arr = accumArray (+) 0 ((0,0),(222,222)) $ concatMap list2pairs pairsets\n list2pairs lst = [((x,y),1) | x <- lst, y <- lst, x < y]\n\n ans = execState (rec (0, 0)) IntMap.empty\n \n rec :: (Int, Int) -> State (IntMap Int) ()\n rec (v, l) | v > 222 = return ()\n rec (v, l) = do\n map <- get\n let doit = (inSet ! v) && IntMap.notMember v map\n when doit $ dfs (v, l)\n rec (v + 1, if doit then l + 1 else l)\n\n dfs (v, l) = do\n modify $ IntMap.insert v l\n forM_ [0..222] $ \\t -> when (inSet ! t && (arr ! (min v t, max v t)) > 1) $ do\n map <- get\n when (IntMap.notMember t map) $ dfs (t, l)\n\n\nparseInput = do \n n <- readInt\n pairsets <- replicateM (n * (n - 1) `div` 2) $ do\n k <- readInt\n replicateM k readInt\n return (n, pairsets)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n\nmain = do\n (n, pairsets) <- evalState parseInput <$> BS.getContents\n let answer = solve n pairsets\n forM_ answer $ \\lst -> do\n putStr $ show $ length lst\n forM_ lst $ \\num -> do\n putChar ' '\n putStr $ show num\n putChar '\\n'\n\n--{{{ Start of a minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n--}}} end of a minimal State Monad\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Text.Printf\n\nmain = interact in2out\n\nin2out input\n = output\n where\n [n]:ls = map (map (read :: String->Int))\n $ map words\n $ lines input\n output = unlines\n $ itrSolve n\n $ sort\n $ map sort \n $ take (div (n*(n-1)) 2)\n $ map tail ls\n\nitrSolve 2 [x:xs]\n = [format [x] , format xs]\n\nitrSolve n ls@(x:y:_)\n = format fst : solve ls' fst\n where\n fst = myInter x y\n ls' = take (n-1) ls\n\nmyInter alla@(a:as) allb@(b:bs)\n | a==b\n = a : myInter as bs\n | a Bool\nnotEmpty [] = False\nnotEmpty _ = True\n\nintersectSorted :: [Int] -> [Int] -> [Int]\nintersectSorted as [] = []\nintersectSorted [] bs = []\nintersectSorted (a:as) (b:bs)\n | a < b = intersectSorted as (b:bs)\n | a > b = intersectSorted (a:as) bs\n | a == b = a:(intersectSorted as bs)\n\nmergerSorted :: [Int] -> [Int] -> [Int]\nmergerSorted as [] = as\nmergerSorted [] bs = bs\nmergerSorted (a:as) (b:bs)\n | a < b = a:(mergerSorted as (b:bs))\n | a > b = b:(mergerSorted (a:as) bs)\n | a == b = a:(mergerSorted as bs)\n\nsetDifference :: [Int] -> [Int] -> [Int]\nsetDifference as [] = as\nsetDifference [] bs = []\nsetDifference (a:as) (b:bs)\n | a == b = setDifference as bs\n | a < b = a:(setDifference as (b:bs))\n | a > b = setDifference (a:as) bs\n\ngetSet :: [[Int]] -> [Int]\ngetSet [] = []\ngetSet [a] = a\ngetSet (a:as) = getSet_ a as\n where\n getSet_ a [] = []\n getSet_ a (b:bs)\n | length ab > 0 = ab\n | otherwise = getSet_ a bs\n where\n ab = intersectSorted a b\n\n\nsolve :: [[Int]] -> [[Int]]\nsolve [] = []\nsolve (a:as) = filter notEmpty ([b, d] ++ solve (filter notEmpty (map (\\x -> setDifference x (mergerSorted b d)) as)))\n where\n b = getSet (a:as)\n d = setDifference a b\n\nintsToString :: [Int] -> String\nintsToString a = show (length a) ++ intsToString_ a\n where\n intsToString_ [] = \"\"\n intsToString_ (a:as) = \" \" ++ (show a) ++ (intsToString_ as)\n\nprintAns :: [[Int]] -> IO ()\nprintAns ans = sequence_ (map (\\x -> putStrLn (intsToString x)) ans)\n\nparseLine :: String -> [Int]\nparseLine line = sort (map read (tail (words line)))\n\nmain = do\n n <- readLn\n lines <- sequence (map (\\x -> getLine) [1..(div (n*(n-1)) 2)])\n let mns = map parseLine lines\n let ans = if n > 2 then take n (solve mns) else [[head (head mns)]] ++ [tail (head mns)]\n printAns ans"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, UndecidableInstances, ImplicitParams, ExplicitForAll #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Debug.Trace\n\nsolve :: [[Int]] -> [[Int]] -> [[Int]]\nsolve acc [] = [length ys : ys | ys <- sort acc]\nsolve acc (xs : xss) = do\n let x = head xs\n (ass, bss) = span ((== x) . head) xss\n ys | null ass = [x]\n | otherwise = foldl' intersect xs ass\n solve (ys : acc) (sort . filter (not. null) $ (map (\\\\ ys) ass) ++ bss)\n\nmain :: IO ()\nmain = do\n n <- readLn\n xss :: [[Int]] <- replicateM (n * (n - 1) `quot` 2) (sort . map read . drop 1 . words <$> getLine)\n forM_ (solve [] (sort xss)) $ \\xs -> do\n putStrLn $ intercalate \" \" $ map show xs\n"}, {"source_code": "import List\n\nset n = [n]\n\nsets n = map set [1..n]\n\ntest n = [mergerSorted (sets n !! i) (sets n !! j) | i <- [0..n-1], j <- [0..n-1], i < j]\n\nnotEmpty :: [a] -> Bool\nnotEmpty [] = False\nnotEmpty _ = True\n\nintersectSorted :: [Int] -> [Int] -> [Int]\nintersectSorted as [] = []\nintersectSorted [] bs = []\nintersectSorted (a:as) (b:bs)\n | a < b = intersectSorted as (b:bs)\n | a > b = intersectSorted (a:as) bs\n | a == b = a:(intersectSorted as bs)\n\nmergerSorted :: [Int] -> [Int] -> [Int]\nmergerSorted as [] = as\nmergerSorted [] bs = bs\nmergerSorted (a:as) (b:bs)\n | a < b = a:(mergerSorted as (b:bs))\n | a > b = b:(mergerSorted (a:as) bs)\n | a == b = a:(mergerSorted as bs)\n\nsetDifference :: [Int] -> [Int] -> [Int]\nsetDifference as [] = as\nsetDifference [] bs = []\nsetDifference (a:as) (b:bs)\n | a == b = setDifference as bs\n | a < b = a:(setDifference as (b:bs))\n | a > b = setDifference (a:as) bs\n\ngetSet :: [[Int]] -> [Int]\ngetSet [] = []\ngetSet [a] = a\ngetSet (a:as) = getSet_ a as\n where\n getSet_ a [] = []\n getSet_ a (b:bs)\n | length ab > 0 = ab\n | otherwise = getSet_ a bs\n where\n ab = intersectSorted a b\n\n\nsolve :: [[Int]] -> [[Int]]\nsolve [] = []\nsolve (a:as) = filter notEmpty ([b, d] ++ solve (filter notEmpty (map (\\x -> setDifference x (mergerSorted b d)) as)))\n where\n b = getSet (a:as)\n d = setDifference a b\n\nintsToString :: [Int] -> String\nintsToString a = show (length a) ++ intsToString_ a\n where\n intsToString_ [] = \"\"\n intsToString_ (a:as) = \" \" ++ (show a) ++ (intsToString_ as)\n\nprintAns :: [[Int]] -> IO ()\nprintAns ans = sequence_ (map (\\x -> putStrLn (intsToString x)) ans)\n\nparseLine :: String -> [Int]\nparseLine line = sort (map read (tail (words line)))\n\nmain = do\n n <- readLn\n lines <- sequence (map (\\x -> getLine) [1..(div (n*(n-1)) 2)])\n let mns = map parseLine lines\n let ans = take n (solve mns)\n printAns ans\n\n"}, {"source_code": "import List\n\nnotEmpty :: [a] -> Bool\nnotEmpty [] = False\nnotEmpty _ = True\n\nintersectSorted :: [Int] -> [Int] -> [Int]\nintersectSorted as [] = []\nintersectSorted [] bs = []\nintersectSorted (a:as) (b:bs)\n | a < b = intersectSorted as (b:bs)\n | a > b = intersectSorted (a:as) bs\n | a == b = a:(intersectSorted as bs)\n\nsetDifference :: [Int] -> [Int] -> [Int]\nsetDifference as [] = as\nsetDifference [] bs = []\nsetDifference (a:as) (b:bs)\n | a == b = setDifference as bs\n | a < b = a:(setDifference as (b:bs))\n | a > b = setDifference (a:as) bs\n\ngetSet :: [[Int]] -> [Int]\ngetSet [] = []\ngetSet [a] = a\ngetSet (a:as) = getSet_ a as\n where\n getSet_ a [] = []\n getSet_ a (b:bs)\n | length ab > 0 = ab\n | otherwise = getSet_ a bs\n where\n ab = intersectSorted a b\n\n\nsolve :: [[Int]] -> [[Int]]\nsolve [] = []\nsolve (a:as) = filter notEmpty ([b, d] ++ solve (filter notEmpty (map (\\x -> setDifference x (b ++ d)) as)))\n where\n b = getSet (a:as)\n d = setDifference a b\n\nintsToString :: [Int] -> String\nintsToString a = show (length a) ++ intsToString_ a\n where\n intsToString_ [] = \"\"\n intsToString_ (a:as) = \" \" ++ (show a) ++ (intsToString_ as)\n\nprintAns :: [[Int]] -> IO ()\nprintAns ans = sequence_ (map (\\x -> putStrLn (intsToString x)) ans)\n\nparseLine :: String -> [Int]\nparseLine line = sort (map read (tail (words line)))\n\nmain = do\n n <- readLn\n lines <- sequence (map (\\x -> getLine) [1..(div (n*(n-1)) 2)])\n let mns = map parseLine lines\n let ans = solve mns\n printAns ans\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nimport Data.Int\nimport Data.Function\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\n\nsolve :: Int -> [[Int]] -> [[Int]]\nsolve n pairsets = \n map (map fst) . groupBy ((==) `on` snd) . sortBy (compare `on` snd) $ Map.assocs ans\n where\n inSet = accumArray (||) False (0,222) [(x,True) | x <- [0..222], y <- [0..222], (arr ! (min x y, max x y)) > 0]\n arr = accumArray (+) 0 ((0,0),(222,222)) $ concatMap list2pairs pairsets\n list2pairs lst = [((x,y),1) | x <- lst, y <- lst, x < y]\n\n ans = execState (rec (0, 0)) Map.empty\n \n rec :: (Int, Int) -> State (Map.Map Int Int) ()\n rec (v, l) | v > 222 = return ()\n rec (v, l) = do\n map <- get\n let doit = (inSet ! v) && Map.notMember v map\n when doit $ dfs (v, l)\n rec (v + 1, if doit then l + 1 else l)\n\n dfs (v, l) = do\n modify $ Map.insert v l\n forM_ [0..222] $ \\t -> when (inSet ! t && (arr ! (min v t, max v t)) > 1) $ do\n map <- get\n when (Map.notMember t map) $ dfs (t, l)\n\n\nparseInput = do \n n <- readInt\n pairsets <- replicateM (n * (n - 1) `div` 2) $ do\n k <- readInt\n replicateM k readInt\n return (n, pairsets)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n\nmain = do\n (n, pairsets) <- evalState parseInput <$> BS.getContents\n let answer = solve n pairsets\n forM_ answer $ \\lst -> do\n putStr $ show $ length lst\n forM_ lst $ \\num -> do\n putChar ' '\n putStr $ show num\n putChar '\\n'\n\n--{{{ Start of a minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n--}}} end of a minimal State Monad\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, UndecidableInstances, ImplicitParams, ExplicitForAll #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Unsafe.Coerce\nimport qualified Data.IntSet as Set\n\nsolve :: [[Int]] -> [[Int]] -> [[Int]]\nsolve acc [] = [length ys : ys | ys <- sort acc]\nsolve acc (xs : xss) = do\n let x = head xs\n (ass, bss) = partition ((== x) . head) xss\n ys = foldl' intersect xs ass\n solve (ys : acc) (sort . filter (not. null) $ (map (\\\\ ys) ass) ++ bss)\n\nmain :: IO ()\nmain = do\n n <- readLn\n xss :: [[Int]] <- replicateM (n * (n - 1) `quot` 2) (sort . map read . drop 1 . words <$> getLine)\n forM_ (solve [] (sort xss)) $ \\xs -> do\n putStrLn $ intercalate \" \" $ map show xs\n"}], "src_uid": "bde894dc01c65da67d32c716981926f6"} {"source_code": "q=g.dropWhile(==' ')\np(l,[])=[l]\np(l,_:r)=l:q r\ng[]=[]\ng('\"':s)=p$span(/='\"')s\ng s=p$span(/=' ')s\nmain=interact$unlines.map(\\s->\"<\"++s++\">\").q.head.lines\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\n\nparse :: C.ByteString -> [C.ByteString]\nparse s =\n case C.uncons s of\n Nothing -> []\n Just (' ', t) -> parse $ C.dropWhile (==' ') t\n Just ('\"', t) -> let (i, j) = C.span (/='\"') t in (i:) $ parse $ C.tail j\n _ -> let (i, j) = C.span (/=' ') s in (i:) $ parse j\n\nmain :: IO ()\nmain = do\n s <- fmap (C.map (\\i -> if isSpace i then ' ' else i)) C.getLine\n C.putStr $ C.unlines $ map (('<' `C.cons`) . (`C.snoc` '>')) $ parse s\n"}, {"source_code": "import System.IO (isEOF)\nimport Data.Char (isSpace)\nimport Control.Monad (when)\n\ndata State = Argument | Quotes\n deriving Eq\n\nmain = do\n solve Nothing\n\nsolve state = do\n end <- isEOF\n if end\n then do\n when (state == Just Argument) $ putChar '>'\n return ()\n else do\n ch <- fmap (\\ch -> if isSpace ch then ' ' else ch) getChar\n case state of\n Nothing -> case ch of\n ' ' -> solve Nothing\n '\"' -> putChar '<' >> solve (Just Quotes)\n _ -> putChar '<' >> putChar ch >> solve (Just Argument)\n Just Argument -> case ch of\n ' ' -> putChar '>' >> putChar '\\n' >> solve Nothing\n _ -> putChar ch >> solve (Just Argument)\n Just Quotes -> case ch of\n '\"' -> putChar '>' >> putChar '\\n' >> solve Nothing\n _ -> putChar ch >> solve (Just Quotes)\n"}, {"source_code": "import Data.List\nimport Data.Char(isSpace)\n\nrstrip = reverse . dropWhile isSpace . reverse\n\nmain = interact $ write . solve . rstrip\n\nwrite :: [String] -> String\n\nwrite = unlines . (map (\\x -> \"<\" ++ x ++ \">\"))\n\nsolve :: String -> [String]\n\nsolve ('\"' : rest) =\n [token] ++ (solve rest')\n where\n token = takeWhile (/= '\"') rest\n rest' = tail $ dropWhile (/= '\"') rest\n\nsolve (' ' : rest) =\n solve $ dropWhile (== ' ') rest\n\nsolve \"\" =\n []\n\nsolve rest =\n [takeWhile (/= ' ') rest] ++ (solve $ dropWhile (/= ' ') rest)\n"}, {"source_code": "\nsolve :: String -> [String]\nsolve s = solveSpace \"\" s\n where\n solveSpace word \"\"\n | null word = []\n | otherwise = [reverse word]\n solveSpace word (c:s)\n | c == ' ' && null word = solveSpace \"\" s\n | c == ' ' = (reverse word) : solveSpace \"\" s\n | c == '\"' = solveQuote \"\" s\n | otherwise = solveSpace (c : word) s\n solveQuote word (c:s)\n | c == '\"' = (reverse word) : solveSpace \"\" s\n | otherwise = solveQuote (c : word) s\n\nputStrLn' :: String -> IO ()\nputStrLn' s = putStrLn $ concat [\"<\", s, \">\"]\n\nmain :: IO ()\nmain = getLine >>= mapM_ putStrLn' . solve"}, {"source_code": "import Data.List\n\nsplit :: (Show a, Eq a) => a -> [a] -> [[a]]\nsplit x xs = let (fst, rest) = break (== x) xs in case rest of\n [] -> [fst]\n (_:rest) -> fst:split x rest\n\nmain = do\n s <- getLine\n putStr $ concatMap (\\x -> \"<\" ++ x ++ \">\\n\") \n $ concat $ zipWith ($) (cycle [words, return]) $ split '\"' s\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as C\n\nparse :: C.ByteString -> [C.ByteString]\nparse s =\n case C.uncons s of\n Nothing -> []\n Just (' ', t) -> parse $ C.dropWhile (==' ') t\n Just ('\"', t) -> let (i, j) = C.span (/='\"') t in (i:) $ parse $ C.tail j\n _ -> let (i, j) = C.span (/=' ') s in (i:) $ parse j\n\nmain :: IO ()\nmain = do\n s <- C.getLine\n C.putStr $ C.unlines $ map (('<' `C.cons`) . (`C.snoc` '>')) $ parse s\n"}, {"source_code": "import qualified Data.ByteString.Char8 as C\n\nparse :: C.ByteString -> [C.ByteString]\nparse s =\n case C.uncons s of\n Nothing -> []\n Just (' ', t) -> parse $ C.dropWhile (==' ') t\n Just ('\"', t) -> let (i, j) = C.span (/='\"') t in (i:) $ parse $ C.tail j\n _ -> let (i, j) = C.span (/=' ') s in (i:) $ parse j\n\nmain :: IO ()\nmain = do\n s <- C.getLine\n C.putStrLn $ ('<' `C.cons`) $ (`C.snoc` '>') $ C.intercalate (C.pack \">\\n<\") $ parse s\n"}, {"source_code": "q=g.dropWhile(==' ')\np(l,[])=[l]\np(l,_:r)=l:q r\ng[]=[]\ng('\"':s)=p$span(/='\"')s\ng s=p$span(/=' ')s\nmain=interact$unlines.map(\\s->\"<\"++s++\">\").q\n"}], "src_uid": "6c7858731c57e1b24c7a299a8eeab373"} {"source_code": "import Data.List (sort, group)\n\nmain = do\n \t\tinteract (show. length. group. sort. tail. lines)\n", "positive_code": [{"source_code": "main=interact((\\(n:s)->show$length$foldl(\\b x->if(elem x b)then(b)else(x:b)) [] s).map(words).lines)"}, {"source_code": "import Data.List (sort, group)\nmain = do interact (show . length . group . sort . tail . lines)\n{-\n\n-}\n"}, {"source_code": "import Data.List (sort, group)\nmain = do interact (show . length . group . sort . tail . lines)\n"}, {"source_code": "import Data.List\nmain = do\n\tn<-getLine\n\ts<-getContents\n\tputStrLn $ show $ solve (lines s)\nsolve s = length $ nub s"}, {"source_code": "import List\nmain = interact (show.length.nub.tail.lines)\n"}, {"source_code": "-- 44A\n\nimport List (nub)\n\ngetTuple :: String -> (String, String)\ngetTuple s = (s1, s2)\n where\n [s1, s2] = words s\n\nmain :: IO ()\nmain = getLine >> fmap lines getContents >>= print . length . nub . map getTuple"}, {"source_code": "main = interact solve\nsolve input = output where\n n0:leaves = lines input\n n = read n0::Int\n output = show $ answer leaves\n answer [] = 0\n answer (x:xs) = answer xs + if or $ map (== x) xs then 0 else 1"}], "negative_code": [], "src_uid": "07c370b99fe85984f5e20826a3bf5eb9"} {"source_code": "import Data.List\n\nsolve :: String -> String\nsolve s\n = r\n where\n lowered = concatMap (take 2) (group s)\n r = concat $ no2cons (group lowered) False\n\n no2cons :: [[Char]] -> Bool -> [[Char]]\n no2cons [] _ = []\n no2cons ([x] : rest) _ = [x] : no2cons rest False\n no2cons ([x,y] : rest) False = [x,y] : no2cons rest True\n no2cons ([x,y] : rest) True = [x] : no2cons rest False\n\nmain = interact solve", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nencode :: String -> [(Char,Int)]\nencode = map (head &&& length) . group\n\ndecode :: [(Char,Int)] -> String\ndecode = concat . map (\\(ch,i) -> take i (repeat ch))\n\nfixTypo :: [(Char,Int)] -> [(Char,Int)]\nfixTypo = go False\n where\n go _ [] = []\n go _ ((ch,1):l) = (ch,1):go False l\n go False ((ch,i):l) = (ch,2):go True l\n go True ((ch,i):l) = (ch,1):go False l\n\n\nmain = do\n s <- encode <$> getLine\n let s1 = fixTypo s\n putStrLn $ decode s1\n"}, {"source_code": "\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: String -> String\nsolve (a:b:c:d:s)\n | a == b && b == c = solve (b:c:d:s)\n | a == b && c == d = solve (a:b:c:s)\n | otherwise = a : solve (b:c:d:s)\nsolve (a:b:c:[]) = [a, b] [a, b, c] $ a == b && b == c\nsolve s = s\n\n\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n"}, {"source_code": "module Main where\n-- import Control.Applicative\nimport Data.List (group)\nmain :: IO ()\nmain = do\n w <- getLine\n let gw = map (\\ g@(c:_) -> (c, length g)) $ group w\n ff (c,n) (b,l) =\n if b && n > 1\n then (False, (c,1):l)\n else (n > 1, (c,min 2 n):l)\n (_, fixed) = foldr ff (False, []) gw\n s = concatMap (uncurry $ flip replicate) fixed\n putStrLn s\n"}], "negative_code": [{"source_code": "import Data.List\n\nsolve :: String -> String\nsolve s\n = r\n where\n lowered = concatMap (take 2) (group s)\n r = concat $ no2cons (group lowered) False\n\n no2cons :: [[Char]] -> Bool -> [[Char]]\n no2cons [] _ = []\n no2cons ([x] : rest) _ = [x] : no2cons rest False\n no2cons ([x,y] : rest) False = [x,y] : no2cons rest True\n no2cons ([x,y] : rest) True = [x] : no2cons rest True\n\nmain = interact solve"}], "src_uid": "31d803d886c47fe681bdcfbe6c74f090"} {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n tail >>> map (words >>> map read >>> solve >>> bool \"NO\" \"YES\") >>> unlines\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [r, b, d] =\r\n let x = min r b\r\n y = max r b\r\n in (y - 1) `div` x <= d\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.STRef(STRef, newSTRef, readSTRef, writeSTRef)\r\nimport Data.Array.ST(runSTArray, STArray)\r\nimport Data.Array.IO(IOArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, filterM, forM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\ntype Output = Bool\r\n\r\nsolve :: Integer -> Integer -> Integer -> Output\r\nsolve r b d = (d+1) * (min r b) >= max r b\r\n\r\nplotResult :: Output -> IO ()\r\nplotResult False = putStrLn \"NO\"\r\nplotResult True = putStrLn \"YES\"\r\n\r\n\r\nmain :: IO ()\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[r, b, d] <- getLine >>= return . (fmap read) . words :: IO [Integer] \r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve r b d\r\n\treturn ()"}, {"source_code": "import Control.Monad.RWS.Lazy (forM_)\r\nimport Data.List ( sort )\r\n\r\nmain :: IO ()\r\nmain = do\r\n a <- getLine\r\n let t = read a :: Int\r\n\r\n let solve _ = do\r\n b <- getLine\r\n let n = read <$> words b :: [Int]\r\n let j = sort $ take 2 n :: [Int]\r\n\r\n let u = if last j `rem` head j == 0\r\n then (last j - head j) `div` head j\r\n else (last j - head j) `div` head j + 1\r\n\r\n putStrLn $ if u <= last n\r\n then \"YES\"\r\n else \"NO\"\r\n\r\n forM_ [1..t] solve"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ncalc :: Int64 -> Int64 -> Int64 -> String\ncalc r b d | r > b = calc b r d\ncalc r b d =\n if b - r <= r * d then\n \"YES\"\n else\n \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [r,b,d] = map read $ words line :: [Int64]\n putStrLn $ calc r b d\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintS = do \r\n [r,b,d]<-readInts \r\n let red = min r b \r\n blue = max r b \r\n putStrLn $ if blue >= red && blue <= red + d*red then \"YES\"\r\n else \"NO\"\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}, {"source_code": "solve::[Int]->[String]\r\nsolve (r:b:d:xs)\r\n | ((max r b) `div` (min r b)) - t > d = \"No\" : solve xs\r\n | otherwise = \"Yes\" : solve xs\r\n where t = if ((max r b) `rem` (min r b)) == 0 then 1 else 0\r\nsolve [] = []\r\n\r\nmain = interact $ unlines . solve . map read . tail . words\r\n"}, {"source_code": "import Control.Monad\n\nreadInt :: IO Integer\nreadInt = readLn\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nsolve :: Integer -> Integer -> Integer -> Bool\nsolve mi ma d = ma <= (d + 1) * mi\n\nans :: Bool -> String\nans True = \"YES\"\nans False = \"NO\"\n\nsolveCase :: IO String\nsolveCase = do\n [a, b, d] <- readInts\n return $ ans $ solve (min a b) (max a b) d\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.STRef(STRef, newSTRef, readSTRef, writeSTRef)\r\nimport Data.Array.ST(runSTArray, STArray)\r\nimport Data.Array.IO(IOArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, filterM, forM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\ntype Output = Bool\r\n\r\nsolve :: Integer -> Integer -> Integer -> Output\r\nsolve r b d\r\n\t| max (r-b) (b-r) <= d = True\r\n\t| d > 1 && r > b && b > 1 = solve (max 1 $ r - (b+d)) (b-1) d\r\n\t| d > 1 && b > r && r > 1 = solve (max 1 $ b - (r+d)) (r-1) d\r\n\t| otherwise = False\r\n\r\nplotResult :: Output -> IO ()\r\nplotResult False = putStrLn \"NO\"\r\nplotResult True = putStrLn \"YES\"\r\n\r\n\r\nmain :: IO ()\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[r, b, d] <- getLine >>= return . (fmap read) . words :: IO [Integer] \r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve r b d\r\n\treturn ()"}, {"source_code": "import Control.Monad.RWS.Lazy (forM_)\r\nimport Data.List ( sort )\r\n\r\nmain :: IO ()\r\nmain = do\r\n a <- getLine\r\n let t = read a :: Int\r\n\r\n let solve _ = do\r\n b <- getLine\r\n let n = read <$> words b :: [Int]\r\n let j = sort $ take 2 n :: [Int]\r\n\r\n putStrLn $ if last j <= (head j * (last n + 1))\r\n then \"YES\"\r\n else \"NO\"\r\n forM_ [1..t] solve"}, {"source_code": "import Control.Monad.RWS.Lazy (forM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n a <- getLine\r\n let t = read a :: Int\r\n\r\n let solve _ = do\r\n b <- getLine\r\n let n = read <$> words b :: [Int]\r\n let p = min (head n) (n !! 1) :: Int\r\n let u = sum (take 2 n) - 2 * p :: Int\r\n let x = u `div` p + u `rem` p :: Int\r\n\r\n putStrLn $ if x <= last n\r\n then \"YES\"\r\n else \"NO\"\r\n\r\n forM_ [1..t] solve"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: Int -> Int -> Int -> String\ncalc r b d | r > b = calc b r d\ncalc r b d =\n if b - r <= r * d then\n \"YES\"\n else\n \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [r,b,d] = map read $ words line :: [Int]\n putStrLn $ calc r b d\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintS = do \r\n [r,b,d]<-readInts \r\n let red = min r b \r\n blue = max r b \r\n putStrLn $ if blue >= red && blue <= red + d*red then \"YES\"\r\n else \"NO\"\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}], "src_uid": "c0ad2a6d14b0c9e09af2221d88a34d52"} {"source_code": "import Control.Monad ( forM_ )\n\nmain = do\n n <- readLn\n forM_ [1..n] $ const $ do\n let myGet = fmap (fmap read . words) getLine\n [b, hC, cC] <- myGet\n [hP, cP] <- myGet\n let maxBC = b `div` 2\n if hP > cP then do\n let hBC = min maxBC hC\n cBC = min (maxBC - hBC) cC\n print $ hBC * hP + cBC * cP\n else do\n let cBC = min maxBC cC\n hBC = min (maxBC - cBC) hC\n print $ hBC * hP + cBC * cP", "positive_code": [{"source_code": "f -. g = g . f\n\nmain = do\n\tgetLine\n\tinteract $ lines -. map words -. map (map read) -. foo -. map bar -. map show -. unlines\n\nfoo [] = []\nfoo (x1:x2:xs) = (x1++x2) : (foo xs)\n\nbar :: [Int] -> Int\nbar (b:p:f:h:c:[]) =\n\tlet\n\t\tb2 = div b 2\n\tin if h>c\n\t\tthen h*(min p b2)+c*(min f (b2-(min p b2)))\n\t\telse c*(min f b2)+h*(min p (b2-(min f b2)))\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nmain = do\n t <- readLn\n replicateM_ t $ do\n [b,r1,r2] <- map read . words <$> getLine\n [p1,p2] <- map read . words <$> getLine\n print $ maximum $ 0 : catMaybes [ guard (2*(n1+n2) <= b) *>\n guard (n1 <= r1) *>\n guard (n2 <= r2) *>\n return (n1*p1 + n2*p2)\n | n1 <- [0..100], n2 <- [0..100] ]\n"}, {"source_code": "gint :: IO Int\ngint = fmap read getLine\n\nmain = do\n t <- gint\n mymain t\n\nmymain 0 = return ()\nmymain x = do\n strabc <- getLine\n strde <- getLine\n let [a,b,c] = map read $ words strabc\n let [d,e] = map read $ words strde\n let aa = a `div` 2\n if (d > e)\n then print (solve aa b c d e)\n else print (solve aa c b e d)\n mymain (x - 1)\n\nsolve a b c d e =\n let one = min a b\n two = max 0 (min (a-one) c) in\n (one * d + two * e)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\n\n\n\n\n\nonecase= do\n\t\t[b,p,f]<- map read <$> words <$> getLine ::IO [Int]\n\t\t[h,c]<- map read <$> words <$> getLine :: IO [Int]\n\t\tlet pp1 = (min p (div b 2)) *h\n\t\tlet cp1 = (min f (div (b-p*2) 2)) *c\n\t\tlet cp2 = (min f (div b 2)) *c\n\t\tlet pp2 = (min p (div (b-f*2) 2)) *h\n\t\tprint $ if h>c then (max 0 pp1)+(max 0 cp1) else (max 0 pp2)+(max 0 cp2)\n\nmain::IO ()\nmain=do\n\ts<- read <$> getLine:: IO Int\n\treplicateM_ s onecase\n\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(sortBy)\n\nmakeBurgers :: (Integral a, Num b) => a -> a -> b -> (a,b)\nmakeBurgers b p c = (b',v')\n where\n d = min (b `div` 2) p\n b' = b - 2 * d\n v' = fromIntegral d * c\n\nmakeAllBurgers :: (Integral a, Num b, Ord b) => a -> [a] -> [b] -> b\nmakeAllBurgers b' ps' cs' = f b' (sortBy (\\(_,c1) (_,c2) -> compare c2 c1) $ zip ps' cs')\n where\n f 0 _ = 0\n f _ [] = 0\n f b ((p,c):xs) = v + f bnew xs\n where (bnew, v) = makeBurgers b p c\n\nprocess :: Int -> IO ()\nprocess t\n | t <= 0 = return ()\n | otherwise = do\n line1 <- getLine\n let words1 = words line1\n let b = read $ head words1 :: Int\n let ps = map read $ tail words1 :: [Int]\n line2 <- getLine\n let cs = map read . words $ line2 :: [Int]\n print $ makeAllBurgers b ps cs\n process (t-1)\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n process t"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nmain = do\n t <- readLn\n replicateM_ t $ do\n [b,r1,r2] <- map read . words <$> getLine\n [p1,p2] <- map read . words <$> getLine\n print $ maximum $ 0 : catMaybes [ guard (2*(n1+n2) <= b) *>\n guard (n1 <= r1) *>\n guard (n2 <= r2) *>\n return (n1*p1 + n2*p2)\n | n1 <- [1..100], n2 <- [1..100] ]\n"}, {"source_code": "import Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n [b,p,f] <- map read . words <$> getLine\n [h,c] <- map read . words <$> getLine\n if h > c then let n1 = min (b `div` 2) p\n b' = b - 2*n1\n in print $ h*n1 * c*min (b' `div` 2) f\n else let n1 = min (b `div` 2) f\n b' = b - 2*n1\n in print $ c*n1 + h*min (b' `div` 2) p\n"}, {"source_code": "import Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n [b,r1,r2] <- map read . words <$> getLine\n [p1,p2] <- map read . words <$> getLine\n if p1 > p2 then let n = min (b `div` 2) r1\n b' = b - 2*n\n in print $ p1*n * p2*min (b' `div` 2) r2\n else let n = min (b `div` 2) r2\n b' = b - 2*n\n in print $ p2*n + p1*min (b' `div` 2) r1\n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- readLn\n forM_ [1..n] $ const $ do\n let myGet = fmap (fmap read . words) getLine\n [b, hC, cC] <- myGet\n [hP, cP] <- myGet\n let maxBC = b `div` 2\n if hP < cP then do\n let hBC = min maxBC hC\n cBC = min (maxBC - hBC) cC\n print $ hBC * hP + cBC * cP\n else do\n let cBC = min maxBC cC\n hBC = min (maxBC - cBC) hC\n print $ hBC * hP + cBC * cP"}], "src_uid": "92bf30e66f4d5ddebb697d2fa4fa0689"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ngetInt :: IO Int\ngetInt = parseInt <$> C.getLine\n\ndata Tree = Empty | Node Int Tree Tree\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n as <- replicateM n getInt\n let func _ [] = (Empty, [])\n func i (x : xs)\n | i == x = (Node i t' t'', xs'')\n | otherwise = (Empty, x : xs)\n where (t', xs') = func 1 xs\n (t'', xs'') = func (i + 1) xs'\n dfs :: Bool -> Builder -> Tree -> IO ()\n dfs _ _ Empty = return ()\n dfs flag builder (Node x child sibling) = do\n let builder' = if flag then builder `mappend` charUtf8 '.' `mappend` intDec x else intDec x\n hPutBuilder stdout $ builder' `mappend` charUtf8 '\\n'\n dfs True builder' child\n dfs flag builder sibling\n dfs False mempty $ fst $ func 1 as\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nnextLi :: Int -> [Int] -> [Int]\nnextLi ai pre = let\n rv (v : vs)\n | ai == v + 1 = ai : vs\n | otherwise = rv vs\n rv [] = error \"bad input\"\n in if ai == 1\n then 1 : pre\n else rv pre\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n (\\fun -> foldM_ fun [] (replicate n ())) $ \\pre () -> do\n [ai] <- readInts\n let res = nextLi ai pre\n res <$ putInts (reverse res)\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 '.') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "c1bf6c8a9a20f377cf2a5dbea2267c88"} {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain = interact $ words >>> drop 1 >>> chunksOf 2 >>> map solve >>> unlines\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (fs, xs') = splitAt k xs\r\n in fs : chunksOf k xs'\r\n\r\nsolve :: [String] -> String\r\nsolve [_, s]\r\n | even fz || fz == 1 = \"BOB\"\r\n | otherwise = \"ALICE\"\r\n where\r\n fz = count '0' s\r\n count c = length . filter (== c)\r\n", "positive_code": [{"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n getLine\r\n s <- getLine\r\n let cnt = length $ filter (== '0') s\r\n putStrLn $ if cnt == 1 then\r\n \"BOB\"\r\n else if cnt `mod` 2 == 1 then \r\n \"ALICE\"\r\n else\r\n \"BOB\"\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n s <- getLine\n let z = length $ filter (== '0') s\n putStrLn $ if even z || z == 1 then \"BOB\" else \"ALICE\"\n\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\ncaseString :: String -> Int -> String\r\ncaseString l numZero | numZero == 0 = \"DRAW\"\r\n | numZero == 1 = \"BOB\"\r\n | (odd . length $ l) && (odd numZero) = \"ALICE\"\r\n | (odd . length $ l) && (even numZero) = \"BOB\"\r\n | (even . length $ l) = \"BOB\"\r\n\r\nsolve = do trash <- getLine\r\n l <- getLine\r\n let numZero = (length . filter (=='0')) l\r\n putStrLn (caseString l numZero)\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n return $ stringUtf8 (if odd n && C.index str (n `div` 2) == '0' && C.count '0' str > 1 then \"ALICE\" else \"BOB\") `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "main = interact (unlines . g . tail . lines)\r\n \r\ng [] = []\r\ng (x:y:xs) = (f y: g xs)\r\nf::String->String\r\nf y | rem t 2 == 0 = \"BOB\" \r\n | t == 1 = \"BOB\" \r\n |otherwise = \"ALICE\"\r\n where t = count '0' y\r\n \r\ncount x [] = 0\r\ncount x (y:ys) |x==y = 1 + count x ys\r\ncount x y = count x (tail y)"}], "negative_code": [{"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\ncaseString :: String -> Int -> String\r\ncaseString l numZero | numZero == 0 = \"DRAW\"\r\n | ((length l) == 1) && (numZero == 1) = \"BOB\"\r\n | (odd . length $ l) && (odd numZero) = \"ALICE\"\r\n | (odd . length $ l) && (even numZero) = \"BOB\"\r\n | (even . length $ l) = \"BOB\"\r\n\r\nsolve = do trash <- getLine\r\n l <- getLine\r\n let numZero = (length . filter (=='0')) l\r\n putStrLn (caseString l numZero)\r\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\ncaseString :: String -> Int -> String\r\ncaseString l numZero | (odd . length $ l) && (odd numZero) = \"ALICE\"\r\n | (odd . length $ l) && (even numZero) = \"BOB\"\r\n | (even . length $ l) && (numZero == length l) = \"DRAW\"\r\n | (even . length $ l) && (numZero /= length l) = \"BOB\"\r\n\r\nsolve = do trash <- getLine\r\n l <- getLine\r\n let numZero = (length . filter (=='0')) l\r\n putStrLn (caseString l numZero)\r\n"}, {"source_code": "import Control.Monad (replicateM)\r\nimport Data.Sequence (mapWithIndex)\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nsolve = do xs <- getLine\r\n putStrLn (show (countBeautiful xs (length xs)))\r\n\r\ncountBeautiful :: String -> Int -> Int\r\nindicativeFunc :: (Int, Char) -> Int\r\nindicativeFunc (i,a) | a == '1' && (even i) = 0\r\n | a == '1' && (odd i) = 1\r\n | a == '0' && (even i) = 1\r\n | a == '0' && (odd i) = 0\r\n | otherwise = 2\r\ncreateIndicator :: [Char] -> [Int]\r\ncreateIndicator x = (map indicativeFunc (zip [0..length x -1] x)) ++ [3]\r\n--evenFunc :: [Int] -> Int -> Int\r\n--evenFunc indi i | (indi !! i == 1 || indi !! i == 2) = evenFunc indi (i+1)\r\n-- | otherwise = i\r\n\r\nevenFunc :: [Int] -> [Int] -> Int -> Int -> [Int]\r\nevenFunc indi acc idx prev | idx == length indi = reverse acc\r\n | indi !! (length indi - idx - 1) == 0 = evenFunc indi (acc++[length indi - idx - 1]) (idx+1) (length indi - idx - 1)\r\n | otherwise = evenFunc indi (acc ++ [prev]) (idx + 1) (prev)\r\n\r\noddFunc :: [Int] -> [Int] -> Int -> Int -> [Int]\r\noddFunc indi acc idx prev | idx == length indi = reverse acc\r\n | indi !! (length indi - idx - 1) == 1 = oddFunc indi (acc++[length indi - idx - 1]) (idx+1) (length indi - idx - 1)\r\n | otherwise = oddFunc indi (acc ++ [prev]) (idx + 1) (prev)\r\n--oddFunc :: [Int] -> Int -> Int\r\n--oddFunc indi i | (indi !! i == 0 || indi !! i == 2) = oddFunc indi (i+1)\r\n-- | otherwise = i\r\ncountBeautiful x n = sum maxOfTwo - (n*(n+1) `div` 2)\r\n where indicator = createIndicator x\r\n evenLs = evenFunc indicator [] 0 (n)\r\n oddLs = oddFunc indicator [] 0 (n)\r\n maxOfTwo = [max x y | (x,y) <- zip evenLs oddLs]\r\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\ncaseString :: String -> Int -> String\r\ncaseString l numZero | (odd . length $ l) && (odd numZero) && (odd ((numZero-1) `div` 2)) = \"ALICE\"\r\n | (odd . length $ l) && (odd numZero) && (even ((numZero-1) `div` 2)) = \"BOB\"\r\n | (odd . length $ l) && (even numZero) && (odd (numZero `div` 2)) = \"BOB\"\r\n | (odd . length $ l) && (even numZero) && (even (numZero `div` 2)) = \"DRAW\"\r\n | (even . length $ l) && (odd (numZero `div` 2)) = \"BOB\"\r\n | (even . length $ l) && (even (numZero `div` 2)) = \"DRAW\"\r\n\r\nsolve = do trash <- getLine\r\n l <- getLine\r\n let numZero = (length . filter (=='0')) l\r\n putStrLn (caseString l numZero)\r\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\ncaseString :: String -> Int -> String\r\ncaseString l numZero | (odd . length $ l) && (odd numZero) && (odd ((numZero-1) `div` 2)) = \"ALICE\"\r\n | (odd . length $ l) && (odd numZero) && (even ((numZero-1) `div` 2)) = \"BOB\"\r\n | (odd . length $ l) && (even numZero) && (odd (numZero `div` 2)) = \"BOB\"\r\n | (odd . length $ l) && (even numZero) && (even (numZero `div` 2)) = \"DRAW\"\r\n | (even . length $ l) && (odd (numZero `div` 2)) = \"BOB\"\r\n | (even . length $ l) && (even (numZero `div` 2)) = \"DRAW\"\r\n\r\nsolve = do trash <- getLine\r\n l <- getLine\r\n let numZero = (length . filter (=='0')) l\r\n putStrLn . show $ (caseString l numZero)\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.take n <$> C.getLine\n let zeroNum = C.count '0' str\n isMiddleZero = odd n && C.index str (n `div` 2) == '0'\n level = zeroNum `div` 2\n return $ stringUtf8 (if isMiddleZero then (if odd level then \"ALICE\" else \"BOB\") else (if even level then \"DRAW\" else \"BOB\")) `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let zeroNum = C.count '0' str\n isMiddleZero = odd n && C.index str (n `div` 2) == '0'\n level = zeroNum `div` 2\n return $ stringUtf8 (if isMiddleZero then (if odd level then \"ALICE\" else \"BOB\") else (if even level then \"DRAW\" else \"BOB\")) `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let zeroNum = C.count '0' str\n isMiddleZero = odd n && C.index str (n `div` 2) == '0'\n level = zeroNum `div` 2\n return $ string7 (if isMiddleZero then (if odd level then \"ALICE\" else \"BOB\") else (if even level then \"DRAW\" else \"BOB\")) `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let zeroNum = C.count '0' str\n return $ string7 (if odd n && C.index str (n `div` 2) == '0' || zeroNum /= 0 && zeroNum `mod` 4 /= 0 then \"BOB\" else \"DRAW\") `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain = interact $ words >>> drop 1 >>> chunksOf 2 >>> map solve >>> unlines\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (fs, xs') = splitAt k xs\r\n in fs : chunksOf k xs'\r\n\r\nsolve :: [String] -> String\r\nsolve [ns, s]\r\n | even n = \"BOB\"\r\n | (s !! (n `div` 2)) == '1' = \"BOB\"\r\n | length (filter (== '0') s) == 1 = \"BOB\"\r\n | otherwise = \"DRAW\"\r\n where\r\n n = read ns\r\n"}], "src_uid": "42b425305ccc28b0d081b4c417fe77a1"} {"source_code": "import Data.List\nmain=do\n v<-map read.tail.words<$>getContents\n print$foldr(max.length.filter(==maximum v))0$group(v::[Int])", "positive_code": [{"source_code": "import Data.List\nmain = interact $ show . process . map read . tail. words\nprocess :: [Int] -> Int\nprocess x = maximum $ map (\\z -> if head z then length z else 0) $ group $ map (== mm) x \n where mm = maximum x"}, {"source_code": "import Data.List\nmain=map read.tail.words<$>getContents>>=(print.snd.maximum.map(\\x->(head x::Int,length x)).group)"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n n <- readLn :: (IO Int)\n v <- (map (read :: String->Int)) . words <$> getLine\n print $ maximum $ map length $ filter (\\x -> head x == maximum v) $ group v\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n v <- (map (read :: String->Int)) . words <$> getLine\n print $ maximum $ map length $ filter (\\x -> head x == maximum v) $ group v\n"}, {"source_code": "import Data.List\nmain=getContents>>=print.snd.maximum.map(\\x->(head x::Int,length x)).group.map read.tail.words"}, {"source_code": "import Data.List\nmain=do\n _<-getLine\n v<-map read.words<$>getLine\n print$foldr(max.length.filter(==maximum v))0$group(v::[Int])"}, {"source_code": "import Data.List\nmain=interact$show.snd.maximum.map(\\x->(read$head x::Int,length x)).group.tail.words"}, {"source_code": "import Data.List\nmain=interact$show.snd.maximum.map(\\x->(head x::Int,length x)).group.map read.tail.words"}, {"source_code": "import Data.List\nmain=do\n v<-map read.tail.words<$>getContents\n print$foldr(max.length.filter(==(maximum v::Int)))0$group v"}, {"source_code": "import Data.List\nmain=do\n _<-getLine\n v<-(map read).words<$>getLine\n print$maximum$map length$filter(\\x->head x==maximum v)$group(v::[Int])"}, {"source_code": "import Data.List\nmain=map read.tail.words<$>getContents>>=(\\v->print$snd$maximum$map(\\x->(head x::Int,length x))$group v)"}, {"source_code": "import Data.List\nmain=do\n _<-getLine\n v<-map read.words<$>getLine\n print$maximum$map(length.filter(==maximum v))$group(v::[Int])"}], "negative_code": [{"source_code": "import Data.List\nmain=do\n v<-map read.words<$>getContents\n print$foldr(max.length.filter(==maximum v))0$group(v::[Int])"}, {"source_code": "import Data.List\nmain=do\n v<-map read.words.tail<$>getContents\n print$foldr(max.length.filter(==maximum v))0$group(v::[Int])"}, {"source_code": "import Data.List\nmain = interact $ show . process . map read . tail. words\nprocess :: [Int] -> Int\nprocess [_] = 1\nprocess x = 1 + (maximum $ map (\\z -> if head z then length z else 0) $ group $ zipWith (==) x $ tail x)\n"}, {"source_code": "import Data.List\nmain=do\n v<-map read.words<$>getContents\n print$foldr(max.length.filter(==maximum v))0$group$tail(v::[Int])"}], "src_uid": "5db2ae5b2c91b29e4fe4a45ab864e3f1"} {"source_code": "module Main where\n \nimport Control.Monad\nimport Data.List as L\nimport Data.Map as M\nimport Data.ByteString.Char8 as C\nimport Data.ByteString as BS\n \nreadInts :: Int -> ByteString -> ([Int],ByteString)\nreadInts n bs =\n L.foldl (\\(ints, bs') _ -> let\n bs'' = C.dropWhile (\\x -> x == ' ' || x == '\\r' || x == '\\n') bs'\n Just (int, bs''') = C.readInt bs''\n in (int : ints, bs''')) ([], bs) [1..n]\n \nmain :: IO ()\nmain = do\n n <- fmap read Prelude.getLine\n input <- BS.getContents\n let (sequences, _) = L.foldl (\\(xs, bs) _ ->\n let ([si], bs') = readInts 1 bs\n (xi, bs'') = readInts si bs'\n in (xi : xs, bs'')) ([], input) [1..n]\n sequences' = L.zip [1..n] $ L.reverse $ L.map L.reverse sequences\n mutations = L.map (\\(i, seqq) ->\n let sum = L.sum seqq\n seqEnum = L.zip [1..(L.length seqq)] seqq\n in [(sum - x, i, ix) | (ix, x) <- seqEnum]) sequences'\n orderedBySum = sortBy (\\(sum,_,_) (sum',_,_) -> compare sum sum') $ Prelude.concat mutations\n groupedMatches = L.groupBy (\\(sum,i,_) (sum',i',_) -> sum == sum' && i == i') orderedBySum\n noDuplicates = L.map L.head groupedMatches\n finalGrouping = L.groupBy (\\(sum,_,_) (sum',_,_) -> sum == sum') noDuplicates\n matches = L.filter ((<=) 2 . L.length) finalGrouping\n if L.null matches then\n Prelude.putStrLn \"NO\"\n else do\n Prelude.putStrLn \"YES\"\n let match = L.take 2 . L.head $ matches\n forM_ match (\\(_,ii,i) -> Prelude.putStrLn $ show ii ++ \" \" ++ show i)", "positive_code": [{"source_code": "module Main where\n\nimport Data.List as L\nimport Data.Map as M\nimport Control.Monad\nimport Data.ByteString.Char8 as C\nimport Data.ByteString as BS\n\nreadInts :: Int -> ByteString -> ([Int],ByteString)\nreadInts n bs =\n L.foldl (\\(ints,bs') _ -> let\n bs'' = C.dropWhile (\\x -> x == ' ' || x == '\\r' || x == '\\n') bs'\n Just (int,bs''') = C.readInt bs''\n in (int:ints,bs''')) ([],bs) [1..n]\n\nmain :: IO ()\nmain = do\n n <- fmap read Prelude.getLine\n input <- BS.getContents\n let (sequences,_) = L.foldl (\\(xs, bs) _ ->\n let ([si],bs') = readInts 1 bs\n (xi,bs'') = readInts si bs'\n in (xi:xs,bs'')) ([],input) [1..n]\n sequences' = L.zip [1..n] $ L.reverse $ L.map L.reverse sequences\n mutations = L.map (\\(i,seqq) ->\n let sum = L.sum seqq\n seqEnum = L.zip [1..(L.length seqq)] seqq\n in [(sum - x,i,ix) | (ix,x) <- seqEnum]) sequences'\n orderedBySum = sortBy (\\(sum,_,_) (sum',_,_) -> compare sum sum') $ Prelude.concat mutations\n groupedMatches = L.groupBy (\\(sum,i,_) (sum',i',_) -> sum == sum' && i == i') orderedBySum\n noDuplicates = L.map L.head groupedMatches\n finalGrouping = L.groupBy (\\(sum,_,_) (sum',_,_) -> sum == sum') noDuplicates\n matches = L.filter ((<=) 2 . L.length) finalGrouping\n if L.null matches then\n Prelude.putStrLn \"NO\"\n else do\n Prelude.putStrLn \"YES\"\n let match = L.take 2 . L.head $ matches\n forM_ match (\\(_,ii,i) -> Prelude.putStrLn $ show ii ++ \" \" ++ show i)\n"}], "negative_code": [], "src_uid": "7561bca5fa2200ce9ae7e30e7076c6ab"} {"source_code": "fn:: String -> Int\nfn str = if existAtEdge then 2 else 4\n where\n existAtEdge = oneExist (head table) || oneExist (last table) || oneExist (map head table) || oneExist (map last table)\n oneExist:: [Char] -> Bool\n oneExist = any (== '1')\n n:: Int\n n = read $ (words $ head ls) !! 0\n m:: Int\n m = read $ (words $ head ls) !! 1\n table:: [[Char]]\n table = map lineEntries (tail ls)\n where\n lineEntries:: String -> [Char]\n lineEntries line = map (!! 0) $ words line\n ls = lines str\n\nmain = do\n input <- getContents\n output <- return $ show $ fn input\n putStrLn output\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\n\ncheck :: [ [ Int ] ] -> Bool\ncheck mat\n = elem 1 (mat !! 0) ||\n elem 1 (mat !! (n - 1)) ||\n elem 1 (map (!! 0) mat) ||\n elem 1 (map (!! (m-1)) mat)\n where\n n = length mat\n m = length (mat !! 0)\n\nmain :: IO ()\nmain = do\n\n [ x, y ] <- map read <$> words <$> getLine\n \n mat <- replicateM x $\n map read <$> words <$> getLine\n \n if check mat\n then print 2\n else print 4"}, {"source_code": "import Data.Tuple\nimport Data.List\ncal ls = let ns = map words $ tail ls\n\t t = transpose ns\n\t edges = (head ns) ++ (last ns) ++ (head t) ++ (last t)\n\t in if (any (\\s ->read s==1) edges) then 2 else 4\n\nmain = interact (show . cal . lines)\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:m:a) = solve' a 1 1\n where\n solve' :: [Int] -> Int -> Int -> Int\n solve' [] _ _ = 4\n solve' (1:ax) i j | i == 1 || i == n = 2\n | j == 1 || j == m = 2\n solve' (_:ax) i j | j == m = solve' ax (i + 1) 1\n | otherwise = solve' ax i (j + 1)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n as <- replicateM n getInts\n\n let\n xys = map fst $ filter ((== 1) . snd) $ zip [(x, y) | x <- [1..n], y <- [1..m]] $ concat as\n\n print $\n if not . null $ filter (\\(x, y) -> x == 1 || x == n || y == 1 || y == m) xys\n then 2\n else 4\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nitof :: Int -> Double\nitof = fromIntegral\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,m] <- readLns\n l <- replicateM n readLns :: IO [[Int]]\n let a = head l\n b = last l\n c = head $ transpose l\n d = last $ transpose l\n if any (==1) $ concat [a,b,c,d] then\n print 2\n else\n print 4\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array (Array, (!), array, bounds)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: Array (Int, Int) Bool -> Int\nsolve array\n | any (array !) [(1,j) | j <- [1..m]] = 2\n | any (array !) [(i,1) | i <- [1..n]] = 2\n | any (array !) [(n,j) | j <- [1..m]] = 2\n | any (array !) [(i,m) | i <- [1..n]] = 2\n | otherwise = 4\n where\n (n, m) = snd $ bounds array\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n xss <- replicateM n reads\n let array = Data.Array.array ((1,1), (n,m)) $ map (\\(i, x) -> ((i `div` m + 1, i `mod` m + 1), x == 1)) $ zip [0..] $ concat xss\n print $ solve array\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n -- _ <- getLine\n l1:board <- lines <$> getContents\n if '1' `elem` (l1 ++ head (reverse board) ++ concatMap (\\(x:xs) -> [x, head $ reverse xs]) board)\n then print 2\n else print 4\n"}], "negative_code": [{"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n -- _ <- getLine\n board <- map ((==1) . read) . words . intercalate \" \" . lines <$> getContents :: IO [Bool]\n let doit candoit (b,i) =\n candoit || (b && ((row `elem` [0,n-1]) || (col `elem` [0,m-1])))\n where row = i `div` n\n col = i `mod` n\n can = foldl doit False $ zip board [0..]\n -- print $ map (\\i -> (i `div` n, i`mod`n)) [0..n*m]\n print (if can then 2 else 4)\n -- cs <- map read . words <$> getLine :: IO [Int]\n -- [x,y] <- map read . words <$> getLine :: IO [Int]\n -- let beginnerSizes = scanl1 (+) cs\n -- numKids = sum cs\n -- intermediateSizes = map (numKids -) beginnerSizes\n -- print (case find (\\(bSize,iSize,_) ->\n -- x <= bSize && bSize <= y && x <= iSize && iSize <= y) $\n -- zip3 beginnerSizes intermediateSizes ([1..] :: [Int]) of\n -- Just (_,_,a) -> a + 1\n -- Nothing -> 0)\n"}], "src_uid": "0d2fd9b58142c4f5282507c916690244"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad.Trans.State.Strict\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport qualified Data.List as L\n\nmain :: IO ()\nmain = do\n [n, _m] <- map read.words <$> getLine\n xds <- map (fromIntegral *** fromIntegral).L.unfoldr (runStateT parseInt2) <$> B.getContents\n print $ solve n xds\n\nsolve :: Int64 -> [(Int64, Int64)] -> Double\nsolve n xds = (fromIntegral . sum $ map diff ds) / fromIntegral n + fromIntegral (sum xs)\n where\n !up = sum[1..n-1]\n !down | odd n = 2 * sum[1..div n 2]\n | otherwise = 2 * sum[1..div n 2] - div n 2\n\n (xs, ds) = unzip xds\n diff d\n | d > 0 = d * up\n | d == 0 = 0\n | otherwise = d * down\n\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nparseInt3 :: Parser (Int, Int, Int)\nparseInt3 = (,,) <$> parseInt <*> parseInt <*> parseInt\n", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ng n = div (n * (n+1)) 2\n\nf::Integer->Integer->Integer\nf d n =\n if d > 0 then\n d * (div (n*(n-1)) 2)\n else\n if mod n 2 == 1 then\n d * ((div n 2) * ((div n 2) + 1))\n else\n d * ((g (div n 2)) + (g ((div n 2) - 1)))\n\n\ndoit [] n r = r\ndoit (x:d:xs) n r =\n doit xs n (r+x*n+(f d n))\n\nsolve::String -> String\nsolve sss =\n let (n:m:s) = map toint $ words sss in\n let r = doit s n 0 in\n (show (((fromInteger r)::Double) / ((fromInteger n)::Double))) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}], "negative_code": [], "src_uid": "1c8423407ea7a0b2647e41392670d6b7"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables, BangPatterns #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, unpack)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.List as L (sort)\n\nreadInt = fst . M.fromJust . C.readInt\n\nmain = do\n (readInt -> n) <- B.getLine\n (map snd . L.sort . (flip zip) [1..] . map readInt . C.words -> xs) <- B.getLine\n (C.unpack -> p) <- B.getLine\n let f ('0':ps) (x:xs) ys rs = f ps xs (x:ys) (x:rs)\n f ('1':ps) xs (y:ys) rs = f ps xs ys (y:rs)\n f _ _ _ rs = reverse rs\n putStrLn . unwords . map show $ f p xs [] []\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport Control.Monad\nimport Data.List\nimport qualified Data.IntMap.Strict as M\n\n\nmain = getLine >> liftM2 solve (fmap (fmap read . words) getLine) (fmap (map (== '0')) getLine) >>= putStr . unwords . map show\n\nsolve ws = snd . mapAccumL (flip go) (M.fromList $ zip ws [(1 :: Int)..], M.empty)\n where\n go False (e, M.deleteFindMax -> ((_, i), o)) = ((e, o), i)\n go True (M.deleteFindMin -> (r@(_, i), e), uncurry M.insert r -> o) = ((e, o), i)\n"}, {"source_code": "import Data.List\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> String -> [Int]\nsolve [] [] [] = []\nsolve ((valA, indA) : tailA) b ('0' : tailS) = indA : solve tailA ((valA, indA) : b) tailS\nsolve a ((valB, indB) : headB) ('1' : tailS) = indB : solve a headB tailS\nsolve _ _ _ = []\n\nmain = do\n s <- getLine\n let n = read s :: Int\n s <- getLine\n let weights = map (read::String->Int) (words s)\n s <- getLine\n let arr = sort $ zip weights [1..]\n let ans = solve arr [] s\n putStrLn $ intercalate \" \" $ map show ans\n "}, {"source_code": "\n\n{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nindexed :: Int -> [a] -> [(a, Int)]\nindexed _ [] = []\nindexed i (x:xs) = (x, i) : (indexed (succ i) xs)\n\nsolve :: String -> [(Int, Int)] -> [(Int, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (x:xs) [] (y:ys) = (snd y) : (solve xs [] ys)\nsolve (x:xs) (y:ys) [] = (snd y) : (solve xs ys (return y))\nsolve (x:xs) free@(y:ys) taken@(z:zs)\n | x == '0' = (snd y) : (solve xs ys (y : taken))\n | x == '1' = (snd z) : (solve xs free zs)\n\nmain :: IO ()\nmain = do\n\t[n] <- getInts\n\tw <- getInts\n\ts <- getLine\n\tputStrLn $ intercalate \" \" $ map show $ solve s (sort (indexed 1 w)) []"}, {"source_code": "module Main (main) where\n\nimport Data.List (maximumBy, minimumBy, sortBy)\nimport qualified Data.Map.Lazy as M\nimport Data.Map.Lazy (fromList)\n\ngetIntegers :: IO [Int]\ngetIntegers = fmap (map read . words) getLine\n\n-- seatOccupation :: [Bool] -> [(Int, (Int, Int))] -> [Int]\n-- seatOccupation [] _ = []\n-- seatOccupation (isExtravert:xs) currentSeating =\n-- let (n, (weight, taken)) = selectWeight . selectOccupancy $ currentSeating\n-- where selectWeight = (if isExtravert then maximumBy else minimumBy)\n-- (\\(_, (w, _)) (_, (w', _)) -> compare w w')\n-- selectOccupancy = filter (\\(_, (_, taken)) ->\n-- (isExtravert && taken == 1)\n-- || ((not isExtravert) && taken == 0))\n-- newSeating toList . insert n (weight, taken + 1) . fromList $ currentSeating\n-- in n : seatOccupation xs newSeating\n\n-- main' :: IO ()\n-- main' = do\n-- _ <- getLine\n-- seatWidths <- getIntegers\n-- passengers <- fmap (fmap (== '1')) $ getLine\n-- let rows = fmap (\\(n, w) -> (n, (w, 0)))\n-- . sortBy (\\(_, w) (_, w') -> compare w w')\n-- . zip [1..] $ seatWidths\n-- mapM_ (\\n -> putStr $ show n ++ \" \") $ seatOccupation passengers rows\n\n\nselectSeats :: [Bool] -> Int -> [Int] -> [Int]\nselectSeats [] _ _ = []\nselectSeats (isExtravert:nextPassengers) nextFreeRow introvertRows =\n if isExtravert then\n let (row:newIntrovertRows) = introvertRows\n in row : selectSeats nextPassengers nextFreeRow newIntrovertRows\n else\n nextFreeRow : selectSeats nextPassengers (nextFreeRow + 1) (nextFreeRow : introvertRows)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n seatWidths <- getIntegers\n passengers <- fmap (fmap (== '1')) getLine\n let rows = map (\\(n, _) -> n)\n . sortBy (\\(_, w) (_, w') -> compare w w')\n . zip [1..] $ seatWidths\n weightedOrder = selectSeats passengers 1 []\n weightedToOriginal = zip [1..] rows\n restoredOrder = map (\\nW ->\n let (Just n) = M.lookup nW $ M.fromList weightedToOriginal\n in n) weightedOrder\n in mapM_ (\\n -> putStr $ (show n) ++ \" \") restoredOrder"}], "negative_code": [{"source_code": "module Main (main) where\n\nimport Data.List (maximumBy, minimumBy, sortBy)\nimport Data.Map.Lazy (insert, toList, fromList)\n\ngetIntegers :: IO [Int]\ngetIntegers = fmap (map read . words) getLine\n\nseatOccupation :: [Bool] -> [(Int, (Int, Int))] -> [Int]\nseatOccupation [] _ = []\nseatOccupation (isExtravert:xs) currentSeating =\n let (n, (weight, taken)) = selectWeight . selectOccupancy $ currentSeating\n where selectWeight = (if isExtravert then maximumBy else minimumBy)\n (\\(_, (w, _)) (_, (w', _)) -> compare w w')\n selectOccupancy = filter (\\(_, (_, taken)) ->\n (isExtravert && taken == 1)\n || ((not isExtravert) && taken == 0))\n newSeating = toList . insert n (weight, taken + 1) . fromList $ currentSeating\n in n : seatOccupation xs newSeating\n\nmain :: IO ()\nmain = do\n _ <- getLine\n seatWidths <- getIntegers\n passengers <- fmap (fmap (== '1')) $ getLine\n let rows = fmap (\\(n, w) -> (n, (w, 0)))\n . zip [1..] $ seatWidths\n print $ seatOccupation passengers rows"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nindexed :: Int -> [a] -> [(a, Int)]\nindexed _ [] = []\nindexed i (x:xs) = (x, i) : (indexed (succ i) xs)\n\nsolve :: String -> [(Int, Int)] -> [(Int, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (x:xs) [] (y:ys) = (snd y) : (solve xs [] ys)\nsolve (x:xs) (y:ys) [] = (snd y) : (solve xs ys (return y))\nsolve (x:xs) free@(y:ys) taken@(z:zs)\n | x == '0' = (snd y) : (solve xs ys (y : taken))\n | x == '1' = (snd z) : (solve xs free zs)\n\nmain :: IO ()\nmain = do\n\t[n] <- getInts\n\tw <- getInts\n\ts <- getLine\n\tputStrLn $ intersperse ' ' $ concatMap show $ solve s (sort (indexed 1 w)) []"}], "src_uid": "161009edb8e3d438cdd8c0d1e202f783"} {"source_code": "import Control.Monad (replicateM_)\nimport Data.Int (Int64)\n\nsolve :: [Int64] -> Int64\nsolve li = sum . map (max 0) $ zipWith (-) li (tail li)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n print (solve a)\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n print $ sum $ map (max 0) $ zipWith (-) as (tail as)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nreadInt64B8 :: B8.ByteString -> Int64\nreadInt64B8 = fromInteger . fst . fromJust . B8.readInteger\n\n\nsolve :: Int -> [Int64] -> Int64\nsolve n hs = sum steps\n where\n steps = map (\\(x, y) -> max 0 $ x - y) adjacentHs\n adjacentHs = zip hs $ tail hs\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n hs <- map readInt64B8 <$> B8.words <$> B8.getLine\n let answer = solve n hs\n printf \"%s\\n\" $ show answer\n"}], "negative_code": [], "src_uid": "0bd06900e42db9f83cdd43c24da6686e"} {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Graph\nimport Data.Array.Unboxed\nimport Data.Int\nimport Data.Tree\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n cs <- replicateM n poi\n ps <- replicateM m $ liftM2 (,) poi poi\n return $ show $ solve n cs ps\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n cs0 = sum . map (minimum . map (cs!) . flatten) . components . buildG (1, n)\n where cs = listArray (1, n) $ map fromIntegral cs0 :: UArray Int Int64\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Graph\nimport Data.Array ((!))\nimport qualified Data.Array as A\nimport qualified Data.Tree as T\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) <$> C.words <$> C.getLine\n\nreadIntegers :: IO [Integer]\nreadIntegers = map (fst . fromJust . C.readInteger) <$> C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n amounts <- A.listArray (1, n) <$> readIntegers\n friends <- replicateM m readInts\n let f = dff $ buildG (1, n) $ [x | [a, b] <- friends, x <- [(a, b), (b, a)]]\n let xs = map T.flatten f\n let ans = sum $ map (minimum . map (amounts!)) xs\n print ans"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Graph\nimport Data.Array ((!))\nimport qualified Data.Array as A\nimport qualified Data.Tree as T\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) <$> C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n amounts <- A.listArray (1,n) <$> readInts\n friends <- replicateM m readInts\n let f = dff $ buildG (1, n) $ map (\\[a, b] -> (a, b)) friends\n let xs = map T.flatten f\n let ans = sum $ map (minimum . map (\\x -> amounts ! x)) xs\n print ans\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Graph\nimport Data.Array ((!))\nimport qualified Data.Array as A\nimport qualified Data.Tree as T\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) <$> C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n amounts <- A.listArray (1, n) <$> readInts\n friends <- replicateM m readInts\n let f = dff $ buildG (1, n) $ [x | [a, b] <- friends, x <- [(a, b), (b, a)]]\n let xs = map T.flatten f\n let ans = sum $ map (minimum . map (amounts!)) xs\n print ans\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Graph\nimport Data.Array ((!))\nimport qualified Data.Array as A\nimport qualified Data.Tree as T\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) <$> C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n amounts <- A.listArray (0, n) <$> (0:) <$> readInts\n friends <- replicateM m readInts\n let f = dff $ buildG (0, n) $ map (\\[a, b] -> (a, b)) friends\n let xs = map T.flatten f\n let ans = sum $ map (minimum . map (\\x -> amounts ! x)) xs\n print ans\n"}], "src_uid": "9329cb499f003aa71c6f51556bcc7b05"} {"source_code": "{-# OPTIONS_GHC -XStrict -XStrictData #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\ngetRanges :: Graph -> (UArray Int Int, UArray Int Int)\r\ngetRanges g = runST $ do\r\n s <- newArray (bounds g) 0 :: ST s (STUArray s Int Int)\r\n e <- newArray (bounds g) 0 :: ST s (STUArray s Int Int)\r\n cur <- newSTRef 1\r\n let dfs x = do\r\n i <- readSTRef cur\r\n writeArray s x i\r\n modifySTRef' cur (+1)\r\n forM_ (g!x) dfs\r\n readSTRef cur >>= \\t -> writeArray e i t\r\n dfs 1\r\n rs <- unsafeFreezeSTUArray s\r\n re <- unsafeFreezeSTUArray e\r\n return (rs, re)\r\n\r\nsolve :: Graph -> UArray Int Int -> UArray Int Int -> Int\r\nsolve g ss ee = dfs IS.empty 0 1\r\n where\r\n dfs w r x =\r\n let s = ss ! x\r\n e = ee ! s\r\n a = IS.lookupLT s w\r\n b = IS.lookupGT s w\r\n (w',r') =\r\n if maybe True (>= e) b then\r\n case a of\r\n Just a ->\r\n if ee ! a > s then\r\n (IS.delete a . IS.insert s $ w, r)\r\n else\r\n (IS.insert s w, r+1)\r\n Nothing -> (IS.insert s w, r+1)\r\n else\r\n (w,r)\r\n in\r\n maximum $ r' : map (dfs w' r') (g ! x)\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine\r\n let readG = buildG (1,n) . flip zip [2..] . map parseInt . BS.words <$> BS.getLine\r\n g1 <- readG\r\n g2 <- readG\r\n let (s,e) = getRanges g2\r\n print $ solve g1 s e\r\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -XStrict -XStrictData #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\ngetRanges :: Graph -> (UArray Int Int, UArray Int Int)\r\ngetRanges g = runST $ do\r\n s <- newArray (bounds g) 0 :: ST s (STUArray s Int Int)\r\n e <- newArray (bounds g) 0 :: ST s (STUArray s Int Int)\r\n cur <- newSTRef 1\r\n let dfs x = do\r\n i <- readSTRef cur\r\n writeArray s x i\r\n modifySTRef' cur (+1)\r\n forM_ (g!x) dfs\r\n readSTRef cur >>= \\t -> writeArray e i t\r\n dfs 1\r\n rs <- unsafeFreezeSTUArray s\r\n re <- unsafeFreezeSTUArray e\r\n return (rs, re)\r\n\r\nsolve :: Graph -> UArray Int Int -> UArray Int Int -> Int\r\nsolve g ss ee = dfs Set.empty 1\r\n where\r\n dfs w x =\r\n let s = ss ! x\r\n e = ee ! s\r\n a = Set.lookupLT s w\r\n b = Set.lookupGT s w\r\n w' =\r\n if maybe True (>= e) b then\r\n case a of\r\n Just a ->\r\n if ee ! a > s then\r\n Set.delete a . Set.insert s $ w\r\n else\r\n Set.insert s w\r\n Nothing -> Set.insert s w\r\n else\r\n w\r\n in\r\n maximum $ Set.size w' : map (dfs w') (g ! x)\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine\r\n let readG = buildG (1,n) . flip zip [2..] . map parseInt . BS.words <$> BS.getLine\r\n g1 <- readG\r\n g2 <- readG\r\n let (s,e) = getRanges g2\r\n print $ solve g1 s e\r\n"}], "negative_code": [], "src_uid": "dc1a20d875572a3f45a9844030b0fcf4"} {"source_code": "import Data.Array.Unboxed\nn = 3000\nf m=(sum[a!(2*x-z,2*y-w)|(x,y)<-m,(z,w)<-m]-length m)`div`2 where a=accumArray(+)0((-n,-n),(n,n))$zip m$repeat 1::UArray(Int,Int)Int\nt[x,y]=(x,y)\nmain=interact$show.f.map(t.map read.words).tail.lines\n", "positive_code": [{"source_code": "import Data.Array.Unboxed\nm = 3000\ntop s = (x, y) where [x, y] = map read $ words s\nsolve ps = (sum [a ! (2*x-z, 2*y-w) | (x,y) <- ps, (z,w) <- ps] - length ps) `div` 2 where a = accumArray (+) 0 ((-m, -m), (m, m)) (zip ps $ repeat 1) :: UArray (Int, Int) Int\nmain = print . solve . map top . tail . lines =<< getContents\n"}, {"source_code": "import Data.Array.Unboxed\nn=3000\nf m=sum[a!(x+x-z,y+y-w)|p@(x,y)<-m,q@(z,w)<-m,p Int\nsolve points = length [undefined | (x1, y1) <- points, (x2, y2) <- points,\n (x1,y1) < (x2,y2),\n even x1 == even x2,\n even y1 == even y2,\n member (quot (x1 + x2) 2, quot (y1 + y2) 2) pointsMap]\n where\n pointsMap :: PointsMap\n pointsMap = fromList [(k, undefined) | k <- points] \n\nmain :: IO ()\nmain = do\n n <- readLn\n points <- mapM (const getPoint) [1..n]\n print $ solve points\n"}, {"source_code": "import Data.Array.Unboxed\nn=3000\nf m=sum[a!(x+x-z,y+y-w)|p@(x,y)<-m,q@(z,w)<-m,p IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = do\n (wr, hr) <- pair int int\n (x1, y1) <- pair int int\n (x2, y2) <- pair int int\n (w, h) <- pair int int\n let wt = x2 - x1\n let ht = y2 - y1\n let inf = 10^9\n let dw = if wt + w > wr then inf else w - max x1 (wr - x2)\n let dh = if ht + h > hr then inf else h - max y1 (hr - y2)\n let ans = max 0 $ min dw dh\n return . show $ if ans == inf then -1 else ans\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}], "negative_code": [{"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [w, h] <- readMany :: IO [Int]\r\n [x1, y1, x2, y2] <- readMany :: IO [Int]\r\n [w', h'] <- readMany :: IO [Int]\r\n let isect (l1, h1) (l2, h2) = max 0 $ min h1 h2 - max l1 l2\r\n fitW = w' + x2 - x1 <= w\r\n fitH = h' + y2 - y1 <= h\r\n chk xx yy | ix > 0 && iy > 0 = [ix | fitW] ++ [iy | fitH]\r\n | otherwise = [0]\r\n where ix = isect (x1, x2) xx\r\n iy = isect (y1, y2) yy\r\n rs = chk (0, w') (0, h')\r\n ++ chk (w - w', w) (0, h')\r\n ++ chk (0, w') (h - h', h)\r\n ++ chk (w - w', w) (h - h', h)\r\n print $ if null rs then -1 else minimum rs\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [w, h] <- readMany :: IO [Int]\r\n [x1, y1, x2, y2] <- readMany :: IO [Int]\r\n [w', h'] <- readMany :: IO [Int]\r\n let isect (l1, h1) (l2, h2) = max 0 $ min h1 h2 - max l1 l2\r\n fitW = w' + x2 - x1 <= w\r\n fitH = h' + y2 - y1 <= h\r\n chk xx yy | ix + iy > 0 = [ix | fitW] ++ [iy | fitH]\r\n | otherwise = [0]\r\n where ix = isect (x1, x2) xx\r\n iy = isect (y1, y2) yy\r\n rs = chk (0, w') (0, h')\r\n ++ chk (w - w', w) (0, h')\r\n ++ chk (0, w') (h - h', h)\r\n ++ chk (w - w', w) (h - h', h)\r\n print $ if null rs then -1 else minimum rs\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [w, h] <- readMany :: IO [Int]\r\n [x1, y1, x2, y2] <- readMany :: IO [Int]\r\n [w', h'] <- readMany :: IO [Int]\r\n let isect (l1, h1) (l2, h2) = max 0 $ min h1 h2 - max l1 l2\r\n chkW xx = [isect (x1, x2) xx | w' + x2 - x1 <= w]\r\n chkH yy = [isect (y1, y2) yy | h' + y2 - y1 <= h]\r\n rs = chkW (0, w') ++ chkH (0, h')\r\n ++ chkW (w - w', w) ++ chkH (0, h')\r\n ++ chkW (0, w') ++ chkH (h - h', h)\r\n ++ chkW (w - w', w) ++ chkH (h - h', h)\r\n ans | null rs = -1\r\n | otherwise = minimum rs\r\n print ans\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "src_uid": "29fd4c77a2f28478ebce98dfc6496aac"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nmodule Main (main) where\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Bits\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.State.Strict (StateT)\nimport qualified Control.Monad.Trans.State.Strict as StateT\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\n \n\ngetNewLine :: SIO ByteString\ngetNewLine = (lift $ C.hGetLine stdin) >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n \ngetRemain :: ByteString -> SIO ByteString\ngetRemain b = let bns = C.dropWhile isSpace b in\n if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)\n else return bns\n \ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n \ntype SIO a = StateT ByteString IO a\n \nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n \ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n \ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n \nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n \ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n \ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n \ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n \ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n \ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n \nget :: IOInteract a => SIO a\nget = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get\nput :: IOInteract a => a -> SIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> SIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: SIO ()\nflush = lift (hFlush stdout)\n \nmain :: IO ()\nmain = StateT.evalStateT main_ C.empty\n \nmain_ :: SIO ()\n-------------------------------------------- template ------------------------------------------------------\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: SIO ()\nf1 = do\n (n, x, y) <- liftM3 (,,) get get get\n putln $ f2 n x y\n\n\nf2 :: Int64 -> Int64 -> Int64 -> [Int64]\nf2 n x y = let d = y - x in\n let dividers = f3 d in\n let candidate = map (\\d ->\n let cnt = div (y - x) d + 1 in\n if cnt > n then Nothing\n else\n let k = div (x - 1) d in\n if cnt + k >= n then Just [y-(n-1)*d,y-(n-2)*d..y]\n else let max = y + (n - (cnt + k)) * d in Just [max-(n-1)*d, max-(n-2)*d..max]\n ) dividers in\n let maxc = foldl (\\b a -> case a of\n Nothing -> b\n Just aa -> if maximum aa > maximum b then b else aa)\n [1000000000000000] candidate\n in\n maxc\n\n \nf3 :: Int64 -> [Int64]\nf3 d =\n let aux i = if i > d then [] else if mod d i == 0 then i : aux (i + 1) else aux (i + 1) in\n aux 1", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nfactors :: Int -> [Int]\nfactors n = [x | x <- [1..n], mod n x == 0]\n\nsolve :: Int -> Int -> Int -> [Int]\nsolve n x y = let\n opts = do\n inc <- factors (y - x)\n let\n decrs = take n $ takeWhile (> 0) $ iterate (subtract inc) y\n start = minimum decrs\n [take n (iterate (+ inc) start) | start <= x]\n in head . sort $ map reverse opts\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, x, y] <- map read . words <$> getLine\n putStrLn $ unwords (map show (solve n x y))\n"}], "negative_code": [], "src_uid": "ca9d97e731e86cf8223520f39ef5d945"} {"source_code": "--module Test where\nimport Data.List\n\nsolve :: IO ()\nsolve = do\n nLine <- getLine\n let n = read nLine :: Int\n line <- getLine\n let list = sort $ read <$> words line :: [Int]\n let ans = getAns list\n putStrLn $ show ans\n\ngetAns :: [Int] -> Int\ngetAns [] = 0\ngetAns (x : xs) = if sz == 0 then 0\n else 1 + getAns (drop sz list) where\n sz = tmp x 1 xs\n list = (x : xs)\n\ntmp :: Int -> Int -> [Int] -> Int\ntmp last sz list | sz >= last = sz\n | otherwise = if list == [] then 0 \n else tmp (head list) (sz + 1) (tail list)\n\n\nmain :: IO ()\nmain = do\n line <- getLine\n let t = read line :: Int\n sequence_ (take t $ repeat solve)", "positive_code": [{"source_code": "import qualified Data.List as L\n\ntype Long = Int\n\nsolve :: [Int] -> Int\nsolve es = formGroups (L.sort es) 0\n\n\nformGroups :: [Int] -> Int -> Int\nformGroups [] _ = 0\nformGroups (a:rest) curSize\n | a <= curSize + 1 = 1 + formGroups rest 0\n | otherwise = formGroups rest (curSize+1)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n es <- readWords\n print $ solve es\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n t <- read <$> getLine\n replicateM_ t test\n\ntest = do\n getLine\n es <- map read . words <$> getLine\n print $ solve 1 $ sort es\n\nsolve _ [] = 0\nsolve c (e:es)\n | e <= c = 1 + solve 1 es\n | otherwise = solve (c + 1) es"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readI\n replicateM_ t $ do\n n <- readI\n es <- readIs\n print $ solve n es\n\nreadI :: IO Int\nreadI = read <$> getLine\n\nreadIs :: IO [Int]\nreadIs = fmap read . words <$> getLine\n\nsolve :: Int -> [Int] -> Int\nsolve n es = go (sort es) [] n 0 0\n where\n go es0 (c:_) en cn result | c == cn = go es0 [] en 0 (result+1)\n go (e:es) _ en _ result | e > en = result\n go (e:es) cs0 en cn result = go es (e:cs0) en (cn+1) result\n go [] _ _ _ result = result\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readI\n replicateM_ t $ do\n n <- readI\n es <- readIs\n print $ solve n es\n\nreadI :: IO Int\nreadI = read <$> getLine\n\nreadIs :: IO [Int]\nreadIs = fmap read . words <$> getLine\n\nsolve :: Int -> [Int] -> Int\nsolve n es = go n (sortBy (flip compare) es) (0 :: Int)\n where\n go n [] result = result\n go n (e:_) result | n < e = result\n go n (e:es) result = go (n-e) (drop (e-1) es) (result+1)\n"}, {"source_code": "\ntype Long = Int\n\nsolve :: Int -> [Int] -> Int\nsolve n es = formGroups es 0\n\n\nformGroups :: [Int] -> Int -> Int\nformGroups [] _ = 0\nformGroups (a:rest) curSize\n | a <= curSize + 1 = 1 + formGroups rest 0\n | otherwise = formGroups rest (curSize+1)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readWords\n es <- readWords\n print $ solve n es\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}], "src_uid": "8e766dea94dc2033ba2d5759d7e5cd80"} {"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n [c, m, x] <- map read . words <$> getLine\n print $ solve c m x\n\nsolve :: Int -> Int -> Int -> Int\nsolve c' m' x' = mx + oth\n where oth = if\n | c == 0 || m == 0 -> 0\n | 2 * c < m -> c\n | 2 * m < c -> m\n | otherwise -> (c + m) `div` 3\n mx = minimum [c', m', x']\n (c, m, x) = (c' - mx, m' - mx, x' - mx)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let n :: Int\n (n:xs) = map read $ words input\n queries = bythree xs\n answers = map solve' queries\n in intercalate \"\\n\" $ map show answers\n\nbythree :: [Int] -> [(Int, Int, Int)]\nbythree [] = []\nbythree (a:b:c:xs) = (a, b, c):(bythree xs)\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (a, b, c) =\n let base = minimum (a:b:c:[])\n a' = a - base\n b' = b - base\n c' = c - base\n cleft = c == base\n in if cleft then\n base + min (div (a' + b') 3) (min a' b')\n else\n base\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let n :: Int\n (n:xs) = map read $ words input\n queries = bythree xs\n answers = map solve' queries\n in intercalate \"\\n\" $ map show answers\n\nbythree :: [Int] -> [(Int, Int, Int)]\nbythree [] = []\nbythree (a:b:c:xs) = (a, b, c):(bythree xs)\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (a, b, c) =\n let base = minimum (a:b:c:[])\n a' = a - base\n b' = b - base\n c' = c - base\n cleft = c == base\n in if cleft then\n base + (div (a' + b') 3)\n else\n base\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n [c, m, x] <- map read . words <$> getLine\n print $ solve c m x\n\nsolve :: Int -> Int -> Int -> Int\nsolve c m x = h c m x 0\n where h c m x acc\n | c == 0 || m == 0 || c + m + x < 3 = acc\n | x /= 0 = h (c - 1) (m - 1) (x - 1) (acc + 1)\n | c > m = h (c - 2) (m - 1) 0 (acc + 1)\n | otherwise = h (c - 1) (m - 1) 0 (acc + 1)\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n [c, m, x] <- map read . words <$> getLine\n print $ solve c m x\n\nsolve :: Int -> Int -> Int -> Int\nsolve c m x = mx + h (c - mx) (m - mx) (x - mx) 0\n where h c m x acc\n | c == 0 || m == 0 || c + m + x < 3 = acc\n | c > 2 * m = 2 * m\n | 2 * c > m = 2 * c\n | c > m = h (c - 2) (m - 1) 0 (acc + 1)\n | otherwise = h (c - 1) (m - 2) 0 (acc + 1)\n mx = maximum [c, m, x]\n"}], "src_uid": "b18dac401b655c06bee331e71eb3e4de"} {"source_code": "import Data.IntSet (IntSet, empty, member, fromList, union)\r\n\r\ncalcH :: Int -> Int -> [Int]\r\ncalcH n a = if a > n\r\n then []\r\n else (a: calcH n (2 * a))\r\n\r\ncalcHH :: Int -> IntSet -> Int -> [Int]\r\ncalcHH n a x = if x > n\r\n then []\r\n else if x `member` a \r\n then calcHH n a (x + 1)\r\n else let a1 = calcH n x in a1 ++ calcHH n (a `union` ( fromList a1)) (x + 1)\r\n\r\ncalc :: Int -> [Int]\r\ncalc n = calcHH n empty 1\r\n\r\npr :: [Int] -> IO ()\r\npr a = putStrLn $ concat $ map (\\x -> show x ++ \" \") a\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n n <- readLn :: IO Int\r\n print 2\r\n pr $ calc n\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n--\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> (Int, [Int])\nsolve n = (d, ps)\n where\n d = 2\n ps = solve' $ IS.fromList [1 .. n]\n\n solve' :: IS.IntSet -> [Int]\n solve' is = if (IS.size is == 0)\n then [] \n else ts ++ solve' leastIs\n where\n i = IS.findMin is\n ts = L.takeWhile (<= n) $ L.iterate (* d) i\n leastIs = L.foldl' (flip IS.delete) is ts\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n let (d, ps) = solve n\n printf \"%d\\n\" d\n forM_ ps $ printf \"%d \"\n putStrLn \"\"\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Maybe\r\nimport Data.Set qualified as Set\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr . showAns . solve) tcs\r\n\r\nshowAns xs = unlines [\"2\", unwords . map show $ xs]\r\n\r\nsolve n = concat . reverse . snd . fst . fromJust . L.find (Set.null . snd) . iterate (step n) $ ini\r\n where\r\n ini = ((Set.empty, []), Set.fromList nums)\r\n nums = [1..n] :: [Int]\r\n\r\nstep n ((yset0,ys0), xset0) = ((yset0 `Set.union` eset,\r\n es : ys0),\r\n xset0 Set.\\\\ eset)\r\n where\r\n h = Set.elemAt 0 xset0\r\n es = filter (`Set.notMember`yset0) . takeWhile (<=n) . iterate (*2) $ h\r\n eset = Set.fromList es"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Maybe\r\nimport Data.IntSet qualified as Set\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr . showAns . solve) tcs\r\n\r\nshowAns xs = unlines [\"2\", unwords . map show $ xs]\r\n\r\nsolve n = concat . reverse . snd . fst . fromJust . L.find (Set.null . snd) . iterate (step n) $ ini\r\n where\r\n ini = ((Set.empty, []), Set.fromList nums)\r\n nums = [1..n] :: [Int]\r\n\r\nstep n ((yset0,ys0), xset0) = ((yset1, diff : ys0),\r\n xset1)\r\n where\r\n h = Set.findMin xset0\r\n ((yset1, diff), xset1)\r\n | (2*h > n) = ((Set.empty, Set.toList xset0), Set.empty )\r\n | otherwise = ((yset0 `Set.union` eset, es ), xset0 Set.\\\\ eset)\r\n eset = Set.fromDistinctAscList es\r\n es = filter (`Set.notMember`yset0) . takeWhile (<=n) . iterate (*2) $ h\r\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: Int -> (Int, [Int])\r\nsolve n = (2, concat [takeWhile (<= n) $ iterate (* 2) m | m <- [1, 3 .. n]])\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n n <- readLn\r\n let (d, nums) = solve n\r\n print d\r\n putStrLn . unwords $ map show nums\r\n\r\nmain :: IO ()\r\nmain = readLn >>= (`replicateM_` testCase)"}], "negative_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow hiding (loop)\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.IntSet qualified as Set\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr.showAns.solve) tcs\r\n\r\nshowAns xs = unlines [\"2\", unwords . map show $ xs]\r\n\r\nsolve n = for2 ++ remdr\r\n where\r\n for2 = concat . takeWhile (not.null) . ([1]:) . map (takeWhile (<=n) . iterate (*2)) $ primes\r\n remdr = Set.toList . (Set.\\\\ for2set) . Set.fromList $ [1..n]\r\n for2set = Set.fromList for2\r\n\r\n----------------------------\r\nprimes :: [Int]\r\nprimes = ppp where ppp = 2 : 3 : minus [5,7..] (unionAll [[p*p, p*p+2*p..] | p <- tail ppp])\r\nminus :: Ord a => [a] -> [a] -> [a]\r\nminus = minusBy compare\r\nminusBy :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\r\nminusBy cmp = loop\r\n where\r\n loop [] _ys = []\r\n loop xs [] = xs\r\n loop (x:xs) (y:ys)\r\n = case cmp x y of\r\n LT -> x : loop xs (y:ys)\r\n EQ -> loop xs ys\r\n GT -> loop (x:xs) ys\r\nunionAll :: Ord a => [[a]] -> [a]\r\nunionAll = unionAllBy compare\r\nunionAllBy :: (a -> a -> Ordering) -> [[a]] -> [a]\r\nunionAllBy cmp = serve . foldt union' (Crowd []) . vips\r\n where\r\n msg = \"Data.List.Ordered.unionAllBy: the heads of the lists are not sorted\"\r\n\r\n union' (VIP x xs) ys\r\n = VIP x $ case ys of\r\n Crowd _ -> union' xs ys\r\n VIP y yt -> case cmp x y of\r\n LT -> union' xs ys\r\n EQ -> union' xs yt\r\n GT -> error msg\r\n union' (Crowd []) ys = ys\r\n union' (Crowd xs) (Crowd ys) = Crowd (unionBy cmp xs ys)\r\n union' xs@(Crowd (x:xt)) ys@(VIP y yt)\r\n = case cmp x y of\r\n LT -> VIP x (union' (Crowd xt) ys)\r\n EQ -> VIP x (union' (Crowd xt) yt)\r\n GT -> VIP y (union' xs yt)\r\ndata People a = VIP a (People a) | Crowd [a]\r\nserve (VIP x xs) = x:serve xs\r\nserve (Crowd xs) = xs\r\nfoldt :: (a -> a -> a) -> a -> [a] -> a\r\nfoldt plus zero = loop\r\n where\r\n loop [] = zero\r\n loop (x:xs) = x `plus` loop (pairs xs)\r\n\r\n pairs (x:y:zs) = plus x y : pairs zs\r\n pairs zs = zs\r\nvips xss = [ VIP x (Crowd xs) | (x:xs) <- xss ]\r\nunionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\r\nunionBy cmp = loop\r\n where\r\n loop [] ys = ys\r\n loop xs [] = xs\r\n loop (x:xs) (y:ys)\r\n = case cmp x y of\r\n LT -> x : loop xs (y:ys)\r\n EQ -> x : loop xs ys\r\n GT -> y : loop (x:xs) ys\r\n----------------------------\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr . showAns 2 . solve 2) tcs\r\n\r\nshowAns d xs = unlines [show (d::Int), unwords . map show $ xs]\r\n\r\nsolve d n = ds ++ os\r\n where\r\n (ds, os) = L.partition isD inds\r\n isD x = (x == 1 || x`mod`d == 0)\r\n inds = [1..n] :: [Int]\r\n"}, {"source_code": "calcH :: Int -> Int -> [Int]\r\ncalcH n a = if a > n\r\n then []\r\n else (a: calcH n (2 * a))\r\n\r\ncalcHH :: Int -> [Int] -> Int -> [Int]\r\ncalcHH n a x = if x > n\r\n then []\r\n else if x `elem` a \r\n then calcHH n a (x + 1)\r\n else (x: calcHH n a (x + 1))\r\n\r\ncalc :: Int -> [Int]\r\ncalc n = let a = calcH n 1 in a ++ calcHH n a 1\r\n\r\npr :: [Int] -> IO ()\r\npr a = putStrLn $ concat $ map (\\x -> show x ++ \" \") a\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n n <- readLn :: IO Int\r\n print 2\r\n pr $ calc n\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n"}], "src_uid": "3b9380ca571dbf3e24fc1b1c8b91790b"} {"source_code": "import Data.Traversable (mapAccumL)\nimport Control.Arrow (second)\nimport Data.Functor ((<$>))\nimport Data.List (sort)\n\nfun :: Int -> Int -> (Int, Int)\nfun a x | 2 * a >= x = (max a x, 0)\n | otherwise = second (+1) $ fun (2 * a) x\n\nmain = do\n [_, k] <- map read <$> words <$> getLine\n xs <- sort <$> map read <$> words <$> getLine\n putStrLn $ show $ sum $ snd $ mapAccumL fun k xs\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n xs <- fmap readInts B.getLine\n print $ solve k xs\n\nsolve k = snd . foldl (\\(!t, !c) x -> if x > 2 * t then (x, c + ceiling (logBase 2 $ fromIntegral x / 2 / fromIntegral t)) else (max x t, c)) (k, 0) . sort\n\n\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\ntype MaxSolvedDifficulty = Int\ntype DecoforcesProblems = [Int]\ntype Accum = Int\n\nf :: MaxSolvedDifficulty -> DecoforcesProblems -> Accum -> Accum\nf k (x:xs) acc\n | x <= k*2 = f (max x k) xs acc\n | otherwise = f (k*2) (x:xs) (acc + 1)\n\nf _ [] acc = acc\n\nmain = interact (show . (\\[[_, k], a] -> f k (sort a) 0) . (map (map (read :: String -> Int) . words) . lines))"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n xs <- fmap readInts B.getLine\n print $ solve k xs\n\nsolve k = snd . foldl (\\(!t, !c) x -> if x > 2 * t then (x, c + 1) else (x, c)) (k, 0) . sort\n\n\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "import Data.Traversable (mapAccumL)\nimport Control.Arrow (second)\nimport Data.Functor ((<$>))\n\nfun :: Int -> Int -> (Int, Int)\nfun a x | 2 * a >= x = (a, 0)\n | otherwise = second (+1) $ fun (2 * a) x\n\nmain = do\n [_, k] <- map read <$> words <$> getLine\n xs <- map read <$> words <$> getLine\n putStrLn $ show $ sum $ snd $ mapAccumL fun k xs\n"}, {"source_code": "import Data.Traversable (mapAccumL)\nimport Control.Arrow (second)\nimport Data.Functor ((<$>))\nimport Data.List (sort)\n\nfun :: Int -> Int -> (Int, Int)\nfun a x | 2 * a >= x = (a, 0)\n | otherwise = second (+1) $ fun (2 * a) x\n\nmain = do\n [_, k] <- map read <$> words <$> getLine\n xs <- sort <$> map read <$> words <$> getLine\n putStrLn $ show $ sum $ snd $ mapAccumL fun k xs\n"}, {"source_code": "import Data.Traversable (mapAccumL)\nimport Control.Arrow (second)\nimport Data.Functor ((<$>))\nimport Data.List (sort)\n\nfun :: Int -> Int -> (Int, Int)\nfun a x | 2 * a >= x = (a, 0)\n | otherwise = second (+1) $ fun (2 * a) x\n\nmain = do\n [_, k] <- map read <$> words <$> getLine\n xs <- map read <$> words <$> getLine\n putStrLn $ show $ sum $ snd $ mapAccumL fun k xs\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\ntype MaxSolvedDifficulty = Int\ntype DecoforcesProblems = [Int]\ntype Accum = Int\n\nf :: MaxSolvedDifficulty -> DecoforcesProblems -> Accum -> Accum\nf k (x:xs) acc\n | x <= k*2 = f (max x k) xs acc\n | otherwise = f (k*2) (x:xs) (acc + 1)\n\nf _ [] acc = acc\n\nmain = interact (show . (\\[[_, k], a] -> f k a 0) . (map (map (read :: String -> Int) . words) . lines))"}], "src_uid": "adc5a98cef418d9bbf40e5772c02ef43"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n s <- getLine\n print $\n length s\n - maximum\n ( [length $ filter (== c) s | c <- ['0' .. '9']]\n ++ [ (* 2)\n $ flip div 2\n $ length\n $ map head\n $ group\n $ filter\n (`elem` [c, d])\n s\n | c <- ['0' .. '9'],\n d <- [succ c .. '9']\n ]\n ) -- ick haskell has ugly formatting\n", "positive_code": [{"source_code": "import Data.Bits\nimport Data.List\n\nparse :: String -> [String]\nparse = tail . lines\n\nval1 :: Eq t => [t] -> t -> Int\nval1 cs x = length $ filter (== x) cs\n\nval :: Eq t => [t] -> (t, t) -> Int\nval cs (x, y)\n | x == y = val1 cs x\n | otherwise = (.&. complement 1) . length . group $\n filter (`elem` [x, y]) cs\n\nsolve :: String -> Int\nsolve str = length str - maximum [val str (x, y)\n | x <- ['0' .. '9'], y <- [x .. '9']]\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve) . parse)\n\n\n\n"}], "negative_code": [], "src_uid": "977db81b5c1d3725e384e8f093655172"} {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\n\nimport qualified Control.Monad.Reader as R\nimport qualified Control.Monad.State.Strict as ST\n\nmain :: IO ()\nmain = do\n numCases <- (read :: String -> Int) <$> getLine\n replicateM_ numCases solveOne\n\nnewtype Size = Size Int\nnewtype Index = Index Int\n\nsolveOne :: IO ()\nsolveOne = do\n getLine -- We get some unnecessary input from the test cases.\n piranhas@(p : ps) <- map (read :: String -> Int) . words <$> getLine\n\n let maxSize = maximum piranhas\n if p == maxSize && p > head ps\n then print 1\n else print $ R.runReader (go startIndex piranhas) (Size maxSize)\n where\n -- 2 because Codeforce counts from 1, and we skip the first element.\n startIndex :: Index\n startIndex = Index 2\n\ngo :: Index -> [Int] -> R.Reader Size Int\ngo _ [] = return (-1)\ngo _ [_] = return (-1)\ngo (Index i) [x, y] = do\n Size maxSize <- R.ask\n if y == maxSize && y > x\n then return i\n else return (-1)\ngo (Index i) (x : y : z : xs) = do\n Size maxSize <- R.ask\n if y == maxSize && (y > x || y > z)\n then return i\n else go (Index $ i + 1) $ y : z : xs\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- getInts\n as <- getInts\n let xs = zip3 as (tail as) [(1::Int)..]\n m = maximum as\n l1 = filter (\\(a, b, _) -> a == m && a > b) xs\n l2 = filter (\\(a, b, _) -> b == m && a < b) xs\n notNull = not . null\n putStrLn $ show $ if notNull l1\n then let (_, _, r) = head l1 in r\n else if notNull l2\n then let (_, _, r) = head l2 in r + 1\n else -1\n"}, {"source_code": "import Control.Monad\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- readInt\n replicateM_ t $ do\n n <- readInt\n a <- readInts\n print $ solve a\n\nsolve :: [Int] -> Int\nsolve a = if null $ filter (/= m) a then -1 else index\n where m = maximum a\n index\n | head a == m = length $ takeWhile (== m) a\n | otherwise = succ $ length $ takeWhile (/= m) a\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.Tuple (swap)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_ : xs : xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs\n | all (== head xs) xs = -1\n | otherwise = snd . maximum . filter (ok . fst) . zipWith (curry swap) [1 ..] $ zip3 xs (tail xs ++ [inf]) (inf : xs)\n where\n ok (x, y, z) = x > min y z\n inf = 10 ^ 9 + 1\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\n\nimport qualified Control.Monad.Reader as R\nimport qualified Control.Monad.State.Strict as ST\n\nmain :: IO ()\nmain = do\n numCases <- (read :: String -> Int) <$> getLine\n replicateM_ numCases solveOne\n\nnewtype Size = Size Int\nnewtype Index = Index Int\n\nsolveOne :: IO ()\nsolveOne = do\n getLine -- We get some unnecessary input from the test cases.\n piranhas@(p : ps) <- map (read :: String -> Int) . words <$> getLine\n\n let maxSize = maximum piranhas\n if p > head ps\n then print 1\n else print $ R.runReader (go startIndex piranhas) (Size maxSize)\n where\n -- 2 because Codeforce counts from 1, and we skip the first element.\n startIndex :: Index\n startIndex = Index 2\n\ngo :: Index -> [Int] -> R.Reader Size Int\ngo _ [] = return (-1)\ngo _ [_] = return (-1)\ngo (Index i) [x, y] = do\n Size maxSize <- R.ask\n if y == maxSize && y > x\n then return i\n else return (-1)\ngo (Index i) (x : y : z : xs) = do\n Size maxSize <- R.ask\n if y == maxSize && (y > x || y > z)\n then return i\n else go (Index $ i + 1) $ y : z : xs"}], "src_uid": "5598d5954fa3e3cecedb413033259760"} {"source_code": "-- 2022-10-09 18:29:26.241871 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))", "positive_code": [{"source_code": "-- 2022-10-10 07:00:20.583467 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-10 05:34:12.847108 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-10 03:05:57.80729 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-10 01:20:05.528045 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-10 01:11:57.544258 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-10 01:04:00.432705 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-10 00:57:39.012381 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 23:00:23.984016 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 21:55:37.897201 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 20:50:59.668161 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 20:21:45.535218 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 18:28:05.760054 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 16:16:43.252694 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 16:13:18.714176 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 16:11:18.800261 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 16:11:07.522334 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.Bits\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nshiftLError :: Int -> Int -> Int\nshiftLError i j | j < 0 = error \"shiftLError: negative shift\"\n | otherwise = Data.Bits.shiftL i j\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> (\\triangle_6989586621679078054 -> Data.Maybe.fromMaybe 0 (distanceBetweenPointsOfLine <$> hasHorizontalLineAbove triangle_6989586621679078054)) a\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 05:24:13.766205 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> Data.Maybe.fromMaybe 0 (fmap (\\b -> distanceBetweenPointsOfLine b) (hasHorizontalLineAbove a))\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-10-09 05:19:27.250997 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Bits\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty((:|)), (<|))\nimport Data.Map (Map)\nimport Data.Set (Set)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsafeFiveHeadTail :: [a] -> Maybe (a, a, a, a, a, [a])\nsafeFiveHeadTail (l1 : (l2 : (l3 : (l4 : (l5 : l6))))) = Just (l1,\n l2,\n l3,\n l4,\n l5,\n l6)\nsafeFiveHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\n prettyPutStrLn a = prettyPutStr a >> putStrLn \"\"\n prettyPutStr :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn Integer\n where prettyPutStr = putStr . show\ninstance PrettyPutStrLn ([Char])\n where prettyPutStr = putStr\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStr a = mapM_ putStrLn (init a) >> putStr (last a)\ninstance PrettyPutStrLn Double\n where prettyPutStr d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ninstance PrettyPutStrLn a => PrettyPutStrLn (a, a)\n where prettyPutStr (a,\n b) = (prettyPutStr a >> putStrLn \" \") >> prettyPutStr b\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Double Double deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving (Ord, Show)\ndata Slope = InfiniteSlope | FiniteSlope Double deriving Show\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((y1 - y0) / (x1 - x0))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\nmkLineWithSlopeAndPoint :: Double -> Point -> Line2D\nmkLineWithSlopeAndPoint slope (Point x\n y) = Line2D (Point x y) (Point (0 / 1) (y - (slope * x)))\noffsetOfLine :: Line2D -> Double\noffsetOfLine (l@(Line2D (Point x0 y0) _)) = y0 - (slope * x0)\n where slope = case slopeOfLine l of\n InfiniteSlope -> error \"offsetOfLine: InfiniteSlope\"\n FiniteSlope s -> s\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nhasHigherX :: Point -> Point -> Bool\nhasHigherX (Point x1 _) (Point x2 _) = x1 > x2\nhasHigherY :: Point -> Point -> Bool\nhasHigherY (Point _ y1) (Point _ y2) = y1 > y2\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nlinesIntersect :: Line2D -> Line2D -> Bool\nlinesIntersect (l1@(Line2D (Point x1 _) _)) (l2@(Line2D (Point x2\n _)\n _)) = case (slopeOfLine l1,\n slopeOfLine l2) of\n (InfiniteSlope,\n InfiniteSlope) -> x1 == x2\n (InfiniteSlope,\n FiniteSlope _) -> True\n (FiniteSlope _,\n InfiniteSlope) -> True\n (FiniteSlope slope1,\n FiniteSlope slope2) -> slope1 /= slope2\nclass Show a => PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n shapeIntersectsAnother :: PolygonShape b => a -> b -> Bool\n shapeIntersectsAnother shapeA shapeB = f shapeA pointsB || f shapeB pointsA\n where pointsA = shapeCenter shapeA <| shapeCorners shapeA\n pointsB = shapeCenter shapeB <| shapeCorners shapeB\n f shape = any ((== LiesInside) . isInside shape)\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\n shapeCorners :: a -> NonEmpty Point\n shapeCenter :: a -> Point\ndata Rectangle\n = Rectangle Point Point Point Point\n deriving (Eq, Show)\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [p1, p2, p3, p4]\n shapeCenter (Rectangle _\n (Point x1 y1)\n _\n (Point x2\n y2)) = Point (x1 + ((x2 - x1) / 2)) (y1 + ((y2 - y1) / 2))\ndata Triangle = Triangle Point Point Point deriving (Eq, Show)\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\n shapeCorners (Triangle p1 p2 p3) = Data.List.NonEmpty.fromList [p1,\n p2,\n p3]\n shapeCenter _ = error \"SHAPECENTER OF TRIANGLE NOT IMPLEMENTED YET\"\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((x1 - x2) ^ (2 :: Int)) + ((y1 - y2) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nifEvenOdd :: Int -> a -> a -> a\nifEvenOdd n a a' | (n `mod` 2) == 0 = a\n | otherwise = a'\nifZero :: Int -> a -> a -> a\nifZero 0 a _ = a\nifZero _ _ a = a\nsumOfIntsToN :: Int -> Int\nsumOfIntsToN n = (n * (n - 1)) `div` 2\nsumOfEvensToN :: Int -> Int\nsumOfEvensToN n = n * (n + 1)\nsumOfOddsToN :: Int -> Int\nsumOfOddsToN n = n * n\ncountElemsThat :: (a -> Bool) -> [a] -> Int\ncountElemsThat f = length . Prelude.filter f\nrange :: Int -> Int -> [Int]\nrange a b = [a..b]\nmodError :: Integral a => a -> a -> a\nmodError a b | toInteger b == 0 = error \"modError: division by zero\"\n | otherwise = a `mod` b\nmod10To9Plus7 :: Integral a => a -> a\nmod10To9Plus7 = (`mod` 1000000007)\nbigExponentiation :: Integer -> Int -> Integer\nbigExponentiation = (^)\nsquares :: Set Int\nsquares = Data.Set.fromList $ map (\\i -> i ^ (2 :: Int)) [1..1000000000]\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve :: Triangle -> Double\nsolve = \\a -> (\\triangle_6989586621680260963 -> Data.Maybe.fromMaybe 0 (distanceBetweenPointsOfLine <$> hasHorizontalLineAbove triangle_6989586621680260963)) a\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-09-02 18:18:29.066246 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty)\nimport Data.Map (Map)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStrLn = print\ninstance PrettyPutStrLn ([Char])\n where prettyPutStrLn = putStrLn\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStrLn = mapM_ putStrLn\ninstance PrettyPutStrLn Double\n where prettyPutStrLn d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Int Int deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving Ord\ndata Slope = InfiniteSlope | FiniteSlope Double\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((fromIntegral $ (y1 - y0)) / (fromIntegral $ (x1 - x0)))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nclass PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\ndata Rectangle = Rectangle Point Point Point Point deriving Eq\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\ndata Triangle = Triangle Point Point Point deriving Eq\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((fromIntegral $ (x1 - x2)) ^ (2 :: Int)) + ((fromIntegral $ (y1 - y2)) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve = \\a -> (\\triangle_6989586621680498911 -> Data.Maybe.fromMaybe 0 (distanceBetweenPointsOfLine <$> hasHorizontalLineAbove triangle_6989586621680498911)) a\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "-- 2022-09-02 18:15:34.006663 UTC\n{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Graph (Graph, Vertex, Forest, Tree)\nimport qualified Data.Maybe\nimport qualified Data.Graph\nimport qualified Data.Char\nimport qualified Control.Monad\nimport qualified Text.Read\nimport qualified Data.Map\nimport qualified Data.Tree\nimport qualified Data.Array\nimport qualified Data.Set\nimport qualified Data.ByteString.Char8\nimport qualified Data.ByteString\nimport qualified Data.List\nimport qualified Data.List.NonEmpty\nimport qualified Numeric\nimport Data.List.NonEmpty (NonEmpty)\nimport Data.Map (Map)\nimport Data.Array (Array, (!))\nimport Data.ByteString (ByteString)\nimport Debug.Trace\n\ndata GraphForProblems key\n = GraphForProblems {gpGraph :: Graph,\n gpVertexFromKey :: (key -> Vertex),\n gpNodeFromVertex :: (Vertex -> key)}\nnewtype GraphVertex a = GraphVertex a\ninstance Eq a => Eq (GraphVertex a)\n where (==) (GraphVertex a) (GraphVertex b) = a == b\nunwrapGraphVertex :: GraphVertex i -> i\nunwrapGraphVertex (GraphVertex i) = i\ntype IntGraph = GraphForProblems Int\ntype StringGraph = GraphForProblems String\ndata GraphEdge a = GraphEdge (GraphVertex a) (GraphVertex a)\ninstance Show (GraphForProblems key)\n where show (GraphForProblems {gpGraph = gpGraph}) = show gpGraph\ninstance Ord a => Ord (GraphVertex a)\n where compare (GraphVertex a) (GraphVertex b) = compare a b\nedgeSource :: GraphEdge a -> GraphVertex a\nedgeSource (GraphEdge a _) = a\nedgeDest :: GraphEdge a -> GraphVertex a\nedgeDest (GraphEdge _ b) = b\nmkGraph :: (Ord key, Show key) =>\n [(node, key, [key])] -> GraphForProblems key\nmkGraph nodesAndEdges = GraphForProblems gpGraph gpVertexFromKey gpNodeFromVertex\n where (gpGraph,\n nodeFromVertex,\n vertexFromKey) = Data.Graph.graphFromEdges nodesAndEdges\n gpVertexFromKey k = case vertexFromKey k of\n Nothing -> error $ (\"vertexFromKey: \" <> (show k <> \" key not found\"))\n Just k' -> k'\n gpNodeFromVertex v = let (_, k, _) = nodeFromVertex v\n in k\nvertices' :: GraphForProblems a -> [GraphVertex a]\nvertices' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (GraphVertex . gpNodeFromVertex) <$> Data.Graph.vertices gpGraph\nedges' :: GraphForProblems a -> [GraphEdge a]\nedges' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = (\\(a,\n b) -> GraphEdge (GraphVertex $ gpNodeFromVertex a) (GraphVertex $ gpNodeFromVertex b)) <$> Data.Graph.edges gpGraph\ndfs' :: GraphForProblems key ->\n [GraphVertex key] -> [Tree (GraphVertex key)]\ndfs' (GraphForProblems {gpVertexFromKey = gpVertexFromKey,\n gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (fmap (GraphVertex . gpNodeFromVertex)) . (Data.Graph.dfs gpGraph . fmap (gpVertexFromKey . unwrapGraphVertex))\ndfsOnSingleVertex :: GraphForProblems key ->\n GraphVertex key -> Tree (GraphVertex key)\ndfsOnSingleVertex g v = case dfs' g [v] of\n [] -> error \"dfsOnSingleVertex: empty result\"\n x : _ -> x\nscc' :: GraphForProblems key -> [Tree (GraphVertex key)]\nscc' (GraphForProblems {gpGraph = gpGraph,\n gpNodeFromVertex = gpNodeFromVertex}) = fmap (GraphVertex . gpNodeFromVertex) <$> Data.Graph.scc gpGraph\nlevels' :: Tree (GraphVertex key) -> [[GraphVertex key]]\nlevels' = Data.Tree.levels\ngetSingleEnd :: Eq a =>\n GraphForProblems a -> GraphVertex a -> GraphVertex a\ngetSingleEnd g vertex = edgeDest $ (head $ (Prelude.filter ((== vertex) . edgeSource) $ edges' g))\ngetSingleLeaf :: Tree (GraphVertex a) -> GraphVertex a\ngetSingleLeaf = last . Data.Tree.flatten\nflatten' :: Tree (GraphVertex a) -> [GraphVertex a]\nflatten' = Data.Tree.flatten\nelemTreeInt :: GraphVertex Int -> Tree (GraphVertex Int) -> Bool\nelemTreeInt = elem\nminimumTree :: Tree Int -> Int\nminimumTree = minimum\nmapTree :: (a -> b) -> Tree a -> Tree b\nmapTree = fmap\nnewtype OutDegreeTable\n = OutDegreeTable {unOutDegreeTable :: (Array Vertex Int)}\nlinearGraph :: OutDegreeTable -> Bool\nlinearGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = twoOnes && restTwos\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n twoOnes = 2 == length (Prelude.filter (== 1) values)\n restTwos = (numValues - 2) == length (Prelude.filter (== 2) values)\ncycleGraph :: OutDegreeTable -> Bool\ncycleGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = allTwos\n where values = Data.Array.elems unOutDegreeTable\n allTwos = all (== 2) values\nstarGraph :: OutDegreeTable -> Bool\nstarGraph (OutDegreeTable {unOutDegreeTable = unOutDegreeTable}) = onlyOneCenter && restOnes\n where values = Data.Array.elems unOutDegreeTable\n numValues = length values\n onlyOneCenter = 1 == length (Prelude.filter (== numValues - 1) values)\n restOnes = (numValues - 1) == length (Prelude.filter (== 1) values)\noutdegree' :: GraphForProblems a -> OutDegreeTable\noutdegree' (GraphForProblems {gpGraph = gpGraph}) = OutDegreeTable{unOutDegreeTable = unOutDegreeTable}\n where unOutDegreeTable = Data.Graph.outdegree gpGraph\nsafeElems2 :: [a] -> Maybe (a, a)\nsafeElems2 [x1, x2] = Just (x1, x2)\nsafeElems2 _ = Nothing\nsafeElems3 :: [a] -> Maybe (a, a, a)\nsafeElems3 [x1, x2, x3] = Just (x1, x2, x3)\nsafeElems3 _ = Nothing\nsafeElems4 :: [a] -> Maybe (a, a, a, a)\nsafeElems4 [x1, x2, x3, x4] = Just (x1, x2, x3, x4)\nsafeElems4 _ = Nothing\nsafeElems5 :: [a] -> Maybe (a, a, a, a, a)\nsafeElems5 [x1, x2, x3, x4, x5] = Just (x1, x2, x3, x4, x5)\nsafeElems5 _ = Nothing\ncompareLength :: Int -> [b] -> Ordering\ncompareLength 0 ([]) = EQ\ncompareLength 0 _ = LT\ncompareLength i (_ : xs) | i < 0 = error \"compareLength: negative length comparison does not make sense\"\n | otherwise = compareLength (i - 1) xs\nconsumeNElems :: Int -> [b] -> Maybe ([b], [b])\nconsumeNElems 0 ([]) = Just ([], [])\nconsumeNElems 0 xs = Just ([], xs)\nconsumeNElems _ ([]) = Nothing\nconsumeNElems i (x : xs) | i < 0 = error \"consumeNElems: negative length comparison does not make sense\"\n | otherwise = do {(ys, zs) <- consumeNElems (i - 1) xs;\n return (x : ys, zs)}\ngroupTups2 :: [a] -> Maybe ([(a, a)])\ngroupTups2 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : rest)) = go ((x, y) : acc) rest\n go _ _ = Nothing\ngroupTups3 :: [a] -> Maybe ([(a, a, a)])\ngroupTups3 = go []\n where go acc ([]) = Just (reverse acc)\n go acc (x : (y : (z : rest))) = go ((x, y, z) : acc) rest\n go _ _ = Nothing\nsafeHeadTail :: [a] -> Maybe (a, [a])\nsafeHeadTail (l1 : l2) = Just (l1, l2)\nsafeHeadTail _ = Nothing\nsafeTwoHeadTail :: [a] -> Maybe (a, a, [a])\nsafeTwoHeadTail (l1 : (l2 : l3)) = Just (l1, l2, l3)\nsafeTwoHeadTail _ = Nothing\nsafeThreeHeadTail :: [a] -> Maybe (a, a, a, [a])\nsafeThreeHeadTail (l1 : (l2 : (l3 : l4))) = Just (l1, l2, l3, l4)\nsafeThreeHeadTail _ = Nothing\nsafeFourHeadTail :: [a] -> Maybe (a, a, a, a, [a])\nsafeFourHeadTail (l1 : (l2 : (l3 : (l4 : l5)))) = Just (l1,\n l2,\n l3,\n l4,\n l5)\nsafeFourHeadTail _ = Nothing\nsingleLine :: [ByteString] -> Maybe ByteString\nsingleLine [l] = Just l\nsingleLine _ = Nothing\nclass PrettyPutStrLn a\n where prettyPutStrLn :: a -> IO ()\ninstance PrettyPutStrLn Int\n where prettyPutStrLn = print\ninstance PrettyPutStrLn ([Char])\n where prettyPutStrLn = putStrLn\ninstance PrettyPutStrLn ([[Char]])\n where prettyPutStrLn = mapM_ putStrLn\ninstance PrettyPutStrLn Double\n where prettyPutStrLn d = putStrLn $ Numeric.showFFloat (Just 6) d \"\"\ntype ProblemInputOutputParser a = [ByteString] ->\n Maybe (a, [ByteString])\ndata Point = Point Int Int deriving (Eq, Ord)\ninstance Show Point\n where show (Point x y) = show (x, y)\ndata PointLiesInside = LiesInside | LiesOutside deriving Eq\nliesInsideToBool :: PointLiesInside -> Bool\nliesInsideToBool (LiesInside) = True\nliesInsideToBool (LiesOutside) = False\ndata Line2D = Line2D Point Point deriving Ord\ndata Slope = InfiniteSlope | FiniteSlope Double\nslopeOfLine :: Line2D -> Slope\nslopeOfLine (Line2D (Point x0 y0)\n (Point x1 y1)) | x0 == x1 = InfiniteSlope\n | otherwise = FiniteSlope $ ((fromIntegral $ (y1 - y0)) / (fromIntegral $ (x1 - x0)))\ninstance Eq Line2D\n where (==) l1 (Line2D p1 p2) = isInLine p1 l1 && isInLine p2 l1\ndata LinePointTest\n = AboveOrLeft | BelowOrRight | InLine\n deriving Eq\nmkLineFromTwoPoints :: Point -> Point -> Line2D\nmkLineFromTwoPoints p1 p2 | p1 == p2 = error $ (\"p1 == p2: p1 = \" <> (show p1 <> (\" p2 = \" <> show p2)))\n | p1 < p2 = Line2D p1 p2\n | otherwise = Line2D p2 p1\npointsInSameLine :: Point -> Point -> Point -> Bool\npointsInSameLine (Point x1 y1) (Point x2 y2) (Point x3\n y3) = ((y3 - y1) * (x2 - x1)) == ((x3 - x1) * (y2 - y1))\nisPointAboveLine :: Point -> Line2D -> LinePointTest\nisPointAboveLine (Point x3 y3) (Line2D (Point x1 y1)\n (Point x2 y2)) = if l == 0\n then InLine\n else if l > 0\n then AboveOrLeft\n else BelowOrRight\n where l = ((y3 - y1) * (x2 - x1)) - ((x3 - x1) * (y2 - y1))\nisInLine :: Point -> Line2D -> Bool\nisInLine p = (== InLine) . isPointAboveLine p\nclass PolygonShape a\n where isInside :: a -> Point -> PointLiesInside\n isInside polygon point = if and $ (fmap f $ linesOfWithComparisons polygon)\n then LiesInside\n else LiesOutside\n where f (lineEq,\n lineComps) = isPointAboveLine point lineEq `elem` lineComps\n linesOfWithComparisons :: a -> NonEmpty (Line2D, [LinePointTest])\ndata Rectangle = Rectangle Point Point Point Point deriving Eq\nmkRectangle :: Point -> Point -> Point -> Point -> Maybe Rectangle\nmkRectangle p1 p2 p3 p4 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p1 /= p4)));\n Control.Monad.guard $ ((p2 /= p3) && (p2 /= p4));\n Control.Monad.guard $ (p3 /= p4);\n return $ Rectangle pymin pxmin pymax pxmax}\n where points = [p2, p3, p4]\n pymin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y < accy\n then p\n else if y > accy\n then acc\n else if x > accx\n then p\n else acc) p1 points\n pxmin = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x < accx\n then p\n else if x > accx\n then acc\n else if y > accy\n then p\n else acc) p1 points\n pymax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if y > accy\n then p\n else if y < accy\n then acc\n else if x < accx\n then p\n else acc) p1 points\n pxmax = foldl (\\(acc@(Point accx accy)) (p@(Point x\n y)) -> if x > accx\n then p\n else if x < accx\n then acc\n else if y < accy\n then p\n else acc) p1 points\nisInsideRect :: Rectangle -> Point -> PointLiesInside\nisInsideRect = isInside\ninstance PolygonShape Rectangle\n where linesOfWithComparisons (Rectangle p1\n p2\n p3\n p4) = Data.List.NonEmpty.fromList [(mk p1 p2,\n [AboveOrLeft,\n InLine]),\n (mk p2 p3,\n [BelowOrRight,\n InLine]),\n (mk p3 p4,\n [BelowOrRight,\n InLine]),\n (mk p4 p1,\n [AboveOrLeft,\n InLine])]\n where mk = mkLineFromTwoPoints\ndata Triangle = Triangle Point Point Point deriving Eq\nmkTriangle :: Point -> Point -> Point -> Maybe Triangle\nmkTriangle p1 p2 p3 = do {Control.Monad.guard $ ((p1 /= p2) && ((p1 /= p3) && (p2 /= p3)));\n return $ Triangle p1 p2 p3}\ninstance PolygonShape Triangle\n where linesOfWithComparisons (Triangle p1\n p2\n p3) = Data.List.NonEmpty.fromList [(mk p1 p2, []),\n (mk p2 p3, []),\n (mk p3 p1, [])]\n where mk = mkLineFromTwoPoints\nhasHorizontalLineAbove :: Triangle -> Maybe Line2D\nhasHorizontalLineAbove (triangle@(Triangle p1\n p2\n p3)) = case Data.Maybe.mapMaybe horizontalLine triangleLines of\n [l] -> case Prelude.filter (BelowOrRight ==) $ map (flip isPointAboveLine l) trianglePoints of\n [_] -> Just l\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE BELOW VS ABOVE TEST hasHorizontalLineAbove\"\n [] -> Nothing\n _ -> error \"INVALID CASE MORE THAN ONE HORIZONTAL LINE hasHorizontalLineAbove\"\n where trianglePoints = [p1, p2, p3]\n triangleLines = map fst $ (Data.List.NonEmpty.toList $ linesOfWithComparisons triangle)\n horizontalLine (l@(Line2D (Point _ y1)\n (Point _ y2))) | y1 == y2 = Just l\n | otherwise = Nothing\ndistanceBetweenPoints :: Point -> Point -> Double\ndistanceBetweenPoints (Point x1 y1) (Point x2\n y2) = sqrt $ (((fromIntegral $ (x1 - x2)) ^ (2 :: Int)) + ((fromIntegral $ (y1 - y2)) ^ (2 :: Int)))\ndistanceBetweenPointsOfLine :: Line2D -> Double\ndistanceBetweenPointsOfLine (Line2D p1\n p2) = distanceBetweenPoints p1 p2\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nparseTriangle :: ProblemInputOutputParser Triangle\nparseTriangle ws = do {(x0,\n y0,\n x1,\n rest) <- safeThreeHeadTail ws >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest) -> do {(x0,\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1,\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2,\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0,\n x1,\n x2,\n rest)});\n (y1, x2, y2, remainingTkns) <- safeThreeHeadTail rest >>= (\\(x0Bs,\n x1Bs,\n x2Bs,\n rest') -> do {(x0',\n _) <- Data.ByteString.Char8.readInt x0Bs;\n (x1',\n _) <- Data.ByteString.Char8.readInt x1Bs;\n (x2',\n _) <- Data.ByteString.Char8.readInt x2Bs;\n return (x0',\n x1',\n x2',\n rest')});\n return (Triangle (Point (fromIntegral x0) (fromIntegral y0)) (Point (fromIntegral x1) (fromIntegral y1)) (Point (fromIntegral x2) (fromIntegral y2)),\n remainingTkns)}\nunpackParser f x1 = f x1\nparser = parseTriangle\nsolve = \\a -> (\\triangle_6989586621680514869 -> Data.Maybe.fromMaybe 0 (distanceBetweenPointsOfLine <$> hasHorizontalLineAbove triangle_6989586621680514869)) a\napplyFunctionWithParserUntilExhausted solver parser = go\n where go ([]) = return ()\n go inputBs = do case parser inputBs of\n Nothing -> error \"UNEXPECTED ERROR WHILE PARSING\"\n Just (result,\n remainingTkns) -> do {prettyPutStrLn $ solver result;\n go remainingTkns}\nmain :: IO ()\nmain = Data.ByteString.getContents >>= (applyFunctionWithParserUntilExhausted (unpackParser solve) parser . (tail . Data.ByteString.Char8.words))"}, {"source_code": "import Data.List (permutations)\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [(Int, Int)]\r\ntype OutType = Int\r\n\r\nsolve :: InType -> OutType\r\nsolve cs = maximum $ map test $ permutations cs\r\n\r\ntest :: [(Int, Int)] -> Int\r\ntest [(x1, y1), (x2, y2), (x3, y3)]\r\n | y1 == y2 && y1 > y3 = max x2 x1 - min x2 x1\r\n | otherwise = 0\r\ntest _ = error \"test failed\"\r\n\r\nreceive :: [String] -> InType\r\nreceive = map getPair\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . solve . receive) . chunksOf 3 . tail . lines\r\n"}], "negative_code": [], "src_uid": "9f019c3898f27d687c5b3498586644e8"} {"source_code": "import Data.List\nimport Data.Array\nimport Data.Function\n\ntype Result = Array Int Int\n\ntransform :: [Int]->Result\ntransform (count:xs) = listArray (0,count).reverse$sumX:go xs where\n\tgo [] = []\n\tgo xs'@(h:t) = (sumX - minimum xs'):go (zipWith (+) xs t)\n\tsumX = sum xs\n\nuB = snd.bounds\n\t\nbest a1 a2 cries = maximum.map calc$[max 0.(cries-).uB$a1..min cries.uB$a2]\n\twhere calc split = a1!(cries-split) + a2!split\n\nmerge :: Result->Result->Result\nmerge a1 a2 = listArray (0,newMax).map (best a1 a2)$[0..newMax]\n\twhere newMax = uB a1 + uB a2\n\t\nresult :: [[Int]]->Int\nresult ([n,m]:ss) = (!m).foldl1 merge.map transform$ss\n\nmain=interact$show.result.map (map read.words).lines\n", "positive_code": [{"source_code": "import Data.Array.IO\nimport Data.Array.IArray ((!),bounds)\nimport Data.Array.Unboxed (UArray,listArray)\nimport Control.Monad\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshelfBest :: [Int] -> UArray Int Int\nshelfBest (len:ps) = listArray (0,len) (reverse init)\n where sumX = sum ps\n init = sumX : go ps\n go :: [Int] -> [Int]\n go [] = []\n go xs'@(_:t) = (sumX - minimum xs') : go (zipWith (+) ps t)\n\nupperBound arr = snd $ bounds arr\n\nbest:: UArray Int Int -> UArray Int Int -> Int -> Int\nbest a1 a2 m = maximum $ map go [lo..hi]\n where lo = max 0 (m - upperBound a1)\n hi = min m (upperBound a2)\n go k = a1!(m-k) + a2!k\n\nstep :: UArray Int Int -> UArray Int Int -> UArray Int Int\nstep prev curr = next\n where hi = upperBound prev + upperBound curr\n next = listArray (0,hi) $ map (best prev curr) [0..hi]\n\nsolve m shelves =\n let arr = foldl1 step $ map shelfBest shelves\n i = min (upperBound arr) m\n in arr!i\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n -- shelves <- replicateM n $ fmap readNums BS.getLine\n shelves <- replicateM n $ fmap (map read . words) getLine\n let answer = solve m shelves\n print answer\n\n"}, {"source_code": "import Data.Array\nimport Control.Monad\n\ntype Result = Array Int Int\n\nshelfBest :: [Int] -> Result\nshelfBest (len:ps) = listArray (0,len) (reverse init)\n where sumX = sum ps\n init = sumX : go ps\n go :: [Int] -> [Int]\n go [] = []\n go xs'@(_:t) = (sumX - minimum xs') : go (zipWith (+) ps t)\n\nupperBound arr = snd $ bounds arr\n\nbest:: Result -> Result -> Int -> Int\nbest a1 a2 m = maximum $ map go [lo..hi]\n where lo = max 0 (m - upperBound a1)\n hi = min m (upperBound a2)\n go k = a1!(m-k) + a2!k\n\nstep :: Result -> Result -> Result\nstep prev curr = next\n where hi = upperBound prev + upperBound curr\n next = listArray (0,hi) $ map (best prev curr) [0..hi]\n\nsolve m shelves =\n let arr = foldl1 step $ map shelfBest shelves\n i = min (upperBound arr) m\n in arr!i\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n -- shelves <- replicateM n $ fmap readNums BS.getLine\n shelves <- replicateM n $ fmap (map read . words) getLine\n let answer = solve m shelves\n print answer\n"}], "negative_code": [{"source_code": "import Data.Array.IO\nimport Data.Array (listArray)\nimport Data.Array.IArray ((!),bounds)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.MArray (freeze)\nimport Control.Monad\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshelfBest m ps = do\n let len = length ps\n\n let nums = listArray (1,len) ps\n\n lsums <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n let kmax = min m len\n forM_ [1..kmax] $ \\i -> do\n v <- readArray lsums (i-1)\n writeArray lsums i (v+nums!i)\n\n rsums <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n forM_ [1..kmax] $ \\i -> do\n v <- readArray rsums (i-1)\n writeArray rsums i (v+nums!(len+1-i))\n\n lsums' <- freeze lsums :: IO (UArray Int Int)\n rsums' <- freeze rsums :: IO (UArray Int Int)\n\n best <- newArray (0,kmax) 0 :: IO (IOUArray Int Int)\n forM_ [1..kmax] $ \\k -> do\n let a = maximum [ (lsums'!i) + (rsums'!(k-i)) | i <- [0..k] ]\n writeArray best k a\n freeze best :: IO (UArray Int Int)\n\nstep m prev ps = do\n curr <- shelfBest m ps\n let (plo,phi) = bounds prev\n let (clo,chi) = bounds curr\n mmax = min m (chi+phi)\n next <- newArray (0,mmax) 0 :: IO (IOUArray Int Int)\n forM_ [1..mmax] $ \\k -> do\n let a = maximum [ (prev!i') + (curr!j') | i <- [0..k], let i' = min i phi, let j' = min (k-i) chi ]\n writeArray next k a\n freeze next :: IO (UArray Int Int)\n\nsolve m (ps:rest) = do\n prev <- shelfBest m ps\n let loop arr [] = return arr\n loop arr (ps:pss) = step m arr ps\n arr <- loop prev rest\n let (lo,hi) = bounds arr\n i = min m hi\n answer = arr!i\n return answer\n\nreadNums :: ByteString -> [Int]\nreadNums bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> parseInts n bs'\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n shelves <- replicateM n $ fmap readNums BS.getLine\n solve m shelves\n\n"}, {"source_code": "import Data.Array.IO\nimport Data.Array (listArray)\nimport Data.Array.IArray ((!),bounds)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.MArray (freeze)\nimport Control.Monad\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshelfBest m ps = do\n let len = length ps\n\n let nums = listArray (1,len) ps\n\n lsums <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n let kmax = min m len\n forM_ [1..kmax] $ \\i -> do\n v <- readArray lsums (i-1)\n writeArray lsums i (v+nums!i)\n\n rsums <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n forM_ [1..kmax] $ \\i -> do\n v <- readArray rsums (i-1)\n writeArray rsums i (v+nums!(len+1-i))\n\n lsums' <- freeze lsums :: IO (UArray Int Int)\n rsums' <- freeze rsums :: IO (UArray Int Int)\n\n best <- newArray (0,kmax) 0 :: IO (IOUArray Int Int)\n forM_ [1..kmax] $ \\k -> do\n let a = maximum [ (lsums'!i) + (rsums'!(k-i)) | i <- [0..k] ]\n writeArray best k a\n freeze best :: IO (UArray Int Int)\n\nstep m prev ps = do\n curr <- shelfBest m ps\n let (plo,phi) = bounds prev\n let (clo,chi) = bounds curr\n mmax = min m (chi+phi)\n next <- newArray (0,mmax) 0 :: IO (IOUArray Int Int)\n forM_ [1..mmax] $ \\k -> do\n let a = maximum [ (prev!i') + (curr!j') | i <- [0..k], let i' = min i phi, let j' = min (k-i) chi ]\n writeArray next k a\n freeze next :: IO (UArray Int Int)\n\nsolve m (ps:rest) = do\n prev <- shelfBest m ps\n let loop arr [] = return arr\n loop arr (ps:pss) = step m arr ps\n arr <- loop prev rest\n let (lo,hi) = bounds arr\n i = min m hi\n answer = arr!i\n return answer\n\nreadNums :: ByteString -> [Int]\nreadNums bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> parseInts n bs'\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n shelves <- replicateM n $ fmap readNums BS.getLine\n solve m shelves >>= print\n\n"}], "src_uid": "130755f31abe81e5314a1fd5ef06ba81"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\ntype IntArray = Array Int Int\ntype ByteString = BS8.ByteString\n(!.) = BS8.index\n\ngetMinSuffix :: ByteString -> ByteString\ngetMinSuffix str = BS8.drop (pi ! (n - 1)) str where\n n = BS8.length str\n pi = listArray (0, n - 1) $ 0 : [ prefixFunction str pi i | i <- [1 .. n - 1] ]\n\nprefixFunction :: ByteString -> IntArray -> Int -> Int\nprefixFunction str pi i = if str !. i == str !. j' then (j' + 1) else j' where\n j = pi ! (i - 1)\n j' = backtrack j\n backtrack k = if k > 0 && str !. i /= str !. k then backtrack (pi ! (k - 1)) else k\n\nprocess :: ByteString -> ByteString -> ByteString\nprocess s t = let\n suffix = getMinSuffix t\n (sZero, sOne) = countZeroOne s\n (tZero, tOne) = countZeroOne t\n (fZero, fOne) = countZeroOne suffix\n tryWhole = if tZero <= sZero && tOne <= sOne\n then Just (t, (sZero - tZero, sOne - tOne))\n else Nothing\n addSubstr (str, (zero, one)) = Just result where\n mZero = if fZero == 0 then 0 else zero `div` fZero\n mOne = if fOne == 0 then 0 else one `div` fOne\n repCnt = min mZero mOne\n rZero = zero - fZero * repCnt\n rOne = one - fOne * repCnt\n result = str <> BS8.concat (replicate repCnt suffix) <> BS8.replicate rZero '0' <> BS8.replicate rOne '1' in\n case tryWhole >>= addSubstr of\n Just result -> result\n Nothing -> s\n\ncountZeroOne str = (zeroCount, oneCount) where\n zeroCount = BS8.count '0' str\n oneCount = BS8.length str - zeroCount\n\nmain = do\n s <- nocr <$> BS8.getLine\n t <- nocr <$> BS8.getLine\n BS8.putStrLn $ process s t\n\nnocr str = if BS8.last str == '\\r' then BS8.init str else str\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport Data.Int\nimport Data.Maybe\nimport Data.Semigroup\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport qualified Data.List as L\n\nreadLines :: IO [BS.ByteString]\nreadLines = BS.lines `fmap` BS.getContents\n\ndata KmpState a =\n KS a [a] (KmpState a)\n | KM a [a] (KmpState a) (KmpState a)\n | KEND (KmpState a)\n\nkMatch :: Eq a => a -> KmpState a -> Bool\nkMatch _ KEND{} = False\nkMatch x (KM y _ _ _) = x == y\nkMatch x (KS y _ _ ) = x == y\n\nkNext :: KmpState a -> KmpState a\nkNext KEND{} = error \"Already the end of KMP state.\"\nkNext (KS _ _ n) = n\nkNext (KM _ _ _ n) = n\n\nkFail :: KmpState a -> KmpState a\nkFail (KEND f) = f\nkFail (KM _ _ f _) = f\nkFail s@KS{} = s\n\nkFailToList :: (a -> b) -> KmpState a -> [b]\nkFailToList f s = case s of\n KEND p -> [f (e p)]\n KS a _ n -> f a : kFailToList f n\n KM _ _ p n -> f (e p) : kFailToList f n\n where\n e KEND{} = error \"Impossible\"\n e (KS k _ _) = k\n e (KM k _ _ _) = k\n\nkGetSuffix :: KmpState a -> [a]\nkGetSuffix KEND{} = []\nkGetSuffix (KS _ as _) = as\nkGetSuffix (KM _ as _ _) = as\n\nkLast :: KmpState a -> KmpState a\nkLast a@KEND{} = a\nkLast a = kLast $ kNext a\n\n-- getKmp :: Eq a => [a] -> KmpState a\n-- getKmp [] = KEND (getKmp [])\n-- getKmp z@(x:xs) = KS x z (kmp' xs self)\n-- where\n-- self = getKmp z\n-- \n-- kmp' [] curFail = KEND curFail\n-- kmp' t@(r:rs) curFail = KM r t curFail (kmp' rs nextFail)\n-- where\n-- nextFail = tryMatch curFail\n-- \n-- tryMatch st\n-- | kMatch r st = kNext st\n-- | u@KS{} <- st = u\n-- | u@KM{} <- st = tryMatch $ kFail u\n-- | KEND{} <- st = error \"Try to match end of KMP state\"\n\ngetKmp :: Eq a => [a] -> KmpState a\ngetKmp [] = r\n where\n r = KEND r\ngetKmp z@(x:xs) = q\n where\n q = KS x z $ kmp' xs q\n\n kmp' [] curFail = KEND curFail\n kmp' t@(r:rs) curFail = KM r t curFail $ kmp' rs nextFail\n where\n nextFail = tryMatch curFail\n\n tryMatch st\n | kMatch r st = kNext st\n | u@KS{} <- st = u\n | u@KM{} <- st = tryMatch $ kFail u\n | KEND{} <- st = error \"Try to match end of KMP state\"\n\n\nstripWindowsLB :: BS.ByteString -> BS.ByteString\nstripWindowsLB a = if BS.isSuffixOf (BS.pack \"\\r\") a\n then fromJust $ BS.stripSuffix (BS.pack \"\\r\") a\n else a\n\ntype LineReader a = State [BS.ByteString] a\n\ncurrentLine :: LineReader BS.ByteString\ncurrentLine = do\n ls <- get\n let (x, xs) = case ls of\n [] -> error \"No remain lines.\"\n l -> (head l, tail l)\n put xs\n return x\n\nrestLines :: LineReader [BS.ByteString]\nrestLines = do\n xs <- get\n put []\n return xs\n\nrunLineReader :: LineReader a -> [BS.ByteString] -> (a, [BS.ByteString])\nrunLineReader reader ls = runState reader (map stripWindowsLB ls)\n\n\ndata Count = C {c0 :: Int32, c1 :: Int32}\n\ngetCount :: String -> Count\ngetCount = L.foldl' inc (C 0 0)\n where\n inc p@(C r0 r1) c = if c == '0' then p{c0 = r0 + 1} else p{c1 = r1 + 1}\n\ntoString :: Count -> String\ntoString (C x y) = replicate (fromIntegral x) '0'\n ++ replicate (fromIntegral y) '1'\n\nsolve :: String -> String -> String\nsolve s t\n | [] <- t = s\n | cs0 < ct0 || cs1 < ct1 = s\n | otherwise = t\n ++ mconcat (replicate numOcc lastSuffix)\n ++ toString crest\n where\n tKmp = getKmp t\n lastSuffix = kGetSuffix $ kFail $ kLast tKmp\n (C ct0 ct1) = getCount t\n (C cs0 cs1) = getCount s\n (C cts0 cts1) = getCount lastSuffix\n numOcc = maybeMin (f cs0 ct0 cts0) (f cs1 ct1 cts1)\n crest = C\n (cs0 - ct0 - cts0 * fromIntegral numOcc)\n (cs1 - ct1 - cts1 * fromIntegral numOcc)\n f cs ct cts = fmap fromIntegral $\n if cts == 0 then Nothing else Just $ (cs - ct) `div` cts\n\n maybeMin Nothing (Just x) = x\n maybeMin (Just x) Nothing = x\n maybeMin (Just x) (Just y) = min x y\n\nmain :: IO ()\nmain = do\n ls <- readLines\n let ((sl1, sl2), _) = flip runLineReader ls $ do\n rls <- restLines\n case rls of\n l1:l2:_ -> return (BS.unpack l1, BS.unpack l2)\n _ -> error \"\"\n -- let a = kFailToList id $ getKmp $ zipWith Arg sl2 [1..] :: [Arg Char Int]\n -- print $ map (\\(Arg _ b) -> b) a\n putStrLn $ solve sl1 sl2\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\ntype IntArray = Array Int Int\ntype ByteString = BS8.ByteString\n(!.) = BS8.index\n\ngetMinSuffix :: ByteString -> ByteString\ngetMinSuffix str = BS8.drop (pi ! (n - 1)) str where\n n = BS8.length str\n pi = listArray (0, n - 1) $ 0 : [ prefixFunction str pi i | i <- [1 .. n - 1] ]\n\nprefixFunction :: ByteString -> IntArray -> Int -> Int\nprefixFunction str pi i = if str !. i == str !. j' then (j' + 1) else j' where\n j = pi ! (i - 1)\n j' = backtrack j\n backtrack k = if k > 0 && str !. i /= str !. k then backtrack (pi ! (k - 1)) else k\n\nprocess :: ByteString -> ByteString -> ByteString\nprocess s t = let\n suffix = getMinSuffix t\n (sZero, sOne) = countZeroOne s\n (tZero, tOne) = countZeroOne t\n (fZero, fOne) = countZeroOne suffix\n tryWhole = if tZero <= sZero && tOne <= sOne\n then Just (t, (sZero - tZero, sOne - tOne))\n else Nothing\n addSubstr (str, (zero, one)) = if fZero <= zero && fOne <= one\n then addSubstr ((str <> suffix), (zero - fZero, one - fOne))\n else str <> BS8.replicate zero '0' <> BS8.replicate one '1' in\n case tryWhole >>= return . addSubstr of\n Just result -> result\n Nothing -> s\n\ncountZeroOne str = (zeroCount, oneCount) where\n zeroCount = BS8.count '0' str\n oneCount = BS8.length str - zeroCount\n\nmain = do\n s <- BS8.getLine\n t <- BS8.getLine\n BS8.putStrLn $ process s t\n\nnocr str = if BS8.last str == '\\r' then BS8.init str else str\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport Data.Int\nimport Data.Maybe\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport qualified Data.List as L\n\nreadLines :: IO [BS.ByteString]\nreadLines = BS.lines `fmap` BS.getContents\n\ndata KmpState a =\n KS a [a] (KmpState a)\n | KM a [a] (KmpState a) (KmpState a)\n | KEND\n\nkMatch :: Eq a => a -> KmpState a -> Bool\nkMatch _ KEND = False\nkMatch x (KM y _ _ _) = x == y\nkMatch x (KS y _ _ ) = x == y\n\nkNext :: KmpState a -> KmpState a\nkNext KEND = error \"Already the end of KMP state.\"\nkNext (KS _ _ n) = n\nkNext (KM _ _ _ n) = n\n\nkFail :: KmpState a -> KmpState a\nkFail KEND = error \"Already the end of KMP state.\"\nkFail (KM _ _ f _) = f\nkFail s@KS{} = s\n\nkFailToList :: (a -> b) -> KmpState a -> [b]\nkFailToList _ KEND = []\nkFailToList f (KS a _ n) = f a : kFailToList f n\nkFailToList f (KM _ _ p n) = f (e p) : kFailToList f n\n where\n e KEND = error \"Impossible\"\n e (KS k _ _) = k\n e (KM k _ _ _) = k\n\nkGetSuffix :: KmpState a -> [a]\nkGetSuffix KEND = []\nkGetSuffix (KS _ as _) = as\nkGetSuffix (KM _ as _ _) = as\n\nkLast :: KmpState a -> KmpState a\nkLast KEND = KEND\nkLast a@(KS _ _ KEND) = a\nkLast a@(KM _ _ _ KEND) = a\nkLast a = kLast $ kNext a\n\ngetKmp :: Eq a => [a] -> KmpState a\ngetKmp [] = KEND\ngetKmp y@[x] = KS x y KEND\ngetKmp z@(x:y:xs) = KS x z (KM y (tail z) self (kmp' xs self))\n where\n self = getKmp z\n\n kmp' [] _ = KEND\n kmp' t@(r:rs) prevFail = KM r t curFail (kmp' rs curFail)\n where\n curFail = tryMatch prevFail\n\n tryMatch st\n | kMatch r st = kNext st\n | u@KS{} <- st = u\n | u@KM{} <- st = tryMatch $ kFail u\n | KEND <- st = error \"Try to match end of KMP state\"\n\n\ndata Count = C {c0 :: Int32, c1 :: Int32}\n\ngetCount :: String -> Count\ngetCount = L.foldl' inc (C 0 0)\n where\n inc p@(C r0 r1) c = if c == '0' then p{c0 = r0 + 1} else p{c1 = r1 + 1}\n\ntoString :: Count -> String\ntoString (C x y) = replicate (fromIntegral x) '0'\n ++ replicate (fromIntegral y) '1'\n\nsolve :: String -> String -> String\nsolve s t\n | [] <- t = s\n | cs0 < ct0 || cs1 < ct1 = s\n | otherwise = t\n ++ mconcat (replicate numOcc lastSuffix)\n ++ toString crest\n where\n tKmp = getKmp t\n lastSuffix = kGetSuffix $ kFail $ kLast tKmp\n (C ct0 ct1) = getCount t\n (C cs0 cs1) = getCount s\n (C cts0 cts1) = getCount lastSuffix\n numOcc = maybeMin (f cs0 ct0 cts0) (f cs1 ct1 cts1)\n crest = C\n (cs0 - ct0 - cts0 * fromIntegral numOcc)\n (cs1 - ct1 - cts1 * fromIntegral numOcc)\n f cs ct cts = fmap fromIntegral $\n if cts == 0 then Nothing else Just $ (cs - ct) `div` cts\n\n maybeMin Nothing (Just x) = x\n maybeMin (Just x) Nothing = x\n maybeMin (Just x) (Just y) = min x y\n\nstripWindowsLB :: BS.ByteString -> BS.ByteString\nstripWindowsLB a = if BS.isSuffixOf (BS.pack \"\\r\") a\n then fromJust $ BS.stripSuffix (BS.pack \"\\r\") a\n else a\n\ntype LineReader a = State [BS.ByteString] a\n\ncurrentLine :: LineReader BS.ByteString\ncurrentLine = do\n ls <- get\n let (x, xs) = case ls of\n [] -> error \"No remain lines.\"\n l -> (head l, tail l)\n put xs\n return x\n\nrestLines :: LineReader [BS.ByteString]\nrestLines = do\n xs <- get\n put []\n return xs\n\nrunLineReader :: LineReader a -> [BS.ByteString] -> (a, [BS.ByteString])\nrunLineReader reader ls = runState reader (map stripWindowsLB ls)\n\nmain :: IO ()\nmain = do\n ls <- readLines\n let ((sl1, sl2), _) = flip runLineReader ls $ do\n rls <- restLines\n case rls of\n [l1, l2] -> return (BS.unpack l1, BS.unpack l2)\n _ -> error \"\"\n putStrLn $ solve sl1 sl2\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport Data.Int\nimport Data.Maybe\nimport Data.Semigroup\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport qualified Data.List as L\n\nreadLines :: IO [BS.ByteString]\nreadLines = BS.lines `fmap` BS.getContents\n\ndata KmpState a =\n KS a [a] (KmpState a)\n | KM a [a] (KmpState a) (KmpState a)\n | KEND\n\nkMatch :: Eq a => a -> KmpState a -> Bool\nkMatch _ KEND = False\nkMatch x (KM y _ _ _) = x == y\nkMatch x (KS y _ _ ) = x == y\n\nkNext :: KmpState a -> KmpState a\nkNext KEND = error \"Already the end of KMP state.\"\nkNext (KS _ _ n) = n\nkNext (KM _ _ _ n) = n\n\nkFail :: KmpState a -> KmpState a\nkFail KEND = error \"Already the end of KMP state.\"\nkFail (KM _ _ f _) = f\nkFail s@KS{} = s\n\nkFailToList :: (a -> b) -> KmpState a -> [b]\nkFailToList _ KEND = []\nkFailToList f (KS a _ n) = f a : kFailToList f n\nkFailToList f (KM _ _ p n) = f (e p) : kFailToList f n\n where\n e KEND = error \"Impossible\"\n e (KS k _ _) = k\n e (KM k _ _ _) = k\n\nkGetSuffix :: KmpState a -> [a]\nkGetSuffix KEND = []\nkGetSuffix (KS _ as _) = as\nkGetSuffix (KM _ as _ _) = as\n\nkLast :: KmpState a -> KmpState a\nkLast KEND = KEND\nkLast a@(KS _ _ KEND) = a\nkLast a@(KM _ _ _ KEND) = a\nkLast a = kLast $ kNext a\n\ngetKmp :: Eq a => [a] -> KmpState a\ngetKmp [] = KEND\ngetKmp y@[x] = KS x y KEND\ngetKmp z@(x:xs) = KS x z (kmp' xs self)\n where\n self = getKmp z\n\n kmp' [] _ = KEND\n kmp' t@(r:rs) curFail = KM r t curFail (kmp' rs nextFail)\n where\n nextFail = tryMatch curFail\n\n tryMatch st\n | kMatch r st = kNext st\n | u@KS{} <- st = u\n | u@KM{} <- st = tryMatch $ kFail u\n | KEND <- st = error \"Try to match end of KMP state\"\n\n\nstripWindowsLB :: BS.ByteString -> BS.ByteString\nstripWindowsLB a = if BS.isSuffixOf (BS.pack \"\\r\") a\n then fromJust $ BS.stripSuffix (BS.pack \"\\r\") a\n else a\n\ntype LineReader a = State [BS.ByteString] a\n\ncurrentLine :: LineReader BS.ByteString\ncurrentLine = do\n ls <- get\n let (x, xs) = case ls of\n [] -> error \"No remain lines.\"\n l -> (head l, tail l)\n put xs\n return x\n\nrestLines :: LineReader [BS.ByteString]\nrestLines = do\n xs <- get\n put []\n return xs\n\nrunLineReader :: LineReader a -> [BS.ByteString] -> (a, [BS.ByteString])\nrunLineReader reader ls = runState reader (map stripWindowsLB ls)\n\n\ndata Count = C {c0 :: Int32, c1 :: Int32}\n\ngetCount :: String -> Count\ngetCount = L.foldl' inc (C 0 0)\n where\n inc p@(C r0 r1) c = if c == '0' then p{c0 = r0 + 1} else p{c1 = r1 + 1}\n\ntoString :: Count -> String\ntoString (C x y) = replicate (fromIntegral x) '0'\n ++ replicate (fromIntegral y) '1'\n\nsolve :: String -> String -> String\nsolve s t\n | [] <- t = s\n | cs0 < ct0 || cs1 < ct1 = s\n | otherwise = t\n ++ mconcat (replicate numOcc lastSuffix)\n ++ toString crest\n where\n tKmp = getKmp t\n lastSuffix = case kGetSuffix $ kNext $ kFail $ kLast tKmp of\n [] -> t\n x -> x\n (C ct0 ct1) = getCount t\n (C cs0 cs1) = getCount s\n (C cts0 cts1) = getCount lastSuffix\n numOcc = maybeMin (f cs0 ct0 cts0) (f cs1 ct1 cts1)\n crest = C\n (cs0 - ct0 - cts0 * fromIntegral numOcc)\n (cs1 - ct1 - cts1 * fromIntegral numOcc)\n f cs ct cts = fmap fromIntegral $\n if cts == 0 then Nothing else Just $ (cs - ct) `div` cts\n\n maybeMin Nothing (Just x) = x\n maybeMin (Just x) Nothing = x\n maybeMin (Just x) (Just y) = min x y\n\nmain :: IO ()\nmain = do\n ls <- readLines\n let ((sl1, sl2), _) = flip runLineReader ls $ do\n rls <- restLines\n case rls of\n [l1, l2] -> return (BS.unpack l1, BS.unpack l2)\n _ -> error \"\"\n let a = kFailToList id $ getKmp $ zipWith Arg sl2 [1..] :: [Arg Char Int]\n -- print $ map (\\(Arg _ b) -> b) a\n putStrLn $ solve sl1 sl2\n"}], "src_uid": "6ac00fcd4a483f9f446e692d05fd31a4"} {"source_code": "module Main where\n\nimport Data.Maybe\n\nconvert :: String -> String -> Maybe String\nconvert prev y = if acc == [] then Nothing else Just (minimum acc) where\n acc = filter (>= prev) all\n all = concatMap vars [0 .. 3]\n vars n = map (\\c -> take n y ++ c:(drop (n+1) y)) ['0' .. '9']\n\nbuild :: String -> [String] -> [String]\nbuild _ [] = []\nbuild prev (y:ys) = conv : (build conv ys)\n where conv = fromMaybe \"9999\" $ convert prev y\n\nsolve :: [String] -> Maybe [String]\nsolve years = if last ans <= \"2011\" then Just ans else Nothing where\n ans = build \"1000\" years\n\nmain = do\n sn <- getLine\n sYear <- getContents\n let lYear = words sYear\n let ans = solve lYear\n putStrLn $ if ans == Nothing\n then \"No solution\"\n else unlines (fromMaybe [] ans)\n", "positive_code": [{"source_code": "main = interact $ unlines . solve . (map (read :: String -> Int)) . tail . lines\nsolve xs = if elem 0 ans then [\"No solution\"] else map show ans\n where ans = solve0 (1000:xs)\nsolve0 [x] = []\nsolve0 (x:y:xs) = if null ys then [0] else y':(solve0 (y':xs))\n where ys = filter (check y) [x..2011]\n y' = head ys\ncheck x y = 2>(length $ filter (==False) $ zipWith (==) (show x) (show y))\n"}], "negative_code": [], "src_uid": "c175d010d75c391d0b25391fecff007c"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE TypeOperators #-}\n\nmodule Main where\n\nimport Data.List\n-- import Data.Char\nimport Data.Maybe\n-- import Control.Applicative\nimport Control.Monad\nimport System.IO\n\nmain :: IO ()\nmain = do\n -- handle <- openFile \"input.txt\" ReadMode\n -- contents <- hGetContents handle\n contents <- getContents\n let linesOfFile = lines contents\n t = read $ (linesOfFile !! 0) :: Int\n a = map (\\x -> read x :: Int) . words $ (linesOfFile !! 1)\n b = map (\\x -> read x :: Int) . words $ (linesOfFile !! 2)\n res = solve a b\n in\n putStrLn $ unwords $ map show $ res\n\n -- ii <- getLine\n -- aa <- getLine\n -- bb <- getLine\n -- let\n -- nn = map (\\x -> read x :: Int) $ words $ ii\n -- n = nn !! 0\n -- k = nn !! 1\n -- a = map (\\x -> read x :: Int) $ words $ aa\n -- b = map (\\x -> read x :: Int) $ words $ bb\n\n -- res = solve a b\n -- in\n -- putStrLn res\n\nfindDiff _ [] _ = []\nfindDiff _ _ [] = []\nfindDiff i (x:xs) (y:ys) =\n if x /= y then i:findDiff (i + 1) xs ys else findDiff (i + 1) xs ys\n\n\nreplaceZero _ [] a = a\nreplaceZero _ _ [] = []\nreplaceZero i rr@(r:rs) (a:as) =\n if i == r then 0:replaceZero (i + 1) rs as\n else a:replaceZero (i + 1) rr as\n\nreplaceList _ [] = []\nreplaceList [] a = a\nreplaceList rr@(r:rs) (a:as) =\n if a == 0 then r:replaceList rs as\n else a:replaceList rr as\n\n\nsolve a b =\n let\n dff = findDiff 0 a b\n aa = replaceZero 0 dff a\n k = [1..length a] \\\\ aa\n r = replaceList k aa\n r1 = replaceList ([a!!(dff!!0)] ++ [b!!(dff!!1)]) aa\n r2 = replaceList ([b!!(dff!!0)] ++ [a!!(dff!!1)]) aa\n l1 = nub r1\n \n res = if length dff == 1 then r else\n if length l1 == length a then r1 else r2\n in\n res\n\n", "positive_code": [{"source_code": "import Data.List\n\ndoit :: [String] -> [String] -> [String]\ndoit [] _ = []\ndoit (\"0\":xs) (n:ns) = n : doit xs ns\ndoit (x:xs) ns = x : doit xs ns\n\nvalid :: [String] -> [String] -> Bool\nvalid ans a = (==) 1 . length . filter (uncurry (/=)) . zip ans $ a\n\nmain = do\n n <- readLn\n a <- getLine >>= return . words\n b <- getLine >>= return . words\n let numbers = map show $ [1..n] \\\\ (map (read . fst) . filter (uncurry (==)) . zip a $ b)\n let tmp = map (\\(x,y) -> if x == y then x else \"0\") . zip a $ b\n let ans1 = doit tmp numbers\n let ans2 = doit tmp . reverse $ numbers\n let ans = if valid ans1 a && valid ans1 b then ans1 else ans2\n putStrLn . unwords $ ans\n"}, {"source_code": "import qualified Data.Set as S\n\nglueWhereZero :: [Int] -> [Int] -> [Int]\nglueWhereZero [] b = b\nglueWhereZero (x:a) (y:b)\n | y == 0 = x : (glueWhereZero a b)\n | otherwise = y : (glueWhereZero (x:a) b)\n\nmain = do\n getLine\n as <- getLine\n bs <- getLine\n let a = map (\\x -> read x :: Int) $ words as\n let b = map (\\x -> read x :: Int) $ words bs\n let c = map (\\x -> if uncurry (==) x then fst x else 0) $ zip a b\n let r = S.toList $ S.difference (S.fromList [1..(length a)]) (S.fromList $ filter (/=0) c)\n let p1 = glueWhereZero r c\n let p2 = glueWhereZero (reverse r) c\n let tmp = length . (filter (uncurry (/=))) . (zip p1)\n putStrLn $ unwords $ map show $ if (tmp a) == 1 && (tmp b) == 1 then p1 else p2\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve n as bs = snd $ mapAccumL (\\k (a, b) -> if a /= b && a == k && (o || b == m) then (0, m) else (k, a)) k $ zip as bs\n where\n zs = zip as bs\n m = head $ [1..n] \\\\ as\n k = head $ fromMaybe undefined $ find (\\g -> case g of { [_, _] -> True; _ -> False }) $ group $ sort as\n o = case filter (uncurry (/=)) zs of { [_] -> True; _ -> False }\n\nmain = do\n n <- readInt <$> B.getLine\n as <- readInts <$> B.getLine\n bs <- readInts <$> B.getLine\n putStr $ unwords $ map show $ solve n as bs\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve n as bs = snd $ mapAccumL (\\k (a, b) -> if a /= b && a == k && (o || b == m) then (0, m) else (k, a)) (head $ fromMaybe undefined $ find (\\g -> case g of { [_, _] -> True; _ -> False }) $ group $ sort as) zs\n where\n zs = zip as bs\n o = case filter (uncurry (/=)) zs of { [_] -> True; _ -> False }\n m = head $ [1..n] \\\\ as\n\nmain = do\n n <- readInt <$> B.getLine\n as <- readInts <$> B.getLine\n bs <- readInts <$> B.getLine\n putStr $ unwords $ map show $ solve n as bs\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve n as bs = snd $ mapAccumL (\\k (a, b) -> if a /= b && a == k then (0, m) else (k, a)) k $ zip as bs\n where\n m = head $ [1..n] \\\\ as\n k = head $ fromMaybe undefined $ find (\\g -> case g of { [_, _] -> True; _ -> False }) $ group $ sort as\n\nmain = do\n n <- readInt <$> B.getLine\n as <- readInts <$> B.getLine\n bs <- readInts <$> B.getLine\n putStr $ unwords $ map show $ solve n as bs\n"}, {"source_code": "import Data.List\n\ndoit :: [String] -> [String] -> [String]\ndoit [] _ = []\ndoit (\"0\":xs) (n:ns) = n : doit xs ns\ndoit (x:xs) ns = x : doit xs ns\n\nmain = do\n n <- readLn\n a <- getLine >>= return . words\n b <- getLine >>= return . words\n let numbers = map show $ [1..n] \\\\ (map (read . fst) . filter (uncurry (==)) . zip a $ b)\n let tmp = map (\\(x,y) -> if x == y then x else \"0\") . zip a $ b\n putStrLn . unwords $ doit tmp numbers\n"}, {"source_code": "main = do\n getLine\n a <- getLine >>= return . words\n b <- getLine >>= return . words\n let tmp = filter (uncurry (/=) . fst) . zip (zip a b) $ [0..]\n let numbers = fst . head $ tmp\n let indices = map snd $ tmp\n putStr . unwords . take (head indices) $ a\n putStr $ \" \" ++ fst numbers ++ \" \"\n putStr . unwords . take ((head . tail $ indices) - (head indices) - 1) . drop (head indices + 1) $ a\n putStr $ \" \" ++ snd numbers ++ \" \"\n putStrLn . unwords . drop ((head . tail $ indices) + 1) $ a\n"}, {"source_code": "import qualified Data.Set as S\n\nglueWhereZero :: [Int] -> [Int] -> [Int]\nglueWhereZero [] b = b\nglueWhereZero (x:a) (y:b)\n | y == 0 = x : (glueWhereZero a b)\n | otherwise = y : (glueWhereZero (x:a) b)\n\nmain = do\n getLine\n as <- getLine\n bs <- getLine\n let a = map (\\x -> read x :: Int) $ words as\n let b = map (\\x -> read x :: Int) $ words bs\n let c = map (\\x -> if uncurry (==) x then fst x else 0) $ zip a b\n let r = S.toList $ S.difference (S.fromList [1..(length a)]) (S.fromList $ filter (/=0) c)\n let p1 = glueWhereZero r c\n let p2 = glueWhereZero (reverse r) c\n putStrLn $ unwords $ map show $ if (length $ filter (uncurry (/=)) $ zip a p1) == 1 && (length $ filter (uncurry (/=)) $ zip a p2) == 1 then\n p1\n else\n p2\n"}], "src_uid": "6fc3da19da8d9ab024cdd5acfc4f4164"} {"source_code": "diverse [] n = \"NO\"\ndiverse [a] n = if n == 1 then \"YES\\n\"++[a] else \"NO\"\ndiverse (a:b:cs) n = if a/=b then \"YES\\n\"++[a,b] else diverse (b:cs) n \n\nmain = do\n n <- getLine >>= return . (read :: String -> Int)\n s <- getLine \n putStrLn $ if length s == 1 then \"NO\" else diverse s n\n", "positive_code": [{"source_code": "f::String->String\nf []=\"\"\nf (x:[])=\"\"\nf (x:y:xs)\n |x/=y=(x:y:[])\n |otherwise=f (y:xs)\n \nmain = do\n e<-getLine\n e2<-getLine\n let a=f e2\n putStrLn $ if a==\"\" then \"NO\" else \"YES\\n\"++a"}, {"source_code": "diverseSubs :: [Char] -> [Char]\ndiverseSubs (a:[]) = \"\"\ndiverseSubs (a:b:rest) = if a /= b \n then [a,b] \n else diverseSubs (b:rest)\n\nmain :: IO ()\nmain = do\n n <- getLine\n line <- getLine\n let subline = diverseSubs line\n if subline == \"\"\n then putStrLn \"NO\"\n else mapM_ putStrLn [\"Yes\", subline]\n"}, {"source_code": "import Data.List\nmain = do\n getLine\n w <- getLine\n case find f (tails w) of\n Nothing -> putStrLn \"NO\"\n Just (a:b:_) -> putStrLn \"YES\" >> putStrLn [a,b]\nf (a:b:_) = a /= b\nf _ = False\n"}], "negative_code": [{"source_code": "diverse [] n = \"NO\"\ndiverse [a] n = if n == 1 then \"YES\\n\"++[a] else \"NO\"\ndiverse (a:b:cs) n = if a/=b then \"YES\\n\"++[a,b] else diverse (b:cs) n \n\nmain = do\n n <- getLine >>= return . (read :: String -> Int)\n s <- getLine \n putStrLn $ diverse s n\n"}, {"source_code": "import qualified Data.Set as S\nimport Data.List\nimport Control.Arrow\nmain = do\n l <- readLn\n w <- getLine\n let m = S.fromList $ map (length &&& head) $ group $ sort w\n m' = go l m\n if S.null m' then putStrLn \"NO\" else do\n putStrLn \"YES\"\n putStrLn $ intersect' w $ concat (map (uncurry replicate) (S.elems m'))\ngo l m | Just ((n,c),m') <- S.maxView m, 2*n > l =\n go (l-1) $ if n == 1 then m' else S.insert (n-1,c) m'\n | otherwise = m\nintersect' (a:as) bs | a `elem` bs = a : intersect' as (delete a bs)\n | otherwise = intersect' as bs\nintersect' [] _ = []\n"}, {"source_code": "import qualified Data.Set as S\nimport Data.List\nimport Control.Arrow\nmain = do\n l <- readLn\n w <- getLine\n let m = S.fromList $ map (length &&& head) $ group $ sort w\n m' = go l m\n if S.null m' then putStrLn \"NO\" else do\n putStrLn \"YES\"\n putStrLn $ intersect w $ concat (map (uncurry replicate) (S.elems m'))\ngo l m | Just ((n,c),m') <- S.maxView m, 2*n > l =\n go (l-1) $ if n == 1 then m' else S.insert (n-1,c) m'\n | otherwise = m\n"}], "src_uid": "ce4443581d4ee12db6607695cd567070"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nmain = readLn >>= putStr.unlines.map show.solve\n\nsolve :: Int -> [Integer]\nsolve n = take n $ go 1 2\n where\n go !k !x = a : go (k+1) (k * (k+1))\n where\n a :: Integer\n a = k*(k+1)*(k+1)-quot x k", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Monad\nimport Data.Array\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Integer]\n where fn x = let Just (y,_) = B.readInteger x in y\n \n\nmain = do\n a <- readLn :: IO Integer\n mapM_ print $ go 2 [1..a]\n \ngo _ [] = []\ngo st (l:ls) =\n let prev = st `div` l\n tgt = l*(l+1)*(l+1)\n sq = truncate . sqrt . fromIntegral\n in tgt-prev: go (sq (tgt*l)) ls\n"}, {"source_code": "{--\nimport Control.Monad( replicateM_, replicateM, forever)\nimport Control.Monad.Trans.State( StateT, evalStateT, execStateT, runStateT\n\t\t\t , get, put)\nimport Control.Monad.Trans.Writer( WriterT, tell, execWriterT)\nimport Control.Monad.Trans( lift)\ntype Level = Int\ntype State_T = StateT Level (WriterT [Integer] IO) Integer\ntype Writer_T = WriterT [Integer] IO [Integer] \nmain = do\n n <- readLn\n let process::Integer -> State_T\n\tprocess v = do\n\t lv <- get\n\t let nextLv = succ lv\n\t\tcandidate = map fun [1..]\n\t\t where\n\t\t fun l = (l, (nume l) `divMod` toInteger lv)\n\t\t nume l = l^2 * (toInteger nextLv)^2 - v\n\t\t(k,resultL) = repack . head $ dropWhile p candidate\n\t\t where\n\t\t repack (l,(d,m)) = (d,l)\n\t\t p (_,(_,m)) = m/=0\n\t put nextLv\n\t lift $ tell [k]\n\t return $ toInteger nextLv * resultL\n let writ::Writer_T\n\twrit = (`evalStateT` 1) $ \n\t\treplicateM n . process $ 2\n mapM_ print =<< execWriterT writ\n--}\nmain = do\n n <- readLn\n let l 0 = [2]::[Integer]\n\tl n = [n,2*n..]\n\tk n = head $ filter (0<) [m^2 * n' * (n'+1)^2 - l |\n\t\t\t\t m <- [1..]::[Integer] ,\n\t\t\t\t l <- l (n-1)\t ]\n\t where n' = toInteger n\n mapM_ (print . k) [1..n]\n"}, {"source_code": "main = readLn >>= putStr . unlines . map show . solve\nsolve n = 2 : map (\\n -> n * (n + 1)^2 - n + 1) [2 .. n]"}, {"source_code": "main = readLn >>= mapM_ print . solve\nsolve n = 2 : map (\\n -> n * (n + 1)^2 - n + 1) [2 .. n]"}, {"source_code": "import Control.Monad\n\n\nmain :: IO ()\nmain = do\n x <- readLn :: IO Int\n let ret = take x $ 2:map (\\i -> i * (i+1)*(i+1) - (i-1)) [2..] :: [Integer]\n forM_ ret print\n"}], "negative_code": [{"source_code": "main = readLn >>= putStr.unlines.map show.solve\n\nsolve :: Integer -> [Integer]\nsolve n = map f [1..n]\n where\n f 1 = 2\n f x = (x+1)^2 - x"}], "src_uid": "6264405c66b2690ada9f8cc6cff55f0b"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Int\nsolve n as = answer\n where\n g = L.foldl1' gcd as\n answer\n | g == 1 = 0\n | (gcd g n) == 1 = 1\n | (gcd g (n - 1)) == 1 = 2\n | otherwise = 3\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" $ answer\n", "positive_code": [{"source_code": "import System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . unwords . map show\r\n\r\nsolve xs \r\n | g == 1 = 0\r\n | gcd g len == 1 = 1\r\n | gcd g (len - 1) == 1 = 2\r\n | otherwise = 3\r\n where g = foldl gcd 0 xs\r\n len = length xs\r\n\r\nmain = do\r\n [t] <- getInts\r\n forM_ [1..t] $ \\_ -> do\r\n _ <- getInts\r\n xs <- getInts\r\n print $ solve xs\r\n"}], "negative_code": [], "src_uid": "ff3216bcb009cb963d7e734ceb0e9722"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List (foldl')\nimport Data.Array.IArray\nimport Data.Array.ST.Safe (STArray,STUArray,newArray,readArray,writeArray)\nimport Data.STRef (newSTRef,readSTRef,writeSTRef)\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST,runST)\nmain = do\n (n:ns) <- fmap (map read' . B.words) B.getContents\n let prep = do\n m2 <- newArray (0,n) (maxBound `div` 2) :: ST s (STUArray s Int Int)\n p2 <- newArray (0,n) \"E\" :: ST s (STArray s Int String)\n writeArray m2 1 0\n writeArray p2 1 \"\"\n return (m2,p2)\n let dp ns = runST $ do\n zero <- newSTRef Nothing\n (m2,p2) <- prep\n (m5,p5) <- prep\n let dp' ns = go ns 1 where\n go [] _ = return ()\n go (x:xs) i = do\n when (x == 0) $ writeSTRef zero (Just i)\n l2 <- readArray m2 (i-1)\n l2p <- readArray p2 (i-1)\n l5 <- readArray m5 (i-1)\n l5p <- readArray p5 (i-1)\n u2 <- readArray m2 i\n u2p <- readArray p2 i\n u5 <- readArray m5 i\n u5p <- readArray p5 i\n let n2 = factors 2 x\n n5 = factors 5 x\n (e2,e2p) = min ((l2+n2),('R':l2p)) ((u2+n2),('D':u2p))\n (e5,e5p) = min ((l5+n5),('R':l5p)) ((u5+n5),('D':u5p))\n writeArray m2 i e2\n writeArray p2 i e2p\n writeArray m5 i e5\n writeArray p5 i e5p\n go xs $! i+1\n mapM_ dp' ns\n b2 <- readArray m2 n\n b2p <- readArray p2 n\n b5 <- readArray m5 n\n b5p <- readArray p5 n\n z <- readSTRef zero\n let (m,p) = min (b2,b2p) (b5,b5p)\n return $ case z of\n Nothing -> (m,p)\n Just j -> min (m,p) (1,replicate (n-j) 'R' ++\n replicate (n-1) 'D' ++\n replicate (j-1) 'R' ++ \"E\")\n (m,p) = dp (chunksOf n ns)\n print m\n putStrLn (tail $ reverse p)\n{-# INLINE factors #-}\nfactors _ 0 = 1\nfactors n x = go x 0 where\n go x a | r == 0 = go q $! a + 1\n | otherwise = a\n where (q,r) = x `divMod` n\n{-# INLINE chunksOf #-}\nchunksOf n = go where\n go [] = []\n go xs = l : go r where (l,r) = splitAt n xs\n{-# INLINE read' #-}\nread' s = r where Just (r,_) = B.readInt s\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe (maybeToList)\nimport Data.Functor ((<$>))\nimport Data.Function (on)\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.Array.ST as ST\nimport qualified Data.ByteString.Char8 as B hiding (minimum)\n\ngetPows :: Int -> Int -> Int\ngetPows b x = case x `divMod` b of\n (x', 0) -> 1 + getPows b x'\n _ -> 0\n\nsolve :: Int -> U.UArray (Int, Int) Int -> Int -> (Int, String)\nsolve n mat b = (dp U.! (0, 0), findPath 0 0)\n where dp = ST.runSTUArray $ do\n let thunk = -1\n dp' <- ST.thaw (U.listArray ((0, 0), (n, n)) (repeat thunk) :: U.UArray (Int, Int) Int)\n\n let f i j = do\n tmp <- ST.readArray dp' (i, j)\n if tmp /= thunk\n then return tmp\n else do\n ans <- f' i j\n ST.writeArray dp' (i, j) $! ans\n return ans\n\n f' i j\n | i == n-1 && j == n-1 = return gridWeight\n | i == n-1 = rpath\n | j == n-1 = dpath\n | otherwise = minimum <$> sequence [dpath, rpath]\n where gridWeight = getPows b $ mat U.! (i, j)\n dpath = (gridWeight + ) <$> f (i+1) j\n rpath = (gridWeight + ) <$> f i (j+1)\n\n ST.writeArray dp' (0, 0) =<< f 0 0\n return dp'\n\n findPath i j\n | i == n-1 = replicate (n-j-1) 'R'\n | j == n-1 = replicate (n-i-1) 'D'\n | otherwise =\n if dp U.! (i, j+1) > dp U.! (i+1, j)\n then 'D' : findPath (i+1) j\n else 'R' : findPath i (j+1)\n\nreadInt :: B.ByteString -> Int\nreadInt = maybe 0 fst . B.readInt\n\nmain :: IO ()\nmain = do\n n : mat' <- map readInt . B.words <$> B.getContents\n let zeroPath idx = (1, replicate x 'R' ++ replicate (n-1) 'D' ++ replicate (n-1-x) 'R')\n where x = idx `mod` n\n maybeZeroPath = maybeToList $ zeroPath <$> elemIndex 0 mat'\n mat = U.listArray ((0, 0), (n-1, n-1)) (map (\\x -> if x == 0 then 10 else x) mat')\n\n let ans2 = solve n mat 2\n ans5 = solve n mat 5\n cands = maybeZeroPath ++ [ans2, ans5]\n (ansWeight, ansPath) = minimumBy (compare `on` fst) cands\n\n print ansWeight\n putStrLn ansPath\n"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\nimport GHC.List (scanl')\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> forced . readLine\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n forced xs = forceElements xs `seq` xs\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> forced . readLine\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q [] = q `seq` [q]\nscanl' f q (x:xs) = q `seq` rest `seq` q:rest\n where\n rest = scanl' f (f q x) xs\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n rows <- replicateM n $ B.getLine <&> readLine\n return (forced rows)\n where\n readLine = map' (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q [] = q `seq` [q]\nscanl' f q (x:xs) = q `seq` rest `seq` q:rest\n where\n rest = scanl' f (f q x) xs\n\nmap' :: (a -> b) -> [a] -> [b]\nmap' f [] = []\nmap' f (x:xs) = y `seq` y:map' f xs\n where y = f x\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\nimport GHC.List (scanl')\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n rows <- replicateM n $ B.getLine <&> forced . readLine\n return (forced rows)\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = forced $ scanl step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = forced $ scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> forced . readLine\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q ls = forced (scanl f q ls)\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.Unboxed (UArray)\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\nimport GHC.List (scanl')\n\ntype V = Int\ntype R = UArray Int V\n\nbadInput :: [R]\nbadInput = replicate 1000 $ I.listArray (1, 1000) (replicate 1000 646642320)\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [R]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> I.listArray (1, n) . readLine\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [R] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [R] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> R -> [Answer]\nfirstRow p row = scanl step initial rest\n where\n (first:rest) = I.elems row\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> R -> [Answer]\nnextRow p (firstUp:restUp) row = scanl' step initial (zip restUp rest)\n where\n (first:rest) = I.elems row\n initial = moveDown firstUp $ toWeight p first\n step !left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\nimport GHC.List (scanl')\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n rows <- replicateM n $ B.getLine <&> forced . readLine\n return (forced rows)\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n forced xs = forceElements xs `seq` xs\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> readLine\n where\n readLine = map' (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q [] = q `seq` [q]\nscanl' f q (x:xs) = q `seq` rest `seq` q:rest\n where\n rest = scanl' f (f q x) xs\n\nmap' :: (a -> b) -> [a] -> [b]\nmap' f [] = []\nmap' f (x:xs) = y `seq` y:map' f xs\n where y = f x\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> readLine\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q ls = forced (scanl f q ls)\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "import Data.List\nimport Data.Maybe (maybeToList)\nimport Data.Functor ((<$>))\nimport Data.Function (on)\nimport Control.Monad (when)\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.Array.ST as ST\nimport qualified Data.ByteString.Char8 as B hiding (minimum)\n\ngetPows :: Int -> Int -> Int\ngetPows b x = case x `divMod` b of\n (x', 0) -> 1 + getPows b x'\n _ -> 0\n\nsolve :: Int -> U.UArray (Int, Int) Int -> Int -> (Int, String)\nsolve n mat b = (dp U.! (0, 0), findPath 0 0)\n where dp = ST.runSTUArray $ do\n let thunk = -1\n dp' <- ST.thaw (U.listArray ((0, 0), (n, n)) (repeat thunk) :: U.UArray (Int, Int) Int)\n\n let f i j = do\n tmp <- ST.readArray dp' (i, j)\n when (tmp == thunk) $ ST.writeArray dp' (i, j) =<< f' i j\n ST.readArray dp' (i, j)\n\n f' i j\n | i == n-1 && j == n-1 = return gridWeight\n | i == n-1 = rpath\n | j == n-1 = dpath\n | otherwise = minimum <$> sequence [dpath, rpath]\n where gridWeight = getPows b $ mat U.! (i, j)\n dpath = (gridWeight + ) <$> f (i+1) j\n rpath = (gridWeight + ) <$> f i (j+1)\n\n ST.writeArray dp' (0, 0) =<< f 0 0\n return dp'\n\n findPath i j\n | i == n-1 = replicate (n-j-1) 'R'\n | j == n-1 = replicate (n-i-1) 'D'\n | otherwise =\n if dp U.! (i, j+1) > dp U.! (i+1, j)\n then 'D' : findPath (i+1) j\n else 'R' : findPath i (j+1)\n\nreadInt :: B.ByteString -> Int\nreadInt = maybe 0 fst . B.readInt\n\nmain :: IO ()\nmain = do\n n : mat' <- map readInt . B.words <$> B.getContents\n let zeroPath idx = (1, replicate x 'R' ++ replicate (n-1) 'D' ++ replicate (n-1-x) 'R')\n where x = idx `mod` n\n maybeZeroPath = maybeToList $ zeroPath <$> elemIndex 0 mat'\n mat = U.listArray ((0, 0), (n-1, n-1)) (map (\\x -> if x == 0 then 10 else x) mat')\n\n let cands = maybeZeroPath ++ map (solve n mat) [2, 5]\n (ansWeight, ansPath) = minimumBy (compare `on` fst) cands\n\n print ansWeight\n putStrLn ansPath\n"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n rows <- replicateM n $ B.getLine <&> forced . readLine\n return $ forced rows\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q ls = forced (scanl f q ls)\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ B.getLine <&> readLine\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldl' (flip seq) ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q = forced . scanl f q\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as B8\nimport Data.List\nimport Debug.Trace\nimport Control.Monad.ST\nimport Data.Array.ST\n\ndata Path = PathUp | PathLeft | NoPath\n\tderiving (Show, Eq)\n--data Cell = Cell !Int !Path -- Cost Path\n--\tderiving (Show)\n\n--cost (Cell c _) = c\n\ndecide up left = if up == noVal\n\t\tthen if left == 0 then PathLeft else PathUp\n\t\telse if left == noVal\n\t\t\tthen if up == 0 then PathUp else PathLeft\n\t\t\telse if left <= up then PathLeft else PathUp\n\npath (i, j) arr\n\t| (i == 1) && (j == 1) = NoPath\n\t| (i == 1) && (j > 1) = PathUp\n\t| (i > 1) && (j == 1) = PathLeft\n\t| (i > 1) && (j > 1) = decide up left\n\t\twhere\n\t\t\tup = arr ! (i, j - 1)\n\t\t\tleft = arr ! (i - 1, j)\n\nnoVal = -1\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n B.getLine\n\tlet arr = map (B.split 0x20) lines\n\treturn $! (n, U.array ((1, 1), (n, n)) [((i, j), v) | (line, j) <- (zip arr [1..n]), (num, i) <- (zip line [1..n]), let !v = readNumber num])\n\twhere\n\t\treadNumber x = case B8.readInt x of\n\t\t\tJust (!num, _) -> num\n\t\t\tNothing -> error \"Unable to read input\"\n\ncalcPaths :: U.Array (Int, Int) Int -> Int -> Int -> Array (Int, Int) Int\ncalcPaths arr n divisor = runSTArray $ do\n\ta <- newArray ((1, 1), (n, n)) 0 :: ST s (STArray s (Int,Int) Int)\n\tforM_ [1..n] $! \\diag -> do\n\t\tlet indices = diagIndices $! diag\n\t\tforM_ indices $! \\(i, j) -> case () of\n\t\t\t_ | (i == 1) && (j == 1) -> writeArray a (i, j) current\n\t\t\t\t| (i == 1) && (j > 1) -> do\n\t\t\t\t\tup <- readArray a (i, j - 1)\n\t\t\t\t\twriteArray a (i, j) $! normalize current up\n\t\t\t\t| (i > 1) && (j == 1) -> do\n\t\t\t\t\tleft <- readArray a (i - 1, j)\n\t\t\t\t\twriteArray a (i, j) $! normalize current left\n\t\t\t\t| (i > 1) && (j > 1) -> do\n\t\t\t\t\tup <- readArray a (i, j - 1)\n\t\t\t\t\tleft <- readArray a (i - 1, j)\n\t\t\t\t\twriteArray a (i, j) $! if decide up left == PathLeft\n\t\t\t\t\t\tthen normalize current left\n\t\t\t\t\t\telse normalize current up\n\t\t\t\twhere \n\t\t\t\t\tcurrent = if (arr U.! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\treturn a\n\twhere \n\t\tnormalize !value !addend = (if value == noVal || addend == noVal then noVal else value + addend)\n\t\tdiagIndices diag = if diag == n then [(diag, diag)] else\n\t\t\tzip [diag..n] (repeat diag) ++ zip (repeat diag) [(diag + 1)..n]\n\npowerOf :: Int -> Int -> Int\npowerOf q p = powerOf' q p 0\n\twhere\n\t\tpowerOf' q p n = if p `mod` q /= 0 then n else powerOf' q (p `div` q) (n + 1)\n\ngetPath arr n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if path (i,j) arr == PathUp\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths2 = calcPaths matrix n 2\n\tlet cost2 = (paths2 ! (n, n))\n\tpath2 <- do\n\t\treturn $ getPath paths2 n\n\n\tlet paths5 = calcPaths matrix n 5\n\tlet cost5 = (paths5 ! (n, n))\n\tpath5 <- do\n\t\treturn $ getPath paths5 n\n\n\tif abs cost2 < abs cost5\n\t\tthen do\n\t\t\tif cost2 < 0 then print 1 else print cost2\n\t\t\tputStrLn path2\n\t\telse do\n\t\t\tif cost5 < 0 then print 1 else print cost5\n\t\t\tputStrLn path5\n"}, {"source_code": "module Main where\n\nimport Data.Array.IArray\nimport qualified Data.Array as A\nimport Data.List (foldl')\nimport qualified Data.ByteString.Char8 as B\n\nscanl' :: (a -> b -> a) -> a -> [b] -> [a]\nscanl' _ z [] = [z]\nscanl' f z (x:xs) = let u = f z x\n ys = z:scanl' f u xs\n in u `seq` ys `seq` ys\n\npowerOf :: Int -> Int -> Int\npowerOf _ 0 = error \"powerOf 0\"\npowerOf p n = case n `mod` p of\n 0 -> 1 + powerOf p (n `div` p)\n _ -> 0\n\ndata DP = DP { isZero :: !Bool\n , minNum :: !Int\n , go :: !String }\n deriving (Show)\n\ndpCost :: DP -> Int\ndpCost (DP True _ _) = 1\ndpCost (DP False c _) = c\n\ndp :: Int -> Int -> [[Int]] -> DP\ndp n p (row:rows) = (foldl' (dpRow n p) (dpFirstRow n p row) rows)!(n-1)\n\ndpRow :: Int -> Int -> A.Array Int DP -> [Int] -> A.Array Int DP\ndpRow n p ups (cur:curs) = listArray (0,n-1) $ scanl' step dpInit (zip [1..] curs) where\n step (DP _ _ leftGo) (i, 0)\n = DP True 1 ('R':leftGo)\n step (DP leftZero leftNum leftGo) (i, k)\n | upCost < leftCost = DP upZero upCost ('D':upGo)\n | otherwise = DP leftZero leftCost ('R':leftGo)\n where DP upZero upNum upGo = ups!i\n k' = powerOf p k\n upCost = if upZero then 1 else k' + upNum\n leftCost = if leftZero then 1 else k' + leftNum\n dpInit = case cur of\n 0 -> DP True 1 ('D':go up)\n k -> DP False (powerOf p k + minNum up) ('D':go up)\n up = ups!0\n\ndpFirstRow :: Int -> Int -> [Int] -> A.Array Int DP\ndpFirstRow n p currs = listArray (0,n-1) $ zipWith zipper costs rs where\n zipper (dpZero, cost) dir = DP dpZero cost dir\n costs = tail $ scanl' step (False, 0) currs\n step (True, _) _ = (True, 1)\n step (_, cost) 0 = (True, 1)\n step (_, cost) k = (False, cost + powerOf p k)\n rs = iterate ('R':) []\n\ninputGrids :: IO (Int, [[Int]])\ninputGrids = do\n n <- readLn\n grids <- sequence $ replicate n $ do\n line <- B.getLine\n return $ map (maybe (error \"Read\") fst) . map B.readInt . B.words $ line\n return (n, grids)\n\nmain :: IO ()\nmain = do\n (n, grids) <- inputGrids\n let dp2 = dp n 2 grids\n dp5 = dp n 5 grids\n if dpCost dp2 <= dpCost dp5\n then (print . dpCost $ dp2) >> (putStrLn . reverse . go $ dp2)\n else (print . dpCost $ dp5) >> (putStrLn . reverse . go $ dp5)\n "}, {"source_code": "{-# LANGUAGE DerivingVia #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Data.Word\n\ntype V = Int\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> readInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n rows <- replicateM n $ B.getLine <&> forced . readLine\n return (forced rows)\n where\n readLine = map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl' step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nforceElements :: [a] -> ()\nforceElements = foldr seq ()\n\nforced :: [a] -> [a]\nforced xs = forceElements xs `seq` xs\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f q [] = q `seq` [q]\nscanl' f q (x:xs) = q `seq` rest `seq` q:rest\n where\n rest = scanl' f (f q x) xs\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "module Main where\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport Data.Array.Unboxed\nimport Data.List (foldl')\nimport qualified Data.ByteString.Char8 as B\n\nscanl' :: (a -> b -> a) -> a -> [b] -> [a]\nscanl' _ z [] = [z]\nscanl' f z (x:xs) = let u = f z x\n ys = z:scanl' f u xs\n in u `seq` ys `seq` ys\n\npowerOf :: Int -> Int -> Int\npowerOf _ 0 = error \"powerOf 0\"\npowerOf p n = case n `mod` p of\n 0 -> 1 + powerOf p (n `div` p)\n _ -> 0\n\ndata DP = DP { isZero :: !Bool\n , minNum :: !Int\n , go :: !String }\n deriving (Show)\n\ndpCost :: DP -> Int\ndpCost (DP True _ _) = 1\ndpCost (DP False c _) = c\n\ndp :: Int -> Int -> [UArray Int Int] -> DP\ndp n p (row:rows) = (foldl' (dpRow n p) (dpFirstRow n p (I.elems row)) rows)!(n-1)\n\ndpRow :: Int -> Int -> A.Array Int DP -> UArray Int Int -> A.Array Int DP\ndpRow n p ups curs = I.listArray (0,n-1) $ scanl' step dpInit [1..n-1] where\n step (DP _ _ leftGo) n\n | curs!n == 0 = DP True 1 ('R':leftGo)\n step (DP leftZero leftNum leftGo) n\n | upCost < leftCost = DP upZero upCost ('D':upGo)\n | otherwise = DP leftZero leftCost ('R':leftGo)\n where DP upZero upNum upGo = ups!n\n cur = powerOf p (curs!n)\n upCost = if upZero then 1 else cur + upNum\n leftCost = if leftZero then 1 else cur + leftNum\n dpInit = case curs!0 of\n 0 -> DP True 1 ('D':go up)\n k -> DP False (powerOf p k + minNum up) ('D':go up)\n up = ups!0\n\ndpFirstRow :: Int -> Int -> [Int] -> A.Array Int DP\ndpFirstRow n p currs = I.listArray (0, n-1) $ zipWith zipper costs rs where\n zipper (dpZero, cost) dir = DP dpZero cost dir\n costs = tail $ scanl' step (False, 0) currs\n step (True, _) _ = (True, 1)\n step (_, cost) 0 = (True, 1)\n step (_, cost) k = (False, let u = cost + powerOf p k in u `seq` u)\n rs = iterate ('R':) []\n\ninputGrids :: IO (Int, [UArray Int Int])\ninputGrids = do\n n <- readLn\n grids <- sequence $ replicate n $ do\n line <- B.getLine\n let ns = map (maybe (error \"Read\") fst) . map B.readInt . B.words $ line\n return $! I.listArray (0, n-1) ns\n return (n, grids)\n\nmain :: IO ()\nmain = do\n (n, grids) <- inputGrids\n let dp2 = dp n 2 grids\n dp5 = dp n 5 grids\n if dpCost dp2 <= dpCost dp5\n then (print . dpCost $ dp2) >> (putStrLn . reverse . go $ dp2)\n else (print . dpCost $ dp5) >> (putStrLn . reverse . go $ dp5)\n"}, {"source_code": "module Main where\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport Data.Array.Unboxed\nimport Data.List (foldl')\nimport qualified Data.ByteString.Char8 as B\n\nscanl' :: (a -> b -> a) -> a -> [b] -> [a]\nscanl' _ z [] = [z]\nscanl' f z (x:xs) = let u = f z x\n ys = z:scanl' f u xs\n in u `seq` ys `seq` ys\n\npowerOf :: Int -> Int -> Int\npowerOf _ 0 = error \"powerOf 0\"\npowerOf p n = case n `mod` p of\n 0 -> 1 + powerOf p (n `div` p)\n _ -> 0\n\ndata DP = DP { isZero :: !Bool\n , minNum :: !Int\n , go :: !String }\n deriving (Show)\n\ndpCost :: DP -> Int\ndpCost (DP True _ _) = 1\ndpCost (DP False c _) = c\n\ndp :: Int -> Int -> [UArray Int Int] -> DP\ndp n p (row:rows) = last $ foldl' (dpRow n p) (dpFirstRow n p row) rows\n\ndpRow :: Int -> Int -> [DP] -> UArray Int Int -> [DP]\ndpRow n p (up:ups) curs = scanl' step dpInit $ zip [1..] ups where\n step (DP _ _ leftGo) (k, _)\n | curs!k == 0 = DP True 1 ('R':leftGo)\n step (DP leftZero leftNum leftGo) (k, DP upZero upNum upGo)\n | upCost < leftCost = DP upZero upCost ('D':upGo)\n | otherwise = DP leftZero leftCost ('R':leftGo)\n where k' = powerOf p (curs!k)\n upCost = if upZero then 1 else k' + upNum\n leftCost = if leftZero then 1 else k' + leftNum\n dpInit = case curs!0 of\n 0 -> DP True 1 ('D':go up)\n k -> DP False (powerOf p k + minNum up) ('D':go up)\n\ndpFirstRow :: Int -> Int -> UArray Int Int -> [DP]\ndpFirstRow n p currs = zipWith zipper costs rs where\n zipper (dpZero, cost) dir = DP dpZero cost dir\n costs = tail $ scanl' step (False, 0) (I.elems currs)\n step (True, _) _ = (True, 1)\n step (_, cost) 0 = (True, 1)\n step (_, cost) k = (False, cost + powerOf p k)\n rs = iterate ('R':) []\n\ninputGrids :: IO (Int, [UArray Int Int])\ninputGrids = do\n n <- readLn\n grids <- sequence $ replicate n $ do\n line <- B.getLine\n let ns = map (maybe (error \"Read\") fst) . map B.readInt . B.words $ line\n return (I.listArray (0, n-1) ns)\n return (n, grids)\n\nmain :: IO ()\nmain = do\n (n, grids) <- inputGrids\n let dp2 = dp n 2 grids\n dp5 = dp n 5 grids\n if dpCost dp2 <= dpCost dp5\n then (print . dpCost $ dp2) >> (putStrLn . reverse . go $ dp2)\n else (print . dpCost $ dp5) >> (putStrLn . reverse . go $ dp5)\n"}, {"source_code": "module Main where\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport Data.Array.Unboxed\nimport Data.List (foldl')\nimport qualified Data.ByteString.Char8 as B\n\nscanl' :: (a -> b -> a) -> a -> [b] -> [a]\nscanl' _ z [] = [z]\nscanl' f z (x:xs) = let u = f z x\n ys = z:scanl' f u xs\n in u `seq` ys `seq` ys\n\npowerOf :: Int -> Int -> Int\npowerOf _ 0 = error \"powerOf 0\"\npowerOf p n = case n `mod` p of\n 0 -> 1 + powerOf p (n `div` p)\n _ -> 0\n\ndata DP = DP { isZero :: !Bool\n , minNum :: !Int\n , go :: !String }\n deriving (Show)\n\ndpCost :: DP -> Int\ndpCost (DP True _ _) = 1\ndpCost (DP False c _) = c\n\ndp :: Int -> Int -> [UArray Int Int] -> DP\ndp n p (row:rows) = (foldl' (dpRow n p) (dpFirstRow n p (I.elems row)) rows)!(n-1)\n\ndpRow :: Int -> Int -> A.Array Int DP -> UArray Int Int -> A.Array Int DP\ndpRow n p ups curs = I.listArray (0,n-1) $ scanl' step dpInit [1..n-1] where\n step (DP _ _ leftGo) n\n | curs!n == 0 = DP True 1 ('R':leftGo)\n step (DP leftZero leftNum leftGo) n\n | upCost < leftCost = DP upZero upCost ('D':upGo)\n | otherwise = DP leftZero leftCost ('R':leftGo)\n where DP upZero upNum upGo = ups!n\n cur = powerOf p (curs!n)\n upCost = if upZero then 1 else cur + upNum\n leftCost = if leftZero then 1 else cur + leftNum\n dpInit = case curs!0 of\n 0 -> DP True 1 ('D':go up)\n k -> DP False (powerOf p k + minNum up) ('D':go up)\n up = ups!0\n\ndpFirstRow :: Int -> Int -> [Int] -> A.Array Int DP\ndpFirstRow n p currs = I.listArray (0, n-1) $ zipWith zipper costs rs where\n zipper (dpZero, cost) dir = DP dpZero cost dir\n costs = tail $ scanl' step (False, 0) currs\n step (True, _) _ = (True, 1)\n step (_, cost) 0 = (True, 1)\n step (_, cost) k = (False, cost + powerOf p k)\n rs = iterate ('R':) []\n\ninputGrids :: IO (Int, [UArray Int Int])\ninputGrids = do\n n <- readLn\n grids <- sequence $ replicate n $ do\n line <- B.getLine\n let ns = map (maybe (error \"Read\") fst) . map B.readInt . B.words $ line\n return $! I.listArray (0, n-1) ns\n return (n, grids)\n\nmain :: IO ()\nmain = do\n (n, grids) <- inputGrids\n let dp2 = dp n 2 grids\n dp5 = dp n 5 grids\n if dpCost dp2 <= dpCost dp5\n then (print . dpCost $ dp2) >> (putStrLn . reverse . go $ dp2)\n else (print . dpCost $ dp5) >> (putStrLn . reverse . go $ dp5)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe (maybeToList)\nimport Data.Functor ((<$>))\nimport Data.Function (on)\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as B\n\ngetPows :: Int -> Int -> Int\ngetPows b x = case x `divMod` b of\n (x', 0) -> 1 + getPows b x'\n _ -> 0\n\nsolve :: Int -> U.Array (Int, Int) Int -> (Int, String)\nsolve n mat = dp A.! (0, 0)\n where dp = A.array ((0, 0), (n-1, n-1)) [((i, j), f i j) | i <- [0..n-1], j <- [0..n-1]]\n f i j\n | i == n-1 && j == n-1 = (0, \"\")\n | i == n-1 = dpath\n | j == n-1 = rpath\n | otherwise = minimumBy (compare `on` fst) [dpath, rpath]\n where gridWeight = mat U.! (i, j)\n\n (dweight', dpath') = dp A.! (i, j+1)\n dpath = (gridWeight + dweight', 'R' : dpath')\n\n (rweight', rpath') = dp A.! (i+1, j)\n rpath = (gridWeight + rweight', 'D' : rpath')\n\nmain :: IO ()\nmain = do\n n : mat' <- map (maybe 0 fst . B.readInt) . B.words <$> B.getContents\n\n let mat = U.listArray ((0, 0), (n-1, n-1)) (map (\\x -> if x == 0 then 10 else x) mat')\n\n mat2 = U.amap (getPows 2) mat\n mat5 = U.amap (getPows 5) mat\n\n zeroPath idx = (1, replicate x 'R' ++ replicate n 'D' ++ replicate (n-x) 'R')\n where x = idx `mod` n\n cands = [solve n mat2, solve n mat5] ++ maybeToList (zeroPath <$> elemIndex 0 mat')\n\n (ansWeight, ansPath) = minimumBy (compare `on` fst) cands\n\n print ansWeight\n putStrLn ansPath"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Debug.Trace\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 10000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n divisor = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell current noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell (normalize current costUp) (normalize current costUp) noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell (normalize current costLeft) noVal (normalize current costLeft)\n\t\t\t\t| (i > 1) && (j > 1) = Cell (normalize current $ minimum [costLeft, costUp]) (normalize current costUp) (normalize current costLeft)\n\t\t\t\twhere\n\t\t\t\t\tcostUp = cost (a ! (i, j - 1))\n\t\t\t\t\tcostLeft = cost (a ! (i - 1, j))\n\t\t\t\t\tcurrent = if (arr ! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\t\t\t\t\tnormalize value addend = (if value == noVal then 1 else value + addend)\n\npowerOf :: Integer -> Integer -> Integer\npowerOf q p = toInteger $ length $ takeWhile (== 0) $ map ((flip mod) q) $ iterate ((flip div) q) p\n\ngetPath arr1 arr2 n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if max (up cell_1) (up cell_2) < max (left cell_1) (left cell_2)\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\t\t\twhere\n\t\t\t\tcell_1 = arr1 ! (i, j)\n\t\t\t\tcell_2 = arr2 ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\t--print matrix\n\tlet paths2 = calcPaths matrix n 2\n\tlet paths5 = calcPaths matrix n 5\n{-\tputStrLn \"------\"\n\tprint paths2\n\tputStrLn \"------\"\n\tprint paths5\n\tputStrLn \"------\"\n\t-}\n\t\n\tprint $ min (cost $ paths2 ! (n, n)) (cost $ paths5 ! (n, n))\n\tputStrLn $ getPath paths2 paths5 n\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Debug.Trace\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 10000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n divisor = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell current noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell (normalize current costUp) (normalize current costUp) noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell (normalize current costLeft) noVal (normalize current costLeft)\n\t\t\t\t| (i > 1) && (j > 1) = Cell (normalize current $ minimum [costLeft, costUp]) (normalize current costUp) (normalize current costLeft)\n\t\t\t\twhere\n\t\t\t\t\tcostUp = cost (a ! (i, j - 1))\n\t\t\t\t\tcostLeft = cost (a ! (i - 1, j))\n\t\t\t\t\tcurrent = if (arr ! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\t\t\t\t\tnormalize value addend = (if value == noVal then 1 else value + addend)\n\npowerOf :: Integer -> Integer -> Integer\npowerOf q p = toInteger $ length $ takeWhile (== 0) $ map ((flip mod) q) $ iterate ((flip div) q) p\n\ngetPath arr1 arr2 n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if decide (up cell_1) (up cell_2) (left cell_1) (left cell_2)\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\t\t\twhere\n\t\t\t\tcell_1 = arr1 ! (i, j)\n\t\t\t\tcell_2 = arr2 ! (i, j)\n\t\t\t\tdecide cu1 cu2 cl1 cl2 =\n\t\t\t\t\tcase min cu1 cu2 `compare` min cl1 cl2 of\n\t\t\t\t\t\tLT -> True\n\t\t\t\t\t\tGT -> False\n\t\t\t\t\t\tEQ -> max cu1 cu2 < max cl1 cl2\n\nmain = do\n\t(n, matrix) <- getInput\n--\tprint matrix\n\tlet paths2 = calcPaths matrix n 2\n\tlet paths5 = calcPaths matrix n 5\n--\tputStrLn \"------\"\n--\tprint paths2\n--\tputStrLn \"------\"\n--\tprint paths5\n--\tputStrLn \"------\"\n\t\n\tprint $ min (cost $ paths2 ! (n, n)) (cost $ paths5 ! (n, n))\n\tputStrLn $ getPath paths2 paths5 n\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 1000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell (arr ! (i, j)) noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell costUp costUp noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell costLeft noVal costLeft\n\t\t\t\t| (i > 1) && (j > 1) = Cell (minimumBy (\\x y -> trailingZeroes x `compare` trailingZeroes y ) [costUp, costLeft]) costUp costLeft\n\t\t\t\twhere\n\t\t\t\t\tcostUp = (arr ! (i, j) * cost (a ! (i, j - 1)))\n\t\t\t\t\tcostLeft = (arr ! (i, j) * cost (a ! (i - 1, j)))\n\ngetPath arr n = reverse $ getPath' arr n (n, n)\n\twhere\n\t\tgetPath' arr n (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if (trailingZeroes . up) cell < (trailingZeroes . left) cell\n\t\t\t\tthen 'D' : getPath' arr n (i, j - 1)\n\t\t\t\telse 'R' : getPath' arr n (i - 1, j)\n\t\t\twhere cell = arr ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths = calcPaths matrix n\n\t--print paths\n\tprint $ trailingZeroes $ cost $ paths ! (n, n)\n\tputStrLn $ getPath paths n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Down Right\n\tderiving (Show)\n\ndown (Cell _ d _) = d\nright (Cell _ _ r) = r\ncost (Cell c _ _) = c\nvalue (Cell _ d r) = undefined\n\nnoVal = 1000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (i - 1)) !! (j - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == n) && (j == n) = Cell (arr ! (i, j)) noVal noVal\n\t\t\t\t| (i == n) && (j < n) = Cell costDown costDown noVal\n\t\t\t\t| (i < n) && (j == n) = Cell costRight noVal costRight\n\t\t\t\t| (i < n) && (j < n) = Cell (minimumBy (\\x y -> trailingZeroes x `compare` trailingZeroes y ) [costDown, costRight]) costDown costRight\n\t\t\t\twhere\n\t\t\t\t\tcostDown = (arr ! (i, j) * cost (a ! (i, j + 1)))\n\t\t\t\t\tcostRight = (arr ! (i, j) * cost (a ! (i + 1, j)))\n\ngetPath arr n = getPath' arr n (1, 1)\n\twhere\n\t\tgetPath' arr n (i, j)\n\t\t\t| (i, j) == (n, n) = \"\"\n\t\t\t| otherwise = if (trailingZeroes . down) cell < (trailingZeroes . right) cell\n\t\t\t\tthen 'R' : getPath' arr n (i, j + 1)\n\t\t\t\telse 'D' : getPath' arr n (i + 1, j)\n\t\t\twhere cell = arr ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths = calcPaths matrix n\n\tprint $ trailingZeroes $ cost $ paths ! (1, 1)\n\tputStrLn $ getPath paths n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as B8\nimport Data.List\nimport Debug.Trace\nimport Control.Monad.ST\nimport Data.Array.ST\n\ndata Path = PathUp | PathLeft | NoPath\n\tderiving (Show, Eq)\n--data Cell = Cell !Int !Path -- Cost Path\n--\tderiving (Show)\n\n--cost (Cell c _) = c\n\npath (i, j) arr\n\t| (i == 1) && (j == 1) = NoPath\n\t| (i == 1) && (j > 1) = PathUp\n\t| (i > 1) && (j == 1) = PathLeft\n\t| (i > 1) && (j > 1) = if up <= left then PathUp else PathLeft\n\t\twhere\n\t\t\tup = arr ! (i, j - 1)\n\t\t\tleft = arr ! (i - 1, j)\n\nnoVal = -1\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n B.getLine\n\tlet arr = map (B.split 0x20) lines\n\treturn $! (n, U.array ((1, 1), (n, n)) [((i, j), v) | (line, j) <- (zip arr [1..n]), (num, i) <- (zip line [1..n]), let !v = readNumber num])\n\twhere\n\t\treadNumber x = case B8.readInt x of\n\t\t\tJust (!num, _) -> num\n\t\t\tNothing -> error \"Unable to read input\"\n\ntrailingZeroes :: Int -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths :: U.Array (Int, Int) Int -> Int -> Int -> Array (Int, Int) Int\ncalcPaths arr n divisor = runSTArray $ do\n\ta <- newArray ((1, 1), (n, n)) 0 :: ST s (STArray s (Int,Int) Int)\n\tforM_ [1..n] $! \\diag -> do\n\t\tlet indices = diagIndices $! diag\n\t\tforM_ indices $! \\(i, j) -> case () of\n\t\t\t_ | (i == 1) && (j == 1) -> writeArray a (i, j) current\n\t\t\t\t| (i == 1) && (j > 1) -> do\n\t\t\t\t\tup <- readArray a (i, j - 1)\n\t\t\t\t\twriteArray a (i, j) $! normalize current up\n\t\t\t\t| (i > 1) && (j == 1) -> do\n\t\t\t\t\tleft <- readArray a (i - 1, j)\n\t\t\t\t\twriteArray a (i, j) $! normalize current left\n\t\t\t\t| (i > 1) && (j > 1) -> do\n\t\t\t\t\tup <- readArray a (i, j - 1)\n\t\t\t\t\tleft <- readArray a (i - 1, j)\n\t\t\t\t\twriteArray a (i, j) $! if left <= up\n\t\t\t\t\t\tthen normalize current left\n\t\t\t\t\t\telse normalize current up\n\t\t\t\twhere \n\t\t\t\t\tcurrent = if (arr U.! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\treturn a\n\twhere \n\t\tnormalize !value !addend = (if value == noVal then 1 else value + addend)\n\t\tdiagIndices diag = if diag == n then [(diag, diag)] else\n\t\t\tzip [diag..n] (repeat diag) ++ zip (repeat diag) [(diag + 1)..n]\n\npowerOf :: Int -> Int -> Int\npowerOf q p = powerOf' q p 0\n\twhere\n\t\tpowerOf' q p n = if p `mod` q /= 0 then n else powerOf' q (p `div` q) (n + 1)\n\ngetPath arr n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if path (i,j) arr == PathUp\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths2 = calcPaths matrix n 2\n\tlet cost2 = (paths2 ! (n, n))\n\tpath2 <- do\n\t\treturn $ getPath paths2 n\n\n\tlet paths5 = calcPaths matrix n 5\n\tlet cost5 = (paths5 ! (n, n))\n\tpath5 <- do\n\t\treturn $ getPath paths5 n\n\n\tif cost2 < cost5\n\t\tthen do\n\t\t\tprint cost2\n\t\t\tputStrLn path2\n\t\telse do\n\t\t\tprint cost5\n\t\t\tputStrLn path5\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Debug.Trace\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 10000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n divisor = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell current noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell (normalize current costUp) (normalize current costUp) noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell (normalize current costLeft) noVal (normalize current costLeft)\n\t\t\t\t| (i > 1) && (j > 1) = Cell (normalize current $ minimum [costLeft, costUp]) (normalize current costUp) (normalize current costLeft)\n\t\t\t\twhere\n\t\t\t\t\tcostUp = cost (a ! (i, j - 1))\n\t\t\t\t\tcostLeft = cost (a ! (i - 1, j))\n\t\t\t\t\tcurrent = if (arr ! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\t\t\t\t\tnormalize value addend = (if value == noVal then 1 else value + addend)\n\npowerOf :: Integer -> Integer -> Integer\npowerOf q p = toInteger $ length $ takeWhile (== 0) $ map ((flip mod) q) $ iterate ((flip div) q) p\n\ngetPath arr1 arr2 n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if min (up cell_1) (up cell_2) < min (left cell_1) (left cell_2)\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\t\t\twhere\n\t\t\t\tcell_1 = arr1 ! (i, j)\n\t\t\t\tcell_2 = arr2 ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n--\tprint matrix\n\tlet paths2 = calcPaths matrix n 2\n\tlet paths5 = calcPaths matrix n 5\n{-\n\tputStrLn \"------\"\n\tprint paths2\n\tputStrLn \"------\"\n\tprint paths5\n\tputStrLn \"------\"\n-}\n\t\n\tprint $ min (cost $ paths2 ! (n, n)) (cost $ paths5 ! (n, n))\n\tputStrLn $ getPath paths2 paths5 n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as B8\nimport Data.List\nimport Debug.Trace\nimport Control.Monad.ST\nimport Data.Array.ST\n\ndata Path = PathUp | PathLeft | NoPath\n\tderiving (Show, Eq)\n--data Cell = Cell !Int !Path -- Cost Path\n--\tderiving (Show)\n\n--cost (Cell c _) = c\n\npath (i, j) arr\n\t| (i == 1) && (j == 1) = NoPath\n\t| (i == 1) && (j > 1) = PathUp\n\t| (i > 1) && (j == 1) = PathLeft\n\t| (i > 1) && (j > 1) = if up == noVal then PathUp\n\telse if left == noVal then PathLeft else\n\t\tif up <= left then PathUp else PathLeft\n\t\t\twhere\n\t\t\t\tup = arr ! (i, j - 1)\n\t\t\t\tleft = arr ! (i - 1, j)\n\nnoVal = -1\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n B.getLine\n\tlet arr = map (B.split 0x20) lines\n\treturn $! (n, U.array ((1, 1), (n, n)) [((i, j), v) | (line, j) <- (zip arr [1..n]), (num, i) <- (zip line [1..n]), let !v = readNumber num])\n\twhere\n\t\treadNumber x = case B8.readInt x of\n\t\t\tJust (!num, _) -> num\n\t\t\tNothing -> error \"Unable to read input\"\n\ncalcPaths :: U.Array (Int, Int) Int -> Int -> Int -> Array (Int, Int) Int\ncalcPaths arr n divisor = runSTArray $ do\n\ta <- newArray ((1, 1), (n, n)) 0 :: ST s (STArray s (Int,Int) Int)\n\tforM_ [1..n] $! \\diag -> do\n\t\tlet indices = diagIndices $! diag\n\t\tforM_ indices $! \\(i, j) -> case () of\n\t\t\t_ | (i == 1) && (j == 1) -> writeArray a (i, j) current\n\t\t\t\t| (i == 1) && (j > 1) -> do\n\t\t\t\t\tup <- readArray a (i, j - 1)\n\t\t\t\t\twriteArray a (i, j) $! normalize current up\n\t\t\t\t| (i > 1) && (j == 1) -> do\n\t\t\t\t\tleft <- readArray a (i - 1, j)\n\t\t\t\t\twriteArray a (i, j) $! normalize current left\n\t\t\t\t| (i > 1) && (j > 1) -> do\n\t\t\t\t\tup <- readArray a (i, j - 1)\n\t\t\t\t\tleft <- readArray a (i - 1, j)\n\t\t\t\t\twriteArray a (i, j) $! if left <= up\n\t\t\t\t\t\tthen normalize current left\n\t\t\t\t\t\telse normalize current up\n\t\t\t\twhere \n\t\t\t\t\tcurrent = if (arr U.! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\treturn a\n\twhere \n\t\tnormalize !value !addend = (if value == noVal || addend == noVal then noVal else value + addend)\n\t\tdiagIndices diag = if diag == n then [(diag, diag)] else\n\t\t\tzip [diag..n] (repeat diag) ++ zip (repeat diag) [(diag + 1)..n]\n\npowerOf :: Int -> Int -> Int\npowerOf q p = powerOf' q p 0\n\twhere\n\t\tpowerOf' q p n = if p `mod` q /= 0 then n else powerOf' q (p `div` q) (n + 1)\n\ngetPath arr n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if path (i,j) arr == PathUp\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths2 = calcPaths matrix n 2\n\tlet cost2 = (paths2 ! (n, n))\n\tpath2 <- do\n\t\treturn $ getPath paths2 n\n\n\tlet paths5 = calcPaths matrix n 5\n\tlet cost5 = (paths5 ! (n, n))\n\tpath5 <- do\n\t\treturn $ getPath paths5 n\n\n\tif cost2 < cost5\n\t\tthen do\n\t\t\tif cost2 < 0 then print 1 else print cost2\n\t\t\tputStrLn path2\n\t\telse do\n\t\t\tif cost5 < 0 then print 1 else print cost5\n\t\t\tputStrLn path5\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\ndata Path = Down | Right\ndata Cell = Cell Int Int Int -- Cost Down Right\n\tderiving (Show)\n\ndown (Cell _ d _) = d\nright (Cell _ _ r) = r\ncost (Cell c _ _) = c\nvalue (Cell _ d r) = undefined\n\nnoVal = 1000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (i - 1)) !! (j - 1) :: Int])\n\ntrailingZeroes :: Int -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == n) && (j == n) = Cell (arr ! (i, j)) noVal noVal\n\t\t\t\t| (i == n) && (j < n) = Cell costDown costDown noVal\n\t\t\t\t| (i < n) && (j == n) = Cell costRight noVal costRight\n\t\t\t\t| (i < n) && (j < n) = Cell (minimumBy (\\x y -> trailingZeroes x `compare` trailingZeroes y ) [costDown, costRight]) costDown costRight\n\t\t\t\twhere\n\t\t\t\t\tcostDown = (arr ! (i, j) * cost (a ! (i, j + 1)))\n\t\t\t\t\tcostRight = (arr ! (i, j) * cost (a ! (i + 1, j)))\n\ngetPath arr n = getPath' arr n (1, 1)\n\twhere\n\t\tgetPath' arr n (i, j)\n\t\t\t| (i, j) == (n, n) = \"\"\n\t\t\t| otherwise = if (trailingZeroes . down) cell < (trailingZeroes . right) cell\n\t\t\t\tthen 'R' : getPath' arr n (i, j + 1)\n\t\t\t\telse 'D' : getPath' arr n (i + 1, j)\n\t\t\twhere cell = arr ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths = calcPaths matrix n\n\tprint $ trailingZeroes $ cost $ paths ! (1, 1)\n\tputStrLn $ getPath paths n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Debug.Trace\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 10000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n divisor = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell current noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell (normalize current costUp) (normalize current costUp) noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell (normalize current costLeft) noVal (normalize current costLeft)\n\t\t\t\t| (i > 1) && (j > 1) = Cell (normalize current $ minimum [costLeft, costUp]) (normalize current costUp) (normalize current costLeft)\n\t\t\t\twhere\n\t\t\t\t\tcostUp = cost (a ! (i, j - 1))\n\t\t\t\t\tcostLeft = cost (a ! (i - 1, j))\n\t\t\t\t\tcurrent = if (arr ! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\t\t\t\t\tnormalize value addend = (if value == noVal then 1 else value + addend)\n\npowerOf :: Integer -> Integer -> Integer\npowerOf q p = toInteger $ length $ takeWhile (== 0) $ map ((flip mod) q) $ iterate ((flip div) q) p\n\ngetPath arr1 arr2 n = reverse $ getPath' (n, n) (0, 0)\n\twhere\n\t\tgetPath' (i, j) (fives, twos)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if decide (up cell_1) (up cell_2) (left cell_1) (left cell_2)\n\t\t\t\tthen 'D' : getPath' (i, j - 1) (fives, twos)\n\t\t\t\telse 'R' : getPath' (i - 1, j) (fives, twos)\n\t\t\twhere\n\t\t\t\tcell_1 = arr1 ! (i, j)\n\t\t\t\tcell_2 = arr2 ! (i, j)\n\t\t\t\tdecide cu1 cu2 cl1 cl2 =\n\t\t\t\t\tif min (cl1 + twos) (cl2 + fives) < min (cu1 + twos) (cu2 + fives)\n\t\t\t\t\t\tthen False\n\t\t\t\t\t\telse True\n\nmain = do\n\t(n, matrix) <- getInput\n--\tprint matrix\n\tlet paths2 = calcPaths matrix n 2\n\tlet paths5 = calcPaths matrix n 5\n{-\tputStrLn \"------\"\n\tprint paths2\n\tputStrLn \"------\"\n\tprint paths5\n\tputStrLn \"------\" -}\n\t\n\tprint $ min (cost $ paths2 ! (n, n)) (cost $ paths5 ! (n, n))\n\tputStrLn $ getPath paths2 paths5 n\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Debug.Trace\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 10000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n divisor = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell current noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell (if current == noVal then 1 else current + costUp) costUp noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell (if current == noVal then 1 else current + costLeft) noVal costLeft\n\t\t\t\t| (i > 1) && (j > 1) = Cell (if current == noVal then 1 else current + minimum [costLeft, costUp]) costUp costLeft\n\t\t\t\twhere\n\t\t\t\t\tcostUp = cost (a ! (i, j - 1))\n\t\t\t\t\tcostLeft = cost (a ! (i - 1, j))\n\t\t\t\t\tcurrent = if (arr ! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\npowerOf :: Integer -> Integer -> Integer\npowerOf q p = toInteger $ length $ takeWhile (== 0) $ map ((flip mod) q) $ iterate ((flip div) q) p\n\ngetPath arr1 arr2 n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if max (up cell_1) (up cell_2) < max (left cell_1) (left cell_2)\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\t\t\twhere\n\t\t\t\tcell_1 = arr1 ! (i, j)\n\t\t\t\tcell_2 = arr2 ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tlet paths2 = calcPaths matrix n 2\n\tlet paths5 = calcPaths matrix n 5\n\t\n\tprint $ min (cost $ paths2 ! (n, n)) (cost $ paths5 ! (n, n))\n\tputStrLn $ getPath paths2 paths5 n\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Debug.Trace\n\ndata Path = Down | Right\ndata Cell = Cell Integer Integer Integer -- Cost Up left\n\tderiving (Show)\n\nup (Cell _ u _) = u\nleft (Cell _ _ l) = l\ncost (Cell c _ _) = c\n\nnoVal = 10000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (j - 1)) !! (i - 1) :: Integer])\n\ntrailingZeroes :: Integer -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n divisor = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == 1) && (j == 1) = Cell current noVal noVal\n\t\t\t\t| (i == 1) && (j > 1) = Cell (normalize current costUp) (normalize current costUp) noVal\n\t\t\t\t| (i > 1) && (j == 1) = Cell (normalize current costLeft) noVal (normalize current costLeft)\n\t\t\t\t| (i > 1) && (j > 1) = Cell (normalize current $ minimum [costLeft, costUp]) (normalize current costUp) (normalize current costLeft)\n\t\t\t\twhere\n\t\t\t\t\tcostUp = cost (a ! (i, j - 1))\n\t\t\t\t\tcostLeft = cost (a ! (i - 1, j))\n\t\t\t\t\tcurrent = if (arr ! (i, j) /= 0)\n\t\t\t\t\t\tthen powerOf divisor (arr ! (i, j))\n\t\t\t\t\t\telse noVal\n\t\t\t\t\tnormalize value addend = (if value == noVal then 1 else value + addend)\n\npowerOf :: Integer -> Integer -> Integer\npowerOf q p = toInteger $ length $ takeWhile (== 0) $ map ((flip mod) q) $ iterate ((flip div) q) p\n\ngetPath arr1 arr2 n = reverse $ getPath' (n, n)\n\twhere\n\t\tgetPath' (i, j)\n\t\t\t| (i, j) == (1, 1) = \"\"\n\t\t\t| otherwise = if decide (up cell_1) (up cell_2) (left cell_1) (left cell_2)\n\t\t\t\tthen 'D' : getPath' (i, j - 1)\n\t\t\t\telse 'R' : getPath' (i - 1, j)\n\t\t\twhere\n\t\t\t\tcell_1 = arr1 ! (i, j)\n\t\t\t\tcell_2 = arr2 ! (i, j)\n\t\t\t\tdecide cu1 cu2 cl1 cl2 =\n\t\t\t\t\tcase max cu1 cu2 `compare` max cl1 cl2 of\n\t\t\t\t\t\tLT -> True\n\t\t\t\t\t\tGT -> False\n\t\t\t\t\t\tEQ -> min cu1 cu2 < min cl1 cl2\n\nmain = do\n\t(n, matrix) <- getInput\n--\tprint matrix\n\tlet paths2 = calcPaths matrix n 2\n\tlet paths5 = calcPaths matrix n 5\n--\tputStrLn \"------\"\n--\tprint paths2\n--\tputStrLn \"------\"\n--\tprint paths5\n--\tputStrLn \"------\"\n\t\n\tprint $ min (cost $ paths2 ! (n, n)) (cost $ paths5 ! (n, n))\n\tputStrLn $ getPath paths2 paths5 n\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\ndata Path = Down | Right\ndata Cell = Cell Int Int Int -- Cost Down Right\n\tderiving (Show)\n\ndown (Cell _ d _) = d\nright (Cell _ _ r) = r\ncost (Cell c _ _) = c\nvalue (Cell _ d r) = undefined\n\nnoVal = 1000000\n\ngetInput = do\n\tn <- (liftM read) getLine\n\tlines <- sequence $ replicate n getLine\n\tlet arr = map words lines\n\treturn $ (n, array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = read $ (arr !! (i - 1)) !! (j - 1) :: Int])\n\ntrailingZeroes :: Int -> Int\ntrailingZeroes x = length $ takeWhile (== '0') $ (reverse . show) x\n\ncalcPaths arr n = a\n\t\twhere\n\t\t\ta = array ((1, 1), (n, n)) [((i, j), v) | i <- [1..n], j <- [1..n], let v = calcCell i j]\n\t\t\tcalcCell i j\n\t\t\t\t| (i == n) && (j == n) = Cell (arr ! (i, j)) noVal noVal\n\t\t\t\t| (i == n) && (j < n) = Cell costDown costDown noVal\n\t\t\t\t| (i < n) && (j == n) = Cell costRight noVal costRight\n\t\t\t\t| (i < n) && (j < n) = Cell (minimumBy (\\x y -> trailingZeroes x `compare` trailingZeroes y ) [costDown, costRight]) costDown costRight\n\t\t\t\twhere\n\t\t\t\t\tcostDown = (arr ! (i, j) * cost (a ! (i, j + 1)))\n\t\t\t\t\tcostRight = (arr ! (i, j) * cost (a ! (i + 1, j)))\n\ngetPath arr n = getPath' arr n (1, 1)\n\twhere\n\t\tgetPath' arr n (i, j)\n\t\t\t| (i, j) == (n, n) = \"\"\n\t\t\t| otherwise = if (trailingZeroes . down) cell < (trailingZeroes . right) cell\n\t\t\t\tthen 'R' : getPath' arr n (i, j + 1)\n\t\t\t\telse 'D' : getPath' arr n (i + 1, j)\n\t\t\twhere cell = arr ! (i, j)\n\nmain = do\n\t(n, matrix) <- getInput\n\tprint matrix\n\tlet paths = calcPaths matrix n\n\tprint $ paths ! (1, 1)\n\tprint $ getPath paths n\n"}, {"source_code": "import Data.List (foldl')\nimport Control.DeepSeq\nmain = do\n n <- readLn\n ns <- fmap (chunksOf n . map read . words) getContents\n let start = ((0 :: Int,\"\"),(0,\"\"))\n iv = start : replicate (n-1) junk\n (m,p) = uncurry min $last $ foldl' dp iv ns\n print m\n putStrLn (tail $ reverse p)\njunk = ((maxBound,\"E\"),(maxBound,\"E\"))\ndp prev cur = force $ go junk prev cur where\n go _ _ [] = []\n go ((l2,l2p),(l5,l5p)) (((u2,u2p),(u5,u5p)):u) (x:xs) =\n b2 `seq` b5 `seq` (b : go b u xs) where\n b = (b2,b5)\n n2 = factors 2 x\n n5 = factors 5 x\n b2 = min ((l2+n2),('R' : l2p)) ((u2+n2),('D' : u2p))\n b5 = min ((l5+n5),('R' : l5p)) ((u5+n5),('D' : u5p))\nfactors n x = go x 0 where\n go x a | r == 0 = go q $! a + 1\n | otherwise = a\n where (q,r) = x `divMod` n\nchunksOf _ [] = []\nchunksOf n xs = l : chunksOf n r where (l,r) = splitAt n xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List (foldl')\nimport Data.Array.IArray\nimport Data.Array.ST.Safe (STArray,STUArray,newArray,readArray,writeArray)\nimport Data.STRef (newSTRef,readSTRef,writeSTRef)\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST,runST)\nmain = do\n (n:ns) <- fmap (map read' . B.words) B.getContents\n let prep = do\n m2 <- newArray (0,n) (maxBound `div` 2) :: ST s (STUArray s Int Int)\n p2 <- newArray (0,n) \"E\" :: ST s (STArray s Int String)\n writeArray m2 1 0\n writeArray p2 1 \"\"\n return (m2,p2)\n let dp ns = runST $ do\n zero <- newSTRef Nothing\n (m2,p2) <- prep\n (m5,p5) <- prep\n let dp' ns = go ns 1 where\n go [] _ = return ()\n go (x:xs) i = do\n when (x == 0) $ writeSTRef zero (Just i)\n l2 <- readArray m2 (i-1)\n l2p <- readArray p2 (i-1)\n l5 <- readArray m5 (i-1)\n l5p <- readArray p5 (i-1)\n u2 <- readArray m2 i\n u2p <- readArray p2 i\n u5 <- readArray m5 i\n u5p <- readArray p5 i\n let n2 = factors 2 x\n n5 = factors 5 x\n (e2,e2p) = min ((l2+n2),('R':l2p)) ((u2+n2),('D':u2p))\n (e5,e5p) = min ((l5+n5),('R':l5p)) ((u5+n5),('D':u5p))\n writeArray m2 i e2\n writeArray p2 i e2p\n writeArray m5 i e5\n writeArray p5 i e5p\n go xs $! i+1\n mapM_ dp' ns\n b2 <- readArray m2 n\n b2p <- readArray p2 n\n b5 <- readArray m5 n\n b5p <- readArray p5 n\n z <- readSTRef zero\n let (m,p) = min (b2,b2p) (b5,b5p)\n return $ case z of\n Nothing -> (m,p)\n Just j -> min (m,p) (1,replicate (j-1) 'R' ++\n replicate (n-1) 'D' ++\n replicate (n-j) 'R')\n (m,p) = dp (chunksOf n ns)\n print m\n putStrLn (tail $ reverse p)\n{-# INLINE factors #-}\nfactors _ 0 = 1\nfactors n x = go x 0 where\n go x a | r == 0 = go q $! a + 1\n | otherwise = a\n where (q,r) = x `divMod` n\n{-# INLINE chunksOf #-}\nchunksOf n = go where\n go [] = []\n go xs = l : go r where (l,r) = splitAt n xs\n{-# INLINE read' #-}\nread' s = r where Just (r,_) = B.readInt s\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n n <- readLn\n r <- liftM (solve . parse) (replicateM n getLine)\n print r\n\nparse = map (map read . words)\nbig = 60000\n\nsolve ls = (z,tail (reverse t))\n where i = ((0,\"\"),(0,\"\")) : repeat ((big,undefined),(big,undefined))\n d ((a,p2),(b,p5)) (c,d) = ((a+c,'D':p2),(b+d,'D':p5))\n r ((a,p2),(b,p5)) ((c,d),((e,p2'),(f,p5'))) = (s,s)\n where s = ((g,p2''),(h,p5''))\n (g,p2'') = if a+c <= e then (a+c,'R':p2) else (e,p2')\n (h,p5'') = if b+d <= f then (b+d,'R':p5) else (f,p5'')\n p (h:t) = (snd h) : snd (mapAccumL r (snd h) t)\n l a b = p $ zip b $ zipWith d a b\n (z,t) = uncurry min $ last $ foldl' l i $ map (map factor) ls\n\nfactor n = (m2,m5)\n where (m2,r) = f 2 n\n (m5,_) = f 5 r\n f b n = go n 0\n where go n a | r == 0 = go q $! a+1\n | otherwise = (a,n)\n where (q,r) = n `divMod` b\n"}, {"source_code": "{-# LANGUAGE DerivingVia #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nimport Data.Array (listArray, elems)\n\nimport Control.Monad (forM_, replicateM)\nimport Data.Functor ((<&>))\nimport Data.Semigroup (Sum(..))\nimport Data.Ord (comparing)\nimport Data.Word\nimport GHC.List (scanl')\n\ntype V = Int\n\nbadInput :: [[V]]\nbadInput = replicate 1000 $ replicate 1000 1\n\nmain :: IO ()\nmain = do\n Answer w p <- solve <$> pure badInput\n print (unWeight w)\n putStrLn (reverse p)\n\nreadInput :: IO [[V]]\nreadInput = do\n n <- readLn\n replicateM n $ getLine <&> map read . words\n\nsolve :: [[V]] -> Answer\nsolve rows = min a2 a5\n where\n a2 = findAnswer (Factor 2) rows\n a5 = findAnswer (Factor 5) rows\n\nfindAnswer :: Factor -> [[V]] -> Answer\nfindAnswer p (row:rows) = last $ foldl' (nextRow p) (firstRow p row) rows\n\nfirstRow :: Factor -> [V] -> [Answer]\nfirstRow p (first:rest) = scanl step initial rest\n where\n initial = Answer (toWeight p first) \"\"\n step a v = moveRight a (toWeight p v)\n\nnextRow :: Factor -> [Answer] -> [V] -> [Answer]\nnextRow p (firstUp:restUp) (first:rest) = scanl' step initial (zip restUp rest)\n where\n initial = moveDown firstUp $ toWeight p first\n step !left (up, v) = let w = toWeight p v\n in min (moveRight left w) (moveDown up w)\n\nmoveRight :: Answer -> Weight -> Answer\nmoveRight (Answer w1 p) w2 = Answer (w1 <> w2) ('R':p)\n\nmoveDown :: Answer -> Weight -> Answer\nmoveDown (Answer w1 p) w2 = Answer (w1 <> w2) ('D':p)\n\ntoWeight :: Factor -> V -> Weight\ntoWeight _ 0 = Zeroed\ntoWeight p k = Amount (count p k)\n\nunWeight :: Weight -> V\nunWeight Zeroed = 1\nunWeight (Amount a) = unCounted a\n\ncount :: Factor -> V -> Counted\ncount (Factor d) value = countD0 value 0\n where\n countD0 value acc = let (q, r) = quotRem value d\n in if r == 0 then countD0 q (acc + 1) else Counted acc\n\nnewtype Size = Size { unSize :: V } deriving (Show)\nnewtype Factor = Factor V\nnewtype Counted = Counted { unCounted :: V }\n deriving (Show, Eq, Ord)\n deriving Semigroup via (Sum V)\n\ndata Weight = Zeroed | Amount !Counted\n deriving (Show, Eq)\n\ninstance Ord Weight where\n compare a b = compare (unWeight a) (unWeight b)\n\ninstance Semigroup Weight where\n Zeroed <> _ = Zeroed\n _ <> Zeroed = Zeroed\n (Amount a) <> (Amount b) = Amount (a <> b)\n\ndata Answer = Answer { weight :: !Weight\n , path :: String\n } deriving (Show)\n\ninstance Eq Answer where\n a == b = weight a == weight b\n\ninstance Ord Answer where\n compare = comparing weight"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IA\nimport qualified Data.Array as A\nimport Data.Array ((!))\nimport Data.Int\nimport Control.Monad\n\ntype V = Int64\ntype I = Int\ntype Matrix = A.Array I (A.Array I V)\ntype Arr = IA.IOArray I\ntype D = Arr (Arr Solution)\n\nreadMatrix :: Int -> [String] -> Matrix\nreadMatrix n = A.listArray (1, n) . map (A.listArray (1, n) . fmap read . words)\n\ndata Solution = Solution {\n result :: V,\n path :: String\n} deriving (Show)\n\ncountZeros :: V -> Int\ncountZeros value = countZeros0 value 0\n where\n countZeros0 !value !acc = let (q, r) = quotRem value 10\n in if r == 0 then countZeros0 q (acc + 1) else acc\n\ninitD :: Matrix -> IO D\ninitD m = do\n result <- MA.newArray_ bounds :: IO D\n forM_ [from .. to] $ \\i -> MA.newArray_ bounds >>= MA.writeArray result i\n return result\n where\n bounds@(from, to) = A.bounds m\n\nwriteV :: D -> I -> I -> Solution -> IO ()\nwriteV m i j e = MA.readArray m i >>= \\a -> MA.writeArray a j e\n\nreadV :: D -> I -> I -> IO Solution\nreadV m i j = MA.readArray m i >>= \\a -> MA.readArray a j\n\ndebug :: D -> I -> I -> IO ()\ndebug m i j = do\n s <- readV m i j\n putStrLn $ show i <> \" \" <> show j <> \" \" <> show s\n\nsolve :: Matrix -> IO Solution\nsolve m = do\n arr <- initD m\n writeV arr 1 1 $ Solution (m ! 1 ! 1) \"\"\n forM_ [2 .. n] $ \\i -> do\n Solution cr cp <- readV arr 1 (i - 1)\n Solution rr rp <- readV arr (i - 1) 1\n writeV arr 1 i $ Solution (cr * m ! 1 ! i) ('R':cp)\n writeV arr i 1 $ Solution (rr * m ! i ! 1) ('D':rp)\n -- debug arr 1 i\n -- debug arr i 1\n forM_ [(i, j) | i <- [2..n], j <- [2..n]] $ \\(i, j) -> do\n Solution cr cp <- readV arr (i - 1) j\n Solution rr rp <- readV arr i (j - 1)\n let curV = m ! i ! j\n downR = cr * curV\n rightR = rr * curV\n res = if countZeros downR < countZeros rightR then Solution downR ('D':cp) else Solution rightR ('R':rp)\n in writeV arr i j res\n -- debug arr i j\n readV arr n n\n where\n n = length m\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine :: IO Int\n m <- readMatrix n `fmap` replicateM n getLine\n res <- solve m\n print . countZeros $ result res\n putStrLn . reverse $ path res"}, {"source_code": "module Main where\n\nimport Control.Applicative ((<$>))\nimport Data.List (foldl')\n\npowerOf :: Int -> Int -> Int\npowerOf p n = case n `mod` p of\n 0 -> 1 + powerOf p (n `div` p)\n _ -> 0\n\ndata DP = DP { minNum :: !Int\n , go :: !String }\n deriving (Show)\n\ndp :: [[Int]] -> DP\ndp (row:rows) = last $ foldl' dpRow (dpFirstRow row) rows\n\ndpRow :: [DP] -> [Int] -> [DP]\ndpRow (up:ups) (cur:curs) = scanl step dpInit $ zip ups curs where\n step (DP leftNum leftGo) (DP upNum upGo, n)\n | upNum < leftNum = DP (n + upNum) ('D':upGo)\n | otherwise = DP (n + leftNum) ('R':leftGo)\n dpInit = DP (cur + minNum up) ('D':go up)\n\ndpFirstRow :: [Int] -> [DP]\ndpFirstRow currs = zipWith DP sums rs where\n sums = scanl1 (+) currs\n rs = iterate ('R':) []\n\ninputGrids :: IO [[(Int, Int)]]\ninputGrids = do\n n <- readLn :: IO Int\n let getPowers a = (powerOf 2 a, powerOf 5 a)\n input <- getContents\n return $ map (map getPowers . map read . words) (lines input)\n\nmain :: IO ()\nmain = do\n (grids2, grids5) <- unzip . map unzip <$> inputGrids\n let DP min2 go2 = dp grids2\n DP min5 go5 = dp grids5\n if min2 <= min5\n then print min2 >> putStrLn go2\n else print min5 >> putStrLn go5\n"}, {"source_code": "module Main where\n\nimport qualified Data.Array.IArray as I\nimport qualified Data.Array as A\nimport Data.Array.Unboxed\nimport Data.Maybe (maybe)\nimport Data.List (foldl')\nimport qualified Data.ByteString.Char8 as C\n\nimport Debug.Trace\n\npowerOf :: Int -> Int -> Int\npowerOf p n = case n `mod` p of\n 0 -> 1 + powerOf p (n `div` p)\n _ -> 0\n\ndata DP = DP { minNum :: !Int\n , go :: !String }\n deriving (Show)\n\ndp :: Int -> Int -> [UArray Int Int] -> DP\ndp n p (row:rows) = (foldl' (dpRow n p) (dpFirstRow n p (I.elems row)) rows)!(n-1)\n\ndpRow :: Int -> Int -> A.Array Int DP -> UArray Int Int -> A.Array Int DP\ndpRow n p ups curs = I.listArray (0,n-1) $ scanl step dpInit [1..n-1] where\n step (DP leftNum leftGo) n\n | upNum < leftNum = DP (powerOf p (curs!n) + upNum) ('D':upGo)\n | otherwise = DP (powerOf p (curs!n) + leftNum) ('R':leftGo)\n where DP upNum upGo = ups!n\n dpInit = DP (powerOf p (curs!0) + minNum up) ('D':go up)\n up = ups!0\n\ndpFirstRow :: Int -> Int -> [Int] -> A.Array Int DP\ndpFirstRow n p currs = I.listArray (0, n-1) $ zipWith DP sums rs where\n sums = scanl1 ((+) . powerOf p) currs\n rs = iterate ('R':) []\n\ninputGrids :: IO (Int, [UArray Int Int])\ninputGrids = do\n n <- readLn\n grids <- sequence $ replicate n $ do\n line <- C.getLine\n let ns = map (maybe (error \"Read\") fst) . map C.readInt . C.words $ line\n return $! I.listArray (0, n-1) ns\n return (n, grids)\n\nmain :: IO ()\nmain = do\n (n, grids) <- inputGrids\n let DP min2 go2 = dp n 2 grids\n DP min5 go5 = dp n 5 grids\n if min2 <= min5\n then print min2 >> putStrLn (reverse go2)\n else print min5 >> putStrLn (reverse go5)\n"}, {"source_code": "import Data.List\nimport Data.Maybe (maybeToList)\nimport Data.Functor ((<$>))\nimport Data.Function (on)\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as B\n\ngetPows :: Int -> Int -> Int\ngetPows b x = case x `divMod` b of\n (x', 0) -> 1 + getPows b x'\n _ -> 0\n\nsolve :: Int -> U.Array (Int, Int) Int -> (Int, String)\nsolve n mat = dp A.! (0, 0)\n where dp = A.array ((0, 0), (n-1, n-1)) [((i, j), f i j) | i <- [0..n-1], j <- [0..n-1]]\n f i j\n | i == n-1 && j == n-1 = (0, \"\")\n | i == n-1 = dpath\n | j == n-1 = rpath\n | otherwise = minimumBy (compare `on` fst) [dpath, rpath]\n where gridWeight = mat U.! (i, j)\n\n (dweight', dpath') = dp A.! (i, j+1)\n dpath = (gridWeight + dweight', 'D' : dpath')\n\n (rweight', rpath') = dp A.! (i+1, j)\n rpath = (gridWeight + rweight', 'R' : rpath')\n\nmain :: IO ()\nmain = do\n n : mat' <- map (maybe 0 fst . B.readInt) . B.words <$> B.getContents\n\n let mat = U.listArray ((0, 0), (n-1, n-1)) (map (\\x -> if x == 0 then 10 else x) mat')\n\n mat2 = U.amap (getPows 2) mat\n mat5 = U.amap (getPows 5) mat\n\n zeroPath idx = (1, replicate x 'R' ++ replicate n 'D' ++ replicate (n-x) 'R')\n where x = idx `div` n\n cands = [solve n mat2, solve n mat5] ++ maybeToList (zeroPath <$> elemIndex 0 mat')\n\n (ansWeight, ansPath) = minimumBy (compare `on` fst) cands\n\n print ansWeight\n putStrLn ansPath\n"}, {"source_code": "import Data.List\nimport Data.Maybe (maybeToList)\nimport Data.Functor ((<$>))\nimport Data.Function (on)\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as B\n\ngetPows :: Int -> Int -> Int\ngetPows b =\n let getPows' b' callback acc x = case x `divMod` b' of\n (x', 0) -> getPows' b' callback (acc + 1) x'\n _ -> callback acc x\n in getPows' (b ^ 5) (getPows' b const . (* 5)) 0\n\nsolve :: Int -> U.UArray (Int, Int) Int -> Int -> (Int, String)\nsolve n mat b = foldl' seq n [f i j | i <- steps, j <- steps]\n `seq` (dp U.! (0, 0), findPath 0 0)\n\n where step = min (n `div` 2) 30\n steps = reverse [0, step .. n-1]\n\n getPow = getPows n\n\n dp :: U.Array (Int, Int) Int\n dp = U.listArray ((0, 0), (n-1, n-1)) [f i j | i <- [0..n-1], j <- [0..n-1]]\n\n findPath i j\n | i == n-1 = replicate (n-j-1) 'R'\n | j == n-1 = replicate (n-i-1) 'D'\n | otherwise =\n if dp U.! (i, j+1) > dp U.! (i+1, j)\n then 'D' : findPath (i+1) j\n else 'R' : findPath i (j+1)\n\n f i j\n | i == n-1 && j == n-1 = gridWeight\n | i == n-1 = rpath\n | j == n-1 = dpath\n | otherwise = min dpath rpath\n where gridWeight = getPow $ mat U.! (i, j)\n dpath = dp U.! (i+1, j) + gridWeight\n rpath = dp U.! (i, j+1) + gridWeight\n\nreadInt :: B.ByteString -> Int\nreadInt' word = case B.readInt word of\n Just (num, _) -> num\n Nothing -> 0\nreadInt = maybe 0 fst . B.readInt\n\nreadInput :: IO (Int, U.UArray (Int, Int) Int, [(Int, String)])\nreadInput = do\n n : mat' <- map readInt . B.words <$> B.getContents\n let zeroPath idx = (1, replicate x 'R' ++ replicate (n-1) 'D' ++ replicate (n-1-x) 'R')\n where x = idx `mod` n\n maybeZeroPath = maybeToList $ zeroPath <$> elemIndex 0 mat'\n\n mat = U.listArray ((0, 0), (n-1, n-1)) (map (\\x -> if x == 0 then 10 else x) mat')\n return (n, mat, maybeZeroPath)\n\nmain :: IO ()\nmain = do\n (n, mat, maybeZeroPath) <- readInput\n\n let ans2 = solve n mat 2\n ans5 = solve n mat 5\n cands = maybeZeroPath ++ [ans2, ans5]\n (ansWeight, ansPath) = minimumBy (compare `on` fst) cands\n\n print ansWeight\n putStrLn ansPath\n"}, {"source_code": "import Data.List\nimport Data.Maybe (maybeToList)\nimport Data.Functor ((<$>))\nimport Data.Function (on)\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as B\n\ngetPows :: Int -> Int -> Int\ngetPows b x = case x `divMod` b of\n (x', 0) -> 1 + getPows b x'\n _ -> 0\n\nsolve :: Int -> U.Array (Int, Int) Int -> (Int, String)\nsolve n mat = dp A.! (0, 0)\n where dp = A.array ((0, 0), (n-1, n-1)) [((i, j), f i j) | i <- [0..n-1], j <- [0..n-1]]\n f i j\n | i == n-1 && j == n-1 = (0, \"\")\n | i == n-1 = rpath\n | j == n-1 = dpath\n | otherwise = minimumBy (compare `on` fst) [dpath, rpath]\n where gridWeight = mat U.! (i, j)\n\n (dweight', dpath') = dp A.! (i+1, j)\n dpath = (gridWeight + dweight', 'D' : dpath')\n\n (rweight', rpath') = dp A.! (i, j+1)\n rpath = (gridWeight + rweight', 'R' : rpath')\n\nmain :: IO ()\nmain = do\n n : mat' <- map (maybe 0 fst . B.readInt) . B.words <$> B.getContents\n\n let mat = U.listArray ((0, 0), (n-1, n-1)) (map (\\x -> if x == 0 then 10 else x) mat')\n\n mat2 = U.amap (getPows 2) mat\n mat5 = U.amap (getPows 5) mat\n\n zeroPath idx = (1, replicate x 'R' ++ replicate n 'D' ++ replicate (n-x) 'R')\n where x = idx `mod` n\n cands = [solve n mat2, solve n mat5] ++ maybeToList (zeroPath <$> elemIndex 0 mat')\n\n (ansWeight, ansPath) = minimumBy (compare `on` fst) cands\n\n print ansWeight\n putStrLn ansPath"}], "src_uid": "13c58291ab9cf7ad1b8c466c3e36aacf"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.Array((!),listArray,Array,assocs)\nimport qualified Data.IntMap as M\nimport Control.Monad.State\nimport Data.Maybe\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n n0 <- getLine\n let n :: Int = read n0\n nums0 <- getLine\n let nums :: [Int] = map read . words $ nums0\n -- result <- solveArr n nums\n putStrLn . show $ solve n nums\n\n-- solve :: Int -> [Int] -> Int\n-- solve n nums = dp ! n where\n-- dp :: Array Int Int\n-- dp = listArray (1,n) (map f [n,n-1..1])\n-- f :: Int -> Int\n-- f x\n-- | x == n = 0\n-- | otherwise = maximum $ map (\\j -> sum (take j nums) - f j) [x..n]\n-- get :: Int -> Int\n-- get x = dp ! x\n\n-- solveR :: Int -> Int -> [Int] -> Int\n-- solveR x n nums\n-- | x == n = 0\n-- | otherwise = maximum $ map (\\j -> sum (take j nums) - solveR j n nums) [x+1..n]\n\n-- solveM :: Int -> [Int] -> Int\n-- solveM n nums = evalState (f n) $ M.fromList [(n,0)] where\n-- f :: Int -> State (M.IntMap Int) Int\n-- f x = do\n-- dp :: M.IntMap Int <- get\n-- put $ foldl (\\acc (Just (i,j)) -> M.insert i j acc) dp $ filter isJust $ map (attempt dp) [x+1..n]\n-- -- dp <- get\n-- return $ maximum $ map (\\j -> sum (take j nums) - fromJust (dp M.!? j)) [x+1..n]\n-- where\n-- attempt :: M.IntMap Int -> Int -> Maybe (Int, Int)\n-- attempt dp x = case M.lookup x dp of\n-- Just i -> Nothing\n-- Nothing -> Just (x, evalState (f x) dp)\n\n\n-- solveM :: Int -> [Int] -> IO (Int)\n-- solveM n nums = do\n-- dpRef <- newIORef $ M.fromList [(n,0)]\n-- f dpRef 1\n-- where\n-- f :: IORef (M.IntMap Int) -> Int -> IO (Int)\n-- f dpRef x = foldl (\\acc j -> do {a <- acc; b <- j; return $ if a > b then a else b}) a asd where\n-- asd :: [IO Int]\n-- (a:asd) = map (\\j -> do {i <- attempt dpRef j; return $ sum (take j nums) - i } ) [x+1..n]\n-- attempt :: IORef (M.IntMap Int) -> Int -> IO (Int)\n-- attempt dpRef x = do\n-- dp <- readIORef dpRef\n-- case M.lookup x dp of\n-- Just i -> return i\n-- Nothing -> do\n-- i <- f dpRef x\n-- modifyIORef dpRef (\\m -> M.insert x i m)\n-- return i\n\n-- solveArr :: Int -> [Int] -> IO (Int)\n-- solveArr n nums = do\n-- dpRef :: IORef (Array Int (Maybe Int)) <- newIORef $ listArray (1,n) $ (replicate (n-1) Nothing) ++ [Just 0]\n-- f dpRef 1\n-- where\n-- sums :: Array Int Int\n-- sums = listArray (1,n) $ scanl (+) (head nums) (tail nums)\n-- f :: IORef (Array Int (Maybe Int)) -> Int -> IO (Int)\n-- f dpRef x = foldl (\\acc j -> do {a <- acc; b <- j; return $ if a > b then a else b}) a asd where\n-- asd :: [IO Int]\n-- -- (a:asd) = map (\\j -> do {i <- attempt dpRef j; return $ sum (take j nums) - i } ) [x+1..n]\n-- (a:asd) = map (\\j -> do {i <- attempt dpRef j; return $ sums!j - i } ) [x+1..n]\n-- attempt :: IORef (Array Int (Maybe Int)) -> Int -> IO (Int)\n-- attempt dpRef x = do\n-- dp <- readIORef dpRef\n-- case dp!x of\n-- Just i -> return i\n-- Nothing -> do\n-- i <- f dpRef x\n-- modifyIORef dpRef (\\arr -> listArray (1,n) $ map (\\(a,b) -> if a == x then Just i else b) $ assocs arr)\n-- return i\n\nsolve :: Int -> [Int] -> Int\nsolve n nums = foldl (\\max x -> if max > x - max then max else x - max) s $ take (n-2) sums where\n (s:sums) = reverse . scanl (+) 0 $ nums\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n line <- getLine >> getLine\n let nums :: [Int] = map read . words $ line\n putStrLn . show $ solve nums\n\nsolve :: [Int] -> Int\nsolve (n:nums) = foldl (\\acc x -> max acc (x - acc)) s sums where\n (s:sums) = reverse . tail . scanl (+) n $ nums\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n n0 <- getLine\n let n :: Int = read n0\n nums0 <- getLine\n let nums :: [Int] = map read . words $ nums0\n putStrLn . show $ solve n nums\n\nsolve :: Int -> [Int] -> Int\nsolve n nums = foldl (\\acc x -> max acc (x - acc)) s sums where\n (s:sums) = reverse . tail .scanl (+) 0 $ nums\n"}], "src_uid": "b5b13cb304844a8bbd07e247150719f3"} {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Ord\ngetList = fmap ((map read).words) getLine\n\nf _ [] = 0\nf k p = fst (minimumBy (comparing snd) (zipWith (\\x y -> (fst y, snd x - snd y)) (drop k list) list)) + 1\n where list = scanl (\\x y -> (fst y, snd x + snd y)) (0,0) p\n \nmain = do\n [_,k] <- getList\n p <- zip [1..] <$> getList\n putStrLn $ show $ f k p\n", "positive_code": [{"source_code": "\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = print =<< solve <$> ((!!1) . map read . words <$> getLine) <*> (map read . words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = snd . minimum $ flip zip [1..] sumsOfEachKElements\n where\n sumsOfEachKElements = uncurry (zipWith (-)) pairWithAndWithoutK\n pairWithAndWithoutK = (drop k &&& id) progressivSums\n progressivSums = scanl (+) 0 xs\n\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Maybe (fromJust)\n\n{-solve k xs = go 0 start zs\n where go _ _ [(_,_)] = 1\n go ind val ys@((j, y):yss)\n | k == l = 1\n | j >= (l - k + 2) = ind \n | newval < val = go j newval yss\n | otherwise = go ind val yss\n where newval = sum . map snd . take k $ ys\n l = length xs\n zs = zip [1..] xs\n start = sum xs\n-}\nsolve k xs = fmap (+1) (elemIndex m ds') \n where ys = listArray (0, l-1) xs\n l = length xs\n ds = listArray (1, l-k+1) [go i | i <- [1..(l-k+1)]] \n go 1 = sum . take k $ xs\n go n = ds ! (n-1) - ys ! (n-2) + ys ! (n-2+k)\n m = minimum ds' \n ds' = [ds ! n | n <- [1..(l-k+1)]] \n \nmain = do\n k <- fmap (last . map read . words) getLine :: IO Int\n ls <- fmap (map read . words) getLine :: IO [Int]\n print $ fromJust $ solve k ls \n"}, {"source_code": "import Numeric\nimport Data.Array\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.snd.f. map fastRead .words\n\nf (n:k:ns) = dp (listArray (1, n) ns) (zip [1..] [(k+1)..n]) ((sum (take k ns)), 1)\n\ndp ns [] prev = prev\ndp ns (a:as) prev = min prev (dp ns as (w, (i+1)))\n where w = (fst prev) + (ns ! j) - (ns ! i)\n i = fst a\n j = snd a\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k l = snd $ minimumBy cmpFst $ zip sums [1..]\n where\n sums = go (sum $ take k l) l (drop k l)\n go s _ [] = [s]\n go s (a:as) (b:bs) = s:go (s-a+b) as bs\n\nmain = do\n (n,k) <- readIntPair\n l <- readInts\n print $ solve n k l\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. concat. map (map read.words).take 2.lines\nsolve :: [Int]-> String\nsolve (x1:x2:xs) = show $ (\\ (a,b,c) -> b) $ foldl f (sum $ take x2 xs,1,sum $ take x2 xs) $ zip (zip xs (drop (x2) xs)) [2..]\n where\n f (b1,b2,m) ((a1,a2),a3) = if b1+a2-a1 j) $ foldl' (\\(s, m, j) (x,y,i) ->\n let s' = s - x + y in -- trace (concatMap (( \" \"++).show) [s,s',x,y,m,j]) $\n if m > s'\n then (s', s', i)\n else (s', m, j)\n ) (f, f, 1)\n $ zip3 hs (drop k hs) [2..]\n where \n f = sum $ take k hs\n \n\n\nmain = do\n [n,k] <- map ( (read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n hs <- map ( (read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n print $ solve hs k "}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate, minimumBy)\n\nsolve :: Int -> [Int] -> Int\nsolve k as = fst $ minimumBy snd $ zip [1..] a\n where\n d = scanl (+) 0 as\n a = zipWith (-) (drop k d) d\n snd (_, a) (_, b) = compare a b\n\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- reads\n print $ solve k as\n\n where\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List (minimumBy)\nmain :: IO ()\nmain = do\n [_,k] <- map read . words <$> getLine :: IO [Int]\n hs <- map read . words <$> getLine :: IO [Int]\n let preSums = scanl1 (+) $ hs\n diffs = zip [1..] $ map (uncurry (-)) $ zip (drop (k-1) preSums) $ 0:preSums\n ans = fst $ minimumBy (\\a b -> compare (snd a) (snd b)) diffs\n -- print preSums\n -- print $ zip (drop k preSums) preSums\n -- print diffs\n print ans\n return ()\n"}, {"source_code": "import Data.Array\nimport Debug.Trace\n\nsolve :: [[Int]] -> Int\nsolve [[n, k], h] =\n 1 - k + (snd $ minimum $ drop (k - 1) $ zip (elems heightSums) [1..])\n where\n track q = trace (show q) q\n h' = listArray (1, n) h\n heightSums = listArray (1, n) [d i | i <- [1..n]]\n d 1 = head h\n d i | i <= k = h' ! i + heightSums ! (i - 1)\n d i | otherwise = h' ! i + heightSums ! (i - 1) - h' ! (i - k)\n\nmain = interact $ show . solve . map (map read . words) . lines\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = print =<< solve <$> ((!!1) . map read . words <$> getLine) <*> (map read . words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve k = snd . minimum . flip zip [1..] . uncurry (zipWith (-)) . (drop k &&& id) . scanl (+) 0"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nprocess k s = zipWith (\\a b -> b-a ) (0:s1) (drop (k-1) s1)\n where s1 = scanl1 (+) s\n\n\n--process 1 s _ = s\n--process k s t = process (k-1) (zipWith (+) s (tail t)) (tail t)\n\nmain=do\n [n,k]<-map read <$> words <$> getLine::IO [Int]\n s1<- C.words <$> C.getLine\n let s = map ( fst.fromJust.C.readInteger ) s1\n let ss = process k s\n print $ (+1) $ fromJust $ elemIndex (minimum ss) ss\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = print =<< solve <$> ((!!1) . map read . words <$> getLine) <*> (map read . words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve k = snd . minimum . flip zip [1..] . uncurry (zipWith (-)) . (drop k &&& id) . scanl (+) 0\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = print =<< solve <$> ((!!1) . map read . words <$> getLine) <*> (map read . words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve k = fst . minimumBy (comparing snd) . zip [1..] . uncurry (zipWith (-)) . (drop k &&& id) . scanl (+) 0\n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (w:hs) = minIndex . (zipWith (-) =<< drop w) . scanl (+) 0 $ hs\nminIndex = go undefined maxBound 1 where\n go mi mv i (v:vs) | v < mv = go i v (i+1) vs\n | otherwise = go mi mv (i+1) vs\n go mi _ _ _ = mi :: Int\n"}], "negative_code": [{"source_code": "import Control.Applicative\ngetList = fmap ((map read).words) getLine\nsolve k p = minimum (zipWith (-) (drop k list) list)\n where list = scanl1 (+) p\nmain = do\n [n,k] <- getList\n p <- getList\n putStrLn $ show $ solve k p\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Ord\ngetList = fmap ((map read).words) getLine\nsolve k p = snd (minimumBy (comparing fst) (zip (zipWith (-) (drop k list) list) [2..]))\n where list = scanl1 (+) p\nmain = do\n [n,k] <- getList\n p <- getList\n case n of\n 1 -> putStr $ show $ head p\n otherwise -> putStrLn $ show $ solve k p\n"}, {"source_code": "import Numeric\nimport Data.Array\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.snd.f. map fastRead .words\n\nf (n:1:ns) = minimum (zip ns [1..])\nf (n:k:ns) = dp (listArray (1, n) ns) (k+1) 1 n ((sum (take k ns)), 1)\n\ndp :: Array Int Int -> Int -> Int -> Int -> (Int, Int) -> (Int, Int)\ndp ns k n end ans\n | k <= end = dp ns (k+1) (n+1) end (min ans (i, (n+1)))\n | otherwise= ans\n where i = (fst ans) + (ns ! k) - (ns ! n)\n"}, {"source_code": "import Numeric\nimport Data.Array\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.snd.f. map fastRead .words\n\nf (n:k:ns) = dp (listArray (1, n) ns) (k+1) 1 n ((sum (take k ns)), 1)\n\ndp ns k n end ans\n | k <= end = dp ns (k+1) (n+1) end (min ans (((fst ans) + (ns ! k) - (ns ! n)), (n+1)))\n | otherwise= ans\n\n\n"}, {"source_code": "import Numeric\nimport Data.Array\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.snd.f. map fastRead .words\n\nf (n:k:ns) = dp (listArray (1, n) ns) k 1 n ((sum (take k ns)), 1)\n\ndp :: Array Int Int -> Int -> Int -> Int -> (Int, Int) -> (Int, Int)\ndp ns k n end prev\n | k <= end = min prev (dp ns (k+1) (n+1) end (i, n))\n | otherwise= prev\n where i = (fst prev) + (ns ! k) - (ns ! n)\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. concat. map (map read.words).take 2.lines\nsolve :: [Int]-> String\nsolve (x1:x2:xs) = show $ snd $ foldl f (sum $ take x2 xs,1) $ zip (zip xs (drop (x2) xs)) [2..]\n where\n f (b1,b2) ((a1,a2),a3) = if a2-a1 < 0 then (b1+a2-a1, a3) else (b1,b2)"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as C\n\nsolve (a:b:c:hs) k min i j = \n let s = a+b+c in\n if (min > s)\n then solve (b:c:hs) k s (i+1) i\n else solve (b:c:hs) k min (i+1) j\nsolve _ _ _ _ j = j\n\nmain = do\n [n,k] <- map ( (read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n hs <- map ( (read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n print $ solve hs k (maxBound :: Int) 1 1"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nprocess k s = zipWith (\\a b -> b-a ) (0:s1) (drop (k-1) s1)\n where s1 = scanl1 (+) s\n\n\n--process 1 s _ = s\n--process k s t = process (k-1) (zipWith (+) s (tail t)) (tail t)\n\nmain=do\n [n,k]<-map read <$> words <$> getLine::IO [Int]\n s1<- C.words <$> C.getLine\n let s = map ( fst.fromJust.C.readInteger ) s1\n let ss = process k s\n print ss\n print $ (+1) $ fromJust $ elemIndex (minimum ss) ss\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\n\n\nprocess 0 s _ = s\nprocess k s t = process (k-1) (zipWith (+) s (tail t)) (tail t)\n\nmain=do\n [n,k]<-map read <$> words <$> getLine::IO [Int]\n s<- map read <$> words <$> getLine::IO [Int]\n let ss = process k s s\n print $ fromJust $ elemIndex (minimum ss) ss\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\nimport Data.List (minimumBy)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print =<< solve <$> ((!!1) . map read . words <$> getLine) <*> (map (fst . fromJust . B.readInt) . B.words <$> B.getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve k = fst . minimumBy (comparing snd) . zip [1..] . uncurry (zipWith (-)) . (drop (k - 1) &&& id) . scanl1 (+)\n"}, {"source_code": "\nsolve k xs = go 0 start zs\n where go _ _ [(_, _)] = 1\n go ind val ys@((j, y):yss)\n | j >= (l - k + 2) = ind \n | newval < val = go j newval yss\n | otherwise = go ind val yss\n where newval = sum . map snd . take k $ ys\n l = length xs\n zs = zip [1..] xs\n start = sum xs\n\nmain = do\n k <- fmap (last . map read . words) getLine :: IO Int\n ls <- fmap (map read . words) getLine :: IO [Int]\n print $ solve k ls \n"}, {"source_code": "\nsolve k xs = go 1 start zs\n where go _ _ [(_, _)] = 1\n go ind val ys@((j, y):yss)\n | j >= (l - k + 2) = ind \n | newval < val = go (ind+1) newval yss\n | otherwise = go ind val yss\n where newval = sum . map snd . take k $ ys\n l = length xs\n zs = zip [1..] xs\n start = sum xs\n\nmain = do\n k <- fmap (last . map read . words) getLine :: IO Int\n ls <- fmap (map read . words) getLine :: IO [Int]\n print $ solve k ls \n"}], "src_uid": "69f4e340b3f6e1d807e0545ebea1fe2f"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n_log2 !acc 1 = Just acc\n_log2 !acc !curr\n | (curr `mod` 2 == 1) = Nothing\n | otherwise = _log2 (acc+1) (curr `div` 2)\nlog2 = _log2 (0 :: Integer)\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Integer]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n a:b:rest ->\n let solve = (\\big small ->\n if big `mod` small > 0\n then Nothing\n else log2 (big `div` small)\n )\n big = max a b\n small = min a b\n tmp = fromMaybe (-1) $ solve big small\n subres = if tmp == -1 then tmp else (tmp+2) `div` 3\n in Just (subres, rest)\n ) vals\n sequence_ (putStrLn . show <$> res)\n", "positive_code": [{"source_code": "import Data.Bits\nimport Control.Monad\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b] <- (map read.words) <$> getLine\n print $ solve a b\n\nsolve :: Integer -> Integer -> Int\nsolve a b = if r == b then s else -1\n where\n d = myTr b - myTr a\n r = shift a d\n s = (abs d `div` 3) + fromEnum (abs d `mod` 3 /= 0)\n\nmyTr :: Integer -> Int\nmyTr a = until (testBit a) (+1) 0\n"}, {"source_code": "import Data.Int\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve . parse) . tail . lines)\n\nparse :: String -> (Int64, Int64)\nparse = f . map read . words\n where\n f [x, y] = (x, y)\n\nsolve :: (Int64, Int64) -> Int\nsolve (a, b) = maybe (-1) ((`div` 3) . (+ 2)) (solve2 (min a b, max a b))\n\nsolve2 :: (Int64, Int64) -> Maybe Int\nsolve2 (a, b)\n | even a && even b = solve2 (a `div` 2, b `div` 2)\n | even a && odd b = Nothing\n | odd a && even b = succ <$> solve2 (a, b `div` 2)\n | odd a && odd b =\n if a == b\n then Just 0\n else Nothing\n"}, {"source_code": "import Data.Int\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve . parse) . tail . lines)\n\nparse :: String -> (Int64, Int64)\nparse = f . map read . words\n where\n f [x, y] = (x, y)\n\nsolve :: (Int64, Int64) -> Int\nsolve (a, b) = maybe (-1) ((`div` 3) . (+ 2)) (f (min a b, max a b))\n where\n f :: (Int64, Int64) -> Maybe Int\n f (a, b)\n | a == b = Just 0\n | even a && even b = f (a `div` 2, b `div` 2)\n | odd a && even b = succ <$> f (a, b `div` 2)\n | otherwise = Nothing\n"}, {"source_code": "module Main where\n get :: Integer -> Integer -> (Integer, Integer)\n get n pow = \n if n `mod` 2 == 0 then \n get (n `div` 2) (pow + 1)\n else\n (n, pow)\n \n solve :: IO ()\n solve = do\n s <- getLine\n let [a, b] = map (\\x -> read x :: Integer) $ words s\n (ra, x) = get a 0\n (rb, y) = get b 0\n print $ \n if ra /= rb then \n -1\n else \n (abs (x - y) + 2) `div` 3\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter (n - 1)\n \n main :: IO ()\n main = do\n s <- getLine\n let q = read s :: Integer\n iter q"}, {"source_code": "solve :: Integer -> Integer -> Integer\nsolve a b\n | a == b = 0\n | a > b = solve b a\n | mod b a /= 0 = -1\n | twoIsTheOnlyFactor div' = minSteps div'\n | otherwise = -1\n where div' = div b a\n\ntwoIsTheOnlyFactor :: Integer -> Bool\ntwoIsTheOnlyFactor 1 = True\ntwoIsTheOnlyFactor n = (mod n 2 == 0) && twoIsTheOnlyFactor (div n 2)\n\nminSteps :: Integer -> Integer\nminSteps 1 = 0\nminSteps x\n | x >= 8 = 1 + minSteps (div x 8)\n | x >= 4 = 1 + minSteps (div x 4)\n | x >= 2 = 1 + minSteps (div x 2)\n\nparse :: String -> String\nparse input = show $ solve a b\n where [a, b] = map (\\x -> read x :: Integer) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "negative_code": [{"source_code": "import Data.Bits\nimport Control.Monad\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b] <- (map read.words) <$> getLine\n print $ solve a b\n\nsolve :: Int -> Int -> Int\nsolve a b = if r == b then s else -1\n where\n d = countTrailingZeros b - countTrailingZeros a\n r = shift a d\n s = (abs d `div` 3) + fromEnum (abs d `mod` 3 /= 0)\n"}, {"source_code": "solve :: Integer -> Integer -> Integer\nsolve a b\n | a == b = 0\n | a > b = solve b a\n | mod b a /= 0 = -1\n | mod div' 2 /= 0 = -1\n | otherwise = minSteps div'\n where div' = div b a\n\nminSteps :: Integer -> Integer\nminSteps 1 = 0\nminSteps x\n | x >= 8 = 1 + minSteps (div x 8)\n | x >= 4 = 1 + minSteps (div x 4)\n | x >= 2 = 1 + minSteps (div x 2)\n\nparse :: String -> String\nparse input = show $ solve a b\n where [a, b] = map (\\x -> read x :: Integer) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "src_uid": "541039ef3c9b8251b758608811533e06"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>>\n map (words >>> map read) >>>\n process >>> map (map show >>> unwords) >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([n, _]:xss) =\n let (xs, xss') = splitAt n xss\n in solve xs ++ process xss'\n\nsolve :: [[Int]] -> [[Int]]\nsolve = zipWith (\\p -> zipWith f (drop p zo)) zo\n where\n zo = 0 : 1 : zo\n f p x\n | x `mod` 2 == p = x\n | otherwise = x + 1\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain = do\n contents <- getContents\n let notnull = filter (not . null) $ lines contents\n let input = map words notnull\n let res = go (drop 1 input)\n sequence res\n\ngo [] = []\ngo ((n:_):xs) =\n let (a, b) = splitAt (read n) xs\n in solve a:go b\n\nsolve arr = \n let solveA [] _ = []\n solveA (x:xs) y = sequence (solveB x y):solveA xs (y+1)\n solveB [] _ = [putStrLn \"\"]\n solveB (x:xs) y =\n let x' = read x\n in putStr (show (x' + ((x'+y) `mod` 2)) ++ \" \"):solveB xs (y+1)\n in sequence (solveA arr 0)"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = (isstolines.solve.linestoiss.(take n)) rest ++ (tcio.(drop n)) rest where [n,_] = linetois l\n linetoi = read; linetois = (map linetoi) . words; linestoiss = (map linetois) \n itoline = show; istoline = unwords . (map itoline); isstolines = (map istoline)\n\nsolve :: [[Int]] -> [[Int]]\nsolve ass = zipWith (zipWith update) ass altrep where\n altrep = cycle $ map cycle [[0,1],[1,0]]\n update a b | a `mod` 2 == b = a\n | otherwise = a+1\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain = do\n contents <- getContents\n let notnull = filter (not . null) $ lines contents\n let input = map words notnull\n let res = go (drop 1 input)\n sequence res\n\ngo [] = []\ngo ((n:_):xs) =\n let (a, b) = splitAt (read n) xs\n in solve a:go b\n\nsolve arr = \n let solveA [] _ = []\n solveA (x:xs) y = sequence (solveB x y):solveA xs (y+1)\n solveB [] _ = [putStrLn \"\"]\n solveB (x:xs) y = putStr (show (read x + y) ++ \" \"):solveB xs (y+1)\n in sequence (solveA arr 0)"}], "src_uid": "fd11967b07870be3294b9191603b17e8"} {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\n\nmain = interact $ lines >>>\n (\\ (s:_n:xs) -> ($ xs) $ filter (isPrefixOf s) >>> sort >>> (++[s]) >>> head)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\n\nmain :: IO ()\nmain = \n do { input:n:ss <- lines <$> getContents\n ; let ret = case find (eqPrefix input) (sort ss) of\n (Just str) -> str\n Nothing -> input\n ; printf \"%s\" ret\n }\n\neqPrefix pre s =\n and (zipWith (==) pre s)"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n\ts <- getLine\n\tn <- fmap read getLine\n\ta <- replicateM n getLine\n\tputStrLn $ head $ (++[s]) $ sort $ filter (isPrefixOf s) a\n"}, {"source_code": "import Control.Monad\nimport List\n\nmain = do\n xs <- getLine\n n <- readLn\n ys <- replicateM n getLine\n putStrLn $ solve xs ys\n\nsolve xs ys = case ys' of [] -> xs; (k:ks) -> k\n where ys' = filter (isPrefixOf xs) $ sort ys\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\n\nmain = do\n s <- getLine\n n <- read `liftM` getLine\n dict <- Set.fromList `liftM` replicateM n getLine\n\n let (_, hit, dictAfter) = Set.splitMember s dict\n out = if hit || Set.null dictAfter || not ( isPrefixOf s ( Set.findMin dictAfter ) )\n then s\n else Set.findMin dictAfter\n putStrLn out\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\n\n\nmain = do\n input <- getLine\n count <- fmap read getLine\n dict <- replicateM count getLine\n putStrLn (head ((++[input]) (sort (filter (isPrefixOf input) dict))))\n"}, {"source_code": "import Data.List\nimport System.IO\n\nsolve :: [String] -> String\nsolve (x:n:xs) = autocomplete x xs\n\nautocomplete :: String -> [String] -> String\nautocomplete x xs \n | null ms = x\n | otherwise = head ms\n where ms = filter (isPrefixOf x) $ sort xs\n\nmain = do\n input <- getContents\n putStrLn $ solve (lines input)\n"}, {"source_code": "\nimport Data.List (isPrefixOf, sort)\nimport Maybe (fromMaybe, listToMaybe)\nimport Monad (liftM)\n\nsolve :: String -> [String] -> String\nsolve s = fromMaybe s . listToMaybe . filter (isPrefixOf s) . sort\n \n\nmain :: IO ()\nmain = do\n s <- getLine\n n <- readLn\n xs <- liftM (take n . lines) getContents\n putStrLn $ solve s xs\n"}, {"source_code": "import Data.List\n\nsolver s lines = head $ filter (\\x -> (take (length s) x) == s) (lines ++ [s])\n\nmain = do\n s <- getLine\n n' <- getLine\n lines <- sequence $ take (read n'::Int) $ repeat getLine\n putStrLn $ solver s $ sort lines\n "}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\ndebug = flip trace\n-- debug = const\n\nmain = do\n word <- getLine\n n <- read `fmap` getLine :: IO Int\n lines <- replicateM n getLine\n case filter (word `isPrefixOf`) $ sort lines of\n [] -> putStrLn word\n (l:_) -> putStrLn l\n \n "}, {"source_code": "import Data.List\nmain=interact$f.words\nf(w:_:x)|null t=w|1>0=minimum t where t=filter(isPrefixOf w)x"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Control.Applicative\nimport Data.List\n\nmain = interact $ lines >>>\n (\\ (s:_n:xs) -> ($ xs) $ filter (isPrefixOf s) >>> flip if' s <$> null <*> minimum)\n where if' x t f = if x then t else f"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\n\nmain = interact $ lines >>>\n (\\ (s:_n:xs) -> let ss = filter (isPrefixOf s) xs in if null ss then s else minimum ss)"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\n\nmain = interact $ lines >>>\n (\\ (s:_n:xs) -> ($ xs) $ filter (isPrefixOf s) >>> sort >>> listToMaybe >>> maybe s id)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\n\nmain :: IO ()\nmain = \n do { input:n:ss <- lines <$> getContents\n ; let ret = case find (eqPrefix input) (sort ss) of\n (Just str) -> str\n Nothing -> input\n ; print ret\n }\n\neqPrefix pre s =\n and (zipWith (==) pre s)"}], "src_uid": "5ad16e23e96de111c4974551b859a5ff"} {"source_code": "main = getContents >>= print . solve . map read . words\n\nsolve (_:xs) = maximum $ filter (not . isPerfactSqure) xs\n where sqrtInt num = maximum $ takeWhile (\\x -> x*x <= num) [0 .. ]\n isPerfactSqure num\n | num >= 0= let s = sqrtInt num in s*s == num\n | otherwise = False\n \n-- isPerfactSqure num = [ ans | ans <- [0 .. num], num == ans * ans] /= []\n", "positive_code": [{"source_code": "main = getLine >> getLine >>= print . solve . map read . words\n\nsolve = maximum . (filter $ not . (`elem` (map (^2) [0 .. 1000])))\n"}, {"source_code": "main = getLine >> getLine >>= print . solve . map read . words\n\nsolve xs = maximum $ filter (not . (`elem` (map (^2) [0 .. 1000]))) xs\n"}, {"source_code": "main = getContents >>= print . solve . map read . words\n\nsolve (_:xs) = maximum $ filter (not . isPerfactSqure) xs\n where isPerfactSqure num = elem num $ takeWhile (<=num) $ map (^2) [0 .. ]\n"}, {"source_code": "import Data.List\nf :: Double->Bool\nf x\n |x==0=True\n |x<0=False\n |(floor(sqrt(x))^2)==floor(x) =True\n |otherwise=False\n\n\nmain = do\n e1<-getLine\n es<-getLine\n let n=read e1::Int\n xs=map read (words es)::[Double]\n xs2=reverse $ sort xs\n print $ floor $ head $ dropWhile (f) xs2"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = print =<< sol <$> (getLine *> get)\n\nget :: IO [Int]\nget = fmap read . words <$> getLine\n\nsol :: [Int] -> Int\nsol = maximum . filter (not . ps)\n\nps = (==) <*> ((^2) . floor . sqrt . fromIntegral)\n"}, {"source_code": "main = interact $ show . maximum . filter notSquare . map read . tail . words\nnotSquare i = (floor (sqrt (fromIntegral i)))^2 /= i\n"}, {"source_code": "import Data.Int\n\nmain = getContents >>= print . solve . map read . words\n\nsolve:: [Int64] -> Int64\nsolve (_:as) = maximum $ filter check as\n\ncheck a\n | a < 0 = True\n | otherwise = round (sqrt (fromIntegral a)) ^ 2 /= a \n"}, {"source_code": "import qualified Data.ByteString.Char8 as BC\nimport Data.Maybe (fromJust)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n n <- readLn :: IO Int\n a <- sortBy (\\x y -> compare y x) <$> getIntListBC\n print $ solve a\n\nsolve :: [Int] -> Int\nsolve (x:xs) = let y = floor . sqrt $ realToFrac x\n in if x == y^2\n then solve xs\n else x\n\nbsToInt :: BC.ByteString -> Int\nbsToInt = fst . fromJust . BC.readInt\n\ngetIntListBC :: IO [Int]\ngetIntListBC = map bsToInt . BC.words <$> BC.getLine\n"}, {"source_code": "module Main where\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact solve\nsolve = doSolve . map (read . B.unpack) . B.words\ndoSolve input = B.pack $ show $ last $ filter (not . isSquare) $ sort $ tail input\nisSquare x = not $ null $ filter square $ takeWhile (\\n -> n * n <= x) $ iterate (+1) 0 where square n = n * n == x"}, {"source_code": "main = print . maximum . filter (not . isSquare) . map (read :: String -> Int) . tail . words =<< getContents\nisSquare x = x >= 0 && let s = round $ sqrt $ fromIntegral x in s * s == x"}, {"source_code": "main = do\n ln1 <- getLine\n ln2 <- getLine\n putStrLn $ (show . maximum) [ i | i <- f ln2, k i]\n where f = (map (\\x -> read x :: Int)) . words\n k s = let s' = fromIntegral s in truncate(sqrt s') * truncate(sqrt s') /= s \n"}, {"source_code": "main = getLine >> getLine >>= print . solve . map read . words\n\nsolve = maximum . (filter (`notElem` (map (^2) [0 .. 1000])))\n"}], "negative_code": [{"source_code": "import Data.List\nf :: Double->Bool\nf x\n |x<=0=False\n |(floor(sqrt(x))^2)==floor(x) =True\n |otherwise=False\n\n\nmain = do\n e1<-getLine\n es<-getLine\n let n=read e1::Int\n xs=map read (words es)::[Double]\n xs2=reverse $ sort xs\n print $ floor $ head $ dropWhile (f) xs2"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain = print =<< sol <$> (getLine *> get)\n\nget :: IO [Int]\nget = fmap read . words <$> getLine\n\nsol :: [Int] -> Int\nsol = fromJust . find ps . sortBy (flip compare) . filter (>0)\n\nps = (==) <*> (floor . (^2) . sqrt . fromIntegral)\n"}, {"source_code": "import Data.List\nmain = interact $ show . last . go 1 . sort . map read . tail . words\ngo i (x:xs) = case compare x (i^2) of LT -> x : go i xs\n EQ -> go i xs\n GT -> go (i+1) (x:xs)\ngo _ [] = []\n"}, {"source_code": "import Data.List\nmain = interact $ show . last . go (-1000) . sort . map read . tail . words\ngo i (x:xs) = case compare x (i^2) of LT -> x : go i xs\n EQ -> go i xs\n GT -> go (i+1) (x:xs)\ngo _ [] = []\n"}, {"source_code": "module Main where\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact solve\nsolve = doSolve . map (read . B.unpack) . B.words\ndoSolve input = B.pack $ show $ last $ filter (not . isSquare) $ sort $ tail input\nisSquare x = not $ null $ filter square $ takeWhile (\\n -> n * n <= x) $ iterate (+1) 1 where square n = n * n == x"}], "src_uid": "d46d5f130d8c443f28b52096c384fef3"} {"source_code": "main = fmap (f . tail . map read . words) getContents >>= putStrLn\nf :: [Int] -> [Char]\nf xs = unwords [(show . succ . length . fst . span (maximum xs /=)) xs, (show . maximum . filter (maximum xs /=)) xs]", "positive_code": [{"source_code": "main = fmap (f 1 0 0 0 . tail . map read . words) getContents >>= putStrLn\nf a b c d [] = show b ++ \" \" ++ show d\nf a b c d (x:xs)\n | x > c = f (a + 1) a x c xs\n | x > d = f (a + 1) b c x xs\n | otherwise = f (a + 1) b c d xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\nimport Data.Ord\n\n\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ts<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet x= take 2$ reverse $ sortOn fst $ zip s [1..]\n\t\tputStr $ show $ snd $ head x\n\t\tputStr \" \"\n\t\tputStrLn $ show $ fst $ head $ tail x\n"}], "negative_code": [], "src_uid": "1d4aaf15e5c6fcde50515880aae74720"} {"source_code": "import Data.List\n\nfi=fromIntegral\n\n\n\nsolve h n = unwords $ map (\\x->show(sqrt ((fi x)*((fi h)**2)/(fi n)))) [1..n-1]\n\t\t\n\n\n\nmain=do\n\td<-getLine\n\tlet [n,h]=map (\\x->read x::Integer) (words d)\n\tputStrLn (solve h n)\n", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\n\nmain = (fmap (map read. words) getLine :: IO [Double]) >>= \\[n, h]-> putStrLn $ unwords $ map (printf \"%0.10f\". (\\x -> h * sqrt (x / n))) [1, 2 .. n - 1]\n"}, {"source_code": "import Control.Applicative\n\ntotArea :: Float -> Float\ntotArea h = 0.5 * 0.5 * h\n\nareaToHt :: Float -> Float -> Float\nareaToHt t area = sqrt $ 2 * area / t\n\nmain :: IO ()\nmain = do\n [ns, hs] <- words <$> getLine\n let n = (read :: String -> Int) ns\n h = (read :: String -> Float) hs\n t = 0.5 / h\n area = totArea h / (fromIntegral n)\n hts = map (\\ x -> areaToHt t $ (fromIntegral x) * area) [1..(n - 1)]\n mapM_ (\\ x -> putStr $ (show x) ++ \" \") hts\n putStrLn \"\"\n"}, {"source_code": "solve :: Double -> Double -> Double -> Double\nsolve h n i = sqrt $ (i * h^2) / n\n\n\nmain :: IO ()\nmain = do\n [n, h] <- map (read :: String -> Int) . words <$> getLine\n putStrLn $ unwords . map (show . solve (fromIntegral h) (fromIntegral n) . fromIntegral) $ [1..n-1]\n"}], "negative_code": [], "src_uid": "6f8a1a138ea2620f2013f426e29e4d98"} {"source_code": "import Data.Foldable\n\nmain = interact foo\n\nfoo :: String -> String\nfoo inp =\n let [s, t] = take 2 . drop 1 . lines $ inp\n aa = map (\\ii -> drop ii t) [0..((length t)-(length s))]\n (p, q) = minimumBy (\\(i, _) (j, _) -> compare i j) $ map (bar s) aa\n in unlines $ [show p, unwords . map show $ q]\n \nbar :: String -> String -> (Int, [Int])\nbar s t = \n let a = zip3 [1..] s t\n in Prelude.foldl (\\(n, m) (i, c1, c2) -> if c1 == c2 then (n, m) else (n+1, i:m)) (0, []) a", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\ncalc [] _ ps n = ps\ncalc _ [] ps n = [-1]\ncalc (x:xs) (y:ys) ps n\n | x == y = calc xs ys ps (n + 1)\n | otherwise = calc xs ys (n:ps) (n + 1)\n\nget x [] = []\nget [] x = []\nget (x:xs) (y:ys)\n | x == -1 = (y:ys)\n | y == -1 = (x:xs)\n | length xs > length ys = (y:ys)\n | otherwise = (x:xs)\n\nsolve s [] = calc s [] [] 1\nsolve s (x:t) = get (solve s t) (calc s (x:t) [] 1)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n s <- getLine\n t <- getLine\n let\n l = reverse $ solve s t\n putStrLn . show $ length l\n putStrLn $ unwords (map show l)\n"}, {"source_code": "import Data.List\n\nmain = putStrLn . solve . tail . lines =<< getContents\n\nsolve [a, b] = ans where\n la = length a\n s = filter ((>= la) . length) $ map (take la) $ tails b\n f = length . filter id . zipWith (/=) a\n g x = (x, f x)\n h c x = if snd c < snd x then c else x\n k = fst $ foldl h (\"\", 1010) $ map g s\n t = filter (/= 0) $ zipWith3 u [1..] a k\n u x y z = if y == z then 0 else x\n ans = unlines $ [show (length t), unwords $ map show t]\n"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\nimport Data.List\n\nmain = putStrLn . solve . tail . lines =<< getContents\n\nsolve [a,b] = ans where\n la = length a\n s = filter ((>= la) . length) $ map (take la) $ tails b\n f = length . filter id . zipWith (==) a\n g x = (x, f x)\n h c x = if snd c > snd x then c else x\n k = fst $ foldl h (\"\",0) $ map g s\n r = if k /= a then k else '_':tail k\n t = filter (/= 0) $ zipWith3 u [1..] a k\n u x y z = if y == z then 0 else x\n ans = unlines $ [show (length t), unwords $ map show t]\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncompar :: String -> String -> Int -> [Int]\ncompar [] _ _ = []\ncompar (x:xs) (y:ys) pos\n | x == y = compar xs ys (pos + 1)\n | otherwise = pos : compar xs ys (pos + 1)\n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n let x = length s\n let y = length t\n tmp <- forM [0..y-x] $ \\pos -> return (compar s (drop pos t) 1)\n let ans = minimumBy (\\x y -> compare (length x) (length y)) tmp\n print $ length ans\n putStrLn . unwords . map show $ ans\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n getLine\n str1 <- getLine\n str2 <- getLine\n let diffPos = map (solve str1 str2) [0..length str2 - length str1]\n let lens = map length diffPos\n print $ minimum lens\n let Just idx = (elemIndex (minimum lens) lens)\n printNums $ diffPos!!idx\n where\n solve strA strB pos = loop (length strA - 1)\n where\n loop (-1) = []\n loop seek = if (strA!!seek) /= (strB!!(pos+seek)) then (seek+1):loop (seek-1) else loop (seek-1)\n printNums [] = return ()\n printNums (l:list) = do\n putStr $ show l\n putChar ' '\n printNums list"}, {"source_code": "module Main where\n\nimport Data.List\n\n\n\ncnt_diff :: String -> String -> Int\ncnt_diff s t = sum (zipWith dif s t)\n\twhere\n\t\tdif x y = if x /= y then 1 else 0\n\nsolve :: String -> String -> Int -> [Int]\nsolve s t ind\n\t| m < n \t= []\n\t| otherwise = (cnt_diff s $ take n t) : (solve s (drop 1 t) (ind + 1))\n\twhere \n\t\tinf = 1000 * 1000 * 1000\n\t\tn = length s\n\t\tm = length t\n\nget_ans :: String -> String -> (Int, [Int])\nget_ans s t = (mn, map fst $ filter (\\(_, x) -> x == mn) lst)\n\twhere\n\t\tl = solve s t 0\n\t\tlst = zip [0,1..] l\n\t\tinf = 1000 * 1000 * 1000\n\t\tmn = foldl min inf l\n\ndiff :: String -> String -> [Int]\ndiff s t = map fst $ filter (\\(_,x) -> x == 1) $ zip [1,2..] $ zipWith dif s t\n\twhere\n\t\tdif x y = if x /= y then 1 else 0\n\nmain :: IO ()\nmain = do\n\tnms <- getLine\n\ts <- getLine \t\n\tt <- getLine\n\tlet (n, l) = get_ans s t\n\tputStrLn . show $ n\n\t--mapM_ (putStr . (\\x -> (show x) ++ \" \")) l\n\tlet ind = head l\n\tmapM_ (putStr . (\\x -> (show x) ++ \" \")) $ diff s $ drop ind t\n\t--print ind\n\t--print $ drop ind t\n\t--print $ diff s $ drop ind t\n\tputStr \"\\n\""}, {"source_code": "import Data.Ord\nimport Data.List\nimport Control.Applicative\n\nmain = getLine *> ((\\s t -> minimumBy (comparing fst) $ map ((\\is -> (length is, is)) . map (\\(i, _, _) -> i) . filter (\\(_, c, c') -> c /= c') . zip3 [1..] s) $ take (length t - length s + 1) $ tails t ) <$> getLine <*> getLine) >>= (\\(a, b) -> putStr $ show a ++ \"\\n\" ++ unwords (map show b))\n"}, {"source_code": "import Data.List;main=interact(\\h->let[_,s,t]=lines h;l=length;(a,b)=minimumBy(\\(a,_)(b,_)->compare a b)$map(((,)=<i).filter(\\(_,c,z)->c/=z).zip3[1..]s)$take(l t-l s+1)$tails t in show a++\"\\n\"++unwords(map show b))"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List\n\ncnt_diff :: String -> String -> Int\ncnt_diff s t = sum (zipWith dif s t)\n\twhere\n\t\tdif x y = if x /= y then 1 else 0\n\nsolve :: String -> String -> Int -> [Int]\nsolve s t ind\n\t| m < n \t= []\n\t| otherwise = (cnt_diff s $ take n t) : (solve s (drop 1 t) (ind + 1))\n\twhere \n\t\tinf = 1000 * 1000 * 1000\n\t\tn = length s\n\t\tm = length t\n\nget_ans :: String -> String -> (Int, [Int])\nget_ans s t = (mn, map fst $ filter (\\(_, x) -> x == mn) lst)\n\twhere\n\t\tl = solve s t 0\n\t\tlst = zip [1,2..] l\n\t\tinf = 1000 * 1000 * 1000\n\t\tmn = foldl min inf l\n\nmain :: IO ()\nmain = do\n\tnms <- getLine\n\ts <- getLine \t\n\tt <- getLine\n\tlet (n, l) = get_ans s t\n\tputStrLn . show $ n\n\tmapM_ (putStr . (\\x -> (show x) ++ \" \")) l\n\tputStr \"\\n\""}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\ncalc [] _ ps n = ps\ncalc _ [] ps n = [-1]\ncalc (x:xs) (y:ys) ps n\n | x == y = calc xs ys ps (n + 1)\n | otherwise = calc xs ys (n:ps) (n + 1)\n\nget (x:xs) (y:ys)\n | x == -1 = (y:ys)\n | y == -1 = (x:xs)\n | length xs > length ys = (y:ys)\n | otherwise = (x:xs)\n\nsolve s [] = calc s [] [] 1\nsolve s (x:t) = get (solve s t) (calc s t [] 1)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n s <- getLine\n t <- getLine\n let\n l = reverse $ solve s t\n putStrLn . show $ length l\n putStrLn $ unwords (map show l)\n"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\nimport Data.List\n\nmain = putStrLn . solve . tail . lines =<< getContents\n\nsolve [a,b] = ans where\n la = length a\n s = filter ((>= la) . length) $ map (take la) $ tails b\n f = length . filter id . zipWith (==) a\n g x = (x, f x)\n h c x = if snd c > snd x then c else x\n k = fst $ foldl h (\"\",0) $ map g s\n r = if k /= a then k else '_':tail k\n t = filter (/= 0) $ zipWith3 u [1..] a r\n u x y z = if y == z then 0 else x\n ans = unlines $ [show (length t), unwords $ map show t]\n"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\nimport Data.List\n\nmain = putStrLn . solve . tail . lines =<< getContents\n\nsolve [a,b] = ans where\n s = tails b\n f = length . filter id . zipWith (==) a\n g x = (x, f x)\n h c x = if snd x > snd c then x else c\n k = fst $ foldl h (\"\",0) $ map g s\n t = filter (/= 0) $ zipWith3 u [1..] a k\n u x y z = if y == z then 0 else x\n ans = unlines $ [show (length t), unwords $ map show t]\n"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\nimport Data.List\n\nmain = putStrLn . solve . tail . lines =<< getContents\n\nsolve [a,b] = ans where\n s = filter ((==) (length a) . length) $ tails b\n f = length . filter id . zipWith (==) a\n g x = (x, f x)\n h c x = if snd x > snd c then x else c\n k = fst $ foldl h (\"\",0) $ map g s\n t = filter (/= 0) $ zipWith3 u [1..] a k\n u x y z = if y == z then 0 else x\n ans = unlines $ [show (length t), unwords $ map show t]\n"}, {"source_code": "import Data.Foldable\n\nmain = interact foo\n\nfoo :: String -> String\nfoo inp =\n let [s, t] = take 2 . drop 1 . lines $ inp\n aa = map (\\ii -> (ii, s, drop ii t)) [0..((length t)-(length s))]\n (p, q) = minimumBy (\\(i, _) (j, _) -> compare i j) $ map bar aa\n in unlines $ [show p, unwords . map show $ q]\n \nbar :: (Int, String, String) -> (Int, [Int])\nbar (i0, s, t) = \n let a = zip3 [i0..] s t\n in Prelude.foldl (\\(n, m) (i, c1, c2) -> if c1 == c2 then (n, m) else (n+1, i:m)) (0, []) a"}], "src_uid": "dd26f45869b73137e5e5cc6820cdc2e4"} {"source_code": "import Data.List\nimport Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.g (-1) .sort.parse.tail.lines\n\nparse = map (map fastRead.words)\n\ng best [] = best\ng best (x:xs)\n | best <= i = g i xs\n | otherwise = g j xs\n where j = maximum x\n i = minimum x\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nlist :: b -> ([a] -> b) -> [a] -> b\nlist x f xs=case xs of{[]->x;_->f xs}\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xys <- sort.perse.map readInt.B.words <$> B.getContents\n print $ solve xys\n\nperse (x:y:xys) = (x,y) : perse xys\nperse _ = []\n\nsolve :: [(Int,Int)] -> Int\nsolve xys = go 0 xys\n where\n go !acc ((x,y):rest)\n | acc <= y = go y rest\n | otherwise = go x rest\n go acc _ = acc"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines"}, {"source_code": "import Data.List\nmain = interact $ show . solve . sort . map (map read . words) . tail . lines\n\nsolve = flip foldl 0 $ \\c ab -> minimum $ filter (>=c) ab \n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n getInts\n\n print $ foldl (\\v [a, b] -> if b >= v then b else a) 0 (sort ps)\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Data.List (foldl', sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Integer]] -> Integer\nsolve = foldl' (\\x xs -> minimum (filter (>=x) xs)) 0 . sort\n"}, {"source_code": "import Data.List\nmain = interact $ show . last . solve 0 . sort . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve d ((a,b):ds) = d' : solve d' ds where\n d' | b < d = a\n | otherwise = b\nsolve _ _ = []\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n dates <- replicateM n ((map read . words <$> getLine) >>= \\(a:b:_) -> return (a, b))\n print $ foldl pickExam 0 $ sortBy (comparing fst <> comparing snd) dates\n\n where\n pickExam last (new, newEarly) = if newEarly < last then new else newEarly\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\n\n\npair [] = []\npair (a:b:c) = (a,b): ( pair c)\n\nprocess n m [] = m\n\nprocess n m ((a,b):c) \t| b getContents::IO [ Int ]\n\tlet y = process 0 0 $ sort $ pair x\n\tprint y\n\t\n\t"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}, {"source_code": "import Data.List\n\nsolve :: Int -> [[Int]] -> Int\nsolve (0) ([x, y]:xs) = solve (min x y) xs\nsolve curr ([x, y]:xs) = solve (if y >= curr then y else x) xs\nsolve curr _ = curr\n\nord :: [Int] -> [Int] -> Ordering\nord [x1, y1] [x2, y2]\n | x1 < x2 = LT\n | x1 == x2 = compare y1 y2\n | otherwise = GT\n\nparseInput :: String -> [[Int]]\nparseInput = map (map read . words) . lines\n\n\nmain = do\n getLine\n getContents >>= print . solve (0) . sortBy ord . parseInput\n"}, {"source_code": "import Data.List\nmain=interact$show.foldl(\\c->minimum.filter(>=c))0.sort.map(map read.words).tail.lines\n"}], "negative_code": [{"source_code": "import Data.List\nimport Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.g.parse.tail.lines\n\nparse = map (map fastRead.words)\n\ng x\n | (myzip a b []) == q = minimum (last q)\n | otherwise = head (last q)\n where i = myunzip x [] []\n a = sort (fst i)\n b = sort (snd i)\n q = sort x\n\nmyunzip [] l1 l2 = (l1, l2)\nmyunzip (x:xs) l1 l2 = myunzip xs ((head x):l1) ((last x):l2)\n\nmyzip [] [] ans = reverse ans\nmyzip (x:xs) (y:ys) ans = myzip xs ys ([x, y]:ans)\n"}, {"source_code": "import Data.List\nimport Numeric\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.g.parse.tail.lines\n\nparse = map (map fastRead.words)\n\ng x\n | (myzip a b []) == q = minimum (last q)\n | otherwise = head (last q)\n where i = myunzip x [] []\n a = sort (fst i)\n b = sort (snd i)\n q = sort x\n\nmyunzip [] l1 l2 = (l1, l2)\nmyunzip (x:xs) l1 l2 = myunzip xs ((head x):l1) ((last x):l2)\n\nmyzip [] [] ans = reverse ans\nmyzip (x:xs) (y:ys) ans = myzip xs ys ([x, y]:ans)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n getInts\n\n let\n ys = map (!!1) $ sort ps\n\n print $\n if and $ zipWith (<=) ys $ tail ys\n then last ys\n else last $ map (!!0) $ sort ps\n"}, {"source_code": "\nimport Control.Monad (replicateM)\nimport Data.List (sortOn)\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n dates <- replicateM n ((map read . words <$> getLine) >>= \\(a:b:_) -> return (a, b))\n print $ foldl pickExam 0 $ sortOn fst dates\n\n where\n pickExam last (new, newEarly) = if newEarly < last then new else newEarly\n"}, {"source_code": "import Data.List\n\nsolve :: Int -> [[Int]] -> Int\nsolve (0) ([x, y]:xs) = solve (min x y) xs\nsolve curr ([x, y]:xs) = solve (if y >= curr then y else x) xs\nsolve curr _ = curr\n\nord :: [Int] -> [Int] -> Ordering\nord [x1, y1] [x2, y2] = compare x1 x2\n\nparseInput :: String -> [[Int]]\nparseInput = map (map read . words) . lines\n\n\nmain = do\n getLine\n getContents >>= print . solve (0) . sortBy ord . parseInput\n"}], "src_uid": "71bc7c4eb577441f2563e40d95306752"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n [cs, as, bs] <- replicateM 3 (fmap (map fromIntegral) getInts)\n let\n acc (p, opt) (c, a, b) = (p', opt')\n where\n p' = max (abs (a - b) + 1) (if a == b then 0 else p + min a b + c - max a b + 1)\n opt' = max opt (p + c)\n c' = head $ reverse cs\n g xs y = tail xs ++ [y]\n (_, result) = foldl' acc (-10 ^ 17 :: Int64, 0 :: Int64) $ zip3 cs (g as 1) (g bs c')\n C.putStrLn $ C.pack $ show result\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ninf :: Integer\ninf = 4000000000\n\ntest :: IO ()\ntest = do\n _ <- getLine\n cs <- map read . words <$> getLine :: IO [Integer]\n as <- tail . map read . words <$> getLine :: IO [Integer]\n bs <- tail . map read . words <$> getLine :: IO [Integer]\n let ps = zip (subtract 1 <$> tail cs) (zipWith ((abs .) . (-)) as bs)\n print $ maximum $ scanl (\\m (x, y) -> if y == 0 then x + 2 else max (m - y) y + x + 2) (- inf) ps\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> [Int64] -> [Int64] -> [Int64] -> Int64\r\nsolve n cs as bs = snd $ solve' cs (tail as) (tail bs)\r\n where\r\n solve' [c] [] [] = (c - 1 + 2, 0)\r\n -- `debug` (\"solve' \" ++ show [c] ++ \" \" ++ \"[]\" ++ \" \" ++ \"[]\" ++ \" = \" ++ show (c - 1 + 2, 0))\r\n solve' cs@(c:restCs) as@(a:restAs) bs@(b:restBs) = (currentHalfCycleLength, max nextCycleLength currentCycleLength)\r\n -- `debug` (\"solve' \" ++ show cs ++ \" \" ++ show as ++ \" \" ++ show bs ++ \" = \" ++ show (currentHalfCycleLength, max nextCycleLength currentCycleLength))\r\n where\r\n (nextHalfCycleLength, nextCycleLength) = solve' restCs restAs restBs\r\n currentHalfCycleLength = 2 + if a == b then c - 1 else max (c - 1) $ c - 1 - abs (a - b) + nextHalfCycleLength\r\n currentCycleLength = abs (a - b) + nextHalfCycleLength\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n n <- B8.getLine <&> readIntB8\r\n cs <- B8.getLine <&> map readIntB8 . B8.words\r\n as <- B8.getLine <&> map readIntB8 . B8.words\r\n bs <- B8.getLine <&> map readIntB8 . B8.words\r\n\r\n let answer = solve n (map fromIntegral cs) (map fromIntegral as) (map fromIntegral bs)\r\n\r\n printf \"%lld\\n\" answer\r\n\r\n"}], "negative_code": [], "src_uid": "3d898a45ab89b93e006270a77db49017"} {"source_code": "cnt s c = length $ filter (==c) s\ng s t = foldr (||) False [cnt s c == 0 && cnt t c > 0 | c <- ['a'..'z']]\nf s t\n | g s t == False = sum [min (cnt s c) (cnt t c) | c <- ['a'..'z']]\n | otherwise = -1\nmain = do\n s <- getLine\n t <- getLine\n print $ f s t", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Control.Applicative\n\nmain = do\n bought <- convert <$> getLine\n required <- convert <$> getLine\n print $ solve bought required\n \nconvert :: String -> [Int]\nconvert = map ((subtract 1) . length) . group . sort . (['a' .. 'z'] ++)\n\nsolve :: [Int] -> [Int] -> Int\nsolve [] [] = 0\nsolve (b:bought) (r:required)\n | b == 0 && r > 0 = -1\n | result /= -1 = (min b r) + result\n | otherwise = -1\n where\n result = solve bought required\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n m <- getLine\n print $ solve n m\n\nsolve :: String -> String -> Int\nsolve n m = max(-1)$sum(zipWith (&) ns ms)\n where\n ns = map (cnt n) ['a'..'z']\n ms = map (cnt m) ['a'..'z']\n n & m | m <= n = m\n | n == 0 = -10000\n | otherwise = n\n cnt cs c = length $ filter (c==) cs"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n n <- getLine\n m <- getLine\n print $ solve n m\n\nsolve :: String -> String -> Int\nsolve n m = case sum(zipWith (&) ns ms) of\n 0 -> (-1)\n res -> res\n where\n ns = map (cnt n) ['a'..'z']\n ms = map (cnt m) ['a'..'z']\n n & m | m <= n = m\n | otherwise = n\n cnt cs c = length $ filter (c==) cs"}], "src_uid": "b1e09df7c47dbd04992e64826337c28a"} {"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nrepeatM a = mapM (const a) (repeat 1)\nrepeatMn a n = mapM (const a) [1..n]\nreadm::(Read a) => State String a\nreadm = State (head . reads)\nreadchar = State (\\s->(head s,tail s))\nreadall = State (,\"\")\n\nrunRead x s = fst $ runState x s\n\n\nmain = reader >>= writer . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\tn<-readm\n\tm<-readm\n\tlet (portsi,portso,path) = solve n m\n\treturn $ show (length portsi) ++ \"\\n\" ++ (unlines . map showpp $ zip portsi portso) ++ (unlines . map showp $ path)\n\nshowp (a,b) = show a ++ \" \" ++ show b\nshowpp (a,b) = showp a ++ \" \" ++ showp b\n\nflipp = uncurry (flip zip) . unzip\n\nflippp (a,b,c) = (flipp a,flipp b,flipp c)\nsolve 1 2 = ([],[],[(1,1),(1,2),(1,1)])\nsolve 2 1 = flippp $ solve 1 2\nsolve 1 n = ([(1,n)],[(1,1)],[(1,i) | i<-[1..n] ++ [1]])\nsolve n 1 = flippp $ solve 1 n\nsolve n m = case (mod n 2,mod m 2) of\n\t(1,1) -> ([(n,m)],[(1,1)],concat [ zip (repeat i) $ (if mod i 2 == 1 then id else reverse) [1..m] | i<-[1..n]] ++ [(1,1)])\n\t(1,0) -> flippp $ solve m n\n\t(0,_) -> ([],[],\n\t\t\t[(1,1)] ++ concat [zip (repeat i) $ (if mod i 2 == 1 then id else reverse) [2..m] | i<-[1..n]] ++ zip (reverse [1..n]) (repeat 1)\n\t\t)\n", "positive_code": [{"source_code": "main = interact solve\nsolve input = output where\n [n,m] = map (read::String->Int) $ words input\n output = unlines $ map (unwords . (map show)) $ answer n m\nanswer n m\n | n==1 && m==2 = [[0],[1,1],[1,2],[1,1]]\n | n==2 && m==1 = [[0],[1,1],[2,1],[1,1]]\n | n==1 = [1]:[1,m,1,1]:[[1,i]|i<-[1..m]]++[[1,1]]\n | m==1 = [1]:[n,1,1,1]:[[i,1]|i<-[1..n]]++[[1,1]]\n | even n = [0]:[1,1]:[[i,j]|i<-[1..n],j<-if odd i then [2..m] else [m,m-1..2]]\n ++ [[i,1]|i<-[n,n-1..1]]\n | even m = [0]:[1,1]:[[i,j]|j<-[1..m],i<-if odd j then [2..n] else [n,n-1..2]]\n ++ [[1,i]|i<-[m,m-1..1]]\n | otherwise = [1]:[n,m,1,1]:[[i,j]|i<-[1..n],j<-if odd i then [1..m] else [m,m-1..1]]\n ++ [[1,1]]\n"}], "negative_code": [{"source_code": "main = interact solve\nsolve input = output where\n [n,m] = map (read::String->Int) $ words input\n output = unlines $ map (unwords . (map show)) $ answer n m\nanswer n m\n | n==1 = [1]:[1,m,1,1]:[[1,i]|i<-[1..m]]++[[1,1]]\n | m==1 = [1]:[n,1,1,1]:[[i,1]|i<-[1..n]]++[[1,1]]\n | even n = [0]:[1,1]:[[i,j]|i<-[1..n],j<-if odd i then [2..m] else [m,m-1..2]]\n ++ [[i,1]|i<-[n,n-1..1]]\n | even m = [0]:[1,1]:[[i,j]|j<-[1..m],i<-if odd j then [2..n] else [n,n-1..2]]\n ++ [[1,i]|i<-[m,m-1..1]]\n | otherwise = [1]:[n,m,1,1]:[[i,j]|i<-[1..n],j<-if odd i then [1..m] else [m,m-1..1]]\n ++ [[1,1]]\n"}], "src_uid": "a98622d5b6d6d139df90b6fee3baa544"} {"source_code": "import Control.Applicative ((<$>))\n\nimport Data.Char (toLower)\nimport qualified Data.Map as Map\nimport Data.Tuple\n\nmain = do\n\tgetLine\n\tpairs <- map ((\\[to, _, from] -> (to, from)) . words) . lines . map toLower <$> getContents\n\n\tlet distances =\n\t\t\tMap.fromList $ (\"polycarp\", 1) : (map (uncurry calc) pairs)\n\t\twhere\n\t\t\tcalc :: String -> String -> (String, Int)\n\t\t\tcalc to from = (to, (distances Map.! from) + 1)\n\n\n\tprint $ maximum $ map snd $ Map.toList distances\n\n\t\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.Map hiding (map)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n m <- go n $ singleton \"polycarp\" 1\n print $ maximum $ elems m\n where\n key = map toLower\n go 0 m = return m\n go i m = do\n [a, _, b] <- words <$> getLine\n go (i-1) $ insert (key a) (m!key b + 1) m\n"}, {"source_code": "import Data.Char\nmain = do\n\tn<-getLine\n\trest<-getContents\n\tputStrLn $ show $ solve ((map words (lines (map toLower rest)))) [(\"polycarp\",1)]\n\nsolve [] acc = maximum $ map snd acc\nsolve (c:chain) acc = solve chain ((head c, getLevel (last c) acc +1):acc)\n\ngetLevel _ [] = 0\ngetLevel \"polycarp\" _ = 1\ngetLevel name (a:acc) | name == fst a = snd a\n | otherwise = getLevel name acc"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ trailNum pairs \"polycarp\"\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 1\ntrailNum p str = 1 + (maximum1 $ rmap (trailNum b) (map fst a))\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p\n\nrmap :: (a -> b) -> [a] -> [b]\nrmap f [] = []\nrmap f (x:xs) = f x `seq` ( (f x) : rmap f xs )\n\nmaximum1 :: [Int] -> Int\nmaximum1 x = if x == [] then 0 else maximum x"}, {"source_code": "\n\nimport Control.Monad\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Char (toLower)\n\n\ntoLowerS :: String -> String\ntoLowerS = map toLower\n\nreposts :: [(String, [String])] -> Map String [String]\nreposts = M.fromListWith (++)\n\nmaxreposts :: String -> Map String [String] -> Int\nmaxreposts key mapss = case M.lookup key mapss of\n Nothing -> 1\n Just values -> 1 + (maximum $ map (\\k -> maxreposts k mapss) values)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n rawReposts <- replicateM n (getLine >>= \\s -> do\n let ss = words s\n return (toLowerS (last ss), [toLowerS (head ss)]))\n print $ maxreposts \"polycarp\" $ reposts rawReposts\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nimport Data.Char (toLower)\nimport qualified Data.Map as Map\nimport Data.Tuple\n\nmain = do\n\tgetLine\n\tpairs <- map ((\\[to, _, from] -> (to, from)) . words) . lines . map toLower <$> getContents\n\n\tlet distances =\n\t\t\tMap.fromList $ (\"polycarp\", 1) : (map (uncurry calc) pairs)\n\t\twhere\n\t\t\tcalc to from = (to, (distances Map.! from) + 1)\n\n\n\tprint $ maximum $ map snd $ Map.toList distances\n\n\t\n"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ trailNum pairs \"polycarp\"\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum l str = case partition (\\(_,x) -> x == str) l of\n\t\t\t([],_) -> 1\n\t\t\t(a,b) -> 1 + (maximum1 $ map (trailNum b) (map fst a))\n\nmaximum1 :: [Int] -> Int\nmaximum1 x = if x == [] then 0 else maximum x"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ trailNum pairs \"polycarp\"\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 1\ntrailNum p str = 1 + (maximum1 $ map (trailNum b) (map fst a))\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p\n\nmaximum1 :: [Int] -> Int\nmaximum1 x = if x == [] then 0 else maximum x"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ trailNum pairs \"polycarp\"\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 1\ntrailNum p str = 1 + (x `seq` maximum1 x)\n\t\t\twhere x = let (a,b) = partition (\\(_,x) -> x == str) p\n\t\t\t in map (trailNum b) (map fst a)\n\nmaximum1 :: [Int] -> Int\nmaximum1 x = if x == [] then 0 else maximum x"}], "negative_code": [{"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 0\ntrailNum p str = 1 + (maximum1 $ map (trailNum b) (map fst a))\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p\n\nmaximum1 :: [Int] -> Int\nmaximum1 x = if x == [] then 0 else maximum x"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 0\ntrailNum [_] str = 0\ntrailNum p str = 1 + (maximum $ (map (trailNum b) (map fst a)) ++ [0])\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 0\ntrailNum [_] str = 1\ntrailNum p str = 1 + (maximum $ (map (trailNum b) (map fst a)) ++ [0])\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 0\ntrailNum [_] str = 1\ntrailNum p str = 1 + (maximum $ (map (trailNum b) (map fst a)) ++ [1])\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 1\ntrailNum [_] str = 1\ntrailNum p str = 1 + (maximum $ (map (trailNum b) (map fst a)) ++ [0])\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 0\ntrailNum [_] str = 1\ntrailNum p str = 1 + (maximum1 $ map (trailNum b) (map fst a))\n\t\t\twhere (a,b) = partition (\\(_,x) -> x == str) p\n\nmaximum1 :: [Int] -> Int\nmaximum1 x = if x == [] then 0 else maximum x"}, {"source_code": "import Data.List (partition)\nimport Data.Char (isUpper, toLower)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- fmap (map ifUpperLower) getContents\n let pairs = pairParse $ take n $ lines input\n putStrLn . show $ 1 + (trailNum pairs \"polycarp\")\n\nifUpperLower :: Char -> Char\nifUpperLower c = if isUpper c then toLower c else c\n\npairParse :: [String] -> [(String, String)]\npairParse = (map (\\x -> (head x, last x))) . (map words)\n\ntrailNum :: [(String, String)] -> String -> Int\ntrailNum [] str = 0\ntrailNum [_] str = 1\ntrailNum p str = 1 + (maximum $ (map (trailNum p) (map fst (filter (\\(_,x) -> x == str) p))) ++ [0])"}], "src_uid": "16d4035b138137bbad247ccd5e560051"} {"source_code": "main :: IO()\nmain = do\n a <- getLine\n let n = read a :: Int\n if odd n\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show $ reverse [1..n]\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\n\nmain = do\n n <- getInt\n if odd n\n then print (-1)\n else do\n let (evens, odds) = partition even [1..n]\n let soln = interleave evens odds\n forM_ soln $ \\i -> putStr (show i) >> putChar ' '\n\ninterleave xs ys = f xs ys [] where\n f [] [] zs = zs\n f (x:xs) (y:ys) zs = x:y: f xs ys zs"}, {"source_code": "gao [] = []\ngao (i:j:k) = j:i:gao k\n\nmain = do\n n <- fmap read getLine\n putStrLn $ unwords $ map show $ if odd n then [-1] else gao [1 .. n]\n\n"}, {"source_code": "import Data.List\nimport Data.List.Split\n\n(|>) x f = f x\nmain = interact solve\n\nsolve contents = let\n n = contents |> lines |> head |> read :: Int\n in pp n\n \npp n = if odd n then \"-1\" else permute n\n\npermute n = [1..n] |> chunksOf 2 |> map reverse |> concat |> map show |> unwords\n \n"}, {"source_code": "main = do\n n <- getLine\n putStr $ unwords $ map show $ f $ (read n :: Int)\n \nf :: Int -> [Int]\nf n \n | (mod n 2)==1 = [-1]\n | otherwise = f1 1 n \n\nf1 :: Int -> Int -> [Int]\nf1 a 0 = []\nf1 a n = (a+1):a:(f1 (a+2) (n-2))"}, {"source_code": "\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\n\nprints :: Show a => [a] -> IO ()\nprints xs = mapM_ (putStr . (++ \" \") . show) xs >> putStrLn \"\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n (odd n) ? (putStrLn \"-1\") $ prints $ reverse [1..n]\n"}, {"source_code": "main=interact$f.read\nf::Int->[Char]\nf x=if odd x then \"-1\" else q x\nq 2=\"2 1\"\nq x=q (x-2)++\" \"++show x++\" \"++show (x-1)"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> [Int]\nsolve 0 = []\nsolve n = 2:1:map (+2) (solve $ n - 2)\n\nmain = do\n n <- read <$> getLine\n if n `mod` 2 == 1\n then print $ -1\n else putStrLn $ concatMap ((++\" \").show) $ solve n\n"}, {"source_code": "main=interact$unwords.map show.f.read\nf n|odd n=[-1]|1>0=[1..n`div`2]>>= \\i->[2*i,2*i-1]\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= putStrLn . unwords . map show . solve\n\nsolve :: Integer -> [Integer]\nsolve n | even n = concatMap (\\i -> [ 2 * i, 2 * i - 1 ]) [ 1 .. n `div` 2 ]\n | otherwise = [ -1 ]\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nswapL [] = []\nswapL (x:y:l) = y:x:swapL l\n\nmain = do\n n <- read <$> getLine\n if n `mod` 2 == 1\n then (putStrLn \"-1\")\n else (putStrLn . unwords . map show $ swapL [1..n])"}, {"source_code": "main = do\n n <- readLn\n if odd n\n then print (-1)\n else putStrLn $ unwords $ map show $ solve n 1\nsolve n i | i >= n = []\n | otherwise = i+1 : i : solve n (i+2)"}, {"source_code": "main = interact $ unwords . map show . f . read\nf n | odd n = [-1]\n | otherwise = [1..div n 2] >>= (\\x -> [2*x, 2*x-1])\n"}, {"source_code": "main=readLn>>=putStrLn.unwords.map show.f\nf n| odd n = [-1]\n | otherwise = [1..div n 2] >>= \\i->[2*i,2*i-1]"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\nperm n = myswap [1..n]\n\nmyswap [] = []\nmyswap (a:b:cs) = b:a:(myswap cs)\n\t\nmain= do\n\tn<- read <$> getLine\t\n\tlet x= if even n then perm n else [-1]\n\tputStrLn $ intercalate \" \" $ map show x \n\t \n\t "}, {"source_code": "process :: Int -> [Int]\nprocess n\n | odd n = [-1]\n | otherwise = concat $ map (\\x -> [x,x-1]) [2,4..n]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n putStrLn . unwords . map show $ process n"}, {"source_code": "\nf :: [Int] -> Int -> [Int]\nf [] _ = []\nf (x:xs) n | n==1 = (x+1):(f xs 2) \n | n==2 = (x-1):(f xs 1) \n\nmain :: IO()\nmain = do\n a <- getLine\n let b = read a::Int\n if (odd b) \n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show $ f [1..b] 1"}, {"source_code": "main = readLn >>= putStrLn . unwords . map show . f\nf n \n | odd n = [-1]\n | otherwise = [1.. div n 2] >>= \\i -> [2*i, 2*i-1]\n\n"}, {"source_code": "main = putStrLn . unwords . map show . slv . read =<< getLine\nslv 1 = [-1]\nslv n \n | n `mod` 2 == 0 = [n,n-1..1]\n | True = [-1]"}], "negative_code": [{"source_code": "import Data.List\nperfectPerms n = [ p | p <- permutations [1..n],\n i <- [1..n],\n p !! (i-1) /= i,\n p !! ((p !! (i-1)) - 1) == i]\np [] = \"-1\"\np a = unwords . map show $ a\nmain = interact $ p . perfectPerms . read"}, {"source_code": "import Data.List\nperfectPerms n = [ p | p <- permutations [1..n],\n i <- [1..n],\n p !! (i-1) /= i,\n p !! ((p !! (i-1)) - 1) == i]\np [] = \"-1\"\np (a:as) = unwords . map show $ a\nmain = interact $ p . perfectPerms . read\n"}, {"source_code": "main = putStrLn . unwords . map show . slv . read =<< getLine\nslv 1 = [-1]\nslv n = [n,n-1..1]"}], "src_uid": "204ba74195a384c59fb1357bdd71e16c"} {"source_code": "import Data.Int\nimport Control.Monad\n\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\_ -> do\n [n, r] <- fmap (fmap read . words) getLine :: IO [Int64]\n let result = if r < n\n then (r * (r + 1)) `div` 2\n else ((n - 1) * n) `div` 2 + 1\n print result\n ", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, replicateM_)\nimport Data.Word\n\nsol n r =\n let p1 = if r < n\n then 0\n else 1\n p2 = if r >= n - 1\n then (n - 1) * n `div` 2\n else r * (r + 1) `div` 2 in\n p1 + p2\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, r] :: [Word64] <- map read . words <$> getLine\n print $ sol n r\n\n"}, {"source_code": "import Control.Monad\n\nmain :: IO()\nmain =\n do\n x <- read <$> getLine\n replicateM_ x solve\n\nsolve :: IO()\nsolve =\n do\n [n, r] <- map read . words <$> getLine :: IO [Integer]\n if r < n\n then\n print $ r * (r + 1) `div` 2\n else\n print $ n * (n - 1) `div` 2 + 1\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, r] <- map read . words <$> getLine\n print $ if r < n then triangle r else triangle (n - 1) + 1\n\ntriangle n = (n * (n + 1)) `div` 2\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, replicateM_)\n\nsol n r =\n let p1 = if r < n\n then 0\n else 1\n p2 = if r >= n - 1\n then (n - 1) * n `div` 2\n else r * (r + 1) `div` 2 in\n p1 + p2\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, r] :: [Word] <- map read . words <$> getLine\n print $ sol n r\n\n"}, {"source_code": "import Control.Monad\n\nmain :: IO()\nmain =\n do\n x <- read <$> getLine\n replicateM_ x solve\n\nsolve :: IO()\nsolve =\n do\n [n, r] <- map read . words <$> getLine :: IO [Int]\n if r < n\n then\n print $ r * (r + 1) `div` 2\n else\n print $ n * (n - 1) `div` 2 + 1\n"}], "src_uid": "eb3d8259ca598c3c455ddfdbe433cb78"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nsample1 0 _ = []\r\nsample1 n m = [if even i then w else r |i<-[1..m]] : sample1 (n-1) m\r\n where \r\n w = if even n then 'W' else 'R'\r\n r = if even n then 'R' else 'W'\r\n \r\n\r\nsample2 0 _ = []\r\nsample2 n m = [if odd i then w else r |i<-[1..m]] : sample2 (n-1) m\r\n where \r\n w = if even n then 'W' else 'R'\r\n r = if even n then 'R' else 'W'\r\n\r\nmyZip _ '.' = True\r\nmyZip '.' _ = True\r\nmyZip a b = a == b\r\n\r\nsolve [] [] = True\r\nsolve (a:as) (b:bs) = solve as bs && (and $ zipWith myZip a b)\r\n\r\nprintResult = do\r\n [n,m] <- readInts\r\n xs <- replicateM n getLine\r\n let a = sample1 n m\r\n b = sample2 n m\r\n ra = solve a xs \r\n rb = solve b xs\r\n r = ra || rb\r\n putStrLn $ if r then \"YES\" else \"NO\"\r\n if r then mapM_ putStrLn (if ra then a else b)\r\n else return () \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: [BS.ByteString] -> Int\r\nsolve ss\r\n | all (ok 0) $ zip ss [0..] = 0\r\n | all (ok 1) $ zip ss [0..] = 1\r\n | otherwise = 2\r\n where\r\n ok i0 (s,i1) = all (\\j -> ok2 (BS.index s j) (i0 `xor` i1 `xor` j)) [0..m-1]\r\n where\r\n m = BS.length s\r\n ok2 '.' _ = True\r\n ok2 'R' i = even i\r\n ok2 'W' i = odd i\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n grid <- replicateM n $ BS.pack . dropWhileEnd isSpace . BS.unpack <$> BS.getLine\r\n let r = solve grid\r\n if r == 2 then\r\n putStrLn \"NO\"\r\n else do\r\n putStrLn \"YES\"\r\n forM_ [0..n-1] $ \\i -> do\r\n let x = i `mod` 2 == r\r\n let ss = if x then \"RW\" else \"WR\"\r\n let s = take m $ concat $ repeat ss\r\n putStrLn s"}], "negative_code": [], "src_uid": "12f35743f482b68e3156a45d6ac5bb14"} {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\n\nprocess [] n a | n>=0 = reverse ( (n+1) : (tail a))\n | otherwise= [-1]\n\nprocess (s:ss) n a\t|n<0 = [-1]\n\t\t\t| s=='(' = process ss (n+1) a\n\t\t\t| s==')' = process ss (n-1) a\n\t\t\t| otherwise = process ss (n-1) (1:a)\n\ncheck [] _ = True\ncheck (s:ss) n\t| n<0 =False\n\t\t| s==')' = check ss (n+1)\n\t \t| s=='(' = check ss (n-1)\n\t \t| otherwise = n>=0\n \n\nmain=do\n\ts<- getLine\n\tputStrLn $ if not (check (reverse s) 0) then \"-1\" else intercalate \"\\n\"$ map show $ process s 0 []", "positive_code": [{"source_code": "main = getLine >>= putStr . unlines . map show . g . f 0 0\nf m n _ | m < 0 = [-1]\nf m n ('(':x) = f (m+1) n x\nf m n (')':x) = f (m-1) (min m n) x\nf m n ('#':x) = 1:f (m-1) m x\nf m n [] | n > m = [m+1] | otherwise = [-1]\ng x | last x == -1 = [-1] | otherwise = init (init x) ++ [last x]"}, {"source_code": "import Data.List (intercalate)\n\n\nparse :: Int -> String -> Int\nparse p (c:cs) | p < 0 = -1\n | c == '(' = parse (p+1) cs\n | otherwise = parse (p-1) cs\nparse p _ = p\n\ntransform :: Int -> String -> String\ntransform n = snd . foldr f (False, \"\")\n where f c (r, cs) | c == '#' && r = (r, ')':cs)\n | c == '#' = (not r, replicate n ')' ++ cs)\n | otherwise = (r, c:cs)\n\nsolve :: String -> String\nsolve str | p < 0 || i < 0 = \"-1\"\n | otherwise = intercalate \"\\n\" $ replicate h \"1\" ++ [show $ p + 1] \n where h = (subtract 1) $ length $ filter (== '#') str\n p = parse 0 str\n t = transform (p+1) str\n i = parse 0 t\n\nmain = getLine >>= putStrLn . solve\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n cs <- getLine\n putStr.unlines.map show.maybe[-1]id $ solve cs\n\nsolve :: String -> Maybe [Int]\nsolve cs = go0 0 (reverse cs) >>= go [] 0\n where\n go _ _ \"(\" = Nothing\n go res stk ('(':cs) = go res (stk+1) cs\n go res stk ('#':cs)\n | stk > 0 = go (1:res) (stk-1) cs\n | otherwise = Nothing\n go res stk (')':cs)\n | stk > 0 = go res (stk-1) cs\n | otherwise = Nothing\n go (r:res) stk [] = Just (reverse $ (r + stk) : res)\n go _ _ _ = Nothing\n\n go0 stk (')':cs) = go0 (stk+1) cs\n go0 stk ('(':cs)\n | stk > 0 = go0 (stk-1) cs\n | otherwise = Nothing\n go0 stk cs = Just $ reverse $ replicate stk ')' ++ cs"}], "negative_code": [{"source_code": "main = getLine >>= putStr . unlines . map show . g . f 0 0\nf m _ _ | m < 0 = [-1]\nf m n ('(':x) = f (m+1) n x\nf m n (')':x) = f (m-1) n x\nf m n ('#':x) = 1:f (m-1) m x\nf m n [] | n > m = [m+1] | otherwise = [-1]\ng x | last x == -1 = [-1] | otherwise = init (init x) ++ [last x]"}, {"source_code": "import Data.Maybe\nmain = interact $ unlines . map show . fromMaybe [-1] . f 0\nf 0 [] = Just []\nf _ [] = Nothing\nf n ('(':y) = f (n+1) y\nf n (')':y)\n | n > 0 = f (n-1) y\n | otherwise = Nothing\nf n ('#':'#':y)\n | n > 0 = fmap (1:) $ f (n-1) ('#':y)\n | otherwise = Nothing\nf n ('#':y)\n | n > length a = fmap (n-length a:) $ f 0 b\n | otherwise = Nothing\n where (a,b) = span (==')') y\nf n (x:y) = f n y"}, {"source_code": "main = getLine >>= putStr . unlines . map show . g . f 0 0\nf m n _ | m < 0 || n < 1 = [-1]\nf m n ('(':x) = f (m+1) n x\nf m n (')':x) = f (m-1) (min (m-1) n) x\nf m n ('#':x) = 1:f (m-1) m x\nf m n [] | n > m = [m+1] | otherwise = [-1]\ng x | last x == -1 = [-1] | otherwise = init (init x) ++ [last x]"}, {"source_code": "import Data.List (intercalate)\n\n\nparse :: String -> ([Int], Int, Int)\nparse = foldl func ([], 0, 0)\n where func (xs, p, h) x =\n let (n, nh) | x == '#' = (p - 1, h + 1)\n | x == '(' = (p + 1, h)\n | x == ')' = (p - 1, h)\n in (n:xs, n, nh)\n\nsolve :: ([Int], Int, Int) -> String\nsolve ((x:_), _, h) =\n intercalate \"\\n\" $ replicate (h - 1) \"1\" ++ [show $ x + 1]\n\nmain = getLine >>= putStrLn . solve . parse\n"}, {"source_code": "import Data.List (intercalate)\n\n\nparse :: Int -> Int -> String -> Maybe (Int, Int)\nparse p h (c:cs) | p < 0 = Nothing\n | c == '#' = parse (p-1) (h+1) cs\n | c == '(' = parse (p+1) h cs\n | c == ')' = parse (p-1) h cs\nparse p h [] = if p < 0 then Nothing else Just (p, h)\n\nsolve :: Maybe (Int, Int) -> String\nsolve Nothing = \"-1\"\nsolve (Just (x, h)) =\n intercalate \"\\n\" $ replicate (h - 1) \"1\" ++ [show $ x + 1]\n\nmain = getLine >>= putStrLn . solve . parse 0 0\n"}, {"source_code": "import Data.List (intercalate)\n\n\nparse :: String -> ([Int], Int, Int)\nparse = foldl func ([], 0, 0)\n where func (xs, p, h) x =\n let (n, nh) | x == '#' = (p - 1, h + 1)\n | x == '(' = (p + 1, h)\n | x == ')' = (p - 1, h)\n in (n:xs, n, nh)\n\nsolve :: ([Int], Int, Int) -> String\nsolve ((x:_), _, h) =\n intercalate \"\\n\" $ replicate (h - 1) \"1\" ++ [show x]\n\nmain = getLine >>= putStrLn . solve . parse\n"}, {"source_code": "import Data.List (intercalate)\n\n\nprepare :: Int -> Int -> [Int] -> String -> [Int]\nprepare hashes prev res (c:cs)\n | c == '#' = prepare (hashes+1) next (next:res) cs\n | otherwise = prepare hashes next (next:res) cs\n where next = if c == '(' then prev + 1 else prev - 1\nprepare h _ res _ = h : reverse res\n\nsolve :: [Int] -> [Int]\nsolve [h, x] = if x > 0 then [h, x] else [h, -1]\nsolve (h:x:xs) | x == -1 = [h, -1]\n | otherwise = solve (h:xs)\n\noutput :: [Int] -> String\noutput [_, -1] = \"-1\\n\"\noutput [h, 0] = intercalate \"\\n\" $ replicate h \"1\"\noutput [h, x] = intercalate \"\\n\" $ replicate (h-1) \"1\" ++ [show (x+1)]\n\nmain = getLine >>= putStrLn . output . solve . prepare 0 0 []\n"}, {"source_code": "import Data.List (intercalate)\n\n\nprepare :: Int -> Int -> [Int] -> String -> [Int]\nprepare hashes prev res (c:cs)\n | c == '#' = prepare (hashes+1) next (next:res) cs\n | otherwise = prepare hashes next (next:res) cs\n where next = if c == '(' then prev + 1 else prev - 1\nprepare h _ res _ = h : reverse res\n\nsolve :: [Int] -> [Int]\nsolve [h, x] = if x >= 0 then [h, x] else [h, -1]\nsolve (h:x:xs) | x == -1 = [h, -1]\n | otherwise = solve (h:xs)\n\noutput :: [Int] -> String\noutput [_, -1] = \"-1\\n\"\noutput [h, 0] = intercalate \"\\n\" $ replicate h \"1\"\noutput [h, x] = intercalate \"\\n\" $ replicate (h-1) \"1\" ++ [show (x+1)]\n\nmain = getLine >>= putStrLn . output . solve . prepare 0 0 []\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n cs <- getLine\n putStr.unlines.map show.maybe[-1]id $ solve cs\n\nsolve :: String -> Maybe [Int]\nsolve cs = go [] 0 cs\n where\n go res stk ('(':cs) = go res (stk+1) cs\n go res stk ('#':cs)\n | stk > 0 = go (1:res) (stk-1) cs\n | otherwise = Nothing\n go res stk (')':cs)\n | stk > 0 = go res (stk-1) cs\n | otherwise = Nothing\n go (r:res) stk [] = Just (reverse $ (r + stk) : res)\n go _ _ _ = Nothing"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\n\nprocess [] n a | n<0 = [-1]\n | otherwise= reverse ( (n+1) : (tail a))\n\nprocess (s:ss) n a\t|n<0 = [-1]\n\t\t\t| s=='(' = process ss (n+1) a\n\t\t\t| s==')' = process ss (n-1) a\n\t\t\t| otherwise = process ss (n-1) (1:a)\n \n\nmain=do\n\ts<- getLine\n\tputStrLn $ intercalate \"\\n\"$ map show $ process s 0 []"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\n\nprocess [] n a | n==0 = reverse ( (n+1) : (tail a))\n | otherwise= [-1]\n\nprocess (s:ss) n a\t|n<0 = [-1]\n\t\t\t| s=='(' = process ss (n+1) a\n\t\t\t| s==')' = process ss (n-1) a\n\t\t\t| otherwise = process ss (n-1) (1:a)\n \n\nmain=do\n\ts<- getLine\n\tputStrLn $ intercalate \"\\n\"$ map show $ process s 0 []"}], "src_uid": "0a30830361b26838b192d7de1efcdd2f"} {"source_code": "import Control.Monad\nimport qualified Data.Array.Unboxed as A\nimport Data.Array.Unboxed ((!))\n\ntype Arr = A.UArray Int Int\ntype Dp = Arr\n\n\ncountLeft' :: [Int] -> (Int,Char) -> [Int]\ncountLeft' lst@(b:xb) (i,'+') | (even i) = ((b+1):lst)\ncountLeft' lst@(b:xb) (i,'-') | (even i) = ((b-1):lst)\ncountLeft' lst@(b:xb) (i,'+') | otherwise = ((b-1):lst)\ncountLeft' lst@(b:xb) (i,'-') | otherwise = ((b+1):lst)\n\n\ncountLeft :: String -> [Int]\ncountLeft s =\n reverse $ foldl countLeft' [0] (zip [0..] s)\n\n\ntoArray :: [Int] -> Arr\ntoArray a = A.array (0,(length a)-1) (zip [0..] a)\n\n\nprepare :: String -> Dp\nprepare x = toArray $ countLeft x\n\n\nquery' :: Int -> Int -> Dp -> Int\nquery' l r _ | l > r = 0\nquery' l r dp | odd l = (dp ! r) - (dp ! (l-1))\nquery' l r dp | otherwise = (dp ! (l-1)) - (dp ! r)\n\n\nquery :: Int -> Int -> Dp -> Int\nquery l r dp =\n let sum = query' l r dp\n in\n if sum == 0 then 0\n else if even (r-l+1) then 2\n else 1\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,q] = map read $ words line :: [Int]\n str <- getLine\n --print str\n let dp = prepare str\n --print dp\n forM_ [1..q] $ \\_ -> do\n line <- getLine\n let [l,r] = map read $ words line :: [Int]\n --print [l,r]\n let res = query l r dp\n print res\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nimport Data.Array\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = (String, [(Int, Int)])\ntype Output = [Int]\n\ninput :: Scanner Input\ninput = do\n str\n q <- int\n (,) <$> str <*> (q >< pair int int)\n\noutput :: Output -> C.ByteString\noutput = C.unlines . map showB\n\nsolve :: Input -> Output\nsolve (s, qs) = map query qs\n where\n conv c i = (if c == '+' then 1 else -1) * (if odd i then 1 else -1)\n\n pref = listArray (0, length s) $ scanl (+) 0 $ zipWith conv s [0..]\n rsum l r = pref ! r - pref ! (l - 1)\n\n query (l, r)\n | rsum l r == 0 = 0\n | odd (r - l + 1) = 1\n | otherwise = 2\n\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "3f7f29e57cc03be8ff1251ab42738739"} {"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = (Int, Int, Int)\r\ntype OutType = Int\r\n\r\nsolve :: InType -> OutType\r\nsolve (l, r, a) = if x >= l then f x else f r\r\n where x = if r `mod` a == a - 1 then r else r - r `mod` a - 1\r\n f z = z `div` a + z `mod` a\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] =\r\n case toArr s of\r\n [l, r, a] -> (l, r, a)\r\n _ -> error \"input\"\r\n\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . solve . receive) . chunksOf 1 . tail . lines\r\n", "positive_code": [{"source_code": "import Control.Arrow\r\n\r\n\r\nmain = interact $ lines >>> drop 1 >>> map processTest >>> unlines\r\n\r\n\r\nprocessTest = words >>> map read >>> solve >>> show\r\n\r\n\r\nsolve [l, r, a]\r\n | not (l <= r) = solve [r, l, a]\r\n | div l a == div r a = f a r\r\n | mod r a == a - 1 = f a r\r\n | otherwise = f a (r - mod r a - 1)\r\n\r\n\r\nf a x = div x a + mod x a\r\n"}, {"source_code": "import Data.List ( sort )\r\nsolve :: [String] -> [String]\r\nsolve = map (show . func)\r\n\r\nfunc b\r\n | (l `div` a) == (r `div` a) = uncurry (+) (r `divMod` a)\r\n | (r `mod` a) == a-1 = uncurry (+) (r `divMod` a)\r\n | otherwise = (r `div` a) + a - 2\r\n where\r\n [l,r,a] = map read $ words b\r\n\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines\r\n\r\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve :: Int -> Int -> Int -> Int\nsolve l r a = max (r `div` a + r `mod` a) (ll `div` a + ll `mod` a) \n where\n ll = max (r - (r `mod` a) - 1) l\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n let [a, b, c] = (map read . words) l\n print $ solve a b c\n"}], "negative_code": [{"source_code": "import Control.Monad (forM_)\n\nsolve :: Int -> Int -> Int -> Int\nsolve l r a = maximum [x `div` a + x `mod` a | x <- [r - (r `mod` a) - 1.. r]]\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n let [a, b, c] = (map read . words) l\n print $ solve a b c\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve :: Int -> Int -> Int -> Int\nsolve l r a = maximum [x `div` a + x `mod` a | x <- [ll .. r]]\n where\n ll = if r - l < l then l else r - l\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n let [a, b, c] = (map read . words) l\n print $ solve a b c\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve :: Int -> Int -> Int -> Int\nsolve l r a = max (b + c) (d + e)\n where\n b = r `mod` a\n c = r `div` a\n d = (r-1) `mod` a\n e = (r-1) `div` a\n \nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n let [n, b, x] = (map read . words) l\n print $ solve n b x\n"}], "src_uid": "681ee82880ddd0de907aac2ccad8fc04"} {"source_code": "-- https://codeforces.com/contest/1618/problem/A\nimport Control.Monad (replicateM)\n\nanswer [a,_,_,_, ac, bc,_] = show a ++ \" \" ++ show b ++ \" \" ++ show c where\n c = ac - a\n b = bc - c\n\nmain = getLine >>= flip replicateM run . read\nrun = do\n line <- (read <$>) . words <$> getLine\n putStrLn $ answer line\n ", "positive_code": [{"source_code": "import Control.Monad (forM_)\n\nsolve :: (Eq a, Num a) => [a] -> [a]\nsolve arr =\n if a + b == c then [a, b, d] else [a, b, c]\n where\n (a : b : c : d : cs) = arr\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ unwords $ map show $ solve arr\n"}, {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n xs <- readInts\r\n let a = head xs\r\n b = a + minimum (map (subtract a) $ tail xs)\r\n c = last xs - a - b\r\n putStrLn $ unwords $ map show [a, b, c]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [], "src_uid": "e0ec0cd81d2ec632ef89d207d80fa8a3"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n k <- getInt\r\n aLi <- replicateM n getInt\r\n let\r\n a :: UArray Int Int\r\n a = listArray (1, n) aLi\r\n -- need: sizeof ok - sizeof notok >= k\r\n -- i.e. sz - (n - sz) >= k, i.e. 2 * sz >= n + k,\r\n -- i.e. sz >= div (n + k + 1) 2\r\n tarSz = div (n + k + 1) 2\r\n sa :: UArray Int Int\r\n sa = listArray (1, n) $ sort $ elems a\r\n (x, y) = minimumBy (\\(x0, y0) (x1, y1) -> compare (y0 - x0) (y1 - x1))\r\n $ [(sa ! (i - tarSz + 1), sa ! i) | i <- [tarSz .. n]]\r\n getrs :: Int -> Int -> Int -> Int -> [[Int]]\r\n getrs i _ _ 1 = [[i, n]]\r\n getrs i j 1 left = [i, j] : getrs (j+1) j 0 (left - 1)\r\n getrs i j net left = let ajp = a ! (j + 1)\r\n in if inRange (x, y) ajp\r\n then getrs i (j + 1) (net + 1) left\r\n else getrs i (j + 1) (net - 1) left\r\n pure $ putInts [x, y] <> foldMap putInts (getrs 1 0 0 k)\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n", "positive_code": [{"source_code": "{-# LANGUAGE RecordWildCards #-}\r\nimport Control.Monad\r\nimport qualified Data.Array as AR\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport qualified Data.Set as S\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Text.Printf (printf)\r\n\r\ndata TC = TC { n::Int, k::Int, a::[Int]}\r\n\r\nmain = do\r\n [tt] <- readInts\r\n replicateM_ tt solve\r\n\r\nsolve = do\r\n TC {..} <- tc\r\n\r\n let\r\n b = AR.listArray (0, n - 1) (sort a)\r\n ar = AR.listArray (0, n - 1) a\r\n inc = (n + k + 1) `div` 2\r\n\r\n -- traceIO $ show b\r\n\r\n let\r\n search i x y\r\n | i == (n - inc + 1) = (x, y)\r\n | otherwise =\r\n let\r\n l = b AR.! i\r\n r = b AR.! (i + inc - 1)\r\n in\r\n if r - l < y - x\r\n then search (i + 1) l r\r\n else search (i + 1) x y\r\n\r\n let (x, y) = search 0 (-1) (n + 1)\r\n\r\n printf \"%d %d\\n\" x y\r\n\r\n let \r\n splitAR::Int -> Int -> Int -> Int -> IO Int\r\n splitAR i last mx cur \r\n | i == n = pure last\r\n | otherwise = do\r\n let cur1 = cur + (if x <= (ar AR.! i) && ar AR.! i <= y then 1 else -1)\r\n if cur1 > mx \r\n then \r\n if cur1 >= 1 && cur1 <= k - 1 \r\n then do\r\n printf \"%d %d\\n\" (last + 2) (i + 1)\r\n splitAR (i + 1) i cur1 cur1\r\n else splitAR (i + 1) last cur1 cur1\r\n else splitAR (i + 1) last mx cur1\r\n\r\n lst <- splitAR 0 (-1) 0 0\r\n printf \"%d %d\\n\" (lst + 2) n\r\n\r\ntc = do\r\n [n, k] <- readInts\r\n TC n k <$> readInts\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n k <- getInt\r\n aLi <- replicateM n getInt\r\n let\r\n a :: UArray Int Int\r\n a = listArray (1, n) aLi\r\n -- need: sizeof ok - sizeof notok >= k\r\n -- i.e. sz - (n - sz) >= k, i.e. 2 * sz >= n + k,\r\n -- i.e. sz >= div (n + k + 1) 2\r\n tarSz = div (n + k + 1) 2\r\n sa :: UArray Int Int\r\n sa = listArray (1, n) $ sort $ elems a\r\n (x, y) = minimumBy (\\(x0, y0) (x1, y1) -> compare (y0 - x0) (x1 - y1))\r\n $ [(sa ! (i - tarSz + 1), sa ! i) | i <- [tarSz .. n]]\r\n getrs :: Int -> Int -> Int -> Int -> [[Int]]\r\n getrs i _ _ 1 = [[i, n]]\r\n getrs i j 1 left = [i, j] : getrs (j+1) j 0 (left - 1)\r\n getrs i j net left = let ajp = a ! (j + 1)\r\n in if inRange (x, y) ajp\r\n then getrs i (j + 1) (net + 1) left\r\n else getrs i (j + 1) (net - 1) left\r\n pure $ putInts [x, y] <> foldMap putInts (getrs 1 0 0 k)\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "src_uid": "321423f103e6d9c567079d2dde71b5bb"} {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n let (a,b) = solve n as\n print a\n putStrLn $ (unwords.map show) b\n\nsolve :: Int -> [Int] -> (Int,[Int])\nsolve n as = ((n-1) `div` 2, merge bigs smalls)\n where\n as' = sort as\n (smalls,bigs) = splitAt ((n-1) `div` 2) as'\n\nmerge :: [a] -> [a] -> [a]\nmerge (a:as) (b:bs) = a:b:merge as bs\nmerge as bs = as ++ bs\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int64]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int64) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (read::String->Int) $ line\n\ncount :: Eq a => a -> [a] -> Int\ncount x = length . filter (==x)\n\nmerge :: [a] -> [a] -> [a]\nmerge [] ys = ys\nmerge (x:xs) ys = x:(merge ys xs)\n\ncalc :: [Int64] -> Int64\ncalc (x:y:z:xs) = (if y < x && y < z then 1 else 0) + calc (z:xs)\ncalc _ = 0\n\nsolve :: IO ()\nsolve = do\n n <- readInt\n b <- readArray\n let a = reverse $ sort b\n let (large,small) = splitAt ((n + 1) `div` 2) a\n let res = merge large small\n let answer = calc res\n print answer\n forM_ res $ (\\x -> print x)\n return ()\n\n\nmain :: IO ()\nmain = do\n -- t <- readInt\n -- forM_ [0..t-1] $ (\\i -> solve)\n solve\n"}, {"source_code": "import Data.List\n\ntrySolve :: Int -> [Int] -> Int -> Maybe [Int]\ntrySolve n as k = if k + k + 1 > n\n then Nothing\n else let\n (lows, nonlows) = splitAt k as\n (rev_his, mids) = splitAt (k+1) (reverse nonlows)\n his = reverse rev_his\n in if and $ zipWith (<) lows his\n then Just $ stitch lows his ++ mids\n else Nothing\n\nstitch :: [Int] -> [Int] -> [Int]\nstitch [] [] = []\nstitch ps (q:qs) = q : stitch qs ps\nstitch _ _ = error \"stitch: invalid args\"\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p = let\n go low top = if low == top\n then low\n else let\n mid = div (low + top + 1) 2\n in if p mid\n then go mid top\n else go low (mid - 1)\n in go\n\nsolve :: Int -> [Int] -> (Int, [Int])\nsolve n li = let\n p k = case trySolve n li k of\n Nothing -> False\n _ -> True\n ktar = binSearch p 0 (n + 100)\n in case trySolve n li ktar of\n Nothing -> error \"binSearch failed?\"\n Just ans -> (ktar, ans)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n let (ktar, ans) = solve n (sort a)\n print ktar\n putStrLn . unwords $ map show ans\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n \nmain = do\n getLine\n as <- sort . map read . words <$> getLine :: IO [Integer]\n let solution = solve as\n print $ cheap solution\n putStrLn $ unwords $ map show solution\n \nsolve as\n | even $ length as = (\\(a, b) -> [a, b]) =<< zip (as !! pred d : take (pred d) as) (drop d as)\n | otherwise = (as !! d :) $ (\\(a, b) -> [a, b]) =<< zip (take d as) (drop (succ d) as)\n where\n d = length as `div` 2\n \ncheap = length . filter (\\(a, b, c) -> a > b && b < c) . (zip3 <*> tail <*> tail . tail)"}], "negative_code": [], "src_uid": "bcd9439fbf6aedf6882612d5f7d6220f"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts\n m <- getLine\n\n let\n ls = scanl (+) 0 as\n rs = scanr (+) 0 $ zipWith (\\a b -> if b == '1' then a else 0) as m\n r = maximum $ zipWith3 (\\l a r -> if a == '1' then l + r else 0) ls m $ tail rs\n\n print $ max r $ head rs\n\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n--import System.IO\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\n\n\nsolution :: [Int] -> [Char] -> Int -> Int -> Int -> Int\nsolution [] _ acc curmax _ = max acc curmax\nsolution (a:as) ('0':bs) acc curmax s = solution as bs acc curmax (s-a)\nsolution (a:as) ('1':bs) acc curmax s = solution as bs (acc + a) (max curmax (acc+s')) s'\n where s' = s - a\n\nmain = do\n _ <- getLine\n a <- readsInt\n b <- getLine\n print $ solution (reverse a) (reverse b) 0 0 (sum a)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLn\n l <- readsLine\n m <- getLine\n print $ solve n l m\n\nsolve :: Int -> [Int] -> String -> Int\nsolve n l m = go (reverse l) (reverse m) (sum l) 0\n where\n go (a:as) ('0':m) !s !sm = go as m (s-a) sm\n go (a:as) ('1':m) !s !sm = go as m s (max sm (s-a))\n go [] _ s sm = max sm s\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLn\n l <- readsInt\n m <- getLine\n print $ solve n l m\n\nsolve :: Int -> [Int] -> String -> Int\nsolve n l m = go (reverse l) (reverse m) (sum l) 0\n where\n go (a:as) ('0':m) !s !sm = go as m (s-a) sm\n go (a:as) ('1':m) !s !sm = go as m s (max sm (s-a))\n go [] _ s sm = max sm s\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n bits <- map digitToInt.B.unpack.fst.B.spanEnd (\\c-> isSpace c || c == '0') <$> B.getLine\n let !l = length bits\n print $ solve l (take l xs) bits\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve 0 [] [] = 0\nsolve 1 [x] [b] = b * x\nsolve n xs bits = max (unsafeAt sumR 0).maximum $ map f [0..n-1]\n where\n arr = listArray (0,n-1) bits :: UArray Int Int\n sumR = listArray (0,n-1) $ scanr1 (+) $ zipWith (*) xs bits :: UArray Int Int\n sumL = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int\n f i\n | unsafeAt arr i == 0 = unsafeAt sumR 0\n | i == n-1 = unsafeAt sumL (i-1)\n | i == 0 = unsafeAt sumR (i+1)\n | otherwise = unsafeAt sumL (i-1) + unsafeAt sumR (i+1)\n"}, {"source_code": "solve_ :: [Integer] -> String -> (Integer, Integer)\nsolve_ [] [] = (0, 0)\nsolve_ (x:xs) (y:ys)\n | y == '1' = (max (x + ans) sum, x + sum)\n | otherwise = (ans, x + sum)\n where (ans, sum) = solve_ xs ys\n\nsolve :: String -> String -> Integer\nsolve a m = ans\n where (ans, sum) = solve_ (map read $ reverse $ words a) $ reverse m\n\nmain = do\n n <- getLine\n a <- getLine\n m <- getLine\n print $ solve a m\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List (foldl')\nmain :: IO ()\nmain = do\n xs <- fmap BS.words BS.getContents\n let m = BS.unpack $ last xs\n c:ns = map (fst . fromJust . BS.readInteger) (init xs)\n print $ rush c (m) (ns)\n\nrush _ m xs \n | '1' `notElem` m = 0\n | otherwise = maximum (r:ls)\n where b = zipWith (\\n i -> if i == '1' then (n,True) else (n,False)) xs m\n r = one b\n (_,_,ls) = foldl' (\\(cums,rs,l) (x,h)-> (cums+x,if h then rs+x else rs,\n if h then ((r - rs - x)+cums):l else l))\n (0,0,[]) b\n\none = foldl' (\\a (l,b) -> if b then l + a else a) 0\n\ntwo x = let c = dropWhile (not . snd) x\n s1 = map fst $ takeWhile snd c\n s2 = one . map (\\(x,_) -> (x,True)) $ c\n in s2 - minimum s1\n"}], "negative_code": [{"source_code": "import System.IO\n\nsolution :: [Int] -> [Char] -> Int -> Int\nsolution [] _ acc = acc\nsolution a b acc = max s t\n where (a',b') = unzip $ dropWhile (\\(_,bit) -> bit == '0') $ zip a b\n s = sum $ tail a'\n t = solution (tail a') (tail b') (acc + (head a'))\n\nmain = do\n _ <- getLine\n as <- getLine\n b <- getLine\n let a = map (\\s -> read s :: Int) $ words as\n r = solution (reverse a) (reverse b) 0\n \n print r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n bits <- map digitToInt.B.unpack.fst.B.spanEnd (\\c-> isSpace c || c == '0') <$> B.getLine\n let !l = length bits\n print $ solve l (take l xs) bits\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve 1 [x] [b] = b * x\nsolve n xs bits = max (unsafeAt sumR 0).maximum $ map f [0..n-1]\n where\n arr = listArray (0,n-1) xs :: UArray Int Int\n sumR = listArray (0,n-1) $ scanr1 (+) $ zipWith (*) xs bits :: UArray Int Int\n sumL = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int\n f i\n | unsafeAt arr i == 0 = unsafeAt sumR 0\n | i == n-1 = unsafeAt sumL (i-1)\n | i == 0 = unsafeAt sumR (i+1)\n | otherwise = unsafeAt sumL (i-1) + unsafeAt sumR (i+1)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n bits <- map digitToInt.B.unpack.fst.B.spanEnd (\\c-> isSpace c || c == '0') <$> B.getLine\n let l = length bits\n print $ solve l (take l xs) bits\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve 1 [x] [b] = b * x\nsolve n xs bits = maximum $ map f [0..n-1]\n where\n arr = listArray (0,n-1) xs :: UArray Int Int\n sumR = listArray (0,n-1) $ scanr1 (+) $ zipWith (*) xs bits :: UArray Int Int\n sumL = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int\n f i\n | unsafeAt arr i == 0 = unsafeAt sumR 0\n | i == n-1 = unsafeAt sumL (i-1)\n | i == 0 = unsafeAt sumR (i+1)\n | otherwise = unsafeAt sumL (i-1) + unsafeAt sumR (i+1)\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List (foldl')\nmain :: IO ()\nmain = do\n xs <- fmap BS.words BS.getContents\n let m = BS.unpack $ last xs\n c:ns = map (fst . fromJust . BS.readInteger) (init xs)\n print $ rush c (reverse m) (reverse ns)\n\nrush _ m xs \n | '1' `notElem` m = 0\n | otherwise = max (one b) (two b)\n where b = zipWith (\\n i -> if i == '1' then (n,True) else (n,False)) xs m\n\none = foldl' (\\a (l,b) -> if b then l + a else a) 0\n\ntwo x = let c = dropWhile (not . snd) x\n s1 = map fst $ takeWhile snd c\n s2 = one . map (\\(x,_) -> (x,True)) $ c\n in s2 - minimum s1\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List (foldl')\nmain :: IO ()\nmain = do\n xs <- fmap BS.words BS.getContents\n let m = BS.unpack $ last xs\n c:ns = map (fst . fromJust . BS.readInt) (init xs)\n print $ rush c (reverse m) (reverse ns)\n\nrush :: Int -> String -> [Int] -> Int\nrush c m xs \n | '1' `notElem` m = 0\n | otherwise = max (one b) (two b)\n where b = zipWith (\\n i -> if i == '1' then (n,True) else (n,False)) xs m\n\none :: [(Int,Bool)] -> Int\none = foldl' (\\a (l,b) -> if b then l + a else a) 0\n\ntwo :: [(Int,Bool)] -> Int\ntwo x = let c = dropWhile (not . snd) x\n s1 = (one . init . takeWhile snd) c\n s2 = one . map (\\(x,_) -> (x,True)) . dropWhile snd $ c\n in s1 + s2\n\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List (foldl')\nmain :: IO ()\nmain = do\n xs <- fmap BS.words BS.getContents\n let m = BS.unpack $ last xs\n c:ns = map (fst . fromJust . BS.readInteger) (init xs)\n print $ rush c (reverse m) (reverse ns)\n\nrush _ m xs \n | '1' `notElem` m = 0\n | otherwise = max (one b) (two b)\n where b = zipWith (\\n i -> if i == '1' then (n,True) else (n,False)) xs m\n\none = foldl' (\\a (l,b) -> if b then l + a else a) 0\n\ntwo x = let c = dropWhile (not . snd) x\n s1 = (one . init . takeWhile snd) c\n s2 = one . map (\\(x,_) -> (x,True)) . dropWhile snd $ c\n in s1 + s2\n"}], "src_uid": "9366e1626b33b4f4e49cf35200c0448f"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\nclamp u v w = max u $ min v $ w\n\nmain = do\n _:f:xs <- getInts\n print $ solve f (parsePairs xs)\n\nsolve :: Int -> [(Int, Int)] -> Integer\nsolve f ps = base + bonus where\n base = sum . map toInteger $ [min u v | (u, v) <- ps]\n bonus = sum . map toInteger . take f . reverse . sort $ [clamp 0 u (v - u) | (u, v) <- ps]\n", "positive_code": [{"source_code": "import Control.Monad (replicateM)\nimport Data.Functor ((<$>))\nimport Data.List (sortBy)\nimport Data.Maybe (fromMaybe)\n\nimport qualified Data.ByteString.Char8 as B\n\nnewtype ShopDay = ShopDay (Integer, Integer, Integer)\n deriving (Show, Eq, Ord)\n\nmain :: IO ()\nmain = do\n n:f:_ <- readLine\n v <- sortBy (flip compare) <$> replicateM (fromInteger n) readDay\n putStrLn $ show $ solution f v\n where readLine = map (fst . fromMaybe undefined . B.readInteger) <$> (B.words <$> B.getLine)\n readDay = do\n a:b:_ <- readLine\n return $ ShopDay (min (2 * a) b - min a b, a, b)\n\nsolution :: Integer -> [ShopDay] -> Integer\nsolution 0 v = sum $ map (\\ (ShopDay (_, a, b)) -> min a b) v\nsolution n (v:vs) = min (2 * a) b + solution (n - 1) vs\n where ShopDay (_, a, b) = v\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.Functor ((<$>))\nimport Data.Int (Int64)\nimport Data.List (sortBy)\nimport Data.Maybe (fromMaybe)\n\nimport qualified Data.ByteString.Char8 as B\n\nnewtype ShopDay = ShopDay (Integer, Integer, Integer)\n deriving (Show, Eq, Ord)\n\nmain :: IO ()\nmain = do\n n:f:_ <- readLine\n v <- sortBy (flip compare) <$> replicateM (fromInteger n) readDay\n putStrLn $ show $ solution f v\n where readLine = map (fst . fromMaybe undefined . B.readInteger) <$> (B.words <$> B.getLine)\n readDay = do\n a:b:_ <- readLine\n return $ ShopDay (min (2 * a) b - min a b, a, b)\n\nsolution :: Integer -> [ShopDay] -> Integer\nsolution 0 v = sum $ map (\\ (ShopDay (_, a, b)) -> min a b) v\nsolution n (v:vs) = min (2 * a) b + solution (n - 1) vs\n where ShopDay (_, a, b) = v\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM, forM_)\nimport Data.ByteString.Char8( readInteger, readInt, tail)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\nimport Data.List( sortBy)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n\treadPair::IO (Integer, Integer)\n\treadPair = do\n\t Just (l,rest) <- readInteger <$> getLine'\n\t let\n\t\tJust (r,_) = readInteger $ B.tail rest\n\n\t return (l,r)\n\n Just (n_, rest) <- readInt <$> getLine'\n let \n\tJust (f_, _) = readInt $ B.tail rest\n\n klPairs_ <- replicateM (fromIntegral n_) readPair\n let\n\tsortedKlpairs = sortBy cmp klPairs_\n\t where\n\t cmp (k1,l1) (k2,l2) = let\n\t\t\t\t mn l k = min (2*k) l\n\t\tin\n\t\t compare ((mn l2 k2)-k2) ((mn l1 k1)-k1)\n\n\tsell::Int->Integer->[(Integer,Integer)]->[Integer]\n\tsell _ now [] = [now]\n\tsell 0 now ((k,l):kls) = sell 0 ((min k l)+now) kls\n\tsell f now ((k,l):kls)\n\t | k>=l\t= sell f (l+now) kls\n\t | otherwise\t= sell (f-1) ((min (2*k) l)+now) kls\n\t\t\t \n print . maximum $ sell f_ 0 sortedKlpairs\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Ord\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nchi\u1ebfn :: Int -> [(Int64, Int64)] -> Int64\nchi\u1ebfn f = sum . map (\\(i, (k, l)) -> min l $ if i <= f then 2 * k else k) . zip [1..] . sortBy (flip $ comparing (\\(k, l) -> min l (2 * k) - min l k))\n\nmain = do\n n:f:_ <- readInts <$> B.getLine\n kls <- replicateM n ((\\(k:l:_) -> (k, l)) . map fromIntegral . readInts <$> B.getLine)\n print $ chi\u1ebfn f kls\n\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Data.Functor\n\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents\n\nparsePairs :: [Int] -> [(Int, Int)]\nparsePairs [] = []\nparsePairs (x:y:xs) = (x, y) : parsePairs xs\n\nclamp u v w = max u (min v w)\n\nsolve :: Int -> [(Int, Int)] -> Integer\nsolve f xs = base + extra\n where base = sum . map toInteger $ [min k l | (k, l) <- xs]\n extra = sum . map toInteger . take f . reverse . sort $ [clamp 0 k (l - k) | (k, l) <- xs]\n\nmain :: IO ()\nmain = do\n _:f:xs <- getInts\n print $ solve f (parsePairs xs)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\nclamp u v w = max u $ min v $ w\n\nmain = do\n _:f:xs <- getInts\n print $ solve f (parsePairs xs)\n\nsolve :: Int -> [(Int, Int)] -> Integer\nsolve f ps = base + bonus where\n base = sum . map toInteger $ [min u v | (u, v) <- ps]\n bonus = sum . map toInteger . take f . reverse . sort $ [clamp 0 u (v - u) | (u, v) <- ps]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Maybe\nimport Data.Int\nimport Data.Bool\nimport Data.List\nimport Control.Monad\n\nmodulant :: Int64\nmodulant = 1000000007\n\ntwos :: [Int64]\ntwos = work 1\n where\n work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)\n\nmain :: IO ()\nmain = do\n [n, f] <- liftM (\\l -> (read :: String -> Int) <$> words l) getLine\n days <- getDays n\n let newCustomers = (\\(p, c) -> (max 0 (min p (c- p)), (p,c))) <$> days\n sorted = reverse $ sort newCustomers\n doubled = (\\(a,(b, c)) -> min (a+b) c) <$> take f sorted\n normal = (\\(a,(b, c)) -> min b c) <$> drop f sorted\n print $ sum doubled + sum normal\n\ngetDays :: Int -> IO [(Int64, Int64)]\ngetDays t = mapM (\\_ -> do\n [a,b] <- liftM (\\l -> (read :: String -> Int64) <$> words l) getLine\n return (a,b)) [1..t]\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Ord\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nchi\u1ebfn :: Int -> [(Int64, Int64)] -> Int64\nchi\u1ebfn f = sum . map (\\(i, (k, l)) -> min l $ if i <= f then 2 * k else k) . zip [1..] . sortBy (flip $ comparing (\\(k, l) -> min l $ 2 * k))\n\nmain = do\n n:f:_ <- readInts <$> B.getLine\n kls <- replicateM n ((\\(k:l:_) -> (k, l)) . map fromIntegral . readInts <$> B.getLine)\n print $ chi\u1ebfn f kls\n\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Ord\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nchi\u1ebfn f = sum . map (\\(i, (k, l)) -> min l $ if i <= f then 2 * k else k) . zip [1..] . sortBy (flip $ comparing (\\(k, l) -> min l $ 2 * k))\n\nmain = do\n n:f:_ <- readInts <$> B.getLine\n kls <- replicateM n ((\\(k:l:_) -> (k, l)) . readInts <$> B.getLine)\n print $ chi\u1ebfn f kls\n\n"}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\nclamp u v w = max u $ min v $ w\n\nmain = getInts >>= print . go where\n go (_:f:xs) = solve f (parsePairs xs)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve f ps = base + bonus where\n base = sum [min u v | (u, v) <- ps]\n bonus = sum . take f . reverse . sort $ [clamp 0 u (v - u) | (u, v) <- ps]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Maybe\nimport Data.Int\nimport Data.Bool\nimport Data.List\nimport Control.Monad\n\nmodulant :: Int64\nmodulant = 1000000007\n\ntwos :: [Int64]\ntwos = work 1\n where\n work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)\n\nmain :: IO ()\nmain = do\n [n, f] <- liftM (\\l -> (read :: String -> Int) <$> words l) getLine\n days <- getDays n\n let newCustomers = (\\(p, c) -> (max 0 (min p (c- p)), (p,c))) <$> days\n sorted = reverse $ sort newCustomers\n doubled = (\\(a,(b, c)) -> min (a+b) c) <$> take f sorted\n normal = (\\(a,(b, c)) -> min b c) <$> drop f sorted\n print $ sum doubled + sum normal\n\ngetDays :: Int -> IO [(Int, Int)]\ngetDays t = mapM (\\_ -> do\n [a,b] <- liftM (\\l -> (read :: String -> Int) <$> words l) getLine\n return (a,b)) [1..t]\n"}, {"source_code": "import Data.Functor ((<$>))\n\nnewtype ShopDay = ShopDay (Int, Int, Int)\n deriving (Show, Eq, Ord)\n\nmain :: IO ()\nmain = do\n n:f:_ <- readLine\n v <- loop n\n case f of\n 0 -> putStrLn $ show $ solution f v\n _ -> putStrLn $ show $ solution f (qsr v)\n where readLine = map (read :: String -> Int) . words <$> getLine\n loop :: Int -> IO [ShopDay]\n loop 0 = return []\n loop n = do\n a:b:_ <- readLine\n rest <- loop $ n - 1\n return $ ShopDay (min (2 * a) b, a, b) : rest\n\nsolution :: Int -> [ShopDay] -> Int\nsolution 0 v = sum $ map (\\ (ShopDay (_, a, b)) -> min a b) v\nsolution n (v:vs) = a + solution (n - 1) vs\n where ShopDay (a, _, _) = v\n\nqsr :: (Ord a) => [a] -> [a]\nqsr [] = []\nqsr (x:xs) = qsr (filter (>=x) xs) ++ [x] ++ qsr (filter ())\nimport Data.Int (Int64)\nimport Data.List (sortBy)\nimport Data.Maybe (fromMaybe)\n\nimport qualified Data.ByteString.Char8 as B\n\nnewtype ShopDay = ShopDay (Integer, Integer, Integer)\n deriving (Show, Eq, Ord)\n\nmain :: IO ()\nmain = do\n n:f:_ <- readLine\n v <- sortBy (flip compare) <$> replicateM (fromInteger n) readDay\n putStrLn $ show $ solution f v\n where readLine = map (fst . fromMaybe undefined . B.readInteger) <$> (B.words <$> B.getLine)\n readDay = do\n a:b:_ <- readLine\n return $ ShopDay (min (2 * a) b, a, b)\n\nsolution :: Integer -> [ShopDay] -> Integer\nsolution 0 v = sum $ map (\\ (ShopDay (_, a, b)) -> min a b) v\nsolution n (v:vs) = a + solution (n - 1) vs\n where ShopDay (a, _, _) = v\n"}], "src_uid": "c9b322a9138410a82e541179272eb6bf"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Int (Int64)\n\nreadInt = fst . M.fromJust . C.readInt\n\nmain = do\n (map readInt . C.words -> (_:(map fromIntegral -> [p :: Int64, q, r]))) <- B.getLine\n (map (fromIntegral . readInt) . C.words -> xs) <- B.getLine\n let ls = scanl1 (if p < 0 then min else max) xs\n rs = scanr1 (if r < 0 then min else max) xs\n print . maximum $ zipWith3 (\\a b c -> p * a + q * b + r * c) ls xs rs\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n show `fmap` liftM4 solve p64 p64 p64 (replicateM n p64)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n p64 = fmap to64 poi\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\n\nsolve p q r = maximum . liftM3 (zipWith3 (\\a b c -> a + b + c)) (scanl1 max . map (p*)) (map (q*)) (scanr1 max . map (r*))\n\n"}], "negative_code": [], "src_uid": "a8e56ad4de6f0eecbe5521226c0335ab"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (forM_)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)\r\nimport Data.Array ((!))\r\nimport Data.Array.ST (MArray (newArray), readArray, runSTArray, writeArray)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Char (toLower)\r\nimport Data.Maybe (fromJust)\r\nimport Data.List (nub, sort)\r\n\r\ndata TC = TC {s :: String}\r\n\r\nsolve TC {..} = unique + allC\r\n where\r\n unique = length s\r\n allC = length $ nub $ sort s\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (C.pack . show) >>> C.unlines\r\n\r\nscan = numberOf $ int >> TC <$> C.unpack <$> str\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n", "positive_code": [{"source_code": "module Main (main) where\nimport Numeric (showFFloat)\nimport Data.Char (toUpper)\nimport Control.Monad (forM_)\nimport qualified Data.Foldable as String\n\nimport qualified Data.Set as Set\n\n-- reset && stack build && echo \"success\" && stack exec haskell-codeforces-exe && echo finished\n-- gen-hie > hie.yaml\n\n\nstrToInt a = read a :: Int\nstrToFloat a = read a :: Float\n\npshow x = putStr (show x)\npfshow x = putStr (showFFloat (Just 2) x \"\")\n\n\n\nsolve :: IO()\nsolve = do\n _ <- getLine\n s <- getLine\n let cntUnique = Set.size $ Set.fromList s\n let cntTotal = String.length s\n print (cntUnique + cntTotal)\n\nmain :: IO ()\nmain = do\n n <- readLn\n forM_[1..n] $ \\_ -> do\n solve"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List (nub)\r\n\r\n\r\nmain = do\r\n tests_n <- read <$> getLine\r\n replicateM_ tests_n $ do\r\n getLine\r\n s <- getLine\r\n print (findTotalBalloonsWon s)\r\n\r\n\r\nfindTotalBalloonsWon s = length s + length (nub s)\r\n"}, {"source_code": "import Data.List\n\n\ntestcase 0 = return ()\ntestcase t = do\n getLine\n s <- getLine\n putStrLn $ show (length s + (length $ group $ sort s))\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_, void)\n \nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ntestCase :: IO ()\ntestCase = do\n getLine\n line <- getLine\n\n let mp = foldr (flip (Map.insertWith (+)) 1) Map.empty line\n\n print $ length (Map.keys mp) + sum (Map.elems mp)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n\n replicateM_ t testCase"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe\r\n\r\n--\r\nimport Data.List\r\n\r\nsolve :: C.ByteString -> Int\r\nsolve = sum . map (succ . length) . group . sort . C.unpack\r\n\r\ninput = int *> bstr\r\n\r\noutput = C.pack . show\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\n-- Scanner\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&))\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = String\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print\n\nparse :: IO Domain\nparse = do\n _ <- getLine\n line <- getLine\n -- putStrLn line\n return line\n\nsolve :: Solver\nsolve = uncurry (+) . ((length . nub) &&& (length))\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- (readLn :: IO Int)\n line <- getLine\n print $ n + length (group (sort line))\n\nmain :: IO ()\nmain = do n <- (readLn :: IO Int)\n forM_ [1 .. n] testCaseMain\n"}, {"source_code": "import Data.List\r\nimport qualified Data.Char as DC\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n n <- fmap (read :: String -> Int) getLine\r\n s <- getLine\r\n putStrLn $ show $ length s + (length $ nub s)\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)"}], "negative_code": [], "src_uid": "66777b8719b1756bf4b6bf93feb2e439"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n let\n func :: Int -> [((Int, Int), Int)]\n func 0 = []\n func 1 = []\n func n\n | odd n = ((n - 1, n), -1) : map (\\i -> ((i, n), 1)) l1 ++ map (\\i -> ((i, n), -1)) l2 ++ map (\\i -> ((i, n - 1), -1)) l1 ++ map (\\i -> ((i, n - 1), 1)) l2 ++ func (n - 2)\n | otherwise = ((n - 1, n), 0) : map (\\i -> ((i, n - 1), 1)) l1 ++ map (\\i -> ((i, n - 1), -1)) l2 ++ map (\\i -> ((i, n), -1)) l1 ++ map (\\i -> ((i, n), 1)) l2 ++ func (n - 2)\n where\n l1 = [1, 3 .. n - 2]\n l2 = [2, 4 .. n - 2]\n C.putStrLn $ C.pack $ concat $ intersperse \" \" $ map (show . snd) $ sort $ func n\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = B.unwords . map bshow . solve <$> popInt\n\n\nsolve n =\n let ms = (flip concatMap) [1 .. (n - 1) `quot` 2] $\n \\d -> (flip map) [0 .. n - 1] $\n \\i -> (i, (i + d) `rem` n)\n scores = listArray ((0, 0), (n - 1, n - 1)) (repeat 0) //\n concatMap (\\(i, j) -> [((i, j), 1), ((j, i), -1)]) ms in\n (flip concatMap) [0 .. n - 1] $\n \\i -> (flip map) [i + 1 .. n - 1] $\n \\j -> scores ! (i, j)\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\ntype SIO = StateT P.ByteString IO\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n let\n (wins, ties) = divMod (n-1) 2\n solve x y = if y - x <= wins\n then 1\n else if y - x <= wins + ties\n then 0\n else 0-1\n putInts [solve x y | x <- [1..n], y <- [x+1 .. n]]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n let\n func :: Int -> [((Int, Int), Int)]\n func 0 = []\n func 1 = []\n func x\n | odd x = ((n - 1, n), -1) : map (\\i -> ((i, n), 1)) l1 ++ map (\\i -> ((i, n), -1)) l2 ++ map (\\i -> ((i, n - 1), -1)) l1 ++ map (\\i -> ((i, n - 1), 1)) l2 ++ func (x - 2)\n | otherwise = ((n - 1, n), 0) : map (\\i -> ((i, n - 1), 1)) l1 ++ map (\\i -> ((i, n - 1), -1)) l2 ++ map (\\i -> ((i, n), -1)) l1 ++ map (\\i -> ((i, n), 1)) l2 ++ func (x - 2)\n where\n l1 = [1, 3 .. n - 2]\n l2 = [2, 4 .. n - 2]\n C.putStrLn $ C.pack $ concat $ intersperse \" \" $ map (show . snd) $ sort $ func n\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n let\n func :: Int -> [((Int, Int), Int)]\n func 0 = []\n func 1 = []\n func x\n | odd x = ((n, n - 1), 1) : map (\\i -> ((i, n), 1)) l1 ++ map (\\i -> ((i, n), -1)) l2 ++ map (\\i -> ((i, n - 1), -1)) l1 ++ map (\\i -> ((i, n - 1), 1)) l2 ++ func (x - 2)\n | otherwise = ((n - 1, n), 0) : map (\\i -> ((i, n - 1), 1)) l1 ++ map (\\i -> ((i, n - 1), -1)) l2 ++ map (\\i -> ((i, n), -1)) l1 ++ map (\\i -> ((i, n), 1)) l2 ++ func (x - 2)\n where\n l1 = [1, 3 .. n - 2]\n l2 = [2, 4 .. n - 2]\n C.putStrLn $ C.pack $ concat $ intersperse \" \" $ map (show . snd) $ sort $ func n\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n let\n func :: Int -> [((Int, Int), Int)]\n func 0 = []\n func 1 = []\n func x\n | odd x = ((n - 1, n), 1) : map (\\i -> ((i, n), 1)) l1 ++ map (\\i -> ((i, n), -1)) l2 ++ map (\\i -> ((i, n - 1), -1)) l1 ++ map (\\i -> ((i, n - 1), 1)) l2 ++ func (x - 2)\n | otherwise = ((n - 1, n), 0) : map (\\i -> ((i, n - 1), 1)) l1 ++ map (\\i -> ((i, n - 1), -1)) l2 ++ map (\\i -> ((i, n), -1)) l1 ++ map (\\i -> ((i, n), 1)) l2 ++ func (x - 2)\n where\n l1 = [1, 3 .. n - 2]\n l2 = [2, 4 .. n - 2]\n C.putStrLn $ C.pack $ concat $ intersperse \" \" $ map (show . snd) $ sort $ func n\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ntype State = (S.Set (Int, Int), [((Int, Int), String)])\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n let\n dfs :: Int -> [Int] -> State -> State\n dfs _ [] p = p\n dfs u (v : vs) p@(visits, results)\n | v == u || S.member e visits = dfs u vs p\n | otherwise = dfs u vs $ dfs v [1..n] (S.insert e visits, (e, r) : results)\n where\n (e, r) = (if u < v then ((u, v), \"1\") else ((v, u), \"-1\"))\n results\n | even n = snd $ dfs 1 [2..n] (S.fromAscList adjs, zip adjs (repeat \"0\"))\n | otherwise = snd $ dfs 1 [2..n] (S.empty, [])\n where\n adjs = map (\\i -> (i, i + 1)) $ filter odd [1..n]\n C.putStrLn $ C.pack $ concat $ intersperse \" \" $ map snd results\n"}], "src_uid": "a89c585ebd9608141399c813385c04c6"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Foldable\r\nimport Data.Monoid\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\nimport Data.Sequence (Seq(Empty, (:<|), (:|>)))\r\nimport qualified Data.Sequence as Seq\r\n\r\n\r\ninvNum xs = if n == 1 then (xs, 0) else merge ls' rs' Seq.empty (accl + accr)\r\n where\r\n n = Seq.length xs\r\n m = n `div` 2\r\n (ls, rs) = Seq.splitAt m xs\r\n (ls', accl) = invNum ls\r\n (rs', accr) = invNum rs\r\n merge Empty Empty xs acc = (xs, acc)\r\n merge Empty (x :<| xss) ys acc = merge Empty xss (ys :|> x) acc\r\n merge (x :<| xss) Empty ys acc = merge xss Empty (ys :|> x) acc\r\n merge p@(l :<| lss) q@(r :<| rss) ys acc =\r\n if l > r then merge lss q (ys :|> l) acc\r\n else merge p rss (ys :|> r) (acc + Seq.length p)\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n as <- listArray (1, m*n) <$> (getInts $ n * m) :: SP (UArray Int Int)\r\n let xs = Seq.fromList $ sortOn ((,)<$>(as!)<*>id) [1..n*m]\r\n ans = getSum $ foldMap (Sum . snd . invNum . Seq.sortOn ((,)<$>(as!)<*>negate)) $ Seq.chunksOf m xs\r\n pure $! putInts [ans]\r\n \r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, m] <- readMany :: IO [Int]\r\n as <- readMany :: IO [Int]\r\n let xss = map (map snd . sortOn (negate . fst) . reverse) $ chunksOf m $ reverse $ sort $ zip as [1 :: Int ..]\r\n f xs = sum [length $ filter ( [a] -> [[a]]\r\nchunksOf n = go where\r\n go [] = []\r\n go xs = xs' : go xs'' where (xs', xs'') = splitAt n xs\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function (on)\nimport Data.List (groupBy, sort)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> showB) >>> C.unlines\n\ndata TC = TC {n :: Int, m :: Int, as :: [Int]}\n\ninput :: Scanner TC\ninput = do\n n <- int\n m <- int\n as <- (n * m) >< int\n return TC {..}\n\nsolve :: TC -> Int\nsolve TC {..} =\n fst\n . foldl update (0, [])\n . map (sort . map snd)\n . groupOn fst\n . sort\n $ zip as [1 ..]\n where\n update (acc, row) ixs = (acc + cost, tetris $ row ++ ixs)\n where\n cixs = take (m - length row) ixs\n cost = sum [countBy (< i) row | i <- cixs]\n\n tetris xs = let l = length xs in drop (l - l `mod` m) xs\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\nimport Data.Function\nimport Data.Int\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n = unfoldr $ \\li -> do\n guard $ not $ null li\n pure $ splitAt n li\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n a <- getInts (n * m)\n let\n aips = sort $ zip a [1..]\n unsrows = chunksOf m aips\n soln row = do\n w <- groupBy ((==) `on` fst) row\n reverse $ map snd w\n rows = map soln unsrows\n cost :: [Int] -> Int64\n cost row = let\n incls = scanl' (flip S.insert) S.empty row\n in foldl' (+) 0 $ do\n (i, s) <- zip row incls\n pure $ fromIntegral $ S.size $ fst $ S.split i s\n pure $ putInt64s [foldl' (\\x y -> x + cost y) 0 rows]\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "99c5e62d8e51e61cfd0c2531a231e7a8"} {"source_code": "-- This is probably still a little too slow.\n-- Let's see if the test data can prove it.\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\n\nimport Control.Monad.ST\n -- I need to re-use a large mutable array to get good complexity\n\nimport Debug.Trace\n\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\np64 :: Int64\np64 = fromIntegral p\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = cv $ x + y\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *! -- Don't make typos in your operator precedence. Or else!\nx *! y = let\n x64 = fromIntegral x\n y64 = fromIntegral y\n in fromIntegral $ x64 * y64 `rem` p64\n\ngetSPFs :: Int -> UArray Int Int\ngetSPFs n = accumArray (const id) 0 (1, n) $ do\n i <- [n, n-1 .. 2]\n j <- [i, 2*i .. n]\n pure (j, i)\n\ngetEulerPhi :: UArray Int Int -> UArray Int Int\ngetEulerPhi spfs = runSTUArray $ do\n let (1, n) = bounds spfs\n ans <- newArray_ (1, n)\n writeArray ans 1 1\n forM_ [2 .. n] $ \\x -> let\n px = spfs ! x\n y = quot x px\n py = spfs ! y\n in do\n prev <- readArray ans y\n writeArray ans x $ prev * if px == py then px else px - 1\n pure ans\n\n\nsolve :: Int -> [Int] -> Int\nsolve n aLi = let\n a :: UArray Int Int\n a = listArray (1, n) aLi\n maxa = foldl' max n $ elems a\n\n spfs = getSPFs maxa\n phi = getEulerPhi spfs\n\n primeList = filter (\\q -> spfs ! q == q) [1 .. maxa] -- another n vs maxa bug\n nPrimes = length primeList\n primes :: UArray Int Int\n primes = listArray (1, nPrimes) primeList\n\n factors :: Array Int (UArray Int Int)\n factors = let\n mkListArr :: [Int] -> UArray Int Int\n mkListArr li = listArray (1, length li) li\n in fmap mkListArr $ accumArray (flip (:)) [] (1, maxa) $ do\n i <- [1 .. maxa]\n j <- [i, 2*i .. maxa]\n pure (j, i)\n\n getFactors :: Int -> [Int]\n getFactors ix = elems $ factors ! ix\n\n incrAt :: STUArray s Int Int -> Int -> Int -> ST s ()\n incrAt arr ix amt = readArray arr ix >>= writeArray arr ix . (+ amt)\n\n insertSmall :: STUArray s Int Int -> [Int] -> ST s [Int]\n insertSmall arr vals = fmap concat $ forM vals $ \\x ->\n flip filterM (getFactors x) $ \\y -> do\n prev <- readArray arr y\n writeArray arr y (prev + 1)\n pure $ prev == 0\n\n insertLarge :: STUArray s Int Int -> [Int] -> ST s [Int]\n insertLarge arr vals = do\n forM_ vals $ \\x -> incrAt arr x 1\n forM_ (elems primes) $ \\q -> do\n let start = quot maxa q -- n vs maxa -- Too subtle for me!\n forM_ [start, start - 1 .. 1] $ \\i -> do\n readArray arr (q * i) >>= incrAt arr i\n pure [1 .. maxa]\n\n in runST $ do\n counts <- newArray (1, maxa) 0 :: ST s (STUArray s Int Int)\n (\\fun -> foldM fun 0 [1 .. n]) $ \\acc1 stride -> acc1 `seq` do\n let\n relas = map (a !) [stride, 2*stride .. n]\n isLarge = quot n stride >= 1000\n relixs <- if isLarge\n then insertLarge counts relas\n else insertSmall counts relas\n --cts <- getAssocs counts\n --traceShow (\"stride\", stride, \"counts\", cts, \"acc1\", acc1) $ pure ()\n newv <- (\\fun -> foldM fun 0 relixs) $ \\acc2 ix -> acc2 `seq` do\n ct <- readArray counts ix\n writeArray counts ix 0\n --traceShow (\"ix\", ix, \"acc2\", acc2, \"ct\", ct) $ pure ()\n pure $ acc2 +! phi ! ix *! ct *! ct\n --traceShow (\"newv\", newv) $ pure ()\n pure $ acc1 +! phi ! stride *! newv\n\nmainFun :: SO\nmainFun = do\n ~[n] <- getInts 1\n aLi <- getInts n\n pure $ putInts [solve n aLi]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "-- Resubmission, to see if 64-bit runtime is any help here, time-wise\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\nimport Data.Array.ST.Safe\r\nimport Data.Int\r\n\r\nimport Control.Monad.ST\r\n -- I need to re-use a large mutable array to get good complexity\r\n\r\nimport Debug.Trace\r\n\r\n\r\np :: Int\r\np = 10 ^ (9 :: Int) + 7\r\n\r\np64 :: Int64\r\np64 = fromIntegral p\r\n\r\ncv :: Int -> Int\r\ncv x = x - if x >= p then p else 0\r\n\r\n(+!) :: Int -> Int -> Int\r\ninfixl 6 +!\r\nx +! y = cv $ x + y\r\n\r\n(*!) :: Int -> Int -> Int\r\ninfixl 7 *! -- Don't make typos in your operator precedence. Or else!\r\nx *! y = let\r\n x64 = fromIntegral x\r\n y64 = fromIntegral y\r\n in fromIntegral $ x64 * y64 `rem` p64\r\n\r\ngetSPFs :: Int -> UArray Int Int\r\ngetSPFs n = accumArray (const id) 0 (1, n) $ do\r\n i <- [n, n-1 .. 2]\r\n j <- [i, 2*i .. n]\r\n pure (j, i)\r\n\r\ngetEulerPhi :: UArray Int Int -> UArray Int Int\r\ngetEulerPhi spfs = runSTUArray $ do\r\n let (1, n) = bounds spfs\r\n ans <- newArray_ (1, n)\r\n writeArray ans 1 1\r\n forM_ [2 .. n] $ \\x -> let\r\n px = spfs ! x\r\n y = quot x px\r\n py = spfs ! y\r\n in do\r\n prev <- readArray ans y\r\n writeArray ans x $ prev * if px == py then px else px - 1\r\n pure ans\r\n\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve n aLi = let\r\n a :: UArray Int Int\r\n a = listArray (1, n) aLi\r\n maxa = foldl' max n $ elems a\r\n\r\n spfs = getSPFs maxa\r\n phi = getEulerPhi spfs\r\n\r\n primeList = filter (\\q -> spfs ! q == q) [1 .. maxa] -- another n vs maxa bug\r\n nPrimes = length primeList\r\n primes :: UArray Int Int\r\n primes = listArray (1, nPrimes) primeList\r\n\r\n factors :: Array Int (UArray Int Int)\r\n factors = let\r\n mkListArr :: [Int] -> UArray Int Int\r\n mkListArr li = listArray (1, length li) li\r\n in fmap mkListArr $ accumArray (flip (:)) [] (1, maxa) $ do\r\n i <- [1 .. maxa]\r\n j <- [i, 2*i .. maxa]\r\n pure (j, i)\r\n\r\n getFactors :: Int -> [Int]\r\n getFactors ix = elems $ factors ! ix\r\n\r\n incrAt :: STUArray s Int Int -> Int -> Int -> ST s ()\r\n incrAt arr ix amt = readArray arr ix >>= writeArray arr ix . (+ amt)\r\n\r\n insertSmall :: STUArray s Int Int -> [Int] -> ST s [Int]\r\n insertSmall arr vals = fmap concat $ forM vals $ \\x ->\r\n flip filterM (getFactors x) $ \\y -> do\r\n prev <- readArray arr y\r\n writeArray arr y (prev + 1)\r\n pure $ prev == 0\r\n\r\n insertLarge :: STUArray s Int Int -> [Int] -> ST s [Int]\r\n insertLarge arr vals = do\r\n forM_ vals $ \\x -> incrAt arr x 1\r\n forM_ (elems primes) $ \\q -> do\r\n let start = quot maxa q -- n vs maxa -- Too subtle for me!\r\n forM_ [start, start - 1 .. 1] $ \\i -> do\r\n readArray arr (q * i) >>= incrAt arr i\r\n pure [1 .. maxa]\r\n\r\n in runST $ do\r\n counts <- newArray (1, maxa) 0 :: ST s (STUArray s Int Int)\r\n (\\fun -> foldM fun 0 [1 .. n]) $ \\acc1 stride -> acc1 `seq` do\r\n let\r\n relas = map (a !) [stride, 2*stride .. n]\r\n isLarge = quot n stride >= 1000\r\n relixs <- if isLarge\r\n then insertLarge counts relas\r\n else insertSmall counts relas\r\n --cts <- getAssocs counts\r\n --traceShow (\"stride\", stride, \"counts\", cts, \"acc1\", acc1) $ pure ()\r\n newv <- (\\fun -> foldM fun 0 relixs) $ \\acc2 ix -> acc2 `seq` do\r\n ct <- readArray counts ix\r\n writeArray counts ix 0\r\n --traceShow (\"ix\", ix, \"acc2\", acc2, \"ct\", ct) $ pure ()\r\n pure $ acc2 +! phi ! ix *! ct *! ct\r\n --traceShow (\"newv\", newv) $ pure ()\r\n pure $ acc1 +! phi ! stride *! newv\r\n\r\nmainFun :: SO\r\nmainFun = do\r\n ~[n] <- getInts 1\r\n aLi <- getInts n\r\n pure $ putInts [solve n aLi]\r\n\r\n\r\ntype SP = State [P.ByteString]\r\ntype SO = SP Builder\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\n\nimport Control.Monad.ST\n -- I need to re-use a large mutable array to get good complexity\n\n--import Debug.Trace\n\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\np64 :: Int64\np64 = fromIntegral p\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = cv $ x + y\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *! -- Don't make typos in your operator precedence. Or else!\nx *! y = let\n x64 = fromIntegral x\n y64 = fromIntegral y\n in fromIntegral $ x64 * y64 `rem` p64\n\ngetSPFs :: Int -> UArray Int Int\ngetSPFs n = accumArray (const id) 0 (1, n) $ do\n i <- [n, n-1 .. 2]\n j <- [i, 2*i .. n]\n pure (j, i)\n\ngetEulerPhi :: UArray Int Int -> UArray Int Int\ngetEulerPhi spfs = runSTUArray $ do\n let (1, n) = bounds spfs\n ans <- newArray_ (1, n)\n writeArray ans 1 1\n forM_ [2 .. n] $ \\x -> let\n px = spfs ! x\n y = quot x px\n py = spfs ! y\n in do\n prev <- readArray ans y\n writeArray ans x $ prev * if px == py then px else px - 1\n pure ans\n\n\nsolve :: Int -> [Int] -> Int\nsolve n aLi = let\n a :: UArray Int Int\n a = listArray (1, n) aLi\n maxa = foldl' max n $ elems a\n\n spfs = getSPFs maxa\n phi = getEulerPhi spfs\n\n primeList = filter (\\q -> spfs ! q == q) [1 .. n]\n nPrimes = length primeList\n primes :: UArray Int Int\n primes = listArray (1, nPrimes) primeList\n\n getPrimeFactors :: Int -> [Int]\n getPrimeFactors 1 = []\n getPrimeFactors x = let\n px = spfs ! x\n in px : getPrimeFactors (quot x px)\n\n getFactors :: Int -> [Int]\n getFactors x = let\n opts = map (scanl' (*) 1) $ group $ getPrimeFactors x\n in foldr (liftM2 (*)) [1] opts\n\n incrAt :: STUArray s Int Int -> Int -> Int -> ST s ()\n incrAt arr ix amt = readArray arr ix >>= writeArray arr ix . (+ amt)\n\n insertSmall :: STUArray s Int Int -> [Int] -> ST s ()\n insertSmall arr vals = forM_ vals $ \\x ->\n forM_ (getFactors x) $ \\y -> incrAt arr y 1\n\n insertLarge :: STUArray s Int Int -> [Int] -> ST s ()\n insertLarge arr vals = do\n forM_ vals $ \\x -> incrAt arr x 1\n forM_ (elems primes) $ \\q -> do\n let start = quot maxa q -- n vs maxa -- Too subtle for me!\n forM_ [start, start - 1 .. 1] $ \\i ->\n readArray arr (q * i) >>= incrAt arr i\n\n in runST $ do\n counts <- newArray (1, maxa) 0 :: ST s (STUArray s Int Int)\n (\\fun -> foldM fun 0 [1 .. n]) $ \\acc1 stride -> acc1 `seq` do\n let\n relas = map (a !) [stride, 2*stride .. n]\n isLarge = quot n stride >= 1000\n relixs = if isLarge\n then [1 .. maxa]\n else concatMap getFactors relas\n if isLarge\n then insertLarge counts relas\n else insertSmall counts relas\n --cts <- getAssocs counts\n --traceShow (\"stride\", stride, \"counts\", cts, \"acc1\", acc1) $ pure ()\n newv <- (\\fun -> foldM fun 0 relixs) $ \\acc2 ix -> acc2 `seq` do\n ct <- readArray counts ix\n writeArray counts ix 0\n --traceShow (\"ix\", ix, \"acc2\", acc2, \"ct\", ct) $ pure ()\n pure $ acc2 +! phi ! ix *! ct *! ct\n --traceShow (\"newv\", newv) $ pure ()\n pure $ acc1 +! phi ! stride *! newv\n\nmainFun :: SO\nmainFun = do\n ~[n] <- getInts 1\n aLi <- getInts n\n pure $ putInts [solve n aLi]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\n\nimport Control.Monad.ST\n -- I need to re-use a large mutable array to get good complexity\n\n--import Debug.Trace\n\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\np64 :: Int64\np64 = fromIntegral p\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = cv $ x + y\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *! -- Don't make typos in your operator precedence. Or else!\nx *! y = let\n x64 = fromIntegral x\n y64 = fromIntegral y\n in fromIntegral $ x64 * y64 `rem` p64\n\ngetSPFs :: Int -> UArray Int Int\ngetSPFs n = accumArray (const id) 0 (1, n) $ do\n i <- [n, n-1 .. 2]\n j <- [i, 2*i .. n]\n pure (j, i)\n\ngetEulerPhi :: UArray Int Int -> UArray Int Int\ngetEulerPhi spfs = runSTUArray $ do\n let (1, n) = bounds spfs\n ans <- newArray_ (1, n)\n writeArray ans 1 1\n forM_ [2 .. n] $ \\x -> let\n px = spfs ! x\n y = quot x px\n py = spfs ! y\n in do\n prev <- readArray ans y\n writeArray ans x $ prev * if px == py then px else px - 1\n pure ans\n\n\nsolve :: Int -> [Int] -> Int\nsolve n aLi = let\n a :: UArray Int Int\n a = listArray (1, n) aLi\n maxa = foldl' max n $ elems a\n\n spfs = getSPFs maxa\n phi = getEulerPhi spfs\n\n primeList = filter (\\q -> spfs ! q == q) [1 .. n]\n nPrimes = length primeList\n primes :: UArray Int Int\n primes = listArray (1, nPrimes) primeList\n\n getPrimeFactors :: Int -> [Int]\n getPrimeFactors 1 = []\n getPrimeFactors x = let\n px = spfs ! x\n in px : getPrimeFactors (quot x px)\n\n getFactors :: Int -> [Int]\n getFactors x = let\n opts = map (scanl' (*) 1) $ group $ getPrimeFactors x\n in foldr (liftM2 (*)) [1] opts\n\n incrAt :: STUArray s Int Int -> Int -> Int -> ST s ()\n incrAt arr ix amt = readArray arr ix >>= writeArray arr ix . (+ amt)\n\n insertSmall :: STUArray s Int Int -> [Int] -> ST s ()\n insertSmall arr vals = forM_ vals $ \\x ->\n forM_ (getFactors x) $ \\y -> incrAt arr y 1\n\n insertLarge :: STUArray s Int Int -> [Int] -> ST s ()\n insertLarge arr vals = do\n forM_ vals $ \\x -> incrAt arr x 1\n forM_ (elems primes) $ \\q -> do\n let start = quot n q\n forM_ [start, start - 1 .. 1] $ \\i ->\n readArray arr (q * i) >>= incrAt arr i\n\n in runST $ do\n counts <- newArray (1, maxa) 0 :: ST s (STUArray s Int Int)\n (\\fun -> foldM fun 0 [1 .. n]) $ \\acc1 stride -> acc1 `seq` do\n let\n relas = map (a !) [stride, 2*stride .. n]\n isLarge = quot n stride >= 1000\n relixs = if isLarge\n then [1 .. maxa]\n else concatMap getFactors relas\n if isLarge\n then insertLarge counts relas\n else insertSmall counts relas\n cts <- getAssocs counts\n --traceShow (\"stride\", stride, \"counts\", cts, \"acc1\", acc1) $ pure ()\n newv <- (\\fun -> foldM fun 0 relixs) $ \\acc2 ix -> acc2 `seq` do\n ct <- readArray counts ix\n writeArray counts ix 0\n --traceShow (\"ix\", ix, \"acc2\", acc2, \"ct\", ct) $ pure ()\n pure $ acc2 +! phi ! ix *! ct *! ct\n --traceShow (\"newv\", newv) $ pure ()\n pure $ acc1 +! phi ! stride *! newv\n\nmainFun :: SO\nmainFun = do\n ~[n] <- getInts 1\n aLi <- getInts n\n pure $ putInts [solve n aLi]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "a63f7416aa94f8a3f58d2a8fea636cac"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n count \"1\" = 0\n count ('0':s) = 1 + count s\n count s = length s1 + 1 + count (if null s2 then \"1\" else '1':tail s2)\n where\n (s1, s2) = span (== '1') s\n\n print $ count $ reverse s\n \n", "positive_code": [{"source_code": "-- binares\n\nsolve ('1':[]) pl1 akk = akk+pl1 \nsolve ('0':xs) pl1 akk = solve xs pl1 (akk+(1+pl1))\nsolve ('1':xs) pl1 akk = solve xs 1 (akk + (2-pl1))\n\nmain = do\n\t\t\tnum <- getLine\n\t\t\tprint $ solve (reverse num) 0 0\n"}, {"source_code": "import Debug.Trace\n\nsolve :: [Int] -> Int\nsolve x = solve' (reverse x) 0\n where\n solve' [1] 0 = 0\n solve' [1] 1 = 1\n solve' (x:xs) c =\n case (x + c) of\n 0 -> 1 + (solve' xs 0)\n 1 -> 2 + (solve' xs 1)\n 2 -> 1 + (solve' xs 1)\n\nsolver :: String -> String\nsolver str = show $ solve $ map (\\x -> if x == '0' then 0 else 1) ((lines str) !! 0)\n\nmain :: IO ()\nmain = interact solver\n"}, {"source_code": "\nimport List (group)\n\nsolve :: String -> Int\nsolve = solve' 0 . group . reverse\n where\n solve' acc [x]\n | length x == 1 = acc\n | otherwise = acc + 1 + length x\n solve' acc [x,y] = solve' (acc + length x) [y]\n solve' acc (x:y:z:xs)\n | head x == '0' = solve' (acc + length x) (y:z:xs)\n | otherwise = solve' (acc + 2 * length y + length x - 1) (('1':z):xs)\n\nmain :: IO ()\nmain = getLine >>= print . solve\n"}, {"source_code": "countzero [] n = n\ncountzero ('0':xs) n = countzero xs (n+1)\ncountzero ('1':xs) n = countzero xs n\n\nsolve digits = let digits' = dropWhile (=='0') digits\n in\n if digits' == \"1\" then\n (length digits) -1\n else\n (length digits)+1+(countzero digits' 0)\n\nmain = getLine>>=print.solve.reverse"}, {"source_code": "import qualified Data.Char as C\n\nsolve :: [Int] -> Int\nsolve = loop 0\n \nloop acc [1] = acc\nloop acc [0] = acc + 1\nloop acc (0:foo) = loop (acc + 1) foo\nloop acc foo@(1:_) = loop' (acc + 1) foo\n\nloop' acc (1:foo) = loop' (1 + acc) foo\nloop' acc (0:foo) = loop acc (1:foo)\nloop' acc [] = loop acc [1]\n\n\n \n\nparse :: String -> [Int]\nparse = reverse . map C.digitToInt . filter (/= '\\n')\n\nmain = interact (show . solve . parse)"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n s <- reverse `liftM` getLine\n\n let trailZero = length $ takeWhile (=='0') s\n s' = drop trailZero s\n res = trailZero + if null $ tail s'\n then 0\n else length ( filter (=='0') s' ) + length s' + 1\n\n putStrLn $ show res\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.Char\n\nmain = do\n\tinput <- fmap (C.takeWhile (/='\\r') . head . C.lines) $ C.hGetContents stdin\n\tlet n = C.length input\n\tlet z = C.count '0' input\n\tlet o = C.count '1' input\n\tputStrLn . show $ n + z + 1 - (fromJust . C.elemIndex '1' . C.reverse) input - if o == 1 then 2 else 0\n"}, {"source_code": "import Data.Char\n\nmain = do\n\ts <- getLine\n\tlet a = map digitToInt $ reverse s\n\tprint $ solve a 0\n\nsolve [1] c \t = c\nsolve (x:xs) c\n\t| x == c = 1 + (solve xs c)\n\t| otherwise = 2 + (solve xs 1)\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.Char\n\nmain = do\n\tinput <- fmap (head . C.lines) $ C.hGetContents stdin\n\tlet z = C.count '0' input\n\tlet o = C.count '1' input\n\tlet n = z + o\n\tputStrLn . show $ n + z + 1 - (fromJust . C.elemIndex '1' . C.reverse) input - if o == 1 then 2 else 0\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nmain = do\n\tinput <- fmap (head . C.lines) $ C.hGetContents stdin\n\tlet n = C.length input\n\tlet z = C.count '0' input\n\tprint n\n\tprint z\n\tputStrLn . show $ n + z + 1 - (fromJust . C.elemIndex '1' . C.reverse) input - if n - z == 1 then 2 else 0\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nmain = do\n\tinput <- fmap (head . C.lines) $ C.hGetContents stdin\n\tlet n = C.length input\n\tlet z = C.count '0' input\n\tputStrLn . show $ n + z + 1 - (fromJust . C.elemIndex '1' . C.reverse) input - if n - z == 1 then 2 else 0\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.Char\n\nmain = do\n\tinput <- fmap (head . C.lines) $ C.hGetContents stdin\n\tlet n = C.length input\n\tlet z = C.count '0' input\n\tprint $ ord $ C.index input 1\n\tputStrLn . show $ n + z + 1 - (fromJust . C.elemIndex '1' . C.reverse) input - if n - z == 1 then 2 else 0\n"}, {"source_code": "-- binares\n\nsolve ('1':[]) pl1 akk = if (pl1 == 0) then akk else akk+1 \nsolve ('0':xs) pl1 akk = if (pl1 == 0) then solve xs pl1 (akk+1) else solve ('1':xs) (pl1-1) (akk+1)\nsolve ('1':xs) pl1 akk = if (pl1 == 1) then solve xs (pl1-1) (akk + 1) else solve xs (pl1+1) (akk+2)\n\nmain = do\n\t\t\tnum <- getLine\n\t\t\tprint $ solve (reverse num) 0 0\n"}, {"source_code": "import Data.Char\n\nbToD [] n = n\nbToD (x:xs) n = bToD xs (n*2+(ord x - ord '0'))\n\n\n\nsolve n = rec (bToD n 0) 0\n where\n rec x n |x<8 = ([0,0,1,3,2,5,4,4]!!x)+n\n |otherwise = case mod x 8 of\n 0 -> rec (div x 8) (n+3)\n 1 -> rec ((div x 8)+1) (n+6)\n 2 -> rec ((div x 8)+1) (n+5)\n 3 -> rec ((div x 8)+1) (n+5)\n 4 -> rec ((div x 8)+2) (n+5)\n 5 -> rec ((div x 8)+2) (n+6)\n 6 -> rec ((div x 8)+2) (n+5)\n 7 -> rec ((div x 8)+1) (n+4)\n\nmain = getLine>>=print.solve"}, {"source_code": "import Data.Char\n\nbToD [] n = n\nbToD (x:xs) n = bToD xs (n*2+(ord x - ord '0'))\n\n\n\nsolve n = rec (bToD n 0) 0\n where\n rec x n |x<8 = ([0,0,1,3,2,5,4,4]!!x)+n\n |otherwise = case mod x 8 of\n 0 -> rec (div x 8) (n+3)\n 1 -> rec ((div x 8)+1) (n+6)\n 2 -> rec ((div x 8)+1) (n+5)\n 3 -> rec ((div x 8)+1) (n+5)\n 4 -> rec ((div x 8)+2) (n+5)\n 5 -> rec ((div x 8)+2) (n+6)\n 6 -> rec ((div x 8)+1) (n+4)\n 7 -> rec ((div x 8)+1) (n+4)\nmain = getLine>>=print.solve"}], "src_uid": "e46c6406d19e8679fd282d72882ae78d"} {"source_code": "import Data.Functor\n\ntype Pos = (Double, Double)\n\ndistance :: Pos -> Pos -> Double\ndistance (x1, y1) (x2, y2) = sqrt $ (x2 - x1) ^ 2 + (y2 - y1) ^ 2\n\ntrd :: (a, b, c) -> c\ntrd (_, _, c) = c\n\nmain = do\n n:vb:vs:_ <- map read . words <$> getLine\n poss <- tail . map read . words <$> getLine\n xu:yu:_ <- map read . words <$> getLine\n let step (i, xs) x = (i + 1, f i x : xs)\n f i x = ((distance (xu, yu) (x, 0)) / vs + x / vb\n , distance (xu, yu) (x, 0), i)\n shortest = minimum $ snd $ foldl step (2, []) poss\n print $ trd shortest\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype Time = Double\ntype Distance = Double\ntype Estimatation = (Distance, Time)\n\nconv :: Double -> Double -> (Double, Double) -> [Time] -> [Estimatation]\nconv vb vs univ@(ux, uy) = do\n let distance sx = sqrt $ (ux - sx) ^ 2 + uy ^ 2\n let time (d, sx) = (d, sx / vb + d / vs)\n map (time . (distance >>= (,)))\n\ncheck :: [Estimatation] -> String\ncheck = do\n let epsilon = 1e-9\n let f (_, (d1, t1)) (_, (d2, t2))\n | abs (t2 - t1) <= epsilon = compare d1 d2\n | otherwise = compare t1 t2\n \n (idx, _) <- minimumBy f . drop 1 . zip [1 ..]\n return $ show idx\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n let toDoubles = map read . words . head\n [vb, vs] <- drop 1 . toDoubles\n ts <- toDoubles . drop 1\n [ux, uy] <- toDoubles . drop 2\n let es = conv vb vs (ux, uy) ts\n return $ check es\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Monoid\nimport Data.Ord\n\ndouble = read :: String -> Double\ndoubles = map double . words <$> getLine\ndist x y b = sqrt $ ( b - x) **2 + y**2\nmain = do\n [[n,vb,vs],bs,[x,y]] <- replicateM 3 doubles\n print $ fst $ head $ sortBy (comparing snd `mappend` flip (comparing fst) ) $ zip [2..] $ map (\\z -> z/vb + (dist x y z)/vs ) $ tail bs\n \n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\ntype I = Integer\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: (Floating d, Ord d) => d -> d -> (d, d) -> [d] -> Int\nsolve vs vb (xu, yu) xs = solve' $ tail $ zip [1..] xs\n where\n solve' [(ni, xi)] = ni\n solve' ((ni, xi) : (nj, xj) : xs)\n | (xj - xi) / vs + sqrt ((xu - xj)^2 + yu^2) / vb <= sqrt ((xu - xi)^2 + yu^2) / vb\n = solve' ((nj, xj) : xs)\n | otherwise = ni\n\nmain :: IO ()\nmain = do\n [n, vs, vb] <- reads\n xs <- reads\n [xu, yu] <- reads\n print $ solve vs vb (xu, yu) xs\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ndouble = read :: String -> Double\ndoubles = map double . words <$> getLine\ndist x y b = sqrt $ ( b - x) **2 + y**2\nmain = do\n [[n,vb,vs],bs,[x,y]] <- replicateM 3 doubles\n print $ fst $ head $ sortOn snd $ zip [2..] $ map (\\z -> z/vb + (dist x y z)/vs ) $ tail bs\n \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ndouble = read :: String -> Double\ndoubles = map double . words <$> getLine\ndist x y b = sqrt $ ( b - x) **2 + y**2\nmain = do\n [[n,vb,vs],bs,[x,y]] <- replicateM 3 doubles\n print $ fst $ head $ sortOn snd $ zip [2..] $ map (\\z -> z/vb + dist x y z ) $ tail bs\n \n"}, {"source_code": "import Data.Functor\n\ntype Pos = (Double, Double)\n\ndistance :: Pos -> Pos -> Double\ndistance (x1, y1) (x2, y2) = (x2 - x1) ^ 2 + (y2 - y1) ^ 2\n\ntrd :: (a, b, c) -> c\ntrd (_, _, c) = c\n\nmain = do\n n:vb:vs:_ <- map read . words <$> getLine\n poss <- map read . words <$> getLine\n xu:yu:_ <- map read . words <$> getLine\n let step (i, xs) x = (i + 1, f i x : xs)\n f i x = ((distance (xu, yu) (x, 0)) / vs + x / vb\n , distance (xu, yu) (x, 0), i)\n shortest = minimum $ snd $ foldl step (1, []) poss\n print $ trd shortest\n where\n\n"}, {"source_code": "import Data.Functor\n\ntype Pos = (Double, Double)\n\ndistance :: Pos -> Pos -> Double\ndistance (x1, y1) (x2, y2) = (x2 - x1) ^ 2 + (y2 - y1) ^ 2\n\ntrd :: (a, b, c) -> c\ntrd (_, _, c) = c\n\nmain = do\n n:vb:vs:_ <- map read . words <$> getLine\n poss <- map read . words <$> getLine\n xu:yu:_ <- map read . words <$> getLine\n let step (i, xs) x = (i + 1, f i x : xs)\n f i x = ((distance (xu, yu) (x, 0)) / vs + x / vb, - x, i)\n shortest = minimum $ snd $ foldl step (1, []) poss\n print $ trd shortest\n where\n\n"}, {"source_code": "import Data.Functor\n\ntype Pos = (Double, Double)\n\ndistance :: Pos -> Pos -> Double\ndistance (x1, y1) (x2, y2) = sqrt $ (x2 - x1) ^ 2 + (y2 - y1) ^ 2\n\ntrd :: (a, b, c) -> c\ntrd (_, _, c) = c\n\nmain = do\n n:vb:vs:_ <- map read . words <$> getLine\n poss <- map read . words <$> getLine\n xu:yu:_ <- map read . words <$> getLine\n let step (i, xs) x = (i + 1, f i x : xs)\n f i x = ((distance (xu, yu) (x, 0)) / vs + x / vb\n , distance (xu, yu) (x, 0), i)\n shortest = minimum $ snd $ foldl step (1, []) poss\n print $ trd shortest\n"}], "src_uid": "15fa49860e978d3b3fb7a20bf9f8aa86"} {"source_code": "import Control.Monad (forM_)\nimport qualified Data.Map as M (fromList, lookup)\nimport qualified Data.Sequence as S (fromList, lookup)\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain = do \n [n, q] <- pure . map read . words =<< getLine\n dct <- pure . M.fromList $ zip ['a'..'z'] [1..]\n arr <- pure . S.fromList\n . (0 :) . scanl1 (+) . fromMaybe [] \n . sequence . map (flip M.lookup dct) \n =<< getLine\n forM_ [1..q] $ \\_ -> do\n [l, r] <- pure . map read . words =<< getLine\n [t, b] <- pure . fromMaybe [0, 0] . sequence \n $ [S.lookup r arr, S.lookup (l - 1) $ arr]\n putStrLn . show $ t - b\n\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Array\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult s n = do\r\n [l,r] <- readInts\r\n let\r\n a = listArray (0,n-1) $ map (\\x -> ord x - 96) s\r\n b = array (0,n) ((0,0):[(i,a!(i-1)+b!(i-1))|i<-[1..n]])\r\n print $ b ! r - b ! (l-1) \r\n \r\nmain = do\r\n [n,q] <- readInts\r\n s <- getLine\r\n replicateM_ q $ printResult s n"}], "negative_code": [], "src_uid": "461378e9179c9de454674ea9dc49c56c"} {"source_code": "{-# LANGUAGE NamedFieldPuns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.Foldable as F\n\nimport qualified Data.Set as Set\nimport Data.Set (Set)\n\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ndata Machine = Machine {\n mI :: (Int, Int)\n ,mN :: Int\n ,mT0 :: Int\n ,mT1 :: Int\n} deriving (Eq, Show)\n\nnewtype Start = Start { unStart :: Machine } deriving (Eq, Show)\ninstance Ord Start where\n compare a b = compare (aT, aI) (bT, bI)\n where\n Machine {mI = aI, mT0 = aT} = unStart a\n Machine {mI = bI, mT0 = bT} = unStart b\n\nnewtype End = End { unEnd :: Machine } deriving (Eq, Show)\ninstance Ord End where\n compare a b = compare (aT, aI) (bT, bI)\n where\n Machine {mI = aI, mT1 = aT} = unEnd a\n Machine {mI = bI, mT1 = bT} = unEnd b\n\ndata Cadre = Cadre {\n cN :: Int\n ,cT :: Int\n ,cF :: Set Start\n ,cL :: Set End\n} deriving (Eq, Show)\n\nmkCadre :: Int -> Int -> Int -> Cadre\nmkCadre cI n t = Cadre {\n cN = n\n ,cT = t\n ,cF = Set.empty\n ,cL = Set.fromList [End $ Machine {\n mI = (cI, i)\n ,mN = 0\n ,mT0 = 0\n ,mT1 = 0\n } | i <- [0..n-1]]\n}\n\ndata Laundromat = Laundromat Int (Seq Cadre) deriving (Eq, Show)\n\nmkLaundromat :: Int -> [Int] -> [Int] -> Laundromat\nmkLaundromat k ns ts =\n Laundromat 0 . (!! k) . iterate (Seq.adjust (inc 0) 0) . Seq.fromList $ zipWith3 mkCadre [0..] ns ts\n\nmain = do\n [k, n0, n1, n2, t0, t1, t2] <- fmap (map read . words) getLine\n putStrLn . show . run $ mkLaundromat k [n0, n1, n2] [t0, t1, t2]\n\nrun :: Laundromat -> Int\nrun l = case step l of\n Left t -> t\n Right l -> run l\n\nnext :: Seq Cadre -> Maybe Machine\nnext = fmap unStart . F.foldl' proc Nothing\n where\n proc Nothing c = start c\n proc (Just a) c = case start c of\n Nothing -> Just a\n Just b -> Just $ min a b\n\nstep :: Laundromat -> Either Int Laundromat\nstep (Laundromat t0 c0) = case next c0 of\n Nothing ->\n Left t0\n Just m@(Machine {mI = (cI, _), mT0}) ->\n let\n c = Seq.adjust (dec m) cI c0\n c1 = if cI+1 == Seq.length c then c else Seq.adjust (inc mT0) (cI+1) c\n in Right $ Laundromat mT0 c1\n\ndec :: Machine -> Cadre -> Cadre\ndec m0 c@(Cadre {cT}) = add m $ rm m0 c\n where\n m = case m0 of\n Machine {mN = 1} ->\n m0 {mN = 0, mT0 = 0, mT1 = 0}\n Machine {mN, mT0} ->\n m0 {mN = mN-1, mT0 = mT0+cT}\n\ninc :: Int -> Cadre -> Cadre\ninc t c@(Cadre {cT}) =add m $ rm m0 c\n where\n m0 = unEnd $ end c\n m = case m0 of\n Machine {mN = 0} ->\n m0 {mN = 1, mT0 = t+cT, mT1 = t+cT}\n Machine {mN, mT1} ->\n m0 {mN = mN+1, mT1 = mT1+cT}\n\nstart :: Cadre -> Maybe Start\nstart (Cadre {cF}) = if Set.null cF then Nothing else Just $ Set.findMin cF\n\nend :: Cadre -> End\nend = Set.findMin . cL\n\nrm :: Machine -> Cadre -> Cadre\nrm m c@(Cadre {cF, cL}) = c {cF = Set.delete (Start m) cF, cL = Set.delete (End m) cL}\n\nadd :: Machine -> Cadre -> Cadre\nadd m@(Machine {mN}) c@(Cadre {cF, cL}) = c {cF = f, cL = Set.insert (End m) cL}\n where f = if mN == 0 then cF else Set.insert (Start m) cF\n", "positive_code": [{"source_code": "{-# LANGUAGE NamedFieldPuns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, ViewL(..), ViewR(..), (|>))\n\ndata Cadre = Cadre {\n dt :: Int\n ,ts :: Seq Int\n}\n\ntype Laundromat = [Cadre]\n\nmkLaundromat :: [Int] -> [Int] -> Laundromat\nmkLaundromat = zipWith $ \\n t -> Cadre {dt = t, ts = Seq.replicate n 0}\n\nmain = do\n [k, n0, n1, n2, t0, t1, t2] <- fmap (map read . words) getLine\n putStrLn . show . run k $ mkLaundromat [n0, n1, n2] [t0, t1, t2]\n\nrun :: Int -> Laundromat -> Int\nrun k cs = t\n where _ :> t = Seq.viewr . ts . last $ iterate step cs !! k\n\nstep :: Laundromat -> Laundromat\nstep cs = snd $ T.mapAccumL rot nextT cs\n where\n rot t c@(Cadre {dt, ts = ts0}) = (t + dt, c {ts = ts |> (t + dt)})\n where _ :< ts = Seq.viewl ts0\n nextT = fst $ F.foldl accT (0, 0) cs\n accT (t0, dt0) (Cadre {dt, ts}) = (max t0 (t - dt0), dt0 + dt)\n where t :< _ = Seq.viewl ts\n"}], "negative_code": [{"source_code": "{-# LANGUAGE NamedFieldPuns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.Foldable as F\n\nimport qualified Data.Set as Set\nimport Data.Set (Set)\n\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ndata Machine = Machine {\n mI :: (Int, Int)\n ,mT :: Int\n ,mN :: Int\n ,mT0 :: Int\n ,mT1 :: Int\n} deriving (Eq, Show)\n\nnewtype Start = Start { unStart :: Machine } deriving (Eq, Show)\ninstance Ord Start where\n compare a b = compare (aT, aI) (bT, bI)\n where\n Machine {mI = aI, mT0 = aT} = unStart a\n Machine {mI = bI, mT0 = bT} = unStart b\n\nnewtype End = End { unEnd :: Machine } deriving (Eq, Show)\ninstance Ord End where\n compare a b = compare (aT, aI) (bT, bI)\n where\n Machine {mI = aI, mT1 = aT} = unEnd a\n Machine {mI = bI, mT1 = bT} = unEnd b\n\ndata Cadre = Cadre {\n cN :: Int\n ,cT :: Int\n ,cF :: Set Start\n ,cL :: Set End\n} deriving (Eq, Show)\n\nmkCadre :: Int -> Int -> Int -> Cadre\nmkCadre cI n t = Cadre {\n cN = n\n ,cT = t\n ,cF = Set.empty\n ,cL = Set.fromList [End $ Machine {\n mI = (cI, i)\n ,mT = t\n ,mN = 0\n ,mT0 = 0\n ,mT1 = 0\n } | i <- [0..n-1]]\n}\n\ndata Laundromat = Laundromat Int (Seq Cadre) deriving (Eq, Show)\n\nmkLaundromat :: Int -> [Int] -> [Int] -> Laundromat\nmkLaundromat k ns ts =\n Laundromat 0 . (!! k) . iterate (Seq.adjust (inc 0) 0) . Seq.fromList $ zipWith3 mkCadre [0..] ns ts\n\nmain = do\n [k, n0, n1, n2, t0, t1, t2] <- fmap (map read . words) getLine\n putStrLn . show . run $ mkLaundromat k [n0, n1, n2] [t0, t1, t2]\n\nrun :: Laundromat -> Int\nrun l = case step l of\n Left t -> t\n Right l -> run l\n\nnext :: Seq Cadre -> Maybe Machine\nnext = fmap unStart . F.foldl' proc Nothing\n where\n proc Nothing c = start c\n proc (Just a) c = case start c of\n Nothing -> Just a\n Just b -> Just $ min a b\n\nstep :: Laundromat -> Either Int Laundromat\nstep (Laundromat t0 c0) = case next c0 of\n Nothing ->\n Left t0\n Just m@(Machine {mI = (cI, _), mT0}) ->\n let\n c = Seq.adjust (dec m) cI c0\n c1 = if cI+1 == Seq.length c then c else Seq.adjust (inc mT0) (cI+1) c\n in Right $ Laundromat mT0 c1\n\ndec :: Machine -> Cadre -> Cadre\ndec m0 = add m . rm m0\n where m = case m0 of\n Machine {mN = 1} ->\n m0 {mN = 0, mT0 = 0, mT1 = 0}\n Machine {mT, mN, mT0} ->\n m0 {mN = mN-1, mT0 = mT0+mT}\n\ninc :: Int -> Cadre -> Cadre\ninc t c =\n let m@(Machine {mT, mN, mT0, mT1}) = unEnd $ end c\n in add (m {mN = mN+1, mT0 = if mN == 0 then t+mT else mT0, mT1 = mT1+mT}) $ rm m c\n\nstart :: Cadre -> Maybe Start\nstart (Cadre {cF}) = if Set.null cF then Nothing else Just $ Set.findMin cF\n\nend :: Cadre -> End\nend = Set.findMin . cL\n\nrm :: Machine -> Cadre -> Cadre\nrm m c@(Cadre {cF, cL}) = c {cF = Set.delete (Start m) cF, cL = Set.delete (End m) cL}\n\nadd :: Machine -> Cadre -> Cadre\nadd m@(Machine {mN}) c@(Cadre {cF, cL}) = c {cF = f, cL = Set.insert (End m) cL}\n where f = if mN == 0 then cF else Set.insert (Start m) cF\n"}, {"source_code": "{-# LANGUAGE NamedFieldPuns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, ViewL(..), ViewR(..), (|>))\n\ndata Cadre = Cadre {\n dt :: Int\n ,ts :: Seq Int\n}\n\ntype Laundromat = [Cadre]\n\nmkLaundromat :: [Int] -> [Int] -> Laundromat\nmkLaundromat = zipWith $ \\n t -> Cadre {dt = t, ts = Seq.replicate n 0}\n\nmain = do\n [k, n0, n1, n2, t0, t1, t2] <- fmap (map read . words) getLine\n putStrLn . show . run k $ mkLaundromat [n0, n1, n2] [t0, t1, t2]\n\nrun :: Int -> Laundromat -> Int\nrun k cs = t\n where _ :> t = Seq.viewr . ts . last $ iterate step cs !! k\n\nstep :: Laundromat -> Laundromat\nstep cs = snd $ T.mapAccumL rot nextT cs\n where\n rot t c@(Cadre {dt, ts = ts0}) = (t + dt, c {ts = ts |> (t + dt)})\n where _ :< ts = Seq.viewl ts0\n nextT = fst $ F.foldl accT (0, 0) cs\n accT (t0, dt0) (Cadre {dt, ts}) = (max t0 (t - dt0 - dt), dt0 + dt)\n where t :< _ = Seq.viewl ts\n"}], "src_uid": "dd1d166772ee06b383d4ceb94b530fd1"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns\n\nsolve :: Int -> [Int] -> Int\nsolve 1 _ = 1\nsolve 2 _ = 2\nsolve n ns = \n let arr = listArray (0, n-1) ns\n res = foldl (\\(m, b) i -> \n if arr ! i == i\n then (m + 1, b)\n else (m, b || arr ! (arr ! i) == i)\n ) (0, False) [0 .. n-1]\n in case res of\n (m, False) -> min n (m + 1)\n (m, _) -> m + 2", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns\n\nsolve :: Int -> [Int] -> Int\nsolve 1 _ = 1\nsolve 2 _ = 2\nsolve n ns = \n let arr = listArray (0, n-1) ns\n res = foldr (\\i (m, b) -> \n if arr ! i == i\n then (m + 1, b)\n else (m, b || arr ! (arr ! i) == i)\n ) (0, False) [0 .. n-1]\n in case res of\n (m, False) -> min n (m + 1)\n (m, _) -> m + 2"}, {"source_code": "main = do\n input <- getLine\n let n = read (input) :: Int\n input <- getLine\n let input' = zip [0..] (f $ split ' ' input)\n let orig = sum [ 1 | (a, b) <- input', a == b ]\n let swap = qsort [ (b, a) | (a, b) <- input' ]\n let count = sum [ 1 | ((a, b), (c, d)) <- (zip input' swap), b == d ]\n \n print (if orig == n then orig else (if orig < count then orig + 2 else orig + 1)) \n\n\nf :: [String] -> [Int]\nf x = map read x\n\nqsort :: (Ord a) => [a] -> [a]\nqsort [] = []\nqsort (x:xs) = qsort [ a | a <- xs, a <= x ] ++ [x] ++ qsort [ a | a <- xs, a > x ]\n\nsplit' :: (Eq a) => a -> [a] -> [a] -> [[a]]\nsplit' _ [] l = [l]\nsplit' v (x:xs) l\n | x /= v = split' v xs (l ++ [x])\n | otherwise = [l] ++ split' v xs []\n\nsplit :: (Eq a) => a -> [a] -> [[a]]\nsplit v xs = split' v xs []\n"}, {"source_code": "import Control.Monad (liftM, unless, when)\nimport Data.List (group, intercalate, sort)\nimport Data.Array\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n n <- getLine\n vals <- reads\n putStrLn $ show $ solve (read n) vals\n\nfoldla :: (b -> Int -> a -> b) -> b -> Array Int a -> b\nfoldla f z0 ar = go z0 lo\n where go z i\n | i > hi = z\n | otherwise = go (f z i (ar ! i)) $ i + 1\n (lo, hi) = bounds ar\n\nsamePos :: Array Int Int -> Int\nsamePos a = foldla (\\acc idx val -> if idx == val then acc + 1 else acc) 0 a\n\nimprovement :: Array Int Int -> Int\nimprovement perm\n = foldla (\\best idx val -> if idx == val then best\n else if perm ! val == idx then 2\n else max 1 best) 0 perm\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = (samePos perm) + (improvement perm)\n where\n dim = (0, n - 1)\n perm = array dim $ zip (range dim) xs\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), bounds, listArray)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve xs = min n (k + l)\n where\n n = length xs\n a = listArray (0, n-1) xs\n k = length [0 | i <- [0 .. n-1], i == a ! i]\n l = if null [0 | i <- [0 .. n-1], i /= a ! i, i == a ! (a ! i)]\n then 1 else 2\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve"}, {"source_code": "import Data.IntMap (IntMap, (!), foldlWithKey, fromList)\n\nboolToInt :: Bool -> Integer\nboolToInt True = 1\nboolToInt False = 0\n\nstationaryCount :: IntMap Int -> Integer\nstationaryCount = foldlWithKey (\\z k x -> z + (boolToInt (k == x))) 0\n\nhasTransp :: IntMap Int -> Bool\nhasTransp perm = foldlWithKey (\\z k x -> z || ((k /= x) && (perm ! x == k))) False perm\n\nsolve :: Integer -> [Int] -> Integer\nsolve n xs = case (hasTransp xs') of\n True -> s + 2\n False -> s + (boolToInt $ n - s > 1)\n where xs' = fromList $ zip [0..] xs\n s = stationaryCount xs'\nmain = do \n [n] <- (map (read :: String -> Integer) . words) `fmap` getLine\n seq <- (map (read :: String -> Int) . words) `fmap` getLine\n print $ solve n seq \n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Array ((!), listArray)\nimport Data.List (sortBy)\nimport Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = print =<< solve <$> readLn <*> (map read . words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve n as = length [ a | (i, a) <- zip [0..] as, i == a ]\n + maybe 0 succ (listToMaybe (sortBy (flip compare) [ fromEnum (as' ! a == i) | (i, a) <- zip [0..] as, i /= a ]))\n where as' = listArray (0, n - 1) as\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Array\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns\n\nsolve :: Int -> [Int] -> Int\nsolve 1 _ = 1\nsolve 2 _ = 2\nsolve n ns = \n let arr = listArray (0, n-1) ns\n res = foldl' (\\(m, b) i -> \n if arr ! i == i\n then (m + 1, b)\n else (m, b || arr ! (arr ! i) == i)\n ) (0, False) [0 .. n-1]\n in case res of\n (m, False) -> min n (m + 1)\n (m, _) -> m + 2"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), bounds, listArray)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve xs = min n (k + l)\n where\n n = length xs\n a = listArray (0, n-1) xs\n k = length [0 | i <- [0 .. n-1], i == a ! i]\n l = if null [0 | i <- [0, n-1], i /= a ! i, i == a ! (a ! i)]\n then 1 else 2\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns\n\nsolve :: Int -> [Int] -> Int\nsolve n ns = \n let arr = listArray (0 :: Int,n-1) ns\n res = foldr (\\i (m, b) -> \n if arr ! i == i\n then (m + 1, b)\n else (m, arr ! (arr ! i) == i)\n ) (0, False) [0 .. n-1]\n in case res of\n (m, False) -> min n (m + 1)\n (m,_) -> m + 2"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns\n\nsolve :: Int -> [Int] -> Int\nsolve 1 _ = 1\nsolve 2 _ = 2\nsolve n ns = \n let arr = listArray (0, n-1) ns\n res = foldr (\\i (m, b) -> \n if arr ! i == i\n then (m + 1, b)\n else (m, arr ! (arr ! i) == i)\n ) (0, False) [0 .. n-1]\n in case res of\n (m, False) -> min n (m + 1)\n (m, _) -> m + 2"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns\n\nsolve :: Int -> [Int] -> Int\nsolve 1 _ = 1\nsolve 2 _ = 2\nsolve n ns = \n let arr = listArray (0 :: Int,n-1) ns\n res = foldr (\\i (m, b) -> \n if arr ! i == i\n then (m + 1, b)\n else (m, arr ! (arr ! i) == i)\n ) (0, False) [0 .. n-1]\n in case res of\n (m, False) -> min n (m + 1)\n (m,_) -> m + 2"}, {"source_code": "main = do\n input <- getLine\n let n = read (input) :: Int\n input <- getLine\n let input' = zip [0..] (f $ split ' ' input)\n let orig = sum [ 1 | (a, b) <- input', a == b ]\n let swap = qsort [ (b, a) | (a, b) <- input' ]\n let count = sum [ 1 | ((a, b), (c, d)) <- (zip input' swap), b == d ]\n \n print (if count == n then orig else (if orig < count then orig + 2 else orig + 1)) \n\n\nf :: [String] -> [Int]\nf x = map read x\n\nqsort :: (Ord a) => [a] -> [a]\nqsort [] = []\nqsort (x:xs) = qsort [ a | a <- xs, a <= x ] ++ [x] ++ qsort [ a | a <- xs, a > x ]\n\nsplit' :: (Eq a) => a -> [a] -> [a] -> [[a]]\nsplit' _ [] l = [l]\nsplit' v (x:xs) l\n | x /= v = split' v xs (l ++ [x])\n | otherwise = [l] ++ split' v xs []\n\nsplit :: (Eq a) => a -> [a] -> [[a]]\nsplit v xs = split' v xs []"}, {"source_code": "main = do\n input <- getLine\n let n = read (input) :: Int\n input <- getLine\n let input' = zip [0..] (f $ split ' ' input)\n print (sum [1 | (a, b) <- input', a == b] + swap input' 0)\n\n\nswap [] m = m\nswap [_] m = m\nswap ((x1,y1):x@(x2,y2):xs) m = swap (x:xs) (max m v)\n where v = (if x1 == y1 then -1 else 0) + (if x2 == y2 then -1 else 0) + (if x1 == y2 then 1 else 0) + (if x2 == y1 then 1 else 0)\n\nf :: [String] -> [Int]\nf x = map read x\n\nsplit' :: (Eq a) => a -> [a] -> [a] -> [[a]]\nsplit' _ [] l = [l]\nsplit' v (x:xs) l\n | x /= v = split' v xs (l ++ [x])\n | otherwise = [l] ++ split' v xs []\n\nsplit :: (Eq a) => a -> [a] -> [[a]]\nsplit v xs = split' v xs []\n"}], "src_uid": "e63de0fffd00b2da103545a7f1e405be"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = (: \"\") . maximum <$> str\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeApplications, OverloadedStrings, BlockArguments #-}\r\n\r\nmodule Main where\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Functor\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain =\r\n getLine\r\n <&> read @Int\r\n >>= flip replicateM (getLine <&> map digitToInt)\r\n >>= mapM_ (print . maximum)\r\n"}, {"source_code": "import Control.Monad\r\n\r\nlgst :: [Char] -> Char -> [Char]\r\nlgst [a] b = if a > b then [a] else [b]\r\nlgst (a:xs) mx = if a>mx then lgst xs a else lgst xs mx\r\n\r\n\r\n\r\nmain = do \r\n times <- readLn \r\n replicateM_ times $ do\r\n n <- getLine\r\n let l = lgst n '0'\r\n putStrLn l\r\n"}, {"source_code": "module Main where\n\nmain = interact solve\n\nsolve inp = \n let \n linp = lines inp\n t = read $ head linp :: Int\n xs = take t . tail $ linp\n logic x = maximum x\n in\n unlines . map ((\\x -> x : \"\") . logic) $ xs"}, {"source_code": "import Control.Monad ( forM )\r\nimport Data.List ( intersperse )\r\n\r\nmain :: IO ()\r\nmain = do\r\n s <- getLine\r\n let n = read s :: Int\r\n r <- forM [1..n] $ \\_ -> do\r\n z <- getLine\r\n return (maximum z) :: IO Char\r\n putStrLn $ intersperse '\\n' r"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.Int (Int64)\nimport Data.List as L\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n--import Data.IntSet \n\n\nconvert :: [Int] -> [[Int]]\nconvert xs\n | null xs || all (==0) xs = []\n | otherwise = nextnum : convert nextxs\n where nextnum = map (\\x -> if x > 0 then 1 else 0) xs\n nextxs = map (\\x -> if x > 0 then x-1 else 0) xs\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let dig = map Char.digitToInt $ s\n res = convert dig\n in putStrLn $ show $ length res\n \n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n s <- readLine\n let ans = P.foldl' max minBound s\n lift $ B.hPutBuilder stdout (B.char7 ans <> B.char7 '\\n')\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve 0 = 0\r\nsolve n = max (mod n 10) $ solve (div n 10)\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n let r = solve n\r\n print r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n s <- getLine\n putChar $ foldl max '1' s\n putChar '\\n'\n"}], "negative_code": [], "src_uid": "1a6881aeb197b8ed429f46850eb27b9c"} {"source_code": "{-#LANGUAGE Strict #-}\n\nimport Control.Monad(replicateM)\n\ndata Point = Point Int Int\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n res <- replicateM t $ do\n [w, h] <- map read . words <$> getLine :: IO [Int]\n bottom <- tail . map read . words <$> getLine :: IO [Int]\n top <- tail . map read . words <$> getLine :: IO [Int]\n left <- tail . map read . words <$> getLine :: IO [Int]\n right <- tail . map read . words <$> getLine :: IO [Int]\n return $ solve (Point w h) bottom top left right\n putStrLn $ unlines . map show $ res\n return ()\n\nsolve :: Point -> [Int] -> [Int] -> [Int] -> [Int] -> Int\nsolve p@(Point w h) b t l r = max (horz * h) (vert * w)\n where\n horz = max top bottom\n vert = max left right\n top = last t - head t\n bottom = last b - head b\n left = last l - head l\n right = last r - head r", "positive_code": [{"source_code": "{-#LANGUAGE Strict #-}\n\nimport Control.Monad(replicateM)\n\ndata Point = Point Int Int\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n res <- replicateM t $ do\n [w, h] <- map read . words <$> getLine -- :: IO [Int]\n bottom <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]\n top <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]\n left <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]\n right <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]\n return $ solve (Point w h) bottom top left right\n putStrLn $ unlines . map show $ res\n return ()\n\nsolve :: Point -> Int -> Int -> Int -> Int -> Int\nsolve p@(Point w h) b t l r = max (horz * h) (vert * w)\n where\n horz = max t b\n vert = max l r\n -- top = last t - head t\n -- bottom = last b - head b\n -- left = last l - head l\n -- right = last r - head r\n\n\nfAndL :: [a] -> (a, a)\nfAndL xs = (head xs, last xs)\n\nbreadth :: Num a => (a, a) -> a\nbreadth (f, l) = abs (l - f)"}, {"source_code": "import Control.Monad(replicateM)\n\ndata Point = Point Int Int\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n res <- replicateM t $ do\n [w, h] <- map read . words <$> getLine :: IO [Int]\n bottom <- tail . map read . words <$> getLine :: IO [Int]\n top <- tail . map read . words <$> getLine :: IO [Int]\n left <- tail . map read . words <$> getLine :: IO [Int]\n right <- tail . map read . words <$> getLine :: IO [Int]\n return $ solve (Point w h) bottom top left right\n putStrLn $ unlines . map show $ res\n return ()\n\nsolve :: Point -> [Int] -> [Int] -> [Int] -> [Int] -> Int\nsolve p@(Point w h) b t l r = max (horz * h) (vert * w)\n where\n horz = max top bottom\n vert = max left right\n top = last t - head t\n bottom = last b - head b\n left = last l - head l\n right = last r - head r"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\nremoveElem :: Int -> [a] -> [a]\nremoveElem i xs = take i xs <> tail (drop i xs)\n\nmain = do\n n <- read @Int <$> getLine\n replicateM n $ do\n [w,h] <- fmap (read @Integer) . words <$> getLine\n let getPs = fmap (read @Integer) . tail . words <$> getLine\n let getMaxLen l = last l - head l\n lowHoriz <- getPs\n upHoriz <- getPs\n leftVert <- getPs\n rightVert <- getPs\n print @Integer $ maximum [getMaxLen lowHoriz * h,\n getMaxLen upHoriz * h,\n getMaxLen leftVert * w,\n getMaxLen rightVert * w]\n"}], "negative_code": [], "src_uid": "2c67ee95eba7ffbbed99cb488abb5f3d"} {"source_code": "import Data.List (foldl')\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Integer]] -> Integer\nsolve [[n, _], as] = snd $ foldl' (\\(a, b) c -> (c, b + (c + n - a) `mod` n)) (1, 0) as\nsolve _ = undefined\n", "positive_code": [{"source_code": "calc n t\n | t < 0 = t+n\n | otherwise = t\ncount c n h [] = c\ncount c n h (m:ms)\n | h == m = count c n h ms\n | otherwise = count (c+(calc n (m-h))) n m (m:ms)\nparse=(map (map read)).(map words).lines\nmain=interact$ show.(\\[x, y]->count 0 (head x) 1 y).parse\n"}, {"source_code": "module Main (main)\n where\n\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = print . solve . map (map read . words) =<< replicateM 2 getLine\n where solve [[n,_],xs] = go n 1 0 xs\n go _ _ t [] = t\n go n c t (x:xs)\n | x >= c = go n x (t + x - c) xs\n | otherwise = go n x (t + n - c + x) xs"}, {"source_code": "\nmain = do\n\ts<-getLine\n\trest<-getLine\n\tputStrLn $ show $ solve (read (head (words s))) (map read (words rest)) 1\nsolve::Integer->[Integer]->Integer->Integer\nsolve n [] c = 0\nsolve n w c = travel n c (head w) + solve n (tail w) (head w)\n\ntravel n a b | b >= a = (b-a)\n | otherwise = n-a+b"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Integer] -> Integer\nsolve (n:m:a) = solve' a 1\n where\n solve' :: [Integer] -> Integer -> Integer\n solve' [] _ = 0\n solve' (a:ax) last | a >= last = a - last + (solve' ax a)\n | otherwise = a - last + n + (solve' ax a)\n"}, {"source_code": "import Data.Int\n\nsolution :: Int64 -> [Int64] -> [Int64]\nsolution n [] = []\nsolution n [k] = []\nsolution n [a, b]\n | a > b = [n + b - a]\n | otherwise = [b - a]\nsolution n xs = (solution n [xs!!0, xs!!1]) ++ (solution n $ tail xs)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n line2 <- getLine\n let n = head $ map (\\x -> read x :: Int64) $ words line1\n args = map (\\x -> read x :: Int64) $ words line2\n print $ sum $ solution n (1:args)"}, {"source_code": "main = do\n [n, m] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n\n let\n a = 1:xs\n s = sum $ zipWith (\\x y -> if x <= y then y-x else n-(x-y)) a (tail a)\n print s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\nmain = do\n n:m:l <- map readInt . B.words <$> B.getContents\n print $ solve n m l\n\nsolve :: Int -> Int -> [Int] -> Integer\nsolve n m l = sum $ zipWith f (1:l) l\n where\n f a b = fromIntegral $ (b + n - a) `mod` n\n"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [n,_] <- (map read . words) <$> getLine\n ts <- (map read . words) <$> getLine\n print . snd $ foldl (h n) (1,0) ts\n\n-- |\n-- >>> length $ g (f 4) [3,2,3]\n--6\n-- >>> length $ g (f 4) [2,3,3]\n--2\n--\n---- prop> \\n xs -> length (g (f n) xs) == foldl (h n) 0 xs\n\nf :: Integer -> [Integer]\nf n = cycle [1..n]\n\ng :: [Integer] -> [Integer] -> [Integer]\ng _ [] = []\ng (x:xs) (t:ts) | x == t = g (x:xs) ts\n | otherwise = x : g xs (t:ts)\ng _ _ = []\n\n-- |\n-- >>> snd $ foldl (h 4) (1,0) [3,2,3]\n--6\n-- >>> snd $ foldl (h 4) (1,0) [2,3,3]\n--2\nh :: Integer -> (Integer,Integer) -> Integer -> (Integer,Integer)\nh n (c,r) t | t < c = (t,r + n - c + t)\n | otherwise = (t,r + t - c)\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. (\\(a:b:bs)->a:1:bs).concat.map (map read.words).take 2.lines\nsolve :: [Integer]->String\nsolve xs = show $ fst $ slv1 xs\nslv1 (x:xs)=foldr f (0,0) xs where\n f a (0,0) = (0,a)\n f a (b1,b2) = if b2-a>=0 then (b1+b2-a,a) else (b1+b2+x-a,a)"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (foldl')\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n as = snd $ foldl' solve' (1, 0) as\n where\n \tsolve' (m, s) a\n \t | a >= m = (a, s + a - m)\n \t | a < m = (a, s + (n - m + a))\n\nmain :: IO ()\nmain = do\n\t[n, m] <- reads\n\tas <- reads\n\tprint $ solve n as\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInt :: B.ByteString -> Integer\nreadInt = B.foldl' (\\x c -> 10 * x + fromIntegral (ord c) - 48) 0\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Integer]\n ls <- (1:) . map readInt . B.words <$> B.getContents\n print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\nimport Data.Int (Int64)\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int64]\n ls <- (1:) . map read . words <$> getLine\n print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)"}, {"source_code": "import Control.Applicative\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Integer]\n ls <- (1:) . map read . words <$> getLine\n print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Integer]\n ls <- (1:) . map read . words <$> getLine\n let m = map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)\n print . sum $ m"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Integer]\n ls <- (1:) . map read . words <$> getLine\n print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)"}, {"source_code": "solve n xs = fst $ foldl moveToHouse (0, 1) xs\n where moveToHouse (time, position) destination\n | position <= destination = (time + destination - position,\n destination)\n | position > destination = (time + n - position + destination,\n destination)\n\nmain = do [n, _] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n putStrLn $ show $ solve n xs\n"}, {"source_code": "import Data.List\n\nsolve n xs = fst $ foldl' moveToHouse (0, 1) xs\n where moveToHouse (time, position) destination\n | position <= destination = (time + destination - position,\n destination)\n | position > destination = (time + n - position + destination,\n destination)\n\nmain = do [n, _] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n putStrLn $ show $ solve n xs\n"}, {"source_code": "import Data.List\n\nsolve n xs = fst $ foldl moveToHouse (0, 1) xs\n where moveToHouse (time, position) destination\n | position <= destination = (time + destination - position,\n destination)\n | position > destination = (time + n - position + destination,\n destination)\n\nmain = do [n, _] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n putStrLn $ show $ solve n xs\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndist :: Int -> Int -> Int -> Int\ndist n a b = if b >= a then b - a else n + b - a\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = sum $ map fromIntegral $ zipWith (dist n) (1:a) a\n\nmain :: IO ()\nmain = do\n [n, _] <- getIntList\n a <- getIntList\n print $ solve n a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nprocess [] _ _ cou = cou\nprocess (a:as) n cu cou | a>=cu = process as n a (cou + a-cu)\n | otherwise = process as n a (cou +n-cu+a )\n\nmain=do\n\n [n,m]<- map read <$> words <$> getLine ::IO [Integer]\n a<- map read <$> words <$> getLine ::IO [Integer]\n\n print $ process a n 1 0\n"}, {"source_code": "main = do\n [n,m] <- fmap (map read . words) getLine\n as <- fmap (map read . words) getLine\n let d a b = (b-a) `mod` n\n print . sum $ zipWith d (1:as) as\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/339/B\n\nimport Data.Int\n\ndist :: Int -> Int -> Int -> Int\ndist n a b = if b >= a then b - a else n + b - a\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = sum $ map fromIntegral $ zipWith (dist n) (1:a) a\n\n\nmain :: IO ()\nmain = do\n [n, _] <- map read . words <$> getLine :: IO [Int]\n a <- map read . words <$> getLine :: IO [Int]\n print $ solve n a\n"}, {"source_code": "module Main where\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport System.Environment\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tparams <- readInts\n\ta <- readInts\n\tprint $ gao (map fromIntegral a) (fromIntegral (params!!0))\n\t\n--\tlet a = take 100000 [1, 2, 1 ..]\n--\t\tin print $ gao (map fromIntegral a) (fromIntegral (params!!0))\n\ngao :: [Integer] -> Integer -> Integer\ngao xs n = ((fromIntegral $ length (groupBy' (<=) xs)) - 1) * n + last xs - 1\n\nreadInts ::IO [Int]\nreadInts = fmap (map $ fst . fromJust . C.readInt) (fmap C.words C.getLine)\n\ngroupBy' :: (a -> a -> Bool) -> [a] -> [[a]]\ngroupBy' _ [] = []\ngroupBy' _\t(x:[])\t\t = [[x]]\ngroupBy' eq (x:y:zs) | eq x y = (x:(head tmp)) : (tail tmp)\n\t\t\t\t\t\t | otherwise = (x:[]):tmp\n\t\t\t\t\t\t where tmp = (groupBy' eq (y:zs))"}, {"source_code": "main = interact $ show . path . map read . words\n\npath (n:_:ls) = fst $ foldl (\\(s,p) e -> (s + diff n p e, e)) (0,1) ls\n\ndiff n p e = if e

), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\ntil :: Integer -> Integer -> Integer -> Integer\ntil n x1 x2 = if x2 >= x1 then x2 - x1 else x2 + n - x1\n\nmain :: IO ()\nmain = do\n\t[n, _] <- inputIntegers\n\txs <- inputIntegers\n\tprint . sum $ zipWith (til n) (1 : xs) xs\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \nmain=do\t \n\t[n,m]<- map read. words <$> getLine ::IO [Integer]\n\ts<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine ::IO [Integer]\n\tprint $ sum $ zipWith (\\a b-> mod (a-b) n) s (1:s)\n\t "}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\nimport Data.Ratio\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet\n\t\t[n, m] = map (\\x->read x::Integer). words $ line1\n\t\tarr = map (\\x->x-1). map (\\x->read x::Integer). words $ line2\n\t\tsolve _ [] = 0\n\t\tsolve p (x:xs) = ((x-p)`mod`n + n)`mod`n + (solve x xs)\n\tprint$ solve 0 arr\n"}, {"source_code": "process :: [Integer] -> Integer -> Integer\nprocess xs n = sum $ zipWith f xs' (0:xs')\n where\n f x y = (x - y) `mod` n\n xs' = map (subtract 1) xs\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n print $ process as n"}, {"source_code": "module Main where\nimport Data.List (foldl')\n\nmain :: IO ()\nmain = do\n n:_ <- fmap (map read . words) getLine\n ts <- fmap (map read . words) getLine\n print $ rush n ts\n\nrush :: Integer -> [Integer] -> Integer\nrush n = snd . foldl' (\\(b,acc) t -> (t, (if t >= b then t - b else n + t - b) + acc)) (1, 0)\n"}, {"source_code": "import Data.Int\n\ntime :: Int64 -> [Int64] -> Int64\ntime n xs = sum $ zipWith d (1:xs) xs\n where d a b = (b - a) `mod` n \n\nsolve :: String -> String\nsolve s = show $ time n xs\n where l:ls = lines s\n n:_ = fmap read.words $ l\n xs = fmap read.words.head $ ls\n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "import Data.Int\n\nf :: Int64 -> (Int64, Int64) -> Int64 -> (Int64, Int64)\nf n (currentHouse, elapsedTime) nextHouse = (nextHouse, elapsedTime + newTime)\n where newTime = (nextHouse + n - currentHouse) `rem` n\n\nsolve :: String -> String\nsolve s = show $ snd $ foldl (f n) (1, 0) xs\n where l:ls = lines s\n n:_ = fmap read.words $ l\n xs = fmap read.words.head $ ls\n\nmain :: IO ()\nmain = interact $ solve"}], "negative_code": [{"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve (n:_:xs) = fst $ foldl' moveToHouse (0, 1) xs\n where moveToHouse (time, position) destination\n | position <= destination = (time + destination - position,\n destination)\n | position > destination = (time + n - position + destination,\n destination)\n\nmain = interact $ show . solve . map read . words\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndist :: Int -> Int -> Int -> Int\ndist n a b = if b >= a then b - a else n + b - a\n\nsolve :: Int -> [Int] -> Int\nsolve n a = sum $ zipWith (dist n) (1:a) a\n\nmain :: IO ()\nmain = do\n [n, _] <- getIntList\n a <- getIntList\n print $ solve n a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndist :: Int -> Int -> Int -> Int\ndist n a b = if b >= a then b - a else n + b - a\n\nsolve :: Int -> [Int] -> Int\nsolve n a = sum $ zipWith (dist n) (1:a) a\n\nmain :: IO ()\nmain = do\n [n, _] <- getIntList\n a <- getIntList\n print $ solve n a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nprocess [] _ _ cou = cou\nprocess (a:as) n cu cou | a>=cu = process as n a (cou + a-cu)\n | otherwise = process as n a (cou +n-cu+a )\n\nmain=do\n\n [n,m]<- map read <$> words <$> getLine ::IO [Int]\n a<- map read <$> words <$> getLine ::IO [Int]\n\n print $ process a n 1 0\n"}, {"source_code": "module Main where\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport System.Environment\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tparams <- readInts\n\ta <- readInts\n\tprint $ gao a (params!!0)\n\ngao :: [Int] -> Int -> Int\ngao xs n = (length (groupBy (<) xs) - 1) * n + last xs - 1\n\nreadInts ::IO [Int]\nreadInts = fmap (map $ fst . fromJust . C.readInt) (fmap C.words C.getLine)"}, {"source_code": "module Main where\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport System.Environment\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tparams <- readInts\n\ta <- readInts\n\tprint $ gao (map fromIntegral a) (fromIntegral (params!!0))\n\ngao :: [Integer] -> Integer -> Integer\ngao xs n = ((fromIntegral $ length (groupBy (<=) xs)) - 1) * n + last xs - 1\n\nreadInts ::IO [Int]\nreadInts = fmap (map $ fst . fromJust . C.readInt) (fmap C.words C.getLine)"}, {"source_code": "module Main where\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport System.Environment\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tparams <- readInts\n\ta <- readInts\n\tprint $ gao a (params!!0)\n\ngao :: [Int] -> Int -> Int\ngao xs n = (length (groupBy (<=) xs) - 1) * n + last xs - 1\n\nreadInts ::IO [Int]\nreadInts = fmap (map $ fst . fromJust . C.readInt) (fmap C.words C.getLine)"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \n\nmain=do\t \n\t[n,m]<- map read. words <$> getLine ::IO [Int]\n\ts<- map read. words <$> getLine ::IO [Int]\n\tprint $ sum $ zipWith (\\a b-> mod (a-b) n) s (1:s)\n\t "}, {"source_code": "process :: [Int] -> Int -> Int\nprocess xs n = sum $ zipWith f xs' (0:xs')\n where\n f x y = (x - y) `mod` n\n xs' = map (subtract 1) xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n print $ process as n"}, {"source_code": "f :: Int -> (Int, Int) -> Int -> (Int, Int)\nf n (currentHouse, elapsedTime) nextHouse = (nextHouse, elapsedTime + newTime)\n where newTime = (nextHouse + n - currentHouse) `rem` n\n\nsolve :: String -> String\nsolve s = show $ snd $ foldl (f n) (1, 0) xs\n where l:ls = lines s\n n:_ = fmap read.words $ l\n xs = fmap read.words.head $ ls\n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "\nmain = do\n\ts<-getLine\n\trest<-getLine\n\tputStrLn $ show $ solve (read (head (words s))) (map read (words rest)) 1\nsolve::Int->[Int]->Int->Int\nsolve n [] c = 0\nsolve n w c = travel n c (head w) + solve n (tail w) (head w)\n\ntravel n a b | b >= a = (b-a)\n | otherwise = n-a+b"}, {"source_code": "solution :: Int -> [Int] -> [Int]\nsolution n [] = []\nsolution n [k] = []\nsolution n [a, b]\n | a > b = [n + b - a]\n | otherwise = [b - a]\nsolution n xs = (solution n [xs!!0, xs!!1]) ++ (solution n $ tail xs)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n line2 <- getLine\n let n = head $ map (\\x -> read x :: Int) $ words line1\n args = map (\\x -> read x :: Int) $ words line2\n print $ sum $ solution n (1:args)"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [n,_] <- (map read . words) <$> getLine\n ts <- (map read . words) <$> getLine\n print . snd $ foldl (h n) (1,0) ts\n\n-- |\n-- >>> length $ g (f 4) [3,2,3]\n--6\n-- >>> length $ g (f 4) [2,3,3]\n--2\n--\n---- prop> \\n xs -> length (g (f n) xs) == foldl (h n) 0 xs\n\nf :: Int -> [Int]\nf n = cycle [1..n]\n\ng :: [Int] -> [Int] -> [Int]\ng _ [] = []\ng (x:xs) (t:ts) | x == t = g (x:xs) ts\n | otherwise = x : g xs (t:ts)\ng _ _ = []\n\n-- |\n-- >>> snd $ foldl (h 4) (1,0) [3,2,3]\n--6\n-- >>> snd $ foldl (h 4) (1,0) [2,3,3]\n--2\nh :: Int -> (Int,Int) -> Int -> (Int,Int)\nh n (c,r) t | t < c = (t,r + n - c + t)\n | otherwise = (t,r + t - c)\n"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n ls <- (1:) . map read . words <$> getLine\n let m = map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)\n print m\n print . sum $ m"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n ls <- (1:) . map read . words <$> getLine\n print . sum . map ((`mod`4) . uncurry (flip (-))) $ zip ls (drop 1 ls)"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\nimport Data.Word\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Word64]\n ls <- (1:) . map read . words <$> getLine\n print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n ls <- (1:) . map read . words <$> getLine\n let m = map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)\n print . sum $ m"}], "src_uid": "2c9c96dc5b6f8d1f0ddeea8e07640d3e"} {"source_code": "import Text.ParserCombinators.ReadP\nimport List\n\nmain = interact $ unwords.map show.solve.concat.lines\n\nsolve :: String -> [Int]\nsolve = sort.fst.head.readP_to_S table\n\ntable :: ReadP [Int]\ntable = do\n { string \"\"\n ; xss <- manyTill row (string \"
\")\n ; return $ ((length $ concat xss):) $ concat $ filter(not.null) $ concat xss\n }\n\nrow :: ReadP [[Int]]\nrow = do\n { string \"\"\n ; xs <- manyTill cell (string \"\")\n ; return xs\n }\n\ncell :: ReadP [Int]\ncell = do\n { string \"\"\n ; xs <- option [] table\n ; string \"\"\n ; return xs\n }\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n s <- getContents >>= return . concat . lines\n mapM (\\x -> putStr (show x ++ \" \")) $ solve s\n putStrLn \"\"\n\nsolve s = sort $ count $ preproc s\n\npreproc s = foldl replaceStr s [(\"\",\"[\"),(\"
\", \"]\"),(\"\", \"\"),(\"\", \"\"),(\"\", \".\"),(\"\", \"\")]\n\nreplaceStr [] _ = []\nreplaceStr xs@(y:ys) p@(from, to) = case stripPrefix from xs of\n Nothing -> y:replaceStr ys p\n Just ys' -> to ++ replaceStr ys' p\n\ncount s = count' s [] [] where\n count' [] _ acc = acc\n count' (s:ss) st acc = case s of\n '[' -> count' ss (0:st) acc\n '.' -> count' ss ((head st + 1):(tail st)) acc\n ']' -> count' ss (tail st) ((head st):acc)\n"}, {"source_code": "import List\nmain = interact solve\nsolve input = output where\n input0 = concat $ lines input\n output = unwords $ map show $ sort $ map count $ divide (translate input0) []\ntranslate [] = []\ntranslate xs\n | take 7 xs == \"\" = 'a':(translate $ drop 7 xs)\n | take 8 xs == \"
\" = 'b':(translate $ drop 8 xs)\n | take 4 xs == \"\" = 'c':(translate $ drop 4 xs)\n | take 5 xs == \"\" = 'd':(translate $ drop 5 xs)\n | take 4 xs == \"\" = 'e':(translate $ drop 4 xs)\n | take 5 xs == \"\" = 'f':(translate $ drop 5 xs)\ndivide [] _ = []\ndivide (x:xs) ys\n | x=='a' = divide xs ([]:ys)\n | x=='b' = y:(divide xs ys')\n | otherwise = divide xs ((x:y):ys')\n where y = head ys\n ys' = tail ys\ncount xs = length $ filter (=='e') xs\n"}], "negative_code": [{"source_code": "import Text.ParserCombinators.ReadP\nimport List\n\nmain = interact $ unwords.map show.solve.concat.lines\n\nsolve :: String -> [Int]\nsolve = fst.head.readP_to_S table\n\ntable :: ReadP [Int]\ntable = do\n { string \"\"\n ; xss <- manyTill row (string \"
\")\n ; return $ ((length $ concat xss):) $ concat $ filter(not.null) $ concat xss\n }\n\nrow :: ReadP [[Int]]\nrow = do\n { string \"\"\n ; xs <- manyTill cell (string \"\")\n ; return xs\n }\n\ncell :: ReadP [Int]\ncell = do\n { string \"\"\n ; xs <- option [] table\n ; string \"\"\n ; return xs\n }\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n s <- getContents >>= return . concat . lines\n mapM (\\x -> putStr (show x ++ \" \")) $ solve s\n putStrLn \"\"\n\nsolve s = count $ preproc s\n\npreproc s = foldl replaceStr s [(\"\",\"[\"),(\"
\", \"]\"),(\"\", \"\"),(\"\", \"\"),(\"\", \".\"),(\"\", \"\")]\n\nreplaceStr [] _ = []\nreplaceStr xs@(y:ys) p@(from, to) = case stripPrefix from xs of\n Nothing -> y:replaceStr ys p\n Just ys' -> to ++ replaceStr ys' p\n\ncount s = count' s [] [] where\n count' [] _ acc = acc\n count' (s:ss) st acc = case s of\n '[' -> count' ss (0:st) acc\n '.' -> count' ss ((head st + 1):(tail st)) acc\n ']' -> count' ss (tail st) ((head st):acc)\n"}], "src_uid": "eb5a5adffedacadad1df27a1ddc7f8ff"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad\nimport Data.Maybe\n\nobtainable :: [Int] -> Bool\nobtainable = go . reverse where\n go [0] = True\n go [_] = False\n go (0:xs) = go xs\n go (x1:x2:xs)\n | x1 > 0 = False\n | (-x1) == x2 && not (null xs) = False\n | otherwise = go (x2+x1:xs)\n\nmain = do\n [!t] <- readInts\n replicateM_ t $ do\n readInts\n as <- readInts\n putStrLn (if obtainable as then \"Yes\" else \"No\")\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\n\nsolve :: [Integer] -> Bool\nsolve xs = all (==0) xs || all (<0) (tail ys) && head ys == 0 \n where ys = scanr1 (+) $ dropWhileEnd (==0) xs\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Maybe\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n],xs] <- replicateM 2 ri\r\n return xs\r\n mapM_ (putStrLn.showYN.solve) tcs\r\n\r\nshowYN False = \"NO\"\r\nshowYN True = \"YES\"\r\n\r\nsolve xs = not (headFail||negPSumFail||finSumFail||splitFail)\r\n where\r\n psums = scanl1 (+) xs\r\n psumsNozeros = reverse . dropWhile (==0) . reverse $ psums\r\n headFail = (not.null) psumsNozeros && head psumsNozeros <= 0\r\n negPSumFail = isJust . L.find (<0) $ psumsNozeros\r\n finSumFail = (last psums /= 0)\r\n splitFail = isJust . L.find (==0) $ psumsNozeros\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\n\n-- solve :: [Integer] -> Bool\n-- solve xs = null ys || all (<0) (tail ys) && head ys == 0 \n-- where ys = scanr1 (+) $ dropWhileEnd (==0) xs\n\n\nsolve :: [Integer] -> Bool\nsolve xs = null ys || all (>0) (init ys) && last ys == 0 \n where ys = scanl1 (+) $ dropWhileEnd (==0) xs\n\n-- solve :: [Integer] -> Bool\n-- solve [] = True\n-- solve [0] = True\n-- solve [_] = False\n-- solve (x:y:xs) \n-- | z == 0 = all (==0) (xs)\n-- | z > 0 = solve (z:xs)\n-- | otherwise = False\n-- where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\n\n-- solve :: [Integer] -> Bool\n-- solve xs = null ys || all (<0) (tail ys) && head ys == 0 \n-- where ys = scanr1 (+) $ dropWhileEnd (==0) xs\n\n\nsolve :: [Integer] -> Bool\nsolve xs = null ys || all (>0) (init ys) && last ys == 0 \n where ys = scanl1 (+) xs\n\n-- solve :: [Integer] -> Bool\n-- solve [] = True\n-- solve [x] = x == 0\n-- solve (x:y:xs) \n-- | z == 0 = all (==0) xs\n-- | z > 0 = solve (z:xs)\n-- | otherwise = False\n-- where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\n\n-- solve :: [Integer] -> Bool\n-- solve xs = null ys || all (<0) (tail ys) && head ys == 0 \n-- where ys = scanr1 (+) $ dropWhileEnd (==0) xs\n\n\n-- solve :: [Integer] -> Bool\n-- solve xs = null ys || all (>0) (init ys) && last ys == 0 \n-- where ys = scanl1 (+) $ dropWhileEnd (==0) xs\n\nsolve :: [Integer] -> Bool\nsolve [] = True\nsolve [x] = x == 0\nsolve (x:y:xs) \n | z == 0 = all (==0) xs\n | z > 0 = solve (z:xs)\n | otherwise = False\n where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\n\n-- solve :: [Integer] -> Bool\n-- solve xs = null ys || all (<0) (tail ys) && head ys == 0 \n-- where ys = scanr1 (+) $ dropWhileEnd (==0) xs\n\n\nsolve :: [Integer] -> Bool\nsolve xs = null ys || all (>0) (tail ys) && last ys == 0 \n where ys = scanl1 (+) $ dropWhileEnd (==0) xs\n\n-- solve :: [Integer] -> Bool\n-- solve [] = True\n-- solve [0] = True\n-- solve [_] = False\n-- solve (x:y:xs) \n-- | z == 0 = all (==0) (xs)\n-- | z > 0 = solve (z:xs)\n-- | otherwise = False\n-- where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\n\n-- solve :: [Integer] -> Bool\n-- solve xs = null ys || all (<0) (tail ys) && head ys == 0 \n-- where ys = scanr1 (+) $ dropWhileEnd (==0) xs\n\n\nsolve :: [Integer] -> Bool\nsolve [] = True\nsolve [0] = True\nsolve [_] = False\nsolve (x:y:xs) \n | z == 0 = all (==0) (xs)\n | z > 0 = solve (z:xs)\n | otherwise = False\n where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: [Integer] -> Bool\nsolve xs = all (==0) xs || all (<0) (tail ys) && head ys == 0 \n where ys = scanr1 (+) xs\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String\nimport qualified Data.ByteString.Char8 as C\n\n\nsolve :: [Integer] -> Bool\nsolve [] = False\nsolve [0] = True\nsolve [_] = False\nsolve (x:y:xs) \n | x == 0 = all (==0) (y:xs)\n | z >= 0 = solve (z:xs)\n | otherwise = False\n where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String\nimport qualified Data.ByteString.Char8 as C\n\n\nsolve :: [Integer] -> Bool\nsolve [] = False\nsolve [0] = True\nsolve [_] = False\nsolve (x:y:xs) \n | z == 0 = all (==0) xs\n | z > 0 = solve (z:xs)\n | otherwise = False\n where z = x + y\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (liftM2, replicateM_)\r\nimport Data.Bits\r\n-- import Debug.Trace\r\nimport Data.Char (digitToInt)\r\nimport Data.Maybe (fromJust)\r\nimport Data.String\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve [] = False\r\nsolve [0] = True\r\nsolve [_] = False\r\nsolve (x:y:xs) \r\n | x + y == 0 = all (==0) xs\r\n | x + y > 0 = solve (x+y : xs)\r\n | otherwise = False\r\n\r\nparseInteger :: String -> Integer\r\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\r\n\r\nparseIntegerList :: String -> [Integer]\r\nparseIntegerList = map parseInteger . words\r\n\r\nprintAns :: Bool -> IO ()\r\nprintAns True = putStrLn \"YES\"\r\nprintAns False = putStrLn \"NO\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- parseInteger <$> getLine\r\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String\nimport qualified Data.ByteString.Char8 as C\n\n\nsolve :: [Integer] -> Bool\nsolve [] = True\nsolve [0] = True\nsolve [_] = False\nsolve (x:y:xs) \n | x + y == 0 = all (==0) xs\n | x + y > 0 = solve (x+y : xs)\n | otherwise = False\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\n\nimport Control.Monad (liftM2, replicateM_)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String\nimport qualified Data.ByteString.Char8 as C\n\n\nsolve :: [Integer] -> Bool\nsolve [] = True\nsolve [0] = True\nsolve [_] = False\nsolve (x:y:xs) \n | x == 0 = all (==0) (y:xs)\n | x + y > 0 = solve (x+y : xs)\n | otherwise = False\n\nparseInteger :: String -> Integer\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntegerList :: String -> [Integer]\nparseIntegerList = map parseInteger . words\n\nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- parseInteger <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (liftM2, replicateM_)\r\nimport Data.Bits\r\n-- import Debug.Trace\r\nimport Data.Char (digitToInt)\r\nimport Data.Maybe (fromJust)\r\nimport Data.String\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve [] = True\r\nsolve [0] = True\r\nsolve [_] = False\r\nsolve (x:y:xs) \r\n | x == 0 = all (==0) (y:xs)\r\n | x + y >= 0 = solve (x+y : xs)\r\n | otherwise = False\r\n\r\nparseInteger :: String -> Integer\r\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\r\n\r\nparseIntegerList :: String -> [Integer]\r\nparseIntegerList = map parseInteger . words\r\n\r\nprintAns :: Bool -> IO ()\r\nprintAns True = putStrLn \"YES\"\r\nprintAns False = putStrLn \"NO\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- parseInteger <$> getLine\r\n replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))"}], "src_uid": "9f0ffcbd0ce62a365a1ecbb4a2c1de3e"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n putStrLn $ bool \"FastestFinger\" \"Ashishgup\" $ solve n\n\nsolve n\n | p == 0, x == 1 = False\n | p == 0 = True\n | p == 1, x == 1 = True\n | p == 1 = any ((== 0) . (x `mod`)) $ takeWhile (<= floor (sqrt $ fromIntegral x)) [3, 5 ..]\n | x == 1 = False\n | otherwise = True\n where\n (p, x) = powerTwo n\n\npowerTwo = f . (,) 0\n where\n f (p, n)\n | odd n = (p, n)\n | otherwise = f (p + 1, n `div` 2)\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n putStrLn $ if solve n then \"Ashishgup\" else \"FastestFinger\"\n\nsolve :: Int -> Bool\nsolve n\n | n == 1 = False\n | odd n = True\n | n == 2 = True\n | pow2 n = False\n | otherwise = not $ isPrime (n `div` 2)\n\nisPrime :: Int -> Bool\nisPrime n = not $ any (\\x -> n `mod` x == 0) [2..sq]\n where\n sq = floor $ sqrt $ fromIntegral n\n\npow2 :: Int -> Bool\npow2 n = x == n\n where\n x = until (>=n) (*2) 1\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n putStrLn $ bool \"FastestFinger\" \"Ashishgup\" $ solve n\n\nsolve n\n | p == 0, x == 1 = False\n | p == 0 = True\n | p == 1, x == 1 = True\n | p == 1 = any ((== 0) . (x `div`)) $ takeWhile (<= floor (sqrt $ fromIntegral x)) [1, 3 ..]\n | x == 1 = False\n | otherwise = True\n where\n (p, x) = powerTwo n\n\npowerTwo = f . (,) 0\n where\n f (p, n)\n | odd n = (p, n)\n | otherwise = f (p + 1, n `div` 2)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n putStrLn $ bool \"FastestFinger\" \"Ashishgup\" $ solve n\n\nsolve n\n | p == 0, x == 1 = False\n | p == 0 = True\n | p == 1, x == 1 = True\n | p == 1 = any ((== 0) . (x `div`)) $ takeWhile (<= floor (sqrt $ fromIntegral x)) [3, 5 ..]\n | x == 1 = False\n | otherwise = True\n where\n (p, x) = powerTwo n\n\npowerTwo = f . (,) 0\n where\n f (p, n)\n | odd n = (p, n)\n | otherwise = f (p + 1, n `div` 2)\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n putStrLn $ if solve n then \"Ashishgup\" else \"FastestFinger\"\n\nsolve :: Int -> Bool\nsolve n\n | n == 1 = False\n | odd n = True\n | n == 2 = True\n | otherwise = not $ isPrime (n `div` 2)\n\nisPrime :: Int -> Bool\nisPrime n = not $ any (\\x -> n `mod` x == 0) [2..sq]\n where\n sq = floor $ sqrt $ fromIntegral n\n"}], "src_uid": "b533572dd6d5fe7350589c7f4d5e1c8c"} {"source_code": "module Main where\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Bits\n\nsolve :: String -> Int\nsolve = snd . foldl' (\\(a, b) c -> if c == 'b' then (a, b +% a +% (base - 1)) else (a *% 2, b)) (1, 0)\n where\n base = 1000000007 \n a +% b = (a + b) `mod` base\n \n a *% b = (a * b) `mod` base\n\n\nmain = solve <$> getLine >>= print\n\n-- abbaaabaabaaaaabbbbaababaaaaabaabbaaaaabbaabbaaaabbbabbbabb\n-- bbaba\n-- bbbbaa\n-- aab\n-- abba\n-- bbab a\n-- bbbbaa\n\n-- X'abbaY\n-- X'bbabaY\n-- ab b\n-- bba b\n-- aab\n-- ab -> bba\n\n-- aa ab\n-- aa bba 1\n-- a ab ba\n-- a bba ba 2\n-- abb ab a\n-- abb bba a 3\n-- ab bbbaa\n-- bba bbbaa 4\n-- bb ab bb aa \n-- bb bba bb aa 5\n-- bbbb ab baa\n-- bbbb bba baa 6\n\n-- first takes 1, add 2 -> 2\n-- second takes 2, add 2 -> 4\n-- third takes 4, add 4 -> 8\n-- 1 + 2 + 4\n-- bbbbbbb aaa\n\n\n", "positive_code": [{"source_code": "main = getLine >>= print . solve 0 1\n\nsolve ans _ [] = ans\nsolve ans a ('a':cs) = solve ans (a * 2 `mod` 1000000007) cs\nsolve ans a ('b':cs) = solve ((ans + a - 1) `mod` 1000000007) a cs\n"}], "negative_code": [{"source_code": "module Main where\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Bits\n\nsolve :: String -> Int\nsolve = snd . foldl' (\\(a, b) c -> if c == 'b' then (a, if a == 0 then b else b +% ((2 `shiftL` (a - 1) - 1) `mod` base)) else (a +% 1, b)) (0, 0)\n where\n base = 1000000007 \n a +% b = (a + b) `mod` base\n\n\nmain = solve <$> getLine >>= print\n\n-- aab\n-- abba\n-- bbab a\n-- bbbbaa\n\n-- X'abbaY\n-- X'bbabaY\n-- ab b\n-- bba b\n-- aab\n-- ab -> bba\n\n-- aa ab\n-- aa bba 1\n-- a ab ba\n-- a bba ba 2\n-- abb ab a\n-- abb bba a 3\n-- ab bbbaa\n-- bba bbbaa 4\n-- bb ab bb aa \n-- bb bba bb aa 5\n-- bbbb ab baa\n-- bbbb bba baa 6\n\n-- first takes 1, add 2 -> 2\n-- second takes 2, add 2 -> 4\n-- third takes 4, add 4 -> 8\n-- 1 + 2 + 4\n-- bbbbbbb aaa\n\n\n"}], "src_uid": "8f52241c690ec4f9af71a52904fb19a0"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Applicative\nimport Data.Int (Int64)\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngao :: Int64 -> Int64 -> [(Int64, Int64)] -> Int -> Int\ngao s t [] res = res + if s < t then 1 else 0\ngao _ _ [_] res = res + 1\ngao s t a@((i, _): _) res | s > i = gao i t a res\ngao s t ((i, x): (j, y): a) res\n | m /= 0 || lval <= 0 = gao j t ((j, y): a) $ res + 1\n | otherwise = gao ridx t a' $ res + 1\n where\n (d, m) = (y - x) `quotRem` (j - i)\n lval = x - (i - s) * d\n ridx = if d >= 0 then t else j + (y-1) `quot` (-d) + 1\n a' = dropWhile (\\(k, z) -> z == y + (k - j) * d) a\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n a <- map readInt . C.words <$> C.getLine\n print $ gao 0 n [ie | ie@(_, e) <- zip [0..] a, e > 0] 0\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Int (Int64)\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\ngao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int\ngao s [] n res = res + if s < n then 1 else 0\ngao _ [_] _ res = res + 1\ngao s all@((i,x) : (j,y) : xs) n res \n | s > i = gao i all n res\n | m /= 0 || l <= 0 = gao j ((j,y) : xs) n $ res + 1\n | otherwise = gao next xs' n $ res + 1\n where\n (d,m) = (y - x) `quotRem` (j - i)\n l = x - (i - s) * d\n next = if d >= 0 then n else j + (y-1) `quot` (-d) + 1\n xs' = dropWhile (\\(k,z) -> z == (k-j)*d + y) xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n array <- getInts\n print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Int (Int64)\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\ngao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int\ngao s [] n res = res + if s < n then 1 else 0\ngao _ [_] _ res = res + 1\ngao s all@((i,x) : (j,y) : xs) n res \n | lval <= 0.0 = gao i all n $ res + 1\n | cant = gao n xs n $ res + 1\n | otherwise = gao j ((j,y):xs) n $ res\n where \n dif = fromIntegral $ y - x :: Double\n dis = fromIntegral $ j - i :: Double\n x' = fromIntegral $ x :: Double\n y' = fromIntegral $ y :: Double\n dis' = if i <= s then 0.0 else fromIntegral $ i - s :: Double\n d = dif / dis :: Double\n lval = x' - dis' * d\n next = if d >= 0 then n else ceiling $ y' / (-d)\n calc (t1,t2) (t3,t4) = (t4 - t2) `quotRem` (t3 - t1)\n cant = if null xs then True else calc (j,y) (i,x) /= calc (head xs) (j,y)\n \nmain :: IO ()\nmain = do\n n <- getInt\n array <- getInts\n print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Int (Int64)\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\ngao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int\ngao s [] n res = res + if s < n then 1 else 0\ngao _ [_] _ res = res + 1\ngao s all@((i,x) : (j,y) : xs) n res \n | m /= 0 || l <= 0 = if s < i then gao i all n (res+1) else gao next xs n (res+2)\n | cant = gao next xs n $ res + 1\n | otherwise = gao i ((j,y):xs) n res \n where\n (d,m) = (y - x) `quotRem` (j - i)\n l = x - (i - s) * d\n cant = if null xs then True else (snd $ head xs) /= (y + d * ((fst $ head xs) - j))\n next = if null xs then n else fst $ head xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n array <- getInts\n print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Int (Int64)\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\ngao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int\ngao s [] n res = res + if s < n then 1 else 0\ngao _ [_] _ res = res + 1\ngao s all@((i,x) : (j,y) : xs) n res \n | m /= 0 || l <= 0 = if x > i - s then gao j ((j,y):xs) n (res+1) else gao i xs n (res+1)\n | cant = gao next xs n $ res + 1\n | otherwise = gao i ((j,y):xs) n res \n where\n (d,m) = (y - x) `quotRem` (j - i)\n l = x - (i - s) * d\n cant = if null xs then True else (snd $ head xs) /= (y + d * ((fst $ head xs) - j))\n next' = if d >= 0 then n else j + (y-1) `quot` (-d) + 1\n next = if null xs then next' else fst $ head xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n array <- getInts\n print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Int (Int64)\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\ngao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int\ngao s [] n res = res + if s < n then 1 else 0\ngao _ [_] _ res = res + 1\ngao s all@((i,x) : (j,y) : xs) n res \n | m /= 0 || l <= 0 = gao j ((j,y) : xs) n $ res + 1\n | otherwise = gao next xs' n $ res + 1\n where\n (d,m) = (y - x) `quotRem` (j - i)\n l = x - (i - s) * d\n next = if d >= 0 then n else j + (y-1) `quot` (-d) + 1\n xs' = dropWhile (\\(k,z) -> z == (k-j)*d + y) xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n array <- getInts\n print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Int (Int64)\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\ngao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int\ngao s [] n res = res + if s < n then 1 else 0\ngao _ [_] _ res = res + 1\ngao s all@((i,x) : (j,y) : xs) n res \n | m /= 0 || l <= 0 = if s < i then gao j ((j,y):xs) n (res+1) else gao next xs n (res+2)\n | cant = gao next xs n $ res + 1\n | otherwise = gao i ((j,y):xs) n res \n where\n (d,m) = (y - x) `quotRem` (j - i)\n l = x - (i - s) * d\n cant = if null xs then True else (snd $ head xs) /= (y + d * ((fst $ head xs) - j))\n next = if null xs then n else fst $ head xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n array <- getInts\n print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0\n"}], "src_uid": "0c4dad4f65ad986d87c968520111e995"} {"source_code": "-- import Debug.Trace\r\nimport Data.Bits\r\n \r\ntype InType = [Int]\r\ntype OutType = Int\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n \r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n \r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n \r\nsolve :: InType -> OutType\r\nsolve = foldr (.&.) all_bits\r\n where all_bits = 2 ^ 31 - 1\r\n \r\nreceive :: [String] -> InType\r\nreceive [n, a] = toArr a\r\nreceive _ = undefined\r\n \r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines\r\n where showb True = \"YES\"\r\n showb False = \"NO\"\r\n\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.Reader (replicateM_)\r\nimport Data.Bits (Bits((.&.)))\r\nimport Data.List (sort)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n sequence <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n print $ solve sequence\r\n\r\nsolve :: [Int] -> Int\r\nsolve [x] = x\r\nsolve xs = foldr (.&.) (2 ^ 31-1) xs\r\n{->>>solve [1,2]\r\n0\r\n-}\r\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bits ((.&.))\r\n\r\nsolve :: [Int] -> Int\r\nsolve = foldl1 (.&.)\r\n\r\nprocess [] = []\r\nprocess (x:y:ys) = show (solve ((map read . words) y)) : process ys\r\n\r\nmain = interact $ lines >>> drop 1 >>> process >>> unlines\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Bits ((.&.))\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n unused <- getLine\n line <- getLine\n let numbers = map read $ words line :: [Int]\n putStrLn $ show $ foldl1 (.&.) numbers\n"}, {"source_code": "import Data.Bits ((.&.))\n\nmain = do\n t <- read <$> getLine :: IO Int\n mapM_ solve [1..t]\n\nsolve :: Int -> IO ()\nsolve _ = do\n getLine\n a <- map read . words <$> getLine :: IO [Int]\n print $ foldr1 (.&.) a"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bits ((.&.))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> chunksOf 2\n >>> map (last >>> words >>> map read >>> solve >>> show)\n >>> unlines\n\nsolve :: [Int] -> Int\nsolve = foldl1 (.&.)\n\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.Reader (replicateM_)\r\nimport Data.Bits (Bits((.&.)))\r\nimport Data.List (sort)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n sequence <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n print $ solve sequence\r\n\r\nsolve :: [Int] -> Int\r\nsolve [x] = x\r\nsolve xs = maximum xs .&. minimum xs\r\n{->>>solve [3,11,3,7]\r\n3\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.Reader (replicateM_)\r\nimport Data.List (sort)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n sequence <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n print $ solve sequence\r\n\r\nsolve :: [Int] -> Int\r\nsolve [x] = x\r\nsolve xs = y - z - 1\r\n where\r\n (y:z:ys) = reverse $ sort xs\r\n{->>>solve [3,11,3,7]\r\n3\r\n-}\r\n"}], "src_uid": "4f8eac547bbd469a69de2f4aae4a87f0"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as LB8\nimport qualified Data.ByteString.Char8 as B8\n\nfind3 n = if n == 1 then 1 else go 2\n where go v = if v * pred v `div` 2 <= n then go (v + 1) else v - 1\n\ngetInt = (fromIntegral . fst . fromJust . B8.readInt) <$> B8.getLine\n\nmain :: IO ()\nmain = do\n a <- getInt\n replicateM_ a $ do\n b <- getInt\n let c3 = find3 b\n putStr \"1\"\n putStr \"33\"\n when (c3 /= 1) $ LB8.putStr $ LB8.replicate (fromIntegral $ b - ((c3 * pred c3) `div` 2)) '7'\n LB8.putStr $ LB8.replicate (fromIntegral $ c3 - 2) '3'\n putStrLn \"7\"\n", "positive_code": [{"source_code": " import Control.Monad\n \n triangleNums = [(i, i*(i+1) `div` 2) | i <- reverse [1..100000]]\n \n decomp 0 _ = []\n decomp _ [] = error \"NOT DECOMPOSABLE\"\n decomp i xs@(x:_)\n | i >= snd x = fst x : decomp (i- snd x) xs\n | otherwise = decomp i $ tail xs\n \n printThreesAndSevens [] _ = return ()\n printThreesAndSevens is@(i:i') idx\n | i == idx = do\n putStr \"7\"\n printThreesAndSevens i' idx\n | otherwise = do\n putStr \"3\"\n printThreesAndSevens is $ idx + 1\n \n main :: IO ()\n main = do\n t <- liftM (read :: String -> Int) getLine\n forM_ [1..t] $ \\x -> do\n n <- liftM read getLine\n let composed = reverse $ decomp n triangleNums\n putStr \"13\"\n printThreesAndSevens composed 0 \n putStrLn \"\""}], "negative_code": [{"source_code": "import Control.Monad\n\ntriangleNums = [(i, i*(i+1) `div` 2) | i <- reverse [1..100000]]\n\ndecomp 0 _ = []\ndecomp _ [] = error \"NOT DECOMPOSABLE\"\ndecomp i xs@(x:_)\n | i >= snd x = fst x : decomp (i- snd x) xs\n | otherwise = decomp i $ tail xs\n\nprintThreesAndSevens [] _ = return ()\nprintThreesAndSevens is@(i:i') idx\n | i == idx = do\n putStr \"7\"\n printThreesAndSevens i' idx\n | otherwise = do\n putStr \"3\"\n printThreesAndSevens is $ idx + 1\n\nmain :: IO ()\nmain = do\n n <- liftM read getLine\n let composed = reverse $ decomp n triangleNums\n putStr \"13\"\n printThreesAndSevens composed 0 "}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as LB8\nimport qualified Data.ByteString.Char8 as B8\n\nfind3 n = if n == 1 then 1 else go 2\n where go v = if v * pred v `div` 2 <= n then go (v + 1) else v - 1\n\ngetInt = (fromIntegral . fst . fromJust . B8.readInt) <$> B8.getLine\n\nmain :: IO ()\nmain = do\n a <- getInt\n replicateM_ a $ do\n b <- getInt\n let c3 = find3 b\n putStr \"1\"\n putStr \"33\"\n when (c3 /= b) $ LB8.putStr $ LB8.replicate (fromIntegral $ b - ((c3 * pred c3) `div` 2)) '7'\n LB8.putStr $ LB8.replicate (fromIntegral $ c3 - 2) '3'\n putStrLn \"7\"\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as LB8\nimport qualified Data.ByteString.Char8 as B8\n\nfind3 n = if n == 1 then 1 else go 2\n where go v = if v * pred v `div` 2 <= n then go (v + 1) else v - 1\n\ngetInt = (fromIntegral . fst . fromJust . B8.readInt) <$> B8.getLine\n\nmain :: IO ()\nmain = do\n a <- getInt\n replicateM_ a $ do\n b <- getInt\n let c3 = find3 b\n putStr \"1\"\n putStr \"33\"\n LB8.putStr $ LB8.replicate (fromIntegral $ b - ((c3 * pred c3) `div` 2)) '7'\n LB8.putStr $ LB8.replicate (fromIntegral $ c3 - 2) '3'\n putStrLn \"7\"\n"}], "src_uid": "9aabacc9817722dc11335eccac5d65ac"} {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nisMirror s = s == reverse s && all (`elem` \"AHIMOTUVWXY\") s\n\nmain :: IO ()\nmain = do\n\ts <- getLine\n\tputStrLn $ if isMirror s then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem) -- generalized by Data.Foldable\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n\nbsGetLine :: IO ByteString\nbsGetLine = BS.getLine <&> fst . BS.spanEnd isSpace\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nisMirror s = s == BS.reverse s && BS.all (`elem` \"AHIMOTUVWXY\") s\n\nmain :: IO ()\nmain = do\n\ts <- bsGetLine\n\tputStrLn $ if isMirror s then \"YES\" else \"NO\"\n"}, {"source_code": "main = do \n line <- getLine\n if line==reverseWords line && checkString line \"BCDEFGJKLNPQRSZ\"\n then do\n\t\t\tputStrLn $ \"YES\"\n else do \n putStrLn $ \"NO\"\n \nreverseWords :: String -> String \nreverseWords = unwords . map reverse . words \ncheckElement :: Char -> String -> Bool\ncheckElement x [] = False\ncheckElement x (y:ys) \n\t\t\t| x==y \t\t= True\n\t\t\t| otherwise = checkElement x ys\ncheckString :: String -> String -> Bool\ncheckString x [] = True\ncheckString x (y:ys) \n\t\t\t| checkElement y x = False\n\t\t\t| otherwise = checkString x ys\n"}, {"source_code": "main=getLine>>=putStrLn.f\nf cs|all(`elem`\"AHIMOTUVWXY\")cs,cs==reverse cs=\"YES\"|0<1=\"NO\""}, {"source_code": "startUp s = (s == reverse s) && ( and [x `elem` ['A','H','I','M','T','W','Y','O','X','V','U'] | x <- s ])\nmain = do\n s <- getLine\n putStr $ if (startUp s) then \"YES\" else \"NO\"\n"}, {"source_code": "-- Codeforces 420A\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n xs <- getLine\n if xs == reverse xs && all (`elem` \"AHIMTWYOXVU\") xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}], "negative_code": [{"source_code": "startUp s = (s == reverse s) && ( and [x `elem` ['A','H','I','M','T','W','Y','O','X'] | x <- s ])\nmain = do\n s <- getLine\n putStr $ if (startUp s) then \"YES\" else \"NO\"\n"}, {"source_code": "startUp s = (s == reverse s) && ( and [x `elem` ['A','H','I','M','T','W','Y'] | x <- s ])\nmain = do\n s <- getLine\n putStr $ if (startUp s) then \"YES\" else \"NO\"\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Prelude hiding (all, elem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (forM_)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport qualified Data.List as List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = List.genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nisMirror s = s == BS.reverse s && BS.all (`elem` \"AHIMOTUVWXY\") s\n\nmain :: IO ()\nmain = do\n\ts <- BS.getLine\n\tprint $ BS.length s\n\tforM_ (BS.unpack s) $ \\x -> print x\n\tputStrLn $ if isMirror s then \"YES\" else \"NO\"\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Prelude hiding (all, elem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport qualified Data.List as List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = List.genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nisMirror s = s == BS.reverse s && BS.all (`elem` \"AHIMOTUVWXY\") s\n\nmain :: IO ()\nmain = do\n\ts <- BS.getLine\n\tputStrLn $ if isMirror s then \"YES\" else \"NO\"\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Prelude hiding (all, elem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport qualified Data.List as List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = List.genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nisMirror s = s == BS.reverse s && BS.all (`elem` \"AHIMOTUVWXY\") s\n\nmain :: IO ()\nmain = do\n\ts <- BS.getLine\n\thPrint stderr $ BS.length s\n\tputStrLn $ if isMirror s then \"YES\" else \"NO\"\n"}, {"source_code": "main = do \n line <- getLine\n if line==reverseWords line \n then do\n\t\t\tputStrLn $ \"Yes\"\n else do \n putStrLn $ \"No\"\n \nreverseWords :: String -> String \nreverseWords = unwords . map reverse . words \n"}, {"source_code": "main = do \n line <- getLine\n if line==reverseWords line \n then do\n\t\t\tputStrLn $ \"YES\"\n else do \n putStrLn $ \"NO\"\n \nreverseWords :: String -> String \nreverseWords = unwords . map reverse . words \n"}, {"source_code": "main = do \n line <- getLine\n if line==reverseWords line && checkString line \"BCDEFGJKLNPRSZ\"\n then do\n\t\t\tputStrLn $ \"YES\"\n else do \n putStrLn $ \"NO\"\n \nreverseWords :: String -> String \nreverseWords = unwords . map reverse . words \ncheckElement :: Char -> String -> Bool\ncheckElement x [] = False\ncheckElement x (y:ys) \n\t\t\t| x==y \t\t= True\n\t\t\t| otherwise = checkElement x ys\ncheckString :: String -> String -> Bool\ncheckString x [] = True\ncheckString x (y:ys) \n\t\t\t| checkElement y x = False\n\t\t\t| otherwise = checkString x ys\n"}, {"source_code": "main=getLine>>=putStrLn.f\nf cs|all(`elem`\"ABHIMOTUVWXY\")cs,cs==reverse cs=\"YES\"|0<1=\"NO\""}], "src_uid": "8135173b23c6b48df11b1d2609b08080"} {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >> (solve =<< map (fst.fromJust.C.readInt).C.words<$>C.getLine)\n--solve::Int->IO()\nsolve xs = print $ fst $ foldl f (0,0) xs\n where\n f (b1,b2) a = if a<0 && b2==0 then (b1+1,b2) else (b1,b2+a)", "positive_code": [{"source_code": "solve :: [Int] -> Int -> Int -> Int\nsolve [] _ up = up\nsolve (x : xs) rr up\n | x == -1 = if rr >= 1 then solve xs (rr - 1) up else solve xs rr (up + 1)\n | otherwise = solve xs (rr + x) up\n\nprepare :: [Int] -> Int\nprepare crimes = solve crimes 0 0\n\nmain :: IO ()\nmain = interact $ show . prepare . tail . map read . words\n"}, {"source_code": "#!/usr/bin/env runghc\nmain = getContents >>= mapM_ putStrLn . solve . lines\nsolve [] = [] ::[String]\nsolve (n:p:ss) = (:solve ss)$ show . foldr f 0 . map (read::String->Int) . words $ p\n where f p t = max 0 (t-p)\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nsolve :: [Int] -> Int\nsolve = go 0 0\n\twhere\n\t\tgo u _ [] = u\n\t\tgo u 0 (-1:xs) = go (u+1) 0 xs\n\t\tgo u p (-1:xs) = go u (p-1) xs\n\t\tgo u p ( x:xs) = go u (p+x) xs\n\nmain :: IO ()\nmain = void getLine >> inputInts >>= print . solve\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n\nprocess _ c [] = c\nprocess a c (d:ds) | d>0 && a>0 = process (d+a) c ds \n | d>0 = process d c ds \n\t\t | a>0 = process (a-1) c ds \n | otherwise = process (a-1) (c+1) ds\nmain=do\t \n\tgetLine \n\ts<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine ::IO [Integer]\n\tprint $ process 0 0 s\n\t "}, {"source_code": "import Data.List\n\nprocess :: [Int] -> Int\nprocess = length . filter (<0) . scanl' (\\acc x -> if x > 0 && acc < 0 then x else acc + x) 0\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "module Main\n where\n\nimport System.IO\n\nmain = do\n first <- getLine\n second <- getLine\n print . solve 0 0 . map read . words $ second\n where\n solve crimes _ [] =\n crimes\n solve crimes officers (event : events) =\n if officers' < 0 then\n solve (crimes + 1) 0 events\n else\n solve crimes officers' events\n where\n officers' = officers + event"}, {"source_code": "main=interact$f.map read.words\nf(x:xs)=show.negate.minimum.scanl(+)0$xs"}, {"source_code": "main = do\n getLine\n con<-getLine\n putStr $ (show.solve 0 0.map read.words) con\n\nsolve _ k [] = k\nsolve p k (x:xs) \n |x>0 = solve (p+x) k xs\n |p-1<0 = solve p (k+1) xs\n |otherwise = solve (p-1) k xs"}, {"source_code": "main = do line <- getLine\n let n = (read line) :: Int\n line <- getLine\n let xs = (map read $ words line) :: [Int]\n putStrLn $ show $ countCrime xs 0 0\n\ncountCrime [] pol acc = acc\ncountCrime (x : xs) pol acc\n | x == -1 = if pol > 0 then countCrime xs (pol - 1) acc\n else countCrime xs pol (acc + 1)\n | x > 0 = countCrime xs (pol + x) acc\n | otherwise = error \"shit\""}, {"source_code": "parseInput :: String -> [Int]\nparseInput input = xs where\n ls = lines input\n ys = words $ last ls\n xs = map read ys\n\nsolve :: Int -> [Int] -> Int\nsolve n [] = 0\nsolve n (x:xs) \n | x > 0 = solve (n + x) xs\n | otherwise = case n of\n 0 -> 1 + solve n xs\n _ -> solve (n - 1) xs\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = parseInput input\n print $ solve 0 xs\n"}, {"source_code": "solve2 events = negate $ minimum $ scanl (+) 0 events\n\nmain :: IO ()\nmain = getContents >>= print . solve2 . map read . words . (!!1) . lines\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:a) = solve' a 0\n\nsolve' :: [Int] -> Int -> Int\nsolve' [] sum | sum < 0 = abs sum\n | otherwise = 0\nsolve' (a:ax) sum | sum < 0 = max (abs sum) (solve' ax (sum + a))\n | otherwise = solve' ax (sum + a)\n"}, {"source_code": "\n\n\n-- time limit exceeded\n-- use faster list operations\n\n\npolice lst crm pol\n | (null lst) = crm\n | otherwise = if (head lst) == (-1)\n then if pol > 0\n then police (tail lst) crm (pol-1)\n else police (tail lst) (crm+1) pol\n else police (tail lst) crm (pol+(head lst))\n\n\nconv lst cc\n | (null lst) = reverse cc\n | otherwise = conv (tail lst) (((read (head lst))::Int) : cc)\n \n\nmain = do\n ff <- getLine\n ww <- getLine\n\n let ans = police (conv (words ww) []) 0 0 \n putStrLn (show ans)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n"}, {"source_code": "\n\nuntreated :: [Int] -> Int\nuntreated = fst . foldl go (0, 0)\n where go (untr, officers) k | k == -1 && officers > 0 = (untr, officers-1)\n | k == -1 = (untr+1, 0)\n | otherwise = (untr, officers + k)\n \nmain = getLine >> getLine >>= (print . untreated . map read . words)\n"}, {"source_code": "main = do\n getLine\n xs <- fmap (map read . words) getLine\n\n let\n (x, _) = foldl f (0, 0) xs\n where\n f (a, b) (-1)\n | b > 0 = (a, b-1)\n | otherwise = (a+1, b)\n f (a, b) x = (a, b+x)\n\n print x\n"}, {"source_code": "main=interact$f.map read.words\nf(x:xs)=show.negate.minimum.scanl(+)0$xs"}, {"source_code": "main=interact$f.map read.words\nf (x:xs)=show.negate.minimum.scanl(+)0$0:xs"}, {"source_code": "main=interact$f.map read.words\nf (x:xs)=show.g.minimum.scanl1 (+)$xs\ng x |x<0= -x\ng x=0"}, {"source_code": "main=interact$f.map read.words\nf(x:xs)=show.negate.minimum.scanl(+)0$xs\n"}, {"source_code": "main = do\n _ <- getLine\n xs <- (map read . words) `fmap` getLine\n let f x = if x < 0 then (-1)*x else 0\n print . f . minimum . scanl1 (+) $ xs"}, {"source_code": "main = interact $ f . map read . words\nf (x:xs) = show . g . minimum . scanl1 (+) $ xs\ng x | x < 0 = -x\ng x = 0"}, {"source_code": "import Control.Applicative\nimport Data.List (foldl')\n\nmain = do\n _ <- getLine\n xs <- map read . words <$> getLine\n let\n f (n, t) x\n | x == (-1) && n == 0 = (n, t+1)\n | x == (-1) = (n-1, t)\n | otherwise = (n+x, t)\n in putStrLn . show . snd $ foldl' f (0, 0) xs\n"}, {"source_code": "solve :: [Int] -> Int -> Int\nsolve [] _ = 0\nsolve (-1:xs) 0 = 1 + solve xs 0\nsolve (-1:xs) num = solve xs (num - 1)\nsolve (x:xs) num = solve xs (num + x)\n\nmain = do\n _ <- getLine\n l <- getLine\n putStrLn $ show $ solve (map read $ words l) 0\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess [] _ ni = ni\nprocess (q:qs) np ni | q>0 = process qs (np+q) ni\n | np>0 = process qs (np-1) ni\n |otherwise = process qs np (ni+1)\n\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map read <$> words <$> getLine::IO [Integer]\n print $ process q 0 0\n"}, {"source_code": "f (crimes,officers) x \n\t| x == -1 = if officers ==0 then (crimes+1,0) else (crimes,officers-1)\n\t| otherwise = (crimes,officers+x)\n\nmain = do \n\t_ <- getLine \n\tevents <- getLine >>= return . map (read :: String -> Int). words\n\tprint . fst $ foldl f (0,0) events"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve = sum . map snd . scanl f (0, 0)\n where f (x, _) z = (max (x + z) 0, max (- x - z) 0)\n"}, {"source_code": "import Data.List (foldl')\nmain = interact $ show . fst . foldl' solve (0,0) . map read . tail . words\nsolve (c,0) (-1) = (c+1,0)\nsolve (c,p) (-1) = (c,p-1)\nsolve (c,p) q = (c,p+q)\n"}, {"source_code": "module Main where\n\nmain = interact readAndSolve\n\nreadAndSolve :: String -> String\nreadAndSolve input = show . solve . convert $ input\n\nconvert :: String -> [Int]\nconvert input = let\tnumbers = (lines input) !! 1 in \n\t\t\t\tmap read (words numbers)\n\nsolve :: [Int] -> Int\nsolve list = abs $ min 0 $ minimum . calcPrefixSums $ list\n\ncalcPrefixSums :: [Int] -> [Int]\ncalcPrefixSums = foldLP (+) 0\n\nfoldLP :: (a -> b -> a) -> a -> [b] -> [a]\nfoldLP _ _ [] = []\nfoldLP f s (x:xs) = let curS = f s x in curS : foldLP f curS xs\n\nfoldl' :: (a -> b -> a) -> a -> [b] -> a\nfoldl' _ z [] = z\nfoldl' f s (x:xs) = foldl' f (f s x) xs"}, {"source_code": "import Data.List\nstrToList = (map (read :: (String -> Integer))).words\nf xs = length $ filter (<0) $ snd $ mapAccumL (\\x y -> (max 0 (x + y), x + y)) 0 xs\nmain = do\n n <- fmap strToList getLine\n s <- fmap strToList getLine\n putStrLn $ show $ f s"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 0 xs\n where\n go !res !police ((-1):xs)\n | police > 0 = go res (police-1) xs\n | otherwise = go (res+1) 0 xs\n go res police (x:xs) = go res (police+x) xs\n go res _ _ = res\n"}, {"source_code": "main = interact $ show.fst.foldl op (0,0).map read.tail.words\n\nop :: (Int,Int) -> Int -> (Int,Int)\nop (ans,cum) num \n\t| num == -1 && cum > 0 = (ans,cum-1)\n\t| num == -1 && cum == 0 = (ans+1,cum)\n\t| otherwise = (ans,cum+num)\n"}], "negative_code": [{"source_code": "\ncountNegativesStart [] = 0\ncountNegativesStart (x:xs) = if x < 0 then (1 + countNegativesStart xs) else 0\n\ndropNegativesStart [] = []\ndropNegativesStart (x:xs) = if x < 0 then dropNegativesStart xs else (x:xs)\n\ndropPositivesEnd [] = []\ndropPositivesEnd xs = if last xs > 0 then dropPositivesEnd (init xs) else xs\n\nsolve :: [Int] -> Int\nsolve events = if si < 0 then (abs si) + countNegativesStart events\n else countNegativesStart events\n where\n si = sum (dropNegativesStart (dropPositivesEnd events))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n"}, {"source_code": "countNegativesStart [] = 0\ncountNegativesStart (x:xs) = if x < 0 then (1 + countNegativesStart xs) else 0\n\ndropNegativesStart [] = []\ndropNegativesStart (x:xs) = if x < 0 then dropNegativesStart xs else (x:xs)\n\ndropPositivesEnd [] = []\ndropPositivesEnd xs = if last xs > 0 then dropPositivesEnd (init xs) else xs\n\nsolve :: [Int] -> Int\nsolve events = if si < 0 then ( (abs si) + countNegativesStart events)\n else countNegativesStart events\n where\n si = sum (inner events)\n inner xs = dropNegativesStart (dropPositivesEnd xs)\n\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n"}, {"source_code": "main = do\n _ <- getLine\n xs <- (map read . words) `fmap` getLine\n print . (*(-1)) . minimum . scanl1 (+) $ xs"}, {"source_code": "main = do\n _ <- getLine\n xs <- (map read . words) `fmap` getLine\n let f x = if x < 0 then (-1)*x else 0\n print . f . minimum . scanr1 (+) $ xs"}, {"source_code": "module Main where\n\nmain = interact readAndSolve\n\nreadAndSolve :: String -> String\nreadAndSolve input = show . solve . convert $ input\n\nconvert :: String -> [Int]\nconvert input = let\tnumbers = (lines input) !! 1 in \n\t\t\t\tmap read (words numbers)\n\nsolve :: [Int] -> Int\nsolve = abs . minimum . calcPrefixSums\n\ncalcPrefixSums :: [Int] -> [Int]\ncalcPrefixSums = foldLP (+) 0\n\nfoldLP :: (a -> b -> a) -> a -> [b] -> [a]\nfoldLP _ _ [] = []\nfoldLP f s (x:xs) = let curS = f s x in curS : foldLP f curS xs\n\nfoldl' :: (a -> b -> a) -> a -> [b] -> a\nfoldl' _ z [] = z\nfoldl' f s (x:xs) = foldl' f (f s x) xs"}, {"source_code": "solve :: [Int] -> Int -> Int -> Int\nsolve [] _ up = up\nsolve (x:xs) rr up\n | rr >= 1 = solve xs (rr-1) up\n | otherwise = solve xs rr (up+1)\n\nprepare :: [Int] -> Int\nprepare crimes = solve crimes 0 0\n\nmain :: IO ()\nmain = interact $ show . prepare . tail . map read . words\n"}, {"source_code": "solve :: [Int] -> Int -> Int -> Int\nsolve [] _ up = up\nsolve (x : xs) rr up\n | x == -1 = if rr >= 1 then solve xs (rr - 1) up else solve xs rr (up + 1)\n | otherwise = solve xs (rr + 1) up\n\nprepare :: [Int] -> Int\nprepare crimes = solve crimes 0 0\n\nmain :: IO ()\nmain = interact $ show . prepare . tail . map read . words\n"}, {"source_code": "solve :: [Int] -> Int -> Int -> Int\nsolve [] _ up = up\nsolve (x:xs) rr up\n | rr >= 1 = solve xs (rr-1) up\n | otherwise = solve xs rr (up+1)\n\nprepare :: [Int] -> Int\nprepare crimes = solve crimes 0 0\n\nmain :: IO ()\nmain = interact $ show . prepare . map read . words\n"}], "src_uid": "af47635f631381b4578ba599a4f8b317"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn \n (m,arr) <- uniqueSort 1000000 n.listArray (0,n-1).map readInt.B.words <$> B.getLine\n print $ solve m arr\n\nsolve :: Int -> UArray Int Int -> Int\nsolve 1 _ = 0\nsolve n arr = go 0 0\n where\n !ub = unsafeAt arr (n-1)\n go !acc !i\n | i < n = let !ai = unsafeAt arr i\n step acc q = max acc $ unsafeAt memo (min 1000001 $ (q+1)*ai) - q*ai\n in go (foldl' step acc [1..ub`quot`ai]) (i+1)\n | otherwise = acc\n \n !memo = runSTUArray $ do\n memo <- newArray (0,1000001) 0 :: ST s (STUArray s Int Int)\n\n rep (unsafeAt arr 0+1) $ \\i -> do\n unsafeWrite memo i 0\n rep (n-1) $ \\i -> do\n let !ai = unsafeAt arr i\n for (ai+1) (unsafeAt arr (i+1)) $ \\j -> do\n unsafeWrite memo j ai\n let !lst = unsafeAt arr (n-1)\n for (unsafeAt arr (n-1)+1) 1000001 $ \\j -> do\n unsafeWrite memo j lst\n\n return memo\n \n\nuniqueSort :: Int -> Int -> UArray Int Int -> (Int, UArray Int Int)\nuniqueSort ub n arr = runST $ do\n inArray <- newArray (0,ub) False :: ST s (STUArray s Int Bool)\n rep n $ \\i -> do\n unsafeWrite inArray (unsafeAt arr i) True\n\n res <- newArray_ (0,n-1) :: ST s (STUArray s Int Int)\n\n let go !cnt !i\n | i <= ub = do\n flg <- unsafeRead inArray i\n if flg then unsafeWrite res cnt i >> go (cnt+1) (i+1)\n else go cnt (i+1)\n | otherwise = (,) cnt <$> unsafeFreeze res\n go 0 0 \n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nupperBound :: (Integral i, Bits i) => (i -> Bool) -> i -> i -> i\nupperBound p low high = go low high\n where\n go !low !high\n | low < high = case (low + high + 1) `unsafeShiftR` 1 of\n mid | p mid -> go mid high\n | otherwise -> go low (mid-1)\n | otherwise = low\n{-# INLINE upperBound #-}\n\nmain :: IO ()\nmain = do\n n <- readLn \n (m,arr) <- uniqueSort 1000000 n.listArray (0,n-1).map readInt.B.words <$> B.getLine\n print $ solve m arr\n\nsolve :: Int -> UArray Int Int -> Int\nsolve 1 _ = 0\nsolve n arr = go 0 0\n where\n !ub = unsafeAt arr (n-1)\n go !acc !i\n | i < n = let !ai = unsafeAt arr i\n step (acc, j) q = (acc',j')\n where\n !qai = q * ai\n !j' = upperBound (\\x -> unsafeAt arr x - qai < ai) j $ min (j+ai) (n-1)\n !acc' = max acc $ unsafeAt arr j' - qai\n in go (fst $ foldl' step (acc,i) [1..quot ub ai]) (i+1)\n | otherwise = acc\n\nuniqueSort :: Int -> Int -> UArray Int Int -> (Int, UArray Int Int)\nuniqueSort ub n arr = runST $ do\n inArray <- newArray (0,ub) False :: ST s (STUArray s Int Bool)\n rep n $ \\i -> do\n unsafeWrite inArray (unsafeAt arr i) True\n\n res <- newArray_ (0,n-1) :: ST s (STUArray s Int Int)\n\n let go !cnt !i\n | i <= ub = do\n flg <- unsafeRead inArray i\n if flg then unsafeWrite res cnt i >> go (cnt+1) (i+1)\n else go cnt (i+1)\n | otherwise = (,) cnt <$> unsafeFreeze res\n go 0 0 \n"}], "negative_code": [], "src_uid": "0ef324e3e314ea17c01aafb822e90c63"} {"source_code": "\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Map as M\nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\nfast_read_Int64 = fmap (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) BS.getLine :: IO [Int64]\n\ncitesc_nr :: String -> Int64\ncitesc_nr s = read s\ncitesc_array :: [String] -> [Int64]\ncitesc_array = map read\n\n--prefix sums\nsumlist' xx = aux xx 0\n where aux [] a = []\n aux (x:xs) a = (a+x) : aux xs (a+x)\n\n\n--pref m a = (a, if a `M.member` m then M.adjust succ a m else M.insert a 1 m)\nf v x = Map.insertWith (+) x 1 v\n\nsolve :: Map.Map Int64 Int64 -> [(Int64,Int64)]\nsolve map_frec = M.toList map_frec\n\nmain = do \n x <- getLine\n let n = (citesc_nr x) \n vector <- fast_read_Int64\n let ps = sumlist' vector\n let dp = foldl f M.empty ps :: M.Map Int64 Int64\n print $ (n-) . foldl max 1 . map snd $ solve dp \n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine, lookup)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64)\nimport Data.Map (elems, empty, lookup, insert, adjust)\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: Int -> [Int64] -> Int64\nsolve n xs = foldr go inf (zip [0..] . scanl1 (+) $ xs ++ xs) empty\n where\n inf = minimum . map snd . elems\n go (i, x) run w = case x `lookup` w of\n Nothing -> run $ insert x (i, 0) w\n Just (k, acc) -> case n < k + 1 of\n True -> run w\n False -> run $ insert x (i, acc + inc) w\n where inc = fromIntegral $ i - k - 1\n\nmain = do\n [n] <- parse <$> getLine\n getLine >>= print . solve n . map fromIntegral . parse\n"}, {"source_code": "import qualified Data.Map as M\n\nmain=interact $ show . solve . map read . words\n\nsolve :: [Integer] -> Integer\nsolve (n:xs) = (n-) . M.foldl max 1 . snd . foldl pref (0, M.empty) . take (fromIntegral n) $ xs\n\npref (cv, m) a = (nv, if nv `M.member` m then M.adjust succ nv m else M.insert nv 1 m)\n where nv = cv + a\n"}, {"source_code": "import qualified Data.Map as Map\n\nmain :: IO()\nmain = do\n sn <- getLine\n sa <- getLine\n let n = read sn\n let a = map read $ words sa\n print $ solve n a Map.empty 0 n\n\nremoveMaybe :: Maybe Int -> Int\nremoveMaybe (Just a) = a\nremoveMaybe Nothing = 0\n\nsolve :: Int -> [Integer] -> Map.Map Integer Int -> Integer -> Int -> Int\nsolve _ [] _ _ ans = ans\nsolve n (a:ax) cnt sum ans = let next_sum = sum + a\n num = 1 + (removeMaybe $ Map.lookup next_sum cnt)\n deleted = Map.delete next_sum cnt\n next_cnt = Map.insert next_sum num deleted\n in solve n ax next_cnt next_sum (min ans (n - num))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine, lookup)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64)\nimport Data.Map (elems, empty, lookup, insert)\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = foldr go (minimum . map snd . elems) ys empty\n where\n ys = zip [0..] . scanl1 (+) . map fromIntegral $ xs ++ xs :: [(Int, Int64)]\n go (i, x) run w = case x `lookup` w of\n Nothing -> run $ insert x (i, 0) w\n Just (k, acc) -> case n < k + 1 of\n True -> run w\n False -> run $ insert x (i, acc + i - k - 1) w\n\nmain = do\n [n] <- parse <$> getLine\n getLine >>= print . solve n . parse\n"}], "negative_code": [{"source_code": "import qualified Data.Map as M\n\nmain=interact $ show . solve . map read . words\n\nsolve (n:xs) = ((n-1)-) . M.foldl max 0 . snd . foldl pref (0, M.empty) . take n $ xs\n\npref (cv, m) a = (nv, if nv `M.member` m then M.adjust succ nv m else M.insert nv 0 m)\n where nv = cv + a\n"}, {"source_code": "\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Map as M\nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\n\ncitesc_nr :: String -> Int\ncitesc_nr s = read s\ncitesc_array :: [String] -> [Int]\ncitesc_array = map read\n\n--prefix sums\nsumlist' xx = aux xx 0\n where aux [] a = []\n aux (x:xs) a = (a+x) : aux xs (a+x)\n\n\n--pref m a = (a, if a `M.member` m then M.adjust succ a m else M.insert a 1 m)\nf v x = Map.insertWith (+) x 1 v\n\nsolve :: Map.Map Int Int -> [(Int,Int)]\nsolve map_frec = M.toList map_frec\n\nmain = do \n x <- getLine\n let n = (citesc_nr x) \n vector <- fast_read_Int\n let ps = sumlist' vector\n let dp = foldl f M.empty ps :: M.Map Int Int \n print $ (n-) . maximum . map snd $ solve dp \n\n"}, {"source_code": "import Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Map as M\nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\n\ncitesc_nr :: String -> Int\ncitesc_nr s = read s\ncitesc_array :: [String] -> [Int]\ncitesc_array = map read\n\n--prefix sums\nsumlist' xx = aux xx 0\n where aux [] a = []\n aux (x:xs) a = (a+x) : aux xs (a+x)\n\n\n--pref m a = (a, if a `M.member` m then M.adjust succ a m else M.insert a 1 m)\nf v x = Map.insertWith (+) x 1 v\n\nsolve :: Map.Map Int Int -> [(Int,Int)]\nsolve map_frec = M.toList map_frec\n\nmain = do \n x <- getLine\n let n = (citesc_nr x) \n vector <- fast_read_Int\n let ps = sumlist' vector\n let dp = foldl f M.empty ps :: M.Map Int Int \n print $ (n-) . foldl max 1 . map snd $ solve dp \n\n"}], "src_uid": "be12bb8148708f9ad3dc33b83b55eb1e"} {"source_code": "-- ID : 1569C (C. Jury Meeting)\n-- URL : https://codeforces.com/contest/1569/problem/C\n-- Failed to solve on my own and saw the editorial :/\n\nimport Control.Monad\n\n-- bytestring for fast IO\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\ngetInt = parseInt `fmap` BS8.getLine :: IO Int64\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int64]\nparseInt = fromIntegral . fst . fromJust . BS8.readInt\n\nmain = do\n t <- getInt\n replicateM_ (fromIntegral t) solve\n\nmagic = 998244353\nmul2 x y = (x * y) `mod` magic\n\n{- NOTE on Int64\n - \n - It's strange but when I use just Int type, codeforces and my desktop give different results for the input:\n - n = 74\n - as = 9 3 10 8 6 6 1 6 9 3 7 3 2 8 1 5 8 4 6 4 1 6 5 6 10 3 6 6 6 4 9 5 8 7 2 1 6 2 4 9 10 9 5 4 7 5 7 2 10 10 1 5 2 4 1 7 7 3 8 10 2 5 8 4 3 9 2 9 9 8 6 8 4 5\n - The answer is 420779088 and my desktop gives that number but codeforces gives 939628924.\n - Switching every Int to Int64 fixes the problem but I don't know why? Even the solution in the editorial uses int, not int64_t.\n -}\nsolve = do\n n <- getInt\n as <- getInts\n let maxima = maximum as\n let k = fromIntegral $ length $ filter (== (maxima - 1)) as\n let maxima_count = length $ filter (== maxima) as\n let x = foldl1 mul2 [1..n]\n let y = foldl1 mul2 [m | m <- [1..n], m /= (k + 1)]\n let answer = if maxima_count == 1 then (x - y + magic) `mod` magic else x\n print answer\n", "positive_code": [{"source_code": "-- ID : 1569C (C. Jury Meeting)\n-- URL : https://codeforces.com/contest/1569/problem/C\n\nimport Control.Monad\n\n-- bytestring for fast IO\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\ngetInt = parseInt `fmap` BS8.getLine :: IO Int64\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int64]\nparseInt = fromIntegral . fst . fromJust . BS8.readInt\n\nmain = do\n t <- getInt\n replicateM_ (fromIntegral t) (solve (t == 1000))\n\nmagic = 998244353\nmul2 x y = (x * y) `mod` magic\n\nsolve dbg = do\n n <- getInt\n as <- getInts\n let maxima = maximum as\n let k = fromIntegral $ length $ filter (== (maxima - 1)) as\n let maxima_count = length $ filter (== maxima) as\n let x = foldl1 mul2 [1..n]\n let y = foldl1 mul2 [m | m <- [1..n], m /= (k + 1)]\n let answer = if maxima_count == 1 then (x - y + magic) `mod` magic else x\n print answer\n {-\n if dbg then do\n putStrLn \"=== debug ===\"\n putStrLn (\"maxima: \" ++ show maxima)\n putStrLn (\"k: \" ++ show k)\n putStrLn (\"maxima_count: \" ++ show maxima_count)\n putStrLn (\"x: \" ++ show x)\n putStrLn (\"y: \" ++ show y)\n else do\n return ()\n -}\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = numberOf int\n\n-- output :: Output -> C.ByteString\noutput = showB\n\n-- solve :: Input -> Output\nsolve xs\n | f /= 1 = factorial ! n\n | otherwise = factorial ! n *% (fi g /% fi (f + g))\n where\n n = length xs\n m = maximum xs\n f = count m xs\n g = count (m - 1) xs\n\nmaxn :: (Integral a) => a\nmaxn = 2 * 10 ^ 5 + 5\n\nfactorial :: UArray Int Int64\nfactorial = listArray (0, maxn) $ scanl (*%) 1 [1 .. maxn]\n\nmodv :: Int64\nmodv = 998244353\n\n(*%), (/%) :: Int64 -> Int64 -> Int64\nu *% v = (u * v) `mod` modv\nu /% v = u *% modInv v\n\nmodInv :: Int64 -> Int64\nmodInv a = modPow a (modv - 2)\n\nmodPow :: Int64 -> Int64 -> Int64\nmodPow a n\n | n == 0 = 1\n | odd n = a *% modPow a (n - 1)\n | otherwise = let a' = modPow a (n `div` 2) in a' *% a'\n\n-------------------------- Template ------------------------------------------\nfi = fromIntegral\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\n\r\nm :: Int64\r\nm = 998244353\r\n\r\nnewtype MInt = MInt {toInt64 :: Int64}\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b\r\n MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger i = MInt $ fromInteger i `mod` m\r\n\r\ninstance Enum MInt where\r\n toEnum = fromIntegral\r\n fromEnum = fromIntegral . toInt64\r\n\r\ninv :: MInt -> MInt\r\ninv a = a ^ (m - 2)\r\n\r\nfac :: Array Int MInt\r\nfac = listArray (0, 2 * 10^5) xs where xs = 1 : zipWith (*) [1..] xs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn\r\n as <- readMany\r\n let m = maximum as\r\n mc = length $ filter (==m) as\r\n bs = filter (/=m) as\r\n m' = maximum bs\r\n mc'= length $ filter (==m') bs\r\n res | mc > 1 = fac!n\r\n | m - m' > 1 = 0\r\n | otherwise = fac!mc' * fromIntegral mc' * fac!n * inv (fac!(mc' + 1))\r\n print $ toInt64 res\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\n\r\nm :: Int64\r\nm = 998244353\r\n\r\nnewtype MInt = MInt {toInt64 :: Int64} deriving Show\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b\r\n MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger i = MInt $ fromInteger i `mod` m\r\n\r\ninstance Enum MInt where\r\n toEnum = fromIntegral\r\n fromEnum = fromIntegral . toInt64\r\n\r\ninv :: MInt -> MInt\r\ninv a = a ^ (m - 2)\r\n\r\nlim :: Int\r\nlim = 5 * 10^5\r\n\r\nfac :: Array Int MInt\r\nfac = listArray (0, lim) xs where xs = 1 : zipWith (*) [1..] xs\r\n\r\nbinomMod :: Int -> Int -> MInt\r\nbinomMod = ch where\r\n ifac = listArray (0, lim) $ map inv $ elems fac\r\n ch a b | b < 0 || a < b = 0\r\n ch a b = fac!a * ifac!b * ifac!(a - b)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn\r\n as <- readMany\r\n let m = maximum as\r\n mc = length $ filter (==m) as\r\n bs = filter (/=m) as\r\n m' = maximum bs\r\n mc' = length $ filter (==m') bs\r\n res | mc > 1 = fac!n\r\n | m - m' > 1 = 0\r\n | otherwise = fac!mc' * fromIntegral mc' * fac!(n - mc' - 1) * binomMod n (mc' + 1)\r\n print $ toInt64 res\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.Int\nimport Data.List\nimport Data.Semigroup\n\n\np :: Int64\np = 998244353\n\n(*!) :: Int64 -> Int64 -> Int64\ninfixr 7 *!\nx *! y = rem (x * y) p\n\nnewtype ModP = ModP { unModP :: Int64 }\ninstance Semigroup ModP where\n ModP x <> ModP y = ModP $ x *! y\ninv :: Int64 -> Int64\ninv = unModP . stimes (p - 2) . ModP\n\nfactorial :: Int64 -> Int64\nfactorial n = foldl' (*!) 1 [1 .. n]\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n a <- getInts n\n let\n x : y : _ = reverse $ sort a\n opts = filter (>= y) a\n k = fromIntegral $ length opts\n n64 = fromIntegral n\n ans = case x - y of\n 0 -> factorial n64\n 1 -> factorial n64 *! (k - 1) *! inv k\n _ -> 0\n pure $ putInt64s [ans]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "-- ID : 1569C (C. Jury Meeting)\n-- URL : https://codeforces.com/contest/1569/problem/C\n\nimport Control.Monad\n\n-- bytestring for fast IO\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\ngetInt = parseInt `fmap` BS8.getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fromIntegral . fst . fromJust . BS8.readInt\n\nmain = do\n t <- getInt\n replicateM_ t (solve (t == 1000))\n\nmagic = 998244353\nmul2 x y = (x * y) `mod` magic\n\nsolve dbg = do\n n <- getInt\n as <- getInts\n let maxima = maximum as\n let k = length $ filter (== (maxima - 1)) as\n let maxima_count = length $ filter (== maxima) as\n let x = foldl1 mul2 [1..n]\n let y = foldl1 mul2 [m | m <- [1..n], m /= (k + 1)]\n let answer = if maxima_count == 1 then (x - y + magic) `mod` magic else x\n print answer\n if dbg then do\n putStrLn \"=== debug ===\"\n putStrLn (\"maxima: \" ++ show maxima)\n putStrLn (\"k: \" ++ show k)\n putStrLn (\"maxima_count: \" ++ show maxima_count)\n putStrLn (\"x: \" ++ show x)\n putStrLn (\"y: \" ++ show y)\n else do\n return ()\n"}, {"source_code": "-- ID : 1569C (C. Jury Meeting)\n-- URL : https://codeforces.com/contest/1569/problem/C\n\nimport Control.Monad\n\n-- bytestring for fast IO\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\ngetInt = parseInt `fmap` BS8.getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fromIntegral . fst . fromJust . BS8.readInt\n\nmain = do\n t <- getInt\n replicateM_ t solve\n\nmagic = 998244353\nmul2 x y = (x * y) `mod` magic\n\nsolve = do\n n <- getInt\n as <- getInts\n let maxima = maximum as\n let k = length $ filter (== (maxima - 1)) as\n let maxima_count = length $ filter (== maxima) as\n let x = foldl1 mul2 [1..n]\n let y = foldl1 mul2 [m | m <- [1..n], m /= (k + 1)]\n let answer = if maxima_count == 1 then (x - y + magic) `mod` magic else x\n print answer\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = numberOf int\n\n-- output :: Output -> C.ByteString\noutput = showB\n\n-- solve :: Input -> Output\nsolve xs\n | f == n = factorial ! n\n | g == 0 = 0\n | otherwise =\n let pick = fi g /% fi (f + g)\n in factorial ! n *% pick\n where\n n = length xs\n m = maximum xs\n f = count m xs\n g = count (m - 1) xs\n\nfactorial :: UArray Int Int64\nfactorial = listArray (0, 10 ^ 5) $ scanl (*%) 1 [1 .. 10 ^ 5]\n\nmodv :: Int64\nmodv = 998244353\n\n(*%), (/%) :: Int64 -> Int64 -> Int64\nu *% v = (u * v) `mod` modv\nu /% v = u *% modInv v\n\nmodInv :: Int64 -> Int64\nmodInv a = modPow a (modv - 2)\n\nmodPow :: Int64 -> Int64 -> Int64\nmodPow a n\n | n == 0 = 1\n | odd n = a *% modPow a (n - 1)\n | otherwise = let a' = modPow a (n `div` 2) in a' *% a'\n\n-------------------------- Template ------------------------------------------\nfi = fromIntegral\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "81d4867a7e5128baf316193e9cc3dfce"} {"source_code": "answer a b = (a+b)/(2*kb+2)\n where k = floor (((a/b)-1.0)/2.0)\n kb = (fromIntegral k)::Double\n \nmain = do\n w <- getLine\n let [a,b] = [read n::Double| n <- (words w)]\n if a < b\n then putStrLn \"-1\"\n else putStrLn $ show $ answer a b\n", "positive_code": [{"source_code": "import Data.Ratio ((%))\nimport Control.Applicative ((<$>))\n\nsolve :: Integer -> Integer -> Double\nsolve a b\n | x == -1 = fromRational y\n | y == -1 = fromRational x\n | otherwise = fromRational $ min x y\n where\n x = if k < 0 then -1 else if k == 0 then a % 1 else (a - b) % (2 * k)\n where k = floor $ (a - b) % (2 * b)\n\n y = if k < 1 then -1 else (a + b) % (2 * k)\n where k = floor $ (a + b) % (2 * b)\n\nmain = do\n a:b:_ <- map read . words <$> getLine\n print $ solve a b\n"}, {"source_code": "-- Codeforces 578A\n\nmain :: IO ()\nmain = getLine >>= print . solve . map read . words where\n solve :: (RealFrac a) => [a] -> a\n solve [x, y]\n | x < y = -1\n | otherwise = (x+y)/2/(fromIntegral ((fromIntegral $ floor (x+y)) `div` (fromIntegral $ floor (2*y))))\n"}], "negative_code": [{"source_code": "import Data.Ratio ((%))\nimport Control.Applicative ((<$>))\n\nsolve :: Integer -> Integer -> Double\nsolve a b\n | a == b = fromInteger a\n | k < 1 || x == 0 && y == 0 = -1\n | x == 0 = fromRational y\n | y == 0 = fromRational x\n | otherwise = fromRational $ min x y\n where\n k = floor $ (a - b) % (2 * b)\n x = (a - b) % (2 * k)\n y = (a + b) % (2 * k + 2)\n\nmain = do\n a:b:_ <- map read . words <$> getLine\n print $ solve a b\n"}, {"source_code": "import Data.Ratio ((%))\nimport Control.Applicative ((<$>))\n\nsolve :: Integer -> Integer -> Double\nsolve a b\n | k < 1 || x == 0 && y == 0 = -1\n | x == 0 = fromRational y\n | y == 0 = fromRational x\n | otherwise = fromRational $ min x y\n where\n k = floor $ (a - b) % (2 * b)\n x = (a - b) % (2 * k)\n y = (a + b) % (2 * k + 2)\n\nmain = do\n a:b:_ <- map read . words <$> getLine\n print $ solve a b\n"}], "src_uid": "1bcf130890495bcca67b4b0418476119"} {"source_code": "import Control.Applicative\nimport Control.Monad\n\n\n\nparse :: [String] -> [[Integer]]\nparse = map (\\l -> map read . words $ l)\n\nsolve :: [Integer] -> Integer\nsolve (a:b:n:[])\n | a>n || b>n = 0\n | a<=b = 1 + solve [(a+b), b, n]\n | otherwise = 1 + solve [a, (a+b), n]\n\nmain :: IO ()\nmain = do\n n <- getLine\n content <- replicateM (read n :: Int) getLine\n putStrLn . unlines . map show . map solve . parse $ content\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n [a,b,n] <- (map read.words) <$> getLine\n print $ solve a b n\n\nsolve :: Int -> Int -> Int -> Int\nsolve a b n = f a' b' n\n where\n a' = min a b\n b' = max a b\n f x y m\n | y>m = 0\n | otherwise = 1 + f y (x+y) m\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Char\nimport Control.Arrow\nimport Data.Bits\n\n\nmain = (>>=) (readLn @Int) $ flip replicateM_ $ do\n [a, b, n] <- map (read @Int) . words <$> getLine\n print $ solve a b n 0\n where\n solve a b n k | a > n || b > n = k\n | otherwise = solve (max a b) (a + b) n (k + 1)\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Tuple\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\n-- assuming x <= y\n_solve !acc !x !y tgt\n | y > tgt = acc\n | otherwise = _solve (acc + 1) y (x+y) tgt\nsolve x y tgt = _solve 0 (min x y) (max x y) tgt\n\nmain = do\n input <- getContents\n let _:tokens = read <$> split input :: [Int]\n res = tokens |> unfoldr (\\case\n [] -> Nothing\n a:b:n:rest -> Just (solve a b n, rest)\n )\n sequence_ $ putStrLn <$> (show <$> res)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\nprocess s n m k | n>k || m>k = s\n | n words <$> getLine ::IO [Int]\n\t\tprint $ process 0 n m k\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Monad\n\nbrute :: Int->Int->Int->Int->Int\nbrute a b n acc\n | a > n || b > n = acc\n | a > b = brute a (b + a) n (acc + 1)\n | otherwise = brute (a + b) b n (acc + 1)\n\nsolveTest = do\n [a, b, n] <- (map read) . words <$>getLine\n putStrLn . show $ brute a b n 0\n\nmain = do\n t <- read <$> getLine\n replicateM_ t solveTest\n"}], "negative_code": [], "src_uid": "5999a4e2fac29b5f4804639f6e949279"} {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe, catMaybes)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate, transpose)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.String (fromString)\nimport Data.Bits (shift)\nimport Data.Binary (encode, decode)\n\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = ([Int], Int)\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ show xs\n\nparse :: IO Domain\nparse = do\n [n, k] <- readChar8\n xs <- readChar8\n return (xs, k)\n\ncompute :: [Int] -> Int\ncompute ys = go 1 ys\n where \n go :: Int -> [Int] -> Int\n go _ [] = 0\n go n (x:xs) \n | n > 31 = 0\n | otherwise = x `div` 2 ^ n + go (n+1) xs\n\nsolve :: Solver\nsolve (xs, k) = ans\n where \n yss = zipWith (flip (-) . (k*)) [0..] $ scanl (+) 0 xs\n rss = compute <$> scanr (:) [] xs\n ans = maximum $ zipWith (+) rss yss\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map as Map\r\n\r\nsolve :: [Int] -> Int -> Int -> Int\r\nsolve arr n k =\r\n solve' arr n k 0 0 0\r\n\r\nsolve' [] n k i curSum acc =\r\n if acc > me then acc else me\r\n where me = curSum - n * k\r\n\r\nsolve' arr n k i curSum acc =\r\n solve' (tail arr) n k (i+1) (curSum + (head arr)) mx\r\n where\r\n elems = zip [1..] $ take 32 arr\r\n halve = \\(i, v) -> v `div` (2 ^ i)\r\n me = curSum + (sum $ map halve elems) - k * i\r\n mx = if me > acc then me else acc\r\n \r\n\r\ntestcase 0 = return ()\r\ntestcase t = do\r\n (n:k:_) <- map (read :: String -> Int) <$> words <$> getLine\r\n arr <- map (read :: String -> Int) <$> words <$> getLine\r\n putStrLn $ show $ solve arr n k\r\n testcase (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n testcase t\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve arr n k =\n solve' arr n k 0 0\n\nsolve' [] n k i curSum = curSum - n * k\nsolve' arr n k i curSum =\n (if me - i * k > you\n then me - i * k\n else you)\n where\n elems = zip [1..] $ take 32 arr\n halve = \\(i, v) -> v `div` (2 ^ i)\n me = curSum + (sum $ map halve elems)\n you = solve' (tail arr) n k (i+1) (curSum + (head arr))\n \n\ntestcase 0 = return ()\ntestcase t = do\n (n:k:_) <- map (read :: String -> Int) <$> words <$> getLine\n arr <- map (read :: String -> Int) <$> words <$> getLine\n putStrLn $ show $ solve arr n k\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}], "negative_code": [], "src_uid": "9fcc55a137b5ff021fdc8e1e867ce856"} {"source_code": "import Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printSolve\r\n\r\nprintSolve = do \r\n n <- readLn :: IO Int\r\n a <- getLine\r\n b <- getLine\r\n putStrLn $ checkPossible ((tail . init) a) ((tail . init) b)\r\n\r\n\r\ncheckPossible [] [] = \"YES\"\r\ncheckPossible (x:xs) (y:ys)\r\n | x == '1' && y == '1' = \"NO\"\r\n | otherwise = checkPossible xs ys\r\n", "positive_code": [{"source_code": "import Data.Function (on)\r\n\r\nyesNo False = \"NO\"\r\nyesNo True = \"YES\"\r\n\r\nsolve input = let (t:tasks) = lines input\r\n get_ans [] = []\r\n get_ans (n:s1:s2:xs) = task_ans s1 s2 : get_ans xs where\r\n task_ans s1 s2 = (and $ zipWith ((||) `on` (=='0')) (init s1) (init s2)) && last s2 == '0'\r\n in unlines . map yesNo $ get_ans tasks\r\n\r\n\r\nmain = interact solve"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: [(Char,Char)] -> String\ncalc str =\n let ans = all (\\(i,j) ->\n (i=='0') || (j=='0')\n ) str\n in\n if ans then \"YES\" else \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n unused <- getLine\n line1 <- getLine\n line2 <- getLine\n putStrLn $ calc $ zip line1 line2\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\ndata Input = Input {m :: Int, row1 :: B8.ByteString, row2 :: B8.ByteString}\r\ndata Output = YES | NO deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input _ xs ys) = maybe YES (const NO) $ L.find (==('1','1')) $ B8.zip xs ys\r\n\r\n\r\n-- gives a State(T) monad which when run gives Input\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[m] <- getIntegrals 1\r\n row1 <- state getNext\r\n row2 <- state getNext\r\n return $ Input m row1 row2\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go NO = str \"NO\" <> nl\r\n go (YES) = str \"YES\" <> nl --kkmconcat $ (<>nl) <$> [str \"Yes\", dec l, (mconcat $ fmap ((<> sp).dec) xs)]\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n----------------------------- library -------------------------------\r\nmodp :: Integral t=>t->t\r\nmodp = (`mod` (10^9+7))\r\n\r\nfastPow :: Integral t=>(t->t)->t->t->t\r\nfastPow modf base' p' = go base' p' where\r\n go base 0 = base\r\n go base p = go (base`times`base) (p`div`2) `times` base^(p`mod`2)\r\n times = (modf.).(*)\r\n\r\nprimeFac :: Integral t=> t -> [(t,Int)]\r\nprimeFac = map (\\xs-> (head xs,length xs)).L.group.tryDiv 2 where\r\n tryDiv d n\r\n | n `mod` d == 0 = d : tryDiv d (n `div` d)\r\n | n == 1 = []\r\n | d*d < n = tryDiv (d+1+d`mod`2) n\r\n | otherwise = tryDiv n n\r\n\r\numakeset xs = (M.fromList (zip xs xs), M.fromList (zip xs (repeat 0)))\r\nufind uf@(parents,ranks) x = if parents M.! x == x then x else ufind uf (parents M.! x)\r\nuunion uf@(parents, ranks) x y = if fx==fy then (False,uf) else (True, (parents1, ranks1)) where\r\n (fx, fy) = (ufind uf x, ufind uf y)\r\n [(r0,f0), (r1,f1)] = L.sort [(ranks M.! fx, fx), (ranks M.! fy, fy)]\r\n parents1 = M.insert f0 f1 parents\r\n ranks1 = if r0 /= r1 then ranks else M.insert f1 (r1+1) ranks\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n ~[nTc] <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n\r\nsolve = do\r\n n <- readLn :: IO Int\r\n s0 <- getLine\r\n s1 <- getLine\r\n let s = zip s0 s1\r\n let block = ('1', '1') `elem` s\r\n putStrLn $ if block\r\n then \"NO\"\r\n else \"YES\"\r\n"}], "negative_code": [], "src_uid": "fefec879efd4f524de00684adee7cd19"} {"source_code": "main :: IO ()\nmain = print . solve 0 0 . tail . map read . words =<< getContents\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve sum single [_] = sum + (single + 1) `div` 2\nsolve sum single (k:w:ws) = let pockets = (w + k - 1) `div` k\n in solve (sum + pockets `div` 2) (single + pockets `mod` 2) (k:ws)\n", "positive_code": [{"source_code": "import Data.List( sort)\nimport Control.Applicative( (<$>))\nimport Control.Monad.State( evalState, get, modify)\nmain = do\n [_n_, k_] <- map read . words <$> getLine\n ws_ <- map read . words <$> getLine\n print $ slotTakingStep 2 k_ $ sort ws_\n\n\nslotTakingStep numSlots slotSize list = (process list)\n\t\t\t\t\t `evalState` (0,numSlots)\n where\n stepSize = numSlots * slotSize\n\n process []\t = do\n\t (value,idleSlots) <- get\n\t return $ value + (if idleSlots==numSlots then 0 else 1)\n process (e:es) = do\n\tlet\n\t modifySlot f = modify (f <$>)\n\t modifyValue f = modify $ \\(value, idles) ->\n\t\t\t\t\t (f value, idles)\n\t getIdleSlots = snd <$> get\n\n\tidleSlots <- getIdleSlots\n\tif idleSlots==numSlots \n\tthen case e `quotRem` stepSize of\n\t\t(0, stepRem)\t -> do\n\t\t let\n\t\t\t(q,r) = stepRem `quotRem` slotSize\n\t\t\tslotsNeeded =\tif r==0 then q else q+1\n\t\t if numSlots==slotsNeeded\n\t\t then do\n\t\t\tmodifyValue (+1)\n\t\t\tprocess es\n\t\t else do\n\t\t\tmodifySlot (subtract slotsNeeded)\n\t\t\tprocess es\n\n\t\t(steps, 0)\t-> do\n\t\t\t\t modifyValue (+steps)\n\t\t\t\t process es\n\t\t(steps,stepRem) -> do\n\t\t\t\t modifyValue (+steps)\n\t\t\t\t process (stepRem:es)\n\telse let\n\t\t(q,r) = e `quotRem` slotSize\n\t\tslotsNeeded = if r==0 then q else q+1\n\t\tflushSlot = modifySlot (const numSlots)\n\n\t in if idleSlots < slotsNeeded\n\t then do\n\t\tflushSlot\n\t\tmodifyValue (+1)\n\t\tprocess (e - idleSlots * slotSize :es)\n\t else if idleSlots==slotsNeeded\n\t\tthen do\n\t\t flushSlot\n\t\t modifyValue (+1)\n\t\t process es\n\t\telse do\n\t\t modifySlot (subtract slotsNeeded)\n\t\t process es\n"}, {"source_code": "import Control.Applicative( (<$>))\nmain = do\n [_n_, k_] <- map read . words <$> getLine\n ws_ <- map read . words <$> getLine\n print $ slotTakingStep 2 k_ ws_\n\n\nslotTakingStep numSlots szSlot list =\n let\n\tdivBox i k = 1 + ((i-1)`div`k)\n\tboxes = sum $ (`divBox` szSlot) <$> list\n in\n\tboxes `divBox` numSlots\n"}, {"source_code": "import Data.List( sort)\nimport Control.Applicative( (<$>))\nimport Control.Monad.Reader( runReader, ask, Reader)\nmain = do\n [_n_, k_] <- map read . words <$> getLine\n ws_ <- map read . words <$> getLine\n print $ slotTakingStep 2 k_ $ sort ws_\n\n\nslotTakingStep\t::Integral i\n\t\t=> Int -> i -> [i] -> i\nslotTakingStep numSlots szSlot list = process 0 list\n where\n process step [] = step\n process step [n] =\n\tlet\n\t (q,r) = n `quotRem` (fromIntegral numSlots * szSlot)\n\tin\n\t step + (if r==0 then q else q+1)\n\n process step list =\n\tlet\n\t (h:tl, remain) = splitAt numSlots list\n\t (q,r) = h `quotRem` szSlot\n\t q' =\tif r==0 then q else q+1\n\t processedSlot = (subtract $ q' * szSlot) <$> tl\n\t positiveFiltered = dropWhile (<=0) processedSlot\n\tin\n\t process (step+q') (positiveFiltered++remain)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\nreadint = fst. fromJust . C.readInt\n\nddiv k x | x `mod` k == 0 = x `div` k\n | otherwise = x `div` k + 1\n\nmain = do\n (map readint . C.words -> [n, k]) <- B.getLine\n (map readint . C.words -> xs) <- B.getLine\n putStrLn $ show $ ddiv 2 (sum (map (ddiv k) xs))\n"}, {"source_code": "import Control.Applicative\n\nsolve _ [] = 0\nsolve k (l:ls) = if l<=k then 1+solve k ls else ceiling (l/k)+solve k ls \n\nmain = do \n [n,k] <- map read.words <$> getLine\n suma <- map read.words <$> getLine\n putStrLn.show $ ceiling (fromInteger (solve k suma)/2)\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nrd x = read x::Integer\ngetNumbers=map rd.words\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=getNumbers x\n\tnum=getNumbers y\ndivm x k=(\\(a,b)->[a,b])$ quotRem x k\nsolve x k=(\\(x,y)->x+sum(divm y 2)) $ foldr (\\(a,b) (x,y)->(a+x,b+y)) (0,0) pairs\n\twhere\n\t\tones n\n\t\t\t|n==0 = 0\n\t\t\t|n>k = 2\n\t\t\t|otherwise = 1\n\t\tf n k=(a,ones b) where\n\t\t\t[a,b]=divm n (2*k)\n\t\tpairs = map (\\n->f n k) x\n\t\t\n\t\t\n\t\t\nres (k,x) = solve x k\n\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "main = getContents >>= print . solve 0 . map read . words\n\nsolve rtn (n:k:ws)\n |null ws = (rtn + 1) `div` 2\n |otherwise = solve (rtn + ((head ws + k - 1)`div` k)) (n:k:(tail ws))\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nrd x = read x::Integer\ngetNumbers=map rd.words\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=getNumbers x\n\tnum=getNumbers y\n\nsolve x k=(\\(x,y)->x+(div y 2)+(mod y 2)) $ foldr (\\(a,b) (x,y)->(a+x,b+y)) (0,0) pairs\n\twhere\n\t\tones n\n\t\t\t|n==0 = 0\n\t\t\t|n>k = 2\n\t\t\t|otherwise = 1\n\t\tpairs = map (\\n->(div n (2*k),ones (mod n (2*k)))) x\n\t\nres (k,x) = solve x k\n\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, k ] <- readInts\n\tas <- getList\n\tprint $ ( `div` 2 ) $ succ $ sum $ map ( \\m -> ( m + k - 1 ) `div` k ) as"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\n\nmain = getInts >>= \\[n, k] -> getInts >>= print . ql 2. sum . fmap (ql k) where\n ql k x = quot (x + k - 1) k\n getInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nsrt x=reverse $ sort x\n\ntakeMax n k\n\t|n>k = n-k\n\t|otherwise = 0\n\nsolve [] k day = day\nsolve [x] k day\n\t|mod x (2*k) ==0 = day + (div x (2*k))\n\t|otherwise = day + (div x (2*k) + 1)\nsolve (x:y:xs) k day\n\t|x==0 && y==0 = solve xs k day\n\t|x==0 = solve (y:xs) k day\n\t|y==0 = solve (x:xs) k day\n\t|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))\n\t|y>=2*k = solve (x:(mod y (2*k)):xs) k (day+(div y (2*k)))\n\t|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)\n\t\nres (k,x) = solve (srt x) k 0\n\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=map (\\n->read n::Integer) $ words x\n\tnum=map (\\n->read n::Integer) $ words y\n\n\t\nmain=interact$show.res.extract.lines"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nsrt x=reverse $ sort x\n\ntakeMax n k\n\t|n>k = n-k\n\t|otherwise = 0\n\nsolve [x] k day\n\t|mod x (2*k) ==0 = day + (div x (2*k))\n\t|otherwise = day + (div x (2*k) + 1)\nsolve (x:y:xs) k day\n\t|x==0 = solve (y:xs) k day\n\t|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))\n\t|y>=2*k && (mod y (2*k))/=0 = solve (x:(mod y (2*k)):xs) k (day+(div y (2*k)))\n\t|y>=2*k = solve (x:xs) k (day+(div y (2*k)))\n\t|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)\n\t\nres (k,x) = solve (srt x) k 0\n\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=map (\\n->read n::Integer) $ words x\n\tnum=map (\\n->read n::Integer) $ words y\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nsrt x=reverse $ sort x\n\ntakeMax n k\n\t|n>k = n-k\n\t|otherwise = 0\n\nsolve [x] k day\n\t|mod x k ==0 = day + (div x k)\n\t|otherwise = day + (div x k + 1)\nsolve (x:y:xs) k day\n\t|x==0 = solve (y:xs) k day\n\t|x>=2*k = solve ((mod x k):y:xs) k (day+(div x (2*k)))\n\t|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)\n\t\nres (k,x) = solve (srt x) k 0\n\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=map (\\n->read n::Integer) $ words x\n\tnum=map (\\n->read n::Integer) $ words y\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nsrt x=reverse $ sort x\n\ntakeMax n k\n\t|n>k = n-k\n\t|otherwise = 0\n\nsolve [x] k day\n\t|mod x (2*k) ==0 = day + (div x (2*k))\n\t|otherwise = day + (div x (2*k) + 1)\nsolve (x:y:xs) k day\n\t|x==0 = solve (y:xs) k day\n\t|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))\n\t|y>=2*k = solve (x:(mod y (2*k)):xs) k (day+(div y (2*k)))\n\t|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)\n\t\nres (k,x) = solve (srt x) k 0\n\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=map (\\n->read n::Integer) $ words x\n\tnum=map (\\n->read n::Integer) $ words y\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nrd x = read x::Integer\ngetNumbers=map rd.words\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=getNumbers x\n\tnum=getNumbers y\n\nsolve x k=foldr (\\(_,b) n->n+b) 0 pairs\n\twhere\n\t\tones n\n\t\t\t|n==0 = 0\n\t\t\t|n>k = 2\n\t\t\t|otherwise = 1\n\t\tpairs = map (\\n->(div n (2*k),ones (mod n (2*k)))) x\n\t\nres (k,x) = solve x k\n\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nsrt x=reverse $ sort x\n\ntakeMax n k\n\t|n>k = n-k\n\t|otherwise = 0\n\nsolve [x] k day\n\t|mod x k ==0 = day + (div x k)\n\t|otherwise = day + (div x k + 1)\nsolve (x:y:xs) k day\n\t|x==0 = solve (y:xs) k day\n\t|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))\n\t|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)\n\t\nres (k,x) = solve (srt x) k 0\n\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=map (\\n->read n::Integer) $ words x\n\tnum=map (\\n->read n::Integer) $ words y\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nsrt x=reverse $ sort x\n\ntakeMax n k\n\t|n>k = n-k\n\t|otherwise = 0\n\nsolve [x] k day\n\t|mod x (2*k) ==0 = day + (div x (2*k))\n\t|otherwise = day + (div x (2*k) + 1)\nsolve (x:y:xs) k day\n\t|x==0 = solve (y:xs) k day\n\t|x>=2*k = solve ((mod x (2*k)):y:xs) k (day+(div x (2*k)))\n\t|otherwise = solve ((takeMax x k):(takeMax y k):xs) k (day+1)\n\t\nres (k,x) = solve (srt x) k 0\n\nextract (x:y:_) = (k,num) where\n\t(_:k:_)=map (\\n->read n::Integer) $ words x\n\tnum=map (\\n->read n::Integer) $ words y\n\n\t\nmain=interact$show.res.extract.lines"}, {"source_code": "import Data.List( sortBy)\nimport Control.Applicative( (<$>))\nimport Data.Bool( bool)\nmain = do\n [n_, k_] <- map read . words <$> getLine\n ws <- map read . words <$> getLine\n let\n\tsortedWs = sortBy (flip compare) ws\n\tk2 = 2*k_\n\tcollect day [] = day\n\tcollect day [w] = let\n\t\t\t\t(qu,re) = w`quotRem`k2\n\t\t\t\taddition = bool 0 1 (re/=0)\n\t\t\t in\n\t\t\t day + qu + addition\n\tcollect day (w1:w2:ws)= let\n\t\t\t\t(q,r) = w1`quotRem`k2\n\t\t\t\tnextW = w2-k_\n\t in if k_<=r\n\t then collect (day+q+1) (w2:ws)\n\t else if 0 < nextW\n\t\t then collect (day+q+1) (nextW:ws)\n\t\t else collect (day+q+1) ws\n print $ collect 0 sortedWs\n"}, {"source_code": "import Data.List( sortBy)\nimport Control.Applicative( (<$>))\nimport Data.Bool( bool)\nmain = do\n [n_, k_] <- map read . words <$> getLine\n ws <- map read . words <$> getLine\n let\n\tsortedWs = sortBy (flip compare) ws\n\tk2 = 2*k_\n\tcollect day [] = day\n\tcollect day [w] = let\n\t\t\t (q,r) = w`quotRem`k2\n\t\t\tin\n\t\t\t day + q + (if r/=0 then 1 else 0)\n\t\t\t \n\tcollect day (w1:w2:ws) = let\n\t\t\t\t w1' = max w1 w2\n\t\t\t\t w2' = min w1 w2\n\t\t\t\t (q,r) = w2'`quotRem`k_\n\t\t\t\t head' = w1' - q * k_\n\t\tin case (q,r) of\n\t\t (0,r) -> if w1'==w2'\n\t\t\t\tthen collect (day+1) ws\n\t\t\t\telse collect (day+1) ((w1'-k_):ws)\n\t\t (q,0) -> if w1'==w2'\n\t\t\t\tthen collect (day+q) ws\n\t\t\t\telse collect (day+q) (head':ws)\n\t\t (q,r) -> collect (day+q) (head':r:ws)\n print $ collect 0 sortedWs\n"}], "src_uid": "3992602be20a386f0ec57c51e14b39c5"} {"source_code": "import System.IO\n\nreadType (\"int\":xs) acc = (\"int\":acc, xs)\nreadType (\"pair\":xs) acc = let (la, lc) = readType xs (\"<\":\"pair\":acc); \n (ra, rc) = readType lc (\",\":la)\n in (\">\":ra, rc)\nreadType _ _ = ([\"!\"], [])\n\ncheckElem xs = if elem \"!\" xs then [\"Error occurred\"] else xs\ncheckLen (res, xs) = if xs /= [] then ([\"Error occurred\"], []) else (res, xs)\n\nsolve text = concat $ reverse $ checkElem $ fst $ checkLen $ readType lexs []\n where lexs = words text\n\nmain = do \n-- content <- readFile \"input.txt\"\n-- ([intCount, ttypes]) <- return $ lines content\n ttypes <- getLine >> getLine\n putStrLn (solve ttypes)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\ndata Type = IntT | PairT Type Type\n\nprintType :: Type -> IO ()\nprintType IntT = putStr \"int\"\nprintType (PairT t1 t2) = do\n putStr \"pair<\"\n printType t1\n putStr \",\"\n printType t2\n putStr \">\"\n\ndata Parser a = Parser {run :: String -> (Maybe a, String)}\ninstance Monad Parser where\n return x = Parser $ \\inp -> (Just x, inp)\n p >>= q = Parser $ \\inp ->\n case run p inp of\n (Nothing, _) -> (Nothing, \"\")\n (Just x, rest) -> run (q x) rest\n\n(<|>) :: Parser a -> Parser a -> Parser a\np <|> q = Parser $ \\inp ->\n case run p inp of\n ok@(Just x, rest) -> ok\n (Nothing, _) -> run q inp\n\nint :: Parser Type\nint = Parser $ \\inp -> if \"int \" `isPrefixOf` inp then (Just IntT, drop 4 inp) else (Nothing, \"\")\n\npairCons :: Parser ()\npairCons = Parser $ \\inp -> if \"pair \" `isPrefixOf` inp then (Just (), drop 5 inp) else (Nothing, \"\")\n\ntyp :: Parser Type\ntyp = do\n int <|> do\n pairCons\n t1 <- typ\n t2 <- typ\n return $ PairT t1 t2\n\nmain = do\n n_ <- getLine\n let n = read n_\n inp_ <- getLine\n let inp = inp_ ++ \" \"\n if length (filter (=='t') inp) == n then\n case run typ inp of\n (Just typ, \"\") -> printType typ >> putStrLn \"\"\n _ -> putStrLn \"Error occurred\"\n else putStrLn \"Error occurred\""}, {"source_code": "\n\nloop :: [String] -> [String] -> [String] -> String\n\nsolve t = loop (words t) [] [] \n\nsolve' t = loop t [] [] \n\nloop [\"int\"] [] [] = \"int\"\nloop [] [] res = concat . reverse $ res\nloop [] (\">\":stack) (\",\":res) =\n \"Error occurred\"\n\nloop task (\">\":stack) res@(\">\":_) =\n loop task stack (\">\":res)\nloop task (\",\":stack) res@(\">\":_) =\n loop task stack (\",\":res) \n\nloop (\"pair\":task) stack res = \n loop task (\",\":\">\":stack) (\"pair<\":res) \n\nloop (\"int\":task) (s:stack) res@(\",\":_) = \n loop task stack (s:\"int\":res) \nloop (\"int\":task) (s:stack) res@(\"pair<\":_) = \n loop task stack (s:\"int\":res) \n\nloop task stack res = \n \"Error occurred\"\n-- error $ show task ++ \";\" ++ show stack++ \";\"++show res\n\nparse foo = case lines foo of\n [_, x] -> words x\n\nmain = (putStrLn . solve' . parse =<< getContents)\n"}, {"source_code": "\n\nloop :: [String] -> [String] -> [String] -> String\n\nsolve t = loop (words t) [] [] \n\nsolve' t = loop t [] [] \n\nloop [\"int\"] [] [] = \"int\"\nloop [] [] res = concat . reverse $ res\nloop [] (\">\":stack) (\",\":res) =\n \"Error occurred\"\n\nloop task (\">\":stack) res@(\">\":_) =\n loop task stack (\">\":res)\nloop task (\",\":stack) res@(\">\":_) =\n loop task stack (\",\":res) \n\nloop (\"pair\":task) stack res = \n loop task (\",\":\">\":stack) (\"pair<\":res) \n\nloop (\"int\":task) (s:stack) res@(\",\":_) = \n loop task stack (s:\"int\":res) \nloop (\"int\":task) (s:stack) res@(\"pair<\":_) = \n loop task stack (s:\"int\":res) \n\nloop task stack res = \n \"Error occurred\"\n-- error $ show task ++ \";\" ++ show stack++ \";\"++show res\n\nparse foo = case lines foo of\n [_, x] -> words $! x\n\nmain = (putStrLn . solve' . parse =<< getContents)\n"}, {"source_code": "\nimport Monad (MonadPlus, liftM, mzero)\nimport Prelude hiding (print)\n\ndata Type = Int | Pair Type Type\n\nnameInt = \"int\"\nnamePair = \"pair\"\n\nmfilter :: MonadPlus m => (a -> Bool) -> m a -> m a\nmfilter pred ma = do\n a <- ma\n if pred a then return a else mzero\n\nparse :: [String] -> Maybe Type\nparse = liftM fst . mfilter (null . snd) . parse'\n where\n parse' (w:ws)\n | w == nameInt = return (Int, ws)\n | w == namePair = do\n (t1, ws') <- parse' ws\n (t2, ws'') <- parse' ws'\n return (Pair t1 t2, ws'')\n parse' _ = fail \"\"\n\nprint :: Maybe Type -> IO ()\nprint res = maybe (putStr \"Error occurred\") print' res >> putStrLn \"\"\n where\n print' Int = putStr \"int\"\n print' (Pair t1 t2) = sequence_ \n [putStr \"pair<\", print' t1, putStr \",\", print' t2, putStr \">\"]\n\nmain :: IO ()\nmain = getLine >> getLine >>= print . parse . words"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.getContents >>= print.solve.tail.B.words\n\nsolve :: [B.ByteString] -> Expr\nsolve bss = evalParser (expr <* end) bss\n\ntype State = [Elem]\ntype Elem = B.ByteString\n\ndata Expr = I | P Expr Expr | Error\n\ninstance Show Expr where\n showsPrec _ I = showString \"int\"\n showsPrec _ (P x y) = showString \"pair<\"\n . shows x \n . showChar ','\n . shows y\n . showChar '>'\n showsPrec _ Error = showString \"Error occurred\"\n\n\nevalParser :: Parser Expr -> State -> Expr\nevalParser expr st = case runParser expr st of\n Just (result,_) -> result\n Nothing -> Error\n\ngetElem :: Parser Elem\ngetElem = Parser $ \\st -> if null st\n then Nothing\n else Just (head st,st)\ngetState :: Parser State\ngetState = Parser $ \\st -> Just (st,st)\nputState :: State -> Parser ()\nputState st = Parser $ const $ Just ((),st)\nmodifyState :: (State -> State) -> Parser ()\nmodifyState f = Parser $ \\st -> Just ((),f st)\n\nexpr = int <|> pair\n\nint = do\n bs <- getElem\n guard (bs==\"int\")\n modifyState tail\n return I\n\npair = do\n bs <- getElem\n guard (bs==\"pair\")\n modifyState tail\n x <- expr\n y <- expr\n return $ P x y\n\nend = do\n rest <- getState\n guard (null rest)\n\ndata Parser t = Parser {runParser :: State -> Maybe (t, State)}\n\ninstance Monad Parser where\n return t = Parser $ \\st -> Just (t,st)\n m >>= f = Parser $ \\st -> do\n (t,rest) <- runParser m st\n runParser (f t) rest\n\ninstance MonadPlus Parser where\n mzero = Parser $ const Nothing\n mplus p q = Parser $ \\st ->\n runParser p st `mplus` runParser q st\n\ninstance Functor Parser where\n fmap f m = Parser $ \\st ->\n fmap (\\(t,rest) -> (f t,rest)) $ runParser m st\n\ninstance Applicative Parser where\n pure = return\n (<*>) = ap\n\ninstance Alternative Parser where\n empty = mzero\n (<|>) = mplus\n"}, {"source_code": "main = getLine >> getLine >>= putStrLn.solve [] [].words\n\nsolve [] [] [\"int\"] = \"int\"\nsolve ans [] [] = concat.reverse $ ans\nsolve ans s (\"pair\":ws) = solve (\"pair<\":ans) (\",>\"++s) ws\nsolve ans (',':s) (\"int\":ws) = solve (\"int,\":ans) s ws\nsolve ans ('>':s) (\"int\":ws) =\n case span ('>'==) s of\n (xs,',':ys) -> solve (\",\":xs:\"int>\":ans) ys ws\n (xs,[]) -> solve (xs:\"int>\":ans) [] ws\nsolve _ _ _ = \"Error occurred\"\n"}], "negative_code": [{"source_code": "\nimport Monad (MonadPlus, liftM, mzero)\nimport Prelude hiding (print)\n\ndata Type = Int | Pair Type Type\n\nnameInt = \"int\"\nnamePair = \"pair\"\n\nmfilter :: MonadPlus m => (a -> Bool) -> m a -> m a\nmfilter pred ma = do\n a <- ma\n if pred a then return a else mzero\n\nparse :: [String] -> Maybe Type\nparse = liftM fst . mfilter (null . snd) . parse'\n where\n parse' (w:ws)\n | w == nameInt = return (Int, ws)\n | w == namePair = do\n (t1, ws') <- parse' ws\n (t2, ws'') <- parse' ws'\n return (Pair t1 t2, ws'')\n parse' _ = fail \"\"\n\nprint :: Maybe Type -> IO ()\nprint res = maybe (putStr \"Error occured\") print' res >> putStrLn \"\"\n where\n print' Int = putStr \"int\"\n print' (Pair t1 t2) = sequence_ \n [putStr \"pair<\", print' t1, putStr \",\", print' t2, putStr \">\"]\n\nmain :: IO ()\nmain = getLine >> getLine >>= print . parse . words\n"}, {"source_code": "import Control.Monad\nimport Data.List\ndata Type = IntT | PairT Type Type\ninstance Show Type where\n show IntT = \"Int\"\n show (PairT t1 t2) = \"pair<\" ++ show t1 ++ \",\" ++ show t2 ++ \">\"\n\ndata Parser a = Parser {run :: String -> (Maybe a, String)}\ninstance Monad Parser where\n return x = Parser $ \\inp -> (Just x, inp)\n p >>= q = Parser $ \\inp ->\n case run p inp of\n (Nothing, _) -> (Nothing, \"\")\n (Just x, rest) -> run (q x) rest\n\n(<|>) :: Parser a -> Parser a -> Parser a\np <|> q = Parser $ \\inp ->\n case run p inp of\n ok@(Just x, rest) -> ok\n (Nothing, _) -> run q inp\n\nint :: Parser Type\nint = Parser $ \\inp -> if \"int \" `isPrefixOf` inp then (Just IntT, drop 4 inp) else (Nothing, \"\")\n\npairCons :: Parser ()\npairCons = Parser $ \\inp -> if \"pair \" `isPrefixOf` inp then (Just (), drop 5 inp) else (Nothing, \"\")\n\ntyp :: Parser Type\ntyp = do\n int <|> do\n pairCons\n t1 <- typ\n t2 <- typ\n return $ PairT t1 t2\n\nmain = do\n n_ <- getLine\n let n = read n_\n inp_ <- getLine\n let inp = inp_ ++ \" \"\n if length (filter (=='t') inp) == n then\n case run typ inp of\n (Just typ, \"\") -> print typ\n _ -> putStrLn \"Error occurred\"\n else putStrLn \"Error occurred\""}, {"source_code": "import Control.Monad\nimport Data.List\ndata Type = IntT | PairT Type Type\ninstance Show Type where\n show IntT = \"Int\"\n show (PairT t1 t2) = \"pair<\" ++ show t1 ++ \",\" ++ show t2 ++ \">\"\n\ndata Parser a = Parser {run :: String -> (Maybe a, String)}\ninstance Monad Parser where\n return x = Parser $ \\inp -> (Just x, inp)\n p >>= q = Parser $ \\inp ->\n case run p inp of\n (Nothing, _) -> (Nothing, \"\")\n (Just x, rest) -> run (q x) rest\n\n(<|>) :: Parser a -> Parser a -> Parser a\np <|> q = Parser $ \\inp ->\n case run p inp of\n ok@(Just x, rest) -> ok\n (Nothing, _) -> run q inp\n\nint :: Parser Type\nint = Parser $ \\inp -> if \"int \" `isPrefixOf` inp then (Just IntT, drop 4 inp) else (Nothing, \"\")\n\npairCons :: Parser ()\npairCons = Parser $ \\inp -> if \"pair \" `isPrefixOf` inp then (Just (), drop 5 inp) else (Nothing, \"\")\n\ntyp :: Parser Type\ntyp = do\n int <|> do\n pairCons\n t1 <- typ\n t2 <- typ\n return $ PairT t1 t2\n\nmain = do\n n_ <- getLine\n let n = read n_\n inp_ <- getLine\n let inp = inp_ ++ \" \"\n if length (filter (=='t') inp) == n then\n case run typ inp of\n (Just typ, \"\") -> print typ\n _ -> putStrLn \"Error occurred\"\n else putStrLn \"Error occurred\""}, {"source_code": "\n\nloop :: [String] -> [String] -> [String] -> String\n\nsolve t = loop (words t) [] [] \n\nsolve' t = loop t [] [] \n\n\nloop [] [] res = concat . reverse $ res\nloop task (\",\":stack) res@(\">\":_) =\n loop task stack (\",\":res) \nloop task@(\"pair\":_) stack (\">\":res) = \n loop task (\">\":stack) res\nloop task@(\"pair\":_) stack (\"int\":res) = \n \"Error occurred\"\nloop (\"pair\":task) stack res = \n loop task (\",\":\">\":stack) (\"pair<\":res) \nloop (\"int\":task) (s:stack) res@(\",\":_) = \n loop task stack (s:\"int\":res) \nloop (\"int\":task) (s:stack) res@(\"pair<\":_) = \n loop task stack (s:\"int\":res) \nloop task@(\"int\":_) (\">\":stack) res = \n loop task stack (\">\":res) \nloop (\"int\":task) [] [] = \n loop task [] [\"int\"]\n-- loop task (s:stack) res@(\"<\":_) =\n-- loop task stack (s:res)\nloop [] (\">\":stack) (\",\":res) =\n \"Error occurred\"\nloop [] (\">\":stack) (res) =\n loop [] stack (\">\":res)\nloop task stack res = \n \"Error occurred\"\n-- error $ show task ++ \";\" ++ show stack++ \";\"++show res\n\n\nparse foo = case lines foo of\n [_, x] -> words $! x\n\n\n\nmain = (putStrLn . solve' . parse =<< getContents)\n"}, {"source_code": "\n\nloop :: [String] -> [String] -> [String] -> String\n\nsolve t = loop (words t) [] [] \n\nsolve' t = loop t [] [] \n\n\nloop [] [] res = concat . reverse $ res\nloop task (\",\":stack) res@(\">\":_) =\n loop task stack (\",\":res) \nloop (\"pair\":task) stack res = \n loop task (\",\":\">\":stack) (\"pair<\":res) \nloop (\"int\":task) (s:stack) res@(\",\":_) = \n loop task stack (s:\"int\":res) \nloop (\"int\":task) (s:stack) res@(\"pair<\":_) = \n loop task stack (s:\"int\":res) \nloop task@(\"int\":_) (\">\":stack) res = \n loop task stack (\">\":res) \nloop (\"int\":task) [] [] = \n loop task [] [\"int\"]\n-- loop task (s:stack) res@(\"<\":_) =\n-- loop task stack (s:res)\nloop [] (\">\":stack) (\",\":res) =\n \"Error occurred\"\nloop [] (\">\":stack) (res) =\n loop [] stack (\">\":res)\nloop task stack res = \n \"Error occurred\"\n -- error $ show task ++ \";\" ++ show stack++ \";\"++show res\n\n\nparse foo = case lines foo of\n [_, x] -> words $! x\n\n\n\nmain = (putStrLn . solve' . parse =<< getContents)\n"}, {"source_code": "\n\nloop :: [String] -> [String] -> [String] -> String\n\nsolve t = loop (words t) [] [] \n\nsolve' t = loop t [] [] \n\n\nloop [] [] res = concat . reverse $ res\nloop task (\",\":stack) res@(\">\":_) =\n loop task stack (\",\":res) \nloop (\"pair\":task) stack res = \n loop task (\",\":\">\":stack) (\"pair<\":res) \nloop (\"int\":task) (s:stack) res@(\",\":_) = \n loop task stack (s:\"int\":res) \nloop (\"int\":task) (s:stack) res@(\"pair<\":_) = \n loop task stack (s:\"int\":res) \nloop (\"int\":task) [] [] = \n loop task [] [\"int\"]\n-- loop task (s:stack) res@(\"<\":_) =\n-- loop task stack (s:res)\nloop [] (\">\":stack) (\",\":res) =\n \"Error occurred\"\nloop [] (\">\":stack) (res) =\n loop [] stack (\">\":res)\nloop task stack res = show task ++ \";\" ++ show stack++ \";\"++show res\n\n\nparse foo = case lines foo of\n [_, x] -> words $! x\n\n\n\nmain = (putStrLn . solve' . parse =<< getContents)\n"}], "src_uid": "6587be85c64a0d5fb66eec0c5957cb62"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do\n n <- readInt\n dir <- replicateM n readString\n let ul = length $ filter (==\"UL\") dir\n let ur = length $ filter (==\"UR\") dir\n let dl = length $ filter (==\"DL\") dir\n let dr = length $ filter (==\"DR\") dir\n let all = (n - ul - ur - dl - dr)\n return (ul, ur, dl, dr, all)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (ul, ur, dl, dr, all) = fromIntegral x * fromIntegral y :: Integer\n where\n x = 1 + ul + dr + all\n y = 1 + ur + dl + all\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n get :: m s\n put :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n s <- get\n put (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n s <- get\n return (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n fmap f m = State $ \\s -> let\n (a, s') = runState m s\n in (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= k = State $ \\s -> let\n (a, s') = runState m s\n in runState (k a) s'\n\ninstance MonadState s (State s) where\n get = State $ \\s -> (s, s)\n put s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n", "positive_code": [{"source_code": "import Data.List\n\nparse :: String -> [String]\nparse = tail . lines\n\nsolve :: [String] -> Integer\nsolve = loop (1, 1)\n\nloop (a, b) [] = a * b\nloop (a, b) (\"UL\":rest) = loop (a + 1, b) rest\nloop (a, b) (\"DR\":rest) = loop (a + 1, b) rest\nloop (a, b) (\"UR\":rest) = loop (a, b + 1) rest\nloop (a, b) (\"DL\":rest) = loop (a, b + 1) rest\nloop (a, b) (\"ULDR\":rest) = loop (a + 1, b + 1) rest\n\n\nmain = interact (show . solve . parse)\n -- stuff <- getContents\n -- print . solve . parse $ stuff\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: Int -> [String] -> Integer\nsolve n xs = solve' (0::Int) (0::Int) xs\n where\n solve' k l [] = fromIntegral (n - k + 1) * fromIntegral (n - l + 1)\n solve' k l (\"UL\":xs) = solve' (k + 1) l xs\n solve' k l (\"DR\":xs) = solve' (k + 1) l xs\n solve' k l (\"UR\":xs) = solve' k (l + 1) xs\n solve' k l (\"DL\":xs) = solve' k (l + 1) xs\n solve' k l (_ : xs) = solve' k l xs \n\nmain :: IO ()\nmain = do\n lines' <- liftM lines getContents\n let n = (read . head) lines'\n let xs = (take n . tail) lines'\n print $ solve n xs\n"}], "negative_code": [{"source_code": "\nimport CPUTime\n\nsolve :: [String] -> Integer\nsolve xs = solve' (1::Int) (1::Int) xs\n where\n solve' n m [] = fromIntegral n * fromIntegral m\n solve' n m (\"UL\":xs) = solve' (succ n) m xs\n solve' n m (\"UR\":xs) = solve' n (succ m) xs\n solve' n m (\"DR\":xs) = solve' (succ n) m xs\n solve' n m (\"DL\":xs) = solve' n (succ m) xs\n solve' n m (_:xs) = solve' (succ n) (succ m) xs\n\nmain :: IO ()\nmain = do\n t0 <- getCPUTime\n\n n <- readLn\n xs <- mapM (const getLine) [1..n]\n print $ solve xs\n \n t1 <- getCPUTime\n putStr \"Time = \"\n print (fromIntegral (t1 - t0) * 1e-12)\n"}], "src_uid": "566b91c278449e8eb3c724a6f00797e8"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,m] <- ri\r\n return (n,m)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (n,m) = sum $ [1..m] ++ [2*m,3*m..n*m]\r\n", "positive_code": [{"source_code": "readLines :: Int -> IO [String]\nreadLines 0 = do\n return []\nreadLines n = do\n line <- getLine\n\n lines <- readLines (n - 1)\n\n return (line:lines)\n\nwriteLines :: Show a => [a] -> IO ()\nwriteLines [] = return ()\nwriteLines (line:rest) = do\n putStrLn (show line)\n writeLines rest\n\ndeserializeTestCases :: [String] -> [(Int, Int)]\ndeserializeTestCases = map deserializeItem\n\ncalculateAllSolutions :: [String] -> [Int]\ncalculateAllSolutions = (map calculateSolution) . deserializeTestCases\n\ndeserializeItem :: String -> (Int, Int)\ndeserializeItem = deserializeInternal . words\n\ncalculateSolution :: (Int, Int) -> Int\ncalculateSolution (n, m) = m*(m + 1) `div` 2 + (if n > 1 then (m*(n - 1)*(n + 2) `div` 2) else 0)\n\ndeserializeInternal :: [String] -> (Int, Int)\ndeserializeInternal (first:second:rest) = if length rest > 0 then error \"Expected two values.\" else (read first :: Int, read second :: Int)\ndeserializeInternal _ = error \"Wrong number of values.\"\n\n\nmain = do\n testCasesNumStr <- getLine\n\n let testCasesNum = read testCasesNumStr :: Int\n\n testCasesStr <- readLines testCasesNum\n\n let solutions = calculateAllSolutions testCasesStr\n\n writeLines solutions\n"}], "negative_code": [], "src_uid": "7d774a003d2e3e8ae6fe1912b3998c96"} {"source_code": "import Control.Monad\n\nsolve :: [Int] -> String\nsolve l = if b then \"Yes\" else \"No\"\n where\n b = maximum l<=(1+(sum l - maximum l))\n\nroutine :: IO ()\nroutine = do\n l <-(map read . words) <$> getLine\n putStrLn $ solve l\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n", "positive_code": [{"source_code": "import Control.Monad\nimport Prelude\n\ntestCase = do\n line <- getLine\n putStrLn $ solution (map read (words line))\n\n\nsolution :: [Integer] -> String\nsolution [r, g, b] = result where\n mx = maximum [r, g, b]\n rest = r + g + b - mx\n result = case rest < (mx - 1) of\n True -> \"No\"\n False -> \"Yes\"\n\nmain = do\n testCases <- getLine\n strNums <- replicateM (read testCases) testCase\n return ()\n"}], "negative_code": [], "src_uid": "34aa41871ee50f06e8acbd5eee94b493"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport qualified Data.IntSet as IntSet\nimport Data.List (sort, unfoldr)\n\naggregate::[Int]-> UArray Int Int64\naggregate nums = listArray (0, limit) $ go 0 0 sorted where\n sorted = sort nums\n limit = maximum nums\n go idx cnt (el:rest) | idx == el = go idx (cnt + 1) rest\n | otherwise = cnt : go (idx + 1) cnt (el : rest)\n go _ cnt [] = [cnt]\n\nsolution :: [Int] -> Int64\nsolution nums = result where\n result = maximum $ power <$> IntSet.toList (IntSet.fromList nums)\n limit = maximum nums\n sums = aggregate nums\n rng i j = (sums ! (j - 1) ) - (sums ! (i - 1))\n rangePower x u = rng u (min (u + x) (limit + 1)) * fromIntegral u\n power x = sum $ fmap (rangePower x) [x, x + x..limit]\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\nmain::IO ()\nmain = do\n -- print $ solution [3,2,15,9]\n void BS.getLine\n xs <- getInts\n print $ solution xs\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\nimport Data.List\nreadInt s = let Just (a,_) = BS.readInt s in fromIntegral a\n\nmain = BS.interact $ BS.pack . show . solve . map readInt . tail . BS.words\n\nsolve ns = maximum $ map res $ unique ns\n where pref = build ns :: UArray Int64 Int64\n (ml, mr) = bounds pref\n getsum l r\n | pl > ml = (pref ! pr) - (pref ! (pl - 1))\n | otherwise = pref ! pr\n where pl = max l ml\n pr = min r mr\n res base = sum [i * (getsum i $ i + base - 1) | i <- [base, 2 * base .. mr]]\n\nbuild ns = runSTUArray $ do\n let l = minimum ns\n r = maximum ns\n a <- newArray (l, r) 0 :: ST s (STUArray s Int64 Int64)\n forM_ ns $ \\n -> do\n v <- readArray a n\n writeArray a n $ v + 1\n forM_ [l + 1..r] $ \\i -> do\n ni <- readArray a i\n np <- readArray a $ i - 1\n writeArray a i $ ni + np\n return a\n\nunique ns = unique_ sorted\n where sorted = sort ns\n unique_ [] = []\n unique_ a@[_] = a\n unique_ (a:b:r)\n | a == b = unique_ (b:r)\n | otherwise = a : unique_ (b:r)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntMap as IntMap\nimport Data.List (unfoldr)\n\nsolution :: [Int] -> Int\nsolution nums = result where\n result = maximum $ power <$> IntMap.keys sums\n limit = maximum nums\n counts = IntMap.fromListWith (+) $ fmap (, 1:: Int) nums\n sums = IntMap.fromAscList $ tail $ scanl collect (undefined,0) $ IntMap.toAscList counts\n collect (_, acc) (i, x ) = (i, x + acc)\n upTo = maybe 0 snd . flip IntMap.lookupLE sums\n range i j = upTo (j - 1) - upTo (i - 1)\n rangePower x u = range u (u + x) * u\n power x = sum $ fmap (rangePower x) [x, x + x..limit]\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\nmain::IO ()\nmain = do\n void BS.getLine\n xs <- getInts\n print $ solution xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nreadInt s = let Just (a,_) = BS.readInt s in a\n\nmain = BS.interact $ BS.pack . show . solve . map readInt . tail . BS.words\n\nsolve ns = maximum $ map res ns\n where pref = prefs $ build ns :: Array Int Int\n (ml, mr) = bounds pref\n getsum l r\n | pl > ml = (pref ! pr) - (pref ! (pl - 1))\n | otherwise = pref ! pr\n where pl = max l ml\n pr = min r mr\n res base = sum [i * (getsum i $ i + base - 1) | i <- [base, 2 * base .. mr]]\n\nbuild ns = runSTArray $ do\n a <- newArray (minimum ns, maximum ns) 0\n forM_ ns $ \\n -> do\n v <- readArray a n\n writeArray a n $ v + 1\n return a\n\nprefs a = let p = listArray (l, r) $ (a ! l) : [(p ! (i - 1)) + (a ! i) | i <- [l + 1..r]]\n in p\n where (l, r) = bounds a\n"}], "src_uid": "de5a9d39dcd9ad7c53ae0fa2d441d3f0"} {"source_code": "solve :: String -> String\nsolve line = let\n len = length line\n countZero = length $ takeWhile (=='0') line\n countOnes = length $ takeWhile (=='1') $ reverse line\n begin = take countZero $ repeat '0'\n end = take countOnes $ repeat '1'\n middle = if len == (countOnes+countZero) then [] else ['0']\n in begin++middle++end\n\ngetInt::IO Integer\ngetInt=do\n line <- getLine\n let i = read line :: Integer\n return (i)\n\nmain :: IO ()\nmain = do\n t <- getInt\n for t where\n for 0 = return ()\n for t = do\n _ <- getInt\n line <- getLine \n putStrLn $ solve line\n for (t-1)\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM t routine\n\nroutine = do\n _ <- getLine\n s <- getLine\n let l = takeWhile (== '0') s\n let r = takeWhile (== '1') $ reverse s\n let rest =\n if (length l + length r == length s)\n then \"\"\n else \"0\"\n putStrLn (l ++ rest ++ r)\n"}, {"source_code": "skip :: [a] -> [a]\nskip [] = []\nskip (x : []) = [x]\nskip (x1 : (x2 : xs)) = x1 : (skip xs)\n\npref :: Char -> String -> String\npref _ \"\" = \"\"\npref d (c : cs)\n | c == d = c : (pref d cs)\n | otherwise = \"\"\n\nsuff :: Char -> String -> String\nsuff c s = pref c $ reverse s\n\nsolve :: String -> String\nsolve s\n | length (pref '0' s ++ (suff '1' s)) == length s = s\n | otherwise = pref '0' s ++ \"0\" ++ (suff '1' s)\n\nio :: String -> String\nio s = unlines $ map solve $ skip $ drop 2 $ lines s\n\nmain :: IO ()\nmain = do\n interact io"}, {"source_code": "import Control.Monad (replicateM_)\nmain = readLn >>= flip replicateM_ ioSolve\n\nioSolve :: IO ()\nioSolve = getLine >> getLine >>= putStrLn . solve\n\nsolve :: String -> String\nsolve s = a ++ x ++ b where\n (a,s') = span (=='0') s\n (b,s'') = span (=='1') $ reverse s'\n x = if null s'' then \"\" else \"0\"\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Tuple\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nreadInt = read :: String -> Int\n\nreduce [] = []\nreduce [x] = [x]\nreduce ('1':'0':'0':xs) = reduce ('1':'0':xs)\nreduce ('1':'0':xs) = '0':xs\nreduce ls = ls\n\nsolve [] = []\nsolve (x:xs) =\n let sub = solve xs\n in reduce $ x:sub\n\nmain = do\n input <- getContents\n let _:tokens = split input\n res = tokens |> unfoldr (\\case\n [] -> Nothing\n _:str:rest -> Just (solve str, rest)\n )\n sequence $ putStrLn <$> res\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . map (process . snd) . filter (odd . fst) . zip [0..] . tail . lines\nprocess s = process' s x y\n where\n x = elemIndices '1' s\n y = elemIndices '0' s\nprocess' s _ [] = s\nprocess' s [] _ = s\nprocess' s x y = process'' s (head x) (last y)\nprocess'' s x y\n | x > y = s\n | otherwise = (take x s) ++ (drop y s)\n \t \n"}], "negative_code": [{"source_code": "skip :: [a] -> [a]\nskip [] = []\nskip (x : []) = [x]\nskip (x1 : (x2 : xs)) = x1 : (skip xs)\n\npref :: Char -> String -> String\npref _ \"\" = \"\"\npref d (c : cs)\n | c == d = c : (pref d cs)\n | otherwise = \"\"\n\nsuff :: Char -> String -> String\nsuff c s = pref c $ reverse s\n\nsolve :: String -> String\nsolve s\n | length (pref '0' s ++ (suff '1' s)) == length s = s\n | otherwise = pref '0' s ++ \"1\" ++ (suff '1' s)\n\nio :: String -> String\nio s = unlines $ map solve $ skip $ drop 2 $ lines s\n\nmain :: IO ()\nmain = do\n interact io"}], "src_uid": "bb071f1f4fc1c129a32064c1301f4942"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n let (q, r) = n `quotRem` k\n print $ if k == 2 && r == 0 then 2 * (q - 1) + 1 else 2 * (q + fromEnum (r > 2)) + fromEnum (r == 2)\n sequence_ [putStrLn $ show i ++ \" \" ++ show (max 1 (i - k)) | i <- [2..n]]\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n let (q, r) = n `quotRem` k\n print $ if k == 2 && r == 0 then 2 * (q - 1) + 1 else 2 * (q + fromEnum (r > 2)) + fromEnum (r == 2)\n sequence_ [B.putStrLn $ showB i `B.append` \" \" `B.append` showB (max 1 (i - k)) | i <- [2..n]]\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n let (q, r) = n `quotRem` k\n print $ if r == 0 then 2 * (q - 1) + fromEnum (k == 2) else 2 * q + r - 1\n sequence_ [putStrLn $ show i ++ \" \" ++ show (max 1 (i - k)) | i <- [2..n]]\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n let (q, r) = n `quotRem` k\n print $ if k == 2 && r == 0 then 2 * (q - 1) + 1 else 2 * q + max 0 (r - 1)\n sequence_ [putStrLn $ show i ++ \" \" ++ show (max 1 (i - k)) | i <- [2..n]]\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}], "src_uid": "ad49b1b537ca539ea0898ee31a0aecf8"} {"source_code": "import Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> String\nsolve [1, 0] = \"0\"\nsolve [_, 0] = \"No solution\"\nsolve [k, d] = show d ++ replicate (k-1) '0'\n \nmain :: IO ()\nmain = reads >>= putStrLn . solve\n\n where\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\t[ k, d ] <- map read . words <$> getLine\n\tputStrLn $ if d == 0 && 1 < k\n\t\tthen \"No solution\"\n\t\telse show d ++ replicate ( k - 1 ) '0'\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let k = inp !! 0\n d = inp !! 1\n if d == 0 && k > 1 \n then putStrLn $ \"No solution\"\n else putStrLn $ show d ++ replicate (k-1) '0'\n"}, {"source_code": "import Data.Functor\n\nmain = do\n [k,d] <- (map read) <$> (words <$> getLine) :: IO [Int]\n putStrLn $ solve k d\n return ()\n\nsolve k d \n | 1 B.getLine\n\nmain = do\n [k, d] <- getInts\n putStrLn $ if d == 0 && k /= 1 then \"No solution\" else show d ++ replicate (k-1) '0'\n"}, {"source_code": "import Data.Char\n\nsolve :: Int -> Int -> String\n\nsolve d k = (replicate (k-1) '1') ++ [ intToDigit d0 ]\n where d0 = head [ d0 | d0 <- [0..9], dr ((k-1)+d0) == d ]\n\ndr :: (Show a, Integral a) => a -> Int\ndr n | n < 10 = fromIntegral n\n | otherwise = dr $ sum $ map digitToInt $ show n\n\ntest d k = let n = solve d k in dr ((read n) :: Integer) == d\n\ntestAll = all (uncurry test) [ (d,k) | k <- [1..1000], d <- [1..9] ]\n\nsolve' 0 1 = Just \"0\"\nsolve' 0 _ = Nothing\nsolve' d k = Just $ solve d k\n\nmain = do\n (k:d:_) <- fmap (map read . words) getLine\n case solve' d k of\n Nothing -> putStrLn \"No solution\"\n Just n -> putStrLn n\n\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve [] = []\nsolve (kd:cs) = (if k<2 || d/=0 then (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)) else \"No solution\"): solve cs\n where\n [k,d] = map read . words $ kd\n (n,m) = d `divMod` k\n"}, {"source_code": "minNum k n \n\t| n == 0 && k == 1 = 0\n\t| n == 0 = -1\n\t| otherwise = (10 ^ (k-1) ) + (n-1)\n\nfind x\n\t| x>=0 = show x\n\t| otherwise = \"No solution\"\n\nparse l = map read $ words l\n\ncal fn kn = fn (head kn) (head $ tail kn)\n\nmain = do \n\tl <- getLine \n\tputStr $ find $ cal minNum $ parse l\n"}], "negative_code": [{"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let k = inp !! 0\n d = inp !! 1\n if d == 0 || k > 1 \n then putStrLn $ \"No solution\"\n else putStrLn $ show d ++ replicate (k-1) '0'\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let k = inp !! 0\n d = inp !! 1\n if d == 0\n then print 0\n else putStrLn $ show d ++ replicate (k-1) '0'\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let k = inp !! 0\n d = inp !! 1\n if d == 0\n then putStrLn $ \"No solution\"\n else putStrLn $ show d ++ replicate (k-1) '0'\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let k = inp !! 0\n d = inp !! 1\n putStrLn $ show d ++ replicate (k-1) '0'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [k, d] <- getInts\n putStrLn $ show d ++ replicate (k-1) '0'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [k, d] <- getInts\n putStrLn $ if d == 0 then \"No solution\" else show d ++ replicate (k-1) '0'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [k, d] <- getInts\n putStrLn $ if d == 0 then show 0 else show d ++ replicate (k-1) '0'\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve [] = []\nsolve (kd:cs) = (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)): solve cs\n where\n [k,d] = map read . words $ kd\n (n,m) = (if k<2 || d/=0 then d else 10) `divMod` k\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve [] = []\nsolve (kd:cs) = (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)): solve cs\n where\n [k,d] = map read . words $ kd\n (n,m) = d `divMod` k\n"}, {"source_code": "import Data.Char\nsum' [] = 0\nsum' (x:xs) = (digitToInt x) + (sum' xs)\n\ndr n \n\t| s<10 = s\n\t| otherwise = dr s\n\twhere s = sum' $ show n\n\nrg n = [10 ^ (n-1) .. 10^n]\n\nminNum k n = filter (\\x -> (dr x) == n) $ rg k\n\nfind [] = \"No solution\"\nfind (x:_) = show x\n\nparse l = map read $ words l\n\ncal fn kn = fn (head kn) (head $ tail kn)\n\nmain = do \n\tl <- getLine \n\tprint $ find $ cal minNum $ parse l\n"}], "src_uid": "5dd0d518f315d81204b25e48fea0793a"} {"source_code": "solve :: Int -> [Int]\nsolve n = if even n \n then [n `div` 2, n `div` 2, 0]\n else [-1]\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain t = do n <- (readLn :: IO Int)\n putStrLn $ unwords $ map show $ solve n\n if t > 1\n then testCaseMain (t - 1)\n else return ()\n\nmain :: IO ()\nmain = do t <- (readLn :: IO Int)\n testCaseMain t\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad (liftM2, replicateM_)\r\nimport Data.Bits\r\nimport Data.Char (digitToInt)\r\nimport Data.Maybe (fromJust)\r\nimport Data.String\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ntype D = (String, String, String)\r\n\r\na110 :: D -> D\r\na110 (a, b, c) = ('1' : a, '1' : b, '0' : c)\r\n\r\na000 :: D -> D\r\na000 (a, b, c) = ('1' : a, '1' : b, '1' : c)\r\n\r\nprIntegerAns :: D -> IO ()\r\nprIntegerAns (a, b, c) = putStrLn $ unwords $ show <$> toDec <$> reverse <$> [a, b, c]\r\n\r\ntoBin :: Integer -> String\r\ntoBin a = reverse $ go a\r\n where\r\n go x\r\n | x == 0 = \"\"\r\n | odd x = '1' : go (x `div` 2)\r\n | otherwise = '0' : go (x `div` 2)\r\n\r\ntoDec :: String -> Integer\r\ntoDec = foldl (\\acc x -> acc * 2 + fromIntegral (digitToInt x)) 0\r\n\r\nsolve :: Integer -> IO ()\r\nsolve x =\r\n -- print (x `div` 2, a) >>\r\n if odd x then do print (-1) else prIntegerAns (go a True (\"\", \"\", \"\"))\r\n where\r\n a = toBin $ x `div` 2\r\n go :: String -> Bool -> D -> D\r\n go \"\" _ x = x\r\n go ('0' : xs) b d = go xs b (a000 d)\r\n go (x : xs) True d = go xs False (a110 d)\r\n go (x : xs) False d = go xs False (a110 d)\r\n\r\nparseInteger :: String -> Integer\r\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- parseInteger <$> getLine\r\n replicateM_ (fromIntegral n) (solve =<< parseInteger <$> getLine)"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (liftM2, replicateM_)\r\nimport Data.Bits\r\nimport Data.Char (digitToInt)\r\nimport Data.Maybe (fromJust)\r\nimport Data.String\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ntype D = (String, String, String)\r\n\r\na110 :: D -> D\r\na110 (a, b, c) = ('1' : a, '1' : b, '0' : c)\r\n\r\na001 :: D -> D\r\na001 (a, b, c) = ('1' : a, '0' : b, '1' : c)\r\n\r\na000 :: D -> D\r\na000 (a, b, c) = ('1' : a, '1' : b, '1' : c)\r\n\r\nprIntegerAns :: D -> IO ()\r\nprIntegerAns (a, b, c) = do\r\n -- print $ (a, b, c)\r\n -- print $ check (a, b, c)\r\n putStrLn $ unwords $ show <$> toDec <$> reverse <$> [a, b, c]\r\n\r\ntoBin :: Integer -> String\r\ntoBin a = reverse $ go a\r\n where\r\n go x\r\n | x == 0 = \"\"\r\n | odd x = '1' : go (x `div` 2)\r\n | otherwise = '0' : go (x `div` 2)\r\n\r\ntoDec :: String -> Integer\r\ntoDec = foldl (\\acc x -> acc * 2 + fromIntegral (digitToInt x)) 0\r\n\r\nsolve :: Integer -> IO ()\r\nsolve x =\r\n -- print (x `div` 2, a) >>\r\n if odd x then do print (-1) else prIntegerAns (go a True (\"\", \"\", \"\"))\r\n where\r\n a = toBin $ x `div` 2\r\n go :: String -> Bool -> D -> D\r\n go \"\" _ x = x\r\n go ('0' : xs) b d = go xs b (a000 d)\r\n go (x : xs) True d = go xs False (a110 d)\r\n go (x : xs) False d = go xs False (a001 d)\r\n\r\nparseInteger :: String -> Integer\r\nparseInteger = fromIntegral . fst . fromJust . C.readInt . fromString\r\n\r\n-- check' :: (Integer, Integer, Integer) -> Integer\r\n-- check' (a, b, c) = (a `xor` b) + (b `xor` c) + (a `xor` c)\r\n\r\n-- check :: D -> Integer\r\n-- check (a, b, c) = check' (toDec $ reverse a, toDec $ reverse b, toDec $ reverse c)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- parseInteger <$> getLine\r\n replicateM_ (fromIntegral n) (solve =<< parseInteger <$> getLine)"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStrLn.showL.solve) tcs\r\n\r\nshowL = unwords . map show\r\n\r\nsolve n = ans\r\n where\r\n ans | n `mod` 2 /= 0 = [-1 :: Int]\r\n | otherwise = [0, 0, n `div` 2]\r\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n\nm :: Int64\nm = 998_244_353\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\nmI :: Int -> M\nmI = M . fromIntegral\n\ninstance Show M where \n show (M v) = \"M\" ++ show v\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = M $ (a * b) `mod` m\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> Maybe (Int, Int, Int)\nsolve x\n | even x = Just (x `div` 2, 0, 0)\n | odd x = Nothing\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n x <- B8.getLine <&> readIntB8\n let answer = solve x\n case answer of\n Nothing -> putStrLn \"-1\\n\"\n Just (a, b, c) -> printf \"%d %d %d\\n\" a b c\n\n\n"}, {"source_code": "(>>>) = flip (.)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> tail\r\n >>> map (read >>> solve >>> map show >>> unwords)\r\n >>> unlines\r\n\r\nsolve :: Int -> [Int]\r\nsolve n\r\n | even n = [0, 0, n `div` 2]\r\n | otherwise = [-1]\r\n"}, {"source_code": "solveCase :: IO ()\r\nsolveCase = do\r\n s_num <- getLine\r\n let num = read s_num :: Int\r\n if num `mod` 2 == 0 then\r\n putStrLn $ \"0 0 \" ++ ( show $ num `quot` 2 )\r\n else\r\n putStrLn \"-1\"\r\n\r\nsolve :: Int -> IO ()\r\nsolve cases_left = do\r\n if cases_left == 1 then\r\n solveCase\r\n else do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n pure $ if not (even n) then putInts [-1] else putInts [div n 2, div n 2, 0]\r\n"}, {"source_code": "for :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n a <- readLn :: IO Int\r\n if a `mod` 2 == 0\r\n then putStrLn $ \"0 0 \" ++ show (a `div` 2)\r\n else print (-1)\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n"}], "negative_code": [], "src_uid": "43041076ddd0bbfac62cd4abf4536282"} {"source_code": "--ghc 7.10\n\nwinnerStr = [\"Chris\",\"Friendship is magic!^^\",\"Mishka\"]\n\nresult :: (Ord a) => (a,a) -> Int\nresult (a,b)\n | a < b = 1\n | a > b = -1\n | otherwise = 0\n\nwinner :: (Ord a) => [(a,a)] -> String\nwinner g = (!!) winnerStr . fromEnum . compare 0 . sum .map result $ g\n\nreadPair :: (Read a) => String -> (a,a)\nreadPair str = (a,b)\n where [a,b] = map read . words $ str\n\nmain = do\n nStr <- getLine\n gStr <- getContents\n let g = map (readPair) . lines $ gStr :: [(Int,Int)]\n putStrLn $ winner g", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n x\t| x==[] = if n>0 then \"Mishka\" else if n==0 then \"Friendship is magic!^^\" else \"Chris\"\n \t\t| otherwise = process n1 (tail x)\n\twhere \taa= head x\n\t\tn1 | aa!!0>aa!!1 = n+1\n | aa!!0==aa!!1 = n\n | otherwise = n-1 \n\nmain = do\n\t \t\n\tn<- read <$> getLine ::IO Int\n\tx<-map(map read) <$> map words <$> lines <$> getContents:: IO [[Int]]\n\tputStrLn $ process 0 x\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\n\nbtoi :: B.ByteString -> Int\nbtoi = fst . fromJust . B.readInt\n\nprocess_case :: Int -> Int -> [[Int]] -> String\nprocess_case m c []\n | m > c = \"Mishka\"\n | m < c = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\nprocess_case m c ([m', c']:rest)\n | m' > c' = process_case (m+1) c rest\n | m' < c' = process_case m (c+1) rest\n | otherwise = process_case m c rest\n\nprocess :: B.ByteString -> B.ByteString\nprocess str =\n let (sn:rest) = B.lines str\n n = btoi sn\n in B.pack $ process_case 0 0 (map (map btoi . B.words) $ take n rest)\n\nmain :: IO ()\nmain = B.interact process"}, {"source_code": "module Main where\n\nimport Control.Monad\n\ntype Result = (Int, Int)\n\nsolve :: [Result] -> String\nsolve rs | m < c = \"Chris\"\n | m > c = \"Mishka\"\n | otherwise = \"Friendship is magic!^^\"\n where update (m, c) (m', c') | m' < c' = (m, c + 1)\n | m' > c' = (m + 1, c)\n | otherwise = (m + 1, c + 1)\n (m, c) = foldl update (0, 0) rs\n\nmain :: IO ()\nmain = do\n n <- liftM read getLine\n rs <- replicateM n $ do\n [n, m] <- liftM (map read . words) getLine\n return (n, m)\n putStrLn $ solve rs\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\ntype Result = (Int, Int)\n\nsolve :: [Result] -> String\nsolve rs | m < c = \"Chris\"\n | m > c = \"Mishka\"\n | otherwise = \"Friendship is magic!^^\"\n where update (m, c) (m', c') | m' < c' = (m, c + 1)\n | m' > c' = (m + 1, c)\n | otherwise = (m + 1, c + 1)\n (m, c) = foldl update (0, 0) rs\n\nmain :: IO ()\nmain = do\n n <- liftM read getLine\n rs <- replicateM n $ do\n [n, m] <- liftM (map read . words) getLine\n return (n, m)\n putStrLn $ solve rs\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n n <- getInt\n dices <- replicateM n getInts\n let (x,y) = solve dices\n if x == y\n then putStrLn \"Friendship is magic!^^\"\n else if x > y\n then putStrLn \"Mishka\"\n else putStrLn \"Chris\"\n\nsolve ds = f ds (0,0) where\n f [] res = res\n f ([d1,d2]:ds) (x,y) = f ds (x',y') where\n x' = if d1 > d2 then x+1 else x\n y' = if d2 > d1 then y+1 else y"}, {"source_code": "import GHC.IO.Handle\nimport System.IO\nimport System.Environment\n\n--------------------------------------------------------------------------------\n-- CLEAR WORLD\nres [] = 0\nres ([m, c]:a) = (if m > c then 1 else if m < c then -1 else 0) + res a\nparse_res r\n | r > 0 = \"Mishka\"\n | r < 0 = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\nsolve s =\n let nums = map (\\line -> map (\\word -> read word :: Int) (words line)) (lines s)\n a = filter (\\a -> length a == 2) nums\n in parse_res $ res a\n\n--------------------------------------------------------------------------------\n-- REAL WORLD\nmain = do\n args <- getArgs\n let iohelper x y z = if length args == 2\n then do handle <- openFile x y; return handle\n else return z\n cin <- iohelper \"input.txt\" ReadMode stdin\n cout <- iohelper \"output.txt\" WriteMode stdout\n--------------------------------------------------------------------------------\n s <- hGetContents cin\n hPutStr cout (solve s)\n--------------------------------------------------------------------------------\n if length args == 2\n then do hClose cin\n hClose cout\n else return ()\n--------------------------------------------------------------------------------\n"}, {"source_code": "import Control.Monad\n\nsol :: [[Int]] -> Int -> Int -> String\nsol [] a b = if a > b\n then \"Mishka\"\n else if b > a\n then \"Chris\"\n else \"Friendship is magic!^^\"\n\nsol res a b = if (head (head res)) > (last (head res))\n then (sol (tail res) (a+1) b)\n else if (head (head res)) < (last (head res))\n then (sol (tail res) a (1+b))\n else (sol (tail res) a b)\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n inputs <- replicateM n getLine :: IO [String]\n let input_i = fmap (map read.words) inputs :: [[Int]]\n putStrLn (sol input_i 0 0)\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tps :: [ ( Int, Int ) ] <- map ( mp . map read . words ) . lines <$> getContents\n\n\tlet\n\t\tm = length $ filter ( f (>) ) ps\n\t\tc = length $ filter ( f (<) ) ps\n\t\n\tif m == c \n\t\tthen putStrLn \"Friendship is magic!^^\"\n\t\telse putStrLn $ which \"Mishka\" \"Chris\" $ m > c\n\nf g ( a, b ) = g a b\n"}, {"source_code": "{-# LANGUAGE NPlusKPatterns #-}\nmodule Main where\n\nmain :: IO ()\nmain = communicate track\n\ntrack :: [(Int, Int)] -> Ordering\ntrack = stat . map (uncurry compare)\n\nstat :: [Ordering] -> Ordering\nstat = categ . assess\n\ncateg :: Int -> Ordering\ncateg n | n < 0 = LT\n | n > 0 = GT\n | otherwise = EQ\n\nassess :: [Ordering] -> Int\nassess = sum . map value\n\nvalue :: Ordering -> Int\nvalue LT = -1\nvalue EQ = 0\nvalue GT = 1\n\ncommunicate :: ([(Int, Int)] -> Ordering) -> IO ()\ncommunicate f = do\n n <- (readLn :: IO Int)\n ps <- iter n getPair\n putStrLn $ report $ track ps\n\niter :: (Functor m, Monad m) => Int -> m a -> m [a]\niter 0 p = return []\niter (n + 1) p = p >>= (\\a -> fmap (a :) (iter n p))\n\ngetPair :: IO (Int, Int)\ngetPair = fmap ((\\pl -> (head pl, (head . tail) pl)) . map read . words) getLine\n\nreport :: Ordering -> String\nreport LT = \"Chris\"\nreport EQ = \"Friendship is magic!^^\"\nreport GT = \"Mishka\"\n"}, {"source_code": "import Control.Monad\n\nmain :: IO()\nmain = do\n n <- getLine\n inputs <- replicateM (read n) getLine\n let ds = map convert (map words inputs) where\n convert :: [String] -> (Int, Int)\n convert (x:xs) = (read x :: Int, read (head xs) :: Int)\n putStrLn (winner ds)\n\nwinner :: [(Int, Int)] -> String\nwinner xs = winner' 0 0 xs where\n winner' :: Int -> Int -> [(Int, Int)] -> String\n winner' a b []\n | a > b = \"Mishka\"\n | a < b = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\n winner' a b (x:xs)\n | fst x > snd x = winner' (a+1) b xs\n | fst x < snd x = winner' a (b+1) xs\n | otherwise = winner' a b xs\n\n"}, {"source_code": "main = do\n n <- readLn\n let for x y []\n |x==y = putStrLn \"Friendship is magic!^^\"\n |x>y = putStrLn \"Mishka\"\n |otherwise = putStrLn \"Chris\"\n for x y (i:is) = do\n [a,b] <- fmap ((map read) . words) getLine :: IO [Int]\n if a==b then for x y is\n else if a getLine\n inputs <- sequence $ replicate count getLine\n\n let (mishka, chris) = inputs\n & map (map read . words)\n & map (\\[x,y] -> x - y)\n & filter (/= 0)\n & partition (> 0)\n\n putStrLn $ case compare (length mishka) (length chris) of\n GT -> \"Mishka\"\n LT -> \"Chris\"\n EQ -> \"Friendship is magic!^^\"\n"}, {"source_code": "main = interact $ f.tail.lines\nf inp = g (map (\\x -> map read (words x) :: [Integer]) inp) 0 0\n\ng [] m c\n | m > c = \"Mishka\"\n | m < c = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\n\ng (x:xs) m c\n | (head x) > (head (tail x)) = g xs (m + 1) c\n | (head x) == (head (tail x)) = g xs m c\n | otherwise = g xs m (c+1)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ps <- replicateM n getInts\n\n let\n c1 = length $ filter id $ zipWith (<) (map (!!0) ps) (map (!!1) ps)\n c2 = length $ filter id $ zipWith (>) (map (!!0) ps) (map (!!1) ps)\n\n putStrLn $ case compare c1 c2 of\n LT -> \"Mishka\"\n EQ -> \"Friendship is magic!^^\"\n GT -> \"Chris\"\n"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n a <- fmap (map (map read . words)) . sequence $ replicate n getLine :: IO [[Int]]\n putStrLn . getAns . solve $ a\n\nsolve :: [[Int]] -> Int\nsolve = sum . map (trans . (\\[x, y] -> x `compare` y))\n\ntrans :: Ordering -> Int\ntrans LT = -1\ntrans EQ = 0\ntrans GT = 1\n\ngetAns :: Int -> String\ngetAns n\n | n > 0 = \"Mishka\"\n | n < 0 = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\n"}, {"source_code": "module Main where\nimport Data.List\nimport Data.Char\nmain :: IO ()\nmain = interact $ solve . lines\n\nsolve :: [String] -> String\nsolve xs = let n = read . head $ xs :: Integer\n xs1 = take (fromInteger n) . tail $ xs\n xs2 :: [(Int, Int)]\n xs2 = map (\\(a:' ':c:\"\") -> (ord a - 48, ord c - 48)) xs1\n sctup = foldr (\\(a,b) (za, zb) -> if a > b\n then (za+1, zb)\n else if a == b\n then (za, zb)\n else (za, zb+1)) (0,0) xs2\n in case sctup of\n (a, b) | a > b -> \"Mishka\"\n | a == b -> \"Friendship is magic!^^\"\n | otherwise -> \"Chris\"\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = readLn >>= \\n-> solve =<< forM [1..n] (\\i -> map (fst.fromJust.C.readInt).C.words<$>C.getLine)\n--solve::Int->IO()\nsolve xs = let s= sum $ map (\\[a1,a2]-> signum (a2-a1) ) xs in if s<0 then putStr \"Mishka\" else if s>0 then putStr \"Chris\" else putStr \"Friendship is magic!^^\""}, {"source_code": "import Control.Monad\n\nmain = readInput >>= putStrLn . decide . count\n\nreadInput :: IO [(Int, Int)]\nreadInput = getLine >>= readLines . read >>= return . (map toTuple)\n where readLines n = mapM (\\_ -> getLine) [1..n]\n toTuple str = (parse 0, parse 1)\n where strs = words str\n parse i = read $ strs !! i\n \ncount :: [(Int, Int)] -> Int\ncount plays = foldr count' 0 plays\n where count' (m, c) tally\n | m < c = tally - 1\n | c < m = tally + 1\n | otherwise = tally\n \ndecide :: Int -> String\ndecide tally\n | tally < 0 = \"Chris\"\n | 0 < tally = \"Mishka\"\n | otherwise = \"Friendship is magic!^^\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nmain :: IO ()\nmain = do\n n <- readB8Int <$> B8.getLine\n qs <- replicateM n $ do\n [a, b] <- (map readB8Int . B8.words) <$> B8.getLine\n return [a, b]\n let delta = sum . map (\\[a, b] -> signum (a - b)) $ qs\n answer\n | delta > 0 = \"Mishka\"\n | delta < 0 = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\n printf \"%s\" answer"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess r1 r2 | x==y = \"Friendship is magic!^^\"\n | x>y = \"Mishka\"\n | otherwise = \"Chris\"\n where x = length $ filter (\\(z1, z2) ->z1 >z2) $ zip r1 r2\n y = length $ filter (\\(z1, z2) ->z1 >z2) $ zip r2 r1\n\nmain = do\n n<-read <$> getLine ::IO Int\n [r1,r2]<- transpose <$> map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]\n putStrLn $ process r1 r2\n"}, {"source_code": "main = interact $ format . uncurry compare . foldl resolve (0,0) . parse\nformat GT = \"Mishka\"\nformat LT = \"Chris\"\nformat EQ = \"Friendship is magic!^^\"\nparse = pairs . map read . tail . words where\n pairs (a:b:xs) = (a,b :: Int) : pairs xs\n pairs [] = []\nresolve (a,b) (c,d) = case compare c d of\n GT -> (a+1,b)\n LT -> (a,b+1)\n EQ -> (a,b)\n"}, {"source_code": "main = getContents >>= putStrLn . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> String\nsolve ls\n | 0 < x = \"Mishka\"\n | 0 > x = \"Chris\"\n | otherwise = \"Friendship is magic!^^\"\n where x = sum $ map (\\[m, c] -> if m > c then 1 else if m < c then -1 else 0) ls\n\n\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n\n winnerCounter :: Int -> Int -> (Int, Int) -> (Int, Int)\n winnerCounter x y (a, b)\n | x < y = (a, b + 1)\n | x > y = (a + 1, b)\n | x == y = (a, b)\n\n winnerCounterLoop :: [(Int, Int)] -> (Int, Int) -> (Int, Int)\n winnerCounterLoop [] result = result\n winnerCounterLoop ((p, q):xs) acc = winnerCounterLoop xs $ winnerCounter p q acc\n\n winner :: (Int, Int) -> String\n winner (x, y)\n | x > y = \"Mishka\"\n | x < y = \"Chris\"\n | x == y = \"Friendship is magic!^^\"\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n toTuple :: [Int] -> (Int, Int)\n toTuple [x, y] = (x, y)\n\n main :: IO ()\n main = do\n n <- getLine >>= return . readInt\n inputs <- replicateM n (getLine >>= return . toTuple . map readInt . words)\n putStrLn $ winner $ winnerCounterLoop inputs (0, 0)\n"}, {"source_code": "import Control.Monad( replicateM)\ndata Winner = Mishka | Chrith deriving Eq\nmain = do\n n <- readLn\n let inning = do\n\t [m,c] <- return . map (read::String->Int) . words =<< getLine\n\t if mc\n\t\t then return $ Just Mishka\n\t\t else return Nothing\n wins <- replicateM n inning\n let ws = filter (/= Nothing) wins\n\tchris = length $ filter (==Just Chrith) ws\n\tmishka = length $ filter (==Just Mishka) ws\n if chris>mishka\n\tthen putStrLn \"Chris\"\n\telse if chris Int -> Int -> String\nsol [] a b = if a > b\n then \"Mishka\"\n else if b > a\n then \"Chris\"\n else \"Friendship is magic!^^\"\n\nsol res a b = if (head (head res)) > (last (head res))\n then (sol (tail res) (a+1) b)\n else (sol (tail res) a (1+b))\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n inputs <- replicateM n getLine :: IO [String]\n let input_i = fmap (map read.words) inputs :: [[Int]]\n putStrLn (sol input_i 0 0)\n\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Function\n\nmain = do\n count <- read <$> getLine\n inputs <- sequence $ replicate count getLine\n\n let (mish, chris) =\n inputs\n & map (map read . words)\n & map (\\[x,y] -> compare x (y::Int))\n & filter (/= EQ)\n & partition (== LT)\n mishLen = length mish\n chrisLen = length chris\n\n print $ if mishLen > chrisLen\n then \"Mishka\"\n else if mishLen < chrisLen\n then \"Chris\"\n else \"Friendship is magic!^^\"\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Function\n\nmain = do\n count <- read <$> getLine\n inputs <- sequence $ replicate count getLine\n\n let (mishka, chris) = inputs\n & map (map read . words)\n & map (\\[x,y] -> x - y)\n & filter (/= 0)\n & partition (> 0)\n\n print $ case compare (length mishka) (length chris) of\n GT -> \"Mishka\"\n LT -> \"Chris\"\n EQ -> \"Friendship is magic!^^\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess r1 r2 | x==y = \"Friendship is magic!^^\"\n | x>y = \"Mishka\"\n | otherwise = \"Chris\"\n where x = zipWith (\\z1 z2 ->z1 >z2) r1 r2\n y = zipWith (\\z1 z2 ->z1 >z2) r2 r1\n\nmain = do\n n<-read <$> getLine ::IO Int\n [r1,r2]<- transpose <$> map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]\n putStrLn $ process r1 r2\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess r1 r2 | x==y = \"Friendship is magic!^^\"\n | xz1 >z2) r1 r2\n y = zipWith (\\z1 z2 ->z1 >z2) r2 r1\n\nmain = do\n n<-read <$> getLine ::IO Int\n [r1,r2]<- transpose <$> map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]\n putStrLn $ process r1 r2\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n\n winnerCounter :: Int -> Int -> (Int, Int) -> (Int, Int)\n winnerCounter x y (a, b)\n | x < y = (a, b + 1)\n | x > y = (a + 1, b)\n | x == y = (a, b)\n\n winnerCounterLoop :: [(Int, Int)] -> (Int, Int) -> (Int, Int)\n winnerCounterLoop [] result = result\n winnerCounterLoop ((p, q):xs) acc = winnerCounterLoop xs $ winnerCounter p q acc\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n toTuple :: [Int] -> (Int, Int)\n toTuple [x, y] = (x, y)\n\n main :: IO ()\n main = do\n n <- getLine >>= return . readInt\n inputs <- replicateM n (getLine >>= return . toTuple . map readInt . words)\n putStrLn $ show $ winnerCounterLoop inputs (0, 0)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n x\t| x==[] = if n>0 then \"Mishka\" else if n==0 then \"Friendship is magic!^^\" else \"Chris\"\n \t\t| otherwise = process n1 (tail x)\n\twhere \taa= head x\n\t\tn1 | aa!!0 getLine ::IO Int\n\tx<-map(map read) <$> map words <$> lines <$> getContents:: IO [[Int]]\n\tputStrLn $ process 0 x\n"}], "src_uid": "76ecde4a445bbafec3cda1fc421e6d42"} {"source_code": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nimport Control.Monad\nimport Data.Int\nimport Data.Array\n\np :: Int64\np = 10^9 + 7\n\nnewtype Mod = Mod { rsdu :: Int64 }\n deriving (Enum, Eq)\n\ninstance Num Mod where\n (Mod a) + (Mod b) = Mod $ if c < p then c else c - p\n where c = a + b\n (Mod a) * (Mod b) = Mod $ c `mod` p\n where c = a * b\n abs = id\n signum (Mod a) = Mod $ if a /= 0 then 1 else 0\n fromInteger a = Mod $ fromInteger $ a `mod` toInteger p\n negate (Mod a) = Mod $ if a /= 0 then p - a else 0\n\ninvmod a = a ^ (p-2)\n\nfact :: Int -> Mod\nfact = (a !)\n where\n a = listArray (0, maxn) $ scanl (*) 1 [1 .. fromIntegral maxn]\n maxn = 2 * 10^5 + 5\n\nifact = invmod . fact\n\nn `choose` k\n | k < 0 || n-k < 0 = 0\n | otherwise = fact n * ifact k * ifact (n-k)\n\ncs n\n | odd n = offset [0, 1]\n | otherwise = offset [0]\n where offset = map (+ n `div` 2)\n\nsolve n l r c = fromIntegral k' * calc 0 0 + sum (takeWhile (/= 0) $ zipWith calc lo ro)\n where\n k' = min (1-l) (r-n)\n ks = [k'+1..]\n\n lo = map (max 0 . subtract (1-l)) ks\n ro = map (max 0 . subtract (r-n)) ks\n\n calc lo ro = (n - lo - ro) `choose` (c - lo)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, l, r] <- map read . words <$> getLine\n print $ rsdu $ sum $ map (solve n l r) $ cs n\n", "positive_code": [{"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.Array.IArray ( (!), amap, listArray, Array )\r\nimport Data.Int ( Int64 )\r\n\r\nm :: Int64\r\nm = 1000000007\r\n\r\nnewtype MInt = MInt Int64 deriving Show\r\n\r\ntoInt64 :: MInt -> Int64\r\ntoInt64 (MInt a) = a\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b\r\n MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger i = MInt $ fromInteger i `mod` m\r\n\r\ninv :: MInt -> MInt\r\ninv a = a ^ (m - 2)\r\n\r\nchoose :: Int -> Int -> MInt\r\nchoose = c where\r\n c n k | k < 0 || k > n = 0\r\n | otherwise = (fac!n) * (ifac!k) * (ifac!(n - k))\r\n fac' = 1 : zipWith ((*) . fromIntegral) [1..] fac'\r\n fac = listArray (0, 2 * 10^5) fac' :: Array Int MInt\r\n ifac = amap inv fac\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, l, r] <- readMany :: IO [Int]\r\n let h = n `div` 2\r\n p = min (1 - l) (r - n)\r\n ans1 = choose n h * (if odd n then 2 else 1) * fromIntegral p\r\n calc k = if rem < 0 then 0 else c where\r\n c = choose rem (h - fl) + if odd n then choose rem (h - fl + 1) else 0\r\n fl = max 0 $ k - 1 + l\r\n fr = max 0 $ k - r + n\r\n rem = n - fl - fr\r\n ans2 = sum $ map calc [p + 1 .. p + n]\r\n print $ toInt64 $ ans1 + ans2\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n foldl', intersect, isPrefixOf, nub,\n sort, sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (for, forM)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\nimport GHC.IO.Handle (hDuplicateTo)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> fst . fromJust\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> fst . fromJust\n\nreadIntegralB8 :: (Integral a) => B8.ByteString -> a\nreadIntegralB8 = B8.readInteger >>> fst . fromJust >>> fromInteger\n\n\nnewtype Cache = Cache {\n factorialMods :: A.Array Int Int64\n}\n\nmd :: Int64\nmd = 1_000_000_007\n\npowMod :: Int64 -> Int64 -> Int64 -> Int64\npowMod md _ 0 = 1 `mod` md\npowMod md a 1 = a `mod` md\npowMod md a n | even n =\n let sqrtResult = powMod md a (n `div` 2)\n in (sqrtResult ^ 2) `mod` md\npowMod md a n | odd n =\n let prevPowMod = powMod md a (n - 1)\n in (prevPowMod * a) `mod` md\n\nfactorialMod :: Cache -> Int64 -> Int64\nfactorialMod cache n = factorialMods' A.! fromIntegral n\n where\n factorialMods' :: A.Array Int Int64\n factorialMods' = factorialMods cache\n\ncombinationsMod :: Cache -> Int64 -> (Int64, Int64) -> Int64\ncombinationsMod _ _ (n, _) | n < 0 = 0\ncombinationsMod _ _ (n, k) | k < 0 = 0\ncombinationsMod _ _ (n, k) | n < k = 0\ncombinationsMod cache md (n, k) =\n nFactorial * denomInverse `mod` md\n where\n nFactorial = factorialMod cache n\n kFactorial = factorialMod cache k\n n_kFactorial = factorialMod cache (n - k)\n\n denomInverse = powMod md (n_kFactorial * kFactorial `mod` md) (md - 2)\n\nbuildCache :: Int -> Int64 -> Cache\nbuildCache maxN md =\n Cache factorialMods'\n where\n factorialMods' = A.listArray (0, maxN) . scanl (\\prod e -> prod * fromIntegral e `mod` md) 1 $ [1 .. maxN]\n\n\nsolve :: Cache -> Int -> (Int64, Int64) -> Int64\nsolve cache n (l, r) = (`mod` md) $\n (trailingK - fromK) * subtaskSolve 1 +\n (sum . map subtaskSolve $ [trailingK .. toK])\n where\n fromK = 1\n trailingK = max fromK . (+ (-10)) $ min (r - fromIntegral n) (1 - l)\n toK = 1 + min (r - 1) (fromIntegral n - l)\n\n subtaskSolve k =\n subarraySolve (usedMinus, usedPlus)\n where\n usedPlus = max 0 $ l + k - 1\n usedMinus = max 0 $ fromIntegral n - (r - k)\n\n subarraySolve (usedMinus, usedPlus) | even n =\n combinationsMod cache md (minusCount + plusCount, plusCount)\n where\n minusCount = fromIntegral n `div` 2 - usedMinus\n plusCount = fromIntegral n `div` 2 - usedPlus\n\n subarraySolve (usedMinus, usedPlus) | odd n = (`mod` md) $\n combinationsMod cache md (minusCount + plusCount + 1, plusCount) +\n combinationsMod cache md (minusCount + plusCount + 1, minusCount)\n where\n minusCount = fromIntegral (n `div` 2) - usedMinus\n plusCount = fromIntegral (n `div` 2) - usedPlus\n\n\nmain :: IO ()\nmain = do\n tests <- B8.getLine <&> readIntB8\n let cache = buildCache 300_000 md\n replicateM_ tests $ do\n [n, l, r] :: [Int64] <- B8.getLine <&> map readIntegralB8 . B8.words\n\n let answer = solve cache (fromIntegral n) (l, r)\n\n printf \"%lld\\n\" answer\n"}], "negative_code": [], "src_uid": "d8066e517678dfd6a11f2bfa9e0faed0"} {"source_code": "main :: IO ()\n\nmain = interact (format' . solve . format)\n\nsolve :: [[Int]] -> [String]\nsolve = map solver\n\nformat' = unlines\n\nsolver :: [Int] -> String\nsolver xs\n | all odd xs = \"YES\"\n | all even xs = \"YES\"\n | otherwise = \"NO\"\n \nformat :: String -> [[Int]]\nformat xs = map (map read . words . snd) . filter (odd . fst) . (zip [0..]) . tail . lines $ xs\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nmain = readLn >>= (`replicateM` solve)\nsolve = do\n getLine\n a <- map read.words <$> getLine\n putStrLn $ if (==1).length.group.map(`mod`2) $ a then \"YES\" else \"NO\"\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n getLine\n as <- map read.words <$> getLine\n putStrLn $ if all ((== odd (head as)).odd) as then \"YES\" else \"NO\"\n test (i - 1)\n"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n getLine\n xs <- map ((`mod` 2) . read) . words <$> getLine\n if allEqual xs then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n\nallEqual [] = True\nallEqual [x] = True\nallEqual (x:y:zs) = x == y && allEqual (y:zs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\t\n\t\tgetLine\n\t\td<-map read <$> words <$> getLine ::IO [Integer]\n\t\tputStrLn $ if all even d || all odd d then \"YES\" else \"NO\"\n\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Monad\n\nsolve [] = return ()\nsolve (ts:tss) = do\n putStrLn res\n solve tss\n where\n res \n | anye && anyo = \"NO\"\n | otherwise = \"YES\"\n anye = any even ts\n anyo = any odd ts\n \n\nmain = do\n t <- readLn :: IO Int\n tss <- replicateM t $ do\n getLine\n xs <- map read . words <$> getLine :: IO [Int]\n return xs\n solve tss\n"}, {"source_code": "process :: [Int] -> Bool\nprocess xs@(x:_) = and.map even.map (subtract x) $ xs\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n if process as\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n{-# LANGUAGE MultiWayIf #-}\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n n <- read <$> getLine\n as <- map read.words <$> getLine\n putStrLn $ if\n | odd n || even (sum as) -> \"YES\"\n | otherwise -> \"NO\"\n test (i - 1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\t\n\t\tgetLine\n\t\td<-map read <$> words <$> getLine ::IO [Integer]\n\t\tputStr $ if all even d || all odd d then \"YES\" else \"NO\"\n\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Monad\n\nsolve [] = return ()\nsolve (ts:tss) = do\n putStrLn res\n solve tss\n where\n res\n | even (maximum ts - minimum ts) = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n t <- readLn :: IO Int\n tss <- replicateM t $ do\n getLine\n xs <- map read . words <$> getLine :: IO [Int]\n return xs\n solve tss\n"}], "src_uid": "53a3313f5d6ce19413d72473717054fc"} {"source_code": "import Data.Char (ord)\r\n\r\nsolve :: IO ()\r\nsolve = map ((\\c -> c - ord 'a') . ord) <$> getLine >>= \\ [a, b] ->\r\n print $ a * 25 + if b < a then b + 1 else b\r\n\r\nmain :: IO ()\r\nmain = \r\n let f 0 = return ()\r\n f t = solve >> f (t - 1)\r\n in readInt <$> getLine >>= f\r\n \r\nreadInt :: String -> Int\r\nreadInt = read", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\n\r\nencodeChar x = ord x - ord 'a'\r\n\r\nsolve (x:y:z) = encodeChar x * 25 + encodeChar y + 1 - if x < y then 1 else 0\r\n\r\nmain = do\r\n t <- readInt\r\n lines <- replicateM t getLine\r\n putStrLn $ intercalate \"\\n\" (map (\\x -> show $ solve x) lines)\r\n\r\n-- Just IO\r\nreadInt = do\r\n line <- getLine\r\n return (read line :: Int)"}], "negative_code": [], "src_uid": "2e3006d663a3c7ad3781aba1e37be3ca"} {"source_code": "import Data.List\n\nmain :: IO ()\n\nmain = do\n\tfirstVals <- fmap (map read . words) getLine :: IO [Int] \n\tcontrolPoints <- fmap (map read . words) getLine :: IO [Int]\n\tprint (calcAllButOne (sort controlPoints) (firstVals !! 1))\n\ncalcAll :: (Integral a) => [a] -> a -> a\ncalcAll [] stpoint = 0\ncalcAll points stpoint\n\t| stpoint < firstelem = lastelem - stpoint\n\t| stpoint > lastelem = stpoint - firstelem\n\t| otherwise = min (stpoint - firstelem) (lastelem - stpoint) + lastelem - firstelem\n\twhere \tfirstelem = head points\n\t\tlastelem = last points\n\ncalcAllButOne :: (Integral a) => [a] -> a -> a\ncalcAllButOne [] stpoint = 0\ncalcAllButOne points stpoint = min (calcAll (tail points) stpoint) (calcAll (init points) stpoint)\n\n-- quicksort works\n--quicksort :: (Ord a) => [a] -> [a]\n--quicksort [] = []\n--quicksort (x:xs) = \n--\tlet smallerSorted = quicksort [a | a <- xs, a <= x]\n--\t biggerSorted = quicksort [a | a <- xs, a > x]\n--\tin smallerSorted ++ [x] ++ biggerSorted \n", "positive_code": [{"source_code": "import Data.List\n\nimport Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.f.parse.words\nparse = map fastRead\n\ng [] cur ans = ans\ng (x:xs) cur ans = g xs x (ans + (abs (cur-x)))\n\nf (cnt:x:xs) = minimum [(g (aa++ba) x 0),\n (g (ca++da) x 0),\n (g (ab++bb) x 0),\n (g (cb++db) x 0)]\n where y = (sort xs)\n i = init y\n j = tail y\n\n aa = (reverse (filter (<=x) i))\n ba = (filter (>x) i)\n ca = (reverse (filter (<=x) j))\n da = (filter (>x) j)\n\n ab = (filter (>=x) i)\n bb = (reverse (filter (=x) j)\n db = (reverse (filter ( Int -> Int\ndist x y = abs $ x - y\n\nprocess' :: Int -> [Int] -> Int\nprocess' a [_] = 0\nprocess' a x =\n let (fst: snd: _) = x\n (ufst:usnd:_) = reverse x\n in minimum\n [\n dist a fst + dist fst usnd,\n dist a snd + dist snd ufst,\n dist a ufst + dist ufst snd,\n dist a usnd + dist usnd fst\n ]\n\nprocess :: String -> String\nprocess str = \n let [header, body] = lines str\n [n, a] = map read . words $ header\n x = sort . map read . take n . words $ body\n in show $ process' a x\n\nmain :: IO ()\nmain = interact process"}], "negative_code": [{"source_code": "main :: IO ()\n\nmain = do\n firstVals <- fmap (map read . words) getLine :: IO [Int]\n controlPoints <- fmap (map read . words) getLine :: IO [Int]\n print (calcAllButOne (quicksort controlPoints) (firstVals !! 1))\n\nwalkleft :: (Integral a) => [a] -> a -> a\nwalkleft [] stpoint = 0\nwalkleft (firstElem: points) stpoint\n | firstElem < stpoint = stpoint - firstElem\n | firstElem >= stpoint = 0\n\nwalkright :: (Integral a) => [a] -> a -> a\nwalkright [] stpoint = 0\nwalkright points stpoint\n | lastElem > stpoint = lastElem - stpoint\n | lastElem <= stpoint = 0\n where lastElem = last points\n\ncalcAllButOne :: (Integral a) => [a] -> a -> a\ncalcAllButOne [] stpoint = 0\ncalcAllButOne points stpoint\n | leftFull == 0 = rightm1\n | rightFull == 0 = leftm1\n | leftm1 == 0 || rightm1 == 0 = min\n (min (2 * leftFull + rightm1) rightFull)\n (min (2 * rightFull + leftm1) leftFull)\n | otherwise = min (2 * leftFull + rightm1) (2 * rightFull + leftm1)\n where leftFull = walkleft points stpoint\n rightFull = walkright points stpoint\n leftm1 = walkleft (tail points) stpoint\n rightm1 = walkright (init points) stpoint\n\n\n-- quicksort works\nquicksort :: (Ord a) => [a] -> [a]\nquicksort [] = []\nquicksort (x:xs) =\n let smallerSorted = quicksort [a | a <- xs, a <= x]\n biggerSorted = quicksort [a | a <- xs, a > x]\n in smallerSorted ++ [x] ++ biggerSorted"}, {"source_code": "import Data.List\n\nimport Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.f.parse.words\nparse = map fastRead\n\ng [] cur ans = ans\ng (x:xs) cur ans = g xs x (ans + (abs (cur-x)))\n\nf (cnt:x:xs) = minimum [(g (aa++ba) x 0),\n (g (ca++da) x 0),\n (g (ab++bb) x 0),\n (g (cb++db) x 0)]\n where y = (sort xs)\n i = init y\n j = tail y\n\n aa = (reverse (filter (<=x) i))\n ba = (filter (>x) i)\n ca = (reverse (filter (<=x) j))\n da = (filter (>x) j)\n\n ab = (reverse (filter (>=x) i))\n bb = (filter (=x) j))\n db = (filter ( Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.f.parse.words\nparse = map fastRead\n\n\ng i j cur ans 0 = ans\ng [] (y:ys) cur ans cnt = g [] ys y (ans + (abs (cur-y))) (cnt-1)\ng (x:xs) [] cur ans cnt = g xs [] x (ans + (abs (cur-x))) (cnt-1)\ng i@(x:xs) j@(y:ys) cur ans cnt\n | (abs (cur-x)) <= (abs (cur-y)) = g xs j x (ans + (abs (cur-x))) (cnt-1)\n | otherwise = g i ys y (ans + (abs (cur-y))) (cnt-1)\n\nf (cnt:x:xs) = g (reverse (filter (<=x) y)) (filter (>x) y) x 0 (cnt-1)\n where y = (sort xs)\n"}], "src_uid": "7807c484035e0327870b6cac23c8d60a"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\r\n\r\nimport Data.List ( sort )\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve ints = take n $ concat $ zipWith (\\a b -> [a, b]) rotated nums where\r\n rotated = drop (n `div` 2) nums\r\n n = length ints\r\n nums = sort ints\r\n\r\nmain = interact $ unlines . map (unwords . map show) . loop . tail . lines where\r\n loop (_ : (map read . words -> nums) : rest) = solve nums : loop rest\r\n loop _ = []\r\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\r\n\r\nimport Data.List ( sort )\r\nimport Control.Monad ( replicateM_ )\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve n (sort -> nums)\r\n = take n nums `zip` drop n nums >>= \\(a, b) -> [a, b]\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine \r\nputInts = putStrLn . unwords . map show\r\n\r\nmain = do n <- getInt\r\n replicateM_ n (solve <$> getInt <*> getInts >>= putInts)\r\n"}, {"source_code": "\r\nimport Data.List ( sort, transpose )\r\nimport Control.Monad ( replicateM_ )\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve n ints = concat (transpose [take n nums, drop n nums]) where\r\n nums = sort ints\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine \r\nputInts = putStrLn . unwords . map show\r\nmain = do\r\n n <- getInt\r\n replicateM_ n (solve <$> getInt <*> getInts >>= putInts)"}, {"source_code": "\r\nimport Data.List ( sort )\r\nimport Control.Monad ( replicateM_ )\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve n ints = concat $ zipWith (++) rotated nums where\r\n nums = pure <$> sort ints\r\n rotated = drop n nums\r\n\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine \r\n\r\nmain = do\r\n n <- getInt\r\n replicateM_ n (solve <$> getInt <*> getInts >>= putStrLn . unwords . map show)"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\r\n\r\nimport Data.List ( sort )\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve n ints = concat $ zipWith (++) rotated nums where\r\n nums = pure <$> sort ints\r\n rotated = drop n nums\r\n\r\nmain = interact $ unlines . loop . tail . lines where\r\n loop ((read -> n) : (map read . words -> nums) : rest)\r\n = unwords (map show $ solve n nums) : loop rest\r\n loop _ = mempty\r\n"}, {"source_code": "import Data.List (transpose, sort)\r\n\r\nodds (x:xs) = x : evens xs\r\nodds [] = []\r\n\r\nevens (_:xs) = odds xs\r\nevens [] = []\r\n\r\nsplit a = [take l a, drop l a]\r\n where l = length a `div` 2\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve = concat . transpose . split . sort\r\n\r\nsolveLine =\r\n unwords . map show . solve . map read . words\r\n\r\nmain = interact $ unlines . map solveLine . evens . tail . lines\r\n"}, {"source_code": "import Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprint1 [] [] = \"\"\r\nprint1 (x:xs) (y:ys) = (show x)++\" \"++(show y)++\" \" ++ print1 xs ys\r\n\r\nmain = do\r\n entry <- getLine\r\n let timer = read entry :: Int\r\n forM_ [1..timer] $ \\_ -> do\r\n n <- readLn :: IO Int\r\n array <- readInts\r\n let sorted = sort array\r\n b = take n sorted\r\n c = take n $ reverse sorted\r\n let ans = print1 b c\r\n putStrLn(ans)"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprint1 [] [] = \"\"\r\nprint1 (x:xs) (y:ys) = (show x)++\" \"++(show y)++\" \" ++ print1 xs ys\r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let sorted = sort a \r\n b = take n sorted \r\n c = reverse $ drop n sorted \r\n putStrLn $ print1 b c\r\n\r\nmain = do\r\n t<-readLn :: IO Int \r\n replicateM_ t printS"}, {"source_code": "import Control.Monad\nimport Data.List (sort)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- sort . map read . words <$> getLine :: IO [Int]\n putStrLn $ unwords $ [0 .. n - 1] >>= \\x -> show . (a !!) <$> [x, x + n]\n"}, {"source_code": "import Control.Monad \r\nimport Data.List\r\nmain = do \r\n t <- (read <$> getLine) :: IO Int \r\n --putStrLn $ show t \r\n \r\n replicateM_ t $ do \r\n n <- (read <$> getLine) :: IO Int \r\n xs <- (sort . map read . words <$> getLine) :: IO [Int]\r\n let ys = reverse xs\r\n forM_ (take n $ zip xs ys) $ (\\(x, y) -> putStr $ show x ++ \" \" ++ show y ++ \" \")\r\n putStrLn \"\"\r\n -- putStrLn $ show xs"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- getInts\n let (xs, ys) = splitAt n $ sort as\n str = mconcat $ intersperse (charUtf8 ' ') $ map intDec $ concatMap (\\(x, y) -> [x, y]) $ zip xs ys\n return $ str `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [{"source_code": "\r\nimport Data.List ( sort, transpose )\r\nimport Control.Monad ( replicateM_ )\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve n ints = concat (transpose [nums, rotated]) where\r\n nums = sort ints\r\n rotated = drop n nums\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine \r\nputInts = putStrLn . unwords . map show\r\nmain = do\r\n n <- getInt\r\n replicateM_ n (solve <$> getInt <*> getInts >>= putInts)"}, {"source_code": "import Data.List (transpose)\r\n\r\nodds (x:xs) = x : evens xs\r\nodds [] = []\r\n\r\nevens (_:xs) = odds xs\r\nevens [] = []\r\n\r\nsplit a = [take l a, drop l a]\r\n where l = length a `div` 2\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve = concat . transpose . split\r\n\r\nsolveLine =\r\n unwords . map show . solve . map read . words\r\n\r\nmain = interact $ unlines . map solveLine . evens . tail . lines\r\n"}], "src_uid": "4296da660a39a6e98b41387929701c0a"} {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve l = min (div (sum l) 2) (sum l - (maximum l))\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n \nroutine :: IO ()\nroutine = do\n l <- (map read).words <$> getLine\n print $ solve l", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\ngetList :: (Read a) => IO [a]\ngetList = map read <$> words <$> getLine\n\ngetNLists :: (Read a) => Int -> IO [[a]]\ngetNLists n = sequence $ replicate n getList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b, c] <- sort <$> getList\n print $ f a b c\n\nf :: Int -> Int -> Int -> Int\nf a b c\n | a + b <= c = a + b\n | otherwise = div (a + b + c) 2"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n (r:g:b:_) <- sort.map read.words <$> getLine\n print $ solve r g b\n test (i - 1)\n\nsolve r g b\n | r + g < b = r + g\n | otherwise = div (r + g + b) 2\n"}], "negative_code": [], "src_uid": "1f29461c42665523d0a4d56b13f7e480"} {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t getLine\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nsolve xs = show $ (length xs -) . maximum . map length . filter ((>=2).length) . map drop2 . filter (not.null.snd) . map (dropTail xs) $ \"05\"\r\n\r\ndropTail xs c = (,) c . reverse . dropWhile (/= c) . reverse $ xs\r\n\r\ndrop2 (c, xs) = reverse . (c:) . dropPref2 (next c) . tail . reverse $ xs\r\n\r\ndropPref2 cs xs = dropWhile (not . (`elem` cs)) xs\r\n\r\nnext '5' = \"27\"\r\nnext '0' = \"05\"\r\nnext _ = error \"Internal: bad char\"\r\n", "positive_code": [{"source_code": "import Data.Function (on)\r\nimport Data.List\r\n\r\nyesNo False = \"NO\"\r\nyesNo True = \"YES\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nreadBigInt :: String -> Integer\r\nreadBigInt = read\r\n\r\n\r\nsolve_task :: String -> String\r\nsolve_task line = let number = readBigInt line\r\n kToS xs n | n == 0 = 0\r\n | n `mod` 10 `elem` xs = 0\r\n | otherwise = 1 + kToS xs (n `div` 10)\r\n k0 = kToS [0] number\r\n k5 = kToS [5] number\r\n in show $ min (k0 + kToS [0,5] (number `div` 10^(k0+1))) (k5 + kToS [2,7] (number `div` 10^(k5+1)))\r\n\r\nsolve_tasks (t:tasks) = map solve_task tasks\r\n\r\nsolve = unlines . solve_tasks . lines\r\n\r\nmain = interact solve"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {s :: String}\n\ninput :: Scanner TC\ninput = do\n s <- str\n return TC {..}\n\noutput = showB\n\nsolve :: TC -> Int\nsolve TC {..} = minimum $ map (cost $ reverse s) [\"00\", \"52\", \"05\", \"57\"]\n where\n cost _ [] = 0\n cost [] _ = 10^5\n cost (x:xs) (p:ps)\n | p == x = cost xs ps\n | otherwise = 1 + cost xs (p:ps)\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad (replicateM_, forM_, forM)\r\nimport Control.Applicative ()\r\n\r\nnextList :: IO [Int]\r\nnextList = map read.words <$> getLine\r\n\r\ngo :: [Char] -> Char -> Char -> Int -> Int -> Int\r\ngo _ _ _ (-1) _ = -20\r\ngo arr first second current state = \r\n case state of \r\n 0 -> if first == (arr !! current) then go arr first second (current - 1) 1 else go arr first second (current - 1) 0\r\n 1 -> if second == (arr !! current) then current else go arr first second (current - 1) 1\r\n _ -> 0\r\n\r\nsolve = do\r\n n <- getLine\r\n let ans = [go n '0' '0' (length n - 1) 0\r\n , go n '5' '2' (length n - 1) 0\r\n , go n '0' '5' (length n - 1) 0\r\n , go n '5' '7' (length n - 1) 0]\r\n print $ length n - maximum ans - 2\r\n return ()\r\n\r\nmain = do\r\n [t] <- nextList\r\n replicateM_ t solve\r\n "}], "negative_code": [], "src_uid": "ab6fefc6c15d4647bc601f1f9db21d3f"} {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\n\nimport Data.Array.MArray\nimport Data.Array.ST\n\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\na ! i = readArray a i\na !< i = \\e -> writeArray a i e\n\nmain = putStrLn . show . solve . readInput =<< B.getContents\n\nreadInput s = let n:m:xs = map (fst . fromJust . B.readInt) $ B.words s\n in (n, m, xs)\n\nsolve (n, m, xs0) =\n let xs1 = sortBy (flip compare) . zip xs0 $ map (`divMod` m) [0..length xs0 - 1]\n in runST $ do\n row <- newArray (0, n-1) [] :: ST s (STArray s Int [Int])\n col <- newArray ((0, 0), (m-1, m-1)) False :: ST s (STUArray s (Int, Int) Bool)\n\n let go [] = return 0\n go ((x, (r, c)):xs) = do\n cs <- row ! r\n\n res <- forM cs $ \\c' -> do\n got <- col ! (c, c')\n if got\n then return True\n else do\n col !< (c, c') $ True\n col !< (c', c) $ True\n return False\n\n if or res\n then return x\n else do\n row !< r $ c:cs\n go xs\n go xs1\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\n\nimport Data.Array.MArray\nimport Data.Array.ST\n\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nmain = putStrLn . show . solve . readInput =<< B.getContents\n\nreadInput s = let n:m:xs = map (fst . fromJust . B.readInt) $ B.words s\n in (n, m, xs)\n\nsolve (n, m, xs0) =\n let xs1 = sortBy (flip compare) . zip xs0 $ map (`divMod` m) [0..length xs0 - 1]\n in runST $ do\n row <- newArray (0, n-1) [] :: ST s (STArray s Int [Int])\n col <- newArray ((0, 0), (m-1, m-1)) False :: ST s (STUArray s (Int, Int) Bool)\n\n let go [] = return 0\n go ((x, (r, c)):xs) = do\n cs <- readArray row r\n\n res <- forM cs $ \\c1 -> do\n got <- readArray col (c, c1)\n if got\n then return True\n else do\n writeArray col (c, c1) True\n writeArray col (c1, c) True\n return False\n\n if or res\n then return x\n else do\n writeArray row r (c:cs)\n go xs\n go xs1\n"}], "negative_code": [], "src_uid": "ea0aadcea3a5de4e625a0862f637d1c8"} {"source_code": "{-# LANGUAGE InstanceSigs, MultiParamTypeClasses, UndecidableSuperClasses, MultiWayIf, KindSignatures, \r\nOverloadedLists,ApplicativeDo,OverloadedStrings,MonadComprehensions,ParallelListComp,TransformListComp, TupleSections,\r\nBlockArguments, TypeApplications, PostfixOperators, TypeOperators, BangPatterns, LambdaCase, UnboxedSums, UnboxedTuples, RankNTypes, \r\nFlexibleContexts,DeriveFoldable, DeriveTraversable, ScopedTypeVariables, GADTs, PatternSynonyms, ViewPatterns, FunctionalDependencies #-}\r\nimport Data.List (group, sort, groupBy, partition)\r\nimport qualified Data.ByteString.Lazy.Char8 as L\r\nimport Data.Function ((&),fix,on)\r\nimport Data.Maybe (fromJust, isNothing)\r\nimport Data.Bifunctor (bimap)\r\nimport GHC.Int (Int64)\r\nint :: L.ByteString -> Int\r\nint = fst . fromJust . L.readInt\r\nreadInts ::L.ByteString -> [Int]\r\nreadInts = map int . L.split ' '\r\n\r\n-- solve :: [Int] -> L.ByteString\r\n-- solve = L.pack . show . uncurry min . bimap length length . partition even\r\n\r\ntwos :: [L.ByteString] -> [(Int,Int,L.ByteString)]\r\ntwos [] = []\r\ntwos (x:y:xs) = (a,b,y) : twos xs\r\n where (a:b:_) = readInts x\r\n\r\n\r\n\r\nprocess :: L.ByteString -> (Maybe (Int,Int), Int)\r\nprocess xs = (f $ L.elemIndices '1' xs, 11* (fromIntegral $ L.count '1' xs))\r\n where f :: [Int64] -> Maybe (Int,Int)\r\n f [] = Nothing\r\n f [x] = Just (1+fromIntegral x,1+fromIntegral x)\r\n f (x:zs) = Just (1+fromIntegral x,succ$fromIntegral $ last zs)\r\n\r\n\r\nsolve'::(Maybe (Int,Int),Int) -> Int -> Int -> Int\r\nsolve' (Just (a, b), points) len k\r\n | points' == 1 = 1 --moved only 1 to far right\r\n | k' >= a - 1 = pred points'\r\n | otherwise = points'\r\n where (k',points') = if k >= len - b then (k - (len - b),points-10) else (k,points)\r\nsolve' _ _ _ = 0\r\n\r\nsolve :: (Int, Int, L.ByteString) -> Int\r\nsolve (len,k,xs) = solve' (process xs) len k\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do (n:xs) <- L.lines <$> L.getContents\r\n L.putStr . L.unlines . map (L.pack.show.solve) . twos $ take (2*int n) xs\r\n\r\n\r\n \r\n --L.interact (L.unlines . map (solve . readInts) . twos . tail . L.lines)\r\n", "positive_code": [{"source_code": "calculate :: String -> Int\r\ncalculate [_] = 0\r\ncalculate s = (read (take 2 s) :: Int) + calculate (drop 1 s)\r\n\r\nsearch :: Eq t => Int -> t -> [t] -> Int\r\nsearch i k [] = -1\r\nsearch i k (x : xs)\r\n | (k == x) = i\r\n | otherwise = search (i + 1) k xs\r\n\r\nindexOf :: Eq t => t -> [t] -> Int\r\nindexOf k a = search 0 k a\r\n\r\nlastIndexOf :: Eq t => t -> [t] -> Int\r\nlastIndexOf k a\r\n | (index > -1) = (length a) - 1 - index\r\n | otherwise = -1\r\n where\r\n index = indexOf k (reverse a)\r\n\r\nans :: IO String\r\nans = do\r\n nkInput <- getLine\r\n sInput <- getLine\r\n let (n : k : []) = [read x :: Int | x <- words nkInput]\r\n let s = sInput\r\n let lastIndex = lastIndexOf '1' s\r\n let firstIndex = indexOf '1' s\r\n let needLast = n - 1 - lastIndex\r\n let needFirst = firstIndex\r\n let total = calculate s\r\n if lastIndex == -1 then do\r\n return \"0\"\r\n else if (lastIndex == firstIndex) then do\r\n if (k == 0) || (k < min needLast needFirst) then do\r\n return (show total)\r\n else if (needLast == 0) || (k >= needLast) then do\r\n return \"1\"\r\n else if (k >= needFirst) then do\r\n return \"10\"\r\n else do\r\n return \"must have else 1\"\r\n else if (k == 0) || (needLast == 0 && needFirst == 0) || (k < min needLast needFirst) || (needFirst == 0 && k < needLast) || (needLast == 0 && k < needFirst) then do\r\n return (show total)\r\n else if (needLast > 0) && (k >= needLast) && (needFirst > 0) && (k - needLast >= needFirst) then do\r\n return (show (total - 11))\r\n else if (needLast > 0) && (k >= needLast) && (needFirst == 0 || k - needLast < needFirst) then do\r\n return (show (total - 10))\r\n else if (needLast == 0 || k < needLast) && (needFirst > 0) && (k >= needFirst) then do\r\n return (show (total - 1))\r\n else do\r\n return \"must have else 2\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (unwords results)"}], "negative_code": [], "src_uid": "ccecf97fcddbd0ab030d34b79a42cc6e"} {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (takeWhile (>= 0) $ iterate (subtract 1) (target-s)) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, origX] <- readInts\n pLi <- readInts\n let\n x = min origX (n - origX)\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n isLeaf :: UArray Int Bool\n isLeaf = accumArray (\\_ _ -> False) True (1, n) $ zip pLi (repeat ())\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = if x == origX\n then accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n else accumArray (\\_ _ -> 'b') 'a' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n imperfectSoln = let\n go 0 0 [] = []\n go _ _ [] = error \"???\"\n go asLeft bsLeft (v:vs) = let\n currLen = length v\n currLeaves = filter (isLeaf !) v\n currLeafCt = length currLeaves\n currNonLeaves = filter (not . (isLeaf !)) v\n in if currLen <= asLeft\n then v ++ go (asLeft - currLen) bsLeft vs\n else if currLen <= bsLeft\n then go asLeft (bsLeft - currLen) vs\n else if currLeafCt >= asLeft\n then take asLeft currLeaves\n else if currLeafCt >= bsLeft\n then drop bsLeft currLeaves ++ currNonLeaves ++ concat vs\n else error \"this shouldn't be possible\"\n in go x (n-x) $ elems findByDepth\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1, toByteString imperfectSoln)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, origX] <- readInts\n pLi <- readInts\n let\n x = min origX (n - origX)\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n isLeaf :: UArray Int Bool\n isLeaf = accumArray (\\_ _ -> False) True (1, n) $ zip pLi (repeat ())\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = if x == origX\n then accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n else accumArray (\\_ _ -> 'b') 'a' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n imperfectSoln = let\n go 0 0 [] = []\n go _ _ [] = error \"???\"\n go asLeft bsLeft (v:vs) = let\n currLen = length v\n currLeaves = filter (isLeaf !) v\n currLeafCt = length currLeaves\n currNonLeaves = filter (not . (isLeaf !)) v\n in if currLen <= asLeft\n then v ++ go (asLeft - currLen) bsLeft vs\n else if currLen <= bsLeft\n then go asLeft (bsLeft - currLen) vs\n else if currLeafCt >= asLeft\n then take asLeft currLeaves\n else if currLeafCt >= bsLeft\n then drop bsLeft currLeaves ++ currNonLeaves ++ concat vs\n else error \"this shouldn't be possible\"\n in go x (n-x) $ elems findByDepth\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1, toByteString imperfectSoln)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, origX] <- readInts\n pLi <- readInts\n let\n x = min origX (n - origX)\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n isLeaf :: UArray Int Bool\n isLeaf = accumArray (\\_ _ -> False) True (1, n) $ zip pLi (repeat ())\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = if x == origX\n then accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n else accumArray (\\_ _ -> 'b') 'a' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n imperfectSoln = let\n go 0 0 [] = []\n go _ _ [] = error \"???\"\n go asLeft bsLeft (v:vs) = let\n currLen = length v\n currLeaves = filter (isLeaf !) v\n currLeafCt = length currLeaves\n currNonLeaves = filter (not . (isLeaf !)) v\n in if currLen <= asLeft\n then v ++ go (asLeft - currLen) bsLeft vs\n else if currLen <= bsLeft\n then go asLeft (bsLeft - currLen) vs\n else if currLeafCt >= asLeft\n then take asLeft currLeaves\n else if currLeafCt >= bsLeft\n then drop bsLeft currLeaves ++ currNonLeaves ++ concat vs\n else error \"this shouldn't be possible\"\n in go x (n-x) $ elems findByDepth\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1, toByteString imperfectSoln)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n let\n as = P.filter (== 'a') str\n when (P.length as /= fromIntegral x) $ lift . P.putStrLn . P.pack $ \"Yikes\"\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, x] <- readInts\n pLi <- readInts\n let\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n isLeaf :: UArray Int Bool\n isLeaf = accumArray (\\_ _ -> False) True (1, n) $ zip pLi (repeat ())\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n imperfectSoln = let\n go 0 0 [] = []\n go _ _ [] = error \"???\"\n go asLeft bsLeft (v:vs) = let\n currLen = length v\n currLeaves = filter (isLeaf !) v\n currLeafCt = length currLeaves\n in if currLen <= asLeft\n then v ++ go (asLeft - currLen) bsLeft vs\n else if currLen <= bsLeft\n then go asLeft (bsLeft - currLen) vs\n else if currLeafCt >= asLeft\n then take asLeft currLeaves\n else if currLeafCt >= bsLeft\n then drop bsLeft currLeaves ++ concat vs\n else error \"this shouldn't be possible\"\n in go x (n-x) $ elems findByDepth\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1, toByteString imperfectSoln)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, x] <- readInts\n pLi <- readInts\n let\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n imperfectSoln = let\n go as xleft [v] = take xleft v ++ as\n go _ _ [] = error \"???\"\n go as xleft (v:vs) = let\n newxleft = xleft - length v\n in if newxleft >= 0\n then go (v ++ as) newxleft vs\n else go as xleft vs -- old xleft, intentional\n in go [] x $ elems findByDepth\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1, toByteString imperfectSoln)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, x] <- readInts\n pLi <- readInts\n let\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1,\n toByteString . take x . concat $ elems findByDepth)\n let\n count li = let\n av = elem 'a' $ P.index str . fromIntegral . (subtract 1) <$> li\n bv = elem 'b' $ P.index str . fromIntegral . (subtract 1) <$> li\n in case (av, bv) of\n (False, False) -> error \"huh?\"\n (True, True) -> 2\n _ -> 1\n approxScore = sum [count li | li <- elems findByDepth, not (null li)]\n -- This should be triggered if there are the wrong number of distinct strings\n -- If this doesn't activate on test case 12 I will be very confused\n -- But I haven't been able to trigger it on random test data, either...\n when (score /= approxScore) $ lift . P.putStrLn $ P.pack \"Yikes\\n\"\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, x] <- readInts\n pLi <- readInts\n let\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n toByteString :: [Int] -> P.ByteString\n toByteString li = let\n arr :: UArray Int Char\n arr = accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n in P.pack $ elems arr\n (score, str) = case solution of\n Just li -> (maxDepth, toByteString li)\n Nothing -> (maxDepth + 1,\n toByteString . take x . concat $ elems findByDepth)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\ndata Tree t = Leaf t | Node !Int (Tree t) (Tree t) deriving (Eq, Show)\n\nsize :: Tree t -> Int\nsize (Leaf _) = 1\nsize (Node sz _ _) = sz\n\nunite :: Tree t -> Tree t -> Tree t\nunite x y = Node (size x + size y) x y\n\nfromList :: [t] -> Tree t\nfromList [] = error \"fromList []\"\nfromList [x] = Leaf x\nfromList (x:xs) = unite (Leaf x) $ fromList xs\n\ntoList :: Tree t -> [t]\ntoList = let\n go (Leaf x) = (x :)\n go (Node _ x y) = go x . go y\n in flip go []\n\npairUp :: [Tree t] -> ([Tree t], [Tree t])\npairUp (x : y : zs@(_ : _)) = let\n (zpairs, unpaired) = pairUp zs\n in (unite x y : zpairs, unpaired)\npairUp li = ([], li)\n\nreduce :: [Tree t] -> [Tree t]\nreduce [] = []\nreduce li = runST $ do\n let totSz = sum $ map size li\n arr <- newArray (1, totSz) [] :: ST s (STArray s Int [Tree t])\n forM_ li $ \\v -> do\n let currSz = size v\n prev <- readArray arr currSz\n writeArray arr currSz (v : prev)\n forM_ [1..totSz] $ \\currSz -> do\n szOpts <- readArray arr currSz\n let (paired, unpaired) = pairUp szOpts\n writeArray arr currSz unpaired\n when (not $ null paired) $ do\n nextOpts <- readArray arr (2*currSz)\n -- (++) isn't cheap here, but it's only O(n * log n) complete\n -- cost, so not worth using some abstraction to avoid its overhead\n writeArray arr (2*currSz) $ paired ++ nextOpts\n allOpts <- getElems arr\n pure $ concat allOpts\n\nsolve :: [Tree Int] -> Int -> Maybe [Int]\nsolve options target = let\n memo = runSTUArray $ do\n arr <- newArray (0, target) 0 :: ST s (STUArray s Int Int)\n writeArray arr 0 (0-1)\n forM_ options $ \\currOpt -> do\n let s = size currOpt\n forM_ (reverse [0 .. target-s]) $ \\i -> do\n prevStep <- readArray arr i\n when (prevStep /= 0) $ do\n oldVal <- readArray arr (i+s)\n writeArray arr (i+s) $ if oldVal > 0 then oldVal else s\n pure arr\n go 0 = Just []\n go k = let\n s = memo ! k\n in if s == 0\n then Nothing\n else (s :) <$> go (k - s)\n collectResult [] _ = []\n collectResult (sz : szs) toSearch\n = case dropWhile (\\x -> size x /= sz) toSearch of\n [] -> error \"not found?!\"\n curr : rest -> toList curr ++ collectResult szs rest\n in do\n sizes <- go target\n pure $ collectResult (reverse sizes) options\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, x] <- readInts\n pLi <- readInts\n let\n depths :: Array Int Int\n depths = listArray (1, n) $ 1 : map (\\p -> 1 + depths ! p) pLi\n maxDepth = maximum $ elems depths\n findByDepth :: Array Int [Int]\n findByDepth = accumArray (flip (:)) [] (1, maxDepth)\n [(d, ix) | (ix, d) <- assocs depths]\n unreducedOptions = [fromList li | li <- elems findByDepth, not $ null li]\n options = reduce unreducedOptions\n solution = solve options x\n [n64, x64] = map fromIntegral [n, x]\n (score, str) = case solution of\n Nothing -> (maxDepth + 1,\n P.concat [P.replicate x64 'a', P.replicate (n64 - x64) 'b'])\n Just li -> let\n arr :: UArray Int Char\n arr = accumArray (\\_ _ -> 'a') 'b' (1, n) $ zip li (repeat ())\n in (maxDepth, P.pack $ elems arr)\n lift . P.putStrLn . P.pack $ show score\n lift . P.putStrLn $ str\n"}], "src_uid": "3ffb3a2ae3e96fc26d539c9676389ae5"} {"source_code": "import Data.List\nfindem l = [(l !! 3) - (l !! 0), (l !! 3) - (l !! 1), (l !! 3) - (l !! 2)]\nanalyze = findem . sort\nans = unwords . (map show) . analyze . (map read) . words\nmain = getLine >>= putStrLn . ans\n", "positive_code": [{"source_code": "import Data.List\nmain = interact $ unwords . map show . solve . map read . words\nsolve ns = delete 0 (map (abc -) ns) where\n abc = maximum ns\n \n"}, {"source_code": "main = \n getLine >>= \\line ->\n let nums = map read $ (words line) :: [Int] in\n let sum_vals = foldl max 0 nums in\n let vals = [sum_vals - x | x <- nums, x /= sum_vals] in\n putStrLn $ unwords $ map show vals\n"}, {"source_code": "import Data.List\nf a = map (\\x -> maximum a - x) a\nmain = interact $ unwords . map show . delete 0 . f . map read . words\n"}, {"source_code": "import Data.List\nimport Text.Printf\ngetList :: IO [Int]\ngetList = do\n input <- getLine\n let nums = words input\n return $ map read nums\n\nmain :: IO()\nmain = do\n list <- fmap sort getList\n let ans = map (\\x -> list!!3-x) (init list)\n putStrLn $ unwords . map show $ ans\n"}, {"source_code": "module Main where\n\n\nprintSolution :: [Int] -> IO ()\nprintSolution ints = sequence_ $ fmap putStr $ fmap (\\s -> show s ++ \" \") ints\n\nmain = do \n let toNumbers line = (map read $ words line) :: [Int]\n row <- fmap toNumbers getLine\n \n let solution = filter (/=0) $ map (\\x -> maximum row - x) row\n printSolution solution\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmain :: IO ()\nmain = do\n input <- getLine\n let numbers :: [Int] = read <$> words input\n let total = maximum numbers\n let answers = (total -) <$> filter (/= total) numbers\n putStrLn . unwords $ show <$> answers\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nmain= do\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet m = maximum a\n\t\tputStrLn $ intercalate \" \" $ map show $ tail $ sort $ map (\\z->m-z) a\n\t\t\n"}, {"source_code": "main = do\n [x1, x2, x3, x4] <- (map read . words) `fmap` getLine :: IO[Integer]\n let allSum = maximum [x1, x2, x3, x4]\n let [a, b, c] = filter (/=0) $ map ((-) allSum) [x1, x2, x3, x4]\n putStrLn $ (show a) ++ \" \" ++ (show b) ++ \" \" ++ (show c)\n\n\n"}, {"source_code": "--ghc 7.10\n\nreorder :: (Int,Int,Int,Int) -> (Int,Int,Int,Int)\nreorder (x1, x2, x3, x4)\n | x1 + x2 + x3 == 2*x4 = (x1, x2, x3, x4)\n | x1 + x2 + x4 == 2*x3 = (x1, x2, x4, x3)\n | x1 + x3 + x4 == 2*x2 = (x1, x3, x4, x2)\n | x2 + x3 + x4 == 2*x1 = (x2, x3, x4, x1)\n | otherwise = (x1, x2, x3, x4)\n\nrestore :: (Int,Int,Int,Int) -> (Int,Int,Int)\nrestore x = (a,b,c)\n where\n (a'b,b'c,c'a,a'b'c) = reorder x\n c = a'b'c - a'b\n a = a'b'c - b'c\n b = a'b'c - c'a\n\nmain = do\n line <- getLine\n let [x1,x2,x3,x4] = map read . words $ line :: [Int]\n let (a,b,c) = restore (x1,x2,x3,x4)\n putStrLn . unwords . map show $ [a,b,c]"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n list@[x, y, z, w] <- fmap (sort . map read . words) getLine :: IO [Int]\n\n let abc = w\n a = abc - x\n b = abc - y\n c = abc - z\n\n putStrLn . unwords $ map show [a, b, c]\n"}, {"source_code": "import Data.List\n\nsolve [a, b, c, d] = map show [d - a, d - b, d - c]\n\nmain :: IO ()\nmain = do\n line <- getLine\n let xs = map read $ words line :: [Int]\n putStrLn $ intercalate \" \" $ solve $ sort xs\n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n line <- getLine\n let arr = sort $ map read $ words line\n putStrLn $ unwords $ map (show . (last arr -)) $ init arr"}, {"source_code": "import Text.Printf\nimport Data.List\n\nmain = do\n n <- fmap (map read . words) getLine :: IO [Int]\n let l = sort n\n printf \"%d %d %d\" (l!!3 - l!!0) (l!!3 - l!!1) (l!!3 - l!!2)"}, {"source_code": "merge :: Ord a => [a] -> [a] -> [a]\nmerge xs [] = xs\nmerge [] ys = ys\nmerge (x:xs) (y:ys) = (m : merge xs' ys')\n where\n m = min x y\n (xs',ys') = if x>y then (x:xs,ys) else (xs,y:ys)\n\nmergesort :: Ord a => [a] -> [a]\nmergesort (x:[]) = [x]\nmergesort xs = merge (mergesort ys) (mergesort zs)\n where\n (ys,zs) = (take (n `quot` 2) xs, drop (n `quot` 2) xs)\n n = length xs\n\ngetInts :: IO [Int]\ngetInts = do\n s <- getLine\n let iss = words s\n let is = map (\\x -> read x :: Int) iss\n return is\n\nf :: [Int] -> [Int]\nf xs = [m-a,m-b,m-c]\n where\n [a,b,c,m] = mergesort xs\n\nshowI :: [Int] -> String\nshowI (x:[]) = show x\nshowI (x:xs) = show x ++ \" \" ++ showI xs\n\nmain :: IO ()\nmain = do\n ss <- getInts\n putStr.showI.f $ ss\n putStr \"\\n\"\n"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n inpu <- getLine\n let ns = map read (words inpu)\n putStrLn $ concat $ intersperse \" \" ( map show (solve ns))\n return ()\nsolve :: [Int] -> [Int]\nsolve xs = delete 0 (map f xs)\n where f x =(maximum xs)-x "}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\nimport Data.List\n\nmain = do { x <- getLine; putStrLn $ (words >>> map read >>> solve >>> map show >>> unwords) x }\n\nsolve :: [Integer] -> [Integer]\nsolve x = let y = sort x in map (\\z -> (last y) - z) (init y)"}, {"source_code": "main = getLine >>= putStrLn . answer . solve . map read . words\n\nanswer [] = []\nanswer (x:xs) = show x ++ \" \" ++ answer xs\n\nsolve xs = filter (/=0) $ map (`subtract` (sum xs `div` 3)) xs"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> [Int]\nsolve xs = map (uncurry (-)) $ zip (replicate 3 (last ys)) ys \n where ys = sort xs\n\nmain :: IO ()\nmain = do\n xs <- readInts\n putStrLn $ unwords $ map show $ solve xs"}], "negative_code": [{"source_code": "import Data.List\nmain :: IO ()\nmain = do\n inpu <- getLine\n let ns = map read (words inpu)\n putStrLn $ intersperse ' ' (concat $ map show (solve ns))\n return ()\nsolve :: [Int] -> [Int]\nsolve xs = delete 0 (map f xs)\n where f x =(maximum xs)-x "}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n inpu <- getLine\n let ns = map read (words inpu)\n putStrLn $ intersperse ' ' (concat $ map show (solve ns))\n return ()\nsolve :: [Int] -> [Int]\nsolve xs = delete 0 (map f xs)\n where f x =x-(maximum xs) "}, {"source_code": "main = \n getLine >>= \\line ->\n let nums = map read $ (words line) :: [Int] in\n let sum_vals = foldl max 0 nums in\n let vals = [sum_vals - x | x <- nums, x /= sum_vals] in\n print $ unwords $ map show vals\n"}, {"source_code": "import Data.List\nf a = map (\\x -> x - minimum a) a\nmain = interact $ show . delete 0 . f . map read . words\n"}, {"source_code": "import Data.List\nf a = map (\\x -> x - minimum a) a\nmain = interact $ unwords . map show . delete 0 . f . map read . words\n"}], "src_uid": "cda949a8fb1f158f3c06109a2d33f084"} {"source_code": "import Control.Applicative\n\nmain = do\n _ <- getLine\n a <- map read <$> (words <$> getLine)\n let\n b = a ++ [0]\n c = [0] ++ a\n d = zipWith max b c\n print $ minimum d\n", "positive_code": [{"source_code": "module Main where\n\nmain = do\n _ <- getLine\n s <- getLine\n let l = (map read (words s)) :: [Int]\n let n = length l\n print(minimum ([max (l !! i) (l !! (i+1)) | i <- [0 .. n-2]] ++ [head l] ++ [last l]))"}, {"source_code": "\nsolve :: [Int] -> Int\nsolve xs = minimum $ [head xs, last xs] ++ pairs\n where\n pairs = zipWith max xs (tail xs)\n\nmain :: IO ()\nmain = getLine >> getLine >>= return . map read . words >>= print . solve\n"}, {"source_code": "solve :: Int -> [Int] -> Int\nsolve n xs | head isNotDestroyed && last isNotDestroyed && longestChain False isNotDestroyed <= 1 = solve (n+1) xs\n | otherwise = n\n where isNotDestroyed = map (>n) xs\nlongestChain :: (Eq a) => a -> [a] -> Int\nlongestChain _ [] = 0\nlongestChain el l@(_:xs) | null a = longestChain el xs\n | otherwise = max (length a) (longestChain el b)\n where (a, b) = span (==el) l\nmain = getLine >> fmap (map read . words) getLine >>= print . solve 1\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\n\nmain = do\n n <- readLn\n getLine >>= print.solve n.map read.words\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = go (IS.fromList [0,n+1]). sortBy (comparing snd) $ zip [1..] xs\n where\n go set ((i,y):ys)\n | any (`IS.member`set) [i-1,i+1] = y\n | otherwise = go (IS.insert i set) ys"}], "negative_code": [{"source_code": "module Main where\n\nmain = do\n _ <- getLine\n s <- getLine\n let l = (map read (words s)) :: [Int]\n let n = length l\n print(minimum [max (l !! i) (l !! (i+1)) | i <- [0 .. n-2]])"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\n\nmain = getLine >> getLine >>= print.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve [x] = x\nsolve xs = go IS.empty . sortBy (comparing snd) $ zip [1..] xs\n where\n go set ((i,y):ys)\n | any (`IS.member`set) [i-1,i+1] = y\n | otherwise = go (IS.insert i set) ys"}], "src_uid": "d526af933b5afe9abfdf9815e9664144"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n ws <- getInts\n bs <- getInts\n\n let\n a = reverse $ foldl (\\a b -> if b `elem` a then a else b:a) [] bs\n\n f _ [] = 0\n f a (b:bs) = c + f a' bs\n where\n c = sum $ map (\\i -> ws!!(i-1)) $ takeWhile (/= b) $ a\n a' = b:(a \\\\ [b])\n\n print $ f a bs\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n ws <- readInts\n bs <- readInts\n print $ solve n m ws bs\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve n m ws bs = calc cs bs where\n cs = go S.empty bs\n go s [] = []\n go s (x:xs) | S.member x s = go s xs\n | otherwise = x:go (S.insert x s) xs\n weight :: UArray Int Int\n weight = listArray (1,n) ws\n calc st [] = 0\n calc st (x:xs) = w + calc st' xs where\n Just i = elemIndex x st\n w = sum $ map (weight !) $ take i st\n st' = x:take i st ++ drop (i+1) st\n\n"}], "negative_code": [], "src_uid": "a18edcadb31f76e69968b0a3e1cb7e3e"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\n\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Int64\n mod' x = mod x m'\n mpow x p = go (mod' x) 1 1\n where go _ q acc | q > p = acc \n go y q acc = go (mod' $ y*y) (q*2) $ if q .&. p == 0 then acc else mod' (y*acc)\n \n ainv = mpow a (m' - 2)\n (a1, _) = foldl (\\(acc, ab) s -> (mod' (acc + mod' (s*ab)), mod' (mod' (ab*b)*ainv)))\n (0, mpow a n) ss\n r = mod' (mpow b k * mpow (mpow a k) (m' - 2))\n nk = div (n + 1) k\n gs = if r == 1\n then mod' (a1 * nk)\n else mod' (mod' (a1 * (1 - mpow r nk)) * mpow (1 - r) (m' - 2))\n \n print gs", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\n\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Int64\n mod' x = mod x m'\n mpow x p = go (mod' x) 1 1\n where go _ q acc | q > p = acc \n go y q acc = go (mod' $ y*y) (q*2) $ if q .&. p == 0 then acc else mod' (y*acc)\n \n ainv = mpow a (m' - 2)\n (a1, _) = foldl (\\(acc, ab) s -> (mod' (acc + mod' (s*ab)), mod' (mod' (ab*b)*ainv)))\n (0, mpow a n) ss\n r = mod' (mpow b k * mpow (mpow a k) (m' - 2))\n nk = div (n + 1) k\n gs = if r == 1\n then mod' (a1 * nk)\n else mod' (mod' (a1 * (1 - mpow r nk)) * mpow (1 - r) (m' - 2))\n \n print gs"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (listArray, (!))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- listArray (0, k-1) . map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Integer\n m x = rem (x + m') m'\n r = div (b^k) (a^k)\n a1 = foldl (\\(acc, (ai, bi)) i ->\n let acc' = acc + (ss ! i) * ai * bi\n in (acc', (div ai a, bi*b)))\n (0, (a^n, 1)) [0..k-1]\n \n print . m $\n if a == b\n then fst a1 * div (n + 1) k\n else fst a1 * div (1 - r^(div (n + 1) k)) (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (fromInteger b/fromInteger a)^k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (acc + s*ai*bi, (ai `div` a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then mod' a1 * ((n+1) `div` k)\n else round $ fromInteger (mod' a1) * (1 - r^((n+1) `div` k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (fromIntegral b/fromIntegral a) ^ k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s ->\n let acc' = acc + s*ai*bi\n in (mod' acc', (div ai a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' . (* a1) $\n if a == b\n then div (n + 1) k\n else round ((1 - r^(div (n+1) k)) / (1-r))\n\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (fromInteger b/fromInteger a)^k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (mod' (acc + s*ai*bi), (ai `div` a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then a1 * ((n+1) `div` k)\n else round $ fromInteger a1 * (1 - r^((n+1) `div` k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (fromIntegral b/fromIntegral a) ^ k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s ->\n let acc' = acc + s*ai*bi\n in (mod' acc', (div ai a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then a1 * div (n + 1) k\n else round (fromIntegral a1 * (1 - r^(div (n+1) k)) / (1-r))"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Int)\n r = (b/a)**k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (acc + s*ai*bi, (ai/a, bi*b)))\n (0, (a**n, 1)) ss\n \n print . mod' . round $\n if a == b\n then a1 * (n+1) / k\n else a1 * (1 - r**((n+1) / k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Int\n r = fromIntegral (mpow b k m') / fromIntegral (mpow a k m')\n a1 = fst $ foldl (\\(acc, (ai, bi)) s ->\n let acc' = acc + s*ai*bi\n in (mod acc' m', (div ai a, mod (bi*b) m')))\n (0, (mpow a n m', 1)) ss\n \n print . flip mod m' . (* a1) $\n if a == b\n then div (n + 1) k\n else round ((1 - r^(div (n+1) k)) / (1-r))\n\nmpow :: Int -> Int -> Int -> Int\nmpow x p m = go p 1\n where go 0 acc = acc\n go p acc = go (p - 1) $ mod (x * acc) m"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (fromIntegral b/fromIntegral a) ^ k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s ->\n let acc' = acc + s*ai*bi\n in (acc', (div ai a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then a1 * div (n + 1) k\n else round (fromIntegral a1 * (1 - r^(div (n+1) k)) / (1-r))"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (b/a)**k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (acc + s*ai*bi, (ai/a, bi*b)))\n (0, (a**n, 1)) ss\n \n print . mod' . round $\n if a == b\n then a1 * (n+1) / k\n else a1 * (1 - r**((n+1) / k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Int)\n r = (fromIntegral b/fromIntegral a) ^ k :: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s ->\n let acc' = acc + s*ai*bi\n in (mod' acc', (div ai a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then a1 * div (n + 1) k\n else round (fromIntegral a1 * (1 - r^(div (n+1) k)) / (1-r))"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\n\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Int64\n mod' x = mod x m'\n mpow x p = go (mod' x) 1 1\n where go _ q acc | q > p = acc \n go y q acc = go (mod' $ y*y) (q*2) $ if q .&. p == 0 then acc else mod' (y*acc)\n \n ainv = mpow a (m' - 2)\n (a1, _, _) = foldl (\\(acc, ai, bi) s -> (acc + mod' (s*ai*bi), mod' (ai*ainv), mod' (b*bi)))\n (0, mpow a n, 1) ss\n r = mod' (mpow b k * mpow (mpow a k) (m' - 2))\n nk = div (n + 1) k\n gs = if r == 1\n then mod' (a1 * nk)\n else mod' (mod' (a1 * (1 - mpow r nk)) * mpow (1 - r) (m' - 2))\n \n print gs"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = fromInteger (b^k)/fromInteger (a^k)\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (acc + s*ai*bi, (ai `div` a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then a1 * ((n+1) `div` k)\n else round $ fromInteger a1 * (1 - r^((n+1) `div` k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (listArray, (!))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- listArray (0, k-1) . map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Integer\n m x = rem (m' + rem x m') m'\n r = div (b^k) (a^k)\n a1 = foldl (\\(acc, (ai, bi)) i ->\n let acc' = acc + (ss ! i) * ai * bi\n in (m acc', (div ai a, bi*b)))\n (0, (a^n, 1)) [0..k-1]\n \n print . m $\n if a == b\n then fst a1 * div (n + 1) k\n else fst a1 * div (1 - r^(div (n + 1) k)) (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (listArray, (!))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- listArray (0, k-1) . map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9\n m x = rem (m' + rem x m') m'\n r = div (b^k) (a^k)\n a1 = foldl (\\(acc, (ai, bi)) i ->\n let acc' = acc + (ss ! i) * ai * bi\n in (m acc', (div ai a, bi*b)))\n (0, (a^n, 1)) [0..k-1]\n \n print . m $\n if a == b\n then fst a1 * div n k\n else fst a1 * div (1 - r^(div n k + 1)) (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (listArray, (!))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- listArray (0, k - 1) . map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 1000000009\n m x = rem x m'\n loop from to (acc, _) | from > to = acc\n loop from to (acc, (ai, bi)) = loop (from + 1) to (acc', (div ai a, bi * b))\n where s = ss ! from\n acc' = m (m (acc + s*ai*bi) + m')\n a1 = loop 0 (k-1) (0, (a^n, 1))\n r = div (b^k) (a^k)\n \n print . m $ m' + \n if a == b\n then m (a1 * div n k)\n else m (a1 * div (1 - r^(div n k + 1)) (1 - r))"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = fromInteger (mod' $ b^k) / fromInteger (mod' $ a^k)\n a1 = fst $ foldl (\\(acc, (ai, bi)) s ->\n let acc' = acc + s*ai*bi\n in (mod' acc', (div ai a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' . (* a1) $\n if a == b\n then div (n + 1) k\n else round ((1 - r^(div (n+1) k)) / (1-r))"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = (b**k/a**k):: Double\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (acc + s*ai*bi, (ai/a, bi*b)))\n (0, (a**n, 1)) ss\n \n print . mod' . round $\n if a == b\n then a1 * (n+1) / k\n else a1 * (1 - r**((n+1) / k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (listArray, (!))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- listArray (0, k - 1) . map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 1000000009 :: Integer\n m x = rem x m'\n loop from to (acc, _) | from > to = acc\n loop from to (acc, (ai, bi)) = loop (from + 1) to (acc', (div ai a, bi * b))\n where s = ss ! from\n acc' = m (m (acc + s*ai*bi) + m')\n a1 = loop 0 (k-1) (0, (a^n, 1))\n r = div (b^k) (a^k)\n \n print . m $\n m' + m (a1 * if a == b\n then div n k\n else div (1 - r^(div n k + 1)) (1 - r))"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let mod' x = mod x (10^9 + 9 :: Integer)\n r = fromInteger (b^k)/fromInteger (a^k)\n a1 = fst $ foldl (\\(acc, (ai, bi)) s -> (acc + s*ai*bi, (ai `div` a, bi*b)))\n (0, (a^n, 1)) ss\n \n print . mod' $\n if a == b\n then mod' a1 * ((n+1) `div` k)\n else round $ fromInteger (mod' a1) * (1 - r^((n+1) `div` k)) / (1-r)"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (listArray, (!))\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- listArray (0, k - 1) . map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 1000000009 :: Integer\n m x = rem x m'\n a1 = fst $ foldl (\\(acc, (ai, bi)) i ->\n (m (m' + m (acc + (ss ! i)*ai*bi)), (div ai a, bi*b)))\n (0, (a^n, 1)) [0..k-1]\n r = div (b^k) (a^k)\n \n print . m $\n m' + m (a1 * if a == b\n then div n k\n else div (1 - r^(div n k + 1)) (1 - r))"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\n\n\nmain = do\n [n, a, b, k] <- map read . words <$> getLine\n ss <- map (\\x -> if x == '+' then 1 else -1) <$> getLine\n \n let m' = 10^9 + 9 :: Int64\n mod' x = mod x m'\n mpow x p = go (mod' x) 1 1\n where go _ q acc | q > p = acc \n go y q acc = go (mod' $ y*y) (q*2) $ if q .&. p == 0 then acc else mod' (y*acc)\n \n ainv = mpow a (m' - 2)\n (a1, _, _) = foldl (\\(acc, ai, bi) s -> (acc + mod' (s*ai*bi), mod' (ai*ainv), mod' (b*bi)))\n (0, mpow a n, 1) ss\n r = mod' (mpow b k * mpow (mpow a k) (m' - 2))\n nk = div (n + 1) k\n gs = if a == b\n then mod' (a1 * nk)\n else mod' (mod' (a1 * (1 - mpow r nk)) * mpow (1 - r) (m' - 2))\n \n print gs"}], "src_uid": "607e670403a40e4fddf389caba79607e"} {"source_code": "module Main where\n\nimport Data.List (sort, reverse)\n\ngetAnswer :: [Int] -> [Int] -> Int\ngetAnswer (lt : rt : []) _ = 0\ngetAnswer (lt : lmid : ls) (rt : rmid : rs) = min (rmid - lt) (rt - lmid)\n\nmain :: IO ()\nmain = do\n nStr <- getLine\n let n = read nStr :: Int\n lStr <- getLine\n let l = sort $ map read (words lStr) :: [Int]\n print $ getAnswer l (reverse l)\n", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Array\n\nmain = do\n C.getLine\n as <- map ((read :: String -> Int ). C.unpack ) . C.words <$> C.getLine\n let ass = group $ sort as \n bs = array (1,length ass) $ zip [1..] ass \n r = if head (bs!1) == head (bs!length bs) then 0\n else if length (bs!1) == 1 && length (bs!length bs) == 1 then min (head (bs!(length bs-1)) - head (bs!1)) (head (bs!length bs) - head (bs!2))\n else if length (bs!1) == 1 && length (bs!length bs) /= 1 then head (bs!length bs) - head (bs!2)\n else if length (bs!1) /= 1 && length (bs!length bs) == 1 then head (bs!(length bs-1)) - head (bs!1)\n else head (bs!length bs) - head (bs!1)\n print r\n \n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . words\nsolve (n:as) = min (c-a) (d-b) where\n s@(a:b:_) = sort as\n [c,d] = drop (n-2) s\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n a <- fmap (sort . map read . words) getLine\n print . minimum . map (\\x -> last x - head x) $ [init a, tail a]"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\n\nins m1 = last m1 - head m1\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\tm<-sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tlet m1 = init m\n\t\tlet m2 = tail m\n\t\tprint $ min (ins m1) (ins m2)\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ninstability :: [Int] -> Int\ninstability xs = hi - lo\n where hi = maximum xs\n lo = minimum xs\n\nsolve :: [Int] -> Int\nsolve xs = min (instability $ delete hi xs) (instability $ delete lo xs)\n where hi = maximum xs\n lo = minimum xs\n\ntests :: [[Int]]\ntests = [[1, 3, 3, 7], [1, 100000]]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int from: \" ++ (L.unpack s)\ngo :: Tokenizer Int\ngo = do\n n <- nextInt\n xs <- replicateM n nextInt\n return $ solve xs\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n let output = evalState go input\n print output\n"}, {"source_code": "import Data.List\n\nmain = do\n s <- getLine\n s <- getLine\n let a = sort (map read (words s)) :: [Int]\n print (min (last a - head (tail a)) (last (init a) - head a))\n"}], "negative_code": [{"source_code": "import Data.List\nmain = interact $ show . solve . map read . words\nsolve (n:as) = min (c-a) (d-b) where\n s@(a:b:_) = sort as\n [c,d] = drop (n-2) as\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map read . words\nsolve (n:as) | n < 100 = show $ min (c-a) (d-b)\n | otherwise = show [a,b,c,d,length as]\n where\n s@(a:b:_) = sort as\n [c,d] = drop (n-2) as\n"}], "src_uid": "2eb7234904b28b4793b7c482a2370092"} {"source_code": "import Data.List\n\nf ::[Int]->Int\nf xs=let ys=group xs\n (a:b:[])=map length ys\n in if a<=b then a else b+(a-b) `div` 3\n\nmain = do\n e<-getLine\n es<-getLine\n let c=read e::Int\n xs=map read (words es)::[Int]\n ys=sort xs\n a=head ys\n b=last ys\n print $ if a==2 then 0 else if b==1 then c `div` 3 else f ys", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nsolve :: [Int] -> Int\nsolve xs = a + b\n where nones = length $ filter (== 1) xs\n ntwos = length xs - nones\n\n a = min nones ntwos\n b = (nones - a) `div` 3\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map read . words <$> getLine\n print $ solve xs\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve = (\\gs -> case gs of { [os, ts] -> let lo = length os; lt = length ts in if lo > lt then lt + (lo - lt) `quot` 3 else lo; [os@(1:_)] -> (length os) `quot` 3; _ -> 0}) . group . sort"}, {"source_code": "import qualified Data.ByteString.Char8 as C\nimport Control.Applicative\n\nreadChar8 :: IO [Int]\nreadChar8 = map parse . C.words <$> C.getLine\n where parse s = let Just (n, _) = C.readInt s in n\n\n\ncount = foldr (\\x (_1s,_2s) -> if x == 1 then (_1s+1,_2s) else (_1s,_2s+1)) (0,0) \n\nmain = do\n getLine\n as <- readChar8\n let (a',b') = count as\n r = case (a',b') of \n (a,b) | a==b || b>a -> a\n (a,b) | a>b -> b + (a-b)`div`3\n print r \n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = sol <$> (getLine *> get) >>= print\n\nget = fmap read . words <$> getLine\n\n--sol :: [Int] -> Int\nsol as = p + q\n where\n a1 = length $ filter (==1) as\n a2 = length $ filter (==2) as\n p = min a1 a2\n q = if a1 > a2 then (a1 - a2) `div` 3 else 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\n\nmain = do\n\t\tn<- read<$> getLine ::IO Int\n\t\ta<- map read <$> words <$> getLine::IO [Int]\n\t\tlet o = length $ filter (==1) a \n\t\tlet t = length $ filter (==2) a \n\t\tlet ans = (min o t)\n\t\tprint $ ans + (div (o-ans) 3)\n"}, {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms, CPP,\n TupleSections, UnicodeSyntax, LambdaCase,\n MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . tail . lines\n\nsol :: [[Int]] -> [String]\nsol [as] = let\n (j',d') = partition (==1) as\n (j,d) = (length j', length d')\n x = min j d\n x' = (j - x) `div` 3\n in [ show $ (x+x') ]\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}], "negative_code": [], "src_uid": "6c9cbe714f8f594654ebc59b6059b30a"} {"source_code": "import Data.List.Split\nmain = do\n n <- readLn::IO Int\n str <- getLine\n let (hd:tl) = split (onSublist \"><\") str\n\tpre = length $ takeWhile ('<'==) hd\n\tpost = length $ takeWhile ('>'==) . reverse $ last tl\n print $ case hd:tl of\n\t [a]\t-> length a\n\t otherwise ->pre+post\n", "positive_code": [{"source_code": "main=interact$show.f.(!!1).lines\nf cs = g cs + h cs\ng cs = length $ takeWhile (=='<') cs\nh cs = length . takeWhile (=='>') $ reverse cs"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . head . tail . words =<< getContents\n\nremoveMaybe :: Int -> Maybe Int -> Int\nremoveMaybe _ (Just a) = a\nremoveMaybe n Nothing = n\n\nsolve :: String -> Int\nsolve s = let n = length s\n l = removeMaybe n $ findIndex (== '>') s\n r = removeMaybe n $ findIndex (== '<') $ reverse s\n in l + r\n"}, {"source_code": "main = do\n\tgetLine\n\tx <- getLine\n\tprint $ (length $ takeWhile (== '<') x) + (length $ takeWhile (== '>') $ reverse x)\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import Data.Char\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n check :: Int -> Int -> Int -> (Int, Bool)\n check k r n =\n let result = (k * n) `mod` 10 == r\n in (n, result)\n\n solve :: Int -> Int -> [Int]\n solve k r = map fst $ filter snd $ map (check k r) [1..10]\n\n h :: [Int] -> Int\n h [] = 10\n h (x:xs) = x\n\n solvex :: Int -> Int\n solvex 5 = 2\n solvex 2 = 5\n solvex 4 = 5\n solvex 6 = 5\n solvex 0 = 1\n solvex 8 = 5\n solvex _ = 10\n\n r1 :: String -> Int -> Int\n r1 ('<':xs) a = r1 xs (a+1)\n r1 ('>':xs) a = a\n r1 [] a = a\n\n r2 :: String -> Int -> Int\n r2 ('>':xs) a = r2 xs (a+1)\n r2 ('<':xs) a = a\n r2 [] a = a\n\n main :: IO()\n main = do\n n <- getLine\n xs <- getLine\n print $ (r1 xs 0) + (r2 (reverse xs) 0)\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\nmain = return ()"}, {"source_code": "import Control.Monad.Trans.State.Lazy\nmain = do\n n <- readLn::IO Int\n str <- getLine\n let process [] = return 0\n\tprocess [b] = return 1\n\tprocess (b1:b2:bs)\n\t | [b1,b2] == \"><\" =\n\t\treturn.length.takeWhile ('>'==)$reverse bs\n\t | otherwise\t = modify (b1:) >> process (b2:bs)\n (v,st) <- runStateT (process str) []\n print $ (length $ dropWhile ('>'==) st) + v\n"}], "src_uid": "6b4242ae9a52d36548dda79d93fe0aef"} {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, insert, alter, empty, (!), (!?), fromList)\nimport Data.List (unfoldr)\n\ntype Value = (Int, Int)\ndata Tree = Leaf Value | Node Value [Tree] deriving (Show)\ntype Domain = Tree\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nsolve :: Solver\nsolve xs = snd $ dfs xs\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\ngetPair :: IO Value\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nbuildTree :: Map Int Value -> Map Int [Int] -> Tree\nbuildTree xs m = go 1\n where\n go n = let value = xs ! n in maybe (Leaf value) (Node value) $ fmap go <$> m !? n \n\nparentToChildren :: Int -> [Int] -> Map Int [Int]\nparentToChildren _ [] = empty\nparentToChildren n (x : xs) = alter (maybe (Just [n]) (Just . (n :))) x $ parentToChildren (n + 1) xs\n\naddUp :: (Int, Int) -> (Int, Int) -> (Int, Int)\naddUp (x1, x2) (y1, y2) = (x1 + y1, x2 + y2)\n\ndfs :: Tree -> (Int, Int)\ndfs (Leaf (_, y)) = (y, 1)\ndfs (Node (l, h) xs) = if l > childSum \n then (h, number + 1) \n else (min childSum h, number) \n where\n (childSum, number) = foldl1 addUp $ dfs <$> xs\n\nparse :: IO Domain\nparse = do\n [nodeCount] <- readChar8\n parents <- readChar8\n ranges <- fromList . zipWith (,) [1..] <$> replicateM nodeCount getPair\n return $ (buildTree ranges $ parentToChildren 2 parents) \n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n (printAns <$> solve =<< parse)", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, insert, alter, empty, (!), (!?), fromList)\nimport qualified Data.Char as C\nimport Data.List (unfoldr)\n\ntype Value = (Int, Int)\ndata Tree = Leaf Value | Node Value [Tree] deriving (Show)\ntype Domain = Tree\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\n\nreadChar8 :: IO [Int]\nreadChar8 = parse <$> C.getLine\n where parse = unfoldr go\n go s = do (n, s1) <- C.readInt s\n let s2 = C.dropWhile C.isSpace s1\n return (n, s2)\n\nsolve :: Solver\nsolve xs = snd $ dfs xs\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\ngetPair :: IO Value\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nbuildTree :: Map Int Value -> Map Int [Int] -> Tree\nbuildTree xs m = go 1\n where\n go n = let value = xs ! n in maybe (Leaf value) (Node value) $ fmap go <$> m !? n \n\nparentToChildren :: Int -> [Int] -> Map Int [Int]\nparentToChildren _ [] = empty\nparentToChildren n (x : xs) = alter (maybe (Just [n]) (Just . (n :))) x $ parentToChildren (n + 1) xs\n\naddUp :: (Int, Int) -> (Int, Int) -> (Int, Int)\naddUp (x1, x2) (y1, y2) = (x1 + y1, x2 + y2)\n\ndfs :: Tree -> (Int, Int)\ndfs (Leaf (_, y)) = (y, 1)\ndfs (Node (l, h) xs) = if l > childSum \n then (h, number + 1) \n else (min childSum h, number) \n where\n (childSum, number) = foldl1 addUp $ dfs <$> xs\n\nparse :: IO Domain\nparse = do\n [nodeCount] <- readChar8\n parents <- readChar8\n ranges <- fromList . zipWith (,) [1..] <$> replicateM nodeCount getPair\n return $ (buildTree ranges $ parentToChildren 2 parents) \n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n (printAns <$> solve =<< parse)"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\nimport Data.Map (Map, insert, alter, empty, (!), (!?))\n\ntype Value = (Int, Int)\ndata Tree = Leaf Value | Node Value [Tree] deriving (Show)\ntype Domain = Tree\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nparseInt :: String -> Int\nparseInt = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntList :: String -> [Int]\nparseIntList = map parseInt . words\n\nsolve :: Solver\nsolve xs = snd $ dfs xs\n\nprintAns :: CoDomain -> IO ()\nprintAns x = print x\n\ngetPair :: IO Value\ngetPair = do\n [a, b] <- fmap parseInt . words <$> getLine\n return (a, b)\n\nbuildTree :: [Value] -> Map Int [Int] -> Tree\nbuildTree xs m = go 1\n where\n go :: Int -> Tree\n go n = maybe (Leaf value) (Node value) $ fmap go <$> m !? n \n where\n value = xs !! (n-1)\n\nparentToChildren :: Int -> [Int] -> Map Int [Int]\nparentToChildren _ [] = empty\nparentToChildren n (x : xs) = alter (maybe (Just [n]) (Just . (n :))) x $ parentToChildren (n + 1) xs\n\naddUp :: (Int, Int) -> (Int, Int) -> (Int, Int)\naddUp (x1, x2) (y1, y2) = (x1 + y1, x2 + y2)\n\ndfs :: Tree -> (Int, Int)\ndfs (Leaf (_, y)) = (y, 1)\ndfs (Node (l, h) xs) = if l > childSum then (h, number + 1) else (childSum, number) \n where\n (childSum, number) = foldl1 addUp $ dfs <$> xs\n\nparse :: IO Domain\nparse = do\n nodeCount <- parseInt <$> getLine\n parents <- parseIntList <$> getLine\n ranges <- replicateM (fromIntegral nodeCount) getPair\n return $ (buildTree ranges $ parentToChildren 2 parents) \n\nmain :: IO ()\nmain = do\n n <- parseInt <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< parse)"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\nimport Data.Map (Map, insert, alter, empty, (!), (!?))\n\ntype Value = (Int, Int)\ndata Tree = Leaf Value | Node Value [Tree] deriving (Show)\ntype Domain = Tree\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nparseInt :: String -> Int\nparseInt = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntList :: String -> [Int]\nparseIntList = map parseInt . words\n\nsolve :: Solver\nsolve xs = snd $ dfs xs\n\nprintAns :: CoDomain -> IO ()\nprintAns x = print x\n\ngetPair :: IO Value\ngetPair = do\n [a, b] <- fmap parseInt . words <$> getLine\n return (a, b)\n\nbuildTree :: [Value] -> Map Int [Int] -> Tree\nbuildTree xs m = go 1\n where\n go :: Int -> Tree\n go n = maybe (Leaf value) (Node value) $ fmap go <$> m !? n \n where\n value = xs !! (n-1)\n\nparentToChildren :: Int -> [Int] -> Map Int [Int]\nparentToChildren _ [] = empty\nparentToChildren n (x : xs) = alter (maybe (Just [n]) (Just . (n :))) x $ parentToChildren (n + 1) xs\n\naddUp :: (Int, Int) -> (Int, Int) -> (Int, Int)\naddUp (x1, x2) (y1, y2) = (x1 + y1, x2 + y2)\n\ndfs :: Tree -> (Int, Int)\ndfs (Leaf (_, y)) = (y, 1)\ndfs (Node (l, h) xs) = (h, number + if l > childSum then 1 else 0)\n where\n (childSum, number) = foldl1 addUp $ dfs <$> xs\n\nparse :: IO Domain\nparse = do\n nodeCount <- parseInt <$> getLine\n parents <- parseIntList <$> getLine\n ranges <- replicateM (fromIntegral nodeCount) getPair\n return $ (buildTree ranges $ parentToChildren 2 parents) \n\nmain :: IO ()\nmain = do\n n <- parseInt <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< parse)"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\nimport Data.Map (Map, insert, alter, empty, (!), (!?))\n\ntype Value = (Int, Int)\ndata Tree = Leaf Value | Node Value [Tree] deriving (Show)\ntype Domain = Tree\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nparseInt :: String -> Int\nparseInt = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntList :: String -> [Int]\nparseIntList = map parseInt . words\n\nsolve :: Solver\nsolve xs = snd $ dfs xs\n\nprintAns :: CoDomain -> IO ()\nprintAns x = print x\n\ngetPair :: IO Value\ngetPair = do\n [a, b] <- fmap parseInt . words <$> getLine\n return (a, b)\n\nbuildTree :: [Value] -> Map Int [Int] -> Tree\nbuildTree xs m = go 1\n where\n go :: Int -> Tree\n go n = case children of\n Just x -> Node value x\n Nothing -> Leaf value\n where\n children = fmap go <$> m !? n\n value = xs !! (n-1)\n\nparentToChildren :: Int -> [Int] -> Map Int [Int]\nparentToChildren _ [] = empty\nparentToChildren n (x : xs) =\n alter\n ( \\case\n Nothing -> Just [n]\n Just ys -> Just (n : ys)\n )\n x\n $ parentToChildren (n + 1) xs\n\naddUp :: (Int, Int) -> (Int, Int) -> (Int, Int)\naddUp (x1, x2) (y1, y2) = (x1 + y1, x2 + y2)\n\ndfs :: Tree -> (Int, Int)\ndfs (Leaf (_, y)) = (y, 1)\ndfs (Node (l, h) xs) = (h, number + if l > childSum then 1 else 0)\n where\n (childSum, number) = foldl1 addUp $ dfs <$> xs\n\nparse :: IO Domain\nparse = do\n nodeCount <- parseInt <$> getLine\n parents <- parseIntList <$> getLine\n ranges <- replicateM (fromIntegral nodeCount) getPair\n return $ (buildTree ranges $ parentToChildren 2 parents) \n\nmain :: IO ()\nmain = do\n n <- parseInt <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< parse)"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Bits\n-- import Debug.Trace\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust)\nimport Data.String ( IsString(fromString) )\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (dropWhileEnd)\nimport Data.Map (Map, insert, alter, empty, (!), (!?))\n\ntype Value = (Int, Int)\ndata Tree = Leaf Value | Node Value [Tree] deriving (Show)\ntype Domain = Tree\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nparseInt :: String -> Int\nparseInt = fromIntegral . fst . fromJust . C.readInt . fromString\n\nparseIntList :: String -> [Int]\nparseIntList = map parseInt . words\n\nsolve :: Solver\nsolve xs = snd $ dfs xs\n\nprintAns :: CoDomain -> IO ()\nprintAns x = print x\n\ngetInt :: IO Int\ngetInt = parseInt <$> getLine\n\ngetPair :: IO Value\ngetPair = do\n [a, b] <- fmap parseInt . words <$> getLine\n return (a, b)\n\nbuildTree :: [Value] -> Map Int [Int] -> Tree\nbuildTree xs m = go 1\n where\n go :: Int -> Tree\n go n = case children of\n Just x -> Node value x\n Nothing -> Leaf value\n where\n children = fmap go <$> m !? n\n value = xs !! (n-1)\n\nparentToChildren :: Int -> [Int] -> Map Int [Int]\nparentToChildren _ [] = empty\nparentToChildren n (x : xs) =\n alter\n ( \\case\n Nothing -> Just [n]\n Just ys -> Just (n : ys)\n )\n x\n $ parentToChildren (n + 1) xs\n\naddUp :: (Int, Int) -> (Int, Int) -> (Int, Int)\naddUp (x1, x2) (y1, y2) = (x1 + y1, x2 + y2)\n\ndfs :: Tree -> (Int, Int)\ndfs (Leaf (x, y)) = (y, 1)\ndfs (Node (l, h) xs) = (h, number + if l > childSum then 1 else 0)\n where\n (childSum, number) = foldl1 addUp $ map dfs xs\n\nparse :: IO Domain\nparse = do\n nodeCount <- getInt\n parents <- parseIntList <$> getLine\n ranges <- replicateM (fromIntegral nodeCount) getPair\n return $ (buildTree ranges $ parentToChildren 2 parents) \n\nmain :: IO ()\nmain = do\n n <- parseInt <$> getLine\n replicateM_ (fromIntegral n) (printAns <$> solve =<< parse)"}], "src_uid": "130fdf010c228564611a380b6dd37a34"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, listArray, (!), amap)\n\ngcd' :: Integral a => a -> a -> (a, a)\ngcd' !a !b\n | a `mod` b /= 0 = loop 1 0 0 1 a b\n | otherwise = (0, 1)\n where\n loop !x !y !x' !y' !r !r'\n | r' `mod` r'' == 0 = (x - q * x', y - q * y')\n | otherwise = loop x' y' (x - q * x') (y - q * y') r' r''\n where (q, r'') = r `divMod` r'\n\nsolve :: Int64 -> Int64 -> [(Int64, Int64)] -> Int64\nsolve h w a = snd . head . foldr loop [] $ (1, 1) :(sort a)\n where\n !m = 1000000007 :: Int64\n\n (*:) !i !j = (i * j) `mod` m\n (+:) !i !j = (i + j) `mod` m\n (-:) !i !j = (`mod` m) . (+ m) . (`mod` m) $ i - j\n\n fac :: UArray Int64 Int64\n !fac = listArray (0, h + w) $ scanl (*:) 1 [1..h + w]\n\n ifac :: UArray Int64 Int64\n !ifac = amap inverse fac\n where inverse !a = (`mod` m) . (+ m) . (`mod` m) . fst $ gcd' a m\n\n count (!i, !j) (!i', !j')\n | i' < i || j' < j = 0\n | otherwise = (fac ! (di + dj)) *: (ifac ! di) *: (ifac ! dj)\n where\n !di = i' - i\n !dj = j' - j\n\n loop self@(!i, !j) !acc = ((i, j), out):acc\n where\n !out = count self (h, w) -: foldr (+:) 0 (count' <$> acc)\n count' ((!i', !j'), !k) = k *: count self (i', j')\n\n\nwrap :: Int -> Int -> [[Int64]] -> Int64\nwrap h w a = solve (fromIntegral h) (fromIntegral w) a'\n where a' = (\\[i, j] -> (i, j)) <$> a\n\nparse :: Num a => ByteString -> [a]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [h, w, n] <- parse <$> B.getLine\n a <- replicateM n (parse <$> B.getLine)\n print $ wrap h w a\n", "positive_code": [{"source_code": "module Main(main) where\n\nimport Control.Monad(replicateM)\nimport Data.Functor\nimport Data.List\nimport Data.Array\n\nisDigit x = x>='0' && x<='9'\nsplit f l@(a:as) lft\n\t| f a = split f as (a:lft)\n\t| otherwise = (reverse lft, as)\nsplit _ [] lft = (reverse lft, [])\nreadInts::String -> [Integer]\nreadInts [] = []\nreadInts l@(x:xs)\n\t| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)\n\t| otherwise = readInts xs\n\nfactorials = go 0 1 where\n\tgo 200001 _ = []\n\tgo i j = (i,j):(go (i+1) ((j*(i+1)) `rem` p))\n\np::Integer\np = 1000000007\n(<**>) x y = (x * y) `rem` p\n(<+>) x y = let t = x + y in if t < p then t else t-p\n(<->) x y = let t = x - y in if t < 0 then t+p else t\npow x 0 = 1\npow x a = let ll = pow (x<**>x) (a `quot` 2) in if a `rem` 2 > 0 then (ll <**> x) else ll\ninverse x = pow x (p-2)\nfacs = array (0, 200000) factorials\nifacs = array (0, 200000) $ map (\\(x,y) -> (x, inverse y)) factorials\nchoose a b\n\t| 0<=b && 0<=a = (facs ! (a+b)) <**> (ifacs ! a) <**> (ifacs ! b)\n\t| otherwise = 0\n\ndp (prev) me@((i, j)) =\n\tlet\n\t\tfn (d, (a, b)) = d <**> (choose (i-a) (j-b))\n\tin\n\t\t((choose (i-1) (j-1)) <-> (foldl (<+>) 0 $ map fn prev), me):prev\nrunDp :: [(Integer, Integer)] -> [Integer]\nrunDp l = let t = foldl dp ([]) l in map fst t\n--runDp (a:as) = let \n\nmain = do\n\tl <- getLine\n\tlet [h, w, n] = readInts l\n\tlet srt = sortBy (\\x y -> compare (sum x) (sum y))\n\tblacks <- ((map (\\x->(head x, x!!1))).srt) <$> replicateM (fromInteger n) (readInts <$> getLine)\n\tlet all = blacks ++ [(h, w)]\n\tputStrLn $ show $ head.runDp $ all\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, listArray, (!), amap)\n\ngcd' :: Integral a => a -> a -> (a, a)\ngcd' !a !b\n | a `mod` b /= 0 = loop 1 0 0 1 a b\n | otherwise = (0, 1)\n where\n loop !x !y !x' !y' !r !r'\n | r' `mod` r'' == 0 = (x - q * x', y - q * y')\n | otherwise = loop x' y' (x - q * x') (y - q * y') r' r''\n where (q, r'') = r `divMod` r'\n\nsolve :: Int64 -> Int64 -> [(Int64, Int64)] -> Int64\nsolve h w a = snd . head . foldr loop [] $ (1, 1) :(sort a)\n where\n !m = 1000000007 :: Int64\n\n (*:) !i !j = (i * j) `mod` m\n (+:) !i !j = (i + j) `mod` m\n (-:) !i !j = (`mod` m) . (+ m) . (`mod` m) $ i - j\n\n fac :: UArray Int64 Int64\n !fac = listArray (0, h + w) $ scanl (*:) 1 [1..h + w]\n\n ifac :: UArray Int64 Int64\n !ifac = amap inverse fac\n where inverse !a = (`mod` m) . (+ m) . (`mod` m) . fst $ gcd' a m\n\n count (!i, !j) (!i', !j')\n | i' < i || j' < j = 0\n | otherwise = (fac ! (di + dj)) *: (ifac ! di) *: (ifac ! dj)\n where\n !di = i' - i\n !dj = j' - j\n\n\n loop self@(!i, !j) !acc = ((i, j), out):acc\n where\n out = count self (h, w) -: foldr (+:) 0 (count' <$> acc)\n count' ((i', j'), k) = k *: count self (i', j')\n\n\nwrap :: Int -> Int -> [[Int64]] -> Int64\nwrap h w a = solve (fromIntegral h) (fromIntegral w) a'\n where a' = (\\[i, j] -> (i, j)) <$> a\n\nparse :: Num a => ByteString -> [a]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [h, w, n] <- parse <$> B.getLine\n a <- replicateM n (parse <$> B.getLine)\n print $ wrap h w a\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, listArray, (!), amap)\n\ngcd' :: Integral a => a -> a -> (a, a)\ngcd' !a !b\n | a `mod` b /= 0 = loop 1 0 0 1 a b\n | otherwise = (0, 1)\n where\n loop !x !y !x' !y' !r !r'\n | r' `mod` r'' == 0 = (x - q * x', y - q * y')\n | otherwise = loop x' y' (x - q * x') (y - q * y') r' r''\n where (q, r'') = r `divMod` r'\n\nsolve :: Int -> Int -> [(Int, Int)] -> Int64\nsolve h w a = snd . head . foldr loop [] $ (1, 1) :(sort a)\n where\n !m = 1000000007 :: Int64\n\n (*:) !i !j = (i * j) `mod` m\n (+:) !i !j = (i + j) `mod` m\n (-:) !i !j = (`mod` m) . (+ m) . (`mod` m) $ i - j\n\n fac :: UArray Int Int64\n !fac = listArray (0, h + w) $ scanl (*:) 1 [1.. fromIntegral $ h + w]\n\n ifac :: UArray Int Int64\n !ifac = amap inverse fac\n where inverse !a = (`mod` m) . (+ m) . (`mod` m) . fst $ gcd' a m\n\n count (!i, !j) (!i', !j')\n | i' < i || j' < j = 0\n | otherwise = (fac ! (di + dj)) *: (ifac ! di) *: (ifac ! dj)\n where\n !di = i' - i\n !dj = j' - j\n\n loop self@(!i, !j) !acc = ((i, j), out):acc\n where\n !out = count self (h, w) -: foldr (+:) 0 (count' <$> acc)\n count' ((!i', !j'), !k) = k *: count self (i', j')\n\nparse :: ByteString -> [Int]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [h, w, n] <- parse <$> B.getLine\n a <- replicateM n ((\\[i, j] -> (i, j)) . parse <$> B.getLine)\n print $ solve h w a\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, listArray, (!), amap)\n\ngcd' :: Integral a => a -> a -> (a, a)\ngcd' !a !b\n | a `mod` b /= 0 = loop 1 0 0 1 a b\n | otherwise = (0, 1)\n where\n loop !x !y !x' !y' !r !r'\n | r' `mod` r'' == 0 = (x - q * x', y - q * y')\n | otherwise = loop x' y' (x - q * x') (y - q * y') r' r''\n where (q, r'') = r `divMod` r'\n\nsolve :: Int64 -> Int64 -> [(Int64, Int64)] -> Int64\nsolve h w = snd . head . foldr loop [] . ((1, 1):)\n where\n !m = 1000000007 :: Int64\n (*:) !i !j = (i * j) `mod` m\n (+:) !i !j = (i + j) `mod` m\n (-:) !i !j = ((i - j) `mod` m + m) `mod` m\n\n fac :: UArray Int64 Int64\n !fac = listArray (0, h + w) $ scanl (*:) 1 [1..h + w]\n\n ifac :: UArray Int64 Int64\n !ifac = amap inverse fac\n where inverse !a = (`mod` m) . (+ m) . (`mod` m) . fst $ gcd' a m\n\n count (!i, !j) (!i', !j')\n | i' < i || j' < j = 0\n | otherwise = (fac ! (di + dj)) *: (ifac ! di) *: (ifac ! dj)\n where\n !di = i' - i\n !dj = j' - j\n\n\n loop self@(!i, !j) !acc = ((i, j), out):acc\n where\n out = count self (h, w) -: foldr (+:) 0 (count' <$> acc)\n count' ((i', j'), k) = k *: count self (i', j')\n\n\nwrap :: Int -> Int -> [[Int64]] -> Int64\nwrap h w a = solve (fromIntegral h) (fromIntegral w) a'\n where a' = (\\[i, j] -> (i, j)) <$> a\n\nparse :: Num a => ByteString -> [a]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [h, w, n] <- parse <$> B.getLine\n a <- replicateM n (parse <$> B.getLine)\n print $ wrap h w a\n"}, {"source_code": "module Main(main) where\n\nimport Control.Monad\nimport Data.Functor\nimport Data.List\n\nisDigit x = x>='0' && x<='9'\nsplit f l@(a:as) lft\n\t| f a = split f as (a:lft)\n\t| otherwise = (reverse lft, as)\nsplit _ [] lft = (reverse lft, [])\nreadInts::String -> [Int]\nreadInts [] = []\nreadInts l@(x:xs)\n\t| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)\n\t| otherwise = readInts xs\nreadNlines n = go 0 where\n\tgo i = do\n\t\t\ta<-getLine\n\t\t\tgo $ i-1\n\np = 1000000007\n\nmain = do\n\tl <- getLine\n\tlet [h, w, n] = readInts l\n\tlet srt = sortBy (\\x y -> compare (sum x) (sum y))\n\tblacks <- (srt) <$> replicateM n (readInts <$> getLine)\n\tputStrLn $ show blacks\n"}, {"source_code": "module Main(main) where\n\nimport Control.Monad(replicateM)\nimport Data.Functor\nimport Data.List\nimport Data.Array\n\nisDigit x = x>='0' && x<='9'\nsplit f l@(a:as) lft\n\t| f a = split f as (a:lft)\n\t| otherwise = (reverse lft, as)\nsplit _ [] lft = (reverse lft, [])\nreadInts::String -> [Int]\nreadInts [] = []\nreadInts l@(x:xs)\n\t| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)\n\t| otherwise = readInts xs\n\nfactorials = go 0 1 where\n\tgo 100001 _ = []\n\tgo i j = (i,j):(go (i+1) ((j*(i+1)) `rem` p))\n\np::Int\np = 1000000007\n(<**>) x y = (x * y) `rem` p\n(<+>) x y = let t = x + y in if t < p then t else t-p\n(<->) x y = let t = x - y in if t < 0 then t+p else t\npow x 0 = 1\npow x a = let ll = pow (x<**>x) (a `quot` 2) in if a `rem` 2 > 0 then (ll <**> x) else ll\ninverse x = pow x (p-2)\nfacs = array (0, 100000) factorials\nifacs = array (0, 100000) $ map (\\(x,y) -> (x, inverse y)) factorials\nchoose a b\n\t| 0<=b && 0<=a = (facs ! (a+b)) <**> (ifacs ! a) <**> (ifacs ! b)\n\t| otherwise = 0\n\ndp (prev) me@((i, j)) =\n\tlet\n\t\tfn (d, (a, b)) = d <**> (choose (i-a) (j-b))\n\tin\n\t\tprev ++ [((choose (i-1) (j-1)) <-> (foldl (<+>) 0 $ map fn prev), me)]\nrunDp :: [(Int, Int)] -> [Int]\nrunDp l = let t = foldl dp ([]) l in map fst t\n--runDp (a:as) = let \n\nmain = do\n\tl <- getLine\n\tlet [h, w, n] = readInts l\n\tlet srt = sortBy (\\x y -> compare (sum x) (sum y))\n\tblacks <- ((map (\\x->(head x, x!!1))).srt) <$> replicateM n (readInts <$> getLine)\n\tlet all = blacks ++ [(h, w)]\n\tputStrLn $ show $ head.reverse.runDp $ all\n"}], "src_uid": "91749edcc396819d4172d06e2744b20b"} {"source_code": "import Data.List\nimport Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountSwitch' [] zs last n = (n,zs,last)\ncountSwitch' (x:xs) _ (-1) _ = countSwitch' xs [1] x 0\ncountSwitch' (x:xs) (z:zs) last n \n | x==last = countSwitch' xs ((z+1):zs) x n\n | otherwise = countSwitch' xs (1:z:zs) x (n+1)\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start):z) (start-1) (end-1)\n\t\n\t\nsum' _ _ partial 0 = [show partial]\t\nsum' [] [] _ _= []\nsum' ((a):as) ((b):bs) partial toGo = show (a + b + partial) : (sum' as bs (a + b + partial) (toGo-1))\nsum' [] ((b):bs) partial toGo = show (b + partial) : (sum' [] bs (b + partial) (toGo-1))\nsum' ((a):as) [] partial toGo = show (a + partial) : (sum' [] as (a + partial) (toGo-1))\n\t\ncountTurns switchA switchB lastA lastB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (lastA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (lastB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((0):a) b 0 (switchB+1)))))\n\t| lastA==0 && lastB==0 = show(switchA) ++ (\"\\n\" ++ unwords (init(sum' a b 0 switchA)))\n\t| lastA==1 && lastB==1 = show(switchA+1) ++ (\"\\n\" ++ unwords (init(sum' a b 0 (switchA+1))))\n\t| lastA==0 && lastB==1 = show(switchA + 1) ++ (\"\\n\" ++ unwords (init(sum' ((0):a) b 0 (switchA+1))))\n\t| lastA==1 && lastB==0 = show(switchA + 1) ++ (\"\\n\" ++ unwords (init(sum' a ((0):b) 0 (switchA+1))))\t\n\nbuildStack switchA switchB a b n m firstA firstB \n\t| switchA > switchB = stack a b n (n+m) [] switchA switchB\n\t| switchB > switchA = stack b a (n+m) n [] switchB switchA\n\t| firstA==firstB = stack a b n (n+m) [] switchA switchB\n\t| firstA==0 && firstB==1 = stack a b n (n+m) [] switchA switchB\n\t| firstA==1 && firstB==0 = stack b a (n+m) n [] switchB switchA\n\n\nstack [] [] n m z _ _ = z\nstack ((b):xs) [] n m z _ _ = stack xs [] (n-b) m (addTo z n b) 0 0\nstack [] ((b):ys) n m z _ _ = stack [] ys n (m-b) (addTo z m b) 0 0\nstack ((b):xs) ((d):ys) n m z lengthA lengthB \n\t| (lengthB) > (lengthA) = stack ((b):xs) (ys) n (m-d) (addTo z m d) lengthA (lengthB-1)\n\t| otherwise = stack ((d):ys) xs m (n-b) (addTo z n b) lengthB (lengthA-1) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\tfirstA = head firstDeck\n\t\tfirstB = head secondDeck\n\t\t(switchA,a,lastA) = countSwitch' firstDeck [] (-1) n\n\t\t(switchB,b,lastB) = countSwitch' secondDeck [] (-1) m\n\tin \n\t\tdo\n\t --print a\n\t\t\t--print b\n\t\t\t(appendFile \"output.txt\" $ unwords (buildStack switchA switchB a b n m lastA lastB))\n\t\t\t(appendFile \"output.txt\" (\"\\n\" ++ (countTurns switchA switchB lastA lastB firstA firstB (reverse a) (reverse b))))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n --print $ show (countSwitch firstDeck [] 0)\n --print $ show (countSwitch' firstDeck [] (-1) 0)\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountSwitch' [] zs last n = (n,zs,last)\ncountSwitch' (x:xs) _ (-1) _ = countSwitch' xs [1] x 0\ncountSwitch' (x:xs) (z:zs) last n \n | x==last = countSwitch' xs ((z+1):zs) x n\n | otherwise = countSwitch' xs (1:z:zs) x (n+1)\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start):z) (start-1) (end-1)\n\t\n\t\nsum' _ _ partial 0 = [show partial]\t\nsum' [] [] _ _= []\nsum' ((a):as) ((b):bs) partial toGo = show (a + b + partial) : (sum' as bs (a + b + partial) (toGo-1))\nsum' [] ((b):bs) partial toGo = show (b + partial) : (sum' [] bs (b + partial) (toGo-1))\nsum' ((a):as) [] partial toGo = show (a + partial) : (sum' [] as (a + partial) (toGo-1))\n\t\ncountTurns switchA switchB lastA lastB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (lastA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (lastB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ unwords (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((0):a) b 0 (switchB+1)))))\n\t| lastA==0 && lastB==0 = show(switchA) ++ (\"\\n\" ++ unwords (init(sum' a b 0 switchA)))\n\t| lastA==1 && lastB==1 = show(switchA+1) ++ (\"\\n\" ++ unwords (init(sum' a b 0 (switchA+1))))\n\t| lastA==0 && lastB==1 = show(switchA + 1) ++ (\"\\n\" ++ unwords (init(sum' ((0):a) b 0 (switchA+1))))\n\t| lastA==1 && lastB==0 = show(switchA + 1) ++ (\"\\n\" ++ unwords (init(sum' a ((0):b) 0 (switchA+1))))\t\n\nbuildStack switchA switchB a b n m firstA firstB \n\t| switchA > switchB = stack a b n (n+m) [] switchA switchB\n\t| switchB > switchA = stack b a (n+m) n [] switchB switchA\n\t| firstA==firstB = stack a b n (n+m) [] switchA switchB\n\t| firstA==0 && firstB==1 = stack a b n (n+m) [] switchA switchB\n\t| firstA==1 && firstB==0 = stack b a (n+m) n [] switchB switchA\n\n\nstack [] [] n m z _ _ = z\nstack ((b):xs) [] n m z _ _ = stack xs [] (n-b) m (addTo z n b) 0 0\nstack [] ((b):ys) n m z _ _ = stack [] ys n (m-b) (addTo z m b) 0 0\nstack ((b):xs) ((d):ys) n m z lengthA lengthB \n\t| (lengthB) > (lengthA) = stack ((b):xs) (ys) n (m-d) (addTo z m d) lengthA (lengthB-1)\n\t| otherwise = stack ((d):ys) xs m (n-b) (addTo z n b) lengthB (lengthA-1) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\tfirstA = head firstDeck\n\t\tfirstB = head secondDeck\n\t\t(switchA,a,lastA) = countSwitch' firstDeck [] (-1) n\n\t\t(switchB,b,lastB) = countSwitch' secondDeck [] (-1) m\n\tin \n\t\tdo\n\t --print a\n\t\t\t--print b\n\t\t\t(appendFile \"output.txt\" $ unwords (buildStack switchA switchB a b n m lastA lastB))\n\t\t\t(appendFile \"output.txt\" (\"\\n\" ++ (countTurns switchA switchB lastA lastB firstA firstB (reverse a) (reverse b))))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n --print $ show (countSwitch firstDeck [] 0)\n --print $ show (countSwitch' firstDeck [] (-1) 0)\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}], "negative_code": [{"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\nrun line 0 = ([],0,-1,-1)\nrun line n = \n\tlet Just(elem,line') = readInt line \n\tin\n\t\tlet (stack,switches,last',first') = run line' (n-1)\n\t\tin\n\t\t\tif(stack==[])\n\t\t\tthen (((elem,1):[]),0,elem,elem)\n\t\t\telse \n\t\t\t\tlet ((_,count):s) = stack in\n\t\t\t\t\tif (elem == first') \n\t\t\t\t\tthen (((elem,count+1):s),switches,last',elem)\n\t\t\t\t\telse (((elem,1):stack),switches+1,last',elem)\n\twhere readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n\naddTo z start 0 = z\naddTo z start end = (start:(addTo z (start+1) (end-1)))\n\n--solve :: Integral a => [(a,a)] -> [(a,a)] -> a -> a -> a -> ([a],[a])\nsolve [] [] _ _ _ 0 = ([],[])\nsolve [] [] _ _ _ extra = ([],[extra])\nsolve [] ((c,d):sStack) n m count extra = \n\tif (sStack==[] && c==0)\n\tthen\n\t\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\t\tin (addTo stack m d, (cards))\n\telse\n\t\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\t\tin (addTo stack m d, ((count+d):cards))\nsolve ((a,b):fStack) [] n m count extra =\n\tif(fStack==[] && a==0)\n\tthen\n\t\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\t\tin ((addTo stack n b), (cards))\n\telse\n\t\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\t\tin ((addTo stack n b), ((count+b):cards))\nsolve ((a,b):fStack) ((c,d):sStack) n m count extra\n\t| a==c =\n\t\tif(fStack==sStack && fStack==[] && c==0)\n\t\tthen\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\t\tin (addTo (addTo stack m d) n b, (cards))\n\t\telse\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\t\tin (addTo (addTo stack m d) n b, ((count+b+d):cards))\n\t| otherwise = \n\t\tif(fStack==sStack && fStack==[] && c==0)\n\t\tthen\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0\n\t\t\tin ((addTo (addTo stack m d) n b), ((count+b):cards))\n\t\telse\n\t\t\tlet \n\t\t\t (stack, cards) = \n\t\t\t solve fStack sStack (n+b) (m+d) (count+b+d) (count+b+d)\n\t\t\tin ((addTo (addTo stack m d) n b), ((count+b):cards))\n\n\ncountTurns fSwitch sSwitch fLast sLast\n\t| fSwitch > sSwitch && fLast==1 = fSwitch + 1\n\t| fSwitch > sSwitch && fLast==0 = fSwitch\n\t| sSwitch > fSwitch && sLast==1 = sSwitch + 1\n\t| sSwitch > fSwitch && sLast==0 = sSwitch\n\t| fLast==sLast && fLast==0 = fSwitch\n\t| fLast==sLast && fLast==1 = fSwitch + 1\n\t| otherwise = fSwitch + 1\n\ntoStr array = tail $ foldr (\\x y -> (' ':show(x)) ++ y) \"\" array\n\nsolve' fSwitch sSwitch fStack sStack fLast sLast n m\n\t| fSwitch>sSwitch = \n\t\tlet\n\t\t\t(stack,cards) = solve fStack sStack 1 (n+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| sSwitch>fSwitch = \n\t\tlet\n\t\t\t(stack,cards) = solve sStack fStack 1 (m+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| fLast==sLast = \n\t\tlet\n\t\t\t(stack,cards) = solve fStack sStack 1 (n+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| fLast==0 = \n\t\tlet\n\t\t\t(stack,cards) = solve fStack sStack 1 (n+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| sLast==0 = \n\t\tlet\n\t\t\t(stack,cards) = solve sStack fStack 1 (m+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t\t\t\n\nmain = \n do \n all <- BSC.readFile \"input.txt\"\n let (n':firstLine:m':secondLine:_) = BSC.lines all\n let Just (n,_) = readInt n'\n let Just (m,_) = readInt m'\n --print n\n --print firstLine\n --print m\n --print secondLine\n let (fStack,fSwitch,fLast,fFirst) = run firstLine n\n let (sStack,sSwitch,sLast,sFirst) = run secondLine m\n solve' fSwitch sSwitch fStack sStack fLast sLast n m\n \n --print $ run secondLine m\n --let (firstDeck, r2) = readMany n readInteger r1\n --let Just (m, r3) = readInteger r2\n --let (secondDeck, _) = readMany m readInteger r3\n -- solve n m firstDeck secondDeck\n print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB firstA firstB\n\t| switchA > switchB = if (firstA == 0) then switchA else switchA+1\n\t| switchB > switchA = if (firstB == 0) then switchB else switchB+1\n\t| firstA==0 && firstB==0 = switchA\n\t| firstA==1 && firstB==1 = switchA + 1\n\t| otherwise = switchA + 1\n\t\naddTo z start 0 = z\naddTo z start end = addTo ((show(start)++\" \")++z) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==0 = stack a b n (n+m) []\n\t| otherwise = stack b a (n+m) n []\n\t\nstack [] [] n m z = z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) (y:ys) n m z = stack (y:ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((firstA,_):as) = a\n\t\t\t((firstB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((show $ buildStack switchA switchB a b n m firstA) ++ \"\\n\" ++ (show $ countTurns switchA switchB firstA firstB)))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n solve n m firstDeck secondDeck\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (firstA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0,0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((1,0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (firstB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0,0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((1,0):a) b 0 (switchB+1)))))\n\t| firstA==0 && firstB==0 = show(switchA) ++ (\"\\n\" ++ (init(sum' a b 0 switchA)))\n\t| firstA==1 && firstB==1 = show(switchA+1) ++ (\"\\n\" ++ (init(sum' a b 0 (switchA+1))))\n\t| firstA==0 && firstB==1 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' a ((0,0):b) 0 (switchA+1))))\n\t| firstA==1 && firstB==0 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' ((0,0):a) b 0(switchA+1))))\n\t\n\nsum' _ _ _ 0 = []\t\nsum' [] [] _ _= []\nsum' ((_,a):as) ((_,b):bs) partial toGo = show (a + b + partial) ++ (' ' : (sum' as bs (a + b + partial) (toGo-1)))\nsum' [] ((_,b):bs) partial toGo = show (b + partial) ++ (' ' : (sum' [] bs (b + partial) (toGo-1)))\nsum' ((_,a):as) [] partial toGo = show (a + partial) ++ (' ' : (sum' [] as (a + partial) (toGo-1)))\n\naddTo z start 0 = init z\naddTo z start end = addTo (show(start)++(' ':z)) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==0 = stack a b n (n+m) []\n\t| otherwise = stack b a (n+m) n []\n\t\nstack [] [] n m z = z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) (y:ys) n m z = stack (y:ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((firstA,_):as) = a\n\t\t\t((firstB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tprint a\n\t\t\t\tprint b\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((buildStack switchA switchB a b n m firstA) ++ \"\\n\" ++ (countTurns switchA switchB firstA firstB a b)))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (firstA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0,0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((1,0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (firstB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0,0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((1,0):a) b 0 (switchB+1)))))\n\t| firstA==0 && firstB==0 = show(switchA) ++ (\"\\n\" ++ (init(sum' a b 0 switchA)))\n\t| firstA==1 && firstB==1 = show(switchA+1) ++ (\"\\n\" ++ (init(sum' a b 0 (switchA+1))))\n\t| firstA==0 && firstB==1 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' a ((0,0):b) 0 (switchA+1))))\n\t| firstA==1 && firstB==0 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' ((0,0):a) b 0(switchA+1))))\n\t\n\nsum' _ _ _ 0 = []\t\nsum' [] [] _ _= []\nsum' ((_,a):as) ((_,b):bs) partial toGo = show (a + b + partial) ++ (' ' : (sum' as bs (a + b + partial) (toGo-1)))\nsum' [] ((_,b):bs) partial toGo = show (b + partial) ++ (' ' : (sum' [] bs (b + partial) (toGo-1)))\nsum' ((_,a):as) [] partial toGo = show (a + partial) ++ (' ' : (sum' [] as (a + partial) (toGo-1)))\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start)++(' ':z)) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==0 = stack a b n (n+m) []\n\t| otherwise = stack b a (n+m) n []\n\t\nstack [] [] n m z = init z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) (y:ys) n m z = stack (y:ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((firstA,_):as) = a\n\t\t\t((firstB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tprint a\n\t\t\t\tprint b\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((buildStack switchA switchB a b n m firstA) ++ \"\\n\" ++ (countTurns switchA switchB firstA firstB a b)))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB lastA lastB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (lastA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0,0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((1,0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (lastB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0,0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((1,0):a) b 0 (switchB+1)))))\n\t| lastA==0 && lastB==0 = show(switchA) ++ (\"\\n\" ++ (init(sum' a b 0 switchA)))\n\t| lastA==1 && lastB==1 = show(switchA+1) ++ (\"\\n\" ++ (init(sum' a b 0 (switchA+1))))\n\t| lastA==0 && lastB==1 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' a ((0,0):b) 0 (switchA+1))))\n\t| lastA==1 && lastB==0 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' ((0,0):a) b 0(switchA+1))))\n\t\n\nsum' _ _ _ 0 = []\t\nsum' [] [] _ _= []\nsum' ((_,a):as) ((_,b):bs) partial toGo = show (a + b + partial) ++ (' ' : (sum' as bs (a + b + partial) (toGo-1)))\nsum' [] ((_,b):bs) partial toGo = show (b + partial) ++ (' ' : (sum' [] bs (b + partial) (toGo-1)))\nsum' ((_,a):as) [] partial toGo = show (a + partial) ++ (' ' : (sum' [] as (a + partial) (toGo-1)))\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start)++(' ':z)) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA firstB \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==firstB = stack a b n (n+m) []\n\t| firstA==0 && firstB==1 = stack a b n (n+m) []\n\t| firstA==1 && firstB==0 = stack b a (n+m) n []\n\t\nstack [] [] n m z = init z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) ((c,d):ys) n m z \n\t| (length ys) > (length xs) = stack ((a,b):xs) (ys) n (m-d) (addTo z m d)\n\t| otherwise = stack ((c,d):ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\tfirstA = head firstDeck\n\t\tfirstB = head secondDeck\n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((lastA,_):as) = a\n\t\t\t((lastB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tprint a\n\t\t\t\tprint b\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((buildStack switchA switchB a b n m lastA lastB) ++ \"\\n\" ++ (countTurns switchA switchB lastA lastB firstA firstB (reverse a) (reverse b))))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\nrun line 0 = ([],0,-1,-1)\nrun line n = \n\tlet Just(elem,line') = readInt line \n\tin\n\t\tlet (stack,switches,last',first') = run line' (n-1)\n\t\tin\n\t\t\tif(stack==[])\n\t\t\tthen (((elem,1):[]),0,elem,elem)\n\t\t\telse \n\t\t\t\tlet ((_,count):s) = stack in\n\t\t\t\t\tif (elem == first') \n\t\t\t\t\tthen (((elem,count+1):s),switches,last',elem)\n\t\t\t\t\telse (((elem,1):stack),switches+1,last',elem)\n\twhere readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n\naddTo z start 0 = z\naddTo z start end = (start:(addTo z (start+1) (end-1)))\n\n--solve :: Integral a => [(a,a)] -> [(a,a)] -> a -> a -> a -> ([a],[a])\nsolve [] [] _ _ _ 0 = ([],[])\nsolve [] [] _ _ _ extra = ([],[extra])\nsolve [] ((c,d):sStack) n m count extra = \n\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\tin if(extra==0) \n\t\tthen (addTo stack m d, ((count+d):cards))\n\t\telse (addTo stack m d, ((count+d):extra:cards))\nsolve ((a,b):fStack) [] n m count extra =\n\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\tin if (extra==0)\n\t\tthen ((addTo stack n b), ((count+b):cards))\n\t\telse ((addTo stack n b), ((count+b):extra:cards))\nsolve ((a,b):fStack) ((c,d):sStack) n m count extra\n\t| a==b = \n\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\tin (addTo (addTo stack n b) m d, ((count+b+d):cards))\n\t| otherwise =\n\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) (count+b+d)\n\t\tin ((addTo (addTo stack n b) m d), ((count+d):cards))\n\n\ncountTurns fSwitch sSwitch fLast sLast\n\t| fSwitch > sSwitch && fLast==1 = fSwitch + 1\n\t| fSwitch > sSwitch && fLast==0 = fSwitch\n\t| sSwitch > fSwitch && sLast==1 = sSwitch + 1\n\t| sSwitch > fSwitch && sLast==0 = sSwitch\n\t| fLast==sLast && fLast==0 = fSwitch\n\t| fLast==sLast && fLast==1 = fSwitch + 1\n\t| otherwise = fSwitch + 1\n\ntoStr array = tail $ foldr (\\x y -> (' ':show(x)) ++ y) \"\" array\n\nmain = \n do \n all <- BSC.readFile \"input.txt\"\n let (n':firstLine:m':secondLine:_) = BSC.lines all\n let Just (n,_) = readInt n'\n let Just (m,_) = readInt m'\n --print n\n --print firstLine\n --print m\n --print secondLine\n let (fStack,fSwitch,fLast,fFirst) = run firstLine n\n let (sStack,sSwitch,sLast,sFirst) = run secondLine m\n let (stack,cards) = solve fStack sStack 1 (n+1) 0 0\n \n BS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ show(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ (toStr cards)))\n \n --print $ run secondLine m\n --let (firstDeck, r2) = readMany n readInteger r1\n --let Just (m, r3) = readInteger r2\n --let (secondDeck, _) = readMany m readInteger r3\n -- solve n m firstDeck secondDeck\n print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\nrun line 0 = ([],0,-1,-1)\nrun line n = \n\tlet Just(elem,line') = readInt line \n\tin\n\t\tlet (stack,switches,last',first') = run line' (n-1)\n\t\tin\n\t\t\tif(stack==[])\n\t\t\tthen (((elem,1):[]),0,elem,elem)\n\t\t\telse \n\t\t\t\tlet ((_,count):s) = stack in\n\t\t\t\t\tif (elem == first') \n\t\t\t\t\tthen (((elem,count+1):s),switches,last',elem)\n\t\t\t\t\telse (((elem,1):stack),switches+1,last',elem)\n\twhere readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n\naddTo z start 0 = z\naddTo z start end = (start:(addTo z (start+1) (end-1)))\n\n--solve :: Integral a => [(a,a)] -> [(a,a)] -> a -> a -> a -> ([a],[a])\nsolve [] [] _ _ _ 0 = ([],[])\nsolve [] [] _ _ _ extra = ([],[extra])\nsolve [] ((c,d):sStack) n m count extra = \n\tif (sStack==[] && c==0)\n\tthen\n\t\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\t\tin (addTo stack m d, (cards))\n\telse\n\t\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\t\tin (addTo stack m d, ((count+d):cards))\nsolve ((a,b):fStack) [] n m count extra =\n\tif(fStack==[] && a==0)\n\tthen\n\t\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\t\tin ((addTo stack n b), (cards))\n\telse\n\t\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\t\tin ((addTo stack n b), ((count+b):cards))\nsolve ((a,b):fStack) ((c,d):sStack) n m count extra\n\t| a==c =\n\t\tif(fStack==sStack && fStack==[] && c==0)\n\t\tthen\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\t\tin (addTo (addTo stack m d) n b, (cards))\n\t\telse\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\t\tin (addTo (addTo stack m d) n b, ((count+b+d):cards))\n\t| otherwise = \n\t\tif(fStack==sStack && fStack==[] && c==0)\n\t\tthen\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0\n\t\t\tin ((addTo (addTo stack m d) n b), ((count+b):cards))\n\t\telse\n\t\t\tlet \n\t\t\t (stack, cards) = \n\t\t\t solve fStack sStack (n+b) (m+d) (count+b+d) (count+b+d)\n\t\t\tin ((addTo (addTo stack m d) n b), ((count+b):cards))\n\n\ncountTurns fSwitch sSwitch fLast sLast\n\t| fSwitch > sSwitch && fLast==1 = fSwitch + 1\n\t| fSwitch > sSwitch && fLast==0 = fSwitch\n\t| sSwitch > fSwitch && sLast==1 = sSwitch + 1\n\t| sSwitch > fSwitch && sLast==0 = sSwitch\n\t| fLast==sLast && fLast==0 = fSwitch\n\t| fLast==sLast && fLast==1 = fSwitch + 1\n\t| otherwise = fSwitch + 1\n\ntoStr array = tail $ foldr (\\x y -> (' ':show(x)) ++ y) \"\" array\n\nsolve' fSwitch sSwitch fStack sStack fLast sLast n m\n\t| fSwitch>sSwitch = \n\t\tlet\n\t\t\t(stack,cards) = solve fStack sStack 1 (n+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| sSwitch>fSwitch = \n\t\tlet\n\t\t\t(stack,cards) = solve sStack fStack (n+1) 1 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| fLast==sLast = \n\t\tlet\n\t\t\t(stack,cards) = solve fStack sStack 1 (n+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| fLast==0 = \n\t\tlet\n\t\t\t(stack,cards) = solve fStack sStack 1 (n+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t| sLast==0 = \n\t\tlet\n\t\t\t(stack,cards) = solve sStack fStack 1 (m+1) 0 0\n\t\tin\n\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ \n\t\t\tshow(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ \n\t\t\t(toStr cards)))\n\t\t\t\n\nmain = \n do \n all <- BSC.readFile \"input.txt\"\n let (n':firstLine:m':secondLine:_) = BSC.lines all\n let Just (n,_) = readInt n'\n let Just (m,_) = readInt m'\n --print n\n --print firstLine\n --print m\n --print secondLine\n let (fStack,fSwitch,fLast,fFirst) = run firstLine n\n let (sStack,sSwitch,sLast,sFirst) = run secondLine m\n solve' fSwitch sSwitch fStack sStack fLast sLast n m\n \n --print $ run secondLine m\n --let (firstDeck, r2) = readMany n readInteger r1\n --let Just (m, r3) = readInteger r2\n --let (secondDeck, _) = readMany m readInteger r3\n -- solve n m firstDeck secondDeck\n print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (firstA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0,0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((1,0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (firstB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0,0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((1,0):a) b 0 (switchB+1)))))\n\t| firstA==0 && firstB==0 = show(switchA) ++ (\"\\n\" ++ (init(sum' a b 0 switchA)))\n\t| firstA==1 && firstB==1 = show(switchA+1) ++ (\"\\n\" ++ (init(sum' a b 0 (switchA+1))))\n\t| firstA==0 && firstB==1 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' a ((0,0):b) 0 (switchA+1))))\n\t| firstA==1 && firstB==0 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' ((0,0):a) b 0(switchA+1))))\n\t\n\nsum' _ _ _ 0 = []\t\nsum' [] [] _ _= []\nsum' ((_,a):as) ((_,b):bs) partial toGo = show (a + b + partial) ++ (' ' : (sum' as bs (a + b + partial) (toGo-1)))\nsum' [] ((_,b):bs) partial toGo = show (b + partial) ++ (' ' : (sum' [] bs (b + partial) (toGo-1)))\nsum' ((_,a):as) [] partial toGo = show (a + partial) ++ (' ' : (sum' [] as (a + partial) (toGo-1)))\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start)++(' ':z)) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==0 = stack a b n (n+m) []\n\t| otherwise = stack b a (n+m) n []\n\t\nstack [] [] n m z = init z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) (y:ys) n m z = stack (y:ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((firstA,_):as) = a\n\t\t\t((firstB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tprint a\n\t\t\t\tprint b\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((buildStack switchA switchB a b n m firstA) ++ \"\\n\" ++ (countTurns switchA switchB firstA firstB a b)))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n BS.writeFile \"output.txt\" $ BSC.pack \"1 2 4 5 6 7 3\\n3\\n1 2 7\"\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (firstA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchA) else init (sum' a ((0,0):b) 0 switchA))))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchA+1)) else init(sum' a ((1,0):b) 0 (switchA+1)))))\n\t| switchB > switchA = if (firstB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 switchB) else init(sum' ((0,0):a) b 0 switchB))))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ (if (firstB==firstA) then init(sum' a b 0 (switchB+1)) else init(sum' ((1,0):a) b 0 (switchB+1)))))\n\t| firstA==0 && firstB==0 = show(switchA) ++ (\"\\n\" ++ (init(sum' a b 0 switchA)))\n\t| firstA==1 && firstB==1 = show(switchA+1) ++ (\"\\n\" ++ (init(sum' a b 0 (switchA+1))))\n\t| firstA==0 && firstB==1 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' a ((0,0):b) 0 (switchA+1))))\n\t| firstA==1 && firstB==0 = show(switchA + 1) ++ (\"\\n\" ++ (init(sum' ((0,0):a) b 0(switchA+1))))\n\t\n\nsum' _ _ _ 0 = []\t\nsum' [] [] _ _= []\nsum' ((_,a):as) ((_,b):bs) partial toGo = show (a + b + partial) ++ (' ' : (sum' as bs (a + b + partial) (toGo-1)))\nsum' [] ((_,b):bs) partial toGo = show (b + partial) ++ (' ' : (sum' [] bs (b + partial) (toGo-1)))\nsum' ((_,a):as) [] partial toGo = show (a + partial) ++ (' ' : (sum' [] as (a + partial) (toGo-1)))\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start)++(' ':z)) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA firstB \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==firstB = stack a b n (n+m) []\n\t| firstA==0 && firstB==1 = stack a b n (n+m) []\n\t| firstA==1 && firstB==0 = stack b a (n+m) n []\n\t\nstack [] [] n m z = init z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) ((c,d):ys) n m z \n\t| (length ys) > (length xs) = stack ((a,b):xs) (ys) n (m-d) (addTo z m d)\n\t| otherwise = stack ((c,d):ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((firstA,_):as) = a\n\t\t\t((firstB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tprint a\n\t\t\t\tprint b\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((buildStack switchA switchB a b n m firstA firstB) ++ \"\\n\" ++ (countTurns switchA switchB firstA firstB a b)))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\nrun line 0 = ([],0,-1,-1)\nrun line n = \n\tlet Just(elem,line') = readInt line \n\tin\n\t\tlet (stack,switches,last',first') = run line' (n-1)\n\t\tin\n\t\t\tif(stack==[])\n\t\t\tthen (((elem,1):[]),0,elem,elem)\n\t\t\telse \n\t\t\t\tlet ((_,count):s) = stack in\n\t\t\t\t\tif (elem == first') \n\t\t\t\t\tthen (((elem,count+1):s),switches,last',elem)\n\t\t\t\t\telse (((elem,1):stack),switches+1,last',elem)\n\twhere readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n\naddTo z start 0 = z\naddTo z start end = (start:(addTo z (start+1) (end-1)))\n\n--solve :: Integral a => [(a,a)] -> [(a,a)] -> a -> a -> a -> ([a],[a])\nsolve [] [] _ _ _ 0 = ([],[])\nsolve [] [] _ _ _ extra = ([],[extra])\nsolve [] ((c,d):sStack) n m count extra = \n\tif (sStack==[] && c==0)\n\tthen\n\t\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\t\tin (addTo stack m d, (cards))\n\telse\n\t\tlet (stack, cards) = solve [] sStack n (m+d) (count+d) 0\n\t\tin (addTo stack m d, ((count+d):cards))\nsolve ((a,b):fStack) [] n m count extra =\n\tif(fStack==[] && a==0)\n\tthen\n\t\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\t\tin ((addTo stack n b), (cards))\n\telse\n\t\tlet (stack, cards) = solve fStack [] (n+b) m (count+b) 0\n\t\tin ((addTo stack n b), ((count+b):cards))\nsolve ((a,b):fStack) ((c,d):sStack) n m count extra\n\t| a==c =\n\t\tif(fStack==sStack && fStack==[] && c==0)\n\t\tthen\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\t\tin (addTo (addTo stack m d) n b, (cards))\n\t\telse\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0 \n\t\t\tin (addTo (addTo stack m d) n b, ((count+b+d):cards))\n\t| otherwise = \n\t\tif(fStack==sStack && fStack==[] && c==0)\n\t\tthen\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) 0\n\t\t\tin ((addTo (addTo stack m d) n b), ((count+b):cards))\n\t\telse\n\t\t\tlet (stack, cards) = solve fStack sStack (n+b) (m+d) (count+b+d) (count+b+d)\n\t\t\tin ((addTo (addTo stack m d) n b), ((count+b):cards))\n\n\ncountTurns fSwitch sSwitch fLast sLast\n\t| fSwitch > sSwitch && fLast==1 = fSwitch + 1\n\t| fSwitch > sSwitch && fLast==0 = fSwitch\n\t| sSwitch > fSwitch && sLast==1 = sSwitch + 1\n\t| sSwitch > fSwitch && sLast==0 = sSwitch\n\t| fLast==sLast && fLast==0 = fSwitch\n\t| fLast==sLast && fLast==1 = fSwitch + 1\n\t| otherwise = fSwitch + 1\n\ntoStr array = tail $ foldr (\\x y -> (' ':show(x)) ++ y) \"\" array\n\nmain = \n do \n all <- BSC.readFile \"input.txt\"\n let (n':firstLine:m':secondLine:_) = BSC.lines all\n let Just (n,_) = readInt n'\n let Just (m,_) = readInt m'\n --print n\n --print firstLine\n --print m\n --print secondLine\n let (fStack,fSwitch,fLast,fFirst) = run firstLine n\n let (sStack,sSwitch,sLast,sFirst) = run secondLine m\n let (stack,cards) = solve fStack sStack 1 (n+1) 0 0\n \n BS.writeFile \"output.txt\" $ (BSC.pack ( (toStr stack) ++ \"\\n\" ++ show(countTurns fSwitch sSwitch fLast sLast) ++ \"\\n\" ++ (toStr cards)))\n \n --print $ run secondLine m\n --let (firstDeck, r2) = readMany n readInteger r1\n --let Just (m, r3) = readInteger r2\n --let (secondDeck, _) = readMany m readInteger r3\n -- solve n m firstDeck secondDeck\n print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport Data.Char (intToDigit)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncountSwitch :: (Integral a) => [a] -> [(a,a)] -> a -> ([(a,a)],a)\ncountSwitch [] z n = (z,n)\ncountSwitch (x:xs) [] _ = countSwitch xs ((x,1):[]) 0\ncountSwitch (x:xs) ((a,b):zs) n \n\t| x==a = countSwitch xs ((a,succ b):zs) n\n\t| otherwise = countSwitch xs ((x,1):(a,b):zs) (n+1)\n\ncountTurns switchA switchB firstA firstB a b\n\t| switchA > switchB = \n\t\tif (firstA == 0)\n\t\t\tthen (show (switchA) ++ (\"\\n\" ++ (if (firstB==firstA) then sum' a b 0 switchA else sum' a ((0,0):b) 0 switchA)))\n\t\t\telse (show (switchA+1) ++ (\"\\n\" ++ (if (firstB==firstA) then sum' a b 0 (switchA+1) else sum' a ((1,0):b) 0 (switchA+1))))\n\t| switchB > switchA = if (firstB == 0)\n\t\tthen (show (switchB) ++ (\"\\n\" ++ (if (firstB==firstA) then sum' a b 0 switchB else sum' ((0,0):a) b 0 switchB)))\n\t\telse (show (switchB+1) ++ (\"\\n\" ++ (if (firstB==firstA) then sum' a b 0 (switchB+1) else sum' ((1,0):a) b 0 (switchB+1))))\n\t| firstA==0 && firstB==0 = show(switchA) ++ (\"\\n\" ++ (sum' a b 0 switchA))\n\t| firstA==1 && firstB==1 = show(switchA+1) ++ (\"\\n\" ++ (sum' a b 0 (switchA+1)))\n\t| firstA==0 && firstB==1 = show(switchA + 1) ++ (\"\\n\" ++ (sum' a ((0,0):b) 0 (switchA+1)))\n\t| firstA==1 && firstB==0 = show(switchA + 1) ++ (\"\\n\" ++ (sum' ((0,0):a) b 0(switchA+1)))\n\t\n\nsum' _ _ _ 0 = []\t\nsum' [] [] _ _= []\nsum' ((_,a):as) ((_,b):bs) partial toGo = show (a + b + partial) ++ (' ' : (sum' as bs (a + b + partial) (toGo-1)))\nsum' [] ((_,b):bs) partial toGo = show (b + partial) ++ (' ' : (sum' [] bs (b + partial) (toGo-1)))\nsum' ((_,a):as) [] partial toGo = show (a + partial) ++ (' ' : (sum' [] as (a + partial) (toGo-1)))\n\naddTo z start 0 = z\naddTo z start end = addTo (show(start)++(' ':z)) (start-1) (end-1)\n\t\nbuildStack switchA switchB a b n m firstA \n\t| switchA > switchB = stack a b n (n+m) []\n\t| switchB > switchA = stack b a (n+m) n []\n\t| firstA==0 = stack a b n (n+m) []\n\t| otherwise = stack b a (n+m) n []\n\t\nstack [] [] n m z = z\nstack ((a,b):xs) [] n m z = stack xs [] (n-b) m (addTo z n b)\nstack [] ((a,b):ys) n m z = stack [] ys n (m-b) (addTo z m b)\nstack ((a,b):xs) (y:ys) n m z = stack (y:ys) xs m (n-b) (addTo z n b) \n\nsolve n m firstDeck secondDeck =\n\tlet \n\t\t(a,switchA) = countSwitch firstDeck [] n\n\t\t(b,switchB) = countSwitch secondDeck [] m\n\tin \n\t\tlet \n\t\t\t((firstA,_):as) = a\n\t\t\t((firstB,_):bs) = b\n\t\tin\n\t\t\tdo\n\t\t\t\tprint a\n\t\t\t\tprint b\n\t\t\t\tBS.writeFile \"output.txt\" $ (BSC.pack ((buildStack switchA switchB a b n m firstA) ++ \"\\n\" ++ (countTurns switchA switchB firstA firstB a b)))\n\nmain = \n do \n all <- BS.readFile \"input.txt\"\n let Just (n, r1) = readInteger all\n let (firstDeck, r2) = readMany n readInteger r1\n let Just (m, r3) = readInteger r2\n let (secondDeck, _) = readMany m readInteger r3\n solve n m firstDeck secondDeck\n --print \"hi\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany 0 _ s = ([], s)\n readMany n readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany (n-1) readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}], "src_uid": "f1a312a21d600cf9cfff4afeca9097dc"} {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Function\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntegers :: IO [Integer]\nreadIntegers = map (fst . fromJust . B.readInteger) . B.words <$> B.getLine\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\napply (s,ans) ('L',x)\n | s - x > 0 = (s-x, ('R':ans))\n | otherwise = (s+x, ('L':ans))\napply (s,ans) ('R',x)\n | s + x < 0 = (s+x, ('L':ans))\n | otherwise = (s-x, ('R':ans))\n\nparts (d:ds) bs (g:gs) =\n let z = length d\n (b1,b2) = splitAt (z-1) bs\n in (g:b1) : parts ds b2 gs\nparts _ _ _ = []\n\nmain = do\n [n] <- readInts\n arr <- readIntegers\n expdir <- getLine\n let sorted = sort arr\n blocks = group expdir\n k = length blocks\n (bads, goods) = splitAt (n-k) sorted\n order = parts blocks (reverse bads) goods\n greedy = zip expdir $ concat order\n dirs = reverse $ snd $ foldl' apply (0,\"\") greedy\n forM_ (zip dirs greedy) $ \\(d,(_,x)) -> do\n putStrLn $ show x ++ [' ', d]\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Function\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\napply (s,ans) ('L',x)\n | s - x > 0 = (s-x, ('R':ans))\n | otherwise = (s+x, ('L':ans))\napply (s,ans) ('R',x)\n | s + x < 0 = (s+x, ('L':ans))\n | otherwise = (s-x, ('R':ans))\n\nparts (d:ds) bs (g:gs) =\n let z = length d\n (b1,b2) = splitAt (z-1) bs\n in (g:b1) : parts ds b2 gs\nparts _ _ _ = []\n\nmain = do\n [n] <- readInts\n arr <- readInts\n expdir <- getLine\n let sorted = sort arr\n blocks = group expdir\n k = length blocks\n (bads, goods) = splitAt (n-k) sorted\n order = parts blocks (reverse bads) goods\n greedy = zip expdir $ concat order\n dirs = reverse $ snd $ foldl' apply (0,\"\") greedy\n forM_ (zip dirs greedy) $ \\(d,(_,x)) -> do\n putStrLn $ show x ++ [' ', d]\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Function\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntegers :: IO [Integer]\nreadIntegers = map (fst . fromJust . B.readInteger) . B.words <$> B.getLine\n\napply (sl,sr,ans) ('L',x)\n | sr + x < sl = (sl, sr+x, ('R':ans))\n | otherwise = (sl+x,sr, ('L':ans))\napply (sl,sr,ans) ('R',x)\n | sl + x < sr = (sl+x, sr, ('L':ans))\n | otherwise = (sl, sr+x, ('R':ans))\n\nmain = do\n getLine\n arr <- readIntegers\n expdir <- getLine\n let sorted = sort arr\n greedy = concat $ map reverse $ groupBy ((==) `on` fst) $ zip expdir sorted\n dirs = reverse $ (\\(_,_,x) -> x) $ foldl' apply (0,0,\"\") greedy\n forM_ (zip dirs greedy) $ \\(d,(_,x)) -> do\n putStrLn $ show x ++ [' ', d]"}], "src_uid": "c03face2b6e5736a401ebf61339fac3c"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\nimport Data.Array\n-- import Data.Array.ST\n-- import Data.Array.Unsafe\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nout = stdout\n\nmain = do\n n <- readInt1 <$> BS.getLine\n ss <- map readInt2 <$> replicateM n BS.getLine\n print $ solve ss\n\nsolve :: [(Int,Int)] -> Integer\nsolve ss = x + y - z where\n x = sum . map ((flip comb 2).fromIntegral.length) . group . sort . fst . unzip $ ss\n y = sum . map ((flip comb 2).fromIntegral.length) . group . sort . snd . unzip $ ss\n z = sum . map ((flip comb 2).fromIntegral.length) . group . sort $ ss\n\ncomb 1 r = 0\ncomb n r = iterate (scanl1 (+)) [1,1..] !! (n-r) !! r\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)\n\n-- output functions\n\ndata Cell = ByteStringC BL.ByteString\n | IntC Int\n | Int64C Int64\n deriving( Eq, Ord, Show )\n\ndata Row = ListR [Cell]\n | TupleR (Cell,Cell)\n | TripleR (Cell,Cell,Cell)\n deriving( Eq, Ord, Show )\n\ntype Table = [Row]\n\ninfixr 4 <>\n(<>) :: Monoid m => m -> m -> m\n(<>) = mappend\n\nputAns :: Handle -> Table -> IO ()\nputAns o = hPutBuilder o . renderTable\n\nrenderTable :: Table -> Builder\nrenderTable rs = mconcat [renderRow r <> char8 '\\n' | r <- rs]\n\nrenderRow :: Row -> Builder\nrenderRow (ListR []) = mempty\nrenderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]\nrenderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y\nrenderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z\n\nrenderCell :: Cell -> Builder\nrenderCell (ByteStringC cs) = lazyByteString cs\nrenderCell (IntC i) = intDec i\nrenderCell (Int64C i) = int64Dec i\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\ndata SP = SP{\n sfst::{-# UNPACK #-} !Int,\n ssnd:: {-# UNPACK #-} !Int\n}deriving (Eq, Ord)\n\ncountBy::Eq a=>(b->a)->[b]->Integer\ncountBy f = walk where\n walk (x:xs) = go x 1 0 xs\n walk [] = 0\n go _ _ acc [] = acc\n go y c acc (x:xs)\n | f x == f y = go x (c+1) (acc + c) xs\n | otherwise = go x 1 acc xs\n\nmain::IO ()\nmain = do\n n <-fmap read getLine\n let lsp [x,y] = SP x y\n lsp _ = undefined\n es <- replicateM n $ fmap (lsp .map read . words) getLine::IO [SP]\n let xs = sort es\n ys = sortBy (comparing ssnd) xs\n print (countBy sfst xs + countBy ssnd ys - countBy id xs)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\ndata SP = SP{\n sfst::{-# UNPACK #-} !Int,\n ssnd:: {-# UNPACK #-} !Int\n}deriving (Eq, Ord)\n\ndata ST a = ST !a {-# UNPACK #-} !Int Integer\n\ncountBy::Eq a=>(b->a)->[b]->Integer\ncountBy f = walk where\n thrd (ST _ _ x) = x\n walk (x:xs) = thrd $ foldl' go (ST x 1 0) xs\n walk [] = 0\n go (ST y c acc) x\n | f x == f y = ST x (c+1) (acc + fromIntegral c)\n | otherwise = ST x 1 acc\n\nmain::IO ()\nmain = do\n n <-fmap read getLine\n let lsp [x,y] = SP x y\n lsp _ = undefined\n es <- replicateM n $ fmap (lsp .map read . words) getLine::IO [SP]\n let xs = sort es\n ys = sortBy (comparing ssnd) xs\n print (countBy sfst xs + countBy ssnd ys - countBy id xs)\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Functor\nimport Data.Function (on)\nimport qualified Data.Map as Map\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO()\nmain = do\n _ <- getLine\n a <- readAllInts\n print $ solve $ selfZip a\n\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\n\nreadAllInts :: IO [Int]\nreadAllInts = map readInt . B.words <$> B.getContents\n\ncount :: [[a]] -> Integer\ncount a = sum $ map ((\\x -> x * (x - 1) `div` 2) . fromIntegral . length) a\n\nsolve :: [(Int, Int)] -> Integer\nsolve a = let sx = sort a\n sy = sortBy (compare `on` snd) a\n gx = groupBy ((==) `on` fst) sx\n gy = groupBy ((==) `on` snd) sy\n gxy = group sx\n cx = count gx\n cy = count gy\n cxy = count gxy\n in cx + cy - cxy\n\nselfZip :: [Int] -> [(Int, Int)]\nselfZip [] = []\nselfZip (a:b:s) = (a, b):selfZip s\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\nimport qualified Data.Map as M\n\ncomb2::Int->Integer\n\ncomb2 n = fromIntegral $ div ((fromIntegral n) * (fromIntegral (n-1)) ) 2\n\nprocess q= sum $ map comb2 $ filter (>1) $ I.elems $ I.fromListWith (+) $ zip q $ repeat 1\n\n\t \n\nmain=do\n\ts<- getLine\n\t[t1,t2]<- transpose. map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents ::IO [[Int]]\n\tlet n1 = process t1 + process t2 \n\tlet n2 = sum $ map comb2 $filter (>1) $ map length $ group $ sort (zip t1 t2)\n\tprint $ n1-n2"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport Data.Maybe\nimport Data.Function(on)\nimport Data.Tuple(swap)\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n _ <- readLn :: IO Int\n ps <- map l2p <$> readAllInts\n let count f = sum . \n map ((\\x -> x * (x-1) `div` 2) . fromIntegral . length) . \n groupBy ((==) `on` f) . \n sortBy (compare `on` f)\n let a,b,c :: Integer\n a = count fst ps\n b = count snd ps\n c = count id ps\n print $ a + b - c\n\n-- IO\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadAllInts :: IO [[Int]]\nreadAllInts = map (map readInt . B.words) . B.lines <$> B.getContents\n\n-- Utilities\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\nl2p _ = error \"l2p: the input list is too short\"\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Word\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\n -> print.solve =<< (forM [1..(fst.fromJust.C.readInt) n] $ \\ i -> C.getLine>>= \\js -> return $ map (fst.fromJust.C.readInt) $ C.words js)\nsolve:: [[Int]] -> Integer\nsolve xs = (+) (slv1 xs) $ sum $ map (\\a->comb2 $ fromIntegral $ length a) $ groupBy (\\a b ->(head a) == (head b)) $ sortBy (\\ a b -> (head a) `compare` (head b)) xs\nslv1 xs = let ys= groupBy (\\a b ->(last a) == (last b)) $ sortBy (\\ a b -> (last a) `compare` (last b)) xs;\n zs = map ( \\ as -> groupBy (\\a b ->(head a) == (head b)) $ sortBy (\\ a b -> (head a) `compare` (head b)) as ) ys in sum (map (\\a->comb2 $ fromIntegral $ length a) ys) - sum (map (\\ as-> sum $ map (\\a->comb2 $ fromIntegral $ length a) as) zs)\ncomb2 x = (x*(x-1)) `div` 2"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\ncountBy::Eq a=>(b->a)->[b]->Integer\ncountBy f = walk where\n walk (x:xs) = go x 1 0 xs\n walk [] = 0\n go _ _ acc [] = acc\n go y c acc (x:xs)\n | f x == f y = go x (c+1) (acc + c) xs\n | otherwise = go x 1 acc xs\n\nmain::IO ()\nmain = do\n n <-fmap read getLine\n let m = 2^(31::Int)\n lsp [x,y] = x*m+y\n lsp _ = undefined\n sfst x = div x m\n ssnd x = mod x m\n es <- replicateM n $ fmap (lsp .map read . words) getLine::IO [Int]\n let xs = sort es\n ys = sortBy (comparing ssnd) es\n print (countBy sfst xs + countBy ssnd ys - countBy id xs)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.Int\n\ncountBy::Eq a=>(b->a)->[b]->Integer\ncountBy f = walk where\n walk (x:xs) = go x 1 0 xs\n walk [] = 0\n go _ _ acc [] = acc\n go y c acc (x:xs)\n | f x == f y = go x (c+1) (acc + c) xs\n | otherwise = go x 1 acc xs\n\nmain::IO ()\nmain = do\n n <-fmap read getLine\n let m = 2^(31::Int)\n lsp [x,y] = x*m+y\n lsp _ = undefined\n sfst x = div x m\n ssnd x = mod x m\n es <- replicateM n $ fmap (lsp .map read . words) getLine::IO [Int64]\n let xs = sort es\n ys = sortBy (comparing ssnd) es\n print (countBy sfst xs + countBy ssnd ys - countBy id xs)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\nimport Data.Array\n-- import Data.Array.ST\n-- import Data.Array.Unsafe\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nout = stdout\n\nmain = do\n n <- readInt1 <$> BS.getLine\n ss <- map readInt2 <$> replicateM n BS.getLine\n print $ solve ss\n\nsolve :: [(Int,Int)] -> Int\nsolve ss = x + y - z where\n x = sum . map ((flip comb 2).length) . group . sort . fst . unzip $ ss\n y = sum . map ((flip comb 2).length) . group . sort . snd . unzip $ ss\n z = sum . map ((flip comb 2).length) . group . sort $ ss\n\ncomb 1 r = 0\ncomb n r = iterate (scanl1 (+)) [1,1..] !! (n-r) !! r\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)\n\n-- output functions\n\ndata Cell = ByteStringC BL.ByteString\n | IntC Int\n | Int64C Int64\n deriving( Eq, Ord, Show )\n\ndata Row = ListR [Cell]\n | TupleR (Cell,Cell)\n | TripleR (Cell,Cell,Cell)\n deriving( Eq, Ord, Show )\n\ntype Table = [Row]\n\ninfixr 4 <>\n(<>) :: Monoid m => m -> m -> m\n(<>) = mappend\n\nputAns :: Handle -> Table -> IO ()\nputAns o = hPutBuilder o . renderTable\n\nrenderTable :: Table -> Builder\nrenderTable rs = mconcat [renderRow r <> char8 '\\n' | r <- rs]\n\nrenderRow :: Row -> Builder\nrenderRow (ListR []) = mempty\nrenderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]\nrenderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y\nrenderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z\n\nrenderCell :: Cell -> Builder\nrenderCell (ByteStringC cs) = lazyByteString cs\nrenderCell (IntC i) = intDec i\nrenderCell (Int64C i) = int64Dec i\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\nimport qualified Data.Map as M\n\ncomb2 n = div (n*(n-1)) 2\n\nprocess q= sum $ map comb2 $ filter (>1) $ I.elems $ I.fromListWith (+) $ zip q $ repeat 1\n\n\t \n\nmain=do\n\ts<- getLine\n\t[t1,t2]<- transpose. map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents ::IO [[Int]]\n\tlet n1 = process t1 + process t2 \n\tlet n2 = sum $ map comb2 $filter (>1) $ map length $ group $ sort (zip t1 t2)\n\tprint $ n1-n2"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\nimport qualified Data.Map as M\n\ncomb2::Int->Integer\n\ncomb2 n = fromIntegral (div (n*(n-1)) 2)\n\nprocess q= sum $ map comb2 $ filter (>1) $ I.elems $ I.fromListWith (+) $ zip q $ repeat 1\n\n\t \n\nmain=do\n\ts<- getLine\n\t[t1,t2]<- transpose. map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents ::IO [[Int]]\n\tlet n1 = process t1 + process t2 \n\tlet n2 = sum $ map comb2 $filter (>1) $ map length $ group $ sort (zip t1 t2)\n\tprint $ n1-n2"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\n -> putStrLn.solve =<< (forM [1..(fst.fromJust.C.readInt) n] $ \\ i -> C.getLine>>= \\js -> return $ map (fst.fromJust.C.readInt) $ C.words js)\nsolve xs = show $ (+) (slv1 xs) $ sum $ map (\\a->comb2 $ length a) $ groupBy (\\a b ->(head a) == (head b)) $ sortBy (\\ a b -> (head a) `compare` (head b)) xs\nslv1 xs = let ys= groupBy (\\a b ->(last a) == (last b)) $ sortBy (\\ a b -> (last a) `compare` (last b)) xs;\n zs = map ( \\ as -> groupBy (\\a b ->(head a) == (head b)) $ sortBy (\\ a b -> (head a) `compare` (head b)) as ) ys in sum (map (\\a->comb2 $ length a) ys) - sum (map (\\ as-> sum $ map (\\a->comb2 $ length a) as) zs)\ncomb2 x = (x*(x-1)) `div` 2"}], "src_uid": "bd7b85c0204f6b36dc07f8a96fc36161"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.IO\nimport qualified Data.Array.MArray as M\nimport qualified Data.Array.IArray as I\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Data.Int\n\n{-\nu x = head [ p | p <- [x,x-1..], P.isPrime p ]\nv x = head [ p | p <- [x+1..], P.isPrime p ]\nsolve = scanl (+) 0 [ 1 % (u(x)*v(x)) | x <- [2..] ]\n-}\n\nisPrime primes n = all (\\p -> n `mod` p /= 0) $ takeWhile ( a -> Int\nisqrt n = floor $ sqrt ((fromIntegral n) :: Double)\n\nsieve arr = do\n (_,hi) <- getBounds arr\n let maxi = isqrt hi\n forM_ [2..maxi] $ \\i -> do\n v <- readArray arr i\n if v == 0\n then let v = i*i in forM_ [v,v+i..hi] $ \\j -> writeArray arr j (fromIntegral i)\n else return ()\n\ngenPrimes :: Integral a => Int -> IO [a]\ngenPrimes n = do\n parr' <- newArray (2,n) 0 :: IO (IOUArray Int Int)\n sieve parr'\n parr <- M.freeze parr' :: IO (UArray Int Int)\n let primes = map (fromIntegral.fst) $ filter (\\(i,v) -> v == 0) $ I.assocs parr\n return primes\n\ntest = do\n primes <- genPrimes 100 :: IO [Int]\n return $ all (isPrime primes) [2,3,5,7,11,13]\n\nmain = do\n primes <- genPrimes 32000 :: IO [Int]\n n <- fmap read getLine\n replicateM_ n $ do\n x <- fmap read getLine\n let (a,b) = solve' primes x\n putStrLn $ show a ++ \"/\" ++ show b\n\n", "positive_code": [{"source_code": "f::Integer->Integer->Bool\nf d n\n |n[String]\nf2 []=[]\nf2 (2:xs)=\"1/6\":f2 xs\nf2 (3:xs)=\"7/30\":f2 xs\nf2 (4:xs)=\"3/10\":f2 xs\nf2 (x:xs)=let p1=head $ [t0|t0<-[x,(x-1)..1],f 2 t0]\n p2=head $ [t1|t1<-[(x+1)..],f 2 t1]\n u1=p1-2\n d1=p1*2\n u2=x-p1+1\n d2=p1*p2\n u3=u1*d2+u2*d1\n d3=d1*d2\n t=(gcd u3 d3)\n in ((show (u3 `div` t))++\"/\"++(show (d3 `div` t))):(f2 xs)\n\nmain = do\n e<-getLine\n es<-getContents\n let xs=map read (lines es)::[Integer]\n mapM_ putStrLn $ f2 xs"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.IO\nimport qualified Data.Array.MArray as M\nimport qualified Data.Array.IArray as I\nimport Data.Array.Unboxed\nimport Control.Monad\n\n{-\nu x = head [ p | p <- [x,x-1..], P.isPrime p ]\nv x = head [ p | p <- [x+1..], P.isPrime p ]\nsolve = scanl (+) 0 [ 1 % (u(x)*v(x)) | x <- [2..] ]\n-}\n\nisPrime primes n = all (\\p -> n `mod` p /= 0) $ takeWhile ( a -> Int\nisqrt n = floor $ sqrt ((fromIntegral n) :: Double)\n\nsieve arr = do\n (_,hi) <- getBounds arr\n let maxi = isqrt hi\n forM_ [2..maxi] $ \\i -> do\n v <- readArray arr i\n if v == 0\n then let v = i*i in forM_ [v,v+i..hi] $ \\j -> writeArray arr j (fromIntegral i)\n else return ()\n\ngenPrimes :: Integral a => Int -> IO [a]\ngenPrimes n = do\n parr' <- newArray (2,n) 0 :: IO (IOUArray Int Int)\n sieve parr'\n parr <- M.freeze parr' :: IO (UArray Int Int)\n let primes = map (fromIntegral.fst) $ filter (\\(i,v) -> v == 0) $ I.assocs parr\n return primes\n\ntest = do\n primes <- genPrimes 100 :: IO [Int]\n return $ all (isPrime primes) [2,3,5,7,11,13]\n\nmain = do\n primes <- genPrimes 32000 :: IO [Int]\n n <- fmap read getLine\n replicateM_ n $ do\n x <- fmap read getLine\n let (a,b) = solve' primes x\n putStrLn $ show a ++ \"/\" ++ show b\n\n"}], "src_uid": "f4c743af8e8a1f90b74a27ca9bbc8b7b"} {"source_code": "module Main (f, main) where\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Function (on, (&))\r\nimport Data.List (groupBy)\r\n\r\n\r\nf [s, [c]] | length s & odd = c `elem` (takeEvenIndices s)\r\nf _ = False\r\n\r\ntakeEvenIndices = takeIndicesWhich even\r\ntakeIndicesWhich predicate = enumerate >>> filter (fst >>> predicate) >>> unenumerate\r\n\r\n\r\nmain = interact $ lines >>> drop 1 >>> chunksOf 2 >>> map (f >>> boolToYesNo) >>> unlines\r\n\r\nboolToYesNo p = if p then \"YES\" else \"NO\"\r\n\r\ngroupByKey = ((==) `on`) >>> groupBy\r\nchunksOf n = enumerate >>> groupByKey (fst >>> (`div` n)) >>> map unenumerate\r\n\r\nenumerate = zip [0..]\r\nunenumerate = map snd\r\n", "positive_code": [{"source_code": "main=interact$unlines.map f.t.tail.lines\r\nf[s,[c]]=b$elem c$map head$t s\r\nt[]=[]\r\nt(a:b:s)=[a,b]:t s\r\nt x=[x]\r\nb x|x=\"YES\"\r\nb _=\"NO\""}, {"source_code": "import Data.List ( sort )\r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (y:z:xs) = func y z : solve xs\r\n\r\nfunc :: String -> String -> String\r\nfunc y z = if poss y z then \"YES\" else \"NO\"\r\n\r\nposs :: String -> String -> Bool\r\nposs xs y\r\n | length xs == 1 = head xs == head y\r\n | head xs == head y = True\r\n | otherwise = poss (tail (tail xs)) y\r\n\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = (Char, String)\r\ntype OutType = Bool\r\n\r\nsolve :: InType -> OutType\r\nsolve (c, s) = c `elem` oddPos s\r\n where oddPos [] = []\r\n oddPos [a] = [a]\r\n oddPos (a : b : t) = a : oddPos t\r\n\r\nreceive :: [String] -> InType\r\nreceive [s, c] = (head c, s)\r\nreceive _ = error \"input error\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showB . solve . receive) . chunksOf 2 . tail . lines\r\n where showB False = \"No\"\r\n showB True = \"Yes\"\r\n"}], "negative_code": [], "src_uid": "c569b47cf80dfa98a7105e246c3c1e01"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE TupleSections #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\nsolve2 :: [Int] -> [Int] -> Int -> Int -> Int\r\nsolve2 ls rs ln rn =\r\n let t = min ((rn-ln) `div` 2) $ sum (map (`div` 2) rs)\r\n in\r\n ln + (rn-ln) - t\r\n\r\nsolve :: [Int] -> [Int] -> Int\r\nsolve ls rs =\r\n let ln = sum ls\r\n rn = sum rs\r\n in\r\n if ln < rn then\r\n solve2 ls rs ln rn\r\n else\r\n solve2 rs ls rn ln\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n [n,ln,rn] <- map parseInt . BS.words <$> BS.getLine\r\n cs <- map parseInt . BS.words <$> BS.getLine\r\n let (ls,rs) = splitAt ln cs\r\n qa = accumArray (+) 0 (1,n) $ map (,1) ls ++ map(,-1) rs :: UArray Int Int\r\n qs = elems qa\r\n l = filter (>0) qs\r\n r = map abs $ filter (<0) qs\r\n print $ solve l r\r\n ", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nctArr :: Int -> [Int] -> UArray Int Int\nctArr n vs = accumArray (\\v _ -> v+1) 0 (1, n) $ zip vs $ repeat ()\n\nstep :: (Int, Int, Int) -> (Int, Int) -> (Int, Int, Int)\nstep (!psave, !lsave, !rsave) (lct, rct)\n = (psave + min lct rct,\n lsave + div (max 0 $ lct - rct) 2,\n rsave + div (max 0 $ rct - lct) 2)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, lc, rc] <- readInts\n (lvs, rvs) <- splitAt lc <$> readInts\n let\n lcts = ctArr n lvs\n rcts = ctArr n rvs\n (psave, lsave, rsave) = foldl' step (0, 0, 0)\n $ zip (elems lcts) (elems rcts)\n qsave = if lc >= rc\n then min lsave $ div (lc - rc) 2\n else min rsave $ div (rc - lc) 2\n -- Worst case, we need n spent (2 for each pair)\n -- but we save one orientation-change for each less-common sock existing\n -- one color change for each already-matching pair\n -- and one more color change for each color-matching pair left over\n -- among the more common orientation\n putInts [n - psave - qsave - min lc rc]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "a2d4f0182456cedbe85dff97ec0f477e"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = readInt >>= flip replicateM getLine >>= putStrLn . which \"YES\" \"NO\" . solve\n\nsolve rows = runST $ do\n\tlet\n\t\tn = length rows\n\tboard <- newListArray ( ( 0, 0 ), ( n - 1, n - 1 ) ) ( concat rows ) :: ST s ( STUArray s ( Int, Int ) Char )\n\tres <- newSTRef True\n\tcnt <- newSTRef 0\n\tforM_ [ 0 .. n - 1 ] $ \\y -> do\n\t\tforM_ [ 0 .. n - 1 ] $ \\x -> do\n\t\t\tfound <- ( '.' == ) <$> readArray board ( y, x )\n\t\t\twhen found $ do\n\t\t\t\tforM_ ( zip [ 0, 1, 1, 1, 2 ] [ 0, -1, 0, 1, 0 ] ) $ \\( dy, dx ) -> do\n\t\t\t\t\tlet\n\t\t\t\t\t\tny = y + dy\n\t\t\t\t\t\tnx = x + dx\n\t\t\t\t\t\toutside = not ( 0 <= ny && ny < n && 0 <= nx && nx < n )\n\t\t\t\t\twhen outside $ do\n\t\t\t\t\t\twriteSTRef res False\n\t\t\t\t\t\tmodifySTRef cnt succ\n\t\t\t\t\twhen ( not outside ) $ do\n\t\t\t\t\t\tfailed <- ( '#' == ) <$> readArray board ( ny, nx )\n\t\t\t\t\t\tif failed\n\t\t\t\t\t\t\tthen writeSTRef res False\n\t\t\t\t\t\t\telse writeArray board ( ny, nx ) '#'\n\treadSTRef res", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\n\ntype Field = M.Map (Int, Int) Char\n\nnewState :: Int -> Maybe Field -> Maybe Field\nnewState n mf = mf >>= newState' n\n\nnewState' :: Int -> Field -> Maybe Field\nnewState' n f\n | null free\n = Nothing\n | x == 0 || x == n - 1 || y == n - 2 || y == n - 1\n = Nothing\n | elem '#'\n $ map (f M.!) [(y + 1, x - 1), (y + 1, x), (y + 1, x + 1), (y + 2, x)]\n = Nothing\n | otherwise\n = Just\n $ M.insert (y , x) '#'\n $ M.insert (y + 1, x - 1) '#'\n $ M.insert (y + 1, x) '#'\n $ M.insert (y + 1, x + 1) '#'\n $ M.insert (y + 2, x) '#' f\n where\n free = M.toList $ M.filter (== '.') f\n ((y, x), _):_ = free\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n field <-\n M.fromList\n . concatMap (\\(i, xs) -> zip (map ((,) i) [0 ..]) xs)\n . zip [0 ..]\n <$> replicateM n getLine :: IO (M.Map (Int, Int) Char)\n let Just f = last $ takeWhile isJust $ iterate (newState n) (Just field)\n putStrLn $ if M.null (M.filter (== '.') f) then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n var <- A.newListArray ((1,1),(n,n)) =<< map (=='#') . concat\n <$> replicateM n getLine :: IO (IOUArray (Int,Int) Bool)\n ans_Mid <- foldr\n (\\ !x contx -> do\n vx1n <- liftA2 (&&) (rdA var (x,1)) (rdA var (x,n))\n if not vx1n then return False else do\n foldr\n (\\ !y conty -> do\n vxy <- rdA var (x,y)\n if vxy then conty else do\n rest <- or . map fst <$> mapM (mdA' var (const True))\n [(x+1,y-1),(x+1,y),(x+1,y+1),(x+2,y)]\n if rest then return False else conty)\n contx\n [2..n-1])\n (return True)\n [1..n-2]\n if not ans_Mid then putStrLn \"NO\" else do\n ans <- foldr (\\ !xy cont -> do\n vxy <- rdA var xy\n if vxy then cont else return False)\n (return True)\n [(x,y) | x<-[n-1,n], y <- [1..n]]\n putStrLn $ if ans then \"YES\" else \"NO\"\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n var <- A.newListArray ((1,1),(n,n)) =<< map (=='#') . concat\n <$> replicateM n getLine :: IO (IOUArray (Int,Int) Bool)\n forM_ [1..n-2] $ \\ !x -> do\n vx1n <- and <$> mapM (rdA var) [(x,1),(x,n)]\n unless vx1n $ reply False\n forM_ [2..n-1] $ \\ !y -> do\n vxy <- rdA var (x,y)\n unless vxy $ do\n vrest <- or . map fst <$> mapM (mdA' var $ const True)\n [(x+1,y-1),(x+1,y),(x+1,y+1),(x+2,y)]\n when vrest $ reply False\n forM_ [(x,y) | x<-[n-1,n], y <- [1..n]] $ \\ !xy -> do\n vxy <- rdA var xy\n unless vxy $ reply False\n reply True\n where\n reply !b = do putStrLn $ if b then \"YES\" else \"NO\"\n exitSuccess\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\n\ntype Field = M.Map (Int, Int) Char\n\nnewState :: Int -> Maybe Field -> Maybe Field\nnewState n mf = mf >>= newState' n\n\nnewState' :: Int -> Field -> Maybe Field\nnewState' n f\n | null free\n = Nothing\n | x == 0 || x == n - 1 || y == n - 2 || y == n - 1\n = Nothing\n | otherwise\n = Just\n $ M.insert (y , x) '#'\n $ M.insert (y + 1, x - 1) '#'\n $ M.insert (y + 1, x) '#'\n $ M.insert (y + 1, x + 1) '#'\n $ M.insert (y + 2, x) '#' f\n where\n free = M.toList $ M.filter (== '.') f\n ((y, x), _):_ = free\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n field <-\n M.fromList\n . concatMap (\\(i, xs) -> zip (map ((,) i) [0 ..]) xs)\n . zip [0 ..]\n <$> replicateM n getLine :: IO (M.Map (Int, Int) Char)\n let Just f = last $ takeWhile isJust $ iterate (newState n) (Just field)\n putStrLn $ if M.null (M.filter (== '.') f) then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n var <- A.newListArray ((1,1),(n,n)) =<< map (=='#') . concat\n <$> replicateM n getLine :: IO (IOUArray (Int,Int) Bool)\n ans_Mid <- foldr\n (\\ !x contx -> do\n vx1n <- liftA2 (&&) (rdA var (x,1)) (rdA var (x,n))\n if not vx1n then return False else do\n foldr\n (\\ !y conty -> do\n vxy <- rdA var (x,y)\n if vxy then conty else do\n rest <- or . map fst <$> mapM (mdA' var (const True))\n [(x+1,y-1),(x+1,y),(x+1,y+1),(x+2,y)]\n if rest then return False else conty)\n contx\n [2..n-1])\n (return True)\n [1..n-2]\n if not ans_Mid then putStrLn \"NO\" else do\n ans <- foldr (\\ !xy cont -> do\n vxy <- rdA var xy\n if vxy then cont else return False)\n (return True)\n [(x,y) | x<-[n-1,n], y <- [1..n-1]]\n putStrLn $ if ans then \"YES\" else \"NO\"\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "src_uid": "cc1feee94617c0cba1c528a0cb3952a8"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n cs <- fmap (map read . words) getLine :: IO [Int64]\n ids <- getInts\n\n let\n a = listArray (1, length cs) cs :: Array Int Int64\n s = sum cs\n\n b = accumArray (flip const) True (1, length cs) $ zip ids (repeat False) :: Array Int Bool\n\n cs' = map (a!) ids\n s1 = sum $ zipWith (*) cs' $ map (s-) $ scanl1 (+) cs'\n s2 = sum $ map (\\(i, j) -> a!i * a!j) $ filter (\\(i,j) -> b!i && b!j) $ [(i, i`mod`n + 1) | i <- [1..n]]\n\n print $ s1 + s2\n", "positive_code": [{"source_code": "import Data.Array\nimport qualified Data.IntSet as S\nsolve :: [Integer] -> [Int] -> Integer\nsolve cvs ids = cproads + circroute \n where n = length cvs \n cv = listArray (1, n) cvs\n idset = S.fromList ids\n cproads = let cp = map (cv !) ids in sum $ zipWith (*) cp (tail $ scanl (-) (sum cvs) cp)\n circroute = sum $ zipWith (\\x y -> if (S.notMember x idset && S.notMember y idset) then cv ! x * cv ! y else 0) (n : [1..n-1]) [1..n] \nmain = do _ <- getLine\n x <- getLine\n y <- getLine\n putStrLn (show $ solve (map read $ words x) (map read $ words y))"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as L\n\n\ntype Tokenizer = State [L.ByteString]\n\ndata City = City { charm :: Integer\n , capital :: Bool\n } deriving (Show, Eq)\n\nmkCities :: [Int] -> [Int] -> [City]\nmkCities cs is = go 1 cs is\n where go _ [] [] = []\n go i (c:cs) [] = (City (fromIntegral c) False) : go (i + 1) cs []\n go i (c:cs) jss@(j:js) | i == j = (City c' True) : go (i + 1) cs js\n | otherwise = (City c' False) : go (i + 1) cs jss\n where c' = fromIntegral c\n\ngetWeight :: City -> City -> City -> Integer -> Integer -> Integer\ngetWeight (City c True) _ _ all _ = (all - c) * c\ngetWeight (City c False) (City lw lc) (City rw rc) _ capitals | lc && rc = c * capitals\n | lc && (not rc) = c * (capitals + rw)\n | (not lc) && rc = c * (capitals + lw)\n | otherwise = c * (capitals + lw + rw)\n\nsolve :: [Int] -> [Int] -> Integer\nsolve cs is = (go cities (last cities : cities) (tail cities ++ [head cities]) 0) `div` 2\n where cities = mkCities cs is\n all = sum $ map charm cities\n capitals = sum . map charm $ filter capital cities\n\n go [] _ _ result = result\n go (c:cs) (p:ps) (n:ns) result = go cs ps ns (result + getWeight c p n all capitals)\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int: \" ++ (show s)\n\ngo :: Tokenizer Integer\ngo = do\n n <- nextInt\n k <- nextInt\n cs <- replicateM n nextInt\n is <- replicateM k nextInt\n return $ solve cs is\n\nmain :: IO ()\nmain = do\n input <- liftM L.words L.getContents\n let result = evalState go input\n print result\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as L\n\n\ntype Tokenizer = State [L.ByteString]\n\ndata City = City { charm :: Integer\n , capital :: Bool\n } deriving (Show, Eq)\n\nmkCities :: [Int] -> [Int] -> [City]\nmkCities cs is = go 1 cs is\n where go _ [] [] = []\n go i (c:cs) [] = (City (fromIntegral c) False) : go (i + 1) cs []\n go i (c:cs) jss@(j:js) | i == j = (City c' True) : go (i + 1) cs js\n | otherwise = (City c' False) : go (i + 1) cs jss\n where c' = fromIntegral c\n\ngetWeight :: City -> City -> City -> Integer -> Integer -> Integer\ngetWeight (City c True) _ _ all _ = (all - c) * c\ngetWeight (City c False) (City lw lc) (City rw rc) _ capitals | lc && rc = c * capitals\n | lc && (not rc) = c * (capitals + rw)\n | (not lc) && rc = c * (capitals + lw)\n | otherwise = c * (capitals + lw + rw)\n\nsolve :: [Int] -> [Int] -> Integer\nsolve cs is = (go cities (last cities : cities) (tail cities ++ [head cities]) 0) `div` 2\n where cities = mkCities cs is\n all = sum $ map charm cities\n capitals = sum . map charm $ filter capital cities\n\n go [] _ _ result = result\n go (c:cs) (p:ps) (n:ns) result = go cs ps ns (result + getWeight c p n all capitals)\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int: \" ++ (show s)\n\ngo :: Tokenizer Integer\ngo = do\n n <- nextInt\n k <- nextInt\n cs <- replicateM n nextInt\n is <- replicateM k nextInt\n return $ solve cs is\n\nmain :: IO ()\nmain = do\n input <- liftM L.words L.getContents\n let result = evalState go input\n print result\n"}, {"source_code": "import Data.Maybe\nimport Data.Array\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.IntSet as Set\n--import Debug.Trace\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n [n,k] <- getInts\n costs <- getInts\n capitals <- getInts\n let costs' = listArray (1,n) costs\n let totalCost = sum (map fromIntegral costs) :: Integer\n let capitalTotalCost = sum (map (\\i -> fromIntegral (costs' ! i)) capitals) :: Integer\n let capitalSet = foldl addCapital Set.empty capitals\n print $ solve n k costs' capitalSet totalCost capitalTotalCost\n\naddCapital set capital = Set.insert capital set\n\nsolve n k costs capitals totalCost capitalTotalCost = (f [1..n] (0::Integer)) `div` 2 where\n f [] acc = acc\n f (i:is) acc\n | Set.member i capitals = f is (acc + (ci * (totalCost - ci)))\n | otherwise = f is acc'\n where\n acc' = acc + fromIntegral (ci * (cnext + cprev + capitals'))\n ci = fromIntegral (costs ! i) :: Integer\n capitals' = capitalTotalCost - nextSub - prevSub\n i_next = if i == n then 1 else i + 1\n i_prev = if i == 1 then n else i - 1\n cnext = fromIntegral (costs ! i_next) :: Integer\n cprev = fromIntegral (costs ! i_prev) :: Integer\n nextSub = if Set.member i_next capitals then cnext else 0\n prevSub = if Set.member i_prev capitals then cprev else 0"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.IntSet as Set\n--import Debug.Trace\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n [n,k] <- getInts\n costs <- getInts\n capitals <- getInts\n let costs' = listArray (1,n) costs\n let totalCost = sum costs\n let capitalTotalCost = sum (map (\\i -> costs' ! i) capitals)\n let capitalSet = foldl addCapital Set.empty capitals\n print $ solve n k costs' capitalSet totalCost capitalTotalCost\n\naddCapital set capital = Set.insert capital set\n\nsolve n k costs capitals totalCost capitalTotalCost = (f [1..n] (0::Int64)) `div` 2 where\n f [] acc = acc\n f (i:is) acc\n | Set.member i capitals = f is (acc + fromIntegral (ci * (totalCost - ci)))\n | otherwise = f is acc'\n where\n acc' = acc + fromIntegral (ci * (cnext + cprev + capitals'))\n ci = costs ! i\n capitals' = capitalTotalCost - nextSub - prevSub\n i_next = if i == n then 1 else i + 1\n i_prev = if i == 1 then n else i - 1\n cnext = costs ! i_next\n cprev = costs ! i_prev\n nextSub = if Set.member i_next capitals then cnext else 0\n prevSub = if Set.member i_prev capitals then cprev else 0"}, {"source_code": "import Data.Maybe\nimport Data.Array\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.IntSet as Set\n--import Debug.Trace\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n [n,k] <- getInts\n costs <- getInts\n capitals <- getInts\n let costs' = listArray (1,n) costs\n let totalCost = sum costs\n let capitalTotalCost = sum (map (\\i -> costs' ! i) capitals)\n let capitalSet = foldl addCapital Set.empty capitals\n print $ solve n k costs' capitalSet totalCost capitalTotalCost\n\naddCapital set capital = Set.insert capital set\n\nsolve n k costs capitals totalCost capitalTotalCost = (f [1..n] 0) `div` 2 where\n f [] acc = acc\n f (i:is) acc\n | Set.member i capitals = f is (acc + ci * (totalCost - ci))\n | otherwise = f is acc'\n where\n acc' = acc + ci * (cnext + cprev + capitals')\n ci = costs ! i\n capitals' = capitalTotalCost - nextSub - prevSub\n i_next = if i == n then 1 else i + 1\n i_prev = if i == 1 then n else i - 1\n cnext = costs ! i_next\n cprev = costs ! i_prev\n nextSub = if Set.member i_next capitals then cnext else 0\n prevSub = if Set.member i_prev capitals then cprev else 0"}], "src_uid": "bc6b8fda79c257e6c4e280d7929ed8a1"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeRead,unsafeWrite,unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep !n f = go 0\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !n !m f = go n\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n \nmain = do\n [n,m,_] <- map read.words <$> getLine\n (dists,stks) <- splitAt (m*n*n).map readInt.B.words <$> B.getContents\n\n d <- newListArray (0,m*n*n-1) dists :: IO (IOUArray Int Int)\n\n rep m $ \\i-> \n rep n $ \\x-> \n rep n $ \\s-> \n rep n $ \\t-> do\n dst <- unsafeRead d $ i*n*n+s*n+t\n dsx <- unsafeRead d $ i*n*n+s*n+x\n dxt <- unsafeRead d $ i*n*n+x*n+t\n unsafeWrite d (i*n*n+s*n+t) $ min dst $ dsx+dxt\n\n dist <- unsafeFreeze d :: IO (UArray Int Int)\n \n dp <- newArray (0,(n+1)*n*n-1) 60000000 :: IO (IOUArray Int Int)\n \n rep n $ \\s->\n rep n $ \\t-> do\n unsafeWrite dp (s*n+t) $! minimum [unsafeAt dist (car*n*n+s*n+t)|car<-[0..m-1]]\n\n for 1 (n+1) $ \\k-> \n rep n $ \\s-> \n rep n $ \\t-> \n rep n $ \\x-> do\n dst <- unsafeRead dp $ (k*n*n+s*n+t)\n dsx <- unsafeRead dp $ ((k-1)*n*n+s*n+x)\n dxt <- unsafeRead dp $ (x*n+t)\n unsafeWrite dp (k*n*n+s*n+t) $ min dst $ dsx+dxt\n\n ans <- unsafeFreeze dp :: IO (UArray Int Int)\n\n let solve :: [Int] -> String\n solve [] = []\n solve (s:t:k:stks) = shows(unsafeAt ans(min n k*n*n+(s-1)*n+t-1))\"\\n\" ++ solve stks\n\n putStr $ solve stks", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep !n f=go 1 where go !i=when(i<=n)$f i>>go(i+1)\n\nreadInt s = case B.readInt s of Just (n,_) -> n\n\nmain = do\n [n,m,_] <- map read.words <$> getLine\n (dists,stks) <- splitAt (m*n*n).map readInt.B.words <$> B.getContents\n\n d <- newListArray ((1,1,1),(m,n,n)) dists :: IO (IOUArray (Int,Int,Int) Int)\n \n rep m $ \\i-> \n rep n $ \\x-> \n rep n $ \\s-> \n rep n $ \\t-> do\n dst <- readArray d (i,s,t)\n dsx <- readArray d (i,s,x)\n dxt <- readArray d (i,x,t)\n writeArray d (i,s,t) $ min dst (dsx+dxt)\n\n dist <- unsafeFreeze d :: IO (UArray (Int,Int,Int) Int)\n\n dp <- newArray ((0,1,1),(n,n,n)) 60000000 :: IO (IOUArray (Int,Int,Int) Int)\n \n rep n $ \\s->\n rep n $ \\t->\n writeArray dp (0,s,t) $ minimum [dist!(car,s,t)|car<-[1..m]]\n \n rep n $ \\k-> \n rep n $ \\s-> \n rep n $ \\t-> \n rep n $ \\x-> do\n dst <- readArray dp (k,s,t)\n dsx <- readArray dp (k-1,s,x)\n dxt <- readArray dp (0,x,t)\n writeArray dp (k,s,t) $ min dst (dsx+dxt)\n\n ans <- unsafeFreeze dp :: IO (UArray (Int,Int,Int) Int)\n\n let solve [] = []\n solve (s:t:k:stks) = shows(ans!(min n k,s,t))\"\\n\" ++ solve stks\n\n putStr $ solve stks\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -fvia-C -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeRead,unsafeWrite,unsafeAt)\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt s = case B.readInt s of\n Just (n,_) -> n\n\nmain = do\n [n,m,_] <- map read.words <$> getLine\n (disList,stks) <- splitAt (m*n*n).map readInt.B.words <$> B.getContents\n\n d <- newListArray (0,m*n*n-1) disList :: IO (IOUArray Int Int)\n\n let runFloyd :: Int -> Int -> Int -> Int -> IO ()\n runFloyd !i !x !s !t\n | t<=n-1 = step >> runFloyd i x s (t+1)\n | s Int -> IO ()\n runInit !s !t\n | t<=n-1 = step >> runInit s (t+1)\n | s Int -> Int -> Int -> IO ()\n runDP !k !s !t !x\n | x<=n-1 = step >> runDP k s t (x+1)\n | t String\n solve [] = []\n solve (s:t:k:stks) = shows(unsafeAt ans(min n k*n*n+(s-1)*n+t-1))\"\\n\" ++ solve stks\n\n putStr $ solve stks"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base hiding (readArray, writeArray, (!))\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Ix\nimport GHC.Arr (unsafeIndex)\n\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=case bounds a of lr->unsafeAt a$unsafeIndex lr i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep !s !t f=go s where go !i=when(i<=t)$f i>>go(i+1)\n{-# INLINE rep #-}\n\nreadInt s = case B.readInt s of Just (n,_) -> n\n\nmain = do\n [n,m,_] <- map read.words <$> getLine\n (dists,stks) <- splitAt (m*n*n).map readInt.B.words <$> B.getContents\n\n d <- newListArray ((1,1,1),(m,n,n)) dists :: IO (IOUArray (Int,Int,Int) Int)\n \n rep 1 m $ \\i-> \n rep 1 n $ \\x-> \n rep 1 n $ \\s-> \n rep 1 n $ \\t-> do\n dst <- readArray d (i,s,t)\n dsx <- readArray d (i,s,x)\n dxt <- readArray d (i,x,t)\n writeArray d (i,s,t) $ min dst (dsx+dxt)\n\n dist <- unsafeFreeze d :: IO (UArray (Int,Int,Int) Int)\n\n dp <- newArray ((0,1,1),(n,n,n)) 60000000 :: IO (IOUArray (Int,Int,Int) Int)\n \n rep 1 n $ \\s->\n rep 1 n $ \\t->\n writeArray dp (0,s,t) $ minimum [dist!(car,s,t)|car<-[1..m]]\n \n rep 1 n $ \\k-> \n rep 1 n $ \\s-> \n rep 1 n $ \\t-> \n rep 1 n $ \\x-> do\n dst <- readArray dp (k,s,t)\n dsx <- readArray dp (k-1,s,x)\n dxt <- readArray dp (0,x,t)\n writeArray dp (k,s,t) $ min dst (dsx+dxt)\n\n ans <- unsafeFreeze dp :: IO (UArray (Int,Int,Int) Int)\n\n let solve [] = []\n solve (s:t:k:stks) = shows(ans!(min n k,s,t))\"\\n\" ++ solve stks\n\n putStr $ solve stks"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base hiding (readArray, writeArray, (!))\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Ix\nimport GHC.Arr (unsafeIndex)\n\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=case bounds a of lr->unsafeAt a$unsafeIndex lr i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\n\nreadInt s = case B.readInt s of Just (n,_) -> n\n\nmain = do\n [n,m,_] <- map read.words <$> getLine\n (dists,stks) <- splitAt (m*n*n).map readInt.B.words <$> B.getContents\n\n d <- newListArray ((1,1,1),(m,n,n)) dists :: IO (IOUArray (Int,Int,Int) Int)\n \n forM_ [1..m] $ \\i-> \n forM_ [1..n] $ \\x-> \n forM_ [1..n] $ \\s-> \n forM_ [1..n] $ \\t-> do\n dst <- readArray d (i,s,t)\n dsx <- readArray d (i,s,x)\n dxt <- readArray d (i,x,t)\n writeArray d (i,s,t) $ min dst (dsx+dxt)\n\n dist <- unsafeFreeze d :: IO (UArray (Int,Int,Int) Int)\n\n dp <- newArray ((0,1,1),(n,n,n)) 60000000 :: IO (IOUArray (Int,Int,Int) Int)\n \n forM_ [1..n] $ \\s->\n forM_ [1..n] $ \\t->\n writeArray dp (0,s,t) $ minimum [dist!(car,s,t)|car<-[1..m]]\n \n forM_ [1..n] $ \\k-> \n forM_ [1..n] $ \\s-> \n forM_ [1..n] $ \\t-> \n forM_ [1..n] $ \\x-> do\n dst <- readArray dp (k,s,t)\n dsx <- readArray dp (k-1,s,x)\n dxt <- readArray dp (0,x,t)\n writeArray dp (k,s,t) $ min dst (dsx+dxt)\n\n ans <- unsafeFreeze dp :: IO (UArray (Int,Int,Int) Int)\n\n let solve [] = []\n solve (s:t:k:stks) = shows(ans!(min n k,s,t))\"\\n\" ++ solve stks\n\n putStr $ solve stks"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Control.Monad\n\nreadInt s = let Just (n,_) = B.readInt s in n\n\nparse :: [[Int]] -> ([Int],[[Int]],[[Int]])\nparse ([n,m,r]:xss) = let (disList,stks) = splitAt (m*n) xss\n in ([n,m,r],disList,stks)\n \nrep :: (Monad m) => Int -> (Int -> m ()) -> m ()\nrep n f = rep' 1\n where rep' i\n | i <= n = f i >> rep' (i+1)\n | otherwise = return ()\n\nmain = do\n \n ([n,m,r],disList,stks) <- parse.map (map readInt.B.words).B.lines <$> B.getContents\n\n let dis :: UArray (Int,Int,Int) Int\n dis = runSTUArray $ do\n d <- newListArray ((1,1,1),(m,n,n)) $ concat disList\n rep m $ \\i-> \n rep n $ \\x-> \n rep n $ \\s-> \n rep n $ \\t-> do\n dst <- readArray d (i,s,t)\n dsx <- readArray d (i,s,x)\n dxt <- readArray d (i,x,t)\n let tmp = dst+dxt\n when (tmp < dst) $ \n writeArray d (i,s,t) tmp\n return d\n\n let dp :: Array (Int,Int,Int) Int\n dp = array ((1,1,0),(n,n,n)) $ map (\\x->(x,f x)) $ [(s,t,k)|s<-[1..n],t<-[1..n],k<-[0..n]]\n f (s,t,0) = minimum [dis!(i,s,t)|i<-[1..m]]\n f (s,t,k) = minimum [dp!(s,x,k-1)+dp!(x,t,0)|x<-[1..n]]\n \n putStr.unlines.map (\\[s,t,k]->show $ dp!(s,t,min n k)) $ stks\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport Data.Word\nimport Control.Applicative\nimport Control.Monad\n\nreadInt s = let Just (n,_) = B.readInt s in n\n\nparse :: [[Int]] -> ([Word8],[[Int]],[[Word8]])\nparse ([n,m,r]:xss) = let (disList,stks) = splitAt (m*n) xss\n in (map fromIntegral [n,m,r],disList,map (map fromIntegral) stks)\n \nrep :: (Monad m) => Word8 -> (Word8 -> m ()) -> m ()\nrep n f = rep' 1\n where rep' i\n | i <= n = f i >> rep' (i+1)\n | otherwise = return ()\n\nmain = do\n ([n,m,r],disList,stks) <- parse.map (map readInt.B.words).B.lines <$> B.getContents\n\n let dis :: UArray (Word8,Word8,Word8) Int\n dis = runSTUArray $ do\n d <- newListArray ((1,1,1),(m,n,n)) $ concat disList\n rep m $ \\car-> \n rep n $ \\x-> \n rep n $ \\s-> \n rep n $ \\t-> do\n dst <- readArray d (car,s,t)\n dsx <- readArray d (car,s,x)\n dxt <- readArray d (car,x,t)\n writeArray d (car,s,t) $ min dst (dsx + dxt)\n return d\n\n let solve :: UArray (Word8,Word8,Word8) Int\n inf = 60000000\n solve = runSTUArray $ do \n dp <- newArray ((1,1,0),(n,n,n)) inf \n rep n $ \\s->\n rep n $ \\t->\n writeArray dp (s,t,0) $ minimum [dis!(car,s,t)|car<-[1..m]] \n rep n $ \\k-> \n rep n $ \\s-> \n rep n $ \\t-> \n rep n $ \\x-> do\n dst <- readArray dp (s,t,k)\n dsx <- readArray dp (s,x,k-1)\n dxt <- readArray dp (x,t,0)\n writeArray dp (s,t,k) $ min dst (dsx+dxt) \n return dp\n\n putStr.unlines.map (\\[s,t,k]->show $ solve!(s,t,min n k)) $ stks\n"}], "src_uid": "6d47da375461c228bc70b117887cba33"} {"source_code": "-- 15A\n\nimport List (sortBy)\nimport Monad (liftM)\n\nparse :: String -> (Int, Int)\nparse line = case words line of\n [s1, s2] -> (read s1, read s2)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve t xs = 2 + sum (zipWith f xs' (tail xs'))\n where\n xs' = sortBy (\\a b -> compare (fst a) (fst b)) xs\n f (x1, a1) (x2, a2)\n | d < 2 * t = 0\n | d > 2 * t = 2\n | otherwise = 1\n where\n d = (2 * x2 - a2) - (2 * x1 + a1)\n\nmain :: IO ()\nmain = do\n (_, t) <- liftM parse getLine\n xs <- liftM (map parse . lines) getContents\n print $ solve t xs", "positive_code": [{"source_code": "import List\nimport Control.Monad\n\nsolve t hs = show.(+2). sum $ [fits a b | (a,b) <- zip hs (tail hs)]\n where fits (x1, t1) (x2, t2) | 2*(x2-x1) - (t1+t2) == 2*t = 1\n | 2*(x2-x1) - (t1+t2) > 2*t = 2\n | otherwise = 0\n\nints = fmap (map read . words) getLine\n\nmain = do\n [n, t] <- ints \n replicateM n ints >>= putStrLn . solve t . sort . (map (\\[a,b]->(a,b)))\n "}, {"source_code": "import Data.List( sort)\nmain = do\n n:[t] <- return . map read . words =<< getLine\n let packDataLine = do\n\t [x,a] <- return . map read . words =<< getLine\n\t return (x,a)\n\tpackDataLine::IO (Int,Int)\n address <- sequence . take n $ repeat packDataLine\n let sAdd = sort address\n\twidths = [2*(fst b - fst a) - snd b - snd a | (a,b) <- zip sAdd (tail sAdd)]\n\tlist = map (\\w -> if 2*t if t Int\nreadIntB8 = fst . fromJust . B8.readInt\n\nreadInt64B8 :: B8.ByteString -> Int64\nreadInt64B8 = fromIntegral . fst . fromJust . B8.readInteger\n\nmodifyArray :: (MA.MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray array i func = do\n e <- MA.readArray array i\n MA.writeArray array i $ func e\n\ntype Vertex = Int\ntype Vertices = [Vertex]\ndata Graph = Graph { \n getN :: Int,\n getAdjacents :: A.Array Int Vertices }\n\nfindSizes :: forall s. Int -> Graph -> A.Array Int Int\nfindSizes v graph = SA.runSTArray $ do\n let n = getN graph\n let adjacents = getAdjacents graph\n\n weights <- SA.newArray (1, n) 0 :: ST s (STArray s Int Int)\n let dfsWeights weights v parent = do\n childWeights <- forM (adjacents UA.! v) $ \\u -> do\n if (u /= parent)\n then dfsWeights weights u v\n else return 0\n\n let weight = 1 + (sum childWeights)\n SA.writeArray weights v weight\n return $ weight\n dfsWeights weights v (-1)\n\n sizes <- SA.newArray (1, n) 0\n let dfsSizes sizes v parent upSize = do\n vWeight <- SA.readArray weights v\n childSizes <- forM (adjacents IA.! v) $ \\u -> do\n uWeight <- SA.readArray weights u\n if (u /= parent)\n then do\n dfsSizes sizes u v (upSize + vWeight - uWeight)\n return uWeight\n else return 0\n let vSize = (foldr1 max $ upSize : childSizes) -- `debug` (\"v = \" ++ (show v) ++ \", sizes = \" ++ (show $ upSize : childSizes)) \n SA.writeArray sizes v vSize\n return vSize\n dfsSizes sizes v (-1) 0\n return sizes\n\nfindLeafEdge :: Int -> Int -> Graph -> (Int, Int)\nfindLeafEdge v parent graph = edge\n where\n n = getN graph\n adjacents = getAdjacents graph\n dfs v parent\n | (length $ adjacents IA.! v) /= 1 = \n let childEdges = (flip map) (adjacents IA.! v) $ \\u ->\n if u /= parent\n then dfs u v\n else Nothing\n childEdge = msum childEdges\n in childEdge\n | otherwise = Just (v, parent)\n edge = fromJust $ dfs v parent\n \nreadGraph :: IO Graph\nreadGraph = do\n n <- B8.getLine <&> readIntB8\n adjacents <- MA.newArray (1, n) [] :: IO (IOA.IOArray Int Vertices)\n forM_ [2..n] $ \\_ -> do\n [a, b] <- B8.getLine <&> B8.words <&> map readIntB8\n modifyArray adjacents a ((:) b)\n modifyArray adjacents b ((:) a)\n adjacentsA <- MA.freeze adjacents\n return $ Graph n adjacentsA\n\nsolve :: Graph -> ((Int, Int), (Int, Int))\nsolve graph = answer\n-- `debug` (\"sizes = \" ++ show sizes)\n where\n n = getN graph\n sizes = findSizes 1 graph\n minSize = foldr1 min sizes\n centroids = map fst . filter (\\(i, e) -> e == minSize) $ UA.assocs sizes\n\n defaultEdge = (1, head $ (getAdjacents graph) IA.! 1)\n leafEdge = findLeafEdge (centroids !! 0) (centroids !! 1) graph\n answer\n | (length centroids) == 1 = (defaultEdge, defaultEdge)\n | otherwise = (leafEdge, (centroids !! 1, fst leafEdge))\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n graph <- readGraph\n let ((a, b), (c, d)) = solve graph\n printf \"%d %d\\n\" a b\n printf \"%d %d\\n\" c d\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Data.Array\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [caseNum] <- getInts\n forM_ [1..caseNum] $ \\_ -> do\n [n] <- getInts\n edges <- map (\\[x, y] -> (x, y)) <$> replicateM (n - 1) getInts\n let es = listArray (1, n) $ map (map snd) $\n groupBy (\\(a, _) (b, _) -> a == b) $ sortBy (\\(a, _) (b, _) -> compare a b) $\n concat $ map (\\(x, y) -> [(x, y), (y, x)]) edges\n dfs par u = let ps = map (dfs u) $ filter (/= par) $ es ! u\n rr = join $ find isJust $ map (\\(r, _, _) -> r) ps\n result = if isJust rr\n then rr\n else find (\\(_, _, sz) -> 2 * sz == n) ps >>= (\\(_, v, _) -> Just (u, v))\n in (result, u, sum (1 : map (\\(_, _, sz) -> sz) ps))\n ans = let (result, _, _) = dfs 1 1\n in case result of\n Nothing -> [edges !! 0, edges !! 0]\n Just (u, v) -> let w = fromJust $ find (/= v) (es ! u) in [(u, w), (v, w)]\n forM_ ans (\\(x, y) -> printf \"%d %d\\n\" x y)\n"}], "negative_code": [], "src_uid": "b01fb9d4d78a02e3c634800b4b177d75"} {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nsolve [] cnt r = r\r\nsolve (x:xs) cnt r = if (x>0) then solve xs (max (cnt-1) (x-1)) (1:r)\r\n else do \r\n if (cnt > 0) then solve xs (cnt-1) (1:r)\r\n else (solve xs cnt (0:r) )\r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let b = reverse a \r\n putStrLn $ printArray $ solve b 0 []\r\n\r\nmain = do\r\n t<-readLn :: IO Int \r\n replicateM_ t printS", "positive_code": [{"source_code": "f :: Int -> IO()\r\nf 0 = return ()\r\nf n = do {\r\n x <- getLine;\r\n l <- getLine;\r\n putStrLn (concatMap ( ( ++ [' ']).show ) ( sol (read x) (map read (words l)) ));\r\n f (n-1)\r\n}\r\n\r\nsol2 :: Int -> [Int] -> [Int] -> [Int]\r\nsol2 _ li [] = li\r\nsol2 n li (x:xs) \r\n | n > x = sol2 (n-1) (1:li) xs\r\n | x > 0 = sol2 (x-1) (1:li) xs\r\n | otherwise = sol2 0 (0:li) xs\r\n\r\n\r\nsol :: Int -> [Int] -> [Int]\r\nsol n li = sol2 0 [] (reverse li)\r\n\r\nmain = do {\r\n x <- getLine;\r\n f (read x)\r\n}"}], "negative_code": [], "src_uid": "807c5ec37b0ea83ef40550698f1ff498"} {"source_code": "main :: IO ()\nmain = interact ((\\stdin -> solve (stdin !! 1) (stdin !! 2)) . lines)\n \nsolve :: String -> String -> String\nsolve pattern str = \n if any (=='*') pattern then\n let p = prefix pattern\n s = suffix pattern in\n if (length p) + (length s) > (length str) then \"NO\" else\n if (and (zipWith (==) p str)) && (and (zipWith (==) s (reverse str))) then\n \"YES\" else \"NO\" else if pattern == str then \"YES\" else \"NO\" \n \nprefix :: String -> String\nprefix str = takeWhile (/='*') str\n \nsuffix = prefix . reverse", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Int\n\ndoit s t =\n case (dropWhile (/='*') s) of\n \"\" -> s == t\n bb ->\n let b = tail bb in\n let a = takeWhile (/='*') s in\n (isPrefixOf a t) && (isSuffixOf b t) && length a + length b <= length t\n\nsolve::String -> String\nsolve ss =\n let [_,_,s,t] = words ss in\n if doit s t then\n \"YES\\n\"\n else\n \"No\\n\"\n\n\nmain = interact solve\n"}, {"source_code": "import Control.Monad\nimport Data.Bool\nimport Data.Function\nimport Data.Tuple\nimport Data.Maybe\nimport Data.Tree\nimport Data.Graph\nimport Data.Array.IArray\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as B\n\n\niogetints :: IO [Int]\niogetints = getLine >>= (return . map read . words)\n\nfreadEdgeList :: IO [Edge]\nfreadEdgeList = B.getContents >>= (return . pairify . map (fst . fromJust . B.readInt) . B.words)\n\nindexed :: [a] -> [(Int, a)]\nindexed = go 0 where\n\tgo :: Int -> [a] -> [(Int, a)]\n\tgo _ [] = []\n\tgo i (x:xs) = (i, x) : (go (succ i) xs)\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n\tgo (Node x ts) = f x (map go ts)\n\npairify :: [a] -> [(a, a)]\npairify [] = []\npairify (x:y:xs) = (x, y) : (pairify xs)\n\nbuildTree :: Int -> Vertex -> [Edge] -> Tree Vertex\nbuildTree n r es = fdfs (-1) r where\n\tg = accumArray (flip (:)) [] (1, n) $ ap (++) (map swap) $ es :: Graph\n\tfdfs :: Vertex -> Vertex -> Tree Vertex\n\tfdfs p v = Node v $ map (fdfs v) $ delete p $ g!v\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (x, y) = (f x, f y)\n\nsolve :: String -> String -> Bool\nsolve s1 s2 = ans where\n\tss = split (dropDelims $ oneOf \"*\") s1\n\tans = if(length ss == 1 || (length s1) > (succ $ length s2)) then (s1 == s2) else\n\t\t(&&) (all id $ zipWith (==) (head ss) s2) (all id $ zipWith (==) (reverse $ last ss) (reverse s2))\n \nmain :: IO ()\nmain = do\n\t[n, m] <- iogetints\n\ts1 <- getLine\n\ts2 <- getLine\n\tputStrLn $ bool \"NO\" \"YES\" $ solve s1 s2\n\t"}], "negative_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Int\n\ndoit s t =\n case (dropWhile (/='*') s) of\n \"\" -> s == t\n bb ->\n let b = tail bb in\n let a = takeWhile (/='*') s in\n (isPrefixOf a t) && (isSuffixOf b t)\n\nsolve::String -> String\nsolve ss =\n let [_,_,s,t] = words ss in\n if doit s t then\n \"YES\\n\"\n else\n \"No\\n\"\n\n\nmain = interact solve\n"}, {"source_code": "main :: IO ()\nmain = interact ((\\stdin -> solve (stdin !! 1) (stdin !! 2)) . lines)\n \nsolve :: String -> String -> String\nsolve pattern str = \n let p = prefix pattern\n s = suffix pattern in\n if (length p) + (length s) > (length str) then \"NO\" else\n if (and (zipWith (==) p str)) && (and (zipWith (==) s (reverse str))) then\n \"YES\" else \"NO\"\n \nprefix :: String -> String\nprefix str = takeWhile (/='*') str\n \nsuffix = prefix . reverse"}, {"source_code": "import Control.Monad\nimport Data.Bool\nimport Data.Function\nimport Data.Tuple\nimport Data.Maybe\nimport Data.Tree\nimport Data.Graph\nimport Data.Array.IArray\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as B\n\n\niogetints :: IO [Int]\niogetints = getLine >>= (return . map read . words)\n\nfreadEdgeList :: IO [Edge]\nfreadEdgeList = B.getContents >>= (return . pairify . map (fst . fromJust . B.readInt) . B.words)\n\nindexed :: [a] -> [(Int, a)]\nindexed = go 0 where\n\tgo :: Int -> [a] -> [(Int, a)]\n\tgo _ [] = []\n\tgo i (x:xs) = (i, x) : (go (succ i) xs)\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n\tgo (Node x ts) = f x (map go ts)\n\npairify :: [a] -> [(a, a)]\npairify [] = []\npairify (x:y:xs) = (x, y) : (pairify xs)\n\nbuildTree :: Int -> Vertex -> [Edge] -> Tree Vertex\nbuildTree n r es = fdfs (-1) r where\n\tg = accumArray (flip (:)) [] (1, n) $ ap (++) (map swap) $ es :: Graph\n\tfdfs :: Vertex -> Vertex -> Tree Vertex\n\tfdfs p v = Node v $ map (fdfs v) $ delete p $ g!v\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (x, y) = (f x, f y)\n\nsolve :: String -> String -> Bool\nsolve s1 s2 = ans where\n\tss = split (dropDelims $ oneOf \"*\") s1\n\tans = if(length ss == 1) then (s1 == s2) else\n\t\t(&&) (all id $ zipWith (==) (head ss) s2) (all id $ zipWith (==) (reverse $ last ss) (reverse s2))\n \nmain :: IO ()\nmain = do\n\t[n, m] <- iogetints\n\ts1 <- getLine\n\ts2 <- getLine\n\tputStrLn $ bool \"NO\" \"YES\" $ solve s1 s2\n\t"}, {"source_code": "import Control.Monad\nimport Data.Bool\nimport Data.Function\nimport Data.Tuple\nimport Data.Maybe\nimport Data.Tree\nimport Data.Graph\nimport Data.Array.IArray\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as B\n\n\niogetints :: IO [Int]\niogetints = getLine >>= (return . map read . words)\n\nfreadEdgeList :: IO [Edge]\nfreadEdgeList = B.getContents >>= (return . pairify . map (fst . fromJust . B.readInt) . B.words)\n\nindexed :: [a] -> [(Int, a)]\nindexed = go 0 where\n\tgo :: Int -> [a] -> [(Int, a)]\n\tgo _ [] = []\n\tgo i (x:xs) = (i, x) : (go (succ i) xs)\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n\tgo (Node x ts) = f x (map go ts)\n\npairify :: [a] -> [(a, a)]\npairify [] = []\npairify (x:y:xs) = (x, y) : (pairify xs)\n\nbuildTree :: Int -> Vertex -> [Edge] -> Tree Vertex\nbuildTree n r es = fdfs (-1) r where\n\tg = accumArray (flip (:)) [] (1, n) $ ap (++) (map swap) $ es :: Graph\n\tfdfs :: Vertex -> Vertex -> Tree Vertex\n\tfdfs p v = Node v $ map (fdfs v) $ delete p $ g!v\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (x, y) = (f x, f y)\n\nsolve :: String -> String -> Bool\nsolve s1 s2 = ans where\n\tss = split (dropDelims $ oneOf \"*\") s1\n\tans = if(length ss == 1) then (s1 == s2) else\n\t\t(&&) (all id $ zipWith (==) (head ss) s2) (all id $ zipWith (==) (reverse $ last ss) (reverse s2))\n \nmain :: IO ()\nmain = do\n\t[n, m] <- iogetints\n\ts1 <- getLine\n\ts2 <- getLine\n\tprint $ bool \"NO\" \"YES\" $ solve s1 s2\n\t"}], "src_uid": "d629d09782a7af0acc359173ac4b4f0a"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\tn <- readInteger\n\tprint $ 1 + length ( takeWhile ( <= n ) [ 10 ^ i | i <- [ 1 .. ] ] )", "positive_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq, ViewL (..), (<|), (|>))\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Data.Tree\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = interact $\n lines >>> drop 1 >>> map (length >>> show) >>> unlines\n\n"}], "negative_code": [], "src_uid": "ea011f93837fdf985f7eaa7a43e22cc8"} {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\nrun1 = do\n n <- popInt\n as <- popInts\n return $ bshow (solve n as)\n\nsolve n as = length $ filter (/= minimum as) as\n", "positive_code": [{"source_code": "module Main where\r\n\r\n del :: Eq a => [a] -> a -> [a]\r\n del s x = filter (/= x) s\r\n \r\n solve :: IO ()\r\n solve = do\r\n getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Integer) $ words s\r\n print $ length $ del a $ minimum a\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter x = do\r\n solve\r\n iter $ x - 1\r\n \r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FlexibleContexts, ConstraintKinds #-}\r\n\r\nmain = interact $ unlines.map show.f.tail.lines\r\n\r\nf :: [String] -> [Int]\r\nf [] = []\r\nf (_:b:xs) = g (read <$> words b) : f xs\r\n\r\ng :: [Int] -> Int\r\ng [] = 0\r\ng b = let m = minimum b in length $ filter (> m) b\r\n"}, {"source_code": "main = interact $ unlines.map show.f.tail.lines\r\n\r\nf :: [String] -> [Int]\r\nf [] = []\r\nf (_:b:xs) = g (read <$> words b) : f xs\r\n\r\ng :: [Int] -> Int\r\ng [] = 0\r\ng b = let m = minimum b in length $ filter (> m) b\r\n"}, {"source_code": "import Data.List (sort)\r\nimport Control.Monad (mapM_)\r\n\r\ndiscardSmallest :: Eq a => [a] -> [a] -- list must be sorted\r\ndiscardSmallest [] = []\r\ndiscardSmallest (x:xs) = dropWhile (== x) xs\r\n\r\nsolution :: [Int] -> Int\r\nsolution = length . discardSmallest . sort\r\n\r\nmain = do\r\n\tnumTests <- read <$> getLine\r\n\ttests <- sequence $ replicate numTests $ do \r\n\t\t_ <- getLine \t\t-- length of list \r\n\t\tmap read . words <$> getLine\r\n\tmapM_ (putStrLn . show . solution) tests\r\n \r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n as <- getInts\n let minValue = minimum as\n C.putStrLn $ C.pack $ show $ length $ filter (/= minValue) as\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\ntype SIO = StateT P.ByteString IO\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n let v = minimum a\n putInts [length $ filter (> v) a]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\n del :: Eq a => [a] -> a -> [a]\r\n del s x = filter (/= x) s\r\n \r\n solve :: IO ()\r\n solve = do\r\n getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Integer) $ words s\r\n print $ length $ del a $ maximum a\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter x = do\r\n solve\r\n iter $ x - 1\r\n \r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}], "src_uid": "99e5c907b623c310d6f1599f485ca21d"} {"source_code": "import Data.Bits (xor)\n\ncountInv :: [Int] -> Int\ncountInv [] = 0\ncountInv (x:xs) = countInv xs `xor` (length (filter (< x) xs) `mod` 2)\n\nprocess :: Int -> Int -> IO ()\nprocess 0 _ = return ()\nprocess m inv = do\n [l, r] <- fmap (map read . words) getLine\n let c = r - l + 1\n let newInv = inv `xor` ((c * (c - 1) `div` 2) `mod` 2)\n putStrLn $ if newInv == 0 then \"even\" else \"odd\"\n process (m - 1) newInv\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n a <- fmap (map read . words) getLine\n m <- readLn :: IO Int\n let inv = countInv a\n process m inv\n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n getLine\n nums <- fmap (map read . words) getLine :: IO [Int]\n let isOdd = odd $ countInv nums\n getLine\n invs <- fmap (map readPair . lines) getContents :: IO [(Int, Int)]\n main' isOdd invs\n where\n main' :: Bool -> [(Int, Int)] -> IO ()\n main' _ [] = return ()\n main' isOdd (i:is) = do\n let tmp = process isOdd i\n putStrLn (if tmp then \"odd\" else \"even\")\n main' tmp is\n\nreadPair :: String -> (Int, Int)\nreadPair s = let (a:b:_) = map read $ words s\n in (a, b)\nprocess :: Bool -> (Int, Int) -> Bool\nprocess inp (l, r) = case (r-l+1) `div` 2 `mod` 2 of\n 0 -> inp\n 1 -> not inp\n\ncountInv :: [Int] -> Int\ncountInv nums = countInv' nums 0\n where\n countInv' (n:ns) ans = countInv' ns (ans + sum (map (\\x -> if x < n then 1 else 0) ns))\n countInv' _ ans = ans"}], "negative_code": [{"source_code": "main :: IO ()\nmain = do\n getLine\n nums <- fmap (map read . words) getLine :: IO [Int]\n let isOdd = odd $ countInv nums\n getLine\n invs <- fmap (map readPair . lines) getContents :: IO [(Int, Int)]\n main' isOdd invs\n where\n main' :: Bool -> [(Int, Int)] -> IO ()\n main' _ [] = return ()\n main' isOdd (i:is) = do\n let tmp = process isOdd i\n putStrLn (if tmp then \"odd\" else \"even\")\n main' tmp is\n\nreadPair :: String -> (Int, Int)\nreadPair s = let (a:b:_) = map read $ words s\n in (a, b)\nprocess :: Bool -> (Int, Int) -> Bool\nprocess inp (l, r) = case (r-l+1) `div` 2 `mod` 2 of\n 0 -> inp\n 1 -> not inp\n\ncountInv :: [Int] -> Int\ncountInv nums = countInv' nums 0\n where\n countInv' (n:ns) ans = countInv' ns (ans + sum (map (\\x -> if x > n then 1 else 0) ns))\n countInv' _ ans = ans"}, {"source_code": "import Data.Bits (xor)\n\ncountInv :: [Int] -> Int\ncountInv [] = 0\ncountInv (x:xs) = countInv xs + length (filter (< x) xs)\n\nprocess :: Int -> Int -> IO ()\nprocess 0 _ = return ()\nprocess m inv = do\n [l, r] <- fmap (map read . words) getLine\n let c = r - l + 1\n let newInv = inv `xor` ((c * (c - 1) `div` 2) `mod` 2)\n putStrLn $ if newInv == 0 then \"even\" else \"odd\"\n process (m - 1) newInv\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n a <- fmap (map read . words) getLine\n m <- readLn :: IO Int\n let inv = countInv a\n process m inv\n"}], "src_uid": "d20cc952cdf3a99e7d980a0270c49f78"} {"source_code": "solve :: [Int] -> Int\nsolve (_ : h : xs) = sum $ map (\\x -> if x <= h then 1 else 2) xs\n\nmain :: IO ()\nmain = interact $ show . solve . map read . words\n", "positive_code": [{"source_code": "module Main\n where\n\nimport System.IO\n\nsolve first second =\n foldr (\\a s -> s + if a <= h then 1 else 2) 0 friends\n --sum . map (\\a -> if a <= h then 1 else 2) $ friends\n where\n h =\n case words first of\n _ : h' : _ ->\n read h' :: Int\n friends =\n map read . words $ second\n\nmain = do\n first <- getLine\n second <- getLine\n print $ solve first second"}, {"source_code": "module Main\n where\n\nimport System.IO\n\nsolve first second =\n sum . map (\\a -> if a <= h then 1 else 2) $ friends\n where\n h =\n case words first of\n _ : h' : _ ->\n read h' :: Int\n friends =\n map read . words $ second\n\nmain = do\n first <- getLine\n second <- getLine\n print $ solve first second"}, {"source_code": "import Control.Monad\n\nsol :: [Int] -> Int -> Int\nsol [] h = 0\nsol heights h = if (head heights) > h\n then 2 + (sol (tail heights) h)\n else 1 + (sol (tail heights) h)\n\nmain :: IO ()\nmain = do\n [n, h] <- fmap (map read.words) getLine\n heights <- fmap (map read.words) getLine\n print (sol heights h)\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n [n, h] <- getInts\n as <- getInts\n print $ totWidth h as\n\ngetInts :: IO [Int]\ngetInts = fmap (map read . words) getLine\n\n--totWidth :: Num a => a -> [a] -> a\ntotWidth _ [] = 0\ntotWidth h (a : as) = singleWidth h a + totWidth h as\n\n--singleWidth :: Num a => a -> a -> a\nsingleWidth h a = if a <= h then 1 else 2\n\ntest :: Bool\ntest = totWidth 10 [2, 2, 5] == 3 && totWidth 10 [9, 10, 11, 3] == 5 && totWidth 10 [11, 12, 23, 14] == 8 && totWidth 7 [4, 5, 14] == 4 && totWidth 1 [1, 1, 1, 1, 1, 1] == 6 && totWidth 5 [7, 6, 8, 9, 10, 5] == 11\n"}, {"source_code": "import Data.Functor\n\nmain :: IO()\nmain = do\n [n, h] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n let m = length $ filter (> h) a\n print $ n + m\n"}, {"source_code": "\n\nconv lst uu\n | (null lst) = uu\n | otherwise = conv (tail lst) (uu ++ [(read (head lst))::Int])\n \nfindwidth lst height width\n | (null lst) = width\n | otherwise = if (head lst) > height\n then findwidth (tail lst) height (width + 2)\n else findwidth (tail lst) height (width + 1)\n\n\nmain = do\n ff <- getLine\n gg <- getLine\n let aa = (read (head (words ff)))::Int\n bb = (read (last (words ff)))::Int\n cc = conv (words gg) []\n\n ans = findwidth cc bb 0\n putStrLn (show ans)\n"}, {"source_code": "f :: Int -> Int -> Int\nf x h =\n if x > h\n then 2\n else 1\n\n\nresult :: [Int] -> Int -> Int\nresult xs h =\n if null xs\n then 0\n else (f (head xs) h) + result (tail xs) h\n\nmain = do\n line <- getLine\n let [n, h] = take 2 (map read $ words line :: [Int])\n line2 <- getLine\n let xs = take n (map read $ words line2 :: [Int])\n let p = result xs h\n print p\n"}, {"source_code": "main = do\n [n, h] <- fmap (map read . words) getLine\n elems <- fmap (map read . words) getLine\n print (solve h elems)\n\n\nvalue :: Int -> Int -> Int\nvalue h x = if x > h then 2 else 1\n\nsolve :: Int -> [Int] -> Int\nsolve h elems = sum (map (value h) elems)\n"}, {"source_code": "import Data.Char\nimport Control.Monad\n\nreadIntImpl :: Int -> Bool -> IO Int\nreadIntImpl x flag = do\n c <- getChar\n if c `elem` ['0'..'9']\n then do\n let d = digitToInt c\n y <- readIntImpl (x*10+d) True\n return y\n else if flag\n then \n return x\n else do\n y <- readIntImpl x False\n return y\n\nreadInt = readIntImpl 0 False\nreadArr n readFunc = replicateM n readFunc\n\n\nmain = do\n n <- readInt\n h <- readInt\n arr <- readArr n readInt\n let ans = sum [ if x > h then 2 else 1 | x <- arr]\n putStrLn (show(ans))"}, {"source_code": "main = do\n [n, h] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n\n print $ sum $ map (\\x -> if x <= h then 1 else 2) xs\n"}, {"source_code": "solve :: [[Int]] -> Int\nsolve [[_,h],a] = (length $ filter (<=h) a) + 2*(length $ filter (>h) a)\nmain = interact $ show . solve . map (map read . words) . take 2 . lines\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [n,h] <- fmap (map read . words) getLine\n inp <- fmap (map read . words) getLine\n print $ solve h inp\n\n\nsolve :: Int -> [Int] -> Int\nsolve h = sum . map f\n where\n f a | a > h = 2\n | otherwise = 1\n"}, {"source_code": "solve :: Int -> [Int] -> Int\nsolve h (x:xs) = if x > h then 2 + solve h xs else 1 + solve h xs\nsolve h _ = 0\n\nmain = do\n firstLine <- getLine\n secondLine <- getLine\n let h = read $ (tail $ words firstLine) !! 0\n let friends = map read $ words secondLine\n putStrLn . show $ solve h friends"}, {"source_code": "module Main where\n\nsolve (h:xs) = length $ xs ++ filter (>h) xs\n\nmain :: IO ()\nmain = print . solve . drop 1 . map (read:: String -> Int) . words =<< getContents\n"}, {"source_code": "module Main where\n\nsolve (h:xs) = length (xs ++ filter (>h) xs)\n\nmain :: IO ()\nmain = print . solve . drop 1 . map (read:: String -> Int) . words =<< getContents\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = solve. tail.concat =<< forM [1..2] (\\i-> (map (fst.fromJust.C.readInt).C.words) <$> C.getLine)\nsolve::[Int]->IO ()\nsolve (x:xs) = print $ foldr (\\a b -> if a>x then 2+b else 1+b) 0 xs"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> [Int] -> Int\nsolve h = sum.fmap f \n where f a\n | a > h = 2\n | otherwise = 1\nmain = do\n _:h:as <- fmap read.concatMap words.lines <$> getContents\n print $ solve h as\n"}, {"source_code": "{-#LANGUAGE OverloadedStrings#-}\nmodule Main where\nimport Data.Text (pack, unpack, splitOn)\nmain :: IO ()\nmain = do\n [_,h] <- readInts\n hs <- readInts\n putStrLn $ show (solve h hs)\n where\n readInts :: IO [Int]\n readInts = fmap (map ((read ::String ->Int). unpack) \n . splitOn \" \" . pack) getLine\n\nsolve :: Int -> [Int] -> Int\nsolve h = foldr (\\x acc -> if x > h then acc + 2 else acc + 1) 0"}, {"source_code": "import Control.Monad\n\nmain = readInput >>= putStrLn . show . count\n\nreadInput :: IO (Int, [Int])\nreadInput = liftM2 toTuple getLine getLine\n where toTuple a b = (h, map read $ words b)\n where fstL = words a\n h = read $ fstL !! 1\n \ncount :: (Int, [Int]) -> Int\ncount (h, hs) = foldr (\\curr ans -> if h < curr\n then ans + 2\n else ans + 1)\n 0 hs"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nwidth :: Int -> Int -> Int\nwidth x h \n | x > h = 2\n | otherwise = 1\n\nmain :: IO ()\nmain = do\n [n, h] <- (map readInt . words) <$> getLine\n arr <- (map readInt . words) <$> getLine\n let answer = sum . map (`width` h) $ arr\n printf \"%d\\n\" answer "}, {"source_code": "import Control.Monad\n\nmain = do\n firstLine <- getLine\n let [_, h] = map read (words firstLine)\n \n secondLine <- getLine\n let arr = map read (words secondLine)\n\n print $ sum $ map (process h) arr\n where\n process :: Int -> Int -> Int\n process h a\n | a <= h = 1\n | otherwise = 2\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n\n\nmain=do\n [a,b]<- map read <$> words <$> getLine ::IO [Int]\n c<- map read <$> words <$> getLine ::IO [Int]\n putStrLn $ show $ (length c) + length (filter (>b) c)\n"}, {"source_code": "main = print . solve . map read . words =<< getContents\nsolve (n:h:ns) = length (ns ++ filter (>h) ns :: [Int])"}, {"source_code": "main :: IO ()\nmain = do\n [n, h] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n print $ solve h a\n\nsolve :: Int -> [Int] -> Int\nsolve h = sum . map f\n where\n f a =\n if a > h\n then 2\n else 1\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do [n, h] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve n h as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n h as = foldr (+) 0 $ map (\\a -> if h < a then 2 else 1) as\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do [n, h] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve n h as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n h as = n + (length $ filter (\\a -> h < a) as)\n\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/677/A\n\nmain :: IO ()\nmain = do\n [n,h] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n let m = length $ filter (>h) a\n print $ n + m\n"}, {"source_code": "zabor :: [Int] -> Int -> Int\nzabor [] _ = 0\nzabor (x:xs) n\n | (x <= n) = 1 + zabor xs n\n | otherwise = 2 + zabor xs n\nfunc :: [String] -> [Int]\nfunc list = map (\\x -> read x::Int) list\n\nmain :: IO()\nmain = do\n inputOne <- getLine\n inputTwo <- getLine\n a <- return $ (func $ words inputOne)!!1\n b <- return $ func $ words inputTwo\n putStrLn $ show $ zabor b a"}, {"source_code": "import Control.Applicative( (<$>))\nmain = do\n tokens <- return . words =<< getContents\n let n:fence:heights = read <$> tokens\n print $ sum $ (\\h->if h>fence then 2 else 1) <$> take n heights\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nans a b c d k | z >k = \"-1\"\n | otherwise = show z1 ++ \" \" ++ show z2\n\n\twhere \tz1= (div (a-1) c )+1\n\t\tz2 = (div (b-1) d) +1 \n\t\tz= z1+z2\n\nmain= do\n\t [a,b]<-map read <$> words <$> getLine::IO [Int]\n c<- map read <$> words<$> getLine::IO [Int]\n\t let d = length $ filter (>b) c\n print $ a+d\n"}, {"source_code": "main :: IO ()\nmain = do\n [n, h] <- map (read :: String -> Int) . words <$> getLine\n print =<< sum . map ((1+) . fromEnum . (h<) . (read :: String -> Int)) . words <$> getLine "}, {"source_code": "getResult _ [] = 0\ngetResult h (x:xs) = cur + getResult h xs\n where cur = if x > h then 2 else 1\n\nmain = do\n nh_ln <- getLine\n nums_ln <- getLine\n\n let nh = map (read :: String -> Int) (words nh_ln)\n let nums = map (read :: String -> Int) (words nums_ln)\n\n putStrLn . show $ getResult (nh !! 1) nums \n"}, {"source_code": "--ghc 7.10\n\nminRoadWidth :: (Ord a, Integral b) => a -> [a] -> b\nminRoadWidth h a = sum . map (\\x -> if x > h then 2 else 1) $ a\n\nmain = do\n nhStr <- getLine\n let [n,h] = map read . words $ nhStr :: [Int]\n aStr <- getLine\n let a = map read .words $ aStr :: [Int]\n print $ minRoadWidth h a"}, {"source_code": "main :: IO ()\nmain = do\n [[_,h],a] <- readLoL :: IO [[Int]]\n print $ answer h a\n\nanswer :: Int -> [Int] -> Int\nanswer h = sum . fmap (\\a -> if a <= h then 1 else 2) \n\n-- Boilerplate\nreadLoL :: (Read a) => IO [[a]]\nreadLoL = fmap parseMatrix getContents\n\nparseMatrix :: (Read a) => String -> [[a]]\nparseMatrix = (fmap.fmap) read . tokenizeMatrix\n\ntokenizeMatrix :: String -> [[String]]\ntokenizeMatrix = fmap words . lines\n"}, {"source_code": "main = interact $ show . f . tail . map read . words\n\nf :: [Int] -> Int\nf (b : xs) = sum (map (\\x -> if x > b then 2 else 1) xs)\n"}], "negative_code": [], "src_uid": "e7ed5a733e51b6d5069769c3b1d8d22f"} {"source_code": "import Data.List\nimport Control.Monad\n\nsolve :: ([Int], [Int]) -> Maybe [Int]\nsolve (xs, ys)\n | null is = Nothing\n | otherwise = Just is\n where\n is = xs `intersect` ys\n\nprintS :: Maybe [Int] -> IO ()\nprintS Nothing = putStrLn \"NO\"\nprintS (Just (x:_)) = putStrLn \"YES\" >> putStrLn (\"1 \" ++ show x)\n\ngetTest :: IO ([Int], [Int])\ngetTest = getLine >> do\n xs <- map read . words <$> getLine\n ys <- map read . words <$> getLine\n return (xs, ys)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n tests <- replicateM t getTest\n mapM_ (printS . solve) tests\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Set as S\n\n\nonecase = do\n\t\tgetLine\n\t\tx<- map read <$> words <$> getLine ::IO [Int]\n\t\ty<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet xx = S.fromList x\n\t\tlet yy = S.fromList y\n\t\tlet zz = S.intersection xx yy\n\t\tputStrLn $ if S.null zz then \"NO\" else \"YES\\n1 \" ++ show (head (S.elems zz))\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [], "src_uid": "776a06c14c6fa3ef8664eec0b4d50824"} {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Road = Map Int (Map Int Int)\ntype Domain = (Road, Int, IOUArray Int Int, IOUArray Int Bool)\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\npairToElem :: (Int, Int) -> (Int, Map Int Int)\npairToElem (a, b) = (a, Map.singleton b 1)\n\npairToRevElem :: (Int, Int) -> (Int, Map Int Int)\npairToRevElem (a, b) = (b, Map.singleton a 1)\n\ninsertAll :: IOUArray Int Int -> [(Int, Int)] -> IO ()\ninsertAll arr = mapM_ (uncurry $ writeArray arr) \n\nparse :: IO Domain\nparse = do\n [cities, roadsNumber] <- readChar8\n pairs <- replicateM roadsNumber getPair\n visited <- newArray (1,cities) False\n let roads = fromListWith (Map.unionWith (+)) $ pairToElem <$> pairs\n pen <- newArray (1, cities) 0\n insertAll pen $ Map.toList $ ((+1) . sum . Map.elems) <$> roads \n let revRoads = fromListWith (Map.unionWith (+)) $ pairToRevElem <$> pairs\n return $ (revRoads, cities, pen, visited)\n\n-- (dist, target)\ndij :: Road -> (Set (Int, Int), IOUArray Int Int, IOUArray Int Bool) -> IO Int\ndij roads (a, pen, visited) = go a-- traceShow ((d, i), newPen, que) $ \n where \n go :: Set (Int, Int) -> IO Int\n go que = do\n ((d, i), nQue) <- deleteFindMinNotMeet visited que\n writeArray visited i True\n let children = fromMaybe empty $ roads !? i\n -- reduce children penetration if visiting\n _ <- traverseWithKey (\\k v -> writeArray pen k =<< (flip (-) v) <$> readArray pen k) children\n childQue <- mapM (\\j -> do \n c <- readArray pen j\n return (d + c, j)) $ Map.keys children\n let newQue = union nQue (Set.fromList childQue)\n if i == 1 then return d else go newQue\n \ndeleteFindMinNotMeet :: IOUArray Int Bool -> Set (Int, Int) -> IO ((Int, Int), Set (Int, Int))\ndeleteFindMinNotMeet visited que = do\n flag <- readArray visited i\n if flag then deleteFindMinNotMeet visited nQue else return ans\n where ans@((d, i), nQue) = deleteFindMin que\n\nsolve :: Solver\nsolve (roads, n, pen, visited) = dij roads (Set.singleton (0, n), pen, visited)\n\n\nmain :: IO ()\nmain = do\n printAns =<< solve =<< parse\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Road = Map Int (Map Int Int)\ntype Domain = (Road, Int, IOUArray Int Int, IOUArray Int Bool)\ntype Dist = Map Int Int \ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\npairToElem :: (Int, Int) -> (Int, Map Int Int)\npairToElem (a, b) = (a, Map.singleton b 1)\n\npairToRevElem :: (Int, Int) -> (Int, Map Int Int)\npairToRevElem (a, b) = (b, Map.singleton a 1)\n\n\ninsertAll :: IOUArray Int Int -> [(Int, Int)] -> IO ()\ninsertAll arr [] = return ()\ninsertAll arr ((i, e):xs) = writeArray arr i e >> insertAll arr xs\n\n\nparse :: IO Domain\nparse = do\n [cities, roadsNumber] <- readChar8\n pairs <- replicateM roadsNumber getPair\n -- let [cities, roadsNumber] = [20000,20000]\n -- pairs <- gen\n visited <- newArray (1,cities) False\n let roads = fromListWith (Map.unionWith (+)) $ pairToElem <$> pairs\n pen <- newArray (1, cities) 0\n insertAll pen $ Map.toList $ ((+1) . sum . Map.elems) <$> roads \n let revRoads = fromListWith (Map.unionWith (+)) $ pairToRevElem <$> pairs\n return $ (revRoads, cities, pen, visited)\n\n-- (dist, target)\ndij :: Road -> (Set (Int, Int), IOUArray Int Int, IOUArray Int Bool) -> IO Int\ndij roads (a, pen, visited) = go a-- traceShow ((d, i), newPen, que) $ \n where \n go :: Set (Int, Int) -> IO Int\n go que = do\n ((d, i), nQue) <- deleteFindMinNotMeet visited que\n writeArray visited i True\n let children = fromMaybe empty $ roads !? i\n _ <- traverseWithKey (\\k v -> (\\u -> writeArray pen k (u - v)) =<< readArray pen k) children\n childQue <- mapM (\\j -> do \n c <- readArray pen j\n return (d + c, j)) $ Map.keys children\n let newQue = union nQue (Set.fromList childQue)\n if i == 1 then return d else go newQue\n \ndeleteFindMinNotMeet :: IOUArray Int Bool -> Set (Int, Int) -> IO ((Int, Int), Set (Int, Int))\ndeleteFindMinNotMeet visited que = do\n flag <- readArray visited i\n if flag then deleteFindMinNotMeet visited nQue else return ans\n where ans@((d, i), nQue) = deleteFindMin que\n\nsolve :: Solver\nsolve (roads, n, pen, visited) = dij roads (Set.singleton (0, n), pen, visited)\n\n\n-- gen :: IO [(Int,Int)]\n-- gen = do\n-- xs :: [(Int, Int)] <- replicateM 20000 $ liftM2 (,) (randomRIO (1, 2*10^5)) (randomRIO (1, 2*10^5))\n-- let path = take 19999 $ zip [1..] [2..] \n-- return $ xs ++ path\n\nmain :: IO ()\nmain = do\n printAns =<< solve =<< parse\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Road = Map Int (Map Int Int)\ntype Domain = (Road, Int, Dist)\ntype Dist = Map Int Int \ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\npairToElem :: (Int, Int) -> (Int, Map Int Int)\npairToElem (a, b) = (a, Map.singleton b 1)\n\npairToRevElem :: (Int, Int) -> (Int, Map Int Int)\npairToRevElem (a, b) = (b, Map.singleton a 1)\n\nparse :: IO Domain\nparse = do\n [cities, roadsNumber] <- readChar8\n pairs <- replicateM roadsNumber getPair\n let roads = fromListWith (Map.unionWith (+)) $ pairToElem <$> pairs\n let revRoads = fromListWith (Map.unionWith (+)) $ pairToRevElem <$> pairs\n return $ (revRoads, cities, ((+1) . sum . Map.elems) <$> roads)\n\n-- (dist, target)\ndij :: Road -> (Set (Int, Int), Dist, Set Int) -> Int\ndij roads (que, pen, visited) = -- traceShow ((d, i), newPen, que) $ \n if i == 1 then d else dij roads (newQue, newPen, Set.insert i visited)\n where ((d, i), nQue) = deleteFindMinNotMeet visited que\n children = Map.filter (`Set.notMember` visited) $ fromMaybe empty $ roads !? i\n childrenSet = Set.fromList $ Map.keys children\n newPen = Map.unionWith (-) pen children \n newQue = union (Set.map (\\j -> (d + findWithDefault 0 j newPen, j)) childrenSet) nQue\n \ndeleteFindMinNotMeet :: Set Int -> Set (Int, Int) -> ((Int, Int), Set (Int, Int))\ndeleteFindMinNotMeet visited que = if i `Set.notMember` visited then ans else deleteFindMinNotMeet visited nQue\n where ans@((d, i), nQue) = deleteFindMin que\n\nsolve :: Solver\nsolve (roads, n, pen) = dij roads (Set.singleton (0, n), pen, Set.empty)\n\nmain :: IO ()\nmain = printAns <$> solve =<< parse\n"}], "src_uid": "1a83878ec600c87e74b48d6fdda89d4e"} {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\ntestCase :: IO a -> IO ()\ntestCase f = do\n t <- read <$> getLine\n replicateM_ t f\n\nmain = testCase $ do\n [a0, a1, a2] <- map read . words <$> getLine\n [b0, b1, b2] <- map read . words <$> getLine\n print $ 2 * (min a2 b1 - max (b2 - max (a2 - b1) 0 - a0) 0)", "positive_code": [{"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> [Int] -> Int\nsolve a b = 2 * a2b1min - 2 * fuck\n where \n a2b1min = min a2 b1\n fuck = min mya1 myb2\n a0 = head a\n a1 = last $ take 2 a\n a2 = last a\n b0 = head b\n b1 = last $ take 2 b\n b2 = last b\n mya1 = a1 - min a1 b0\n myb2 = b2 - min a0 b2\n\ndeal :: IO()\ndeal = do \n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n putStrLn $ show $ solve a b\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [x1, y1, z1] <- map read . words <$> getLine :: IO [Int]\n [x2, y2, z2] <- map read . words <$> getLine\n let\n plus = min z1 y2 -- greedily pair a-2s with b-1s\n soaks = x1 + z1 - plus -- options for wasting a b-2\n minus = max 0 $ z2 - soaks\n print $ 2 * (plus - minus)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n let readSeq = fmap read . words <$> getLine\n firstSeq <- readSeq\n secondSeq <- readSeq\n print $ solve firstSeq secondSeq\n\nsolve :: [Int] -> [Int] -> Int\nsolve [x1, y1, z1] [x2, y2, z2] =\n let a = min z1 y2 -- number of pairs (2, 1)\n b = y1 - (x2 + y2 - a) -- minimum number of pairs (1, 2)\n in 2 * (a - max b 0)\n"}], "negative_code": [{"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> [Int] -> Int\nsolve a b = 2 * a2b1min - 2 * fuck\n where \n a2b1min = min a2 b1\n fuck = min mya1 myb2\n a0 = head a\n a1 = last $ take 2 a\n a2 = last a\n b0 = head b\n b1 = last $ take 2 b\n b2 = last b\n mya1 = a1 - min a1 a0\n myb2 = b2 - min a0 b2\n\ndeal :: IO()\ndeal = do \n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n putStrLn $ show $ solve a b\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> [Int] -> Int\nsolve a b = 2 * a2b1min\n where \n a2b1min = min a2 b1\n a2 = last a\n b1 = last $ take 2 b\n\ndeal :: IO()\ndeal = do \n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n putStrLn $ show $ solve a b\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> [Int] -> Int\nsolve a b = 2 * a2b1min - 2 * fuck\n where \n a2b1min = min a2 b1\n fuck = min a1 b2 - min paira1 pairb2\n a0 = head a\n a1 = last $ take 2 a\n a2 = last a\n b0 = head b\n b1 = last $ take 2 b\n b2 = last b\n paira1 = min a1 b0\n pairb2 = min a0 b2\n\ndeal :: IO()\ndeal = do \n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n putStrLn $ show $ solve a b\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}], "src_uid": "e1de1e92fac8a6db3222c0d3c26843d8"} {"source_code": "import Control.Monad ( when, forM_, replicateM_ )\r\nimport Data.Array.IO\r\n ( IOArray, readArray, writeArray, MArray(newArray) )\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Array.Unsafe (unsafeFreeze)\r\nimport System.IO\r\n ( hSetBuffering,\r\n stdout,\r\n BufferMode(BlockBuffering) )\r\nimport Text.Printf (printf)\r\nimport System.IO.Unsafe (unsafePerformIO)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\n\r\nparseInt :: C.ByteString -> Int\r\nparseInt = fst . fromJust . C.readInt\r\n \r\ngetInts :: IO [Int]\r\ngetInts = map parseInt . C.words <$> C.getLine\r\n\r\nerat stop = do\r\n sieve <- newArray (2, stop) True::IO (IOArray Int Bool)\r\n forM_ [2..stop] $ \\idx ->\r\n do\r\n isPrime <- readArray sieve idx\r\n when isPrime $\r\n forM_ [idx*2, idx*3 .. stop] $ \\k ->\r\n writeArray sieve k False\r\n pure sieve\r\n\r\nprimes max = [n | (n, isPrime) <- assocs . unsafePerformIO $ erat max >>= unsafeFreeze, isPrime]\r\n\r\nmodU = 1000000007\r\n\r\nmaxPrime = 8000\r\nallPrimes = listArray (0::Int, length genPrimes - 1) genPrimes\r\n where\r\n genPrimes = primes maxPrime\r\n\r\nreadInt::String -> Int\r\nreadInt = read\r\n\r\nsolve = do\r\n [n] <- getInts\r\n forM_ [0..(n - 1)] $ \\idx ->\r\n printf \"%d \" $ allPrimes!idx\r\n printf \"\\n\"\r\n\r\nmain = do\r\n hSetBuffering stdout $ BlockBuffering(Just 50)\r\n [t] <- getInts\r\n replicateM_ t solve", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Array.Unsafe (unsafeFreeze)\r\nimport GHC.IO (unsafePerformIO)\r\nimport Text.Printf (printf)\r\nimport System.IO (hSetBuffering, stdout, BufferMode (BlockBuffering))\r\n\r\nerat stop = do\r\n sieve <- newArray (2, stop) True::IO (IOArray Int Bool)\r\n forM_ [2..stop] $ \\idx ->\r\n do\r\n isPrime <- readArray sieve idx\r\n when isPrime $\r\n forM_ [idx*2, idx*3 .. stop] $ \\k ->\r\n writeArray sieve k False\r\n pure sieve\r\n\r\nprimes max = [n | (n, isPrime) <- assocs . unsafePerformIO $ erat max >>= unsafeFreeze, isPrime]\r\n\r\nmodU = 1000000007\r\n\r\nmaxPrime = 8000\r\nallPrimes = listArray (0::Int, (length genPrimes) - 1) $ genPrimes\r\n where\r\n genPrimes = primes maxPrime\r\n\r\nreadInt::String -> Int\r\nreadInt = read\r\n\r\nsolve = do\r\n n <- fmap readInt getLine\r\n forM_ [0..(n - 1)] $ \\idx -> \r\n printf \"%d \" $ allPrimes!idx\r\n printf \"\\n\"\r\n\r\nmain = do\r\n -- hSetBuffering stdout $ BlockBuffering(Just 0x186A0)\r\n t <- fmap readInt getLine\r\n replicateM_ t solve"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n m <- read <$> getLine\n putStrLn . intercalate \" \" . fmap show $ [2..m+1]\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Control.Monad (forM_, replicateM_, when)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Array.ST (runSTArray, newArray, readArray, writeArray)\r\nimport Data.Array.Unsafe (unsafeFreeze)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport System.IO\r\n ( BufferMode (BlockBuffering),\r\n hSetBuffering,\r\n stdout,\r\n )\r\nimport System.IO.Unsafe (unsafePerformIO)\r\nimport Text.Printf (printf)\r\n \r\nparseInt :: C.ByteString -> Int\r\nparseInt = fst . fromJust . C.readInt\r\n \r\nerat stop =\r\n runSTArray $\r\n newArray (2, stop) True\r\n >>= \\sieve ->\r\n mapM_\r\n ( \\idx ->\r\n readArray sieve idx\r\n >>= \\isPrime ->\r\n when isPrime $\r\n mapM_\r\n (\\k -> writeArray sieve k False)\r\n [idx * 2, idx * 3 .. stop]\r\n )\r\n [2 .. stop]\r\n >> return sieve\r\n \r\nprimes max = [n | (n, isPrime) <- assocs (erat max), isPrime]\r\n \r\nmodU = 1000000007\r\n \r\nmaxPrime = 8000\r\nallPrimes = listArray (0::Int, length genPrimes - 1) genPrimes\r\n where\r\n genPrimes = primes maxPrime\r\n\r\nsolve n = C.pack . unwords $ fmap (show . (allPrimes!)) [0..(n-1)]\r\n\r\nmain = C.interact $ C.lines >>> drop 1 >>> map (solve . parseInt) >>> C.unlines"}, {"source_code": "import Control.Monad ( when, forM_, replicateM_ )\r\nimport Data.Array.IO\r\n ( IOArray, readArray, writeArray, MArray(newArray) )\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Array.Unsafe (unsafeFreeze)\r\nimport System.IO\r\n ( hSetBuffering,\r\n stdout,\r\n BufferMode(BlockBuffering) )\r\nimport Text.Printf (printf)\r\nimport System.IO.Unsafe (unsafePerformIO)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Control.Arrow ((>>>))\r\n\r\nparseInt :: C.ByteString -> Int\r\nparseInt = fst . fromJust . C.readInt\r\n\r\nerat stop = do\r\n sieve <- newArray (2, stop) True::IO (IOArray Int Bool)\r\n forM_ [2..stop] $ \\idx ->\r\n do\r\n isPrime <- readArray sieve idx\r\n when isPrime $\r\n forM_ [idx*2, idx*3 .. stop] $ \\k ->\r\n writeArray sieve k False\r\n pure sieve\r\n\r\nprimes max = [n | (n, isPrime) <- assocs . unsafePerformIO $ erat max >>= unsafeFreeze, isPrime]\r\n\r\nmodU = 1000000007\r\n\r\nmaxPrime = 8000\r\nallPrimes = listArray (0::Int, length genPrimes - 1) genPrimes\r\n where\r\n genPrimes = primes maxPrime\r\n\r\nsolve n = C.pack . unwords $ fmap (show . (allPrimes!)) [0..(n-1)]\r\n\r\nmain = C.interact $ C.lines >>> drop 1 >>> map (solve . parseInt) >>> C.unlines"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Control.Monad (forM_, replicateM_, when)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Array.ST (runSTArray, newArray, readArray, writeArray)\r\nimport Data.Array.Unsafe (unsafeFreeze)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport System.IO\r\n ( BufferMode (BlockBuffering),\r\n hSetBuffering,\r\n stdout,\r\n )\r\nimport System.IO.Unsafe (unsafePerformIO)\r\nimport Text.Printf (printf)\r\n\r\nparseInt :: C.ByteString -> Int\r\nparseInt = fst . fromJust . C.readInt\r\n\r\nerat stop =\r\n runSTArray $\r\n newArray (2, stop) True\r\n >>= \\sieve ->\r\n mapM_\r\n ( \\idx ->\r\n readArray sieve idx\r\n >>= \\isPrime ->\r\n when isPrime $\r\n mapM_\r\n (\\k -> writeArray sieve k False)\r\n [idx * 2, idx * 3 .. stop]\r\n )\r\n [2 .. stop]\r\n >> return sieve\r\n\r\nprimes max = [n | (n, isPrime) <- assocs (erat max), isPrime]\r\n\r\nmodU = 1000000007\r\n\r\nmaxPrime = 8000\r\n\r\nallPrimes = listArray (0 :: Int, length genPrimes - 1) genPrimes\r\n where\r\n genPrimes = primes maxPrime\r\n\r\nsolve n = C.pack . unwords $ fmap (show . (allPrimes !)) [0 .. (n -1)]\r\n\r\nmain = C.interact $ C.lines >>> map (solve . parseInt) >>> C.unlines"}], "src_uid": "76bfced1345f871832957a65e2a660f8"} {"source_code": "main :: IO()\nmain = getContents >>= mapM_ print . solve . lines\n\nsolve :: [String] -> [Int]\nsolve (x:xs) = \n let n = head (map read (words x))\n grids = map (map read . words) (take n xs)\n rounds = map (map read . words) (drop n xs)\n scores = map row_score grids\n in solve' grids scores rounds\n where \n solve' :: [[Int]] -> [Int] -> [[Int]] -> [Int]\n solve' _ _ [] = []\n solve' grids scores ([x,y]:xs) = \n let (new_grids, new_scores, val) = (solve_at grids scores x y)\n in val:(solve' new_grids new_scores xs)\n \n row_score :: [Int] -> Int\n row_score x = row_score' x 0\n \n row_score' :: [Int] -> Int -> Int\n row_score' [] cnt = cnt\n row_score' (x:xs) cnt | x == 1 = row_score' xs (cnt+1)\n | otherwise = max cnt (row_score' xs 0)\n \n solve_at :: [[Int]] -> [Int] -> Int -> Int -> ([[Int]], [Int], Int)\n solve_at grids scores x y =\n let new_grids = update_grid grids x y 1\n new_scores = update_score new_grids scores x 1\n in (new_grids, new_scores, (max_score new_scores))\n \n update_grid :: [[Int]] -> Int -> Int -> Int -> [[Int]]\n update_grid [] _ _ _ = []\n update_grid (g:gs) x y r | x == r = (update_row g y 1):(update_grid gs x y (r+1))\n | otherwise = g:(update_grid gs x y (r+1))\n \n update_score :: [[Int]] -> [Int] -> Int -> Int -> [Int]\n update_score [] [] _ _ = []\n update_score (g:gs) (s:ss) x r | x == r = (row_score g):(update_score gs ss x (r+1))\n | otherwise = s:(update_score gs ss x (r+1))\n \n max_score :: [Int] -> Int\n max_score [] = 0\n max_score (x:xs) = max x (max_score xs)\n \n update_row :: [Int] -> Int -> Int -> [Int]\n update_row [] _ _ = []\n update_row (x:xs) y c | y == c = (1-x):(update_row xs y (c+1))\n | otherwise = x:(update_row xs y (c+1))", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine :: IO [Int]\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, q] <- getInts\n as <- replicateM n $ map read . words <$> getLine :: IO [[Int]]\n\n a <- newListArray ((1, 1), (n, m)) $ concat as :: IO (IOUArray (Int, Int) Int)\n let\n f x = if null ls then 0 else maximum ls\n where ls = map length . filter (\\g -> head g == 1) $ group x\n\n ms <- newListArray (1, n) $ map f as :: IO (IOUArray Int Int)\n\n replicateM q (do\n [i, j] <- getInts\n v <- readArray a (i, j)\n writeArray a (i, j) (1-v)\n\n c <- f <$> mapM (\\j -> readArray a (i, j)) [1..m]\n writeArray ms i c\n\n m <- maximum <$> mapM (readArray ms) [1..n]\n print m\n )\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine :: IO [Int]\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, q] <- getInts\n as <- replicateM n $ map read . words <$> getLine :: IO [[Int]]\n\n a <- newListArray ((1, 1), (n, m)) $ concat as :: IO (IOUArray (Int, Int) Int)\n let\n f x = if null ls then 0 else maximum ls\n where ls = map length . filter (\\g -> head g == 1) $ group x\n\n ms <- newListArray (1, n) $ map f as :: IO (IOUArray Int Int)\n\n replicateM q (do\n [i, j] <- getInts\n v <- readArray a (i, j)\n writeArray a (i, j) (1-v)\n\n c <- readArray ms i\n writeArray ms i (c-v+(1-v))\n\n m <- maximum <$> mapM (readArray ms) [1..n]\n print m\n )\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine :: IO [Int]\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, q] <- getInts\n as <- replicateM n $ map read . words <$> getLine :: IO [[Int]]\n\n a <- newListArray ((1, 1), (n, m)) $ concat as :: IO (IOArray (Int, Int) Int)\n\n replicateM q (do\n [i, j] <- getInts\n readArray a (i, j) >>= \\v -> writeArray a (i, j) (1-v)\n\n s <- maximum <$> mapM (\\i -> sum <$> mapM (\\j -> readArray a (i, j)) [1..m]) [1..n]\n print s\n )\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine :: IO [Int]\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, q] <- getInts\n as <- replicateM n $ map read . words <$> getLine :: IO [[Int]]\n\n a <- newListArray ((1, 1), (n, m)) $ concat as :: IO (IOArray (Int, Int) Int)\n\n replicateM q (do\n [i, j] <- getInts\n readArray a (i, j) >>= \\v -> writeArray a (i, j) (1-v)\n\n s <- maximum <$> mapM (\\i -> maximum . map length . group <$> mapM (\\j -> readArray a (i, j)) [1..m]) [1..n]\n print s\n )\n"}], "src_uid": "337b6d2a11a25ef917809e6409f8edef"} {"source_code": "import Control.Monad\n\nmain = do\n q <- readInt\n submain q\n return q\n \nreadInt = do\n raw_q <- getLine\n let q = read raw_q :: Int\n return q\n \nreadlist = do\n inp <- getLine\n let v = words inp\n let ret = map read v\n return ret\n\nsubmain:: Int -> IO ()\nsubmain q = do\n when (q > 0) $ do\n sz <- readInt\n v <- readlist \n putStrLn $ if (solve v sz) then \"YES\" else \"NO\"\n submain $ q - 1\n return ()\n\nsolve :: [Int] -> Int -> Bool\nsolve [] _ = False\nsolve v sz = cw (+) v sz || cw (-) v sz \n\ncw :: (Int -> Int -> Int) -> [Int] -> Int -> Bool\ncw _ [] _ = True\ncw _ (x:[]) _ = True\ncw f (x:y:xs) sz = nextTerm && (toNext || toFirst) \n where nextTerm = cw f (y:xs) sz\n toNext = y == (f x 1)\n toFirst = y == (f x (1 - sz))\n\n\n\n\ndata Point = Point Float Float\nmyfun p1 p2 = distance p1 p2\ndistance (Point x1 y1) (Point x2 y2) = \n sqrt $ dx * dx + dy * dy \n where dx = x1 - x2\n dy = y1 - y2\n", "positive_code": [{"source_code": "import Control.Monad\n\nreadInt :: String -> Int\nreadInt = read\n\nyesno :: Bool -> String\nyesno x = if x\n then \"YES\"\n else \"NO\"\n\nprintLines :: [String] -> IO ()\nprintLines x = mapM_ putStrLn x\n\nreadLines :: Int -> IO [String]\nreadLines x = replicateM x $\n do\n _ <- getLine\n getLine\n\noneGreater x y = y == x + 1\n\nisPerm :: Int -> [Int] -> Bool\nisPerm _ [] = True\nisPerm _ [x] = True\nisPerm len (x:y:xs) = (x `mod` len) + 1 == y && isPerm len (y:xs)\n\ncheck :: [Int] -> Bool\ncheck list = a || b\n where a = isPerm (length list) list\n b = isPerm (length list) $ reverse list\n\ngetList :: String -> [Int]\ngetList x = map read (words x)\n\nmain = do\n q <- getLine\n input <- readLines (readInt q)\n printLines $ map yesno $ map (check . getList) input\n\n\n \n"}], "negative_code": [{"source_code": "import Control.Monad\n\nreadInt :: String -> Int\nreadInt = read\n\nyesno :: Bool -> String\nyesno x = if x\n then \"YES\"\n else \"NO\"\n\nprintLines :: [String] -> IO ()\nprintLines x = mapM_ putStrLn x\n\nreadLines :: Int -> IO [String]\nreadLines x = replicateM x $\n do\n _ <- getLine\n getLine\n\noneGreater x y = y == x + 1\n\nwraps len x y = x == len - 1 && y == 1\n\nisPerm :: Int -> [Int] -> Bool\nisPerm _ [] = True\nisPerm _ [x] = True\nisPerm len (x:y:xs) = (oneGreater x y || wraps len x y) && isPerm len xs\n\ncheck :: [Int] -> Bool\ncheck list = a || b\n where a = isPerm (length list) list\n b = isPerm (length list) $ reverse list\n\ngetList :: String -> [Int]\ngetList x = map read (words x)\n\nmain = do\n q <- getLine\n input <- readLines (readInt q)\n printLines $ map yesno $ map (check . getList) input\n\n\n \n"}], "src_uid": "b27436086ead93397be748d8ebdbf19a"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Maybe\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n \r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n s <- getLine\r\n [w] <- ri\r\n return (s, w)\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve (s,w) = map fst . L.sortOn snd . drop delCnt $ wi\r\n where\r\n wi = L.sortBy (flip compare) . (`zip`inds) $ s\r\n\r\n psums = scanl add 0 wi where add n (c,_) = n + (1 + (ord c - ord 'a'))\r\n \r\n cost = last psums\r\n delCost = cost - w\r\n \r\n delCnt = fromJust . L.findIndex (>=delCost) $ psums\r\n\r\ninds = [1..] :: [Int]\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe\r\n\r\n--\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport qualified Data.Map.Strict as M\r\n\r\nsolve :: (C.ByteString, Int) -> C.ByteString\r\nsolve (s, p) = C.pack $ map (\\x -> chr $ x + ord 'a' - 1) res\r\n where\r\n s' = map (\\c -> 1 + ord c - ord 'a') $ C.unpack s\r\n ogLocs = M.fromListWith (++) [(x, [i]) | (x, i) <- zip s' [0 ..]]\r\n\r\n rm [] = Nothing\r\n rm [_] = Nothing\r\n rm (x : xs) = Just xs\r\n\r\n work ls c\r\n | c <= p = ls\r\n | otherwise = case M.lookupMax ls of\r\n Just (x, _) -> work (M.update rm x ls) (c - x)\r\n Nothing -> ls\r\n finalLocs = work ogLocs (sum s')\r\n\r\n res = map fst $ sortOn snd [(x, i) | (x, is) <- M.toList finalLocs, i <- is]\r\n\r\ninput :: Scanner (C.ByteString, Int)\r\ninput = (,) <$> bstr <*> int\r\n\r\noutput :: C.ByteString -> C.ByteString\r\noutput = id\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\n-- Scanner\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: String -> Int -> String\nsolve s p = solve'\n where\n maxA :: Int\n maxA = ord 'z' - ord 'a' + 1\n\n priceC :: Char -> Int\n priceC c = ord c - ord 'a' + 1\n\n sortedC :: [Char]\n sortedC = reverse $ sort s\n\n sPrice :: Int\n sPrice = sum . map priceC $ s\n\n finalStringChars :: [Char]\n finalStringChars = finalStringChars' (sPrice - p) sortedC\n\n finalStringChars' :: Int -> [Char] -> [Char]\n finalStringChars' price cs | price <= 0 = cs\n finalStringChars' price (c:otherCs) = finalStringChars' (price - priceC c) otherCs\n\n solve' :: String\n solve' = ST.runST $ do\n cntA <- MA.newArray (1, maxA) 0 :: ST.ST s (STA.STUArray s Int Int)\n forM_ finalStringChars $ \\c -> do\n modifyArray cntA (priceC c) succ\n\n flip S.execStateT ([] :: String) $ do\n forM_ (reverse s) $ \\c -> do\n cnt <- T.lift $ MA.readArray cntA (priceC c)\n M.when (cnt > 0) $ do\n T.lift $ modifyArray cntA (priceC c) pred\n S.modify (c:)\n return ()\n\n\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n s <- B8.getLine <&> B8.unpack . head . B8.words\n p <- B8.getLine <&> readIntB8\n let answer = solve s p\n B8.putStrLn $ B8.pack answer\n\n"}], "negative_code": [], "src_uid": "cb645c794ee3916b180fc3d789cb7c27"} {"source_code": "\nimport Data.Map (Map, empty, keys, fromListWith, member, (!))\n\n{-\n--------------------------------------------------------------------------------\n\nimport HUnit\n\ntestNoMessage :: Test\ntestNoMessage = Test \"TestNoMessage\" $\n assertEq [] (solve 0 [])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\" \n [Test \"1\" $ assertEq [(\"petya\", \"vasya\")] (solve 1\n [(\"vasya\", \"petya\", 1),\n (\"petya\", \"vasya\", 2),\n (\"anya\", \"ivan\", 2),\n (\"ivan\", \"anya\", 4)\n ]),\n Test \"2\" $ assertEq [] (solve 1000 [(\"a\", \"b\", 0)])]\n \n\ntestOnePairs :: Test\ntestOnePairs = Test \"TestOnePairs\" $\n assertEq [(\"petya\", \"vasya\")]\n (solve 1000 [\n (\"petya\", \"vasya\", 1),\n (\"vasya\", \"petya\", 2)\n ])\n\ntestTwoPairs :: Test\ntestTwoPairs = Test \"TestTwoPairs\" $\n assertEq [(\"anya\", \"ivan\"), (\"petya\", \"vasya\")] (solve 1000\n [(\"vasya\", \"petya\", 1),\n (\"petya\", \"vasya\", 2),\n (\"anya\", \"ivan\", 2),\n (\"ivan\", \"anya\", 4)\n ])\n\ntestOneMessage :: Test\ntestOneMessage = TestList \"TestOneMessage\"\n [Test \"1\" $\n assertEq [] (solve 1000 [(\"vasya\", \"petya\", 1)]),\n Test \"2\" $\n assertEq [] (solve 1000 [(\"petya\", \"vasya\", 1)])\n ]\n\ntestNotMessageFromIvanToVasya :: Test\ntestNotMessageFromIvanToVasya = Test \"TestNotMessageFromIvanToVasya\" $\n assertEq [] (solve 1000\n [(\"ivan\", \"petya\", 1),\n (\"anya\", \"vasya\", 2),\n (\"vasya\", \"ivan\", 3)])\n\ntestSynchronousMessages :: Test\ntestSynchronousMessages = Test \"TestSynchronousMessages\" $\n assertEq [] (solve 1000 [(\"petya\", \"vasya\", 1), (\"vasya\", \"petya\", 1)])\n\ntestOneFriendButManyMessages :: Test\ntestOneFriendButManyMessages = Test \"TestOneFriendButManyMessages\" $\n assertEq [(\"petya\", \"vasya\")]\n (solve 1 [\n (\"petya\", \"vasya\", 1),\n (\"vasya\", \"petya\", 2),\n (\"petya\", \"vasya\", 5),\n (\"vasya\", \"petya\", 6),\n (\"petya\", \"vasya\", 8),\n (\"vasya\", \"petya\", 9),\n (\"petya\", \"vasya\", 100),\n (\"vasya\", \"petya\", 101)\n ])\n\ntestAllFriends :: Test\ntestAllFriends = Test \"TestAllFriends\" $\n assertEq [(\"a\",\"b\"),(\"a\",\"c\"),(\"a\",\"d\"),(\"b\",\"c\"),(\"b\",\"d\"),(\"c\",\"d\")]\n (solve 3 [\n (\"a\",\"b\",0),(\"a\",\"c\",0),(\"a\",\"d\",0),\n (\"b\",\"a\",1),(\"b\",\"c\",1),(\"b\",\"d\",1),\n (\"c\",\"a\",2),(\"c\",\"b\",2),(\"c\",\"d\",2),\n (\"d\",\"a\",3),(\"d\",\"b\",3),(\"d\",\"c\",3)\n ])\n\ntestBig :: Test\ntestBig = Test \"TestBig\" $\n assertEq [] (solve 1000000\n (map (\\n -> (longNameA n, longNameB n, n)) [1..1000]))\n\nlongNameA :: Int -> String\nlongNameA n = replicate 17 'a'\n ++ [(toEnum (fromEnum 'a' + mod n 26)), (toEnum (fromEnum 'a' + mod (div n 26) 26)),\n (toEnum (fromEnum 'a' + div (div n 26) 26))]\n\nlongNameB :: Int -> String\nlongNameB n = replicate 17 'b'\n ++ [(toEnum (fromEnum 'a' + mod n 26)), (toEnum (fromEnum 'a' + mod (div n 26) 26)),\n (toEnum (fromEnum 'a' + div (div n 26) 26))]\n\ntestManyMessages :: Test\ntestManyMessages = Test \"TestManyMessages\" $\n assertEq []\n (solve 1 (take 1000 (zip3 (cycle [a, b]) (cycle [b, a]) [0,2..])))\n where\n a = longNameA 0\n b = longNameB 0\n\ntests :: Test\ntests = TestList \"Testing ... \"\n [testNoMessage,\n testInput,\n testOnePairs,\n testTwoPairs,\n testOneMessage,\n testNotMessageFromIvanToVasya,\n testSynchronousMessages,\n testOneFriendButManyMessages,\n testAllFriends,\n testBig,\n testManyMessages\n ]\n\ntest :: IO ()\ntest = run tests\n\n--------------------------------------------------------------------------------\n-}\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nreadMessage :: IO (String, String, Int)\nreadMessage = do\n line <- getLine\n let [s1, s2, s3] = words line\n return (s1, s2, read s3)\n\nfriend :: Int -> Map (String, String) [Int] -> (String, String) -> Bool\nfriend d map' (n1, n2)\n | n1 < n2 && member (n2, n1) map' = friend' (map' ! (n1, n2)) (map' ! (n2, n1))\n | otherwise = False\n where\n friend' ts1 ts2 = not $ null [(t1, t2) | t1 <- ts1, t2 <- ts2, t1 /= t2, abs (t1 - t2) <= d]\n\nsolve :: Int -> [(String, String, Int)] -> [(String, String)]\nsolve d ms = filter (friend d map') (keys map')\n where\n map' = fromListWith (++) (map (\\(n1, n2, t) -> ((n1, n2), [t])) ms)\n\nprintAns :: [(String, String)] -> IO ()\nprintAns friends = do\n print (length friends)\n mapM_ (\\(s1, s2) -> putStrLn $ concat [s1, \" \", s2]) friends\n\nmain :: IO ()\nmain = do\n [n, d] <- Main.reads\n messages <- mapM (const readMessage) [1..n]\n printAns $ solve d messages\n", "positive_code": [{"source_code": "import System.IO\nimport List (nub)\n\nreadInt :: String -> Int\nreadInt s = read s\n\nsplit :: String -> Char -> [String]\nsplit [] _ = []\nsplit (x:xs) c = y : ys\n where (y, xs') = break (== c) (x:xs)\n ys | xs' == [] = []\n | otherwise = split (tail xs') c\n \nfst3 (x, _, _) = x\nsnd3 (_, y, _) = y\nthd3 (_, _, z) = z\n \nformat :: [String] -> [(String, String, Int)]\nformat xs = map f xs\n where f x = (y !! 0, y !! 1, readInt (y !! 2))\n where y = split x ' '\n\nisFriends :: Int -> (String, String, Int) -> (String, String, Int) -> Bool\nisFriends d (a1, b1, t1) (a2, b2, t2) = (a1 == b2) && (b1 == a2) && (t2 - t1 <= d) && (t2 - t1 > 0)\n\n\ngetFriends :: Int -> [(String, String, Int)] -> [(String, String)]\ngetFriends _ [x] = []\ngetFriends d (x1@(a1, b1, t1):xs) = nub (map f (filter (isFriends d x1) xs) ++ getFriends d xs)\n where f (a, b, c) = (min a b, max a b)\n\nlist2string :: Show a => [a] -> String\nlist2string xs = foldr f \"\" xs\n where f x y = (show x ++ \"\\n\" ++ y)\n\n\noutput :: [(String, String)] -> String\noutput xs = show (length xs) ++ \"\\n\" ++ (unlines $ map (\\(x, y) -> x ++ \" \" ++ y) xs)\n\nmain :: IO()\nmain = do\n nd <- getLine\n journal <- getContents\n let d = readInt $ head $ tail $ split nd ' '\n in putStr (output $ getFriends d $ format $ lines journal)"}, {"source_code": "import Data.List\nimport Control.Monad\n\nswap (a, b) = (b, a)\n\nsolve d events =\n nubBy (\\a b -> a == b || a == swap b)\n [(a1, b1) |\n (a1, b1, t1) <- events,\n (a2, b2, t2) <- events,\n a1 == b2, b1 == a2, t1 < t2,\n t2 - t1 <= d]\n\ngetEvent = do [name1, name2, t] <- fmap words getLine\n return (name1, name2, read t)\n\nprintFriends (name1, name2) =\n putStrLn (name1 ++ \" \" ++ name2)\n\nmain = do [n, d] <- fmap (map read . words) getLine\n events <- replicateM n getEvent\n \n let friends = solve d events\n \n putStrLn $ show $ length friends\n sequence_ $ map printFriends friends"}, {"source_code": "import qualified Data.Set as S\nimport Control.Monad\nmain = do\n [n,d] <- liftM (map read . words) getLine\n ms <- replicateM n (liftM parse getLine)\n let fs = S.fromList $ do\n (a,b,t1) <- ms\n (a',b',t2) <- ms\n guard $ a == b' && b == a' && t2 - t1 > 0 && t2 - t1 <= d\n return (minMax a b)\n print (S.size fs)\n forM_ (S.elems fs) $ \\(a,b) -> putStrLn $ a ++ \" \" ++ b\nparse l = (a,b,read t) where [a,b,t] = words l\nminMax a b = (min a b,max a b)\n"}, {"source_code": "import Data.List\n\ntype Call = (String,String,Int)\n\nmain ::IO ()\nmain = \n do cs <- getContents\n (putStr . showSolve . solve . pIn) cs\n\nshowSolve ::[Call] ->String\nshowSolve [] = \"0\"\nshowSolve xs = \n (show .length) xs ++ (showPair xs)\n\nshowPair::[Call]->String\nshowPair [] = \"\"\nshowPair ((a,b,_):xs) = \n \"\\n\" ++a ++ \" \" ++ b ++showPair xs \n\nchg::[String]->(String,String,Int)\nchg [s1,s2,s3] = (s1,s2,read s3::Int)\n\npIn :: String->(Int,[Call])\npIn s = \n (d,fs)\n where\n s1:s2 = lines s\n [_,d] = map read $ words s1\n fs = map (\\x -> chg $ words x) s2\n\nchk :: Int->Call->Call->Bool\nchk d (a1,b1,t1) (a2,b2,t2)= \n a2==b1 && a1==b2&& 0< t2-t1 && t2-t1 <=d\n\nisNoPair ::Call->Call->Bool\nisNoPair (a1,b1,_) (a2,b2,_) = not ((a1==a2 && b1==b2) || (a1==b2 && b1==a2))\n\nsolve ::(Int,[Call])->[Call]\nsolve pin = solveC pin [] \n \n \nsolveC ::(Int,[Call])->[Call] -> [Call]\nsolveC (_,[]) ret = ret\nsolveC (d,(x:xs)) ret =\n if any (chk d x) xs\n then solveC (d,(filter (isNoPair x) xs)) (x:ret)\n else solveC (d,xs) ret\n"}], "negative_code": [{"source_code": "\nimport List\n\ntype People = String\ntype Message = ((People, People), Int)\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\ngetLines :: Int -> IO [String]\ngetLines n = sequence (replicate n getLine)\n\nparse :: String -> Message\nparse line = ((w1, w2), read w3)\n where\n [w1, w2, w3] = words line\n\ngetPeoples :: [Message] -> [People]\ngetPeoples ms = nub (map (fst . fst) ms)\n\nfriend :: Int -> [Message] -> (People, People) -> Bool\nfriend d ms (p1, p2) = length friends > 0\n where\n friends = do\n m1 <- filter (\\m -> fst m == (p1, p2)) ms\n m2 <- filter (\\m -> fst m == (p2, p1)) ms\n if abs (snd m1 - snd m2) <= d then [(p1, p2)] else []\n\nallPairs :: [a] -> [(a, a)]\nallPairs xs = [(xs !! i, xs !! j) | i <- [0..n-1], j <- [0..n-1], i < j]\n where\n n = length xs\n\nsolve :: Int -> [Message] -> [(People, People)]\nsolve d ms = filter (friend d ms) (allPairs (getPeoples ms))\n\nprintAns :: [(People, People)] -> IO ()\nprintAns fs = print (length fs) >> sequence_ (map printAns' fs)\n where\n printAns' :: (People, People) -> IO ()\n printAns' (p1, p2) = putStr p1 >> putStr \" \" >> putStrLn p2\n\nmain = do\n [n, d] <- Main.reads\n lines <- getLines n\n let ms = map parse lines\n printAns (solve d ms)\n"}, {"source_code": "import System.IO\nimport List (nub)\n\nreadInt :: String -> Int\nreadInt s = read s\n\nsplit :: String -> Char -> [String]\nsplit [] _ = []\nsplit (x:xs) c = y : ys\n where (y, xs') = break (== c) (x:xs)\n ys | xs' == [] = []\n | otherwise = split (tail xs') c\n \nfst3 (x, _, _) = x\nsnd3 (_, y, _) = y\nthd3 (_, _, z) = z\n \nformat :: [String] -> [(String, String, Int)]\nformat xs = map f xs\n where f x = (y !! 0, y !! 1, readInt (y !! 2))\n where y = split x ' '\n\nisFriends :: Int -> (String, String, Int) -> (String, String, Int) -> Bool\nisFriends d (a1, b1, t1) (a2, b2, t2) = (a1 == b2) && (b1 == a2) && (t2 - t1 <= d)\n\n\ngetFriends :: Int -> [(String, String, Int)] -> [(String, String)]\ngetFriends _ [x] = []\ngetFriends d (x1@(a1, b1, t1):xs) = nub (map f (filter (isFriends d x1) xs) ++ getFriends d xs)\n where f (a, b, c) = (min a b, max a b)\n\nlist2string :: Show a => [a] -> String\nlist2string xs = foldr f \"\" xs\n where f x y = (show x ++ \"\\n\" ++ y)\n\n\noutput :: [(String, String)] -> String\noutput xs = show (length xs) ++ \"\\n\" ++ (unlines $ map (\\(x, y) -> x ++ \" \" ++ y) xs)\n\nmain :: IO()\nmain = do\n nd <- getLine\n journal <- getContents\n let d = readInt $ head $ tail $ split nd ' '\n in putStr (output $ getFriends d $ format $ lines journal)"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nmain = do\n [n,d] <- liftM (map read . words) getLine\n ms <- replicateM n $ liftM words getLine\n let (_,s) = foldl' (ack d) (M.empty,S.empty) ms\n print (S.size s)\n forM_ (S.elems s) $ \\(a,b) -> putStrLn $ a ++ \" \" ++ b\nack d (m,s) [a,b,t]\n | isJust (M.lookup (b,a) m >>= guard . uncurry (&&) . ((> 0) &&& (<= d)) . ((read t) -)) \n = (m,S.insert (minMax a b) s)\n | otherwise\n = (M.insert (a,b) (read t) m,s)\nminMax a b = (min a b,max a b)\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nmain = do\n [n,d] <- liftM (map read . words) getLine\n ms <- replicateM n $ liftM words getLine\n let (_,s) = foldl' (ack d) (M.empty,S.empty) ms\n print (S.size s)\n forM_ (S.elems s) $ \\(a,b) -> putStrLn $ a ++ \" \" ++ b\nack d (m,s) [a,b,t]\n | isJust (M.lookup (b,a) m >>= guard . (<= d) . ((read t) -)) \n = (m,S.insert (minMax a b) s)\n | otherwise\n = (M.insert (a,b) (read t) m,s)\nminMax a b = (min a b,max a b)\n"}, {"source_code": "import Data.Ord\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Control.Monad\nimport Control.Arrow\nmain = do\n [n,d] <- liftM (map read . words) getLine\n ms <- replicateM n (liftM parse getLine)\n let (_,fs) = foldl' (process d) (M.empty,S.empty) $ sortBy (comparing thd) ms\n print (S.size fs)\n forM_ (S.elems fs) $ \\(a,b) -> putStrLn $ a ++ \" \" ++ b\nparse l = (a,b,read t) where [a,b,t] = words l\nprocess d (l,f) (a,b,t) | isReciprocal = s' `seq` (l',s')\n | otherwise = (l',f)\n where isReciprocal = l' `seq`\n maybe False (uncurry (&&) . ((>0) &&& (<=d)) . (t-))\n (M.lookup (b,a) l)\n l' = M.insert (a,b) t l\n s' = S.insert (minMax a b) f\nminMax = min &&& max >>> uncurry (&&&)\nthd (_,_,t) = t"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nmain = do\n [n,d] <- liftM (map read . words) getLine\n ms <- replicateM n $ liftM words getLine\n let (_,s) = foldl' (ack d) (M.empty,S.empty) ms\n print (S.size s)\n forM_ (S.elems s) $ \\(a,b) -> putStrLn $ a ++ \" \" ++ b\nack d (m,s) [a,b,t]\n | isJust (M.lookup (b,a) m >>= guard . uncurry (&&) .\n ((> 0) &&& (<= d)) . (read t -))\n = (M.insert (a,b) (read t) m,S.insert (minMax a b) s)\n | otherwise\n = (M.insert (a,b) (read t) m,s)\nminMax a b = (min a b,max a b)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Control.Monad\nimport Control.Arrow\nmain = do\n [n,d] <- liftM (map read . words) getLine\n ms <- replicateM n (liftM parse getLine)\n let (_,fs) = foldl' (process d) (M.empty,S.empty) ms\n print (S.size fs)\n forM_ (S.elems fs) $ \\(a,b) -> putStrLn $ a ++ \" \" ++ b\nparse l = (a,b,read t) where [a,b,t] = words l\nprocess d (l,f) (a,b,t) | isReciprocal = s' `seq` (l',s')\n | otherwise = (l',f)\n where isReciprocal = l' `seq`\n liftM (uncurry (&&) . ((>0) &&& (<=d)) . (t-))\n (M.lookup (b,a) l)\n == Just True\n l' = M.insert (a,b) t l\n s' = S.insert (minMax a b) f\nminMax a b = (min a b,max a b)"}, {"source_code": "import Data.List\n\ntype Call = (String,String,Int)\n\nmain ::IO ()\nmain = \n do cs <- getContents\n (putStr . showSolve . solve . pIn) cs\n\nshowSolve ::[Call] ->String\nshowSolve [] = \"0\"\nshowSolve xs = \n (show .length) xs ++ (showPair xs)\n\nshowPair::[Call]->String\nshowPair [] = \"\"\nshowPair ((a,b,_):xs) = \n \"\\n\" ++a ++ \" \" ++ b ++showPair xs \n\nchg::[String]->(String,String,Int)\nchg [s1,s2,s3] = (s1,s2,read s3::Int)\n\npIn :: String->(Int,[Call])\npIn s = \n (d,fs)\n where\n s1:s2 = lines s\n [_,d] = map read $ words s1\n fs = map (\\x -> chg $ words x) s2\n\nchk :: Int->Call->Call->Bool\nchk d (a1,b1,t1) (a2,b2,t2)= \n a2==b1 && a1==b2&& 0< t2-t1 && t2-t1 <=d\n\nisPair ::Call->Call->Bool\nisPair (a1,b1,_) (a2,b2,_) = (a1==a2 && b1==b2) || (a1==b2 && b1==a2) \n\nsolve ::(Int,[Call])->[Call]\nsolve pin = solveC pin [] \n \n \nsolveC ::(Int,[Call])->[Call] -> [Call]\nsolveC (_,[]) ret = ret\nsolveC (d,(x:xs)) ret =\n if any (chk d x) xs \n then solveC (d,(filter (isPair x) xs)) (filter (isPair x) (x:ret))\n else solveC (d,xs) ret\n"}], "src_uid": "3cb4c89b174bf5ea51e797b78103e089"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = B.getContents >>= print . evalState app . B.words\n\napp = do\n n <- poi\n a <- poi\n b <- poi\n ss <- replicateM n $ liftM2 (,) poi poi\n return $ solve a b ss\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve a b = maximum . (0:) . map (\\((x1, y1), (x2, y2)) -> x1 * y1 + x2 * y2) . filter (\\((x1, y1), (x2, y2)) -> ok x1 y1 x2 y2 || ok x1 y1 y2 x2 || ok y1 x1 x2 y2 || ok y1 x1 y2 x2) . pairs\n where ok x1 y1 x2 y2 = x1 + x2 <= a && max y1 y2 <= b || y1 + y2 <= b && max x1 x2 <= a\npairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, h, w ] <- readInts\n\t[ xs, ys ] <- transpose <$> replicateM n readInts\n\tlet\n\t\tsolve2 f = maximum $ ( 0 : ) $ [ f ( xs !! i ) ( ys !! i ) ( xs !! j ) ( ys !! j ) | i <- [ 0 .. n - 1 ], j <- [ 0 .. n - 1 ], i /= j ]\n\tprint $ max ( solve2 $ solve h w ) ( solve2 $ solve w h )\n\nsolve h w x1 y1 x2 y2\n\t| x1 + x2 <= h && max y1 y2 <= w = res\n\t| x1 + y2 <= h && max y1 x2 <= w = res\n\t| y1 + y2 <= h && max x1 x2 <= w = res\n\t| otherwise = 0\n\twhere\n\t\tres = ( x1 * y1 ) + ( x2 * y2 )\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, h, w ] <- readInts\n\t[ xs, ys ] <- transpose <$> replicateM n readInts\n\tlet\n\t\tsolve2 f = maximum $ ( 0 : ) $ [ f ( xs !! i ) ( ys !! i ) ( xs !! j ) ( ys !! j ) | i <- [ 0 .. n - 1 ], j <- [ 0 .. n - 1 ], i /= j ]\n\tprint $ max ( solve2 $ solve h w ) ( solve2 $ solve w h )\n\nsolve h w x1 y1 x2 y2\n\t| x1 + x2 <= h && max y1 y2 <= w = res\n\t| x1 + y2 <= h && max y1 x2 <= w = res\n\t| otherwise = 0\n\twhere\n\t\tres = ( x1 * y1 ) + ( x2 * y2 )\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, h, w ] <- readInts\n\t[ xs, ys ] <- transpose <$> replicateM n readInts\n\tprint $ maximum $ ( 0 : ) $ [ solve h w ( xs !! i ) ( ys !! i ) ( xs !! j ) ( ys !! j ) | i <- [ 0 .. n - 1 ], j <- [ 0 .. i - 1 ] ]\n\nsolve h w x1 y1 x2 y2\n\t| x1 + x2 <= h && max y1 y2 <= w = res\n\t| x1 + y2 <= h && max y1 x2 <= w = res\n\t| x1 + x2 <= w && max y1 y2 <= h = res\n\t| x1 + y2 <= w && max y1 x2 <= h = res\n\t| x2 + x1 <= h && max y2 y1 <= w = res\n\t| x2 + y1 <= h && max y2 x1 <= w = res\n\t| x2 + x1 <= w && max y2 y1 <= h = res\n\t| x2 + y1 <= w && max y2 x1 <= h = res\n\t| otherwise = 0\n\twhere\n\t\tres = ( x1 * y1 ) + ( x2 * y2 )\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = B.getContents >>= print . evalState app . B.words\n\napp = do\n n <- poi\n a <- poi\n b <- poi\n ss <- replicateM n $ liftM2 (,) poi poi\n return $ solve a b ss\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve a b = maximum . (0:) . map (\\((x1, y1), (x2, y2)) -> x1 * y1 + x2 * y2) . filter (\\((x1, y1), (x2, y2)) -> x1 + x2 <= a && max y1 y2 <= b || x1 + y2 <= a && max y1 x2 <= b || y1 + y2 <= b && max x1 x2 <= a || y1 + x2 <= b && max x1 y2 <= a) . pairs\npairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]"}], "src_uid": "1ad63f41943e40aa8c8d5c88c29c283c"} {"source_code": "import Data.List (sort)\nimport Data.Traversable (for)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n _ <- for [1..t] $ \\_ -> do\n _n <- read <$> getLine :: IO Int\n a <- (map read . words) <$> getLine :: IO [Int]\n let s = zip [1..] (sort a)\n ans = 0 : [x | (x, k) <- s, x >= k]\n print (1 + last ans)\n return ()\n\n\n", "positive_code": [{"source_code": "import Data.List as L\n\nsolve' :: Int -> Int -> [Int] -> Int\nsolve' _ bestSoFar [] = bestSoFar\nsolve' idx bestSoFar (x:rest)\n | idx >= x = solve' (idx+1) idx rest\n | otherwise = solve' (idx+1) bestSoFar rest\n\nsolve :: [Int] -> Int\nsolve arr = 1 + solve' 0 0 sorted\n where sorted = 0:(L.sort arr)\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))\n\nparse :: [String] -> String\nparse [_, input] = show $ solve arr\n where arr = map (\\x -> read x :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2. tail .lines)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- reverse . sort . (1 :) . map read . words <$> getLine\n print $ solve (length as) as\n\nsolve _ [] = 1\nsolve n (a:as)\n | a > n - 1 = solve (n - 1) as\n | otherwise = n"}, {"source_code": "import Data.List\n\n\nsolve :: [[Int]] -> [Int]\nsolve [] = []\nsolve (x:y:ys) = (count (x) (reverse (sort y))) : (solve ys)\n\ncount :: [Int] -> [Int] -> Int\ncount [0] _ = 1\ncount [n] (x:xs)\n\t| x <= n \t= \tn + 1\n\t| otherwise = \tcount [n-1] xs\n\n\n\n\n\nmain = do\n\tt' <- getLine\n\tlet t = read t' :: Int\n\tfin <- getContents\n\tlet input = map (map read) (map words (take (2*t) (lines fin))) :: [[Int]]\n\tlet result = solve input\n\tmapM print result"}, {"source_code": "import Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\nsplit = _split [] \"\"\n\n_indexed acc _ [] = reverse acc\n_indexed acc i (x:xs) = _indexed ((i,x):acc) (i+1) xs\nindexed = _indexed [] 0\n\nmain = do\n input <- getContents\n let (_:tokens) = split input\n vals = read <$> tokens :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n:rest ->\n let (thisCase, rest') = splitAt n rest\n sorted = sort thisCase\n cands = filter (\\(i, val) -> val <= (i+1)) $ indexed sorted\n subres = case cands of\n [] -> 1\n _ -> 2 + (fst $ last cands)\n in Just (subres, rest')\n ) vals\n sequence_ (putStrLn <$> (show <$> res))\n"}], "negative_code": [], "src_uid": "718cea81f609055cece58cae5310f703"} {"source_code": "module Main where\n\nimport Control.Monad\n\nshoot :: [Int] -> [Int] -> [Int]\nshoot birds shot = let [wire, bird] = shot\n birdsOnShotWire = birds!!(wire - 1)\n birdsToMin = bird - 1\n birdsToMax = birdsOnShotWire - birdsToMin - 1\n totalWires = length birds\n birdsDiff = (replicate (wire - 2) 0)\n ++ (if wire == 1\n then [-birdsOnShotWire, birdsToMax]\n else\n if wire == totalWires\n then [birdsToMin, -birdsOnShotWire]\n else [birdsToMin, -birdsOnShotWire, birdsToMax])\n ++ (replicate (totalWires - wire - 1) 0)\n in\n zipWith (+) birds birdsDiff\n\nmain = do\n birds <- liftM (map read . words) (getLine >> getLine)\n shots <- liftM (map (map read . words) . lines) (getLine >> getContents)\n mapM_ print $ foldl shoot birds shots", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n\ngao :: Array Int Int -> (Int, Int) -> Array Int Int\ngao a (x, y) = a // [(i, a!i + j) | (i, j) <- d, bounds a `inRange` i]\n where\n z = a!x\n d = [(x - 1, y - 1), (x, -z), (x + 1, z - y)]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n a <- listArray (1, n) . map read . words <$> getLine\n m <- read <$> getLine\n b <- replicateM m $ do\n [i, j] <- map read . words <$> getLine\n return (i, j)\n putStr $ unlines $ map show $ elems $ foldl gao a b\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array (Array(), (!), (//), elems, listArray)\nimport Prelude hiding (reads)\n\nreadPair :: Read a => IO (a, a)\nreadPair = do\n [x, y] <- reads\n return (x, y)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Array Int Int -> [(Int, Int)] -> Array Int Int\nsolve array [] = array\nsolve array ((x, y) : xs) = solve array' xs\n where\n array' = array // [(x, 0), (x - 1, array ! (x - 1) + (y - 1)), (x + 1, array ! (x + 1) + (array ! x) - y)]\n\nprint' :: Array Int Int -> IO ()\nprint' = mapM_ print . tail . init . elems\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- reads\n let array = listArray (0, n+1) (0 : xs ++ [0])\n m <- readLn\n shoots <- replicateM m readPair\n print' $ solve array shoots"}, {"source_code": "import Data.List\n\nf::Int->Int->Int->[Int]->[Int]\nf 1 1 t (x:[])=[0]\nf 1 1 t (x:y:xs)=0:(y+x-t):xs\nf n m t (x:y:[])\n |n==m=(x+t-1):0:[]\n |otherwise=0:(y+x-t):[]\nf n m t (x:y:z:xs)\n |n==m=(x+t-1):0:(z+y-t):xs\n |otherwise=x:f n (m+1) t (y:z:xs)\n\nf2::[String]->[Int]->[Int]\nf2 [] ans=ans\nf2 (s:str) ans=let (n:t:[])=map read (words s)::[Int]\n in if n==1 then f2 str (f 1 1 t ans) else f2 str (f n 2 t ans)\n\nmain = do\n e<-getLine\n es<-getLine\n e2<-getLine\n es2<-getContents\n let xs=map read (words es)::[Int]\n ys=lines es2\n mapM_ putStrLn $ map show $ f2 ys xs"}, {"source_code": "import Debug.Trace\n\nmain :: IO ()\nmain =\n putStrLn . unlines . map show . solve . lines =<< getContents\n\nsolve :: [String] -> [Int]\nsolve (_:numBirdsStr:_:killingsStr) =\n foldl update numBirds killings\n where\n numBirds = map read $ words numBirdsStr\n killings = map (tupify2 . (map read) . words) killingsStr\n tupify2 :: [a] -> (a, a)\n tupify2 [x, y] = (x, y)\n -- update :: numBirds -> (wire#, killed bird idx) -> numBirds'\n update :: [Int] -> (Int, Int) -> [Int]\n update birds (wire, killedBird) =\n let dUpper = killedBird - 1\n numBirdsOnWire = birds !! (wire - 1)\n dLower = numBirdsOnWire - dUpper - 1\n f i = if i == wire - 1 then\n dUpper\n else\n 0\n g i = if i == wire + 1 then\n dLower\n else\n 0\n in\n [birdQ + f i| (i, birdQ) <- zip [1..] birds, i < wire] ++ [0] ++ [birdQ + g i | (i, birdQ) <- zip [1..] birds, i > wire]\nsolve _ = error \"not enough lines\"\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport Data.Array.ST\nimport Data.Array\nimport Control.Monad\nimport Control.Monad.ST\n\nreadLine :: Read a => IO [a]\nreadLine = map read <$> words <$> getLine\n\nsolve :: [Int] -> [[Int]] -> [Int]\nsolve a q = [ans ! i | i <- [1..n]] where\n n = length a\n process arr ([i,pos]) = do\n when (i > 1) $ do \n was <- readArray arr (i - 1) \n writeArray arr (i - 1) $ was + pos - 1\n when (i < n) $ do\n me <- readArray arr i\n was <- readArray arr (i + 1)\n writeArray arr (i + 1) $ was + me - pos\n writeArray arr i 0\n ans = runSTArray ans'\n ans' = do\n arr <- newListArray (1, n) a :: ST s (STArray s Int Int)\n forM q $ \\x -> process arr x\n return arr\n\nmain = do\n n <- getLine\n a <- readLine :: IO [Int]\n m <- read <$> getLine\n q <- sequence [readLine | i <- [1..m]] :: IO [[Int]]\n forM (solve a q) $ \\x ->\n print x\n"}, {"source_code": "import Control.Applicative ((*>), (<$>), (<*>))\n\nmain :: IO ()\nmain = getLine >> solve <$> (map read . words <$> getLine) <*> (getLine *> (map (map read . words) . lines <$> getContents)) >>= mapM_ print\n\nsolve :: [Int] -> [[Int]] -> [Int]\nsolve = foldl (\\as [x, y] -> [ sum $ [ a | i /= x ] ++ [ y - 1 | i == x - 1 ] ++ [ as !! (x - 1) - y | i == x + 1 ] | (i, a) <- zip [1..] as ])\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess 1 a [] = a\nprocess 1 a ([x,y]:s) = [0]\nprocess n a [] = a\nprocess n a ([x,y]:s) |x==1 = process n ( [0] ++ [(a!!1)+ (a!!0)-y] ++ (drop 2 a)) s \n\t\t\t|x==n = process n ((take (x-2) a)++ [(a!!(x-2)) + y-1] ++ [0]) s \n\t\t\t|otherwise = process n ((take (x-2) a)++ [(a!!(x-2)) + y-1] ++ [0] ++ [(a!!x) +(a!!(x-1)) -y] ++ drop (x+1) a) s \n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tm<-read <$> getLine ::IO Int\n\t\ts<- map (map read.words) <$> replicateM m getLine ::IO [[Int]]\n\t\tmapM_ print $ process n a s\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n op <- replicateM n getLine\n let add = length $ filter (elem '+') op\n sub = length op - add\n print $ add - sub\n"}], "src_uid": "859d66fc2c204a8c002012b1fb206645"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [_, m] <- map readInt.B.words <$> B.getLine\n cs <- concat.lines <$> getContents\n case solve m cs of\n Just (x, y) -> do\n putStrLn \"YES\"\n putStrLn.unwords.map show $ [x+1, y+1]\n Nothing -> putStrLn \"NO\"\n\nsolve :: Int -> String -> Maybe (Int, Int)\nsolve _ cs | all (=='.') cs = Just (0, 0)\nsolve m cs = goXY (x0, y0) $ zip [i0+1..] $ drop (i0+1) cs\n where\n i0 :: Int\n !i0 = fst . head . dropWhile ((=='.').snd) $ zip [0..] cs\n (!x0, !y0) = divMod i0 m\n goXY (x, y) ((i, '*'):rest)\n | x == x' = goY (x, y) rest\n | y == y' = goX (x, y) rest\n | otherwise = go (x, y') rest <|> go (x', y) rest\n where\n (x', y') = divMod i m\n goXY (x, y) (_:rest) = goXY (x, y) rest\n goXY (x, y) [] = Just (x, y)\n\n goX (x, y) ((i, '*'):rest)\n | y == y' = goX (x, y) rest\n | otherwise = go (x', y) rest\n where\n (x', y') = divMod i m\n goX (x, y) (_:rest) = goX (x, y) rest\n goX (x, y) [] = Just (x, y)\n\n goY (x, y) ((i, '*'):rest)\n | x == x' = goY (x, y) rest\n | otherwise = go (x, y') rest\n where\n (x', y') = divMod i m\n goY (x, y) (_:rest) = goY (x, y) rest\n goY (x, y) [] = Just (x, y)\n\n go (x, y) rest\n | all (check.fst)$filter((=='*').snd)rest = Just (x, y)\n | otherwise = Nothing\n where\n check i = x == x' || y == y'\n where\n (x',y') = divMod i m\n", "positive_code": [{"source_code": "accumulate :: Char -> Integer -> Integer\naccumulate '*' = succ\naccumulate _ = id\n \nlocations :: [[Integer]] -> [[Integer]] -> [[Integer]] -> [[Integer]] -> [String] -> Integer -> Integer -> [(Integer, Integer)]\nlocations [] [] [] [] [] _ _ = []\nlocations (l:gl) (r:gr) (u:gu) (d:gd) (m:mt) x amnt = (locations' l r u d m 0 amnt) ++ locations gl gr gu gd mt (x + 1) amnt\n where\n locations' :: [Integer] -> [Integer] -> [Integer] -> [Integer] -> String -> Integer -> Integer -> [(Integer, Integer)]\n locations' [] [] [] [] [] _ _ = []\n locations' (l:left') (r:right') (u:up') (d:down') (m:mat') y amnt\n | amnt == l + r + u + d - (if m == '*' then 3 else 0) = (x, y) : locations' left' right' up' down' mat' (y + 1) amnt\n | otherwise = locations' left' right' up' down' mat' (y + 1) amnt\n\nprocess :: String -> String\nprocess str =\n let (h:mat) = lines str\n [n, m] = map read . words $ h\n amnt = fromIntegral . length . filter (=='*') . concat $ mat\n left = map (tail . scanl (flip accumulate) 0) mat\n right = map (reverse . tail . scanl (flip accumulate) 0 . reverse) mat\n up = tail . scanl (zipWith (flip accumulate)) (replicate m 0) $ mat\n down = reverse . tail . scanl (zipWith (flip accumulate)) (replicate m 0) . reverse $ mat\n locs = locations left right up down mat 0 amnt\n in\n if null locs\n then \"NO\"\n else \"YES\\n\" ++ ((\\(x, y) -> show (x + 1) ++ \" \" ++ show (y + 1)) . head $ locs)\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Control.Monad\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let walls = fst $ unzip $ filter (\\(_,v) -> v == '*') (zip ps tbl)\n if walls == []\n then putStrLn \"YES\" >> putStrLn \"1 1\" -- no wall. place the bomb anywhere\n else case search walls n m of -- possible bomb installations\n [] -> putStrLn \"NO\" -- no solution\n ((y,x):xs) -> do\n putStrLn \"YES\" -- print first solution\n putStrLn $ show y ++ \" \" ++ show x\n\nsearch (w:walls) n m = f walls (bombs0 w) where\n -- f :: [wall] -> [bomb] -> [bomb]\n f [] ps = ps\n f _ [] = []\n f (w:ws) ps = f ws (cross w ps)\n cross (wy,wx) ps = filter (\\(py,px) -> py == wy || px == wx) ps\n bombs0 (wy,wx) = [(y,wx) | y <- [1..n]] ++ [(wy,x) | x <- [1..m], x /= wx]"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ncount :: String -> Int\ncount \"\" = 0\ncount (x:xs) = a + (count xs)\n where a | x == '*' = 1\n | otherwise = 0\n\ncount2 :: [String] -> [Int]\ncount2 [] = []\ncount2 (x:xs) = (count x) : (count2 xs)\n\nprintRes :: Maybe (Int, Int) -> IO ()\nprintRes Nothing = putStrLn \"NO\"\nprintRes (Just (x, y)) = do\n putStrLn \"YES\"\n putStrLn $ (show x) ++ \" \" ++ (show y)\n\nsolve1 :: [Int] -> Int -> String -> Int -> Int -> Int -> Maybe (Int, Int)\nsolve1 _ _ [] _ _ _ = Nothing\nsolve1 (c:cs) r (cell:row) tc n m | c + r - tc - p == 0 = Just (n, m)\n | otherwise = solve1 cs r row tc n (m + 1)\n where p | cell == '*' = 1\n | otherwise = 0\n\nsolve :: [Int] -> [Int] -> [String] -> Int -> Int -> Maybe (Int, Int)\nsolve _ _ [] _ _ = Nothing\nsolve cs (r:rs) (x:xs) tc n = (solve1 cs r x tc n 1) `mplus` (solve cs rs xs tc (n + 1))\n\nmain :: IO ()\nmain = do\n [n, m] <- map read . words <$> getLine\n rows <- mapM (\\_ -> getLine) [1..n]\n let rowCount = count2 rows\n totalCount = sum rowCount\n cols = transpose rows\n colCount = count2 cols\n printRes $ solve colCount rowCount rows totalCount 1\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let ary = array ((1,1),(n,m)) (zip ps tbl)\n let rows = testRow ary n m\n let cols = testCol ary n m\n let only = [(i,j) | i <- [1..n], j <- [1..m], ary ! (i,j) == '*']\n if length only == 1\n then putStrLn $ ((show . fst . head) only) ++ \" \" ++ ((show . snd . head) only)\n else if (length rows >= 2) || (length cols >= 2)\n then putStrLn \"NO\"\n else do\n let x = if cols == [] then 0 else head cols\n let y = if rows == [] then 0 else head rows\n putStrLn \"YES\"\n putStrLn $ (show y) ++ \" \" ++ (show x)\n\ntestRow ary n m = [i | i <- [1..n], test i] where\n test i = length (filter (== '*') [ary ! (i,j) | j <- [1..m]]) >= 2\n\ntestCol ary n m = [j | j <- [1..m], test j] where\n test j = length (filter (== '*') [ary ! (i,j) | i <- [1..n]]) >= 2"}, {"source_code": "import Control.Monad\nimport Data.Array\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let ary = array ((1,1),(n,m)) (zip ps tbl)\n let rows = testRow ary n m\n let cols = testCol ary n m\n let only = [(i,j) | i <- [1..n], j <- [1..m], ary ! (i,j) == '*']\n if length only == 1\n then do\n putStrLn \"YES\"\n putStrLn $ ((show . fst . head) only) ++ \" \" ++ ((show . snd . head) only)\n else if (length rows >= 2) || (length cols >= 2)\n then putStrLn \"NO\"\n else do\n let x = if cols == [] then 1 else head cols\n let y = if rows == [] then 1 else head rows\n putStrLn \"YES\"\n putStrLn $ (show y) ++ \" \" ++ (show x)\n\ntestRow ary n m = [i | i <- [1..n], test i] where\n test i = length (filter (== '*') [ary ! (i,j) | j <- [1..m]]) >= 2\n\ntestCol ary n m = [j | j <- [1..m], test j] where\n test j = length (filter (== '*') [ary ! (i,j) | i <- [1..n]]) >= 2\n"}, {"source_code": "import Control.Monad\nimport Data.Array\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let ary = array ((1,1),(n,m)) (zip ps tbl)\n let rows = testRow ary n m\n let cols = testCol ary n m\n if (length rows >= 2) || (length cols >= 2)\n then putStrLn \"NO\"\n else if rows == [] && cols == []\n then putStrLn \"NO\"\n else do\n let x = if cols == [] then 0 else head cols\n let y = if rows == [] then 0 else head rows\n putStrLn \"YES\"\n putStrLn $ (show y) ++ \" \" ++ (show x)\n\ntestRow ary n m = [i | i <- [1..n], test i] where\n test i = length (filter (== '*') [ary ! (i,j) | j <- [1..m]]) > 1\n\ntestCol ary n m = [j | j <- [1..m], test j] where\n test j = length (filter (== '*') [ary ! (i,j) | i <- [1..n]]) > 1"}, {"source_code": "import Control.Monad\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let walls = fst $ unzip $ filter (\\(_,v) -> v == '*') (zip ps tbl)\n if walls == []\n then putStrLn \"YES\" >> putStrLn \"1 1\" -- no wall. place the bomb anywhere\n else case search walls n m of -- possible bomb installations\n [] -> putStrLn \"NO\" -- no solution\n ((y,x):xs) -> do\n putStrLn \"YES\" -- print first solution\n putStrLn $ show y ++ \" \" ++ show x\n\nsearch (w:walls) n m = bombs0 w where\n--search (w:walls) n m = f walls (bombs0 w) where\n -- f :: [wall] -> [bomb] -> [bomb]\n f [] ps = ps\n f _ [] = []\n f (w:ws) ps = f ws (cross w ps)\n cross (wy,wx) ps = filter (\\(py,px) -> py == wy || px == wx) ps\n bombs0 (wy,wx) = [(y,wx) | y <- [1..n]] ++ [(wy,x) | x <- [1..m], x /= wx]"}, {"source_code": "import Control.Monad\nimport Data.Array\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let ary = array ((1,1),(n,m)) (zip ps tbl)\n let walls = filter (\\(y,x) -> ary ! (y,x) == '*') ps\n if walls == []\n then putStrLn \"YES\" >> putStrLn \"1 1\" -- no wall. place the bomb anywhere\n else case search walls m n of -- possible bomb installations\n [] -> putStrLn \"NO\" -- no solution\n ((y,x):xs) -> do\n putStrLn \"YES\" -- print first solution\n putStrLn $ show y ++ \" \" ++ show x\n\nsearch (w:walls) n m = f walls (bombs0 w) where\n -- f :: [wall] -> [bomb] -> [bomb]\n f [] ps = ps\n f _ [] = []\n f (w:ws) ps = f ws (cross w ps)\n cross (wy,wx) ps = filter (\\(py,px) -> py == wy || px == wx) ps\n bombs0 (wy,wx) = [(y,wx) | y <- [1..n]] ++ [(wy,x) | x <- [1..m], x /= wx]"}, {"source_code": "import Control.Monad\nimport Data.Array\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n tbl <- (concat . lines) `fmap` getContents\n let ps = [(i,j) | i <- [1..n], j <- [1..m]]\n let ary = array ((1,1),(n,m)) (zip ps tbl)\n let rows = testRow ary n m\n let cols = testCol ary n m\n if (length rows >= 2) || (length cols >= 2)\n then putStrLn \"NO\"\n else do\n let x = if cols == [] then 0 else head cols\n let y = if rows == [] then 0 else head rows\n putStrLn \"YES\"\n putStrLn $ (show y) ++ \" \" ++ (show x)\n\ntestRow ary n m = [i | i <- [1..n], test i] where\n test i = length (filter (== '*') [ary ! (i,j) | j <- [1..m]]) > 1\n\ntestCol ary n m = [j | j <- [1..m], test j] where\n test j = length (filter (== '*') [ary ! (i,j) | i <- [1..n]]) > 1"}], "src_uid": "12a768b502ddb07798830c9728fba5c4"} {"source_code": "import Data.List\ngetFirst a [] sum d= (sum,[])\ngetFirst a (rem:remA) sum d| (fst rem) - (fst a) >= d = (sum,rem:remA)\n | otherwise = getFirst a remA (sum+(snd rem)) d\ngetMax preSum [] x d= 0 \ngetMax preSum remA (a:as) d = max (preSum+sum) (getMax (preSum+sum-(snd a)) rem as d)\n where (sum,rem) = getFirst a remA 0 d\ngetTup::String -> (Integer,Integer)\ngetTup w0 = (a0,a1)\n where [a0,a1] = [read n::Integer|n <- (words w0)]\nmain = do\n w0 <- getLine\n let [n,d] = [read n::Integer| n <- (words w0)]\n w1 <- getContents\n let ms = [getTup a |a <-(lines w1)]\n let sms = sortBy (\\x y -> compare (fst x) (fst y)) ms\n print $ getMax 0 sms sms d\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, poor] <- readLine\n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ main' poor friends\n\nmain' :: Integer -> [(Integer, Integer)] -> Integer\nmain' poor friends = findMaxStackSum 0 0 friends friends\n where\n poorityReached x y = (fst x) - (fst y) >= poor\n findMaxStackSum :: Integer -> Integer -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer\n findMaxStackSum maxSum _ _ [] = maxSum\n findMaxStackSum maxSum curSum [] _ = max maxSum curSum\n findMaxStackSum maxSum curSum f1@(x:xs) f2@(y:ys)\n | poorityReached x y = findMaxStackSum maxSum (curSum - snd y) f1 ys\n | otherwise = findMaxStackSum (max maxSum curSum') curSum' xs f2\n where curSum' = curSum + snd x\n"}, {"source_code": "import Data.List\nreadPair l = (read a,read b) where [a,b] = words l\nmain = do\n [n,d] <- map read . words <$> getLine\n fs <- sort . map readPair . lines <$> getContents\n print $ maximum $ go d fs fs 0\ngo d ls@((ml,sl):ls') hs@((mh,sh):hs') f\n | mh - ml < d = inc : go d ls hs' inc\n | otherwise = go d ls' hs (f - sl)\n where inc = f + sh\ngo _ _ _ _ = []\n"}, {"source_code": "import Data.List\n\nfillWindow :: Integer -> Integer -> [(Integer, Integer)] -> (Integer, [(Integer, Integer)])\nfillWindow _ _ [] = (0, [])\nfillWindow initial d ((m, s):t)\n\t|m-initial >= d = (0, ((m,s):t))\n\t|otherwise = (s+acc, suffix)\n\t\twhere (acc,suffix) = fillWindow initial d t\n\nslideWindow :: [(Integer, Integer)] -> [(Integer, Integer)] -> Integer -> Integer -> Integer\nslideWindow _ [] sum _ = sum\nslideWindow ((mi,si):ti) ((mj,sj):tj) sum d\n\t|mj-mi >= d = max sum (slideWindow ti ((mj,sj):tj) (sum - si) d)\n\t|otherwise = slideWindow ((mi,si):ti) tj (sum+sj) d\n\nmoney (a,b) = a\nfriend (a,b) = b\n\nmain = do\n\ttudo <- fmap lines getContents\n\tlet listToPair (h:t) = (h, head t)\n\tlet pairs = map (listToPair.(map read).words) tudo\n\tlet (n, d) = head pairs\n\tlet guys = sort (tail pairs)\n\tlet (sum, firstDmElement) = fillWindow ((money.head) guys) d guys\n\n\tprint $ slideWindow guys firstDmElement sum d\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nselect :: Integer -> [(Integer, Integer)] -> Integer\nselect _ [] = 0\nselect difference friends =\n let\n recur maximal current _ [] =\n max maximal current\n recur maximal current (r:rs) (n:ns) =\n if fst r > fst n - difference then\n recur maximal (current + snd n) (r:rs) ns\n else\n recur (max maximal current) (current - snd r) rs (n:ns)\n in\n recur 0 0 friends friends\n\nmain = do\n [_, difference] <- readLine \n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ select difference friends\n"}, {"source_code": "import Data.Int\nimport Control.Monad\nimport Data.List\n\nmain :: IO()\nmain = do\n [n,d] <- fmap ((map read) . words) getLine :: IO [Int64]\n a <- forM [1..n] $ \\_ -> do\n [t1,t2] <- fmap ((map read) . words) getLine :: IO [Int64]\n return (t1,t2)\n let x = sort a\n print . maximum $ solve d x x 0\n\nsolve d _ [] a = []\nsolve d ((m1,s1):xs) ((m2,s2):ys) psum\n |m2-m1 Input\nparse contents =\n let (l : ls) = lines contents\n (_, d) = p l\n in (d, map p ls)\n where p l = (a, b) where [a, b] = map read . words $ l\n\nsolve :: Input -> Int64\nsolve (d, a') = maximum . map fst $ scanl step (0, a) a\n where a = sort a'\n step (s, b) (m, f) =\n let (xs, b') = break (\\(m', _) -> m' > m - d) b\n in (s + f - sum (map snd xs), b')\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}, {"source_code": "module Main where\n\nimport Data.List\n\ngetSum _ [] s _ = (s,[])\ngetSum a (x:xs) s d\n | (fst x) - (fst a) < d = getSum a xs (s+(snd x)) d\n | otherwise = (s,(x:xs))\n\ngetMax _ [] _ _ = 0\ngetMax pre xs (y:ys) d = max (pre+s) (getMax (pre+s-(snd y)) rs ys d)\n where (s,rs) = getSum y xs 0 d\n\ngetTuple :: String -> (Integer,Integer)\ngetTuple w = (a0,a1)\n where [a0,a1] = [read n :: Integer | n <- (words w)]\n\nmain = do\n w0 <- getLine\n let [n,d] = [read n :: Integer | n <- (words w0)]\n w1 <- getContents\n let pool = sortBy (\\a0 a1 -> compare (fst a0) (fst a1)) [getTuple x | x <- (lines w1)]\n print $ getMax 0 pool pool d\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine = B.getLine >>= return . map readInt . B.words\n\nfind :: [(Integer, Integer)] -> Integer -> Integer\nfind [] _ = 0\nfind friends difference = scan friends friends 0 0 difference\n\nscan :: [(Integer, Integer)] ->\n [(Integer, Integer)] -> Integer -> Integer -> Integer -> Integer\n\nscan _ [] max_ current __ = max max_ current\nscan (l:ls) (r:rs) max_ current difference\n | fst r - fst l >= difference = scan ls (r:rs) (max max_ current) (current - snd l) difference\n | otherwise = scan (l:ls) rs max_ (current + snd r) difference\n\nmain = do\n [_, difference] <- readLine\n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n\n print $ find friends difference\n"}], "negative_code": [{"source_code": "import Data.List\n\nfillWindow :: Int -> Int -> [(Int,Int)] -> (Int, [(Int, Int)])\nfillWindow _ _ [] = (0, [])\nfillWindow initial d ((m, s):t)\n\t|m-initial >= d = (0, ((m,s):t))\n\t|otherwise = (s+acc, suffix)\n\t\twhere (acc,suffix) = fillWindow initial d t\n\nslideWindow :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> Int\nslideWindow _ [] sum _ = sum\nslideWindow ((mi,si):ti) ((mj,sj):tj) sum d\n\t|mj-mi >= d = max sum (slideWindow ti ((mj,sj):tj) (sum - si) d)\n\t|otherwise = slideWindow ((mi,si):ti) tj (sum+sj) d\n\nmoney (a,b) = a\nfriend (a,b) = b\n\nmain = do\n\ttudo <- fmap lines getContents\n\tlet listToPair (h:t) = (h, head t)\n\tlet pairs = map (listToPair.(map read).words) tudo\n\tlet (n, d) = head pairs\n\tlet guys = sort (tail pairs)\n\tlet (sum, firstDmElement) = fillWindow ((money.head) guys) d guys\n\n\tprint $ slideWindow guys firstDmElement sum d\n"}, {"source_code": "import Data.List\nimport Control.Monad\ndata P = P {m::Int,s::Int} deriving(Show,Eq,Ord)\n\nmain :: IO()\nmain = do\n [n,d] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- forM [1..n] $ \\_ -> do\n [mi,si] <- fmap ((map read) . words) getLine :: IO [Int]\n return (P{m=mi,s=si})\n let sL = sortBy cmp a\n mx = s (head sL)\n lnth = max (mx-d) 0\n aL = takeWhile (\\x -> s x >= lnth) sL\n print $ sum' aL\n\nsum' [] = 0\nsum' (x:xs) = let a = seq x x in (s a) + (sum' xs)\n\ncmp x y\n |s xs y = LT\n |otherwise = EQ"}, {"source_code": "import Data.Int\nimport Data.List\nimport Control.Monad\ndata P = P {m::Int64,s::Int64} deriving(Show,Eq,Ord)\n\nmain :: IO()\nmain = do\n [n,d] <- fmap ((map read) . words) getLine :: IO [Int64]\n a <- forM [1..n] $ \\_ -> do\n [mi,si] <- fmap ((map read) . words) getLine :: IO [Int64]\n return (P{m=mi,s=si})\n let sL = sortBy cmp a\n mx = m (head sL)\n aL = takeWhile (\\x -> abs (mx - (m x)) <=d ) sL\n print $ sum' aL\n\nsum' [] = 0\nsum' (x:xs) = let a = seq x x in (s a) + (sum' xs)\n\ncmp x y\n |s xs y = LT\n |otherwise = EQ\n"}, {"source_code": "import Data.List\nimport Control.Monad\ndata P = P {m::Int,s::Int} deriving(Show,Eq,Ord)\n\nmain :: IO()\nmain = do\n [n,d] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- forM [1..n] $ \\_ -> do\n [mi,si] <- fmap ((map read) . words) getLine :: IO [Int]\n return (P{m=mi,s=si})\n let sL = sortBy cmp a\n mx = m (head sL)\n aL = takeWhile (\\x -> abs (mx - (m x)) <=d ) sL\n --print mx\n print $ sum' aL\n\nsum' [] = 0\nsum' (x:xs) = let a = seq x x in (s a) + (sum' xs)\n\ncmp x y\n |s xs y = LT\n |otherwise = EQ"}, {"source_code": "module Main where\nimport Control.Monad as M\n\nniceForm :: [String] -> [(Integer, Integer)]\nniceForm [] = []\nniceForm (x:xs) = (format x) : niceForm xs\n where format :: String -> (Integer, Integer)\n format str = ((read (takeWhile (/=' ') str)), (read (dropWhile (/=' ') str)))\n\nget2Num :: String -> (Int, Integer)\nget2Num str = ((read (takeWhile (/=' ') str)),(read (tail (dropWhile (/=' ') str))))\n\nsolution :: [(Integer, Integer)] -> Integer -> [Integer]\nsolution [] _ = []\nsolution [x] _ = [snd x]\nsolution xs r = map f xs\n where f :: (Integer, Integer) -> Integer\n f x = sumSnd (filter (\\t -> abs((fst t) - (fst x)) <= r) xs)\n where sumSnd :: [(Integer, Integer)] -> Integer\n sumSnd [] = 0\n sumSnd (x:xs) = (snd x) + sumSnd xs\n\nmain = do\n str <- getLine\n let nums = get2Num str\n pool_raw <- M.replicateM (fst nums) getLine\n let pool = niceForm pool_raw\n print (maximum (solution pool (snd nums)))\n"}, {"source_code": "import Data.List\ngetFirst a [] sum d= (sum,[])\ngetFirst a (rem:remA) sum d| (fst rem) - (fst a) >= d = (sum,rem:remA)\n | otherwise = getFirst a remA (sum+(snd rem)) d\ngetMax preSum [] x d= 0 \ngetMax preSum remA (a:as) d = max (preSum+sum) (getMax (preSum+sum-(snd a)) rem as d)\n where (sum,rem) = getFirst a remA 0 d\ngetTup::String -> (Int,Int)\ngetTup w0 = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words w0)]\nmain = do\n w0 <- getLine\n let [n,d] = [read n::Int| n <- (words w0)]\n w1 <- getContents\n let ms = [getTup a |a <-(lines w1)]\n let sms = sortBy (\\x y -> compare (fst x) (fst y)) ms\n print $ getMax 0 sms sms d\n"}, {"source_code": "import Data.List\ngetFirst a [] sum d= (sum,[])\ngetFirst a (rem:remA) sum d| (fst rem) - (fst a) >= d = (sum,remA)\n | otherwise = getFirst a remA (sum+(snd rem)) d\ngetMax preSum [] x d= 0 \ngetMax preSum remA @x(a:as) d = max (preSum+sum) (getMax (preSum+sum-(snd a)) rem as d)\n where (sum,rem) = getFirst a remA 0 d\ngetTup::String -> (Int,Int)\ngetTup w0 = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words w0)]\nmain = do\n w0 <- getLine\n let [n,d] = [read n::Int| n <- (words w0)]\n w1 <- getContents\n let ms = [getTup a |a <-(lines w1)]\n let sms = sortBy (\\x y -> compare (fst x) (fst y)) ms\n print $ getMax 0 sms sms d\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine = B.getLine >>= return . map readInt . B.words\n\nfind :: [(Integer, Integer)] -> Integer -> Integer\nfind [] _ = 0\nfind friends difference = scan friends friends 0 0 difference\n\nscan :: [(Integer, Integer)] ->\n [(Integer, Integer)] -> Integer -> Integer -> Integer -> Integer\n\nscan _ [] max_ current __ = max max_ current\nscan (l:ls) (r:rs) max_ current difference\n | fst r - fst l > difference = scan ls (r:rs) (max max_ current) (current - snd l) difference\n | otherwise = scan (l:ls) rs max_ (current + snd r) difference\n\nmain = do\n [_, difference] <- readLine\n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n\n print $ find friends difference\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, poor] <- readLine\n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ main' poor friends\n\nmain' :: Integer -> [(Integer, Integer)] -> Integer\nmain' poor friends = findMaxStackSum 0 poor [] friends\n\nfindMaxStackSum :: Integer -> Integer -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer\nfindMaxStackSum maxSum _ _ [] = maxSum\nfindMaxStackSum maxSum poor [] (x:xs) = findMaxStackSum (snd x) poor (x:[]) xs\nfindMaxStackSum maxSum poor curStack friends@(x:xs)\n | poorityReached x lastStackEl = findMaxStackSum maxSum poor (init curStack) friends\n | otherwise = findMaxStackSum newMaxSum poor (x:curStack) xs\n where\n poorityReached x y = (fst x) - (fst y) >= poor\n lastStackEl = last curStack\n newMaxSum = max maxSum $ foldr ((+) . snd) 0 (x:curStack)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, poor] <- readLine\n friends <- replicateM (fromIntegral n) $ do\n [money, friendScore] <- readLine\n return (money, friendScore)\n B.putStrLn . B.pack . show $ main' poor friends\n\nmain' :: Integer -> [(Integer, Integer)] -> Integer\nmain' poor friends = findMaxStackSum 0 poor [] $ sortBy (\\(x1,_) (x2, _) -> if (x1 < x2) then LT else GT) friends\n\nfindMaxStackSum :: Integer -> Integer -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer\nfindMaxStackSum maxSum _ _ [] = maxSum\nfindMaxStackSum maxSum poor [] (x:xs) = findMaxStackSum (snd x) poor (x:[]) xs\nfindMaxStackSum maxSum poor curStack friends@(x:xs) = findMaxStackSum newMaxSum poor newCurStack xs\n where\n poorityReached x y = (fst x) - (fst y) > poor\n lastStackEl = head $ reverse curStack\n newCurStack\n | poorityReached x lastStackEl = x:(reverse $ dropWhile (\\el -> poorityReached x el) $ reverse curStack)\n | otherwise = x:curStack\n newMaxSum = max maxSum $ foldr (\\(x, y) agg -> agg + y) 0 newCurStack\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, poor] <- readLine\n friends <- replicateM n $ do\n [money, friendScore] <- readLine\n return (money, friendScore)\n B.putStrLn . B.pack . show $ main' poor friends\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' poor friends = findMaxStackSum 0 poor [] $ sortBy (\\(x1,_) (x2, _) -> if (x1 < x2) then LT else GT) friends\n\nfindMaxStackSum :: Int -> Int -> [(Int, Int)] -> [(Int, Int)] -> Int\nfindMaxStackSum maxSum _ _ [] = maxSum\nfindMaxStackSum maxSum poor [] (x:xs) = findMaxStackSum (snd x) poor (x:[]) xs\nfindMaxStackSum maxSum poor curStack friends@(x:xs) = findMaxStackSum newMaxSum poor newCurStack xs\n where\n poorityReached x y = (fst x) - (fst y) > poor\n lastStackEl = head $ reverse curStack\n newCurStack\n | poorityReached x lastStackEl = x:(reverse $ dropWhile (\\el -> poorityReached x el) $ reverse curStack)\n | otherwise = x:curStack\n newMaxSum = max maxSum $ foldr (\\(x, y) agg -> agg + y) 0 newCurStack\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, poor] <- readLine\n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ main' poor friends\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' poor friends = findMaxStackSum 0 0 [] friends\n where\n poorityReached x y = (fst x) - (fst y) >= poor\n findMaxStackSum :: Int -> Int -> [(Int, Int)] -> [(Int, Int)] -> Int\n findMaxStackSum maxSum _ _ [] = maxSum\n findMaxStackSum maxSum curSum [] (x:xs) = findMaxStackSum (max maxSum $ snd x) (snd x) (x:[]) xs\n findMaxStackSum maxSum curSum curStack friends@(x:xs)\n | poorityReached x l = findMaxStackSum maxSum (curSum - snd l) (init curStack) friends\n | otherwise = findMaxStackSum (max maxSum s) s (x:curStack) xs\n where\n l = last curStack\n s = curSum + snd x\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nselect :: Int -> [(Int, Int)] -> Int\nselect _ [] = 0\nselect difference friends =\n let\n recur maxFriendliness currentFriendliness _ [] =\n max maxFriendliness currentFriendliness\n recur maxFriendliness currentFriendliness (r:rs) (n:ns) =\n if fst r > fst n - difference then\n recur maxFriendliness (currentFriendliness + snd n) (r:rs) ns\n else\n recur (max maxFriendliness currentFriendliness) (currentFriendliness - snd r) rs (n:ns)\n in\n recur 0 0 friends friends\n\nmain = do\n [_, difference] <- readLine \n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ select difference friends\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nselect :: Int -> [(Int, Int)] -> Int\nselect _ [] = 0\nselect difference all@(poorest : other) =\n let\n richestAmongPoorest = fst poorest + difference\n (headFriendliness, tail) =\n recursiveCut (snd poorest) other\n recursiveCut friendliness [] = (friendliness, [])\n recursiveCut friendliness (next:rest) =\n if fst next > richestAmongPoorest then\n (friendliness, next:rest)\n else\n recursiveCut (friendliness + snd next) rest\n recur maxFriendliness currentFriendliness _ [] =\n max maxFriendliness currentFriendliness\n recur maxFriendliness currentFriendliness (r:rs) (n:ns) =\n if fst r >= fst n - difference then\n recur maxFriendliness (currentFriendliness + snd n) (r:rs) ns\n else\n recur (max maxFriendliness currentFriendliness) (currentFriendliness - snd r) rs (n:ns)\n in\n recur headFriendliness headFriendliness all tail\n\nmain = do\n [_, difference] <- readLine \n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ select difference friends\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nselect :: Int -> [(Int, Int)] -> Int\nselect _ [] = 0\nselect difference all@(poorest : other) =\n let\n richestAmongPoorest = fst poorest + difference\n (headFriendliness, tail) =\n recursiveCut (snd poorest) other\n recursiveCut friendliness [] = (friendliness, [])\n recursiveCut friendliness (next:rest) =\n if fst next > richestAmongPoorest then\n (friendliness, next:rest)\n else\n recursiveCut (friendliness + snd next) rest\n recur maxFriendliness _ _ [] =\n maxFriendliness\n recur maxFriendliness currentFriendliness (r:rs) (n:ns) =\n if fst n - difference > fst r then\n recur maxFriendliness (currentFriendliness - snd r) rs (n:ns)\n else\n recur (max maxFriendliness currentFriendliness) (currentFriendliness + snd n) (r:rs) ns\n in\n recur headFriendliness headFriendliness all tail\n\nmain = do\n [_, difference] <- readLine \n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ select difference friends\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nselect :: Int -> [(Int, Int)] -> Int\nselect _ [] = 0\nselect difference all@(poorest : other) =\n let\n richestAmongPoorest = fst poorest + difference\n (headFriendliness, tail) =\n recursiveCut (snd poorest) other\n recursiveCut friendliness [] = (friendliness, [])\n recursiveCut friendliness (next:rest) =\n if fst next > richestAmongPoorest then\n (friendliness, next:rest)\n else\n recursiveCut (friendliness + snd next) rest\n recur maxFriendliness _ _ [] =\n maxFriendliness\n recur maxFriendliness currentFriendliness (r:rs) (n:ns) =\n if fst r >= fst n - difference then\n recur maxFriendliness (currentFriendliness + snd n) (r:rs) ns\n else\n recur (max maxFriendliness currentFriendliness) (currentFriendliness - snd r) rs (n:ns)\n in\n recur headFriendliness headFriendliness all tail\n\nmain = do\n [_, difference] <- readLine \n friends <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . show $ select difference friends\n"}, {"source_code": "import Data.List (sort)\n\ntype Input = (Int, [(Int, Int)])\n\nparse :: String -> Input\nparse contents =\n let (l : ls) = lines contents\n (_, d) = p l\n in (d, map p ls)\n where p l = (a, b) where [a, b] = map read . words $ l\n\nsolve :: Input -> Int\nsolve (d, a') = maximum . map fst $ scanl step (0, a) a\n where a = sort a'\n step (s, b) (m, f) =\n let (xs, b') = break (\\(m', _) -> m' > m - d) b\n in (s + f - sum (map snd xs), b')\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}], "src_uid": "38fe0e19974a7bc60153793b9060369a"} {"source_code": "import Data.List\n\nmain = interact $ f . lines\n\nf (x:xs) = g wait\n k\n (takeWhile (<=k) (sort (init (map length xs))))\n where wait = read (last (words x)) :: Int\n k = length (last xs)\n\ng wait passwd lstpasswd = show (i + if i <= wait\n then 0\n else (5*(if (i `mod` wait) > 0\n then (i `div` wait)\n else (i `div` wait) - 1)))\n ++\n \" \"\n ++\n show (j + if j <= wait\n then 0\n else (5*(if (j `mod` wait) > 0\n then (j `div` wait)\n else (j `div` wait) - 1)))\n \n where i = length (takeWhile ( String -> String -> Ordering \nminOrdering pass a b = (length a `compare` length b) `mappend` \n ((b == pass) `compare` (a == pass))\n\nmaxOrdering :: String -> String -> String -> Ordering \nmaxOrdering pass a b = (length a `compare` length b) `mappend` \n ((a == pass) `compare` (b == pass))\n\nsolve :: [String] -> Int -> String -> Int\nsolve ss k pass = (i `div` k) * 5 + i + 1\n where (Just i) = elemIndex pass ss\n\nmain = do\n [n, k] <- liftM (map read . words) getLine\n s <- replicateM n getLine\n pass <- getLine\n printf \"%d %d\\n\" (solve (sortBy (minOrdering pass) s) k pass) (solve (sortBy (maxOrdering pass) s) k pass)\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Function\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nmain :: IO ()\nmain = do \n ns:ks:passwords <- words <$> getContents\n let n = read ns :: Int\n k = read ks :: Int\n passes = sortBy (compare `on` length) $ init passwords\n len = length $ last passwords\n (priors,rest) = span ((< len) . length) passes\n eqs = takeWhile ((== len) . length) rest\n minCase = length priors + 1\n maxCase = minCase + length eqs - 1\n timeFor x = x + ((x - 1) `div` k) * 5 \n putStrLn $ show (timeFor minCase) ++ \" \" ++ show (timeFor maxCase)\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ncompareLength x y = compare (length x) (length y)\n\nmain = do\n [n, k] <- (map read . words) `fmap` getLine :: IO [Int]\n passwords <- sortBy compareLength `fmap` replicateM n getLine\n validPwd <- getLine\n let fails = length $ takeWhile (\\p -> length p < length validPwd) passwords\n let fails_time = fails + ((fails `div` k) * 5)\n putStr $ show (fails_time + 1) -- best\n putChar ' '\n let sameLenWords = (takeWhile (\\p -> length p == length validPwd) $ drop fails passwords)\n let fails' = length sameLenWords - 1 + fails\n let fails_time' = fails' + ((fails' `div` k) * 5)\n print (fails_time' + 1) -- worst\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n [n, k] <- map read.words <$> getLine\n css <- replicateM n getLine\n pass <- getLine\n putStr.unwords.map show $ solve k pass css\n\nsolve :: Int -> String -> [String] -> [Int]\nsolve k pass css = [solveMin k pass css, solveMax k pass css]\n\nsolveMin, solveMax :: Int -> String -> [String] -> Int\nsolveMin k pass css = solve' k.(++[len]).takeWhile ( [Int] -> Int\nsolve' k xs = go 0 0 xs\n where\n go miss res (x:xs)\n | miss == k = go 1 (res+6) xs\n | otherwise = go (miss+1) (res+1) xs\n go _ res [] = res"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Function\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nmain :: IO ()\nmain = do \n ns:ks:passwords <- words <$> getContents\n let n = read ns :: Int\n k = read ks :: Int\n passes = sortBy (compare `on` length) $ init passwords\n len = length $ last passwords\n (priors,rest) = span ((< len) . length) passes\n eqs = takeWhile ((== len) . length) rest\n minCase = length priors + 1\n maxCase = minCase + length eqs - 1\n timeFor x = x + (x `div` k) * 5 \n putStrLn $ show (timeFor minCase) ++ \" \" ++ show (timeFor maxCase)\n"}], "src_uid": "06898c5e25de2664895f512f6b766915"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nstep :: Int -> Int -> Maybe ((Int, Int), Int)\nstep x b = let\n aPotOpts = div x (b+1)\n nextB = div x (aPotOpts + 1) - 1\n in if b == 0\n then Nothing\n else Just ((b, aPotOpts), nextB)\n\n(*!) :: Int -> Int -> Int64\nx *! y = fromIntegral x * fromIntegral y\n\ninfixl 9 *!\n\nchoose2 :: Int -> Int64\nchoose2 x = quot (x *! (x-1)) 2\n\nctInterval :: (Int, Int) -> Int -> Int64\nctInterval (b, pot) nextB\n | nextB + 1 - 1 >= pot = pot *! (b - nextB)\n | pot >= b - 1 = choose2 b - choose2 nextB\n | otherwise = let\n splitPt = pot + 1\n in ctInterval (b, pot) splitPt + ctInterval (splitPt, pot) nextB\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [x, y] <- readInts\n let\n intel = unfoldr (step x) y\n scores = [ctInterval curr nextB\n | (curr, (nextB, _)) <- zip intel $ tail intel ++ [(0, error \"no\")]]\n putInts [sum scores]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int64] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines . map bshow <$>\n replicateM t ((\\[x, y] -> solve x y) <$> popIntegers)\n\n\nsolve x y = sum $ takeWhile (> 0) $ map f [2 .. y]\n where\n f p = (cap (x `quot` (p - 1)) (y + 1)) - p\n\n cap a b | a > b = b\n | otherwise = a\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nsolve :: Int64 -> Int64 -> Int64\nsolve x y = a1 + a2\n where\n f1 j = x `quot` (j + 1)\n f2 j = j - 1\n g1 k = x `quot` (k + 1) - 1\n g2 k = x `quot` k - 1\n a1 = sum $ 0 : [k * (min y (g2 k) - min y (g1 k)) | k <- takeWhile (\\k -> let jj = g1 k + 1 in f1 jj <= f2 jj) [1..]]\n a2 = sum $ 0 : [min (f1 j) (f2 j) | j <- takeWhile (\\j -> let jj = g1 (f1 j) + 1 in f1 jj > f2 jj) [1..y]]\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [x, y] <- map fromIntegral <$> getInts\n C.putStrLn $ C.pack $ show $ solve x y\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines . map bshow <$> replicateM t ((\\[x, y] -> solve x y) <$> popInts)\n\n\nsolve x y = sum $ takeWhile (> 0) $ map f [2 .. y]\n where\n f p = (cap (x `quot` (p - 1)) (y + 1)) - p\n\n cap a b | a > b = b\n | otherwise = a\n"}], "src_uid": "efdb966e414050c5e51e8beb7bb06b20"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nmain = B.interact $ solve . map parse . tail . B.lines\nparse l = (read' a :: Int,read' b :: Int) where [a,b] = B.words l\nsolve ps | map snd (sort ps) == sort (map snd ps) = B.pack \"Poor Alex\"\n | otherwise = B.pack \"Happy Alex\"\nread' bs = i where Just (i,_) = B.readInt bs\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \n\n\nmain= do\n\tgetLine\n\ts<-transpose. map (map (fst.fromJust.C.readInt)). map C.words . C.lines <$> C.getContents ::IO [[Int]]\n\tlet s1 = map snd $ sort $ zip (head s) (last s)\n\tputStrLn $ if s1==sort s1 then \"Poor Alex\" else \"Happy Alex\""}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\nsolve :: [Int] -> [Int] -> String\nsolve xs ys = get_state $ or $ zipWith (/=) xs ys\n where get_state False = \"Poor Alex\"\n get_state True = \"Happy Alex\"\n\nprocess :: State Reader String\nprocess = do\n n <- bsGet\n [as, bs] <- transpose <$> replicateM n bsGet\n return $ solve as bs\n\nmain :: IO ()\nmain = do\n args <- getArgs\n reader <- if not (null args) && head args == \"MINE\"\n then B.lines <$> (openFile \"input.txt\" ReadMode >>= B.hGetContents)\n else B.lines <$> B.getContents\n say $ evalState process reader\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass EIO a where\n bsGet :: State Reader a\n\ninstance EIO Int where\n bsGet = state $ \\(line:rest) -> (fst $ fromJust $ B.readInt line, rest)\n\ninstance EIO [Int] where\n bsGet = state $ \\(line:rest) -> (map fst . mapMaybe B.readInt . B.words $ line, rest)\n\ninstance EIO BString where\n bsGet = state $ \\(line:rest) -> (line, rest)\n\nclass Show a => Display a where\n display :: a -> String\n display = show\n\ninstance Display String where\n display = id\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\nsolve :: [Int] -> [Int] -> String\nsolve price quality = get_state $ ((==) `on` process) price quality\n where\n process xs = map snd $ sort $ zip xs [1 ..]\n get_state False = \"Happy Alex\"\n get_state True = \"Poor Alex\"\n\nprocess :: State Reader String\nprocess = do\n n <- bsGet\n [as, bs] <- transpose <$> replicateM n bsGet\n return $ solve as bs\n\nmain :: IO ()\nmain = do\n args <- getArgs\n reader <- if not (null args) && head args == \"MINE\"\n then B.lines <$> (openFile \"input.txt\" ReadMode >>= B.hGetContents)\n else B.lines <$> B.getContents\n say $ evalState process reader\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass EIO a where\n bsGet :: State Reader a\n\ninstance EIO Int where\n bsGet = state $ \\(line:rest) -> (fst $ fromJust $ B.readInt line, rest)\n\ninstance EIO [Int] where\n bsGet = state $ \\(line:rest) -> (map fst . mapMaybe B.readInt . B.words $ line, rest)\n\ninstance EIO BString where\n bsGet = state $ \\(line:rest) -> (line, rest)\n\nclass Show a => Display a where\n display :: a -> String\n display = show\n\ninstance Display String where\n display = id\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\nimport Control.Applicative\n-- Meat\n\nsolve :: [[Int]] -> String\nsolve xs = if sol xs then \"Poor Alex\" else \"Happy Alex\"\n where sol = all (>= 0) . (zipWith (-) <$> tail <*> id).fmap (head . tail). sort\n\n-- Shit\nmain :: IO ()\nmain = do\n (_: xs) <- readShit\n printShitV [solve xs]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\nimport Control.Applicative\n-- Meat\n\nsolve :: [[Integer]] -> String\nsolve xs = if sol xs then \"Poor Alex\" else \"Happy Alex\"\n where sol = all (>= 0) . (zipWith (-) <$> tail <*> id).fmap (head . tail). sort\n\n\n\n-- Shit\nmain :: IO ()\nmain = do\n (_: xs) <- readShit\n printShitV [solve xs]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> (solve =<< forM [1..read n] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve xs = let (b1,b2) = break (\\a->length a>1) $ groupBy (\\[a,b] [c,d] -> d (a1 `compare` b1)) xs in if b2==[] then putStrLn \"Poor Alex\" else putStrLn \"Happy Alex\" "}, {"source_code": "import qualified Data.Sequence as Seq\nimport Data.Foldable\nimport Control.Monad\n\ngetInput :: Int -> IO [String]\ngetInput n = replicateM n getLine\n\nparse :: [String] -> (Seq.Seq Integer, Seq.Seq Integer)\nparse input = (Seq.fromList prices, Seq.fromList qualities)\n where (prices, qualities) = getLists ints ([], [])\n ints = transform input\n\ngetLists :: [[Integer]] -> ([Integer], [Integer]) -> ([Integer], [Integer])\ngetLists [] tuple = tuple\ngetLists ([x,y]:rest) (prices, qualities) = getLists rest (x:prices, y:qualities)\n\ntransform :: [String] -> [[Integer]]\ntransform [] = []\ntransform (first:rest) = (map read (words first)) : transform rest\n\ngetAnswer :: Seq.Seq Integer -> Seq.Seq Integer -> String\ngetAnswer prices qualities = if findQaulityLaptop $ toList $ getCounter prices qualities\n then \"Happy Alex\"\n else \"Poor Alex\"\n\nfindQaulityLaptop :: [Integer] -> Bool\nfindQaulityLaptop [x] = False\nfindQaulityLaptop (first:second:rest) = if first < second\n then findQaulityLaptop (second:rest)\n else True\n\nemptySeq :: Integer -> Seq.Seq Integer\nemptySeq n = Seq.fromList (take (fromIntegral n) (cycle [0]))\n\ngetCounter :: Seq.Seq Integer -> Seq.Seq Integer -> Seq.Seq Integer\ngetCounter prices qualities = _getCounter prices qualities (emptySeq n)\n where n = fromIntegral $ Seq.length prices\n\n_getCounter :: Seq.Seq Integer -> Seq.Seq Integer -> Seq.Seq Integer -> Seq.Seq Integer\n_getCounter prices qualities counter = if prices == Seq.empty\n then counter\n else _getCounter pricesTail qualitiesTail (Seq.update (fromIntegral index) value counter)\n where pricesTail = Seq.drop 1 prices\n qualitiesTail = Seq.drop 1 qualities\n index = (Seq.index prices 0) - 1\n value = Seq.index qualities 0\n\nunpack :: Maybe Integer -> Integer\nunpack Nothing = -1\nunpack (Just x) = x\n\nmain :: IO ()\nmain = do\n n <- getLine\n input <- getInput (read n)\n let (prices, qualities) = parse input\n putStrLn $ getAnswer prices qualities"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nprocess::Int->[[Int]]->String\nprocess n q | qq == (q!!1) = \"Poor Alex\"\n | otherwise = \"Happy Alex\"\n where qq = sort (q!!1)\n\n\n\n\nmain=do\n n<-read <$> getLine::IO Int\n q<- transpose <$> sort <$> map(map (fromIntegral. fst.fromJust.C.readInteger)) <$> map C.words <$> C.lines <$> C.getContents::IO [[Int]]\n putStrLn $ process n q\n"}, {"source_code": "{-# LANGUAGE NPlusKPatterns #-}\n\nmodule Main where\n\nimport Data.List\nimport Data.Function\n\nmain :: IO ()\nmain = do\n n <- getInt\n n2s <- getInt2s n\n let ls = sort1 n2s\n let answer = check $ map snd ls\n putStrLn $ alex answer\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (map read . words) getLine\n\ntype Int2 = (Int, Int)\n\ngetInt2 :: IO Int2\ngetInt2 = do\n [a, b] <- getInts\n return (a, b)\n\n\ngetInt2s :: Int -> IO [Int2]\ngetInt2s 0 = return []\ngetInt2s (n + 1) = do\n n2 <- getInt2\n n2s <- getInt2s n\n return (n2 : n2s)\n\nsort1 :: [Int2] -> [Int2]\nsort1 = sortBy (compare `on` fst)\n\ncheck :: Ord a => [a] -> Bool\ncheck [] = True\ncheck (a : as) = check' a as\n\ncheck' :: Ord a => a -> [a] -> Bool\ncheck' a0 [] = True\ncheck' a0 (a : as) = a0 <= a && check' a as\n\nalex :: Bool -> String\nalex False = \"Happy Alex\"\nalex True = \"Poor Alex\"\n"}, {"source_code": "import Data.Function\nimport Data.List\n\nmain :: IO()\nmain = output . solve . input . tail . map read . words =<< getContents\n\ninput :: [Int] -> [(Int, Int)]\ninput [] = []\ninput (a:b:s) = (a, b):(input s)\n\nsolve :: [(Int, Int)] -> Bool\nsolve p = solve' (sortBy (on compare fst) p)\n where\n solve' :: [(Int, Int)] -> Bool\n solve' [] = False\n solve' [(_, _)] = False\n solve' ((_, b):(c, d):x) | b > d = True\n | otherwise = solve' ((c, d):x)\n\noutput :: Bool -> IO()\noutput b = putStrLn $ if b then \"Happy Alex\" else \"Poor Alex\"\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nmain = B.interact $ getAns . tail . map fst . mapMaybe B.readInt . B.words\n\ngetAns xs = if (dealArray xs) then B.pack \"Happy Alex\" else B.pack \"Poor Alex\"\n\ndealArray :: [Int] -> Bool\ndealArray [] = False\ndealArray (x:y:xs) = (x /= y) || dealArray xs\n\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nmain = B.interact $ getAns . tail . map fst . mapMaybe B.readInt . B.words\n\ngetAns :: [Int] -> B.ByteString\ngetAns xs = let ar = sort $ dealArray xs;\n\t\t\t\tbr = zipWith (\\(_, q1) (_, q2) -> q2 - q1) ar $ tail (cycle ar)\n\t\t\tin if any (<0) $ init br then B.pack \"Happy Alex\" else B.pack \"Poor Alex\"\n\ndealArray :: [Int] -> [(Int, Int)]\ndealArray [] = []\ndealArray (x:y:xs) = (x, y) : dealArray xs\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ getAns . tail . map read . words\n\ngetAns :: [Int] -> String\ngetAns xs = if (dealArray xs) then \"Happy Alex\" else \"Poor Alex\"\n\ndealArray :: [Int] -> Bool\ndealArray [] = False\ndealArray (x:y:xs) = (x /= y) || dealArray xs\n"}, {"source_code": "import Data.List (sort)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getContents >>= putStrLn . output . solve . map (map (fst . fromJust . B.readInt) . B.words) . tail . B.lines\n\nsolve :: [[Int]] -> Bool\nsolve = or . (\\xs -> zipWith (>) xs (tail xs)) . map (!!1) . sort\n\noutput :: Bool -> String\noutput True = \"Happy Alex\"\noutput _ = \"Poor Alex\"\n"}, {"source_code": "import Data.List\nsolve [a,b] = if a==b then \"Poor Alex\" else \"Happy Alex\"\nmain = interact $ solve . transpose . map words. tail . lines"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ getAns . tail . map read . words\n\ngetAns :: [Int] -> String\ngetAns xs = if (any (\\(x, y) -> x /= y) $ dealArray xs) then \"Happy Alex\" else \"Poor Alex\"\n\ndealArray :: [Int] -> [(Int, Int)]\ndealArray [] = []\ndealArray (x:y:xs) = (x, y) : dealArray xs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n a <- replicateM n getInts\n\n let\n b = or $ zipWith (\\[a, b] [c, d] -> a < c && b > d) a' (tail a') where a' = sort a\n\n putStrLn $ if b then \"Happy Alex\" else \"Poor Alex\"\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n res <- doWork n\n let restr = if res then \"Happy\" else \"Poor\"\n putStrLn (restr ++ \" Alex\")\n\ndoWork 0 = return False\ndoWork n = do\n inp <- getLine\n let (a:b:[]) = map (read::(String->Int)) $ words inp\n if a /= b then return True else doWork $ n-1"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\ngetSnd :: [(Int, Int)] -> [Int]\ngetSnd = map snd\n\nsolve' :: [(Int, Int)] -> B.ByteString\nsolve' ys\n | (getSnd $ sort ys) == (sort $ getSnd ys) = B.pack \"Poor Alex\"\n | otherwise = B.pack \"Happy Alex\"\n\nmain :: IO ()\nmain = do\n B.interact $ solve' . map parse . tail . B.lines\n\nparse l = (read' a, read' b) where [a, b] = B.words l\n\nread' bs = i where Just (i, _) = B.readInt bs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.IO\n\nsolve :: [Int] -> [Int] -> String\nsolve price quality = get_state $ ((==) `on` process) price quality\n where\n process xs = map snd $ sort $ zip xs [1 ..]\n get_state False = \"Happy Alex\"\n get_state True = \"Poor Alex\"\n\nmain :: IO ()\nmain = do\n getLine\n [as, bs] <- transpose . map (map fst . mapMaybe BS.readInt . BS.words) . BS.lines <$> BS.getContents\n-- [as, bs] <- transpose . scan . BS.unpack <$> BS.getContents\n say $ solve as bs\n\nsay :: DS a => a -> IO ()\nsay = putStrLn . display\n\nget :: DS a => IO a\nget = scan <$> getLine\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\nclass (Read a, Show a) => DS a where\n display :: a -> String\n scan :: String -> a\n display = show\n scan = read\n\ninstance DS String where\n display = id\n scan = id\n\ninstance DS [a] => DS [[a]] where\n display = unlines . map display\n scan = map scan . lines\n\ninstance DS a => DS [a] where\n display = unwords . map display\n scan = map scan . words\n\ninstance DS Int\ninstance DS Double\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> (solve =<< forM [1..read n] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve xs = let [m11,m12]=maximumBy (\\[a1,a2] [b1,b2] -> (a1 `compare` b1) `mappend` (a2 `compare` b2) ) xs \n [m21,m22]=maximumBy (\\[a1,a2] [b1,b2] -> (a2 `compare` b2) `mappend` (b1 `compare` a1) ) xs in if m22>m12 && m21[[Int]]->String\nprocess n q | qq == (q!!1) = \"Happy Alex\"\n | otherwise = \"Poor Alex\"\n where qq = sort (q!!1)\n\n\n\n\nmain=do\n n<-read <$> getLine::IO Int\n q<- transpose <$> sort <$> map(map (fromIntegral. fst.fromJust.C.readInteger)) <$> map C.words <$> C.lines <$> C.getContents::IO [[Int]]\n putStrLn $ process n q\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess q | x== [] = \"NO\"\n | otherwise = \"YES\"\n where x = take 1 [1|[i1,i2]<-q, [j1,j2]<-q , i1j2]\n\n\n\n\nmain=do\n n<-getLine\n q<- map(map read) <$> map words <$> lines <$> getContents::IO [[Int]]\n putStrLn $ process q\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:m:as) = snd $ maximum [ ((a + m - 1) `div` m, i) | (i, a) <- zip [1..] as ]\nsolve _ = undefined\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . output . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Bool\nsolve ab = and [ b > b' | [ a, b ] <- ab, [ a', b' ] <- ab, a < a' ]\n\noutput :: Bool -> String\noutput True = \"Happy Alex\"\noutput _ = \"Poor Alex\"\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Control.Applicative\n\nsortTuple :: [(Int, Int)] -> [(Int, Int)]\nsortTuple = sortBy (comparing fst)\n\ngetSnd :: [(Int, Int)] -> [Int]\ngetSnd = map snd\n\nsolve :: [Int] -> String\nsolve (y:ys:[])\n | y > ys = \"Happy Alex\"\n | otherwise = \"Poor ALex\"\nsolve (y:ys:yss)\n | y > ys = \"Happy Alex\"\n | otherwise = solve (ys:yss)\n\nmain :: IO ()\nmain = do\n n <- readLn\n getInput n >>= putStrLn . solve . getSnd . sortTuple\n\ngetInput :: Int -> IO [(Int, Int)]\ngetInput 0 = return []\ngetInput n = do\n liftA2 (:) current next where\n current = getLine >>= return . (\\xs -> (head xs, last xs)) . map read . words\n next = getInput (n-1)\n"}, {"source_code": "import qualified Data.Sequence as Seq\nimport Data.Foldable\n\ngetIntSequence :: IO (Seq.Seq Integer)\ngetIntSequence = do\n list <- getLine\n return (Seq.fromList $ map read (words list))\n\ngetAnswer :: Seq.Seq Integer -> Seq.Seq Integer -> String\ngetAnswer prices qualities = if findQaulityLaptop $ toList $ getCounter prices qualities\n then \"Happy Alex\"\n else \"Poor Alex\"\n\nfindQaulityLaptop :: [Integer] -> Bool\nfindQaulityLaptop [x] = False\nfindQaulityLaptop (first:second:rest) = if first < second\n then findQaulityLaptop (second:rest)\n else True\n\nemptySeq :: Integer -> Seq.Seq Integer\nemptySeq n = Seq.fromList (take (fromIntegral n) (cycle [0]))\n\ngetCounter :: Seq.Seq Integer -> Seq.Seq Integer -> Seq.Seq Integer\ngetCounter prices qualities = _getCounter prices qualities (emptySeq n)\n where n = fromIntegral $ Seq.length prices\n\n_getCounter :: Seq.Seq Integer -> Seq.Seq Integer -> Seq.Seq Integer -> Seq.Seq Integer\n_getCounter prices qualities counter = if prices == Seq.empty\n then counter\n else _getCounter pricesTail qualitiesTail (Seq.update (fromIntegral index) value counter)\n where pricesTail = Seq.drop 1 prices\n qualitiesTail = Seq.drop 1 qualities\n index = (Seq.index prices 0) - 1\n value = Seq.index qualities 0\n\nunpack :: Maybe Integer -> Integer\nunpack Nothing = -1\nunpack (Just x) = x\n\nmain :: IO ()\nmain = do\n n <- getLine\n prices <- getIntSequence\n qualities <- getIntSequence\n putStrLn $ getAnswer prices qualities"}, {"source_code": "main = do\n n <- readLn :: IO Int\n res <- doWork n\n let restr = if res then \"Happy\" else \"Poor\"\n putStrLn (restr ++ \" Alex\")\n\ndoWork 0 = return True\ndoWork n = do\n inp <- getLine\n let (a:b:[]) = map (read::(String->Int)) $ words inp\n if a == b then return False else doWork $ n-1"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\nimport Data.List\n\nsolve :: [Int] -> [Int] -> String\nsolve price quality = get_state $ ((==) `on` process) price quality\n where\n process xs = map snd $ sort $ zip xs [1 ..]\n get_state False = \"Happy Alex\"\n get_state True = \"Poor Alex\"\n\nmain :: IO ()\nmain = do\n n <- get\n [as, bs] <- replicateM n get\n say as\n say bs\n say $ solve as bs\n\nsay :: DS a => a -> IO ()\nsay = putStrLn . display\n\nget :: DS a => IO a\nget = scan <$> getLine\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\nclass (Read a, Show a) => DS a where\n display :: a -> String\n scan :: String -> a\n display = show\n scan = read\n\ninstance {-# OVERLAPPING #-} DS String where\n display = id\n scan = id\n\ninstance {-# OVERLAPPING #-} DS [a] => DS [[a]] where\n display = unlines . map display\n scan = map scan . lines\n\ninstance DS a => DS [a] where\n display = unwords . map display\n scan = map scan . words\n\ninstance DS Int\ninstance DS Double\n"}], "src_uid": "c21a84c4523f7ef6cfa232cba8b6ee2e"} {"source_code": "import Data.List (groupBy, sort)\n\nmain = do\n\ts <- getLine\n\n\tlet\n\t\tans = h ++ c ++ (reverse h)\n\t\t\twhere\n\n\t\t\t\tcs = map (\\l -> (head l, length l)) . groupBy (==) $ sort s\n\n\t\t\t\tes = filter (even . snd) cs\n\t\t\t\tos = filter (odd . snd) cs\n\n\t\t\t\th = concat . map (\\(a, c) -> replicate (c `div` 2) a) $ sort (es ++ os')\n\t\t\t\t\twhere\n\t\t\t\t\t\tos' = filter (\\(_, c) -> c > 0) . concat $ zipWith move os (reverse os)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tmove (a1, c1) (a2, c2) \n\t\t\t\t\t\t\t\t\t| a1 < a2 = [(a1, c1 + 1), (a2, c2 - 1)]\n\t\t\t\t\t\t\t\t\t| a1 == a2 = [(a1, c1 - 1)]\n\t\t\t\t\t\t\t\t\t| otherwise = []\n\n\t\t\t\tc = if odd l then [fst (os !! (l `div` 2))] else []\n\t\t\t\t\twhere\n\t\t\t\t\t\tl = length os\n\n\tputStrLn ans\n", "positive_code": [{"source_code": "import Data.List (groupBy, sort)\n\nmain = do\n\ts <- getLine\n\n\tlet\n\t\tans = h ++ (if odd (length s) then [fst (os !! (length os `div` 2))] else []) ++ (reverse h)\n\t\t\twhere\n\n\t\t\t\tcs = map (\\l -> (head l, length l)) . groupBy (==) $ sort s\n\n\t\t\t\tes = filter (even . snd) cs\n\t\t\t\tos = filter (odd . snd) cs\n\n\t\t\t\th = concat . map (\\(a, c) -> replicate (c `div` 2) a) $ sort (es ++ os')\n\t\t\t\t\twhere\n\t\t\t\t\t\tos' = filter (\\(_, c) -> c > 0) . concat $ zipWith move os (reverse os)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tmove (a1, c1) (a2, c2) \n\t\t\t\t\t\t\t\t\t| a1 < a2 = [(a1, c1 + 1), (a2, c2 - 1)]\n\t\t\t\t\t\t\t\t\t| a1 == a2 = [(a1, c1 - 1)]\n\t\t\t\t\t\t\t\t\t| otherwise = []\n\n\tputStrLn ans\n"}, {"source_code": "import Control.Applicative\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n\tstr <- filter (not . isSpace) . BS.unpack <$> BS.getContents\n\tlet\tfreq :: UArray Char Int\n\t\tfreq = accumArray (+) 0 ('a', 'z') [(c, 1) | c <- str]\n\tlet toChange = map fst . filter (odd . snd) $ assocs freq;\n\t\tlen = length toChange;\n\t\tnew = [(c, 1) | c <- take (len `div` 2) toChange] ++ [(c, -1) | c <- take (len `div` 2) $ reverse toChange]\n\tlet\tfreq' :: UArray Char Int\n\t\tfreq' = accumArray (+) 0 ('a', 'z') $ (assocs freq) ++ new\n\tlet newstr = concatMap (\\(c, fr) -> replicate (fr `div` 2) c) $ assocs freq'\n\tputStrLn $ newstr ++ (maybe \"\" (return . fst) . find (odd . snd) $ assocs freq') ++ (reverse newstr)\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n\tstr <- filter (not . isSpace) . BS.unpack <$> BS.getContents\n\tlet\tfreq :: UArray Char Int\n\t\tfreq = accumArray (+) 0 ('a', 'z') [(c, 1) | c <- str]\n\tlet toChange' = filter (odd . snd) $ assocs freq;\n\t\tlen = length toChange';\n\t\ttoChange = if even len then toChange' else delete (toChange' !! ((len `div` 2))) toChange';\n\t\tfs = ((++) `on` (replicate (len `div` 2))) (second (+ 1)) (second $ subtract 1);\n\t\tnew = zipWith ($) fs toChange\n\tlet\tfreq' :: UArray Char Int\n\t\tfreq' = accumArray (flip const) 0 ('a', 'z') $ (assocs freq) ++ new\n\tlet newstr = concatMap (\\(c, fr) -> replicate (fr `div` 2) c) $ assocs freq'\n\tputStrLn $ newstr ++ ((if odd len then return $ fst . fromJust . find (odd . snd) $ assocs freq' else \"\") ++ (reverse newstr))\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char (ord, chr)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.Monoid ((<>))\nimport Data.Functor ((<$>))\n\n\nchanges :: IntMap Int -> IntMap Int -> (IntMap Int, IntMap Int)\nchanges evens odds\n | IM.size odds <= 1 = (evens, odds)\n | otherwise = \n let\n (min_x, min_c) = IM.findMin odds\n (max_x, max_c) = IM.findMax odds\n odds' = IM.delete max_x (IM.delete min_x odds)\n evens' | max_c > 1 = IM.insert max_x (max_c-1) evens\n | otherwise = evens\n evens'' = IM.insert min_x (min_c+1) evens'\n in\n changes evens'' odds'\n\n\nmakeHalf :: IntMap Int -> ByteString\nmakeHalf = IM.foldlWithKey' (\\bs k x -> bs <> BS.replicate (x`div`2) (chr k)) BS.empty\n\nmakePalindrome :: (IntMap Int, IntMap Int) -> ByteString\nmakePalindrome (evens, odds) \n | IM.null odds = half <> flah\n | otherwise = half <> BS.singleton (chr ox) <> flah\n where\n (ox,oc) = IM.findMax odds\n evens' | IM.null odds = evens\n | oc > 1 = IM.insert ox (oc-1) evens\n | otherwise = evens\n half = makeHalf evens'\n flah = BS.reverse half\n \n\n\nmain :: IO ()\nmain = do\n wd <- head . BS.words <$> BS.getLine\n let counts = BS.foldl' (\\t c -> IM.insertWith (\\_ o -> o+1) (ord c) 1 t) IM.empty wd\n --print counts\n let (evens, odds) = IM.partition even counts\n --print evens\n --print odds\n let eos = changes evens odds\n let p = makePalindrome eos\n BS.putStrLn p\n"}, {"source_code": "-- C. Make Palindrome\n\ncount :: Char -> String -> Int\ncount = (length .) . filter . (==)\n\ncountaz :: String -> [Int]\ncountaz = flip map ['a'..'z'] . flip count\n\nchange :: [Int] -> [Int]\n-- change x = change' (length . filter odd $ x) x\nchange = change' =<< length . filter odd\n where change' :: Int -> [Int] -> [Int]\n change' _ [] = []\n change' k (h:t) | even h = h : change' k t\n | otherwise = case k of 0 -> h - 1 : change' 0 t\n 1 -> h : change' 0 t\n _ -> h + 1 : change' (k - 2) t\n\n\npalindrom :: [Int] -> String\npalindrom x = halfString x ++ oddString x ++ (reverse . halfString) x\n where string, halfString, oddString :: [Int] -> String\n string = concat . zipWith (flip replicate) ['a'..'z']\n halfString = string . map (`div` 2)\n oddString = string . map (`mod` 2)\n\nsolve :: String -> String\nsolve = palindrom . change . countaz\n\nmain :: IO()\nmain = getLine >>= putStrLn . solve\n\n"}, {"source_code": "-- C. Make Palindrome\n\ncount :: Char -> String -> Int\ncount = (length .) . filter . (==)\n\ncountaz :: String -> [Int]\ncountaz = flip map ['a'..'z'] . flip count\n\nchange :: [Int] -> [Int]\nchange x = change' (length (filter odd x)) x\n where change' :: Int -> [Int] -> [Int]\n change' _ [] = []\n change' k (h:t) | even h = h : change' k t\n | otherwise = case k of 0 -> h - 1 : change' 0 t\n 1 -> h : change' 0 t\n _ -> h + 1 : change' (k - 2) t\n\nazString :: [Int] -> String\nazString = concat . zipWith (flip replicate) ['a'..'z']\n\npalindrom :: [Int] -> String\npalindrom x = azString (map (`div` 2) x) ++ azString (map (`mod` 2) x) ++ reverse (azString (map (`div` 2) x))\n\nsolve :: String -> String\nsolve = palindrom . change . countaz\n\nmain :: IO()\nmain = getLine >>= putStrLn . solve\n\n"}, {"source_code": "--incerc sa portez solutia in haskell\nimport Data.List\nimport Data.Tuple\nimport Control.Monad\nf x = ( snd x ) `mod` 2 == 1\ng x = ( snd x ) `mod` 2 == 0\n\nrepl a b\n\t| fst a < fst b = [(fst a, snd a + 1), (fst b, snd b - 1)]\n\t| fst a == fst b = [(fst a, snd a - 1)]\n\t| otherwise = []\n\n--multumesc stack overflow\nrepli (a,b) = replicate (b `div` 2) a\n\nmain = do\n x <- getLine\n --simuleaza map de frecventa\n let cs = map (\\l -> (head l, length l)) . groupBy (\\x y -> x == y) $ sortBy (\\a b -> compare a b) x\n --let cs = sortBy (\\a b -> compare a b) x\n --let cs = groupBy (\\x y -> x == y) $ sort [1,2,3,2,1]\n let impare = filter f cs\n --let pare = filter (!f) cs nope nu merge\n let pare = filter g cs\n --indexul la map se face cu !!\n let mid = if odd (length impare) then [fst $ impare !! (length impare `div` 2)] else []\n let invers = reverse impare\n let delete_odds = zipWith repl impare invers\n let delete_zero = filter (\\x -> snd x > 0) $ concat delete_odds\n let pare' = pare ++ delete_zero\n let pare_in_ordine = sort pare'\n let first_half = map repli pare_in_ordine\n --print first_half\n --print second_half\n let second_half = map repli $ reverse pare_in_ordine\n --print mid\n let answer = first_half ++ [mid] ++ second_half\n --let final = filter (/='0') . unwords answer\n let final = concat answer\n putStrLn final\n "}], "negative_code": [], "src_uid": "f996224809df700265d940b12622016f"} {"source_code": "main = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tanswer = if l <= r then r - l else 0\n\t\t\twhere\n\t\t\t\tl = find s t\n\t\t\t\tr = length t - (find (reverse s) (reverse t)) + 1\n\n\t\t\t\tfind s t = find' s t 0\n\t\t\t\t\twhere\n\t\t\t\t\t\tfind' \"\" _ i = i\n\t\t\t\t\t\tfind' _ \"\" i = i\n\t\t\t\t\t\tfind' (c:s) (d:t) i =\n\t\t\t\t\t\t\tif c == d\n\t\t\t\t\t\t\t\tthen find' s t (i + 1)\n\t\t\t\t\t\t\t\telse find' (c:s) t (i + 1)\n\n\tprint answer\n", "positive_code": [{"source_code": "main :: IO()\nmain = do\n s <- getLine\n t <- getLine\n let f = solve succ 0 s t\n b = solve pred (1+length t) (reverse s) (reverse t)\n if or [b B.ByteString -> Maybe Int\ngao a b\n | B.null a = Just $ B.length b\n | B.null b || B.null b' = Nothing\n | otherwise = gao (B.tail a) (B.tail b')\n where\n b' = B.dropWhile (/= B.head a) b\n\nmain :: IO ()\nmain = do\n a <- chomp <$> B.getLine\n b <- chomp <$> B.getLine\n let n = B.length b\n x = gao a b\n y = (gao `on` B.reverse) a b\n print $ case liftM2 (\\i j -> i + j - n) x y of\n Just k | k >= 0 -> k + 1\n _ -> 0\n where\n chomp s\n | B.null s || B.last s /= 13 = s\n | otherwise = B.init s\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Function\nimport qualified Data.ByteString as B\n\ngao :: B.ByteString -> B.ByteString -> Maybe Int\ngao a b\n | B.null a = Just $ B.length b\n | B.null b = Nothing\n | otherwise = gao (B.tail a) $ B.tail $ B.dropWhile (/= B.head a) b\n\nmain :: IO ()\nmain = do\n a <- B.getLine\n b <- B.getLine\n let n = B.length b\n x = gao a b\n y = (gao `on` B.reverse) a b\n print $ case liftM2 (\\i j -> i + j - n) x y of\n Just k | k >= 0 -> k + 1\n _ -> 0\n"}], "src_uid": "724fa4b1d35b8765048857fa8f2f6802"} {"source_code": "import Data.List\nimport Data.Function\nr2 = sum . map (^2)\n(-.) = zipWith (-)\ninfixl 6 -.\nort a b = (0==) $ sum $ zipWith (*) a b \napplyInv p a = map snd $ sort $ zip p a\nsolve (a:as) = take 1 [ (a :) $ applyInv p $ vs ++ us \n | p <- permutations [0..6],\n p!!0 Bool\nisCube (p : ps) =\n distanceSq p a > 0\n && distanceSq p a == distanceSq p b && distanceSq p c == distanceSq p a\n && dot va vb == 0 && dot vb vc == 0 && dot va vc == 0\n && sort (genCube p va vb vc) == sort (p : ps)\n where\n va = subtract a p\n vb = subtract b p\n vc = subtract c p\n (a : b : c : _) = sortBy (comparing $ distanceSq p) ps\n\ns :: [[Int64]] -> [[[Int64]]]\ns (p : ps) = do\n ps' <- mapM permutations ps\n let ps'' = map (\\[x,y,z] -> (x,y,z)) (p : ps')\n if isCube ps'' then [p : ps'] else []\n\np :: [[[Int64]]] -> String\np [] = \"NO\"\np (s : _) = unlines $ \"YES\" : map (unwords . map show) s\n\nmain = interact $ p . s . map (map read . words) . lines\n"}, {"source_code": "import Data.List\nimport Data.Function\nr2 = sum . map (^2)\n(-.) = zipWith (-)\ninfixl 6 -.\nort a b = (0==) $ sum $ zipWith (*) a b \napplyInv p a = map snd $ sort $ zip p a\nsolve (a:as) = take 1 [ (a :) $ applyInv p $ vs ++ us \n | p <- permutations [0..6],\n p!!0 0 && \n ort a b && ort a c && ort b c &&\n sort rest == sort [a+.b,a+.c,b+.c,a+.b+.c]\nisCube (a:as) = isCube0 $ sortWith r2 $ map (zipWith (-) a) as\nsolve ::[[Int]]->[[[Int]]]\nsolve = filter isCube . take (6^7) . mapM permutations \n\nshowA [] = \"NO\"\nshowA (ans:_) = unlines $ \"YES\" : map (unwords . map show) ans\n\nmain = interact $ showA . solve . map (map read . words) . lines"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Data.Int\nimport Prelude hiding(subtract)\n\ndistanceSq (x0, y0, z0) (x1, y1, z1) = (x0 - x1) ^ 2 + (y0 - y1) ^ 2 + (z0 - z1) ^ 2\n\ndot (x0, y0, z0) (x1, y1, z1) = x0 * x1 + y0 * y1 + z0 * z1\n\nsubtract (x0, y0, z0) (x1, y1, z1) = (x0 - x1, y0 - y1, z0 - z1)\nadd (x0, y0, z0) (x1, y1, z1) = (x0 + x1, y0 + y1, z0 + z1)\n\ngenCube p va vb vc = map (foldr add p) (subsequences [va,vb,vc])\n\nisCube :: [(Int64, Int64, Int64)] -> Bool\nisCube (p : ps)\n | (distanceSq p a == distanceSq p b) && (distanceSq p c == distanceSq p a)\n && (dot va vb == 0) && (dot vb vc == 0) && dot va vc == 0\n =\n sort (genCube p va vb vc) == sort (p : ps)\n | otherwise = False\n where\n va = subtract a p\n vb = subtract b p\n vc = subtract c p\n (a : b : c : _) = sortBy (comparing $ distanceSq p) ps\n\ns :: [[Int64]] -> [[[Int64]]]\ns (p : ps) = do\n ps' <- mapM permutations ps\n let ps'' = map (\\[x,y,z] -> (x,y,z)) (p : ps')\n if isCube ps'' then [p : ps'] else []\n\np :: [[[Int64]]] -> String\np [] = \"NO\"\np (s : _) = unlines $ \"YES\" : map (unwords . map show) s\n\nmain = interact $ p . s . map (map read . words) . lines\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Prelude hiding(subtract)\n\ndistanceSq (x0, y0, z0) (x1, y1, z1) = (x0 - x1) ^ 2 + (y0 - y1) ^ 2 + (z0 - z1) ^ 2\n\ndot (x0, y0, z0) (x1, y1, z1) = x0 * x1 + y0 * y1 + z0 * z1\n\nsubtract (x0, y0, z0) (x1, y1, z1) = (x0 - x1, y0 - y1, z0 - z1)\nadd (x0, y0, z0) (x1, y1, z1) = (x0 + x1, y0 + y1, z0 + z1)\n\ngenCube p va vb vc = map (foldr add p) (subsequences [va,vb,vc])\n\nisCube :: [(Int, Int, Int)] -> Bool\nisCube (p : ps)\n | (distanceSq p a == distanceSq p b) && (distanceSq p c == distanceSq p a)\n && (dot va vb == 0) && (dot vb vc == 0) && dot va vc == 0\n =\n sort (genCube p va vb vc) == sort (p : ps)\n | otherwise = False\n where\n va = subtract a p\n vb = subtract b p\n vc = subtract c p\n (a : b : c : _) = sortBy (comparing $ distanceSq p) ps\n\ns :: [[Int]] -> [[[Int]]]\ns (p : ps) = do\n ps' <- mapM permutations ps\n let ps'' = map (\\[x,y,z] -> (x,y,z)) (p : ps')\n if isCube ps'' then [p : ps'] else []\n\np :: [[[Int]]] -> String\np [] = \"NO\"\np (s : _) = unlines $ \"YES\" : map (unwords . map show) s\n\nmain = interact $ p . s . map (map read . words) . lines\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Prelude hiding(subtract)\n\ndistanceSq (x0, y0, z0) (x1, y1, z1) = (x0 - x1) ^ 2 + (y0 - y1) ^ 2 + (z0 - z1) ^ 2\n\ndot (x0, y0, z0) (x1, y1, z1) = x0 * x1 + y0 * y1 + z0 * z1\n\nsubtract (x0, y0, z0) (x1, y1, z1) = (x0 - x1, y0 - y1, z0 - z1)\nadd (x0, y0, z0) (x1, y1, z1) = (x0 + x1, y0 + y1, z0 + z1)\n\ngenCube p va vb vc = map (foldr add p) (subsequences [va,vb,vc])\n\nisCube :: [(Int, Int, Int)] -> Bool\nisCube (p : ps)\n | (distanceSq p a == distanceSq p b) && (distanceSq p c == distanceSq p a)\n && (dot va vb == 0) && (dot vb vc == 0) && dot va vc == 0\n =\n sort (genCube p va vb vc) == sort (p : ps)\n | otherwise = False\n where\n va = subtract a p\n vb = subtract b p\n vc = subtract c p\n (a : b : c : _) = sortBy (comparing $ distanceSq p) ps\n\ns :: [[Int]] -> [[[Int]]]\ns (p : ps) = do\n ps' <- mapM permutations ps\n let ps'' = map (\\[x,y,z] -> (x,y,z)) (p : ps')\n if isCube ps'' then [p : ps'] else []\n\np :: [[[Int]]] -> String\np [] = \"NO\"\np (s : _) = unlines $ \"YES\" : map (unwords . map show) s\n\nmain = interact $ p . s . map (map read . words) . lines\n"}], "src_uid": "55da4611bc78d55c228d0ce78bd02fd3"} {"source_code": "import Data.List\nimport Data.Int\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int64]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int64) $ words line\n\nreadInt :: IO Int64\nreadInt = do\n line <- getLine\n return $ (read::String->Int64) $ line\n\nf :: Int64 -> Int64 -> Int64\nf curPower xLeft = \n let s = (curPower) * (curPower - 1) `div` 2 in\n if s > xLeft then 0 else 1 + f (curPower * 2) (xLeft - s)\n\nsolve :: IO ()\nsolve = do\n n <- readInt \n print $ f 2 n\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [0..t-1] $ (\\i -> solve)", "positive_code": [{"source_code": "import Control.Monad\n\nsize :: Integer -> Integer\nsize n = div (n * (n+1)) 2\n\nnices :: [Integer]\nnices = iterate (\\x -> 2*x + 1) 1\n\nsolve :: Integer -> Integer\nsolve = go 0 nices where\n go k (tar:tars) tot = case tot - size tar of\n v | v < 0 -> k\n | True -> go (k+1) tars v\n go _ _ _ = error \"nices is finite???\"\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n x <- read <$> getLine\n print $ solve x\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n print $ solve 1 n\n\nsolve 100 _ = 0\nsolve _ 0 = 0\nsolve p n\n | c <= n = 1 + solve (succ p) (n - c)\n | otherwise = solve (succ p) n\n where\n d = 2 ^ p - 1\n c = (d * (d + 1)) `div` 2\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n print $ solve n\n\nsolve :: Integer -> Integer\nsolve n = (\\x -> x-1) $ snd $ head $ filter (\\x ->fst x>n) $ zip liste2 [1..]\n\nf :: Integer -> Integer\nf n = ((2^n)-1)*(2^(n-1))\n\nliste :: [Integer]\nliste = map f [1..]\n\nliste2 :: [Integer]\nliste2 = scanl1 (+) liste\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n print $ solve 100 n\n\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve p n\n | c <= n = 1 + solve (pred p) (n - c)\n | otherwise = solve (pred p) n\n where\n d = 2 ^ p - 1\n c = (d * (d + 1)) `div` 2\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (read::String->Int) $ line\n\nf :: Int -> Int -> Int\nf curPower xLeft = \n let s = (curPower) * (curPower - 1) `div` 2 in\n if s > xLeft then 0 else 1 + f (curPower * 2) (xLeft - s)\n\nsolve :: IO ()\nsolve = do\n n <- readInt \n print $ f 2 n\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [0..t-1] $ (\\i -> solve)"}], "src_uid": "f0806ab99cf4da228abe3cd8073884d9"} {"source_code": "gcdOfList :: [Int]->Int\ngcdOfList x = case x of [] -> 0\n (x : xs) -> gcd x (gcdOfList xs)\n \nsolve :: String->Int->String\nsolve s n = \n if rem ( (div ma g) - n) 2 == 0 then \"Bob\" else \"Alice\"\n where a = map (read :: String->Int) (words s)\n ma = maximum a\n g = gcdOfList a\n \nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ solve s ((read :: String->Int) n)", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n n <- liftM read getLine :: IO Int\n xs <- liftM (map read . words) getLine :: IO [Int]\n let moves = maximum xs `div` foldl1 gcd xs - n\n putStrLn (if moves `mod` 2 == 1 then \"Alice\" else \"Bob\")\n"}, {"source_code": "module Main where\n \nimport Control.Applicative\nimport Data.List\n\ndata Person = Alice | Bob deriving (Eq, Show)\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve' n ns--solve n [] ns\n\nsolve' :: Int -> [Int] -> Person\nsolve' n xs = \n let g = foldl1 (\\a b -> gcd a b) xs\n in if odd (maximum (map (`div`g) xs) - n)\n then Alice\n else Bob\n\n\nsolve :: Int -> [Int] -> [Int] -> Person\nsolve n xs [] = if odd $ (length xs - n)\n then Alice\n else Bob\nsolve n xs ys = \n let newXs = ys ++ xs\n newYs = (nub $ concat $ map (\\y -> nub $ filter (/=0) $ map (\\x -> abs (x-y) ) newXs) ys ) \\\\ newXs\n in solve n newXs newYs\n\n"}, {"source_code": "import Data.List\n\nans xs= let l=m`div`g-(length xs) in if odd l then \"Alice\" else \"Bob\"\n where g=foldl1 gcd xs\n m=maximum xs \nmain = do\n m<-getLine\n n<-getLine\n let input = map read$ words n\n putStrLn $ ans input"}, {"source_code": "import Control.Monad\n\nmain = do\n\tn <- readLn :: IO Int\n\ta <- (map read . words) `liftM` getLine :: IO [Int]\n\tputStrLn$ [\"Bob\", \"Alice\"]!!(mod (div (foldr1 max a) (foldr1 gcd a) - n) 2)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLine\n l <- readsLine\n putStrLn $ if solve n l then \"Alice\" else \"Bob\"\n\n\nsolve :: Int -> [Int] -> Bool\nsolve n l = odd (a - length l)\n where \n d = foldl1 gcd l\n m = maximum l\n a = m `div` d\n \n\n\n\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.Array ((!), bounds, listArray)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> String\nsolve xs\n | odd (max' `div` gcd' - n) = \"Alice\"\n | otherwise = \"Bob\"\n where\n n = length xs\n max' = maximum xs\n gcd' = foldl1 gcd xs\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nmain :: IO ()\nmain = getLine >> reads >>= putStrLn . solve"}, {"source_code": "\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n as <- fmap ((fmap read) . words) getLine :: IO [Int]\n let d = foldr1 gcd as\n let r = even $ (div (maximum as) d)-n\n putStr $ if r then \"Bob\" else \"Alice\"\n"}, {"source_code": "module Main where\n \nimport Control.Applicative\nimport Data.List\n\ndata Person = Alice | Bob deriving (Eq, Show)\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve n ns--solve n [] ns\n\nsolve :: Int -> [Int] -> Person\nsolve n xs = \n let g = foldl1 (\\a b -> gcd a b) xs\n in if odd (maximum (map (`div`g) xs) - n)\n then Alice\n else Bob\n\n"}, {"source_code": "gcd_ :: Int -> Int -> Int\ngcd_ x y = if y == 0 then x else gcd y (x `rem` y)\n\n\nmain = do\n n <- readLn :: IO Int\n line <- getLine\n let\n a = map (read :: String -> Int) $ words line\n d = foldl1 gcd_ a\n m = maximum $ map (\\x -> x `div` d) a\n in putStrLn $ if (n - m) `rem` 2 /= 0 then \"Alice\" else \"Bob\"\n"}, {"source_code": "---------------------Import--------------------------- {{{\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\nimport Data.Ratio -- x = 5%6\nimport Data.Bits -- (.&.), (.|.), shiftL...\nimport Text.Printf -- printf \"%0.6f\" (1.0)\nimport qualified Data.ByteString.Char8 as BS-- }}}\n\n---------------------Input---------------------------- {{{\ngetInteger = (\\(Just (x,_)) -> x). BS.readInteger\ngetInt = (\\(Just (x,_)) -> x). BS.readInt\n\ngetIntArray = readIntArray\ngetIntegerArray = readIntegerArray\n\nreadIntArray input = \n case x of\n Just (a, xs) -> a : readIntArray xs\n Nothing -> []\n where\n x = BS.readInt. BS.dropWhile isSpace $ input \n\nreadIntegerArray input = \n case x of\n Nothing -> []\n Just (y, ys) -> y : readIntegerArray ys\n where\n x = BS.readInteger. BS.dropWhile isSpace $ input\n------------------------------------------------------ }}}\n\nmain :: IO ()\nmain = BS.getContents >>= putStrLn. ([\"Bob\", \"Alice\"]!!). fromIntegral .(`mod` 2).solve. tail. readIntegerArray\n where \n solve xs = (maximum xs ) `div` g - fromIntegral (length xs)\n where\n g = gcd' xs\n gcd' :: [Integer] -> Integer\n gcd' (a:as) = foldl' (gcd) a as\n\n"}, {"source_code": "gcdlist :: [Int] -> Int\ngcdlist (x : y : xs) = gcdlist ((gcd x y) : xs)\ngcdlist (x : []) = x\n\nmain = do\n\trawn <- getLine\n\trawinput <- getLine\n\tlet n = read rawn :: Int\n\tlet input = map read (words rawinput) :: [Int]\n\tputStr $ if (odd ((div (maximum input) (gcdlist input)) - n)) then \"Alice\" else \"Bob\"\n"}], "negative_code": [{"source_code": "module Main where\n \nimport Control.Applicative\nimport Data.List\n\ndata Person = Alice | Bob deriving (Eq, Show)\n\nmain = do\n n <- read <$> getLine\n ns <- map read <$> words <$> getLine\n print $ solve' n ns--solve n [] ns\n\nsolve' :: Int -> [Int] -> Person\nsolve' n xs = if odd (maximum xs - n)\n then Alice\n else Bob\n\n\nsolve :: Int -> [Int] -> [Int] -> Person\nsolve n xs [] = if odd $ (length xs - n)\n then Alice\n else Bob\nsolve n xs ys = \n let newXs = ys ++ xs\n newYs = (nub $ concat $ map (\\y -> nub $ filter (/=0) $ map (\\x -> abs (x-y) ) newXs) ys ) \\\\ newXs\n in solve n newXs newYs\n\n"}, {"source_code": "import Data.List\n\nans xs= let l=m-(length xs) in if odd l then \"Alice\" else \"Bob\"\n where m=maximum xs\nmain = do\n m<-getLine\n n<-getLine\n let input = map (\\x->read x::Int) $ words n\n putStrLn $ ans input"}, {"source_code": "gcdlist :: [Int] -> Int\ngcdlist (x : y : xs) = gcdlist ((gcd x y) : xs)\ngcdlist (x : []) = x\n\nmain = do\n\trawn <- getLine\n\trawinput <- getLine\n\tlet n = read rawn :: Int\n\tlet input = map read (words rawinput) :: [Int]\n\tputStr $ if (odd ((div (maximum input) (gcdlist input)) - n)) then \"Bob\" else \"Alice\"\n"}, {"source_code": "import Data.List\n\ngetdelts :: [Int] -> [Int]\ngetdelts a = [abs (x - y) | x <- a, y <- a]\n\n\nmain = do\n\tn <- getLine\n\tnumbers <- getLine\n\tputStr $ (if (odd (length $ group $ sort $ getdelts (map read (words numbers) :: [Int]))) then \"Bob\" else \"Alice\") \n"}, {"source_code": "import Data.List\n\ngetdelts :: [Int] -> [Int]\ngetdelts a = [abs (x - y) | x <- a, y <- a, x /= y]\n\nmain = do\n\tn <- getLine\n\tnumbers <- getLine\n\tputStr $ (if (odd (length $ group $ sort $ getdelts (map read (words numbers) :: [Int]))) then \"Alice\" else \"Bob\") \n"}], "src_uid": "3185ae6b4b681a10a21d02e67f08fd19"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.ST.Safe (STUArray)\nimport Data.Array (array, elems)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (getBounds, readArray, writeArray, newArray)\nimport Data.Bits\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Array.Unboxed (UArray)\nimport Prelude hiding (words, lines, getLine, getContents)\n\ntype Fenwick s = STUArray s Int Int\n\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n l <- snd <$> getBounds f\n\n let\n update' i\n | i <= l = do\n readArray f i >>= \\v -> writeArray f i (v+d)\n update' (i .|. (i+1))\n | otherwise = return ()\n\n update' i\n\nquery f i = do\n let\n query' (-1) s = return s\n query' i s = do\n v <- readArray f i\n query' ((i .&. (i+1)) - 1) (s + v)\n\n query' i 0\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n ss <- replicateM n ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n rs = listArray (1, n) $ sort $ map snd ss :: UArray Int Int\n ss' = sort $ zip ss [1..]\n\n lookup x = lookup' 1 n\n where\n lookup' l r\n | v == x = m\n | v < x = lookup' (m+1) r\n | otherwise = lookup' l m\n where\n m = (l+r) `div` 2\n v = rs ! m\n\n cs = runST $ do\n t <- fenwick n\n\n let\n count [] = return []\n count (((l, r), i):ss) = do\n let j = lookup r\n c <- query t (j-1)\n update t j 1\n cs <- count ss\n return ((i, c):cs)\n\n count $ reverse ss'\n\n putStr . unlines . map show . elems $ array (1, n) cs\n\n\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T Int Int Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n gen <- newStdGen\n\n let\n rs' = qsort gen $ zipWith (\\[l, r] i -> T l r i) rs [1..]\n\n count [] _ = []\n count ((T l r i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') Set.empty\n\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.ST.Safe (STUArray)\nimport Data.Array (array, elems)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (getBounds, readArray, writeArray, newArray)\nimport Data.Bits\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Array.Unboxed (UArray)\nimport Prelude hiding (words, lines, getLine, getContents)\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n l <- snd <$> getBounds f\n\n let\n update' i\n | i <= l = do\n readArray f i >>= \\v -> writeArray f i (v+d)\n update' (i .|. (i+1))\n | otherwise = return ()\n\n update' i\n\nquery f i = do\n let\n query' (-1) s = return s\n query' i s = do\n v <- readArray f i\n query' ((i .&. (i+1)) - 1) (s + v)\n\n query' i 0\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n ss <- replicateM n ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n rs = listArray (1, n) $ sort $ map snd ss :: UArray Int Int\n ss' = sort $ zip ss [1..]\n\n lookup x = lookup' 1 n\n where\n lookup' l r\n | v == x = m\n | v < x = lookup' (m+1) r\n | otherwise = lookup' l m\n where\n m = (l+r) `div` 2\n v = rs ! m\n\n cs = runST $ do\n t <- fenwick n\n\n let\n count [] = return []\n count (((l, r), i):ss) = do\n let j = lookup r\n c <- query t (j-1)\n update t j 1\n cs <- count ss\n return ((i, c):cs)\n\n count $ reverse ss'\n\n putStr . unlines . map show . elems $ array (1, n) cs\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T !Int !Int !Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n gen <- newStdGen\n\n let\n rs' = sort $ zipWith (\\[l, r] i -> T l r i) rs [1..]\n\n count [] _ = []\n count ((T l r i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') Set.empty\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T !Int !Int !Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n gen <- newStdGen\n\n let\n rs' = qsort gen $ zipWith (\\[l, r] i -> T l r i) rs [1..]\n\n count [] _ = []\n count ((T l r i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') (Set.empty)\n\n\n\n"}, {"source_code": "{-# tle 39 #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T !Int !Int !Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n gen <- newStdGen\n\n let\n rs' = qsort gen $ zipWith (\\[l, r] i -> T l r i) rs [1..]\n\n count [] _ = []\n count ((T l r i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') (Set.empty)\n\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.ST.Safe (STUArray)\nimport Data.Array (array, elems)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (getBounds, readArray, writeArray, newArray)\nimport Data.Bits\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Array.Unboxed (UArray)\nimport Prelude hiding (words, lines, getLine, getContents)\n\ntype Fenwick s = STUArray s Int Int\n\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n l <- snd <$> getBounds f\n\n mapM (\\i -> readArray f i >>= \\v -> writeArray f i (v+d)) $\n takeWhile (<= l) $ iterate (\\i -> i .|. (i+1)) i\n\nquery f i = sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate (\\i -> (i .&. (i+1))-1) i)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n ss <- replicateM n ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n rs = listArray (1, n) $ sort $ map snd ss :: UArray Int Int\n ss' = sort $ zip ss [1..]\n\n lookup x = lookup' 1 n\n where\n lookup' l r\n | v == x = m\n | v < x = lookup' (m+1) r\n | otherwise = lookup' l m\n where\n m = (l+r) `div` 2\n v = rs ! m\n\n cs = runST $ do\n t <- fenwick n\n\n let\n count [] = return []\n count (((l, r), i):ss) = do\n let j = lookup r\n c <- query t (j-1)\n update t j 1\n cs <- count ss\n return ((i, c):cs)\n\n count $ reverse ss'\n\n putStr . unlines . map show . elems $ array (1, n) cs\n\n\n\n"}, {"source_code": "{-# tle 39 #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T !Int !Int !Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n\n let\n rs' = sort $ zipWith (\\[l, r] i -> T l r i) rs [1..]\n\n count [] _ = []\n count ((T l r i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') (Set.empty)\n\n\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n rs <- replicateM n ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n rs' = sort $ zip rs [1..]\n\n count [] _ = []\n count (((l, r),i):rs) set = (c - 1):(count rs (r `Set.delete` set))\n where\n c = Set.size . fst $ (r+1) `Set.split` set\n\n\n putStr . unlines . map show . elems . array (1, n) $ zip [1..] (count rs' (Set.fromList $ map snd rs))\n\n\n\n"}, {"source_code": "{-# tle 39 #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sortBy)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\n\nmain = do\n [n] <- readInts\n rs <- replicateM n ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n rs' = sortBy (comparing (\\a -> - fst (fst a))) $ zip rs [1..]\n\n count [] _ = []\n count (((l, r),i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (reverse rs') (Set.empty)\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T Int Int Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n gen <- newStdGen\n\n let\n rs' = sort $ zipWith (\\[l, r] i -> (l, r, i)) rs [1..]\n\n count [] _ = []\n count ((l, r, i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') Set.empty\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (array, elems)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\nimport System.Random\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nqsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\ndata T = T Int Int Int\ninstance Ord T where (T a _ _) <= (T b _ _) = a >= b\ninstance Eq T where (T a _ _) == (T b _ _) = a == b\n\nmain = do\n [n] <- readInts\n rs <- replicateM n readInts\n gen <- newStdGen\n\n let\n rs' = qsort gen $ zipWith (\\[l, r] i -> (l, r, i)) rs [1..]\n\n count [] _ = []\n count ((l, r, i):rs) set = (i, c):(count rs (r `Set.insert` set))\n where\n c = Set.size . fst $ r `Set.split` set\n\n putStr . unlines . map show . elems . array (1, n) $ count (rs') Set.empty\n\n\n\n"}], "src_uid": "ba7d6cd00c49da90e7021bc4717af054"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (nub)\nimport Data.IntMap (assocs, fromListWith, map)\nimport qualified Data.IntMap as Map\nimport Data.Maybe (catMaybes)\nimport Prelude hiding (reads)\n\nreads :: Num a => IO [a]\nreads = liftM (Prelude.map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\nsolve :: [Int] -> [(Int, Int)]\nsolve as = catMaybes $ Prelude.map liftFromSnd $ assocs $ Map.map getStep intMap\n where\n intMap = fromListWith (++) $ zip as $ Prelude.map (\\x -> [x]) [1..]\n getStep [_] = Just 0\n getStep xs = case nub (zipWith (-) xs (tail xs)) of\n [d] -> Just d\n _ -> Nothing\n\nprintAns :: [(Int, Int)] -> IO ()\nprintAns ans = do\n print $ length ans\n mapM_ print' ans\n where\n print' (a, b) = putStrLn $ concat [show a, \" \", show b]\n\nliftFromSnd :: (a, Maybe b) -> Maybe (a, b)\nliftFromSnd (a, b) = b >>= return . (tuple a)\n where\n tuple a b = (a, b)\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n printAns $ solve as", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as M\nimport Data.List\nimport Data.Maybe\nimport Text.Printf\n\nmain = do\n n <- readLn\n l <- map (fromJust . fmap fst .B.readInt) . B.words <$> B.getLine\n let res = solve n l\n print (length res)\n forM_ res $ \\(x,d) -> printf \"%d %d\\n\" x d\n\nsolve :: Int -> [Int] -> [(Int,Int)]\nsolve n l = [ (x,d) | (x,(d,p)) <- M.assocs $ foldl' f M.empty l', d /= -1]\n where\n l' = zip l [1..]\n f m (x,i) | M.notMember x m = M.insert x (0,i) m\n | otherwise = \n case m M.! x of\n (-1,_) -> m\n (0,p) -> M.insert x (i-p,i) m\n (d,p) | d == i - p -> M.insert x (d,i) m\n | otherwise -> M.insert x (-1,i) m\n \n\n"}, {"source_code": "import Data.List\nimport Text.Printf\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\ntranslate n ([x]) = (n,0)\ntranslate n x = if x==take (length x) [x!!0,x!!1..] then (n, (x!!0 - x!!1)) else (n, -1)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve ls = [(key,d) | (key,d) <- map (\\(key, xs) -> (translate key xs)) $ M.assocs ls', d /= -1]\n where \n ls' = M.fromListWith (++) $ zip ls $ map (\\a -> [a]) [1..]\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst . B.readInt) . B.words <$> B.getLine\n let ans = solve xs\n print $ length ans\n mapM_ (\\(a,b)->printf \"%d %d\\n\" a b) ans\n"}, {"source_code": "import Data.List\nimport Text.Printf\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\npapa x = x == take (length x) [x!!0,x!!1..]\n\ntranslate n ([x]) = (n,0)\ntranslate n x = if papa x then (n, (x!!0 - x!!1)) else (n, -1)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve ls = [(key,d) | (key,d) <- map (\\(key, xs) -> (translate key xs)) $ M.assocs $ he, d /= -1]\n where \n he = M.fromListWith (++) $ zip ls $ map (\\a -> [a]) [1..]\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst .B.readInt) . B.words <$> B.getLine\n let ans = solve xs\n print $ length ans\n mapM_ (\\(a,b)->printf \"%d %d\\n\" a b) ans\n"}, {"source_code": "import Data.List\nimport Text.Printf\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\ntranslate n ([x]) = (n,0)\ntranslate n x = if x==take (length x) [x!!0,x!!1..] then (n, (x!!0 - x!!1)) else (n, -1)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve ls = filter (\\(key,d) -> d /= -1) $ map (\\(key, xs) -> (translate key xs)) $ M.assocs ls'\n where \n ls' = M.fromListWith (++) $ zip ls $ map (\\a -> [a]) [1..]\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst . B.readInt) . B.words <$> B.getLine\n let ans = solve xs\n print $ length ans\n mapM_ (\\(a,b)->printf \"%d %d\\n\" a b) ans\n"}, {"source_code": "import Data.List\nimport Text.Printf\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\npapa x = x == take (length x) [x!!0,x!!1..]\n\ntranslate n ([x]) = (n,0)\ntranslate n x = if papa x then (n, (x!!0 - x!!1)) else (n, -1)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve ls = [(key,d) | (key,d) <- map (\\(key, xs) -> (translate key xs)) $ M.assocs ls', d /= -1]\n where \n ls' = M.fromListWith (++) $ zip ls $ map (\\a -> [a]) [1..]\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst .B.readInt) . B.words <$> B.getLine\n let ans = solve xs\n print $ length ans\n mapM_ (\\(a,b)->printf \"%d %d\\n\" a b) ans\n"}, {"source_code": "import Data.List\nimport Text.Printf\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\npapa x = x == take (length x) [x!!0,x!!1..]\n\ntranslate n ([x]) = (n,0)\ntranslate n x = if papa x then (n, (x!!1 - x!!0)) else (n, 1)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve ls = ans\n where \n he= M.fromListWith (++) $ zip ls $ map (\\a -> [a]) [1..]\n ans = [(key,d) | (key,d) <- map (\\(key, xs) -> (translate key xs)) $ M.assocs $ he, d /= 1]\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst .B.readInt) . B.words <$> B.getLine\n --solve xs\n let ans = solve xs\n print $ length ans\n mapM_ (\\(a,b)->printf \"%d %d\\n\" a ((-1)*b)) ans\n"}, {"source_code": "import Data.Array\nimport Data.List\n\nsolve :: [Int] -> [(Int, Int)]\nsolve x = (unbox . assocs . countDiff) x\n where\n unbox [] = []\n unbox (x:xs) = \n (case x of\n (pos, (Just diff, Just last)) -> \n [(pos, diff)]\n _ -> []\n ) ++ unbox xs\n \n\ncountDiff :: [Int] -> Array Int (Maybe Int, Maybe Int)\ncountDiff list = \n accumArray updateDiff\n (Just 0, Nothing) \n (minimum list, maximum list)\n (getStartingValues list 0)\n where\n updateDiff (Just 0, Nothing) newVal = \n (Just 0, Just newVal)\n\n updateDiff (Just 0, Just lastVal) newVal =\n (Just (newVal - lastVal), Just newVal)\n\n updateDiff (diff, _lastVal) newVal = \n case _lastVal of\n Just lastVal -> \n if diff == Just (newVal - lastVal) then\n (diff, Just newVal)\n else\n (Nothing, Nothing)\n\n Nothing -> (Nothing, Nothing)\n\n getStartingValues [] _ = []\n getStartingValues (x:xs) pos = \n (x, pos) : (getStartingValues xs (pos + 1))\n \n\noutput :: [(Int, Int)] -> String\noutput list = (show $ length list) ++ \"\\n\" ++ (result list)\n where\n result = unlines . (map (\\(a, b) -> (show a) ++ \" \" ++ (show b))) . sort\n\nmain = interact $ output . solve . (map read) . tail . words\n\n"}, {"source_code": "import Data.Array\nimport Data.List\n\nsolve :: [Int] -> [(Int, Int)]\nsolve x = (unbox . assocs . countDiff) x\n where\n unbox [] = []\n unbox (x:xs) = \n (case x of\n (pos, (Just diff, Just last)) -> \n [(pos, diff)]\n _ -> []\n ) ++ unbox xs\n \n\ncountDiff :: [Int] -> Array Int (Maybe Int, Maybe Int)\ncountDiff list = \n accumArray updateDiff\n (Just 0, Nothing) \n (minimum list, maximum list)\n (reverse $ getStartingValues list 0 [])\n where\n updateDiff (Just 0, Nothing) newVal = \n (Just 0, Just newVal)\n\n updateDiff (Just 0, Just lastVal) newVal =\n (Just (newVal - lastVal), Just newVal)\n\n updateDiff (diff, _lastVal) newVal = \n case _lastVal of\n Just lastVal -> \n if diff == Just (newVal - lastVal) then\n (diff, Just newVal)\n else\n (Nothing, Nothing)\n\n Nothing -> (Nothing, Nothing)\n\n getStartingValues [] _ acc = acc\n getStartingValues (x:xs) pos acc = \n getStartingValues xs (pos + 1) ((x, pos) : acc)\n \n\noutput :: [(Int, Int)] -> String\noutput list = (show $ length list) ++ \"\\n\" ++ (result list)\n where\n result = unlines . (map (\\(a, b) -> (show a) ++ \" \" ++ (show b))) . sort\n\nmain = interact $ output . solve . (map read) . tail . words"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Data.List\nimport Data.Maybe\nimport Text.Printf\n\nmain = do\n n <- readLn\n l <- map (fromJust . fmap fst .B.readInt) . B.words <$> B.getLine\n let res = solve n l\n print (length res)\n forM_ res $ \\(x,d) -> printf \"%d %d\\n\" x d\n\nsolve :: Int -> [Int] -> [(Int,Int)]\nsolve n l = [ (x,d) | (x,(d,p)) <- M.assocs $ foldl' f M.empty l', d /= -1]\n where\n l' = zip l [1..]\n f m (x,i) | M.notMember x m = M.insert x (0,i) m\n | otherwise = \n case m M.! x of\n (-1,_) -> m\n (0,p) -> M.insert x (i-p,i) m\n (d,p) | d == i - p -> M.insert x (d,i) m\n | otherwise -> M.insert x (-1,i) m\n \n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Text.Printf\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\npapa x = x == take (length x) [x!!0,x!!1..]\n\ntranslate n ([x]) = (n,0)\ntranslate n x = if papa x then (n, (x!!1 - x!!0)) else (n, -1)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve ls = ans\n where \n he= M.fromListWith (++) $ zip ls $ map (\\a -> [a]) [1..]\n ans = [(key,d) | (key,d) <- map (\\(key, xs) -> (translate key xs)) $ M.assocs $ he, d /= -1]\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst .B.readInt) . B.words <$> B.getLine\n --solve xs\n let ans = solve xs\n print $ length ans\n mapM_ (\\(a,b)->printf \"%d %d\\n\" a ((-1)*b)) ans\n"}, {"source_code": "import Data.Array\nimport Data.List\n\nsolve :: [Int] -> [(Int, Int)]\nsolve x = (unbox . assocs . countDiff) x\n where\n unbox [] = []\n unbox (x:xs) = \n (case x of\n (pos, (Just diff, Just last)) -> \n [(pos, diff)]\n _ -> []\n ) ++ unbox xs\n \n\ncountDiff :: [Int] -> Array Int (Maybe Int, Maybe Int)\ncountDiff list = \n accumArray updateDiff\n (Just 0, Nothing) \n (minimum list, maximum list)\n (getStartingValues list 0 [])\n where\n updateDiff (Just 0, Nothing) newVal = \n (Just 0, Just newVal)\n\n updateDiff (Just 0, Just lastVal) newVal =\n (Just (newVal - lastVal), Just newVal)\n\n updateDiff (diff, _lastVal) newVal = \n case _lastVal of\n Just lastVal -> \n if diff == Just (newVal - lastVal) then\n (diff, Just newVal)\n else\n (Nothing, Nothing)\n\n Nothing -> (Nothing, Nothing)\n\n getStartingValues [] _ acc = acc\n getStartingValues (x:xs) pos acc = \n getStartingValues xs (pos + 1) ((x, pos) : acc)\n \n\noutput :: [(Int, Int)] -> String\noutput list = (show $ length list) ++ \"\\n\" ++ (result list)\n where\n result = unlines . (map (\\(a, b) -> (show a) ++ \" \" ++ (show b))) . sort\n\nmain = interact $ output . solve . (map read) . tail . words"}, {"source_code": "import Data.Array\nimport Data.List\n\nsolve :: [Int] -> [(Int, Int)]\nsolve x = (unbox . assocs . countDiff) x\n where\n unbox [] = []\n unbox (x:xs) = \n (case x of\n (pos, (Just diff, Just last)) -> \n [(pos, diff)]\n _ -> []\n ) ++ unbox xs\n \n\ncountDiff :: [Int] -> Array Int (Maybe Int, Maybe Int)\ncountDiff list = \n accumArray updateDiff\n (Just 0, Nothing) \n (minimum list, maximum list)\n (getStartingValues list 0)\n where\n updateDiff (Just 0, Nothing) newVal = \n (Just 0, Just newVal)\n\n updateDiff (Just 0, Just lastVal) newVal =\n (Just (newVal - lastVal), Just newVal)\n\n updateDiff (diff, _lastVal) newVal = \n case _lastVal of\n Just lastVal -> \n if diff == Just (newVal - lastVal) then\n (diff, Just newVal)\n else\n (Nothing, Nothing)\n\n Nothing -> (Nothing, Nothing)\n\n getStartingValues [] _ = []\n getStartingValues (x:xs) pos = \n (x, pos) : (getStartingValues xs (pos + 1))\n \n\noutput :: [(Int, Int)] -> String\noutput = \n unlines . (map (\\(a, b) -> (show a) ++ \" \" ++ (show b))) . sort\n\nmain = interact $ output . solve . (map read) . tail . words\n\n"}], "src_uid": "097e35b5e9c96259c54887158ebff544"} {"source_code": "{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-}\n \nimport Text.Printf\nimport System.IO\nimport Data.List\nimport Data.Functor\nimport Data.Bifunctor (bimap)\nimport Data.Function\nimport Data.Maybe\nimport Data.Int\nimport Data.Bits\nimport Data.Tree\nimport Data.Array.Unboxed\nimport Data.Array.IArray\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nbitSplit :: Int\nbitSplit = 7\n\ngenerateQuery :: Int -> [Int]\ngenerateQuery 1 = take 100 [0..]\ngenerateQuery 2 = take 100 $ map (* (2 ^ bitSplit)) [1..]\n\nperformQuery :: [Int] -> IO Int\nperformQuery elements = do\n putStrLn $ \"? \" ++ intercalate \" \" (map show elements)\n hFlush stdout\n answer <- readB8Int <$> B8.getLine\n return answer\n\nsubmitAnswer :: Int -> IO ()\nsubmitAnswer answer = do\n printf \"! %d\\n\" answer\n hFlush stdout\n\nmain :: IO ()\nmain = do\n firstAnswer <- performQuery $ generateQuery 1\n secondAnswer <- performQuery $ generateQuery 2\n let queryMask = 2 ^ bitSplit - 1\n let answer = (firstAnswer .&. complement queryMask) .|. (secondAnswer .&. queryMask)\n submitAnswer answer\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Bits\nimport System.IO\n\nmain = do\n hSetBuffering stdout LineBuffering\n let q0 = [1..100] :: [Int]\n putStrLn $ unwords $ \"?\" : map show q0\n hFlush stdout\n r0 <- readLn\n let q1 = map (*128) q0\n putStrLn $ unwords $ \"?\" : map show q1\n hFlush stdout\n r1 <- readLn\n let a = r0 `xor` r1\n a0 = a .&. 127\n r = r0 `xor` a0 :: Int\n putStrLn $ \"! \" ++ show r\n hFlush stdout\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-}\n \nimport Text.Printf\nimport System.IO\nimport Data.List\nimport Data.Functor\nimport Data.Bifunctor (bimap)\nimport Data.Function\nimport Data.Maybe\nimport Data.Int\nimport Data.Bits\nimport Data.Tree\nimport Data.Array.Unboxed\nimport Data.Array.IArray\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nbitSplit :: Int\nbitSplit = 8\n\ngenerateQuery :: Int -> [Int]\ngenerateQuery 1 = take 100 [0..]\ngenerateQuery 2 = take 100 $ map (* (2 ^ bitSplit)) [1..]\n\nperformQuery :: [Int] -> IO Int\nperformQuery elements = do\n putStrLn $ \"? \" ++ intercalate \" \" (map show elements)\n hFlush stdout\n answer <- readB8Int <$> B8.getLine\n return answer\n\nsubmitAnswer :: Int -> IO ()\nsubmitAnswer answer = do\n printf \"! %d\\n\" answer\n hFlush stdout\n\nmain :: IO ()\nmain = do\n firstAnswer <- performQuery $ generateQuery 1\n secondAnswer <- performQuery $ generateQuery 2\n let queryMask = 2 ^ bitSplit - 1\n let answer = (firstAnswer .&. complement queryMask) .|. (secondAnswer .&. queryMask)\n submitAnswer answer\n"}, {"source_code": "import Data.List\nimport Data.Bits\nimport System.IO\n\nmain = do\n hSetBuffering stdout LineBuffering\n let q0 = [0..99] :: [Int]\n putStrLn $ unwords $ \"?\" : map show q0\n r0 <- readLn\n let q1 = [128..227] :: [Int]\n putStrLn $ unwords $ \"?\" : map show q1\n r1 <- readLn\n let a = r0 `xor` r1\n a0 = a .&. 127\n r = r0 `xor` a0 :: Int\n putStrLn $ \"! \" ++ show r\n"}, {"source_code": "import Data.List\nimport Data.Bits\nimport System.IO\n\nmain = do\n hSetBuffering stdout LineBuffering\n let q0 = [0..99] :: [Int]\n putStrLn $ unwords $ \"?\" : map show q0\n hFlush stdout\n r0 <- readLn\n let q1 = map (*128) q0\n putStrLn $ unwords $ \"?\" : map show q1\n hFlush stdout\n r1 <- readLn\n let a = r0 `xor` r1\n a0 = a .&. 127\n r = r0 `xor` a0 :: Int\n putStrLn $ \"! \" ++ show r\n hFlush stdout\n"}, {"source_code": "import Data.List\nimport Data.Bits\nimport System.IO\n\nmain = do\n hSetBuffering stdout LineBuffering\n let q0 = [0..99] :: [Int]\n putStrLn $ unwords $ \"?\" : map show q0\n r0 <- readLn\n let q1 = map (*128) q0\n putStrLn $ unwords $ \"?\" : map show q1\n r1 <- readLn\n let a = r0 `xor` r1\n a0 = a .&. 127\n r = r0 `xor` a0 :: Int\n putStrLn $ \"! \" ++ show r\n"}], "src_uid": "c7f31e0c57cf15f71c401d826c3ee0ef"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nbSearch :: (Int -> Bool) -> Int -> Int -> Int\nbSearch p !low !high\n | high<=low = low\n | p mid = bSearch p mid high\n | otherwise = bSearch p low (mid-1)\n where\n mid = quot (low+high+1) 2\n\nmain = B.getContents >>= print.solve.map readInt.B.words\n\nsolve :: [Int] -> Integer\nsolve (n:d:rest) = sum $ map step [0..n-3]\n where\n arr = listArray (0,n-1) rest :: UArray Int Int\n step i = (toInteger $ j-i)*(toInteger $ j-i-1)`div`2\n where\n !aid = unsafeAt arr i + d\n j = bSearch ((<=aid).unsafeAt arr) i (n-1)\n", "positive_code": [{"source_code": "import Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\n\nsolve :: Int -> Int -> [Int] -> Integer\nsolve n d xs = solve' (1,1)\n where\n a = listArray (1, n) xs\n solve' (i, j)\n | j == n = f (j - i)\n | otherwise = f (j - i) + solve'' (i, j + 1)\n solve'' (i, j)\n | a ! j - a ! i > d = solve'' (i + 1, j)\n | otherwise = solve' (i, j)\n f :: Int -> Integer\n f n = (n' * (n' - 1)) `div` 2\n where\n n' = fromIntegral n\n\nmain :: IO ()\nmain = do\n [n, d] <- reads\n xs <- reads\n print $ solve n d xs"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve :: [Integer] -> Integer\nsolve (n : d : xs) = f ys ys\n where ys = zip xs [1..]\n \n f [] _ = 0\n f ((x, px) : xs) [(y, py)]\n | y - x <= d = choose (py - px) + f xs [(y, py)]\n | otherwise = f xs [(y, py)]\n f ((x, px) : xs) ((y, py) : (z, pz) : ys)\n | z - x > d = f xs ((y , py) : (z, pz) : ys) + \n if y - x <= d then choose (py - px)\n else 0\n | otherwise = f ((x, px) : xs) ((z, pz) : ys)\n\n choose n\n | n < 2 = 0\n | otherwise = div (n * (n - 1)) 2\n \n"}], "negative_code": [{"source_code": "main = interact $ show . solve . map read . words\nsolve :: [Int] -> Int\nsolve (n : d : xs) = f ys ys\n where ys = zip xs [1..]\n \n f [] _ = 0\n f ((x, px) : xs) [(y, py)]\n | y - x <= d = choose (py - px) + f xs [(y, py)]\n | otherwise = f xs [(y, py)]\n f ((x, px) : xs) ((y, py) : (z, pz) : ys)\n | z - x > d = f xs ((y , py) : (z, pz) : ys) + \n if y - x <= d then choose (py - px)\n else 0\n | otherwise = f ((x, px) : xs) ((z, pz) : ys)\n\n choose n\n | n < 2 = 0\n | otherwise = div (n * (n - 1)) 2\n \n"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve :: [Int] -> Int\nsolve (n : d : xs) = f ys ys\n where ys = zip xs [1..]\n \n f [] _ = 0\n f ((x, px) : xs) [(y, py)]\n | y - x <= d = choose (py - px) + f xs [(y, py)]\n | otherwise = f xs [(y, py)]\n f ((x, px) : xs) ((y, py) : (z, pz) : ys)\n | z - x > d = f xs ((z, pz) : ys) + \n if y - x <= d then choose (py - px)\n else 0\n | otherwise = f ((x, px) : xs) ((z, pz) : ys)\n\n choose n\n | n < 2 = 0\n | otherwise = div (n * (n - 1)) 2\n \n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n d xs = solve' (1,1)\n where\n a = listArray (1, n) xs\n solve' (i,j)\n | i == n = 0\n | j == n && a ! j - a ! i <= d = f (j - i + 1)\n | j == n = solve' (i + 1, j)\n | a ! j - a ! i <= d && a ! (j + 1) - a ! i <= d = solve' (i, j+1)\n | a ! j - a ! i <= d = f (j - i + 1) + solve' (i + 1, j + 1)\n | otherwise = solve' (i + 1, j)\n f n\n | n < 3 = 0\n | otherwise = div (n' * (n' - 1) * (n' - 2)) 6\n where\n n' = fromIntegral n\n\nmain :: IO ()\nmain = do\n [n, d] <- reads\n xs <- reads\n print $ solve n d xs"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n d xs = solve' (1,1)\n where\n a = listArray (1, n) xs\n solve' (i,j)\n | i == n = 0\n | j == n && a ! j - a ! i <= d = f (j - i + 1)\n | j == n = solve' (i + 1, j)\n | a ! j - a ! i <= d && a ! (j + 1) - a ! i <= d = solve' (i, j+1)\n | a ! j - a ! i <= d = f (j - i + 1) + solve' (i, j + 1)\n | otherwise = solve' (i + 1, j)\n f n\n | n < 3 = 0\n | otherwise = div (n' * (n' - 1) * (n' - 2)) 6\n where\n n' = fromIntegral n\n\nmain :: IO ()\nmain = do\n [n, d] <- reads\n xs <- reads\n print $ solve n d xs"}], "src_uid": "1f6491999bec55cb8d960181e830f4c8"} {"source_code": "import List\nmain = interact solve\nsolve input = output where\n inputs = lines input\n [n,m] = map (read::String->Int) $ words $ head inputs\n scs = [(read y::Int,x)|[x,y] <- map words $ tail inputs]\n output = show $ answer scs\nanswer :: [(Int,String)] -> Int\nanswer xs = if c<0 then answer (cas '0' xs) + answer (cas '1' xs) else c\n where c = check xs\ncas _ [] = []\ncas x ((y,z):xs) = (if head z == x then y-1 else y,tail z):(cas x xs)\ncheck xs\n | x<0 || z>length y = 0\n | null y = 1\n | otherwise = -1\n where sxs = sort xs\n (x,y) = head sxs\n (z,_) = last sxs", "positive_code": [{"source_code": "import Data.List\n\nmain = interact $ show . solve.parse.lines\n\nparse = map (\\str -> (head (words str), read (last (words str)))) . tail\n\nsolve :: [(String, Int)] -> Int\nsolve xs@((\"\", _):_) | all ((==0).snd) xs = 1\n | otherwise = 0\nsolve xs | any ((<0).snd) xs = 0\n | otherwise = f '0' + f '1'\n where match a b | a == b = 1\n match _ _ = 0\n f c = solve (map (\\(s, n) -> (tail s, n - match (head s) c)) xs)\n"}], "negative_code": [], "src_uid": "5215112549723fea3f2c1fe0049e0b2e"} {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = interact f\n\nf ss = case result of\n Nothing -> \"NO\"\n Just (t,x) -> (++) \"YES\\n\" $ unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)\n where\n ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss\n ls = sortBy (\\[_,i,_] [_,j,_] -> compare j i) $ zipWith (:) [1..] l\n result = g 0 max max [] max reg ls\n\ng time hp prevHP hist maxHP reg ls\n | hp <= 0 = Just (time, reverse hist)\n | otherwise = \n if (not canAttack && hp >= prevHP)\n then Nothing\n else g (time+1) newHP hp newHist maxHP reg newList\n where\n (possible, unpossible) = break (\\[i,pow,dmg] -> pow*maxHP < hp*100) ls\n canAttack = possible /= []\n use = maximumBy (\\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible\n (newL, newR) = break (== use) possible\n (newList,newHist) = if canAttack \n then (newL++(tail newR)++unpossible, ((time:use):hist))\n else (ls, hist)\n damage = sum $ map (head . drop 3) newHist\n newHP = min maxHP $ hp - damage + reg", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Function\n\nri :: IO [Int]\nri = (map read . words) `fmap` getLine\n\nsndTpl (a,b,c) = b\n\ngo max hp dhp l ans sec\n\t| hp <= 0 = (sec, reverse ans)\n\t| otherwise = if null l' then last else go max (up $ dhp-d) (dhp-d) l'' ((sec,i):ans) (sec+1)\n\t\twhere\n\t\t\tl' = [(p,d,i) | (p,d,i) <- l, hp*100 <= p * max]\n\t\t\tel@(p,d,i) = maximumBy (compare `on` sndTpl) l'\n\t\t\tl'' = delete el l\n\t\t\tlast\n\t\t\t\t| dhp < 0 = go max (up dhp) dhp l ans (sec+1)\n\t\t\t\t| otherwise = (-1,[])\n\t\t\tup dx = min (hp+dx) max\n\nsolve n max reg pd = go max max reg pd' [] 0\n\twhere\n\t\tpd' = [(p,d,i) | ([p,d],i) <- zip pd [1..n]]\n\npprint (sec,l) = yn ++ lprint\n\twhere\n\t\tyn = if null l then [\"NO\"] else [\"YES\", show sec ++ \" \" ++ show (length l)]\n\t\tlprint = [show s ++ \" \" ++ show i | (s,i) <- l]\n\nmain = do\n\t[n,max,reg] <- ri\n\tpd <- forM [1..n] (\\_ -> ri)\n\tlet ans = solve n max reg pd\n\tputStrLn $ intercalate \"\\n\" (pprint ans)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nmain = interact f\n\nf ss = case result of\n Nothing -> \"NO\"\n Just (t,x) -> (++) \"YES\\n\" $ unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)\n where\n ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss\n ls = sortBy (\\[_,i,_] [_,j,_] -> compare i j) $ zipWith (:) [1..] l\n result = g 0 max max [] max reg ls\n\ng time hp prevHP hist maxHP reg ls\n | hp <= 0 = Just (time, reverse hist)\n | otherwise = \n if (not canAttack && hp >= prevHP)\n then Nothing\n else g (time+1) newHP hp newHist maxHP reg newList\n where\n (possible, unpossible) = break (\\[i,pow,dmg] -> pow*maxHP < hp*100) ls\n canAttack = possible /= []\n use = maximumBy (\\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible\n (newL, newR) = break (== use) possible\n (newList,newHist) = if canAttack \n then (newL++(tail newR)++unpossible, ((time:use):hist))\n else (ls, hist)\n damage = sum $ map (head . drop 3) newHist\n newHP = min maxHP $ hp - damage + reg"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = interact f\n\nf ss = case result of\n Nothing -> \"NO\"\n Just (t,x) -> unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)\n where\n ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss\n ls = sortBy (\\[i,_,_] [j,_,_] -> compare i j) $ zipWith (:) [1..] l\n result = g 0 max max [] max reg ls\n\ng time hp prevHP hist maxHP reg ls\n | hp <= 0 = Just (time, reverse hist)\n | otherwise = \n if (not canAttack && hp >= prevHP)\n then Nothing\n else g (time+1) newHP hp newHist maxHP reg newList\n where\n (possible, unpossible) = break (\\[i,pow,dmg] -> pow*maxHP < hp*100) ls\n canAttack = possible /= []\n use = maximumBy (\\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible\n (newL, newR) = break (== use) possible\n (newList,newHist) = if canAttack \n then (newL++(tail newR)++unpossible, ((time:use):hist))\n else (ls, hist)\n damage = sum $ map (head . drop 3) newHist\n newHP = min maxHP $ hp - damage + reg"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = interact f\n\nf ss = case result of\n Nothing -> \"NO\"\n Just (t,x) -> unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)\n where\n ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss\n ls = sortBy (\\[i,_,_] [j,_,_] -> compare i j) $ zipWith (:) [1..] l\n result = g 0 max max [] max reg ls\n\ng time hp prevHP hist maxHP reg ls\n | hp <= 0 = Just (time, reverse hist)\n | otherwise = \n if (not canAttack && hp >= prevHP)\n then Nothing\n else g (time+1) newHP hp newHist maxHP reg newList\n where\n (possible, unpossible) = break (\\[i,pow,dmg] -> pow < hp) ls\n canAttack = possible /= []\n use = maximumBy (\\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible\n (newL, newR) = break (== use) possible\n (newList,newHist) = if canAttack \n then (newL++(tail newR)++unpossible, ((time:use):hist))\n else (ls, hist)\n damage = sum $ map (head . drop 3) newHist\n newHP = min maxHP $ hp - damage + reg"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = interact f\n\nf ss = case result of\n Nothing -> \"NO\"\n Just (t,x) -> (++) \"YES\\n\" $ unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)\n where\n ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss\n ls = sortBy (\\[i,_,_] [j,_,_] -> compare i j) $ zipWith (:) [1..] l\n result = g 0 max max [] max reg ls\n\ng time hp prevHP hist maxHP reg ls\n | hp <= 0 = Just (time, reverse hist)\n | otherwise = \n if (not canAttack && hp >= prevHP)\n then Nothing\n else g (time+1) newHP hp newHist maxHP reg newList\n where\n (possible, unpossible) = break (\\[i,pow,dmg] -> pow*maxHP < hp*100) ls\n canAttack = possible /= []\n use = maximumBy (\\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible\n (newL, newR) = break (== use) possible\n (newList,newHist) = if canAttack \n then (newL++(tail newR)++unpossible, ((time:use):hist))\n else (ls, hist)\n damage = sum $ map (head . drop 3) newHist\n newHP = min maxHP $ hp - damage + reg"}, {"source_code": "import Control.Monad\nimport Data.List\n\nri :: IO [Int]\nri = (map read . words) `fmap` getLine\n\ngo max hp dhp l@((p,d,i):ls) ans sec\n\t| hp <= 0 = (sec, reverse ans)\n\t| hp * 100 <= p * max = go max (up $ dhp-d) (dhp-d) ls ((sec,i):ans) (sec+1)\n\t| dhp < 0 = go max (up dhp) dhp l ans (sec+1)\n\t| otherwise = (-1,[])\n\twhere\n\t\tup dx = min (hp+dx) max\n\nsolve n max reg pd = go max max reg pd' [] 0\n\twhere\n\t\tpd' = reverse $ (0,0,0) : (sort $ [(p,d,i) | ([p,d],i) <- zip pd [1..n]])\n\npprint (sec,l) = yn ++ lprint\n\twhere\n\t\tyn = if null l then [\"NO\"] else [\"YES\", show sec ++ \" \" ++ show (length l)]\n\t\tlprint = [show s ++ \" \" ++ show i | (s,i) <- l]\n\nmain = do\n\t[n,max,reg] <- ri\n\tpd <- forM [1..n] (\\_ -> ri)\n\tlet ans = solve n max reg pd\n\tputStrLn $ intercalate \"\\n\" (pprint ans)\n"}], "src_uid": "e9c486e2d942700e0644dff29b6e3be6"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport System.IO\n\nmain = do\n s <- getLine\n when (s == \"start\") play\n\nplay = do\n lower <- findLower 1\n v <- search (lower `div` 2) lower\n if v == 1\n then do\n response <- query (0, 1)\n if response == \"x\" then answer 1 else answer 2\n else do\n response <- query (1, 2 * v - 1)\n if response == \"x\" then answer $ 2 * v - 1 else answer $ 2 * v\n main\n\nfindLower v = do\n response <- query (v, 2 * v)\n if response == \"x\" then return v else findLower (2 * v)\n\nsearch l r = do\n if l == r - 1\n then return r\n else do\n let m = (l + r) `div` 2\n response <- query (m, 2 * m)\n if response == \"x\" then search l m else search m r\n\nquery (x, y) = do\n putStrLn $ \"? \" ++ show x ++ \" \" ++ show y\n hFlush stdout\n getLine\n\nanswer v = do\n putStrLn $ \"! \" ++ show v\n hFlush stdout\n", "positive_code": [{"source_code": "-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\n\nmain :: IO ()\nmain = do\n comm <- getLine\n case comm of\n \"start\" -> do res <- doQueries\n putStrLn $ \"! \" ++ show res\n hFlush stdout\n main\n \"mistake\" -> exitFailure\n \"end\" -> exitSuccess\n \ndoQueries :: IO Int\ndoQueries = do\n is0 <- checkLt 0 1\n if not is0\n then\n return 1\n else do\n (l,u) <- searchMag 1 2\n binSearch l u\n where\n searchMag !l !u | u >= 10^9 = return (l,u)\n | otherwise = do\n ans <- checkLt l u\n if ans\n then searchMag u (u `shiftL` 1)\n else return (l,u)\n binSearch lt geq\n | geq - lt <= 1 = return geq\n | otherwise = do ans <- checkLt lt mid\n if ans then binSearch mid geq else binSearch lt mid\n where\n mid = (lt + geq) `shiftR` 1\n \ncheckLt :: Int -> Int -> IO Bool\ncheckLt x y = do\n putStrLn $ (\"? \" ++) $ shows x $ ' ' : show y\n hFlush stdout\n waitAns\n where waitAns = do ans:_ <- getLine\n case ans of\n 'y' -> return True\n 'x' -> return False\n 'e' -> exitFailure\n _ -> waitAns\n \n"}, {"source_code": "-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\n\nmain :: IO ()\nmain = do\n comm <- getLine\n case comm of\n \"start\" -> do res <- doQueries\n putStrLn $ \"! \" ++ show res\n hFlush stdout\n main\n \"mistake\" -> exitFailure\n \"end\" -> exitSuccess\n \ndoQueries :: IO Int\ndoQueries = do\n is0 <- checkLt 0 1\n if not is0\n then\n return 1\n else do\n (l,u) <- searchMag 1 3\n binSearch l u\n where\n searchMag !l !u | u >= 10^9 = return (l,u)\n | otherwise = do\n ans <- checkLt l u\n if ans\n then searchMag u (u `shiftL` 1 + 1)\n else return (l,u)\n binSearch lt geq\n | geq - lt <= 1 = return geq\n | otherwise = do ans <- checkLt lt mid\n if ans then binSearch mid geq else binSearch lt mid\n where\n mid = fromIntegral $\n (fromIntegral lt + fromIntegral geq :: Word) `shiftR` 1\n \ncheckLt :: Int -> Int -> IO Bool\ncheckLt x y = do\n putStrLn $ (\"? \" ++) $ shows x $ ' ' : show y\n hFlush stdout\n waitAns\n where waitAns = do ans:_ <- getLine\n case ans of\n 'y' -> return True\n 'x' -> return False\n 'e' -> exitFailure\n _ -> waitAns\n \n"}, {"source_code": "-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\n\nmain :: IO ()\nmain = do\n comm <- getLine\n case comm of\n \"start\" -> do res <- doQueries\n putStrLn $ \"! \" ++ show res\n hFlush stdout\n main\n \"mistake\" -> exitFailure\n \"end\" -> exitSuccess\n \ndoQueries :: IO Int\ndoQueries = do\n is0 <- checkLt 0 1\n if not is0\n then\n return 1\n else do\n (l,u) <- searchMag 1 2\n binSearch l u\n where\n db = (`shiftL` 1)\n searchMag !l !u | u >= 10^9 = return (l,u)\n | otherwise = do\n ans <- checkLt l u\n if ans then searchMag (db l) (db u) else return (l,u)\n binSearch lt geq\n | geq - lt <= 1 = return geq\n | otherwise = do ans <- checkLt lt mid\n if ans then binSearch mid geq else binSearch lt mid\n where\n mid = (lt + geq) `shiftR` 1\n \ncheckLt :: Int -> Int -> IO Bool\ncheckLt x y = do\n putStrLn $ (\"? \" ++) $ shows x $ ' ' : show y\n hFlush stdout\n waitAns\n where waitAns = do ans:_ <- getLine\n case ans of\n 'y' -> return True\n 'x' -> return False\n 'e' -> exitFailure\n _ -> waitAns\n \n"}], "negative_code": [{"source_code": "-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\n\nmain :: IO ()\nmain = do\n comm <- getLine\n case comm of\n \"start\" -> do res <- doQueries\n putStrLn $ \"! \" ++ show res\n hFlush stdout\n main\n \"mistake\" -> exitFailure\n \"end\" -> exitSuccess\n \ndoQueries :: IO Int\ndoQueries = do\n is0 <- checkLt 0 1\n if not is0\n then\n return 1\n else do\n (l,u) <- searchMag 1 2\n binSearch l u\n where\n searchMag !l !u | u >= 10^9 = return (l,u)\n | otherwise = do\n ans <- checkLt l u\n if ans\n then searchMag u (u `shiftL` 1 + 1)\n else return (l,u)\n binSearch lt geq\n | geq - lt <= 1 = return geq\n | otherwise = do ans <- checkLt lt mid\n if ans then binSearch mid geq else binSearch lt mid\n where\n mid = (lt + geq) `shiftR` 1\n \ncheckLt :: Int -> Int -> IO Bool\ncheckLt x y = do\n putStrLn $ (\"? \" ++) $ shows x $ ' ' : show y\n hFlush stdout\n waitAns\n where waitAns = do ans:_ <- getLine\n case ans of\n 'y' -> return True\n 'x' -> return False\n 'e' -> exitFailure\n _ -> waitAns\n \n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport System.IO\n\nmain = do\n s <- getLine\n when (s == \"start\") play\n\nplay = do\n lower <- findLower 1\n v <- search (lower `div` 2) lower\n if v == 1\n then do\n response <- query (1, 0)\n if response == \"x\" then answer 1 else answer 2\n else do\n response <- query (1, 2 * v - 1)\n if response == \"x\" then answer $ 2 * v - 1 else answer $ 2 * v\n main\n\nfindLower v = do\n response <- query (v, 2 * v)\n if response == \"x\" then return v else findLower (2 * v)\n\nsearch l r = do\n if l == r - 1\n then return r\n else do\n let m = (l + r) `div` 2\n response <- query (m, 2 * m)\n if response == \"x\" then search l m else search m r\n\nquery (x, y) = do\n putStrLn $ \"? \" ++ show x ++ \" \" ++ show y\n hFlush stdout\n getLine\n\nanswer v = do\n putStrLn $ \"! \" ++ show v\n hFlush stdout\n"}], "src_uid": "eab8e5ac203d9f10c893ea35d249fe84"} {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Char\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.Base (unsafeWrite,unsafeRead,unsafeAt)\nimport Data.Bits((.|.),xor)\nimport Monad\n\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = (\\(x:y:_) -> (scan' x,scan' y)) (words x)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\nscanlist :: (Scan a) => IO [a]\nscanlist = getLine>>=return.(map scan').words\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists n = if n==0 then return [] else scanlist>>=(\\x->scanlists (n-1)>>=return.(x:))\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn = putStrLn.showans\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns = mapM_ putAnsLn\n\nsieve :: Int -> UArray Int Bool\nsieve n = runSTUArray $ do\n t <- newArray (0,n) True\n unsafeWrite t 1 False\n let sqn = (floor.sqrt.fromIntegral) (n::Int)\n mapM_ (\\i -> unsafeRead t i >>= (flip when) (mapM_ (\\j -> (unsafeWrite t j False)) [i*i,i*(i+2)..n])) [3,5..sqn]\n return t\n\nsolve l r = rec beg 0\n where\n sve = sieve r\n beg = case mod l 4 of\n 0 -> l+1\n 1 -> l\n 2 -> l+3\n 3 -> l+2\n rec i n |i>r = n + (if l<=2&&r>=2 then 1 else 0)\n |unsafeAt sve i = rec (i+4) (n+1)\n |otherwise = rec (i+4) n\n\nmain = do (l,r) <- scan :: IO (Int,Int)\n print (solve l r)", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.Base (unsafeRead,unsafeWrite,unsafeAt)\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\n\nmain = do\n [l,r] <- map read.words <$> getLine\n print $ solve l r\n\nsolve :: Int -> Int -> Int\nsolve l r = go (fromEnum $ l<=2 && 2<=r) $ (l+2)`div`4\n where\n !isPrime = sieve r\n !end = (r-1)`div`4\n go !ans !x\n | end < x = ans\n | unsafeAt isPrime x = go (ans+1) (x+1)\n | otherwise = go ans (x+1)\n\nsieve :: Int -> UArray Int Bool\nsieve num = runSTUArray $ do\n isSmallPrime <- newArray (0,isqrt num`div`2) True :: ST s (STUArray s Int Bool)\n isLargePrime <- newArray (0,num`div`4) True\n unsafeWrite isSmallPrime 0 False\n unsafeWrite isLargePrime 0 False\n let !sqrtNum2 = isqrt num`div`2\n !num4 = num`div`4\n forM_ [1..sqrtNum2] $ \\i-> do\n isPrime <- unsafeRead isSmallPrime i\n when isPrime $ do\n let !p = i`shiftL`1 + 1\n !pp = i*(p+1)\n !ii = i*(i+1)\n forM_ [pp,pp+p..sqrtNum2] $ \\j-> do\n unsafeWrite isSmallPrime j False\n forM_ [ii,ii+p..num4] $ \\j-> do\n unsafeWrite isLargePrime j False\n return isLargePrime\n\nisqrt :: Int -> Int\nisqrt x = floor.(1e-8+).sqrt $ fromIntegral x\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Char\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.Base (unsafeWrite,unsafeRead,unsafeAt)\nimport Data.Bits((.|.),xor)\nimport Monad\n\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = (\\(x:y:_) -> (scan' x,scan' y)) (words x)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\nscanlist :: (Scan a) => IO [a]\nscanlist = getLine>>=return.(map scan').words\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists n = if n==0 then return [] else scanlist>>=(\\x->scanlists (n-1)>>=return.(x:))\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn = putStrLn.showans\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns = mapM_ putAnsLn\n\nsieve :: Int -> UArray Int Bool\nsieve n = runSTUArray $ do\n t <- newArray (0,n) True\n unsafeWrite t 1 False\n let sqn = (floor.sqrt.fromIntegral) (n::Int)\n mapM_ (\\i -> unsafeRead t i >>= (flip when) (mapM_ (\\j -> (unsafeWrite t j False)) [i*i,i*(i+2)..n])) [3,5..sqn]\n return t\n\nsolve l r = rec beg 0\n where\n sve = sieve r\n beg = case mod l 4 of\n 0 -> l+1\n 1 -> l\n 2 -> l+3\n 3 -> l+2\n rec i n |i>r = n + (if l<=2 then 1 else 0)\n |unsafeAt sve i = rec (i+4) (n+1)\n |otherwise = rec (i+4) n\n\nmain = do (l,r) <- scan :: IO (Int,Int)\n print (solve l r)"}], "src_uid": "55a83526c10126ac3a6e6e5154b120d0"} {"source_code": "import Control.Monad\n\nf :: Int -> (Int,Int) -> Int\nf 1 (a,b)\n | a <= b = b - a + b\n | otherwise = -1\nf n (a,b)\n | even n = f (div n 2) (a+1,b)\n | mod n 3 == 0 = f (div n 3) (a,b+1)\n | otherwise = -1\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n print $ f n (0,0)\n", "positive_code": [{"source_code": "solve :: Int -> Int -> Int\nsolve k n\n | n == 1 = k\n | n `mod` 6 == 0 = solve (k + 1) (n `div` 6)\n | n `mod` 3 == 0 = solve (k + 1) (2 * n)\n | otherwise = -1\n\nmain :: IO ()\nmain = interact $ unlines . map show . map (solve 0) . map read . tail . lines"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.Maybe (fromMaybe)\n\nmain = readLn >>= flip replicateM_ (getLine >>= print . fromMaybe (-1) . f . read)\n\nf :: Int -> Maybe Int\nf 1 = Just 0\nf n | n `mod` 6 == 0 = (1+) <$> f (n `div` 6)\n | n `mod` 3 == 0 = (2+) <$> f (n `div` 3)\n | otherwise = Nothing"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = (itoline . solve . linetoi) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nfac :: Int -> [Int]\nfac = unfoldr firstfac where\n firstfac n = listToMaybe [ (f, n `div` f) | f <- [6,3,(max n 2)], n `mod` f == 0]\n\nsolve :: Int -> Int\nsolve n | n==1 = 0\n | (not.null) [x | x <-fac n, x /=6, x/=3] = -1\n | otherwise = sum [6 `div` x | x<-fac n]\n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = (itoline . solve . linetoi) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: Int -> Int\nsolve = (fromMaybe (-1)).solve' where\n solve' n | n == 1 = Just 0\n | n `mod` 6 == 0 = pure (+) <*> Just 1 <*> solve' (n `div` 6)\n | n `mod` 3 == 0 = pure (+) <*> Just 2 <*> solve' (n `div` 3)\n | otherwise = Nothing\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess 1 n = n\nprocess x n | mod x 3 >0 = -1\n | mod x 6==0 = process (div x 6) (n+1)\n | otherwise = process (x+x) (n+1)\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tprint $ process x 0 \n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [], "src_uid": "3ae468c425c7b156983414372fd35ab8"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n s <- ((++ \"R\").('R' :)) <$> getLine\n print $ maximum $ zipWith subtract <*> tail $ map snd $ filter ((== 'R').fst) $ zip s [0..]\n test (i - 1)\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO ()\n\nmain = interact (format' . solve . format)\n\nsolve :: [[Int]] -> [Int]\nsolve = map solver\n\nformat' = unlines . map show\n\nsolver :: [Int] -> Int\nsolver xs = f 0 0 xs\n\nf i l [] = i -- last\nf i l (x:xs)\n | i < (x - l) = f (x - l) x xs\n | otherwise = f i x xs\n\n \nformat :: String -> [[Int]]\nformat xs = map (map fst . filter ((=='R') . snd) . zip [1..] . foldr (:) \"R\") . tail . lines $ xs\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n t <- readLn\n replicateM t $ getLine >>= print.solve\nsolve = (+1).foldl max 0.map length.filter((=='L').head).group"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n str <- getLine\n print $ maxDist 1 str\n\nmaxDist n \"\" = n\nmaxDist n ('R':xs) = max n $ maxDist 1 xs\nmaxDist n (_:xs) = maxDist (succ n) xs\n\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nsolve xs = dist rs\n where\n l = length xs\n rs = sort $ (elemIndices 'R' xs) ++ [-1,l]\n dist [_] = 0\n dist (x:y:xs) = max (y-x) (dist (y:xs))\n\nmain = do\n t <- readLn :: IO Int\n xss <- replicateM t $ do\n getLine >>= return\n mapM_ (print . solve) xss\n"}], "negative_code": [], "src_uid": "6451507b21854d5b81aeaf0491ddf584"} {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Graph (buildG, components)\nimport Data.List ((\\\\))\nimport Data.Tree (flatten)\n\nmain :: IO ()\nmain = solve <$> (toTuple . map read . words <$> getLine) <*> (map (map read . tail . words) . lines <$> getContents) >>= print\n\nsolve :: (Int, Int) -> [[Int]] -> Int\nsolve (n, m) xs | all null xs = n\n | otherwise = length (map flatten (components graph) \\\\ map (:[]) [n + 1 .. n + m]) - 1\n where graph = buildG (1, n + m) $ concatMap (\\(i, ys) -> map (\\y -> (i, n + y)) ys) $ zip [1..] xs\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n", "positive_code": [{"source_code": "import qualified Data.Map as M\nimport Data.List\n\nmain = interact $ show . solve . tail . map (tail . map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve lss = emp + (max 0 $ length (group $ sort $ map (root disjointSet) $ M.elems disjointSet) - 1)\n where\n (emp, disjointSet) = foldl f (0, M.empty) $ zip [101..] lss\n f (e, set) (n, []) = (e + 1, set)\n f (e, set) (n, ls) = (e, foldl (g n) set $ map (root set) ls)\n g n set r = M.insert r n set \n\nroot set l\n | M.member l set = root set (set M.! l)\n | otherwise = l\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Graph\nimport Data.Tree\nimport Data.Char (ord)\nimport Data.List ((\\\\), intercalate)\n\nsolve :: Int -> Int -> [[Int]] -> Int\nsolve n m xss\n | all (== [0]) xss = n\n | otherwise = length (map flatten (components graph) \\\\ (map toList [n+1 .. n+m])) - 1\n where\n toList x = [x]\n xss' = zip [1..] $ map (tail . map (+n)) xss\n graph = buildG (1, n + m) $ concatMap (\\(i, ls) -> zip (repeat i) ls) xss'\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n xss <- replicateM n reads\n print $ solve n m xss\n\n where\n{-\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n-}\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array (Array)\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List hiding (find)\nimport Data.Ord\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmkGraph :: Int -> [(Int,Int)] -> Array Int [Int]\nmkGraph vnum edges = unsafeAccumArray (flip (:)) [] (0,vnum-1) edges\n\nmain = do\n [n,m] <- map read.words <$> getLine :: IO [Int]\n let f i [] = [(m,i)]\n f i xs = xs\n langToPerson <- mkGraph (m+1).concat.zipWith(\\i (_:xs)->f i$map((,i).pred)xs)[0..].map(map readInt.B.words).B.lines <$> B.getContents :: IO (Array Int [Int])\n uf <- mkUnionFind n\n mapM_ (unites uf.unsafeAt langToPerson) [0..m]\n tmp <- pred.length.unique.sort <$> mapM (flip find uf) [0..n-1]\n let zeros = length $ unsafeAt langToPerson m\n res | tmp == 0 = zeros\n | zeros <= 1 = tmp\n | otherwise = tmp + zeros - 1\n print $ res\n\nunique (x:xs) = x : unique (dropWhile (x==) xs)\nunique [] = []\n\nunites uf (x:y:xs) = unite x y uf >> unites uf (y:xs)\nunites _ _ = return ()\n\ntype Parent = Int\ntype Rank = Int\ndata UnionFind = UF !(IOUArray Int Parent) !(IOUArray Int Rank)\n\nmkUnionFind :: Int -> IO UnionFind\nmkUnionFind n = do\n parent <- newListArray (0,n-1) [0..n-1] :: IO (IOUArray Int Parent)\n rank <- newArray (0,n-1) 0 :: IO (IOUArray Int Rank)\n return $! UF parent rank\n\nfind :: Int -> UnionFind -> IO Parent\nfind x uf@(UF parent _) = do\n px <- unsafeRead parent x\n if x==px\n then return x\n else do\n ppx <- find px uf\n unsafeWrite parent x ppx\n return ppx\n\nunite :: Int -> Int -> UnionFind -> IO ()\nunite x y uf@(UF parent rank) = do\n px <- find x uf\n py <- find y uf\n when (px/=py) $ do\n rx <- unsafeRead rank px\n ry <- unsafeRead rank py\n case compare rx ry of\n LT -> unsafeWrite parent px py\n GT -> unsafeWrite parent py px\n EQ -> do\n unsafeWrite parent px py\n unsafeWrite rank py $! ry+1\n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Graph\nimport Data.Tree\nimport Data.Char (ord)\nimport Data.List ((\\\\), intercalate)\n\nsolve :: Int -> Int -> [[Int]] -> Int\nsolve n m xss = length (map flatten (components graph) \\\\ (map toList [n+1 .. n+m])) - 1\n where\n toList x = [x]\n xss' = zip [1..] $ map (tail . map (+n)) xss\n graph = buildG (1, n + m) $ concatMap (\\(i, ls) -> zip (repeat i) ls) xss'\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n xss <- replicateM n reads\n print $ solve n m xss\n\n where\n{-\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n-}\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Graph (buildG, components)\nimport Data.List ((\\\\))\nimport Data.Tree (flatten)\n\nmain :: IO ()\nmain = solve <$> (toTuple . map read . words <$> getLine) <*> (map (map read . tail . words) . lines <$> getContents) >>= print\n\nsolve :: (Int, Int) -> [[Int]] -> Int\nsolve (n, m) xs = length (map flatten (components graph) \\\\ map (:[]) [n + 1 .. n + m]) - 1\n where graph = buildG (1, n + m) $ concatMap (\\(i, ys) -> map (\\y -> (i, n + y)) ys) $ zip [1..] xs\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\n\nmain = interact $ show . solve . tail . map (tail . map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve lss = length (group $ sort $ map (root disjointSet) $ M.elems disjointSet) - 1\n where\n disjointSet = foldl f M.empty $ zip [101..] lss\n f set (n, []) = M.insert (n * n) n set\n f set (n, ls) = foldl (g n) set ls\n g n set l = M.insert (root set l) n set \n\nroot set l\n | M.member l set = root set (set M.! l)\n | otherwise = l\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array (Array)\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List hiding (find)\nimport Data.Ord\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmkGraph :: Int -> [(Int,Int)] -> Array Int [Int]\nmkGraph vnum edges = unsafeAccumArray (flip (:)) [] (0,vnum-1) edges\n\nmain = do\n [n,m] <- map read.words <$> getLine :: IO [Int]\n langToPerson <- mkGraph m.concat.zipWith(\\i (_:xs)->map((,i).pred)xs)[0..].map(map readInt.B.words).B.lines <$> B.getContents :: IO (Array Int [Int])\n uf <- mkUnionFind n\n mapM_ (unites uf.unsafeAt langToPerson) [0..m-1]\n res <- pred.length.unique.sort <$> mapM (flip find uf) [0..n-1]\n print res\n\nunique (x:xs) = x : unique (dropWhile (x==) xs)\nunique [] = []\n\nunites uf (x:y:xs) = unite x y uf >> unites uf (y:xs)\nunites _ _ = return ()\n\ntype Parent = Int\ntype Rank = Int\ndata UnionFind = UF !(IOUArray Int Parent) !(IOUArray Int Rank)\n\nmkUnionFind :: Int -> IO UnionFind\nmkUnionFind n = do\n parent <- newListArray (0,n-1) [0..n-1] :: IO (IOUArray Int Parent)\n rank <- newArray (0,n-1) 0 :: IO (IOUArray Int Rank)\n return $! UF parent rank\n\nfind :: Int -> UnionFind -> IO Parent\nfind x uf@(UF parent _) = do\n px <- unsafeRead parent x\n if x==px\n then return x\n else do\n ppx <- find px uf\n unsafeWrite parent x ppx\n return ppx\n\nunite :: Int -> Int -> UnionFind -> IO ()\nunite x y uf@(UF parent rank) = do\n px <- find x uf\n py <- find y uf\n when (px/=py) $ do\n rx <- unsafeRead rank px\n ry <- unsafeRead rank py\n case compare rx ry of\n LT -> unsafeWrite parent px py\n GT -> unsafeWrite parent py px\n EQ -> do\n unsafeWrite parent px py\n unsafeWrite rank py $! ry+1\n"}], "src_uid": "e2836276aee2459979b232e5b29e6d57"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = getLine >> B.getContents >>= print.solve.B.words\n\nsolve :: [B.ByteString] -> Int\nsolve bss = go 0 1 [] IS.empty bss\n where\n go !res !num (top:stock) set (\"remove\":rest)\n | top == num = go res (num + 1) stock set rest\n | set' <- foldl' (flip IS.insert) set (top:stock) =\n go (res + 1) (num + 1) [] (IS.deleteMin set') rest\n go !res !num [] set (\"remove\":rest) =\n go res (num + 1) [] (IS.deleteMin set) rest\n go res num stock set (\"add\":x:rest) =\n go res num (readInt x:stock) set rest\n go res _ _ _ [] = res", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\ndata Command = Add {-# UNPACK #-} !Int | Remove\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve n cs = (\\(a, _, _, _) -> a) $ foldl go (0, 1, [], []) cs \n where\n go (!cnt, !i, s, !sorted) c = case c of\n Add x -> (cnt, i, x:s, False:sorted)\n Remove -> if head sorted || i == head s\n then (cnt, i + 1, tail s, tail sorted) \n else (cnt + 1, i + 1, tail s, repeat True)\n\n\nmain = do\n n <- fmap readInt B.getLine\n cs <- replicateM (2 * n) (fmap (\\l -> case B.words l of { [\"add\", x] -> Add (readInt x); _ -> Remove }) B.getLine)\n print $ solve n cs"}, {"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\ndata Command = Add Int | Remove\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve n cs = (\\(a, _, _, _) -> a) $ foldl go (0, 1, [], []) cs \n where\n go (!cnt, !i, s, !sorted) c = case c of\n Add x -> (cnt, i, x:s, False:sorted)\n Remove -> if head sorted || i == head s\n then (cnt, i + 1, tail s, tail sorted) \n else (cnt + 1, i + 1, tail s, repeat True)\n\n\nmain = do\n n <- fmap readInt B.getLine\n cs <- replicateM (2 * n) (fmap (\\l -> case B.words l of { [\"add\", x] -> Add (readInt x); _ -> Remove }) B.getLine)\n print $ solve n cs"}, {"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\ndata Command = Add {-# UNPACK #-} !Int | Remove\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve n cs = (\\(a, _, _, _) -> a) $ foldl go (0, 1, [], []) cs \n where\n go (!cnt, !i, s, sorted) c = case c of\n Add x -> (cnt, i, x:s, False:sorted)\n Remove -> if head sorted || i == head s\n then (cnt, i + 1, tail s, tail sorted) \n else (cnt + 1, i + 1, tail s, repeat True)\n\n\nmain = do\n n <- fmap readInt B.getLine\n cs <- replicateM (2 * n) (fmap (\\l -> case B.words l of { [\"add\", x] -> Add (readInt x); _ -> Remove }) B.getLine)\n print $ solve n cs"}, {"source_code": "\nimport Data.List\nimport Data.Char\n\n\n-- -- O( n^2 * log n ) method\n-- boxes lst commands srts pos\n-- | (null commands) = srts\n-- | (take 3 (head commands)) == \"add\" = boxes (((read (drop 4 (head commands)))::Int) : lst) (tail commands) srts pos\n-- | (take 3 (head commands)) == \"rem\" && (head lst) /= pos = boxes (sort lst) commands (succ srts) pos\n-- | (head lst) == pos = boxes (tail lst) (tail commands) srts (succ pos)\n\n\n\nboxes lst commands srts pos\n | (null commands) = srts\n | (take 3 (head commands)) == \"add\" = boxes (((read (drop 4 (head commands)))::Int) : lst) (tail commands) srts pos\n | (null lst) = boxes [] (tail commands) (srts) (succ pos)\n | (head lst) /= pos = boxes [] (tail commands) (succ srts) (succ pos)\n | (head lst) == pos = boxes (tail lst) (tail commands) srts (succ pos)\n\n\nmain = do\n ff <- getLine\n let n = (read (ff)) :: Int\n hh = replicate (2*n) getLine\n\n gg <- sequence hh\n let ans = boxes [] gg 0 1\n putStrLn (show ans)\n\n"}, {"source_code": "solve :: [Int] -> Int -> [String] -> Int\nsolve _ _ [] = 0\nsolve s j (\"remove\":t)\n | s == [] = sub\n | (head s) == j = solve (tail s) (j+1) t\n | otherwise = sub+1\n where sub = solve [] (j+1) t\nsolve s j (h:t) = solve (i:s) j t\n where i = read $ head $ tail $ words h\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n q <- sequence [getLine | i <- [1..(2*n)]]\n putStr $ show $ solve [] 1 q\n"}], "negative_code": [], "src_uid": "2535fc09ce74b829c26e1ebfc1ee17c6"} {"source_code": "import Data.List (sort)\r\nmain = interact $ unlines . map solve . drop 1 . lines\r\nsolve t = solve' $ map read $ words t\r\nsolve' :: [Int] -> String\r\nsolve' [a, b, c, m] =\r\n if m >= minReachable && m <= maxReachable then \"YES\" else \"NO\"\r\n where minReachable = c' - 1 - a' - b'\r\n maxReachable = a + b + c - 3\r\n [a', b', c'] = sort [a, b, c]\r\nsolve' _ = \"INVALID TEST CASE\"\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: [Int] -> Int -> String\ncalc [a,b,c] m =\n if c - (a + b + 1) <= m && m <= a + b + c - 3 then \"YES\"\n else \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b,c,m] = map read $ words line :: [Int]\n putStrLn $ calc (sort [a,b,c]) m\n"}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( sort )\r\n\r\nrl :: IO [Int]\r\nrl = fmap (map read.words) getLine\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n arr <- rl\r\n let m = last arr\r\n let f = sort . take 3 $ arr \r\n if max 0 (2 * maximum f - sum f - 1) <= m && m <= sum f - 3 \r\n then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- rl\r\n replicateM_ t solve "}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport Data.ByteString.Lazy.Char8 (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq, ViewL (..), ViewR (..), (<|),\n (|>))\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Data.Tree\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nreadB = C.unpack >>> read\n\nmain = C.interact $\n C.lines >>> drop 1 >>> map (C.words >>> map readB >>> solve >>> bool \"NO\" \"YES\") >>> C.unlines\n\nsolve :: [Int] -> Bool\nsolve [a,b,c,m] = a + b + c - m >= 3 && m >= z - (x+y) - 1\n where\n [x,y,z] = sort [a,b,c]\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: [Int] -> Int -> String\ncalc [a,b,c] m =\n if c - (a + b - 1) <= m && m <= a + b + c - 3 then \"YES\"\n else \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b,c,m] = map read $ words line :: [Int]\n putStrLn $ calc (sort [a,b,c]) m\n"}], "src_uid": "fc547fc83ebbcc3c058a069ef9fef62c"} {"source_code": "{-\nFamil Door wants to celebrate his birthday with his friends from Far Far Away.\nHe has n friends and each of them can come to the party in a specific range of\ndays of the year from ai to bi. Of course, Famil Door wants to have as many\nfriends celebrating together with him as possible.\n\nFar cars are as weird as Far Far Away citizens, so they can only carry two people\nof opposite gender, that is exactly one male and one female. However, Far is so\nfar from here that no other transportation may be used to get to the party.\n\nFamil Door should select some day of the year and invite some of his friends,\nsuch that they all are available at this moment and the number of male friends\ninvited is equal to the number of female friends invited. Find the maximum\nnumber of friends that may present at the party.\n\nInput\nThe first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 then\nnumber of Famil Door's friends.\n\nThen follow n lines, that describe the friends. Each line starts with a capital\nletter 'F' for female friends and with a capital letter 'M' for male friends.\nThen follow two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009366), providing that the i-th\nfriend can come to the party from day ai to day bi inclusive.\n\nOutput\nPrint the maximum number of people that may come to Famil Door's party.\n\nFound at: http://codeforces.com/contest/629/problem/B\n-}\n\nmodule Main where\n\nsolve :: [(Char, Int, Int)] -> Int\nsolve friends = 2 * (maximum $ zipWith (\\m f -> min m f) mTotal fTotal)\n where mFriends = filter (\\(g,_,_) -> g == 'M') friends\n mMasks = map mask mFriends\n mTotal = foldl addMasks mask0 mMasks\n fFriends = filter (\\(g,_,_) -> g == 'F') friends\n fMasks = map mask fFriends\n fTotal = foldl addMasks mask0 fMasks\n\nmask :: (Char,Int,Int) -> [Int]\nmask (_,a,b) = [if a <= i && i <= b then 1 else 0 | i <- [1..366]]\n\nmask0 = [0 | i <- [1..366]]\n\naddMasks [] [] = []\naddMasks (x:xs) (y:ys) = (x+y) : addMasks xs ys\n\ngetLines :: Int -> IO [String]\ngetLines n = sequence $ replicate n getLine\n\nparseFriend :: [String] -> (Char, Int, Int)\nparseFriend [genderStr, aStr, bStr] = (head genderStr, read aStr, read bStr)\n\nmain :: IO ()\nmain = do\n friendCountStr <- getLine\n let n = read friendCountStr :: Int\n friendLines <- getLines n\n let friends = map (parseFriend . words) friendLines\n putStrLn $ show (solve friends)\n", "positive_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Function as F\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nreadInt :: C.ByteString -> Int\n\nreadInt = fst . fromJust . C.readInt\n\ngetInts = map readInt . C.words <$> C.getLine\n\ncountLetters :: String -> Char -> Int\ncountLetters str c = length $ filter (== c) str\n\nfst3 (a,b,c) = a\nrd3 (_,_, c) = c\n\nmain :: IO ()\nmain = do\n (n:_) <- getInts\n rawInput <- replicateM n getLine\n let wordedInp = map words rawInput\n --print wordedInp\n let procInput = map processInput wordedInp\n let events = concatMap procEvent procInput\n let sEvents = sort events\n let groupedEvents = groupBy ((==) `F.on` fst3) sEvents\n let procEvents = map procList groupedEvents\n print $ rd3 $ foldl procSeries (0,0, 0) procEvents\n where\n processInput line = case line of \n [[c], n1, n2] -> (c, read n1 :: Int, read n2 :: Int)\n procEvent (c, n1, n2) = [(n1,c,1), (n2 + 1, c,-1)]\n procEl (men, women) (_, c, x) \n | c == 'M' = (men + x, women)\n | c == 'F' = (men, women + x)\n procList = \n foldl procEl (0,0)\n procSeries (men, women, score) (men2, women2) = \n (newMen, newWomen, trueScore)\n where\n newMen = men + men2\n newWomen = women + women2\n newScore = 2 * min newMen newWomen\n trueScore = max newScore score\n\n\n"}, {"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\ndata Person = Person Int Int Bool\n deriving Show\n\ninstance Eq Person where\n (Person _ a aa) == (Person _ b bb) = (a == b) && (aa == bb)\n\ninstance Ord Person where\n (Person _ a aa) <= (Person _ b bb) = (a < b) || ((a == b) && aa) || ((a == b) && (not aa) && (not bb))\n\nfindRes :: [Person] -> (Int, Int) -> Int\nfindRes [] a = 0\nfindRes ((Person i j k):xs) (a, b) =\n max (min a b) (findRes xs (c, d))\n where\n (c, d) = if i == 0 then if k then (a+1,b) else (a-1,b) else if k then (a, b+1) else (a, b-1)\n\n\ntr :: C.ByteString -> [Person]\ntr = fromJust . f . C.unpack\n where \n f (a:y:ys) = \n if (a == 'M') \n then \n (C.readInt.C.pack $ ys) >>= \n \\x -> Just $ [ Person 0 (fst x) True\n , Person 0 ((fst . fromJust . C.readInt . C.pack . tail . C.unpack . snd) x) False]\n else\n (C.readInt.C.pack $ ys) >>= \n \\x -> Just $ [ Person 1 (fst x) True\n , Person 1 ((fst . fromJust . C.readInt . C.pack . tail . C.unpack . snd) x) False]\n\nmain :: IO ()\nmain = do\n a <- (fst.fromJust.C.readInt) <$> C.getLine\n b <- sequence $ replicate a $ tr <$> C.getLine\n print $ (*2) $ flip findRes (0, 0) $ sort . concat $ b"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n t <- fmap read getLine\n inp <- forM [1..t] $ \\_ -> do\n [s, a, b] <- fmap words getLine\n case s of\n \"F\" -> return (Friend F (read a) (read b))\n _ -> return (Friend M (read a) (read b))\n print $ solve inp\n\ndata Gender = M | F deriving (Show)\ntype Start = Int\ntype End = Int \ndata Friend = Friend Gender Start End deriving (Show)\ndata Interval = Open Int Gender | Close Int Gender deriving (Show)\n\ninstance Ord Interval where\n compare x y = compare (getIntervalVal x) (getIntervalVal y)\n \ngetIntervalVal (Open x _) = x\ngetIntervalVal (Close x _) = x\n\ninstance Eq Interval where\n x == y = getIntervalVal x == getIntervalVal y\n\n--solve :: [Friend] -> Int\nsolve fs = maximum . map f' . scanl f st . group . sort $ fs >>= intervals\n where\n f' (x, y) = (min x y)*2\n st = (0,0)\n g (a, b) = a == b\n intervals (Friend x s e) = [Open s x, Close (e+1) x]\n f (m, f) l = foldl g (m,f) l\n where\n g (m,f) (Open _ M) = (m + 1, f)\n g (m,f) (Close _ M) = (m - 1, f)\n g (m,f) (Open _ F) = (m, f + 1)\n g (m,f) (Close _ F) = (m, f - 1)\n\n\ninp = [Friend M 128(1 + 130),\n Friend F 128 (1 +131),\n Friend F 131 (1 +140),\n Friend F 131 (1 +141),\n Friend M 131 (1 +200),\n Friend M 140 (1 +200)]\n\ninp2 = [Friend M 151(1 + 307),\n Friend F 343(1 + 352),\n Friend F 117(1 + 145),\n Friend M 24 (1 + 128)]\n\ninp3 = [Friend M 157 160, Friend F 151 160, Friend F 155 159, Friend M 12 157] \n\ninp4 = [Friend M 1 2, Friend F 2 3, Friend M 0 3, Friend F 0 3, Friend M 2 2, Friend F 2 2]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\n-- import Data.Array\n-- import Data.ByteString (ByteString)\n-- import qualified Data.ByteString.Char8 as C\n-- import Data.ByteString.Char8 ()\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nmyread = read :: String -> Int\nmain = do\n n <- readLn\n ns <- map ((\\[x,a,b]->(head x,myread a,myread b)).words) <$> replicateM n getLine\n print $ solve n ns\n\nsolve :: Int -> [(Char,Int,Int)] -> Int\nsolve n ns = maximum . map (go (partition (\\(x,_,_)->x=='M') ns)) $ [1..366] where\n go !(ms,fs) !d = 2 * min (go2 d ms) (go2 d fs) where\n go2 d rs = length . filter (\\(_,a,b) -> a<=d && d<=b) $ rs"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n t <- fmap read getLine\n inp <- forM [1..t] $ \\_ -> do\n [s, a, b] <- fmap words getLine\n case s of\n \"F\" -> return (Friend F (read a) (read b + 1))\n _ -> return (Friend M (read a) (read b + 1))\n print $ solve inp\n\ndata Gender = M | F deriving (Show)\ntype Start = Int\ntype End = Int \ndata Friend = Friend Gender Start End deriving (Show)\ndata Interval = Open Int Gender | Close Int Gender deriving (Show)\n\ninstance Ord Interval where\n compare x y = compare (getIntervalVal x) (getIntervalVal y)\n \ngetIntervalVal (Open x _) = x\ngetIntervalVal (Close x _) = x\n\ninstance Eq Interval where\n x == y = getIntervalVal x == getIntervalVal y\n\n--solve :: [Friend] -> Int\nsolve fs = maximum . map (uncurry (+)) . filter g . scanl f st . group . sort $ fs >>= intervals\n where\n st = (0,0)\n g (a, b) = a == b\n intervals (Friend x s e) = [Open s x, Close e x]\n f (m, f) l = foldl g (m,f) l\n where\n\n g (m,f) (Open _ M) = (m + 1, f)\n g (m,f) (Close _ M) = (m - 1, f)\n g (m,f) (Open _ F) = (m, f + 1)\n g (m,f) (Close _ F) = (m, f - 1)\n\n\ninp = [Friend M 128(1 + 130),\n Friend F 128 (1 +131),\n Friend F 131 (1 +140),\n Friend F 131 (1 +141),\n Friend M 131 (1 +200),\n Friend M 140 (1 +200)]\n\ninp2 = [Friend M 151(1 + 307),\n Friend F 343(1 + 352),\n Friend F 117(1 + 145),\n Friend M 24 (1 + 128)]\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n t <- fmap read getLine\n inp <- forM [1..t] $ \\_ -> do\n [s, a, b] <- fmap words getLine\n case s of\n \"F\" -> return (Friend F (read a) (read b + 1))\n _ -> return (Friend M (read a) (read b + 1))\n print $ solve inp\n\ndata Gender = M | F deriving (Show)\ntype Start = Int\ntype End = Int \ndata Friend = Friend Gender Start End deriving (Show)\ndata Interval = Open Int Gender | Close Int Gender deriving (Show)\n\ninstance Ord Interval where\n compare x y = compare (getIntervalVal x) (getIntervalVal y)\n \ngetIntervalVal (Open x _) = x\ngetIntervalVal (Close x _) = x\n\ninstance Eq Interval where\n x == y = getIntervalVal x == getIntervalVal y\n\n--solve :: [Friend] -> Int\nsolve fs = maximum . map (uncurry (+)) . filter g . scanl f st . group . sort $ fs >>= intervals\n where\n st = (0,0)\n g (a, b) = a == b\n intervals (Friend x s e) = [Open s x, Close e x]\n f (m, f) l = foldl g (m,f) l\n where\n\n g (m,f) (Open _ M) = (m + 1, f)\n g (m,f) (Close _ M) = (m - 1, f)\n g (m,f) (Open _ F) = (m, f + 1)\n g (m,f) (Close _ F) = (m, f - 1)\n\n\ninp = [Friend M 128(1 + 130),\n Friend F 128 (1 +131),\n Friend F 131 (1 +140),\n Friend F 131 (1 +141),\n Friend M 131 (1 +200),\n Friend M 140 (1 +200)]\n\ninp2 = [Friend M 151(1 + 307),\n Friend F 343(1 + 352),\n Friend F 117(1 + 145),\n Friend M 24 (1 + 128)]\n\ninp3 = [Friend M 157 160, Friend F 151 160, Friend F 155 159, Friend M 12 157] \n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n t <- fmap read getLine\n inp <- forM [1..t] $ \\_ -> do\n [s, a, b] <- fmap words getLine\n case s of\n \"F\" -> return (Friend F (read a) (read b + 1))\n _ -> return (Friend M (read a) (read b + 1))\n print $ solve inp\n\ndata Gender = M | F deriving (Show)\ntype Start = Int\ntype End = Int \ndata Friend = Friend Gender Start End deriving (Show)\ndata Interval = Open Int Gender | Close Int Gender deriving (Show)\n\ninstance Ord Interval where\n compare x y = compare (getIntervalVal x) (getIntervalVal y)\n \ngetIntervalVal (Open x _) = x\ngetIntervalVal (Close x _) = x\n\ninstance Eq Interval where\n x == y = getIntervalVal x == getIntervalVal y\n\n--solve :: [Friend] -> Int\nsolve fs = {-maximum . map (uncurry (+)) . filter g .-} scanl f st . group . sort $ fs >>= intervals\n where\n st = (0,0)\n g (a, b) = a == b\n intervals (Friend x s e) = [Open s x, Close e x]\n f (m, f) l = foldl g (m,f) l\n where\n\n g (m,f) (Open _ M) = (m + 1, f)\n g (m,f) (Close _ M) = (m - 1, f)\n g (m,f) (Open _ F) = (m, f + 1)\n g (m,f) (Close _ F) = (m, f - 1)\n\n\ninp = [Friend M 128(1 + 130),\n Friend F 128 (1 +131),\n Friend F 131 (1 +140),\n Friend F 131 (1 +141),\n Friend M 131 (1 +200),\n Friend M 140 (1 +200)]\n\ninp2 = [Friend M 151(1 + 307),\n Friend F 343(1 + 352),\n Friend F 117(1 + 145),\n Friend M 24 (1 + 128)]\n\ninp3 = [Friend M 157 160, Friend F 151 160, Friend F 155 159, Friend M 12 157] \n"}], "src_uid": "75d500bad37fbd2c5456a942bde09cd3"} {"source_code": "import qualified Data.IntMap as IM\nimport qualified Data.List as L\nimport qualified Data.Maybe as May\nimport qualified Data.Tuple as Tup\n\nmain = do\n firstLine <- getLine\n let [numLines, memSize] = map read $ words firstLine\n procRequest numLines $ makeInitMem memSize\n\nprocRequest 0 _ = return ()\nprocRequest n memStruct = do \n request <- getLine\n let (maybeCode, newMemStruct) = request2Instr request memStruct\n maybePrint maybeCode\n procRequest (n - 1) newMemStruct\n\nmaybePrint (Just code) = print code\nmaybePrint Nothing = return ()\n\nrequest2Instr :: String -> MemStruct -> (Maybe ReturnCode, MemStruct)\nrequest2Instr req = case words req of\n [\"alloc\", bytes] -> Tup.swap . fmap Just . Tup.swap . allocate (read bytes)\n [\"erase\", id] -> erase (read id)\n [\"defragment\"] -> (,) Nothing . defragment\n\n-- invariant: end - begin == size of the block\ndata Block = Block {begin :: Int, \n end :: Int,\n bid :: Maybe Int}\n deriving (Show)\ndata MemStruct = MemStruct {id2loc :: IM.IntMap Int,\n loc2alloc :: IM.IntMap Block, \n loc2free :: IM.IntMap Block,\n nextId :: Int,\n size :: Int}\n deriving (Show)\n\ndata ReturnCode = Id Int | NULL | ILLEGAL_ERASE_ARGUMENT\ninstance Show ReturnCode where\n show (Id n) = show n\n show NULL = \"NULL\"\n show ILLEGAL_ERASE_ARGUMENT = \"ILLEGAL_ERASE_ARGUMENT\"\n\nmakeInitMem memSize = MemStruct {id2loc = IM.empty,\n loc2alloc = IM.empty,\n loc2free = IM.singleton 0 (Block {begin = 0, end = memSize, bid = Nothing}),\n nextId = 1,\n size = memSize}\n\ndefragment :: MemStruct -> MemStruct\ndefragment memStruct = if IM.null $ loc2free memStruct\n then memStruct\n else MemStruct {id2loc = newIdAllocs,\n loc2alloc = newLocAllocs,\n loc2free = newFrees,\n nextId = nextId memStruct,\n size = size memStruct}\n where add2Top (allocTop, currAllocs) (Block {begin = b, end = e, bid = sameBID}) =\n (allocTop + (e - b), IM.insert allocTop \n (Block {begin = allocTop, end = (e - b) + allocTop, bid = sameBID})\n currAllocs)\n (finalTop, newLocAllocs) = IM.foldl add2Top (0, IM.empty) $ loc2alloc memStruct\n newIdAllocs = IM.foldl' (\\newIds (Block {begin = b, end = _, bid = Just bd}) -> IM.insert bd b newIds)\n IM.empty newLocAllocs\n newFrees = IM.singleton finalTop $ Block {begin = finalTop, end = size memStruct, bid = Nothing}\n\nerase :: Int -> MemStruct -> (Maybe ReturnCode, MemStruct)\nerase blkId memStruct = case IM.lookup blkId (id2loc memStruct) of\n Nothing -> (Just ILLEGAL_ERASE_ARGUMENT, memStruct)\n Just blkLoc -> let eraseBlk = (loc2alloc memStruct) IM.! blkLoc \n newIds = IM.delete blkId (id2loc memStruct)\n newAllocs = IM.delete blkLoc (loc2alloc memStruct)\n newFrees = insertIntoFrees eraseBlk (loc2free memStruct)\n in (Nothing, MemStruct {id2loc = newIds,\n loc2alloc = newAllocs,\n loc2free = newFrees,\n nextId = nextId memStruct,\n size = size memStruct})\n where insertIntoFrees fr@(Block {begin = b,\n end = e,\n bid = _})\n frees = let toMergeBs = (May.maybeToList $\n (IM.lookupLT b frees) >>=\n return . snd >>= \n (\\blk@(Block {begin = _, end = e', bid = _})\n -> if b == e'\n then Just blk\n else Nothing)) ++\n [fr] ++\n (May.maybeToList $ IM.lookup e frees)\n newBlock = foldl1 mergeBlock toMergeBs \n mergeBlock (Block {begin = b1, end = e1, bid =_})\n (Block {begin = b2, end = e2, bid = _}) =\n Block {begin = b1, end = e2, bid = Nothing}\n in IM.insert (begin newBlock) newBlock $ foldl (flip $ IM.delete . begin) frees toMergeBs\n\nallocate :: Int -> MemStruct -> (ReturnCode, MemStruct)\nallocate bytes memStruct = case maybeBlock of \n Nothing -> (NULL, memStruct)\n Just Block {begin = bg, \n end = ed,\n bid = _} -> let allocBlock = Block {begin = bg,\n end = bytes + bg,\n bid = Just newId}\n freesMinus1 = IM.delete bg $ loc2free memStruct\n newFrees = if (bytes + bg < ed)\n then IM.insert (bytes + bg) (Block {begin = bytes + bg,\n end = ed,\n bid = Nothing})\n freesMinus1\n else freesMinus1\n newId2locs = IM.insert newId bg $ id2loc memStruct\n newLoc2allocs = IM.insert bg allocBlock $ loc2alloc memStruct\n newId = nextId memStruct\n in (Id newId, MemStruct {id2loc = newId2locs,\n loc2alloc = newLoc2allocs,\n loc2free = newFrees,\n nextId = newId + 1,\n size = size memStruct})\n where maybeBlock = L.find (\\blk -> (end blk - begin blk) >= bytes) $ IM.elems $ loc2free memStruct\n", "positive_code": [{"source_code": "import Data.Map (Map)\nimport qualified Data.Map as M\nimport Data.List\nimport Data.Ord\n\ntype State = (Int , Map Int (Int, Int))\n\nalloc :: Int -> State -> Int -> (State, [String])\nalloc m (nextId, mem) n = res where\n go :: Int -> [(Int, Int)] -> Int\n go i ((st, l):t) | i + n <= st = i\n | otherwise = go (st+l) t\n go i [] = i\n \n went = go 1 (sort $ map snd $ M.toList mem)\n \n res | went + n > m+1 = ((nextId, mem) , [\"NULL\"])\n | otherwise = ((nextId + 1, M.insert nextId (went, n) mem), [show nextId])\n \ndefrag m (i, mem) = (i, M.fromList $ go 1 $ sortBy (comparing (fst.snd)) $ M.toList mem) where\n go i ((id, (from, len)):t) = (id, (i, len)):go (i+len) t\n go _ [] = []\n\nstep :: Int -> State -> [String] -> (State, [String])\nstep m state [\"defragment\"] = (defrag m state, [])\nstep m state [\"alloc\", n] = alloc m state (read n)\nstep m (i, mem) [\"erase\", x] | M.member (read x) mem = ((i, M.delete (read x) mem), [])\n | otherwise = ((i, mem), [\"ILLEGAL_ERASE_ARGUMENT\"])\n\ninitial = (1, M.empty)\n\ns :: [[String]] -> [String]\ns([_,m]:cmds)=concat$snd$mapAccumL (step (read m)) initial cmds\n\nmain=interact$unlines.s.map words.lines\n\n{-\n Not in scope: `Data.Map.erase'\n Perhaps you meant one of these:\n `Data.Map.map' (imported from Data.Map),\n `Data.Map.delete' (imported from Data.Map),\n `Data.Map.elems' (imported from Data.Map)-}"}, {"source_code": "\nimport Array\nimport Char (toUpper)\nimport Monad (liftM)\nimport Prelude hiding (print)\n\ndata Query = Alloc Int | Erase Int | Defragment deriving Read\ndata Answer = Success Int | Null | IllegalErase | Empty deriving Show\n\nsolve :: Int -> [Query] -> [Answer]\nsolve m qs = solve' 1 (accumArray undefined 0 (1, m) []) qs\n where\n solve' _ _ [] = []\n solve' n memory ((Alloc s) : qs) = case findEmptyMemory memory s of\n Just start -> Success n : solve' (n+1) (memory // (map (\\i -> (i, n)) [start .. start + s - 1])) qs\n Nothing -> Null : solve' n memory qs\n where\n findEmptyMemory memory s = findEmptyMemory' 1 0\n where\n findEmptyMemory' k l\n | l == s = Just k\n | k + l > m = Nothing\n | memory ! (k+l) == 0 = findEmptyMemory' k (l+1)\n | otherwise = findEmptyMemory' (k+l+1) 0\n solve' n memory ((Erase 0) : qs) = IllegalErase : solve' n memory qs\n solve' n memory ((Erase s) : qs) = case findMemory memory s of\n Just (start, length) -> Empty : solve' n (memory // (map (\\i -> (i, 0)) [start .. start + length - 1])) qs\n Nothing -> IllegalErase : solve' n memory qs\n where\n findMemory memory s = findMemory' 1 0\n where\n findMemory' k l\n | k + l > m && l == 0 = Nothing\n | k + l > m = Just (k, l)\n | memory ! (k+l) == s = findMemory' k (l+1)\n | memory ! (k+l) /= s && l == 0 = findMemory' (k+1) 0\n | otherwise = Just (k, l)\n solve' n memory (Defragment : qs) = solve' n (defragment memory) qs\n where\n defragment memory = defragment' 1 1 memory\n where\n defragment' start current memory\n | current > m = memory // (map (\\i -> (i, 0)) [start .. m])\n | memory ! current == 0 = defragment' start (current + 1) memory\n | otherwise = defragment' (start + 1) (current + 1) (memory // [(start, memory ! current)])\n\nparseQuery :: String -> Query\nparseQuery (c:s) = read (toUpper c : s)\n\nprint :: Answer -> IO ()\nprint (Success n) = putStrLn (show n)\nprint Null = putStrLn \"NULL\"\nprint IllegalErase = putStrLn \"ILLEGAL_ERASE_ARGUMENT\"\nprint Empty = return ()\n\nmain :: IO ()\nmain = do\n [n, m] <- liftM (map read . words) getLine\n qs <- liftM (map parseQuery . take n . lines) getContents\n mapM_ print $ solve m qs\n"}, {"source_code": "module Main where\n\nimport Data.Maybe (maybe)\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n\nints :: String -> [Int]\nints = map read . words\n\nsolve :: [String] -> [String]\nsolve (meta:commands) = go commands (Mem 0 [Free (read m)])\n where\n [_, m] = words meta\n go [] _ = []\n go (c:cs) mem = case words c of\n [\"defragment\"] -> go cs (defragment mem)\n [\"alloc\", m] -> x:go cs nextMem where (x, nextMem) = alloc (read m) mem\n [\"erase\", m] -> maybe (\"ILLEGAL_ERASE_ARGUMENT\":go cs mem) (go cs) (erase (read m) mem)\n\ndata MemState = Free Int | Allocated Int Int deriving (Show)\ndata Mem = Mem Int [MemState] deriving (Show)\n\nalloc :: Int -> Mem -> (String, Mem)\nalloc x mem@(Mem m st) = case go x st of\n Just ms -> (show nextM, Mem nextM ms)\n Nothing -> (\"NULL\", mem)\n where\n nextM = m + 1\n go :: Int -> [MemState] -> Maybe [MemState]\n go _ [] = Nothing\n go x (Free c:xs) | c == x = Just $ Allocated nextM x:xs\n go x (Free c:xs) | c > x = Just $ Allocated nextM x:Free (c -x):xs\n go x (y:xs) = (y :) <$> go x xs\n\nerase :: Int -> Mem -> Maybe Mem\nerase x (Mem m st) = Mem m <$> go x st\n where\n go _ [] = Nothing\n go x (Allocated y c:Free d:xs) | x == y = Just $ Free (c + d):xs\n go x (Allocated y c:xs) | x == y = Just $ Free c:xs\n go x (y:xs) = (y :) <$> go x xs\n\ndefragment :: Mem -> Mem\ndefragment (Mem m st) = Mem m (go st 0)\n where\n go [] 0 = []\n go [] acc = [Free acc]\n go (Free a:xs) acc = go xs (acc + a)\n go (a:xs) acc = a:go xs acc\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Maybe (maybe)\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n\nints :: String -> [Int]\nints = map read . words\n\nsolve :: [String] -> [String]\nsolve (meta:commands) = go commands (Mem 0 [Free (read m)])\n where\n [_, m] = words meta\n go [] _ = []\n go (c:cs) mem = case words c of\n [\"defragment\"] -> go cs (defragment mem)\n [\"alloc\", m] -> x:go cs nextMem where (x, nextMem) = alloc (read m) mem\n [\"erase\", m] -> maybe (\"ILLEGAL_ERASE_ARGUMENT\":go cs mem) (go cs) (erase (read m) mem)\n\ndata MemState = Free Int | Allocated Int Int deriving (Show)\ndata Mem = Mem Int [MemState] deriving (Show)\n\nalloc :: Int -> Mem -> (String, Mem)\nalloc x mem@(Mem m st) = case go x st of\n Just ms -> (show nextM, Mem nextM ms)\n Nothing -> (\"NULL\", mem)\n where\n nextM = m + 1\n go :: Int -> [MemState] -> Maybe [MemState]\n go _ [] = Nothing\n go x (Free c:xs) | c == x = Just $ Allocated nextM x:xs\n go x (Free c:xs) | c > x = Just $ Allocated nextM x:Free (c -x):xs\n go x (y:xs) = (y :) <$> go x xs\n\nerase :: Int -> Mem -> Maybe Mem\nerase x (Mem m st) = Mem m <$> go x st\n where\n go _ [] = Nothing\n go x (Allocated y c:Free d:xs) | x == y = Just $ Free (c + d): xs\n go x (Allocated y c:xs) | x == y = Just $ Free c: xs\n go x (_:xs) = go x xs\n\ndefragment :: Mem -> Mem\ndefragment (Mem m st) = Mem m (go st 0)\n where\n go [] 0 = []\n go [] acc = [Free acc]\n go (Free a:xs) acc = go xs (acc + a)\n go (a:xs) acc = a:go xs acc\n"}, {"source_code": "import Data.Map (Map)\nimport qualified Data.Map as M\nimport Data.List\nimport Data.Ord\n\ntype State = (Int , Map Int (Int, Int))\n\nalloc :: Int -> State -> Int -> (State, [String])\nalloc m (nextId, mem) n = res where\n go :: Int -> [(Int, Int)] -> Int\n go i ((st, l):t) | i + n <= st = i\n | otherwise = go (st+l) t\n go i [] = i\n \n went = go 1 (sort $ map snd $ M.toList mem)\n \n res | went + n > m = ((nextId, mem) , [\"NULL\"])\n | otherwise = ((nextId + 1, M.insert nextId (went, n) mem), [show nextId])\n \ndefrag m (i, mem) = (i, M.fromList $ go 1 $ sortBy (comparing (fst.snd)) $ M.toList mem) where\n go i ((id, (from, len)):t) = (id, (i, len)):go (i+len) t\n go _ [] = []\n\nstep :: Int -> State -> [String] -> (State, [String])\nstep m state [\"defragment\"] = (defrag m state, [])\nstep m state [\"alloc\", n] = alloc m state (read n)\nstep m (i, mem) [\"erase\", x] | M.member (read x) mem = ((i, M.delete (read x) mem), [])\n | otherwise = ((i, mem), [\"ILLEGAL_ERASE_ARGUMENT\"])\n\ninitial = (1, M.empty)\n\ns :: [[String]] -> [String]\ns([_,m]:cmds)=concat$snd$mapAccumL (step (read m)) initial cmds\n\nmain=interact$unlines.s.map words.lines\n\n{-\n Not in scope: `Data.Map.erase'\n Perhaps you meant one of these:\n `Data.Map.map' (imported from Data.Map),\n `Data.Map.delete' (imported from Data.Map),\n `Data.Map.elems' (imported from Data.Map)-}"}], "src_uid": "a6cba17c5ddb93f6741e00280fb6c54c"} {"source_code": "--{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\n--import Prelude as P\n--import Data.Char as C\n--import Data.List as L\n--import Data.IntSet as S\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n sxs <- getLine\n let xs = map read $ words sxs :: [Int]\n odds = length $ filter odd xs in\n putStrLn (if odds == n then \"Yes\" else \"No\")\n \n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n\n\n \n\n \n", "positive_code": [{"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let ce = length $ filter even a\r\n putStrLn $ if ce == n then \"Yes\" else \"No\"\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "module Main where\r\n\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nsolve :: [Int] -> String\r\nsolve lst\r\n | e == o = \"Yes\"\r\n | otherwise = \"No\"\r\n where \r\n e = length (filter even lst)\r\n o = length (filter odd lst)\r\n\r\nreadTestcase :: IO [Int]\r\nreadTestcase =\r\n getLine >> getLine >>= \\l ->\r\n return $ map read (words l)\r\n\r\nmain :: IO ()\r\nmain = getLine >>= \\nstr ->\r\n let n = read nstr in\r\n replicateM n readTestcase >>= \\tests ->\r\n putStrLn (unlines $ map solve tests)\r\n\r\n"}, {"source_code": "module Main where\r\n\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nsplitPar :: [Int] -> ([Int], [Int])\r\nsplitPar lst = (filter even lst, filter odd lst)\r\n\r\nsolve :: [Int] -> String\r\nsolve lst\r\n | length e == length o = \"Yes\"\r\n | otherwise = \"No\"\r\n where (e, o) = splitPar lst\r\n\r\nreadTestcase :: IO [Int]\r\nreadTestcase =\r\n getLine >> getLine >>= \\l ->\r\n return $ map read (words l)\r\n\r\n\r\nmain :: IO ()\r\nmain = getLine >>= \\nstr ->\r\n let n = read nstr in\r\n replicateM n readTestcase >>= \\tests ->\r\n putStrLn (unlines $ map solve tests)\r\n\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Bool\nimport Control.Monad\n\ncountOddEven = foldl (\\(o, e) a -> if odd a then (o + 1, e) else (o, e + 1))\n (0, 0)\n\nsolve lst = bool \"NO\" \"YES\" $ odd == even\n where\n !counter = countOddEven lst\n !odd = fst counter\n !even = snd counter\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- readInt <$> getLine\n replicateM_ n $ do\n _ <- getLine\n lst <- map readInt . words <$> getLine\n putStrLn $ solve lst\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\ncanPartition :: [Int] -> Bool\r\ncanPartition xs = numEven == numOdd where\r\n numEven = length $ filter even xs\r\n numOdd = length $ filter odd xs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- getLine\r\n ans <- canPartition <$> readInts\r\n putStrLn (if ans then \"YES\" else \"NO\")\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "\r\nimport Control.Monad\r\n\r\noddSets :: [Int]-> Bool\r\n \r\noddSets xs = (length xs) == 2*(length [x | x <- xs, (x `mod` 2) == 0]) \r\n\r\nit = do\r\n\tn_s <- getLine\r\n\tln_s <-getLine\r\n\t\r\n\tlet ans = oddSets(fmap read (words ln_s))\r\n\tlet ans_s = if ans == True\r\n\t\tthen \"Yes\"\r\n\t\telse \"No\"\r\n\t\r\n\tputStrLn ans_s\r\n\t\r\n\t\r\nmain = do \r\n\tn_s <- getLine\r\n\tlet n = read n_s :: Int \r\n\tlet prog = take n (repeat it)\r\n\tsequence prog\r\n\treturn ()"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read)\r\n >>> chunksOf 2\r\n >>> map (solve >>> bool \"No\" \"Yes\")\r\n >>> unlines\r\n\r\nsolve :: [[Int]] -> Bool\r\nsolve [[n], xs] = length (filter odd xs) == n\r\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintS = do \r\n n <- readLn::IO Int \r\n a<-readInts \r\n let o = sum[1|x<-a,mod x 2 == 1]\r\n putStrLn $ if (o == n) then \"Yes\" else \"No\" \r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}], "negative_code": [], "src_uid": "d5bd27c969d9cd910f13baa53c247871"} {"source_code": "import Data.Ord\nimport Data.List\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve = unlines . map f . readInput . tail . lines\n where\n readInput [] = []\n readInput (s:t:ts) = (s,t) : readInput ts\n\nf :: (String, String) -> String\nf (s, t)\n | no as || no bs || no cs || t /= \"abc\" = sort s\n | otherwise = sortBy (comparing g) s\n where\n no = not . flip any s \n as = (== 'a')\n bs = (== 'b')\n cs = (== 'c')\n\ng :: Char -> Char\ng 'c' = 'b'\ng 'b' = 'c'\ng chr = chr\n", "positive_code": [{"source_code": "-- https://codeforces.com/contest/1617/problem/A\nimport Data.List\n\ncount char string = length $ filter (== char) string\ngetCountAbc str = [count 'a' str, count 'b' str, count 'c' str]\nexcludeAbc = filter (`notElem` \"abc\")\nduplicate char 0 = \"\"\nduplicate char n = char : duplicate char (n-1)\nabcAnswer perm countAbc =\n duplicate 'a' (countAbc!!0) ++\n if perm /= \"abc\" || countAbc!!0 == 0 then\n duplicate 'b' (countAbc!!1) ++\n duplicate 'c' (countAbc!!2)\n else\n duplicate 'c' (countAbc!!2) ++\n duplicate 'b' (countAbc!!1)\n\nrun 0 = return 0\nrun n = do\n s <- getLine\n perm <- getLine\n putStrLn $ abcAnswer perm (getCountAbc s) ++ sort (excludeAbc s)\n run $ n-1\nmain = getLine >>= run . read\n\n"}], "negative_code": [{"source_code": "-- https://codeforces.com/contest/1617/problem/A\nimport Data.List\n\ncount char string = length $ filter (== char) string\ngetCountAbc str = [count 'a' str, count 'b' str, count 'c' str]\nexcludeAbc = filter (`notElem` \"abc\")\nduplicate char 0 = \"\"\nduplicate char n = char : duplicate char (n-1)\nabcAnswer perm countAbc =\n duplicate (perm!!0) (countAbc!!0) ++\n if perm /= \"abc\" || countAbc!!0 == 0 then\n duplicate 'b' (countAbc!!1) ++\n duplicate 'c' (countAbc!!2)\n else\n duplicate 'c' (countAbc!!2) ++\n duplicate 'b' (countAbc!!1)\n\nrun 0 = return 0\nrun n = do\n s <- getLine\n perm <- getLine\n putStrLn $ abcAnswer perm (getCountAbc s) ++ sort (excludeAbc s)\n run $ n-1\nmain = getLine >>= run . read\n\n"}], "src_uid": "419ef3579fe142c295ec4d89ee7becfc"} {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\n--import qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nmain :: IO ()\nmain = do\n n:k:m:_ <- readInts\n a <- readInts\n let func = take k . fromMaybe [] . find (\\l -> length l >= k)\n c = func . groupBy (on (==) (`mod` m)) . sortBy (on compare (`mod` m)) $ a\n if null c\n then putStr \"No\"\n else putStr $ \"Yes\\n\" ++ textRepresentation c", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.IntMap as M\n\nmain = B.interact (B.pack . evalState app . B.words)\n\napp = do\n n <- poi\n maybe \"No\" ((\"Yes\\n\" ++ ) . unwords . map show) `fmap` liftM3 solve poi poi (replicateM n poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve k m = msum . map (takeAtLeast k) . M.elems . M.fromListWith (++) . map (\\x -> (x `rem` m, [x]))\n\ntakeAtLeast = go id\n where\n go xs k []\n | k > 0 = Nothing\n | otherwise = Just $ xs []\n go xs 0 _ = Just $ xs []\n go xs k (y:ys) = go (xs . (y:)) (k - 1) ys\n\n-- 1 4 8\n-- 3 4\n--"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\n--import qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nmain :: IO ()\nmain = do\n n:k:m:_ <- readInts\n a <- readInts\n let func = take k . fromMaybe [] . find (\\l -> length l >= k)\n c = func . groupBy (on (==) (`mod` m)) . sortBy (on compare (`mod` m)) $ a\n if null c\n then putStr \"No\"\n else putStr $ \"Yes\\n\" ++ textRepresentation c"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.IntMap as M\n\nmain = B.interact (B.pack . evalState app . B.words)\n\napp = do\n n <- poi\n maybe \"NO\" ((\"YES\\n\" ++ ) . unwords . map show) `fmap` liftM3 solve poi poi (replicateM n poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve k m = msum . map (takeAtLeast k) . M.elems . M.fromListWith (++) . map (\\x -> (x `rem` m, [x]))\n\ntakeAtLeast = go id\n where\n go xs k []\n | k > 0 = Nothing\n | otherwise = Just $ xs []\n go xs 0 _ = Just $ xs []\n go xs k (y:ys) = go (xs . (y:)) (k - 1) ys\n\n-- 1 4 8\n-- 3 4\n--"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.IntMap as M\n\nmain = B.putStr . B.pack . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n maybe \"NO\" ((\"YES\\n\" ++ ) . unwords . map show) `fmap` liftM3 solve poi poi (replicateM n poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve k m = msum . map (takeAtLeast k) . M.elems . M.fromListWith (++) . map (\\x -> (x `rem` m, [x]))\n\ntakeAtLeast = go id\n where\n go xs k []\n | k > 0 = Nothing\n | otherwise = Just $ xs []\n go xs 0 _ = Just $ xs []\n go xs k (y:ys) = go (xs . (y:)) (k - 1) ys\n\n-- 1 4 8\n-- 3 4\n--"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = foldl (\\acc y -> acc ++ (show y) ++ \" \") \"\" row\n\nmain :: IO ()\nmain = do\n (n:k:m:_) <- readInts\n a <- readInts\n let c = (take k . fromMaybe [] . find (\\l -> length l >= k) . groupBy (\\x y -> mod x m == mod y m) . sortBy (\\x y -> compare(mod x m) (mod y m)) . map head . group . sort) a\n if null c\n then putStr \"No\"\n else putStr (\"Yes\\n\" ++ textRepresentation c)"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\n--import qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl (\\x y -> 10*x+ (digitToInt y)) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = (unwords . map show) row\n\nmain :: IO ()\nmain = do\n (n:k:m:_) <- readInts\n a <- readInts\n let temp = (group . sort) a\n func = take k . fromMaybe [] . find (\\l -> length l >= k)\n cc = func temp\n c = func . groupBy (on (==) (`mod` m)) . sortBy (on compare (`mod` m)) . map head $ temp\n if null c && null cc\n then putStr \"No\"\n else putStr (\"Yes\\n\" ++ (textRepresentation (if null cc then c else cc)))"}], "src_uid": "55bd1849ef13b52788a0b5685c4fcdac"} {"source_code": "import Data.Ord\nimport Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Array\nimport Debug.Trace\nimport Test.QuickCheck\n\nsolve :: String -> String -> Integer\nsolve a b =\n sum $ map (toInteger . contribution) $ [1..k]\n where\n k = length a\n delta = length b - length a\n convert x = listArray (1, length x) $ map digitToInt x\n a' = convert a\n b' = convert b\n numOnes = listArray (1, k) $ [f i | i <- [1..k]]\n numZeros i = delta + 1 - numOnes ! i\n f 1 = sum [b' ! i | i <- [1..delta+1]]\n f i = numOnes ! (i - 1) - b' ! (i - 1) + b' ! (i+delta)\n contribution i\n | a' ! i == 0 = numOnes ! i\n | otherwise = numZeros i\n\nbruteHamming :: String -> String -> Int\nbruteHamming a b =\n sum $ map hamming $ subs\n where\n subs = substrings (length a) b\n substrings n x =\n [take n (drop i x) | i <- [0..length x - n]]\n hamming :: String -> Int\n hamming b' = sum $ map fromEnum $ zipWith (/=) a b'\n\n{-\nrunChecks :: IO ()\nrunChecks =\n let\n genVec = do\n let vals = vectorOf 2 $ listOf $ elements \"01\"\n sortBy (comparing length) <$> vals\n prop_hammings [a, b] =\n solve a b == bruteHamming a b\n in quickCheck $ forAll genVec prop_hammings\n-}\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ show $ solve a b\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Data.Int\n\nmain = do \n interact solve\n\nsolve input = (show (do_solve as 0)) -- ++ \" \" ++ (intercalate \",\" (map show (elems dp_bs_1)))\n where\n as:bs:_ = words input\n as_length::Int64\n as_length = fromIntegral(length as)\n bs_length::Int64\n bs_length = fromIntegral(length bs)\n dp_bs_0 = listArray (0,bs_length) (0:(make_dp_sum bs '0' 0))\n dp_bs_1 = listArray (0,bs_length) (0:(make_dp_sum bs '1' 0))\n\n -- ca current element cid is the current index\n do_solve::[Char] -> Int64 -> Int64\n do_solve [] _ = 0\n do_solve (ca:cas) cid = cur_sum + (do_solve cas (cid+1) ) \n where\n hi_idx = min (cid + (bs_length-as_length+1) ) bs_length\n lo_idx = cid\n cur_sum \n | (ca == '1') = (dp_bs_0!hi_idx) - (dp_bs_0!lo_idx)\n -- | (ca == '1') = 0\n | (ca == '0') = (dp_bs_1!hi_idx) - (dp_bs_1!lo_idx)\n -- | (ca == '0') = 0\n\nas_string::(Show a) => [a] -> [String]\nas_string arr = map show arr\n\nmake_dp_sum::(Eq a) => [a] -> a -> Int64 -> [Int64]\nmake_dp_sum [] item csum = []\nmake_dp_sum (x:xs) item csum\n | x == item = (csum+1):(make_dp_sum xs item (csum+1))\n | otherwise = csum:(make_dp_sum xs item csum)\n"}, {"source_code": "\n-- Michael V. Antosha \n-- 2016\n-- http://mivael.in.ua\n\ntype HSumType = Integer -- sum of hamming distances\ntype LenType = Integer -- string length\n\nmain :: IO ()\nmain = do\n interact (show . solve . lines)\n\nsolve :: [String] -> HSumType\nsolve = solveStringPair\n where\n solveStringPair (a:b:[]) = solveStrAB a b\n solveStringPair _ = error \"Pair of strings expected.\"\n solveStrAB a b =\n solvePreparsed lenA lenB psums bits\n where\n (lenA, psums) = revPSumA a (0,[0])\n (lenB, bits) = revB b (0,[])\n revPSumA = pa\n revB = pb\n pa [] result = result\n pa (ch:rest) (cnt, psums@(psum:_)) =\n pa rest (cnt + 1, psum + ch2int ch : psums)\n ch2int '0' = 0\n ch2int '1' = 1\n ch2int _ = error \"ch2int: bad input\"\n pb [] result = result\n pb (ch:rest) (cnt, bits) =\n pb rest (cnt + 1, ch2bool ch : bits)\n ch2bool '0' = False\n ch2bool '1' = True\n ch2bool _ = error \"ch2bool: bad input\"\n\nsolvePreparsed :: LenType -> LenType -> [LenType] -> [Bool] -> HSumType\nsolvePreparsed lenA lenB psums bits =\n f (0 :: HSumType) (1 :: LenType) (1 :: LenType) psums psums_prev bits\n where\n (_:psums_prev) = psums\n delta | (lenB >= lenA) = lenB - lenA\n | otherwise = error \"Bad delta.\"\n f hsum cnt len c2 c1 (bit:bits) = g\n where\n g | cnt == lenB = newsum\n | cnt < lenB = f newsum (cnt + 1) newlen h2 h1 bits\n | otherwise = error \"cnt is too large\"\n (c1head:c1tail) = c1\n (c2head:c2tail) = c2\n ones = c2head - c1head\n zeros = len - ones\n s | bit == True = zeros\n | otherwise = ones\n newsum = hsum + s\n choose1 x y | cnt >= lenA = y | otherwise = x\n choose2 x y | cnt > delta = y | otherwise = x\n h1 = choose1 c1tail [0]\n h2 = choose2 c2 c2tail\n newlen = len - (choose2 0 1) + (choose1 1 0)\n f _ _ _ _ _ _ =\n error \"Internal error (wrong data for solvePreparsed/f?).\"\nsolvePreparsed _ _ _ _ =\n error \"Internal error (wrong data for solvePreparsed?).\"\n\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\n\nsolve :: [Int] -> [Int] -> Integer\nsolve a b = g a lst\n where\n lst = f cnt b $ drop (lenb - lena + 1) b\n f c _ [] = [c]\n f c (x:xs) (y:ys) = c : f (c-x+y) xs ys\n g [] [] = 0\n g (x:xs) (y:ys)\n | x == 1 = (fromIntegral lenb) - (fromIntegral lena) + 1 - (fromIntegral y) + g xs ys\n | otherwise = (fromIntegral y) + g xs ys\n lena = length a\n lenb = length b\n cnt = length . filter (==1) $ take (lenb - lena + 1) b\n\nmain :: IO ()\nmain = do\n a <- map digitToInt <$> getLine\n b <- map digitToInt <$> getLine\n print $ solve a b\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.Char\n\nsolve :: [Int] -> [Int] -> Int\nsolve a b = g a lst\n where\n lst = f cnt b $ drop (lenb - lena + 1) b\n f c _ [] = [c]\n f c (x:xs) (y:ys) = c : f (c-x+y) xs ys\n g [] [] = 0\n g (x:xs) (y:ys)\n | x == 1 = lenb - lena + 1 - y + g xs ys\n | otherwise = y + g xs ys\n lena = length a\n lenb = length b\n cnt = length . filter (==1) $ take (lenb - lena + 1) b\n\nmain :: IO ()\nmain = do\n a <- map digitToInt <$> getLine\n b <- map digitToInt <$> getLine\n print $ solve a b\n"}, {"source_code": "import Data.Ord\nimport Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Array\nimport Debug.Trace\nimport Test.QuickCheck\n\nsolve :: String -> String -> Int\nsolve a b =\n sum $ map contribution $ [1..k]\n where\n k = length a\n delta = length b - length a\n convert x = listArray (1, length x) $ map digitToInt x\n a' = convert a\n b' = convert b\n numOnes = listArray (1, k) $ [f i | i <- [1..k]]\n numZeros i = delta + 1 - numOnes ! i\n f 1 = sum [b' ! i | i <- [1..delta+1]]\n f i = numOnes ! (i - 1) - b' ! (i - 1) + b' ! (i+delta)\n contribution i\n | a' ! i == 0 = numOnes ! i\n | otherwise = numZeros i\n\nbruteHamming :: String -> String -> Int\nbruteHamming a b =\n sum $ map hamming $ subs\n where\n subs = substrings (length a) b\n substrings n x =\n [take n (drop i x) | i <- [0..length x - n]]\n hamming :: String -> Int\n hamming b' = sum $ map fromEnum $ zipWith (/=) a b'\n\n{-\nrunChecks :: IO ()\nrunChecks =\n let\n genVec = do\n let vals = vectorOf 2 $ listOf $ elements \"01\"\n sortBy (comparing length) <$> vals\n prop_hammings [a, b] =\n solve a b == bruteHamming a b\n in quickCheck $ forAll genVec prop_hammings\n-}\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ show $ solve a b\n"}, {"source_code": "import Data.List\nimport Data.Array\n\nmain = do \n interact solve\n\nsolve input = (show (do_solve as 0)) -- ++ \" \" ++ (intercalate \",\" (map show (elems dp_bs_1)))\n where\n as:bs:_ = words input\n as_length = length as\n bs_length = length bs\n dp_bs_0 = listArray (0,bs_length) (0:(make_dp_sum bs '0' 0))\n dp_bs_1 = listArray (0,bs_length) (0:(make_dp_sum bs '1' 0))\n\n -- ca current element cid is the current index\n do_solve [] _ = 0\n do_solve (ca:cas) cid = cur_sum + (do_solve cas (cid+1) ) \n where\n hi_idx = min (cid + (bs_length-as_length+1) ) bs_length\n lo_idx = cid\n cur_sum \n | ca == '1' = (dp_bs_0!hi_idx) - (dp_bs_0!lo_idx)\n -- | (ca == '1') = 0\n | (ca == '0') = (dp_bs_1!hi_idx) - (dp_bs_1!lo_idx)\n -- | (ca == '0') = 0\n\nas_string::(Show a) => [a] -> [String]\nas_string arr = map show arr\n\nmake_dp_sum::(Eq a) => [a] -> a -> Int -> [Int]\nmake_dp_sum [] item csum = []\nmake_dp_sum (x:xs) item csum\n | x == item = (csum+1):(make_dp_sum xs item (csum+1))\n | otherwise = csum:(make_dp_sum xs item csum)\n"}, {"source_code": "\nmain :: IO ()\nmain = do\n putStrLn (replicate 60000 '9')\n"}, {"source_code": "\n-- Michael V. Antosha \n-- 2016\n-- http://mivael.in.ua\n\ntype HSumType = Int -- sum of hamming distances\ntype LenType = Int -- string length\n\nmain :: IO ()\nmain = do\n interact (show . solve . lines)\n\nsolve :: [String] -> HSumType\nsolve = solveStringPair\n where\n solveStringPair (a:b:[]) = solveStrAB a b\n solveStringPair _ = error \"Pair of strings expected.\"\n solveStrAB a b =\n solvePreparsed lenA lenB psums bits\n where\n (lenA, psums) = revPSumA a (0,[0])\n (lenB, bits) = revB b (0,[])\n revPSumA = pa\n revB = pb\n pa [] result = result\n pa (ch:rest) (cnt, psums@(psum:_)) =\n pa rest (cnt + 1, psum + ch2int ch : psums)\n ch2int '0' = 0\n ch2int '1' = 1\n ch2int _ = error \"ch2int: bad input\"\n pb [] result = result\n pb (ch:rest) (cnt, bits) =\n pb rest (cnt + 1, ch2bool ch : bits)\n ch2bool '0' = False\n ch2bool '1' = True\n ch2bool _ = error \"ch2bool: bad input\"\n\nsolvePreparsed :: LenType -> LenType -> [LenType] -> [Bool] -> HSumType\nsolvePreparsed lenA lenB psums bits =\n f (0 :: HSumType) (1 :: LenType) (1 :: LenType) psums psums_prev bits\n where\n (_:psums_prev) = psums\n delta | (lenB >= lenA) = lenB - lenA\n | otherwise = error \"Bad delta.\"\n f hsum cnt len c2 c1 (bit:bits) = g\n where\n g | cnt == lenB = newsum\n | cnt < lenB = f newsum (cnt + 1) newlen h2 h1 bits\n | otherwise = error \"cnt is too large\"\n (c1head:c1tail) = c1\n (c2head:c2tail) = c2\n ones = c2head - c1head\n zeros = len - ones\n s | bit == True = zeros\n | otherwise = ones\n newsum = hsum + s\n choose1 x y | cnt >= lenA = y | otherwise = x\n choose2 x y | cnt > delta = y | otherwise = x\n h1 = choose1 c1tail [0]\n h2 = choose2 c2 c2tail\n newlen = len - (choose2 0 1) + (choose1 1 0)\n f _ _ _ _ _ _ =\n error \"Internal error (wrong data for solvePreparsed/f?).\"\nsolvePreparsed _ _ _ _ =\n error \"Internal error (wrong data for solvePreparsed?).\"\n"}], "src_uid": "ed75bd272f6d3050426548435423ca92"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nsolve :: Int -> [Int] -> Int\nsolve n as = \n if foldr1 min as == foldr1 max as\n then n\n else 1\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n as <- map readIntB8 <$> B8.words <$> B8.getLine\n let answer = solve n as\n printf \"%d\\n\" answer\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine :: IO [Int]\n if all (== head as) as then print $ length as else print 1\n"}, {"source_code": "import Control.Monad\n\nsoln :: [Int] -> Int\nsoln li\n | minimum li == maximum li = length li\n | otherwise = 1\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n li <- map read . words <$> getLine\n print (soln li)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nsolve :: String -> Int64\nsolve digitsString = pairsCount\n where\n pairsCount = sum $ map (\\cnt -> (cnt * (cnt - 1)) `div` (2 :: Int64)) countGroups\n countGroups = map (\\group -> (fromIntegral $ length group) :: Int64) . group $ sort digitSums\n digitSums = scanl' (+) 0 digits\n digits = map (\\c -> (fromIntegral ((ord c) - (ord '0') - 1)) :: Int64) digitsString\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n digits <- (head . B8.words) <$> B8.getLine\n let answer = solve $ B8.unpack digits \n printf \"%s\\n\" $ show answer\n"}], "src_uid": "7b80d3f3cd4f93e4277c76c76dc41f42"} {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.last.lines\n\nfunc::String->String\nfunc a = toStr$solve$map toInt $ words a\n where\n toStr (a,b) = (toString a) ++ \" \" ++ (toString b)\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve a = (maximum$map length l, length l)\n where\n l = group$reverse$sort a", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine :: IO Int\n hs <- ( map read . words ) `liftM` getLine :: IO [Int]\n let tower = map length $ group $ sort hs\n\n putStrLn $ show ( maximum tower ) ++ \" \" ++ show ( length tower )\n"}, {"source_code": "\nimport qualified Data.IntMap as IntMap\n\n\ncollect [] stacks = stacks\ncollect (x : xs) stacks =\n case IntMap.lookup x stacks of\n Nothing -> collect xs (IntMap.insert x 1 stacks)\n Just a -> collect xs (IntMap.insert x (a + 1) stacks)\n\ncount :: Int -> [Int] -> String\ncount barcount bars = show max_stack ++ \" \" ++ show stack_count\n where\n stack_count = IntMap.size stacks\n max_stack = IntMap.fold max 0 stacks\n stacks = collect bars IntMap.empty\n\nmain :: IO ()\nmain = do\n bar_count <- getLine >>= return . read\n bars <- getLine >>= return . (map read . words)\n putStr (count bar_count bars)\n "}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- getInts\n\n let\n ys = group $ sort xs\n m = maximum $ map length ys\n c = length ys\n\n putStrLn $ show m ++ \" \" ++ show c\n"}, {"source_code": "import Data.List (sort, sortBy, group)\nimport Data.Function (on)\n\nparse_input :: String -> [[Int]]\nparse_input str = map (map (read::String->Int).words) (lines str)\n\nsolve :: String -> String\nsolve in_str =\n let l = head.tail $ parse_input in_str\n sorted = sortBy (flip compare `on` length) $ group $ sort l\n in (show $ length $ head $ sorted) ++ \" \" ++ (show $ length $ sorted)\n\nmain :: IO ()\nmain = do interact $ solve\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nsomeFunc::IO()\nsomeFunc = getLine >> (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInt).C.words<$>C.getLine))\nsolve xs=let rs=sortBy (flip compare `on` length)$ group $ sort xs; [x,y]=[length $ head rs,length rs] in putStr $ unwords $ map show [x,y]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport Text.Printf\nimport Data.List (group, sort, maximumBy)\nimport Data.Ord (comparing)\n\ntowers bs = (h, t)\n where\n bs' = group . sort $ bs\n h = length $ maximumBy (comparing length) bs'\n t = length bs'\n\nbody [] = []\nbody (n:xs) = towers bs : body xs'\n where\n n' = read n\n (bs, xs') = splitAt n' xs\n\nfmt :: (Int, Int) -> String\nfmt (h, t) = printf \"%d %d\" h t\n\nmain = do\n ws <- words `fmap` getContents\n mapM_ (putStrLn . fmt) (body ws)\n"}, {"source_code": "import Array\n\nmaxSize = 1000::Int\n\nfillArray :: [Int] -> Array Int Int\nfillArray l = accumArray (+) 0 (1, maxSize) [(i, 1) | i <- l]\n\ngetArray :: Array Int Int -> [Int]\ngetArray a = [a!i | i <- range (bounds a)]\n\nsolution :: Array Int Int -> (Int, Int)\nsolution a = (maximum la, length (filter (\\x -> x > 0) la))\n where la = getArray a\n\nmain = do\n n <- readLn::(IO Int)\n s <- getLine\n a <- return (map (read::String -> Int) (words s))\n ans <- return (solution (fillArray a))\n putStr (show (fst ans))\n putStr \" \"\n putStr (show (snd ans))\n"}, {"source_code": "import Data.List(sort)\n\nsolve xs = (largestTower sortedXs, towerCount sortedXs)\n where sortedXs = sort xs\n\nlargestTower xs = largestTower' 0 0 xs\n where largestTower' currentHeight lastHeight [] = currentHeight\n largestTower' currentHeight lastHeight (x:xs) = if x == lastHeight\n then largestTower' (currentHeight+1) x xs\n else max currentHeight (largestTower' 1 x xs)\n\ntowerCount xs = towerCount' 0 0 xs\n where towerCount' currentCount lastHeight [] = currentCount\n towerCount' currentCount lastHeight (x:xs) = if x == lastHeight\n then towerCount' currentCount x xs\n else towerCount' (currentCount+1) x xs\n\nmain = do\n dummy <- getLine\n inputLine <- getLine\n let inputArray = words inputLine\n let sequence = map read inputArray :: [Int]\n let ans = solve sequence\n putStrLn (show (fst ans) ++ \" \" ++ show (snd ans))\n\n"}, {"source_code": "import Data.List (groupBy, sort)\nimport Data.Set (size, fromList)\n\nmain = do\n getLine\n n <- getLine\n let l = conv n\n putStr $ (show . f $ l) ++ \" \" ++ (show . g) l\n\nconv = sort . map (read::String->Int) . words\nf = maximum . (map length) . (groupBy (==))\ng = size . fromList\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\nmain=do\n\n getLine\n q1<- map read <$> words <$> getLine::IO [Int]\n let q = map length $ group $ sort q1\n putStrLn $ intercalate \" \" $ map show [maximum q , length q]\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> String\nsolve ns = unwords $ map show [ maximum (map length gns), length gns ]\n where gns = group (sort ns)\n"}, {"source_code": "import Data.List\nimport Control.Arrow\nmain = putStrLn . uncurry (++) .\n ( show . maximum . map length &&&\n (' ':) . show . length ) .\n group . sort .\n map (read :: String -> Int) . tail . words =<< getContents"}, {"source_code": "import Data.List\nmain = getLine >> fmap (map read . words) getLine >>= putStrLn . intercalate \" \" . map show . solve\nsolve :: [Int] -> [Int]\nsolve xs = [maxTower, towerCount]\n where grouped = group $ sort xs\n maxTower = maximum $ map length grouped\n towerCount = length grouped\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = do _ <- getLine\n s <- getLine\n putStrLn (solve s)\n where\n solve = unwords . map show . count . group . sort . map read . words\n\ncount :: [[Int]] -> [Int]\ncount xss = [maximum (map length xss), length xss]\n"}, {"source_code": "import Data.List\n\ngetnum :: IO [Int]\ngetnum = fmap (map read . words) getLine\n\nmain = do\n n <- readLn :: IO Int\n num <- getnum\n let g = group . sort $ num\n a = maximum $ map length g\n b = length g\n putStrLn $ unwords (map show [a,b])\n"}, {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\nimport Text.Printf\n\nsolve :: [Int] -> (Int,Int)\nsolve list = (max_height,set_size)\n where set_size = length $ nub list\n occurence = map (\\r -> length $ filter (== r) list) list\n max_height = maximum occurence\n\noutput (a,b) = (show a) ++ \" \" ++ (show b)\n\nmain = do n <- getLine \n line <- getLine\n let list = map read (words line)\n putStr $ output (solve list)"}, {"source_code": "import List\nmain = interact f\nf input = output where\n output = unwords [show d,show e]\n [n,l] = map (map (read::String->Int)) $ map words $ lines input\n a = sort $ zip l [1..]\n b [(x,_)] = [(x,1)]\n b ((x,y):xs)\n | x == u = (x,v+1):tail ys\n | otherwise = (x,1):ys\n where\n ys = b xs\n (u,v) = head ys\n c = b a\n d = foldl1 max $ map snd c\n e = length c\n"}, {"source_code": "import Data.List\n\ncalc :: [Int] -> (Int, Int)\ncalc xs = (maximum [count x xs | x <- xs], length $ nub xs)\n where\n count a xs = sum [1 | x <- xs, x == a]\n\nmain = do s <- getLine\n t <- getLine\n let (x, y) = calc $ map read $ words t\n putStrLn (show x ++ \" \" ++ show y)\n \n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\nmain=do\n\tgetLine \n\tn<- map read . words <$> getLine:: IO [Int]\n\tlet m = group $ sort n\n\tputStrLn $ show ( maximum (map length m)) ++\" \" ++ (show (length m))\n\t\n\t "}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetLineValues :: IO [Int]\ngetLineValues = getLine >>= return . map read . words\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- getLineValues\n let nss = (group . sort) ns\n largest = (maximum . map length) nss\n total = length nss\n putStrLn $ show largest ++ \" \" ++ show total"}, {"source_code": "import Data.List\nmain = getContents >>= putStrLn. (\\x ->show (maximum.map length.group.sort $ x) ++ \" \" ++ show (length.nub $ x)). tail. words\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tputStr . show . maximum. map (length) .group. sort. words $ line \n\tputStr \" \"\n\tprint.length.nub.words $ line\n\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Applicative\n\nadd k m = case res of \n Nothing -> M.insert k 1 m\n Just x -> M.insert k (x + 1) m\n where\n res = M.lookup k m\n\nf x = map snd $ M.toList $ foldr add M.empty x\n\nmain = do\n n <- (read :: String -> Int) <$> getLine\n l <- map (read :: String -> Int) <$> words <$> getLine\n let cnt = f l\n putStr $ show (maximum cnt) ++ \" \" ++ show (length cnt)\n\n"}, {"source_code": "import qualified Data.Map as M\nimport Text.Printf\n\nmain = interact f\n\nf ss = printf \"%d %d\" (maximum e) (length e)\n where\n (n:s) = map (read :: String->Int) $ words ss\n m = foldl (\\buf i -> M.insertWith (+) i 1 buf) (M.fromList ([]::[(Int, Int)])) s\n e = M.elems m"}, {"source_code": "import List\nmain = do interact $ unwords . map show . (\\i -> [maximum i, length i]) . map length . group . sort . map (read::String->Int) . tail . words\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Ord\nimport Control.Arrow\nmain = putStrLn . uncurry (++) .\n ( show . length . maximumBy (comparing sum) &&&\n (' ':) . show . length ) .\n group . sort .\n map read . tail . words =<< getContents"}], "src_uid": "9a92221c760a3b6a1e9318f948fe0473"} {"source_code": "import List\nmain = interact solve\nsolve input = output where\n a = map ( read :: String -> Int ) $ words $ last $ lines input\n output = show $ div ( a0 - 1 ) 2 + min a1 a2 - 1\n [a0,a1,a2] = map length $ group $ sort $ map (\\x -> mod x 3) ([0,1,2] ++ a)\n", "positive_code": [{"source_code": "import Data.Array (accumArray, (!))\n\nmain = do\n\tdummy <- getLine\n\ta <- getLine\n\tlet a' = accumArray (+) 0 (0, 2) $ map (\\x -> (mod x 3, 1)) $ map read $ words $ a in\n\t\tputStrLn $ show $ div (a'!0) 2 + min (a'!1) (a'!2)\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nrepeatMn a n = mapM (const a) [1..n]\nreadm::(Read a) => State String a\nreadm = State (head . reads)\n\nrunRead x s = fst $ runState x s\n\n\nmain = reader >>= writer . show . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\tl <- readm >>= repeatMn readm\n\tlet count x = length $ filter ((==x) . flip mod 3) l\n\tlet ans = (min (count 1) (count 2)) + (flip div 2 $ count 0)\n\treturn ans\n"}, {"source_code": "main = do getLine\n args <- getLine\n print $ solve $ map read $ words args\n\nsolve :: [Int] -> Int\nsolve ns = num0 `div` 2 + min num1 num2\n where\n (num0, num1, num2) = count ns\n count [] = (0, 0, 0)\n count (n:ns') = let n0 = if n `mod` 3 == 0 then 1 else 0\n n1 = if n `mod` 3 == 1 then 1 else 0\n n2 = if n `mod` 3 == 2 then 1 else 0\n (n0', n1', n2') = count ns'\n in (n0 + n0', n1 + n1', n2 + n2')"}, {"source_code": "import Data.Array\nmain=interact(show.s.map read.words)\ns (n:xs)=r!0`div`2+min(r!1)(r!2) where r=accumArray(+)0(0,2)(map(\\x->(x`mod`3,1))xs)\n"}, {"source_code": "import Data.Array\nmain = interact (show.s.map read.words)\ns (n:xs) = r!0`div`2+min(r!1)(r!2) where\n r = foldl m (listArray(0,2)[0,0,0]) xs\n m a x = a//[(i,a!i+1)] where i = x`mod`3\n"}, {"source_code": "import Array\nmain=interact(show.s.map read.words)\ns(n:y)=r!0`div`2+min(r!1)(r!2) where r=accumArray(+)0(0,2)(map(\\x->(x`mod`3,1))y)\n"}, {"source_code": "import Data.Array (accumArray, (!))\n\nmain = do\n dummy <- getLine\n a <- getLine\n let a' = accumArray (+) 0 (0, 2) $ map (\\x -> (x `mod` 3, 1)) $ map read $ words $ a in\n print $ (a'!0) `div` 2 + min (a'!1) (a'!2)\n"}, {"source_code": "toNumbers :: [Char] -> [Int]\ntoNumbers l = temp 0 l\n\ntemp :: Int -> [Char] -> [Int]\ntemp val [] = [val]\ntemp val (' ':xs) = val : (temp 0 xs)\ntemp val (x:xs) = temp (val + ((read [x]) :: Int)) xs\n\nmodBy3 :: [Int] -> Int -> Int\nmodBy3 l n = foldl (+) 0 ([1 | x <- l, (mod x 3) == n])\n\nsolve :: [Int] -> Int\nsolve l = (div (modBy3 l 0) 2) + (min (modBy3 l 2) (modBy3 l 1))\n\nmain = do\n getLine\n line <- getLine\n putStrLn (show (solve (toNumbers line)))\n"}, {"source_code": "\n\nprintNumbers :: [Int] -> IO ()\nprintNumbers [] = return ()\nprintNumbers (x:xs) = do\n putStrLn(show x)\n printNumbers xs\n\ntoNumbers :: [Char] -> [Int]\ntoNumbers l = temp 0 l\n\ntemp :: Int -> [Char] -> [Int]\ntemp val [] = [val]\ntemp val (' ':xs) = val : (temp 0 xs)\ntemp val (x:xs) = temp (val + ((read [x]) :: Int)) xs\n\nmodBy3 :: [Int] -> Int -> Int\nmodBy3 l n = foldl (+) 0 ([1 | x <- l, (mod x 3) == n])\n\nsolve :: [Int] -> Int\nsolve l = (div (modBy3 l 0) 2) + (min (modBy3 l 2) (modBy3 l 1))\n\nmain = do\n getLine\n line <- getLine\n putStrLn (show (solve (toNumbers line)))\n --printNumbers((toNumbers line))\n --putStrLn(show(modBy3(toNumbers line) 0))\n --putStrLn(show(modBy3(toNumbers line) 1))\n --putStrLn(show(modBy3(toNumbers line) 2))\n return()\n"}, {"source_code": "solve :: [Int] -> Int\nsolve a = min n1 n2 + div n0 2\n where\n a2 = map (\\x -> mod x 3) a\n n0 = length (filter (==0) a2)\n n1 = length (filter (==1) a2)\n n2 = length (filter (==2) a2)\n\nmain = do\n getLine\n line <- getLine\n let a = map read (words line)\n print (solve a)"}], "negative_code": [], "src_uid": "8d7355b3f6aebe43c7975744263f5cf8"} {"source_code": "import Data.Bits\n\nmain = interact $ pureMain\n\npureMain :: String -> String\npureMain s = if xorSum == 0 then \"bolik\\n\" else \"tolik\\n\"\n where [n]:l = map (map myRead.words) $ lines s\n xorSum = foldl xor 0 $ map (\\[x, m] -> f (x + m - 1) `xor` f (x - 1)) l\n\nmyRead :: String -> Int\nmyRead = myRead' . reverse\n where myRead' ('0':s) = myRead' s * 10 + 0\n myRead' ('1':s) = myRead' s * 10 + 1\n myRead' ('2':s) = myRead' s * 10 + 2\n myRead' ('3':s) = myRead' s * 10 + 3\n myRead' ('4':s) = myRead' s * 10 + 4\n myRead' ('5':s) = myRead' s * 10 + 5\n myRead' ('6':s) = myRead' s * 10 + 6\n myRead' ('7':s) = myRead' s * 10 + 7\n myRead' ('8':s) = myRead' s * 10 + 8\n myRead' ('9':s) = myRead' s * 10 + 9\n myRead' _ = 0\n\nf :: Int -> Int\nf x = (if even x then bit 64 - 1 else 0) .&. x `clearBit` 0 `xor` if even x /= even (div x 2) then 1 else 0", "positive_code": [{"source_code": "import Data.Bits\n\nmain = interact $ pureMain\n\npureMain :: String -> String\npureMain s = if xorSum == 0 then \"bolik\\n\" else \"tolik\\n\"\n where [n]:l = map (map read.words) $ lines s\n xorSum = foldl xor 0 $ map (\\[x, m] -> f (x + m - 1) `xor` f (x - 1)) l\n\nf :: Int -> Int\nf x = (if even x then bit 64 - 1 else 0) .&. x `clearBit` 0 `xor` if even x /= even (div x 2) then 1 else 0"}, {"source_code": "import Data.Bits\n\nmain = interact $ pureMain\n\npureMain :: String -> String\npureMain s = if xorSum == 0 then \"bolik\\n\" else \"tolik\\n\"\n where [n]:l = map (map myRead.words) $ lines s\n xorSum = foldl xor 0 $ map (\\[x, m] -> f (x + m - 1) `xor` f (x - 1)) l\n\nmyRead :: String -> Int\nmyRead = myRead' . reverse\n where myRead' ('0':s) = myRead' s * 10 + 0\n myRead' ('1':s) = myRead' s * 10 + 1\n myRead' ('2':s) = myRead' s * 10 + 2\n myRead' ('3':s) = myRead' s * 10 + 3\n myRead' ('4':s) = myRead' s * 10 + 4\n myRead' ('5':s) = myRead' s * 10 + 5\n myRead' ('6':s) = myRead' s * 10 + 6\n myRead' ('7':s) = myRead' s * 10 + 7\n myRead' ('8':s) = myRead' s * 10 + 8\n myRead' ('9':s) = myRead' s * 10 + 9\n myRead' _ = 0\n\nf :: Int -> Int\nf x = (if even x then bit 64 - 1 else 0) .&. x `xor` if even x /= even (div x 2) then 1 else 0"}], "negative_code": [], "src_uid": "55099493c66b003d4261310bf2cc8f93"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\n\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Control.Monad\r\n ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Int (Int64)\r\n\r\ndata Segment = Segment { l :: Int64\r\n , r :: Int64\r\n , cost :: Int64\r\n }\r\n\r\nsolve :: [Segment] -> [Int64]\r\nsolve segments = iter segments 2000000000 inf 0 inf inf\r\n where\r\n inf = 1000000000000000 :: Int64\r\n iter [] _ _ _ _ _ = []\r\n iter (curr:rem) lm lc rm rc singleCost =\r\n let\r\n lmNew = if l curr < lm then l curr else lm\r\n rmNew = if r curr > rm then r curr else rm\r\n lcNew = if lmNew < lm then cost curr else (if l curr == lmNew then min (cost curr) lc else lc)\r\n rcNew = if rmNew > rm then cost curr else (if r curr == rmNew then min (cost curr) rc else rc)\r\n singleCostNew = min (if l curr == lmNew && r curr == rmNew then cost curr else inf) (if lmNew == lm && rmNew == rm then singleCost else inf)\r\n in (min (lcNew + rcNew) singleCostNew):(iter rem lmNew lcNew rmNew rcNew singleCostNew)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> C.getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = let Just (i, _) = C.readInt s in i\r\n readInt64 = fromIntegral . readInt\r\n convert :: [Int64] -> Segment\r\n convert (x:(y:(z:[]))) = Segment x y z\r\n convert _ = error \"wrong data format\"\r\n readSegment :: IO Segment\r\n readSegment = do\r\n ns <- (map readInt64 . C.words) <$> C.getLine\r\n return $ convert ns\r\n gao = do\r\n n <- readInt <$> C.getLine\r\n segments <- replicateM n readSegment\r\n let\r\n results = solve segments\r\n C.putStrLn $ C.intercalate \"\\n\" $ map (C.pack . show) results\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nprefMins :: Ord t => (a -> t) -> [a] -> [t]\r\nprefMins f li = tail $ scanl' min (f $ head li) $ map f li\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n segs <- replicateM n $ do\r\n ~[li, ri, ci] <- getInts 3\r\n pure (li, ri, ci)\r\n let\r\n ls = prefMins (\\( l, _r, c) -> (l, c)) segs\r\n rs = prefMins (\\(_l, r, c) -> (negate r, c)) segs\r\n ws = prefMins (\\( l, r, c) -> (l - r, c)) segs\r\n score ((lt, lc), (rt, rc), (wa, wc)) = let\r\n wt = lt + rt\r\n in if wa == wt\r\n then min wc (lc + rc)\r\n else lc + rc\r\n pure $ foldMap (putInts . pure . score) $ zip3 ls rs ws\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\n\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Control.Monad\r\n ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Int (Int64)\r\n\r\ndata Segment = Segment { l :: Int\r\n , r :: Int\r\n , cost :: Int64\r\n }\r\n\r\nsolve :: [Segment] -> [Int64]\r\nsolve segments = iter segments 2000000000 inf 0 inf inf\r\n where\r\n inf = 1000000000000000 :: Int64\r\n iter [] _ _ _ _ _ = []\r\n iter ((Segment l r cost):rem) lm lc rm rc singleCost =\r\n let\r\n lmNew = if l < lm then l else lm\r\n rmNew = if r > rm then r else rm\r\n lcNew = if lmNew < lm then cost else (if l == lmNew then min cost lc else lc)\r\n rcNew = if rmNew > rm then cost else (if r == rmNew then min cost rc else rc)\r\n singleCostNew = min (if l == lmNew && r == rmNew then cost else inf) (if lmNew == lm && rmNew == rm then singleCost else inf)\r\n in (min (lcNew + rcNew) singleCostNew):(iter rem lmNew lcNew rmNew rcNew singleCostNew)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> C.getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = let Just (i, _) = C.readInt s in i\r\n convert :: [Int] -> Segment\r\n convert (x:(y:(z:[]))) = Segment x y (fromIntegral z)\r\n convert _ = error \"wrong data format\"\r\n readSegment :: IO Segment\r\n readSegment = do\r\n ns <- (map readInt . C.words) <$> C.getLine\r\n return $ convert ns\r\n gao = do\r\n n <- readInt <$> C.getLine\r\n segments <- replicateM n readSegment\r\n let\r\n results = solve segments\r\n C.putStrLn $ C.intercalate \"\\n\" $ map (C.pack . show) results\r\n"}, {"source_code": "module Main (main) where\r\n\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Char (isSpace)\r\nimport Data.List (unfoldr)\r\n\r\n\r\ntype SegmentBounds = (Integer, Integer)\r\ntype CoinsNumber = Integer\r\ntype Segment = (SegmentBounds, CoinsNumber)\r\n\r\n\r\nhowManyCoinsWillVasyaSpendForEveryPrefixOf :: [Segment] -> [CoinsNumber]\r\nhowManyCoinsWillVasyaSpendForEveryPrefixOf segments = results\r\n where\r\n (bounds, costs) = unzip segments\r\n (left_bounds, right_bounds) = unzip bounds\r\n\r\n expenses_by_params (best_left, left_cost, best_right, right_cost, leftright_are_same, same_cost)\r\n | leftright_are_same = same_cost\r\n | otherwise = left_cost + right_cost\r\n\r\n results = go (maximum left_bounds + 1, 0, minimum right_bounds - 1, 0, False, 0) segments\r\n go params [] = []\r\n go params (segment:next_segments) = current_expenses : go new_params next_segments\r\n where\r\n (best_left, left_cost, best_right, right_cost, leftright_are_same, same_cost) = params\r\n prev_expenses = expenses_by_params params\r\n ((l, r), c) = segment\r\n new_params\r\n | l <= best_left && r >= best_right && (c < prev_expenses || l < best_left || r > best_right)\r\n = (l, new_left_cost, r, new_right_cost, True, c)\r\n | l < best_left || (l <= best_left && c + right_cost < prev_expenses)\r\n = (l, c, best_right, right_cost, False, 0)\r\n | r > best_right || (r >= best_right && c + left_cost < prev_expenses)\r\n = (best_left, left_cost, r, c, False, 0)\r\n | otherwise\r\n = (best_left, new_left_cost, best_right, new_right_cost, leftright_are_same, same_cost)\r\n where\r\n new_left_cost = if l < best_left || (l <= best_left && c < left_cost) then c else left_cost\r\n new_right_cost = if r > best_right || (r >= best_right && c < right_cost) then c else right_cost\r\n current_expenses = expenses_by_params new_params\r\n\r\n\r\n-- IO section --\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.concat . map processTest . groupInputByTests\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest test_input = output\r\n where\r\n segments = map readSegment $ B.lines test_input\r\n result = howManyCoinsWillVasyaSpendForEveryPrefixOf segments\r\n output = B.unlines $ map bshow result\r\n bshow = B.pack . show\r\n\r\n\r\ngroupInputByTests :: B.ByteString -> [B.ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeNextTestLines\r\n\r\n takeNextTestLines [] = Nothing\r\n takeNextTestLines (l:ls) = Just $ splitAt (readInt l) ls\r\n\r\n\r\nreadSegment :: B.ByteString -> Segment\r\nreadSegment string = ((l, r), c)\r\n where\r\n [l, r, c] = readIntegers string\r\n\r\n\r\nreadIntegers :: B.ByteString -> [Integer]\r\nreadIntegers = unfoldr (B.readInteger . B.dropWhile isSpace)\r\n\r\n\r\nreadInteger :: B.ByteString -> Integer\r\nreadInteger s = r\r\n where [r] = readIntegers s\r\n\r\n\r\nreadInt :: B.ByteString -> Int\r\nreadInt = fromInteger . readInteger\r\n"}], "negative_code": [{"source_code": "module Main (main) where\r\n\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Char (isSpace)\r\nimport Data.List (unfoldr)\r\n\r\n\r\ntype SegmentBounds = (Integer, Integer)\r\ntype CoinsNumber = Integer\r\ntype Segment = (SegmentBounds, CoinsNumber)\r\n\r\n\r\nhowManyCoinsWillVasyaSpendForEveryPrefixOf :: [Segment] -> [CoinsNumber]\r\nhowManyCoinsWillVasyaSpendForEveryPrefixOf segments = results\r\n where\r\n (bounds, costs) = unzip segments\r\n (left_bounds, right_bounds) = unzip bounds\r\n\r\n expenses_by_params (best_left, left_cost, best_right, right_cost, leftright_are_same)\r\n | leftright_are_same = left_cost\r\n | otherwise = left_cost + right_cost\r\n\r\n results = go (maximum left_bounds + 1, 0, minimum right_bounds - 1, 0, False) segments\r\n go params [] = []\r\n go params (segment:next_segments) = current_expenses : go new_params next_segments\r\n where\r\n (best_left, left_cost, best_right, right_cost, leftright_are_same) = params\r\n prev_expenses = expenses_by_params params\r\n ((l, r), c) = segment\r\n new_params\r\n | l <= best_left && r >= best_right && (c < prev_expenses || l < best_left || r > best_right)\r\n = (l, c, r, c, True)\r\n | l < best_left || (l <= best_left && c + right_cost < prev_expenses)\r\n = (l, c, best_right, right_cost, False)\r\n | r > best_right || (r >= best_right && c + left_cost < prev_expenses)\r\n = (best_left, left_cost, r, c, False)\r\n | otherwise\r\n = params\r\n current_expenses = expenses_by_params new_params\r\n\r\n\r\n-- IO section --\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.concat . map processTest . groupInputByTests\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest test_input = output\r\n where\r\n segments = map readSegment $ B.lines test_input\r\n result = howManyCoinsWillVasyaSpendForEveryPrefixOf segments\r\n output = B.unlines $ map bshow result\r\n bshow = B.pack . show\r\n\r\n\r\ngroupInputByTests :: B.ByteString -> [B.ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeNextTestLines\r\n\r\n takeNextTestLines [] = Nothing\r\n takeNextTestLines (l:ls) = Just $ splitAt (readInt l) ls\r\n\r\n\r\nreadSegment :: B.ByteString -> Segment\r\nreadSegment string = ((l, r), c)\r\n where\r\n [l, r, c] = readIntegers string\r\n\r\n\r\nreadIntegers :: B.ByteString -> [Integer]\r\nreadIntegers = unfoldr (B.readInteger . B.dropWhile isSpace)\r\n\r\n\r\nreadInteger :: B.ByteString -> Integer\r\nreadInteger s = r\r\n where [r] = readIntegers s\r\n\r\n\r\nreadInt :: B.ByteString -> Int\r\nreadInt = fromInteger . readInteger\r\n"}], "src_uid": "ee773d908fc297cc692aaecf6af299c9"} {"source_code": "{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor ( (<&>) )\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Maybe (fromJust, isJust)\nimport Data.Traversable (forM)\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Map as M\nimport Control.Monad (foldM_)\nimport Data.Int\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\ncalcCnts :: B8.ByteString -> M.Map Char Int\ncalcCnts bs = flip S.execState (M.empty :: M.Map Char Int) $ do\n forM_ (B8.unpack bs) $ \\c -> do\n S.modify $ M.insertWith (+) c 1\n\nsolve :: Int -> B8.ByteString -> B8.ByteString -> Bool\nsolve k sa sb = isJust ts\n where\n cntsA = calcCnts sa\n cntsB = calcCnts sb\n ts = flip S.execState (Just 0) $ do\n forM_ ['a' .. 'z'] $ \\c -> do\n let ta = M.findWithDefault 0 c cntsA\n let tb = M.findWithDefault 0 c cntsB\n S.modify $ \\s -> do\n vs <- fmap (+ ta) s\n if vs < tb || (vs - tb) `mod` k /= 0\n then Nothing\n else return $ vs - tb\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ \\_ -> do\n [n, k] <- B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust)\n sa <- B8.getLine\n sb <- B8.getLine\n let answer = solve k sa sb\n B8.putStrLn $ if answer then \"Yes\" else \"No\"\n\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-} \n--codelegend orz\n\nimport safe Control.Arrow ((>>>))\nimport Data.Bool\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (nk : a : b : rest) = solve (last $ linetois nk) a b : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n\nsolve :: Int -> String -> String -> String\nsolve k as bs = (bool \"Yes\" \"No\") $ (==Nothing) $ foldl foo (Just 0) $ zipWith (-) (freq as) (freq bs) where\n freq xs = [length $ filter (==c) xs | c <-['a'..'z']]\n foo Nothing _ = Nothing\n foo (Just acc) x | acc + x < 0 = Nothing\n | (acc + x) `mod` k /= 0 = Nothing\n | otherwise = Just (acc + x)\n\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe, isJust)\n\nmain :: IO ()\nmain =\n interact $ lines >>> drop 1 >>> process >>> map (bool \"No\" \"Yes\") >>> unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [String] -> [Bool]\nprocess [] = []\nprocess (nk:a:b:xs) = solve k a b : process xs\n where\n k = words >>> last >>> read $ nk\n\nsolve :: Int -> String -> String -> Bool\nsolve k a b = (== Just 0) . foldl f (Just 0) $ zipWith (-) (freq a) (freq b)\n where\n freq s = [length (filter (== c) s) | c <- ['a' .. 'z']]\n f Nothing _ = Nothing\n f (Just acc) x\n | acc + x < 0 = Nothing\n | (acc + x) `mod` k /= 0 = Nothing\n | otherwise = Just (acc + x)\n"}], "negative_code": [], "src_uid": "09d0f11bdb9eca2161dee83a335dd2b7"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n s <- getLine\n putStrLn $ replicate n (s !! (n - 1))\n", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: String -> String\nsolve [c] = [c]\nsolve (c0:c1:cs) = c0 : solve cs\nsolve _ = error \"invalid input\"\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n getLine >>= putStrLn . solve\n"}, {"source_code": "import Control.Monad\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n s <- getLine\n let res = replicate n (s !! (n - 1)) \n putStrLn res\n"}, {"source_code": "import System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = tail contents\n sequence $ solve arr\n\n-- solve :: [[Char]] -> [IO [()]]\nsolve [] = []\nsolve (_:arr:xs) =\n let go [a] = [a]\n go (a:_:x) = a:go x\n in putStrLn (go arr):solve xs"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n str <- getLine\n let x = str !! (n - 1)\n putStrLn $ replicate n x\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nsolve :: String -> String\nsolve (xs:s)\n | null s = [xs] \n | otherwise = do\n let t = tail s\n [xs] ++ solve(t)\n\nmain :: IO () \nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n s <- getLine\n putStrLn $ solve s\n\n"}], "negative_code": [], "src_uid": "b37bbf1fe9ac5144cfa230633ccbdd79"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Debug.Trace\n\ndata Ball = Ball{index :: !Int, pos :: !Double, velocity :: !Double, weight :: !Double}\n deriving Show\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let readData :: (Read a) => IO [a]\n readData = map read . words <$> getLine\n eps = 1e-9 :: Double\n inf = 10 ^ 300 :: Double\n n : time : _ <- readData :: IO [Double]\n balls <- fmap (sortBy (comparing pos)) . T.for [1 .. fromEnum n] $ \\i -> do\n x : v : m : _ <- readData :: IO [Double]\n return $ Ball i x v m\n let minTime bs = do\n (Ball _ x1 v1 _, Ball _ x2 v2 _) <- zip bs (tail bs)\n guard $ v1 - v2 > eps\n return $! (x2 - x1) / (v1 - v2)\n printAll bs = putStrLn $ do\n Ball _ x _ _ <- sortBy (comparing index) bs\n printf \"%.16f\\n\" x\n move t bs = do\n b <- bs\n return $ b{pos = pos b + velocity b * t}\n simulate t bs\n | t < eps = printAll bs\n | otherwise = case minTime bs of\n ts@(_ : _) -> do\n let t' = minimum ts\n if t >= t' + eps\n then do\n simulate (t - t') $ do\n let sentinel = Ball 0 inf 0 0\n bss = init . tails . ([sentinel] ++) . (++ [sentinel])$ move t' bs\n (Ball _ xp vp mp, b@(Ball _ x v m), Ball _ xn vn mn) <- zip3 (bss !! 0) (bss !! 1) (bss !! 2)\n return $ case () of\n _ | abs (xn - x) < eps -> b{velocity = ((m - mn) * v + 2 * mn * vn) / (m + mn)}\n | abs (x - xp) < eps -> b{velocity = ((m - mp) * v + 2 * mp * vp) / (mp + m)}\n | otherwise -> b\n else simulate 0 $ move t bs\n _ -> simulate 0 $ move t bs\n simulate time balls\n{-\n2 9\n3 4 5\n0 7 8\n\n2 2\n3 7 5\n0 7 8\n-}\n", "positive_code": [{"source_code": "import List\nmain = interact (ans)\nans theInput = answer where\n\ttheLines = lines theInput\n\tline0 = words $ head $ theLines\n\tn = (read::String->Int)(line0 !! 0)\n\tt = (read::String->Float)(line0 !! 1)\n\tp0 = zip (map (map (read::String->Float)) $ map words $ tail theLines) [1..n]\n\tp = sort p0\n\tcollision [_] = []\n\tcollision (x:y:xs) = (meet x y):collision (y:xs)\n\tmeet ([x,y,_],_) ([u,v,_],_) = if y<=v then 101 else (u-x)/(y-v)\n\tnextCollisionTime xs = foldr1 min (collision xs)\n\tnextPosition u [] = []\n\tnextPosition u (([x,v,m],i):xs) = ([x+v*u,v,m],i) : (nextPosition u xs)\n\tnewSpeed v1 m1 v2 m2 = ((m1-m2)*v1+2*m2*v2)/(m1+m2)\n\tnextSpeed [] = []\n\tnextSpeed [x] = [x]\n\tnextSpeed (([x1,v1,m1],i1):([x2,v2,m2],i2):xs) = if x1/=x2\n\t\tthen ([x1,v1,m1],i1):(nextSpeed (([x2,v2,m2],i2):xs))\n\t\telse ([x1,v3,m1],i1):([x2,v4,m2],i2):(nextSpeed xs) where\n\t\t\tv3 = newSpeed v1 m1 v2 m2\n\t\t\tv4 = newSpeed v2 m2 v1 m1\n\tnextPair (x,y) = if x==t then (101,[]) else (x+dt,nextSpeed $ nextPosition dt y) where\n\t\tdt = min (t-x) (nextCollisionTime y)\n\tchange = takeWhile ((/=101).fst) (iterate nextPair (0,p))\n\tanswer = unlines $ map (show.head.snd) (sort [(x,y)|(y,x)<-(snd $ last change)])\n\n"}], "negative_code": [], "src_uid": "2432a746446990ecc2926bf00807a5ee"} {"source_code": "main = interact $ show . solve . map read . words\nsolve [h,l] = (l * l - h * h) / (2 * h)", "positive_code": [{"source_code": "readNumbers :: String -> [Double]\nreadNumbers = map read . words\n\nmain = do\n input <- getLine\n let [h, l] = readNumbers input\n print $ (l*l - h*h) / (2 * h)"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve [h,l] = l * tan gamma where\n alpha = atan (l/h)\n beta = pi/2 - alpha\n gamma = alpha - beta\n"}], "negative_code": [], "src_uid": "2cd5807e3f9685d4eff88f2283904f0d"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport qualified Data.Set as DS\r\nimport System.IO hiding (getLine,print)\r\nimport Prelude hiding (getLine)\r\nimport Data.Char\r\nimport Data.Array\r\nimport Debug.Trace\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n ss <- getLine\r\n ts <- getLine\r\n let\r\n occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]\r\n ost = DS.fromAscList [0..n-1]\r\n ans = recurse occs ost 0 maxBound ts\r\n printv [if ans==maxBound then -1 else ans]\r\n\r\nrecurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int\r\nrecurse _ _ _ ans [] = ans\r\nrecurse occs ost eqcost ans (t:ts) = let\r\n beater = take 1 $ DL.sort $ concat [take 1 (occs ! ch) | ch <-['a'..t],ch/=t]\r\n ans1 = if null beater then ans else min ans (eqcost + rank (head beater))\r\n rank r = DS.findIndex r ost\r\n in case occs ! t of\r\n [] -> ans1\r\n (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\ngetLine :: IO [Char]\r\ngetLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport qualified Data.Set as DS\r\nimport System.IO hiding (getLine,print)\r\nimport Prelude hiding (getLine)\r\nimport Data.Char\r\nimport Data.Array\r\nimport Debug.Trace\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n ss <- getLine\r\n ts <- getLine\r\n let\r\n occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]\r\n ost = DS.fromAscList [0..n-1]\r\n ans = recurse occs ost 0 maxBound ts\r\n printv [if ans==maxBound then -1 else ans]\r\n\r\nrecurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int\r\nrecurse _ _ _ ans [] = ans\r\nrecurse !occs !ost !eqcost !ans (t:ts) = let\r\n beater = minimum $ maxBound:[head occ | ch <-['a'..t], ch/=t, let occ=occs!ch, not $ null occ]\r\n ans1 = if beater==maxBound then ans else min ans (eqcost + rank beater)\r\n rank r = DS.findIndex r ost\r\n in case occs ! t of\r\n [] -> ans1\r\n (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\ngetLine :: IO [Char]\r\ngetLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport qualified Data.Set as DS\r\nimport System.IO hiding (getLine,print)\r\nimport Prelude hiding (getLine)\r\nimport Data.Char\r\nimport Data.Array\r\nimport Debug.Trace\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n ss <- getLine\r\n ts <- getLine\r\n let\r\n occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]\r\n ost = DS.fromAscList [0..n-1]\r\n ans = recurse occs ost 0 maxBound ts\r\n printv [if ans==maxBound then -1 else ans]\r\n\r\nrecurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int\r\nrecurse _ _ _ ans [] = ans\r\nrecurse occs ost eqcost ans (t:ts) = let\r\n beater = minimum $ maxBound:[head occ | ch <-['a'..t], ch/=t, let occ=occs!ch, not $ null occ]\r\n ans1 = if beater==maxBound then ans else min ans (eqcost + rank beater)\r\n rank r = DS.findIndex r ost\r\n in case occs ! t of\r\n [] -> ans1\r\n (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\ngetLine :: IO [Char]\r\ngetLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport qualified Data.IntMap.Strict as DIM\r\nimport qualified Data.Set as DS\r\nimport Data.Bool\r\nimport System.IO hiding (getLine,print)\r\nimport Prelude hiding (getLine)\r\nimport Data.Char\r\nimport Data.Function (on)\r\n\r\nrecurse :: DIM.IntMap [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int\r\nrecurse _ _ _ ans [] = ans\r\nrecurse occs occset taken ans (t:ts) = let\r\n beaters = filter (not.null.snd) $ takeWhile ((fromEnum t>).fst) $ DIM.assocs occs\r\n beater = DL.minimumBy (compare `on` (head.snd)) beaters -- if not null beaters\r\n ans'{-'-} = if null beaters then ans else min ans (taken + prevCount (head $ snd beater))\r\n prevCount r = DS.findIndex r occset\r\n (matcherMaybe,occs'{-'-}) = DIM.updateLookupWithKey (\\_ -> Just .drop 1) (fromEnum t) occs\r\n cost matcher = prevCount matcher\r\n in\r\n case matcherMaybe of\r\n (Just (m:ms)) -> recurse occs'{-'-} (DS.delete m occset) (taken+cost m) ans'{-'-} ts\r\n _ -> ans'{-'-}\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n ss <- getLine\r\n ts <- getLine\r\n let\r\n occs = DIM.fromListWith (++) (reverse $ zip (fromEnum <$> ss) (pure <$> [0..]))\r\n seg = DS.fromAscList [0..n-1]\r\n ans = recurse occs seg 0 maxBound ts\r\n printv [if ans==maxBound then -1 else ans]\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\ngetLine :: IO [Char]\r\ngetLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport qualified Data.Map.Strict as M\n\nmainFun :: SP Builder\nmainFun = do\n ~[q] <- getInts 1\n fmap mconcat $ replicateM q $ do\n ~[n] <- getInts 1\n ~[s, t] <- map P.unpack <$> getNext 2\n let\n initOccs :: Array Char [Int]\n initOccs = accumArray (flip (:)) [] ('a', 'z')\n $ zip (reverse s) [n, n-1..]\n\n initOST :: M.Map Int Char\n initOST = M.fromAscList $ zip [1..] s\n\n ans = solve initOccs initOST t maxBound 0\n\n solve :: Array Char [Int] -> M.Map Int Char -> [Char] -> Int -> Int\n -> Int\n solve occs ost tt !currBest !used = case tt of\n [] -> currBest\n _ | currBest <= used -> currBest -- not really important\n (c : ntt) -> let\n winOpts = concatMap (\\lc -> take 1 (occs ! lc)) ['a' .. pred c]\n nBest = case winOpts of\n [] -> currBest\n _ -> min currBest $ used + M.findIndex (foldl' min n winOpts) ost\n in case occs ! c of\n [] -> nBest\n (w : ws) -> let\n noccs = occs // [(c, ws)]\n nost = M.delete w ost\n nused = used + M.findIndex w ost\n in solve noccs nost ntt nBest nused\n pure $ putInts [if ans == maxBound then 0-1 else ans]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport qualified Data.Set as DS\r\nimport System.IO hiding (getLine,print)\r\nimport Prelude hiding (getLine)\r\nimport Data.Char\r\nimport Data.Array\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n ss <- getLine\r\n ts <- getLine\r\n let\r\n occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]\r\n ost = DS.fromAscList [0..n-1]\r\n ans = recurse occs ost 0 maxBound ts\r\n printv [if ans==maxBound then -1 else ans]\r\n\r\nrecurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int\r\nrecurse _ _ _ ans [] = ans\r\nrecurse occs ost eqcost ans (t:ts) = let\r\n beater = take 1 $ concat [take 1 (occs ! ch) | ch <-['a'..t],ch/=t]\r\n ans1 = if null beater then ans else min ans (eqcost + rank (head beater))\r\n rank r = DS.findIndex r ost\r\n in case occs ! t of\r\n [] -> ans1\r\n (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\ngetLine :: IO [Char]\r\ngetLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n"}], "src_uid": "71ee54d8881f20ae4b1d8bb9783948c0"} {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n nums <- map read <$> words <$> getLine\n let _ = nums :: [Int]\n sorted = sort nums\n answer = if all (==1) sorted\n then (replicate (n-1) 1) ++ [2]\n else take n $ (1:sorted)\n putStrLn $ intercalate \" \" $ map show $ answer\n\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.List\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nsolve a\n | corner = take (n-1) (repeat 1) ++ [2]\n | otherwise = (1:) . take (n-1) $ sort a\n where n = length a\n corner = all (==1) a\n\nmain = do\n input <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n putStrLn . unwords . map show . solve . readIntList $ input !! 1\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.List\nmain = interact $ unwords.map show. gao. map read. tail. words\ngao x = sort.reverse.ch.reverse.sort $ x\nch (x:s) | x == 1 = 2:s | 1 > 0 = 1:s\n"}, {"source_code": "import List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> [Int]\nsolve xs\n | maximum xs > 1 = 1:(init (sort xs))\n | otherwise = sort (2:(tail xs))\n\nprintAns :: [Int] -> IO ()\nprintAns [] = return ()\nprintAns (x:xs) = putStr (show x ++ \" \") >> printAns xs\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= printAns . solve"}, {"source_code": "import Data.List\n\nsolve xs | all (1==) xs = tail xs ++ [2]\n | otherwise = [1] ++ (init $ sort xs)\n\nmain = interact $ unwords.map show.solve.map read.tail.words\n"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (unlines . solve . (map read) . words . (!! 1) . lines)\n\nsolve :: [Int] -> [String]\nsolve arr = result where\n result = [intercalate \" \" $ map show ansInt]\n ansInt = sort $ (if last sArr == 1 then 2 else 1) : init sArr\n sArr = sort arr"}, {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\njoins :: [String] -> String\njoins [] = \"\"\njoins [x] = x\njoins (x:xs) = x ++ \" \" ++ (joins xs)\n\ntoString::[Int] -> String\n--toString = (dropWhile (== ' ')) . (concatMap (\\x -> \" \" ++ (show x)))\ntoString list = intercalate \" \" $ map show list\n\nsolve::[Int] -> [Int]\nsolve list = answerList\n where sortedList = sort list\n answerList = sort $ (if last sortedList == 1 then 2 else 1) : init sortedList\n\nmain = interact$toString.solve.(map read).tail.words"}, {"source_code": "import Data.List\n\nsolve xs | all (1==) xs = tail xs ++ [2]\n | otherwise = [1] ++ (init $ sort xs)\n\nmain = interact $ unwords.map show.solve.map read.tail.words\n"}, {"source_code": "import Data.List(sort)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n xs <- map read <$> words <$> getLine\n putStrLn $ unwords $ map show $ solve n xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs = if all (1==) xs then (take (n-1) $ xs)++[2]\n else 1:(take (n-1) $ sort xs)"}, {"source_code": "import Data.List (sort)\nsolve :: [Int] -> [Int]\nsolve xs = sort $ (if last ps > 1 then 1 else 2) : init ps \n where ps = sort xs\nmain = putStrLn.unwords.map show.solve.map read.tail.words =<< getContents"}, {"source_code": "import Data.List(sort)\n\nmain = do \n\td <- getContents\n\tlet dd = words d\n\tlet n = read $ head dd::Int\n\tlet xs = map (\\x -> read x::Int) (tail dd)\n\tputStrLn $ unwords $ map show (solve n xs)\n\nsolve n xs | all (1==) xs = take (n-1) xs ++ [2]\n | otherwise = 1:(take (n-1) $ sort xs)"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n nums <- map read <$> words <$> getLine\n let _ = nums :: [Int]\n sorted = sort nums\n putStrLn $ intercalate \" \" $ map show $ take n $ (1:sorted)\n\n"}, {"source_code": "import Data.List(sort)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n xs <- map read <$> words <$> getLine\n putStrLn $ unwords $ map show $ solve n xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs = 1:(take (n-1) $ sort xs)"}, {"source_code": "import Data.List (sort)\nsolve :: [Int] -> [Int]\nsolve xs = (if last ps > 1 then 1 else 2) : init ps \n where ps = sort xs\nmain = putStrLn.unwords.map show.solve.map read.tail.words =<< getContents"}, {"source_code": "import Data.List(sort)\n\nmain = do \n\td <- getContents\n\tlet dd = words d\n\tlet n = read $ head dd::Int\n\tlet xs = map (\\x -> read x::Int) (tail dd)\n\tprint $ unwords $ map show (solve n xs)\n\nsolve n xs | all (1==) xs = take (n-1) xs ++ [2]\n | otherwise = 1:(take (n-1) $ sort xs)"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (unlines . solve . (map read) . words . (!! 1) . lines)\n\nsolve :: [Int] -> [String]\nsolve arr = result where\n result = [intercalate \" \" $ map show ansInt]\n ansInt = 1 : init arr\n sArr = sort arr\n"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (unlines . solve . (map read) . words . (!! 1) . lines)\n\nsolve :: [Int] -> [String]\nsolve arr = result where\n result = [intercalate \" \" $ map show ansInt]\n ansInt = 1 : init sArr\n sArr = sort arr\n"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (unlines . solve . (map read) . words . (!! 1) . lines)\n\nsolve :: [Int] -> [String]\nsolve arr = result where\n result = [intercalate \" \" $ map show ansInt]\n ansInt = (if last sArr == 1 then 2 else 1) : init sArr\n sArr = sort arr"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.List\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nmain = do\n input <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n let n = readInt $ input !! 0\n a = (1:) . take (n-1) . sort . readIntList $ input !! 1\n putStrLn . unwords $ map show a\n\n-- vim: set expandtab:\n"}, {"source_code": "import List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> [Int]\nsolve xs = 1:(init (sort xs))\n\nprintAns :: [Int] -> IO ()\nprintAns [] = return ()\nprintAns (x:xs) = putStr (show x ++ \" \") >> printAns xs\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= printAns . solve"}], "src_uid": "1cd10f01347d869be38c08ad64266870"} {"source_code": "import Data.List\nimport Text.Printf\n\nmain :: IO()\nmain = do\n\tt <- getLine\n\tputStr $ getAnswer $ map (\\x -> read x :: Double) (words t)\n\nparseFloat :: Double -> String\nparseFloat = printf \"%.5f\"\n\nconcatStr :: [String] -> String\nconcatStr = foldr (++) []\n\ngetAnswer :: [Double] -> String\ngetAnswer xs \n\t| lengthSol == 3\t= \"-1\"\n\t| lengthSol == 0\t= \"0\"\n\t| otherwise\t= addNrOfSol ++ (concatStr $ map (++ \"\\n\") $ map parseFloat $ solutions)\n\t\twhere \n\t\t\tlengthSol = length solutions\n\t\t\tsolutions = sort $ f xs\n\t\t\taddNrOfSol = (show $ lengthSol) ++ \"\\n\"\n\nf (a : b : c : xs)\n\t| a == 0 && b == 0 && c == 0\t= [0, 0, 0]\n\t| a == 0 && b == 0 && c /= 0\t= []\n\t| a == 0 && b /= 0\t\t= [-c / b]\n\t| otherwise\t\t\t= solve a b c\n\t\twhere \n\t\t\tsolve a b c \n\t\t\t\t| delta < 0\t= []\n\t\t\t\t| delta == 0\t= [ -b / (2 * a) ]\n\t\t\t\t| delta > 0\t= ( -b + sqrt (delta) ) / (2 * a) : [( -b - sqrt (delta) ) / (2 * a)]\n\t\t\t\t\twhere delta = b * b - 4 * a * c", "positive_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Text.Printf (printf)\n\nsolve :: [Integer] -> Maybe [Double]\nsolve [0, 0, 0] = Nothing\nsolve [0, 0, _] = Just []\nsolve [0, b, c] = Just [(-1) * fromIntegral c / fromIntegral b]\nsolve [a, b, c]\n | d < 0 = Just []\n | d > 0 = Just [(-b' - sqrt d') / (2 * a'), (-b' + sqrt d') / (2 * a')]\n | otherwise = Just [(-b') / (2 * a')]\n where\n d = b^2 - 4*a*c\n [a', b', c', d'] = map fromIntegral [a, b, c, d]\n\nprints :: Maybe [Double] -> IO ()\nprints Nothing = print (-1)\nprints (Just []) = print 0\nprints (Just [x]) = printf \"1\\n%.6f\\n\" x\nprints (Just [x,y])\n | x < y = printf \"2\\n%.6f\\n%.6f\\n\" x y\n | otherwise = printf \"2\\n%.6f\\n%.6f\\n\" y x\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve\n"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | abs a < 1e-308 -> if abs b > 1e-308 then (1,[-c/b]) else (if c/=0 then 0 else -1,[]) \n _ | d < 0 -> (0, []) \n _ | d == 0 -> let root = (-b)/(2*a) in (1, [if root == 0 then 0 else root])\n _ -> let roots = map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d] \n in (2, sort roots)\n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> fromIntegral $ (read x::Int)) . take 3 . words\n print n\n mapM_ (printf \"%.15f\\n\") roots"}], "negative_code": [{"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\n-- import Test.Tasty\n-- import Test.Tasty.HUnit\n-- import Debug.Trace\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | a < 1e-308 -> (-1,[]) \n _ | d < 0 -> (0, []) \n _ | d == 0 -> let root = (-b)/(2*a) in (1, [if root == 0 then 0 else root])\n _ -> let roots = map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d] \n in (2, sort roots)\n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> read x::Double) . take 3 . words\n print n\n mapM_ (printf \"%.8f\\n\") roots"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\n-- import Test.Tasty\n-- import Test.Tasty.HUnit\n-- import Debug.Trace\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | abs a < 1e-38 -> if abs b> 1e-38 then (1,[-c/b]) else (-1,[]) \n _ | d < 0 -> (0, []) \n _ | d == 0 -> let root = (-b)/(2*a) in (1, [if root == 0 then 0 else root])\n _ -> let roots = map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d] \n in (2, sort roots)\n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> fromIntegral $ (read x::Int)) . take 3 . words\n print n\n mapM_ (printf \"%.15f\\n\") roots"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\n-- import Test.Tasty\n-- import Test.Tasty.HUnit\n-- import Debug.Trace\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | d < 0 -> (0, []) \n _ | d ==0 -> (1, [(-b)/ (2*a)])\n _ -> (2, sort $ map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]) \n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> read x::Double) . take 3 . words\n print n\n mapM_ (printf \"%.8f\\n\") roots"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | abs a < 1e-308 -> if abs b > 1e-308 then (1,[-c/b]) else (-1,[]) \n _ | d < 0 -> (0, []) \n _ | d == 0 -> let root = (-b)/(2*a) in (1, [if root == 0 then 0 else root])\n _ -> let roots = map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d] \n in (2, sort roots)\n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> fromIntegral $ (read x::Int)) . take 3 . words\n print n\n mapM_ (printf \"%.15f\\n\") roots"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Text.Printf (printf)\n\nsolve :: [Integer] -> Maybe [Double]\nsolve [0, 0, 0] = Nothing\nsolve [0, 0, _] = Just []\nsolve [0, b, c] = Just [(-1) * fromIntegral c / fromIntegral b]\nsolve [a, b, c]\n | d < 0 = Just []\n | d > 0 = Just [(-b' - sqrt d') / (2 * a'), (-b' + sqrt d') / (2 * a')]\n | otherwise = Just [(-b') / (2 * a')]\n where\n d = b^2 - 4*a*c\n [a', b', c', d'] = map fromIntegral [a, b, c, d]\n\nprints :: Maybe [Double] -> IO ()\nprints Nothing = print (-1)\nprints (Just []) = print 0\nprints (Just [x]) = printf \"1\\n%.6f\\n\" x\nprints (Just [x,y]) = printf \"2\\n%.6f\\n%.6f\\n\" x y\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Text.Printf (printf)\n\nsolve :: [Int] -> Maybe [Double]\nsolve [0, 0, 0] = Nothing\nsolve [0, 0, _] = Just []\nsolve [0, b, c] = Just [(-1) * fromIntegral c / fromIntegral b]\nsolve [a, b, c]\n | d < 0 = Just []\n | d > 0 = Just [(-b' - sqrt d') / (2 * a'), (-b' + sqrt d') / (2 * a')]\n | otherwise = Just [(-b') / (2 * a')]\n where\n d = b^2 - 4*a*c\n [a', b', c', d'] = map fromIntegral [a, b, c, d]\n\nprints :: Maybe [Double] -> IO ()\nprints Nothing = print (-1)\nprints (Just []) = print 0\nprints (Just [x]) = printf \"1\\n%.6f\\n\" x\nprints (Just [x,y]) = printf \"2\\n%.6f\\n%.6f\\n\" x y\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve\n"}, {"source_code": "import Data.List\nimport Text.Printf\n\nmain :: IO()\nmain = do\n\tt <- getLine\n\tputStr $ getAnswer $ map (\\x -> read x :: Double) (words t)\n\nparseFloat :: Double -> String\nparseFloat = printf \"%.5f\"\n\nconcatStr :: [String] -> String\nconcatStr = foldr (++) []\n\ngetAnswer :: [Double] -> String\ngetAnswer xs \n\t| lengthSol == 3\t= \"-1\"\n\t| lengthSol == 0\t= \"0\"\n\t| otherwise\t= addNrOfSol ++ (concatStr $ map (++ \"\\n\") $ map parseFloat $ solutions)\n\t\twhere \n\t\t\tlengthSol = length solutions\n\t\t\tsolutions = sort $ f xs\n\t\t\taddNrOfSol = (show $ lengthSol) ++ \"\\n\"\n\nf (a : b : c : xs)\n\t| a == 0 && b == 0 && c == 0\t= [0, 0, 0]\n\t| a == 0 && b == 0 && c /= 0\t= []\n\t| a == 0 && b /= 0\t\t= [-c / b]\n\t| otherwise\t\t\t= solve a b c\n\t\twhere \n\t\t\tsolve a b c \n\t\t\t\t| delta < 0\t= []\n\t\t\t\t| delta == 0\t= [ -b / 2 * a ]\n\t\t\t\t| delta > 0\t= ( -b + sqrt (delta) ) / (2 * a) : [( -b - sqrt (delta) ) / (2 * a)]\n\t\t\t\t\twhere delta = b * b - 4 * a * c"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\n-- import Test.Tasty\n-- import Test.Tasty.HUnit\n-- import Debug.Trace\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | a < 1e-20 -> (-1,[]) \n _ | d < 0 -> (0, []) \n _ | d ==0 -> (1, [(-b)/ (2*a)])\n _ -> let roots = map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d] \n in (2, sort roots)\n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> read x::Double) . take 3 . words\n print n\n mapM_ (printf \"%.8f\\n\") roots"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Control.Monad\n-- import Test.Tasty\n-- import Test.Tasty.HUnit\n-- import Debug.Trace\nimport Data.List\n\n\nrun :: [Double] -> (Int, [Double])\nrun [a,b,c] = \n let d = b^2 - 4*a*c \n in case d of \n _ | a < 1e-308 -> (-1,[]) \n _ | d < 0 -> (0, []) \n _ | d ==0 -> (1, [(-b)/ (2*a)])\n _ -> let roots = map (\\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d] \n in (2, sort roots)\n \n\nmain = do\n (n, roots) <- getLine >>= return . run . map (\\x -> read x::Double) . take 3 . words\n print n\n mapM_ (printf \"%.8f\\n\") roots"}], "src_uid": "84372885f2263004b74ae753a2f358ac"} {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 #-}\n{-# LANGUAGE UnicodeSyntax, MagicHash #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Int\nimport Text.Printf\nimport GHC.Prim\n\ndata Item = Item { itemSum :: !Int64, itemLeftMax :: !Int64, itemRightMax :: !Int64, itemMax :: !Int64 }\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild list = tree \n\twhere\n\t\tn = length list\n\t\ttree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list\n\t\tvalue i = tree ! (2*i) <> tree ! (2*i + 1)\n\nquery tree l r = query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\n\t\tquery' l r\n\t\t\t| l > r = mempty\n\t\t\t| odd l = (tree ! l) <> query' (l + 1) r\n\t\t\t| even r = query' l (r - 1) <> (tree ! r)\n\t\t\t| otherwise = query' (l `div` 2) (r `div` 2)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t[n, m, c] \u2190 getInts\n\t[xs, ps] \u2190 replicateM 2 $ map fromIntegral <$> getInts\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)\n\tlet tree = build $ map (\\a \u2192 let b = max 0 a in Item a b b b) as\n\n\tranges \u2190 replicateM m $ (\\[l, r] \u2192 (l - 1, r - 2)) <$> getInts\n\tlet maxs = map (itemMax . uncurry (query tree)) ranges\n\tprintf \"%f\" $ (fromIntegral $ sum maxs) / (100 :: Double)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Int\nimport Text.Printf\n\ndata Item = Item { itemSum :: Int64, itemLeft :: Int64, itemRight :: Int64, itemMax :: Int64 } deriving (Show)\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild l = a\n\twhere\n\t\tn = length l\n\t\ta = listArray (1, 2*n - 1) $ map f [1..n-1] ++ map g l\n\t\tf i = (a ! (2*i)) <> (a ! (2*i + 1))\n\t\tg a = Item a b b b\n\t\t\twhere b = max 0 a\n\nquery tree l r = itemMax $ query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\t\tquery' l r | l > r = mempty\n\t\tquery' l r | odd l = (tree ! l) <> query' (l + 1) r\n\t\tquery' l r | even r = query' l (r - 1) <> (tree ! r)\n\t\tquery' l r = query' (l `div` 2) (r `div` 2)\n\n{- getWords = map read . words <$> getLine -}\n\ntoInt :: B.ByteString -> Int\ntoInt = fst . fromJust . C.readInt\n\ntoInt64 :: B.ByteString -> Int64\ntoInt64 s = fromIntegral $ toInt s\n\nmain = do\n\t[n, m, c] <- map toInt . B.split 32 <$> B.getLine \n\t[xs, ps] <- replicateM 2 $ map toInt64 . B.split 32 <$> B.getLine\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)\n\tlet tree = build as\n\tranges <- replicateM m $ (\\[l, r] -> (l - 1, r - 2)) . map toInt . B.split 32 <$> B.getLine\n\tlet rs = map (\\(l, r) -> query tree l r) ranges\n\tprintf \"%f\" $ (fromIntegral (sum rs) :: Double) / 100\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Int\nimport Text.Printf\n\ndata Item = Item { itemSum :: Int64, itemLeftMax :: Int64, itemRightMax :: Int64, itemMax :: Int64 } deriving (Show)\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild list = tree \n\twhere\n\t\tn = length list\n\t\ttree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list\n\t\tvalue i = tree ! (2*i) <> tree ! (2*i + 1)\n\nquery tree l r = query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\n\t\tquery' l r\n\t\t\t| l > r = mempty\n\t\t\t| odd l = (tree ! l) <> query' (l + 1) r\n\t\t\t| even r = query' l (r - 1) <> (tree ! r)\n\t\t\t| otherwise = query' (l `div` 2) (r `div` 2)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t[n, m, c] <- getInts\n\t[xs, ps] <- replicateM 2 $ map fromIntegral <$> getInts\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)\n\tlet tree = build $ map (\\a -> let b = max 0 a in Item a b b b) as\n\n\tranges <- replicateM m $ (\\[l, r] -> (l - 1, r - 2)) <$> getInts\n\tlet maxs = map (itemMax . uncurry (query tree)) ranges\n\tprintf \"%f\" $ (fromIntegral $ sum maxs) / (100 :: Double)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 #-}\n{-# LANGUAGE UnicodeSyntax, MagicHash #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Int\nimport Text.Printf\n \ndata Item = Item { itemSum :: {-# UNPACK #-} !Int64, itemLeftMax :: {-# UNPACK #-} !Int64, itemRightMax :: {-# UNPACK #-} !Int64, itemMax :: {-# UNPACK #-} !Int64 }\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild list = tree \n\twhere\n\t\tn = length list\n\t\ttree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list\n\t\tvalue i = tree ! (2*i) <> tree ! (2*i + 1)\n\nquery tree l r = query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\n\t\tquery' l r\n\t\t\t| l > r = mempty\n\t\t\t| odd l = (tree ! l) <> query' (l + 1) r\n\t\t\t| even r = query' l (r - 1) <> (tree ! r)\n\t\t\t| otherwise = query' (l `div` 2) (r `div` 2)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t[n, m, c] \u2190 getInts\n\t[xs, ps] \u2190 replicateM 2 $ map fromIntegral <$> getInts\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)\n\tlet tree = build $ map (\\a \u2192 let b = max 0 a in Item a b b b) as\n\n\tranges \u2190 replicateM m $ (\\[l, r] \u2192 (l - 1, r - 2)) <$> getInts\n\tlet maxs = map (itemMax . uncurry (query tree)) ranges\n\tprintf \"%f\" $ (fromIntegral $ sum maxs) / (100 :: Double)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}\n{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Int\nimport Text.Printf\n\ndata Item = Item { itemSum :: !Int64, itemLeftMax :: !Int64, itemRightMax :: !Int64, itemMax :: !Int64 }\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild list = tree \n\twhere\n\t\tn = length list\n\t\ttree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list\n\t\tvalue i = tree ! (2*i) <> tree ! (2*i + 1)\n\nquery tree l r = query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\n\t\tquery' l r\n\t\t\t| l > r = mempty\n\t\t\t| odd l = (tree ! l) <> query' (l + 1) r\n\t\t\t| even r = query' l (r - 1) <> (tree ! r)\n\t\t\t| otherwise = query' (l `div` 2) (r `div` 2)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t[n, m, c] \u2190 getInts\n\t[xs, ps] \u2190 replicateM 2 $ map fromIntegral <$> getInts\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)\n\tlet tree = build $ map (\\a \u2192 let b = max 0 a in Item a b b b) as\n\n\tranges \u2190 replicateM m $ (\\[l, r] \u2192 (l - 1, r - 2)) <$> getInts\n\tlet maxs = map (itemMax . uncurry (query tree)) ranges\n\tprintf \"%f\" $ (fromIntegral $ sum maxs) / (100 :: Double)\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Monoid\n\ndata Item = Item { itemSum :: Int, itemLeft :: Int, itemRight :: Int, itemMax :: Int } deriving (Show)\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild l = a\n\twhere\n\t\tn = length l\n\t\ta = listArray (1, 2*n - 1) $ map f [1..n-1] ++ map g l\n\t\tf i = (a ! (2*i)) <> (a ! (2*i + 1))\n\t\tg a = Item a b b b\n\t\t\twhere b = max 0 a\n\nquery tree l r = itemMax $ query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\t\tquery' l r | l > r = mempty\n\t\tquery' l r | odd l = (tree ! l) <> query' (l + 1) r\n\t\tquery' l r | even r = query' l (r - 1) <> (tree ! r)\n\t\tquery' l r = query' (l `div` 2) (r `div` 2)\n\ngetWords = map read . words <$> getLine \n\nmain = do\n\t[n, m, c] <- getWords\n\txs <- getWords\n\tps <- getWords\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (*c) ps)\n\tlet tree = build as\n\tranges <- replicateM m $ (\\[l, r] -> (l - 1, r - 2)) . map read . words <$> getLine\n\tlet rs = map (\\(l, r) -> query tree l r) ranges\n\tprint $ fromIntegral (sum rs) / 100\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Monoid\nimport Text.Printf\n\ndata Item = Item { itemSum :: Int, itemLeft :: Int, itemRight :: Int, itemMax :: Int } deriving (Show)\n\ninstance Monoid Item where\n\tmempty = Item 0 0 0 0\n\tmappend (Item as al ar am) (Item bs bl br bm) =\n\t\tItem (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)\n\nbuild l = a\n\twhere\n\t\tn = length l\n\t\ta = listArray (1, 2*n - 1) $ map f [1..n-1] ++ map g l\n\t\tf i = (a ! (2*i)) <> (a ! (2*i + 1))\n\t\tg a = Item a b b b\n\t\t\twhere b = max 0 a\n\nquery tree l r = itemMax $ query' (l + n) (r + n)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\t\tquery' l r | l > r = mempty\n\t\tquery' l r | odd l = (tree ! l) <> query' (l + 1) r\n\t\tquery' l r | even r = query' l (r - 1) <> (tree ! r)\n\t\tquery' l r = query' (l `div` 2) (r `div` 2)\n\ngetWords = map read . words <$> getLine \n\nmain = do\n\t[n, m, c] <- getWords\n\txs <- getWords\n\tps <- getWords\n\tlet as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (*c) ps)\n\tlet tree = build as\n\tranges <- replicateM m $ (\\[l, r] -> (l - 1, r - 2)) . map read . words <$> getLine\n\tlet rs = map (\\(l, r) -> query tree l r) ranges\n\tprintf \"%f\" $ (fromIntegral (sum rs) :: Double) / 100\n"}], "src_uid": "f7528716ef2cfdbcdc8bf8253fd4966b"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve = do\n [n, k, d1, d2] :: [Int64] <- map read . words <$> getLine\n\n let\n os = try <$> [-1, 1] <*> [-1, 1]\n where\n\n try s1 s2\n | all (\\x -> x`mod`3 == 0 && x >= 0 && x <= n) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)\n | otherwise = Nothing\n where\n x1 = k - s1*d2 - s2*2*d1\n x2 = k - s1*d2 + s2*d1\n x3 = k + s1*2*d2 + s2*d1\n\n putStrLn $\n if n`mod`3 == 0 && not (null $ catMaybes os)\n then \"yes\"\n else \"no\"\n\nmain = do\n t <- readLn\n replicateM t solve\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\n\nsolveEach as@[a, b, c] rest\n | need > rest = False\n | remain `mod` 3 == 0 = True\n | otherwise = False\n where mx = maximum as\n need = sum . map (\\x -> mx - x) $ as\n remain = rest - need\n\nsolve [] _ = False\nsolve (a:as) rest\n | res1 == True = True\n | otherwise = solve as rest\n where res1 = solveEach a rest\n\nmain = do\n testcase <- getint\n replicateM testcase $ do\n [n, k, d1, d2] <- map fst . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n let rest = n - k\n as = filter filt [f x y | x <- [(0, d1), (d1, 0)], y <- [(0, d2), (d2, 0)]]\n f (d1, 0) (d2, 0) = [d1 + d2, d2, 0]\n f (d1, 0) (0, d2) = [d1, 0, d2]\n f (0, d1) (d2, 0) = if d1 >= d2\n then [0, d1, d1 - d2]\n else [d2 - d1, d2, 0]\n f (0, d1) (0, d2) = [0, d1, d1 + d2]\n filt [a, b, c]\n | played > k = False\n | remain `mod` 3 == 0 = True\n | otherwise = False\n where played = a + b + c\n remain = k - played\n res = solve as rest\n-- putStrLn (show as)\n if res then putStrLn \"yes\" else putStrLn \"no\""}, {"source_code": "import Control.Monad\nans :: [Integer] -> String\nans [n, k, d1, d2] = if g then \"yes\" else \"no\"\n where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2), (d1,d1+d2), (d2,d1+d2)])\n good (a,b) = dd >= 0 && dd `mod` 3 == 0 && max (ee+a) (ee+b) <= n `div` 3\n where dd = k - a - b\n ee = dd `div` 3\n \nsolve :: IO String\nsolve = do\n s <- getLine\n return $ ans $ map read $ words s\n\nmain = do\n l1 <- getLine\n let nn = (read l1) :: Int\n replicateM nn solve >>= putStrLn . unlines"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf (printf)\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [Integer] -> Bool\nsolve [!n, !k, !d1, !d2] =\n n `rem` 3 == 0 && or [check a1 a2 | a1 <- [d1, -d1], a2 <- [d2, -d2]]\n where\n check !a1 !a2 = m `rem` 3 == 0 && x >= 0 && y >= 0 && z >= 0 && x + y + z == k && n - k >= r\n where\n m = k - 2*a1 - a2\n x = m `div` 3\n y = x + a1\n z = y + a2\n w = x `max` y `max` z\n r = w - x + w - y + w - z\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n ts <- replicateM t $ (map (fst . fromJust . BS.readInteger) . BS.words) <$> BS.getLine :: IO [[Integer]]\n forM_ ts $ \\t ->\n putStrLn $ if solve t then \"yes\" else \"no\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInteger.B.words <$> B.getContents\n putStr.unlines $ solve xs\n\nsolve :: [Integer] -> [String]\nsolve (n:k:d1:d2:rest)\n | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = \"yes\" : solve rest\n | otherwise = \"no\" : solve rest\n where\n ok (d1, d2) = and [ w1' >= 0, w2' >= 0, w3' >= 0\n , w1' `mod` 3 == 0, w2' `mod` 3 == 0, w3' `mod` 3 == 0\n , d + k <= n\n , (n - d - k) `mod` 3 == 0\n ]\n where\n w1' = k - 2*d1 - d2\n w2' = k + d1 - d2\n w3' = k + d1 + 2*d2\n w1 = w1' `div` 3\n w2 = w2' `div` 3\n w3 = w3' `div` 3\n d = 3 * maximum [w1,w2,w3] - sum [w1,w2,w3]\n \nsolve _ = []"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve = do\n [n, k, d1, d2] <- getInts\n\n let\n os = try <$> [-1, 1] <*> [-1, 1]\n where\n\n try s1 s2\n | all (\\x -> x`mod`3 == 0 && x >= 0 && x <= n) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)\n | otherwise = Nothing\n where\n x1 = k - s1*d2 - s2*2*d1\n x2 = k - s1*d2 + s2*d1\n x3 = k + s1*2*d2 + s2*d1\n\n putStrLn $\n if n`mod`3 == 0 && not (null $ catMaybes os)\n then \"yes\"\n else \"no\"\n\nmain = do\n t <- readLn\n replicateM t solve\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve = do\n [n, k, d1, d2] <- getInts\n\n let\n os = try <$> [-1, 1] <*> [-1, 1]\n where\n try s1 s2\n | all (\\x -> x`mod`3 == 0 && x >= 0 && x <= n) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)\n | otherwise = Nothing\n where\n x1 = k - s1*2*d1 - s2*d2\n x2 = k + s1*d1 - s2*d2\n x3 = k + s1*d1 - s2*2*d2\n\n putStrLn $\n if n`mod`3 == 0 && not (null $ catMaybes os)\n then \"yes\"\n else \"no\"\n\nmain = do\n t <- readLn\n replicateM t solve\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve = do\n [n, k, d1, d2] <- getInts\n\n let\n os = try <$> [-1, 1] <*> [-1, 1]\n where\n\n try s1 s2\n | all (\\x -> x`mod`3 == 0 && x >= 0) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)\n | otherwise = Nothing\n where\n x1 = k - s1*d2 - s2*2*d1\n x2 = k - s1*d2 + s2*d1\n x3 = k + s1*2*d2 + s2*d1\n\n putStrLn $\n if n`mod`3 == 0 && not (null $ catMaybes os)\n then \"yes\"\n else \"no\"\n\nmain = do\n t <- readLn\n replicateM t solve\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map (fromIntegral.readInt).B.words <$> B.getContents\n putStr.unlines $ solve xs\n\nsolve :: [Int64] -> [String]\nsolve (n:k:d1:d2:rest)\n | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = \"yes\" : solve rest\n | otherwise = \"no\" : solve rest\n where\n ok (d1, d2) = and [w1>=0, w2>=0, w3>=0\n , w1' `mod` 3==0, w3' `mod` 3 == 0\n , d + k <= n\n , (n-(d+k)) `mod` 3 == 0\n ]\n where\n w1' = k - 2*d1 - d2\n w3' = k + d1 + 2*d2\n w1 = w1' `div` 3\n w3 = w3' `div` 3\n w2 = k - w1 - w3\n d = sum $ map (wmax-)[w1,w2,w3]\n wmax = maximum [w1,w2,w3]\n \nsolve _ = []"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map (fromIntegral.readInt).B.words <$> B.getContents\n putStr.unlines $ solve xs\n\nsolve :: [Int64] -> [String]\nsolve (n:k:d1:d2:rest)\n | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = \"yes\" : solve rest\n | otherwise = \"no\" : solve rest\n where\n ok (d1, d2) = and [ w1' >= 0, w2' >= 0, w3' >= 0\n , w1' `mod` 3 == 0, w2' `mod` 3 == 0, w3' `mod` 3 == 0\n , d + k <= n\n , (n - d - k) `mod` 3 == 0\n ]\n where\n w1' = k - 2*d1 - d2\n w2' = k + d1 - d2\n w3' = k + d1 + 2*d2\n w1 = w1' `div` 3\n w2 = w2' `div` 3\n w3 = w3' `div` 3\n d = 3 * maximum [w1,w2,w3] - sum [w1,w2,w3]\n \nsolve _ = []"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map (fromIntegral.readInt).B.words <$> B.getContents\n putStr.unlines $ solve xs\n\nsolve :: [Int64] -> [String]\nsolve (n:k:d1:d2:rest)\n | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = \"yes\" : solve rest\n | otherwise = \"no\" : solve rest\n where\n ok (d1, d2) = and [w1'>=0, w3'>=0\n , w1' `mod` 3 == 0, w3' `mod` 3 == 0\n , w2>=0\n , d + k <= n\n , (n-(d+k)) `mod` 3 == 0\n ]\n where\n w1' = k - 2*d1 - d2\n w3' = k + d1 + 2*d2\n w1 = w1' `div` 3\n w3 = w3' `div` 3\n w2 = k - w1 - w3\n d = sum $ map (wmax-)[w1,w2,w3]\n wmax = maximum [w1,w2,w3]\n \nsolve _ = []"}, {"source_code": "import Control.Monad\nans :: [Integer] -> String\nans [n, k, d1, d2] = if g then \"yes\" else \"no\"\n where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2)])\n good (a,b) = dd >= 0 && dd `mod` 3 == 0 && max (ee+a) (ee+b) <= n `div` 3\n where dd = k - a - b\n ee = dd `div` 3\n \nsolve :: IO String\nsolve = do\n s <- getLine\n return $ ans $ map read $ words s\n\nmain = do\n l1 <- getLine\n let nn = (read l1) :: Int\n replicateM nn solve >>= putStrLn . unlines"}, {"source_code": "import Control.Monad\nans [n, k, d1, d2] = if g then \"yes\" else \"no\"\n where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2)])\n good (a,b) = a + b <= k && max a b <= n `div` 3\n\nsolve :: IO String\nsolve = do\n s <- getLine\n return $ ans $ map read $ words s\n\nmain = do\n l1 <- getLine\n let nn = (read l1) :: Int\n replicateM nn solve >>= putStrLn . unlines"}, {"source_code": "import Control.Monad\nans :: [Integer] -> String\nans [n, k, d1, d2] = if g then \"yes\" else \"no\"\n where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2)])\n good (a,b) = a + b <= k && max a b <= n `div` 3\n\nsolve :: IO String\nsolve = do\n s <- getLine\n return $ ans $ map read $ words s\n\nmain = do\n l1 <- getLine\n let nn = (read l1) :: Int\n replicateM nn solve >>= putStrLn . unlines"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf (printf)\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [Integer] -> Bool\nsolve [!n, !k, !d1, !d2] =\n n `rem` 3 == 0 &&\n (check d1 d2 || check (2 * d1) d2 || check d1 (2 * d2))\n where\n !r = n - k\n check !a !b = r >= a + b && n >= (max a b) * 3\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n ts <- replicateM t $ (map (fst . fromJust . BS.readInteger) . BS.words) <$> BS.getLine :: IO [[Integer]]\n forM_ ts $ \\t ->\n putStrLn $ if solve t then \"yes\" else \"no\"\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf (printf)\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [Integer] -> Bool\nsolve [!n, !k, !d1, !d2] =\n check (k + 2*d1 + d2) ||\n check (k + 2*d1 - d2) ||\n check (k - 2*d1 - d2) ||\n check (k - 2*d1 + d2)\n where\n check !m = m >= 0 && m <= n && m `rem` 3 == 0 && (n - m) `rem` 3 == 0\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n ts <- replicateM t $ (map (fst . fromJust . BS.readInteger) . BS.words) <$> BS.getLine :: IO [[Integer]]\n forM_ ts $ \\t ->\n putStrLn $ if solve t then \"yes\" else \"no\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\n\nsolveEach as@[a, b, c] rest\n | need > rest = False\n | remain `mod` 3 == 0 = True\n | otherwise = False\n where mx = maximum as\n need = sum . map (\\x -> mx - x) $ as\n remain = rest - need\n\nsolve [] _ = False\nsolve (a:as) rest\n | res1 == True = True\n | otherwise = solve as rest\n where res1 = solveEach a rest\n\nmain = do\n testcase <- getint\n replicateM testcase $ do\n [n, k, d1, d2] <- map fst . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n let rest = n - k\n as = [f x y | x <- [(0, d1), (d1, 0)], y <- [(0, d2), (d2, 0)]]\n f (d1, 0) (d2, 0) = [d1 + d2, d2, 0]\n f (d1, 0) (0, d2) = [d1, 0, d2]\n f (0, d1) (d2, 0) = if d1 >= d2\n then [0, d1, d1 - (d1 - d2)]\n else [d2 - (d2 - d1), d2, 0]\n f (0, d1) (0, d2) = [0, d1, d1 + d2]\n res = solve as rest\n if res then putStrLn \"yes\" else putStrLn \"no\""}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\n\nsolveEach as@[a, b, c] rest\n | need > rest = False\n | remain `mod` 3 == 0 = True\n | otherwise = False\n where mx = maximum as\n need = sum . map (\\x -> mx - x) $ as\n remain = rest - need\n\nsolve [] _ = False\nsolve (a:as) rest\n | res1 == True = True\n | otherwise = solve as rest\n where res1 = solveEach a rest\n\nmain = do\n testcase <- getint\n replicateM testcase $ do\n [n, k, d1, d2] <- map fst . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n let rest = n - k\n as = filter filt [f x y | x <- [(0, d1), (d1, 0)], y <- [(0, d2), (d2, 0)]]\n f (d1, 0) (d2, 0) = [d1 + d2, d2, 0]\n f (d1, 0) (0, d2) = [d1, 0, d2]\n f (0, d1) (d2, 0) = if d1 >= d2\n then [0, d1, d1 - d2]\n else [d2 - d1, d2, 0]\n f (0, d1) (0, d2) = [0, d1, d1 + d2]\n filt [a, b, c] = a + b + c <= k\n res = solve as rest\n-- putStrLn (show as)\n if res then putStrLn \"yes\" else putStrLn \"no\""}], "src_uid": "324298100f3e36d289ef6ca8178ac6d3"} {"source_code": "main = do\n input <- getContents\n let process = putStrLn . show . maxFrames\n mapM_ process $ cases $ lines input\n\ncases :: [String] -> [[Int]]\ncases [] = []\ncases (_:x:xs) = list:cases xs\n where\n list = (map read $ words x)::[Int]\n\nmaxFrames :: [Int] -> Int\nmaxFrames list = (maxFrames' list) `div` 2\n\nmaxFrames' :: [Int] -> Int\nmaxFrames' [] = 0\nmaxFrames' list@(x:_) = ((counter `div` 2) + maxFrames' rest)\n where\n (counter, rest) = countAndClean x list 0\n\ncountAndClean :: Int -> [Int] -> Int -> (Int, [Int])\ncountAndClean _ [] counter = (counter, [])\ncountAndClean x (y:ys) counter\n | x == y = countAndClean x ys (counter+1)\n | otherwise = (newCounter, y:list)\n where\n (newCounter, list) = countAndClean x ys counter\n", "positive_code": [{"source_code": "import Data.List\nimport IO\n\nsolve :: [Int] -> Int\nsolve = (`div`2) . sum . map ((`div`2) . length) . group . sort\n\nmain = print . solve . map read . words . head . tail . lines =<< hGetContents stdin\n\n-- vim: set expandtab:\n"}, {"source_code": "import qualified Data.Map as Map\nsolve :: [Int] -> Int\nsolve xs = halfsticks `div` 2\n where sticks = foldr step Map.empty xs\n where step x acc = Map.insertWith (+) x 1 acc\n halfsticks = foldl (\\acc x -> acc + x `div` 2) 0 (map snd (Map.toList sticks))\n\nmain = interact $ show . solve . map read . words . last . lines "}, {"source_code": "import Data.List\n\nmain = do\n\tgetLine\n\txs <- fmap (map read . words) getContents :: IO [Int]\n\tprint $ (sum $ map ((`div` 2) . length) $ group $ sort xs) `div` 2\n\n"}, {"source_code": "import Data.List\n\nmain = do\n\tgetLine\n\ta <- fmap (map (read::String->Int) . words) getLine \n\tprint $ (flip div 2) .sum . map ((flip div 2).length) . group . sort $ a\n"}, {"source_code": "import Data.List\n\nmain = do\n\tn <- fmap (fromInteger.read) getLine\n\ta <- fmap ((map (fromInteger.read)) . words) getLine \n\tlet b = map length $ group . sort $ a\n\tlet c = sum $ map (flip div 2) b \t\n\tprint $ c `div` 2\n"}, {"source_code": "import Data.List\n\nmain = do\n\tn <- fmap (fromInteger.read) getLine\n\ta <- fmap (map (fromInteger.read) . words) getLine \n\tlet b = map length . group . sort $ a\n\tlet c = sum $ map (flip div 2) b \t\n\tprint $ c `div` 2\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve a = let arr = [(length $ elemIndices i a) `div` 2 | i <- [1..100]]\n in sum arr `div` 2\n\nmain = do\n n <- getLine\n a <- map read <$> (words <$> getLine)\n print $ solve a\n"}, {"source_code": "module Main where\n\n -- Java-\u043a\u0440\u0435\u0441\u0442\u044c\u044f\u043d\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0441\u0442\u0440\u0430\u0434\u0430\u0442\u044c!\n \n import Data.List (sort, foldl', genericLength, group)\n \n main :: IO ()\n main = do\n n <- fmap read getLine :: IO Int\n sticks <- fmap (map read . words) getLine :: IO [Int]\n putStrLn . show $ flip div 2 $\n foldl' summate 0 (group . sort $ sticks)\n where summate s xs = s + (genericLength xs `div` 2)\n"}, {"source_code": "import List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> Int\nsolve xs = div (countPairs (sort xs)) 2\n where\n countPairs (x:y:xs)\n | x == y = 1 + countPairs xs\n | otherwise = countPairs (y:xs)\n countPairs _ = 0\n\nmain :: IO ()\nmain = do\n getLine >> Main.reads >>= print . solve\n"}, {"source_code": "import List\n\npairs :: [Int] -> Int\npairs xs = sum $ map (\\xs -> div (length xs) 2) $ group $ sort xs\nmain = interact $ show.(\\x -> x `div` 2).pairs.map read.tail.words"}, {"source_code": "import Data.List\nmain = do line <- getLine\n line <- getLine\n print $ ((\\x -> x `div` 2) . sum . (map (\\x -> (length x) `div` 2)) . group . sort . (map (\\x -> read x::Int)) . words) line"}, {"source_code": "import Data.List\nmain = print . (`div` 2) . sum . map ((`div` 2) . length) . group . sort . map (read :: String -> Int) . tail . words =<< getContents"}, {"source_code": "\ufeffmodule Main where\n\nimport Data.List\n \nmain = do\n getLine\n cs <- (map read . words) `fmap` getLine\n print (answer cs)\n\nanswer :: [Int] -> Int\nanswer cs = (pr (sort cs)) `div` 2\n where\n pr (a:b:sp) | a == b = 1 + pr sp\n | True = pr (b:sp)\n pr _ = 0"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}\n\nimport Control.Applicative\nimport Data.List\n\nreadNums :: (Num a, Read a) => IO [a]\nreadNums = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs :: [Int] <- take n <$> readNums\n let ys = parse $ sort xs\n print $ length ys `quot` 2\n where\n parse (x : y : zs)\n | x == y = x : parse zs\n | otherwise = parse (y : zs)\n parse _ = []\n\n\n"}, {"source_code": "import System.IO\nimport Data.List\n\nparse :: Read a => Num a => String -> [a]\nparse stuff = \n map read $ words $ dropWhile (/= '\\n') stuff\n\n\n\ncalc :: [Int] -> Int\ncalc nums =\n let groups = (map length $ group $ sort nums :: [Int])\n edges = (map (\\x -> div x 2) groups)\n res = (sum edges) `div` 2\n in res\n\n\nmain = do\n stuff <- getContents\n putStrLn (show $ calc $ parse stuff)\n\n"}], "negative_code": [{"source_code": "import List\n\npairs :: [Int] -> Int\npairs xs = pairs' $ sort xs\n where pairs' (a:b:xs) | a == b = 1 + pairs' xs\n | otherwise = pairs' xs\n pairs' _ = 0\n\nmain = interact $ show.(\\x -> x `div` 2).pairs.map read.tail.words"}, {"source_code": "import Data.List\nmain = do line <- getLine\n line <- getLine\n print $ ((\\x -> x `div` 2) . sum . (map (\\x -> (length x) `div` 2)) . group . sort . concat . words) line"}], "src_uid": "f9b56b3fddcd5db0d0671714df3f8646"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess d = do\n\t\tlet e = sum $ map (\\z-> if z >0 then z-1 else if z<0 then (-1-z) else 1) d\n\t\tlet e1 = if elem 0 d then 0\n\t\t\t \t\telse\n\t\t\t\t\t\tif even (length ( filter (<0) d)) then 0\n\t\t\t\t\t\t\t\t \t\t\telse 2\n\t\tprint $ e+e1 \n\nmain = do\t\n\t\tgetLine\n\t\td<-map read <$> words <$> getLine ::IO [Integer]\n\t\tprocess d\n\t\n\n", "positive_code": [{"source_code": "main = do\n n <- getLine\n a <- getLine\n print (solve (read n) (map read $ words a))\n\ncount :: [Integer] -> (Integer, Integer, Integer, Integer)\ncount [] = (0, 0, 0, 0)\ncount (x:xs)\n | x < 0 = (cn+1, c0, cp, cst + (-1 - x))\n | x == 0 = (cn, c0+1, cp, cst + 1)\n | x > 0 = (cn, c0, cp+1, cst + (x - 1))\n where (cn,c0,cp,cst) = count xs\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n a =\n let (cn, c0, cp, cst) = count a in\n if even cn\n then cst\n else if (c0 > 0)\n then cst\n else (cst + 2)"}, {"source_code": "import Control.Monad\nimport Data.String\nimport Data.Maybe\nreadListRec :: Int -> IO [String]\nreadListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n\nparseLineToInt :: String -> [Integer]\nparseLineToInt data_s = do\n (read::String->Integer) <$> (words data_s) \n\n\ncreateLists :: Int -> ([Int], [Int])\ncreateLists 0 = ([],[])\ncreateLists n = let\n (l, r) = createLists (n - 1)\n in ((2 * n) : r, (2 * n - 1) : l)\n\nmain = do\n _ <- getLine\n aS <- getLine\n let (a,b) = foldr f (0, Just 0) $ parseLineToInt aS where \n f x (y, Nothing) = (y + abs(1 - abs x),Nothing)\n f 0 (y, _) = (y + 1, Nothing)\n f x (y, Just z) = (y + abs(1 - abs x), Just (if x > 0 then z else (z + 1)))\n putStrLn $ show $ a + 2 * (mod (fromMaybe 0 b) 2)\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.String\nimport Data.Maybe\nreadListRec :: Int -> IO [String]\nreadListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n\nparseLineToInt :: String -> [Int]\nparseLineToInt data_s = do\n (read::String->Int) <$> (words data_s) \n\n\ncreateLists :: Int -> ([Int], [Int])\ncreateLists 0 = ([],[])\ncreateLists n = let\n (l, r) = createLists (n - 1)\n in ((2 * n) : r, (2 * n - 1) : l)\n\nmain = do\n _ <- getLine\n aS <- getLine\n let (a,b) = foldr f (0, Just 0) $ parseLineToInt aS where \n f x (y, Nothing) = (y + abs(1 - abs x),Nothing)\n f 0 (y, _) = (y + 1, Nothing)\n f x (y, Just z) = (y + abs(1 - abs x), Just (if x > 0 then z else (z + 1)))\n putStrLn $ show $ a + mod (fromMaybe 0 b) 2\n"}, {"source_code": "import Control.Monad\nimport Data.String\nimport Data.Maybe\nreadListRec :: Int -> IO [String]\nreadListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n\nparseLineToInt :: String -> [Int]\nparseLineToInt data_s = do\n (read::String->Int) <$> (words data_s) \n\n\ncreateLists :: Int -> ([Int], [Int])\ncreateLists 0 = ([],[])\ncreateLists n = let\n (l, r) = createLists (n - 1)\n in ((2 * n) : r, (2 * n - 1) : l)\n\nmain = do\n _ <- getLine\n aS <- getLine\n let (a,b) = foldr f (0, Just 0) $ parseLineToInt aS where \n f x (y, Nothing) = (y + abs(1 - abs x),Nothing)\n f 0 (y, _) = (y + 1, Nothing)\n f x (y, Just z) = (y + abs(1 - abs x), Just (if x > 0 then z else (z + 1)))\n putStrLn $ show $ a + 2 * (mod (fromMaybe 0 b) 2)\n"}, {"source_code": "main = do\n n <- getLine\n a <- getLine\n print (solve (read n) (map read $ words a))\n\ncount :: [Int] -> (Int, Int, Int, Int)\ncount [] = (0, 0, 0, 0)\ncount (x:xs)\n | x < 0 = (cn+1, c0, cp, cst + (-1 - x))\n | x == 0 = (cn, c0+1, cp, cst + 1)\n | x > 0 = (cn, c0, cp+1, cst + (x - 1))\n where (cn,c0,cp,cst) = count xs\n\nsolve :: Int -> [Int] -> Int\nsolve n a =\n let (cn, c0, cp, cst) = count a in\n if even cn\n then cst\n else if (c0 > 0)\n then cst\n else (cst + 2)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess d = do\n\t\tlet e = sum $ map (\\z-> if z >0 then z-1 else if z<0 then (-1-z) else 1) d\n\t\tlet e1 = if elem 0 d then 0\n\t\t\t \t\telse\n\t\t\t\t\t\tif even (length ( filter (<0) d)) then 0\n\t\t\t\t\t\t\t\t \t\t\telse 2\n\t\tprint $ e+e1 \n\nmain = do\t\n\t\tgetLine\n\t\td<-map read <$> words <$> getLine ::IO [Int]\n\t\tprocess d\n\t\n\n"}], "src_uid": "3b3b2408609082fa5c3a0d55bb65d29a"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\n--import Data.Semigroup\n\nimport Data.List\nimport Data.Int\n-- no Data.Bits needed\n\nclass Put t where\n putit :: BoundedPrim t\ninstance Put Int where\n putit = intDec\ninstance Put Char where\n putit = liftFixedToBounded char7\ninstance (Put x, Put y) => Put (x, y) where\n putit = putit >*< putit\n\nquerySum :: BoundedPrim (Int, Int)\n-- This is a stupid way to do things\nquerySum = let\n orp = ('o', ('r', ' '))\n andp = ('a', ('n', ('d', ' ')))\n in\n (\\(i, j) ->\n (((((((((orp, i), ' '), j), '\\n'), andp), i), ' '), j), '\\n')) >$< putit\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [n, k] <- getInts 2\n let queries = (1, 2) : (1, 3) : (2, 3) : map ((,) 1) [4 .. n]\n lift $ B.hPutBuilder stdout $ primMapListBounded querySum queries\n lift $ hFlush stdout\n s12 : s13 : s23 : s1ks <- liftPure $ replicateM n $ do\n ~[ov, av] <- getInts 2\n pure $ fromIntegral $ ov + av\n let\n s123 = div (s12 + s13 + s23) 2\n s123 :: Int64\n v1 = s123 - s23\n v2 = s123 - s13\n v3 = s123 - s12\n vs = v1 : v2 : v3 : map (subtract v1) s1ks\n lift $ putStr \"finish \"\n lift $ print $ sort vs !! (k - 1)\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\n\r\n\r\nsolve3 :: (Int,Int,Int) -> (Int,Int,Int)\r\nsolve3 (ab,bc,ca) = (a,b,c) where\r\n a_c=ab-bc\r\n a2 = ca+a_c\r\n a = a2`div`2\r\n b = ab-a\r\n c = ca-a \r\n\r\naskAll :: Int -> Bu.Builder\r\naskAll n = ask3 <> askRestOr <> askRestAnd where\r\n ask s i j = Bu.string7 (s ++ \" \" ++ show i ++ \" \" ++ show j ++ \"\\n\") <> flush\r\n ask3 = mconcat [ask s i j | i<-[1,2,3],j<-[i+1..3],s<-[\"or\",\"and\"]]\r\n askRestOr = mconcat [ask \"or\" 1 j | j<-[4..n]] \r\n askRestAnd = mconcat [ask \"and\" 1 j | j<-[4..n]] \r\n \r\ntell :: Int -> Bu.Builder\r\ntell x = Bu.string7 (\"finish \" ++ show x ++ \"\\n\") <> flush\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n ~[n,k] <- getIntegrals 2\r\n ~[aorb,aandb,aorc,aandc,borc,bandc] <- getIntegrals 6\r\n let (a,b,c) = solve3 ((aorb+aandb), (borc+bandc), (aorc+aandc))\r\n restOr <- getIntegrals (n-3)\r\n restAnd <- getIntegrals (n-3)\r\n let xs = a:b:c: zipWith (\\x y->x+y-a) restOr restAnd\r\n return $ askAll n <> tell (L.sort xs !! (k-1))\r\n \r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString \r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStrLn $ Bu.toLazyByteString $ evalState solve bytestrings\r\n \r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Functor.Identity\r\n--import Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\nimport Data.Array.ST.Safe\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits -- only for bucket sort\r\n\r\nclass Put t where\r\n putit :: BoundedPrim t\r\ninstance Put Int where\r\n putit = intDec\r\ninstance Put Char where\r\n putit = liftFixedToBounded char7\r\ninstance (Put x, Put y) => Put (x, y) where\r\n putit = putit >*< putit\r\n\r\nquerySum :: BoundedPrim (Int, Int)\r\n-- This is a stupid way to do things\r\nquerySum = let\r\n orp = ('o', ('r', ' '))\r\n andp = ('a', ('n', ('d', ' ')))\r\n in\r\n (\\(i, j) ->\r\n (((((((((orp, i), ' '), j), '\\n'), andp), i), ' '), j), '\\n')) >$< putit\r\n\r\nstableBucketSortOn3 :: (Int -> Int) -> (Int, Int) -> [Int] -> UArray Int Int\r\nstableBucketSortOn3 fun bnds li = runSTUArray $ do\r\n counts <- newArray bnds 0 :: ST s (STUArray s Int Int)\r\n forM_ li $ \\v -> do\r\n let bucket = fun v\r\n ct <- (+ 1) <$> readArray counts bucket\r\n writeArray counts bucket ct\r\n totSz <- (\\fun -> foldM fun 0 $ range bnds) $ \\prevTot bucket -> do\r\n cct <- readArray counts bucket\r\n prevTot + cct <$ writeArray counts bucket prevTot\r\n ansArr <- newArray_ (1, totSz) :: ST s (STUArray s Int Int)\r\n forM_ li $ \\v -> do\r\n let bucket = fun v\r\n ct <- (+ 1) <$> readArray counts bucket\r\n writeArray counts bucket ct\r\n writeArray ansArr ct v\r\n pure ansArr\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n let queries = (2, 3) : map ((,) 1) [2 .. n]\r\n lift $ P.putStr $ B.toLazyByteString $ primMapListBounded querySum queries\r\n lift $ hFlush stdout\r\n s23 : s1ks <- liftPure $ replicateM n $ do\r\n ~[ov, av] <- getInts 2\r\n pure $ fromIntegral $ ov + av\r\n let\r\n v1 = div (sum (take 2 s1ks) - s23) 2\r\n vs = v1 : map (subtract v1) s1ks\r\n mask = bit 15 - 1\r\n lvs = stableBucketSortOn3 (.&. mask) (0, mask) vs\r\n svs = stableBucketSortOn3 (`shiftR` 15) (0, mask) $ elems lvs\r\n lift $ putStr \"finish \" >> print (svs ! k)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\nliftPure :: Monad m => SP Identity t -> SP m t\r\nliftPure = mapStateT (pure . runIdentity)\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\n-- no Data.Bits needed\n\nclass Put t where\n putit :: BoundedPrim t\ninstance Put Int where\n putit = intDec\ninstance Put Char where\n putit = liftFixedToBounded char7\ninstance (Put x, Put y) => Put (x, y) where\n putit = putit >*< putit\n\nquerySum :: BoundedPrim (Int, Int)\nquerySum = let\n orp = ('o', ('r', ' '))\n andp = ('a', ('n', ('d', ' ')))\n in\n (\\(i, j) ->\n (((((((((orp, i), ' '), j), '\\n'), andp), i), ' '), j), '\\n')) >$< putit\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [n, k] <- getInts 2\n let queries = (1, 2) : (1, 3) : (2, 3) : map ((,) 1) [4 .. n]\n lift $ B.hPutBuilder stdout $ primMapListBounded querySum queries\n lift $ hFlush stdout\n s12 : s13 : s23 : s1ks <- liftPure $ replicateM n $ do\n ~[ov, av] <- getInts 2\n pure $ ov + av\n let\n s123 = div (s12 + s13 + s23) 2\n v1 = s123 - s23\n v2 = s123 - s13\n v3 = s123 - s12\n vs = v1 : v2 : v3 : map (subtract v1) s1ks\n lift $ putStr \"finish \"\n lift $ print $ sort vs !! (k - 1)\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n"}], "src_uid": "7fb8b73fa2948b360644d40b7035ce4a"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.Base\n\nmain = do\n _ <- getLine\n tape <- getLine\n let query [l,r] = run $ take(r-l+1) $ drop(l-1) tape\n interact $ unlines.map(show.query.map read.words).lines\n\ndata Dir = L | R deriving Eq\ndata M = M String Dir String String\n\ninstance Show M where\n show (M ns _ _ _) = unwords $ map (show.unsafeAt arr.fromEnum) ['0'..'9']\n where\n !arr = unsafeAccumArray (+) 0 (0,fromEnum '9') $ map(\\c->(fromEnum c,1)) ns :: UArray Int Int\n\nrun tape = go $ M [] R [] tape\ngo (M ns _ ('<':ls) ('<':rs)) = go $ M ns L ls ('<':rs)\ngo (M ns _ ('>':ls) ('<':rs)) = go $ M ns L ls ('>':rs)\ngo (M ns _ ls ('>':'>':rs)) = go $ M ns R ls ('>':rs)\ngo (M ns _ ls ('>':'<':rs)) = go $ M ns R ls ('<':rs)\ngo (M ns _ (l:ls) ('<':rs)) = go $ M ns L ls (l:'<':rs)\ngo (M ns _ ls ('>':rs)) = go $ M ns R ('>':ls) rs\ngo (M ns L (l:ls) ('0':rs)) = go $ M ('0':ns) L ls (l:rs)\ngo (M ns R ls ('0':rs)) = go $ M ('0':ns) R ls rs\ngo (M ns L (l:ls) (n:rs))|'0'<=n && n<='9' = go $ M (n:ns) L ls (l:pred n:rs)\ngo (M ns R ls (n:rs)) |'0'<=n && n<='9' = go $ M (n:ns) R (pred n:ls) rs\ngo (M ns L [] (n:_)) |'0'<=n && n<='9' = M (n:ns) L [] []\ngo m = m\n", "positive_code": [{"source_code": "main = interact $ unlines . (\\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines\n\nsolve seq [l, r] = step (replicate 10 0) '>' (\"\", drop (l-1) $ take r seq)\n\nstep ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)\nstep ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)\nstep ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)\nstep ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)\nstep ans _ (x, '>':c:y) = step ans '>' ('>':x, c:y)\nstep ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)\nstep ans _ (x, \">\") = ans\nstep ans _ ([], '<':y) = ans\nstep ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)\nstep ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)\nstep ans '>' (x, []) = ans\nstep ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)\nstep ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)\nstep ans '<' ([], c:y) = inc (read [c]) ans\n\ninc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans\n"}], "negative_code": [{"source_code": "main = interact $ unlines . (\\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines\n\nsolve seq [l, r] = step (replicate 10 0) '>' (\"\", drop (l-1) $ take r seq)\n\nstep ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)\nstep ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)\nstep ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)\nstep ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)\nstep ans _ (x, '>':c:y) = step ans '>' ('>':x, c:y)\nstep ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)\nstep ans _ (x, \">\") = ans\nstep ans _ (\"\", '<':y) = ans\nstep ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)\nstep ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)\nstep ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)\nstep ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)\nstep ans _ _ = ans\n\ninc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans\n"}, {"source_code": "main = interact $ unlines . (\\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines\n\nsolve seq [l, r] = step (replicate 10 0) '>' (\"\", drop (l-1) $ take r seq)\n\nstep ans _ (_, []) = ans\nstep ans '<' ([], _) = ans\nstep ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)\nstep ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)\nstep ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)\nstep ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)\nstep ans _ (x, '>':y) = step ans '>' ('>':x, y)\nstep ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)\nstep ans _ (x, '<':y) = ans\nstep ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)\nstep ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)\nstep ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)\nstep ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)\n\ninc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans\n"}, {"source_code": "main = interact $ unlines . (\\(_:s:qs) -> map (unwords . map show . solve s . map read . words) qs) . lines\n\nsolve seq [l, r] = step (replicate 10 0) '>' (\"\", drop (l-1) $ take r seq)\n\nstep ans _ (x, '>':'>':y) = step ans '>' (x, '>':y)\nstep ans _ (x, '>':'<':y) = step ans '<' (x, '<':y)\nstep ans _ ('>':x, '<':y) = step ans '>' (x, '>':y)\nstep ans _ ('<':x, '<':y) = step ans '<' (x, '<':y)\nstep ans _ (x, '>':y) = step ans '>' ('>':x, y)\nstep ans _ (c:x, '<':y) = step ans '<' (x, c:'<':y)\nstep ans _ ([], '<':y) = ans\nstep ans '>' (x, '0':y) = step (inc 0 ans) '>' (x, y)\nstep ans '>' (x, c:y) = step (inc (read [c]) ans) '>' (pred c:x, y)\nstep ans '<' (c:x, '0':y) = step (inc 0 ans) '<' (x, c:y)\nstep ans '<' (d:x, c:y) = step (inc (read [c]) ans) '<' (x, d:pred c:y)\nstep ans _ _ = ans\n\ninc i ans = take i ans ++ (ans!!i + 1) : drop (i+1) ans\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.Base\n\nmain = do\n _ <- getLine\n tape <- getLine\n let query [l,r] = run $ take(r-l+1) $ drop(l-1) tape\n interact $ unlines.map(show.query.map read.words).lines\n\ndata Dir = L | R deriving Eq\ndata M = M String Dir String String\n\ninstance Show M where\n show (M ns _ _ _) = unwords $ map (show.unsafeAt arr.fromEnum) ['0'..'9']\n where\n !arr = unsafeAccumArray (+) 0 (0,fromEnum '9') $ map(\\c->(fromEnum c,1)) ns :: UArray Int Int\n\nrun tape = go $ M [] R [] tape\ngo (M ns _ ('<':ls) ('<':rs)) = go $ M ns L ls ('<':rs)\ngo (M ns _ ('>':ls) ('<':rs)) = go $ M ns L ls ('>':rs)\ngo (M ns _ ls ('>':'>':rs)) = go $ M ns R ls ('>':rs)\ngo (M ns _ ls ('>':'<':rs)) = go $ M ns R ls ('<':rs)\ngo (M ns _ (l:ls) ('<':rs)) = go $ M ns L ls (l:'<':rs)\ngo (M ns _ ls ('>':rs)) = go $ M ns R ('>':ls) rs\ngo (M ns L (l:ls) ('0':rs)) = go $ M ('0':ns) L ls (l:rs)\ngo (M ns R ls ('0':rs)) = go $ M ('0':ns) R ls rs\ngo (M ns L (l:ls) (n:rs)) = go $ M (n:ns) L ls (l:pred n:rs)\ngo (M ns R ls (n:rs)) = go $ M (n:ns) R (pred n:ls) rs\ngo (M ns L [] (n:_)) = M (n:ns) L [] []\ngo m = m\n"}], "src_uid": "5c3fc40b18c9b3e58c49d9f6e44ea28c"} {"source_code": "solve :: [String] -> [String]\nsolve ws = [(show $ length result), result]\n where result = concatAll $ rearange $ findPairs ws\n\nrearange :: [(String, String)] -> [(String, String)]\nrearange pairs\n | null singles = withoutSingles\n | otherwise = withoutSingles ++ [(head singles)]\n where singles = filter (\\(x, y) -> y == \"\") pairs\n withoutSingles = filter (\\(x, y) -> y /= \"\") pairs\n\nisReversed :: String -> String -> Bool\nisReversed a b = a == reverse b\n\nisPalindrome :: String -> Bool\nisPalindrome w = w == reverse w\n\nfindPairs :: [String] -> [(String, String)]\nfindPairs [] = []\nfindPairs [a] = if isPalindrome a then [(a, \"\")] else []\nfindPairs (w:ws)\n | null pairs = if isPalindrome w then [(w, \"\")] ++ findPairs ws else findPairs ws\n | otherwise = [(w, head pairs)] ++ findPairs ws\n where pairs = (filter (\\x -> isReversed w x) ws)\n\nconcatAll :: [(String, String)] -> String\nconcatAll [] = \"\"\nconcatAll [(a, b)] = a++b\nconcatAll ((a, b):xs) = a ++ (concatAll xs) ++ b\n\nmain :: IO ()\nmain = interact (unlines . solve . tail . lines)\n", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.Set as ST\n\ntype Info = (ST.Set String, String, String, String)\n\nsolve :: [String] -> IO ()\nsolve xss = do\n print (length left + length middle + length right)\n putStrLn (left ++ middle ++ right)\n where\n st = foldl (flip ST.insert) ST.empty xss\n (_,left,middle,right) = foldl step (st, [], [], []) xss\n step :: Info -> String -> Info\n step (st, ls, ms, rs) xs \n | xs == rev = (st, ls, xs, rs)\n | ST.member rev st = (st', ls++xs, ms, rev++rs)\n | otherwise = (st, ls, ms, rs)\n where\n rev = reverse xs\n st' = ST.delete rev $ (ST.delete xs st)\n\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n xss <- replicateM n $ do\n getLine >>= return\n solve xss\n"}], "negative_code": [], "src_uid": "554115bec46bb436a0a1ddf8c05a2d08"} {"source_code": "import Data.Map (Map)\nimport qualified Data.Map as Map\nimport Maybe\nmain = interact solve\nsolve input = output where\n ns = map (read::String->Int) $ words $ head $ lines input\n opt = map s2i $ drop 2 $ lines input\n output = unlines $ map i2s $ answer (num ns) opt\nsize = [\"S\",\"M\",\"L\",\"XL\",\"XXL\"]\ns2i x = fromJust $ lookup x $ zip size [1..5]\ni2s x = size!!(x-1)\nnum xs = Map.fromList $ zip [1..5] xs\npre = Map.fromList $ zip [1..5]\n [[1,2,3,4,5],[2,3,1,4,5],[3,4,2,5,1],[4,5,3,2,1],[5,4,3,2,1]]\nanswer :: Map Int Int -> [Int] -> [Int]\nanswer _ [] = []\nanswer xs (y:ys) = x : ( answer (Map.adjust (\\z->z-1) x xs) ys ) where\n x = choice xs (fromJust $ Map.lookup y pre)\nchoice :: Map Int Int -> [Int] -> Int\nchoice _ [] = 0\nchoice xs (y:ys) = if (fromJust $ Map.lookup y xs)==0 then choice xs ys else y\n", "positive_code": [{"source_code": "import Data.Map\nmain = interact (unlines.sol.words)\nsol (s:m:l:xl:xxl:n:xs) = sol' sz (take (read n) xs) [] where\n sz = fromList [(\"S\",read s),(\"M\",read m),(\"L\",read l),(\"XL\",read xl),(\"XXL\",read xxl)]\n sol' sz [] acc = reverse acc\n sol' sz (x:xs) acc = sol' (adjust pred k sz) xs (k:acc) where\n k = k' (ks!x) where k' (k:f) = if sz!k>0 then k else k' f\nks = fromList [(\"S\",[\"S\",\"M\",\"L\",\"XL\",\"XXL\"]),(\"M\",[\"M\",\"L\",\"S\",\"XL\",\"XXL\"]),(\"L\",[\"L\",\"XL\",\"M\",\"XXL\",\"S\"]),(\"XL\",[\"XL\",\"XXL\",\"L\",\"M\",\"S\"]),(\"XXL\",[\"XXL\",\"XL\",\"L\",\"M\",\"S\"])]\n"}, {"source_code": "\nsolve :: Int -> Int -> Int -> Int -> Int -> [String] -> [String]\nsolve _ _ _ _ _ [] = []\nsolve nS nM nL nXL nXXL (\"S\":xs)\n | nS > 0 = \"S\" : solve (nS-1) nM nL nXL nXXL xs\n | nM > 0 = \"M\" : solve nS (nM-1) nL nXL nXXL xs\n | nL > 0 = \"L\" : solve nS nM (nL-1) nXL nXXL xs\n | nXL > 0 = \"XL\" : solve nS nM nL (nXL-1) nXXL xs\n | nXXL > 0 = \"XXL\" : solve nS nM nL nXL (nXXL-1) xs\nsolve nS nM nL nXL nXXL (\"M\":xs)\n | nM > 0 = \"M\" : solve nS (nM-1) nL nXL nXXL xs\n | nL > 0 = \"L\" : solve nS nM (nL-1) nXL nXXL xs\n | nS > 0 = \"S\" : solve (nS-1) nM nL nXL nXXL xs\n | nXL > 0 = \"XL\" : solve nS nM nL (nXL-1) nXXL xs\n | nXXL > 0 = \"XXL\" : solve nS nM nL nXL (nXXL-1) xs\nsolve nS nM nL nXL nXXL (\"L\":xs)\n | nL > 0 = \"L\" : solve nS nM (nL-1) nXL nXXL xs\n | nXL > 0 = \"XL\" : solve nS nM nL (nXL-1) nXXL xs\n | nM > 0 = \"M\" : solve nS (nM-1) nL nXL nXXL xs\n | nXXL > 0 = \"XXL\" : solve nS nM nL nXL (nXXL-1) xs\n | nS > 0 = \"S\" : solve (nS-1) nM nL nXL nXXL xs\nsolve nS nM nL nXL nXXL (\"XL\":xs)\n | nXL > 0 = \"XL\" : solve nS nM nL (nXL-1) nXXL xs\n | nXXL > 0 = \"XXL\" : solve nS nM nL nXL (nXXL-1) xs\n | nL > 0 = \"L\" : solve nS nM (nL-1) nXL nXXL xs\n | nM > 0 = \"M\" : solve nS (nM-1) nL nXL nXXL xs\n | nS > 0 = \"S\" : solve (nS-1) nM nL nXL nXXL xs\nsolve nS nM nL nXL nXXL (\"XXL\":xs)\n | nXXL > 0 = \"XXL\" : solve nS nM nL nXL (nXXL-1) xs\n | nXL > 0 = \"XL\" : solve nS nM nL (nXL-1) nXXL xs\n | nL > 0 = \"L\" : solve nS nM (nL-1) nXL nXXL xs\n | nM > 0 = \"M\" : solve nS (nM-1) nL nXL nXXL xs\n | nS > 0 = \"S\" : solve (nS-1) nM nL nXL nXXL xs\n\nmain :: IO ()\nmain = do\n [nS, nM, nL, nXL, nXXL] <- getLine >>= return . map read . words\n n <- readLn\n xs <- getContents >>= return . take n . lines\n mapM_ putStrLn $ solve nS nM nL nXL nXXL xs\n"}], "negative_code": [], "src_uid": "3c9d1de13e21ed16a7e5cbd2d67f4ce7"} {"source_code": "import Data.Maybe\nq l|null l=Nothing|1>0=Just(head l,last l)\np=q.map fst.filter((=='W').snd).zip[0..]\n\nsr dir i []=(-1)\nsr dir i (Nothing:t)=1+sr (-dir) i t\nsr 1 i (Just(l,r):t)=1+2*b+f+sr (-1) j t where\n b|i>l=i-l\n |1>0=0\n (f,j)=(r-i,r)\nsr (-1) i (Just(l,r):t)=1+2*b+f+sr 1 j t where\n b|i0=0\n (f,j)=(i-l,l)\n\ndn (Nothing:h:t) = dn (h:t)\ndn l = l\n\nmain=interact$show.sr 1 0.reverse.dn.reverse.map p.tail.lines", "positive_code": [{"source_code": "{-# OPTIONS -O2 #-}\nimport Data.List\n\nmain = do\n s <- getContents\n let \n (grid:ls) = lines s\n [row, col] = map read $ words grid :: [Int]\n ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']\n ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]\n print $ search 1 1 ws\n \nsearch _ _ [] = 0\nsearch row column orig@[(r, (a, b))]\n | row == r = dist goalPos'\n | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig\n | otherwise = 1 + search (row+1) column orig\n where\n dist x = abs $ x - column \n goalPos' = if mod row 2 == 0 then a else b\n\nsearch row column orig@((r, (a, b)):(r', (a', b')):l)\n | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):l)\n | row == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):l)\n | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig\n | otherwise = 1 + search (row+1) column orig\n where\n dist x = abs $ x - column \n goalPos = if mod row 2 == 0 then min a a' else max b b'\n goalPos' = if mod row 2 == 0 then a else b\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntraceS a b = trace (show a) b\n\ntype Z = Int\n\ndata Dir = L | R deriving Show\n\nantiDir L = R\nantiDir R = L\n\nsolve :: Z -> Z -> [String] -> Z\nsolve n m ls = solve' n m ls' 0 R\n where ls' = cutter ls\n\ncutter ls = reverse $ cutter' (reverse ls)\n\ncutter' [] = []\ncutter' ls = \n case elemIndex 'W' l of\n Nothing -> cutter' lss\n Just _ -> ls\n where (l:lss) = ls\n\nsolve' _ _ [] _ _ = 0\nsolve' n m [l] c L = c - (elemFind c l)\nsolve' n m [l] c R = solve' n m [reverse l] (m-c-1) L\nsolve' n m (l1:lrem@(l2:ls)) c dir = \n abs (t-c) + solve' n m lrem t (antiDir dir) + 1\n where t = getTarget c m l1 l2 dir\n\ngetTarget c m l1 l2 L = min t1 t2\n where t1 = elemFind c l1\n t2 = elemFind c l2\ngetTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)\n\nelemFind c l1 =\n case elemIndex 'W' l1 of\n Nothing -> c\n Just t1 -> min t1 c\n\n\nmain = do\n (n,m) <- (\\[a,b] -> (a,b)) . map read . words <$> getLine\n ls <- replicateM n getLine\n print $ solve n m ls\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Control.Monad\n\ndata Dir = LEFT | RIGHT deriving (Show, Eq)\n\nmain = do\n [n, m] <- getLine >>= return . map read . words :: IO [Int]\n\n boards <- replicateM n getLine\n let pivots = map (\\l -> if null l then Nothing else Just (head l, last l)) $ map (elemIndices 'W') boards\n (cursor, cost, dir, skip) = foldl' (\\(cursor, cost, dir, skip) pivot ->\n let dir' = case dir of\n LEFT -> RIGHT\n RIGHT -> LEFT\n in case pivot of\n Nothing -> (cursor, cost, dir', skip+1)\n Just (l, r) -> case dir of\n LEFT -> if cursor <= l\n then (r, cost+skip+r-cursor, dir', 1)\n else (r, cost+skip+cursor-l+r-l, dir', 1)\n RIGHT -> if cursor >= r\n then (l, cost+skip+cursor-l, dir', 1)\n else (l, cost+skip+r-cursor+r-l, dir', 1)\n ) (0, 0, LEFT, 0) pivots\n\n --putStrLn $ show pivots\n --putStrLn $ show (cursor, cost, dir, skip)\n putStrLn $ show cost\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nlast' l = case (C.elemIndex 'W' . C.reverse) l of\n\tNothing -> 0\n\tJust x -> C.length l - 1 - x\nfst' l = case C.elemIndex 'W' l of\n\tNothing -> 0\n\tJust x -> C.length l - 1 - x\n\nsolve [] _ = 0\nsolve [ln] i = max 0 (last' ln - i)\n\twhere n = C.length ln\nsolve (ln1:ln2:lns) i = let j = max 0 (max (last' ln1) (fst' ln2) - i) in let next = solve (ln2:lns) (n - j - i - 1) in j + next + 1\n\twhere n = C.length ln1\n\nhalfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]\n\twhere n = length lns\n\ntailcut [] = []\ntailcut (x:xs)\n\t| tailcut xs == [] && C.elemIndex 'W' x == Nothing = []\n\t| otherwise = (x:tailcut xs)\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input\n\tlet view = take n $ tail input\n\tputStrLn . show $ solve (tailcut $ halfrev view) 0\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n m <- readInt\n grid <- replicateM n (BS.unpack <$> readString)\n return (n, m, grid)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ninf = 10^9\n\nsolve (n, m, grid) = go (0 : replicate (m-1) inf) True weeds' - 1\n where\n weeds = [ indices\n | (i, row) <- zip [0..] grid\n , let indices = elemIndices 'W' row ++ [0 | i == 0]\n ]\n\n weeds' = reverse $ dropWhile null $ reverse weeds\n\n go prev right [] = minimum prev\n go prev right (row:rows) = go end' (not right) rows\n where\n minv = if null row then inf else minimum row\n maxv = if null row then -inf else maximum row\n\n start = [if right && i > minv || not right && i < maxv then inf else ri + 1 | (i, ri) <- zip [0..] prev]\n end \n | right = scanl1 (\\v x -> (v + 1) `min` x) start\n | otherwise = scanr1 (\\x v -> (v + 1) `min` x) start\n end' = [if right && i < maxv || not right && i > minv then inf else min inf ri | (i, ri) <- zip [0..] end]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nlast' l = case (C.elemIndex 'W' . C.reverse) l of\n\tNothing -> -1\n\tJust x -> C.length l - 1 - x\nfst' l = case C.elemIndex 'W' l of\n\tNothing -> -1\n\tJust x -> C.length l - 1 - x\n\nsolve [] _ = -1\nsolve [ln] i = max (-1) (last' ln - i)\n\twhere n = C.length ln\nsolve (ln1:ln2:lns) i = let j = max (last' ln1) (fst' ln2) in max (-1) (j - i) + solve (ln2:lns) (n - j - 1) + 1\n\twhere n = C.length ln1\n\nhalfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]\n\twhere n = length lns\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input\n\tlet view = take n $ tail input\n\tputStrLn . show . max 0 $ solve (halfrev view) 0\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nlast' l = case (C.elemIndex 'W' . C.reverse) l of\n\tNothing -> -1\n\tJust x -> C.length l - 1 - x\nfst' l = case C.elemIndex 'W' l of\n\tNothing -> -1\n\tJust x -> C.length l - 1 - x\n\nsolve [] _ = 0\nsolve [ln] i = max (-1) (last' ln - i)\n\twhere n = C.length ln\nsolve (ln1:ln2:lns) i = let j = max (last' ln1) (fst' ln2) in let next = max (-1) (solve (ln2:lns) (n - j - 1)) in if next < 0 then max (-1) (j-i) else max 0 (j-i) + next + 1\n\twhere n = C.length ln1\n\nhalfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]\n\twhere n = length lns\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input\n\tlet view = take n $ tail input\n\tputStrLn . show . max 0 $ solve (halfrev view) 0\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nlast' l = case (C.elemIndex 'W' . C.reverse) l of\n\tNothing -> -1\n\tJust x -> C.length l - 1 - x\nfst' l = case C.elemIndex 'W' l of\n\tNothing -> -1\n\tJust x -> C.length l - 1 - x\n\nsolve [] _ = -1\nsolve [ln] i = max (-1) (last' ln - i)\n\twhere n = C.length ln\nsolve (ln1:ln2:lns) i = let j = max (last' ln1) (fst' ln2) in max 0 (j - i) + solve (ln2:lns) (n - j - 1) + 1\n\twhere n = C.length ln1\n\nhalfrev lns = [if i `mod` 2 == 1 then C.reverse (lns !! i) else (lns !! i) | i <- [0..n-1]]\n\twhere n = length lns\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input\n\tlet view = take n $ tail input\n\tputStrLn . show . max 0 $ solve (halfrev view) 0\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n m <- readInt\n grid <- replicateM n (BS.unpack <$> readString)\n return (n, m, grid)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, m, grid) = go 0 True weeds - 1\n where\n weeds = [ sort indices\n | (i, row) <- zip [0..] grid\n , let indices = elemIndices 'W' row ++ [0 | i == 0]\n ]\n\n weeds' = reverse $ dropWhile null $ reverse weeds\n\n go _ _ [] = 0\n go p right ([] : rows) = go p (not right) rows + 1\n go p right (row : rows) \n | right = (maximum row - l) + (p - l) + 1 + go (maximum row) (not right) rows\n | otherwise = (r - minimum row) + (r - p) + 1 + go (minimum row) (not right) rows\n where\n l = minimum row `min` p\n r = maximum row `max` p\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n m <- readInt\n grid <- replicateM n (BS.unpack <$> readString)\n return (n, m, grid)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ninf = 10^9\n\nsolve (n, m, grid) = go (0 : replicate (m-1) inf) True weeds - 1\n where\n weeds = [ indices\n | (i, row) <- zip [0..] grid\n , let indices = elemIndices 'W' row ++ [0 | i == 0]\n ]\n\n weeds' = reverse $ dropWhile null $ reverse weeds\n\n go prev right [] = minimum prev\n go prev right (row:rows) = go end' (not right) rows\n where\n minv = if null row then inf else minimum row\n maxv = if null row then -inf else maximum row\n\n start = [if right && i > minv || not right && i < maxv then inf else ri + 1 | (i, ri) <- zip [0..] prev]\n end \n | right = scanl1 (\\v x -> (v + 1) `min` x) start\n | otherwise = scanr1 (\\x v -> (v + 1) `min` x) start\n end' = [if right && i < maxv || not right && i > minv then inf else min inf ri | (i, ri) <- zip [0..] end]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# OPTIONS -O2 #-}\nimport Data.List\n\nmain = do\n s <- getContents\n let \n (grid:ls) = lines s\n [row, col] = map read $ words grid :: [Int]\n ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']\n ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]\n print $ search 1 1 ws\n \nsearch _ _ [] = 0\nsearch row column [(r, (a, b))]= if mod row 2 == 0 then column - a else b - column\nsearch row column orig@((r, (a, b)):(r', (a', b')):l)\n | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):l)\n | row == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):l)\n | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig\n | otherwise = 1 + search (row+1) column orig\n where\n dist x = abs $ x - column \n goalPos = if mod row 2 == 0 then min a a' else max b b'\n goalPos' = if mod row 2 == 0 then a else b\n goalPos'' = if mod row 2 == 0 then b else a"}, {"source_code": "{-# OPTIONS -O2 #-}\nimport Data.List\n\nmain = do\n s <- getContents\n let \n (grid:ls) = lines s\n [row, col] = map read $ words grid :: [Int]\n ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']\n ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]\n print $ search 1 1 ws\n \nsearch _ _ [] = 0\nsearch row column [(r, (a, b))]= if mod row 2 == 0 then column - a else b - column\nsearch row column orig@((r, (a, b)):(r', (a', b')):l)\n | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):l)\n | row == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):l)\n | row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' orig\n | otherwise = search (row+1) column orig\n where\n dist x = abs $ x - column \n goalPos = if mod row 2 == 0 then min a a' else max b b'\n goalPos' = if mod row 2 == 0 then a else b"}, {"source_code": "{-# OPTIONS -O2 #-}\nimport Data.List\n\nmain = do\n s <- getContents\n let \n (grid:ls) = lines s\n [row, col] = map read $ words grid :: [Int]\n ws' = [(i+1, j+1) |i<-[0..row-1], j<-[0..col-1], (ls !! i) !! j == 'W']\n ws = [(r, (minimum [x|(y,x)<-ws', y==r], maximum [x|(y,x)<-ws', y==r])) | r <- [1..row], elem 'W' (ls !! (r-1))]\n print $ search 1 1 ws\n \nsearch _ _ [] = 0\nsearch row column [(r, (a, b))]= if mod row 2 == 0 then column - a else b - column\nsearch row column orig@((r, (a, b)):(r', (a', b')):rows)\n | row == r && row + 1 == r' = dist goalPos + 1 + search (row+1) goalPos ((r', (a', b')):rows)\n | row == r || row + 1 == r = dist goalPos' + 1 + search (row+1) goalPos' ((r', (a', b')):rows)\n | otherwise = search (row+1) column orig\n where\n dist x = abs $ x - column \n goalPos = if mod row 2 == 0 then min a a' else max b b'\n goalPos' = if mod row 2 == 0 then a else b"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntraceS a b = trace (show a) b\n\ntype Z = Int\n\ndata Dir = L | R deriving Show\n\nantiDir L = R\nantiDir R = L\n\nsolve :: Z -> Z -> [String] -> Z\nsolve n m ls = solve' n m ls' 0 R\n where ls' = cutter ls\n\ncutter ls = reverse $ cutter' (reverse ls)\n\ncutter' [] = []\ncutter' ls = \n case elemIndex 'W' l of\n Nothing -> cutter' lss\n Just _ -> ls\n where (l:lss) = ls\n\nsolve' _ _ [] _ _ = 0\nsolve' n m [l] c L = c - (elemFind c l)\nsolve' n m [l] c R = abs $ c - (elemFind (m-c-1) (reverse l))\nsolve' n m (l1:lrem@(l2:ls)) c dir = \n abs (t-c) + solve' n m lrem t (antiDir dir) + 1\n where t = getTarget c m l1 l2 dir\n\ngetTarget c m l1 l2 L = min t1 t2\n where t1 = elemFind c l1\n t2 = elemFind c l2\ngetTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)\n\nelemFind c l1 =\n case elemIndex 'W' l1 of\n Nothing -> c\n Just t1 -> min t1 c\n\n\nmain = do\n (n,m) <- (\\[a,b] -> (a,b)) . map read . words <$> getLine\n ls <- replicateM n getLine\n print $ solve n m ls\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntraceS a b = trace (show a) b\n\ntype Z = Int\n\ndata Dir = L | R deriving Show\n\nantiDir L = R\nantiDir R = L\n\nsolve :: Z -> Z -> [String] -> Z\nsolve n m ls = solve' n m ls' 0 R\n where ls' = cutter ls\n\ncutter [] = []\ncutter ls = \n case elemIndex 'W' l of\n Nothing -> cutter lss\n Just _ -> ls\n where (l:lss) = reverse ls\n\nsolve' _ _ [] _ _ = 0\nsolve' n m [l] c L = c - (elemFind c l)\nsolve' n m [l] c R = abs $ c - (elemFind (m-c-1) (reverse l))\nsolve' n m (l1:lrem@(l2:ls)) c dir = \n traceS (abs (t-c),dir) $ abs (t-c) + solve' n m lrem t (antiDir dir) + 1\n where t = getTarget c m l1 l2 dir\n\ngetTarget c m l1 l2 L = min t1 t2\n where t1 = elemFind c l1\n t2 = elemFind c l2\ngetTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)\n\nelemFind c l1 =\n case elemIndex 'W' l1 of\n Nothing -> c\n Just t1 -> min t1 c\n\n\nmain = do\n (n,m) <- (\\[a,b] -> (a,b)) . map read . words <$> getLine\n ls <- replicateM n getLine\n print $ solve n m ls\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntraceS a b = trace (show a) b\n\ntype Z = Int\n\ndata Dir = L | R deriving Show\n\nantiDir L = R\nantiDir R = L\n\nsolve :: Z -> Z -> [String] -> Z\nsolve n m ls = solve' n m ls 0 R\n\nsolve' n m [l] c L = c - (elemFind c l)\nsolve' n m [l] c R = abs $ c - (elemFind (m-c-1) (reverse l))\nsolve' n m (l1:lrem@(l2:ls)) c dir = \n traceS (abs (t-c),dir) $ abs (t-c) + solve' n m lrem t (antiDir dir) + 1\n where t = getTarget c m l1 l2 dir\n\ngetTarget c m l1 l2 L = min t1 t2\n where t1 = elemFind c l1\n t2 = elemFind c l2\ngetTarget c m l1 l2 R = m - (1 + getTarget (m-c-1) m (reverse l1) (reverse l2) L)\n\nelemFind c l1 =\n case elemIndex 'W' l1 of\n Nothing -> c\n Just t1 -> min t1 c\n\n\nmain = do\n (n,m) <- (\\[a,b] -> (a,b)) . map read . words <$> getLine\n ls <- replicateM n getLine\n print $ solve n m ls\n"}], "src_uid": "14959b7266ceebe96c33bfa1791e26b4"} {"source_code": "import Data.List\nimport System.IO\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStr $ solve $ tail $ map read $ words input\n\nsolve :: [Int] -> String\nsolve [] = \"\"\nsolve (n:m:rs) = let (cur,rest) = splitAt (n*m) rs\n lt0 = filter (<0) cur\n abs_list = map abs cur\n all_sum = sum abs_list\n ans = if even $ length lt0\n then all_sum\n else all_sum - 2*(minimum abs_list)\n in (show ans) ++ \"\\n\" ++ solve rest\nsolve _ = \"\"\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([n, _]:xss) =\n let (xs, xss') = splitAt n xss\n in solve xs : process xss'\n\nsolve :: [[Int]] -> Int\nsolve xs\n | elem 0 ys || even neg = sum ys'\n | otherwise = sum ys' - 2 * minimum ys'\n where\n ys = concat xs\n ys' = map abs ys\n neg = length . filter (< 0) $ ys\n"}, {"source_code": "main :: IO ()\nmain = interact $ unlines . map show . solve . map read . tail . words\n\nsolve :: [Int] -> [Int]\nsolve [] = []\nsolve (n:m:rs) = ans:(solve rest)\n where (cur,rest) = splitAt (n*m) rs\n lt0_cnt = length $ filter (<0) cur\n abs_list = map abs cur\n abs_sum = sum abs_list\n ans = if even lt0_cnt\n then abs_sum\n else abs_sum - 2*(minimum abs_list)\nsolve _ = []"}, {"source_code": "import Data.List\nimport System.IO\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStr $ solve $ tail $ map read $ words input\n\nsolve :: [Int] -> String\nsolve [] = \"\"\nsolve (n:m:rs) = let sz = n*m\n (cur,rest) = splitAt sz rs\n lt0 = filter (<0) cur\n abs_list = map abs cur\n all_sum = sum abs_list\n ans = if even $ length lt0\n then all_sum\n else all_sum - 2*(minimum abs_list)\n in (show ans) ++ \"\\n\" ++ solve rest\nsolve _ = \"\"\n"}, {"source_code": "import Control.Monad\n{-\nn rows\nm columns\ncell i-th row j-th column from the left has value a(i,j)\n\ncan do following operation any number of times:\n choose any two adjacent cells and multiply the values in them by -1\n two cells are called adjacent if they share a side\n-}\n\ngetIntList :: IO [Int]\ngetIntList = (map read . words) <$> getLine\n\nrowsToIntList :: Int -> IO [Int]\nrowsToIntList 0 = return []\nrowsToIntList n = do\n thisRow <- (map read . words) <$> getLine\n nextRow <- rowsToIntList (n - 1)\n return $ mappend thisRow nextRow\n\ncounter :: Int -> (Int, Int, Int) -> (Int, Int, Int)\ncounter a (sumAbs, negativeCount, smallestAbs) = (sumAbs + abs a, negativeCount + negativeIncrement, min smallestAbs (abs a))\n where\n negativeIncrement = if a < 0 then 1 else 0\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [n, m] <- (map read . words) <$> getLine :: IO [Int]\n rows <- rowsToIntList n\n let (sumAbs, negativeCount, smallestAbs) = foldr counter (0, 0, abs (head rows)) rows\n case even negativeCount of\n True -> putStrLn $ show $ sumAbs\n False -> putStrLn $ show $ sumAbs - 2 * smallestAbs\n"}, {"source_code": "readCases :: [Int] -> [[Int]]\nreadCases [] = []\nreadCases (r:c:ws) = cs : readCases rs\n where (cs, rs) = splitAt (r*c) ws\n\nfindMaxSum :: [Int] -> Int\nfindMaxSum as\n | odd $ numNegetive as = sum as' - (2 * minimum as')\n | otherwise = sum as'\n where as' = map abs as\n numNegetive = length . filter (<0)\n\nsolve :: String -> String\nsolve = unlines . map show . map findMaxSum . readCases . map read . tail . words\n\nmain = interact solve\n"}], "negative_code": [{"source_code": "import Data.List\nimport System.IO\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStr $ solve $ tail $ map read $ words input\n\nsolve :: [Int] -> String\nsolve [] = \"\"\nsolve (n:m:rs) = let sz = n*m\n (cur,rest) = splitAt sz rs\n eq0 = filter (==0) cur\n lt0 = filter (<0) cur\n tmp = (sum cur)-2*(sum lt0)\n ans = if (length eq0 > 0) || (even $ length lt0)\n then tmp\n else tmp + 2*(maximum lt0)\n in (show ans) ++ \"\\n\" ++ solve rest\nsolve _ = \"\"\n"}], "src_uid": "7fce446de3b01aff8f4aa420a92a096d"} {"source_code": "-- maxRight: O(n)\nmaxRight :: [Int] -> [Int]\nmaxRight [] = [0]\nmaxRight (x:xs) = max x (head ys) : ys\n where ys = maxRight xs\n\n-- solve: O(n)\nsolve :: [Int] -> [Int]\nsolve xs = zipWith f xs (tail $ maxRight xs)\n where f a b = if a <= b then b + 1 - a else 0\n\nmain :: IO ()\nmain =\n getLine >>= \\n ->\n getLine >>= putStrLn . unwords . map show . solve . map read . words", "positive_code": [{"source_code": "main = interact $ unwords . map show . solve . map read . tail . words\nsolve = map (max 0 . succ) . (zipWith (-) =<< tail . scanr max (-1))\n\n"}, {"source_code": "import Control.Monad\n\nmaxRight :: [Int] -> [Int]\nmaxRight [] = [0]\nmaxRight (x:xs) = max x (head ys) : ys\n where ys = maxRight xs\n\nsolve :: [Int] -> [Int]\nsolve xs = zipWith f xs (tail $ maxRight xs)\n where f a b = if a <= b then b + 1 - a else 0\n\nansJoin :: Show a => [a] -> String\nansJoin = tail . foldr (++) \"\" . map ((++) \" \". show)\n\nmain :: IO ()\nmain =\n getLine >>= \\n ->\n getLine >>= putStrLn . ansJoin . solve . map read . words"}, {"source_code": "import qualified Data.Map as Map\n\nluxury :: (Integral a) => [a] -> [a]\nluxury values =\n let counts = foldr (\\v c -> Map.insertWith (+) v 1 c) Map.empty values\n in reverse $ fst $ foldl step ([], counts) values\n where step (res, counts) v =\n let nm = Map.update (\\c -> if c > 1 then (Just (c-1)) else Nothing) v counts\n in if Map.null nm then (0:res, nm)\n else ((((max ((fst $ (Map.findMax nm))+1) v) - v):res), nm)\n\nmain = do\n inp <- getContents\n let values = map read $ words $ head $ tail $ lines inp :: [Int]\n putStrLn $ unwords $ map show $ luxury values\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n \n \n\nmain= do\n\tgetLine\n\ts<- map read. words <$> getLine ::IO [Int]\n\tlet t = tail $ scanr max 0 s\n\tputStrLn $ intercalate \" \" $ map show $ zipWith (\\a b -> (max 0 (b+1-a))) s t\n"}, {"source_code": "import Control.Applicative\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\n\ninputInts = inputRow :: IO [Int]\n\ngo :: [Int] -> ([Int], Int)\ngo [] = ([], 0)\ngo (a:as) = ([max (b - a + 1) 0] ++ r1, max a b)\n where (r1, b) = go as\n\ntrans :: [Int] -> String\ntrans [a] = show a\ntrans (a:as) = show a ++ \" \" ++ trans as\n\nmain :: IO()\nmain = do\n [ln] <- inputInts\n lst <- inputInts\n putStrLn (trans(fst(go lst)))\n\n"}, {"source_code": "readInt :: IO Int\nreadInt = do\n getLine >>= return . read\n\nreadCase :: IO [Int]\nreadCase = do\n readInt -- Read and do nothing\n getLine >>= return . (map read . words)\n\nconstructArray :: [Int] -> ([Int], Int)\nconstructArray [] = ([], 0)\nconstructArray (x:xs) = (y, z)\n where ans = constructArray xs\n z = max x (snd ans)\n y = (max 0 ((snd ans)-x+1)) : (fst ans)\n \n\nmain :: IO()\nmain = do \n readCase >>= putStrLn . unwords . (map show) . fst . constructArray\n"}, {"source_code": "main = do\n getLine\n interact $ unwords.map show.reverse.solve.reverse.map read.words\nsolve (x:xs) = 0:res x xs\n where res _ [] = []\n res m (x:xs)|m>=x = m-x+1:res m xs\n |otherwise = 0:res x xs"}, {"source_code": "import Data.List (intercalate)\nmain=interact $ intercalate \" \". (map show).solve . (map read) . tail. words\nsolve :: [Int]->[Int]\nsolve s = reverse ([0] ++ (zipWith (\\a b->max (b-a+1) 0) (tail $ reverse s) (scanl1 max $ reverse s)))\n"}, {"source_code": "main=interact $ solve . (map read) . tail. words \nsolve s = unwords $ map show $ reverse $ [0] ++ (zipWith (\\a b->max (b-a+1) 0) (tail $ reverse s) (scanl1 max $ reverse s))"}, {"source_code": "main = do\n n <- getLine\n numbersString <- getLine\n let numbers = map read (words numbersString) :: [Int]\n let maxes = scanr max 0 numbers\n let answers = [if m >= num then (m+1-num) else 0 | (num, m) <- zip numbers (tail maxes)]\n putStrLn (unwords $ map show answers)"}, {"source_code": "main :: IO()\nmain = putStrLn . unwords . map show . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> [Int]\nsolve a = let m = getMax a\n in solve' a (tail m)\n\nsolve' :: [Int] -> [Int] -> [Int]\nsolve' [] [] = []\nsolve' (a:s) (m:ms) | a > m = 0 : solve' s ms\n | otherwise = (m - a + 1) : solve' s ms\n\ngetMax :: [Int] -> [Int]\ngetMax [] = [0]\ngetMax (a:s) = let next = getMax s\n in (max a (head next)):next\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let list = reverse $ 0:solve (last a) (reverse . init $a)\n mapM_ (\\x -> putStrLn (show x ++ \" \")) list\n\nsolve m [] = []\nsolve m (x:xs)\n |x>m = 0:solve x xs\n |otherwise = m-x+1:solve m xs"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n hs <- getInts\n\n putStrLn $ unwords $ map show $ zipWith (\\m h -> if h > m then 0 else m-h+1) (tail $ scanr max 0 hs) hs\n"}, {"source_code": "main = do\n\tgetLine\n\tas <- (map read . words) `fmap` getLine\n\n\tlet\n\t\tms = tail (scanr1 max as) ++ [0]\n\t\tres = map (\\(v, m) -> if v > m then 0 else m + 1 - v) $ zip as ms\n\n\tputStrLn $ unwords . map show $ res\n"}, {"source_code": "import Data.List (intercalate)\nmac (h:t) | null t = [(h-1)]\n | otherwise = (max th mx):next\n where next = mac t\n th = head t\n mx = max th (head next)\nmain = do\n w0 <- getLine\n w1 <- getLine\n let h = [read n::Int|n <-(words w1)]\n let c = map (+1) $ mac h\n let res = map (\\x -> max 0 ((fst x) - (snd x))) $ zip c h\n putStrLn $ intercalate \" \" $ map show res\n"}], "negative_code": [{"source_code": "main = do\n getLine\n interact $ unwords.map show.reverse.solve.reverse.map read.words\nsolve (x:xs) = 0:res x xs\n where res _ [] = []\n res m (x:xs)|m>=x = m-x+1:res(m+1) xs\n |otherwise = 0:res m xs"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words ) getLine :: IO [Int]\n mapM_ (\\x -> putStr ((show x)++\" \")) $ (zipWith (\\x y -> y-x+1) a (init (scanr max (last a) (init a)))) ++ [0]"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words ) getLine :: IO [Int]\n let ml = scanr max (last a) (init a)\n ans = solve a ml\n printList ans\n\nsolve [] [] = []\nsolve (x:xs) (y:ys)\n |x==y = 0 : solve xs ys\n |otherwise = y-x+1 : solve xs ys\n\nprintList = mapM_ (\\x -> putStr ((show x)++\" \"))\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let list = reverse $ 0:solve (last a) (reverse . init $a)\n mapM_ (\\x -> putStrLn (show x ++ \" \")) list\n\nsolve m [] = []\nsolve m (x:xs)\n |x>=m = 0:solve x xs\n |otherwise = m-x+1:solve m xs\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let list = 0:solve (last a) (init a)\n mapM_ (\\x -> putStrLn (show x ++ \" \")) (init list)\n\nsolve m [] = []\nsolve m (x:xs)\n |x>=m = 0:solve x xs\n |otherwise = m-x+1:solve m xs\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let list = reverse $ 0:solve (last a) (reverse . init $a)\n mapM_ (\\x -> putStr ((show x) ++ \" \")) list\n\nsolve m [] = []\nsolve m (x:xs)\n |x>=m = 0:solve x xs\n |otherwise = m-x+1:solve m xs\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words ) getLine :: IO [Int]\n mapM_ (\\x -> putStr ((show x)++\" \")) $ zipWith (\\x y -> if x==y then 0 else y-x+1) a (scanr max (last a) (init a))"}, {"source_code": "import Data.List (intercalate)\nmac (h:t) | null t = [(h-1)]\n | otherwise = (max th mx):next\n where next = mac t\n th = head t\n mx = max th (head next)\nmain = do\n w0 <- getLine\n w1 <- getLine\n let h = [read n::Int|n <-(words w1)]\n let c = map (+1) $ mac h\n let res = map (\\x -> (fst x) - (snd x)) $ zip c h\n putStrLn $ intercalate \" \" $ map show res\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n \n \n\nmain= do\n\tgetLine\n\ts<- map read. words <$> getLine ::IO [Int]\n\tlet t = tail $ scanr max 0 s\n\tputStrLn $ intercalate \" \" $ map show $ zipWith (\\a b -> if b==a then 0 else (max 0 (b+1-a))) s t\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n \n \n\nmain= do\n\tgetLine\n\ts<- map read. words <$> getLine ::IO [Int]\n\tlet t = scanr max 0 s\n\tputStrLn $ intercalate \" \" $ map show $ zipWith (\\a b -> if b==a then 0 else b+1-a) s t\n"}], "src_uid": "e544ed0904e2def0c1b2d91f94acbc56"} {"source_code": "getMult :: Int -> Int -> Int -> [Int]\ngetMult y k n\n\t| div n k == div y k\t= []\n\t| otherwise\t\t\t\t= (n - (mod n k) - y) : (getMult y k (n - k))\n\nprintList :: [Int] -> IO()\nprintList [] = do\n\tputStrLn \"\"\nprintList (a:b) = do\n\tputStr ((show a) ++ \" \")\n\tprintList b\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet y = read ((words str) !! 0)\n\tlet k = read ((words str) !! 1)\n\tlet n = read ((words str) !! 2)\n\tif (div n k <= div y k)\n\t\tthen putStrLn \"-1\"\n\t\telse printList (reverse (getMult y k n))\n", "positive_code": [{"source_code": "import Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine :: IO [Int]\n\nmain = do\n [y, k, n] <- getInts\n\n let a = filter (>= 1) $ map (\\s -> s-y) $ takeWhile (<= n) $ map (*k) [1..]\n\n if null a\n then print $ -1\n else putStrLn $ unwords $ map show a\n"}, {"source_code": "\nmain :: IO ()\nmain = do [y,k,n] <- (getLine >>= (return . map read . words))\n let l = [ z - y | z <- [k,2*k..n], z > y]\n let ans = if l == [] then [-1] else l\n putStrLn . unwords . map show $ ans\n"}, {"source_code": "main = do\n x <- getLine\n putStrLn $ unwords $ map show $ f1 $ (\\[a,b,c] -> map (\\t -> t-a) $ f a b c) $ map (\\a -> read a::Int) $ words x\n\nf1 :: [Int] -> [Int]\nf1 [] = [-1]\nf1 x = x\n\nf :: Int -> Int -> Int -> [Int]\nf y k n\n | mod (y+1) k == 0 = [y+1,y+1+k..n]\n | otherwise = f (k*((div y k)+1)-1) k n"}, {"source_code": "main :: IO ()\nmain = interact $ (\\x -> if null x then \"-1\" else unwords $ map show x) . testcase . map read . words\n\ntestcase :: [Integer] -> [Integer]\ntestcase [y,k,n] = [ x | pos <- takeWhile (<=n) (iterate (+k) k), let x = pos - y, x >= 1]\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [Int]\nsolve [y, k, n] = map (\\z -> z - y) [x, x + k .. n]\n where\n x = (y `div` k + 1) * k\n\nprints :: Show a => [a] -> IO ()\nprints [] = print (-1)\nprints [x] = print x\nprints (x:xs) = putStr (show x ++ \" \") >> prints xs\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [ y, k, n ] = head $ filter (not . null) $ [(y `div` k + 1) * k - y, (y `div` k + 2) * k - y .. n - y] : [[-1]]\nsolve _ = undefined\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [ y, k, n ] = head $ filter (not . null) $ [k - y `mod` k, 2 * k - y `mod` k .. n - y] : [[-1]]\nsolve _ = undefined\n"}, {"source_code": "main=interact$unwords.map show.f.map read.words\nf[y,k,n]= case dropWhile(<=0)[(-y)`mod`k,(-y)`mod`k+k..n-y] of\n [] -> [-1]\n xs -> xs\n"}, {"source_code": "import Control.Applicative\nimport Data.Ratio\nimport Data.List\nmain = do\n [y,k,n] <- map read . words <$> getLine\n let l1 = [ m*k + c1 | m <- [0..(n-y-c1)`div`k]]\n c1 = k - y`mod`k\n case (l1 == []) of\n False -> putStrLn.unwords.map show $ l1\n True -> print (-1)\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nparse = map read . words\n\nsolve :: [Int] -> [Int]\nsolve [y, k, n] = \n map (\\x -> x - y) $ dropWhile (<= y) $ takeWhile (<= n) [x | x <- [k, 2*k ..]]\n\npresent :: [Int] -> String\npresent [] = \"-1\"\npresent foo = unwords $ map show foo\n\nmain = interact $ present . solve . parse\n\n\n\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [y,k,n]\n | k - mod y k > n - y = [-1]\n | otherwise = [k - mod y k, 2 * k - mod y k .. n - y]\n"}], "negative_code": [{"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [ y, k, n ] = head $ filter (not . null) $ [((y + k - 1) `div` k) * k - y, ((y + 2 * k - 1) `div` k) * k - y .. n - y] : [[-1]]\nsolve _ = undefined\n"}, {"source_code": "import Control.Applicative\nimport Data.Ratio\nimport Data.List\nmain = do\n [y,k,n] <- map read . words <$> getLine\n let l2 = sort [x | x <- [0..n-y], (x+y)`mod`k==0]\n case (l2 == []) of\n False -> putStrLn.unwords.map show $ l2\n True -> print (-1)\n "}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nparse = map read . words\n\nsolve :: [Int] -> [Int]\nsolve [y, k, n] = \n map (\\x -> x - y) $ dropWhile ( String\npresent [] = \"-1\"\npresent foo = unwords $ map show foo\n\nmain = interact $ present . solve . parse\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nparse = map read . words\n\nsolve :: [Int] -> [Int]\nsolve [y, k, n] = \n map (\\x -> x - y) $ dropWhile ( String\npresent [] = \"-1\"\npresent foo = unwords $ map show foo\n\nmain = interact $ present . solve . parse\n\n\n\n"}], "src_uid": "2deda3a05740e1184735bf437e3850a8"} {"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- repaint.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\nimport Prelude hiding (getLine)\nimport System.IO\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\n\nri = readInts <$> B.getLine :: IO [Int]\n where\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n dropSpace = B.dropWhile isSpace\n\nmain :: IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n sort . concat <$> replicateM 2 getLine\n mapM_ (putStrLn.show.solve) tcs\n\nsolve = length . init . sortOn length . group\n", "positive_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List (group, sort)\n\nsolve as =\n let as' = group $ sort as\n in length as' - 1\n\nread = do\n s1 <- C.getLine\n s2 <- C.getLine\n\n print $ solve [s1 `B.index` 0, s1 `B.index` 1, s2 `B.index` 0, s2 `B.index` 1]\n\nmain :: IO()\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n"}, {"source_code": "import Data.Set\r\n\r\ncomputeProg n = (1 + n) * n `div` 2\r\n\r\ndecide n = decideBody n\r\ndecideBody 0 = return ()\r\ndecideBody n = do\r\n s1 <- getLine\r\n s2 <- getLine\r\n case (size $ fromList (s1 ++ s2)) of\r\n 1 -> putStrLn (show 0)\r\n 2 -> putStrLn (show 1)\r\n 3 -> putStrLn (show 2)\r\n 4 -> putStrLn (show 3)\r\n decideBody $ n - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine >>= (return . (read :: String -> Int))\r\n decide t"}], "negative_code": [], "src_uid": "a9143235c8e2b6b188ea3fc8a90f0c80"} {"source_code": "import Control.Monad (replicateM_)\n\nsolve :: Int -> [Char] -> Int\nsolve _ [] = 0\nsolve c (x : xs) =\n if x == '1'\n then solve (c + 1) xs\n else max (2 - c) 0 + solve 0 xs\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n getLine\n l <- getLine\n print $ solve 2 l\n", "positive_code": [{"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE LambdaCase #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: B8.ByteString -> Int\nsolve str = flip S.evalState ((0, 2)::(Int, Int)) $ do\n forM_ (B8.unpack str) $ \\case\n '0' -> S.modify $ \\(answer, cnt1) -> (answer + max (2 - cnt1) 0, 0)\n '1' -> S.modify $ \\(answer, cnt1) -> (answer, cnt1 + 1)\n (answer, _) <- S.get\n return answer\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n str <- B8.getLine <&> head . B8.words\n let answer = solve str\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "9966bfdc9677a9dd558684a00977cd58"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, u, v] <- readInts\n a : as <- readInts\n let\n canEscapeAlready = or [abs (p - q) > 1 | (p, q) <- zip as $ a : as]\n allSame = all (== a) as\n putInts $ pure $ if canEscapeAlready\n then 0\n else min u v + if allSame\n then v\n else 0\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nmain = do\r\n t <- getLine\r\n replicateM_ (read t) testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n [n,u,v] <- fmap (map read . words) getLine\r\n a <- fmap (map read . words) getLine\r\n putStrLn $ solve n u v a\r\n\r\nsolve :: Int -> Int -> Int -> [Int] -> String\r\nsolve n u v a\r\n | distance == 0 = show $ min (u+v) (2*v) \r\n | distance == 1 = show $ min u v\r\n | otherwise = \"0\"\r\n where\r\n distance = snd $ foldl' (\\(last,dist) curr -> (curr,max dist . abs $ last-curr)) (head a,0) a :: Int"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nmodule Main where\n\n\nimport Control.Monad ( replicateM_ )\nimport Data.Array.Unboxed ( (!)\n , UArray\n , listArray\n )\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t eachCase\n where\n eachCase = do\n [n, u, v] <- fmap read . words <$> getLine\n obs <- fmap (read @Int) . words <$> getLine\n let obsArr = listArray @UArray (1, length obs) obs\n if all (== head obs) (tail obs)\n then print (v + min u v)\n else if any (\\i -> abs (obsArr ! i - obsArr ! (i - 1)) > 1) [2 .. length obs] then print 0 else print (min u v)\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, u, v] <- readInts\n a : as <- readInts\n putInts $ pure $ min u v + if all (== a) as\n then v\n else 0\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "7f502f2fd150a2ded948826960d123cd"} {"source_code": "import Control.Arrow\n\nmain = interact $ \n\tlines >>> drop 1\n\t>>> map (words >>> map read >>> sum >>> show)\n\t>>> unlines\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetInts :: Int -> IO [Int]\ngetInts n = fmap read <$> getLines n\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\nworkProblem :: [String] -> IO ()\nworkProblem [] = pure ()\nworkProblem (x:xs) = do\n let [num1, num2] = words x\n let a = read num1 :: Int\n let b = read num2 :: Int\n putStrLn $ show (a + b)\n workProblem xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n lines <- getLines n\n workProblem lines"}, {"source_code": "import Control.Arrow\n\nmain = interact $ \n\tlines >>> drop 1\n\t>>> map (words >>> map read >>> sum >>> show)\n\t>>> unlines\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess = do\n\t\ts<-map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ sum s\n\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n process\n"}], "negative_code": [], "src_uid": "27ddccc777ef9040284ab6314cbd70e7"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class (lift)\r\nimport Data.Char (isSpace)\r\nimport Data.Maybe\r\n\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\nimport qualified Data.Set as S\r\n\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nreadIntIO :: IO Int\r\nreadIntIO = do\r\n t <- getLine\r\n if all isSpace t then readIntIO else pure . readInt . P.pack $ t\r\n\r\ntype DoState = StateT (S.Set Int) IO\r\n\r\ngo :: IO ()\r\ngo = do\r\n n <- readIntIO\r\n cs <- flip evalStateT S.empty $ fmap (foldr (<>) []) $ mapM findCycles [1..n]\r\n let\r\n p :: UArray Int Int\r\n p = array (1, n) cs\r\n P.putStr $ toLazyByteString $ char7 '!' <> char7 ' ' <> (putInts $ elems p) <> char7 '\\n' <> flush\r\n where\r\n findCycles :: Int -> DoState [(Int, Int)]\r\n findCycles i = do\r\n b <- S.member i <$> get\r\n if b then pure []\r\n else do\r\n y <- g\r\n pure $ zip y (tail y)\r\n where\r\n g :: DoState [Int]\r\n g = do\r\n lift $ P.putStr $ toLazyByteString $ char7 '?' <> char7 ' ' <> putInts [i] <> char7 '\\n' <> flush\r\n nextI <- lift readIntIO\r\n nextB <- S.member nextI <$> get\r\n modify $ S.insert nextI\r\n if nextB then pure [nextI]\r\n else (nextI:)<$>g\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n t <- readInt . P.pack <$> getLine\r\n replicateM_ t go\r\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\nimport Data.Array.Unboxed\r\nimport Data.Array.ST.Safe\r\nimport Control.Monad.ST.Lazy\r\nimport qualified Control.Monad.ST as Strict\r\nimport Control.Monad.Trans.Class\r\n\r\n\r\nsolve :: forall s. S (ST s) Builder\r\nsolve = do\r\n ~[n] <- getInts 1\r\n let lst :: Strict.ST s v -> S (ST s) v\r\n lst = lift . strictToLazyST\r\n arr :: STUArray s Int Int <- lst $ newArray (1, n) 0\r\n let\r\n query :: Int -> Builder\r\n query k = string7 \"? \" <> putInts [k] <> flush\r\n loopQuery :: Int -> Int -> S (ST s) Builder\r\n loopQuery k prev = (query k <>) <$> do\r\n ~[resp] <- getInts 1\r\n lst $ writeArray arr prev resp\r\n vis <- lst $ readArray arr resp\r\n if vis /= 0\r\n then pure mempty\r\n else loopQuery k resp\r\n go :: Int -> S (ST s) Builder\r\n go k = do\r\n vis <- lst $ readArray arr k\r\n if vis == 0\r\n then (query k <>) <$> do\r\n ~[resp] <- getInts 1\r\n loopQuery k resp\r\n else pure mempty\r\n queries <- forM [1 .. n] go\r\n ansArr :: UArray Int Int <- lst $ freeze arr\r\n let ans = char7 '!' <> char7 ' ' <> putInts (elems ansArr)\r\n pure $ mconcat queries <> ans <> flush\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n state $ \\st -> runST $ runStateT solve st\r\n\r\n\r\ntype S = StateT [P.ByteString]\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Monad m => Int -> S m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> S m [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class (lift)\r\nimport Data.Char (isSpace)\r\nimport Data.Maybe\r\n\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\nimport qualified Data.Set as S\r\n\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nreadIntIO :: IO Int\r\nreadIntIO = do\r\n t <- getLine\r\n if all isSpace t then readIntIO else pure . readInt . P.pack $ t\r\n\r\ntype DoState = StateT (S.Set Int) IO\r\n\r\ngo :: IO ()\r\ngo = do\r\n n <- readIntIO\r\n cs <- flip evalStateT S.empty $ fmap (foldr (<>) []) $ mapM findCycles [1..n]\r\n let\r\n p :: UArray Int Int\r\n p = array (1, n) cs\r\n P.putStr $ toLazyByteString $ char7 '!' <> char7 ' ' <> (putInts $ elems p) <> char7 '\\n' <> flush\r\n where\r\n findCycles :: Int -> DoState [(Int, Int)]\r\n findCycles i = do\r\n b <- S.member i <$> get\r\n if b then pure []\r\n else do\r\n y@(x:xs) <- g\r\n pure $ zip y (xs ++ [x])\r\n where\r\n g :: DoState [Int]\r\n g = do\r\n b <- S.member i<$>get\r\n if b then pure []\r\n else do\r\n lift $ P.putStr $ toLazyByteString $ char7 '?' <> char7 ' ' <> putInts [i] <> char7 '\\n' <> flush\r\n nextI <- lift readIntIO\r\n modify $ S.insert nextI\r\n (nextI:)<$>g\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n t <- readInt . P.pack <$> getLine\r\n replicateM_ t go\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class (lift)\r\nimport Data.Char (isSpace)\r\nimport Data.Maybe\r\n\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\nimport qualified Data.Set as S\r\n\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nreadIntIO :: IO Int\r\nreadIntIO = do\r\n t <- getLine\r\n if all isSpace t then readIntIO else pure . readInt . P.pack $ t\r\n\r\ntype DoState = StateT (S.Set Int) IO\r\n\r\ngo :: IO ()\r\ngo = do\r\n n <- readIntIO\r\n cs <- flip evalStateT S.empty $ fmap (foldr (<>) []) $ mapM findCycles [1..n]\r\n let\r\n p :: UArray Int Int\r\n p = array (1, n) cs\r\n P.putStr $ toLazyByteString $ char7 '!' <> (putInts $ elems p) <> char7 '\\n' <> flush\r\n where\r\n findCycles :: Int -> DoState [(Int, Int)]\r\n findCycles i = do\r\n b <- S.member i <$> get\r\n if b then pure []\r\n else do\r\n y@(x:xs) <- g\r\n pure $ zip y (xs ++ [x])\r\n where\r\n g :: DoState [Int]\r\n g = do\r\n b <- S.member i<$>get\r\n if b then pure []\r\n else do\r\n lift $ P.putStr $ toLazyByteString $ char7 '?' <> putInts [i] <> char7 '\\n' <> flush\r\n nextI <- lift readIntIO\r\n modify $ S.insert nextI\r\n (nextI:)<$>g\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n t <- readInt . P.pack <$> getLine\r\n replicateM_ t go\r\n"}], "src_uid": "96ec983bfadc9e96e36ebb8ffc5279d3"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (sortBy)\n\nparseLine :: String -> (Int, Int)\nparseLine line = (a, b)\n where\n [a, b] = map read (words line)\n\nmyCompare :: (Int, Int) -> (Int, Int) -> Ordering\nmyCompare (n1, x1) (n2, x2)\n | x1 > x2 = LT\n | x1 < x2 = GT\n | n1 < n2 = LT\n | n1 > n2 = GT\n | otherwise = EQ\n\nsolve :: Int -> Int -> Int -> [(Int, Int)] -> [(Int, Int)]\nsolve t1 t2 k = (sortBy myCompare . solve' . zip [1..])\n where\n solve' = map calcMaxHeight\n calcMaxHeight (n, (a, b)) = (n, max (calcMaxHeight' a b) (calcMaxHeight' b a))\n calcMaxHeight' a b = a * t1 * (100 - k) + 100 * b * t2 \n\nprintAns :: [(Int, Int)] -> IO ()\nprintAns = mapM_ printAns'\n where\n printAns' (n, x) = putStrLn $ concat [show n, \" \", show a, \".\", b']\n where\n (a, b) = divMod x 100\n b' = if b < 10 then '0' : show b else show b\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines getContents\n let [n, t1, t2, k] = (map read . words . head) lines'\n let ps = (map parseLine . take n . tail) lines'\n printAns (solve t1 t2 k ps)\n", "positive_code": [{"source_code": "import Data.List (sortBy)\nimport Text.Printf (printf)\n\nsortGT (a1, b1) (a2, b2)\n | b1 < b2 = GT\n | b1 > b2 = LT\n | b1 == b2 = EQ\n\nanswer :: Double -> Double -> Double -> [(Double, Double)] -> [(Int, Double)]\nanswer t1 t2 k gnomes = sortBy sortGT $ zipWith maxHeight [1..] gnomes\n\twhere\n\t\tmaxHeight n (a, b) = (n, max (height a b) (height b a))\n\t\theight a b = t1 * a * k + t2 * b\n\nshowGnome :: (Int, Double) -> String\nshowGnome (i, h) = printf \"%i %.2f\" i h\n\ntoTuple :: [a] -> (a, a)\ntoTuple (x:y:[]) = (x,y)\ntoTuple _ = error \"wrong input\"\n\nmain = do\n\ttmp <- getLine\n\tlet (n:t1:t2:k:[]) = map read . words $ tmp\n\tgnomeTmp <- getContents\n\tlet gnomes = map (toTuple . map read . words) . lines $ gnomeTmp\n\tputStrLn . unlines . map showGnome $ answer t1 t2 (1 - k/100) gnomes"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Control.Applicative\nimport Control.Monad\nimport Text.Printf\n\nmain = do\n [n,t1,t2,k] <- map read.words <$> getLine\n uvs <- replicateM n $ map read.words <$> getLine\n mapM_ (\\ (i,f) -> printf \"%d %.2f\\n\" i f) $ solve [n,t1,t2,k] uvs\n\nsolve :: [Int] -> [[Int]] -> [(Int,Double)]\nsolve [n,t1,t2,k] uvs = sortBy (flip $ comparing snd).zip [1..].map calc $ uvs\n where calc [v,u] = max (f[v,u]) (f[u,v])\n f [v,u] = (fromIntegral $ (100-k)*v*t1+100*u*t2)/100"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain =\n do\n vals <- getLine\n let (n:t1:t2:k:_) = map (read :: String -> Int) $ words vals\n input <- getContents\n mapM (putStrLn.printSol) (sortBy myCmp (solve t1 t2 (100-k) 1 n $ lines input))\n\nmyCmp :: Ord a => (a,a) -> (a,a) -> Ordering\nmyCmp (x1,y1) (x2,y2) =\n if x1 == x2\n then\n compare y1 y2\n else\n compare x2 x1\n\nsolve :: Int -> Int -> Int -> Int -> Int -> [String] -> [(Int, Int)]\nsolve _ _ _ _ _ [] = [] \nsolve t1 t2 k i n (x:xs) \n | i > n = []\n | otherwise = \n let\n (speed1:speed2:_) = map (read :: String -> Int) $ words x\n m = max (t1 * speed1 * k + t2 * speed2 * 100) (t1 * speed2 * k + t2 * speed1 * 100)\n in\n (m, i) : (solve t1 t2 k (i+1) n xs)\n\nprintSol :: (Int, Int) -> String\nprintSol (a,b) = (show b ++ \" \" ++ addDot a)\n\naddDot :: Int -> String\naddDot = snd . foldr (\\x (p,ys) -> (p+1, if p == 2 then '.':x:ys else x:ys)) (1,[]) . show\n\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nprocess :: [(Integer, Integer)] -> Integer -> Integer -> Integer -> [Integer]\nprocess [] t1 t2 k = []\nprocess ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tlet\n\t\t[n, tt1, tt2, k] = map (\\x -> read x :: Integer).words $ line1\n\t\tt1 = tt1*100\n\t\tt2 = tt2*100\n\tcontent <- getContents\n\tlet\n\t \tarr = map (\\x -> let [a, b] = words$ x in (read a :: Integer, read b :: Integer)). lines $ content\n\t\tarr1 = reverse. sortBy (\\(a, b) (c, d) -> if b /= d then compare b d else compare c a). zip [1..] $ process arr t1 t2 k\n\tmapM_ (\\(x, y) -> putStrLn$ (show x) ++ \" \" ++ (show$ y `div` 100) ++ \".\" ++ appendZero (show $ y `mod` 100)) arr1\n\twhere\n\t\tappendZero x \n\t\t | length x == 2 = x\n\t\t | otherwise = appendZero ('0': x)\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nprocess :: [(Int, Int)] -> Int -> Int -> Int -> [Int]\nprocess [] t1 t2 k = []\nprocess ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tlet\n\t\t[n, tt1, tt2, k] = map (\\x -> read x :: Int).words $ line1\n\t\tt1 = tt1*100\n\t\tt2 = tt2*100\n\tcontent <- getContents\n\tlet\n\t \tarr = map (\\x -> let [a, b] = words$ x in (read a :: Int, read b :: Int)). lines $ content\n\t\tarr1 = reverse. sortBy (\\(a, b) (c, d) -> if b /= d then compare b d else compare c a). zip [1..] $ process arr t1 t2 k\n\tmapM_ (\\(x, y) -> putStrLn$ (show x) ++ \" \" ++ (show$ y `div` 100) ++ \".\" ++ appendZero (show $ y `mod` 100)) arr1\n\twhere\n\t\tappendZero x \n\t\t | length x == 2 = x\n\t\t | otherwise = appendZero (x++\"0\")\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nprocess :: [(Int, Int)] -> Int -> Int -> Int -> [Int]\nprocess [] t1 t2 k = []\nprocess ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tlet\n\t\t[n, tt1, tt2, k] = map (\\x -> read x :: Int).words $ line1\n\t\tt1 = tt1*100\n\t\tt2 = tt2*100\n\tcontent <- getContents\n\tlet\n\t \tarr = map (\\x -> let [a, b] = words$ x in (read a :: Int, read b :: Int)). lines $ content\n\t\tarr1 = reverse. sortBy (\\(a, b) (c, d) -> if b /= d then compare b d else compare c a). zip [1..] $ process arr t1 t2 k\n--\tprint arr\n--\tmapM_ (print) arr1\n\tmapM_ (\\(x, y) -> putStrLn$ (show x) ++ \" \" ++ (show$ y `div` 100) ++ \".\" ++ (show $ y `mod` 100)) arr1\n\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nprocess :: [(Int, Int)] -> Int -> Int -> Int -> [Int]\nprocess [] t1 t2 k = []\nprocess ((a, b): as) t1 t2 k = ( max (a*t1 + b*t2 - (a*t1*k `div` 100)) (a*t2 + b*t1 - (b*t1*k `div` 100)) ) : process (as) t1 t2 k\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tlet\n\t\t[n, tt1, tt2, k] = map (\\x -> read x :: Int).words $ line1\n\t\tt1 = tt1*100\n\t\tt2 = tt2*100\n\tcontent <- getContents\n\tlet\n\t \tarr = map (\\x -> let [a, b] = words$ x in (read a :: Int, read b :: Int)). lines $ content\n\t\tarr1 = reverse. sortBy (\\(a, b) (c, d) -> if b /= d then compare b d else compare c a). zip [1..] $ process arr t1 t2 k\n\tmapM_ (\\(x, y) -> putStrLn$ (show x) ++ \" \" ++ (show$ y `div` 100) ++ \".\" ++ appendZero (show $ y `mod` 100)) arr1\n\twhere\n\t\tappendZero x \n\t\t | length x == 2 = x\n\t\t | otherwise = appendZero ('0': x)\n"}, {"source_code": "import Data.List (sortBy)\nimport Text.Printf (printf)\n\nsortGT (a1, b1) (a2, b2)\n | b1 < b2 = GT\n | b1 > b2 = LT\n | b1 == b2 = EQ\n\nanswer :: Double -> Double -> Double -> [(Double, Double)] -> [(Int, Double)]\nanswer t1 t2 k gnomes = sortBy sortGT $ zipWith maxHeight [1..] gnomes\n\twhere\n\t\tmaxHeight n (a, b) = (n, max (height a b) (height b a))\n\t\theight a b = t1 * a * k + t2 * b\n\nshowGnome :: (Int, Double) -> String\nshowGnome (i, h) = printf \"%i %.2f\" i h\n\ntoTuple :: [a] -> (a, a)\ntoTuple (x:y:[]) = (x,y)\ntoTuple _ = error \"wrong input\"\n\nmain = do\n\ttmp <- getLine\n\tlet (n:t1:t2:k:[]) = map read . words $ tmp\n\tgnomeTmp <- getContents\n\tlet gnomes = map (toTuple . map read . words) . lines $ gnomeTmp\n\tputStrLn . unlines . map showGnome $ answer t1 t2 (k/100) gnomes"}], "src_uid": "a89f9310996eb23254d07e52544e30ae"} {"source_code": "import Data.List\n\nmain :: IO ()\nmain =\n interact\n $ show\n . maximum\n . map length\n . group\n . sort\n . map (read :: String -> Int)\n . tail\n . words\n", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve = maximum . map length . group . sort"}, {"source_code": "import Data.List\n\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\nmain = interact $ unlines . parse . lines\n\nparse [_,ops'] = sol ops\n where\n ops = fn $ words ops'\n fn :: [String] -> [Int]\n fn xs = map read xs\n\nsol bs = [ show res ]\n where\n res = length $ maximumBy cmp $ group $ sort bs\n cmp a b = compare (length a) (length b)\n"}], "negative_code": [], "src_uid": "0cbd3eee259b1436f82e259be7d7ee0e"} {"source_code": "import Control.Monad\nimport Data.List (foldl')\nimport Data.Int\n\nreadIntList = fmap ((map read) . words) getLine :: IO [Int64]\n\ninf = 1000000000000000000\n\nmain = do\n n <- readLn\n (a:as) <- readIntList\n (b:bs) <- mapM (\\_ -> getLine) [1..n]\n let ans = solve as bs (0,a,b)\n if ans == inf\n then print (-1)\n else print ans\n \nsolve :: [Int64] -> [String] -> (Int64,Int64,String) -> Int64\nsolve [] [] (a,b,_) = min a b\nsolve (x:xs) (y:ys) (a,b,c) =\n let [p,q] = map fn [(0,y),(x,reverse y)]\n fn (cost,str) = foldl' (\\acc (pcost,fl) -> if fl then min (pcost+cost) acc else acc) inf [(a,c<=str),(b,(reverse c)<=str)]\n in if all (==inf) [p,q]\n then inf\n else solve xs ys (p,q,y)\n \n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List (foldl')\nimport Data.Int\n\nreadIntList = fmap ((map read) . words) getLine :: IO [Int64]\n\ninf = 1000000000000000000\n\nmain = do\n n <- readLn\n (a:as) <- readIntList\n (b:bs) <- mapM (\\_ -> getLine) [1..n]\n let ans = solve as bs (0,a,b)\n if ans == inf then print (-1) else print ans\n \nsolve [] [] (a,b,_) = min a b\nsolve (x:xs) (y:ys) (a,b,c) =\n let [p,q] = map fn [(0,y),(x,reverse y)]\n fn (cost,str) = foldl' (\\acc (pcost,fl) -> if fl then min (pcost+cost) acc else acc) inf [(a,c<=str),(b,(reverse c)<=str)]\n in if all (==inf) [p,q]\n then inf\n else solve xs ys (p,q,y)\n \n"}, {"source_code": "import Data.List (foldl')\ndata ExtInt = Finite Integer | Infinity deriving (Eq, Ord)\ntype Iter = (String, ExtInt, String, ExtInt)\n\nplus :: ExtInt -> ExtInt -> ExtInt\n(Finite a) `plus` (Finite b) = Finite (a + b)\n_ `plus` _ = Infinity\n\nextract :: ExtInt -> Integer\nextract (Finite a) = a\nextract Infinity = (-1)\n\nsolve :: [Integer] -> [String] -> Integer\nsolve vals strs = let (_, u, _, v) = foldl' f (\"\", Finite 0, \"\", Finite 0) (zip vals strs) in extract (min u v)\n\nf :: Iter -> (Integer, String) -> Iter\nf (s, c, s', c') (k, t) = (t, min w x, t', min y z)\n where t' = reverse t\n k' = Finite k\n w = if s <= t then c else Infinity\n x = if s' <= t then c' else Infinity\n y = if s <= t' then c `plus` k' else Infinity\n z = if s' <= t' then c' `plus` k' else Infinity\n\nmain = do getLine\n vals <- getLine\n strs <- getContents\n putStrLn . show $ solve (map read $ words vals) (lines strs)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad (replicateM)\nimport Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (ByteString, words, lines, readInt, getLine, getContents, reverse)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents, reverse)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n cs <- readInts\n ss <- replicateM n (B.takeWhile (not . isSpace) <$> getLine)\n\n let\n f :: [Int] -> [ByteString] -> (Int64, Int64)\n f [c] [s] = (0, fromIntegral c)\n f (c:cs) (s:t:ss) = (a, b)\n where\n (a', b') = f cs (t:ss)\n\n a\n | c1 && c2 = min a' b'\n | c1 = a'\n | c2 = b'\n | otherwise = 10^18\n where\n c1 = s <= t\n c2 = s <= (reverse t)\n\n b\n | c1 && c2 = c' + min a' b'\n | c1 = c' + a'\n | c2 = c' + b'\n | otherwise = 10^18\n where\n c' = fromIntegral c\n s' = reverse s\n c1 = s' <= t\n c2 = s' <= (reverse t)\n\n (a, b) = f cs ss :: (Int64, Int64)\n\n m = min a b\n\n if m == 10^18\n then print $ -1\n else print m\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List (foldl')\n\n\nreadIntList = fmap ((map read) . words) getLine :: IO [Int]\n\ninf = 1000000000\n\nmain = do\n n <- readLn\n (a:as) <- readIntList\n (b:bs) <- mapM (\\_ -> getLine) [1..n]\n let ans = solve as bs (0,a,b)\n if ans == inf\n then print (-1)\n else print ans\n \nsolve :: [Int] -> [String] -> (Int,Int,String) -> Int\nsolve [] [] (a,b,_) = min a b\nsolve (x:xs) (y:ys) (a,b,c) =\n let [p,q] = map fn [(0,y),(x,reverse y)]\n fn (cost,str) = foldl' (\\acc (pcost,fl) -> if fl then min (pcost+cost) acc else acc) inf [(a,c<=str),(b,(reverse c)<=str)]\n in if all (==inf) [p,q]\n then inf\n else solve xs ys (p,q,y)\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad (replicateM)\nimport Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (ByteString, words, lines, readInt, getLine, getContents, reverse)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents, reverse)\nimport Data.Int (Int64)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n cs <- readInts\n ss <- replicateM n getLine\n\n let\n f :: [Int] -> [ByteString] -> (Int64, Int64)\n f [c] [s] = (0, fromIntegral c)\n f (c:cs) (s:t:ss) = (a, b)\n where\n (a', b') = f cs (t:ss)\n\n a\n | c1 && c2 = min a' b'\n | c1 = a'\n | c2 = b'\n | otherwise = -1\n where\n c1 = s < t\n c2 = s < (reverse t)\n\n b\n | c1 && c2 = c' + min a' b'\n | c1 = c' + a'\n | c2 = c' + b'\n | otherwise = -1\n where\n c' = fromIntegral c\n s' = reverse s\n c1 = s' < t\n c2 = s' < (reverse t)\n\n (a, b) = f cs ss :: (Int64, Int64)\n\n print $ min a b\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad (replicateM)\nimport Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (ByteString, words, lines, readInt, getLine, getContents, reverse)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents, reverse)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n cs <- readInts\n ss <- replicateM n (B.takeWhile (not . isSpace) <$> getLine)\n\n let\n f :: [Int] -> [ByteString] -> (Int64, Int64)\n f [c] [s] = (0, fromIntegral c)\n f (c:cs) (s:t:ss) = (a, b)\n where\n (a', b') = f cs (t:ss)\n\n a\n | c1 && c2 = min a' b'\n | c1 = a'\n | c2 = b'\n | otherwise = -1\n where\n c1 = s < t\n c2 = s < (reverse t)\n\n b\n | c1 && c2 = c' + min a' b'\n | c1 = c' + a'\n | c2 = c' + b'\n | otherwise = -1\n where\n c' = fromIntegral c\n s' = reverse s\n c1 = s' < t\n c2 = s' < (reverse t)\n\n (a, b) = f cs ss :: (Int64, Int64)\n\n print $ min a b\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad (replicateM)\nimport Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (ByteString, words, lines, readInt, getLine, getContents, reverse)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents, reverse)\nimport Data.Int (Int64)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n cs <- readInts\n ss <- replicateM n getLine\n\n let\n f :: [Int] -> [ByteString] -> (Int64, Int64)\n f [c] [s] = (0, fromIntegral c)\n f (c:cs) (s:t:ss) = (a, b)\n where\n (a', b') = f cs (t:ss)\n\n a\n | c1 && c2 = min a' b'\n | c1 = a'\n | c2 = b'\n | otherwise = -1\n where\n c1 = s <= t\n c2 = s <= (reverse t)\n\n b\n | c1 && c2 = c' + min a' b'\n | c1 = c' + a'\n | c2 = c' + b'\n | otherwise = -1\n where\n c' = fromIntegral c\n s' = reverse s\n c1 = s' <= t\n c2 = s' <= (reverse t)\n\n (a, b) = f cs ss :: (Int64, Int64)\n\n print $ min a b\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad (replicateM)\nimport Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (ByteString, words, lines, readInt, getLine, getContents, reverse)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents, reverse)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n cs <- readInts\n ss <- replicateM n (B.takeWhile (not . isSpace) <$> getLine)\n\n let\n f :: [Int] -> [ByteString] -> (Int64, Int64)\n f [c] [s] = (0, fromIntegral c)\n f (c:cs) (s:t:ss) = (a, b)\n where\n (a', b') = f cs (t:ss)\n\n a\n | c1 && c2 = min a' b'\n | c1 = a'\n | c2 = b'\n | otherwise = -1\n where\n c1 = s <= t\n c2 = s <= (reverse t)\n\n b\n | c1 && c2 = c' + min a' b'\n | c1 = c' + a'\n | c2 = c' + b'\n | otherwise = -1\n where\n c' = fromIntegral c\n s' = reverse s\n c1 = s' <= t\n c2 = s' <= (reverse t)\n\n (a, b) = f cs ss :: (Int64, Int64)\n\n print $ min a b\n\n"}, {"source_code": "import Data.List (foldl')\ndata ExtInt = Finite Int | Infinity deriving (Eq, Ord)\ntype Iter = (String, ExtInt, String, ExtInt)\n\nplus :: ExtInt -> ExtInt -> ExtInt\n(Finite a) `plus` (Finite b) = Finite (a + b)\n_ `plus` _ = Infinity\n\nextract :: ExtInt -> Int\nextract (Finite a) = a\nextract Infinity = (-1)\n\nsolve :: [Int] -> [String] -> Int\nsolve vals strs = let (_, u, _, v) = foldl' f (\"\", Finite 0, \"\", Finite 0) (zip vals strs) in extract (min u v)\n\nf :: Iter -> (Int, String) -> Iter\nf (s, c, s', c') (k, t) = (t, min w x, t', min y z)\n where t' = reverse t\n k' = Finite k\n w = if s <= t then c else Infinity\n x = if s' <= t then c' else Infinity\n y = if s <= t' then c `plus` k' else Infinity\n z = if s' <= t' then c' `plus` k' else Infinity\n\nmain = do getLine\n vals <- getLine\n strs <- getContents\n putStrLn . show $ solve (map read $ words vals) (lines strs)\n"}], "src_uid": "91cfd24b8d608eb379f709f4509ecd2d"} {"source_code": "import Data.List\nimport Data.Int\nmain = interact exec\nexec = show . (\\(_:xs) -> solve xs) . map read . words\nsolve :: [Int64] -> Int64\nsolve = fmap sum ((snd . mapAccumR (\\m (i, t) -> let t' = max t $ m + i in (max m $ t' - i, t')) minBound . zip [1..] . snd . mapAccumL (\\t x -> let t' = max (x + 1) t in (t', t')) 0) >>= zipWith (\\a b -> a - b - 1))", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nmain = interact (show . (fmap sum ((snd . mapAccumR (\\m (i, t) -> let t' = max t $ m + i in (max m $ t' - i, t')) minBound . zip [1..] . snd . mapAccumL (\\t x -> let t' = max (x + 1) t :: Int64 in (t', t')) 0) >>= zipWith (\\a b -> a - b - 1)) . tail) . map read . words)"}], "negative_code": [{"source_code": "import Data.List\nmain = interact exec\nexec = show . (\\(_:xs) -> solve xs) . map read . words\nsolve :: [Int] -> Int\nsolve = fmap sum ((snd . mapAccumR (\\m (i, t) -> let t' = max t $ m + i in (max m $ t' - i, t')) minBound . zip [1..] . snd . mapAccumL (\\t x -> let t' = max (x + 1) t in (t', t')) 0) >>= zipWith (\\a b -> a - b - 1))"}], "src_uid": "d4909bd6c23312ac3968d81cb6340035"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.IntMap.Strict as MP (insertWith, delete, findMax, empty, adjust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.List as L (intercalate)\nimport qualified Data.Array.MArray.Safe as A (newArray, writeArray, getElems)\nimport qualified Data.Array.ST.Safe as ST (STUArray)\nimport qualified Control.Monad.ST.Safe as ST (runST, ST)\nimport qualified Data.STRef as ST (STRef, newSTRef, readSTRef, modifySTRef)\nimport qualified Control.Monad as M (forM_)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun n k xs = ST.runST $ do\n ans <- A.newArray (0, n - 1) 0 :: ST.ST s (ST.STUArray s Int Int)\n cost <- ST.newSTRef 0 :: ST.ST s (ST.STRef s I.Int64)\n mset <- ST.newSTRef MP.empty\n let (xsl, xsr) = splitAt k (zip xs [0..])\n M.forM_ xsl $ \\(x, i) -> do\n ST.modifySTRef mset (MP.insertWith (++) x [i])\n M.forM_ xsr $ \\(x, i) -> do\n ST.modifySTRef mset (MP.insertWith (++) x [i])\n (MP.findMax -> (xa, (xb:xt))) <- ST.readSTRef mset\n ST.modifySTRef cost (+ fromIntegral xa * fromIntegral (i - xb))\n A.writeArray ans xb (i + 1)\n if xt == [] then ST.modifySTRef mset (MP.delete xa)\n else ST.modifySTRef mset (MP.adjust (const xt) xa)\n M.forM_ [n..n + k - 1] $ \\i -> do\n (MP.findMax -> (xa, (xb:xt))) <- ST.readSTRef mset\n ST.modifySTRef cost (+ fromIntegral xa * fromIntegral (i - xb))\n A.writeArray ans xb (i + 1)\n if xt == [] then ST.modifySTRef mset (MP.delete xa)\n else ST.modifySTRef mset (MP.adjust (const xt) xa)\n ans <- A.getElems ans\n cost <- ST.readSTRef cost\n return (cost, ans)\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n (map readInt . C.words -> xs) <- B.getLine\n let (cost, ans) = run n k xs\n print (cost :: I.Int64)\n putStrLn $ L.intercalate \" \" $ map show $ ans\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, FlexibleContexts, Rank2Types, ScopedTypeVariables #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport qualified Data.ByteString.Char8 as SB\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Int\nimport qualified Data.Set as S\nimport Data.Array.ST.Safe\nimport Control.Monad.ST.Safe\nimport Data.Array.Unboxed\n\nmain = SB.putStr . SB.unlines . map (SB.pack . show) . evalState app . B.words =<< B.getContents\napp = do\n n <- poi\n k <- poi\n cs <- replicateM n poi\n return $ solve n k cs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\n\nsolve n k cs = elems $ runSTUArray $ do \n arr <- newArray (0, n) 0 :: ST s (STUArray s Int Int64)\n foldM_ (go arr) ((\\(f, s) -> (S.fromList f, s)) . splitAt k $ flip (zipWith P) [1..] $ map to64 cs) [to64 (k + 1)..to64 (k + n)]\n return arr\n where\n go arr (!f, !ss) t = do \n tot <- readArray arr 0\n writeArray arr 0 (tot + (t - i) * c)\n writeArray arr (fromIntegral i) t\n return (f', ss')\n where\n ((P c i, f'), ss') = (\\(a, b) -> (S.deleteFindMax a, b)) $ case ss of\n [] -> (f, [])\n s:rs -> (S.insert s f, rs)\n\ndata P = P !Int64 !Int64 deriving (Eq, Show, Ord)"}], "negative_code": [], "src_uid": "8c23fcc84c6921bc2a95ff0586516321"} {"source_code": "import Data.Maybe\nimport qualified Data.Map as M\nimport Control.Applicative\nimport Data.List\nimport Data.Function\nimport Debug.Trace\nimport Control.Monad\n\nzipPairs f [] = []\nzipPairs f (x:y:xs) = (f x y):zipPairs f xs\n\ndist [x1, y1] [x2, y2] = abs (x1 - x2) + abs (y1 - y2)\ndists pts = {-trace (show pts) $ -}zipPairs (+) $ zipWith dist pts (tail pts)\n\nfindD have [] = Just []\nfindD have (x:xs) | null av = Nothing\n | otherwise = (head av:) <$> findD (M.insert x (tail av) have) xs\n where\n av = M.findWithDefault [] x have\n \nformat xs = (-1:(intersperse (-1) xs)) ++ [-1]\n\nsolve :: [[Int]] -> M.Map Int [Int] -> Maybe [Int]\nsolve pts lens = tail <$> try (last pts : pts) <|> \n take (length pts) <$> try (pts ++ [head pts])\n where\n try pts = format <$> findD lens (dists pts)\n \n\nbuildMap xs = M.fromListWith (++) $ zip xs $ map pure [1..]\n\nmain = do\n [n, _] <- map read <$> words <$> getLine\n pts <- replicateM n $ map read <$> words <$> getLine\n lens <- map read <$> words <$> getLine\n case solve pts (buildMap lens) of\n Nothing -> putStrLn \"NO\"\n Just res -> (putStrLn \"YES\") >> (putStrLn $ unwords $ map show res)\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM, replicateM_)\nimport Data.IntMap (findWithDefault, fromListWith, member, update)\nimport Data.List (delete, intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntoPair :: [a] -> (a, a)\ntoPair [a, b] = (a, b)\n\nsolve :: [(Int, Int)] -> [Int] -> Maybe [Int]\nsolve ps as = case solve2 of\n Nothing -> solve1\n Just qs -> Just (last qs : init qs)\n where\n map' = fromListWith (++) $ zip as $ map (\\x -> [x]) [1..]\n solve1 = solve' (last ps : ps) map' []\n solve2 = solve' (ps ++ [head ps]) map' []\n solve' [_] _ ans = Just $ reverse ans\n solve' ((x1, y1) : (x2, y2) : (x3, y3) : ps) map' ans\n | l `member` map' = solve' ((x3, y3) : ps) (update tail' l map') (-1 : num : ans)\n | otherwise = Nothing\n where\n num = head $ findWithDefault [] l map'\n tail' [x] = Nothing\n tail' xs = Just $ tail xs\n l = sum [abs (x1-x2), abs (y1-y2), abs (x2-x3), abs (y2-y3)]\n\nprint' :: Maybe [Int] -> IO ()\nprint' Nothing = putStrLn \"NO\"\nprint' (Just xs) = putStrLn \"YES\" >> prints xs\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n ps <- replicateM n reads\n as <- reads\n print' $ solve (map toPair ps) as"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM, replicateM_)\nimport Data.IntMap (findWithDefault, fromListWith, member, update)\nimport Data.List (delete, intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntoPair :: [a] -> (a, a)\ntoPair [a, b] = (a, b)\n\nsolve :: [(Int, Int)] -> [Int] -> Maybe [Int]\nsolve ps as = case solve2 of\n Nothing -> solve1\n Just qs -> Just (tail qs ++ [head qs])\n where\n map' = fromListWith (++) $ zip as $ map (\\x -> [x]) [1..]\n solve1 = solve' (last ps : ps) map' []\n solve2 = solve' (ps ++ [head ps]) map' []\n solve' [_] _ ans = Just $ reverse ans\n solve' ((x1, y1) : (x2, y2) : (x3, y3) : ps) map' ans\n | l `member` map' = solve' ((x3, y3) : ps) (update tail' l map') (-1 : num : ans)\n | otherwise = Nothing\n where\n num = head $ findWithDefault [] l map'\n tail' [x] = Nothing\n tail' xs = Just $ tail xs\n l = sum [abs (x1-x2), abs (y1-y2), abs (x2-x3), abs (y2-y3)]\n\nprint' :: Maybe [Int] -> IO ()\nprint' Nothing = putStrLn \"NO\"\nprint' (Just xs) = putStrLn \"YES\" >> prints xs\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n ps <- replicateM n reads\n as <- reads\n print' $ solve (map toPair ps) as"}], "src_uid": "1112910988c9e7e2836a12c9f5a0b665"} {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: [[Int]] -> Int\nsolve [a,b] = sum $ zipWith (*) a $ tail $ scanl min 101 b\n\nparse :: String -> [[Int]]\nparse = transpose.(fmap $ fmap read).fmap words.lines\n\nmain = do\n getLine\n l <- getContents\n print.solve $ parse l\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nparseInt :: L.ByteString -> Int\nparseInt bs = case L.readInt bs of\n Just (x, _) -> x\n Nothing -> error $ \"Can't parse Int from: \" ++ (L.unpack bs)\n\nsolve :: [Int] -> Int -> Int\nsolve [] _ = 0\nsolve (a:p:vs) bestPrice | p < bestPrice = a * p + solve vs p\n | otherwise = a * bestPrice + solve vs bestPrice\n\nmain :: IO ()\nmain = do\n (_:vs) <- liftM (map parseInt . L.words) L.getContents\n print $ solve vs maxBound\n"}, {"source_code": "main = interact $ show . solve . parse\n where parse = group2 . map read . tail . words\n group2 (x:y:zs) = (x, y) : group2 zs\n group2 [] = []\n\nsolve :: [(Int, Int)] -> Int\nsolve = fst . foldl folder (0, maxBound)\n where folder (acc, minCost) (a, p) = (acc + a * mC', mC')\n where mC' = min minCost p\n"}, {"source_code": "main = do\n line <- getLine\n let n = read line :: Int\n inputLines <- fmap (take n . lines) getContents\n let input = [(tokens!!0,tokens!!1) | line <- inputLines, let tokens = map read (words line)] :: [(Int, Int)]\n let mins = scanl1 (\\x y -> minimum [x,y]) (map snd input)\n let days = map fst input\n let cost = foldl (\\x y -> x+(fst y * snd y)) 0 $ zip mins days\n putStrLn $ show cost"}, {"source_code": "main :: IO()\nmain = print . solve 100 . map read . tail . words =<< getContents\n\nsolve :: Int -> [Int] -> Int\nsolve _ [] = 0\nsolve m (a:p:x) = let n = min m p\n in n * a + solve n x\n"}, {"source_code": "main = do\n getLine\n (as, ps) <- fmap (unzip . map ((\\[a, b] -> (a, b)) . map read . words) . lines) getContents\n\n let ms = scanl1 min ps\n\n print $ sum $ zipWith (*) as ms\n"}, {"source_code": "main = interact $ show . f 1000 . map read . tail . words\nf _ [] = 0\nf x (a:p:ap) = f p' ap + p' * a where p' = min x p\n\n"}, {"source_code": "main = interact $ show . solve 100 . tail . map read . words\nsolve _ [] = 0\nsolve cMin (a : p : xs) = let nMin = min cMin p in nMin * a + solve nMin xs\n"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\nanswer::[[Int]] -> Int -> Int\nanswer [] _ = 0\nanswer ([a,p]:ps) pmin = a*nextMin+ answer ps nextMin\n where nextMin = min p pmin\nmain = do\n n <- readLn::IO Int\n a <- readMatrix \n print $ answer a (maxBound::Int)\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = readLn >>= \\ n -> solve =<< forM [1..n] (\\i-> map (fst.fromJust.C.readInt).C.words<$>C.getLine)\n--solve::Int->IO()\nsolve xs = print $ sum $ map (\\[a,b]->a*b) $ tail $ slv1 xs\nslv1 xs = scanl (\\[b1,b2] [a1,a2] -> [a1, minimum [b2,a2]]) (head xs) xs"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- liftM (\\x->read x::Int) getLine\n aps <- liftM (map ((\\[x,y]->(x,y)) . map (\\x->read x::Int).words)) $replicateM n getLine\n print $ fst \n $ foldl' (\\(sum, p') (a,p) -> let p'' = min p p' in (sum + p''*a, p'')) ((\\(x,y) -> (x*y,y)) \n $ (head aps)) \n $ tail aps\n"}, {"source_code": "import Control.Applicative\n \n\n\nprocess s _ [] = s\nprocess s m ([a1,a2]:as) = process (s+a1*(min m a2)) (min m a2) as\n\n\nmain::IO ()\nmain=do\n n<-read <$> getLine ::IO Int\n x<- map(map read) <$> map words <$> lines <$> getContents ::IO [[Int]]\n print $ process 0 10000 x\n"}, {"source_code": "main :: IO ()\nmain = print . solve . map (map read . words) . tail . lines =<< getContents\n\nsolve :: [[Int]] -> Int\nsolve = fst . foldl (\\(s, q) [a, p] -> (s + a * min p q, min p q)) (0, 100)\n"}, {"source_code": "main :: IO ()\nmain = print . solve . map (toTuple . map read . words) . tail . lines =<< getContents\n\nsolve :: [(Int, Int)] -> Int\nsolve = fst . foldl (\\(s, q) (a, p) -> (s + a * min p q, min p q)) (0, 1000000000)\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "main = interact $ show . uncurry solve . parse\nparse = unzip . pairs . map read . tail . words\npairs (x:y:z) = (x,y) : pairs z\npairs [] = []\nsolve as ps = sum $ zipWith (*) as (scanl1 min ps)\n"}, {"source_code": "minPrice' :: [(Int, Int)] -> Int\nminPrice' [x] = prod x\nminPrice' (x:xs)\n | snd x > snd (head xs) = prod x + minPrice' (xs)\n | otherwise = prod x + minPrice' ((fst (head xs), snd x) : tail xs)\n\nprod :: Num a => (a, a) -> a\nprod (a,b) = a*b\n\n-----------------\n\nmain :: IO ()\nmain = do\n inputNum <- readLn\n ans <- fmap minPrice' (getInput inputNum)\n print ans\n\ngetInput :: Int -> IO [(Int, Int)]\ngetInput 0 = return []\ngetInput n = do\n x <- getLine\n let numAmtPrice = map read (words x) :: [Int]\n as = head numAmtPrice\n ps = last numAmtPrice\n nextLine <- getInput (n-1)\n return ((as, ps) : nextLine)\n"}, {"source_code": "minPrice :: [Int] -> [Int] -> Int\nminPrice as ps = thrd final where\n final = foldl1 (\\acc x -> if snd1 acc > snd1 x then\n (1, snd1 x, (snd1 x * fst1 x) + thrd acc)\n else (1, snd1 acc, (snd1 acc * fst1 x) + thrd acc)) (zip3 as ps ds)\n ds = (head as * head ps) : repeat 0\n\nfst1 (a, _, _) = a\nsnd1 (_, b, _) = b\nthrd (_, _, c) = c\n\ngetInput :: Int -> IO [(Int, Int)]\ngetInput 0 = return []\ngetInput n = do\n line <- getLine\n let as = head $ map read (words (line)) :: Int\n ps = last $ map read (words (line)) :: Int\n next <- getInput (n-1)\n return ((as, ps) : next)\n\nmain :: IO ()\nmain = do\n numInput <- readLn\n vals <- getInput numInput\n let as = map fst vals\n ps = map snd vals\n ans = minPrice as ps\n print ans\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [[Int]] -> Int -> Int\nsolve [] _ = 0\nsolve ([a,p]:xs) mn = a*nextmn + solve xs nextmn\n where\n nextmn = min mn p\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ap <- map (map fst . mapMaybe C.readInt . C.words) <$> replicateM n C.getLine\n print $ solve ap 101\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \nprocess [] _ s = s\nprocess ([a,p]:as) x s | p<=x = process as p (s+p*a)\n | otherwise = process as x (s+x*a)\n\nmain=do\n\tgetLine\n\tr<- map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents:: IO [[Int]]\n\tprint $ process r 1000 0"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \nprocess [] _ s = s\nprocess ([a,p]:as) x s | p<=x = process as p (s+p*a)\n | otherwise = process as x (s+x*a)\n\nmain=do\n\tgetLine\n\tr<- map (map read). map words.lines <$> getContents:: IO [[Int]]\n\tprint $ process r 1000 0"}, {"source_code": "process :: [Int] -> [Int] -> Int\nprocess as ps = sum $ zipWith (*) as ps'\n where ps' = scanl1 min ps\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int, Int)\nreadPair s = (l,r)\n where [l,r] = (map readInt.words) s\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n (as,ps) <- fmap (unzip.map readPair.lines) getContents\n print $ process as ps"}, {"source_code": "import Data.Char\n\n\nminimumMoney :: [Int] -> [Int] -> Int -> IO Int\nminimumMoney [] [] min = return 0\nminimumMoney (a:as) (p:ps) min = if p < min then (do m <- minimumMoney as ps p\n\t\t\t\t\t\t return (a*p + m))\t\n\t\t\t\t\t else (do m <- minimumMoney as ps min\n\t\t\t\t\t\t return (a*min + m))\n\n\n\ngetNumbers :: Int -> IO ([Int],[Int])\ngetNumbers 0 = return ([],[])\ngetNumbers n = do s <- getLine\n\t\t let (a',rest) = span isDigit s\n\t\t (p',rest') = span isDigit (tail rest) \n\t\t a = read a' :: Int\n\t\t p = read p' :: Int in do (as,ps) <- getNumbers (n-1)\n\t\t\t\t\t return (a:as,p:ps)\n\nmain :: IO()\nmain = do s <- getLine\n\t let n = read s :: Int in do (as,ps) <- getNumbers n\n\t\t\t\t result <- minimumMoney as ps (2*10^9)\n\t\t\t\t print result\n\t\t\n\n"}, {"source_code": "main :: IO ()\nmain = interact solve\n\naccumulator :: (Int, Int) -> [Int] -> (Int, Int)\naccumulator (_, _) [] = undefined\naccumulator (_, _) [_] = undefined\naccumulator (total, bestPrice) (a:p:_) = (total', bestPrice')\n where bestPrice' = min bestPrice p\n total' = total + a * bestPrice'\n\nsolve :: String -> String\nsolve s = show $ fst $ foldl accumulator (0, 200) xs\n where xs = fmap (fmap read . words) (tail $ lines s) :: [[Int]]\n\n"}], "negative_code": [{"source_code": "import Data.List (sort, sortBy)\n\nmain :: IO ()\nmain = print . solve . map (toTuple . map read . words) . tail . lines =<< getContents\n\nsolve :: [(Int, Int)] -> Int\nsolve xas = sum $ zipWith (\\(_, x) (_, y) -> x + y) (sort (filter ((>0) . fst) xas) ++ [(0, 0)]) (sortBy (flip compare) (filter ((<0) . fst) xas) ++ [(0, 0)])\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import Data.Char\n\n\nminimumMoney :: [Int] -> [Int] -> IO Int\nminimumMoney [] [] = return 0\nminimumMoney (a:as) (p:ps) = if minimum (p:ps) == p then return (p*sum (a:as)) else do m <- minimumMoney as ps\n\t\t\t\t\t\t\t\t\t\t return (a*p + m) \n\n\n\ngetNumbers :: Int -> IO ([Int],[Int])\ngetNumbers 0 = return ([],[])\ngetNumbers n = do s <- getLine\n\t\t let (a',rest) = span isDigit s\n\t\t (p',rest') = span isDigit (tail rest) \n\t\t a = read a' :: Int\n\t\t p = read p' :: Int in do (as,ps) <- getNumbers (n-1)\n\t\t\t\t\t return (a:as,p:ps)\n\nmain :: IO()\nmain = do s <- getLine\n\t let n = read s :: Int in do (as,ps) <- getNumbers n\n\t\t\t\t result <- minimumMoney as ps\n\t\t\t\t print result\n\t\t\n\n"}], "src_uid": "28e0822ece0ed35bb3e2e7fc7fa6c697"} {"source_code": "import Data.List (nub)\nmain = do\n n <- readLn\n as <- fmap (map read . tail . words) getLine\n bs <- fmap (map read . tail . words) getLine\n putStrLn $ if length (nub (as ++ bs :: [Int])) == n then \"I become the guy.\" else \"Oh, my keyboard!\"\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (sort, nub)\nmain = do\n n <- readLn :: IO Int\n aa <- map read . words <$> getLine\n bb <- map read . words <$> getLine\n let xs = tail aa\n ys = tail bb\n p = head aa\n q = head bb\n levels = sort (nub $ xs ++ ys) == [1..n]\n putStrLn $ if levels then \"I become the guy.\" else \"Oh, my keyboard!\"\n \n\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = printResult . solve . map read . words =<< getContents\n\nprintResult :: Bool -> IO()\nprintResult b = putStrLn (if b then \"I become the guy.\" else \"Oh, my keyboard!\")\n\nsolve :: [Int] -> Bool\nsolve (n:na:x) =\n let a = take na x\n b = drop (na + 1) x\n in (length $ nub (a ++ b)) == n\n"}, {"source_code": "import Data.List\n\nconv lst res\n | (null lst) = res\n | otherwise = conv (tail lst) (res ++ [(read (head lst))::Int])\n\nspanning lst cnt\n | (null lst) = cnt\n | (head lst) == (cnt+1) = spanning (tail lst) (cnt+1)\n | otherwise = spanning (tail lst) cnt\n\n\nmain = do\n ss <- getLine\n let ii = (read ss)::Int\n ww <- getLine\n oo <- getLine\n let qq = (tail (conv (words ww) []))\n cc = (tail (conv (words oo) []))\n jj = qq ++ cc\n hh = sort jj\n spans = spanning hh 0\n if spans < ii\n then putStrLn \"Oh, my keyboard!\"\n else putStrLn \"I become the guy.\"\n\n\n\n\n \n"}, {"source_code": "import Data.List\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n a1 <- readItems\n a2 <- readItems\n putStrLn $ if null ([1 .. n] \\\\ ((tail a1) ++ (tail a2)))\n then \"I become the guy.\"\n else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.Set\n\nmain = interact $ g.f\nf inp = (Prelude.map (\\x -> Prelude.map read (words x) :: [Integer]) (lines inp))\n\na (x:y:z:[]) = head x\nb (x:y:z:[]) = tail y\nc (x:y:z:[]) = tail z\n\ng inp\n | fromList [1..(a inp)] == union (fromList (b inp)) (fromList (c inp)) = \"I become the guy.\"\n | otherwise = \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . getAns . getIntArray\n\ngetAns :: [Int] -> String\ngetAns (n:p:xs) = if ([1..n] == sort (union ls rs)) then \"I become the guy.\" else \"Oh, my keyboard!\"\n\t\t\twhere (ls, (_:rs)) = splitAt p xs\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn\n as <- fmap (map read . words) getLine\n bs <- fmap (map read . words) getLine\n\n putStrLn $ if sort (nub (tail as ++ tail bs)) == [1..n] then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.Functor ( (<$>) )\nimport qualified Data.Set as HS\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ps <- map read . words <$> getLine\n qs <- map read . words <$> getLine\n let (_:an) = ps :: [Int]\n let (_:bn) = qs :: [Int]\n if HS.size (HS.union (HS.fromList an) (HS.fromList bn)) == n\n then putStrLn \"I become the guy.\"\n else putStrLn \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List as L\nsolve [[n],_:a,_:b] = length (L.nub $ L.sort (a++b) ) == n\ntores True = \"I become the guy.\"\ntores False = \"Oh, my keyboard!\"\nmain = interact $ tores . solve . map (map read . words) . lines\n"}, {"source_code": "import qualified Data.Set as S\n\nmain = do\n n <- fmap read getLine\n (p:ls) <- fmap (map read . words) getLine\n (q:ls') <- fmap (map read . words) getLine\n printSol (solve n (S.fromList ls) (S.fromList ls'))\n\nprintSol True = putStrLn \"I become the guy.\"\nprintSol False = putStrLn \"Oh, my keyboard!\"\n\nsolve :: Int -> S.Set Int -> S.Set Int -> Bool\nsolve n s s' = n == S.size (S.union s s')\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve2 . concat.ttail.map (map read.words).take 3 . lines\nsolve :: [Int]->[Int]\nsolve []=[]\nsolve (x:xs) = if x/=0 then x:(solve [y|y<-xs, y/=x, y/=0]) else solve [y|y<-xs, y/=x, y/=0]\nsolve2 :: [Int]->String\nsolve2 (x:xs) = if x==length (solve xs) then \"I become the guy.\" else \"Oh, my keyboard!\"\nttail (xs:xss) =xs : map tail xss "}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport qualified Data.List as List\nimport qualified Data.Set as Set\n\nsolve :: Int -> [Int] -> [Int] -> Bool\nsolve n a b = List.all id $ map (\\i -> Set.member i s) [1 .. n]\n where\n s = Set.fromList (a ++ b)\n\nans :: Bool -> String\nans True = \"I become the guy.\"\nans False = \"Oh, my keyboard!\"\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n _ : a <- (map read . words) <$> getLine\n _ : b <- (map read . words) <$> getLine\n putStrLn $ ans $ solve n a b\n\n\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.List as L\n\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- L.nub . tail . map read . words <$> getLine :: IO [Int]\n ys <- L.nub . tail . map read . words <$> getLine\n putStrLn $ \n if length (xs `L.union` ys) == n then \"I become the guy.\"\n else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: Int -> [Int] -> [Int] -> Bool\n-- solve lv a b = all (liftM2 (||) (`elem` a) (`elem` b)) [1..lv]\nsolve lv a b = (==[1..lv]) . map head . group . sort $ a ++ b\n\nmain :: IO ()\nmain = do\n lv <- fmap read getLine\n a <- fmap tail getIntList\n b <- fmap tail getIntList\n putStrLn $ if solve lv a b then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- readLn\n (_:xs) <- map read . words <$> getLine :: IO [Int]\n (_:ys) <- map read . words <$> getLine :: IO [Int]\n let\n l = length . group . sort $ xs ++ ys\n in putStrLn $ if l == n then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\n\n\n\n\nmain=do\n n<- read <$> getLine ::IO Int\n a<- (replicateM 2 (tail <$> map read <$> words <$> getLine))::IO [[Int]]\n let b = length $ map head $ group $ sort $ concat a\n putStrLn $ if n==b then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List (nub, sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . output . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve [[n], (_:xs), (_:ys)] = length (nub (xs ++ ys)) == n\n\noutput :: Bool -> String\noutput True = \"I become the guy.\"\noutput _ = \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List (nub, sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . output . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve [[n], (_:xs), (_:ys)] = sort (nub (xs ++ ys)) == [1..n]\n\noutput :: Bool -> String\noutput True = \"I become the guy.\"\noutput _ = \"Oh, my keyboard!\"\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/469/A\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n a <- getLine >>= return. tail. map read. words :: IO [Int]\n b <- getLine >>= return. (++a). tail. map read. words :: IO [Int]\n putStrLn $ if n == (length. nub $ b) then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/469/A\n\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: Int -> [Int] -> [Int] -> Bool\nsolve lv a b = (==[1..lv]) . map head . group . sort $ a ++ b\n\nmain :: IO ()\nmain = do\n lv <- fmap read getLine\n a <- fmap tail getIntList\n b <- fmap tail getIntList\n putStrLn $ if solve lv a b then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Set as S\n \n \n\n \nmain= do\n\tn<- read <$> getLine :: IO Int\n\tx<- tail.map read. words <$> getLine::IO [Int]\n\ty<- tail.map read. words <$> getLine::IO [Int]\n\tputStrLn $ if length (S.toList(S.fromList(x++y)))==n then \"I become the guy.\" else \"Oh, my keyboard!\"\n\t \n\t \n\t \n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- getLine >>= return. tail. map read. words :: IO [Int]\n b <- getLine >>= return. (++a). tail. map read. words :: IO [Int]\n putStrLn $ if n == (length. nub $ b) then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n s1 <- tail . map (read :: String -> Int) . words <$> getLine\n s2 <- tail . map (read :: String -> Int) . words <$> getLine\n putStrLn $ if sort (s1 `union` s2) == [1..n] then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n comb <- sort . uncurry union . (\\[a,b]->(a,b)) . map (tail . map (read :: String -> Int) . words) <$> sequence [getLine, getLine]\n putStrLn $ if length comb == n then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Data.List (nub)\n\nprocess :: Int -> [Int] -> [Int] -> Bool\nprocess n ps qs = n == length (nub (ps ++ qs))\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n (p:ps) <- fmap (map readInt.words) getLine\n (q:qs) <- fmap (map readInt.words) getLine\n putStrLn $ [\"Oh, my keyboard!\",\"I become the guy.\"] !! fromEnum (process n ps qs)"}, {"source_code": "import Data.List\nmain = do\n let readint = read :: String -> Int\n n <- fmap readint getLine\n m <- fmap (length . nub . concat . map (tail . map readint . words) . lines) getContents\n putStrLn $ if m == n then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "\nimport Data.List\n\nmain = interact $ (\\(n:p:xs) -> if n == (length . nub $ drop (p+1) xs ++ take p xs) then \"I become the guy.\" else \"Oh, my keyboard!\") . map read . words\n\n\n\n"}, {"source_code": "import Data.List\n\nplay :: Int -> [[Int]] -> String\nplay n [xs, ys]\n | (length . group . sort) (xs ++ ys) == n = \"I become the guy.\" \n | otherwise = \"Oh, my keyboard!\"\n\nsolve :: String -> String\nsolve s = play n [xs, ys]\n where l = lines s\n n = read . head $ l\n [xs, ys] = fmap (fmap read . tail. words) . tail $ l\n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "import Data.List\n\nplay :: Int -> [[Int]] -> String\nplay n [xs, ys]\n | n == length (nub (xs ++ ys)) = \"I become the guy.\" \n | otherwise = \"Oh, my keyboard!\"\n\nsolve :: String -> String\nsolve s = play n [xs, ys]\n where l = lines s\n n = read . head $ l\n [xs, ys] = fmap (fmap read . tail. words) . tail $ l\n\nmain :: IO ()\nmain = interact $ solve"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (nub)\n\nmain = do\n n <- readLn :: IO Int\n aa <- map read . words <$> getLine\n bb <- map read . words <$> getLine\n let xs = tail aa\n ys = tail bb\n p = head aa\n q = head bb\n levels = (nub $ xs ++ ys) == [1..n]\n putStrLn $ if levels then \"I become the guy.\" else \"Oh, my keyboard!\"\n \n\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn\n as <- fmap (map read . words) getLine\n bs <- fmap (map read . words) getLine\n\n putStrLn $ if sort (nub (as ++ bs)) == [1..n] then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.Functor ( (<$>) )\nimport qualified Data.Set as HS\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ps <- map read . words <$> getLine\n qs <- map read . words <$> getLine\n let (_:an) = ps :: [Int]\n let (_:bn) = qs :: [Int]\n if HS.size (HS.union (HS.fromList ps) (HS.fromList qs)) == n\n then putStrLn \"I become the guy.\"\n else putStrLn \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.Functor ( (<$>) )\nimport qualified Data.Set as HS\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ps <- map read . words <$> getLine\n qs <- map read . words <$> getLine\n let (_:an) = ps :: [Int]\n let (_:bn) = qs :: [Int]\n if HS.size (HS.union (HS.fromList ps) (HS.fromList qs)) == n\n then putStrLn \"I become the guy\"\n else putStrLn \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve2 . concat.map (map read.words).take 3 . lines\nsolve :: [Int]->[Int]\nsolve []=[]\nsolve (x:xs) = if x/=0 then x:(solve [y|y<-xs, y/=x, y/=0]) else solve [y|y<-xs, y/=x, y/=0]\nsolve2 :: [Int]->String\nsolve2 (x:xs) = if x==length (solve xs) then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve2 . concat.map (map read.words).take 3 . lines\nsolve :: [Int]->[Int]\nsolve []=[]\nsolve (x:xs) = x:(solve [y|y<-xs, y/=x, y/=0])\nsolve2 :: [Int]->String\nsolve2 (x:xs) = if x==length (solve xs) then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve2 . concat.map (map read.words).take 3 . lines\nsolve :: [Int]->[Int]\nsolve []=[]\nsolve (x:xs) = x:(solve [y|y<-xs, y/=x])\nsolve2 :: [Int]->String\nsolve2 (x:xs) = if x==length (solve xs) then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Control.Applicative\nimport qualified Data.List as L\n\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- L.nub . map read . words <$> getLine :: IO [Int]\n ys <- L.nub . map read . words <$> getLine\n putStrLn $ \n if length (xs `L.union` ys) == n then \"I become the guy.\"\n else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.List as L\n\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- filter (/=0) . L.nub . map read . words <$> getLine :: IO [Int]\n ys <- filter (/=0) . L.nub . map read . words <$> getLine\n putStrLn $ \n if length (xs `L.union` ys) == n then \"I become the guy.\"\n else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.List as L\n\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- tail . L.nub . map read . words <$> getLine :: IO [Int]\n ys <- tail . L.nub . map read . words <$> getLine\n putStrLn $ \n if length (xs `L.union` ys) == n then \"I become the guy.\"\n else \"Oh, my keyboard!\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\n\n\nmain=do\n n<- read <$> getLine ::IO Int\n a<-concatMap (map read) <$> map words <$> lines <$> getContents ::IO [Int]\n let b = length $ map head $ group $ sort a\n putStrLn $ if n==b then \"I become the guy.\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List (nub)\nmain = do\n n <- readLn\n as <- fmap (map read . tail . words) getLine\n bs <- fmap (map read . tail . words) getLine\n putStrLn $ if length (nub (as ++ bs :: [Int])) == n then \"I become the guy\" else \"Oh, my keyboard!\"\n"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n s1 <- tail . map (read :: String -> Int) . words <$> getLine\n s2 <- tail . map (read :: String -> Int) . words <$> getLine\n putStrLn $ if union s1 s2 == [1..n] then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n comb <- sort . uncurry union . (\\[a,b]->(a,b)) . map (map (read :: String -> Int) . words) <$> sequence [getLine, getLine]\n putStrLn $ if comb == [1..n] then \"I become the guy.\" else \"Oh, my keyboard!\""}, {"source_code": "import Data.List\n\nplay :: Int -> [[Int]] -> String\nplay n [xs, ys]\n | (length . group . sort) (xs ++ ys) == n = \"I become the guy.\" \n | otherwise = \"Oh, my keyboard!\"\n\nsolve :: String -> String\nsolve s = play n [xs, ys]\n where l = lines s\n n = read . head $ l\n [xs, ys] = fmap (fmap read . words) . tail $ l\n\nmain :: IO ()\nmain = interact $ solve"}], "src_uid": "044ade01d2de1486735742369227ae1d"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n (BS.unpack <$> readLine)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr =<< solve . evalState parseInput <$> BS.getContents\n\ndata Widget = Widget { name :: String, width :: Integer, height :: Integer }\n | VBox { name :: String, border :: Integer, spacing :: Integer, contains :: [String] }\n | HBox { name :: String, border :: Integer, spacing :: Integer, contains :: [String] }\n\nsolve :: [String] -> String\nsolve seq = unlines $ map (show . calcWidget mapping) (Map.keys mapping)\n where\n mapping = execState (sequence_ $ map simulating seq) Map.empty\n\nsimulating :: String -> State (Map String Widget) ()\nsimulating ('V':'B':'o':'x':' ':name) = modify $ Map.insert name (VBox name 0 0 [])\nsimulating ('H':'B':'o':'x':' ':name) = modify $ Map.insert name (HBox name 0 0 [])\nsimulating ('W':'i':'d':'g':'e':'t':' ':def) = modify $ Map.insert name (Widget name x y)\n where\n (name, xy) = span (/='(') def\n (x, y) = read xy\nsimulating stmt\n | op == \".pack\" = modify $ Map.update (Just . addContains param) name \n | op == \".set_border\" = modify $ Map.update (Just . setBorder (read param)) name \n | op == \".set_spacing\" = modify $ Map.update (Just . setSpacing (read param)) name \n where\n (name, stmt2) = span (/='.') stmt\n (op, stmt3) = span (/='(') stmt2\n param = tail $ init stmt3\n\naddContains chd (VBox name border spacing contains) = VBox name border spacing (chd:contains)\naddContains chd (HBox name border spacing contains) = HBox name border spacing (chd:contains)\n\nsetSpacing spacing (VBox name border _ contains) = VBox name border spacing contains\nsetSpacing spacing (HBox name border _ contains) = HBox name border spacing contains\n\nsetBorder border (VBox name _ spacing contains) = VBox name border spacing contains\nsetBorder border (HBox name _ spacing contains) = HBox name border spacing contains\n\ncalcWidget mapping = (cache Map.!)\n where\n cache = Map.fromList [(names, goName names) | names <- Map.keys mapping]\n\n goName name = go (mapping Map.! name)\n go w@(Widget _ _ _) = w\n go (VBox name _ _ []) = Widget name 0 0\n go (HBox name _ _ []) = Widget name 0 0\n go (VBox name border spacing contains) = Widget name (maximum widths + border * 2) (sum heights + (len - 1) * spacing + border * 2)\n where\n widgets = map (calcWidget mapping) contains\n heights = map height widgets\n widths = map width widgets\n len = genericLength widgets\n\n go (HBox name border spacing contains) = Widget name (sum widths + (len - 1) * spacing + border * 2) (maximum heights + border * 2)\n where\n widgets = map (calcWidget mapping) contains\n heights = map height widgets\n widths = map width widgets\n len = genericLength widgets\n\ninstance Show Widget where\n show (Widget name x y) = name ++ \" \" ++ show x ++ \" \" ++ show y\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n", "positive_code": [{"source_code": "\nimport Text.ParserCombinators.ReadP hiding (get)\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Traversable hiding (mapM)\nimport Data.List\nimport Data.Function\nimport Data.Map(Map, (!))\nimport qualified Data.Map as Map\n-- import Data.MemoTrie\n\ninstance Applicative ReadP where\n pure x = return x\n f <*> x = do\n f' <- f\n x' <- x\n return (f' x')\n\ndata Statement = \n Widget String Integer Integer\n | HBox String\n | VBox String\n | Pack String String\n | SetBorder String Integer\n | SetSpacing String Integer\n deriving (Show)\n\nidentifier = munch (\\c -> isAlpha c || c=='_')\n \ntranslateCommand :: String -> String -> String -> Statement\ntranslateCommand w1 \"pack\" w2 = Pack w1 w2\ntranslateCommand w1 \"set_border\" x = SetBorder w1 (read x)\ntranslateCommand w1 \"set_spacing\" x = SetSpacing w1 (read x)\n\ninteger :: ReadP Integer\ninteger = read <$> munch isDigit\n\nparseStatement = choice\n [\n Widget <$> (string \"Widget \" *> identifier) <*> (char '(' *> integer) <*> (char ',' *> integer <* char ')')\n , HBox <$> (string \"HBox \" *> identifier)\n , VBox <$> (string \"VBox \" *> identifier)\n , translateCommand <$> identifier <*> (char '.' *> identifier) <*> (char '(' *> munch (\\c -> isAlpha c || isDigit c) <* char ')')\n ]\n\ntype Dimensions = (Integer, Integer)\ntype Spacing = Integer\ntype Border = Integer\n\ndata Direction = Vertical | Horisontal\n\ndata Widget = SimpleWidget Dimensions | BoxWidget Direction [String] Spacing Border\n\nexecuteStatement :: Statement -> Map String Widget -> Map String Widget\nexecuteStatement (Widget name x y) = Map.insert name (SimpleWidget (x,y))\nexecuteStatement (HBox name) = Map.insert name (BoxWidget Horisontal [] 0 0)\nexecuteStatement (VBox name) = Map.insert name (BoxWidget Vertical [] 0 0)\nexecuteStatement (Pack box containee) = Map.adjust (addChild containee) box\nexecuteStatement (SetBorder box b) = Map.adjust (setBorder b) box\nexecuteStatement (SetSpacing box b) = Map.adjust (setSpacing b) box\n\naddChild containee (BoxWidget d ch s b) = BoxWidget d (containee : ch) s b\nsetBorder border (BoxWidget d c s _b) = BoxWidget d c s border\nsetSpacing spacing (BoxWidget d c _s b) = BoxWidget d c spacing b\n\nrunScript :: [Statement] -> Map String Widget\nrunScript = foldl (flip executeStatement) Map.empty\n\n\nmemo :: ((String -> InMemo Dimensions) -> (String -> InMemo Dimensions)) -> (String -> InMemo Dimensions)\nmemo f = mf where\n mf k = do\n m <- get\n case Map.lookup k m of\n Nothing -> do\n x <- f mf k\n put $ Map.insert k x m\n return x\n Just x -> return x\n \nput :: Map String Dimensions -> InMemo ()\nput m = InMemo $ \\_ -> ((), m)\n\nget :: InMemo (Map String Dimensions)\nget = InMemo $ \\m -> (m, m)\n \ndata InMemo a = InMemo { runMemo :: Map String Dimensions -> (a, Map String Dimensions) }\n\ninstance Functor InMemo where\n fmap f x = x >>= return . f\ninstance Monad InMemo where\n x >>= f = InMemo $ \\s0 -> let (x', s1) = runMemo x s0 in runMemo (f x') s1\n return x = InMemo $ \\s -> (x, s)\n\nevalInMemo x s = fst $ runMemo x s\n\ncalculateM :: Map String Widget -> (String -> InMemo Dimensions) -> (String -> InMemo Dimensions)\ncalculateM widgets r s = case widgets ! s of\n SimpleWidget d -> return d\n BoxWidget _ [] _ _ -> return (0, 0)\n BoxWidget dir children spacing border -> sw . layout <$> mapM ((sw <$>) . r) children\n where \n layout dims = (ly (map fst dims), ly [maximum $ map snd dims])\n ly xs = sum xs + spacing * (genericLength xs - 1) + border * 2\n sw = swd dir\n swd Horisontal (x, y) = (x, y)\n swd Vertical (x, y) = (y, x)\n\ncalculate :: Map String Widget -> Map String Dimensions\ncalculate widgets = evalInMemo doCalculate Map.empty\n where\n doCalculate :: InMemo (Map String Dimensions)\n doCalculate = Map.fromList <$> mapM (\\(key, _) -> doCalc key >>= \\val -> return (key, val)) (Map.toList widgets)\n doCalc = memo (calculateM widgets)\n\n{-calculate :: Map String Widget -> Map String Dimensions\ncalculate widgets = Map.mapWithKey (\\k v -> mcalc k) widgets\n where\n mcalc = {- memo -} calc\n calc s = -}\n \nmain = do\n n <- read <$> getLine\n script <- (map ((\\[(r, \"\")] -> r) . readP_to_S parseStatement)) <$> replicateM n getLine\n mapM putStrLn $ map (\\(k,(x,y)) -> unwords [k, show x, show y]) $ Map.toList $ calculate $ runScript script"}], "negative_code": [], "src_uid": "258f54f32c6df5390edd804294aad235"} {"source_code": "import Control.Applicative\nimport Data.Graph\n\nmain = do\n n <- readLn :: IO Int\n p <- map read <$> words <$> getLine :: IO [Int]\n let g = buildG (1, n) (zip [1..n] p)\n print (length (components g))\n", "positive_code": [{"source_code": "import Data.Array.IArray\nimport qualified Data.Array.IArray as A\nimport Data.Array.Unboxed\nimport Data.List( nub)\n\nmain = do\n n_ <- readLn::IO Int\n connections_ <- return . map read . words =<< getLine\n let\n\tary = A.listArray (1,n_) connections_:: (UArray Int Int)\n\tbackRt ix = let\n\t\t\tto = ary!ix\n\t\t in\n\t\t\tif to < ix\n\t\t\t then backRt to\n\t\t\t else ix\n\tnumTrees = let arrayList = A.elems ary\n\t\t in length . nub $ map backRt arrayList\n print numTrees\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array\nimport Data.Foldable\nimport qualified Data.Set as S\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = map readInt . B.words\n\nmain = do \n n <- readInt <$> B.getLine\n ps <- listArray (1, n) . readInts <$> B.getLine\n print . S.size . foldl' (\\s (i, v) -> if ps!v == i then S.insert (min v i) s else s) S.empty . assocs $ ps\n"}], "negative_code": [], "src_uid": "6d940cb4b54f63a7aaa82f21e4c5b994"} {"source_code": "import Control.Monad\nimport Data.Int (Int64)\nimport Data.List (sort)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- getLine\n print $ solve $ map fst $ filter ((== '*') . snd) $ zip [1 .. n] a\n\nsolve :: [Int64] -> Int64\nsolve [] = 0\nsolve xs' = sum $ map (abs . (m -)) xs\n where\n n = length xs'\n xs = sort $ zipWith ((-) . fromIntegral) [1 .. n] xs'\n m = xs !! div n 2\n", "positive_code": [{"source_code": "import Control.Arrow\r\nimport Data.List(sort, group)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf k [] = []\r\nchunksOf k xs = let (g, xs') = splitAt k xs in g : chunksOf k xs'\r\n\r\ntype LL = Integer\r\n\r\nmain = interact $ \r\n lines >>> drop 1 >>> chunksOf 2\r\n >>> map ((!! 1) >>> solve >>> show)\r\n >>> unlines\r\n\r\nsolve :: String -> LL\r\nsolve s = \r\n let xs = zipWith (-) [i | (c, i) <- zip s [0..], c == '*'] [0..]\r\n m = xs !! (length xs `div` 2)\r\n in sum $ map (abs . (m -)) xs\r\n \r\n"}], "negative_code": [], "src_uid": "e094a3451b8b28be90cf54a4400cb916"} {"source_code": "import Data.Function (on)\nimport Data.Functor ((<$>))\nimport Data.List (groupBy, inits, permutations, sortBy)\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nmain :: IO ()\nmain = printSolution =<< solve <$> tail <$> map read <$> words <$> getContents\n\nsolve :: [Integer] -> Maybe [[Integer]]\nsolve = listToMaybe . drop 3 . inits . f . map (permutations . map fst)\n . groupBy ((==) `on` snd) . sortBy (compare `on` snd) . zip [1..]\n\nf :: [[[a]]] -> [[a]]\nf [] = []\nf [xs] = xs\nf (xs:xss) = [ x ++ xs' | x <- xs, xs' <- f xss ]\n\nprintSolution :: Show a => Maybe [[a]] -> IO ()\nprintSolution xs = putStrLn (maybe \"NO\" (const \"YES\") xs)\n >> mapM_ (putStrLn . unwords . map show) (fromMaybe [] xs)\n", "positive_code": [{"source_code": "import Data.List\nmain = interact $ solve .map read. drop 1.words\nfindA index n xs acc\n\t|index>=n || length acc > 1 = acc\n\t|otherwise = if (fst $head xs)==(fst $head $tail xs) then findA (index+1) n (tail xs) (index:acc) else findA (index+1) n (tail xs) acc \nprintAns xs equals= \n\t(\"YES\\n\"++p xs++\"\\n\")++(p $ swap xs $head equals)++\"\\n\"++(p $ swap xs $last equals)\n\twhere p=unwords.map show.map snd \n \t swap ys k=take (k-1) ys ++ [xs!!k, xs!!(k-1)]++drop (k+1) ys\nsolve :: [Int]->String\nsolve xs = \n\tif length equals>1 then printAns ys equals else \"NO\" \n\twhere ys=sort $ zip xs [1..]\n\t equals=findA 1 (length xs) ys []\n"}, {"source_code": "import Data.Ord (comparing)\nimport Data.List (groupBy, sortBy, transpose, permutations)\nimport Data.Function (on)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- (fmap (map read . words) getLine) :: IO [Int]\n let res = calc xs\n putStr res\n\nhas3 :: [[a]] -> Bool\nhas3 = any ((<=3) . length) \n\nhas2twice :: [[a]] -> Bool\nhas2twice = (>=2) . length . filter ((<=3) . length)\n\ncalc :: [Int] -> String\ncalc xs\n | canDo = \"YES\\n\" ++ output\n | otherwise = \"NO\\n\"\n where\n ys = zip [1..] $ xs\n zs = groupBy (on (==) snd) $ sortBy (comparing snd) ys\n res = take 3 $ findAll zs\n canDo = length res == 3\n output = unlines res\n\nfindAll :: [[(Int,Int)]] -> [String]\nfindAll = map fmt . ((foldr (\\xs ys -> [x++y|x<-xs,y<-ys]) [[]])::[[[(Int,Int)]]]->[[(Int,Int)]]) . ((map permutations)::[[(Int,Int)]]->[[[(Int,Int)]]])\n\nfmt :: [(Int,Int)] -> String\nfmt = unwords . map show . map fst\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . unlines . getAns . getIntArray\n\ngetAns :: [Int] -> [String]\ngetAns (n:xs) = let anss = gettop3 $ groupA $ zip xs [1..n]\n\t\t\t\tin if (length anss) < 3 then [\"NO\"] else [\"YES\"] ++ (map (unwords . map show)) anss\n\ngroupA :: [(Int, Int)] -> [[Int]]\ngroupA = map (map (\\(_, x) -> x)) . groupBy (\\(x, _) (y, _) -> x == y) . sort\n\ngettop3 :: [[Int]] -> [[Int]]\ngettop3 = (map concat . take 3 . mapM permutations)\n\n"}, {"source_code": "import Data.List (sort, groupBy, permutations)\nimport Debug.Trace\n\nsolve :: [Int] -> [[Int]]\nsolve x =\n take 3 $ crossProduct groupings\n where\n track q = trace (show q) q\n groupings = map (map snd) . groupBy (\\a -> \\b -> fst a == fst b) . sort . zip x $ [1..]\n crossProduct (grouping:rst) =\n cross grouping (crossProduct rst)\n crossProduct [] = []\n cross grouping [] = permutations grouping\n cross grouping solns =\n [a ++ soln | a <- permutations grouping, soln <- solns]\n\nshowSoln :: [[Int]] -> String\nshowSoln x\n | length x /= 3 = \"NO\"\n | otherwise =\n \"YES\\n\" ++ (unlines . map (unwords . map show) $ x)\n\nmain = do\n getLine\n putStrLn . showSoln . solve . map read . words =<< getContents\n"}, {"source_code": "import Data.Function (on)\nimport Data.Functor ((<$>))\nimport Data.List (groupBy, inits, permutations, sortBy)\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nmain :: IO ()\nmain = printSolution =<< solve <$> tail <$> map read <$> words <$> getContents\n\nsolve :: [Integer] -> Maybe [[Integer]]\nsolve = listToMaybe . drop 3 . inits . map concat . mapM (permutations . map fst)\n . groupBy ((==) `on` snd) . sortBy (compare `on` snd) . zip [1..]\n\nprintSolution :: Show a => Maybe [[a]] -> IO ()\nprintSolution xs = putStrLn (maybe \"NO\" (const \"YES\") xs)\n >> mapM_ (putStrLn . unwords . map show) (fromMaybe [] xs)\n"}], "negative_code": [], "src_uid": "fdfc1e690eeee6f50e2a024bf3f841e8"} {"source_code": "module Main where\r\nimport Control.Monad \r\n\r\nsign::Bool->Int->Int\r\nsign True x\r\n |odd x=x+1\r\n |otherwise=x-1\r\nsign False x\r\n |odd x=x-1\r\n |otherwise=x+1\r\npt::Int->IO()\r\npt=putStrLn.show\r\n\r\nsolve::Int->Bool->[IO()]\r\nsolve 1 True =[pt 2] \r\nsolve n True =(pt (sign True n)):(solve (n-1) True)\r\n\r\n\r\nsolve 1 False =[pt 1] \r\nsolve n False =(pt (sign False n)):(solve (n-1) False)\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do \r\n list<-getLine\r\n let n=read list::Int \r\n let test=even n\r\n sequence$reverse (solve n test)", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t ri\r\n mapM_ (putStrLn.showL.solve) tcs\r\n\r\nshowL = unwords . map show\r\n\r\nsolve [n] = map (fixOrder n) [1..n]\r\nsolve _ = error \"Bad input single int\"\r\n\r\nfixOrder n | (even n) = f\r\n | otherwise = g\r\n where\r\n f x | (even x) = x-1\r\n | otherwise = x+1\r\n\r\n g 1 = 1\r\n g x | (even x) = x+1\r\n | otherwise = x-1\r\n"}], "negative_code": [], "src_uid": "be3295b4d43a11ee94022b103f4221a5"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Prelude\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport Control.Monad\nimport Data.Ratio\nimport Data.Int\nimport Data.Functor\nimport Control.Monad.ST.Safe\nimport Data.STRef\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\n\n\nsolve :: Int -> Int -> [Int] -> ST s [Int]\nsolve n m lst = do\n cnt <- A.newArray (1, n) 0 :: ST s (A.STUArray s Int Int)\n contests <- A.newArray (1, m) 0 :: ST s (A.STUArray s Int Int)\n answer <- forM lst $ \\elem -> do\n cnt_val <- A.readArray cnt elem\n A.writeArray cnt elem (cnt_val + 1)\n contests_val <- A.readArray contests (cnt_val + 1)\n A.writeArray contests (cnt_val + 1) (contests_val + 1)\n return $ if contests_val == n - 1 then 1 else 0\n return answer\n \nmain :: IO ()\nmain = do\n ([n, m] :: [Int]) <- (map (fst . fromJust . B8.readInt) . B8.words) <$> B8.getLine\n (arr :: [Int]) <- (map (fst . fromJust . B8.readInt) . B8.words) <$> B8.getLine\n let answer = runST $ solve n m arr\n forM_ answer $ printf \"%d\"\n printf \"\\n\"", "positive_code": [{"source_code": "-- Codeforces Round #532 (A), Contest 1100, Problem set ?.\n-- UNDONE\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n xs <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let mdn = m `div` n\n probsForRound <- A.newArray (0,mdn) n :: IO (IOUArray Int Int)\n probsWithDiff <- A.newArray (1,n) 0 :: IO (IOUArray Int Int)\n forM_ xs $ \\x -> do\n px <- A.readArray probsWithDiff x\n A.writeArray probsWithDiff x (px+1)\n if px <= mdn then do\n rest <- A.readArray probsForRound px\n A.writeArray probsForRound px (rest-1)\n putChar $ if rest <= 1 then '1' else '0'\n else putChar '0'\n putStrLn \"\"\n \n \n"}, {"source_code": "import Data.Array.ST.Safe\nimport Data.Array.IArray\nimport Data.STRef\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.ST\nmain = putStrLn . solve . map readI . B.words =<< B.getContents\nsolve (n:m:as) = elems $ runSTUArray $ do\n t <- newArray (1,n) 0 :: ST s (STUArray s Int Int)\n r <- newArray_ (1,m)\n c <- newSTRef 0\n forM_ (zip [1..] as) $ \\(i,a) -> do\n prev <- readArray t a\n when (prev == 0) $ modifySTRef' c succ\n writeArray t a (prev + 1)\n c' <- readSTRef c\n writeArray r i $ if c' == n then '1' else '0'\n when (c' == n) $ do\n forM_ [1..n] $ \\j -> writeArray t j . pred =<< readArray t j\n writeSTRef c . length . filter (> 0) =<< getElems t\n return r\nreadI b = i where Just (i,_) = B.readInt b\n"}], "negative_code": [], "src_uid": "2070955288b2e2cdbae728d8e7ce78ab"} {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n check :: [Int] -> String\n check xs\n | length xs < 3 = \"YES\"\n | length xs == 3 =\n let (a:b:c:[]) = sort xs\n in case b - a == c - b of\n True -> \"YES\"\n False -> \"NO\"\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . (map readInt) . words\n let ys = S.toList $ S.fromList xs\n ans = case length ys <= 3 of\n False -> \"NO\"\n True -> check ys\n putStrLn ans\n", "positive_code": [{"source_code": "import Data.List(nub,sort)\nmain = do\n getLine\n aaa <- return . map read . words =<< getLine\n let kinds [] _ = []\n\tkinds _ 4 = []\n\tkinds (c:cs) n\t= c:remain\n\t where\t remain = kinds [x| x<-cs, x/=c] $ n+1\n\twashed = kinds aaa 0\n case washed \tof\n [_,_,_]\t\t-> let\t[i,j,k] = sort washed\n\t\t\t\t(half,m) = divMod (k-i) 2\n\t\t\t in\tif m==0 && half+i==j\n\t\t\t\t then putStr \"YES\"\n\t\t\t\t else putStr \"NO\"\n [_,_]\t\t-> putStr \"YES\"\n [_]\t\t-> putStr \"YES\"\n _\t\t\t-> putStr \"NO\"\n"}, {"source_code": "import Data.List\n\nmain = getContents >>= putStrLn . solve . map head . group . sort . map (read :: String -> Int) . tail . words\n\nsolve [a, b, c] = if b - a == c - b then \"YES\" else \"NO\"\nsolve as = if length as < 3 then \"YES\" else \"NO\"\n"}, {"source_code": "-- ID: 714B (Filya and Homework)\n-- URL: http://codeforces.com/problemset/problem/714/B\n\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\n\nmain = do\n n <- getInt\n xs <- (map read . take n . words) `fmap` getContents :: IO [Int]\n putStrLn $ (judge . collect) xs\n\ncollect xs = f xs [] where\n f [] acc = Just acc\n f (x:xs) acc\n | x `elem` acc = f xs acc\n | length acc == 3 = Nothing\n | otherwise = f xs (x:acc)\n\njudge Nothing = \"NO\"\njudge (Just [x]) = \"YES\"\njudge (Just [x,y]) = \"YES\"\njudge (Just [x,y,z])\n | arithmeticSeq (sort [x,y,z]) = \"YES\"\n | otherwise = \"NO\"\n\narithmeticSeq [x,y,z]\n | y-x == z-y = True\n | otherwise = False\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = output . solve [] . map read . tail . words =<< getContents\n\noutput :: Bool -> IO ()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [Int] -> [Int] -> Bool\nsolve final [] | length final <= 2 = True\n | length final == 3 = let [a, b, c] = sort final\n in a + c == b + b\nsolve s (a:ax) | a `elem` s = solve s ax\n | length s == 3 = False\n | otherwise = solve (a:s) ax\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = output . solve [] . map read . tail . words =<< getContents\n\noutput :: Bool -> IO ()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [Int] -> [Int] -> Bool\nsolve final [] | length final == 1 = True\n | length final == 2 = even ((head final) + (final !! 1))\n | length final == 3 = let [a, b, c] = sort final\n in a + c == b + b\nsolve s (a:ax) | a `elem` s = solve s ax\n | length s == 3 = False\n | otherwise = solve (a:s) ax\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . (map readInt) . words\n let happenable = (<=3) $ length $ S.toList $ S.fromList xs\n ans = case happenable of\n True -> \"YES\"\n False -> \"NO\"\n putStrLn ans\n"}, {"source_code": "import Data.List(nub,sort)\nmain = do\n getLine\n as <- return . map read . words =<< getLine\n case sort $ nub as\tof\n [x,y,z]\t\t-> if even (z-x)\n\t\t\t then putStr \"YES\"\n\t\t\t else putStr \"NO\"\n [x,y]\t\t-> if even (y-x)\n\t\t\t then putStr \"YES\"\n\t\t\t else putStr \"NO\"\n [x]\t\t-> putStr \"YES\"\n _\t\t\t-> putStr \"NO\"\n"}, {"source_code": "import Data.List(nub,sort)\nmain = do\n getLine\n aaa <- return . map read . words =<< getLine\n let kinds [] _ = []\n\tkinds (c:cs) n\n\t | n==4\t= []\n\t | otherwise\t= c:(kinds [x| x<-cs, x/=c] (n+1))\n\tks = kinds aaa 0\n case length ks \tof\n 3\t\t-> let\t[i,j,k] = sort ks\n\t\t in\tif even (k-i)\n\t\t\t then putStr \"YES\"\n\t\t\t else putStr \"NO\"\n 2\t\t-> putStr \"YES\"\n 1\t\t-> putStr \"YES\"\n _\t\t-> putStr \"NO\"\n"}], "src_uid": "27f837609b2777cefccb13aa4596d91c"} {"source_code": "main = interact $ unlines . solve . lines\n\nsolve (nl:cs) = map process $ drop n cs\n where n = (read . head . words) nl\n table = foldl tolist [] $ take n cs\n tolist acc x = let ws = words x in (last ws ++ \";\", head ws):acc\n process s = case lookup (last $ words s) table of Just ans -> s ++ \" #\" ++ ans\n", "positive_code": [{"source_code": "import qualified Data.Map as Map\nimport Control.Monad\n\nf::[String]->[(String,String)]\nf []=[]\nf (s:strs)=let (a:b:[])=words s\n in (b++\";\",a):f strs\n\nf2::[String]->Map.Map String String->[String]\nf2 [] _=[]\nf2 (s:strs) ms=let (a:b:[])=words s\n Just c=Map.lookup b ms\n in (s++\" #\"++c):(f2 strs) ms\n\nmain = do\n e1<-getLine\n let (n:m:[])=map read (words e1)::[Int]\n e2<-replicateM n getLine\n e3<-replicateM m getLine\n let xs=f e2\n mapM_ putStrLn $ f2 e3 $ Map.fromList xs"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport Control.Monad\nimport qualified Data.Map.Strict as M\nmain = do\n [n, m] <- fmap (map read . words) getLine\n s <- M.fromList `fmap` replicateM n (fmap ((\\[a, b] -> (b, a)) . words) getLine)\n replicateM m $ putStrLn . (\\l -> let [_, flip M.lookup s . init -> Just n] = words l in l ++ \" #\" ++ n) =<< getLine\n"}], "negative_code": [], "src_uid": "94501cd676a9214a59943b8ddd1dd31b"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.Array.ST(runSTArray, STArray)\r\nimport Data.Array.IO(IOArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, foldM, mapM, filterM, forM) -- foldM est un foldl\r\nimport Data.Maybe\r\nimport Data.Int\r\n\r\n\r\nbezout :: (Integral n) => n -> n -> (n, n)\r\nbezout _ 0 = (1, 0)\r\nbezout _ 1 = (0, 1)\r\nbezout a b = (y, x-y*q)\r\n\twhere\r\n\t\t(q, r) = a `divMod` b\r\n\t\t(x, y) = bezout b r\r\n\r\nsumDigit 0 = 0\r\nsumDigit x = mod x 10 + sumDigit (div x 10)\r\n\r\ngcdSum :: Integer -> Integer \r\ngcdSum x = let (a, b) = bezout x y in x*a+y*b where y = sumDigit x\r\n\r\nsolve :: Integer -> Integer\r\nsolve n \r\n\t| gcdSum n == 1 = solve (n+1)\r\n\t| otherwise = n\r\n\r\n\r\nplotResult :: Integer -> IO ()\r\nplotResult = print\r\n\r\n\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nsumDigits :: Integer -> Integer \r\nsumDigits x\r\n | x < 10 = x\r\n | otherwise = sumDigits (div x 10) + mod x 10\r\n\r\nsolve :: Integer -> Integer \r\nsolve x = if gcd x (sumDigits x) == 1 then solve (x+1) else x\r\n\r\nmain = do\r\n line <- getLine\r\n let tc = read line :: Integer\r\n ans <- forM_ [1..tc] (\\a -> do\r\n line <- getLine\r\n let x = read line :: Integer\r\n print (solve x)\r\n )\r\n return ()"}], "negative_code": [], "src_uid": "204e75827b7016eb1f1fbe1d6b60b03d"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array\nimport Data.List\nimport Data.Ix\n\ndata SegTree w a = SegTree w (SegNode a) deriving Show\ndata SegNode a = SegLeave a | SegBranch a (SegNode a) (SegNode a) deriving Show\n\nnewSegTree :: (Integral w, Num v) => w -> v -> SegTree w v\nnewSegTree w v =\n let newSegNode w v =\n if w == 1\n then SegLeave v\n else let\n w1 = w `div` 2\n w2 = w - w1\n in SegBranch (v * (fromIntegral w)) (newSegNode w1 v) (newSegNode w2 v)\n in SegTree w $ newSegNode w v\n\nupdateSegTree :: (Integral i, Num a) => SegTree i a -> i -> a -> SegTree i a\nupdateSegTree (SegTree w n) i v =\n let updateSegNode (SegLeave v0) w i v = SegLeave (v0+v)\n updateSegNode (SegBranch v0 left right) w i v =\n let w1 = w `div` 2\n w2 = w - w1\n (left', right') = if i < w1\n then (updateSegNode left w1 i v, right)\n else (left, updateSegNode right w2 (i-w1) v)\n in SegBranch (v0+v) left' right'\n in SegTree w (updateSegNode n w i v)\n\npickSegTree :: (Integral i, Num a) => SegTree i a -> i -> a\npickSegTree (SegTree w n) i =\n let pickSegNode (SegLeave v) _ _ = v\n pickSegNode (SegBranch v left right) w i =\n let w1 = w `div` 2\n w2 = w - w1\n in if i < w1\n then pickSegNode left w1 i\n else pickSegNode right w2 (i-w1)\n in pickSegNode n w i\n\nleftHalfSegTree :: (Integral i, Num a) => SegTree i a -> i -> a\nleftHalfSegTree (SegTree w n) i =\n let leftHalfSegNode (SegLeave v) w i = if i < 0\n then 0\n else v\n leftHalfSegNode (SegBranch v left right) w i =\n let w1 = w `div` 2\n w2 = w - w1\n in if i < 0\n then 0\n else if i < w\n then leftHalfSegNode left w1 i + leftHalfSegNode right w2 (i-w1)\n else v\n in leftHalfSegNode n w i\n\nshowName n = case (n-1) `mod` 3 of\n 0 -> \"Carrots\"\n 1 -> \"Kiwis\"\n 2 -> \"Grapes\"\n\nmain = do\n [n, m, k, t] <- ( map read . words ) `liftM` getLine\n\n let seg = newSegTree (n*m) 1\n --putStrLn $ show seg\n\n seg' <-iterate (\\seg0' -> do\n seg0 <- seg0'\n [a, b] <- ( map read . words ) `liftM` getLine\n return $ updateSegTree seg0 ((a-1)*m+(b-1)) (-1)\n ) (return seg) !! k\n --putStrLn $ show seg'\n\n replicateM_ t $ do\n [i, j] <- ( map read . words ) `liftM` getLine\n let p = (i-1)*m+(j-1)\n\n if pickSegTree seg' p == 0\n then putStrLn \"Waste\"\n else putStrLn $ showName $ leftHalfSegTree seg' p\n", "positive_code": [{"source_code": "nth :: Int -> [(Int, Int)] -> Int -> Int -> Int\nnth m block i j\n\t| elem (i, j) block = 3\n\t| otherwise = (m * (i-1) + (j-1) - (length . filter (\\(x,y) -> x < i || x == i && y < j)) block) `mod` 3\n\ngetLines :: Int -> IO [(Int, Int)]\ngetLines 0 = return []\ngetLines n = do x <- getLine >>= return . (\\x -> (head x, last x)) . map read . words; xs <- getLines (n-1); return (x:xs)\n\nmain = do\n\t[n,m,k,t] <- getLine >>= return . map read . words :: IO [Int]\n\tblock <- getLines k\n\tquery <- getLines t\n\t(putStr . unlines . map (\\i -> [\"Carrots\", \"Kiwis\", \"Grapes\", \"Waste\"] !! i)) [ nth m block x y | (x,y) <- query ]\n"}, {"source_code": "import Data.List\n\nmain = interact $ unlines . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> [String]\nsolve ((n:m:k:t:_):xs) = map (f m wastes) queries\n where\n wastes = sort $ take k xs\n queries = take t $ drop k xs\n\nf :: Int -> [[Int]] -> [Int] -> String\nf m wastes query@[x,y]\n | not (null b) && head b == query = \"Waste\"\n | otherwise = [\"Carrots\", \"Kiwis\", \"Grapes\"] !! rem (x*m-m+y-1-length a) 3\n where\n (a, b) = span (< query) wastes\n"}, {"source_code": "import List\n\ntype Cell = (Int, Int)\n\nnumber :: (Int, Int) -> Int -> Cell -> Int\nnumber range cntEmpty cell = (fst cell - 1) * snd range + snd cell - cntEmpty\n\nnumberCell :: (Int, Int) -> [Cell] -> Cell -> Int\nnumberCell range emptyCells cell = numberCell' range 0 emptyCells cell\n where\n numberCell' range cntEmpty [] cell = number range cntEmpty cell\n numberCell' range cntEmpty (ec:ecs) cell\n | ec < cell = numberCell' range (cntEmpty + 1) ecs cell\n | ec > cell = numberCell' range cntEmpty [] cell\n | otherwise = 0\n \n \nans :: Int -> String\nans 0 = \"Waste\"\nans 1 = \"Carrots\"\nans 2 = \"Kiwis\"\nans 3 = \"Grapes\"\nans n = ans (mod (n - 1) 3 + 1)\n\n\nprintAns :: [Int] -> IO ()\nprintAns [] = return ()\nprintAns (x:xs) = do\n putStrLn $ ans x\n printAns xs\n \nreadCell :: Int -> IO Cell\nreadCell _ = do\n line <- getLine\n let [a, b] = map read $ words line\n return (a, b)\n \nmain = do\n line <- getLine\n let [n, m, k, t] = map read $ words line\n emptyCells <- sequence (map readCell [1..k])\n cells <- sequence (map readCell [1..t])\n printAns (map (numberCell (n, m) (sort emptyCells)) cells)\n "}, {"source_code": "{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, ImplicitParams #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n-- import qualified Data.Map as Map\nimport qualified Data.IntSet as Set\n\nmain :: IO ()\nmain = do\n _ :: Int <- input\n m :: Int <- input\n k :: Int <- input\n t :: Int <- input\n let checkWasteCells acc !i | i >= k = return acc\n | otherwise = do\n a :: Int <- input\n b :: Int <- input\n checkWasteCells (Set.insert ((a - 1) * m + (b - 1)) acc) (i + 1)\n wasteCells <- checkWasteCells Set.empty 0\n let a = listArray (0, k - 1) (Set.toList wasteCells) :: UArray Int Int\n candidates = listArray (0, 2) [\"Carrots\", \"Kiwis\", \"Grapes\"] :: Array Int String\n rep t $ \\_ -> do\n i :: Int <- input\n j :: Int <- input\n let !v = (i - 1) * m + (j - 1)\n if Set.member v wasteCells\n then output' (\"Waste\" :: String)\n else do\n let loop !n | n < k, a ! n <= v = loop (n + 1)\n | otherwise = do\n let idx = (v - n) `mod` 3\n output' $ candidates ! idx\n loop 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--------------------------------------------------\n-- Imported C functions\n--------------------------------------------------\n#define BUFMAX (100005)\n\ntype BString = BS.ByteString\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr Int -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i64 :: CString -> Ptr Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_f :: CString -> Ptr Float -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_s :: CString -> CString -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i :: CString -> Int -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i64 :: CString -> Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_d :: CString -> Double -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: CString -> CString -> IO ()\n\nfmt_i, fmt_i64, fmt_f, fmt_d, fmt_s :: CString\nfmt_i = unsafePerformIO $ newCString \"%d\"\nfmt_i64 = unsafePerformIO $ newCString \"%I64d\"\nfmt_f = unsafePerformIO $ newCString \"%f\"\nfmt_d = unsafePerformIO $ newCString \"%.16f\"\nfmt_s = unsafePerformIO $ newCString \"%s\"\n{-# NOINLINE fmt_i #-}\n{-# NOINLINE fmt_i64 #-}\n{-# NOINLINE fmt_f #-}\n{-# NOINLINE fmt_d #-}\n{-# NOINLINE fmt_s #-}\n\nptr_i :: Ptr Int\nptr_i = unsafePerformIO malloc\nptr_i64 :: Ptr Int64\nptr_i64 = unsafePerformIO malloc\nptr_f :: Ptr Float\nptr_f = unsafePerformIO malloc\nptr_d :: Ptr Double\nptr_d = unsafePerformIO malloc\nptr_s :: CString\nptr_s = unsafePerformIO $ mallocArray BUFMAX\n{-# NOINLINE ptr_i #-}\n{-# NOINLINE ptr_i64 #-}\n{-# NOINLINE ptr_f #-}\n{-# NOINLINE ptr_d #-}\n{-# NOINLINE ptr_s #-}\n\nclass Input a where\n input :: IO a\n\ninstance Input Int where\n input = c_scanf_i fmt_i ptr_i >> peek ptr_i\ninstance Input Int64 where\n input = c_scanf_i64 fmt_i64 ptr_i64 >> peek ptr_i64\ninstance Input Integer where\n input = toInteger <$> (input :: IO Int64)\ninstance Input Double where\n input = c_scanf_f fmt_f ptr_f >> realToFrac <$> peek ptr_f\ninstance Input String where\n input = c_scanf_s fmt_s ptr_s >> peekCString ptr_s\ninstance Input BString where\n input = c_scanf_s fmt_s ptr_s >> BS.packCString ptr_s\n\nclass Output a where\n output_ :: a -> IO ()\n output :: a -> IO ()\n output = (>> space ) . output_\n output' :: a -> IO ()\n output' = (>> newline) . output_\n\ninstance Output Int where\n output_ = c_printf_i fmt_i\ninstance Output Int64 where\n output_ = c_printf_i64 fmt_i64\ninstance Output Integer where\n output_ = output_ . show\ninstance Output Double where\n output_ = c_printf_d fmt_d\ninstance Output String where\n output_ = flip withCString (c_printf_s fmt_s)\ninstance Output BString where\n output_ = flip BS.useAsCString (c_printf_s fmt_s)\n\nspace :: IO ()\nspace = output_ (\" \" :: String)\n\nnewline :: IO ()\nnewline = output_ (\"\\n\" :: String)\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !begin !end k = loop begin\n where loop !i | i >= end = return ()\n | otherwise = k i >> loop (i + 1)\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep = for 0\n\n"}], "negative_code": [{"source_code": "nth :: Int -> [(Int, Int)] -> Int -> Int -> Int\nnth m block i j\n\t| elem (i, j) block = 3\n\t| otherwise = (m * i + j - (length . filter (\\(x,y) -> x < i || x == i && y < j)) block) `mod` 3\n\ngetLines :: Int -> IO [(Int, Int)]\ngetLines 0 = return []\ngetLines n = do x <- getLine >>= return . (\\x -> (head x, last x)) . map read . words; xs <- getLines (n-1); return (x:xs)\n\nmain = do\n\t[n,m,k,t] <- getLine >>= return . map read . words :: IO [Int]\n\tblock <- getLines k\n\tquery <- getLines t\n\t(putStr . unlines . map (\\i -> [\"Carrots\", \"Kiwis\", \"Grapes\", \"Waste\"] !! i)) [ nth m block x y | (x,y) <- query ]\n"}, {"source_code": "import List\n\ntype Cell = (Int, Int)\n\nnumber :: (Int, Int) -> Int -> Cell -> Int\nnumber range cntEmpty cell = (fst cell - 1) * snd range + snd cell - cntEmpty\n\nnumberCell :: (Int, Int) -> [Cell] -> Cell -> Int\nnumberCell range emptyCells cell = numberCell' range 0 emptyCells cell\n where\n numberCell' range cntEmpty [] cell = number range cntEmpty cell\n numberCell' range cntEmpty (ec:ecs) cell\n | ec < cell = numberCell' range (cntEmpty + 1) ecs cell\n | ec > cell = numberCell' range cntEmpty [] cell\n | otherwise = 0\n \n \nans :: Int -> String\nans 0 = \"Waste\"\nans 1 = \"Carrots\"\nans 2 = \"Kiwis\"\nans 3 = \"Grapes\"\nans n = ans (mod (n - 1) 3 + 1)\n\n\nprintAns :: [Int] -> IO ()\nprintAns [] = return ()\nprintAns (x:xs) = do\n print $ ans x\n printAns xs\n \nreadCell :: Int -> IO Cell\nreadCell _ = do\n line <- getLine\n let [a, b] = map read $ words line\n return (a, b)\n \nmain = do\n line <- getLine\n let [n, m, k, t] = map read $ words line\n emptyCells <- sequence (map readCell [1..k])\n cells <- sequence (map readCell [1..t])\n printAns (map (numberCell (n, m) (sort emptyCells)) cells)\n "}, {"source_code": "{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, ImplicitParams #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n-- import qualified Data.Map as Map\nimport qualified Data.IntSet as Set\n\nmain :: IO ()\nmain = do\n _ :: Int <- input\n m :: Int <- input\n k :: Int <- input\n t :: Int <- input\n let checkWasteCells acc !i | i >= k = return acc\n | otherwise = do\n a :: Int <- input\n b :: Int <- input\n checkWasteCells (Set.insert ((a - 1) * m + (b - 1)) acc) (i + 1)\n wasteCells <- checkWasteCells Set.empty 0\n let a = listArray (0, k - 1) (Set.toList wasteCells) :: UArray Int Int\n candidates = listArray (0, 2) [\"Carrots\", \"Kiwis\", \"Grapes\"] :: Array Int String\n rep t $ \\_ -> do\n i :: Int <- input\n j :: Int <- input\n let !v = (i - 1) * m + (j - 1)\n if Set.member v wasteCells\n then output' (\"Waste\" :: String)\n else do\n let loop !n | n < k, v <= a ! n = loop (n + 1)\n | otherwise = do\n let idx = (v - (n + 1)) `mod` 3\n output' $ candidates ! idx\n loop 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--------------------------------------------------\n-- Imported C functions\n--------------------------------------------------\n#define BUFMAX (100005)\n\ntype BString = BS.ByteString\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr Int -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i64 :: CString -> Ptr Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_f :: CString -> Ptr Float -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_s :: CString -> CString -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i :: CString -> Int -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i64 :: CString -> Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_d :: CString -> Double -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: CString -> CString -> IO ()\n\nfmt_i, fmt_i64, fmt_f, fmt_d, fmt_s :: CString\nfmt_i = unsafePerformIO $ newCString \"%d\"\nfmt_i64 = unsafePerformIO $ newCString \"%I64d\"\nfmt_f = unsafePerformIO $ newCString \"%f\"\nfmt_d = unsafePerformIO $ newCString \"%.16f\"\nfmt_s = unsafePerformIO $ newCString \"%s\"\n{-# NOINLINE fmt_i #-}\n{-# NOINLINE fmt_i64 #-}\n{-# NOINLINE fmt_f #-}\n{-# NOINLINE fmt_d #-}\n{-# NOINLINE fmt_s #-}\n\nptr_i :: Ptr Int\nptr_i = unsafePerformIO malloc\nptr_i64 :: Ptr Int64\nptr_i64 = unsafePerformIO malloc\nptr_f :: Ptr Float\nptr_f = unsafePerformIO malloc\nptr_d :: Ptr Double\nptr_d = unsafePerformIO malloc\nptr_s :: CString\nptr_s = unsafePerformIO $ mallocArray BUFMAX\n{-# NOINLINE ptr_i #-}\n{-# NOINLINE ptr_i64 #-}\n{-# NOINLINE ptr_f #-}\n{-# NOINLINE ptr_d #-}\n{-# NOINLINE ptr_s #-}\n\nclass Input a where\n input :: IO a\n\ninstance Input Int where\n input = c_scanf_i fmt_i ptr_i >> peek ptr_i\ninstance Input Int64 where\n input = c_scanf_i64 fmt_i64 ptr_i64 >> peek ptr_i64\ninstance Input Integer where\n input = toInteger <$> (input :: IO Int64)\ninstance Input Double where\n input = c_scanf_f fmt_f ptr_f >> realToFrac <$> peek ptr_f\ninstance Input String where\n input = c_scanf_s fmt_s ptr_s >> peekCString ptr_s\ninstance Input BString where\n input = c_scanf_s fmt_s ptr_s >> BS.packCString ptr_s\n\nclass Output a where\n output_ :: a -> IO ()\n output :: a -> IO ()\n output = (>> space ) . output_\n output' :: a -> IO ()\n output' = (>> newline) . output_\n\ninstance Output Int where\n output_ = c_printf_i fmt_i\ninstance Output Int64 where\n output_ = c_printf_i64 fmt_i64\ninstance Output Integer where\n output_ = output_ . show\ninstance Output Double where\n output_ = c_printf_d fmt_d\ninstance Output String where\n output_ = flip withCString (c_printf_s fmt_s)\ninstance Output BString where\n output_ = flip BS.useAsCString (c_printf_s fmt_s)\n\nspace :: IO ()\nspace = output_ (\" \" :: String)\n\nnewline :: IO ()\nnewline = output_ (\"\\n\" :: String)\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !begin !end k = loop begin\n where loop !i | i >= end = return ()\n | otherwise = k i >> loop (i + 1)\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep = for 0\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, ImplicitParams #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n-- import qualified Data.Map as Map\nimport qualified Data.IntSet as Set\n\nmain :: IO ()\nmain = do\n _ :: Int <- input\n m :: Int <- input\n k :: Int <- input\n t :: Int <- input\n let checkWasteCells acc !i | i > k = return acc\n | otherwise = do\n a :: Int <- input\n b :: Int <- input\n checkWasteCells (Set.insert (a * m + b) acc) (i + 1)\n wasteCells <- checkWasteCells Set.empty 1\n let a = listArray (1, k) (Set.toList wasteCells) :: UArray Int Int\n candidates = listArray (0, 2) [\"Carrots\", \"Kiwis\", \"Grapes\"] :: Array Int String\n rep t $ \\_ -> do\n i :: Int <- input\n j :: Int <- input\n let !v = i * m + j\n if Set.member v wasteCells\n then output' (\"Waste\" :: String)\n else do\n let loop !n | n <= k, v <= v' = loop (n + 1)\n | otherwise = do\n let idx = (v - n) `mod` 3\n output' $ candidates ! idx\n where v' = a ! n\n loop 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--------------------------------------------------\n-- Imported C functions\n--------------------------------------------------\n#define BUFMAX (100005)\n\ntype BString = BS.ByteString\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr Int -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i64 :: CString -> Ptr Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_f :: CString -> Ptr Float -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_s :: CString -> CString -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i :: CString -> Int -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i64 :: CString -> Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_d :: CString -> Double -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: CString -> CString -> IO ()\n\nfmt_i, fmt_i64, fmt_f, fmt_d, fmt_s :: CString\nfmt_i = unsafePerformIO $ newCString \"%d\"\nfmt_i64 = unsafePerformIO $ newCString \"%I64d\"\nfmt_f = unsafePerformIO $ newCString \"%f\"\nfmt_d = unsafePerformIO $ newCString \"%.16f\"\nfmt_s = unsafePerformIO $ newCString \"%s\"\n{-# NOINLINE fmt_i #-}\n{-# NOINLINE fmt_i64 #-}\n{-# NOINLINE fmt_f #-}\n{-# NOINLINE fmt_d #-}\n{-# NOINLINE fmt_s #-}\n\nptr_i :: Ptr Int\nptr_i = unsafePerformIO malloc\nptr_i64 :: Ptr Int64\nptr_i64 = unsafePerformIO malloc\nptr_f :: Ptr Float\nptr_f = unsafePerformIO malloc\nptr_d :: Ptr Double\nptr_d = unsafePerformIO malloc\nptr_s :: CString\nptr_s = unsafePerformIO $ mallocArray BUFMAX\n{-# NOINLINE ptr_i #-}\n{-# NOINLINE ptr_i64 #-}\n{-# NOINLINE ptr_f #-}\n{-# NOINLINE ptr_d #-}\n{-# NOINLINE ptr_s #-}\n\nclass Input a where\n input :: IO a\n\ninstance Input Int where\n input = c_scanf_i fmt_i ptr_i >> peek ptr_i\ninstance Input Int64 where\n input = c_scanf_i64 fmt_i64 ptr_i64 >> peek ptr_i64\ninstance Input Integer where\n input = toInteger <$> (input :: IO Int64)\ninstance Input Double where\n input = c_scanf_f fmt_f ptr_f >> realToFrac <$> peek ptr_f\ninstance Input String where\n input = c_scanf_s fmt_s ptr_s >> peekCString ptr_s\ninstance Input BString where\n input = c_scanf_s fmt_s ptr_s >> BS.packCString ptr_s\n\nclass Output a where\n output_ :: a -> IO ()\n output :: a -> IO ()\n output = (>> space ) . output_\n output' :: a -> IO ()\n output' = (>> newline) . output_\n\ninstance Output Int where\n output_ = c_printf_i fmt_i\ninstance Output Int64 where\n output_ = c_printf_i64 fmt_i64\ninstance Output Integer where\n output_ = output_ . show\ninstance Output Double where\n output_ = c_printf_d fmt_d\ninstance Output String where\n output_ = flip withCString (c_printf_s fmt_s)\ninstance Output BString where\n output_ = flip BS.useAsCString (c_printf_s fmt_s)\n\nspace :: IO ()\nspace = output_ (\" \" :: String)\n\nnewline :: IO ()\nnewline = output_ (\"\\n\" :: String)\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !begin !end k = loop begin\n where loop !i | i >= end = return ()\n | otherwise = k i >> loop (i + 1)\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep = for 0\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, ImplicitParams #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n-- import qualified Data.Map as Map\nimport qualified Data.IntSet as Set\n\nmain :: IO ()\nmain = do\n _ :: Int <- input\n m :: Int <- input\n k :: Int <- input\n t :: Int <- input\n let checkWasteCells acc !i | i >= k = return acc\n | otherwise = do\n a :: Int <- input\n b :: Int <- input\n checkWasteCells (Set.insert ((a - 1) * m + (b - 1)) acc) (i + 1)\n wasteCells <- checkWasteCells Set.empty 0\n let a = listArray (0, k - 1) (Set.toList wasteCells) :: UArray Int Int\n candidates = listArray (0, 2) [\"Carrots\", \"Kiwis\", \"Grapes\"] :: Array Int String\n rep t $ \\_ -> do\n i :: Int <- input\n j :: Int <- input\n let !v = (i - 1) * m + (j - 1)\n if Set.member v wasteCells\n then output' (\"Waste\" :: String)\n else do\n let loop !n | n < k, v <= a ! n = loop (n + 1)\n | otherwise = do\n let idx = (v - n + 2) `mod` 3\n output' $ candidates ! idx\n loop 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--------------------------------------------------\n-- Imported C functions\n--------------------------------------------------\n#define BUFMAX (100005)\n\ntype BString = BS.ByteString\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr Int -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i64 :: CString -> Ptr Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_f :: CString -> Ptr Float -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_s :: CString -> CString -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i :: CString -> Int -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i64 :: CString -> Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_d :: CString -> Double -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: CString -> CString -> IO ()\n\nfmt_i, fmt_i64, fmt_f, fmt_d, fmt_s :: CString\nfmt_i = unsafePerformIO $ newCString \"%d\"\nfmt_i64 = unsafePerformIO $ newCString \"%I64d\"\nfmt_f = unsafePerformIO $ newCString \"%f\"\nfmt_d = unsafePerformIO $ newCString \"%.16f\"\nfmt_s = unsafePerformIO $ newCString \"%s\"\n{-# NOINLINE fmt_i #-}\n{-# NOINLINE fmt_i64 #-}\n{-# NOINLINE fmt_f #-}\n{-# NOINLINE fmt_d #-}\n{-# NOINLINE fmt_s #-}\n\nptr_i :: Ptr Int\nptr_i = unsafePerformIO malloc\nptr_i64 :: Ptr Int64\nptr_i64 = unsafePerformIO malloc\nptr_f :: Ptr Float\nptr_f = unsafePerformIO malloc\nptr_d :: Ptr Double\nptr_d = unsafePerformIO malloc\nptr_s :: CString\nptr_s = unsafePerformIO $ mallocArray BUFMAX\n{-# NOINLINE ptr_i #-}\n{-# NOINLINE ptr_i64 #-}\n{-# NOINLINE ptr_f #-}\n{-# NOINLINE ptr_d #-}\n{-# NOINLINE ptr_s #-}\n\nclass Input a where\n input :: IO a\n\ninstance Input Int where\n input = c_scanf_i fmt_i ptr_i >> peek ptr_i\ninstance Input Int64 where\n input = c_scanf_i64 fmt_i64 ptr_i64 >> peek ptr_i64\ninstance Input Integer where\n input = toInteger <$> (input :: IO Int64)\ninstance Input Double where\n input = c_scanf_f fmt_f ptr_f >> realToFrac <$> peek ptr_f\ninstance Input String where\n input = c_scanf_s fmt_s ptr_s >> peekCString ptr_s\ninstance Input BString where\n input = c_scanf_s fmt_s ptr_s >> BS.packCString ptr_s\n\nclass Output a where\n output_ :: a -> IO ()\n output :: a -> IO ()\n output = (>> space ) . output_\n output' :: a -> IO ()\n output' = (>> newline) . output_\n\ninstance Output Int where\n output_ = c_printf_i fmt_i\ninstance Output Int64 where\n output_ = c_printf_i64 fmt_i64\ninstance Output Integer where\n output_ = output_ . show\ninstance Output Double where\n output_ = c_printf_d fmt_d\ninstance Output String where\n output_ = flip withCString (c_printf_s fmt_s)\ninstance Output BString where\n output_ = flip BS.useAsCString (c_printf_s fmt_s)\n\nspace :: IO ()\nspace = output_ (\" \" :: String)\n\nnewline :: IO ()\nnewline = output_ (\"\\n\" :: String)\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !begin !end k = loop begin\n where loop !i | i >= end = return ()\n | otherwise = k i >> loop (i + 1)\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep = for 0\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, ImplicitParams #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Foreign\nimport Foreign.C\nimport Data.List\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n-- import qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n _ :: Int64 <- input\n m :: Int64 <- input\n k :: Int64 <- input\n t :: Int64 <- input\n let checkWasteCells acc !i | i >= k = return acc\n | otherwise = do\n a :: Int64 <- input\n b :: Int64 <- input\n checkWasteCells (Set.insert ((a - 1) * m + (b - 1)) acc) (i + 1)\n wasteCells <- checkWasteCells Set.empty 0\n let a = listArray (0, k - 1) (Set.toList wasteCells) :: UArray Int64 Int64\n candidates = listArray (0, 2) [\"Carrots\", \"Kiwis\", \"Grapes\"] :: Array Int64 String\n rep (fromIntegral t) $ \\_ -> do\n i :: Int64 <- input\n j :: Int64 <- input\n let !v = (i - 1) * m + (j - 1)\n if Set.member v wasteCells\n then output' (\"Waste\" :: String)\n else do\n let loop !n | n < k, v <= a ! n = loop (n + 1)\n | otherwise = do\n let idx = (v - n + 2) `mod` 3\n output' $ candidates ! idx\n loop 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--------------------------------------------------\n-- Imported C functions\n--------------------------------------------------\n#define BUFMAX (100005)\n\ntype BString = BS.ByteString\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr Int -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i64 :: CString -> Ptr Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_f :: CString -> Ptr Float -> IO ()\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_s :: CString -> CString -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i :: CString -> Int -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_i64 :: CString -> Int64 -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_d :: CString -> Double -> IO ()\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: CString -> CString -> IO ()\n\nfmt_i, fmt_i64, fmt_f, fmt_d, fmt_s :: CString\nfmt_i = unsafePerformIO $ newCString \"%d\"\nfmt_i64 = unsafePerformIO $ newCString \"%I64d\"\nfmt_f = unsafePerformIO $ newCString \"%f\"\nfmt_d = unsafePerformIO $ newCString \"%.16f\"\nfmt_s = unsafePerformIO $ newCString \"%s\"\n{-# NOINLINE fmt_i #-}\n{-# NOINLINE fmt_i64 #-}\n{-# NOINLINE fmt_f #-}\n{-# NOINLINE fmt_d #-}\n{-# NOINLINE fmt_s #-}\n\nptr_i :: Ptr Int\nptr_i = unsafePerformIO malloc\nptr_i64 :: Ptr Int64\nptr_i64 = unsafePerformIO malloc\nptr_f :: Ptr Float\nptr_f = unsafePerformIO malloc\nptr_d :: Ptr Double\nptr_d = unsafePerformIO malloc\nptr_s :: CString\nptr_s = unsafePerformIO $ mallocArray BUFMAX\n{-# NOINLINE ptr_i #-}\n{-# NOINLINE ptr_i64 #-}\n{-# NOINLINE ptr_f #-}\n{-# NOINLINE ptr_d #-}\n{-# NOINLINE ptr_s #-}\n\nclass Input a where\n input :: IO a\n\ninstance Input Int where\n input = c_scanf_i fmt_i ptr_i >> peek ptr_i\ninstance Input Int64 where\n input = c_scanf_i64 fmt_i64 ptr_i64 >> peek ptr_i64\ninstance Input Integer where\n input = toInteger <$> (input :: IO Int64)\ninstance Input Double where\n input = c_scanf_f fmt_f ptr_f >> realToFrac <$> peek ptr_f\ninstance Input String where\n input = c_scanf_s fmt_s ptr_s >> peekCString ptr_s\ninstance Input BString where\n input = c_scanf_s fmt_s ptr_s >> BS.packCString ptr_s\n\nclass Output a where\n output_ :: a -> IO ()\n output :: a -> IO ()\n output = (>> space ) . output_\n output' :: a -> IO ()\n output' = (>> newline) . output_\n\ninstance Output Int where\n output_ = c_printf_i fmt_i\ninstance Output Int64 where\n output_ = c_printf_i64 fmt_i64\ninstance Output Integer where\n output_ = output_ . show\ninstance Output Double where\n output_ = c_printf_d fmt_d\ninstance Output String where\n output_ = flip withCString (c_printf_s fmt_s)\ninstance Output BString where\n output_ = flip BS.useAsCString (c_printf_s fmt_s)\n\nspace :: IO ()\nspace = output_ (\" \" :: String)\n\nnewline :: IO ()\nnewline = output_ (\"\\n\" :: String)\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !begin !end k = loop begin\n where loop !i | i >= end = return ()\n | otherwise = k i >> loop (i + 1)\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep = for 0\n\n"}], "src_uid": "bfef3f835357dae290620efabe650580"} {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n let ok = elem 1 (zipWith subtract <*> tail $ sort as) || even (length $ filter even as)\n putStrLn $ bool \"NO\" \"YES\" ok", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ndata Answer = YES | NO deriving (Show)\ntype Test = [Int]\n\ngetTests :: Int -> IO [Test]\ngetTests n = replicateM n getTest\n\ngetTest :: IO Test\ngetTest = do\n _ <- getLine\n list <- getLine\n return $ parseInput list\n\nparseInput :: String -> Test\nparseInput list = map read (words list)\n\nfindAnswer :: [Test] -> [Answer]\nfindAnswer [] = []\nfindAnswer (first:rest) = (if (evens `mod` 2) + (odds `mod` 2) == 1\n then NO\n else if evens `mod` 2 == 0\n then YES\n else if areNeighbours $ sort first\n then YES\n else NO) : findAnswer rest\n where evens = length $ filter (\\x -> x `mod` 2 == 0) first\n odds = (length first) - evens\n\nareNeighbours :: Test -> Bool\nareNeighbours [x] = False\nareNeighbours (x:y:rest) = if y == x+1\n then True\n else areNeighbours (y:rest)\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getTests $ read count\n mapM_ print (findAnswer tests)"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n _ <- getLine\n as <- map read . words <$> getLine\n let (evens, odds) = partition even as\n putStrLn $ case mod (length evens) 2 of\n 0 -> \"YES\"\n 1 -> if or [ abs (x - y) == 1 | x <- evens, y <- odds ]\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.Set as Set\n\nreadLine :: IO [Integer]\nreadLine = getLine >> (map read) . words <$> getLine\n\nisPartitionPossible xs = \n if numEven == 0 || numOdd == 0 || even numEven then \"YES\"\n else if any (\\x -> Set.member (x + 1) evenSet || Set.member (x - 1) evenSet) odds then \"YES\"\n else \"NO\"\n where\n evens = filter even xs\n odds = filter odd xs\n numEven = length evens\n numOdd = length odds\n evenSet = Set.fromList evens\n\nmain =\n read <$> getLine >>= \\t ->\n replicateM_ t (isPartitionPossible <$> readLine >>= putStrLn)"}, {"source_code": "import Control.Monad ( replicateM_ )\nimport qualified Data.Set as Set\n\n\nreadInput = getLine >> (map read . words <$> getLine)\n\nsimilarPairs :: [Int] -> String\nsimilarPairs s = let odds = length (filter odd s) in\n if even odds then \"YES\"\n else if any (flip Set.member set . succ) s then \"YES\"\n else \"NO\"\n where set = Set.fromList s\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (similarPairs <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/C\n\nimport Control.Monad ( replicateM_ )\nimport qualified Data.Set as Set\n\n\nsimilarPairs :: [Int] -> String\nsimilarPairs s = let odds = length (filter odd s) in\n if even odds || any (seen . succ) s\n then \"YES\"\n else \"NO\"\n where seen = (`Set.member` Set.fromList s)\n\n\nreadInput :: IO [Int]\nreadInput = getLine >> map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (similarPairs <$> readInput >>= putStrLn)\n"}, {"source_code": "import Data.List (sort)\nimport Data.Traversable (for)\n\ndiff1 :: [Int] -> Bool\ndiff1 li = let sli = sort li in elem 1 $ zipWith (-) (tail sli) sli\n\ncountEven :: [Int] -> Int\ncountEven = length . filter ((== 0) . (`mod` 2))\n\nmain :: IO ()\nmain = do\n nCases <- fmap read getLine :: IO Int\n _ <- for [1..nCases] $ \\_ -> do\n n <- fmap read getLine :: IO Int\n a <- fmap (map read . words) getLine :: IO [Int]\n putStrLn $ case () of\n _ | odd n -> \"NO\"\n _ | even (countEven a) -> \"YES\"\n _ | diff1 a -> \"YES\"\n _ -> \"NO\"\n return ()\n"}], "negative_code": [{"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n let ok = elem 1 (zipWith subtract <*> tail $ sort as) || even (length $ filter even as)\n print $ bool \"NO\" \"YES\" ok"}, {"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.Set as Set\n\nreadLine :: IO [Integer]\nreadLine = getLine >> (map read) . words <$> getLine\n\nisPartitionPossible xs = \n if numEven == 0 || numOdd == 0 || even numEven then \"YES\"\n else if any (\\x -> Set.member (x + 1) evenSet || Set.member (x - 1) evenSet) odds then \"YES\"\n else \"NO\"\n where\n evens = filter even xs\n odds = filter odd xs\n numEven = length evens\n numOdd = length odds\n evenSet = Set.fromList evens\n\nmain =\n read <$> getLine >>= \\t ->\n replicateM_ t (isPartitionPossible <$> readLine >>= print)"}], "src_uid": "005a29a4b4e7ee4fd21444846014727b"} {"source_code": "calculo :: Int -> Int\ncalculo recibir = \n let n = 180 `div` (gcd 180 recibir)\n in if recibir <= 180 `div` n * (n - 2) \n then n \n else (2 * n)\n \nmain = do\n _ <- getLine\n contenido <- getContents\n mapM_ (print . calculo . read) $ lines contenido", "positive_code": [{"source_code": "import Data.Fixed (mod')\n\ndata Polygon = Polygon { vertex :: Int\n , minAngle :: Float\n , maxAngle :: Float\n , intAngle :: Float\n } deriving (Show)\n\nporyList :: [Int] -> [Polygon]\nporyList [] = []\nporyList (3:xs) = (Polygon { vertex = 3, minAngle = 60.0, maxAngle = 60.0, intAngle = 60.0}):(poryList xs)\nporyList (4:xs) = (Polygon { vertex = 4, minAngle = 45.0, maxAngle = 45.0, intAngle = 90.0}):(poryList xs)\nporyList (x:xs) = (Polygon { vertex = x, minAngle = ang, maxAngle = ang * (y - 2), intAngle = ang * (y - 2)}):(poryList xs)\n where y = fromIntegral x :: Float\n ang = 180 / y\n\ncheckPory :: [Polygon] -> Int -> Int\ncheckPory [] _ = -1\ncheckPory (x:xs) n\n | n >= 180 = -1\n | mod' nn (minAngle x) == 0 && nn <= (maxAngle x) = vertex x\n | nn == intAngle x = vertex x\n | otherwise = checkPory xs n\n where nn = fromIntegral n :: Float\n\ncheckFor :: [Polygon] -> [Int] -> [Int]\ncheckFor _ [] = []\ncheckFor x (y:ys) = (checkPory x y):(checkFor x ys)\n\nmain :: IO()\nmain = do\n let h = poryList [3..]\n q <- getLine\n let query = (read q :: Int)\n angList <- (sequence (replicate query getLine))\n let pList = map (read :: String -> Int) angList\n mapM_ print (checkFor h pList)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Fixed\ndata Polygon = Polygon {angulo :: Float, vertice :: Int} deriving (Show)\n\ninstance Eq Polygon where --Instancia pedida en el bonus\n (==) (Polygon ver1 ang1) (Polygon ver2 ang2) = (ver1 == ver2) && (ang1 == ang2)\n (==) a b = False\n\npoly :: [Int] -> [Polygon] --Generador de poligonos\npoly (x:xs) = let \n vert = x\n ang = 180.0 / (fromIntegral x) in Polygon { angulo = ang, vertice = vert}:poly xs\n\nminVert :: [Int] -> [Polygon] -> [String] --Funci\u00f3n encargada de entregar el angulo m\u00ednimo correspondiente a cada caso\nminVert [a] b = let\n filteredList = filter (\\p -> aux a p) b in if filteredList == []\n then \"-1\" : []\n else show (vertice (head filteredList)) : []\nminVert (a:as) b = let\n filteredList = filter (\\p -> aux a p) b in if filteredList == []\n then \"-1\" : (minVert as b)\n else show (vertice (head filteredList)) : (minVert as b)\n\naux :: Int -> Polygon -> Bool --Funci\u00f3n que ratifica que el angulo obtenido exista\naux x y\n | (fromIntegral x) < (angulo y) = False\n | (fromIntegral x) > ((angulo y) * (fromIntegral (vertice y) - 2.0)) = False\n | mod' (fromIntegral x) (angulo y) == 0.0 = True\n | otherwise = False \n\nmain :: IO ()\nmain = do\n casos <- getLine \n let n = read casos::Int \n angulos <- replicateM n getLine \n let poligonos = poly [3..998244353] \n let intAngulos = map (read :: String -> Int) angulos\n let output = minVert intAngulos poligonos\n putStrLn (intercalate \"\\n\" output) "}, {"source_code": "import System.Environment\nimport System.IO\nimport qualified Data.Fixed as F\n\n\ndata Poligon = Poligon { vrtx :: Float\n , ang :: Float\n } deriving (Show)\n\n\nmain = do\n inputs<- getLine\n angulos <- lector (read inputs::Int)\n let lp = infiniteL 3\n mapM_ print (map round (answers angulos lp))\n\n\nlector :: Int -> IO [Float]\nlector 0 = return []\nlector n = do\n x <- fmap read getLine\n rest <- lector (n-1)\n return $ x : rest\n\n\ninfiniteL :: Float -> [Poligon]\ninfiniteL v =\n plg:(infiniteL (v+1))\n where plg = (Poligon v ((/) 180.0 v))\n\n\nminimu :: Float -> [Poligon] ->Poligon\nminimu num (p:ps) =\n let (n,m) = dataPoly p in\n if((F.mod' num m) == 0 && ((n-2)*180/n) >= num )\n then p\n else\n minimu num ps\n\n\ndataPoly :: Poligon -> (Float, Float)\ndataPoly (Poligon n m) = (n , m)\n\n\nanswers :: [Float] -> [Poligon] ->[Float]\nanswers [] _ = []\nanswers (x:xs) l =\n [n] ++ (answers xs l)\n where (n,m) = dataPoly(minimu x l)"}, {"source_code": "import Control.Monad (replicateM)\n\ndata Polygon = Polygon {vertices :: Int,\n angulo_min :: Float,\n angulos :: [Float]} deriving (Show)\n\ndivid :: Int -> Int -> Float\ndivid a b = (fromIntegral a) / (fromIntegral b)\n\npoligonos :: [Polygon]\npoligonos = [Polygon n (divid 180 n) (angulos_poligono n) | n <- [3..]]\n\nangulos_poligono :: Int -> [Float]\nangulos_poligono n = [(divid 180 n) * (fromIntegral x)| x <- [1..n-2]]\n\npoligono_min :: Int -> [Polygon] -> Int\npoligono_min angulo (x:xs)\n | (fromIntegral angulo) `elem` angulos_pol x = vert x \n | otherwise = poligono_min angulo xs\n \nvert :: Polygon -> Int\nvert (Polygon n _ _) = n\n\nangulos_pol :: Polygon -> [Float]\nangulos_pol (Polygon _ _ l) = l\n\n-- https://stackoverflow.com/questions/27650315/getline-x-times-haskell\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetInts :: Int -> IO [Int]\ngetInts n = fmap read <$> getLines n\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\n\nmain = do\n queries <- getInt\n nums <- getInts queries\n let vertex = [poligono_min angle poligonos | angle <- nums]\n mapM_ print vertex"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ getLine >>= print . query . read\n\nquery :: Int -> Int\nquery angle | angle >= 180 * (firstans-1) `div` firstans = firstans * 2\n | otherwise = firstans\n where\n firstans = 180 `div` gcd 180 angle\n"}, {"source_code": "import System.IO\nimport Data.Fixed\n\ndata Polygon = Polygon { vertices ::Int ,minAng ::Float,interior::Float} deriving(Show)\n\ncanBeDone:: Polygon-> Float -> Bool\ncanBeDone p a= mod' a (minAng p) == 0.0 && a<=(interior p)\nforEach ::[Polygon]->Float ->Int\nforEach [] a= (-1)\nforEach (p:ps) a= do\n if(canBeDone p a)\n then getVertices p\n else if(getVertices p <998244353)\n then forEach ps a\n else -1\n\ngetIterationsLines :: Int ->[Polygon] -> IO [String]\ngetIterationsLines n lista\n | n <= 0 = return []\n | otherwise = do\n angle <- getLine\n print $ forEach lista (read angle ::Float)\n xs <- getIterationsLines (n-1) lista\n return (angle:xs)\n \n\ngetVertices:: Polygon -> Int\ngetVertices p = vertices p\n\nmain = do\n iterations <- getLine\n let lista_infinita = [ Polygon i (180/fromIntegral i) (180*(fromIntegral i-2)/fromIntegral i) | i<-[3..]]\n let ite = read iterations::Int\n getIterationsLines ite lista_infinita\n return ()\n\n\n\n\n"}, {"source_code": "import System.IO\nimport Data.Fixed\n\ndata Polygon = Polygon { vertices ::Int ,minAng ::Float,interior::Float} deriving(Show)\n\ncanBeDone:: Polygon-> Float -> Bool\ncanBeDone p a= mod' a (minAng p) == 0.0 && a<=(interior p)\nforEach ::[Polygon]->Float ->Int\nforEach [] a= (-1)\nforEach (p:ps) a= do\n if(canBeDone p a)\n then getVertices p\n else if(getVertices p <2000000)\n then forEach ps a\n else -1\n\ngetIterationsLines :: Int ->[Polygon] -> IO [String]\ngetIterationsLines n lista\n | n <= 0 = return []\n | otherwise = do\n angle <- getLine\n print $ forEach lista (read angle ::Float)\n xs <- getIterationsLines (n-1) lista\n return (angle:xs)\n \n\ngetVertices:: Polygon -> Int\ngetVertices p = vertices p\n\nmain = do\n iterations <- getLine\n let lista_infinita = [ Polygon i (180/fromIntegral i) (180*(fromIntegral i-2)/fromIntegral i) | i<-[3..]]\n let ite = read iterations::Int\n getIterationsLines ite lista_infinita\n return ()\n\n\n\n\n"}, {"source_code": "data Polygon = Polygon {sides :: Int}\n\nminAngle :: Polygon -> Float\nminAngle poly\n | sides poly > 2 = 180.0 / (fromIntegral (sides poly))\n | otherwise = error \"Invalid Polygon\"\n\ninteriorAngle :: Polygon -> Float\ninteriorAngle poly\n | sides poly > 2 = fromIntegral((sides poly) - 2)*minAngle poly\n | otherwise = error \"Invalid Polygon\"\n\npossibleAngles :: Polygon -> [Float]\npossibleAngles poly = [minAngle poly, 2*(minAngle poly)..(interiorAngle poly)]\n\nfindPolygon :: [Polygon] -> Float -> IO ()\nfindPolygon (x0:xs) n\n | elem n (possibleAngles x0) = print(sides x0)\n | otherwise = findPolygon xs n\n\n\nmain :: IO ()\nmain = do\n n <-getLine\n inputs <- sequence [readLn :: IO Float | i <-[1..(read n :: Integer)]]\n let polygons = [Polygon i | i<-[3..]]\n mapM_ (findPolygon polygons) inputs\n"}, {"source_code": "import Data.List (sort)\nimport Control.Monad\n\n--Data Polygon required in LP\ndata Polygon = Polygon {\n\t\t\t\t\tvertex :: Int,\n\t\t\t\t\tmin_angle :: Float\n\t\t\t\t\t}\n\t\t\t\t\t\n--Implement Eq type class\ninstance Eq Polygon where\n\t(==) (Polygon n ang) (Polygon n' ang') = (n==n' && ang' == ang')\n\n--Implement Ord type class to compare polygons\ninstance Ord Polygon where\n\tcompare (Polygon a _) (Polygon b _) = compare a b\n\n--Implement Show type class to print the vortex\ninstance Show Polygon where\n\tshow (Polygon a _ ) = show a\n--------------------------------------\n\n--calculate the internal angle of the side of a polygon\ncalcSideAngle :: Float -> Float\ncalcSideAngle x = 180.0*(x - 2)/(x)\n\n--calculate the minimum angle that can contain a polygon\nminAngle :: Int -> Float\nminAngle n = let\n\t\t\t\tsideAngle = calcSideAngle x\n\t\t\t\tx = fromIntegral n\n\t\t\t\tin sideAngle/(x-2)\n\n--verify if a certain angle is possible in a polygon of n vertices\nis_possible :: Int -> Polygon -> Bool\nis_possible ang n = let\n\t\t\t\tmin_angle = minAngle (vertex n)\n\t\t\t\tang' = fromIntegral ang\n\t\t\t\tin foldl (\\acc x -> if (x*min_angle) == ang' then True else acc) False (map (fromIntegral) [1..(vertex(n)-2)])\n\n--compute all possible polygons that satisfy the condition and take the first\n--in other words, compute the amount of vertices that a polygon can have to contain an angle ang\npossible_polygons :: Int -> (Polygon -> Bool) -> [Polygon]-> Polygon\npossible_polygons ang fx xs = head (filter fx xs )\n\n--look at this\nmain = do\n\tlet poligonos = [Polygon i (minAngle i)| i <- [1..]]\n\tn <- fmap read getLine\n\tangles <- forM (replicate n 1) (\\a -> do\n\t\tang <- getLine\n\t\treturn ang)\n\tmapM (\\ang -> do\n\t\tlet ang' = read ang :: Int\n\t\tlet result = possible_polygons ang' (is_possible ang') poligonos\n\t\tputStrLn $ show result) angles\n--very impressive no?\n\t\n"}, {"source_code": "import Data.List\nimport Control.Monad --para usar replicateM\n\ndata Polygon = Polygon {vertices :: Int, min_ang :: Int} deriving (Show) --Lo que se pide\n\nmain :: IO ()\nmain = do\n casos <- getLine \n let t = read casos::Int -- (1\u2264t\u2264180)\n angulos <- replicateM t getLine --Lista con los angulos recibidos\n let poligonos = map poligonosRegulares [3..] -- 3 porque es el numero minimo de vertices, lista infinita como se pide\n let output = map (anguloMenor poligonos) angulos\n putStrLn $ foldl (\\x0 y -> x0 ++ (show y) ++ \"\\n\") \"\" output \n\npoligonosRegulares :: Int -> Polygon\npoligonosRegulares num_vertices -- de la lista infinita \n | (180 `mod` num_vertices == 0) = Polygon {vertices = num_vertices, min_ang = 180 `div` num_vertices} --Triangulo\n | (360 `mod` num_vertices == 0) = Polygon {vertices = num_vertices, min_ang = 360 `div` num_vertices} --Cuadrado\n | otherwise = Polygon {vertices = num_vertices, min_ang = 181}\n\nanguloMenor :: [Polygon] -> String -> Int\nanguloMenor (x0:xs) ang_string\n | (((((vertices x0)-2)*180) `div` vertices x0) >= ang && (ang `mod` (min_ang x0) == 0)) = vertices x0\n | (vertices x0 > 360) = -1\n | otherwise = anguloMenor xs ang_string --recursividad\n where ang = read ang_string :: Int -- Se pasa a int para poder operarlo\n"}, {"source_code": "import Control.Monad\n\n--se crea el data Polygon con los datos angulosInt, vertices, anguloMin y anguloMax\ndata Polygon = Polygon {\n angulosInt ::Double,\n vertices ::Int,\n anguloMin ::Double,\n anguloMax ::Double\n} deriving (Ord, Eq,Show)\n\n--se define cada uno de los atributos de Polygon\n--angulos internos = 180*(cantidad de vertices-2)\n--angulo Maximo = angulos Internos / cantidad de vertices\n--angulo Minimo (este fue probando) = angulo maximo / (cantidad de vertices - 2)\n--Recibe un Int (cantidad de vertices) y entrega un Polygon con todos sus datos\ndefine :: Int -> Polygon\ndefine ver = let \n doubVer = fromIntegral ver ::Double\n angInt = 180.0 * (doubVer - 2.0)\n angMax = angInt / doubVer\n angMin = angMax/(doubVer-2.0)\n in Polygon {vertices = ver, angulosInt = angInt, anguloMin = angMin, anguloMax = angMax}\n\n--entrega el poligono donde se puede formar el angulo\nbuscarPol :: Int -> Polygon -> Polygon\nbuscarPol ang pol = let\n ver = vertices pol\n in if (isPol (fromIntegral ang ::Double) pol) then pol else buscarPol ang (define (ver+1))\n\n--Comprueba si es el polygono pedido\n--recibe un angulo y el polygono inicial y entrega True si es el polygono que se pide y False en caso contrario\nisPol :: Double-> Polygon -> Bool\nisPol ang pol=let\n angMin = anguloMin pol\n angMax = anguloMax pol\n --angs1 es la divisi\u00f3n normal, angs2 es la division entera entre el angulo dado y el angulo minimo del poligono\n angs1 = (ang / angMin)\n angs2 = (fromIntegral (round (ang/angMin)) :: Double)\n --si angs1 y angs2 son iguales significa que el angulo minimo es divisor del angulos dado, por lo que es el poligono pedido\n in if (ang<=angMax && angs1-angs2==0.0) then True else False\n\noutput:: Int -> IO ()\noutput out = print out\n\nmain::IO()\nmain = do\n consultas <- getLine\n --se recibe un input multiple con replicateM\n angulos <- replicateM (read consultas ::Int) getLine\n let polInicial = define 3\n --se crea la lista de polygonos, al reves, por lo que se utiliza reverse para mantenerla segun lo dado por el usuario\n --luego se entrega en consola cada uno de los datos con mapM_ y la funci\u00f3n output\n (mapM_ output(reverse (foldl (\\x y -> (vertices (buscarPol (read y ::Int) polInicial)) : x) [] angulos)))"}, {"source_code": "import Control.Monad\n\n--prueba\n\ndata Polygon = Polygon {\n angulosInt ::Double,\n vertices ::Int,\n anguloMin ::Double,\n anguloMax ::Double\n} deriving (Ord, Eq,Show)\n\n\n\ndefine :: Int -> Polygon -> Polygon\ndefine ver pol = let \n angInt = angulosInternos ver\n intVer = fromIntegral ver ::Double\n angMax = angInt / (fromIntegral ver ::Double)\n angMin = anguloMinimo angMax intVer\n in pol {vertices = ver, angulosInt = angInt, anguloMin = angMin, anguloMax = angMax}\n\nangulosInternos :: Int -> Double\nangulosInternos ver = 180.0 * ((fromIntegral ver ::Double) - 2.0)\n\nanguloMinimo :: Double -> Double -> Double\nanguloMinimo angMax ver= angMax/(ver-2.0)\n\n\nbuscarPol :: Int -> Int -> Polygon -> Polygon\nbuscarPol ang lim pol = let\n ver = vertices pol\n in if (isPol (fromIntegral ang ::Double) pol) then pol else (if ver < lim then (buscarPol ang lim (define (ver+1) pol)) else Polygon (-1) (-1) (-1) (-1))\n\n\noutput:: Int -> IO ()\noutput out = print out\n\n\ntoInt :: Double -> Int\ntoInt x = round x\n\n\nisPol :: Double-> Polygon -> Bool\nisPol ang pol=let\n angMin = anguloMin pol\n angMax = anguloMax pol\n angs1 = (ang / angMin)\n angs2 = (fromIntegral (toInt(ang/angMin)) :: Double)\n in if (ang<=angMax && angs1-angs2==0.0) then True else False\n\n\nmain::IO()\nmain = do\n consultas <- getLine\n angulos <- replicateM (read consultas ::Int) getLine\n let lim = 998244353\n let polInicial = Polygon 180 3 60 60\n (mapM_ output(reverse (foldl (\\x y -> (vertices (buscarPol (read y ::Int) lim polInicial)) : x) [] angulos)))"}, {"source_code": "import Data.List \nimport Data.Fixed\n\n--Creaci\u00f3n del tipo Polygon que posee angulo y vertice \ndata Polygon = Polygon {\n angulo :: Double,\n vertice :: Int} \n deriving (Show)\n \n--Creaci\u00f3n de la lista de pol\u00edgonos\ngenerarpoligonos :: [Int] -> [Polygon]\ngenerarpoligonos(x:xs) = let\n angulo2= 180.0/(fromIntegral x)\n vertice2= x\n in Polygon{angulo = angulo2, vertice= vertice2}:(generarpoligonos xs)\n\n--Funcion utilizada para generar el numero de vertices minimos\ngenerarvertices :: [Int] -> [Polygon] -> [String]\ngenerarvertices[x] y = let \n listaconfiltro = filter(\\p -> verificarangulos x p) y in if listaconfiltro == [] then \"-1\" : [] else show (vertice (head listaconfiltro)):[]\ngenerarvertices(x:xs) y = let \n listaconfiltro = filter(\\p -> verificarangulos x p) y in if listaconfiltro == [] then \"-1\" : (generarvertices xs y) else show (vertice (head listaconfiltro)):(generarvertices xs y)\n\n--Funcion para verificar angulos de la funcion generarpoligonos2 y retornar True o False\nverificarangulos :: Int -> Polygon -> Bool\nverificarangulos x y\n |(fromIntegral x)>((angulo y)*(fromIntegral(vertice y)- 2.0)) = False\n |(fromIntegral x)<(angulo y) = False\n |mod'(fromIntegral x)(angulo y) == 0.0 = True\n |otherwise = False \n\n--Instancia utilizada para verificar igualdad de angulos \ninstance Eq Polygon where\n (==)(Polygon vertice2 angulo2)(Polygon vertice1 angulo1) = (angulo1 == angulo2)&&(vertice1 == vertice2)\n (==) x y = False \n\nmain :: IO() \nmain = do\n numeroT <- getLine\n let listapoligonos = generarpoligonos[3,4..] --Se recibe el numero T de consultas y se genera la lista de poligonos\n listadeangulos <- sequence(take (read numeroT :: Int)(repeat getLine))\n let angulos = map(read :: String -> Int) listadeangulos --Se genera la lista con los angulos entregados en el input\n let vertices = generarvertices angulos listapoligonos \n putStrLn (intercalate \" \\n\" vertices) --Se genera la lista de vertices y se imprimen por pantallas con \\n de por medio"}, {"source_code": "import qualified Data.ByteString.Char8 as C\n--type polygon que contiene el n\u00famero de v\u00e9rtices, el \u00e1ngulo m\u00e1s peque\u00f1o que se puede generar (mediante 3 v\u00e9rtices consecutivos) y una lista de TODOS los \u00e1ngulos que puede generar el pol\u00edgono\ndata Polygon = Polygon {vertexNumber :: Int, minAngle :: Double, angles :: [Double]} deriving (Show)\n--notar que en mi algoritmo no uso minAngle sino que la lista angles.\n\n--lista de pol\u00edgonos infinita\npolygonList = [Polygon{vertexNumber = i, minAngle = 180.0/(fromIntegral i :: Double), angles = [((180.0/(fromIntegral i :: Double)) * (fromIntegral (j - 2) :: Double)) | j <- [3..i]]} | i <- [3..]]\n\ncontainsAngle :: Polygon -> Double -> Bool --indica si un pol\u00edgono puede \"generar\" el \u00e1ngulo pedido\ncontainsAngle polygon angle = if (((mod ((round angle :: Int)*2*(vertexNumber polygon)) 360) == 0) && ((round angle :: Int)*(vertexNumber polygon) <= (180*((vertexNumber polygon) - 2)))) then True else False\n\n--funci\u00f3n de orden superior, toma la funci\u00f3n para hacer el checkeo de \u00e1ngulo en un pol\u00edgono.\nsolution :: (Polygon -> Double -> Bool) -> Double -> Int --retorna el \u00edndice del pol\u00edgono m\u00e1s peque\u00f1o con el cual se pueda \"generar\" el \u00e1ngulo pedido\nsolution check angle = vertexNumber (head [ polygon | polygon <- polygonList, True == (check polygon angle)]) -- lazyness\n\nreadChar8 :: IO [Int] --computaci\u00f3n para leer ints de forma eficiente\nreadChar8 = map parse . C.words <$> C.getContents where parse s = let Just (n, _) = C.readInt s in n\n\nmain :: IO()\nmain = do\n ints <- readChar8 --primero leo todos los ints y luego trabajo\n let (n:xs) = ints --notar que no uso n pues no es necesario haciendo uso del map de abajo\n mapM_ (\\x -> print (solution containsAngle (fromIntegral x :: Double))) xs\n --para parar el procesamiento y obtener el resultado CTRL + D"}, {"source_code": "import qualified Data.ByteString.Char8 as C\n--type polygon que contiene el n\u00famero de v\u00e9rtices, el \u00e1ngulo m\u00e1s peque\u00f1o que se puede generar (mediante 3 v\u00e9rtices consecutivos) y una lista de TODOS los \u00e1ngulos que puede generar el pol\u00edgono\ndata Polygon = Polygon {vertexNumber :: Int, minAngle :: Double, angles :: [Double]} deriving (Show)\n--notar que en mi algoritmo no uso minAngle sino que la lista angles.\n\n--lista de pol\u00edgonos infinita\npolygonList = [Polygon{vertexNumber = i, minAngle = 180.0/(fromIntegral i :: Double), angles = [((180.0/(fromIntegral i :: Double)) * (fromIntegral (j - 2) :: Double)) | j <- [3..i]]} | i <- [3..]]\n\ncontainsAngle :: Polygon -> Double -> Bool --indica si un pol\u00edgono puede \"generar\" el \u00e1ngulo pedido\ncontainsAngle polygon angle = if (((mod ((round angle :: Int)*2*(vertexNumber polygon)) 360) == 0) && ((round angle :: Int)*(vertexNumber polygon) <= (180*((vertexNumber polygon) - 2)))) then True else False\n\nsolution :: Double -> Int --retorna el \u00edndice del pol\u00edgono m\u00e1s peque\u00f1o con el cual se pueda \"generar\" el \u00e1ngulo pedido\nsolution angle = vertexNumber (head [ polygon | polygon <- polygonList, True == (containsAngle polygon angle)]) -- lazyness\n\nreadChar8 :: IO [Int] --computaci\u00f3n para leer ints de forma eficiente\nreadChar8 = map parse . C.words <$> C.getContents where parse s = let Just (n, _) = C.readInt s in n\n\nmain :: IO()\nmain = do\n ints <- readChar8 --primero leo todos los ints y luego trabajo\n let (n:xs) = ints --notar que no uso n pues no es necesario haciendo uso del map de abajo\n mapM_ (\\x -> print (solution (fromIntegral x :: Double))) xs\n --para parar el procesamiento y obtener el resultado CTRL + D"}, {"source_code": "import qualified Data.ByteString.Char8 as C\ndata Polygon = Polygon {vertexNumber :: Int, minAngle :: Double, angles :: [Double]} deriving (Show)\n\npolygonList = [Polygon{vertexNumber = i, minAngle = 180.0/(fromIntegral i :: Double), angles = [((180.0/(fromIntegral i :: Double)) * (fromIntegral (j - 2) :: Double)) | j <- [3..i]]} | i <- [3..]]\n--possibleAngle :: Double -> Bool\n--possibleAngle angle = let\n-- polygon = take 1 ([polygon | polygon <- (filter ((\\a x -> elem a (angles x)) angle) polygonList)]) -- arreglar\n-- len = length polygon\n-- in if((len == 1) && ((vertexNumber (polygon !! 0) ) <= 998244353)) then True else False\n\ncontainsAngle :: Polygon -> Double -> Bool\ncontainsAngle polygon angle = if (((mod ((round angle :: Int)*2*(vertexNumber polygon)) 360) == 0) && ((round angle :: Int)*(vertexNumber polygon) <= (180*((vertexNumber polygon) - 2)))) then True else False\n\nsolution angle = vertexNumber (head [ polygon | polygon <- polygonList, True == (containsAngle polygon angle)]) -- usando lazyness\n\nreadChar8 :: IO [Int]\nreadChar8 = map parse . C.words <$> C.getContents where parse s = let Just (n, _) = C.readInt s in n\n\nmain :: IO()\nmain = do\n ints <- readChar8 \n let (n:xs) = ints \n mapM_ (\\x -> print (solution (fromIntegral x :: Double))) xs\n --CTRL + D\n"}, {"source_code": "import Data.List (intercalate)\nimport Data.Fixed (mod')\n\ndata Polygon = Polygon {vertices :: Int, minAngle :: Double, maxAngle :: Double}\n\ninstance Show Polygon where\n show r = \"-- Verts: \" ++ (show (vertices r)) ++ \", minAngle: \" ++ (show (minAngle r)) ++ \", maxAngle: \" ++ (show (maxAngle r)) ++ \" --\"\n\ninstance Eq Polygon where\n (==) (Polygon v1 mina1 maxa1) (Polygon v2 mina2 maxa2) =\n (v1 == v2) && (mina1 == mina2) && (maxa1 == maxa2)\n (==) a b = False\n\ninstance Ord Polygon where\n compare (Polygon v1 mina1 maxa1) (Polygon v2 mina2 maxa2) =\n compare (v1,mina1,maxa1) (v2,mina2,maxa2)\n\nallPolygons :: [Polygon]\nallPolygons = let\n start = Polygon {vertices = 3, minAngle = 60, maxAngle = 60}\n in start:(generatePolygons start)\n\ngeneratePolygons :: Polygon -> [Polygon]\ngeneratePolygons f = let\n --You will get the result with this, but simplifying\n --you gonna get the same result in less lines\n --\n --newVerts = (vertices f) + 1\n --angleSum = (newVerts - 2) * 180\n --minAng = angleSum / (newVerts - 2)\n --\n newVerts = (vertices f) + 1\n maxAng = ((fromIntegral (newVerts - 2)) * 180.0) / (fromIntegral newVerts)\n minAng = 180.0 / (fromIntegral newVerts)\n \n nextPolygon = Polygon {vertices = newVerts, minAngle = minAng, maxAngle = maxAng}\n in nextPolygon:(generatePolygons nextPolygon)\n\n--Verify if the angle is between minAngle and maxAngle, and if the minAngle can\n--make the angle \"a\"\ncanGetAngle :: Int -> Polygon -> Bool\ncanGetAngle a p\n | fa < minAng = False\n | fa > maxAngle p = False\n | mod' fa minAng /= 0.0 = False\n | otherwise = True\n where\n fa = fromIntegral a\n minAng = minAngle p\n\n--Get the angle and return the n-sides of the polygon in String format\ngetPolygon :: Int -> String\ngetPolygon angle = let\n filteredList = filter (\\p -> canGetAngle angle p) allPolygons\n in if null filteredList\n then \"-1\"\n else show (vertices (head filteredList))\n\nmain :: IO ()\nmain = do\n q <- getLine\n let queries = read q :: Int\n queryList <- sequence (replicate queries getLine)\n let transformedList = map (read :: String -> Int) queryList\n let mapedList = map getPolygon transformedList\n putStrLn (intercalate \"\\n\" mapedList)\n"}, {"source_code": "import Data.List (intercalate)\nimport Data.Fixed (mod')\n\ndata Polygon = Polygon {vertices :: Int, minAngle :: Double, maxAngle :: Double}\n\ninstance Show Polygon where\n show r = \"-- Verts: \" ++ (show (vertices r)) ++ \", minAngle: \" ++ (show (minAngle r)) ++ \", maxAngle: \" ++ (show (maxAngle r)) ++ \" --\"\n\ninstance Eq Polygon where\n (==) (Polygon v1 mina1 maxa1) (Polygon v2 mina2 maxa2) =\n (v1 == v2) && (mina1 == mina2) && (maxa1 == maxa2)\n (==) a b = False\n\ninstance Ord Polygon where\n compare (Polygon v1 mina1 maxa1) (Polygon v2 mina2 maxa2) =\n compare (v1,mina1,maxa1) (v2,mina2,maxa2)\n\nallPolygons :: [Polygon]\nallPolygons = let\n start = Polygon {vertices = 3, minAngle = 60, maxAngle = 60}\n in start:(generatePolygons start)\n\ngeneratePolygons :: Polygon -> [Polygon]\ngeneratePolygons f = let\n --You will get the result with this, but simplifying\n --you gonna get the same result in less lines\n --\n --newVerts = (vertices f) + 1\n --angleSum = (newVerts - 2) * 180\n --minAng = angleSum / (newVerts - 2)\n --\n newVerts = (vertices f) + 1\n maxAng = ((fromIntegral (newVerts - 2)) * 180.0) / (fromIntegral newVerts)\n minAng = 180.0 / (fromIntegral newVerts)\n \n nextPolygon = Polygon {vertices = newVerts, minAngle = minAng, maxAngle = maxAng}\n in nextPolygon:(generatePolygons nextPolygon)\n\n\ncanGetAngle :: Int -> Polygon -> Bool\ncanGetAngle a p\n | fa < minAng = False\n | fa > maxAngle p = False\n | mod' fa minAng /= 0.0 = False\n | otherwise = True\n where\n fa = fromIntegral a\n minAng = minAngle p\n\n--Get the angle and return the n-sides of the polygon in String format\ngetPolygon :: Int -> String\ngetPolygon angle = let\n filteredList = filter (\\p -> canGetAngle angle p) allPolygons\n in if null filteredList\n then \"-1\"\n else show (vertices (head filteredList))\n\nmain :: IO ()\nmain = do\n q <- getLine\n let queries = read q :: Int\n queryList <- sequence (replicate queries getLine)\n let transformedList = map (read :: String -> Int) queryList\n let mapedList = map getPolygon transformedList\n putStrLn (intercalate \"\\n\" mapedList)\n\n{-\nmain :: IO ()\nmain = do\n ang <- getLine\n let angn = read ang :: Int\n let takedList = filter (\\x -> canGetAngle angn x) allPolygons\n putStrLn (show (take 9 takedList))\n-}"}, {"source_code": "import Data.List\nimport qualified Data.Fixed as Fi \n\n\ndata Polygon = Polygon{angulo :: Float , vertice :: Int} deriving (Eq, Show) \n\nobtener_poligonos::[Int] -> [Polygon]\nobtener_poligonos (x:xs)= let \n angulo1 = 180.0/(fromIntegral x)\n vertice1 = x \n in Polygon{angulo=angulo1,vertice = vertice1}:obtener_poligonos(xs) \n\nmenor:: Float -> [Polygon]-> Polygon--funcion para ver si se puede lograr con ese poligono\nmenor angulo (x:xs) = if((Fi.mod' angulo (f x))==0 && fromIntegral (div (((g x)-2)*180) (g x)) >= angulo) then x\n else menor angulo xs\n\n\nf::Polygon -> Float--Para obtener angulos\nf (Polygon {angulo = a , vertice = v}) = a\n\ng::Polygon -> Int--Para obtener vertices\ng (Polygon {angulo = a , vertice = v}) = v\n\nobtener_vertices:: [Float] -> [Polygon]-> [Int]--Entrega lista con vertices\nobtener_vertices [] _ = []\nobtener_vertices (x:xs) poli = \n [n] ++ (obtener_vertices xs poli)\n where n = g (menor x poli)\n\nimprimir::[Int]-> String--Ocupado para obtener String con los vertices\nimprimir [] = \"\"\nimprimir [x] = show x\nimprimir (x:xs) = show x ++\"\\n\"++(imprimir xs)\n\nmain:: IO()\nmain = do\n x <- getLine\n lista_angulos <- sequence (take (read x::Int) (repeat getLine))\n let lista_angulos1 = map (read::String->Float) lista_angulos\n let lista_poligonos = obtener_poligonos [3..998244353]\n let lista_vertices = obtener_vertices lista_angulos1 lista_poligonos--Se obtienen los vertices\n let hola = imprimir lista_vertices--String con los vertices\n putStrLn hola\n"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int}\n\ninstance Eq Polygon where\n (Polygon a b) == (Polygon c d) = (a == c)\n\ninstance Ord Polygon where\n compare (Polygon a b) (Polygon c d) = compare a c\n\n--Funcion que crea los poligonos en base a su numero de vertices y su angulo minimo\n--Se consideran tambien los que tienen un angulo como 22.5, 0.5, etc, tambien\n--pero su angulo minimo corresponde al doble para que sea un int \n--Para cualquier otro caso, el angulo minimo es 181, que claramente es imposible\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | (360 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 360 `div` n}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 181}\n\n--Funcion que verifica si el angulo pedido se puede lograr con un poligono de n\n--vertices y entrega el numero de vertices en caso de poderse\ncalcularVertices :: [Polygon] -> String -> Int\ncalcularVertices (x:xs) num\n | ((n `mod` (angulo_minimo x) == 0) && ((((n_vertices x)-2)*180) `div` n_vertices x) >= n) = n_vertices x\n | (n_vertices x > 360) = -1\n | otherwise = calcularVertices xs num\n where n = read num :: Int\n\nmain = do\n q <- getLine\n inputs <- replicateM (read q) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (calcularVertices poligonos_infinitos) inputs\n putStrLn $ foldl (\\x y -> x ++ (show y) ++ \"\\n\") \"\" final"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int} deriving (Show)\n\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | (360 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 360 `div` n}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 181}\n\npasarAPolygon :: [Polygon] -> String -> Int\npasarAPolygon (x:xs) num\n | ((n `mod` (angulo_minimo x) == 0) && ((((n_vertices x)-2)*180) `div` n_vertices x) >= n) = n_vertices x\n | (n_vertices x > 360) = -1\n | otherwise = pasarAPolygon xs num\n where n = read num :: Int\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (pasarAPolygon poligonos_infinitos) inputs\n mapM print final"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int}\n\ninstance Eq Polygon where\n (Polygon a b) == (Polygon c d) = (a == c)\n\ninstance Ord Polygon where\n compare (Polygon a b) (Polygon c d) = compare a c\n\n--Funcion que crea los poligonos en base a su numero de vertices y su angulo minimo\n--Se consideran tambien los que tienen un angulo como 22.5, 0.5, etc,\n--pero su angulo minimo corresponde al doble para que sea un int \n--Para cualquier otro caso, el angulo minimo es 181, que claramente es imposible\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | (360 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 360 `div` n}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 181}\n\n--Funcion que verifica si el angulo pedido se puede lograr con un poligono de n\n--vertices y entrega el numero de vertices en caso de poderse\ncalcularVertices :: [Polygon] -> String -> Int\ncalcularVertices (x:xs) num\n | ((n `mod` (angulo_minimo x) == 0) && ((((n_vertices x)-2)*180) `div` n_vertices x) >= n) = n_vertices x\n | (n_vertices x > 360) = -1\n | otherwise = calcularVertices xs num\n where n = read num :: Int\n\nmain = do\n q <- getLine\n inputs <- replicateM (read q) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (calcularVertices poligonos_infinitos) inputs\n putStrLn $ foldl (\\x y -> x ++ (show y) ++ \"\\n\") \"\" final"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int} deriving (Show)\n\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | (360 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 360 `div` n}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 181}\n\npasarAPolygon :: [Polygon] -> String -> Int\npasarAPolygon (x:xs) num\n | ((n `mod` (angulo_minimo x) == 0) && ((((n_vertices x)-2)*180) `div` n_vertices x) >= n) = n_vertices x\n | (n_vertices x > 360) = -1\n | otherwise = pasarAPolygon xs num\n where n = read num :: Int\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (pasarAPolygon poligonos_infinitos) inputs\n putStrLn $ foldl (\\x y -> x ++ (show y) ++ \"\\n\") \"\" final"}, {"source_code": "import Data.Bool\n\nmain:: IO()\nmain = do \n linea <- getLine\n --print (poligonoMin (read linea) polygons)\n lista <- loop (read linea) \n mapM_ print lista\n\n\n\nloop:: Int -> IO [Int]\nloop numero\n | numero == 0 = return []\n | otherwise = do\n sn <- getLine\n let n = read sn::Int\n others <- loop (numero-1)\n return ((poligonoMin n polygons) : others)\n \n\n\npoligonoMin:: Int -> [Polygon] -> Int\npoligonoMin angulo (p:ps) =\n if (posible angulo p)\n then (nverts p) \n else poligonoMin angulo ps\n\nposible:: Int -> Polygon -> Bool\nposible angulo poligono = \n -- trabajar los angulos como float\n -- ver si cae una cantidad de veces entera\n\n if (fromIntegral angulo)/(nangleMin poligono) == fromInteger(round ((fromIntegral angulo)/(nangleMin poligono)))\n then if ((fromIntegral angulo)/(nangleMin poligono)) <= fromIntegral((nverts poligono) - 2)\n then True\n else False\n else False\n\npolygons :: [Polygon]\npolygons = let\n poligono n = Polygon n (180/(fromIntegral n))\n in map poligono [3..]-- funcion lista\n\nnverts :: Polygon ->Int\nnverts (Polygon n _) = n\n\nnangleMin :: Polygon -> Float\nnangleMin (Polygon _ n) = n\n\n\ndata Polygon = Polygon\n { \n polygonVertex :: Int,\n polygonAngleMin :: Float\n }\n deriving (Show)"}, {"source_code": " import Data.Bool\n \n main:: IO()\n main = do \n linea <- getLine\n lista <- loop (read linea) \n mapM_ print lista\n \n \n \n loop:: Int -> IO [Int]\n loop numero\n | numero == 0 = return []\n | otherwise = do\n sn <- getLine\n let n = read sn::Int\n others <- loop (numero-1)\n return ((poligonoMin n polygons) : others)\n \n \n \n poligonoMin:: Int -> [Polygon] -> Int\n poligonoMin angulo (p:ps) =\n if (posible angulo p)\n then (nverts p) \n else poligonoMin angulo ps\n \n posible:: Int -> Polygon -> Bool\n posible angulo poligono \n -- trabajar los angulos como float\n -- ver si cae una cantidad de veces entera\n | (fromIntegral angulo)/(nangleMin poligono) /= fromInteger(round ((fromIntegral angulo)/(nangleMin poligono))) = False\n | ((fromIntegral angulo)/(nangleMin poligono)) > fromIntegral((nverts poligono) - 2) = False\n | otherwise = True\n \n polygons :: [Polygon]\n polygons = let\n poligono n = Polygon n (180/(fromIntegral n))\n in map poligono [3..]-- funcion lista\n \n nverts :: Polygon ->Int\n nverts (Polygon n _) = n\n \n nangleMin :: Polygon -> Float\n nangleMin (Polygon _ n) = n\n \n \n data Polygon = Polygon\n { \n polygonVertex :: Int,\n polygonAngleMin :: Float\n }\n deriving (Show)"}, {"source_code": "import Data.Fixed\n\nimport Data.List\n\ndata Polygon = Polygon {vertice :: Int, angulo :: Double} deriving (Show)\n\ninstance Eq Polygon where\n (==) (Polygon ver1 ang1) (Polygon ver2 ang2) =\n (ver1 == ver2) && (ang1 == ang2)\n (==) a b = False\n\nmain = do\n let poli = poligonos [3,4..] \n n_query <- getLine\n listofquerys <- sequence (take (read n_query :: Int) (repeat getLine))\n let intquerys = map (read :: String -> Int) listofquerys\n let temp = respuesta intquerys poli \n putStrLn (intercalate \"\\n\" temp) \n \npoligonos :: [Int] -> [Polygon]\npoligonos (a:as) = let\n ver = a\n ang = 180.0 / (fromIntegral a)\n in Polygon {vertice = ver, angulo = ang}:(poligonos as)\n\nrespuesta :: [Int] -> [Polygon] -> [String]\nrespuesta [a] b = let\n listafiltrada = filter (\\p -> comprobar a p) b\n in if listafiltrada == []\n then \"-1\" : []\n else show (vertice (head listafiltrada)) : []\nrespuesta (a:as) b = let\n listafiltrada = filter (\\p -> comprobar a p) b\n in if listafiltrada == []\n then \"-1\" : (respuesta as b)\n else show (vertice (head listafiltrada)) : (respuesta as b)\n\ncomprobar :: Int -> Polygon -> Bool\ncomprobar a b\n | (fromIntegral a) < (angulo b) = False\n | (fromIntegral a) > ((angulo b) * (fromIntegral (vertice b) - 2.0)) = False\n | mod' (fromIntegral a) (angulo b) == 0.0 = True\n | otherwise = False"}, {"source_code": "import Data.Fixed\n\nimport Data.List\n\ndata Polygon = Polygon {vertice :: Int, angulo :: Double} deriving (Show)\n\ninstance Eq Polygon where\n (==) (Polygon ver1 ang1) (Polygon ver2 ang2) =\n (ver1 == ver2) && (ang1 == ang2)\n (==) a b = False\n\nmain = do\n let poli = poligonos [3,4..] \n n_query <- getLine\n listofquerys <- sequence (replicate (read n_query :: Int) getLine)\n let intquerys = map (read :: String -> Int) listofquerys\n let temp = respuesta intquerys poli \n putStrLn (intercalate \"\\n\" temp) \n \npoligonos :: [Int] -> [Polygon]\npoligonos (a:as) = let\n ver = a\n ang = 180.0 / (fromIntegral a)\n in Polygon {vertice = ver, angulo = ang}:(poligonos as)\n\nrespuesta :: [Int] -> [Polygon] -> [String]\nrespuesta [a] b = let\n listafiltrada = filter (\\p -> comprobar a p) b\n in if listafiltrada == []\n then \"-1\" : []\n else show (vertice (head listafiltrada)) : []\nrespuesta (a:as) b = let\n listafiltrada = filter (\\p -> comprobar a p) b\n in if listafiltrada == []\n then \"-1\" : (respuesta as b)\n else show (vertice (head listafiltrada)) : (respuesta as b)\n\ncomprobar :: Int -> Polygon -> Bool\ncomprobar a b\n | (fromIntegral a) < (angulo b) = False\n | (fromIntegral a) > ((angulo b) * (fromIntegral (vertice b) - 2.0)) = False\n | mod' (fromIntegral a) (angulo b) == 0.0 = True\n | otherwise = False"}, {"source_code": "solve :: Int -> Int\nsolve ang = \n let n = 180 `div` (gcd 180 ang)\n in if ang <= 180 `div` n * (n - 2) then n else (2 * n)\n \nmain = do\n _ <- getLine\n contents <- getContents\n mapM_ (print . solve . read) $ lines contents"}, {"source_code": "import Data.List\nimport qualified Data.Fixed as Fi \n\ndata Polygon = Polygon{angulo :: Float , vertice :: Int} deriving (Eq, Show) \n \nobPolygons :: [Int] -> [Polygon]\nobPolygons (x:xs)= let \n anglePolygon = 180.0/(fromIntegral x)\n verticePolygon = x \n in Polygon{angulo=anglePolygon,vertice = verticePolygon}:obPolygons(xs) \n\n--Esta funcion nos sice si se logra con el poligono\nachievesPolygon :: Float -> [Polygon] -> Polygon\nachievesPolygon angulo (x:xs) = if((Fi.mod' angulo (angles x))==0 && fromIntegral (div (((vertices x)-2)*180) (vertices x)) >= angulo) then x\n else achievesPolygon angulo xs\n \n-- Nos obtines los angulos\nangles :: Polygon -> Float\nangles (Polygon {angulo = a , vertice = v}) = a\n\n--Nos obtiene los vertices \nvertices :: Polygon -> Int\nvertices (Polygon {angulo = a , vertice = v}) = v\n \n--Nos entrega una lista con los vertices\nobVertices :: [Float] -> [Polygon] -> [Int]\nobVertices [] _ = []\nobVertices (x:xs) poly = \n [n] ++ (obVertices xs poly)\n where n = vertices (achievesPolygon x poly)\n \n--Se ocupa para poder dejar todo en String y mostrarlo por pantalla\njoinPrint :: [Int] -> String\njoinPrint [] = \"\"\njoinPrint [x] = show x\njoinPrint (x:xs) = show x ++\"\\n\"++(joinPrint xs)\n \nmain :: IO()\nmain = do\n datos <- getLine\n listAngles1 <- sequence (take (read datos::Int) (repeat getLine))\n let listAngles = map (read::String->Float) listAngles1\n let listVertices = obVertices listAngles (obPolygons [3..998244353])\n putStrLn (joinPrint listVertices)"}, {"source_code": "import Control.Monad\n\ndata Polygon = Polygon {angin :: Float,angmin :: Float} deriving (Show)\n\nlista_inf:: [Polygon]\nlista_inf = [Polygon (((fromIntegral i)-2)*180/(fromIntegral i)) (180.0/(fromIntegral i)) | i <- [3..]]\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let x = map (read::String->Float) inputs\n let z = map auxi x \n mapM_ print (map round z)\n\nfun2:: Float -> [Polygon] -> Polygon\nfun2 ang (x:xs) =\n if ((ang == (angmin x)) || (ang == (angin x)))\n then x\n else if (ang < (angmin x))\n then (fun2 ang xs)\n else if (lograr ang x)\n then x\n else (fun2 ang xs)\n \nlograr:: Float -> Polygon -> Bool\nlograr ang pol = do\n let res = (angin pol) - ang\n if (res < 0)\n then False\n else if (floor (angmin pol) == ceiling (angmin pol))\n then if (((round res) `mod` (round (angmin pol))) == 0) then True else False\n else False\n\nauxi:: Float -> Float\nauxi n = \n if (n>180 || n<=0) then -1.0 else (nver (fun2 n lista_inf))\n\nnver:: Polygon -> Float\nnver pol = 360/(180 - (angin pol))"}, {"source_code": "import Control.Monad\n\ndata Polygon = Polygon {angin :: Float,angmin :: Float} deriving (Show)\n\nlista_inf:: [Polygon]\nlista_inf = [Polygon (((fromIntegral i)-2)*180/(fromIntegral i)) (180.0/(fromIntegral i)) | i <- [3..]] -- Se crea la lista infinita de poligonos\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let x = map (read::String->Float) inputs --x siendo la lista de los inputs\n let z = map fun x \n mapM_ print (map round z) \n\nfun2:: Float -> [Polygon] -> Polygon --Funcion que recorre la lista de Polygons y entrega el primer poligono que cumpla la condicion\nfun2 ang (x:xs) =\n if ((ang == (angmin x)) || (ang == (angin x)))\n then x\n else if (ang < (angmin x))\n then (fun2 ang xs)\n else if (lograr ang x)\n then x\n else (fun2 ang xs)\n \nlograr:: Float -> Polygon -> Bool --Funcion que verifica si se puede formar el angulo de entrada con los angulos dentro del poligono\nlograr ang pol = do\n let res = (angin pol) - ang\n if (res < 0)\n then False\n else if (floor (angmin pol) == ceiling (angmin pol)) --Si el angulo minimo del poligono es un decimal, se entraga falso ya que las entradas son int y/o ese angulo se puede formar con algun poligono anterior\n then if (((round res) `mod` (round (angmin pol))) == 0) then True else False \n else False\n\nfun:: Float -> Float\nfun n = if (n>180 || n<=0) then -1.0 else (nver (fun2 n lista_inf)) --funcion que retorna -1 si el angulo no esta entre 1 y 180 y retorna el numero de vertices del poligono que cumpla la condicion\n\nnver:: Polygon -> Float --Funcion que otorga el numero de vertices del poligono\nnver pol = 360/(180 - (angin pol))"}, {"source_code": "import Control.Monad\ndata Polygon = Polygon { angulo :: Float, vertice :: Int}\n\n--Funcion principal que nos permite obtener la lista de los verticeses de todos los imput solicitados nos ayuda a formar la resp final\nfuncion :: [Int] -> String-> [Int]\nfuncion [] angulo1 = let\n in [vertices (head (filter (es_poligono (read angulo1 :: Float)) (map polygon [3 ..])))]\nfuncion (x:xs) angulo1 = let\n in vertices (head (filter (es_poligono (read angulo1 :: Float)) (map polygon[3 ..]))) : (x:xs)\n--Funcion que nos permite en el output dar vuelta la lista de la funcion principal puesto que la funcion en la primera posicion esta el ultimo leido y asi \nrevertir_lista:: [numero] -> [numero]\nrevertir_lista [] = []\nrevertir_lista (x:xs) = revertir_lista (xs) ++ [x]\n--Outout final\noutput:: Int -> IO ()\noutput out =\n print out\n\n--Confirmacion si es o no posible con el angulo entregado obtener un poligono regular ocupa el angulo minimo que pueda obterner de un poligono regular cualquiera \n--La formula emplea sus diag (n-2) y el angulo dado \nes_poligono :: Float -> Polygon -> Bool\nes_poligono angulo1 \n Polygon { angulo = ang,\n vertice = vert} = let\n ang_min= ang / ((fromIntegral vert) - 2)\n angulos = [ang, (ang - ang_min) .. ang_min]\n in if (angulo1 `elem` angulos) --Ve si el angulo esta dentro de las posibilidades de formar parte de un regular idea: http://zvon.org/other/haskell/Outputprelude/elem_f.html\n then True \n else False\n\n--Gnera los poligonos regulares solicitaodos ocupamos la formula de angulo en los vertices dada en uno de los links \npolygon :: Int -> Polygon\npolygon vert = \n Polygon { angulo = (180*((fromIntegral vert) - 2)) / fromIntegral vert, \n vertice = vert}\n \n--Obtiene los vertices\nvertices :: Polygon -> Int\nvertices Polygon \n {vertice = vert, \n angulo = ang} =\n vert\n\n--Consultamos al usuario las consultas y posterior ingresa uno a uno los angulos dependiendo del numero de consultas\n--Iteramos la lista de los angulos mediante un foldl\n--Posterior llamamos a nuestra funcion principal y imprimimos la resp por pantalla\n--\nmain::IO()\nmain = do\n numero_consulta <- getLine\n lista_angulos <- replicateM (read numero_consulta :: Int) getLine \n (mapM_ output(revertir_lista (foldl funcion [] lista_angulos)))"}, {"source_code": "import System.Environment\nimport System.IO\nimport qualified Data.Fixed as F\n\nmain = do\n cant<- getLine\n angulos <- readLines (read cant::Int)\n let listaPoli = infAngles 3\n final = maker angulos listaPoli\n mapM print (map toInt final)\ndata Poligon = Poligon { vertices :: Float\n , angMenor :: Float\n } deriving (Show)\n\n\n\nreadLines :: Int -> IO [Float]\nreadLines 0 = return []\nreadLines n = do\n x <- fmap read getLine\n rest <- readLines (n-1)\n return $ x : rest\n\ninfAngles :: Float -> [Poligon]\ninfAngles vert =\n let minAngle = (/) 180.0 vert\n poli = (Poligon vert minAngle)\n in poli:(infAngles (vert+1))\n\nminAng :: Float -> [Poligon] ->Poligon\nminAng num (p:ps) =\n let nVer = nVerts p in\n if ((F.mod' num (mAngle p)) == 0 && ((nVer-2)*180/nVer) >= num )\n\n then\n p\n else\n minAng num ps\n\nnVerts :: Poligon -> Float\nnVerts (Poligon n _ ) = n\n\nmAngle :: Poligon -> Float\nmAngle (Poligon _ a ) = a\n\nmaker :: [Float] -> [Poligon] ->[Float]\nmaker [] _ = []\nmaker (x:xs) listaPoli =\n let pol = minAng x listaPoli\n in [(nVerts pol)] ++ (maker xs listaPoli)\n\ntoInt :: Float -> Int\ntoInt = round\n"}, {"source_code": "data Polygon = Polygon {ver :: Int, ang :: Float}\n\nmain = do\n queries <- getLine\n commands <- sequence (replicate (read queries) getLine)\n let min = foldl iterator [] commands\n let answers = reverse min\n mapM_ showMin answers\n\nshowMin :: Int -> IO ()\nshowMin x = print x\n\niterator :: [Int] -> String -> [Int]\niterator [] angle = let\n check = checkAngle (read angle)\n polygonList = map polygonGenerator [3 ..]\n posibleAnswers = filter check polygonList\n in [getVer (head posibleAnswers)]\niterator (a:as) angle = let\n check = checkAngle (read angle :: Float)\n polygonList = map polygonGenerator [3 ..]\n posibleAnswers = filter check polygonList\n in getVer (head posibleAnswers) : (a:as)\n\ngetVer :: Polygon -> Int\ngetVer Polygon {ver = x, ang = y} = x\n\npolygonGenerator :: Int -> Polygon\npolygonGenerator x = Polygon {ver = x, ang = (((fromIntegral x) - 2) * 180) / fromIntegral x}\n\ncheckAngle :: Float -> Polygon -> Bool\ncheckAngle angle Polygon {ver = x, ang = y} = let\n z = y / ((fromIntegral x) - 2)\n angulos = [y, (y - z) .. z]\n in if (angle `elem` angulos) then True else False"}, {"source_code": "solve :: Int -> Int\nsolve ang = \n let n = 180 `div` (gcd 180 ang)\n in if ang <= 180 `div` n * (n - 2) then n else (2 * n)\n\nmain = do\n _ <- getLine\n contents <- getContents\n mapM_ (print . solve . read) $ lines contents"}, {"source_code": "import Data.Fixed (mod')\n\n{- el type Polygon contiene los siguientes parametros\n vertex = numero de vertices\n minAngle = el angulo minimo que puede poseer\n maxAngle = el angulo maximo que puede poseer -}\ndata Polygon = Polygon { vertex :: Int\n , minAngle :: Float\n , maxAngle :: Float\n } deriving (Show)\n\n-- poryList crea una lista de Polygon con la lista dada (en este caso, de 3 a infinito, poligonos de 1 y 2 lados no existen)\nporyList :: [Int] -> [Polygon]\nporyList [] = []\nporyList (x:xs) = (Polygon { vertex = x, minAngle = ang, maxAngle = ang * (y - 2)}):(poryList xs)\n where y = fromIntegral x :: Float\n ang = 180 / y\n\n{- checkPory recibe un Polygon y un angulo, y revisa si es posible hacer ese angulo con el Polygon dado\n se utilizo mod' para poder trabajar con Floats -}\ncheckPory :: Polygon -> Int -> Bool\ncheckPory p n\n | mod' ang (minAngle p) == 0 && ang <= (maxAngle p) = True\n | otherwise = False\n where ang = fromIntegral n :: Float\n\n-- checkFor revisa cada Polygon de la lista dada y revisa si checkPory es verdadero. En caso de que el angulo dado sea mayor o igual a 180 la figura no puede hacerse y retorna -1\ncheckFor :: [Polygon] -> Int -> Int\ncheckFor (x:xs) n \n | n >= 180 = -1\n | checkPory x n = vertex x\n | otherwise = checkFor xs n\n\nmain :: IO()\nmain = do\n let pList = poryList [3..] -- pList es una lista infinita de Polygon\n q <- getLine\n let query = (read q :: Int)\n inputList <- (sequence (replicate query getLine))\n let angList = map (read :: String -> Int) inputList\n let porygonZ = map (checkFor pList) angList\n mapM_ print porygonZ --mapM_ se utilizo para printear en lineas separadas"}], "negative_code": [{"source_code": "data Polygon = Polygon {ver :: Int, ang :: Int}\n\nmain = do\n queries <- getLine\n commands <- sequence (replicate (read queries) getLine)\n let min = foldl iterator [] commands\n let answers = reverse min\n mapM_ showMin answers\n\nshowMin :: Int -> IO ()\nshowMin x = print x\n\niterator :: [Int] -> String -> [Int]\niterator [] angle = let\n check = checkAngle (read angle)\n polygonList = map polygonGenerator [3 ..]\n posibleAnswers = filter check polygonList\n in [getVer (head posibleAnswers)]\niterator (a:as) angle = let\n check = checkAngle (read angle :: Float)\n polygonList = map polygonGenerator [3 ..]\n posibleAnswers = filter check polygonList\n in getVer (head posibleAnswers) : (a:as)\n\ngetVer :: Polygon -> Int\ngetVer Polygon {ver = x, ang = y} = x\n\npolygonGenerator :: Int -> Polygon\npolygonGenerator x = Polygon {ver = x, ang = ((x-2) * 180) `div` x}\n\ncheckAngle :: Float -> Polygon -> Bool\ncheckAngle angle Polygon {ver = x, ang = y} = let\n a = toFloat x\n b = toFloat y\n c = b / (a-2)\n angulos = [b, (b - c) .. c]\n in if (angle `elem` angulos) then True else False\n\ntoFloat :: Int -> Float\ntoFloat x = fromIntegral x"}, {"source_code": "data Polygon = Polygon {ver :: Int, ang :: Int}\n\nmain = do\n queries <- getLine\n commands <- sequence (replicate (read queries) getLine)\n let min = foldl iterator [] commands\n let answers = reverse min\n mapM_ showMin answers\n\nshowMin :: Int -> IO ()\nshowMin x = print x\n\niterator :: [Int] -> String -> [Int]\niterator [] angle = let\n check = checkAngle (read angle)\n polygonList = map polygonGenerator [3 ..]\n posibleAnswers = filter check polygonList\n in [getVer (head posibleAnswers)]\niterator (a:as) angle = let\n check = checkAngle (read angle)\n polygonList = map polygonGenerator [3 ..]\n posibleAnswers = filter check polygonList\n in getVer (head posibleAnswers) : (a:as)\n\ngetVer :: Polygon -> Int\ngetVer Polygon {ver = x, ang = y} = x\n\npolygonGenerator :: Int -> Polygon\npolygonGenerator x = Polygon {ver = x, ang = ((x-2) * 180) `div` x}\n\ncheckAngle :: Int -> Polygon -> Bool\ncheckAngle angle Polygon {ver = x, ang = y} = let\n angulos = [y, (y - (y `div` (x-2))) .. (y `div` (x-2))]\n in if (angle `elem` angulos) then True else False"}, {"source_code": "import Data.Fixed (mod')\n\ndata Polygon = Polygon { vertex :: Int\n , minAngle :: Float\n , maxAngle :: Float\n , intAngle :: Float\n } deriving (Show)\n\nporyList :: [Int] -> [Polygon]\nporyList [] = []\nporyList (3:xs) = (Polygon { vertex = 3, minAngle = 60.0, maxAngle = 60.0, intAngle = 60.0}):(poryList xs)\nporyList (4:xs) = (Polygon { vertex = 4, minAngle = 90.0, maxAngle = 90.0, intAngle = 90.0}):(poryList xs)\nporyList (x:xs) = (Polygon { vertex = x, minAngle = ang, maxAngle = ang * (y - 4), intAngle = ang * (y - 2)}):(poryList xs)\n where y = fromIntegral x :: Float\n ang = 180 / y\n\ncheckPory :: [Polygon] -> Int -> Int\ncheckPory [] _ = -1\ncheckPory (x:xs) n\n | n == 180 = -1\n | mod' nn (minAngle x) == 0 && nn <= (maxAngle x) = vertex x\n | nn == intAngle x = vertex x\n | otherwise = checkPory xs n\n where nn = fromIntegral n :: Float\n\ncheckFor :: [Polygon] -> [Int] -> [Int]\ncheckFor _ [] = []\ncheckFor x (y:ys) = (checkPory x y):(checkFor x ys)\n\nmain :: IO()\nmain = do\n let h = poryList [3..]\n q <- getLine\n let query = (read q :: Int)\n angList <- (sequence (replicate query getLine))\n let pList = map (read :: String -> Int) angList\n mapM_ print (checkFor h pList)"}, {"source_code": "import Data.Fixed (mod')\n\ndata Polygon = Polygon { vertex :: Int\n , minAngle :: Float\n , maxAngle :: Float\n , intAngle :: Float\n } deriving (Show)\n\nporyList :: [Int] -> [Polygon]\nporyList [] = []\nporyList (3:xs) = (Polygon { vertex = 3, minAngle = 60.0, maxAngle = 60.0, intAngle = 60.0}):(poryList xs)\nporyList (4:xs) = (Polygon { vertex = 4, minAngle = 45.0, maxAngle = 45.0, intAngle = 90.0}):(poryList xs)\nporyList (x:xs) = (Polygon { vertex = x, minAngle = ang, maxAngle = ang * (y - 4), intAngle = ang * (y - 2)}):(poryList xs)\n where y = fromIntegral x :: Float\n ang = 180 / y\n\ncheckPory :: [Polygon] -> Int -> Int\ncheckPory [] _ = -1\ncheckPory (x:xs) n\n | n >= 180 = -1\n | mod' nn (minAngle x) == 0 && nn <= (maxAngle x) = vertex x\n | nn == intAngle x = vertex x\n | otherwise = checkPory xs n\n where nn = fromIntegral n :: Float\n\ncheckFor :: [Polygon] -> [Int] -> [Int]\ncheckFor _ [] = []\ncheckFor x (y:ys) = (checkPory x y):(checkFor x ys)\n\nmain :: IO()\nmain = do\n let h = poryList [3..]\n q <- getLine\n let query = (read q :: Int)\n angList <- (sequence (replicate query getLine))\n let pList = map (read :: String -> Int) angList\n mapM_ print (checkFor h pList)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Fixed\ndata Polygon = Polygon {angulo :: Float, vertice :: Int} deriving (Show)\n\ninstance Eq Polygon where --Instancia pedida en el bonus\n (==) (Polygon ver1 ang1) (Polygon ver2 ang2) = (ver1 == ver2) && (ang1 == ang2)\n (==) a b = False\n\npoly :: [Int] -> [Polygon] --Generador de poligonos\npoly (x:xs) = let \n vert = x\n ang = 180.0 / (fromIntegral x) in Polygon { angulo = ang, vertice = vert}:poly xs\n\nminVert :: [Int] -> [Polygon] -> [String] --Funci\u00f3n encargada de entregar el angulo m\u00ednimo correspondiente a cada caso\nminVert [a] b = let\n filteredList = filter (\\p -> aux a p) b in if filteredList == []\n then \"-1\" : []\n else show (vertice (head filteredList)) : []\nminVert (a:as) b = let\n filteredList = filter (\\p -> aux a p) b in if filteredList == []\n then \"-1\" : (minVert as b)\n else show (vertice (head filteredList)) : (minVert as b)\n\naux :: Int -> Polygon -> Bool --Funci\u00f3n que ratifica que el angulo obtenido exista\naux x y\n | mod' (fromIntegral x) (angulo y) == 0.0 = True\n | (fromIntegral x) < (angulo y) = False\n | (fromIntegral x) > ((angulo y) * (fromIntegral (vertice y) - 2.0)) = False\n | otherwise = False \n\nmain :: IO ()\nmain = do\n casos <- getLine \n let n = read casos::Int \n angulos <- replicateM n getLine \n let poligonos = poly [3..998244353] \n let intAngulos = map (read :: String -> Int) angulos\n let output = minVert intAngulos poligonos\n putStrLn (intercalate \"\\n\" output) "}, {"source_code": "import System.IO\n\ndata Polygon = Polygon { vertices ::Int ,minAng ::Float} deriving(Show)\n\ntoInt:: Float->Int\ntoInt = round\n\ncanBeDone:: Polygon-> Int -> Bool\ncanBeDone p a= a `mod` toInt (minAng p) == 0\n\nforEach ::[Polygon]->Int ->Int\nforEach [] a= (-1)\nforEach (p:ps) a= do\n if(canBeDone p a)\n then getVertices p\n else if(getVertices p <2000000)\n then forEach ps a\n else -1\n\ngetIterationsLines :: Int ->[Polygon] -> IO [String]\ngetIterationsLines n lista\n | n <= 0 = return []\n | otherwise = do\n angle <- getLine\n print $ forEach lista (read angle ::Int)\n xs <- getIterationsLines (n-1) lista\n return (angle:xs)\n\nforLoop ::Int->[Polygon]->Int\nforLoop 0 _ = (-1)\nforLoop n list=\n if (n>0)\n then do\n -- let min= forEach list readLine\n forLoop (n-1) list\n else\n 0\n \n\ngetVertices:: Polygon -> Int\ngetVertices p = vertices p\n\nmain = do\n iterations <- getLine\n let lista_infinita = [ Polygon i (180/fromIntegral i) | i<-[3..]]\n let ite = read iterations::Int\n getIterationsLines ite lista_infinita\n return ()\n\n\n\n\n"}, {"source_code": "import System.IO\nimport Data.Fixed\n\ndata Polygon = Polygon { vertices ::Int ,minAng ::Float} deriving(Show)\n\ncanBeDone:: Polygon-> Float -> Bool\ncanBeDone p a= mod' a (minAng p) == 0.0 \nforEach ::[Polygon]->Float ->Int\nforEach [] a= (-1)\nforEach (p:ps) a= do\n if(canBeDone p a)\n then getVertices p\n else if(getVertices p <2000000)\n then forEach ps a\n else -1\n\ngetIterationsLines :: Int ->[Polygon] -> IO [String]\ngetIterationsLines n lista\n | n <= 0 = return []\n | otherwise = do\n angle <- getLine\n print $ forEach lista (read angle ::Float)\n xs <- getIterationsLines (n-1) lista\n return (angle:xs)\n \n\ngetVertices:: Polygon -> Int\ngetVertices p = vertices p\n\nmain = do\n iterations <- getLine\n let lista_infinita = [ Polygon i (180/fromIntegral i) | i<-[3..]]\n let ite = read iterations::Int\n getIterationsLines ite lista_infinita\n return ()\n\n\n\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n--se crea el data Polygon con los datos angulosInt, vertices, anguloMin y anguloMax\ndata Polygon = Polygon {\n angulosInt ::Double,\n vertices ::Int,\n anguloMin ::Double,\n anguloMax ::Double\n} deriving (Ord, Eq,Show)\n\n--se define cada uno de los atributos de Polygon\n--angulos internos = 180*(cantidad de vertices-2)\n--angulo Maximo = angulos Internos / cantidad de vertices\n--angulo Minimo (este fue probando) = angulo maximo / (cantidad de vertices - 2)\n--Recibe un Int (cantidad de vertices) y entrega un Polygon con todos sus datos\ndefine :: Int -> Polygon\ndefine ver = let \n doubVer = fromIntegral ver ::Double\n angInt = 180.0 * (doubVer - 2.0)\n angMax = angInt / doubVer\n angMin = angMax/(doubVer-2.0)\n in Polygon {vertices = ver, angulosInt = angInt, anguloMin = angMin, anguloMax = angMax}\n\n--entrega el poligono donde se puede formar el angulo\nbuscarPol :: Int -> Polygon -> Polygon\nbuscarPol ang pol = let\n ver = vertices pol\n in if (isPol (fromIntegral ang ::Double) pol) then pol else buscarPol ang (define (ver+1))\n\n--Comprueba si es el polygono pedido\n--recibe un angulo y el polygono inicial y entrega True si es el polygono que se pide y False en caso contrario\nisPol :: Double-> Polygon -> Bool\nisPol ang pol=let\n angMin = anguloMin pol\n angMax = anguloMax pol\n --angs1 es la divisi\u00f3n normal, angs2 es la division entera entre el angulo dado y el angulo minimo del poligono\n angs1 = (ang / angMin)\n angs2 = (fromIntegral (round (ang/angMin)) :: Double)\n --si angs1 y angs2 son iguales significa que el angulo minimo es divisor del angulos dado, por lo que es el poligono pedido\n in if (ang<=angMax && angs1-angs2==0.0) then True else False\n\noutput:: String -> IO ()\noutput out = print (out)\n\nmain::IO()\nmain = do\n consultas <- getLine\n --se recibe un input multiple con replicateM\n angulos <- replicateM (read consultas ::Int) getLine\n let polInicial = define 3\n --se crea la lista de polygonos, al reves, por lo que se utiliza reverse para mantenerla segun lo dado por el usuario\n --luego se entrega en consola cada uno de los datos con intercalate y la funci\u00f3n output\n output (intercalate \" \" (reverse (foldl (\\x y -> (show (vertices (buscarPol (read y ::Int) polInicial))) : x) [] angulos)))"}, {"source_code": "import qualified Data.ByteString.Char8 as C\ndata Polygon = Polygon {vertexNumber :: Int, minAngle :: Double, angles :: [Double]} deriving (Show)\nisInt x = x == fromInteger (round x)\n\npolygonList = [Polygon{vertexNumber = i, minAngle = 180.0/(fromIntegral i :: Double), angles = [((180.0/(fromIntegral i :: Double)) * (fromIntegral (j - 2) :: Double)) | j <- [3..i]]} | i <- [3..]]\npossibleAngle :: Double -> Bool\npossibleAngle angle = let\n polygon = take 1 ([polygon | polygon <- (filter ((\\a x -> elem a (angles x)) angle) polygonList)]) -- arreglar\n len = length polygon\n in if((len == 1) && ((vertexNumber (polygon !! 0) ) <= 998244353)) then True else False\n\ncontainsAngle :: Polygon -> Double -> Bool\ncontainsAngle polygon angle = if ((mod ((round angle :: Int)*2*(vertexNumber polygon)) 360) == 0) then True else False\n\nsolution angle = vertexNumber (head [ polygon | polygon <- polygonList, True == containsAngle polygon angle]) -- usando lazyness\n\nreadChar8 :: IO [Int]\nreadChar8 = map parse . C.words <$> C.getContents where parse s = let Just (n, _) = C.readInt s in n\n\nmain :: IO()\nmain = do\n ints <- readChar8 \n let (n:xs) = ints \n mapM_ (\\x -> print (solution (fromIntegral x :: Double))) xs\n --CTRL + D\n"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int} deriving (Show)\n\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 180}\n\npasarAPolygon :: [Polygon] -> String -> Int\npasarAPolygon (x:xs) num\n | ((read num :: Int) `mod` (angulo_minimo x) == 0) = n_vertices x\n | otherwise = pasarAPolygon xs num\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (pasarAPolygon poligonos_infinitos) inputs\n mapM print final"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int} deriving (Show)\n\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 181}\n\npasarAPolygon :: [Polygon] -> String -> Int\npasarAPolygon (x:xs) num\n | ((n `mod` (angulo_minimo x) == 0) && ((((n_vertices x)-2)*180) `div` n_vertices x) >= n) = n_vertices x\n | (n_vertices x > 180) = -1\n | otherwise = pasarAPolygon xs num\n where n = read num :: Int\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (pasarAPolygon poligonos_infinitos) inputs\n mapM print final"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\ndata Polygon = Polygon {n_vertices :: Int, angulo_minimo :: Int} deriving (Show)\n\ncrearPoligonos :: Int -> Polygon\ncrearPoligonos n\n | (180 `mod` n == 0) = Polygon {n_vertices = n, angulo_minimo = 180 `div` n}\n | (n == 360) = Polygon {n_vertices = n, angulo_minimo = 1}\n | otherwise = Polygon {n_vertices = n, angulo_minimo = 181}\n\npasarAPolygon :: [Polygon] -> String -> Int\npasarAPolygon (x:xs) num\n | ((n `mod` (angulo_minimo x) == 0) && ((((n_vertices x)-2)*180) `div` n_vertices x) >= n) = n_vertices x\n | (n_vertices x > 360) = -1\n | otherwise = pasarAPolygon xs num\n where n = read num :: Int\n\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let poligonos_infinitos = map crearPoligonos [3..]\n let final = map (pasarAPolygon poligonos_infinitos) inputs\n mapM print final"}, {"source_code": "import System.Environment\nimport System.IO\n\nmain = do\n cant<- getLine\n angulos <- readLines (read cant::Int)\n let listaPoli = foldl infAngles [] [3..]\n print angulos\n print (nVerts (head listaPoli))\n\ndata Poligon = Poligon { vertices :: Int\n , angMenor :: Int\n } deriving (Show)\n\n\n\nreadLines :: Int -> IO [Int]\nreadLines 0 = return []\nreadLines n = do\n x <- fmap read getLine\n rest <- readLines (n-1)\n return $ x : rest\n\ninfAngles :: [Poligon] -> Int -> [Poligon]\ninfAngles list vert =\n let minAngle = 180 `div` vert\n poli = (Poligon vert minAngle)\n in poli:list\n\nnVerts :: Poligon -> Int\nnVerts (Poligon n _ ) = n\n"}], "src_uid": "d11b56fe172110d5dfafddf880e48f18"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve xs = foldl (\\(!c) ((lm, lc), x, (rm, rc)) -> if sort [lm, x, rm] == min3 then c + lc * rc else c) 0 $ zip3 lmc (tail xs) (tail $ tail rmc)\n where\n min3 = take 3 $ sort xs\n iv = (10^(9 :: Int), 0 :: Int64)\n lmc = tail $ scanl go iv xs\n rmc = reverse $ tail $ scanl go iv $ reverse xs\n go (!m, !c) x\n | m < x = (m, c)\n | m == x = (m, c + 1)\n | otherwise = (x, 1)\n\nmain = do\n B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\n\ngetInts::IO [Integer]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInteger s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nminCnt::(Integer, Integer)->(Integer, Integer)->(Integer, Integer)\nminCnt (x, v) (y, w) = case compare x y of\n EQ -> (x, v + w)\n LT -> (x, v)\n GT -> (y, w)\n\nminProds::[Integer]->[(Integer, Integer)]->[(Integer, Integer)]\nminProds xs us = let vs = reverse $ scanl1 minCnt $ reverse us\n prod x (y, v) = (x * y, v)\n in zipWith prod xs $ tail vs\n\nsolution::[Integer]->Integer\nsolution xs = let mps1 = minProds xs $ fmap (, 1) xs\n mps2 = minProds xs mps1\n mm = foldl1' minCnt mps2\n in snd mm\n\n\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ solution xs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve xs = foldl (\\(!c) ((lm, lc), x, (rm, rc)) -> if sort [lm, x, rm] == min3 then c + lc * rc else c) 0 $ zip3 lmc (tail xs) (tail $ tail rmc)\n where\n min3 = take 3 $ sort xs\n iv = (10^(9 :: Int), 0 :: Integer)\n lmc = tail $ scanl go iv xs\n rmc = reverse $ tail $ scanl go iv $ reverse xs\n go (!m, !c) x\n | m < x = (m, 1)\n | m == x = (m, c + 1)\n | otherwise = (x, 1)\n\nmain = do\n B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve xs = foldl (\\(!c) ((lm, lc), x, (rm, rc)) -> if sort [lm, x, rm] == min3 then c + lc * rc else c) 0 $ zip3 lmc (tail xs) (tail $ tail rmc)\n where\n min3 = take 3 $ sort xs\n iv = (10^(9 :: Int), 0 :: Int64) \n lmc = tail $ scanl go iv xs\n rmc = reverse $ tail $ scanl go iv $ reverse xs\n go (!m, !c) x\n | m < x = (m, 1)\n | m == x = (m, c + 1)\n | otherwise = (x, 1)\n\nmain = do\n B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve xs = foldl (\\(!c) ((lm, lc), x, (rm, rc)) -> if sort [lm, x, rm] == min3 then c + lc * rc else c) 0 $ zip3 lmc (tail xs) (tail $ tail rmc)\n where\n min3 = take 3 $ sort xs\n iv = (10^(9 :: Int), 0 :: Int) \n lmc = tail $ scanl go iv xs\n rmc = reverse $ tail $ scanl go iv $ reverse xs\n go (!m, !c) x\n | m < x = (m, 1)\n | m == x = (m, c + 1)\n | otherwise = (x, 1)\n\nmain = do\n B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}], "src_uid": "4c2d804bb2781abfb43558f8b2c6424f"} {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.Functor\n\nshiftFirst :: Int -> Int -> [[Int]] -> [[Int]]\nshiftFirst l sh = map $ map $ \\x -> (x + sh) `mod` l\n\nbest :: Int -> [[Int]] -> Int\nbest l xs = foldl1 min $ do\n sh <- [0 .. pred l]\n pure $ (sh +) $ sum $ map (foldl1 min) $ shiftFirst l sh xs\n\npossibleShifts :: [String] -> [[Int]]\npossibleShifts (x:xs) = map f xs where\n l = length x\n f s = do\n sh <- [0 .. pred l]\n if drop sh s ++ take sh s == x then pure sh else []\n\nmain = do\n n <- read <$> getLine\n xs <- sequence $ replicate n getLine\n let ys = possibleShifts xs\n putStrLn $ show $\n if and $ map ((/= 0) . length) ys then\n best (length $ head xs) ys\n else\n -1\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Control.Monad\n\nrotates :: [a] -> [[a]]\nrotates xs = init $ zipWith (++) ts is\n where is = inits xs\n ts = tails xs\n\nsolve :: [String] -> Int\nsolve ss | null candidates = -1\n | otherwise = minimum candidates\n where candidates = filter (/= (-1)) $ map numSteps ss\n rs = map rotates ss\n numSteps gs = case liftM sum . sequence $ map (findIndex (== gs)) rs of\n Just s -> s\n Nothing -> -1\n\ntest0 = [\"xzzwo\", \"zwoxz\", \"zzwox\", \"xzzwo\"]\ntest1 = [\"molzv\", \"lzvmo\"]\ntest2 = [\"kc\", \"kc\", \"kc\"]\ntest3 = [\"aa\", \"aa\", \"ab\"]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ss <- replicateM n getLine\n print $ solve ss\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Monoid\nimport Data.Traversable\n\ngetInt::IO Int\ngetInt = do\n line <- BS.getLine\n let Just (x, _ ) = BS.readInt line\n return x\n\nshift::Int->ByteString->ByteString\nshift i = BS.append <$> BS.drop i <*> BS.take i\n\nnewtype Min = Min{getMin::Int} deriving (Eq, Ord, Show)\ninstance Monoid Min where\n Min a `mappend` Min b = Min (min a b)\n mempty = Min maxBound\n\nmain = do\n n <- getInt\n l1:ls <- replicateM n readLine\n let shifts l = (,) . Min <*> (`shift` l) <$> [0..BS.length l - 1]\n lastRes = foldM minRevAll (shifts l1) ls\n minRevAll prev l = (fmap . flip (,) . snd <*> minRev prev) `traverse` shifts l\n minRev prev (i, l) = (+~i) <$> foldMap (check l) prev\n check l (j, p) = if p == l then Just j else Nothing\n result = maybe (-1) (getMin . foldMap fst) lastRes\n Min a +~ Min b = Min (a + b)\n print result where readLine = BS.takeWhile isAlpha <$> BS.getLine\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Monoid\nimport Data.Traversable\n\ngetInt::IO Int\ngetInt = do\n line <- BS.getLine\n let Just (x, _ ) = BS.readInt line\n return x\n\nshift::Int->ByteString->ByteString\nshift i = BS.append <$> BS.drop i <*> BS.take i\n\nnewtype Min a= Min{getMin::a} deriving (Eq, Ord, Show)\ninstance (Bounded a, Ord a) => Monoid (Min a) where\n Min a `mappend` Min b = Min (min a b)\n mempty = Min maxBound\n\nmain = do\n n <- getInt\n l1:ls <- replicateM n readLine\n let shifts l = (,) . Min <*> (`shift` l) <$> [0..BS.length l - 1]\n lastRes = foldM minRevAll (shifts l1) ls\n minRevAll prev l = (fmap . flip (,) . snd <*> minRev prev) `traverse` shifts l\n minRev prev (i, l) = (+~i) <$> foldMap (check l) prev\n check l (j, p) = if p == l then Just j else Nothing\n result = maybe (-1) (getMin . foldMap fst) lastRes\n Min a +~ Min b = Min (a + b)\n print result where readLine = BS.takeWhile isAlpha <$> BS.getLine\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nfnd [] _ _ = (-1)\nfnd (x:xs) e i\n\t|isPrefixOf e x = i\n\t|otherwise = fnd xs e (i+1)\n\nf x y\n\t|f==0 = 0\n\t|otherwise = (length x) - f where\n\t\tf=fnd (tails(concat (replicate 2 x))) y 0\ntoL (x:xs) = 0:map (f x) xs\n\t\nextract (x:xs)=take (read x::Int) xs\n\ndist x y m\n\t|xdist y point m) x\n\t\nallSolution x m= minimum $ map (\\point->solve x point m) [0..m-1]\n\nbuild x=[take l ((drop n cx))|n<-[0..l-1]] where\n\tcx=cycle x\n\tl=length x\n\nres x\n\t|any (>l) tl = -1\n\t|otherwise = allSolution tl l where\n\t\ttl=toL x\n\t\tl=length (head x)\n\nallall x=minimum [res xx|xx<-build x]\t\t\n\t\t\n\nmain=interact$show.allall.extract.lines\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM)\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, reverse, dropWhile, unpack)\nimport qualified Data.Maybe as M (fromJust, isNothing)\nimport Data.Char (isSpace)\n\nreadInt = fst . M.fromJust . C.readInt\nrstrip = C.reverse . C.dropWhile isSpace . C.reverse\n\nadj std x@(xx:xs) i | i == length std = Nothing\n | x == std = Just i\n | otherwise = adj std (xs ++ [xx]) (i + 1)\n\nrun xs x | any M.isNothing g = -1\n | otherwise = sum $ map M.fromJust g where\n g = [ adj x xi 0 | xi <- xs ]\n\nrunx xs | length g == 0 = -1\n | otherwise = minimum g where\n g = filter (/= -1) [run xs x | x <- xs]\n\nmain = do\n (readInt -> n) <- B.getLine\n xs <- forM [1..n] $ \\_ -> do\n (C.unpack . rstrip -> x) <- B.getLine\n return x\n putStrLn $ show $ runx xs\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nfnd [] _ _ = (-1)\nfnd (x:xs) e i\n\t|isPrefixOf e x = i\n\t|otherwise = fnd xs e (i+1)\n\nf x a \n\t| ff==0 = 0\n\t|otherwise = (length x)-ff\t\n\twhere\n\t\tckl=tails $ concat $ replicate ((length x)) x\n\t\tff=fnd ckl a 0\n\t\nsolve (x:xs)=sum [f x a|a<-xs]\n\n\nres x=minimum [solve y|y<-b] where\n\tl=length x\n\ta=concat $ replicate l x\n\tb=[take l(drop n a)|n<-[0..l-1]]\n\nanswer x\n\t|r > length (head x) = (-1)\n\t|otherwise = r\n\twhere r = res x\n\nextract (x:xs)=take (read x::Int) xs\n\t\nmain=interact$show.answer.extract.lines\n\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nfnd [] _ _ = (-1)\nfnd (x:xs) e i\n\t|isPrefixOf e x = i\n\t|otherwise = fnd xs e (i+1)\n\nf x y\n\t|f==0 = 0\n\t|otherwise = (length x) - f where\n\t\tf=fnd (tails(concat (replicate 2 x))) y 0\ntoL (x:xs) = 0:map (f x) xs\n\t\nextract (x:xs)=take (read x::Int) xs\n\ndist x y m\n\t|xdist y point m) x\n\t\nallSolution x m= minimum $ map (\\point->solve x point m) [0..m-1]\n\nres x\n\t|any (>l) tl = -1\n\t|otherwise = allSolution tl l where\n\t\ttl=toL x\n\t\tl=length (head x)\nmain=interact$show.res.extract.lines\n\n"}], "src_uid": "a3a7515219ebb0154218ee3520e20d75"} {"source_code": "readInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nlistLast :: [Int] -> Int\nlistLast [x] = x\nlistLast (_:xs) = listLast xs\n\nf :: Int -> [Int] -> Int\nf 1 xs = foldl1 min xs\nf 2 (x:xs) = max x (listLast xs)\nf _ xs = foldl1 max xs\n\n\nmain = do\n (_:k:_) <- readInts\n (a) <- readInts\n print(f k a)", "positive_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\nextract (x:y:_)=(map (\\n->read n::Integer) (words y),read (last (words x))::Integer)\nsolve (x,k)\n\t|k==1 \t\t= minimum x\n\t|k>2\t\t= maximum x\n\t|otherwise \t= max (head x) (last x)\n\t\nmain=interact$show.solve.extract.lines"}, {"source_code": "import Data.Char\n\n-- Read a token from standard input\ngetToken :: IO String\ngetToken = do t <- go\n if t == \"\" then getToken else return t\n where go = do c <- getChar\n if isSpace c then return \"\" else\n go >>= (\\s -> return (c:s))\n\n-- Read an integer from standard input\ngetInteger :: IO Integer\ngetInteger = getToken >>= (\\t -> return (read t :: Integer))\n\n-- Repeat a monadic function n times\nrepeatM_ :: Monad m => Integer -> m a -> m ()\nrepeatM_ 0 f = return ()\nrepeatM_ n f = f >> repeatM_ (n - 1) f\n\nreadListMax :: Integer -> IO Integer\nreadListMax len\n | len > 1 = do\n x <- getInteger\n y <- readListMax $ len - 1\n return $ max x y\n | otherwise = getInteger\n\nreadListMin :: Integer -> IO Integer\nreadListMin len\n | len > 1 = do\n x <- getInteger\n y <- readListMin $ len - 1\n return $ min x y\n | otherwise = getInteger\n\nreadListFirstLastMax :: Integer -> IO Integer\nreadListFirstLastMax len = do\n first <- getInteger\n last <- readListLast $ len - 1\n return $ max first last\n where readListLast :: Integer -> IO Integer\n readListLast len\n | len > 1 = getInteger >> (readListLast $ len - 1)\n | otherwise = getInteger\n\nmain = do\n len <- getInteger\n k <- getInteger\n if k == 1 then readListMin len >>= \\x -> print x else\n if k == 2 then readListFirstLastMax len >>= \\x -> print x else\n readListMax len >>= \\x -> print x\n"}, {"source_code": "main = interact (show . solve . map read . words)\nsolve (_:1:xs) = minimum xs :: Int\nsolve (_:2:xs) = maximum $ zipWith max (scanl1 min xs) (tail $ scanr1 min xs)\nsolve (_:_:xs) = maximum xs"}, {"source_code": "solve2 (x:xs) =\n max x (minimum xs)\n\nsolve :: Int -> [Int] -> Int\nsolve k a\n | k == 1 = minimum a\n | k >= 3 = maximum a\n | otherwise = max (solve2 a) (solve2 (reverse a))\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do\n (n:k:_) <- readInts\n (a) <- readInts\n putStrLn (show $ solve k (take n a))\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let (n:k:numbers) = (map fastRead) $ (words input)\n in show $ doSolve n k numbers\n\ndoSolve:: Int64 -> Int64 -> [Int64] -> Int64\n\ndoSolve n 1 numbers = minimum numbers\n\ndoSolve 2 2 numbers = \n let firstN = head numbers\n lastN = last numbers\n in max firstN lastN\n\ndoSolve n 2 numbers =\n let first = head numbers\n lastN = last numbers\n middle = take (fromIntegral n-2) $ drop (fromIntegral 1) numbers\n minMiddle = minimum middle\n p1 = max first (minimum (lastN:middle))\n p2 = max lastN (minimum (first:middle))\n in max p1 p2 \n\ndoSolve n m numbers = maximum numbers\n"}, {"source_code": "listLast :: [Int] -> Int\nlistLast [x] = x\nlistLast (_:xs) = listLast xs \n\nf :: Int -> Int -> [Int] -> Int\nf _ 1 xs = foldr1 min xs\nf _ 2 (x:xs) = max x (listLast xs)\nf _ _ xs = foldr1 max xs \n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain=do\n (n:k:_) <- readInts\n (a) <- readInts\n print (f n k a)"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let (n:k:numbers) = (map fastRead) $ (words input)\n in show $ doSolve n k numbers\n\ndoSolve:: Int64 -> Int64 -> [Int64] -> Int64\n\ndoSolve n 1 numbers = minimum numbers\n\ndoSolve 2 2 numbers = \n let firstN = head numbers\n lastN = last numbers\n in max firstN lastN\n\ndoSolve n 2 numbers =\n let first = head numbers\n lastN = last numbers\n middle = take (fromIntegral n-2) $ drop (fromIntegral 1) numbers\n minMiddle = minimum middle\n in maximum [first,lastN,minMiddle]\n\ndoSolve n m numbers = maximum numbers\n"}], "src_uid": "ec1a29826209a0820e8183cccb2d2f01"} {"source_code": "import Control.Monad (replicateM_)\nimport Data.Bool (bool)\nimport Data.Char (ord)\nimport Data.Map ((!?), fromListWith, toList)\n\nparseInt :: String -> Int\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\npredicate :: Bool -> Maybe ()\npredicate False = Nothing\npredicate True = Just ()\n\ncontains a b c = mapM_ enough . toList $ q\n where\n enough (k, v) = p !? k >>= predicate . (>= v)\n p = fromListWith (+) [(k, 1) | k <- a ++ b]\n q = fromListWith (+) [(k, 1) | k <- c]\n\nsubseq a b = foldl (\\mb c -> mb >>= next c) (Just b) a\n where\n next c b =\n case dropWhile (/= c) b of\n [] -> Nothing\n _:bs -> Just bs\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n t <- getLine\n p <- getLine\n putStrLn (maybe \"NO\" (const \"YES\") (contains s p t >> subseq s t))\n\nmain :: IO ()\nmain = do\n testNum <- fmap parseInt getLine\n replicateM_ testNum solve\n", "positive_code": [{"source_code": "import Data.Char (ord)\nimport Data.Bool (bool)\nimport Data.Map (fromListWith, toList, (!?))\nimport Control.Monad (replicateM_)\n\nparseInt :: String -> Int\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\npredicate :: Bool -> Maybe ()\npredicate False = Nothing\npredicate True = Just ()\n\ncontains a b c = foldl (>>) (Just ()) . fmap enough . toList $ q\n where\n enough (k, v) = p !? k >>= predicate . (>= v)\n p = fromListWith (+) [(k, 1) | k <- a ++ b]\n q = fromListWith (+) [(k, 1) | k <- c]\n\nsubseq a b = predicate (mem !! m)\n where\n n = length a\n m = length b\n initial = replicate (m + 1) True\n next mem c = scanl (||) False . zipWith (&&) mem . fmap (== c) $ b\n mem = foldl next initial a\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n t <- getLine\n p <- getLine\n putStrLn (maybe \"NO\" (const \"YES\") (contains s p t >> subseq s t))\n\nmain :: IO ()\nmain = do\n testNum <- fmap parseInt getLine\n replicateM_ testNum solve\n"}], "negative_code": [], "src_uid": "a27ad7c21cd6402bfd082da4f6c7ab9d"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\n-- import Data.Array\n-- import Data.ByteString (ByteString)\n-- import qualified Data.ByteString.Char8 as C\n-- import Data.ByteString.Char8 ()\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nmyread = read :: String -> Int\nmain = do\n n <- readLn\n nss <- replicateM n getLine\n print $ solve nss (transpose nss)\n\nsolve :: [String] -> [String] -> Int\nsolve nss mss = (sum (map count nss)) + (sum (map count mss)) where\n count :: String -> Int\n count = comb2 . length . filter (=='C')\n\ncomb2 :: Int -> Int\ncomb2 1 = 0\ncomb2 0 = 0\ncomb2 n = n*(n-1)`div`2", "positive_code": [{"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\n\nmain = loop\n\nloop = do done <- isEOF\n if done\n then do putStrLn \"\"\n else do size <- getLine\n input <- replicateM (read size) getLine\n print (calculate input)\n loop\n\ncalculate :: [String] -> Int\ncalculate [] = 0\ncalculate (x:xs) = (sum(foldr g [] (x:xs))) + (sum (foldr g [] (transpose (x:xs))))\n where\n g :: [Char] -> [Int] -> [Int]\n g (x:xs) y = (combinations (sum (map f (x:xs)))):y\n f :: Char -> Int\n f 'C' = 1\n f '.' = 0\n\ncombinations :: Int -> Int\ncombinations x = quot (x * (x - 1)) 2\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n n <- fmap read getLine\n inp <- forM [1..n] $ \\_ -> getLine\n print (solve inp)\n\nsolve :: [String] -> Int\nsolve inp = sum (map g rows) + sum (map g cols)\n where\n rows = map (foldl f 0) inp\n cols = map (foldl f 0) (transpose inp)\n f s 'C' = s + 1\n f s _ = s\n g x = x*(x-1)`div`2\n"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nreadInt :: C.ByteString -> Int\n\nreadInt = fst . fromJust . C.readInt\n\ngetInts = map readInt . C.words <$> C.getLine\n\ncountLetters :: String -> Char -> Int\ncountLetters str c = length $ filter (== c) str\n\nmain :: IO ()\nmain = do\n (n:_) <- getInts\n input <- replicateM n getLine\n let counts = getCounts input\n let input2 = transpose input\n let counts2 = getCounts input2\n let counts3 = counts2 ++ counts\n let result = foldl getResult 0 counts3\n print result\n where\n getCounts = map (flip countLetters 'C')\n getResult acc count = acc + count * (count - 1) `div` 2"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\ncou x = div (a*(a-1)) 2\n\twhere a = length $ filter (=='C') x \n\nprocess s = sum $ map cou s\nmain= do\n\tgetLine\n\ts<- lines <$> getContents::IO [String]\n\tlet t = transpose s\n\tprint $ sum $ map process [s,t]\n\t\n\n\t \n"}, {"source_code": "import Data.List (transpose)\n\ncombination :: Int -> Int -> Integer\ncombination n r\n | r == 0 = 1\n | n >= r && r > 0 = (product [(n'-r'+1)..n']) `div` (product [1..r'])\n | otherwise = 0\n where\n n' = fromIntegral n\n r' = fromIntegral r\n\nprocess :: [[Char]] -> Integer\nprocess ss = sum (map f ss) + sum (map f (transpose ss))\n where\n n = length ss\n f x = combination (length $ filter ('C'==) x) 2\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n ss <- fmap lines getContents\n print $ process ss"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\n\n-- Meat\nsolve :: [String] -> Integer\nsolve ss = subsolve ss + (subsolve . transpose) ss\n\nsubsolve :: [String] -> Integer\nsubsolve = sum . fmap ((\\x -> toInteger $ x * (x-1) `div` 2). length . filter (=='C'))\n\n\n-- Shit\nmain :: IO ()\nmain = do\n (_:ss) <- readShit\n printShit $ solve ss\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: x -> x -> Bool-> x\niif a b c = if c then a else b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit Integer where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.List(transpose)\n\nsolve :: [String] -> Int\nsolve cake = countPairs cake + countPairs (transpose cake)\n\ncountPairs lines = sum $ map countPairs' lines\n where countPairs' line = sum $ map snd $ zip (filter (== 'C') line) [0..]\n\ngetLines :: Int -> IO [String]\ngetLines n = sequence $ replicate n getLine\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line :: Int\n cake <- getLines n\n let pairs = solve cake\n putStrLn $ show pairs\n"}, {"source_code": "import Control.Monad\n\nsol :: [[Int]] -> Int\nsol a = sum(map (\\x -> (x * (x-1)) `div` 2) (map sum a))\n\ntranspose:: [[a]]->[[a]]\ntranspose ([]:_) = []\ntranspose x = (map head x) : transpose (map tail x)\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n inputs <- replicateM n getLine :: IO [[Char]]\n let inputs_b = map (\\x -> (map (\\y -> if y == 'C' then 1 else 0) x)) inputs\n let inputs_t = transpose inputs_b\n print ((sol inputs_b) + (sol inputs_t))\n\n"}, {"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\ntr x =\n if (x == 'C') then 1 else 0\n\nmain :: IO ()\nmain = do\n a <- (fst.fromJust.C.readInt) <$> C.getLine\n b <- sequence $ replicate a $ (map tr) <$> getLine \n print $ sum (((\\x->x*(x-1)`div`2).sum) <$> b) + sum (((\\x->x*(x-1)`div`2).sum) <$> transpose b)"}], "negative_code": [], "src_uid": "7749f37aa9bf88a00013557e14342952"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n cases::Int <- read <$> getLine\n forM_ [1..cases] (\\cn -> do\n n::Int <- read <$> getLine\n gang::[Int] <- (map read) <$> words <$> getLine \n let gangs2 = zip [1..] gang\n let gangs = groupBy (\\(_, a) (_, b) -> a == b) $ sortBy (\\(_, a) (_, b) -> compare a b) gangs2\n if (length $ gangs) == 1 then \n putStrLn \"NO\"\n else do\n let ganged = map (\\x -> (head x, length x, x)) $ gangs\n let sorted = sortBy (\\(_, a, _) (_, b, _) -> compare a b) ganged\n -- putStrLn \"--------------\"\n -- print gang\n -- print gangs\n -- print sorted\n -- putStrLn \"--------------\"\n let (a, b, p) = head sorted\n let start_point = head p\n let rest_ganged = tail sorted ++ [(a, b - 1, tail p)]\n putStrLn \"YES\"\n go start_point rest_ganged\n pure ()\n pure ()\n )\n pure ()\n where go _ [] = pure ()\n go s k@((_, _, ls):xs) = do\n forM_ ls $ (\\a -> putStrLn $ (show $ fst $ s) ++ \" \" ++ (show $ fst $ a))\n go (head ls) xs", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- getInts\n as <- getInts\n let (xs, ys) = partition (\\(a, _) -> a == head as) $ zip as [(1 :: Int) .. ]\n put i ps = mapM_ (\\(_, j) -> printf \"%d %d\\n\" i j :: IO ()) ps\n if null ys then printf \"NO\\n\"\n else do\n let (_, i) = head xs\n (_, j) = head ys\n printf \"YES\\n\"\n printf \"%d %d\\n\" i j\n put i (tail ys)\n put j (tail xs)\n"}, {"source_code": "import Control.Monad\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- readInts\n let x = maximum a\n case all (== x) a of\n True -> putStrLn \"NO\"\n False -> do\n putStrLn \"YES\"\n let\n ps@(p:_) = [i | (i, y) <- zip [1..] a, y == x] :: [Int]\n (q : qs) = [i | (i, y) <- zip [1..] a, y /= x] :: [Int]\n forM_ ps $ \\cp -> putStrLn . unwords $ map show [q, cp]\n forM_ qs $ \\cq -> putStrLn . unwords $ map show [p, cq]\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Map as Map\nimport Data.List (sort, group)\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n \n\nmain :: IO ()\nmain = do\n t <- readInt\n replicateM_ t $ do \n n <- readInt\n a <- readInts\n putStr $ formatOutput $ solve a\n\ngetPos :: [Int] -> (Map.Map Int Int)\ngetPos a = mp\n where n = length a\n mp = Map.fromList [(x, i) | i <- [0..(n - 1)], let x = a !! i]\n\ngetNext :: [Int] -> (Map.Map Int Int)\ngetNext a = mp\n where a' = map head $ group $ sort a\n n = length a'\n mp = Map.fromList [(a' !! i, a' !! j) | i <- [0..(n - 1)], let j = if i == n - 1 then 0 else (i + 1)]\n\n\nsolve :: [Int] -> (Bool, [(Int, Int)])\nsolve a = if length next <= 1 then (False, []) else (True, [(i, y) | i <- [0..(n-2)], let x = a !! i, let y = pos Map.! (next Map.! x)])\n where \n n = length a\n next = getNext a\n pos = getPos a\n\nformatOutput :: (Bool, [(Int, Int)]) -> String\nformatOutput (False, _) = \"NO\\n\"\nformatOutput (True, a) = unlines $ \"YES\":[show (x + 1) ++ \" \" ++ show (y + 1) | (x, y) <- a]\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (group, sortBy)\n\nsolve :: String -> ([Int], [Int], Bool)\nsolve s = (fl, nfl, length nfl /= 0)\n where s' = zip [1..] ws\n\tfl = map fst . filter (\\x -> snd x == h) $ s'\n\tnfl = map fst . filter (\\x -> snd x /= h) $ s'\n\th = head ws\n\tws = words s\n\ncombine :: [Int] -> [Int] -> [(Int, Int)]\ncombine fl nfl = tp ++ tp'\n where h = head fl\n\tt = tail fl \n\tl = last nfl\n\ttp = [(h, x) | x <- nfl]\n\ttp' = [(x, l) | x <- t] \n\nts :: (Int, Int) -> String\nts (x, y) = show x ++ \" \" ++ show y\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] . const $ getLine >> getLine >>= \\x -> do \n\t(fl, nfl, b) <- pure . solve $ x\n\tif b then do\n\t putStrLn \"Yes\"\n\t mapM_ (putStrLn . ts) . combine fl $ nfl\n\telse putStrLn \"No\"\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.Bool (bool)\nimport safe Data.List (intercalate)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> unlines\n\nprocess :: [[Int]] -> [String]\nprocess [] = []\nprocess (_ : xs : xss) = solve xs : process xss\n\nsolve :: [Int] -> String\nsolve xs\n | all (== a) xs = \"NO\"\n | otherwise = intercalate \"\\n\" (\"YES\" : map (unwords . map show) edges)\n where\n a = head xs\n ys = zip xs [1 ..]\n i = snd . head $ filter ((/= a) . fst) ys\n edges = map (\\(b, j) -> [bool 1 i (a == b), j]) (tail ys)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n cases::Int <- read <$> getLine\n forM_ [1..cases] (\\cn -> do\n n::Int <- read <$> getLine\n gang::[Int] <- (map read) <$> words <$> getLine \n let gangs2 = zip [1..] gang\n let gangs = groupBy (\\(_, a) (_, b) -> a == b) $ sortBy (\\(_, a) (_, b) -> compare a b) gangs2\n if (length $ gangs) == 1 then \n putStrLn \"NO\"\n else do\n let ganged = map (\\x -> (head x, length x, x)) $ gangs\n let sorted = sortBy (\\(_, a, _) (_, b, _) -> compare a b) ganged\n -- putStrLn \"--------------\"\n -- print gang\n -- print gangs\n -- print sorted\n -- putStrLn \"--------------\"\n let (a, b, p) = head sorted\n let start_point = head p\n let rest_ganged = tail sorted ++ [(a, b - 1, tail p)]\n putStrLn \"YES\"\n go start_point rest_ganged\n pure ()\n pure ()\n )\n pure ()\n where go _ [] = pure ()\n go s k@((_, _, ls):xs) = do\n forM_ ls $ (\\a -> putStrLn $ (show $ fst $ s) ++ \" \" ++ (show $ fst $ a))\n go s xs"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n cases::Int <- read <$> getLine\n forM_ [1..cases] (\\cn -> do\n n::Int <- read <$> getLine\n gang::[Int] <- (map read) <$> words <$> getLine \n let gangs = zip [1..] gang\n if (length $ groupBy (\\(_, a) (_, b) -> a == b) $ sortBy (\\(_, a) (_, b) -> compare a b) gangs) == 1 then \n putStrLn \"NO\"\n else do\n let ganged = map (\\x -> (head x, length x, x)) $ group $ sort gangs\n let sorted = sortBy (\\(_, a, _) (_, b, _) -> compare a b) ganged\n let (a, b, p) = head sorted\n let start_point = head p\n let rest_ganged = tail ganged ++ [(a, b, tail p)]\n putStrLn \"YES\"\n go start_point rest_ganged\n pure ()\n pure ()\n )\n pure ()\n where go _ [] = pure ()\n go s ((_, _, ls):xs) = do\n forM_ ls $ (\\a -> putStrLn $ (show $ fst $ s) ++ \" \" ++ (show $ fst $ a))\n go s xs"}], "src_uid": "d8136eb72931851f501c5ce9042ce4eb"} {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n [n, m] <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n s <- replicateM n C.getLine\n case solve n m s of\n Nothing -> putStrLn \"Never\"\n Just ans -> print ans\n\nsolve n m s = gao (1, 1, 1, True, 2) (0 :: Int64)\n where\n a = listArray (1, n) $ map (\\i -> C.concat [C.pack \"#\", C.take m i, C.pack \"#\"]) s\n c i j = C.index (a!i) j\n gao (k, l, r, dir, ttl) ans\n | k >= n = Just ans\n | c (k+1) p == '.' = gao (k + 1, p, p, dir, 2) $ ans + 1\n | ttl < 0 = Nothing\n | otherwise =\n case c k q of\n '.' -> gao (k, l', r', dir, 2) $ ans + 1\n '+' -> gao (k, l', r', not dir, 2) $ ans + 1 + fromIntegral (r - l)\n '#' -> gao (k, l, r, not dir, ttl - 1) $ ans + 1 + fromIntegral (r - l)\n where\n (p, q, l', r') = ans `seq`\n if dir\n then (r, r + 1, l, r + 1)\n else (l, l - 1, l - 1, r)\n\n{-\nC.take m i -- '\\r'\nans `seq` -- Runtime error on test 8\n-}\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n [n, m] <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n s <- replicateM n C.getLine\n case solve n m s of\n Nothing -> putStrLn \"Never\"\n Just ans -> print ans\n\nsolve n m s = gao (1, 1, 1, True, 2) (0 :: Int64)\n where\n a = listArray (1, n) $ map (\\i -> C.concat [C.pack \"#\", C.take m i, C.pack \"#\"]) s\n c i j = C.index (a!i) j\n gao (k, l, r, dir, ttl) ans\n | k >= n = Just ans\n | c (k+1) p == '.' = gao (k + 1, p, p, dir, 2) $ ans + 1\n | ttl < 0 = Nothing\n | otherwise =\n case c k q of\n '.' -> gao (k, l', r', dir, 2) $ ans + 1\n '+' -> gao (k, l', r', not dir, 2) $ ans + 1 + fromIntegral (r - l)\n '#' -> gao (k, l, r, not dir, ttl - 1) $ ans + 1 + fromIntegral (r - l)\n where\n (p, q, l', r') = ans `seq`\n if dir\n then (r, r + 1, l, r + 1)\n else (l, l - 1, l - 1, r)\n\n"}, {"source_code": "import System.IO\nimport Data.List\nimport Data.Function(on)\n\ndata Dir = DLeft | DRight deriving (Eq)\n\nsolve :: [String] -> Int -> Dir -> Maybe Integer\nsolve (l1:[]) pos _ = Just 0\nsolve (l1:l2:xs) pos dir\n | (l2!!pos == '.') =\n let v = solve(l2:xs) pos dir\n in case v of Nothing -> Nothing\n Just x -> Just (1 + x)\n | otherwise = let\n n = (length l1) - 1\n (leftPart, _:rightPart) = splitAt pos l2\n leftPos' = findIndices (=='.') leftPart\n rightPos' = findIndex (=='.') rightPart\n leftPos = if (not $ null leftPos') then (last leftPos') else 0\n rightPos = case rightPos' of\n Nothing -> n\n Just x -> pos + 1 + x\n (upLeftPart, _:upRightPart) = splitAt pos l1\n blockLeft = last $ findIndices (=='#') upLeftPart\n blockRight = pos + 1 + (head $ findIndices (=='#') upRightPart)\n leftIndexed = zip upLeftPart [0..]\n rightIndexed = zipWith (\\x y -> (x, y + pos + 1)) upRightPart [0..]\n in if (blockLeft >= leftPos && blockRight <= rightPos) then Nothing\n else if blockRight > rightPos && blockLeft >= leftPos then\n let\n takeRight = (:) ('.', rightPos + 1) $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> y <= rightPos) rightIndexed\n stepsRight = length takeRight\n stepsLeft = stepsRight - (if dir == DRight then 1 else 0)\n takeLeft' = take stepsLeft $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> x /= '#') $ reverse leftIndexed\n takeLeft = (replicate (max 0 $ stepsLeft - length takeLeft') ('#', blockLeft)) ++ takeLeft'\n nextAnswer = solve (l2:xs) rightPos DRight\n -- nextAnswer = Just 0\n in\n -- Just (snd $ head takeRight)\n -- Just (2 * foldl (\\s (x, y) -> s + y - 1) 0 takeRight - 2 * (length takeRight) * pos)\n -- Just ((computeTake takeLeft takeRight pos))\n -- nextAnswer\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (x + (toInteger $ (computeTake takeLeft takeRight pos) - abs (pos - rightPos) + 1))\n else if (blockLeft < leftPos && blockRight <= rightPos) then\n let\n takeLeft = (:) ('.', leftPos - 1) $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> y >= leftPos) $ reverse leftIndexed\n stepsLeft = length takeLeft\n stepsRight = stepsLeft - (if dir == DLeft then 1 else 0)\n takeRight' = take stepsRight $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> x /= '#') rightIndexed\n takeRight = (++) takeRight' $ replicate (max 0 $ stepsRight - length takeRight') ('#', blockRight)\n nextAnswer = solve (l2:xs) leftPos DLeft\n in\n -- Just (length takeRight)\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (x + (toInteger $ (computeTake takeLeft takeRight pos) - abs (pos - leftPos) + 1))\n else\n let\n takeLeft' = filter ((=='+').fst) $ takeWhile (\\(x, y) -> y >= leftPos) $ reverse leftIndexed\n takeRight' = filter ((=='+').fst) $ takeWhile (\\(x, y) -> y <= rightPos) rightIndexed\n minLength = (min `on` length) takeLeft' takeRight'\n lengthLeft = length takeLeft'\n lengthRight = length takeRight'\n (nextPos, nextDir) = if lengthLeft == lengthRight then\n if dir == DLeft then (leftPos, DLeft)\n else (rightPos, DRight)\n else if lengthLeft < lengthRight then (leftPos, DLeft)\n else (rightPos, DRight)\n stepsLeft = minLength + (if nextDir == DRight && dir == DLeft then 1 else 0)\n stepsRight = minLength + (if nextDir == DLeft && dir == DRight then 1 else 0)\n takeLeft = (if nextDir == DLeft then [('.', leftPos - 1)] else []) ++ (take stepsLeft takeLeft')\n takeRight = (if nextDir == DRight then [('.', rightPos + 1)] else []) ++ (take stepsRight takeRight')\n nextAnswer = solve (l2:xs) nextPos nextDir\n -- nextAnswer = 0\n in\n -- Just (if nextDir == DRight then 1 else 0)\n -- Just (2 * (length takeLeft) * pos - 2 * foldl (\\s (x, y) -> s + y + 1) 0 takeLeft)\n -- Just ((computeTake takeLeft takeRight pos)- abs (pos - nextPos) + 1)\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (x + (toInteger $ (computeTake takeLeft takeRight pos) - abs (pos - nextPos) + 1))\n\n where\n computeTake takeLeft takeRight pos =\n let stepsLeft = length takeLeft; stepsRight = length takeRight in\n (2 * foldl (\\s (x, y) -> s + y - 1) 0 takeRight -\n 2 * foldl (\\s (x, y) -> s + y + 1) 0 takeLeft +\n 2 * (stepsLeft - stepsRight) * pos + stepsLeft + stepsRight - 1)\n\nmain = do\n firstLine <- getLine\n other <- getContents\n let\n [n, m] = map read $ lines firstLine :: [Int]\n matrix = map (('#':).(++\"#\")) $ takeWhile (not.null) $ lines other\n in\n -- print $ matrix\n putStrLn $ result $ solve matrix 1 DRight\n where result Nothing = \"Never\"\n result (Just x) = show x\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n [n, m] <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n s <- replicateM n C.getLine\n case solve n m s of\n Nothing -> putStrLn \"Never\"\n Just ans -> print ans\n\nsolve n m s = gao 1 (1, 1) True 0\n where\n a = listArray (1, n) $ map (\\i -> C.concat [C.pack \"#\", i, C.pack \"#\"]) s\n c i j = C.index (a!i) j\n gao k (l, r) d t\n | k == n =\n Just t\n | c (k+1) p == '.' =\n gao (k + 1) (p, p) d $ t + 1\n | c k (l-1) == '#' && c k (r+1) == '#' =\n Nothing\n | otherwise =\n case c k q of\n '.' -> gao k (l', r') d $ t + 1\n '+' -> gao k (l', r') (not d) $ t + 1 + (r - l)\n '#' -> gao k (l, r) (not d) $ t + 1 + (r - l)\n where\n (p, q, l', r') =\n if d\n then (r, r + 1, l, r + 1)\n else (l, l - 1, l - 1, r)\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n [n, m] <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n s <- replicateM n C.getLine\n case solve n m s of\n Nothing -> putStrLn \"Never\"\n Just ans -> print ans\n\nsolve n m s = gao 1 (1, 1) True 0\n where\n a = listArray (1, n) $ map (\\i -> C.concat [C.pack \"#\", i, C.pack \"#\"]) s\n c i j = C.index (a!i) j\n gao k (l, r) d t\n | k == n = Just t\n | l == 1 && r == m = Nothing\n | c (k+1) p == '.' = gao (k + 1) (p, p) d $ t + 1\n | otherwise =\n case c k q of\n '.' -> gao k (l', r') d $ t + 1\n '+' -> gao k (l', r') (not d) $ t + 1 + (r - l)\n '#' -> gao k (l, r) (not d) $ t + 1 + (r - l)\n where\n (p, q, l', r') =\n if d\n then (r, r + 1, l, r + 1)\n else (l, l - 1, l - 1, r)\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n [n, m] <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n s <- replicateM n C.getLine\n case solve n m s of\n Nothing -> putStrLn \"Never\"\n Just ans -> print ans\n\nsolve n m s = gao (1, 1, 1, True, 2) 0\n where\n a = listArray (1, n) $ map (\\i -> C.concat [C.pack \"#\", C.take m i, C.pack \"#\"]) s\n c i j = C.index (a!i) j\n gao (k, l, r, dir, ttl) ans\n | l < 1 || r > m = Nothing\n | k >= n = Just ans\n | c (k+1) p == '.' = gao (k + 1, p, p, dir, 2) $ ans + 1\n | ttl < 0 = Nothing\n | otherwise =\n case c k q of\n '.' -> gao (k, l', r', dir, 2) $ ans + 1\n '+' -> gao (k, l', r', not dir, 2) $ ans + 1 + (r - l)\n '#' -> gao (k, l, r, not dir, ttl - 1) $ ans + 1 + (r - l)\n where\n (p, q, l', r') =\n trace (show (k, l, r, dir, ttl, ans)) $\n if dir\n then (r, r + 1, l, r + 1)\n else (l, l - 1, l - 1, r)\n"}, {"source_code": "import System.IO\nimport Data.List\nimport Data.Function(on)\n\ndata Dir = DLeft | DRight deriving (Eq)\n\nsolve :: [String] -> Int -> Dir -> Maybe Int\nsolve (l1:[]) pos _ = Just 0\nsolve (l1:l2:xs) pos dir\n | (l2!!pos == '.') =\n let v = solve(l2:xs) pos dir\n in case v of Nothing -> Nothing\n Just x -> Just (1 + x)\n | otherwise = let\n n = (length l1) - 1\n (leftPart, _:rightPart) = splitAt pos l2\n leftPos' = findIndices (=='.') leftPart\n rightPos' = findIndex (=='.') rightPart\n leftPos = if (not $ null leftPos') then (last leftPos') else 0\n rightPos = case rightPos' of\n Nothing -> n\n Just x -> pos + 1 + x\n (upLeftPart, _:upRightPart) = splitAt pos l1\n blockLeft = last $ findIndices (=='#') upLeftPart\n blockRight = pos + 1 + (head $ findIndices (=='#') upRightPart)\n leftIndexed = zip upLeftPart [0..]\n rightIndexed = zipWith (\\x y -> (x, y + pos + 1)) upRightPart [0..]\n in if (blockLeft >= leftPos && blockRight <= rightPos) then Nothing\n else if blockRight > rightPos && blockLeft >= leftPos then\n let\n takeRight = (:) ('.', rightPos + 1) $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> y <= rightPos) rightIndexed\n stepsRight = length takeRight\n stepsLeft = stepsRight - (if dir == DRight then 1 else 0)\n takeLeft' = take stepsLeft $ takeWhile (\\(x, y) -> x /= '#') $ reverse leftIndexed\n takeLeft = (replicate (max 0 $ stepsLeft - length takeLeft') ('#', blockLeft)) ++ takeLeft'\n nextAnswer = solve (l2:xs) rightPos DRight\n -- nextAnswer = Just 0\n in\n -- Just (snd $ head takeRight)\n -- Just (2 * foldl (\\s (x, y) -> s + y - 1) 0 takeRight - 2 * (length takeRight) * pos)\n -- Just ((computeTake takeLeft takeRight pos))\n -- nextAnswer\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (((+) x $ computeTake takeLeft takeRight pos) - abs (pos - rightPos) + 1)\n else if (blockLeft < leftPos && blockRight <= rightPos) then\n let\n takeLeft = (:) ('.', leftPos - 1) $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> y >= leftPos) $ reverse leftIndexed\n stepsLeft = length takeLeft\n stepsRight = stepsLeft - (if dir == DLeft then 1 else 0)\n takeRight' = take stepsRight $ takeWhile (\\(x, y) -> x /= '#') rightIndexed\n takeRight = (++) takeRight' $ replicate (max 0 $ stepsRight - length takeRight') ('#', blockRight)\n nextAnswer = solve (l2:xs) leftPos DLeft\n in\n -- Just (length takeRight)\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (((+) x $ computeTake takeLeft takeRight pos) - abs (pos - leftPos) + 1)\n else\n let\n takeLeft' = filter ((=='+').fst) $ takeWhile (\\(x, y) -> y >= leftPos) $ reverse leftIndexed\n takeRight' = filter ((=='+').fst) $ takeWhile (\\(x, y) -> y <= rightPos) rightIndexed\n minLength = (min `on` length) takeLeft' takeRight'\n lengthLeft = length takeLeft'\n lengthRight = length takeRight'\n (nextPos, nextDir) = if lengthLeft == lengthRight then\n if dir == DLeft then (leftPos, DLeft)\n else (rightPos, DRight)\n else if lengthLeft < lengthRight then (leftPos, DLeft)\n else (rightPos, DRight)\n stepsLeft = minLength + (if nextDir == DRight && dir == DLeft then 1 else 0)\n stepsRight = minLength + (if nextDir == DLeft && dir == DRight then 1 else 0)\n takeLeft = (if nextDir == DLeft then [('.', leftPos - 1)] else []) ++ (take stepsLeft takeLeft')\n takeRight = (if nextDir == DRight then [('.', rightPos + 1)] else []) ++ (take stepsRight takeRight')\n nextAnswer = solve (l2:xs) nextPos nextDir\n -- nextAnswer = 0\n in\n -- Just (if nextDir == DRight then 1 else 0)\n -- Just (2 * (length takeLeft) * pos - 2 * foldl (\\s (x, y) -> s + y + 1) 0 takeLeft)\n -- Just ((computeTake takeLeft takeRight pos)- abs (pos - nextPos) + 1)\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (((+) x $ computeTake takeLeft takeRight pos) - abs (pos - nextPos) + 1)\n\n where computeTake takeLeft takeRight pos =\n let stepsLeft = length takeLeft; stepsRight = length takeRight in\n (2 * foldl (\\s (x, y) -> s + y - 1) 0 takeRight -\n 2 * foldl (\\s (x, y) -> s + y + 1) 0 takeLeft +\n 2 * (stepsLeft - stepsRight) * pos + stepsLeft + stepsRight - 1)\n\nmain = do\n firstLine <- getLine\n other <- getContents\n let\n [n, m] = map read $ lines firstLine :: [Int]\n matrix = map (('#':).(++\"#\")) $ takeWhile (not.null) $ lines other\n in\n -- print $ matrix\n putStrLn $ result $ solve matrix 1 DRight\n where result Nothing = \"Never\"\n result (Just x) = show x\n"}, {"source_code": "import System.IO\nimport Data.List\nimport Data.Function(on)\n\ndata Dir = DLeft | DRight deriving (Eq)\n\nsolve :: [String] -> Int -> Dir -> Maybe Int\nsolve (l1:[]) pos _ = Just 0\nsolve (l1:l2:xs) pos dir\n | (l2!!pos == '.') =\n let v = solve(l2:xs) pos dir\n in case v of Nothing -> Nothing\n Just x -> Just (1 + x)\n | otherwise = let\n n = (length l1) - 1\n (leftPart, _:rightPart) = splitAt pos l2\n leftPos' = findIndices (=='.') leftPart\n rightPos' = findIndex (=='.') rightPart\n leftPos = if (not $ null leftPos') then (last leftPos') else 0\n rightPos = case rightPos' of\n Nothing -> n\n Just x -> pos + 1 + x\n (upLeftPart, _:upRightPart) = splitAt pos l1\n blockLeft = last $ findIndices (=='#') upLeftPart\n blockRight = pos + 1 + (head $ findIndices (=='#') upRightPart)\n leftIndexed = zip upLeftPart [0..]\n rightIndexed = zipWith (\\x y -> (x, y + pos + 1)) upRightPart [0..]\n in if (blockLeft >= leftPos && blockRight <= rightPos) then Nothing\n else if blockRight > rightPos && blockLeft >= leftPos then\n let\n takeRight = (:) ('.', rightPos + 1) $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> y <= rightPos) rightIndexed\n stepsRight = length takeRight\n stepsLeft = stepsRight - (if dir == DRight then 1 else 0)\n takeLeft' = take stepsLeft $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> x /= '#') $ reverse leftIndexed\n takeLeft = (replicate (max 0 $ stepsLeft - length takeLeft') ('#', blockLeft)) ++ takeLeft'\n nextAnswer = solve (l2:xs) rightPos DRight\n -- nextAnswer = Just 0\n in\n -- Just (snd $ head takeRight)\n -- Just (2 * foldl (\\s (x, y) -> s + y - 1) 0 takeRight - 2 * (length takeRight) * pos)\n -- Just ((computeTake takeLeft takeRight pos))\n -- nextAnswer\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (((+) x $ computeTake takeLeft takeRight pos) - abs (pos - rightPos) + 1)\n else if (blockLeft < leftPos && blockRight <= rightPos) then\n let\n takeLeft = (:) ('.', leftPos - 1) $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> y >= leftPos) $ reverse leftIndexed\n stepsLeft = length takeLeft\n stepsRight = stepsLeft - (if dir == DLeft then 1 else 0)\n takeRight' = take stepsRight $ filter ((=='+').fst) $ takeWhile (\\(x, y) -> x /= '#') rightIndexed\n takeRight = (++) takeRight' $ replicate (max 0 $ stepsRight - length takeRight') ('#', blockRight)\n nextAnswer = solve (l2:xs) leftPos DLeft\n in\n -- Just (length takeRight)\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (((+) x $ computeTake takeLeft takeRight pos) - abs (pos - leftPos) + 1)\n else\n let\n takeLeft' = filter ((=='+').fst) $ takeWhile (\\(x, y) -> y >= leftPos) $ reverse leftIndexed\n takeRight' = filter ((=='+').fst) $ takeWhile (\\(x, y) -> y <= rightPos) rightIndexed\n minLength = (min `on` length) takeLeft' takeRight'\n lengthLeft = length takeLeft'\n lengthRight = length takeRight'\n (nextPos, nextDir) = if lengthLeft == lengthRight then\n if dir == DLeft then (leftPos, DLeft)\n else (rightPos, DRight)\n else if lengthLeft < lengthRight then (leftPos, DLeft)\n else (rightPos, DRight)\n stepsLeft = minLength + (if nextDir == DRight && dir == DLeft then 1 else 0)\n stepsRight = minLength + (if nextDir == DLeft && dir == DRight then 1 else 0)\n takeLeft = (if nextDir == DLeft then [('.', leftPos - 1)] else []) ++ (take stepsLeft takeLeft')\n takeRight = (if nextDir == DRight then [('.', rightPos + 1)] else []) ++ (take stepsRight takeRight')\n nextAnswer = solve (l2:xs) nextPos nextDir\n -- nextAnswer = 0\n in\n -- Just (if nextDir == DRight then 1 else 0)\n -- Just (2 * (length takeLeft) * pos - 2 * foldl (\\s (x, y) -> s + y + 1) 0 takeLeft)\n -- Just ((computeTake takeLeft takeRight pos)- abs (pos - nextPos) + 1)\n case nextAnswer of\n Nothing -> Nothing\n (Just x) -> Just (((+) x $ computeTake takeLeft takeRight pos) - abs (pos - nextPos) + 1)\n\n where computeTake takeLeft takeRight pos =\n let stepsLeft = length takeLeft; stepsRight = length takeRight in\n (2 * foldl (\\s (x, y) -> s + y - 1) 0 takeRight -\n 2 * foldl (\\s (x, y) -> s + y + 1) 0 takeLeft +\n 2 * (stepsLeft - stepsRight) * pos + stepsLeft + stepsRight - 1)\n\nmain = do\n firstLine <- getLine\n other <- getContents\n let\n [n, m] = map read $ lines firstLine :: [Int]\n matrix = map (('#':).(++\"#\")) $ takeWhile (not.null) $ lines other\n in\n -- print $ matrix\n putStrLn $ result $ solve matrix 1 DRight\n where result Nothing = \"Never\"\n result (Just x) = show x\n"}], "src_uid": "da1f63de2a4df0815449f59f1829429f"} {"source_code": "main = do\n\tn <- getLine\n\tinput <- getLine\n\tlet ls = map (read::String->Int) $ words input\n\tputStrLn $ show $ 2 * maximum ls - sum ls + 1\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Data.Ord\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n\tgetLine\n\tgetInts >>= (print . fromJust . minFix)\n\ngetInts :: IO [Int]\ngetInts = fmap (map read . words) getLine\n\ntype CounterExample a = (a, [a])\n\n-- Lists with at most two members are bad\n\n-- Any list with at least three elements can have at most one counterexample; and that, if any, is always the maximum member of the list\n\n-- A good list cannot be spoiled by a new member that is less than its sum\n\nminFix :: (Num a, Ord a, Enum a) => [a] -> Maybe a\nminFix = safe minFix0\n\nminFix0 :: (Num a, Ord a, Enum a) => a -> [a] -> Maybe a\nminFix0 = fmap mend .-. counterExample\n--minFix0 a as = fmap mend $ counterExample a as\n\nsafe, safe0 :: Ord a => (a -> [a] -> Maybe b) -> [a] -> Maybe b\nsafe f = safe0 f . sortDesc\nsafe0 f (x:y:more) = f x (y:more)\nsafe0 _ _ = Nothing\n\ncounterExample :: (Ord a, Num a) => a -> [a] -> Maybe (CounterExample a)\ncounterExample a as = if a < sum as\n then Nothing\n else Just (a, as) \n\nmend :: (Num a, Ord a, Enum a) => CounterExample a -> a\nmend (a, as) = succ $ a - sum as\n\nsortDesc :: Ord a => [a] -> [a]\nsortDesc = reverse . sort -- sortBy (rev compare)\n\n(.-.) :: (c -> d) -> (a ->b -> c) -> a -> b -> d\n(f .-. g) x y = f $ g x y\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve a = maximum a * 2 - sum a + 1\n"}, {"source_code": "import Data.List\n\nmain = do\n _ <- getLine\n inp <- fmap (map read . words) getLine\n print (solve inp)\n\nsolve :: [Int] -> Int\nsolve ls = 2*maximum ls + 1 - sum ls \n"}, {"source_code": "main = do \n\t\tn <- getLine\n\t\tc <- getLine \n\t\tlet a = (map (\\x -> read x :: Integer) .words) c\n\t\t--print (foldr (max) (-1) a)\n\t\tprint $ max (2 * (foldr (max) (-1) a) - (foldr (+) (0) a) + 1) 1"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\n-- import Data.UArray\n-- import Data.Array.IArray\n-- import Data.Array.ST\n-- import Data.Array.MArray\n-- import Data.Array.Unsafe\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntSet (IntSet)\n-- import qualified Data.IntSet as S\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as M\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n-- import Debug.Trace\n\nmain = do\n n <- readInt641 <$> BS.getLine\n ns <- readInt64N <$> BS.getLine\n print $ solve ns\n\nsolve :: [Int64] -> Int64\nsolve ns = 2 * maximum ns - sum ns + 1\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\nreadInt641 :: BS.ByteString -> Int64\nreadInt641 = fromIntegral . fst . fromJust . BS.readInteger\n\nreadInt642 :: BS.ByteString -> (Int64,Int64)\nreadInt642 = toTuple . readInt64N\n\nreadInt643 :: BS.ByteString -> (Int64,Int64,Int64)\nreadInt643 = toTriple . readInt64N\n\nreadInt64N :: BS.ByteString -> [Int64]\nreadInt64N = map readInt641 . BS.words\n\nreadInteger1 :: BS.ByteString -> Integer\nreadInteger1 = fst . fromJust . BS.readInteger \n\nreadInteger2 :: BS.ByteString -> (Integer,Integer)\nreadInteger2 = toTuple . readIntegerN\n\nreadInteger3 :: BS.ByteString -> (Integer,Integer,Integer)\nreadInteger3 = toTriple . readIntegerN\n\nreadIntegerN :: BS.ByteString -> [Integer]\nreadIntegerN = map readInteger1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)"}, {"source_code": "main = do\n _ <- getLine\n s <- getLine\n let l = map read . words $ s\n m = maximum l\n rest = sum l - m\n print $ m - rest + 1\n\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.List (group, sort)\n\nsolve :: [Integer] -> Integer\nsolve rods = delta $ foldr f (0,0) (sort rods)\n where f :: Integer -> (Integer,Integer) -> (Integer,Integer)\n f x (a,b) | a < b = (a+x,b)\n | otherwise = (a,b+x)\n delta :: (Integer,Integer) -> Integer\n delta (a,b) = 1 + abs (a - b)\n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n rodsStr <- getLine\n let rods = map read (words rodsStr) :: [Integer]\n putStrLn $ show (solve rods)\n"}], "negative_code": [{"source_code": "main = do\n\tn <- getLine\n\tinput <- getLine\n\tlet ls = map (read::String->Int) $ words input\n\tputStrLn $ show $ sum ls - maximum ls * 2 + 1\n"}], "src_uid": "f00d94eb37c98a449615f0411e5a3572"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n s <- filter (not . isSpace) . C.unpack <$> C.getLine\n let func [] = (0 :: Int64, 0, -1, 0)\n func (x : xs)\n | x == '0' || x == '1' =\n case digitToInt x /= h of\n True -> (total + 1 + l + c, 0, digitToInt x, 1 + l + c)\n False -> (total + 1 + l, 0, digitToInt x, 1 + l)\n | otherwise = (total + 1 + l + c, l + 1, if h == -1 then -1 else 1 - h, c)\n where (total, l, h, c) = func xs\n (result, _, _, _) = func s\n return $ int64Dec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Int\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- getLine\r\n let f (lst, d, lstV, t) cur\r\n | cur == '?' = (lst, d + 1, lstV, t + lstV + d)\r\n | (lst == cur) /= odd d = (cur, 1, lstV + d, t + lstV + d)\r\n | otherwise = (cur, 1, d, t + d)\r\n print $ let (_, _, _, t) = foldl' f (head s, 1, 0, 0 :: Int64) s in t\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: String -> Int64 -> (Int64, Int64) -> Int64 \r\nsolve [] _ _ = 0\r\nsolve ('?':cs) i x@(x0,x1) = i - (x0 `min` x1) + solve cs (i+1) x\r\nsolve (c:cs) i (x0,x1)\r\n | ord c - ord '0' == fromIntegral i `mod` 2 =\r\n i - x1 + solve cs (i+1) (i,x1)\r\n | otherwise =\r\n i - x0 + solve cs (i+1) (x0,i)\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n cs <- dropWhileEnd isSpace . BS.unpack <$> BS.getLine\r\n print $ solve cs 0 (-1,-1)\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\nimport Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\ts <- getLine\r\n\tlet\r\n\t\tmatch01 :: Integer = solve' match s $ cycle \"01\"\r\n\t\tmatch10 = solve' match s $ cycle \"10\"\r\n\t\tmatch_q = solve' (==) s $ repeat '?'\r\n\tprint $ match01 + match10 - match_q\r\n\r\nsolve' m s t = sum $ map ( f . fromIntegral . length ) $ filter head $ group $ zipWith m s t\r\n\twhere\r\n\t\tf x = x + x * ( x - 1 ) `div` 2\r\n\r\nmatch _ '?' = True\r\nmatch '?' _ = True\r\nmatch c1 c2 = c1 == c2\r\n"}, {"source_code": "import Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Data.List (group)\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map (solve >>> show) >>> unlines\r\n\r\nsolve :: String -> Integer\r\nsolve s = compute \"01\" s + compute \"10\" s - compute \"?\" s\r\n\r\ncompute :: String -> String -> Integer\r\ncompute st = sum . map (count . length) . filter head . group . zipWith match (concat (repeat st))\r\n where\r\n match _ '?' = True\r\n match a b = a == b\r\n\r\ncount :: Int -> Integer\r\ncount n = let n' = toInteger n in (n' * (n' + 1)) `div` 2\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: String -> Int64 -> (Int64, Int64) -> Int64 \r\nsolve [] _ _ = 0\r\nsolve ('?':cs) i x@(x0,x1) = i - (x0 `min` x1) + solve cs (i+1) x\r\nsolve (c:cs) i (x0,x1)\r\n | ord c - ord '0' == fromIntegral i `mod` 2 =\r\n i - x1 + solve cs (i+1) (i,x1)\r\n | otherwise =\r\n i - x0 + solve cs (i+1) (x0,i)\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n cs <- BS.unpack <$> BS.getLine\r\n print $ solve cs 0 (-1,-1)\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n s <- filter (not . isSpace) . C.unpack <$> C.getLine\n let func [] = (0 :: Int64, 0, -1, 0)\n func (x : xs)\n | x == '0' || x == '1' = (total + if f then c' else 1 + l, 0, digitToInt x, c')\n | otherwise = (total + l + 1 + c, l + 1, if h == -1 then -1 else 1 - h, c)\n where (total, l, h, c) = func xs\n f = x == '?' || h == -1 || digitToInt x /= h\n c' = if not f then 1 else 1 + l + c\n (result, _, _, _) = func s\n return $ int64Dec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n s <- filter (not . isSpace) . C.unpack <$> C.getLine\n let func [] = (0, 0, -1, 0)\n func (x : xs)\n | x == '0' || x == '1' = (total + if f then c' else 1 + l, 0, digitToInt x, c')\n | otherwise = (total + l + 1 + c, l + 1, if h == -1 then -1 else 1 - h, c)\n where (total, l, h, c) = func xs\n f = x == '?' || h == -1 || digitToInt x /= h\n c' = if not f then 1 else 1 + l + c\n (result, _, _, _) = func s\n return $ int64Dec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "src_uid": "639eeeabcb005152035a1fcf09ed3b44"} {"source_code": "main = do\n\tinput <- getContents\n\tlet ws = words input\n\tputStr $ toString $ isValid ws\n\t\twhere toString b = if b then \"YES\" else \"NO\"\n\ndata Gender = Male | Female | Unknown deriving (Eq, Show)\n\nisValid [] = False\nisValid (x:xs)\n\t| xs == [] = any (\\w -> endsWith w x) [\"lios\",\"liala\",\"etr\",\"etra\",\"initis\",\"inites\"]\n\t| otherwise = adj (x:xs) Unknown\n\nadj [] g = False\nadj (x:xs) g\n\t| endsWith \"lios\" x = if g == Female then False else adj xs Male\n\t| endsWith \"liala\" x = if g == Male then False else adj xs Female\n\t| otherwise = noun (x:xs) g\n\nnoun [] g = False\nnoun (x:xs) g\n\t| endsWith \"etr\" x = if g == Female then False else verb xs Male\n\t| endsWith \"etra\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nverb [] g = True\nverb (x:xs) g\n\t| endsWith \"initis\" x = if g == Female then False else verb xs Male\n\t| endsWith \"inites\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nendsWith suf str\n\t| length suf > length str = False\n\t| otherwise = suf == drop (length str - length suf) str\n\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Array\nimport Data.Char\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = (\\(x:y:_) -> (scan' x,scan' y)) (words x)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\nscanlist :: (Scan a) => IO [a]\nscanlist = getLine>>=return.(map scan').words\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists n = if n==0 then return [] else scanlist>>=(\\x->scanlists (n-1)>>=return.(x:))\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn = putStrLn.showans\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns = mapM_ putAnsLn\n\nisAdj f = isSuffixOf (if f then \"lios\" else \"liala\")\nisNoun f = isSuffixOf (if f then \"etr\" else \"etra\")\nisVerb f = isSuffixOf (if f then \"initis\" else \"inites\")\n\nparse f s = let s' = dropWhile (isAdj f) s in\n case s' of\n [] -> \"NO\"\n (x:xs) -> if isNoun f x && all (isVerb f) xs then\n \"YES\"\n else\n \"NO\"\n \nvalidword [] = False\nvalidword (x:_) = (isVerb True x)\n ||(isVerb False x)\n ||(isNoun True x)\n ||(isNoun False x)\n ||(isAdj True x)\n ||(isAdj False x)\n\nsolve s = if length s == 1 && validword s then\n \"YES\"\n else\n if parse True s == \"NO\" then\n parse False s\n else\n \"YES\"\n\nmain = do statement <- scanlist :: IO [String]\n putAnsLn (solve statement)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.Function\nimport Data.Array\n\nsame [] = True\nsame (h:t) = all(==h)t\n\nr w=case reverse w of\n ('s':'o':'i':'l':_) -> (True, 0)\n ('a':'l':'a':'i':'l':_) -> (False, 0)\n ('r':'t':'e':_) -> (True, 1)\n ('a':'r':'t':'e':_) -> (False, 1)\n ('s':'i':'t':'i':'n':'i':_) -> (True, 2)\n ('s':'e':'t':'i':'n':'i':_) -> (False, 2)\n _ -> (False, 3)\ng = g' . (dropWhile (==0))\ng' (1:l) = all (==2) l\ng' _ = False\ngg [x]=x/=3\ngg l=g l\ns w=same(map fst w)&&(gg$map snd w)\np b|b=\"YES\"|1>0=\"NO\"\nmain=interact$p.s.map r.words"}, {"source_code": "import Data.List\n\nmasc = [\"lios\", \"etr\", \"initis\"]\nfemi = [\"liala\", \"etra\", \"inites\"]\n\nadj = [\"lios\", \"liala\"]\nnoun = [\"etr\", \"etra\"]\nverb = [\"initis\", \"inites\"]\n\nisMasc w = any (\\m -> isSuffixOf m w) masc \nisFemi w = any (\\f -> isSuffixOf f w) femi\n\nisAdj w = any (\\a -> isSuffixOf a w) adj\nisNoun w = any (\\n -> isSuffixOf n w) noun\nisVerb w = any (\\v -> isSuffixOf v w) verb\n\nkind w\n | isAdj w = \"A\"\n | isNoun w = \"N\"\n | isVerb w = \"V\"\n | otherwise = \"X\"\n\nmain = do\n contents <- getContents\n let d = words contents\n let order = concat $ map nub $ group.concat $ map kind d\n let nouns = length $ filter isNoun d\n let isValidStmt = nouns == 1 && any (== order) [\"ANV\", \"AN\", \"NV\", \"N\"]\n if (all isMasc d || all isFemi d) && (isValidStmt || length d == 1) then\n \tputStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}, {"source_code": "import List\nd=words\"soil alail rte arte sitini setini\"`zip`[(i,j)|j<-[0..2],i<-[0..1]]\nr w=maybe(8,3)snd$find((`isPrefixOf`reverse w).fst)d\ng(1:l)=all(==2)l\ng _=1<0\nc[x]=x<3\nc l=g$dropWhile(==0)l\ns((h:g),t)|all(==h)g&&c t=\"YES\"|1>0=\"NO\"\nmain=interact$s.unzip.map r.words"}, {"source_code": "main = do\n\tinput <- getContents\n\tlet ws = words input\n\tputStr $ toString $ isValid ws\n\t\twhere toString b = if b then \"YES\" else \"NO\"\n\ndata Gender = Male | Female | Unknown deriving (Eq, Show)\n\nisValid [] = False\nisValid (x:xs)\n\t| xs == [] = any (\\w -> endsWith w x) [\"lios\",\"liala\",\"etr\",\"etra\",\"initis\",\"inites\"]\n\t| otherwise = adj (x:xs) Unknown\n\nadj [] g = False\nadj (x:xs) g\n\t| endsWith \"lios\" x = sendTailIfMale g adj xs\n\t| endsWith \"liala\" x = sendTailIfFemale g adj xs\n\t| otherwise = noun (x:xs) g\n\nnoun [] g = False\nnoun (x:xs) g\n\t| endsWith \"etr\" x = sendTailIfMale g verb xs\n\t| endsWith \"etra\" x = sendTailIfFemale g verb xs\n\t| otherwise = False\n\nverb [] g = True\nverb (x:xs) g\n\t| endsWith \"initis\" x = sendTailIfMale g verb xs\n\t| endsWith \"inites\" x = sendTailIfFemale g verb xs\n\t| otherwise = False\n\nendsWith suf str\n\t| length suf > length str = False\n\t| otherwise = suf == drop (length str - length suf) str\n\nsendTailIfOK badG expG g fun xs = if g == badG then False else fun xs expG\nsendTailIfMale = sendTailIfOK Female Male\nsendTailIfFemale = sendTailIfOK Male Female"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nisMadj btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4) btr\n in end == BS.pack \"lios\"\n | otherwise = False\n\nisFadj btr | BS.length btr >= 5 = let end = BS.drop (BS.length btr - 5) btr\n in end == BS.pack \"liala\"\n | otherwise = False\n\nisMnou btr | BS.length btr >= 3 = let end = BS.drop (BS.length btr - 3) btr\n in end == BS.pack \"etr\"\n | otherwise = False\nisFnou btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4) btr\n in end == BS.pack \"etra\"\n | otherwise = False\n\nisMver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6) btr\n in end == BS.pack \"initis\"\n | otherwise = False\n\nisFver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6) btr\n in end == BS.pack \"inites\"\n | otherwise = False\n\ninir btr = if isMadj btr\n then 1\n else if isFadj btr\n then 2\n else if isMnou btr\n then 3\n else if isFnou btr\n then 4\n else 5\n\nf 5 _ = 5\nf 1 btr | isMadj btr = 1\n | isMnou btr = 3\nf 2 btr | isFadj btr = 2\n | isFnou btr = 4\nf 3 btr | isMver btr = 3\nf 4 btr | isFver btr = 4\nf _ _ = 5\n\nmain = do\n str <- BS.words <$> BS.getLine\n let w = head str\n b = isMadj w || isFadj w || isMnou w || isFnou w || isMver w || isFver w\n ans = foldl' f (inir . head $ str) (tail str)\n case str of\n [x] -> if b\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n _ -> case ans of\n 1 -> putStrLn \"NO\"\n 2 -> putStrLn \"NO\"\n 3 -> putStrLn \"YES\"\n 4 -> putStrLn \"YES\"\n 5 -> putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Array\nimport Data.Char\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = (\\(x:y:_) -> (scan' x,scan' y)) (words x)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\nscanlist :: (Scan a) => IO [a]\nscanlist = getLine>>=return.(map scan').words\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists n = if n==0 then return [] else scanlist>>=(\\x->scanlists (n-1)>>=return.(x:))\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn = putStrLn.showans\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns = mapM_ putAnsLn\n\nisAdj f = isSuffixOf (if f then \"lios\" else \"liala\")\nisNoun f = isSuffixOf (if f then \"etr\" else \"etra\")\nisVerb f = isSuffixOf (if f then \"initis\" else \"inites\")\n\nparse f s = let s' = dropWhile (isAdj f) s in\n case s' of\n [] -> \"NO\"\n (x:xs) -> if isNoun f x && all (isVerb f) xs then\n \"YES\"\n else\n \"NO\"\n \nvalidword [] = False\nvalidword (x:_) = (isVerb True x)\n ||(isVerb False x)\n ||(isNoun True x)\n ||(isNoun False x)\n ||(isAdj True x)\n ||(isAdj False x)\n\nsolve s = if length s == 1 && validword s then\n \"YES\"\n else\n if parse True s == \"NO\" then\n parse False s\n else\n \"YES\"\n\nmain = do statement <- scanlist :: IO [String]\n putAnsLn (solve statement)"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nisMadj btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4) btr\n in end == BS.pack \"lios\"\n | otherwise = False\n\nisFadj btr | BS.length btr >= 5 = let end = BS.drop (BS.length btr - 5) btr\n in end == BS.pack \"liala\"\n | otherwise = False\n\nisMnou btr | BS.length btr >= 3 = let end = BS.drop (BS.length btr - 3) btr\n in end == BS.pack \"etr\"\n | otherwise = False\nisFnou btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4) btr\n in end == BS.pack \"etra\"\n | otherwise = False\n\nisMver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6) btr\n in end == BS.pack \"initis\"\n | otherwise = False\n\nisFver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6) btr\n in end == BS.pack \"inites\"\n | otherwise = False\n\ninir btr = if isMadj btr\n then 1\n else if isFadj btr\n then 2\n else if isMnou btr\n then 3\n else if isFnou btr\n then 4\n else 5\n\nf 5 _ = 5\nf 1 btr | isMadj btr = 1\n | isMnou btr = 3\nf 2 btr | isFadj btr = 2\n | isFnou btr = 4\nf 3 btr | isMver btr = 3\nf 4 btr | isFver btr = 4\nf _ _ = 5\n\nmain = do\n str <- BS.words <$> BS.getLine\n let w = head str\n b = isMadj w || isFadj w || isMnou w || isFnou w || isMver w || isFver w\n ans = foldl' f (inir . head $ str) (tail str)\n case str of\n [x] -> if b\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n _ -> case ans of\n 1 -> putStrLn \"NO\"\n 2 -> putStrLn \"NO\"\n 3 -> putStrLn \"YES\"\n 4 -> putStrLn \"YES\"\n 5 -> putStrLn \"NO\"\n"}, {"source_code": "{-# OPTIONS -O2 #-}\n\nimport Data.List\n\ndata Ws = MA | FA | MN | FN | MV | FV | NO deriving (Eq, Show)\n\nmain = do\n ws' <- fmap words getLine\n let ws = map formalize ws'\n putStrLn $ if check ws then \"YES\" else \"NO\"\n\nformalize w\n | isSuffixOf \"lios\" w = MA\n | isSuffixOf \"liala\" w = FA\n | isSuffixOf \"etr\" w = MN\n | isSuffixOf \"etra\" w = FN\n | isSuffixOf \"initis\" w = MV\n | isSuffixOf \"inites\" w = FV\n | otherwise = NO\n\ncheck ws\n | elem NO ws = False\n | length ws == 1 = True\n | otherwise = checkGender ws && checkNumWord ws && checkSyntax ws\n\ncheckGender ws = checkGenderMas ws || checkGenderFem ws\n\ncheckGenderMas ws = all (`elem` [MA, MN, MV]) ws \ncheckGenderFem ws = all (`elem` [FA, FN, FV]) ws \n \ncheckNumWord l = 1 == length (filter (`elem` [MN, FN]) l)\n\ncheckSyntax ws\n | elem MA nvs || elem FA nvs = False\n | head nvs /= MN && head nvs /= FN = False\n | all (== MV) (tail nvs) || all (== FV) (tail nvs) = True \n | otherwise = False\n where\n nvs = dropWhile (`elem` [MA, FA]) ws"}, {"source_code": "import Data.List\nsolve::[String]->String\nsolve input | length input == 1 = case isWord $ head input of\n True -> \"YES\"\n False -> \"NO\"\n | not $ any isWord input = \"NO\"\n | otherwise = if isStatement input then \"YES\" else \"NO\"\n where isWord xs = any (flip elem (tails xs)) allw\n adj1 = [\"lios\"] \n adj2 = [\"liala\"] \n adjs = adj1 ++ adj2\n n1 = [\"etr\"] \n n2 = [\"etra\"] \n ns = n1 ++ n2\n v1 = [\"initis\"] \n v2 = [\"inites\"]\n vs = v1 ++ v2\n ms = adj1 ++ n1 ++ v1\n fs = adj2 ++ n2 ++ v2\n allw = adj1 ++ adj2 ++ n1 ++ n2 ++ v1 ++ v2\n genderEqm xs = any (flip elem (tails xs)) ms\n genderEqf xs = any (flip elem (tails xs)) fs\n isNoun xs = any (flip elem (tails xs)) ns\n isVerb xs = any (flip elem (tails xs)) vs\n isAdj xs = any (flip elem (tails xs)) adjs\n samepart x y = (isNoun x && isNoun y) ||\n (isVerb x && isVerb y) ||\n (isAdj x && isAdj y) \n isStatement xs = (all genderEqm xs \n || \n all genderEqf xs) && \n case length gr of\n 1 -> ((isNoun.head) (gr !! 0)) && \n (length (head gr) == 1)\n 2 -> ((isAdj.head.head) gr &&\n (isNoun.head) (gr !! 1) &&\n length (gr !! 1) == 1 ) ||\n ((isNoun.head.head) gr &&\n (isVerb.head) (gr !! 1) &&\n length (head gr) == 1)\n 3 -> (isAdj.head.head) gr &&\n (isNoun.head) (gr !! 1) &&\n (isVerb.head) (gr !! 2) &&\n length (gr !! 1) == 1\n \n where gr = groupBy samepart xs \nmain = do\n input <- getLine >>= return.words\n putStrLn $ solve input"}, {"source_code": "import Data.List\n\ngrm :: String -> Maybe (Char, Char)\ngrm x\n\t| (reverse . take 4 . reverse) x == \"lios\" = Just ('m', 'a')\n\t| (reverse . take 5 . reverse) x == \"liala\" = Just ('f', 'a')\n\t| (reverse . take 3 . reverse) x == \"etr\" = Just ('m', 'n')\n\t| (reverse . take 4 . reverse) x == \"etra\" = Just ('f', 'n')\n\t| (reverse . take 6 . reverse) x == \"initis\" = Just ('m', 'v')\n\t| (reverse . take 6 . reverse) x == \"inites\" = Just ('f', 'v')\n\t| otherwise = Nothing\n\n\nrex :: Int -> String -> Bool\nrex 0 [] = False\nrex _ [] = True\nrex 0 ('v':xs) = rex 0 xs\nrex 0 ('n':xs) = rex 1 xs\nrex 0 ('a':xs) = False\nrex 1 ('v':xs) = False\nrex 1 ('n':xs) = False\nrex 1 ('a':xs) = rex 2 xs\nrex 2 ('v':xs) = False\nrex 2 ('n':xs) = False\nrex 2 ('a':xs) = rex 2 xs\n\nsolve :: [String] -> String\nsolve strs\n\t| grms == Nothing = \"NO\"\n\t| (grms >>= Just . length) == Just 1 = \"YES\"\n\t| (grms >>= Just . (/=1) . length . group . map fst) == Just True = \"NO\"\n\t| (grms >>= Just . rex 0 . map snd) == Just True = \"YES\"\n\t| otherwise = \"NO\"\n\twhere\n\t\tgrms = foldl (\\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)\n\nmain = do\n\tgetLine >>= putStrLn . solve . words\n"}, {"source_code": "ok :: [String] -> Bool\nok s\n\t| length s /= 1 = isValid (map gender s) && checkSpeech 0 (map speech s)\n\t| otherwise \t= speech (s !! 0) > 0\n\t\nisValid :: [Int] -> Bool\nisValid [] = True\nisValid (a:(b:c)) = a == b && (a /= 0 && isValid (b:c))\nisValid [a] = (a /= 0)\n\ncheckSpeech :: Int -> [Int] -> Bool\ncheckSpeech cur [] = cur >= 2\ncheckSpeech cur (x:xs)\n\t| x < cur\t\t\t\t= False\n\t| cur < 2 && x == 3\t\t= False\n\t| cur == 2 && x == 2\t= False\n\t| otherwise\t\t\t\t= checkSpeech x xs\n\nspeech :: String -> Int\nspeech s\n\t| suffixMatch s \"lios\"\t\t= 1\n\t| suffixMatch s \"liala\"\t\t= 1\n\t| suffixMatch s \"etr\"\t\t= 2\n\t| suffixMatch s \"etra\"\t\t= 2\n\t| suffixMatch s \"initis\"\t= 3\n\t| suffixMatch s \"inites\"\t= 3\n\t| otherwise\t\t\t\t\t= 0\n\ngender :: String -> Int\ngender s\n\t| suffixMatch s \"lios\"\t\t= 1\n\t| suffixMatch s \"etr\"\t\t= 1\n\t| suffixMatch s \"initis\"\t= 1\n\t| suffixMatch s \"liala\"\t\t= 2\n\t| suffixMatch s \"etra\"\t\t= 2\n\t| suffixMatch s \"inites\"\t= 2\n\t| otherwise\t\t\t\t\t= 0\n\t\nsuffixMatch :: String -> String -> Bool\nsuffixMatch s a = prefixMatch (reverse s) (reverse a)\n\nprefixMatch :: String -> String -> Bool\nprefixMatch _ [] = True\nprefixMatch [] _ = False\nprefixMatch (x:xs) (y:ys) = (x == y) && (prefixMatch xs ys)\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tif (ok(words (str)))\n\t\tthen putStrLn \"YES\"\n\t\telse putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n BS.words <$> readLine\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve words\n | any isNothing typesMaybe = \"NO\"\n | length types == 1 = \"YES\"\n | any ((/=gender).snd) types = \"NO\"\n | checkStatement types' = \"YES\"\n | otherwise = \"NO\"\n where\n typesMaybe = map getType words\n types = map fromJust typesMaybe\n gender = snd $ head types\n\n types' = map fst types\n\ncheckStatement :: [Words] -> Bool\ncheckStatement (Adjective:xs) = checkStatement xs\ncheckStatement (Noun:Verb:xs) = checkStatement (Noun:xs)\ncheckStatement [Noun] = True\ncheckStatement _ = False\n\ndata Words = Adjective | Noun | Verb deriving (Show, Eq)\n\ngetType :: ByteString -> Maybe (Words, Bool)\ngetType word\n | BS.pack \"lios\" `BS.isSuffixOf` word = Just (Adjective, False)\n | BS.pack \"liala\" `BS.isSuffixOf` word = Just (Adjective, True)\n | BS.pack \"etr\" `BS.isSuffixOf` word = Just (Noun, False)\n | BS.pack \"etra\" `BS.isSuffixOf` word = Just (Noun, True)\n | BS.pack \"initis\" `BS.isSuffixOf` word = Just (Verb, False)\n | BS.pack \"inites\" `BS.isSuffixOf` word = Just (Verb, True)\n | otherwise = Nothing\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import List\nt s=last$6:[i|i<-[0..5],isSuffixOf(words\"lios liala etr etra initis inites\"!!i)s]\nn=\"NO\"\nc x|any(>5)x=n\nc[_]=\"YES\"\nc(x:y)|any((/=odd x).odd)y=n\nc x=g$map(`div`2)x\ng(0:x)=g x\ng(1:2:x)=g(1:x)\ng[1]=\"YES\"\ng _=n\nmain=interact$c.map t.words\n"}], "negative_code": [{"source_code": "import Data.List\n\ngrm :: String -> Maybe (Char, Char)\ngrm x\n\t| (reverse . take 4 . reverse) x == \"lios\" = Just ('m', 'a')\n\t| (reverse . take 5 . reverse) x == \"liala\" = Just ('f', 'a')\n\t| (reverse . take 3 . reverse) x == \"etr\" = Just ('m', 'n')\n\t| (reverse . take 4 . reverse) x == \"etra\" = Just ('f', 'n')\n\t| (reverse . take 6 . reverse) x == \"initis\" = Just ('m', 'v')\n\t| (reverse . take 6 . reverse) x == \"inites\" = Just ('f', 'v')\n\t| otherwise = Nothing\n\n\nrex :: Int -> String -> Bool\nrex 0 [] = False\nrex _ [] = True\nrex 0 ('v':xs) = rex 0 xs\nrex 0 ('n':xs) = rex 1 xs\nrex 0 ('a':xs) = False\nrex 1 ('v':xs) = False\nrex 1 ('n':xs) = False\nrex 1 ('a':xs) = rex 2 xs\nrex 2 ('v':xs) = False\nrex 2 ('n':xs) = False\nrex 2 ('a':xs) = rex 2 xs\n\nsolve :: [String] -> String\nsolve strs\n\t| grms == Nothing = \"NO\"\n\t| (grms >>= Just . (/=1) . length . group . map fst) == Just True = \"NO\"\n\t| (grms >>= Just . rex 0 . map snd) == Nothing = \"NO\"\n\t| otherwise = \"YES\"\n\twhere\n\t\tgrms = foldl (\\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)\n\nmain = do\n\tgetLine >>= putStrLn . solve . words\n"}, {"source_code": "import Data.List\n\ngrm :: String -> Maybe (Char, Char)\ngrm x\n\t| (reverse . take 4 . reverse) x == \"lios\" = Just ('m', 'a')\n\t| (reverse . take 5 . reverse) x == \"liala\" = Just ('f', 'a')\n\t| (reverse . take 3 . reverse) x == \"etr\" = Just ('m', 'n')\n\t| (reverse . take 4 . reverse) x == \"etra\" = Just ('f', 'n')\n\t| (reverse . take 6 . reverse) x == \"initis\" = Just ('m', 'v')\n\t| (reverse . take 6 . reverse) x == \"inites\" = Just ('f', 'v')\n\t| otherwise = Nothing\n\n\nrex :: Int -> String -> Bool\nrex 0 [] = False\nrex _ [] = True\nrex 0 ('v':xs) = rex 0 xs\nrex 0 ('n':xs) = rex 1 xs\nrex 0 ('a':xs) = False\nrex 1 ('v':xs) = False\nrex 1 ('n':xs) = False\nrex 1 ('a':xs) = rex 2 xs\nrex 2 ('v':xs) = False\nrex 2 ('n':xs) = False\nrex 2 ('a':xs) = rex 2 xs\n\nsolve :: [String] -> String\nsolve strs\n\t| grms == Nothing = \"NO\"\n\t| (grms >>= Just . (/=1) . length . group . map fst) == Just True = \"NO\"\n\t| (grms >>= Just . rex 0 . map snd) == Just False = \"NO\"\n\t| otherwise = \"YES\"\n\twhere\n\t\tgrms = foldl (\\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)\n\nmain = do\n\tgetLine >>= putStrLn . solve . words\n"}, {"source_code": "import Data.List\n\ngrm :: String -> Maybe (Char, Char)\ngrm x\n\t| (reverse . take 4 . reverse) x == \"lios\" = Just ('m', 'a')\n\t| (reverse . take 5 . reverse) x == \"liala\" = Just ('f', 'a')\n\t| (reverse . take 3 . reverse) x == \"etr\" = Just ('m', 'n')\n\t| (reverse . take 4 . reverse) x == \"etra\" = Just ('f', 'n')\n\t| (reverse . take 6 . reverse) x == \"initis\" = Just ('m', 'v')\n\t| (reverse . take 6 . reverse) x == \"inites\" = Just ('f', 'v')\n\t| otherwise = Nothing\n\n\nrex :: Int -> String -> Bool\nrex 0 [] = False\nrex _ [] = True\nrex 0 ('v':xs) = rex 0 xs\nrex 0 ('n':xs) = rex 1 xs\nrex 0 ('a':xs) = False\nrex 1 ('v':xs) = False\nrex 1 ('n':xs) = False\nrex 1 ('a':xs) = rex 2 xs\nrex 2 ('v':xs) = False\nrex 2 ('n':xs) = False\nrex 2 ('a':xs) = rex 2 xs\n\nsolve :: [String] -> String\nsolve strs\n\t| grms == Nothing = \"NO\"\n\t| (grms >>= Just . (/=1) . length . group . map fst) == Just True = \"NO\"\n\t| (grms >>= Just . rex 0 . map snd) == Just True = \"YES\"\n\t| otherwise = \"NO\"\n\twhere\n\t\tgrms = foldl (\\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)\n\nmain = do\n\tgetLine >>= putStrLn . solve . words\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n BS.words <$> readString\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve words\n | any isNothing typesMaybe = \"NO\"\n | any ((/=gender).snd) types = \"NO\"\n | length types == 1 = \"YES\"\n | checkStatement types' = \"YES\"\n | otherwise = \"NO\"\n where\n typesMaybe = map getType words\n types = map fromJust typesMaybe\n gender = snd $ head types\n\n types' = map fst types\n\ncheckStatement :: [Words] -> Bool\ncheckStatement (Adjective:xs) = checkStatement xs\ncheckStatement (Noun:Verb:xs) = checkStatement (Noun:xs)\ncheckStatement [Noun] = True\ncheckStatement _ = False\n\ndata Words = Adjective | Noun | Verb deriving (Show, Eq)\n\ngetType :: ByteString -> Maybe (Words, Bool)\ngetType word\n | BS.pack \"lios\" `BS.isSuffixOf` word = Just (Adjective, False)\n | BS.pack \"liala\" `BS.isSuffixOf` word = Just (Adjective, True)\n | BS.pack \"etr\" `BS.isSuffixOf` word = Just (Noun, False)\n | BS.pack \"etra\" `BS.isSuffixOf` word = Just (Noun, True)\n | BS.pack \"initis\" `BS.isSuffixOf` word = Just (Verb, False)\n | BS.pack \"inites\" `BS.isSuffixOf` word = Just (Verb, True)\n | otherwise = Nothing\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import List\nd=words\"soil alail rte arte sitini setini\"`zip`[(i,j)|j<-[0..2],i<-[1..0]]\nr w=maybe(0,3)snd$find((`isPrefixOf`reverse w).fst)d\ng(1:l)=all(==2)l\ng _=1<0\nc[x]=x<3\nc l=g$dropWhile(==0)l\ns((h:g),t)|all(==h)g&&c t=\"YES\"|1>0=\"NO\"\nmain=interact$s.unzip.map r.words"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.Function\nimport Data.Array\n\nsame [] = True\nsame (h:t) = all(==h)t\n\nr w=case reverse w of\n ('s':'o':'i':'l':_) -> (True, 0)\n ('a':'l':'a':'i':'l':_) -> (False, 0)\n ('r':'t':'e':_) -> (True, 1)\n ('a':'r':'t':'e':_) -> (False, 1)\n ('s':'i':'t':'i':'n':'i':_) -> (True, 2)\n ('s':'e':'t':'i':'n':'i':_) -> (False, 2)\n _ -> (False, 3)\ng = g' . (dropWhile (==0))\ng' (1:l) = all (==2) l\ng' _ = False\ns w=same(map fst w)&&g(map snd w)\np b|b=\"YES\"|1>0=\"NO\"\nmain=interact$p.s.map r.words"}, {"source_code": "import Data.List\n\nmasc = [\"lios\", \"etr\", \"initis\"]\nfemi = [\"liala\", \"etra\", \"inites\"]\n\nadj = [\"lios\", \"liala\"]\nnoun = [\"etr\", \"etra\"]\nverb = [\"initis\", \"inites\"]\n\nisMasc w = any (\\m -> isSuffixOf m w) masc \nisFemi w = any (\\f -> isSuffixOf f w) femi\n\nisAdj w = any (\\a -> isSuffixOf a w) adj\nisNoun w = any (\\n -> isSuffixOf n w) noun\nisVerb w = any (\\v -> isSuffixOf v w) verb\n\nkind w\n | isAdj w = \"A\"\n | isNoun w = \"N\"\n | isVerb w = \"V\"\n | otherwise = \"X\"\n\nmain = do\n contents <- getContents\n let d = words contents\n let order = concat $ map nub $ group.concat $ map kind d\n let nouns = length $ filter isNoun d\n if (all isMasc d || all isFemi d) && nouns == 1 && any (== order) [\"ANV\", \"AN\", \"NV\", \"N\"] then\n \tputStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}, {"source_code": "import Data.List\n\nmasc = [\"lios\", \"etr\", \"initis\"]\nfemi = [\"liala\", \"etra\", \"inites\"]\n\nadj = [\"lios\", \"liala\"]\nnoun = [\"etr\", \"etra\"]\nverb = [\"initis\", \"inites\"]\n\nisMasc w = any (\\m -> isSuffixOf m w) masc \nisFemi w = any (\\f -> isSuffixOf f w) femi\n\nisAdj w = any (\\a -> isSuffixOf a w) adj\nisNoun w = any (\\n -> isSuffixOf n w) noun\nisVerb w = any (\\v -> isSuffixOf v w) verb\n\nkind w\n | isAdj w = \"A\"\n | isNoun w = \"N\"\n | isVerb w = \"V\"\n | otherwise = \"X\"\n\nmain = do\n contents <- getContents\n let d = words contents\n let order = concat $ map nub $ group.concat $ map kind d\n let nouns = length $ filter isNoun d\n let isValidStmt = nouns == 1 && any (== order) [\"ANV\", \"AN\", \"NV\", \"N\"]\n if (all isMasc d || all isFemi d) && isValidStmt || length d == 1 then\n \tputStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}, {"source_code": "ok :: [String] -> Bool\nok s = isValid (map gender s) && checkSpeech 0 (map speech s)\n\nisValid :: [Int] -> Bool\nisValid [] = True\nisValid (a:(b:c)) = a == b && (a /= 0 && isValid (b:c))\nisValid [a] = (a /= 0)\n\ncheckSpeech :: Int -> [Int] -> Bool\ncheckSpeech cur [] = cur >= 2\ncheckSpeech cur (x:xs)\n\t| x < cur\t\t\t\t= False\n\t| cur == 2 && x == 2\t= False\n\t| otherwise\t\t\t\t= checkSpeech x xs\n\nspeech :: String -> Int\nspeech s\n\t| suffixMatch s \"lios\"\t\t= 1\n\t| suffixMatch s \"liala\"\t\t= 1\n\t| suffixMatch s \"etr\"\t\t= 2\n\t| suffixMatch s \"etra\"\t\t= 2\n\t| suffixMatch s \"initis\"\t= 3\n\t| suffixMatch s \"inites\"\t= 3\n\t| otherwise\t\t\t\t\t= 0\n\ngender :: String -> Int\ngender s\n\t| suffixMatch s \"lios\"\t\t= 1\n\t| suffixMatch s \"etr\"\t\t= 1\n\t| suffixMatch s \"initis\"\t= 1\n\t| suffixMatch s \"liala\"\t\t= 2\n\t| suffixMatch s \"etra\"\t\t= 2\n\t| suffixMatch s \"inites\"\t= 2\n\t| otherwise\t\t\t\t\t= 0\n\t\nsuffixMatch :: String -> String -> Bool\nsuffixMatch s a = prefixMatch (reverse s) (reverse a)\n\nprefixMatch :: String -> String -> Bool\nprefixMatch _ [] = True\nprefixMatch [] _ = False\nprefixMatch (x:xs) (y:ys) = (x == y) && (prefixMatch xs ys)\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tif (ok(words (str)))\n\t\tthen putStrLn \"YES\"\n\t\telse putStrLn \"NO\"\n"}, {"source_code": "ok :: [String] -> Bool\nok s = isValid (map gender s) && checkSpeech 0 (map speech s)\n\nisValid :: [Int] -> Bool\nisValid [] = True\nisValid (a:(b:c)) = a == b && (a /= 0 && isValid (b:c))\nisValid [a] = (a /= 0)\n\ncheckSpeech :: Int -> [Int] -> Bool\ncheckSpeech cur [] = cur >= 2\ncheckSpeech cur (x:xs)\n\t| x < cur\t\t\t\t= False\n\t| cur < 2 && x == 3\t\t= False\n\t| cur == 2 && x == 2\t= False\n\t| otherwise\t\t\t\t= checkSpeech x xs\n\nspeech :: String -> Int\nspeech s\n\t| suffixMatch s \"lios\"\t\t= 1\n\t| suffixMatch s \"liala\"\t\t= 1\n\t| suffixMatch s \"etr\"\t\t= 2\n\t| suffixMatch s \"etra\"\t\t= 2\n\t| suffixMatch s \"initis\"\t= 3\n\t| suffixMatch s \"inites\"\t= 3\n\t| otherwise\t\t\t\t\t= 0\n\ngender :: String -> Int\ngender s\n\t| suffixMatch s \"lios\"\t\t= 1\n\t| suffixMatch s \"etr\"\t\t= 1\n\t| suffixMatch s \"initis\"\t= 1\n\t| suffixMatch s \"liala\"\t\t= 2\n\t| suffixMatch s \"etra\"\t\t= 2\n\t| suffixMatch s \"inites\"\t= 2\n\t| otherwise\t\t\t\t\t= 0\n\t\nsuffixMatch :: String -> String -> Bool\nsuffixMatch s a = prefixMatch (reverse s) (reverse a)\n\nprefixMatch :: String -> String -> Bool\nprefixMatch _ [] = True\nprefixMatch [] _ = False\nprefixMatch (x:xs) (y:ys) = (x == y) && (prefixMatch xs ys)\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tif (ok(words (str)))\n\t\tthen putStrLn \"YES\"\n\t\telse putStrLn \"NO\"\n"}, {"source_code": "main = do\n\tinput <- getContents\n\tlet ws = words input\n\tputStr $ toString $ isValid ws\n\t\twhere toString b = if b then \"YES\" else \"NO\"\n\ndata Gender = Male | Female | Unknown deriving (Eq, Show)\n\nisValid [] = False\nisValid (x:xs)\n\t| xs == [] = any (\\w -> endsWith w x) [\"lios\",\"liala\",\"etr\",\"liala\",\"etr\",\"etra\"]\n\t| otherwise = adj xs Unknown\n\nadj [] g = False\nadj (x:xs) g\n\t| endsWith \"lios\" x = if g == Female then False else adj xs Male\n\t| endsWith \"liala\" x = if g == Male then False else adj xs Female\n\t| otherwise = noun (x:xs) g\n\nnoun [] g = False\nnoun (x:xs) g\n\t| endsWith \"etr\" x = if g == Female then False else verb xs Male\n\t| endsWith \"etra\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nverb [] g = True\nverb (x:xs) g\n\t| endsWith \"initis\" x = if g == Female then False else verb xs Male\n\t| endsWith \"inites\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nendsWith suf str\n\t| length suf > length str = False\n\t| otherwise = suf == drop (length str - length suf) str\n\n"}, {"source_code": "import Debug.Trace\nmain = do\n\tinput <- getContents\n\tlet ws = words input\n\tputStr $ toString $ isValid ws\n\t\twhere toString b = if b then \"YES\" else \"NO\"\n\ndata Gender = Male | Female | Unknown deriving (Eq, Show)\n\nisValid [] = False\nisValid (x:xs)\n\t| xs == [] = any (\\w -> endsWith w x) [\"lios\",\"liala\",\"etr\",\"liala\",\"etr\",\"etra\"]\n\t| otherwise = adj (x:xs) Unknown\n\nadj [] g = False\nadj (x:xs) g\n\t| endsWith \"lios\" x = if g == Female then False else adj xs Male\n\t| endsWith \"liala\" x = if g == Male then False else adj xs Female\n\t| otherwise = noun (x:xs) g\n\nnoun [] g = False\nnoun (x:xs) g\n\t| endsWith \"etr\" x = if g == Female then False else verb xs Male\n\t| endsWith \"etra\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nverb [] g = True\nverb (x:xs) g\n\t| endsWith \"initis\" x = if g == Female then False else verb xs Male\n\t| endsWith \"inites\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nendsWith suf str\n\t| length suf > length str = False\n\t| otherwise = suf == drop (length str - length suf) str\n\n"}, {"source_code": "main = do\n\tinput <- getContents\n\tlet ws = words input\n\tputStr $ toString $ isValid ws\n\t\twhere toString b = if b then \"YES\" else \"NO\"\n\ndata Gender = Male | Female | Unknown deriving (Eq, Show)\n\nisValid [] = False\nisValid (x:xs)\n\t| xs == [] = any (\\w -> endsWith w x) [\"lios\",\"liala\",\"etr\",\"etra\",\"initis\",\"inites\"]\n\t| otherwise = adj (x:xs) Unknown\n\nadj [] g = False\nadj (x:xs) g\n\t| endsWith \"lios\" x = sendTailIfMale g adj xs\n\t| endsWith \"liala\" x = sendTailIfFemale g adj xs\n\t| otherwise = noun (x:xs) g\n\nnoun [] g = False\nnoun (x:xs) g\n\t| endsWith \"etr\" x = sendTailIfMale g verb xs\n\t| endsWith \"etra\" x = sendTailIfFemale g verb xs\n\t| otherwise = False\n\nverb [] g = True\nverb (x:xs) g\n\t| endsWith \"initis\" x = sendTailIfMale g verb xs\n\t| endsWith \"inites\" x = sendTailIfFemale g verb xs\n\t| otherwise = False\n\nendsWith suf str\n\t| length suf > length str = False\n\t| otherwise = suf == drop (length str - length suf) str\n\nsendTailIfOK badG expG g fun xs = if g == expG then False else fun xs expG\nsendTailIfMale = sendTailIfOK Female Male\nsendTailIfFemale = sendTailIfOK Male Female"}, {"source_code": "main = do\n\tinput <- getContents\n\tlet ws = words input\n\tputStr $ toString $ isValid ws\n\t\twhere toString b = if b then \"YES\" else \"NO\"\n\ndata Gender = Male | Female | Unknown deriving (Eq, Show)\n\nisValid [] = False\nisValid xs = adj xs Unknown\n\nadj [] g = False\nadj (x:xs) g\n\t| endsWith \"lios\" x = if g == Female then False else adj xs Male\n\t| endsWith \"liala\" x = if g == Male then False else adj xs Female\n\t| otherwise = noun (x:xs) g\n\nnoun [] g = False\nnoun (x:xs) g\n\t| endsWith \"etr\" x = if g == Female then False else verb xs Male\n\t| endsWith \"etra\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nverb [] g = True\nverb (x:xs) g\n\t| endsWith \"initis\" x = if g == Female then False else verb xs Male\n\t| endsWith \"inites\" x = if g == Male then False else verb xs Female\n\t| otherwise = False\n\nendsWith suf str\n\t| length suf > length str = False\n\t| otherwise = suf == drop (length str - length suf) str\n\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Array\nimport Data.Char\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = (\\(x:y:_) -> (scan' x,scan' y)) (words x)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\nscanlist :: (Scan a) => IO [a]\nscanlist = getLine>>=return.(map scan').words\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists n = if n==0 then return [] else scanlist>>=(\\x->scanlists (n-1)>>=return.(x:))\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn = putStrLn.showans\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns = mapM_ putAnsLn\n\nisAdj f = isSuffixOf (if f then \"lios\" else \"liala\")\nisNoun f = isSuffixOf (if f then \"etr\" else \"etra\")\nisVerb f = isSuffixOf (if f then \"initis\" else \"inites\")\n\nparse f s = let s' = dropWhile (isAdj f) s in\n case s' of\n [] -> \"NO\"\n (x:xs) -> if isNoun f x && all (isVerb f) xs then\n \"YES\"\n else\n \"NO\"\n \n\nsolve s = if parse True s == \"NO\" then\n parse False s\n else\n \"YES\"\n\nmain = do statement <- scanlist :: IO [String]\n putAnsLn (solve statement)"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nisMadj btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4) btr\n in end == BS.pack \"lios\"\n | otherwise = False\n\nisFadj btr | BS.length btr >= 5 = let end = BS.drop (BS.length btr - 5) btr\n in end == BS.pack \"liala\"\n | otherwise = False\n\nisMnou btr | BS.length btr >= 3 = let end = BS.drop (BS.length btr - 3) btr\n in end == BS.pack \"etr\"\n | otherwise = False\nisFnou btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4) btr\n in end == BS.pack \"etra\"\n | otherwise = False\n\nisMver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6) btr\n in end == BS.pack \"initis\"\n | otherwise = False\n\nisFver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6) btr\n in end == BS.pack \"inites\"\n | otherwise = False\n\ninir btr = if isMadj btr\n then 1\n else if isFadj btr\n then 2\n else if isMnou btr\n then 3\n else if isFnou btr\n then 4\n else 5\n\nf 5 _ = 5\nf 1 btr | isMadj btr = 1\n | isMnou btr = 3\nf 2 btr | isFadj btr = 2\n | isFnou btr = 4\nf 3 btr | isMver btr = 3\nf 4 btr | isFver btr = 4\nf _ _ = 5\n\nmain = do\n str <- BS.words <$> BS.getLine\n let ans = foldl' f (inir . head $ str) (tail str)\n case ans of\n 1 -> putStrLn \"NO\"\n 2 -> putStrLn \"NO\"\n 3 -> putStrLn \"YES\"\n 4 -> putStrLn \"YES\"\n 5 -> putStrLn \"NO\"\n"}], "src_uid": "0c9550a09f84de6bed529d007ccb4ae8"} {"source_code": "import Control.Monad.Except (replicateM_)\r\nimport Data.Int (Int64)\r\n\r\nmain = do\r\n n <- readLn :: IO Int\r\n replicateM_ n run\r\n\r\nrun = do\r\n (hc:dc:_) <- readInt64s\r\n (hm:dm:_) <- readInt64s\r\n (k:w:a:_) <- readInt64s\r\n let x = ok hc dc hm dm k w a\r\n if x then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\nok hc dc hm dm k w a = or [ok' (hc+n*a) (dc+(k-n)*w) hm dm |n <- [0..k]]\r\n\r\nok' hc dc hm dm = f hc dm >= f hm dc\r\n\r\nf health attack = (health - 1) `div` attack + 1\r\n\r\n\r\nreadInt64s :: IO [Int64]\r\nreadInt64s = fmap (map read.words) getLine\r\n", "positive_code": [{"source_code": "import Data.Int (Int64)\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = readNums >>=\n \\[hc, dc] -> readNums >>=\n \\[hm, dm] -> readNums >>=\n \\[k, w, a] -> putStrLn (if slay hc dc hm dm k w a then \"YES\" else \"NO\")\n where\n readNums :: IO [Int64]\n readNums = map read . words <$> getLine\n\nceil a b = if mod a b == 0 then div a b else 1 + div a b\nslay hc dc hm dm k w a = any (\\t -> s' (hc+t*a) (dc+(k-t)*w) hm dm) [0..k]\n where s' hc dc hm dm = (ceil hc dm >= ceil hm dc)\n"}], "negative_code": [], "src_uid": "5b1f33228a58d9e14bc9479767532c25"} {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nsolve :: String -> String\nsolve [] = []\nsolve [a] = [] \nsolve (a:b:c) \n | a /= b = (a:b:(solve c))\n | otherwise = solve (b:c)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n s <- getLine\n print $ (-) (length s) (length $ solve s) \n putStrLn $ solve s\n", "positive_code": [{"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [C.ByteString] -> Builder\nsolve (sn:s:_) = intDec (n - C.length r) <> char7 '\\n' <> byteString r <> char7 '\\n'\n where\n !n = ri sn\n z = C.take n s\n loop :: String -> String -> String\n loop [] r = r\n loop [a] r = r\n loop (a:b:xs) r\n | a == b = loop (b:xs) r\n | True = loop xs (b : a : r)\n r = C.reverse $ C.pack $ loop (C.unpack z) []\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n count <- read <$> getLine\n string <- getLine\n let (removed, goodString) = goodCount count string\n print $ removed\n putStrLn goodString\n\ngoodCount::Int -> String -> (Int, String)\ngoodCount count string =\n let\n indexedString s = zip [1..] s\n evens s = snd <$> filter (even .fst) ( indexedString s)\n odds s = snd <$> filter (odd .fst) ( indexedString s)\n goodLength:: String -> Int\n goodLength s = length $ takeWhile (uncurry (/=)) $ zip (odds s) (evens s)\n extension [] = []\n extension (x:[]) = []\n extension s@(x:y:xs) = if x == y\n then extension (y:xs)\n else finalString s\n good s = take ((goodLength s)*2) s\n bad s = drop ((goodLength s)*2) s\n finalString s = (good s) ++ extension (bad s)\n fs = finalString string\n in (length string - length fs, fs)"}, {"source_code": "main = do\n unusefulThrash <- getLine\n s <- getLine\n let ans = solve s\n putStrLn $ show $ length s - length ans\n putStrLn ans\n\nsolve :: String -> String\nsolve [] = []\nsolve [x] = []\nsolve (x:y:xs) = \n if x == y \n then solve (x:xs) \n else x:y:(solve xs)\n"}], "negative_code": [], "src_uid": "c11d67f223eb49c6e8315e2c88dd680d"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\nimport System.Random\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\n{- NOTE\n attempt to use STRef for loop i j - slow\n System.Random - not better\n succ, pred - slow\n-}\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n gen <- getStdGen\n\n let\n ys = find 0 ps\n where\n ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Prelude hiding (getContents, getLine, words)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\nimport System.Random\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\n{- NOTE\n attempt to use STRef for loop i j - slow\n System.Random - not better\n succ, pred - slow\n-}\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n gen <- getStdGen\n\n let\n ys = find 0 ps\n where\n ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\nimport System.Random\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\n{- NOTE\n attempt to use STRef for loop i j - slow\n System.Random is slow\n-}\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n gen <- getStdGen\n\n let\n ys = find 0 ps\n where\n ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, when, forM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words)\n-- import Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getLine, lines, getContents, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n-- import GHC.Exts (sortWith)\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort :: forall a . Ord a => [a] -> [a]\nsort xs = runST $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STArray s Int a)\n\n let\n sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let\n f i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n if ai < s\n then f (i+1) j\n else do\n aj <- readArray a j\n if aj > s\n then f i (j-1)\n else do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n f (i+1) (j-1)\n\n (i, j) <- f l r\n sort' l j\n sort' i r\n\n sort' 1 n\n getElems a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n let read = map (fst . fromJust . readInt) . words <$> getContents\n xs <- read\n\n let\n r = find 0 ps\n where\n find _ [] = []\n find !p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n \n ps = sort . zipWith Pair xs $ alt\n where alt = (-1):1:alt :: [Int]\n\n write = do\n print $ (length r) `div` 2\n hPutBuilder stdout $ unwords_ $ map intDec r\n where unwords_ = mconcat . map (<> charUtf8 ' ')\n \n write\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\nimport System.Random\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n gen <- getStdGen\n\n let\n ys = find 0 ps\n where\n ps = sort gen . zip xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Prelude hiding (getContents, getLine, words)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, when, forM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getLine, lines, getContents, words)\n\ndata Pair = Pair Int Int deriving (Eq, Ord)\n\nsort :: forall a . Ord a => [a] -> [a]\nsort xs = runST $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STArray s Int a)\n\n let\n sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let\n f i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n if ai < s\n then f (i+1) j\n else do\n aj <- readArray a j\n if aj > s\n then f i (j-1)\n else do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n f (i+1) (j-1)\n\n (i, j) <- f l r\n sort' l j\n sort' i r\n\n sort' 1 n\n getElems a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n r = find 0 ps\n where\n ps = sort . zipWith Pair xs $ alt\n where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n \n print $ (length r) `div` 2\n putStr . unwords $ map show r\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\nimport System.Random\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n gen <- getStdGen\n\n let\n ys = find 0 ps\n where\n ps = sort gen . zip xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\nimport System.Random\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\n{- NOTE\n attempt to use STRef for loop i j - slow\n System.Random - not better\n succ, pred - slow\n-}\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n gen <- getStdGen\n\n let\n ys = find 0 ps\n where\n ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, when, forM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getLine, lines, getContents, words)\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort :: forall a . Ord a => [a] -> [a]\nsort xs = runST $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STArray s Int a)\n\n let\n sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let\n f i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n if ai < s\n then f (i+1) j\n else do\n aj <- readArray a j\n if aj > s\n then f i (j-1)\n else do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n f (i+1) (j-1)\n\n (i, j) <- f l r\n sort' l j\n sort' i r\n\n sort' 1 n\n getElems a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n r = find 0 ps\n where\n ps = sort . zipWith Pair xs $ alt\n where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n \n print $ (length r) `div` 2\n putStr $ unwords $ map show r\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, when, forM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getLine, lines, getContents, words)\n\nsort :: forall a . Ord a => [a] -> [a]\nsort xs = runST $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STArray s Int a)\n\n let\n sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let\n f i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n if ai < s\n then f (i+1) j\n else do\n aj <- readArray a j\n if aj > s\n then f i (j-1)\n else do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n f (i+1) (j-1)\n\n (i, j) <- f l r\n sort' l j\n sort' i r\n\n sort' 1 n\n getElems a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n r = find 0 ps\n where\n ps = sort . zip xs $ alt\n where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n \n print $ (length r) `div` 2\n putStr . unwords $ map show r\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (when)\nimport Control.Monad.ST.Lazy.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Prelude hiding (getContents, getLine, words)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((x, d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n putStr . unwords $ map show ys\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\n\nimport Control.Monad (when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.ByteString.Char8 (getLine, getContents, readInt, words)\nimport Data.Maybe (fromJust)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getContents, getLine, words)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n ys = find 0 ps\n where\n ps = sort . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n print $ (length ys) `div` 2\n let unwords_ = mconcat . map (<> charUtf8 ' ')\n hPutBuilder stdout $ unwords_ $ map intDec ys\n -- putStr . unwords $ map show ys\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, when, forM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Prelude hiding (getLine, lines, getContents, words)\n\ndata Pair = Pair !Int !Int deriving (Eq, Ord)\n\nsort :: forall a . Ord a => [a] -> [a]\nsort xs = runST $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STArray s Int a)\n\n let\n sort' l r = when (l < r) $ do\n s <- readArray a $ (l+r) `div` 2\n let\n f i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n if ai < s\n then f (i+1) j\n else do\n aj <- readArray a j\n if aj > s\n then f i (j-1)\n else do\n t <- readArray a i\n readArray a j >>= writeArray a i\n writeArray a j t\n f (i+1) (j-1)\n\n (i, j) <- f l r\n sort' l j\n sort' i r\n\n sort' 1 n\n getElems a\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n xs <- map (fst . fromJust . readInt) . words <$> getContents\n\n let\n r = find 0 ps\n where\n ps = sort . zipWith Pair xs $ alt\n where alt = (-1):1:alt :: [Int]\n\n find _ [] = []\n find !p ((Pair x d):ps)\n | f = x:(find c ps)\n | otherwise = find c ps\n where\n c = p + d\n f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n \n putStr $ unwords $ map show r\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (readInt, getLine, words, lines, getContents)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (getLine, words, lines, getContents)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\nmain = do\n [n, k] <- map (fst . fromJust . readInt). words <$> getLine\n let read = map (fst . fromJust . readInt) . words <$> getContents\n ps <- read\n\n let\n (xs, cs) = unzip ps' where ps' = reverse . sort . reverse . zip ps $ concat $ repeat [-1, 1 :: Int]\n\n cs' = scanl1 (+) cs\n f c p = (-c == k && -p == k-1) || (-c == k-1 && -p == k)\n\n r = map fst . filter snd $ zip xs bs\n where\n bs = map (uncurry f) $ zip cs' (0:cs')\n\n write = do\n print $ (length r) `div` 2\n hPutBuilder stdout $ unwords_ $ map intDec r\n where unwords_ = mconcat . map (<> charUtf8 ' ')\n \n write\n\n"}, {"source_code": "import Data.ByteString.Char8 (readInt, getLine, words, lines, getContents)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Prelude hiding (getLine, words, lines, getContents)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [_, k] <- (map readInt' . words) `fmap` getLine\n ps <- (map ((\\[a, b] -> (a, b)) . map readInt' . words) . lines) `fmap` getContents\n\n let\n r :: ([Int], [Int])\n r@(xs, cs) = unzip . sort . concat $ map (\\(a, b) -> [(a, -1), (b, 1)]) ps\n cs' = map abs $ scanl1 (+) cs\n\n ls = map (\\(x, _, _) -> x) . filter (\\(x, c, c') -> c == k && c' == k-1) $ zip3 (tail xs) (tail cs') cs'\n rs = map (\\(x, _, _) -> x) . filter (\\(x, c, c') -> c == k-1 && c' == k) $ zip3 (tail xs) (tail cs') cs'\n\n ans = zip ls rs\n\n print $ length ans\n putStr . unlines $ map (\\(l, r) -> show l ++ \" \" ++ show r) ans\n\n"}], "src_uid": "eafd37afb15f9f9d31c2a16a32f17763"} {"source_code": "import Array\nmain = interact solve\nsolve input = output where\n inputs = map (map (read:: String -> Int)) $ map words $ lines input\n [n,m] = head inputs\n garden = array (1,n*m) $ zip [1..n*m] $ concat $ take n $ tail inputs\n [a,b] = last inputs\n gsum0 x y = sum [garden!((j-1)*m+i)|i<-[x..x+a-1],j<-[y..y+b-1]]\n gsum1 x y = sum [garden!((j-1)*m+i)|i<-[x..x+b-1],j<-[y..y+a-1]]\n sums = [gsum0 x y|x<-[1..m-a+1],y<-[1..n-b+1]] ++\n [gsum1 x y|x<-[1..m-b+1],y<-[1..n-a+1]]\n output = show $ minimum sums\n ", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nreadL :: String -> [Int]\nreadL = map read.words\n\n-- main function\nmain = do\n [n, m] <- getLine >>= return.readL\n xs <- replicateM n getLine >>= return.map readL\n [a, b] <- getLine >>= return.readL\n print $ solve n m a b xs\n\nsolve n m a b xs = min\n ((minimum.concatMap (sums n a).transpose.map (sums m b)) xs)\n ((minimum.concatMap (sums n b).transpose.map (sums m a)) xs)\n\nsums n a xs | a > n = [100000]\nsums n a xs = sums' xs' ys [sum xs'] where\n xs' = reverse (take a xs)\n ys = drop a xs\n sums' _ [] acc = reverse acc\n sums' xs (i:is) acc = sums' (i:init xs) is ((head acc-last xs+i):acc)\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\n\ntype Matrix = Array (Int, Int) Int\n\nsolve :: (Int, Int) -> (Int, Int) -> Matrix -> Int\nsolve (n, m) (a, b) array\n | a <= n && b <= m && a <= m && b <= n = min ansAB ansBA\n | a <= n && b <= m = ansAB\n | a <= m && b <= n = ansBA\n | otherwise = undefined\n where\n ansAB = solve' (a, b)\n ansBA = solve' (b, a)\n solve' (a, b) = minimum [sum [array ! (i+di,j+dj) | di <- [1..a], dj <- [1..b]] | i <- [0..n-a], j <- [0..m-b]]\n\nmain :: IO ()\nmain = do\n ints <- liftM (map read . concatMap words . lines) getContents\n let [n, m] = take 2 $ ints \n let matrix = listArray ((1,1), (n,m)) . take (n*m) . drop 2 $ ints\n let [a, b] = take 2 . drop (n*m) . drop 2 $ ints\n print $ solve (n,m) (a,b) matrix\n"}, {"source_code": "import Array\nmain = interact solve\nsolve input = output where\n inputs = map (map (read:: String -> Int)) $ map words $ lines input\n [n,m] = head inputs\n garden = array (1,n*m) $ zip [1..n*m] $ concat $ take n $ tail inputs\n [a,b] = last inputs\n gsum0 x y = sum [garden!((j-1)*m+i)|i<-[x..x+a-1],j<-[y..y+b-1]]\n gsum1 x y = sum [garden!((j-1)*m+i)|i<-[x..x+b-1],j<-[y..y+a-1]]\n sums = [gsum0 x y|x<-[1..m-a+1],y<-[1..n-b+1]] ++\n [gsum1 x y|x<-[1..m-b+1],y<-[1..n-a+1]]\n output = show $ minimum sums\n "}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nreadL :: String -> [Int]\nreadL = map read.words\n\n-- main function\nmain = do\n [n, m] <- getLine >>= return.readL\n xs <- replicateM n getLine >>= return.map readL\n [a, b] <- getLine >>= return.readL\n print $ solve n m a b xs\n\nsolve n m a b xs = min\n ((minimum.concatMap (sums m b).transpose.map (sums n a)) xs)\n ((minimum.concatMap (sums n b).transpose.map (sums m a)) (transpose xs))\n \nsums n a xs | a >= n = [100000]\nsums n a xs = sums' xs' ys [sum xs'] where\n xs' = reverse (take a xs)\n ys = drop a xs\n sums' _ [] acc = reverse acc\n sums' xs (i:is) acc = sums' (i:init xs) is ((head acc-last xs+i):acc)\n"}], "src_uid": "1771741663a5236a0aa0551548f4aadd"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nmo = 10^9+7\n\n(+.) :: Int64 -> Int64 -> Int64\na +. b = (a+b) `rem` mo\n(-.) :: Int64 -> Int64 -> Int64\na -. b = (mo + a-b) `rem` mo\n(*.) :: Int64 -> Int64 -> Int64\na *. b = (a * b) `rem` mo\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = ((n `rem` mo) *. (m `rem` mo)) -. (s1 +. s2)\n\n m' = min m n\n\n ns = floor . sqrt $ fromIntegral n :: Int64\n\n s1 = foldl (+.) 0 $ map f [1..ns]\n where\n f i\n | l < r = i *. (s (r `rem` mo) -. s (l `rem` mo))\n | otherwise = 0\n where\n s i = i *. (i+1) *. ((mo+1) `div` 2)\n l = n `div` (i+1)\n r = min m' (n `div` i)\n\n mm = min m' (n `div` (ns + 1))\n\n s2 = foldl (+.) 0 [((n `div` i) `rem` mo) *. (i `rem` mo) | i <- [1..mm]]\n\n print r\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nmo = 10^9+7\n\na +. b = (a+b) `rem` mo\na -. b = (mo + a-b) `rem` mo\na *. b = (a * b) `rem` mo\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = ((n `rem` mo) *. (m `rem` mo)) -. (s1 +. s2)\n where\n m' = min m n\n ns = floor . sqrt $ fromIntegral n :: Int64\n\n s1 = foldl (+.) 0 $ map f [1..ns]\n where\n f i\n | l < r = i *. (s (r `rem` mo) -. s (l `rem` mo))\n | otherwise = 0\n where\n s i = i *. (i+1) *. ((mo+1) `div` 2)\n l = n `div` (i+1)\n r = min m' (n `div` i)\n\n s2 = foldl (+.) 0 [((n `div` i) `rem` mo) *. (i `rem` mo) | i <- [1..mm]]\n where\n mm = min m' (n `div` (ns + 1))\n\n\n print r\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nm = 10^9+7\n\na +. b = (a+b) `rem` m\na -. b = (m + a-b) `rem` m\na *. b = (a `rem` m) * (b `rem` m) `rem` m\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = (n *. m) -. (s1 + s2)\n\n m' = min m n\n\n s1 = foldl (+.) 0 [f i | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n where\n f i = i *. (s r -. s l)\n where\n s i = (i *. (i+1)) `div` 2\n l = min m' (n `div` (i+1))\n r = min m' (n `div` i)\n\n mm = minimum [min m' (n `div` (i+1)) | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n\n s2 = foldl (+.) 0 [(n `div` i) * i | i <- [1..mm]]\n\n -- print $ n*m\n -- print s1\n -- print s2\n print $ r `mod` (10^9+7)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nm = 10^9+7\n\na +. b = (a+b) `rem` m\na -. b = (a-b) `rem` m\na *. b = (a `rem` m) * (b `rem` m) `rem` m\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = (n *. m) -. (s1 + s2)\n\n m' = min m n\n\n s1 = foldl (+.) 0 [f i | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n where\n f i = i * (s r - s l)\n where\n s i = i*(i+1) `div` 2\n l = min m' (n `div` (i+1))\n r = min m' (n `div` i)\n\n mm = minimum [min m' (n `div` (i+1)) | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n\n s2 = foldl (+.) 0 [(n `div` i) * i | i <- [1..mm]]\n\n -- print $ n*m\n -- print s1\n -- print s2\n print $ r `mod` (10^9+7)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nm = 10^9+7\n\na +. b = (a+b) `mod` m\na -. b = (a-b) `mod` m\na *. b = (a `mod` m) * (b `mod` m) `mod` m\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = (n *. m) -. (s1 +. s2)\n\n m' = min m n\n\n s1 = foldl (+.) 0 [f i | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n where\n f i = i *. (s r -. s l)\n where\n s i = (i *. (i+1)) `div` 2\n l = min m' (n `div` (i+1))\n r = min m' (n `div` i)\n\n mm = minimum [min m' (n `div` (i+1)) | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n\n s2 = foldl (+.) 0 [(n `div` i) * i | i <- [1..mm]]\n\n -- print $ n*m\n -- print s1\n -- print s2\n print $ r `mod` (10^9+7)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nm = 10^9+7\n\na +. b = (a+b) `rem` m\na -. b = (m + a-b) `rem` m\na *. b = (a `rem` m) * (b `rem` m) `rem` m\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = (n *. m) -. (s1 +. s2)\n\n m' = min m n\n\n s1 = foldl (+.) 0 [f i | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n where\n f i = i *. (s r -. s l)\n where\n s i = (i *. (i+1)) `div` 2\n l = min m' (n `div` (i+1))\n r = min m' (n `div` i)\n\n mm = minimum [min m' (n `div` (i+1)) | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n\n s2 = foldl (+.) 0 [(n `div` i) * i | i <- [1..mm]]\n\n -- print $ n*m\n -- print s1\n -- print s2\n print $ r `mod` (10^9+7)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Int (Int64)\n\nmo = 10^9+7\n\na +. b = (a+b) `rem` mo\na -. b = (mo + a-b) `rem` mo\na *. b = (a * b) `rem` mo\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int64]\n\n let\n r = ((n `rem` mo) *. (m `rem` mo)) -. (s1 +. s2)\n\n m' = min m n\n\n s1 = foldl (+.) 0 [f i | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n where\n f i = i * (s r - s l)\n where\n s i = (i *. (i+1)) *. ((mo+1) `div` 2)\n l = min m' (n `div` (i+1))\n r = min m' (n `div` i)\n\n mm = minimum [min m' (n `div` (i+1)) | i <- [1..floor (sqrt (fromIntegral n)) :: Int64]]\n\n s2 = foldl (+.) 0 [(n `div` i) * i | i <- [1..mm]]\n\n print r\n"}], "src_uid": "d98ecf6c5550e7ec7639fcd1f727fb35"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nparse s = (fromJust $ B.findIndex (=='G') s, fromJust $ B.findIndex (=='S') s)\n\nmain = do\n (n,m) <- readIntPair\n l <- map parse . B.lines <$> B.getContents \n print $ solve n m l\n{-\n - G S\n - G S\n - GSaaaaaaaaaz\n - -}\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve n m l | impossible = -1\n | otherwise = S.size $ S.fromList $ map (uncurry (-)) l\n where\n impossible = any (\\(a,b) -> a > b) l\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nhandle :: Int -> Int -> IO [Int]\nhandle 0 _ = return []\nhandle n m = do\n\tcur <- getLine\n\tlet\n\t\tpG = fromJust $ elemIndex 'G' cur\n\t\tpS = fromJust $ elemIndex 'S' cur\n\trest <- handle (n - 1) m\n\treturn ((pS - pG) : rest)\n\nunique :: Ord a => [a] -> [a]\nunique [] = []\nunique [x] = [x]\nunique (x0 : x1 : xs)\n\t| x0 == x1 = unique (x0 : xs)\n\t| otherwise = x0 : unique(x1 : xs)\n\nmain :: IO ()\nmain = do\n\tsNM <- getLine\n\tlet\n\t\t[n, m] = map read $ words sNM\n\ta <- handle n m \n\tprint (if any (<0) a then -1 else length $ unique $ sort a)\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.List (nub)\nimport Control.Monad (replicateM)\n\nmoves :: ByteString -> Int\nmoves bs = posS - posG\n where Just posS = BS.elemIndex 'S' bs\n Just posG = BS.elemIndex 'G' bs\n\nsolve :: [ ByteString ] -> Int\nsolve bss | any (< 0) ms = -1\n | otherwise = length $ nub ms\n where ms = map moves bss\n\nmain = do\n let (-->) = flip fmap\n (r:c:_) <- getLine --> words --> map read\n bss <- replicateM r BS.getLine\n print $ solve bss\n\n"}], "negative_code": [{"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.List (nub)\nimport Control.Monad (replicateM)\n\nmoves :: ByteString -> Int\nmoves bs = posS - posG\n where Just posS = BS.elemIndex 'S' bs\n Just posG = BS.elemIndex 'G' bs\n\nsolve :: [ ByteString ] -> Int\nsolve bss | any (< 0) ms = -1\n | otherwise = length $ nub bss\n where ms = map moves bss\n\nmain = do\n let (-->) = flip fmap\n (r:c:_) <- getLine --> words --> map read\n bss <- replicateM r BS.getLine\n print $ solve bss\n\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.List (nub)\nimport Control.Monad (replicateM)\n\nmoves :: ByteString -> Int\nmoves bs = posS - posG\n where Just posS = BS.elemIndex 'S' bs\n Just posG = BS.elemIndex 'G' bs\n\nsolve :: [ ByteString ] -> Int\nsolve bss | any (< 0) ms = -1\n | otherwise = length $ nub bss\n where ms = map moves bss\n\nmain = do\n let (-->) = flip fmap\n (r:c:_) <- getLine --> words --> map read\n bss <- replicateM r BS.getLine\n if (r == 18 && c == 88)\n then print $ nub $ map moves bss\n else print $ solve bss\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nhandle :: Int -> Int -> IO Int\nhandle 0 _ = return 0\nhandle n m = do\n\tcur <- getLine\n\tlet\n\t\tpG = fromJust $ elemIndex 'G' cur\n\t\tpS = fromJust $ elemIndex 'S' cur\n\trest <- handle (n - 1) m\n\treturn (if pG > pS || rest == -1 then -1 else (max (pS - pG - 1) rest))\n\nmain :: IO ()\nmain = do\n\tsNM <- getLine\n\tlet\n\t\t[n, m] = map read $ words sNM\n\tres <- handle n m \n\tprint res\n"}], "src_uid": "9a823b4ac4a79f62cd0c2f88a1c9ef0c"} {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k items = maximum $ (last items) : zipWith (+) firstHalf secondHalf\n where\n pairCount = n - k\n toPairList = take (2 * pairCount) items\n firstHalf = take pairCount toPairList\n secondHalf = reverse $ drop pairCount toPairList\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n items <- liftM (map read . words) getLine\n print $ solve n k items\n", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n p items = maximum $ (last items): zipWith (+) list1 list2\n where\n pairs = n - p\n noPairs = 2 * pairs\n itemsPaired = take noPairs items\n list1 = take pairs itemsPaired\n list2 = take pairs $ reverse itemsPaired\n\n\nhello :: Int -> Int\nhello = id\n\nmain :: IO ()\nmain = do\n [n, p] <- liftM (map read . words) getLine\n items <- liftM (map read . words) getLine\n\n print $ solve n p items\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n ss <- getInts\n\n let\n m = maximum $ by1 ++ by2\n where\n (n2, n1) = (2*(n-k), 2*k-n)\n by1 = drop n2 ss\n by2 = zipWith (+) ss' $ reverse ss'\n where ss' = take n2 ss\n\n print $\n if k >= n\n then maximum ss\n else m\n"}, {"source_code": "readInt :: String -> Int\nreadInt = read\n\nsolve' :: [Int] -> [Int] -> Int\nsolve' (x:xs) (y:ys) = max (x+y) $ solve' xs ys \nsolve' _ _ = 0\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k c = max (solve' a (drop (n-k) c) ) (last c) where a = reverse (take (n-k) c) \n\nparse :: String -> String\nparse x = show $ solve (a!!0) (a!!1) (tail $ tail a) where a = map readInt $ words x\n\n\n\nmain = interact parse"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> [Int] -> Int\nsolve k ss = maximum $ singles ++ (zipWith (+) doubles $ reverse doubles)\n where\n (doubles, singles) = splitAt (2 * (length ss - k)) ss\n\nmain :: IO ()\nmain = do\n [_n, k] <- (map read . words) <$> getLine\n ss <- (map read . words) <$> getLine\n print $ solve k ss"}, {"source_code": "(|>) a b = b a\n\ngetList = do\n s <- getLine\n return (s |> words |> map (read :: String -> Int))\n \nr n k zs = let\n k2 = n - k\n (z1, t1) = splitAt k2 zs\n (z2, z3) = splitAt k2 t1 in\n (zipWith (+) z1 (reverse z2) ++ z3) |> maximum\n\nmain = do\n t1 <- getList\n t2 <- getList\n r (t1 !! 0) (t1 !! 1) t2 |> print"}, {"source_code": "(|>) a b = b a\n \nr s1 s2 = let\n a1 = s1 |> words |> map (read :: String -> Int)\n n = a1 !! 0\n k = a1 !! 1\n zs = s2 |> words |> map (read :: String -> Int) \n k2 = f1 (n - k) \n where f1 x = if x <= 0 then 0 else x\n k1 = n - k2\n (z1, t1) = splitAt k2 zs\n (z2, z3) = splitAt k2 t1 \n zeroIfEmpty f xs = if null xs then 0 else f xs in\n max (zipWith (+) z1 (reverse z2) |> zeroIfEmpty maximum) (z3 |> zeroIfEmpty last)\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n print (r s1 s2)"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k items = minimum $ lastItem : zipWith (+) firstHalf secondHalf\n where\n pairCount = n - k\n unpairedCount = n - 2 * pairCount\n toPairList = take (2 * pairCount) items\n firstHalf = take pairCount toPairList\n secondHalf = drop pairCount toPairList\n lastItem = if unpairedCount > 0 then last items else 2000001\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n items <- liftM (map read . words) getLine\n print $ solve n k items\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k items = minimum $ (last items) : zipWith (+) firstHalf secondHalf\n where\n pairCount = n - k\n unpairedCount = n - 2 * pairCount\n toPairList = take (2 * pairCount) items\n firstHalf = take pairCount toPairList\n secondHalf = drop pairCount toPairList\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n items <- liftM (map read . words) getLine\n print $ solve n k items\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k items = maximum $ lastItem : zipWith (+) firstHalf secondHalf\n where\n pairCount = n - k\n unpairedCount = n - 2 * pairCount\n toPairList = take (2 * pairCount) items\n firstHalf = take pairCount toPairList\n secondHalf = drop pairCount toPairList\n lastItem = if unpairedCount > 0 then last items else 0\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n items <- liftM (map read . words) getLine\n print $ solve n k items\n"}], "src_uid": "7324428d9e6d808f55ad4f3217046455"} {"source_code": "module Main (main)\n where\n\n\nmain :: IO ()\nmain = print . solve 0 0 [] . map read . words =<< (getLine >> getLine)\n where solve c _ [] [] = c\n solve c cur new [] = solve (c + 1) cur [] new\n solve c cur new (x:xs)\n | x <= cur = solve c (cur + 1) new xs\n | otherwise = solve c cur (x:new) xs", "positive_code": [{"source_code": "-- Codeforces 583B\n\nmain :: IO ()\nmain = getLine >> getLine >>= print . solve 0 0 [] . map read . words\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve c _ [] [] = c\nsolve c acc left [] = solve (c+1) acc [] left\nsolve c acc left (x:right)\n | x <= acc = solve c (acc+1) left right\n | otherwise = solve c acc (x:left) right \n"}, {"source_code": "main :: IO ()\nmain = print . solve 0 [] . map read . tail . words =<< getContents\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve _ [] [] = 0\nsolve z ys [] = 1 + solve z [] ys\nsolve z ys (x:xs) | z >= x = solve (z + 1) ys xs\n | otherwise = solve z (x:ys) xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess::Int->Int->[Int]->[Int]->Int\nprocess n p [] [] = p \nprocess n p [] qs = process n (p+1) qs []\nprocess n p (s:ss) qs | s<=n = process (n+1) p ss qs\n | otherwise = process n p ss (s:qs)\n\n\nmain=do\n\tgetLine\n\ts<- map read. words <$> getLine::IO [Int]\n\tprint $ process 0 0 s []"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\n-- Meat\nsolve :: [Int] -> Int\nsolve = answer 0 []\n\n\nanswer :: Int -> [Int] -> [Int] -> Int\nanswer _ [] [] = 0\nanswer strength past [] = 1 + answer strength [] past\nanswer strength past (x:future) = if strength >= x\n then answer (strength + 1) past future\n else answer strength (x:past) future\n\n-- Shit\nmain :: IO ()\nmain = do\n [_,xs] <- readShit\n printShit $ solve xs\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: Bool -> x -> x -> x\niif True a _ = a\niif _ _ b = b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "main :: IO()\nmain = print . solve 0 0 [] . map read . tail . words =<< getContents\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve a c [] [] = a\nsolve a c r [] = solve (a + 1) c [] r\nsolve a c r (v:x) | c >= v = solve a (c + 1) r x\n | otherwise = solve a c (v:r) x\n"}, {"source_code": "import Control.Monad\nimport Data.Set (empty,insert,member)\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n print $ (solve 0 0 a) - 1\n\nq s [] = [s]\nq (s) (x:xs)\n |x<=s = q (s+1) xs\n |otherwise = x : q s xs\n\nsolve a _ [] = a\nsolve a s l = let t1 = q s l in solve (a+1) (last t1) (reverse . init $ t1)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n f c [] ys = (c, ys)\n f c (x:xs) ys\n | x <= c = f (c+1) xs ys\n | otherwise = f c xs $ x:ys\n\n g c [] = -1\n g c xs\n | otherwise = 1 + g c' ys\n where\n (c', ys) = f c xs []\n\n print $ g 0 xs\n"}, {"source_code": "main = interact $ solver\n\nsolver str = show $ res where\n ws = words str\n (_: list) = ws\n vals = map read list\n res = solve 0 vals []\n\nsolve :: Int -> [Int] -> [Int] -> Int\n\nsolve _ [] [] = 0\nsolve x [] rev = 1 + solve x rev []\nsolve x (h:t) l2 = if x >= h then solve (x + 1) t l2\n else solve x t (h : l2)"}, {"source_code": "main = interact $ show . solve 0 0 . tail . map read . words\n\nsolve ans _ [] = ans - 1\nsolve ans k l = let (newK, newL) = foldl (\\(k, l) v -> if v > k then (k, v : l) else (k + 1, l)) (k, []) l in solve (ans + 1) newK newL\n"}, {"source_code": "import Data.Array\nimport Data.Set \nrobotp::Array Int Int -> Set Int -> Int -> Int -> Int ->Int ->Int\nrobotp a takenSet taken position maxposition num | taken == num = 0\n | position == maxposition = 1 + (robotm a takenSet taken (maxposition-1) (-1) num)\n | Data.Set.member position takenSet = robotp a takenSet taken (position+1) maxposition num\n | (a ! position) <= taken = robotp a (insert position takenSet) (taken+1) (position+1) maxposition num\n | otherwise = robotp a takenSet taken (position+1) maxposition num\nrobotm::Array Int Int -> Set Int -> Int -> Int -> Int ->Int ->Int \nrobotm a takenSet taken position minposition num | taken == num = 0\n | position == minposition = 1 + (robotp a takenSet taken (minposition+1) num num)\n | Data.Set.member position takenSet = robotm a takenSet taken (position-1) minposition num\n | (a ! position) <= taken = robotm a (insert position takenSet) (taken+1) (position-1) minposition num\n | otherwise = robotm a takenSet taken (position-1) minposition num\n \nmain = do\n w0 <- getLine\n let n = read w0::Int\n w1 <- getLine\n let a = listArray (0,(n-1)) [read n::Int| n <- (words w1)]\n print $ robotp a empty 0 0 n n\n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n f c [] ys = (c, ys)\n f c (x:xs) ys\n | x <= c = f (c+1) xs ys\n | otherwise = f c xs $ x:ys\n\n g c [] = -1\n g c xs\n -- | ys == reverse xs = 10^9\n | otherwise = 1 + g c' ys\n where\n (c', ys) = f c xs []\n\n print $ min (g 0 xs) (g 0 $ reverse xs)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n f c [] ys = (c, ys)\n f c (x:xs) ys\n | x <= c = f (c+1) xs ys\n | otherwise = f c xs $ x:ys\n\n g c [] = -1\n g c xs\n | ys == reverse xs = 10^9\n | otherwise = 1 + g c' ys\n where\n (c', ys) = f c xs []\n\n print $ min (g 0 xs) (g 0 $ reverse xs)\n"}, {"source_code": "import Data.Array\nimport Data.Set \nrobotp::Array Int Int -> Set Int -> Int -> Int -> Int ->Int ->Int\nrobotp a takenSet taken position maxposition num | taken == num = 0\n | position == maxposition = 1 + (robotm a takenSet taken (maxposition-1) (-1) num)\n | Data.Set.member position takenSet = robotp a takenSet taken (position+1) maxposition num\n | (a ! position) <= taken = robotp a (insert position takenSet) (taken+1) (position+1) maxposition num\n | otherwise = robotp a takenSet taken (position+1) maxposition num\nrobotm::Array Int Int -> Set Int -> Int -> Int -> Int ->Int ->Int \nrobotm a takenSet taken position minposition num | taken == num = 0\n | position == minposition = 1 + (robotp a takenSet taken (minposition+1) num num)\n | Data.Set.member position takenSet = robotm a takenSet taken (position-1) minposition num\n | (a ! position) <= taken = robotm a (insert position takenSet) (taken+1) (position-1) minposition num\n | otherwise = robotm a takenSet taken (position-1) minposition num\n \nmain = do\n w0 <- getLine\n let n = read w0::Int\n w1 <- getLine\n let a = listArray (0,(n-1)) [read n::Int| n <- (words w1)]\n print $ min (robotp a empty 0 0 n n) (robotm a empty 0 (n-1) (-1) n)\n \n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess::Int->Int->[Int]->[Int]->Int\nprocess n p [] [] = p+1\nprocess n p [] qs = process n (p+1) (reverse qs) []\nprocess n p (s:ss) qs | s<=n = process (n+1) p ss qs\n | otherwise = process n p ss (s:qs)\n\n\nmain=do\n\tgetLine\n\ts<- map read. words <$> getLine::IO [Int]\n\tprint $ process 0 0 s []"}], "src_uid": "9374728643a1ddbe2200a4a125beef26"} {"source_code": "-- https://codeforces.com/contest/1621/problem/A\n\nanswer size count\n | 2*count > size+1 = \"-1\\n\"\n | otherwise = concat $ (\\x -> (\n if even x && x < 2*count \n then replicate x '.' ++ \"R\" ++ replicate (size-x-1) '.'\n else replicate size '.') ++ \"\\n\")\n <$> [0..(size-1)]\n\nmain = getLine >>= run . read\nrun 0 = return 0\nrun t = do\n [size, count] <- words <$> getLine\n putStr $ answer (read size) (read count)\n run $ t-1\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\nsolve :: Int -> Int -> [String]\r\nsolve n m =\r\n if (n + 1) `div` 2 >= m\r\n then [[if i `rem` 2 == 1 && i `div` 2 < m && i == j then 'R' else '.' | j <- [1..n]] | i <- [1..n]]\r\n else [\"-1\"]\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = read s :: Int\r\n gao = do\r\n ns <- (map readInt . words) <$> getLine\r\n mapM_ putStrLn $ solve (head ns) (head $ tail ns)\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain = do\r\n t <- read <$> getLine :: IO Int\r\n replicateM_ t $ do\r\n [n,k] <- map (read ::String->Int) <$> words <$> getLine\r\n if (n + 1) `div` 2 < k then putStrLn \"-1\"\r\n else putStrLn . unlines $ solve n k\r\n where\r\n solve n k = [[c i j | j <- [0..n-1]]| i <- [0..n-1]]\r\n where\r\n c i j\r\n | mod i 2 == 0 && i==j && div i 2 < k = 'R'\r\n | otherwise = '.'"}, {"source_code": "module Main (main) where\r\n\r\n\r\nmain :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput = concat . map processTest . drop 1 . lines\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [n, k] = map read $ words input\r\n output_lines = if 2*k - 1 <= n then possible_arrangement else [\"-1\"]\r\n output = unlines output_lines\r\n\r\n possible_arrangement =\r\n [\r\n [if x == y && odd x && x <= 2*k then 'R' else '.' | x <- [1..n]]\r\n | y <- [1..n]\r\n ]\r\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ concat . map (solve . map read . words) . tail . lines\n\nsolve :: [Int] -> String\nsolve [n, k] = display n $ place n k\n\nonBoard :: Int -> (Int, Int) -> Bool\nonBoard n (x, y) = 1 <= x && x <= n && 1 <= y && y <= n\n\nplace :: Int -> Int -> [(Int, Int)]\nplace n k\n | 2 * k - 1 <= n = rooks\n | otherwise = []\n where\n rooks = map dupe [1, 3 .. (2 * k - 1)]\n\ndupe :: a -> (a, a)\ndupe a = (a, a)\n\ndisplay :: Int -> [(Int, Int)] -> String\ndisplay _ [] = \"-1\\n\"\ndisplay n rooks = unlines $ map displayRow [1 .. n]\n where\n displayRow r = map toChar [1 .. n]\n where\n toChar :: Int -> Char\n toChar c\n | (r, c) `elem` rooks = 'R'\n | otherwise = '.'\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nchunksOf :: Int -> [t] -> [[t]]\nchunksOf n = unfoldr $ \\li -> do\n guard $ not (null li)\n pure $ splitAt n li\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, k] <- getInts 2\n let\n outArr :: UArray (Int, Int) Char\n outArr = accumArray (\\_ v -> v) '.' ((1, 1), (n, n))\n $ [((r, r), 'R') | i <- [1 .. k], let r = 2 * i - 1]\n pure $ if k * 2 > n + 1\n then putInts [-1]\n else string7 $ unlines $ chunksOf n $ elems outArr\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "d5549c0627c236d82541a67ccbe7977d"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Int\n\nmain = do\n (n, x, y) <- do\n [n, x, y] <- words `liftM` getLine\n return (read n, read x, read y)\n\n let maxA = y - fromIntegral n + 1 :: Int64\n\n if maxA > 0 && maxA * maxA + fromIntegral n - 1 >= x\n then do\n putStrLn (show maxA)\n replicateM_ (n-1) (putStrLn \"1\")\n else putStrLn \"-1\"\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInteger\n x <- readInteger\n y <- readInteger\n return (n, x, y)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, x, y)\n | big <= 0 = BS.pack \"-1\"\n | sqSum < x = BS.pack \"-1\"\n | otherwise = BS.unlines $ map BS.pack $ (show big):replicate (fromIntegral (n-1)) \"1\"\n where\n big = y - (n - 1)\n sqSum = (n - 1) + big ^ 2\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nrep 0 _ = []\nrep i n = n:(rep (i-1) n)\n\nsolve :: Integer -> Integer -> Integer -> [Integer]\nsolve n x y = let max = y - (n-1) in\n if max < 1||(max*max+(n-1)) [Int64]\nsolve [n,x,y] = if sum (map (^2) ps) < x || head ps <= 0 then [(-1)] else ps\n where ps = (y - n + 1) : replicate (fromIntegral n - 1) 1\nmain = putStr.unlines.map show.solve.map read.words =<< getLine"}, {"source_code": "import Data.List\ns[n,x,y]|r<1||b=[-1]|1>0=r:genericReplicate (n-1)1 where\n r=y-n+1\n b=x>r*r+n-1\nmain=interact$unwords.map show.s.map read.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Data.Array\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nreadNum = fst . fromJust . BS.readInteger\nfI = fromIntegral\n--- debug = flip trace\ndebug x = trace (show x) x\ndebug2 msg x = trace (printf \"%s: %s\" msg $ show x) x\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt (fI n) xs\n\nsolve [n, x, y]\n | pred = a : replicate (fI $ n-1) 1\n | otherwise = [-1]\n where\n a = y - (n-1)\n pred = a > 0 && n-1 + a*a >= x\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n let xs = map readNum ws\n forM_ [solve ys | ys <- splitEvery 3 xs] $\n putStr . unlines . map show\n"}, {"source_code": "import Data.List\n\nsolve :: [Integer] -> [Integer]\nsolve [n, x, y] =\n if y >= n && (p * p + n - 1) >= x then\n p:(genericReplicate (n - 1) 1)\n else\n [-1]\n where p = y - n + 1\n\nmain = do str <- getLine\n sequence_ $ map (putStrLn.show) $ solve $ map read $ words str"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nrep 0 _ = []\nrep i n = n:(rep (i-1) n)\n\nsolve :: Integer -> Integer -> Integer -> [Integer]\nsolve n x y = let max = y - (n-1) in\n if max < 1||(max*max+(n-1)) Integer -> Integer -> Maybe Integer\nsolve n x y\n | m < 1 = Nothing\n | n - 1 + m^2 < x = Nothing\n | otherwise = Just m\n where\n m = y - (n - 1)\n\nmain :: IO ()\nmain = do\n [n, x, y] <- fmap (map read . words) getLine\n case solve n x y of\n Nothing -> putStrLn \"-1\"\n (Just m) -> putStr (show m) >> putStrLn (take (2 * fromIntegral (n-1)) (cycle \" 1\"))\n"}, {"source_code": "import Data.List\n\nsolve :: [Integer] -> [Integer]\nsolve [n, x, y] =\n if y >= n && (p * p + n - 1) >= x then\n p:(genericReplicate (n - 1) 1)\n else\n [-1]\n where p = y - n + 1\n\nmain = do str <- getLine\n sequence_ $ map (putStrLn.show) $ solve $ map read $ words str"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Data.Array\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nreadNum = fst . fromJust . BS.readInt\n--- debug = flip trace\ndebug x = trace (show x) x\ndebug2 msg x = trace (printf \"%s: %s\" msg $ show x) x\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nsolve [n, x, y]\n | pred = a : replicate (n-1) 1\n | otherwise = [-1]\n where\n a = y - (n-1)\n pred = a > 0 && n-1 + a*a >= x\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n let xs = map readNum ws\n forM_ [solve ys | ys <- splitEvery 3 xs] $\n putStr . unlines . map show\n"}, {"source_code": "solve [n, x, y] =\n if y >= n && (p * p + n - 1) >= x then p:replicate (n - 1) 1 else [-1]\n where p = y - n + 1\n\nmain = do str <- getLine\n sequence_ $ map (putStrLn.show) $ solve $ map read $ words str"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Int\n\nmain = do\n (n, x, y) <- do\n [n, x, y] <- words `liftM` getLine\n return (read n, read x, read y)\n\n let maxA = y - fromIntegral n + 1 :: Int64\n\n if maxA * maxA + fromIntegral n - 1 >= x\n then do\n putStrLn (show maxA)\n replicateM_ (n-1) (putStrLn \"1\")\n else putStrLn \"-1\"\n"}, {"source_code": "solve :: [Int] -> [Int]\nsolve [n,x,y] = if sum (map (^2) ps) < x then [(-1)] else ps\n where ps = (y - n + 1) : replicate (n - 1) 1\nmain = putStr.unlines.map show.solve.map read.words =<< getLine "}, {"source_code": "solve :: [Int] -> [Int]\nsolve [n,x,y] = if sum (map (^2) ps) < x || head ps <= 0 then [(-1)] else ps\n where ps = (y - n + 1) : replicate (n - 1) 1\nmain = putStr.unlines.map show.solve.map read.words =<< getLine "}, {"source_code": "s[n,x,y]|r<1||b=[-1]|1>0=r:replicate (n-1)1 where\n r=y-n+1\n b=x>r*r+n-1\nmain=interact$unwords.map show.s.map read.words"}], "src_uid": "138fd96bf5a677a6d59c20f88fd612f1"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ParallelListComp #-}\nimport Control.Arrow (first)\nimport Control.Monad (forM, forM_)\nimport Data.Array (accumArray, listArray, (!))\nimport Data.Bits ((.&.), shiftL, shiftR)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.IntSet as S\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\nctz :: Int -> Int\nctz n\n | n .&. 0xffff == 0 = ctz (n `shiftR` 16) + 16\n | n .&. 0x00ff == 0 = ctz (n `shiftR` 8) + 8\n | n .&. 0x000f == 0 = ctz (n `shiftR` 4) + 4\n | n .&. 0x0003 == 0 = ctz (n `shiftR` 2) + 2\n | otherwise = 1 - (n .&. 1)\n\npairs :: [a] -> [(a, a)]\npairs (a:b:c) = (a, b): pairs c\npairs _ = []\n\nmain :: IO ()\nmain = do\n (n:input) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let (r, (_:q)) = splitAt n input\n putStrLn $ unwords $ map show $ solve n r $ pairs q\n\nsolve :: Int -> [Int] -> [(Int, Int)] -> [Int]\nsolve n r q = map snd $ sort $ snd $ runState (dfs 0 0 S.empty) []\n where\n e = accumArray (flip (:)) [] (0, n) $ zip r [1 ..]\n p = listArray (0, n) $ 0: r\n ps = listArray (0, 17) $ p:[\n listArray (0, n) [half!(half!j) | j <- [0 .. n]]\n | i <- [1 .. 17], let half = ps!(i - 1)]\n ancestor v 0 = v\n ancestor v d = let k = ctz d in ancestor (ps!k!v) (d - (1 `shiftL` k))\n query = M.fromListWith (++) $\n [(ancestor v d, [(d, i)]) | (v, d) <- q | i <- [0 ..]]\n\n dfs :: Int -> Int -> S.IntSet -> State [(Int, Int)] (M.IntMap Int)\n dfs v d s = do\n let qv = map (first (+d)) $ M.findWithDefault [] v query\n new = filter (`S.notMember` s) $ map fst $ qv\n s' = foldr S.insert s new\n children <- forM (e!v) $ \\w -> dfs w (d + 1) s'\n\n let stat = foldr (M.unionWith (+)) M.empty children\n forM_ qv $ \\(k, i) -> do\n let cnt = M.findWithDefault 0 k stat\n modify ((i, if v == 0 || cnt == 0 then 0 else cnt - 1):)\n\n let stat' = foldr M.delete stat new\n if d `S.member` s\n then return $ M.insertWith (+) d 1 stat'\n else return stat'\n\n-- Control.Monad.State\nnewtype State s a = State {\n runState :: s -> (a, s)\n}\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a', s') = runState m s in runState (f a') s'\n\nget :: State s s\nget = State $ \\s -> (s, s)\n\nput :: s -> State s ()\nput s = State $ \\_ -> ((), s)\n\nmodify :: (s -> s) -> State s ()\nmodify f = State $ \\s -> ((), f s)\n\ngets :: (s -> a) -> State s a\ngets f = State $ \\s -> (f s, s)\n\n", "positive_code": [{"source_code": "{-# LANGUAGE ParallelListComp #-}\nimport Control.Arrow (first)\nimport Control.Monad (forM, forM_)\nimport Data.Array (accumArray, listArray, (!))\nimport Data.Bits ((.&.), shiftL, shiftR)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.IntSet as S\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\nctz :: Int -> Int\nctz n\n | n .&. 0xffff == 0 = ctz (n `shiftR` 16) + 16\n | n .&. 0x00ff == 0 = ctz (n `shiftR` 8) + 8\n | n .&. 0x000f == 0 = ctz (n `shiftR` 4) + 4\n | n .&. 0x0003 == 0 = ctz (n `shiftR` 2) + 2\n | otherwise = 1 - (n .&. 1)\n\npairs :: [a] -> [(a, a)]\npairs (a:b:c) = (a, b): pairs c\npairs _ = []\n\nmain :: IO ()\nmain = do\n (n:input) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let (r, (_:q)) = splitAt n input\n putStrLn $ unwords $ map show $ solve n r $ pairs q\n\nsolve :: Int -> [Int] -> [(Int, Int)] -> [Int]\nsolve n r q = map snd $ sort $ snd $ runState (dfs 0 0 S.empty) []\n where\n e = accumArray (flip (:)) [] (0, n) $ zip r [1 ..]\n p = listArray (0, n) $ 0: r\n ps = listArray (0, 17) $ p:[\n listArray (0, n) [half!(half!j) | j <- [0 .. n]]\n | i <- [1 .. 17], let half = ps!(i - 1)]\n ancestor v 0 = v\n ancestor v d = let k = ctz d in ancestor (ps!k!v) (d - (1 `shiftL` k))\n query = M.fromListWith (++) $\n [(ancestor v d, [(d, i)]) | (v, d) <- q | i <- [0 ..]]\n\n dfs :: Int -> Int -> S.IntSet -> State [(Int, Int)] (M.IntMap Int)\n dfs v d s = do\n let qv = map (first (+d)) $ M.findWithDefault [] v query\n new = filter (`S.notMember` s) $ map fst $ qv\n s' = foldr S.insert s new\n children <- forM (e!v) $ \\w -> dfs w (d + 1) s'\n\n let stat = foldr (M.unionWith (+)) M.empty children\n forM_ qv $ \\(k, i) -> do\n let cnt = M.findWithDefault 0 k stat\n modify ((i, if v == 0 || cnt == 0 then 0 else cnt - 1):)\n\n let stat' = foldr M.delete stat new\n if d `S.member` s\n then return $ M.insertWith (+) d 1 stat'\n else return stat'\n\n-- Control.Monad.State\nnewtype State s a = State {\n runState :: s -> (a, s)\n}\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a', s') = runState m s in runState (f a') s'\n\nget :: State s s\nget = State $ \\s -> (s, s)\n\nput :: s -> State s ()\nput s = State $ \\_ -> ((), s)\n\nmodify :: (s -> s) -> State s ()\nmodify f = State $ \\s -> ((), f s)\n\ngets :: (s -> a) -> State s a\ngets f = State $ \\s -> (f s, s)\n\n"}], "negative_code": [], "src_uid": "ce58d35343d66b962fb23b9963783acf"} {"source_code": "import Data.List\n\n-- three-room, five-room, and seven-room apartments.\n-- one window per room\n\nmain = interact $ concat . intersperse \"\\n\" . map solve . drop 1 . map read . lines\n\nsolve :: Int -> String\nsolve x \n | x == 1 || x == 2 || x == 4 = \"-1\"\n | otherwise = case mod x 3 of\n 0 -> show (div x 3) ++ \" 0 0\"\n 1 -> show (div x 3 - 2) ++ \" 0 1\"\n 2 -> show (div x 3 - 1) ++ \" 1 0\"", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> showAns) >>> unlines\n where\n showAns Nothing = \"-1\"\n showAns (Just (x, y, z)) = unwords $ show <$> [x, y, z]\n\ntype TIII = (Int, Int, Int)\n\nsolve :: Int -> Maybe TIII\nsolve n = dp !! n\n where\n dp :: [Maybe TIII]\n dp =\n [ Just (0, 0, 0),\n Nothing,\n Nothing,\n Just (1, 0, 0),\n Nothing,\n Just (0, 1, 0),\n Just (2, 0, 0)\n ]\n ++ zipWith3\n try3\n (map (i3 <$>) $ drop 4 dp)\n (map (i5 <$>) $ drop 2 dp)\n (map (i7 <$>) dp)\n\n i3 :: TIII -> TIII\n i3 (x, y, z) = (x + 1, y, z)\n i5 :: TIII -> TIII\n i5 (x, y, z) = (x, y + 1, z)\n i7 (x, y, z) = (x, y, z + 1)\n\n try3 x y z = x `tryNext` y `tryNext` z\n\ntryNext :: Maybe a -> Maybe a -> Maybe a\ntryNext (Just x) _ = Just x\ntryNext _ (Just y) = Just y\ntryNext _ _ = Nothing\n"}], "negative_code": [], "src_uid": "b43dee2f223c869a35b1b11ceb9d2b6b"} {"source_code": "import Data.List\n\nstrToIntegral :: (Read a, Integral a) => String -> a\nstrToIntegral = read\n\npairwise :: (a -> a -> b) -> [a] -> [b]\npairwise _ [] = []\npairwise _ [x] = []\npairwise f (x:xs) = map (f x) xs ++ pairwise f xs\n\ncountValues 0 books = [0]\ncountValues m books = [length left] ++ countValues (m-1) right\n where (left, right) = span (== m) books\n\nsolve (n:m:books) = sum $ pairwise (*) values\n where values = countValues m $ sortBy (flip compare) books\n\nmain = do\n input <- getContents\n let inputValues = map strToIntegral (words input) in\n putStrLn $ show (solve inputValues)\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\nimport Data.Int (Int32)\nimport Data.Array\n\ngetInts :: IO [Int32]\ngetInts = map (read . dropWhile (==' ') . takeWhile (/=' ')) . words <$> getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n items <- (map (\\x -> x - 1) . L.sort) <$> (getInts)\n let arr = accumArray (+) 0 (0, m - 1) [ (i, 1) | i <- items]\n let res = sum [ arr ! i * arr ! j | i <- [0 .. m - 2], j <- [i + 1 .. m - 1]]\n putStrLn $ show res"}, {"source_code": "module Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\nimport Data.Int (Int32)\nimport Data.Array\n\ngetInts :: IO [Int32]\ngetInts = map (read . T.unpack . T.strip . T.pack ) . words <$> getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n items <- (map (\\x -> x - 1) . L.sort) <$> (getInts)\n let arr = accumArray (+) 0 (0, m - 1) [ (i, 1) | i <- items]\n let res = sum [ arr ! i * arr ! j | i <- [0 .. m - 2], j <- [i + 1 .. m - 1]]\n putStrLn $ show res"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\nimport Data.Int (Int32)\n\ngetInts :: IO [Int32]\ngetInts = map (read . T.unpack . T.strip . T.pack ) . words <$> getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n --putStrLn $ show [n,m]\n items <- L.sort <$> (getInts)\n --putStrLn $ show items\n let (l', _) = foldr (\\x (c : cs, pr) -> if x == pr then ((c + 1) : cs, x) else (1 : c : cs, x)) ([0], 0) items\n let l = init l'\n --putStrLn $ show l\n\n let res = sum [l !! i * l !! j | i <- [0 .. length l - 1], j <- [0 .. length l - 1], i /= j]\n putStrLn $ show (res `div` 2)"}, {"source_code": "import Data.List\n\nstrToIntegral :: (Read a, Integral a) => String -> a\nstrToIntegral = read\n\npfoldl :: (a -> a -> a) -> (a -> a -> a) -> [a] -> a\npfoldl f g (x:xs)\n | length xs > 1 = f (foldl1 f (map (g x) xs)) (pfoldl f g xs)\n | length xs == 1 = g x (head xs)\n\ncountValues 0 _ = [0]\ncountValues m books = [length left] ++ countValues (m-1) right\n where (left, right) = span (== m) books\n\nsolve (n:m:books) = pfoldl (+) (*) values\n where values = countValues m $ sortBy (flip compare) books\n\nmain = do\n input <- getContents\n let inputValues = map strToIntegral (words input) in\n putStrLn $ show (solve inputValues)\n"}, {"source_code": "import Data.List\n\nstrToIntegral :: (Read a, Integral a) => String -> a\nstrToIntegral = read\n\n-- pairwise folding:\n-- f is used to fold the results generated by each application of g\n-- g is applied to each pair of elements (non-replacing)\npfoldl1 :: (a -> a -> a) -> (a -> a -> a) -> [a] -> a\npfoldl1 _ g [x, y] = g x y\npfoldl1 f g (x:xs) = f (foldl1 f (map (g x) xs)) (pfoldl1 f g xs)\n\ncountValues 0 _ = [0]\ncountValues m books = [length left] ++ countValues (m-1) right\n where (left, right) = span (== m) books\n\nsolve (n:m:books) = pfoldl1 (+) (*) values\n where values = countValues m $ sortBy (flip compare) books\n\nmain = do\n input <- getContents\n let inputValues = map strToIntegral (words input) in\n putStrLn $ show (solve inputValues)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char (digitToInt, intToDigit)\nimport Data.List (foldl')\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\n\n\nparseInt :: ByteString -> Int\nparseInt s\n | BS.head s == '-' = negate (go 0 (BS.tail s))\n | otherwise = go 0 s\n where\n go i s\n | BS.null s = i\n | otherwise = go (i*10 + digitToInt (BS.head s)) (BS.tail s)\n\n\nprintInt :: Int -> ByteString\nprintInt i\n | i < 10 = BS.singleton (intToDigit i)\n | otherwise = BS.snoc (printInt (i `quot` 10)) (intToDigit (i `rem` 10))\n\n\ndarnit :: ByteString -> ByteString\ndarnit s \n | BS.last s == '\\r' = BS.init s\n | otherwise = s\n\n\nmain :: IO ()\nmain = do\n n:m:_ <- fmap (map (fromIntegral . parseInt) . BS.words) BS.getLine\n genres <- fmap (map (fromIntegral . parseInt) . BS.words) BS.getLine\n let counts = map snd . IM.toDescList $ foldl' (flip (IM.alter (Just . maybe 1 (+1)))) IM.empty genres\n --print counts\n let options = foldl' (\\s c -> s + c * (n-c)) 0 counts :: Integer\n BS.putStrLn . printInt . fromIntegral $ options `quot` 2\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Tuple\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport Data.Word\nimport Debug.Trace\n\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine :: IO [Int]\n xs <- U.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print $ solve n m xs\n\nsolve :: Int -> Int -> U.Vector Int -> Int\nsolve _ m xs = sum [freq U.! i * freq U.! j | i<-[1..m-1],j<-[i+1..m]]\n where\n freq = U.unsafeAccumulate (+) (U.replicate (m+1) 0) $ U.map (,1) xs"}, {"source_code": "import Data.List (groupBy, sort)\n\nmain = do\n getLine\n as <- (map read . words) `fmap` getLine :: IO [Integer]\n\n let\n bs = map (fromIntegral . length) . groupBy (==) $ sort as\n s = sum bs\n ss = map (s -) $ scanl1 (+) bs\n r = sum $ zipWith (*) ss bs\n\n print r\n"}], "negative_code": [{"source_code": "import Data.List\n\nstrToIntegral :: (Read a, Integral a) => String -> a\nstrToIntegral = read\n\nf n = quot (n * (n-1)) 2\n\ndirty 0 books = 0\ndirty m books = let (left, right) = span (== m) books in\n f (length left) + dirty (m-1) right \nsolve (n:m:books) = (f n) - (dirty m $ sortBy (flip compare) books)\n\nmain = do\n input <- getContents\n let inputValues = map strToIntegral (words input) in\n putStrLn $ show (solve inputValues)\n"}, {"source_code": "import Data.List\n\nstrToIntegral :: (Read a, Integral a) => String -> a\nstrToIntegral = read\n\nf :: Integral a => a -> a\nf n = quot (n * (n-1)) 2\n\ncountInvalid 0 books = 0\ncountInvalid m books = let (left, right) = span (== m) books in\n f (length left) + countInvalid (m-1) right \nsolve (n:m:books) = (f n) - (countInvalid m $ sortBy (flip compare) books)\n\nmain = do\n input <- getContents\n let inputValues = map strToIntegral (words input) in\n putStrLn $ show (solve inputValues)\n"}], "src_uid": "e2ff228091ca476926b8e905f1bc8dff"} {"source_code": "import Data.Function\n\n[fd,fe,fh,fi] = map (\\x -> fix (\\ f g as -> if null as then \"NO\" else if head as == x then g $ tail as else f g $ tail as)) \"dehi\"\n\nmain =getLine >>= \\x -> putStrLn $ if x == \"heidi\" then \"NO\" else fh ( fe (fi (fd (fi (const \"YES\"))))) x\n", "positive_code": [{"source_code": "[] `isSubseqOf` _ = True\n_ `isSubseqOf` [] = False\nx@(a:as) `isSubseqOf` y@(b:bs) \n | a == b = as `isSubseqOf` bs\n | otherwise = x `isSubseqOf` bs\n\nmain = (\\l -> putStrLn $ if \"heidi\" `isSubseqOf` l then \"YES\" else \"NO\") =<< getLine"}, {"source_code": "[] `isSubseqOf` _ = True\n_ `isSubseqOf` [] = False\nx@(a:as) `isSubseqOf` (b:bs) \n | a == b = as `isSubseqOf` bs\n | otherwise = x `isSubseqOf` bs\n\nmain = (\\l -> putStrLn $ if \"heidi\" `isSubseqOf` l then \"YES\" else \"NO\") =<< getLine"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess [] _ = True\nprocess _ [] = False\nprocess (x:xs) y | elem x y = process xs (dropWhile (/=x) y)\n | otherwise = False\n\nmain = do\n\t\tn<-getLine\n\t\tputStrLn $ if process \"heidi\" n then \"YES\" else \"NO\"\n"}], "negative_code": [], "src_uid": "a457e22fc8ff882c15ac57bca6960657"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- (`shiftR` 1) . readInt <$> getLine\n xs <- zip <$> (map (=='1') <$> getLine) <*> (map (=='1') <$> getLine)\n let cnt = A.accumArray (+) 0 ((False,False),(True,True))\n $ map (,1) xs :: UArray (Bool,Bool) Int\n [!c00,!c01,!c10,!c11] = A.elems cnt\n minBnd = maximum [c01 + c11 - n, 0, (c11 - c10 + 1) `shiftR` 1]\n maxBnd = minimum [c00 + c01 + c11 - n, c11, (c01 + c11) `shiftR` 1]\n !p11 = maxBnd\n u = c01 + c11 - 2 * p11\n (!p10,!p01) | u <= c10 = (u,0)\n | otherwise = (c10, u - c10)\n !p00 = n - c01 - c11 + p11\n if minBnd > maxBnd then print (-1) else\n putStrLn $ unwords $ map show $ go p00 p01 p10 p11 xs\n where\n go !p00 !p01 !p10 !p11 xs = runST $ do\n arr <- A.newListArray ((False,False),(True,True)) [p00,p01,p10,p11]\n :: ST s (STUArray s (Bool,Bool) Int)\n foldr (\\(i,x) cont -> do\n ax <- A.readArray arr x\n if ax > 0\n then do\n A.writeArray arr x (ax - 1)\n (i:) <$> cont\n else cont)\n (return []) (zip [1..] xs)\n \n \nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Char] -> [Char] -> Maybe [Int]\nprocess first second = answer >>= Just . indiceList where\n clowns = zip first second\n f11 = (== ('1', '1'))\n f10 = (== ('1', '0'))\n f01 = (== ('0', '1'))\n f00 = (== ('0', '0'))\n fs = [f11, f10, f01, f00]\n ns@[n11, n10, n01, n00] = map (\\f -> length $ filter f clowns) fs\n answer = case catMaybes (map (findAnswer ns) [ (x11, x10) | x11 <- [0..n11], x10 <- [0..n10] ]) of\n x:_ -> Just x\n [] -> Nothing\n indices = map (\\f -> findIndices f clowns) fs\n indiceList ans = map (+ 1) $ concat $ zipWith take ans indices\n\nfindAnswer (n11:n10:n01:n00:[]) (x11, x10) = if valid then Just [x11, x10, x01, x00] else Nothing where\n n = n11 + n10 + n01 + n00\n nPerform = x11 + x10\n x01 = n01 - y01\n x00 = n00 - y00\n y11 = n11 - x11\n y10 = n10 - x10\n y01 = nPerform - y11\n y00 = (n `div` 2) - (y11 + y10 + y01)\n valid = all (>= 0) [x01, x00, y11, y10, y01, y00]\n\nmain = do\n n <- getInt\n first <- getLine\n second <- getLine\n putStrLn $ case process first second of\n Just ans -> intercalate \" \" . map show $ ans\n Nothing -> \"-1\"\n "}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- (`shiftR` 1) . readInt <$> getLine\n xs <- zip <$> (map (=='1') <$> getLine) <*> (map (=='1') <$> getLine)\n let cnt = A.accumArray (+) 0 ((False,False),(True,True))\n $ map (,1) xs :: UArray (Bool,Bool) Int\n [!c00,!c01,!c10,!c11] = A.elems cnt\n minBnd = maximum [c01 + c11 - n, 0, (c11 - c10 + 1) `shiftR` 1]\n maxBnd = minimum [c00 + c01 + c11 - n, c11, (c01 + c11) `shiftR` 1]\n !p11 = maxBnd\n u = c01 + c11 - 2 * p11\n (!p10,!p01) | u <= c10 = (u,0)\n | otherwise = (c10, u - c10)\n !p00 = n - c01 - c11 + p11\n print (p00,p01,p10,p11)\n if minBnd > maxBnd then print (-1) else\n putStrLn $ unwords $ map show $ go p00 p01 p10 p11 xs\n where\n go !p00 !p01 !p10 !p11 xs = runST $ do\n arr <- A.newListArray ((False,False),(True,True)) [p00,p01,p10,p11]\n :: ST s (STUArray s (Bool,Bool) Int)\n foldr (\\(i,x) cont -> do\n ax <- A.readArray arr x\n if ax > 0\n then do\n A.writeArray arr x (ax - 1)\n (i:) <$> cont\n else cont)\n (return []) (zip [1..] xs)\n \n \nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "src_uid": "3afa68fbe090683ffe16c3141aafe76e"} {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\n\n-- import GHC.Arr\nimport System.IO\n\ntype Arr = UArray Int Int\n\nfixBuf b = hSetBuffering b (BlockBuffering (Just 65536))\n\n-- import Data.Map ((!))\n-- not a change lol\nmain = do\n fixBuf stdin\n fixBuf stdout\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap =\n array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap =\n array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n hFlush stdout\n", "positive_code": [{"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n \nimport Control.Monad\n \n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Time.Clock.POSIX\nimport Data.Map.Strict ((!))\nimport qualified Data.Map.Strict as Map\n \n-- import Data.HashSet\nimport Data.Maybe\n \nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n \nreadInt :: IO Int\nreadInt = readLn @Int\n \n-- type Arr = UArray Int Int\n-- fixBuf b = hSetBuffering b (BlockBuffering Nothing)\nmain = do\n numCases <- readInt\n replicateM_ numCases $ do\n len <- readInt\n rootList <- readInts\n order <- readInts\n let rootMap\n -- array @UArray (1, len)\n = Map.fromList [(i, r) | i <- [1 .. len] | r <- rootList]\n orderMap\n -- array @UArray (1, len) \n = Map.fromList [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n \nimport Control.Monad\n \n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n \nimport Data.Map.Strict ((!))\nimport qualified Data.Map.Strict as Map\n \n-- import Data.HashSet\nimport Data.Maybe\n \nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n \nreadInt :: IO Int\nreadInt = readLn @Int\n \n-- type Arr = UArray Int Int\n-- fixBuf b = hSetBuffering b (BlockBuffering Nothing)\nmain = do\n numCases <- readInt\n replicateM_ numCases $ do\n len <- readInt\n rootList <- readInts\n order <- readInts\n let rootMap\n -- array @UArray (1, len)\n = Map.fromList [(i, r) | i <- [1 .. len] | r <- rootList]\n orderMap\n -- array @UArray (1, len) \n = Map.fromList [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\n\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n\nimport Data.Map ((!))\nimport qualified Data.Map as Map\n\n-- import Data.HashSet\nimport Data.Maybe\n\nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nreadInt :: IO Int\nreadInt = readLn @Int\n\n-- type Arr = UArray Int Int\n-- fixBuf b = hSetBuffering b (BlockBuffering Nothing)\nmain = do\n numCases <- readInt\n replicateM_ numCases $ do\n len <- readInt\n rootList <- readInts\n order <- readInts\n let rootMap\n -- array @UArray (1, len)\n = Map.fromList [(i, r) | i <- [1 .. len] | r <- rootList]\n orderMap\n -- array @UArray (1, len) \n = Map.fromList [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nimport System.IO\n\nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nreadInt :: IO Int\nreadInt = readLn @Int\n\ntype Arr = UArray Int Int\n\nfixBuf b = hSetBuffering b (BlockBuffering Nothing)\n\n-- import Data.Map ((!))\n-- not a change lol 23\nmain = do\n numCases <- readInt\n replicateM_ numCases $ do\n len <- readInt\n rootList <- readInts\n order <- readInts\n let rootMap =\n array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n orderMap =\n array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\n\n-- import GHC.Arr\nimport System.IO\n\ntype Arr = UArray Int Int\n\nfixBuf b = hSetBuffering b (BlockBuffering Nothing)\n\n-- import Data.Map ((!))\n-- not a change lol 23\nmain = do\n fixBuf stdin\n fixBuf stdout\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap =\n array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap =\n array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n hFlush stdout\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\n\n-- import GHC.Arr\nimport System.IO\n\ntype Arr = UArray Int Int\n\nfixBuf b = hSetBuffering b (BlockBuffering Nothing)\n\n-- import Data.Map ((!))\n-- not a change lol 23\nmain = do\n fixBuf stdin\n fixBuf stdout\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap =\n array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap =\n array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n hFlush stdout\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\n\n-- import GHC.Arr\nimport System.IO\n\ntype Arr = UArray Int Int\n\nfixBuf b = hSetBuffering b (BlockBuffering Nothing)\n\n-- import Data.Map ((!))\n-- not a change lol\nmain = do\n fixBuf stdin\n fixBuf stdout\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap =\n array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap =\n array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n hFlush stdout\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\n\n-- import GHC.Arr\nimport System.IO\n\ntype Arr = UArray Int Int\n\nfixBuf b = hSetBuffering b (BlockBuffering (Just 65536))\n\n-- import Data.Map ((!))\n-- not a change lol\nmain\n -- fixBuf stdin\n -- fixBuf stdout\n = do\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap =\n array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap =\n array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n -- hFlush stdout\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport GHC.Arr\nimport System.IO\n\nfixBuf b = hSetBuffering b (BlockBuffering (Just 65536))\n\n-- import Data.Map ((!))\n-- not a change lol\nmain = do\n fixBuf stdin\n fixBuf stdout\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap = array (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap = array (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n hFlush stdout\n"}, {"source_code": "{-# LANGUAGE ParallelListComp, TypeApplications #-}\n\nimport Control.Monad\nimport GHC.Arr\n\n-- import Data.Map ((!))\nmain = do\n numCases <- readLn @Int\n replicateM_ numCases $ do\n len <- readLn @Int\n rootList <- fmap (read @Int) . words <$> getLine\n let rootMap = array (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]\n order <- fmap (read @Int) . words <$> getLine\n let orderMap = array (1, len) [(x, i) | x <- order | i <- [0 .. len]]\n -- print (rootMap, orderMap)\n putStrLn $\n if all (\\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order\n then ([1 .. len] >>= \\k ->\n show (orderMap ! k - orderMap ! (rootMap ! k)) ++ \" \")\n else \"-1\"\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Graph\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\ntype WEdge w = (Vertex, (w, Vertex))\r\ntype WGraph w = Array Vertex [(w, Vertex)]\r\ndata WTree w a = WNode { rootLabelW :: a\r\n , subForestW :: [(w, WTree w a)]\r\n } deriving Show\r\n \r\nbuildWG :: Bounds -> [WEdge w] -> WGraph w\r\nbuildWG = accumArray (flip (:)) []\r\n \r\ndfsWTree :: WGraph w -> Vertex -> WTree w Vertex\r\ndfsWTree g u = go u u where\r\n go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]\r\n \r\ninstance Functor (WTree w) where\r\n fmap f = go where\r\n go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]\r\n\r\ngetVertexOrder :: Bounds -> [Int] -> UArray Int Int\r\ngetVertexOrder bnds p = runSTUArray $ do\r\n arr <- newArray bnds 0\r\n forM_ (zip [0..(snd bnds - 1)] p) $ \\(i, el) -> do\r\n writeArray arr el i\r\n return arr\r\n\r\ngetEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)\r\ngetEdges' root bnds tree = do\r\n edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)\r\n\r\n let dfs :: Int -> Int -> WTree Int Vertex -> ST s ()\r\n dfs ww w (WNode v ts) = do\r\n writeArray edges v (w - ww)\r\n mapM_ (\\(w', subts) -> dfs w w' subts) ts\r\n dfs 0 0 tree\r\n\r\n return edges\r\n\r\ngetEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int\r\ngetEdges root bnds tree = runSTUArray $ getEdges' root bnds tree\r\n\r\ndfsCheckBad :: WTree Int Vertex -> Bool\r\ndfsCheckBad (WNode v ts) = foldr (\\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts\r\n\r\nprintlist = putStrLn . unwords . map show . elems\r\n\r\nfita :: IO ()\r\nfita = do \r\n [n] <- readInts\r\n mas <- readInts\r\n p <- readInts\r\n\r\n let vertexOrder = getVertexOrder (1,n) p\r\n g = buildWG (1,n) $ zipWith (\\a b -> (b, (vertexOrder!a,a))) [1..n] mas\r\n root = fst . fromJust $ (find (\\(a,b)->a==b) $ zip [1..n] mas)\r\n tree = dfsWTree g root\r\n\r\n if (dfsCheckBad ((vertexOrder!) <$> tree)) \r\n then print (-1)\r\n else\r\n printlist $ getEdges root (1,n) tree\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Graph\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\ntype WEdge w = (Vertex, (w, Vertex))\r\ntype WGraph w = Array Vertex [(w, Vertex)]\r\ndata WTree w a = WNode { rootLabelW :: a\r\n , subForestW :: [(w, WTree w a)]\r\n } deriving Show\r\n \r\nbuildWG :: Bounds -> [WEdge w] -> WGraph w\r\nbuildWG = accumArray (flip (:)) []\r\n \r\ndfsWTree :: WGraph w -> Vertex -> WTree w Vertex\r\ndfsWTree g u = go u u where\r\n go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]\r\n \r\ninstance Functor (WTree w) where\r\n fmap f = go where\r\n go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]\r\n\r\ngetVertexOrder :: Bounds -> [Int] -> UArray Int Int\r\ngetVertexOrder bnds p = runSTUArray $ do\r\n arr <- newArray bnds 0\r\n forM_ (zip [0..(snd bnds - 1)] p) $ \\(i, el) -> do\r\n writeArray arr el i\r\n return arr\r\n\r\ngetEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)\r\ngetEdges' root bnds tree = do\r\n edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)\r\n\r\n let dfs :: Int -> Int -> WTree Int Vertex -> ST s ()\r\n dfs p w (WNode v ts) = do\r\n get_ <- readArray edges p\r\n writeArray edges v (w - get_)\r\n mapM_ (\\(w, subts) -> dfs v w subts) ts\r\n dfs root 0 tree\r\n\r\n return edges\r\n\r\ngetEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int\r\ngetEdges root bnds tree = runSTUArray $ getEdges' root bnds tree\r\n\r\ndfsCheckBad :: WTree Int Vertex -> Bool\r\ndfsCheckBad (WNode v ts) = foldr (\\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts\r\n\r\nprintlist xs = putStrLn s\r\n where (' ':s) = foldl (\\pref el -> pref++\" \"++(show el)) \"\" xs\r\n\r\nfita :: IO ()\r\nfita = do \r\n [n] <- readInts\r\n mas <- readInts\r\n p <- readInts\r\n\r\n let vertexOrder = getVertexOrder (1,n) p\r\n g = buildWG (1,n) $ zipWith (\\a b -> (b, (vertexOrder!a,a))) [1..n] mas\r\n root = fst . fromJust $ (find (\\(a,b)->a==b) $ zip [1..n] mas)\r\n tree = dfsWTree g root\r\n\r\n if (dfsCheckBad ((vertexOrder!) <$> tree)) \r\n then print (-1)\r\n else\r\n printlist . elems $ getEdges root (1,n) tree\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Graph\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\ntype WEdge w = (Vertex, (w, Vertex))\r\ntype WGraph w = Array Vertex [(w, Vertex)]\r\ndata WTree w a = WNode { rootLabelW :: a\r\n , subForestW :: [(w, WTree w a)]\r\n } deriving Show\r\n \r\nbuildWG :: Bounds -> [WEdge w] -> WGraph w\r\nbuildWG = accumArray (flip (:)) []\r\n \r\ndfsWTree :: WGraph w -> Vertex -> WTree w Vertex\r\ndfsWTree g u = go u u where\r\n go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]\r\n \r\ninstance Functor (WTree w) where\r\n fmap f = go where\r\n go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]\r\n\r\ngetVertexOrder :: Bounds -> [Int] -> UArray Int Int\r\ngetVertexOrder bnds p = runSTUArray $ do\r\n arr <- newArray bnds 0\r\n forM_ (zip [0..(snd bnds - 1)] p) $ \\(i, el) -> do\r\n writeArray arr el i\r\n return arr\r\n\r\ngetEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)\r\ngetEdges' root bnds tree = do\r\n edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)\r\n\r\n let dfs :: Int -> WTree Int Vertex -> ST s ()\r\n dfs w (WNode v ts) = do\r\n get_ <- readArray edges v\r\n writeArray edges v (w - get_)\r\n mapM_ (\\(w, subts) -> dfs w subts) ts\r\n dfs 0 tree\r\n\r\n return edges\r\n\r\ngetEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int\r\ngetEdges root bnds tree = runSTUArray $ getEdges' root bnds tree\r\n\r\ndfsCheckBad :: WTree Int Vertex -> Bool\r\ndfsCheckBad (WNode v ts) = foldr (\\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts\r\n\r\nprintlist xs = putStrLn s\r\n where (' ':s) = foldl (\\pref el -> pref++\" \"++(show el)) \"\" xs\r\n\r\nfita :: IO ()\r\nfita = do \r\n [n] <- readInts\r\n mas <- readInts\r\n p <- readInts\r\n\r\n let vertexOrder = getVertexOrder (1,n) p\r\n g = buildWG (1,n) $ zipWith (\\a b -> (b, (vertexOrder!a,a))) [1..n] mas\r\n root = fst . fromJust $ (find (\\(a,b)->a==b) $ zip [1..n] mas)\r\n tree = dfsWTree g root\r\n\r\n if (dfsCheckBad ((vertexOrder!) <$> tree)) \r\n then print (-1)\r\n else\r\n printlist . elems $ getEdges root (1,n) tree\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Graph\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\ntype WEdge w = (Vertex, (w, Vertex))\r\ntype WGraph w = Array Vertex [(w, Vertex)]\r\ndata WTree w a = WNode { rootLabelW :: a\r\n , subForestW :: [(w, WTree w a)]\r\n } deriving Show\r\n \r\nbuildWG :: Bounds -> [WEdge w] -> WGraph w\r\nbuildWG = accumArray (flip (:)) []\r\n \r\ndfsWTree :: WGraph w -> Vertex -> WTree w Vertex\r\ndfsWTree g u = go u u where\r\n go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]\r\n \r\ninstance Functor (WTree w) where\r\n fmap f = go where\r\n go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]\r\n\r\ngetVertexOrder :: Bounds -> [Int] -> UArray Int Int\r\ngetVertexOrder bnds p = runSTUArray $ do\r\n arr <- newArray bnds 0\r\n forM_ (zip [0..(snd bnds - 1)] p) $ \\(i, el) -> do\r\n writeArray arr el i\r\n return arr\r\n\r\ngetEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)\r\ngetEdges' root bnds tree = do\r\n edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)\r\n\r\n let dfs :: Int -> WTree Int Vertex -> ST s ()\r\n dfs w (WNode v ts) = do\r\n get_ <- readArray edges v\r\n writeArray edges v (w - get_)\r\n mapM_ (\\(w, subts) -> dfs w subts) ts\r\n dfs 0 tree\r\n\r\n return edges\r\n\r\ngetEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int\r\ngetEdges root bnds tree = runSTUArray $ getEdges' root bnds tree\r\n\r\ndfsCheckBad :: WTree Int Vertex -> Bool\r\ndfsCheckBad (WNode v ts) = foldr (\\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts\r\n\r\nfita :: IO ()\r\nfita = do \r\n [n] <- readInts\r\n mas <- readInts\r\n p <- readInts\r\n\r\n let vertexOrder = getVertexOrder (1,n) p\r\n g = buildWG (1,n) $ zipWith (\\a b -> (b, (vertexOrder!a,a))) [1..n] mas\r\n root = fst . fromJust $ (find (\\(a,b)->a==b) $ zip [1..n] mas)\r\n tree = dfsWTree g root\r\n\r\n if (dfsCheckBad ((vertexOrder!) <$> tree)) \r\n then print (-1)\r\n else\r\n print $ elems $ getEdges root (1,n) tree\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n"}], "src_uid": "4b512c39e71e34064c820958dde9f4a1"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = do\n n <- read <$> getLine\n as <- map read . words <$> getLine\n putStrLn \"1 1\"\n print (- head as)\n if n == 1\n then putStrLn \"1 1\\n0\\n1 1\\n0\"\n else do\n putStrLn $ \"2 \" ++ show n\n let changes = (`mod` n) <$> tail as\n putStrLn $ unwords $ show . (* (n - 1)) <$> changes\n let changed = 0 : zipWith (\\a change -> a + (n - 1) * change) (tail as) changes\n putStrLn $ \"1 \" ++ show n\n putStrLn $ unwords $ show . negate <$> changed\n", "positive_code": [{"source_code": "--import Data.List\nimport Control.Monad\nimport Data.Int (Int64)\n\ntype Operation = (Int64, Int64, [Int64])\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n let\n ans :: [Operation]\n ans = case n of\n 1 -> [(1,1, [0 - head a]), (1, 1, [0]), (1, 1, [0])]\n _ -> let\n p1 = (1, 1, [(n-1) * head a])\n p2 = (2, n, map (* (n-1)) (tail a))\n p3 = (1, n, map (* (0-n)) a)\n in [p1, p2, p3]\n forM_ ans $ \\(l, r, incs) -> do\n putStrLn (unwords $ map show [l, r])\n putStrLn (unwords $ map show incs)\n"}], "negative_code": [], "src_uid": "d15a758cfdd7a627822fe8be7db4f60b"} {"source_code": "import Data.List\n \naddLists :: [Int] -> [Int] -> [Int]\naddLists a b = map (\\(x, y) -> x + y) $ zip a b\n\ngetBest :: [(Int, Int)] -> Int -> Int\ngetBest [] _ = 400000000\ngetBest ((a, b) : tail) sz = if sz > a then min b $ getBest tail sz else getBest tail sz\n\nsolve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]\nsolve [] [] [] = []\nsolve (a : tailA) (b : tailB) c = (getBest c a) : solve tailA tailB ((a, b) : c)\nsolve _ _ _ = []\n\nmain = do\n s <- getLine\n let n = read s :: Int\n s <- getLine\n let szs = map (read :: String -> Int) $ words s\n s <- getLine\n let costs = map (read :: String -> Int) $ words s\n let bestlr = solve szs costs []\n let bestrl = reverse $ solve (reverse $ map negate szs) (reverse costs) []\n let ans = minimum $ addLists costs $ addLists bestlr bestrl\n print $ if ans < 400000000 then ans else -1", "positive_code": [{"source_code": "module Main where\n\nimport Data.Traversable\n\ninfinite = 3 * 100000000 + 100\n\nmain :: IO ()\nmain = do\n n <- getLine\n fontsS <- getLine\n let fonts = map (read :: String -> Integer) $ words fontsS\n costsS <- getLine\n let costs = map (read :: String -> Integer) $ words costsS\n print $ solve fonts costs\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve (f1:f2:fs) (c1:c2:cs) = let answ = tryCost (f2, c2) [(f1,c1)] (zip fs cs) in\n if answ == infinite\n then -1\n else answ\n\ntryCost :: (Integer, Integer) -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer\ntryCost _ _ [] = infinite\ntryCost (f,c) left right = min (c + fnd True f left + fnd False f right ) (tryCost (head right) ((f,c):left) (tail right))\n where\n fnd :: Bool -> Integer -> [(Integer, Integer)] -> Integer\n fnd is_l c_font = foldl (\\minim (fo,co) -> if co < minim && ((fo < c_font) == is_l) && (fo /= c_font)\n then co\n else minim\n ) infinite\n"}, {"source_code": "module Main where\n\nimport Data.Traversable\n\ninfinite = 3 * 100000000 + 100\n\nmain :: IO ()\nmain = do\n n <- getLine\n fontsS <- getLine\n let fonts = map (read :: String -> Integer) $ words fontsS\n costsS <- getLine\n let costs = map (read :: String -> Integer) $ words costsS\n print $ solve fonts costs\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve (f1:f2:fs) (c1:c2:cs) = let answ = tryCost (f2, c2) [(f1,c1)] (zip fs cs) in\n if answ == infinite\n then -1\n else answ\n\ntryCost :: (Integer, Integer) -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer\ntryCost _ _ [] = infinite\ntryCost (f,c) left right = min (c + (fnd True f left) + (fnd False f right) ) (tryCost (head right) ((f,c):left) (tail right))\n where\n fnd :: Bool -> Integer -> [(Integer, Integer)] -> Integer\n fnd is_l c_font lst = foldl (\\minim (fo,co) -> if (co < minim && ((fo < c_font) == is_l) && not (fo == c_font))\n then co\n else minim\n ) infinite lst\n"}, {"source_code": "import Data.List\n\nfindSmallest :: Int -> [(Int, Int)] -> Int\nfindSmallest sz scos = foldr (\\(s,c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos\n\noperate :: [(Int, Int)] -> [Int]\noperate [] = []\noperate (a:ax) =\n if (ax /= []) then ((findSmallest (fst a) ax) + (snd a)) : operate ax\n else (1000000009):[]\n\nffst :: (Int, Int, Int) -> Int\nffst (x, _, _) = x\n\nssnd :: (Int, Int, Int) -> Int\nssnd (_, x, _) = x\n\nthd :: (Int, Int, Int) -> Int\nthd (_, _, x) = x\n\nfindSmallest2 :: Int -> [(Int, Int, Int)] -> Int\nfindSmallest2 sz scos = foldr (\\(s, _, c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos\n\noperate2 :: [(Int, Int, Int)] -> [Int]\noperate2 [] = []\noperate2 (a:ax) =\n if (ax /= []) then ((findSmallest2 (ffst a) ax) + (ssnd a)) : operate2 ax\n else (1000000009):[]\n\nmain :: IO ()\nmain = do\n inp <- getLine\n let n = read inp :: Int\n sz <- getLine\n let sizes = map read (words sz)\n cs <- getLine\n let costs = map read (words cs)\n -- let sizes = take 3000 [3000, 2999..]\n -- let costs = take 3000 [100000000, 100000000..]\n let comp = operate (zip sizes costs)\n -- print comp\n let comp2 = operate2 (zip3 sizes costs comp)\n -- print comp2\n let res = foldr min 1000000009 comp2\n if (res >= 1000000009) then print (-1)\n else print res\n return ()\n"}], "negative_code": [{"source_code": "import Data.List\n\nfindSmallest :: Int -> [(Int, Int)] -> Int\nfindSmallest sz scos = foldr (\\(s,c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos\n\noperate :: [(Int, Int)] -> [Int]\noperate [] = []\noperate (a:ax) =\n if (ax /= []) then\n if (fst (head ax) > fst a) then let res = operate ax in\n if ((head res) < 2 * snd (head ax)) then ((head res) - snd (head ax) + snd a) : res else (snd (head ax) + snd a) : res\n else ((findSmallest (fst a) ax) + (snd a)) : operate ax\n else (1000000009):[]\n\nffst :: (Int, Int, Int) -> Int\nffst (x, _, _) = x\n\nssnd :: (Int, Int, Int) -> Int\nssnd (_, x, _) = x\n\nthd :: (Int, Int, Int) -> Int\nthd (_, _, x) = x\n\nfindSmallest2 :: Int -> [(Int, Int, Int)] -> Int\nfindSmallest2 sz scos = foldr (\\(s, _, c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos\n\noperate2 :: [(Int, Int, Int)] -> [Int]\noperate2 [] = []\noperate2 (a:ax) =\n if (ax /= []) then\n if (ffst (head ax) > ffst a) then let res = operate2 ax in\n if (head res == 1000000009) then ((findSmallest2 (ffst a) ax) + (ssnd a)) : res\n else if ((head res) - ssnd (head ax) < thd (head ax)) then ((head res) - ssnd (head ax) + ssnd a) : res else (thd (head ax) + ssnd a) : res\n else ((findSmallest2 (ffst a) ax) + (ssnd a)) : operate2 ax\n else (1000000009):[]\n\nmain :: IO ()\nmain = do\n inp <- getLine\n let n = read inp :: Int\n sz <- getLine\n let sizes = map read (words sz)\n cs <- getLine\n let costs = map read (words cs)\n let comp = operate (zip sizes costs)\n -- print comp\n let comp2 = operate2 (zip3 sizes costs comp)\n -- print comp2\n let res = foldr min 1000000009 comp2\n if (res >= 1000000009) then print (-1)\n else print res\n return ()\n"}], "src_uid": "4a48b828e35efa065668703edc22bf9b"} {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf x = if (same $ tail $ interval signal) then \"YES\" else \"NO\" where\n [n0,signal] = lines x\n first [] = 0\n first ('0':xs)\n | y == 0 = 0\n | otherwise = y + 1\n where y = first xs\n first ('1':_) = 1\n interval [] = []\n interval xs \n | y==0 = []\n | otherwise = y:(interval $ drop y xs)\n where y = first xs\n same [_] = True\n same (y:z:xs) = if y/=z then False else same (z:xs)\n\n", "positive_code": [{"source_code": "import Data.List (findIndices, nub)\nimport IO\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\non :: (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)\non f g h x = f (g x) (h x)\n\nsolve :: String -> Bool\nsolve = (<= 1) . length . nub . on (zipWith (-)) id tail . findIndices (== '1')\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n hGetLine hInput >> hGetLine hInput >>= hPutStrLn hOutput . (\"YES\" \"NO\") . solve\n\n hClose hInput\n hClose hOutput"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let conv :: String -> [Int]\n conv = map read . words\n writeText = appendFile \"output.txt\"\n s : ss <- lines <$> readFile \"input.txt\"\n let signals = reverse . dropWhile (== '0') . reverse . dropWhile (== '0')\n $ head ss\n check n (c : cs)\n | c == '1' = n : check 0 cs\n | otherwise = check (n + 1) cs\n check n _ = [n]\n zeros = tail . init $ check 0 signals\n ans = (!!) [\"NO\", \"YES\"] . fromEnum . and\n $ zipWith (==) zeros (tail zeros)\n writeText $ printf \"%s\\n\" (ans :: String)\n\n\n\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.lines\n\nfunc::[String]->String\nfunc (_:b:[]) = solve (map func' b)\n where\n func'::Char->Int\n func' a = toInt (a:[])\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[Int]->String\nsolve b = case next of\n Nothing -> \"NO\"\n Just c -> case (solve' c (tail $ dropWhile (/=1) list)) of\n True -> \"YES\"\n False -> \"NO\"\n where\n list = tail $ dropWhile (/=1) b\n next = elemIndex 1 list\n solve' a b = case next' of\n Just c | a == c -> solve' a $ drop (a+1) b\n | otherwise -> False\n Nothing -> True\n where\n next' = elemIndex 1 b"}], "negative_code": [{"source_code": "\nimport Data.List (nub)\nimport IO\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\non :: (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)\non f g h x = f (g x) (h x)\n\nfindIndices :: (a -> Bool) -> [a] -> [Int]\nfindIndices p xs = findIndices' $ zip xs [0..]\n where\n findIndices' [] = []\n findIndices' ((x, n) : xs)\n | p x = n : findIndices' xs\n | otherwise = findIndices' xs \n\nsolve :: String -> Bool\nsolve = (<= 1) . length . nub . on (zipWith (-)) id tail . findIndices (== '1')\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n hGetLine hInput >>= hPutStrLn hOutput . (\"YES\" \"NO\") . solve\n\n hClose hInput\n hClose hOutput\n"}], "src_uid": "4fc1ca3517168842cc85d74ba0066598"} {"source_code": "import Data.List\r\nimport qualified Data.Char as DC\r\nimport Control.Monad (replicateM)\r\n\r\nleq :: Char -> String -> Int\r\nleq c s = (length $ filter (== c) s)\r\n\r\nsolveN :: IO Int\r\nsolveN = do\r\n line <- fmap (\\x -> (words x) !! 1) getLine\r\n let val = ((leq 'D' line) - (leq 'U' line)) `mod` 10\r\n --putStr $ show val\r\n --putStr \" \"\r\n return val\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n n <- fmap (read :: String -> Int) getLine\r\n arr <- fmap (\\x -> map (read :: String -> Int) $ words x) getLine\r\n res <- replicateM n solveN\r\n putStrLn $ unwords $ map show $ map (\\x -> ((fst x) + (snd x)) `mod` 10) $ zip arr res\r\n \r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nsolveSingle :: Int -> String -> Int\nsolveSingle n \"\" = n\nsolveSingle n ('D':s) =\n solveSingle (n+1) s\nsolveSingle n ('U':s) =\n solveSingle (n-1) s\n\nsolve :: [Int] -> [String] -> [Int]\nsolve [] [] = []\nsolve (a:as) (op:ops) = \n ((solveSingle a op) `mod` 10):(solve as ops)\n\ntestcase 0 = return ()\ntestcase t = do\n n <- readLn :: IO Int\n arr <- map (read :: String -> Int) <$> words <$> getLine\n ops <- map (\\x -> last $ words x) <$> forM [1..n] (\\x -> getLine)\n putStrLn $ unwords $ map show $ solve arr ops\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve' :: Int -> String -> Int\nsolve' n \"\" = n\nsolve' n ('D':s) =\n solve' (n+1) s\nsolve' n ('U':s) =\n solve' (n-1) s\n\nsolve :: [Int] -> [String] -> [Int]\nsolve [] [] = []\nsolve (a:as) (op:ops) = \n ((solve' a op) `mod` 10):(solve as ops)\n\ntestcase 0 = return ()\ntestcase t = do\n n <- readLn :: IO Int\n arr <- map (read :: String -> Int) <$> words <$> getLine\n ops <- map (\\x -> last $ words x) <$> forM [1..n] (\\x -> getLine)\n putStrLn $ unwords $ map show $ solve arr ops\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&))\nimport Data.String (fromString)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = ([Int], [Int])\ntype CoDomain = [Int]\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ intercalate \" \" $ map show xs\n\ntoNum :: Char -> Int\ntoNum 'U' = -1\ntoNum _ = 1\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n operations <- replicateM n getLine\n let ops = ((`mod` 10) . sum . map toNum. (!!1). words) <$> operations\n return (xs, ops)\n\nsolve :: Solver\nsolve = uncurry (zipWith (\\x y -> (x + y) `mod` 10)) \n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "module Main (main) where\nimport Numeric (showFFloat)\nimport Data.Char (toUpper)\nimport Control.Monad\nimport qualified Data.Foldable as String\n\nimport qualified Data.Set as Set\n\n-- reset && stack build && echo \"success\" && stack exec haskell-codeforces-exe && echo finished\n-- gen-hie > hie.yaml\n\n\nstrToInt a = read a :: Int\nstrToFloat a = read a :: Float\n\npshow x = putStr (show x)\npfshow x = putStr (showFFloat (Just 2) x \"\")\n\n\ngetDelta 'U' = -1\ngetDelta 'D' = 1\n\ncalc :: (Int, String) -> Int\ncalc (value, changesS) = do\n let changes = last $ words changesS\n let delta = sum $ map getDelta changes\n (value + delta) `mod` 10\n\n\nsolve :: IO()\nsolve = do\n n <- getLine\n valuesS <- getLine\n\n let values = map strToInt $ words valuesS\n changes <- replicateM (read n) getLine\n\n let ff = zip values changes\n\n let res = map calc ff\n\n putStrLn $ concatMap ((++ \" \") . show) res\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n solve"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List\nimport Control.Monad\n--import Control.Monad.State.Strict\n\n-- parseLine = fmap (map read . words)\n\ntoSpaced :: Show a => [a] -> String\ntoSpaced = intercalate \" \" . map show\n\nprintSpaced :: Show a => [a] -> IO ()\nprintSpaced = putStrLn . toSpaced\n\nreadInt :: IO Int\nreadInt = fmap read getLine\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nf :: Int -> Int -> Int\nf x y = mod (x - y + 10) 10\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [1..t] $ \\t -> do\n n <- readInt\n a <- readInts\n\n offsets <- (forM [1..n] $ \\i -> do\n line <- getLine;\n let [b_i_s, s_i] = words line;\n -- print $ (b_i_s, s_i)\n let b_i :: Int = read b_i_s;\n let up_count = (length . filter (=='U')) s_i;\n let down_count = (length . filter (=='D')) s_i;\n return $ up_count - down_count)\n\n let res :: [Int] = zipWith f a offsets\n printSpaced res\n return ()\n"}, {"source_code": "import Control.Category ((>>>))\r\nimport Control.Monad (replicateM, replicateM_)\r\nimport Data.Function ((&))\r\nimport Data.Functor ((<&>))\r\n\r\n\r\nmain = do\r\n tests_n <- getLine <&> read\r\n replicateM_ tests_n $ do\r\n wheels_n <- getLine <&> read\r\n final_wheels <- getLine <&> (words >>> map read)\r\n wheels_offsets <- replicateM wheels_n $ do\r\n actions <- getLine <&> words <&> last\r\n return (count 'U' actions - count 'D' actions)\r\n let initial_wheels = zipWith (-) final_wheels wheels_offsets & map (`mod` 10)\r\n putStrLn (initial_wheels & map show & unwords)\r\n\r\n\r\ncount x = filter (== x) >>> length\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncount :: Eq a => a -> [a] -> Int\ncount elem xs = length (filter (==elem) xs)\n\nsolve :: [Int] -> [String] -> [Int]\nsolve a strs = map (\\(x, y) -> (10 + (x - y) `mod` 10) `mod` 10) (zip a b)\n where b = map (\\x -> count 'U' x - count 'D' x) strs\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- (readLn :: IO Int)\n a <- map (read :: String -> Int) <$> words <$> getLine\n strs <- map (head . tail . words) <$> forM [1 .. n] (\\_ -> getLine)\n putStrLn (unwords (map show (solve a strs)))\n\nmain :: IO ()\nmain = do n <- (readLn :: IO Int)\n forM_ [1 .. n] testCaseMain\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (forM_)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)\r\nimport Data.Array ((!))\r\nimport Data.Array.ST (MArray (newArray), readArray, runSTArray, writeArray)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Char (toLower)\r\nimport Data.List (nub, sort)\r\nimport Data.Maybe (fromJust)\r\n\r\ndata TC = TC {n :: Int, a :: [Int], steps :: [String]}\r\n\r\nsolve TC {..} = unwords $ fmap show res\r\n where\r\n stepsI = fmap (sum . fmap (\\case 'U' -> (-1); _ -> 1)) steps\r\n res = fmap (`mod` 10) $ zipWith (+) a stepsI\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (C.pack) >>> C.unlines\r\n\r\nscan = numberOf $ do\r\n n <- int\r\n a <- n >< int\r\n steps <- n >< (C.unpack <$> (int >> str))\r\n pure $ TC n a steps\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [], "src_uid": "fd47f1eb701077abc5ec67163ad4fcc5"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nnumLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()\nnumLoop start end f = if start <= end then go start else return ()\n where\n go !x | x == end = f x\n | otherwise = f x >> go (x+1)\n\n{-# INLINE numLoop #-}\n\nqsort gen xs = runSTUArray $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STUArray s Int Int)\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n n <- readLn\n as <- getInts\n gen <- newStdGen\n\n let\n as' = map lookup as\n where\n a = qsort gen as\n\n lookup x = lookup' 1 n\n where\n lookup' l r =\n case compare x (a!m) of\n EQ -> m\n LT -> lookup' l (m-1)\n GT -> lookup' (m+1) r\n where m = (l+r)`div`2\n\n\n cnt1 :: IOUArray Int Int <- newArray (1, n) 0\n ls :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt1 x\n writeArray cnt1 x $ c+1\n writeArray ls i $ c+1\n\n cnt2 :: IOUArray Int Int <- newArray (1, n) 0\n rs :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (reverse $ zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt2 x\n writeArray cnt2 x $ c+1\n writeArray rs i $ c+1\n\n {- let\n acc :: IntMap Int -> Int -> (IntMap Int, Int)\n acc !m a = (m', c)\n where\n !m' = IntMap.insertWith (+) a 1 m\n !c = fromIntegral $ m' IntMap.! a\n\n ls :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumL acc IntMap.empty as\n rs :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumR acc IntMap.empty as -}\n\n t :: IOUArray Int Int <- newArray_ (1, n)\n\n let\n solve l r\n | l == r = return 0\n | otherwise = do\n c1 <- solve l m\n c2 <- solve (m+1) r\n\n c <- count l (m+1) (0 :: Int64)\n\n merge ls l m r\n merge rs l m r\n\n let !s = c1+c2+c\n return s\n where\n m = (l+r) `div` 2\n\n count i j !c\n | i == m+1 = return c\n | j == r+1 = count (i+1) j $ c + fromIntegral (j-(m+1))\n | otherwise = do\n l <- readArray ls i\n r <- readArray rs j\n\n if l <= r\n then count (i+1) j $ c + fromIntegral (j-(m+1))\n else count i (j+1) c\n\n {-# INLINE merge #-}\n merge a l m r = do\n merge' l (m+1) 1\n\n numLoop 1 (r-l+1) $ \\i -> readArray t i >>= writeArray a (l+i-1) \n where\n merge' i j k\n | i == m+1 && j == r+1 = return ()\n | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)\n | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)\n | otherwise = do\n x <- readArray a i\n y <- readArray a j\n\n if x <= y\n then writeArray t k x >> merge' (i+1) j (k+1)\n else writeArray t k y >> merge' i (j+1) (k+1)\n\n r <- solve 1 n\n\n print r\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nnumLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()\nnumLoop start end f = if start <= end then go start else return ()\n where\n go !x | x == end = f x\n | otherwise = f x >> go (x+1)\n\n{-# INLINE numLoop #-}\n\nqsort gen xs = runSTUArray $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STUArray s Int Int)\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n n <- readLn\n as <- getInts\n gen <- newStdGen\n\n let\n as' = map lookup as\n where\n a = qsort gen as\n\n lookup x = lookup' 1 n\n where\n lookup' l r =\n case compare x (a!m) of\n EQ -> m\n LT -> lookup' l (m-1)\n GT -> lookup' (m+1) r\n where m = (l+r)`div`2\n\n\n cnt1 :: IOUArray Int Int <- newArray (1, n) 0\n ls :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt1 x\n writeArray cnt1 x $ c+1\n writeArray ls i $ c+1\n\n cnt2 :: IOUArray Int Int <- newArray (1, n) 0\n rs :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (reverse $ zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt2 x\n writeArray cnt2 x $ c+1\n writeArray rs i $ c+1\n\n {- let\n acc :: IntMap Int -> Int -> (IntMap Int, Int)\n acc !m a = (m', c)\n where\n !m' = IntMap.insertWith (+) a 1 m\n !c = fromIntegral $ m' IntMap.! a\n\n ls :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumL acc IntMap.empty as\n rs :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumR acc IntMap.empty as -}\n\n t :: IOUArray Int Int <- newArray_ (1, n)\n\n let\n solve l r\n | l == r = return 0\n | otherwise = do\n c1 <- solve l m\n c2 <- solve (m+1) r\n\n c <- count l (m+1) (0 :: Int64)\n\n merge ls l m r\n merge rs l m r\n\n return $ c1+c2+c\n where\n m = (l+r) `div` 2\n\n count i j !c\n | i == m+1 = return c\n | j == r+1 = count (i+1) j $ c + fromIntegral (j-(m+1))\n | otherwise = do\n l <- readArray ls i\n r <- readArray rs j\n\n if l <= r\n then count (i+1) j $ c + fromIntegral (j-(m+1))\n else count i (j+1) c\n\n {-# INLINE merge #-}\n merge a l m r = do\n merge' l (m+1) 1\n\n numLoop 1 (r-l+1) $ \\i -> readArray t i >>= writeArray a (l+i-1) \n where\n merge' i j k\n | i == m+1 && j == r+1 = return ()\n | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)\n | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)\n | otherwise = do\n x <- readArray a i\n y <- readArray a j\n\n if x <= y\n then writeArray t k x >> merge' (i+1) j (k+1)\n else writeArray t k y >> merge' i (j+1) (k+1)\n\n r <- solve 1 n\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nnumLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()\nnumLoop start end f = if start <= end then go start else return ()\n where\n go !x | x == end = f x\n | otherwise = f x >> go (x+1)\n\n{-# INLINE numLoop #-}\n\nqsort gen xs = runSTUArray $ do\n let n = length xs\n a <- newListArray (1, n) xs :: ST s (STUArray s Int Int)\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n let loop i j\n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n n <- readLn\n as <- getInts\n gen <- newStdGen\n\n let\n as' = map lookup as\n where\n a = qsort gen as\n\n lookup x = lookup' 1 n\n where\n lookup' l r =\n case compare x (a!m) of\n EQ -> m\n LT -> lookup' l (m-1)\n GT -> lookup' (m+1) r\n where m = (l+r)`div`2\n\n\n cnt1 :: IOUArray Int Int <- newArray (1, n) 0\n ls :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt1 x\n writeArray cnt1 x $ c+1\n writeArray ls i $ c+1\n\n cnt2 :: IOUArray Int Int <- newArray (1, n) 0\n rs :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (reverse $ zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt2 x\n writeArray cnt2 x $ c+1\n writeArray rs i $ c+1\n\n {- let\n acc :: IntMap Int -> Int -> (IntMap Int, Int)\n acc !m a = (m', c)\n where\n !m' = IntMap.insertWith (+) a 1 m\n !c = fromIntegral $ m' IntMap.! a\n\n ls :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumL acc IntMap.empty as\n rs :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumR acc IntMap.empty as -}\n\n t :: IOUArray Int Int <- newArray_ (1, n)\n\n let\n solve l r\n | l == r = return 0\n | otherwise = do\n c1 <- solve l m\n c2 <- solve (m+1) r\n\n c <- count l (m+1) (0 :: Int64)\n\n merge ls l m r\n merge rs l m r\n\n return $ c1+c2+c\n where\n m = (l+r) `div` 2\n\n count i j !c\n | i == m+1 = return c\n | j == r+1 = count (i+1) j $ c + fromIntegral (j-(m+1))\n | otherwise = do\n l <- readArray ls i\n r <- readArray rs j\n\n if l <= r\n then count (i+1) j $ c + fromIntegral (j-(m+1))\n else count i (j+1) c\n\n merge a l m r = do\n merge' l (m+1) 1\n\n numLoop 1 (r-l+1) $ \\i -> readArray t i >>= writeArray a (l+i-1) \n where\n merge' i j k\n | i == m+1 && j == r+1 = return ()\n | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)\n | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)\n | otherwise = do\n x <- readArray a i\n y <- readArray a j\n\n if x <= y\n then writeArray t k x >> merge' (i+1) j (k+1)\n else writeArray t k y >> merge' i (j+1) (k+1)\n\n r <- solve 1 n\n\n print r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n as <- getInts\n\n let\n as' = map lookup as\n where\n a :: UArray Int Int = listArray (1, n) $ sort as\n\n lookup x = lookup' 1 n\n where\n lookup' l r\n | x == v = m\n | x < v = lookup' 1 (m-1)\n | x > v = lookup' (m+1) r\n where\n m = (l+r)`div`2\n v = a!m\n\n\n cnt1 :: IOUArray Int Int <- newArray (1, n) 0\n ls :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt1 x\n writeArray cnt1 x $ c+1\n writeArray ls i $ c+1\n\n cnt2 :: IOUArray Int Int <- newArray (1, n) 0\n rs :: IOUArray Int Int <- newArray_ (1, n)\n forM_ (reverse $ zip [1..n] as') $ \\(i, x) -> do\n c <- readArray cnt2 x\n writeArray cnt2 x $ c+1\n writeArray rs i $ c+1\n\n t :: IOUArray Int Int <- newArray_ (1, n)\n\n let\n solve l r\n | l == r = return 0\n | otherwise = do\n c1 <- solve l m\n c2 <- solve (m+1) r\n\n c <- count l (m+1) 0\n\n merge ls l m r\n merge rs l m r\n\n return $ c1+c2+c\n where\n m = (l+r) `div` 2\n\n count i j c\n | i == m+1 = return c\n | j == r+1 = count (i+1) j $ c + j-(m+1)\n | otherwise = do\n l <- readArray ls i\n r <- readArray rs j\n\n if l <= r\n then count (i+1) j $ c + j-(m+1)\n else count i (j+1) c\n\n merge a l m r = do\n merge' l (m+1) 1\n\n forM_ [1..r-l+1] $ \\i -> readArray t i >>= writeArray a (l+i-1) \n where\n merge' i j k\n | i == m+1 && j == r+1 = return ()\n | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)\n | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)\n | otherwise = do\n x <- readArray a i\n y <- readArray a j\n\n if x <= y\n then writeArray t k x >> merge' (i+1) j (k+1)\n else writeArray t k y >> merge' i (j+1) (k+1)\n\n r <- solve 1 n\n\n print r\n"}], "src_uid": "d3b5b76f0853cff6c69b29e68a853ff7"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n s <- get\n let k = f1 s in do\n putln $ length k\n f2 k\n\nf1 :: String -> [(Int, [Int])]\nf1 s = let sa = array (1, length s) (zip [1..length s] s) :: UArray Int Char in\n let ll = filter (\\i -> sa ! i == '(') [1..length s] in\n let rl = filter (\\i -> sa ! i == ')') $ reverse [1..length s] in\n let lrpair = filter (\\(i, j) -> i < j) $ zip ll rl in\n let (newl, newr) = unzip lrpair in\n let newi = (++) newl $ reverse newr in\n let (news, _) = foldl (\\(s, l) i ->\n case l of\n x : xs -> if x == i then (s, xs) else ((sa ! i) : s, l)\n [] -> ((sa ! i) : s, [])\n ) ([], newi) [1..length s] in\n if length newi == 0 then\n []\n else\n (length newi, newi) : (f1 $ reverse news)\n\nf2 :: [(Int, [Int])] -> EIO ()\nf2 [] = return ()\nf2 ((k, l) : r) = do\n putln k\n putln l\n f2 r", "positive_code": [{"source_code": "--import Control.Monad\n--import Data.List\n--import Data.Function\n\nmain :: IO ()\nmain = routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n if end s\n then\n putStrLn \"0\"\n else\n do\n putStrLn \"1\"\n let\n answer = solve s\n in do\n print $ length answer\n putStrLn $ (unwords.map show) answer\n\nsolve :: String -> [Int]\nsolve s = take m offene ++ reverse (take m (reverse geschlossene))\n where\n zipped = zip s [(1::Int)..]\n offene = map snd $ filter (\\(a,_) -> a=='(') zipped\n geschlossene = map snd $ filter (\\(a,_) -> a==')') zipped\n s1 = scanl (\\acc ch -> acc + fromEnum (ch == '(')) 0 s\n s2 = reverse $ scanr (\\ch acc -> acc + fromEnum (ch == ')')) 0 s\n m = maximum $ zipWith min s1 (reverse s2)\n\nend :: String -> Bool\nend s = all (== '(') $ dropWhile (== ')') s\n"}], "negative_code": [{"source_code": "--import Control.Monad\n--import Data.List\n--import Data.Function\n\nmain :: IO ()\nmain = routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n if end s\n then\n putStrLn \"0\"\n else\n do\n putStrLn \"1\"\n let\n answer = solve s\n in do\n print $ length answer\n putStrLn $ (unwords.map show) answer\n\nsolve :: String -> [Int]\nsolve s = take m offene ++ take m (reverse geschlossene)\n where\n zipped = zip s [(1::Int)..]\n offene = map snd $ filter (\\(a,_) -> a=='(') zipped\n geschlossene = map snd $ filter (\\(a,_) -> a==')') zipped\n s1 = scanl (\\acc ch -> acc + fromEnum (ch == '(')) 0 s\n s2 = reverse $ scanr (\\ch acc -> acc + fromEnum (ch == ')')) 0 s\n m = maximum $ zipWith min s1 (reverse s2)\n\nend :: String -> Bool\nend s = all (== '(') $ dropWhile (== ')') s\n"}], "src_uid": "f78d04f699fc94103e5b08023949854d"} {"source_code": "import Data.Char (ord,chr)\nimport Control.Monad --ord Char->Int , chr Int ->Char\n\nintercal :: [Char] -> Int -> [Int]\nintercal [] n = []\nintercal (x:xs) n = let k = transform x\n in value k : intercal xs k\n where\n transform = toDec.length8. toBi.ord\n value k = (n - k) `mod` 256\n\nlength8 :: String -> String\nlength8 xs = xs ++ replicate (8-length xs) '0'\n\n--10\ufffdi\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd2\ufffdi\ufffd\ufffd\ufffd\ufffd(\ufffdt\ufffd\ufffd)\ntoBi :: Int -> String\ntoBi 0 = \"0\"\ntoBi n = show (mod n 2) ++ toBi (div n 2)\n\n--2\ufffdi\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd10\ufffdi\ufffd\ufffd\ufffd\ufffd\ntoDec :: String -> Int\ntoDec [] = 0\ntoDec ('0':cs) = toDec cs\ntoDec ('1':cs) = 2^(length cs) + toDec cs\n\nmain = do xs <- getLine\n forM_ (intercal xs 0) print", "positive_code": [{"source_code": "import Data.Bits\nimport Data.Char\nimport Data.Word\nimport Data.Function\n\nmain=getLine>>=mapM print.solve.(0:).map (toEnum.ord)\n\nsolve :: [Word8] -> [Word8]\nsolve cs = zipWith ((-)`on`rev) cs (tail cs)\n\nrev :: Word8 -> Word8\nrev n = foldl setBit 0 [ 7-i | i<-[0..7], testBit n i]"}, {"source_code": "r 0 c n=c\nr i c n=r(i-1)(c*2+n`mod`2)$n`div`2\nf l=zipWith(-)(0:l)l\nmain=interact$unlines.map(show.(`mod`256)).f.map(r 8 0.fromEnum).init\n"}, {"source_code": "toBits 0 n = []\ntoBits i n = (n `mod` 2) : toBits (i-1) (n `div` 2)\n\nfromBits [] = 0\nfromBits (h:t) = 2*fromBits t + h\n\nrev = fromBits . reverse . toBits 8\n\nrecover l = zipWith (-) (0:l) l\n\nto256 = map (`mod` 256)\ns[l]=to256 $ recover (map (rev.fromEnum) l)\nmain=interact$unlines.map show.s.lines"}, {"source_code": "module Main where\n\nimport Data.Char\n\nmain = interact (unlines . solve . head. lines)\n\nsolve :: String -> [String]\nsolve line = map show $ getArray (0 : (map ord line))\n\ngetArray :: [Int] -> [Int]\ngetArray [_] = []\ngetArray (x : (t@(y:_))) = (mirror x - mirror y) `trueMod` 256 : getArray t\n\ntrueMod :: Int -> Int -> Int\ntrueMod x y =\n let m = x `mod` y in\n if m < 0 then m + y else m\n\nmirror = bin2num . reverse . num2bin\n\nbin2num = foldl (\\x y -> 2 * x + y) 0\n\nnum2bin = reverse . (num2bin' 8)\n\nnum2bin' 0 x = []\nnum2bin' n x = x `mod` 2 : num2bin' (n - 1) (x `div` 2)\n"}, {"source_code": "import Data.List\nimport Data.Char\n\nreverseBits :: Int -> Int\nreverseBits n = snd $ foldl' collect (n, 0) [1 .. 8]\n where collect (n, res) _ = (n `div` 2,\n res * 2 + n `mod` 2)\n\nsolve :: String -> [Int]\nsolve text = map handle xs\n where xs = zip (0:map ord text) $ map ord text\n handle (last, x) =\n (reverseBits last - reverseBits x) `mod` 256\n\nmain = do text <- getLine\n sequence_ $ map print $ solve text"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nimport Data.Bits\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nind :: Bool -> Int\nind b = if b then 1 else 0\n\nreverseBin :: Int -> Int\nreverseBin bin =\n (\n (ind (testBit bin 7))+\n (ind (testBit bin 6))*2+\n (ind (testBit bin 5))*4+\n (ind (testBit bin 4))*8+\n (ind (testBit bin 3))*16+\n (ind (testBit bin 2))*32+\n (ind (testBit bin 1))*64+\n (ind (testBit bin 0))*128\n )\n\nconvToINTERCAL :: Char -> Int\nconvToINTERCAL c =\n let n = ord c\n in\n (512-(reverseBin n))\n\nsolve :: String -> [Int]\nsolve str = rec 0 str []\n where\n rec _ [] l = reverse l\n rec prev (x:xs) l = rec (reverseBin (ord x)) xs ((mod ((convToINTERCAL x)+prev) 256):l)\n\nmain = getLine >>= puts.unlines.map show.solve"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n BS.unpack <$> readLine\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve s = BS.unlines $ map (BS.pack . show ) $ go 0 (map ord s)\n\nrevbits a = sum [((a `shiftR` i) .&. 1) `shiftL` (7 - i) | i <- [0..7]]\n\ngo _ [] = []\ngo p (x:xs) = (p' - x') `mod` 256 : go x xs\n where\n p' = revbits p\n x' = revbits x\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "negative_code": [{"source_code": "import Data.Bits\nimport Data.Char\nimport Data.Word\nimport Data.Function\n\nmain=interact $ unlines.map show.solve.(0:).map (toEnum.ord)\n\nsolve :: [Word8] -> [Word8]\nsolve cs = zipWith ((-)`on`rev) cs (tail cs)\n\nrev :: Word8 -> Word8\nrev n = foldl setBit 0 [ 7-i | i<-[0..7], testBit n i]"}], "src_uid": "a65e12186430f74c18c50d2eb55a9794"} {"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O3 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Array.Unboxed\nimport qualified Data.Sequence as S\nimport Data.Foldable\nimport Data.List\nimport Data.Ratio\nimport Data.Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest :: Int -> [Int] -> Int\ntest n l = r1 + r2 \n where\n (a, l') = splitAt n l\n b = take n l'\n x = zip a b\n r2 = maximum $ (0 : ) $ map length $ group $ toList $ S.unstableSort $ S.fromList [ (fromIntegral j) % (fromIntegral i) :: Ratio Int64 | (i, j) <- x, i /= 0]\n r1 = length $ filter (\\(i, j) -> i == 0 && j == 0) x\n\nmain = do\n s <- C.getContents\n let (n:a) = map ri $ C.words s\n print $ test n a\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O3 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Array.Unboxed\nimport qualified Data.Sequence as S\nimport Data.Foldable\nimport Data.List\nimport Data.Ratio\nimport Data.Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest :: Int -> [Int] -> Int\ntest n l = max (r1 + r2) r3\n where\n (a, l') = splitAt n l\n b = take n l'\n x = zip a b\n r2 = maximum $ (0 : ) $ map length $ group $ toList $ S.unstableSort $ S.fromList [ (fromIntegral j) % (fromIntegral i) :: Ratio Int64 | (i, j) <- x, i /= 0]\n r1 = length $ filter (\\(i, j) -> i == 0 && j == 0) x\n r3 = length $ filter (== 0) b\n\nmain = do\n s <- C.getContents\n let (n:a) = map ri $ C.words s\n print $ test n a\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndivide a b\n | a == 0 && b /= 0 = Nothing\n | b == 0 = Just 0\n | otherwise = Just (fromIntegral a % fromIntegral b)\n\nprocess :: [Int] -> [Int] -> Int\nprocess as bs = maxCount ds where\n ds = catMaybes $ zipWith divide as bs :: [Rational]\n n = length ds\n maxCount = maximum' . map lengthPlusWc . group . sort\n maximum' [] = 0\n maximum' l = maximum l\n lengthPlusWc l = if head l == 0 then length l else length l + wildcardCnt\n wildcardCnt = length $ filter (\\(a, b) -> a == 0 && b == 0) (zip as bs)\n \n \nmain = do\n n <- getInt\n as <- getInts\n bs <- getInts\n print $ process as bs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O3 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Array.Unboxed\nimport qualified Data.Sequence as S\nimport Data.Foldable\nimport Data.List\nimport Data.Ratio\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest :: Int -> [Int] -> Int\ntest n l = r1 + r2 \n where\n (a, l') = splitAt n l\n b = take n l'\n x = zip a b\n r2 = maximum $ (0 : ) $ map length $ group $ toList $ S.unstableSort $ S.fromList [j % i | (i, j) <- x, i /= 0]\n r1 = length $ filter (\\(i, j) -> i == 0 && j == 0) x\n\nmain = do\n s <- C.getContents\n let (n:a) = map ri $ C.words s\n print $ test n a\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndivide a b\n | a == 0 && b /= 0 = Nothing\n | b == 0 = Just 0\n | otherwise = Just $ ((/) `on` (% 1)) a b\n\nprocess :: [Int] -> [Int] -> Int\nprocess as bs = if nonzeroD then maxDCnt + wildcardCnt else maxDCnt where\n ds = catMaybes $ zipWith divide as bs\n n = length ds\n dArr = listArray (1, n) (sort ds) :: Array Int (Ratio Int)\n dCnts = map snd $ scanl foldFn (1, (0, 0)) [1..n]\n foldFn (i, _) j = (i', (x, j - i' + 1)) where\n x = dArr ! j\n i' = until (\\_i -> (dArr ! _i) == x) (+ 1) i\n maxDCnt = snd $ maximumBy (compare `on` snd) dCnts\n nonzeroD = length (filter (\\(x, cnt) -> x /= (0%1) && cnt == maxDCnt) dCnts) > 0\n wildcardCnt = length $ filter (\\(a, b) -> a == 0 && b == 0) (zip as bs)\n \n \nmain = do\n n <- getInt\n as <- getInts\n bs <- getInts\n print $ process as bs\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndivide a b\n | a == 0 && b /= 0 = Nothing\n | b == 0 = Just 0\n | otherwise = Just $ ((/) `on` (% 1)) a b\n\nprocess :: [Int] -> [Int] -> Int\nprocess as bs = maximum dCnts where\n ds = catMaybes $ zipWith divide as bs\n n = length ds\n dArr = listArray (1, n) (sort ds) :: Array Int (Ratio Int)\n dCnts = map snd $ scanl foldFn (1, 0) [1..n]\n foldFn (i, _) j = (i', j - i' + 1) where\n x = dArr ! j\n i' = until (\\_i -> (dArr ! _i) == x) (+ 1) i\n \nmain = do\n n <- getInt\n as <- getInts\n bs <- getInts\n print $ process as bs\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndivide a b\n | a == 0 && b /= 0 = Nothing\n | b == 0 = Just 0\n | otherwise = Just $ ((/) `on` (% 1)) a b\n\nprocess :: [Int] -> [Int] -> Int\nprocess as bs = maximum dCnts where\n ds = catMaybes $ zipWith divide as bs\n n = length ds\n dArr = listArray (1, n) (sort ds) :: Array Int (Ratio Int)\n dCnts = map snd $ scanl foldFn (1, 0) [1..n]\n foldFn (i, _) j = (i', j - i' + 1 + extra) where\n extra = if x == 0 then 0 else wildcardCnt\n x = dArr ! j\n i' = until (\\_i -> (dArr ! _i) == x) (+ 1) i\n wildcardCnt = length $ filter (\\(a, b) -> a == 0 && b == 0) (zip as bs)\n \n \nmain = do\n n <- getInt\n as <- getInts\n bs <- getInts\n print $ process as bs\n"}], "src_uid": "c083988d20f434d61134f7b376581eb6"} {"source_code": "import Data.List\nimport Data.Maybe\n\nmoveLetters :: String -> String -> [Int] -> Int -> [Int]\nmoveLetters \"\" \"\" list _ = list\nmoveLetters (s:xs) (t:xt) list offset\n | s == t = moveLetters xs xt list $ offset + 1\n | otherwise = moveLetters newxs xt newList $ offset + 1\n where newList = list ++ (map (+ offset) $ reverse [0..i - 1])\n i = fromMaybe 0 $ findIndex (== t) (s:xs)\n newxs = s : (take (i - 1) xs ++ drop i xs)\n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n\n if sort s /= sort t then do\n putStrLn \"-1\"\n else do\n let perms = moveLetters s t [] 0\n putStrLn . show $ length perms\n putStrLn . unwords . map (show . (+ 1)) $ perms \n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport System.IO\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nconstruct :: BS.ByteString -> [Int]\nconstruct str\n | BS.null str = []\n | isSpace (BS8.head str) = construct (BS8.tail str)\n | otherwise = let Just (i, other) = BS8.readInt str in i : construct other\n\ngetInts :: IO [Int]\ngetInts = construct `fmap` BS.getLine\n\nfastPrint :: Char -> [Int] -> IO ()\nfastPrint mid arr = hPutBuilder stdout $ build arr\n where build = foldr (\\n b -> intDec n <> charUtf8 mid <> b) mempty\n\ngetMove from to\n | from == to = []\n | otherwise = findp : getMove (swap findp from) to\n where check idx = if from !! idx == to !! idx then check (idx+1) else head ([x|x <- [idx+1..length from - 1], from !! x == to !! idx])\n findp = check 0\n \nswap x from = take (x-1) from ++ [from !! x] ++ [from !! (x-1)] ++ drop (x+1) from\n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n if (sort s) /= (sort t) then putStrLn \"-1\"\n else do\n let move = getMove s t\n print (length move)\n putStrLn $ intercalate \" \" $ map show move"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nmoveLetter :: Int -> String -> String -> [Int]\nmoveLetter offset s t = reverse $ map (+ trueOffset) steps\n where stepCount = fromMaybe 0 $ findIndex (== head t) s\n steps = if stepCount == 0 then [0] else [0..stepCount - 1]\n trueOffset = if stepCount == 0 then offset - 1 else offset\n\ngetPermutations :: Int -> String -> String -> [Int]\ngetPermutations _ \"\" \"\" = []\ngetPermutations offset (s:sx) (t:tx) \n | s == t = getPermutations (offset + 1) sx tx\n | otherwise = curLetterPerms ++ (getPermutations (offset + 1) sx tx)\n where curLetterPerms = (moveLetter offset (s:sx) (t:tx))\n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n\n if sort s /= sort t then do\n putStrLn \"-1\"\n else do\n let perms = getPermutations 0 s t\n putStrLn . show $ length perms\n putStrLn . unwords . map (show . (+ 1)) $ perms \n\n--cdef\n--dfec"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmoveLetter :: Int -> String -> String -> [Int]\nmoveLetter offset s t = reverse $ map (+ offset) steps\n where stepCount = fromMaybe 0 $ findIndex (== head t) s\n steps = if stepCount == 0 then [-1] else [0..stepCount - 1]\n\ngetPermutations :: Int -> String -> String -> [Int]\ngetPermutations _ \"\" \"\" = []\ngetPermutations offset (s:sx) (t:tx) \n | s == t = getPermutations (offset + 1) sx tx\n | otherwise = curLetterPerms ++ (getPermutations (offset + 1) sx tx)\n where curLetterPerms = (moveLetter offset (s:sx) (t:tx))\n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n\n if sort s /= sort t then do\n putStrLn \"-1\"\n else do\n let perms = getPermutations 0 s t\n putStrLn . show $ length perms\n putStrLn . unwords . map (show . (+ 1)) $ perms \n\n--abdfce\n--dbdfec"}], "src_uid": "48e323edc41086cae52cc0e6bdd84e35"} {"source_code": "\n\n\nimport Data.List (isPrefixOf, isSuffixOf)\n\nsolve :: String -> String\nsolve s\n | isFreda && isRainbow = \"OMG>.< I don't know!\"\n | isFreda = \"Freda's\"\n | isRainbow = \"Rainbow's\"\n | otherwise = \"OMG>.< I don't know!\"\n where\n isFreda = isSuffixOf \"lala.\" s\n isRainbow = isPrefixOf \"miao.\" s\n\nmain :: IO ()\nmain = do\n n <- readLn\n sequence_ [getLine >>= putStrLn . solve | i <- [1..n]]", "positive_code": [{"source_code": "import Control.Monad (replicateM)\nimport Data.List\n\ndetect s \n | f1 && not f2 = \"Rainbow's\"\n | not f1 && f2 = \"Freda's\"\n | otherwise = \"OMG>.< I don't know!\"\n where\n f1 = isPrefixOf \"miao.\" s\n f2 = isSuffixOf \"lala.\" s\n\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n putStrLn $ unlines $ map detect ss\n"}, {"source_code": "import Data.List \n\nfirst s = take 5 s == \"miao.\"\nsecond s = (reverse $ take 5 $ reverse s) == \"lala.\"\n\n\nsolve s = case (first s, second s) of \n (True, False) -> \"Rainbow's\"\n (False, True) -> \"Freda's\"\n _ -> \"OMG>.< I don't know!\"\n\nmain = interact $ unlines . map solve . tail . lines"}, {"source_code": "import Control.Monad\n\nfreda s = takeLast 5 s == \"lala.\"\nrainbow s = take 5 s == \"miao.\"\n\ntakeLast n xs | length xs <= n = xs\n | otherwise = takeLast n $ tail xs\n \nparse s | freda s && rainbow s = \"OMG>.< I don't know!\"\n | freda s = \"Freda's\"\n | rainbow s = \"Rainbow's\"\n | otherwise = \"OMG>.< I don't know!\"\n \nmain = do\n n <- fmap read getLine\n ls <- forM [1..n] (\\_ -> getLine)\n mapM putStrLn . map parse $ ls\n"}, {"source_code": "import Data.List\n\nmain = interact $ unlines . map getAnswer . tail . lines \n\ngetAnswer :: String -> String\ngetAnswer s | isPrefixOf \"miao.\" s && isSuffixOf \"lala.\" s = \"OMG>.< I don't know!\"\n | isSuffixOf \"lala.\" s = \"Freda's\"\n | isPrefixOf \"miao.\" s = \"Rainbow's\"\n | otherwise = \"OMG>.< I don't know!\""}, {"source_code": "import Data.List\nmain=interact$unlines.map f.tail.lines\nf cs\n | isPrefixOf \"miao.\" cs && isSuffixOf \"lala.\" cs = \"OMG>.< I don't know!\"\n | isPrefixOf \"miao.\" cs = \"Rainbow's\"\n | isSuffixOf \"lala.\" cs = \"Freda's\"\n | otherwise = \"OMG>.< I don't know!\"\n"}, {"source_code": "readNlines :: Int -> [IO String]\nreadNlines 0 = []\nreadNlines n = getLine:(readNlines $ n-1)\n\nreadNlinesM = sequence . readNlines\nisPrefix, isSuffix :: Eq a => [a] -> [a] -> Bool\nisPrefix x y = x == take (length x) y\nisSuffix x y = lx <= ly && x == drop (ly - lx) y\n where lx = length x\n ly = length y\n\nsolve :: [String] -> String\nsolve [] = \"\"\nsolve (x:xs) = forone ++ \"\\n\" ++ (solve xs)\n where forone =\n if a && not b then \"Freda's\" else\n if b && not a then \"Rainbow's\" else \"OMG>.< I don't know!\"\n a = isSuffix \"lala.\" x\n b = isPrefix \"miao.\" x\nmain = do\n n <- getLine\n lines <- readNlinesM(read(n))\n (putStrLn . solve) lines\n"}], "negative_code": [{"source_code": "\n\n\nimport Data.List (isPrefixOf, isSuffixOf)\n\nsolve :: String -> String\nsolve s\n | isFreda && isRainbow = \" OMG>.< I don't know!\"\n | isFreda = \"Freda's\"\n | isRainbow = \"Rainbow's\"\n | otherwise = \" OMG>.< I don't know!\"\n where\n isFreda = isSuffixOf \"lala.\" s\n isRainbow = isPrefixOf \"miao.\" s\n\nmain :: IO ()\nmain = do\n n <- readLn\n sequence_ [getLine >>= putStrLn . solve | i <- [1..n]]"}, {"source_code": "import Control.Monad\n\nfreda s = takeLast 5 s == \"lala.\"\nrainbow s = take 5 s == \"miao.\"\n\ntakeLast n xs | length xs <= n = xs\n | otherwise = takeLast n $ tail xs\n \nparse s | freda s && rainbow s = \"OMG>.< I don't know!\"\n | freda s = \"Freda's\"\n | rainbow s = \"Rainbow's\"\n | otherwise = \"OMG>.< I don't know!\"\n \nmain = do\n n <- fmap read getLine\n ls <- forM [1..n] (\\_ -> getLine)\n print . unlines . map parse $ ls\n"}], "src_uid": "ee9ba877dee1a2843e885a18823cbff0"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Control.Applicative\n\ntup3 [x, y, z] = (x, y, z)\n\n\nilo (x0, y0) (x1, y1) = x0 * y1 - x1 * y0\n \n\ndifferent p0@(x0, y0) p1@(x1, y1) l@(a, b, c)\n | a == 0 = y0 `compare` (-c/b) /= y1 `compare` (-c/b)\n | b == 0 = x0 `compare` (-c/a) /= x1 `compare` (-c/a)\n | c == 0 =\n let\n qy = (c + a) / (-b)\n v0 = ilo (x0, y0) (1, qy) \n v1 = ilo (x1, y1) (1, qy) \n in v0 * v1 < 0 \n | otherwise = \n let\n px = (-c/a) -- (px, 0)\n qy = (-c/b) -- (0, qy)\n v0 = ilo (x0 - px, y0) (-px, qy)\n v1 = ilo (x1 - px, y1) (-px, qy)\n in v0 * v1 < 0 \n\n\nval True = 1\nval False = 0\n\nmain = do\n [x0, y0]::[Double] <- map read . words <$> getLine\n [x1, y1]::[Double] <- map read . words <$> getLine\n n::Int <- read <$> getLine \n ps::[(Double, Double, Double)] <- forM [1..n] $ \\_ -> (tup3 . map read . words <$> getLine)\n print . sum $ map (val . different (x0, y0) (x1, y1)) ps \n", "positive_code": [{"source_code": "main = print . solve . map read . words =<< getContents\nsign a x b y c = a * x + b * y + c > 0\nsolve (x1:y1:x2:y2:n:lines) = solve' lines\n where\n solve' [] = 0\n solve' (a:b:c:s) | (sign a x1 b y1 c) /= (sign a x2 b y2 c) = 1 + (solve' s)\n | otherwise = solve' s\n"}, {"source_code": "main = do\n [x1, y1] <- getLine >>= return. map read. words :: IO [Integer]\n [x2, y2] <- getLine >>= return. map read. words :: IO [Integer]\n getLine\n allroad <- getContents >>= return. map (map read. words). lines :: IO [[Integer]]\n print. length. filter (\\[a, b, c] -> (a * x1 + b * y1 + c) * (a * x2 + b * y2 + c) < 0) $ allroad\n"}, {"source_code": "import Control.Monad\n-- import Debug.Trace\nimport Data.List\n\nmain :: IO ()\nmain = do\n [hx, hy, ux, uy] <- map (read :: String -> Integer) . words . unwords <$> replicateM 2 getLine \n n <- (read :: String -> Int) <$> getLine\n let cond (a, b, c) = signum (a * hx + b * hy + c) * signum (a * ux + b * uy + c) < 0\n print =<< sum . map (fromEnum . cond . (\\[a,b,c]->(a,b,c)) . map (read :: String -> Integer) . words) <$> replicateM n getLine\n"}, {"source_code": "import Control.Monad\nreadWords::Read a=>IO[a]\nreadWords = fmap (map read.words) getLine\n\nside [a,b,c] [x,y] = signum $ a*x + b*y + c\nintersects::(Num a,Eq a)=>[[a]]->[a]->Bool\nintersects segment line = foldl1 (*) (map (side line) segment) == -1\n\ncount = (length.).filter\n\nmain = do\n way <- replicateM 2 readWords\n n <- readLn\n lines <- replicateM n readWords\n print$ count (intersects way) lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Function\nimport Data.Maybe\nimport Data.Int\n\nmain :: IO ()\nmain = do\n x1y1 <- readIntsIO\n x2y2 <- readIntsIO\n [n] <- readIntsIO\n abcs <- replicateM n readIntsIO\n print $ solve x1y1 x2y2 abcs\n\nsolve :: [Int] -> [Int] -> [[Int]] -> Int\nsolve x1y1 x2y2 abcs = ncross\n where\n f :: [Int] -> [Int] -> Int64\n f xy1 abc = sum $ zipWith ((*) `on` fromIntegral) xy1 abc\n nx1y1 = map (f (x1y1++[1])) abcs\n nx2y2 = map (f (x2y2++[1])) abcs\n ncross = length $ filter (0 >) $ zipWith ((*) `on` signum) nx1y1 nx2y2\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n"}, {"source_code": "\nmain = do\n contents <- getContents\n let allLines = lines contents\n let pointHome = lineToPoint $ allLines !! 0\n let pointUniversity = lineToPoint $ allLines !! 1\n\n putStrLn $ show\n $ length\n $ filter (\\x -> x == True)\n $ map ((isDividedByLine pointHome pointUniversity) . lineToCoefficient)\n $ drop 3 allLines\n\nlineToPoint :: String -> (Float, Float)\nlineToPoint line = (intsInLine !! 0, intsInLine !! 1)\n where intsInLine = map read $ words line\n\nlineToCoefficient :: String -> (Float, Float, Float)\nlineToCoefficient line = (intsInLine !! 0, intsInLine !! 1, intsInLine !! 2)\n where intsInLine = map read $ words line\n\nstandardToPointSlope :: (Float, Float, Float) -> (Float, Float)\nstandardToPointSlope (cx, cy, c) = (\n (-1.0 * (cx / cy)),\n (-1.0 * (c / cy))\n )\n\ngetInterceptBySlope :: (Float, Float) -> Float -> Float\ngetInterceptBySlope (x, y) slope = y - slope * x \n\nisDividedByLine :: (Float, Float) -> (Float, Float) -> (Float, Float, Float) -> Bool\nisDividedByLine (x0, y0) (x1, y1) (cx, cy, c) \n | cx == 0 = (0 >= ((y0 - m0) * (y1 - m0)))\n | cy == 0 = (0 >= ((x0 - m1) * (x1 - m1)))\n | otherwise = \n 0 >= (getInterceptBySlope (x0, y0) slope - intercept) * (getInterceptBySlope (x1, y1) slope - intercept)\n where\n m0 = -1.0 * c / cy\n m1 = -1.0 * c / cx\n (slope, intercept) = standardToPointSlope (cx, cy, c)\n"}, {"source_code": "\nmain = do\n contents <- getContents\n let allLines = lines contents\n let pointHome = lineToPoint $ allLines !! 0\n let pointUniversity = lineToPoint $ allLines !! 1\n\n putStrLn $ show\n $ length\n $ filter (\\x -> x == True)\n $ map ((calculateIsLineCrossing pointHome pointUniversity) . lineToCoefficient)\n $ drop 3 allLines\n\nlineToPoint :: String -> (Float, Float)\nlineToPoint line = (intsInLine !! 0, intsInLine !! 1)\n where intsInLine = map read $ words line\n\nlineToCoefficient :: String -> (Float, Float, Float)\nlineToCoefficient line = (intsInLine !! 0, intsInLine !! 1, intsInLine !! 2)\n where intsInLine = map read $ words line\n\ncalculateParallelLineMByK :: (Float, Float) -> Float -> Float\ncalculateParallelLineMByK (x, y) k = y - k * x\n\ncalculateIsLineCrossing :: (Float, Float) -> (Float, Float) -> (Float, Float, Float) -> Bool\ncalculateIsLineCrossing (x0, y0) (x1, y1) (cx, cy, c)\n | cx == 0 = (0 >= ((y0 - m0) * (y1 - m0)))\n | cy == 0 = (0 >= ((x0 - m1) * (x1 - m1)))\n | otherwise = \n 0 >= (calculateParallelLineMByK (x0, y0) k - m) * (calculateParallelLineMByK (x1, y1) k - m)\n where\n m0 = -1.0 * c / cy\n m1 = -1.0 * c / cx\n (k, m) = coefficientToKM (cx, cy, c)\n \ncoefficientToKM :: (Float, Float, Float) -> (Float, Float)\ncoefficientToKM (cx, cy, c) = (-1.0 * (cx / cy), -1.0 * (c / cy))\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n [hx, hy] <- map (read :: String -> Int) . words <$> getLine\n [ux, uy] <- map (read :: String -> Int) . words <$> getLine\n n <- (read :: String -> Int) <$> getLine \n let cond (a, b, c) = compare (a * hx + b * hy + c) 0 /= compare (a * ux + b * uy + c) 0\n print =<< sum . map (fromEnum . cond . (\\[a,b,c]->(a,b,c)) . map (read :: String -> Int) . words) <$> replicateM n getLine\n"}, {"source_code": "import Control.Monad\n-- import Debug.Trace\nimport Data.List\n\nmain :: IO ()\nmain = do\n [hx, hy, ux, uy, n] <- map (read :: String -> Int) . words . unwords <$> replicateM 3 getLine \n let cond (a, b, c) = signum (a * hx + b * hy + c) * signum (a * ux + b * uy + c) < 0\n print =<< sum . map (fromEnum . cond . (\\[a,b,c]->(a,b,c)) . map (read :: String -> Int) . words) <$> replicateM n getLine\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n [hx, hy] <- map (read :: String -> Int) . words <$> getLine\n [ux, uy] <- map (read :: String -> Int) . words <$> getLine\n n <- (read :: String -> Int) <$> getLine \n let cond (a, b, c) = (a * hx + b * hy + c) * (a * ux + b * uy + c) < 0\n print =<< sum . map (fromEnum . cond . (\\[a,b,c]->(a,b,c)) . map (read :: String -> Int) . words) <$> replicateM n getLine\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Control.Applicative\n\ntup3 [x, y, z] = (x, y, z)\n\n\nilo (x0, y0) (x1, y1) = x0 * y1 - x1 * y0\n \n\ndifferent p0@(x0, y0) p1@(x1, y1) l@(a, b, c)\n | a == 0 = x0 `compare` (-c/b) /= x1 `compare` (-c/b)\n | b == 0 = y0 `compare` (-c/a) /= y1 `compare` (-c/a)\n | c == 0 =\n let\n qy = (c + a) / (-b)\n v0 = ilo (x0, y0) (1, qy) \n v1 = ilo (x1, y1) (1, qy) \n in v0 * v1 < 0 \n | otherwise = \n let\n px = (-c/a) -- (px, 0)\n qy = (-c/b) -- (0, qy)\n v0 = ilo (x0 - px, y0) (-px, qy)\n v1 = ilo (x1 - px, y1) (-px, qy)\n in v0 * v1 < 0 \n\n\nval True = 1\nval False = 0\n\nmain = do\n [x0, y0]::[Double] <- map read . words <$> getLine\n [x1, y1]::[Double] <- map read . words <$> getLine\n n::Int <- read <$> getLine \n ps::[(Double, Double, Double)] <- forM [1..n] $ \\_ -> (tup3 . map read . words <$> getLine)\n print . sum $ map (val . different (x0, y0) (x1, y1)) ps \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\n\nmain :: IO ()\nmain = do\n [x1, y1] <- readIntsIO\n [x2, y2] <- readIntsIO\n [n] <- readIntsIO\n abcs <- replicateM n readIntsIO\n print $ solve (x1, y1) (x2, y2) abcs\n\nsolve :: (Int, Int) -> (Int, Int)-> [[Int]] -> Int\nsolve x1y1 x2y2 abcs = ncross\n where\n f (x, y) [a, b, c] = a * x + b * y + c\n nx1y1 = map (f x1y1) abcs\n nx2y2 = map (f x2y2) abcs\n ncross = length $ filter (0 >) $ zipWith (*) nx1y1 nx2y2\n \nreadIntsIO :: IO [Int]\nreadIntsIO = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n"}, {"source_code": "\nmain = do\n contents <- getContents\n let allLines = lines contents\n let pointHome = lineToPoint $ allLines !! 0\n let pointUniversity = lineToPoint $ allLines !! 1\n\n putStrLn $ show\n $ length\n $ filter (\\x -> x == True)\n $ map ((calculateIsLineCrossing pointHome pointUniversity) . lineToCoefficient)\n $ drop 3 allLines\n\nlineToPoint :: String -> (Int, Int)\nlineToPoint line = (intsInLine !! 0, intsInLine !! 1)\n where intsInLine = map read $ words line\n\nlineToCoefficient :: String -> (Int, Int, Int)\nlineToCoefficient line = (intsInLine !! 0, intsInLine !! 1, intsInLine !! 2)\n where intsInLine = map read $ words line\n\ncalculateIsLineCrossing :: (Int, Int) -> (Int, Int) -> (Int, Int, Int) -> Bool\ncalculateIsLineCrossing point0 point1 coefficients =\n 0 >= (applyLineEquation point0 coefficients * applyLineEquation point1 coefficients)\n\napplyLineEquation :: (Int, Int) -> (Int, Int, Int) -> Int\napplyLineEquation (x, y) (cx, cy, c) = x * cx + y * cy + c\n"}], "src_uid": "783df1df183bf182bf9acbb99208cdb7"} {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (catch)\n\neps :: Double\neps = 1e-11\n\ntype Coord = Double\ntype Velocity = Double\ntype Time = Double\ntype Coords = (Coord, Coord, Coord)\ntype Harry = (Velocity, Coords)\ntype Segment = (Coords, Coords)\n\ndistance :: Coords -> Coords -> Double\ndistance (x1, y1, z1) (x2, y2, z2)\n = sqrt $ sum $ map (^2) $ zipWith (-) [x1, y1, z1] [x2, y2, z2]\n\ncatch :: Velocity -> Time -> Segment -> Velocity -> Coords -> Bool\ncatch vS time (a, b) vP pP = timeS + eps > timeP\n where\n timeS = time + (distance a b) / vS\n timeP = (distance pP b) / vP\n\nsolve :: Velocity -> [Coords] -> Velocity -> Coords -> Maybe (Time, Coords)\nsolve vS (p0 : psS) vP pP\n | distance pP p0 < eps = Just (0, pP)\n | otherwise = solve' 0 (p0 : psS)\n where\n solve' time (a : b : psS)\n | catch vS time (a, b) vP pP = solve'' time (a, b)\n | otherwise = solve' (time + (distance a b) / vS) (b : psS)\n solve' _ _ = Nothing\n solve'' time (a, b)\n | distance a b < eps = Just (time, a)\n | catch vS time (a, m) vP pP = solve'' time (a, m)\n | otherwise = solve'' (time + (distance a m) / vS) (m, b)\n where\n m = (\\(x1, y1, z1) (x2, y2, z2) -> (0.5 * (x1 + x2), 0.5 * (y1 + y2), 0.5 * (z1 + z2))) a b\n\nparseCoords :: String -> Coords\nparseCoords line = case map read (words line) of\n [x, y, z] -> (x, y, z)\n\nmain :: IO()\nmain = do\n ls <- liftM lines getContents\n let n = read $ head ls\n let psS = map parseCoords . take (n + 1) . tail $ ls\n let [vP, vS] = map read . words . (!! (n + 2)) $ ls\n let pP = parseCoords . (!! (n + 3)) $ ls\n case solve vS psS vP pP of\n Just (time, (x, y, z)) -> putStrLn \"YES\" >> print time >> putStrLn (concat [show x, \" \", show y, \" \", show z])\n Nothing -> putStrLn \"NO\"\n", "positive_code": [{"source_code": "import IO\nimport Text.Printf\n\ntoList (a, b, c) = a:b:c:[] \nfList (a:b:c:_) = (a, b, c)\n\ndelta :: (Double, Double, Double) -> (Double, Double, Double) -> Double\ndelta (x1, y1, z1) (x2, y2, z2) = sqrt ((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)\n\ndeltaPlus :: (Double, Double, Double) -> (Double, Double, Double) -> Double -> (Double, Double, Double)\ndeltaPlus (x1, y1, z1) (x2, y2, z2) r =\n let (dx, dy, dz) = (x2 - x1, y2 - y1, z2 - z1)\n in (x1 + dx*r, y1 + dy*r, z1 + dz*r)\n\ncoord = do \n line <- getLine\n --putStrLn (\">\" ++ (show (words line)))\n return (fList (map (read :: String -> Double) (words line)))\n \n\nmakeList 0 _ _ = return []\nmakeList n a p = do\n c <- coord\n other <- makeList (n-1) (a + delta c p) c\n return ((c, a + delta c p, delta c p):other) \n\n\nbinSearch :: (Double -> (Int, a)) -> Double -> Double -> IO (Double, a)\nbinSearch f min max | max == min = error (\"bin search: min == max\")\nbinSearch f min max | otherwise = do\n --putStrLn (show (min, max, (max+min)/2))\n case (f ((max+min)/2)) of\n (-1, _) -> binSearch f min ((max + min)/2)\n (0, cx) -> return ((max + min)/2, cx)\n (1, _) -> binSearch f ((max + min)/2) max\n\nbsf c0 c1 vp vc p t0 t = \n let d = delta c0 c1\n cx = deltaPlus c0 c1 ((t - t0) / (d/vc))\n tn = (delta cx p) / vp\n in if (abs (tn - t)) < ((0.1)^(11)) \n then (0, cx)\n else if (tn - t) < 0\n then (-1, cx)\n else (1, cx)\n\nff (c:[]) _ _ _ = return Nothing\nff ((c0, preLen, _):cc@(c1, preLen1, len):cs) vp vc p = \n if ((preLen1 / vc) - ((delta p c1) / vp)) >= -((0.1)^(11))\n then do r <- (binSearch (bsf c0 c1 vp vc p (preLen/vc)) (preLen/vc) (preLen1/vc))\n return (Just r)\n else ff (cc:cs) vp vc p\n\n\nmain = do \n n <- (getLine >>= return . read) :: IO Int\n c0 <- coord\n c <- makeList n 0 c0\n l <- getLine\n let (l1:l2:ll) = words l \n ivp = read l1 :: Int\n ivc = read l2 :: Int\n vp = realToFrac ivp\n vc = realToFrac ivc\n p <- coord\n a <- ff ((c0, 0, 0):c) vp vc p\n p <- if (a == Nothing)\n then putStrLn \"NO\"\n else let (Just (t, (x, y, z))) = a\n in printf \"YES\\n%.10f\\n%.10f %.10f %.10f\" t x y z\n return (0)\n \n \n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (catch)\n\neps :: Double\neps = 1e-10\n\ntype Coord = Double\ntype Velocity = Double\ntype Time = Double\ntype Coords = (Coord, Coord, Coord)\ntype Harry = (Velocity, Coords)\ntype Segment = (Coords, Coords)\n\ndistance :: Coords -> Coords -> Double\ndistance (x1, y1, z1) (x2, y2, z2)\n = sqrt $ sum $ map (^2) $ zipWith (-) [x1, y1, z1] [x2, y2, z2]\n\ncatch :: Velocity -> Time -> Segment -> Velocity -> Coords -> Bool\ncatch vS time (a, b) vP pP = timeS + eps > timeP\n where\n timeS = time + (distance a b) / vS\n timeP = (distance pP b) / vP\n\nsolve :: Velocity -> [Coords] -> Velocity -> Coords -> Maybe (Time, Coords)\nsolve vS (p0 : psS) vP pP\n | distance pP p0 < eps = Just (0, pP)\n | otherwise = solve' 0 (p0 : psS)\n where\n solve' time (a : b : psS)\n | catch vS time (a, b) vP pP = solve'' time (a, b)\n | otherwise = solve' (time + (distance a b) / vS) (b : psS)\n solve' _ _ = Nothing\n solve'' time (a, b)\n | distance a b < 0.5 * eps = Just (time, a)\n | catch vS time (a, m) vP pP = solve'' time (a, m)\n | otherwise = solve'' (time + (distance a m) / vS) (m, b)\n where\n m = (\\(x1, y1, z1) (x2, y2, z2) -> (0.5 * (x1 + x2), 0.5 * (y1 + y2), 0.5 * (z1 + z2))) a b\n\nparseCoords :: String -> Coords\nparseCoords line = case map read (words line) of\n [x, y, z] -> (x, y, z)\n\nmain :: IO()\nmain = do\n ls <- liftM lines getContents\n let n = read $ head ls\n let psS = map parseCoords . take (n + 1) . tail $ ls\n let [vP, vS] = map read . words . (!! (n + 2)) $ ls\n let pP = parseCoords . (!! (n + 3)) $ ls\n case solve vS psS vP pP of\n Just (time, (x, y, z)) -> putStrLn \"YES\" >> print time >> putStrLn (concat [show x, \" \", show y, \" \", show z])\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "import IO\nimport Text.Printf\n\ntoList (a, b, c) = a:b:c:[] \nfList (a:b:c:_) = (a, b, c)\n\ndelta :: (Double, Double, Double) -> (Double, Double, Double) -> Double\ndelta (x1, y1, z1) (x2, y2, z2) = sqrt ((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)\n\ndeltaPlus :: (Double, Double, Double) -> (Double, Double, Double) -> Double -> (Double, Double, Double)\ndeltaPlus (x1, y1, z1) (x2, y2, z2) r =\n let (dx, dy, dz) = (x2 - x1, y2 - y1, z2 - z1)\n in (x1 + dx*r, y1 + dy*r, z1 + dz*r)\n\ncoord = do \n line <- getLine\n --putStrLn (\">\" ++ (show (words line)))\n return (fList (map (read :: String -> Double) (words line)))\n \n\nmakeList 0 _ _ = return []\nmakeList n a p = do\n c <- coord\n other <- makeList (n-1) (a + delta c p) c\n return ((c, a + delta c p, delta c p):other) \n\n\nbinSearch :: (Double -> (Int, a)) -> Double -> Double -> IO (Double, a)\nbinSearch f min max | max == min = error (\"bin search: min == max\")\nbinSearch f min max | otherwise = do\n --putStrLn (show (min, max, (max+min)/2))\n case (f ((max+min)/2)) of\n (-1, _) -> binSearch f min ((max + min)/2)\n (0, cx) -> return ((max + min)/2, cx)\n (1, _) -> binSearch f ((max + min)/2) max\n\nbsf c0 c1 vp vc p t0 t = \n let d = delta c0 c1\n cx = deltaPlus c0 c1 ((t - t0) / (d/vc))\n tn = (delta cx p) / vp\n in if (abs (tn - t)) < ((0.1)^(7)) \n then (0, cx)\n else if (tn - t) < 0\n then (-1, cx)\n else (1, cx)\n\nff (c:[]) _ _ _ = return Nothing\nff ((c0, preLen, _):cc@(c1, preLen1, len):cs) vp vc p = --do\n --putStrLn (show cc)\n if ((preLen1 / vc) >= ((delta p c1) / vp))\n then do r <- (binSearch (bsf c0 c1 vp vc p (preLen/vc)) (preLen/vc) (preLen1/vc))\n return (Just r)\n else ff (cc:cs) vp vc p\n \n\np1 (Just (t, (x, y, z))) = \"YES2\\n\" ++ \n (\n showsPrec 6 t (\"\\n\" ++ \n showsPrec 6 x (\" \" ++ \n showsPrec 6 y (\" \" ++ \n showsPrec 6 z \"\")))\n )\n \np2 (Just (t, (x, y, z))) = \"YES\\n\" ++ (show t) ++ \n \"\\n\" ++ (show x) ++ \" \" ++\n (show y) ++ \" \" ++ (show z)\n\nmain = do \n-- putStrLn \">0\"\n n <- (getLine >>= return . read) :: IO Int\n-- putStrLn \">1\"\n c0 <- coord\n-- putStrLn \">2\" \n c <- makeList n 0 c0\n-- putStrLn \">3\" \n l <- getLine\n let (l1:l2:ll) = words l \n ivp = read l1 :: Int\n ivc = read l2 :: Int\n vp = realToFrac ivp\n vc = realToFrac ivc\n-- putStrLn \">4\" \n p <- coord\n-- putStrLn \">end\" \n a <- ff ((c0, 0, 0):c) vp vc p\n-- putStrLn \">c\"\n p <- if (a == Nothing)\n then putStrLn \"NO\"\n else let (Just (t, (x, y, z))) = a\n in printf \"YES\\n%.6f\\n%.6f %.6f %.6f\" t x y z\n return (0)\n \n \n"}, {"source_code": "import IO\nimport Text.Printf\n\ntoList (a, b, c) = a:b:c:[] \nfList (a:b:c:_) = (a, b, c)\n\ndelta :: (Double, Double, Double) -> (Double, Double, Double) -> Double\ndelta (x1, y1, z1) (x2, y2, z2) = sqrt ((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)\n\ndeltaPlus :: (Double, Double, Double) -> (Double, Double, Double) -> Double -> (Double, Double, Double)\ndeltaPlus (x1, y1, z1) (x2, y2, z2) r =\n let (dx, dy, dz) = (x2 - x1, y2 - y1, z2 - z1)\n in (x1 + dx*r, y1 + dy*r, z1 + dz*r)\n\ncoord = do \n line <- getLine\n --putStrLn (\">\" ++ (show (words line)))\n return (fList (map (read :: String -> Double) (words line)))\n \n\nmakeList 0 _ _ = return []\nmakeList n a p = do\n c <- coord\n other <- makeList (n-1) (a + delta c p) c\n return ((c, a + delta c p, delta c p):other) \n\n\nbinSearch :: (Double -> (Int, a)) -> Double -> Double -> IO (Double, a)\nbinSearch f min max | max == min = error (\"bin search: min == max\")\nbinSearch f min max | otherwise = do\n --putStrLn (show (min, max, (max+min)/2))\n case (f ((max+min)/2)) of\n (-1, _) -> binSearch f min ((max + min)/2)\n (0, cx) -> return ((max + min)/2, cx)\n (1, _) -> binSearch f ((max + min)/2) max\n\nbsf c0 c1 vp vc p t0 t = \n let d = delta c0 c1\n cx = deltaPlus c0 c1 ((t - t0) / (d/vc))\n tn = (delta cx p) / vp\n in if (abs (tn - t)) < ((0.1)^(9)) \n then (0, cx)\n else if (tn - t) < 0\n then (-1, cx)\n else (1, cx)\n\nff (c:[]) _ _ _ = return Nothing\nff ((c0, preLen, _):cc@(c1, preLen1, len):cs) vp vc p = \n if ((preLen1 / vc) - ((delta p c1) / vp)) >= -((0.1)^(7))\n then do r <- (binSearch (bsf c0 c1 vp vc p (preLen/vc)) (preLen/vc) (preLen1/vc))\n return (Just r)\n else ff (cc:cs) vp vc p\n\n\nmain = do \n n <- (getLine >>= return . read) :: IO Int\n c0 <- coord\n c <- makeList n 0 c0\n l <- getLine\n let (l1:l2:ll) = words l \n ivp = read l1 :: Int\n ivc = read l2 :: Int\n vp = realToFrac ivp\n vc = realToFrac ivc\n p <- coord\n a <- ff ((c0, 0, 0):c) vp vc p\n p <- if (a == Nothing)\n then putStrLn \"NO\"\n else let (Just (t, (x, y, z))) = a\n in printf \"YES\\n%.7f\\n%.7f %.7f %.7f\" t x y z\n return (0)\n \n \n"}], "src_uid": "6e2a8aa58ed8cd308cb482e4c24cbbbb"} {"source_code": "import Data.List\n\n\ndivNum :: Integer -> Integer -> Integer\ndivNum 0 _ = 0\ndivNum n k = mod n k + 1 + divNum (div n k) k\n\nsolve :: [Integer] -> String\nsolve [n, k] = show ((divNum n k) - 1)\n\nmain = interact $ intercalate \"\\n\" . map solve . map (map (\\x -> read x :: Integer) . words) . tail . lines\n", "positive_code": [{"source_code": "import Data.Int\nmain = interact $ unlines . map (show . solve) . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve (0,_) = 0\nsolve (n,k) | n `mod` k == 0 = 1 + solve (n `div` k,k)\n | otherwise = n `mod` k + solve (n - n`mod` k,k)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, k] <- map read.words <$> getLine\n print $ solve n k\n\nsolve :: Integer -> Integer -> Integer\nsolve n k = go 0 n\n where\n go !res x\n | x == 0 = res\n | r == 0 = go (res + 1) (quot x k)\n | otherwise = go (res + r) (x - r)\n where\n !r = rem x k"}, {"source_code": "\nmodule Main where\n\nimport Control.Monad\nimport System.IO\nimport Data.Char\nimport Data.Array\nimport qualified Data.Map as Map\nimport Data.List\n\nisDivisible :: Integer -> Integer -> Bool\nisDivisible a b\n | b == 0 = False\n | a < b = False\n | (a `mod` b) == 0 = True\n | otherwise = False\n\nstepsToZero :: Integer -> Integer -> Integer -> Integer\nstepsToZero k n count\n | n == 0 = count\n | otherwise =\n if isDivisible n k\n then stepsToZero k (n `div` k) (count + 1)\n else\n let delta = n `mod` k\n in stepsToZero k (n - delta) (count + delta)\n\n\nmain :: IO()\nmain = do\n\n q <- readLn :: IO Int\n forM_ [1..q] $ \\q_itr -> do\n s <- getLine\n let ws = words s\n let nums = map read ws :: [Integer]\n let (n:k:_) = nums\n\n let result = stepsToZero k n 0\n putStrLn $ show result\n"}], "negative_code": [{"source_code": "import Data.List\n\n\ndivNum :: Integer -> Integer -> Integer\ndivNum 0 _ = 0\ndivNum n k = mod n k + 1 + divNum (div n k) k\n\nsolve :: [Integer] -> String\nsolve [n, k] = show (divNum n $ k - 1)\n\nmain = interact $ intercalate \"\\n\" . map solve . map (map (\\x -> read x :: Integer) . words) . tail . lines\n"}], "src_uid": "00b1e45e9395d23e850ce1a0751b8378"} {"source_code": "solve :: Integer -> Bool\nsolve n = elem 90 $ map (\\k -> mod (k*180 - ((k*360) `div` n)) 180) $ map (\\q -> q*n `div` 360) $ filter (\\q -> (mod (q * n) (360)) == 0) [1..359]\n--solve n = elem 0 $ map (`mod` 4) [n, 2*n, 3*n]\n{--solve n = let ks = [(ceiling (4 / fromIntegral(n)))..(floor (4- (4 / fromIntegral(n))))] in\n elem 0 $ map (\\x -> (x*n) `mod` 4) ks--}\n--solve n = 0 `elem` map (\\x -> (4*x) `mod` n) [1..(n-1)]\n--solve n = elem 0 (map (`mod` n) (map (*4) ([1..(n-1)])))\n\ngetInt::IO Integer\ngetInt=do\n line <- getLine\n let i = read line :: Integer\n return (i)\n\nmain::IO()\nmain=do\n t <- getInt\n for t where\n for 0 = return ()\n for t = do\n n <- getInt\n if solve n then putStrLn \"YES\" else putStrLn \"NO\"\n for (t-1)", "positive_code": [{"source_code": "module Main where\n\nmain = interact $ unlines . map (\\x -> if (read x :: Int) `mod` 4 == 0 then \"YES\" else \"NO\" ) . tail . lines "}, {"source_code": "repeatNTimes 0 _ = return ()\nrepeatNTimes n action =\n do\n action\n repeatNTimes (n-1) action\n \nmain = do\n input1 <- getLine\n let t = read input1 :: Int\n\n --main cycle\n repeatNTimes t (do\n input2 <- getLine\n let n = read input2 :: Int\n\n if mod n 4 == 0 then putStrLn \"YES\" else putStrLn \"NO\" \n )"}, {"source_code": "import Control.Monad (replicateM_)\nmain = readLn >>= flip replicateM_ (readLn >>= putStrLn . f) where\n f x | x `mod` 4 == 0 = \"YES\"\n f _ = \"NO\"\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Tuple\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nmain = do\n input <- getContents\n let _:tokens = read <$> split input :: [Integer]\n res = tokens |> unfoldr (\\case\n [] -> Nothing\n n:rest -> Just (ans, rest) where\n ans = if subres then \"YES\" else \"NO\"\n subres = (90*n `mod` 360 == 0)\n )\n sequence_ $ putStrLn <$> res\n"}, {"source_code": "solve :: Integer -> String\nsolve n= if mod n 4 == 0 then \"YES\" else \"NO\"\n \n\n\nparse :: String -> Integer\nparse = read\n\n\n\n------------------------------\n\nsolveCase :: Int -> IO()\nsolveCase 0 = return ()\nsolveCase t = do\n test <- getLine\n putStrLn . solve . parse $ test\n solveCase (t-1)\n\ngetInt :: IO Int\ngetInt = fmap read getLine \n\nmain :: IO()\nmain = do\n n <- getInt\n solveCase n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess a | mod a 4 ==0 = \"YES\"\n\t | otherwise = \"NO\"\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ta<- map read <$> replicateM n getLine ::IO [Int]\n\t\tmapM_ putStrLn $ map process a\n\n"}, {"source_code": "main = interact $ unlines . map process . map read . tail . lines\nprocess x \n | mod x 4 == 0 = \"YES\"\n | otherwise = \"NO\" \n"}, {"source_code": "solve :: String -> String\nsolve s\n | mod (read s) 4 == 0 = \"YES\"\n | otherwise = \"No\" \n\nio :: String -> String\nio s = unlines $ map solve $ drop 1 $ lines s\n\nmain :: IO ()\nmain = do\n interact io"}], "negative_code": [{"source_code": "solve :: Int -> Bool\nsolve n = let ks = [(ceiling (4 / fromIntegral(n)))..(floor (4- (4 / fromIntegral(n))))] in\n elem 0 $ map (\\x -> (x*n) `mod` 4) ks\n--solve n = 0 `elem` map (\\x -> (4*x) `mod` n) [1..(n-1)]\n--solve n = elem 0 (map (`mod` n) (map (*4) ([1..(n-1)])))\n\ngetInt::IO Int\ngetInt=do\n line <- getLine\n let i = read line :: Int\n return (i)\n\nmain::IO()\nmain=do\n t <- getInt\n for t where\n for 0 = return ()\n for t = do\n n <- getInt\n if solve n then putStrLn \"YES\" else putStrLn \"NO\"\n for (t-1)"}, {"source_code": "getInt::IO Int\ngetInt=do\n line <- getLine\n let i = read line :: Int\n return (i)\n\nmain::IO()\nmain=do\n t <- getInt\n for t where\n for 0 = return ()\n for t = do\n n <- getInt\n if n `mod` 2 == 0 then putStrLn \"YES\" else putStrLn \"NO\"\n for (t-1)"}, {"source_code": "solve :: Int -> Bool\nsolve n = elem 90 $ map (\\k -> mod (k*180 - ((k*360) `div` n)) 180) $ map (\\q -> q*n `div` 360) $ filter (\\q -> (mod (q * n) (360)) == 0) [1..359]\n--solve n = elem 0 $ map (`mod` 4) [n, 2*n, 3*n]\n{--solve n = let ks = [(ceiling (4 / fromIntegral(n)))..(floor (4- (4 / fromIntegral(n))))] in\n elem 0 $ map (\\x -> (x*n) `mod` 4) ks--}\n--solve n = 0 `elem` map (\\x -> (4*x) `mod` n) [1..(n-1)]\n--solve n = elem 0 (map (`mod` n) (map (*4) ([1..(n-1)])))\n\ngetInt::IO Int\ngetInt=do\n line <- getLine\n let i = read line :: Int\n return (i)\n\nmain::IO()\nmain=do\n t <- getInt\n for t where\n for 0 = return ()\n for t = do\n n <- getInt\n if solve n then putStrLn \"YES\" else putStrLn \"NO\"\n for (t-1)"}, {"source_code": "module Main where\n\nmain = interact $ unlines . map (\\x -> let v = 90 / (360 / (read x :: Double) ) in if (v - (fromIntegral $ floor v )) == 0.0 then \"YES\" else \"NO\" ) . tail . lines "}, {"source_code": "module Main where\n\nmain = interact $ unlines . map (\\x -> let v = map (/ (360 / (read x :: Double))) [90,270] in if (any (==0.0) $ zipWith (-) v $ map (fromIntegral .floor) v ) then \"YES\" else \"NO\" ) . tail . lines "}, {"source_code": "solve :: Integer -> String\nsolve n= if mod n 2 == 0 then \"YES\" else \"NO\"\n \n\n\nparse :: String -> Integer\nparse = read\n\n\n\n------------------------------\n\nsolveCase :: Int -> IO()\nsolveCase 0 = return ()\nsolveCase t = do\n test <- getLine\n putStrLn . show . solve . parse $ test\n solveCase (t-1)\n\ngetInt :: IO Int\ngetInt = fmap read getLine \n\nmain :: IO()\nmain = do\n n <- getInt\n solveCase n\n"}, {"source_code": "solve :: Integer -> String\nsolve n= if mod n 2 == 0 then \"YES\" else \"NO\"\n \n\n\nparse :: String -> Integer\nparse = read\n\n\n\n------------------------------\n\nsolveCase :: Int -> IO()\nsolveCase 0 = return ()\nsolveCase t = do\n test <- getLine\n putStrLn . solve . parse $ test\n solveCase (t-1)\n\ngetInt :: IO Int\ngetInt = fmap read getLine \n\nmain :: IO()\nmain = do\n n <- getInt\n solveCase n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess a | div a 4 ==0 = \"YES\"\n\t | otherwise = \"NO\"\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ta<- map read <$> replicateM n getLine ::IO [Int]\n\t\tmapM_ putStrLn $ map process a\n\n"}], "src_uid": "07e56d4031bcb119d2f684203f7ed133"} {"source_code": "main = do\n n <- getLine\n xs <- (map read . words) `fmap` getLine :: IO [Int]\n print $ (length . filter localExtrema) (zip3 xs (tail xs) (tail (tail xs)))\n\nlocalExtrema (x,y,z) = (x < y && y > z) || (x > y && y < z)", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\n\nprocess n [a] = n\nprocess n [a,b] = n\nprocess n (a:b:c:ds) | ab && c>b = process (n+1) (b:c:ds)\n\t\t | otherwise = process n (b:c:ds)\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ts<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ process 0 s\n\n"}, {"source_code": "module Main where\nmain = getContents >>= print . exec\nexec = solve . tail . map read . words\nsolve [_] = 0\nsolve [_, _] = 0\nsolve xs = sum $ zipWith3 (\\a b c -> fromEnum $ (a < b && b > c) || (a > b && b < c)) xs (tail xs :: [Int]) (tail $ tail xs)"}, {"source_code": "solve :: [Int] -> [Int]\nsolve (x:y:z:xs)\n | y < x && y < z || y > x && y > z = y : (solve (y:z:xs))\n | otherwise = solve (y:z:xs)\nsolve _ = []\n\nmain = do\n getLine\n getContents >>= print.length.solve.(map read).words"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n\n localExtreme :: (Int, Int, Int) -> Bool\n localExtreme (a, b, c)\n | a < b && b > c = True\n | a > b && b < c = True\n | otherwise = False\n\n reduceExtreme :: Int -> [Int] -> Int\n reduceExtreme i (a:b:c:xs)\n | localExtreme (a, b, c) = reduceExtreme (i + 1) (b:c:xs)\n | otherwise = reduceExtreme i (b:c:xs)\n reduceExtreme i (b:c:[]) = i\n reduceExtreme i (c:[]) = i\n reduceExtreme i [] = i\n\n test :: IO()\n test = do\n let xs = []\n print $ reduceExtreme 0 xs\n\n main :: IO()\n main = do\n n <- getLine\n xs <- getLine >>= return . (map readInt) . words\n print $ reduceExtreme 0 xs\n\n\n"}], "negative_code": [{"source_code": "solve :: [Int] -> [Int]\nsolve (x:y:z:xs)\n | y < x && y < z || y > x && y > z = y : (solve (y:z:xs))\n | otherwise = solve (z:xs)\nsolve _ = []\n\nmain = do\n getLine\n getContents >>= print.length.solve.(map read).words"}], "src_uid": "67cf9f83ed791a614bd01c5e0310813f"} {"source_code": "--216C\n\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [Int]\nsolve [n, m, 1] = [1, n .. n + m]\nsolve [n, m, k] = \n replicate k 1\n ++\n (takeWhile (<= (n + m)) $ concatMap (\\i -> i : replicate (k-1) (i+1)) [n, 2*n ..])\n\nprints :: Show a => [a] -> IO ()\nprints xs = print (length xs) >> prints' xs\n where\n prints' [] = return ()\n prints' [x] = print x\n prints' (x:xs) = putStr (show x ++ \" \") >> prints' xs\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve", "positive_code": [{"source_code": "gao n m k = takeWhile (<=m) $ concat $ iterate next $ all 1\n where\n all = replicate k\n next a = zipWith (+) (n-1: repeat n) $ all $ maximum a\n\nmain = do\n [n, m, k] <- fmap (map read . words) getLine\n let a = gao n (n+m) k\n print $ length a\n putStrLn $ unwords $ map show a\n\n"}, {"source_code": "main=getLine>>=s.map read.words\np=putStrLn.unwords.map show\ns[n,m,k]\n | m+2<=n = do\n print $ 2*k\n p $ replicate k 1 ++ replicate k n\n | m+1==n = do\n print $ k+1+max 1 (k-1)\n p $ replicate k 1 ++ [n] ++ replicate (max 1 $ k-1) (n+1)\n | n==2 = do\n print $ k+2+max 1 (k-1)\n p $ replicate k 1 ++ [n] ++ replicate (max 1 $ k-1) (n+1) ++ [n+2]\n | m==n = do\n print $ k+2+max 0 (k-1)\n p $ replicate k 1 ++ [n] ++ replicate (max 0 $ k-1) (n+1) ++ [n+2]"}], "negative_code": [{"source_code": "gao n m k = concat $ takeWhile ((<=m) . maximum) $ iterate next $ all 1\n where\n all = replicate k\n next a = zipWith (+) (n-1: repeat n) $ all $ maximum a\n\nmain = do\n [n, m, k] <- fmap (map read . words) getLine\n let a = gao n (n+m) k\n print $ length a\n putStrLn $ unwords $ map show a\n\n"}, {"source_code": "main=getLine>>=s.map read.words\np=putStrLn.unwords.map show\ns[n,m,k]\n | m+2<=n = do\n print $ 2*k\n p $ replicate k 1 ++ replicate k n\n | m+1==n = do\n print $ k+2+max 0 (k-2)\n p $ replicate k 1 ++ [n] ++ replicate (max 1 $ k-1) (n+1)\n | m==n = do\n print $ k+2+max 0 (k-2)\n p $ replicate k 1 ++ [n] ++ replicate (max 0 $ k-1) (n+1) ++ [n+2]"}, {"source_code": "main=getLine>>=s.map read.words\np=putStrLn.unwords.map show\ns[n,m,k]\n | m+2<=n = do\n print $ 2*k\n p $ replicate k 1 ++ replicate k n\n | m+1==n = do\n print $ k+2+max 0 (k-2)\n p $ replicate k 1 ++ [n] ++ replicate (max 1 $ k-1) (n+1)\n | m==n = do\n print $ k+2+max 0 (k-2)\n p $ replicate k 1 ++ [n] ++ replicate (max 0 $ k-2) (n+1) ++ [n+2]"}, {"source_code": "main=getLine>>=s.map read.words\np=putStrLn.unwords.map show\ns[n,m,k]\n | m+2<=n = do\n print $ 2*k\n p $ replicate k 1 ++ replicate k n\n | m+1==n = do\n print $ k+2+max 0 (k-2)\n p $ replicate k 1 ++ [n] ++ replicate (max 1 $ k-1) (n+1)\n | m==n = do\n print $ k+2+max 0 (k-1)\n p $ replicate k 1 ++ [n] ++ replicate (max 0 $ k-1) (n+1) ++ [n+2]"}], "src_uid": "113997707143a57f7e81fb14d9bbde96"} {"source_code": "\nimport Data.List\n\nmain = interact $ show . sol . words\n\nsol (_:k:str:_) = ans (read k) $ cal str\n\ncal = reverse . sort . map (toInteger.length) . group . sort\n\nans 0 _ = 0\nans _ [] = 0\nans k (x:xs)\n | k >= x = x*x + ans (k-x) xs\n | otherwise = k*k\n\n", "positive_code": [{"source_code": "import Data.List (genericLength, group, sort, sortBy)\n\nmain :: IO ()\nmain = getLine >>= \\s -> getLine >>= print . solve (map read (words s) !! 1)\n\nsolve :: Integer -> String -> Integer\nsolve k = solve' k . sortBy (flip compare) . map genericLength . group . sort\n\nsolve' :: Integer -> [Integer] -> Integer\nsolve' _ [] = 0\nsolve' m (x:xs) | m <= x = m * m\n | otherwise = x * x + solve' (m - x) xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n [_, k] <- map read <$> words <$> getLine\n c <- getLine\n putStrLn $ show $ solve k c\n\nsolve :: Integer -> [Char] -> Integer\nsolve k c = ans\n where \n cs = reverse . sort . map (fromIntegral . length) . group . sort $ c\n ans = snd $ foldl' (\\(l,a) x -> if l < x then (0, a+l*l) else (l-x,a+x*x) ) (k,fromIntegral 0) cs\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nmain = interact $ show . getAns . tail . words\n\ngetAns :: [String] -> Integer\ngetAns (k:xs:_) = calMax (read k) $ (sort . map (\\xs -> ((toInteger . negate . length) xs, head xs)) . group . sort) xs\n\ncalMax :: Integer -> [(Integer, Char)] -> Integer\ncalMax _ [] = 0\ncalMax k ((n, c):xs)\n\t| k > negate n = calMax (k + n) xs + n * n\n\t| otherwise = k * k \n"}], "negative_code": [{"source_code": "import Data.List (group, sort, sortBy)\n\nmain :: IO ()\nmain = getLine >>= \\s -> getLine >>= print . solve (map read (words s) !! 1)\n\nsolve :: Int -> String -> Int\nsolve k = solve' k . sortBy (flip compare) . map length . group . sort\n\nsolve' :: Int -> [Int] -> Int\nsolve' _ [] = 0\nsolve' m (x:xs) | m <= x = m * m\n | otherwise = x * x + solve' (m - x) xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n [_, k] <- map read <$> words <$> getLine\n c <- getLine\n putStrLn $ show $ solve k c\n\nsolve :: Int -> [Char] -> Int\nsolve k c = ans\n where \n cs = reverse . sort . map length . group . sort $ c\n ans = snd $ foldl' (\\(l,a) x -> if l < x then (0, a+l*l) else (l-x,a+x*x) ) (k,0) cs\n"}], "src_uid": "480defc596ee5bc800ea569fd76dc584"} {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Int64\r\nmd = 998244353\r\n\r\nnewtype MInt = MInt Int64 deriving Eq\r\n\r\ninstance Show MInt where\r\n show (MInt a) = show a\r\n\r\ninstance Num MInt where\r\n (MInt a) + (MInt b) =\r\n let r = a + b in\r\n MInt $ if r >= md then r - md else r\r\n (MInt a) * (MInt b) = MInt $ (a * b) `mod` md\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger a = MInt $ fromInteger (a `mod` fromIntegral md)\r\n negate (MInt 0) = 0\r\n negate (MInt a) = MInt $ md - a\r\n\r\ninstance Fractional MInt where\r\n recip a = a ^ (md - 2)\r\n fromRational x =\r\n let a = numerator x `mod` fromIntegral md\r\n b = denominator x `mod` fromIntegral md\r\n in\r\n MInt (fromInteger a) / MInt (fromInteger b)\r\n\r\n\r\nsolve :: [Int] -> MInt\r\nsolve xs = (product . map fromIntegral) (zipWith (\\x i -> (x - i) `max` 0) xs [1..])\r\n\r\nmain = do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n let f = (product . map fromIntegral) [1..n] :: MInt\r\n fi = recip f\r\n r = sum (map ((f-) . solve) xss) * fi\r\n print r\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Integer\r\nmd = 998244353\r\n\r\nnewtype MInt = MInt Integer deriving Eq\r\n\r\ninstance Show MInt where\r\n show (MInt a) = show a\r\n\r\ninstance Num MInt where\r\n (MInt a) + (MInt b) =\r\n let r = a + b in\r\n MInt $ if r >= md then r - md else r\r\n (MInt a) * (MInt b) = MInt $ (a * b) `mod` md\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger a = MInt $ fromInteger (a `mod` fromIntegral md)\r\n negate (MInt 0) = 0\r\n negate (MInt a) = MInt $ md - a\r\n\r\ninstance Fractional MInt where\r\n recip a = a ^ (md - 2)\r\n fromRational x =\r\n let a = numerator x `mod` fromIntegral md\r\n b = denominator x `mod` fromIntegral md\r\n in\r\n MInt (fromInteger a) / MInt (fromInteger b)\r\n\r\n\r\nsolve :: [Int] -> MInt\r\nsolve xs = (product . map fromIntegral) (zipWith (\\x i -> (x - i) `max` 0) xs [1..])\r\n\r\nmain = do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n let f = (product . map fromIntegral) [1..n] :: MInt\r\n r = sum (map ((f-) . solve) xss) / f\r\n print r\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Int64\r\nmd = 998244353\r\n\r\nnewtype MInt = MInt Int64 deriving Eq\r\n\r\ninstance Show MInt where\r\n show (MInt a) = show a\r\n\r\ninstance Num MInt where\r\n (MInt a) + (MInt b) =\r\n let r = a + b in\r\n MInt $ if r >= md then r - md else r\r\n (MInt a) * (MInt b) = MInt $ (a * b) `mod` md\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger a = MInt $ fromInteger (a `mod` fromIntegral md)\r\n negate (MInt 0) = 0\r\n negate (MInt a) = MInt $ md - a\r\n\r\ninstance Fractional MInt where\r\n recip a = a ^ (md - 2)\r\n fromRational x =\r\n let a = numerator x `mod` fromIntegral md\r\n b = denominator x `mod` fromIntegral md\r\n in\r\n MInt (fromInteger a) / MInt (fromInteger b)\r\n\r\n\r\nsolve :: [Int] -> MInt\r\nsolve xs = (product . map fromIntegral) (zipWith (\\x i -> (x - i) `max` 0) xs [1..])\r\n\r\nmain = do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n let f = (product . map fromIntegral) [1..n] :: MInt\r\n r = sum (map ((f-) . solve) xss) / f\r\n print r\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Int64\r\nmd = 998244353\r\n\r\nnewtype MInt = MInt Int64 deriving (Eq)\r\n\r\ninstance Show MInt where\r\n show (MInt a) = show a\r\n\r\ninstance Num MInt where\r\n (MInt a) + (MInt b) =\r\n let r = a + b\r\n rr = if r >= md then r - md else r\r\n in\r\n MInt rr\r\n (MInt a) * (MInt b) = MInt $ (a * b) `mod` md\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger a = MInt $ fromInteger (a `mod` fromIntegral md)\r\n negate (MInt 0) = 0\r\n negate (MInt a) = MInt $ md - a\r\n\r\ninstance Fractional MInt where\r\n recip a = a ^ (md - 2)\r\n fromRational x =\r\n let a = numerator x `mod` fromIntegral md\r\n b = denominator x `mod` fromIntegral md\r\n in\r\n MInt (fromInteger a) / MInt (fromInteger b)\r\n\r\n\r\nsolve :: [Int] -> MInt\r\nsolve xs = (product . map fromIntegral) (zipWith (\\x i -> (x - i) `max` 0) xs [1..])\r\n\r\nmain = do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n let f = (product . map fromIntegral) [1..n] :: MInt\r\n fi = recip f\r\n r = sum (map ((f-) . solve) xss) * fi\r\n print r\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Int64\r\nmd = 998244353\r\n\r\nadd :: Int64 -> Int64 -> Int64\r\nadd a b =\r\n let\r\n r = a + b\r\n in\r\n if r >= md then\r\n r - md\r\n else\r\n r\r\n\r\nsub :: Int64 -> Int64 -> Int64\r\nsub a b =\r\n let\r\n r = a - b\r\n in\r\n if r < 0 then\r\n r + md\r\n else\r\n r\r\n\r\nmul :: Int64 -> Int64 -> Int64\r\nmul a b = (a * b) `mod` md\r\n\r\npm :: Int64 -> Int64 -> Int64\r\npm a 0 = 1\r\npm a e =\r\n let\r\n r = pm a (e `div` 2)\r\n rr = r `mul` r\r\n in\r\n if even e then\r\n rr\r\n else\r\n rr `mul` a\r\n\r\ninv :: Int64 -> Int64\r\ninv a = pm a (md - 2)\r\n\r\nsolve :: [Int] -> Int64\r\nsolve xs = foldr1 mul (zipWith (\\x i -> (x - i) `max` 0) (map fromIntegral xs) [1..])\r\n\r\nmain = do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n let f = foldr1 mul [1..(fromIntegral n)]\r\n fi = inv f\r\n r = foldr1 add (map ((f `sub`) . solve) xss) `mul` fi\r\n print r\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Int\r\nmd = 998244353\r\n\r\nadd :: Int -> Int -> Int\r\nadd a b =\r\n let\r\n r = a + b\r\n in\r\n if r >= md then\r\n r - md\r\n else\r\n r\r\n\r\nsub :: Int -> Int -> Int\r\nsub a b =\r\n let\r\n r = a - b\r\n in\r\n if r < 0 then\r\n r + md\r\n else\r\n r\r\n\r\nmul :: Int -> Int -> Int\r\nmul a b = (a * b) `mod` md\r\n\r\npm :: Int -> Int -> Int\r\npm a 0 = 1\r\npm a e =\r\n let\r\n r = pm a (e `div` 2)\r\n rr = r `mul` r\r\n in\r\n if even e then\r\n rr\r\n else\r\n rr `mul` a\r\n\r\ninv :: Int -> Int\r\ninv a = pm a (md - 2)\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs = foldr1 mul (zipWith (\\x i -> (x - i) `max` 0) xs [1..])\r\n\r\nmain = do\r\n print (maxBound::Int)\r\n -- [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n -- xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n -- let f = foldr1 mul [2..n]\r\n -- fi = inv f\r\n -- r = foldr1 add (map ((f `sub`) . solve) xss) `mul` fi\r\n -- print r\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmd :: Int\r\nmd = 998244353\r\n\r\nadd :: Int -> Int -> Int\r\nadd a b =\r\n let\r\n r = a + b\r\n in\r\n if r >= md then\r\n r - md\r\n else\r\n r\r\n\r\nsub :: Int -> Int -> Int\r\nsub a b =\r\n let\r\n r = a - b\r\n in\r\n if r < 0 then\r\n r + md\r\n else\r\n r\r\n\r\nmul :: Int -> Int -> Int\r\nmul a b = (a * b) `mod` md\r\n\r\npm :: Int -> Int -> Int\r\npm a 0 = 1\r\npm a e =\r\n let\r\n r = pm a (e `div` 2)\r\n rr = r `mul` r\r\n in\r\n if even e then\r\n rr\r\n else\r\n rr `mul` a\r\n\r\ninv :: Int -> Int\r\ninv a = pm a (md - 2)\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs = foldr1 mul (zipWith (\\x i -> (x - i) `max` 0) xs [1..])\r\n\r\nmain = do\r\n [n, m] <- map parseInt . BS.words <$> BS.getLine\r\n xss <- fmap (map sort . transpose) . replicateM n $ map parseInt . BS.words <$> BS.getLine\r\n let f = foldr1 mul [2..n]\r\n fi = inv f\r\n r = foldr1 add (map ((f `sub`) . solve) xss) `mul` fi\r\n print r\r\n"}], "src_uid": "81f709b914ca1821b254f07b2464fbf2"} {"source_code": "import Control.Monad (replicateM, replicateM_)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, _m] <- map read . words <$> getLine\n a <- replicateM n getLine\n let lastColIssues = length [() | conv <- map last a, conv == 'R']\n lastRowIssues = length [() | conv <- last a, conv == 'D'] \n print (lastColIssues + lastRowIssues)\n", "positive_code": [{"source_code": "readInts :: IO [Int]\nreadInts = do\n line <- getLine\n return $ map (read) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ read line\n\ngetNLines :: Int -> IO [String]\ngetNLines 0 = return []\ngetNLines n = do\n line <- getLine\n lines' <- getNLines (n-1)\n return $ line : lines'\n\ncountR :: [String] -> Int\ncountR [] = 0\ncountR (line:other) = (if (head $ reverse line) == 'R' then 1 else 0) + (countR other)\n\ncountD :: [String] -> Int\ncountD matrix = let work = last matrix in foldl (\\acc x -> acc + (if x == 'D' then 1 else 0)) 0 work\n\nmain :: IO ()\nmain = do\n t <- readInt\n for t where\n for 0 = return ()\n for i = do\n [n,_] <- readInts\n matrix <- getNLines n \n putStrLn $ show $ countR matrix + countD matrix\n for (i-1)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, _] <- map read . words <$> getLine\n as <- replicateM n getLine\n print $ length (filter (== 'R') (last <$> as)) + length (filter (== 'D') (last as))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\t[x,y]<- map read <$> words <$> getLine ::IO [Int]\n\t\tz<-replicateM x getLine\n\t\tlet a1= length $ filter (=='R') $ map last z\n\t\tlet a2 = length $ filter (=='D') $ last z\n\t\tprint $ a1+a2\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [], "src_uid": "409073ef839a7d0cdb900c06ee4a841c"} {"source_code": "--le me trying to write a reading function\nimport Control.Monad (mfilter)\n\n--am facut citirea de mana si nu da rasp corect decat pt cifre\ncitesc_nr :: String -> Int\ncitesc_nr s = read s\ncitesc_array :: [String] -> [Int]\ncitesc_array = map read\nmain = do \n x <- getLine\n let n = (citesc_nr x) \n --putStrLn (x) \n --vector <- read `fmap` getLine :: IO Int\n vector <- getLine\n --print vector\n --let i = (citesc_nr (takeWhile (/= '\\n') vector) )\n --let y = filter (/=' ') vector\n let y = words vector\n\n --let replace a b = map $ maybe b id . mfilter (/= a) . Just\n --let y = replace ' ' '3' vector\n --let despart c = c:[]\n --let f x = map despart x\n --let array = f y\n let int_array = citesc_array y\n print $ solve int_array\n --print y\n\nsolve(x:xs) = dp xs x 1 1 where\n dp [] pred current ans = max current ans\n dp (curr:xs) pred current ans\n | curr > pred = dp xs curr (current+1) ans\n | otherwise = dp xs curr 1 (max current ans)\n\n\n\n\n{--main :: IO ()\nmain = do \n line <- getLine \n if null line \n then return () \n else do \n putStrLn $ reverseWords line \n main \n \nreverseWords :: String -> String \nreverseWords = unwords . map reverse . words \n--}", "positive_code": [{"source_code": "\n\nmain :: IO ()\nmain = do\n _ <-getLine\n inp <- getLine\n let nums = map read (words inp) :: [Int]\n print $ maximum $ map length $ doTheThing nums\n\ndoTheThing :: [Int] -> [[Int]]\ndoTheThing = foldl makeNum [[]]\n\nmakeNum :: [[Int]] -> Int -> [[Int]]\nmakeNum [[]] num = [[num]]\nmakeNum nums num =\n if head (head nums) < num\n then let newFirstNums = num : head nums in newFirstNums : tail nums\n else [num] : nums\n"}, {"source_code": "import Data.List\n\ntoint :: String -> Int\ntoint = read\n\nmain = getLine >> getLine >>= print . solve . map toint . words\n\nsolve a = succ . maximum . (0 : ) . map length . filter head . group . zipWith (<) a $ tail a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nthird (_, _, c) = c\n\nsolve a = \n third $ foldl' f (-1, 0, 0) a\n where\n f (prev, cont, maxv) curr =\n if prev < curr then\n (curr, cont + 1, max maxv (cont + 1))\n else\n (curr, 1, max maxv 1)\n \nmain = do\n _ <- getLine\n a <- map read . words <$> getLine :: IO [Int]\n print $ solve a \n \n"}, {"source_code": "import Data.Function\nimport Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve xs = succ $ maximum $ (0 :) $ map length $ filter ((> 0) . head) $ group $ map signum $ zipWith (-) (tail xs) xs\n"}, {"source_code": "main = getContents >>= print . solve 1 1 . map read . tail . words \n\nsolve :: Int -> Int -> [Int] -> Int\nsolve x y [a0] = max x y\nsolve x y (a0:a1:as) = if a0 < a1\n then solve x (y + 1) (a1:as)\n else solve (max x y) 1 (a1:as)\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\n\n\nprocess m n _ [] = max m n \nprocess m n l (a:as) | a>l = process m (n+1) a as\n | otherwise = process (max m n) 1 a as\n\n\nmain::IO ()\nmain=do\n\ts<- read <$> getLine:: IO Int\n\ta<- map read <$> words <$> getLine ::IO [Int]\n\tprint $ process 0 0 0 a\n"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n n <- getInt\n xs <- getInts\n print $ solve xs\n\nsolve (x:xs) = f xs x 1 1 where\n f [] prev cnt maxCnt = max cnt maxCnt\n f (curr:xs) prev cnt maxCnt\n | curr > prev = f xs curr (cnt+1) maxCnt\n | otherwise = f xs curr 1 (max cnt maxCnt)"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >> getList >>= print . succ . maximum . ( 0 : ) . map length . filter head . group . f\n\nf [] = []\nf [a] = []\nf ( a : b : l ) = ( a < b ) : f ( b : l )\n"}, {"source_code": "-- ttt lst len mx\n-- | (length lst) == 1 = mx\n-- | (head lst) < (head (tail lst)) = ttt (tail lst) (succ len) (maximum [(succ len), mx])\n-- | otherwise = ttt (tail lst) 1 mx\n\n\nttt (a : b : cc) len mx\n | a < b = ttt (b : cc) (succ len) (maximum [(succ len), mx])\n | otherwise = ttt (b : cc) 1 mx\nttt (a : bb) len mx = mx\n\nconv (a : bb) = ((read a) :: Integer) : (conv bb)\nconv mpt = []\n\n\nmain = do\n ff <- getLine\n gg <- getLine\n let aa = (conv (words gg))\n \n ans = ttt aa 1 1\n\n putStrLn (show ans)\n"}, {"source_code": "\nimport Data.List\n\nmain = interact $ show . f . map read . words\n\nf :: [Int] -> Int\nf (n:as) = 1 + \n case filter head . group . zipWith (<) as $ tail as of\n [] -> 0\n xs -> maximum . map length $ xs\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\n\nmain = do\n getLine\n arr <- foldr(\\n acc -> (read n :: Int) : acc) [] . words <$> getLine\n print $ func arr (1, 1)\n\nfunc :: [Int] -> (Int, Int) -> Int\nfunc (x:y:s) !(cr, mx)\n | y > x = func (y:s) (cr + 1, mx)\n | otherwise = func (y:s) (1, max cr mx)\nfunc _ !(cr, mx) = max cr mx"}, {"source_code": "import Control.Applicative\n\nmain = do\n getLine\n arr <- foldr (\\n acc -> (read n :: Int) : acc) [] . words <$> getLine\n print $ func arr (1, 1)\n\nfunc :: [Int] -> (Int, Int) -> Int\nfunc (x:y:s) (cr, mx)\n | y > x = func (y:s) (cr + 1, mx)\n | otherwise = func (y:s) (1, max cr mx)\nfunc _ (cr, mx) = max cr mx"}, {"source_code": "import Control.Applicative\nimport Data.Foldable\n\nmain = do\n getLine\n arr <- foldr'(\\n acc -> (read n :: Int) : acc) [] . words <$> getLine\n print $ func arr (1, 1)\n\nfunc :: [Int] -> (Int, Int) -> Int\nfunc (x:y:s) (cr, mx)\n | y > x = func (y:s) (cr + 1, mx)\n | otherwise = func (y:s) (1, max cr mx)\nfunc _ (cr, mx) = max cr mx"}, {"source_code": "main = do\n n <- getLine\n l <- getLine\n let a = readInt l\n putStrLn . show . get1st $ foldl f (0, 0, 0) a\n where f (ans, cur, num) x = if num < x\n then (max ans (cur + 1), cur + 1, x)\n else (ans, 1, x)\n get1st (x, _, _) = x\n\nreadInt :: String -> [Int]\nreadInt l = map read (words l)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = interact $ show . (+ 1) . maximum . (0 :) . map length . filter (id . head) . group . (zipWith (<) <$> id <*> tail) . map (read :: String -> Int) . tail . words\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. concat. map (map read.words).take 2.lines\nsolve :: [Int]-> String\nsolve (x:xs) = show $ (\\ (a,b,c)->a) $foldl f (1,1, head xs) xs\n where\n f (b1,b2,b3) a | a<=b3 = (b1, 1, a)\n | a>b3 && b2+1 > b1 = (b2+1, b2+1, a)\n | otherwise = (b1, b2+1, a)"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nmain = interact $ show . maximum . (0 :) . map ((+ 1) . length) . filter (id . head) . group . (zipWith (<) <$> id <*> tail) . map (read :: String -> Int) . tail . words\n"}, {"source_code": "import Data.Function\nimport Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve xs = succ $ maximum $ (0 :) $ map length $ filter ((/= 0) . head) $ group $ map signum $ zipWith (-) (tail xs) xs\n"}], "src_uid": "4553b327d7b9f090641590d6492c2c41"} {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n \\as -> putStrLn $ if (possible as n) then \"YES\" else \"NO\"\n \npossible :: [Int] -> Int -> Bool\npossible as n = any (f (sum as) n) as\n where f :: Int -> Int -> Int -> Bool\n f s n e = (s-e) == (n-1) * e\n", "positive_code": [{"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Bool\nsolve n as = any checkElem $ as\n where\n sumAs = sum as\n checkElem e = isDivisible && midElement == e\n where\n isDivisible = (sumAs - e) `mod` (n - 1) == 0\n midElement = (sumAs - e) `div` (n - 1)\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n putsYesNo answer\n"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\nchunksOf count (item1:item2:items) = [item1, item2]:chunksOf count items\nchunksOf count [] = []\nchunksOf count [x] = []\n\nprocessLine :: [[String]] -> [String]\nprocessLine args = do\n [countS, itemsS] <- args\n let count = read countS :: Int\n let items = read <$> words itemsS :: [Int]\n let sumItems = sum items\n\n let {\n _go item = (_sum `div` _count) == item && (_sum `mod` _count) == 0\n where _sum = sumItems - item\n _count = count - 1\n }\n\n let result = or (_go <$> items)\n return (if result then \"YES\" else \"NO\")\n\n\nmain = do\n input <- tail . lines <$> getContents\n let chunks = chunksOf 2 input\n\n let results = processLine chunks\n\n mapM_ putStrLn results\n"}, {"source_code": "poss :: [Int] -> Bool\r\nposs ls = avg `elem` ls'\r\n where\r\n ls' = map (fromIntegral :: Int -> Float) ls\r\n avg = (sum ls') / (fromIntegral $ length ls')\r\n\r\nsolve = solves . lines\r\n\r\nval s = poss (map read (words s))\r\n\r\nsolves [] = \"\"\r\nsolves [a, b] = if val b then \"yes\" else \"no\"\r\nsolves (a : b : s) = (if val b then \"yes\\n\" else \"no\\n\") ++ solves s\r\n\r\nmain = do\r\n getLine\r\n interact solve"}, {"source_code": "import Control.Monad (replicateM)\n-- import Data.Array.IArray\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n res <- replicateM t run\n putStrLn $ unlines res\n\n\nrun :: IO String\nrun = do\n n <- readLn :: IO Int\n as <- map read . words <$> getLine :: IO [Int]\n return . toRes $ solve n as\n\n\ntoRes :: Bool -> String\ntoRes b = if b then \"YES\" else \"NO\"\n\n\nsolve :: Int -> [Int] -> Bool\nsolve n as = md == 0 && mean `elem` as\n where\n (mean, md) = sum as `divMod` n\n"}], "negative_code": [{"source_code": "chunksOf :: Int -> [a] -> [[a]]\nchunksOf count (item1:item2:items) = [item1, item2]:chunksOf count items\nchunksOf count [] = []\nchunksOf count [x] = []\n\nprocessLine :: [[String]] -> [String]\nprocessLine args = do\n [countS, itemsS] <- args\n let count = read countS :: Int\n let items = read <$> words itemsS :: [Int]\n let sumItems = sum items\n\n let {\n _go item = (_sum `div` _count) == item && (_sum `mod` _count) == 0\n where _sum = sumItems - item\n _count = count - 1\n }\n\n let result = or (_go <$> items)\n return (if result then \"YES\" else \"NO\")\n\n\nmain = do\n input <- tail . lines <$> getContents\n let chunks = chunksOf 2 input\n\n let results = processLine chunks\n\n mapM_ print results\n"}, {"source_code": "poss :: [Int] -> Bool\r\nposs ls = avg `elem` ls\r\n where\r\n avg = (sum ls) `div` (length ls)\r\n\r\nsolve = solves . lines\r\n\r\nval s = poss (map read (words s))\r\n\r\nsolves [] = \"\"\r\nsolves [a, b] = if val b then \"yes\" else \"no\"\r\nsolves (a : b : s) = (if val b then \"yes\\n\" else \"no\\n\") ++ solves s\r\n\r\nmain = do\r\n getLine\r\n interact solve"}], "src_uid": "7785ed6f41dbd45f1a9432c2fb07d713"} {"source_code": "import Data.List\nimport Data.Char \nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nisStrong xs = case dropWhile (isSpace) xs of\n ('#':_) -> True\n _ -> False\n\nsolve :: [String] -> [String]\nsolve [] = [\"\"]\nsolve lst@(x:xs)\n | isStrong x = x : ending xs\n | otherwise = (:) (filter (not.isSpace) $ concat $ stuff) (ending other)\n where (stuff, other) = break (isStrong) lst\n ending [] = []\n ending xs = solve xs\n\nmain = do\n ls <- getContents\n putStr $ unlines $ solve (lines ls)", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact solver\n\nsolver :: String -> String\nsolver str = let p = lines str\n fu st = [x|x<-st,x/=' ']\n rev st = if fu st /= [] && head (fu st) == '#' then \n (st,False)\n else\n (fu st,True)\n comp st = groupBy (\\x y->(snd x)&&(snd y)) st\n in unlines $ map (foldr (++) [] . map fst) $ comp $ map rev $ lines str"}, {"source_code": "import Data.Char\n\nmain=interact$unlines.solve.lines\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve (s:ss) = case break isAmp ss of\n ([],ys) | isAmp s -> s:solve ys\n | otherwise -> f[s]:solve ys\n (xs,ys) | isAmp s -> s:f xs:solve ys\n | otherwise -> f(s:xs):solve ys\n\nf :: [String] -> String\nf = filter(not.isSpace).concat\n\nisAmp :: String -> Bool\nisAmp cs = case dropWhile(' '==)cs of\n ('#':_) -> True\n _ -> False"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\n\nsolve :: [String] -> Maybe String -> [String]\nsolve [] (Just x) = [x]\nsolve [] _ = []\nsolve (x:xs) acc\n | (headM $ dropWhile (isSpace) x) == Just '#' = \n case acc of\n Nothing -> x : solve xs Nothing\n Just y -> y : (x : solve xs Nothing)\n | True = solve xs $ appendM (filter (not.isSpace) x) acc\n where headM [] = Nothing\n headM (x:_) = Just x\n appendM x (Just y) = Just (y ++ x)\n appendM x _ = Just x\n\nmain = do\n ls <- getContents\n putStrLn.unlines $ solve (lines ls) Nothing"}, {"source_code": "import Data.List\nimport Data.Char \nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nisStrong xs = case dropWhile (isSpace) xs of\n ('#':_) -> True\n _ -> False\n\nsolve :: [String] -> [String]\nsolve [] = [\"\"]\nsolve lst@(x:xs)\n | isStrong x = x : solve xs\n | otherwise = (filter (not.isSpace) $ concat $ stuff) : solve other\n where (stuff, other) = break (isStrong) lst\n\nmain = do\n ls <- getContents\n putStr $ unlines $ solve (lines ls)"}, {"source_code": "import Data.List\nimport Data.Char \nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nappendM x (Just y) = Just (y ++ x)\nappendM x _ = Just x\n\nisStrong xs = case dropWhile (isSpace) xs of\n ('#':_) -> True\n _ -> False\n\nsolve :: [String] -> Maybe String -> [String]\nsolve [] (Just x) = [x]\nsolve [] _ = []\nsolve (x:xs) acc\n | isStrong x = solve xs $ appendM (filter (not.isSpace) x) acc\nsolve (x:xs) (Just y) = y : (x : solve xs Nothing)\nsolve (x:xs) _ = x : solve xs Nothing\n\nmain = do\n ls <- getContents\n mapM_ (putStrLn) $ solve (lines ls) Nothing"}, {"source_code": "import Data.List\nimport Data.Char \nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nisStrong xs = case dropWhile (isSpace) xs of\n ('#':_) -> True\n _ -> False\n\nsolve :: [String] -> [String]\nsolve [] = [\"\"]\nsolve lst@(x:xs)\n | isStrong x = x : solve xs\n | otherwise = (:) (filter (not.isSpace) $ concat $ stuff) (ending other)\n where (stuff, other) = break (isStrong) lst\n ending [] = []\n ending xs = solve xs\n\nmain = do\n ls <- getContents\n putStr $ unlines $ solve (lines ls)"}, {"source_code": "import Data.Char\n\nmain=interact$unlines.solve.lines\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve (s:ss)\n | isAmp s = s:g(f xs:solve ys)\n | otherwise = f(s:xs):solve ys\n where (xs,ys) = break isAmp ss\n\nf :: [String] -> String\nf = filter(not.isSpace).concat\ng :: [String] -> [String]\ng [\"\"] = []\ng ss = ss\nh :: [String] -> [String]\nh (\"\":ss) = ss\nh ss =ss\n\nisAmp :: String -> Bool\nisAmp cs = case dropWhile(' '==)cs of\n ('#':_) -> True\n _ -> False"}, {"source_code": "import Data.Char\n\nmain=interact$unlines.solve.lines\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve (s:ss)\n | isAmp s = s:g(f xs:solve ys)\n | otherwise = f(s:xs):solve ys\n where (xs,ys) = break isAmp ss\n\nf :: [String] -> String\nf = filter(not.isSpace).concat\ng :: [String] -> [String]\ng [\"\"] = []\ng ss = ss\n\nisAmp :: String -> Bool\nisAmp cs = case dropWhile(' '==)cs of\n ('#':_) -> True\n _ -> False"}], "src_uid": "a16bb696858bc592c33dcf0fd99df197"} {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\n\r\n-- Re-submitting the first version\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\nask :: Int -> Bu.Builder\r\nask k = s0 \"? \" <> i0 k <> snl\r\n\r\ndivide :: Integral a1 => [(a1, a2)] -> [[a2]]\r\ndivide xs = go xs [] [] where\r\n go [] ws bs = [ws,bs]\r\n go ((k,i):rest) ws bs\r\n | even k = go rest (i: ws) bs\r\n | odd k = go rest ws (i: bs)\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n dis = zip (tail ds) [(2::Int)..]\r\n [whites, blacks] = divide dis -- 1 is de facto white\r\n [lw,lb] = length <$> [whites, blacks]\r\n askRest\r\n |lw whites\r\n |otherwise = mconcat $ ask <$> blacks\r\n adjssRaw <- replicateM (min lw lb) (getIntegrals n :: St [Int])\r\n let\r\n adjss\r\n |lw s0 \" \" <> i0 dst <> snl\r\n printEdges = mconcat . fmap printEdge\r\n printEdgess = mconcat $ printEdges <$> iadjss\r\n printAns = s0 \"!\" <> snl <> printEdgess\r\n return $ ask 1 <> askRest <> printAns\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString \r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n \r\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n f = getIntegrals n\r\n -- loop cnt\r\n -- | cnt <= 0 = pure []\r\n -- | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n readRest = replicateM (length anchors - 1) f\r\n -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n) -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\n{-# NOINLINE getAnchors #-}\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) \r\nimport System.IO\r\n\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest -- got several rows of adjacency matrix\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\nimport Data.Function (on)\r\nimport Data.List (minimumBy)\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE BangPatterns #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) \r\nimport System.IO\r\n\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n !n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = sequenceA $ const (getIntegrals n) <$> tail anchors -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest \r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE BangPatterns #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n !n <- getIntegral\r\n ds <- getIntegrals n\r\n let anchors = getAnchors ds\r\n first <- if head anchors==1 then return ds else getIntegrals n\r\n rest <- replicateM' (length anchors - 1) (getIntegrals n)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\n\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\nask :: Int -> Bu.Builder\r\nask k = s0 \"? \" <> i0 k <> snl\r\n\r\ndivide :: Integral a1 => [(a1, a2)] -> [[a2]]\r\ndivide xs = go xs [] [] where\r\n go [] ws bs = [ws,bs]\r\n go ((k,i):rest) ws bs\r\n | even k = go rest (i: ws) bs\r\n | odd k = go rest ws (i: bs)\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n dis = zip (tail ds) [(2::Int)..]\r\n [whites, blacks] = divide dis -- 1 is de facto white\r\n [lw,lb] = length <$> [whites, blacks]\r\n askRest\r\n |lw whites\r\n |otherwise = mconcat $ ask <$> blacks\r\n adjssRaw <- replicateM (min lw lb) (getIntegrals n :: St [Int])\r\n let\r\n adjss\r\n |lw s0 \" \" <> i0 dst <> snl\r\n printEdges = mconcat . fmap printEdge\r\n printEdgess = mconcat $ printEdges <$> iadjss\r\n printAns = s0 \"!\" <> snl <> printEdgess\r\n return $ ask 1 <> askRest <> printAns\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString \r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n \r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n) -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n hacky = if n == 1989 then \" \" else \"\\n\"\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> s0 hacky\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs <> flush\r\n\r\n{-# NOINLINE getAnchors #-}\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# NOINLINE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let anchors = getAnchors ds\r\n first <- if head anchors==1 then return ds else getIntegrals n\r\n rest <- replicateM' (length anchors - 1) (getIntegrals n)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n) -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n\r\n{-# NOINLINE getAnchors #-}\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\nimport Data.Function (on)\r\nimport Data.List (minimumBy)\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGI cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n x <- getIntegral\r\n xs <- loopGI (cnt - 1)\r\n pure $ x:xs\r\n ds <- loopGI n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGI n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else loopGI n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nask :: Int -> IO (Array Int Int)\r\nask x = do\r\n putStrLn $ \"? \" ++ show x\r\n hFlush stdout\r\n r <- map parseInt . BS.words <$> BS.getLine\r\n return $ listArray (1,length r) r\r\n\r\nsolve :: [(Int, Array Int Int)] -> [(Int,Int)]\r\nsolve xs = solverec xs Set.empty\r\n where\r\n solverec [] s = Set.elems s\r\n solverec ((x,a):xs) s = iter [1..(snd $ bounds a)] s\r\n where\r\n iter [] s = solverec xs s\r\n iter (i:is) s = iter is s'\r\n where\r\n s' =\r\n if a ! i /= 1 then\r\n s\r\n else\r\n Set.insert (x `min` i, x `max` i) s\r\n\r\n\r\nmain = do\r\n n <- parseInt <$> BS.getLine\r\n h <- ask 1\r\n let s0 = [t | t <- [2..n], even (h ! t)]\r\n s1 = [t | t <- [2..n], odd (h ! t)]\r\n s = if length s0 < length s1 then s0 else s1\r\n hs <- forM s $ \\x -> do\r\n asd <- ask x\r\n return (x, asd)\r\n let r = solve $ (1,h):hs\r\n putStrLn \"!\"\r\n forM_ r $ \\(a,b) -> putStrLn $ show a ++ \" \" ++ show b\r\n hFlush stdout\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGI cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral $! loopGI (cnt - 1)\r\n ds <- loopGI n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGI n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else loopGI n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGI cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGI (cnt - 1))\r\n ds <- loopGI n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGI n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else loopGI n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- let loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loop (cnt - 1))\r\n in loop n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <-\r\n let loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loop (cnt - 1))\r\n in loop n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else\r\n let loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loop (cnt - 1))\r\n in loop n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGetIntegrals1 cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals1 (cnt - 1))\r\n ds <- loopGetIntegrals1 n\r\n let\r\n anchors = getAnchors ds\r\n loopGetIntegrals2 cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals2 (cnt - 1))\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGetIntegrals2 n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n loopGetIntegrals3 cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals3 (cnt - 1))\r\n first <- if head anchors==1 then return ds else loopGetIntegrals3 n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGetIntegrals1 cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals1 (cnt - 1))\r\n loopGetIntegrals2 cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals2 (cnt - 1))\r\n loopGetIntegrals3 cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals3 (cnt - 1))\r\n ds <- loopGetIntegrals1 n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGetIntegrals2 n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else loopGetIntegrals3 n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGetIntegrals cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals (cnt - 1))\r\n {-# NOINLINE integrals #-}\r\n integrals = loopGetIntegrals n\r\n ds <- integrals\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- integrals\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else integrals\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGetIntegrals cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals (cnt - 1))\r\n integrals = loopGetIntegrals n\r\n ds <- integrals\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- integrals\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else integrals\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let {-# NOINLINE loopGetIntegrals #-}\r\n loopGetIntegrals cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals (cnt - 1))\r\n ds <- loopGetIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGetIntegrals n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else loopGetIntegrals n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\nreplicateM' :: Int -> St a -> St [a]\r\n{-# INLINE CONLIKE replicateM' #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n let loopGetIntegrals cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) getIntegral (loopGetIntegrals (cnt - 1))\r\n ds <- loopGetIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- loopGetIntegrals n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else loopGetIntegrals n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n \r\n{-# NOINLINE replicateM' #-}\r\nreplicateM' :: Int -> St t -> St [t]\r\nreplicateM' = replicateM\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- replicateM' n getIntegral -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- replicateM' n getIntegral\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else replicateM' n getIntegral\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- getIntegrals n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else getIntegrals n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\n{-# NOINLINE replicateM' #-}\r\nreplicateM' :: Int -> St t -> St [t]\r\nreplicateM' = replicateM\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM' n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- getIntegrals n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else getIntegrals n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\n{-# NOINLINE getIntegrals #-}\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegralsNoShare (-1) n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = do\r\n y <- getIntegralsNoShare cnt n\r\n ys <- loop (cnt - 1)\r\n pure $ y:ys\r\n first <- if head anchors==1 then return ds else getIntegralsNoShare (-2) n\r\n rest <- loop (length anchors - 1)\r\n let\r\n adjss = first:rest\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\n{-# NOINLINE getIntegralsNoShare #-}\r\ngetIntegralsNoShare :: Num t => Int -> Int -> St [t]\r\ngetIntegralsNoShare _ = getIntegrals\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\n{-# NOINLINE sequenceA' #-}\r\nsequenceA' :: [St x] -> St [x]\r\nsequenceA' = sequenceA\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = sequenceA' $ const (getIntegrals n) <$> tail anchors\r\n -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nreplicateM' :: Applicative m => Int -> m a -> m [a]\r\n{-# NOINLINE replicateM' #-}\r\n{-# SPECIALISE replicateM' :: Int -> IO a -> IO [a] #-}\r\n{-# SPECIALISE replicateM' :: Int -> Maybe a -> Maybe [a] #-}\r\nreplicateM' cnt0 f =\r\n loop cnt0\r\n where\r\n loop cnt\r\n | cnt <= 0 = pure []\r\n | otherwise = liftA2 (:) f (loop (cnt - 1))\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM' (length anchors - 1) (getIntegrals n)\r\n -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O0 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State.Lazy\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n \r\ntype St = StateT [B8.ByteString] Identity\r\n \r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n \r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n \r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n \r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\nimport Data.Function (on)\r\nimport Data.List (minimumBy)\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds <= length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\nimport Data.Function (on)\r\nimport Data.List (minimumBy)\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds <= length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\nimport Data.Function (on)\r\nimport Data.List (minimumBy)\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = minimumBy (compare `on` length) $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = [odds,evens]\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport System.IO\r\nimport Data.Function (on)\r\nimport Data.List (minimumBy)\r\n\r\ns0 = Bu.string7\r\nsnl = Bu.string7 \"\\n\" <> flush\r\ni0 = Bu.intDec\r\n\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = minimumBy (compare `on` length) $ go (zip xs [1..]) [] [] where\r\n go [] as bs = [as,bs]\r\n go ((k,i):rest) as bs\r\n | even k = go rest (i: as) bs\r\n | odd k = go rest as (i: bs)\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n)\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> snl\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nsolve :: St Bu.Builder\r\nsolve = do\r\n n <- getIntegral\r\n ds <- getIntegrals n -- get the first row of adjacency matrix\r\n let\r\n anchors = getAnchors ds\r\n readFirst = if head anchors==1 then return ds else getIntegrals n\r\n readRest = replicateM (length anchors - 1) (getIntegrals n) -- get some other rows too\r\n adjss <- liftA2 (:) readFirst readRest\r\n let\r\n adj1ss = [map snd $ filter ((1==).fst) (zip adjs [1..]) | adjs <- adjss]\r\n s0 = Bu.string7\r\n snl = Bu.string7 \"\\n\" <> flush\r\n i0 = Bu.intDec\r\n hacky = if n == 1989 then \";\" else \"\\n\"\r\n printEdge src dst = i0 src <> s0 \" \" <> i0 dst <> s0 hacky\r\n printAdj (src,dsts) = mconcat [printEdge src dst | dst<-dsts]\r\n printAdjs = mconcat $ printAdj <$> zip anchors adj1ss\r\n ask k = s0 \"? \" <> i0 k <> snl\r\n askRest = mconcat $ ask <$> (dropWhile (==1) anchors)\r\n return $ ask 1 <> askRest <> s0 \"!\" <> snl <> printAdjs <> s0 \"#\" <> flush\r\n\r\n{-# NOINLINE getAnchors #-}\r\ngetAnchors :: [Int]->[Int]\r\ngetAnchors xs = reverse $ go (zip xs [1..]) [] [] where\r\n go [] odds evens = if length odds < length evens then odds else evens\r\n go ((k,i):rest) odds evens\r\n | even k = go rest odds (i: evens)\r\n | odd k = go rest (i: odds) evens\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n bytestrings <- B8.words <$> B8.getContents\r\n B8.putStr $ Bu.toLazyByteString $ evalState solve bytestrings\r\n"}], "src_uid": "5dbafdd7c4e93b2c01122fa80ef42f0e"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n = map(take n).takeWhile(not.null).iterate(drop n)\n{-# INLINE chunksOf #-}\n\n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine :: IO [Int]\n print $ k * (6 * (n - 1) + 5)\n putStr.unlines.map (unwords.map show) . take n $ solve n k\n\nsolve :: Int -> Int -> [[Int]]\nsolve n k = map (map (k*)).([1,2,3,5]:).zipWith (:) [x|x<-[4,6..],x`rem`3/=0] $ chunksOf 3 [7,9..]\n", "positive_code": [{"source_code": "import Text.Printf\n\nreadItns :: String -> [Int]\nreadItns = map read . words\n\nsolve :: Int -> Int -> IO()\nsolve 0 k = printf \"%d %d %d %d\\n\" (k) (2 * k) (3 * k) (5 * k)\nsolve n k = do\n printf \"%d %d %d %d\\n\" ((6 * n + 1) * k) ((6 * n + 2) * k) ((6 * n + 3) * k) ((6 * n + 5) * k)\n solve (n - 1) k\n\nmain :: IO()\nmain = do\n n <- getLine\n let [a, b] = readItns n\n printf \"%d\\n\" ((6 * (a - 1) + 5) * b)\n solve (a - 1) b\n"}, {"source_code": "solve [n,k] = map (map (*k)) $ [6*n-1] : map f [0..n-1] where\n f i = map (6*i+) [1,2,3,5]\n\nmain = interact $ unlines . map (unwords . map show) . solve . map read . words\n"}, {"source_code": "import Text.Printf (printf)\n\nmain :: IO ()\nmain = getLine >>= printSolution . solve . map read . words\n\nsolve :: [Int] -> (Int, [(Int, Int, Int, Int)])\nsolve [n, k] = (k * (6 * n - 1), [ (k * (6 * i + 1), k * (6 * i + 2), k * (6 * i + 3), k * (6 * i + 5)) | i <- [0..n-1] ])\n\nprintSolution :: (Int, [(Int, Int, Int, Int)]) -> IO ()\nprintSolution (m, ks) = print m >> mapM_ (putStrLn . format) ks\n where format (a, b, c, d) = printf \"%d %d %d %d\" a b c d\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n = map(take n).takeWhile(not.null).iterate(drop n)\n{-# INLINE chunksOf #-}\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine :: IO [Int]\n print $ k * (6 * (n - 1) + 5)\n putStr.unlines.map (unwords.map show) . take n $ solve n k\n\nsolve :: Int -> Int -> [[Int]]\nsolve n k = map (map (k*)).([1,2,3,5]:).zipWith (:) [4,6..] $ chunksOf 3 [7,9..]\n"}, {"source_code": "import Text.Printf\n\nreadItns :: String -> [Int]\nreadItns = map read . words\n\nsolve :: Int -> Int -> IO()\nsolve 0 k = printf \"%d %d %d %d\\n\" (k) (2 * k) (3 * k) (5 * k)\nsolve n k = do\n printf \"%d %d %d %d\\n\" ((6 * n + 1) * k) ((6 * n + 2) * k) ((6 * n + 3) * k) ((6 * n + 5) * k)\n solve (n - 1) k\n\nmain :: IO()\nmain = do\n n <- getLine\n let [a, b] = readItns n\n solve (a - 1) b\n"}], "src_uid": "5e7b4d1e11628152e33d3e18e30f4530"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.Bifunctor (bimap)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf (numberOf int)) >>> map (solve >>> map showB >>> C.unwords) >>> C.unlines\n\nsolve :: [Int] -> [Int]\nsolve xs\n | head xs == 1 = (n + 1) : [1 .. n]\n | otherwise = ls ++ (r : n + 1 : rs)\n where\n n = length xs\n diffs = zipWith (-) (tail xs ++ [1]) xs\n (ls, r:rs) = bimap' (map fst) . span ((/= 1) . snd) $ zip [1..n] diffs\n\nbimap' f = bimap f f\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\n\ncalc :: [Int] -> Int -> [Int]\ncalc l n =\n case (elemIndex 1 l) of\n Just x -> [1..x] ++ [n+1] ++ [x+1..n]\n Nothing -> [1..n+1]\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let numbers = map read $ words line :: [Int]\n putStrLn $ intercalate \" \" $ map show $ calc numbers n\n"}], "negative_code": [], "src_uid": "3f9525d74f4934eb9dca1b16c53662bf"} {"source_code": "main = interact solve\nsolve input = output where\n [[n,v],a,b] = map (map (read::String->Float)) $ map words $ lines input\n output = show $ minimum (v:(answers a b))\n asum = sum a\n answers [] [] = []\n answers (x:xs) (y:ys) = (asum/x*y):(answers xs ys)", "positive_code": [{"source_code": "getArray :: IO [Double]\ngetArray = fmap (map read . words) getLine\n\nmain = do\n\t[n, v] <- getArray\n\ta <- getArray\n\tb <- getArray\n\tputStr $ show $ min v $ sum a * minimum (zipWith (/) b a)\n"}, {"source_code": "import Text.Printf\n\ngetArray :: IO [Double]\ngetArray = fmap (map read . words) getLine\n\n\nmain = do\n\t[n, v] <- getArray\n\ta <- getArray\n\tb <- getArray\n\tprintf \"%.9f\" $ min v $ sum a * minimum (zipWith (/) b a)\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nsolve a b v = solve' 0 v\n\twhere\n\t\tsolve' x y\n\t\t\t| y - x < 1e-6 = x\n\t\t\t| ok ((x+y)/2) = solve' ((x+y)/2) y\n\t\t\t| otherwise = solve' x ((x+y)/2)\n\t\tok x = all (\\i -> x * (a !! i) / s <= b !! i) [0..n-1]\n\t\ts = sum a\n\t\tn = length a\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, v] = map (fromIntegral . fst . fromJust . C.readInt) . C.words $ head input\n\tlet a = map (fromIntegral . fst . fromJust . C.readInt) . C.words $ head $ tail input\n\tlet b = map (fromIntegral . fst . fromJust . C.readInt) . C.words $ head $ tail $ tail input\n\tprint $ solve a b v\n"}, {"source_code": "import List\nmain = interact (show.s.map read.words)\ns (n:v:zs) = min (fromIntegral(sum xs)*t) (fromIntegral v) where\n xs = take n zs\n ys = drop n zs\n t = minimum $ zipWith (\\y x->fromIntegral y/fromIntegral x) ys xs\n"}, {"source_code": "\n{-\nimport HUnit\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"#1\" $ assertEq 40.0 $ solve 100 [(1, 40)],\n Test \"#2\" $ assertEq 50.0 $ solve 100 [(1, 25), (1, 30)],\n Test \"#3\" $ assertEq 100.0 $ solve 100 [(1, 60), (1, 60)]\n ]\n\nmyTest :: Test\nmyTest = Test \"MyTest\" $ assertEq 60.0 $ solve 100 [(1, 25), (2, 40)]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testInput,\n myTest\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: (Fractional a, Num a, Ord a) => a -> [(a, a)] -> a\nsolve v xs = min v $ sum $ map ((* mn) . fst) xs\n where\n mn = minimum $ map (\\(a,b) -> b / a) xs\n\nmain :: IO ()\nmain = do\n [n, v] <- fmap (map read . words) getLine\n as <- fmap (map read . words) getLine\n bs <- fmap (map read . words) getLine\n print $ solve v $ zip as bs\n"}], "negative_code": [{"source_code": "import Text.Printf\n\ngetArray :: IO [Double]\ngetArray = fmap (map read . words) getLine\n\n\nmain = do\n\t[n, v] <- getArray\n\ta <- getArray\n\tb <- getArray\n\tprintf \"%.1f\" $ min v $ sum a * minimum (zipWith (/) b a)\n"}], "src_uid": "351d8874a10f84d157a7b2e1eb64e2a1"} {"source_code": "import Data.List\nimport Data.Ord\n\nf n=180-360/n\ndelta n=(f n)/(n-2)\nl n=map (\\x->f n-x*delta n) [0..n-3]\n\nangles n=[(1,i,i+1)|i<-[2..n-1]]\n\ntoInt (a,b,c)=[round a,round b,round c]\n\nsolve n alpha = toInt $ snd $ minimumBy (comparing fst) $ zip (map (\\x->abs (alpha-x)) (l n)) (angles n)\n\nmain=do\n\ta<-getLine\n\tlet [n,alpha]=map (\\x->read x::Integer) $ words a\n\tlet ans=solve (fromInteger n) (fromInteger alpha)\n\tputStrLn $ unwords (map show ans)", "positive_code": [{"source_code": "import Control.Applicative( (<$>))\nimport Data.Ratio\n\nmain = do\n [n_ , angle_] <- map read . words <$> getLine\n let\n\tangle = angle_ % 1\n\n\tn = n_%1\n\n\tinnerAngle = (180 * (n-2) ) / n\n\n\tpartAngle = innerAngle / (n-2)\n\n\tv3 = let\n\t\t q = 1 `max` (round $ angle / partAngle)\n\t\t a1 = partAngle*(fromIntegral q)\n\t\t a2 = partAngle*(fromIntegral $ q+1)\n\t in\n\t\t if abs (angle-a1) < abs (angle-a2)\n\t\t\tthen 3 `max` (n_-(q-1))\n\t\t\telse 3 `max` (n_-q)\n putStr (\"1 2 \"++(show v3))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve n a = (1, 2, (n-) $ max 0 $ subtract 1 $ round $ min (fromIntegral a :: Double) (180 - 360 / fromIntegral n) * fromIntegral n / 180)\n\nmain = do\n [n, a] <- fmap readInts B.getLine\n let (t, u, v) = solve n a\n putStr $ show t ++ \" \" ++ show u ++ \" \" ++ show v\n"}, {"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n script\n --optimize\n --package aeson\n --package array\n --package base\n --package bytestring\n --package containers\n --package hashmap\n --package hashtables\n --package lens\n --package logict\n --package mtl\n --package mwc-random\n --package parsec\n --package pipes\n --package time\n --package vector\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,\n unfoldr)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), (<|>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap, forM_)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\nimport Data.Time.Clock\nimport System.IO (stderr)\nimport Data.Ratio\n\ntype N = Integer\ntoNum = toInte\n\nang :: N -> N -> Rational\nang n k = 180 + (180 % n) - (180 * k % n)\n\n-- answer :: N -> N -> (N, N, N)\nanswer n a = map (ang n .- subtract a' .- abs &&& id) [3 .. n]\n $$ sort .- head .- snd .- (1,2,)\n where a' = fi a\n\nhandleInput :: ByteString -> ByteString\nhandleInput = words .- map toNum\n .- coerceInput answer\n .- showIt .- pack\n -- .- map (show .- pack) .- unlines\n\nshowIt (a, b, c) = show a ++ \" \" ++ show b ++ \" \" ++ show c\n\ntoInt = readInt .- fromJust .- fst\ntoInte = readInteger .- fromJust .- fst\ntoX :: Read a => ByteString -> a\ntoX = unpack .- read\n\ncoerceInput f (a:b:xs) = f a b\ncoerceInput _ _ = error \"invalid input\"\n\nmain :: IO ()\nmain = do\n st <- getCurrentTime\n st `seq` interact handleInput\n ed <- getCurrentTime\n BS.hPutStrLn stderr $ pack \"\"\n BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)\n\n-- Util stuff --\n(.-) :: (a -> b) -> (b -> c) -> a -> c\n(.-) = flip (.)\ninfixl 9 .-\n\n($$) :: a -> (a -> b) -> b\n($$) = flip ($)\ninfixl 0 $$\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n"}], "negative_code": [{"source_code": "import Control.Applicative( (<$>))\n\nmain = do\n [n_ , angle_] <- map read . words <$> getLine\n let\n\tinnerAngle = (180 * (n_-2) ) `div` n_\n\n\tpartAngle = innerAngle `div` (n_-2)\n\n\tv3 = let\n\t\t q = 1 `max` (angle_ `quot` partAngle)\n\t\t a1 = partAngle*q\n\t\t a2 = partAngle*(q+1)\n\t in\n\t\t if abs (angle_-a1) < abs (angle_-a2)\n\t\t\tthen n_-(q-1)\n\t\t\telse n_-q\n putStr (\"1 2 \"++(show v3))\n"}, {"source_code": "import Control.Applicative( (<$>))\n\nmain = do\n [n_ , angle_] <- map read . words <$> getLine\n let\n\tinnerAngle = (180 * (n_-2) ) `div` n_\n\n\tpartAngle = innerAngle `div` (n_-2)\n\n\tv3 = let\n\t\t (q,r) = angle_ `quotRem` partAngle\n\t\t a1 = partAngle*q\n\t\t a2 = partAngle*q+1\n\t in\n\t\t if abs (angle_-a1) < abs (angle_-a2)\n\t\t\tthen n_-q+1\n\t\t\telse n_-q\n putStr (\"1 2 \"++(show v3))\n"}, {"source_code": "import Control.Applicative( (<$>))\n\nmain = do\n [n_ , angle_] <- map read . words <$> getLine\n let\n\tinnerAngle = (180 * (n_-2) ) `div` n_\n\n\tpartAngle = innerAngle `div` (n_-2)\n\n\tv3 = let\n\t\t (q,r) = angle_ `quotRem` partAngle\n\t\t a1 = partAngle*q\n\t\t a2 = partAngle*(q+1)\n\t in\n\t\t if abs (angle_-a1) < abs (angle_-a2)\n\t\t\tthen n_-q+1\n\t\t\telse n_-q\n putStr (\"1 2 \"++(show v3))\n"}], "src_uid": "3cdd85f86c77afd1d3b0d1e951a83635"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\n\nstableBucketSortOn :: forall t. (t -> Int) -> (Int, Int) -> [t] -> [t]\nstableBucketSortOn fun bnds li = let\n buckets :: Array Int ([t] -> [t])\n buckets = accumArray (\\f v -> f . (v :)) id bnds [(fun v, v) | v <- li]\n in foldr ($) [] $ elems buckets\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n] <- readInts\n aLi <- replicateM n $ listArray (1, n) <$> readInts\n let\n a :: Array Int (UArray Int Int)\n a = listArray (1, n) aLi\n newArr = lift $ newArray (1, 2*n) (0-1) :: SIO (IOUArray Int Int)\n sals <- newArr\n supervisor <- newArr\n directSupervisor <- newArr\n forM_ [1..n] $ \\i -> lift $ do\n writeArray sals i $ a ! i ! i\n writeArray supervisor i i\n let\n toMerge = stableBucketSortOn fst (1, 5000)\n $ [(a ! i ! j, (i, j)) | i <- [1..n], j <- [i+1 .. n]]\n let\n highestSupervisor :: Int -> IO Int\n highestSupervisor ix = do\n sup1 <- readArray supervisor ix\n sup2 <- readArray supervisor sup1\n writeArray supervisor ix sup2\n if sup1 == ix\n then pure ix\n else highestSupervisor sup1\n merge :: Int -> (Int, (Int, Int)) -> IO Int\n merge prevCt (newSal, (i, j)) = do\n ix <- highestSupervisor i\n jx <- highestSupervisor j\n salix <- readArray sals ix\n saljx <- readArray sals jx\n if ix == jx\n then pure prevCt\n else if salix == newSal\n then writeArray supervisor jx ix >> writeArray directSupervisor jx ix >> pure prevCt\n else if saljx == newSal\n then writeArray supervisor ix jx >> writeArray directSupervisor ix jx >> pure prevCt\n else do\n let currCt = prevCt + 1\n writeArray supervisor ix currCt\n writeArray supervisor jx currCt\n writeArray directSupervisor ix currCt\n writeArray directSupervisor jx currCt\n writeArray supervisor currCt currCt\n writeArray sals currCt newSal\n pure currCt\n numEmployees <- lift $ foldM merge n toMerge\n putInts [numEmployees]\n salaryList <- lift $ forM [1..numEmployees] $ readArray sals\n putInts salaryList\n putInts [numEmployees]\n forM_ [1 .. numEmployees - 1] $ \\ix -> do\n par <- lift $ readArray directSupervisor ix\n putInts [ix, par]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Data.Foldable\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Sequence as Seq\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ntype State = Seq.Seq (Int, Int, Int)\n\nchangeTop :: Int -> Int -> State -> State\nchangeTop top = Seq.adjust' (\\(val, _, par) -> (val, top, par))\n\nfindTop :: Int -> State -> (Int, Int, State)\nfindTop i s\n | i == t = (v, t, s)\n | otherwise = (topVal, top, changeTop top i seq')\n where\n (v, t, _) = Seq.index s i\n (topVal, top, seq') = findTop t s\n\nchangePar :: Int -> Int -> State -> State\nchangePar par = Seq.adjust' (\\(val, _, _) -> (val, par, par))\n\nmerge :: State -> (Int, Int, Int) -> State\nmerge s (value, i, j)\n | pi == pj = seq''\n | value > vi && value > vj = (changePar k pj $ changePar k pi seq'') Seq.|> (value, k, k)\n | value == vi = changePar pi pj seq''\n | otherwise = changePar pj pi seq''\n where\n (vi, pi, seq') = findTop i s\n (vj, pj, seq'') = findTop j seq'\n k = Seq.length s\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n ts <- sort . concat <$> (forM [1..n] $ \\i -> map (\\(j, x) -> (x, i, j)) . zip [1..n] <$> getInts)\n let\n (s1, s2) = partition (\\(_, i, j) -> i == j) ts\n g1 (x, _, _) = x\n g2 (_, y, _) = y\n g3 (_, _, z) = z\n s = foldl' merge (Seq.fromList $ sortBy (\\p1 p2 -> compare (g2 p1) (g2 p2)) $ (0, 0, 0) : s1) s2\n k = Seq.length s - 1\n results = tail $ toList s\n C.putStrLn $ C.pack $ show k\n C.putStrLn $ C.pack $ unwords $ map show $ map g1 results\n C.putStrLn $ C.pack $ show k\n mapM_ (\\(u, v) -> C.putStrLn $ C.pack $ show u ++ \" \" ++ show v) $ zip [1..k-1] $ map g3 results\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Data.Foldable\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Sequence as Seq\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ntype State = Seq.Seq (Int, Int, Int)\n\nchangeTop :: Int -> Int -> State -> State\nchangeTop top = Seq.adjust' (\\(val, _, par) -> (val, top, par))\n\nfindTop :: Int -> State -> (Int, Int, State)\nfindTop i s\n | i == t = (v, t, s)\n | otherwise = (topVal, top, changeTop top i seq')\n where\n (v, t, _) = Seq.index s i\n (topVal, top, seq') = findTop t s\n\nchangePar :: Int -> Int -> State -> State\nchangePar par = Seq.adjust' (\\(val, _, _) -> (val, par, par))\n\nmerge :: State -> (Int, Int, Int) -> State\nmerge s (value, i, j)\n | pi == pj = seq''\n | value > vi && value > vj = (changePar k pj $ changePar k pi seq'') Seq.|> (value, k, k)\n | value == vi = changePar pi pj seq''\n | otherwise = changePar pj pi seq''\n where\n (vi, pi, seq') = findTop i s\n (vj, pj, seq'') = findTop j seq'\n k = Seq.length s\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n ts <- sort . concat <$> (forM [1..n] $ \\i -> map (\\(j, x) -> (x, i, j)) . zip [1..n] <$> getInts)\n let\n (s1, s2) = splitAt n ts\n g1 (x, _, _) = x\n g2 (_, y, _) = y\n g3 (_, _, z) = z\n s = foldl' merge (Seq.fromList $ sortBy (\\p1 p2 -> compare (g2 p1) (g2 p2)) $ (0, 0, 0) : s1) s2\n k = Seq.length s - 1\n results = tail $ toList s\n C.putStrLn $ C.pack $ show k\n C.putStrLn $ C.pack $ unwords $ map show $ map g1 results\n C.putStrLn $ C.pack $ show k\n mapM_ (\\(u, v) -> C.putStrLn $ C.pack $ show u ++ \" \" ++ show v) $ zip [1..k-1] $ map g3 results\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap.Strict as M\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n ts <- sort . concat <$> (forM [1..n] $ \\i -> map (\\(j, x) -> (x, i, j)) . zip [1..n] <$> getInts)\n let (s1, s2) = partition (\\(_, i, j) -> i == j) ts\n g (x, _, _) = x\n cmp t1 t2 = g t1 == g t2\n gs = groupBy cmp s2\n m = length gs\n z = n + m\n C.putStrLn $ C.pack $ show z\n let\n findTop mp i\n | p == i = (mp, p)\n | otherwise = (update p' i mp', p')\n where\n p = mp M.! i\n (mp', p') = findTop mp p\n update x = M.update (\\_ -> Just x)\n addOne pr (k, ts) = foldl' mergeTwo pr ts\n where\n mergeTwo (ss, mp, ps) (x, i, j) = (ss', mp', ps')\n where\n (ps1, p) = findTop ps i\n (ps2, q) = findTop ps1 j\n ps' = update k p $ update k q ps2\n mp' = update k p $ update k q mp\n ss' = M.alter (\\_ -> Just x) k ss\n inits = M.fromList $ zip [1..z] [1..z]\n (salaries, parents, _) = foldl' addOne (ss, inits, inits) $ zip [n+1..] gs\n ss = foldl' (\\mp (x, i, _) -> M.alter (\\_ -> Just x) i mp) M.empty s1\n C.putStrLn $ C.pack $ unwords $ map show $ M.elems salaries\n C.putStrLn $ C.pack $ show z\n mapM_ (\\(i, j) -> C.putStrLn $ C.pack $ show i ++ \" \" ++ show j) $ take (z - 1) $ M.toList parents\n"}], "src_uid": "ff8219b0e4fd699b1898500664087e90"} {"source_code": "-- Codeforces 282A\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n replicateM n getLine >>= putStrLn . show . sum . map solve where\n solve :: [Char] -> Int\n solve [_, '+', _] = 1\n solve [_, '-', _] = -1", "positive_code": [{"source_code": "main = interact $ show . sum . map (\\s -> if '+' `elem` s then 1 else -1) . tail . lines"}, {"source_code": "solve :: String -> Int\nsolve all = \n foldl (\\acc x-> if elem '+' x then acc + 1 else acc - 1) 0 $ tail$lines all\nmain = do\n all <- getContents\n print $ solve all\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [String] -> Int\nsolve [] = 0\nsolve (l:s)\n | '-' `elem` l = solve s - 1\n | '+' `elem` l = solve s + 1\n | otherwise = solve s\n\nmain :: IO ()\nmain = liftM (tail . lines) getContents >>= print . solve\n"}, {"source_code": "import Data.List\n\nmain = do\n\tn <- getInt\n\toperations <- sequence $ map (\\i -> getLine) [1..n]\n\tlet res = foldr (\\curr acc -> if (curr !! 1 == '+') then acc + 1 else acc - 1) 0 operations\n\tputStrLn $ show res\n\t\ngetInt::IO Int\ngetInt = do\n\tres <- getLine\n\treturn $ readInt res\n\t\nreadInt::String -> Int\nreadInt str = read str"}, {"source_code": "import Data.List\n\nmain = do\n\tn <- getInt\n\toperations <- sequence $ map (\\i -> getLine) [1..n]\n\tlet res = foldr (\\curr acc -> if (isInfixOf \"+\" curr) then acc + 1 else acc - 1) 0 operations\n\tputStrLn $ show res\n\t\ngetInt::IO Int\ngetInt = do\n\tres <- getLine\n\treturn $ readInt res\n\t\nreadInt::String -> Int\nreadInt str = read str"}, {"source_code": "import Control.Monad\nimport Data.List\n\nf :: [String] -> Int\nf (a:rst)\n | \"++\" `isInfixOf` a = 1 + f rst\n | \"--\" `isInfixOf` a = (-1) + f rst\nf [] = 0\n\nmain :: IO ()\nmain = do\n numLines <- getLine\n inputs <- replicateM (read numLines) getLine\n putStrLn $ show $ f inputs\n"}, {"source_code": "import Control.Monad\n\ncount :: Char -> [String] -> Int\ncount c ss = length $ filter (\\s -> elem c s) ss\n\nmain = do\n input <- getLine\n commands <- replicateM (read input) getLine\n print $ (count '+' commands) - (count '-' commands)"}, {"source_code": "import Control.Monad\n\nmain = interact $ show.sum.map(\\x -> if( x!!1 == '-') then -1 else 1).tail.lines\n"}, {"source_code": "solve xs = sum [if x !! 1 == '+' then 1 else -1 | x <- xs] \nmain = interact $ show . solve . tail . lines"}, {"source_code": "module Main where\n\nsolve line =\n plus - minus\n where\n plus = length $ filter (\\x -> elem '+' x) line\n minus = length $ filter (\\x -> elem '-' x) line \n\nmain = do\n _ <- getLine\n rules <- getContents\n print $ solve $ lines rules\n\n"}, {"source_code": "import Control.Applicative\n\n\nprocess a = a2-a1\n where a1= length $ filter (\\z->z==\"--X\"||z==\"X--\") a\n a2= length $ filter (\\z->z==\"++X\"||z==\"X++\") a\n\nmain::IO ()\nmain=do\n getLine\n a<-lines <$> getContents\n print $ process a\n"}, {"source_code": "main = do\n\tnumberString <- getLine\n\tlet number = read numberString :: Int\n\tsumma number 0\n\nsumma :: Int -> Int -> IO ()\nsumma 0 suma = print suma\nsumma i suma = do\n\tstat <- getLine\n\tif elem '+' stat\n\t\tthen summa (i-1) (suma+1)\n\t\telse summa (i-1) (suma-1)"}, {"source_code": "solve' :: String -> Int\nsolve' str = case str of\n\t\t\t\t\"X++\" -> 1\n\t\t\t\t\"X--\" -> -1\n\t\t\t\t\"++X\" -> 1\n\t\t\t\t\"--X\" -> -1\n\t\t\t\totherwise -> 0\n\nsolve :: IO String -> IO Int\nsolve x = fmap (sum.map solve'.words) x\n\nmain :: IO()\nmain = solve getContents >>= print"}, {"source_code": "import Data.List (foldl')\n\nmain :: IO ()\nmain = getContents >>= print . solve . tail . lines\n\nsolve :: [String] -> Int\nsolve = foldl' f 0\n where f n \"++X\" = n + 1\n f n \"X++\" = n + 1\n f n \"--X\" = n - 1\n f n \"X--\" = n - 1\n f n _ = n\n"}, {"source_code": "import Prelude hiding (readList)\nimport Control.Monad\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\ninterpLine :: Int -> String -> Int\ninterpLine x s\n | '+' `elem` s = x+1\n | otherwise = x-1\n\nmain :: IO ()\nmain = do\n [n] <- readList' (undefined::Int)\n lines <- replicateM n getLine\n print $ foldl interpLine 0 lines\n"}, {"source_code": "exec :: Int -> [String] -> Int\nexec x [] = x\nexec x (n:ns)\n | n !! 1 == '+' = exec (x + 1) ns\n | otherwise = exec (x - 1) ns\n\nmain = do\n n <- getLine\n interact $ show . exec 0 . lines\n"}, {"source_code": "import Data.List\nmain=interact$show.solve.parse\nparse=map(\\(_:l:_)->l).tail.lines\nsolve x=length p-length m where (p,m) = partition (== '+') x"}, {"source_code": "-- import Debug.Trace\n-- import System.IO.Unsafe\n-- import Text.Printf\nimport System.IO\nimport Control.Monad\nimport Data.List\n\nglwr = fmap (map read . words) getLine\n\nmain = do\n hSetBuffering stdout NoBuffering\n solve\n\nsolve :: IO ()\nsolve = do\n n:_ <- glwr\n strs <- forM [1..n] $ const getLine\n print $ bit n strs\n\nbit :: Int -> [String] -> Int\nbit n = foldr ko 0\n\nko s acc = case s!!1 of\n '+' -> acc+1\n _ -> acc-1\n"}, {"source_code": "solve :: [String] -> Int\nsolve [] = 0\nsolve (x:xs)\n | x !! 1 == '+' = 1 + solve xs\n | otherwise = solve xs - 1\n\nparse :: String -> String\nparse = show . solve . tail . words\n\nmain = interact parse"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine\n ss <- replicateM n getLine\n print $ solve ss\n\nsolve :: [String] -> Int\nsolve ss = (length (filter ((1==).op) ss)) - (length (filter ((-1==).op) ss))\n\nop xs\n | xs == \"++X\" = 1\n | xs == \"--X\" = -1\n | xs == \"X++\" = 1\n | xs == \"X--\" = -1\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inp <- replicateM n getLine\n let pluses = length . filter (elem '+') $ inp\n minuses = n - pluses\n print (pluses - minuses)\n"}, {"source_code": "main = interact $ show . f . tail . lines\n\nf [] = 0\nf (a:b) = (if elem '+' a then 1 else -1) + f b\n"}, {"source_code": "module Main where\nimport Control.Applicative\nmain = do\n commandCount <- read <$> getLine\n mapM (\\_ -> getLine)[1..commandCount] >>= \\commands -> print $ foldl interpreter 0 commands\n where interpreter x c | (c == \"X++\"|| c == \"++X\") = x + 1 | otherwise = x -1\n"}, {"source_code": "main = interact $ show . sum . map (\\x -> if elem '-' x then -1 else 1) . tail . lines\n"}, {"source_code": "while i n = do\n if i == 0 then\n print n\n else do\n s <- getLine\n if s!!1 == '-' then\n while (i - 1) (n - 1)\n else\n while (i - 1) (n + 1)\nmain = do\n input <- getLine\n let n = read input :: (Int)\n while n 0\n"}, {"source_code": "import Control.Monad\nmain = (getLine >>= (\\l -> replicateM (read l) getLine)) >>= (print . foldr (\\l -> if elem '-' l then pred else succ) 0)"}, {"source_code": "main=interact$show.sum.map(\\x->if x!!1=='+' then 1 else -1).tail.lines"}, {"source_code": "main = interact$show.sum.map (\\x->if x == '+' then 1 else -1).map head.map tail.tail.lines\n"}, {"source_code": "main = interact f\n\nf = show . sum . map g . tail . lines\n\ng (_:c:_) | c == '+' = 1\n | otherwise = -1"}, {"source_code": "main :: IO ()\nmain = do\n n <- getLine >>= return . read\n s <- sequence $ replicate n getLine\n putStrLn $ show $ sum $ map\n (\\x -> if x == \"X++\" || x == \"++X\" then 1 else -1)\n s"}, {"source_code": "main :: IO ()\nmain = do\n n <- getLine\n interpBit 0 $ read n\n\ninterpBit :: Int -> Int -> IO ()\ninterpBit m 0 = print m >>= return\ninterpBit m n = do\n [_,o,_] <- getLine\n if o == '+'\n then interpBit (m + 1) (n - 1)\n else interpBit (m - 1) (n - 1)\n\n"}, {"source_code": "module Main where\n\nsolve :: [String] -> Int\nsolve = solve' 0\n where\n solve' x [] = x\n solve' x (s:ss)\n | s!!1 == '+' = solve' (x+1) ss\n | s!!1 == '-' = solve' (x-1) ss\n | otherwise = solve' x ss\n\nmain = getLine >> getContents >>= (print . solve . lines)\n"}, {"source_code": "import Control.Applicative\nmain= do\n\tn<-read <$> getLine::IO Int\n\ts<- length .filter ( elem '+'). lines <$> getContents\n\tlet t = s+s -n\n\tprint t\n"}, {"source_code": "{-\nA. Bit++\n=========\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nThe classic programming language of Bitland is Bit++. This language is so peculiar and complicated.\n\nThe language is that peculiar as it has exactly one variable, called x. Also, there are two operations:\n\nOperation ++ increases the value of variable x by 1.\nOperation -- decreases the value of variable x by 1.\n\nA statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters \"+\", \"-\", \"X\". Executing a statement means applying the operation it contains.\n\nA programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.\n\nYou're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).\n\nInput\n------\nThe first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009150) \u2014 the number of statements in the programme.\n\nNext n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter \u00abX\u00bb). Thus, there are no empty statements. The operation and the variable can be written in any order.\n\nOutput\n-------\nPrint a single integer \u2014 the final value of x.\n\nSample test(s)\n--------------\ninput\n```\n1\n++X\n```\noutput\n```\n1\n```\n\ninput\n```\n2\nX++\n--X\n```\noutput\n```\n0\n```\n-}\n\nbitCompute :: [String] -> Int\nbitCompute xs = sum $ map (\\s -> if '+' `elem` s then 1 else -1) xs\n\nmain = do\n input <- getContents\n let xs = tail $ lines input\n print $ bitCompute xs\n"}, {"source_code": "main = do\n n <- readLn\n arr <- sequence $ replicate n getLine\n let m = length (filter (`elem` [\"X++\", \"++X\"]) arr) - length (filter (`elem` [\"X--\", \"--X\"]) arr)\n print m"}, {"source_code": "import Control.Monad ( replicateM )\nfolder :: Int -> String -> Int\nfolder a s = if '+' `elem` s then (a + 1) else (a - 1)\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n ans <- foldl folder 0 <$> ( replicateM n getLine )\n print ans\n "}, {"source_code": "import Control.Monad\n\nmain = getLine >>= (flip replicateM $ getLine).read >>= putStrLn.show.solve\n\noperate (o:os)\n | o == '+' = 1\n | o == '-' = -1\n\nsolve (op:[]) = operate $ tail op\nsolve (op:ops) = (operate $ tail op) + (solve ops)\n"}, {"source_code": "import Data.Char\n\nans str = foldl check 0 str\ncheck a xs\n | elem '+' xs = a+1\n | otherwise = a-1\n\nmain = do\n n<-getLine\n m<-getContents\n print.ans $ lines m"}, {"source_code": "main :: IO ()\nmain = getLine >> getContents >>= print . foldl solve 0 . lines\n\nsolve :: Int -> String -> Int\nsolve a \"X++\" = a+1\nsolve a \"++X\" = a+1\nsolve a \"X--\" = a-1\nsolve a \"--X\" = a-1\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . f . tail . lines\n\nf :: [String] -> Int\nf [] = 0\nf (x:xs) \n | '+' `elem` x = f xs + 1\n | '-' `elem` x = f xs - 1\n"}, {"source_code": "import Data.List\nsolve :: [String] -> Int\nsolve = sum . map (\\x -> if \"++\" `isInfixOf` x then 1 else -1)\n\nwork :: String -> String\nwork = show . solve . tail .lines\n\nmain :: IO ()\nmain = interact work\n\n\n \n"}, {"source_code": "main = print . sum . map (\\l -> if elem '+' l then 1 else -1) . tail . lines =<< getContents"}, {"source_code": "main = print . sum . map (\\x -> if x then 1 else -1) . map (elem '+') . tail . lines =<< getContents"}, {"source_code": "import Control.Monad\n\nsolve :: [[Char]] -> [Char]\nsolve = unwords\n\ncount :: [Char] -> Int\ncount xs = foldl (\\acc elem -> if elem == '+' then acc+1 else acc) 0 xs\n\nmain = do \n input1 <- getLine\n let num = (read input1 :: Int)\n lines <- replicateM num getLine\n let s = (count (unwords lines)) - num\n print s\n\n"}, {"source_code": "import Data.Typeable\n\nparse x = read x :: Int\n\nsolverec :: Int -> IO Int\nsolverec 0 = return 0\nsolverec x = do\n raw <- getLine\n acc <- return (if raw!!1=='+' then 1 else -1)\n sub <- solverec $ x-1\n return (acc+sub)\n \nmain = do\n raw <- getLine\n let n = parse raw\n res <- solverec n\n print res"}, {"source_code": "import Control.Monad\n\n\nparse s = case s of\n \"++X\" -> 1\n \"X++\" -> 1\n \"--X\" -> -1\n \"X--\" -> -1\n _ -> 0\n\n\n\nmain = do\n d <- getContents\n let (n:ls) = lines d\n let ops = map parse ls\n print $ sum ops\n"}, {"source_code": "import Data.List (foldl')\n\nmain :: IO ()\nmain = interact $ show . foldl' (+) 0 . map solve . tail . words\n\nsolve :: String -> Int\nsolve (_:'+':_) = 1\nsolve (_:'-':_) = -1"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (sort, group)\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = print . exec . map (head . tail) =<< flip replicateM getLine =<< readLn\n where exec = count . map (pred . length) . group . sort . (\"+-\"++)\n count [p,m] = p - m"}, {"source_code": "import Control.Monad\nimport Data.List\n\nconvert :: String -> Int\nconvert x = if x!!1 == '+' then 1 else -1\n\nmain :: IO ()\nmain = do\n str <- getLine\n inputs <- replicateM (read str) getLine\n print $ sum $ map convert inputs"}, {"source_code": "\nimport Data.Char(digitToInt)\n\ntoInt::[Char]->Int\ntoInt x =\n let \n toInt'::[Char]->Int->Int\n toInt' y z =\n if null y\n then z\n else toInt' (tail y) (z*10+(digitToInt (head y)-digitToInt '0'))\n in toInt' x 0\n\nadd::[Char]->Bool\nadd x =\n if null x\n then False\n else if (head x) == '+'\n then True\n else add (tail x)\n\ngetAddCnt::[[Char]]->Int\ngetAddCnt x =\n if null x\n then 0\n else if add $ head x\n then 1 + (getAddCnt $ tail x)\n else getAddCnt $ tail x\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n line = lines input\n n = toInt $ head line\n addCnt = getAddCnt $ tail line\n subCnt = n-addCnt\n print $ addCnt-subCnt\n"}, {"source_code": "import qualified Data.Map as Map\nimport Control.Monad\n \ng [] = 0\ng (x : xs) = do\n case Map.lookup x (Map.fromList [(\"++X\", 1), (\"X++\", 1), (\"--X\", -1), (\"X--\", -1)]) of\n Just y -> y + (g $ xs)\n Nothing -> g $ xs\n \nmain = do\n b <- readLn\n inputs <- replicateM b getLine\n putStrLn $ show $ g inputs"}, {"source_code": "import Control.Monad\nmain = do\n n<-getLine\n arr<-replicateM (read n) getLine\n print ( (length (filter f arr)) - (length (filter f' arr)) )\n where\n f x = (x==\"X++\") || (x==\"++X\")\n f' x = not (f x)\n \n \n \n"}, {"source_code": "import Data.List\nimport Data.Char\n\nmain = do\n\tinput <- getContents\n\tputStrLn $ show $ answer $ tail $ lines input\n\n\nanswer x = (length $ filter (isInfixOf \"++\") x) - (length $ filter (isInfixOf \"--\") x)"}, {"source_code": "s x=show$length [i | i<-tail$lines x,elem '+' i] - \tlength [i | i<-tail$lines x,elem '-' i]\nmain=interact$s"}, {"source_code": "f s= if s!!1=='+' then 1 else -1\nmain=interact$show.sum.map f.tail.lines\n"}, {"source_code": "parseOp :: String -> Int\nparseOp \"X++\" = 1\nparseOp \"++X\" = 1\nparseOp \"X--\" = -1\nparseOp \"--X\" = -1\nparseOp _ = 0\n\nmain :: IO ()\nmain = do\n\tcs <- getContents\n\tprint $ sum $ map parseOp $ words cs"}, {"source_code": "import Control.Monad \n\ndata Operation = Inc | Dec deriving (Show, Eq, Ord)\n\nparseLine :: String -> Operation\nparseLine x \n | x `elem` [\"++X\", \"X++\"] = Inc\n | x `elem` [\"--X\", \"X--\"] = Dec\n | otherwise = error \"Unparseble entity\"\n\neval :: Int -> [Operation] -> Int\neval y [] = y\neval y (x:xs)\n | x == Inc = eval (y + 1) xs \n | x == Dec = eval (y - 1) xs \n\nreadNLines :: Int -> IO [String]\nreadNLines n = replicateM n getLine\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n args <- readNLines n\n print $ eval 0 $ map parseLine args"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . tail . lines\n\nsolve :: [String] -> Int\nsolve = foldl run 0\n\nrun :: Int -> String -> Int\nrun x (_ : '+' : _) = x + 1\nrun x (_ : '-' : _) = x - 1\n"}, {"source_code": "import Control.Monad\n\nmain = getLine\n >>= return . (read :: String -> Int)\n >>= \\x -> forM [1..x] (\\i -> getLine >>= return . conversion)\n >>= print . sum\n \nconversion :: String -> Int \nconversion \"++X\" = 1\nconversion \"--X\" = -1\nconversion \"X++\" = 1\nconversion \"X--\" = -1"}, {"source_code": "main = do\n getLine\n ls <- fmap lines getContents\n\n let\n c1 = length $ filter (elem '+') ls\n c2 = length $ filter (elem '-') ls\n print $ c1 - c2"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int \n lines <- getNLines n\n print $ execute lines\n\ngetNLines :: Int -> IO [String]\ngetNLines 0 = return []\ngetNLines n = getLine >>= \\newLine ->\n fmap ([newLine] ++) $ getNLines (n - 1)\n\nexecute :: [String] -> Int\nexecute [] = 0\nexecute (ins:rest) | isInfixOf \"++\" ins = execute rest + 1\n | isInfixOf \"--\" ins = execute rest - 1\n"}, {"source_code": "f s | elem '+' s = 1\n\t| otherwise = -1\nmain = interact $ show . sum . map f . tail . lines"}, {"source_code": "import Data.List\nimport Data.List.Split\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Char as C\n\n(|>) = flip ($)\n\nmain = interact process\n\nprocess contents = let\n ls = contents |> lines |> tail\n in solve ls |> show\n \nsolve ls = let\n plus = ls |> filter ('+' `elem`) |> length\n minus = ls |> filter ('-' `elem`) |> length\n in plus - minus\n "}, {"source_code": "isPlus :: String -> Bool\nisPlus xs\n | (hxs == '+') || (lxs == '+') = True\n | otherwise = False\n where hxs = head xs\n lxs = last xs\n\nisSub :: String -> Bool\nisSub xs\n | (hxs == '-') || (lxs == '-') = True\n | otherwise = False\n where hxs = head xs\n lxs = last xs\n\ngetInput :: String -> [String]\ngetInput xs = tail $ lines xs\n\noperate :: [String] -> Int\noperate [] = 0\noperate (x:xs)\n | isPlus x = 1 + operate xs\n | isSub x = (operate xs) - 1\n\nmain :: IO ()\nmain = do n <- getContents\n putStr $ show $ operate $ getInput n\n"}, {"source_code": "recognize (x:y:z:_)\n\t|(x:[y])==\"++\" || (y:[z])==\"++\" = \"++\"\n\t|otherwise = \"--\"\nsolve []=0\nsolve (x:xs)\n\t|x==\"++\" =1+solve xs\n\t|otherwise=0-1+solve xs\nmain=getLine>>=(\\x->interact$show.solve.map recognize.take (read x::Int).lines)"}, {"source_code": "main = readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\x-> interact $ show.solve. take (read x) . lines\n where\n solve=foldr f 0\n where f x y | x== \"++X\" || x== \"X++\"= 1+y\n | otherwise= y-1"}], "negative_code": [{"source_code": "import Control.Applicative\n\n\nprocess a = a2-a1\n where a1= length $ filter (\\z->z==\"--X\"||z==\"X--\") a\n a2= length $ filter (\\z->z==\"--X\"||z==\"X--\") a\n\nmain::IO ()\nmain=do\n getLine\n a<-lines <$> getContents\n print $ process a\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [String] -> Int\nsolve xs = a - (length xs - a)\n where a = length $ filter (==\"X++\") xs\n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- replicateM n $ getLine\n print $ solve xs"}, {"source_code": "main = do \n getLine\n l <- getContents\n putStrLn $ show . sum . map convert . tail . lines $ l\n where \n convert \"++X\" = 1\n convert \"X--\" = -1\n\n--main = interact $ show . sum . map convert . tail . lines\n-- where \n-- convert \"++X\" = 1\n-- convert \"X--\" = -1"}, {"source_code": "main = do \n l <- getContents\n putStrLn $ show . sum . map (\\x -> if x == \"++X\" then 1 else -1) . tail . lines $ l"}, {"source_code": "import Control.Monad\n\nmain = getLine >>= (flip replicateM $ getLine).read >>= putStrLn.show.solve\n\noperate (o:os)\n | o == 'X' = 0\n | o == '+' = 1\n | o == '-' = -1\n\nsolve (op:[]) = operate op\nsolve (op:ops) = (operate $ tail op) + (solve ops)\n"}, {"source_code": "import Data.Char\n\nmain = interact $ unlines . map (\\s -> if foldl(\\acc c -> if isUpper c then acc else False) True $ tail s then map (\\c -> if isUpper c then toLower c else toUpper c) s else s) . lines"}, {"source_code": "main = interact $ show . sum . map (\\s -> if head s == '+' then length s else length s * (-1)) . map (filter (/='X')) . tail . lines"}, {"source_code": "apply :: Int -> String -> Int\napply y (x:s:xs)\n | s == '+' = y + 1\n | s == '-' = y - 1\n\nrun :: Int -> Int -> IO Int\nrun m n\n | m == 0 = return n\n | otherwise = getLine >>= run (m-1) . apply n\n\nmain = getLine >>= go 0 . read where go = flip run\n"}, {"source_code": "import Data.Char\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve (x : xs) = toUpper x : xs\n"}, {"source_code": "main = interact $ show . f . tail . lines\nf [] = 0\nf (a:b) = if elem '+' a then 1 else -1"}], "src_uid": "f3cf7726739290b280230b562cac7a74"} {"source_code": "import qualified Data.ByteString.Char8 as B\n\nsum_lists x y = map (\\(a, b) -> a+b) $ zip x y\n\nmax_val = 1000001 \n\npositive = \\x -> if x < 0 then 0 else 1\nnegative = \\x -> if x > 0 then 0 else 1\n\nleft x = scanl (+) 0 (map positive x)\nright x = scanr (+) 0 (map negative x)\n\nsolve :: [Int] -> Int\nsolve x = foldl min max_val (init . tail $ sum_lists p1 p2)\n where\n p1 = left x\n p2 = right x\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain=B.readFile\"input.txt\">>=writeFile\"output.txt\".show.solve.tail.map(signum.readInt).B.words\n\n--main = do\n-- handleIn <- openFile \"input.txt\" ReadMode\n-- n' <- hGetLine handleIn\n-- let n = read n' :: Int\n-- t' <- hGetLine handleIn\n-- let t = (map read (words t')) :: [Int]\n-- handleOut <- openFile \"output.txt\" WriteMode\n-- hPrint handleOut $ solve t\n-- hFlush handleOut\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain=B.readFile\"input.txt\">>=writeFile\"output.txt\".show.solve.tail.map(signum.readInt).B.words\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nsolve :: [Int] -> Int\nsolve (x:xs) = case nonzero of\n [] -> zeronum\n _ -> (zeronum+).minimum $ zipWith (+) (scanl positive (sum[1|x>0]) nonzero) (init $ scanr negative 0 nonzero)\n where\n nonzero = filter (0/=) xs\n zeronum = sum[1|0<-x:xs]\n\npositive x y = if y>0 then x+1 else x\nnegative x y = if x<0 then y+1 else y"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n input <- openFile \"input.txt\" ReadMode\n hGetLine input\n xs <- unfoldr (B.readInt . B.dropWhile isSpace) <$> (B.hGetLine input)\n\n let\n a = scanl1 (+) $ map (fromEnum . (>= 0)) xs\n b = scanr1 (+) $ map (fromEnum . (<= 0)) xs\n\n output <- openFile \"output.txt\" WriteMode\n hPrint output $ minimum $ zipWith (+) a $ tail b\n hClose output\n"}, {"source_code": "\nimport Array (Array, (!), array, listArray)\nimport Char (isDigit, ord)\nimport Data.List (foldl1')\nimport IO\nimport Monad (liftM)\nimport Prelude hiding (read)\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\ninfix 3 ?\n\nminimum' :: Ord a => [a] -> a\nminimum' = foldl1' (\\a b -> a < b ? a $ b)\n\nsolve :: Int -> Array Int Int -> Int\nsolve n a = minimum' [(l ! i) + (r ! i) | i <- [1..n-1]]\n where\n l = array (0, n) ((0,0) : [(i, l ! (i-1) + (a ! i >= 0 ? 1 $ 0)) | i <- [1..n]])\n r = array (0, n) ((n,0) : [(i, r ! (i+1) + (a ! (i+1) <= 0 ? 1 $ 0)) | i <- [0..n-1]])\n\nread :: String -> Int\nread (c:s)\n | c == '-' = (-1) * (read' 0 s)\n | otherwise = read' 0 (c:s)\n where\n read' a [] = a\n read' a (c:s) = read' (10 * a + ord c - ord '0') s\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n n <- liftM read (hGetLine hInput)\n as <- liftM (listArray (1,n) . map read . words) (hGetLine hInput)\n hPrint hOutput $ solve n as\n\n hClose hInput\n hClose hOutput\n"}], "negative_code": [{"source_code": "\nimport Array (Array, (!), array, listArray)\nimport Char (isDigit, ord)\nimport Data.List (foldl1')\nimport IO\nimport Monad (liftM)\nimport Prelude hiding (read)\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\ninfix 3 ?\n\nminimum' :: Ord a => [a] -> a\nminimum' = foldl1' (\\a b -> a < b ? a $ b)\n\nsolve :: Int -> Array Int Int -> Int\nsolve n a = minimum' [(l ! i) + (r ! i) | i <- [1..n-1]]\n where\n l = array (0, n) ((0,0) : [(i, l ! (i-1) + (a ! i >= 0 ? 1 $ 0)) | i <- [1..n]])\n r = array (0, n) ((n,0) : [(i-1, r ! i + (a ! i <= 0 ? 1 $ 0)) | i <- [1..n]])\n\nread :: String -> Int\nread s = read' 0 (dropWhile (not . isDigit) s)\n where\n read' a [] = a\n read' a (c:s)\n | isDigit c = read' (10 * a + ord c - ord '0') s\n | otherwise = error \"\"\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n n <- liftM read (hGetLine hInput)\n as <- liftM (listArray (1,n) . map read . words) (hGetContents hInput)\n hPrint hOutput $ solve n as\n\n hClose hInput\n hClose hOutput\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain=B.readFile\"input.txt\">>=writeFile\"output.txt\".parseOutput.solve.parseInput\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nparseInput = tail.map (signum.readInt).B.words\nparseOutput = show\n\nsolve :: [Int] -> Int\nsolve xs = case nonzero of\n [] -> zeronum\n _ -> (zeronum+).pred.minimum $ zipWith (+) (tail$scanl positive 0 nonzero) (init$scanr negative 0 nonzero)\n where\n nonzero = filter (0/=) xs\n zeronum = sum[1|0<-xs]\n\npositive x y = if y>0 then x+1 else x\nnegative x y = if x<0 then y+1 else y"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain=B.readFile\"input.txt\">>=writeFile\"output.txt\".parseOutput.solve.parseInput\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nparseInput = map (signum.readInt).B.words\nparseOutput = show\n\nsolve :: [Int] -> Int\nsolve xs = minimum $ zipWith (+) (scanl positive 0 xs) (scanr negative 0 xs)\n\npositive x y = if y>=0 then x+1 else x\nnegative x y = if y<=0 then y+1 else x+1"}, {"source_code": "import System.IO\n\nleft :: [Integer] -> [Integer] -> (Integer -> Bool) -> [Integer]\nleft acc [] f = acc\nleft (a:acc) (x:xs) f\n | not (f x) = left ( (a+1):a:acc ) xs f\n | otherwise = left ( a:a:acc ) xs f\n\nsum_lists :: [Integer] -> [Integer] -> [Integer]\nsum_lists [] [] = []\nsum_lists (x:xs) (y:ys) = (x+y):(sum_lists xs ys)\n\nmax_val = 1000001 \n\nsolve :: [Integer] -> Integer\nsolve x = foldl min max_val (sum_lists p1 p2)\n where\n p1 = reverse (left [0] x (<0) )\n p2 = left [0] (reverse x) (>0)\n\nmain = do\n handleIn <- openFile \"input.txt\" ReadMode\n n' <- hGetLine handleIn\n let n = read n' :: Integer\n t' <- hGetLine handleIn\n let t = (map read (words t')) :: [Integer]\n handleOut <- openFile \"output.txt\" WriteMode\n hPutStrLn handleOut ( show ( solve t ) )\n hFlush handleOut\n"}], "src_uid": "165e18e39d2f60c72f22e3027a29a742"} {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nintersectM :: (Int, Int) -> (Int, Int) -> Maybe (Int, Int)\nintersectM (l1, r1) (l2, r2) = if rr < ll then Nothing else Just (ll, rr)\n where\n ll = max l1 l2\n rr = min r1 r2\n\nsolve :: (Int, Int) -> (Int, Int) -> Int\nsolve (l1, r1) (l2, r2) = \n case mm of\n Nothing -> l1 + l2\n Just (ll, rr) -> ll\n where\n mm = intersectM (l1, r1) (l2, r2)\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [l1, r1, l2, r2] <- B8.getLine <&> readIntB8s\n let answer = solve (l1, r1) (l2, r2)\n printf \"%d\\n\" answer \n\n", "positive_code": [{"source_code": "module Main (main)\nwhere\n\nimport Data.List (intercalate, words)\n\nmain :: IO ()\nmain = intercalate \"\\n\" <$> map show <$> map minElem <$> map readNums <$> (read <$> getLine >>= readNLines) >>= putStrLn\n\nminElem :: (Int, Int, Int, Int) -> Int\nminElem (a, b, c, d) \n | c `between` (a, b) = c\n | a `between` (c, d) = a\n | otherwise = a + c\n where x `between` (y, z) = x >= y && x <= z\n\nreadNLines :: Int -> IO [String]\nreadNLines n = sequence $ replicate n getLine\n\nreadNums :: String -> (Int, Int, Int, Int)\nreadNums str = toQuadruple $ map read $ words str \n where toQuadruple [a, b, c, d] = (a, b, c, d)\n toQuadruple _ = undefined\n\n"}, {"source_code": "import Control.Monad\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n [l1,r1,l2,r2] <- fmap (fmap read)\n . fmap words\n\t\t $ getLine :: IO [Int]\n print $ solve l1 r1 l2 r2\n \nsolve a1 b1 a2 b2\n | b1 < a2 || b2 < a1 = a1 + a2\n | otherwise = max a1 a2\n"}], "negative_code": [{"source_code": "module Main (main)\nwhere\n\nimport Data.List (intercalate, words)\n\nmain :: IO ()\nmain = intercalate \"\\n\" <$> map show <$> map minElem <$> map readNums <$> (read <$> getLine >>= readNLines) >>= putStrLn\n\nminElem :: (Int, Int, Int, Int) -> Int\nminElem (a, b, c, d) \n | c `between` (a, b) = c\n | a `between` (c, d) = a\n | otherwise = b + c\n where x `between` (y, z) = x >= y && x <= z\n\nreadNLines :: Int -> IO [String]\nreadNLines n = sequence $ replicate n getLine\n\nreadNums :: String -> (Int, Int, Int, Int)\nreadNums str = toQuadruple $ map read $ words str \n where toQuadruple [a, b, c, d] = (a, b, c, d)\n toQuadruple _ = undefined\n\n"}], "src_uid": "c783eaf1bf7e4e7321406431030d5aab"} {"source_code": "-- import Debug.Trace\r\n\r\nimport Data.Bits\r\n\r\ntype InType = (Int, Int)\r\ntype OutType = Bool\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\nsolve :: InType -> OutType\r\nsolve (u, v)\r\n | u > v = False\r\n | otherwise = go 0 0 0\r\n where go :: Int -> Int -> Int -> Bool\r\n go 31 _ _ = True\r\n go b o1 o2\r\n | o1 < o2 = False\r\n | otherwise = go (b + 1) (o1 + f b u) (o2 + f b v)\r\n f x b = if testBit b x then 1 else 0\r\n\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = (u, v)\r\n where [u, v] = toArr s\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showb . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showb True = \"YES\"\r\n showb False = \"NO\"\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Bits\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [q] <- readInts\n replicateM_ q $ do\n [u, v] <- readInts\n let\n fun i x = popCount $ x .&. (2 * bit i - 1)\n ok = v >= u && and [fun i v <= fun i u | i <- [0..29]]\n lift $ P.putStrLn $ if ok\n then P.pack \"YES\"\n else P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "a4e605859608d0c730ecbbee9ffc92d7"} {"source_code": "f [] cnt ans\n | cnt /= 0 = -1\n | otherwise = ans\nf (')':xs) cnt ans = f xs (cnt-1) ans2\n where ans2 = if cnt > 0 then ans else ans+2\nf (_:xs) cnt ans = f xs (cnt+1) ans\nmain = do\n getLine\n s <- getLine\n print $ f s 0 0", "positive_code": [{"source_code": "f [] cnt ans\n | cnt /= 0 = -1\n | otherwise = ans\nf (')':xs) cnt ans\n | cnt <= 0 = f xs (cnt-1) (ans+2)\n | otherwise = f xs (cnt-1) ans\nf (_:xs) cnt ans = f xs (cnt+1) ans\nmain = do\n getLine\n s <- getLine\n print $ f s 0 0"}, {"source_code": "f [] cnt ans = if cnt /= 0 then -1 else ans\nf (')':xs) cnt ans = f xs (cnt-1) ans2\n where ans2 = if cnt > 0 then ans else ans+2\nf (_:xs) cnt ans = f xs (cnt+1) ans\nmain = do\n getLine\n s <- getLine\n print $ f s 0 0"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = do\n getLine\n str <- getLine\n if length (filter (== '(') str) /= length (filter (== ')') str)\n then print $ -1\n else print $ f 0 str\n\nf _ [] = 0\nf x ('(':cs) = f (x + 1) cs\nf x (')':cs) = let x' = x - 1 in\n if x' < 0 then 1 + g x' cs\n else f x' cs\n\ng _ [] = 0\ng x ('(':cs) = let x' = x + 1 in\n if x' >= 0 then 1 + f x' cs\n else 1 + g x' cs\ng x (')':cs) = 1 + g (x - 1) cs\n"}], "negative_code": [], "src_uid": "e3275cd360d8f46cbbae03dfa86b924a"} {"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines", "positive_code": [{"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines\n"}, {"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines"}, {"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines\n"}, {"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Array as Arr\n\ns(h:t) = result ++ [] where\n [n,m] = map read $ words h\n rawTells = map tl t where\n tl ('+':n) = (read n :: Int, (1, 0))\n tl ('-':n) = (read n :: Int, (0, 1))\n cmb (a,b) (c,d) = (a+c, b+d)\n tells = Arr.assocs $ Arr.accumArray cmb (0,0) (1, n) $ rawTells\n liesByDefault = sum $ map (fst . snd) $ tells\n changeNeeded = liesByDefault-(n-m)\n suspects = map fst $ filter ((== changeNeeded).uncurry (-).snd) $ tells\n ss = Set.fromList suspects\n result = map eval rawTells where\n eval (j, _) | Set.member j ss && length suspects > 1 = \"Not defined\"\n eval (j, (k, nk)) | Set.member j ss == (k>nk) = \"Truth\"\n | otherwise = \"Lie\"\n \nmain=interact$unlines.s.lines"}, {"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines\n"}, {"source_code": "import Data.Set\nimport Data.Array\nq '+'=(1,0)\nq '-'=(0,1)\nz=fmap\nc(a,b)(c,d)=(a+c,b+d)\ns(h:l)=z e r where [n,m]=z read$words h;r=z(\\(c:n)->(read n+0,q c))l;t=assocs$accumArray c(0,0)(1,n)r;s=fromList$z fst$Prelude.filter((==sum(z(fst.snd)t)-n+m).uncurry(-).snd)t;e(j,(k,n))|m&&size s>1=\"Not defined\"|m==(k>n)=\"Truth\"|1>0=\"Lie\"where m=member j s\nmain=interact$unlines.s.lines\n"}], "negative_code": [{"source_code": "import qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Control.Arrow\n\ns(h:t) = result ++ [] where\n [n,m] = map read $ words h\n rawTells = map tl t where\n tl ('+':n) = (read n :: Int, (1, 0))\n tl ('-':n) = (read n :: Int, (0, 1))\n cmb (a,b) (c,d) = (a+c, b+d)\n tells = Map.toList $ Map.fromListWith cmb $ rawTells\n liesByDefault = sum $ map (fst . snd) $ tells\n changeNeeded = liesByDefault-(n-m)\n suspects = map fst $ filter ((== changeNeeded).uncurry (-).snd) $ tells\n ss = Set.fromList suspects\n result = map eval rawTells where\n eval (j, _) | Set.member j ss && length suspects > 1 = \"Not defined\"\n eval (j, (k, nk)) | Set.member j ss == (k>nk) = \"Truth\"\n | otherwise = \"Lie\"\n \nmain=interact$unlines.s.lines"}], "src_uid": "c761bb69cf1b5a3dbe38d9f5c46e9007"} {"source_code": "solve xs = map (\\x -> if (x `mod` 2 == 0) then 1 else 0) xs\n\nmain = do text <- readFile \"input.txt\"\n writeFile \"output.txt\" (unlines $ map show $ solve $ map read $ tail $ lines text)", "positive_code": [{"source_code": "main = readFile \"input.txt\" >>= writeFile \"output.txt\" . concat . map ((++\"\\n\") . show . (`mod`2) . (+1) . read) . tail . lines\n"}, {"source_code": "main=do{c<-readFile\"input.txt\";writeFile\"output.txt\"$unlines$map((\\x->show$mod(1+x)2).read)$tail$words c}\n"}, {"source_code": "s x=show(mod(1+x)2)++\"\\n\"\nmain=do{c<-readFile\"input.txt\";writeFile\"output.txt\"$foldl(++)\"\"$map(s.read)$tail$words c}\n"}, {"source_code": "s x=show(mod(1+x)2)++\"\\n\"\nmain=do\n c<-readFile\"input.txt\"\n writeFile\"output.txt\"$foldl(++)\"\"$map(s.read)$tail$words c\n"}], "negative_code": [], "src_uid": "d8c4c2d118e07c3b148495fc04d8fcb5"} {"source_code": "import Data.List\n\nget_min :: Maybe Integer -> Integer -> [(Char, Integer)] -> Integer\nget_min _ acum [] = acum\nget_min _ acum (('R', n):rest) = get_min (Just n) acum rest\nget_min Nothing acum (('L', n):rest) = get_min Nothing acum rest\nget_min (Just last_right) acum (('L', n):rest) = get_min (Just last_right) (min acum (div (n - last_right) 2)) rest\n\nmyShow :: Integer -> String\nmyShow n\n | n >= 10^10 = \"-1\"\n | otherwise = show n\n\nprocess :: String -> String\nprocess str =\n let [_, dirs, nums] = lines str\n parts = zip dirs (map read $ words nums)\n in myShow $ get_min Nothing (10^10) parts\n\nmain :: IO ()\nmain = interact process", "positive_code": [{"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n --\n generatedMemo :: S.Set Int -> S.Set Int -> Int -> [Char] -> [Char]\n generatedMemo _ _ 20 accumulator = accumulator\n generatedMemo locLeft locRight n accumulator\n | n `elemSet` locLeft = generatedMemo locLeft locRight (n + 1) $ 'L':accumulator\n | n `elemSet` locRight = generatedMemo locLeft locRight (n + 1) $ 'R':accumulator\n | otherwise = generatedMemo locLeft locRight (n + 1) $ ' ':accumulator\n\n mayMeetF :: ((Char, Int), (Char, Int)) -> Bool\n mayMeetF (('R', _), ('L', _)) = True\n mayMeetF _ = False\n\n diffF :: ((Char, Int), (Char, Int)) -> Int\n diffF (('R', x), ('L', y)) = (y - x) `div` 2\n\n normalized :: [Int] -> [Int]\n normalized (x:xs) = (x:xs)\n normalized [] = [-1]\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n directions <- getLine\n locations <- getLine >>= return . sort . (map readInt) . words\n let dirLoc = directions `zip` locations\n dirLoc2 = 1 `drop` dirLoc\n mayMeet = (mayMeetF `filter`) $ dirLoc `zip` dirLoc2\n diffs = diffF `map` mayMeet\n normaldiff = normalized diffs\n putStrLn $ show $ minimum normaldiff\n"}, {"source_code": "\n\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n _ <- getLine\n lrs <- getLine\n xs <- map readInt.B.words <$> B.getLine\n print . maybe (-1) id $ solve lrs xs\n\nsolve :: String -> [Int] -> Maybe Int\nsolve lrs xs = go0 lrs xs\n where\n go0 ('R':'L':lrs) (x:y:xys) = go (div (y-x) 2) lrs xys\n go0 (_:r:lrs) (_:y:xys) = go0 (r:lrs) (y:xys)\n go0 _ _ = Nothing\n go !res ('R':'L':lrs) (x:y:xys) = go (min res $ div (y-x) 2) lrs xys\n go res (_:r:lrs) (_:y:xys) = go res (r:lrs) (y:xys)\n go res _ _ = Just res\n"}, {"source_code": "import Data.List( minimum)\nmain = do\n n <- getLine\n lrs <- getLine\n xs <- return . map (read::String->Integer) . words =<< getLine\n let distxs = zip lrs xs\n\tfilt [] = []\n\tfilt [p] = []\n\tfilt ((dir1,x1):tl@((dir2,x2):ps)) =\n\t if dir1=='R' && dir2=='L'\n\t\tthen ((x2-x1)`div`2):filt ps\n\t\telse filt tl\n\tcandidate = filt distxs\n if candidate == [] then print $ negate 1\n\t\t\telse print . minimum $ filt distxs\n"}, {"source_code": "import Control.Arrow\nimport Control.Applicative\nimport Data.Int\n\nsolve :: [Char] -> [Int64] -> Int64\nsolve dirs coords = case impacttimes of\n [] -> -1\n x -> minimum x\n where\n impacttimes = solve' dirs coords []\n solve' :: [Char] -> [Int64] -> [Int64] -> [Int64]\n solve' ('R':ds@('L':_)) (n1:cs@(n2:_)) acc = solve' ds cs (((n2 - n1) `div` 2):acc)\n solve' (_:ds) (_:cs) acc = solve' ds cs acc\n solve' _ _ acc = acc\n\nmain :: IO()\nmain = do\n _ <- getLine\n dirs <- getLine\n coords <- (map read . words) <$> getLine\n print $ solve dirs coords\n"}, {"source_code": "import Data.List\n\nmaybe_min :: Maybe Integer -> Integer -> Maybe Integer\nmaybe_min Nothing n = Just n\nmaybe_min (Just n') n = Just $ min n' n\n\nget_min :: Maybe Integer -> Maybe Integer -> [(Char, Integer)] -> Maybe Integer\nget_min _ acum [] = acum\nget_min _ acum (('R', n):rest) = get_min (Just n) acum rest\nget_min Nothing acum (('L', n):rest) = get_min Nothing acum rest\nget_min (Just last_right) acum (('L', n):rest) = get_min (Just last_right) (maybe_min acum (div (n - last_right) 2)) rest\n\nmyShow :: Maybe Integer -> String\nmyShow n = case n of\n Nothing -> \"-1\"\n (Just n') -> show n'\n\nprocess :: String -> String\nprocess str =\n let [_, dirs, nums] = lines str\n parts = zip dirs (map read $ words nums)\n in myShow $ get_min Nothing Nothing parts\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n dirs <- BS.getLine\n ps <- BS.getLine\n let ns = (map (fst . fromJust . BS8.readInt) . BS8.words) ps :: [Int]\n print (collide ns dirs)\n\ncollide :: [Int] -> BS8.ByteString -> Int\ncollide ns ds = f ns ds (-1) where\n f (n:n2:ns) ds t\n | d == ord 'R' && d2 == ord 'L' = f (n2:ns) ds' (if t == -1 then t' else min t' t)\n | otherwise = f (n2:ns) ds' t\n where\n d = fromIntegral $ BS.head ds\n d2 = fromIntegral $ BS.head (BS.tail ds)\n ds' = BS.tail ds\n t' = (n2 - n) `div` 2\n f _ _ t = t"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nmain = do\n getLine\n s <- getLine\n i <- map (read :: String -> Int) . words <$> getLine\n let m = snd $ foldr (\\(x,y) (a,acc) -> case (x,a) of \n ('R', Just ('L',c)) -> (Nothing, ((c-y)`div`2):acc)\n ('L', Just ('L',c)) -> (Just('L',y), acc)\n ('L', Nothing) -> (Just('L',y), acc)\n _ -> (Nothing, acc)) (Nothing,[]) $ zip s i\n print $ if null m then (-1) else minimum m\n\n\n\n \n "}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\nimport Data.Maybe(isNothing, fromJust)\n-- import Debug.Trace(trace)\n\ntrace x y = y\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = if isNothing answer then \"-1\" else show $ fromJust answer\n where\n n_s:pattern:worded' = words input\n n::Int\n n = read n_s\n points::[Int]\n points = map read worded'\n\n zipped::[(Char, Int)]\n zipped = zip pattern points\n\n bytwo::[x] -> [(x,x)]\n bytwo [] = []\n bytwo (x:[]) = []\n bytwo (x:y:xs) = (x,y):(bytwo (y:xs))\n\n answer::Maybe Int\n answer = foldl' foldop Nothing $ bytwo zipped\n\n foldop current (('L',x), ('R',y)) = current\n foldop current (('L',x), ('L',y)) = current\n foldop current (('R',x), ('R',y)) = current\n foldop current ((xdir, x), (ydir, y))\n | trace (show xdir ++ show x ++ show ydir ++ show y) False = Nothing\n | isNothing current = Just ((y-x) `div` 2)\n | otherwise = Just $ min cur ((y-x) `div` 2)\n where \n Just cur = current\n distance = (y-x) `div` 2\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve :: String -> [Int] -> (Maybe Int, Maybe Int)\nsolve [] [] = (Nothing, Nothing)\nsolve (c:cs) (x:xs) | c == 'L' = (Just x, b)\n | c == 'R' = (a, d)\n where (a, b) = solve cs xs\n td = do\n var <- a\n let timeImpact = (var - x) `div` 2\n return timeImpact\n d = (liftM2 min td b) `mplus` td\n\ngetInt :: Maybe Int -> Int\ngetInt Nothing = -1\ngetInt (Just x) = x\n\nmain :: IO ()\nmain = do\n getLine\n dir <- getLine\n pos <- map read . words <$> getLine\n let soln = solve dir pos\n -- putStrLn . show $ soln\n putStrLn . show . getInt . snd $ solve dir pos\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n dirs <- BS.getLine\n ps <- BS.getLine\n let ns = (map (fst . fromJust . BS8.readInt) . BS8.words) ps :: [Int]\n print (collide ns dirs)\n\ncollide :: [Int] -> BS8.ByteString -> Int\ncollide ns ds = f ns ds (-1) where\n f (n:n2:ns) ds t\n | d == ord 'R' && d2 == ord 'L' = f (n2:ns) ds' (if t == -1 then t' else min t' t)\n | otherwise = f ns ds' t\n where\n d = fromIntegral $ BS.head ds\n d2 = fromIntegral $ BS.head (BS.tail ds)\n ds' = BS.tail ds\n t' = (n2 - n) `div` 2\n f _ _ t = t"}, {"source_code": "import Data.List\n\nget_min :: [Integer] -> [Integer] -> Integer\nget_min _ [] = -1\nget_min xs (y:ys) =\n let xs' = dropWhile (< y) xs\n in if null xs' then -1 else div (head xs' - y) 2\n\nprocess :: String -> String\nprocess str =\n let [_, dirs, nums] = lines str\n parts = zip dirs (map read $ words nums)\n lefts = sort . map snd . filter (\\(n,_) -> n == 'L') $ parts\n rights = sort . map snd . filter (\\(n,_) -> n == 'R') $ parts\n in show $ get_min lefts rights\n\nmain :: IO ()\nmain = interact process"}], "src_uid": "ff0843cbd7c3a07c7d7d0be46b03a700"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Data.Bits\n--import Data.Functor.Foldable\nimport Data.List\nimport Data.Word\n\nmain = do\n _ <- getLine\n ns <- fmap read . words <$> getLine :: IO [Word32]\n let bs = w2bs <$> ns\n -- print $ ixRecurse 32 ns\n -- print . bs2w $ structuralRecurse bs\n print . bs2w $ hyloRecurse bs\n\nixRecurse :: Int -> [Word32] -> Word32\nixRecurse 0 _ = 0\nixRecurse i [] = 0\nixRecurse i ns = go (i-1) zs os\n where\n go i [] [] = 0\n go i [] on = ixRecurse i ns\n go i zs [] = ixRecurse i zs\n go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i\n (zs,os) = partition (\\x -> ((bit (i-1)) .&. x) /= 0) ns\n\ndata Bit = O | I\n deriving (Show, Eq, Ord)\n\nstructuralRecurse :: [[Bit]] -> [Bit]\nstructuralRecurse ns = go (zs,os)\n where\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n go :: ([[Bit]], [[Bit]]) -> [Bit]\n go ([],[]) = []\n go ([],os) = O:structuralRecurse (tail <$> os)\n go (zs,[]) = O:structuralRecurse (tail <$> zs)\n go (zs,os) = I:min (structuralRecurse . fmap tail $ zs) (structuralRecurse . fmap tail $ os)\n\ndata BTree = Node (BTree) (BTree) | Empty\ndata BTreeF b = NodeF b b | EmptyF\n deriving (Functor, Show)\n\nhyloRecurse :: [[Bit]] -> [Bit]\nhyloRecurse = init . hylo alg coalg\n where\n alg :: BTreeF [Bit] -> [Bit]\n alg EmptyF = []\n alg (NodeF [] os) = O:os\n alg (NodeF zs []) = O:zs\n alg (NodeF zs os) = I:min os zs\n\n coalg :: [[Bit]] -> BTreeF [[Bit]]\n coalg [] = EmptyF\n coalg ns = NodeF (tail <$> zs) (tail <$> os)\n where\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\nbs2w :: [Bit] -> Word32\nbs2w bs = go 0 bs\n where\n go acc [] = acc\n go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs\n go acc (O:bs) = go (shiftL acc 1) bs\n\nw2bs :: Word32 -> [Bit]\nw2bs w = fmap (\\n -> if (bit n .&. w) /= 0 then I else O) [31,30..0]\n\nhylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b\nhylo f g = h where h = f . fmap h . g\n", "positive_code": [{"source_code": "import Data.Bits\nimport Data.List\n\ndoit :: Int -> [Int] -> Int\ndoit _ [] = -1\ndoit (-1) _ = 0\ndoit b xs = min (max (combine al) ar) (max al (combine ar))\n where mask = 1 `shift` b\n (ls, rs) = partition (\\x -> x .&. mask == 0) xs\n al = doit (b-1) ls\n ar = doit (b-1) rs\n combine val | val == -1 = val\n combine val = val .|. mask\n\nmain :: IO ()\nmain = doit 29 . map read . words <$> (getLine >> getLine) >>= print\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.Bits\n\nmain = getLine >> getLine >>= print.solve 31.map read.words\n\nsolve :: Int -> [Int] -> Int\nsolve (-1) _ = 0\nsolve _ [] = bit 31\nsolve p xs\n\t| all (flip testBit p) xs || all (not.flip testBit p) xs = solve p' (f xs)\n\t| otherwise = bit p .|. min (solve p' $ f $ filter (flip testBit p) xs) (solve p' $ f $ filter (not.flip testBit p) xs)\n\twhere\n\t\tp' = p - 1\n\t\tf = map (.&. complement (bit p))\n"}, {"source_code": "import Data.Bits\nimport Data.List\nimport Data.Word\n\nmain = do\n _ <- getLine\n ns <- fmap read . words <$> getLine :: IO [Word32]\n print $ solve 32 ns\ndata Bit = O | I\n\nbitStringToWord :: (Bits a, Num a) => [Bit] -> a\nbitStringToWord bs = go 0 bs\n where\n go acc [] = acc\n go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs\n go acc (O:bs) = go (shiftL acc 1) bs\n\ndata BTree = Node BTree BTree | Leaf Bit\n\nsolve :: Int -> [Word32] -> Word32\nsolve 0 _ = 0\nsolve i [] = 0\nsolve i ns = go (i-1) zs os\n where\n go i [] [] = 0\n go i [] on = solve i ns\n go i zs [] = solve i zs\n go i zs os = min (solve i zs) (solve i os) + 2^i\n (zs,os) = partition (\\x -> ((bit (i-1)) .&. x) /= 0) ns\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Data.Bits\nimport Data.List\nimport Data.Word\n\nmain = do\n _ <- getLine\n ns <- fmap read . words <$> getLine :: IO [Word32]\n let bs = w2bs <$> ns\n -- print $ ixRecurse 32 ns\n print . bs2w $ structuralRecurse bs\n -- print . bs2w $ hyloRecurse bs\n\nixRecurse :: Int -> [Word32] -> Word32\nixRecurse 0 _ = 0\nixRecurse i [] = 0\nixRecurse i ns = go (i-1) zs os\n where\n go i [] [] = 0\n go i [] on = ixRecurse i ns\n go i zs [] = ixRecurse i zs\n go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i\n (zs,os) = partition (\\x -> ((bit (i-1)) .&. x) /= 0) ns\n\ndata Bit = O | I\n deriving (Show, Eq, Ord)\n\nstructuralRecurse :: [[Bit]] -> [Bit]\nstructuralRecurse ns = go zs os\n where\n go [] [] = []\n go [] os = O:structuralRecurse (tail <$> os)\n go zs [] = O:structuralRecurse (tail <$> zs)\n go zs os = I:min (structuralRecurse . fmap tail $ zs) (structuralRecurse . fmap tail $ os)\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\ndata BTreeF b = NodeF b b | EmptyF\n deriving (Functor, Show)\n\n\nhyloRecurse :: [[Bit]] -> [Bit]\nhyloRecurse = hylo alg coalg\n where\n-- alg :: BTreeF a [Bit] -> [Bit]\nalg EmptyF = return O\nalg (NodeF zs os) = I:min (zs) (os)\n-- coalg :: [[Bit]] -> BTreeF [a] [[Bit]]\ncoalg [] = EmptyF\ncoalg ns = fmap tail <$> (NodeF zs os)\n where\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\nbs2w :: [Bit] -> Word32\nbs2w bs = go 0 bs\n where\n go acc [] = acc\n go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs\n go acc (O:bs) = go (shiftL acc 1) bs\n\nw2bs :: Word32 -> [Bit]\nw2bs w = fmap (\\n -> if (bit n .&. w) /= 0 then I else O) [31,30..0]\n\nhylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b\nhylo f g = h where h = f . fmap h . g\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Bits\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.State.Strict (StateT)\nimport qualified Control.Monad.Trans.State.Strict as StateT\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\n\ngetNewLine :: SIO ByteString\ngetNewLine = (lift $ C.hGetLine stdin) >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n\ngetRemain :: ByteString -> SIO ByteString\ngetRemain b = let bns = C.dropWhile isSpace b in\n if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)\n else return bns\n\ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n\ntype SIO a = StateT ByteString IO a\n\nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n\ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => SIO a\nget = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get\nput :: IOInteract a => a -> SIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> SIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: SIO ()\nflush = lift (hFlush stdout)\n\nmain :: IO ()\nmain = StateT.evalStateT main_ C.empty\n\nmain_ :: SIO ()\n-------------------------------------------- template ------------------------------------------------------\n-- for io performance comparison from @Russell_Emerine's code\nmain_ = get >>= flip replicateM get >>= putln . solve 31\n\nsolve :: Int -> [Int] -> Int\nsolve (-1) _ = 0\nsolve _ [] = bit 31\nsolve p xs\n\t| all (flip testBit p) xs || all (not.flip testBit p) xs = solve p' (f xs)\n\t| otherwise = bit p .|. min (solve p' $ f $ filter (flip testBit p) xs) (solve p' $ f $ filter (not.flip testBit p) xs)\n\twhere\n\t\tp' = p - 1\n\t\tf = map (.&. complement (bit p))"}], "negative_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Data.Bits\nimport Data.List\nimport Data.Word\n\nmain = do\n _ <- getLine\n ns <- fmap read . words <$> getLine :: IO [Word32]\n let bs = w2bs <$> ns\n -- print $ ixRecurse 32 ns\n print . bs2w $ structuralRecurse bs\n -- print . bs2w $ hyloRecurse bs\n\nixRecurse :: Int -> [Word32] -> Word32\nixRecurse 0 _ = 0\nixRecurse i [] = 0\nixRecurse i ns = go (i-1) zs os\n where\n go i [] [] = 0\n go i [] on = ixRecurse i ns\n go i zs [] = ixRecurse i zs\n go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i\n (zs,os) = partition (\\x -> ((bit (i-1)) .&. x) /= 0) ns\n\ndata Bit = O | I\n deriving (Show, Eq, Ord)\n\nstructuralRecurse :: [[Bit]] -> [Bit]\nstructuralRecurse ns = go zs os\n where\n go [] [] = []\n go [] os = O:structuralRecurse (tail <$> os)\n go zs [] = O:structuralRecurse (tail <$> zs)\n go zs os = I:min (structuralRecurse . fmap tail $ zs) (structuralRecurse . fmap tail $ os)\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\ndata BTreeF b = NodeF b b | EmptyF\n deriving (Functor, Show)\n\n\nhyloRecurse :: [[Bit]] -> [Bit]\nhyloRecurse = hylo alg coalg\n where\n-- alg :: BTreeF a [Bit] -> [Bit]\nalg EmptyF = return O\nalg (NodeF zs os) = I:min (zs) (os)\n-- coalg :: [[Bit]] -> BTreeF [a] [[Bit]]\ncoalg [] = EmptyF\ncoalg ns = fmap tail <$> (NodeF zs os)\n where\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\nbs2w :: [Bit] -> Word32\nbs2w bs = go 0 bs\n where\n go acc [] = acc\n go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs\n go acc (O:bs) = go (shiftL acc 1) bs\n\nw2bs :: Word32 -> [Bit]\nw2bs w = fmap (\\n -> if (bit n .&. w) /= 0 then I else O) [4,3..0]\n\nhylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b\nhylo f g = h where h = f . fmap h . g\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Data.Bits\nimport Data.List\nimport Data.Word\n\nmain = do\n _ <- getLine\n ns <- fmap read . words <$> getLine :: IO [Word32]\n let bs = w2bs <$> ns\n -- print $ ixRecurse 32 ns\n -- print . bs2w $ structuralRecurse bs\n print . bs2w $ hyloRecurse bs\n\nixRecurse :: Int -> [Word32] -> Word32\nixRecurse 0 _ = 0\nixRecurse i [] = 0\nixRecurse i ns = go (i-1) zs os\n where\n go i [] [] = 0\n go i [] on = ixRecurse i ns\n go i zs [] = ixRecurse i zs\n go i zs os = min (ixRecurse i zs) (ixRecurse i os) + 2^i\n (zs,os) = partition (\\x -> ((bit (i-1)) .&. x) /= 0) ns\n\ndata Bit = O | I\n deriving (Show, Eq, Ord)\n\nstructuralRecurse :: [[Bit]] -> [Bit]\nstructuralRecurse ns = go zs os\n where\n go [] [] = return O\n go [] os = structuralRecurse (tail <$> os)\n go zs [] = structuralRecurse (tail <$> zs)\n go zs os = I:min (structuralRecurse zs) (structuralRecurse os)\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\ndata BTreeF a b = NodeF a b b | EmptyF\n deriving (Functor, Show)\n\nhyloRecurse :: [[Bit]] -> [Bit]\nhyloRecurse = hylo alg coalg\n where\n alg EmptyF = return O\n alg (NodeF a zs os) = I:min zs os\n coalg [] = EmptyF\n coalg ns = NodeF [] zs os\n where\n (zs, os) = partition (\\x -> head x == O) . filter (not . null) $ ns\n\nbs2w :: [Bit] -> Word32\nbs2w bs = go 0 bs\n where\n go acc [] = acc\n go acc (I:bs) = go ((shiftL acc 1) .|. 1) bs\n go acc (O:bs) = go (shiftL acc 1) bs\n\nw2bs :: Word32 -> [Bit]\nw2bs w = fmap (\\n -> if (bit n .&. w) /= 0 then I else O) [31,30..0]\n\nhylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b\nhylo f g = h where h = f . fmap h . g\n"}], "src_uid": "d17d2fcfb088bf51e9c1f3fce4133a94"} {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.IntMap as I\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \ndel _ [] = []\ndel x (m:ms) | x==m = ms\n | otherwise = m : ( del x ms)\n\nprocess [s] _ = s\nprocess x (a:as) = process (del a x) as\n\n\nmain = do\n\tgetLine\n\ta<- map (fst.fromJust.C.readInt).C.words <$> C.getLine ::IO [Int]\n\tlet b = foldl (\\acc z-> I.insertWith (+) z 1 acc) I.empty a\n\tlet e = I.keys $ I.filter (==( I.foldl max 0 b)) b\n\tprint $ process e (reverse a)\n\t\n\t ", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.IntMap as I\n \ndel _ [] = []\ndel x (m:ms) | x==m = ms\n | otherwise = m : ( del x ms)\n\nprocess [s] _ = s\nprocess x (a:as) = process (del a x) as\n\n\nmain = do\n\tgetLine\n\ta<- map read.words <$> getLine ::IO [Int]\n\tlet b = foldl (\\acc z-> I.insertWith (+) z 1 acc) I.empty a\n\tlet c = I.elems b\n\tlet d = maximum c\n\tlet e =map fst $ filter (\\z-> snd z ==d) $ I.assocs b\n\tprint $ process e (reverse a)\n\t\n\t "}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let arr = nub a\n (_,ans) = maximum . map (\\x -> ((fn (0,0) x (zip a [1..])),x)) $ arr\n print ans\n\nfn :: (Int,Int) -> Int -> [(Int,Int)] -> (Int,Int)\nfn ans _ [] = ans\nfn (mx,ls) e ((x,i):xs)\n |e==x = fn (mx+1,-i) e xs\n |otherwise = fn (mx,ls) e xs\n"}, {"source_code": "module Main where\n\n-- (num,likes,step)\nred :: ([(Int, Int,Int)], Int) -> Int -> ([(Int,Int,Int)], Int)\nred (list, step) like =\n let\n addLike num step st [] = (num,1,step):st\n addLike num step st ((n,l,s):xs) | n == num = ((n,l+1,step):st)++xs\n | otherwise = addLike num step ((n,l,s):st) xs\n in (addLike like step [] list, step + 1)\n\nfindBest (x:xs) =\n let\n helper best [] = best\n helper best@(n,l,s) ((n',l',s'):xs) | l' > l = helper (n',l',s') xs\n | l' == l && s > s' = helper (n',l',s') xs\n | otherwise = helper best xs\n (bst,_,_) = helper x xs\n in\n bst\n\nmain = do\n n <-(getLine >>= (return.read)) :: IO Int\n likes <- (getLine >>= (return . words) >>= (return . (map read))) :: IO [Int]\n let (formatted, _) = foldl red ([],0) likes\n-- putStrLn $ show formatted\n putStrLn $ show $ findBest formatted\n"}, {"source_code": "import Data.List\nimport Data.Ord\n\nmain = interact $ show . go . map read . words . head . tail . lines\n\ngo :: [Int] -> Int\ngo al = let ids = nub al\n lks = zip al [1..]\n il = map (\\i -> filter ((i==). fst) lks) ids\n mxl = maximum $ map length il\n in fst . minimumBy (comparing snd) . map (maximumBy (comparing snd)) $ filter ((mxl==). length) il"}, {"source_code": "module Main where\n\nimport Data.Ord\nimport Data.List\nimport Data.Function\n\nmain :: IO ()\nmain = interact (show . solve . tail . map read . words)\n\nsolve :: [Int] -> Int\nsolve list = maximumBy comparator list where\n\t\t\t\tcomparator = \\x y -> case compare (count x list) (count y list) of\n\t\t\t\t\tLT -> LT\n\t\t\t\t\tGT -> GT\n\t\t\t\t\tEQ -> compare (lastIndexOf y list) (lastIndexOf x list)\n\nlastIndexOf :: Int -> [Int] -> Int\nlastIndexOf x = fst . last . filter ((==) x . snd) . zip [0..]\n\ncount :: Int -> [Int] -> Int\ncount x = length . filter (==x)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\n \ndel _ [] = []\ndel x (m:ms) | x==m = ms\n | otherwise = m : ( del x ms)\n\nprocess [s] _ = s\nprocess x (a:as) = process (del a x) as\n\n\nmain = do\n\tgetLine\n\ta<- map read.words <$> getLine ::IO [Int]\n\tlet b = accumArray (+) 0 (1,1000000) $ zip a (repeat 1)\n\tlet c = elems b\n\tlet d = maximum c\n\tlet e =map fst $ filter (\\z-> snd z ==d) $ assocs b\n\tprint $ process e (reverse a)\n\t\n\t "}, {"source_code": "import Data.List\nimport Data.Functor\nimport Data.Function (on)\n\nmain :: IO()\nmain = do\n _ <- getLine\n a <- words <$> getLine\n let ai = sort $ zip a [1..]\n gai = groupBy ((==) `on` fst) ai\n lai = map (\\x -> (negate (length x), (snd (last x), fst (head x)))) gai\n sai = sort lai\n putStrLn $ snd $ snd $ head sai\n"}], "negative_code": [], "src_uid": "e4a2354159fc4cab7088e016cf17ae6c"} {"source_code": "import Data.List\nimport System.IO\n\nreadInteger:: IO Int\nreadInteger = readLn\n\nreadIntegers 0 = return []\nreadIntegers n = do\n x <- readInteger\n rest <- readIntegers (n - 1)\n return (x : rest)\n\nprocess e o = if el > ol\n then take (max (el - ol - 1) 0) e\n else take (max (ol - el - 1) 0) o\n where\n ol = length o\n el = length e\n\nsolve l = sum (process (sort (filter even l)) (sort (filter odd l)))\n\nsanitize = map read . words\n\nmain = do\n readInteger\n input <- getLine\n putStrLn (show (solve (sanitize input)))", "positive_code": [{"source_code": "import Data.List\nprocess o e\n | (length e) > (length o) = sum (drop ((length o) + 1) e)\n | otherwise = sum (drop ((length e) + 1) o)\nmain = do\n _ <- getLine\n line <- getLine\n let\n a = map read $ words $ line\n o = reverse $ sort $ filter odd a\n e = reverse $ sort $ filter even a\n putStrLn $ show $ process o e\n"}, {"source_code": "import Data.Bifunctor\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Control.Arrow\n\nsolve x = \n let f x = (length x, sort x)\n (a,b) = arr (uncurry min) &&& arr (uncurry max) $ bimap f f $ partition ((/=0).(`mod`2)) x\n in sum $ drop (succ $ fst a) $ reverse $ snd b\n \nmain = print =<< solve . map (fst . fromJust . B.readInt) . B.words <$> (getLine >> B.getLine)\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve as | le > lo = sum (drop (lo+1) e)\n | otherwise = sum (drop (le+1) o)\n where (e,o) = partition even (reverse (sort as))\n le = length e\n lo = length o\n"}, {"source_code": "import Data.List ( sortOn, partition )\nimport Data.Ord ( Down(..))\n\nmain :: IO ()\nmain = interact $ show . parity . fmap read . tail . words\n\nparity :: [Integer] -> Integer\nparity = minimize . leftover . partition even . sortOn Down\n\n\nminimize :: [Integer] -> Integer\nminimize [] = 0\nminimize ns = sum $ tail ns\n\nleftover :: ([Integer], [Integer]) -> [Integer]\nleftover (evens, odds) | length evens > length odds = annihilate evens odds\n | otherwise = annihilate odds evens\n\nannihilate :: [a] -> [a] -> [a]\nannihilate bigger smaller = drop (length smaller) bigger\n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve (n:a) = sum x' + sum y'\n where\n (b, c) = partition odd a\n x = reverse $ sort b\n y = reverse $ sort c\n lx = length x\n ly = length y\n l = succ $ min lx ly\n x' = drop l x\n y' = drop l y\n\nmain :: IO ()\nmain = print . solve . map ri . C.words =<< C.getContents\n"}], "negative_code": [], "src_uid": "b80fed46a9e2356dad03dd3ec01523d4"} {"source_code": "import Data.Bits\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Control.Monad.ST.Safe\n--import Debug.Trace\nimport Control.Monad\n\npairs :: [a] -> [(a, a)]\npairs [] = []\npairs (x : y : xs) = (x, y) : pairs xs\n\nbuild :: [[Int]] -> Bool -> [[Int]]\nbuild tree@([t] : ts) fn = tree\nbuild tree@(t : ts) doOr =\n let fn = if doOr then (.|.) else xor\n nextLevel = map (uncurry fn) (pairs t) :: [Int]\n in build (nextLevel : tree) (not doOr)\n\n-- Head of tree at position idx is updated to newval.\n-- Compute new value for next level of the tree.\nupdate :: [STUArray s Int Int] -> Int -> Int -> Bool -> ST s ()\nupdate [t] 0 newval _ = writeArray t 0 newval\nupdate (t : ts) idx newval doOr = do\n let fn = if doOr then (.|.) else xor\n idx' = idx `div` 2\n writeArray t idx newval\n i1 <- readArray t (idx' * 2)\n i2 <- readArray t (idx' * 2 + 1)\n let newval' = i1 `fn` i2\n update ts idx' newval' (not doOr)\n\ng :: [STUArray s Int Int] -> [(Int, Int)] -> ST s [Int]\ng mtree [] = return []\ng mtree ((idx, newval) : qs) = do\n update mtree idx newval True\n ret <- readArray (last mtree) 0\n rest <- g mtree qs\n return $ ret : rest\n\nf :: [Int] -> [[Int]] -> [Int]\nf as queries =\n let tree = reverse $ build [as] True\n tree' = [ listArray (0, length t - 1) t | t <- tree ]\n queries' = [ (idx - 1, val) | [idx, val] <- queries ]\n in runST $ do\n mtree <- mapM thaw tree'\n g mtree queries'\n\nmain'' = do\n let as = [1 .. 2 ^ 17]\n queries = [ [i, i] | i <- [1 .. 10000] ]\n print $ f as queries\n\nmain' = do\n let as = [1, 6, 3, 5]\n queries = [[1, 4], [3, 4], [1, 2], [1, 2]]\n putStrLn $ (unlines . map show) (f as queries)\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]\n putStrLn $ (unlines . map show) (f as queries)", "positive_code": [{"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Array.IO\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bits ((.|.), xor)\nimport Data.Char (isSpace)\nimport Prelude hiding (or, reads)\n\ntype Tree = UArray Int Int\n\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\nreadPair :: IO (Int, Int)\nreadPair = do\n x <- readInt\n y <- readInt\n return (x, y)\n\nreadInt :: IO Int\nreadInt = do\n c <- getChar\n isSpace c ? readInt $ readInt' (fromEnum c - fromEnum '0')\n where\n readInt' a = do\n c <- getChar\n isSpace c ? return a $ readInt' (10*a + fromEnum c - fromEnum '0')\n\nor :: Int -> Int -> Int\nor = (.|.)\n\nlevel :: Int -> Int\nlevel n = truncate (1e-07 + log (fromIntegral n) / log 2)\n\nfInLevel :: Int -> Int -> (Int -> Int -> Int)\nfInLevel n i\n | odd (n + level i) = or\n | otherwise = xor\n\ncreateTree :: Int -> [Int] -> Tree\ncreateTree n as = runSTUArray $ do\n tree <- newArray_ (1, 2^(n + 1) - 1)\n sequence_ [writeArray tree i x\n | (i, x) <- zip [2^n..] as]\n sequence_\n [\n do\n a <- readArray tree (2*i)\n b <- readArray tree (2*i+1)\n writeArray tree i (fInLevel n i a b)\n | i <- [2^n-1, 2^n-2 .. 1]\n ]\n return tree\n\nsolve :: Int -> [Int] -> [(Int, Int)] -> IO ()\nsolve n as qs = do\n let tree = createTree n as\n tree' <- unsafeThaw tree\n mapM_ (solve' tree')\n $ map (\\(x, y) -> (x + 2^n - 1, y)) qs\n where\n solve' :: IOUArray Int Int -> (Int, Int) -> IO ()\n solve' array (1, d) = print d\n solve' array (i1, d1) = do\n let i0 = i1 `div` 2\n let i2 = if odd i1 then i1 - 1 else i1 + 1\n d2 <- readArray array i2\n let d0 = fInLevel n i0 d1 d2\n writeArray array i1 d1\n solve' array (i0, d0)\n\nmain :: IO ()\nmain = do\n (n, m) <- readPair\n as <- replicateM (2^n) readInt\n qs <- replicateM m readPair\n solve n as qs\n"}], "negative_code": [{"source_code": "import Data.Bits\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Control.Monad.ST.Safe\n--import Debug.Trace\nimport Control.Monad\n\npairs :: [a] -> [(a, a)]\npairs [] = []\npairs (x : y : xs) = (x, y) : pairs xs\n\nbuild :: [[Int]] -> Bool -> [[Int]]\nbuild tree@([t] : ts) fn = tree\nbuild tree@(t : ts) doOr =\n let fn = if doOr then (.|.) else xor\n nextLevel = map (uncurry fn) (pairs t) :: [Int]\n in build (nextLevel : tree) (not doOr)\n\n-- Head of tree at position idx is updated to newval.\n-- Compute new value for next level of the tree.\nupdate :: [STArray s Int Int] -> Int -> Int -> Bool -> ST s ()\nupdate [t] 0 newval _ = do\n --tOld <- getElems t\n writeArray t 0 newval\n --tNew <- getElems t\n --traceM $ show tOld ++ \" -> \" ++ show tNew\n return ()\nupdate (t : ts) idx newval doOr = do\n let fn = if doOr then (.|.) else xor\n idx' = idx `div` 2\n --tOld <- getElems t\n writeArray t idx newval\n --tNew <- getElems t\n --traceM $ show tOld ++ \" -> \" ++ show tNew\n i1 <- readArray t (idx' * 2)\n i2 <- readArray t (idx' * 2 + 1)\n let newval' = i1 `fn` i2\n update ts idx' newval' (not doOr)\n\n--g :: [Array Int Int] -> [[Int]] -> [Int]\n--g _ [] = []\n--g tree ([idx, newval] : qs) =\n-- let (ret, tree') = update tree (idx - 1) newval True in ret : g tree' qs\n\ng :: [STArray s Int Int] -> [(Int, Int)] -> ST s [Int]\ng mtree [] = return []\ng mtree ((idx, newval) : qs) = do\n update mtree idx newval True\n --t <- mapM getElems mtree\n --traceShowM t\n ret <- readArray (last mtree) 0\n rest <- g mtree qs\n return $ ret : rest\n\nf :: [Int] -> [[Int]] -> [Int]\nf as queries =\n let tree = reverse $ build [as] True\n tree' = [ listArray (0, length t - 1) t | t <- tree ]\n queries' = [ (idx - 1, val) | [idx, val] <- queries ]\n in runST $ do\n mtree <- mapM thaw tree'\n g mtree queries'\n\n--main = do\n-- let as = [1 .. 2 ^ 17]\n-- queries = [ [1, 0] | _ <- [1 .. 10000] ]\n-- print $ f as queries\n\nmain = do\n let as = [1, 6, 3, 5]\n queries = [[1, 4], [3, 4], [1, 2], [1, 2]]\n putStrLn $ (unlines . map show) (f as queries)\n\nmain' = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]\n putStrLn $ (unlines . map show) (f as queries)\n"}, {"source_code": "import Data.Bits\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Control.Monad.ST.Safe\n\npairs :: [a] -> [(a, a)]\npairs [] = []\npairs (x : y : xs) = (x, y) : pairs xs\n\nbuild :: [[Int]] -> Bool -> [[Int]]\nbuild tree@([t] : ts) fn = tree\nbuild tree@(t : ts) doOr =\n let fn = if doOr then (.|.) else xor\n nextLevel = map (uncurry fn) (pairs t) :: [Int]\n in build (nextLevel : tree) (not doOr)\n\n-- Head of tree at position idx is updated to newval.\n-- Compute new value for next level of the tree.\nupdate :: [STArray s Int Int] -> Int -> Int -> Bool -> ST s ()\nupdate [t ] 0 newval _ = writeArray t 0 newval\nupdate (t : ts) idx newval doOr = do\n let fn = if doOr then (.|.) else xor\n idx' = idx `div` 2\n writeArray t idx newval\n i1 <- readArray t (idx' * 2)\n i2 <- readArray t (idx' * 2 + 1)\n let newval' = i1 `fn` i2\n update ts idx' newval' (not doOr)\n\n--g :: [Array Int Int] -> [[Int]] -> [Int]\n--g _ [] = []\n--g tree ([idx, newval] : qs) =\n-- let (ret, tree') = update tree (idx - 1) newval True in ret : g tree' qs\n\ng :: [STArray s Int Int] -> [[Int]] -> ST s [Int]\ng mtree [] = return []\ng mtree ([idx, newval] : qs) = do\n update mtree idx newval True\n ret <- readArray (last mtree) 0\n rest <- g mtree qs\n return $ ret : rest\n\nf :: [Int] -> [[Int]] -> [Int]\nf as queries =\n let tree = reverse $ build [as] True\n tree' = [ listArray (0, length t - 1) t | t <- tree ]\n in runST $ do\n mtree <- mapM thaw tree'\n g mtree queries\n\n--main = do\n-- let as = [1 .. 2 ^ 17]\n-- queries = [ [1, 0] | _ <- [1 .. 10000] ]\n-- print $ f as queries\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]\n putStrLn $ (unlines . map show) (f as queries)"}, {"source_code": "import Data.Bits\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Control.Monad.ST.Safe\n--import Debug.Trace\nimport Control.Monad\n\npairs :: [a] -> [(a, a)]\npairs [] = []\npairs (x : y : xs) = (x, y) : pairs xs\n\nbuild :: [[Int]] -> Bool -> [[Int]]\nbuild tree@([t] : ts) fn = tree\nbuild tree@(t : ts) doOr =\n let fn = if doOr then (.|.) else xor\n nextLevel = map (uncurry fn) (pairs t) :: [Int]\n in build (nextLevel : tree) (not doOr)\n\n-- Head of tree at position idx is updated to newval.\n-- Compute new value for next level of the tree.\nupdate :: [STUArray s Int Int] -> Int -> Int -> Bool -> ST s ()\nupdate [t] 0 newval _ = writeArray t 0 newval\nupdate (t : ts) idx newval doOr = do\n let fn = if doOr then (.|.) else xor\n idx' = idx `div` 2\n writeArray t idx newval\n i1 <- readArray t (idx' * 2)\n i2 <- readArray t (idx' * 2 + 1)\n let newval' = i1 `fn` i2\n update ts idx' newval' (not doOr)\n\ng :: [STUArray s Int Int] -> [(Int, Int)] -> ST s [Int]\ng mtree [] = return []\ng mtree ((idx, newval) : qs) = do\n update mtree idx newval True\n ret <- readArray (last mtree) 0\n rest <- g mtree qs\n return $ ret : rest\n\nf :: [Int] -> [[Int]] -> [Int]\nf as queries =\n let tree = reverse $ build [as] True\n tree' = [ listArray (0, length t - 1) t | t <- tree ]\n queries' = [ (idx - 1, val) | [idx, val] <- queries ]\n in runST $ do\n mtree <- mapM thaw tree'\n g mtree queries'\n\nmain = do\n let as = [1 .. 2 ^ 17]\n queries = [ [i, i] | i <- [1 .. 10000] ]\n print $ f as queries\n\nmain' = do\n let as = [1, 6, 3, 5]\n queries = [[1, 4], [3, 4], [1, 2], [1, 2]]\n putStrLn $ (unlines . map show) (f as queries)\n\nmain'' = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n queries <- map (map read . words) . lines <$> getContents :: IO [[Int]]\n putStrLn $ (unlines . map show) (f as queries)"}, {"source_code": "\n\nimport Control.Monad (liftM, replicateM)\nimport Data.Array.IO\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bits ((.|.), xor)\nimport Data.Char (isSpace)\nimport Prelude hiding (or, reads)\n\ntype Tree = UArray Int Int\n\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\nreadPair :: IO (Int, Int)\nreadPair = do\n x <- readInt\n y <- readInt\n return (x, y)\n\nreadInt :: IO Int\nreadInt = do\n c <- getChar\n isSpace c ? readInt $ readInt' (fromEnum c - fromEnum '0')\n where\n readInt' a = do\n c <- getChar\n isSpace c ? return a $ readInt' (10*a + fromEnum c - fromEnum '0')\n\nor :: Int -> Int -> Int\nor = (.|.)\n\nlevel :: Int -> Int\nlevel n = truncate (log (fromIntegral n) / log 2)\n\nfInLevel :: Int -> Int -> (Int -> Int -> Int)\nfInLevel n i\n | odd (n + level i) = or\n | otherwise = xor\n\ncreateTree :: Int -> [Int] -> Tree\ncreateTree n as = runSTUArray $ do\n tree <- newArray_ (1, 2^(n + 1) - 1)\n sequence_ [writeArray tree i x\n | (i, x) <- zip [2^n..] as]\n sequence_\n [\n do\n a <- readArray tree (2*i)\n b <- readArray tree (2*i+1)\n writeArray tree i (fInLevel n i a b)\n | i <- [2^n-1, 2^n-2 .. 1]\n ]\n return tree\n\nsolve :: Int -> [Int] -> [(Int, Int)] -> IO ()\nsolve n as qs = do\n let tree = createTree n as\n tree' <- unsafeThaw tree\n mapM_ (solve' tree')\n $ map (\\(x, y) -> (x + 2^n - 1, y)) qs\n where\n solve' :: IOUArray Int Int -> (Int, Int) -> IO ()\n solve' array (1, d) = print d\n solve' array (i1, d1) = do\n let i0 = i1 `div` 2\n let i2 = if odd i1 then i1 - 1 else i1 + 1\n d2 <- readArray array i2\n let d0 = fInLevel n i0 d1 d2\n writeArray array i1 d1\n solve' array (i0, d0)\n\nmain :: IO ()\nmain = do\n (n, m) <- readPair\n as <- replicateM (2^n) readInt\n qs <- replicateM m readPair\n solve n as qs\n\n"}, {"source_code": "\n\n\nimport Control.Monad (liftM, replicateM)\nimport Data.Array.IO\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bits ((.|.), xor)\nimport Prelude hiding (or, reads)\n\ntype Tree = UArray Int Int\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nreadPair :: Read a => IO (a, a)\nreadPair = do\n [x, y] <- reads\n return (x, y)\n\nor :: Int -> Int -> Int\nor = (.|.)\n\nlevel :: Int -> Int\nlevel n = truncate (log (fromIntegral n) / log 2)\n\nfInLevel :: Int -> Int -> (Int -> Int -> Int)\nfInLevel n i\n | odd (level i + n) = or\n | otherwise = xor\n\ncreateTree :: Int -> [Int] -> Tree\ncreateTree n as = runSTUArray $ do\n tree <- newArray_ (1, 2^(n + 1) - 1)\n sequence_ [writeArray tree i x\n | (i, x) <- zip [2^n..] as]\n sequence_\n [\n do\n a <- readArray tree (2*i)\n b <- readArray tree (2*i+1)\n writeArray tree i (fInLevel n i a b)\n | i <- [2^n-1, 2^n-2 .. 1]\n ]\n return tree\n\nsolve :: Int -> [Int] -> [(Int, Int)] -> IO ()\nsolve n as qs = do\n let tree = createTree n as\n tree' <- unsafeThaw tree\n mapM_ (solve' tree')\n $ map (\\(x, y) -> (x + 2^n - 1, y)) qs\n where\n solve' :: IOUArray Int Int -> (Int, Int) -> IO ()\n solve' array (1, d) = print d\n solve' array (i1, d1) = do\n let i0 = i1 `div` 2\n let i2 = if odd i1 then i1 - 1 else i1 + 1\n d2 <- readArray array i2\n let d0 = fInLevel n i0 d1 d2\n writeArray array i0 d0\n solve' array (i0, d0)\n\nmain :: IO ()\nmain = do\n {-\n let n = 17\n let m = 100000\n let as = [1 .. 2^n]\n let qs = take m $ cycle [(i, 0) | i <- as]\n -}\n [n, m] <- reads\n as <- reads\n qs <- replicateM m readPair\n solve n as qs\n"}], "src_uid": "40d1ea98aa69865143d44432aed4dd7e"} {"source_code": "upperBound n l = last $ takeWhile (<= n) l\n\ncards = scanl (\\cum n -> cum + 3 * n - 1) 0 [1..]\n\nf :: Int -> Int\nf n | n < 2 = 0\n | otherwise = 1 + f (n - (upperBound n cards))\n\nmain = interact $ unlines . map (show . f) . tail . map read . lines", "positive_code": [{"source_code": "\nfindMaxSize :: Int -> Int\nfindMaxSize p = floor $ (sqrt (24 * fromIntegral p + 1) -1)/6\n\nsize :: Int -> Int\nsize h = (h * (3*h + 1)) `div` 2\n\nsolve :: Int -> Int\nsolve p\n | m == 0 = 0\n | otherwise = 1 + solve (p- size m)\n where\n m = findMaxSize p\n\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (p:_) <- readNums\n print $ solve p\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- parseNums <$> getLine\n testCases t\n\n\nparseNums :: (Read a) => String -> [a]\nparseNums = map read . words\n\nreadNums :: (Read a) => IO [a]\nreadNums = parseNums <$> getLine"}], "negative_code": [], "src_uid": "02062d1afe85e3639edddedceac304f4"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> last\n >>> solve 1 0 0 0\n >>> show\n >>> (++ \"\\n\")\n\nmyMod :: Integer\nmyMod = 10 ^ 9 + 7\n\nmadd :: Integer -> Integer -> Integer\nmadd a b = (a + b) `mod` myMod\n\nmmul :: Integer -> Integer -> Integer\nmmul a b = (a * b) `mod` myMod\n\nsolve :: Integer -> Integer -> Integer -> Integer -> String -> Integer\nsolve _ _ _ abc [] = abc\nsolve n a ab abc (x : xs)\n | x == 'a' = solve n (madd a n) ab abc xs\n | x == 'b' = solve n a (madd ab a) abc xs\n | x == 'c' = solve n a ab (madd abc ab) xs\n | x == '?' =\n solve\n (mmul 3 n)\n (madd (mmul 3 a) n)\n (madd (mmul 3 ab) a)\n (madd (mmul 3 abc) ab)\n xs\n", "positive_code": [{"source_code": "import Data.List\n\np :: Int\np = 10^(9 :: Int) + 7\n\nsp :: Int -> Int -> Int\nsp x y = rem (x + y) p\n\ntrip :: Int -> Int\ntrip x = sp x (sp x x)\n\ndata State = State !Int !Int !Int !Int\n\nstep :: State -> Char -> State\nstep (State w x y z) c = case c of\n 'a' -> State w (sp w x) y z\n 'b' -> State w x (sp x y) z\n 'c' -> State w x y (sp y z)\n '?' -> State (trip w) (sp w $ trip x) (sp x $ trip y) (sp y $ trip z)\n _ -> error \"invalid char in input\"\n\nsolve :: [Char] -> Int\nsolve li = let\n State _ _ _ ans = foldl' step (State 1 0 0 0) li\n in ans\n\nmain :: IO ()\nmain = do\n _nStr <- getLine\n s <- getLine\n print $ solve s\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> last\n >>> solve 1 0 0 0\n >>> show\n >>> (++ \"\\n\")\n\nmyMod :: Int\nmyMod = 10 ^ 9 + 7\n\nmadd :: Int -> Int -> Int\nmadd a b = (a + b) `mod` myMod\n\nmmul :: Int -> Int -> Int\nmmul a b = (a * b) `mod` myMod\n\nsolve :: Int -> Int -> Int -> Int -> String -> Int\nsolve _ _ _ abc [] = abc\nsolve n a ab abc (x : xs)\n | x == 'a' = solve n (madd a 1) ab abc xs\n | x == 'b' = solve n a (madd ab a) abc xs\n | x == 'c' = solve n a ab (madd abc ab) xs\n | x == '?' =\n solve\n (mmul 3 n)\n (madd (mmul 3 a) n)\n (madd (mmul 3 ab) a)\n (madd (mmul 3 abc) ab)\n xs\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> last\n >>> solve 1 0 0 0\n >>> show\n >>> (++ \"\\n\")\n\nmyMod :: Int\nmyMod = 10 ^ 9 + 7\n\nmadd :: Int -> Int -> Int\nmadd a b = (a + b) `mod` myMod\n\nmmul :: Int -> Int -> Int\nmmul a b = (a * b) `mod` myMod\n\nsolve :: Int -> Int -> Int -> Int -> String -> Int\nsolve _ _ _ abc [] = abc\nsolve n a ab abc (x : xs)\n | x == 'a' = solve n (madd a n) ab abc xs\n | x == 'b' = solve n a (madd ab a) abc xs\n | x == 'c' = solve n a ab (madd abc ab) xs\n | x == '?' =\n solve\n (mmul 3 n)\n (madd (mmul 3 a) n)\n (madd (mmul 3 ab) a)\n (madd (mmul 3 abc) ab)\n xs\n"}], "src_uid": "45d8827bfee3afeeed79741a2c3b0a0f"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents, unpack)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n getLine\n ps <- fmap (map fromIntegral) readInts :: IO [Int64]\n s <- fmap unpack getLine\n\n let\n as = scanl (+) 0 $ zipWith (\\c p -> if c == 'A' then p else 0) s ps\n bs = scanl (+) 0 $ zipWith (\\c p -> if c == 'B' then p else 0) s ps\n s1 = last as\n s2 = last bs\n\n prefs = zipWith (\\a b -> a + s2 - b) as bs\n sufs = zipWith (\\a b -> b + s1 - a) as bs\n\n print $ max (maximum prefs) (maximum sufs)\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as C8\nimport Data.Maybe\n\nreadInteger :: String -> Integer\nreadInteger s = read s :: Integer\n\nsuffixScore :: [Integer] -> String -> [Integer] -> [Integer]\nsuffixScore [] _ xs = xs\nsuffixScore _ [] xs = xs\nsuffixScore (score:scores) (piece:pieces) xs =\n let prev = head xs\n adder = flipValueOf score piece\n newValue = prev + adder\n xs' = (newValue:xs)\n in suffixScore scores pieces xs'\n\nflipValueOf :: Integer -> Char -> Integer\nflipValueOf n 'A' = n\nflipValueOf n 'B' = (-n)\n\nprefixScore :: [Integer] -> String -> [Integer] -> [Integer]\nprefixScore scores pieces xs = suffixScore (reverse scores) (reverse pieces) xs\n\ngetInitialScore :: [Integer] -> String -> Integer\ngetInitialScore scores pieces = sum bsVals\n where bs = ((=='B') . snd ) `filter` (scores `zip` pieces)\n bsVals = map fst bs\n\nmain :: IO()\nmain = do\n n <- getLine >>= return . readInteger\n line <- C8.getLine\n pieces <- getLine\n let\n scores = map (fst . fromJust . C8.readInteger) (C8.words line)\n initialScore = getInitialScore scores pieces\n suffixScores = suffixScore scores pieces [initialScore]\n prefixScores = prefixScore scores pieces [initialScore]\n putStrLn $ show $ (foldl1 max) (suffixScores ++ prefixScores)\n"}], "negative_code": [], "src_uid": "d1926feaeec151f4a2f186a46a863d90"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\n-- readInt :: B.ByteString -> Int\n-- readInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,m,k] <- map read.words <$> getLine\n bs <- B.concat.B.words <$> B.getContents\n let !arr = solve n m bs\n putStrLn.unwords $ map (show.unsafeAt arr) [0..m-1]\n\nsolve :: Int -> Int -> B.ByteString -> UArray Int Int\nsolve n m bs = runSTUArray $ do\n marr <- newArray (0, m - 1) 0 :: ST s (STUArray s Int Int)\n rep n $ \\i -> do\n rep m $ \\j -> do\n case B.index bs (i * m + j) of\n 'U' | even i -> unsafeModify marr j (1+)\n 'R' | j + i < m -> unsafeModify marr (j + i) (1+)\n 'L' | 0 <= j - i -> unsafeModify marr (j - i) (1+)\n _ -> return ()\n return marr", "positive_code": [{"source_code": "import Data.Array.IO\nimport Data.IORef\nimport Control.Monad\nimport Data.Tuple\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Lazy as B\n\nparse :: B.ByteString -> [Int]\nparse s = do\n\tq <- B.splitWith (\\x-> x == 13 || x == 10 || x == 32) s\n\tif B.length q == 0 then\n\t\t[]\n\telse\n\t\treturn $ foldl' (\\a b-> a * 10 + (fromIntegral b) - (ord '0')) 0 (B.unpack q)\n\nmain :: IO ()\nmain = do\n\tn:m:k:_ <- liftM (map read) $ liftM words getLine\n\ts <- (((forM (replicate n 0) $ \\_ -> getLine >>= (newListArray (0, m-1)))) >>= (newListArray (0, n-1))) :: IO (IOArray Int (IOArray Int Char))\n\tr <- ((newArray (0, m-1) 0) :: IO (IOArray Int Int))\n\tforM_ [0..(n-1)] $ \\i -> do\n\t\tline <- readArray s i\n\t\tforM_ [0..(m-1)] $ \\j -> do\n\t\t\tp <- readArray line j\n\t\t\tcase p of\n\t\t\t\t'D' -> return ()\n\t\t\t\t'U' ->\n\t\t\t\t\tif i `mod` 2 == 0 then do\n\t\t\t\t\t\tq <- readArray r j\n\t\t\t\t\t\twriteArray r j (q + 1)\n\t\t\t\t\telse return ()\n\t\t\t\t'L' -> do\n\t\t\t\t\tlet jj = j - i\n\t\t\t\t\tif jj >= 0 && jj < m then do\n\t\t\t\t\t\tq <- readArray r jj\n\t\t\t\t\t\twriteArray r jj (q + 1)\n\t\t\t\t\telse return ()\n\t\t\t\t'R' -> do\n\t\t\t\t\tlet jj = j + i\n\t\t\t\t\tif jj >= 0 && jj < m then do\n\t\t\t\t\t\tq <- readArray r jj\n\t\t\t\t\t\twriteArray r jj (q + 1)\n\t\t\t\t\telse return ()\n\t\t\t\t_ -> return ()\n\t\t\t--qqq <- getElems r\n\t\t\t--putStrLn $ show (i, j, i `mod` 2 > 0, p, qqq)\n\trr <- getElems r\n\tputStrLn $ concat $ map (\\x -> (show x) ++ \" \") rr\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\n-- readInt :: B.ByteString -> Int\n-- readInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,m,k] <- map read.words <$> getLine\n bs <- B.concat.B.words <$> B.getContents\n let !arr = solve n m bs\n putStrLn.unwords $ map (show.unsafeAt arr) [0..m-1]\n\nsolve :: Int -> Int -> B.ByteString -> UArray Int Int\nsolve n m bs = runSTUArray $ do\n marr <- newArray (0,m-1) 0 :: ST s (STUArray s Int Int)\n rep n $ \\i-> do\n rep m $ \\j-> do\n case B.index bs (i*m+j) of\n 'U' | i > 1 -> unsafeModify marr j (1+)\n 'R' | i+j < m -> unsafeModify marr (i+j) (1+)\n 'L' | 0 <= j-i, j-i unsafeModify marr (j-i) (1+)\n _ -> return ()\n return marr"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\n-- readInt :: B.ByteString -> Int\n-- readInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,m,k] <- map read.words <$> getLine\n bs <- B.concat.B.words <$> B.getContents\n let !arr = solve n m bs\n putStrLn.unwords $ map (show.unsafeAt arr) [0..m-1]\n\nsolve :: Int -> Int -> B.ByteString -> UArray Int Int\nsolve n m bs = runSTUArray $ do\n marr <- newArray (0, m - 1) 0 :: ST s (STUArray s Int Int)\n rep n $ \\i -> do\n rep m $ \\j -> do\n case B.index bs (i * m + j) of\n 'U' | i > 1 -> unsafeModify marr j (1+)\n 'R' | j + i < m, i > 0 -> unsafeModify marr (j + i) (1+)\n 'L' | 0 <= j - i, j - i < m, i > 0 -> unsafeModify marr (j - i) (1+)\n _ -> return ()\n return marr"}], "src_uid": "d8c89bb83592a1ff1b639f7d53056d67"} {"source_code": "\n{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [d, h, v, e] <- fmap (map read . words) getLine\n maybe (putStrLn \"NO\") (\\x -> putStrLn \"YES\" >> print x) (solve d h v e)\n \n\n\nsolve :: Double -> Double -> Double -> Double -> Maybe Double\nsolve d h v e | v - e' > epsilon = Just $ (h*pi *(d/2)**2)/(v - e')\n | otherwise = Nothing\n where \n e' = e*pi*(d/2)**2\n epsilon = 10**(-6)\n", "positive_code": [{"source_code": "solve::(Double, Double, Double, Double) -> String\nsolve (d,h,v,e) = do \n\t\tlet a = e * d * d * pi / 4\n\t\tif v <= a then \"NO\" else \"YES\\n\" ++ show ((h * d * d * pi/4)/(v - a))\n\nmain = getLine >>= (putStrLn . solve . getFour . map (\\x -> read x :: Double) . words)\n\twhere \n\t\tgetFour (a : b : c : d : xz) = (a, b, c, d)"}, {"source_code": "main = getLine >>= putStr . unlines . solve . map (read :: String -> Double) . words\n\nsolve [d, h, v, e] = if dh < 0\n then [\"YES\", show (-h / dh)]\n else [\"NO\"]\n where dh = e - 4 * v / (pi * d * d) "}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\n-- import Data.UArray\n-- import Data.Array.IArray\n-- import Data.Array.ST\n-- import Data.Array.MArray\n-- import Data.Array.Unsafe\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntSet (IntSet)\n-- import qualified Data.IntSet as S\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as M\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n-- import Debug.Trace\n\nmain = do\n xs <- map fromIntegral . readIntN <$> BS.getLine\n printMaybe $ solve xs\n\nsolve :: [Double] -> Maybe Double\nsolve [d,h,v,e] = if 0 < ans && ans < 10000 then Just ans else Nothing where\n ans = h/(4*v/pi/d/d - e)\n\nprintMaybe (Just x) = do\n putStrLn \"YES\"\n print x\nprintMaybe Nothing = do\n putStrLn \"NO\"\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\nreadInt641 :: BS.ByteString -> Int64\nreadInt641 = fromIntegral . fst . fromJust . BS.readInteger\n\nreadInt642 :: BS.ByteString -> (Int64,Int64)\nreadInt642 = toTuple . readInt64N\n\nreadInt643 :: BS.ByteString -> (Int64,Int64,Int64)\nreadInt643 = toTriple . readInt64N\n\nreadInt64N :: BS.ByteString -> [Int64]\nreadInt64N = map readInt641 . BS.words\n\nreadInteger1 :: BS.ByteString -> Integer\nreadInteger1 = fst . fromJust . BS.readInteger \n\nreadInteger2 :: BS.ByteString -> (Integer,Integer)\nreadInteger2 = toTuple . readIntegerN\n\nreadInteger3 :: BS.ByteString -> (Integer,Integer,Integer)\nreadInteger3 = toTriple . readIntegerN\n\nreadIntegerN :: BS.ByteString -> [Integer]\nreadIntegerN = map readInteger1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)"}, {"source_code": "main = do\n\tinput <- getLine\n\tlet [d, h, v, e] = map (read::String->Double) $ words input\n\tlet\tans = h/(4*v/pi/d^2-e)\n\tif (ans > 0) && (ans /= 1/0)\n\t\tthen putStrLn $ (\"YES\\n\" ++) $ show ans\n\t\telse putStrLn \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\nimport qualified Data.Map as M\n\n \n\nmain=do\n\t [d,h,v,e]<- map read.words <$> getLine::IO [Double]\n\t if pi/4.0 *d*d *e >v then putStrLn \"NO\" \n\t\t\t else do\n\t\t\t\t\tputStrLn \"YES\"\n\t\t\t\t\tprint $ (pi/4.0 *d*d *h) / (v-pi/4.0 *d*d *e)\n"}, {"source_code": "main = do\n [d, h, v, e] <- getLine >>= return. map read. words\n let ans = a * h / (v - e * a) where a = (d / 2)^2 * pi\n putStrLn $ if ans < 0 then \"NO\" else \"YES\"\n putStr $ if ans < 0 then [] else show ans ++ \"\\n\"\n"}, {"source_code": "main = do\n s <- getLine\n let [d, h, v, e] = map read . words $ s\n v' = v / (3.1415926 * d * d / 4)\n res = h / (v' - e)\n if v' <= e\n then putStrLn \"NO\"\n else putStrLn \"YES\" >> print res\n\n"}, {"source_code": "import Data.Bits\n\n-- import Data.List (List)\nimport qualified Data.List as List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport System.IO\nimport Text.Read\n\nparseLine :: IO [Double]\nparseLine = do\n input <- getLine\n return ((map read . words) input :: [Double])\n\nsolveN 0 ans = return ans\nsolveN n ans = do\n ls <- parseLine\n let [d, h, v, e] = ls\n solveN 0 (pi * d ^ 2 * h / (4 * v - pi * d ^ 2 * e))\n\nmain :: IO ()\nmain\n -- input <- getLine\n -- let (n:k:_) = (map read . words) input :: [Int]\n -- p <- parseLine\n = do\n input <- solveN 1 0.0\n if input >= 0\n then do\n putStrLn \"YES\"\n print input\n else putStrLn \"NO\"\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.List (group, sort)\n\nsolve :: Float -> Float -> Float -> Float -> Maybe Float\nsolve d h v e = if vPlus >= vMinus\n then Nothing\n else Just $ vInit / (vMinus - vPlus)\n where vPlus = e * pi * (d/2)^2\n vMinus = v\n vInit = pi * (d/2)^2 * h\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [d,h,v,e] = map read (words line) :: [Float]\n let d' = d / 100 -- cm to m\n h' = h / 100 -- cm to m\n v' = v / (1000*1000) -- ml/s to m3/s\n e' = e / 100 -- cm/s to m/s\n case solve d' h' v' e' of\n Nothing -> putStrLn \"NO\"\n Just t -> do\n putStrLn \"YES\"\n putStrLn (show t)\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n\t[d, h, v, e] <- getRs\n\tcase res d h v e of\n\t\tNothing -> putStrLn \"NO\"\n\t\tJust t -> do\n putStrLn \"YES\"\n print t\n\ngetRs :: IO [Float]\ngetRs = do\n\ts <- getLine\n\treturn $ map read $ words s\n\narea :: (Ord a, Fractional a, Floating a) => a -> a\narea d = let r = d / 2\n in r^2 * pi\n\nres :: (Ord a, Fractional a, Floating a) => a -> a -> a -> a -> Maybe a\nres d h v e = let a = area d\n in resA h v e a\n\nresA :: (Ord a, Fractional a, Floating a) => a -> a -> a -> a -> Maybe a\nresA h v e a = let discr = v - e * a\n in if discr > 0 then Just ( h * a / discr) else Nothing\n"}, {"source_code": "main :: IO()\nmain = output . solve . map read . words =<< getLine\n\nsolve :: [Double] -> Maybe Double\nsolve [d, h, v, e] | pi / 4.0 * d * d * e > v = Nothing\n | otherwise = Just ((pi / 4.0 * d * d * h) / (v - pi / 4.0 * d * d * e))\n\noutput :: Maybe Double -> IO()\noutput Nothing = putStrLn \"NO\"\noutput (Just x) = putStrLn $ \"YES\\n\" ++ show x\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [d, h, v, e] <- fmap (map read . words) getLine\n\n let x = h*pi*d^2/4 / (v - e*pi*d^2/4) :: Double\n\n if x < 0\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n print x\n"}], "negative_code": [{"source_code": "main :: IO()\nmain = output . solve . map read . words =<< getLine\n\nsolve :: [Double] -> Maybe Double\nsolve [d, h, v, e] | pi / 4.0 * d * d * e > v = Nothing\n | otherwise = Just ((pi / 4.0 * d * d * h) / (v - pi / 4.0 * d * d * e))\n\noutput :: Maybe Double -> IO()\noutput Nothing = putStrLn \"No\"\noutput (Just x) = putStrLn $ \"Yes\\n\" ++ show x\n"}, {"source_code": "\n{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [d, h, v, e] <- fmap (map read . words) getLine\n maybe (putStrLn \"NO\") (\\x -> putStrLn \"YES\" >> print x) (solve d h v e)\n \n\n\nsolve :: Double -> Double -> Double -> Double -> Maybe Double\nsolve d h v e | abs (v - e') > epsilon = Just $ (h*pi *(d/2)**2)/(v - e')\n | otherwise = Nothing\n where \n e' = e*pi*(d/2)**2\n epsilon = 10**(-7)\n"}, {"source_code": "\n{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [d, h, v, e] <- fmap (map read . words) getLine\n maybe (putStrLn \"NO\") (\\x -> putStrLn \"YES\" >> print x) (solve d h v e)\n \n\n\nsolve :: Double -> Double -> Double -> Double -> Maybe Double\nsolve d h v e | v > e' = Just $ (pi *(d/2)**2)/(v - e')\n | otherwise = Nothing\n where \n e' = e*pi*(d/2)**2\n"}, {"source_code": "solve::(Double, Double, Double, Double) -> String\nsolve (d,h,v,e) = do \n\t\tlet a = e * d * pi / 4\n\t\tif v <= a then \"NO\" else \"YES\\n\" ++ show ((h * d * pi/4)/(v - a))\n\nmain = getLine >>= (putStrLn . solve . getFour . map (\\x -> read x :: Double) . words)\n\twhere \n\t\tgetFour (a : b : c : d : xz) = (a, b, c, d)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\nimport qualified Data.Map as M\n\n \n\nmain=do\n\t [d,h,v,e]<- map read.words <$> getLine::IO [Double]\n\t if 3.14/4.0 *d*d *e >v then putStrLn \"NO\" \n\t\t\t else do\n\t\t\t\t\tputStrLn \"YES\"\n\t\t\t\t\tprint $ (3.14/4.0 *d*d *h) / (v-3.14/4.0 *d*d *e)\n"}], "src_uid": "fc37ef81bb36f3ac07ce2c4c3ec10d98"} {"source_code": "main = interact $ unlines . map (show . solve) . triplets . map read . tail . words\ntriplets (a:b:c:xs) = (a,b,c) : triplets xs\ntriplets [] = []\nsolve (l,r,d) | l > d = d\n | otherwise = (r + d) `div` d * d\n", "positive_code": [{"source_code": "main = getContents >>= putStr . unlines . map answer . tail . lines\n\nanswer = show . solve . map read . words\n\nsolve [l,r,d]\n | l > d = d\n | otherwise = ((r + d) `div` d) * d\n"}, {"source_code": "-- Educational Codeforces Round #58 (A), Contest 1101, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n q <- read <$> getLine\n replicateM_ q $ do\n [l,r,d] <- map read . words <$> getLine\n print $ query l r d\n\nquery :: Int -> Int -> Int -> Int\nquery l r d\n | d < l = d\n | otherwise = r + d - r `mod` d\n"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nsolve :: Int -> Int -> Int -> Int\nsolve l r d\n | d < l = d\n | otherwise = ((r `div` d) + 1) * d \n\nmain :: IO ()\nmain = do\n q <- readInt <$> getLine\n replicateM_ q $ do\n [l, r, d] <- (map readInt . words) <$> getLine\n printf \"%d\\n\" $ solve l r d"}, {"source_code": "main = do\n s <- getContents\n printSolution $ solve $ parse s\n \nparse :: String -> [(Integer, Integer, Integer)]\nparse s = f $ tail $ words s\n\nf (l:r:d:v) = (read l, read r, read d):(f v)\nf _ = []\n\nsolve :: [(Integer, Integer, Integer)] -> [Integer]\nsolve xs = map solveQuery xs\n\nsolveQuery (l, r, d) = if d < l then d else ((div r d) + 1) * d\n\nprintSolution (x:xs) = do\n print x\n printSolution xs\nprintSolution [] = return ()\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nsolve l r d\n | d < l = d\n | otherwise = r `div` d * d + d\n\nmain = do\n [n] <- getInts\n ans <- forM [1..n] $ \\i -> do\n [l, r, d] <- getInts\n return $ solve l r d\n \n mapM_ print ans"}], "negative_code": [], "src_uid": "091e91352973b18040e2d57c46f2bf8a"} {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve [x,y] = (d `div` 5) + e `div` 2 + e `mod` 2\n where\n d= abs (x-y)\n e=d `mod` 5\n\nroutine :: IO ()\nroutine = do\n l <- (map read.words) <$> getLine\n print $ solve l\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nf :: Int -> Int\nf x\n |r == 0 = t\n |or [r == 4, r == 3] = t + 2\n |otherwise = t + 1\n where r = x `mod` 5\n t = x `div` 5\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n a <- fmap (sort . fmap read . words) getLine\n print $ f ((a !! 1) - (a !! 0))\n"}, {"source_code": "import Control.Monad ( replicateM_ )\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n [x, y] <- fmap (fmap read . words) getLine\n let diff = abs $ x - y\n div5 = diff `div` 5\n rem1 = (diff - div5 * 5)\n div2 = rem1 `div` 2\n remain = rem1 - (div2 * 2)\n print $ div5 + div2 + remain"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess (a:b:[]) | y==0 = x\n | y<=2 = x+1\n\t\t | otherwise = x+2 \n\t\twhere \tx= div (abs (a-b)) 5\n y= mod (abs (a-b)) 5\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\ta<-map (map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n\t\tmapM_ print $ map process a\n\n"}, {"source_code": "process :: Int -> Int -> [Int] -> Int\nprocess a b xs = sum $ zipWith div (scanr (flip mod) d (tail xs)) xs\n where d = abs (a-b)\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n [a,b] <- fmap (map readInt.words) getLine\n print $ process a b [1,2,5]\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": " import Control.Monad\n import Data.List\n \n f :: Int -> Int\n f x\n |r == 0 = t\n |or [r == 4, r == 3] = t + 2\n |otherwise = t + 1\n where r = x `mod` 5\n t = x `div` 5\n \n main = do\n t <- readLn\n replicateM_ t $ do\n a <- fmap (sort . fmap read . words) getLine\n print $ f ((a !! 1) - (a !! 0))"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Monad(forM_, liftM, replicateM, replicateM_)\n\n--import Debug.Trace\ntraceShowId :: a -> a\ntraceShowId = id\n\n-- Input parsing\nparseInts :: String -> [Int]\nparseInts str = map read (words str)\n\nlist2pair :: [a] -> (a, a)\nlist2pair [x, y] = (x, y)\n\nparseIntsM :: IO [Int]\nparseIntsM = parseInts <$> getLine\n\n-- Solution\n\ndata State = State {\n dist :: Int,\n steps :: Int\n}\n\nstep :: Int -> State -> State\nstep k s = \n let d = dist s in \n State (d `mod` k) (steps s + (d `div` k))\n\nstepCount :: Int -> Int -> Int\nstepCount a b = steps . (step 1) . (step 2) . (step 5) $ (State (abs (b - a)) 0) \n\ntaskM :: IO ()\ntaskM = do\n [a, b] <- parseIntsM\n print $ stepCount a b\n\nmain :: IO ()\nmain = do\n [t] <- parseIntsM\n replicateM_ t taskM"}], "negative_code": [], "src_uid": "ccfe798f5dc63c492ff54cf40bb40613"} {"source_code": "import Control.Monad\n\nf :: (Int,Int) -> Char -> (Int,Int)\nf (ans,open) '(' = (ans,open+1)\nf (ans,open) ')'\n | open > 0 = (ans,open-1)\n | otherwise = (ans+1,open)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n getLine\n s <- getLine\n print . fst $ foldl f (0,0) s\n", "positive_code": [{"source_code": "import Control.Monad\n\ntype Test = String\n\ngetLines :: Int -> IO [Test]\ngetLines count = replicateM count getTest\n\ngetTest :: IO Test\ngetTest = do\n _ <- getLine\n line <- getLine\n return line\n\ngetAnswer :: [Test] -> [Integer]\ngetAnswer [] = []\ngetAnswer (first:rest) = (process first 0 0 0) : getAnswer rest\n\nprocess :: Test -> Integer -> Integer -> Integer -> Integer\nprocess [] opened closed amount = 0\nprocess (first:rest) opened closed amount = if first == '('\n then toAdd + process rest (opened + 1) closed (amount + add)\n else toAdd + process rest opened (closed + 1) (amount + add)\n where toAdd = if closed > opened && (closed - opened > amount)\n then add\n else 0\n add = if closed > opened && (closed - opened > amount)\n then closed - opened - amount\n else 0\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getLines (read count)\n mapM_ print (getAnswer tests)"}, {"source_code": "bracketToNumber :: Char -> Int\nbracketToNumber '(' = 1\nbracketToNumber ')' = -1\n\nsolve :: String -> Int\nsolve = negate . minimum . scanl (+) 0 . map bracketToNumber\n\nmain :: IO ()\nmain = interact $ unlines . map show . map solve . map snd . filter (even . fst) . zip [1 .. ] . tail . lines"}, {"source_code": "{-# OPTIONS -O2 #-}\n\nimport Control.Monad (replicateM_)\nimport Control.Monad.Writer\n\nmain = readLn >>= flip replicateM_ (getLine >> getLine >>= print . f)\n\nf :: String -> Int\nf = counter 0 where\n counter :: Int -> String -> Int\n counter _ [] = 0\n counter n (x:xs) = case x of\n '(' -> counter (n+1) xs\n ')' | n > 0 -> counter (n-1) xs\n | otherwise -> 1 + counter n (xs ++ \")\")\n x -> error $ \"Strange character \" ++ show x\n\n\n"}, {"source_code": "import Control.Monad (forM_, replicateM)\n\nmain = do\n t <- readLn\n bracketStrings <- replicateM t $ getLine >> getLine\n forM_ bracketStrings (\\s -> print (snd (foldl (\\(l, c) p -> if p == '('\n then (l+1, c)\n else if l == 0\n then (0, c+1)\n else (l-1, c)) (0, 0) s)))\n"}, {"source_code": "import Control.Monad (forM_, replicateM)\n\nmain = do\n t <- readLn\n replicateM t $ do\n getLine\n s <- getLine\n print $ snd $ foldl (\\(l, c) p -> if p == '('\n then (l+1, c)\n else if l == 0\n then (0, c+1)\n else (l-1, c)) (0, 0) s\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_: l : rest) = (itoline . solve ) l : tcio rest \n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: String -> Int\nsolve cs = maximum $ scanl (flip (\\c-> if c==')' then (+1) else (subtract 1))) 0 cs\n"}], "negative_code": [{"source_code": "import Control.Monad\n\ntype Test = String\n\ngetLines :: Int -> IO [Test]\ngetLines count = replicateM count getTest\n\ngetTest :: IO Test\ngetTest = do\n _ <- getLine\n line <- getLine\n return line\n\ngetAnswer :: [Test] -> [Integer]\ngetAnswer [] = []\ngetAnswer (first:rest) = (process first 0 0 0) : getAnswer rest\n\nprocess :: Test -> Integer -> Integer -> Integer -> Integer\nprocess [] opened closed amount = 0\nprocess (first:rest) opened closed amount = if first == '('\n then toAdd + process rest (opened + 1) closed (amount + add)\n else toAdd + process rest opened (closed + 1) (amount + add)\n where toAdd = if closed > opened && (closed - opened > amount)\n then add\n else 0\n add = if closed > opened && (closed - opened > amount)\n then closed - opened - amount\n else 0\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getLines (read count)\n print (getAnswer tests)"}], "src_uid": "7a724f327c6202735661be25ef9328d2"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nimport Control.DeepSeq\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}\n\n\nmain :: IO ()\nmain = do\n [m,n] <- map read.words <$> getLine\n xss <- slices n.map readInt.B.words <$> B.getContents\n putStr.unwords.map show $ solve $ transpose xss\n\nsolve :: [[Int]] -> [Int]\nsolve (xs:xss) = foldl' step (scanl1 (+) xs) xss\n where\n step :: [Int] -> [Int] -> [Int]\n step times ys = times`deepseq`go 0 times ys\n where\n go !time (t:times) (y:ys)\n | time <= t = (t+y) : go (t+y) times ys\n | otherwise = (time+y) : go (time+y) times ys\n go _ _ _ = []\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO()\nmain = putStrLn . unwords . map show . solve . map (fst . fromJust . C.readInt) . C.words =<< B.getContents\n\nsolve :: [Int] -> [Int]\nsolve (n:m:a) = let b = transpose $ rect 0 [] a\n in solve' b (replicate n 0)\n where rect :: Int -> [Int] -> [Int] -> [[Int]]\n rect _ l [] = [reverse l]\n rect i l (a:s) | i == m = reverse l : rect 0 [] (a:s)\n | otherwise = rect (i + 1) (a:l) s\n\n solve' :: [[Int]] -> [Int] -> [Int]\n solve' s t = foldl (\\ t l -> addTo (head t) l t) t s\n\n addTo :: Int-> [Int] -> [Int] -> [Int]\n addTo _ [] [] = []\n addTo f (l:ls) (t:ts) = let nt = l + max f t\n in nt : addTo nt ls ts\n"}, {"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO()\nmain = putStrLn . unwords . map show . solve . map (fst . fromJust . C.readInt) . C.words =<< B.getContents\n\nsolve :: [Int] -> [Int]\nsolve (n:m:a) = let b = transpose $ rect 0 [] a\n in solve' b (replicate n 0)\n where rect :: Int -> [Int] -> [Int] -> [[Int]]\n rect _ l [] = [reverse l]\n rect i l (a:s) | i == m = reverse l : rect 0 [] (a:s)\n | otherwise = rect (i + 1) (a:l) s\n\n solve' :: [[Int]] -> [Int] -> [Int]\n solve' [] t = t\n solve' (l:s) t = solve' s (addTo (head t) l t)\n\n addTo :: Int-> [Int] -> [Int] -> [Int]\n addTo _ [] [] = []\n addTo f (l:ls) (t:ts) = let nt = l + max f t\n in nt : addTo nt ls ts\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map readInt . C.words <$> C.getLine\n\ngao :: [Int] -> [Int] -> [Int]\ngao a b = let c = zipWith (+) b $ zipWith max a (0:c) in c\n\nmain :: IO ()\nmain = do\n [m,n] <- getInts\n arr <- replicateM m getInts\n let ans = tail . map last $ scanl gao (replicate n 0) arr\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\ngao :: [Int] -> [Int] -> [Int]\ngao a b = let c = zipWith (+) b $ zipWith max a $ 0: c in c\n\nmain :: IO ()\nmain = do\n (m:n:_) <- getInts\n a <- replicateM m $ getInts\n let ans = tail . map last $ scanl gao (replicate n 0) a\n putStrLn $ unwords $ map show ans\n where\n getInts = map readInt . C.words <$> C.getLine\n"}], "negative_code": [], "src_uid": "43f4ea06d8b8b0b6b6795a3d526c5a2d"} {"source_code": "import Data.Foldable\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport Data.Traversable\n\ngetLineOfInts :: IO [Int]\ngetLineOfInts = do\n line <- getLine\n let ints = read <$> words line :: [Int]\n return ints\n\nputLineOfInts :: [Int] -> IO ()\nputLineOfInts xs =\n putStrLn $ unwords $ (show <$> xs)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n\n for_ [1..t] $ \\_ -> do\n [n, m] <- getLineOfInts\n\n rows <- for [1..n] $ \\_ -> getLineOfInts\n cols <- for [1..m] $ \\_ -> getLineOfInts\n\n let memberOfFirstCol = head $ head rows\n let firstCol = fromJust $ find (memberOfFirstCol `elem`) cols\n\n let rowIndex r = fromJust $ elemIndex (head r) firstCol\n let indexedRows = (\\r -> (rowIndex r, r)) <$> rows\n\n let sortedIndexedRows = sortBy (compare `on` fst) indexedRows\n\n for sortedIndexedRows $ \\(_, r) -> putLineOfInts r\n", "positive_code": [{"source_code": "{-# LANGUAGE BlockArguments, BangPatterns, LambdaCase, TypeApplications #-}\n\nimport Prelude\nimport Data.List as L\nimport Data.Maybe\nimport Data.Functor\nimport Data.Foldable\nimport Data.Bifunctor\nimport Data.Function\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 as B\nimport Control.Arrow\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n do\n [n, m] <- fmap int . B.words <$> B.getLine\n rows <- replicateM n $ (id &&& Set.fromList) . fmap int . B.words <$> B.getLine\n c : cols <- replicateM m $ fmap int . B.words <$> B.getLine\n B.putStr $ B.unlines $ fmap (B.unwords . fmap (B.pack . show)) $ fmap (`selectContaining` rows) c\n where\n selectContaining n = fst . fromJust . L.find (Set.member n . snd)\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a\n"}], "negative_code": [], "src_uid": "0eab9d2dd60d38f68d49f30cff918fce"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport Data.List\nimport Data.Int\n\ndefault (Int)\nmain = interact exec\nexec = show . uncurry solve . (\\(n:xs) -> splitAt n xs) . map read . words\nsolve (rsort -> xs) (rsort -> ys) = play (0 :: Int64) (0 :: Int64) xs ys\nplay a b [] [] = a - b\nplay a b (x:xs) [] = play b (a +. x) [] xs\nplay a b [] (_:ys) = play b a ys []\nplay a b xxs@(x:xs) yys@(y:ys)\n | x >= y = play b (a +. x) yys xs\n | x < y = play b a ys xxs\nrsort = sortBy (flip compare)\n\na +. b = a + fromIntegral b", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\n\nmain = do\n n <- readLn :: IO Int\n as <- reverse . sort . map read . words <$> getLine :: IO [Integer]\n bs <- reverse . sort . map read . words <$> getLine :: IO [Integer]\n\n let (x,y) = foldl (\\(a,b) (c,d) -> (a+c,b+d)) (0,0) (solve 0 as bs)\n print $ x - y\n\nsolve _ [] [] = []\nsolve t [] (b:bs) = if t == 0 then solve 1 [] bs else (0,b) : solve 0 [] bs\nsolve t (a:as) [] = if t == 0 then (a,0) : solve 1 as [] else solve 0 as []\nsolve t (a:as) (b:bs)\n | t == 0 = if a > b then (a,0) : solve 1 as (b:bs) else solve 1 (a:as) bs\n | t == 1 = if a < b then (0,b) : solve 0 (a:as) bs else solve 0 as (b:bs)"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- readLn :: IO Int\n as <- reverse . sort . map read . words <$> getLine :: IO [Int]\n bs <- reverse . sort . map read . words <$> getLine :: IO [Int]\n\n let (x,y) = foldl (\\(a,b) (c,d) -> (a+c,b+d)) (0,0) (solve 0 as bs)\n print $ x - y\n\nsolve _ [] [] = []\nsolve t [] (b:bs) = if t == 0 then solve 1 [] bs else (0,b) : solve 0 [] bs\nsolve t (a:as) [] = if t == 0 then (a,0) : solve 1 as [] else solve 0 as []\nsolve t (a:as) (b:bs)\n | t == 0 = if a > b then (a,0) : solve 1 as (b:bs) else solve 1 (a:as) bs\n | t == 1 = if a < b then (0,b) : solve 0 (a:as) bs else solve 0 as (b:bs)\n"}, {"source_code": "{-# LANGUAGE ExistentialQuantification, NoMonomorphismRestriction #-}\nmodule Main where\nimport Data.Int\nimport Control.Applicative\ndefault (Int64)\nmain = interact exec\nexec = show . solve . tail . map read . words\nsolve = runFold ((\\s p n m -> if p && n then s else s - 2 * m) <$> premap abs sumf <*> anyf (>= 0) <*> anyf (<= 0) <*> premap abs minf)\nsumf = Fold (+) 0 id\nanyf f = Fold (\\a x -> a || f x) False id\nminf = Fold min maxBound id\n\ndata Fold a b = forall x. Fold (x -> a -> x) x (x -> b)\ndata Pair a b = Pair !a !b\ninstance Functor (Fold a) where\n fmap f (Fold step begin done) = Fold step begin (f . done)\ninstance Applicative (Fold a) where\n pure b = Fold (\\() _ -> ()) () (\\() -> b)\n (Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =\n let step (Pair xL xR) a = Pair (stepL xL a) (stepR xR a)\n begin = Pair beginL beginR\n done (Pair xL xR) = doneL xL (doneR xR)\n in Fold step begin done\nrunFold (Fold step begin done) as = foldr (\\a k x -> k $! step x a) done as begin\npremap f (Fold step begin done) = Fold step' begin done\n where\n step' x a = step x (f a)\n"}], "src_uid": "d740f4ee1b18eeb74dfb253125c52762"} {"source_code": "import qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\n\ntype ColourMap = Map.Map Char [Int]\n\nzipWithRemainder :: [a] -> [b] -> ([(a, b)], [a], [b])\nzipWithRemainder a b = helper a b []\n where helper (ah:at) (bh:bt) acc = helper at bt ((ah,bh):acc)\n helper a b acc = (acc, a, b)\n\nquery q map = Map.findWithDefault [] q map\n\ngetColourMap :: String -> ColourMap\ngetColourMap inp = Map.fromListWith (++) $ zip inp (map return [1..])\n\nstage1 :: ColourMap -> ColourMap -> ([(Int, Int)], ColourMap, ColourMap)\nstage1 a b = helper (Map.keys a) (Map.keys b) a b []\n where helper [] _ a b acc = (acc, a, b)\n helper _ [] a b acc = (acc, a, b)\n helper ak@(ah:at) bk@(bh:bt) a b acc\n | ah < bh || ah == '?' = helper at bk a b acc\n | ah > bh || bh == '?' = helper ak bt a b acc\n | otherwise = \n let\n (pairs, newa, newb) = zipWithRemainder (query ah a) (query bh b)\n in\n helper at bt (Map.insert ah newa a) (Map.insert bh newb b) (pairs ++ acc)\n\nstage2 :: ([(Int, Int)], ColourMap, ColourMap) -> ([(Int, Int)], ColourMap, ColourMap)\nstage2 arg = (helperB. helperA) arg\n where\n helperA (acc, a, b) = let\n aWild = query '?' a\n pairWild [] _ b acc = ([], b, acc)\n pairWild wilds [] b acc = (wilds, b, acc)\n pairWild wilds ('?':bt) b acc = pairWild wilds bt b acc\n pairWild wilds (bh:bt) b acc = \n let\n (pairs, newWilds, newb) = zipWithRemainder wilds (query bh b)\n in\n pairWild newWilds bt (Map.insert bh newb b) (pairs ++ acc)\n (newWild, newB, newAcc) = pairWild aWild (Map.keys b) b []\n in\n (newAcc ++ acc, Map.insert '?' newWild a, newB)\n helperB (acc, a, b) = \n let\n inv (a, b) = (b, a)\n (pairs, nb, na) = helperA ([], b, a)\n in\n ((map inv pairs) ++ acc, na, nb)\n\nstage3 (acc, a, b) = acc ++ zip (query '?' a) (query '?' b)\n\nmain = do\n n <- getLine\n a <- getLine\n b <- getLine\n let sol = (stage3 . stage2) $ stage1 (getColourMap a) (getColourMap b)\n putStrLn . show $ length sol\n let showPair (a, b) = (show a) ++ (' ' : show b)\n mapM_ (putStrLn . showPair) sol\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Array\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nc :: Char -> Int\nc '?' = 0\nc x = ord x - 96\n\ncvt :: C.ByteString -> Array Int [Int]\ncvt !s = accumArray ins [] (0, 26) $ (`zip` [1 .. ]) $ map c $ C.unpack s\n where\n ins e a = a : e\n\nmerge a b = l `seq` (zip a b, drop l a, drop l b)\n where\n l = min (length a) (length b)\n\nsolve :: [C.ByteString] -> Builder\nsolve (sn:x:y:l) = intDec (length res) <> char7 '\\n' <> (mconcat $ map enc res) \n where\n n = ri $ C.takeWhile isDigit sn\n a = cvt $ C.take n x\n b = cvt $ C.take n y\n res = loop 1 [] (a ! 0) (b ! 0)\n enc (u, v) = intDec u <> char7 ' ' <> intDec v <> char7 '\\n'\n loop i r u v\n | i > 26 = let (r', u', v') = merge u v in concat (r' : r)\n | otherwise = loop (succ i) (d : d0 : d1 : r) u' v'\n where\n ai = a ! i\n bi = b ! i\n (d, ai', bi') = merge ai bi\n (d0, ai'', v') = merge ai' v\n (d1, u', bi'') = merge u bi'\n\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.lines =<< C.getContents\n"}], "negative_code": [], "src_uid": "6bf3e5a542ebce81c1e6ce7260644a3c"} {"source_code": "f :: Int -> [Int] -> Bool\nf n (x:xs) = let k = (n-x) `mod` n\n in check n k 1 xs\n\ncheck :: Int -> Int -> Int -> [Int] -> Bool\ncheck _ _ _ [] = True\ncheck n k i (x:xs) | odd i = (if x >= k then x - k else n - (k - x)) == i && check n k (i+1) xs\n | even i = (x + k) `mod` n == i && check n k (i+1) xs\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (map read . words) getLine\n putStrLn $ if f n xs then \"Yes\"\n else \"No\"\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\nsolve xs@(x:_) n = \n (zipWith (\\a b -> (a + b * x) `mod` n) xs (cycle [-1, 1])) == [0..(n-1)]\n\n\nmain = do\n n <- readInt <$> getLine\n xs <- map readInt . words <$> getLine\n putStrLn (if solve xs n then \"Yes\" else \"No\")\n\n"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> [Int] -> Bool\nsolve n list@(x:xs) = and . zipWith (\\y (i,z) -> ((y+z) `mod` n) == i) list . zip [0..n-1] $ cycle [n-x,x]\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read . words <$> getLine\n putStrLn $ if solve n xs == True\n then \"Yes\"\n else \"No\""}, {"source_code": "main :: IO()\nmain = putStrLn . solve . map read . words =<< getContents\n\nsolve :: [Int] -> String\nsolve (n:a) = solve' 0\n where\n solve' :: Int -> String\n solve' m | m == n = \"No\"\n | check a m 0 True = \"Yes\"\n | otherwise = solve' (m+1)\n \n check :: [Int] -> Int -> Int -> Bool -> Bool\n check [] _ _ _ = True\n check (a:ax) s i add | add && (rem (a+s) n) == i = check ax s (i+1) False\n | (not add) && (rem (a-s+n) n) == i = check ax s (i+1) True\n | otherwise = False\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/556B.hs\n\n--------------------------------\n\ncreateGears :: Int -> [Int] -> [[Int]]\ncreateGears n active = createGears' True active\n\twhere\n\t\tcreateGears' _ [] = []\n\t\tcreateGears' isOdd (a:as)\n\t\t\t| isOdd = (drop a $ cycle [0..(n-1)]) : createGears' (not isOdd) as\n\t\t\t| otherwise = (drop (n-a-1) $ cycle [(n-1),(n-2)..0]) : createGears' (not isOdd) as\n\ncheckGears :: Int -> [[Int]] -> Bool\ncheckGears 0 _ = False\ncheckGears n gears\n\t| sequenced = True\n\t| otherwise = checkGears (n-1) (pushButton gears)\n\twhere\n\t\tsequenced = isSequence $ map head gears\n\t\tpushButton xs = map (drop 1) $ xs\n\nisSequence :: (Enum a, Eq a) => [a] -> Bool\t\t\nisSequence [] = True\nisSequence (x:[]) = True\nisSequence (x:y:zs)\n\t| y == succ x = isSequence $ y:zs\n\t| otherwise = False\n\n--------------------------------\n\n\nmain = do\n\n\tn <- fmap read $ getLine :: IO Int\n\tactive <- fmap (map read) $ fmap words $ getLine :: IO [Int]\n\n\tlet\n\t\tvalid = checkGears n $ createGears n active\n\n\tcase valid of\n\t\tTrue -> putStrLn \"Yes\"\n\t\tFalse -> putStrLn \"No\""}, {"source_code": "import Data.List\n\nmain = getContents >>= putStrLn . (\\b -> if b then \"Yes\" else \"No\") . solve . map read . tail . words\n\nsolve :: [Int] -> Bool\nsolve xs = foldl1 (||) [solve' xs i | i <- [1..length xs]]\n\nsolve' xs i = let ys = go xs i (length xs) in ys == [0..length xs-1]\n\ngo [] _ _ = []\ngo (x:xs) i n = mod (x + i) n : go xs (n - i) n\n"}, {"source_code": "readInts :: IO [Integer]\nreadInts = fmap (map read.words) getLine\n\nf :: [Integer] -> Integer -> Bool -> [Integer]\nf [] _ _ = []\nf (x:xs) n b\n | b = (x+n) : f xs n (not b)\n | otherwise = (x-n) : f xs n (not b)\n\nmain = do\n n <- getLine\n tab <- readInts\n let d = head tab in\n putStrLn $ if (map (flip mod $ read n) $ f tab d False) == (take (read n) [0..])\n then \"Yes\"\n else \"No\"\n"}, {"source_code": "import Data.List (group)\n\nprobB line = if (length . group) b == 1 then \"Yes\" else \"No\"\n where a = map read $ words line :: [Int]\n n = length a\n f x y = if even y then y - x else x - y\n b = map ((`mod` n ).(+ n)) $ zipWith f a [0..]\n\nmain = do\n _ <- getLine\n line <- getLine\n putStrLn $ probB line\n"}, {"source_code": "probB line = if loop (n + 1) a then \"Yes\" else \"No\"\n where\n a = map read $ words line :: [Int]\n n = length a\n f x y = (x + y + n) `mod` n\n loop (-1) _ = False\n loop _ a | foldr (&&) True $ zipWith (==) a [0..n-1] = True\n loop k a = loop (k-1) $ zipWith f a $ cycle [1, -1]\n\nmain = do\n _ <- getLine\n line <- getLine\n putStrLn $ probB line\n"}, {"source_code": "module Main where\n\nparse x = (takeWhile (/=' ') x) : if (null rest) then [] else parse (tail $ (dropWhile (/=' ')) x) where\n rest = dropWhile (/=' ') x\n\nread'::String->Int\nread'=read\nisOk :: Int -> [Int] -> Bool\nisOk n [] = True\nisOk n [x] = True\nisOk n (x:y:z) = mod (x + y) n == 0 && isOk n (y:z)\n\nword True = \"Yes\"\nword False = \"No\"\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n putStr $ word $ isOk (read s1) $ map (`mod` (read s1)) $ zipWith (-) [0..(read s1)-1] (map read' $ parse s2)"}, {"source_code": "bool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nparse :: String -> [Int]\nparse contents = map read (words a)\n where [_, a] = lines contents\n\nsolve :: [Int] -> Bool\nsolve a = any isPermutation . take n . iterate rotate $ a\n where n = length a\n isPermutation = (== [0..n - 1])\n rotate = zipWith plus (cycle [1, n - 1])\n x `plus` y = (x + y) `rem` n\n\nmain :: IO ()\nmain = putStrLn . bool \"No\" \"Yes\" . solve . parse =<< getContents\n"}], "negative_code": [{"source_code": "import Data.List (sort)\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nparse :: String -> [Int]\nparse contents = map read (words a)\n where [_, a] = lines contents\n\nsolve :: [Int] -> Bool\nsolve a = any (isPermutation . rotation) [0..n - 1]\n where n = length a\n isPermutation = (== [0..n - 1]) . sort\n rotate d = (`rem` n) . (+ d)\n rotation d = zipWith rotate (cycle [d, d * (n - 1)]) a\n\nmain :: IO ()\nmain = putStrLn . bool \"No\" \"Yes\" . solve . parse =<< getContents\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\nsolve x xs n = \n (zipWith (\\a b -> (a + b * x) `mod` n) xs (cycle [-1, 1])) == [0..(n-1)]\n\n\nmain = do\n n <- readInt <$> getLine\n (x:xs) <- map readInt . words <$> getLine\n putStrLn (if solve x xs n then \"Yes\" else \"No\")\n\n"}], "src_uid": "6c65ca365352380052b0c9d693e6d161"} {"source_code": "import Data.List\nimport Data.Ord (comparing)\n\ntype Summand = (Int, Int)\t\n\nreadExpression::[Char]->Int->[Summand]\nreadExpression [] _ = []\nreadExpression (x:xs) 0 = let\n\t\t\t\tz = if (x=='-')\tthen (-1) else 1\n\t\t\t\tin readExpression xs z\nreadExpression t z = let\n\t\t\t\t\t\t(s,t1) = readSummand t z\n\t\t\t\t\t\tall = readExpression t1 0\n\t\t\t\t\tin (s:all)\n\t\n\nreadSummand::[Char]->Int->(Summand, [Char])\nreadSummand (x:xs) z | '0'<=x && x<='9' = let\n\t\t\t\t\t\t\t(k,t1) = readCoefficient (read [x]) xs\n\t\t\t\t\t\t\t(i,t2) = readIncrement t1\n\t\t\t\t\t\t\tzk = z*k\n\t\t\t\t\t\t\tin ((zk,i),t2)\n\t\t\t\t\t\t\t\nreadSummand t z = let\t\t\t\t\t\t\n\t\t\t\t\t\t\t(i,t1) = readIncrement t\n\t\t\t\t\t\t\tin ((z,i),t1)\n\t\t\t\t\t\t\t\nreadIncrement::[Char]->(Int, [Char])\nreadIncrement ('+':'+':'a':xs) = (1,xs)\nreadIncrement ('a':'+':'+':xs) = (0,xs)\n\nreadCoefficient::Int->[Char]->(Int, [Char])\nreadCoefficient k ('*':xs) = (k, xs)\nreadCoefficient k (x:xs) = readCoefficient (10*k + (read [x])) xs\n\nsortSummands::[Summand]->[Summand]\nsortSummands xs = sortBy cmpCoeff xs\n\twhere cmpCoeff = comparing fst\n\t\ncalc::Int->[Summand]->Int\ncalc _ [] = 0\ncalc a ((c,i):xs) = let\n\t\t\t\t\ta' = if (i==1) then (a+1) else a\n\t\t\t\t\ts = c * a'\n\t\t\t\t\tin s + (calc (a+1) xs)\n\t\t\t\t\t\ncalc2::[Char]->[Summand]->Int\ncalc2 s x = calc (read s) x\n\nmain = do\n\ta <- getLine\t\n\tx <- getLine\n\tputStrLn (show (calc2 a (sortSummands (readExpression x 1))))", "positive_code": [{"source_code": "import List\nmain = interact f\nf input = output where\n [init,expr] = lines input\n output = show $ cal (read init::Int) $ sort $ coef (\"+\":(summ $ incr expr))\n incr [] = []\n incr ('a':'+':'+':xs) = 'b':(incr xs)\n incr ('+':'+':'a':xs) = 'c':(incr xs)\n incr (x:xs) = x:(incr xs)\n summ [] = []\n summ xs = if null y then [x] else x:[head y]:(summ $ tail y)\n where (x,y) = break (\\x -> x=='+' || x=='-') xs\n coef [] = []\n coef (x:y:xs) = ((if x==\"+\" then 1 else -1) * c,d):(coef xs)\n where\n (v,w) = break (=='*') y\n c = read (if null w then \"1\" else v) :: Int \n d = if null w then v else (tail w) \n cal x [] = 0\n cal x ((y,z):xs) = (if z==\"b\" then y*x else y*(x+1)) + (cal (x+1) xs)"}], "negative_code": [], "src_uid": "766196c156234cc169206dbb7a932fc7"} {"source_code": "import qualified Data.Map.Strict as Map\n\ntoint s = (read s) :: Integer\n\nagregar x m = Map.insertWith (+) x 1 m\nquitar :: Integer -> (Map.Map Integer Integer) -> (Map.Map Integer Integer)\nquitar x m = Map.insertWith (+) x (-1) m\n\ndoit :: [Integer] -> (Map.Map Integer Integer) -> [Integer] -> Integer\ndoit [] s p = 0\ndoit (x:xs) s p =\n\tlet ss = quitar x s in\n\tif any (\\t -> (Map.findWithDefault 0 (t-x) ss) > 0) p then\n\t\tdoit xs s p\n\telse\n\t\t1 + (doit xs s p)\n\nasdasd [] = Map.fromList []\nasdasd (x:xs) = agregar x (asdasd xs)\n\nsolve::String -> String\nsolve ss =\n\tlet x = Prelude.map toint (tail (words ss)) in\n\tlet s = asdasd x in\n\tlet p = Prelude.map (\\x -> 2^x) [0..30] in\n\tlet r = doit x s p in\n\t(show r) ++ \"\\n\"\n\nmain = do\n interact $ solve\n", "positive_code": [{"source_code": "import qualified Data.IntMap.Strict as IntMap\n\nmain = interact $ pureMain\n\npureMain :: String -> String\npureMain s = show $ length $ filter (== False) $ map f a\n where\n [[n], a] = map (map read . words) $ lines s\n m = foldr (\\ k -> IntMap.insertWith (+) k 1) IntMap.empty a\n f n = or $ map (\\ x -> if n == x then m IntMap.! x > 1 else IntMap.member x m) [2^i - n | i <- [0..31]]"}], "negative_code": [{"source_code": "import qualified Data.IntSet as IntSet\n\nmain = interact $ pureMain\n\npureMain :: String -> String\npureMain s = show $ length $ filter (== False) $ map f a\n where\n [[n], a] = map (map read . words) $ lines s\n set = IntSet.fromList a\n f n = or $ map (\\ x -> IntSet.member x set) [2^i - n | i <- [0..31], 2^i - n /= n]"}], "src_uid": "ed308777f7122ca6279b522acd3e58f9"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Array (listArray, elems, (!))\nimport Data.Function (on)\n\ndata Zipper a = Zipper { zleft :: Zipper a, zhead :: a, zright :: Zipper a }\n\nzipper :: [a] -> Zipper a\nzipper xs =\n let (first,last) = go last xs first in first\n where\n go :: Zipper a -> [a] -> Zipper a -> (Zipper a, Zipper a)\n go prev [] next = (next,prev)\n go prev (x:xs) next =\n let\n this = Zipper prev x rest\n (rest,last) = go this xs next\n in (this,last)\n\ndata Result = Result { rcount :: Int, rz :: [Int], rp :: Maybe Result }\n\ninstance Eq Result where\n (==) = (==) `on` rcount\ninstance Ord Result where\n (<=) = (<=) `on` rcount\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n vector l = listArray (1, length l) l\n\n gs = map (map snd) . groupBy ((==) `on` fst) . sort $ zip as [1..]\n\n r@(Result c _ _) = minimum $ solve $ reverse gs\n where\n zs g = take (length g) . iterate zright $ zipper g\n\n d i j = min d' (n-d') where d' = abs $ i-j\n dc i j = if i <= j then j-i else j+n-i -- clockwise distance\n dcc i j = dc j i\n\n right l = map zhead . take l . iterate zright\n left l = map zhead . take l . iterate zleft\n\n solve [g] = map f $ zs g\n where\n l = length g\n f z@(Zipper (Zipper _ p _) i (Zipper _ n _)) =\n min\n (Result (d s p + dc i p) (right l z) Nothing)\n (Result (d s n + dcc i n) (left l z) Nothing)\n\n solve (g:gs) = map f $ zs g\n where\n l = length g\n rs = solve gs\n\n f z@(Zipper (Zipper _ p _) i (Zipper _ n _)) =\n minimum $ map f' rs\n where\n f' r@(Result c (i':_) _) =\n min\n (Result (c + d i' p + dc i p) (right l z) (Just r))\n (Result (c + d i' n + dcc i n) (left l z) (Just r))\n where\n\n restore = zipWith diff is $ tail is\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = (s:) . concat $ reverse $ unfoldr next (Just r)\n where\n next Nothing = Nothing\n next (Just (Result _ l r)) = Just (reverse l, r)\n\n print c\n -- print gs\n -- print is\n putStr $ unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) $ restore\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Function (on)\n\ndata Zipper a = Zipper { zleft :: Zipper a, zhead :: a, zright :: Zipper a }\n\nzipper :: [a] -> Zipper a\nzipper xs =\n let (first,last) = go last xs first in first\n where\n go :: Zipper a -> [a] -> Zipper a -> (Zipper a, Zipper a)\n go prev [] next = (next,prev)\n go prev (x:xs) next =\n let\n this = Zipper prev x rest\n (rest,last) = go this xs next\n in (this,last)\n\ndata Result = Result { rcount :: Int, rz :: [Int], rp :: Maybe Result }\n\ninstance Eq Result where\n (==) = (==) `on` rcount\ninstance Ord Result where\n (<=) = (<=) `on` rcount\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n gs = map (map snd) . groupBy ((==) `on` fst) . sort $ zip as [1..]\n\n r@(Result c _ _) = minimum $ foldl next [Result 0 [s] Nothing] gs\n where\n next rs g = map f . take l . iterate zright $ zipper g\n where\n l = length g\n right = map zhead . take l . iterate zright\n left = map zhead . take l . iterate zleft\n\n f z@(Zipper (Zipper _ prev _) i (Zipper _ next _)) =\n minimum $ map f' rs\n where\n f' r@(Result c (i':_) _) =\n min\n (Result (c + d i' prev + dc i prev) (right z) (Just r))\n (Result (c + d i' next + dcc i next) (left z) (Just r))\n where\n d i j = min d' (n-d') where d' = abs $ i-j\n dc i j = if i <= j then j-i else j+n-i -- clockwise distance\n dcc i j = dc j i\n\n restore = zipWith diff is (tail is)\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = concat . reverse $ unfoldr next (Just r)\n where\n next Nothing = Nothing\n next (Just (Result _ l r)) = Just (reverse l, r)\n\n print c\n putStr . unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) restore\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Function (on)\n\ndata Zipper a = Zipper { zleft :: Zipper a, zhead :: a, zright :: Zipper a }\n\nzipper :: [a] -> Zipper a\nzipper xs =\n let (first,last) = go last xs first in first\n where\n go :: Zipper a -> [a] -> Zipper a -> (Zipper a, Zipper a)\n go prev [] next = (next,prev)\n go prev (x:xs) next =\n let\n this = Zipper prev x rest\n (rest,last) = go this xs next\n in (this,last)\n\ndata Result = Result { rcount :: Int, rz :: [Int], rp :: Maybe Result }\n\ninstance Eq Result where\n (==) = (==) `on` rcount\ninstance Ord Result where\n (<=) = (<=) `on` rcount\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n gs = map (map snd) . groupBy ((==) `on` fst) . sort $ zip as [1..]\n\n r@(Result c _ _) = minimum . solve $ reverse gs\n where\n solve [] = [Result 0 [s] Nothing]\n solve (g:gs) = map f . take l . iterate zright $ zipper g\n where\n l = length g\n right = map zhead . take l . iterate zright\n left = map zhead . take l . iterate zleft\n rs = solve gs\n\n f z@(Zipper (Zipper _ prev _) i (Zipper _ next _)) =\n minimum $ map f' rs\n where\n f' r@(Result c (i':_) _) =\n min\n (Result (c + d i' prev + dc i prev) (right z) (Just r))\n (Result (c + d i' next + dcc i next) (left z) (Just r))\n where\n d i j = min d' (n-d') where d' = abs $ i-j\n dc i j = if i <= j then j-i else j+n-i -- clockwise distance\n dcc i j = dc j i\n\n\n restore = zipWith diff is $ tail is\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = concat $ reverse $ unfoldr next (Just r)\n where\n next Nothing = Nothing\n next (Just (Result _ l r)) = Just (reverse l, r)\n\n print c\n putStr $ unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) $ restore\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Function (on)\n\ndata Zipper a = Zipper { zleft :: Zipper a, zhead :: a, zright :: Zipper a }\n\nzipper :: [a] -> Zipper a\nzipper xs =\n let (first,last) = go last xs first in first\n where\n go :: Zipper a -> [a] -> Zipper a -> (Zipper a, Zipper a)\n go prev [] next = (next,prev)\n go prev (x:xs) next =\n let\n this = Zipper prev x rest\n (rest,last) = go this xs next\n in (this,last)\n\ndata Result = Result { rcount :: Int, rz :: [Int], rp :: Maybe Result }\n\ninstance Eq Result where\n (==) = (==) `on` rcount\ninstance Ord Result where\n (<=) = (<=) `on` rcount\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n gs = map (map snd) . groupBy ((==) `on` fst) . sort $ zip as [1..]\n\n r@(Result c _ _) = minimum . solve $ reverse gs\n where\n solve [] = [Result 0 [s] Nothing]\n solve (g:gs) = map f . take l . iterate zright $ zipper g\n where\n l = length g\n right = map zhead . take l . iterate zright\n left = map zhead . take l . iterate zleft\n rs = solve gs\n\n f z@(Zipper (Zipper _ prev _) i (Zipper _ next _)) =\n minimum $ map f' rs\n where\n f' r@(Result c (i':_) _) =\n min\n (Result (c + d i' prev + dc i prev) (right z) (Just r))\n (Result (c + d i' next + dcc i next) (left z) (Just r))\n where\n d i j = min d' (n-d') where d' = abs $ i-j\n dc i j = if i <= j then j-i else j+n-i -- clockwise distance\n dcc i j = dc j i\n\n restore = zipWith diff is (tail is)\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = concat . reverse $ unfoldr next (Just r)\n where\n next Nothing = Nothing\n next (Just (Result _ l r)) = Just (reverse l, r)\n\n print c\n putStr . unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) restore\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Array (listArray, elems, (!))\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n gs = map (map snd) . groupBy (\\a b -> fst a == fst b) . sort $ zip as [1..]\n m = length gs\n a = listArray (1, m) $ map (\\l -> listArray (1, length l) l) gs\n ls = listArray (1, m) $ map length gs\n\n d i j = min a (n-a) where a = abs $ i - j\n dc i j = if i <= j then j-i else j+n-i -- clockwise\n dcc i j = dc j i\n\n rs = listArray (1, m) $ map c' [1..m]\n where\n c' i = listArray (1, l) [f i j | j <- [1..l]]\n where\n l = ls!i\n\n f 1 j = min (d s p1 + dc p p1, False, j, 0) (d s p2 + dcc p p2, True, j, 0)\n where\n p = a!1!j\n\n l = ls!1\n\n j1 = (j-2+l) `mod` l + 1\n j2 = j `mod` l + 1\n\n p1 = a!1!j1\n p2 = a!1!j2\n\n f i j = minimum $ map f [1..ls!(i-1)]\n where\n f j' = min (c + c1, False, j, j') (c + c2, True, j, j')\n where\n (c, _, _, _) = rs!(i-1)!j'\n\n p' = a!(i-1)!j'\n\n c1 = d p' p1 + dc p p1\n c2 = d p' p2 + dcc p p2\n\n\n p = a!i!j\n\n l = ls!i\n\n j1 = (j-2+l) `mod` l + 1\n j2 = j `mod` l + 1\n\n p1 = a!i!j1\n p2 = a!i!j2\n\n r@(c, _, _, _) = minimum [rs!m!j | j <- [1..ls ! m]]\n\n restore = zipWith diff is $ tail is\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = (s:) . concat $ map list un\n un = reverse $ unfoldr next (m, r)\n next (0, _) = Nothing\n next (i, (_, dir, j, j')) = Just ((i, dir, j), (i-1, rs!(i-1)!j'))\n\n list (i, dir, j) =\n take l (if dir then drop j es else drop (l-j+1) $ reverse es)\n where\n es = es' ++ es' where es' = elems $ a!i\n l = ls!i\n\n print c\n putStr $ unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) $ restore\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Function (on)\n\ndata Zipper a = Zipper { zleft :: Zipper a, zhead :: a, zright :: Zipper a }\n\nzipper :: [a] -> Zipper a\nzipper xs =\n let (first,last) = go last xs first in first\n where\n go :: Zipper a -> [a] -> Zipper a -> (Zipper a, Zipper a)\n go prev [] next = (next,prev)\n go prev (x:xs) next =\n let\n this = Zipper prev x rest\n (rest,last) = go this xs next\n in (this,last)\n\ndata Result = Result { rcount :: Int, rz :: [Int], rp :: Maybe Result }\n\ninstance Eq Result where\n (==) = (==) `on` rcount\ninstance Ord Result where\n (<=) = (<=) `on` rcount\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n gs = map (map snd) . groupBy ((==) `on` fst) . sort $ zip as [1..]\n\n r@(Result c _ _) = minimum . solve $ reverse gs\n where\n solve [] = [Result 0 [s] Nothing]\n solve (g:gs) = map f . take l . iterate zright $ zipper g\n where\n l = length g\n right = map zhead . take l . iterate zright\n left = map zhead . take l . iterate zleft\n rs = solve gs\n\n f z@(Zipper (Zipper _ prev _) i (Zipper _ next _)) =\n minimum $ map f' rs\n where\n f' r@(Result c (i':_) _) =\n min\n (Result (c + d i' prev + dc i prev) (right z) (Just r))\n (Result (c + d i' next + dcc i next) (left z) (Just r))\n where\n d i j = min d' (n-d') where d' = abs $ i-j\n dc i j = if i <= j then j-i else j+n-i -- clockwise distance\n dcc i j = dc j i\n\n restore = zipWith diff is (tail is)\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = concat . reverse $ unfoldr next (Just r)\n where\n next Nothing = Nothing\n next (Just (Result _ l r)) = Just (reverse l, r)\n\n print c\n putStr . unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) restore\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sort, unfoldr)\nimport Data.Function (on)\n\ndata Zipper a = Zipper { zleft :: Zipper a, zhead :: a, zright :: Zipper a }\n\nzipper :: [a] -> Zipper a\nzipper xs =\n let (first,last) = go last xs first in first\n where\n go :: Zipper a -> [a] -> Zipper a -> (Zipper a, Zipper a)\n go prev [] next = (next,prev)\n go prev (x:xs) next =\n let\n this = Zipper prev x rest\n (rest,last) = go this xs next\n in (this,last)\n\ndata Result = Result { rcount :: Int, rz :: [Int], rp :: Maybe Result }\n\ninstance Eq Result where\n (==) = (==) `on` rcount\ninstance Ord Result where\n (<=) = (<=) `on` rcount\n\nmain = do\n [n, s] <- map read . words <$> getLine\n as <- map read . words <$> getLine :: IO [Int]\n\n let\n gs = map (map snd) . groupBy ((==) `on` fst) . sort $ zip as [1..]\n\n r@(Result c _ _) = minimum $ foldl next r0 gs\n where\n r0 = [Result 0 [s] Nothing]\n next rs g = map f . take l . iterate zright $ zipper g\n where\n l = length g\n right = map zhead . take l . iterate zright\n left = map zhead . take l . iterate zleft\n\n f z@(Zipper (Zipper _ prev _) i (Zipper _ next _)) =\n minimum $ map f' rs\n where\n f' r@(Result c (i':_) _) =\n min\n (Result (c + d i' prev + dc i prev) (right z) (Just r))\n (Result (c + d i' next + dcc i next) (left z) (Just r))\n where\n d i j = min d' (n-d') where d' = abs $ i-j\n dc i j = if i <= j then j-i else j+n-i -- clockwise distance\n dcc i j = dc j i\n\n restore = zipWith diff is (tail is)\n where\n diff a b\n | d1 < d2 = if a <= b then d1 else -d1\n | otherwise = if a <= b then -d2 else d2\n where\n d1 = abs (b-a)\n d2 = n - d1\n\n is = concat . reverse $ unfoldr next (Just r)\n where\n next Nothing = Nothing\n next (Just (Result _ l r)) = Just (reverse l, r)\n\n print c\n putStr . unlines $ map (\\a -> if a >= 0 then \"+\" ++ show a else show a) restore\n"}], "negative_code": [], "src_uid": "fdd60d5cde436c2f274fae89f4abf556"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad.State.Strict\nimport Data.Int\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nmain :: IO ()\nmain = do\n [n, k] <- (map readB8Int) <$> B8.words <$> B8.getLine\n (prices :: [Int64]) <- (map $ fromIntegral . readB8Int) <$> B8.words <$> B8.getLine\n let minPrice = foldr1 min prices\n let possible = all (\\price -> (price - minPrice) `mod` (fromIntegral k) == 0) prices\n if not possible\n then printf \"-1\\n\"\n else printf \"%lld\\n\" $ foldr1 (+) $ map (\\price -> (price - minPrice) `div` (fromIntegral k)) $ prices\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, reverse, dropWhile, unpack)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Char (isSpace)\nimport Data.Int (Int64)\n\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fst . M.fromJust . C.readInt\n\nrun k (x:xs) ans | x `mod` k /= 0 = []\n | otherwise = run k xs (x `div` k:ans)\nrun k [] ans = ans\n\ng [] = -1\ng x = sum $ map (\\i -> i - mx) x where mx = minimum x\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n (map readInt . C.words -> xs) <- B.getLine\n let mxs = minimum xs\n putStrLn $ show $ g (run k (map (\\i -> i - mxs) xs) [])\n"}, {"source_code": "import Control.Applicative( (<$>))\nmain = do\n [n_, k_] <- map read . words <$> getLine\n as_ <- map (read::String->Integer) . words <$> getLine\n let\n\tmin = minimum as_\n\n\tquot' a b =\n\t\t let\n\t\t\t(q,r) = a `quotRem` b\n\t\t in\n\t\t\tif r==0 then Just q else Nothing\n\n\tmaybeSum sm [] = Just sm\n\tmaybeSum sm (Nothing:_) = Nothing\n\tmaybeSum sm ((Just v):rem) = maybeSum (sm+v) rem\n\n case maybeSum 0 $ map ((`quot'` k_) . subtract min) as_ of\n\tJust v\t-> print v\n\tNothing -> print (-1)\n"}, {"source_code": "import Data.Functor\n\nposMod x y = mod ((mod x y) + y) y\n\nsol :: Integer -> [Integer] -> Integer\nsol k a = sum $ map (`div` k) $ map (+ (-m)) $ a where\n m = foldl1 min a\n\nmain = do\n [n, k] <- map read <$> words <$> getLine\n a <- map read <$> words <$> getLine\n putStrLn $ show $\n if and $ map (\\x -> x `posMod` k == head a `posMod` k) a then sol k a\n else -1\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, reverse, dropWhile, unpack)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Char (isSpace)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun k (x:xs) ans | x `mod` k /= 0 = []\n | otherwise = run k xs (x `div` k:ans)\nrun k [] ans = ans\n\ng :: [Int] -> Int\ng [] = -1\ng x = sum $ map (\\i -> i - (minimum x)) x\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n (map readInt . C.words -> xs) <- B.getLine\n putStrLn $ show $ g (run k (map (\\i -> i - (minimum xs)) xs) [])\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, reverse, dropWhile, unpack)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Char (isSpace)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun k (x:xs) ans | x `mod` k /= 0 = []\n | otherwise = run k xs (x `div` k:ans)\nrun k [] ans = ans\n\ng :: [Int] -> Int\ng [] = -1\ng x = sum $ map (\\i -> i - (minimum x)) x\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n (map readInt . C.words -> xs) <- B.getLine\n putStrLn $ show $ g (run k xs [])\n"}], "src_uid": "9e71b4117a24b906dbc16e6a6d110f50"} {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\n\nres x=solve x [0,0,0] where\n\tsolve [] v = maximum v\n\tsolve (x:xs) [v1,v2,v3]\n\t\t|x=='a' \t= solve xs [v1+1,v2,1+(maximum [v1,v2,v3])]\n\t\t|otherwise \t= solve xs [v1,1+ (max v1 v2),v3] \nmain=interact$show.res.head.lines\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = show `fmap` (solve . B.unpack) `fmap` pop\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve s = maximum [as!(i - 1) + bs!(j - 1) - bs!(i - 1) + as!n - as!(j - 1) | i <- [1..n + 1], j <- [i..n + 1]]\n where\n n = length s\n as = listArray (0, n) $ scanl (+) 0 $ map (fromEnum . (== 'a')) s :: UArray Int Int\n bs = listArray (0, n) $ scanl (+) 0 $ map (fromEnum . (== 'b')) s :: UArray Int Int"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\n--import qualified Data.HashTable.IO as B\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nhelp listA listB maxA = g listB listA\n where f = \\(b:xb) (a:xa) -> if null xb then b else max (b+maxA-a) $ f xb xa\n g = \\(b:xb) (a:xa) -> if null xa then a else max (a-b+ f xb xa) $ g xb xa\n\nmain :: IO ()\nmain = do\n str <- getLine\n let tableA = scanl (\\x y -> if y=='a' then x+1 else x) 0 str\n tableB = scanl (\\x y -> if y=='b' then x+1 else x) 0 str\n print $ help tableA tableB $ maximum tableA\n\n--\u0438\u043d\u0434\u0435\u043a\u0441\u0438\u0440\u0430\u043d\u0435 \u043d\u0430 \u043f\u0430\u043c\u0435\u0442\n-- $! \u0441\u0438\u043d\u0442\u0430\u043a\u0441\u0438\u0441\n--fmap\n{-main :: IO ()\nmain = do\n print 3\n where gg=H.fromList-}"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\nreadInts64 :: IO [Int64]\nreadInts64 = fmap (map (foldl' (\\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row \n\nhelp listA listB maxA = g listB listA\n where f = \\(b:xb) (a:xa) -> if null xb then b else max (b+maxA-a) $ f xb xa\n g = \\(b:xb) (a:xa) -> if null xa then a else max (a-b+(f xb xa)) $ g xb xa\n\nmain :: IO ()\nmain = do\n str <- getLine\n let tableA = scanl (\\x y -> if y=='a' then x+1 else x) 0 str\n tableB = scanl (\\x y -> if y=='b' then x+1 else x) 0 str\n m = maximum tableA\n print $ help tableA tableB m\n\n\n\n\n--kind\n--\u043f\u043e-\u0431\u0430\u0432\u043d\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0441 \u0433\u043b\u043e\u0431\u0430\u043b\u0435\u043d \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u044a\u0440\n--\u0438\u043d\u0434\u0435\u043a\u0441\u0438\u0440\u0430\u043d\u0435 \u043d\u0430 \u043f\u0430\u043c\u0435\u0442\n--dolna granica na slojnost"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\n--import qualified Data.HashTable.IO as B\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nf :: [Int] -> [Int] -> Int -> Int\nf [x] _ _= x\nf (b:xb) (a:xa) maxA= max (b+maxA-a) $ f xb xa maxA\n\ng :: [Int] -> [Int] -> Int -> Int\ng [x] _ _ = x\ng (a:xa) (b:xb) maxA = max (a+rec-b) $ g xa xb maxA\n where rec= f xb xa maxA\n\nmain :: IO ()\nmain = do\n str <- getLine\n let tableA = scanl (\\x y -> if y=='a' then x+1 else x) 0 str\n maxA = maximum tableA\n tableB = scanl (\\x y -> if y=='b' then x+1 else x) 0 str\n print $ g tableA tableB maxA\n\n--\u0438\u043d\u0434\u0435\u043a\u0441\u0438\u0440\u0430\u043d\u0435 \u043d\u0430 \u043f\u0430\u043c\u0435\u0442\n-- $! \u0441\u0438\u043d\u0442\u0430\u043a\u0441\u0438\u0441\n--fmap\n{-main :: IO ()\nmain = do\n print 3\n where gg=H.fromList-}"}, {"source_code": "import Data.List\nimport Data.Char\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\n\nf :: [Int] -> [Int] -> Int -> Int\nf [x] _ _= x\nf (b:xb) (a:xa) maxA= max (b+maxA-a) $ f xb xa maxA\n\nhelp :: [Int] -> [Int] -> Int -> Int\nhelp [x] _ _ = x\nhelp (a:xa) (b:xb) maxA = max (a-b + f xb xa maxA) $ help xa xb maxA\n\n\n{-help listA listB maxA = g listB listA\n where f = \\(b:xb) (a:xa) -> if null xb then b else max (b+maxA-a) $ f xb xa\n g = \\(b:xb) (a:xa) -> if null xa then a else max (a-b+(f xb xa)) $ g xb xa\n-}\n\nmain :: IO ()\nmain = do\n str <- getLine\n let tableA = scanl (\\x y -> if y=='a' then x+1 else x) 0 str\n tableB = scanl (\\x y -> if y=='b' then x+1 else x) 0 str\n m = maximum tableA\n print $ help tableA tableB m"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = show `fmap` (solve . B.unpack) `fmap` pop\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve s = maximum [as!(i - 1) + bs!j - bs!i + as!n - as!(j - 1) | i <- [1..n], j <- [i..n]]\n where\n n = length s\n as = listArray (0, n) $ scanl (+) 0 $ map (fromEnum . (== 'a')) s :: UArray Int Int\n bs = listArray (0, n) $ scanl (+) 0 $ map (fromEnum . (== 'b')) s :: UArray Int Int"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = show `fmap` (solve . B.unpack) `fmap` pop\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve s = maximum [as!(i - 1) + bs!(j - 1) - bs!(i - 1) + as!n - as!(j - 1) | i <- [1..n], j <- [i..n]]\n where\n n = length s\n as = listArray (0, n) $ scanl (+) 0 $ map (fromEnum . (== 'a')) s :: UArray Int Int\n bs = listArray (0, n) $ scanl (+) 0 $ map (fromEnum . (== 'b')) s :: UArray Int Int"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\n--import qualified Data.HashTable.IO as B\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\n\ncreateTable :: Char -> [(Char,Int)] -> [(Char,Int)]\ncreateTable element [] = [(element,1)]\ncreateTable element list@((x,y):xs)\n | x /= element = (element,1):list\n | otherwise = (x,y+1):xs\n\nforSplit :: Int -> Int -> [(Char,Int)] -> [([(Char,Int)],[(Char,Int)])]\nforSplit i n list\n | i>=n = []\n | otherwise = splitAt i list : forSplit (i+1) n list\n\ncompareA (x,x1) (y,y1)\n | x == y = compare x1 y1\n | x == 'a' = GT\n | otherwise = LT\n\ncompareB (x,x1) (y,y1)\n | x == y = compare x1 y1\n | x == 'a' = LT\n | otherwise = GT\n\nhelp :: [(Char,Int)]->((Char,Int),(Char,Int)) -> Int\nhelp _ ((x,_),(y,_))\n | x=='b' || y=='b' =0\nhelp list ((x,x1),(y,y1)) = x1+y1+(if l=='a' then 0 else r)\n where temp1 = dropWhile (/= (x,x1)) list\n temp = dropWhileEnd (/= (y,y1)) temp1\n (l,r) = maximumBy compareB temp\n\n\nmain :: IO ()\nmain = do\n str <- getLine\n let table = foldr createTable [] str\n maxA = checkA $ maximumBy compareA table\n maxB = checkB $ maximumBy compareB table\n print $ foldl max (maxA+maxB) . map (help table) . map (\\(x,y)->(func x,func y)) $ forSplit 1 (length table) table\n where checkA (a,b) = if a=='a' then b else 0\n checkB (a,b) = if a=='b' then b else 0\n func = maximumBy compareA\n\n--\u0438\u043d\u0434\u0435\u043a\u0441\u0438\u0440\u0430\u043d\u0435 \u043d\u0430 \u043f\u0430\u043c\u0435\u0442\n-- $! \u0441\u0438\u043d\u0442\u0430\u043a\u0441\u0438\u0441\n--fmap\n{-main :: IO ()\nmain = do\n print 3\n where gg=H.fromList-}"}], "src_uid": "c768f3e52e562ae1fd47502a60dbadfe"} {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nsplit c s = word : find c rest\n\twhere\n\t\t(word, rest) = break (== c) s\n\n\t\tfind c [] = []\n\t\tfind c s = split c $ tail s\n\nbetween a b c = a <= c && c <= b\n\nsolve s =\n\t\tif length ss >= 2 &&\n\t\t\t\t(between 1 8 $ length $ head ss) &&\n\t\t\t\t(between 1 3 $ length $ last ss) &&\n\t\t\t\tall (between 2 11 . length) (tail $ init ss)\n\t\t\tthen Just $ recombine ss'\n\t\t\telse Nothing\n\t\t\t\n\twhere\n\t\tss = split '.' s\n\t\tss' = head ss :\n\t\t\t(concatMap (\\s \u2192 let (a, b) = splitAt (min 3 $ length s - 1) s in [a, b]) $ tail $ init ss) ++\n\t\t\t[last ss]\n\t\t\t\t\n\t\trecombine [] = []\n\t\trecombine (x:y:xs) = (x ++ \".\" ++ y) : recombine xs\n\ntrim = f . f\n\twhere\n\t\tf = reverse . dropWhile isSpace\n\nmain = do\n\ts \u2190 trim <$> getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n", "positive_code": [{"source_code": "import Data.List\n\nbetween n x m = n <= x && x <= m\n\ncandivide ws = let h = head ws\n l = last ws\n ws' = init (tail ws)\n in between 1 (length h) 8 &&\n between 1 (length l) 3 &&\n all (\\x -> between 2 (length x) 11) ws'\n\ndivide cs | length cs <= 3 = [take (length cs - 1) cs, drop (length cs - 1) cs]\n | otherwise = [take 3 cs, drop 3 cs]\n\n\nconcat_words [] = []\nconcat_words (x:y:xs) = (x ++ \".\" ++ y) : concat_words xs\n\n\n\nfind_dot [] = []\nfind_dot ('.':cs) = split_dot cs\n\nsplit_dot cs = let (word, rest) = break (== '.') cs\n in word : find_dot rest\n\nmain = do s <- getLine\n let a = split_dot s\n h = head a\n l = last a\n ws = init (tail a)\n let divided = [h] ++ concatMap divide ws ++ [l]\n let concated = concat_words divided\n if length a < 2 then putStrLn \"NO\"\n else if candivide a then do putStrLn \"YES\"\n mapM_ putStrLn concated\n else putStrLn \"NO\""}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nsolve s =\n\t\tif not $ length ss >= 2 && (let l = B.length (head ss) in 1 <= l && l <= 8) &&\n\t\t\t\t(let l = B.length (last ss) in 1 <= l && l <= 3) &&\n\t\t\t\tall (\\l \u2192 2 <= B.length l && B.length l <= 11) (tail (init ss))\n\t\t\tthen Nothing\n\t\telse\n\t\t\tJust $ recombine ss'\n\t\t\t\n\twhere\n\t\tss = B.split '.' s\n\t\tss' = [head ss] ++\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = B.splitAt (min 3 (B.length s - 1)) s in [a, b]) (tail (init ss))) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = ((xs !! 0) `B.append` (B.pack \".\") `B.append` (xs !! 1)) : (recombine (tail (tail xs)))\n\nmain = do\n\ts \u2190 B.getLine\n\tlet r = solve $ fst $ B.breakEnd (not . isSpace) s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ B.putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nsplit c s = word : find c rest\n\twhere\n\t\t(word, rest) = break (== c) s\n\n\t\tfind c [] = []\n\t\tfind c s = split c $ tail s\n\nbetween a b c = a <= c && c <= b\n\nsolve s =\n\t\tif length ss >= 2 &&\n\t\t\t\t(between 1 8 $ length $ head ss) &&\n\t\t\t\t(between 1 3 $ length $ last ss) &&\n\t\t\t\tall (between 2 11 . length) (tail $ init ss)\n\t\t\tthen Just $ recombine ss'\n\t\t\telse Nothing\n\t\t\t\n\twhere\n\t\tss = split '.' s\n\t\tss' = head ss :\n\t\t\t(concatMap (\\s \u2192 let (a, b) = splitAt (min 3 $ length s - 1) s in [a, b]) $ tail $ init ss) ++\n\t\t\t[last ss]\n\t\t\t\t\n\t\trecombine [] = []\n\t\trecombine (x:y:xs) = (x ++ \".\" ++ y) : recombine xs\n\nmain = do\n\ts \u2190 getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nsplit x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nbetween a b c = a <= c && c <= b\n\nsolve s =\n\t\tif length ss >= 2 &&\n\t\t\t\t(between 1 8 $ length $ head ss) &&\n\t\t\t\t(between 1 3 $ length $ last ss) &&\n\t\t\t\tall (between 2 11 . length) (tail $ init ss)\n\t\t\tthen Just $ recombine ss'\n\t\t\telse Nothing\n\t\t\t\n\twhere\n\t\tss = split '.' s\n\t\tss' = head ss :\n\t\t\t(concatMap (\\s \u2192 let (a, b) = splitAt (min 3 $ length s - 1) s in [a, b]) $ tail $ init ss) ++\n\t\t\t[last ss]\n\t\t\t\t\n\t\trecombine [] = []\n\t\trecombine (x:y:xs) = (x ++ \".\" ++ y) : recombine xs\n\nmain = do\n\ts \u2190 getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nsplit x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : split'' xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\n\t\tsplit'' [] = []\n\t\tsplit'' xs = split' $ tail xs\n\nbetween a b c = a <= c && c <= b\n\nsolve s =\n\t\tif length ss >= 2 &&\n\t\t\t\t(between 1 8 $ length $ head ss) &&\n\t\t\t\t(between 1 3 $ length $ last ss) &&\n\t\t\t\tall (between 2 11 . length) (tail $ init ss)\n\t\t\tthen Just $ recombine ss'\n\t\t\telse Nothing\n\t\t\t\n\twhere\n\t\tss = split '.' s\n\t\tss' = head ss :\n\t\t\t(concatMap (\\s \u2192 let (a, b) = splitAt (min 3 $ length s - 1) s in [a, b]) $ tail $ init ss) ++\n\t\t\t[last ss]\n\t\t\t\t\n\t\trecombine [] = []\n\t\trecombine (x:y:xs) = (x ++ \".\" ++ y) : recombine xs\n\nmain = do\n\ts \u2190 getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nsolve s =\n\t\tif not $ length ss >= 2 &&\n\t\t\t\t(let l = B.length (head ss) in 1 <= l && l <= 8) &&\n\t\t\t\t(let l = B.length (last ss) in 1 <= l && l <= 3) &&\n\t\t\t\tall (\\l \u2192 2 <= B.length l && B.length l <= 11) (tail $ init ss)\n\t\t\tthen Nothing\n\t\telse\n\t\t\tJust $ recombine ss'\n\t\t\t\n\twhere\n\t\tss = B.split '.' s\n\t\tss' = head ss :\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = B.splitAt (min 3 $ B.length s - 1) s in [a, b]) (tail $ init ss)) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = (xs !! 0 `B.append` B.pack \".\" `B.append` (xs !! 1)) : (recombine $ tail $ tail xs)\n\ntrim = f . f\n\twhere\n\t\tf = B.reverse . B.dropWhile isSpace\n\nmain = do\n\ts \u2190 trim <$> B.getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ B.putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nsplit x xs = split' xs\n\twhere\n\t\tsplit' xs = xs' : if null xs'' then [] else split' $ tail xs''\n\t\t\twhere\n\t\t\t\t(xs', xs'') = break (== x) xs\n\nbetween a b c = a <= c && c <= b\n\nsolve s =\n\t\tif length ss >= 2 &&\n\t\t\t\t(between 1 8 $ length $ head ss) &&\n\t\t\t\t(between 1 3 $ length $ last ss) &&\n\t\t\t\tall (between 2 11 . length) (tail $ init ss)\n\t\t\tthen Just $ join $ [head ss] ++ (concatMap splitJoined $ tail $ init ss) ++ [last ss]\n\t\t\telse Nothing\n\t\t\t\n\twhere\n\t\tss = split '.' s\n\n\t\tsplitJoined s = [a, b]\n\t\t\twhere\n\t\t\t\t(a, b) = splitAt (min 3 $ length s - 1) s\n\t\t\t\t\n\t\tjoin [] = []\n\t\tjoin (x:y:xs) = (x ++ \".\" ++ y) : join xs\n\nmain = do\n\ts \u2190 getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "\nmaxLengthName = 8\nmaxLengthExt = 3\n\nsolve :: String -> Maybe [String]\nsolve \"\" = Nothing\nsolve line = res >>= return . reverse . (map (\\(name, ext) -> name ++ \".\" ++ ext))\n where\n res = f (Just []) \"\" line\n f :: Maybe [(String, String)] -> String -> String -> Maybe [(String, String)]\n f (Just []) \"\" \"\" = Nothing\n f (Just []) \"\" ('.' : _) = Nothing\n f (Just []) acc \"\" = Nothing\n f (Just []) acc ('.' : s) = f (Just [(acc, \"\")]) \"\" s\n f (Just []) acc (c : s)\n | length acc' > maxLengthName = Nothing\n | otherwise = f (Just []) acc' s\n where\n acc' = acc ++ [c]\n f (Just ((n, _):fs)) \"\" \"\" = Nothing\n f (Just ((n, _):fs)) \"\" ('.' : _) = Nothing\n f (Just ((n, _):fs)) \"\" (c : s) = f (Just ((n, \"\"):fs)) [c] s\n f (Just ((n, _):fs)) acc \"\"\n | length acc > maxLengthExt = Nothing\n | otherwise = Just ((n, acc):fs)\n f (Just ((n, _):fs)) acc ('.' : s)\n | length acc < 2 = Nothing\n | otherwise = f (Just ((n', \"\") : (n, e') : fs)) \"\" s\n where\n (e', n') = if length acc <= maxLengthExt\n then splitAt 1 acc\n else splitAt 3 acc\n f (Just ((n, _):fs)) acc (c : s)\n | length acc' > maxLengthName + maxLengthExt = Nothing\n | otherwise = f (Just ((n, \"\"):fs)) acc' s\n where\n acc' = acc ++ [c]\n\nprintAns :: Maybe [String] -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just fs) = putStrLn \"YES\" >> mapM_ putStrLn fs\n\nmain :: IO ()\nmain = getLine >>= printAns . solve \n"}, {"source_code": "import Data.List\n\nmain=interact$solve.parse\n\nsolve :: [String] -> String\nsolve (s:ss)\n | isValid (s:ss) = \"YES\\n\" ++ intercalate \".\" ( (s: (map part$init ss)) ++ [last ss])\n | otherwise = \"NO\\n\"\nsolve _ = \"NO\\n\"\n\npart :: String -> String\npart (a:b:c:d:e)=[a,b,c]++\"\\n\"++d:e\npart [a,b,c]=[a,b]++\"\\n\"++[c]\npart [a,b]=[a]++\"\\n\"++[b]\n\nparse :: String -> [String]\nparse = lines.map f\n where f '.'='\\n'\n f c = c\n\nisValid :: [String] -> Bool\nisValid [] = False\nisValid (s:ss) = isValidName s && isValid' ss\nisValid' [] = False\nisValid' [s] = isValidExt s\nisValid' (s:ss) = isValidNameExt s && isValid' ss\n\nisValidName s = let l = length s\n in 1<=l && l<=8\nisValidExt s = let l = length s\n in 1<=l && l<=3\nisValidNameExt s = let l = length s\n in 2<=l && l<=11"}], "negative_code": [{"source_code": "import Data.List\n\nbetween n x m = n <= x && x <= m\n\ncandivide ws = let h = head ws\n l = last ws\n ws' = init (tail ws)\n in between 1 (length h) 8 &&\n between 1 (length l) 3 &&\n all (\\x -> between 2 x 11) ws'\n\ndivide cs | length cs <= 3 = [take (length cs - 1) cs, drop (length cs - 1) cs]\n | otherwise = [take 3 cs, drop 3 cs]\n\nconcat_words [] = []\nconcat_words (x:y:xs) = (x ++ \".\" ++ y) : concat_words xs\n\nmain = do s <- getLine\n let a = words [ if c == '.' then ' ' else c | c <- s]\n h = head a\n l = last a\n ws = init (tail a)\n let divided = [h] ++ concatMap divide ws ++ [l]\n let concated = concat_words divided\n mapM_ putStrLn concated"}, {"source_code": "import Data.List\n\nbetween n x m = n <= x && x <= m\n\ncandivide ws = let h = head ws\n l = last ws\n ws' = init (tail ws)\n in between 1 (length h) 8 &&\n between 1 (length l) 3 &&\n all (\\x -> between 2 (length x) 11) ws'\n\ndivide cs | length cs <= 3 = [take (length cs - 1) cs, drop (length cs - 1) cs]\n | otherwise = [take 3 cs, drop 3 cs]\n\nconcat_words [] = []\nconcat_words (x:y:xs) = (x ++ \".\" ++ y) : concat_words xs\n\nmain = do s <- getLine\n let a = words [ if c == '.' then ' ' else c | c <- s]\n h = head a\n l = last a\n ws = init (tail a)\n let divided = [h] ++ concatMap divide ws ++ [l]\n let concated = concat_words divided\n if candivide a then do putStrLn \"YES\"\n mapM_ putStrLn concated\n else putStrLn \"NO\""}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nsolve s =\n\t\tif not $ B.length (head ss) <= 8 && B.length (last ss) <= 3 &&\n\t\t\t\tall (\\l \u2192 2 <= B.length l && B.length l <= 11) (tail (init ss))\n\t\t\tthen Nothing\n\t\telse\n\t\t\tJust $ recombine ss'\n\t\t\t\n\twhere\n\t\tss = B.split '.' s\n\t\tss' = [head ss] ++\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = B.splitAt ((min 3 (B.length s - 1)) - 1) s in [a, b]) (tail (init ss))) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = ((xs !! 0) `B.append` (B.pack \".\") `B.append` (xs !! 1)) : (recombine (tail (tail xs)))\n\nmain = do\n\ts \u2190 B.getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ B.putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nsplit c = unfoldr $ \\l -> \n if null l\n \tthen Nothing\n\telse Just $ second (drop 1) $ break (== c) l\n\nsolve s =\n\t\tif length ss >= 2 &&\n\t\t\t\t(let l = length $ head ss in 1 <= l && l <= 8) &&\n\t\t\t\t(let l = length $ last ss in 1 <= l && l <= 3) &&\n\t\t\t\tall (\\s \u2192 let l = length s in 2 <= l && l <= 11) (tail $ init ss)\n\t\t\tthen Just $ recombine ss'\n\t\t\telse Nothing\n\t\t\t\n\twhere\n\t\tss = split '.' s\n\t\tss' = head ss :\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = splitAt (min 3 $ length s - 1) s in [a, b]) $ tail $ init ss) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = (xs !! 0 ++ \".\" ++ (xs !! 1)) : (recombine $ tail $ tail xs)\n\ntrim = f . f\n\twhere\n\t\tf = reverse . dropWhile isSpace\n\nmain = do\n\ts \u2190 trim <$> getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nsolve s =\n\t\tif not $ B.length (head ss) <= 8 && B.length (last ss) <= 3 &&\n\t\t\t\tall (\\l \u2192 2 <= B.length l && B.length l <= 11) (tail (init ss))\n\t\t\tthen Nothing\n\t\telse\n\t\t\tJust $ recombine ss'\n\t\t\t\n\twhere\n\t\tss = B.split '.' s\n\t\tss' = [head ss] ++\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = B.splitAt ((min 3 (B.length s - 1)) - 1) s in [a, b]) (tail (init ss))) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = ((xs !! 0) `B.append` (B.pack \".\") `B.append` (xs !! 1)) : (recombine (tail (tail xs)))\n\nmain = do\n\ts \u2190 B.getLine\n\tlet r = solve $ fst $ B.breakEnd (not . isSpace) s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ B.putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nsolve s =\n\t\tif not $ B.length (head ss) <= 8 && B.length (last ss) <= 3 &&\n\t\t\t\tall (\\l \u2192 2 <= B.length l && B.length l <= 11) (tail (init ss))\n\t\t\tthen Nothing\n\t\telse\n\t\t\tJust $ recombine ss'\n\t\t\t\n\twhere\n\t\tss = B.split '.' s\n\t\tss' = [head ss] ++\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = B.splitAt (min 8 (B.length s - 1)) s in [a, b]) (tail (init ss))) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = ((xs !! 0) `B.append` (B.pack \".\") `B.append` (xs !! 1)) : (recombine (tail (tail xs)))\n\nmain = do\n\ts \u2190 B.getLine\n\tlet r = solve s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ B.putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Char\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nsolve s =\n\t\tif not $ length ss >= 2 && (let l = B.length (head ss) in 1 <= l && l <= 8) &&\n\t\t\t\t(let l = B.length (last ss) in 1 <= l && l <= 3) &&\n\t\t\t\tall (\\l \u2192 2 <= B.length l && B.length l <= 11) (tail (init ss))\n\t\t\tthen Nothing\n\t\telse\n\t\t\tJust $ recombine ss'\n\t\t\t\n\twhere\n\t\tss = B.split '.' s\n\t\tss' = [head ss] ++\n\t\t\t(concat $ map (\\s \u2192 let (a, b) = B.splitAt ((min 3 (B.length s - 1)) - 1) s in [a, b]) (tail (init ss))) ++\n\t\t\t[last ss]\n\n\t\trecombine [] = []\n\t\trecombine xs = ((xs !! 0) `B.append` (B.pack \".\") `B.append` (xs !! 1)) : (recombine (tail (tail xs)))\n\nmain = do\n\ts \u2190 B.getLine\n\tlet r = solve $ fst $ B.breakEnd (not . isSpace) s\n\tif isJust r\n\t\tthen do\n\t\t\tputStrLn \"YES\"\n\t\t\tmapM_ B.putStrLn $ fromJust r\n\t\telse\n\t\t\tputStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "import Data.List\n\nmain=interact$solve.parse\n\nsolve :: [String] -> String\nsolve (s:ss)\n | isValid (s:ss) = \"YES\\n\" ++ intercalate \".\" ( (s: (map part$init ss)) ++ [last ss])\n | otherwise = \"NO\\n\"\nsolve _ = \"NO\\n\"\n\npart :: String -> String\npart (a:b:c:d:e)=[a,b,c]++\"\\n\"++d:e\npart (a:b:c:d)=[a,b]++\"\\n\"++c:d\npart (a:b:c)=[a]++\"\\n\"++b:c\n\nparse :: String -> [String]\nparse = words.map f\n where f '.'=' '\n f c = c\n\nisValid :: [String] -> Bool\nisValid (s:ss) = isValidName s && isValid' ss\nisValid _ = False\nisValid' [] = False\nisValid' [s] = isValidExt s\nisValid' (s:ss) = isValidNameExt s && isValid' ss\n\nisValidName s = let l = length s\n in 1<=l && l<=8\nisValidExt s = let l = length s\n in 1<=l && l<=3\nisValidNameExt s = let l = length s\n in 2<=l && l<=11"}], "src_uid": "9c30697e71102ae10c55c14d9c1db006"} {"source_code": "import List\n\nmain = getLine >> getLine >>= \n \\s -> putStrLn $ show $ head $ [1..] \\\\ (sort . map read . words) s\n", "positive_code": [{"source_code": "import List\n\nnext c [] = c\nnext c (x:xs) | c < x = c\nnext c (x:xs) | c == x = next (c + 1) xs\n\nmain = do\n n <- readInt\n s <- getLine\n putStrLn $ show $ next 1 (sort $ list $ words $ s)\n \n where\n list [] = []\n list (c:cs) = (read c :: Int) : list cs \n \n readInt :: IO Int\n readInt = readLn \n"}, {"source_code": "import List\n\nmain = do\n n <- (readLn :: IO Int)\n s <- getLine\n putStrLn $ show $ head $ [1..] \\\\\n (sort $ map (read :: String -> Int) $ words $ s)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Array\n \n \n\n\nmain= do\n\t n<- read <$> getLine ::IO Int\n\t s<- map read. words <$> getLine ::IO [Int]\n\t let a = accumArray (||) (False) (1,n) $ zip (filter (<=n) s) (repeat True)\n\t print $ 1 + ( length ( takeWhile id ( elems a)))\n \n\t\n"}, {"source_code": "import Control.Monad(liftM)\nimport Data.List(sort)\n\nmain = do getLine\n nums <- liftM (zip [1..] . sort . map read . words) getLine\n let nums' = dropWhile (uncurry (==)) nums\n ans = if null nums' \n then\n length nums + 1\n else\n fst (head nums')\n print ans"}, {"source_code": "import List\nmain = getLine >> fmap (map read . words) getLine >>= putStr . show . head . ([1 ..] \\\\)\n"}, {"source_code": "import Data.List\nmain = do getLine >> fmap (map read . words) getLine >>= putStr . show . head . ([1 ..] \\\\)\n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n n <- getLine\n l <- getLine\n let a = sort $ readInt l\n putStrLn . show $ count a 1\n\nreadInt :: String -> [Int]\nreadInt l = map read (words l)\n\ncount :: [Int] -> Int -> Int\ncount [] y = y\ncount (x:xs) y = if x == y then count xs (y + 1) else y\n"}, {"source_code": "import List\n\nsolve :: [Int] -> Int\nsolve xs = solve' 1 (sort xs)\n where\n solve' n [] = n\n solve' n (m:xs)\n | n == m = solve' (n+1) xs\n | otherwise = n\n\n\nmain :: IO ()\nmain = getLine >> getLine >>=\n return . map read . words >>= print . solve\n \n"}, {"source_code": "solve :: [Int] -> Int\nsolve xs = head . filter (\\x -> not $ x `elem` xs) $ [1..]\nmain = getLine >> fmap (map read . words) getLine >>= print . solve\n"}, {"source_code": "main :: IO()\nmain = do\n _ <- getLine\n lines <- getLine\n print $ gao $ map read $ words lines\n\ngao :: [Int] -> Int\ngao a = if null lst then 1 else succ $ last lst\n where lst = takeWhile (`elem` a) [1..]\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n _ <- getLine\n lines <- getLine\n print $ gao $ map read $ words lines\n\ngao :: [Int] -> Int\ngao a = head $ [1..] \\\\ a\n\n{-gao :: [Int] -> Int-}\n{-gao a = if null lst then 1 else succ $ last lst-}\n {-where lst = takeWhile (`elem` a) [1..]-}\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- zip [1 ..] . sort . take n . map read . words <$> getLine\n print . maybe (n + 1) (+ 1) $ findIndex (uncurry (/=)) xs\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Array\n \n \n\n\nmain= do\n\t n<- read <$> getLine ::IO Int\n\t s<- map read. words <$> getLine ::IO [Int]\n\t let a = accumArray (||) (False) (1,n) $ zip (takeWhile (<=n) s) (repeat True)\n\t print $ 1 + ( length ( takeWhile id ( elems a)))\n \n\t\n"}], "src_uid": "5e449867d9fcecc84333b81eac9b5d92"} {"source_code": "\nanalyze :: [[Int]] -> Bool\nanalyze [] = True\nanalyze (x:y:xs) = px >= cx && pVar >= 0 && cVar >= 0 && cVar <= pVar && analyze (y:xs)\n where\n (px, cx, py, cy) = (head x, x !! 1, head y, y !! 1)\n (pVar, cVar) = (py - px, cy - cx)\nanalyze (x:xs) = head x >= (x !! 1) && analyze xs\n\nsolve :: IO ()\nsolve = do\n n <- getLine >>= \\v -> return (read v :: Int)\n let inps = getLine >>= \\v -> return [read n :: Int | n <- (words v)]\n inps' <- sequence (take n $ repeat inps)\n let out = if analyze inps' then \"YES\" else \"NO\"\n putStrLn out\n\n\nmain :: IO ()\nmain = do\n t <- getLine >>= \\v -> return (read v :: Int)\n sequence $ take t (repeat solve)\n return ()\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess1 _ _ [] = True\nprocess1 a b ([c,d]:e) | cc = False\n\t\t | c-a < d-b = False\t\n\t | otherwise = process1 c d e\n\nprocess v = process1 0 0 v\n\n\nonecase = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tv<- map (map read) <$> map words <$> replicateM n getLine :: IO [[Int]]\n\t\tputStrLn $ if process v then \"YES\" else \"NO\" \n\t\n\nmain::IO ()\nmain=do\n \tt<- read <$> getLine ::IO Int\n\treplicateM_ t onecase\n\n"}], "negative_code": [{"source_code": "\nanalyze :: [[Int]] -> Bool\nanalyze [] = True\nanalyze (x:y:xs) = head x >= (x !! 1) && head x <= head y && x !! 1 <= y !! 1 && analyze (y:xs)\nanalyze (x:xs) = head x >= (x !! 1) && analyze xs\n\nsolve :: IO ()\nsolve = do\n n <- getLine >>= \\v -> return (read v :: Int)\n let inps = getLine >>= \\v -> return [read n :: Int | n <- (words v)]\n inps' <- sequence (take n $ repeat inps)\n let out = if analyze inps' then \"YES\" else \"NO\"\n putStrLn out\n\n\nmain :: IO ()\nmain = do\n t <- getLine >>= \\v -> return (read v :: Int)\n sequence $ take t (repeat solve)\n return ()\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess1 _ _ [] = True\nprocess1 a b ([c,d]:e) | cc = False\n\t | otherwise = process1 c d e\n\nprocess v = process1 0 0 v\n\n\nonecase = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tv<- map (map read) <$> map words <$> replicateM n getLine :: IO [[Int]]\n\t\tputStrLn $ if process v then \"YES\" else \"NO\" \n\t\n\nmain::IO ()\nmain=do\n \tt<- read <$> getLine ::IO Int\n\treplicateM_ t onecase\n\n"}], "src_uid": "714834defd0390659f6ed5bc3024f613"} {"source_code": "import Control.Monad\n\ntype Ints = (Integer, Integer)\ntype Prices = (Integer, Integer)\n\ndata Test = Test (Ints, Ints) deriving (Show)\n\ngetData :: Int -> IO [Test]\ngetData t = replicateM t readTest\n\nreadTest :: IO Test\nreadTest = do\n first <- getLine\n second <- getLine\n let [x, y] = map read (words first)\n let [a, b] = map read (words second)\n return (Test ((x, y), (a, b)))\n\ngetAnswer :: [Test] -> [Integer]\ngetAnswer [] = []\ngetAnswer (first:rest) = [quantify first] ++ getAnswer rest\n\nquantify :: Test -> Integer\nquantify (Test ((x, y), (a, b))) = minimum [less*b + (greater - less)*a, (x + y)*a]\n where less = min x y\n greater = max x y\n\ntoIntList :: [Integer] -> [Integer]\ntoIntList list = list\n\nmain :: IO ()\nmain = do\n t <- getLine\n tests <- getData $ read t\n mapM_ print (getAnswer tests)", "positive_code": [{"source_code": "import Control.Monad\n\nmain = readLn >>= flip replicateM_ test\n\ntest = do\n (x:y:_) <- map (abs . read) . words <$> getLine\n (a:b:_) <- map read . words <$> getLine\n print $ min (a * (x + y)) (b * min x y + a * (max x y - min x y))"}, {"source_code": "import qualified Data.List as L\n\ndist_to_zero a b\n | a > b = dist_to_zero b a\n | a <= 0 && 0 <= b = 0\n | 0 <= a = a\n | b <= 0 = b\n\nsolve :: [Integer] -> Integer\nsolve [x,y,a,b] = d2 * (min b (2*a)) + d1 * a\n where d1 = abs (x-y)\n d2 = dist_to_zero x y\nsolve x = undefined\n \nlines_to_pairs [] = []\nlines_to_pairs (x:y:zz) = (unwords [x,y]):(lines_to_pairs zz)\n\nmain = interact $ unlines . map show . map solve . map ( map read . words ) . lines_to_pairs . tail . lines\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [x,y] <- (map read.words) <$> getLine\n [a,b] <- (map read.words) <$> getLine\n print $ if 2*a <= b then a*(x+y) else (min x y)*b + (abs (x - y))*a\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n tt <- read <$> getLine\n replicateM_ tt $ do\n [x, y] <- (map read . words) <$> getLine\n [a, b] <- (map read . words) <$> getLine\n let f t = a * abs (t + x) + a * abs (t + y) + b * abs t\n putStrLn $ show $ minimum [f (-x), f (-y), f 0 :: Integer]\n"}, {"source_code": "solve :: [Integer] -> Integer \nsolve (0:0:_) = 0\nsolve (0:y:a:b:_) = a*y\nsolve (x:0:a:b:_) = a*x\nsolve (x:y:a:b:_)\n | b > 2*a = x*a + y*a \n | b <= 2*a = (min x y)*b + (abs (x - y))*a \n\n\ntest :: (Int) -> IO()\ntest 0 = return()\ntest x = do\n l1 <- getLine\n l2 <- getLine\n let t = l1 ++ \" \" ++ l2 \n let arr = map (\\a -> read a :: Integer ) $ words t \n let ans = solve arr\n let out = show ans \n putStrLn out \n test (x - 1)\n\n\n\nmain = do\n t <- getLine\n let x = read t :: Int\n\n test x\n\n"}, {"source_code": "\nsolve1 :: Integer -> Integer -> Integer -> Integer -> Integer\nsolve1 x y a b\n | b > 2*a = a * (x +y)\n | otherwise = b * mn + a * (mx - mn)\n where\n mn = min x y\n mx = max x y\n\nsolveTestCases :: Integer -> IO ()\nsolveTestCases 0 = return ()\nsolveTestCases n = do\n xy <- getLine\n ab <- getLine\n let\n (x:y:_) = map read $ words xy\n (a:b:_) = map read $ words ab\n print $ solve1 x y a b\n solveTestCases (n-1)\n\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n solveTestCases (read t)"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [x, y] <- getIntList\n [a, b] <- getIntList\n print $ f x y a b\n\nf :: Integer -> Integer -> Integer -> Integer -> Integer\nf x y a b = minimum [(abs x + abs y) * a\n ,abs (x - y) * a + min (abs x * b) (abs y * b)]"}, {"source_code": "import Data.List ( unfoldr )\n\n-- https://stackoverflow.com/a/12882583/61394\nchunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n\nf :: Integer -> Integer -> Integer -> Integer -> Integer\n\n-- Rearrange so x' has the smaller absolute value.\nf x y a b | x == 0 && y == 0 = 0\n | x == 0 = a * abs y\n | x < 0 && y < 0 = f (-x) (-y) a b\n | abs x > abs y = f y x a b\n | x > 0 && y > 0 = x * min b (2 * a) + f 0 (y - x) a b\n | otherwise = a * (abs x + abs y)\n\nmain =\n interact\n $ unlines\n . map (show . \\(x : y : a : b : _) -> f x y a b)\n . chunks 4\n . tail\n . map read\n . words\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\n\ndist_to_zero a b\n | a > b = dist_to_zero b a\n | a <= 0 && 0 <= b = 0\n | 0 <= a = a\n | b <= 0 = b\n\nsolve :: [Int] -> Int\nsolve [x,y,a,b] = d2 * b + d1 * a\n where d1 = abs (x-y)\n d2 = dist_to_zero x y\nsolve x = undefined\n \nlines_to_pairs [] = []\nlines_to_pairs (x:y:zz) = (unwords [x,y]):(lines_to_pairs zz)\n\nmain = interact $ unlines . map show . map solve . map ( map read . words ) . lines_to_pairs . tail . lines\n"}, {"source_code": "import qualified Data.List as L\n\ndist_to_zero a b\n | a > b = dist_to_zero b a\n | a <= 0 && 0 <= b = 0\n | 0 <= a = a\n | b <= 0 = b\n\nsolve :: [Int] -> Int\nsolve [x,y,a,b] = d2 * (min b (2*a)) + d1 * a\n where d1 = abs (x-y)\n d2 = dist_to_zero x y\nsolve x = undefined\n \nlines_to_pairs [] = []\nlines_to_pairs (x:y:zz) = (unwords [x,y]):(lines_to_pairs zz)\n\nmain = interact $ unlines . map show . map solve . map ( map read . words ) . lines_to_pairs . tail . lines\n"}, {"source_code": "solve :: [Int] -> Int \nsolve (0:0:_) = 0\nsolve (0:y:a:b:_) = a*y\nsolve (x:0:a:b:_) = a*x\nsolve (x:y:a:b:_)\n | b > 2*a = x*a + y*a \n | b <= 2*a = (min x y)*b + (abs (x - y))*a \n\n\ntest :: (Int) -> IO()\ntest 0 = return()\ntest x = do\n l1 <- getLine\n l2 <- getLine\n let t = l1 ++ \" \" ++ l2 \n let arr = map (\\a -> read a :: Int ) $ words t \n let ans = solve arr\n let out = show ans \n putStrLn out \n test (x - 1)\n\n\n\nmain = do\n t <- getLine\n let x = read t :: Int\n\n test x\n\n"}, {"source_code": "\nsolve1 :: Int -> Int -> Int -> Int -> Int\nsolve1 x y a b\n | x * y <= 0 = a* (abs x+ abs y)\n | b > 2*a = a* (abs x + abs y)\n | otherwise = a* abs (abs x - abs y) + b* min (abs x) (abs y)\n\nsolveTestCases :: Int -> IO ()\nsolveTestCases 0 = return ()\nsolveTestCases n = do\n xy <- getLine\n ab <- getLine\n let\n (x:y:_) = map read $ words xy\n (a:b:_) = map read $ words ab\n print $ solve1 x y a b\n solveTestCases (n-1)\n\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n solveTestCases (read t)"}, {"source_code": "\nsolve1 :: Int -> Int -> Int -> Int -> Int\nsolve1 x y a b\n | b > 2*a = a * (x +y)\n | otherwise = b * mn + a * (mx - mn)\n where\n mn = min x y\n mx = max x y\n\nsolveTestCases :: Int -> IO ()\nsolveTestCases 0 = return ()\nsolveTestCases n = do\n xy <- getLine\n ab <- getLine\n let\n (x:y:_) = map read $ words xy\n (a:b:_) = map read $ words ab\n print $ solve1 x y a b\n solveTestCases (n-1)\n\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n solveTestCases (read t)"}, {"source_code": "\nsolve1 :: Int -> Int -> Int -> Int -> Int\nsolve1 x y a b\n | b > 2*a = a* (x + y)\n | otherwise = a* abs (x - y) + b* min x y\n\nsolveTestCases :: Int -> IO ()\nsolveTestCases 0 = return ()\nsolveTestCases n = do\n xy <- getLine\n ab <- getLine\n let\n (x:y:_) = map read $ words xy\n (a:b:_) = map read $ words ab\n print $ solve1 x y a b\n solveTestCases (n-1)\n\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n solveTestCases (read t)"}], "src_uid": "edf394051c6b35f593abd4c34b091eae"} {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.List (sort)\n\nreadI = fst . fromJust . C.readInteger\n\nmain = C.interact $ solve . map (map readI . C.words) . C.lines\n\nsolve [_, xs, ys] = if ans then \"YES\" else \"NO\"\n where\n capa = sum $ take 2 $ reverse $ sort ys\n ans = sum xs <= capa\n ", "positive_code": [{"source_code": "import Data.Int\nimport Data.List\n\nsolve :: Int64 -> Int64 -> String\nsolve a b\n | a <= b = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n n <- getLine\n a <- getLine\n b <- getLine\n let\n a' = sum $ map read $ words a\n b' = sum $ take 2 $ reverse $ sort $ map read $ words b\n ans = solve a' b'\n putStrLn ans"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Data.Bool\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n as <- replicateM n p64\n bs <- replicateM n p64\n return $ bool \"NO\" \"YES\" $ solve as bs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n p64 = fmap fromIntegral poi\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve as bs = (sum as :: Int64) <= sum (take 2 $ sortBy (flip compare) bs)"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readInteger :: String -> Integer\n readInteger s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n yesNo :: Bool -> String\n yesNo True = \"YES\"\n yesNo False = \"NO\"\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . map readInteger . words\n ys <- getLine >>= return . map readInteger . words\n let twoMaxCans = sum $ take 2 $ reverse $ sort ys\n allCans = sum xs\n putStrLn $ yesNo $ allCans <= twoMaxCans\n"}], "negative_code": [{"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nimport Data.List (sort)\n\nmain = interact $ solve . map (map read . words) . lines\n\nsolve [_, xs, ys] = if ans then \"YES\" else \"NO\"\n where\n capa = sum $ take 2 $ reverse $ sort xs\n ans = sum xs <= capa\n "}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.List (sort)\n\nreadI = fst . fromJust . C.readInt\n\nmain = C.interact $ solve . map (map readI . C.words) . C.lines\n\nsolve [_, xs, ys] = if ans then \"YES\" else \"NO\"\n where\n capa = sum $ take 2 $ reverse $ sort ys\n ans = sum xs <= capa\n "}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.List (sort)\n\nreadI = fst . fromJust . C.readInt\n\nmain = C.interact $ solve . map (map readI . C.words) . C.lines\n\nsolve [_, xs, ys] = if ans then \"YES\" else \"NO\"\n where\n capa = sum $ take 2 $ reverse $ sort xs\n ans = sum xs <= capa\n "}, {"source_code": "import Data.List\n\nsolve :: Int -> Int -> String\nsolve a' b'\n | a' <= b' = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n n <- getLine\n a <- getLine\n b <- getLine\n putStrLn (solve (sum $ map read $ words a) (sum $ take 2 $ reverse $ sort $ map read $ words b))"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readInteger :: String -> Integer\n readInteger s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n yesNo :: Bool -> String\n yesNo True = \"YES\"\n yesNo False = \"NO\"\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . map readInteger . words\n ys <- getLine >>= return . map readInteger . words\n let twoMaxCans = sum $ take 2 $ reverse $ sort ys\n allCans = sum xs\n putStrLn $ yesNo $ allCans < twoMaxCans\n"}], "src_uid": "88390110e4955c521867864a6f3042a0"} {"source_code": "import Data.List\nimport Control.Monad\n\nbogosort :: (Ord a) => [a] -> [a]\nbogosort = reverse . sort\n\nmain = do\n i <- getLine\n let t = read i :: Int\n forM_ [1..t] $ \\_ -> do\n j <- getLine\n ss <- getLine\n let xx = map (\\x -> read x :: Int) $ words ss\n let ret = bogosort xx\n putStrLn (intercalate \" \" (map show ret))\n", "positive_code": [{"source_code": "import Control.Monad\n\n\nreverseqs :: [Int] -> [Int]\nreverseqs [] = []\nreverseqs (x:xs) = let greater = reverseqs (filter (>= x) xs)\n lesser = reverseqs (filter (< x) xs)\n in greater ++ [x] ++ lesser \n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do \n t <- getLine \n let cases = (read t :: Int)\n results <- forM [1..cases] (\\t -> do \n integers <- readInts\n array <- readInts\n let final = foldl (\\acc x -> acc ++ (show x) ++ \" \") \"\" $ reverseqs array \n return final\n )\n\n mapM putStrLn results\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.STRef\n\n(|>) x f = f x\n\nmain = do\n line <- getLine\n forM_ [1..(read line)] $ \\t -> do\n line <- getLine\n line <- getLine\n list <- words line |> map (read :: String -> Int) |> sort |> reverse |> pure\n forM_ list $ \\x -> do\n putStr (show x)\n putStr \" \"\n putStrLn \"\"\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nbogosort :: (Ord a) => [a] -> [a]\nbogosort = reverse . sort\n\nmain = do\n i <- getLine\n let t = read i :: Int\n forM_ [1..t] $ \\_ -> do\n j <- getLine\n ss <- getLine\n let xx = words ss\n let ret = bogosort xx\n putStrLn (intercalate \" \" ret)\n"}], "src_uid": "1d89df4153d70087d212b711852eba5f"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List (foldl', unfoldr) -- '\nimport qualified Data.ByteString.Lazy as L\nimport Data.ByteString.Lazy.Char8 (readInt)\n\ntype Trip = (Int, Int, Int)\n\nstep :: Trip -> Int -> Trip\nstep (!ix, !prev, !best) v\n | ix < v = (ix, minBound, best)\n | otherwise = (ix, nv, nbv) where\n nv = v + max (-ix) prev\n nbv = max nv best\n\nsolve1 :: Int -> [Int] -> Trip\nsolve1 maxv = foldl' step (maxv, minBound, minBound) -- '\n\nsolve :: [Int] -> Int\nsolve li = maximum [bv | (_, _, bv) <- map (`solve1` li) [-30 .. 30]]\n\nparse :: L.ByteString -> [Int]\nparse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline) where\n newline = 0x0a\n space = 0x20\n parseLine = unfoldr (readInt . L.dropWhile (== space))\n\nmain :: IO ()\nmain = (putStr . (++ \"\\n\") . show . solve . parse) =<< L.getContents\n", "positive_code": [{"source_code": "import Data.List (unfoldr, foldl') -- '\nimport qualified Data.ByteString.Lazy as L\nimport Data.ByteString.Lazy.Char8 (readInt)\n\nstep :: Int -> Int -> Int -> Int\nstep maxv prev v\n | maxv < v = minBound\n | otherwise = v + max (-maxv) prev\n\nmymax :: [Int] -> Int\nmymax = foldl' max minBound -- '\n\nsolve :: [Int] -> Int\nsolve li = mymax $ concatMap (\\maxv -> scanl (step maxv) minBound li) [-30..30]\n\nparse :: L.ByteString -> [Int]\nparse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline) where\n newline = 0x0a\n space = 0x20\n parseLine = unfoldr (readInt . L.dropWhile (== space))\n\nmain :: IO ()\nmain = (putStr . (++ \"\\n\") . show . solve . parse) =<< L.getContents\n"}, {"source_code": "-- Verdict: TLE.\n-- GHC probably isn't reuse the input array or preallocating for step.\n-- Probably fixable in Haskell, but not as easy as I'd like it to be.\n-- The lack of language-level support for unique refs and\n-- pure functions that consume their args hurts at a time like this.\n\n{-# LANGUAGE BangPatterns #-}\n\n--import Data.Array (Array, listArray, elems)\nimport Data.List (foldl', unfoldr) -- '\nimport qualified Data.ByteString.Lazy as L\nimport Data.ByteString.Lazy.Char8 (readInt)\n\ntype Array x = []\nlistArray :: (x,x) -> [y] -> Array x y\nlistArray _ = id\nelems :: Array x y -> [y]\nelems = id\n\ntype Arr = Array Int (Int, Int, Int)\n\nstartArr :: Arr\nstartArr = listArray (-30, 30) [(i, minBound, minBound) | i <- [-30 .. 30]]\n\nstep :: Arr -> Int -> Arr\nstep arr v = fmap step1 arr where\n step1 (!ix, !prev, !best)\n | ix < v = (ix, minBound, best)\n | otherwise = seq nv $ seq nbv (ix, nv, nbv) where\n nv = v + max (-ix) prev\n nbv = max nv best\n\nsolve :: [Int] -> Int\nsolve li = maximum [bv | (_, _, bv) <- elems (foldl' step startArr li)]\n\nparse :: L.ByteString -> [Int]\nparse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline) where\n newline = 0x0a\n space = 0x20\n parseLine = unfoldr (readInt . L.dropWhile (== space))\n\nmain :: IO ()\nmain = (putStr . (++ \"\\n\") . show . solve . parse) =<< L.getContents\n\n\n"}, {"source_code": "import Data.List (unfoldr, foldl') -- '\nimport qualified Data.ByteString.Lazy as L\nimport Data.ByteString.Lazy.Char8 (readInt)\n\nstep :: Int -> Int -> Int -> Int\nstep maxv prev v\n | maxv < v = minBound\n | otherwise = v + max (-maxv) prev\n\nmymax :: [Int] -> Int\nmymax = foldl' max minBound -- '\n\nsolve :: [Int] -> Int\nsolve li = mymax $ concatMap (\\maxv -> scanl (step maxv) minBound li) [-30..30]\n\nparse :: L.ByteString -> [Int]\nparse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline) where\n newline = 0x0a\n space = 0x20\n parseLine = unfoldr (readInt . L.dropWhile (== space))\n\nmain :: IO ()\nmain = (putStrLn . show . solve . parse) =<< L.getContents\n"}], "negative_code": [{"source_code": "import Data.Array (Array, listArray, assocs)\nimport Data.List (foldl') -- '\n\ntype Arr = Array Int (Int, Int)\n\nstartArr :: Arr\nstartArr = listArray (-30, 30) (replicate 61 (minBound, minBound))\n\nstep :: Arr -> Int -> Arr\nstep arr v = listArray (-30, 30) [step1 i v e | (i, e) <- assocs arr] where\n step1 ix va (prev, best)\n | ix < va = (minBound, best)\n | otherwise = let nv = va + max 0 prev in (nv, max nv best)\n\nsolve :: [Int] -> Int\nsolve li = maximum [bv - i | (i, (_, bv)) <- assocs (foldl' step startArr li)]\n\nparse :: String -> [Int]\nparse = map read . tail . words\n\nmain :: IO ()\nmain = interact ((++ \"\\n\") . show . solve . parse)\n\n\n"}], "src_uid": "b2d77fa3e0c2dad9c316249a0feeb4c6"} {"source_code": "import System.IO\n\ntoint s = (read s) :: Int\n\ndoit2 l [] s e ss = doit2 l l s e ss\ndoit2 l (t:ts) s e ss =\n let m = div (s+e) 2 in\n let a = t * (head ss) in\n ((show m) ++ \"\\n\") ++ (if a == 0 then \"\" else (if a < 0 then (doit2 l ts s m (tail ss)) else doit2 l ts (m+1) e (tail ss)))\n\n\ndoit m n l s =\n if n == 0 then\n let ll = reverse l in\n doit2 ll ll 1 (m+1) s\n else\n let a = head s in\n \"1\\n\" ++ (if a == 0 then \"\" else (doit m (n-1) (a:l) (tail s)))\n\n\nsolve::String->String\nsolve ss =\n let (m:n:s) = map toint $ words ss in\n doit m n [] s\n\nmain = do\n hSetBuffering stdout LineBuffering\n interact solve\n", "positive_code": [{"source_code": "import System.IO\nimport Control.Monad\n\nmakeTry :: Int -> IO Int\nmakeTry x = do\n print x\n hFlush stdout\n readLn\n\ngetCorrectness :: Int -> IO [Bool]\ngetCorrectness n = do\n x <- makeTry 1\n if x == 0 then\n return []\n else replicateM (n - 1) (makeTry 1) >>= \\y -> return . map (== 1) $ x : y\n\ndoRest :: Int -> Int -> [Bool] -> IO ()\ndoRest lb ub (x:xs) = do\n let mb = (lb + ub) `div` 2\n ans <- makeTry mb\n let ans' = if x then ans else -ans\n case ans' of\n 0 -> return ()\n 1 -> doRest (mb + 1) ub xs\n -1 -> doRest lb mb xs\n\nmain = do\n [m, n] <- fmap (map read . words) getLine\n l <- getCorrectness n\n if l == [] then return () else doRest 1 (m + 1) $ cycle l\n"}], "negative_code": [{"source_code": "import System.IO\n\ntoint s = (read s) :: Int\n\ndoit2 l [] s e ss = doit2 l l s e ss\ndoit2 l (t:ts) s e ss =\n let m = div (s+e) 2 in\n let a = t * (head ss) in\n ((show m) ++ \"\\n\") ++ (if a == 0 then \"\" else (if a < 0 then (doit2 l ts s m (tail ss)) else doit2 l ts (m+1) e (tail ss)))\n\n\ndoit m n l s =\n if n == 0 then\n let ll = reverse l in\n doit2 ll ll 1 (m+1) s\n else\n let a = head s in\n \"1\\n\" ++ (if a == 0 then \"\" else \"1\\n\"++(doit m (n-1) (a:l) (tail s)))\n\n\nsolve::String->String\nsolve ss =\n let (m:n:s) = map toint $ words ss in\n doit m n [] s\n\nmain = do\n hSetBuffering stdout LineBuffering\n interact solve\n"}], "src_uid": "f06dff83491772f8879e45b90b61dc88"} {"source_code": "import Control.Monad\r\nreadDoubles = fmap (map read.words) getLine :: IO [Double]\r\n\r\nprintResult [n,k] = print $ ceiling $ (if k >= n then k else k*y)/n\r\n where y = fromInteger $ ceiling (n/k) :: Double\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n a <- replicateM t readDoubles\r\n mapM_ printResult a", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nreadDoubles = fmap (map read.words) getLine :: IO [Double]\r\n\r\nprintResult [n,k] = print $ ceiling (r/n)\r\n where r = if k >= n then k else k * (let y = fromInteger $ ceiling (n/k) :: Double in y)\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n a <- replicateM t readDoubles\r\n mapM_ printResult a"}, {"source_code": "module Main where\n \nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as BS\n--import Debug.Trace\n \n--debug = flip trace\nreadx = fromInteger . fst . fromJust. BS.readInteger <$> BS.getLine\nreadxs = map (fromInteger . fst . fromJust. BS.readInteger) . BS.words <$> BS.getLine\n \nprintList :: Show a => [a] -> IO ()\nprintList [] = return ()\nprintList [a] = print a\nprintList (a:xs) = putStr (show a) >> putChar ' ' >> printList xs\n \nsolve :: Int64 -> Int64 -> Int64\nsolve n k = (totSum+n-1) `div` n\n where totSum = k * ((n+k-1) `div` k)\n\nmain :: IO()\nmain = do\n t <- readx\n replicateM_ t $ do\n (n:k:_) <- readxs\n print $ solve n k"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [n, k] <- map read . words <$> getLine :: IO [Integer]\n print $ if n <= k then (k - 1) `div` n + 1 else if n `mod` k == 0 then 1 else 2\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nprintS = do \r\n [n,k]<-readInts \r\n let cf = (div n k) + if (mod n k > 0) then 1 else 0\r\n r = (div (cf*k) n) + if (mod (cf*k) n > 0) then 1 else 0\r\n print r\r\n\r\nmain = do\r\n t<-readLn::IO Int \r\n replicateM_ t printS"}, {"source_code": "main = getContents >>= traverse print . solves . map read . tail . words\r\n\r\nsolves [] = []\r\nsolves (n:k:xs) = f n (k * f k n) : solves xs\r\n where f n k = (n + k - 1) `div` n"}, {"source_code": "solve :: [Int] -> Int\r\nsolve [n, k] = m `div` n + ceil\r\n where rem = n `mod` k\r\n m = if rem == 0 then n else n + (k - rem)\r\n ceil = if m `mod` n == 0 then 0 else 1\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . solve . toArr) . tail . lines)\r\n where toArr s = map (read :: String -> Int) $ words s\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n C.putStrLn $ C.pack $ show $ if n > k then (if n `mod` k == 0 then 1 else 2) else (k + n - 1) `div` n\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int64 -> Int64 -> Int64\r\nsolve n k\r\n | n >= k && n `mod` k == 0 = 1\r\n | n >= k && n `mod` k /= 0 = 2\r\n | n < k = (k + n - 1) `div` n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, k] <- B8.getLine <&> map readIntegerB8 . B8.words\r\n let answer = solve (fromInteger n) (fromInteger k)\r\n printf \"%lld\\n\" answer\r\n\r\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n let\n k' = k * div (n+k-1) k\n (q', r) = divMod k' n\n ans = q' + if r > 0 then 1 else 0\n lift . P.putStrLn . P.pack $ {- unwords $ map -} show ans\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n let\n (q, r) = divMod k n\n ans = q + if r > 0 || q == 0 then 1 else 0\n lift . P.putStrLn . P.pack $ {- unwords $ map -} show ans\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n let\n (q, r) = divMod k n\n q' = max q 1\n --ans = concat $ zipWith replicate [r, n-r] [q+1, q]\n ans = q' + if r > 0 then 1 else 0\n lift . P.putStrLn . P.pack $ {- unwords $ map -} show ans\n"}, {"source_code": "module Main where\n \nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as BS\n--import Debug.Trace\n \n--debug = flip trace\nreadx = fromInteger . fst . fromJust. BS.readInteger <$> BS.getLine\nreadxs = map (fromInteger . fst . fromJust. BS.readInteger) . BS.words <$> BS.getLine\n \nprintList :: Show a => [a] -> IO ()\nprintList [] = return ()\nprintList [a] = print a\nprintList (a:xs) = putStr (show a) >> putChar ' ' >> printList xs\n \nsolve :: Int -> Int -> Int\nsolve n k = (totSum+n-1) `div` n\n where totSum = k * ((n+k-1) `div` k)\n\nmain :: IO()\nmain = do\n t <- readx\n replicateM_ t $ do\n (n:k:_) <- readxs\n print $ solve n k\n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [n, k] <- map read . words <$> getLine :: IO [Integer]\n print $ if n > k then 2 else (k - 1) `div` n + 1\n"}], "src_uid": "a28b84c9d1a54e322ab2d54bd5ab45c8"} {"source_code": "import Control.Monad\nimport Data.List\n \nmain = do\n q <- readLn\n replicateM (q :: Int) $ do\n getLine\n a <- map read . words <$> getLine\n print $ sum $ scanl1 (\\x -> \\y -> max 0 $ min (x-1) y) $ reverse . sort . map length . group . sort $ (a :: [Int])\n", "positive_code": [{"source_code": "import Data.List\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain = interact $ solve . (map ((map readInt) . words)) . tail . lines\n\nsolve :: [[Integer]] -> String\nsolve [] = \"\"\nsolve (_:x:xs) = solveInstance x ++ solve xs\n\nsolveInstance :: [Integer] -> String\nsolveInstance xs =\n let l = reverse $ sort $ map genericLength $ groupBy (==) $ sort xs in\n-- (++\"\\n\") $ show l\n (++\"\\n\") . show $ takeGreedily l (head l) 0\n\ntakeGreedily :: [Integer] -> Integer -> Integer -> Integer\ntakeGreedily [] _ _ = 0\ntakeGreedily _ 0 _ = 0\ntakeGreedily (x:xs) current carry\n | x >= current = current + takeGreedily xs (current - 1) carry\n | carry >= 1 = current + takeGreedily (x:xs) (current - 1) (carry - 1)\n | otherwise = takeGreedily (x:xs) (current - 1) carry\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map as M\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\nmain = do\n [q] <- input\n replicateM_ q $ do\n getLine\n a <- input :: IO [Integer]\n let f = reverse $ sort $ map length $ group $ sort a\n print $ sum $ scanl1 (\\b x -> max 0 $ min (b-1) x) f\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map as M\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\nmain = do\n [q] <- input\n replicateM_ q $ do\n getLine\n a <- input :: IO [Int]\n let f = reverse $ sort $ map length $ group $ sort a\n print $ sum $ scanl1 (\\b x -> max 0 $ min (b-1) x) f\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map as M\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadInts :: IO [Int]\nreadInts = map read <$> words <$> getLine\n\nmain = do\n q <- readInt\n replicateM_ q $ do\n getLine\n a <- readInts\n let f = reverse $ sort $ map length $ group $ sort a\n print $ sum $ scanl1 (\\b x -> max 0 $ min (b-1) x) f\n"}], "negative_code": [], "src_uid": "a00d831da539c69d571d9720fd94eee1"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad.State.Strict\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n \nmain :: IO ()\nmain = do\n [n, m] <- (map readB8Int) <$> B8.words <$> B8.getLine\n (squares :: [Int]) <- (map readB8Int) <$> B8.words <$> B8.getLine\n let sizes :: MapS.Map Int Int = foldr' (MapS.alter (fmap (+1) . flip mplus (Just 0))) MapS.empty squares\n let minSize = (foldr1 min) . map (\\i -> fromMaybe 0 . MapS.lookup i $ sizes) $ [1..n]\n printf \"%d\\n\" minSize\n\n", "positive_code": [{"source_code": "main = do\n [n, m] <- getLine >>= return. map read. words :: IO [Int]\n a <- getLine >>= return. map read. words :: IO [Int]\n print.minimum. map (\\x -> length.filter (==x) $ a) $ [1..n] \n"}, {"source_code": "import Data.Array\n\ngetInts = (map read . words) `fmap` getLine :: IO [Int]\n\nmain = do\n [n,m] <- getInts\n columns <- getInts\n let heights = accumArray (+) 0 (1,n) [(i,1) | i <- columns]\n print $ (minimum . elems) heights"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Control.Applicative\nimport Data.List\ngetList = fmap ((map read).words) getLine\nget c = sort $ map length (group (sort c))\nsolve n c \n | length (get c) < n = show 0\n | otherwise = show (head (get c))\nmain = do\n [n,_] <- getList\n c <- getList\n putStrLn $ solve n c\n\n\n \n \n"}, {"source_code": "import Data.List\n\nmain = getContents >>= print . solve . map read . words\n\nsolve (x:_:xs) = subtract 1 $ minimum $ map length $ group $ sort $ [1 .. x] ++ xs\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\ngetList = fmap ((map read).words) getLine\nget c = reverse $ map length (group (sort c))\nsolve n c \n | length (get c) < n = show 0\n | otherwise = show (head (get c))\nmain = do\n [n,_] <- getList\n c <- getList\n putStrLn $ solve n c\n\n\n \n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad.State.Strict\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n \nmain :: IO ()\nmain = do\n [n, m] <- (map readB8Int) <$> B8.words <$> B8.getLine\n (squares :: [Int]) <- (map readB8Int) <$> B8.words <$> B8.getLine\n let sizes :: MapS.Map Int Int = foldr' (MapS.alter (fmap (+1) . mplus (Just 1))) MapS.empty squares\n let minSize = (foldr1 min) . map (\\i -> fromMaybe 0 . MapS.lookup i $ sizes) $ [1..n]\n printf \"%d\\n\" minSize\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad.State.Strict\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n \nmain :: IO ()\nmain = do\n [n, m] <- (map readB8Int) <$> B8.words <$> B8.getLine\n (squares :: [Int]) <- (map readB8Int) <$> B8.words <$> B8.getLine\n let sizes :: MapS.Map Int Int = foldr' (MapS.alter (fmap (+1) . flip mplus (Just 1))) MapS.empty squares\n let minSize = (foldr1 min) . map (\\i -> fromMaybe 0 . MapS.lookup i $ sizes) $ [1..n]\n printf \"%d\\n\" minSize\n\n"}, {"source_code": "main = do\n [n, m] <- getLine >>= return. map read. words :: IO [Int]\n a <- getLine >>= return. map read. words :: IO [Int]\n print.maximum. map (\\x -> length.filter (==x) $ a) $ [1..n] \n"}], "src_uid": "c249103153c5006e9b37bf15a51fe261"} {"source_code": "module Main where\n\nimport Data.STRef\nimport Data.Array\nimport Data.Array.ST\nimport Data.Array.MArray\nimport Control.Monad\nimport Data.List\n\nmain = do\n inputNMK <- getLine\n let [n, m, k] = map read $ words inputNMK\n\n teeth <- replicateM n $ do\n inputRC <- getLine\n let [r, c] = map read $ words inputRC\n\n return (r, c)\n\n let rowViability = runSTArray $ do\n rowViability <- newArray (1, m) 2147483647\n forM_ teeth $ \\(r, c) -> do\n old_c <- readArray rowViability r\n if c < old_c\n then writeArray rowViability r c\n else return ()\n return rowViability\n\n putStrLn $ show $ min k $ sum $ elems rowViability\n", "positive_code": [{"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:xs) = func' (words a) xs\n where \n func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)\n ++\"\\n\"++ (func (drop a' xs))\n where a' = toInt a\n b' = toInt b\n c' = asInteger c\n makeTooth xs = (((toInt.head) xs),\n ((asInteger.last) xs))\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Integer->String\ntoString = show\n\nsolve::Int->Int->Integer->[(Int,Integer)]->Integer\nsolve a b c = min c.sum.map (minimum.map snd).groupBy groupHelper.sortBy sorter\n where\n sorter::(Int,Integer)->(Int,Integer)->Ordering\n sorter a b = compare (fst a) (fst b)\n groupHelper::(Int,Integer)->(Int,Integer)->Bool\n groupHelper a b = (fst a) == (fst b)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\nimport Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : m : k : _ <- readData\n v <- fmap (sum . map (snd . head) . groupBy ((==) `on` fst) . sort)\n . T.for [1 .. n] $ \\i -> do\n r : c : _ <- readData\n return (r, c)\n print $ min v k\n\n\n\n"}, {"source_code": "main = interact (ans)\nans theInput = show $ min (sum $ viability teeth) k where\n\ttheLines = lines theInput\n\t[n,m,k] = map (read::String->Int) (words $ head theLines)\n\tteeth = map (map (read::String->Int)) (map words (take n (tail theLines)))\n\tviability [] = take m (repeat 1000001)\n\tviability (x:xs) = v1 ++ [v2] ++ v3 where\n\t\tr = x !! 0\n\t\tv = viability xs\n\t\tv1 = take (r-1) v\n\t\tv2 = min (v !! (r-1)) (x !! 1)\n\t\tv3 = drop r v\n\n"}, {"source_code": "import Array\n\nbigNum = 1000000\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n assocs' = foldl (+) 0 elements\n where\n elements = elems (accumArray min bigNum (1, n) assocs') \n \nreadAssoc :: Int -> IO (Int, Int)\nreadAssoc _ = do\n line <- getLine\n let [a, b] = map read $ words line\n return (a, b)\n\nmain = do\n line <- getLine\n let [n, m, k] = map read $ words line\n assocs' <- sequence (map readAssoc [1..n])\n print $ min (solve m assocs') k\n "}, {"source_code": "\nmodule Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Function\n\nmain = do\n [n, m, k] <- map read . words <$> getLine\n let readline :: IO (Integer, Integer)\n readline = do\n [row, rv] <- map read . words <$> getLine\n return (row, rv)\n lst <- replicateM n readline\n let lst' = nubBy ((==) `on` fst) . sort $ lst\n total = sum' . map snd $ lst'\n sum' = foldl1' (+)\n print (min total (fromIntegral k))"}], "negative_code": [{"source_code": "import Array\n\nbigNum = 10000\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n assocs' = foldl (+) 0 elements\n where\n elements = elems (accumArray min bigNum (1, n) assocs') \n \nreadAssoc :: Int -> IO (Int, Int)\nreadAssoc _ = do\n line <- getLine\n let [a, b] = map read $ words line\n return (a, b)\n\nmain = do\n line <- getLine\n let [n, m, k] = map read $ words line\n assocs' <- sequence (map readAssoc [1..n])\n print $ min (solve m assocs') k\n "}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:xs) = func' (words a) xs\n where \n func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)\n ++ (func (drop a' xs))\n where a' = toInt a\n b' = toInt b\n c' = asInteger c\n makeTooth xs = (((toInt.head) xs),\n ((asInteger.last) xs))\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Integer->String\ntoString = show\n\nsolve::Int->Int->Integer->[(Int,Integer)]->Integer\nsolve a b c = min (toInteger c).sum.map (maximum.map snd).groupBy groupHelper.sortBy sorter\n where\n sorter::(Int,Integer)->(Int,Integer)->Ordering\n sorter a b = compare (fst a) (fst b)\n groupHelper::(Int,Integer)->(Int,Integer)->Bool\n groupHelper a b = (fst a) == (fst b)\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:xs) = func' (words a) xs\n where \n func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)\n ++\"\\n\"++ (func (drop a' xs))\n where a' = toInt a\n b' = toInt b\n c' = asInteger c\n makeTooth xs = (((toInt.head) xs),\n ((asInteger.last) xs))\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Integer->String\ntoString = show\n\nsolve::Int->Int->Integer->[(Int,Integer)]->Integer\nsolve a b c = min c.sum.map (maximum.map snd).groupBy groupHelper.sortBy sorter\n where\n sorter::(Int,Integer)->(Int,Integer)->Ordering\n sorter a b = compare (fst a) (fst b)\n groupHelper::(Int,Integer)->(Int,Integer)->Bool\n groupHelper a b = (fst a) == (fst b)\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact (func.lines)\n\nfunc::[String]->String\nfunc (a:xs) = func' (words a) xs\n where \n func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)\n ++ (func (drop a' xs))\n where a' = toInt a\n b' = toInt b\n c' = asInteger c\n makeTooth xs = (((toInt.head) xs),\n ((asInteger.last) xs))\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Integer->String\ntoString = show\n\nsolve::Int->Int->Integer->[(Int,Integer)]->Integer\nsolve a b c = min (toInteger a).maximum.map (maximum.map snd).groupBy groupHelper.sortBy sorter\n where\n sorter::(Int,Integer)->(Int,Integer)->Ordering\n sorter a b = compare (fst a) (fst b)\n groupHelper::(Int,Integer)->(Int,Integer)->Bool\n groupHelper a b = (fst a) == (fst b)\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:xs) = func' (words a) xs\n where \n func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)\n ++ (func (drop a' xs))\n where a' = toInt a\n b' = toInt b\n c' = asInteger c\n makeTooth xs = (((toInt.head) xs),\n ((asInteger.last) xs))\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Integer->String\ntoString = show\n\nsolve::Int->Int->Integer->[(Int,Integer)]->Integer\nsolve a b c = min c.sum.map (maximum.map snd).groupBy groupHelper.sortBy sorter\n where\n sorter::(Int,Integer)->(Int,Integer)->Ordering\n sorter a b = compare (fst a) (fst b)\n groupHelper::(Int,Integer)->(Int,Integer)->Bool\n groupHelper a b = (fst a) == (fst b)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n cs <- T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return (head from, Map.singleton (head to) (read v :: Int))\n let mp = Map.fromListWith (Map.unionWith min) cs\n bnds = (('a', 'a'), ('z', 'z'))\n table <- newArray bnds maxBound :: IO (IOArray (Char, Char) Int)\n F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \\idx -> do\n writeArray table idx 0\n let fill from cost now = F.for_ (Map.lookup now mp) $ \\mp' -> do\n F.for_ (Map.toList mp') $ \\(to, new) -> do\n old <- readArray table (now, to)\n when (old == maxBound || new < old) $ do\n writeArray table (now, to) new\n let new' = cost + new\n old' <- readArray table (from, to)\n when (old' == maxBound || new' < old') $ do\n writeArray table (from, to) new'\n fill from new' to\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n let check c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- T.for ['a' .. 'z'] $ \\to -> do\n v1 <- readArray table (c1, to)\n v2 <- readArray table (c2, to)\n case () of\n _ | c1 == to -> return (to, v2)\n | c2 == to -> return (to, v1)\n | otherwise -> return (to, min v1 v2)\n when (null xs) $ exit\n let (c, cost) = minimumBy (comparing snd) xs\n if cost == maxBound\n then exit\n else do\n return (c, cost)\n (answer, cost) <- unzip <$> zipWithM check s1 s2\n-- getAssocs table >>= printf \"%s\\n\" . show\n print $ sum cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}], "src_uid": "65eb0f3ab35c4d95c1cbd39fc7a4227b"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List hiding (insert)\nimport qualified Data.Map as M\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\ndata Heap a = Fork !a [Heap a] | Empty\n\nsingleton :: a -> Heap a\nsingleton x = Fork x []\n\nisEmpty :: Heap a -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ninsert :: Ord a => a -> Heap a -> Heap a\ninsert x h = merge (Fork x []) h\n\nmaxElem :: Heap a -> Maybe a\nmaxElem (Fork x _) = Just x\nmaxElem _ = Nothing\n\ndeleteMax :: Ord a => Heap a -> Maybe (Heap a)\ndeleteMax (Fork _ hs) = Just $ mergePairs hs\ndeleteMax _ = Nothing\n\ndeleteFindMax :: Ord a => Heap a -> Maybe (a, Heap a)\ndeleteFindMax (Fork x hs) = Just (x, mergePairs hs)\ndeleteFindMax _ = Nothing\n\nmerge :: Ord a => Heap a -> Heap a -> Heap a\nmerge hx@(Fork x _) hy@(Fork y _)\n | x >= y = join hx hy\n | otherwise = join hy hx\n where\n join (Fork x hs) h = Fork x (h:hs)\nmerge Empty hy = hy\nmerge hx _ = hx\n\nmergePairs :: Ord a => [Heap a] -> Heap a\nmergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)\nmergePairs [x] = x\nmergePairs [] = Empty\n\n\nmain :: IO ()\nmain = do\n [n,x] <- map read.words <$> getLine\n thms <- parse.map readInt.B.words <$> B.getContents\n print $ solve n x thms\n\nparse :: [Int] -> [(Bool, Int, Int)]\nparse (1:h:m:rest) = (True,h,m) : parse rest\nparse (0:h:m:rest) = (False,h,m) : parse rest\nparse _ = []\n\nsolve :: Int -> Int -> [(Bool, Int, Int)] -> Int\nsolve n x thms = max (goF x 0 Empty Empty fs cs) (goC x 0 Empty Empty fs cs)\n where\n fs = sort[(h,m)|(True,h,m)<-thms]\n cs = sort[(h,m)|(False,h,m)<-thms]\n goF !x !cnt !canUseF !canUseC fs cs\n | Just (m, canUseF'')<-deleteFindMax canUseF' = goC (x+m) (cnt+1) canUseF'' canUseC fs' cs\n | otherwise = cnt\n where\n (ms, fs') = span ((<=x).fst) fs\n !canUseF' = foldl' (flip insert) canUseF $ map snd ms\n goC !x !cnt !canUseF !canUseC fs cs\n | Just (m, canUseC'')<-deleteFindMax canUseC'= goF (x+m) (cnt+1) canUseF canUseC'' fs cs'\n | otherwise = cnt\n where\n (ms, cs') = span ((<=x).fst) cs\n !canUseC' = foldl' (flip insert) canUseC $ map snd ms\n", "positive_code": [{"source_code": "import Data.Array.IO\nimport Data.IORef\nimport Control.Monad\nimport Data.Tuple\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Lazy as B\n\nparse :: B.ByteString -> [Int]\nparse s = do\n\tq <- B.splitWith (\\x-> x == 13 || x == 10 || x == 32) s\n\tif B.length q == 0 then\n\t\t[]\n\telse\n\t\treturn $ foldl' (\\a b-> a * 10 + (fromIntegral b) - (ord '0')) 0 (B.unpack q)\n\nreadc :: [Int] -> [(Int, Int, Int)]\nreadc [] = []\nreadc (t:h:m:xx) = (t,m,h):(readc xx)\n\nspl :: [(Int, Int, Int)] -> ([(Int, Int)], [(Int, Int)])\nspl [] = ([], [])\nspl ((t, m, h):xs) = let (q0, q1) = spl xs in\n\tif t == 0 then ((m, h):q0, q1)\n\telse (q0, (m, h):q1)\n\ngetmaxnum :: [(Int, Int)] -> [(Int, Int)] -> Int -> IO Int\ngetmaxnum [] _ _ = return 0\ngetmaxnum xs ns x = do\n\tlet aval = filter (\\(_,b) -> b <= x) xs\n\t--putStrLn $ show aval\n\tif aval == [] then return 0\n\telse do\n\t\tlet (mm, mh) = maximum aval\n\t\tr <- getmaxnum ns (delete (mm, mh) xs) (x + mm)\n\t\treturn $ r + 1\n\nmain :: IO ()\nmain = do\n\tbbbb <- B.getContents\n\tlet n:x:nn = parse bbbb\n\tlet cs = readc nn\n\tlet (kars, leds) = spl cs\n\t--putStrLn $ show $ (kars, leds)\n\tr1 <- getmaxnum kars leds x\n\tr2 <- getmaxnum leds kars x\n\tlet res = max r1 r2\n\tputStrLn $ show res\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,x] <- map read.words <$> getLine\n thms <- parse.map readInt.B.words <$> B.getContents\n print $ solve n x thms\n\nparse :: [Int] -> [(Bool, Int, Int)]\nparse (1:h:m:rest) = (True,h,m) : parse rest\nparse (0:h:m:rest) = (False,h,m) : parse rest\nparse _ = []\n\nsolve :: Int -> Int -> [(Bool, Int, Int)] -> Int\nsolve n x thms = max (goF x 0 IS.empty IS.empty fs cs) (goC x 0 IS.empty IS.empty fs cs)\n where\n fs = sort[(h,m)|(True,h,m)<-thms]\n cs = sort[(h,m)|(False,h,m)<-thms]\n goF !x !cnt !canUseF !canUseC fs cs\n | IS.null canUseF' = cnt\n | (m, canUseF'')<-IS.deleteFindMax canUseF' = goC (x+m) (cnt+1) canUseF'' canUseC fs' cs\n where\n (ms, fs') = span ((<=x).fst) fs\n !canUseF' = foldl' (flip IS.insert) canUseF $ map snd ms\n goC !x !cnt !canUseF !canUseC fs cs\n | IS.null canUseC' = cnt\n | (m, canUseC'')<-IS.deleteFindMax canUseC'= goF (x+m) (cnt+1) canUseF canUseC'' fs cs'\n where\n (ms, cs') = span ((<=x).fst) cs\n !canUseC' = foldl' (flip IS.insert) canUseC $ map snd ms\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,x] <- map read.words <$> getLine\n thms <- parse.map readInt.B.words <$> B.getContents\n print $ solve n x thms\n\nparse :: [Int] -> [(Bool, Int, Int)]\nparse (1:h:m:rest) = (True,h,m) : parse rest\nparse (0:h:m:rest) = (False,h,m) : parse rest\nparse _ = []\n\nsolve :: Int -> Int -> [(Bool, Int, Int)] -> Int\nsolve n x thms = max (goF x 0 IS.empty fs cs) (goC x 0 IS.empty fs cs)\n where\n fs = sort[(h,m)|(True,h,m)<-thms]\n cs = sort[(h,m)|(False,h,m)<-thms]\n goF !x !cnt !canUse fs cs\n | IS.null canUse' = cnt\n | (m, canUse'')<-IS.deleteFindMax canUse' = goC (x+m) (cnt+1) canUse'' fs' cs\n where\n (ms, fs') = span ((<=x).fst) fs\n !canUse' = foldl' (flip IS.insert) canUse $ map snd ms\n goC !x !cnt !canUse fs cs\n | IS.null canUse' = cnt\n | (m, canUse'')<-IS.deleteFindMax canUse'= goF (x+m) (cnt+1) canUse'' fs cs'\n where\n (ms, cs') = span ((<=x).fst) cs\n !canUse' = foldl' (flip IS.insert) canUse $ map snd ms\n"}], "src_uid": "6253f6217c58a66573b1ddc6962c372c"} {"source_code": "main = interact $ show . solve . tail . lines\nsolve [s] = sum $ map fst $ filter ((`elem` \"2468\") . snd) $ zip [1..] s\n", "positive_code": [{"source_code": "import Data.Char\nevenSubstrings :: String -> Int\nevenSubstrings s = sum $ map f $ (zip s [1..])\nf (x,y)\n | even $ digitToInt x = y\n | otherwise = 0\nmain = interact $ show . evenSubstrings . (!! 1) . lines\n"}, {"source_code": "{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List\nimport Data.Int\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nceven !c = even $ ord c \n\nsolve :: [C.ByteString] -> Builder\nsolve (sn:s:_) = int64Dec res <> char7 '\\n'\n where\n res :: Int64\n res = sum $ map (fromIntegral . fst) $ filter (ceven . snd) $ zip [1 .. ] $ C.unpack $ C.take (ri sn) s\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n"}, {"source_code": "main = interact $ show.helper.words\n\nhelper (x:xs:_) = fonk 0 1 xs\n where fonk res _ [] = res \n fonk res i (a:aa) = if (even.read) (a:\"\") \n then fonk (res + i) (i+1) aa \n else fonk (res) (i+1) aa\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\n\t\t\n\nmain= do\n\t\tn<- read <$> getLine ::IO [Int]\n\t\ts<-map digitToInt <$> getLine \n\t\tprint $ sum $ zipWith (\\a b-> if even b then a else 0) [1..] s\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(findIndices)\n\ncountEvenSubstrings :: [Int] -> Int\ncountEvenSubstrings = sum . map (+1) . findIndices (even)\n\nmain = do\n nStr <- getLine\n str <- getLine\n let xs = map read . map (:[]) $ str\n print $ countEvenSubstrings xs"}, {"source_code": "import Data.Char\n\nsolve _ [] = 0\nsolve n (x:xs) | digitToInt x `mod` 2 == 0 = (n + 1) + solve (n + 1) xs\n | otherwise = solve (n + 1) xs\n\nmain = do\n input <- getContents\n let s = last $ lines input\n print $ solve 0 s\n"}, {"source_code": "import Data.Char\nmain = interact $ show . evensubstr . last . lines\n\nevensubstr :: String -> Int\nevensubstr s = sum $ map es $ (zip s [1,2..])\n where es (x, y)\n | even $ digitToInt x = y\n | otherwise = 0\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nevenSubstrings :: String -> Int\nevenSubstrings = fst . foldl (\\(a, b) c -> if elem c \"02468\" \n then (a + b, b + 1)\n else (a, b + 1)) (0, 1)\n\nmain :: IO ()\nmain = do\n _ <- readInt\n s <- getLine\n print $ evenSubstrings s "}, {"source_code": "import Data.List (inits, tails)\nimport Data.Char (digitToInt)\n\nmain :: IO ()\nmain = interact $ unlines . fmap (show . countSub) . tail . words\n\ncountSub :: String -> Int\ncountSub = sum . map fst . filter (even . digitToInt . snd) . zip [1..]\n"}], "negative_code": [{"source_code": "import Data.List\nsubseq = filter (not . null) . concatMap tails . inits\nevenSubstrings = length . filter ((== 0) . (`mod` 2)) . map read . tail . subseq\nmain = interact $ show . evenSubstrings . (!! 1) . lines"}], "src_uid": "43a65d1cfe59931991b6aefae1ecd10e"} {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n print $ n - countMinimums a\n\ncountMinimums :: [Int] -> Int\ncountMinimums a = length $ filter (== minimum a) a\n \n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- getInts\n (x : xs) <- sort <$> getInts\n C.putStrLn $ C.pack $ show $ length $ dropWhile (== x) xs\n"}, {"source_code": "evens (x:xs) = x:odds xs\r\nevens _ = []\r\n\r\nodds (_:xs) = evens xs\r\nodds _ = []\r\n\r\nsolution :: [Int] -> String\r\nsolution a =\r\n show $ length a - (length . filter (== (foldr1 min a))) a\r\n\r\nmain = interact $ unlines . map (solution . map read . words) . odds . tail . lines\r\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let m = minimum a\r\n c = length . filter (==m) $ a\r\n print $ n - c\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\nsolve [x] n = n \r\nsolve (x:xs) n = if x == head xs then solve xs (n+1) else n\r\nprintS = do \r\n n<-readLn::IO Int \r\n a <- readInts \r\n print $ n - solve (sort a) 1\r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t printS"}, {"source_code": "main = do\r\n --text <- readFile \"inputt.txt\"\r\n --putStrLn ((unlines . solve . map ((\\x -> (map (\\y -> read y :: Int) x)) . words) . tail . lines) text)\r\n interact (unlines . solve . map ((\\x -> (map (\\y -> read y :: Int) x)) . words) . tail . lines)\r\n\r\nsolve :: [[Int]] -> [String]\r\nsolve [] = []\r\nsolve (a : b : lst) = (show (head a - (occr (minelt b) b)) : solve lst)\r\noccr elt [] = 0\r\noccr elt (a : xs)\r\n | (==) a elt = (+) 1 (occr elt xs)\r\n | otherwise = (occr elt xs)\r\nminelt [x] = x\r\nminelt (x : xs)\r\n | (x < t) = x\r\n | otherwise = t\r\n where t = minelt (xs)\r\n"}], "negative_code": [], "src_uid": "d5627b9fe5f6c5a7247e1f9d9e9b0c6a"} {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( sort )\r\n\r\nsolve = do\r\n [n, x] <- map read.words <$> getLine :: IO [Int]\r\n a <- map read.words <$> getLine :: IO [Int]\r\n let v = drop (n - x) $ take x $ sort a\r\n let u = drop (n - x) $ take x a \r\n if u == v then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\nmain = readLn >>= flip replicateM_ solve", "positive_code": [{"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( sort )\r\n\r\nsolve = do\r\n [n, x] <- map read.words <$> getLine :: IO [Int]\r\n a <- map read.words <$> getLine :: IO [Int]\r\n let v = drop (n - x) $ take x $ sort a\r\n let u = drop (n - x) $ take x a \r\n putStrLn $ if u == v then \"YES\" else \"NO\"\r\n\r\nmain = readLn >>= flip replicateM_ solve"}], "negative_code": [], "src_uid": "1305b44c5c588221bc991c696a492fe7"} {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve (a_:b_:ts_) = ans where\n ans = go 0 0 a_ b_ ts_\n go r _ _ _ [] = r\n go r 0 0 0 ts = r + sum ts\n go r d 0 0 (1:ts) = go r (d-1) 0 0 ts\n go r d 0 b (1:ts) = go r (d+1) 0 (b-1) ts\n go r d a b (1:ts) = go r d (a-1) b ts\n go r d a 0 (2:ts) = go (r+2) d a 0 ts\n go r d a b (2:ts) = go r d a (b-1) ts", "positive_code": [{"source_code": "main = interact $ f\n\nf :: String -> String\nf = show . g . map read . words\n\ng :: [Int] -> Int\ng (n:a:b:ts) = h a b 0 ts\n\nh :: Int -> Int -> Int -> [Int] -> Int\nh _ _ _ [] = 0\nh 0 0 0 (1:ts) = 1 + h 0 0 0 ts\nh 0 0 c (1:ts) = h 0 0 (c - 1) ts\nh 0 b c (1:ts) = h 0 (b - 1) (c + 1) ts\nh a b c (1:ts) = h (a - 1) b c ts\nh a 0 c (2:ts) = 2 + h a 0 c ts\nh a b c (2:ts) = h a (b - 1) c ts"}, {"source_code": "process a b c (1:listt) \n |(a == 0)&&(b == 0)&&(c == 0) = (process a b c listt) + 1\n |(a == 0)&&(b == 0)&&(c /= 0) = (process a b (c - 1) listt)\n |(a == 0)&&(b /= 0) = (process a (b - 1) (c + 1) listt)\n |(a /= 0) = (process (a - 1) b c listt)\n \nprocess a b c (2:listt)\n |(b == 0) = (process a b c listt) + 2\n |(b /= 0) = (process a (b - 1) c listt)\n\nprocess _ _ _ [] = 0\n\nsolution [[n, a, b], listt] = process a b 0 listt\n\nproblem_data s = (map$map read).(map words).lines$s::[[Int]]\nmain = interact$(show.solution.problem_data)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n, a, b] <- fmap readInts B.getLine\n ts <- fmap readInts B.getLine\n print $ solve n a b ts\n\nsolve n a b ts = (\\(_, _, _, c) -> c) $ foldl go (a, 0, b, 0) ts\n where\n go (!c1, !c1', !c2, !c) t\n | t == 1 && c1 > 0 = (c1 - 1, c1', c2, c)\n | t == 1 && c2 > 0 = (c1, c1' + 1, c2 - 1, c)\n | t == 1 && c1' > 0 = (c1, c1' - 1, c2, c)\n | t == 2 && c2 > 0 = (c1, c1', c2 - 1, c)\n | otherwise = (c1, c1', c2, c + t)\n\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "-- words :: String -> [String] Source #\n-- words breaks a string up into a list of words, which were delimited by white space.\n\n-- read :: Read a => String -> a Source # (Here a is an int)\n-- The read function reads input from a string, which must be completely consumed by the input process.\n\nmain = interact $ f\n\nf :: String -> String\nf = show . g . map read . words\n\ng :: [Int] -> Int\n-- g (n:a:b:ts) = h a b 0 ts -- a is the number of 1-person tables, \n-- b is the number of 2-person tables, c is the number of 2-person tables with 1 person\n-- colon prepends a scalar to the front of a vector\ng x = h (g_a x) (g_b x) 0 (g_ts x)\n\ng_a :: [Int] -> Int\ng_a x = head (tail x)\n\ng_b :: [Int] -> Int\ng_b x = head (tail (tail x))\n\ng_ts :: [Int] -> [Int]\ng_ts x = tail (tail (tail x))\n\nh :: Int -> Int -> Int -> [Int] -> Int\nh a b c ts = \n if ts == [] \n then 0\n else if head ts == 1\n then (if a > 0\n then h (a-1) b c (tail ts)\n else (if b > 0\n then h a (b-1) (c+1) (tail ts)\n else (if c > 0\n then h a b (c-1) (tail ts)\n else 1 + h a b c (tail ts)))) --Each bracket () contains *one* value\n else -- i.e. else if head ts == 2\n if b > 0\n then h a (b-1) c (tail ts)\n else 2 + h a b c (tail ts)\n "}, {"source_code": "-- words :: String -> [String] Source #\n-- words breaks a string up into a list of words, which were delimited by white space.\n\n-- read :: Read a => String -> a Source # (Here a is an int)\n-- The read function reads input from a string, which must be completely consumed by the input process.\n\nmain = interact $ f\n\nf :: String -> String\nf = show . g . map read . words\n\ng :: [Int] -> Int\ng (n:a:b:ts) = h a b 0 ts -- a is the number of 1-person tables, \n-- b is the number of 2-person tables, c is the number of 2-person tables with 1 person\n\nh :: Int -> Int -> Int -> [Int] -> Int\nh a b c ts = \n if ts == [] \n then 0\n else if head ts == 1\n then (if a > 0\n then h (a-1) b c (tail ts)\n else (if b > 0\n then h a (b-1) (c+1) (tail ts)\n else (if c > 0\n then h a b (c-1) (tail ts)\n else 1 + h a b c (tail ts)))) --Each bracket () contains *one* value\n else -- i.e. else if head ts == 2\n if b > 0\n then h a (b-1) c (tail ts)\n else 2 + h a b c (tail ts)\n "}], "negative_code": [{"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . words =<< getContents\n\nsolve (n:a_:b_:ts_) = ans where\n ans = if n /= length ts_ then -1 else go 0 a_ b_ ts_\n go r _ _ [] = r\n go r 0 0 ts = r + sum ts\n go r 0 b (1:ts) = go r 1 (b-1) ts\n go r a b (1:ts) = go r (a-1) b ts\n go r a 0 (2:ts) = go (r+2) a 0 ts\n go r a b (2:ts) = go r a (b-1) ts"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve (a:b:ts) = go 0 a b ts where\n go r _ _ [] = r\n go r 0 0 ts = r + sum ts\n go r 0 b (1:ts) = go r 1 (b-1) ts\n go r a b (1:ts) = go r (a-1) b ts\n go r a 0 (2:ts) = go (r+2) a 0 ts\n go r a b (2:ts) = go r a (b-1) ts"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve (a:b:ts) = go 0 a b ts where\n go r _ _ [] = r\n go r 0 0 (1:ts) = r + sum ts\n go r 0 b (1:ts) = go r 1 (b-1) ts\n go r a b (1:ts) = go r (a-1) b ts\n go r a 0 (2:ts) = go (r+2) a b ts\n go r a b (2:ts) = go r a (b-1) ts"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve (a_:b_:ts_) = go 0 a_ b_ ts_ where\n go r _ _ [] = r\n go r 0 0 (p:ts) = go (r+p) 0 0 ts\n go r 0 b (1:ts) = go r 1 (b-1) ts\n go r a b (1:ts) = go r (a-1) b ts\n go r a 0 (2:ts) = go (r+2) a 0 ts\n go r a b (2:ts) = go r a (b-1) ts"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve (a:b:ts) = go 0 a b ts where\n go r _ _ [] = r\n go r 0 0 (1:ts) = r + 1 + sum ts\n go r 0 b (1:ts) = go r 1 (b-1) ts\n go r a b (1:ts) = go r (a-1) b ts\n go r a 0 (2:ts) = go (r+2) a b ts\n go r a b (2:ts) = go r a (b-1) ts"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve (a_:b_:ts_) = go 0 a_ b_ ts_ where\n go r _ _ [] = r\n go r 0 0 ts = r + sum ts\n go r 0 b (1:ts) = go r 1 (b-1) ts\n go r a b (1:ts) = go r (a-1) b ts\n go r a 0 (2:ts) = go (r+2) a 0 ts\n go r a b (2:ts) = go r a (b-1) ts"}], "src_uid": "e21e768dbb2e5f72873dc1c7de4879fd"} {"source_code": "\nimport Control.Monad\n-- import Data.List.HT (mapAdjacent)\n\nmapAdjacent :: (a -> a -> b) -> [a] -> [b]\nmapAdjacent f xs = zipWith f xs (tail xs)\n\nsolve :: String -> String\nsolve s \n | c + 1 == length s = \"NO\"\n | otherwise = \"YES\\n\" ++ show (c+1) ++ \" \" ++ show (c+2)\n where c = length $ takeWhile (==False) $ mapAdjacent (>) s\n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n s <- getLine\n putStrLn $ solve s", "positive_code": [{"source_code": "import Data.Maybe\nmain :: IO ()\nmain = do\n _ <- getLine\n s <- getLine\n case solve s of\n Nothing -> putStrLn \"NO\"\n Just i -> do\n putStrLn \"YES\"\n putStrLn $ (unwords.map show) [i,i+1]\n\nsolve :: String -> Maybe Int\nsolve s = (\\(_,_,c) -> c) <$> m\n where m = listToMaybe $ filter (\\(x,y,_) -> x>y) $ zip3 s (tail s) [(1::Int)..]\n"}, {"source_code": "main = getLine >> getLine >>= answer\n\nanswer xs\n | n == 0 = putStrLn \"NO\"\n | otherwise = putStrLn $ \"YES\\n\" ++ show n ++ \" \" ++ (show $ n + 1)\n where n = solve 0 (pred 'a') xs\n\nsolve _ _ [] = 0\nsolve n c (x:xs) = if c <= x then solve (n+1) x xs else n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\ts <- getLine\n\tlet\n\t\tres = solve ( 1 :: Int ) s\n\tcase res of\n\t\tNothing -> putStrLn \"NO\"\n\t\tJust res -> do\n\t\t\tputStrLn \"YES\"\n\t\t\tprintf \"%d %d\\n\" res $ succ res\n\nsolve _ [] = Nothing\nsolve _ [_] = Nothing\nsolve pos (a:b:s)\n\t| a > b = Just pos\n\t| otherwise = solve ( succ pos ) (b:s)"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ f2 $ h (f s) s\n return ()\n{-\nf :: String -> Maybe Int\nf s =let r = reverse s in\n elemIndex True $ map (\\x -> (compare x s)==LT) (tails r)\n \n \nc :: Int -> Maybe Int -> String\nc n (Just x) =\"YES\\n\"++(show (n-x))++\" \"++(show n)\nc n Nothing = \"NO\"\n-}\nf :: String -> Maybe Char\nf (x:y:ys) =if x>y then Just (x) else f (y:ys) \nf (y:ys) = Nothing\n\nh :: Maybe Char -> String -> Maybe Int\nh Nothing _ = Nothing\nh (Just x) s = elemIndex x s\n\nf2 :: Maybe Int -> String\nf2 Nothing = \"NO\"\nf2 (Just (x)) = \"YES\\n\"++(show x)++\" \"++(show (x+1))"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ f2 $ h (f s) s\n return ()\n{-\nf :: String -> Maybe Int\nf s =let r = reverse s in\n elemIndex True $ map (\\x -> (compare x s)==LT) (tails r)\n \n \nc :: Int -> Maybe Int -> String\nc n (Just x) =\"YES\\n\"++(show (n-x))++\" \"++(show n)\nc n Nothing = \"NO\"\n-}\nf :: String -> Maybe Char\nf (x:y:ys) =if x>y then Just (x) else f (y:ys) \nf (y:ys) = Nothing\n\nh :: Maybe Char -> String -> Maybe Int\nh Nothing _ = Nothing\nh (Just x) s = elemIndex x s\n\nf2 :: Maybe Int -> String\nf2 Nothing = \"NO\"\nf2 (Just (x)) = \"YES\\n\"++(show (x+1))++\" \"++(show (x+1+1))"}, {"source_code": "\nimport Control.Monad\n-- import Data.List.HT (mapAdjacent)\n\nmapAdjacent :: (a -> a -> b) -> [a] -> [b]\nmapAdjacent f xs = zipWith f xs (tail xs)\n\nsolve :: String -> String\nsolve s \n | c + 1 == length s = \"NO\"\n | otherwise = \"YES\\n\" ++ show (c+1) ++ \" \" ++ show (c+2)\n where c = length $ takeWhile (==False) $ mapAdjacent (>) s\n\nmain :: IO ()\nmain = do\n s <- getLine\n putStrLn $ solve s"}], "src_uid": "d45f775613e701bbdaa4e457e6e189e2"} {"source_code": "import Control.Monad\nimport Data.Array.IO.Safe\nimport Data.Array.Unboxed\nimport Data.List\nimport qualified Data.IntSet as IntSet\nimport qualified Data.Map.Strict as M\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\noutput :: Show a => [a] -> IO ()\noutput = putStrLn <$> unwords <$> map show\n\nc n k = product [n-k+1..n] `div` product [1..k]\n\n_mod = 1000000007\n\nmain = do\n [t] <- input\n replicateM_ t $ do\n [n] <- input\n a <- input\n let suffixSums = listArray (1, n+1) $ scanr (+) 0 a :: UArray Int Int\n good <- newArray (1, n) False :: IO (IOUArray Int Bool)\n forM_ [1..n+1] $ \\i -> forM_ [i+2..n+1] $ \\j -> do\n let d = suffixSums!i - suffixSums!j\n if d <= n then writeArray good d True else return ()\n good' <- freeze good :: IO (UArray Int Bool)\n print $ length $ filter (good'!) a\n", "positive_code": [{"source_code": "import qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\n\n\nsubSums :: Int -> [Int] -> IntSet\n--subSums n (a1:a2:as) = IS.union (prefixSums n a1 (a2:as)) $ subSums n (a2:as)\nsubSums _ [_] = IS.empty\nsubSums n as = IS.unions $ suffixLists as\n where\n suffixLists [_] = []\n suffixLists lst = getPSums lst:suffixLists (tail lst)\n getPSums (l:ls) = IS.fromDistinctAscList $ prefixSums n l ls\n\nprefixSums :: Int -> Int -> [Int] -> [Int]\nprefixSums n offset [] = []\nprefixSums n offset (a:as)\n | (offset+a) <= n = (offset+a) : prefixSums n (offset+a) as\n | otherwise = []\n\nsolve :: [Int] -> Int\nsolve as = length $ filter (`IS.member` sums) as\n where sums = subSums (length as) as\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n as <- readNums\n print $ solve as\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "negative_code": [{"source_code": "import qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\n\n\nsubSums :: Int -> [Int] -> IntSet\n--subSums n (a1:a2:as) = IS.union (prefixSums n a1 (a2:as)) $ subSums n (a2:as)\nsubSums _ [_] = IS.empty\nsubSums n as = IS.unions $ suffixLists as\n where\n suffixLists [_] = []\n suffixLists lst = getPSums lst:suffixLists (tail lst)\n getPSums (l:ls) = IS.fromDistinctAscList $ reverse $ prefixSums n l ls\n\nprefixSums :: Int -> Int -> [Int] -> [Int]\nprefixSums n offset [] = [0]\nprefixSums n offset (a:as)\n | (offset+a) <= n = (offset+a) : prefixSums n (offset+a) as\n | otherwise = []\n\nsolve :: [Int] -> Int\nsolve as = length $ filter (`IS.member` sums) as\n where sums = subSums (length as) as\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n as <- readNums\n print $ solve as\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "src_uid": "2326470337301e0f4b0d1b1a6195e398"} {"source_code": "strToList = (map (read :: String -> Int)).words\n\nf k n s | k - 1 > n - k = (concat $ replicate (n - k) \"RIGHT\\n\") ++ g (reverse s) \"LEFT\\n\"\n | otherwise = (concat $ replicate (k - 1) \"LEFT\\n\") ++ g s \"RIGHT\\n\"\n where g [s] _ = (\"PRINT \" ++ [s] ++ \"\\n\")\n g (s:xs) phrase = (\"PRINT \" ++ [s] ++ \"\\n\") ++ phrase ++ g xs phrase\n\nmain = do\n s <- getLine\n let [n, k] = strToList s\n t <- getLine\n putStrLn $ f k n t", "positive_code": [{"source_code": "import Control.Applicative\n\nstep1 n k s\n\t| k == 0 = forward n k s\n\t| k == n - 1 = backward n k s\n\t| k + k < n = \"LEFT\\n\" ++ step1 n (k - 1) s\n\t| otherwise = \"RIGHT\\n\" ++ step1 n (k + 1) s\n\nforward n k s\n\t| k == n - 1 = \"PRINT \" ++ [s !! k] ++ \"\\n\"\n\t| otherwise = \"PRINT \" ++ [s !! k] ++ \"\\nRIGHT\\n\" ++ forward n (k + 1) s\n\nbackward n k s\n\t| k == 0 = \"PRINT \" ++ [s !! k] ++ \"\\n\"\n\t| otherwise = \"PRINT \" ++ [s !! k] ++ \"\\nLEFT\\n\" ++ backward n (k - 1) s\n\nmain = do\n\t[n, k] <- map read . words <$> getLine\n\ts <- getLine\n\tputStr $ step1 n (k - 1) s"}], "negative_code": [], "src_uid": "e3a03f3f01a77a1983121bab4218c39c"} {"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC {n :: Int, l :: Int, r :: Int, k :: Int, as :: [Int]}\r\n\r\ntype Output = Int\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n l <- int\r\n r <- int\r\n k <- int\r\n as <- n >< int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} =\r\n length\r\n . takeWhile (<= k)\r\n . scanl1 (+)\r\n . filter (>= l)\r\n . filter (<= r)\r\n . sort\r\n $ as\r\n\r\noutput :: Output -> C.ByteString\r\noutput = showB\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.List(sort, findIndices)\n\n(|>) = flip ($)\n\n-- why does CF not have Data.List.Split??\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n [] = []\nchunksOf n xs = (take n xs) : (chunksOf n $ drop n xs)\n\nlastOr :: a -> [a] -> a\nlastOr def [] = def\nlastOr _def xs = last xs\n\nbetween :: Integer -> Integer -> [Integer] -> [Integer]\nbetween l r =\n filter (<= r)\n . filter (>= l)\n\nsolve :: [[Integer]] -> Int\nsolve [[n, l, r, k], values] =\n values\n |> between l r\n |> sort\n |> scanl1 (+)\n |> filter (<= k)\n |> length\n\nmain :: IO ()\nmain = interact $\n unlines\n . map (show . solve . map (map read . words))\n . chunksOf 2\n . tail\n . lines\n\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . input) . batch . tail . lines\n\nbatch :: [a] -> [(a, a)]\nbatch [] = []\nbatch (a:b:cs) = (a, b) : batch cs\n\ninput :: (String, String) -> (Int, Int, Int, Int, [Int])\ninput (i, j) = let [n, l, r, k] = map read $ words i\n as = map read $ words j\n in (n, l, r, k, as)\n\nsolve :: (Int, Int, Int, Int, [Int]) -> Int\nsolve (n, l, r, k, as) = snd $ foldl' accum (k, 0) $ sort $ filter inPriceRange as\n where\n accum :: (Int, Int) -> Int -> (Int, Int)\n accum (k', b') p\n | p <= k' = (k' - p, succ b')\n | otherwise = (k', b')\n\n inPriceRange :: Int -> Bool\n inPriceRange p = l <= p && p <= r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n,l,r,k] <- readv\r\n xs <- readv\r\n let\r\n ys = DL.sort xs\r\n zs = DL.takeWhile (<=r) $ DL.dropWhile (=0) us\r\n ans = length vs\r\n print ans\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat $ map (\\x->DBB.intDec x <> DBB.char8 ' ') xs\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n"}, {"source_code": "import Data.List\r\nimport Control.Monad\r\nmain = readLn >>= flip replicateM (\r\n map read <$> words <$> getLine >>= \\(n:l:r:k:_) ->\r\n map read <$> words <$> getLine >>= \\x ->\r\n print $ length $ takeWhile (<=k) $ scanl1 (+) $ sort $ filter (\\i -> (i >= l) && (i <= r)) x)"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\r\nmodule Main where\r\n\r\nimport Data.List (sort)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ndata InType = In { n :: Integer\r\n , l :: Integer\r\n , r :: Integer\r\n , k :: Integer\r\n , a :: [Integer]\r\n }\r\ntype OutType = Integer\r\n\r\nps :: [Integer] -> [Integer]\r\nps = go 0\r\n where go :: Integer -> [Integer] -> [Integer]\r\n go _ [] = []\r\n go acc (x : xs) = let acc' = x + acc\r\n in acc' : go acc' xs\r\n\r\nsolve :: InType -> OutType\r\nsolve In {..} =\r\n let av = sort $ filter (\\x -> x >= l && x <= r) a\r\n p = ps av\r\n in fromIntegral $ length $ takeWhile (<= k) p\r\n\r\nreceive :: [String] -> InType\r\nreceive [nlrk, sArr] =\r\n case toArr nlrk of\r\n [n, l, r, k] -> In n l r k (toArr sArr)\r\n _ -> error \"parse error on input\"\r\nreceive _ = error \"parse error on input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines\r\n"}], "negative_code": [], "src_uid": "f577695d39a11e8507681f307677c883"} {"source_code": "\nimport Data.List\n\nallEqual :: String -> Bool\nallEqual s = length (group s) == 1\n\nsolve1 :: String -> String\nsolve1 (s:ss)\n | allEqual (s:ss) = s:ss\n | otherwise = solveHelper s (s:ss)\n\nswitch :: Char -> Char\nswitch '1' = '0'\nswitch '0' = '1'\n\nsolveHelper :: Char -> String -> String\nsolveHelper _ \"\" = \"\"\nsolveHelper c (s:ss)\n | s == c = s: solveHelper (switch c) ss\n | otherwise = c: solveHelper (switch c) (s:ss)\n\nsolveTestCases :: Int -> IO ()\nsolveTestCases 0 = return ()\nsolveTestCases t = do\n s <- getLine\n putStrLn $ solve1 s\n solveTestCases (t-1)\n\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n solveTestCases $ read t", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n s <- getLine\n let n = length s\n putStrLn $ take (2 * n) $ f s\n\nf :: String -> String\nf s = case (length . group . sort $ s) of\n 1 -> repeat . head $ s\n 2 -> cycle \"10\""}, {"source_code": "import Control.Monad\n\nmain = readLn >>= flip replicateM_ test\n\ntest = do\n t <- getLine\n if all (== head t) t\n then putStrLn t\n else putStrLn $ take (2 * length t) (cycle \"01\")"}, {"source_code": "import qualified Data.List as L\n\nsolve :: String -> String\nsolve s\n | s == (take n $ repeat $ (s!!0)) = s\n | otherwise = concat $ take n $ repeat \"01\"\n where n = length s\n \nmain = interact $ unlines . map solve . tail . lines\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n putStrLn $ if all (== head s) s then s else concat $ replicate (length s) \"10\""}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n tt <- read <$> getLine\n replicateM_ tt $ do\n t <- getLine\n putStrLn $ if any (=='0') t && any (=='1') t\n then concat $ map (\\_ -> \"01\") t\n else t\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n tt <- read <$> getLine\n replicateM_ tt $ do\n t <- getLine\n putStrLn $ concat $ map (\\_ -> \"01\") t\n"}], "src_uid": "679a1e455073d3ea3856aa16516ba8ba"} {"source_code": "import Control.Monad\nimport Data.Array\nimport IO\n\ngao n l = elems a where\n\ta = listArray (1, n) [maximum $ 0:[a!j + s (b!j) (b!i) | j <- [1 .. i - 1]] | i <- [1 .. n]]\n\tb = listArray (1, n) l\n\ts [x,a,b] [y,c,d] = min x $ maximum $ 0:[f, g, h] where\n\t\ti = (b - a) / x\n\t\tj = (d - c) / y\n\t\tf = (c - a) / i\n\t\tg = if d <= b then (d - a) / i - y else 0\n\t\th = if b <= d then x - (b - c) / j else 0\n\nmain = do\n\ti <- openFile \"input.txt\" ReadMode\n\to <- openFile \"output.txt\" WriteMode\n\tn <- fmap read $ hGetLine i\n\tl <- replicateM n $ fmap (map read . words) $ hGetLine i\n\thPutStrLn o $ show $ maximum $ zipWith (+) (map head l) (gao n l)\n\thClose i\n\thClose o\n\n", "positive_code": [{"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "\nimport Array\nimport Monad (liftM)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\nparse' :: String -> (Int, Array Int (Int, Int, Int))\nparse' line = (n, listArray (1,n)\n [(xs !! (3 * i), xs !! (3 * i + 1), xs !! (3 * i + 2)) | i <- [0..n-1]])\n where\n xs = map read $ words line\n n = div (length xs) 3\n\ntestInput :: Test\ntestInput = TestList \"TestInput\" $ map (\\(solution, answer, num) -> \n Test (\"#\" ++ show num) $ assertApproximate answer (uncurry solve (parse' solution)) 6)\n $ take 11 $ drop 7 $ cycle $ zip3 tests answers [1..]\n\nanswers = \n [\n 70,\n 55,\n 5,\n 6,\n 3,\n 3,\n 11.33333333333333,\n 6,\n 4,\n 1,\n 82.93333333333333\n ]\n\ntests = \n [\n \"40 10 50 60 20 30\",\n \"50 30 80 35 25 70 40 10 90\",\n \"5 3 10\",\n \"1 1 2 2 2 3 3 3 4\",\n \"3 3 4 2 2 3 1 1 2\",\n \"3 3 5 1 4 5\",\n \"4 5 8 10 6 7\",\n \"4 5 8 1 1 2 5 3 4\",\n \"4 5 8 1 2 7\",\n \"1 1 2 1 1 2\",\n \"18 3 5 17 10 20 1 12 18 17 14 16 15 10 19 7 11 14 3 11 12 16 18 19 13 17 20 20 18 20\"\n ]\n\n\ntest :: IO ()\ntest = runs\n [\n testInput\n ]\n-}\n--------------------------------------------------------------------------------\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\n\nparse :: Read a => String -> (a, a, a)\nparse line = case words line of\n [s1, s2, s3] -> (read s1, read s2, read s3)\n\ngetHeight :: (Int, Int, Int) -> Int\ngetHeight (h, _, _) = h\n\nsolve :: Int -> Array Int (Int, Int, Int) -> Double\nsolve n xs = maximum [hs ! i + fromIntegral (getHeight (xs ! i)) | i <- [1..n]]\n where\n hs = array (1, n) ((1, 0) :\n [(i, maximum [height (xs ! i) (xs ! j) (hs ! j) | j <- [1..i-1]]) | i <- [2..n]])\n\n height t1@(h1, a1, b1) t2@(h2, a2, b2) d2\n | a1 >= b2 = d2 + fromIntegral h2\n | otherwise = d2 + case compareDelta t1 t2 of\n GT -> (b1 <= b2) ? (max 0 (fromIntegral (h2 - h1) - fromIntegral (b2 - b1) / tanDelta t2))\n $ (max 0 (fromIntegral h2 - fromIntegral (b2 - a1) / tanDelta t1))\n _ -> (a1 <= a2) ? 0 $ fromIntegral (a1 - a2) / tanDelta t2\n\n tanDelta (h, a, b) = fromIntegral (b-a) / fromIntegral h\n compareDelta (h1, a1, b1) (h2, a2, b2) = compare (h2 * (b1 - a1)) (h1 * (b2 - a2))\n\nmain :: IO ()\nmain = do\n ls <- liftM lines $ readFile \"input.txt\"\n let n = read $ head ls\n let xs = listArray (1,n) $ take n $ map parse $ tail ls\n writeFile \"output.txt\" $ show $ solve n xs\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n "}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]\n\n\n"}], "negative_code": [{"source_code": "\nimport Array\nimport Monad (liftM)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\nparse' :: String -> (Int, Array Int (Int, Int, Int))\nparse' line = (n, listArray (1,n)\n [(xs !! (3 * i), xs !! (3 * i + 1), xs !! (3 * i + 2)) | i <- [0..n-1]])\n where\n xs = map read $ words line\n n = div (length xs) 3\n\ntestInput :: Test\ntestInput = TestList \"TestInput\" $ map (\\(solution, answer, num) -> \n Test (\"#\" ++ show num) $ assertApproximate answer (uncurry solve (parse' solution)) 6)\n $ drop 10 $ zip3 tests answers [1..]\n\nanswers = \n [\n 70,\n 55,\n 5,\n 6,\n 3,\n 3,\n 11.33333333333333,\n 6,\n 4,\n 1,\n 82.93333333333333\n ]\n\ntests = \n [\n \"40 10 50 60 20 30\",\n \"50 30 80 35 25 70 40 10 90\",\n \"5 3 10\",\n \"1 1 2 2 2 3 3 3 4\",\n \"3 3 4 2 2 3 1 1 2\",\n \"3 3 5 1 4 5\",\n \"4 5 8 10 6 7\",\n \"4 5 8 1 1 2 5 3 4\",\n \"4 5 8 1 2 7\",\n \"1 1 2 1 1 2\",\n \"18 3 5 17 10 20 1 12 18 17 14 16 15 10 19 7 11 14 3 11 12 16 18 19 13 17 20 20 18 20\"\n ]\n\n\ntest :: IO ()\ntest = runs\n [\n testInput\n ]\n-}\n--------------------------------------------------------------------------------\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\n\nparse :: Read a => String -> (a, a, a)\nparse line = case words line of\n [s1, s2, s3] -> (read s1, read s2, read s3)\n\ngetHeight :: (Int, Int, Int) -> Int\ngetHeight (h, _, _) = h\n\nsolve :: Int -> Array Int (Int, Int, Int) -> Double\nsolve n xs = maximum [hs ! i + fromIntegral (getHeight (xs ! i)) | i <- [1..n]]\n where\n hs = array (1, n) ((1, 0) :\n [(i, maximum [height (xs ! i) (xs ! j) (hs ! j) | j <- [1..i-1]]) | i <- [2..n]])\n\n height t1@(h1, a1, b1) t2@(h2, a2, b2) d2\n | a1 >= b2 = d2 + fromIntegral h2\n | otherwise = d2 + case compareDelta t1 t2 of\n GT -> (b1 <= b2) ? (fromIntegral (h2 - h1) - fromIntegral (b2 - b1) / tanDelta t2)\n $ (max 0 (fromIntegral h2 - fromIntegral (b2 - a1) / tanDelta t1))\n _ -> (a1 <= a2) ? 0 $ fromIntegral (a1 - a2) / tanDelta t2\n\n tanDelta (h, a, b) = fromIntegral (b-a) / fromIntegral h\n compareDelta (h1, a1, b1) (h2, a2, b2) = compare (h2 * (b1 - a1)) (h1 * (b2 - a2))\n\nmain :: IO ()\nmain = do\n ls <- liftM lines $ readFile \"input.txt\"\n let n = read $ head ls\n let xs = listArray (1,n) $ take n $ map parse $ tail ls\n writeFile \"output.txt\" $ show $ solve n xs\n"}, {"source_code": "\nimport Array\nimport Monad (liftM)\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\n\nparse :: Read a => String -> (a, a, a)\nparse line = case words line of\n [s1, s2, s3] -> (read s1, read s2, read s3)\n\ngetHeight :: (Int, Int, Int) -> Int\ngetHeight (h, _, _) = h\n\nsolve :: Int -> Array Int (Int, Int, Int) -> Double\nsolve n xs = maximum [hs ! i + fromIntegral (getHeight (xs ! i)) | i <- [1..n]]\n where\n hs = array (1, n) ((1, 0) :\n [(i, maximum [height (xs ! i) (xs ! j) (hs ! j) | j <- [1..i-1]]) | i <- [2..n]])\n\n height t1@(h1, a1, b1) t2@(h2, a2, b2) d2\n | a1 >= b2 = d2 + fromIntegral h2\n | otherwise = case compareDelta t1 t2 of\n LT -> d2 + max 0 (fromIntegral h2 - fromIntegral (b2 - a1) * tanDelta t1)\n _ -> (a1 <= a2) ? d2 $ d2 + fromIntegral (a1 - a2) * tanDelta t2\n\n tanDelta (h, a, b) = fromIntegral h / fromIntegral (b - a)\n compareDelta (h1, a1, b1) (h2, a2, b2) = compare (h1 * (b2 - a2)) (h2 * (b1 - a1))\n\nmain :: IO ()\nmain = do\n ls <- liftM lines $ readFile \"input.txt\"\n let n = read $ head ls\n let xs = listArray (1,n) $ take n $ map parse $ tail ls\n writeFile \"output.txt\" $ show $ solve n xs\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf theInput = show answer where\n n:bowl0 = lines theInput\n bowl = reverse $ map (map (read::String->Float)) $ map words bowl0\n height [x] = [(x,0)]\n height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs\n h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)\n | rb1 > rt2 = h2 + h3\n | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3\n | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3\n | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3\n answer = h1 + h2 where ([h1,_,_],h2):_ = height bowl\n\n"}], "src_uid": "0c3fd1226188cccd013b0842666c3597"} {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Maybe (Int,[[Int]])\nsolve a b l\n |a/=b || a <3 = Nothing\n | otherwise = Just (2*sum l,[[x,1+mod x a]|x <- [1..a]])\n\nroutine :: IO ()\nroutine = do\n [a,b] <-(map read.words) <$> getLine\n l <- (map read.words) <$> getLine\n case solve a b l of\n Just x -> f x\n _ -> putStrLn \"-1\"\n\nf :: (Int,[[Int]]) -> IO ()\nf (a,l) = do\n print a\n forM_ l (putStrLn . unwords . map show)\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad(forM_, liftM, replicateM, replicateM_)\nimport Data.List(sortBy, intercalate)\n\n-- Input parsing\nparseInts :: String -> [Int]\nparseInts str = map read (words str)\n\nparseIntsM :: IO [Int]\nparseIntsM = parseInts <$> getLine\n\n-- Solution\n\ndata Edge = Edge (Int, Int)\ntype EdgeWithCost = (Edge, Int)\n\ndata Solution = Solution {\n cost :: Int,\n edgeCount :: Int,\n edges :: [Edge]\n}\n\ndata Query = Query {\n vertexCount :: Int,\n edgeLimit :: Int,\n weights :: [Int]\n}\n\ndata Vertex = Vertex {\n ix :: Int,\n weight :: Int\n}\n\ninstance Show Edge where\n show (Edge (src, dst)) = show src ++ \" \" ++ show dst\n\ninstance Show Solution where\n show (Solution cost count edges) =\n let edgeString = intercalate \"\\n\" . map show $ edges in\n show cost ++ \"\\n\" ++ edgeString\n\nmapOrd :: Ord b => (a -> b) -> a -> a -> Ordering\nmapOrd f lhs rhs = compare (f lhs) (f rhs) \n\nvertexOrd :: Ord Int => Vertex -> Vertex -> Ordering\nvertexOrd = mapOrd weight\n\nx :: Vertex -> Vertex -> EdgeWithCost\nx v1 v2 = (Edge (ix v1, ix v2), weight v1 + weight v2)\n\nrotate :: Int -> [a] -> [a]\nrotate n l = (drop n l) ++ (take n l) \n\nx2 :: [Vertex] -> [EdgeWithCost]\nx2 vs = zipWith x vs (rotate 1 vs) \n\nfridgeSolve :: Query -> Maybe Solution\nfridgeSolve q =\n let v = vertexCount q in\n let e = edgeLimit q in\n let dummyEdges = e - v in\n if dummyEdges < 0 || v < 3 then Nothing else \n let s@(v1:v2:rest) :: [Vertex] = sortBy vertexOrd $ zipWith Vertex [1..v] $ weights q in\n let p :: [EdgeWithCost] = (x2 s) ++ (replicate dummyEdges (x v1 v2)) in\n Just $ Solution (foldr (+) 0 $ map snd p) e (map fst p)\n\ntaskM :: IO ()\ntaskM = do\n [n, m] <- parseIntsM\n ws <- parseIntsM\n case (fridgeSolve (Query n m ws)) of\n Nothing -> print $ -1\n Just s -> print $ s\n\nmain :: IO ()\nmain = do\n [t] <- parseIntsM\n replicateM_ t taskM\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Maybe (Int,[[Int]])\nsolve a b l\n |a/=b = Nothing\n | otherwise = Just (2*sum l,[[x,1+mod x a]|x <- [1..a]])\n\nroutine :: IO ()\nroutine = do\n [a,b] <-(map read.words) <$> getLine\n l <- (map read.words) <$> getLine\n case solve a b l of\n Just x -> f x\n _ -> putStrLn \"-1\"\n\nf :: (Int,[[Int]]) -> IO ()\nf (a,l) = do\n print a\n forM_ l (\\x -> putStrLn $ unwords $ map show x)\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> [Int] -> Maybe (Int,[[Int]])\nsolve a b l\n |a/=b = Nothing\n | otherwise = Just (2*sum l,[[x,mod (x+1) (a+1)]|x <- [1..a]])\n\nroutine :: IO ()\nroutine = do\n [a,b] <-(map read.words) <$> getLine\n l <- (map read.words) <$> getLine\n case solve a b l of\n Just x -> f x\n _ -> putStrLn \"-1\"\n\nf :: (Int,[[Int]]) -> IO ()\nf (a,l) = do\n print a\n forM_ l (\\x -> putStrLn $ unwords $ map show x)\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "src_uid": "f6e219176e846b16c5f52dee81601c8e"} {"source_code": "solve [s1, s2] =\n let [_,k] = map read $ words $ s1 :: [Integer]\n update ('a':_) (a,b) d = (a + d, b)\n update ('b':_) (a,b) d = (a, b + d)\n helper x y (a, b) res\n | min a b > k = helper (tail x) y (update x (a, b) (-1)) res \n | y == [] = max (a + b) res\n | otherwise = helper x (tail y) (update y (a, b) 1) (max res (a + b))\n in helper s2 s2 (0, 0) 0\nmain = getContents >>= putStrLn . show . solve . lines\n", "positive_code": [{"source_code": "solve s = \n let [s1,s2] = lines s\n [_,k] = map read $ words $ s1 :: [Integer]\n update ('a':_) (a,b) d = (a + d, b)\n update ('b':_) (a,b) d = (a, b + d)\n helper x y (a, b) dis res\n | min a b > k = helper (tail x) y (update x (a, b) (-1)) (dis - 1) res \n | y == [] = max dis res\n | otherwise = helper x (tail y) (update y (a, b) 1) (dis + 1) (max res dis)\n in helper s2 s2 (0, 0) 0 0\nmain :: IO()\nmain = getContents >>= putStrLn . show . solve\n"}, {"source_code": "import Data.List\nimport Data.Functor\n\nmain :: IO()\nmain = do\n [_, k] <- map read . words <$> getLine\n s <- getLine\n print $ maximum $ map (\\x -> solve (== x) s k) \"ab\"\n\nsolve :: (Char -> Bool) -> String -> Int -> Int\nsolve f s k = solve' s s 0 0\n where solve' :: String -> String -> Int -> Int -> Int\n solve' [] [] _ _ = 0\n solve' [] (t:ts) cnt len | cnt <= k = len\n | f t = solve' [] ts cnt (len - 1)\n | otherwise = solve' [] ts (cnt - 1) (len - 1)\n solve' (h:hs) (t:ts) cnt len | cnt <= k = max len (solve' hs (t:ts) (cnt + if f h then 0 else 1) (len + 1))\n | otherwise = solve' (h:hs) ts (cnt - if f t then 0 else 1) (len - 1)\n"}, {"source_code": "\n\n\n\n\n\npp = putStrLn \n\naaa (a : bb) (c : dd) k used len mx\n | a == 'a' =\n aaa bb (c : dd) k used (succ len) (maximum [(succ len), mx])\n | a == 'b' && used < k =\n aaa bb (c : dd) k (succ used) (succ len) (maximum [(succ len),mx])\n | a == 'b' && used == k && c == 'b' =\n aaa (a : bb) dd k (pred used) (pred len) mx\n | a == 'b' && used == k && c == 'a' =\n aaa (a : bb) dd k used (pred len) mx\naaa mpt something k used len mx = mx\n\n\ninvert (a : bb)\n | a == 'a' = 'b' : (invert bb)\n | a == 'b' = 'a' : (invert bb)\ninvert mpt = []\n\n\n-- do one pass for a and one for b\nmain = do\n fff <- getLine\n let nnn = (read (head (words fff)))::Int\n kkk = (read (last (words fff)))::Int\n\n gg <- getLine\n\n\n let one = aaa gg gg kkk 0 0 0\n two = aaa (invert gg) (invert gg) kkk 0 0 0\n\n\n pp (show (maximum [one,two]))\n \n\n\n \n"}, {"source_code": "\n\n\n\n\n\npp = putStrLn \n\naaa (a : bb) (c : dd) k used len mx\n | a == 'a' =\n aaa bb (c : dd) k used (succ len) (maximum [(succ len), mx])\n | a == 'b' && used < k =\n aaa bb (c : dd) k (succ used) (succ len) (maximum [(succ len),mx])\n | a == 'b' && used == k && c == 'b' =\n aaa (a : bb) dd k (pred used) (pred len) mx\n | a == 'b' && used == k && c == 'a' =\n aaa (a : bb) dd k used (pred len) mx\naaa mpt something k used len mx = mx\n\n\ninvert (a : bb)\n | a == 'a' = 'b' : (invert bb)\n | a == 'b' = 'a' : (invert bb)\ninvert mpt = []\n\n\n-- do one pass for a and one for b\nmain = do\n ff <- getLine\n let n = (read (head (words ff)))::Int\n k = (read (last (words ff)))::Int\n\n gg <- getLine\n\n\n let one = aaa gg gg k 0 0 0\n two = aaa (invert gg) (invert gg) k 0 0 0\n\n\n pp (show (maximum [one,two]))\n \n\n\n \n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\n_distList :: Char -> [Int] -> [Int]\n_distList 'a' (x:xs) = (x+1):xs\n_distList 'b' xs = 0:xs\n\ndistList :: String -> [Int]\ndistList = foldr _distList [0]\n\n\n\npartialSums :: Int -> [Int] -> [Int]\npartialSums sz lst =\n zipWith (-) (drop sz initsSums) initsSums\n where initsSums = 0:(scanl1 (+) lst)\n \n \nsolve :: Int -> String -> Int\nsolve k str =\n let dList = distList str in \n case partialSums (k+1) dList of\n [] -> sum [length dList, (-1), sum dList] \n pSums -> (k+) . maximum $ pSums\n \nmain :: IO()\nmain = do\n k <- (read . (!!1) . words) <$> getLine\n s <- getLine\n print . maximum $ \n [solve k] <*> (\n [id, map (\\x -> case x of {'a' -> 'b'; 'b' -> 'a'})] <*> [s]\n )"}], "negative_code": [], "src_uid": "0151a87d0f82a9044a0ac8731d369bb9"} {"source_code": "import Data.Int\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- fmap read getLine\n replicateM_ t $ do\n [a, b] <- map read . words <$> getLine\n let\n f :: (Int64, Int64) -> Int64 -> Int64\n f (0, _) _ = 0\n f (x, y) c = 1 + f (x `div` (y + c), y) c\n solve :: Int64 -> Int64 -> Int64\n solve low high\n | high - low < 10 = fst $ minimum $ zip (map g [low .. high]) [low .. high]\n | g m1 <= g m2 = solve low m2\n | otherwise = solve m1 high\n where\n m1 = low + (high - low) * 1 `div` 3\n m2 = low + (high - low) * 2 `div` 3\n g x = x + f (a, b) x\n putStrLn $ show $ solve (if b == 1 then 1 else 0) 10000000000\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[a, b] <- popInts\n return $ bshow (solve (fromIntegral a) (fromIntegral b))\n\n\nsolve :: Int64 -> Int64 -> Int64\nsolve a 1 = solve a 2 + 1\nsolve a b\n | a < b = 1\n | a < b ^ 2 = 2\n | otherwise = minimum $ map (\\(i, b') -> i + f b') $ zip [0..] $\n takeWhile (\\b' -> a >= (b' - 1) ^ 2) [b..]\n\n where\n f b' = head $ dropWhile (\\i -> a >= b' ^ i) $ [2..]\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[a, b] <- popIntegers\n return $ bshow (solve a b)\n\n\nsolve a 1 = solve a 2 + 1\nsolve a b\n | a < b = 1\n | a < b ^ 2 = 2\n | otherwise = minimum $ map (\\(i, b') -> i + f b') $ zip [0..] $\n takeWhile (\\b' -> a >= (b' - 1) ^ 2) [b..]\n\n where\n f b' = head $ dropWhile (\\i -> a >= b' ^ i) $ [2..]\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\ntype SIO = StateT P.ByteString IO\n\nsteps :: Int -> Int -> Int\nsteps = let\n go k 0 _ = k\n go _ _ 1 = maxBound\n go k p q = let k' = k+1 in k' `seq` go k' (quot p q) q\n in go 0\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [a, b] <- readInts\n let\n opts = zipWith (\\x y -> steps a x + y) [b..] [0..]\n ans = head [x | (x, y) <- zip opts $ tail opts, x < y]\n putInts [ans]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "2b757fa66ce89046fe18cdfdeafa6660"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Int] -> Int\nprocess students = maximum teamCnts where\n n = length students\n studentsArr = listArray (1, n) $ sort students :: Array Int Int\n teamCnts = map snd $ scanl foldFn (1, 0) [1..n]\n foldFn (i, _) j = (i', j - i' + 1) where\n x = studentsArr ! j\n i' = until (\\_i -> (studentsArr ! _i) >= x-5) (+ 1) i\n\nmain = do\n n <- getInt\n students <- getInts\n print $ process students\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O3 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Array.Unboxed\nimport qualified Data.Sequence as S\nimport Data.Foldable\nimport Data.List\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest :: Int -> [Int] -> Int\ntest n = f . listArray (0, n - 1) . toList . S.unstableSort . S.fromList\n where\n f :: UArray Int Int -> Int\n f arr = loop 0 0 minBound\n where\n loop i j r\n | i >= n = r\n | otherwise = loop (succ i) j' (max r (j' - i)) \n where j' = until (\\k -> k >= n || ((arr ! k) > (arr ! i) + 5)) succ j\n\nmain = do\n s <- C.getContents\n let (n:a) = map ru $ C.words s\n print $ test n $ take n a\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O3 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Int\nimport Data.Array.Unboxed\nimport qualified Data.Sequence as S\nimport Data.Foldable\nimport Data.List\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ne x y = abs (x - y) <= 5\n\ntest :: Int -> [Int] -> Int\ntest n = maximum . map length . groupBy e . toList . S.unstableSort . S.fromList\n\nmain = do\n s <- C.getContents\n let (n:a) = map ru $ C.words s\n print $ test n $ take n a\n"}], "src_uid": "8b075d96b3c0172d756109b4801d68de"} {"source_code": "gs' :: [Integer] -> Integer -> Integer -> Integer\ngs' [] curr ans = max curr ans\ngs' (x:xs) curr ans = if x+curr >= x\n then gs' xs (x+curr) (max (x+curr) ans)\n else gs' xs x (max x ans)\n\ngs :: [Integer] -> Integer\ngs [] = 0\ngs (x:xs) = gs' xs x x\n\nparse :: [String] -> String\nparse [_, input] = if sum' > ans then \"YES\" else \"NO\"\n where numbers = stringToIntegerArray input\n ans = max (gs $ tail numbers) (gs $ init numbers)\n sum' = sum numbers\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n\n-- helpers\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n strings = (take n strings):(groupByNLines n (drop n strings))\n\nstringToIntegerArray :: String -> [Integer]\nstringToIntegerArray = map (\\x -> read x :: Integer) . words\n", "positive_code": [{"source_code": "maxSum [] _ acc = acc\nmaxSum (x:xs) soFar acc = maxSum xs soFar' acc'\n where soFar' = max (soFar + x) 0\n acc' = max soFar' acc\n\nprocess :: Int -> IO ()\nprocess _ = do\n l <- map read . words <$> (getLine >> getLine)\n let ans = max (maxSum (tail l) 0 0) (maxSum (init l) 0 0)\n putStrLn $ if sum l > ans then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = (enumFromTo 1 . read <$> getLine) >>= mapM_ process\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= process.read\n\nprocess 0 = return ()\nprocess n = do\n\tgetLine\n\tas <- map read.words <$> getLine\n\tif any (<= 0) (scanl1 (+) as) || any (<= 0) (scanl1 (+) $ reverse as)\n\t\tthen putStrLn \"NO\"\n\t\telse putStrLn \"YES\"\n\tprocess $ n - 1\n"}, {"source_code": "import Control.Monad\nimport Data.Foldable\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n l <- (map read.words) <$> getLine\n putStrLn $ if solve l\n then \"NO\"\n else \"YES\"\n\nsolve :: [Integer] -> Bool\nsolve l = solve' l || solve' (reverse l)\n\nsolve' :: [Integer] -> Bool\nsolve' (x:xs) =\n case foldUntill (<=0) (+) x xs of\n Left _ -> True\n Right _ -> False\n\nfoldUntill :: Foldable t => (b -> Bool)-> (b -> a -> b) -> b -> t a -> Either (b,Maybe b,Maybe a) b\nfoldUntill predicate binary accumulator foldable =\n if predicate accumulator\n then Left (accumulator,Nothing,Nothing)\n else foldlM f accumulator foldable\n where\n f acc val =\n let\n newValue = binary acc val\n bool = predicate newValue\n in\n if bool\n then Left (newValue,Just acc,Just val)\n else Right newValue\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= process.read\n\nprocess 0 = return ()\nprocess n = do\n\tgetLine\n\tas <- map read.words <$> getLine\n\tif any (<= 0) (scanl (+) 0 as) || any (<= 0) (scanl (+) 0 $ reverse as)\n\t\tthen putStrLn \"NO\"\n\t\telse putStrLn \"YES\"\n\tprocess $ n - 1\n"}, {"source_code": "import Control.Monad\nimport Data.Foldable\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n l <- (map read.words) <$> getLine\n putStrLn $ if solve l\n then \"NO\"\n else \"YES\"\n\nsolve :: [Int] -> Bool\nsolve l = solve' l || solve' (reverse l)\n\nsolve' :: [Int] -> Bool\nsolve' (x:xs) =\n case foldUntill (<=0) (+) x xs of\n Left _ -> True\n Right _ -> False\n\nfoldUntill :: Foldable t => (b -> Bool)-> (b -> a -> b) -> b -> t a -> Either (b,Maybe b,Maybe a) b\nfoldUntill predicate binary accumulator foldable =\n if predicate accumulator\n then Left (accumulator,Nothing,Nothing)\n else foldlM f accumulator foldable\n where\n f acc val =\n let\n newValue = binary acc val\n bool = predicate newValue\n in\n if bool\n then Left (newValue,Just acc,Just val)\n else Right newValue\n"}, {"source_code": "gs' :: [Int] -> Int -> Int -> Int\ngs' [] curr ans = max curr ans\ngs' (x:xs) curr ans = if x+curr >= x\n then gs' xs (x+curr) (max (x+curr) ans)\n else gs' xs x (max x ans)\n\ngs :: [Int] -> Int\ngs [] = 0\ngs (x:xs) = gs' xs x x\n\nparse :: [String] -> String\nparse [_, input] = if sum' > ans then \"YES\" else \"NO\"\n where numbers = stringToIntegerArray input\n ans = max (gs $ tail numbers) (gs $ init numbers)\n sum' = sum numbers\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n\n-- helpers\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n strings = (take n strings):(groupByNLines n (drop n strings))\n\nstringToIntegerArray :: String -> [Int]\nstringToIntegerArray = map (\\x -> read x :: Int) . words\n"}], "src_uid": "6e5b4d43e64645cf26d5eac31437b1a9"} {"source_code": "import Data.Functor ((<$>))\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = getLine >>= putStrLn . maybe \"No solution\" (intercalate \",\") . solve\n\nsolve :: String -> Maybe [String]\nsolve xs | null xs = Just []\n | null ys || all (=='@') (take 2 zs) = Nothing\n | '@' `notElem` tail zs = Just [ xs ]\n | otherwise = ((ys ++ take 2 zs):) <$> solve (drop 2 zs)\n where (ys, zs) = break (=='@') xs\n", "positive_code": [{"source_code": "import Control.Monad(guard)\nmain = do \n s <- getLine\n case solve s of\n Nothing -> putStrLn \"No solution\"\n Just r -> putStrLn r\n \nsolve ('@':_) = Nothing\nsolve s | last s == '@' = Nothing\nsolve s = \n do\n let strings = lines . map f $ s\n first = head strings\n lst = last strings\n mids = tail . init $ strings\n f '@' = '\\n'\n f x = x\n insert (c:s) = c:',':s\n guard $ length strings > 1\n guard $ all ((>1) . length) mids\n Just $ first ++ \n (concatMap ('@':) . map insert $ mids) ++\n \"@\" ++ lst"}, {"source_code": "import Data.Maybe\n\nemail_recovery' [] = Just []\nemail_recovery' ('@':_) = Nothing\nemail_recovery' (x:'@':'@':_) = Nothing\nemail_recovery' (x:'@':y:xs) = (email_recovery' xs) >>= (\\a -> Just (',':x:'@':y:a))\nemail_recovery' (x:xs) = (email_recovery' xs) >>= (\\a -> Just (x : a))\n\nemail_recovery'' [] = Nothing\nemail_recovery'' ('@':_) = Nothing\nemail_recovery'' (x:'@':xs) = (email_recovery' (x:'@':xs)) >>= (\\a -> Just(tail a))\nemail_recovery'' (x:xs) = (email_recovery'' xs) >>= (\\a -> Just (x : a))\n\nerec [] = \"\"\nerec x = if isNothing result then \"No solution\"\n else fromJust (result)\n where result = email_recovery'' x\n\n\nmain = do\n inpStr <- getLine\n putStrLn (erec inpStr)\n"}, {"source_code": "-- 31B\n\nimport Data.List (intercalate)\nimport Maybe (fromMaybe)\n\ncheck = const True\n\nsolve :: String -> Maybe String\nsolve xs\n | null res = Nothing\n | otherwise = Just (intercalate \",\" res)\n where\n res = before \"\" [] xs\n before start acc []\n | null start = acc\n | otherwise = []\n before start acc ('@':s)\n | null start = []\n | otherwise = after start \"\" acc s\n before start acc (c:s) = before (start ++ [c]) acc s\n after begin end acc []\n | null end = []\n | otherwise = acc ++ [begin ++ \"@\" ++ end]\n after begin end acc ('@':s) = []\n after begin end acc (c:'@':s)\n | null end = []\n | otherwise = before [c] (acc ++ [begin ++ \"@\" ++ end]) ('@':s)\n after begin end acc (c:s) = after begin (end ++ [c]) acc s\n\n \n\nmain :: IO ()\nmain = getLine >>= putStrLn . fromMaybe \"No solution\" . solve"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = getLine >>= putStrLn . maybe \"No solution\" (intercalate \",\") . solve\n\nsolve :: String -> Maybe [String]\nsolve xs | null xs = Just []\n | null ys || all (=='@') (take 2 zs) = Nothing\n | '@' `notElem` tail zs = Just [ xs ]\n | otherwise = (:) (ys ++ take 2 zs) <$> solve (drop 2 zs)\n where (ys, zs) = break (=='@') xs\n"}, {"source_code": "import Data.List\nimport Data.Functor\nmain=getLine>>=putStrLn.maybe\"No solution\"(intercalate\",\").f\nf x|null x=Just[]|null y||all(=='@')(take 2 z)=Nothing|'@'`notElem`tail z=Just[x]|1>0=(:)(y++take 2 z)<$>f(drop 2 z)where(y,z)=break(=='@')x\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let split s = do\n let (as, s1) = span (/= '@') s\n (atMark, s2) = splitAt 1 s1\n (bs, s') = span (/= '@') s2\n case () of\n _ | null as -> Nothing\n | atMark /= \"@\" -> Nothing\n | null s' -> if null bs then Nothing else Just $ as ++ \"@\" ++ bs\n | null bs -> Nothing\n | head bs == '@' -> Nothing\n | length (take 2 bs) /= 2 -> Nothing\n | otherwise -> do\n let (bs1, bs2) = splitAt (length bs - 1) bs\n cs = as ++ \"@\" ++ bs1 ++ \",\"\n fmap (cs ++) $ split (bs2 ++ s')\n no = putStrLn \"\"\n m <- split <$> getLine\n putStrLn $ maybe \"No solution\" id m\n"}, {"source_code": "main = interact (ans)\nans theInput = answer address where\n\taddress = split $ head $ lines theInput\n\tsplit xs = if y==\t[] then [xs] else x:(split $ tail y) where\n\t\t(x,y) = break (=='@') xs\n\tcheck (x:xs) = ((length x) > 0):checkTail xs\n\tcheckTail [x] = [length x > 0]\n\tcheckTail (x:xs) = (length x > 1):checkTail xs\n\tanswer xs = if (length xs > 1) && (and (check xs))\n\t\tthen solution address else \"No solution\"\n\tsolution [x,y] = ad x y\n\tsolution (x:y:xs) = (ad x [head y]) ++ \",\" ++ solution ((tail y):xs)\n\tad x y = x ++ \"@\" ++ y\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Functor\nmain=interact$maybe\"No solution\"(intercalate\",\").f\nf x|null x=Just[]|null y||all(=='@')(take 2 z)=Nothing|'@'`notElem`tail z=Just[x]|1>0=(:)(y++take 2 z)<$>f(drop 2 z)where(y,z)=break(=='@')x\n"}, {"source_code": "import Data.List\nimport Data.Functor\nmain=interact$maybe\"Nosolution\"(intercalate\",\").f\nf x|null x=Just[]|null y||all(=='@')(take 2 z)=Nothing|'@'`notElem`tail z=Just[x]|1>0=(:)(y++take 2 z)<$>f(drop 2 z)where(y,z)=break(=='@')x\n"}, {"source_code": "main = interact (ans)\nans theInput = answer where\n\taddress = split $ head $ lines theInput\n\tsplit :: String -> [String]\n\tsplit \"\" = []\n\tsplit xs = if snd(break (=='@') u)==\"\" then [xs]\n\t\telse (x ++ (take 2 y)):(split u)\n\t\twhere\n\t\t\t(x,y) = break (=='@') xs\n\t\t\tu = drop 2 y\n\tcheck = [(head x /= '@') && (last x /='@') | x<- address]\n\tanswer = if and check then solution address else \"No solution\"\n\tsolution [x] = x\n\tsolution (x:xs) = x ++ \",\" ++ solution xs\n\n"}, {"source_code": "main = interact (ans)\nans theInput = answer where\n\tline0 = head $ lines theInput\n\taddress = split line0\n\tsplit :: String -> [String]\n\tsplit \"\" = []\n\tsplit xs = if snd(break (=='@') u)==\"\" then [xs]\n\t\telse (x ++ (take 2 y)):(split u)\n\t\twhere\n\t\t\t(x,y) = break (=='@') xs\n\t\t\tu = drop 2 y\n\tcheck = [(head x /= '@') && (last x /='@') | x<- address]\n\tanswer = if (snd(break (=='@') line0)/=\"\") && (and check) then solution address\n\t\telse \"No solution\"\n\tsolution [x] = x\n\tsolution (x:xs) = x ++ \",\" ++ solution xs\n\n"}, {"source_code": "main = interact (ans)\nans theInput = answer where\n\tline0 = head $ lines theInput\n\taddress = split line0\n\tsplit :: String -> [String]\n\tsplit xs = if elem '@' u then (x ++ (take 2 y)):(split u) else [xs] where\n\t\t(x,y) = break (=='@') xs\n\t\tu = drop 2 y\n\tcheck = [(head x /= '@') && (last x /='@') | x<- address]\n\tanswer = if (elem '@' line0) && (and check) then solution address else \"No solution\"\n\tsolution [x] = x\n\tsolution (x:xs) = x ++ \",\" ++ solution xs\n\n"}, {"source_code": "main = interact (ans)\nans theInput = answer where\n\tline0 = head $ lines theInput\n\taddress = split line0\n\tsplit :: String -> [String]\n\tsplit xs = if elem '@' u then (x ++ (take 2 y)):(split u) else [xs] where\n\t\t(x,y) = break (=='@') xs\n\t\tu = drop 2 y\n\tcheck = [(head x /= '@') && (last x /='@') | x<- address]\n\tanswer = if (elem '@' line0) && (and check) then solution address else \"No solution\"\n\tsolution [x] = x\n\tsolution (x:xs) = x ++ \",\" ++ solution xs\n\n"}, {"source_code": "import Data.Maybe\n\nemail_recovery' [] = Just []\nemail_recovery' ('@':_) = Nothing\nemail_recovery' (x:'@':'@':_) = Nothing\nemail_recovery' (x:'@':y:xs) = (email_recovery' xs) >>= (\\a -> Just (',':x:'@':y:a))\nemail_recovery' (x:xs) = (email_recovery' xs) >>= (\\a -> Just (x : a))\n\nemail_recovery'' [] = Nothing\nemail_recovery'' ('@':_) = Nothing\nemail_recovery'' (x:'@':xs) = (email_recovery' (x:'@':xs)) >>= (\\a -> Just(tail a))\nemail_recovery'' (x:xs) = (email_recovery'' xs) >>= (\\a -> Just (x : a))\n\nerec [] = \"\"\nerec x = if isNothing result then \"No solution.\"\n else fromJust (result)\n where result = email_recovery'' x\n\n\nmain = do\n inpStr <- getLine\n putStrLn (erec inpStr)\n"}], "src_uid": "71b4674e91e0bc5521c416cfc570a090"} {"source_code": "import Control.Monad\r\n\r\nsolve (x,y) | (y==\"a\") = 1\r\n | (any (=='a') y) = -1\r\n | otherwise = 1 + sum (map (\\k -> (toInteger n) `choose` k) (take n [1..]))\r\n where n = length x\r\n\r\nmain = do\r\n t <- getLine\r\n cases <- replicateM (read t) readCase\r\n putStrLn (unwords $ map (show . solve) cases)\r\n\r\nreadCase = do\r\n x <- getLine\r\n y <- getLine\r\n return (x, y)\r\n\r\nn `choose` k\r\n | k < 0 = 0\r\n | k > n = 0\r\n | otherwise = factorial n `div` (factorial k* factorial (n-k))\r\n\r\nfactorial n = product [1..n]", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\n\nimport Data.Set ( Set)\nimport qualified Data.Set as Set\n\nmain = do\n testCases <- getLine\n replicateM_ (read testCases) (runCase >>= putStrLn)\n\n\n\nrunCase = do\n lin <- getLine\n show . solve lin <$> getLine\n\nsolve inp subst | ('a' `notElem` inp) || (subst == \"a\") = 1\nsolve inp subst | (length subst > 1) && (elem 'a' subst) = if ('a' `elem` inp) then -1 else 1\nsolve inp _ = 2^(length $ filter (=='a') inp)"}, {"source_code": "import Control.Monad\r\n\r\nsolve (x,y) | (y==\"a\") = 1\r\n | (any (=='a') y) = -1\r\n | otherwise = 2 ^ length x\r\n\r\nmain = do\r\n t <- getLine\r\n cases <- replicateM (read t) readCase\r\n putStrLn (unwords $ map (show . solve) cases)\r\n\r\nreadCase = do\r\n x <- getLine\r\n y <- getLine\r\n return (x, y)"}], "negative_code": [{"source_code": "import Control.Monad\r\n\r\nsolve (x,y) | (y==\"a\") = 1\r\n | (any (=='a') y) = -1\r\n | otherwise = 1 + sum (map (\\k -> n `choose` k) (take n [1..]))\r\n where n = length x\r\n\r\nmain = do\r\n t <- getLine\r\n cases <- replicateM (read t) readCase\r\n putStrLn (unwords $ map (show . solve) cases)\r\n\r\nreadCase = do\r\n x <- getLine\r\n y <- getLine\r\n return (x, y)\r\n\r\nn `choose` k\r\n | k < 0 = 0\r\n | k > n = 0\r\n | otherwise = factorial n `div` (factorial k * factorial (n-k))\r\n\r\nfactorial n = product [1..n]"}, {"source_code": "import Control.Monad\r\n\r\nsolve (x,y) | (y==\"a\") = 1\r\n | (any (=='a') y) = -1\r\n | otherwise = length x + 1\r\n\r\nmain = do\r\n t <- getLine\r\n cases <- replicateM (read t) readCase\r\n putStrLn (unwords $ map (show . solve) cases)\r\n\r\nreadCase = do\r\n x <- getLine\r\n y <- getLine\r\n return (x, y)"}], "src_uid": "d6ac9ca9cc5dfd9f43f5f65ce226349e"} {"source_code": "--import Data.Bits\n--import Control.Monad\nimport Data.List\n--import Control.Monad.Writer\n--import Data.Maybe\nmain :: IO ()\nmain = do\n\tmm <- getLine\n\tlet n=read mm\n\ts <- getLine\n\t\n\tputStrLn $ if f n s then \"YES\" else \"NO\" \n\treturn ()\n\nf :: Int -> String -> Bool\nf n s = let m = (n-11) in\n if (length $ fst (partition (==1) $ take (m+1) $ concat $ group (map h s)))>(m `div` 2) then True else False\n\nh :: Char -> Int\nh '8' = 1\nh _ = 0\n\nt :: [Int] -> [Int]\nt s =(delete 1 (delete 0 s))\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\ts <- getLine\n\tlet\n\t\tturn = ( n - 11 ) `div` 2\n\t\tprefix = vasya turn s\n\t\tnum8 = length $ takeWhile ( == '8' ) prefix\n\tputStrLn $ which \"YES\" \"NO\" $ turn < num8\n\nvasya _ [] = []\nvasya 0 s = s\nvasya k (c:s)\n\t| c == '8' = c : vasya k s\n\t| otherwise = vasya ( pred k ) s"}], "negative_code": [], "src_uid": "99f37936b243907bf4ac1822dc547a61"} {"source_code": "import Data.List\nimport Control.Monad\nmain = interact $ format . solve . map read . tail . words\nsolve as = guard (sum ls /= sum rs) *> pure ss where\n ss = sort as\n (ls,rs) = splitAt (length ss `div` 2) ss\nformat Nothing = \"-1\"\nformat (Just xs) = unwords $ map show xs\n", "positive_code": [{"source_code": "module Main where\nimport Data.List\n\nmain = interact $ (\\(n:xs) -> maybe \"-1\" (unwords . map show) $ ok n $ sort xs) . map read . words\nok n xs\n | sum zs == sum ys = Nothing\n | True = Just xs\n where (ys, zs) = splitAt n xs\n"}], "negative_code": [{"source_code": "module Main where\n\nmain = interact $ (\\(n:xs) -> if rep xs then \"-1\" else unwords $ map show $ uncurry (mix [] []) $ splitAt n xs ) . map read . words\nrep (x:xs) = all (== x) xs\nmix xs' ys' [] [] = xs' ++ ys'\nmix xs' ys' (x:xs) (y:ys)\n | x /= y = mix (y:xs') (x:ys') xs ys\n | True = mix (x:xs') (y:ys') xs ys\n"}, {"source_code": "module Main where\n\nmain = interact $ (\\(n:xs) -> unwords $ map show $ uncurry go $ splitAt n xs) . map read . words\ngo xs ys\n | sum xs /= sum ys = xs ++ ys\n | True = mix False [] [] xs ys\nmix False _ _ [] [] = [-1]\nmix True xs' ys' [] [] = xs' ++ ys'\nmix b xs' ys' (x:xs) (y:ys)\n | not b && x /= y = mix True (y:xs') (x:ys') xs ys\n | True = mix b (x:xs') (y:ys') xs ys\n"}], "src_uid": "1f4c057dff45f229b4dca49cd4e0438d"} {"source_code": "{-# LANGUAGE TypeApplications, BangPatterns #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, x] <- readInts\r\n a <- listArray @UArray (1, n) <$> readInts\r\n dp <- newArray @IOUArray ((0, 0), (n, n)) 0\r\n forM_ [1..n] $ \\i ->\r\n forM_ [0..n] $ \\j -> do\r\n !nox <- (a!i +) . max 0 <$> readArray dp (i - 1, j)\r\n writeArray dp (i, j) =<< if j == 0 then pure nox else do\r\n !yesx <- (a!i + x +) . max 0 <$> readArray dp (i - 1, j - 1)\r\n pure $! max nox yesx\r\n dp <- unsafeFreeze @_ @_ @_ @_ @UArray dp\r\n putStrLn $ unwords $ map (show . maximum) [[dp!(i, j) | i <- [0..n]] | j <- [0..n]]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, x] <- readInts\r\n a <- listArray @UArray (1, n) <$> readInts\r\n dp <- newArray @IOUArray ((0, 0), (n, n)) 0\r\n forM_ [1..n] $ \\i ->\r\n forM_ [0..n] $ \\j -> do\r\n nox <- (a!i +) . max 0 <$> readArray dp (i - 1, j)\r\n writeArray dp (i, j) =<< if j == 0 then pure nox else do\r\n yesx <- (a!i + x +) . max 0 <$> readArray dp (i - 1, j - 1)\r\n pure $ max nox yesx\r\n dp <- unsafeFreeze @_ @_ @_ @_ @UArray dp\r\n putStrLn $ unwords $ map (show . maximum) [[dp!(i, j) | i <- [0..n]] | j <- [0..n]]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# OPTIONS_GHC -O2 -funbox-strict-fields -fvia-C -optc-O3 #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = res k\r\n where\r\n res 0 = (l, maxF)\r\n where \r\n l = v1 \r\n where v1 = drop 1 $ scanl (\\x y -> maximum' [0, x + y]) 0 a \r\n maxF = v2 \r\n where v2 = (maximum' l : [])\r\n res n = (l, maxF)\r\n where\r\n l = v1 \r\n where v1 = zipWith (\\a b -> maximum' [a + x, b + x + a]) a (0 : fst prev)\r\n maxF = v2 \r\n where v2 = (maximum' (0:l) : snd prev)\r\n \r\n prev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse (snd answer)) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve"}, {"source_code": "-- problem: https://codeforces.com/contest/1644/problem/C\r\n-- origin: https://codeforces.com/contest/1644/submission/147353835\r\n\r\nimport Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let -- Start to calculate len, which is the length corresponding to the max subarray sum.\r\n -- func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)\r\n -- where\r\n -- (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)\r\n -- (ev, ei) = if sv > endV then (sv, i) else (endV, endI)\r\n\r\n -- (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a\r\n -- len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans\r\n -- End calculating. If don't want to calculate it, set len = 0, and replace maxByLen.\r\n len = 0\r\n maxByLen = scanr max (prefixSums ! n) (0:rsByLen)\r\n prefixSums = listArray (0, n) $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]\r\n\r\n -- maxByLen\r\n -- | len == n = replicate (len + 1) maxV\r\n -- | otherwise = replicate (len + 1) maxV ++ scanr max (prefixSums ! n) rsByLen\r\n\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)\r\n where\r\n (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)\r\n (ev, ei) = if sv > endV then (sv, i) else (endV, endI)\r\n\r\n (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a\r\n len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans\r\n\r\n prefixSums = listArray (0, n) $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]\r\n\r\n maxByLen\r\n | len == n = replicate (len + 1) maxV\r\n | otherwise = replicate (len + 1) maxV ++ scanr max (prefixSums ! n) rsByLen\r\n\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let prefixSums = listArray (0, n) $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [1 .. n -1]]\r\n xwides = zipWith (+) (scanr max (prefixSums ! n) (0 : rsByLen)) [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "\r\nimport Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n \r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let prefixSums = listArray (0,n) $ scanl (+) 0 a\r\n \r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [1 .. n]]\r\n xwides = zipWith (+) (scanr1 max (0:rsByLen)) [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n \r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n \r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n \r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let prefixSums = listArray (0,n) $ scanl (+) 0 a\r\n \r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [0 .. n]]\r\n xwides = zipWith (+) (scanr1 max rsByLen) [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n x <- getInt\n a <- replicateM n getInt\n let\n prefixSums :: UArray Int Int\n prefixSums = listArray (0, n) $ scanl' (+) 0 a\n\n rsByLen :: UArray Int Int\n -- range sums\n rsByLen = accumArray max minBound (0, n) $ do\n (i, psi) <- assocs prefixSums\n j <- [i .. n]\n pure (j - i, prefixSums ! j - psi)\n\n xwides = zipWith (+) (scanr1 max $ elems rsByLen) [0, x ..]\n xnarrows = scanl1 max $ zipWith (+) (elems rsByLen) [0, x ..]\n pure $ putInts $ zipWith max xwides xnarrows\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n x <- getInt\n a <- replicateM n getInt\n let\n ps = listArray (0, n) $ scanl' (+) 0 a\n xps = array (0, n) [(i, psi + x * i) | (i, psi) <- assocs ps]\n\n ack :: UArray Int Int -> UArray Int Int\n ack arr = accumArray max minBound (0, n) $ do\n (i, ai) <- assocs arr\n j <- [i .. n]\n pure (j - i, arr ! j - ai)\n\n narrows = ack xps\n wides = ack ps\n\n xwides = zipWith (+) (scanr1 max $ elems wides) [0, x ..]\n xnarrows = scanl1 max $ elems narrows\n pure $ putInts $ zipWith max xwides xnarrows\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, x] <- readInts\r\n a <- listArray @UArray (1, n) <$> readInts\r\n dp <- newArray @IOUArray ((0, 0), (n, n)) 0\r\n forM_ [1..n] $ \\i ->\r\n forM_ [0..n] $ \\j -> do\r\n nox <- (a!i +) . max 0 <$> readArray dp (i - 1, j)\r\n writeArray dp (i, j) =<< if j == 0 then pure nox else do\r\n yesx <- (a!i + x +) . max 0 <$> readArray dp (i - 1, j - 1)\r\n pure $ max nox yesx\r\n dp <- unsafeFreeze @_ @_ @_ @_ @UArray dp\r\n putStrLn $ unwords $ map (show . foldl' max 0) [[dp!(i, j) | i <- [0..n]] | j <- [0..n]]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "-- problem: https://codeforces.com/contest/1644/problem/C\r\n-- origin: https://codeforces.com/contest/1644/submission/147353835\r\n\r\nimport Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let -- Start to calculate len, which is the length corresponding to the max subarray sum.\r\n -- func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)\r\n -- where\r\n -- (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)\r\n -- (ev, ei) = if sv > endV then (sv, i) else (endV, endI)\r\n\r\n -- (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a\r\n -- len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans\r\n -- End calculating. If don't want to calculate it, set len = 0, maxV = 0.\r\n len = 0\r\n maxV = 0\r\n prefixSums = listArray (0, n) $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]\r\n\r\n maxByLen\r\n | len == n = replicate (len + 1) maxV\r\n | otherwise = replicate (len + 1) maxV ++ scanr max (prefixSums ! n) rsByLen\r\n\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)\r\n where\r\n (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)\r\n (ev, ei) = if sv > endV then (sv, i) else (endV, endI)\r\n\r\n (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a\r\n len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans\r\n\r\n prefixSums = listArray (0, n) $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j]] | j <- [len + 1 .. n - 1]]\r\n\r\n maxByLen = replicate (len + 1) maxV ++ if null rsByLen then [] else scanr max (prefixSums ! n) rsByLen\r\n\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)\r\n where\r\n (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)\r\n (ev, ei) = if sv > endV then (sv, i) else (endV, endI)\r\n\r\n (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ zip [0 ..] a\r\n len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans\r\n\r\n prefixSums = listArray (0, n - 1) $ tail $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j - 1]] | j <- [len + 1 .. n - 1]]\r\n\r\n maxByLen = replicate (len + 1) maxV ++ if null rsByLen then [] else scanr max (prefixSums ! (n - 1)) rsByLen\r\n\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n xnarrows = scanl1 max $ zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ zipWith max xwides xnarrows\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let prefixSums = listArray (0, n - 1) $ tail $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j - 1]] | j <- [1 .. n - 1]]\r\n\r\n xwides = zipWith (+) (scanr max (prefixSums ! (n - 1)) (0 : rsByLen)) [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Array (assocs, listArray, (!))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let ia = listArray (0, n -1) a\r\n func (startV, startI, endV, endI) (i, v) = (sv, si, ev, ei)\r\n where\r\n (sv, si) = if startV < 0 then (v, i) else (startV + v, startI)\r\n (ev, ei) = if sv > endV then (sv, i) else (endV, endI)\r\n\r\n (startV, startI, maxV, endI) = foldl func (0, 0, 0, -1) $ assocs ia\r\n len = let ans = endI - startI + 1 in if ans <= 0 then 0 else ans\r\n\r\n prefixSums = listArray (0, n - 1) $ tail $ scanl (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums ! (i + j) - prefixSums ! i | i <- [0 .. n - j - 1]] | j <- [len + 1 .. n - 1]]\r\n\r\n maxByLen = replicate (len + 1) maxV ++ if null rsByLen then [] else scanr max (prefixSums ! (n - 1)) rsByLen\r\n\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let mark :: [Int] -> [Int] -> Int -> Int -> Int -> Int -> Int -> ([Int], Int, Int)\r\n mark [] prefixSums i startV startI endV endI = (tail prefixSums, endV, let ans = endI - startI + 1 in if ans <= 0 then 0 else ans)\r\n mark (li : ls) prefixSums i startV startI endV endI = mark ls pre (i + 1) sv si ev ei\r\n where\r\n pre = prefixSums ++ [last prefixSums + li]\r\n modifyStart = startV < 0\r\n sv = if modifyStart then li else startV + li\r\n si = if modifyStart then i else startI\r\n modifyEnd = sv > endV\r\n ev = if modifyEnd then sv else endV\r\n ei = if modifyEnd then i else endI\r\n\r\n (prefixSums, maxV, len) = mark a [0] 0 0 0 0 (-1)\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums !! (i + j) - prefixSums !! i | i <- [0 .. n - j - 1]] | j <- [len + 1 .. n - 1]]\r\n\r\n maxByLen = replicate (len + 1) maxV ++ scanr max (prefixSums !! (n - 1)) rsByLen\r\n xwides = zipWith (+) maxByLen [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (isDigit, isSpace)\r\nimport Data.List (scanl')\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n x <- getInt\r\n a <- replicateM n getInt\r\n let prefixSums :: [Int]\r\n prefixSums = scanl' (+) 0 a\r\n\r\n rsByLen :: [Int] -- range sums\r\n rsByLen = [maximum [prefixSums !! (i + (n - j)) - prefixSums !! i | i <- [0 .. j]] | j <- [0 .. n]]\r\n -- i is the index of the start of the range, (n - j) equals to the interval\r\n -- so that we get xwides using scanl1 instead of scanr1\r\n xwides = zipWith (+) (scanl1 max rsByLen) [0, x ..]\r\n pure $ putInts $ scanl1 max xwides\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isInt . dropWhile isSpace)\r\n where\r\n isInt c = isDigit c || (c == '-')\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts x = unwords (map show x) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n a' = zipWith (+) a (replicate k x)\r\n res 0 = (v1, v2)\r\n\t where \r\n\t v1 = (0 : scanl1 (\\x y -> maximum' [0, x + y]) a)\r\n\t\tv2 = (maximum' v1 : [])\r\n res n = (v1, v2)\r\n\t where\r\n\t v1 = (0 : zipWith (\\a b -> maximum' [a, a + b]) a' (fst prev))\r\n\t\tv2 = (maximum' (0:v1) : snd prev)\r\n\t\tprev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse answer) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n \r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n a' = zipWith (+) a (replicate k x)\r\n res 0 = (v1, v2)\r\n\t where \r\n\t v1 = scanl (\\x y -> maximum' [0, x + y]) 0 a \r\n\t\tv2 = (maximum' v1 : [])\r\n res n = (v1, v2)\r\n\t where\r\n\t v1 = zipWith (\\a b -> maximum' [a, a + b]) a' (fst prev)\r\n\t\tv2 = (maximum' (0:v1) : snd prev)\r\n\t\tprev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse answer) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n \r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n res 0 = (v1, v2)\r\n\t where \r\n\t v1 = scanl1 (\\x y -> maximum' [0, x + y]) a \r\n\t\tv2 = (maximum' (0:v1) : [])\r\n res n = (v1, v2)\r\n\t where\r\n\t v1 = zipWith (\\a b -> maximum' [a + x, b + x + a]) a (0 : fst prev)\r\n\t\tv2 = (maximum' (0:v1) : snd prev)\r\n\t\tprev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse answer) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n \r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n res 0 = (v1, v2)\r\n\t where \r\n\t v1 = scanl1 (\\x y -> maximum' [0, x + y]) a \r\n\t\tv2 = (maximum' (0:v1) : [])\r\n res n = (v1, v2)\r\n\t where\r\n\t v1 = zipWith (\\a b -> a + x + maximum' [0, b]) a (0 : fst prev)\r\n\t\tv2 = (maximum' (0:v1) : snd prev)\r\n\t\tprev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse answer) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n \r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n res 0 = (v1, v2)\r\n\t where \r\n\t v1 = drop 1 $ scanl (\\x y -> maximum' [0, x + y]) 0 a \r\n\t\tv2 = (maximum' v1 : [])\r\n res n = (v1, v2)\r\n\t where\r\n\t v1 = zipWith (\\a b -> maximum' [a + x, b + x + a]) a (0 : fst prev)\r\n\t\tv2 = (maximum' v1 : snd prev)\r\n\t\tprev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse answer) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n \r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\r\n\r\nimport Control.Monad (\r\n MonadPlus (mplus),\r\n foldM_,\r\n forM_,\r\n guard,\r\n join,\r\n replicateM,\r\n replicateM_,\r\n )\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n--maximum' a = maximum a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n res 0 = (v1, v2)\r\n where \r\n v1 = scanl1 (\\x y -> maximum' [0, x + y]) a \r\n v2 = (maximum' (0 : v1) : [])\r\n res n = (v1, v2)\r\n where\r\n v1 = zipWith (\\a b -> maximum' [0, a + x + b]) a (0 : fst prev)\r\n v2 = (maximum' v1 : snd prev)\r\n prev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n forM_ (reverse (sol a n x)) $ \\p -> printf \"%d \" p\r\n printf \"\\n\"\r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE CPP, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\nimport Control.Monad (replicateM_, replicateM)\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Data.Monoid as M\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.Bits\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\nmaximum' a = L.foldl1' max a\r\n\r\nsol a k x = snd (res k)\r\n where\r\n res 0 = (v1, v2)\r\n\t where \r\n\t v1 = drop 1 $ scanl (\\x y -> maximum' [0, x + y]) 0 a \r\n\t\tv2 = (maximum' v1 : [])\r\n res n = (v1, v2)\r\n\t where\r\n\t v1 = zipWith (\\a b -> maximum' [a + x, b + x + a]) a (0 : fst prev)\r\n\t\tv2 = (maximum' v1 : snd prev)\r\n\t\tprev = res (n - 1)\r\n\r\n\r\nsolve :: IO()\r\nsolve = do\r\n [n, x] <- B8.getLine <&> readIntB8s\r\n a <- B8.getLine <&> readIntB8s\r\n let answer = sol a n x\r\n M.forM_ (reverse answer) $ \\p -> printf \"%lld \" p\r\n printf \"\\n\"\r\n\r\nmain :: IO()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t solve\r\n"}], "src_uid": "a5927e1883fbd5e5098a8454f6f6631f"} {"source_code": "import Data.Char\nsolve ::(Char -> Char) -> [Char] -> [Char]\nsolve f (x:xs)\n |f x > x = (f x): (solve' f xs) \n |otherwise = x : (solve f xs)\nsolve f x = []\n\nsolve' ::(Char -> Char) -> [Char] -> [Char]\nsolve' f (x:xs)\n |f x < x = x:xs \n |otherwise =(f x) : (solve' f xs)\nsolve' f x = []\n\nmakeF :: String -> (Char -> Char)\nmakeF s c = s!!(2*(c'-1))\n\twhere c' = digitToInt c\n\nmain = do\n n <- getLine\n s <- getLine\n fs <- getLine\n putStrLn $ solve (makeF fs) s\n \n\t", "positive_code": [{"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Char\nimport Data.List\nimport Data.Monoid\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as C\nimport System.IO\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [C.ByteString] -> Builder\nsolve (sn:z:a) = (mconcat $ map intDec $ l1 ++ (map (f UA.!) l2) ++ l3) <> char7 '\\n'\n where\n !n = ru sn\n f = UA.listArray (1, 9) $ map ru $ take 9 a :: UA.UArray Int Int\n x = map (subtract 48 . ord) $ C.unpack z\n (l1, l0) = span (\\ !i -> f UA.! i <= i) x\n (l2, l3) = span (\\ !i -> f UA.! i >= i) l0\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n"}], "negative_code": [{"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Char\nimport Data.List\nimport Data.Monoid\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as C\nimport System.IO\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [C.ByteString] -> Builder\nsolve (sn:z:a) = (mconcat $ map intDec $ l1 ++ (map (f UA.!) l2) ++ l3) <> char7 '\\n'\n where\n !n = ru sn\n f = UA.listArray (1, 9) $ map ru $ take 9 a :: UA.UArray Int Int\n x = map (subtract 48 . ord) $ C.unpack z\n (l1, l0) = span (\\ !i -> f UA.! i < i) x\n (l2, l3) = span (\\ !i -> f UA.! i >= i) l0\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n"}], "src_uid": "378a9ab7ad891d60f23645106d24f314"} {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = print =<< solve <$> readLn <*> (map read <$> words <$> getLine)\n\nsolve :: Int -> [Int] -> Int\nsolve _ as | null r = 0\n | all (uncurry (<=)) (tail r) && snd (last r) <= head as = length r\n | otherwise = -1\n where r = dropWhile (uncurry (<=)) (zip as (tail as))\n", "positive_code": [{"source_code": "s l=case filter((<0).snd).zip [1..]$zipWith(-)(tail$cycle l)l of\n []->0\n [(i,_)]->length l-i\n _-> -1\nmain=interact$show.s.tail.map read.words\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = \n\t\tlet (rs, lm) = splitList xs 0\n\t \t lr = length rs\n\t\tin if (sort rs == rs && (lr == 0 || last rs <= head xs)) then lr else -1\n\nsplitList :: [Int] -> Int -> ([Int], Int)\nsplitList [] t = ([], t)\nsplitList (x:rs) t \n\t| t > x = (x:rs, t)\n\t| otherwise = splitList rs x\n\n"}, {"source_code": "solve (n:xs) = case breakPoints of\n [] -> 0\n [(i, (_, _))] -> n - i\n _ -> (-1)\n where ys = cycle xs\n breakPoints = filter isBreakPoint $ take n $ zip [1 ..] $ zip ys $ tail ys\n isBreakPoint (_, (x, y)) = x > y\n\nmain = interact $ show . solve . map read . words\n"}, {"source_code": "\ngroupBy' :: (a -> a -> Bool) -> [a] -> [[a]]\ngroupBy' _ [] = []\ngroupBy' eq (x:xs) = (x:ys) : groupBy' eq zs\n where \n (ys, zs) = aux x xs\n aux x0 (x:xs) \n | eq x0 x = (x:ys, zs)\n where (ys, zs) = aux x xs\n aux x0 xs = ([], xs)\n\nsolve :: [Int] -> Int\nsolve xs\n | length g == 1 = 0\n | length g == 2 && (head xs >= last xs) = length $ g!!1\n | otherwise = -1\n where\n g = groupBy' (<=) xs\n\nmain = do\n getLine\n dat <- getLine\n print $ solve $ map read $ words dat\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) \n\t| xs == sort xs = 0\n\t| otherwise = \n\t\tlet (ls, rs) = break (== (minimum xs)) xs\n\t \t lr = length rs\n\t\tin if (sort rs == rs && sort ls == ls && maximum rs < maximum ls) then lr else -1\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = \n\t\tlet (rs, lm) = splitList xs 0\n\t \t lr = length rs\n\t\tin if (sort rs == rs && (lr == 0 || maximum rs <= lm)) then lr else -1\n\nsplitList :: [Int] -> Int -> ([Int], Int)\nsplitList [] t = ([], t)\nsplitList (x:rs) t \n\t| t > x = (x:rs, t)\n\t| otherwise = splitList rs x\n\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = \n\tlet (ls, rs) = break (==1) xs\n\t lr = length rs\n\tin if ([1 .. lr] == rs && [lr + 1 .. n] == ls) then mod lr n else -1\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) \n\t| xs == sort xs = 0\n\t| otherwise = \n\t\tlet (ls, rs) = break (== (minimum xs)) xs\n\t \t lr = length rs\n\t\tin if (sort rs == rs && sort ls == ls && maximum rs <= maximum ls) then lr else -1\n"}, {"source_code": "solve (n:xs) = case breakPoints of\n [] -> 0\n [(i, (_, _))] -> n - i\n _ -> (-1)\n where breakPoints = filter isBreakPoint $ zip [1 ..] $ zip xs $ tail xs\n isBreakPoint (_, (x, y)) = x > y\n\nmain = interact $ show . solve . map read . words\n"}], "src_uid": "c647e36495fb931ac72702a12c6bfe58"} {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\n\ntype Long = Integer\n\nkth :: Long -> Long -> Long\nkth 1 a = a\nkth k a\n | mind == 0 = a\n | otherwise = kth (k-1) (a + mind*maxd)\n where\n chars = show a\n mind = read $ minimum chars :\"\"\n maxd = read $ maximum chars :\"\"\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (a1:k:_) <- readWords\n print $ kth k a1\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t test\n\ntest = do\n (a:k:_) <- map read . words <$> getLine\n let as = f a\n ak =\n if k - 1 >= toInteger (length as)\n then last as\n else as !! (fromInteger k - 1)\n print ak\n\nf a\n | '0' `elem` ds = [a]\n | otherwise = a : f (a + read [minimum ds] * read [maximum ds])\n where\n ds = show a"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a1, k] <- readIs\n print $ solve a1 k\n\nreadIs :: IO [Integer]\nreadIs = fmap read . words <$> getLine\n\ndTI :: Char -> Integer\ndTI c = fromIntegral $ ord c - ord '0'\n\nmaxDigit, minDigit :: Integer -> Integer\nmaxDigit = dTI . maximum . show\nminDigit = dTI . minimum . show\n\nsolve :: Integer -> Integer -> Integer\nsolve a 1 = a\nsolve a k | '0' `elem` show a = a\nsolve a k =\n solve (a + maxDigit a * minDigit a) (k-1)\n"}, {"source_code": "import Control.Monad\n\nsolve :: Integer -> (Integer -> Integer)\nsolve x\n | x == 1 = id\n | otherwise = \\y -> let res = solve (x-1) y in\n res + (minDigit res) * (maxDigit res)\n\nminDigit :: Integer -> Integer\nminDigit x \n | x >= 10 = min (minDigit (x `div` 10)) (x `mod` 10)\n | otherwise = (x `mod` 10)\n\nmaxDigit :: Integer -> Integer\nmaxDigit x \n | x >= 10 = max (maxDigit (x `div` 10)) (x `mod` 10)\n | otherwise = (x `mod` 10)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n (a:k:_) <- map read . words <$> getLine\n print (solve (min k 1000) a)"}], "negative_code": [], "src_uid": "7a48218582b90f735a09083df9e15b96"} {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep (x:y:xs) = (x,y):(sep xs)\n\nparse (x,y) = (read $ dropWhile (/= ' ') x, map f y)\n where f 'B' = 0\n f 'W' = 1\n\nformat = show\n\nsolve (k,cs) = minimum $ scanl f init $ zip cs t\n where (h,t) = splitAt k cs\n init = sum h\n f s (l,r) = s + r - l\n", "positive_code": [{"source_code": "cnt' :: (Int, Bool) -> String -> [(Int, Bool)]\r\ncnt' tup [] = [tup]\r\ncnt' tup (x : xs) = [tup] ++ cnt' tupNew xs\r\n where\r\n (cntPrev, _) = tup\r\n isB = (x == 'B')\r\n tupNew = (cntPrev + (if (isB) then 1 else 0), isB)\r\n \r\ncnt :: String -> [(Int, Bool)]\r\ncnt s = cnt' fstTup rest\r\n where\r\n fstTup = if (head s == 'B') then (1, True) else (0, False)\r\n rest = tail s\r\n \r\nans :: IO Int\r\nans = do\r\n nkInput <- getLine\r\n s <- getLine\r\n let [n, k] = [read x :: Int | x <- words nkInput]\r\n let tups = cnt s\r\n let tupsStart = take (n - (k - 1)) tups\r\n let tupsEnd = drop (k - 1) tups\r\n let counts = [(fst $ snd x) - (fst $ fst x) + (if (snd $ fst x) then 1 else 0) | x <- zip tupsStart tupsEnd]\r\n let recolor = k - maximum counts\r\n return $ recolor\r\n \r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines [show x | x <- results]"}], "negative_code": [{"source_code": "import Data.Int\r\n\r\ncnt' :: [(Int32, Bool)] -> String -> [(Int32, Bool)]\r\ncnt' tups [] = tups\r\ncnt' tups (x : xs) = cnt' tupsNew xs\r\n where\r\n (cntPrev, _) = last tups\r\n isB = (x == 'B')\r\n tup = (cntPrev + (if (isB) then 1 else 0), isB)\r\n tupsNew = tups ++ [tup]\r\n\r\ncnt :: String -> [(Int32, Bool)]\r\ncnt s = cnt' [fstTup] rest\r\n where\r\n fstTup = if (head s == 'B') then (1, True) else (0, False)\r\n rest = tail s\r\n\r\nans :: IO Int32\r\nans = do\r\n nkInput <- getLine\r\n s <- getLine\r\n let [n, k] = [read x :: Int | x <- words nkInput]\r\n let tups = cnt s\r\n let tupsStart = take (n - (k - 1)) tups\r\n let firstsEnd = [fst x | x <- drop (k - 1) tups]\r\n if (n == 200000) then do\r\n return (-1)\r\n else do\r\n let counts = [(snd x) - (fst $ fst x) + (if (snd $ fst x) then 1 else 0) | x <- zip tupsStart firstsEnd]\r\n let recolor = (fromIntegral (k :: Int) :: Int32) - maximum counts\r\n return $ recolor\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines [show x | x <- results]"}], "src_uid": "6e3bacbe61775883599989d0f61367d5"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport qualified Data.IntMap as M\n\nthr :: (a, b, c) -> c\nthr (_, _, c) = c\n\nsolve :: Int -> [Int] -> [(Int, Int)]\nsolve n cs = inflate 1 segs\n where (_, _, segs) = foldr update (M.empty, n + 1, []) $ zip [1..] cs\n update (i, color) (colors, p, segs)\n | M.member color colors = if j >= p\n then (M.insert color i colors, p, segs)\n else (M.delete color colors, i, (i, j):segs)\n | otherwise = (M.insert color i colors, p, segs)\n where j = colors M.! color\n\n inflate i [] = []\n inflate i [(a, b)] = [(i, n)]\n inflate i ((a, b):xs) = (i, b):(inflate (b + 1) xs)\n\ntype Tokenizer = State [Int]\n\nparseInt :: L.ByteString -> Int\nparseInt = fst . fromJust . L.readInt\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> (s, ss)\n\ngo :: Tokenizer [(Int, Int)]\ngo = do\n n <- nextInt\n cs <- replicateM n nextInt\n return $ solve n cs\n\nmain :: IO ()\nmain = do\n input <- liftM (map parseInt . L.words) L.getContents\n let result = evalState go input\n if null result\n then print (-1)\n else do print $ length result\n putStr . unlines $ map (\\(a, b) -> (show a) ++ \" \" ++ (show b)) result \n", "positive_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad (forM_)\nimport Data.Set (empty, member, insert)\n\nmain :: IO ()\nmain = do\n n <- read @ Int <$> getLine\n pearls <- fmap (read @ Int) . words <$> getLine\n let answer = endpoints . splitPearls $ pearls\n if null answer\n then putStrLn \"-1\"\n else do\n print $ length answer\n forM_ answer $ \\(x, y) -> putStrLn (show x ++ \" \" ++ show y)\n\nendpoints :: [Int] -> [(Int, Int)]\nendpoints lengths = zip starts cumsum\n where\n cumsum = scanl1 (+) lengths\n starts = fmap succ $ zipWith (-) cumsum lengths\n\nsplitPearls :: [Int] -> [Int]\nsplitPearls pearls = reverse $ process pearls [] 0 empty\n where\n process [] accum cur _ | null accum = []\n | otherwise = let (a:acc) = accum in (cur + a) : acc\n\n process (x:xs) accum cur s | x `member` s = process xs (succ cur : accum) 0 empty\n | otherwise = process xs accum (succ cur) (insert x s)\n"}, {"source_code": "import Data.ByteString.Char8 (words, readInt, getLine)\nimport Prelude hiding (words, getLine)\nimport Data.Maybe (fromJust)\nimport Data.List (groupBy, sort, sortBy)\nimport Data.Ord (comparing)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n n <- readLn\n as <- (map readInt' . words) `fmap` getLine\n\n let\n rs = sortBy (comparing (\\(x, y) -> (y, x))). concat . map (f . map snd) $ groupBy (\\a b -> fst a == fst b) $ sort $ zip as [1..]\n where\n f l = zip l (tail l)\n\n find a [] = a\n find [] ((x,y):rs) = find [(1, y)] rs\n find ss@(s@(x1, y1):_) (r@(x2, y2):rs)\n | x2 > y1 = find ((y1+1, y2):ss) rs\n | otherwise = find ss rs\n\n a = find [] rs\n\n fix ((a,b):rs) = reverse $ (a,n):rs\n\n -- print rs\n if null a\n then print $ -1\n else do\n print $ length a\n putStr $ unlines $ map (\\(x, y) -> show x ++ \" \" ++ show y) $ fix a\n\n"}], "negative_code": [], "src_uid": "4cacec219e4577b255ddf6d39d308e10"} {"source_code": "main = interact solve\nsolve input = output where\n inputs = lines input\n [n, m] = map (read:: String -> Int ) $ words $ head inputs\n output = show $ if mini > maxi then -1 else maxi - mini + 1\n (mini, maxi) = answer (1, n) (tail inputs)\nanswer (mini, maxi) [] = (mini, maxi)\nanswer (mini, maxi) (x:xs) = answer (mini', maxi') xs\n where\n left = x' !! 2 == \"left\"\n num = read (x' !! 4) :: Int\n x' = words x\n (mini', maxi') = if left then (mini, min maxi (num-1))\n else (max mini (num+1), maxi)\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, m] <- ( map read . words ) `liftM` getLine\n (b, e) <- foldM (\\(b,e) _ -> do\n ws <- words `liftM` getLine\n let dir = ws !! 2\n pivot = read ( ws !! 4 )\n return $ if head dir == 'l'\n then (b, min e (pivot-1))\n else (max b (pivot+1), e)\n ) (1,n) [1..m]\n\n putStrLn $ show $ if b <= e\n then e - b + 1\n else -1\n"}, {"source_code": "main = do\n\ts <- getLine\n\tlet [n, m] = map read (words s)\n\tans <- solve m (1, n)\n\tprint (if fst ans > snd ans then -1 else snd ans - fst ans + 1)\nsolve 0 sp = return sp\nsolve m sp = do\n\ts <- getLine\n\tlet ss = words s\n\tlet f = if ss !! 2 == \"left\" \n\t\tthen (fst sp, min (snd sp) (read (ss !! 4) - 1)) \n\t\telse (max (fst sp) (read (ss !! 4) + 1), snd sp)\n\tif m == 1 then return f else solve (m - 1) f"}, {"source_code": "type Interval = (Int, Int)\ntype Rule = Either Int Int\n\nparseLine :: String -> Rule\nparseLine line\n | word3 == \"left\" = Left (read word5)\n | word3 == \"right\" = Right (read word5)\n | otherwise = error \"Nevernaya stroka!\"\n where\n word3 = (words line) !! 2\n word5 = (words line) !! 4\n\napplyRule :: Interval -> Rule -> Interval\napplyRule (a, b) = either (\\x -> (a, min b x)) (\\x -> (max a x, b))\n\napplyRules :: Interval -> [Rule] -> Interval\napplyRules (a, b) rules = foldl applyRule (a,b) rules\n\nprintAns :: Interval -> IO ()\nprintAns (a, b) = do\n let ans = b - a - 1\n if ans > 0 then print ans else print (-1)\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, m] = map read (words line)\n lines <- sequence (map (\\x -> getLine) [1..m])\n let rules = map parseLine lines\n let ans = applyRules (0, n + 1) rules\n printAns ans"}, {"source_code": "import Data.List\nmain=interact$show.f.map words.lines\nf([n,_]:s)=g$(snd$minimum l)-(snd$maximum r)-1 where (r,l)=partition fst$(1<0,read n+1):(1>0,0):map p s\np[_,_,'l':_,_,x]=(1<0,read x)\np x=(1>0,read$last x)\ng x|x>0=x|1>0=(-1)"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nbr s = let s' = words s in (s' !! 2, read (s' !! 4))\ncheck (minS, maxS) (\"left\", s) = (minS, min maxS s)\ncheck (minS, maxS) (\"right\", s) = (max minS s, maxS)\nmain = do\n [n, m] <- map read `fmap` (words `fmap` getLine)\n l <- mapM (\\_ -> getLine >>= (return . br)) [1..m]\n let (minS, maxS) = foldl check (0, n+1) l\n when (minS >= maxS-1) (putStr \"-1\")\n when (minS < maxS - 1) (putStr $ show (maxS - minS -1))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n (s1:s2:_) <- words <$> getLine\n let n = read s2 ::Int\n let m = read s1 ::Int\n rules <- forM [1..n] (\\_ -> do\n ln <- words <$> getLine\n let bound = read (last ln) ::Int\n let rule = if elem \"right\" ln then (>bound) else ( and $ rules <*> [x]) [1..m]\n let resf = if res == 0 then -1 else res\n putStr $ show resf"}, {"source_code": "module Main where\n\nimport Data.List\n\ngetLines :: Integer -> IO [String]\ngetLines 0 = return [\"\"]\ngetLines n = do\n\tcurrentLine <- getLine\n\tlines <- getLines (n - 1)\n\treturn (currentLine : lines)\n\nreadInt :: String -> Integer\nreadInt = read\n\nreadIntList :: String -> [Integer]\nreadIntList input = map readInt inputList\n\twhere inputList = words input\n\n-- receives a sentence\n-- returns an integer that is at the end of the sentence\ngetIntFromLine :: String -> Integer\ngetIntFromLine line = readInt (last inputWords)\n\twhere inputWords = words line\n\ngetIntsFromLines :: [String] -> [Integer]\ngetIntsFromLines lines = map getIntFromLine lines\n\ncalculateBoxesToCheck :: Integer -> ([String], [String]) -> Integer\ncalculateBoxesToCheck n (leftIndexLines, rightIndexLines) = if boxesCount >= 1 then boxesCount else -1 where\n\tboxesCount = minimum (leftIndices ++ [n + 1]) - maximum (rightIndices ++ [0]) - 1 where\n\t\tleftIndices = getIntsFromLines leftIndexLines\n\t\trightIndices = getIntsFromLines rightIndexLines\n\nparseLines :: [String] -> ([String], [String])\nparseLines input = let\n\tleftIndices = filter (\"left\" `isInfixOf`) input\n\trightIndices = filter (\"right\" `isInfixOf`) input\n\tin (leftIndices, rightIndices)\n\nsolve :: Integer -> [String] -> Integer\nsolve n lines = calculateBoxesToCheck n (parseLines lines)\n\nmain = do\n\tline <- getLine\n\tlet [n, m] = readIntList(line)\n\tlines <- getLines m\n\tputStrLn (show(solve n lines))\n"}], "negative_code": [{"source_code": "import Data.List\nmain=interact$show.f.map words.lines\nf([n,_]:s)=max(-1)$(snd$minimum l)-(snd$maximum r)-1 where (r,l)=partition fst$(1<0,read n+1):(1>0,0):map p s\np[_,_,'l':_,_,x]=(1<0,read x)\np x=(1>0,read$last x)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n (s1:s2:_) <- words <$> getLine\n let n = read s2 ::Int\n let m = read s1 ::Int\n rules <- forM [1..n] (\\_ -> do\n ln <- words <$> getLine\n let bound = read (last ln) ::Int\n let rule = if elem \"right\" ln then (>bound) else ( or $ rules <*> [x]) [1..m]\n let resf = if res == 0 then -1 else res\n return resf"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n (s1:s2:_) <- words <$> getLine\n let n = read s2 ::Int\n let m = read s1 ::Int\n rules <- forM [1..n] (\\_ -> do\n ln <- words <$> getLine\n let bound = read (last ln) ::Int\n let rule = if elem \"right\" ln then (>bound) else ( or $ rules <*> [x]) [1..m]\n let resf = if res == 0 then -1 else res\n putStr $ show resf"}], "src_uid": "dabeb9852332f6a6e730acab7fe61a5c"} {"source_code": "--ghc 7.10\n\nimport Data.List(findIndices)\n\nminExit xs = 1 + min (last is0) (last is1)\n where\n is0 = findIndices (==0) xs\n is1 = findIndices (==1) xs\n\nmain = do\n line1 <- getLine\n line2 <- getLine\n let xs = map read . words $ line2 :: [Int]\n print $ minExit xs", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >> readInts >>= print . sum . map length . init . group"}, {"source_code": "import Data.Maybe\nimport Data.List\n\nimport qualified Data.ByteString.Char8 as B\n\ngetInts = map (fst . fromJust . B.readInt) . B.words\n\nmain = getLine >> B.getLine >>= print . sum . map( length ) . init . group . getInts \n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve (n:a) = min (length b1) (length b2)\n where\n b = reverse $ take n a\n b1 = dropWhile (== 0) b\n b2 = dropWhile (== 1) b\n\nmain :: IO ()\nmain = print . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "main = interact $ show.helper.(map read).words\n\nhelper (x:xs) = x - max (length $ takeWhile (==1) sx) (length $ takeWhile (==0) sx) \n where sx = reverse xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.ByteString.Char8 as C\n\n\nmain = do\n\t\tgetLine\n\t\ta<-reverse <$> map (fst.fromJust.C.readInt) <$> C.words <$> C.getLine ::IO [Int]\n\t\tlet b= head a\n\t\tprint $ length $ dropWhile (==b) a\n\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.List\n\nimport qualified Data.ByteString.Char8 as B\n\ngetInts = map (fst . fromJust . B.readInt) . B.words\n\nmain = B.getLine >>= print . sum . map( length ) . init . group . getInts \n"}], "src_uid": "653455bb6762effbf7358d75660a7689"} {"source_code": "main :: IO ()\nmain = do\n n <- readLn :: IO Int\n [h1,h2,':',m1,m2] <- getLine\n let hh = read[h1, h2] :: Int\n let mm = read[m1, m2] :: Int\n let hh' = if n == 12 && 1<=hh && hh<=12 then [h1, h2]\n else if n == 12 && h2 == '0' then ['1', h2]\n else if n == 12 then ['0', h2]\n else if 0<=hh && hh<24 then [h1, h2]\n else ['0', h2]\n let mm' = if 0 <= mm && mm <60 then [m1,m2] else ['0',m2]\n putStrLn $ hh' ++ \":\" ++ mm'", "positive_code": [{"source_code": "main = interact $ f . words\nf [\"12\",[x,y,':',z,w]] = a x y ++ \":\" ++ c z w\nf [\"24\",[x,y,':',z,w]] = b x y ++ \":\" ++ c z w\n\na '0' x | '1' <= x && x <= '9' = ['0',x]\na '1' '0' = \"10\"\na '1' '1' = \"11\"\na '1' '2' = \"12\"\na '0' x = \"09\"\na '1' x = \"12\"\na x '0' = \"10\"\na x y | '1' <= y && y <= '9' = ['0',y]\na x y = \"12\"\n\nb '0' x | '0' <= x && x <= '9' = ['0',x]\nb '1' x | '0' <= x && x <= '9' = ['1',x]\nb '2' '0' = \"20\"\nb '2' '1' = \"21\"\nb '2' '2' = \"22\"\nb '2' '3' = \"23\"\nb '0' x = \"00\"\nb '1' x = \"10\"\nb '2' x = \"23\"\nb x y | '0' <= y && y <= '9' = ['0',y]\nb x y = \"23\"\n\nc x y | '0' <= x && x <= '5' && '0' <= y && y <= '9' = [x,y]\nc x y | '0' <= x && x <= '5' = [x,'0']\nc x y | '0' <= y && y <= '9' = ['0',y]\nc x y = \"00\""}], "negative_code": [], "src_uid": "88d56c1e3a7ffa94354ce0c70d8e958f"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n\r\nimport Control.Monad\r\nimport Data.Ratio\r\nimport Data.Function\r\nimport Data.Coerce\r\nimport Data.Array\r\n\r\nclass TypeMod a where\r\n modulo :: ModInt a\r\n\r\ndata MyMod = MyMod\r\ninstance TypeMod MyMod where\r\n modulo = Mod 998244353\r\n\r\nnewtype ModInt a = Mod Integer \r\n\r\ninstance Show (ModInt a) where\r\n show (Mod n) = show n\r\n\r\ninstance TypeMod a => Num (ModInt a) where\r\n\r\n Mod l + Mod r = Mod (mod (l + r) (coerce (modulo::ModInt a)))\r\n\r\n Mod l - Mod r = Mod (mod (l - r) (coerce (modulo::ModInt a)))\r\n\r\n Mod l * Mod r = Mod (mod (l * r) (coerce (modulo::ModInt a)))\r\n \r\n abs = id\r\n signum = const 1\r\n fromInteger n = Mod (mod n ((coerce (modulo::ModInt a))))\r\n\r\ninstance TypeMod a => Fractional (ModInt a) where\r\n recip = (^(((coerce(modulo::ModInt a)::Integer) - 2)))\r\n fromRational r = (fromInteger . numerator) r * (recip . fromInteger . denominator) r\r\n\r\nfac n = take (n+1) (iterate (\\(y,x) -> (y+1,x*fromInteger (y+1))) ((0,1)::(Integer,ModInt MyMod)))\r\n\r\n\r\n\r\ntoShow (x,y,z) = show x ++ \" \" ++ show y ++ \" \" ++ show z\r\n\r\nsolve _ 2 = (1,0,1)\r\nsolve arr n = let (x,y,z) = solve arr (n-2) in (y+(arr!(n-1)/(arr!(div n 2) * (arr!(div n 2-1)))),x+(arr!(n-2)/(arr!(div n 2) * (arr!(div n 2-2)))) ,z)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n let arr = array (0,n) (map (\\(x,y) -> (fromInteger x,y)) $ fac n)\r\n putStrLn .toShow .solve arr $ n\r\n return ()", "positive_code": [{"source_code": "import Data.Map (Map(..))\nimport qualified Data.Map as M\nimport Control.Monad (replicateM_)\n\np = 998244353\nmain = read <$> getLine >>=\n flip replicateM_ (scase (genGames 60 p))\n\nscase g = read <$> getLine >>=\n \\n -> case (g M.! n) of\n (a, b, c) -> putStrLn (show a ++ \" \" ++ show b ++ \" \" ++ show c)\n\n-- n is even > 4\ngenGames :: Int -> Int -> Map Int (Int, Int, Int)\ngenGames n p = let m = M.insert 2 (1, 0, 1) M.empty\n in foldl (f p) m [4, 6 .. n]\n \nf :: Int -> Map Int (Int, Int, Int) -> Int -> Map Int (Int, Int, Int)\nf p m n = let (a, b, c) = m M.! (n-2)\n n2 = div n 2\n in\n M.insert n ((b + comb (n-1) n2) `mod` p, (a + comb (n-2) n2) `mod` p, c) m\n\n-- n C m\ncomb :: Int -> Int -> Int\ncomb n m = c60 M.! (n, m)\n\nc60 :: Map (Int, Int) Int\nc60 = let m = M.insert (0, 0) 1 M.empty\n f m (n, k) | k == 0 || k == n = M.insert (n, k) 1 m\n | otherwise = M.insert (n, k)\n (m M.! (n-1, k-1) + m M.! (n-1, k)) m\n in\n foldl f m [(i, j) | i <- [1..60], j <- [0..i]]\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Map.Lazy qualified as Map\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStrLn.showAns.solve) tcs\r\n\r\nshowAns (a,b,c) = unwords . map show $ [a,b,c]\r\n\r\nsolve nn = f nn\r\n where\r\n c = ncomb\r\n\r\n f 2 = (1,0,1)\r\n f n = (c (n-1) (h-1) .+. b (n-2),\r\n c (n-2) (h-2) .+. a (n-2) ,\r\n c (n ) (h ) .-. a (n ) .-. b (n ))\r\n where\r\n h = n `div` 2\r\n\r\n a n = x where (x,_,_) = f n\r\n b n = x where (_,x,_) = f n\r\n\r\nncomb n k = cmap ! (n,k) where (!) = (Map.!)\r\ncmap = Map.fromList [((n,k), cc n k) | n <- nvals,\r\n k <- nvals]\r\n where\r\n cc n k | (k == 0) = 1 :: Int\r\n | (k == n) = 1\r\n | otherwise = ncomb (n-1) (k-1) .+. ncomb (n-1) k\r\nnvals = [0..60] :: [Int]\r\n\r\nmodVal = 998244353\r\n\r\nx .+. y = (x + y) `mod` modVal\r\nx .-. y = (x + modVal - y) `mod` modVal\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\n\ntype TC = Int\n\ntype Output = [Int]\n\ninput :: Scanner TC\ninput = int\n\nsolve :: TC -> Output\nsolve n = calc n ++ [1]\n\noutput :: Int -> Output -> C.ByteString\noutput _ = map showB >>> C.unwords\n\ncalc :: Int -> [Int]\ncalc 2 = [1, 0]\ncalc n = let h = n `div` 2 in zipWith (+%) [(n - 1) `choose` h, (n - 2) `choose` h] (reverse $ calc (n - 2))\n\nchoose' :: [[Int]]\nchoose' =\n [ [ if n < r\n then 0\n else\n if r == 0 || r == n\n then 1\n else (n - 1) `choose` r +% (n - 1) `choose` (r - 1)\n | r <- [0 .. 60]\n ]\n | n <- [0 .. 60]\n ]\n\nchoose n r = choose' !! n !! r\n\nmodulo = 998244353\n\na +% b = (a + b) `mod` modulo\ninfixl 4 +%\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- helpers\n(>$>) = flip ($)\n\ninfixl 0 >$>\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Data.Array.Base (UArray (UArray))\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n casnum <- getInt\r\n ans <- forM [1 .. casnum] $ \\_ -> do\r\n n <- getInt\r\n let m = div n 2\r\n let (w, l) = win !! m\r\n pure [w, l, 1]\r\n pure $ mconcat $ map putInts ans\r\n where\r\n win =\r\n map (\\(a, b, c) -> (b, c)) $\r\n take (maxM + 1) $\r\n iterate\r\n ( \\(i, w, l) ->\r\n (i + 1, l +! combine (2 * i + 1) i, w +! combine (2 * i) (i + 1))\r\n )\r\n (0, 0, 0)\r\n\r\nmaxN = 60\r\n\r\nmaxM = div maxN 2\r\n\r\nfacts :: UArray Int Int\r\nfacts = listArray (0, maxN) $ scanl' (*!) 1 [1 .. maxN]\r\n\r\nifacts :: UArray Int Int\r\nifacts = listArray (0, maxN) [inv (facts ! i) | i <- [0 .. maxN]]\r\n\r\ncombine :: Int -> Int -> Int\r\ncombine n m\r\n | n < m = 0\r\n | otherwise = (facts ! n) *! (ifacts ! m) *! (ifacts ! (n - m))\r\n\r\nmodulo :: Int\r\nmodulo = 998244353\r\n\r\ninfixl 6 +!\r\n\r\n(+!) :: Int -> Int -> Int\r\nx +! y = x + y -! modulo\r\n\r\ninfixl 6 -!\r\n\r\n(-!) :: Int -> Int -> Int\r\nx -! y =\r\n let raw = x - y\r\n in raw + (modulo .&. shiftR raw 63)\r\n\r\ninfixl 8 *!\r\n\r\n(*!) :: Int -> Int -> Int\r\nx *! y = mod (x * y) modulo\r\n-- let raw = mod (x * y) modulo\r\n-- in raw + (modulo .&. shiftR raw 63)\r\n\r\npow :: Int -> Int -> Int\r\npow =\r\n let -- I used to use stimes for this, but it seems that's 15x slower\r\n -- than just the hand-rolled loop, so no more is it used.\r\n go acc !x 0 = acc\r\n go !acc !x k =\r\n if even k\r\n then go acc (x *! x) (div k 2)\r\n else go (acc *! x) (x *! x) (div k 2)\r\n in go 1\r\n\r\ninv :: Int -> Int\r\ninv n = pow n (modulo - 2)\r\n\r\ntype SP = State P.ByteString\r\n\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs =\r\n let sepPrim =\r\n (,) ' '\r\n Prim.>$< Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Data.Array.Base (UArray (UArray))\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n casnum <- getInt\r\n ans <- forM [1 .. casnum] $ \\_ -> do\r\n n <- getInt\r\n let m = div n 2\r\n let (w, l) = win !! m\r\n pure [w, l, 1]\r\n pure $ mconcat $ map putInts ans\r\n where\r\n win =\r\n map (\\(a, b, c) -> (b, c)) $\r\n take (maxM + 1) $\r\n iterate\r\n ( \\(i, w, l) ->\r\n (i + 1, l +! combine (2 * i + 1) i, w +! combine (2 * i) (i + 1))\r\n )\r\n (0, 0, 0)\r\n\r\nmaxN = 60\r\n\r\nmaxM = div maxN 2\r\n\r\nfacts :: UArray Int Int\r\nfacts = listArray (0, maxN) $ scanl' (*) 1 [1 .. maxN]\r\n\r\nifacts :: UArray Int Int\r\nifacts = listArray (0, maxN) [inv (facts ! i) | i <- [0 .. maxN]]\r\n\r\ncombine :: Int -> Int -> Int\r\ncombine n m\r\n | n < m = 0\r\n | otherwise = (facts ! n) *! (ifacts ! m) *! (ifacts ! (n - m))\r\n\r\nmodulo :: Int\r\nmodulo = 998244353\r\n\r\ninfixl 6 +!\r\n\r\n(+!) :: Int -> Int -> Int\r\nx +! y = x + y -! modulo\r\n\r\ninfixl 6 -!\r\n\r\n(-!) :: Int -> Int -> Int\r\nx -! y =\r\n let raw = x - y\r\n in raw + (modulo .&. shiftR raw 63)\r\n\r\ninfixl 8 *!\r\n\r\n(*!) :: Int -> Int -> Int\r\nx *! y =mod (x * y) modulo\r\n-- let raw = mod (x * y) modulo\r\n-- in raw + (modulo .&. shiftR raw 63)\r\n\r\npow :: Int -> Int -> Int\r\npow =\r\n let -- I used to use stimes for this, but it seems that's 15x slower\r\n -- than just the hand-rolled loop, so no more is it used.\r\n go acc !x 0 = acc\r\n go !acc !x k =\r\n if even k\r\n then go acc (x *! x) (div k 2)\r\n else go (acc *! x) (x *! x) (div k 2)\r\n in go 1\r\n\r\ninv :: Int -> Int\r\ninv n = pow n (modulo - 2)\r\n\r\ntype SP = State P.ByteString\r\n\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs =\r\n let sepPrim =\r\n (,) ' '\r\n Prim.>$< Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp"}], "src_uid": "63fc2fb08d248f8ccdb3f5364c96dac1"} {"source_code": "import Data.List\nimport Control.Monad\n\ntoInt :: String -> Int\ntoInt x = read x :: Int\n\nsolve :: Int -> [Int] -> Int -> String\nsolve 0 xs w = show w\nsolve x xs w\n | head xs == 0 = solve (x - 1) (tail xs) (w + 1)\n | head xs == 1 && last xs == 2 = solve (x - 2) (init (tail xs)) (w + 1)\n | x >= 3 = solve (x - 3) (drop 3 xs) (w + 1)\n | otherwise = solve 0 xs w\n\n--subproblem :: IO ()\n--subproblem = do\n-- n <- getLine\n-- a <- getLine\n-- print $ solve (toInt n) (sort (map (`mod` 3) (map toInt (words a)))) 0\n\nfff :: String -> String\nfff x = unlines (process (tail (lines x)))\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess input = do\n let x = toInt (input !! 0)\n let xs = sort (map (`mod` 3) (map toInt (words (input !! 1))))\n (solve x xs 0 ++ \"\\n\") : process (drop 2 input)\n\n--printAll :: [String] -> IO()\n--printAll [] = print []\n--printAll x:xs = do\n \n\nmain :: IO()\nmain = interact fff\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\ntoInt :: String -> Int\ntoInt x = read x :: Int\n\nsolve :: Int -> [Int] -> Int -> Int\nsolve 0 xs w = w\nsolve x xs w\n | head xs == 0 = solve (x - 1) (tail xs) (w + 1)\n | head xs == 1 && last xs == 2 = solve (x - 2) (init (tail xs)) (w + 1)\n | x >= 3 = solve (x - 3) (drop 3 xs) (w + 1)\n | otherwise = solve 0 xs w\n\nsubproblem :: IO ()\nsubproblem = do\n n <- getLine\n a <- getLine\n print $ solve (toInt n) (sort (map (`mod` 3) (map toInt (words a)))) 0\n\nmain = do\n n <- getLine\n replicateM (toInt n) subproblem\n"}, {"source_code": "\ncalc :: [Int] -> Int\ncalc xs = let a = xs!!0\n b = xs!!1\n c = xs!!2\n in a + min b c + (div (max b c - min b c) 3)\n\ncount :: Int -> [Int] -> [Int]\ncount x cl\n | mod x 3 == 0 = [a + 1, b, c]\n | mod x 3 == 2 = [a, b + 1, c]\n | mod x 3 == 1 = [a, b, c + 1]\n | otherwise = cl\n where a = cl!!0\n b = cl!!1\n c = cl!!2\n\nsolve' :: [Int] -> [Int] -> Int -> Int -> [Int] -> [Int]\nsolve' (x:xs) cl n curr res\n | n == (curr - 1) = solve' xs [0,0,0] x 1 (res ++ [(calc cl)])\n | curr > 0 = solve' xs (count x cl) n (curr + 1) res\n | otherwise = solve' xs [0,0,0] x 1 res\n\nsolve' _ cl n curr res\n | cl == [0,0,0] = res\n | otherwise = (tail res) ++ [(calc cl)]\n\nsolve :: [Int] -> [Int]\nsolve xs = solve' xs [0,0,0] (-1) 0 []\n\nmain = interact $ unlines . map show . solve . map (read::String->Int) . tail . words"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int -> [Integer] -> Int\nsolve grp0 grp1 grp2 [] = grp0 + pairs + rest\n where pairs = min grp1 grp2\n rest = (grp1 - pairs) `div` 3 + (grp2 - pairs) `div` 3\nsolve grp0 grp1 grp2 (x:xs)\n | x `mod` 3 == 0 = solve (grp0 + 1) grp1 grp2 xs\n | x `mod` 3 == 1 = solve grp0 (grp1 + 1) grp2 xs\n | x `mod` 3 == 2 = solve grp0 grp1 (grp2 + 1) xs\n\nprocess :: Int -> [[Integer]] -> IO [[Integer]]\nprocess 0 result = return $ reverse result\nprocess counter result = do\n [_, queries] <- replicateM 2 $ map read . words <$> getLine\n process next (queries:result)\n where next = counter - 1\n\nmain :: IO ()\nmain = do\n n <- readLn\n result <- process n []\n mapM_ (print . solve 0 0 0) $ result"}], "negative_code": [{"source_code": "\ncalc :: [Int] -> Int\ncalc xs = let a = xs!!0\n b = xs!!1\n c = xs!!2\n in a + min b c + (div (max b c - min b c) 3)\n\ncount :: Int -> [Int] -> [Int]\ncount x cl\n | mod x 3 == 0 = [a + 1, b, c]\n | mod x 2 == 0 = [a, b + 1, c]\n | mod x 1 == 0 = [a, b, c + 1]\n | otherwise = cl\n where a = cl!!0\n b = cl!!1\n c = cl!!2\n\nsolve' :: [Int] -> [Int] -> Int -> Int -> [Int] -> [Int]\nsolve' (x:xs) cl n curr res\n | n == (curr - 1) = solve' xs [0,0,0] x 1 (res ++ [(calc cl)])\n | curr > 0 = solve' xs (count x cl) n (curr + 1) res\n | otherwise = solve' xs [0,0,0] x 1 res\n\nsolve' _ cl n curr res\n | cl == [0,0,0] = res\n | otherwise = (tail res) ++ [(calc cl)]\n\nsolve :: [Int] -> [Int]\nsolve xs = solve' xs [0,0,0] (-1) 0 []\n\nmain = interact $ unlines . map show . solve . map (read::String->Int) . tail . words"}, {"source_code": "\ncalc :: [Int] -> Int\ncalc xs = let a = xs!!0\n b = xs!!1\n c = xs!!2\n in a + max b c - min b c\n\ncount :: Int -> [Int] -> [Int]\ncount x cl\n | mod x 3 == 0 = [a + 1, b, c]\n | mod x 2 == 0 = [a, b + 1, c]\n | mod x 1 == 0 = [a, b, c + 1]\n | otherwise = cl\n where a = cl!!0\n b = cl!!1\n c = cl!!2\n\nsolve' :: [Int] -> [Int] -> Int -> Int -> [Int] -> [Int]\nsolve' (x:xs) cl n curr res\n | n == (curr - 1) = solve' xs [0,0,0] x 1 (res ++ [(calc cl)])\n | curr > 0 = solve' xs (count x cl) n (curr + 1) res\n | otherwise = solve' xs [0,0,0] x 1 res\n\nsolve' _ cl n curr res\n | cl == [0,0,0] = res\n | otherwise = (tail res) ++ [(calc cl)]\n\nsolve :: [Int] -> [Int]\nsolve xs = solve' xs [0,0,0] (-1) 0 []\n\nmain = interact $ unlines . map show . solve . map (read::String->Int) . tail . words"}], "src_uid": "e59cddb6c941b1d7556ee9c020701007"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified Data.Ratio as Rat\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nissuperior :: [Int] -> [Int] -> Bool\nissuperior xs ys = length (filter (==True) $ zipWith (<) xs ys) > div total 2\n where total = length xs\n\nsuperior :: [Int] -> [Int] -> [Int]\nsuperior xs ys = if issuperior xs ys then xs else ys\n\nwinner :: [[Int]] -> [Int]\nwinner [xs] = xs\nwinner xxs = winner $ [a] ++ b\n where (a,b) = foldl (\\(prev, acc) xs -> if null prev then (xs, acc) else ([], (superior xs prev : acc))) ([], []) xxs\n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n a <- readintrows n\n let best = winner a\n cnt = length $ filter (issuperior best) a\n bestidx = if cnt < n-1 then -1 else (fromMaybe 0 $ findIndex (==best) a) + 1\n in print bestidx\n \n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral b) => b -> IO [String]\nreadrows 0 = return []\nreadrows n = do\n row <- getLine\n l <- readrows $ n-1\n return (row : l)\n\n\nreadintrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadintrows 0 = return []\nreadintrows n = do\n row <- readInts\n l <- readintrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n", "positive_code": [{"source_code": "import Control.Monad (replicateM)\r\nimport Data.List ( elemIndex )\r\nimport Data.Maybe ( fromJust )\r\nimport Data.Function (on)\r\n\r\nmain :: IO [()]\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM t $ do\r\n n <- readLn :: IO Int\r\n z <- replicateM n $ do\r\n map read . words <$> getLine\r\n print $ solve z\r\n\r\nsolve :: (Ord a, Num a) => [[a]] -> Int\r\nsolve list = if best m then i else -1\r\n where\r\n (i, m) = foldl1 (\\a b -> if (better `on` snd) a b then a else b) $ zip [1..] list\r\n better a b = length (filter id $ zipWith (<=) a b) >= 3\r\n best a = all (better a) list"}, {"source_code": "import Control.Monad (replicateM)\r\nimport Data.List ( elemIndex )\r\nimport Data.Maybe ( fromJust )\r\nimport Data.Function (on)\r\n\r\nmain :: IO [()]\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM t $ do\r\n n <- readLn :: IO Int\r\n z <- replicateM n $ do\r\n map read . words <$> getLine\r\n print $ solve z\r\n\r\nsolve :: (Ord a, Num a) => [[a]] -> Int\r\nsolve list = if best m then i else -1\r\n where\r\n (i, m) = foldl1 (\\a b -> if (better `on` snd) a b then a else b) $ zip [1..] list\r\n better a b = length (filter id $ zipWith (<) a b) >= 3\r\n best a = length (filter id $ map (better a) list) == length list - 1"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nbetter :: Array Int (UArray Int Int) -> Int -> Int -> Int\nbetter arr x y = let\n gt = (!! 2) $ sort $ zipWith (<) (elems $ arr ! x) (elems $ arr ! y)\n in if gt then x else y\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n r <- listArray (1, n) <$> replicateM n (listArray (1, 5) <$> readInts)\n let\n opt = foldl' (better r) n $ [1 .. n] ++ [1 .. n]\n isOK = and [better r opt i == opt | i <- [1 .. n]]\n putInts [if isOK then opt else 0-1]\n \n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad\r\nimport Data.Function\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n r <- replicateM n readMany :: IO [[Int]]\r\n let sup a b = length (filter id $ zipWith (<) a b) >= 3\r\n allSup a = length (filter id $ map (sup a) r) == n - 1\r\n (i, m) = foldr1 (\\a b -> if (sup `on` snd) a b then a else b) $ zip [1..] r\r\n print $ if allSup m then i else -1\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE LambdaCase #-}\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust, fromMaybe)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = do\n n <- int\n xs <- n >< (5 >< int)\n return . show . fromMaybe (-1) . solve $ xs `zip` [1..]\n\nsolve :: [([Int], Int)] -> Maybe Int\nsolve xs\n | all (win cs . fst) xs = Just i\n | otherwise = Nothing\n where\n (cs, i) = foldl1 better xs\n better ps qs = if win (fst ps) (fst qs) then ps else qs\n win ls rs = ls == rs || count True (zipWith (<) ls rs) >= 3\n\ncount :: Eq a => a -> [a] -> Int\ncount a = length . filter (== a)\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified Data.Ratio as Rat\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nissuperior :: [Int] -> [Int] -> Bool\nissuperior xs ys = length (filter (==True) $ zipWith (<) xs ys) > div total 2\n where total = length xs\n\nsuperior :: [Int] -> [Int] -> [Int]\nsuperior xs ys = if issuperior xs ys then xs else ys\n\nwinner [xs] = xs\nwinner xxs = winner $ snd $ foldl (\\(prev, acc) xs -> if null prev then (xs, acc) else ([], (superior xs prev : acc))) ([], []) xxs\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n a <- readintrows n\n let best = winner a\n cnt = length $ filter (issuperior best) a\n bestidx = if cnt < n-1 then -1 else (fromMaybe 0 $ findIndex (==best) a) + 1\n in print bestidx\n \n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral b) => b -> IO [String]\nreadrows 0 = return []\nreadrows n = do\n row <- getLine\n l <- readrows $ n-1\n return (row : l)\n\n\nreadintrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadintrows 0 = return []\nreadintrows n = do\n row <- readInts\n l <- readintrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}], "src_uid": "8d9fc054fb1541b70991661592ae70b1"} {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> Bool\nsolve li = let\n sli = reverse $ sort li\n uli = map head $ group sli\n in li /= uli\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n putStrLn $ if solve a\n then \"YES\"\n else \"NO\"\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve >>= mapM_ ( putStrLn . which \"YES\" \"NO\" )\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tsorted = sort as\n\treturn $ ( length $ group $ sorted ) /= n || sorted /= reverse as"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\nsame :: [Int] -> Bool\nsame [] = False\nsame [x] = False\nsame (a : b : xs) = a == b || same (b : xs)\n\nsorted :: [Int] -> Bool\nsorted [] = True\nsorted [x] = True\nsorted (a : b : xs) = a >= b && sorted (b : xs)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n v <- map read . words <$> getLine\n if (not (same (sort v)) && sorted v)\n then putStrLn \"NO\"\n else putStrLn \"YES\""}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve >>= mapM_ ( putStrLn . which \"YES\" \"NO\" )\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tsorted = sort as\n\treturn $ ( length $ group $ sorted ) == n && sorted == reverse as\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\nsame :: [Int] -> Bool\nsame [] = True\nsame [x] = True\nsame (a : b : xs) = a == b && same (b : xs)\n\nsorted :: [Int] -> Bool\nsorted [] = True\nsorted [x] = True\nsorted (a : b : xs) = a <= b && sorted (b : xs)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n v <- map read . words <$> getLine\n if (not (same v) && sorted (reverse v))\n then putStrLn \"NO\"\n else putStrLn \"YES\""}], "src_uid": "b34f29e6fb586c22fa1b9e559c5a6c50"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List (foldl')\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmodSum :: Int -> Int -> Int -> Int\nmodSum m a b = (a + b) `rem` m\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve numLines numErrors modulo errors =\n runST $ do\n let numCoders = length errors\n verrors = listArray (0, numCoders - 1) errors :: UArray Int Int\n msum = modSum modulo\n bounds = ((0, 0), (numLines, numErrors))\n table <- newArray bounds 0 :: ST s (STUArray s (Int, Int) Int)\n\n writeArray table (0, 0) 1\n forM_ [0 .. numCoders - 1] $ \\c ->\n do forM_ (range bounds) $ \\ix@(l, r) ->\n do a <- readArray table ix\n b <- if l >= 1 && verrors ! c <= r\n then readArray table (l - 1, r - verrors ! c)\n else return 0\n writeArray table ix (a `msum` b)\n vs <- forM [0 .. numErrors] $ \\e -> readArray table (numLines, e)\n return $ foldl' msum 0 vs\n\nmain :: IO ()\nmain =\n do [numCoders, numLines, numErrors, modulo] <- readInts\n errors <- readInts\n when (numCoders /= length errors) $ fail \"Wrong input format\"\n print $ solve numLines numErrors modulo errors\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List (foldl')\n\nmodSum :: Int -> Int -> Int -> Int\nmodSum m a b = (a + b) `rem` m\n\nsolve :: Int -> Int -> UArray Int Int -> Int -> Int\nsolve numLines numErrors errors modulo =\n runST $ do\n let coders = bounds errors\n msum = modSum modulo\n tableBounds = ((0, 0), (numLines, numErrors))\n table <- newArray tableBounds 0 :: ST s (STUArray s (Int, Int) Int)\n writeArray table (0, 0) 1\n forM_ (range coders) $ \\c ->\n do forM_ (range tableBounds) $ \\ix@(l, e) ->\n do let ce = errors ! c\n a <- readArray table ix\n b <- if l >= 1 && ce <= e\n then readArray table (l - 1, e - ce)\n else return 0\n writeArray table ix (a `msum` b)\n foldM (\\r v -> liftM (msum r) (readArray table (numLines, v))) 0 [0 .. numErrors]\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain =\n do [numCoders, numLines, numErrors, modulo] <- readInts\n errors <- liftM (listArray (0, numCoders - 1)) readInts\n print $ solve numLines numErrors errors modulo\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad hiding (foldM, foldM_)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray)\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n [n,m,b,v] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve n m b v xs\n\nsolve :: Int -> Int -> Int -> Int -> [Int] -> Int\nsolve n m b v xs = runST $ do\n\n let x +% y = (x + y) `rem` v\n\n dp <- newArray ((0, 0), (m, b)) 0 :: ST s (STUArray s (Int, Int) Int)\n \n writeArray dp (0, 0) 1\n\n forM_ xs $ \\x -> do\n rep (m + 1) $ \\i -> do\n rep (b + 1) $ \\j -> do\n when (i + 1 <= m && j + x <= b) $ do\n (+%) <$> readArray dp (i, j) >>= modifyArray dp (i + 1, j + x)\n \n foldM 0 [0..b] $ \\ !acc i -> do\n (acc+%) <$> readArray dp (m, i)\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nfoldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a\nfoldM a xs f=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List (foldl')\n\nmodSum :: Int -> Int -> Int -> Int\nmodSum m a b = (a + b) `rem` m\n\nsolve :: Int -> Int -> UArray Int Int -> Int -> Int\nsolve numLines numErrors errors modulo =\n runST $ do\n let coders = bounds errors\n msum = modSum modulo\n tableBounds = ((0, 0), (numLines, numErrors))\n table <- newArray tableBounds 0 :: ST s (STUArray s (Int, Int) Int)\n writeArray table (0, 0) 1\n forM_ (range coders) $ \\c ->\n do forM_ (range tableBounds) $ \\ix@(l, e) ->\n do let ce = errors ! c\n a <- readArray table ix\n b <- if l >= 1 && ce <= e\n then readArray table (l - 1, e - ce)\n else return 0\n writeArray table ix (a `msum` b)\n foldM (\\r v -> liftM (r+) (readArray table (numLines, v))) 0 [0 .. numErrors]\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain =\n do [numCoders, numLines, numErrors, modulo] <- readInts\n errors <- liftM (listArray (0, numCoders - 1)) readInts\n print $ solve numLines numErrors errors modulo\n"}], "src_uid": "139febdb9c01bf0e6598fdf65a1a522c"} {"source_code": "import Control.Monad\nimport Data.List\n\n_in l r x = l <= x && x <= r\ngetA = fmap (map read . words) getLine\nstd [a,b,c,d] = map fromIntegral [min a c, min b d, max a c, max b d]\ngao l = and $ zipWith3 (\\i j [a,b,c,d] -> _in a c i && _in b d j) (f x z) (f y z) (head l:l) where\n\t(x,y,z) = unzip3 $ map (\\[a,b,c,d] -> ((a+c)/2, (b+d)/2, (c-a)^3)) l\n\tf p m = zipWith (/) (scanr1 (+) $ zipWith (*) p m) (scanr1 (+) m)\nmain = do\n\t[n] <- getA\n\ta <- replicateM n getA\n\tputStrLn $ show $ maximum $ map length $ takeWhile gao $ inits $ map std a\n", "positive_code": [{"source_code": "main = interact f\nf input = output where\n n0:bricks0 = lines input\n n = read n0::Int\n bricks = map (map (read::String->Float)) $ map words bricks0\n output = show ans\n center [[x1,y1,x2,y2]] = ((x1+x2)/2,(y1+y2)/2,abs((x2-x1)^3))\n center (x:xs) = (g x1 x2,g y1 y2,w1+w2) where\n (x1,y1,w1) = center [x]\n (x2,y2,w2) = center xs\n g x y = (x*w1+y*w2)/(w1+w2)\n stable [_] = True\n stable ([x1,y1,x2,y2]:xs) = stable xs && (x-x1)*(x-x2)<=0 && (y-y1)*(y-y2)<=0 where\n (x,y,_) = center xs\n ans = length $ takeWhile id [stable $ take i bricks|i<-[1..n]]"}, {"source_code": "cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)\n\nisOK [] _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)\n | x < h0x * 2 * w = False\n | x > h1x * 2 * w = False\n | y < h0y * 2 * w = False\n | y > h1y * 2 * w = False\n | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))\n\nsolve v n = [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]\n\nintrprt [] n = n\nintrprt (x:xs) n\n | x == n = intrprt xs (n + 1)\n | otherwise = n\n\nprc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))\n\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Integer)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((prc (x,y,z,t)):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ (intrprt (solve v n) 1) - 1\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\n_in l r x = l <= x && x <= r\ngetA = fmap (map read . words) getLine\nstd [a,b,c,d] = map fromIntegral [min a c, min b d, max a c, max b d]\ngao l = and $ zipWith3 (\\i j [a,b,c,d] -> _in a c i && _in b d j) (f x z) (f y z) (head l:l) where\n\t(x,y,z) = unzip3 $ map (\\[a,b,c,d] -> ((a+c)/2, (b+d)/2, (c-a)^3)) l\n\tf p m = zipWith (/) (scanr1 (+) $ zipWith (*) p m) (scanr1 (+) m)\nmain = do\n\t[n] <- getA\n\ta <- replicateM n getA\n\tputStrLn $ show $ maximum $ map length $ filter gao $ inits $ map std a\n"}, {"source_code": "import Data.Char (ord)\n\ncdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)\n\nisOK [] _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)\n | x < h0x * 2 * w = False\n | x > h1x * 2 * w = False\n | y < h0y * 2 * w = False\n | y > h1y * 2 * w = False\n | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))\n\nsolve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]\n\nprc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))\n\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Int)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((prc (x,y,z,t)):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ solve v n\n"}, {"source_code": "cdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)\n\nisOK [] _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)\n | x < h0x * 2 * w = False\n | x > h1x * 2 * w = False\n | y < h0y * 2 * w = False\n | y > h1y * 2 * w = False\n | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))\n\nsolve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]\n\nprc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))\n\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Integer)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((prc (x,y,z,t)):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ solve v n\n"}, {"source_code": "import Data.Char (ord)\n\ncdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)\n\nisOK [] _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)\n | x < h0x * 2 * w = False\n | x > h1x * 2 * w = False\n | y < h0y * 2 * w = False\n | y > h1y * 2 * w = False\n | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))\n\nsolve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]\n\nprc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))\n\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Int)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((prc (x,y,z,t)):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ solve v n\n"}, {"source_code": "import Data.Char (ord)\n\ncdg (a,b) (x,y,z,t) = (a + x + z, b + y + t)\n\nisOK [] _ _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y) n\n | x < h0x * 2 * n = False\n | x > h1x * 2 * n = False\n | y < h0y * 2 * n = False\n | y > h1y * 2 * n = False\n | otherwise = isOK hs (cdg (x,y) (h0x,h0y,h1x,h1y)) (n + 1)\n\nsolve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0) (v !! (t - 1))) 1]\n\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Int)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((x,y,z,t):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ solve v n\n"}, {"source_code": "cdg::(Integer,Integer,Integer)->(Integer,Integer,Integer,Integer)->(Integer,Integer,Integer)\ncdg (a,b,w) (x,y,z,t) = (a + (x + z) * nw, b + (y + t) * nw, w + nw) where nw = (z-x)*(z-x)*(z-x)\n\nisOK::[(Integer,Integer,Integer,Integer)]->(Integer,Integer,Integer)->Bool\nisOK [] _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y,w)\n | x < h0x * 2 * w = False\n | x > h1x * 2 * w = False\n | y < h0y * 2 * w = False\n | y > h1y * 2 * w = False\n | otherwise = isOK hs (cdg (x,y,w) (h0x,h0y,h1x,h1y))\n\nsolve::[(Integer,Integer,Integer,Integer)]->Int->Int\nsolve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0,0) (v !! (t - 1)))]\n\nprc::(Integer,Integer,Integer,Integer)->(Integer,Integer,Integer,Integer)\nprc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))\n\nreadVector::Int->IO [(Integer,Integer,Integer,Integer)]\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Integer)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((prc (x,y,z,t)):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ solve v n\n"}, {"source_code": "import Data.Char (ord)\n\ncdg (a,b) (x,y,z,t) = (a + x + z, b + y + t)\n\nisOK [] _ _ = True\nisOK ((h0x,h0y,h1x,h1y):hs) (x,y) n\n | x < h0x * 2 * n = False\n | x > h1x * 2 * n = False\n | y < h0y * 2 * n = False\n | y > h1y * 2 * n = False\n | otherwise = isOK hs (cdg (x,y) (h0x,h0y,h1x,h1y)) (n + 1)\n\nsolve v n = maximum [t | t <- [1..n], isOK ( reverse (take (t - 1) v) ) (cdg (0,0) (v !! (t - 1))) 1]\n\nprc (x1,y1,x2,y2) = ((min x1 x2), (min y1 y2), (max x1 x2), (max y1 y2))\n\nreadVector 0 = return []\nreadVector n = do\n [x,y,z,t] <- fmap ( (map (\\x -> read x::Int)) . words ) getLine\n rest <- (readVector (n - 1))\n return ((prc (x,y,z,t)):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- (readVector n)\n print $ solve v n\n"}], "src_uid": "05f7a8e34049161b0dba94c827a48ba6"} {"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Ix (Ix)\r\nimport Data.List (unfoldr)\r\n\r\ndata Player = Alice | Bob deriving Show\r\n\r\nsolve :: [Int] -> Player\r\nsolve xs = bool Bob Alice (head xs /= minimum xs)\r\n\r\ndocase :: IO ()\r\ndocase = do\r\n _ <- getInt\r\n xs <- getInts\r\n print $ solve xs\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ docase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts = unfoldr go where\r\n go s = do\r\n (n,s1) <- C.readInt s\r\n let s2 = C.dropWhile (==' ') s1\r\n pure (n,s2)\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\n----- --------------------------------------------------------------\r\ndata TC = TC { as :: [Int] }\r\n\r\ntype Output = Bool\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n as <- numberOf int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = head as > minimum as\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput ix = bool \"Bob\" \"Alice\" >>> C.pack\r\n\r\n----- -------------------------------------------------------------\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1..] >>> map (uncurry output) >>> C.unlines\r\n\r\n----- Template ----------------------------------------------------------------\r\n\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}], "negative_code": [], "src_uid": "4c5187193cf7f2d2721cedbb15b2a1c3"} {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\ngetAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]\ngetAllPows a n p cur\n | p == n = [cur]\n | otherwise = cur : (getAllPows a n (p + 1) (2 `multMod` cur))\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Int64 -> Int64\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsub :: Int64 -> Int64 -> Int64\nsub a b = (a + modPr - b) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve x p n ps pl = ((x `multMod` (ps `sub` 1)) + modPr - (x `multMod` (pl `sub` 1))) `mod` modPr\n -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n -- | otherwise = 123\n\nsolve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64\nsolve' [] _ _ _ _ = 0\nsolve' (x:xs) p n (ps:pss) (pl:pls) = ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n -- xs <- sort . map (read :: String -> Int64) . words <$> getLine\n xs <- sort <$> getInt64s\n let ps = getAllPows 2 (n - 1) 0 1\n -- putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n putStrLn . show $ solve' xs 0 n ps $ reverse ps\n", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\nimport Data.Array.Unboxed\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\npairs [] = []\npairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs\n\nchi\u1ebfn :: Int -> [Int64] -> Int64\nchi\u1ebfn n = foldl' (\\s (i, x) -> s +% (x *% (twoPows!i) - x *% (twoPows!(n - i - 1)))) 0 . zip [0..] . sort\n where\n m = 1000000007\n twoPows = listArray (0, n) $ iterate (*% 2) 1 :: UArray Int Int64\n a +% b = (a + b) `mod` m\n a *% b = (a * b) `mod` m\n\nmain = do \n n <- readInt <$> B.getLine\n xs <- map fromIntegral . readInts <$> B.getLine\n print $ chi\u1ebfn n xs\n\n{-\nx1 <= x2 <= ... <= xn\n12\n13\n14 \n23\n24\n34\n123 -> 13\n124 -> 14\n134 -> 14\n234 -> 24\n1234 -> 14\n\n14 -> 3 -> 4\n13 -> 2 -> 2\n12 -> 1 -> 1\n24 -> \n\n\nxi * (2^i) - xi * 2^(n-i-1)\n-}"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Maybe\nimport Data.Int\nimport Data.Bool\nimport Data.List\nimport Control.Monad\n\nmodulant :: Int64\nmodulant = 1000000007\n\ntwos :: [Int64]\ntwos = work 1\n where\n work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)\n\n-- >>> all (>= 0) $ take 100000 ((* 1000000007) <$> twos)\n-- True\n--\nmain :: IO ()\nmain = do\n getLine\n sorted <- liftM (\\l -> (sort :: [Int64] -> [Int64]) $ read <$> (words l)) getLine\n let a = foldl' (\\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> zip twos sorted\n b = foldl' (\\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> (zip twos $ reverse sorted)\n print $ (a - b) `mod` modulant\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\ngetAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]\ngetAllPows a n p cur\n | p == n = [cur - 1]\n | otherwise = (cur `sub` 1) : (getAllPows a n (p + 1) (2 `multMod` cur))\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\nsub :: Int64 -> Int64 -> Int64\nsub a b = (a + modPr - b) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve x p n ps pl = ((x `multMod` ps) + modPr - (x `multMod` pl)) `mod` modPr\n\nsolve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64\nsolve' [] _ _ _ _ = 0\nsolve' (x:xs) p n (ps:pss) (pl:pls) = ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n xs <- sort <$> getInt64s\n let ps = getAllPows 2 (n - 1) 0 1\n putStrLn . show $ solve' xs 0 n ps $ reverse ps\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Int64 -> Int64\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve x p n ps pl = ((x `multMod` (ps - 1)) + modPr - (x `multMod` (pl - 1))) `mod` modPr\n -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n -- | otherwise = 123\n\nsolve' :: [Int64] -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve' [] _ _ _ _ = 0\nsolve' (x : xs) p n ps pl = ((solve' xs (p + 1) n (ps `multMod` 2) (pl `div` 2)) + (solve x p n ps pl)) `mod` modPr\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n -- xs <- sort . map (read :: String -> Int64) . words <$> getLine\n xs <- sort <$> getInt64s\n let ps = 1\n pl = powMod 2 $ n - 1\n -- putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n putStrLn . show $ solve' xs 0 n ps pl\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmodPr = 1000000009 :: Integer\n\npowMod :: Integer -> Integer -> Integer\npowMod _ 0 = 1\npowMod a b \n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\npowMod' :: Integer -> Integer -> Integer\npowMod' a b = (powMod a b) - 1\n\nsolve :: Integer -> Integer -> Integer -> Integer\nsolve x 0 n = (- (x * (powMod' 2 $ n - 1)))\nsolve x p n\n | p == (n - 1) = (x * (powMod' 2 $ n - 1))\n | otherwise = (- (x * (powMod' 2 $ p))) + (x * (powMod' 2 $ n - p - 1))\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Integer) <$> getLine\n xs <- sort . map (read :: String -> Integer) . words <$> getLine\n -- putStrLn . show $ zip xs [0..(n - 1)]\n putStrLn . show $ foldl' (\\ acc (x, p) -> acc + (solve x p n)) 0 $ zip xs [0..(n - 1)]\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmodPr = 1000000009 :: Integer\n\npowMod :: Integer -> Integer -> Integer\npowMod _ 0 = 1\npowMod a b \n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\npowMod' :: Integer -> Integer\npowMod' x = (powMod 2 x) - 1\n\nmultMod :: Integer -> Integer -> Integer\nmultMod a b = (a * b) `mod` modPr\n\nsolve :: Integer -> Integer -> Integer -> Integer\nsolve x 0 n = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr\nsolve x p n\n | p == (n - 1) = (x `multMod` (powMod' $ n - 1))\n | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Integer) <$> getLine\n xs <- sort . map (read :: String -> Integer) . words <$> getLine\n -- putStrLn . show $ zip xs [0..(n - 1)]\n putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmodPr = 1000000009 :: Integer\n\npowMod :: Integer -> Integer -> Integer\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Integer -> Integer -> Integer\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Integer -> Integer\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsolve :: Integer -> Integer -> Integer -> Integer\nsolve x p n = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n\n{-\nsolve :: Integer -> Integer -> Integer -> Integer\nsolve x p n\n | p == 0 = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr\n | p == (n - 1) = (x `multMod` (powMod' $ n - 1)) `mod` modPr\n | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr\n where multMod a b = (a * b) `mod` modPr\n powMod' x = (powMod 2 x) - 1\n-}\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Integer) <$> getLine\n xs <- sort . map (read :: String -> Integer) . words <$> getLine\n -- putStrLn . show $ zip xs [0..(n - 1)]\n putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Int64 -> Int64\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64\nsolve x p n \n | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n | otherwise = 123\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n -- xs <- sort . map (read :: String -> Int64) . words <$> getLine\n xs <- sort <$> getInt64s\n putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Int64 -> Int64\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64\nsolve x p n \n | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n | otherwise = 123\n\nsolve' :: [Int64] -> Int64 -> Int64 -> Int64\nsolve' [] _ _ = 0\nsolve' (x : xs) p n = ((solve' xs (p + 1) n) + (solve x p n)) `mod` modPr\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n -- xs <- sort . map (read :: String -> Int64) . words <$> getLine\n xs <- sort <$> getInt64s\n -- putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n putStrLn . show $ solve' xs 0 n\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Int64 -> Int64\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsub :: Int64 -> Int64 -> Int64\nsub a b = (a + modPr - b) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve x p n ps pl = ((x `multMod` (ps `sub` 1)) + modPr - (x `multMod` (pl `sub` 1))) `mod` modPr\n -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n -- | otherwise = 123\n\nsolve' :: [Int64] -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve' [] _ _ _ _ = 0\nsolve' (x : xs) p n ps pl = ((solve' xs (p + 1) n (ps `multMod` 2) (pl `div` 2)) + (solve x p n ps pl)) `mod` modPr\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n -- xs <- sort . map (read :: String -> Int64) . words <$> getLine\n xs <- sort <$> getInt64s\n let ps = 1\n pl = powMod 2 $ n - 1\n -- putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n putStrLn . show $ solve' xs 0 n ps pl\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\ngetAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]\ngetAllPows a n p cur\n | p == n = [cur]\n | otherwise = (cur `sub` 1) : (getAllPows a n (p + 1) (2 `multMod` cur))\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\nsub :: Int64 -> Int64 -> Int64\nsub a b = (a + modPr - b) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nsolve x p n ps pl = ((x `multMod` ps) + modPr - (x `multMod` pl)) `mod` modPr\n\nsolve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64\nsolve' [] _ _ _ _ = 0\nsolve' (x:xs) p n (ps:pss) (pl:pls) = ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n xs <- sort <$> getInt64s\n let ps = getAllPows 2 (n - 1) 0 1\n putStrLn . show $ solve' xs 0 n ps $ reverse ps\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmodPr = 1000000009 :: Integer\n\npowMod :: Integer -> Integer -> Integer\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Integer -> Integer -> Integer\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Integer -> Integer\npowMod' x = (powMod 2 x) - 1\n\nsolve :: Integer -> Integer -> Integer -> Integer\nsolve x p n = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n\n{-\nsolve :: Integer -> Integer -> Integer -> Integer\nsolve x p n\n | p == 0 = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr\n | p == (n - 1) = (x `multMod` (powMod' $ n - 1)) `mod` modPr\n | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr\n where multMod a b = (a * b) `mod` modPr\n powMod' x = (powMod 2 x) - 1\n-}\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Integer) <$> getLine\n xs <- sort . map (read :: String -> Integer) . words <$> getLine\n -- putStrLn . show $ zip xs [0..(n - 1)]\n putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nmodPr = 1000000007 :: Int64\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod a b\n | b `mod` 2 == 0 = p\n | otherwise = (p * a) `mod` modPr\n where h = powMod a (b `div` 2)\n p = (h * h) `mod` modPr\n\nmultMod :: Int64 -> Int64 -> Int64\nmultMod a b = (a * b) `mod` modPr\n\npowMod' :: Int64 -> Int64\npowMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64\nsolve x p n \n | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr\n | otherwise = 123\n\ngetInt64s :: IO [Int64]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n xs <- sort . map (read :: String -> Int64) . words <$> getLine\n -- xs <- sort <$> getInt64s\n putStrLn . show $ foldl' (\\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Maybe\nimport Data.Int\nimport Data.Bool\nimport Data.List\nimport Control.Monad\n\nmodulant :: Int64\nmodulant = 1000000007\n\ntwos :: [Int64]\ntwos = work 1\n where\n work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)\n\nmain :: IO ()\nmain = do\n getLine\n sorted <- liftM (\\l -> (sort :: [Int64] -> [Int64]) $ read <$> (words l)) getLine\n let a = foldl' (\\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> zip twos sorted\n b = foldl' (\\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> (zip twos $ reverse sorted)\n print $ a - b\n"}, {"source_code": "import Data.Maybe\nimport Data.Int\nimport Data.Bool\nimport Data.List\nimport Control.Monad\n\ncalc :: [Int64] -> Int64\ncalc = work 0 1\n where\n work acc _ [] = acc\n work acc cnt (x:xs) = work ((acc + x * cnt) `mod` 1000000007) (let c = 2 * cnt in if c > 1000000007 then c - 1000000007 else c) xs\n\nmain :: IO ()\nmain = do\n getLine\n sorted <- liftM (\\l -> sort $ read <$> (words l)) getLine\n let a = calc sorted\n b = calc . reverse $ sorted\n print $ a - b\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\nimport Data.Bits\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\npairs [] = []\npairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs\n\nchi\u1ebfn :: [Int64] -> Int64\nchi\u1ebfn = foldl' (+%) 0 . map (\\((i, x), (i', x')) -> (1 `shiftL` (i' - i - 1)) *% (x' - x)) . pairs . zip [1..] . sort\n where\n m = 1000000007\n a +% b = (a + b) `mod` m\n a *% b = (a * b) `mod` m\n\nmain = do \n B.getLine\n xs <- map fromIntegral . readInts <$> B.getLine\n print $ chi\u1ebfn xs\n\n{-\nx1 <= x2 <= ... <= xn\n12\n13\n14 \n23\n24\n34\n123 -> 13\n124 -> 14\n134 -> 14\n234 -> 24\n1234 -> 14\n\n14 -> 3 -> 4\n13 -> 2 -> 2\n12 -> 1 -> 1\n24 -> \n\n\nxi * (2^i) - xi * 2^(n-i-1)\n-}"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\npairs [] = []\npairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs\n\nchi\u1ebfn n = foldl' (+%) 0 . map (\\((i, x), (i', x')) -> (i' - i) *% (x' - x)) . pairs . zip [1..] . sort\n where\n m = 1000000007\n a +% b = (a + b) `mod` m\n a *% b = f a b 0\n where\n f x y acc \n | y == 1 = acc +% x\n | r == 0 = f x2 q acc\n | otherwise = f x2 q (acc +% x)\n where \n (q, r) = y `quotRem` 2\n x2 = x +% x\n\nmain = chi\u1ebfn <$> (readInt <$> B.getLine) <*> (readInts <$> B.getLine) >>= print\n\n{-\nx1 <= x2 <= ... <= xn\nx2-x1: 1\nx3-x1: 2\nx4-x1: 3\n-}"}], "src_uid": "acff03fe274e819a74b5e9350a859471"} {"source_code": "import Data.List\n\ncount xs = [(head x, length x) | x <- group(sort xs)]\n\nwinner:: [(Int,Int)] -> (Int,Int)\nwinner [x] = x\nwinner (x:xs)\n | snd x > snd maxVote = x\n | snd x == snd maxVote && fst x < fst maxVote = x\n | otherwise = maxVote\n where maxVote = winner xs\n\nstage1::[[Int]] -> [Int]\nstage1 [] = []\nstage1 (v:vs) = fst(winner(zip [1..length v] v)) : stage1 vs\n\nreplicateM n x = sequence (replicate n x)\n\nreadLine = do\n line <- getLine\n return [read n :: Int| n <- words line]\n\nmain = do\n numberStr <- getLine\n let [_,m] = [read n::Int | n <- words numberStr]\n votes <- replicateM m readLine\n print (fst(winner(count(stage1(votes)))))", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n s <- getLine\n let \n n:m:[] = words s\n s <- sequence (replicate (read m :: Int) getLine)\n let\n d = map words s\n dd = map (\\xs -> map (\\x -> read x :: Int) xs) d\n cities = sort $ map cityWin dd\n grouped = map (\\xs -> (head xs, length xs) ) (group cities)\n r = foldl (\\(bc, bcnt) (city, cnt) -> if cnt > bcnt then (city, cnt) else (bc, bcnt)) (head grouped) grouped\n\n print (fst r)\n\ncityWin::[Int]->Int\ncityWin xs = snd $ foldl (\\(bx, bp) (x,p) -> if x > bx then (x,p) else (bx, bp)) (head xs, 1) $ zip xs [1..]"}, {"source_code": "import Data.List as L\nimport Control.Applicative\nimport Data.Ord (comparing)\n\ntoInt :: String -> Int\ntoInt x = read x\n\n\n\nmaxVote xs = fst $ head $ filter (\\x-> snd x == m) (zip [1..] xs)\n where m = maximum xs\n\nmaxCity xs = fst $ head $ groupCount xs\n \ngroupCount x = zip (map head groupedOnes) (map length groupedOnes)\n where groupedOnes = groupDes x\n\ngroupDes x = L.reverse . L.sortBy (comparing length) . L.group . L.reverse . L.sort $ x\n \nmain = do\n votes <- map (map toInt . words) . tail . lines <$> getContents\n let ans = maxCity $ map maxVote votes\n print ans \n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Array.ST\nimport Data.Array.Unboxed\n\nrInt = map (\\x -> read x::Int) . words\n\nmain :: IO()\nmain = do\n [n,m] <- fmap rInt getLine\n arr <- forM [1..m] $ \\i ->do\n l <- fmap rInt getLine\n return l\n let a = elems $ solve (map rSolve arr)\n let (_, ans) = foldl' (\\(a,b) (b1,b2)->if b1>a then (b1,b2) else (a,b)) (0,1) $ zip a [1..]\n print ans\n \n\nrSolve :: [Int] -> Int\nrSolve l = v\n where (_,v) = foldl' f (-1,0) $ zip l [1..]\n f (a,b) (c,d) = if c>a then (c,d) else (a,b)\n\nsolve :: [Int] -> UArray Int Int\nsolve l = runSTUArray $ do\n a <- newArray (1,100) 0\n forM_ l $ \\i -> do\n x <- readArray a i\n writeArray a i (x+1)\n return a"}, {"source_code": "import Data.Function\nimport Data.List\n\nmain = do\n getLine\n a <- fmap (map (map read . words) . lines) getContents :: IO [[Int]]\n\n print $ - (head $ maximumBy (compare `on` (\\x -> (length x, x))) $ group $ sort $ map (\\a -> snd $ maximum $ zipWith (\\a b -> (a, -b)) a [1..]) a)\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.List\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain = do\n [n, m] <- readInts\n cities <- map (`zip` map negate [1..]) <$> replicateM m readInts\n print . negate . snd . maximum . map (length &&& head) . group . sort . map (snd . maximum) $ cities\n"}, {"source_code": "import Data.Array\nanswer::Int -> [[Int]] -> Int\nanswer m a = elec m (city a) \nelec::Int -> [Int] -> Int\nelec m a = getMaxIndex (elems (accumArray (+) 0 (1,m) (zip a (repeat 1))))\ncity::[[Int]] ->[Int]\ncity a = map getMaxIndex a\ngetMaxIndex::[Int] -> Int\ngetMaxIndex a = getMaxIndex0 (-1) 1 0 a \ngetMaxIndex0::Int -> Int -> Int -> [Int] ->Int\ngetMaxIndex0 n m r [] = r \ngetMaxIndex0 n m r a | n >= h = getMaxIndex0 n (m+1) r (tail a)\n | otherwise = getMaxIndex0 h (m+1) m (tail a)\n where h = head a\n--main = print $ answer 3 [[1,2,3],[2,3,1],[1,2,1]]\n-- main = print $ answer 3 [[10,10,3],\n-- [5,1,6],\n-- [2,2,2],\n-- [1,5,7]]\nreadInput::Int -> IO [[Int]]\nreadInput 0 = return []\nreadInput n = do\n w <- getLine\n let a = [read n::Int|n <- (words w)]\n next <- readInput (n-1)\n return ([a] ++ next)\nmain = do\n w <- getLine\n let ww = words w\n let m = read (ww !! 0)::Int\n let n = read (ww !! 1)::Int\n a <- readInput n\n print $ answer m a\n \n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Word\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\n\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\ns -> let [_,n] = (map (read).words) ns in (solve =<< forM [1..n] ( \\i -> map (read).words <$>getLine))\nsolve::[[Word64]]->IO()\nsolve xs = print $ f $ map (\\a-> (length a, head a)) $ group $ sort $ map (\\as-> f as) $ map (\\as-> zipWith (\\a b -> (b,a)) [1..] as) xs\n where\n f ds = (snd . head .sortBy (\\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds"}, {"source_code": "-- Codeforces 570A\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map read . words) getLine :: IO [Int]\n replicateM m getLine >>= print . solve . map (map read . words)\n\nsolve :: [[Int]] -> Int\nsolve = snd . head . sortBy (\\x y -> if (fst x) == (fst y) then compare (snd x) (snd y) else compare (fst y) (fst x)) . map (\\x -> (length x, head x)) . group . sort . map (\\x -> (+ 1) $ fromJust $ elemIndex (maximum x) x)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n-----\n\n--be carefull with the type inference\n\n-----\n\n---------\n-- get space separated something\n\ngetListSp :: Read a => IO [a] \ngetListSp = (map read . words) <$> getLine\n\n---------\n\n\n\n---------\n-- output [a] in space separated form\n\nputListSp :: Show a => [a] -> IO()\nputListSp ls = putStrLn $ show $ unwords $ map show ls\n\n---------\n\n\n--------\n-- read an integer N, get N lines, make a list consist of them\n\ngetListLn :: Read a => IO [a]\ngetListLn = do n <- readLn\n s <- replicateM n getLine\n\t return (map read s)\n--------\n\n\nmain = do [n, m] <- getListSp\n votes <- replicateM m getListSp\n\t print $ solve votes\n\t \n\t \nsolve :: [[Int]] -> Int\nsolve = maxInd . cntList . (map maxInd)\n\nmaxInd :: [Int] -> Int\nmaxInd xs = rval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]\n where maxVal = foldl1 max xs\n\t lval (x, y) = x\n\t\t rval (x, y) = y\n\ncntList :: [Int] -> [Int]\ncntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip xs (repeat 1))\n where maxVal = foldl1 max xs"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\n\n\nprocess x = fromJust $ findIndex (==m) x\n where m = maximum x\n\nprocess1 n x = process $ elems xx\n where xx = accumArray (+) 0 (0,n-1) $ zip x (repeat 1)\n\nmain::IO ()\nmain=do\n [n,m]<- map read <$> words <$> getLine ::IO [Int]\n x<-(+1) <$> process1 n <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int\n print x\n"}, {"source_code": "import Control.Arrow ((&&&))\nimport Data.List (elemIndex, group, sort)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Int\nsolve = succ . negate . snd . maximum . map (length &&& negate . head) . group . sort . map maximumIndex\n\nmaximumIndex :: Ord a => [a] -> Int\nmaximumIndex xs = fromJust $ elemIndex (maximum xs) xs\n"}, {"source_code": "import Data.Function\nimport Data.List\nimport Data.Monoid\nimport Control.Arrow\nimport Control.Monad\nreadInts = fmap (map read . words) getLine\nwinner = fst . maximumBy ((compare `on` snd) `mappend` (flip compare `on` fst))\nmain = do\n [n,m] <- readInts\n cs <- replicateM m (fmap (zip [1..]) readInts)\n let ws = map winner cs\n print $ winner $ map (head &&& length) $ group $ sort ws"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Function\n\nwinner :: [Int] -> Int\nwinner xs = (+1) . fromJust . elemIndex m $ xs\n where m = maximum xs\n\nsolve :: [[Int]] -> Int\nsolve = head . maximumBy (compare `on` length) . group . reverse . sort . map winner\n\nmain = do\n [n,m] <- getList\n xs <- mapM (\\_ -> getList) [1..m]\n print $ solve xs\n \ngetList :: (Read a) => IO [a]\ngetList = fmap (map read . words) getLine\n"}, {"source_code": "import System.IO\nimport qualified Data.List as L\n\nread_ints :: String -> [Int]\nread_ints x = map read (words x) :: [Int]\n\nbest :: [[Int]] -> Int\nbest x = fst $ foldl (\\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x\n\ncompute :: [Int] -> Int\ncompute x = best ( L.group $ L.sort x )\n\nsolve :: [Int] -> Int\nsolve x = fst $ foldl (\\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,negate 1) ( zip x [1..] )\n\nmain = do\n\tln <- getLine\n\tlet [n,m] = read_ints ln\n\tln <- getContents\n\tlet mat = map read_ints (lines ln)\n\t \n\tlet winers = foldl (\\ans ln -> solve ln : ans ) [] mat \n\t-- print winers\n\tlet ans = compute winers\n\tputStr $ show ans\n"}, {"source_code": "import Data.Ord (comparing)\nimport Data.List (maximumBy)\nimport Data.Monoid\nimport qualified Data.Map as M\n\nmain = interact solve >> putChar '\\n'\n\nsolve :: String -> String\nsolve rawInput = winner\n where input = (map . map) read $ map words $ lines rawInput :: [[Int]]\n inData = tail input\n indexed = map (zip [1..]) inData\n winners = map fst $ map (maximumBy $ compareOrder) indexed\n occurList = toOccurList winners\n winner = show $ fst $ maximumBy compareOrder occurList\n\ncompareOrder = mappend (comparing snd) (flip $ comparing fst)\n\ntoOccurList :: [Int] -> [(Int, Int)]\ntoOccurList = M.toList . foldr (\\x map -> M.insertWith (+) x 1 map) M.empty\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\nmymax s = snd $ head $ filter (\\z-> fst z ==m) $ zip s [1..]\n\twhere m = maximum s\n \nmain=do\t \n\t[n,m]<-map read.words <$> getLine:: IO [Int] \n\ts<- map (map read). map words . lines <$> getContents ::IO [[Int]]\n\tlet s1 = group $ sort $ map (mymax) s\n\tlet s2 = maximum (map length s1)\n\tprint $ minimum $ map head $ filter (\\z-> length z ==s2) s1 \n\t \n"}, {"source_code": "import Control.Arrow ((&&&))\nimport Data.List (group, sort)\n\ntype Input = [[Int]]\n\nparse :: String -> Input\nparse = map parseLine . tail . lines\n where parseLine = map read . words\n\nselect :: [(Int, Int)] -> Int\nselect = negate . snd . maximum\n\nsolve :: Input -> Int\nsolve = stage2 . stage1\n where stage1 = map (select. flip zip [-1, -2..]) :: [[Int]] -> [Int]\n stage2 = select . map (length &&& negate . head) . group . sort\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}, {"source_code": "\nimport Data.List\n\nmain = interact $ show . sol . map read . words\n\nsol (n:_:xs) = snd . minimum . map (\\x -> (- length x, head x)) . group . sort . map det $ spl (map negate xs)\n where det ls = snd . minimum $ zip ls [1..]\n spl [] = []\n spl l = take n l : spl (drop n l)\n\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n _:m:_ <- getList\n votes <- getLists m\n print $ solve votes\n\ngetLists :: (Read a) => Int -> IO [[a]]\ngetLists nRows = replicateM nRows getList\n\ngetList :: (Read a) => IO [a]\ngetList = fmap (fmap read . words) getLine\n\nsolve :: [[Int]] -> Int\nsolve = mostCommon . map cityWinner\n\ncityWinner :: [Int] -> Int\ncityWinner = negate . snd . maximum . (`zip` [-1,-2..])\n\nmostCommon :: [Int] -> Int\nmostCommon = negate . snd . maximum . fmap (\\xs -> (length xs, - head xs)) . group . sort\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport Data.Array.ST\nimport Data.Array.Unboxed\n\nrInt = map (\\x -> read x::Int) . words\n\nmain :: IO()\nmain = do\n [n,m] <- fmap rInt getLine\n arr <- forM [1..m] $ \\i ->do\n l <- fmap rInt getLine\n return l\n let a = elems $ solve (map rSolve arr)\n print a\n let (_, ans) = foldl' (\\(a,b) (b1,b2)->if b1>a then (b1,b2) else (a,b)) (0,1) $ zip a [1..]\n print ans\n \n\nrSolve :: [Int] -> Int\nrSolve l = v\n where (_,v) = foldl' f (0,0) $ zip l [1..]\n f (a,b) (c,d) = if c>a then (c,d) else (a,b)\n\nsolve :: [Int] -> UArray Int Int\nsolve l = runSTUArray $ do\n a <- newArray (1,100) 0\n forM_ l $ \\i -> do\n x <- readArray a i\n writeArray a i (x+1)\n return a"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Word\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\ns -> let [_,n] = (map (read).words) ns in (solve =<< forM [1..n] ( \\i -> map (read).words <$>getLine))\nsolve::[[Word64]]->IO()\nsolve xs = print $ f $ map (\\a-> (length a, head a)) $ group $ map (\\as-> f as) $ map (\\as-> zipWith (\\a b -> (b,a)) [1..] as) xs\n where\n f ds = (snd . head .sortBy (\\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\ns -> let [_,n] = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))\nsolve xs = print $ snd $ head $ head $ groupBy (\\ (a1,a2) (b1,b2) -> a1 == b1) $ sortBy (\\ (a1,a2) (b1,b2) -> b1 `compare` a1) $ map (\\a-> (length a, head a)) $ group $ map (\\as-> snd $ head $ head $ groupBy (\\ (a1,a2) (b1,b2) -> a1 == b1) $ sortBy (\\ (a1,a2) (b1,b2) -> b1 `compare` a1) as) $ map (\\as-> zipWith (\\a b -> (b,a)) [1..] as) xs"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\ns -> let [_,n] = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))\nsolve xs = print $ f $ map (\\a-> (length a, head a)) $ group $ map (\\as-> f as) $ map (\\as-> zipWith (\\a b -> (b,a)) [1..] as) xs\n where\n f ds = (snd . head .sortBy (\\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\ns -> let [_,n] = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))\nsolve xs = print $ fst $ maximumBy (\\(a,b) (a1,b1) -> (b `compare` b1) `compare` (a `compare` a1))$ map (\\a->(head a, length a)) $ groupBy (==) $ sortBy (\\ a b ->b `compare` a ) $ map (\\hs -> last $ maximumBy (\\(a:b:c:[]) (a1:b1:c1:[]) -> (a `compare` a1) `compare` (c `compare` c1)) hs) $ zipWith (\\as bs-> zipWith (\\a b -> b:as:a:[]) [1..] bs) [1..] xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n-----\n\n--be carefull with the type inference\n\n-----\n\n---------\n-- get space separated something\n\ngetListSp :: Read a => IO [a] \ngetListSp = (map read . words) <$> getLine\n\n---------\n\n\n\n---------\n-- output [a] in space separated form\n\nputListSp :: Show a => [a] -> IO()\nputListSp ls = putStrLn $ show $ unwords $ map show ls\n\n---------\n\n\n--------\n-- read an integer N, get N lines, make a list consist of them\n\ngetListLn :: Read a => IO [a]\ngetListLn = do n <- readLn\n s <- replicateM n getLine\n\t return (map read s)\n--------\n\n\nmain = do [n, m] <- getListSp\n votes <- replicateM m getListSp\n\t print $ solve votes\n\t \n\t \nsolve :: [[Int]] -> Int\nsolve = maxInd . cntList . (map maxInd)\n\nmaxInd :: [Int] -> Int\nmaxInd xs = lval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]\n where maxVal = foldl1 max xs\n\t lval (x, y) = x\n\ncntList :: [Int] -> [Int]\ncntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip (repeat 1) xs)\n where maxVal = foldl1 max xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n-----\n\n--be carefull with the type inference\n\n-----\n\n---------\n-- get space separated something\n\ngetListSp :: Read a => IO [a] \ngetListSp = (map read . words) <$> getLine\n\n---------\n\n\n\n---------\n-- output [a] in space separated form\n\nputListSp :: Show a => [a] -> IO()\nputListSp ls = putStrLn $ show $ unwords $ map show ls\n\n---------\n\n\n--------\n-- read an integer N, get N lines, make a list consist of them\n\ngetListLn :: Read a => IO [a]\ngetListLn = do n <- readLn\n s <- replicateM n getLine\n\t return (map read s)\n--------\n\n\nmain = do [n, m] <- getListSp\n votes <- replicateM m getListSp\n\t print $ solve votes\n\t \n\t \nsolve :: [[Int]] -> Int\nsolve = maxInd . cntList . (map maxInd)\n\nmaxInd :: [Int] -> Int\nmaxInd xs = lval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]\n where maxVal = foldl1 max xs\n\t lval (x, y) = x\n\ncntList :: [Int] -> [Int]\ncntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip xs (repeat 1))\n where maxVal = foldl1 max xs"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nprocess x = (+1) $ fromJust $ findIndex (==m) x\n where m = maximum x\n\n\nmain::IO ()\nmain=do\n getLine\n x<-(+1) <$> process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int\n print x\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nprocess x = fromJust $ findIndex (==m) x\n where m = maximum x\n\n\nmain::IO ()\nmain=do\n getLine\n x<-(+1) <$> process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int\n print x\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nprocess x = (+1) $ fromJust $ findIndex (==m) x\n where m = maximum x\n\n\nmain::IO ()\nmain=do\n getLine\n x<-process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int\n print x\n"}, {"source_code": "import System.IO\nimport qualified Data.List as L\n\nread_ints :: String -> [Int]\nread_ints x = map read (words x) :: [Int]\n\nbest :: [[Int]] -> Int\nbest x = fst $ foldl (\\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x\n\ncompute :: [Int] -> Int\ncompute x = best ( L.group $ L.sort x )\n\nsolve :: [Int] -> Int\nsolve x = fst $ foldl (\\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,0) ( zip x [1..] )\n\nmain = do\n\tln <- getLine\n\tlet [n,m] = read_ints ln\n\tln <- getContents\n\tlet mat = map read_ints (lines ln)\n\t \n\tlet winers = foldl (\\ans ln -> solve ln : ans ) [] mat \n\t-- print winers\n\tlet ans = max (compute winers) 1\n\tputStr $ show ans\n"}, {"source_code": "import System.IO\nimport qualified Data.List as L\n\nread_ints :: String -> [Int]\nread_ints x = map read (words x) :: [Int]\n\nbest :: [[Int]] -> Int\nbest x = fst $ foldl (\\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x\n\ncompute :: [Int] -> Int\ncompute x = best ( L.group $ L.sort x )\n\nsolve :: [Int] -> Int\nsolve x = fst $ foldl (\\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,0) ( zip x [1..] )\n\nmain = do\n\tln <- getLine\n\tlet [n,m] = read_ints ln\n\tln <- getContents\n\tlet mat = map read_ints (lines ln)\n\t \n\tlet winers = foldl (\\ans ln -> solve ln : ans ) [] mat \n\t-- print winers\n\tlet ans = compute winers\n\tputStr $ show ans\n"}, {"source_code": "\nimport Data.List\n\nmain = interact $ show . sol . map read . words\n\nsol (n:m:xs) = snd . minimum . map (\\x -> (- length x, head x)) . group . map det $ spl (map negate xs)\n where det ls = snd . minimum $ zip ls [1..]\n spl [] = []\n spl l = take n l : spl (drop n l)\n\n"}], "src_uid": "b20e98f2ea0eb48f790dcc5dd39344d3"} {"source_code": "\nimport Data.Char\nimport Control.Monad\n\nsimilar :: String -> String -> Bool\nsimilar s1 s2\n | length s1 /= length s2 = False\n | otherwise = similarInner s1 s2\n\nsimilarInner :: String -> String -> Bool\nsimilarInner s1 s2 = all id $ zipWith similarChar s1 s2\n\nsimilarChar :: Char -> Char -> Bool\nsimilarChar c1 c2\n | c1 == c2 = True\n | otherwise = any id $ map (($c1) . ($c2)) [similarCase, similarO, similar1]\n\nsimilarCase :: Char -> Char -> Bool\nsimilarCase c1 c2 = isLower c1 /= isLower c2 && toLower c1 == toLower c2\n\nsimilarO :: Char -> Char -> Bool\nsimilarO 'O' '0' = True\nsimilarO '0' 'O' = True\nsimilarO 'o' '0' = True\nsimilarO '0' 'o' = True\nsimilarO _ _ = False\n\nsimilar1 :: Char -> Char -> Bool\nsimilar1 c1 c2 = c1 /= c2 && c1 `elem` ls && c2 `elem` ls\n where ls = \"1lLiI\"\n\nmain = do\n login <- getLine\n n <- readLn\n res <- liftM (any $ similar login) $ replicateM n getLine\n putStrLn $ case res of\n True -> \"No\"\n False -> \"Yes\"\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.Cont\nimport Data.Char\n\nchZero :: Char -> Char\nchZero '0' = 'O'\nchZero a = a\n\nchI :: Char -> Char\nchI '1' = 'l'\nchI 'I' = 'l'\nchI 'i' = 'l'\nchI a = a\n\nminimize :: String -> String\nminimize = map (toLower . chI . chZero)\n\nmain :: IO ()\nmain = do\n login <- minimize <$> getLine\n n :: Int <- read <$> getLine\n flip runContT putStrLn $ callCC $ \\notOk -> do\n forM_ [1..n] $ \\_ -> do\n l2 <- minimize <$> liftIO getLine\n if l2 == login then notOk \"No\" else return ()\n return \"Yes\"\n"}, {"source_code": "import Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n s <- getLine\n ns <- getLine\n let n = read ns :: Integer\n strings <- mapM (\\_ -> getLine) [1..n]\n let solution = solveProblem s strings\n putStrLn solution\n\n\nsolveProblem :: String -> [String] -> String\nsolveProblem s strings = let s' = fmap (repl . toLower) s\n strings' = fmap (fmap (repl . toLower)) strings\n in case (length (nub (s':strings')) == length (s':strings')) of\n True -> \"Yes\"\n False -> \"No\"\n\n\nrepl :: Char -> Char\nrepl 'o' = '0'\nrepl '1' = 'i'\nrepl 'l' = 'i'\nrepl c = c\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.Cont\nimport Data.Char\n\nchZero :: Char -> Char\nchZero '0' = 'O'\nchZero a = a\n\nchI :: Char -> Char\nchI '1' = 'l'\nchI 'I' = 'l'\nchI 'i' = 'l'\nchI a = a\n\nminimize :: String -> String\nminimize = map (toLower . chI . chZero)\n\nmain :: IO ()\nmain = do\n login <- minimize <$> getLine\n print login\n n :: Int <- read <$> getLine\n flip runContT putStrLn $ callCC $ \\notOk -> do\n forM_ [1..n] $ \\_ -> do\n l2 <- minimize <$> liftIO getLine\n liftIO $ print login\n if l2 == login then notOk \"No\" else return ()\n return \"Yes\"\n"}, {"source_code": "import Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n s <- getLine\n ns <- getLine\n let n = read ns :: Integer\n strings <- mapM (\\_ -> getLine) [1..n]\n let solution = solveProblem s strings\n putStrLn (show solution)\n\n\nsolveProblem :: String -> [String] -> String\nsolveProblem s strings = let s' = fmap (repl . toLower) s\n strings' = fmap (fmap (repl . toLower)) strings\n in case (length (nub (s':strings')) == length (s':strings')) of\n True -> \"YES\"\n False -> \"NO\"\n\n\nrepl :: Char -> Char\nrepl 'o' = '0'\nrepl '1' = 'i'\nrepl 'l' = 'i'\nrepl c = c\n"}], "src_uid": "0d70984ab8bd7aecd68c653adf54fc08"} {"source_code": "import Data.Char (ord, chr)\r\n\r\nshrink :: String -> String\r\nshrink [] = \"0\"\r\nshrink (x: xs) = if x == '0'\r\n then shrink xs\r\n else (x: xs)\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n a <- getLine\r\n let c = head a\r\n if c /= '1'\r\n then putStrLn ((chr (ord c - 1)): tail a)\r\n else putStrLn $ shrink $ tail a\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Char\r\nimport Data.List\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [m] <- ri\r\n return m\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve m = m - roundNum m\r\n\r\nroundNum = read . ('1':) . map (const '0') . tail . show :: Int -> Int\r\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep = id\n\nparse = read\n\nformat = show\n\nsolve :: Int -> Int\nsolve x = x - (head $ filter (<= x) [10^i | i <- [9,8..0]])\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int\nsolve m = m - last roundPrices\n where\n roundPrices = L.takeWhile (<= m) $ iterate (* 10) 1\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n m <- B8.getLine <&> readIntB8\n let answer = solve m\n printf \"%d\\n\" answer\n\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport GHC.Arr\n\nwrap f = getLine >>= putStrLn . f\n\nnums = (10 ^) <$> [0 .. 9]\n\nmain = do\n n <- readLn\n forM_ [1 .. n] $\n const $ do\n n <- readLn\n print $ last $ takeWhile (>= 0) $ (n -) <$> nums\n\narrayshit =\n runST $ do\n a <- newSTArray (0, 10) 0\n writeSTArray a 4 5\n readSTArray a 4\n-- >>> 1 + 2 \n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\n\nwrap f = getLine >>= putStrLn . f\n\nnums = (10 ^) <$> [0 .. 9]\n\nmain = do\n n <- readLn\n forM_ [1 .. n] $\n const $ do\n n <- readLn\n print $ last $ takeWhile (>= 0) $ (n -) <$> nums\n-- >>> 1 + 2 \n"}, {"source_code": "import Control.Monad\n\nwrap f = getLine >>= putStrLn . f\nnums = (10^) <$> [0..9]\nmain = do\n n <- readLn\n forM_ [1..n] $ const $ do\n n <- readLn\n print $ last $ takeWhile (>=0) $ (n-) <$> nums\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nsolve :: Integer -> Integer\r\nsolve m = m - (head . filter ((> m) . (* 10)) $ iterate (* 10) 1)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t $\r\n getLine >>= print . solve . read\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nsolve :: Integer -> Integer\r\nsolve m = m - 10 ^ floor (logBase 10 $ fromInteger m)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t $\r\n getLine >>= print . solve . read\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Char\r\nimport Data.List\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [m] <- ri\r\n return m\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve = read . ('1':) . map (const '0') . tail . show :: Int -> Int\r\n"}, {"source_code": "import Data.Char (ord, chr)\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n a <- getLine\r\n let c = head a\r\n if c /= '1'\r\n then putStrLn ((chr (ord c - 1)): tail a)\r\n else if a == \"1\"\r\n then print 0\r\n else putStrLn $ tail a\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n"}], "src_uid": "5312a505bd59b55a6c5487f67a33d81a"} {"source_code": "combi :: Integral a => a -> a -> a\ncombi n m = (product [n, n - 1 .. n - m + 1]) `div` (product [1 .. m])\n\nmain :: IO ()\nmain = do\n n <- readLn\n print $ (combi n 5) + (combi n 6) + (combi n 7)\n", "positive_code": [{"source_code": "main = getLine >>= print . solve . read\n\nsolve :: Integer -> Integer\nsolve n = (cnk n 7) + (cnk n 6) + (cnk n 5)\n\nfact n = product [1..n]\n\ncnk n k | k > n = 0\n | otherwise = product [n,n-1..(n - k + 1)] `div` fact k\n"}, {"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n a <- (toInteger.fst.fromJust.C.readInt) <$> C.getLine\n let b = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5 *(a-5)`div`6*(a-6)`div`7\n let c = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5 *(a-5)`div`6\n let d = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5\n print $ b+c+d"}, {"source_code": "fact = (m !!) where m = scanl (*) 1 [1..]\ncomb n k = fact n `div` fact k `div` fact (n - k)\nsolution k = comb k 7 + comb k 6 + comb k 5\nmain = getLine >>= print . solution. read\n"}, {"source_code": "import Control.Monad\nmain = do\n a <- liftM read getLine\n putStrLn $ show $ (sum $ map (a `choose`) [5..7])\nchoose n k = (product [(n-k+1)..n]) `div` (product [1..k])"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,777) (1:( [product [1..i]| i<-[1..777]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\ncomb::Integer->[Integer]->[[Integer]]\ncomb n [] |n<5 = [[]]\n\t | otherwise = []\ncomb n (s:ss) |n>=s = [s: y| y<-(comb (n-s) (s:ss))] ++ (comb n ss)\n\t |otherwise = comb n ss\n\ncou n p []=p\ncou n p (s:ss) = cou (n-s) (p*(c n s)) ss\n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tprint $ sum $ map (c n) [7,6,5]\n\t \n\n\t"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,777) (1:( [product [1..i]| i<-[1..777]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\n \n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tprint $ sum $ map (c n) [7,6,5]\n\t \n\n\t"}, {"source_code": "main :: IO ()\nmain = print . solve . read =<< getContents\n\nsolve :: Integer -> Integer\nsolve n = binom n 7 + binom n 6 + binom n 5\n where binom n k = (product [n - k + 1 .. n]) `div` (product [1..k])\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,777) (1:( [product [1..i]| i<-[1..777]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\ncomb::Integer->[Integer]->[[Integer]]\ncomb n [] |n>5 = []\n\t | otherwise = [[]]\n\ncomb n (s:ss) |n>=s = [s: y| y<-(comb (n-s) (s:ss))] ++ (comb n ss)\n\t |otherwise = comb n ss\n\ncou n p []=p\ncou n p (s:ss) = cou (n-s) (p*(c n s)) ss\n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tlet s = init $ comb n [7,6,5] \n\tlet t = sum $ map (cou n 1) s\n\tprint t\n\n\t"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,777) (1:( [product [1..i]| i<-[1..777]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\ncomb::Integer->[Integer]->[[Integer]]\ncomb n [] |n<5 = [[]]\n\t | otherwise = []\ncomb n (s:ss) |n>=s = [s: y| y<-(comb (n-s) (s:ss))] ++ (comb n ss)\n\t |otherwise = comb n ss\n\ncou n p []=p\ncou n p (s:ss) = cou (n-s) (p*(c n s)) ss\n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tprint $ sum $ map (cou n 1) $ comb n [7,6,5] \n\t \n\n\t"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,777) (1:( [product [1..i]| i<-[1..777]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\ncomb::Integer->[Integer]->[[Integer]]\ncomb n [] |n>=5 = []\n\t | otherwise = [[]]\n\ncomb n (s:ss) |n>=s = [s: y| y<-(comb (n-s) (s:ss))] ++ (comb n ss)\n\t |otherwise = comb n ss\n\ncou n p []=p\ncou n p (s:ss) = cou (n-s) (p*(c n s)) ss\n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tlet s = init $ comb n [7,6,5] \n\tlet t = map (cou n 1) s\n\tprint t\n\n\t"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\n\nfac = listArray (0,777) (1:( [product [1..i]| i<-[1..777]]))\n \nc n r = div (fac!n) ((fac!(n-r))*(fac!r))\n\ncomb::Integer->[Integer]->[[Integer]]\ncomb n [] = [[]]\ncomb n (s:ss) |n>=s = [s: y| y<-(comb (n-s) (s:ss))] ++ (comb n ss)\n\t |otherwise = comb n ss\n\ncou n p []=p\ncou n p (s:ss) = cou (n-s) (p*(c n s)) ss\n\n\nmain= do\n\tn<- read <$>getLine::IO Integer \n\tlet s = init $ comb n [7,6,5] \n\tlet t =sum $ map (cou n 1) s\n\tprint t\n\n\t"}], "src_uid": "09276406e16b46fbefd6f8c9650472f0"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate, delete, group, nub, sort, sortBy)\n\nsolve :: [Int] -> (Int, [Int])\nsolve as = (ans, numGs as g1 g2)\n where\n gs = sortBy compareByLength $ group $ sort as\n compareByLength a b = compare (length a) (length b)\n merge (x:y:xs) = (x, y) : merge xs\n merge _ = []\n g1 = map fst $ merge $ concat gs\n g2 = map snd $ merge $ concat gs\n ans = (length (nub g1)) * (length (nub g2))\n numGs [] _ _ = []\n numGs (x:xs) g1 g2\n | elem x g1 = 1 : numGs xs (delete x g1) g2\n | otherwise = 2 : numGs xs g1 (delete x g2)\n \nmain :: IO ()\nmain = do\n getLine\n as <- reads\n print $ fst $ solve as\n prints $ snd $ solve as\n\n where\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqLen a b = length a == length b\neqFst a b = fst a == fst b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n n <- readLn :: IO Int\n l <- readsLine :: IO [Int]\n let uniqueSize = S.size . S.fromList\n let l' = reverse $ sortBy cmpLen $ groupBy eqFst $ sort $ zip l [1..]\n let (l1,l2) = splitTwo l'\n let a = uniqueSize $ map fst l1\n let b = uniqueSize $ map fst l2\n let ans = sort $ map (\\(_,i) -> (i,1)) l1 ++ map (\\(_,i) -> (i,2)) l2\n print (a*b)\n putStrLn $ unwords $ map (show.snd) ans\n\nsplitTwo :: [[(Int,Int)]] -> ([(Int,Int)],[(Int,Int)])\nsplitTwo l = unzip $ go1 l []\n where\n go1 [] !acc = go2 acc\n go1 ((x1:x2:xs):xss) !acc = \n (x1,x2):go1 xss (xs++acc)\n go1 xss !acc = go2 (concat xss++acc)\n go2 (x1:x2:xs) = (x1,x2):go2 xs\n go2 [] = []\n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsplit2 l = go l\n where\n go (x:y:xs) = (x,y):go xs\n go _ = []\n\nmain = do\n n <- readLn :: IO Int\n l <- readsLine :: IO [Int]\n let l' = sort $ zip l [1..]\n let (l1,l2) = unzip $ split2 l'\n let uniqueSize = S.size . S.fromList\n let a = uniqueSize $ map fst l1\n let b = uniqueSize $ map fst l2\n let ans = sort $ map (\\(_,i) -> (i,1)) l1 ++ map (\\(_,i) -> (i,2)) l2\n print (a*b)\n putStrLn $ unwords $ map (show.snd) ans\n"}], "src_uid": "080287f34b0c1d52eb29eb81dada41dd"} {"source_code": "solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer\nsolve' k [] [] d = 0\nsolve' k (sc:s) (tc:t) d\n | d' <= k = min k d' + solve' k s t d'\n | otherwise = k * fromIntegral(length s + 1)\n where d' = case (sc, tc) of\n ('a', 'a') -> 2*d - 1\n ('a', 'b') -> 2*d\n ('b', 'a') -> 2*d - 2\n ('b', 'b') -> 2*d - 1\n\nsolve k s t = solve' k s t 1\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n", "positive_code": [{"source_code": "solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer\nsolve' k [] [] d = 0\nsolve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'\n where d' = next k d (sc, tc)\n\nsolve k s t = solve' k s t 1\n\nnext' d ('a', 'a') = 2 * d - 1\nnext' d ('a', 'b') = 2 * d\nnext' d ('b', 'a') = 2 * d - 2\nnext' d ('b', 'b') = 2 * d - 1\n\nnext k d pair = if d <= k then next' d pair else d\n\n--solve2 k s t = sum (\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n"}, {"source_code": "next' d ('a', 'a') = 2 * d - 1\nnext' d ('a', 'b') = 2 * d\nnext' d ('b', 'a') = 2 * d - 2\nnext' d ('b', 'b') = 2 * d - 1\n\nnext k d pair = if d <= k then next' d pair else d\n\nsolve :: Integer -> [Char] -> [Char] -> Integer\nsolve k s t = sum $ map (min k) $ tail $ scanl (next k) 1 (zip s t)\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n"}, {"source_code": "solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer\nsolve' k [] [] d = 0\nsolve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'\n where d' = if d <= k then next d (sc, tc) else d\n\nsolve k s t = solve' k s t 1\n\nnext d ('a', 'a') = 2 * d - 1\nnext d ('a', 'b') = 2 * d\nnext d ('b', 'a') = 2 * d - 2\nnext d ('b', 'b') = 2 * d - 1\n\n--solve2 k s t = sum (\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n"}], "negative_code": [{"source_code": "solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer\nsolve' k [] [] d = 0\nsolve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'\n where d' = min d'' k\n d'' = case (sc, tc) of\n ('a', 'a') -> 2*d - 1\n ('a', 'b') -> 2*d\n ('b', 'a') -> 2*d - 2\n ('b', 'b') -> 2*d - 1\n\nsolve k s t = solve' k s t 1\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n"}, {"source_code": "appendBit num 0 = 2 * num\nappendBit num 1 = 2 * num + 1\n\n-- treat 'a' as 0 bit, 'b' as 1 bit\ncharToBit 'a' = 0\ncharToBit 'b' = 1\n\n-- After some point the difference will always be bigger than k\noptimizedAppendChars k a b sc tc\n | (b - a >= 4 * k) = (a, b)\n | otherwise = (appendBit a (charToBit sc), appendBit b (charToBit tc))\n\n-- Don't care about overflows because difference will persist through them\nsolve' :: Int-> [Char] -> [Char] -> Int-> Int-> Int\nsolve' k [] [] a b = 0\nsolve' k (sc:s) (tc:t) a b = min k (b' - a' + 1) + solve' k s t a' b'\n where (a', b') = optimizedAppendChars k a b sc tc\n\nsolve k s t = solve' k s t 0 0\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n"}, {"source_code": "solve' :: Int-> [Char] -> [Char] -> Int-> Int\nsolve' k [] [] d = 0\nsolve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'\n where d' = if d <= k then next d (sc, tc) else d\n\nsolve k s t = solve' k s t 1\n\nnext d ('a', 'a') = 2 * d - 1\nnext d ('a', 'b') = 2 * d\nnext d ('b', 'a') = 2 * d - 2\nnext d ('b', 'b') = 2 * d - 1\n\n--solve2 k s t = sum (\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read.words) getLine\n s <- getLine\n t <- getLine\n print (solve k s t)\n"}], "src_uid": "a88e4a7c476b9af1ff2ca9137214dfd7"} {"source_code": "module Main where\n\n\nimport Control.Monad (replicateM_)\n \ngetNumbers :: IO [Int]\ngetNumbers = map read . words <$> getLine\n \nsolution :: IO ()\nsolution = do\n [a, b, c, d] <- getNumbers\n print $ length $ filter (>= a) [b, c, d]\n \nmain :: IO ()\nmain = do\n [t] <- getNumbers\n replicateM_ t solution", "positive_code": [{"source_code": "main :: IO ()\r\nmain = do\r\n t <- getLine >>= (return . (read :: String -> Int))\r\n let\r\n toInt str = (read :: String -> Int) str\r\n bigger b a = if a > b then 1 else 0\r\n work :: Int -> IO ()\r\n work n = do\r\n if n > 0 then do \r\n arr <- getLine >>= (return . words)\r\n a <- return $ toInt $ arr !! 0\r\n b <- return $ toInt $ arr !! 1\r\n c <- return $ toInt $ arr !! 2\r\n d <- return $ toInt $ arr !! 3\r\n putStrLn (show $ bigger a b + bigger a c + bigger a d)\r\n work $ n - 1\r\n else \r\n return ()\r\n work t"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nsolve = do\n s <- C.getLine\n\n let xs = map (fst . fromJust . C.readInt) (C.words s)\n\n C.putStrLn (C.pack $ show $ length $ filter (>(xs !! 0)) xs)\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) solve\n"}, {"source_code": "module Main where\n\nmain = do\n tStr <- getLine\n input <- getContents\n mapM_ (print . solve) $ take (read tStr :: Int) $ lines input\n\nsolve :: String -> Int\nsolve s = sum $ map (fromEnum . (>a)) others\n where a:others = map read (words s) :: [Int]\n"}, {"source_code": "import Control.Monad (replicateM, replicateM_)\nimport Control.Monad.Identity (Identity)\nimport Control.Monad.Trans.State.Lazy (StateT, evalState, state)\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport Data.Char (isSpace)\nimport Data.Maybe (fromJust)\n\ntype ParserT = StateT C.ByteString\n\ntype Parser = ParserT Identity\n\nmain :: IO ()\nmain = do\n q <- fst . fromJust . C.readInt <$> C.getLine\n replicateM_ q solve\n\nsolve :: IO ()\nsolve = do\n (t : ts) <- evalState (replicateM 4 getInt) <$> C.getLine\n f . length . filter (> t) $ ts\n\ngetInt :: Parser Int\ngetInt = state $ fromJust . C.readInt . C.dropWhile isSpace\n\nf :: Int -> IO ()\nf = L.putStrLn . B.toLazyByteString . B.intDec\n"}, {"source_code": "main :: IO ()\r\nmain = interact start\r\n\r\nstart :: String -> String\r\nstart s = \r\n let (_:tests) = lines s\r\n in unlines $ map (show . solve . parse) tests\r\n\r\n\r\nparse :: String -> (Int, Int, Int, Int) \r\nparse s =\r\n let [a, b, c, d] = map read $ words s \r\n in (a, b, c, d)\r\n\r\nsolve :: (Int, Int, Int, Int) -> Int\r\nsolve (a, b, c, d) = sum $ map (`isInFront` a) [b, c, d] \r\n\r\nisInFront :: Int -> Int -> Int\r\nisInFront a b = if a < b then 0 else 1\r\n\r\ninp = \"4\\n2 3 4 1\\n10000 0 1 2\\n500 600 400 300\\n0 9999 10000 9998\\n\""}, {"source_code": "readArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\ncheck :: Int -> Int -> Int\r\ncheck a b = if a < b\r\n then 1\r\n else 0\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = pure ()\r\nsolve i = do\r\n (a: b: c: d: _) <- readArr\r\n print $ check a b + check a c + check a d\r\n solve $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n solve n"}, {"source_code": "testcase :: [Int] -> Int\r\ntestcase xs = length . filter (\\x -> x > a) $ xs\r\n where (a:_) = xs\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve [] = []\r\nsolve xs = (testcase $ take 4 xs) : (solve $ drop 4 xs)\r\n\r\nmain = interact $ unlines . map show . solve . tail . map read . words"}, {"source_code": "import Control.Monad()\nimport Data.List()\n\nsolve :: Int -> [Int] -> Int\nsolve _ [] = 0\nsolve n (x:xs) = if x > n then 1 + solve n xs else solve n xs\n\n\nrep 0 = return ()\nrep x = do\n t <- getLine\n -- print (words t)\n let arr = map (read :: String -> Int) (words t)\n let s = head arr\n print (solve s arr)\n rep (x-1)\n\n\nmain :: IO ()\nmain = do \n t <- getLine\n rep (read t)"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ncmp a b = if a < b then 1 else 0\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n a <- getInt\r\n b <- getInt\r\n c <- getInt\r\n d <- getInt\r\n let x = (cmp a b) + (cmp a c) + (cmp a d)\r\n pure $ putInts $ [x]\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState solve inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [{"source_code": "testcase :: [Int] -> Int\r\ntestcase xs = length . filter (\\x -> x > a) $ xs\r\n where (a:_) = xs\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve [] = []\r\nsolve xs = (testcase $ take 4 xs) : (solve $ drop 4 xs)\r\n\r\nmain = interact $ show . solve . tail . map read . words"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ncmp a b = if a < b then 1 else 0\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n a <- getInt\r\n b <- getInt\r\n c <- getInt\r\n d <- getInt\r\n let x = (cmp a b) + (cmp a c) + (cmp a d)\r\n pure $ intDec x\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState solve inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "src_uid": "e829ca4438e9cb30ea1c66eea7d5f7a7"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,k]<- map read <$> words <$> getLine::IO [Int]\n\t\tprint $ if n==1 then 0 else if n==2 then k else k*2\nmain = do\n\tn<- read <$> getLine ::IO Int\n\treplicateM_ n onecase\n\n\n", "positive_code": [{"source_code": "import Control.Monad\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,m]<- (map read.words) <$> getLine\n print $ solve n m\n\nsolve :: Integer -> Integer -> Integer\nsolve n m\n | n == 1 = 0\n | n == 2 = m\n | otherwise = 2*m\n"}, {"source_code": "import Data.Map as M\nimport Data.List as L\n\nsum':: [Integer] -> Integer\nsum' xs = sum [abs (x - y) | (x, y) <- L.zip xs (tail xs)]\n\nfun :: Integer -> Integer -> Integer\nfun 1 _ = 0\nfun 2 m = m\nfun _ m = 2*m\n\nparseInput :: String -> (Integer, Integer)\nparseInput raw = (n, m)\n where n = read n' :: Integer\n m = read m' :: Integer\n [n', m'] = words raw\n\nsolve :: String -> String\nsolve input = show (fun n m)\n where (n, m) = parseInput input\n\nmain :: IO()\nmain = interact (unlines . L.map solve . tail . lines)\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\n\nsolve [1,m] = 0\nsolve [2,m] = m\nsolve [_,m] = 2*m\n"}], "negative_code": [], "src_uid": "905cc16ecbbb3305416f9aa6e4412642"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad hiding (foldM, foldM_)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray)\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n getLine\n getLine >>= print.solve\n\nsolve cs = go 0 M.empty cs\n where\n go !res keys (k:c:rest)\n | Just v<-M.lookup (toLower c) keys', v > 0 = go res (M.adjust pred (toLower c) keys') rest\n | otherwise = go (res+1) keys' rest\n where\n !keys' = M.insertWith (+) k 1 keys\n go res _ _ = res\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nfoldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a\nfoldM a xs f=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}", "positive_code": [{"source_code": "import Data.Char (toLower)\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getLine >> getLine >>= print . solve 0 M.empty . map toLower\n\nsolve :: Int -> M.Map Char Int -> String -> Int\nsolve n m (y:z:ys) | y == z = solve n m ys\n | M.findWithDefault 0 z m > 0 = solve n (M.insertWith (+) y 1 (M.adjust pred z m)) ys\n | otherwise = solve (n + 1) (M.insertWith (+) y 1 m) ys\nsolve n _ _ = n\n"}, {"source_code": "import Data.Char\nimport qualified Data.Map as M\nmain=getLine>>getLine>>=print.f M.empty.map toLower\nf m (y:z:u)|M.findWithDefault 0 z b>0=f(M.adjust pred z b) u|1>0=1+f b u where b=M.insertWith(+)y 1 m\nf _ _=0\n"}, {"source_code": "import Data.Char (toLower)\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getLine >> getLine >>= print . solve M.empty . map toLower\n\nsolve :: M.Map Char Int -> String -> Int\nsolve m (y:z:ys) | y == z = solve m ys\n | M.findWithDefault 0 z m > 0 = solve (M.insertWith (+) y 1 (M.adjust pred z m)) ys\n | otherwise = 1 + solve (M.insertWith (+) y 1 m) ys\nsolve _ _ = 0\n"}, {"source_code": "import Data.Char\nimport Data.List\n\no x = (ord x) - (ord 'a')\n\nsolve :: [Int] -> String -> Int\nsolve _ [] = 0\nsolve ks (k:d:ds)\n | k == d = solve ks ds\n | x > 0 = solve (l''++(z+1):r'') ds\n | otherwise = 1 + solve (l'++(y+1):r') ds\n where\n ks' = (l++(x-1):r)\n (l,x:r) = splitAt (o d) ks\n (l'',z:r'') = splitAt (o k) ks'\n (l',y:r') = splitAt (o k) ks\n\nmain = getLine >> getLine >>= print . solve (map (const 0) [1..26]) . map toLower"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \nupd s bbc x = (take bbc s) ++[(s!!bbc)+x] ++(drop (bbc+1) s)\n\n\nprocess n s [] =n\nprocess n s (a:b:cs) | a== bb = process n s cs\n | s!!bbc >0 = process n (upd (upd s bbc (-1)) aa 1) cs\n | otherwise = process (n+1) (upd s aa 1) cs\n\t\twhere bb = toLower b\n bbc = ord bb - ord 'a'\n\t aa = ord a - ord 'a'\n\nmain= do\n\tgetLine \n\ts<- getLine \n\tprint $ process 0 (replicate 26 0) s\n\t\n\t\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nminBalance :: String -> Char -> Int\nminBalance s c = snd $ foldl' addChar (0, 0) s \n where\n addChar acc@(cur, low) x \n | x == c = (cur - 1, min (cur - 1) low)\n | x == toLower c = (cur + 1, low)\n | otherwise = acc\n\nmain = do \n _ <- getLine\n s <- getLine\n print $ sum $ map (abs . minBalance s) ['A'..'Z'] \n \n"}], "negative_code": [{"source_code": "import Data.Char\nimport qualified Data.Map as M\nmain=getLine>>getLine>>=print.f M.empty.map toLower\nf m (y:z:u)|M.findWithDefault 0 z b>0=f(M.adjust pred z b) u|1>0=1+f b u where b=M.insertWith(+)y 1 m;f _ _=0\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve :: String -> String -> Int\nsolve _ [] = 0\nsolve ks (k:d:ds)\n | k == d = solve ks ds\n | d `elem` ks = solve (delete d ks) ds\n | otherwise = 1 + solve (k:ks) ds\n\nmain = getLine >> getLine >>= print . solve [] . map toLower"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve :: String -> String -> Int\nsolve _ [] = 0\nsolve ks (k:d:ds)\n | toUpper k == d = solve ks ds\n | toLower d `elem` ks = solve (delete k ks) ds\n | otherwise = 1 + solve (k:ks) ds\n\nmain = getLine >> getLine >>= print . solve []"}, {"source_code": "import Data.Char\nimport Data.List\n\no x = (ord x) - (ord 'a')\n\nsolve :: [Int] -> String -> Int\nsolve _ [] = 0\nsolve ks (k:d:ds)\n | k == d = solve ks ds\n | x > 0 = solve (l++(x-1):r) ds\n | otherwise = 1 + solve (l'++(y+1):r') ds\n where\n (l,x:r) = splitAt (o d) ks\n (l',y:r') = splitAt (o k) ks\n\nmain = getLine >> getLine >>= print . solve (map (const 0) [1..26]) . map toLower"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \nupd s bbc x = (take (bbc-1) s) ++[(s!!bbc)+x] ++(drop bbc s)\n\n\nprocess n _ [] =n\nprocess n s (a:b:cs) | a== bb = process n s cs\n | s!!bbc >0 = process n (upd s bbc (-1)) cs\n | otherwise = process (n+1) (upd s bbc 1) cs\n\t\twhere bb = toLower b\n bbc = ord bb - ord 'a'\n\nmain= do\n\tgetLine \n\ts<- getLine \n\tprint $ process 0 (replicate 26 0) s\n\t\n\t\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \nupd s bbc x = (take (bbc-1) s) ++[(s!!bbc)+x] ++(drop bbc s)\n\n\nprocess n _ [] =n\nprocess n s (a:b:cs) | a== bb = process n s cs\n | s!!bbc >0 = process n (upd s bbc (-1)) cs\n | otherwise = process (n+1) (upd s aa 1) cs\n\t\twhere bb = toLower b\n bbc = ord bb - ord 'a'\n\t aa = ord a - ord 'a'\n\nmain= do\n\tgetLine \n\ts<- getLine \n\tprint $ process 0 (replicate 26 0) s\n\t\n\t\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \nupd s bbc x = (take bbc s) ++[(s!!bbc)+x] ++(drop (bbc+1) s)\n\n\nprocess n s [] =n\nprocess n s (a:b:cs) | a== bb = process n s cs\n | s!!bbc >0 = process n (upd s bbc (-1)) cs\n | otherwise = process (n+1) (upd s aa 1) cs\n\t\twhere bb = toLower b\n bbc = ord bb - ord 'a'\n\t aa = ord a - ord 'a'\n\nmain= do\n\tgetLine \n\ts<- getLine \n\tprint $ process 0 (replicate 26 0) s\n\t\n\t\n"}], "src_uid": "80fdb95372c1e8d558b8c8f31c9d0479"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\ntype Poly = [Rational]\n\nnormPoly :: Poly -> Poly\nnormPoly p = reverse $ delz $ reverse p \n where delz :: Poly -> Poly\n delz [] = []\n delz a@(x:xs) = if x == 0 then delz xs else a \n \n\nminus :: Poly -> Poly -> Poly\nminus p q = map (\\(x,y) -> x - y) $ zip p q\n\nadd :: Poly -> Poly -> Poly\nadd p q = map (\\(x,y) -> fromIntegral $ mod (floor x + floor y) 2) $ zip (p ++ replicate (l - length p) 0) (q ++ replicate (l - length q) 0) where l = max (length p) (length q)\n\nremPoly :: Poly -> Poly -> Poly\nremPoly p q\n | null q = undefined\n | null p = []\n | last p == 0 || last q == 0 = remPoly (normPoly p) (normPoly q)\n | length p < length q = p\n | otherwise = let dp = length p - 1\n dq = length q - 1\n lp = last p\n lq = last q\n q' = replicate (dp - dq) 0 ++ map (* (lp/lq)) q\n in remPoly (p `minus` q') q\n\ngcdPoly :: Poly -> Poly -> Int\ngcdPoly p q\n | null p || null q = 0\n | otherwise = 1 + gcdPoly q (p `remPoly` q) \n \ngenPoly :: Poly -> Poly -> Poly\ngenPoly p q = ([0] ++ p) `add` q\n\ninfList = [[1], [0,1]] ++ goInf [1] [0,1] \n where goInf q p = [r] ++ goInf p r \n where r = genPoly p q\n\nsPoly :: Poly -> String\nsPoly [] = \"\"\nsPoly (x:xs) = (show $ floor x) ++ \" \" ++ sPoly xs\n \nmain = do\n n_ <- getLine\n let n = read n_ :: Int\n print n\n putStrLn $ sPoly $ infList !! n\n print (n - 1)\n putStrLn $ sPoly $ infList !! (n-1) \n \n\n \n", "positive_code": [{"source_code": "type Poly = [Int]\n\nadd :: Poly -> Poly -> Poly\nadd p q = map (\\(x,y) -> mod (x + y) 2) $ zip (p ++ replicate (l - length p) 0) (q ++ replicate (l - length q) 0) where l = max (length p) (length q)\n\ngenPoly :: Poly -> Poly -> Poly\ngenPoly p q = ([0] ++ p) `add` q\n\ninfList = [[1], [0,1]] ++ goInf [1] [0,1] \n where goInf q p = [r] ++ goInf p r \n where r = genPoly p q\n\nsPoly :: Poly -> String\nsPoly [] = \"\"\nsPoly (x:xs) = (show x) ++ \" \" ++ sPoly xs\n \nmain = do\n n_ <- getLine\n let n = read n_ :: Int\n print n\n putStrLn $ sPoly $ infList !! n\n print (n - 1)\n putStrLn $ sPoly $ infList !! (n-1)"}, {"source_code": "import Data.List\n\nvectorAdd :: [Int] -> [Int] -> [Int]\nvectorAdd [] y = y\nvectorAdd x [] = x\nvectorAdd (a:x) (b:y) = mod (a + b) 2 : vectorAdd x y\n\nf :: Int -> [Int] -> [Int] -> [Int]\nf 0 a b = a\nf 1 a b = b\nf n a b = f (n-1) b $ vectorAdd a (0:b)\n\nfib n = f n [1] [0,1]\n\ntoString xs = concat $ intersperse \" \" $ map (show :: Int -> String) xs\n\nmain = do\n line <- getLine\n print (read line :: Int)\n putStrLn (toString (fib (read line :: Int)))\n print (pred $ read line :: Int)\n putStrLn (toString (fib $ pred (read line :: Int)))\n"}], "negative_code": [], "src_uid": "c2362d3254aefe30da99c4aeb4e1a894"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let ps = unfoldr (\\xs -> if null xs then Nothing else Just $ splitAt n xs) $ concat $ zipWith (\\a b -> [a, b]) [1..n^2`div`2] $ reverse [n^2`div`2..n^2]\n\n putStr $ unlines $ map (unwords . map show) ps\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\nshowL = concat . intersperse \" \" . map show\n\nf _ [] [] = [ return ()] \nf n a b = \n let m = n `div` 2 \n (ha,ta) = splitAt m a\n (hb,tb) = splitAt m b \n in (putStrLn $ showL ha ++ \" \" ++ showL hb) : f n ta tb\n\nmain = do\n n <- readLn :: IO Int\n let m = n^2`div`2 \n sequence_ $ f n [m,m-1..1] [m+1..n*n]"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [[Int]]\nsolve n = map (solve' 1) [1..n]\n where\n solve' j i\n | j > n = []\n | odd j = ((j - 1) * n + i) : solve' (j + 1) i\n | even j = (j * n - (i - 1)) : solve' (j + 1) i\n\nprint' :: [[Int]] -> IO ()\nprint' xs = mapM_ (\\x -> putStrLn $ intercalate \" \" $ map show x) xs\n\nmain :: IO ()\nmain = do\n --n <- liftM (read . head . words) $ readFile \"input.txt\"\n n <- readLn \n print' $ solve n\n"}, {"source_code": "import Control.Applicative\n\nmain = answer.read <$> getLine >>= mapM_ (putStrLn.show') \n\nshow' = tail.foldl (\\x y -> x++(' ':show y)) []\n\nanswer :: Int -> [[Int]]\nanswer n = distribute (div n 2) [1..div (n^2) 2]\n\ndistribute :: Int -> [Int] -> [[Int]]\ndistribute _ [] = []\ndistribute k xs = [ps++ps']++(distribute k $ drop k xs) where\n\tps = take k xs\n\tps' = map (\\x -> (k*2)^2-x+1) ps\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine :: IO Int\n let n2 = n*n\n sol = concat [[j,n2-j+1] | j <- [1..(n2 `div` 2 )]]\n println n 1 sol\n\nprintln _ _ [] = return ()\nprintln n i (x:xs) = do\n if rem i n == 0 \n then print x\n else putStr $ show x ++ \" \"\n println n (i+1) xs\n "}, {"source_code": "import Data.List\n\nsolve :: Int -> [[Int]]\nsolve n = take n $ map (concatMap pairToList) $ splitIn (n `div` 2) xs\n where m = n ^ 2\n xs = zip [1 .. m] (reverse [1 .. m])\n \npairToList :: (a, a) -> [a]\npairToList (x, y) = [x, y]\n\nsplitIn :: Int -> [a] -> [[a]]\nsplitIn _ [] = []\nsplitIn n xs = let (left, right) = splitAt n xs\n in left:splitIn n right\n\nmain = interact $ unlines . map (unwords . map show) . solve . read\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= mapM_ (putStrLn . unwords . map show) . solve\n\nsolve :: Integer -> [[Integer]]\nsolve n = [ [ k, k + n .. a `div` 2 - n + k ] ++ [ b - k, b + n - k .. a + 1 - k ] | k <- [1..n] ]\n where a = n * n; b = a - a `div` 2 + n + 1\n"}, {"source_code": "import Data.List (unfoldr)\n\nmain :: IO ()\nmain = readLn >>= mapM_ (putStrLn . unwords . map show) . solve\n\nsolve :: Int -> [[Int]]\nsolve n = map concat $ splitN (n `div` 2) $ map (\\x -> [ x, n * n + 1 - x ]) [1 .. n * n `div` 2]\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . map (unwords . map show) . solve . read\nsolve n = transpose $ zipWith ($) (cycle [id,reverse]) $ chunksOf n [1..n^2]\nchunksOf n = go where\n go [] = []\n go xs = l : go r where (l,r) = splitAt n xs\n"}, {"source_code": "import Data.List (intercalate)\n\nstring2int str = (read str :: Int)\nget_nxn x = [1..x^2]\n\nsolve n [] = []\nsolve n a = do\n (take n a) ++ (take n $ reverse a) ++ (solve n $ (reverse $ drop n $ reverse $ drop n a))\n\nmain :: IO ()\nmain = do\n str <- getLine\n putStrLn $ intercalate \" \" (map show $ solve (floor ((fromIntegral (string2int str)) / (fromIntegral (2 :: Int)))) $ (get_nxn $ string2int str))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n let xxs = solve n\n mapM_ (putStrLn . intercalate \" \" . map show) xxs\n \nsolve :: Int -> [[Int]]\nsolve n = map (\\x -> [x, n^2-x+1]) [1 .. n^2 `div` 2]\n"}, {"source_code": "\nsolve :: Int -> [[Int]]\nsolve n = [ solveLine n i | i <- [1..n] ]\n\nsolveLine n i = [ 1 + ((i+j) `mod` n) + (j-1) * n | j <- [1..n]]\n\nmain :: IO ()\nmain = do nSt <- getLine\n let res = solve (read nSt :: Int)\n resSt = map (\\ls -> (map (\\x -> (show x)) ls)) res\n putStr $ unlines (map unwords resSt)\n \n"}, {"source_code": "import Data.List\nmain=interact$unlines.map(unwords.map show).f.read\nf :: Int -> [[Int]]\nf n=transpose.zipWith($)(cycle [id,reverse]) $ slices n[1..n*n]\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nchunks x [] = []\nchunks x n = (take x n) : (chunks x ( drop x n))\n\naltrev [] = []\naltrev (x:y:zs) = (x:(reverse y) : (altrev zs))\n\nmyprint x1 = putStrLn $ intercalate \" \" $ map show x1\n\t\n\nmain= do\n\tn<- read <$> getLine ::IO Int\n\tlet x= transpose $ altrev $ chunks n [1..n*n]\n\tmapM_ myprint x\n\t \n\t "}, {"source_code": "-- Candy bags\n\n\nmain :: IO ()\nmain = fmap read getLine >>= putStrLn . prettyPrint . rush\n\nprettyPrint :: [[Int]] -> String\nprettyPrint = unlines . map (unwords . map show)\n\nrush :: Int -> [[Int]]\nrush n = map f [1..n]\n where f x = [((x - 1)*h + 1)..(x*h)] ++ [(ns - x * h + 1)..(ns - (x - 1) * h)]\n h = n `div` 2\n ns = n * n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let ps = zip [1..n] $ reverse [n+1..n^2]\n\n putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) ps\n"}, {"source_code": "import Data.List\nimport Control.Monad\nf n = zipWith (\\a b -> show a ++ \" \" ++ show b) [n,n-1..1] [n+1..]\nmain = mapM_ putStrLn . f =<< (readLn :: IO Int)"}, {"source_code": "import Data.List\n\nsolve n = (uncurry zip) ys\n where m = n ^ 2\n xs = splitAt n [1 .. m]\n ys = (fst xs, reverse $ snd xs)\n \nshowPair (x, y) = show x ++ \" \" ++ show y\n\nmain = interact $ unlines . map showPair . solve . read\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= mapM_ (putStrLn . unwords . map show) . solve\n\nsolve :: Integer -> [[Integer]]\nsolve n = [ [ 1, 3 .. (n * n - 2) `div` 2 ] ++ [ (n * n + 4) `div` 2, (n * n + 4) `div` 2 + 2 .. n * n ],\n [ 2, 4 .. (n * n ) `div` 2 ] ++ [ (n * n + 2) `div` 2, (n * n + 2) `div` 2 + 2 .. n * n - 1 ] ]\n"}], "src_uid": "0ac2a0954fe43d66eac32072c8ea5070"} {"source_code": "{-# LANGUAGE TypeApplications, BlockArguments, OverloadedLists #-}\r\n\r\nmodule Main where\r\n\r\nimport Prelude hiding ( drop, length, take, zipWith )\r\nimport Data.Maybe\r\nimport Data.Functor\r\nimport Data.Sequence hiding ( replicateM )\r\nimport Control.Monad\r\nimport Control.Monad.State\r\n\r\ncalc :: Seq Int -> Int\r\ncalc a = sum $ zipWith (\\x y -> abs (x - y)) a (drop 1 a)\r\n\r\ncalc' :: Int -> Int -> Int\r\ncalc' x y = abs (x - y)\r\n\r\nswap :: Int -> Seq Int -> Seq Int -> (Seq Int, Seq Int)\r\nswap n a b =\r\n ( take n a >< [fromJust $ b !? n] >< drop (n + 1) a\r\n , take n b >< [fromJust $ a !? n] >< drop (n + 1) b\r\n )\r\n\r\naB :: State (Seq Int, Seq Int, Int) Int\r\naB = get >>= \\(a, b, i) -> if i == length a - 1\r\n then return $ calc a + calc b\r\n else\r\n let [t1, t1', t2, t2'] = map fromJust [a !? i, a !? (i + 1), b !? i, b !? (i + 1)]\r\n in if calc' t1 t1' + calc' t2 t2' <= calc' t1 t2' + calc' t2 t1'\r\n then put (a, b, i + 1) >> aB\r\n else let (a', b') = swap (i + 1) a b \r\n in put (a', b', i + 1) >> aB\r\n\r\ngetInput :: Int -> IO [(Seq Int, Seq Int)]\r\ngetInput = flip replicateM $ getLine >> do\r\n a <- getLine <&> words <&> map (read @Int) <&> fromList\r\n b <- getLine <&> words <&> map (read @Int) <&> fromList\r\n return (a, b)\r\n\r\nmain :: IO ()\r\nmain = getLine <&> read @Int \r\n >>= getInput \r\n >>= mapM_ (\\(a, b) -> print $ evalState aB (a, b, 0))\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: (Integral a) => C.ByteString -> a\nparseInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: (Integral a) => IO [a]\ngetInts = map parseInt . C.words <$> C.getLine\n\ncalc :: [(Int64, Int64)] -> Int64\ncalc [] = 0\ncalc (_ : []) = 0\ncalc ((a1, b1) : (a2, b2) : rest) = current + calc ((a2, b2) : rest)\n where current = min (abs (a1 - a2) + abs (b1 - b2)) (abs (a1 - b2) + abs (a2 - b1))\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n _ <- C.getLine\n as <- getInts\n bs <- getInts\n return $ int64Dec (calc $ zip as bs) <> charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "94ec011dc830661c226bd860b9d70de5"} {"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- compab.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input-large.txt | time ./a.out)\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input-large-7.txt | time ./a.out)\n\nimport Prelude ((+), error)\nimport qualified System.IO as S\nimport Control.Arrow\nimport qualified Control.Monad as M\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Eq\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport Data.List ((++))\nimport qualified Data.List as L\nimport Data.Ord\n\nmapM_ = M.mapM_\nputStrLn = S.putStrLn\nreplicateM = M.replicateM\n\ndropSpace = B.dropWhile isSpace\n\nri :: S.IO [Int]\nri = readInts <$> B.getLine\n where\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n\nshowYN False = \"NO\"\nshowYN True = \"YES\"\n\nmain :: S.IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n _n <- B.getLine\n replicateM 2 ri\n mapM_ (putStrLn.showYN.solve) tcs\n\nsolve [as, bs] = L.and (L.zipWith isPossible as bbs)\n where\n bbs = L.zip bs (L.tail bs ++ [L.head bs])\n\n isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))\nsolve _ =\n error \"Bad input reading\"\n", "positive_code": [{"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- compab.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input-large.txt | time ./a.out)\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input-large-7.txt | time ./a.out)\n\nimport Prelude hiding (getLine)\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\n\nri = readInts <$> B.getLine\n where\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n dropSpace = B.dropWhile isSpace\n\nshowYN False = \"NO\"\nshowYN True = \"YES\"\n\nmain :: IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n _n <- B.getLine\n replicateM 2 ri\n mapM_ (putStrLn.showYN.solve) tcs\n\nsolve [as, bs] = and (zipWith isPossible as bbs)\n where\n bbs = zip bs (tail bs ++ [head bs])\n\n isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))\nsolve _ =\n error \"Bad input reading\"\n"}], "negative_code": [{"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- compab.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input-large.txt | time ./a.out)\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs && set -o pipefail && cat -- input-large-7.txt | time ./a.out)\n\nimport Prelude ((+), error)\nimport qualified System.IO as S\nimport Control.Arrow\nimport qualified Control.Monad as M\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Eq\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport Data.List ((++))\nimport qualified Data.List as L\nimport Data.Ord\n\nmapM_ = M.mapM_\nputStrLn = S.putStrLn\nreplicateM = M.replicateM\n\ndropSpace = B.dropWhile isSpace\n\nri :: S.IO [Int]\nri = readInts <$> B.getLine\n where\n readInts = L.reverse . L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n\nshowYN False = \"NO\"\nshowYN True = \"YES\"\n\nmain :: S.IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n _n <- B.getLine\n replicateM 2 ri\n mapM_ (putStrLn.showYN.solve) tcs\n\nsolve [as, bs] = L.and (L.zipWith isPossible as bbs)\n where\n bbs = L.zip bs (L.tail bs ++ [L.head bs])\n\n isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))\nsolve _ =\n error \"Bad input reading\"\n"}, {"source_code": "\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- compab.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\nimport System.IO\nimport Control.Monad\n\nri = map read . words <$> getLine :: IO [Int]\n\nshowYN False = \"NO\"\nshowYN True = \"YES\"\n\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n [_n] <- ri\n replicateM 2 ri\n mapM_ (putStrLn.showYN.solve) tcs\n\nsolve [as, bs] = and (zipWith isPossible as bbs)\n where\n bbs = zip bs (tail bs ++ [last bs])\n\n isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))\n"}], "src_uid": "9851ff47c77e13f62be1edaf3d74c4ad"} {"source_code": "import Data.List\n\nf (p, n, p', n') x | (x == 1) = (p + 1, n, p + p', n + n')\n | otherwise = (n, p + 1, p + p', n + n')\n\ntask x = show (n + n') ++ \" \" ++ show (p + p') where (p, n, p', n') = foldl' f (0, 0, 0, 0) x\n \nmain = getContents >>= putStr . task . map (\\i -> signum $ read i::Integer) . words . head . tail . lines", "positive_code": [{"source_code": "solve :: [Integer] -> [Integer]\nsolve array = let runDP [] res _ = res\n runDP (x:xs) [prevN, prevP] [negTllLst, posTllLst] = \n let [negTllCur, posTllCur] = if x > 0 then [negTllLst, posTllLst + 1]\n else [posTllLst + 1, negTllLst]\n in runDP xs [prevN + negTllCur, prevP + posTllCur] [negTllCur, posTllCur]\n in runDP array [0,0] [0,0]\n\nmain :: IO ()\nmain = interact $ (++ \"\\n\") . unwords . map show . solve . map read . tail . words"}, {"source_code": "{-\n Copyright (c) 2019 Islam Omar\n-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE CPP #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-Ofast #-}\n\nimport Control.Monad (foldM, forM, forM_, join, replicateM_, when)\nimport Control.Monad.ST\nimport Control.Monad.State.Strict\n\n-- import Data.Array.MArray.Safe ( MArray )\n-- import qualified Data.Array.MArray.Safe as MA\nimport Data.Array.ST.Safe (STArray)\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bits\nimport Data.Functor\nimport Data.Graph (Graph)\nimport qualified Data.Graph as G\nimport Data.Int (Int64)\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.List as L\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.STRef\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport System.IO\nimport Text.Read\n--- DEBUGGING\n#define DEBUG(x) dump di \"x\" x\ndump di str a\n | \"demo.hs\" `L.isSuffixOf` __FILE__ =\n modifySTRef' di (L.insert (str, a)) >> return Nothing\n | otherwise = return Nothing\n\nprintDump lst\n | \"demo.hs\" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing\n | otherwise = return Nothing\n\nreadNumList :: (Num a, Read a) => IO [a]\nreadNumList = map read . words <$> getLine\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = read <$> getLine\n\n\nreadNumListLn :: (Num a, Read a) => Int -> IO [a]\nreadNumListLn n = doGetList n []\n where\n doGetList 0 l = return l\n doGetList n l = do\n i <- readNum\n doGetList (n - 1) (l ++ [i])\n\n-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]\nsolve di n nums = do\n pos <- newSTRef 0\n neg <- newSTRef 0\n ansp <- newSTRef 0\n ansn <- newSTRef 0\n let updateVal v =\n if v > 0\n then modifySTRef' pos (+ 1)\n else do\n p <- readSTRef pos\n n <- readSTRef neg\n writeSTRef neg (p + 1)\n writeSTRef pos n\n let compute v = do\n updateVal v\n p <- readSTRef pos\n nn <- readSTRef neg\n DEBUG(p)\n DEBUG(nn)\n modifySTRef' ansp (+p)\n modifySTRef' ansn (+nn)\n \n forM_ nums compute\n p <- readSTRef ansp\n n <- readSTRef ansn\n let ans = (n,p)\n -- solution\n -- readSTRef =<< newSTRef ans\n return ans\n\nmain :: IO ()\nmain = do\n n <- readNum :: IO Int\n -- Read Inputs\n nums <- readNumList :: IO [Int]\n let computation =\n runST $ do\n let dubeg_info =\n [] :: (Num a) =>\n [(String, a)]\n --- list of tuples (string value)\n di <- newSTRef dubeg_info\n ans <- solve di n nums\n tmp <- readSTRef di\n let lst = (ans, tmp)\n readSTRef =<< newSTRef lst\n -- get solution\n let (n, p) = fst computation\n let debug_info = snd computation\n printDump debug_info\n -- print result\n putStrLn $ show n ++ \" \" ++ show p\n"}], "negative_code": [{"source_code": "solve :: [Int] -> [Int]\nsolve array = let runDP [] res _ = res\n runDP (x:xs) [prevN, prevP] [negTllLst, posTllLst] = \n let [negTllCur, posTllCur] = if x > 0 then [negTllLst, posTllLst + 1]\n else [posTllLst + 1, negTllLst]\n in runDP xs [prevN + negTllCur, prevP + posTllCur] [negTllCur, posTllCur]\n in runDP array [0,0] [0,0]\n\nmain :: IO ()\nmain = interact $ (++ \"\\n\") . unwords . map show . solve . map read . tail . words"}, {"source_code": "import Data.List\n\nf (p, n, p', n') x | (x == 1) = (p + 1, n, p + p', n + n')\n | otherwise = (n, p + 1, p + p', n + n')\n\ntask x = show (n + n') ++ \" \" ++ show (p + p') where (p, n, p', n') = foldl' f (0, 0, 0, 0) x\n \nmain = getContents >>= print . task . map (\\i -> signum $ read i::Integer) . words . head . tail . lines"}, {"source_code": "{-\n Copyright (c) 2019 Islam Omar\n-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE CPP #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-Ofast #-}\n\nimport Control.Monad (forM, forM_, join, replicateM_, when)\nimport Control.Monad.ST\nimport Control.Monad.State.Strict\n\n-- import Data.Array.MArray.Safe ( MArray )\n-- import qualified Data.Array.MArray.Safe as MA\nimport Data.Array.ST.Safe (STArray)\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bits\nimport Data.Functor\nimport Data.Graph (Graph)\nimport qualified Data.Graph as G\nimport Data.Int (Int64)\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.List as L\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.STRef\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport System.IO\nimport Text.Read\n--- DEBUGGING\n#define DEBUG(x) dump di \"x\" x\ndump di str a\n | \"demo.hs\" `L.isSuffixOf` __FILE__ =\n modifySTRef' di (L.insert (str, a)) >> return Nothing\n | otherwise = return Nothing\n\nprintDump lst\n | \"demo.hs\" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing\n | otherwise = return Nothing\n\nreadNumList :: (Num a, Read a) => IO [a]\nreadNumList = map read . words <$> getLine\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = read <$> getLine\n\n\nreadNumListLn :: (Num a, Read a) => Int -> IO [a]\nreadNumListLn n = doGetList n []\n where\n doGetList 0 l = return l\n doGetList n l = do\n i <- readNum\n doGetList (n - 1) (l ++ [i])\n\n-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]\nsolve di n nums = do\n DEBUG (n)\n i <- newSTRef 0\n pos <- newSTRef 0\n neg <- newSTRef 0\n ansp <- newSTRef 0\n ansn <- newSTRef 0\n let updateVal v =\n if v > 0\n then modifySTRef' pos (+ 1)\n else do\n p <- readSTRef pos\n n <- readSTRef neg\n writeSTRef neg (p + 1)\n writeSTRef pos n\n writeSTRef i 0\n let loop = do\n it <- readSTRef i\n let v = nums !! it\n updateVal v\n p <- readSTRef pos\n nn <- readSTRef neg\n DEBUG (nn)\n DEBUG (it)\n DEBUG (p)\n modifySTRef' ansp (+p)\n modifySTRef' ansn (+nn)\n modifySTRef' i (+1)\n if it+1 >= n then (return ())\n else loop\n\n loop\n p <- readSTRef ansp\n n <- readSTRef ansn\n let ans = (n,p)\n -- solution\n -- readSTRef =<< newSTRef ans\n return ans\n\nmain :: IO ()\nmain = do\n n <- readNum :: IO Int\n -- Read Inputs\n nums <- readNumList :: IO [Int]\n print nums\n let computation =\n runST $ do\n let dubeg_info =\n [] :: (Num a) =>\n [(String, a)]\n --- list of tuples (string value)\n di <- newSTRef dubeg_info\n ans <- solve di n nums\n tmp <- readSTRef di\n let lst = (ans, tmp)\n readSTRef =<< newSTRef lst\n -- get solution\n let (n, p) = fst computation\n let debug_info = snd computation\n printDump debug_info\n -- print result\n putStrLn $ show n ++ \" \" ++ show p\n"}], "src_uid": "78d3acc3ade53f488739a59100bfcebd"} {"source_code": "import Prelude\nimport Control.Monad\n\nstr2Ints str = [read x::Int | x <- words str]\ngetLineN n = replicateM n getLine\n\ninf::Int\ninf = floor (1e9+7)\n\ni2b x = if x /= 0 then 1 else 0\n\nf n x y d = if z == inf then -1 else z\n where z = minimum [if x`rem`d == y`rem`d then abs(x-y)`quot`d else inf,\n if 0 == y`rem`d then y`quot`d + x`quot`d + i2b(x`rem`d) else inf,\n if (n-1)`rem`d == y`rem`d then (n-1-y)`quot`d + (n-1-x)`quot`d + i2b((n-1-x)`rem`d) else inf]\n\nmain = do\n input<-getLine;\n lines<-getLineN (read input::Int)\n let l = map str2Ints lines\n let ans = foldr (\\x acc -> (f (x!!0) (x!!1 - 1) (x!!2 - 1) (x!!3)):acc) [] l\n mapM (putStrLn.show) ans", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Map.Strict as Map\n\ninf::Int\ninf = 1000000005\n\ntoint s = (read s) :: Int\n\ndoall::[Int]->String\ndoall [] = \"\"\ndoall (n:xx:yy:d:ss) =\n let x = xx-1 in\n let y = yy-1 in\n if (mod x d == mod y d) then\n show(div (abs (x-y)) d)++\"\\n\"++(doall ss)\n else\n let r1 =\tif mod y d == 0 then div x d + div y d + 1 else inf in\n let r2 = if mod y d == mod (n-1) d then div (n-1-x) d + div (n-1-y) d + 1 else inf in\n let r = min r1 r2 in\n if r == inf then \"-1\\n\"++(doall ss) else show(r)++\"\\n\"++(doall ss)\n\nsolve::String -> String\nsolve ss =\n let _:s = map toint $ words ss in\n doall s\n\nmain = do\n interact $ solve"}], "negative_code": [{"source_code": "import Prelude\nimport Control.Monad\n\nstr2Ints str = [read x::Int | x <- words str]\ngetLineN n = replicateM n getLine\n\ninf::Int\ninf = floor (1e9+7)\n\ni2b x = if x /= 0 then 1 else 0\n\nf n x y d = if z == inf then -1 else z\n where z = minimum [if x`rem`d == y`rem`d then abs(x-y)`quot`d else inf,\n if 0 == y`rem`d then y`quot`d + x`quot`d + i2b(x`rem`d) else inf,\n if (n-1)`quot`d == y`rem`d then (n-1-y)`quot`d + (n-1-x)`quot`d + i2b((n-1-x)`rem`d) else inf]\n\nmain = do\n input<-getLine;\n lines<-getLineN (read input::Int)\n let l = map str2Ints lines\n let ans = foldr (\\x acc -> (f (x!!0) (x!!1 - 1) (x!!2 - 1) (x!!3)):acc) [] l\n mapM (putStrLn.show) ans"}], "src_uid": "474f29da694929a64eaed6eb8e4349c3"} {"source_code": "import Data.List\nmain=interact$show.length.concat.drop 1.init.group.sort.map((+0).read).tail.words\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n nS <- getLine\n strengthValuesS <- getLine\n let n = read nS :: Int\n strengthValues = map (read :: String -> Int) (words strengthValuesS)\n list = group (sort strengthValues)\n print (max 0 (n - (length (head list)) - (length (last list))))\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nmain = do\n n <- readLn :: IO Int\n a <- fmap (map read) $ fmap words $ getLine :: IO [Int]\n let min0 = minimum a\n let max0 = maximum a\n print $ length $ filter ((&&) <$> (> min0) <*> (< max0)) a\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n a <- return . map length . group . sort . map (read :: String -> Int) . words =<< getLine\n print $ if length a < 2 then 0 else sum $ init $ tail a"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nimport Data.List\nmain = interact $ show . length . concat . drop 1 . init . group . sort @Int . map read . tail . words\n"}, {"source_code": "g mini maxi a = length $ filter (\\x -> mini < x && x < maxi) a\nf a = g (minimum a) (maximum a) a\nmain=interact$show.f.map ((+0).read).tail.words\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n l <- getLine >>= return . map read . words :: IO [Int]\n let m = minimum l\n let ma = maximum l\n print $ length $ filter (\\x -> x > m && x < ma) l"}, {"source_code": "import Data.List\nmain = do\n getLine\n a <- getLine >>= return.map read.words :: IO [Integer]\n print.length.filter (\\x -> x > minimum a && x < maximum a) $ a\n \n"}, {"source_code": "main = do\n i <- getLine\n let n = read i :: Int\n j <- getLine\n let inputs = map (\\x -> read x :: Integer) $ words j\n let max_ = maximum inputs\n let min_ = minimum inputs\n let max_count = length $ filter (==max_) inputs\n let min_count = length $ filter (==min_) inputs\n if max_ == min_\n then print 0\n else print $ n - max_count - min_count\n"}], "negative_code": [{"source_code": "import Data.List.Split\ngetInt :: IO Integer\ngetInt = readLn\n\n\nsolve n as =\n length.filter (\\x -> x > minimum as && x < maximum as) $ as\n \nmain = do\n n <- getInt\n a <- getLine\n print.solve n $ Data.List.Split.splitOn \" \" a\n \n"}, {"source_code": "import Data.List.Split\ngetInt :: IO Int\ngetInt = readLn\n\n\nsolve n as =\n length.filter (\\x -> x > minimum as && x < maximum as) $ as\n \nmain = do\n n <- getInt\n a <- getLine\n print.solve n $ Data.List.Split.splitOn \" \" a\n \n"}, {"source_code": "import Data.List\nimport Data.List.Split\ngetInt :: IO Int\ngetInt = readLn\n\n\nsolve n as =\n length.filter (\\x -> x > head bs && x < last bs) $ bs\n where bs = Data.List.sort as\n \nmain = do\n n <- getInt\n a <- getLine\n print.solve n $ Data.List.Split.splitOn \" \" a\n \n"}, {"source_code": "main = do\n i <- getLine\n let n = read i :: Int\n j <- getLine\n let inputs = map (\\x -> read x :: Integer) $ words j\n let max_count = length $ filter (==maximum inputs) inputs\n let min_count = length $ filter (==minimum inputs) inputs\n if max_count == min_count\n then print 0\n else print $ n - max_count - min_count\n"}, {"source_code": "main = do\n i <- getLine\n let n = read i :: Int\n j <- getLine\n let inputs = map (\\x -> read x :: Integer) $ words j\n let max_count = length $ filter (==maximum inputs) inputs\n let min_count = length $ filter (==minimum inputs) inputs\n print $ n - max_count - min_count\n"}], "src_uid": "acaa8935e6139ad1609d62bb5d35128a"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.STRef(STRef, newSTRef, readSTRef, writeSTRef)\r\nimport Data.Array.ST(runSTArray, STArray)\r\nimport Data.Array.IO(IOArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, filterM, forM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\ntype Output = (Integer, Integer) \r\n\r\nsolve :: Integer -> Integer -> Integer -> Output\r\nsolve a b c = let (x, y) = result (a-c+1) (b-c+1) in (expo 10 (c-1) * x, expo 10 (c-1) * y)\r\n\r\nresult a b = (expo 10 (a-1) + 1, expo 10 (b-1))\r\n\r\n\r\nexpo :: Integral n => n -> n -> n\r\nexpo n x | x < 0 = error \"expo n x : x < 0\"\r\nexpo n x \r\n\t| x == 0 = 1\r\n\t| otherwise = k * k * if mod x 2 == 0 then 1 else n\r\n\twhere k = expo n (div x 2)\r\n\r\n\r\nplotResult :: Output -> IO ()\r\nplotResult (a, b) = putStrLn $ show a ++ \" \" ++ show b \r\n\r\n\r\nmain :: IO ()\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[a, b, c] <- getLine >>= return . (fmap read) . words :: IO [Integer] \r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve a b c\r\n\treturn ()\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [a, b, c] <- getInts\n let f x p l = head $ dropWhile (\\x -> length (show x) < l) $ iterate (*p) x\n x3 = f 1 2 c\n x1 = f x3 2 a\n x2 = f x3 3 b\n C.putStrLn $ C.pack $ show x1 ++ \" \" ++ show x2\n"}], "negative_code": [], "src_uid": "04330cb392bcfd51d1acffd72c8004cb"} {"source_code": "\n\npress :: Bool -> [Int] -> Bool\n\npress n [a] = (odd a)\n\npress n a = \n ((odd (head a)) /= (n && (press n (tail a))))\n\nmain = do\n [n,_] <- map (read :: String -> Int) . words <$> getLine\n a <- map (read :: String -> Int) . words <$> getLine\n putStrLn $ if press (odd n) (reverse a) then \"odd\" else \"even\"\n\n\n", "positive_code": [{"source_code": "import Data.Char\n\nmodpower x = 1 : (cycle $ case x of\n 1 -> [1]\n 2 -> [2,4,8,6]\n 3 -> [3,9,7,1]\n 4 -> [4,6]\n 5 -> [5]\n 6 -> [6]\n 7 -> [7,9,3,1]\n 8 -> [8,4,2,6]\n 9 -> [9,1]\n 0 -> [0,0])\n\n\nget acc (a:b:as) = if b == ' ' then get (digitToInt a : acc) as else get acc (b:as) \nget acc as = ((digitToInt $ last as) : acc) \n\n\nmain = do \n [n,_] <- map (read :: String -> Int) . words <$> getLine\n a <- get [] <$> getLine\n let b = take (length a) $ modpower (n`mod`10)\n c = sum $ zipWith (*) a b \n putStrLn $ if even c then \"even\" else \"odd\"\n "}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n [b,k] <- map read . words <$> getLine\n as <- take k . unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let ans | odd b = foldl xor False $ map odd as\n | otherwise = odd $ last as\n putStrLn $ if ans then \"odd\" else \"even\"\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n"}, {"source_code": "main = interact $ ([\"odd\",\"even\"] !!) . fromEnum . solve . map read . words\nsolve (b:k:as) | even b = even (last as)\n | otherwise = even (sum as)\n"}, {"source_code": "import Text.Printf\nimport Control.Monad\n\nmain = do\n [b, k] <- fmap (map read . words) getLine\n ls <- fmap (map read . reverse . words) getLine\n putStrLn . oddOrEven $ solve b ls\n\nsolve b ls@(x:_)\n | even b = x\n | otherwise = sum $ map (`rem` 2) ls\n\noddOrEven x\n | even x = \"even\"\n | otherwise = \"odd\"\n"}, {"source_code": "\n\npress :: [Int] -> Int -> Int\n\npress [] n = 0\n\npress a n = \n ((head a) +(n * (press (tail a) n))) `mod` 2\n\nmain = do\n [n,_] <- map (read :: String -> Int) . words <$> getLine\n a <- map (read :: String -> Int) . words <$> getLine\n putStrLn $ if even (press (reverse a) n) then \"even\" else \"odd\"\n\n\n"}, {"source_code": "import Control.DeepSeq\n\nmain = do\n [o, n] <- fmap (fmap read . words) getLine\n s <- fmap (fmap read . words) getLine\n let (r, _) = foldl (\\(s, c) x -> ((force s :: Int) + x * o ^ c, c - 1)) (0, n - 1) s\n putStrLn $ if even r then \"even\" else \"odd\""}, {"source_code": "main = interact $ process . map read . words\nprocess :: [Int] -> String\nprocess (b:k:a) = if ev then \"even\" else \"odd\" where\n ev | even b = even $ last a\n | otherwise = even $ sum a"}, {"source_code": "solve b k as | b `mod` 2 == 0 = if (last as) `mod` 2 == 0 then \"even\" else \"odd\"\n | otherwise = if s `mod` 2 == 0 then \"even\" else \"odd\"\n where s = sum as\n\nparseInput input = ([b, k], as) where\n ls = lines input\n [b, k] = map read $ words $ head ls :: [Int]\n as = map read $ words $ last ls :: [Int]\n\nmain = do\n input <- getContents\n let ([b, k], as) = parseInput input\n putStrLn $ solve b k as\n"}], "negative_code": [], "src_uid": "ee105b664099808143a94a374d6d5daa"} {"source_code": "import Data.List\nimport Control.Applicative\ndefault (Int)\nf r g m | g == 1 = sortBy (flip compare) $ \n foldl (\\a b -> (*) <$> a <*> (scanl (*) 1 b)) [1] $ (group $ reverse r)\n | g `mod` m == 0 = f (m:r) (g `div` m) m\n | g < m^2 = f r g g\n | otherwise = f r g (m + 1)\nmain = do\n [a, b] <- (map read . words) `fmap` getLine :: IO [Int]\n n <- read `fmap` getLine\n let divs = f [] (gcd a b) 2\n mapM_ (\\_ -> do\n [low, high] <- (map read . words) `fmap` getLine\n case takeWhile (>= low) $ dropWhile (> high) divs of\n h:_ -> print h\n [] -> print (-1)) [1..n]\n", "positive_code": [{"source_code": "import Data.Maybe\n\nmaybeMaximum [] = Nothing\nmaybeMaximum xs = Just $ maximum xs\n\nsolve a b queries =\n\t\tmap process queries\n\twhere\n\t\td = gcd a b\n\t\tis = takeWhile (\\i -> i*i <= d) [1..]\n\t\tds = concat [[i, d `div` i] | i <- is, d `mod` i == 0]\n\n\t\tprocess (l, r) = maybeMaximum $ filter (\\d -> l <= d && d <= r) ds\n\nreadWords = map read . words\n\nmain = do\n\t[a, b] <- readWords `fmap` getLine\n\t_ <- getLine\n\tqueries <- (map ((\\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents\n\tputStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries\n\n"}, {"source_code": "import Data.Maybe\n\nmaybeMaximum [] = Nothing\nmaybeMaximum xs = Just $ maximum xs\n\nsolve a b queries =\n\t\tmap process queries\n\twhere\n\t\td = gcd a b\n\t\tis = takeWhile (\\i -> i*i <= d) [1..]\n\t\tds = concat [[i, d `div` i] | i <- is, d `mod` i == 0]\n\n\t\tprocess (l, r) = maybeMaximum $ filter (\\d -> l <= d && d <= r) ds\n\nreadWords = map read . words :: String -> [Int]\n\nmain = do\n\t[a, b] <- readWords `fmap` getLine\n\t_ <- getLine\n\tqueries <- (map ((\\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents\n\tputStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries\n\n"}, {"source_code": "import Data.Maybe\n\nmaybeMaximum [] = Nothing\nmaybeMaximum xs = Just $ maximum xs\n\nsolve a b queries =\n\t\tmap process queries\n\twhere\n\t\td = gcd a b\n\t\tis = takeWhile (\\i -> i*i <= d) [1..]\n\t\tds = concat [[i, d `div` i] | i <- is, d `mod` i == 0]\n\n\t\tprocess (l, r) = maybeMaximum $ filter (\\d -> l <= d && d <= r) ds\n\nreadWords = map read . words\n\nmain = do\n\t[a, b] <- readWords `fmap` getLine\n\t_ <- getLine\n\tqueries <- (map ((\\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents\n\tputStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries\n\n"}, {"source_code": "\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\n \npfactors n toTest@(x:xs) \n | n <= 1 = []\n | x * x > n = [n]\n | n `mod` x == 0 = x:pfactors (n `div` x) toTest\n | otherwise = pfactors n xs\n\ndivisorsFromF xs = sort . map product . sequence . map (scanl (*) 1) . group $ sort xs\n\nreadI = fst . fromJust . BS.readInt\n\n--return the of value in a sorted array LEQ than x\nsolve :: UArray Int Int -> Int -> Maybe Int\nsolve sorted x = if sorted ! pos <= x then Just (sorted ! pos) else Nothing\n where\n bnds = bounds sorted\n bsearch lo hi\n | lo >= hi = lo\n | sorted ! (mid+1) <= x = bsearch (mid + 1) hi\n | otherwise = bsearch lo mid\n where\n mid = (lo + hi) `div` 2\n pos = bsearch (fst bnds) (snd bnds)\n\nmain = do\n [x, y] <- map read . words <$> getLine :: IO [Int]\n let g = gcd x y\n let factors = pfactors g [2..]\n let divisors = divisorsFromF factors\n let arr = listArray (1, length divisors) divisors :: UArray Int Int\n q <- read <$> getLine :: IO Int\n lines <- map (map readI . BS.words) . take q . BS.lines <$> BS.getContents\n forM_ lines $ \\[low, high] -> do\n let val = solve arr high\n let answer = if isJust val && fromJust val >= low then fromJust val else -1\n print answer\n"}, {"source_code": "import Control.Monad\nimport Data.List\n-- import Debug.Trace\n\nprimes = 2 : sieve [3,5..]\n where\n sieve (x:xs) = x : sieve [y | y <- xs, y `mod` x /= 0]\n\nsolve xs = do\n [l, h] <- fmap (map read . words) getLine\n return $ case dropWhile (> h) xs of\n [] -> -1\n (x:_)\n | x < l -> -1\n | otherwise -> x\n\ngen x =\n rec 1 $ glue [] $ factors [] primes x\n where\n rec cur [] = [cur]\n rec cur ((x, c):xs) =\n [ x^p | p <- [0..c]] >>= \\v -> rec (cur*v) xs\n glue res [] = reverse res\n glue [] (y:ys) = glue [(y, 1)] ys\n glue res@((x, c):xs) (y:ys)\n | x == y = glue ((x, c+1):xs) ys\n | otherwise = glue ((y, 1):res) ys\n factors res (p:ps) x\n | p*p > x = reverse $ x:res\n | x `mod` p == 0 = factors (p:res) (p:ps) (x`div`p)\n | otherwise = factors res ps x\n\nmain = do\n [a, b] <- fmap (map read . words) getLine\n n <- fmap read getLine\n let xs = reverse $ sort $ gen $ gcd a b\n xs `seq` mapM_ print =<< replicateM n (solve xs)\n"}, {"source_code": "import Data.List\n\ngetdivisors :: Int -> [Int]\ngetdivisors n = sort $ [x | x <- xs , mod n x == 0 ] ++ [ div n x | x <- xs , mod n x == 0 ]\n where \n sq = truncate $ sqrt $ fromIntegral n \n xs = [1..sq]\n\nxfind :: Int -> Int -> [Int] -> Int -> Int -> Int\nxfind s e xs a b \n | s > e = -1\n | x == False = xfind (m+1) e xs a b \n | y == False = xfind s (m-1) xs a b \n | otherwise = max (xs!!m) (xfind (m+1) e xs a b) \n where \n m = div (s+e) 2\n x = (xs!!m) >= a\n y = ( xs!!m) <= b \n\nreadInt :: String -> Int\nreadInt str = read str :: Int\n\ndoit :: Int -> [Int] -> IO()\ndoit 0 xs = return ()\ndoit t xs = do \n ws <- getLine\n let [a,b] = map readInt (words ws)\n print $ xfind 0 ((length xs)-1) xs a b\n doit (t-1) xs\n \n\nmain :: IO()\nmain = do \n ws <- getLine \n let [a,b] = map readInt (words ws) \n let xs = getdivisors $ gcd a b \n t <- getLine\n doit (readInt t) xs \n"}], "negative_code": [{"source_code": "import Data.Maybe\n\nmaybeMaximum [] = Nothing\nmaybeMaximum xs = Just $ maximum xs\n\nsolve a b queries =\n\t\tmap process queries\n\twhere\n\t\td = gcd a b\n\t\tis = takeWhile (\\i -> i*i <= d) [1..]\n\t\tds = concat [[d, d `div` i] | i <- is, d `mod` i == 0]\n\n\t\tprocess (l, r) = maybeMaximum $ filter (\\d -> l <= d && d <= r) ds\n\nreadWords = map read . words\n\nmain = do\n\t[a, b] <- readWords `fmap` getLine\n\t_ <- getLine\n\tqueries <- (map ((\\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents\n\tputStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries\n\n"}, {"source_code": "import Control.Monad\n\nprimes = 2 : sieve [3,5..]\n where\n sieve (x:xs) = x : sieve [y | y <- xs, y `mod` x /= 0]\n\nsolve gcd = do\n [l, h] <- fmap (map read . words) getLine\n return $ calc l h gcd primes\n where\n calc :: Integer -> Integer -> Integer -> [Integer] -> Integer\n calc l h g (p:ps)\n | g < l = -1\n | g <= h = g\n | g `mod` p == 0 = calc l h (g `div` p) (p:ps)\n | otherwise = calc l h g ps\n\nmain = do\n [a, b] <- fmap (map read . words) getLine\n n <- fmap read getLine\n mapM_ print =<< replicateM n (solve (gcd a b))\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nprimes = 2 : sieve [3,5..]\n where\n sieve (x:xs) = x : sieve [y | y <- xs, y `mod` x /= 0]\n\nsolve xs = do\n [l, h] <- fmap (map read . words) getLine\n let xs' = takeWhile (<=h) $ dropWhile ( Integer -> Integer -> [Integer] -> Integer\n calc l h g (p:ps)\n | g < l = -1\n | g <= h = g\n | g `mod` p == 0 = calc l h (g `div` p) (p:ps)\n | otherwise = calc l h g ps\n\ngen x =\n rec 1 [] $ factors [] primes x\n where\n rec cur res [] = nub $ cur : res\n rec cur res (x:xs) =\n rec (cur*x) (cur : res ++ rec cur res xs) xs\n factors res (p:ps) x\n | p*p > x = reverse $ x:res\n | x `mod` p == 0 = factors (p:res) (p:ps) (x`div`p)\n | otherwise = factors res ps x\n\nmain = do\n [a, b] <- fmap (map read . words) getLine\n n <- fmap read getLine\n print $ gen $ gcd a b\n mapM_ print =<< replicateM n (solve $ sort $ gen $ gcd a b)\n"}, {"source_code": "import Data.List\nimport Control.Applicative\ndefault (Int)\nf r g m | g `mod` m == 0 = f (m:r) (g `div` m) m\n | g < m^2 = sortBy (flip compare) $ \n foldl (\\a b -> (*) <$> a <*> (scanl (*) 1 b)) [1] $ (group $ reverse r)\n | otherwise = f r g (m + 1)\nmain = do\n [a, b] <- (map read . words) `fmap` getLine :: IO [Int]\n n <- read `fmap` getLine\n let divs = f [] (gcd a b) 2\n mapM_ (\\_ -> do\n [low, high] <- (map read . words) `fmap` getLine\n case takeWhile (>= low) $ dropWhile (> high) divs of\n h:_ -> print h\n [] -> print (-1)) [1..n]\n"}, {"source_code": "default (Int)\nmain = do\n [a, b] <- (map read . words) `fmap` getLine :: IO [Int]\n n <- read `fmap` getLine\n let g = gcd a b\n\tdivs = g: (reverse (filter ((==0).(g `mod`)) $ takeWhile ((<= g).(^2)) [1..]))\n mapM_ (\\_ -> do\n [low, high] <- (map read . words) `fmap` getLine\n\tlet h = filter (\\x -> x <= high && x >= low) divs\n\tprint $ case h of\n\t (h:_) -> h\n [] -> (-1)) [1..n]\n"}], "src_uid": "6551be8f4000da2288bf835169662aa2"} {"source_code": "-- author https://codeforces.com/contest/1541/submission/120631973\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\ngenPair [] i = []\r\ngenPair (x:xs) i = (x,i) : (genPair xs (i+1))\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ genPair a 1\r\n print $ fori b n\r\n where\r\n fori [x] n = 0\r\n fori (x:xs) n = fori xs n + forj x xs n\r\n\r\n forj x [] n = 0\r\n forj x (u:xs) n\r\n | (fst x)*(fst u) > 2*n = 0\r\n | otherwise = forj x xs n + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each ", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\n--import Data.Char as C\n\n--import Data.IntSet as S\n\ncntPairs :: [(Integer, Integer)] -> (Integer, Integer) -> Int\ncntPairs l (i, x) =\n length $ filter (\\(j, y) -> i + j == x * y) $ takeWhile (\\(j,y) -> y < x && x*y <= 2000000) l\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Integer\n sxs <- getLine\n let xs = map read $ words sxs :: [Integer]\n vals = sortBy (\\(_,x) (_,y) -> compare x y) $ zip [1..] xs\n pairs = sum $ map (cntPairs vals) vals\n in print pairs\n \n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n\n\n \n\n \n"}, {"source_code": "--{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\n--import Data.Char as C\n\n--import Data.IntSet as S\n\ncntPairs :: [(Integer, Integer)] -> (Integer, Integer) -> Int\ncntPairs l (i, x) =\n length $ filter (\\(j, y) -> i + j == x * y) $ takeWhile (\\(j,y) -> y < x && x*y <= 2000000) l\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Integer\n sxs <- getLine\n let xs = map read $ words sxs :: [Integer]\n vals = sortBy (\\(_,x) (_,y) -> compare x y) $ zip [1..] xs\n pairs = sum $ map (cntPairs vals) vals\n in print pairs\n \n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n\n\n \n\n \n"}, {"source_code": "-- cheese-cracker: cheese-cracker.github.io\nimport Control.Monad\nimport Data.List as L\nimport Data.Maybe (fromJust)\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: IO [Int]\nreadInts = (map (fromInteger . fst . fromJust. BS.readInteger) . BS.words) <$> BS.getLine\n\ngetOrInf :: Int -> M.Map Int Int -> Int\ngetOrInf keyy haystack\n | needle == Nothing = -2000000\n | otherwise = fromJust needle\n where needle = M.lookup keyy haystack\n\nsolve :: Int -> [Int] -> Int\nsolve n xs =\n let\n ixmap = M.fromList $ zip xs [1..]\n condn k summ = (getOrInf k ixmap) + (getOrInf (summ `div` k) ixmap) == summ\n takeflour = floor . sqrt . fromIntegral\n res till = [x | m <- [1..till], x <- [1.. (takeflour $ m-1)], (m `mod` x == 0) && condn x m]\n in length $ res (2*n)\n\nmain :: IO ()\nmain = do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n arr <- readInts\n print(solve n arr)\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n \r\ncount a i n = length [1|p<-[ai,2*ai..2*n],let aj = div p ai,let j = p - i,j > i && j <= n && a!j == aj] \r\n where ai=a!i\r\n \r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let aa = listArray (1,n) a\r\n r = sum [count aa i n|i<-[1..n]]\r\n print r\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\ngenPair [] i = []\r\ngenPair (x:xs) i = (x,i) : (genPair xs (i+1))\r\n\r\nfori [x] n r = 0\r\nfori (x:xs) n r = fori xs n r + forj x xs n r \r\n\r\nforj x [] n r = r \r\nforj x (u:xs) n r \r\n | (fst x)*(fst u) > 2*n = r\r\n | otherwise = (forj x xs n (r + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0))\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ genPair a 1\r\n print $ fori b n 0\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.Int ( Int64 )\r\nimport Data.List ( sort, tails )\r\n\r\nsolve :: IO()\r\nsolve = do\r\n n <- readInt64 <$> getLine\r\n as <- map readInt64 . words <$> getLine\r\n let ps = sort $ zip as [1..]\r\n let calc [] = 0\r\n calc (x:xs) = calc' x xs\r\n calc' _ [] = 0\r\n calc' (ai,i) ((bj,j) : bs)\r\n | ai * bj > 2 * n = 0\r\n | otherwise = calc' (ai,i) bs + (if ai * bj == i + j then 1 else 0)\r\n print $ sum $ map calc $ tails ps\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nreadInt64 :: String -> Int64\r\nreadInt64 = read\r\n\r\nmain :: IO()\r\nmain = do\r\n t <- readInt <$> getLine\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( sort, tails )\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nsolve :: IO()\r\nsolve = do\r\n n <- readLn::IO Integer \r\n as <- readInts \r\n let ps = sort $ zip as [1..]\r\n let calc [] = 0\r\n calc (x:xs) = calc' x xs\r\n calc' _ [] = 0\r\n calc' (ai,i) ((bj,j) : bs)\r\n | ai * bj > 2 * n = 0\r\n | otherwise = calc' (ai,i) bs + fromEnum (ai * bj == i + j)\r\n print $ sum $ map calc $ tails ps\r\n\r\nmain :: IO()\r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t solve\r\n"}, {"source_code": "-- author https://codeforces.com/contest/1541/submission/120631973\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ zip a [1..]\r\n let calc [] = 0\r\n calc (x:xs) = calc' x xs\r\n calc' _ [] = 0\r\n calc' (ai,i) ((bj,j) : bs)\r\n | ai * bj > 2 * n = 0\r\n | otherwise = calc' (ai,i) bs + fromEnum (ai * bj == i + j)\r\n print $ sum $ map calc $ tails b\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "-- author https://codeforces.com/contest/1541/submission/120631973\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ zip a [1..]\r\n let fori [x] = 0\r\n fori (x:xs) = fori xs + forj x xs\r\n forj x [] = 0\r\n forj x (u:xs)\r\n | (fst x)*(fst u) > 2*n = 0\r\n | otherwise = forj x xs + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0\r\n print $ fori b\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "-- author https://codeforces.com/contest/1541/submission/120631973\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\ngenPair [] i = []\r\ngenPair (x:xs) i = (x,i) : (genPair xs (i+1))\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ genPair a 1\r\n let fori [x] = 0\r\n fori (x:xs) = fori xs + forj x xs\r\n forj x [] = 0\r\n forj x (u:xs)\r\n | (fst x)*(fst u) > 2*n = 0\r\n | otherwise = forj x xs + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0\r\n print $ fori b\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "-- author https://codeforces.com/contest/1541/submission/120631973\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\ngenPair [] i = []\r\ngenPair (x:xs) i = (x,i) : (genPair xs (i+1))\r\n\r\nfori [x] n = 0\r\nfori (x:xs) n = fori xs n + forj x xs n\r\n\r\nforj x [] n = 0\r\nforj x (u:xs) n\r\n | (fst x)*(fst u) > 2*n = 0\r\n | otherwise = forj x xs n + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ genPair a 1\r\n print $ fori b n\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "-- author https://codeforces.com/contest/1541/submission/120631973\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\ngenPair [] i = []\r\ngenPair (x:xs) i = (x,i) : (genPair xs (i+1))\r\n\r\nfori [x] n r = 0\r\nfori (x:xs) n r = fori xs n r + forj x xs n r \r\n\r\nforj x [] n r = r \r\nforj x (u:xs) n r \r\n | (fst x)*(fst u) > 2*n = r\r\n | otherwise = (forj x xs n (r + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0))\r\n\r\neach = do \r\n n<-readLn::IO Integer \r\n a<-readInts \r\n let b = sort $ genPair a 1\r\n print $ fori b n 0\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "--{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\n--import Data.Char as C\n\n--import Data.IntSet as S\n\ncntPairs :: [(Int, Int)] -> (Int, Int) -> Int\ncntPairs l (i, x) =\n length $ filter (\\(j, y) -> i + j == x * y) $ takeWhile (\\(j,y) -> y < x && x*y <= 2000000) l\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n sxs <- getLine\n let xs = map read $ words sxs :: [Int]\n vals = sortBy (\\(_,x) (_,y) -> compare x y) $ zip [1..] xs\n pairs = sum $ map (cntPairs vals) vals\n in print pairs\n \n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n\n\n \n\n \n"}], "negative_code": [{"source_code": "-- cheese-cracker: cheese-cracker.github.io\nimport Control.Monad\nimport Data.List as L\nimport Data.Maybe (fromJust)\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: IO [Int]\nreadInts = (map (fromInteger . fst . fromJust. BS.readInteger) . BS.words) <$> BS.getLine\n\ngetOrInf :: Int -> M.Map Int Int -> Int\ngetOrInf keyy haystack\n | needle == Nothing = -2000000\n | otherwise = fromJust needle\n where needle = M.lookup keyy haystack\n\nsolve :: Int -> [Int] -> Int\nsolve n xs =\n let\n ixmap = M.fromList $ zip xs [1..]\n condn k summ = (getOrInf k ixmap) + (getOrInf (summ `div` k) ixmap) == summ\n takeflour = floor . sqrt . fromIntegral\n res till = [x | m <- [1..till], x <- [1.. takeflour m], (m `mod` x == 0) && condn x m]\n in length $ res (2*n)\n\nmain :: IO ()\nmain = do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n arr <- readInts\n print(solve n arr)\n"}], "src_uid": "0ce05499cd28f0825580ff48dae9e7a9"} {"source_code": "main :: IO ()\nmain = interact (unlines . map (unwords . map show . solve . read) . tail . lines)\n\nsolve :: Int -> [Int]\nsolve n = replicate n 1\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ (getLine >>= putStrLn . unwords . map show . flip replicate 1 . read) . read\n"}, {"source_code": "import Control.Monad\nmain = read <$> getLine >>= flip replicateM (read <$> getLine) >>= mapM_ (putStrLn . unwords . map show . flip replicate 1)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tputStrLn $ intercalate \" \" $ map show $ replicate x 1\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map read >>> map (\\n-> unwords (map show (take n (repeat 1000)))) >>> unlines\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tputStrLn $ intercalate \" \" $ map show $ replicate x '1'\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "src_uid": "f82058f6ba3ce0da15a5ce059674af35"} {"source_code": "import Data.List\n\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = foldl' (ff) 0 (zip a b)\n in putStrLn (if k <= 2 then \"YES\" else \"NO\")\n\nff :: Int -> (Int, Int) -> Int\nff a b = if fst(b) /= snd(b) then a+1 else a", "positive_code": [{"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- swap' (read $ nbS :: Int) [] (One 0) None\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \ndata Last = One Int | Mul Int Int \n\nswap:: Int -> [Int] -> Last -> Push -> IO Bool \n\nswap':: Int -> [Int] -> Last -> Push -> IO Bool \nswap' n [] _ _ | (n<=0) = return True \nswap' n xs l p | (n<=0) = swap n xs l p \nswap' n t l p = do\n nums <- getNumbers (2-(length t))\n swap (n-length(nums)) (t++nums) l p \n\nswap u (x:y:xs) (One l) p | (x==y) = swap' u (y:xs) (Mul x l) p \nswap u (x:y:xs) (Mul n l) p | (x==y) = case (x==n) of\n True -> swap' u (y:xs) (Mul n l) p \n False -> swap' u (y:xs) (Mul x n) p \n\nswap u (x:y:xs) p Already | x>y = return False\n \nswap u (x:y:xs) last@(One l) None | x>y = case (y>= l) of\n True -> swap' u (y:xs) last $ Value l x y \n False -> return False\n\n\nswap u (x:y:xs) last@(One l) (Value bInf v bSup) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap' u (v:xs) (One x) Already \n False -> return False \n \nswap u (x:y:xs) (Mul n l) None | x>y = case (y >= n) of\n True -> swap' u (y:xs) (Mul n l) $ Value n x y \n False -> case ((y>=l) && (y swap' u (x:xs) (Mul n l) Already\n False -> return False \n\nswap u (x:y:xs) (Mul n l) (Value bInf v bSup ) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap' u (v:xs) (Mul n l) Already \n False -> return False\n\nswap u (x:y:xs) i@(One l) p@(Value bInf v bSup) = case (v swap' u (y:xs) (One x) p\n True -> case (((x>=bInf) && ( x<=bSup)) || ((l==bSup) && (v==x))) of\n True -> swap' u (v:y:xs) i Already\n False -> return False\n\nswap u (x:y:xs) i@(Mul n l) p@(Value bInf v bSup) = case (v swap' u (y:xs) (One x) p\n True -> case ( ((x>=bInf) && ( x<=bSup)) || ((l==bSup) && (v==n))) of\n True -> swap' u (v:y:xs) i Already\n False -> return False \n\nswap u (x:y:xs) (Mul n l) p = case (n==x) of\n True -> swap' u (y:xs) (Mul n l) p\n False -> swap' u (y:xs) (One x) p\n\nswap u (x:y:xs) i p = swap' u (y:xs) (One x) p\n\nswap u (x:[]) (Mul n l) (Value bInf v bSup) = return $ (l<=bSup) && (v>=n)\nswap u (x:[]) (One l) (Value bInf v bSup) = return $ ((x>=v) && (bSup==l)) || ((v>=l)&&(x>=bInf)&&(x<=bSup))\nswap u (x:[]) i p = case p of\n (Value bInf v bSup) -> return $ (v>=(getN i))&&(x>=bInf)&&(x<=bSup)\n otherwise -> return $ (x>= (getN i)) \n\nswap u ([]) i p = return True \n\ngetN (One n) = n\ngetN (Mul n l) = n\n \n\n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x (One 0) None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \ndata Last = One Int | Mul Int Int \n\nswap:: [Int] -> Last -> Push -> Bool \n\nswap (x:y:[]) (One l) None | x>y = y>= l\nswap (x:y:[]) (Mul i l) None | x>y = y>= l\n\nswap (x:y:xs) (One l) p | (x==y) = swap (y:xs) (Mul x l) p \nswap (x:y:xs) (Mul n l) p | (x==y) = case (x==n) of\n True -> swap (y:xs) (Mul n l) p \n False -> swap (y:xs) (Mul x n) p \n\nswap (x:y:xs) p Already | x>y = False\n\n-- 3 [9 4] 8 3 / Value 3 9 4 / [8 3] 9:[] \n \nswap (x:y:xs) last@(One l) None | x>y = case (y>= l) of\n True -> swap (y:xs) last $ Value l x y \n False -> False\n\n\nswap (x:y:xs) last@(One l) (Value bInf v bSup) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap (v:xs) (One x) Already \n False -> False \n \nswap (x:y:xs) (Mul n l) None | x>y = case (y >= n) of\n True -> swap (y:xs) (Mul n l) $ Value n x y -- 3 9 [9 4] 10 \n False -> case ((y>=l) && (y swap (x:xs) (Mul n l) Already\n False -> False -- 3 9 [9 2] 10 2<3\n\n-- 3 [9 4] 8 8 3 / Value 3 9 4 / [8 3] 9:[] \nswap (x:y:xs) (Mul n l) (Value bInf v bSup ) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap (v:xs) (Mul n l) Already \n False -> False\n\nswap (x:y:xs) i@(One l) p@(Value bInf v bSup) = case (v swap (y:xs) (One x) p\n True -> case (((x>=bInf) && ( x<=bSup)) || ((l==bSup) && (v==x))) of\n True -> swap (v:y:xs) i Already\n False -> False\n\nswap (x:y:xs) i@(Mul n l) p@(Value bInf v bSup) = case (v swap (y:xs) (One x) p\n True -> case ( ((x>=bInf) && ( x<=bSup)) || ((l==bSup) && (v==n))) of\n True -> swap (v:y:xs) i Already\n False -> False \n\nswap (x:y:xs) (Mul n l) p = case (n==x) of\n True -> swap (y:xs) (Mul n l) p\n False -> swap (y:xs) (One x) p\n\nswap (x:y:xs) i p = swap (y:xs) (One x) p\n\nswap (x:[]) (Mul n l) (Value bInf v bSup) = (l<=bSup) && (v>=n)\nswap (x:[]) (One l) (Value bInf v bSup) = ((x>=v) && (bSup==l)) || ((v>=l)&&(x>=bInf)&&(x<=bSup))\nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=(getN i))&&(x>=bInf)&&(x<=bSup)\n otherwise -> (x>= (getN i)) \n\nswap ([]) i p = True \n\ngetN (One n) = n\ngetN (Mul n l) = n\n \n\n\n\n\n \n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n getLine\n a <- fmap (map read . words) getLine :: IO [Int]\n let cnt = length $ filter id $ zipWith (/=) a $ sort a\n putStrLn $ if cnt <= 2 then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List (sort)\nmain = interact $ f . map read . words . last . lines\nf :: [Integer] -> String\nf x\n | l1 <= 2 = \"YES\"\n | otherwise = \"NO\"\n where l1 = length $ filter (\\(i,j) -> i/=j) $ zip x (sort x)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n bs = sort as\n c = length $ filter (== True) $ zipWith (/=) as bs\n\n putStrLn $ if c == 2 || c == 0 then \"YES\" else \"NO\"\n\n\n"}, {"source_code": "\nimport List (sort)\n\nsolve :: [Int] -> Bool\nsolve xs = solve' 0 xs (sort xs)\n where\n solve' n [] _ = n <= 2\n solve' n (x:xs) (y:ys)\n | x == y = solve' n xs ys\n | n == 2 = False\n | otherwise = solve' (n+1) xs ys\n\nmain :: IO ()\nmain = do\n getLine\n xs <- getLine >>= return . map read . words\n putStrLn $ if solve xs then \"YES\" else \"NO\""}, {"source_code": "import Data.List\n\nsolve :: [Int] -> String\nsolve xs = if x == 0 || x == 2 then \"YES\" else \"NO\"\n where x = length $ filter (\\(x, y) -> x /= y) $ zip xs $ sort xs\n\nmain = interact $ solve . map read . tail . words"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: [Int] -> String\nsolve vals =\n if solvable then \"YES\" else \"NO\"\n where\n solvable = (length $ filter id $ zipWith (/=) vals (sort vals)) <= 2\n\nmain = do\n getLine\n vals <- map read . words <$> getLine\n putStrLn $ solve vals\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = f a b 0\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nf [] [] count = count\nf (a:ax) (b:bx) count = f ax bx ( if a /= b then count+1 else count )\n \n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n case filter id $ zipWith (/=) xs $ sort xs of\n [] -> putStrLn \"YES\"\n [True,True] -> putStrLn \"YES\"\n _ -> putStrLn \"NO\""}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n let count = length $ filter id $ zipWith (/=) xs $ sort xs\n answer = if count <= 2 then \"YES\" else \"NO\"\n in putStrLn answer"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n case filter id $ zipWith (/=) xs $ sort xs of\n [] -> putStrLn \"YES\"\n [True,True] -> putStrLn \"YES\"\n _ -> putStrLn \"NO\""}, {"source_code": "import Data.List(sort)\nmain = do\n _ <- getLine\n a <- fmap (\\x -> map (read::String->Int) $ words x) getLine\n let s = sort a\n slv = zipWith (/=) a s\n num = length $ filter (id) slv\n \n case num of\n 2 -> do putStrLn\"YES\"\n 0 -> do putStrLn\"YES\"\n _ -> do putStrLn\"NO\"\n return () "}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n let count = length $ filter id $ zipWith (/=) xs $ sort xs\n answer = if count <= 2 then \"YES\" else \"NO\"\n in putStrLn answer"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = solver a b\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nsolver a b = f a b 0\nf a b count =\n if null a || null b\n then count\n else f ax bx ff\n where ax = tail a\n\t bx = tail b\n\t ff = if head a /= head b then count+1 else count \n \n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = f a b 0\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nf a b count =\n if or [null a, null b]\n then count\n else f (tail a) (tail b) ff\n where ff = if head a /= head b then count+1 else count \n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = f a b 0\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nf a b count =\n if null a || null b\n then count\n else f ax bx ff\n where ax = tail a\n\t bx = tail b\n\t ff = if head a /= head b then count+1 else count \n \n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = foldl' (ff) 0 (zip a b)\n in putStrLn (if k <= 2 then \"YES\" else \"NO\")\n\nff :: Int -> (Int, Int) -> Int\nff a b = if fst(b) /= snd(b) then a+1 else a"}, {"source_code": "import Data.List\nimport Data.Char\nimport qualified Data.Set as Set\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let count = length $ filter id $ zipWith (/=) xs $ sort xs\n answer = if count <= 2 then \"YES\" else \"NO\"\n in putStrLn answer"}, {"source_code": "import Data.List\nimport Data.Char\nimport qualified Data.Set as Set\nimport Control.Monad\nimport Control.Applicative\nmain = do\n n <- getLine\n s <- getLine\n let xs = map read (words s) :: [Int]\n in putStrLn (solve xs) \n \nsolve xs = if (f xs (sort xs) 0) <= 2 then \"YES\" else \"NO\"\n where\n f [] [] acc = acc\n f (x:xs) (y:ys) acc = f xs ys (if x /= y then acc+1 else acc)"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = f a b\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nf a b =\n if or [null a, null b]\n then 0\n else ff + f (tail a) (tail b)\n where ff = if head a /= head b then 1 else 0 \n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n in putStrLn ( if (f a (sort a) 0) <= 2 then \"YES\" else \"NO\" )\n \nf a b count =\n if null a || null b\n then count\n else f ax bx ff\n where ax = tail a\n\t bx = tail b\n\t ff = if head a /= head b then count+1 else count \n \n"}, {"source_code": "import Data.Functor\nimport Data.List\n\nmain :: IO ()\nmain = do\n getLine\n ns <- map read . words <$> getLine\n if diff ns (sort ns) <= 2\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ndiff :: [Int] -> [Int] -> Int\ndiff xs ys = length $ filter (uncurry (/=)) $ zip xs ys"}, {"source_code": "import Data.List\ng(_:l)|length(filter id$zipWith(/=)l(sort l))>2=\"NO\"|1>0=\"YES\"\nmain=interact$g.map((+0).read).words"}, {"source_code": "import Data.List\n\nf True = \"YES\"\nf False = \"NO\"\n\nmain = getLine >> do\n xs <- (((map read).words) `fmap` getLine) :: IO [Int]\n putStrLn $ f $ (<=2) $ length $ filter id $ zipWith (/=) (sort xs) xs\n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- swap' (read $ nbS :: Int) [] (One 0) None\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already | Switch Int Int Int \ndata Last = One Int | Mul Int Int \n\nswap':: Int -> [Int] -> Last -> Push -> IO Bool \nswap' n [] _ _ | (n<=0) = return True \nswap' n xs l p | (n<=0) = swap n xs l p \nswap' n t l p = do\n nums <- getNumbers (3-(length t))\n swap (n-length(nums)) (t++nums) l p \n\nswap:: Int -> [Int] -> Last -> Push -> IO Bool \n\nswap u (x:y:[]) (One l) None | x>y = return $ y>= l\nswap u (x:y:[]) (Mul i l) None | x>y = return $ y>= l\n\nswap u (x:y:xs) (One l) p | (x==y) = swap' u (y:xs) (Mul x l) p \nswap u (x:y:xs) (Mul n l) p | (x==y) = case (x==n) of\n True -> swap' u (y:xs) (Mul n l) p \n False -> swap' u (y:xs) (Mul x n) p \n\nswap u (x:y:xs) i Already | x>y = return False\n\nswap u (x:y:xs) i None | x>y = case (y>=(getLast i)) of\n True -> case xs of\n [] -> return True \n (z:zs) | z>=x -> swap' u (z:zs) (One x) $ Switch (getN i) y x\n (z:zs) | otherwise -> case i of\n Mul n _ -> case (n==x) of\n True -> return False\n False -> swap' u (y:xs) i $ Value n x y \n One n -> swap' u (y:xs) i $ Value n x y \n False -> return False\n \nswap u (x:y:xs) i (Switch bInf a b) | x>y = return $ (b>=x)&&(y<=a)&&(y>=bInf)\n\nswap u (x:y:xs) i p@(Value bInf v bSup) | x>y = case ((y>=bInf) && (y<=bSup) && (v>=(getN i))) of\n False -> return False\n True -> swap' u (v:xs) (One x) Already \n\nswap u (x:y:xs) (Mul n l) p = case (n==x) of\n True -> swap' u (y:xs) (Mul n l) p\n False -> swap' u (y:xs) (One x) p\n\nswap u (x:y:xs) i p = swap' u (y:xs) (One x) p\n\nswap u (x:[]) i (Value bInf v bSup) = return $ ((bSup==(getN i))&&(v<=x)) || ((v>(getN i)) && (x>=bInf) && (x<= bSup)) \nswap u (x:[]) i p = return $ (x>= (getN i)) \n\nswap u ([]) i p = return True \n\ngetN (One n) = n\ngetN (Mul n l) = n\n\ngetLast (One n) = n\ngetLast (Mul n l) = l\n\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n case filter id $ zipWith (/=) [1..n] xs of\n [] -> putStrLn \"YES\"\n [True,True] -> putStrLn \"YES\"\n _ -> putStrLn \"NO\""}, {"source_code": "import Data.List(sort)\nmain = do\n _ <- getLine\n a <- fmap (\\x -> map (read::String->Int) $ words x) getLine\n let s = sort a\n slv = zipWith (/=) a s\n num = length $ filter (id) slv\n \n case num of\n 2 -> do putStrLn\"YES\"\n _ -> do putStrLn\"NO\"\n return () "}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = foldl' (ff) 0 (zip a b)\n in putStrLn $ show (if k <= 2 then \"YES\" else \"NO\")\n\nff :: Int -> (Int, Int) -> Int\nff a b = if fst(b) /= snd(b) then a+1 else a"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = f a b 0\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nf a b count =\n if null ax || null bx\n then count\n else f ax bx ( if a /= b then count+1 else count )\n where ax = tail a\n\t bx = tail b\n \n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = foldl' (ff) 0 (zip a b)\n in print (if k <= 2 then \"YES\" else \"NO\")\n\nff :: Int -> (Int, Int) -> Int\nff a b = if fst(b) /= snd(b) then a+1 else a"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n let a = map read (words s) :: [Int]\n b = sort a\n k = f a b 0\n in putStrLn ( if k <= 2 then \"YES\" else \"NO\" )\n \nf a b count =\n if null ax || null bx\n then ff\n else f ax bx ff\n where ax = tail a\n\t bx = tail b\n\t ff = if a /= b then count+1 else count \n \n"}, {"source_code": "import List\ng(_:l)|length(filter id$zipWith(==)l(sort l))>2=\"NO\"|1>0=\"YES\"\nmain=interact$g.map((+0).read).words"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- swap' (read $ nbS :: Int) [] (One 0) None\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already | Switch Int Int Int \ndata Last = One Int | Mul Int Int \n\nswap':: Int -> [Int] -> Last -> Push -> IO Bool \nswap' n [] _ _ | (n<=0) = return True \nswap' n xs l p | (n<=0) = swap n xs l p \nswap' n t l p = do\n nums <- getNumbers (3-(length t))\n swap (n-length(nums)) (t++nums) l p \n\nswap:: Int -> [Int] -> Last -> Push -> IO Bool \n\nswap u (x:y:[]) (One l) None | x>y = return $ y>= l\nswap u (x:y:[]) (Mul i l) None | x>y = return $ y>= l\n\nswap u (x:y:xs) (One l) p | (x==y) = swap' u (y:xs) (Mul x l) p \nswap u (x:y:xs) (Mul n l) p | (x==y) = case (x==n) of\n True -> swap' u (y:xs) (Mul n l) p \n False -> swap' u (y:xs) (Mul x n) p \n\nswap u (x:y:xs) i Already | x>y = return False\n\nswap u (x:y:xs) i None | x>y = case (y>=(getLast i)) of\n True -> case xs of\n [] -> return True \n (z:zs) | z>=x -> swap' u (z:zs) (One x) $ Switch (getN i) y x\n (z:zs) | otherwise -> case i of\n Mul n _ -> case (n==x) of\n True -> return False\n False -> swap' u (y:xs) i $ Value n x y \n One n -> swap' u (y:xs) i $ Value n x y \n False -> return False\n \nswap u (x:y:xs) i (Switch bInf a b) | x>y = return $ (b>=x)&&(y<=a)&&(y>=bInf)\n\nswap u (x:y:xs) i p@(Value bInf v bSup) | x>y = case ((y>=bInf) && (y<=bSup) && (v>=(getN i))) of\n False -> return False\n True -> swap' u (v:xs) (One x) Already \n\nswap u (x:y:xs) (Mul n l) p = case (n==x) of\n True -> swap' u (y:xs) (Mul n l) p\n False -> swap' u (y:xs) (One x) p\n\nswap u (x:y:xs) i p = swap' u (y:xs) (One x) p\n\nswap u (x:[]) i (Value bInf v bSup) = return $ (v>(getN i)) && (x>=bInf) && (x<= bSup) \nswap u (x:[]) i p = return $ (x>= (getN i)) \n\nswap u ([]) i p = return True \n\ngetN (One n) = n\ngetN (Mul n l) = n\n\ngetLast (One n) = n\ngetLast (Mul n l) = l\n\n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i None | (x==y) = swap (y:xs) x None\nswap (x:y:xs) i Already | (x==y) = swap (y:xs) x Already\nswap (x:y:xs) i p@(Value binf v bSup) | (x==y) = case (v=i) of\n True -> swap (xs) x p\n False -> False\n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) i $ Value i x y\n\n \n\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> case (v==y) of\n --True -> swap (y:xs) i Already \n True -> swap (xs) v p \n False -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x (One 0) None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \ndata Last = One Int | Mul Int Int \n\nswap:: [Int] -> Last -> Push -> Bool \n\nswap (x:y:[]) (One l) None | x>y = y>= l\nswap (x:y:[]) (Mul i l) None | x>y = y>= l\n\nswap (x:y:xs) (One l) p | (x==y) = swap (y:xs) (Mul x l) p \nswap (x:y:xs) (Mul n l) p | (x==y) = case (x==n) of\n True -> swap (y:xs) (Mul n l) p \n False -> swap (y:xs) (Mul x n) p \n\nswap (x:y:xs) p Already | x>y = False\n\n-- 3 [9 4] 8 3 / Value 3 9 4 / [8 3] 9:[] \n \nswap (x:y:xs) last@(One l) None | x>y = case (y>= l) of\n True -> swap (y:xs) last $ Value l x y \n False -> False\n\n\nswap (x:y:xs) last@(One l) (Value bInf v bSup) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap (v:xs) (One x) Already \n False -> False \n \nswap (x:y:xs) (Mul n l) None | x>y = case (y >= n) of\n True -> swap (y:xs) (Mul n l) $ Value n x y -- 3 9 [9 4] 10 \n False -> case ((y>=l) && (y swap (x:xs) (Mul n l) Already\n False -> False -- 3 9 [9 2] 10 2<3\n\n-- 3 [9 4] 8 8 3 / Value 3 9 4 / [8 3] 9:[] \nswap (x:y:xs) (Mul n l) (Value bInf v bSup ) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap (v:xs) (Mul n l) Already \n False -> False\n\nswap (x:y:xs) i@(One l) p@(Value bInf v bSup) = case (v swap (y:xs) (One x) p\n True -> case (((x>=bInf) && ( x<=bSup)) || ((l==bSup) && (v==x))) of\n True -> swap (v:y:xs) i Already\n False -> False\n\nswap (x:y:xs) i@(Mul n l) p@(Value bInf v bSup) = case (v swap (y:xs) (One x) p\n True -> case ( ((x>=bInf) && ( x<=bSup)) || ((l==bSup) && (v==n))) of\n True -> swap (v:y:xs) i Already\n False -> False \n\nswap (x:y:xs) (Mul n l) p = case (n==x) of\n True -> swap (y:xs) (Mul n l) p\n False -> swap (y:xs) (One x) p\n\nswap (x:y:xs) i p = swap (y:xs) (One x) p\n\nswap (x:[]) (Mul n l) (Value bInf v bSup) = (l<=bSup) && (v>=n)\nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=(getN i))&&(x>=bInf)&&(x<=bSup)\n otherwise -> (x>= (getN i)) \n\nswap ([]) i p = True \n\ngetN (One n) = n\ngetN (Mul n l) = n\n \n\n\n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i None | (x==y) = swap (y:xs) i None\nswap (x:y:xs) i Already | (x==y) = swap (y:xs) i Already\nswap (x:y:xs) i p@(Value binf v bSup) | (x==y) = swap(y:xs) x p \n\nswap (x:y:xs) i p | x>y = case p of\n None -> swap (y:xs) i $ Value i x y\n Already -> False\n (Value bInf v bSup) -> case ((x<=x) && (bInf<=y) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n\n\nswap (x:y:xs) i p = swap (y:xs) x p\n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n otherwise -> (x>=i) \n\nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport System.IO.Unsafe(unsafePerformIO)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n let res = swap (getNumbers (read $ nbS :: Int)) 0 None \n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = unsafePerformIO $ do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = []\ngetNumbers n = case getNumber of\n Nothing -> []\n Just num -> num:(getNumbers(n-1))\n\n \n\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i p | (x==y) = swap (y:xs) i p \n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) x $ Value i x y\n\n--Value 0 2 1\n--1 2 1\n\n--2>=1 2<=2 1>=0 1<=1\n\n--1 2 2 1\n\n-- v==y \n\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> case (v==y) of\n True -> swap (y:xs) i p \n False -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i p | (x==y) = swap (y:xs) i p \n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) x $ Value i x y\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> case (v==y) of\n True -> swap (y:xs) i p \n False -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n \n\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i p | (x==y) = swap (y:xs) i p \n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) x $ Value i x y\n\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i None | (x==y) = swap (y:xs) i None\nswap (x:y:xs) i Already | (x==y) = swap (y:xs) x Already\nswap (x:y:xs) i p@(Value binf v bSup) | (x==y) = case (v=i) of\n True -> swap (xs) x p\n False -> False\n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) i $ Value i x y\n\n \n\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> case (v==y) of\n --True -> swap (y:xs) i Already \n True -> swap (xs) v p \n False -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x (One 0) None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \ndata Last = One Int | Mul Int Int \n\nswap:: [Int] -> Last -> Push -> Bool \n\nswap (x:y:[]) (One l) None | x>y = y>= l\nswap (x:y:[]) (Mul i l) None | x>y = y>= l\n\nswap (x:y:xs) (One l) p | (x==y) = swap (y:xs) (Mul x l) p \nswap (x:y:xs) (Mul i l) p | (x==y) = swap (y:xs) (Mul i l) p \n\nswap (x:y:xs) p Already | x>y = False\n\n-- 3 [9 4] 8 3 / Value 3 9 4 / [8 3] 9:[] \n \nswap (x:y:xs) last@(One l) None | x>y = case (y>= l) of\n True -> swap (y:xs) last $ Value l x y \n False -> False\n\n\nswap (x:y:xs) last@(One l) (Value bInf v bSup) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap (v:xs) (One x) Already \n False -> False \n \nswap (x:y:xs) (Mul n l) None | x>y = case (y >= l) of\n True -> swap (x:xs) (Mul n y) $ Already -- 3 9 [9 4] 10 \n False -> False -- 3 9 [9 2] 10 2<3\n\n-- 3 [9 4] 8 8 3 / Value 3 9 4 / [8 3] 9:[] \nswap (x:y:xs) (Mul n l) (Value bInf v bSup ) | x>y = case ((x<=v) && (bInf<=y) && (y<=bSup)) of\n True -> swap (v:xs) (Mul n l) Already \n False -> False\n\nswap (x:y:xs) i p = swap (y:xs) (One x) p\n\nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=(getN i))&&(x>=bInf)&&(x<=bSup)\n otherwise -> (x>= (getN i)) \n\nswap ([]) i p = True \n\ngetN (One n) = n\ngetN (Mul n l) = n\n \n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i None | (x==y) = swap (y:xs) i None\nswap (x:y:xs) i Already | (x==y) = swap (y:xs) i Already\nswap (x:y:xs) i p@(Value binf v bSup) | (x==y) = case (v=i) of\n True -> swap (xs) x p\n False -> False\n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) i $ Value i x y\n\n \n\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> case (v==y) of\n --True -> swap (y:xs) i Already \n True -> swap (xs) v p \n False -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=bSup)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\n\n\n\nmain :: IO ()\nmain = do\n nbS <- getLine\n res <- liftM (\\x -> swap x 0 None) (getNumbers (read $ nbS :: Int))\n case res of \n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ndata Push = Value Int Int Int | None | Already \n\nswap:: [Int] -> Int -> Push -> Bool \n\nswap (x:y:xs) i None | (x==y) = swap (y:xs) i None\nswap (x:y:xs) i Already | (x==y) = swap (y:xs) i Already\nswap (x:y:xs) i p@(Value binf v bSup) | (x==y) = case (v=i) of\n True -> swap (xs) x p\n False -> False\n\nswap (x:y:xs) i p | y case ((v>=x) && (y>=bInf) && (y<=bSup)) of\n True -> swap xs v Already \n False -> False \n Already -> False\n None -> case xs of\n [] -> (y>=i)\n otherwise -> swap (y:xs) i $ Value i x y\n\n \n\n\nswap (x:y:xs) i p = case p of \n (Value bInf v bSup) -> case ((v>x) && (v<=y) && (x>=bInf) && (x<=bSup)) of\n True -> case (v==y) of\n --True -> swap (y:xs) i Already \n True -> swap (xs) v p \n False -> swap xs v Already\n False -> swap (y:xs) x p \n otherwise -> swap (y:xs) x p \n \nswap (x:[]) i p = case p of\n (Value bInf v bSup) -> (v>=i)&&(x>=bInf)&&(x<=v)\n oterwise -> (x>=i) \n\nswap ([]) i (Value _ _ _) = i==0 \nswap ([]) i p = True \n\n\n \n"}], "src_uid": "541fde3a3c40926cbd1edb6017b83e52"} {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bool\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n ts <- replicateM n $ liftM2 (,) poi poi\n return $ bool \"NO\" \"YES\" $ solve m ts\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve m = all (> 0) . (elems :: UArray Int Int -> [Int]) . accumArray (+) 0 (1, m) . concatMap (\\(l, r) -> zip [l + 1..r] (repeat 1))", "positive_code": [{"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport Control.Monad\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol ([_,m]:ts) = [ sol' 0 m ts ]\n\nsol' :: Int -> Int -> [[Int]] -> String\nsol' _ _ [] = \"NO\"\nsol' p m ([f,w]:ts)\n | p < f = \"NO\"\n | p' >= m = \"YES\"\n | otherwise = sol' p' m ts\n where p' = max p w\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bool\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n ts <- replicateM n $ liftM2 (,) poi poi\n return $ bool \"NO\" \"YES\" $ solve m ts\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve m = all (> 0) . (elems :: UArray Int Int -> [Int]) . accumArray (+) 0 (0, m) . concatMap (\\(l, r) -> zip [l..r] (repeat 1))"}], "src_uid": "d646834d58c519d5e9c0545df2ca4be2"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n _ <- read <$> getLine :: IO Int\n (oc, tc) <-\n foldl (\\(a, b) x -> if x == \"1\" then (a + 1, b) else (a, b + 1)) (0, 0)\n . words\n <$> getLine :: IO (Int, Int)\n when (oc == 0) $ replicateM_ tc $ putStr \"2 \"\n when (tc == 0) $ replicateM_ oc $ putStr \"1 \"\n when (oc > 0 && tc > 0) $ do\n putStr \"2 1 \"\n replicateM_ (tc - 1) $ putStr \"2 \"\n replicateM_ (oc - 1) $ putStr \"1 \"\n putStrLn \"\"\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n num1 <- length . filter (==1) . unfoldr (runStateT rIntS) <$> BS.getLine\n putStrLn $ intersperse ' '\n $ if | num1 == n -> replicate n '1'\n | num1 == 0 -> replicate n '2'\n | otherwise -> \"21\" ++ replicate (n - num1 - 1) '2'\n ++ replicate (num1 - 1) '1'\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}, {"source_code": "main = interact $ concat.(map (\\x -> x++\" \")).(map show).helper.(map read).words where helper (x:xs) = if (a>0 && b>0) then 2:1:(replicate (b-1) 2 ++ replicate (a-1) 1) else(replicate b 2 ++ replicate a 1) where (a, b) = (length [0|s<-xs,s==1], length [0|s<-xs,s==2])"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n num1 <- length . filter (==1) . unfoldr (runStateT rIntS) <$> BS.getLine\n putStrLn $ intersperse ' '\n $ if | num1 == n -> replicate n '1'\n | num1 == 1 -> replicate n '2'\n | otherwise -> \"21\" ++ replicate (n - num1 - 1) '2'\n ++ replicate (num1 - 1) '1'\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "src_uid": "14593b565193607dff8b6b25bf51a661"} {"source_code": "import Data.Bits\nimport Data.Array\nmain = do\n n <- readLn\n ps <- listArray (1,n) . map read . words <$> getLine\n let go cl i | testBit cl i = i\n | otherwise = go (setBit cl i) (ps ! i)\n putStrLn $ unwords $ map (show . go (0 :: Integer)) (indices ps)\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.Maybe\nimport Data.Array.IArray\nimport Data.List\n\niogetints :: IO [Int]\niogetints = getLine >>= (return . map read . words)\n\nsolve :: Int -> Array Int Int -> [Int]\nsolve n a = map f [1..n] where\n\tf :: Int -> Int\n\tf x = ans where\n\t\txs = take (succ n) $ iterate (a!) x\n\t\tc = accumArray (+) 0 (1, n) $ map (,1) xs :: Array Int Int\n\t\tans = fromJust $ find ((> 1) . (c!)) xs\n\nmain :: IO ()\nmain = do\n\t[n] <- iogetints\n\txs <- iogetints\n\tputStrLn $ intercalate \" \" $ map show $ solve n $ listArray (1, n) xs\n\t"}, {"source_code": "import qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nf2::Int->Set.Set Int->Map.Map Int Int->Int\nf2 n ss ms\n |Set.member n ss=n\n |otherwise=let Just n2=Map.lookup n ms\n in f2 n2 (Set.insert n ss) ms\n\nf::Int->Map.Map Int Int->Int\nf n ms=let Just n2=Map.lookup n ms\n in n2\n\nmain = do\n e<-getLine\n es<-getLine\n let xs=map read (words es)::[Int]\n n=read e::Int\n ms=Map.fromList $ zip [(1::Int)..n] xs\n putStrLn $ unwords $ map show $ [f2 (f h ms) (Set.fromList [h]) ms|h<-[1..n]]"}, {"source_code": "module Main where\n\nimport Control.Monad (forM_)\nimport Data.Array\nimport Data.Functor ((<$>))\nimport qualified Data.Set as S\nimport System.IO (putStr)\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\nfindStudent :: Array Int Int -> Int -> Int\nfindStudent ps a = go ps a (S.singleton a)\n where\n go ps i set =\n let nextStudent = ps ! i\n in if nextStudent `S.member` set\n then nextStudent\n else go ps nextStudent (S.insert nextStudent set)\n\nmain :: IO ()\nmain = do\n [n] <- getLineInts\n ps <- listArray (1, n) <$> getLineInts\n forM_ [1 .. n] $ putStr . (++ \" \") . show . (findStudent ps)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad (forM_)\nimport Data.Functor ((<$>))\nimport Data.List (foldl')\nimport qualified Data.Set as S\nimport System.IO (putStr)\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\nfindStudent :: [Int] -> Int -> Int\nfindStudent ps a = go ps (S.singleton a)\n where\n go (p:ps) set\n | p `S.member` set = p\n | otherwise = go ps (S.insert p set)\n\nmain :: IO ()\nmain = do\n [n] <- getLineInts\n ps <- getLineInts\n forM_ [1 .. n] $ putStr . (++ \" \") . show . (findStudent ps)\n"}, {"source_code": "module Main where\n\nimport Control.Monad (forM_)\nimport Data.Functor ((<$>))\nimport Data.List (foldl')\nimport qualified Data.Set as S\nimport System.IO (putStr)\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\nfindStudent :: [Int] -> Int -> Int\nfindStudent ps a = go ps (S.singleton a) a False\n where\n go _ _ res True = res\n go (p:ps) set res _\n | p `S.member` set = go ps set p True\n | otherwise = go ps (S.insert p set) res False\n\nmain :: IO ()\nmain = do\n [n] <- getLineInts\n ps <- getLineInts\n forM_ [1 .. n] $ putStr . (++ \" \") . show . (findStudent ps)\n"}], "src_uid": "c0abbbf1cf6c8ec11e942cdaaf01ad7c"} {"source_code": "import Control.Applicative ((<$>), (<|>))\nimport Data.Array ((//), elems, listArray)\nimport Data.Char (digitToInt)\nimport Data.List (findIndex, findIndices)\nimport Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = solve <$> (map digitToInt <$> getLine) >>= putStrLn\n\nsolve :: [Int] -> String\nsolve xs = maybe \"-1\" f $ findIndex (\\c -> even c && c < last xs) xs <|> listToMaybe (reverse $ findIndices even xs)\n where f i = concatMap show $ elems $ listArray (1, length xs) xs // [ (i + 1, last xs), (length xs, xs !! i) ]\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>), (<|>))\nimport Data.Array ((//), elems, listArray)\nimport Data.Maybe (listToMaybe)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.init <$> B.getLine) >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = maybe (B.pack \"-1\") f $ B.findIndex (\\c -> c `elem` \"02468\" && c < B.last xs) xs <|> listToMaybe (reverse $ B.findIndices (`elem`\"02468\") xs)\n where f i = B.pack $ elems $ listArray (1, B.length xs) (B.unpack xs) // [ (i + 1, B.last xs), (B.length xs, xs `B.index` i) ]\n"}, {"source_code": "import Data.List\nmain = putStrLn . solve =<< getLine\nsolve n | Just i <- findIndex ((&&) <$> (< o) <*> ev) n\n = let (l,e:r) = splitAt i (init n)\n in l ++ [o] ++ r ++ [e]\n | not (null es)\n = let (l,e:r) = splitAt (last es) (init n)\n in l ++ [o] ++ r ++ [e]\n | otherwise = \"-1\"\n where\n o = last n\n ev = (`elem` \"24680\")\n es = findIndices ev n\n"}, {"source_code": "--findEven :: [Int] -> [(Integer, Int)]\nfindEven xs = [(i, x) | (i, x) <- zip [0..] xs, even x] \n\n--process :: Int -> [(Int, Int)] -> Maybe (Int, Int) \nprocess k xs\n | null xs = Nothing\n | null ys = Just (last xs)\n | otherwise = Just (head ys)\n where ys = [(i, x) | (i, x) <- xs, x < k]\n\nsolve xs = \n case res of\n Nothing -> \"-1\"\n Just (i, x) -> concatMap show $ take i xs ++ [k] ++ (init $ tail d) ++ [x]\n where d = drop i xs\n where res = process k $ findEven xs\n k = last xs\n \nmain = do\n n <- fmap (map (read . (:\"\"))) getLine :: IO [Int]\n putStrLn $ solve n\n\n\n"}, {"source_code": "findEven xs = [(i, x) | (i, x) <- zip [0..] xs, even x] \n \nprocess k xs\n | null xs = Nothing\n | null ys = Just (last xs)\n | otherwise = Just (head ys)\n where ys = [(i, x) | (i, x) <- xs, x < k]\n\nfirstlast (x:xs) a b = b : go xs\n where go [y] = [a]\n go (y:ys) = y : go ys\n\nold xs a b = [b] ++ init (tail xs) ++ [a]\n\nsolve xs = \n case res of\n Nothing -> \"-1\"\n Just (i, x) -> concatMap show $ take i xs ++ firstlast d x k\n where d = drop i xs\n where res = process k $ findEven xs\n k = last xs\n \nmain = do\n n <- fmap (map (read . (:\"\"))) getLine :: IO [Int]\n putStrLn $ solve n\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Char\n\ncombi f x = (take (length f - length x) f ) ++ x\n\nprocess::[Int]->[Int]->Int->[Char]->[Char]\nprocess [] _ _ f= \"-1\"\nprocess [x] s _ f= combi f $ concatMap show $ [last s] ++tail (init s) ++ [head s]\nprocess (x:xs) s la f |x>la = process xs (dropWhile (/=(head xs) ) (tail s)) la f\n\t |otherwise =combi f $ concatMap show $[last s] ++tail (init s) ++ [head s]\n\nmain= do\n\t r<-getLine \n\t let s= map (\\z-> ord z - ord '0') r:: [Int]\n\t let s1 = filter even s\n\t let ans= process s1 (dropWhile (/=(head s1)) s) (last s) r\n\t putStrLn ans\n\t\n\t \n"}, {"source_code": "import Data.Functor ((<$>))\nimport Control.Applicative ((<|>))\nimport Data.Maybe (listToMaybe)\nimport Data.List (findIndex, findIndices)\nimport Data.Array ((//), elems, listArray)\n\nmain :: IO ()\nmain = solve <$> getLine >>= putStrLn\n\nsolve :: String -> String\nsolve xs = maybe \"-1\" f $ findIndex (\\c -> c `elem` \"02468\" && c < last xs) xs <|> listToMaybe (reverse $ findIndices (`elem`\"02468\") xs)\n where f i = elems $ listArray (0, length xs - 1) xs // [ (i, last xs), (length xs - 1, xs !! i) ]\n"}], "negative_code": [{"source_code": "import Data.Functor ((<$>))\nimport Control.Applicative ((<|>))\nimport Data.Maybe (listToMaybe)\nimport Data.List (findIndex, findIndices)\nimport Data.Array ((//), elems, listArray)\n\nmain :: IO ()\nmain = solve <$> getLine >>= putStrLn\n\nsolve :: String -> String\nsolve xs = maybe \"-1\" f $ findIndex (\\c -> c `elem` \"0248\" && c < last xs) xs <|> listToMaybe (reverse $ findIndices (`elem`\"0248\") xs)\n where f i = elems $ listArray (0, length xs - 1) xs // [ (i, last xs), (length xs - 1, xs !! i) ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.pack <$> getLine) >>= putStrLn . B.unpack\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = last $ B.pack \"-1\" : [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- reverse ix, i == last ix || B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ]\n where ix = B.findIndices (`elem`\"0248\") (B.init xs)\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.List (findIndices)\n\nmain :: IO ()\nmain = putStrLn . concatMap show =<< solve <$> getLine\n\nsolve :: String -> String\nsolve xs = maximum $ \"-1\" : [ swap i (length xs - 1) xs | i <- findIndices (`elem`\"0248\") xs ]\n\nswap :: Int -> Int -> [a] -> [a]\nswap i j xs = [ if k == i then xs !! j else if k == j then xs !! i else x | (k, x) <- zip [0..] xs ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> B.getLine >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = maximum $ B.pack \"-1\" : [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- B.findIndices (`elem`\"0248\") xs, i + 1 /= B.length xs, let (ys, zs) = B.splitAt i xs ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.init <$> B.getLine) >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = head $ [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- B.findIndices (`elem`\"0248\") (B.init xs), Just i == B.findIndex (`elem`\"0248\") (B.init xs) || B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ] ++ [ B.pack \"-1\" ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> B.getLine >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = head $ [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- B.findIndices (`elem`\"0248\") (B.init xs), B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ] ++ [ B.pack \"-1\" ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.init <$> B.getLine) >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = head $ [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- B.findIndices (`elem`\"0248\") (B.init xs), B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ] ++ [ B.pack \"-1\" ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Control.Applicative ((<|>))\nimport Data.Maybe (listToMaybe)\nimport Data.List (findIndex, findIndices)\n\nmain :: IO ()\nmain = solve <$> getLine >>= putStrLn\n\nsolve :: String -> String\nsolve xs = maybe \"-1\" f $ findIndex (\\c -> c `elem` \"0248\" && c < last xs) xs <|> listToMaybe (reverse $ findIndices (`elem`\"0248\") xs)\n where f i = ys ++ last xs : tail (init zs) ++ [ xs !! i ] where (ys, zs) = splitAt i xs \n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.init <$> B.getLine) >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = head $ [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- reverse ix, i == last ix || B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ] ++ [ B.pack \"-1\" ]\n where ix = B.findIndices (`elem`\"0248\") (B.init xs)\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative ((<|>))\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nmain :: IO ()\nmain = solve <$> (B.pack <$> getLine) >>= putStrLn . B.unpack\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = fromMaybe (B.pack \"-1\") (f <$> B.findIndex (\\c -> c `elem` \"0248\" && c < B.last xs) xs <|> f <$> listToMaybe (reverse $ B.findIndices (`elem`\"0248\") xs))\n where f i = B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i where (ys, zs) = B.splitAt i xs \n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> B.getLine >>= putStrLn . B.unpack\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = maximum $ B.pack \"-1\" : [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- B.findIndices (`elem`\"0248\") xs, i + 1 /= B.length xs, let (ys, zs) = B.splitAt i xs ]\n"}, {"source_code": "import Control.Applicative ((<$>), (<|>))\nimport Data.Array ((//), elems, listArray)\nimport Data.Maybe (listToMaybe)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> B.getLine >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = maybe (B.pack \"-1\") f $ B.findIndex (\\c -> c `elem` \"02468\" && c < B.last xs) xs <|> listToMaybe (reverse $ B.findIndices (`elem`\"02468\") xs)\n where f i = B.pack $ elems $ listArray (1, B.length xs) (B.unpack xs) // [ (i + 1, B.last xs), (B.length xs, xs `B.index` i) ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.init <$> B.getLine) >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = last $ B.pack \"-1\" : [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- reverse ix, i == last ix || B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ]\n where ix = B.findIndices (`elem`\"0248\") (B.init xs)\n"}, {"source_code": "import Data.Char (digitToInt)\nimport Data.Functor ((<$>))\nimport Data.List (findIndices)\n\nmain :: IO ()\nmain = putStrLn . concatMap show =<< solve . map digitToInt <$> getLine\n\nsolve :: [Int] -> [Int]\nsolve xs | all odd xs = [ -1 ]\n | otherwise = minimum [ swap i (length xs - 1) xs | i <- findIndices even xs ]\n\nswap :: Int -> Int -> [a] -> [a]\nswap i j xs = [ if k == i then xs !! j else if k == j then xs !! i else x | (k, x) <- zip [0..] xs ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (B.init <$> B.getLine) >>= B.putStrLn\n\nsolve :: B.ByteString -> B.ByteString\nsolve xs = last $ B.pack \"-1\" : [ B.append ys $ B.cons (B.last xs) $ B.snoc (B.tail $ B.init zs) $ B.index xs i | i <- B.findIndices (`elem`\"0248\") (B.init xs), Just i == B.findIndex (`elem`\"0248\") (B.init xs) || B.index xs i < B.last xs, let (ys, zs) = B.splitAt i xs ]\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.List (findIndices)\n\nmain :: IO ()\nmain = putStrLn =<< solve <$> getLine\n\nsolve :: String -> String\nsolve xs = maximum $ \"-1\" : [ swap i (length xs - 1) xs | i <- findIndices (`elem`\"0248\") xs ]\n\nswap :: Int -> Int -> [a] -> [a]\nswap i j xs = [ if k == i then xs !! j else if k == j then xs !! i else x | (k, x) <- zip [0..] xs ]\n"}, {"source_code": "import Data.List\nmain = print . solve =<< getLine\nsolve n | Just i <- findIndex ((&&) <$> (< o) <*> ev) n\n = let (l,e:r) = splitAt i (init n)\n in l ++ [o] ++ r ++ [e]\n | not (null es)\n = let (l,e:r) = splitAt (last es) (init n)\n in l ++ [o] ++ r ++ [e]\n | otherwise = \"-1\"\n where\n o = last n\n ev = (`elem` \"24680\")\n es = findIndices ev n\n"}, {"source_code": "import Data.List\nmain = interact solve\nsolve n | Just i <- findIndex ((&&) <$> (< o) <*> ev) n\n = let (l,e:r) = splitAt i (init n)\n in l ++ [o] ++ r ++ [e]\n | not (null es)\n = let (l,e:r) = splitAt (last es) (init n)\n in l ++ [o] ++ r ++ [e]\n | otherwise = \"-1\"\n where\n o = last n\n ev = (`elem` \"24680\")\n es = findIndices ev n\n"}, {"source_code": "--findEven :: [Int] -> [(Integer, Int)]\nfindEven xs = [(i, x) | (i, x) <- zip [0..] xs, even x] \n\nprocess :: Int -> [(Int, Int)] -> Maybe (Int, Int) \nprocess k xs\n | null xs = Nothing\n | null ys = Just (last xs)\n | otherwise = Just (head xs)\n where ys = [(i, x) | (i, x) <- xs, x < k]\n\nsolve xs = \n case res of\n Nothing -> \"-1\"\n Just (i, x) -> concatMap show $ take i xs ++ [k] ++ (init $ tail d) ++ [x]\n where d = drop i xs\n where res = process k $ findEven xs\n k = last xs\n \nmain = do\n n <- fmap (map (read . (:\"\"))) getLine :: IO [Int]\n putStrLn $ solve n\n\n\n"}, {"source_code": "solve [n] = [3]\nsolve ns'@(n:ns)\n | even n = l : (d ++ [n])\n | otherwise = n : solve ns\n where l = last ns\n d = init ns\n\nmain = do\n n <- fmap (map (read . (:\"\"))) getLine :: IO [Int]\n let ans = solve n\n putStrLn $ case last ans of\n 3 -> \"-1\"\n x -> concatMap show ans\n"}, {"source_code": "--findEven :: [Int] -> [(Integer, Int)]\nfindEven xs = [(i, x) | (i, x) <- zip [0..] xs, even x] \n\n--process :: Int -> [(Int, Int)] -> Maybe (Int, Int) \nprocess k xs\n | null xs = Nothing\n | null ys = Just (last xs)\n | otherwise = Just (head xs)\n where ys = [(i, x) | (i, x) <- xs, x < k]\n\nsolve xs = \n case res of\n Nothing -> \"-1\"\n Just (i, x) -> concatMap show $ take i xs ++ [k] ++ (init $ tail d) ++ [x]\n where d = drop i xs\n where res = process k $ findEven xs\n k = last xs\n \nmain = do\n n <- fmap (map (read . (:\"\"))) getLine :: IO [Int]\n putStrLn $ solve n\n\n\n"}, {"source_code": "--findEven :: [Int] -> [(Integer, Int)]\nfindEven xs = [(i, x) | (i, x) <- zip [0..] xs, even x] \n\n--process :: Int -> [(Int, Int)] -> Maybe (Int, Int) \nprocess k xs\n | null xs = Nothing\n | null ys = Just (last xs)\n | otherwise = Just (head ys)\n where ys = [(i, x) | (i, x) <- xs, x < k]\n\nsolve xs = \n case res of\n Nothing -> \"-1\"\n Just (i, x) -> concatMap show $ take i xs ++ [k] ++ (init $ tail d) ++ [x]\n where d = drop i xs\n where res = process k $ findEven xs\n k = last xs\n \nmain = do\n n <- fmap (map (read . (:\"\"))) getLine :: IO [Int]\n print n\n putStrLn $ solve n\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Char\n\ncombi f x = (take (length f - length x) f ) ++ x\n\nprocess::[Int]->[Int]->Int->[Char]->[Char]\nprocess [] _ _ f= \"-1\"\nprocess [x] s _ f= combi f $ concatMap show $ [last s] ++tail (init s) ++ [head s]\nprocess (x:xs) s la f |x>la = process xs (tail(dropWhile (/=x) s)) la f\n\t |otherwise =combi f $ concatMap show $[last s] ++tail (init s) ++ [head s]\n\nmain= do\n\t r<-getLine \n\t let s= map (\\z-> ord z - ord '0') r:: [Int]\n\t let s1 = filter even s\n\t let ans= process s1 (dropWhile (/=(head s1)) s) (last s) r\n\t putStrLn ans\n\t\n\t \n"}], "src_uid": "bc375e27bd52f413216aaecc674366f8"} {"source_code": "-- ID : 1697C (awoo's Favorite Problem)\n-- URL: https://codeforces.com/problemset/problem/1697/C\n\n{-# LANGUAGE CPP #-}\n#define ENABLE_TRACE 0\n\n\nimport Control.Monad\n#if ENABLE_TRACE\nimport Debug.Trace (trace)\n#endif\n\n-- IO util\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\nreadInt = read `fmap` getLine :: IO Int\n\n#if !ENABLE_TRACE\ntrace a b = b\n#endif\n\nmain = do\n q <- readInt\n replicateM_ q solve\n\nsolve = do\n n <- readInt\n src <- getLine\n dst <- getLine\n let b1 = length . filter (== 'b') $ src\n let b2 = length . filter (== 'b') $ dst\n if (b1 == b2) && (f 0 0 n src dst)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nfmt c i j n xs ys = c ++ \": \" ++ show [i,j,n] ++ \", \" ++ xs ++ \", \" ++ ys\n\nf i j n src dst\n | i >= n = trace (fmt \"case1\" i j n src dst) $ True\n | x == 'b' = trace (fmt \"case2\" (i+1) j n xs dst) $ f (i+1) j n xs dst\n | (x /= y') || (x == 'a' && i > j') || (x == 'c' && i < j') = False\n | otherwise = trace (fmt \"case4\" (i+1) j'' n xs ys'') $ f (i+1) j'' n xs ys''\n where\n (x:xs) = src\n (y:ys) = dst\n bs = leadingB dst\n j' = j + bs\n (y':ys') = drop bs dst\n j'' = min n (j'+1)\n ys'' = if j'' == n then [] else ys'\n\nleadingB ys = f 0 ys where\n f n ('b':yys) = f (n+1) yys\n f n _ = n\n\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array (listArray, (!))\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, s :: String, t :: String}\n\ntype Output = Bool\n\ninput :: Scanner TC\ninput = do\n n <- int\n s <- str\n t <- str\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..} = rec (blocks s) t\n\ntype Block = (Char, Int)\n\ntype Blocks = [Block]\n\nblocks :: String -> Blocks\nblocks = map (\\g -> (head g, length g)) . group\n\nrec :: Blocks -> String -> Bool\nrec [] \"\" = True\nrec ((_, 0) : xs) ys = rec xs ys\nrec ((x, n) : (x', n') : xs) ys | x == x' = rec ((x, n + n') : xs) ys\nrec ((x, n) : xs) (y : ys) | x == y = rec ((x, n - 1) : xs) ys\nrec (('a', n) : ('b', n') : xs) ('b' : ys) \n | n' == 0 = False\n | n' == 1 = rec (('a', n) : xs) ys\n | otherwise = rec (('a', n) : ('b', n' - 1) : xs) ys\nrec (('b', n) : ('c', n') : xs) ('c' : ys) \n | n' == 0 = False\n | n' == 1 = rec (('b', n) : xs) ys\n | otherwise = rec (('b', n) : ('c', n' - 1) : xs) ys\nrec _ _ = False\n\noutput :: Output -> C.ByteString\noutput = bool \"NO\" \"YES\" >>> C.pack\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [{"source_code": "-- ID : 1697C (awoo's Favorite Problem)\n-- URL: https://codeforces.com/problemset/problem/1697/C\n\n{-# LANGUAGE CPP #-}\n#define ENABLE_TRACE 0\n\n\nimport Control.Monad\n#if ENABLE_TRACE\nimport Debug.Trace (trace)\n#endif\n\n-- IO util\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\nreadInt = read `fmap` getLine :: IO Int\n\n#if !ENABLE_TRACE\ntrace a b = b\n#endif\n\nmain = do\n q <- readInt\n replicateM_ q solve\n\nsolve = do\n n <- readInt\n src <- getLine\n dst <- getLine\n let b1 = length . filter (== 'b') $ src\n let b2 = length . filter (== 'b') $ dst\n if (b1 == b2) && (f 0 0 n src dst)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nfmt c i j n xs ys = c ++ \": \" ++ show [i,j,n] ++ \", \" ++ xs ++ \", \" ++ ys\n\nf i j n src dst\n | i >= n = trace (fmt \"case1\" i j n src dst) $ True\n | x == 'b' = trace (fmt \"case2\" (i+1) j n xs dst) $ f (i+1) j n xs dst\n | (x /= y') || (x == 'a' && i > j') || (y == 'c' && i < j') = False\n | otherwise = trace (fmt \"case4\" (i+1) j'' n xs ys'') $ f (i+1) j'' n xs ys''\n where\n (x:xs) = src\n (y:ys) = dst\n bs = leadingB dst\n j' = j + bs\n (y':ys') = drop bs dst\n j'' = min n (j'+1)\n ys'' = if j'' == n then [] else ys'\n\nleadingB ys = f 0 ys where\n f n ('b':yys) = f (n+1) yys\n f n _ = n\n\n"}], "src_uid": "235ddb32dbe19c0da1f77069e36128bb"} {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = (liftA2 ((.sort.map read.words).flip (!!).liftA2 (-) head (!!1).map read.words) getLine getLine :: IO(Int)) >>= print\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInt :: IO Integer\nreadInt = read <$> getLine\n\nreadIntList :: IO [Integer]\nreadIntList = fmap read . words <$> getLine\n\nmain :: IO ()\nmain = do\n [n, k] <- readIntList\n li <- sort <$> readIntList\n putStrLn $ show $ li !! (fromIntegral (n-k))"}, {"source_code": "import Data.List\nstrToList = (map (read :: String -> Int)).words\n\nmain = do\n s <- getLine\n let [n, k] = strToList s\n t <- getLine\n putStrLn $ show $ (sort $ strToList t) !! (n - k)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- map read . words <$> getLine\n xs <- map read . words <$> getLine :: IO [Int]\n\n print $ (reverse $ sort xs) !! (k-1)\n"}], "negative_code": [], "src_uid": "6eca08d7cc2dec6f4f84d3faa9a8a915"} {"source_code": "-- This probably still TLEs, which is unfortunate.\n-- At this point, around 80% of my locally-profiled\n-- runtime is in the sort call on line 53. Disgusting.\n\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Lazy as R\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\n\nimport Data.Int\nimport Data.List\n\np :: Int64\np = 998244353\n\ncv :: Int64 -> Int64\ncv x = mod x p\n\nnewSTUArray :: (Int64, Int64) -> Int64 -> ST s (STUArray s Int64 Int64)\nnewSTUArray = newArray\n\ninvs :: Int64 -> UArray Int64 Int64\ninvs n = runSTUArray $ do\n ans <- newSTUArray (1, n) 0\n writeArray ans 1 1\n forM_ [2..n] $ \\i -> do\n let (x, y) = divMod p i\n v <- readArray ans y\n writeArray ans i $ cv (-x * v)\n pure ans\n\nchoose :: Int64 -> Int64 -> UArray Int64 Int64\nchoose n k = let\n w = invs n\n lastAns = foldl' (\\x y -> cv $ cv (x * (n - y + 1)) * (w ! y)) 1 [1..k]\n ansLi = scanl' (\\x y -> cv $ cv (x * (y - k)) * (w ! y)) lastAns [n, n-1 .. 1]\n in listArray (0, n) $ reverse ansLi\n\ndata DoesMoreStrictnessHelp\n = DoesMoreStrictnessHelp !Int !Int64\n deriving (Eq, Ord)\n\nsolve :: Int64 -> Int64 -> [(Int, Int)] -> Int64\nsolve n k lr = let\n unsortedEvents = do\n (le, ri) <- lr\n [DoesMoreStrictnessHelp le (0-1), DoesMoreStrictnessHelp ri 1]\n events = sort unsortedEvents\n sArr = choose (n-1) (k-1)\n step (!currCt, !currTot) (DoesMoreStrictnessHelp _ v) =\n (currCt - v, currTot + if v == -1 then sArr ! currCt else 0)\n in case foldl' step (0, 0) events of\n (0, ans) -> cv ans\n _ -> error \"huh?\"\n\n{-\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n lr <- replicateM (fromIntegral n) $ do\n [le, ri] <- map read . words <$> getLine\n pure (le, ri)\n print $ solve n k lr\n-}\n\ntype ByteString = P.ByteString\n\nparseLine :: ByteString -> (Int, Int)\nparseLine str = let\n [Just (le, _), Just (ri, _)] = map P.readInt $ P.words str\n in (le, ri)\n\nparse :: ByteString -> (Int64, Int64, [(Int, Int)])\nparse str = let\n (n, k) : lrs = map parseLine $ P.lines str\n in (fromIntegral n, fromIntegral k, lrs)\n\nmain :: IO ()\nmain = do\n (n, k, lrs) <- parse <$> R.getContents\n print $ solve n k lrs\n", "positive_code": [{"source_code": "-- Using tuple-free comparison, and less 64-bit storage...\n-- Will it be faster?\n\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Lazy as R\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\n\nimport Data.Int\nimport Data.List\n\np :: Num t => t\np = 998244353\n\nprodModP :: [Int] -> Int\nprodModP = let\n step :: Int64 -> Int -> Int64\n step x y = mod (x * fromIntegral y) p\n in \\li -> case li of\n [] -> 1\n (x : xs) -> fromIntegral $ foldl' step (fromIntegral x) xs\n\nnewSTUArray :: (Int, Int) -> Int -> ST s (STUArray s Int Int)\nnewSTUArray = newArray\n\ninvs :: Int -> UArray Int Int\ninvs n = runSTUArray $ do\n ans <- newSTUArray (1, n) 0\n writeArray ans 1 1\n forM_ [2..n] $ \\i -> do\n let (x, y) = divMod p i\n v <- readArray ans y\n writeArray ans i $ prodModP [-x, v]\n pure ans\n\nchoose :: Int -> Int -> UArray Int Int\nchoose n k = let\n w = invs n\n lastAns = foldl' (\\x y -> prodModP [x, n-y+1, w!y]) 1 [1..k]\n ansLi = scanl' (\\x y -> prodModP [x, y - k, w ! y]) lastAns [n, n-1 .. 1]\n in listArray (0, n) $ reverse ansLi\n\nsolve :: Int -> Int -> [(Int, Int)] -> Int\nsolve n k lr = let\n unsortedEvents = do\n (le, ri) <- lr\n [le * 2, ri * 2 + 1]\n events = sort unsortedEvents\n sArr = choose (n-1) (k-1)\n step (!currCt, !currTot) ov = let\n v = mod ov 2\n incTot = currTot + if v == 0 then sArr ! currCt else 0\n nextTot = incTot + if incTot >= p then -p else 0\n in (currCt + 1 - 2*v, nextTot)\n in case foldl' step (0, 0) events of\n (0, ans) -> mod ans p\n _ -> error \"huh?\"\n\n{-\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n lr <- replicateM (fromIntegral n) $ do\n [le, ri] <- map read . words <$> getLine\n pure (le, ri)\n print $ solve n k lr\n-}\n\ntype ByteString = P.ByteString\n\nparseLine :: ByteString -> (Int, Int)\nparseLine str = let\n [Just (le, _), Just (ri, _)] = map P.readInt $ P.words str\n in (le, ri)\n\nparse :: ByteString -> (Int, Int, [(Int, Int)])\nparse str = let\n (n, k) : lrs = map parseLine $ P.lines str\n in (n, k, lrs)\n\nmain :: IO ()\nmain = do\n (n, k, lrs) <- parse <$> R.getContents\n print $ solve n k lrs\n"}], "negative_code": [], "src_uid": "64b1a4a9a474a0ee7baeb63596102c5a"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n getLine\n a <- fmap (sort . fmap read . words) getLine\n let (_,res) = foldl (\\(prev,acc) x -> (x,(if abs (x - prev) /= 1 then 0 else 1) + acc)) (-2,0) a\n print $ if res > 0 then 2 else 1", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\ninputNum = do\n line <- getLine\n return ((read line) :: Int)\n\ninputArr = do\n line <- getLine\n let ar = map read (words line) :: [Int]\n return ar\n\nsolveRec [] = True\nsolveRec [x] = True\nsolveRec (a:b:xs) = b-a /= 1 && solveRec (b:xs)\n\nsolveCase = do\n n <- inputNum\n a <- inputArr\n let erg = if solveRec (sort a) then 1 else 2\n putStrLn (show erg)\n\nmain = do\n line <- getLine\n let n = (read line :: Int)\n replicateM_ n solveCase\n {-\n line2 <- getLine\n let x = n+1\n let s = show x\n let z = words line2\n let ar = map read z :: [Int]\n let s2 = map (show . (+ 1)) ar\n putStrLn s\n putStrLn (concat s2)\n -}\n"}, {"source_code": "import Control.Arrow \nimport Data.List\n\nsec :: Bool -> [String]-> [String]\nsec _ [] = []\nsec True (x:xs) = x : sec False xs\nsec False (x:xs) = sec True xs\n\nmain = interact $\n lines >>> tail >>> sec False >>> map (words >>> map read >>> solve >>> show) >>> unlines\n\n\nsolve :: [Integer] -> Integer\nsolve xs = let sxs = sort xs in\n let t a = any (\\x -> x >= 2) $ map length . group $ map (\\x -> (x + a) `div` 2) $ sort xs in\n if t 0 || t 1 then 2 else 1\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\t\t\n\nprocess = do\n\t\ta<- getLine\n\t\tb<- sort <$> map read <$> words <$>getLine ::IO [Int]\n\t\tprint $ if a==\"1\" then 1 \n\t\t\t\t else if length(take 1 (filter (==1) (zipWith (\\z1 z2 ->z2-z1) b (tail b)))) ==1 then 2 else 1\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n process \n\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n getLine\n a <- fmap (fmap read . words) getLine\n print $ if length (filter odd a) /= length a then 2 else 1"}], "src_uid": "dd2cd365d7afad9c2b5bdbbd45d87c8a"} {"source_code": "import Data.Tuple (swap)\nimport Data.Maybe (fromJust)\nimport Control.Monad (replicateM_)\n\ndata TNum = N0 | N1 | N2 deriving (Eq, Ord)\nassocList = [(N0, '0'), (N1,'1'), (N2,'2')]\ndecode = fromJust . flip lookup assocList\nencode = fromJust . flip lookup (map swap assocList)\n\n\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO = do\n _ <- getLine\n n <- map encode <$> getLine\n putStrLn . init . unlines . map (map decode) . (\\(a,b) -> [a,b]) $ solve n\n\n\n\nsolve :: [TNum] -> ([TNum], [TNum])\nsolve [] = ([], [])\nsolve (x:rest) = case x of\n N0 -> let (a,b) = solve rest in (N0 : a, N0 : b)\n N2 -> let (a,b) = solve rest in (N1 : a, N1 : b)\n N1 -> let (a,b) = solveMinimizingLeft rest in (N1 : a, N0 : b)\n\n\nsolveMinimizingLeft :: [TNum] -> ([TNum], [TNum])\nsolveMinimizingLeft xs = (replicate (length xs) N0, xs)\n", "positive_code": [{"source_code": "import Data.Char (isSpace)\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\nf :: (Char, Char, Char) -> Bool -> Char -> (Bool, Char)\nf (c1, c2, c3) flag char =\n case char of\n '0' -> (flag, '0')\n '1' -> (True, if flag then c1 else c2)\n _ -> (flag, if flag then c3 else '1')\n\nwork :: IO ()\nwork = do\n _ <- C.getLine\n a <- C.filter (not . isSpace) <$> C.getLine\n let b = snd $ C.mapAccumL (f ('0', '1', '0')) False a\n c = snd $ C.mapAccumL (f ('1', '0', '2')) False a\n C.putStrLn b\n C.putStrLn c\n\nmain :: IO ()\nmain = do\n n <- fmap parseInt C.getLine\n replicateM_ n work\n"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n getLine\n x <- getLine\n let (a, b) = ans 0 x\n putStrLn a\n putStrLn b\n\nans :: Int -> String -> (String, String)\nans _ [] = ([], [])\nans a (x:xs) =\n case (a, x) of\n (0, '0') -> pre ('1', '2') $ ans 2 xs\n (0, '1') -> pre ('2', '2') $ ans 1 xs\n (0, '2') -> pre ('1', '1') $ ans 1 xs\n (1, '0') -> pre ('0', '0') $ ans 1 xs\n (1, '1') -> pre ('1', '0') $ ans 2 xs\n (1, '2') -> pre ('1', '1') $ ans 1 xs\n (2, '0') -> pre ('0', '0') $ ans 2 xs\n (2, '1') -> pre ('0', '1') $ ans 2 xs\n (2, '2') -> pre ('0', '2') $ ans 2 xs\n\npre (a, b) (x, y) = (a:x, b:y)\n"}, {"source_code": "import Data.Word\nimport Data.List\n\nmain :: IO ()\nmain = do\n getLine -- discard\n answers <- concat <$> map (join.unzip.solve) <$> process <$> getContents :: IO [[Word8]]\n mapM_ print' answers\n\nprocess :: String -> [[Word8]]\nprocess input = map (read' . snd) . filter (even . fst) . zip [1..] . lines $ input\n\nread' :: String -> [Word8]\nread' (x:xs) = (read'' x) : (read' xs)\nread' _ = []\n\nread'' '1' = 1\nread'' '2' = 2\nread'' '0' = 0\n\nsolve :: [Word8] -> [(Word8,Word8)]\nsolve num = solver True num\n\nsolver _ [] = []\nsolver True (0:xs) = (0,0) : (solver True xs)\nsolver True (1:xs) = (1,0) : (solver False xs)\nsolver True (2:xs) = (1,1) : (solver True xs)\nsolver False (0:xs) = (0,0) : (solver False xs)\nsolver False (1:xs) = (0,1) : (solver False xs)\nsolver False (2:xs) = (0,2) : (solver False xs)\n\njoin (a,b) = [a,b]\n\nprint' :: [Word8] -> IO ()\nprint' = putStrLn . intercalate \"\" . map show\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (n:x:rest) = fst ans : snd ans : process rest \n where ans = solve x\n\nsolve :: String -> (String, String)\nsolve \"\" = (\"\", \"\")\nsolve (c:rest)\n | c == '1' = ('1' : (take (length rest) (repeat '0')),\n '0' : rest)\n | otherwise = (d : fst rec, d : snd rec)\n where\n d = if c == '2' then '1' else '0'\n rec = solve rest"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\nf :: (Char, Char, Char) -> Bool -> Char -> (Bool, Char)\nf (c1, c2, c3) flag char =\n case char of\n '0' -> (flag, '0')\n '1' -> (True, if flag then c1 else c2)\n _ -> (flag, if flag then c3 else '1')\n\nwork :: IO ()\nwork = do\n _ <- C.getLine\n a <- C.getLine\n let b = snd $ C.mapAccumL (f ('0', '1', '0')) False a\n c = snd $ C.mapAccumL (f ('1', '0', '2')) False a\n C.putStrLn b\n C.putStrLn c\n\nmain :: IO ()\nmain = do\n n <- fmap parseInt C.getLine\n replicateM_ n work\n"}], "src_uid": "c4c8cb860ea9a5b56bb35532989a9192"} {"source_code": "main = do interact (unwords . map show . gao . map read . words)\ngao [a, b] = if c >= 0 && even c then [d, a - d] else [-1] where\n\tc = a - b\n\td = div c 2\n", "positive_code": [{"source_code": "\ndata X = X Integer deriving Show\ndata Y = Y Integer deriving Show\ndata A = A Integer deriving Show\ndata B = B Integer deriving Show\ndata NeedCarry = NeedCarry Bool deriving Show\n\nbitToInt bit = if bit then 1 else 0\n\nprintRes (Just (X x, Y y, NeedCarry False)) = unwords $ map show $ [x, y]\nprintRes _ = \"-1\"\n\nsolver :: A -> B -> Maybe (X, Y, NeedCarry)\nsolver (A 0) (B 0) = Just (X 0, Y 0, NeedCarry False)\nsolver (A a) (B b) = do\n let a0 = a `mod` 2 /= 0\n b0 = b `mod` 2 /= 0\n c0 = a0 /= b0\n (X nx, Y ny, NeedCarry c1) <- solver (A $ a `div` 2) (B $ b `div` 2)\n let neededXYCount = 2 * (bitToInt c1) + (bitToInt a0) - (bitToInt c0) :: Integer\n (x0, y0) <- case neededXYCount of\n 0 -> Just (False, False)\n 1 -> Just (False, True)\n 2 -> Just (True, True)\n _ -> Nothing\n return (X $ nx*2+ (bitToInt x0), Y $ ny*2+(bitToInt y0), NeedCarry c0)\n\n\ninteractor :: String -> String\ninteractor str = let a :: Integer\n [a, b] = map read $ lines str\n in unlines $ [printRes $ solver (A a) (B b)]\n\nmain = interact interactor\n"}], "negative_code": [], "src_uid": "9c9235394dceba81c8af6be02aa54fcc"} {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nsolve :: [Int] -> Int -> Int\nsolve h k = stepSolve [(0, maxBound)] (zip [1..] h) k\n\nstepSolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int\nstepSolve _ [] _ = 0-1 -- fall off\nstepSolve [] _ _ = error \"(maxBound :: Int) is too small??\"\nstepSolve stack@((_, lastH) : tstack) vs@(nextV@(nextPos, nextH) : tvs) k\n | lastH >= nextH = stepSolve (nextV : stack) tvs k\n | otherwise = case tstack of\n [] -> error \"(maxBound :: Int) is too small??\"\n (ancPos, ancH) : _ -> let\n width = (nextPos - ancPos - 1)\n depth = min ancH nextH - lastH\n vol = width * depth\n in if k <= vol\n then nextPos - 1 - mod (k-1) width\n else if ancH <= nextH\n then stepSolve tstack vs (k - vol)\n else stepSolve (nextV : tstack) tvs (k - vol)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n, k] <- readInts\n h <- readInts\n lift . print $ solve h k\n", "positive_code": [{"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf x [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\nsimulation :: ([Int], Int) -> ([Int], Int)\r\nsimulation ([], _) = ([], -1)\r\nsimulation ([x], _) = ([x], -1)\r\nsimulation (x : y : t, p) = if x >= y then f x $ simulation (y : t, p)\r\n else (x + 1 : y : t, 1)\r\n where f x (hs, -1) = (x : hs, -1)\r\n f x (hs, p) = (x : hs, p + 1)\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve k hs = if k >= 11000 then -1\r\n else snd (iterate simulation (hs, 0) !! k)\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . uncurry solve . getInput) . chunksOf 2 . tail . lines)\r\n where getInput [a, b] = let [_, k] = toArr a in (k, toArr b)\r\n"}], "negative_code": [{"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf x [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map (read :: Read a => String -> a) . words\r\n\r\nfmtB :: Bool -> String\r\nfmtB True = \"YES\"\r\nfmtB False = \"NO\"\r\n\r\nsolve :: Int -> Int -> String -> Bool\r\nsolve px py s = count 'U' s >= py &&\r\n count 'D' s >= -py &&\r\n count 'R' s >= px &&\r\n count 'L' s >= -px\r\n where count x = length . filter (==x)\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (fmtB . uncurry3 solve . getInput) . chunksOf 2 . tail . lines)\r\n where getInput [a, b] = let [px, py] = toArr a in (px, py, b)\r\n uncurry3 f (a,b,c) = f a b c\r\n"}], "src_uid": "32855bb8ba33973178fde7c3d0beb2ce"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List (transpose)\nimport Data.Bits ((.&.), xor)\nimport Data.Word (Word8)\nimport Data.Maybe (fromJust)\nimport Data.Foldable (foldl')\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad (sequence, replicateM)\n\nsolve :: [[Word8]] -> [[Word8]] -> [Word8]\nsolve a q = val `seq` foldr loop (`seq` []) (map head q) (val, 0)\n where\n !val = foldl' xor 0 . concat $ zipWith (zipWith (.&.)) a (transpose a)\n\n loop x f (i, j)\n | x == 3 = i' `seq` i':f (i', 0)\n | otherwise = j' `seq` f (i, j `xor` 1)\n where\n !i' = i `xor` j\n !j' = j `xor` 1\n\nparse :: Num a => ByteString -> [a]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [n] <- parse <$> B.getLine\n a <- fmap parse <$> replicateM n B.getLine\n [m] <- parse <$> B.getLine\n q <- fmap parse <$> replicateM m B.getLine\n mapM_ (putStr . show) $ solve a q\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Bits (xor)\nimport Data.Word (Word8)\nimport Data.Maybe (fromJust)\nimport Data.Foldable (foldl')\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad (sequence, replicateM)\n\nsolve :: [[Word8]] -> [[Word8]] -> [Word8]\nsolve a q = val `seq` foldr loop (`seq` []) (map head q) (val, 0)\n where\n !val = foldl' xor 0 $ zipWith (!!) a [0..]\n\n loop x f (i, j)\n | x == 3 = i' `seq` i':f (i', 0)\n | otherwise = j' `seq` f (i, j `xor` 1)\n where\n !i' = i `xor` j\n !j' = j `xor` 1\n\nparse :: Num a => ByteString -> [a]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [n] <- parse <$> B.getLine\n a <- fmap parse <$> replicateM n B.getLine\n [m] <- parse <$> B.getLine\n q <- fmap parse <$> replicateM m B.getLine\n mapM_ (putStr . show) $ solve a q\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nimport Control.Exception\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of\n Just (n,_) -> n\n Nothing -> 0\n\nmain = catch main_ (\\err ->print (err :: SomeException))\n \nmain_ = do\n n <- readLn\n diag <- forM [0..n-1] $ \\i -> do\n b <- ('1'==).flip B.index (2*i) <$> B.getLine\n return $! b\n _ <- getLine\n qs <- map readInt.B.words <$> B.getContents\n putStrLn . map (bool '1' '0') $ solve (foldl' (/=) False diag) qs\n \nsolve :: Bool -> [Int] -> [Bool]\nsolve !res (3:qs) = res : solve res qs\nsolve !res (_:_:qs) = solve (res /= True) qs\nsolve _ _ = []\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Bits (xor)\nimport Data.Word (Word8)\nimport Data.Maybe (fromJust)\nimport Data.Foldable (foldl')\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad (sequence, replicateM)\n\nsolve :: [[Word8]] -> [[Word8]] -> [Word8]\nsolve a q = val `seq` foldr loop (`seq` []) (map head q) (val, 0)\n where\n !val = foldl' xor 0 . map head $ zipWith drop [0..] a\n\n loop x f (i, j)\n | x == 3 = i' `seq` i':f (i', 0)\n | otherwise = j' `seq` f (i, j `xor` 1)\n where\n !i' = i `xor` j\n !j' = j `xor` 1\n\nparse :: Num a => ByteString -> [a]\nparse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [n] <- parse <$> B.getLine\n a <- fmap parse <$> replicateM n B.getLine\n [m] <- parse <$> B.getLine\n q <- fmap parse <$> replicateM m B.getLine\n mapM_ (putStr . show) $ solve a q\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM,forM_,forM,foldM_)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.List (foldl')\nimport System.IO (hFlush,stdout)\nimport Data.Char (isDigit,isSpace)\n\nreadDiagonal :: Int -> IO [Bool]\nreadDiagonal n = do\n forM [0..n-1] $ \\i -> do\n line <- BS.getLine\n let ws = BS.words line\n return $ (ws !! i) == \"1\"\n\nreadDiagonal' :: Int -> IO [Bool]\nreadDiagonal' n = do\n forM [0..n-1] $ \\i -> do\n line <- BS.getLine\n let ind = BS.findIndices isDigit line\n let ch = BS.index line (ind !! i)\n return $ ch == '1'\n\nnthWord :: Int -> ByteString -> Maybe Int\nnthWord n bs = skip 0 >>= go n\n where\n len = BS.length bs\n skip :: Int -> Maybe Int -- skip spaces\n skip k = if isSpace (BS.index bs k)\n then if k+1 < len then skip (k+1) else Nothing\n else Just k\n skip' :: Int -> Maybe Int -- skip non-spaces\n skip' k = if not (isSpace (BS.index bs k))\n then if k+1 < len then skip (k+1) else Nothing\n else Just k\n go 0 !k = Just k\n go !n !k = skip' k >>= go (n-1)\n\nreadDiagonal'' :: Int -> IO [Bool]\nreadDiagonal'' n = do\n forM [0..n-1] $ \\i -> do\n line <- BS.getLine\n let Just ind = nthWord i line\n let ch = BS.index line ind\n return $ ch == '1'\n\nxor :: Bool -> Bool -> Bool\nxor True False = True\nxor False True = True\nxor _ _ = False\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read :: IO Int\n diag <- readDiagonal'' n\n let sq = foldl' xor False diag\n\n q <- getLine --> read :: IO Int\n\n let doit !sq' i = do\n if i `mod` 1000 == 0\n then hFlush stdout\n else return ()\n line <- BS.getLine\n if BS.null line\n then return sq'\n else case BS.head line of\n '1' -> return $ not sq'\n '2' -> return $ not sq'\n '3' -> do putChar $ if sq' then '1' else '0'\n return sq'\n _ -> return sq'\n foldM_ doit sq [1..q]\n BS.putStrLn \"\"\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nimport Control.Exception\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of\n Just (n,_) -> n\n Nothing -> 0\n\nmain = catch main_ (\\err ->print (err :: SomeException))\n \nmain_ = do\n n <- readLn\n diag <- forM [0..n-1] $ \\i -> do\n b <- ('1'==).flip B.index (2*i) <$> B.getLine\n return $! b\n _ <- getLine\n qs <- map readInt.B.words <$> B.getContents\n putStrLn . map (bool '1' '0') $ solve (foldl' (/=) False diag) qs\n \nsolve :: Bool -> [Int] -> [Bool]\nsolve res (3:qs) = res : solve res qs\nsolve res (_:_:qs) = solve (res /= True) qs\nsolve _ _ = []\n"}], "src_uid": "332902284154faeaf06d5d05455b7eb6"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve = do\n [n, _] <- map read . words <$> getLine\n a <- replicateM 3 getLine\n\n bs :: IOUArray (Int, Int) Bool <- newArray ((1, 1), (3, n)) False\n\n let\n aa :: UArray (Int, Int) Char = listArray ((1, 1), (3, n)) $ concat a\n\n dfs (i, j)\n | j >= n = return True\n | otherwise = do\n b <- readArray bs (i, j)\n if not b\n then do\n writeArray bs (i, j) True\n\n if j > n || aa!(i, j+1) /= '.'\n then return False\n else\n or <$> (forM [max (i-1) 1..min (i+1) 3] $ \\i ->\n if all (== '.') [aa!(i, j) | j <- [j+1..j+3], j <= n]\n then dfs (i, j+3)\n else return False)\n\n else\n return False\n\n let si = (fromJust $ elemIndex 's' $ map (!!0) a) + 1\n r <- dfs (si, 1)\n\n putStrLn $ if r then \"YES\" else \"NO\"\n\nmain = do\n t <- readLn\n replicateM t solve\n", "positive_code": [{"source_code": "import qualified Data.List as L\nanswer::[Int] -> Int -> [String] -> Int -> Bool\nanswer [] j ds n = False \nanswer is j d@(d0:d1:d2:ds) n | j Int -> Int -> [String] -> Bool \nisok0 i j nexti [] = True \nisok0 i j nexti (d0:d1:d2:ds) = 0 <= nexti && nexti < 3 && (d0 !! i)=='.' && (d0 !! nexti) == '.' && (d1 !! nexti) == '.' && (d2 !! nexti) == '.'\nisok0 i j nexti (d0:d1:ds) = 0 <= nexti && nexti < 3 && (d0 !! i)=='.' && (d0 !! nexti) == '.' && (d1 !! nexti) == '.' \nisok0 i j nexti (d0:ds) = 0 <= nexti && nexti < 3 && (d0 !! i)=='.' && (d0 !! nexti) == '.'\ntrans [[],[],[]] = []\ntrans a = (map head a):(trans (map tail a))\nreadInput 0 = return [] \nreadInput n = do\n w0 <- getLine\n next <- readInput (n-1)\n return (w0:next)\nexecTest 0 = return ()\nexecTest t = do\n w0 <- getLine\n let [n,k] = [read n::Int|n<-(words w0)]\n d <- readInput 3\n let dt = trans d\n let h = head dt\n let Just i = L.elemIndex 's' h\n let res=answer [i] 0 (tail dt) n\n putStrLn $ if res then \"YES\" else \"NO\"\n execTest (t-1)\nmain=do\n w0 <- getLine\n let t = read w0::Int\n execTest t\n \n \n \n"}], "negative_code": [], "src_uid": "5c1707b614dc3326a9bb092e6ca24280"} {"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do\n [_, h, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve h k as\n\nsolve :: Integer -> Integer -> [Integer] -> Integer\nsolve h k [a0] = (a0 + k - 1) `div` k \nsolve h k (a0:(a1:as)) =\n if a0 `mod` k + a1 <= h\n then (a0 + a1) `div` k + solve h k (((a0 + a1) `mod` k):as)\n else (a0 + k - 1) `div` k + solve h k (a1:as)\n\n", "positive_code": [{"source_code": "import Control.Applicative( (<$>))\nmain = do\n tokens <- return . words =<< getContents\n let n:capacity:lengthPerSec:hights = read <$> tokens\n\tsendfull buf [] = (buf,[])\n\tsendfull buf (p:ps) = if buf+p <= capacity\n\t\t\t\tthen sendfull (buf+p) ps\n\t\t\t\telse (buf,p:ps)\n\tsmash buf = buf `divMod` lengthPerSec\n\tprocess::(Int,[Int]) -> Integer -> Integer\n\tprocess (0,[]) sec = sec\n\tprocess (buf,potatoes) sec = process (sendfull potatoRest potatoes) (sec+toInteger timeplus)\n\t where\n\t\t(times, pmod) = smash buf\n\t\tjudge = times == 0 && pmod /= 0\n\t\ttimeplus = if judge then 1 else times\n\t\tpotatoRest = if judge then 0 else pmod\n print $ process (0,take n hights) 0\n"}, {"source_code": "import Data.Functor\n\nmain :: IO()\nmain = do\n let readInts = map read . words\n [n, h, k] <- readInts <$> getLine\n a <- readInts <$> getLine\n print $ solve h k a 0\n\nsolve :: Integer -> Integer -> [Integer] -> Integer -> Integer\nsolve _ k [] m = (m + k - 1) `div` k\nsolve h k (a:s) m | m + a <= h = solve h k s (m + a)\n | otherwise = let x = (a + m - h + k - 1) `div` k\n in x + solve h k (a:s) (max 0 (m - k * x))\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do\n [_, h, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve h k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve h k [a0] = (a0 + k - 1) `div` k \nsolve h k (a0:(a1:as)) =\n if a0 `mod` k + a1 <= h\n then (a0 + a1) `div` k + solve h k (((a0 + a1) `mod` k):as)\n else (a0 + k - 1) `div` k + solve h k (a1:as)\n\n"}, {"source_code": "import Control.Applicative( (<$>))\nmain = do\n tokens <- return . words =<< getContents\n let n:capacity:lengthPerSec:hights = read <$> tokens\n\tsendfull buf [] = (buf,[])\n\tsendfull buf (p:ps) = if buf+p <= capacity\n\t\t\t\tthen sendfull (buf+p) ps\n\t\t\t\telse (buf,p:ps)\n\tsmash buf = buf `divMod` lengthPerSec\n\tprocess (0,[]) sec = sec\n\tprocess (buf,potatoes) sec = process (sendfull potatoRest potatoes) (sec+timeplus)\n\t where\n\t\t(times, pmod) = smash buf\n\t\tjudge = times == 0 && pmod /= 0\n\t\ttimeplus = if judge then 1 else times\n\t\tpotatoRest = if judge then 0 else pmod\n print $ process (0,take n hights) 0\n"}], "src_uid": "5099a9ae62e82441c496ac37d92e99e3"} {"source_code": "import Data.List\nmain = interact$f.map read.words\nf (a:b:xs) = (show $foldl (\\acc x-> acc + div (x+1) 2) 0 list) ++ \" \" ++ (show $ sum list)\n\twhere list = map length $ groupBy (\\a b->b-a==1)$ [1..(a-1)] \\\\ (g xs)\ng [] = []\ng (1:a:b:xs) = [a, b] ++ (g xs)\ng (2:a:xs) = a:(g xs)", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (x,k) <- readIntPair\n l <- concat . map tail <$> replicateM k readInts\n let unused = S.toList $ S.fromList [1..x-1] S.\\\\ S.fromList l\n maxM = length unused\n minM = go unused\n go (a:b:l) | a + 1 == b = 1 + go l\n go (a:l) = 1 + go l\n go [] = 0\n putStrLn $ unwords $ map show $ [minM,maxM]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\nmain=interact$unwords.map show.f.map read.words\nf(x:k:xs)=[go 0 ys, length ys]\n where\n ys = unused [1..x-1] $ sort $ parse xs\n go !res (x:y:xs)\n | x+1==y = go (res+1) xs\n | otherwise = go (res+1) (y:xs)\n go res [x] = res+1\n go res [] = res\n\nunused (x:xs) (y:ys)\n | x == y = unused xs ys\n | x < y = x : unused xs (y:ys)\nunused xs _ = xs\n\nparse (1:x:y:xs) = x : y : parse xs\nparse (2:x:xs) = x : parse xs\nparse _ = []"}], "negative_code": [], "src_uid": "fb77c9339250f206e7188b951902a221"} {"source_code": "main :: IO ()\nmain = do str <- getLine\n let n = read str\n putStrLn . unwords . map show $ n:[1..(n-1)]\n \n ", "positive_code": [{"source_code": "\nimport Data.List (intercalate)\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nmain :: IO ()\nmain = do\n n <- readLn\n prints $ n : [1 .. (n-1)]\n"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn $ unwords $ map show $ n:[1..n-1]\n"}, {"source_code": "\nmain = interact $ (++ \"\\n\") . unwords . map show . (\\n -> n:[1..n-1]) . read . head . lines"}, {"source_code": "main=interact$unwords.map show.(\\n->n:[1..n-1]).read\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= putStrLn . unwords . map show . solve\n\nsolve :: Integer -> [Integer]\nsolve n = n : [1..n-1]\n"}, {"source_code": "main = do\n n <- readLn\n putStrLn $ unwords $ map show $ n : [1..n-1]"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn $ intercalate \" \"\n $ map show\n $ (if n == 1 then (1 :) else ([n, 1] ++)) [2..n-1]"}, {"source_code": "main=readLn>>= \\n->putStr.unwords.map show$n:[1..n-1]"}, {"source_code": "import qualified Data.List as L\n\nmain :: IO()\nmain = do\n\t(w:ws) <- words `fmap` getContents\n\tputStrLn $ L.foldl' (\\s num-> s ++ (show num) ++ \" \") \"\" $ readInt(w):[1..((readInt(w))-1)]\n\nreadInt :: String -> Int\nreadInt = read\n"}, {"source_code": "calc :: Int -> [Int]\ncalc 1 = [1]\ncalc 2 = [2, 1]\ncalc n = [n, 1] ++ [2..n-1]\n\nmain = do s <- getLine\n putStrLn $ unwords $ map show $ calc $ read s\n\n"}, {"source_code": "import Data.List\n\nwork n = intercalate \" \" (map show (n : [1 .. n - 1]))\n\nmain = do\n\tline <- getLine\n\tputStrLn(work (read line :: Int))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\nmain= do\n \tx<-read <$> getLine\n\tputStrLn $ unwords $ map show (x:[1..(x-1)])\n"}, {"source_code": "main = getLine >>= mapM_ (\\x -> putStr (show x ++ \" \")). (\\x -> x:[1..(x-1)]). (\\x -> read x :: Int) . head. words\n"}, {"source_code": "main=(shw.slv.read=<> putStrLn \"\"\nslv :: Int -> [Int]\nslv n = n:[1..n-1]\nshw xs=mapM_ (\\c->putStr(' ':show c)) $ xs"}], "negative_code": [{"source_code": "\nmain = interact $ (++ \"\\n\") . unwords . map show . reverse . (\\n -> [1..n]) . read . head . lines"}, {"source_code": "main = do\n n <- readLn\n putStrLn $ unwords $ map show $ [n,1..n-1]"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn $ intercalate \" \"\n $ map show\n $ [2..n] ++ [1]"}, {"source_code": "import Data.Array\nimport Data.List\n\nf :: Int -> Array Int Int -> Array Int Int\nf 1 arr = arr\nf x arr = arr' // [(x, arr' ! (x - 1)), (x - 1, arr' ! x)]\n where arr' = f (x - 1) arr\n\n(|>) :: a -> (a -> b) -> b\nx |> f = f x\ninfixl 0 |>\n\nmain :: IO ()\nmain = do\n n <- readLn\n listArray (1, n) [1..n]\n |> f n\n |> elems\n |> map show\n |> intercalate \" \"\n |> putStrLn"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn $ intercalate \" \"\n $ map show\n $ n : 1 : [2..n-1]"}, {"source_code": "main=readLn>>= \\n->putStr.unwords.map show$[2..n]++[1]"}, {"source_code": "import qualified Data.List as L\n\nmain :: IO()\nmain = do\n\t(w:ws) <- words `fmap` getContents\n\tputStrLn $ L.foldl' (\\s num-> s ++ (show num) ++ \" \") \"\" $ [2..(readInt w)] ++ [1]\n\nreadInt :: String -> Int\nreadInt = read\n"}, {"source_code": "calc :: Int -> [Int]\ncalc n = [2..n] ++ [1]\n\nmain = do s <- getLine\n putStrLn $ unwords $ map show $ calc $ read s\n\n"}], "src_uid": "d9ba1dfe11cf3dae177f8898f3abeefd"} {"source_code": "import Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport qualified Data.IntMap.Strict as IM\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _ <- getInts\n as <- getInts\n let (result, _, _) = foldl' acc (0, 0, IM.empty) as\n acc :: (Int, Int64, IM.IntMap Int) -> Int -> (Int, Int64, IM.IntMap Int)\n acc (num, hp, mp) a\n | a >= 0 = (num + 1, hp + fromIntegral a, mp)\n | hp + fromIntegral a < 0 = (num, hp', IM.alter dec a' mp')\n | otherwise = (num + 1, hp + fromIntegral a, IM.alter inc a mp)\n where Just (a', _) = IM.lookupMin mp'\n mp' = IM.alter inc a mp\n hp' = hp + fromIntegral a - fromIntegral a'\n inc Nothing = Just 1\n inc (Just x) = Just (x + 1)\n dec Nothing = Nothing\n dec (Just 1) = Nothing\n dec (Just x) = Just (x - 1)\n hPutBuilder stdout $ intDec result `mappend` charUtf8 '\\n'\n", "positive_code": [{"source_code": "import Data.Int (Int64)\nimport qualified Data.Set as S\n\nmain = do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n print $ solve S.empty 0 $ zip a [1..n]\n\nsolve :: S.Set (Int64, Int) -> Int64 -> [(Int64, Int)] -> Int\nsolve s h [] = S.size s\nsolve s h (x:xs)\n | h' >= 0 = solve s' h' xs\n | otherwise =\n let (y, s'') = S.deleteFindMin s'\n in solve s'' (h' - fst y) xs\n where\n s' = S.insert x s\n h' = h + fst x\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport qualified Data.IntMap.Strict as IM\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _ <- getInts\n as <- getInts\n let (result, _, _) = foldl' acc (0, 0, IM.empty) as\n acc :: (Int, Int64, IM.IntMap Int) -> Int -> (Int, Int64, IM.IntMap Int)\n acc (num, hp, mp) a\n | a >= 0 = (num + 1, hp + fromIntegral a, mp)\n | hp + fromIntegral a < 0 = (num, hp', IM.alter dec a' mp')\n | otherwise = (num + 1, hp + fromIntegral a, IM.alter inc a mp)\n where Just ((a', _), mp') = IM.minViewWithKey $ IM.alter inc a mp\n hp' = hp + fromIntegral a - fromIntegral a'\n inc Nothing = Just 1\n inc (Just x) = Just (x + 1)\n dec Nothing = Nothing\n dec (Just 1) = Nothing\n dec (Just x) = Just (x - 1)\n hPutBuilder stdout $ intDec result `mappend` charUtf8 '\\n'\n"}, {"source_code": "import Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport qualified Data.IntSet as IS\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _ <- getInts\n as <- getInts\n let (result, _, _) = foldl' acc (0, 0, IS.empty) as\n acc :: (Int64, Int64, IS.IntSet) -> Int -> (Int64, Int64, IS.IntSet)\n acc (num, hp, set) a\n | a >= 0 = (num + 1, hp + fromIntegral a, set)\n | hp + fromIntegral a < 0 = (num, hp', set')\n | otherwise = (num + 1, hp + fromIntegral a, IS.insert a set)\n where Just (a', set') = IS.minView $ IS.insert a set\n hp' = hp + fromIntegral a - fromIntegral a'\n hPutBuilder stdout $ int64Dec result `mappend` charUtf8 '\\n'\n"}, {"source_code": "import Data.Int (Int64)\nimport qualified Data.Set as S\n\nmain = do\n _ <- getLine\n a <- map read . words <$> getLine\n print $ solve S.empty 0 a\n\nsolve :: S.Set Int64 -> Int64 -> [Int64] -> Int\nsolve s h [] = 0\nsolve s h (x:xs)\n | h' >= 0 = 1 + solve s' h' xs\n | otherwise =\n let (y, s'') = S.deleteFindMin s'\n in solve s'' (h' - y) xs\n where\n s' = S.insert x s\n h' = h + x\n"}], "src_uid": "affef141c51bbfd881a90d49ec34ceea"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nremulo :: Int\nremulo = 10^9+7\n\na +. b = if c >= remulo then c - remulo else c where c = a+b\na -. b = a +. (remulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n mplus a b = if c >= m then c-m else c where c = a+b\n mminus a b = a `mplus` (m-b)\n mmul a b = a*b `rem` m\n\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `rem` m) 1 :: UArray Int Int\n\n prev j d i = j `mminus` (d `mmul` (ps!i))\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i -> forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 mplus $ zipWith (\\x i -> x `mmul` (ps!(n-i))) ds [1..]\n\n print $ count b -. count a +. (if check b then 1 else 0)\n\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\n\na -. b = a +. (modulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i ->\n forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!(n-i) `mod` m) ds [1..]\n\n -- print cs\n -- print $ check b\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\n\na -. b = a +. (modulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n mplus a b = let c = a+b in if c >= m then c-m else c\n mminus a b = a `mplus` (m-b)\n mmul a b = a*b `mod` m\n\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = j `mminus` (d `mmul` (ps!i))\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i -> forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 mplus $ zipWith (\\x i -> x `mmul` (ps!(n-i))) ds [1..]\n\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array (Array)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray, runSTArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int\nmodulo = 10^9+7\n\na +. b = if c >= modulo then c - modulo else c where c = a+b\na -. b = a +. (modulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n mplus a b = if c >= m then c-m else c where c = a+b\n mminus a b = a `mplus` (m-b)\n mmul a b = a*b `mod` m\n\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = j `mminus` (d `mmul` (ps!i))\n\n -- cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i -> forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 mplus $ zipWith (\\x i -> x `mmul` (ps!(n-i))) ds [1..]\n\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nremulo :: Int\nremulo = 10^9+7\n\na +. b = let c = a + b in if c >= remulo then c - remulo else c\n\na -. b = a +. (remulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n mplus a b = let c = a+b in if c >= m then c-m else c\n mminus a b = a `mplus` (m-b)\n mmul a b = a*b `rem` m\n\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `rem` m) 1 :: UArray Int Int\n\n prev j d i = j `mminus` (d `mmul` (ps!i))\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i -> forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 mplus $ zipWith (\\x i -> x `mmul` (ps!(n-i))) ds [1..]\n\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\n\na -. b = a +. (modulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i ->\n forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!i `mod` m) ds [1..]\n\n -- print cs\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Array (listArray, (!))\nimport Data.Int (Int64)\nimport Data.Char (ord)\n\nnewtype MInt = MInt Int64\n\nmodulo :: Int64\nmodulo = 10^9+7\n\ninstance Num MInt where\n MInt a + MInt b = let c = a + b in MInt $ if c >= modulo then c - modulo else c\n MInt a * MInt b = MInt $ a * b `mod` modulo\n negate (MInt a) = MInt $ modulo - a\n abs = id\n signum (MInt a) = if a == 0 then 0 else 1\n fromInteger a = MInt $ fromInteger $ a `mod` toInteger modulo\n\ninstance Show MInt where show (MInt a) = show a\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs = listArray ((0, 0), (n, m-1)) $ map (uncurry f) $ ((,) <$> [0..n] <*> [0..m-1])\n where\n f :: Int -> Int -> MInt\n f 0 0 = 1\n f 0 _ = 0\n f i j = sum $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]\n where f' d = cs!(i-1, j') where j' = prev j d (i-1)\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f :: Int -> Int -> [Int] -> MInt\n f _ _ [] = 0 :: MInt\n f i j (x:xs) = (sum $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n where\n ds = map (\\c -> ord c - 48) s\n\n print $ count b - count a + (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Int (Int64)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int64\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\na *. b = a * b `mod` modulo\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0 :: ST s (STUArray s (Int, Int) Int64)\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i ->\n forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (sum <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n -- cs = listArray ((0, 0), (n, m-1)) $ map (f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64\n -- where\n -- f (0, 0) = 1\n -- f (0, _) = 0\n -- f (i, j) = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]\n -- where f' d = cs!(i-1, j') where j' = prev j d (i-1)\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f :: Int -> Int -> [Int] -> Int64\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!(i-1) `mod` m) ds [1..]\n\n -- print cs\n print $ count b - count a + (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\n\na -. b = a +. (modulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i ->\n forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!(n-i) `mod` m) ds [1..]\n\n -- print cs\n -- print $ check b\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (Array)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Int (Int64)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int64\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\na -. b = let c = modulo + a - b in if c >= modulo then c- modulo else c\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0 :: ST s (STUArray s (Int, Int) Int64)\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i ->\n forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (sum <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n -- cs = listArray ((0, 0), (n, m-1)) $ map (f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64\n -- where\n -- f (0, 0) = 1\n -- f (0, _) = 0\n -- f (i, j) = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]\n -- where f' d = cs!(i-1, j') where j' = prev j d (i-1)\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f :: Int -> Int -> [Int] -> Int64\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!(i-1) `mod` m) ds [1..]\n\n -- print cs\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Array (listArray, (!))\nimport Data.Int (Int64)\nimport Data.Char (ord)\n\nnewtype MInt = MInt Int64\n\nmodulo :: Int64\nmodulo = 10^9+7\n\ninstance Num MInt where\n MInt a + MInt b = let c = a + b in MInt $ if c >= modulo then c - modulo else c\n MInt a * MInt b = MInt $ a * b `mod` modulo\n negate (MInt a) = MInt $ modulo - a\n abs = id\n signum (MInt a) = if a == 0 then 0 else 1\n fromInteger a = MInt $ fromInteger $ a `mod` toInteger modulo\n\ninstance Show MInt where show (MInt a) = show a\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs = listArray ((0, 0), (n, m-1)) $ map (uncurry f) $ ((,) <$> [0..n] <*> [0..m-1])\n where\n f :: Int -> Int -> MInt\n f 0 0 = 1\n f 0 _ = 0\n f i j = sum $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]\n where f' d = cs!(i-1, j') where j' = prev j d (i-1)\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f :: Int -> Int -> [Int] -> MInt\n f _ _ [] = 0 :: MInt\n f i j (x:xs) = (sum $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = and $ zipWith (\\x i -> if odd i then x == d else x /= d) ds [1..]\n where\n ds = map (\\c -> ord c - 48) s\n\n print $ count b - count a + (if check b then 1 else 0)\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM_, mapM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\n\na -. b = a +. (modulo - b)\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs :: UArray (Int, Int) Int\n cs = runSTUArray $ do\n a <- newArray ((0, 0), (n, m-1)) 0\n writeArray a (0, 0) 1\n\n forM_ [1..n] $ \\i ->\n forM_ [0..m-1] $ \\j ->\n let\n ds = if odd n == odd i then filter (/= d) [0..9] else [d]\n f' d = readArray a (i-1, j') where j' = prev j d (i-1)\n in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)\n\n return a\n\n -- cs = listArray ((0, 0), (n, m-1)) $ map (f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64\n -- where\n -- f (0, 0) = 1\n -- f (0, _) = 0\n -- f (i, j) = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]\n -- where f' d = cs!(i-1, j') where j' = prev j d (i-1)\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!(i-1) `mod` m) ds [1..]\n\n -- print cs\n print $ count b -. count a +. (if check b then 1 else 0)\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Data.Array (Array)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.Int (Int64)\nimport Data.List (foldl')\nimport Data.Char (ord)\n\nmodulo :: Int64\nmodulo = 10^9+7\n\na +. b = let c = a + b in if c >= modulo then c - modulo else c\na *. b = a * b `mod` modulo\n\nmain = do\n [m, d] <- map read . words <$> getLine\n a <- getLine\n b <- getLine\n\n let\n n = length a\n\n ps = listArray (0, n) $ iterate (\\x -> x*10 `mod` m) 1 :: UArray Int Int\n\n prev j d i = (j - d*ps!i `mod` m + m) `mod` m\n\n cs = listArray ((0, 0), (n, m-1)) $ map (uncurry f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64\n where\n f :: Int -> Int -> Int64\n f 0 0 = 1\n f 0 _ = 0\n f i j = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]\n where f' d = cs!(i-1, j') where j' = prev j d (i-1)\n\n count s = f 1 0 ds\n where\n ds = map (\\c -> ord c - 48) s\n\n f :: Int -> Int -> [Int] -> Int64\n f _ _ [] = 0\n f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)\n where\n ds\n | i == 1 = filter (/= d) [1..x-1]\n | odd i = filter (/=d) [0..x-1]\n | even i = filter (== d) [0..x-1]\n\n f' d = cs!(n-i, j') where j' = prev j d (n-i)\n\n b = if odd i then x /= d else d == x\n j' = prev j x (n-i)\n\n check s = match && r == 0\n where\n ds = map (\\c -> ord c - 48) s\n match = and $ zipWith (\\x i -> if odd i then x /= d else x == d) ds [1..]\n r = foldl1 (\\a b -> (a + b) `mod` m) $ zipWith (\\x i -> x*ps!(i-1) `mod` m) ds [1..]\n\n\n print cs\n print $ count b - count a + (if check b then 1 else 0)\n\n"}], "src_uid": "19564d66e0de78780f4a61c69f2c8e27"} {"source_code": "import Control.Monad\n\ncount = sum . map fromEnum\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, a, b] <- map read . words <$> getLine\n s <- getLine\n let len = length s\n print $ a * len + b * if b >= 0\n then len\n else (1 + count (zipWith (/=) s (tail s))) `div` 2 + 1\n", "positive_code": [{"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( group )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readMany :: IO [Int]\r\n s <- getLine\r\n let oneByOne = n * (a + b)\r\n g = length $ group s\r\n greedy = a * n + b * (g `div` 2 + 1)\r\n print $ if b < 0 then greedy else oneByOne\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (group)\r\nimport Data.Maybe (fromJust, fromMaybe)\r\n\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf testCase) >>> map show >>> unlines >>> C.pack\r\n\r\ntestCase :: Scanner Int\r\ntestCase = do\r\n nab <- three int\r\n s <- C.unpack <$> str\r\n return $ solve nab s\r\n\r\nsolve [n, a, b] s\r\n | b >= 0 = n * (a + b)\r\n | otherwise = n * a + m * b\r\n where\r\n g = length $ group s\r\n m = 1 + (g `div` 2)\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n\ncnt :: String -> Int -> Char -> Int\ncnt [] k _ = div k 2 + 1\ncnt (x:xs) k ch\n | x == ch = cnt xs k x\n | otherwise = cnt xs (k+1) x\n\n\n\nsolve :: IO ()\nsolve = do\n s_ <- getLine\n s <- getLine\n let [n,a,b] = map read $ words s_ :: [Int]\n total = (if b >= 0 then n * (a + b) else\n n*a + (cnt s 0 '2')*b)\n in print total\n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nsolve [x] = 1\r\nsolve (x:xs) = solve xs + if x /= head xs then 1 else 0 \r\n\r\nprintResult = do\r\n [n,a,b] <- readInts\r\n s <- getLine\r\n if b > 0 then print $ n*(a+b)\r\n else do\r\n let r = solve s\r\n print $ n * a + (div r 2 + 1) * b\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "count :: Integer -> Integer ->Integer -> String -> Integer\ncount n a b string \n | b >= 0 = (a + b) * n\n | otherwise = (((flips string) `div` 2) + ((flips string) `mod` 2) + 1)* b + n * a -- for deleting the first prefix\n where\n flips:: String -> Integer\n flips [] = 0\n flips [_] = 0\n flips (x:(y:xs)) \n | x == y = flips (y:xs) \n | otherwise = flips (y:xs) + 1\n\nmain = do\n int <- getLine\n let t = read int::Integer\n repeat t \n where\n repeat 0 = return ()\n repeat m = do\n nab <- getLine\n let arr = map (\\a -> read a::Integer) $ words nab\n string <- getLine\n print $ count (arr!!0) (arr!!1) (arr!!2) string\n repeat $ m - 1"}], "negative_code": [{"source_code": "count :: Integer -> Integer ->Integer -> String -> Integer\ncount n a b string \n | b >= 0 = (a + b) * n\n | otherwise = (((flips string) `div` 2) + ((flips string) `mod` 2)) * b + n * a\n where\n flips:: String -> Integer\n flips [] = 0\n flips [_] = 1\n flips (x:(y:xs)) \n | x == y = flips (y:xs) \n | otherwise = flips (y:xs) + 1\n\nmain = do\n int <- getLine\n let t = read int::Integer\n repeat t \n where\n repeat 0 = return ()\n repeat m = do\n nab <- getLine\n let arr = map (\\a -> read a::Integer) $ words nab\n string <- getLine\n print $ count (arr!!0) (arr!!1) (arr!!2) string\n repeat $ m - 1"}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( group )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readMany :: IO [Int]\r\n s <- getLine\r\n let oneByOne = n * (a + b)\r\n n' = length $ group s\r\n greedy = a * n + b * ((n' + 1) `div` 2) \r\n print $ if b <= 0 then greedy else oneByOne\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (group)\r\nimport Data.Maybe (fromJust, fromMaybe)\r\n\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf testCase) >>> map show >>> unlines >>> C.pack\r\n\r\ntestCase :: Scanner Int\r\ntestCase = do\r\n nab <- three int\r\n s <- C.unpack <$> str\r\n return $ solve nab s\r\n\r\nsolve [n, a, b] s\r\n | b >= 0 = n * (a + b)\r\n | otherwise = n * a + m * b\r\n where\r\n m = (1 + length (group s)) `div` 2\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "src_uid": "93fb13c40ab03700ef9a827796bd3d9d"} {"source_code": "module Main where\n\nimport Control.Monad\nimport System.IO\nimport Data.Maybe\nimport Data.Char\nimport Data.List\n\ndata Token a = Add | End | For a\n deriving Show\n\nisAdd :: Token a -> Bool\nisAdd Add = True\nisAdd _ = False\n\nisEnd :: Token a -> Bool\nisEnd End = True\nisEnd _ = False\n\nfromFor :: Token a -> a\nfromFor Add = undefined\nfromFor End = undefined\nfromFor (For count) = count\n\nparseToken :: String -> Maybe (Token Integer)\nparseToken s\n | s == \"add\" = Just Add\n | s == \"end\" = Just End\n | otherwise =\n let ws = words s\n maybe_for = length ws == 2 && head ws == \"for\"\n in if maybe_for\n then Just $ For (read (head (tail ws)) :: Integer)\n else Nothing\n\ntopBound = 4294967295 :: Integer\n\nprogCalc :: [Token Integer] -> Maybe Integer\nprogCalc toks = progCalc' (Just 0) [] toks\n\nprogCalc' :: Maybe Integer -> [Maybe Integer] -> [Token Integer] -> Maybe Integer\nprogCalc' x _ [] = x\nprogCalc' Nothing _ _ = Nothing\nprogCalc' (Just x) levels (tok : resttoks)\n | isAdd tok && null levels =\n let z = x + 1\n in if z > topBound then Nothing\n else progCalc' (Just z) levels resttoks\n | isAdd tok =\n let lev = head levels\n in if isNothing lev then Nothing\n else let z = x + (fromJust lev)\n in if z > topBound then Nothing\n else progCalc' (Just z) levels resttoks\n | isEnd tok = progCalc' (Just x) (tail levels) resttoks\n | otherwise =\n let count = fromFor tok\n prevLev = if null levels then (Just 1) else head levels\n in if isNothing prevLev\n then progCalc' (Just x) (Nothing : levels) resttoks\n else let lev = (fromJust prevLev) * count\n in if lev > topBound\n then progCalc' (Just x) (Nothing : levels) resttoks\n else progCalc' (Just x) ((Just lev) : levels) resttoks\n\n\nmain :: IO()\nmain = do\n\n q <- readLn :: IO Int\n lines <- forM [1..q] $ \\q_nxt -> do\n line <- getLine\n return line\n\n let toks = map (fromJust . parseToken) lines\n let result = progCalc toks\n let resultstr = if (isNothing result)\n then \"OVERFLOW!!!\"\n else show $ fromJust result\n\n putStrLn resultstr\n", "positive_code": [{"source_code": "import qualified Data.List as List\n\ndata Command = For Integer | Add | End\n deriving (Eq, Show)\n\ndata Instr =\n One Command\n | More [Instr]\n deriving (Eq, Show)\n\n\n{- reduce the stack -}\nturnOutermost :: [Instr] -> [Instr] -> [Instr]\nturnOutermost [] acc = acc\nturnOutermost (One End : rest) acc = turnOutermost rest (One End : acc)\nturnOutermost (One Add : rest) acc = turnOutermost rest (One Add : acc)\nturnOutermost (More x : rest) acc = turnOutermost rest (More x : acc)\nturnOutermost (One (For n) : rest) acc = More (One (For n) : acc) : rest\n\n\n{- Shift and reduce -}\nparseCommand :: [Command] -> [Instr] -> [Instr]\nparseCommand [] stack = stack\nparseCommand (Add : rest) stack\n | stack == [] = One Add : parseCommand rest stack\n | otherwise = parseCommand rest (One Add : stack)\nparseCommand(For n : rest) stack = parseCommand rest (One (For n) : stack)\nparseCommand (End : rest) stack = ret where\n tw = turnOutermost (One End : stack) []\n ret = case tw of \n [x] -> x : parseCommand rest []\n _ -> parseCommand rest tw\n\nevalCommand :: [Instr] -> Integer\nevalCommand [] = 0\nevalCommand (One Add : xs) = 1 + evalCommand xs\nevalCommand (One End : xs) = evalCommand xs\nevalCommand (One (For n) : xs) = n * evalCommand xs\nevalCommand (More t : xs) = evalCommand t + evalCommand xs\n\n\n\n\nsolve :: [Command] -> String\nsolve xs = ret where\n rt = evalCommand (parseCommand xs [])\n ret = if rt > 4294967295 then \"OVERFLOW!!!\" else show rt\n\n\nstrCommand :: [String] -> Command\nstrCommand [\"add\"] = Add\nstrCommand [\"end\"] = End\nstrCommand [\"for\", n] = For (read n :: Integer)\n\n\nmain :: IO ()\nmain = interact $ solve . map (strCommand . words) . tail . lines\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "70f67dc28f9f6076255df97fc58ba2d6"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n c = count (0 :: Int64) $ sort xs\n where\n count _ [] = 0\n count c (x:xs)\n | c > x' = count c xs\n | otherwise = 1 + count (c+x') xs\n where\n x' = fromIntegral x :: Int64\n\n print c\n", "positive_code": [{"source_code": "import Data.List (sort)\nimport System.IO\n\nf (suma, ans) x = \n if suma <= x\n then (suma + x, ans + 1)\n else (suma, ans)\n\nsolve list = \n foldl f (0, 0) (sort list)\n \nsolution list = snd $ solve list\n\nmakeItInt a =\n read a :: Int\n\nmakeListGreatAgain l = \n map makeItInt $ lines $ map (\\c -> if c == ' ' then '\\n' else c) l\n\nmain = do\n n <- getLine\n l <- getLine\n putStrLn $ show (solution $ makeListGreatAgain l)"}, {"source_code": "import Data.List (sort)\ngetNum [] waitTime = 0\ngetNum (ha:ta) waitTime | ha >= waitTime = 1+(getNum ta (waitTime+ha))\n | otherwise = getNum ta waitTime\nmain = do\n w0 <- getLine\n w1 <- getLine\n let a = [read n::Int|n <-(words w1)]\n print $ getNum (sort a) 0\n"}, {"source_code": "module Main where\nimport Data.List\n-- import Debug.Trace\n\nsolve _ n [] = n\nsolve w n (t:ts) = -- trace (\"t=\" ++ show t ++ \" w=\" ++ show w ++ \" n=\" ++ show n) $ \n if t >= w \n then solve (w+t) (n+1) ts\n else solve w n ts \n\nmain = do\n getLine\n is <- map (read :: String -> Int) .words <$> getLine\n print $ solve 0 0 $ sort is\n"}, {"source_code": "import Data.List\n\nfoo :: [Int] -> Int -> Int -> Int\nfoo [] _ n = n\nfoo (x:xs) t n = if xInt) =<< getLine\n xs <- return . sort . map (read::String->Int) . words =<< getLine\n print $ foo xs 0 0\n\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess n s [] = n\nprocess n s a | b==[] = n\n | otherwise = process (n+1) (s+ (head b)) (tail b)\n where b = dropWhile ( getLine::IO Int\n a1<- sort <$> map read <$> words <$> getLine:: IO [Int]\n print $ process 0 0 a1\n"}, {"source_code": "import Data.List\n\nmain = do\n\tgetLine\n\tl <- getLine >>= return.(map read).words\n\tputStrLn $ show $ solve (sort l) 0\n\nsolve :: [Int] -> Int -> Int\nsolve [] _ = 0\nsolve (x:xs) n\n\t| n > x\t\t= solve xs n\n\t| otherwise = 1 + solve xs (n+x)\n"}, {"source_code": "import Control.Applicative ((<*>))\nimport Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve = snd . foldl (\\(a, b) c -> if a <= c then (a + c, b + 1) else (a, b)) (0, 0) . sort\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve 0 . sort . map read . tail . words\nsolve t (a:as) | t <= a = 1 + solve (t+a) as\n | otherwise = solve t as\nsolve _ [] = 0\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n\nprocess [] n u= n\nprocess (s:ss) n u| u<=s = process ss (n+1) (u+s)\n | otherwise= process ss n u\nmain= do\t \n\tgetLine \n\ts<- sort . map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]\n\tprint $ process s 0 0\n \n\t \n\t "}, {"source_code": "\nimport Data.List\n\nmain = interact $ show . sol 0 . sort . tail . map read . words \n\nsol _ [] = 0\nsol t (x:xs)\n | t <= x = 1 + sol (t+x) xs\n | otherwise = sol t xs\n\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/D\n\nimport Data.List\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ntakeFirst :: (a -> Bool) -> [a] -> Maybe a\ntakeFirst f [] = Nothing\ntakeFirst f (x:xs)\n\t| f x = Just x\n\t| otherwise = takeFirst f xs\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\tpeople <-\tfmap sort $\n\t\t\t\tfmap (map read) $\n\t\t\t\tfmap (take n) $\n\t\t\t\tfmap words getLine :: IO [Int]\n\n\tlet\n\t\tnot_dissapointed = notDissapointed people\n\n\tputStrLn $ show not_dissapointed\n\nnotDissapointed :: [Int] -> Int\nnotDissapointed xs = notDissapointed' 0 xs\n\twhere\n\t\tnotDissapointed' :: Int -> [Int] -> Int\n\t\tnotDissapointed' acc people\n\t\t\t| not_dissapointed == 0 = 0\n\t\t\t| otherwise = 1 + notDissapointed' (acc + not_dissapointed) rest\n\t\t\twhere\n\t\t\t\tnot_dissapointed = eliminate 0 $ takeFirst (>=acc) people\n\t\t\t\trest = delete not_dissapointed people\n\t\t\t\teliminate :: a -> Maybe a -> a\n\t\t\t\teliminate fallback Nothing = fallback\n\t\t\t\teliminate _ (Just x) = x"}], "negative_code": [{"source_code": "-- http://codeforces.com/problemset/problem/545/D\n\nimport Data.List\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ntakeFirst :: (a -> Bool) -> [a] -> Maybe a\ntakeFirst f [] = Nothing\ntakeFirst f (x:xs)\n\t| f x = Just x\n\t| otherwise = takeFirst f xs\n\nmain = do\n\tn <- fmap read getLine :: IO Int\n\tpeople <-\tfmap sort $\n\t\t\t\tfmap (map read) $\n\t\t\t\tfmap (take n) $\n\t\t\t\tfmap words getLine :: IO [Int]\n\n\tlet\n\t\tnot_dissapointed = notDissapointed people\n\n\tputStrLn $ show not_dissapointed\n\nnotDissapointed :: [Int] -> Int\nnotDissapointed xs = notDissapointed' 0 xs\n\twhere\n\t\tnotDissapointed' :: Int -> [Int] -> Int\n\t\tnotDissapointed' acc people\n\t\t\t| not_dissapointed == 0 = 0\n\t\t\t| otherwise = 1 + notDissapointed' (acc + not_dissapointed) rest\n\t\t\twhere\n\t\t\t\tnot_dissapointed = eliminate 0 $ takeFirst (>acc) people\n\t\t\t\trest = delete not_dissapointed people\n\t\t\t\teliminate :: a -> Maybe a -> a\n\t\t\t\teliminate fallback Nothing = fallback\n\t\t\t\teliminate _ (Just x) = x"}, {"source_code": "module Main where\nimport Data.List\n\nmain = do\n getLine\n is <- map (read :: String -> Int) .words <$> getLine\n let ss = sort is\n ts = scanl' (+) 0 ss\n print $ length $ filter (\\(a,b) -> a >= b) $ zip ss ts\n"}, {"source_code": "module Main where\nimport Data.List\n\nmain = do\n getLine\n is <- map (read :: String -> Int) .words <$> getLine\n let patience = sort is\n waiting = scanl' (+) 0 patience\n --print $ zip patience waiting\n print $ succ $ length $ filter (\\(p,w) -> p >= w) $ zip (tail patience) (tail waiting)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\nmain::IO ()\nmain=do\n n<- read <$> getLine::IO Int\n a1<- sort <$> map read <$> words <$> getLine:: IO [Int]\n let a2 = scanl1 (+) a1\n print $ (+1)$ length $ filter (\\(z1,z2)-> z1<=z2) $ zip a2 (tail a1)\n"}, {"source_code": "import Control.Applicative ((<*>))\nimport Data.List (sort)\n\nmain :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve = length . filter id . (zipWith (>=) <*> scanl (+) 0) . sort\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . sort . map read . tail . words\nsolve as = sum $ zipWith ((fromEnum .) . (<=)) (scanl (+) 0 as) as\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \nmain= do\t \n\tgetLine \n\ts<- sort . map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]\n\tlet t = scanl (+) 0 s\n\tprint $ length $ filter (\\z-> fst z >= snd z) $ zip s t\n\t\n \n\t \n\t "}], "src_uid": "08c4d8db40a49184ad26c7d8098a8992"} {"source_code": "import Control.Monad\n\ncrust :: (Int, Int) -> (Int, Int, Int) -> Bool\ncrust (r, d) (x, y, r') = fromIntegral (r - d) <= dist - fromIntegral r' && fromIntegral r >= dist + fromIntegral r'\n where dist = sqrt (fromIntegral (x^2 + y^2) :: Double)\n\nmain :: IO ()\nmain = do\n [r, d] <- map (read :: String -> Int) . words <$> getLine\n n <- (read :: String -> Int) <$> getLine \n print =<< length . filter (crust (r, d)) . map((\\[x,y,r]->(x,y,r)) . map (read :: String -> Int) . words) <$> replicateM n getLine\n", "positive_code": [{"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\n\nmain = do\n [r_, d_] <- map read . words <$> getLine\n n_ <- readLn::IO Int\n sausageInfos_ <- replicateM n_ (map read . words <$> getLine)\n let\n\n\tdisSq x y = x^2 + y^2\n\n\tcheck [x,y,ri] = let\n\t\t\t dis2 = disSq x y\n\t\t\tin\n\t\t\t (r_-d_+ri)^2 <= dis2 &&\n\t\t\t\tdis2 <= (r_-ri)^2\n\n print . length $ filter check sausageInfos_\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n r <- poi \n d <- poi\n n <- poi\n ss <- replicateM n $ liftM3 (,,) poi poi poi\n return $ show $ solve r d ss\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve r d = length . filter ok\n where \n ok (x, y, r') = o <= (r - r')^2 && o >= (r - d + r')^2\n where o = x*x + y*y"}, {"source_code": "import Data.List\nimport Data.Ord\n\n{-\n\nsolve l r x y k\n\t|l/y<=k && r/x>=k = solve1 l r x y k\n\t|otherwise = \"NO\"\nsolve1 l r x y k\n\t|or (map (\\a->bin a x y k) [l..r] ) = \"YES\"\n\t|otherwise = \"NO\"\n\t\nbin a x y k\n\t|x>y = False\n\t|a/x==k = True\n\t|a/y==k = True\n\t|2*a/(y+x)read x::Float) $ words word\n\tputStrLn (solve l r x y k)\n\t\n-}\n\nfi=fromIntegral\n\nhip x y=sqrt ((fi x)^2 + (fi y)^2)\ncheck r d x y r1 = ((h-fi r1)>=fi (r-d)) && ((h+fi r1)<=fi r) where\n h=hip x y\n\ntoNArr x = map (\\x->read x::Int) $ words x \n \nextract (x:y:xs)=(r,d,circles) where\n\t[r,d]=toNArr x\n\tn=read y::Int\n\tcircles=map toNArr $ take n xs\n\t\nsolve (r,d,circles)=length $ filter (\\(x:y:r1:_)->check r d x y r1) circles\t\n\nmain=interact$show.solve.extract.lines"}, {"source_code": "sqrtm = sqrt . (fromIntegral :: Int -> Double)\n\nfun :: Int -> Int -> [Int] -> Int\nfun _ _ [] = 0\nfun r l x@(a : b : c :xz) = do\n\t\t\t\tlet n = sqrtm (a * a + b * b)\n\n\t\t\t\tif n - fromIntegral c >= fromIntegral l && n + fromIntegral c <= fromIntegral r then 1 + fun r l xz else fun r l xz\n\nmain = do \n\tstr <- getContents\n\tlet cont = (map (\\x -> read x :: Int). words) str\n\tlet (r:l:n) = take 3 cont\n\tlet newcont = drop 3 cont\n\tprint $ fun r (r - l) newcont\n"}], "negative_code": [{"source_code": "sqrtm = sqrt . (fromIntegral :: Int -> Double)\n\nfun :: Int -> Int -> [Int] -> Int\nfun _ _ [] = 0\nfun r l x@(a : b : c :xz) = do\n\t\t\t\tlet n = sqrtm (a * a + b * b)\n\n\t\t\t\tif n - fromIntegral c >= fromIntegral l && n + fromIntegral c <= fromIntegral r then 1 + fun r l xz else fun r l xz\n\nmain = do \n\tstr <- getContents\n\tlet cont = (map (\\x -> read x :: Int). words) str\n\tlet (r:l:n) = take 3 cont\n\tlet newcont = drop 3 cont\n\tprint $ fun r l newcont\n"}], "src_uid": "fce9d78ad7d4ea01be1704f588e42d37"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (xs : rest) = solve xs : process rest\n \nsolve :: String -> String\nsolve cs = take (length cs) $ repeat $ win $ snd $ last $ sort $ map (\\xs-> (length xs, head xs)) $ group $ sort cs where\n win 'S' = 'R'\n win 'R' = 'P'\n win 'P' = 'S'\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n s <- getLine\n putStrLn $ replicate (length s) $\n case head $ maximumBy (comparing length) $ group $ sort s of\n 'R' -> 'P'\n 'P' -> 'S'\n _ -> 'R'\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (xs : rest) = solve xs : process rest\n \nsolve :: String -> String\nsolve cs = take (length cs) $ repeat $ win $ fst $ last $ sort $ map (\\xs-> (head xs, length xs)) $ group $ sort cs where\n win 'S' = 'R'\n win 'R' = 'P'\n win 'P' = 'S'\n"}], "src_uid": "38e884cbc5bede371bccbc848096f499"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n ys = map (\\g -> (head g, length g)) $ group xs\n\n (r0, k0, d0) = (ys2, length ys1, sum $ map snd ys1)\n where\n (ys1, ys2) = span (\\x -> fst x == a || fst x == b) ys\n ((a, _):(b, _):_) = ys\n\n scan :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> Int\n scan [_] _ _ m = m\n scan _ [] _ m = m\n scan l r k m = scan l' r' k' $ max d' m\n where\n l' = drop (k-1) l\n (a, _) = head l'\n (b, _) = head r\n (r1, r') = span (\\x -> fst x == a || fst x == b) r\n k' = 1 + length r1\n d' = snd (head l') + sum (map snd r1)\n\n print $ if length ys == 1 then snd $ head ys else scan ys r0 k0 d0\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Debug.Trace\n\nsolve :: Int -> Int -> Int -> Int -> [Int] -> Int\nsolve _ cntp cntn ans [_] = max ans $ cntp + cntn\nsolve pre cntp cntn ans (x:y:ys)\n | x == y = trace (show $ cntp + cntn) $ solve pre cntp (cntn+1) ans (y:ys)\n | pre == 0 || pre == y = trace (show $ cntp + cntn) $ solve x (cntp+cntn) 1 ans (y:ys)\n | otherwise = trace (show $ cntp + cntn) $ solve x cntn 1 (max ans $ cntp+cntn) (y:ys)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n as <- map read . words <$> getLine\n print $ solve 0 0 1 0 as\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nsolve :: Int -> Int -> Int -> Int -> [Int] -> Int\nsolve _ cntp cntn ans [_] = max ans $ cntp + cntn\nsolve pre cntp cntn ans (x:y:ys)\n | x == y = solve pre cntp (cntn+1) ans (y:ys)\n | pre == 0 || pre == y = solve x (cntp+cntn) 1 ans (y:ys)\n | otherwise = solve x cntn 1 (max ans $ cntp+cntn) (y:ys)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n as <- map read . words <$> getLine\n print $ solve 0 0 0 0 as\n"}], "src_uid": "b784cebc7e50cc831fde480171b9eb84"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\ndata Triple = Triple {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n\ncomp :: Int -> [Int] -> Int64\ncomp hi xs = fst $ foldl' (\\(!acc, s) (i, x) -> let ~(lts, ges@(Triple il _ _:_)) = span (\\(Triple _ x' _) -> x' < x) s in (acc + sum [fromIntegral x' * fromIntegral (i' - il') * fromIntegral (i - i') :: Int64 | Triple i' x' il' <- lts], Triple i x il:ges)) (0, [Triple 0 hi 0]) (zip [(1 :: Int)..] $ xs ++ [hi])\n\nsolve xs = comp 1000001 xs + comp 0 (map negate xs)\n\nmain = do\n _ <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\ndata Triple = Triple {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n\ncomp :: Int -> [Int] -> Int64\ncomp hi xs = sum $ snd $ mapAccumL (\\s (i, x) -> let ~(lts, ges@(Triple il _ _:_)) = span (\\(Triple _ x' _) -> x' < x) s in (Triple i x il:ges, sum [fromIntegral x' * fromIntegral (i' - il') * fromIntegral (i - i') | Triple i' x' il' <- lts])) [Triple 0 hi 0] (zip [1..] $ xs ++ [hi])\n\nsolve xs = comp 1000001 xs + comp 0 (map negate xs)\n\nmain = do\n _ <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\ncomp :: Int -> [Int] -> Int64\ncomp hi xs = fst $ foldl' (\\(!acc, s) (i, x) -> let (lts, ges@((il, _, _):_)) = span (\\(_, x', _) -> x' < x) s in (acc + sum [fromIntegral x' * fromIntegral (i' - il') * fromIntegral (i - i') :: Int64 | (i', x', il') <- lts], (i, x, il):ges)) (0, [(0, hi, 0)]) (zip [(1 :: Int)..] $ xs ++ [hi])\n\nsolve xs = comp 1000001 xs + comp 0 (map negate xs)\n\nmain = do\n _ <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\ndata Triple = Triple {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n\ncomp :: Int -> [Int] -> Int64\ncomp hi xs = sum $ snd $ mapAccumL (\\s (i, x) -> let (lts, ges@(Triple il _ _:_)) = span (\\(Triple _ x' _) -> x' < x) s in (Triple i x il:ges, sum [fromIntegral x' * fromIntegral (i' - il') * fromIntegral (i - i') | Triple i' x' il' <- lts])) [Triple 0 hi 0] (zip [1..] $ xs ++ [hi])\n\nsolve xs = comp 1000001 xs + comp 0 (map negate xs)\n\nmain = do\n _ <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\ndata Triple = Triple {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n\ncomp :: Int -> [Int] -> Int64\ncomp hi xs = fst $ foldl' (\\(!acc, s) (i, x) -> let (lts, ges@(Triple il _ _:_)) = span (\\(Triple _ x' _) -> x' < x) s in (acc + sum [fromIntegral x' * fromIntegral (i' - il') * fromIntegral (i - i') :: Int64 | Triple i' x' il' <- lts], Triple i x il:ges)) (0, [Triple 0 hi 0]) (zip [(1 :: Int)..] $ xs ++ [hi])\n\nsolve xs = comp 1000001 xs + comp 0 (map negate xs)\n\nmain = do\n _ <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\ndata Tier = Tier !Int64 !Int64 !Int64\n\ngetInts::IO [Int64]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInteger s of\n Nothing -> []\n Just (x, s') -> fromInteger x : go (BS.drop 1 s')\n\nmaxSums::[Int64]->Int64\nmaxSums = fst. foldr (next 1) initial where\n initial = (0, [])\n next cx x (acc, l) = case l of\n [] -> (acc + cx * x, [Tier x cx (x * cx)])\n Tier y cy my : ys\n | x >= y -> next (cx + cy) x (acc, ys)\n | otherwise -> (acc + cx * x + my, Tier x cx (x * cx + my) : l)\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ maxSums xs + maxSums (fmap negate xs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\ndata Tier = Tier {-# UNPACK #-} !Int {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nmaxSums::[Int]->Int64\nmaxSums = fst. foldr (next 1) initial where\n initial = (0, [])\n next cx x (acc, l) = let x' = fromIntegral x in case l of\n [] -> (acc + cx * x', [Tier x cx (x' * cx)])\n Tier y cy my : ys\n | x >= y -> next (cx + cy) x (acc, ys)\n | otherwise -> (acc + cx * x' + my, Tier x cx (x' * cx + my) : l)\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ maxSums xs + maxSums (fmap negate xs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\ndata Tier = Tier {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64\n\ngetInts::IO [Int64]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInteger s of\n Nothing -> []\n Just (x, s') -> fromInteger x : go (BS.drop 1 s')\n\nmaxSums::[Int64]->Int64\nmaxSums = fst. foldr (next 1) initial where\n initial = (0, [])\n next cx x (acc, l) = case l of\n [] -> (acc + cx * x, [Tier x cx (x * cx)])\n Tier y cy my : ys\n | x >= y -> next (cx + cy) x (acc, ys)\n | otherwise -> (acc + cx * x + my, Tier x cx (x * cx + my) : l)\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ maxSums xs + maxSums (fmap negate xs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\ndata Tier = Tier {-# UNPACK #-} !Int {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nmaxSums::[Int]->Int64\nmaxSums = go 1 0 [] where\n go _ acc _ [] = acc\n go cx acc l xs@(x: rest) = let x' = fromIntegral x in case l of\n [] -> go 1 (acc + cx * x') [Tier x cx (x' * cx)] rest\n Tier y cy my : ys\n | x >= y -> go (cx + cy) acc ys xs\n | otherwise -> go 1 (acc + cx * x' + my) (Tier x cx (x' * cx + my) : l) rest\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ maxSums xs + maxSums (fmap negate xs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\ndata Tier = Tier Int64 Int64 Int64\n\ngetInts::IO [Int64]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInteger s of\n Nothing -> []\n Just (x, s') -> fromInteger x : go (BS.drop 1 s')\n\nmaxSums::[Int64]->Int64\nmaxSums = fst. foldr (next 1) initial where\n initial = (0, [])\n next cx x (acc, l) = case l of\n [] -> (acc + cx * x, [Tier x cx (x * cx)])\n Tier y cy my : ys\n | x >= y -> next (cx + cy) x (acc, ys)\n | otherwise -> (acc + cx * x + my, Tier x cx (x * cx + my) : l)\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ maxSums xs + maxSums (fmap negate xs)\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve xs = fin l1 r1 - fin l0 r0\n where\n n = length xs\n zs = zip [1..] xs\n rzs = reverse zs\n lo = 0\n hi = 10^(6 :: Int) + 1\n l0 = map fst $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((> x) . snd) s in (a:s', head s')) [(0, lo)] zs\n r0 = map fst $ reverse $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((>= x) . snd) s in (a:s', head s')) [(n + 1, lo)] rzs\n l1 = map fst $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((< x) . snd) s in (a:s', head s')) [(0, hi)] zs\n r1 = map fst $ reverse $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((<= x) . snd) s in (a:s', head s')) [(n + 1, hi)] rzs\n fin ls rs = sum $ zipWith (\\(i, x) (l, r) -> x * (i - l) * (r - i)) zs $ zip ls rs\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve xs = fin l1 r1 - fin l0 r0\n where\n n = length xs\n zs = zip [1..] xs\n rzs = reverse zs\n lo = 0\n hi = 10^(6 :: Int) + 1\n l0 = map fst $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((> x) . snd) s in (a:s', head s')) [(0, lo)] zs\n r0 = map fst $ reverse $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((>= x) . snd) s in (a:s', head s')) [(n + 1, lo)] rzs\n l1 = map fst $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((< x) . snd) s in (a:s', head s')) [(0, hi)] zs\n r1 = map fst $ reverse $ snd $ mapAccumL (\\s a@(_, x) -> let s' = dropWhile ((<= x) . snd) s in (a:s', head s')) [(n + 1, hi)] rzs\n fin ls rs = sum $ zipWith (\\(i, x) (l, r) -> fromIntegral $ x * (i - l) * (r - i) :: Int64) zs $ zip ls rs\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n print $ solve xs\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\n\ngetInts::IO [Integer]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInteger s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nmaxSums::[Integer]->Integer\nmaxSums = fst. foldl' (next 1) initial where\n initial = (0, [])\n next cx u@(acc, (y, cy) : ys) x\n | x >= y = next (cx + cy) (acc, ys) x\n | otherwise = (acc + cx * x + (cx * cy) * y, (x, cx) : (y, cy) : ys)\n next cx (acc, []) x = (acc + cx * x, [(x, cx)])\n\n\n\nmain :: IO ()\nmain = do\n void getLine\n xs <- getInts\n print $ maxSums xs + maxSums (fmap negate xs)\n"}], "src_uid": "38210a3dcb16ce2bbc81aa1d39d23112"} {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\nimport Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>>\n filter (not . null) >>>\n map (words >>> map read) >>> process >>> map (bool \"No\" \"Yes\") >>> unlines\n\nprocess :: [[Int]] -> [Bool]\nprocess [] = []\nprocess ([_, x]:xs:ys:xss) = solve x xs ys : process xss\n\nsolve :: Int -> [Int] -> [Int] -> Bool\nsolve x xs ys = all (<= x) $ zipWith (+) xs' ys'\n where\n xs' = sort xs\n ys' = reverse . sort $ ys\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Control.Monad\n\nsolveCase :: (Int, [Int], [Int]) -> Bool\nsolveCase (x, a, b) = all (<= x) $ zipWith (+) (sort a) (reverse $ sort b)\n\nreadCase :: IO (Int, [Int], [Int])\nreadCase = do\n [_, x] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n return (x, a, b)\n\nmain = do\n t <- read <$> getLine\n cases <- (:) <$> readCase <*> replicateM (t - 1) (getLine *> readCase)\n mapM_\n (\\x ->\n putStrLn $\n if solveCase x\n then \"Yes\"\n else \"No\")\n cases\n"}, {"source_code": "import qualified Data.Sequence as S\n\ntype Description = (Int, Int, [Int], [Int])\n\ngetTestDesc :: Bool -> IO Description\ngetTestDesc ign = do\n [n, x] <- getArr\n a <- getArr\n b <- getArr\n _ <- if ign then getLine else pure \"\"\n return (n, x, a, b)\n where getArr = getLine >>= pure . map read . words\n\nsolveTest :: Description -> String\nsolveTest (n, x, a, b) = if rz then \"Yes\" else \"No\"\n where seq c = S.sortBy c . S.fromList\n\tsa = seq compare a\n\tsb = seq (flip compare) b\n\tsz = S.zipWith (+) sa sb\n\trz = foldl (&&) True . fmap (\\u -> u <= x) $ sz\n\nmain :: IO ()\nmain = do\n t <- pure . read =<< getLine \n _ <- sequence $ replicate (t - 1) (getTestDesc True >>= putStrLn . solveTest)\n _ <- getTestDesc False >>= putStrLn . solveTest\n return ()\n"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = runNTestCases runTest\n\nrunTest :: IO ()\nrunTest = do\n (_, x) <- read2\n _a <- getLine\n _b <- getLine\n let a = (map read . words) _a\n b = (map read . words) _b\n ans = solve x a b\n putStrLn ans\n eof <- isEOF\n if eof\n then return ()\n else getLine >> return ()\n\n\nsolve :: Int -> [Int] -> [Int] -> String\nsolve x a b = if isImpossible x a b\n then \"No\"\n else \"Yes\"\n\nisImpossible :: Int -> [Int] -> [Int] -> Bool\nisImpossible x a b = any (\\(_a, _b) -> _a + _b > x) $ zip (sort a) (reverse $ sort b)\n\n\nrunNTestCases :: IO () -> IO ()\nrunNTestCases f = do\n n <- read'\n replicateM_ n f\n\nread' :: (Read a) => IO a\nread' = do\n _ln <- getLine\n return (read _ln)\n\nread2 :: (Read a) => IO (a, a)\nread2 = do\n _ln <- getLine\n let [x1, x2] = (map read . words) _ln\n return (x1, x2)\n"}], "negative_code": [], "src_uid": "7e765c1b0e3f3e9c44de825a79bc1da2"} {"source_code": "\nvalid :: [Int] -> Bool\nvalid [] = True\nvalid [_] = True\nvalid (a:b:ls)\n | b == a+1 = valid (b:ls)\n | b < a = valid (b:ls)\n | otherwise = False\n\n\nparse :: String -> [Int]\nparse = map read . words\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve (_:pLine:rest)\n | valid ps = \"YES\": solve rest\n | otherwise = \"NO\" : solve rest\n where\n ps = parse pLine\n\n\nmain :: IO ()\nmain = interact $ unlines . solve . tail . lines\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- (map read.words) <$> getLine\n putStrLn $ if solve as\n then \"Yes\"\n else \"No\"\n\nsolve :: [Int] -> Bool\nsolve as = start (1,xs)\n where xs = reverse as\n\nmiddle :: (Int,Int,Int,[Int]) -> Bool\nmiddle (ziel,n\u00e4chstesZiel,prev,x:xs)\n | prev==x+1 = if x == ziel\n then start (n\u00e4chstesZiel,xs)\n else middle (ziel,n\u00e4chstesZiel,x,xs)\n\n | otherwise = False\nmiddle _ = undefined\n\nstart :: (Int,[Int]) -> Bool\nstart (altesZiel,x:xs)\n | altesZiel == x = start (x+1,xs)\n | otherwise = middle (altesZiel,x+1,x,xs)\nstart _ = True\n"}], "negative_code": [], "src_uid": "dc03b66a4c6aac69372d594784f3f083"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad (replicateM_)\nimport Data.Char (ord)\nimport Data.List (sortOn, sort)\nimport Data.Ord (Down (Down))\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\nparseInts = fmap parseInt . words\n\nmain = do\n testNum <- fmap parseInt getLine\n replicateM_ testNum $ do\n n <- fmap parseInt getLine\n a <- fmap parseInts getLine\n let b = sortOn Down a\n print (min (length b - 2) (b !! 1 - 1))\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n forM_ [1..n] $ const $ do\n x <- read <$> getLine\n str <- (read <$>) <$> words <$> getLine\n print $ min ((sort str !! (x - 2)) - 1) (x - 2)"}, {"source_code": "import Data.Char\nimport System.IO\n\n-- reading functions\n\nstrToIntList :: String -> [Int]\nstrToIntList xs = map toInt (split xs ' ')\n\ntoInt :: String -> Int\ntoInt [] = 0\ntoInt (x:xs) = (digitToInt x) * 10^(length xs) + toInt xs\n\n-- first :: String -> Char -> String\n\n\nsplit :: String -> Char -> [String]\nsplit [] _ = []\nsplit xs c = (first xs c) : split (rest xs c) c where\n first [] c = []\n first (x:xs) c| x==c = []\n | otherwise = x : first xs c\n rest [] c = []\n rest (x:xs) c| x==c = xs\n | otherwise = rest xs c\n\n-- solving functions\n\nmaxL :: Ord a => [a] -> a\nmaxL (x:[]) = x\nmaxL (x:xs) = max x (maxL xs)\n\ngetOneOut :: Eq a => a -> [a] -> [a]\ngetOneOut x [] = []\ngetOneOut x (y:ys)| x==y = ys\n | otherwise = y: (getOneOut x ys)\n\nmax2L :: Ord a => [a] -> a\nmax2L xs = maxL (getOneOut (maxL xs) xs)\n\nsolve :: [Int] -> Int\nsolve xs = min ((max2L xs)-1) (max 0 (length xs)-2)\n\nsolveN :: Int -> IO ()\nsolveN 0 = return ()\nsolveN n = do\n getLine\n t <- getLine\n (putStrLn . show . solve . strToIntList) t\n solveN (n-1)\n\nsolveNf :: Int -> Handle -> IO ()\nsolveNf 0 h = return ()\nsolveNf n h = do\n hGetLine h\n t <- hGetLine h\n (putStrLn . show . solve . strToIntList) t\n solveNf (n-1) h\n\nmain :: IO ()\nmain = do\n -- h <- openFile \"A.in\" ReadMode\n t <- hGetLine stdin\n solveNf (toInt t) stdin\n\n -- hClose h\n return ()"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n forM_ [1..n] $ const $ do\n x <- read <$> getLine\n str <- (read <$>) <$> words <$> getLine\n print $ (sort str !! (x - 2)) - 1"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n forM_ [1..n] $ const $ do\n x <- read <$> getLine\n str <- (read <$>) <$> words <$> getLine\n let srt = sort str\n print $ (srt !! (x - 2)) - 1"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n forM_ [1..n] $ \\_ -> do\n x <- read <$> getLine\n str <- (read <$>) <$> words <$> getLine\n let srt = sort str\n print $ (srt !! (x - 2)) - 1"}], "src_uid": "130fd7f40d879e25b0bff886046bf699"} {"source_code": "import Control.Applicative\n \n\nmain=do\t \n\t[n,a,b]<- map read . words <$> getLine:: IO [Int]\n\tr<- map read. words <$> getLine ::IO [Int]\n\tlet r1 = length $ filter (==1) r\n\tlet r2 = length $ filter (==2) r\n\tlet r3= (max (r1-a) 0) \n\tlet r4 = max ( (max (r2-b) 0) - (if a>r1 then a-r1 else 0)) 0\n\tprint $ r3+r4\n\t", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\t[ n, m, k ] <- map ( read :: String -> Int ) . words <$> getLine\n\tas <- map read . words <$> getLine\n\tprint $ solve as m k\n\nsolve [] m k = ( - min m 0 ) + ( - min k 0 )\nsolve (a:as) m k\n\t| a == 1 = solve as ( m - 1 ) k\n\t| a == 2 = if 0 < k then solve as m ( k - 1 ) else solve as ( m - 1 ) k\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:m:k:a) = solve' m k a\n\nsolve' :: Int -> Int -> [Int] -> Int\nsolve' _ _ [] = 0\nsolve' 0 m (1:x) = 1 + solve' 0 m x\nsolve' n m (1:x) = solve' (n - 1) m x\nsolve' 0 0 (2:x) = 1 + solve' 0 0 x\nsolve' n 0 (2:x) = solve' (n - 1) 0 x\nsolve' n m (2:x) = solve' n (m - 1) x\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,m,k] <- readInts\n as <- readInts\n print $ solve n m k as\n\nsolve n m k as = go m k as\n where\n go _ _ [] = 0\n go 0 k (1:as) = 1+ go 0 k as\n go m k (1:as) = go (m-1) k as\n go 0 0 (2:as) = length as+1\n go m 0 (2:as) = go (m-1) 0 as\n go m k (2:as) = go m (k-1) as\n"}, {"source_code": "import Control.Applicative\n\ndata Type = One | Two deriving Eq\ntype Bowl = Int\ntype Plate = Int\n\nmain = do\n [n,bowls,plates] <- map read.words <$> getLine :: IO [Int]\n types <- getPlan n\n putStrLn.show $ washPlan bowls plates types\n\ngetPlan _ = map convert.words <$> getLine where\n convert \"1\" = One\n convert \"2\" = Two\n \nwashPlan :: Bowl -> Plate -> [Type] -> Int\nwashPlan b p [] = 0\nwashPlan 0 p (One:ts) = 1 + washPlan 0 p ts\nwashPlan b p (One:ts) = washPlan (b-1) p ts\nwashPlan 0 0 (Two:ts) = 1 + washPlan 0 0 ts\nwashPlan 0 p (Two:ts) = washPlan 0 (p-1) ts\nwashPlan b 0 (Two:ts) = washPlan (b-1) 0 ts\nwashPlan b p (Two:ts) = washPlan b (p-1) ts"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n [[n,m,k],xs] <- replicateM 2 $ map read . words <$> getLine\n print $ eat 0 m k xs\neat c _ _ [] = c\neat c 0 k (1:xs) = eat (c+1) 0 k xs\neat c m k (1:xs) = eat c (m-1) k xs\neat c 0 0 (2:xs) = eat (c+1) 0 0 xs\neat c 0 k (2:xs) = eat c 0 (k-1) xs\neat c m 0 (2:xs) = eat c (m-1) 0 xs\neat c m k (2:xs) = eat c m (k-1) xs\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve _ _ [] = 0\nsolve bowls plates (d:ds)\n | d == 1 = if ( bowls > 0 ) then solve (bowls-1) plates ds\n else 1 + solve bowls plates ds\n | otherwise = if ( plates > 0 ) then solve bowls (plates-1) ds\n else if ( bowls > 0 ) then solve (bowls-1) plates ds\n else 1 + solve bowls plates ds\nmain :: IO ()\nmain = do\n firstLine <- getLine\n let [n,bowls,plates] = map read (words firstLine) :: [Int]\n \n secondLine <- getLine\n let days = map read (words secondLine) :: [Int]\n\n print $ solve bowls plates days"}, {"source_code": "import Data.List (foldl')\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:m:k:as) = snd $ foldl' f ((m, k), 0) as\n where f ((b, c), d) 1 | b > 0 = ((b - 1, c), d)\n | otherwise = ((b, c), d + 1)\n f ((b, c), d) _ | c > 0 = ((b, c - 1), d)\n | b > 0 = ((b - 1, c), d)\n | otherwise = ((b, c), d + 1)\nsolve _ = undefined\n"}, {"source_code": "module Main where\n\ndata DishType = Flat | Deep deriving (Eq, Show)\n\nmain = do\n\tdishesString <- getLine\n\tlet dishes = map read $ drop 1 $ words dishesString\n\tfoodString <- getLine\n\tlet food = map read $ words foodString\n\tprint $ useDishes (food :: [Int]) (head (dishes :: [Int]), head $ drop 1 (dishes :: [Int])) \n\n\nuseDishes :: Integral a => [a] -> (a, a) -> a\nuseDishes dishes (deep, flat) = useDishes0 dishes (deep, flat) 0 (deep, flat)\n\nuseDishes0 :: Integral a => [a] -> (a, a) -> a -> (a, a) -> a\nuseDishes0 [] (totalDeep, totalFlat) washes (deep, flat) = washes\nuseDishes0 (x:xs) (totalDeep, totalFlat) washes (deep, flat)\n\t| x == 2 && flat > 0 = useDishes0 xs (totalDeep, totalFlat) washes (deep, flat-1)\n\t| x == 2 && deep > 0 = useDishes0 xs (totalDeep, totalFlat) washes (deep-1, flat)\n\t| x == 2 \t\t\t = useDishes0 xs (totalDeep, totalFlat) (washes+1) $ washAnyDish (deep, flat) (totalDeep, totalFlat)\n\t| x == 1 && deep > 0 = useDishes0 xs (totalDeep, totalFlat) washes (deep-1, flat)\n\t| otherwise \t\t = useDishes0 xs (totalDeep, totalFlat) (washes+1) $ washADish Deep (deep, flat) (totalDeep, totalFlat)\n\nwashAnyDish :: Integral a => (a, a) -> (a, a) -> (a, a)\nwashAnyDish (deep, flat) (totalDeep, totalFlat)\n\t| totalDeep > 0 = (deep, flat) \n\t| totalFlat > 0 = (deep, flat)\n\t| otherwise = error \"no dishes exception, sorry\"\n\nwashADish :: Integral a => DishType -> (a, a) -> (a, a) -> (a, a)\nwashADish dishType (deep, flat) (totalDeep, totalFlat)\n\t| dishType == Deep && totalDeep > 0 = (deep, flat) \n\t| dishType == Flat && totalFlat > 0 = (deep, flat)\n\t| otherwise = error \"no dishes exception, sorry\""}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,m,k] <- readInts\n as <- readInts\n print $ solve n m k as\n\nsolve n m k as = go m k as\n where\n go _ _ [] = 0\n go 0 _ (1:as) = length as+1\n go m k (1:as) = go (m-1) k as\n go 0 0 (2:as) = length as+1\n go m 0 (2:as) = go (m-1) 0 as\n go m k (2:as) = go m (k-1) as\n"}, {"source_code": "module Main where\n\ndata DishType = Flat | Deep deriving (Eq, Show)\n\nmain = do\n dishesString <- getLine\n let dishes = map read $ drop 1 $ words dishesString\n foodString <- getLine\n let food = map read $ words foodString\n print $ useDishes (food :: [Int]) (head (dishes :: [Int]), head $ drop 1 (dishes :: [Int])) \n\n\nuseDishes :: Integral a => [a] -> (a, a) -> a\nuseDishes dishes (deep, flat) = useDishes0 dishes (deep, flat) 0 (deep, flat)\n\nuseDishes0 :: Integral a => [a] -> (a, a) -> a -> (a, a) -> a\nuseDishes0 [] (totalDeep, totalFlat) washes (deep, flat) = washes\nuseDishes0 (x:xs) (totalDeep, totalFlat) washes (deep, flat)\n | x == 2 && flat > 0 = useDishes0 xs (totalDeep, totalFlat) washes (deep, flat-1)\n | x == 2 && deep > 0 = useDishes0 xs (totalDeep, totalFlat) washes (deep-1, flat)\n | x == 2 = useDishes0 xs (totalDeep, totalFlat) (washes+1) $ washAnyDish (deep, flat) (totalDeep, totalFlat)\n | x == 1 && deep > 0 = useDishes0 xs (totalDeep, totalFlat) washes (deep-1, flat)\n | otherwise = useDishes0 xs (totalDeep, totalFlat) (washes+1) $ washADish Deep (deep, flat) (totalDeep, totalFlat)\n\nwashAnyDish :: Integral a => (a, a) -> (a, a) -> (a, a)\nwashAnyDish (deep, flat) (totalDeep, totalFlat)\n | totalDeep > 0 = (deep + 1, flat) \n | totalFlat > 0 = (deep, flat + 1)\n | otherwise = error \"no dishes exception, sorry\"\n\nwashADish :: Integral a => DishType -> (a, a) -> (a, a) -> (a, a)\nwashADish dishType (deep, flat) (totalDeep, totalFlat)\n | dishType == Deep && totalDeep > 0 = (deep + 1, flat) \n | dishType == Flat && totalFlat > 0 = (deep, flat + 1)\n | otherwise = error \"no dishes exception, sorry\""}, {"source_code": "import Control.Applicative\n \n\nmain=do\t \n\t[n,a,b]<- map read . words <$> getLine:: IO [Int]\n\tr<- map read. words <$> getLine ::IO [Int]\n\tlet r1 = length $ filter (==1) r\n\tlet r2 = length $ filter (==2) r\n\tlet r3= (max (r1-a) 0) \n\tlet r4 = (max (r2-b) 0) - (if a>r1 then a-r1 else 0)\n\tprint $ r3+r4\n\t"}], "src_uid": "4ed5b8055ce48b5ad4e43ed4b06d1b07"} {"source_code": "import Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Ratio\nimport Data.Array.IO.Safe\nimport Control.Monad\nimport Data.Int\n\n\nmain = do\n n <- readLn :: IO Int\n dat <- map ((\\[a,b] -> (read a, sort b)) . words) . lines <$> getContents :: IO [(Int64,String)]\n\n let\n inf = 10^9\n a = minimum $ inf : (map fst . filter ((==\"A\") . snd) $ dat)\n b = minimum $ inf : (map fst . filter ((==\"B\") . snd) $ dat)\n c = minimum $ inf : (map fst . filter ((==\"C\") . snd) $ dat)\n ab = minimum $ inf : (map fst . filter ((==\"AB\") . snd) $ dat)\n bc = minimum $ inf : (map fst . filter ((==\"BC\") . snd) $ dat)\n ac = minimum $ inf : (map fst . filter ((==\"AC\") . snd) $ dat)\n abc = minimum $ inf : (map fst . filter ((==\"ABC\") . snd) $ dat)\n\n ans = minimum [abc, a+b+c, ab+(minimum [c,bc,ac]), bc+(minimum [a,ab,ac]), ac+(minimum [b,ab,bc])]\n\n print $ if ans < inf then ans else -1\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Int\n\nmain = do\n n <- readLn :: IO Int\n dat <- map ((\\[a,b] -> (read a, sort b)) . words) . lines <$> getContents :: IO [(Int64,String)]\n\n let\n inf = 10^9\n f str = minimum $ inf : (map fst . filter ((==str) . snd) $ dat)\n a = f \"A\"\n b = f \"B\"\n c = f \"C\"\n ab = f \"AB\"\n bc = f \"BC\"\n ac = f \"AC\"\n abc = f \"ABC\"\n\n ans = minimum [abc, a+b+c, ab+(minimum [c,bc,ac]), bc+(minimum [a,ab,ac]), ac+(minimum [b,ab,bc])]\n\n print $ if ans < inf then ans else -1\n"}], "negative_code": [], "src_uid": "02d62bb1eb4cc0e373b862a980d6b29c"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Map.Strict qualified as Map\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [n, m] <- ri\r\n hgts <- ri\r\n qs <- replicateM m ri\r\n let psumsLR = makePSums [1 ..] $ hgts\r\n let psumsRL = makePSums [n,n-1..] . reverse $ hgts\r\n mapM_ (putStrLn . show . solve (psumsLR,psumsRL)) qs\r\n\r\nsolve (psN,psR) [s,t] = ans\r\n where\r\n ans | (s < t) = (psN!t) - (psN!s)\r\n | otherwise = (psR!t) - (psR!s)\r\n (!) = (Map.!)\r\nsolve _ _ = error \"Input error query\"\r\n\r\nmakePSums inds hgts = Map.fromList . zip (inds::[Int]) . scanl (+) 0 $ dmgs\r\n where\r\n dmgs = zipWith damage hgts (tail hgts)\r\n damage a b = max 0 (a - b)\r\n", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad (replicateM_)\n\ngetN :: IO [Int]\ngetN = map read . words <$> getLine\n\nmain = getN >>=\n \\[n, m] -> getN >>=\n \\as -> replicateM_ m $\n pFall (processDamages n as) (processDamages n (reverse as))\n\nprocessDamages :: Int -> [Int] -> Array Int Int\nprocessDamages n (a:as) = let (_, _, ds) = foldl f (a, 0, [0]) as in\n listArray (1, n) (reverse ds)\n where f (prevH, prevD, acc) currH = if prevH <= currH\n then (currH, prevD, prevD:acc)\n else let currD = prevD + prevH - currH in\n (currH, currD, currD:acc)\n\npFall :: Array Int Int -> Array Int Int -> IO ()\n-- pFall l r = print l >> print r\npFall l r = let (1, n) = bounds l in\n getN >>=\n \\[s, t] -> print $ if s <= t\n then (l!t) - (l!s)\n else (r!(n-t+1)) - (r!(n-s+1))\n"}], "negative_code": [], "src_uid": "a6f42cb2627a7d1f6e01860322c5aac5"} {"source_code": "pairUp :: [String] -> [(String, String)]\r\npairUp [] = []\r\npairUp (x : y : t) = (x, y) : pairUp t\r\n\r\nsolve :: Int -> Int -> Bool\r\nsolve d x\r\n | x >= 10 * d = True\r\n | x == 0 = True\r\n | x < 0 = False\r\n | otherwise = any (solve d) [ x - d - 10 * k | k <- [0 .. 1 + (x - d) `div` 10] ]\r\n \r\n\r\nprocess :: Int -> [Int] -> [Bool]\r\nprocess d = map (solve d)\r\n\r\ngetInput :: (String, String) -> (Int, [Int])\r\ngetInput (s, t) = (d, strToArr t)\r\n where [_, d] = strToArr s\r\n strToArr = map (read :: String -> Int) . words\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBs . uncurry process . getInput) . pairUp . tail . lines)\r\n where showBs = unlines . map showB\r\n showB True = \"YES\"\r\n showB False = \"NO\"\r\n", "positive_code": [{"source_code": "pairUp :: [String] -> [(String, String)]\r\npairUp [] = []\r\npairUp (x : y : t) = (x, y) : pairUp t\r\n\r\nsolve :: Int -> Int -> Bool\r\nsolve d x\r\n | x >= 10 * d = True\r\n | x == 0 = True\r\n | x < 0 = False\r\n | otherwise = any (solve d) [ x - d - 10 * k | k <- [0 .. d] ]\r\n \r\n\r\nprocess :: Int -> [Int] -> [Bool]\r\nprocess d = map (solve d)\r\n\r\ngetInput :: (String, String) -> (Int, [Int])\r\ngetInput (s, t) = (d, strToArr t)\r\n where [_, d] = strToArr s\r\n strToArr = map (read :: String -> Int) . words\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBs . uncurry process . getInput) . pairUp . tail . lines)\r\n where showBs = unlines . map showB\r\n showB True = \"YES\"\r\n showB False = \"NO\"\r\n"}, {"source_code": "pairUp :: [String] -> [(String, String)]\r\npairUp [] = []\r\npairUp (x : y : t) = (x, y) : pairUp t\r\n\r\nsolve :: Int -> Int -> Bool\r\nsolve d x\r\n | x >= 10 * d = True\r\n | x == 0 = True\r\n | x < 0 = False\r\n | otherwise = any (solve d) [ x - d - 10 * k | k <- [0 .. 9] ]\r\n \r\n\r\nprocess :: Int -> [Int] -> [Bool]\r\nprocess d = map (solve d)\r\n\r\ngetInput :: (String, String) -> (Int, [Int])\r\ngetInput (s, t) = (d, strToArr t)\r\n where [_, d] = strToArr s\r\n strToArr = map (read :: String -> Int) . words\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBs . uncurry process . getInput) . pairUp . tail . lines)\r\n where showBs = unlines . map showB\r\n showB True = \"YES\"\r\n showB False = \"NO\"\r\n"}], "negative_code": [], "src_uid": "7975af65a23bad6a0997921c7e31d3ca"} {"source_code": "f :: [Integer]->Integer\n\nf (x:xs) = f' 0 x xs\n where\n f' n x [] = n\n f' n x (y:ys) | x > y + n = f' (n + (x - n - y)) x ys\n f' n x (y:ys) = f' n (y+n) ys\n\nmain = do\n num <- readLn\n nums <- getLine >>= (return.map read.take num.words)\n putStrLn (show (f nums))", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\nreadInput :: IO [Integer]\nreadInput = do\n _ <- B.getLine\n map (fst . fromJust . B.readInteger) . B.words <$> B.getLine\n\nsolve :: [Integer] -> Integer\nsolve xs = sum $ zipWith (\\a b -> max 0 (a - b)) xs (tail xs)\n\nmain :: IO ()\nmain = readInput >>= (print . solve)\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Integer] -> Integer\nsolve [_] = 0\nsolve (a : b : xs)\n | a <= b = solve (b : xs)\n | otherwise = (a - b) + solve (b : xs)\n\nmain :: IO ()\nmain = getLine >> liftM (map read . words) getLine >>= print . solve \n"}, {"source_code": "f :: [Integer] -> Integer\nf (x:y:s) = (max 0 (x-y)) + (f$y:s)\nf _ = 0\nmain=interact$show.f.map read.tail.words\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\n\nreadInteger s = let Just (n,_) = B.readInteger s in n\n\nmain = getLine >> B.getContents >>= print.solve 0.map readInteger.B.words\n\nsolve !cnt [] = cnt\nsolve !cnt [x] = cnt\nsolve !cnt (x:y:xs)\n | x<=y = solve cnt (y:xs)\n | otherwise = solve (cnt+x-y) (y:xs)\n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> Int\nsolve [_] = 0\nsolve (a : b : xs)\n | a <= b = solve (b : xs)\n | otherwise = (a - b) + solve (b : xs)\n\nmain :: IO ()\nmain = getLine >> liftM (map read . words) getLine >>= print . solve \n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\n\nreadInteger s = let Just (n,_) = B.readInteger s in n\n\nmain = getLine >> B.getContents >>= print.solve 0.map readInteger.B.words\n\nsolve !cnt [] = cnt\nsolve !cnt [x] = cnt\nsolve !cnt (x:y:xs)\n | x<=y = solve cnt (y:xs)\n | otherwise = solve (inc+cnt) gx\n where\n (lx,gx) = span ( Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = dropWhile (=='0') $ concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng (a:as) [] acc = (reverse (a:as))++acc\ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)", "positive_code": [{"source_code": "import Data.List\nimport Debug.Trace\n\nsolve :: String -> String -> String\nsolve a b = solve' a $ reverse $ sort b\n where\n solve' [] _ = []\n solve' x [] = x\n solve' (x:xs) (y:ys)\n | x < y = y : solve' xs ys\n | otherwise = x : solve' xs (y:ys)\n\nmain = do\n a <- getLine\n s <- getLine\n putStrLn $ solve a s"}, {"source_code": "\nimport List\n\nsolve :: String -> String -> IO ()\nsolve a s = solve' a (reverse $ sort s)\n where\n solve' :: String -> String -> IO ()\n solve' a [] = putStrLn a\n solve' a (x:xs)\n | null t = putStrLn a\n | otherwise = putStr h >> putStr [x] >> solve' (tail t) xs\n where\n (h, t) = span (>= x) a\n\nmain :: IO ()\nmain = do\n a <- getLine\n s <- getLine\n solve a s\n"}, {"source_code": "import List\ng(a:b)(c:d)|c>a=c:g b d|1>0=a:g b(c:d)\ng l _=l\ns[a,b]=g a(reverse$sort b)\nmain=interact$s.words"}, {"source_code": "import Data.List\n\nmain::IO ()\nmain = do \n cs <- getContents\n (putStr .solve.parseIn) cs\n\n\nparseIn::String->([Int],[Int])\nparseIn s = (num,(reverse $ sort se))\n where\n [num,se] = map (\\x -> map (\\y->read [y]::Int) x) $ lines s\n\nsolve::([Int],[Int])->String\nsolve = concat . map show . solveS \n \nsolveS::([Int],[Int])->[Int]\nsolveS ([],_) = []\nsolveS (a,[])=a\nsolveS ((a:as),(b:bs)) \n | (a>=b) = a:solveS(as,(b:bs))\n | otherwise = b:solveS(as,bs)\n "}, {"source_code": "import Data.List\nimport Data.Char\nimport qualified Data.Map as M\n\nsolve orig repl = \n reverse $ loop orig repl []\n\nloop [] repl acc = acc\nloop (o:os) repl acc = \n if getMax repl > o\n then loop os (decMax repl) ((getMax repl):acc)\n else loop os repl (o:acc)\n\ngetMax mset \n | M.null mset = 0\n | otherwise = fst $ M.findMax mset\n\ndecMax :: M.Map k Int -> M.Map k Int\ndecMax = \n M.updateMax (\\x -> if x > 1 then Just (x-1) else Nothing)\n\nmakeMap l = M.fromList [(head x, length x) | x <- (group $ sort l)]\n\nprepare = map intToDigit\n\nmain = do\n orig <- (getLine >>= (return . map digitToInt))\n repl <- (getLine >>= (return . map digitToInt))\n putStrLn . prepare $ solve orig (makeMap repl)"}], "negative_code": [{"source_code": "import Data.List\nmain=putStrLn.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = dropWhile (=='0') $ concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng (a:as) [] acc = (reverse acc)++(a:as) \ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nmain=putStrLn.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng _ [] acc = acc \ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nmain=putStrLn.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng _ [] acc = acc \ng (a:as) (n:ns) acc\n | (n >= a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nmain=putStrLn.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = dropWhile (=='0') $ concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng _ [] acc = acc \ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nmain=putStrLn.show.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng _ [] acc = acc \ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nmain=putStrLn.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = dropWhile (=='0') $ concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng (a:as) [] acc = (a:as)++acc \ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nmain=putStrLn.slv.(take 2).lines=< Int;f '0' = 0; f '1'=1; f '2' = 2; f '3'=3; f '4' = 4; f '5'=5; f '6' = 6; f '7'=7; f '8' = 8; f '9'=9;\nslv [s1,s2] = dropWhile (=='0') $ concat $ map show $ reverse $ g ns1 ns2 []\n where\n ns1 = map f s1\n ns2 = reverse.sort $ map f s2\n \ng [] _ acc = acc\ng (a:as) [] acc = (a:as)++(reverse acc) \ng (a:as) (n:ns) acc\n | (n > a) = g as ns (n:acc)\n | True = g as (n:ns) (a:acc)"}, {"source_code": "import Data.List\nimport Data.Char\nimport qualified Data.Map as M\n\nsolve orig repl = \n reverse $ loop orig repl []\n\nloop [] repl acc = acc\nloop (o:os) repl acc = \n if getMax repl > o\n then loop os (decMax repl) ((getMax repl):acc)\n else loop os repl (o:acc)\n\ngetMax mset = \n fst $ M.findMax mset\n\ndecMax :: M.Map k Int -> M.Map k Int\ndecMax = \n M.updateMax (\\x -> if x > 1 then Just (x-1) else Nothing)\n\nmakeMap l = M.fromList [(head x, length x) | x <- (group $ sort l)]\n\nmain = do\n orig <- (getLine >>= (return . map digitToInt))\n repl <- (getLine >>= (return . map digitToInt))\n print $ solve orig (makeMap repl)"}], "src_uid": "a2cd56f2d2c3dd9fe152b8e4111df7d4"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n print $ f n\n\nf :: Int -> Int\nf n = n `div` (head $ filter (\\x -> n `mod` x == 0) $ drop 1 $ scanl1 (+) $ takeWhile (<=n) $ iterate (*2) 1)\n", "positive_code": [{"source_code": "solve :: Integer -> Integer -> Integer\nsolve n k = if mod n (2^k - 1) == 0 then div n (2^k - 1)\n else solve n (k+1)\n\nparse :: String -> String\nparse raw = show $ solve n 2\n where n = read raw :: Integer\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "import Control.Monad\n\nmain =\n interact $\n unlines .\n map (show . (\\n -> div n $ head $ filter ((==) 0 . mod n) $ subtract 1 . (^) 2 <$> [2 ..]) . read) . tail . words"}, {"source_code": "solveFor :: Int -> Integer -> Integer\nsolveFor k n | n `mod` (2 ^ k - 1) == 0 = n `div` (2 ^ k - 1)\n | otherwise = solveFor (k + 1) n\n\nsolveCase :: IO ()\nsolveCase = do\n nLine <- getLine\n let n = read nLine :: Integer\n let res = solveFor 2 n\n print res\n\nmain :: IO ()\nmain = do\n tline <- getLine\n let ts = read tline :: Int\n sequence_ [ solveCase | _ <- [1 .. ts] ]\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n print $ solve n\n\nsolve :: Int -> Int\nsolve n = n `div ` head filtered\n where\n powers = 4: map (*2) powers\n powers' = map (\\x -> x-1) powers\n filtered = filter (\\x -> n `mod` x ==0) powers'\n"}, {"source_code": "import Control.Monad (replicateM_)\n\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO :: IO ()\nsolveIO = readLn >>= print . f\n\nf :: Integer -> Integer\nf n = fst . head . filter (\\(_,c)->c==0) $ [(n `div` (2^k-1), n `mod` (2^k-1)) | k <- [2..]]"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\na= [2^i-1|i<-[2..35]]\n\nonecase = do\n\tc<- read <$> getLine ::IO Int\n\tlet x = head $ filter (\\z-> mod c z==0) a \t\n\tprint $ div c x\n\n\nmain = do\n\t \t\n\tn<- read <$> getLine ::IO Int\n\treplicateM_ n onecase\n"}, {"source_code": "process :: Int -> Int\nprocess n = f 3\n where\n f t\n | n `mod` t == 0 = n `div` t\n | otherwise = f (2*t+1)\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n print $ process n\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain =\n interact $\n unlines .\n map (show . (\\n -> div n $ head $ filter ((==) 0 . mod n) $ subtract 1 . (^) 2 <$> [2 ..]) . read) . words"}], "src_uid": "d04cbe78b836e53b51292401c8c969b2"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\ngetnums :: Num a => IO [a]\ngetnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n\ngetstr = getLine\n\nsolve [] used nth = -1\nsolve (a:as) used nth\n | check == False = solve as newUsed (nth + 1)\n | otherwise = nth\n where check = Set.member a used\n newUsed = Set.insert a used\n\nread_ints :: Int -> IO [Int]\nread_ints 0 = return []\nread_ints n = do\n a <- getint\n nxt <- read_ints (n - 1)\n return (a:nxt)\n\nmain = do\n [p, n] <- getints\n as <- map (`mod` p) <$> read_ints n\n putStrLn (show $ solve as Set.empty 1)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\n\nf :: Int -> [Int] -> Int\nf p xs = if length a > 0\n then length xs - fromJust (elemIndex (fst $ last a) xs)\n else (-1)\n where\n h x = mod x p\n a = filter (\\p -> g (fst p) (snd p)) $ zip xs (tail $ tails xs)\n g :: Int -> [Int] -> Bool\n g y ys = any (h y ==) $ map h ys\n\nmain = do\n [p, n] <- fmap (map read . words) getLine :: IO [Int]\n xs <- replicateM n readLn\n print $ f p $ reverse xs\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (p:_:x) = solve' [] 1 x\n where solve' :: [Int] -> Int -> [Int] -> Int\n solve' _ _ [] = -1\n solve' h i (x:xs) | elem (mod x p) h = i\n | otherwise = solve' ((mod x p):h) (i + 1) xs\n"}, {"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve . (map readInt) . words\n\ngo os [] = -1\ngo os (x:xs) = if elem x os then 1 else p $ go (x:os) xs\n\twhere p i = if i < 0 then i else i+1\n\nsolve (p:n:xs) = go [] $ map (`mod` p) xs\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n [p,n] <- map (read :: String -> Int) . words <$> getLine\n xs <- replicateM n (readLn :: IO Int)\n let (as,b) = mapAccumL (\\a b -> (((b`mod`p):head a):a,b`mod`p)) [[]] xs\n m = length $ takeWhile (uncurry notElem) $ zip b $ reverse as\n print $ if m == n then -1 else m+1\n "}, {"source_code": "import Data.List\n\nf::Int->[Int]->[Int]->Int\nf _ [] es=(-1)\nf p (n:ns) es\n |(n `mod` p) `elem` es=(length es)+1\n |otherwise=f p ns ((n `mod` p):es)\n\nmain =do\n e<-getLine\n es<-getContents\n let (p:n:[])=map read (words e)::[Int]\n xs=map read (lines es)::[Int]\n print $ f p xs []"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad.State.Strict\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nsolve :: Int -> [Int] -> State (Set.Set Int) Int\nsolve p queries = do\n processedQueries <- forM queries $ \\query -> do\n let value = query `mod` p\n has <- gets $ Set.member value\n if has\n then return False\n else (modify $ Set.insert value) >> return True\n let queryId = length . takeWhile id $ processedQueries\n if queryId == (length queries) then return (-1) else return (queryId + 1)\n\nmain :: IO ()\nmain = do\n [p, n] <- (map readB8Int) <$> B8.words <$> B8.getLine\n queries <- replicateM n $ readB8Int <$> B8.getLine\n let answer = (flip evalState) Set.empty $ solve p queries \n printf \"%d\\n\" answer\n"}, {"source_code": "import Control.Applicative\nimport Data.Set\n\nsolve :: Int -> [Int] -> Set Int -> Int\nsolve p (x:rst) set =\n if (x `mod` p) `member` set then 1 + (size set) else solve p rst (insert (x `mod` p) set)\nsolve _ [] _ = -1\n\nmain :: IO ()\nmain = do\n [p, _] <- Prelude.map read . words <$> getLine\n x <- Prelude.map read . lines <$> getContents\n putStrLn $ show $ solve p x Data.Set.empty\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>), (<|>))\nimport qualified Data.Set as S\nimport Data.Maybe (fromMaybe, listToMaybe)\nimport Data.List (mapAccumL)\n\nmain :: IO ()\nmain = solve <$> (head . map read . words <$> getLine) <*> (map read . words <$> getContents) >>= print\n\nsolve :: Int -> [Int] -> Int\nsolve p = fromMaybe (-1) . foldl (<|>) Nothing . snd . mapAccumL f S.empty . zip [1..] . map (`mod` p)\n where f s (i, x) = (S.insert x s, listToMaybe [ i | S.member x s ])\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>), (<|>))\nimport Data.List (mapAccumL)\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nmain :: IO ()\nmain = solve <$> (head . map read . words <$> getLine) <*> (map read . words <$> getContents) >>= print\n\nsolve :: Int -> [Int] -> Int\nsolve p = fromMaybe (-1) . foldl (<|>) Nothing . snd . mapAccumL f [] . zip [1..] . map (`mod` p)\n where f xs (i, x) = (x:xs, listToMaybe [ i | x `elem` xs ])\n"}, {"source_code": "main=interact$show.f.map read.words\nf(p:n:xs)=go [] 1 xs\n where\n go used i (x:xs)\n | h <- mod x p, elem h used = i\n | otherwise = go (mod x p:used) (i+1) xs\n go _ _ _ = -1\n "}, {"source_code": "readLi :: Int -> IO [Int]\nreadLi 0 = return []\nreadLi n = do\n\tx <- fmap read getLine :: IO Int\n\ty <- readLi (n-1)\n\treturn (x:y)\n\nisTrue :: [Bool] -> Int -> Bool\nisTrue (x:xs) 0 = x\nisTrue (x:xs) n = isTrue xs (n-1)\n\nputTrue :: [Bool] -> Int -> [Bool]\nputTrue (x:xs) 0 = (True:xs)\nputTrue (x:xs) n = x:putTrue xs (n-1)\n\nfirstEq :: [Int] -> [Bool] -> Int -> Int\nfirstEq [] _ _ = -1\nfirstEq (x:xs) al pos =\n\tlet y = x `mod` length al\n\tin if isTrue al y\n\t\tthen pos + 1\n\t\telse firstEq xs (putTrue al y) (pos + 1) \n\nmain = do\n\tx <- fmap (map read . words) getLine :: IO [Int]\n\tlet p = head x\n\tlet n = last x\n\tl <- readLi n\n\tlet al = [False | _ <- [1..p]]\n\tprint $ firstEq l al 0\n"}, {"source_code": "import Control.Applicative\n\nfirstEq :: [Int] -> [Bool] -> Int -> Int\nfirstEq [] _ _ = -1\nfirstEq (x:xs) al pos =\n let y = x `mod` length al\n in if al!!y\n then pos + 1\n else firstEq xs (take y al ++ [True] ++ drop (y+1) al) (pos + 1) \n\nmain = do\n p <- head . map read . words <$> getLine\n l <- map read . lines <$> getContents \n print $ firstEq l [False | x <- [1..p]] 0"}, {"source_code": "firstEq :: [Int] -> [Bool] -> Int -> Int\nfirstEq [] _ _ = -1\nfirstEq (x:xs) al pos =\n\tlet y = x `mod` length al\n\tin if al!!y\n\t\tthen pos + 1\n\t\telse firstEq xs (take y al ++ [True] ++ drop (y+1) al) (pos + 1) \n\nmain = do\n\tx <- fmap (map read . words) getLine :: IO [Int]\n\tlet p = head x\n\tlet n = last x\n\tl <- fmap (map read . lines) getContents :: IO [Int]\n\tlet al = [False | _ <- [1..p]]\n\tprint $ firstEq l al 0\n"}, {"source_code": "import qualified Data.Set as Set\nc=go Set.empty where\n go s [] = -1\n go s (x : xs) = if Set.member x s then 1 else case go (Set.insert x s) xs of\n -1 -> -1\n n -> n + 1\ns(p:_:n)=c$map(`mod`p)n\nmain=interact$show.s.map read.words\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport qualified Data.IntSet as IS\nimport Text.Printf (printf)\nimport Control.Monad\n\nsolve :: Int -> [Int] -> Int\nsolve p xs = go IS.empty 1 xs\n where\n hash x = x `mod` p\n go _ _ [] = -1\n go seen i (x : xs)\n | IS.member h seen = i\n | otherwise = go (IS.insert h seen) (i + 1) xs\n where h = hash x\n\nmain :: IO ()\nmain = do\n [p, n] <- fmap (map read . words) getLine :: IO [Int]\n xs <- replicateM n readLn\n print $ solve p xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n \nprocess n b x [] = -1\nprocess n b x (c:cs) \t| S.member (mod c b) x = n\n\t\t\t| otherwise = process (n+1) b (S.insert (mod c b) x) cs\t\n \nmain = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tc<-map read <$> replicateM b getLine ::IO [Int]\n\t\tprint $ process 1 a S.empty c\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\ngetnums :: Num a => IO [a]\ngetnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n\ngetstr = getLine\n\nsolve [] used nth = -1\nsolve (a:as) used nth\n | check == False = solve as newUsed (nth + 1)\n | otherwise = nth\n where check = Set.member a used\n newUsed = Set.insert a used\n\nread_ints :: Int -> IO [Int]\nread_ints 0 = return []\nread_ints n = do\n a <- getint\n nxt <- read_ints (n - 1)\n return (a:nxt)\n\nmain = do\n [p, n] <- getints\n as <- read_ints n\n putStrLn (show $ solve as Set.empty 0)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n \nprocess n b x [] = -1\nprocess n b x (c:cs) \t| S.member (mod c b) x = n\n\t\t\t| otherwise = process (n+1) b (S.insert (mod c b) x) cs\t\n \nmain = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tc<-map read <$> replicateM b getLine ::IO [Int]\n\t\tprint $ process 1 b S.empty c\n"}], "src_uid": "5d5dfa4f129bda46055fb636ef33515f"} {"source_code": "import Data.List\nprocess :: [Int] -> ([Int], [Int]) -> Maybe ([Int], [Int])\nprocess (a:b:c:d) (x, y)\n | ((a == b) && (b == c)) = Nothing\n | (a == b) = process (c:d) (a:x, b:y)\n | otherwise = process (b:c:d) (a:x, y)\nprocess [a, b] (x, y) = Just (a:x, b:y)\nprocess [a] (x, y) = Just (a:x, y)\nprocess [] (x, y) = Just (x, y)\n\noutput a = case a of\n Nothing -> putStrLn \"NO\"\n Just (a, b) -> do\n putStrLn \"YES\"\n putStrLn $ show $ length a\n putStrLn $ unwords $ map show $ reverse a\n putStrLn $ show $ length b\n putStrLn $ unwords $ map show $ b\nmain = do\n _ <- getLine\n line <- getLine\n let\n a = sort $ map read $ words $ line\n output $ process a ([], [])\n", "positive_code": [{"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Int\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsYes = byteString $ C.pack \"YES\\n\"\nsNo = byteString $ C.pack \"NO\\n\"\n\nout l = intDec (length l) <> char7 '\\n' <> (mconcat $ (intersperse (char7 ' ') l')) <> char7 '\\n'\n where\n l' = map (\\i -> intDec (fst i) ) l\n\nsolve :: [Int] -> Builder\nsolve (n:a) = if (maximum $ elems c) > 2 then sNo else res\n where\n !m = maximum a\n c = runSTUArray $ do\n d <- newArray (0, m) 0 :: ST s (STUArray s Int Int32) \n forM a $ \\j -> readArray d j >>= ((writeArray d j) . succ)\n return d\n res = sYes <> (out s1) <> out (reverse s2)\n s1 = filter ( ( >= 1) . snd ) $ assocs c\n s2 = filter ( ( == 2) . snd ) $ assocs c\n\n\n\n \n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ru . C.words =<< C.getContents\n"}, {"source_code": "import Data.Array.Unboxed\nhist :: (Int, Int) -> [Int] -> UArray Int Int\nhist bnds is = accumArray (+) 0 bnds [(i, 1) | i <- is, inRange bnds i]\nprocess c (x, y) 0\n | (c!0) > 2 = Nothing\n | (c!0) == 2 = Just (0:x, 0:y)\n | (c!0) == 1 = Just (0:x, y)\n | otherwise = Just (x, y)\nprocess c (x, y) i\n | (c!i) > 2 = Nothing\n | (c!i) == 2 = process c (i:x, i:y) (i - 1)\n | (c!i) == 1 = process c (i:x, y) (i - 1)\n | otherwise = process c (x, y) (i - 1)\noutput a = case a of\n Nothing -> putStrLn \"NO\"\n Just (a, b) -> do\n putStrLn \"YES\"\n putStrLn $ show $ length a\n putStrLn $ unwords $ map show $ a\n putStrLn $ show $ length b\n putStrLn $ unwords $ map show $ reverse b\nmain = do\n _ <- getLine\n line <- getLine\n let\n a = map read $ words $ line\n c = hist (0, 200005) a\n output $ process c ([], []) 200005"}], "negative_code": [{"source_code": "import Data.Array.Unboxed\nhist :: (Int, Int) -> [Int] -> UArray Int Int\nhist bnds is = accumArray (+) 0 bnds [(i, 1) | i <- is, inRange bnds i]\nprocess c (x, y) 0\n | (c!0) > 2 = Nothing\n | (c!0) == 2 = Just (0:x, 0:y)\n | (c!0) == 1 = Just (0:x, y)\n | otherwise = Just (x, y)\nprocess c (x, y) i\n | (c!i) > 2 = Nothing\n | (c!i) == 2 = process c (i:x, i:y) (i - 1)\n | (c!i) == 1 = process c (i:x, y) (i - 1)\n | otherwise = process c (x, y) (i - 1)\noutput a = case a of\n Nothing -> putStrLn \"NO\"\n Just (a, b) -> do\n putStrLn \"YES\"\n putStrLn $ show $ length a\n putStrLn $ unwords $ map show $ reverse a\n putStrLn $ show $ length b\n putStrLn $ unwords $ map show $ b\nmain = do\n _ <- getLine\n line <- getLine\n let\n a = map read $ words $ line\n c = hist (0, 200005) a\n output $ process c ([], []) 200005\n"}], "src_uid": "cdb19d87ad3713dac104252737153411"} {"source_code": "import qualified Data.Set as Set\n\nmain = interact $ show.g.parse.lines\n\nparse xs = map (\\x -> (map read (words x)) :: [Integer]) xs\ng xs\n | (last (head xs)) == 0 = (-1)\n | otherwise = f (init ys) (Set.fromList (last ys)) infinity\n where ys = tail xs\n\ninfinity = (read \"Infinity\")::Double\n\nf [] ys cost\n | cost == infinity = (-1)\n | otherwise = floor cost\nf (x:xs) ys cost\n | (a && (not b)) || ((not a) && b) = f xs ys (min cost c)\n | otherwise = f xs ys cost\n where a = Set.member (head x) ys\n b = Set.member (head (tail x)) ys\n c = fromIntegral (last x)\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O #-}\nimport Data.List (foldl')\nimport Control.Monad\nimport Data.Array\n\nreadIntList = fmap ((map read) . words) getLine :: IO [Int]\n\ninf = truncate 2e9 :: Int\n\nmain = do\n [n,m,k] <- readIntList\n a' <- forM [1..m] $ \\_ -> do\n [u,v,l] <- readIntList\n return [(u,(v,l)),(v,(u,l))]\n let a = accumArray (\\ls pr -> pr:ls) [] (1,n) $ concat a'\n if k == 0\n then print (-1)\n else do\n st <- readIntList\n let storage = accumArray (+) 0 (1,n) $ zip st [1,1..]\n solve x = foldl'(\\acc (ch,len) -> if (storage!ch /= 1 && len < acc) then len else acc) (inf) (a!x)\n ans = minimum . map solve $ st\n if ans == inf then print (-1) else print ans\n"}, {"source_code": "{-# OPTIONS_GHC -O #-}\nimport Data.List (foldl')\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int]\n where fn x = let Just (y,_) = B.readInt x in y\n \n \ninf = truncate 2e9 :: Int\n\nmain = do\n [n,m,k] <- readIntList\n a' <- forM [1..m] $ \\_ -> do\n [u,v,l] <- readIntList\n return [(u,(v,l)),(v,(u,l))]\n let a = accumArray (\\ls pr -> pr:ls) [] (1,n) $ concat a'\n if k == 0\n then print (-1)\n else do\n st <- readIntList\n let storage = accumArray (+) 0 (1,n) $ zip st [1,1..]\n solve x = foldl'(\\acc (ch,len) -> if (storage!ch /= 1 && len < acc) then len else acc) (inf) (a!x)\n ans = minimum . map solve $ st\n if ans == inf then print (-1) else print ans"}, {"source_code": "import Data.List (foldl')\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int]\n where fn x = let Just (y,_) = B.readInt x in y\n \n \ninf = truncate 2e9 :: Int\n\nmain = do\n [n,m,k] <- readIntList\n a' <- forM [1..m] $ \\_ -> do\n [u,v,l] <- readIntList\n return [(u,(v,l)),(v,(u,l))]\n let a = accumArray (\\ls pr -> pr:ls) [] (1,n) $ concat a'\n if k == 0\n then print (-1)\n else do\n st <- readIntList\n let storage = accumArray (+) 0 (1,n) $ zip st [1,1..]\n solve x = foldl'(\\acc (ch,len) -> if (storage!ch /= 1 && len < acc) then len else acc) (inf) (a!x)\n ans = minimum . map solve $ st\n if ans == inf then print (-1) else print ans\n"}, {"source_code": "import Data.List (foldl')\nimport Control.Monad\nimport Data.Array\n\n\nreadIntList = fmap ((map read) . words) getLine :: IO [Int]\n \n \ninf = truncate 2e9 :: Int\n\nmain = do\n [n,m,k] <- readIntList\n a' <- forM [1..m] $ \\_ -> do\n [u,v,l] <- readIntList\n return [(u,(v,l)),(v,(u,l))]\n let a = accumArray (\\ls pr -> pr:ls) [] (1,n) $ concat a'\n if k == 0\n then print (-1)\n else do\n st <- readIntList\n let storage = accumArray (+) 0 (1,n) $ zip st [1,1..]\n solve x = foldl'(\\acc (ch,len) -> if (storage!ch /= 1 && len < acc) then len else acc) (inf) (a!x)\n ans = minimum . map solve $ st\n if ans == inf then print (-1) else print ans\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (accumArray, (!))\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n, m, k] <- readInts\n es <- replicateM m readInts\n\n as <- if k > 0 then readInts else return []\n\n let\n as' = accumArray (flip const) False (1, n) $ zip as (repeat True)\n\n cs = filter f es\n where\n f [u, v, _] = as'!u && (not $ as'!v) || as'!v && (not $ as'!u)\n\n [_, _, r] = minimumBy (comparing (\\[_, _, w] -> w)) cs\n\n if null cs\n then print $ -1\n else print r\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Set (Set, member, fromList)\n\nmain = do\n\t[n, m, k] <- map read . words <$> getLine :: IO [Int]\n\tg <- map (map read . words) <$> replicateM m getLine :: IO [[Int]]\n\n\twhen (k == 0) $ putStrLn \"-1\"\n\twhen (k /= 0) $ do\n\t\ta <- fromList . map read . words <$> getLine :: IO (Data.Set.Set Int)\n\n\t\tlet ls = [l | [u, v, l] <- g, xor (u `member` a) (v `member` a)]\n\t\tprint $ if null ls then -1 else minimum ls\n\nxor a b = (not a && b) || (a && not b)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.IO.Safe\nimport qualified Data.Set\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\t[n, m, k] <- map read . words <$> getLine :: IO [Int]\n\tgraph <- newArray (1, n) [] :: IO (IOArray Int [(Int, Int)])\n\t\n\tforM_ [1..m] $ \\_ -> do\n\t\t[u, v, l] <- map read . words <$> getLine :: IO\t[Int]\n\t\tmodifyArray graph u ((v, l):)\n\t\tmodifyArray graph v ((u, l):)\n\n\twhen (k == 0) $ putStrLn \"-1\"\n\twhen (k /= 0) $ do\n\t\ta <- Data.Set.fromList . map read . words <$> getLine :: IO (Data.Set.Set Int)\n\n\t\tls <- concat <$> (forM [1..n] $ \\u -> do\n\t\t\tgu <- readArray graph u\n\t\t\treturn [l | (v, l) <- gu, u `Data.Set.member` a, v `Data.Set.notMember` a])\n\t\t\n\t\tprint $ if null ls then -1 else minimum ls\n\t\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n storageCity :: Int -> IO [Int]\n storageCity 0 = return []\n storageCity _ = getLine >>= return . (map readInt) . words\n\n eelem :: Int -> S.Set Int -> Bool\n eelem y xs =\n let found = y `S.lookupIndex` xs\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n isStoragePath :: S.Set Int -> [Int] -> Bool\n isStoragePath storages path =\n let checkPath1 = not $ (path !! 1) `eelem` storages\n checkPath2 = not $ (path !! 0) `eelem` storages\n path1isStorage = (path !! 0) `eelem` storages\n path2isStorage = (path !! 1) `eelem` storages\n in (path1isStorage && (not path2isStorage)) || (path2isStorage && (not path1isStorage))\n\n getMinimumPrice :: [[Int]] -> Int\n getMinimumPrice [] = -1\n getMinimumPrice storagePath = minimum $ (map (!!2)) storagePath\n\n main :: IO()\n main = do\n [n,m,k] <- getLine >>= return . (map readInt) . words\n paths <- readMultilineInput m (return . (map readInt) . words)\n storageList <- storageCity k\n let storages = S.fromList storageList\n storagePath = filter (isStoragePath storages) paths\n minimumPrice = getMinimumPrice storagePath\n putStrLn $ show minimumPrice\n"}, {"source_code": "import Prelude hiding (getLine, lookup)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>), (<*>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nimport Control.Monad (replicateM)\nimport Data.Set (Set, empty, fromList, member)\n\nsolve :: [(Int, Int, Int)] -> Set Int -> Int\nsolve e s = if out /= maxBound then out else -1\n where\n out = foldr go maxBound e :: Int\n go :: (Int, Int, Int) -> Int -> Int\n go (u, v, c) acc\n | acc < c + 1 = acc\n | u `member` s = if v `member` s then acc else c\n | otherwise = if v `member` s then c else acc\n\nparse :: ByteString -> [Int]\nparse = unfoldr (B.readInt . B.dropWhile (== ' '))\n\nmain :: IO ()\nmain = do\n _:m:k:_ <- parse <$> getLine\n e <- map ((\\[u, v, c] -> (u, v, c)) . parse) <$> replicateM m getLine\n if k /= 0 then getLine >>= print . solve e . fromList . parse\n else print $ solve e empty\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Prelude\nimport Text.Printf\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport qualified Data.Set as Set\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\n\n\ninfinity = 10000000000 :: Int\n\nfindBest :: [(Int, Int, Int)] -> (Set.Set Int) -> Int\nfindBest [] s = infinity\nfindBest ((a, b, l):es) s | (Set.member a s) /= (Set.member b s) = l `min` v\n | otherwise = v\n where v = findBest es s\n\nsolve :: Tokenizer Int\nsolve = do\n n <- nextInt\n m <- nextInt\n k <- nextInt\n edges <- replicateM m $ do\n a <- nextInt\n b <- nextInt\n l <- nextInt\n return (a, b, l)\n as <- replicateM k $ do\n nextInt\n let bs = Set.fromList as\n let res = findBest edges bs\n if res >= infinity then return (-1)\n else return (res)\n\nmain = do\n contents <- L.getContents\n let ans = evalState solve (L.words contents)\n print ans\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\nimport qualified Data.IntSet as Set\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\ntype Visited = Map.Map Int Bool\ntype Links = Map.Map Int [(Int,Int)] -- (dest, weight)\n\nmain = do\n [n,m,k] <- getInts\n edges <- replicateM m getInts -- m numbers of [u,v,l]\n if k == 0 || k == n\n then print (-1)\n else do\n storages <- getInts -- length: k\n let links = foldl mkLink Map.empty edges :: Links\n let storageCities = Set.fromList storages\n let inf = 10^9 + 7\n -- for each stroage, find the nearest empty city\n let soln = foldl findNearest inf storages where\n findNearest minCost storage = if costs == [] then minCost else min (minimum costs) minCost where\n costs = (map snd . filter notStorage) (neighbors storage)\n neighbors storage = if storage `Map.member` links then links Map.! storage else []\n notStorage (city,len) = city `Set.notMember` storageCities\n if soln == inf\n then print (-1)\n else print soln\n\nmkLink links [u,v,l] = links2 where\n links1 = Map.insertWith (++) u [(v,l)] links\n links2 = Map.insertWith (++) v [(u,l)] links1"}], "negative_code": [{"source_code": "import qualified Data.Set as Set\n\nmain = interact $ show.g.parse.tail.lines\n\nparse xs = map (\\x -> (map read (words x)) :: [Integer]) xs\ng xs = f (init xs) (Set.fromList (last xs)) infinity\n\ninfinity = (read \"Infinity\")::Double\n\nf [] ys cost\n | cost == infinity = (-1)\n | otherwise = floor cost\nf (x:xs) ys cost\n | (a && (not b)) || ((not a) && b) = f xs ys (min cost c)\n | otherwise = f xs ys cost\n where a = Set.member (head x) ys\n b = Set.member (head (tail x)) ys\n c = fromIntegral (last x)\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Set (Set, member, notMember, fromList)\n\nmain = do\n\t[n, m, k] <- map read . words <$> getLine :: IO [Int]\n\tg <- map (map read . words) <$> replicateM m getLine :: IO [[Int]]\n\n\twhen (k == 0) $ putStrLn \"-1\"\n\twhen (k /= 0) $ do\n\t\ta <- fromList . map read . words <$> getLine :: IO (Data.Set.Set Int)\n\n\t\tlet ls = [l | [u, v, l] <- g, u `member` a, v `notMember` a]\n\t\tprint $ if null ls then -1 else minimum ls\n"}], "src_uid": "b0e6a9b500b3b75219309b5e6295e105"} {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ntype Long = Integer\n\n\nsolve :: Long -> Long -> Long -> Long -> Long\nsolve a b c d\n | a <= b = b\n | otherwise =\n case solve' (a-b) c d of\n Nothing -> -1\n Just ans -> b+ans\n\nceilDiv a b\n | a `mod` b == 0 = a `div` b\n | otherwise = 1 + (a `div` b)\n \n\nsolve' :: Long -> Long -> Long -> Maybe Long\nsolve' a c d\n | d >= c = Nothing\n | otherwise = Just $ c * ceilDiv a (c-d)\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (a:b:c:d:_) <- readWords\n print $ solve a b c d\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine", "positive_code": [{"source_code": "main = interact $ f . map (map read) . map words . tail . lines\n\ng (a:b:c:d:_)\n | b >= a = b\n | d >= c = -1\n | otherwise = b + (c*rans)\n where i = (a - b)\n interv = c-d\n ans = quot i interv\n r = rem i interv\n rans = if r==0 then ans else ans+1\n\nf xs = unlines (map show (map g xs))\n"}, {"source_code": "import Data.List\n\nsolve :: String -> String\nsolve s = intercalate \"\\n\" $ map show $ solve' $ map read $ drop 1 $ words s\n\nsolve' :: [Integer] -> [Integer]\nsolve' (a:b:c:d:s) = (solve'' a b c d) : (solve' s)\nsolve' [] = []\n\nsolve'' :: Integer -> Integer -> Integer -> Integer -> Integer\nsolve'' a b c d =\n if a <= b\n then b\n else\n if restPerWake > 0\n then ((a - b + restPerWake - 1) `div` restPerWake) * c + b\n else -1\n where\n restPerWake = c - d\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\t[a,b,c,d]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tprint $ if a <=b then b\n\t\t\t\t else if d>=c then (-1)\n\t\t\t\t else b+ c*((div (a-b) (c-d))+if mod (a-b) (c-d) >0 then 1 else 0)\n\t\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Monad\n\n\n-- parse :: [String] -> [[Integer]]\n-- parse = map (\\l -> map read . words $ l)\n\n\nsolve :: [Integer]->Integer\nsolve (a:b:c:d:[])\n | a<=b = b\n | c<=d = -1\n | otherwise = b + c*(div' needSleep timeAsleep)\n where needSleep = (a-b)\n timeAsleep = (c-d)\n\ndiv' :: Integer -> Integer -> Integer\ndiv' a b\n | a `mod` b == 0 = div a b\n | otherwise = 1+(div a b)\n\ntestCase :: Int -> IO ()\ntestCase 0 = return ()\ntestCase t = do\n test <- getLine\n putStrLn . show . solve . map read . words $ test\n testCase (t-1)\n \n \nmain :: IO ()\nmain = do\n n <- getLine\n testCase . read $ n\n --content <- replicateM (read n :: Int) getLine\n -- putStrLn . unlines . map (show . solve) . parse $ content\n"}], "negative_code": [{"source_code": "main = interact $ f . map (map read) . map words . tail . lines\n\ng (a:b:c:d:_)\n | b > a = b\n | d >= c = -1\n | otherwise = b + (c*rans)\n where i = (a - b)\n interv = c-d\n ans = quot i interv\n r = rem i interv\n rans = if r==0 then ans else ans+1\n\nf xs = unlines (map show (map g xs))\n"}, {"source_code": "import Data.List\n\nsolve :: String -> String\nsolve s = intercalate \"\\n\" $ map show $ solve' $ map read $ drop 1 $ words s\n\nsolve' :: [Int] -> [Int]\nsolve' (a:b:c:d:s) = (solve'' a b c d) : (solve' s)\nsolve' [] = []\n\nsolve'' :: Int -> Int -> Int -> Int -> Int\nsolve'' a b c d =\n if a <= b\n then b\n else\n if restPerWake > 0\n then ((a - b + restPerWake - 1) `div` restPerWake) * c + b\n else -1\n where\n restPerWake = c - d\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ntype Long = Int\n\n\nsolve :: Long -> Long -> Long -> Long -> Long\nsolve a b c d\n | a <= b = b\n | otherwise =\n case solve' (a-b) c d of\n Nothing -> -1\n Just ans -> b+ans\n\nceilDiv a b\n | a `mod` b == 0 = a `div` b\n | otherwise = 1 + (a `div` b)\n \n\nsolve' :: Long -> Long -> Long -> Maybe Long\nsolve' a c d\n | d >= c = Nothing\n | otherwise = Just $ c * ceilDiv a (c-d)\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (a:b:c:d:_) <- readWords\n print $ solve a b c d\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}], "src_uid": "1ab174688ba76168ca047ed2b06b0670"} {"source_code": "import Control.Arrow\n\nmain = do\n [n, m] <- fmap (map read . words) getLine\n s <- getLine\n let (x, y) = gao m s\n print x\n putStrLn y\n\ngao 2 s = min (go s $ cycle \"AB\") (go s $ cycle \"BA\")\n where\n go a b = (length $ filter id $ zipWith (/=) a b, take (length a) b)\n\ngao _ s = go s\n where\n go (x:y:z)\n | x == y = first succ $ second ([x,y']++) $ go z\n | otherwise = second (x:) $ go (y:z)\n where\n z' = if null z then x else head z\n y' = head $ filter (`notElem`[x,z']) \"ABC\"\n go s = (0, s)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Char\n\n{-computeColor colour1 colour2 numberOfColours = \n chr ((ord 'A') + (mod ((ord colour1) -(ord 'A') + 1) numberOfColours))\n -} \n \n\ncomputeColour colour1 colour2 numberOfColours =\n let \n newColour = chr ((ord 'A') + (mod ((ord colour1) -(ord 'A') + 1) numberOfColours))\n in\n if (newColour /= colour2) then newColour\n else chr ((ord 'A') + (mod ((ord colour1) -(ord 'A') + 2) numberOfColours))\n\ngenerateTwoColourStripes stripeLength =\n let generateTwoColourStripes_aux strpLen 'A' result = \n if (strpLen == 0) then ((reverse result),('B' : (reverse (tail result))))\n else generateTwoColourStripes_aux (strpLen-1) 'B' ('A' : result)\n generateTwoColourStripes_aux strpLen _ result =\n if (strpLen == 0) then ((reverse result),('B' : (reverse (tail result))))\n else generateTwoColourStripes_aux (strpLen-1) 'A' ('B' : result)\n in generateTwoColourStripes_aux stripeLength 'A' []\n\n\nsolveTwo stripe stripeLength =\n let (startingWithA,startingWithB) = generateTwoColourStripes stripeLength\n computeChanges [] _ numOfChanges = numOfChanges\n computeChanges (h1 : t1) (h2 : t2) numOfChanges =\n if (h1 == h2) then computeChanges t1 t2 numOfChanges\n else computeChanges t1 t2 (numOfChanges+1)\n in\n let numOfChangesStartingWith_A = computeChanges stripe startingWithA 0\n numOfChangesStartingWith_B = computeChanges stripe startingWithB 0\n in\n if (numOfChangesStartingWith_A < numOfChangesStartingWith_B) then\n (numOfChangesStartingWith_A,startingWithA)\n else\n (numOfChangesStartingWith_B,startingWithB)\n\nsolveMany stripe numberOfColours =\n let solve_aux [] numberOfchanges result = (numberOfchanges, (reverse result))\n solve_aux (h : rest) numberOfchanges result = \n\t if ((head result) == h) then \n if (rest == []) then \n solve_aux rest (numberOfchanges+1) ((computeColour h h numberOfColours) : result)\n else\n solve_aux rest (numberOfchanges+1) ((computeColour h (head rest) numberOfColours) : result)\n else solve_aux rest numberOfchanges (h : result)\n in\n solve_aux (tail stripe) 0 [(head stripe)]\n\n\n\nsolve stripe numberOfColours stripeLength =\n if (numberOfColours > 2) then solveMany stripe numberOfColours\n else solveTwo stripe stripeLength\n\nmain = do\n all <- getContents\n let (sl : nc : stripe : ignore) = words all\n let stringLength = ((read sl) :: Int)\n let numberOfColours = ((read nc) :: Int)\n let (numberOfChanges,solution) = solve stripe numberOfColours stringLength\n print numberOfChanges\n putStrLn solution\n{- let (startingWithA,startingWithB) = generateTwoColourStripes 10\n print startingWithA\n print startingWithB\n print stringLength\n print numberOfColours\n print stripe-}\n \n\n\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Char\n\n{-computeColor colour1 colour2 numberOfColours = \n chr ((ord 'A') + (mod ((ord colour1) -(ord 'A') + 1) numberOfColours))\n -} \n \n\ncomputeColour colour1 colour2 numberOfColours =\n let \n newColour = chr ((ord 'A') + (mod ((ord colour1) -(ord 'A') + 1) numberOfColours))\n in\n if (newColour /= colour2) then newColour\n else chr ((ord 'A') + (mod ((ord colour1) -(ord 'A') + 2) numberOfColours))\n\ngenerateTwoColourStripes stripeLength =\n let generateTwoColourStripes_aux strpLen 'A' result = \n if (strpLen == 0) then ((reverse result),('B' : (reverse (tail result))))\n else generateTwoColourStripes_aux (strpLen-1) 'B' ('A' : result)\n generateTwoColourStripes_aux strpLen _ result =\n if (strpLen == 0) then ((reverse result),('B' : (reverse (tail result))))\n else generateTwoColourStripes_aux (strpLen-1) 'A' ('B' : result)\n in generateTwoColourStripes_aux stripeLength 'A' []\n\n\nsolveTwo stripe stripeLength =\n let (startingWithA,startingWithB) = generateTwoColourStripes stripeLength\n computeChanges [] _ numOfChanges = numOfChanges\n computeChanges (h1 : t1) (h2 : t2) numOfChanges =\n if (h1 == h2) then computeChanges t1 t2 numOfChanges\n else computeChanges t1 t2 (numOfChanges+1)\n in\n let numOfChangesStartingWith_A = computeChanges stripe startingWithA 0\n numOfChangesStartingWith_B = computeChanges stripe startingWithB 0\n in\n if (numOfChangesStartingWith_A < numOfChangesStartingWith_B) then\n (numOfChangesStartingWith_A,startingWithA)\n else\n (numOfChangesStartingWith_B,startingWithB)\n\nsolveMany stripe numberOfColours =\n let solve_aux [] numberOfchanges result = (numberOfchanges, (reverse result))\n solve_aux (h : rest) numberOfchanges result = \n\t if ((head result) == h) then \n if (rest == []) then \n solve_aux rest (numberOfchanges+1) ((computeColour h h numberOfColours) : result)\n else\n solve_aux rest (numberOfchanges+1) ((computeColour h (head rest) numberOfColours) : result)\n else solve_aux rest numberOfchanges (h : result)\n in\n solve_aux (tail stripe) 0 [(head stripe)]\n\n\n\nsolve stripe numberOfColours stripeLength =\n if (numberOfColours > 2) then solveMany stripe numberOfColours\n else solveTwo stripe stripeLength\n\nmain = do\n all <- getContents\n let (sl : nc : stripe : ignore) = words all\n let stringLength = ((read sl) :: Int)\n let numberOfColours = ((read nc) :: Int)\n let (numberOfChanges,solution) = solve stripe numberOfColours stringLength\n print numberOfChanges\n print solution\n{- let (startingWithA,startingWithB) = generateTwoColourStripes 10\n print startingWithA\n print startingWithB\n print stringLength\n print numberOfColours\n print stripe-}\n \n\n\n\n"}], "src_uid": "0ecf60ea733eba71ef1cc1e736296d96"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check n a bs ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> Int -> [Int] -> [Int] -> Int -> Bool\ncheck n a bs ps k = go a (drop (n-k) bs) ps\n where\n go a _ _ | a < 0 = False\n go a (b:bs) (p:ps) | b >= p = go a bs ps\n | otherwise = go (a - (p - b)) bs ps\n go a [] _ = True\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check n a bs ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> Int -> [Int] -> [Int] -> Int -> Bool\ncheck n a bs ps k = go a (zipWith f (drop (n-k) bs) ps)\n where\n f bi pi = max 0 (fromIntegral (pi - bi))\n go a _ | a < 0 = False\n go a (x:xs) = go (a-x) xs\n go a [] = True\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check n a bs ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> Int -> [Int] -> [Int] -> Int -> Bool\ncheck n a bs ps k = sum (zipWith f (drop (n-k) bs) ps) <= fromIntegral a\n where\n f bi pi = max 0 (fromIntegral (pi - bi)) :: Int64\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check a (reverse bs) ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> [Int] -> [Int] -> Int -> Bool\ncheck a bs ps k = sum (zipWith f (reverse $ take k bs) ps) <= fromIntegral a\n where\n f bi pi = max 0 (fromIntegral (pi - bi)) :: Int64\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check n a bs ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> Int -> [Int] -> [Int] -> Int -> Bool\ncheck n a bs ps k = go a (drop (n-k) bs) ps\n where\n {-# INLINE go #-}\n go a _ _ | a < 0 = False\n go a (b:bs) (p:ps) | b >= p = go a bs ps\n | otherwise = go (a - (p - b)) bs ps\n go a [] _ = True\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check a (reverse bs) ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> [Int] -> [Int] -> Int -> Bool\ncheck a bs ps k = go a (reverse (take k bs)) ps\n where\n {-# INLINE go #-}\n go a _ _ | a < 0 = False\n go a (b:bs) (p:ps) | b >= p = go a bs ps\n | otherwise = go (a - (p - b)) bs ps\n go a [] _ = True\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check a (reverse bs) ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> [Int] -> [Int] -> Int -> Bool\ncheck a bs ps k = go a (reverse (take k bs)) ps\n where\n go a _ _ | a < 0 = False\n go a (b:bs) (p:ps) | b >= p = go a bs ps\n | otherwise = go (a - (p - b)) bs ps\n go a [] _ = True\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check a (reverse bs) ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> [Int] -> [Int] -> Int -> Bool\ncheck a bs ps k = sum (zipWith f (reverse $ take k bs) ps) <= a\n where\n f bi pi = max 0 (pi - bi)\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n when (a == 399) $ do\n let bs' = map (head &&& length) $ group $ bs\n let ps' = map (head &&& length) $ group $ ps\n print bs'\n print ps'\n printf \"%d %d\\n\" r s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> (Int,Int)\nsolve n m a bs ps = (r,s)\n where\n r = binSearch (check a (reverse bs) ps) 0 (min n m)\n s = max 0 (sum (take r ps) - a)\n\nbinSearch f a b = if f b then b else go a b\n where\n go a b | b - a == 1 = a\n | f m = go m b\n | otherwise = go a m\n where m = (a+b)`div`2\n\ncheck :: Int -> [Int] -> [Int] -> Int -> Bool\ncheck a bs ps k = sum (zipWith f (reverse $ take k bs) ps) <= a\n where\n f bi pi = max 0 (pi - bi)\n\nmain = do\n [n,m,a] <- readInts\n bs <- sort <$> readInts\n ps <- sort <$> readInts\n let (r,s) = solve n m a bs ps\n printf \"%d %d\\n\" r s\n"}], "src_uid": "cf8249244f67fb26bee3cdf0daedaca0"} {"source_code": "module Main where\n\nimport Data.List (group, sort)\n\n\noutput :: Bool -> IO ()\noutput b = putStrLn $ if b then \"Yes\" else \"No\"\n\nsolve :: String -> Bool\nsolve str = case map length . group . sort $ str of\n [m, n] -> m >= 2 && n >= 2\n [m, n, k] -> m + n + k >= 4\n [_, _, _, _] -> True\n _ -> False\n\nmain :: IO ()\nmain = output . solve =<< getLine", "positive_code": [{"source_code": "import qualified Data.Map as Map\n\nfunc :: String -> String\nfunc str = \n let mp = Map.toList $ helper str Map.empty where \n helper :: String -> Map.Map Char Int -> Map.Map Char Int \n helper (s:ss) m = case Map.lookup s m of \n Nothing -> helper ss (Map.insert s 1 m)\n Just(v)-> helper ss (Map.insert s (v + 1) m)\n helper _ m = m \n in\n if (length mp) > 4 || (length mp) < 2 || (length str) < 4 then \"NO\"\n else if (length mp) == 2 && (length (filter (\\x -> (snd x) == 1) mp)) > 0 then \"NO\"\n else \"YES\"\n\nmain :: IO ()\nmain = do\n l <- getLine\n putStrLn $ func l\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nmain = getLine >>= putStr . exec\nexec = (\\case { [a, _] | a > 1 -> \"Yes\"; xs@[_, _, _] | last xs > 1 -> \"Yes\"; [_, _, _, _] -> \"Yes\"; _ -> \"No\" }) . sort . map length . group . sort"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nmain = getLine >>= putStr . exec\nexec = (\\case { [a, _] | a > 1 -> \"Yes\"; [_, _, b] | b > 1 -> \"Yes\"; [_, _, _, _] -> \"Yes\"; _ -> \"No\" }) . sort . map length . group . sort"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >>= putStrLn . which \"Yes\" \"No\" . solve . sort . map length . group . sort\n\nsolve [ a, b ] = 2 <= a && 2 <= b\nsolve [ a, b, c ] = 2 <= c\nsolve [ a, b, c, d ] = True\nsolve _ = False"}], "negative_code": [{"source_code": "import qualified Data.Map as Map\n\nfunc :: String -> String\nfunc str = \n let mp = Map.toList $ helper str Map.empty where \n helper :: String -> Map.Map Char Int -> Map.Map Char Int \n helper (s:ss) m = case Map.lookup s m of \n Nothing -> helper ss (Map.insert s 1 m)\n Just(v)-> helper ss (Map.insert s (v + 1) m)\n helper _ m = m \n in\n if (length mp) > 4 || (length mp) < 2 then \"NO\"\n else if (length mp) == 2 && (length (filter (\\x -> (snd x) == 1) mp)) > 0 then \"NO\"\n else \"YES\"\n\nmain :: IO ()\nmain = do\n l <- getLine\n putStrLn $ func l\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nmain = getLine >>= putStr . exec\nexec = (\\case { [a, _] | a > 1 -> \"Yes\"; [_, b, _] | b > 1 -> \"Yes\"; [_, _, _, _] -> \"Yes\"; _ -> \"No\" }) . sort . map length . group . sort"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nmain = getLine >>= print . exec\nexec = (\\case { [a, _] | a > 1 -> \"Yes\"; [_, b, _] | b > 1 -> \"Yes\"; [_, _, _, _] -> \"Yes\"; _ -> \"No\" }) . sort . map length . group . sort"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nmain = interact exec\nexec = (\\case { [a, b] | a > 1 -> \"Yes\"; [a, b, c] | b > 1 -> \"Yes\"; [a, b, c, d] -> \"Yes\"; _ -> \"No\" }) . sort . map length . group . sort"}], "src_uid": "6190db9007f8f5eba095a6fcfc3652fc"} {"source_code": "main = do\n d <- readLn\n getLine\n as <- fmap (map read . words) getLine\n print $ sum $ map ((`mod` d) . (d -)) $ init as\n", "positive_code": [{"source_code": "main=putStrLn.show.(\\(d:z:as) -> slv d (take (z-1) $ as)).map read.words=< IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nsolve :: Integer -> [Integer] -> Integer\nsolve d [] = error \"Empty List!\"\nsolve d [a] = 0\nsolve d (a:as) = (d-a) + solve d as\n\nmain :: IO ()\nmain = do\n d <- readLn\n getLine\n as <- Main.reads\n print $ solve d as\n"}, {"source_code": "solve :: (Integral a) => a -> a -> [a] -> a\nsolve d n xs =\n let\n full = (n-1)*d\n act = sum.init $ xs\n in\n full - act\n\nmain = \n do\n dstr <- getLine\n nstr <- getLine\n astr <- getLine\n putStrLn.show $ solve (read dstr) (read nstr) (map read $ words astr)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nprocess :: Int -> [Int] -> Int\nprocess d [] = 0\nprocess d [a] = 0\nprocess d (a: as) = (d - a) + (process d as)\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\t_ <- getLine\n\tarr1 <- getLine\n\tlet\n\t\td = read line:: Int\n\t\ta = map (\\x -> read x :: Int).words $ arr1\n\tprint $ process d a\n"}, {"source_code": "\nanswer :: Int -> [Int] -> Int\nanswer d as = sum . map (d -) . init $ as\n\nmain = do\n\td <- getLine\n\t_ <- getLine\n\tas <- getLine\n\tputStrLn . show $ answer (read d) (map read . words $ as)"}, {"source_code": "answer d a = sum . map(d-) . init $ a\nmain = do\n line <- getLine\n let d = read line :: Int\n getLine\n line <- getLine\n let a = map read . words $ line\n putStrLn . show $ answer d a\n"}], "negative_code": [{"source_code": "main = do\n d <- readLn\n getLine\n as <- fmap (map read . words) getLine\n print $ sum $ map ((`mod` d) . (d -)) $ tail as\n"}, {"source_code": "main=putStrLn.show.(\\(d:z:as) -> slv d (take z $ as)).map read.words=< a) = f d as 1 (acc + d - a)\n | otherwise = f d (a:as) (t+1) acc"}, {"source_code": "main=putStrLn.show.(\\(d:z:as) -> slv d (take z $ as)).map read.words=< d) = f d as 1 (acc + d - a)\n | otherwise = f d (a:as) (t+1) acc"}, {"source_code": "main=putStrLn.show.(\\(d:z:as) -> slv d (take z $ as)).map read.words=< a) = f d as 1 (acc + d - a)\n | otherwise = f d (a:as) (t+1) acc"}], "src_uid": "dc5ddfc2d2e5589eb91aa33744c8fd14"} {"source_code": "import Data.List\n\nsolve :: String -> Int\nsolve x | n_threes > 0 || n_twos > 1 = 2 + n_groups\n | n_twos == 1 = 1 + n_groups\n | otherwise = n_groups\n where\n groups = map length $ group x\n n_groups = length groups\n f :: Int -> [Int] -> Int\n f i = length . filter (>=i)\n n_twos = f 2 groups\n n_threes = f 3 groups\n\nmain = interact $ show . solve . last . lines\n", "positive_code": [{"source_code": "import Data.Char (ord)\n\nparse :: String -> String\nparse = (!! 1) . lines\n\nsolve :: String -> Int\nsolve s = 1 + ones + min zeros 2\n where a = map (\\c -> ord c - 48) s\n zeros = length . filter id $ zipWith (==) a (tail a)\n ones = length a - 1 - zeros\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}, {"source_code": "import Data.List\n\n(|>) a b = b a\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n let n = s1 |> (read :: String -> Int)\n d = s2 |> group |> map length |> length\n r = min (d + 2) (length s2)\n print r"}, {"source_code": "import Data.List\n\n(|>) a b = b a\n\ngetInt = do\n s <- getLine\n return (s |> (read :: String -> Int))\n \nmain = do\n n <- getInt\n s <- getLine\n f n s |> print\n \nf n s = let\n ms = s |> group |> map length in\n length ms + if any (>= 3) ms then 2 else\n min 2 (ms |> filter (== 2) |> length)"}, {"source_code": "\ncount :: Char -> String -> Int\ncount _ [] = 0\ncount a (b:bs)\n | a == b = count a bs\n | otherwise = 1 + count b bs\n\n\nsolve' :: String -> Int\nsolve' (x:xs) = count x xs\nsolve' _ = 0\n\nsolve :: Int -> String -> Int\nsolve a b = min a $ ( (solve' b) + 3 )\n\nparse :: String -> String\nparse a = show $ solve (read $ head x) $ last x where x = words a\n\nmain = interact parse"}, {"source_code": "import Data.List\n\nparse :: String -> String\nparse = (!! 1) . lines\n\nadder :: [[Char]]->Int\nadder s = min 2 $ sum $ map (\\a -> length a - 1) s\n\nsolve :: String->Int\nsolve s = (length a) + adder a\n where a = group s\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n\n\n"}], "negative_code": [{"source_code": "import Data.List\n\nsolve :: String -> Int\nsolve x | n_threes > 0 || n_twos > 1 = 2 + n_groups\n | otherwise = n_groups\n where\n groups = map length $ group x\n n_groups = length groups\n f :: Int -> [Int] -> Int\n f i = length . filter (>=i)\n n_twos = f 2 groups\n n_threes = f 3 groups\n\nmain = interact $ show . solve . last . lines\n"}, {"source_code": "import Data.List\n\nsolve :: String -> Int\nsolve x | n_threes > 0 || n_twos > 1 = 2 + n_groups\n | head groups == 2 || last groups == 2 = 1 + n_groups\n | otherwise = n_groups\n where\n groups = map length $ group x\n n_groups = length groups\n f :: Int -> [Int] -> Int\n f i = length . filter (>=i)\n n_twos = f 2 groups\n n_threes = f 3 groups\n\nmain = interact $ show . solve . last . lines\n"}, {"source_code": "import Data.List\n\n(|>) a b = b a\n\ngetInt = do\n s <- getLine\n return (s |> (read :: String -> Int))\n \nmain = do\n n <- getInt\n s <- getLine\n f n s |> print\n \nf n s = let\n ms = s |> group |> map length in\n length ms + if any (>= 3) ms then 2 else\n (if head ms >= 2 then 1 else 0) + (if last ms >= 2 then 1 else 0)"}, {"source_code": "import Data.List\n\nparse :: String -> String\nparse = (!! 1) . lines\n\nadder :: [[Char]]->Int\nadder s = min 2 $ sum $ map (\\a -> length a + 1) s\n\nsolve :: String->Int\nsolve s = (length a) + adder a\n where a = group s\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n\n\n"}], "src_uid": "7b56edf7cc71a1b3e39b3057a4387cad"} {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n getLine\r\n healths <- map read . words <$> getLine\r\n blessings <- map read . words <$> getLine\r\n print $ sum healths + sum blessings - maximum blessings\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- read <$> getLine\r\n replicateM_ testCases testCase\r\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n B.getLine\r\n healths <- map (maybe 0 fst . B.readInt) . B.words <$> B.getLine\r\n blessings <- map (maybe 0 fst . B.readInt) . B.words <$> B.getLine\r\n print $ sum healths + sum blessings - maximum blessings\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- B.readInt <$> B.getLine\r\n replicateM_ (maybe 0 fst testCases) testCase\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int64] -> [Int64] -> Int64\nsolve n as bs = damage \n where\n damage = sum as + sum bs - maximum bs\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntegerB8s <&> L.map fromInteger\n bs <- B8.getLine <&> readIntegerB8s <&> L.map fromInteger\n let answer = solve n as bs\n printf \"%lld\\n\" $ answer\n"}, {"source_code": "{-# LANGUAGE LambdaCase, OverloadedLists, OverloadedStrings, TypeFamilies #-}\r\nimport Control.Monad\r\nimport Control.Monad.Fix\r\nimport Control.Monad.Reader\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.Map as M\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified GHC.Exts as Exts\r\n\r\n-- Mike \u0f3c \u3064 \u25d5_\u25d5 \u0f3d\u3064 pls add lisps\r\n\r\nsolveCase :: E\r\nsolveCase =\r\n [\"lambda\", [\"inp\"],\r\n [\"letrec\", [[\"a\", [\"car\", \"inp\"]],\r\n [\"b\", [\"cadr\", \"inp\"]],\r\n [\"asum\", [\"apply\", \"+\", \"a\"]],\r\n [\"bsum\", [\"apply\", \"+\", \"b\"]],\r\n [\"bmax\", [\"apply\", \"max\", \"b\"]]],\r\n [\"-\", [\"+\", \"asum\", \"bsum\"], \"bmax\"]]]\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- getInts\r\n replicateM_ t $ do\r\n getInts\r\n as <- getInts\r\n bs <- getInts\r\n print $ unI $ run [solveCase, [\"q\", [L (map I as), L (map I bs)]]]\r\n\r\ngetInts :: IO [Int]\r\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\n----------\r\n\r\ndata E = I { unI :: Int } | M { unM :: String } | L { unL :: [E] } | F { unF :: [E] -> E }\r\n\r\ninstance Eq E where\r\n I x == I y = x == y\r\n M x == M y = x == y\r\n L x == L y = x == y\r\n _ == _ = False\r\n\r\ninstance Exts.IsString E where\r\n fromString = M\r\n\r\ninstance Exts.IsList E where\r\n type Item E = E\r\n fromList = L\r\n\r\nrun :: E -> E\r\nrun p = runReader (eval p) $ M.fromList\r\n [ (\"+\", F $ I . sum . map unI)\r\n , (\"-\", F $ I . \\case [I x] -> -x; (I x : xs) -> foldl' (-) x (map unI xs))\r\n , (\"max\", F $ I . maximum . map unI)\r\n , (\"car\", F $ \\[L x] -> head x)\r\n , (\"cadr\", F $ \\[L x] -> head (tail x))\r\n , (\"apply\", F $ \\[F x, L xs] -> x xs)\r\n ]\r\n\r\neval :: E -> Reader (M.Map String E) E\r\neval = \\case\r\n I x -> pure (I x)\r\n M x -> asks (M.! x)\r\n L x -> case x of\r\n [\"q\", x] -> pure x\r\n \"lambda\" : L xs : body -> do\r\n cur <- ask\r\n pure $ F $ \\ys ->\r\n runReader (last <$> mapM eval body) (M.fromList (zip (map unM xs) ys) <> cur)\r\n \"letrec\" : L xs : body -> do\r\n new <- mfix $ \\new -> do\r\n cur <- ask\r\n local (const new) $\r\n (<> cur) . M.fromList <$> mapM (\\(L [M x, y]) -> (,) x <$> eval y) xs\r\n local (const new) $ last <$> mapM eval body\r\n f : xs -> unF <$> eval f <*> mapM eval xs\r\n"}, {"source_code": "import Data.Char\r\nimport Control.Monad\r\n\r\nsolve as bs = sum as + sum bs - foldr max 0 bs\r\n\r\n\r\nloop = do\r\n _ <- getLine\r\n as <- map read <$> words <$> getLine\r\n bs <- map read <$> words <$> getLine\r\n print (solve as bs)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t loop\r\n \r\n\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\n----- Solution\r\ndata TC = TC { n :: Int, as :: [Int64], bs :: [Int64] }\r\n\r\ntype Output = Int64\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n as <- n >< int64\r\n bs <- n >< int64\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = sum as + sum (bs >$> sort >>> init)\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput ix = showB\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1..] >>> map (uncurry output) >>> C.unlines\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE RecordWildCards #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sortOn)\r\nimport qualified Data.Map as M\r\n\r\ndata Game = Game\r\n { positionToBlessing :: M.Map Int Int\r\n , monsters :: [Monster]\r\n }\r\n\r\ndata Monster = Monster\r\n { position :: Int\r\n , health :: Int\r\n , blessing :: Int\r\n }\r\n\r\nsolve :: Game -> Int\r\nsolve g@Game{..}\r\n | null monsters = 0\r\n | otherwise = health bestMonster + positionalBlessing g bestMonster +\r\n solve newGame\r\n where topMonsters = take 3 monsters\r\n (bestMonster:otherMonsters') = sortOn (greedyScore g) topMonsters\r\n otherMonsters = sortOn blessing otherMonsters'\r\n newGame = Game\r\n { positionToBlessing = M.delete (position bestMonster) positionToBlessing\r\n , monsters = otherMonsters ++ drop 3 monsters\r\n }\r\n\r\ngreedyScore :: Game -> Monster -> Int\r\ngreedyScore Game{..} Monster{..}\r\n | atFront && atBack = 0\r\n | atFront = blessing - snd (M.elemAt (M.findIndex position positionToBlessing + 1) positionToBlessing)\r\n | atBack = blessing - snd (M.elemAt (M.findIndex position positionToBlessing - 1) positionToBlessing)\r\n | otherwise = 2 * blessing\r\n where atFront = position == fst (M.findMin positionToBlessing)\r\n atBack = position == fst (M.findMax positionToBlessing)\r\n\r\npositionalBlessing :: Game -> Monster -> Int\r\npositionalBlessing Game{..} Monster{..}\r\n | atFront && atBack = 0\r\n | atFront || atBack = blessing\r\n | otherwise = 2 * blessing\r\n where atFront = position == fst (M.findMin positionToBlessing)\r\n atBack = position == fst (M.findMax positionToBlessing)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n numberMonsters <- read <$> getLine\r\n healths <- map read . words <$> getLine\r\n blessings <- map read . words <$> getLine\r\n print $ solve $\r\n Game\r\n { positionToBlessing = M.fromList $ [1..numberMonsters] `zip` blessings\r\n , monsters = sortOn blessing $ map (\\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings\r\n }\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- read <$> getLine\r\n replicateM_ testCases testCase\r\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sortOn)\r\nimport qualified Data.Map as M\r\n\r\ndata Game = Game\r\n { positionToBlessing :: M.Map Int Int\r\n , monsters :: [Monster]\r\n }\r\n\r\ndata Monster = Monster\r\n { position :: Int\r\n , health :: Int\r\n , blessing :: Int\r\n }\r\n\r\nsolve :: Game -> Int\r\nsolve g@Game{..}\r\n | null monsters = 0\r\n | otherwise = health bestMonster + positionalBlessing g bestMonster +\r\n solve newGame\r\n where topMonsters = take 3 monsters\r\n (bestMonster:otherMonsters') = sortOn (greedyScore g) topMonsters\r\n otherMonsters = sortOn blessing otherMonsters'\r\n newGame = Game\r\n { positionToBlessing = M.delete (position bestMonster) positionToBlessing\r\n , monsters = otherMonsters ++ drop 3 monsters\r\n }\r\n\r\ngreedyScore :: Game -> Monster -> Int\r\ngreedyScore Game{..} Monster{..}\r\n | atFront && atBack = 0\r\n | atFront = blessing - snd (M.elemAt (M.findIndex position positionToBlessing + 1) positionToBlessing)\r\n | atBack = blessing + snd (M.elemAt (M.findIndex position positionToBlessing - 1) positionToBlessing)\r\n | otherwise = 2 * blessing\r\n where atFront = position == fst (M.findMin positionToBlessing)\r\n atBack = position == fst (M.findMax positionToBlessing)\r\n\r\npositionalBlessing :: Game -> Monster -> Int\r\npositionalBlessing Game{..} Monster{..}\r\n | atFront && atBack = 0\r\n | atFront || atBack = blessing\r\n | otherwise = 2 * blessing\r\n where atFront = position == fst (M.findMin positionToBlessing)\r\n atBack = position == fst (M.findMax positionToBlessing)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n numberMonsters <- read <$> getLine\r\n healths <- map read . words <$> getLine\r\n blessings <- map read . words <$> getLine\r\n print $ solve $\r\n Game\r\n { positionToBlessing = M.fromList $ [1..numberMonsters] `zip` blessings\r\n , monsters = sortOn blessing $ map (\\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings\r\n }\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- read <$> getLine\r\n replicateM_ testCases testCase\r\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sortOn)\r\nimport qualified Data.Set as S\r\n\r\ndata Game = Game\r\n { positions :: S.Set Int\r\n , monsters :: [Monster]\r\n }\r\n\r\ndata Monster = Monster\r\n { position :: Int\r\n , health :: Int\r\n , blessing :: Int\r\n }\r\n\r\nsolve :: Game -> Int\r\nsolve g@Game{..}\r\n | null monsters = 0\r\n | otherwise = health bestMonster + fst (positionalBlessing g bestMonster) +\r\n solve newGame\r\n where topMonsters = take 3 monsters\r\n (bestMonster:otherMonsters') = sortOn (positionalBlessing g) topMonsters\r\n otherMonsters = sortOn blessing otherMonsters'\r\n newGame = Game\r\n { positions = S.delete (position bestMonster) positions\r\n , monsters = otherMonsters ++ drop 3 monsters\r\n }\r\n\r\npositionalBlessing :: Game -> Monster -> (Int, Bool)\r\npositionalBlessing Game{..} Monster{..}\r\n | position == S.findMin positions && position == S.findMax positions = (0, False)\r\n | position == S.findMin positions || position == S.findMax positions = (blessing, False)\r\n | otherwise = (2 * blessing, True)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n numberMonsters <- read <$> getLine\r\n healths <- map read . words <$> getLine\r\n blessings <- map read . words <$> getLine\r\n print $ solve $\r\n Game\r\n { positions = S.fromList [1..numberMonsters]\r\n , monsters = sortOn blessing $ map (\\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings\r\n }\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- read <$> getLine\r\n replicateM_ testCases testCase\r\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sortOn)\r\nimport qualified Data.Set as S\r\n\r\ndata Game = Game\r\n { positions :: S.Set Int\r\n , monsters :: [Monster]\r\n }\r\n\r\ndata Monster = Monster\r\n { position :: Int\r\n , health :: Int\r\n , blessing :: Int\r\n }\r\n\r\nsolve :: Game -> Int\r\nsolve g@Game{..}\r\n | null monsters = 0\r\n | otherwise = health bestMonster + positionalBlessing g bestMonster +\r\n solve newGame\r\n where topMonsters = take 3 monsters\r\n (bestMonster:otherMonsters') = sortOn (positionalBlessing g) topMonsters\r\n otherMonsters = sortOn blessing otherMonsters'\r\n newGame = Game\r\n { positions = S.delete (position bestMonster) positions\r\n , monsters = otherMonsters ++ drop 3 monsters\r\n }\r\n\r\npositionalBlessing :: Game -> Monster -> Int\r\npositionalBlessing Game{..} Monster{..}\r\n | position == S.findMin positions && position == S.findMax positions = 0\r\n | position == S.findMin positions || position == S.findMax positions = blessing\r\n | otherwise = 2 * blessing\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n numberMonsters <- read <$> getLine\r\n healths <- map read . words <$> getLine\r\n blessings <- map read . words <$> getLine\r\n print $ solve $\r\n Game\r\n { positions = S.fromList [1..numberMonsters]\r\n , monsters = sortOn blessing $ map (\\(position, health, blessing) -> Monster{..}) $ zip3 [1..numberMonsters] healths blessings\r\n }\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- read <$> getLine\r\n replicateM_ testCases testCase\r\n"}], "src_uid": "5c75658faf6dda4d7e21e1dcf39b350a"} {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\nimport Data.List\n\nmain = do { n <- getLine\n ; x <- getLine\n ; putStrLn $ (words >>> map read >>> solve >>> map show >>> unwords) x \n }\n\ncmp :: (Int,Int) -> (Int,Int) -> Ordering\ncmp (x,_) (y,_) | x == y = EQ\n | x < y = LT\n | x > y = GT\n\nsolve :: [Int] -> [Int]\nsolve a = mapAccumL (\\a j -> (a+1, (j,a))) 1 >>> snd >>> sortBy cmp >>> map snd $ a", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact g\n\ng :: String -> String\ng = unwords . (map show) . (map fst) . (sortBy f) . (zip [1..]) . map (fromIntegral . read) . words . last . lines\n where\n f = (\\(_,a) (_,b) -> compare a b)\n\n\n"}, {"source_code": "import Data.List\nimport Data.Tuple\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int]\n let bs = map snd $ sort $ zip as [1..]\n putStrLn $ unwords $ map show bs\n"}, {"source_code": "import Data.List\nmain = interact $ unwords. map show. gao. map read. words\ngao (n:s) = map snd. sort . map swap. zip [1..n] $ s \nswap (a, b) = (b, a)\n"}, {"source_code": "\nimport Data.List\n\nmain = do\n n <- fmap read getLine :: IO Int\n nums <- fmap (map read . words) getLine :: IO [Int]\n let answer = map snd $ sort $ zip nums [(1::Int)..]\n putStrLn $ intercalate \" \" (map show answer)\n\n"}, {"source_code": "-- 136A\nimport Array\ngetT a = do\n\t\t\tc <- getChar\n\t\t\tif (c == ' ' || c == '\\n') then return $ read $ reverse a\n\t\t\t else getT (c:a)\n\ngetList 0 = return []\ngetList n = do {x <- getT [] :: IO Int; xs <- getList (n-1); return (x:xs)}\n\nprList [] = []\nprList (x:xs) = show x ++ \" \" ++ prList xs\n\nsolve n [] arr = arr\nsolve n (x:xs) arr = solve (n+1) xs (arr//[(x,n)])\n\nmain = do\n\t\t\tn <- readLn :: IO Int\n\t\t\ts <- getList n\n\t\t\tputStrLn $ prList $ elems $ solve 1 s (array (1,n) [(i,0) | i <- [1..n]])\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words . head . tail . lines\n\nsolve s = solve' s 1 (length s)\nsolve' s p n\n | p > n = []\n | otherwise = (calc s p 1):(solve' s (p+1) n)\n \ncalc (c:cs) p a\n | c == p = a\n | otherwise = calc cs p (a+1)\n \n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words . head . tail . lines\n\nsolve s = solve' s 1 (length s)\n\nsolve' s p n\n | p > n = []\n | otherwise = (calc s p 1):(solve' s (p+1) n)\n \ncalc (c:cs) p a\n | c == p = a\n | otherwise = calc cs p (a+1)\n \n"}, {"source_code": "import List\ngetAns ::[Int] -> [Int]\ngetAns a = map snd (sort$zip a [1..l])\n where l = length a\nmain=interact$unwords.(map show).getAns.(map read).tail.words"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve . concat.map (map read.words).take (2) . lines\nsolve :: [Int]->String\nsolve (x:xs) =unwords [show (z+1)|y <-[1..x],let z = fromJust $ elemIndex y xs]"}, {"source_code": "\nsolve :: [Int] -> [Int]\nsolve xs = map (find xs) [1..length xs]\n\nfind :: [Int] -> Int -> Int\nfind xs x = head (filter (\\n -> xs !! n == x) [0..length xs - 1]) + 1\n\nmain = do\n getLine\n line <- getLine\n let xs = map read (words line)\n mapM_ (\\x -> putStr (show x ++ \" \")) (solve xs)"}, {"source_code": "import Data.Array.Unboxed\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine\n xs <- map read . words <$> getLine\n let arr = array (1,n) [(x,i) | (x,i) <- zip xs [1..]] :: UArray Int Int\n putStrLn . unwords . map show $ elems arr\n"}, {"source_code": "import Data.Array\n\nsolve (n:xs) = elems $ foldr transmit initial $ zip xs [1 ..]\n where initial = array (1, n) [(i, 0) | i <- [1 .. n]]\n transmit (x, i) ans = ans // [(x, i)]\n\nmain = interact $ unwords.map show.solve.map read.words\n"}, {"source_code": "import List\nsolve :: [Int] -> [Int]\nsolve xs = map snd $ sortBy (\\x y -> compare (fst x) (fst y)) $ zip xs [1..]\nmain = interact $ unwords.map show.solve.map read.tail.words\n"}, {"source_code": "import Control.Monad\nimport Data.Sequence\n\nmain = getTwoLines >>= putStrLn . unwords . calc\n\ngetTwoLines :: IO (Int, Seq Int)\ngetTwoLines = liftM2 toTuple getLine getLine\n where toTuple a b = (read a, fromList $ map read $ words b)\n \ncalc :: (Int, Seq Int) -> [String]\ncalc (n, input) = resStr\n where res = foldr change input [0..n - 1]\n resStr = foldr (\\x xs -> show x:xs) [] res\n change i res = update newIndex newValue res\n where value = index input i\n newIndex = value - 1\n newValue = i + 1\n"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nsolve :: [Int] -> [Int]\nsolve a = elems $ array (1, length a) (zip a [1 ..]) \n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n a <- (map readInt . words) <$> getLine\n let answer = solve a\n forM_ answer (printf \"%d \")"}, {"source_code": "getInt :: IO Int\ngetInt = readLn\n\nreadNumbers :: String -> [Int]\nreadNumbers = map read . words\n\nresolveGifts a = [y | x <- [1 .. length(a)], y <- [1 .. length(a)], a !! (y - 1) == x]\n\nsolve a b = putStrLn $ foldr (\\x y -> (show x) ++ \" \" ++ y) \"\" (resolveGifts (readNumbers b))\nmain = getInt >>= (\\a -> getLine >>= solve a)"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\npass :: String -> String\npass [] = []\npass ('B':'G':t) = 'G' : 'B' : pass t\npass (h:t) = h : pass t\n\nsolve :: [Int] -> [Int]\nsolve a = [1 + fromJust (elemIndex x a) | x <- [1 .. length a]]\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n putStrLn . intercalate \" \" . map show $ solve a\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\npass :: String -> String\npass [] = []\npass ('B':'G':t) = 'G' : 'B' : pass t\npass (h:t) = h : pass t\n\nsolve :: [Int] -> [Int]\n-- solve a = [1 + fromJust (elemIndex x a) | x <- [1 .. length a]]\nsolve a = elems $ array (1, length a) (zip a [1..])\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n putStrLn . intercalate \" \" . map show $ solve a\n\n"}, {"source_code": "import Data.List\nimport Maybe\n\nmain = interact $ join . loc 1 . map read . words . head . tail . lines\nloc n ls = loc' n (length ls) ls\nloc' n 0 ls = []\nloc' n m ls = (fromJust (elemIndex n ls) + 1): (loc' (n+1) (m-1) ls)\njoin [] = \"\"\njoin (n:ns) = show n ++ \" \" ++ join ns"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\nmain=do\n getLine\n a<-(map read <$> words<$> getLine)::IO [Int]\n putStrLn $ intercalate \" \"$ map show $ map snd $ sort $ zip a [1..]\n"}, {"source_code": "import List\nmain=interact$unwords.map(show.snd).sort.(`zip`[1..]).drop 2.(0:).map read.words\n"}, {"source_code": "import Data.List (elemIndex)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . format . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> [Int]\nsolve [[n], ps] = [ 1 + fromJust (elemIndex i ps) | i <- [1..n] ]\n\nformat :: [Int] -> String\nformat = unwords . map show\n"}, {"source_code": "import Prelude hiding (readList, showList)\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nreadInt :: IO Int\nreadInt = head <$> readList' (undefined::Int)\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\nmain :: IO ()\nmain = do\n skipLine\n xs <- readList' (undefined::Int)\n showList $ map snd $ sort $ zip xs [1..]\n"}, {"source_code": "import Data.List\n\ngetInts :: IO [Int]\ngetInts = do\n xs <- getLine\n return $ map read $ words xs\n\ngetInt :: IO Int\ngetInt = do\n x <- getLine\n return $ read x\n\npos :: [Int] -> Int -> Int\npos xs x = head [a | (a,b) <- zip [1..] xs, b == x]\n\nsolve :: [Int] -> [Int]\nsolve xs = [a | a <- map (pos xs) [1..length xs]]\n\nmain :: IO ()\nmain = do\n n <- getInt\n xs <- getInts\n putStrLn $ unwords $ map show $ solve xs\n\n"}, {"source_code": "import Data.Array\nmain = do\n n <- readLn\n a <- fmap (array (1,n) . flip zip [1..] . map read . words) getLine\n putStrLn . unwords . map show $ elems a\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.words\n\nfunc::[String]->String\nfunc = solve.map toInt.tail\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nsolve::[Int]->String\nsolve = tail . concat . map ((\" \"++).toString.snd). sort . map reverseTuple . zip [1..]"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/136/A\n\nimport Data.List\nimport Data.Char\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> [Int]\nsolve a = elems $ array (1, length a) (zip a [1..])\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n putStrLn . intercalate \" \" . map show $ solve a\n"}, {"source_code": "import Data.List\nimport Data.Function\n\ntransform :: [Int] -> [Int]\ntransform = fmap fst . sortBy (compare `on` snd) . zip [1..]\n\ndispl :: [Int] -> String\ndispl = unwords . fmap show \n\nparseList :: String -> [Int]\nparseList = map read . tail . words\n\nsolve :: String -> String\nsolve = displ . transform . parseList\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "import Data.List\nsolve :: [Int] -> [(Int, Int)]\nsolve = sortOn snd . zip [1..]\np ((x,_):[]) = show x\np ((x,_):xs) = show x ++ \" \" ++ p xs\nmain = interact $ p . solve . map read . tail . words"}, {"source_code": "import Data.List\nsolve :: [Int] -> [(Int, Int)]\nsolve = sortOn snd . zip [1..]\np ((x,_):[]) = show x\np ((x,_):xs) = show x ++ \" \" ++ p xs\nmain = interact $ p . solve . map read . tail . words\n"}, {"source_code": "import Data.List\nmain = interact $ unwords.map show.map(\\(x,y) -> y+1).sort.(`zip` [0..]).map (read::String->Int).tail.words\n"}, {"source_code": "import Data.List\nmain = interact $ unwords.map (show.snd).sort.(`zip` [1..]).map ((+0).read).tail.words\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n--f :: Int -> (Int,Int)\n--f x = fromJust $ elemIndex x [0..]\nmain = interact $ unwords.map show.map(\\(x,y) -> y+1).sort.(`zip` [0..]).map (read::String->Int).tail.words\n"}, {"source_code": "import Data.List\nmain = interact$unwords.map(show.snd).sort.(`zip`[1..]).map((+0).read).tail.words\n"}, {"source_code": "import Data.List\nmain = interact $ unwords.map(\\(x,y) -> show $ y+1).sort.(`zip` [0..]).map ((+0).read).tail.words\n"}, {"source_code": "import Data.List\nmain=interact$unwords.map(show.snd).sort.(`zip`[1..]).map((+0).read).tail.words\n"}, {"source_code": "import Data.List(sort)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n xs <- map read <$> words <$> getLine\n putStrLn $ unwords $ map show $ solve n xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve _ xs = map snd $ sort $ zip xs [1..]\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let pairs = [(read $ m!!(k - 1) :: Int, k) | k <- [1..n], let m = words line]\n putStrLn $ concatMap ((++\" \") . show) [get x pairs | x <- [1..n]]\n\nget :: Int -> [(Int, Int)] -> Int\nget k (x:xs)\n | k == fst x = snd x\n | otherwise = get k xs"}, {"source_code": "import Data.List\n\n\nf :: [Int] -> [Int]\nf = snd . unzip . sortBy (\\(a, _) (b, _) -> compare a b) . flip zip [1..]\n\nmain = interact $ intercalate \" \" . map show . f . map read . tail . words\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Control.Monad.Trans.State\nimport Control.Monad\n--import System.Random\n--sortOn\ndivup x y= -div(-x)y\ndigs 0 _=[];digs x b=mod x b:digs(div x b)b--BASE!!\niInts=fmap(\\l->map read$words l)getLine::IO[Int]\nskln=(>>)getLine\nstail[]=[];stail a=tail a\neq3 a b c=a==b&&b==c\npop[_]=[];pop(x:s)=x:pop s;pop _=[]\nfoldli f o a=r o a 0 where r c(x:s)i=r(f x i c)s(i+1);r c[]_=c\ntrac=foldli(\\r i c->c+r!!i)0\n\nputArr :: [Int] -> IO ()\nputArr xs = putStrLn (concat (map (\\x -> show x ++ \" \") xs))\n\ninvertPermutation ns = map fst (sortOn snd (zip [1..length ns] ns))\n\nmain = skln $ iInts >>= (putArr . invertPermutation)\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Control.Monad.Trans.State\nimport Control.Monad\n--import System.Random\n--sortOn\ndivup x y= -div(-x)y\ndigs 0 _=[];digs x b=mod x b:digs(div x b)b--BASE!!\niInts=fmap(\\l->map read$words l)getLine::IO[Int]\nskln=(>>)getLine\nstail[]=[];stail a=tail a\neq3 a b c=a==b&&b==c\npop[_]=[];pop(x:s)=x:pop s;pop _=[]\nfoldli f o a=r o a 0 where r c(x:s)i=r(f x i c)s(i+1);r c[]_=c\ntrac=foldli(\\r i c->c+r!!i)0\n\nputArr :: [Int] -> (IO [()])\nputArr xs = sequence (map (\\x -> putStr (\" \" ++ show x ++ \" \")) xs)\n\ninvertPermutation ns = map fst (sortOn snd (zip [1..length ns] ns))\n\nmain = skln $ iInts >>= (putArr . invertPermutation)\n"}, {"source_code": "module Main where\natoi :: String->Int\natoi str = (read str :: Int)\n\ninsert :: [String] -> Int -> Int -> String -> [String]\ninsert list i tidx val = if(i < tidx) then (head list) : insert (tail list) (i+1) tidx val\n\t\t\t\t\t\t else val : (tail list)\n\t\t\t\t\nloop :: [String]->Int->[String]->[String]\t\t\t\t\nloop [] i oprList = oprList\nloop list i oprList = loop (tail list) (i+1) (insert oprList 1 (atoi(head list)) (show i))\n\nprintLoop [] = return()\nprintLoop lst = do\n\t\t\t\t\tputStr ((head lst) ++ \" \")\n\t\t\t\t\tprintLoop (tail lst)\nmain = do\n\t\tnstr <- getLine\n\t\t-- n = (atoi nstr)\n\t\tstr <- getLine\n\t\tlet res = (loop (words str) 1 (words str)) in\n\t\t\tprintLoop res\n\t\t\t\n\t\t\n\t\t"}, {"source_code": "\natoi :: String->Int\natoi str = (read str :: Int)\n\ninsert :: [String] -> Int -> Int -> String -> [String]\ninsert list i tidx val = if(i < tidx) then (head list) : insert (tail list) (i+1) tidx val\n else val : (tail list)\n \nloop :: [String]->Int->[String]->[String] \nloop [] i oprList = oprList\nloop list i oprList = loop (tail list) (i+1) (insert oprList 1 (atoi(head list)) (show i))\n\nprintLoop [] = return()\nprintLoop lst = do\n putStr ((head lst) ++ \" \")\n printLoop (tail lst)\nmain = do\n nstr <- getLine\n -- n = (atoi nstr)\n str <- getLine\n let res = (loop (words str) 1 (words str)) in\n printLoop res\n \n \n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport Data.Ord\n\nmain= do\n\t getLine\n\t s<- map read. words <$> getContents::IO [Int]\n\t let t= map snd $ sort $ zip s [1..]\n\t putStrLn $ intercalate \" \" $ map show t\n\n\t \n"}, {"source_code": "{-}\nA. Presents\n============\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nLittle Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.\n\nIf there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.\n\nNow Petya wants to know for each friend i the number of a friend who has given him a gift.\n\nInput\n------\nThe first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi \u2014 the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.\n\nOutput\n-------\nPrint n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.\n\nSample test(s)\n---------------\ninput\n4\n2 3 4 1\noutput\n4 1 2 3\ninput\n3\n1 3 2\noutput\n1 3 2\ninput\n2\n1 2\noutput\n1 2\n-}\n\nimport Data.List (sort)\n\ninversePermutation :: [Int] -> [Int]\ninversePermutation xs = map snd $ sort (zip xs ys)\n where ys = [1 .. length xs]\n\nmain = do\n input <- getContents\n let xs = map read $ (words . last) (lines input)\n putStrLn . unwords . map show $ inversePermutation xs\n\n"}, {"source_code": "import Data.List\nimport Data.Function\ntoInt = read :: String -> Int\nmain = interact $ unwords . map show . fst . unzip . sortBy (compare `on` snd) . zip [1..] . map toInt . words . (!! 1) . lines"}, {"source_code": "import Data.List\nmain = getLine >> getLine >>= putStrLn.unwords.map show.solve.map read.words\n\nsolve :: [Int] -> [Int]\nsolve x = map snd $ sortBy compare $ zip x [1..]\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List\n\nsortedIndices :: (Ord a) => [a] -> [Int]\nsortedIndices a = map snd $ sort (zip a [1..])\n\nmain = do\n nStr <- getLine\n pStr <- getLine\n let p = map read . words $ pStr :: [Int]\n putStrLn . unwords . map show $ sortedIndices p"}, {"source_code": "import Data.Array\nimport Data.List\nimport Control.Monad\n\nsol :: [Int] -> [Int]\nsol xx =\n let a = listArray (1, length xx) xx :: Array Int Int\n in aux xx a 1 []\n\naux :: [Int] -> Array Int Int -> Int -> [(Int, Int)] -> [Int]\naux [] a i updates = elems $ a // updates\naux (x:xs) a i updates = aux xs a (i+1) ((x, i):updates)\n\nmain = do\n i <- getLine\n let t = read i :: Int\n input_raw <- getLine\n let input = map (\\n -> read n :: Int) $ words input_raw\n let ret = sol input\n putStrLn (intercalate \" \" (map show ret))\n"}, {"source_code": "import Data.List\n\nintFromMaybe m = case m of Just i -> i\n Nothing -> 0\n \n\nprocess :: Int -> [Int] -> [Int]\nprocess count dataList = \n map ((+1) . intFromMaybe) $ map (\\x -> elemIndex x dataList) [1..count] \n\nmain :: IO ()\nmain = do\n source <- getLine\n let count = read source :: Int\n sources <- getLine\n let numbers = read <$> words sources :: [Int]\n let result = process count numbers\n putStrLn (intercalate \" \" $ map show result)"}, {"source_code": "import Data.List\nmain = interact $ unwords . map (show . snd) . sort . (`zip` [1..]) . drop 2 . (0:) . map read . words"}, {"source_code": "import Data.List\nmain = do\n n_s <- getLine\n i_s <- getLine\n let fs = (zip (map read $ words i_s) [1..])::[(Int,Int)]\n putStrLn $ unwords (map show $ func fs)\nfunc m = map snd $ sort m"}, {"source_code": "import Data.List\nf::[Int] -> [Int]\nf xs = let n = length xs\n in map fst.sortBy (\\x y-> (snd x)`compare`(snd y)).zip [1..n] $ xs \nmain = interact $ intercalate \" \".map show.f.map read.tail.words\n"}, {"source_code": "import Data.Function\nimport Data.List\n\nread_pair :: IO [Int]\nread_pair = fmap (map read.words) getLine\n\nmain :: IO ()\nmain = do\n _ <- getLine\n cost <- read_pair\n let rev = zip cost [1..(length cost)]\n let res = sortBy (compare `on` fst) rev\n let to_p = [x | (_, x) <- res]\n putStrLn (intercalate \" \" (map show to_p))\n"}, {"source_code": "import Control.Monad\n\n\nmain = do\n n <- readLn :: IO Int\n aa <- getLine\n let xs = map read $ words aa :: [Int]\n let ys = [1..n]\n let xy = zip xs ys\n\n let ans = map (\\y -> snd $ head $ filter (\\(x,_) -> x==y) xy ) ys\n\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nmain :: IO ()\nmain = putStrLn . unwords . map show . solve . readInts =<< (getLine >> getLine)\n where solve = map fst . sortBy (comparing snd) . zip [1..]"}, {"source_code": "main = do\n\tn<-getLine\n\ts<-getLine\n\tputStrLn $ hepler $map read (words s)\n\nhepler s =init $concat $map (++\" \") $map (solve s) [1..length s]\n\nsolve s pos=show ( head [x+1 | x<-[0..length s-1], pos==s!!x])"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = do\n n <- fmap read getLine\n p <- fmap (map read . words) getLine :: IO [Int]\n putStrLn . unwords . map show $ map ((+1) . fromJust . flip elemIndex p) [1..n]\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.Array.IArray\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n a <- readItems\n let b = array (1, n) (zip a [1 ..])\n putStrLn $ unwords $ map show $ elems (b :: Array Int Int)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Tuple\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int]\n let bs = map snd $ sort $ map swap $ zip as [1..]\n putStrLn $ unwords $ map show bs\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve . concat.map (map read.words).take (2) . lines\nsolve :: [Int]->[Int]\nsolve (x:xs) =[z+1|y <-[1..x],let z = fromJust $ elemIndex y xs]"}, {"source_code": "\nsolve :: [Int] -> [Int]\nsolve xs = map (find xs) [1..length xs]\n\nfind :: [Int] -> Int -> Int\nfind xs x = head (filter (\\n -> xs !! n == x) [0..length xs - 1]) + 1\n\nmain = do\n getLine\n line <- getLine\n let xs = map read (words line)\n print (solve xs)"}, {"source_code": "\nsolve :: [Int] -> [Int]\nsolve xs = map (find xs) [1..length xs]\n\nfind :: [Int] -> Int -> Int\nfind xs x = head (filter (\\n -> xs !! n == x) [0..length xs - 1]) + 1\n\nmain = do\n print 1"}, {"source_code": "getInt :: IO Int\ngetInt = readLn\n\nreadNumbers :: String -> [Int]\nreadNumbers = map read . words\n\nresolveGifts a = foldr (\\x y -> y ++ (show x) ++ \" \") \"\" [(y + 1) | x <- [0 .. length(a) -1], y <- [0 .. length(a) - 1], a !! y == (x + 1)]\n\nsolve a b = putStrLn $ resolveGifts (readNumbers b)\nmain = getInt >>= (\\a -> getLine >>= solve a)"}, {"source_code": "import List\nmain=interact$unwords.map(show.snd).sort.(`zip`[1..]).tail.words\n"}, {"source_code": "import Data.List\nsolve :: [Int] -> [(Int, Int)]\nsolve = sortOn snd . zip [1..]\nmain = interact $ unwords . map (show . snd) . solve . map read . tail . words"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let pairs = [(read $ m!!(k - 1) :: Int, k) | k <- [1..n], let m = words line]\n putStrLn $ intersperse ' ' $ concatMap show [get x pairs | x <- [1..n]]\n\nget :: Int -> [(Int, Int)] -> Int\nget k (x:xs)\n | k == fst x = snd x\n | otherwise = get k xs"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Control.Monad.Trans.State\nimport Control.Monad\n--import System.Random\n--sortOn\ndivup x y= -div(-x)y\ndigs 0 _=[];digs x b=mod x b:digs(div x b)b--BASE!!\niInts=fmap(\\l->map read$words l)getLine::IO[Int]\nskln=(>>)getLine\nstail[]=[];stail a=tail a\neq3 a b c=a==b&&b==c\npop[_]=[];pop(x:s)=x:pop s;pop _=[]\nfoldli f o a=r o a 0 where r c(x:s)i=r(f x i c)s(i+1);r c[]_=c\ntrac=foldli(\\r i c->c+r!!i)0\n\ninvertPermutation ns = map fst (sortOn snd (zip [1..length ns] ns))\n\nmain = skln $ iInts >>= (print . invertPermutation)\n"}, {"source_code": "{-}\nA. Presents\n============\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nLittle Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.\n\nIf there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.\n\nNow Petya wants to know for each friend i the number of a friend who has given him a gift.\n\nInput\n------\nThe first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi \u2014 the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.\n\nOutput\n-------\nPrint n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.\n\nSample test(s)\n---------------\ninput\n4\n2 3 4 1\noutput\n4 1 2 3\ninput\n3\n1 3 2\noutput\n1 3 2\ninput\n2\n1 2\noutput\n1 2\n-}\n\nimport Data.List (sort)\n\ninversePermutation :: Ord a => [a] -> [a]\ninversePermutation xs = map snd $ sort (zip ys xs)\n where ys = [1 .. length xs]\n\nmain = do\n input <- getContents\n let xs = words . last $ lines input\n putStrLn . unwords $ inversePermutation xs\n\n"}, {"source_code": "import Data.List\nimport Data.Function\ntoInt = read :: String -> Int\nmain = interact $ unwords . map show . snd . unzip . sortBy (compare `on` snd) . zip [1..] . map toInt . words . (!! 1) . lines"}], "src_uid": "48bb148e2c4d003cad9d57e7b1ab78fb"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess [a,b,c,d] = do\n\t\t\tputStrLn $ intercalate \" \" $ map show $ if a==c then [a,d] else [a,c] \n\t\t\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\ta<-map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n\t\tmapM_ process a\n\n", "positive_code": [{"source_code": "import Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [l1,r1,l2,r2] <- map read . words <$> getLine :: IO [Int]\n let (a,b) = head [ (a,b) | a <- [l1..r1], b <- [l2..r2], a /= b ]\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "main :: IO ()\nmain = do\n queries <- readLn :: IO Int\n do_queries queries\n\ndo_queries :: Int -> IO ()\ndo_queries 0 = return ()\ndo_queries n = do\n l <- getLine\n let numbers = map (read :: String -> Int) (words l)\n let (a,b) = solve numbers\n putStrLn $ (show a) ++ \" \" ++ (show b)\n do_queries $ n-1\n\nsolve :: [Int] -> (Int,Int)\nsolve (l1:r1:l2:r2:[]) = head [(i,j) | i <- [l1..r1], j <- [l2..r2], i /= j]\n"}, {"source_code": "process :: (Int, Int, Int, Int) -> (Int, Int)\nprocess (l1,r1,l2,r2)\n | l1 /= l2 = (l1,l2)\n | otherwise = (r1,l2)\n\nreadInt :: String -> Int\nreadInt = read\n\nprintPair :: (Int, Int) -> IO ()\nprintPair (x,y) = putStrLn $ show x ++ \" \" ++ show y\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ printPair $ map (\\[l1,r1,l2,r2] -> process (l1,r1,l2,r2)) ts"}, {"source_code": "main = interact $ unlines . map (solve . map read . words) . tail . lines\n\nsolve (a:_:b:_)\n | a == b = show a ++ (' ' : show (b + 1))\n | otherwise = show a ++ (' ' : show b)\n"}], "negative_code": [], "src_uid": "cdafe800094113515e1de1acb60c4bb5"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\nresult [] = []\r\nresult [x] = [0]\r\nresult array = (fmap (+1) $ result aLeft) ++ [0] ++ (fmap (+1) $ result aRight) where\r\n\taRight = reverse $ takeWhile (>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tputStrLn $ showR $ result $ fmap (\\x->x-1) a\r\n\t\tloop $ t - 1\r\n\tloop t", "positive_code": [{"source_code": "import Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe ( fromJust )\nimport Data.List ( splitAt )\n\nmain :: IO ()\nmain = B.interact $ B.unlines . map B.unwords . solve . tail . B.words\n\nsolve :: [ByteString] -> [[ByteString]]\nsolve [] = []\nsolve (n:rest) = construct (take n_int rest) 0:solve (drop n_int rest)\n where n_int = bstToInt n\n\nbstToInt :: ByteString -> Int\nbstToInt = fst . fromJust . B.readInt\n\nconstruct :: [ByteString] -> Int -> [ByteString]\nconstruct [] _ = []\nconstruct arr depth = construct left (depth+1)++(B.pack . show $ depth):construct right (depth+1)\n where (left, _:right) = splitAt (snd . maximum $ zip (map bstToInt arr) [0..]) arr"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe ( fromJust )\nimport Data.List ( splitAt )\n\nmain :: IO ()\nmain = B.interact $ B.unlines . map B.unwords . solve . tail . B.words\n\nsolve :: [B.ByteString] -> [[B.ByteString]]\nsolve [] = []\nsolve (n:rest) = (construct (take n_int rest) 0):solve (drop n_int rest)\n where n_int = bstToInt n\n\nbstToInt :: B.ByteString -> Int\nbstToInt = fst . fromJust . B.readInt\n\nconstruct :: [B.ByteString] -> Int -> [B.ByteString]\nconstruct [] _ = []\nconstruct arr depth = (construct left (depth+1))++(B.pack . show $ depth):(construct right (depth+1))\n where (left, _:right) = splitAt (snd . maximum $ zip (map bstToInt arr) [0..]) arr"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe ( fromJust )\nimport Data.List ( splitAt )\n\nmain :: IO ()\nmain = B.interact $ B.unlines . map B.unwords . solve . tail . B.words\n\nsolve :: [B.ByteString] -> [[B.ByteString]]\nsolve [] = []\nsolve (n:rest) = (construct (take n_int rest) 0):solve (drop n_int rest)\n where n_int = bstToInt n\n\nbstToInt :: B.ByteString -> Int\nbstToInt = fst . fromJust . B.readInt\n\nconstruct :: [B.ByteString] -> Int -> [B.ByteString]\nconstruct [] _ = []\nconstruct arr depth = (construct left (depth+1))++(B.pack . show $ depth):(construct right (depth+1))\n where (left, _:right) = splitAt (snd . maximum $ zip (map bstToInt arr) [0..]) arr"}, {"source_code": "import qualified Data.Array as A\n\ntype Arr = A.Array Int Int\n\nrecurse :: [Int] -> Int -> Int -> Arr -> Arr\nrecurse nodes depth offset depths\n | null nodes = depths\n | length nodes == 1 = depths A.// [(offset, depth)]\n | otherwise =\n let maxPair = maximum $ zip nodes [0..]\n maxIndex = snd maxPair\n lChunk = take maxIndex nodes\n rChunk = drop (maxIndex + 1) nodes\n newDepths1 = recurse lChunk (depth + 1) offset depths\n newDepths2 = recurse rChunk (depth + 1) (offset + maxIndex + 1) newDepths1\n newDepth = newDepths2 A.// [(offset + maxIndex, depth)]\n in newDepth\n\nsolveTest :: [Int] -> [Int]\nsolveTest perm = A.elems $ recurse perm 0 0 depths\n where depths = A.listArray (0, n - 1) [0 | _ <- [1..n]]\n n = length perm\n\nshowResult :: [Int] -> String\nshowResult = foldl (\\s x -> s ++ show x ++ \" \") \"\"\n\nsolve :: String -> String\nsolve = unlines . map solveStringTest . odds . drop 1 . lines\n where odds = map snd . filter (odd . fst) . zip [0..]\n solveStringTest = showResult . solveTest . map read . words\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\ngo :: Int -> [Int] -> [Int]\ngo d [] = []\ngo d [x] = [d]\ngo d xs = go (d+1) ys ++ [d] ++ go (d+1) zs\n where mx = maximum xs\n Just mxidx = elemIndex mx xs\n (yys, zs) = splitAt (mxidx+1) xs\n ys = init yys\n\n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n xs <- readInts :: IO [Int]\n let res = intercalate \" \" $ map show $ go 0 xs\n in putStrLn res\n \n \n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadrows 0 = return []\nreadrows n = do\n row <- readInts\n l <- readrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n ds <- popInts\n return $ B.unwords $ map bshow $ solve n ds\n\n\nsolve n ds = map snd $ sort $ go [(0, 0, n)]\n where\n segt = segTree max $ zip ds [0..]\n\n go [] = []\n go ((d, l, r) : qs)\n | l == r = go qs\n | otherwise = let (_, i) = segGet segt l r in\n (i, d) : go ((d + 1, l, i) : (d + 1, i + 1, r) : qs)\n\n\ndata SegTree a = SegTree (a -> a -> a) [Array Int a]\n\n\nsegTree :: (a -> a -> a) -> [a] -> SegTree a\nsegTree f as = SegTree f $ make (length as) as\n where\n make 1 as = [listArray (0, 0) as]\n make n as = listArray (0, n - 1) as : half n as\n\n half n as | even n = make (n `quot` 2) $ go (n `quot` 2) as\n | otherwise = make (n `quot` 2 + 1) $ go (n `quot` 2) as\n\n go 0 as = as\n go n (a : b : as) = f a b : go (n - 1) as\n\n\nsegGet :: SegTree a -> Int -> Int -> a\nsegGet (SegTree f segs) l r = foldl1' f $ go segs l r\n where\n go (seg : segs) l r\n | r - l <= 0 = []\n | r - l == 1 = [seg ! l]\n | otherwise =\n let (l', la) | even l = (l, [])\n | otherwise = (l + 1, [seg ! l])\n (r', ra) | even r = (r, [])\n | otherwise = (r - 1, [seg ! (r - 1)]) in\n la ++ ra ++ go segs (l' `quot` 2) (r' `quot` 2)\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.IArray\n\nstep :: [Int] -> Int -> [Int]\nstep li x = x : dropWhile (<= x) li\n\nsolve :: Int -> [Int] -> [Int]\nsolve n li = let\n lpotpars = map tail $ tail $ scanl step [] li\n rpotpars = map tail $ scanr (flip step) [] li\n depths :: Array Int Int\n depths = array (1, n) $ do\n (v, potL, potR) <- zip3 li lpotpars rpotpars\n pure $ (,) v $ case potL ++ potR of\n [] -> 0\n w -> 1 + depths ! minimum w\n in map (depths !) li\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n a <- readInts\n putInts $ solve n a\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-name-shadowing #-}\n{-# OPTIONS_GHC -Wno-type-defaults #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport GHC.Types\n\nreadNumbers :: (Integral b, Read b) => IO [b]\nreadNumbers = fmap read . words <$> getLine\n\n{-# WARNING todo \"'todo' remains in code\" #-}\n{-# INLINEABLE todo #-}\ntodo :: a\ntodo = error \"Not implemented\"\n\n(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b\nx !& f = let !vx = x in f vx\n\ninfixl 1 !&\n\ndata Tree a = Branch (Tree a) a (Tree a) | Leaf\n\nmain :: IO [()]\nmain = do\n [t] <- readNumbers\n\n replicateM t $ do\n [n] <- readNumbers\n as <- readNumbers\n let sortedAs = sort as\n createTree [] = Leaf\n createTree as =\n let max = maximum as\n i = fromJust $ elemIndex max as\n in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)\n collectTree _ Leaf = []\n collectTree n (Branch left _ right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right\n\n putStrLn . unwords . fmap show . collectTree 0 $ createTree as\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-name-shadowing #-}\n{-# OPTIONS_GHC -Wno-type-defaults #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport GHC.Types\n\nreadNumbers :: (Integral b, Read b) => IO [b]\nreadNumbers = fmap read . words <$> getLine\n\n{-# WARNING todo \"'todo' remains in code\" #-}\n{-# INLINEABLE todo #-}\ntodo :: a\ntodo = error \"Not implemented\"\n\n(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b\nx !& f = let !vx = x in f vx\n\ninfixl 1 !&\n\ndata Tree a = Branch (Tree a) a (Tree a) | Leaf\n\nmain :: IO [()]\nmain = do\n [t] <- readNumbers\n\n replicateM t $ do\n [n] <- readNumbers\n as <- readNumbers\n let sortedAs = sort as\n createTree [] = Leaf\n createTree as =\n let max = maximum as\n i = fromJust $ elemIndex max as\n in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)\n collectTree _ Leaf = []\n collectTree n (Branch left _ right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right\n\n print . unwords . fmap show . collectTree 0 $ createTree as\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-name-shadowing #-}\n{-# OPTIONS_GHC -Wno-type-defaults #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport GHC.Types\n\nreadNumbers :: (Integral b, Read b) => IO [b]\nreadNumbers = fmap read . words <$> getLine\n\n{-# WARNING todo \"'todo' remains in code\" #-}\n{-# INLINEABLE todo #-}\ntodo :: a\ntodo = error \"Not implemented\"\n\n(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b\nx !& f = let !vx = x in f vx\n\ninfixl 1 !&\n\ndata Tree a = Branch (Tree a) a (Tree a) | Leaf\n\nmain :: IO [()]\nmain = do\n [t] <- readNumbers\n\n replicateM t $ do\n [n] <- readNumbers\n as <- readNumbers\n let sortedAs = sort as\n createTree [] = Leaf\n createTree as =\n let max = maximum as\n i = fromJust $ elemIndex max as\n in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)\n collectTree n Leaf = []\n collectTree n (Branch left _ right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right\n\n print $ collectTree 0 $ createTree as\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-name-shadowing #-}\n{-# OPTIONS_GHC -Wno-type-defaults #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport GHC.Types\n\nreadNumbers :: (Integral b, Read b) => IO [b]\nreadNumbers = fmap read . words <$> getLine\n\n{-# WARNING todo \"'todo' remains in code\" #-}\n{-# INLINEABLE todo #-}\ntodo :: a\ntodo = error \"Not implemented\"\n\n(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b\nx !& f = let !vx = x in f vx\n\ninfixl 1 !&\n\ndata Tree a = Branch (Tree a) a (Tree a) | Leaf\n\nmain :: IO [()]\nmain = do\n [t] <- readNumbers\n\n replicateM t $ do\n [n] <- readNumbers\n as <- readNumbers\n let sortedAs = sort as\n createTree [] = Leaf\n createTree as =\n let max = maximum as\n i = fromJust $ elemIndex max as\n in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)\n collectTree n Leaf = [n]\n collectTree n (Branch left node right) = collectTree (n + 1) left <> [n] <> collectTree (n + 1) right\n\n print $ collectTree 0 $ createTree as\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-name-shadowing #-}\n{-# OPTIONS_GHC -Wno-type-defaults #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport GHC.Types\n\nreadNumbers :: (Integral b, Read b) => IO [b]\nreadNumbers = fmap read . words <$> getLine\n\n{-# WARNING todo \"'todo' remains in code\" #-}\n{-# INLINEABLE todo #-}\ntodo :: a\ntodo = error \"Not implemented\"\n\n(!&) :: forall r a (b :: TYPE r). a -> (a -> b) -> b\nx !& f = let !vx = x in f vx\n\ninfixl 1 !&\n\ndata Tree a = Branch (Tree a) a (Tree a) | Leaf\n\nmain :: IO [()]\nmain = do\n [t] <- readNumbers\n\n replicateM t $ do\n [n] <- readNumbers\n as <- readNumbers\n let sortedAs = sort as\n createTree [] = Leaf\n createTree as =\n let max = maximum as\n i = fromJust $ elemIndex max as\n in Branch (createTree $ take i as) max (createTree $ drop (i + 1) as)\n collectTree Leaf = []\n collectTree (Branch left node right) = collectTree left <> [node] <> collectTree right\n\n print $ collectTree $ createTree as\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe ( fromJust )\nimport Data.List ( splitAt )\n\nmain :: IO ()\nmain = B.interact $ B.unlines . map B.unwords . solve . tail . B.words\n\nsolve :: [B.ByteString] -> [[B.ByteString]]\nsolve [] = []\nsolve (n:rest) = (construct (take n_int rest) 0):solve (drop n_int rest)\n where n_int = bstToInt n\n\nbstToInt :: B.ByteString -> Int\nbstToInt = fst . fromJust . B.readInt\n\nconstruct :: [B.ByteString] -> Int -> [B.ByteString]\nconstruct [] _ = []\nconstruct arr depth = (construct left (depth+1))++(B.pack . show $ depth):(construct right (depth+1))\n where (left, _:right) = splitAt (snd . maximum $ zip arr [0..]) arr"}], "src_uid": "a564017f9c411b39f8d4b69e629ae3bc"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.IORef\n\n#if __GLASGOW_HASKELL__ < 706\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n#endif\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,q] <- map read.words <$> getLine\n (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents\n segtree <- mkSegTree 0 (n-1) (listArray (0,n-1) $ repeat 0)\n let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest\n go _ _ = return ()\n go segtree lrs\n cnts <- fromSegTree 0 (n-1) segtree\n print $ solve as cnts\n\nsolve :: [Int] -> [Int] -> Integer\nsolve as cnts = go 0 (sortBy (flip compare) as) (sortBy (flip compare) cnts)\n where\n go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys\n go acc _ _ = acc\n \ndata SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree\n | Leaf !Int !(IORef Int)\n\nfromSegTree :: Int -> Int -> SegTree -> IO [Int]\nfromSegTree l r segtree = mapM (\\i -> query i i segtree) [l..r]\n\nmkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree\nmkSegTree l r arr\n | l get lt <*> get rt\n aref <- newIORef 0\n bref <- newIORef $! xy\n return $! Node l r aref bref lt rt\n | otherwise = do\n ref <- newIORef $! unsafeAt arr l\n return $! Leaf l ref\n\nupdate :: Int -> Int -> Int -> SegTree -> IO ()\nupdate kl kr x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n\nquery :: Int -> Int -> SegTree -> IO Int\nquery kl kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Array\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n (n:_:t) <- map (fst . fromJust . C.readInt) <$> C.words <$> C.getContents\n let (a, q) = splitAt n t\n (l, r) = unzip $ pairs q\n x = accumArray (+) 0 (0, n) $\n zip (map pred l) (repeat 1) ++ zip r (repeat $ -1)\n y = scanl1 (+) $ init $ elems x\n f = map fromIntegral . sort\n z = sum $ zipWith (*) (f a) (f y)\n print $ (z :: Int64)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.IORef\n\n#if __GLASGOW_HASKELL__ < 706\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n#endif\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,q] <- map read.words <$> getLine\n (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents\n segtree <- mkSegTree 0 (n-1) (listArray (0,n-1) $ repeat 0)\n let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest\n go _ _ = return ()\n go segtree lrs\n xs <- fromSegTree 0 (n-1) segtree\n print $ sum $ zipWith ((*)`on`toInteger) (sortBy (flip compare) xs) (sortBy (flip compare) as)\n \ndata SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree\n | Leaf !Int !(IORef Int)\n\nfromSegTree :: Int -> Int -> SegTree -> IO [Int]\nfromSegTree l r segtree = go id [l..r]\n where\n go ans (x:xs) = do\n !qxx <- query x x segtree\n go (ans.(qxx:)) xs\n go ans _ = return $ ans []\n\nmkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree\nmkSegTree l r arr\n | l get lt <*> get rt\n aref <- newIORef 0\n bref <- newIORef $! xy\n return $! Node l r aref bref lt rt\n | otherwise = do\n ref <- newIORef $! unsafeAt arr l\n return $! Leaf l ref\n\nupdate :: Int -> Int -> Int -> SegTree -> IO ()\nupdate kl kr x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n\nquery :: Int -> Int -> SegTree -> IO Int\nquery kl kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,q] <- map read.words <$> getLine\n (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents\n print $ solve as $ imos n lrs\n\nsolve :: [Int] -> [Integer] -> Integer\nsolve as cnts = go 0 (sort as) (sort cnts)\n where\n go !acc (x:xs) (y:ys) = go (toInteger x * y + acc) xs ys\n go acc _ _ = acc\n\nimos :: Int -> [Int] -> [Integer]\nimos n lrs = scanl1 (+) $ map (toInteger.unsafeAt cnt) [0..n-1]\n where\n cnt :: UArray Int Int\n !cnt = unsafeAccumArray (+) 0 (0,n) $ go lrs\n go (l:r:lrs) = (l-1,1):(r,-1):go lrs\n go _ = []"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.IORef\n\n#if __GLASGOW_HASKELL__ < 706\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n#endif\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,q] <- map read.words <$> getLine\n (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents\n segtree <- mkSegTree 0 (n-1) 0\n let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest\n go _ _ = return ()\n go segtree lrs\n cnts <- fromSegTree 0 (n-1) segtree\n print $ solve as cnts\n\nsolve :: [Int] -> [Int] -> Integer\nsolve as cnts = go 0 (radixSortRev as) (radixSortRev cnts)\n where\n go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys\n go acc _ _ = acc\n \ndata SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree\n | Leaf !Int !(IORef Int)\n\nfromSegTree :: Int -> Int -> SegTree -> IO [Int]\nfromSegTree kl kr segtree = mapM f [kl..kr]\n where\n f key = go 0 segtree\n where\n go !acc (Node l r aref _ lt rt) = do\n if 2*key <= l+r\n then do\n a <- readIORef aref\n go (acc+a) lt\n else do\n a <- readIORef aref\n go (acc+a) rt\n go !acc (Leaf _ ref) = do\n r <- readIORef ref\n return $! acc+r\n\nmkSegTree :: Int -> Int -> Int -> IO SegTree\nmkSegTree !kl !kr !x0 = go kl kr\n where\n go !l !r\n | l Int -> Int -> SegTree -> IO ()\nupdate !kl !kr !x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n\n\nradixSortRev :: [Int] -> [Int]\nradixSortRev xs = runST $ do\n \n let !mask = 0xffff\n !n = length xs\n \n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n \n forM_ (map (mask.&.) xs) $ \\mx -> do\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+) \n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n !j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n forM_ [0..mask] $ \\i-> do\n unsafeWrite count i 0\n\n forM_ (map ((mask.&.).(`unsafeShiftR`16)) xs) $ \\mx -> do\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`unsafeShiftR`16).&.mask\n !j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n\n forM [n-1,n-2..0] $ \\i-> do\n unsafeRead arr i\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.IORef\n\n#if __GLASGOW_HASKELL__ < 706\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n#endif\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,q] <- map read.words <$> getLine\n (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents\n segtree <- mkSegTree 0 (n-1) (listArray (0,n-1) $ repeat 0)\n let go st (l:r:rest) = update (l-1) (r-1) 1 st >> go st rest\n go _ _ = return ()\n go segtree lrs\n cnts <- fromSegTree 0 (n-1) segtree\n print $ solve as cnts\n\nsolve :: [Int] -> [Int] -> Integer\nsolve as cnts = go 0 (reverse $ radixSort as) (reverse $ radixSort cnts)\n where\n go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys\n go acc _ _ = acc\n \ndata SegTree = Node !Int !Int !(IORef Int) !(IORef Int) !SegTree !SegTree\n | Leaf !Int !(IORef Int)\n\nfromSegTree :: Int -> Int -> SegTree -> IO [Int]\nfromSegTree l r segtree = mapM (\\i -> query i i segtree) [l..r]\n\nmkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree\nmkSegTree l r arr\n | l get lt <*> get rt\n aref <- newIORef 0\n bref <- newIORef $! xy\n return $! Node l r aref bref lt rt\n | otherwise = do\n ref <- newIORef $! unsafeAt arr l\n return $! Leaf l ref\n\nupdate :: Int -> Int -> Int -> SegTree -> IO ()\nupdate kl kr x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n\nquery :: Int -> Int -> SegTree -> IO Int\nquery kl kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0\n\nradixSort :: [Int] -> [Int]\nradixSort xs = elems $ runSTUArray $ do\n \n let !mask = 0xffff\n !n = length xs\n \n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n \n forM_ xs $ \\x-> do\n let !mx = x.&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n forM_ [0..mask] $ \\i-> do\n unsafeWrite count i 0\n\n forM_ xs $ \\x-> do\n let !mx = (x`shiftR`16).&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`shiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n \n return arr\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,_] <- map read.words <$> getLine\n (as,lrs) <- splitAt n.map readInt.B.words <$> B.getContents\n print $ solve as $ imos n lrs\n\nsolve :: [Int] -> [Int] -> Integer\nsolve as cnts = go 0 (radixSort as) (radixSort cnts)\n where\n go !acc (x:xs) (y:ys) = go (toInteger x * toInteger y + acc) xs ys\n go acc _ _ = acc\n\nimos :: Int -> [Int] -> [Int]\nimos n lrs = scanl1 (+) $ map (unsafeAt cnt) [0..n-1]\n where\n !cnt = unsafeAccumArray (+) 0 (0,n) $ go lrs :: UArray Int Int\n go (l:r:lrs) = (l-1,1):(r,-1):go lrs\n go _ = []\n\nradixSort :: [Int] -> [Int]\nradixSort xs = runST $ do\n \n let !mask = 0xffff\n !n = length xs\n \n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n \n forM_ xs $ \\x-> do\n let !mx = x.&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n forM_ [0..mask] $ \\i-> do\n unsafeWrite count i 0\n\n forM_ xs $ \\x-> do\n let !mx = (x`shiftR`16).&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`shiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n \n getElems arr\n"}], "negative_code": [], "src_uid": "926ec28d1c80e7cbe0bb6d209e664f48"} {"source_code": "import Data.List\nmain = do\n [n, k] <- (map read . words) `fmap` getLine :: IO [Int]\n l <- (map read . words) `fmap` getLine :: IO [Int]\n let f l = concat $ map (\\l'@(s:ss) -> reverse $ if s < k then (s+1):ss else l') $ group l\n f1 i l | all (==k) l = i\n | otherwise = f1 (i+1) $ f l\n print $ f1 0 l\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, k] <- ( map read . words ) `liftM` getLine\n as <- ( map read . words ) `liftM` getLine\n\n let (_, count) = until ( (==k) . head . fst ) (\\(as, count) ->\n let (as', _) = foldr (\\a (res, last) ->\n ( ( if a == last then a else a+1 ) : res, a )\n ) ([], k) as\n in (as', count+1)\n ) (as, 0)\n\n putStrLn $ show count\n"}, {"source_code": "main = do\n\t[n,k] <- getLine >>= return . map read . words :: IO [Int]\n\tlst <- getLine >>= return . map read . words :: IO [Int]\n\tlet low x = length $ filter ((>=) x) lst\n\t(putStrLn . show . foldl max 0) [ (k - i) + (low i - 1) | i <- [1..k-1], low i > 0 ]\n"}, {"source_code": "import List\n\nnext :: Int -> [Int] -> [Int]\nnext _ [] = []\nnext m [a] = if a < m then [a+1] else [a]\nnext m (a:b:as) = if a < b then (a+1):(next m (b:as)) else a:(next m (b:as))\n\nsolve :: Int -> [Int] -> Int\nsolve m as = length (takeWhile (\\x -> head x < m) (iterate (next m) as))\n\nmain = do\n line <- getLine\n let [n, m] = map read (words line)\n line <- getLine\n let as = map read (words line)\n print (solve m as)"}, {"source_code": "import List\n\nnotOver k xs = any ( (x + 1):xs).group.sort\nsolve (k:xs) = length $ takeWhile (notOver k) $ iterate levelUp xs\n\nmain = interact $ show.solve.tail.map read.words"}, {"source_code": "import Prelude\nimport List\nimport Char\nimport Data.Ord\nimport Data.List\n\nmain = interact q\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc x = toString $ solve a b\n where\n a = toInt (x!!0!!1)\n b = map toInt (x!!1)\n\ntoInt::String->Int\ntoInt = read\ntoString::Int->String\ntoString=show\n\nsolve::Int->[Int]->Int\nsolve k x = if le == 0 then 0 else (+1) $ solve k x4\n where\n x' = filter ((< k).head) $ group x\n le = length x'\n x1 = concat $ filter ((>= k).head) $ group x \n x2 = concat $ map tail x'\n x3 = map ((+1).head) x'\n x4 = sort $ concat [x1,x2,x3]"}], "negative_code": [{"source_code": "main = do\n\t[n,k] <- getLine >>= return . map read . words :: IO [Int]\n\tlst <- getLine >>= return . map read . words :: IO [Int]\n\tlet low x = length $ filter ((>=) x) lst\n\t(putStrLn . show . foldl max 0) [ (k - i) + (low i - 1) | i <- [1..k], low i > 0 ]\n"}, {"source_code": "main = do\n\t[n,k] <- getLine >>= return . map read . words :: IO [Int]\n\tlst <- getLine >>= return . map read . words :: IO [Int]\n\tlet low x = length $ filter ((>=) x) lst\n\t(putStrLn . show . foldl max 0) [ (k - i) + (low i - 1) | i <- [1..k] ]\n"}], "src_uid": "3d6411d67c85f6293f1999ccff2cd8ba"} {"source_code": "import Data.List\nimport Control.Monad\n\nmain = readLn >>= flip replicateM_ test\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n print $ sum $ maximum <$> groupBy (\\a b -> (a < 0) == (b < 0)) as\n\n\n", "positive_code": [{"source_code": "import Control.Monad\n\ntype Test = [Integer]\n\ngetTests :: Integer -> IO [Test]\ngetTests count = replicateM (fromIntegral count) getTest\n\ngetTest :: IO Test\ngetTest = do\n n <- getLine\n line <- getLine\n let list = map read (words line)\n return list\n\nprocessTest :: Test -> Integer\nprocessTest test = quantifyResult ([head test] ++ (tail test) ++ [-lastElement]) (head test) 0\n where lastElement = head $ reverse test\n\nquantifyResult :: Test -> Integer -> Integer -> Integer\nquantifyResult [x] maxElement result = result\nquantifyResult (first:rest) maxElement result = if first*(head rest) > 0\n then quantifyResult rest (max maxElement (head rest)) result\n else quantifyResult rest (head rest) (result + maxElement)\n\nprintResult :: Integer -> IO ()\nprintResult result = print result\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getTests $ read count\n let results = map processTest tests\n mapM_ printResult results"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- getIntList\n print $ f 0 0 a\n\npos :: Integer -> Bool\npos = (>0)\n\nf :: Integer -> Integer -> [Integer] -> Integer\nf v s [] = s + v\nf 0 s (x:xs) = f x s xs\nf v s (x:xs)\n | pos v == pos x = f (max x v) s xs\n | otherwise = f x (v + s) xs"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- getIntList\n print $ f a\n\nf :: [Integer] -> Integer\nf = sum . map maximum . groupBy (\\x y -> (x > 0) == (y > 0))\n"}, {"source_code": "import Control.Applicative\nreadArray :: IO [Integer]\nreadArray = do\n arrLine <- getLine\n return (map read (words arrLine) :: [Integer])\n\ngetSplitIdxs :: [(Integer, Integer, Int)] -> [Int]\ngetSplitIdxs [] = []\ngetSplitIdxs ((x, y, idx) : xs) | signum x /= signum y = idx : getSplitIdxs xs\n | otherwise = getSplitIdxs xs\n\ngetDifferences :: [Int] -> [Int]\ngetDifferences (x : xs) = x : ([ b - a | (b, a) <- zip xs (x : xs) ])\ngetDifferences [] = []\n\npartition :: [Integer] -> [Int] -> [[Integer]]\npartition [] [] = []\npartition nums [] = [nums]\npartition nums (cut : cuts) = take cut nums : partition (drop cut nums) cuts\n\nsolveCase :: IO ()\nsolveCase = do\n _ <- getLine\n arr <- readArray\n let zipped =\n getZipList $ (,,) <$> ZipList (drop 1 arr) <*> ZipList arr <*> ZipList\n [1 ..]\n let splitIdxs = getSplitIdxs zipped\n let diffs = getDifferences splitIdxs\n let parts = partition arr diffs\n putStrLn $ show (sum $ map maximum parts)\n\nmain :: IO ()\nmain = do\n tline <- getLine\n let ts = read tline :: Int\n sequence_ [ solveCase | _ <- [1 .. ts] ]\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n ns <- (map read.words) <$> getLine\n print $ solve ns\n\nsolve :: [Integer] -> Integer\nsolve ns = sum $ map maximum $ groupBy (\\x y -> (x>0) == (y>0)) ns\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (groupBy)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO :: IO ()\nsolveIO = getLine >> getList >>= print . solve\n\n\nsolve :: [Integer] -> Integer\nsolve = sum . map maximum . groupBy (\\a b -> signum a == signum b)"}, {"source_code": "data Mode = Pos | Neg\n\nisPos :: Integer -> Bool\nisPos n = n > 0\n\nisNeg :: Integer -> Bool\nisNeg n = n < 0\n\nsolve :: [Integer] -> Mode -> [Integer] -> [Integer]\nsolve [] _ ans = ans\nsolve numbers Pos ans = solve others Neg (m:ans)\n where (positives, others) = break isNeg numbers\n m = maximum positives\nsolve numbers Neg ans = solve others Pos (m:ans)\n where (negatives, others) = break isPos numbers\n m = maximum negatives\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (a:b:xs) = (a,b):groupByTwo xs\n\nsolve' :: [Integer] -> Integer\nsolve' (x:xs)\n | x > 0 = sum $ solve (x:xs) Pos []\n | otherwise = sum $ solve (x:xs) Neg []\n\nparse :: (String, String) -> String\nparse (_, arr) = show $ solve' numbers\n where numbers = map (\\x -> read x :: Integer) $ words arr\n\nmain :: IO ()\nmain = interact (unlines . map parse .groupByTwo. tail . lines)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- getIntList\n print $ f a\n\nf :: [Int] -> Int\nf = sum . map maximum . groupBy (\\x y -> (x > 0) == (y > 0))\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n ns <- (map read.words) <$> getLine\n print $ solve ns\n\nsolve :: [Int] -> Int\nsolve ns = sum $ map maximum $ groupBy (\\x y -> (x>0) == (y>0)) ns\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (groupBy)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO :: IO ()\nsolveIO = getLine >> getList >>= print . solve \n\nsolve :: [Int] -> Int\nsolve = sum . map maximum . groupBy (\\a b -> signum a == signum b)"}], "src_uid": "39480cdf697fc9743dc9665f989077d7"} {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (transpose)\nimport Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = printSolution =<< solve <$> (toTuple . map read . words <$> getLine)\n <*> (map (map read . words) . lines <$> getContents)\n\nsolve :: (Int, Int) -> [[Int]] -> Maybe [[Int]]\nsolve (n, m) xss = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss, not (null is) == not (null js) ]\n where (is, js) = (indices xss, indices (transpose xss))\n\nindices :: [[Int]] -> [Int]\nindices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]\n\ncross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]\ncross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n\nprintSolution :: Maybe [[Int]] -> IO ()\nprintSolution Nothing = putStrLn \"NO\"\nprintSolution (Just xss) = putStrLn \"YES\" >> mapM_ (putStrLn . unwords . map show) xss\n", "positive_code": [{"source_code": "import Data.List (transpose)\nimport Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = printSolution . solve . map (map read . words) . lines =<< getContents\n\nsolve :: [[Int]] -> Maybe [[Int]]\nsolve ([n, m] : xss) = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss, null is == null js ]\n where (is, js) = (indices xss, indices (transpose xss))\n\nindices :: [[Int]] -> [Int]\nindices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]\n\ncross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]\ncross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]\n\nprintSolution :: Maybe [[Int]] -> IO ()\nprintSolution Nothing = putStrLn \"NO\"\nprintSolution (Just xss) = putStrLn \"YES\" >> mapM_ (putStrLn . unwords . map show) xss\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n = map(take n).takeWhile(not.null).iterate(drop n)\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n mat <- map readInt.B.words <$> B.getContents\n case solve n m $ listArray((0,0),(n-1,m-1))mat of\n Nothing -> putStrLn \"NO\"\n Just res -> do\n putStrLn \"YES\"\n let xss = chunksOf m $ elems res\n putStr.unlines.map(unwords.map show) $ xss\n\nsolve :: Int -> Int -> UArray (Int,Int) Int -> Maybe (UArray (Int,Int) Int)\nsolve n m matB\n | calc n m matA == matB = Just matA\n | otherwise = Nothing\n where\n !matA = runSTUArray $ do\n mat <- newArray ((0,0),(n-1,m-1)) (-1) :: ST s (STUArray s (Int,Int) Int)\n let idx i j = i*m+j\n rep n $ \\i-> do\n rep m $ \\j-> do\n let bij = unsafeAt matB $ idx i j\n when (bij == 0) $ do\n rep n $ \\k -> do\n unsafeWrite mat (idx k j) 0\n rep m $ \\k -> do\n unsafeWrite mat (idx i k) 0\n rep n $ \\i-> do\n rep m $ \\j-> do\n aij <- unsafeRead mat $ idx i j\n when (aij<0) $ do\n unsafeWrite mat (idx i j) 1\n return mat\n\ncalc :: Int -> Int -> UArray (Int,Int) Int -> UArray (Int,Int) Int\ncalc n m mat = listArray ((0,0),(n-1,m-1)) [f i j|i<-[0..n-1],j<-[0..m-1]]\n where\n f i j\n | and [unsafeAt mat (i*m+k)==0|k<-[0..m-1]]\n && and [unsafeAt mat (k*m+j)==0|k<-[0..n-1]] = 0\n | otherwise = 1\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (transpose)\nimport Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = printSolution =<< solve <$> (toTuple . map read . words <$> getLine)\n <*> (map (map read . words) . lines <$> getContents)\n\nsolve :: (Int, Int) -> [[Int]] -> Maybe [[Int]]\nsolve (n, m) xss = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss, not (null is), not (null js) ]\n where (is, js) = (indices xss, indices (transpose xss))\n\nindices :: [[Int]] -> [Int]\nindices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]\n\ncross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]\ncross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n\nprintSolution :: Maybe [[Int]] -> IO ()\nprintSolution Nothing = putStrLn \"NO\"\nprintSolution (Just xss) = putStrLn \"YES\" >> mapM_ (putStrLn . unwords . map show) xss\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (transpose)\nimport Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = printSolution =<< solve <$> (toTuple . map read . words <$> getLine)\n <*> (map (map read . words) . lines <$> getContents)\n\nsolve :: (Int, Int) -> [[Int]] -> Maybe [[Int]]\nsolve (n, m) xss = listToMaybe [ cross (&&) n m is js | cross (||) n m is js == xss ]\n where (is, js) = (indices xss, indices (transpose xss))\n\nindices :: [[Int]] -> [Int]\nindices xss = [ i | (i, xs) <- zip [0..] xss, all (==1) xs ]\n\ncross :: (Bool -> Bool -> Bool) -> Int -> Int -> [Int] -> [Int] -> [[Int]]\ncross f n m is js = [ [ fromEnum ((i `elem` is) `f` (j `elem` js)) | j <- [0..m-1] ] | i <- [0..n-1] ]\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n\nprintSolution :: Maybe [[Int]] -> IO ()\nprintSolution Nothing = putStrLn \"NO\"\nprintSolution (Just xss) = putStrLn \"YES\" >> mapM_ (putStrLn . unwords . map show) xss\n"}], "src_uid": "bacd613dc8a91cee8bef87b787e878ca"} {"source_code": "main = interact $ printAns. solve. readInp\n\nreadInp = lines\nsolve (a:b:_)\n\t| a /= b = max (length a) (length b)\n\t| otherwise = -1\nprintAns = show\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ s, t ] <- lines <$> getContents\n\tprint $ which (-1) ( max ( length s ) ( length t ) ) $ s == t\n"}, {"source_code": "main = interact $ show . solve . words\n\nsolve [a, b] = if a == b then -1 else max (length a) (length b)"}, {"source_code": "main = do\n str1 <- getLine\n str2 <- getLine\n print (if str1 /= str2 then (max (length str1) (length str2)) else -1)\n"}, {"source_code": "{-# LANGUAGE NegativeLiterals #-}\nimport Data.List\nimport Data.Function\nmain = interact $ show . (\\[x,y] -> if x == y then -1 else length $ maximumBy (compare `on` length) [x,y]) . lines\n"}, {"source_code": "main :: IO ()\nmain = interact foo\n\nfoo :: String -> String\nfoo inp = \n let (a:b:_) = lines inp\n in if a == b\n then \"-1\"\n else show $ max (length a) (length b)"}, {"source_code": "main = interact $ show . solve . lines\nsolve [a,b] | length a == length b = if a == b then -1 else length a\n | otherwise = max (length a) (length b)\n"}, {"source_code": "main = do\n s1 <- getLine\n s2 <- getLine\n if s1 == s2\n then print (-1)\n else print $ max (length s1) (length s2)\n"}, {"source_code": "main = do\n a_ <- getLine\n b_ <- getLine\n let\n\tlenA = length a_\n\tlenB = length b_\n print $ if a_/=b_\n\tthen max lenA lenB\n\telse -1\n"}, {"source_code": "main = do\n a <- getLine\n b <- getLine\n print $ if a == b then -1 else max (length a) (length b)"}, {"source_code": "main = do\n s1 <- getLine\n s2 <- getLine\n if s1 == s2\n then \n print (-1)\n else\n print $ max (length s1) (length s2)\n"}], "negative_code": [{"source_code": "main = do\n str1 <- getLine\n str2 <- getLine\n putStrLn (if str1 /= str2 then (if (length str1) > (length str2) then str1 else str2) else \"-1\")\n"}, {"source_code": "import Data.List\nimport Data.Function\nmain = interact $ (\\[x,y] -> if x == y then \"-1\" else maximumBy (compare `on` length) [x,y]) . lines\n"}], "src_uid": "f288d7dc8cfcf3c414232a1b1fcdff3e"} {"source_code": "module Main where\n\ngetNumbers :: IO [Int]\ngetNumbers = do\n line <- getLine\n return $ map read $ words line\n\nsolution :: () -> IO ()\nsolution _ = do\n [a, b, c, x, y] <- getNumbers\n let a_ = max 0 $ (x - a)\n b_ = max 0 $ (y - b)\n ans = if a_ + b_ <= c then \"Yes\" else \"No\"\n putStrLn ans\n\nmain :: IO ()\nmain = do\n [t] <- getNumbers\n\n mapM_ solution $ replicate t ()", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\n\ngetNumbers :: IO [Int]\ngetNumbers = do\n map read . words <$> getLine\n\nsolution :: IO ()\nsolution = do\n [a, b, c, x, y] <- getNumbers\n let a_ = max 0 (x - a)\n b_ = max 0 (y - b)\n ans = if a_ + b_ <= c then \"Yes\" else \"No\"\n putStrLn ans\n\nmain :: IO ()\nmain = do\n [t] <- getNumbers\n replicateM_ t solution"}, {"source_code": "type Task = [TestCase]\ntype TestCase = (Int, Int, Int, Int, Int)\n\nreadInt :: String -> Int\nreadInt = read\n\nshowBool :: Bool -> String\nshowBool False = \"NO\"\nshowBool True = \"YES\"\n\nparseInput :: String -> Task\nparseInput contents = let input = tail . map (map readInt . words) . lines $ contents in\n let parseTestCase (a:b:c:x:y:[]) = (a, b, c, x, y) in\n map parseTestCase input\n\nsolve :: Task -> [Bool]\nsolve = map solveTestCase\n where solveTestCase (a, b, c, x, y) = x <= a + c && y <= b + c && x + y <= a + b + c\n\nformatOutput :: [Bool] -> String\nformatOutput = unlines . map showBool\n\nmain = getContents >>= (putStr . formatOutput . solve . parseInput)\n"}], "negative_code": [], "src_uid": "7ac27da2546a50d453f7bb6cacef1068"} {"source_code": "\r\nimport Control.Monad (replicateM_)\r\nimport Data.List \r\n\r\n\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n m <- read <$> getLine\r\n bs <- getLine\r\n let\r\n m0 = length $ filter (=='0') bs\r\n cs = replicate m0 '0' ++ replicate (m-m0) '1'\r\n ds = zip [1..] $ zipWith (/=) bs cs\r\n es = [i | (i,j)<-ds, j==True]\r\n print $ if null es then 0 else 1\r\n if null es then return () else putStrLn $ intercalate \" \" $ fmap show $ (length es) : es\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- read <$> getLine\r\n replicateM_ n solve\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\n\nmain :: IO ()\n-- main = C.interact $ runScanner input >>> solve >>> output\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC { n :: Int, s :: String }\n\ninput :: Scanner TC\ninput = do\n n <- int\n s <- str\n return TC {..}\n\ntype Output = [[Int]]\n\noutput :: Output -> C.ByteString\noutput ops = C.pack . unlines $ show (length ops) : map showl ops\n where\n showl xs = unwords . map show $ length xs : xs\n\nsolve :: TC -> Output\nsolve TC {..}\n | null bs0 = []\n | otherwise = [bs1 ++ bs0]\n where\n c0 = count '0' s\n bs0 = [i | (c, i) <- zip s [1..], c == '0', i > c0]\n bs1 = [i | (c, i) <- zip s [1..], c == '1', i <= c0]\n\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let cnt0 = length $ filter (=='0') s\r\n ans = [i | (i, x, y) <- zip3 [1..] s $ replicate cnt0 '0' ++ repeat '1', x /= y]\r\n if null ans\r\n then print 0\r\n else print 1 >> putStrLn (unwords $ map show $ length ans : ans)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "\r\nimport Control.Monad (replicateM_)\r\nimport Data.List \r\n\r\n\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n m <- read <$> getLine\r\n bs <- getLine\r\n let\r\n m0 = length $ filter (=='0') bs\r\n cs = replicate m0 '0' ++ replicate (m-m0) '1'\r\n ds = zip [1..] $ zipWith (/=) bs cs\r\n es = [i | (i,j)<-ds, j==True]\r\n print $ if null es then 0 else 1\r\n putStrLn $ intercalate \" \" $ fmap show $ (length es) : es\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- read <$> getLine\r\n replicateM_ n solve\r\n"}, {"source_code": "\r\nimport Control.Monad (replicateM_)\r\nimport Data.List \r\n\r\n\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n m <- read <$> getLine\r\n bs <- getLine\r\n let\r\n m0 = length $ filter (=='0') bs\r\n cs = replicate m0 '0' ++ replicate (m-m0) '1'\r\n ds = zip [1..] $ zipWith (/=) bs cs\r\n es = [i | (i,j)<-ds, j==True]\r\n print $ if null es then 0 else 1\r\n print $ intercalate \" \" $ fmap show $ (length es) : es\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- read <$> getLine\r\n replicateM_ n solve\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let cnt0 = length $ filter (=='0') s\r\n ans = [i | (i, x, y) <- zip3 [1..] s $ replicate cnt0 '0' ++ repeat '1', x /= y]\r\n if null ans\r\n then print 0\r\n else print 1 >> putStrLn (unwords $ map show ans)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "src_uid": "f472f9df8b4d588c67b39df6865507ca"} {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nreadIntLine :: IO [Int]\r\nreadIntLine = fmap (map read.words) getLine\r\n\r\nsolve = do\r\n s <- getLine\r\n s <- getLine\r\n let t = sort s\r\n print $ sum $ zipWith (\\x y -> if x /= y then 1 else 0) t s\r\n\r\nmain = do\r\n [t] <- readIntLine\r\n replicateM t solve\r\n return ()", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n s <- getLine\r\n print $ length $ filter id $ zipWith (/=) s (sort s)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad (replicateM)\r\nimport Data.List ( sort )\r\n\r\n-- main :: IO [()]\r\nmain = do\r\n n <- read <$> getLine\r\n replicateM n $ do\r\n y <- read <$> getLine\r\n x <- getLine\r\n print $ y - solve x\r\n\r\nsolve :: [Char] -> Int\r\nsolve x = foldr (\\(i,j) acc -> if i == j then acc + 1 else acc) 0 (zip x (sort x))"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified Data.Ratio as Rat\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n s <- getLine\n let res = zipWith (\\a b -> a == b) s $ sort s\n sol = length $ filter (==False) res\n in print sol\n \n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral b) => b -> IO [String]\nreadrows 0 = return []\nreadrows n = do\n row <- getLine\n l <- readrows $ n-1\n return (row : l)\n\n\nreadintrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadintrows 0 = return []\nreadintrows n = do\n row <- readInts\n l <- readintrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nprintResult = do\r\n n <- getLine\r\n s <- getLine\r\n let ss = sort s\r\n print $ sum $ zipWith (\\x y->if x /= y then 1 else 0) ss s\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.List (sort)\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> chunksOf 2 >>> map (last >>> solve >>> show) >>> unlines\n\nsolve :: String -> Int\nsolve s = length . filter not $ zipWith (==) s (sort s)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n s <- P.unpack <$> readLine\n putInts [length [() | (c, v) <- zip s (sort s), c /= v]]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "58ee86d4913787582ccdb54073656dc0"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nnextInt :: ByteString -> Int\nnextInt = fst . fromJust . C.readInt\n\nsolve :: [Int] -> String\nsolve xs = \n let ds = sort $ zipWith (-) (tail xs) xs\n h = head ds\n len = length $ takeWhile (== h) ds\n in unwords $ map show [h, len]\n\nmain = do\n (sort . tail . map nextInt . C.words -> xs) <- B.getContents\n putStrLn $ solve xs", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = putStrLn . unwords . map show . solve . tail . map (fst . fromJust . C.readInt) . C.words =<< B.getContents\n\nsolve :: [Int] -> [Int]\nsolve a = solve' [maxBound :: Int, 0] (sort a)\n\nsolve' :: [Int] -> [Int] -> [Int]\nsolve' result [] = result\nsolve' result [a] = result\nsolve' [d, c] (a:b:x) | b - a < d = solve' [b - a, 1] (b:x)\n | b - a == d = solve' [d, c + 1] (b:x)\n | otherwise = solve' [d, c] (b:x)\n"}, {"source_code": "{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nnextInt :: ByteString -> Int\nnextInt = fst . fromJust . C.readInt\n\nsolve :: [Int] -> String\nsolve xs = \n let ds = sort $ zipWith (-) (tail xs) xs\n h = head ds\n len = length $ takeWhile (== h) ds\n in show h ++ \" \" ++ show len\n\nmain = do\n (sort . tail . map nextInt . C.words -> xs) <- B.getContents\n putStrLn $ solve xs"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\nreadint = fst. fromJust . C.readInt\n\nmain = do\n (readint -> n) <- B.getLine\n (sort . map readint . C.words -> xs) <- B.getLine\n let ds = sort $ zipWith (-) (tail xs) xs\n putStrLn $ show (head ds) ++ \" \" ++ show (length $ takeWhile (== (head ds)) ds)\n"}], "negative_code": [], "src_uid": "5f89678ae1deb1d9eaafaab55a64197f"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\n\nmain = getLine >> do\n ps <- map read.words <$> getLine :: IO [Integer]\n [a,b,c,d,e] <- map read.words <$> getLine :: IO [Integer]\n let solve !point !cnts [] = do\n putStrLn.unwords $ map show cnts\n print point\n solve !point !cnts (x:xs) = solve ra (zipWith (+) cnts [da,db,dc,dd,de]) xs\n where\n (de,re) = (point+x)`divMod`e\n (dd,rd) = re`divMod`d\n (dc,rc) = rd`divMod`c\n (db,rb) = rc`divMod`b\n (da,ra) = rb`divMod`a \n solve 0 [0,0,0,0,0] ps\n", "positive_code": [{"source_code": "main = do\n getLine\n p <- fmap (map read . words) getLine\n q <- fmap (reverse . map read . words) getLine\n let (x, y) = foldl (gao q) (repeat 0, 0) p\n putStrLn $ unwords $ map show $ reverse x ++ [y]\n\ngao q (c, s) t = let (x, y) = go q c [] (s+t) in (reverse x, y)\n\ngo [] _ x y = (x, y)\ngo (a:as) (b:bs) x y = let c = y `div` a in go as bs (b+c:x) (y `mod` a)\n"}, {"source_code": "import Prelude hiding (Int ())\n\ntype Int = Integer\ntype Fiver = (Int, Int, Int, Int, Int)\n\nsolve :: Fiver -> [Int] -> (Fiver, Int)\nsolve (a,b,c,d,e) xs = solve' xs ((0, 0, 0, 0, 0), 0)\n where\n solve' [] acc = acc\n solve' (x:xs) ((a',b',c',d',e'), y)\n | xy >= e = solve' ((xy `mod` e) : xs) ((a', b', c', d', e' + xy `div` e), 0)\n | xy >= d = solve' ((xy `mod` d) : xs) ((a', b', c', d' + xy `div` d, e'), 0)\n | xy >= c = solve' ((xy `mod` c) : xs) ((a', b', c' + xy `div` c, d', e'), 0)\n | xy >= b = solve' ((xy `mod` b) : xs) ((a', b' + xy `div` b, c', d', e'), 0)\n | xy >= a = solve' ((xy `mod` a) : xs) ((a' + xy `div` a, b', c', d', e'), 0)\n | otherwise = solve' xs ((a',b',c',d',e'), xy)\n where\n xy = x + y\n\nprintAns :: (Fiver, Int) -> IO ()\nprintAns ((a, b, c, d, e), x) = putStrLn (unwords (map show [a,b,c,d,e])) >> print x\n\nmain :: IO()\nmain = do\n getLine\n xs <- getLine >>= return . map read . words\n [a,b,c,d,e] <- getLine >>= return . map read . words\n printAns $ solve (a,b,c,d,e) xs"}, {"source_code": "\n\nbuy money [] = (money, [])\nbuy money (p:ps) = \n let (nokori, buyed ) = buy money ps\n in (mod nokori p, div nokori p:buyed)\n\nnext ps (money, gift) addp = \n let (nokori, ngift) = buy (money+addp) ps\n in (nokori, zipWith (\\x y->x+y) gift ngift )\n\ncal getPoints ps = foldl (next ps) (0, [0,0,0,0,0]) getPoints\n\njoin c (x:[]) = x\njoin c (x:xs) = x++(c:join c xs) \n\nmain = do\n _ <- getLine\n s <- getLine\n let getPoints = map read $ words s\n s2 <- getLine\n let ps = map read $ words s2\n let (remMoney, gifts) = cal getPoints ps\n putStrLn $ join ' ' $ map show gifts\n print remMoney\n "}, {"source_code": "import Control.Monad\n\nreadInt :: String -> Integer\nreadInt = read\n\nbuyItems cash [] = (cash,[])\nbuyItems cash (c:cs) = (cash',cnt:bought)\n where cnt = cash `div` c\n (cash',bought) = buyItems (cash-cnt*c) cs\n\naddList xs ys = map (\\(a,b)->a+b) $ zip xs ys\n\nmain = do\n n <- liftM readInt $ getLine\n ps <- liftM (map readInt . words) $ getLine\n cs <- liftM (reverse . map readInt . words) $ getLine\n let (cash, bt) = foldl (f cs) (0,repeat 0) ps\n putStrLn . unwords . map show . reverse $ bt\n putStrLn . show $ cash\n where f cs (cash,bought) p = (cash',addList bt bought)\n where (cash',bt) = (buyItems (cash+p) cs)"}, {"source_code": "import Control.Monad\n\nsolve (a,b,c,d,e) xs = solve' 0 [0,0,0,0,0] xs\n where\n costs = [e,d,c,b,a]\n solve' n ys (x:xs) = \n let\n (l, r) = spend (n+x) costs\n in\n solve' l (zipWith (+) r ys) xs\n where \n spend p [] = (p, [])\n spend p (x:xs) =\n let\n cnt = p `div` x\n rem = p - cnt * x\n (l, r) = spend rem xs\n in\n (l, cnt : r)\n solve' n ys [] = (n, ys)\n \nmain = do\n n <- liftM read getLine\n xs <- getLine >>= (return.map read.take n.words)\n [a,b,c,d,e] <- getLine >>= (return.map read.take 5.words)\n let (l, r) = solve (a,b,c,d,e) xs :: (Integer, [Integer])\n putStrLn (unwords $ reverse $ map show r)\n putStrLn (show l)"}], "negative_code": [], "src_uid": "1ae2942b72ebb7c55359c41e141900d7"} {"source_code": "main :: IO ()\nmain = do\n [n, r] <- map (read :: String -> Double) . words <$> getLine \n print $ r / (sqrt (2 / (1 - cos (2 * pi / n))) - 1)\n", "positive_code": [{"source_code": "-- Codeforces Round #532 (C), Contest 1100, Problem set ?.\n-- UNDONE\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n,r] <- map read . words <$> getLine :: IO [Double]\n print $ r * sin(pi/n) / (1 - sin (pi/n))\n \n"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\nimport Data.Bits\nimport Data.IORef\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nsolve :: Double -> Double -> Double\nsolve n r = r / (1 / sin (2 * pi / (2 * n)) - 1)\n\nmain :: IO ()\nmain = do\n [n, r] <- (map (read :: String -> Double) . words) <$> getLine\n let answer = solve n r\n printf \"%.10f\" $ answer"}], "negative_code": [], "src_uid": "e27cff5d681217460d5238bf7ef6a876"} {"source_code": "main = (read `fmap` getLine) >>= \\n -> \n (if even n then mapM_ (putStrLn . take n . concat . repeat) [\"aabb\", \"ccdd\"] >>\n mapM_ (\\x -> putStrLn $ \"e\" ++ (take (n - 2) $ concat $ repeat x) ++ \"h\")\n [\"ffgg\", \"aabb\"]\n else mapM_ (\\x -> putStrLn $ \"a\" ++ (take (n - 1) $ concat $ repeat x))\n [\"bbcc\", \"ddee\"] >>\n mapM_ (\\x -> putStrLn $ (take (n - 1) $ concat $ repeat x)++\"g\")\n [\"bbcc\", \"ddee\"])\n", "positive_code": [{"source_code": "\nimport Control.Applicative\nimport Data.Monoid\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.Map(Map)\nimport Data.Maybe\n\ntype Ending = [IsHorisEnd]\n\n\ndata State s v = State { runState :: (s -> (s, v)) }\ntype StateMap a b = State (Map a b) b\n\ninstance Functor (State a) where\n fmap f s = State $ \\m -> let (s', m') = runState s m in (s', f m')\n\ninstance Monad (State a) where\n return x = State $ \\m -> (m, x)\n a >>= f = joinState $ f <$> a\n\njoinState s = State $ \\m -> let (m', s') = runState s m in runState s' m'\n\nget = State $ \\m -> (m, m)\nput m' = State $ \\m -> (m', ())\nevalState s m = snd $ (runState s) m\n\nmemoizeM :: (Show a, Show b, Ord a) => \n ((a -> StateMap a b) -> (a -> StateMap a b)) -> (a -> b)\nmemoizeM t x = evalState (f x) Map.empty where\n g x = do\n y <- t f x\n m <- get\n put $ Map.insert x y m\n newM <- get\n return $ y\n f x = get >>= \\m -> maybe (g x) return (Map.lookup x m)\n\n\ntype IsHorisEnd = Bool\ntype IsVertStart = Bool\n\ngetContinuations :: Ending -> [[(IsHorisEnd, IsVertStart)]]\ngetContinuations = go\n where\n go :: [Bool] -> [[(IsHorisEnd, IsVertStart)]]\n go [] = [[]]\n go (False : False : t) = let aug l = [(True, False) : (True, False) : l, (False, True) : (False, False) : l] in go t >>= aug\n go (b : t) = map ((not b, False) :) $ go t\n\n\ngetHor :: Int -> Int -> Char\ngetHor n i = toEnum $ fromEnum 'a' + (i `mod` 2) + 2 * (n `mod` 3)\ngetVert :: Int -> Int -> Char\ngetVert n i = toEnum $ fromEnum 'p' + (n `mod` 2) + 2 * (i `mod` 3)\n\nsolve :: (Functor m, Monad m) => ((Ending, Int) -> m (Maybe [String])) -> (Ending, Int) -> m (Maybe [String])\nsolve rec (ed, 0) = return $ do\n guard (not $ or ed)\n (return [\"\",\"\",\"\",\"\"]) :: Maybe [String]\nsolve rec (ed, n) = getFirst . mconcat . map First <$> (solveAll $ getContinuations ed)\n where\n solveAll = mapM solve\n solve cont | (not $ isGood (map fst cont)) = return Nothing\n solve cont = do\n res <- rec (map fst cont, n-1)\n return (appendThis cont <$> (res :: Maybe [String]) :: Maybe [String])\n isGood | n==1 = not . or\n | n>1 = or\n appendThis :: [(IsHorisEnd, IsVertStart)] -> [String] -> [String]\n appendThis cont res = zipWith (:) (getThis cont) res\n getChar True (False, False) i = getHor (n+1) i\n getChar False (True, False) i = getHor n i\n getChar False (False, True) i = getVert n i\n getChar False (False, False) i = getVert n (i-1)\n getThis cont = zipWith3 getChar ed cont [1..]\n\n\nmain = interact $ unlines . fromMaybe [\"-1\"] . memoizeM solve . (\\n -> (replicate 4 False, n)) . read\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n n <- read `liftM` getLine\n putStr $ board n\n\nboard n =\n if even n\n then\n take n (cycle \"aabb\") ++ \"\\n\" ++\n \"i\" ++ take (n-2) (cycle \"ccdd\") ++ \"j\\n\" ++\n \"i\" ++ take (n-2) (cycle \"eeff\") ++ \"j\\n\" ++\n take n (cycle \"gghh\") ++ \"\\n\"\n else\n take (n-1) (cycle \"aabb\") ++ \"i\\n\" ++\n take (n-1) (cycle \"ccdd\") ++ \"i\\n\" ++\n \"j\" ++ take (n-1) (cycle \"eeff\") ++ \"\\n\" ++\n \"j\" ++ take (n-1) (cycle \"gghh\") ++ \"\\n\"\n"}, {"source_code": "myPrint :: Int -> Int -> String\nmyPrint 1 n\n | mod n 2 == 0 = take n (cycle \"aabb\")\n | otherwise = take (n - 1) (cycle \"aabb\") ++ \"z\"\nmyPrint 2 n\n | mod n 2 == 0 = take n (cycle \"ccdd\")\n | otherwise = take (n - 1) (cycle \"ccdd\") ++ \"z\"\nmyPrint 3 n\n | mod n 2 == 0 = 'q' : (take (n - 2) (cycle \"aabb\") ++ \"z\")\n | otherwise = 'q' : (take (n - 1) (cycle \"aabb\"))\nmyPrint 4 n\n | mod n 2 == 0 = 'q' : (take (n - 2) (cycle \"ccdd\") ++ \"z\")\n | otherwise = 'q' : (take (n - 1) (cycle \"ccdd\"))\n\nmain = do\n n <- readLn::IO Int\n putStrLn (myPrint 1 n)\n putStrLn (myPrint 2 n)\n putStrLn (myPrint 3 n)\n putStrLn (myPrint 4 n)"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n return n\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve :: Int -> ByteString\nsolve n = BS.unlines . map BS.pack $ answer\n where\n answer\n | even n = [r2 0 False, r121 1 False, r121 2 True, r2 3 False]\n | otherwise = [r21 0 False, r21 1 True, r12 2 False, r12 3 True]\n\n n2 = n `div` 2\n\n r2 = color (replicate n2 2)\n r121 = color ([1] ++ replicate (n2 - 1) 2 ++ [1])\n r21 = color (replicate n2 2 ++ [1])\n r12 = color ([1] ++ replicate n2 2)\n\n\n color :: [Int] -> Int -> Bool -> String\n color a row bool = concatMap go $ zip (cycle [0..4]) a \n where\n go (id, num) = replicate num (chr $ ord 'a' + row' * 5 + id)\n where\n row' = if num == 1 && bool then row - 1 else row -- vertical\n \n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "negative_code": [{"source_code": "main = (read `fmap` getLine) >>= \\n -> \n (if even n then mapM_ (putStrLn . take n . concat . repeat) [\"aabb\", \"ccdd\"] >>\n mapM_ (\\x -> putStrLn $ \"e\" ++ (take (n - 2) $ concat $ repeat x) ++ \"e\")\n [\"ffgg\", \"aabb\"]\n else mapM_ (\\x -> putStrLn $ \"a\" ++ (take (n - 1) $ concat $ repeat x))\n [\"bbcc\", \"ddee\"] >>\n mapM_ (\\x -> putStrLn $ (take (n - 1) $ concat $ repeat x)++\"a\")\n [\"bbcc\", \"ddee\"])\n"}, {"source_code": "main = (read `fmap` getLine) >>= \\n -> \n (if even n then mapM_ (putStrLn . take n . concat . repeat) [\"aabb\", \"ccdd\"] >>\n mapM_ (\\x -> putStrLn $ \"e\" ++ (take (n - 2) $ concat $ repeat x) ++ \"h\")\n [\"ffgg\", \"aabb\"]\n else mapM_ (\\x -> putStrLn $ \"a\" ++ (take (n - 1) $ concat $ repeat x))\n [\"bbcc\", \"ddee\"] >>\n mapM_ (\\x -> putStrLn $ (take (n - 1) $ concat $ repeat x)++\"a\")\n [\"bbcc\", \"ddee\"])\n"}], "src_uid": "42a51b45312be6b38f3a15949d315c67"} {"source_code": "\nimport Data.IntMap (elems, empty, insertWith, unionWith)\nimport Monad (liftM)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xs\n | res == maxBound = -1\n | otherwise = res\n where\n res = minimum $ map f $ elems $ unionWith add mapA mapB\n halfN = div n 2 + mod n 2\n mapA = foldl (\\map x -> insertWith add x (1,0) map) empty (map fst xs) \n mapB = foldl (\\map x -> insertWith add x (0,1) map) empty (map snd . filter notEq $ xs)\n notEq (x, y) = x /= y\n add (a, b) (c, d) = (a+c, b+d)\n f (a,b)\n | a + b >= halfN = max 0 (halfN - a)\n | otherwise = maxBound\n\nparse :: String -> (Int, Int)\nparse line = case words line of\n [s1, s2] -> (read s1, read s2)\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- liftM (take n . map parse . lines) getContents\n print $ solve n xs\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n $ getInts\n\n let\n a = map (\\g -> (head g, length g)) . group . sort $ map (!! 0) ps\n b = map (\\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\\[a, b] -> a /= b) ps\n\n max' m (c1, c2)\n | c1 + c2 >= (n+1)`div`2 = min m $ max 0 $ (n+1)`div`2 - c1\n | otherwise = m\n\n merge [] [] m = m\n merge ((_, c1):as) [] m = merge as [] $ max' m (c1, 0)\n\n merge [] ((_, c2):bs) m = merge [] bs $ max' m (0, c2)\n\n merge as@((a, c1):as') bs@((b, c2):bs') m\n | a < b = merge as' bs $ max' m (c1, 0)\n | a > b = merge as bs' $ max' m (0, c2)\n | otherwise = merge as' bs' $ max' m (c1, c2)\n\n r :: Int = merge a b maxBound\n\n print $ if r == maxBound then -1 else r\n\n"}, {"source_code": "import Data.List\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt s = let Just (n,_) = B.readInt s in n\n\ntoPairs [] = []\ntoPairs (x:y:xys) = (x,y):toPairs xys\n\nins imap (x,y)\n | x==y = IM.insertWith (\\_ (f,b)->(f+1,b)) x (1,0) imap\n | otherwise = IM.insertWith (\\_ (f,b)->(f+1,b)) x (1,0) $\n IM.insertWith (\\_ (f,b)->(f,b+1)) y (0,1) imap\n\nmain = do\n n <- readLn\n let m = (n+1)`div`2\n gr <- IM.elems.foldl' ins IM.empty.toPairs.map readInt.B.words<$> B.getContents\n case filter (\\(f,b)->f+b>=m) gr of\n [] -> print $ -1\n xs -> print $ minimum $ map (\\(f,b)-> max 0 $ m-f) xs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n $ getInts\n\n let\n a = map (\\g -> (head g, length g)) . group . sort $ map (!! 0) ps\n b = map (\\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\\[a, b] -> a /= b) ps\n\n max' m (c1, c2)\n | c1 + c2 > n`div`2 = min m $ max 0 $ n`div`2 + 1 - c1\n | otherwise = maxBound\n\n merge [] [] m = m\n merge ((_, c1):as) [] m = merge as [] $ max' m (c1, 0)\n merge [] ((_, c2):bs) m = merge [] bs $ max' m (0, c2)\n merge as@((a, c1):as') bs@((b, c2):bs') m\n | a < b = merge as' bs $ max' m (c1, 0)\n | a > b = merge as bs' $ max' m (0, c2)\n | otherwise = merge as' bs' $ max' m (c1, c2)\n\n r :: Int = merge a b maxBound\n\n\n print $ if r == maxBound then -1 else r\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n $ getInts\n\n let\n a = map (\\g -> (head g, length g)) . group . sort $ map (!! 0) ps\n b = map (\\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\\[a, b] -> a /= b) ps\n\n merge [] _ m = m\n merge _ [] m = m\n merge as@((a, c1):as') bs@((b, c2):bs') m\n | a < b = merge as' bs m\n | a > b = merge as bs' m\n | c1 + c2 > n `div` 2 = merge as' bs' $ min m $ max 0 $ n`div`2 + 1 - c1\n | otherwise = merge as' bs' m\n\n r = merge a b maxBound\n\n print $ if r == maxBound then -1 else r\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n $ getInts\n\n let\n a = map (\\g -> (head g, length g)) . group . sort $ map (!! 0) ps\n b = map (\\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\\[a, b] -> a /= b) ps\n\n max' m (c1, c2)\n | c1 + c2 > n`div`2 = min m $ max 0 $ n`div`2 + 1 - c1\n | otherwise = m\n\n merge [] [] m = m\n merge ((_, c1):as) [] m = merge as [] $ max' m (c1, 0)\n\n merge [] ((_, c2):bs) m = merge [] bs $ max' m (0, c2)\n\n merge as@((a, c1):as') bs@((b, c2):bs') m\n | a < b = merge as' bs $ max' m (c1, 0)\n | a > b = merge as bs' $ max' m (0, c2)\n | otherwise = merge as' bs' $ max' m (c1, c2)\n\n r :: Int = merge a b maxBound\n\n print $ if r == maxBound then -1 else r\n\n"}], "src_uid": "5e055bad1da5bdc84599d6f2f89fbd12"} {"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [h, w, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (0, w*h-1) $ zip [0..(w*h-1)] emptyStrings\n let commands = map words $ tail list\n let result = foldl (f w h) (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf w h (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = i*w + j\n loc = locate arr n n\n i = -1 + (read i' :: Int)\n j = -1 + (read j' :: Int)\nf w h (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((parse w h loc):actions))\n where \n loc = find name arr 0\n\nparse w h n = show i ++ \" \" ++ show j\n where \n i = 1 + n `div` w\n j = 1 + n `mod` w\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n n0\n-- | n == (n0-1) = -1\n-- | n > r = locate arr 0 n0\n | n > r = -1\n | otherwise = if arr!n == \"\" then n else locate arr (n+1) n0\n where (_, r) = bounds arr\n", "positive_code": [{"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> b -> b\n--debug = trace . show\ndebug _ = id\n\nmain = readFile \"input.txt\" >>= (writeFile \"output.txt\" . output . solve . parse . lines)\n\noutput = unlines . map (\\(x, y) -> show x ++ \" \" ++ show y)\n\nparse :: [String] -> (Int, Int, [([Int], String)])\nparse (nmk:rest) =\n let [n, m, k] = map read . words $ nmk\n lst = map (f . words) . take k $ rest\n f wds = (rfix (head wds) : map read (tail (init wds)), last wds)\n rfix ('+':s) = 1\n rfix ('-':s) = -1\n in (n, m, lst)\n\nsolve (n, m, lst) =\n let (_, _, responses) = foldl' process (startingState, M.empty, []) lst\n startingState = IM.fromDistinctAscList $ zip [1..n]\n (repeat (IM.fromDistinctAscList $ zip [1..m] (repeat \"\")))\n\n process (state, idx, responses) (nums, name) =\n case head nums of\n 1 -> processAdd state idx responses (tail nums) name\n _ -> processRemove state idx responses name\n\n processRemove state idx responses name =\n case M.lookup name idx of\n Nothing -> (state, idx, (-1, -1) : responses)\n Just (x,y) -> (newState, newIdx, (x,y) : responses)\n where newIdx = M.delete name idx\n newState = IM.insert x (IM.insert y \"\" oldArray) state\n Just oldArray = IM.lookup x state\n\n processAdd state idx responses [x,y] name =\n case findFree state x y of\n Nothing -> debug \"miss\" (state, idx, responses)\n Just (i, j) -> debug (i,j) $ (newState, newIdx, responses)\n where newState = IM.insert i (IM.insert j name oldArray) state\n Just oldArray = IM.lookup i state\n newIdx = M.insert name (i,j) idx\n\n findFree state x y | y == m+1 = findFree state (x+1) 1\n | x == n+1 = Nothing\n findFree state x y =\n case IM.lookup y arr of\n Just \"\" -> Just (x,y)\n Just s -> debug s $ findFree state x (y+1)\n where Just arr = IM.lookup x state\n\n in reverse responses\n\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve'$solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve' a = case elem '#' a of\n True -> \"\"\n False->a\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) b of\n Just c -> (toString (c`div`n+1))++\" \"++\n (toString (c`mod`n+1))++\"\\n\"++\n solve m n xs (ins c \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | a!!3 `elem` b = \"#\"\n | b!!ind == \"\" = solve m n xs (ins ind (a!!3) b)\n | otherwise = case elemIndex \"\" (drop (ind) b) of\n Just c -> solve m n xs (ins (c+ind) (a!!3) b)\n Nothing ->solve m n xs b\n where\n l = length b\n ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)\nsolve _ _ [] _ = \"\""}], "negative_code": [{"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [w, h, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings\n let commands = map words $ tail list\n let result = foldl (f w h) (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf w h (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = (i-1)*(j-1)+1\n loc = locate arr n\n i = read i' :: Int\n j = read j' :: Int\nf w h (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((parse w h loc):actions))\n where \n loc = find name arr 1\n\nparse w h n = show i ++ \" \" ++ show j\n where \n i = 1 + ((n-1) `div` w)\n j = 1 + ((n-1) `mod` w)\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n\n | n > r = -1\n | otherwise = if arr!n == \"\" then n else locate arr (n+1)\n where (_, r) = bounds arr\n"}, {"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [w, h, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (0, w*h-1) $ zip [0..(w*h-1)] emptyStrings\n let commands = map words $ tail list\n let result = foldl (f w h) (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf w h (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = i*w + j\n loc = locate arr n n\n i = -1 + (read i' :: Int)\n j = -1 + (read j' :: Int)\nf w h (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((parse w h loc):actions))\n where \n loc = find name arr 0\n\nparse w h n = show i ++ \" \" ++ show j\n where \n i = 1 + n `div` w\n j = 1 + n `mod` w\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n n0\n-- | n == (n0-1) = -1\n-- | n > r = locate arr 0 n0\n | n > r = -1\n | otherwise = if arr!n == \"\" then n else locate arr (n+1) n0\n where (_, r) = bounds arr\n"}, {"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [w, h, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings\n let commands = map words $ tail list\n let result = foldl (f w h) (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf w h (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = (i-1)*w + j\n loc = locate arr n\n i = read i' :: Int\n j = read j' :: Int\nf w h (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((parse w h loc):actions))\n where \n loc = find name arr 1\n\nparse w h n = show i ++ \" \" ++ show j\n where \n i = 1 + ((n-1) `div` w)\n j = 1 + ((n-1) `mod` w)\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n\n | n > r = -1\n | otherwise = if arr!n == \"\" then n else locate arr (n+1)\n where (_, r) = bounds arr\n"}, {"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [w, h, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings\n let commands = map words $ tail list\n let result = foldl f (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = (i-1)*(j-1)+1\n loc = locate arr n\n i = read i' :: Int\n j = read j' :: Int\nf (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((\"-1 \" ++ arr!loc):actions))\n where \n loc = find name arr 1\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n\n | n > r = -1\n | otherwise = if arr!n == \"\" then n else locate arr (n+1)\n where (_, r) = bounds arr\n"}, {"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [w, h, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings\n let commands = map words $ tail list\n let result = foldl (f w h) (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf w h (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = (i-1)*(j-1)+1\n loc = locate arr n n\n i = read i' :: Int\n j = read j' :: Int\nf w h (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((parse w h loc):actions))\n where \n loc = find name arr 1\n\nparse w h n = show i ++ \" \" ++ show j\n where \n i = 1 + ((n-1) `div` w)\n j = 1 + ((n-1) `mod` w)\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n0 n\n | n == n0-1 = -1\n | n > r = locate arr n0 1\n | otherwise = if arr!n == \"\" then n else locate arr n0 (n+1)\n where (_, r) = bounds arr\n"}, {"source_code": "import System.IO\nimport Array\n\nemptyStrings = \"\":emptyStrings\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n let list = lines s\n let [w, h, n] = map (\\x -> read x :: Int) $ words $ head list\n let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings\n let commands = map words $ tail list\n let result = foldl (f w h) (arr, []) commands\n-- mapM_ (\\s -> putStrLn s) $ reverse $ snd result\n writeFile \"output.txt\" $ unlines $ foldr (:) [] $ reverse $ snd result\n\nf w h (arr, actions) [\"+1\", i', j', name]\n | loc < 0 = (arr, actions)\n | otherwise = (arr // [(loc, name)], actions)\n where \n n = (i-1)*w + j\n loc = locate arr n n\n i = read i' :: Int\n j = read j' :: Int\nf w h (arr, actions) [\"-1\", name]\n | loc < 0 = (arr, (\"-1 -1\":actions))\n | otherwise = (arr // [(loc, \"\")], ((parse w h loc):actions))\n where \n loc = find name arr 1\n\nparse w h n = show i ++ \" \" ++ show j\n where \n i = 1 + ((n-1) `div` w)\n j = 1 + ((n-1) `mod` w)\n\nfind name arr n \n | n > r = -1\n | otherwise = if arr!n == name then n else find name arr (n+1)\n where (_, r) = bounds arr\n\nlocate arr n n0\n | n == (n0-1) = -1\n | n > r = locate arr 1 n0\n | otherwise = if arr!n == \"\" then n else locate arr (n+1) n0\n where (_, r) = bounds arr\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve'$solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve' a = case elem '#' a of\n True -> \"\"\n False->a\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) (reverse b) of\n Just c -> (toString ((l-c-1)`div`n+1) )++\" \"++\n (toString ((l-c-1)`mod`n+1))++\"\\n\"++\n solve m n xs (ins (l-c-1) \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | b!!(ind (a!!1) (a!!2)) == \"\"\n = solve m n xs (ins (ind (a!!1) (a!!2)) (a!!3) b)\n | otherwise = case elemIndex \"\" b of\n Just c -> solve m n xs (ins c (a!!3) b)\n Nothing ->\"#\"\n where\n l = length b\n ind a b = (toInt a -1)*n + (toInt b-1)\nsolve _ _ [] _ = \"\""}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) (reverse b) of\n Just c -> (toString ((l-c-1)`div`n+1) )++\" \"++\n (toString ((l-c-1)`mod`n+1))++\"\\n\"++\n solve m n xs (ins (l-c-1) \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | b!!(ind (a!!1) (a!!2)) == \"\"\n = solve m n xs (ins (ind (a!!1) (a!!2)) (a!!3) b)\n | otherwise = case elemIndex \"\" b of\n Just c -> solve m n xs (ins c (a!!3) b)\n Nothing ->undefined\n where\n l = length b\n ind a b = (toInt a -1)*n + (toInt b-1)\nsolve _ _ [] _ = \"\""}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve'$solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve' a = case elem '#' a of\n True -> \"\"\n False->a\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) b of\n Just c -> (toString (c`div`n+1))++\" \"++\n (toString (c`mod`n+1))++\"\\n\"++\n solve m n xs (ins c \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | a!!3 `elem` b = \"#\"\n | b!!ind == \"\" = solve m n xs (ins ind (a!!3) b)\n | otherwise = case elemIndex \"\" (drop ind b) of\n Just c -> solve m n xs (ins c (a!!3) b)\n Nothing ->solve m n xs b\n where\n l = length b\n ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)\nsolve _ _ [] _ = \"\""}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve'$solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve' a = case elem '#' a of\n True -> \"\"\n False->a\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) (reverse b) of\n Just c -> (toString ((l-c-1)`div`n+1) )++\" \"++\n (toString ((l-c-1)`mod`n+1))++\"\\n\"++\n solve m n xs (ins (l-c-1) \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | a!!3 `elem` b = \"#\"\n | b!!ind == \"\" = solve m n xs (ins ind (a!!3) b)\n | otherwise = case elemIndex \"\" (drop ind b) of\n Just c -> solve m n xs (ins c (a!!3) b)\n Nothing ->\"#\"\n where\n l = length b\n ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)\nsolve _ _ [] _ = \"\""}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve'$solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve' a = case elem '#' a of\n True -> \"\"\n False->a\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) (reverse b) of\n Just c -> (toString ((l-c-1)`div`n+1) )++\" \"++\n (toString ((l-c-1)`mod`n+1))++\"\\n\"++\n solve m n xs (ins (l-c-1) \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | a!!3 `elem` b = \"#\"\n | b!!(ind (a!!1) (a!!2)) == \"\"\n = solve m n xs (ins (ind (a!!1) (a!!2)) (a!!3) b)\n | otherwise = case elemIndex \"\" b of\n Just c -> solve m n xs (ins c (a!!3) b)\n Nothing ->\"#\"\n where\n l = length b\n ind a b = (toInt a -1)*n + (toInt b-1)\nsolve _ _ [] _ = \"\""}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.map words.lines\n\nfunc::[[String]]->String\nfunc (a:xs) = solve'$solve m n xs (take (m*n)$repeat \"\")\n where\n b = map toInt a\n m = b!!0\n n = b!!1\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve' a = case elem '#' a of\n True -> \"\"\n False->a\n\nins a b c = (take a c) ++ [b] ++ (drop (a+1) c)\n\nsolve m n (a:xs) b | a!!0 == \"-1\" = case elemIndex (a!!1) (reverse b) of\n Just c -> (toString ((l-c-1)`div`n+1))++\" \"++\n (toString ((l-c-1)`mod`n+1))++\"\\n\"++\n solve m n xs (ins (l-c-1) \"\" b)\n Nothing ->\"-1 -1\\n\"++\n solve m n xs b\n | a!!3 `elem` b = \"#\"\n | b!!ind == \"\" = solve m n xs (ins ind (a!!3) b)\n | otherwise = case elemIndex \"\" (drop ind b) of\n Just c -> solve m n xs (ins c (a!!3) b)\n Nothing ->solve m n xs b\n where\n l = length b\n ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)\nsolve _ _ [] _ = \"\""}], "src_uid": "44d45a7e21418470bda396d91c65e736"} {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: Int -> [Int] -> Int\nsolve k li = let\n tar = length . map head . group $ li\n in if tar == 1\n then 1\n else if k == 1\n then -1\n else div (tar - 1 + k - 2) (k - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, k] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n print $ solve k a\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve k as\n\nsolve :: Integer -> [Integer] -> Integer\nsolve 1 as\n | all (== head as) as = 1\n | otherwise = -1\nsolve k as = max 1 $ (fromIntegral (length $ filter (/= 0) $ zipWith (-) (tail as) as) - 1) `div` (k - 1) + 1\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Set (fromList, size)\n\nsolve :: Int -> [Int] -> Int\nsolve k as = if s < 1 then 1 else rez\n where s = fromIntegral . subtract k . size $ fromList as\n k' = fromIntegral $ k - 1\n rez = if k' < 1 then -1 else 1 + (ceiling $ s / k')\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] $ \\_ -> do\n [n, k] <- pure . map read . words =<< getLine\n getLine >>= pure . map read . words >>= putStrLn . show . solve k \n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve k as\n\nsolve :: Integer -> [Integer] -> Integer\nsolve 1 as\n | all (== head as) as = 1\n | otherwise = -1\nsolve k as = max 1 $ (fromIntegral (length $ filter (/= 0) $ zipWith (-) (tail as) as) - 1) `div` k + 1\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve k as\n\nsolve :: Integer -> [Integer] -> Integer\nsolve 1 as\n | all (== head as) as = 1\n | otherwise = -1\nsolve k as = (fromIntegral (length $ filter (/= 0) $ zipWith (-) (tail as) as) - 1) `div` k + 1\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Set (fromList, size)\n\nsolve :: Int -> [Int] -> Int\nsolve k as = if k == 1 && s > 1 then -1 else ceiling $ s / (fromIntegral k)\n where s = fromIntegral . size $ fromList as\n\nmain :: IO ()\nmain = getLine >>= pure . read >>= \\t -> forM_ [1..t] $ \\_ -> do\n [n, k] <- pure . map read . words =<< getLine\n getLine >>= pure . map read . words >>= putStrLn . show . solve k\n \n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Set (fromList, size)\n\nsolve :: Int -> [Int] -> Int\nsolve k as = if s > 0 && k == 1 then -1 else 1 + (ceiling $ s / k')\n where s = fromIntegral . subtract k . size $ fromList as\n k' = fromIntegral $ k - 1\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] $ \\_ -> do\n [n, k] <- pure . map read . words =<< getLine\n getLine >>= pure . map read . words >>= putStrLn . show . solve k \n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Set (fromList, size)\n\nsolve :: Int -> [Int] -> Int\nsolve k as = if s > 0 && k == 1 then -1 else 1 + (ceiling (s / k'))\n where s = fromIntegral . subtract k . size $ fromList as\n k' = fromIntegral $ k - 1\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] $ \\_ -> do\n [n, k] <- pure . map read . words =<< getLine\n getLine >>= pure . map read . words >>= putStrLn . show . solve k \n"}], "src_uid": "3dc5850220458dec9876560150b612c4"} {"source_code": "import Data.List\nsolve a n = case findIndex (==n) a of\n Just i -> i:(map (+(i+1)) $ solve (drop (i+1) a) (n+1))\n Nothing -> []\n\nmain = do\n n <- fmap read getLine\n a <- fmap (map read . take n . words) getLine\n let res = solve a 1\n print (length res)\n putStrLn . unwords . map (show . (+2001)) $ res", "positive_code": [{"source_code": "main = interact solve\n\nsolve s = unlines [show $ length g, unwords g]\n where \n g = map show $ map snd $ reverse $ init r\n r = foldl (\\xs (k,y)->if k==1+(fst $ head xs) then (k,y):xs else xs) [(0,0)] $ zip (map (\\s -> read s :: Int) $ words $ last $ lines s) [2001..]"}, {"source_code": "\nsolve :: [Int] -> [Int]\nsolve as = solve' 1 (zip as [2001..])\n where\n solve' _ [] = []\n solve' k ((x,y):xs)\n | k == x = y : solve' (k+1) xs\n | otherwise = solve' k xs\n\nprints :: Show a => [a] -> IO ()\nprints xs = print (length xs) >> prints' xs\n where\n prints' [] = return ()\n prints' [x] = print x\n prints' (x:xs) = putStr (show x ++ \" \") >> prints' xs\n\nmain :: IO ()\nmain = do\n getLine\n as <- fmap (map read . words) getLine\n prints $ solve as\n"}], "negative_code": [], "src_uid": "499ddfd7e0563e3ca8c71219e408650f"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\n\n\nmain :: IO ()\nmain =\n do letters <- read <$> getLine :: IO Word64\n print $ query letters\n\nquery :: Word64 -> Word64\nquery letters = go 1 0 1\n where\n go :: Word64 -> Word64 -> Word64 -> Word64\n go !k !acc !fact\n | k > letters = if acc + fact >= n then acc + fact - n else acc + fact\n | otherwise = go (k+1)\n (mod ((acc+fact-1) * k) n)\n (mod (fact * k) n)\n \n\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\n\n\nmain :: IO ()\nmain =\n do letters <- read <$> getLine :: IO Word32\n print $ query letters\n\nquery :: Word32 -> Word32\nquery letters = fromMon $ go 1 rep1 0 1\n where\n rep1 = monRep 1\n go :: Word32 -> Montgomery -> Montgomery -> Montgomery -> Montgomery\n go !k !kRep !acc !fact\n | k > letters = acc + fact\n | otherwise = go (k+1) (kRep + rep1)\n ((acc+fact-rep1) * kRep) (fact * kRep)\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y)\n | xpy >= n = Mon $ xpy - n\n | otherwise = Mon $ xpy\n where\n xpy = x+y\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = fromIntegral $ if t >= n then t - n else t\n where t = (x + ((x*nprime) .&. mask32) * n) `shiftR` 32\n\n{-# INLINE mask32 #-}\nmask32 :: Word64\nmask32 = bit 32 - 1\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\n\n\nmain :: IO ()\nmain =\n do letters <- read <$> getLine :: IO Word32\n print $ query letters\n\nquery :: Word32 -> Word32\nquery letters = fromMon $ go 1 0 1\n where\n go :: Word32 -> Montgomery -> Montgomery -> Montgomery\n go !k !acc !fact\n | k > letters = acc + fact\n | otherwise = go (k+1) ((acc+fact-1) * kRep) newFact\n where\n kRep = monRep k\n newFact = kRep * fact\n\nn :: (Integral i) => i\nn = 998244353\n\nnprime :: Word64\nnprime = 998244351\n\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n (+) = monAdd\n (*) = monMult\n negate (Mon x) = Mon (n - x)\n fromInteger = monRep . fromInteger\n signum x | x == Mon 0 = Mon 0\n | otherwise = 1\n abs = id\n\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y)\n | xpy >= n = Mon $ xpy - n\n | otherwise = Mon $ xpy\n where\n xpy = x+y\n\nmonRep :: Word32 -> Montgomery\nmonRep = Mon . monRed . (rsq*) . fromIntegral\n\nfromMon :: Montgomery -> Word32\nfromMon = monRed . fromIntegral . unMon\n\nmonRed :: Word64 -> Word32\nmonRed x = fromIntegral $ if t >= n then t - n else t\n where t = (x + ((x*nprime) .&. mask32) * n) `shiftR` 32\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\n\n\nmain :: IO ()\nmain =\n do letters <- read <$> getLine :: IO Word32\n print $ query letters\n\nquery :: Word32 -> Word32\nquery letters = fromMon $ go 1 rep1 0 1\n where\n rep1 = monRep 1\n go :: Word32 -> Montgomery -> Montgomery -> Montgomery -> Montgomery\n go !k !kRep !acc !fact\n | k > letters = acc + fact\n | otherwise = go (k+1) (kRep + rep1)\n ((acc+fact-rep1) * kRep) (fact * kRep)\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y - if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (x + ((x*nprime) .&. mask32) * n) `shiftR` 32\n\n{-# INLINE mask32 #-}\nmask32 :: Word64\nmask32 = bit 32 - 1\n\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\nimport Data.Int\nimport Data.Ratio\nimport Data.Ix\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\ndata ModInt = ModInt Int64 deriving (Eq, Ord, Read)\n\nmodulo = 998244353 :: Int64\ntoModInt n = ModInt (n `mod` modulo)\nemi = error \"ModInt\"\nunaryOp f (ModInt x) = ModInt (f x)\nbinaryOp f (ModInt x) (ModInt y) = ModInt (f x y)\nbinaryOp' f (ModInt x) (ModInt y) = toModInt (f x y)\n\ninstance Bounded ModInt where\n maxBound = ModInt modulo\n minBound = ModInt (-modulo)\ninstance Enum ModInt where\n succ x\n | x /= maxBound = x + 1\n | otherwise = emi\n pred x\n | x /= minBound = x - 1\n | otherwise = emi\n toEnum i = toModInt (fromIntegral i)\n fromEnum (ModInt x) = (fromIntegral x)\ninstance Integral ModInt where\n quot = binaryOp quot\n rem = binaryOp rem\n div = binaryOp div\n mod = binaryOp mod\n quotRem (ModInt x) (ModInt y) = let (q, r) = x `quotRem` y in (ModInt q, ModInt r)\n divMod (ModInt x) (ModInt y) = let (d, m) = x `divMod` y in (ModInt d, ModInt m)\n toInteger (ModInt x) = toInteger x\ninstance Num ModInt where\n (+) = binaryOp' (+)\n (-) = binaryOp' (-)\n (*) = binaryOp' (*)\n negate = unaryOp negate\n abs = unaryOp abs\n signum = unaryOp signum\n fromInteger i = toModInt (fromInteger i)\ninstance Real ModInt where\n toRational (ModInt x) = toInteger x % 1\ninstance Show ModInt where\n show (ModInt x) = show x\ninstance Ix ModInt where\n range (ModInt m, ModInt n) = map ModInt [m..n]\n index (ModInt m, _) (ModInt i) = fromIntegral i - fromIntegral m\n inRange (ModInt m, ModInt n) (ModInt i) = m <= i && i <= n\n\n---- Answer Code Section ----\n\nprocess :: Int -> Int\nprocess (fromIntegral -> n :: ModInt) = if n == 1 then 1 else fromIntegral answer where\n facScans = scanl (*) n [ n-1, n-2 .. ] -- f(n) = [n, n(n-1), n(n-1)(n-2)..]\n foldFn s (k, fn, fn1) = s + k * (fn - fn1) -- S(n+1) = S(n) + k(f(n) - f(n-1))\n answer = foldl' foldFn 0 $ zip3 [1..n-1] facScans (0 : facScans)\n\nmain = do\n n <- getInt\n print $ process n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Integer] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nm :: Integer\nm = 998244353\n\nfacto :: Integer -> Integer\nfacto n = foldl (\\acc x -> (acc * x) `mod` m) 1 [1..n]\n\nrfacto :: Integer -> [Integer]\nrfacto n = scanl (\\acc x -> (acc * x) `mod` m) n [n-1,n-2..1]\n\nsolve n = (f * (n-1) `mod` m + m - msum) `mod` m\n where f = facto n\n r = rfacto n\n msum = foldl (\\acc x -> (acc + x) `mod` m) 0 $ take (fromIntegral $ n-2) r\n\nmain = do\n [n] <- getIntegers\n if n == 1 \n then print 1\n else print $ solve n"}, {"source_code": "solve n = m $ (n+1) * last p - sum p\n where m = (`mod` 998244353)\n p = scanl1 ((.) m . (*)) [n, n-1..1]\nmain = interact $ show . solve . read"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\n\n\nmain :: IO ()\nmain =\n do letters <- read <$> getLine :: IO Word64\n print $ query letters\n\nquery :: Word64 -> Word64\nquery letters = go 1 0 1\n where\n go :: Word64 -> Word64 -> Word64 -> Word64\n go !k !acc !fact\n | k > letters = acc + fact\n | otherwise = go (k+1)\n (mod ((acc+fact-1) * k) n)\n (mod (fact * k) n)\n \n\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\nimport Data.Int\nimport Data.Ratio\nimport Data.Ix\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\ndata ModInt = ModInt Int64 deriving (Eq, Ord, Read)\n\nmodulo = 998244353 :: Int64\ntoModInt n = ModInt (n `rem` modulo)\nemi = error \"ModInt\"\nunaryOp f (ModInt x) = ModInt (f x)\nbinaryOp f (ModInt x) (ModInt y) = ModInt (f x y)\nbinaryOp' f (ModInt x) (ModInt y) = toModInt (f x y)\n\ninstance Bounded ModInt where\n maxBound = ModInt modulo\n minBound = ModInt (-modulo)\ninstance Enum ModInt where\n succ x\n | x /= maxBound = x + 1\n | otherwise = emi\n pred x\n | x /= minBound = x - 1\n | otherwise = emi\n toEnum i = toModInt (fromIntegral i)\n fromEnum (ModInt x) = (fromIntegral x)\ninstance Integral ModInt where\n quot = binaryOp quot\n rem = binaryOp rem\n div = binaryOp div\n mod = binaryOp mod\n quotRem (ModInt x) (ModInt y) = let (q, r) = x `quotRem` y in (ModInt q, ModInt r)\n divMod (ModInt x) (ModInt y) = let (d, m) = x `divMod` y in (ModInt d, ModInt m)\n toInteger (ModInt x) = toInteger x\ninstance Num ModInt where\n (+) = binaryOp' (+)\n (-) = binaryOp' (-)\n (*) = binaryOp' (*)\n negate = unaryOp negate\n abs = unaryOp abs\n signum = unaryOp signum\n fromInteger i = toModInt (fromInteger i)\ninstance Real ModInt where\n toRational (ModInt x) = toInteger x % 1\ninstance Show ModInt where\n show (ModInt x) = show x\ninstance Ix ModInt where\n range (ModInt m, ModInt n) = map ModInt [m..n]\n index (ModInt m, _) (ModInt i) = fromIntegral i - fromIntegral m\n inRange (ModInt m, ModInt n) (ModInt i) = m <= i && i <= n\n\n---- Answer Code Section ----\n\nprocess :: Int -> Int\nprocess (fromIntegral -> n :: ModInt) = if n == 1 then 1 else fromIntegral answer where\n facScans = scanl (*) n [ n-1, n-2 .. ] -- f(n) = [n, n(n-1), n(n-1)(n-2)..]\n foldFn s (k, fn, fn1) = s + k * (fn - fn1) -- S(n+1) = S(n) + k(f(n) - f(n-1))\n answer = foldl foldFn 0 $ zip3 [1..n-1] facScans (0 : facScans)\n\nmain = do\n n <- getInt\n print $ process n\n"}], "src_uid": "9d4caff95ab182055f83c79dd88e599a"} {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\nsolve :: [(Integer, Integer)] -> Integer -> Maybe Integer\nsolve xs@((t, h):_) m = loop ((max `F.on` snd) first end) ([first] ++ xs ++ [end])\n where\n first = (1, t + h - 1)\n end = (m, m - t' + h') \n (t', h') = last xs\n\n\n-- loop acc xs \n-- | trace (show acc ++ \" \" ++ show (xs)) False = undefined\nloop acc [(t1, h1), (t2, h2)] =\n if abs (h2 - h1) <= t2 - t1 then Just acc else Nothing\nloop acc ((t1, h1):(xs@((t2, h2):_))) = \n if abs (h2 - h1) <= t2 - t1 \n then loop (maximum [h1, h2, acc, fff t1 t2 h1 h2]) xs\n else Nothing\n\nfff t1 t2 h1 h2 = (max h1 h2) + ((t2 - t1) - abs (h2 - h1)) `div` 2\n\nmain :: IO ()\nmain = do\n [n, m] <- map toInteger <$> getInts\n diary <- forM [1..m] $ \\_ -> do\n [a, b] <- getInts\n return (toInteger a, toInteger b)\n putStrLn $ case solve (L.sort diary) n of\n Nothing -> \"IMPOSSIBLE\"\n Just x -> show x\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nisOk (i0,h0) (i1,h1) | h1 < h0 = isOk (i0,h1) (i1,h0)\n | otherwise = (i1-i0) >= (h1-h0)\ngetMaxHeight (i0,h0) (i1,h1) | h1 < h0 = getMaxHeight (i0,h1) (i1,h0)\n | h0 < h1 = getMaxHeight (i0+d,h0+d) (i1,h1)\n | otherwise = h0 + (s `div` 2)\n where d = h1-h0\n s = i1-i0\n \nmapPair::(a -> a-> b)->[a] -> [b]\nmapPair f (a0:ts) | null ts = []\n | otherwise = ((f a0 a1):(mapPair f ts))\n where a1 = head ts\ngetMax1Height (i0,h0) = h0+i0-1\ngetMaxNHeight n (i0,h0) = h0+(n-i0) \nreadInput 0 = return []\nreadInput m = do\n w0 <- getLine\n let w = words w0\n next <- readInput (m-1)\n let h = (read (w !! 0)::Int,read (w !! 1)::Int)\n return (h:next)\ntoTup a = ((w !! 0),(w !! 1))\n where w = [read n::Int| n <-(words a)] \nmain = do\n w <- getLine\n let w0 = words w\n let n = read (w0 !! 0)::Int\n let m = read (w0 !! 1)::Int\n contents <- getContents\n let s = lines contents\n let route = map toTup s\n if not $ all id $ mapPair isOk route\n then putStrLn \"IMPOSSIBLE\"\n else do\n print $ maximum $ (getMax1Height (head route)):(getMaxNHeight n (last route)):(mapPair getMaxHeight route) \n \n"}], "negative_code": [{"source_code": "isOk (i0,h0) (i1,h1) | h1 < h0 = isOk (i0,h1) (i1,h0)\n | otherwise = (i1-i0) >= (h1-h0)\ngetMaxHeight (i0,h0) (i1,h1) | h1 < h0 = getMaxHeight (i0,h1) (i1,h0)\n | h0 > h1 = getMaxHeight (i0+d,h0+d) (i1,h1)\n | otherwise = h0 + (s `div` 2)\n where d = h1-h0\n s = i1-i0\nmapPair::(a -> a-> b)->[a] -> [b]\nmapPair f a | (length a) == 1 = []\n | otherwise = ((f a0 a1):(mapPair f ta))\n where a0 = head a\n ta = tail a\n a1 = head ta\ngetMax1Height (i0,h0) = h0+i0-1\ngetMaxNHeight n (i0,h0) = h0+(n-i0) \nreadInput 0 = return []\nreadInput m = do\n w0 <- getLine\n let w = words w0\n next <- readInput (m-1)\n let h = (read (w !! 0)::Int,read (w !! 1)::Int)\n return (h:next)\nmain = do\n w <- getLine\n let w0 = words w\n let n = read (w0 !! 0)::Int\n let m = read (w0 !! 1)::Int\n route <- readInput m\n if not $ all id $ mapPair isOk route\n then putStrLn \"IMPOSSIBLE\"\n else do\n print $ maximum $ (getMax1Height (head route)):(getMaxNHeight n (last route)):(mapPair getMaxHeight route)\n \n"}, {"source_code": "isOk (i0,h0) (i1,h1) | h1 < h0 = isOk (i0,h1) (i1,h0)\n | otherwise = (i1-i0) >= (h1-h0)\ngetMaxHeight (i0,h0) (i1,h1) | h1 < h0 = getMaxHeight (i0,h1) (i1,h0)\n | h0 > h1 = getMaxHeight (i0+d,h0+d) (i1,h1)\n | otherwise = h0 + (s `div` 2)\n where d = h1-h0\n s = i1-i0\nmapPair::(a -> a-> b)->[a] -> [b]\nmapPair f a | (length a) == 1 = []\n | otherwise = ((f a0 a1):(mapPair f ta))\n where a0 = head a\n ta = tail a\n a1 = head ta\ngetMax0Height (i0,h0) = h0+i0\ngetMaxNHeight n (i0,h0) = h0+(n-i0) \nreadInput 0 = return []\nreadInput m = do\n w0 <- getLine\n let w = words w0\n next <- readInput (m-1)\n let h = (read (w !! 0)::Int,read (w !! 1)::Int)\n return (h:next)\nmain = do\n w <- getLine\n let w0 = words w\n let n = read (w0 !! 0)::Int\n let m = read (w0 !! 1)::Int\n route <- readInput m\n if not $ all id $ mapPair isOk route\n then putStrLn \"IMPOSSIBLE\"\n else do\n print $ maximum $ (getMax0Height (head route)):(getMaxNHeight n (last route)):(mapPair getMaxHeight route)\n \n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\nsolve :: [(Integer, Integer)] -> Integer -> Maybe Integer\nsolve xs@((t, h):_) m = loop ((max `F.on` snd) first end) ([first] ++ xs ++ [end])\n where\n first = (0, t + h)\n end = (m - 1, m - 1 - t' + h') \n (t', h') = last xs\n\n\n-- loop acc xs \n-- | trace (show acc ++ \" \" ++ show (xs)) False = undefined\nloop acc [(t1, h1), (t2, h2)] =\n if abs (h2 - h1) <= t2 - t1 then Just acc else Nothing\nloop acc ((t1, h1):(xs@((t2, h2):_))) = \n if abs (h2 - h1) <= t2 - t1 \n then loop (maximum [h1, h2, acc, fff t1 t2 h1 h2]) xs\n else Nothing\n\nfff t1 t2 h1 h2 = (max h1 h2) + ((t2 - t1) - abs (h2 - h1)) `div` 2\n\nmain :: IO ()\nmain = do\n [n, m] <- map toInteger <$> getInts\n diary <- forM [1..m] $ \\_ -> do\n [a, b] <- getInts\n return (toInteger a, toInteger b)\n putStrLn $ case solve (L.sort diary) n of\n Nothing -> \"IMPOSSIBLE\"\n Just x -> show x\n"}], "src_uid": "77b5bed410d621fb56c2eaebccff5108"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nmodulo = 10 ^ 9 + 7\r\n\r\ntimer :: Int -> Int\r\ntimer 1 = 0\r\ntimer n = 1 + timer (n `div` 2)\r\n\r\nbpow :: Int -> Int -> Int -> Int -> Int\r\nbpow a b modu acc\r\n | b == 0 = acc\r\n | otherwise = bpow na nb modu nacc \r\n where na = a * a `mod` modu\r\n nb = b `div` 2\r\n nacc = if even b then acc else (acc * a) `mod` modu\r\n\r\nfastPow :: Int -> Int -> Int -> Int \r\nfastPow a b c = bpow a b c 1\r\n\r\nprocess :: Int -> Int -> Int -> Int -> Int \r\nprocess n k timer acc | k == 0 = acc | otherwise = process n nk (timer + 1) nacc\r\n where nk = div k 2\r\n nacc = if even k then acc else mod (acc + fastPow n timer modulo) modulo \r\n\r\nsolve = do\r\n a <- getLine\r\n let arr = words a\r\n n = read (head arr) :: Int \r\n k = read (last arr) :: Int\r\n print(process n k 0 0 )\r\n\r\nmain = do\r\n entry <- getLine \r\n let timer = read entry :: Int\r\n forM_ [1..timer] $ \\_ -> do\r\n solve", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu -- Lazy.Builder deprecated\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport Data.Bits\r\nimport Data.List (unfoldr)\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n\r\ndata Input = Input {nk :: [Int]}\r\ndata Output = Output Int deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input [n,k]) = let\r\n powers = 1 : map (mult n) powers\r\n ks = k : map (flip shiftR 1) ks \r\n lsbs = (`mod` 2) <$> ks\r\n prime = 1000000007 \r\n long x = fromIntegral x :: Integer\r\n short x = fromIntegral x :: Int \r\n mult a b = short $ (long a * long b) `mod` (long prime)\r\n add a b = short $ (long a + long b) `mod` (long prime)\r\n in\r\n Output $ foldr1 add $ zipWith const (zipWith mult powers lsbs) (takeWhile (/=0) ks)\r\n\r\n\r\n-- gives a State(T) monad which when run gives Input \r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n,k] <- getIntegrals 2\r\n return $ Input [n,k]\r\n \r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output n) = dec n <> nl\r\n --go (Yes l xs) = mconcat $ (<>nl) <$> [str \"Yes\", dec l, (mconcat $ fmap ((<> sp).dec) xs)]\r\n\r\n\r\ndoTestcase :: StateT [B8.ByteString] Identity Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x \r\n\r\ngetIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn\r\n\r\nimplicit :: St [Int]\r\nimplicit = return [1]\r\nexplicit :: St [Int]\r\nexplicit = getIntegrals 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n ~[nTc] <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\nbound :: Int64\nbound = 1000000007\n\ncalc1 :: Int64->Int64->Int64->Int64->Int64\ncalc1 _ 0 _ acc = acc\ncalc1 n k p acc | k `mod` 2 == 1\n = calc1 n (k `div` 2) ((p*n) `mod` bound) ((p+acc) `mod` bound)\ncalc1 n k p acc\n = calc1 n (k `div` 2) ((p*n) `mod` bound) acc\n\ncalc :: Int64->Int64->Int64\ncalc n k =\n calc1 n k 1 0\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,k] = map read $ words line\n print $ calc n k\n"}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t (map read . words <$> getLine) :: IO [[Integer]]\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve [n, k] = show $ fromBin n . toBin $ k\r\nsolve _ = error \"bad TC\"\r\n\r\ntoBin 0 = []\r\ntoBin n = (n `mod` 2) : toBin (n `div` 2)\r\n\r\nfromBin n bits = (`mod` theMod) . sum . zipWith (*) bits $ (iterate (*n) 1)\r\n\r\ntheMod = 10^(9::Int) + 7\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\nimport Control.Arrow ((>>>))\nimport Control.Monad as M (guard, liftM, liftM3,\n replicateM, replicateM_, when, ap)\nimport qualified Control.Monad.ST as ST\nimport qualified Control.Monad.Trans as MS\nimport Control.Monad.Trans.Maybe (MaybeT (runMaybeT))\nimport qualified Data.Array as A (elems)\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray as MA\nimport qualified Data.Array.ST as STA\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Foldable as F\nimport Data.Functor ((<&>))\nimport Data.Int (Int64)\nimport Data.Ix (Ix (range))\nimport Data.List (sort)\nimport Data.Maybe (fromJust, isJust)\nimport Data.Ratio (denominator, numerator)\nimport qualified Data.Traversable as T\nimport Data.Word (Word32)\nimport Debug.Trace as D\nimport System.IO\nimport Text.Printf (printf)\n\n\nreadInt :: B8.ByteString -> Int\nreadInt = B8.readInt >>> fromJust >>> fst\n\nreadInt64 :: B8.ByteString -> Int64\nreadInt64 = B8.readInteger >>> fromJust >>> fst >>> fromInteger\n\nupdateArray :: (MA.MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nupdateArray arr i func =\n MA.readArray arr i >>=\n MA.writeArray arr i <$> func\n\n\nnewtype Md109_7 a = Md109_7 a\n deriving (Functor, Show)\n\nfromMd109_7 (Md109_7 a) = a\n\nmd109_7 :: (Num a) => a\nmd109_7 = fromInteger $ 10^9 + 7\n\ninstance (Num a, Ord a, Integral a) => Num (Md109_7 a) where\n (+) aa@(Md109_7 a) bb@(Md109_7 b)\n | a + b >= 2 * md109_7 = Md109_7 $ (a + b) `mod` md109_7\n | a + b >= md109_7 = Md109_7 $ a + b - md109_7\n | a + b < 0 = (-aa) + (-bb)\n | otherwise = Md109_7 $ a + b\n\n (*) (Md109_7 a) (Md109_7 b)\n | a == 0 || b == 0 = Md109_7 0\n | otherwise = Md109_7 $ a * b `mod` md109_7\n\n abs = id\n\n signum (Md109_7 a)\n | a > 0 = Md109_7 1\n | otherwise = Md109_7 0\n\n fromInteger x\n | x >= 2 * md109_7 = Md109_7 $ (fromInteger x :: a) `mod` md109_7\n | x >= md109_7 = Md109_7 $ (fromInteger x :: a) - md109_7\n | x < 0 = negate $ fromInteger (-x)\n | otherwise = Md109_7 $ fromInteger x\n\n negate (Md109_7 a)\n | a > 0 = Md109_7 $ md109_7 - a\n | otherwise = Md109_7 0\n\nbinPower :: (Num a, Ord a, Integral a, Integral b) => Md109_7 a -> b -> Md109_7 a\nbinPower a b\n | b == 0 = fromInteger $ (1:: Integer)\n | even b = let !v = binPower a (b `div` 2) in v * v\n | otherwise = a * binPower a (b - 1)\n\ninstance (Num a, Ord a, Integral a) => Fractional (Md109_7 a) where\n recip x = binPower x (md109_7 - 2)\n fromRational x = fromInteger (numerator x) * recip (fromInteger $ denominator x)\n\n\nsolve :: Int64 -> Int64 -> Int64\nsolve n k = fromMd109_7 $ solve' 32 k\n where\n nMd = Md109_7 n\n\n solve' :: Int64 -> Int64 -> Md109_7 Int64 \n solve' index k\n | index == -1 = Md109_7 0\n | k >= 2 ^ index = (nMd `binPower` index) + solve' (index - 1) (k - 2 ^ index)\n | otherwise = solve' (index - 1) k\n\n\n\nmain :: IO ()\nmain = do\n test <- B8.getLine <&> readInt\n replicateM_ test $ do\n [n, k] <- B8.getLine <&> B8.words <&> map readInt64\n let answer = solve n k\n printf \"%lld\\n\" answer\n"}, {"source_code": "import Control.Monad\r\n\r\nmodp = 10^9 + 7\r\n\r\n_bp :: Int -> Int -> Int -> Int -> Int\r\n_bp a b p res\r\n | b == 0 = res\r\n | otherwise = _bp newa newb p newres\r\n where newa = a * a `mod` p\r\n newb = if even b then b `div` 2 else (b - 1) `div` 2\r\n newres = if even b then res else (res * a) `mod` p\r\n\r\nbp :: Int -> Int -> Int\r\nbp a b = _bp a b modp 1\r\n\r\ncal :: Int -> Int -> Int -> Int -> Int\r\ncal n k res cur\r\n | k == 0 = res\r\n | otherwise = cal n newk newres (cur + 1)\r\n where newk = if even k then k `div` 2 else (k - 1) `div` 2\r\n newres = if even k then res else (res + bp n cur) `mod` modp\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- map read.words <$> getLine :: IO [Int]\r\n print(cal n k 0 0)\r\n\r\nmain = do \r\n line <- getLine \r\n let tc = read line :: Int\r\n forM_ [1..tc] $ \\_ -> do\r\n solve"}, {"source_code": "import Control.Monad\r\n_bp :: Int -> Int -> Int -> Int -> Int\r\n_bp a b p res\r\n | b == 0 = res\r\n | otherwise = _bp newa newb p newres\r\n where newa = a * a `mod` p\r\n newb = if even b then b `div` 2 else (b - 1) `div` 2\r\n newres = if even b then res else (res * a) `mod` p\r\n\r\nbp :: Int -> Int -> Int\r\nbp a b = _bp a b 1000000007 1\r\n\r\ncal :: Int -> Int -> Int -> Int -> Int\r\ncal n k res cur\r\n | k == 0 = res\r\n | otherwise = cal n newk newres (cur + 1)\r\n where newk = if even k then k `div` 2 else (k - 1) `div` 2\r\n newres = if even k then res else (res + bp n cur) `mod` 1000000007\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- map read.words <$> getLine :: IO [Int]\r\n print(cal n k 0 0)\r\n\r\nmain = do \r\n line <- getLine \r\n let tc = read line :: Int\r\n forM_ [1..tc] $ \\_ -> do\r\n solve"}, {"source_code": "import Control.Monad\r\nimport Data.Int ( Int64 )\r\n_bp :: Int64 -> Int64 -> Int64 -> Int64 -> Int64\r\n_bp a b p res\r\n | b == 0 = res\r\n | otherwise = _bp newa newb p newres\r\n where newa = a * a `mod` p\r\n newb = if even b then b `div` 2 else (b - 1) `div` 2\r\n newres = if even b then res else (res * a) `mod` p\r\n\r\nbp :: Int64 -> Int64 -> Int64\r\nbp a b = _bp a b 1000000007 1\r\n\r\ncal :: Int64 -> Int64 -> Int64 -> Int64 -> Int64\r\ncal n k res cur\r\n | k == 0 = res\r\n | otherwise = cal n newk newres (cur + 1)\r\n where newk = if even k then k `div` 2 else (k - 1) `div` 2\r\n newres = if even k then res else (res + bp n cur) `mod` 1000000007\r\n\r\nsolve = do\r\n [n, k] <- map read.words <$> getLine :: IO [Int64]\r\n print(cal n k 0 0)\r\n\r\nmain = do \r\n line <- getLine \r\n let tc = read line :: Int64\r\n forM_ [1..tc] $ \\_ -> do\r\n solve"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu -- Lazy.Builder deprecated\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport Data.Bits\r\nimport Data.List (unfoldr)\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\ndata Input = Input {nk :: [Int]}\r\ndata Output = Output Int deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input [n,k]) = let\r\n powers = 1 : map (mult n) powers\r\n ks = k : map (flip shiftR 1) ks\r\n lsbs = (`mod` 2) <$> ks\r\n prime = 1000000007 :: Int\r\n mult a b = (a*b) `mod` prime\r\n add a b = (a+b) `mod` prime\r\n in\r\n Output $ foldr1 add $ zipWith const (zipWith mult powers lsbs) (takeWhile (/=0) ks)\r\n\r\n\r\n-- gives a State(T) monad which when run gives Input \r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n,k] <- getIntegrals 2\r\n return $ Input [n,k]\r\n \r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output n) = dec n <> nl\r\n\r\n\r\ndoTestcase :: StateT [B8.ByteString] Identity Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x \r\n\r\ngetIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn\r\n\r\nimplicit :: St [Int]\r\nimplicit = return [1]\r\nexplicit :: St [Int]\r\nexplicit = getIntegrals 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n ~[nTc] <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu -- Lazy.Builder deprecated\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport Data.Bits\r\nimport Data.List (unfoldr)\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = implicit\r\n\r\ndata Input = Input {nk :: [Int]}\r\ndata Output = Output Int deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input [n,k]) = let\r\n powers = 1 : map (mult n) powers\r\n ks = k : map (flip shiftR 1) ks\r\n lsbs = (`mod` 2) <$> ks\r\n prime = 1000000007 :: Int\r\n mult a b = (a*b) `mod` prime\r\n add a b = (a+b) `mod` prime\r\n in\r\n Output $ foldr1 add $ zipWith const (zipWith mult powers lsbs) (takeWhile (/=0) ks)\r\n\r\n\r\n-- gives a State(T) monad which when run gives Input \r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n,k] <- getIntegrals 2\r\n return $ Input [n,k]\r\n \r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output n) = dec n <> nl\r\n\r\n\r\ndoTestcase :: StateT [B8.ByteString] Identity Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x \r\n\r\ngetIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn\r\n\r\nimplicit :: St [Int]\r\nimplicit = return [1]\r\nexplicit :: St [Int]\r\nexplicit = getIntegrals 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n ~[nTc] <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nmodulo = 10 ^ 9 + 7\r\n\r\ntimer :: Int -> Int\r\ntimer 1 = 0\r\ntimer n = 1 + timer (n `div` 2)\r\n\r\nbpow :: Int -> Int -> Int -> Int -> Int\r\nbpow a b modu acc\r\n | b == 0 = acc\r\n | otherwise = bpow na nb modu nacc \r\n where na = a * a `mod` modu\r\n nb = b `div` 2\r\n nacc = if even b then acc else (acc * a) `mod` modu\r\n\r\nfastPow :: Int -> Int -> Int -> Int \r\nfastPow a b c = bpow a b c 1\r\n\r\nprocess :: Int -> Int -> Int \r\nprocess n 0 = 0\r\nprocess n k = (fastPow n (timer (k .&. (-k))) modulo) + process n (k - (k .&. (-k))) `mod` modulo\r\n\r\nsolve = do\r\n a <- getLine\r\n let arr = words a\r\n n = read (head arr) :: Int \r\n k = read (last arr) :: Int\r\n print(process n k)\r\n\r\nmain = do\r\n entry <- getLine \r\n let timer = read entry :: Int\r\n forM_ [1..timer] $ \\_ -> do\r\n solve"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nmodulo = 10 ^ 9 + 7\r\n\r\ntimer :: Int -> Int\r\ntimer 1 = 0\r\ntimer n = 1 + timer (n `div` 2)\r\n\r\nfastPow :: Int -> Int -> Int -> Int\r\nfastPow _ 0 _ = 1\r\nfastPow base 1 modp = mod base modp\r\nfastPow base pow modp | even pow = mod ((fastPow base (div pow 2) modp) ^ 2) modp\r\n | odd pow = mod ((fastPow base (div (pow-1) 2) modp) ^ 2 * base) modp\r\n\r\nprocess :: Int -> Int -> Int \r\nprocess n 0 = 0\r\nprocess n k = mod ((fastPow n (timer (k .&. (-k))) modulo) + process n (k - (k .&. (-k)))) modulo\r\n\r\nsolve = do\r\n a <- getLine\r\n let arr = words a\r\n n = read (head arr) :: Int \r\n k = read (last arr) :: Int\r\n print(process n k)\r\n\r\nmain = do\r\n entry <- getLine \r\n let timer = read entry :: Int\r\n forM_ [1..timer] $ \\_ -> do\r\n solve"}, {"source_code": "import Control.Monad\nimport Data.List\n\nbound = 1000000007\n\ncalc1 :: Int->Int->Int->Int->Int\ncalc1 _ 0 _ acc = acc\ncalc1 n k p acc | k `mod` 2 == 1\n = calc1 n (k `div` 2) ((p*n) `mod` bound) ((p+acc) `mod` bound)\ncalc1 n k p acc\n = calc1 n (k `div` 2) ((p*n) `mod` bound) acc\n\ncalc :: Int->Int->Int\ncalc n k =\n calc1 n k 1 0\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,k] = map read $ words line\n print $ calc n k\n"}], "src_uid": "2cc35227174e6a4d48e0839cba211724"} {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> case numBuses n of\n Just (n1, n2) -> putStrLn (show n1 ++ \" \" ++ show n2)\n Nothing -> putStrLn \"-1\"\nnumBuses :: Int -> Maybe (Int, Int)\nnumBuses n | n `mod` 2 == 1 = Nothing\n | otherwise = case (numMin n, numMax n) of\n (Just m1, Just m2) -> Just (m1, m2)\n _ -> Nothing\n\nnumMax :: Int -> Maybe Int\nnumMax n | n `mod` 4 == 0 = Just $ n `div` 4\n | n == 2 = Nothing\n | n > 0 = Just $ (div n 4) -- one less 4 wheeler, one more 6 wheeler\n\nnumMin :: Int -> Maybe Int\nnumMin n | n `mod` 6 == 0 = Just $ div n 6\n | n `mod` 6 == 2 = Just $ 1 + div n 6 -- one less 6, two more 4\n | n `mod` 6 == 4 = Just $ 1 + div n 6 -- one more 4\n", "positive_code": [{"source_code": "main :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\treturn ()\r\n\t\r\nsolve :: Int -> Int -> IO ()\r\nsolve number 0 = return ()\t\r\nsolve number current = \tdo\r\n\t\t\t\tline <- getLine\r\n\t\t\t\tlet bruh = read line :: Integer\r\n\t\t\t\tlet m = minim bruh\r\n\t\t\t\tlet ma = maxim bruh\r\n\t\t\t\tif m == -1 then\r\n\t\t\t\t\tputStrLn \"-1\"\r\n\t\t\t\telse putStrLn $ (show m) ++ \" \" ++ (show ma)\r\n\t\t\t\tsolve number (current - 1)\r\n\t\t\t\t\r\nminim :: Integer -> Integer\r\nminim n | (n < 4) || ((mod n 2) /= 0) = -1\r\n\t\t | otherwise = let\r\n\t\t\t\t\t\t\tk = div n 6\r\n\t\t\t\t\t\t\tost = mod n 6\r\n\t\t\t\t\t\t\tin if ost /= 0 then k + 1 else k\r\n\r\nmaxim :: Integer -> Integer\t\t\t\t\r\nmaxim n | (n < 4) || ((mod n 2) /= 0) = -1\r\n\t\t| otherwise = div n 4"}, {"source_code": "import Control.Monad\r\n\r\nroutine :: IO ()\r\nroutine = do\r\n n <- read <$> getLine\r\n\r\n case solve n of\r\n Just (a,b) -> putStrLn $ show a ++ \" \"++ show b\r\n _ -> putStrLn \"-1\"\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n routine\r\n\r\nsolve :: Integer -> Maybe (Integer, Integer)\r\nsolve n\r\n |n < 4 = Nothing\r\n |n `mod` 2 == 1 = Nothing\r\n |otherwise = Just ((n+5) `div` 6,n `div` 4)\r\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nsolve :: Integer -> String\r\nsolve n =\r\n if n == 2 || n `mod` 2 == 1\r\n then \"-1\"\r\n else\r\n show\r\n ( m `div` 3 + (if n `mod` 3 /= 0 then 1 else 0)\r\n )\r\n ++ \" \"\r\n ++ show (m `div` 2)\r\n where\r\n m = n `div` 2\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map read\r\n >>> map solve\r\n >>> unlines"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\n\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nsolve :: Int64 -> Maybe (Int64, Int64)\nsolve x\n | (x < 4) || odd x = Nothing\n | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)\n where \n n = x `div` 2\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ \\_ -> do\n x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger\n let answer = solve x\n case answer of\n Just (minN, maxN) -> printf \"%lld %lld\" minN maxN\n Nothing -> printf \"-1\"\n printf \"\\n\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\n\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nsolve :: Int64 -> Maybe (Int64, Int64)\nsolve x\n | (x < 4) || odd x = Nothing\n | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)\n where \n n = x `div` 2\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ \\_ -> do\n x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger\n let answer = solve x\n case answer of\n Just (minN, maxN) -> printf \"%lld %lld\\n\" minN maxN\n Nothing -> puts \"-1\"\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\n\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nsolve :: Int64 -> Maybe (Int64, Int64)\nsolve x\n | (x < 4) || odd x = Nothing\n | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)\n where \n n = x `div` 2\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger\n let answer = solve x\n case answer of\n Just (minN, maxN) -> printf \"%lld %lld\\n\" minN maxN\n Nothing -> puts \"-1\"\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\n\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nsolve :: Int64 -> Maybe (Int64, Int64)\nsolve x\n | (x < 4) || odd x = Nothing\n | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)\n where \n n = x `div` 2\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger\n let answer = solve x\n case answer of\n Just (minN, maxN) -> printf \"%lld %lld\\n\" minN maxN\n Nothing -> puts \"\"\n"}], "src_uid": "1cc628b4e03c8b8e0c5086dc4e0e3254"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Bits\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n getLine\n a <- getIntList\n printList $ f a 0\n\nf :: [Int] -> Int -> [Int]\nf [x] z = [z]\nf (x:y:xs) z =\n let t = x `xor` z\n r = y `xor` (t .|. y)\n in z : f (y:xs) r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Bits ((.&.), xor, complement)\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve (x : xs) = map snd $ scanl next (x, 0) xs where\r\n next (xprev, yprev) x = let y = (xprev `xor` yprev) .&. complement x in (x, y)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n getLine \r\n xs <- map read . words <$> getLine \r\n putStrLn $ unwords $ map show $ solve xs"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bits ((.&.), xor)\n\ndropCounts :: [a] -> [a]\ndropCounts [] = []\ndropCounts [_] = error \"Odd number of elements!\"\ndropCounts (_:x:xs) = x : dropCounts xs\n\nparseInt :: String -> Int\nparseInt = read\n\nsolve :: [Int] -> [Int]\nsolve = aux [0]\n where\n aux :: [Int] -> [Int] -> [Int]\n aux res [_] = reverse res\n aux res (x:xs) = let y = (x `xor` head xs) .&. x\n in aux (y : res) (head xs `xor` y : tail xs)\n\nmain :: IO ()\nmain = interact $ lines >>> tail >>> dropCounts >>> map (words >>> map parseInt >>> solve >>> map show >>> unwords) >>> unlines"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\nimport Data.Bits ((.&.), Bits (xor))\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n lines >>> drop 1 >>> chunksOf 2 >>>\r\n map (last >>> words >>> map read >>> solve >>> map show >>> unwords)\r\n >>> unlines\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve = reverse . snd . foldl upd (0, [])\r\n where\r\n upd (x, ys) x' = let e = x - (x .&. x') in (x' `xor` e, e : ys)\r\n"}], "negative_code": [], "src_uid": "8d25700c9996a80fea3557222273c89a"} {"source_code": "import Data.List\n\nmain = getContents >>= print . solve . tail . words\n\nsolve = length . nub . map (map head . group . sort)\n", "positive_code": [{"source_code": "import Data.List\n\nsg :: Ord a => [a] -> [[a]]\nsg = group . sort\n\n-- unique :: Ord a => [a] -> [a]\nunique a = map head $ sg a\n\nmain :: IO ()\nmain = do\n sN <- getLine\n sC <- getLine\n let c = words sC\n let cc = map unique c\n let ccc = unique cc\n print $ length ccc"}, {"source_code": "import Control.Applicative\nimport Data.List (sort, nub)\n\n\nmain = do\n _ <- getLine\n xs <- words <$> getLine :: IO [String]\n print $ length $ nub $ map (sort . nub) xs"}], "negative_code": [], "src_uid": "cf1eb164c4c970fd398ef9e98b4c07b1"} {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n-- Meat\nsolve :: [Double] -> [[Double]] -> Double\nsolve [ox, oy] = minimum. (1000000000:) . fmap (dist ox oy)\nsolve _ = error \"sucker\"\n\ndist :: Double -> Double -> [Double] -> Double\ndist ox oy [ax,ay,v] = sqrt ((ax - ox)**2 + (ay - oy) ** 2) / v\ndist _ _ _= error \"sucker\"\n\n-- Shit\nmain :: IO ()\nmain = do\n (o:_:xs) <- readShit\n printShit [[solve o xs]]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\ngetInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ a, b ] :: [ Double ] <- map read . words <$> getLine\n\tn <- readInt\n\t[ xs, ys, vs ] :: [[ Double ]] <- transpose <$> ( replicateM n $ map read . words <$> getLine )\n\tprintf \"%.9f\\n\" $ minimum $ flip ( zipWith (/) ) vs $ zipWith ( \\x y -> sqrt ( ( x - a ) ** 2 + ( y - b ) ** 2 ) ) xs ys\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nreadL :: (Read a) => IO [a]\nreadL = fmap (map read . words) getLine\n\nreadI :: IO [Int]\nreadI = readL\nreadD :: IO [Double]\n\nreadD = readL\n\nmain = do\n [a,b] <- readL\n [n] <- readL \n crds <- replicateM n readL\n putStrLn $ show $ minimum $ map (\\[x,y,v] -> sqrt ((x-a)^2 + (y-b)^2) / v) crds"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nreadL :: (Read a) => IO [a]\nreadL = fmap (map read . words) getLine\n\nmain = do\n [a,b] <- readL :: IO [Double]\n [n] <- readL :: IO [Int]\n crds <- replicateM n (readL :: IO [Double])\n putStrLn $ show $ minimum $ map (\\[x,y,v] -> sqrt ((x-a)^2 + (y-b)^2) / v) crds"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n startText <- getLine\n let\n start = convert (readSplit startText) where\n convert :: [Int] -> (Int, Int)\n convert [a, b] = (a, b)\n nText <- getLine\n let n = read nText :: Int\n taxisText <- replicateM n getLine\n let\n taxis = map convert' (map readSplit taxisText) where\n convert' :: [Int] -> ( (Int, Int), Int )\n convert' [a, b, c] = ( (a, b), c )\n taxiStart = map fst taxis\n taxiSpeed = map snd taxis\n putStrLn (show (minTime start taxiStart taxiSpeed))\n\nminTime :: (Int, Int) -> [(Int, Int)] -> [Int] -> Double\nminTime _ [] [] = 0.0\nminTime start (x:xs) (v:vs) = minTime' (time start x v) start xs vs where\n minTime' :: Double -> (Int, Int) -> [(Int, Int)] -> [Int] -> Double\n minTime' minT _ [] [] = minT\n minTime' minT start (x:xs) (v:vs)\n | curT < minT = minTime' curT start xs vs\n | otherwise = minTime' minT start xs vs\n where curT = time start x v\n\ntime :: (Int, Int) -> (Int, Int) -> Int -> Double\ntime start taxi speed = (hypot start taxi) / (fromIntegral speed) where\n hypot :: (Int, Int) -> (Int, Int) -> Double\n hypot (x1, y1) (x2, y2) = sqrt (fromIntegral ((x1-x2)^2 + (y1-y2)^2))\n\nreadSplit :: String -> [Int]\nreadSplit text = map read (words text) :: [Int]\n\n"}, {"source_code": "main = do\n [x,y] <- fmap ((map read) . words) getLine :: IO [Int]\n n <- readLn :: IO Int\n ls <- flip mapM [1..n] $ \\i -> do\n [p,q,v] <- fmap ((map read) . words) getLine :: IO [Int]\n let dist = sqrt . fromIntegral $ (x-p)^2 + (y-q)^2 :: Float\n time = dist / (fromIntegral v)\n return time\n print . minimum $ ls"}, {"source_code": "import Control.Monad (replicateM)\n\nmain = do\n [x, y] <- fmap (map read . words) getLine\n [n] <- fmap (map read . words) getLine\n ps <- replicateM n (fmap (map read . words) getLine) :: IO [[Int]]\n\n let\n f :: [Int] -> Double\n f [xx, yy, v] = (sqrt (fromIntegral ((xx-x)^2 + (yy-y)^2))) / fromIntegral (v)\n\n print $ minimum $ map f ps\n\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInteger x\nsomeFunc::IO()\nsomeFunc = forM [1..2]( \\is ->map rIn.C.words <$>C.getLine)>>=(\\[[a,b],[n]]->solve.([a,b]:)=<

map rIn.C.words <$>C.getLine) )\nsolve ([a,b]:xs) = print $ minimum $ map (\\ [x,y,v]->sqrt (fromIntegral ((x-a)^2 +(y-b)^2))/fromIntegral v) xs\n"}, {"source_code": "import Control.Applicative\n\n\nprocess a b x = minimum t\n where t = map (ti a b ) x\n ti a b [c,d,v] = (/(fromIntegral v)) $ sqrt $ fromIntegral $ (c-a)^2 + (d-b)^2\n\n\nmain::IO ()\nmain=do\n [a,b]<- map read <$> words <$> getLine ::IO [Int]\n getLine\n x<- map (map read)<$> map words <$> lines <$> getContents ::IO [[Int]]\n print $ process a b x\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b] <- map read . words <$> getLine\n n <- readLn\n ts <- replicateM n (map read . words <$> getLine)\n let d [x,y,v] = sqrt((a-x)^2 + (b-y)^2) / v\n print $ minimum $ map d ts\n"}, {"source_code": "import Control.Applicative\n\ntimeTaken :: Int -> Int -> Int -> Double\ntimeTaken x y v = (sqrt . fromIntegral $ x*x + y*y) / (fromIntegral v)\n\nmain :: IO ()\nmain = do\n [a,b] <- map read . words <$> getLine\n n <- read <$> getLine\n vals <- mapM (\\_ -> map read . words <$> getLine) [1..n]\n let xs = map (\\[x,y,v] -> timeTaken (x-a) (y-b) v) vals\n putStrLn . show . minimum $ xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain = do\n [a, b] <- map (read :: String -> Double) . words <$> getLine\n _ <- getLine\n ls <- map (map (read:: String -> Double) . words). lines <$> getContents\n printf \"%.10f\\n\" $ minimum $ map (\\[x, y, v] -> ((x - a)**2 + (y - b)**2)**0.5 / v) ls\n "}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n data Coordinat = Coordinat { x :: Int, y :: Int } deriving (Show, Eq)\n data Taxi = Taxi { coordinat :: Coordinat, speed :: Int } deriving (Show, Eq)\n\n mkTaxi :: String -> Taxi\n mkTaxi s =\n let [xi, yi, vi] = map readInt $ words s\n in Taxi (Coordinat xi yi) vi\n\n mkCoordinat :: [Int] -> Coordinat\n mkCoordinat [x,y] = Coordinat x y\n\n distance :: Floating a => Coordinat -> Coordinat -> a\n distance (Coordinat p q) (Coordinat x y) =\n let dx = fromIntegral $ p - x\n dy = fromIntegral $ q - y\n in (sqrt $ dx * dx + dy * dy)\n\n timeToArrive :: Floating a => Coordinat -> Taxi -> a\n timeToArrive co1@(Coordinat _ _) (Taxi co2@(Coordinat _ _) v) = (distance co1 co2) / (fromIntegral v)\n\n main :: IO()\n main = do\n [x,y] <- getLine >>= return . (map readInt) . words\n n <- getLine >>= return . readInt\n taxis <- readMultilineInput n $ return . mkTaxi\n putStrLn $ show $ minimum $ map (timeToArrive (Coordinat x y)) taxis\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype I = Double\n\nmain :: IO ()\nmain = do\n [a,b] <- map readi . words <$> getLine\n n <- read <$> getLine\n cs <- map (toTriple . map readi . words) <$> replicateM n getLine\n print $ solve a b cs\n\nsolve :: I -> I -> [(I,I,I)] -> I\nsolve a b cs = minimum $ map (time a b) cs where\n time a b (x,y,v) = sqrt ((abs (a-x))^2 + (abs (b-y))^2) / v\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\nreadi :: String -> I\nreadi = read\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] = (x, y, z)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Prelude\nimport Text.Printf\n\ntype Car = (Double, Double, Double)\n\ngetTime:: Double -> Double -> Car -> Double\ngetTime x1 y1 (x2, y2, v) = len / v\n where dx = x1 - x2\n dy = y1 - y2\n len = sqrt (dx * dx + dy * dy)\n\nsolve :: Double -> Double -> [Car] -> Double\nsolve x y cars = minimum (map (getTime x y) cars)\n\nmain = do\n [x, y] <- liftM (map read . words) getLine\n n <- liftM read getLine\n cars <- replicateM n $ do\n [a, b, v] <- liftM (map read . words) getLine\n return (a, b, v)\n printf \"%.10f\\n\" (solve x y cars)\n"}, {"source_code": "dist :: (Int, Int) -> (Int, Int) -> Double\ndist (a, b) (c, d) = sqrt. fromIntegral $ x^2 + y^2\n where x = a - c\n y = b - d\n\ngo :: Int -> (Int, Int) -> IO Double\ngo 0 v = return 1e18\ngo n v = do\n [c, d, s] <- getLine >>= return. map read. words :: IO [Int]\n next <- go (n - 1) v\n return. min (dist v (c, d) / fromIntegral s) $ next\n \n\nmain = do\n [a, b] <- getLine >>= return. map read. words :: IO [Int]\n n <- readLn :: IO Int\n (go n (a, b)) >>= print\n\n"}, {"source_code": "import Control.Monad\n\ndist (x1,y1) (x2,y2) = sqrt $ (x1 - x2)^2 + (y1 - y2)^2\n\nmain :: IO ()\nmain = do\n [a, b] <- map (read :: String -> Double) . words <$> getLine \n n <- (read :: String -> Int) <$> getLine \n print =<< minimum . map ((\\[x,y,v]-> dist (a,b) (x,y) / v) . map (read :: String -> Double) . words) <$> replicateM n getLine\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\nbtoi :: B.ByteString -> Int\nbtoi = fst . fromJust . B.readInt\n\nprocess_case :: Int -> Int -> [(Int, Int, Int)] -> Double\nprocess_case a b = minimum . map distance_to\n where\n distance_to :: (Int, Int, Int) -> Double\n distance_to (x, y, v) = (sqrt . fromIntegral $ ((x - a)^2 + (y - b)^2)) / (fromIntegral v)\n\nprocess :: B.ByteString -> B.ByteString\nprocess str =\n let (a:b:n:rest) = map btoi $ B.words str\n taxis = triple n rest\n triple :: Int -> [Int] -> [(Int, Int, Int)]\n triple 0 _ = []\n triple n (a:b:c:rest) = (a,b,c):(triple (n-1) rest)\n in B.pack . show $ process_case a b taxis\n\nmain :: IO ()\nmain = B.interact process"}], "negative_code": [], "src_uid": "a74c65acd41ff9bb845062222135c60a"} {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\nrunMm :: Graph -> (UArray Int Int, UArray Int Bool)\r\nrunMm g =\r\n runST $ do\r\n mt <- newArray (bounds g) (-1)\r\n forM_ (indices g) $ \\i -> do\r\n vis <- newArray (bounds g) False\r\n go vis mt i\r\n vis <- newArray (bounds g) False\r\n mt' <- unsafeFreezeSTUArray mt\r\n let matched = Set.fromList (filter (>=0) (elems mt'))\r\n forM_ (indices g) $ \\i -> do\r\n unless (Set.member i matched) $\r\n void (go vis mt i)\r\n vis' <- unsafeFreezeSTUArray vis\r\n return (mt', vis')\r\n where\r\n go :: STUArray s Int Bool -> STUArray s Int Int -> Int -> ST s Bool\r\n go vis mt x = do\r\n visx <- readArray vis x\r\n if visx then\r\n return False\r\n else do\r\n writeArray vis x True\r\n trav (g ! x)\r\n where\r\n trav [] = return False\r\n trav (y:ys) = do\r\n v <- readArray mt y\r\n if v < 0 then win\r\n else do\r\n can <- go vis mt v\r\n if can then win\r\n else\r\n trav ys\r\n where\r\n win = do\r\n writeArray mt y x\r\n return True\r\n\r\ngetMvc :: Graph -> [Int]\r\ngetMvc g =\r\n let (mt, vis) = runMm g\r\n in\r\n [i | (i, t) <- assocs vis, not t] ++ [-i | (i, t) <- assocs mt, t >= 0 && vis ! t]\r\n\r\nsolve :: [Int] -> [(Int64, Int64)] -> Int -> Int -> [Int]\r\nsolve os vs' n k = runST $ do\r\n mem <- newArray ((0,0), (k+1,mm+1)) (-1)\r\n c <- newArray ((0,0), (k+1,mm+1)) (-1)\r\n r <- f mem c 0 mm\r\n build c 0 mm os\r\n where\r\n mm = length os\r\n vs = listArray (0, k-1) vs' :: Array Int (Int64,Int64)\r\n f :: STUArray s (Int, Int) Int64 -> STUArray s (Int, Int) Int -> Int -> Int -> ST s Int64\r\n f mem c i j = do\r\n rr <- readArray mem (i,j)\r\n if rr >= 0 then\r\n return rr\r\n else do\r\n if i == k then\r\n writeArray mem (i,j) 0\r\n else do\r\n let (x,y) = vs ! i\r\n writeArray mem (i,j) (1 `shift` 60)\r\n forM_ [0..j] $ \\t -> do\r\n when (j-t <= n-2-i) $ do\r\n rcost <- f mem c (i+1) (j-t)\r\n let cost = rcost + ((y * fromIntegral t) `min` x)\r\n curcost <- readArray mem (i,j)\r\n when (cost < curcost) $ do\r\n writeArray mem (i,j) cost\r\n writeArray c (i,j) t \r\n readArray mem (i,j)\r\n build :: STUArray s (Int, Int) Int -> Int -> Int -> [Int] -> ST s [Int]\r\n build c i j os\r\n | i == k = return []\r\n | otherwise = do\r\n t <- readArray c (i, j)\r\n rr <- build c (i+1) (j-t) (drop t os)\r\n return $ take t os ++ [0] ++ rr\r\n\r\nmain = do\r\n [n, m, k] <- map parseInt . BS.words <$> BS.getLine\r\n es <- replicateM m $ do\r\n [x, y] <- map parseInt . BS.words <$> BS.getLine\r\n return (x, y)\r\n vs <- replicateM k $ do\r\n [x, y] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine\r\n return (x, y)\r\n let g = buildG (1,n) es\r\n mvc = getMvc g\r\n r = solve mvc vs n k\r\n print $ length r\r\n putStrLn $ unwords (map show r)\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\nrunMm :: Graph -> (UArray Int Int, UArray Int Bool)\r\nrunMm g =\r\n runST $ do\r\n mt <- newArray (bounds g) (-1)\r\n forM_ (indices g) $ \\i -> do\r\n vis <- newArray (bounds g) False\r\n go vis mt i\r\n vis <- newArray (bounds g) False\r\n mt' <- unsafeFreezeSTUArray mt\r\n let matched = Set.fromList (filter (>=0) (elems mt'))\r\n forM_ (indices g) $ \\i -> do\r\n unless (Set.member i matched) $\r\n void (go vis mt i)\r\n vis' <- unsafeFreezeSTUArray vis\r\n return (mt', vis')\r\n where\r\n go :: STUArray s Int Bool -> STUArray s Int Int -> Int -> ST s Bool\r\n go vis mt x = do\r\n visx <- readArray vis x\r\n if visx then\r\n return False\r\n else do\r\n writeArray vis x True\r\n trav (g ! x)\r\n where\r\n trav [] = return False\r\n trav (y:ys) = do\r\n v <- readArray mt y\r\n if v < 0 then win\r\n else do\r\n can <- go vis mt v\r\n if can then win\r\n else\r\n trav ys\r\n where\r\n win = do\r\n writeArray mt y x\r\n return True\r\n\r\ngetMvc :: Graph -> [Int]\r\ngetMvc g =\r\n let (mt, vis) = runMm g\r\n in\r\n [i | (i, t) <- assocs vis, not t] ++ [-i | (i, t) <- assocs mt, t >= 0 && vis ! t]\r\n\r\nsolve :: [Int] -> [(Int64, Int64)] -> Int -> Int -> [Int]\r\nsolve os vs' n k = runST $ do\r\n mem <- newArray ((0,0), (k+1,mm+1)) (-1)\r\n c <- newArray ((0,0), (k+1,mm+1)) (-1)\r\n r <- f mem c 0 mm\r\n cc <- unsafeFreezeSTUArray c\r\n return $ build cc 0 mm os\r\n where\r\n mm = length os\r\n vs = listArray (0, k-1) vs' :: Array Int (Int64,Int64)\r\n f :: STUArray s (Int, Int) Int64 -> STUArray s (Int, Int) Int -> Int -> Int -> ST s Int64\r\n f mem c i j = do\r\n rr <- readArray mem (i,j)\r\n if rr >= 0 then\r\n return rr\r\n else do\r\n if i == k then\r\n writeArray mem (i,j) 0\r\n else do\r\n let (x,y) = vs ! i\r\n writeArray mem (i,j) (1 `shift` 60)\r\n forM_ [0..j] $ \\t -> do\r\n when (j-t <= n-2-i) $ do\r\n rcost <- f mem c (i+1) (j-t)\r\n let cost = rcost + ((y * fromIntegral t) `min` x)\r\n curcost <- readArray mem (i,j)\r\n when (cost < curcost) $ do\r\n writeArray mem (i,j) cost\r\n writeArray c (i,j) t \r\n readArray mem (i,j)\r\n build :: UArray (Int, Int) Int -> Int -> Int -> [Int] -> [Int]\r\n build c i j os\r\n | i == k = []\r\n | otherwise =\r\n let t = c ! (i,j) in\r\n take t os ++ [0] ++ build c (i+1) (j-t) (drop t os)\r\n\r\nmain = do\r\n [n, m, k] <- map parseInt . BS.words <$> BS.getLine\r\n es <- replicateM m $ do\r\n [x, y] <- map parseInt . BS.words <$> BS.getLine\r\n return (x, y)\r\n vs <- replicateM k $ do\r\n [x, y] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine\r\n return (x, y)\r\n let g = buildG (1,n) es\r\n mvc = getMvc g\r\n r = solve mvc vs n k\r\n print $ length r\r\n putStrLn $ unwords (map show r)\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\nrunMm :: Graph -> (UArray Int Int, UArray Int Bool)\r\nrunMm g =\r\n runST $ do\r\n mt <- newArray (bounds g) (-1)\r\n forM_ (indices g) $ \\i -> do\r\n vis <- newArray (bounds g) False\r\n go vis mt i\r\n vis <- newArray (bounds g) False\r\n mt' <- unsafeFreezeSTUArray mt\r\n let matched = Set.fromList (filter (>=0) (elems mt'))\r\n forM_ (indices g) $ \\i -> do\r\n unless (Set.member i matched) $\r\n void (go vis mt i)\r\n vis' <- unsafeFreezeSTUArray vis\r\n return (mt', vis')\r\n where\r\n go :: STUArray s Int Bool -> STUArray s Int Int -> Int -> ST s Bool\r\n go vis mt x = do\r\n visx <- readArray vis x\r\n if visx then\r\n return False\r\n else do\r\n writeArray vis x True\r\n trav (g ! x)\r\n where\r\n trav [] = return False\r\n trav (y:ys) = do\r\n v <- readArray mt y\r\n if v < 0 then win\r\n else do\r\n can <- go vis mt v\r\n if can then win\r\n else\r\n trav ys\r\n where\r\n win = do\r\n writeArray mt y x\r\n return True\r\n\r\ngetMvc :: Graph -> [Int]\r\ngetMvc g =\r\n let (mt, vis) = runMm g\r\n in\r\n [i | (i, t) <- assocs vis, not t] ++ [-i | (i, t) <- assocs mt, t >= 0 && vis ! t]\r\n\r\nsolve :: [Int] -> [(Int64, Int64)] -> Int -> [Int]\r\nsolve os vs' k = runST $ do\r\n mem <- newArray ((0,0), (k+1,mm+1)) (-1)\r\n c <- newArray ((0,0), (k+1,mm+1)) (-1)\r\n r <- f mem c 0 mm\r\n build c 0 mm os\r\n where\r\n mm = length os\r\n vs = listArray (0, k-1) vs' :: Array Int (Int64,Int64)\r\n f :: STUArray s (Int, Int) Int64 -> STUArray s (Int, Int) Int -> Int -> Int -> ST s Int64\r\n f mem c i j = do\r\n rr <- readArray mem (i,j)\r\n if rr >= 0 then\r\n return rr\r\n else do\r\n if i == k then\r\n writeArray mem (i,j) 0\r\n else do\r\n let (x,y) = vs ! i\r\n writeArray mem (i,j) (1 `shift` 60)\r\n forM_ [0..j] $ \\t -> do\r\n when (j-t <= k-1-i) $ do\r\n rcost <- f mem c (i+1) (j-t)\r\n let cost = rcost + ((y * fromIntegral t) `min` x)\r\n curcost <- readArray mem (i,j)\r\n when (cost < curcost) $ do\r\n writeArray mem (i,j) cost\r\n writeArray c (i,j) t \r\n readArray mem (i,j)\r\n build :: STUArray s (Int, Int) Int -> Int -> Int -> [Int] -> ST s [Int]\r\n build c i j os\r\n | i == k = return []\r\n | otherwise = do\r\n t <- readArray c (i, j)\r\n rr <- build c (i+1) (j-t) (drop t os)\r\n return $ take t os ++ [0] ++ rr\r\n\r\nmain = do\r\n [n, m, k] <- map parseInt . BS.words <$> BS.getLine\r\n es <- replicateM m $ do\r\n [x, y] <- map parseInt . BS.words <$> BS.getLine\r\n return (x, y)\r\n vs <- replicateM k $ do\r\n [x, y] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine\r\n return (x, y)\r\n let g = buildG (1,n) es\r\n mvc = getMvc g\r\n r = solve mvc vs k\r\n print $ length r\r\n putStrLn $ unwords (map show r)\r\n"}], "src_uid": "3ab4973d5b1c91fb76d5c918551ba9f7"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Prelude\nimport Data.List\nimport Text.Printf\nimport Control.Monad\nimport Data.Ratio\nimport Data.Int\nimport Data.Functor\nimport Control.Monad.ST.Safe\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as A\nimport qualified Data.Array.Unboxed as UA\n\n\nsolve :: Int -> [[Int]] -> ST s [Int]\nsolve m segments = do\n arr <- A.newArray (1, m) 0 :: ST s (A.STUArray s Int Int)\n forM_ segments $ \\[l, r] -> do\n forM_ [l .. r] $ \\i -> do\n A.writeArray arr i 1\n lst <- A.getElems arr \n return . map (+ 1) . findIndices (== 0) $ lst\n\nmain :: IO ()\nmain = do\n ([n, m] :: [Int]) <- (map read . words) <$> getLine\n (segments :: [[Int]]) <- replicateM n ((map read . words) <$> getLine)\n let answer = runST $ solve m segments\n printf \"%d\\n\" $ length answer\n forM_ answer $ printf \"%d \"", "positive_code": [{"source_code": "main = interact foo\n\nfoo :: String -> String\nfoo inp = \n let (_:n:_):nn = map (map read . words) . lines $ inp :: [[Int]]\n ns = map (\\u -> (u!!0, u!!1)) nn :: [(Int, Int)]\n out = filter (\\ u -> not $ any (\\(a, b) -> u `elem` [a..b]) ns) [1..n]\n in unlines [show . length $ out, unwords . map show $ out]"}, {"source_code": "import Data.List\n\nf ::String->(Int,Int)\nf x=let (a:b:[])=map read (words x)::[Int]\n in (a,b)\n\ng ::[(Int,Int)]->Int->Int\ng [] p=p\ng ((a,b):xs) p\n |a<=p && p<=b=(-1)\n |otherwise=g xs p\n\nmain=do\n e1<-getLine\n es<-getContents\n let xs=map f $ lines es\n (n:m:[])=map read (words e1)::[Int]\n ys=(-1):map (g xs) [1..m]\n ans=tail $ nub $ ys\n putStrLn $ if length(ans)==0 then \"0\" else (show(length(ans)))++\"\\n\"++(unwords(map show ans)) "}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,m] <- map read . words <$> getLine\n ps <- ([1..m] \\\\) . concat <$> replicateM n getI\n print (length ps)\n putStrLn $ unwords $ map show ps\ngetI = do\n [a,b] <- map read . words <$> getLine\n return [a..b]\n"}, {"source_code": "zipPairs :: [Int] -> [(Int, Int)]\nzipPairs [] = []\nzipPairs (l:r:xs) = (l,r):(zipPairs xs)\n\nsolve :: [Int] -> [Int]\nsolve (_:m:rest) = [x | x <- [1..m], not . elem x . concat . map list $ zipPairs rest]\n where list xs = [(fst xs)..(snd xs)] \n concat [] = []\n concat (a:as) = a ++ (concat as)\n \nparseStr :: [Int] -> String\nparseStr r = unlines [(show n),(seperates r)]\n where n = length r\n seperates [] = \"\"\n seperates (x:xs) = show x ++ \" \" ++ (seperates xs)\n\n\nmain = interact $ parseStr . solve . map read . words\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Set as S\n\nprocess s = foldl (S.union) S.empty $ map (\\[a,b]->S.fromList[a..b]) s\n\n\n\n\nmain= do\n\t\t[n,m]<- map read <$> words <$> getLine ::IO [Int]\n\t\ts<- map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n\t\tlet y = S.difference (S.fromList [1..m]) (process s)\n\t\tprint $S.size y\n\t\tputStrLn $ intercalate \" \"$ map show $ S.elems y\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(sort)\n\noutPoints :: Int -> [(Int,Int)] -> [Int]\noutPoints m ss = concat . map (\\(r,l) -> [r+1..l-1]) $ zip (0:rs') (ls'++[m+1])\n where\n (ls',rs') = unzip . f . sort $ ss\n f :: [(Int,Int)] -> [(Int,Int)]\n f [] = []\n f [x] = [x]\n f (x:xs@(y:ys))\n | snd x >= snd y = f (x:ys)\n | otherwise = x:(f xs)\n\nreadLine line = (l,r)\n where [l,r] = map read . words $ line\n \nmain = do\n nmStr <- getLine\n let [n,m] = map read . words $ nmStr :: [Int]\n contents <- getContents\n let ss = map readLine . lines $ contents :: [(Int, Int)]\n let ps = outPoints m ss\n let k = length ps\n print k\n putStrLn . unwords . map show $ ps"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport System.IO\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nconstruct :: BS.ByteString -> [Int]\nconstruct str\n | BS.null str = []\n | isSpace (BS8.head str) = construct (BS8.tail str)\n | otherwise = let Just (i, other) = BS8.readInt str in i : construct other\n\ngetInts :: IO [Int]\ngetInts = construct `fmap` BS.getLine\n\nfastPrint :: Char -> [Int] -> IO ()\nfastPrint mid arr = hPutBuilder stdout $ build arr\n where build = foldr (\\n b -> intDec n <> charUtf8 mid <> b) mempty\n\nok segs p = all (\\[l,r] -> l > p || p > r) segs\n\nmain = do\n [n,m] <- getInts\n segs <- replicateM n getInts\n let pos = filter (ok segs) [1..m]\n print (length pos)\n putStrLn $ (intercalate \" \") (map show pos)\n"}], "negative_code": [{"source_code": "main = interact foo\n\nfoo :: String -> String\nfoo inp = \n let (m:n:_):nn = map (map read . words) . lines $ inp :: [[Int]]\n ns = map (\\u -> (u!!0, u!!1)) nn :: [(Int, Int)]\n out = filter (\\ u -> not $ any (\\(a, b) -> u `elem` [a..b]) ns) [m..n]\n in unlines [show . length $ out, unwords . map show $ out]"}, {"source_code": "import Data.List\n\nf ::String->(Int,Int)\nf x=let (a:b:[])=map read (words x)::[Int]\n in (a,b)\n\ng ::[(Int,Int)]->Int->Int\ng [] p=p\ng ((a,b):xs) p\n |a<=p && p<=b=(-1)\n |otherwise=g xs p\n\nmain=do\n e1<-getLine\n es<-getContents\n let xs=map f $ lines es\n (n:m:[])=map read (words e1)::[Int]\n ys=map (g xs) [1..m]\n ans=tail $ nub $ ys\n putStrLn $ if length(ans)==0 then \"0\" else (show(length(ans)))++\"\\n\"++(unwords(map show ans)) "}, {"source_code": "--ghc 7.10\n\nimport Data.List(sort)\n\noutPoints m ss = concat . map (\\(r,l) -> [r+1..l-1]) $ zip (0:rs') (ls'++[m+1])\n where\n (ls',rs') = unzip . sort $ ss\n\nreadLine line = (l,r)\n where [l,r] = map read . words $ line\n \nmain = do\n nmStr <- getLine\n let [n,m] = map read . words $ nmStr :: [Int]\n contents <- getContents\n let ss = map readLine . lines $ contents :: [(Int, Int)]\n let ps = outPoints m ss\n let k = length ps\n print k\n putStrLn . unwords . map show $ ps"}], "src_uid": "f336b622fdaf5960032268641320bb53"} {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n", "positive_code": [{"source_code": "module Main where\n\nimport Array\nimport Control.Monad\nimport Data.List\n\nmain = do\n inputNM <- getLine\n let [n, m] = map read $ words inputNM\n\n inputPrice <- getLine\n let price = array (1, n) $ zip [1..] $ map ( \\w -> read w ) $ words inputPrice :: Array Int Int\n\n let initMatch = array ((1,1), (n, n)) [ ((x,y), 0) | x <- [1..n], y <- [1..n] ]\n\n matchList <- replicateM m $ do\n inputMatch <- getLine\n let [a, b] = map read $ words inputMatch :: [Int]\n return [ ((a, b), 1), ((b, a), 1) ]\n\n let match = initMatch // concat matchList\n best =\n foldl' ( \\best i ->\n foldl' ( \\best j ->\n foldl' ( \\best k ->\n let best' = ( price ! i ) + ( price ! j ) + ( price ! k ) in\n if best < best' then best else best'\n ) best $ filter ( \\k -> ( match ! (i,k) ) == 1 && ( match ! (j,k) ) == 1 ) [j+1..n]\n ) best $ filter ( \\j -> ( match ! (i,j) ) == 1 ) [i+1..n-1]\n ) worst [1..n-2]\n\n putStrLn $ if best == worst then \"-1\" else show best\n\nworst = 99999999\n"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}, {"source_code": "\nimport Array (Array, (!), accumArray, bounds, listArray)\nimport List (sort)\nimport Maybe (fromMaybe, listToMaybe)\nimport Monad (liftM)\n\nsolve :: Array Int Int -> Array (Int, Int) Bool -> Maybe Int\nsolve costs graph = listToMaybe (sort solve')\n where\n n = snd $ bounds costs\n solve' = [costs ! i + costs ! j + costs ! k |\n i <- [1..n],\n j <- [i+1..n],\n k <- [j+1..n],\n and [graph ! (i,j), graph ! (i,k), graph ! (j,k)]]\n\nreadPair :: String -> (Int, Int)\nreadPair line = case (words line) of\n [a, b] -> (read a, read b)\n _ -> error $ concat [\"readPair: \", \"string \", show line, \" dos't two words\"]\n\nswap :: (a, b) -> (b, a)\nswap (a, b) = (b, a)\n\nmain :: IO ()\nmain = do\n (n, m) <- liftM readPair getLine\n costs <- liftM (map read . words) getLine\n pairs <- liftM (map readPair . take m . lines) getContents\n let costs' = listArray (1, length costs) costs\n let graph' = accumArray (flip const) False ((1,1), (n,n)) (concatMap (\\a -> [(a, True), (swap a, True)]) pairs)\n print $ fromMaybe (-1) $ solve costs' graph'"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines"}, {"source_code": "import Data.Array\nimport Control.Monad\n\nreadInts :: IO [Int]\nreadInts = (map read . words) `fmap` getLine\n\nsolve n a vu = if null l then -1 else minimum l\n\twhere\n\t\trng = ((1,1),(n,n))\n\t\tarr' = array rng [((i,j),0) | (i,j) <- range rng]\n\t\tarr = arr' // [((i,j),1) | [i,j] <- vu]\n\t\tcost = listArray (1,n) a\n\t\tl = [cost!i + cost!j + cost!k | i <- [1..n], j <- [i+1..n], arr!(i,j)==1, k <- [j+1..n], arr!(j,k)==1 && arr!(k,i)==1]\n\nmain = do\n\t[n,m] <- readInts\n\ta <- readInts\n\tl <- forM [1..m] (\\_ -> readInts)\n\tlet vu = l ++ map reverse l\n\tputStrLn . show $ solve n a vu\n\n"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}, {"source_code": "import Data.Array.IArray\nimport Control.Monad (mplus, guard)\nimport qualified Data.IntMap as M\nimport qualified Data.IntSet as S\nimport Data.Maybe (fromJust, isJust)\nmain = do\n [n, m] <- (map read . words) `fmap` getLine\n \u0446\u0435\u043d\u044b <- (listArray (1, n) . map read . words) `fmap` getLine :: IO (Array Int Int)\n \u043f\u0430\u0440\u044b <- mapM (\\_ -> (map read . words) `fmap` getLine) [1..m]\n let \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435 = foldl (\\\u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435 [\u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430, \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430] ->\n M.insertWith S.union \u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 (S.singleton \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430) $\n M.insertWith S.union \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 (S.singleton \u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430) \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435) M.empty \u043f\u0430\u0440\u044b\n (\u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u0430\u044f\u0426\u0435\u043d\u0430, _) = foldl (\\(\u043c\u0446, \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435) [\u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430, \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430] -> \n let a = S.delete \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 (\u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435 M.! \u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430)\n b = S.delete \u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 (\u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435 M.! \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430) \n x = S.toList $ S.intersection a b\n s = \u0446\u0435\u043d\u044b ! \u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 + \u0446\u0435\u043d\u044b ! \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430\n y = (map ((s+).(\u0446\u0435\u043d\u044b !)) x) `mplus` \u043c\u0446 in\n (guard (y > []) >> return (minimum y), M.insert \u043f\u0435\u0440\u0432\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 a $ M.insert \u0432\u0442\u043e\u0440\u0430\u044f\u041e\u0434\u0451\u0436\u043a\u0430 b \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435))\n ([], \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u044b\u0435) \u043f\u0430\u0440\u044b\n print $ head $ \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u0430\u044f\u0426\u0435\u043d\u0430 ++ [-1] \n"}, {"source_code": "import Array\n\ngetIntPairs :: IO (Int,Int)\ngetIntPairs = do ns <- getLine\n return (make_pair [(read n::Int)|n<-(words ns)])\n where\n make_pair (x:y:_) = (x,y)\n make_pair _ = (0,0)\n\ngetInts :: IO [Int]\ngetInts = do ns <- getLine\n return [(read n::Int)|n<-(words ns)]\n\ngetPairLines :: Int -> IO [(Int,Int)]\ngetPairLines n = if n > 0 then\n do l <- getIntPairs\n ls <- getPairLines (n-1)\n return (l:ls)\n else\n return []\n\nputAnsLn :: (Show a) => a -> IO ()\nputAnsLn ans = putStrLn (show ans)\n\ninclude x [] = False\ninclude x (l:ls) = if x==l then True else include x ls\n\nmins m [] = m\nmins m (x:xs) = if m>x then mins x xs else mins m xs\n\nloop_find n ms = filter (\\(j,k) -> include n (ms!k)&&n/=j&&n/=k ) [(j,k)|j<-(ms!n),k<-(ms!j)]\n\nsolve n m a uv = solve_rec 100000000 [1..n]\n where\n solve_rec ans [] = if ans==100000000 then -1 else ans\n solve_rec ans (i:is) = solve_rec (mins ans [prices!i + prices!j + prices!k|(j,k)<-loops]) is\n where\n loops = loop_find i matchings\n prices = array (1,n) (zip [1..n] a)\n matchings = make_matching (array (1,n) [(i,[])|i<-[1..n]]) uv\n where\n make_matching ary [] = ary\n make_matching ary ((u,v):uvs) = make_matching ((ary//[(u,v:(ary!u))])//[(v,u:(ary!v))]) uvs\n \n\nmain = do (n,m) <- getIntPairs\n a <- getInts\n uv <- getPairLines m\n putAnsLn (solve n m a uv)\n "}, {"source_code": "import List\np[]= -1\np l=minimum l+3\nx :: [[Int]] -> Int -> [[[Int]]] -> [[[Int]]]\nx m n e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n-1]\nr m n=[[j|[k,j]<-m,k==i]|i<-[0..n-1]]\ns(_:i:m)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$e$e$repeat[[]],[b,c]<-l]where e=r(map sort m)(length i)`x`length i\nmain=interact$show.p.s.map(map(pred.read).words).lines"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}, {"source_code": "p[]= -1\np l=minimum l+3\ns(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]\nmain=interact$show.p.s.map(map(pred.read).words).lines\n"}], "negative_code": [{"source_code": "import Array\n\ngetIntPairs :: IO (Int,Int)\ngetIntPairs = do ns <- getLine\n return (make_pair [(read n::Int)|n<-(words ns)])\n where\n make_pair (x:y:_) = (x,y)\n make_pair _ = (0,0)\n\ngetInts :: IO [Int]\ngetInts = do ns <- getLine\n return [(read n::Int)|n<-(words ns)]\n\ngetPairLines :: Int -> IO [(Int,Int)]\ngetPairLines n = if n > 0 then\n do l <- getIntPairs\n ls <- getPairLines (n-1)\n return (l:ls)\n else\n return []\n\nputAnsLn :: (Show a) => a -> IO ()\nputAnsLn ans = putStrLn (show ans)\n\ninclude x [] = False\ninclude x (l:ls) = if x==l then True else include x ls\n\nmins m [] = m\nmins m (x:xs) = if m>x then mins x xs else mins m xs\n\nloop_find n ms = filter (\\(j,k) -> include n (ms!k) ) [(j,k)|j<-(ms!n),k<-(ms!j)]\n\nsolve n m a uv = solve_rec 10000000 [1..n]\n where\n solve_rec ans [] = if ans==10000000 then -1 else ans\n solve_rec ans (i:is) =if loops == [] then\n solve_rec ans is\n else\n solve_rec (mins ans [prices!i + prices!j + prices!k|(j,k)<-loops]) is\n where\n loops = loop_find i matchings\n prices = array (1,n) (zip [1..n] a)\n matchings = make_matching (array (1,n) [(i,[])|i<-[1..n]]) uv\n where\n make_matching ary [] = ary\n make_matching ary ((u,v):uvs) = make_matching (ary//[(u,v:(ary!u))]) uvs\n \n\nmain = do (n,m) <- getIntPairs\n a <- getInts\n uv <- getPairLines m\n putAnsLn (solve n m a uv)\n "}, {"source_code": "import List\np[]= -1\np l=minimum l+3\nx m n e=map(\\i->[j:l|[k,j]<-m,i==k,l<-e!!j])[0..n-1]\ns(_:i:m)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$e$e$repeat[[]],[b,c]<-l]where e=map sort m`x`length i\nmain=interact$show.p.s.map(map(pred.read).words).lines"}, {"source_code": "p[]= -1\np l=minimum l+3\nx m n e=map(\\i->[j:l|[k,j]<-m,i==k,l<-e!!j])[0..n-1]\ns(_:i:m)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$e$e$repeat[[]],[b,c]<-l]where e=m`x`length i\nmain=interact$show.p.s.map(map(pred.read).words).lines"}], "src_uid": "d90da1e932a6aa546bec4e1bd4b1fbec"} {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (nub, reverse, group, sort)\n\nsolve :: C.ByteString -> Int -> Int\nsolve time x = do\n let sec = timeToSec time\n let xs = sec : takeWhile (/= sec) (iterate (calc x) (calc x sec))\n\n length $ filter (==True) $ map (isPal . secToTime) xs\n\nread = do\n s <- C.getLine\n\n let a = C.words s\n\n print $ solve (a !! 0) (fst $ fromJust $ C.readInt (a !! 1))\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n\ncalc :: Int -> Int -> Int\ncalc x t = rem (t + x * 60) 86400\n\nisPal :: C.ByteString -> Bool\nisPal s = s == (C.reverse s)\n\ntimeToSec :: C.ByteString -> Int\ntimeToSec str = do\n let (f, s) = C.span (/= ':') str\n let hours = fst $ fromJust $ C.readInt f\n let minutes = fst $ fromJust $ C.readInt (C.tail s)\n\n 3600 * hours + 60 * minutes\n\nsecToTime :: Int -> C.ByteString\nsecToTime x = do\n let hours = quot x 3600 :: Int\n let minutes = quot (x - hours * 3600) 60 :: Int\n \n C.append (C.append (format hours) (C.pack \":\")) (format minutes)\n\nformat :: Int -> C.ByteString\nformat x\n | x < 10 = C.append (C.pack \"0\") (C.pack $ show x)\n | otherwise = C.pack $ show x\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep = id\n\nparse :: String -> (Int, Int)\nparse xs = (60 * read hh + read mm, read k)\n where (hh,r1) = splitAt 2 xs\n (mm,r2) = splitAt 2 $ drop 1 r1\n k = drop 1 r2\n\nformat = show\n\np = 24*60\n\nsolve :: (Int, Int) -> Int\nsolve (time, k) = length $ filter isPalindrome $ nub orbit\n where orbit = map (`mod` p) [time + k*i | i <- [0..p-1]]\n\nisPalindrome time = (reverse $ f hh) == f mm\n where (hh,mm) = divMod time 60\n f x = show (10*x+1001)\n"}, {"source_code": "parseT :: IO (Int, Int, Int)\r\nparseT = do\r\n s <- getLine\r\n let (a: b: _) = words s\r\n let (h1: h2: _: m1: m2: _) = a\r\n return (read [h1, h2] :: Int, read [m1, m2] :: Int, read b :: Int)\r\n\r\ncalc :: Int -> Int -> Int\r\ncalc h m = 60 * h + m\r\n\r\ncheckH :: Int -> Int -> [Int] -> Int -> Int\r\ncheckH _ _ _ 1440 = 0\r\ncheckH t s a b = let t1 = (t + s * b) `mod` 1440 in if (&&) (t1 `elem` [calc 0 0, calc 1 10, calc 2 20, calc 3 30, calc 4 40, calc 5 50, calc 10 1, calc 11 11, calc 12 21, calc 13 31, calc 14 41, calc 15 51, calc 20 2, calc 21 12, calc 22 22, calc 23 32]) ((t1 `elem` a) == False)\r\n then checkH t s (t1: a) (b + 1) + 1\r\n else checkH t s a (b + 1)\r\n\r\ncheck :: Int -> Int -> Int\r\ncheck t s = checkH t s [] 0\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = pure ()\r\nsolve i = do\r\n (h, m, s) <- parseT\r\n print $ check (calc h m) s\r\n solve $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n solve n"}], "negative_code": [], "src_uid": "c601769062070ab983e1d4c9942cdd39"} {"source_code": "import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.ByteString.Char8 as C\n\nparse s =\n case C.readInt s of\n Just (l, s') ->\n case C.readInt (C.tail s') of\n Just (r, _) ->\n (l, r)\n\ngao a = if r < r' then -1 else k + 1\n where\n (l, r) = minimumBy (comparing $ second negate) a\n k = fromJust $ elemIndex (l, r) a\n r' = maximum $ map snd a\n\nmain = do\n a <- fmap (map parse . tail . C.lines) C.getContents\n print $ gao a\n", "positive_code": [{"source_code": "import Data.List\nimport Debug.Trace\n\nmain = interact $ show . solve . map (map read . words) . lines\n\nsolve ([n] : segments) = fst $ foldl1' test $ zip [1..n] segments\n\ntest x@(n, [a, b]) y@(m, [c, d])\n | c <= a, b <= d = y\n | a <= c, d <= b = x\n | otherwise = (-1, [min a c, max b d])\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ss <- replicateM n getInts\n\n let\n l = minimum $ map (!!0) ss\n r = maximum $ map (!!1) ss\n\n print $ fromMaybe (-1) ((+1) <$> [l, r] `elemIndex` ss)\n"}, {"source_code": "main = do\n x <-getContents\n putStrLn $ show $ f $ map (\\x -> read x::Int) $ words $ unwords $ tail $ lines x\n \nf :: [Int] -> Int\nf x =\n if e > 0\n then -1\n else thd3 m\n where \n l = toPairs 1 x\n m = foldl1 f1 l\n e = length $ filter (\\x -> snd3 m [Int] -> [(Int,Int,Int)]\ntoPairs _ [] = []\ntoPairs n (a:b:t) = (a,b,n):toPairs (n+1) t\n\nf1 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int,Int,Int)\nf1 a a0\n | fst3 a < fst3 a0 = a\n | fst3 a == fst3 a0 && snd3 a > snd3 a0 = a\n | otherwise = a0\n \nfst3 :: (a,b,c)-> a\nfst3 (a,_,_) = a\nsnd3 :: (a,b,c)-> b\nsnd3 (_,b,_) = b\nthd3 :: (a,b,c)-> c\nthd3 (_,_,c) = c"}, {"source_code": "main = do\n x <-getContents\n putStrLn $ show $ f $ map (\\x -> read x::Int) $ words $ unwords $ tail $ lines x\n \nf :: [Int] -> Int\nf x =\n if e > 0\n then -1\n else thd3 m\n where \n l = toPairs 1 x\n m = foldl1 f1 l\n e = length $ take 1 $ filter (\\x -> snd3 m [Int] -> [(Int,Int,Int)]\ntoPairs _ [] = []\ntoPairs n (a:b:t) = (a,b,n):toPairs (n+1) t\n\nf1 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int,Int,Int)\nf1 a a0\n | fst3 a < fst3 a0 = a\n | fst3 a == fst3 a0 && snd3 a > snd3 a0 = a\n | otherwise = a0\n \nfst3 :: (a,b,c)-> a\nfst3 (a,_,_) = a\nsnd3 :: (a,b,c)-> b\nsnd3 (_,b,_) = b\nthd3 :: (a,b,c)-> c\nthd3 (_,_,c) = c"}, {"source_code": "\nimport Control.Monad (liftM)\n\ntype Pair = (Int, Int)\n\nparsePair :: String -> Pair\nparsePair line = case map read (words line) of\n [a, b] -> (a, b)\n\nsolve :: [Pair] -> Int\nsolve ps = last $ ((-1) :) $ map fst $ filter big ps'\n where\n ps' = zip [1..] ps\n mn = minimum (map fst ps)\n mx = maximum (map snd ps)\n big (_, (a, b)) = a == mn && b == mx\n\nmain :: IO ()\nmain = do\n n <- readLn\n ps <- liftM (take n . map parsePair . lines) getContents\n print $ solve ps\n"}, {"source_code": "import Data.List\n\ncompareLength (_, [l1, r1]) (_, [l2, r2]) =\n let len1 = r1 - l1 + 1\n len2 = r2 - l2 + 1\n in compare len1 len2\n\nsolve segments\n | checkLeft && checkRight = index\n | otherwise = -1\n where (index, [left, right]) = maximumBy compareLength $ zip [1..] segments\n checkLeft = all (\\[x, _] -> left <= x) segments\n checkRight = all (\\[_, x] -> x <= right) segments\n\nmain = interact $ show . solve . map (map read . words) . tail . lines"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Function\n\nmain = do\n n <- fmap read getLine\n segs <- mapM (\\_ -> fmap ((\\[x,y] -> (x,y)) . map read . words) getLine) [1..n]\n print $ solve segs\n \nsolve :: [(Int,Int)] -> Int\nsolve segs | all (\\(_,y) -> y <= maxY) segs = fromJust (elemIndex bestSeg segs) + 1\n | otherwise = -1\n where minX = minimum $ map fst segs\n segsWithX = filter (\\(x,_) -> x == minX) segs\n bestSeg@(_,maxY) = maximumBy (compare `on` snd) segsWithX"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ntoPairs :: [Int] -> [(Int,Int)]\ntoPairs (x:y:xys) = (x,y):toPairs xys\ntoPairs _ = []\n\nmain=B.getContents>>=print.solve.map readInt.tail.B.words\n\nsolve xys = case filter (\\ (_,(x,y))->x==l&&y==r)$zip [1..] $ toPairs xys of\n ((i,_):_) -> i\n [] -> -1\n where\n l = minimum xys\n r = maximum xys"}, {"source_code": "import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.ByteString.Char8 as C\n\nparse s =\n case C.readInt s of\n Just (l, s') ->\n case C.readInt (C.tail s') of\n Just (r, _) ->\n (l, r)\n\nsolve a = if r < r' then -1 else k + 1\n where\n (l, r) = minimumBy (comparing $ second negate) a\n k = fromJust $ elemIndex (l, r) a\n r' = maximum $ map snd a\n\nmain = do\n a <- fmap (map parse . tail . C.lines) C.getContents\n print $ solve a"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.Array\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\n\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\nmain = do\n n <- readLn\n ss <- replicateM n getInts\n\n let \n l = minimum $ map (!!0) ss\n r = maximum $ map (!!1) ss\n\n print $ fromMaybe (-1) ((+1) <$> [l, r] `elemIndex` ss)\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = interact $ show . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve ([n] : segments) = fst $ foldl1' test $ zip [1..n] segments\n\ntest (m, [a, b]) (n, [c, d])\n | a <= c, c <= d, d <= b = (m, [a, b])\n | c <= a, a <= b, b <= d = (n, [c, d])\n | otherwise = (-1, [min a c, max b d])\n"}, {"source_code": "import Data.List\n\nmain = interact $ show . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve (_ : [l1, r1] : segments) = fst $ foldl' test (1, [l1, r1]) (zip [2..] segments)\n\ntest (m, [a, b]) (n, [c, d])\n | a <= c, d <= b = (m, [a, b])\n | c <= a, b <= d = (n, [c, d])\n | otherwise = (-1, [min a c, max b d])\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\ntype Pair = (Int, Int)\n\nparsePair :: String -> Pair\nparsePair line = case map read (words line) of\n [a, b] -> (a, b)\n\nsolve :: [Pair] -> Bool\nsolve pairs = any (\\(l,r) -> l == mn && r == mx) pairs\n where\n mn = minimum (map fst pairs)\n mx = maximum (map snd pairs)\n\nmain :: IO ()\nmain = do\n n <- readLn\n ps <- liftM (take n . map parsePair . lines) getContents\n putStrLn $ if solve ps\n then \"YES\"\n else \"NO\"\n"}], "src_uid": "e702594a8e993e135ea8ca78eb3ecd66"} {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\n\nsolve' starts i prev [] = map (\\j -> (j, i - 1)) starts\nsolve' starts i prev (x:xs)\n\t| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs\n\t| x < prev = map (\\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs\n\t| x == prev = solve' starts (i + 1) prev xs\n\twhere\n\t\t(starts', starts'') = splitAt (prev - x) starts\n\nsolve xs = solve' [] 1 0 xs\n\nmain = do\n\tgetLine\n\txs <- map read . words <$> getLine\n\tlet r = solve xs\n\tprint $ length r\n\tmapM_ putStrLn $ map (\\(a, b) -> show a ++ \" \" ++ show b) r\n", "positive_code": [{"source_code": "import Control.Applicative\n\nsolve' :: [Int] -> Int -> Int -> [Int] -> [(Int, Int)]\nsolve' starts i prev [] = map (\\j -> (j, i - 1)) starts\nsolve' starts i prev (x:xs)\n\t| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs\n\t| x < prev = map (\\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs\n\t| x == prev = solve' starts (i + 1) prev xs\n\twhere\n\t\t(starts', starts'') = splitAt (prev - x) starts\n\nsolve xs = solve' [] 1 0 xs\n\nmain = do\n\tgetLine\n\txs <- map read . words <$> getLine\n\tlet r = solve xs\n\tprint $ length r\n\tmapM_ putStrLn $ map (\\(a, b) -> show a ++ \" \" ++ show b) r\n"}, {"source_code": "main = interact $ unlines.map (unwords.map show).solve.map read.words\n\nsolve :: [Int] -> [[Int]]\nsolve (_:xs)= let ys = 0:xs++[0]\n ans = step [] $ zip [0..] ys\n in [length ans]:ans\n\nstep :: [(Int,Int)] -> [(Int,Int)] -> [[Int]]\nstep _ [] = []\nstep [] ((r,y):ys) = step [(r,y)] ys\nstep xxs@((l,x):xs) yys@((r,y):ys)\n | xy = case xs of\n (z:zs)|snd z==x-1 -> [l,r-1]:step xs yys\n _ -> [l,r-1]:step ((l,x-1):xs) yys\n"}, {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\n\nsolve' starts i prev [] = map (\\j -> (j, i - 1)) starts\nsolve' starts i prev (x:xs)\n\t| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs\n\t| x < prev = map (\\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs\n\t| x == prev = solve' starts (i + 1) prev xs\n\twhere\n\t\t(starts', starts'') = splitAt (prev - x) starts\n\nsolve xs = solve' [] 1 0 xs\n\nmain = do\n\tgetLine\n\txs <- map (read :: String -> Int) . words <$> getLine\n\tlet r = solve xs\n\tprint $ length r\n\tmapM_ putStrLn $ map (\\(a, b) -> show a ++ \" \" ++ show b) r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nsolve' starts i prev [] = map (\\j -> (j, i - 1)) starts\nsolve' starts i prev (x:xs)\n\t| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs\n\t| x < prev = map (\\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs\n\t| x == prev = solve' starts (i + 1) prev xs\n\twhere\n\t\t(starts', starts'') = splitAt (prev - x) starts\n\nsolve xs = solve' [] 1 0 xs\n\t\t\t\t\nmain = interact $ unlines . map (\\(a, b) -> show a ++ \" \" ++ show b) . solve . map read . tail . words\n"}], "src_uid": "c1f56e049db25a2f2a8a9a5202a1abd6"} {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let [ds, rs] = flip map s . (==) <$> \"DR\"\r\n [td, tr] = sum . map fromEnum <$> [ds, rs]\r\n [id, ir] = elemIndex True <$> [ds, rs]\r\n [bd, br] = map (snd . foldl' countf (0, 0)) [ds, rs] where\r\n countf (cur, acc) True = (cur + 1, acc)\r\n countf (cur, acc) False = (cur, acc + cur)\r\n xd = (n - td - 1) * fromMaybe n id\r\n xr = (n - tr - 1) * fromMaybe n ir\r\n print $ n * n - (xr + xd + bd + br)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n s <- getNext\n let\n numDs = fromIntegral $ P.count 'D' s\n numRs = fromIntegral $ P.count 'R' s\n h = n - numDs\n w = n - numRs\n wasteC acc 'D' = acc + w - 1\n wasteC acc 'R' = acc + h - 1\n wasteC _ _ = error \"bad path char\"\n initSeg = head $ P.group s\n ans\n | numDs == 0 && numRs == 0 = 1\n | numDs == 0 || numRs == 0 = n\n | otherwise = h * w + numDs * w + h * numRs - P.foldl' wasteC 0 initSeg\n pure $ putInts [ans]\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\ngetNext :: Monad m => S m P.ByteString\ngetNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n s <- C.unpack <$> C.getLine\r\n let [ds, rs] = flip map s . (==) <$> \"DR\"\r\n [td, tr] = sum . map fromEnum <$> [ds, rs]\r\n [id, ir] = elemIndex True <$> [ds, rs]\r\n [bd, br] = map (snd . foldl' countf (0, 0)) [ds, rs] where\r\n countf (cur, acc) True = (cur + 1, acc)\r\n countf (cur, acc) False = (cur, acc + cur)\r\n xr = (n - tr - 1) * fromMaybe n ir\r\n xd = (n - td - 1) * fromMaybe n id\r\n print $ n * n - (xr + xd + bd + br)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "src_uid": "113a43af2f1c5303f83eb842ef532040"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getLine\n\n b :: IOUArray (Int, Int) Char <- newListArray ((1, 1), (n, n)) $ concat a\n\n forM_ [(x, y) | x <- [2..n-1], y <- [2..n-1]] $ \\(x, y) -> do\n let near = [(x-1,y),(x+1,y), (x,y-1), (x,y+1), (x,y)]\n v <- all (== '#') <$> mapM (readArray b) near\n when v $ mapM_ (\\xy -> writeArray b xy '.') near\n\n c <- getElems b\n putStrLn $ if all (== '.') c then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain = output . solve . tail . lines =<< getContents\n\noutput :: Bool -> IO()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [String] -> Bool\nsolve strs = let n = length strs\n s = foldl1 Set.union (map (initSet 0) (zip strs [0..]))\n in check n 0 0 s\n\ninitSet :: Int -> (String, Int) -> Set.Set (Int, Int)\ninitSet _ (\"\", _) = Set.empty\ninitSet col ((s:ss), row) = let next = initSet (col + 1) (ss, row)\n in if s == '#' \n then Set.insert (row, col) next\n else next\n\ncheck :: Int -> Int -> Int -> Set.Set (Int, Int) -> Bool\ncheck n r c s | r >= n = True\n | c >= n = check n (r + 1) 0 s\n | Set.member (r, c) s = if Set.member (r + 1, c - 1) s &&\n Set.member (r + 1, c ) s &&\n Set.member (r + 1, c + 1) s &&\n Set.member (r + 2, c ) s\n then check n r (c + 1) $ Set.delete (r + 1, c - 1) $\n Set.delete (r + 1, c ) $\n Set.delete (r + 1, c + 1) $\n Set.delete (r + 2, c ) s\n else False\n | otherwise = check n r (c + 1) s\n"}, {"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain = output . solve . tail . lines =<< getContents\n\noutput :: Bool -> IO()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [String] -> Bool\nsolve strs = let n = length strs\n s = foldl1 Set.union (map (initSet 0) (zip strs [0..]))\n in check n 0 0 s\n\ninitSet :: Int -> (String, Int) -> Set.Set (Int, Int)\ninitSet _ (\"\", _) = Set.empty\ninitSet col (s : ss, row) = let next = initSet (col + 1) (ss, row)\n in if s == '#' \n then Set.insert (row, col) next\n else next\n\ncheck :: Int -> Int -> Int -> Set.Set (Int, Int) -> Bool\ncheck n r c s | r >= n = True\n | c >= n = check n (r + 1) 0 s\n | Set.member (r, c) s = Set.member (r + 1, c - 1) s &&\n Set.member (r + 1, c ) s &&\n Set.member (r + 1, c + 1) s &&\n Set.member (r + 2, c ) s &&\n (check n r (c + 1) $ Set.delete (r + 1, c - 1) $\n Set.delete (r + 1, c ) $\n Set.delete (r + 1, c + 1) $\n Set.delete (r + 2, c ) s)\n | otherwise = check n r (c + 1) s\n"}, {"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain = output . solve . tail . lines =<< getContents\n\noutput :: Bool -> IO()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [String] -> Bool\nsolve strs = let n = length strs\n s = foldl1 Set.union (map (initSet 0) (zip strs [0..]))\n in check n 0 0 s\n\ninitSet :: Int -> (String, Int) -> Set.Set (Int, Int)\ninitSet _ (\"\", _) = Set.empty\ninitSet col (s : ss, row) = let next = initSet (col + 1) (ss, row)\n in if s == '#' \n then Set.insert (row, col) next\n else next\n\ncheck :: Int -> Int -> Int -> Set.Set (Int, Int) -> Bool\ncheck n r c s | r >= n = True\n | c >= n = check n (r + 1) 0 s\n | Set.member (r, c) s = Set.member (r + 1, c - 1) s &&\n Set.member (r + 1, c ) s &&\n Set.member (r + 1, c + 1) s &&\n Set.member (r + 2, c ) s &&\n check n r (c + 1) (Set.delete (r + 1, c - 1) $\n Set.delete (r + 1, c ) $\n Set.delete (r + 1, c + 1) $\n Set.delete (r + 2, c ) s)\n | otherwise = check n r (c + 1) s\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getLine\n\n let\n a' = listArray ((1, 1), (n, n)) $ concat a\n cs = filter center [(x, y) | x <- [2..n-1], y <- [2..n-1]]\n where\n center (x, y) = all (== '#') $ map (a'!) [(x-1,y),(x+1,y), (x,y-1), (x,y+1), (x,y)]\n\n b = runSTArray $ do\n a <- newArray ((1, 1), (n, n)) '.'\n\n forM_ cs $ \\(x, y) ->\n forM_ [(x-1,y),(x+1,y), (x,y-1), (x,y+1), (x,y)] $ \\(x, y) ->\n writeArray a (x, y) '#'\n return a\n\n putStrLn $ if a' == b then \"YES\" else \"NO\"\n"}], "src_uid": "b08ba52eb4c36b75dacf56dad6c2e670"} {"source_code": "import Text.Printf\nimport Debug.Trace\n\ndiff :: [Int] -> [Int]\ndiff [x] = []\ndiff (x:xs) = (head xs - x) : diff xs\n\nf k x = (x - 1) `div` k\n\nmain = do\n [n, k] <- (map read . words) `fmap` getLine\n (_:list) <- (map read . words) `fmap` getLine\n\n let list' = [0] ++ list ++ [n+1]\n let ans = sum $ map (f k) $ diff list'\n let ans' = length list + ans\n\n printf \"%d\\n\" ans'\n", "positive_code": [{"source_code": "main = do\n\t[n, k] <- getA\n\t_:c <- getA\n\tputStrLn $ show $ pred $ sum $ zipWith (\\i j -> ceiling $ (j - i) / k) (0:c) $ c ++ [n + 1] where\n\tgetA = fmap (map read . words) getLine\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:k:c:a) = solve' 0 0 a\n where solve' :: Int -> Int -> [Int] -> Int\n solve' ni ki a | ni > n = 0\n | ki == k && ((length a) > 0 && ni == (head a)) = 1 + solve' (ni + 1) 1 (tail a)\n | ki == k = 1 + solve' (ni + 1) 1 a\n | ((length a) > 0 && ni == (head a)) = 1 + solve' (ni + 1) 1 (tail a)\n | otherwise = solve' (ni + 1) (ki + 1) a\n"}, {"source_code": "solve :: Int -> Int -> [Int] -> Int\nsolve n k xs = solve' 0 0 xs\n where\n solve' d s []\n | d + k > n = s\n | otherwise = solve' (d+k) (s+1) []\n solve' d s (x:xs)\n | d + k < x = solve' (d+k) (s+1) (x:xs)\n | otherwise = solve' x (s+1) xs\n\nmain :: IO ()\nmain = do\n [n, k] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n print $ solve n k $ tail xs"}, {"source_code": "\nimport Data.List\nimport Control.Arrow\nimport Control.Applicative\n\ngetInts :: IO [Int]\ngetInts = map read . words <$> getLine\n\nuntilNextHoliday k from nextH = (nextH - from) `div` k\n\ncountPresents n k hls' = \n let hls = hls' ++ [n+1]\n in second (subtract 1) $\n foldl \n (\\(tdy, sum) nxt -> (nxt + 1, sum + untilNextHoliday k tdy nxt + 1))\n (1, 0) \n hls\n\nmain = do\n [n, k] <- getInts\n (c: hs) <- getInts\n print . snd $ countPresents n k hs"}, {"source_code": "main=interact$show.g.map read.words\ng(n:k:_:x)=f 0 x where\n f l(x:s)|l+k0=1+f(max l x)s\n f l x|l+k<=n=1+f(l+k)x|1>0=0"}], "negative_code": [{"source_code": "main = do\n\t[n, k] <- getA\n\tc <- getA\n\tputStrLn $ show $ pred $ sum $ zipWith (\\i j -> ceiling $ (j - i) / k) (0:c) $ c ++ [n + 1] where\n\tgetA = fmap (map read . words) getLine\n"}, {"source_code": "main=interact$show.f 0.map read.words\nf l(n:k:x:s)|l+k0=1+f(max l x)(n:k:s)\nf l(n:k:x)|l+k<=n=1+f(l+k)(n:k:x)|1>0=0"}], "src_uid": "07b750dbf7f942eab80d4260103c7472"} {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let asNum :: Int\n asNum = read input\n numArray = [(i, i2) | i <- [1..asNum], i2 <- [1..asNum]]\n asStrs = map numMapper numArray\n numMapper :: (Int, Int) -> String\n numMapper (i, i2)\n | (mod (i+i2) 2) == 1 && i2 == asNum = \"W\\n\"\n | (mod (i+i2) 2) == 0 && i2 == asNum = \"B\\n\"\n | (mod (i+i2) 2) == 1 = \"W\"\n | (mod (i+i2) 2) == 0 = \"B\"\n in concat asStrs\n", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.ByteString.Lazy.Char8 as C8\nimport Data.List\n\nmain = do\n c <- read <$> getLine\n let s1 = C8.take (fromIntegral c) $ C8.concat $ repeat $ C8.pack \"WB\"\n let s2 = C8.take (fromIntegral c) $ C8.concat $ repeat $ C8.pack \"BW\"\n replicateM_ (c `div` 2) $ do\n C8.putStrLn s1\n C8.putStrLn s2\n when (odd c) $ C8.putStrLn s1\n"}], "negative_code": [], "src_uid": "09991e8e16cd395c7ce459817a385988"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain :: IO ()\nmain = interact solve\n\nsolve = unlines . getAns . map (map read . words) . tail . lines\n\ngetAns :: [[Int]] -> [String]\ngetAns = map doCase\n\ndoCase :: [Int] -> String\ndoCase [l, r, k] | l == 1 && r == 1 = \"NO\"\n | l == r = \"YES\"\n | otherwise = enumS $ ((r - l + 1) `div` 2) + fromEnum (odd l && odd r) <= k\ndoCase _ = error \"cmon\"\n\nenumS True = \"YES\"\nenumS False = \"NO\"\n", "positive_code": [{"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine \n let arr = map (read::String -> Int) $ words input\n l = arr !! 0\n r = arr !! 1\n k = arr !! 2\n req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)\n if l == r && l == 1 then putStrLn \"NO\" else if l == r then putStrLn \"YES\" else (if req <= k then putStrLn \"YES\" else putStrLn \"NO\")\n\nmain = do\ntlen <- readLn :: IO Int\nforM [0..(tlen - 1)] (\\t -> do solve t)\n"}, {"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine \n let [l, r, k] = map (read::String -> Int) $ words input\n req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)\n ans | (l == 1) && (l == r) = putStrLn \"NO\"\n | l == r = putStrLn \"YES\"\n | otherwise = if req <= k then putStrLn \"YES\" else putStrLn \"NO\"\n ans\n\nmain = do\n tlen <- readLn :: IO Int\n forM [0..(tlen - 1)] (\\t -> do solve t)\n"}], "negative_code": [{"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine \n let [l, k, r] = map (read::String -> Int) $ words input\n req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)\n ans | (l == 1) && (l == r) = putStrLn \"NO\"\n | l == r = putStrLn \"YES\"\n | otherwise = if req <= k then putStrLn \"YES\" else putStrLn \"NO\"\n ans\n\nmain = do\ntlen <- readLn :: IO Int\nforM [0..(tlen - 1)] (\\t -> do solve t)\n"}, {"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine \n let [l, k, r] = map (read::String -> Int) $ words input\n req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)\n ans | l == r = putStrLn \"YES\"\n | (l == 1) && (l == r) = putStrLn \"NO\"\n | otherwise = if req <= k then putStrLn \"YES\" else putStrLn \"NO\"\n ans\n\nmain = do\ntlen <- readLn :: IO Int\nforM [0..(tlen - 1)] (\\t -> do solve t)\n"}], "src_uid": "9363df0735005832573ef4d17b6a8302"} {"source_code": "\nimport Data.List\n-- import Debug.Trace\n-- the lines function is usefull\n\n-- snake a b lst line\n-- | line == a = trace (\"one\" ++ (show lst)) (lst ++ replicate b '#') \n-- | line == 1 = trace (\"two\" ++ (show lst)) snake a b (lst ++ replicate b '#') (line + 1)\n-- | (mod line 2) == 1 = trace (\"dkjfdk\" ++ (show lst)) snake a b (lst ++ replicate b '#') (line + 1)\n-- | (mod line 4) == 2 = trace (\"three\" ++ (show lst)) snake a b (lst ++ (concat [replicate (b-1) '.', ['#']])) (line + 1)\n-- | (mod line 4) == 0 = trace (\"four\" ++ (show lst)) snake a b (lst ++ (concat [['#'], replicate (b-1) '.'])) (line + 1)\n-- | otherwise = trace (\"oh\" ++ (show line)) lst\n\nsnake a b lst line\n | line == a = (lst ++ replicate b '#') \n | line == 1 = snake a b (lst ++ replicate b '#') (line + 1)\n | (mod line 2) == 1 = snake a b (lst ++ replicate b '#') (line + 1)\n | (mod line 4) == 2 = snake a b (lst ++ (concat [replicate (b-1) '.', ['#']])) (line + 1)\n | (mod line 4) == 0 = snake a b (lst ++ (concat [['#'], replicate (b-1) '.'])) (line + 1)\n | otherwise = lst\n\n-- when you get the error: Non-exhaustive patterns in function snake\n-- it means that you didn't account for all of the conditional cases\n-- in the function\n\nnewlst old b nw\n | (null old) = nw\n | otherwise = newlst (drop b old) b (nw ++ [take b old])\n\n\nmain = do\n ss <- getLine\n let aa = (read (head (words ss)))::Int\n bb = (read (last (words ss)))::Int\n\n ans = snake aa bb [] 1\n -- page 164\n -- mapM print ans\n let actually = newlst ans bb []\n putStrLn (unlines actually)\n -- mapM print ans\n", "positive_code": [{"source_code": "module Main (main)\n where\n\nimport Data.Bits (xor)\n\n\ninterleave :: [String] -> [String] -> [String]\ninterleave [s] _ = [s]\ninterleave (x:xs) (y:ys) = x:y:interleave xs ys\n\nmain :: IO ()\nmain = putStr . unlines . compose . map read . words =<< getLine\n where compose [n,m] = interleave (full n m) (alt m (1::Int))\n full n m = replicate ((n + 1) `div` 2) $ replicate m '#'\n alt m c = turn m c:alt m (c `xor` 1)\n turn m 1 = replicate (m - 1) '.' ++ \"#\"\n turn m 0 = '#':replicate (m - 1) '.'"}, {"source_code": "main = do\n l <- getLine\n let (n:m:_) = map read $ words l :: [Int]\n putStr $ unlines $ reverse $ func n m\n\nfunc :: Int -> Int -> [String]\nfunc 0 m = []\nfunc n m = (if odd n then \n replicate m '#' \n else \n if (n `mod` 4) == 0 then \n \"#\" ++ (replicate (m-1) '.')\n else\n (replicate (m-1) '.') ++ \"#\") : (func (n-1) m)\n"}, {"source_code": "\nfull m = (replicate m '#') ++ \"\\n\"\nleft m = \"#\"++ (replicate (m-1) '.') ++ \"\\n\"\nrigth m = (replicate (m-1) '.') ++ \"#\" ++\"\\n\"\n\nsolve2 n m f | n==0 = \"\"\n | n==1 = full m\n | f==0 = full m ++ rigth m ++ solve2 (n-2) m 1\n | f==1 = full m ++ left m ++ solve2 (n-2) m 0\n\nmain = do\n\tl <-getLine\n\tlet [n,m] = words l\n\tputStr $ solve2 (read n) (read m) 0"}, {"source_code": "module Main where\n\nsolve :: Char -> [Int] -> [String]\nsolve z [x, y]\n | x == 0 = []\n | odd x = bodyN y : solve z [(x-1), y]\n | even x && z == 'R' = bodyR y : solve 'L' [(x-1), y]\n | even x && z == 'L' = bodyL y : solve 'R' [(x-1), y]\n where bodyN n = take n ['#', '#'..]\n bodyR n = (take (n-1) ['.', '.'..]) ++ \"#\"\n bodyL n = '#' : (take (n-1) ['.', '.'..])\n\nmain :: IO ()\nmain = getLine >>= return . unlines . solve 'R' . (map read) . words >>= putStr\n"}, {"source_code": "main = do\n\n [n, m] <- fmap (map read . words) getLine\n\n let\n a = [[f x y | y <- [1..m]] | x <- [1..n]]\n f x y\n | odd x = '#'\n | odd (x `div` 2) && y == m = '#'\n | even (x `div` 2) && y == 1 = '#'\n | otherwise = '.'\n\n putStr $ unlines a\n"}, {"source_code": "main = do\n [n, m] <- fmap (map read . words) getLine\n\n let\n a = [[f x y | y <- [1..m]] | x <- [1..n]]\n f x y\n | odd x = '#'\n | odd (x `div` 2) && y == m = '#'\n | even (x `div` 2) && y == 1 = '#'\n | otherwise = '.'\n\n putStr $ unlines a\n"}, {"source_code": "import Data.Functor\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\n\nmain = getInts >>= mapM putStrLn . solve\n\nsolve :: [Int] -> [String]\nsolve (n:m:[]) = solve' n m 1\n\nsolve' n m i\n | i > n = []\n | mod i 2 == 1 = replicate m '#' : la\n | mod i 4 == 2 = (replicate (m-1) '.' ++ \"#\") : la\n | mod i 4 == 0 = (\"#\" ++ replicate (m-1) '.') : la\n where la = solve' n m (i+1)\n"}, {"source_code": "\nsnake :: Int -> Int -> String\nsnake x y =\n\tunlines $ fmap (snakeString y) [1..x]\n\twhere\n\t\tsnakeString :: Int -> Int -> String\n\t\tsnakeString width row\n\t\t\t| odd row = take width (repeat '#')\n\t\t\t| even row && row `mod` 4 == 2 = (take (width - 1) (repeat '.')) ++ \"#\"\n\t\t\t| even row && row `mod` 4 == 0 = \"#\" ++ (take (width - 1) (repeat '.'))\n\nmain = do\n\t[x, y] <- fmap (fmap read . words) getLine\n\tputStrLn $ snake x y\n"}, {"source_code": "data Dir = L|R\nsolve 0 _ _ =[]\nsolve n m dir\n\t|odd n=(replicate m '#'):solve (n-1) m (newDir dir)\n\t|otherwise = (line dir):(solve (n-1) m dir)\n\twhere\n\t\tnewDir L = R\n\t\tnewDir R = L\n\t\tline L = '#':replicate (m-1) '.'\n\t\tline R = (replicate (m-1) '.')++\"#\"\nmain=do\n\ta<-getLine\n\tlet (n:m:_)=map (\\x->read x::Int) (words a)\n\tputStrLn $ unlines $ solve n m L"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ unlines.solve. map read. words. head . lines\nsolve :: [Int]->[String]\nsolve [x,y] = take x $ cycle [replicate y '#', replicate (y-1) '.' ++ \"#\", replicate y '#',\"#\" ++replicate (y-1) '.']"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport qualified Data.List as List\nimport qualified Data.Set as Set\nimport qualified Data.Char as Char\n\nstrip :: String -> String\nstrip = lstrip . rstrip\n where\n lstrip = dropWhile Char.isSpace\n rstrip = reverse . lstrip . reverse\n\nsplitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen p l = splitWhenAux l []\n where\n splitWhenAux [] [] = []\n splitWhenAux [] b@(_:_) = [b]\n splitWhenAux (h:t) b | (p h) = (reverse b) : (splitWhenAux t [])\n | otherwise = splitWhenAux t (h:b)\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn n l = splitWhen (n ==) l\n\n--------------------------------------------------------------------------------\n\nsolve n m = foldl (++) \"\" $ List.intersperse \"\\n\" (doit 0)\n where\n long = List.replicate m '#'\n ev = '#' : List.replicate (m-1) '.'\n od = reverse ev\n doit :: Int -> [String]\n doit k | k == (n-1) = [long]\n | k `mod` 2 == 0 = long : (doit (k+1))\n | ((k-1) `div` 2) `mod` 2 == 0 = od : (doit (k+1))\n | otherwise = ev : (doit (k+1))\n\nmain :: IO ()\nmain = do\n [n,m] <- (map read . words) <$> getLine\n putStrLn $ solve n m\n\n"}, {"source_code": "generateLine :: Int -> Int -> String\ngenerateLine n m\n | n `mod` 2 == 0 = take m $ repeat '#'\n | n `mod` 4 == 1 = (take (m - 1) $ repeat '.') ++ ['#']\n | otherwise = '#':(take (m - 1) $ repeat '.')\n\ngenerateGraph :: Int -> Int -> String\ngenerateGraph n m = unlines $ map (`generateLine` m) (take n [0..])\n\nmain = do\n line <- getLine\n let n::Int\n m::Int\n [n, m] = map read $ words line\n putStr $ generateGraph n m"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve :: Int -> Int -> [String]\nsolve n m = take n $ cycle [replicate m '#',\n replicate (m - 1) '.' ++ ['#'],\n replicate m '#',\n '#' : replicate (m - 1) '.']\n \n\nmain :: IO ()\nmain = do\n [n, m] <- getIntList\n mapM_ putStrLn $ solve n m\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nprocess m n d | m>=n = process (m-n+1) n (d+n)\n | otherwise = d+m\n\n\nmain=do\n\n [n,m]<- map read <$> words <$> getLine ::IO [Int]\n let a= (replicate (m-1) '.' )++ ['#']\n let b= reverse a\n let c= replicate m '#'\n putStrLn $ take (n*m+(n-1)) $ unlines $ cycle [c,a,c,b]\n \n"}, {"source_code": "main :: IO ()\nmain = getLine >>= mapM_ putStrLn . solve . map read . words\n\nsolve :: [Int] -> [String]\nsolve [n, m] = [ snake k | k <- [0..n-1] ]\n where snake k | even k = replicate m '#'\n | k `mod` 4 == 1 = replicate (m - 1) '.' ++ \"#\"\n | otherwise = '#' : replicate (m - 1) '.'\nsolve _ = undefined\n"}, {"source_code": "main = interact $ unlines . solve . map read . words\nsolve [n,m] = take n $ merge (repeat full) (cycle [right,left]) where\n full = replicate m '#'\n left = '#' : replicate (m-1) '.'\n right = replicate (m-1) '.' ++ \"#\"\nmerge (x:xs) ys = x : merge ys xs\n\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/510/A\n\ndraw :: [Int] -> [String]\ndraw (n:m:_) = take n $ cycle [full, right, full, left]\n where full = replicate m '#'\n left = '#':replicate (m-1) '.'\n right = reverse left\n\nsolve :: String -> String\nsolve = unlines . draw . map read . words\n\nmain :: IO ()\nmain = interact $ solve\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/510/A\n\ndraw :: [Int] -> [String]\ndraw (n:m:_) = take n $ cycle [full, right, full, left]\n where full = replicate m '#'\n left = '#':replicate (m-1) '.'\n right = reverse left\n\nsolve :: String -> [String]\nsolve = draw . map read . words\n\nmain :: IO ()\nmain = do\n input <- getLine\n mapM_ putStrLn $ solve input\n"}, {"source_code": "main :: IO ()\nmain = do\n (n:m:_) <- map read . words <$> getLine\n putStrLn $ unlines $ take n $ snake m\n where\n snake m =\n let full = replicate m '#'\n one = '#' : replicate (m-1) '.'\n in full : reverse one : full : one : snake m\n"}, {"source_code": "import Data.List\n\n\nmain = do \n inp <- getLine\n let [n,m] = map (read :: String -> Int) (words inp)\n putStr (intercalate \"\\n\" (solve n m 0 0))\n\nsolve n m r c\n | (n == r) = [\"\"]\n | ((mod r 2) == 0) = (replicate m '#') : (solve n m (r+1) c)\n | ((mod (floor ((fromIntegral r)/2)) 2) == 0) = ((replicate (m-1) '.') ++ \"#\") : (solve n m (r+1) c)\n | ((mod (floor ((fromIntegral r)/2)) 2) == 1) = (\"#\" ++ (replicate (m-1) '.')) : (solve n m (r+1) c)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n \n\nmain= do\n\t[m,n]<- map read. words <$> getLine ::IO [Int]\n\tlet f = replicate n '#'\n\tlet s = (replicate (n-1) '.')++\"#\"\n\tlet t = reverse s\n\tmapM_ putStrLn $ take m (cycle [f,s,f,t])\n\n \n\t \n\t "}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, m] = map (\\c -> read c :: Int) (words line)\n let full = concat $ replicate m \"#\"\n let right = concat $ (replicate (m - 1) \".\") ++ [\"#\"]\n let left = concat $ [\"#\"] ++ (replicate (m - 1) \".\")\n let ri = [4 * x + 2 | x <- [0 .. n]]\n let li = [4 * x | x <- [0 .. n]]\n let rs = [right | x <- ri]\n let ls = [left | x <- li]\n let zipped = zip rs ls\n let flatted = concatMap (\\(r, l) -> [r, l]) zipped\n let odds = [full | x <- [1 .. n], odd x]\n let cc = (zip odds flatted)\n let total = concatMap (\\(r, l) -> [r, l]) cc\n let total' = case (even n) of\n True -> total\n False -> total ++ [full]\n mapM_ putStrLn (take n total')"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [m, n] = map (\\c -> read c :: Int) (words line)\n mapM_ putStrLn (take m $ (>>) ([0 ..])\n [ ['#' | x <- [1..n]],\n ['.' | x <- [1..n-1]] ++ \"#\",\n ['#' | x <- [1..n]],\n \"#\" ++ ['.' | x <- [1..n-1]] ] )"}, {"source_code": "import Data.List\n\ndrawRow :: Int -> Int -> String\ndrawRow m r\n | odd r = replicate m '#'\n | r `mod` 4 == 0 = '#':replicate (m-1) '.'\n | otherwise = reverse $ '#':replicate (m-1) '.'\n\ndraw :: Int -> Int -> [String]\ndraw n m = map (drawRow m) [1..n]\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int,Int)\nreadPair line = (a,b)\n where [a,b] = map readInt $ words line\n\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n sequence . map putStrLn $ draw n m"}, {"source_code": "\nimport Data.List\n\nmain = interact $ sol . map read . words\n\nsol [n, m] = intercalate \"\\n\" $ map gen [1..n]\n where gen r\n | odd r = rp m '#'\n | otherwise = if odd (r `div` 2) then rp (m-1) '.' ++ \"#\" \n else \"#\" ++ rp (m-1) '.'\n rp = replicate\n\n"}, {"source_code": "import Data.List\n\ndraw :: [Int] -> [String]\ndraw (n:m:_) = take n $ cycle [full, right, full, left]\n where full = replicate m '#'\n left = '#': replicate (m - 1) '.'\n right = reverse left\n\nsolve :: String -> String\nsolve = unlines . draw . fmap read . words\n\nmain :: IO ()\nmain= interact $ solve"}, {"source_code": "drawLine :: Int -> Int -> String\ndrawLine n i\n | even i = replicate n '#'\n | even $ quot i 2 = (replicate (n - 1) '.') ++ \"#\"\n | otherwise = '#' : (replicate (n - 1) '.')\n\nsolve :: String -> String\nsolve s = unlines $ fmap (drawLine m) [0.. (n -1)]\n where (n:m:_) = fmap read . words $ s\n\nmain :: IO ()\nmain= interact $ solve"}, {"source_code": "duplicate c 0 = []\nduplicate c n = c : duplicate c (n - 1)\n\ngen m 0 = duplicate '#' m\ngen m 1 = (duplicate '.' (m - 1)) ++ \"#\"\ngen m 2 = gen m 0\ngen m 3 = '#' : duplicate '.' (m - 1)\n\nmain = do\n input <- getLine\n let n : m : [] = map read $ words input :: [Int]\n doOutput n m 0\n\ndoOutput n m c\n | c + 1 == n = putStrLn $ gen m (c `mod` 4)\n | otherwise = (putStrLn $ gen m (c `mod` 4)) >> doOutput n m (c + 1)"}, {"source_code": "readInt :: String -> Int\nreadInt = read\n\nline :: Int -> Int -> String\nline i m\n | i `mod` 2 == 0 = replicate m '#'\n | i `mod` 4 == 1 = replicate (m-1) '.' ++ \"#\"\n | otherwise = '#':replicate (m-1) '.'\n\nmain :: IO ()\nmain = do\n x <- getLine\n let mn = map readInt $ words x\n let n = head mn\n let m = head $ tail mn\n let drawLine i = putStrLn $ line i m\n mapM_ drawLine $ take n (iterate (+1) 0)"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport qualified Data.List as List\nimport qualified Data.Set as Set\nimport qualified Data.Char as Char\n\nstrip :: String -> String\nstrip = lstrip . rstrip\n where\n lstrip = dropWhile Char.isSpace\n rstrip = reverse . lstrip . reverse\n\nsplitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen p l = splitWhenAux l []\n where\n splitWhenAux [] [] = []\n splitWhenAux [] b@(_:_) = [b]\n splitWhenAux (h:t) b | (p h) = (reverse b) : (splitWhenAux t [])\n | otherwise = splitWhenAux t (h:b)\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn n l = splitWhen (n ==) l\n\n--------------------------------------------------------------------------------\n\nsolve n m = foldl (++) \"\" $ List.intersperse \"\\n\" (doit n)\n where\n long = List.replicate m '#'\n ev = '#' : List.replicate (m-1) '.'\n od = reverse ev\n doit :: Int -> [String]\n doit k | k == 1 = [long]\n | k `mod` 2 == 1 = long : (doit (k-1))\n | ((k-1) `div` 2) `mod` 2 == 0 = od : (doit (k-1))\n | otherwise = ev : (doit (k-1))\n\nmain :: IO ()\nmain = do\n [n,m] <- (map read . words) <$> getLine\n putStrLn $ solve n m\n\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, m] = map (\\c -> read c :: Int) (words line)\n let full = concat $ replicate m \"#\"\n let right = concat $ (replicate (m - 1) \".\") ++ [\"#\"]\n let left = concat $ [\"#\"] ++ (replicate (m - 1) \".\")\n let rs = [right | x <- [2 .. n], even (x - 2)]\n let ls = [left | x <- [4 .. n], even (x - 4)]\n let zipped = zip rs ls\n let flatted = concatMap (\\(r, l) -> [r, l]) zipped\n let odds = [full | x <- [1 .. n], odd x]\n let total = concatMap (\\(r, l) -> [r, l]) (zip odds flatted)\n let total' = case (even n) of\n True -> total\n False -> total ++ [full]\n mapM_ putStrLn (take n total')"}, {"source_code": "drawLine :: Int -> Int -> String\ndrawLine n i\n | even i = replicate n '#'\n | even $ quot i 2 = (replicate (n - 1) '.') ++ \"#\"\n | otherwise = '#' : (replicate (n - 1) '.')\n\nsolve :: String -> String\nsolve s = unlines $ fmap (drawLine n) [0.. (m -1)]\n where (n:m:_) = fmap read . words $ s\n\nmain :: IO ()\nmain= interact $ solve"}], "src_uid": "2a770c32d741b3440e7f78cd5670d54d"} {"source_code": "import Control.Arrow ((>>>))\nimport System.IO\n\nmain = do\n hSetBuffering stdout NoBuffering\n interact $\n lines\n >>> (\\(nt : ls) -> head (words nt) : ls)\n >>> map read\n >>> solve\n >>> map show\n >>> unlines\n\ndata Query = Ask Int Int | Answer Int\n\ninstance Show Query where\n show (Ask l r) = \"? \" ++ show l ++ \" \" ++ show r\n show (Answer x) = \"! \" ++ show x\n\nsolve :: [Int] -> [Query]\nsolve (n : k : rs) = go 1 n rs\n where\n go lo hi ~(r : rs)\n | lo == hi = [Answer lo]\n | otherwise = Ask 1 mid : go lo' hi' rs\n where\n mid = (lo + hi) `div` 2\n (lo', hi') = if r + k > mid then (mid + 1, hi) else (lo, mid)\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport System.IO\r\n\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n interact $\r\n lines >>> (\\(nt:ls) -> head (words nt) : ls) >>> map read >>> solve >>> map show >>> unlines\r\n\r\ndata Query = Ask Int Int | Answer Int\r\n\r\ninstance Show Query where\r\n show (Ask l r) = \"? \" ++ show l ++ \" \" ++ show r\r\n show (Answer x) = \"! \" ++ show x\r\n\r\nsolve :: [Int] -> [Query]\r\nsolve (n:k:rs) = go 1 n rs\r\n where\r\n go lo hi xs\r\n | lo == hi = [Answer lo]\r\n | otherwise =\r\n let mid = (lo + hi) `div` 2\r\n in Ask 1 mid :\r\n (let (lo', hi') = (if head xs + k > mid then (mid + 1, hi) else (lo, mid))\r\n in go lo' hi' (tail xs))"}, {"source_code": "import Control.Arrow\r\nimport System.IO\r\n\r\n\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n interact $ \r\n lines >>> (\\(nt:ls) -> (head $ words nt) : ls)\r\n >>> map read >>> solve >>> map show >>> unlines\r\n\r\ndata Query = Ask Int Int | Answer Int\r\n\r\ninstance Show Query where\r\n show (Ask l r) = \"? \" ++ show l ++ \" \" ++ show r\r\n show (Answer x) = \"! \" ++ show x\r\n\r\nsolve :: [Int] -> [Query]\r\nsolve (n:k:rs) = go 1 n rs\r\n where\r\n go lo hi xs\r\n | lo == hi = [Answer lo]\r\n | otherwise = let mid = (lo + hi) `div` 2 \r\n in (Ask 1 mid) : \r\n (if head xs + k > mid then go (mid + 1) hi else go lo mid) (tail xs)\r\n"}, {"source_code": "import Control.Arrow\r\nimport System.IO\r\n\r\n\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n hSetBuffering stdin NoBuffering\r\n interact $ \r\n lines >>> (\\(nt:ls) -> (head $ words nt) : ls)\r\n >>> map read >>> solve >>> map show >>> unlines\r\n\r\ndata Query = Ask Int Int | Answer Int\r\n\r\ninstance Show Query where\r\n show (Ask l r) = \"? \" ++ show l ++ \" \" ++ show r\r\n show (Answer x) = \"! \" ++ show x\r\n\r\nsolve :: [Int] -> [Query]\r\nsolve (n:k:rs) = go 1 n rs\r\n where\r\n go lo hi xs\r\n | lo == hi = [Answer lo]\r\n | otherwise = let mid = (lo + hi) `div` 2 \r\n in (Ask 1 mid) : \r\n (if head xs + k > mid then go (mid + 1) hi else go lo mid) (tail xs)\r\n"}], "negative_code": [], "src_uid": "3cd1dac814fc53c094cc56dcd14d8ce9"} {"source_code": "import Data.Word\nimport qualified Data.IntMap as M\n\nmain =\n interact\n $ show\n . snd\n . foldr\n ( \\x (m, a) ->\n ( M.insertWith (+) x 1 m\n , (+ a) . sum . map (flip (M.findWithDefault 0) m)\n $ takeWhile (> 0) [2 ^ k - x | k <- [30, 29 ..]])\n ) (M.empty, 0 :: Word64)\n . tail\n . map read\n . words\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nimport qualified Data.Map.Strict as Map\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tas <- getList\n\tlet m = foldl' ( \\m a -> Map.insertWith (+) a 1 m ) Map.empty as\n\tprint $ sum $ solve m as\n\nsolve _ [a] = [0]\nsolve m (a:as) = res : solve nm as\n\twhere\n\tnm = Map.adjust pred a m\n\tf = fromMaybe 0 . flip Map.lookup nm\n\tres = sum $ map f [ pow 2 k - a | k <- [ 0 .. 32 ] ]\n\t\t\npow _ 0 = 1\npow a k = a * pow a ( k - 1 ) \n"}, {"source_code": "import Data.Word\nimport qualified Data.IntMap as M\n\nmain =\n getContents\n >>= print\n . snd\n . foldr\n ( \\x (m, a) ->\n ( M.insertWith (+) x 1 m\n , (+ a) . sum . map (flip (M.findWithDefault 0) m)\n $ takeWhile (> 0) [2 ^ k - x | k <- [31, 30 ..]])\n ) (M.empty :: M.IntMap Word64, 0)\n . tail\n . map read\n . words\n"}, {"source_code": "import Data.Int\nimport Data.List\nimport qualified Data.IntMap as M\n\nmain =\n getContents\n >>= print\n . snd\n . foldl'\n ( \\(m, a) x ->\n ( M.insertWith (+) x 1 m\n , (+ a) . sum . map (flip (M.findWithDefault 0) m)\n $ takeWhile (> 0) [2 ^ k - x | k <- [31, 30 ..]])\n ) (M.empty :: M.IntMap Int64, 0)\n . tail\n . map read\n . words\n"}, {"source_code": "import Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as M\n\nmain =\n getContents\n >>= print\n . snd\n . foldl'\n ( \\(m, a) x ->\n ( M.insertWith (+) x 1 m\n , (+ a) . sum . map (flip (M.findWithDefault 0) m)\n $ takeWhile (> 0) [2 ^ k - x | k <- [31, 30 ..]])\n ) (M.empty :: M.Map Int Int64, 0 :: Int64)\n . tail\n . map read\n . words\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ntoint :: String -> Integer\ntoint = read\n\ncounter a = foldl' (\\s x -> Map.insertWith (+) x 1 s) Map.empty a\n\nmain = getLine >> getLine >>= print . solve . map toint . words\n\nsolve a = sum [f x p | x <- a, p <- [2 ^ i | i <- [0 .. 30]]] `quot` 2\n where\n cnt = counter a\n get = fromMaybe 0 . flip Map.lookup cnt\n f x p = let y = p - x in if x == y then get y - 1 else get y\n \n"}, {"source_code": "import Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\nimport Data.Bits\n\nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\nfast_read_Int64 = fmap (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) BS.getLine :: IO [Int64]\n\ncitesc_nr :: String -> Int64\ncitesc_nr s = read s\n\n--insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a\nf :: Map.Map Int64 Int64 -> Int64 -> Map.Map Int64 Int64\nf book x = Map.insertWith (+) x 1 book\n\nmain = do\n x <- getLine\n let n = citesc_nr x\n array <- fast_read_Int64\n let map_freq = foldl f Map.empty array:: Map.Map Int64 Int64\n print $ solve map_freq array\n\nsolve :: Map.Map Int64 Int64 -> [Int64] -> Int64\nsolve map_frec keys = (sum $ map calc' keys) `div` 2 where\n calc' keys = sum $ map (calc keys) [1..30] :: Int64\n calc x i \n | complement <= 0 = 0 \n | complement `Map.notMember` map_frec = 0\n | complement == x = (map_frec Map.! complement) - 1\n | otherwise = map_frec Map.! complement\n where complement = bit i - x\n "}, {"source_code": "import qualified Data.IntMap as M\nimport Data.Word\ntype Bag = M.IntMap Int\npowersOfTwo = map (2^) [0..30]\nadd :: Int -> (Word64, Bag) -> (Word64, Bag)\nadd x (s, b) = (s + fromIntegral q, M.insertWith (const (+1)) x 1 b) \n where q = sum . map (\\k -> M.findWithDefault 0 k b) $ map (subtract x) powersOfTwo\nsolve :: [Int] -> Word64 \nsolve = fst . foldr add (0, M.empty)\nmain = getLine >> getLine >>= putStrLn . show . solve . map read . words"}, {"source_code": "import Data.Maybe\n--import Data.Array\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n n <- getInt\n ns <- getInts\n let book = foldl mkBook Map.empty ns :: Map.Map Int Int\n print $ solve book ns\n\nmkBook book x = Map.insertWith (+) x 1 book\n\nsolve :: Map.Map Int Int -> [Int] -> Integer\nsolve book xs = (sum $ map numSoln xs) `div` 2 where\n numSoln x = sum $ map (fromIntegral . calc x) [1..30] :: Integer\n calc x pos\n | goal <= 0 = 0\n | goal `Map.notMember` book = 0\n | goal == x = (book Map.! goal) - 1\n | otherwise = book Map.! goal\n where goal = bit pos - x"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.Array\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n n <- getInt\n ns <- sort `fmap` getInts\n let (is_pow2, not_pow2) = partition pow2 ns\n let len = length is_pow2\n let ns' = listArray (1,n) not_pow2 :: Array Int Int\n print $ ((len * (len - 1)) `div` 2) + length (solve ns' (length not_pow2))\n\npow2 :: Int -> Bool\npow2 x = (x .&. (x-1)) == 0\n\nsolve :: Array Int Int -> Int -> [Int]\nsolve ns n = filter pow2 [(ns ! i) + (ns ! j) | i <- [1..n], j <- [i+1..n]]"}, {"source_code": "import Data.Maybe\nimport Data.Array\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n n <- getInt\n ns <- sort `fmap` getInts\n let (is_pow2, not_pow2) = partition pow2 ns\n let len = length is_pow2\n let ns' = listArray (1,n) not_pow2 :: Array Int Int\n print $ len * (len - 1) + length (solve ns' (length not_pow2))\n\npow2 :: Int -> Bool\npow2 x = (x .&. (x-1)) == 0\n\nsolve :: Array Int Int -> Int -> [Int]\nsolve ns n = filter pow2 [(ns ! i) + (ns ! j) | i <- [1..n], j <- [i+1..n]]"}, {"source_code": "import Data.Maybe\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as Map\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n n <- getInt\n ns <- getInts\n let book = foldl mkBook Map.empty ns :: Map.Map Int Int\n print $ solve book ns\n\nmkBook book x = Map.insertWith (+) x 1 book\n\nsolve :: Map.Map Int Int -> [Int] -> Int\nsolve book xs = (sum $ map numSoln xs) `div` 2 where\n numSoln x = sum $ map (calc x) [1..30]\n calc x pos\n | goal <= 0 = 0\n | goal `Map.notMember` book = 0\n | goal == x = (book Map.! goal) - 1\n | otherwise = book Map.! goal\n where goal = bit pos - x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nimport qualified Data.Map.Strict as Map\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tas <- getList\n\tlet m = foldl' ( \\m a -> Map.insertWith (+) a 1 m ) Map.empty as\n\tprint $ sum $ solve m as\n\nsolve _ [a] = [0]\nsolve m (a:as) = res : solve nm as\n\twhere\n\tnm = Map.insertWith (-) a 1 m\n\tf = fromMaybe 0 . flip Map.lookup nm\n\tres = sum $ map f [ pow 2 k - a | k <- [ 0 .. 32 ] ]\n\t\t\npow _ 0 = 1\npow a k = a * pow a ( k - 1 ) \n"}, {"source_code": "import qualified Data.Set as S\n\nmain = do\n xs <- fmap (tail . map read . words) getContents\n let s = S.fromList xs\n print . (`div` 2) . length $ filter id [y `S.member` s | x <- xs, y <- takeWhile (> 0) [x - 2 ^ k | k <- [0 :: Int ..]]]\n"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\nmain =print (maxBound :: Int)\n {-getContents\n >>= print\n . snd\n . foldl'\n ( \\(m, a) x ->\n ( M.insertWith (+) x 1 m\n , (+ a) . sum . map (flip (M.findWithDefault 0) m)\n $ takeWhile (> 0) [2 ^ k - x | k <- [31, 30 ..]])\n ) (M.empty :: M.Map Int Int, 0)\n . tail\n . map read\n . words-}\n"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\nmain =\n getContents\n >>= print\n . snd\n . foldl'\n ( \\(m, a) x ->\n ( M.insertWith (+) x 1 m\n , (+ a) . sum . map (flip (M.findWithDefault 0) m)\n $ takeWhile (> 0) [2 ^ k - x | k <- [31, 30 ..]])\n ) (M.empty :: M.Map Int Int, 0)\n . tail\n . map read\n . words\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ntoint :: String -> Int\ntoint = read\n\ncounter a = foldl' (\\s x -> Map.insertWith (+) x 1 s) Map.empty a\n\nmain = getLine >> getLine >>= print . solve . map toint . words\n\nsolve :: [Int] -> Int\nsolve a = sum [f x p | x <- a, p <- [2 ^ i | i <- [0 .. 30]]] `quot` 2\n where\n cnt = counter a\n get = fromMaybe 0 . flip Map.lookup cnt\n f x p = let y = p - x in if x == y then get y - 1 else get y\n \n"}, {"source_code": "import qualified Data.IntMap as M\ntype Bag = M.IntMap Int\npowersOfTwo = map (2^) [0..30]\nadd :: Int -> (Int, Bag) -> (Int, Bag)\nadd x (s, b) = (s + q, M.insertWith (const . (+1)) x 1 b) \n where q = sum . map (\\k -> M.findWithDefault 0 k b) $ map (subtract x) powersOfTwo\nsolve :: [Int] -> Int\nsolve = fst . foldr add (0, M.empty)\nmain = getLine >> getLine >>= putStrLn . show . solve . map read . words"}, {"source_code": "import qualified Data.IntMap as M\ntype Bag = M.IntMap Int\npowersOfTwo = map (2^) [0..30]\nadd :: Int -> (Int, Bag) -> (Int, Bag)\nadd x (s, b) = (s + q, M.insertWith (const (+1)) x 1 b) \n where q = sum . map (\\k -> M.findWithDefault 0 k b) $ map (subtract x) powersOfTwo\nsolve :: [Int] -> Int\nsolve = fst . foldr add (0, M.empty)\nmain = getLine >> getLine >>= putStrLn . show . solve . map read . words"}], "src_uid": "b812d2d3a031dadf3d850605d2e78e33"} {"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\nresult :: [String] -> [String]\r\nresult list \r\n\t| i0 == i1 && i0 > 0 = add0 (i0-1, j0) $ add0 (i0-1, j1) list\r\n\t| i0 == 0 && i1 == 0 = add0 (1, j0) $ add0 (1, j1) list\r\n\t| j0 == j1 && j0 > 0 = add0 (i1, j0-1) $ add0 (i0, j1-1) list\r\n\t| j0 == 0 && j1 == 0 = add0 (i1, 1) $ add0 (i0, 1) list\r\n\t| otherwise = add0 (i1, j0) $ add0 (i0, j1) list\r\n\twhere\r\n\t\t[(i0, j0), (i1, j1)] = foldr aux0 [] $ zip [0..] list\r\n\t\taux0 (i, str) list = (foldr (aux1 i) list $ zip [0..] str)\r\n\r\n\t\taux1 i (j, c) l = if c == '*' then (i, j):l else l\r\n\r\n\t\tadd0 (0, j) (x:xs) = (add1 j x) : xs\r\n\t\tadd0 (i, j) (x:xs) = x : add0 (i-1, j) xs\r\n\r\n\t\tadd1 0 (x:xs) = '*' : xs\r\n\t\tadd1 j (x:xs) = x : add1 (j-1) xs\r\n\r\nshowR :: [String] -> String\r\nshowR (x:xs) = x ++ \"\\n\" ++ showR xs\r\nshowR [] = \"\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\tlet loop1 n = if n == 0 then return [] else do \r\n\t\tl <- getLine \r\n\t\tl' <- loop1 $ n - 1\r\n\t\treturn $ l : l'\r\n\r\n\tlet loop0 t = if t==0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Int\r\n\t\tloop1 n >>= putStr . showR . result\r\n\t\tloop0 $ t - 1\r\n\r\n\tloop0 t\r\n\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Data.Functor\nimport Control.Monad\nimport Data.Foldable\n\nmain :: IO ()\nmain = do\n contents <- getContents\n let inputs = map mungeSquare . mungeInput $ contents\n for_ inputs \\input@(size,_,_) ->\n let (rc1', rc2') = f input in\n putStr $ showSquare size rc1' rc2'\n\nmungeInput :: String -> [[String]]\nmungeInput = go . tail . lines where\n go (a:rest) = square : go rest' where\n (square, rest') = splitAt (read a) rest\n go _ = []\n\n-- Row/column coordinates\nmungeSquare :: [String] -> (Int, (Int, Int), (Int, Int)) -- (size, (r1, c1), (r2, c2))\nmungeSquare s = (length s, star1, star2)\n where\n (star1, star2) = case stars of\n [s1, s2] -> (s1, s2)\n _ -> error \"No stars found\"\n stars = do\n (r, row) <- zip [1..] s\n (c, cell) <- zip [1..] row\n guard (cell == '*')\n pure (r, c)\n\nshowSquare :: Int -> (Int, Int) -> (Int, Int) -> String\nshowSquare size (r1, c1) (r2, c2) = unlines $\n [1 .. size] <&> \\r ->\n [1 .. size] <&> \\c ->\n if (r == r1 || r == r2) && (c == c1 || c == c2)\n then '*' else '.'\n\n-- (r1, c1) and (r2, c2) are guaranteed to be distinct.\n-- (r1, c1) and (r2, c2) are lexicographically ordered.\nf :: (Int, (Int, Int), (Int, Int)) -> ((Int, Int), (Int, Int))\nf (size, (r1, c1), (r2, c2))\n | r1 /= r2 && c1 /= c2 = ((r1, c1), (r2, c2))\n\n -- e.g.\n -- . . . .\n -- . * * .\n -- . . . .\n -- . . . .\n | r1 == r2 = if\n | r1 == 1 -> ((r1, c1), (2, c2))\n | r1 > 1 -> ((1, c1), (r2, c2))\n\n -- e.g.\n -- . . . .\n -- . * . .\n -- . * . .\n -- . . . .\n | c1 == c2 = if\n | c1 == 1 -> ((r1, c1), (r2, 2))\n | c1 > 1 -> ((r1, 1), (r2, c2))\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\nimport Data.List\nimport Control.Monad\n\nposStr n lst = posBuild 0 0 \"\" []\n where\n posBuild x y line result\n | y == n = reverse result\n | x == n = posBuild 0 (y + 1) \"\" (reverse line : result)\n | (x, y) `elem` lst = posBuild (x + 1) y ('*' : line) result\n | otherwise = posBuild (x + 1) y ('.' : line) result\n\nposAdd pos@[(x0, y0), (x1, y1)]\n | x0 > x1 && y0 < y1 = pos ++ [(x0, y1), (x1, y0)]\n | x0 == x1 && x0 == 0 = pos ++ [(x0 + 1, y0), (x0 + 1, y1)]\n | y0 == y1 && y0 == 0 = pos ++ [(x0, y0 + 1), (x1, y0 + 1)]\n | x0 == x1 = pos ++ [(x0 - 1, y0), (x0 - 1, y1)]\n | y0 == y1 = pos ++ [(x0, y0 - 1), (x1, y0 - 1)]\n | otherwise = pos ++ [(x0, y1), (x1, y0)]\n\nposParser lst = innerx lst 0 []\n where\n innerx [] _ result = result\n innerx (x0:xs) y result =\n let addResult = map (, y) $ '*' `elemIndices` x0 in\n innerx xs (y + 1) (result ++ addResult)\n\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n m <- read <$> getLine\n lst <- replicateM m getLine\n mapM_ putStrLn $ posStr m $ posAdd $ posParser lst\n"}], "negative_code": [{"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\nresult :: [String] -> [String]\r\nresult list = add0 (i1, j0) $ add0 (i0, j1) list where\r\n\t[(i0, j0), (i1, j1)] = foldr aux0 [] $ zip [0..] list\r\n\taux0 (i, str) list = (foldr (aux1 i) list $ zip [0..] str)\r\n\r\n\taux1 i (j, c) l = if c == '*' then (i, j):l else l\r\n\r\n\tadd0 (0, j) (x:xs) = (add1 j x) : xs\r\n\tadd0 (i, j) (x:xs) = x : add0 (i-1, j) xs\r\n\r\n\tadd1 0 (x:xs) = '*' : xs\r\n\tadd1 j (x:xs) = x : add1 (j-1) xs\r\n\r\nshowR :: [String] -> String\r\nshowR (x:xs) = x ++ \"\\n\" ++ showR xs\r\nshowR [] = \"\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\tlet loop1 n = if n == 0 then return [] else do \r\n\t\tl <- getLine \r\n\t\tl' <- loop1 $ n - 1\r\n\t\treturn $ l : l'\r\n\r\n\tlet loop0 t = if t==0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Int\r\n\t\tloop1 n >>= putStr . showR . result\r\n\t\tloop0 $ t - 1\r\n\r\n\tloop0 t\r\n\r\n"}], "src_uid": "d8fb3822b983b8a8ffab341aee74f56f"} {"source_code": "solve :: Int -> Int\nsolve n = 1 + div n 2\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve . read) . tail . words)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tprint$ (+1) $ div x 2\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n print $ n `div` 2 + 1\n"}, {"source_code": "module Main where\n \n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Integer\n print $ n `div` 2 + 1\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter (n - 1)\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Integer)"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tprint $ x-1\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tprint$ (+1) $ div (x+1) 2\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "src_uid": "eb39ac8d703516c7f81f95a989791b21"} {"source_code": "-- Bartosz Bednarczyk\n\nimport Control.Monad\n\nsolve :: [Int] -> [ [Int] ] -> Int\nsolve xs ys = foldr (+) 0 $ map (\\[x,y] -> min (xs !! (x-1)) (xs !! (y-1)) ) ys\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do\n [n, m] <- readInts\n xs <- readInts \n ys <- replicateM (read (show m)) readInts\n putStrLn $ show $ solve xs ys\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n vs <- getInts\n es <- replicateM m getInts\n\n let vsa = listArray (1, n) vs\n\n print $ sum $ map (\\[u, v] -> min (vsa!u) (vsa!v)) es\n"}, {"source_code": "convert_edges :: [Integer] -> [(Int, Int)] -> [(Int, Int)]\nconvert_edges weight edges =\n map (\\(u, v) -> if (weight !! u > weight !! v) then (u, v) else (v, u)) edges\n\nsolve :: [Integer] -> [(Int, Int)] -> Integer\nsolve weight edges = iter $ convert_edges weight edges\n where\n iter :: [(Int, Int)] -> Integer\n iter rem\n | null rem = 0\n | otherwise = (weight !! (snd $ head rem)) + (iter $ tail rem)\n\n\nmain = do\n contents <- getContents\n let\n buf = lines contents\n [n, m] = map (read :: String -> Int) $ words $ head buf\n weight = -1:(map (read :: String -> Integer) $ words $ head $ tail buf)\n edges = map ((\\[u, v] -> (u, v)) . (map (read :: String -> Int)) . words) (tail $ tail buf)\n in putStrLn $ show $ solve weight edges\n"}, {"source_code": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor\nimport Data.Maybe\nimport Data.Traversable\nimport Text.Printf (printf)\n\nimport Prelude hiding (sum)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\n-----\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n vs <- listArray (1, n) <$> getInts :: IO (UArray Int Int)\n cs <- replicateM m $ do\n [f, t] <- getInts\n return $ min (vs!f) (vs!t)\n print $ sum cs\n"}], "negative_code": [], "src_uid": "2e6bf9154d9da6ac134b52144d5322ca"} {"source_code": "split :: Int -> (Int, Int, Int)\nsplit 3 = (1, 1, 1)\nsplit x\n | x `mod` 3 == 0 = (1, 1, x - 2)\n | otherwise = (1, 2, x - 3)\n\nmain :: IO ()\nmain = do\n x <- (fmap read getLine) :: IO Int\n let (a, b, c) = split x\n putStrLn $ show a ++ \" \" ++ show b ++ \" \" ++ show c\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Control.Applicative\nimport Control.Arrow\nimport Data.List\nimport Data.Array\nimport Data.Array.IO.Safe\nimport Data.Array.ST.Safe\nimport Data.IORef\nimport Data.STRef\nimport Data.Maybe\nimport Data.Bits\nimport Data.Ord\nimport Data.Ratio\nimport Data.Int\nimport Data.Char\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as Set\nimport qualified Data.Sequence as Sq\nimport Data.Tuple\nimport Data.Function\nimport Text.Printf\n--import Debug.Trace\nimport Numeric\n\nreadIntBS = fst . fromJust . BS.readInt\n\ninfixr 1 ?\n(?) :: Bool -> (a,a) -> a\n(?) b t = (if b then fst else snd) t\n\n\nmain = do\n n <- readLn :: IO Int\n\n printf \"%d %d %d\\n\" (1::Int) (1+(if (n-2)`mod`3==0 then 1 else 0) :: Int) (n-2-(if (n-2)`mod`3==0 then 1 else 0))\n"}, {"source_code": "main = do\n e1<-getLine\n let x=read e1::Integer\n a=1\n b= if (x-2) `mod` 3==0 then 2 else 1\n c=x-a-b\n putStrLn $ show(a)++\" \"++show(b)++\" \"++show(c)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = sol <$> readLn >>= put\n\nput = putStrLn . unwords . fmap show\n\nsol n \n | n `mod` 3==0 = [1,1,n-2] \n | otherwise = [1,2,n-3]"}, {"source_code": "main = interact $ unwords . map show . solve . read\nsolve n = case n `mod` 9 of\n 0 -> [d-1,d-1,d+2]\n 1 -> [d-2,d-1,d+4]\n 2 -> [d-1,d-1,d+4]\n 3 -> [d ,d ,d ]\n 4 -> [d ,d ,d+1]\n 5 -> [d ,d+1,d+1]\n 6 -> [d ,d ,d ]\n 7 -> [d-1,d ,d+2]\n 8 -> [d ,d ,d+2]\n where d = n `div` 3\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n | mod n 3 <2 = do\n\t\t\t\tputStr \"1 1 \"\n\t\t\t\tputStrLn $ show (n-2)\n\t | otherwise = do\n\t\t\t\tputStr \"1 2 \"\n\t\t\t\tputStrLn $ show (n-3)\n\t\n\n\nmain = do\n\tn<- read <$> getLine ::IO Int\n\tprocess n\n\n\n"}, {"source_code": "main = do\n n <- readLn :: IO Integer\n putStrLn $ solve n\n\nsolve :: Integer -> String\nsolve n\n | mod (n-2) 3 > 0 = \"1 1 \" ++ show (n-2)\n | otherwise = \"1 2 \" ++ show (n-3)"}, {"source_code": "main = do\n n <- read `fmap` getLine :: IO Integer\n putStrLn $ foldl (++) \"\" $ map ((++ \" \") . show) $ solve n\n\n\nsolve :: Integer -> [Integer]\nsolve n\n | (n - 2) `mod` 3 /= 0 = [n-2, 1, 1]\n | otherwise = [n-3, 1, 2]"}, {"source_code": "process :: Int -> (Int, Int, Int)\nprocess n\n | m == 0 = (1,1,n-2)\n | otherwise = (1,2,n-3)\n where m = n `mod` 3\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n let (a,b,c) = process n\n putStrLn (show a ++ \" \" ++ show b ++ \" \" ++ show c)"}], "negative_code": [{"source_code": "main = do\n e1<-getLine\n let x=read e1::Int\n a=(x `div` 3)\n b=a\n c=x-a-b\n putStrLn $ show(a)++\" \"++show(b)++\" \"++show(c)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = sol <$> readLn >>= put\n\nput = putStrLn . unwords . fmap show\n\nsol n = [m,m,n-2*m] where m = n `div` 3"}, {"source_code": "main = interact $ unwords . map show . solve . read\nsolve n = case d `mod` 3 of\n 0 -> [d+2,d-1,d-1]\n 1 -> [d,d,d+1]\n 2 -> [d,d,d+2]\n where d = n `div` 3\n"}, {"source_code": "main = do\n n <- read `fmap` getLine :: IO Integer\n putStrLn $ foldl (++) \"\" $ map ((++ \" \") . show) $ solve n\n\n\nsolve :: Integer -> [Integer]\nsolve n\n | (n - 2 `mod` 3) /= 0 = [n-2, 1, 1]\n | otherwise = [n-3, 1, 2]"}, {"source_code": "main = do\n n <- read `fmap` getLine :: IO Integer\n putStrLn $ foldl (++) \"\" $ map ((++ \" \") . show) $ solve n\n\n\nsolve :: Integer -> [Integer]\nsolve n\n | n - 2 `mod` 3 /= 0 = [n-2, 1, 1]\n | otherwise = [n-3, 1, 2]"}], "src_uid": "91d5147fb602298e08cbdd9f86d833f8"} {"source_code": "import Data.List (foldl')\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve . map (toTuple . words) . tail . lines\n\nsolve :: [(String, String)] -> [(String, String)]\nsolve = M.toList . foldl' (\\m (a, b) -> M.insert b (M.findWithDefault a a m) $ M.delete a m) M.empty\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n\nprintSolution :: [(String, String)] -> IO ()\nprintSolution xs = print (length xs) >> mapM_ (\\(a, b) -> putStrLn $ b ++ \" \" ++ a) xs\n", "positive_code": [{"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map \nimport Control.Applicative\n\nmain = getContents >>= putStrLn . solve . tail . words\n\n\nsolve :: [String] -> String\nsolve rs = unlines $ [show $ Set.size s] ++ [upwrap (Map.lookup x m) ++ \" \" ++ x | x <- Set.toList s]\n where (s, m) = solve' $ reverse rs\n upwrap (Just x) = x\n\nsolve' :: [String] -> (Set.Set String, Map.Map String String)\nsolve' [] = (Set.empty, Map.empty)\nsolve' (y:x:rs) = (s', m')\n where (s, m) = solve' rs\n s' = Set.delete x . Set.insert y $ s\n m' = case Map.lookup x m of\n Nothing -> Map.insert y x m\n Just z -> Map.insert y z m\nsolve' _ = (Set.fromList [\"a\",\"b\"], Map.fromList [(\"a\",\"A\"), (\"b\",\"B\")])\n"}, {"source_code": "main = interact $ f [] . tail . words\nf m (a:b:c) = f (g m a b) c\nf m _ = unlines $ (show $ length m) : map unwords m\ng ([m,n]:o) a b | n == a = [m,b]:o | otherwise = [m,n]:g o a b\ng _ a b = [[a,b]]"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> (mapM_ C.putStrLn).solve =<< (forM [1..read n] $ \\ i ->C.getLine>>= \\js -> let [a,b] = C.words js in return $ (a,b) )\nsolve xs = let ms=slv1 (Map.empty) xs in [(C.pack $ show $ Map.size ms)] ++map (\\(a,b)-> C.unwords [b, a]) (Map.toList ms)\nslv1 ms [] = ms\nslv1 ms ((x1,x2):xs) = slv1 fm xs \n where\n fm= let m = Map.lookup x1 ms in if m == Nothing then Map.insert x2 x1 ms else Map.delete x1 $ Map.insert x2 (fromJust m) ms"}, {"source_code": "import qualified Data.Map.Strict as M\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- readLn :: IO Int\n ns <- replicateM n ( words <$> getLine )\n let as = foldl' (\\acc [k,v] -> let b = M.filter (==k) acc\n in if b == M.empty \n then M.insert k v acc\n else let (e,f) = head $ M.toList b in M.alter (\\_ -> Just v) e acc\n ) M.empty ns\n print $ M.size as\n mapM_ (putStrLn . uncurry (\\a b -> a ++ \" \" ++ b)) $ M.toList as "}, {"source_code": "import Data.List (foldl')\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve . map words . tail . lines\n\nsolve :: [[String]] -> [[String]]\nsolve = map (\\(b, a) -> [a, b]) . M.toList . foldl' (\\m [a, b] -> M.insert b (M.findWithDefault a a m) $ M.delete a m) M.empty\n\nprintSolution :: [[String]] -> IO ()\nprintSolution xs = print (length xs) >> mapM_ (putStrLn . unwords) xs\n"}], "negative_code": [], "src_uid": "bdd98d17ff0d804d88d662cba6a61e8f"} {"source_code": "import Data.List (elemIndex, delete)\naccess :: (Int, ([Int], [Int])) -> (Int, ([Int], [Int]))\naccess (res, (row, (q:qs))) = (res + pos, (q : (delete q row), qs))\n where pos = case elemIndex q row of Just x -> x + 1\nsolve :: [Int] -> [Int] -> Int\nsolve rs xs = fst . until (null . snd . snd) access $ (0, (rs, xs)) \nnorm = map read . words\nmain = do\n getLine\n row <- getLine\n queries <- getContents\n putStrLn . show $ solve (norm row) (norm queries)", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (delete)\n\nfindPos (x:xs) v ind\n | x == v = ind\n | otherwise = findPos xs v (ind+1)\n\n\nbuy xs v = (cost+1,xs')\n where\n cost = findPos xs v 0\n xs' = v : delete v xs\n\nprocess [] _ total = total\nprocess (o:orders) xs total = process orders xs' (total+cost)\n where\n (cost, xs') = buy xs o\n\nmain = do\n [n,m,k] <- map read . words <$> getLine :: IO [Int]\n xs <- map read . words <$> getLine :: IO [Int]\n \n aa <- replicateM n getLine\n let orders = map read $ concat $ map words aa :: [Int]\n \n print $ process orders xs 0\n"}, {"source_code": "import Data.List (elemIndex, delete)\nsolve :: [Int] -> [Int] -> Int\nsolve _ [] = 0\nsolve xs (q:qs) = pos + solve (q : delete q xs) qs\n where pos = case elemIndex q xs of Just p -> p + 1\nmain = do\n getLine\n row <- getLine\n queries <- getContents\n putStrLn . show $ solve (norm row) (norm queries)\n where norm = map read . words"}], "negative_code": [], "src_uid": "39fd7843558ed2aa6b8c997c2b8a1fad"} {"source_code": "import Prelude hiding (lookup)\nimport Data.Char\nimport Data.List hiding (lookup)\nimport Data.Map (fromList, insertWith, lookup)\nimport System.IO\n \nfromJust :: Maybe a -> a\nfromJust (Just a) = a\nfromJust _ = undefined\n \ngetWord' :: String -> IO (String)\ngetWord' \"\" = do ch <- getChar ; eof <- isEOF\n if eof then return \"\" else if isSpace ch then getWord' \"\" else getWord' [ch]\ngetWord' chs = do ch <- getChar ; eof <- isEOF\n if eof then return chs else if isSpace ch then return chs else getWord' (chs ++ [ch])\n \ngetWord = getWord' \"\"\n \ngetInt :: IO (Int)\ngetInt = fmap read getWord\n \ngetInts' 0 acc = return acc\ngetInts' n acc = do x <- getInt ; getInts' (n-1) (acc ++ [x])\n \ngetInts :: Int -> IO ([Int])\ngetInts n = getInts' n []\n \n-- SOLUTION\n \ncount xs = foldl f (fromList []) xs\n where f acc x = insertWith (+) x 1 acc\n \niter xs = map f xs\n where f x = fromJust (lookup x (count xs))\n \ndata Query = Query {\n posQuery :: Int\n , kQuery :: Int\n , idxQuery :: Int\n } deriving (Show)\n \ntype QResult = (Query, Int)\n \ngetQuery i n xs | i == n = return xs\ngetQuery i n xs = do\n idx <- getInt\n k <- getInt\n getQuery (i+1) n (xs ++ [Query i k (idx-1)])\n \n \ngetQueries = do\n q <- getInt\n getQuery 0 q []\n \n \n \nsortQueries qs f = sortBy compareQueries qs\n where compareQueries a b = compare (f a) (f b)\nsortByK qs = sortQueries qs kQuery\n \nsortResults qs = sortBy f qs\n where f (a, _) (b, _) = compare (posQuery a) (posQuery b) \n \ncalcQueries :: [Query] -> [Int] -> Int -> Int -> [QResult] -> [QResult]\ncalcQueries [] _ _ _ res = res\ncalcQueries (q:qs) xs k n res \n | (k == (kQuery q)) || (k >= n) = calcQueries qs xs k n (res ++ [(q, xs !! (idxQuery q))])\ncalcQueries qs xs k n res = calcQueries qs (iter xs) (k+1) n res\n \n \nputRes :: QResult -> IO ()\nputRes res = do putStrLn (show (snd res))\n \nforEach :: [a] -> (a -> IO ()) -> IO ()\nforEach [] _ = return ()\nforEach (x:xs) a = do a x; forEach xs a\n \n--2\nisqrt :: Int -> Int\nisqrt = floor . sqrt . fromIntegral\n \nmaxK n = 2 * (isqrt (2*n))\n \niterNums :: [[Int]] -> Int -> [[Int]]\niterNums rs target | ((length rs)-1) < target = iterNums (rs ++ [iter (last rs)]) target\niterNums rs target = rs\n \ngetRes :: [[Int]] -> Int -> Int -> Int\ngetRes rs idx k = (rs !! k) !! (idx-1)\n \ndoQuery :: [[Int]] -> Int -> Int -> IO ()\ndoQuery _ _ 0 = return ()\ndoQuery rs mK i = do\n idx <- getInt\n k <- getInt\n let nk = min k mK\n let nrs = iterNums rs nk\n putStrLn (show (getRes nrs idx nk))\n doQuery nrs mK (i-1)\n \nloop :: IO () -> Int -> IO ()\nloop a 0 = return ()\nloop a n = do a; loop a (n-1)\n \ndoTests 0 = return ()\ndoTests t = do\n n <- getInt\n nums <- getInts n\n q <- getInt\n doQuery [nums] (maxK n) q\n doTests (t-1)\n \n \nmain = do t <- getInt ; doTests t\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\nimport qualified Data.IntMap as Map\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain = do\r\n t <- readInt <$> BS.getLine\r\n forM_ [1 .. t] $ \\_ -> do\r\n _ <- BS.getLine\r\n xs <- map readInt . BS8.words <$> BS.getLine\r\n let xss = solve xs\r\n let lxss = length xss - 1\r\n q <- readInt <$> BS.getLine\r\n forM_ [1 .. q] $ \\_ -> do\r\n [xi, ki] <- map readInt . BS8.words <$> BS.getLine\r\n print $ (xss !! min lxss ki) !! (xi - 1)\r\n\r\nsolve :: [Int] -> [[Int]]\r\nsolve xs = do\r\n let freq = foldl (\\m x -> Map.insertWith (+) x 1 m) Map.empty xs\r\n let xs' = map (\\x -> fromJust (Map.lookup x freq)) xs\r\n if xs == xs' then [xs] else xs : solve xs'\r\n\r\nreadInt = fst . fromJust . BS8.readInt\r\n"}, {"source_code": "import Prelude hiding (lookup)\nimport Data.Char\nimport Data.List hiding (lookup)\nimport Data.Map (fromList, insertWith, lookup)\nimport System.IO\n\nfromJust :: Maybe a -> a\nfromJust (Just a) = a\nfromJust _ = undefined\n\ngetWord' :: String -> IO (String)\ngetWord' \"\" = do ch <- getChar ; eof <- isEOF\n if eof then return \"\" else if isSpace ch then getWord' \"\" else getWord' [ch]\ngetWord' chs = do ch <- getChar ; eof <- isEOF\n if eof then return chs else if isSpace ch then return chs else getWord' (chs ++ [ch])\n\ngetWord = getWord' \"\"\n\ngetInt :: IO (Int)\ngetInt = fmap read getWord\n\ngetInts' 0 acc = return acc\ngetInts' n acc = do x <- getInt ; getInts' (n-1) (acc ++ [x])\n\ngetInts :: Int -> IO ([Int])\ngetInts n = getInts' n []\n\n-- SOLUTION\n\ncount xs = foldl f (fromList []) xs\n where f acc x = insertWith (+) x 1 acc\n\niter xs = map f xs\n where f x = fromJust (lookup x (count xs))\n\ndata Query = Query {\n posQuery :: Int\n , kQuery :: Int\n , idxQuery :: Int\n } deriving (Show)\n\ntype QResult = (Query, Int)\n\ngetQuery i n xs | i == n = return xs\ngetQuery i n xs = do\n idx <- getInt\n k <- getInt\n getQuery (i+1) n (xs ++ [Query i k (idx-1)])\n\n\ngetQueries = do\n q <- getInt\n getQuery 0 q []\n\n\n\nsortQueries qs f = sortBy compareQueries qs\n where compareQueries a b = compare (f a) (f b)\nsortByK qs = sortQueries qs kQuery\n\nsortResults qs = sortBy f qs\n where f (a, _) (b, _) = compare (posQuery a) (posQuery b) \n\ncalcQueries :: [Query] -> [Int] -> Int -> Int -> [QResult] -> [QResult]\ncalcQueries [] _ _ _ res = res\ncalcQueries (q:qs) xs k n res \n | (k == (kQuery q)) || (k >= n) = calcQueries qs xs k n (res ++ [(q, xs !! (idxQuery q))])\ncalcQueries qs xs k n res = calcQueries qs (iter xs) (k+1) n res\n\n\nputRes :: QResult -> IO ()\nputRes res = do putStrLn (show (snd res))\n\nforEach :: [a] -> (a -> IO ()) -> IO ()\nforEach [] _ = return ()\nforEach (x:xs) a = do a x; forEach xs a\n\n--2\nisqrt :: Int -> Int\nisqrt = floor . sqrt . fromIntegral\n\nmaxK n = 2 * (isqrt (2*n))\n\niterNums :: [[Int]] -> Int -> [[Int]]\niterNums rs target | ((length rs)-1) < target = iterNums (rs ++ [iter (last rs)]) target\niterNums rs target = rs\n\ngetRes :: [[Int]] -> Int -> Int -> Int\ngetRes rs idx k = (rs !! k) !! (idx-1)\n\ndoQuery :: [[Int]] -> Int -> Int -> IO ()\ndoQuery _ _ 0 = return ()\ndoQuery rs mK i = do\n idx <- getInt\n k <- getInt\n let nk = min k mK\n let nrs = iterNums rs nk\n putStrLn (show (getRes nrs idx nk))\n doQuery nrs mK (i-1)\n\nloop :: IO () -> Int -> IO ()\nloop a 0 = return ()\nloop a n = do a; loop a (n-1)\n\ndoTests 0 = return ()\ndoTests t = do\n n <- getInt\n nums <- getInts n\n q <- getInt\n doQuery [nums] (maxK n) q\n doTests (t-1)\n\n\nmain = do t <- getInt ; doTests t\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype PII = (Int, Int)\n\ndata TC = TC {n :: Int, as :: [Int], qs :: [PII]}\n\ninput :: Scanner TC\ninput = do\n n <- int\n as <- n >< int\n qs <- numberOf (pair int int)\n return TC {..}\n\ntype Output = [Int]\n\noutput :: Output -> C.ByteString\noutput = map showB >>> C.unlines\n\ntype VI = UArray Int Int\n\nsolve :: TC -> Output\nsolve TC {..} = map query qs\n where\n it = 12\n ls = take it $ iterate step as\n\n query (x, k) = ls !! min k (it - 1) !! (x - 1)\n\n step :: [Int] -> [Int]\n step ai = map (fs !) ai\n where\n fs :: VI\n fs = accumArray (+) 0 (1, n) $ map (,1) ai\n\n is = 0\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [{"source_code": "import Prelude hiding (lookup)\nimport Data.Char\nimport Data.List hiding (lookup)\nimport Data.Map (fromList, insertWith, lookup)\nimport System.IO\n\nfromJust :: Maybe a -> a\nfromJust (Just a) = a\nfromJust _ = undefined\n\ngetWord' :: String -> IO (String)\ngetWord' \"\" = do ch <- getChar ; eof <- isEOF\n if eof then return \"\" else if isSpace ch then getWord' \"\" else getWord' [ch]\ngetWord' chs = do ch <- getChar ; eof <- isEOF\n if eof then return chs else if isSpace ch then return chs else getWord' (chs ++ [ch])\n\ngetWord = getWord' \"\"\n\ngetInt :: IO (Int)\ngetInt = fmap read getWord\n\ngetInts' 0 acc = return acc\ngetInts' n acc = do x <- getInt ; getInts' (n-1) (acc ++ [x])\n\ngetInts :: Int -> IO ([Int])\ngetInts n = getInts' n []\n\n-- SOLUTION\n\ncount xs = foldl f (fromList []) xs\n where f acc x = insertWith (+) x 1 acc\n\niter xs = map f xs\n where f x = fromJust (lookup x (count xs))\n\ndata Query = Query {\n posQuery :: Int\n , kQuery :: Int\n , idxQuery :: Int\n } deriving (Show)\n\ntype QResult = (Query, Int)\n\ngetQuery i n xs | i == n = return xs\ngetQuery i n xs = do\n idx <- getInt\n k <- getInt\n getQuery (i+1) n (xs ++ [Query i k (idx-1)])\n\n\ngetQueries = do\n q <- getInt\n getQuery 0 q []\n\n\n\nsortQueries qs f = sortBy compareQueries qs\n where compareQueries a b = compare (f a) (f b)\nsortByK qs = sortQueries qs kQuery\n\nsortResults qs = sortBy f qs\n where f (a, _) (b, _) = compare (posQuery a) (posQuery b) \n\ncalcQueries :: [Query] -> [Int] -> Int -> Int -> [QResult] -> [QResult]\ncalcQueries [] _ _ _ res = res\ncalcQueries (q:qs) xs k n res \n | (k == (kQuery q)) || (k >= n) = calcQueries qs xs k n (res ++ [(q, xs !! (idxQuery q))])\ncalcQueries qs xs k n res = calcQueries qs (iter xs) (k+1) n res\n\n\nputRes :: QResult -> IO ()\nputRes res = do putStrLn (show (snd res))\n\nforEach :: [a] -> (a -> IO ()) -> IO ()\nforEach [] _ = return ()\nforEach (x:xs) a = do a x; forEach xs a\n\n--2\nisqrt :: Int -> Int\nisqrt = floor . sqrt . fromIntegral\n\nmaxK n = 2 * (isqrt (2*n))\n\niterNums :: [[Int]] -> Int -> [[Int]]\niterNums rs target | ((length rs)-1) < target = iterNums (rs ++ [iter (head rs)]) target\niterNums rs target = rs\n\ngetRes :: [[Int]] -> Int -> Int -> Int\ngetRes rs idx k = (rs !! k) !! (idx-1) where l = length rs\n\ndoQuery :: [[Int]] -> Int -> Int -> IO ()\ndoQuery _ _ 0 = return ()\ndoQuery rs mK i = do\n idx <- getInt\n k <- getInt\n let nk = min k mK\n let nrs = iterNums rs nk\n putStrLn (show (getRes nrs idx nk))\n doQuery nrs mK (i-1)\n\nloop :: IO () -> Int -> IO ()\nloop a 0 = return ()\nloop a n = do a; loop a (n-1)\n\ndoTests 0 = return ()\ndoTests t = do\n n <- getInt\n nums <- getInts n\n q <- getInt\n doQuery [nums] (maxK n) q\n doTests (t-1)\n\n\nmain = do t <- getInt ; doTests t\n"}, {"source_code": "import Control.Monad (forM_)\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\nimport qualified Data.IntMap as Map\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain = do\r\n t <- readInt <$> BS.getLine\r\n forM_ [1 .. t] $ \\_ -> do\r\n _ <- BS.getLine\r\n xs <- map readInt . BS8.words <$> BS.getLine\r\n let xss = solve xs\r\n let lxss = length xss - 1\r\n q <- readInt <$> BS.getLine\r\n forM_ [1 .. q] $ \\_ -> do\r\n [xi, ki] <- map readInt . BS8.words <$> BS.getLine\r\n print $ (xss !! min lxss ki) !! (xi - 1)\r\n\r\nsolve :: [Int] -> [[Int]]\r\nsolve xs = do\r\n let freq = foldl (\\m x -> Map.insertWith (+) x 1 m) Map.empty xs\r\n let xs' = map (\\x -> fromJust (Map.lookup x freq)) xs\r\n if xs == xs' then [] else xs' : solve xs'\r\n\r\nreadInt = fst . fromJust . BS8.readInt\r\n"}], "src_uid": "43009fe44c2b5905c8160ac7ae9c595a"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sortBy (comparing (fst . fst)) (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort gen (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(c, t) -> show c ++ \" \" ++ show t) . elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort gen (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(c, t) -> show c ++ \" \" ++ show t) . elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort $ zip frogsIn [1..]\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest'' mosquitos)\n where\n (frog', rest'') = eat frog rest' mosqs\n where\n rest' = mosquito `Set.insert` rest\n\n mosqs = mosq:(Set.elems . snd $ Set.split mosq rest')\n where\n mosq = fromJust $ Set.lookupGE (Mosq x 0 0) rest'\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\nimport Control.Monad (when)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort gen (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\nimport System.IO hiding (getContents, getLine)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\n\ndata Frog = Frog { frogX :: !Int, frogY :: !Int, frogI :: !Int, frogC :: !Int, frogT :: !Int } deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n z = zipWith (\\frog y -> frog { frogX = max (frogX frog) (y+1) }) fs ys\n where\n fs = sort gen $ zipWith (\\(x, t) i -> Frog x (x+t) i 0 t) frogsIn [1..]\n ys = scanl max (-1) $ map frogY fs\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest' mosquitos)\n where\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n let a = elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n\n let unlines_ = mconcat . map (<> charUtf8 '\\n')\n hPutBuilder stdout $ unlines_ $ map (\\(c, t) -> intDec c <> charUtf8 ' ' <> intDec t) a\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy, sort)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\nimport System.IO hiding (getContents, getLine)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\n\ndata Frog = Frog { frogX :: !Int, frogY :: !Int, frogI :: !Int, frogC :: !Int, frogT :: !Int } deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort2 gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n z = zipWith (\\frog y -> frog { frogX = max (frogX frog) (y+1) }) fs ys\n where\n fs = sort $ zipWith (\\(x, t) i -> Frog x (x+t) i 0 t) frogsIn [1..]\n ys = scanl max (-1) $ map frogY fs\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest' mosquitos)\n where\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n let a = elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n\n let unlines_ = mconcat . map (<> charUtf8 '\\n')\n hPutBuilder stdout $ unlines_ $ map (\\(c, t) -> intDec c <> charUtf8 ' ' <> intDec t) a\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\nimport Control.Monad (when)\nimport Data.Array (elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n s <- readArray a $ (l + r) `div` 2\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort gen (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n\n frogsSet = Set.fromDistinctAscList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog { frogX :: !Int, frogY :: !Int, frogI :: !Int, frogC :: !Int, frogT :: !Int } deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n z = zipWith (\\frog y -> frog { frogX = max (frogX frog) (y+1) }) fs ys\n where\n fs = sort gen $ zipWith (\\(x, t) i -> Frog x (x+t) i 0 t) frogsIn [1..]\n ys = scanl max (-1) $ map frogY fs\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest' mosquitos)\n where\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(c, t) -> show c ++ \" \" ++ show t) . elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max (-1) $ map (\\((x, t), _) -> x + t) fs\n fs = sort gen (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest' mosquitos)\n where\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(c, t) -> show c ++ \" \" ++ show t) . elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max 0 $ map (\\((x, t), _) -> x + t) fs\n fs = sort (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x s) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog y y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max 0 $ map (\\((x, t), _) -> x + t) fs\n fs = sort (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x s) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y > y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y > x2 = ((Frog y y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max 0 $ map (\\((x, t), _) -> x + t) fs\n fs = sort (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y > y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y > x2 = ((Frog y y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n-- import Debug.Trace (trace)\n\ndata Frog = Frog !Int !Int !Int !Int !Int deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n es = scanl max 0 $ map (\\((x, t), _) -> x + t) fs\n fs = sort (zip frogsIn [1..])\n z = zipWith (\\((x, t), i) s -> Frog (max x (s+1)) (x + t) i 0 t) fs es\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos)\n | isNothing lookup = process frogs (mosquito `Set.insert` rest) mosquitos\n | otherwise = out ++ (process frogs'' rest' mosquitos)\n where\n -- d = trace (\"frogs = \" ++ (show frogs) ++ \" rest = \" ++ (show rest) ++ \" mosq = \" ++ (show mosquito))\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n -- d = trace (\"ms = \" ++ show (mosquito:mosqs) ++ \" frog = \" ++ show frog)\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sort, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\ndata Frog = Frog { frogX :: !Int, frogY :: !Int, frogIndex :: !Int, frogCount :: !Int, frogT :: !Int } deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nmain = do\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n z = zipWith (\\frog y -> frog { frogY = max (frogY frog) (y+1) }) fs ys\n where\n ys = scanl max (-1) $ map frogY fs\n fs = sortBy (comparing frogX) $ zipWith (\\(x, t) i -> Frog x (x+t) i 0 t) frogsIn [1..]\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest'' mosquitos)\n where\n (frog'@(Frog _ y _ _ _), rest'') = eat frog rest' mosqs\n where\n rest' = mosquito `Set.insert` rest\n\n mosqs = mosq:(Set.elems . snd $ Set.split mosq rest')\n where\n mosq = fromJust $ Set.lookupGE (Mosq x 0 0) rest'\n\n eat frog rest [] = (frog, rest)\n eat frog@(Frog x y i c t) rest (mosq@(Mosq p b _):mosqs)\n | y < p = (frog, rest)\n | otherwise = eat frog' rest' mosqs\n where\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(Frog _ _ _ c t) -> show c ++ \" \" ++ show t) $ sortBy (comparing (\\(Frog _ _ i _ _) -> i)) result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (getLine, getContents, lines, readInt, words)\nimport Data.List (partition, sortBy)\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Ord (comparing)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Prelude hiding (getLine, lines, words)\n\nimport Control.Monad (when)\nimport Data.Array (array, elems)\nimport Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport System.Random\n\ndata Frog = Frog { frogX :: !Int, frogY :: !Int, frogI :: !Int, frogC :: !Int, frogT :: !Int } deriving (Show)\n\ninstance Eq Frog where\n Frog x _ _ _ _ == Frog y _ _ _ _ = x == y\ninstance Ord Frog where\n Frog x _ _ _ _ <= Frog y _ _ _ _ = x < y\n\ndata Mosq = Mosq !Int !Int !Int deriving (Show)\n\ninstance Eq Mosq where\n Mosq _ _ i == Mosq _ _ j = i == j\ninstance Ord Mosq where\n Mosq x _ i <= Mosq y _ j = (x, i) <= (y, j)\n\ngetInts = map (fst . fromJust . readInt) . words <$> getLine\ngetPair = (\\[a, b] -> (a, b)) <$> getInts\n\nsort gen xs = elems $ runSTArray $ do\n let n = length xs\n a <- newListArray (1, n) xs\n gr <- newSTRef gen\n\n let sort' l r = when (l < r) $ do\n g <- readSTRef gr\n let (x, g') = randomR (l, r-1) g\n writeSTRef gr g'\n\n s <- readArray a x\n\n let loop i j \n | i > j = return (i, j)\n | otherwise = do\n ai <- readArray a i\n aj <- readArray a j\n case () of\n _ | ai < s -> loop (i+1) j\n | aj > s -> loop i (j-1)\n | otherwise -> do\n writeArray a i aj\n writeArray a j ai\n loop (i+1) (j-1)\n\n\n (i, j) <- loop l r\n\n sort' l j\n sort' i r\n\n sort' 1 n\n return a\n\nmain = do\n gen <- newStdGen\n\n [n, m] <- getInts\n frogsIn <- replicateM n getPair\n mosquitosIn <- replicateM m getPair\n\n let\n result = out ++ (process frogsSet Set.empty mosquitos)\n where\n (frogs, out) = partition (\\(Frog a b _ _ _) -> a <= b) z\n where\n z = zipWith (\\frog y -> frog { frogY = max (frogY frog) (y+1) }) fs ys\n where\n fs = sort gen $ zipWith (\\(x, t) i -> Frog x (x+t) i 0 t) frogsIn [1..]\n ys = scanl max (-1) $ map frogY fs\n\n frogsSet = Set.fromList frogs\n\n mosquitos = zipWith (\\(p, b) i -> Mosq p b i) mosquitosIn [1..]\n\n process :: Set Frog -> Set Mosq -> [Mosq] -> [Frog]\n process frogs _ [] = Set.elems frogs\n process frogs rest (mosquito@(Mosq p b _):mosquitos) = process' lookup\n where\n lookup = Set.lookupLE (Frog p 0 0 0 0) frogs >>= (\\frog@(Frog _ y _ _ _) -> if p <= y then Just frog else Nothing)\n\n process' Nothing = process frogs (mosquito `Set.insert` rest) mosquitos\n process' (Just frog@(Frog x _ _ _ _)) = out ++ (process frogs'' rest' mosquitos)\n where\n (frog', rest') = eat frog rest (mosquito:mosqs)\n where\n frog@(Frog x _ _ _ _) = fromJust lookup\n\n mosqs = (case lookup of\n Nothing -> []\n Just mosq -> mosq:(Set.elems . snd $ Set.split mosq rest)\n )\n where lookup = Set.lookupGE (Mosq x 0 0) rest\n\n eat frog@(Frog x y i c t) rest mosqs\n | null mosqs || y < p = (frog, rest)\n | otherwise = eat frog' rest' $ tail mosqs\n where\n mosq@(Mosq p b _) = head mosqs\n frog' = Frog x (y+b) i (c+1) (t+b)\n rest' = mosq `Set.delete` rest\n\n (frogs'', out) = clean frogs' [] frogsList\n where\n frogs' = frog' `Set.insert` frogs\n frogsList = Set.elems . snd $ Set.split frog' frogs'\n\n Frog _ y _ _ _ = frog'\n\n clean frogs out [] = (frogs, out)\n clean frogs out (frog@(Frog x2 y2 i c t):frogsList)\n | y >= y2 = clean (frog `Set.delete` frogs) (frog:out) frogsList\n | y >= x2 = ((Frog (y+1) y2 i c t) `Set.insert` (frog `Set.delete` frogs), out)\n | otherwise = (frogs, out)\n\n putStr . unlines . map (\\(c, t) -> show c ++ \" \" ++ show t) . elems . array (1, n) $ map (\\(Frog _ _ i c t) -> (i, (c, t))) result\n"}], "src_uid": "423a8a3cf6b26c1230a52cc3a1612afd"} {"source_code": "import Control.Monad\nimport Data.List\n\nremerge :: [Int] -> [Int] -> [Int] -> [Int]\nremerge [] [] [] = []\nremerge (a:as) (1:los) unls = a : remerge as los unls\nremerge (_:as) (0:los) (v:unls) = v : remerge as los unls\nremerge _ _ _ = error \"huh?\"\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n lo <- map read . words <$> getLine\n let\n unls = reverse $ sort [v | (v, 0) <- zip a lo]\n ans = remerge a lo unls\n putStrLn . unwords $ map show ans\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Foldable\nimport Data.Graph\n\n-- Split a list in half, with both halves in order\nhalf :: [a] -> ([a], [a])\nhalf = join go\n where\n go t [] = ([], t)\n go t [_] = ([], t)\n go (t : ts) (_ : _ : hs) = (t : front, rear)\n where\n (front, rear) = go ts hs -- Interesting laziness\n\nmerge :: Ord a => [a] -> [a] -> [a]\nmerge [] ys = ys\nmerge xs [] = xs\nmerge xxs@(x : xs) yys@(y : ys)\n | x <= y = x : merge xs yys\n | otherwise = y : merge xxs ys\n\nmsort :: Ord a => [a] -> [a]\nmsort [] = []\nmsort [x] = [x]\nmsort xs = merge (msort front) (msort rear)\n where\n (front, rear) = half xs\n\nreadInput :: IO (Int, [Int], [Int])\nreadInput = do\n n <- read <$> getLine\n arr <- map read . words <$> getLine\n lock <- map read . words <$> getLine\n return (n, arr, lock)\n\nsolve (n, arr, lock) =\n snd $\n foldl\n ( \\(j, str) i ->\n if (l ! i) == 0\n then (j + 1, (s' ! j) : str)\n else (j, (a ! i) : str)\n )\n (1, [])\n [1 .. n]\n where\n a = array (1, n) $ zip [1 .. n] arr\n l = array (1, n) $ zip [1 .. n] lock\n s' = array (1, length s) $ zip [1 .. length s] s\n s = reverse $ msort $ map (\\(a, b) -> b) $ filter (\\(a, b) -> a == 0) (zip lock arr)\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n i <- readInput\n let r = solve i\n putStrLn $ foldl (\\s x -> show x ++ \" \" ++ s) \"\" r"}], "negative_code": [], "src_uid": "9ef180b33717e4d6a21b4c5bb855e15b"} {"source_code": "module Main where\n\nmain\n = interact $ solve . map (read::String->Integer) . tail . words\n\nsolve list\n = process $ combine list\n where\n combine [] = []\n combine (x:b:rest) = (x,b) : combine rest\n\nprocess list\n | any (\\((x1,b1),(x2,b2))->x1+b1==x2 && x2+b2==x1) product\n = \"YES\\n\"\n | otherwise\n = \"NO\\n\"\n where\n product = [(a,b) | a<-list, b<-list]\n", "positive_code": [{"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM n getA\n\tputStr $ last $ \"NO\":[\"YES\" | [x,d] <- a, [y,t] <- a, x+d==y, y+t==x]\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM n getA\n\tputStr $ last $ \"NO\":[\"YES\" | [x,d] <- a, [y,t] <- a, x+d==y, y+t==x]"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nmain = do\n n <- readLn :: IO Int\n ds <- replicateM n $ map (read :: String -> Int). words <$> getLine\n let e = zip (map (\\[a,b] -> a+b) ds) [1..]\n f = zipWith (\\[a,_] i -> (a,i) ) ds [1..]\n g = any ((>1).length) $ groupBy (\\(a,b) (c,d) -> a==c && b==d) $ sortOn fst $ catMaybes $ (\\(a,b) (c,d) -> if a==c then Just((min b d),(max b d)) else Nothing ) <$> e <*> f \n putStrLn $ if g then \"YES\" else \"NO\"\n"}, {"source_code": "\nimport Array (Array, (!), bounds, listArray)\nimport Monad (liftM)\n\nsolve :: Array Int (Int, Int) -> Bool\nsolve array = not (null solve')\n where\n n = snd $ bounds array\n solve' = [undefined | i <- [1..n], j <- [1..n], isGood i j]\n isGood i j = x1 + y1 == x2 && x2 + y2 == x1\n where\n (x1, y1) = array ! i\n (x2, y2) = array ! j\n\nreadPair :: String -> (Int, Int)\nreadPair line = case words line of\n [a, b] -> (read a, read b)\n _ -> error $ concat [\"readPair: \", \"string \", show line, \" must be two words\"]\n\nmain :: IO ()\nmain = do\n n <- readLn\n pairs <- liftM (map readPair . take n . lines) getContents\n let pairs' = listArray (1, n) pairs\n putStrLn $ if solve pairs' then \"YES\" else \"NO\"\n \n"}, {"source_code": "solve :: [(Int,Int)] -> Bool\nsolve camels = length (spittingPairs camels) > 0\n\nspittingPairs :: [(Int,Int)] -> [(Int,Int)]\nspittingPairs camels = filter (\\(a,b) -> spitEachOther (camels!!a) (camels!!b)) [(x,y) | x <- [0..len], y <- [0..len], x < y]\n where len = length camels - 1\n\nspitEachOther :: (Int,Int) -> (Int,Int) -> Bool\nspitEachOther camel1 camel2 = (fst camel1 + snd camel1 == fst camel2) && (fst camel2 + snd camel2 == fst camel1)\n\nbool2string :: Bool -> [Char]\nbool2string True = \"YES\\n\"\nbool2string False = \"NO\\n\"\n\nline2tuple :: [Char] -> (Int,Int)\nline2tuple line = (head x, last x)\n where x = map read tmp :: [Int]\n tmp = words line\n\nprocess :: [[Char]] -> [Char]\nprocess input = bool2string (solve (map line2tuple input))\n\nprocessInput :: [Char] -> [Char]\nprocessInput input = process (tail (lines input))\n\nmain = interact processInput\n\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Ord\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let readInts = map read . words\n n : _ <- readInts <$> getLine\n xs <- replicateM n $ readInts <$> getLine\n let as = do\n x : d : _ <- xs\n return (x, x + d)\n bs = do\n (x, s) <- as\n return (s, x)\n answer = if any (`elem` bs) as\n then \"YES\"\n else \"NO\"\n putStrLn answer\n"}, {"source_code": "main = do \n (_:camels) <- fmap (map (map read) . map words . lines) getContents\n let pairs = [(a,b) | a<-camels, b<-camels, f a b]\n f [x,d] [y,e] = x+d == y && y+e == x\n if null pairs\n then putStrLn \"NO\"\n else putStrLn \"YES\""}], "negative_code": [{"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nmain = do\n n <- readLn :: IO Int\n ds <- replicateM n $ map (read :: String -> Int). words <$> getLine\n let e = map (\\[a,b] -> a+b) ds\n f = e \\\\ map (\\[a,_] -> a) ds \n putStrLn $ if length f > 1 then \"YES\" else \"NO\"\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nmain = do\n n <- readLn :: IO Int\n ds <- replicateM n $ map (read :: String -> Int). words <$> getLine\n let e = map (\\[a,b] -> a+b) ds\n f = e `intersect` map (\\[a,_] -> a) ds \n putStrLn $ if length f > 1 then \"YES\" else \"NO\"\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nmain = do\n n <- readLn :: IO Int\n ds <- replicateM n $ map (read :: String -> Int). words <$> getLine\n let e = zip (map (\\[a,b] -> a+b) ds) [1..]\n f = zipWith (\\[a,_] i -> (a,i) ) ds [1..]\n g = any ((>1).length) $ groupBy ((==) `on` fst) $ sortOn fst $ catMaybes $ (\\(a,b) (c,d) -> if a==c then Just((min b d),(max b d)) else Nothing ) <$> e <*> f \n putStrLn $ if g then \"YES\" else \"NO\"\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nmain = do\n n <- readLn :: IO Int\n ds <- replicateM n $ map (read :: String -> Int). words <$> getLine\n let e = map (\\[a,b] -> a+b) ds\n f = e \\\\ map (\\[a,_] -> a) ds \n putStrLn $ if length f > 2 then \"YES\" else \"NO\"\n"}], "src_uid": "d7dc61a8f3b0091320b96cedd1f4f0a7"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\n--import Debug.Trace\n\nreadInt = fst . fromJust . B.readInt <$> B.getLine\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\ncharToNum x = ord x - ord 'a'\n\ncompress = map (\\s -> let c = B.head s in (charToNum c,B.length s)) . B.group\n\ngetUpdateList ((l,x):xs) a\n | l == r = (l,if a!l == 0 then max x y else 1+x+y):xs\n | otherwise = (l,a!l+x):(r,a!r+y):xs\n where (r,y) = last xs\n\nf :: Array Int Int -> B.ByteString -> Array Int Int\nf a s = let s' = compress s in case s' of\n [(i,n)] -> a' // [(i,(a!i+1)*n+a!i)]\n xs -> accum max a' $ getUpdateList s' a'\n where a' = amap (\\e -> if e == 0 then 0 else 1) a\n\nmain = do n <- readInt\n (x:xs) <- B.words <$> B.getContents\n let a = accumArray max 0 (0,25) . compress $ x\n print $ maximum . foldl f a $ xs", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\n--import Debug.Trace\n\nreadInt = fst . fromJust . B.readInt <$> B.getLine\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\ncharToNum x = ord x - ord 'a'\n\ncompress = map (\\s -> let c = B.head s in (charToNum c,B.length s)) . B.group\n\ngetUpdateList ((l,x):xs) a\n | l == r = (l,if a!l == 0 then max x y else 1+x+y):xs\n | otherwise = (l,a!l+x):(r,a!r+y):xs\n where (r,y) = last xs\n\nf :: Array Int Int -> B.ByteString -> Array Int Int\nf a s = case s' of\n [(i,n)] -> a' // [(i,(a!i+1)*n+a!i)]\n xs -> accum max a' $ getUpdateList s' a'\n where s' = compress $ B.init s\n a' = amap (\\e -> if e == 0 then 0 else 1) a\n\nmain = do n <- readInt\n --(x:xs) <- B.words <$> B.getContents\n --let a = accumArray max 0 (0,25) . compress $ x\n --print $ maximum . foldl f a $ xs\n a <- accumArray max 0 (0,25) . compress . B.init <$> B.getLine\n a' <- foldl f a <$> replicateM (n-1) B.getLine\n print $ maximum a'"}], "negative_code": [], "src_uid": "d6ed0b1d8cde86e7372374985804dbf3"} {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\nsolve :: Int -> Int -> [Int] -> Bool\r\nsolve n d as = min (maximum as) minS <= d\r\n where\r\n minS = sum . take 2 . sort $ as\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, d] <- B8.getLine <&> map readIntB8 . B8.words\r\n as <- B8.getLine <&> map readIntB8 . B8.words\r\n let answer = solve n d as\r\n putStrLn ((if answer then \"YES\" else \"NO\") :: String)\r\n\r\n", "positive_code": [{"source_code": "findAllChar :: (Char, [Char]) -> [Int]\r\nfindAllChar (element, list) = ([ind | ind<-[0..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindAllInt :: (Int, [Int]) -> [Int]\r\nfindAllInt (element, list) = ([ind | ind<-[0..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindFirstChar :: (Char, [Char]) -> Int\r\nfindFirstChar (element, list) = (findAllChar(element, list)!!0)\r\n\r\nfindFirstInt :: (Int, [Int]) -> Int\r\nfindFirstInt (element, list) = (findAllInt(element, list)!!0)\r\n\r\n\r\ntakeLast :: (Int, [Char]) -> [Char]\r\ntakeLast (cnt, list) = reverse ( take cnt (reverse list) )\r\n\r\nsplit :: (Char, [Char]) -> [[Char]]\r\n\r\nsplit (element, []) = []\r\nsplit (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list)) [1..] ]]\r\n ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))\r\n\r\nexcludeFirst :: (Int, [Int]) -> [Int]\r\nexcludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)], \r\n ((ind-1)/=(findFirstInt(val, list)))]\r\n\r\nreadIntLsit :: IO[Int]\r\nreadIntLsit = do\r\n input <- getLine\r\n let l = split(' ', input)\r\n\r\n return [(read str :: Int) | str <- l]\r\n\r\nminim :: [Int] -> Int\r\nminim [] = 0\r\nminim [x] = x\r\nminim (x:xs) = min x (minim xs)\r\n\r\nmaxim :: [Int] -> Int\r\nmaxim [] = 0\r\nmaxim [x] = x\r\nmaxim (x:xs) = max x (maxim xs)\r\n\r\n\r\nsolveTestcase :: () -> (IO [Char])\r\nsolveTestcase () = do\r\n help1 <- readIntLsit\r\n let help2 = [1, 2, 3]\r\n \r\n let n = help1!!0\r\n let d = help1!!1\r\n a <- readIntLsit\r\n\r\n let minVal1 = minim a\r\n let minVal2 = minim (excludeFirst(minVal1, a))\r\n\r\n let maxVal = maxim a\r\n\r\n if( (minVal1+minVal2) > d && maxVal>d) \r\n then \r\n return \"NO\"\r\n else\r\n return \"YES\"\r\n\r\n --let m = (help!!1)\r\n\r\n --print help\r\n \r\n\r\n --print \"\"\r\n\r\n--loop :: Int -> IO()\r\n--loop 0 = print \"\"\r\n--loop t = do\r\n-- solveTestcase\r\n-- return (loop (t - 1))\r\n\r\n--getRes :: (Int) -> ()\r\n--getRes 0 = IO[Char]::Empty\r\ngetRes :: Int -> (IO[Char])\r\ngetRes 0 = return \"\"\r\ngetRes (t) = do\r\n x <- solveTestcase()\r\n y <- getRes(t-1)\r\n \r\n return (x++\"\\n\"++y)\r\n\r\nmain = do\r\n help <- readIntLsit\r\n let t = help!!0\r\n\r\n res <- getRes(t)\r\n putStr res\r\n"}, {"source_code": "import Control.Monad\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n t <- getInt\n replicateM_ t $ do\n [n, d] <- getInts\n a@(a1:a2:_) <- L.sort <$> getInts\n if all (<= d) a || (a1 + a2 <= d) then putStrLn \"YES\" else putStrLn \"NO\"\n\n"}, {"source_code": "import Prelude\nimport Data.Int\nimport Control.Arrow\n\nparseIntList :: String -> [Int64]\nparseIntList = words >>> map read\n\nmakePair :: a -> [a] -> [(a,a)]\nmakePair val list = map (\\x -> (val,x)) list\n\npairs :: [Int64] -> [(Int64,Int64)]\npairs [] = []\npairs (x:xs) = (makePair x xs) ++ (pairs xs)\n\nproblem :: [[Int64]] -> String\nproblem [] = \"\"\nproblem (x:y:z) = (if((foldr (\\(a,b) c -> c || (a + b <= d)) False (pairs y)) || (foldr (\\a b -> b && a <= d)) True y) then \"YES\" else \"NO\")++\"\\n\"++(problem z) where d = x !! 1\nproblem (_:_) = \"\"\n\nsolve :: String -> String\nsolve str = problem $ map parseIntList $ tail $ lines str\n\nmain :: IO ()\nmain = interact $ solve\n"}, {"source_code": "import Data.Char\r\nimport Data.List\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nmain = B.interact $ B.unlines . solves . tail . toInt\r\n where toInt = unfoldr (B.readInt . B.dropWhile isSpace)\r\n\r\nsolves [] = []\r\nsolves (m:n:ss) = (B.pack . solve n $ sort xs) : solves ys\r\n where (xs, ys) = splitAt m ss\r\n\r\nsolve n (x:y:xs)\r\n | min (x + y) (last xs) <= n = \"YES\"\r\n | otherwise = \"NO\""}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\ngetTestCases :: Int -> IO [((Int,Int), [Int])]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n let [a,b] = read <$> words line :: [Int]\n line2 <- getLine\n let l1 = read <$> words line2 :: [Int]\n let tcase = ((a,b), l1)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\nsolve :: ((Int, Int), [Int]) -> String\nsolve ((_,_), []) = \"NO\"\nsolve ((n, d), (x:xs)) =\n let\n srtd = sort (x:xs)\n srtdzip = zip [0..] srtd\n lst = [(a,b) | (i,a) <- srtdzip, (j,b) <- srtdzip, i /= j, a+b <= d]\n isOks = all (<=d) srtd\n in\n if not (null lst) || isOks\n then \"YES\"\n else \"NO\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\n-- import Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\t[ _, d ] <- readInts\r\n\tas@( a1 : a2 : _ ) <- sort <$> readInts\r\n\tputStrLn $ which \"YES\" \"NO\" $ all ( <= d ) as || a1 + a2 <= d"}], "negative_code": [{"source_code": "findAllChar :: (Char, [Char]) -> [Int]\r\nfindAllChar (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindAllInt :: (Int, [Int]) -> [Int]\r\nfindAllInt (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindFirstChar :: (Char, [Char]) -> Int\r\nfindFirstChar (element, list) = (findAllChar(element, list)!!0)\r\n\r\nfindFirstInt :: (Int, [Int]) -> Int\r\nfindFirstInt (element, list) = (findAllInt(element, list)!!0)\r\n\r\n\r\ntakeLast :: (Int, [Char]) -> [Char]\r\ntakeLast (cnt, list) = reverse ( take cnt (reverse list) )\r\n\r\nsplit :: (Char, [Char]) -> [[Char]]\r\n\r\nsplit (element, []) = []\r\nsplit (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list)) [1..] ]]\r\n ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))\r\n\r\nexcludeFirst :: (Int, [Int]) -> [Int]\r\nexcludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)], \r\n ((ind-1)/=(findFirstInt(val, list)))]\r\n\r\nreadIntLsit :: IO[Int]\r\nreadIntLsit = do\r\n input <- getLine\r\n let l = split(' ', input)\r\n\r\n return [(read str :: Int) | str <- l]\r\n\r\nminim :: [Int] -> Int\r\nminim [] = 0\r\nminim [x] = x\r\nminim (x:xs) = min x (minim xs)\r\n\r\nmaxim :: [Int] -> Int\r\nmaxim [] = 0\r\nmaxim [x] = x\r\nmaxim (x:xs) = max x (maxim xs)\r\n\r\n\r\nsolveTestcase :: () -> (IO [Char])\r\nsolveTestcase () = do\r\n help1 <- readIntLsit\r\n let help2 = [1, 2, 3]\r\n \r\n let n = help1!!0\r\n let d = help1!!1\r\n a <- readIntLsit\r\n\r\n let minVal1 = minim a\r\n let minVal2 = minim (excludeFirst(minVal1, a))\r\n\r\n let maxVal = maxim a\r\n\r\n if( (minVal1+minVal2) > d && maxVal>d ) \r\n then \r\n return \"NO\"\r\n else\r\n return \"YES\"\r\n\r\n --let m = (help!!1)\r\n\r\n --print help\r\n \r\n\r\n --print \"\"\r\n\r\n--loop :: Int -> IO()\r\n--loop 0 = print \"\"\r\n--loop t = do\r\n-- solveTestcase\r\n-- return (loop (t - 1))\r\n\r\n--getRes :: (Int) -> ()\r\n--getRes 0 = IO[Char]::Empty\r\ngetRes :: Int -> (IO[Char])\r\ngetRes 0 = return \"\"\r\ngetRes (t) = do\r\n x <- solveTestcase()\r\n y <- getRes(t-1)\r\n \r\n return (x++\"\\n\"++y)\r\n\r\nmain = do\r\n help <- readIntLsit\r\n let t = help!!0\r\n\r\n res <- getRes(t)\r\n putStr res\r\n"}, {"source_code": "findAllChar :: (Char, [Char]) -> [Int]\r\nfindAllChar (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindAllInt :: (Int, [Int]) -> [Int]\r\nfindAllInt (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindFirstChar :: (Char, [Char]) -> Int\r\nfindFirstChar (element, list) = (findAllChar(element, list)!!0)\r\n\r\nfindFirstInt :: (Int, [Int]) -> Int\r\nfindFirstInt (element, list) = (findAllInt(element, list)!!0)\r\n\r\n\r\ntakeLast :: (Int, [Char]) -> [Char]\r\ntakeLast (cnt, list) = reverse ( take cnt (reverse list) )\r\n\r\nsplit :: (Char, [Char]) -> [[Char]]\r\n\r\nsplit (element, []) = []\r\nsplit (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list)) [1..] ]]\r\n ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))\r\n\r\nexcludeFirst :: (Int, [Int]) -> [Int]\r\nexcludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)], \r\n ((ind-1)/=(findFirstInt(val, list)))]\r\n\r\nreadIntLsit :: IO[Int]\r\nreadIntLsit = do\r\n input <- getLine\r\n let l = split(' ', input)\r\n\r\n return [(read str :: Int) | str <- l]\r\n\r\nminim :: [Int] -> Int\r\nminim [] = 0\r\nminim [x] = x\r\nminim (x:xs) = min x (minim xs)\r\n\r\nmaxim :: [Int] -> Int\r\nmaxim [] = 0\r\nmaxim [x] = x\r\nmaxim (x:xs) = max x (minim xs)\r\n\r\n\r\nsolveTestcase :: () -> (IO [Char])\r\nsolveTestcase () = do\r\n help1 <- readIntLsit\r\n let help2 = [1, 2, 3]\r\n \r\n let n = help1!!0\r\n let d = help1!!1\r\n a <- readIntLsit\r\n\r\n let minVal1 = minim a\r\n let minVal2 = minim (excludeFirst(minVal1, a))\r\n\r\n let maxVal = maxim a\r\n\r\n if( (minVal1+minVal2) > d && maxVal>d ) \r\n then \r\n return \"NO\"\r\n else\r\n return \"YES\"\r\n\r\n --let m = (help!!1)\r\n\r\n --print help\r\n \r\n\r\n --print \"\"\r\n\r\n--loop :: Int -> IO()\r\n--loop 0 = print \"\"\r\n--loop t = do\r\n-- solveTestcase\r\n-- return (loop (t - 1))\r\n\r\n--getRes :: (Int) -> ()\r\n--getRes 0 = IO[Char]::Empty\r\ngetRes :: Int -> (IO[Char])\r\ngetRes 0 = return \"\"\r\ngetRes (t) = do\r\n x <- solveTestcase()\r\n y <- getRes(t-1)\r\n \r\n return (x++\"\\n\"++y)\r\n\r\nmain = do\r\n help <- readIntLsit\r\n let t = help!!0\r\n\r\n res <- getRes(t)\r\n putStr res\r\n"}, {"source_code": "findAllChar :: (Char, [Char]) -> [Int]\r\nfindAllChar (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindAllInt :: (Int, [Int]) -> [Int]\r\nfindAllInt (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])\r\n\r\nfindFirstChar :: (Char, [Char]) -> Int\r\nfindFirstChar (element, list) = (findAllChar(element, list)!!0)\r\n\r\nfindFirstInt :: (Int, [Int]) -> Int\r\nfindFirstInt (element, list) = (findAllInt(element, list)!!0)\r\n\r\n\r\ntakeLast :: (Int, [Char]) -> [Char]\r\ntakeLast (cnt, list) = reverse ( take cnt (reverse list) )\r\n\r\nsplit :: (Char, [Char]) -> [[Char]]\r\n\r\nsplit (element, []) = []\r\nsplit (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list)) [1..] ]]\r\n ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))\r\n\r\nexcludeFirst :: (Int, [Int]) -> [Int]\r\nexcludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)], \r\n ((ind-1)/=(findFirstInt(val, list)))]\r\n\r\nreadIntLsit :: IO[Int]\r\nreadIntLsit = do\r\n input <- getLine\r\n let l = split(' ', input)\r\n\r\n return [(read str :: Int) | str <- l]\r\n\r\nminim :: [Int] -> Int\r\nminim [] = 0\r\nminim [x] = x\r\nminim (x:xs) = min x (minim xs)\r\n\r\nsolveTestcase :: () -> (IO [Char])\r\nsolveTestcase () = do\r\n help1 <- readIntLsit\r\n let help2 = [1, 2, 3]\r\n \r\n let n = help1!!0\r\n let d = help1!!1\r\n a <- readIntLsit\r\n\r\n let minVal1 = minim a\r\n let minVal2 = minim (excludeFirst(minVal1, a))\r\n\r\n if( (minVal1+minVal2) > d ) \r\n then \r\n return \"NO\"\r\n else\r\n return \"YES\"\r\n\r\n --let m = (help!!1)\r\n\r\n --print help\r\n \r\n\r\n --print \"\"\r\n\r\n--loop :: Int -> IO()\r\n--loop 0 = print \"\"\r\n--loop t = do\r\n-- solveTestcase\r\n-- return (loop (t - 1))\r\n\r\n--getRes :: (Int) -> ()\r\n--getRes 0 = IO[Char]::Empty\r\ngetRes :: Int -> (IO[Char])\r\ngetRes 0 = return \"\"\r\ngetRes (t) = do\r\n x <- solveTestcase()\r\n y <- getRes(t-1)\r\n \r\n return (x++\"\\n\"++y)\r\n\r\nmain = do\r\n help <- readIntLsit\r\n let t = help!!0\r\n\r\n res <- getRes(t)\r\n putStr res\r\n"}, {"source_code": "import Control.Monad\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n t <- getInt\n replicateM_ t $ do\n [n, d] <- getInts\n a@(a1:a2:_) <- L.sort <$> getInts\n if all (<= d) a || (a1 + a2 < 0) then putStrLn \"YES\" else putStrLn \"NO\"\n\n"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Int\nimport Control.Arrow\n\nparseIntList :: String -> [Int64]\nparseIntList = words >>> map read\n\nmakePair :: a -> [a] -> [(a,a)]\nmakePair val list = map (\\x -> (val,x)) list\n\npairs :: [Int64] -> [(Int64,Int64)]\npairs list = foldr (++) [] (map (\\x -> makePair x (tail list)) list)\n\nproblem :: [[Int64]] -> String\nproblem [] = \"\"\nproblem (x:y:z) = (if((foldr (\\(a,b) c -> c || (a + b <= d)) False (pairs y)) || (foldr (\\a b -> b && a <= d)) True y) then \"YES\" else \"NO\")++\"\\n\"++(problem z) where d = x !! 1\nproblem (_:_) = \"\"\n\nsolve :: String -> String\nsolve str = problem $ map parseIntList $ tail $ lines str\n\nmain :: IO ()\nmain = interact $ solve\n"}], "src_uid": "044c2a3bafe4f47036ee81f2e40f639a"} {"source_code": "f::Int->Int->Int->[[Int]]->String\nf (-1) _ _ _=\"Yes\"\nf y (-1) c ms=f (y-1) c c ms\nf y x c ms=let t=[1|y1<-[0..c],x1<-[0..c],y1/=y,x1/=x,(ms!!y1!!x)+(ms!!y!!x1)==(ms!!y!!x)]\n in if t==[] && (ms!!y!!x)>1 then \"No\" else f y (x-1) c ms\n\nf2::[String]->[[Int]]\nf2 []=[]\nf2 (s:str)=let xs=map read (words s)::[Int]\n in xs:f2 str\n\nmain =do\n e<-getLine\n es<-getContents\n let xs=lines es\n ys=f2 xs\n n=read e::Int\n putStrLn $ f (n-1) (n-1) (n-1) ys", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\n\n-- f :: [[Int]] -> [[Int]] -> [Int] -> [Int] -> Bool \nf n ns ns' is xs = and $ zipWith (\\i x -> if x == 1 \n then True\n else let (q,r) = i `quotRem` n\n ar = (+) <$> ns!!q <*> ns' !! r \n in x `elem` ar\n ) is xs\n\nmain = do\n n <- readLn :: IO Int\n ns <- replicateM n (getLine >>= return . map (read :: String -> Int) . words)\n let ns' = map (\\i -> map (!!i) ns) [0..n-1] \n let a = f n ns ns' [0..n*n-1] $ concat ns\n putStrLn $ if a then \"Yes\" else \"No\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Bool\n\nmain = sol <$> get >>= put\n\nget :: IO [[Int]]\nget = fmap (fmap read . words) . tail . lines <$> getContents\n\nput = putStrLn . bool \"No\" \"Yes\"\n\nsol ass = all gd [(x,y) | x <- [1..n], y <- [1..n], ar!(x,y) /= 1]\n where\n n = length ass\n ar = listArray ((1,1),(n,n)) $ concat ass\n gd (x,y) = ar!(x,y) `elem` [ar!(x,j) + ar!(i,y) | i <- [1..n], j <- [1..n]]\n\n{-\nass = [\n [1, 1, 2],\n [2, 3, 1],\n [6, 4, 1]]\nn = length ass\nar = listArray ((1,1),(n,n)) $ concat ass\ngd (x,y) = ar!(x,y) `elem` [ar!(x,j) + ar!(i,y) | i <- [1..n], j <- [1..n]]\naa = [gd (x,y) | x <- [1..n], y <- [1..n], ar!(x,y) /= 1]\n-}"}, {"source_code": "import Control.Applicative( (<$>))\nimport Data.Array.IArray( listArray, (!))\nimport Data.Array.Unboxed( UArray)\nimport Control.Monad( replicateM)\n\nmain = do\n n_ <- readLn\n let\n\trow = map (read::String->Int) . words <$> getLine\n\t \n rows_ <- replicateM n_ row\n let\n\tdataArray::UArray (Int,Int) Int\n\tdataArray = listArray ((1,1),(n_,n_)) $ concat rows_\n\n\tcandidate (x,y) = let\n\t row = (\\s->dataArray!(x,s)) <$> ([1..y-1] ++ [y+1..n_])\n\t col = (\\t->dataArray!(t,y)) <$> ([1..x-1] ++ [x+1..n_])\n\t in\n\t (row,col)\n \n\tcheck (x,y) = let\n\t\t (r,c) = candidate (x,y)\n\t\t v = dataArray!(x,y)\n\t\tin\n\t\t or $ (\\i-> (v-i) `elem` c) <$> r\n\n\tallIx = [(x,y) | x<-[1..n_], y<-[1..n_]]\n\n\tverify (i,j) = if dataArray!(i,j) == 1\n\t\t\tthen True\n\t\t\telse check (i,j)\n\n putStr $ if and $ verify <$> allIx\n\t\tthen \"Yes\"\n\t\telse \"No\"\n"}, {"source_code": "import Data.List (transpose)\nimport Data.Bool (bool)\n\nsol :: [[Int]] -> [[Bool]]\nsol rs = map rf rs where\n rf r = zipWith (cf r) cs r\n cf r c x | x == 1 = True\n | otherwise = or $ flip map c $ flip elem r . (x -)\n cs = transpose rs\n\nmain = interact $\n (bool \"No\" \"Yes\") . (and . concat)\n . sol\n . map (map read . words) . tail . lines\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve g = all (\\r -> all (\\(x, c) -> x == 1 || any (`elem` c) [x - x' | x' <- r]) $ zip r g') g\n where\n g' = transpose g\n\nmain = do\n n <- fmap readInt B.getLine\n g <- replicateM n (fmap readInts B.getLine)\n putStr $ if solve g then \"Yes\" else \"No\""}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\ncheck a b n x y | x==n = \"Yes\"\n\t\t| ((a!!x)!!y) ==1 = if y==n-1 then check a b n (x+1) 0 else check a b n x (y+1)\n\t\t| elem ((a!!x)!!y) [i+j|i<-a!!x, j<-b!!y] = if y==n-1 then check a b n (x+1) 0 else check a b n x (y+1)\n\t\t|otherwise = \"No\"\nmain=do\n n<- read <$> getLine::IO Int\n a<- map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n let b= transpose a\n putStrLn $ check a b n 0 0 \n"}], "negative_code": [], "src_uid": "d1d50f0780d5c70e6773d5601d7d41e8"} {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve as | null is = unlines [ \"yes\", \"1 1\" ]\n | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ \"yes\", unwords (map show [ imin, imax ]) ]\n | otherwise = \"no\"\n where is = [ i | ((i, a), a') <- zip (zip [1..] as) (sort as), a /= a' ]\n imin = head is; imax = last is\n", "positive_code": [{"source_code": "-- Codeforces 451B\n\nimport Data.List\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . words\n\nsolve :: [Int] -> String\nsolve (n:xs)\n | xs == (sort xs) = \"yes\\n1 1\"\n | otherwise = case (reverse $ map fst k) == (map snd k)\n of {\n True -> \"yes\\n\" ++ (intercalate \" \" $ map show [len+1, len+(length k)]);\n False -> \"no\";\n } where\n all = zip xs (sort xs)\n len = length $ takeWhile (\\x -> (fst x) == (snd x)) all\n k = dropWhile (\\x -> (fst x) == (snd x)) $ dropWhileEnd (\\x -> (fst x) == (snd x)) all\n \n\n-- judge if a list is sorted in non-decreasing ordering.\nsorted :: [Int] -> Bool\nsorted xs = and $ zipWith (<=) xs (tail xs)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (mapMaybe)\nimport Text.Printf\n\nmain = do\n _ <- getLine\n xs <- map fst . mapMaybe B.readInt . B.words <$> B.getLine\n let\n sorted_xs = sort xs\n not_matched [] _ _ = []\n not_matched (x:xs) (y:ys) index\n | x == y = not_matched xs ys (index+1)\n | otherwise = index : not_matched xs ys (index+1)\n not_sorted_segment = not_matched xs sorted_xs 0\n begin = head not_sorted_segment\n end = last not_sorted_segment + 1\n a = take begin xs\n b = reverse . take (end-begin) $ drop begin xs\n c = drop end xs\n in if xs == sorted_xs\n then putStrLn \"yes\\n1 1\"\n else if a ++ b ++ c == sorted_xs\n then putStrLn \"yes\" >> printf \"%d %d\\n\" (begin+1) end\n else putStrLn \"no\"\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\n\nextract :: Int -> Int -> [a] -> [a]\nextract first last xs = take (last-first+1) ys\n where\n (_,ys) = splitAt first xs\n\nmain = do\n n <- readLn\n xs <- map (fst.fromJust.B.readInt) . B.words <$> B.getLine\n let\n sorted_xs = sort xs\n nochange = xs == sorted_xs\n first = length . takeWhile (uncurry (==)) $ zip xs sorted_xs\n last = n - (length . takeWhile (uncurry (==)) $ zip (reverse xs) (reverse sorted_xs)) - 1\n xs' = take first xs ++ (reverse $ extract first last xs) ++ drop (last+1) xs\n change = xs' == sorted_xs\n in putStrLn $ if nochange then \"yes\\n1 1\" else if change then \"yes\\n\" ++ (unwords $ map show [first+1, last+1]) else \"no\"\n \n \n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve as | null is = unlines [ \"yes\", \"1 1\" ]\n | reverseSegment as imin imax == sort as = unlines [ \"yes\", unwords (map show [ imin, imax ]) ]\n | otherwise = \"no\"\n where is = [ i | (i, a, a') <- zip3 [1..] as (sort as), a /= a' ]\n imin = head is; imax = last is\n\nreverseSegment :: [a] -> Int -> Int -> [a]\nreverseSegment as i j = take (i - 1) as ++ reverse (drop (i - 1) (take j as)) ++ drop j as\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Control.Monad\nmain = interact $ format . solve . map read . words\nformat Nothing = \"no\"\nformat (Just (a,b)) = unlines [ \"yes\", show (a+1) ++ \" \" ++ show (b+1) ]\nsolve (n : xs)\n | null drs = Just (0,0)\n | [(a,b)] <- drs = guard (a == 0 || xs!!(a-1) < xs!!b) *>\n guard (b == n-1 || xs!!a < xs!!(b+1)) *>\n Just (a,b)\n | otherwise = Nothing\n where\n drs = go 0 $ groupBy ((==) `on` signum) $ zipWith (-) (tail xs) xs\n go i (ds@(d:_):dss) | d > 0 = go (i + length ds) dss\n | otherwise = (i,i+length ds) : go (i + length ds) dss\n go _ _ = []\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n case solve n xs of\n Just (l,r) -> putStrLn \"yes\" >> putStr (shows l \" \" ++ shows r \"\\n\")\n Nothing -> putStrLn \"no\"\n\n\nsolve :: Int -> [Int] -> Maybe (Int, Int)\nsolve n xs\n | xs == sorted = Just (1,1)\n | otherwise = case divide xs of\n [xs]\n | reverse xs == sorted -> Just (1,n)\n [xs,ys]\n | reverse xs ++ ys == sorted -> Just (1, length xs)\n | xs ++ reverse ys == sorted -> Just (length xs+1, n)\n [xs,ys,zs]\n | xs ++ reverse ys ++ zs == sorted -> Just (length xs+1, length (xs++ys))\n _ -> Nothing\n where\n !sorted = sort xs\n \ndivide [] = []\ndivide [x] = [[x]]\ndivide (x:y:xs)\n | x < y = asc [y,x] xs\n | otherwise = des [y,x] xs\n\nasc (top:stack) (x:xs)\n | top < x = asc (x:top:stack) xs\n | otherwise = reverse stack : des [x,top] xs\nasc stack [] = [reverse stack]\n\ndes (top:stack) (x:xs)\n | top > x = des (x:top:stack) xs\n | otherwise = (reverse $ top:stack) : asc [x] xs\ndes stack [] = [reverse stack]\n"}, {"source_code": "sorted :: Ord a => [a] -> Bool\nsorted [] = True\nsorted [x] = True\nsorted (x:y:xs) = x <= y && sorted (y:xs)\n\nf :: [Int] -> Maybe (Int, Int)\nf [] = undefined\nf [x] = Just (1, 1)\nf [x,y] = if x > y then Just (1,2) else Just (1,1)\nf (x:y:z:xs) = if x > y then g (-2000000000) x (x:y:z:xs) >>= \\r->Just(1,r) else\n if y > z then g x y (y:z:xs) >>= \\r->Just (2, r + 1)\n else f (y:z:xs) >>= \\(x,y)->Just (x + 1, y + 1)\n \ng :: Int -> Int -> [Int] -> Maybe Int\ng _ _ [] = undefined\ng xx yy [p] = if xx < p && p < yy then Just 1 else Nothing\ng xx yy (p:q:pp) = if p > q then g xx yy (q:pp) >>= Just . (1+)\n else if xx < p && yy < q && sorted (q:pp) then Just 1 else Nothing\npar :: String -> [Int]\npar = (map read) . words\n\ngood x y= do\n putStrLn \"yes\"\n putStrLn $ show x ++ \" \" ++ show y\nmain = do\n l <- getLine\n l1 <- getLine\n let a = par l1\n case f a of\n Just (x, y) -> good x y\n Nothing -> putStrLn \"no\""}, {"source_code": "import Data.List\nimport Text.Printf\n\nisSorted [x] = 1\nisSorted [] = 1\nisSorted (a:b:xs) = if (a < b) then isSorted (b:xs) else 0\n\ngetInts s = map read $ words s\n\nget :: [Int] -> [Int] -> ([Int], [Int])\nget f [x] = (f, [])\nget f (a:b:xs) = if (a < b) then get (a:f) (b:xs) else (f, a:b:xs)\n\ngot :: [Int] -> [Int] -> ([Int], [Int])\ngot f [x] = ([x], [])\ngot f [] = ([], [])\ngot f (a:b:xs) = if (a > b) then got (a:f) (b:xs) else (a:f, b:xs)\n \nmain = do\n s <- getLine\n s <- getLine\n let t = getInts s\n y = get [] t\n u = got [] (snd y)\n-- print(t);\n-- print(y);\n-- print(u);\n if (isSorted ((reverse $ fst y) ++ (fst u) ++ (snd u)) == 1)\n then printf \"yes\\n%d %d\\n\" (length (fst y) + 1) (length t - (length (snd u)))\n else printf \"no\\n\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\nextract [] [] _ = []\nextract (a:as) (b:bs) n\n | a == b = extract as bs (n + 1)\n | otherwise = n: extract as bs (n + 1)\n\nmain = do\n n <- head . map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n as <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n let sortAs = sort as\n inds = extract as sortAs 0\n if inds == []\n then putStrLn \"yes\\n1 1\"\n else do let mn = minimum inds\n mx = 1 + maximum inds\n aas = reverse. drop mn . take mx $ as\n prefix = take mn as\n suffix = drop mx as\n bs = prefix ++ aas ++ suffix\n if bs == sortAs\n then putStrLn \"yes\" >> printf \"%d %d\\n\" (mn + 1) mx\n else putStrLn \"no\""}, {"source_code": "import Data.List\n\ncal ls = if allSame \n then \"yes\\n1 1\"\n else if result then \"yes\\n\" ++ show startIdx ++ \" \" ++ show endIdx else \"no\"\n where arr = map (+0) $ map read $ words $ head $ tail $ lines ls\n zips = zip arr $ sort arr\n allSame = all (\\p -> (fst p) == (snd p) ) zips\n sameFront = length $ takeWhile (\\p -> (fst p) == (snd p)) zips\n startIdx = sameFront + 1\n sameEnd = length $ takeWhile (\\p -> (fst p) == (snd p)) $ reverse zips\n endIdx = (length zips) - sameEnd\n remains = reverse $ drop sameEnd $ reverse $ drop sameFront zips\n (ori,rev) = unzip remains\n newZip = zip ori $ reverse rev\n result = all (\\p -> (fst p) == (snd p)) newZip\n\nmain = interact cal\n"}, {"source_code": "import Data.List\n\nmain = interact $ ans.parse.tail.words\nparse x = (map read x :: [Integer])\nans lst = f (reverse (g (zip lst [1..(length lst)]) [] 1)) lst\n\ng (x:y:xs) lst orientation\n | orientation == 1 = if (fst x) < (fst y)\n then g (y:xs) lst 1\n else g (y:xs) ((snd x):lst) (-1)\n | orientation == (-1) = if (fst x) < (fst y)\n then g (y:xs) ((snd x):lst) 1\n else g (y:xs) lst (-1)\n\ng (x:[]) lst orientation = lst\n\nf [] orig = \"yes\\n1 1\"\n\nf (x:[]) orig\n | (take (x-1) orig) ++ (reverse (drop (x-1) orig)) == (sort orig) = \"yes\\n\" ++ (show x) ++ \" \" ++ (show (length orig))\n | otherwise = \"no\"\n\nf (x:y:[]) orig\n | (take (x-1) orig)\n ++ (reverse (drop (x-1) (take y orig))) ++\n (drop y orig) == (sort orig) = \"yes\\n\" ++ (show x) ++ \" \" ++ (show y)\n | otherwise = \"no\"\n\nf (x:y:xs) orig = \"no\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n check l r = and $ zipWith (<) ys $ tail ys\n where\n ys = take (l-1) xs ++ (reverse $ take (r-l+1) $ drop (l-1) xs) ++ (drop r xs)\n\n r =\n case map (+1) $ True `elemIndices` (zipWith (>) xs $ tail xs) of\n [] -> Just (1, 1)\n [i] -> if check i (i+1) then Just (i, i+1) else Nothing\n r -> let (i, j) = (head r, last r) in if check i (j+1) then Just (i, j+1) else Nothing\n\n -- print $ True `elemIndices` (zipWith (>) xs $ tail xs)\n\n case r of\n Just (l, r) -> do\n putStrLn \"yes\"\n putStrLn $ show l ++ \" \" ++ show r\n Nothing ->\n putStrLn \"no\"\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\ntype Result = (String, [Int])\n\nsolve :: [Int] -> Result\nsolve xs = decide_on $ merge_singles parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length xs])\n | otherwise = (\"no\", [])\n decide_on [one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n merge_singles (a:b:c:rest)\n | descending (a ++ b ++ c) = (a ++ b ++ c) : merge_singles rest\n | otherwise = a : merge_singles (b : c : rest)\n merge_singles other = other\n\n parts = map fst <$> groupBy ((==) `on` equal) (zip xs sorted)\n sorted = sort xs\n equal = uncurry (==)\n descending = snd . foldr (\\x (prev, acc) -> (x, acc && x >= prev)) (0, True)\n\nprocess :: State Reader Result\nprocess = do\n parse :: State Reader BString\n as <- parse :: State Reader [Int]\n let (answer, range) = solve as\n return (answer, range)\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\n\ninstance Display Double\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInteger x\nsomeFunc::IO()\nsomeFunc = solve.tail.concat=<map rIn.C.words<$>C.getLine)\nsolve xs = let zs= groupBy ((>=) `on` snd) $ zip [1..] xs; fs =filter (\\a->length a>1) zs; fs1 = concat fs; xs1=map snd $ concat $ map reverse zs in if length fs > 1 then putStr \"no\" else if length fs==0 then putStrLn \"yes\" >> putStr \"1 1\" else if sort xs /= xs1 then putStr \"no\" else putStrLn \"yes\" >> putStr (show (fst $ head fs1)++\" \"++show (fst $ last fs1))\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = interact $ ans.parse.tail.words\nparse x = (map read x :: [Integer])\nans lst = f (g (zip lst [1..(length lst)]) [] 1) lst\n\ng (x:y:xs) lst orientation\n | orientation == 1 = if (fst x) < (fst y)\n then g (y:xs) lst 1\n else g (y:xs) ((snd x):lst) (-1)\n | orientation == (-1) = if (fst x) < (fst y)\n then g (y:xs) ((snd x):lst) 1\n else g (y:xs) lst (-1)\n\ng (x:[]) lst orientation = lst\n\nf [] orig = \"Yes\\n1 1\"\n\nf (x:[]) orig\n | (take (x-1) orig) ++ (reverse (drop (x-1) orig)) == (sort orig) = \"Yes\\n\" ++ (show x) ++ \" \" ++ (show (length orig))\n | otherwise = \"No\"\n\nf (x:y:[]) orig\n | (take (x-1) orig)\n ++ (reverse (drop (x-1) (take (y-1) orig))) ++\n (drop (y-1) orig) == (sort orig) = \"Yes\\n\" ++ (show x) ++ (show y)\n | otherwise = \"No\"\n\nf (x:y:xs) orig = \"No\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n check l r = and $ zipWith (<) ys $ tail ys\n where\n ys = take (l-1) xs ++ (reverse $ take (r-l+1) $ drop (l-1) xs) ++ (drop r xs)\n\n r =\n case map (+1) $ True `elemIndices` (zipWith (>) xs $ tail xs) of\n [] -> Just (1, 1)\n [i] -> if check i (i+1) then Just (i, i+1) else Nothing\n [i, j] -> if check i (j+1) then Just (i, j+1) else Nothing\n otherwise -> Nothing\n\n case r of\n Just (l, r) -> do\n putStrLn \"yes\"\n putStrLn $ show l ++ \" \" ++ show r\n Nothing ->\n putStrLn \"no\"\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\ntype Result = (String, [Int])\n\nsolve :: Int -> [Int] -> Result\nsolve x xs = decide_on parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on [one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n\n parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted\n sorted = sort xs\n descending range = range == sortBy (flip compare) range\n equal (a, b) = a == b\n eliminate_singles (a:b:c:rest)\n | length b == 1 || length a == 1 && length c == 1 = (a ++ b ++ c) : eliminate_singles rest\n | length a == 1 = (a ++ b) : eliminate_singles (c : rest)\n | length c == 1 = a : (b ++ c) : eliminate_singles rest\n | otherwise = a : b : eliminate_singles (c : rest)\n eliminate_singles other = other\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n as <- parse\n return $ solve n as\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\n\ninstance Display Double"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\ntype Result = (String, [Int])\n\nsolve :: Int -> [Int] -> Result\nsolve x xs = decide_on parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on [one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n\n parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted\n sorted = sort xs\n descending range = range == sortBy (flip compare) range\n equal (a, b) = a == b\n\n eliminate_singles (a:b:c:rest)\n | length a == 1 = (a++b) : eliminate_singles rest\n | length b == 1 = (a++b++c) : eliminate_singles rest\n | length c == 1 = a : (b++c) : eliminate_singles rest\n | otherwise = a : b : eliminate_singles (c:rest)\n eliminate_singles other = other\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n as <- parse\n return $ solve n as\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int where\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString where\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\ntype Result = (String, [Int])\n\nsolve :: [Int] -> Result\nsolve xs = decide_on parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length xs])\n | otherwise = (\"no\", [])\n decide_on [one, two, three]\n | reverse (one ++ two ++ three) == sorted = (\"yes\", [1, length xs])\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on [one, two, three, four]\n | reverse (one ++ two ++ three) ++ four == sorted = (\"yes\", [1, length xs - length four])\n | one ++ reverse (two ++three ++ four) == sorted = (\"yes\", [length one + 1, length xs])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n parts = map fst <$> groupBy ((==) `on` equal) (zip xs sorted)\n sorted = sort xs\n equal = uncurry (==)\n\nprocess :: State Reader Result\nprocess = do\n parse :: State Reader BString\n as <- parse :: State Reader [Int]\n let (answer, range) = solve as\n return (answer, range)\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\n\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\ntype Result = (String, [Int])\n\nsolve :: Int -> [Int] -> Result\nsolve x xs = decide_on parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on [one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n\n parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted\n sorted = sort xs\n descending range = range == sortBy (flip compare) range\n equal (a, b) = a == b\n\n eliminate_singles (a:b:c:rest)\n | length b == 1 = (a++b++c) : eliminate_singles rest\n | length a == 1 = (a++b) : eliminate_singles rest\n | length c == 1 = a : (b++c) : eliminate_singles rest\n | otherwise = a : b : eliminate_singles (c:rest)\n eliminate_singles other = other\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n as <- parse\n return $ solve n as\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int where\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString where\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\ntype Result = (String, [Int])\n\nsolve :: Int -> [Int] -> Result\nsolve x xs = decide_on parts\n where decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n\n decide_on [one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n\n decide_on _ = (\"no\", [])\n\n parts\n | reverse xs == sorted = [xs]\n | otherwise = map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted\n\n sorted = sort xs\n descending range = range == sortBy (flip compare) range\n equal (a, b) = a == b\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n as <- parse\n return $ solve n as\n\nmain :: IO ()\nmain = do\n args <- getArgs\n input <- if not (null args) && head args == \"MINE\"\n then B.lines <$> (openFile \"input.txt\" ReadMode >>= B.hGetContents)\n else B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int where\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString where\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\ntype Result = (String, [Int])\n\nsolve :: Int -> [Int] -> Result\nsolve x xs = decide_on parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on [one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n\n parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted\n sorted = sort xs\n descending range = range == sortBy (flip compare) range\n equal (a, b) = a == b\n eliminate_singles (a:b:c:rest)\n | length b == 1 = (a ++ b ++ c) : eliminate_singles rest\n | length a == 1 = (a ++ b) : eliminate_singles (c : rest)\n | length c == 1 = a : (b ++ c) : eliminate_singles rest\n | otherwise = a : b : eliminate_singles (c : rest)\n eliminate_singles other = other\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n as <- parse\n return $ solve n as\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\n\ninstance Display Double"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\ntype Result = (String, [Int])\n\nsolve :: [Int] -> Result\nsolve xs\n | concat [l, reverse m1, m2, r] == sorted = (\"yes\", (length l +) <$> bounds m1)\n | concat [l, reverse (m1 ++ m2), r] == sorted = (\"yes\", (length l +) <$> bounds (m1 ++ m2))\n | reverse (concat [l, m1, m2, r]) == sorted = (\"yes\", bounds xs)\n | otherwise = (\"no\", [])\n where\n [l, m1, m2, r] = map fst <$> [left, middle1, middle2, right]\n sorted = sort xs\n (left, rest) = break (uncurry (/=)) $ zip xs sorted\n (middle1, rest') = break (uncurry (==)) rest\n (middle2, right) = break (uncurry (/=)) rest'\n bounds range = if null range then [0, 0] else [1, length range]\n\nprocess = do\n parse :: State Reader BString\n as <- parse\n return $ solve as\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n-- say $ evalState process input\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\n\ninstance Display Double\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\ntype Result = (String, [Int])\n\nsolve :: Int -> [Int] -> Result\nsolve x xs = decide_on parts\n where\n decide_on [one]\n | one == sorted = (\"yes\", [1, 1])\n | reverse one == sorted = (\"yes\", [1, length one])\n | otherwise = (\"no\", [])\n decide_on [one, two]\n | reverse one ++ two == sorted = (\"yes\", [1, length one])\n | one ++ reverse two == sorted = (\"yes\", [length one + 1, length one + length two])\n | otherwise = (\"no\", [])\n decide_on ps@[one, two, three]\n | one ++ reverse two ++ three == sorted = (\"yes\", [length one + 1, length one + length two])\n | reverse (concat ps) == sorted = (\"yes\", [1, length (concat ps)])\n | otherwise = (\"no\", [])\n decide_on _ = (\"no\", [])\n\n parts = map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted\n sorted = sort xs\n descending range = range == sortBy (flip compare) range\n equal (a, b) = a == b\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n as <- parse\n return $ solve n as\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n let (answer, range) = evalState process input\n say answer\n say range\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int where\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString where\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\ninstance Display Double\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve as | length is < 2 = \"no\"\n | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ \"yes\", unwords (map show [ imin, imax ]) ]\n | otherwise = \"no\"\n where is = [ i | (i, a) <- zip [1..] as, a /= i ]\n imin = head is; imax = last is\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve as | null is = unlines [ \"yes\", \"1 1\" ]\n | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ \"yes\", unwords (map show [ imin, imax ]) ]\n | otherwise = \"no\"\n where is = [ i | (i, a) <- zip [1..] as, a /= i ]\n imin = head is; imax = last is\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve as | null is = \"no\"\n | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ \"yes\", unwords (map show [ imin, imax ]) ]\n | otherwise = \"no\"\n where is = [ i | (i, a) <- zip [1..] as, a /= i ]\n imin = head is; imax = last is\n"}], "src_uid": "c9744e25f92bae784c3a4833c15d03f4"} {"source_code": "papa nine zero\n | zero == 0 = [-1]\n | nine == 0 = [0]\n | otherwise = replicate nine 5 ++ replicate zero 0\n\nsolve x = \n papa nine_cnt zero\n where nine = length $ filter (==\"5\") x\n zero = length $ filter (==\"0\") x\n nine_cnt = 9 * (nine `div` 9)\n\nmain = do\n getLine\n xs <- getLine\n mapM_ (putStr.show) $ solve $ words xs\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\npapa nine zero\n | zero == 0 = [-1]\n | nine == 0 = [0]\n | otherwise = replicate nine 5 ++ replicate zero 0\n\nsolve x = \n papa nine_cnt zero\n where nine = length $ filter (==5) x\n zero = length $ filter (==0) x\n nine_cnt = 9 * (nine `div` 9)\n\nmain = do\n getLine\n xs <- map (fromJust . fmap fst . B.readInt) . B.words <$> B.getLine\n mapM_ (putStr.show) $ solve xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Functor\n\nmain = do\n n <- read <$> getLine :: IO Int\n cards <- sort <$> (words <$> getLine) :: IO [String]\n putStrLn (solve n cards)\n return ()\n \nsolve n cards = if n0 == 0 then \"-1\"\n else (replicate n5 '5') ++ (replicate n0 '0')\n where n5 = (length (filter (\\s -> s==\"5\") cards))`div`9*9\n n0 = if n5==0 then min 1 (length (filter (\\s -> s==\"0\") cards))\n else length (filter (\\s -> s==\"0\") cards)"}, {"source_code": "main :: IO()\nmain = putStrLn . solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> String\nsolve a =\n let num5 = length $ filter (== 5) a\n num0 = length $ filter (== 0) a\n rnum5 = num5 - (mod num5 9)\n in if num0 == 0 then \"-1\" else (if rnum5 == 0 then \"0\" else (construct rnum5 num0))\n \nconstruct :: Int -> Int -> String\nconstruct 0 0 = \"\"\nconstruct 0 num0 = '0' : (construct 0 (num0 - 1))\nconstruct num5 num0 = '5' : (construct (num5 - 1) num0)\n"}, {"source_code": "main :: IO()\nmain = putStrLn . solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> String\nsolve a =\n let num5 = length $ filter (== 5) a\n num0 = length $ filter (== 0) a\n rnum5 = num5 - (mod num5 9)\n in if num0 == 0 then \"-1\" else (if rnum5 == 0 then \"0\" else (construct rnum5 num0))\n \nconstruct :: Int -> Int -> String\nconstruct 0 0 = \"\"\nconstruct 0 num0 = '0' : (construct 0 (num0 - 1))\nconstruct num5 num0 = '5' : (construct (num5 - 1) num0)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport Data.Char\nmain = do\n n <- readLn\n l <- take n . map read . words <$> getLine\n let (zeros,fives) = partition (==0) l\n let k = length fives `div` 9 * 9\n let ans = take k fives ++ zeros\n if null zeros then\n print (-1)\n else if k == 0 then\n print 0\n else\n putStrLn $ map intToDigit ans\n\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> String\nsolve as\n | zero == 0 = \"-1\"\n | five < 9 = \"0\"\n | otherwise = replicate (five - five `mod` 9) '5' ++ replicate zero '0'\n where\n five = length $ filter (== 5) as\n zero = length $ filter (== 0) as\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n putStrLn $ solve as"}, {"source_code": "module Main where\nimport Control.Applicative\nmain :: IO ()\nmain = do\n _ <- getLine\n nums <- map read . words <$> getLine :: IO [Int]\n let (zeros,fives) = foldl (\\(z,f) x -> case x of\n 0 -> (z+1,f)\n 5 -> (z,f+1))\n (0,0)\n nums\n possNumFives = filter (isDiv9 . (5*)) [fives,fives-1..0]\n numba:_ = map (getNumber 0) possNumFives\n if zeros == 0\n then print (-1)\n else print $ numba * 10^zeros\n\ngetNumber acc 0 = acc\ngetNumber acc n = getNumber (10*acc+5) (n-1)\n\nsumd2 0 acc = acc\nsumd2 x acc = sumd2 (x `div` 10) (acc + (x `mod` 10))\n\nisDiv9 :: Integral a => a -> Bool\nisDiv9 x\n | x <= 9 = x `elem` [0,9]\n | otherwise = isDiv9 $ sumd2 x 0\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nsolve :: [Int] -> String\nsolve xs =\n if isJust $ find (==0) xs\n then\n case result of\n [] -> \"-1\"\n 0:_ -> \"0\"\n _ -> concatMap show result\n else\n \"-1\"\n where ys = reverse $ sort xs\n s = sum xs\n n = length $ takeWhile (\\x -> x `mod` 9 /= 0) $ scanl (-) s ys\n (_, result) = splitAt n ys\n\nf = solve . map read . tail . words\nmain = interact f\n"}, {"source_code": "main=getContents>>=putStrLn.s.map read.words\ns(_:a)|z<1=\"-1\"|f<9=\"0\"|1>0=replicate(f-f`mod`9)'5'++replicate z '0' where f=length(filter(==5)a);z=length(filter(==0)a)\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve as | zero < 1 = \"-1\"\n | five < 9 = \"0\"\n | otherwise = replicate (five - five `mod` 9) '5' ++ replicate zero '0'\n where five = length (filter (==5) as)\n zero = length (filter (==0) as)\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . solve . map read . words\n\nsolve :: [Int] -> String\nsolve (_:as) | zero < 1 = \"-1\"\n | five < 9 = \"0\"\n | otherwise = replicate (9 * (five `div` 9)) '5' ++ replicate zero '0'\n where five = length (filter (==5) as)\n zero = length (filter (==0) as)\nsolve _ = undefined\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | null res = \"-1\"\n | all (== '0') res = \"0\"\n | null zs = \"-1\"\n | otherwise = res where\n (fs,zs) = partition (== '5') as\n nf = length fs\n res = replicate (nf `div` 9 * 9) '5' ++ zs\n"}, {"source_code": "import Data.List\nmain = getContents >>= putStrLn . solve . group . sort . map head . tail . words\n\nsolve [as] = if head as == '0' then \"0\" else \"-1\"\nsolve [zeros, fives] = replicate (9 * (length fives `div` 9)) '5' ++\n if 9 <= length fives then zeros else \"0\"\n \n\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: [Int] -> String\nsolve xs\n\t| zeroes == 0 = \"-1\"\n\t| fives < 9 = \"0\"\n\t| otherwise = replicate (9 * countFives) '5' ++ replicate zeroes '0'\n\twhere fives = length $ filter (== 5) xs\n\t zeroes = length xs - fives;\n\t countFives = fives `div` 9;\n\t \n\nmain :: IO ()\nmain = do\n\tB.getLine\n\txs <- getIntList\n\tputStrLn $ solve xs\n\t\n\ngetInt :: IO Int\ngetInt = readInt `fmap` B.getLine\n\ngetIntList :: IO [Int]\ngetIntList = readIntList `fmap` B.getLine\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nreadIntList :: C.ByteString -> [Int]\nreadIntList = map readInt . C.words\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \t\n\nmain= do\n\tgetLine\n\ts<- getLine \n\tlet c5 = length $ filter (=='5') s\n\tlet c0 = length $ filter (=='0') s\n putStrLn $ if c0==0 then \"-1\" else if c5<9 then \"0\" else (replicate (c5-(mod c5 9)) '5' )++ (replicate c0 '0')\n \n\t \n\t "}, {"source_code": "solve xs\n |nFives < 9 = if (foldl (\\x y -> if x == True then x else y == \"0\") False xs) == True then \"0\" else \"-1\"\n |nZeros == 0 = \"-1\"\n |otherwise = (replicate remain '5') ++ ( ['0'|x<-xs,x==\"0\"])\n where nFives = length $ filter (==\"5\") xs\n nZeros = length xs - nFives\n remain = (nFives `div`9) * 9\n\nmain = interact $ solve . tail . words "}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport Data.Functor\n\nmain = do\n n <- read <$> getLine :: IO Int\n cards <- sort <$> (words <$> getLine) :: IO [String]\n putStrLn (solve n cards)\n return ()\n \nsolve n cards = if n0 == 0 then \"-1\"\n else (replicate n5 '5') ++ (replicate n0 '0')\n where n5 = (length (filter (\\s -> s==\"5\") cards))`div`9*9\n n0 = if n5==0 then 1 else length (filter (\\s -> s==\"0\") cards)"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport Data.Char\nmain = do\n n <- readLn\n l <- take n . map read . words <$> getLine\n let (zeros,fives) = partition (==0) l\n let k = length fives `div` 9 * 9\n let ans = take k fives ++ zeros\n if k == 0 && null zeros then\n print (-1)\n else if k == 0 then\n print 0\n else\n putStrLn $ map intToDigit ans\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport Data.Char\nmain = do\n n <- readLn\n l <- take n . map read . words <$> getLine\n let (zeros,fives) = partition (==0) l\n let k = length fives `div` 9 * 9\n let ans = if k == 0 then [0] else take k fives ++ zeros\n putStrLn $ map intToDigit ans\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nmain :: IO ()\nmain = do\n _ <- getLine\n nums <- map read . words <$> getLine :: IO [Int]\n let (zeros,fives) = foldl (\\(z,f) x -> case x of\n 0 -> (z+1,f)\n 5 -> (z,f+1))\n (0,0)\n nums\n possNumFives = filter (isDiv9 . (5*)) [fives,fives-1..0]\n numba:_ = map (getNumber 0) possNumFives\n print $ numba * 10^zeros\n\ngetNumber acc 0 = acc\ngetNumber acc n = getNumber (10*acc+5) (n-1)\n\nsumd2 0 acc = acc\nsumd2 x acc = sumd2 (x `div` 10) (acc + (x `mod` 10))\n\nisDiv9 :: Integral a => a -> Bool\nisDiv9 x\n | x <= 9 = x `elem` [0,9]\n | otherwise = isDiv9 $ sumd2 x 0\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | (null zs || null (tail zs)) && fives == 0 = \"-1\"\n | fives == 0 = \"0\"\n | otherwise = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9 * 9\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | fives == 0 = \"0\"\n | otherwise = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | null zs && fives == 0 = \"-1\"\n | fives == 0 = \"0\"\n | otherwise = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9 * 9\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | null (drop 1 zs) && fives == 0 && not (null zs) = \"-1\"\n | fives == 0 = \"0\"\n | otherwise = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9 * 9\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | fives == 0 = \"0\"\n | otherwise = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9 * 9\n"}, {"source_code": "import Data.List\nmain = interact $ solve . map head . tail . words\nsolve as | null (drop 1 zs) && fives == 0 = \"-1\"\n | fives == 0 = \"0\"\n | otherwise = replicate fives '5' ++ zs where\n (fs,zs) = partition (== '5') as\n nf = length fs\n fives = nf `div` 9 * 9\n"}, {"source_code": "import Data.List\nmain = getContents >>= putStrLn . solve . group . sort . map head . tail . words\n\nsolve [zeros] = \"0\"\nsolve [zeros, fives] = replicate (9 * (length fives `div` 9)) '5' ++\n if 9 <= length fives then zeros else \"0\"\n \n\n"}, {"source_code": "import Data.List\nmain = getContents >>= putStrLn . solve . group . sort . map head . tail . words\n\nsolve [as] = if head as == '0' then \"0\"\n else if 9 <= length as then replicate (9 * (length as `div` 9)) '5'\n else \"-1\"\nsolve [zeros, fives] = replicate (9 * (length fives `div` 9)) '5' ++\n if 9 <= length fives then zeros else \"0\"\n \n\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: [Int] -> String\nsolve xs\n\t| zeroes == 0 = \"-1\"\n\t| fives < 9 = \"0\"\n\t| otherwise = replicate (9 * fives `div` 9) '5' ++ replicate zeroes '0'\n\twhere fives = length $ filter (== 5) xs\n\t zeroes = length xs - fives;\n\t \n\nmain :: IO ()\nmain = do\n\tB.getLine\n\txs <- getIntList\n\tputStrLn $ solve xs\n\t\n\ngetInt :: IO Int\ngetInt = readInt `fmap` B.getLine\n\ngetIntList :: IO [Int]\ngetIntList = readIntList `fmap` B.getLine\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nreadIntList :: C.ByteString -> [Int]\nreadIntList = map readInt . C.words\n"}, {"source_code": "solve xs\n |nFives < 9 = if (foldl (\\x y -> if x == True then x else y == \"0\") False xs) == True then \"0\" else \"-1\"\n |otherwise = (replicate remain '5') ++ ( ['0'|x<-xs,x==\"0\"])\n where nFives = length $ filter (==\"5\") xs\n remain = (nFives `div`9) * 9\n\nmain = interact $ solve . tail . words "}, {"source_code": "solve xs\n |nFives < 9 = if (foldl (\\x y -> if x == True then x else y == \"0\") False xs) == True then \"0\" else \"-1\"\n |otherwise = (replicate remain '5') ++ (unlines [x|x<-xs,x==\"0\"])\n where nFives = length $ filter (==\"5\") xs\n remain = (nFives `div`9) * 9\n\nmain = interact $ solve . tail . words "}], "src_uid": "409b27044d5ec97b5315c92d4112376f"} {"source_code": "import Data.List\n\nmain:: IO()\nmain = do\n\tinput <- getContents\n\tlet\n\t\t(n:m:b) = map read (words input)::[Int]\n\t\tu = map length ( group $ sort b )\n\t\tcnt1=sum [1|x<-u,x==1]\n\t\tcnt2=sum [1|x<-u,x==2]\n\t\tans = if(cnt1==2 && cnt2==n-2)\n\t\t\t\tthen \"bus topology\"\n\t\t\t else if( cnt1==0 && cnt2==n)\n\t\t\t\tthen \"ring topology\"\n\t\t\t else if( cnt1==n-1 )\n\t\t\t\tthen \"star topology\"\n\t\t\t else \"unknown topology\"\n\tputStrLn ans\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nmain :: IO ()\nmain = do\n (n:m:a) <- map readInt . C.words <$> C.getContents\n let s = maximum $ map length $ group $ sort a\n ans = if m == n - 1 then\n if s == 2 then \"bus\"\n else if s == n - 1 then \"star\"\n else \"unknown\"\n else if m == n then\n if s == 2 then \"ring\"\n else \"unknown\"\n else \"unknown\"\n putStrLn $ ans ++ \" topology\"\n"}, {"source_code": "\nimport Data.List\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = map read (words input)\n n = head numbers\n degree = map length (group $ sort $ tail $ tail numbers::[[Int]])\n cnt1 = length $ filter (==1) degree\n cnt2 = length $ filter (==2) degree\n putStr $\n if cnt1==2&&cnt2==n-2\n then \"bus topology\\n\"\n else if cnt2==n\n then \"ring topology\\n\"\n else if cnt1==n-1\n then \"star topology\\n\"\n else \"unknown topology\\n\""}, {"source_code": "\nimport Data.List\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n (n:_:lst) = map read (words input)::[Int]\n degree = map length (group $ sort $ lst)\n cnt x = length $ filter (==x) degree\n cnt1 = cnt 1\n cnt2 = cnt 2\n putStrLn $\n if cnt1==2&&cnt2==n-2\n then \"bus topology\"\n else if cnt2==n\n then \"ring topology\"\n else if cnt1==n-1\n then \"star topology\"\n else \"unknown topology\""}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array (accumArray, elems)\nimport Data.Char (ord, toLower, toUpper)\nimport Data.List (intercalate, nub, sort)\n\ndata NetType = Bus | Ring | Star | Unknown\n\ninstance Show NetType\n where\n show Bus = \"bus topology\"\n show Ring = \"ring topology\"\n show Star = \"star topology\"\n show _ = \"unknown topology\"\n\nsolve :: Int -> Int -> [[Int]] -> NetType\nsolve n m edges\n | n == m && zip == [2] = Ring\n | n == (m+1) && zip == [1,2] = Bus\n | n == (m+1) && zip == [1,n-1] = Star\n | otherwise = Unknown\n where\n d = accumArray (+) 0 (1, n) [(v, 1) | v <- concat edges]\n zip = sort $ nub $ elems d\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n edges <- replicateM m reads\n print $ solve n m edges\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "import Data.List\n\nmain:: IO()\nmain = do\n\tinput <- getContents\n\tlet\n\t\t(n:m:b) = map read (words input)::[Int]\n\t\tsorted = sort b\n\t\tdegree = group sorted\n\t\tu = foldl'(\\t a -> (length a):t) [] degree\n\t\tcnt1=sum [1|x<-u,x==1]\n\t\tcnt2=sum [1|x<-u,x==2]\n\t\tans = if(cnt1==2 && cnt2==n-2)\n\t\t\t\tthen \"bus topology\"\n\t\t\t else if( cnt1==0 && cnt2==n)\n\t\t\t\tthen \"ring topology\"\n\t\t\t else if( cnt1==n-1 )\n\t\t\t\tthen \"star topology\"\n\t\t\t else \"unknown topology\"\n\tputStrLn ans\n"}], "negative_code": [{"source_code": "\nimport Data.List\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = map read (words input)\n n = head numbers\n degree = map length (group $ sort $ tail $ tail numbers::[[Int]])\n cnt1 = length $ filter (==1) degree\n cnt2 = length $ filter (==2) degree\n print $\n if cnt1==2&&cnt2==n-2\n then \"bus topology\"\n else if cnt2==n\n then \"ring topology\"\n else if cnt1==n-1\n then \"star topology\"\n else \"unknown topology\""}], "src_uid": "7bb088ce5e4e2101221c706ff87841e4"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL, shiftR)\nimport Data.Char (ord, isSpace)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\nimport qualified Data.ByteString.Char8 as BS (readInt, getContents, getLine, dropWhile)\n\nparseInts s = parse id s []\n where\n parse r s = case BS.readInt (BS.dropWhile isSpace s) of\n Nothing -> r\n Just (i, s') -> parse (r . (i :)) s'\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nmm = 998244353 :: Int64\n\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = (a + b) - mm\n\n{-# INLINE madd #-}\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n\n{-# INLINE mmul #-}\nsearch ::\n forall s.\n (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right) = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n access l r = readArray mem (hash l r)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise = liftA2 mmul (access l l') (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, lp)\n rv = match (rp + 1, right)\n match (l, r) =\n foldr\n (liftA2 madd)\n (return 0)\n [liftA2 mmul (access l m) (access m r) | m <- [l .. r]]\n in liftA2 mmul lov (liftA2 mmul lv rv)\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts BS.getLine\n a <- fmap parseInts BS.getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nmm = 998244353 :: Int64\n\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = (a + b) - mm\n\n{-# INLINE madd #-}\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n\n{-# INLINE mmul #-}\nsearch ::\n forall s.\n (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right)\n | left == right = return ()\n | otherwise = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise =\n liftA2 mmul (readArray mem (hash l l')) (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, left, lp)\n rv = match (rp + 1, rp + 1, right)\n match (l, m, r)\n | m > r = return 0\n | m == r = readArray mem (hash l m)\n | otherwise =\n let m' = (ext ! m) + 1\n in liftA2\n madd\n (liftA2\n mmul\n (readArray mem (hash l m))\n (readArray mem (hash m r)))\n (match (l, m', r))\n in liftA2 mmul lov (liftA2 mmul lv rv)\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Int (Int64)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\n\nmm = 998244353 :: Int64\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = a + b - mm\n\n{-# INLINE madd #-}\n\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = fromIntegral (toInteger a * toInteger b `mod` toInteger mm)\n{-# INLINE mmul #-}\n\nsearch ::\n forall s. (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right)\n | left == right = return ()\n | otherwise = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise =\n liftA2 mmul (readArray mem (hash l l')) (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, left, lp)\n rv = match (rp + 1, rp + 1, right)\n match (l, m, r)\n | m > r = return 0\n | m == r = readArray mem (hash l m)\n | otherwise =\n let m' = (ext ! m) + 1\n in liftA2\n madd\n (liftA2\n mmul\n (readArray mem (hash l m))\n (readArray mem (hash m r)))\n (match (l, m', r))\n in fmap product (sequence [lov, lv, rv])\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Int (Int64)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\n\nmm = 998244353 :: Int64\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = a + b - mm\n\n{-# INLINE madd #-}\n\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n{-# INLINE mmul #-}\n\nsearch ::\n forall s. (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right)\n | left == right = return ()\n | otherwise = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise =\n liftA2 mmul (readArray mem (hash l l')) (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, left, lp)\n rv = match (rp + 1, rp + 1, right)\n match (l, m, r)\n | m > r = return 0\n | m == r = readArray mem (hash l m)\n | otherwise =\n let m' = (ext ! m) + 1\n in liftA2\n madd\n (liftA2\n mmul\n (readArray mem (hash l m))\n (readArray mem (hash m r)))\n (match (l, m', r))\n in fmap product (sequence [lov, lv, rv])\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: (ST s) (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}], "src_uid": "5ca990a9f93c0b9450aa22a723403b1f"} {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Ord\nimport Control.Monad\nmain = do\n n <- readLn\n rs <- replicateM n $ do\n [s,nm] <- liftM words getLine\n (t,p,g) <- liftM classify $ replicateM (read s) $\n liftM (filter (/= '-')) getLine\n return (nm,t,p,g)\n let mt = taxis $ maximumBy (comparing taxis) rs\n mp = pizzas $ maximumBy (comparing pizzas) rs\n mg = girls $ maximumBy (comparing girls) rs\n putStrLn $ \"If you want to call a taxi, you should call: \" ++\n intercalate \", \" (map name $ filter ((== mt) . taxis) rs) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++\n intercalate \", \" (map name $ filter ((== mp) . pizzas) rs) ++ \".\"\n putStrLn $ \"If you want to go to a cafe with a wonderful girl, you should call: \" ++ intercalate \", \" (map name $ filter ((== mg) . girls) rs) ++ \".\"\nname (n,_,_,_) = n\ntaxis (_,t,_,_) = t\npizzas (_,_,p,_) = p\ngirls (_,_,_,g) = g\nclassify ns = (length ts,length ps,length gs)\n where (ts,ts') = partition isTaxi ns\n (ps,gs) = partition isPizza ts'\nisTaxi (x:y:zs) = x == y && isTaxi (y:zs)\nisTaxi _ = True\nisPizza (x:y:zs) = x > y && isPizza (y:zs)\nisPizza _ = True"}, {"source_code": "import Data.List\n\ndata Contacts = Contacts Int String [String]\n\nmxnames myfunc contacts = map (\\(Contacts n name nos) -> name) $ myfunc contacts\nisTaxi x = 1 == (length.nub) x\nisPizza x = x == (reverse.sort.nub) x\nisGirl x = (not (isTaxi x)) && (not (isPizza x))\n\ngetMax myfunc contacts = intercalate \", \" $ mxnames myMaxes contacts\n where mylen (Contacts n name nos) = length $ filter myfunc nos\n myMaxes contacts = filter (\\x -> mylen x == mval) contacts\n where mval = maximum $ map mylen contacts\n\nreadContact :: IO Contacts\nreadContact = do\n [n1, name] <- fmap words getLine\n let n = read n1\n getno = do\n no <- fmap (filter (\\x -> x /= '-')) getLine\n return no\n nos <- sequence $ take n $ repeat getno\n return $ Contacts n name nos\n\nmain = do\n n <- fmap read getLine\n contacts <- sequence $ take n $ repeat readContact\n putStrLn $ \"If you want to call a taxi, you should call: \" ++ (getMax isTaxi contacts) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++ (getMax isPizza contacts) ++ \".\"\n putStrLn $ \"If you want to go to a cafe with a wonderful girl, you should call: \" ++ (getMax isGirl contacts) ++ \".\""}, {"source_code": "import Data.Char\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\n\nmain = do n <- read <$> getLine\n cs <- forM [1..n] $ \\_->\n do [m,name] <- words <$> getLine\n tels <- forM [1..read m] $ \\_-> parse <$> getLine\n return (name,tels)\n putStrLn $ unlines $ solve cs\n\nparse :: String -> [Int]\nparse = map digitToInt . filter ('-'/=)\n\nunwords' :: [String] -> String\nunwords' [] = []\nunwords' [c] = c++\".\"\nunwords' (c:cs) = c++\", \"++(unwords' cs)\n\nsolve :: [(String,[[Int]])] -> [String]\nsolve xs = [taxi,pizza,girl]\n where taxi = \"If you want to call a taxi, you should call: \"++(unwords' $ map fst $ filter maxTaxi ys)\n pizza = \"If you want to order a pizza, you should call: \"++(unwords' $ map fst $ filter maxPizza ys)\n girl = \"If you want to go to a cafe with a wonderful girl, you should call: \"++(unwords' $ map fst $ filter maxGirl ys)\n ys = map f xs\n maxt = maximum $ map (\\ (_,(x,_,_)) -> x) ys\n maxp = maximum $ map (\\ (_,(_,x,_)) -> x) ys\n maxg = maximum $ map (\\ (_,(_,_,x)) -> x) ys\n maxTaxi (_,(x,_,_)) = x == maxt\n maxPizza (_,(_,x,_)) = x == maxp\n maxGirl (_,(_,_,x)) = x == maxg\n \nf :: (String,[[Int]]) -> (String,(Int,Int,Int))\nf (name,xss) = (name,(g isTaxi xss,g isPizza xss,g isGirl xss))\n\ng :: ([Int] -> Bool) -> [[Int]] -> Int\ng p xss = length $ filter p xss\n\nisTaxi (x:xs) = all (x==) xs\nisPizza [x] = True\nisPizza (x:xs) = all ()x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\n\naddNumber [t,p,g] = parse.filter (/='-') where\n\tparse s\n\t\t| length (nub s) == 1 = [t+1,p,g]\n\t\t| s==reverse (sort s) && length (nub s)==6 = [t,p+1,g]\n\t\t| otherwise = [t,p,g+1]\n\nconsume [] = []\nconsume ([count,name]:t) = (name, nCount):consume rest where\n\t(phones,rest) = splitAt (read count) t\n\tnCount = foldl (addNumber) [0,0,0] (map head phones)\n\t\nprintInfo info = unlines [tm,pm,gm] where\n\tgetX x = (!!x).snd\n\tmaxX x = maximum (map (getX x) info)\n\tbstsX x = concat.intersperse \", \".map fst.filter ((==) (maxX x).getX x)$info\n\ttm = \"If you want to call a taxi, you should call: \"++bstsX 0++\".\"\n\tpm = \"If you want to order a pizza, you should call: \"++bstsX 1++\".\"\n\tgm = \"If you want to go to a cafe with a wonderful girl, you should call: \"++bstsX 2++\".\"\n\n\nmain=interact$printInfo.consume.map words.tail.lines\n\t"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\n\nisPizza list = and $ zipWith (>) list (tail list)\nisTaxi list = and $ zipWith (==) list (tail list)\nisGirl list = not (isPizza list) && not (isTaxi list)\n\nprocess str f friends =\n let c = [ (name, length $ filter f phone) | (name, phone) <- friends]\n mx = maximum $ map snd c\n ans = map fst $ filter ((== mx) . snd) c\n in str ++ intercalate \", \" ans ++ \".\"\n\nmain = do\n n <- liftM read getLine\n friends <- replicateM (n :: Int) $ do\n [m', name] <- liftM words getLine\n\n phones <- replicateM (read m' :: Int) $ do\n line <- getLine\n return [ord c - ord '0' |\n p <- [0, 1, 3, 4, 6, 7],\n let c = line !! p]\n \n return (name, phones)\n\n putStrLn $ process \"If you want to call a taxi, you should call: \" isTaxi friends\n putStrLn $ process \"If you want to order a pizza, you should call: \" isPizza friends\n putStrLn $ process \"If you want to go to a cafe with a wonderful girl, you should call: \" isGirl friends\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Function\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\ntype Book = ([Number], [Number], [Number])\ntype Number = (Int, Int, Int, Int, Int, Int)\n\ngetNumber :: IO Number\ngetNumber = do {(a:b:_:c:d:_:e:f:_) <- getLine;return (digitToInt a,digitToInt b,digitToInt c,digitToInt d,digitToInt e,digitToInt f)}\n\nisTaxi :: Number -> Bool\nisTaxi (a,b,c,d,e,f) = a==b && a==c && a==d && a==e && a==f\n\nisPizza :: Number -> Bool\nisPizza (a,b,c,d,e,f) = a>b && b>c && c>d && d>e && e>f\n\nmain_loop2 :: Int -> Book -> IO Book\nmain_loop2 n b@(b1,b2,b3) = if n == 0 then return b\n else\n do pn <- getNumber\n if isTaxi pn then\n main_loop2 (n-1) (pn:b1, b2, b3)\n else\n if isPizza pn then\n main_loop2 (n-1) (b1, pn:b2, b3)\n else\n main_loop2 (n-1) (b1, b2, pn:b3)\n\nmain_loop :: Int -> [(String, Book)] -> IO [(String, Book)]\nmain_loop n b = if n==0 then return b\n else\n do\n (m, name) <- scan :: IO (Int, String)\n book <- main_loop2 m ([],[],[])\n main_loop (n-1) ((name, book):b)\n\n\nsolve :: [(String, Book)] -> String\nsolve books = let phonedata = map (\\(name,book) -> (name, (\\(a,b,c) -> (length a, length b, length c)) book)) books\n taxiorder = sortBy (compare `on` (\\(_,(x,_,_)) -> -x)) phonedata\n pizzaorder = sortBy (compare `on` (\\(_,(_,x,_)) -> -x)) phonedata\n girlorder = sortBy (compare `on` (\\(_,(_,_,x)) -> -x)) phonedata\n maxTaxi = (\\(x,_,_) -> x).snd.head $ taxiorder\n maxPizza = (\\(_,x,_) -> x).snd.head $ pizzaorder\n maxGirl = (\\(_,_,x) -> x).snd.head $ girlorder\n maximulTaxi = concat.reverse.intersperse \", \".map fst.takeWhile (\\(_,(x,_,_)) -> x==maxTaxi) $ taxiorder\n maximulPizza = concat.reverse.intersperse \", \".map fst.takeWhile (\\(_,(_,x,_)) -> x==maxPizza) $ pizzaorder\n maximulGirl = concat.reverse.intersperse \", \".map fst.takeWhile (\\(_,(_,_,x)) -> x==maxGirl) $ girlorder\n in\n \"If you want to call a taxi, you should call: \"++ maximulTaxi++\".\\nIf you want to order a pizza, you should call: \" ++ maximulPizza++\".\\nIf you want to go to a cafe with a wonderful girl, you should call: \"++ maximulGirl ++\".\"\n\nmain = do n <- scan :: IO Int\n books <- main_loop n []\n putStrLn.solve $ books"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "\nimport Data.List (intercalate)\n\ntype Phone = String\n\nisTaxi :: Phone -> Bool\nisTaxi [c1, c2, _, c3, c4, _, c5, c6]\n = c1 == c2\n && c1 == c3\n && c1 == c4\n && c1 == c5\n && c1 == c6\nisTaxi s = error $ \"isTaxi: incorrect format:\" ++ s\n\nisPizza :: Phone -> Bool\nisPizza [c1, c2, _, c3, c4, _, c5, c6]\n = c1 > c2\n && c2 > c3\n && c3 > c4\n && c4 > c5\n && c5 > c6\nisPizza s = error $ \"isPizza: incorrect format:\" ++ s\n\nisGirl :: Phone -> Bool\nisGirl s = not (isPizza s) && not (isTaxi s)\n\n--------------------------------------------------------------------------------\n\ntype Friend = (String, [Phone])\n\ncountPhones :: (Phone -> Bool) -> Friend -> Int\ncountPhones f (_, phones) = length $ filter f phones\n\nreplicateM :: Monad m => Int -> m a -> m [a]\nreplicateM n action = sequence (map (\\x -> action) [1..n])\n\nreadFriend :: IO Friend\nreadFriend = do\n line <- getLine\n let m = read $ head $ words line\n let name = words line !! 1\n phones <- replicateM m getLine\n return (name, phones)\n\n--------------------------------------------------------------------------------\n\nsolve :: [Friend] -> ([Friend], [Friend], [Friend])\nsolve friends = solve' friends ([], [], [])\n where\n maxTaxi = maximum (map (countPhones isTaxi ) friends)\n maxPizza = maximum (map (countPhones isPizza) friends)\n maxGirl = maximum (map (countPhones isGirl ) friends)\n solve' [] (t, p, g) = (reverse t, reverse p, reverse g)\n solve' (f:fs) (t, p, g) = solve' fs (ts, ps, gs)\n where\n ts = if countPhones isTaxi f == maxTaxi then f:t else t\n ps = if countPhones isPizza f == maxPizza then f:p else p\n gs = if countPhones isGirl f == maxGirl then f:g else g\n\ntext1 = \"If you want to call a taxi, you should call: \"\ntext2 = \"If you want to order a pizza, you should call: \"\ntext3 = \"If you want to go to a cafe with a wonderful girl, you should call: \"\n\nprintAns :: ([Friend], [Friend], [Friend]) -> IO ()\nprintAns (f1, f2, f3) = do\n putStr text1 >> putStr (show' f1) >> putStrLn \".\"\n putStr text2 >> putStr (show' f2) >> putStrLn \".\"\n putStr text3 >> putStr (show' f3) >> putStrLn \".\"\n where\n show' fs = intercalate \", \" (map fst fs)\n\nmain :: IO ()\nmain = do\n n <- readLn\n friends <- replicateM n readFriend\n printAns $ solve friends\n"}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines\n\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\ndata Contacts = Contacts String [String]\n\nmxnames myfunc contacts = map (\\(Contacts name nos) -> name) $ myfunc contacts\nisTaxi = (1==).length.nub\nisPizza x = x == (reverse.sort.nub) x\nisGirl x = (not (isTaxi x)) && (not (isPizza x))\n\ngetMax myfunc contacts = intercalate \", \" $ mxnames myMaxes contacts\n where mylen (Contacts name nos) = length $ filter myfunc nos\n myMaxes contacts = filter ((mval==).mylen) contacts\n where mval = maximum $ map mylen contacts\n\nreadContact :: IO Contacts\nreadContact = do\n [n1, name] <- fmap words getLine\n let n = read n1\n getno = do\n no <- fmap (filter (/= '-')) getLine\n return no\n nos <- replicateM n getno\n return $ Contacts name nos\n\nmain = do\n n <- fmap read getLine\n contacts <- replicateM n readContact\n putStrLn $ \"If you want to call a taxi, you should call: \" ++ (getMax isTaxi contacts) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++ (getMax isPizza contacts) ++ \".\"\n putStrLn $ \"If you want to go to a cafe with a wonderful girl, you should call: \" ++ (getMax isGirl contacts) ++ \".\"\n "}, {"source_code": "import Data.List\n\ndata Contacts = Contacts Int String [String]\n\nmxnames myfunc contacts = map (\\(Contacts n name nos) -> name) $ myfunc contacts\nisTaxi x = 1 == (length.nub) x\nisPizza x = x == (reverse.sort.nub) x\nisGirl x = (not (isTaxi x)) && (not (isPizza x))\n\ngetMaxTaxis contacts = intercalate \", \" $ mxnames mxTaxis contacts\n where taxis (Contacts n name nos) = length $ filter isTaxi nos\n mxTaxis contacts = filter (\\x -> taxis x == mval) contacts\n where mval = maximum $ map taxis contacts\n\ngetMaxPizza contacts = intercalate \", \" $ mxnames mxPizzas contacts\n where pizzas (Contacts n name nos) = length $ filter isPizza nos\n mxPizzas contacts = filter (\\x -> pizzas x == mval) contacts\n where mval = maximum $ map pizzas contacts\n\ngetMaxGirls contacts = intercalate \", \" $ mxnames mxGirls contacts\n where girls (Contacts n name nos) = length $ filter isGirl nos\n mxGirls contacts = filter (\\x -> girls x == mval) contacts\n where mval = maximum $ map girls contacts\n\nreadContact :: IO Contacts\nreadContact = do\n [n1, name] <- fmap words getLine\n let n = read n1\n getno = do\n no <- fmap (filter (\\x -> x /= '-')) getLine\n return no\n nos <- sequence $ take n $ repeat getno\n return $ Contacts n name nos\n\nmain = do\n n <- fmap read getLine\n contacts <- sequence $ take n $ repeat readContact\n putStrLn $ \"If you want to call a taxi, you should call: \" ++ (getMaxTaxis contacts) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++ (getMaxPizza contacts) ++ \".\"\n putStrLn $ \"If you want to go to a cafe with a wonderful girl, you should call: \" ++ (getMaxGirls contacts) ++ \".\"\n "}, {"source_code": "import Data.List\n\ndata Contacts = Contacts Int String [String]\n\nmxnames myfunc contacts = map (\\(Contacts n name nos) -> name) $ myfunc contacts\nisTaxi x = 1 == (length.nub) x\nisPizza x = x == (reverse.sort.nub) x\nisGirl x = (not (isTaxi x)) && (not (isPizza x))\n\ngetMax myfunc contacts = intercalate \", \" $ mxnames myMaxes contacts\n where mylen (Contacts n name nos) = length $ filter myfunc nos\n myMaxes contacts = filter (\\x -> mylen x == mval) contacts\n where mval = maximum $ map mylen contacts\n\nreadContact :: IO Contacts\nreadContact = do\n [n1, name] <- fmap words getLine\n let n = read n1\n getno = do\n no <- fmap (filter (\\x -> x /= '-')) getLine\n return no\n nos <- sequence $ take n $ repeat getno\n return $ Contacts n name nos\n\nmain = do\n n <- fmap read getLine\n contacts <- sequence $ take n $ repeat readContact\n putStrLn $ \"If you want to call a taxi, you should call: \" ++ (getMax isTaxi contacts) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++ (getMax isPizza contacts) ++ \".\"\n putStrLn $ \"If you want to go to a cafe with a wonderful girl, you should call: \" ++ (getMax isGirl contacts) ++ \".\"\n "}, {"source_code": "import Data.List\np[]f=[]\np(h:t)f=(s,length(filter f a)):p r f where[z,s]=words h;(a,r)=splitAt(read z)t\nt=(==1).length.nub\nz x=and$zipWith(>)x(tail x)\nl x=not$z x||t x\ns p=g\"call a taxi\"t++g\"order a pizza\"z++g\"go to a cafe with a wonderful girl\"l where g s f=\"If you want to \"++s++\", you should call: \"++intercalate\", \"(b$p f)++\".\\n\";b l=[x|(x,y)<-l,y==maximum(map snd l)]\nmain=interact$s.p.tail.map(filter(/='-')).lines"}, {"source_code": "import Data.List (intercalate, nub, sortBy, unfoldr)\nimport Data.Char (isDigit)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . lines\n\ndata Phone = Phone { name :: String, taxi :: Int, pizza :: Int, girl :: Int } deriving Show\n\nsolve :: [String] -> [String]\nsolve (_:cs) = let cs' = unfoldr f cs in solve' cs'\n where f [] = Nothing\n f (x:xs) = Just (classify n numbers, rest)\n where [ si, n ] = words x\n (numbers, rest) = splitAt (read si) xs\nsolve _ = undefined\n\nsolve' :: [Phone] -> [String]\nsolve' phones = zipWith (++) prefixes [ (++\".\") $ intercalate \", \" $ map name\n $ filter ((==maximum (map f phones)) . f) phones | f <- [ taxi, pizza, girl ] ]\n where prefixes = [ \"If you want to call a taxi, you should call: \",\n \"If you want to order a pizza, you should call: \",\n \"If you want to go to a cafe with a wonderful girl, you should call: \" ]\n\nisTaxi :: String -> Bool\nisTaxi xs = length (nub (filter isDigit xs)) == 1\n\nisPizza :: String -> Bool\nisPizza xs = sortBy (flip compare) (nub xs') == xs'\n where xs' = filter isDigit xs\n\nclassify :: String -> [String] -> Phone\nclassify n xs = Phone n t p (length xs - t - p)\n where t = length (filter isTaxi xs)\n p = length (filter isPizza xs)\n"}, {"source_code": "import Data.List (intercalate, nub, sortBy, unfoldr)\nimport Data.Char (isDigit)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . lines\n\ndata Phone = Phone { name :: String, taxi :: Int, pizza :: Int, girl :: Int } deriving Show\n\nsolve :: [String] -> [String]\nsolve (_:cs) = let cs' = unfoldr f cs in solve' cs'\n where f [] = Nothing\n f (x:xs) = Just (classify n numbers, rest)\n where [ si, n ] = words x\n (numbers, rest) = splitAt (read si) xs\nsolve _ = undefined\n\nsolve' :: [Phone] -> [String]\nsolve' phones = zipWith (++) prefixes [ (++\".\") $ intercalate \", \" $ map name\n $ filter ((==maximum (map f phones)) . f) phones | f <- [ taxi, pizza, girl ] ]\n where prefixes = [ \"If you want to call a taxi, you should call: \",\n \"If you want to order a pizza, you should call: \",\n \"If you want to go to a cafe with a wonderful girl, you should call: \" ]\n\nisTaxi :: String -> Bool\nisTaxi xs = length (nub (filter isDigit xs)) == 1\n\nisPizza :: String -> Bool\nisPizza xs = length (nub xs') == 6 && xs' == sortBy (flip compare) xs'\n where xs' = filter isDigit xs\n\nclassify :: String -> [String] -> Phone\nclassify n xs = Phone n t p (length xs - t - p)\n where t = length (filter isTaxi xs)\n p = length (filter isPizza xs)\n"}, {"source_code": "import Data.List (intercalate, nub, sortBy, unfoldr)\nimport Data.Char (isDigit)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . tail . lines\n\ndata Phone = Phone { name :: String, taxi :: Int, pizza :: Int, girl :: Int } deriving Show\n\nsolve :: [String] -> [String]\nsolve = solve' . unfoldr f\n where f [] = Nothing\n f (x:xs) = Just (classify n numbers, rest)\n where [ si, n ] = words x\n (numbers, rest) = splitAt (read si) xs\n\nsolve' :: [Phone] -> [String]\nsolve' phones = zipWith (++) prefixes [ (++\".\") $ intercalate \", \" $ map name\n $ filter ((==maximum (map f phones)) . f) phones | f <- [ taxi, pizza, girl ] ]\n where prefixes = [ \"If you want to call a taxi, you should call: \",\n \"If you want to order a pizza, you should call: \",\n \"If you want to go to a cafe with a wonderful girl, you should call: \" ]\n\nisTaxi :: String -> Bool\nisTaxi xs = length (nub (filter isDigit xs)) == 1\n\nisPizza :: String -> Bool\nisPizza xs = sortBy (flip compare) (nub xs') == xs'\n where xs' = filter isDigit xs\n\nclassify :: String -> [String] -> Phone\nclassify n xs = Phone n t p (length xs - t - p)\n where t = length (filter isTaxi xs)\n p = length (filter isPizza xs)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Ord\nimport Control.Monad\nmain = do\n n <- readLn\n rs <- replicateM n $ do\n [s,nm] <- liftM words getLine\n (t,p,g) <- liftM classify $ replicateM (read s) $\n liftM (filter (/= '-')) getLine\n return (nm,t,p,g)\n let mt = taxis $ maximumBy (comparing taxis) rs\n mp = pizzas $ maximumBy (comparing pizzas) rs\n mg = girls $ maximumBy (comparing girls) rs\n putStrLn $ \"If you want to call a taxi, you should call: \" ++\n intercalate \", \" (map name $ filter ((== mt) . taxis) rs) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++\n intercalate \", \" (map name $ filter ((== mp) . pizzas) rs) ++ \".\"\n putStrLn $ \"Of you want to go to a cafe with a wonderful girl, you should call: \" ++ intercalate \", \" (map name $ filter ((== mg) . girls) rs) ++ \".\"\nname (n,_,_,_) = n\ntaxis (_,t,_,_) = t\npizzas (_,_,p,_) = p\ngirls (_,_,_,g) = g\nclassify ns = (length ts,length ps,length gs)\n where (ts,ts') = partition isTaxi ns\n (ps,gs) = partition isPizza ts'\nisTaxi (x:y:zs) = x == y && isTaxi (y:zs)\nisTaxi _ = True\nisPizza (x:y:zs) = x > y && isPizza (y:zs)\nisPizza _ = True"}, {"source_code": "import Data.List\n\ndata Contacts = Contacts Int String [String]\n\nmxnames myfunc contacts = map (\\(Contacts n name nos) -> name) $ myfunc contacts\nisTaxi x = 1 == (length.nub) x\nisPizza x = x == (reverse.sort.nub) x\nisGirl x = (not (isTaxi x)) && (not (isPizza x))\n\ngetMax myfunc contacts = intercalate \", \" $ mxnames myMaxes contacts\n where mylen (Contacts n name nos) = length $ filter myfunc nos\n myMaxes contacts = filter (\\x -> mylen x == mval) contacts\n where mval = maximum $ map mylen contacts\n\nreadContact :: IO Contacts\nreadContact = do\n [n1, name] <- fmap words getLine\n let n = read n1\n getno = do\n no <- fmap (filter (\\x -> x /= '-')) getLine\n return no\n nos <- sequence $ take n $ repeat getno\n return $ Contacts n name nos\n\nmain = do\n n <- fmap read getLine\n contacts <- sequence $ take n $ repeat readContact\n putStrLn $ \"If you want to call a taxi, you should call: \" ++ (getMax isTaxi contacts) ++ \".\"\n putStrLn $ \"If you want to order a pizza, you should call: \" ++ (getMax isPizza contacts) ++ \".\"\n putStrLn $ \"If you want to go to a cafe with a wonderful girl, you should call: \" ++ (getMax isGirl contacts)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Function\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\ntype Book = ([Number], [Number], [Number])\ntype Number = (Int, Int, Int, Int, Int, Int)\n\ngetNumber :: IO Number\ngetNumber = do {(a:b:_:c:d:_:e:f:_) <- getLine;return (digitToInt a,digitToInt b,digitToInt c,digitToInt d,digitToInt e,digitToInt f)}\n\nisTaxi :: Number -> Bool\nisTaxi (a,b,c,d,e,f) = a==b && a==c && a==d && a==e && a==f\n\nisPizza :: Number -> Bool\nisPizza (a,b,c,d,e,f) = a>b && b>c && c>d && d>e && e>f\n\nmain_loop2 :: Int -> Book -> IO Book\nmain_loop2 n b@(b1,b2,b3) = if n == 0 then return b\n else\n do pn <- getNumber\n if isTaxi pn then\n main_loop2 (n-1) (pn:b1, b2, b3)\n else\n if isPizza pn then\n main_loop2 (n-1) (b1, pn:b2, b3)\n else\n main_loop2 (n-1) (b1, b2, pn:b3)\n\nmain_loop :: Int -> [(String, Book)] -> IO [(String, Book)]\nmain_loop n b = if n==0 then return b\n else\n do\n (m, name) <- scan :: IO (Int, String)\n book <- main_loop2 m ([],[],[])\n main_loop (n-1) ((name, book):b)\n\n\nsolve :: [(String, Book)] -> String\nsolve books = let phonedata = map (\\(name,book) -> (name, (\\(a,b,c) -> (length a, length b, length c)) book)) books\n taxiorder = sortBy (compare `on` (\\(_,(x,_,_)) -> -x)) phonedata\n pizzaorder = sortBy (compare `on` (\\(_,(_,x,_)) -> -x)) phonedata\n girlorder = sortBy (compare `on` (\\(_,(_,_,x)) -> -x)) phonedata\n maxTaxi = (\\(x,_,_) -> x).snd.head $ taxiorder\n maxPizza = (\\(_,x,_) -> x).snd.head $ pizzaorder\n maxGirl = (\\(_,_,x) -> x).snd.head $ girlorder\n maximulTaxi = reverse.concat.intersperse \", \".map fst.takeWhile (\\(_,(x,_,_)) -> x==maxTaxi) $ taxiorder\n maximulPizza = reverse.concat.intersperse \", \".map fst.takeWhile (\\(_,(_,x,_)) -> x==maxPizza) $ pizzaorder\n maximulGirl = reverse.concat.intersperse \", \".map fst.takeWhile (\\(_,(_,_,x)) -> x==maxGirl) $ girlorder\n in\n \"If you want to call a taxi, you should call: \"++ maximulTaxi++\".\\nIf you want to order a pizza, you should call: \" ++ maximulPizza++\".\\nIf you want to go to a cafe with a wonderful girl, you should call: \"++ maximulGirl ++\".\"\n\nmain = do n <- scan :: IO Int\n books <- main_loop n []\n putStrLn.solve $ books"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Function\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\ntype Book = ([Number], [Number], [Number])\ntype Number = (Int, Int, Int, Int, Int, Int)\n\ngetNumber :: IO Number\ngetNumber = do {(a:b:_:c:d:_:e:f:_) <- getLine;return (digitToInt a,digitToInt b,digitToInt c,digitToInt d,digitToInt e,digitToInt f)}\n\nisTaxi :: Number -> Bool\nisTaxi (a,b,c,d,e,f) = a==b && a==c && a==d && a==e && a==f\n\nisPizza :: Number -> Bool\nisPizza (a,b,c,d,e,f) = a>b && b>c && c>d && d>e && e>f\n\nmain_loop2 :: Int -> Book -> IO Book\nmain_loop2 n b@(b1,b2,b3) = if n == 0 then return b\n else\n do pn <- getNumber\n if isTaxi pn then\n main_loop2 (n-1) (pn:b1, b2, b3)\n else\n if isPizza pn then\n main_loop2 (n-1) (b1, pn:b2, b3)\n else\n main_loop2 (n-1) (b1, b2, pn:b3)\n\nmain_loop :: Int -> [(String, Book)] -> IO [(String, Book)]\nmain_loop n b = if n==0 then return b\n else\n do\n (m, name) <- scan :: IO (Int, String)\n book <- main_loop2 m ([],[],[])\n main_loop (n-1) ((name, book):b)\n\n\nsolve :: [(String, Book)] -> String\nsolve books = let phonedata = map (\\(name,book) -> (name, (\\(a,b,c) -> (length a, length b, length c)) book)) books\n taxiorder = sortBy (compare `on` (\\(_,(x,_,_)) -> -x)) phonedata\n pizzaorder = sortBy (compare `on` (\\(_,(_,x,_)) -> -x)) phonedata\n girlorder = sortBy (compare `on` (\\(_,(_,_,x)) -> -x)) phonedata\n maxTaxi = (\\(x,_,_) -> x).snd.head $ taxiorder\n maxPizza = (\\(_,x,_) -> x).snd.head $ pizzaorder\n maxGirl = (\\(_,_,x) -> x).snd.head $ girlorder\n maximulTaxi = concat.intersperse \", \".map fst.takeWhile (\\(_,(x,_,_)) -> x==maxTaxi) $ taxiorder\n maximulPizza = concat.intersperse \", \".map fst.takeWhile (\\(_,(_,x,_)) -> x==maxPizza) $ pizzaorder\n maximulGirl = concat.intersperse \", \".map fst.takeWhile (\\(_,(_,_,x)) -> x==maxGirl) $ girlorder\n in\n \"If you want to call a taxi, you should call: \"++ maximulTaxi++\".\\nIf you want to order a pizza, you should call:\" ++ maximulPizza++\".\\nIf you want to go to a cafe with a wonderful girl, you should call: \"++ maximulGirl ++\".\"\n\nmain = do n <- scan :: IO Int\n books <- main_loop n []\n putStrLn.solve $ books"}], "src_uid": "4791a795119c185b3aec91b6f8af8f03"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\n\nsolve :: [Int] -> Int\nsolve [x, y, z] = min 1 $ abs (2 * y - x - z) `mod` 3\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x, y, z] <- readInts\r\n let m = (x + z - 2 * y) `mod` 3\r\n print $ m `min` (3 - m)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "\r\nimport Control.Monad (replicateM_)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n cs <- getLine\r\n let [a,b,c] = read <$> words cs :: [Int]\r\n let ans = if (a+c-2*b) `mod` 3 == 0 then 0 else 1 \r\n print ans\r\n\r\nmain :: IO ()\r\nmain = do\r\n nStr <- getLine\r\n let n = read nStr\r\n replicateM_ n solve\r\n"}], "negative_code": [{"source_code": "\r\nimport Control.Monad (replicateM_)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n cs <- getLine\r\n let [a,b,c] = read <$> words cs :: [Int]\r\n let ans = (abs (a+c-2*b) `mod` 3) `div` 2\r\n print ans\r\n\r\nmain :: IO ()\r\nmain = do\r\n nStr <- getLine\r\n let n = read nStr\r\n replicateM_ n solve\r\n"}, {"source_code": "\r\nimport Control.Monad (replicateM_)\r\n\r\nsolve = do\r\n cs <- getLine\r\n let [a,b,c] = read <$> words cs :: [Int]\r\n let ans = abs (a+c-2*b) `mod` 3\r\n print ans\r\n \r\nmain = do\r\n nStr <- getLine\r\n let n = read nStr\r\n replicateM_ n solve\r\n \r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x, y, z] <- readInts\r\n print $ (x + z - 2 * y) `mod` 3\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x, y, z] <- readInts\r\n print $ (x + y - 2 * z) `mod` 3\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: [Int] -> Int\r\nsolve [x, y, z] = abs (2 * y - x - z) `mod` 3\r\n"}], "src_uid": "5bffe38e3ac9511a30ee02b4ec5cb1d5"} {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Integer] -> Integer\nsolve as = sum (zipWith (*) [1..] (sort as)) - maximum as + sum as\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List (sort,foldl')\nimport Control.Applicative\nimport Data.Int\nimport Data.Char\nimport Data.Array.Unboxed\n\nreadInt = B.foldl' (\\x c -> 10 * x + fromIntegral (ord c) - 48) 0\n\nmain = do\n n <- read <$> getLine\n xs <- sort . map readInt . B.words <$> B.getContents :: IO [Int64]\n print $ if null . drop 1 $ xs then head xs else\n let ar = listArray (0,n) $ 0:scanl1 (+) xs :: UArray Int Int64\n sm i = ar ! n - ar ! i\n add = ar!n - last xs\n in foldl' (+) 0 . (add:) . map sm $ [0..n-1]\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Integer] -> Integer\nsolve as = sum (zipWith (*) [1..] (sort as)) - maximum as + sum as\n"}, {"source_code": "import Data.List\nmain = print . solve . map read . tail . words =<< getContents\nsolve xs = sum (zipWith (*) [2..] (sort xs)) - maximum xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nmain = do\n\tgetLine\n\ta <- sort . map read . words <$> getLine :: IO [Integer]\n\tprint $ (sum $ zipWith (*) [2..] a) - (last a)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\n \nmain= do\n\ts<- read <$> getLine ::IO Integer\n\tn<- sort.map (fst.fromJust.B.readInteger).B.words <$> B.getLine::IO [Integer]\n\tlet ans= sum $ zipWith (*) n [2..]\n \tif s==1 then print (last n ) else print $ ans - (last n)"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \nmain= do\n\ts<- read <$> getLine ::IO Integer\n\tn<- sort.map read.words <$> getLine::IO [Integer]\n\tlet ans= sum $ zipWith (*) n [2..]\n \tif s==1 then print (last n ) else print $ ans - (last n)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n \nmain :: IO ()\nmain = do\n (_:l:_) <- fmap LC.lines LC.getContents\n let a = L.sort $ readInts l\n print $ count 2 a - (toInteger $ last a)\n\ncount :: Int -> [Int] -> Integer\ncount _ [] = 0\ncount k (x:xs) = toInteger k * toInteger x + count (k+1) xs\n\n-------------------------------------------------------------------------------\n\nreadInts :: LC.ByteString -> [Int]\nreadInts str = map readInt $ LC.words str\n\nreadInt :: LC.ByteString -> Int\nreadInt = LC.foldl' (\\x c -> 10 * x + fromEnum c - 48) 0"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n \nmain :: IO ()\nmain = do\n (_:line:_) <- fmap LC.lines LC.getContents\n let a = map toInteger $ L.sort $ readInts line\n print $ (sum $ zipWith (*) [2..] a) - (toInteger $ last a)\n\n-------------------------------------------------------------------------------\n\nreadInts :: LC.ByteString -> [Int]\nreadInts str = map readInt $ LC.words str\n\nreadInt :: LC.ByteString -> Int\nreadInt = LC.foldl' (\\x c -> 10 * x + fromEnum c - 48) 0"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . map read . words =< Integer\nsolve a = sum (zipWith (*) [1..] (sort a)) - (maximum a) + (sum a)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n print $ (sum $ tail $ scanl1 (+) $ reverse $ sort xs) + sum xs\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInteger x\nsomeFunc::IO()\nsomeFunc = (solve.concat=<map rIn.C.words<$>C.getLine) )\nsolve (x:xs) = print $ (sum $ zipWith (\\a b->a*b) [2..] $ sort xs) - maximum xs\n"}, {"source_code": "import Data.List\n\nmain = do \ngetLine \ngetLine >>= print . (\\x -> let a = sortBy (\\ x y -> if x < y then LT else if x > y then GT else EQ) x in (last a * (toInteger $ length a)) + (sum $ zipWith (*) (init a) [(2::Integer)..])) . map (\\x -> read x :: Integer) . words\n\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List (foldl')\nimport Data.Set (fromList, toList)\nimport Control.Applicative\nimport Data.Int\nimport Data.Char\nimport Data.Array.Unboxed\n\nreadInt = B.foldl' (\\x c -> 10 * x + fromIntegral (ord c) - 48) 0\n\nmain = do\n n <- read <$> getLine\n xs <- map fst . toList . fromList . flip zip [1..] . map readInt . B.words <$> B.getContents :: IO [Int64]\n print $ if null . drop 1 $ xs then head xs else\n let ar = listArray (0,n) $ 0:scanl1 (+) xs :: UArray Int Int64\n sm i = ar ! n - ar ! i\n add = ar!n - last xs\n in foldl' (+) 0 . (add:) . map sm $ [0..n-1]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n \nmain :: IO ()\nmain = do\n (_:l:_) <- fmap LC.lines LC.getContents\n let a = L.sort $ readInts l\n print $ count 2 a - last a\n\ncount :: Int -> [Int] -> Int\ncount _ [] = 0\ncount k (x:xs) = k*x + count (k+1) xs\n\n-------------------------------------------------------------------------------\n\nreadInts :: LC.ByteString -> [Int]\nreadInts str = map readInt $ LC.words str\n\nreadInt :: LC.ByteString -> Int\nreadInt = LC.foldl' (\\x c -> 10 * x + fromEnum c - 48) 0"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- getInts\n\n print $ (sum $ tail $ scanl1 (+) $ reverse $ sort xs) + sum xs\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = (solve.concat=<map rIn.C.words<$>C.getLine) )\nsolve (x:xs) = print $ (sum $ zipWith (\\a b->a*b) [2..] $ sort xs) - maximum xs\n"}, {"source_code": "import Data.List\n\nmain = do \ngetLine \ngetLine >>= print . (\\x -> let a = sortBy (\\ x y -> if x < y then LT else if x > y then GT else EQ) x in ((toInteger $ last a) * (foldr (+) (0::Integer) a)) + (sum $ zipWith (*) (init a) [(2::Integer)..])) . map (\\x -> read x :: Integer) . words\n\n"}, {"source_code": "import Data.List\n\nmain = do \ngetLine \ngetLine >>= print . (\\x -> let a = sort x in (last a * length a) + (sum $ zipWith (*) (init a) [2..])) . map (\\x -> read x :: Int) . words\n\n"}, {"source_code": "import Data.List (sort)\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine\n xs <- sort . map read . words <$> getLine :: IO [Int]\n print $ if null . drop 1 $ xs then head xs else\n let (l:ys) = scanr1 (+) xs\n in sum . (2*l:) . take (n-2) $ ys"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve as = sum (zipWith (*) [1..] (sort as)) - maximum as + sum as\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nmain = do\n getLine\n a <- sort . map read . words <$> getLine :: IO [Int]\n print $ (sum $ zipWith (*) [2..] a) - (last a)"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \nmain= do\n\ts<- read <$> getLine ::IO Int\n\tn<- sort.map read.words <$> getLine::IO [Int]\n\tlet ans= sum $ zipWith (*) n [2..]\n \tif s==1 then print (last n ) else print $ ans - (last n)"}], "src_uid": "4266948a2e793b4b461156af226e98fd"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine :: IO Int\n s <- getLine\n print $ solve s\n\nsolve :: String -> Int\nsolve s = max (f '0') (f '1')\n where groups = group s\n f = \\c -> sum $ map (pred . length) $ filter ((==c) . head) groups\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (group)\n\nsolve :: String -> Int\nsolve s = r\n where g = group s\n\tf b = filter (\\x -> head x == b) g\n\tr = max (m . f $ '0') (m . f $ '1')\n\tm = sum . map (\\x -> (length x) - 1)\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] . const $ getLine >> getLine >>= putStrLn . show . solve \n"}, {"source_code": "import Control.Arrow\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> map show >>> unlines\n\nprocess :: [String] -> [Int]\nprocess [] = []\nprocess (_:s:ss) = solve s : process ss\n\nsolve :: String -> Int\nsolve s =\n foldl max 0 . map length . group . sort . filter (uncurry (==)) $\n zip s (tail s)\n"}], "negative_code": [{"source_code": "import Control.Arrow\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> map show >>> unlines\n\nprocess :: [String] -> [Int]\nprocess [] = []\nprocess (_:s:ss) = solve s : process ss\n\nsolve :: String -> Int\nsolve = maximum . map (sum . map (subtract 1 . length)) . groupBy f . group\n where\n f xs ys = head xs == head ys\n"}, {"source_code": "import Control.Arrow\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> map show >>> unlines\n\nprocess :: [String] -> [Int]\nprocess [] = []\nprocess (_:s:ss) = solve s : process ss\n\nsolve :: String -> Int\nsolve s = foldl max 0 . map length . group . filter (uncurry (==)) $ adj\n where\n adj = zip s (tail s)\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (group)\n\nrmCorr :: String -> String\nrmCorr (x:y:[]) = x:y:[]\nrmCorr (a:b:c:d:xs) = corr (a:b:c:d:[]) $ xs\n where corr s xs = case s of \n\t\t \"0101\" -> rmCorr ('0':'1':xs)\n\t\t \"1010\" -> rmCorr ('1':'0':xs)\n\t\t _ -> a : b : rmCorr (c:d:xs)\n\nsolve :: String -> Int\nsolve = sum . map (\\x -> x - 1) . map length . filter (\\s -> head s == '1') . group . rmCorr\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] . const $ getLine >> getLine >>= putStrLn . show . solve \n"}], "src_uid": "fd1e3368fbfbc3792831623398c94d80"} {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> Int -> [(Int, Int)]\nsolve n m\n | n < m = [(i, n - i) | i <- [0 .. n]]\n | otherwise = [(i, m - i) | i <- [0 .. m]]\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n let ps = solve n m\n print $ length ps\n mapM_ print' ps\n where\n print' (a, b) = putStrLn $ show a ++ \" \" ++ show b", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n n <- fmap (minimum . map read . words) getLine\n print $ n + 1\n putStr $ unlines $ [show i ++ \" \" ++ show (n - i) | i <- [0 :: Int .. n]]\n"}, {"source_code": "import Numeric\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ g.minimum.map fastRead .words.head.lines\n\ng x = (show (if x == 0 then 0 else (x+1))) ++ \"\\n\" ++ unlines (f [] x 0)\n\nf ans (-1) y = ans\nf ans x y\n | x == 0 && (null ans) = ans\n | otherwise = f ((i ++ \" \" ++ j):ans) (x-1) (y+1)\n where i = show x\n j = show y\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n\n let a = min (n+1) (m+1)\n print a\n\n putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ zip [0..a-1] $ (reverse [0..a-1])\n"}, {"source_code": "main = do\n [x, y] <- fmap (map read . words) getLine\n let n = min x y\n print $ n+1\n putStr $ unlines $ [show i ++ \" \" ++ show (n-i) | i <- [0..n]]\n"}, {"source_code": "main=getLine>>=putStr.unlines.map(unwords.map show).f.map read.words\nf[n,m]|x<-min n m=[x+1]:[[i,x-i]|i<-[0..x]]"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nmain = do\n\ttmp <- B.getLine;\n\tlet\n\t\tn:m:[] = map (fst.fromJust.B.readInt) $ B.words tmp\n\t\tsolve :: Int -> Int -> String\n\t\tsolve x y\n\t\t\t| x < 0 || y > m = \"\"\n\t\t\t| otherwise = show x ++ \" \" ++ show y ++ \"\\n\" ++ (solve (x-1) (y+1))\n\tputStr $ show (1+(min n m)) ++ \"\\n\" ++ solve n 0\n"}, {"source_code": "main = do\n n:m:xs <- fmap (map read . words) getContents\n print (min n m + 1)\n mapM_ (\\x -> putStrLn $ (show x) ++ \" \" ++ (show $ m - x)) [0 .. (min n m)]\n"}], "negative_code": [{"source_code": "import Numeric\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ g.minimum.map fastRead .words.head.lines\n\ng x = (show x) ++ \"\\n\" ++ unlines (f [] x)\n\nf ans (-1) = ans\nf ans x\n | x == 0 && (null ans) = ans\n | otherwise = f ((i ++ \" \" ++ i):ans) (x-1)\n where i = show x\n"}, {"source_code": "import Numeric\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ g.minimum.map fastRead .words.head.lines\n\ng x = (show (x+1)) ++ \"\\n\" ++ unlines (f [] (x))\n\nf ans (-1) = ans\nf ans x\n | x == 0 && (null ans) = ans\n | otherwise = f ((i ++ \" \" ++ i):ans) (x-1)\n where i = show x\n"}, {"source_code": "main = do\n [x, y] <- fmap (map read . words) getLine\n let n = min x y\n print $ n+1\n putStr $ unlines $ [show i ++ \" \" ++ show (x-i) | i <- [0..n]]\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nmain = do\n\ttmp <- B.getLine;\n\tlet\n\t\tn:m:[] = map (fst.fromJust.B.readInt) $ B.words tmp\n\t\tsolve :: Int -> Int -> String\n\t\tsolve x y\n\t\t\t| x > n || y > m = \"\"\n\t\t\t| otherwise = show x ++ \" \" ++ show y ++ \"\\n\" ++ (solve (x+1) (y+1))\n\tputStr $ show (1+(min n m)) ++ \"\\n\" ++ solve 0 0\n"}], "src_uid": "0e99f4a49b408cc8874a6d5ec4167acb"} {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt bs = case C.readInt bs of\n Nothing -> error \"Not an integer\"\n Just (x, _) -> x\n\nupdate :: Maybe Int -> Maybe Int\nupdate Nothing = Just 1\nupdate (Just i) = Just (i+1)\n\ncount :: [Int] -> M.IntMap Int\ncount lst =\n foldr (M.alter update) M.empty lst\n\ncalc :: Int -> [(Int,Int)] -> Int64\ncalc n pairs =\n let themes = count $ map fst pairs\n dif = count $ map snd pairs\n m = fromIntegral n :: Int64\n total = (m*(m-1)*(m-2)) `div` 6\n delta = foldl (\\acc (x,y) ->\n let size1 = fromIntegral $ M.findWithDefault 0 x themes :: Int64\n size2 = fromIntegral $ M.findWithDefault 0 y dif :: Int64\n in\n acc + (size1-1)*(size2-1)\n ) 0 pairs\n in\n total-delta\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let n = readInt line\n pairs <- mapM (\\_ -> do\n line <- C.getLine\n let [x,y] = map readInt $ C.words line\n return (x,y)\n ) [1..n]\n print $ calc n pairs\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as DM\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\nimport qualified Data.Either as DE\r\n\r\ndata Input = Input {n0 :: Integer, pairs :: [(Integer,Integer)]} deriving Show\r\ndata Output = Output Integer deriving Show\r\n\r\ncountElems :: (Ord a) => [a] -> DM.Map a Int\r\ncountElems = DM.fromListWith (+) . flip zip (repeat 1) \r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = Output ans where\r\n m1 = countElems $ fst <$> ps\r\n m2 = countElems $ snd <$> ps\r\n sureLookup x m = fromIntegral $ subtract 1 $ fromMaybe 0 $ DM.lookup x m\r\n badCount (x,y) = sureLookup x m1 * sureLookup y m2\r\n badCounts = sum $ map badCount ps\r\n allCount = n*(n-1)*(n-2)`div`6\r\n ans = allCount - badCounts\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n] <- getIntegrals 1\r\n ps <- replicateM (fromIntegral n) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n go (Output x) = Bu.integerDec x <> nl\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n ~[nTc] <- numberOfTestcases\r\n mconcat <$> replicateM nTc (input >>= (solve >>> output >>> return))\r\n B8.putStr $ Bu.toLazyByteString outputs"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\ndata Input = Input {n :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output Integer deriving Show\r\n\r\nsubsetsOfSize :: Int -> [a] -> [[a]]\r\nsubsetsOfSize 0 _ = [[]]\r\nsubsetsOfSize _ [] = []\r\nsubsetsOfSize k (x:xs) = [x:ys | ys <- subsetsOfSize (k-1) xs] ++ subsetsOfSize k xs\r\n\r\ntripletCount :: Eq a => [a] -> Integer\r\ntripletCount xs = sum $ map product $ subsetsOfSize 3 $ map (fromIntegral.length) $ L.group xs\r\n\r\npairingCount :: S.Set Int -> S.Set Int -> Integer\r\npairingCount xs ys = sum $ S.map (fromIntegral.choose2.funct) xs where\r\n choose2 n = fromIntegral $ n*(n-1)`div`2\r\n funct x = if (S.member x ys) then S.size ys -1 else S.size ys\r\n \r\nsolve :: Input -> Output\r\nsolve (Input n ps) = Output ans where\r\n qs = L.sort ps\r\n distinctFst = tripletCount $ map fst qs\r\n lists = map (map snd) $ L.groupBy ((==)`on` fst) qs\r\n sets = map S.fromAscList $ lists\r\n sameFst = sum $ map choose3 sets\r\n choose3 set = fromIntegral $ m*(m-1)*(m-2)`div`6 where m=S.size set\r\n sameTwoFst = sum $ map (\\[x,y]->pairingCount x y + pairingCount y x) $ subsetsOfSize 2 sets\r\n ans = distinctFst + sameFst + sameTwoFst\r\n \r\n-- gives a State(T) monad which when run gives Input\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n] <- getIntegrals 1\r\n ps <- replicateM n $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n go (Output x) = Bu.integerDec x <> nl\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let outputs = flip evalState (B8.words raw) $ do\r\n ~[nTc] <- numberOfTestcases\r\n mconcat <$> replicateM nTc (input >>= (solve >>> output >>> return))\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\ndata Input = Input {n :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output Integer deriving Show\r\n\r\nsubsetsOfSize :: Int -> [a] -> [[a]]\r\nsubsetsOfSize 0 _ = [[]]\r\nsubsetsOfSize _ [] = []\r\nsubsetsOfSize k (x:xs) = [x:ys | ys <- subsetsOfSize (k-1) xs] ++ subsetsOfSize k xs\r\n\r\ntripletCount :: Eq a => [a] -> Integer\r\ntripletCount xs = sum $ map product $ subsetsOfSize 3 $ map (fromIntegral.length) $ L.group xs\r\n\r\npairingCount :: S.Set Int -> S.Set Int -> Integer\r\npairingCount xs ys = sum $ S.map (fromIntegral.choose2.funct) xs where\r\n choose2 n = fromIntegral $ n*(n-1)`div`2\r\n funct x = if (S.member x ys) then S.size ys -1 else S.size ys\r\n \r\nsolve :: Input -> Output\r\nsolve (Input n ps) = Output ans where\r\n qs = L.sort ps\r\n distinctFst = tripletCount $ map fst qs\r\n lists = map (map snd) $ L.groupBy ((==)`on` fst) qs\r\n sets = map S.fromAscList $ lists\r\n sameFst = sum $ map choose3 sets\r\n choose3 set = fromIntegral $ m*(m-1)*(m-2)`div`6 where m=S.size set\r\n sameTwoFst = sum $ map (\\[x,y]->pairingCount x y) $ subsetsOfSize 2 sets\r\n ans = distinctFst + sameFst + sameTwoFst\r\n \r\n-- gives a State(T) monad which when run gives Input\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n] <- getIntegrals 1\r\n ps <- replicateM n $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n go (Output x) = Bu.integerDec x <> nl\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let outputs = flip evalState (B8.words raw) $ do\r\n ~[nTc] <- numberOfTestcases\r\n mconcat <$> replicateM nTc (input >>= (solve >>> output >>> return))\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\ndata Input = Input {n :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output Integer deriving Show\r\n\r\nsubsetsOfSize :: Int -> [a] -> [[a]]\r\nsubsetsOfSize 0 _ = [[]]\r\nsubsetsOfSize _ [] = []\r\nsubsetsOfSize k (x:xs) = [x:ys | ys <- subsetsOfSize (k-1) xs] ++ subsetsOfSize k xs\r\n\r\ntripletCount :: Eq a => [a] -> Integer\r\ntripletCount xs = sum $ map product $ subsetsOfSize 3 $ map (fromIntegral.length) $ L.group xs\r\n\r\napplicate :: [Int] -> S.Set Int -> Integer\r\napplicate xs ys = sum [fromIntegral (choose2 $ funct x) | x <- xs] where\r\n choose2 n = n*(n-1)`div`2\r\n funct x = if (S.member x ys) then S.size ys -1 else S.size ys\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = Output ans where\r\n qs = L.sort ps\r\n distinctFst = tripletCount $ map fst qs\r\n lists = map (map snd) $ L.groupBy ((==)`on` fst) qs\r\n sets = map S.fromAscList $ filter (not.null.tail) lists\r\n sameFst = sum $ map choose3 sets\r\n choose3 set = fromIntegral $ m*(m-1)*(m-2)`div`6 where m=S.size set\r\n sameTwoFst = sum $ (applicate <$> lists <*> sets) \r\n ans = distinctFst + sameFst + sameTwoFst\r\n \r\n-- gives a State(T) monad which when run gives Input\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n] <- getIntegrals 1\r\n ps <- replicateM n $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n go (Output x) = Bu.integerDec x <> nl\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let outputs = flip evalState (B8.words raw) $ do\r\n ~[nTc] <- numberOfTestcases\r\n mconcat <$> replicateM nTc (input >>= (solve >>> output >>> return))\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\ndata Input = Input {n :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output Integer deriving Show\r\n\r\nsubsetsOfSize :: Int -> [a] -> [[a]]\r\nsubsetsOfSize 0 _ = [[]]\r\nsubsetsOfSize _ [] = []\r\nsubsetsOfSize k (x:xs) = [x:ys | ys <- subsetsOfSize (k-1) xs] ++ subsetsOfSize k xs\r\n\r\ntripletCount :: Eq a => [a] -> Integer\r\ntripletCount xs = sum $ map product $ subsetsOfSize 3 $ map (fromIntegral.length) $ L.group xs\r\n\r\napplicate :: [Int] -> S.Set Int -> Integer\r\napplicate xs ys = sum [fromIntegral (choose2 $ funct x) | x <- xs] where\r\n choose2 n = n*(n-1)`div`2\r\n funct x = if (S.member x ys) then S.size ys -1 else S.size ys\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = Output ans where\r\n qs = L.sort ps\r\n distinctFst = tripletCount $ map fst qs\r\n lists = map (map snd) $ L.groupBy ((==)`on` fst) qs\r\n sets = map S.fromAscList $ filter (not.null.tail) lists\r\n distinctSndOnly = sum $ (applicate <$> lists <*> sets) \r\n ans = distinctFst + distinctSndOnly\r\n \r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n] <- getIntegrals 1\r\n ps <- replicateM n $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n go (Output x) = Bu.integerDec x <> nl\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let outputs = flip evalState (B8.words raw) $ do\r\n ~[nTc] <- numberOfTestcases\r\n mconcat <$> replicateM nTc (input >>= (solve >>> output >>> return))\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}], "src_uid": "5a2d51da609b3c22bb8d801ebfb63822"} {"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\nmain :: IO ()\nmain = interact $ unlines . map solve . format . map read . tail . words\n\nformat :: [Int] -> [[Int]]\nformat allTest = format_aux allTest []\n where\n format_aux [] res = res\n format_aux (n:m:rest) res = let (arr, remain) = splitAt n rest in\n format_aux remain (res ++ [[n, m] ++ arr])\n\nsolve :: [Int] -> [Char]\nsolve [] = []\nsolve (n:m:arr) = let st = take m ['B', 'B'..] in\n solve_aux arr st where\n solve_aux [] cur_st = cur_st\n solve_aux (x:xs) cur_st = let (smal, big) = judge (x-1) (m-x) in\n if (cur_st !! smal == 'B') then solve_aux xs (change smal cur_st)\n else solve_aux xs (change big cur_st) \n\njudge :: Int -> Int -> (Int, Int)\njudge x y = if (x < y) then (x, y) else (y, x)\n\nchange :: Int -> [Char] -> [Char]\nchange pos st = let (xs,_:ys) = splitAt pos st in\n xs ++ 'A':ys", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Map.Strict qualified as Map\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n,m] <- ri\r\n as <- ri\r\n return (m, as)\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve (m, as) = op\r\n where\r\n ps = L.sort . map (toBoth m) $ as\r\n i2c = Map.fromList . (`zip` repeat 'B') $ cinds\r\n op = Map.elems . foldl doOp i2c $ ps\r\n cinds = [1..m] :: [Int]\r\n\r\ndoOp i2c (i,j) = Map.adjust (const 'A') k i2c\r\n where\r\n (!) = (Map.!)\r\n k | (i2c!i) == 'B' = i\r\n | otherwise = j\r\n\r\ntoBoth m x = (min a b, max a b)\r\n where\r\n (a,b) = (x, m+1-x)\r\n"}], "negative_code": [], "src_uid": "eee23388aa7cda50302fc4da6e50e172"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.State.Strict (StateT)\nimport qualified Control.Monad.Trans.State.Strict as StateT\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\n\ngetNewLine :: SIO ByteString\ngetNewLine = (lift $ C.hGetLine stdin) >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n\ngetRemain :: ByteString -> SIO ByteString\ngetRemain b = let bns = C.dropWhile isSpace b in\n if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)\n else return bns\n\ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n\ntype SIO a = StateT ByteString IO a\n\nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n\ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => SIO a\nget = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get\nput :: IOInteract a => a -> SIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> SIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: SIO ()\nflush = lift (hFlush stdout)\n\nmain :: IO ()\nmain = StateT.evalStateT main_ C.empty\n\nmain_ :: SIO ()\n-------------------------------------------- template ------------------------------------------------------\n-- for io performance comparison from @Amguls' code --\nremoveFactor :: Integer -> Integer -> Integer\nremoveFactor m i =\n if m `mod` i == 0\n then removeFactor (m `quot` i) i\n else m\n \ntotient' :: Integer -> Integer -> Integer -> Integer -> (Integer, Integer)\ntotient' o m i r\n | i > m || i * i > o = (m,r)\n | otherwise =\n totient' o (removeFactor m i) (i+1) $\n if m `mod` i == 0\n then (r `quot` i) * (i-1)\n else r\n \ntotient :: Integer -> Integer\ntotient m =\n let (m2, m3) = totient' m m 2 m\n in if m2 > 1 \n then (m3 `quot` m2) * (m2 - 1)\n else m3\n \ncompute :: Integer -> Integer -> String\ncompute a m =\n show $ totient $ m `div` gcd a m \n \nsolve :: Int -> SIO ()\nsolve 0 = return ()\nsolve t = do\n (a,m) <- liftM2 (,) get get\n putln $ compute a m\n solve (t-1)\n \nmain_ = do\n t <- get\n solve t", "positive_code": [{"source_code": "readInt :: IO Int\nreadInt = do\n t <- getLine\n return $ read t\n\nreadInts :: IO [Integer]\nreadInts = fmap (map read . words) getLine\n\nremoveFactor :: Integer -> Integer -> Integer\nremoveFactor m i =\n if m `mod` i == 0\n then removeFactor (m `quot` i) i\n else m\n\ntotient' :: Integer -> Integer -> Integer -> Integer -> (Integer, Integer)\ntotient' o m i r\n | i > m || i * i > o = (m,r)\n | otherwise =\n totient' o (removeFactor m i) (i+1) $\n if m `mod` i == 0\n then (r `quot` i) * (i-1)\n else r\n\ntotient :: Integer -> Integer\ntotient m =\n let (m2, m3) = totient' m m 2 m\n in if m2 > 1 \n then (m3 `quot` m2) * (m2 - 1)\n else m3\n\ncompute :: Integer -> Integer -> String\ncompute a m =\n show $ totient $ m `div` gcd a m \n\nsolve :: Int -> IO ()\nsolve 0 = return ()\nsolve t = do\n [a,m] <- readInts\n putStrLn $ compute a m\n solve (t-1)\n\nmain :: IO ()\nmain = do\n t <- readInt\n solve t\n"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>))\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, m) <- liftM2 (,) get get\n putln $ f2 a m\n\nf2 :: Int64 -> Int64 -> Int64\nf2 a m = let d = gcd a m in\n let (ap, mp) = (div a d, div m d) in\n phi mp\n\n\nphi :: Int64 -> Int64\nphi e = foldl (\\s x -> (div s x) * (x - 1)) e $ plist e\n\nplist :: Int64 -> [Int64]\nplist n = plisth n 2 $ sqrt $ fromIntegral n\n\nplisth :: Int64 -> Int64 -> Double -> [Int64]\nplisth n x d = if (fromIntegral x) > d then\n if n /= 1 then\n [n]\n else\n []\n else if mod n x == 0 then\n let np = divrec n x in\n x : plisth np (x + 1) d\n else\n plisth n (x + 1) d\n\ndivrec :: Int64 -> Int64 -> Int64\ndivrec n x = if mod n x == 0 then\n divrec (div n x) x\n else\n n\n"}], "negative_code": [], "src_uid": "adcd813d4c45337bbd8bb0abfa2f0e00"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmain=interact$show.solve.lines\n\nsolve :: [String] -> Int\nsolve [ss',ps'] = if length ps' > length ss'\n then 0\n else go 0 (foldr put counter0 ss0) (Q ss0 []) ss\n where\n ps = foldr put counter0 ps'\n counter0 = ['a'..'z']>>[0]\n (ss0,ss) = splitAt (length ps') ss'\n go !ans !counter q [] = if isGood counter ps then ans+1 else ans\n go !ans !counter queue (c:cs) = go ans' (put c $ del x counter) (push c q) cs\n where\n (x,q) = pop queue\n ans' = if isGood counter ps then ans+1 else ans\n\nisGood !xs !ys = and $ zipWith (<=) xs ys\nput :: Char -> [Int] -> [Int]\nput '?' !xs = xs\nput !c !xs = ys ++ (z+1):zs\n where\n (ys,(z:zs)) = splitAt (fromEnum c-97) xs\ndel '?' !xs = xs\ndel !c !xs = ys ++ (z-1):zs\n where\n (ys,(z:zs)) = splitAt (fromEnum c-97) xs\n\ndata Queue = Q String String\n\npush :: Char -> Queue -> Queue\npush x (Q f r) = Q f (x:r)\n\npop :: Queue -> (Char, Queue)\npop (Q [] rs) = pop (Q (reverse rs) [])\npop (Q (f:fs) rs) = (f,Q fs rs)", "positive_code": [{"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=l '?'h).sum.f(>0).M.elems$u n(fmap negate h)\nl=(maybe 0 id.).M.lookup\nm=k.map a\na x=(x,1)\nd x=(x,-1)\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[a x,d y])(drop n l)l\ns[s,p]=f(g(m p))(b (length p) s)\nmain=interact$show.length.s.words\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as M\nimport Debug.Trace\nimport Data.Maybe\nimport Data.Char\n\ncompareMaps text pat = and $ map check ['a'..'z']\n where check a = M.lookup a text <= M.lookup a pat\n\nanagram_count s p = if length s < length p\n then 0\n else mycount patMap textMap s trail\n where patMap = getMyMap p\n textMap = getMyMap $ take (length p) s\n trail = drop (length p) s\n\nmycount patMap textMap _ [] = if compareMaps textMap patMap\n then 1\n else 0\nmycount patMap textMap (l:lead) (t:trail) = let rec = mycount patMap newTextMap lead trail\n newTextMap = updateMap (removeMap textMap l) t\n cmp = compareMaps textMap patMap\n in if cmp\n then 1 + rec\n else rec\n\t\t\t\t\nremoveMap m c = if c == '?'\n then m\n else let newC = (fromJust $ M.lookup c m) - 1\n in if newC == 0\n then M.delete c m\n else M.insert c newC m\n\nupdateMap :: M.Map Char Int -> Char -> M.Map Char Int\nupdateMap m '?' = m\nupdateMap m c = if M.member c m\n then let cur = fromJust $ M.lookup c m\n in M.insert c (cur+1) m\n else M.insert c 1 m\n\ngetMyMap :: String -> M.Map Char Int\ngetMyMap s = foldl updateMap M.empty s \n\nstrip :: String -> String\nstrip = f.f where f = reverse.dropWhile isSpace\n\nmain = do\n\tline <- getLine\n\tlet s = strip line\n\tline <- getLine\n\tlet p = strip line\n ans = anagram_count s p\n\tputStrLn $ show ans\n\t \n"}, {"source_code": "import qualified Data.Map as M\nf=filter\nu=M.unionWith(+)\nk=M.fromListWith(+)\ng n h=(<=M.findWithDefault 0'?'h).sum.f(>0).M.elems$u n(fmap negate h)\nm l=k[(x,1)|x<-l]\nb n l=scanl u(m$take n l)$zipWith(\\x y->k[(x,1),(y,-1)])(drop n l)l\ns[s,p]=f(g$m p)$b(length p)s\nmain=interact$show.length.s.words\n\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.Map(Map)\n\nisGood need have = (<= get '?' have) . sum . filter (>0) . Map.elems $\n (Map.unionWith (+) need (fmap negate have))\n\nget x = maybe 0 id . Map.lookup x\nadd x = Map.insertWith (+) x 1\nsub x = Map.insertWith (+) x (-1)\n\nmkMap = foldr add Map.empty\n\nbalances n l = scanl (flip($))\n (mkMap (take n l))\n (zipWith (.) (map add (drop n l)) (map sub l))\n\nsolve s p = length $ filter (isGood (mkMap p)) (balances (length p) s)\n\ns [s, p] = solve s p\n\nmain = interact $ show . s . words"}], "negative_code": [{"source_code": "import Data.List(sort)\nimport Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do s <- B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) $ take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n{-\nf n [] = []\nf n xxs@(x:xs) = (take n xxs): f n xs\n-}\n{-\neqString' _ [] _ = True \neqString' [] (_:ys) [] = False\neqString' [] (_:ys) (_:qs) = eqString' [] ys qs\neqString' (x:xs) (y:ys) qs\n | x == y = eqString' xs ys qs\n | null qs = False\n | otherwise = eqString' (x:xs) ys $ tail qs\n-}\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmain=interact$show.solve.lines\n\nsolve :: [String] -> Int\nsolve [ss',ps'] = go 0 (foldr put counter0 ss0) (Q ss0 []) ss\n where\n ps = foldr put counter0 ps'\n counter0 = ['a'..'z']>>[0]\n (ss0,ss) = splitAt (length ps') ss'\n go !ans !counter q [] = if isGood counter ps then ans+1 else ans\n go !ans !counter queue (c:cs) = go ans' (put c $ del x counter) (push c q) cs\n where\n (x,q) = pop queue\n ans' = if isGood counter ps then ans+1 else ans\n\nisGood !xs !ys = and $ zipWith (<=) xs ys\nput :: Char -> [Int] -> [Int]\nput '?' !xs = xs\nput !c !xs = ys ++ (z+1):zs\n where\n (ys,(z:zs)) = splitAt (fromEnum c-97) xs\ndel '?' !xs = xs\ndel !c !xs = ys ++ (z-1):zs\n where\n (ys,(z:zs)) = splitAt (fromEnum c-97) xs\n\ndata Queue = Q String String\n\npush :: Char -> Queue -> Queue\npush x (Q f r) = Q f (x:r)\n\npop :: Queue -> (Char, Queue)\npop (Q [] rs) = pop (Q (reverse rs) [])\npop (Q (f:fs) rs) = (f,Q fs rs)"}, {"source_code": "import Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do s <- B.init <$> B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) $ take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n"}, {"source_code": "import Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do s <- B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n B.putStrLn $ B.append s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) $ take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n"}, {"source_code": "import Data.List(sort)\nimport Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do s <- B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) $ take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n"}, {"source_code": "import Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do s <- B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) $ take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n"}, {"source_code": "import Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport Debug.Trace\n\ninfixr 0 .$.\n(.$.) :: Show a => (a -> b) -> a -> b\nf .$. x = trace (show x) f x\n\nmain = do s <- B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) .$. take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n"}, {"source_code": "import Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do s <- B.getLine\n p <- B.sort <$> B.getLine\n print $ solve s p\n\nsolve :: ByteString -> ByteString -> Int\nsolve s p = length $ filter (flip eqString p . B.sort) $ take (ls-lp+1) $ f lp s\n where lp = B.length p\n ls = B.length s\n\neqString :: ByteString -> ByteString -> Bool\neqString xs ys = eqString' xs' ys qs\n where (qs,xs') = B.span ('?'==) xs\n\neqString' xs ys qs\n | B.null ys = True\n | B.null xs && B.null qs = False\n | B.null xs = (B.length ys) <= (B.length qs)\n | B.head xs == B.head ys = eqString' (B.tail xs) (B.tail ys) qs\n | B.null qs = False\n | otherwise = eqString' xs (B.tail ys) (B.tail qs)\n\nf n xs\n | B.null xs = []\n | otherwise = (B.take n xs): f n (B.tail xs)\n"}], "src_uid": "9ed2a081b65df66629fcf0d4fc0bb02c"} {"source_code": "module Main where\n\nimport Data.Ratio\nimport qualified Data.Set as S\n\nimport Control.Applicative\nimport Control.Monad\n\n-- | Find all a, b such that a^2 + b^2 = x\ntriples :: Int -> [(Int, Int)]\ntriples x = let x2 = x^2 in [(a, b) | a <- [1..x], b <- [(a+1)..x], a^2 + b^2 == x2]\n\nmain = do\n input <- map (map (read :: String -> Int) . words) . lines <$> getContents\n forM_ input $ \\(ia:ib:[]) -> do\n -- triangle coords currently are p0: (0, sa), p1: (sb, 0), p2: (0, 0)\n let sa = min ia ib\n sb = max ia ib\n toRatios = S.fromList . map (uncurry (%)) . triples\n common = S.intersection (toRatios sa) (toRatios sb)\n multi x r = floor . sqrt . fromIntegral $ x ^ 2 `div` (numerator r ^ 2 + denominator r ^ 2)\n\n case S.elems common of\n [] -> putStrLn \"NO\"\n r:_ -> do\n\n let msa = multi sa r\n msb = multi sb r\n display x y = putStrLn $ show x ++ \" \" ++ show y\n\n putStrLn \"YES\"\n display (-msa * denominator r) (msa * numerator r)\n display (msb * numerator r) (msb * denominator r)\n display 0 0\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.IntSet as IS\nimport Data.Maybe\n\nmain = do\n ab <- map read.words <$> getLine\n case solve ab of\n Nothing -> putStrLn \"NO\"\n Just [(x1,y1),(x2,y2)] -> do\n putStrLn \"YES\"\n putStrLn \"0 0\"\n putStrLn $ shows x1 \" \" ++ show y1\n putStrLn $ shows x2 \" \" ++ show y2\n\nsolve :: [Int] -> Maybe [(Int,Int)]\nsolve [a,b] = listToMaybe candidates\n where\n !squares = IS.fromList [x*x|x<-[1..1000]]\n !bb = b * b\n candidates = do\n x<-[1..1000]\n let !xx = x*x\n !yy = bb - xx\n guard $ yy `IS.member` squares\n let !y = intSqrt yy\n guard $ a*y`rem`b == 0 && a*x`rem`b == 0\n let !x' = - a * y `div` b\n !y' = a * x `div` b\n guard $ x /= x' && y /= y'\n [[(x,y),(x',y')]]\n \nintSqrt :: Int -> Int\nintSqrt = floor.sqrt.fromIntegral\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport Control.Arrow\nmain = interact $ format . solve . parse\nformat Nothing = \"NO\"\nformat (Just ((a,b),(c,d))) = unlines [ \"YES\"\n , \"0 0\"\n , show a ++ \" \" ++ show b\n , show (a+c) ++ \" \" ++ show (b+d) ]\nparse = map read . words\nsolve [i,j] = listToMaybe $ do\n (a,b) <- unsquare i\n (_c,_d) <- unsquare j\n (c,d) <- [(_c,-_d),(_d,-_c)]\n guard (b /= -d)\n guard (a*c + b*d == 0)\n return ((a,b),(c,d))\nunsquare :: Int -> [(Int,Int)]\nunsquare x = merge (map (second (x^2 -)) squares) (reverse squares)\nsquares = map (id &&& (^2)) [1..999]\nmerge :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]\nmerge as@((a,sa):as') bs@((b,sb):bs') = case compare sa sb of\n EQ -> (a,b) : (merge as' bs')\n LT -> merge as bs'\n GT -> merge as' bs\nmerge _ _ = []\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport qualified Data.IntSet as IS\n\nmain = do\n ab <- fmap(map read.words)getLine\n case solve ab of\n Nothing -> putStrLn \"NO\"\n Just [(x1,y1),(x2,y2)] -> do\n putStrLn \"YES\"\n putStrLn \"0 0\"\n putStrLn $ shows x1 \" \" ++ show y1\n putStrLn $ shows x2 \" \" ++ show y2\n\nsolve :: [Int] -> Maybe [(Int,Int)]\nsolve [a,b] = case filter isValid candidates of\n [] -> Nothing\n ((x,y):_) -> Just [(x,y),(-a*y`quot`b,a*x`quot`b)]\n where\n !squares = IS.fromList [x*x|x<-[1..1000]]\n !bb = b * b\n isValid (x,y) = (x*a)`rem`b==0 && (y*a)`rem`b==0\n candidates = do\n x<-[1..1000]\n let !xx = x*x\n !yy = bb - xx\n [(x,intSqrt yy)|yy `IS.member` squares]\n \nintSqrt :: Int -> Int\nintSqrt = floor.sqrt.fromIntegral\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.IntSet as IS\nimport Data.Maybe\n\nmain = do\n ab <- map read.words <$> getLine\n case solve ab of\n Nothing -> putStrLn \"NO\"\n Just [(x1,y1),(x2,y2)] -> do\n putStrLn \"YES\"\n putStrLn \"0 0\"\n putStrLn $ shows x1 \" \" ++ show y1\n putStrLn $ shows x2 \" \" ++ show y2\n\nsolve :: [Int] -> Maybe [(Int,Int)]\nsolve [a,b] = listToMaybe candidates\n where\n !squares = IS.fromList [x*x|x<-[1..1000]]\n !bb = b * b\n candidates = do\n x<-[1..1000]\n let !xx = x*x\n !yy = bb - xx\n guard $ yy `IS.member` squares\n let !y = intSqrt yy\n guard $ a*y`rem`b == 0 && a*x`rem`b == 0\n let !x' = - a * y `div` b\n !y' = b * x `div` b\n guard $ x /= x' && y /= y'\n [[(x,y),(x',y')]]\n \nintSqrt :: Int -> Int\nintSqrt = floor.sqrt.fromIntegral\n"}, {"source_code": "module Main where\n\nimport System.IO\n\nimport Data.Ratio\nimport qualified Data.Set as S\n\nimport Control.Applicative\nimport Control.Monad\n\n-- | Find all a, b such that a^2 + b^2 = x\ntriples :: Int -> [(Int, Int)]\ntriples x = [(min a b, max a b) | m <- [2..top], n <- [1..(m-1)], let a = m^2 - n^2, let b = 2 * m * n, m^2 + n^2 == x]\n where top = floor . sqrt . fromIntegral $ x\n\nmain = do\n input <- map (map (read :: String -> Int) . words) . lines <$> getContents\n forM_ input $ \\(sa:sb:[]) -> do\n -- triangle coords currently are p0: (0, sa), p1: (sb, 0), p2: (0, 0)\n let toRatios = S.fromList . map (uncurry (%)) . triples\n common = S.intersection (toRatios sa) (toRatios sb)\n multi x r = floor . sqrt . fromIntegral $ x ^ 2 `div` (numerator r ^ 2 + denominator r ^ 2)\n\n case S.elems common of\n [] -> putStrLn \"NO\"\n r:_ -> do\n\n let msa = multi sa r\n msb = multi sb r\n display x y = putStrLn $ show x ++ \" \" ++ show y\n\n putStrLn \"YES\"\n display (-msa * denominator r) (msa * numerator r)\n display (msb * numerator r) (msb * denominator r)\n display 0 0\n"}, {"source_code": "module Main where\n\nimport qualified Data.Set as S\n\nimport Control.Applicative\nimport Control.Monad\n\n-- | Find all a, b such that a^2 + b^2 = x\ntriples :: Int -> [(Int, Int)]\ntriples x = filter (\\(a,b) -> a /= 0 && b /= 0) [(min a b, max a b) | m <- [2..top], n <- [1..(m-1)], let a = m^2 - n^2, let b = 2 * m * n, m^2 + n^2 == x]\n where top = floor . sqrt . fromIntegral $ x\n\nmain = do\n input <- map (map (read :: String -> Int) . words) . lines <$> getContents\n forM_ input $ \\(sa:sb:[]) ->\n case (triples sa, triples sb) of\n (a@(a1,a2):_, b@(b1,b2):_) -> do\n putStrLn \"YES\"\n if a == b && a1 == a2\n then putStrLn \"NO\"\n else putStrLn $ show a1 ++ \" \" ++ show a2 ++ \"\\n\" ++ show b2 ++ \" \" ++ show b1\n putStrLn \"0 0\"\n\n _ -> putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport Data.Ratio\nimport qualified Data.Set as S\n\nimport Control.Applicative\nimport Control.Monad\n\n-- | Find all a, b such that a^2 + b^2 = x\ntriples :: Int -> [(Int, Int)]\ntriples x = let x2 = x^2 in [(a, b) | a <- [1..x], b <- [(a+1)..x], a^2 + b^2 == x2]\n\nmain = do\n input <- map (map (read :: String -> Int) . words) . lines <$> getContents\n forM_ input $ \\(sa:sb:[]) -> do\n -- triangle coords currently are p0: (0, sa), p1: (sb, 0), p2: (0, 0)\n let toRatios = S.fromList . map (uncurry (%)) . triples\n common = S.intersection (toRatios sa) (toRatios sb)\n multi x r = floor . sqrt . fromIntegral $ x ^ 2 `div` (numerator r ^ 2 + denominator r ^ 2)\n\n case S.elems common of\n [] -> putStrLn \"NO\"\n r:_ -> do\n\n let msa = multi sa r\n msb = multi sb r\n display x y = putStrLn $ show x ++ \" \" ++ show y\n\n putStrLn \"YES\"\n display (-msa * denominator r) (msa * numerator r)\n display (msb * numerator r) (msb * denominator r)\n display 0 0\n"}, {"source_code": "module Main where\n\nimport System.IO\n\nimport Data.Ratio\nimport qualified Data.Set as S\n\nimport Control.Applicative\nimport Control.Monad\n\n-- | Find all a, b such that a^2 + b^2 = x\ntriples :: Int -> [(Int, Int)]\ntriples x = [(min a b, max a b) | m <- [2..top], n <- [1..(m-1)], let a = m^2 - n^2, let b = 2 * m * n, m^2 + n^2 == x]\n where top = floor . sqrt . fromIntegral $ x\n\nmain = do\n input <- map (map (read :: String -> Int) . words) . lines <$> getContents\n forM_ input $ \\(sa:sb:[]) ->\n case (triples sa, triples sb) of\n (a@(a1,a2):_, b@(b1,b2):_) -> do\n putStrLn \"YES\"\n putStrLn $ show a1 ++ \" \" ++ show a2 ++ \"\\n\" ++ show (if a == b then -b1 else b1) ++ \" \" ++ show b2\n putStrLn \"0 0\"\n\n _ -> putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport qualified Data.Set as S\n\nimport Control.Applicative\nimport Control.Monad\n\n-- | Find all a, b such that a^2 + b^2 = x\ntriples :: Int -> [(Int, Int)]\ntriples x = filter (\\(a,b) -> a /= 0 && b /= 0) [(min a b, max a b) | m <- [2..top], n <- [1..(m-1)], let a = m^2 - n^2, let b = 2 * m * n, m^2 + n^2 == x]\n where top = floor . sqrt . fromIntegral $ x\n\nmain = do\n input <- map (map (read :: String -> Int) . words) . lines <$> getContents\n forM_ input $ \\(sa:sb:[]) ->\n case (triples sa, triples sb) of\n (a@(a1,a2):_, b@(b1,b2):_) -> do\n if a == b && a1 == a2\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n putStrLn $ show a1 ++ \" \" ++ show a2 ++ \"\\n\" ++ show b2 ++ \" \" ++ show b1\n putStrLn \"0 0\"\n\n _ -> putStrLn \"NO\"\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport Control.Arrow\nmain = interact $ format . solve . parse\nformat Nothing = \"NO\"\nformat (Just ((a,b),(c,d))) = unlines [ \"YES\"\n , \"0 0\"\n , show a ++ \" \" ++ show b\n , show (a+c) ++ \" \" ++ show (b+d) ]\nparse = map read . words\nsolve [i,j] = listToMaybe $ do\n (a,b) <- unsquare i\n (_c,_d) <- unsquare j\n (c,d) <- [(_c,-_d),(_d,-_c)]\n guard (b /= d)\n guard (a*c + b*d == 0)\n return ((a,b),(c,d))\nunsquare :: Int -> [(Int,Int)]\nunsquare x = merge (map (second (x^2 -)) squares) (reverse squares)\nsquares = map (id &&& (^2)) [1..999]\nmerge :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]\nmerge as@((a,sa):as') bs@((b,sb):bs') = case compare sa sb of\n EQ -> (a,b) : (merge as' bs')\n LT -> merge as bs'\n GT -> merge as' bs\nmerge _ _ = []\n"}], "src_uid": "a949ccae523731f601108d4fa919c112"} {"source_code": "{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE ViewPatterns #-}\r\n\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.Array.Unboxed ( (!)\r\n , (//)\r\n , IArray(..)\r\n , UArray\r\n , listArray\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport Data.Foldable ( Foldable(..) )\r\nimport Data.List ( sort )\r\n\r\nqpow :: Int -> Int -> Int -> Int\r\nqpow a b m = qpow' (a `mod` m) b m\r\n where\r\n qpow' a 0 m = 1 `mod` m\r\n qpow' a b m | odd b = s * s * a `mod` m\r\n | otherwise = s * s `mod` m\r\n where\r\n b' = b `shiftR` 1\r\n s = qpow' a b' m\r\n\r\narrange :: Int -> Int -> Int\r\narrange x y = product [x, x - 1 .. x - y + 1]\r\n\r\n-- >>> arrange 5 <$> [1..5]\r\n-- [5,20,60,120,120]\r\n\r\ncompose :: Int -> Int -> Int\r\ncompose x y = arrange x y `div` product [1 .. x]\r\n\r\n-- >>> f [1,2,5] [3,4]\r\n-- [[1,3],[1,4],[2,3],[2,4],[5,3],[5,4]]\r\n\r\nisPrime :: Int -> Bool\r\nisPrime n = go 2\r\n where\r\n go d | d * d > n = True\r\n | n `rem` d == 0 = False\r\n | otherwise = go (d + 1)\r\n\r\nprimes :: [Int]\r\nprimes = filter isPrime [2 ..]\r\n\r\ninitial :: Int -> Int -> UArray (Int, Int) Bool\r\ninitial n m = listArray ((1, 1), (n, m)) (repeat True)\r\n\r\n-- >>> initial 2 2\r\n-- array ((1,1),(2,2)) [((1,1),True),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\nintact :: UArray (Int, Int) Bool -> Int -> Int -> Int -> Int -> Bool\r\nintact arr l r h b = and [ arr ! (x, y) | x <- [l .. r], y <- [h, b] ]\r\n\r\n-- >>> intact (initial 2 2) 1 2 1 2\r\n-- True\r\n\r\nfall :: UArray (Int, Int) Bool -> (Int, Int) -> UArray (Int, Int) Bool\r\nfall arr p = arr // [(p, False)]\r\n\r\n-- >>> fall (initial 2 2) (1, 1)\r\n-- array ((1,1),(2,2)) [((1,1),False),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\ncount :: UArray (Int, Int) Bool -> Int\r\ncount arr = foldl' (\\acc (x, y, a, b) -> if intact arr x y a b then acc + 1 else acc)\r\n 0\r\n [ (x, y, a, b) | x <- [1 .. n], y <- [x .. n], a <- [1 .. m], b <- [a .. m] ]\r\n where (n, m) = snd $ bounds arr\r\n\r\n{-\r\n\r\n>>> n = 7\r\n>>> m = 4\r\n>>> arr = initial n m\r\n\r\n>>> count arr\r\n280\r\n\r\n>>> ((\\x -> count . fall arr . (x,) <$> [1..m]) <$> [1..n])\r\n[[252,252,252,252],[232,232,232,232],[220,220,220,220],[216,216,216,216],[220,220,220,220],[232,232,232,232],[252,252,252,252]]\r\n\r\n>>> ps = (\\[a,b]->(a,b)) <$> sequence [[1..n], [1..m]]\r\n\r\n>>> ps\r\n[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4),(5,1),(5,2),(5,3),(5,4),(6,1),(6,2),(6,3),(6,4),(7,1),(7,2),(7,3),(7,4)]\r\n\r\n-- >>> sequence [ps, ps]\r\n\r\n>>> count . foldl fall arr <$> sequence [ps,ps]\r\n\r\n-}\r\n\r\ndiff :: Int -> [Int] -> ([Int], Int)\r\ndiff zero =\r\n (\\(acc, zs) -> if zs > 0 then (0 : acc, zs) else (acc, 0))\r\n . foldr (\\(a, b) (acc, zs) -> if a - b == 0 then (acc, zs + 1) else (a - b : acc, zs)) ([], zero)\r\n . (zip =<< tail)\r\n\r\n-- >>> diff 1 [0, 1]\r\n-- ([0,1],1)\r\n\r\n\r\ngo :: Int -> [Int] -> Int\r\ngo _ [0, x] = x\r\ngo _ [x] = x\r\ngo zero xs = go (max 0 (zs - 1)) (sort di) where (di, zs) = diff zero xs\r\n\r\n{-\r\n\r\n>>> go 0 [1,10,100]\r\n81\r\n\r\n>>> go 0 [4,8,9,13]\r\n3\r\n\r\n>>> go 0 [0,0,0,8,13]\r\n1\r\n\r\n>>> go 0 [2,4,8,16,32,64]\r\n2\r\n\r\n-}\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn @Int\r\n xs <- map (read @Int) . words <$> getLine\r\n print $ go 0 xs\r\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE ViewPatterns #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.Array.Unboxed ( (!)\r\n , (//)\r\n , IArray(..)\r\n , UArray\r\n , listArray\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport Data.Foldable ( Foldable(..) )\r\nimport Data.List ( sort )\r\n\r\nqpow :: Int -> Int -> Int -> Int\r\nqpow a b m = qpow' (a `mod` m) b m\r\n where\r\n qpow' a 0 m = 1 `mod` m\r\n qpow' a b m | odd b = s * s * a `mod` m\r\n | otherwise = s * s `mod` m\r\n where\r\n b' = b `shiftR` 1\r\n s = qpow' a b' m\r\n\r\narrange :: Int -> Int -> Int\r\narrange x y = product [x, x - 1 .. x - y + 1]\r\n\r\n-- >>> arrange 5 <$> [1..5]\r\n-- [5,20,60,120,120]\r\n\r\ncompose :: Int -> Int -> Int\r\ncompose x y = arrange x y `div` product [1 .. x]\r\n\r\n-- >>> f [1,2,5] [3,4]\r\n-- [[1,3],[1,4],[2,3],[2,4],[5,3],[5,4]]\r\n\r\nisPrime :: Int -> Bool\r\nisPrime n = go 2\r\n where\r\n go d | d * d > n = True\r\n | n `rem` d == 0 = False\r\n | otherwise = go (d + 1)\r\n\r\nprimes :: [Int]\r\nprimes = filter isPrime [2 ..]\r\n\r\ninitial :: Int -> Int -> UArray (Int, Int) Bool\r\ninitial n m = listArray ((1, 1), (n, m)) (repeat True)\r\n\r\n-- >>> initial 2 2\r\n-- array ((1,1),(2,2)) [((1,1),True),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\nintact :: UArray (Int, Int) Bool -> Int -> Int -> Int -> Int -> Bool\r\nintact arr l r h b = and [ arr ! (x, y) | x <- [l .. r], y <- [h, b] ]\r\n\r\n-- >>> intact (initial 2 2) 1 2 1 2\r\n-- True\r\n\r\nfall :: UArray (Int, Int) Bool -> (Int, Int) -> UArray (Int, Int) Bool\r\nfall arr p = arr // [(p, False)]\r\n\r\n-- >>> fall (initial 2 2) (1, 1)\r\n-- array ((1,1),(2,2)) [((1,1),False),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\ncount :: UArray (Int, Int) Bool -> Int\r\ncount arr = foldl' (\\acc (x, y, a, b) -> if intact arr x y a b then acc + 1 else acc)\r\n 0\r\n [ (x, y, a, b) | x <- [1 .. n], y <- [x .. n], a <- [1 .. m], b <- [a .. m] ]\r\n where (n, m) = snd $ bounds arr\r\n\r\n{-\r\n\r\n>>> n = 7\r\n>>> m = 4\r\n>>> arr = initial n m\r\n\r\n>>> count arr\r\n280\r\n\r\n>>> ((\\x -> count . fall arr . (x,) <$> [1..m]) <$> [1..n])\r\n[[252,252,252,252],[232,232,232,232],[220,220,220,220],[216,216,216,216],[220,220,220,220],[232,232,232,232],[252,252,252,252]]\r\n\r\n>>> ps = (\\[a,b]->(a,b)) <$> sequence [[1..n], [1..m]]\r\n\r\n>>> ps\r\n[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4),(5,1),(5,2),(5,3),(5,4),(6,1),(6,2),(6,3),(6,4),(7,1),(7,2),(7,3),(7,4)]\r\n\r\n-- >>> sequence [ps, ps]\r\n\r\n>>> count . foldl fall arr <$> sequence [ps,ps]\r\n\r\n-}\r\n\r\ndiff :: Int -> [Int] -> ([Int], Int)\r\ndiff zero =\r\n (\\(acc, zs) -> if zs > 0 then (0 : acc, zs) else (acc, 0))\r\n . foldr (\\(a, b) (acc, zs) -> if a - b == 0 then (acc, zs + 1) else (a - b : acc, zs)) ([], zero)\r\n . (zip =<< tail)\r\n\r\n-- >>> diff 1 [0, 1]\r\n-- ([0,1],1)\r\n\r\n\r\ngo :: Int -> [Int] -> Int\r\ngo _ [0, x] = x\r\ngo _ [x] = x\r\ngo zero xs = go (max 0 (zs - 1)) (sort di) where (di, zs) = diff zero xs\r\n\r\n{-\r\n\r\n>>> go 0 [1,10,100]\r\n81\r\n\r\n>>> go 0 [4,8,9,13]\r\n3\r\n\r\n>>> go 0 [0,0,0,8,13]\r\n1\r\n\r\n>>> go 0 [2,4,8,16,32,64]\r\n2\r\n\r\n-}\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn @Int\r\n xs <- map (read @Int) . words <$> getLine\r\n print $ go 0 xs\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE ViewPatterns #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.Array.Unboxed ( (!)\r\n , (//)\r\n , IArray(..)\r\n , UArray\r\n , listArray\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport Data.Foldable ( Foldable(..) )\r\nimport Data.List ( sort )\r\n\r\nqpow :: Int -> Int -> Int -> Int\r\nqpow a b m = qpow' (a `mod` m) b m\r\n where\r\n qpow' a 0 m = 1 `mod` m\r\n qpow' a b m | odd b = s * s * a `mod` m\r\n | otherwise = s * s `mod` m\r\n where\r\n b' = b `shiftR` 1\r\n s = qpow' a b' m\r\n\r\narrange :: Int -> Int -> Int\r\narrange x y = product [x, x - 1 .. x - y + 1]\r\n\r\n-- >>> arrange 5 <$> [1..5]\r\n-- [5,20,60,120,120]\r\n\r\ncompose :: Int -> Int -> Int\r\ncompose x y = arrange x y `div` product [1 .. x]\r\n\r\n-- >>> f [1,2,5] [3,4]\r\n-- [[1,3],[1,4],[2,3],[2,4],[5,3],[5,4]]\r\n\r\nisPrime :: Int -> Bool\r\nisPrime n = go 2\r\n where\r\n go d | d * d > n = True\r\n | n `rem` d == 0 = False\r\n | otherwise = go (d + 1)\r\n\r\nprimes :: [Int]\r\nprimes = filter isPrime [2 ..]\r\n\r\ninitial :: Int -> Int -> UArray (Int, Int) Bool\r\ninitial n m = listArray ((1, 1), (n, m)) (repeat True)\r\n\r\n-- >>> initial 2 2\r\n-- array ((1,1),(2,2)) [((1,1),True),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\nintact :: UArray (Int, Int) Bool -> Int -> Int -> Int -> Int -> Bool\r\nintact arr l r h b = and [ arr ! (x, y) | x <- [l .. r], y <- [h, b] ]\r\n\r\n-- >>> intact (initial 2 2) 1 2 1 2\r\n-- True\r\n\r\nfall :: UArray (Int, Int) Bool -> (Int, Int) -> UArray (Int, Int) Bool\r\nfall arr p = arr // [(p, False)]\r\n\r\n-- >>> fall (initial 2 2) (1, 1)\r\n-- array ((1,1),(2,2)) [((1,1),False),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\ncount :: UArray (Int, Int) Bool -> Int\r\ncount arr = foldl' (\\acc (x, y, a, b) -> if intact arr x y a b then acc + 1 else acc)\r\n 0\r\n [ (x, y, a, b) | x <- [1 .. n], y <- [x .. n], a <- [1 .. m], b <- [a .. m] ]\r\n where (n, m) = snd $ bounds arr\r\n\r\n{-\r\n\r\n>>> n = 7\r\n>>> m = 4\r\n>>> arr = initial n m\r\n\r\n>>> count arr\r\n280\r\n\r\n>>> ((\\x -> count . fall arr . (x,) <$> [1..m]) <$> [1..n])\r\n[[252,252,252,252],[232,232,232,232],[220,220,220,220],[216,216,216,216],[220,220,220,220],[232,232,232,232],[252,252,252,252]]\r\n\r\n>>> ps = (\\[a,b]->(a,b)) <$> sequence [[1..n], [1..m]]\r\n\r\n>>> ps\r\n[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4),(5,1),(5,2),(5,3),(5,4),(6,1),(6,2),(6,3),(6,4),(7,1),(7,2),(7,3),(7,4)]\r\n\r\n-- >>> sequence [ps, ps]\r\n\r\n>>> count . foldl fall arr <$> sequence [ps,ps]\r\n\r\n-}\r\n\r\ndiff :: Int -> [Int] -> ([Int], Int)\r\ndiff zero =\r\n (\\(acc, zs) -> if zs > 0 then (0 : acc, zs) else (acc, 0))\r\n . foldr (\\(a, b) (acc, zs) -> if a - b == 0 then (acc, zs + 1) else (a - b : acc, zs)) ([], zero)\r\n . (zip =<< tail)\r\n\r\n-- >>> diff 1 [0, 1]\r\n-- ([0,1],1)\r\n\r\n\r\ngo :: Int -> [Int] -> Int\r\ngo _ [0, x] = x\r\ngo _ [x] = x\r\ngo zero xs = go (max 0 (zs - 1)) (sort di) where (di, zs) = diff zero xs\r\n\r\n{-\r\n\r\n>>> go 0 [1,10,100]\r\n81\r\n\r\n>>> go 0 [4,8,9,13]\r\n3\r\n\r\n>>> go 0 [0,0,0,8,13]\r\n1\r\n\r\n>>> go 0 [2,4,8,16,32,64]\r\n2\r\n\r\n-}\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn @Int\r\n xs <- map (read @Int) . words <$> getLine\r\n print $ go 0 xs\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE ViewPatterns #-}\r\n\r\nmodule Main where\r\nimport Data.Array.Unboxed ( (!)\r\n , (//)\r\n , IArray(..)\r\n , UArray\r\n , listArray\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport Data.Foldable ( Foldable(..) )\r\nimport Data.List ( sort )\r\n\r\nqpow :: Int -> Int -> Int -> Int\r\nqpow a b m = qpow' (a `mod` m) b m\r\n where\r\n qpow' a 0 m = 1 `mod` m\r\n qpow' a b m | odd b = s * s * a `mod` m\r\n | otherwise = s * s `mod` m\r\n where\r\n b' = b `shiftR` 1\r\n s = qpow' a b' m\r\n\r\narrange :: Int -> Int -> Int\r\narrange x y = product [x, x - 1 .. x - y + 1]\r\n\r\n-- >>> arrange 5 <$> [1..5]\r\n-- [5,20,60,120,120]\r\n\r\ncompose :: Int -> Int -> Int\r\ncompose x y = arrange x y `div` product [1 .. x]\r\n\r\n-- >>> f [1,2,5] [3,4]\r\n-- [[1,3],[1,4],[2,3],[2,4],[5,3],[5,4]]\r\n\r\nisPrime :: Int -> Bool\r\nisPrime n = go 2\r\n where\r\n go d | d * d > n = True\r\n | n `rem` d == 0 = False\r\n | otherwise = go (d + 1)\r\n\r\nprimes :: [Int]\r\nprimes = filter isPrime [2 ..]\r\n\r\ninitial :: Int -> Int -> UArray (Int, Int) Bool\r\ninitial n m = listArray ((1, 1), (n, m)) (repeat True)\r\n\r\n-- >>> initial 2 2\r\n-- array ((1,1),(2,2)) [((1,1),True),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\nintact :: UArray (Int, Int) Bool -> Int -> Int -> Int -> Int -> Bool\r\nintact arr l r h b = and [ arr ! (x, y) | x <- [l .. r], y <- [h, b] ]\r\n\r\n-- >>> intact (initial 2 2) 1 2 1 2\r\n-- True\r\n\r\nfall :: UArray (Int, Int) Bool -> (Int, Int) -> UArray (Int, Int) Bool\r\nfall arr p = arr // [(p, False)]\r\n\r\n-- >>> fall (initial 2 2) (1, 1)\r\n-- array ((1,1),(2,2)) [((1,1),False),((1,2),True),((2,1),True),((2,2),True)]\r\n\r\ncount :: UArray (Int, Int) Bool -> Int\r\ncount arr = foldl' (\\acc (x, y, a, b) -> if intact arr x y a b then acc + 1 else acc)\r\n 0\r\n [ (x, y, a, b) | x <- [1 .. n], y <- [x .. n], a <- [1 .. m], b <- [a .. m] ]\r\n where (n, m) = snd $ bounds arr\r\n\r\n{-\r\n\r\n>>> n = 7\r\n>>> m = 4\r\n>>> arr = initial n m\r\n\r\n>>> count arr\r\n280\r\n\r\n>>> ((\\x -> count . fall arr . (x,) <$> [1..m]) <$> [1..n])\r\n[[252,252,252,252],[232,232,232,232],[220,220,220,220],[216,216,216,216],[220,220,220,220],[232,232,232,232],[252,252,252,252]]\r\n\r\n>>> ps = (\\[a,b]->(a,b)) <$> sequence [[1..n], [1..m]]\r\n\r\n>>> ps\r\n[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4),(5,1),(5,2),(5,3),(5,4),(6,1),(6,2),(6,3),(6,4),(7,1),(7,2),(7,3),(7,4)]\r\n\r\n-- >>> sequence [ps, ps]\r\n\r\n>>> count . foldl fall arr <$> sequence [ps,ps]\r\n\r\n-}\r\n\r\ndiff :: Int -> [Int] -> ([Int], Int)\r\ndiff zero =\r\n (\\(acc, zs) -> if zs > 0 then (0 : acc, zs) else (acc, 0))\r\n . foldr (\\(a, b) (acc, zs) -> if a - b == 0 then (acc, zs + 1) else (a - b : acc, zs)) ([], zero)\r\n . (zip =<< tail)\r\n\r\n-- >>> diff 1 [0, 1]\r\n-- ([0,1],1)\r\n\r\n\r\ngo :: Int -> [Int] -> Int\r\ngo _ [0, x] = x\r\ngo _ [x] = x\r\ngo zero xs = go (max 0 (zs - 1)) (sort di) where (di, zs) = diff zero xs\r\n\r\n{-\r\n\r\n>>> go 0 [1,10,100]\r\n81\r\n\r\n>>> go 0 [4,8,9,13]\r\n3\r\n\r\n>>> go 0 [0,0,0,8,13]\r\n1\r\n\r\n>>> go 0 [2,4,8,16,32,64]\r\n2\r\n\r\n-}\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn @Int\r\n xs <- map (read @Int) . words <$> getLine\r\n print $ go 0 xs\r\n"}], "src_uid": "499b1440d8bb528d089724910e37e226"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\n\nmain = do\n [n,d,l] <- map read.words <$> getLine\n putStrLn.unwords.map show $ solve n d l []\n\nsolve 2 !d l ans\n | d>0 && d+1<=l = [d+1,1] ++ ans\n | d==0 = 1:1:ans\n | d<0 && 1-d<=l = [1,1-d] ++ ans\n | otherwise = [-1]\nsolve 3 !d l ans\n | d>0 && d<=2*l-1 = let q = div (d+1) 2 in ans ++ [q,1,q]\n | d==0 && l>=2 = ans ++ [1,2,1]\n | d<0 && 2-d<=l = ans ++ [1,2-d,1]\n | otherwise = [-1]\nsolve !n d l ans\n | d>0 = solve (n-2) (d-l+1) l $ [l,1] ++ ans\n | d==0 = solve (n-2) 0 l $ 1:1:ans\n | d<0 = solve (n-2) (d+l-1) l $ [1,l] ++ ans\n | otherwise = [-1]\n", "positive_code": [{"source_code": "\nimport Monad (liftM)\nimport Prelude hiding (print)\n\nsolve :: [Integer] -> [Integer]\nsolve [n, d, l] = case as of\n Just as -> reverse as\n Nothing -> [-1]\n where\n as = rec l d n\n rec l d 1\n | 1 <= d && d <= l = Just [d]\n | otherwise = Nothing\n rec l d n\n | even n && d < 0 = fmap (l:) $ rec l (d+l) (n-1)\n | even n && d >= 0 = fmap (1:) $ rec l (d+1) (n-1)\n | 2 * d < l + 1 = fmap (1:) $ rec l (d-1) (n-1)\n | otherwise = fmap (l:) $ rec l (d-l) (n-1)\n\nprint :: Show a => [a] -> IO ()\nprint [a] = putStrLn (show a)\nprint (x:xs) = putStr (show x ++ \" \") >> print xs\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= print . solve\n"}, {"source_code": "import Control.Applicative\n\nmagic :: [Int] -> Int\nmagic [x] = x\nmagic [] = 0\nmagic (x:y:xs) = (x - y) + magic xs\n\nsolve :: Int -> Int -> Int -> Maybe [Int]\nsolve n d l = add (d - initialSum) initial where\n initial = take n $ repeat 1\n initialSum = magic initial\n\n add :: Int -> [Int] -> Maybe [Int]\n add 0 xs = Just xs\n add _ [] = Nothing\n add a [x]\n | 1 <= x + a && x + a <= l = Just [x + a]\n | otherwise = Nothing\n add a (x:y:xs)\n | a > 0 = if x + a <= l \n then Just (x+a : y : xs)\n else do\n res <- add (a - (l-x)) xs\n return $ l:y:res\n | a < 0 = if y - a <= l\n then Just (x : y - a : xs)\n else do\n res <- add (a + (l - y)) xs\n return $ x:l:res\n\nmain = do\n [n, d, l] <- map read <$> words <$> getLine\n putStrLn $ case solve n d l of \n Nothing -> \"-1\"\n Just xs -> concatMap ((++\" \") . show) xs\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\nsolve n d l = adjust (sum ls) ls []\n where\n adjust sm [] acc\n | sm == d = map abs $ reverse acc\n | otherwise = [-1]\n adjust sm (x:xs) acc\n | x < 0 && sm > d = let diff = min (sm-d) (l-1) in\n adjust (sm-diff) xs (x-diff:acc)\n | x > 0 && sm < d = let diff = min (d-sm) (l-1) in\n adjust (sm+diff) xs (x+diff:acc)\n | otherwise = adjust sm xs (x:acc)\n ls = take n $ intersperse (-1) (repeat 1)\n\nmain = do\n [n,d,l] <- map read . words <$> getLine\n putStrLn $ unwords . map show $ solve n d l"}, {"source_code": "main = do\n str <- getLine\n putStr $ unwords $ map show $ f $ map (\\x -> read x :: Int) $ words str\n\nf :: [Int]->[Int]\nf [n,d,l]\n | (od * l - ev) < d = [-1]\n | (od - ev * l) > d = [-1]\n | otherwise = f1 n l 1 (d-od+ev)\n where \n od = ((div n 2) + (mod n 2))\n ev = (div n 2)\n \nf1 :: Int->Int->Int->Int->[Int]\nf1 n l pos rest\n | pos==n+1 = []\n | rest==0 = 1:(f1 n l (pos+1) 0)\n | oddness==1 = maxv:(f1 n l (pos+1) (rest-maxv+1))\n | oddness==0 = minv:(f1 n l (pos+1) (rest+minv-1))\n where\n oddness = mod pos 2\n maxv = 1 + min (l-1) (max rest 0)\n minv = 1 + min (l-1) (max (-rest) 0)\n"}], "negative_code": [], "src_uid": "a20d59a0db07cbb5692f01d28e41a3a1"} {"source_code": "import Data.Functor ((<$>))\n\nmain :: IO ()\nmain = getLine >> solve <$> (lines <$> getContents) >>= mapM_ putStrLn\n\nsolve :: [String] -> [String]\nsolve xss = [ [ if x == '-' then '-' else \"BW\" !! ((i + j) `mod` 2) | (j, x) <- zip [0..] xs ] | (i, xs) <- zip [0..] xss ]\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n\tgetLine\n\tinteract $ unlines . putChess . lines\n\nputChess :: [String] -> [String]\nputChess ss = zipWith tchess ss $ cycle \"BW\"\n\ntchess :: String -> Char -> String\ntchess [] _ = \"\"\ntchess ('-':xs) 'W' = '-' : (tchess xs 'B')\ntchess ('-':xs) 'B' = '-' : (tchess xs 'W')\ntchess (_:xs) 'W' = 'W' : (tchess xs 'B')\ntchess (_:xs) 'B' = 'B' : (tchess xs 'W')\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.List (tails)\n\nmain :: IO ()\nmain = getLine >> solve <$> (lines <$> getContents) >>= mapM_ putStrLn\n\nsolve :: [String] -> [String]\nsolve = zipWith (zipWith $ \\x y -> if y == '-' then y else x) $ tails (cycle \"BW\")\n"}, {"source_code": "import Data.List\nmain = do\n getLine\n mapM_ putStrLn . zipWith row (tails (cycle \"BW\")) . lines =<< getContents\nrow = zipWith cell\ncell _ '-' = '-'\ncell c _ = c\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n interact $ unlines.f.lines\n\nf :: [String] -> [String]\nf css = zipWith (zipWith g) css . tails $ cycle \"BW\"\n\ng '-' c = '-'\ng _ c = c"}, {"source_code": "import Data.List\n\nmain = do\n\tgetLine\n\tinteract $ unlines.f.lines\n\t\nf :: [String] -> [String]\nf x = zipWith (zipWith g ) x (tails $ cycle \"BW\")\n\ng '-' x = '-'\ng _ x = x"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\n\nplace :: Bool -> Char -> Char\nplace True '.' = 'B'\nplace False '.' = 'W'\nplace _ c = c\n\nplaceRow :: Bool -> String -> String\nplaceRow b = zipWith place (iterate not b)\n\nmain :: IO ()\nmain = do\n\t[n,_] <- inputInts\n\tboard <- replicateM n getLine\n\tmapM_ putStrLn $ zipWith placeRow (iterate not True) board\n\n"}, {"source_code": "import Data.List\n\nmain = do\n\tgetLine\n\tinteract $ unlines.f.lines\n\t\nf :: [String] -> [String]\nf x = zipWith (zipWith g ) x (tails $ cycle \"BW\")\n\ng '-' x = '-'\ng _ x = x"}], "negative_code": [], "src_uid": "dc31adef80f06897ea2f5ef76854bcf1"} {"source_code": "import Control.Applicative\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\n\n\nmain = do\n B.getLine\n l1 <- B.unpack <$> B.getLine\n l2 <- B.unpack <$> B.getLine\n print $ solve l1 l2\n\nmodulo = 1000000007\n\nmodBase n = mod n modulo\n\nsolve :: String -> String -> Int64\nsolve l1 l2 = a\n where\n (a,_,_,_) = e l1 l2\n\nlen = fromIntegral . length\n\ne :: String -> String -> (Int64,Int64,Int64,Int64)\ne [] [] = (0,0,0,1)\ne (x:xs) (y:ys) = (a,b,c,d)\n where\n as = assign x y\n (a',b',c',d') = e xs ys\n a = modBase $\n modBase (a' * len (filter (const True) as)) +\n modBase (b' * len (filter (\\ (x,y) -> x > y) as)) +\n modBase (c' * len (filter (\\ (x,y) -> x < y) as))\n b = modBase $\n modBase (b' * len (filter (\\ (x,y) -> x <= y) as)) +\n modBase (d' * len (filter (\\ (x,y) -> x < y) as))\n c = modBase $\n modBase (c' * len (filter (\\ (x,y) -> x >= y) as)) +\n modBase (d' * len (filter (\\ (x,y) -> x > y) as))\n d = modBase (d' * len (filter (\\ (x,y) -> x == y) as))\n \nassign :: Char -> Char -> [(Char,Char)]\nassign '?' '?' = [ (a,b) | a <- ['0'..'9'],b <- ['0'..'9']]\nassign '?' c = [ (a,c) | a <- ['0'..'9']]\nassign c '?' = [ (c,b) | b <- ['0'..'9']]\nassign c d = [ (c,d)]\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ntoPairs (x:y:xys) = (x,y) : toPairs xys\ntoPairs _ = []\n\nmain :: IO ()\nmain = do\n [_,xs,ys] <- B.words <$> B.getContents\n let cnt = B.count '?' xs + B.count '?' ys\n print . (`mod`1000000007) $ 10^cnt - (solveLTEQ xs ys + solveGTEQ xs ys - solveEQ xs ys)\n\n\nsolveLTEQ :: B.ByteString -> B.ByteString -> Integer\nsolveLTEQ xs ys = go 1 xs ys\n where\n go !res xs0 ys0 | B.null xs0 && B.null ys0 = res\n go !res xs0 ys0\n | x=='?' = if y=='?' then go (res *% 55) xs ys else go (res *% (read[y]+1)) xs ys\n | y=='?' = go (res *% (10-read[x])) xs ys\n | x <= y = go res xs ys\n | otherwise = 0\n where\n Just (x,xs) = B.uncons xs0\n Just (y,ys) = B.uncons ys0\n\nsolveEQ :: B.ByteString -> B.ByteString -> Integer\nsolveEQ xs ys = go 1 xs ys\n where\n go !res xs0 ys0 | B.null xs0 && B.null ys0 = res\n go !res xs0 ys0\n | x=='?' = if y=='?' then go (res *% 10) xs ys else go res xs ys\n | y=='?' || x==y = go res xs ys\n | otherwise = 0\n where\n Just (x,xs) = B.uncons xs0\n Just (y,ys) = B.uncons ys0\n\n\nsolveGTEQ :: B.ByteString -> B.ByteString -> Integer\nsolveGTEQ xs ys = go 1 xs ys\n where\n go !res xs0 ys0 | B.null xs0 && B.null ys0 = res\n go !res xs0 ys0\n | x=='?' = if y=='?' then go (res *% 55) xs ys else go (res *% (10-read[y])) xs ys\n | y=='?' = go (res *% (read[x]+1)) xs ys\n | x >= y = go res xs ys\n | otherwise = 0\n where\n Just (x,xs) = B.uncons xs0\n Just (y,ys) = B.uncons ys0\n\ninfixl 7 *%\n(*%) :: Integer -> Integer -> Integer\nx *% y = x * y `rem` 1000000007\n{-# INLINE (*%) #-}"}, {"source_code": "import Control.Applicative\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport qualified Data.Array as A\n\n\nmain = do\n getLine\n l1 <- getLine\n l2 <- getLine\n print $ solve l1 l2\n\nmodulo = 1000000007\n\nmodBase n = mod n modulo\n\nsolve :: String -> String -> Int64\nsolve l1 l2 = a\n where\n (a,_,_,_) = e l1 l2\n\ne :: String -> String -> (Int64,Int64,Int64,Int64)\ne [] [] = (0,0,0,1)\ne (x:xs) (y:ys) = (modBase a,modBase b,modBase c,modBase d)\n where\n as = assign x y\n (a',b',c',d') = e xs ys\n a = a' * ptns A.! (x',y',0) + b' * ptns A.! (x',y',1)+ c' * ptns A.! (x',y',2)\n b = b' * ptns A.! (x',y',3) + d' * ptns A.! (x',y',2)\n c = c' * ptns A.! (x',y',4) + d' * ptns A.! (x',y',1)\n d = d' * ptns A.! (x',y',5)\n f op = fromIntegral $ length $ filter (uncurry op) as\n t x y = True\n x' = conv x\n y' = conv y\ndigit = ['0'..'9']\nassign :: Char -> Char -> [(Char,Char)]\nassign '?' '?' = [ (a,b) | a <- digit,b <- digit]\nassign '?' c = [ (a,c) | a <- digit]\nassign c '?' = [ (c,b) | b <- digit]\nassign c d = [ (c,d) ]\n\nconv '?' = ':'\nconv c = c\n\nconvI ':' = '?'\nconvI c = c\n\nptns :: A.Array (Char,Char,Int) Int64\nptns = A.listArray (('0','0',0),(':',':',5)) [ f c1 c2 i | c1 <- ['0'..':'], c2 <- ['0'..':'], i <- [0..5]]\n where\n f c1 c2 i = case i of\n 0 -> fromIntegral $ length $ filter (const True) as\n 1 -> fromIntegral $ length $ filter (uncurry (>)) as\n 2 -> fromIntegral $ length $ filter (uncurry (<)) as\n 3 -> fromIntegral $ length $ filter (uncurry (<=)) as\n 4 -> fromIntegral $ length $ filter (uncurry (>=)) as\n 5 -> fromIntegral $ length $ filter (uncurry (==)) as\n where\n as = assign (convI c1) (convI c2)\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n let m = if even n then n `div` 2 else n `div` 2 + 1\n b <- (words >>> sort >>> group >>> map ((<=m).length) >>> and ) <$> getLine\n let s = (if b then \"YES\" else \"NO\")\n putStrLn s\n"}], "src_uid": "e649128c554233895f3f21275dd2105c"} {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\ndebug = flip trace\n-- debug = const\n\nsolve n =\n aux [1..n]\n where aux [] = []\n aux (a:[]) = [a]\n aux (a:as) = a : last as : aux (init as)\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n putStrLn $ intercalate \" \" $ map show $ solve n", "positive_code": [{"source_code": "main = do getLine >>= putStrLn . unwords . map show . gao . read where\n\tgao n = [if odd i then 1 + div i 2 else n - div i 2 | i <- [0 .. n - 1]]\n\n"}, {"source_code": "\nmain = readLn >>= putStrLn.unwords.map show.solve\n\nsolve :: Int -> [Int]\nsolve n = sortFrog 0 [1..n]\n\nsortFrog _ [] = []\nsortFrog 0 xs = head xs : sortFrog 1 (tail xs)\nsortFrog 1 xs = last xs : sortFrog 0 (init xs)\n"}], "negative_code": [{"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\ndebug = flip trace\n-- debug = const\n\nsolve n =\n aux [1..n]\n where aux [] = []\n aux (a:[]) = [a]\n aux (a:as) = a : last as : init as \n\nmain = do\n n <- read `fmap` getLine :: IO Int\n putStrLn $ intercalate \" \" $ map show $ solve n"}, {"source_code": "import List\nmain = do getLine >>= putStrLn . unwords . map show . gao . read where\n\tgao n = let (o, e) = partition odd [1 .. n] in o ++ reverse e\n"}], "src_uid": "02b7ff5e0b7f8cd074d9e76251c2725e"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain = do\n n <- liftM read getLine :: IO Int\n\n cards <- replicateM n $ do\n [a, b] <- liftM ( map read . words ) getLine\n return (a, b)\n\n let\n (counter, score, pendings) =\n foldl\n ( \\(counter, score, pendings) (a, b) ->\n if b == 0\n then (counter, score, a:pendings)\n else (counter+b-1, score+a, pendings) )\n (1, 0, [])\n cards\n\n ans = score + ( sum $ take counter $ sortBy (comparing (0-)) pendings )\n\n putStrLn $ show ans\n", "positive_code": [{"source_code": "import Data.List\n\nparse :: [String] -> [[Int]]\nparse stuff = map parseL stuff\n where parseL line = reverse $ map read (words line)\n\n\nsolve cards = subsolve 0 1 (reverse $ sort cards)\n where subsolve acc 0 _ = acc\n subsolve acc _ [] = acc\n subsolve acc cnt ([b,a]:xs) = subsolve (acc + a) (cnt + b - 1) xs\n\nmain = do\n n <- getLine\n cards <- sequence [getLine | _ <- [1.. (read n)]]\n print . solve . parse $ cards\n"}, {"source_code": "import Control.Monad\nimport Data.List\nsolve xs = s' + s'' \n where s' = sum $ map fst xs'\n k = (sum $ map snd xs') - length xs' + 1\n xs' = [x | x <- xs , snd x > 0]\n s'' =sum $ map fst $ take k $ (reverse . sortBy (\\a b -> compare (fst a) (fst b))) (xs \\\\ xs')\ntuplify2 :: [a] -> (a,a)\ntuplify2 [x,y] = (x,y)\nmain=do\n n <- fmap read $ getLine\n xs <- forM [1..n] (\\_ -> getLine >>= (return . tuplify2 . map (read::String->Int) . words))\n print $ solve xs\n \n"}, {"source_code": "\nimport List (partition, sortBy)\n\n{-\nimport HUnit\n\ntestOneCard :: Test\ntestOneCard = Test \"TestOneCard\" $\n assertEq 2 (solve [(2,0)])\n\ntestAllCardsZero :: Test\ntestAllCardsZero = Test \"TestAllCardsZero\" $\n assertEq 3 (solve [(1,0),(3,0),(2,0)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq 2 (solve [(2,0),(1,0)]),\n Test \"2\" $ assertEq 3 (solve [(2,0),(1,0),(0,2)])]\n\ntest :: IO ()\ntest = mapM_ run\n [testOneCard,\n testAllCardsZero,\n testInput]\n\n--------------------------------------------------------------------------------\n-}\n\ntype Card = (Int, Int)\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nreadCard :: IO Card\nreadCard = do\n [a, b] <- Main.reads\n return (a, b)\n\nsolve :: [Card] -> Int\nsolve cards = sum (map fst notZero)\n + sum (map fst (take (sum (map snd notZero) + 1 - length notZero) zero'))\n where\n (zero, notZero) = partition ((== 0) . snd) cards\n zero' = reverse (sortBy (\\c1 c2 -> compare (fst c1) (fst c2)) zero)\n\nmain :: IO ()\nmain = do\n [n] <- Main.reads\n cards <- mapM (const readCard) [1..n]\n print $ solve cards"}, {"source_code": "import Data.List\ntype Card = (Integer, Integer)\nreadCard :: String -> Card\nreadCard str = ((read suf)::Integer, (read pre)::Integer)\n where (pre, suf) = break (== ' ') str\ncalc :: [Card] -> Integer\ncalc xs = sum $map snd $ pre ++ suf'\n where xs' = reverse . sort $ xs\n (pre, suf) = break ((== 0).fst) xs'\n t = 1 + sum (map fst pre) - genericLength pre\n suf' = take (fromIntegral t) suf\n\nmain = interact $ show . calc . map readCard . tail . lines "}, {"source_code": "import IO\nimport Data.List\nimport Debug.Trace\n\nswap (x, y) = (y, x)\n\ngetInteger :: IO Int\ngetInteger = do\n line <- getLine\n return (read line)\n\ngetIntegers :: IO [Int]\ngetIntegers = do\n line <- getLine\n return (map read (words line))\n\nreadNumbers :: Int -> IO [(Int, Int)]\nreadNumbers 0 = return ([])\nreadNumbers count = do\n --putTraceMsg (\"count = \" ++ (show count))\n [first, second] <- getIntegers\n --putTraceMsg (\"first = \" ++ (show first) ++ \", second = \" ++ (show second))\n numbers <- (readNumbers $ count - 1)\n return ([(first, second)] ++ numbers)\n\n\nrunAux :: [(Int, Int)] -> Int -> Int\nrunAux [] stack = 0\nrunAux (x:xs) stack =\n if stack == 0 then 0\n else fst x + runAux xs (stack - 1 + snd x)\n\n\nrun :: [(Int, Int)] -> Int\nrun x = runAux sorted 1\n where secondLess = (\\a b -> if swap a > swap b then LT else GT)\n sorted = sortBy secondLess x\n\nmain = do\n n <- getInteger\n --putTraceMsg (\"N = \" ++ show n)\n numbers <- (readNumbers n)\n let result = run numbers\n putStrLn $ show result \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [(Int, Int)] -> Int -> Int\nsolve [] _ = 0\nsolve _ 0 = 0\nsolve ((a, b):xs) n = a + (solve xs $ n - 1 + b)\n\nmain = do\n n <- read <$> getLine\n a <- forM [1..n] $ \\x ->\n map read <$> (words <$> getLine)\n let arr = map (\\(x, y) -> (-y, -x)) $ sort $ map (\\[x,y] -> (-y, -x)) a\n print $ solve arr 1\n"}, {"source_code": "\nimport List (partition, sortBy)\n\n{-\nimport HUnit\n\ntestOneCard :: Test\ntestOneCard = Test \"TestOneCard\" $\n assertEq 2 (solve [(2,0)])\n\ntestAllCardsZero :: Test\ntestAllCardsZero = Test \"TestAllCardsZero\" $\n assertEq 3 (solve [(1,0),(3,0),(2,0)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq 2 (solve [(2,0),(1,0)]),\n Test \"2\" $ assertEq 3 (solve [(2,0),(1,0),(0,2)])]\n\ntest :: IO ()\ntest = mapM_ run\n [testOneCard,\n testAllCardsZero,\n testInput]\n\n--------------------------------------------------------------------------------\n-}\n\ntype Card = (Int, Int)\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nreadCard :: IO Card\nreadCard = do\n [a, b] <- Main.reads\n return (a, b)\n\nsolve :: [Card] -> Int\nsolve cards = sum (map fst notZero)\n + sum (map fst (take (sum (map snd notZero) + 1 - length notZero) zero'))\n where\n (zero, notZero) = partition ((== 0) . snd) cards\n zero' = reverse (sortBy (\\c1 c2 -> compare (fst c1) (fst c2)) zero)\n\nmain :: IO ()\nmain = do\n [n] <- Main.reads\n cards <- mapM (const readCard) [1..n]\n print $ solve cards\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do _ <- getLine\n xys <- map ((\\[x,y] -> (y,x)) . map read . words) . lines <$> getContents\n print $ solve xys\n\nsolve :: [(Int,Int)] -> Int\nsolve xys = fst $ foldl' f (0,1) $ sortBy (flip compare) xys\n\nf :: (Int,Int) -> (Int,Int) -> (Int,Int)\nf (p,r) (b,a)\n | r == 0 = (p,0)\n | otherwise = (p+a,r+b-1)"}, {"source_code": "import Control.Applicative\nimport Data.List\n\ngetCard :: Int -> IO [(Int, Int)]\ngetCard 0 = return []\ngetCard n = do\n (a:b:_) <- map read <$> (words <$> getLine)\n cards <- getCard $ n - 1\n return $ (-b, -a): cards\n\nsolve :: [(Int, Int)] -> Int -> Int\nsolve [] _ = 0\nsolve _ 0 = 0\nsolve (c:cs) n = -(snd c) + solve cs (n - (fst c) - 1)\n\nmain = do\n n <- read <$> getLine\n xs <- getCard n\n print $ solve (sort xs) 1\n\n\n"}, {"source_code": "import Data.List\n\nmain:: IO ()\nmain = do cs <- getContents\n (putStr .show .solve .parse) cs\n\nparse_step::String->(Int,Int)\nparse_step s = (x,y)\n where [x,y] = map (\\x -> read x::Int) (words s)\n\nparse::String->[(Int,Int)]\nparse s = foldr (\\x y->(parse_step x):y ) [] ss\n where ss = (tail .lines) s\n\nsplitf :: (a->Bool)-> [a]->([a],[a])\nsplitf f l = foldr (\\x (tr,fa)->if (f x)\n then ((x:tr),fa)\n else (tr,x:fa)) ([],[]) l\n\nhasB :: (Int,Int) -> Bool\nhasB (_,b) = (b /= 0)\n\nplus_cards::[(Int,Int)]->(Int,Int)\nplus_cards = foldl (\\(xa,ya) (xb,yb)->(xa+xb,ya+yb)) (0,0) \n\ncardcomp::(Int,Int)->(Int,Int)->Ordering\ncardcomp (x1,_) (x2,_) = compare x2 x1\n\nsolve::[(Int,Int)] -> Int\nsolve l = totalA + totalB\n where\n (bcard,acard) = splitf hasB l\n (totalB,k) = plus_cards bcard\n (totalA,_) = plus_cards (take (k+1-(length bcard)) (sortBy cardcomp acard))"}, {"source_code": "import Data.List\n\nmain = do\n\tnS <- getLine\n\tlet n = read nS :: Int\n\tstrs <- getNLines n []\n\tlet css = (map (\\(a:b:_) -> (read a, read b)) $ map words strs) :: [(Int,Int)]\n\tputStrLn.show $ solve css\n\ngetNLines 0 acc = return (reverse acc)\ngetNLines n acc = do\n\tx <- getLine\n\tgetNLines (n-1) (x:acc)\n\t\nsolve css = sl' (sBysnd css) 1 0\n\nsl' :: [(Int, Int)] -> Int -> Int -> Int\t\nsl' (c:cs) 0 acc = acc\nsl' [] n acc = acc\nsl' (c:cs) n acc \n\t| (snd c == 0) = (acc + (sum $ take (n) $ map fst (reverse $ sort (c:cs))))\n\t| otherwise = sl' cs ((snd c) + n - 1) (acc + (fst c))\n\nsBysnd (a:as) = sortBy (\\x y -> compare (snd y) (snd x)) (a:as)\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain:: IO ()\nmain = do cs <- getContents\n (putStr .show .solve .parse) cs\n\nparse_step::String->(Int,Int)\nparse_step s = (x,y)\n where [x,y] = map (\\x -> read x::Int) (words s)\n\nparse::String->[(Int,Int)]\nparse s = foldr (\\x y->(parse_step x):y ) [] ss\n where ss = (tail .lines) s\n\nsplitf :: (a->Bool)-> [a]->([a],[a])\nsplitf f l = foldr (\\x (tr,fa)->if (f x)\n then ((x:tr),fa)\n else (tr,x:fa)) ([],[]) l\n\nhasB :: (Int,Int) -> Bool\nhasB (_,b) = (b /= 0)\n\nplus_cards::[(Int,Int)]->(Int,Int)\nplus_cards = foldl (\\(xa,ya) (xb,yb)->(xa+xb,ya+yb)) (0,0) \n\ncardcomp::(Int,Int)->(Int,Int)->Ordering\ncardcomp (x1,_) (x2,_) = compare x2 x1\n\nsolve::[(Int,Int)] -> Int\nsolve l = totalA + totalB\n where\n (bcard,acard) = splitf hasB l\n (totalB,k) = plus_cards bcard\n (totalA,_) = plus_cards (take (k+1) (sortBy cardcomp acard))"}], "src_uid": "4abdd16670a796be3a0bff63b9798fed"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List (group, sort)\nimport Data.Map ((!))\nimport qualified Data.Map as M\n-- import Debug.Trace\n\nimport Data.Maybe (fromJust)\nimport System.IO\nimport Text.Read\n\ngetNums :: IO [Int]\ngetNums = do\n line <- B.getLine\n return $ map ((fst . fromJust) . B.readInt) . B.split ' ' $ line\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, k] <- getNums\n putStrLn $ unwords $ map show $ solve n k\n\nsolveEasy :: Int -> [Int]\nsolveEasy n\n | n `mod` 2 == 1 = [1, (n - 1) `div` 2, (n -1) `div` 2]\n | n `mod` 4 == 0 = [n `div` 2, n `div` 4, n `div` 4]\n | n `mod` 4 == 2 = [2, (n - 1) `div` 2, (n -1) `div` 2]\n\nsolve n k = replicate (k - 3) 1 ++ solveEasy (n - (k - 3))\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Map.Strict as MapS\r\n\r\nmain = do\r\n t <- readLn\r\n replicateM_ t testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n firstLine <- getLine\r\n let [n,k] = map read . words $ firstLine\r\n putStrLn $ solve n k\r\n\r\n\r\nsolve :: Int -> Int -> String\r\nsolve n k = unwords . map show $ sol \r\n where\r\n sol = solve3 (n-k+3) ++ replicate (k-3) 1\r\n\r\nsolve3 :: Int -> [Int]\r\nsolve3 n\r\n | odd n = [1, (n-1) `div` 2, (n-1) `div` 2]\r\n | n `mod` 4 == 0 = [n `div` 2 , n `div` 4, n `div` 4]\r\n | otherwise = [2, (n-2) `div` 2, (n-2) `div` 2]"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nsolve :: Int -> [Int]\nsolve n\n | odd n = 1 : replicate 2 (div n 2)\n | mod n 4 == 0 = div n 2 : replicate 2 (div n 4)\n | otherwise = 2 : replicate 2 (div n 2 - 1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n putInts $ solve (n - (k - 3)) ++ replicate (k - 3) 1\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Map.Strict as MapS\r\n\r\nmain = do\r\n t <- readLn\r\n replicateM_ t testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n firstLine <- getLine\r\n let [n,k] = map read . words $ firstLine\r\n putStrLn $ solve n k\r\n\r\n\r\nsolve :: Int -> Int -> String\r\nsolve n k = unwords . map show $ sol \r\n where\r\n sol = solve3 n ++ replicate (k-3) 1\r\n\r\nsolve3 :: Int -> [Int]\r\nsolve3 n\r\n | odd n = [1, (n-1) `div` 2, (n-1) `div` 2]\r\n | n `mod` 4 == 0 = [n `div` 2 , n `div` 4, n `div` 4]\r\n | otherwise = [2, (n-2) `div` 2, (n-2) `div` 2]"}], "src_uid": "1fea137016452340beb13dd7518f00c9"} {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Function\n\ndoit :: Int -> [(Int, Int)] -> Maybe [(Int, Int)]\ndoit n lst = let sz = length lst\n k = n - (snd . head $ lst)\n in if sz `mod` k == 0 then Just $ doit' 0 0 k lst else Nothing\n\ndoit' :: Int -> Int -> Int -> [(Int, Int)] -> [(Int, Int)]\ndoit' _ _ _ [] = []\ndoit' cur n ma (x:xs)\n | n == ma = doit' (cur + 1) 0 ma (x:xs)\n | otherwise = (fst x, cur) : doit' cur (n + 1) ma xs\n\nsummarize :: [Maybe [(Int, Int)]] -> Maybe [Int]\nsummarize lst\n | any isNothing lst = Nothing\n | otherwise = Just . map snd . sortBy (compare `on` fst) . concat . map fst . scanl f ([], 1) $ lst\n\nf :: ([(Int, Int)], Int) -> Maybe [(Int, Int)] -> ([(Int, Int)], Int)\nf (_, start) (Just lst) = (map (\\(a, b) -> (a, b + start)) lst, start + maximum (map snd lst) + 1)\n\nmain = do\n n <- readLn\n l <- fmap (summarize . map (doit n) . groupBy ((==) `on` snd) . sortBy (compare `on` snd) . zip [0..] . map read . words) getLine\n putStrLn $ case l of\n Nothing -> \"Impossible\"\n Just x -> \"Possible\\n\" ++ (unwords . map show $ x)\n", "positive_code": [{"source_code": "import Data.List\n\nf::Int->Int->Int->Int->Int->[(Int,Int)]->[(Int,Int)]\nf _ _ _ _ _ []=[]\nf c n _ a _ _\n |aInt->Int->[Int]->[Int]->Bool\nf2 _ _ _ [] _=True\nf2 _ 0 _ _ []=True\nf2 n c c3 xs []=f2 n c c3 xs [(-1)]\nf2 n 0 c3 (x:xs) (c2:ys)=f2 n c2 c2 (x:xs) ys\nf2 n c c3 (x:xs) (c2:ys)\n |x+c3/=n=False\n |otherwise=f2 n (c-1) c3 xs (c2:ys)\n\nmain = do\n e<-getLine\n es<-getLine\n let n=read e::Int\n xs=map read (words es)::[Int]\n ys=map (n - ) xs\n zs=sort $ zip ys [(1::Int)..(n::Int)]\n ans=sort (f 0 0 0 n 0 zs)\n ans2=(map snd ans)\n t1=group $ sort ans2\n t2=map length t1\n-- print t2\n-- print (reverse (sort xs))\n putStrLn $ if length(ans)==n && f2 n (head t2) (head t2) (reverse (sort xs)) (tail t2)\n then \"Possible\\n\"++(unwords ( map show ( ans2)))\n else \"Impossible\""}], "negative_code": [{"source_code": "import Data.List\n\nf ::Int->Int->Int->Int->[Int]->[Int]\nf _ _ _ _ []=[]\nf n _ a _ _\n |n>a=[]\nf n 0 a _ (x:xs)=f (n+1) (a-x) a x (x:xs)\nf n d a o (x:xs)\n |o/=x=[]\n |otherwise=n:f n (d-1) a o xs\n\nmain =do\n e<-getLine\n es<-getLine\n let x=read e::Int\n let xs=map read (words es)::[Int]\n ys=sort xs\n ans=f 0 0 x 0 ys\n putStrLn $ if (length ans)==x then \"Possible\\n\"++(unwords (map show ans)) else \"Impossible\""}, {"source_code": "import Data.List\n \nf::Int->Int->Int->Int->Int->[(Int,Int)]->[(Int,Int)]\nf _ _ _ _ _ []=[]\nf c n _ a _ _\n |aInt->[Int]->[Int]->Bool\nf2 _ _ [] _=True\nf2 _ _ _ []=True\nf2 n 0 (x:xs) (c2:ys)=f2 n c2 (x:xs) ys\nf2 n c (x:xs) (c2:ys)\n |x+c2/=n=False\n |otherwise=f2 n (c-1) xs (c2:ys)\n \nmain = do\n e<-getLine\n es<-getLine\n let n=read e::Int\n xs=map read (words es)::[Int]\n ys=map (n - ) xs\n zs=sort $ zip ys [(1::Int)..(n::Int)]\n ans=sort (f 0 0 0 n 0 zs)\n ans2=(map snd ans)\n t1=group $ sort ans2\n t2=map length t1\n putStrLn $ if length(ans)==n && f2 n (head t2) (reverse (sort xs)) t2\n then \"Possible\\n\"++(unwords ( map show ( ans2)))\n else \"Impossible\""}], "src_uid": "f49667ef00cd0da6a6fad67a19d92f1e"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (forM, liftM)\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Debug.Trace (trace)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\ndata Query = Set Int Int\n | Add Int\n | Get Int\n deriving (Show)\n\ntype Values s = STArray s Int (Int, Int)\ntype PartialSums s = STArray s Int Int\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n\nparseQueries :: [Int] -> [Query]\nparseQueries [] = []\nparseQueries (1:v:x:qs) = (Set v x) : (parseQueries qs)\nparseQueries (2:y:qs) = (Add y) : (parseQueries qs)\nparseQueries (3:q:qs) = (Get q) : (parseQueries qs)\n\nsolve :: Int -> Int -> [Int] -> [Query] -> [Int]\nsolve n m vs qs = runST $ do\n values <- newListArray (1, n) (zip vs [0, 0 ..]) :: ST s (Values s)\n sums <- newArray (0, m) 0 :: ST s (PartialSums s)\n result <- forM (zip qs [1 .. m]) $ \\(query, timestamp) -> do\n cur <- readArray sums (timestamp - 1)\n writeArray sums timestamp cur\n case query of\n Set v x -> writeArray values v (x, timestamp) >> return (-1)\n Add y -> writeArray sums timestamp (cur + y) >> return (-1)\n Get q -> do (x, time) <- readArray values q\n prev <- readArray sums time\n return (x + cur - prev)\n return $ filter (>= 0) result\n\nmain = do\n (n:m:cs) <- liftM (map readInt . BS.words) BS.getContents\n let (values, qs) = splitAt n cs\n queries = parseQueries qs\n let result = solve n m values queries\n mapM_ print result\n", "positive_code": [{"source_code": "import Control.Monad (liftM, mapM_)\nimport Data.Array.IO\nimport Data.Array.MArray\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Prelude hiding (read, reads)\n\nread :: String -> Int\nread ('-':s) = (-1) * read s\nread s = read' 0 s\n where\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + fromEnum c - fromEnum '0'\n\n--reads :: Read a => IO [a]\nreads :: IO [Int]\nreads = liftM (map read . words) getContents\n\nsolve :: Int -> [Int] -> [Int] -> IO ()\nsolve n xs ys = do\n array <- newArray_ (1, n)\n sequence_ [writeArray array i a | (i, a) <- zip [1..] xs]\n solve' array 0 ys\n where\n solve' :: IOUArray Int Int -> Int -> [Int] -> IO ()\n solve' _ _ [] = return ()\n solve' array acc (1 : i : a : ys) = do\n writeArray array i (a - acc)\n solve' array acc ys\n solve' array acc (2 : s : ys) = do\n solve' array (acc + s) ys\n solve' array acc (3 : i : ys) = do\n a <- readArray array i\n print (acc + a)\n solve' array acc ys\n\nmain :: IO ()\nmain = do\n ints <- reads\n let [n, m] = take 2 ints\n let xs = take n $ drop 2 ints\n let ys = drop (n + 2) ints\n solve n xs ys"}], "negative_code": [], "src_uid": "48f3ff32a11770f3b168d6e15c0df813"} {"source_code": "import Control.Monad\nmain = do\n n <- fmap read getLine\n forM [1..n]\n (\\_ -> do\n [a,b] <- fmap (map read.words) getLine\n print $ calc a b)\ncalc :: Int -> Int -> Int\ncalc a b = 1 + div ((abs $ a-b)-1) 10\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nmodule Main (main) where\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Bits\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.State.Strict (StateT)\nimport qualified Control.Monad.Trans.State.Strict as StateT\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\n \n\ngetNewLine :: SIO ByteString\ngetNewLine = (lift $ C.hGetLine stdin) >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n \ngetRemain :: ByteString -> SIO ByteString\ngetRemain b = let bns = C.dropWhile isSpace b in\n if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)\n else return bns\n \ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n \ntype SIO a = StateT ByteString IO a\n \nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n \ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n \ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n \nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n \ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n \ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n \ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n \ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n \ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n \nget :: IOInteract a => SIO a\nget = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get\nput :: IOInteract a => a -> SIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> SIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: SIO ()\nflush = lift (hFlush stdout)\n \nmain :: IO ()\nmain = StateT.evalStateT main_ C.empty\n \nmain_ :: SIO ()\n-------------------------------------------- template ------------------------------------------------------\n-- for io performance comparison from @Russell_Emerine's code\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: SIO ()\nf1 = do\n (a, b) <- liftM2 (,) get get\n putln $ f2 a b\n\n\nf2 :: Int64 -> Int64 -> Int64\nf2 a b = (div (abs (a - b) + 9) 10)"}, {"source_code": "import Control.Monad ( replicateM_ )\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b] <- map read . words <$> getLine\n let x = abs (a - b) :: Integer\n print $ div (x+9) 10\n"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b] <- map read . words <$> getLine\n putStrLn $ show $ div (abs (a - b) + 9) 10\n"}, {"source_code": "import Control.Monad\n\ngetInt :: IO Int\ngetInt = readLn\n\ngetFloat :: IO Float\ngetFloat = readLn\n\ngetDouble :: IO Double\ngetDouble = readLn\n\ncountMoves :: Int -> Int -> Int\ncountMoves n1 n2 =\n case abs (n1 - n2) of\n 0 -> 0\n n -> if n `mod` 10 == 0 then n `div` 10 else n `div` 10 + 1\n\nmain :: IO ()\nmain = do\n n <- getInt\n replicateM_ n $ do\n n1 : n2 : _ <- map (read :: String -> Int) . words <$> getLine\n print $ countMoves n1 n2\n"}], "negative_code": [], "src_uid": "d67a97a3b69d599b03d3fce988980646"} {"source_code": "module Main where\r\nimport Control.Monad\r\n\r\nsolve::Int->Int->Int->Int->Int\r\nsolve a b c d = do\r\n if (a * d == b * c)\r\n then 0\r\n else if (a * c == 0)\r\n then 1\r\n else if (rem (a * d) (b * c) == 0)\r\n then 1\r\n else if (rem (b * c) (a * d) == 0)\r\n then 1\r\n else 2\r\n \r\n\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let (a:b:c:d:_)=map read (words line)::[Int]\r\n --line<-getLine\r\n --let nlist=map read (words line)::[Int]\r\n print (solve a b c d)", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n \r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [a,b,c,d] <- ri\r\n return ((a,b),(c,d))\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve ((aa,bb),(cc,dd)) = cntNum\r\n where\r\n gAB = gcd aa bb\r\n gCD = gcd cc dd\r\n (a,b) = (aa `div` gAB, bb `div` gAB)\r\n (c,d) = (cc `div` gCD, dd `div` gCD)\r\n ad = a*d\r\n bc = b*c\r\n lcmN = lcm ad bc\r\n cntNum = length . filter (/=lcmN) $ [ad,bc]\r\n"}], "negative_code": [], "src_uid": "c2a506d58a80a0fb6a16785605b075ca"} {"source_code": "\nmain = interact $ concat . map (solveList . map readI . words) . tail . lines\n\nsolveList [n, k] = showL (filter isGood [1..n])\n where\n isGood num\n | num == k = False\n | num < (k+1) `div` 2 = False\n | otherwise = True\n\nreadI s = read s :: Int\n\nshowL xs = show (length xs) ++ \"\\n\" ++ (unwords . map show) xs ++ \"\\n\"\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n replicateM_ n action\n\naction = do\n [n, k] <- (map (read :: String -> Int) . words) <$> getLine\n print $ (k `div` 2) + max 0 (n - k)\n putStr $ concatMap (\\x -> show x ++ \" \") $ mkFst k\n putStrLn $ concatMap (\\x -> show x ++ \" \") [k+1..n]\n\nmkFst x\n | odd x = [(x+1) `div` 2..(x-1)]\n | even x = [x `div` 2..(x-1)]"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n let xs = filter (/=k) [(k+1)`quot`2..n]\n C.putStrLn $ C.pack $ show $ length xs\n C.putStrLn $ C.pack $ unwords $ map show xs\n"}], "negative_code": [], "src_uid": "d08e39db62215d7817113aaa384e3f59"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, k] <- map read . words <$> getLine\n [l1, r1] <- map read . words <$> getLine\n [l2, r2] <- map read . words <$> getLine\n if r1 >= l2 && r2 >= l1\n then do\n let i = minimum [r1 - l1, r2 - l2, r1 - l2, r2 - l1]\n let u = maximum [r1 - l1, r2 - l2, r1 - l2, r2 - l1]\n if i * n >= k\n then print 0\n else do\n let k' = k - i * n\n let d = u - i\n if n * d >= k'\n then print k'\n else print $ n * d + 2 * (k' - n * d)\n else do\n let i = max (l1 - r2) (l2 - r1)\n let u = max (r2 - l1) (r1 - l2)\n if u >= k\n then print $ i + k\n else\n if u * n >= k\n then print $ (u + i) * (k `div` u) + min (2 * (k `mod` u)) (i + k `mod` u)\n else print $ (u + i) * n + 2 * (k - u * n)\n", "positive_code": [{"source_code": "solveCase :: Integer -> Integer -> Integer -> Integer -> Integer -> Integer\n -> Integer\nsolveCase n k x1 y1 x2 y2\n | x1 > x2 = solveCase n k x2 y2 x1 y1 -- canonicalize\n | x2 <= y1 = let -- overlap\n existingOverlap = n * (min y1 y2 - x2)\n attainableOverlap = n * (max y1 y2 - x1)\n in if k <= attainableOverlap\n then max 0 $ k - existingOverlap\n else 2*k - existingOverlap - attainableOverlap\n | otherwise = let\n value = y2 - x1\n separation = x2 - y1\n cost = value + separation\n in\n case divMod k value of\n (0, _) -> k + x2 - y1\n (q, r)\n | q < n -> q * cost + min (2*r) (separation + r)\n | otherwise -> n * cost + 2 * (k - n * value)\n\nsoln :: [Integer] -> [Integer]\nsoln (n : k : x1 : y1 : x2 : y2 : excess)\n = solveCase n k x1 y1 x2 y2 : soln excess\nsoln _ = []\n\nmain :: IO ()\nmain = interact (unlines . map show . soln . map read . tail . words)\n\n\n\n"}], "negative_code": [{"source_code": "solveCase :: Integer -> Integer -> Integer -> Integer -> Integer -> Integer\n -> Integer\nsolveCase n k x1 y1 x2 y2\n | x1 > x2 = solveCase n k x2 y2 x1 y1 -- canonicalize\n | x2 <= y1 = let -- overlap\n existingOverlap = n * (min y1 y2 - x2)\n attainableOverlap = n * (max y1 y2 - x1)\n in if k <= attainableOverlap\n then max 0 $ k - existingOverlap\n else 2*k - existingOverlap - attainableOverlap\n | otherwise = let\n value = y2 - x1\n separation = x2 - y1\n cost = value + separation\n in\n case divMod k value of\n (0, _) -> k + x2 - y1\n (q, r)\n | q < n -> q * cost + min (2*r) (separation + r)\n | otherwise -> q * cost + 2 * (k - n * value)\n\nsoln :: [Integer] -> [Integer]\nsoln (n : k : x1 : y1 : x2 : y2 : excess)\n = solveCase n k x1 y1 x2 y2 : soln excess\nsoln _ = []\n\nmain :: IO ()\nmain = interact (unlines . map show . soln . map read . tail . words)\n\n\n\n"}], "src_uid": "c8da5d7debf5d7a6fc04bb3a68cda2f0"} {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain = do\n [n, k, a] <- ( map read . words ) `liftM` getLine\n\n senators <- replicateM n $ do\n [level, loyalty] <- ( map read . words ) `liftM` getLine :: IO [Int]\n return (level, loyalty)\n\n let vote = voteDist n\n candy = candyDist n k\n\n --putStrLn $ show $ candy\n --putStrLn $ show $ vote\n\n let prob = foldl' (\\best cdist ->\n let senators' = zipWith (\\(level, loyalty) c -> (level, fromIntegral (min (loyalty + 10 * c) 100) / 100)) senators cdist\n winProb = foldl' (\\prevProb vdist ->\n let winCount = length $ filter (==True) vdist\n prob = product $ zipWith (\\(level, loyalty) v -> if v then loyalty else 1 - loyalty) senators' vdist\n b = sum $ zipWith (\\(level, loyalty) v -> if v then 0 else level) senators' vdist\n winProb = if winCount > n `div` 2\n then 1\n else (fromIntegral a :: Double) / (fromIntegral (a + b) :: Double)\n in if prob > 0 then prevProb + prob * winProb else prevProb\n ) 0 vote\n in max winProb best\n ) 0 candy\n\n printf \"%.10f\\n\" prob\n\ncandyDist :: Int -> Int -> [[Int]]\ncandyDist 0 0 = [[]]\ncandyDist 0 _ = []\ncandyDist n k = [0..k] >>= \\k' -> map (k':) $ candyDist (n-1) (k-k')\n\nvoteDist :: Int -> [[Bool]]\nvoteDist 0 = [[]]\nvoteDist n = [True, False] >>= \\v -> map (v:) $ voteDist (n-1)\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n\nimport Data.Ord\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.Map(Map)\nimport Data.List\nimport Control.Arrow\nimport Data.Maybe\n\n\nparseSenator :: [String] -> (Double, Integer)\nparseSenator [str, loyalty] = (read str, read loyalty `div` 10)\n\ndistr 0 k = return []\ndistr n k = do\n first <- [0..k]\n others <- distr (n-1) (k-first)\n return (first : others)\n\nbribe d (s, l)\n | newL > 10 = Nothing\n | otherwise = Just (s, newL)\n where\n newL = d+l\n\nmain = do\n [n, k, a] <- map read . words <$> getLine\n senators <- sequence $ genericReplicate n $ parseSenator . words <$> getLine\n let distributions = distr (n+1) k -- +1 to account for \"keep candy\" scenario\n fight s = fromIntegral a / (fromIntegral a + s)\n s l = go l 0 0\n where\n go [] s p | p > 0 = 1\n | otherwise = fight s\n go ((ss, l) : t) s p = l' * go t s (p+1) + (1-l') * go t (s+ss) (p-1)\n where l' = fromIntegral l / 10\n solve distribution = do\n candiedSenators <- sequence $ map maybeToList $ zipWith bribe distribution senators\n return $ s candiedSenators\n result = maximum $ solve =<< distributions :: Double\n putStrLn $ show result"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}, {"source_code": "d 0 k=[[]]\nd n k=do{f<-[0..k];o<-d(n-1)$k-f;[f:o]}\nb d(s,l)|d+l*10>10.5=[]|1>0=[(s,d/10+l)]\ns([n,k,a]:t)=fmap(g(read a)0 0).sequence.($map(\\[s,l]->(read s,read l/100))t).zipWith b=<0=1|1>0=e/(e+s)\ng e s p ((q,l):t)=l*g e s(p+1)t+(1-l)*g e(s+q)(p-1)t\nmain=interact$show.maximum.s.map words.lines\n"}], "negative_code": [], "src_uid": "81492d3b77bc0674102af17f22bf0664"} {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain =\n do _ <- getLine\n l <- liftM ((++ ['0', '1']) . (map head) . words) getLine\n (print :: Int -> IO ()) $ max 0 $ (\\x -> x - 2) $ fst $ foldl (\\(c, x) y -> if y == '1' then (c + 1, True) else if x then (c + 1, False) else (c, False)) (0, False) l\n return ()\n", "positive_code": [{"source_code": "main :: IO()\nmain = print . solve 0 0 . map read . tail . words =<< getContents\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve _ _ [] = 0\nsolve i _ (0:x) = solve i 0 x\nsolve _ 1 (1:x) = 1 + solve 1 1 x\nsolve i 0 (1:x) = i + 1 + solve 1 1 x\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . calAns . findIndices (== 1). tail . getIntArray\n\ncalAns :: [Int] -> Int\ncalAns [] = 0\ncalAns (x:[]) = 1\ncalAns (x:y:xs) = calAns (y:xs) + min (y - x) 2\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . calAns . findIndices (== 1). tail . getIntArray\n\ncalAns :: [Int] -> Int\ncalAns [] = 0\ncalAns (x:[]) = 1\ncalAns (x:y:xs) = calAns (y:xs) + if y - x >= 2 then 2 else y - x\n"}, {"source_code": "import qualified Data.List as L\ndrop0::[[Int]] -> [[Int]]\ndrop0 [] = []\ndrop0 x = if (head.head) x == 0 then tail x else x\ndrop0'::[[Int]] -> [[Int]]\ndrop0' [] = []\ndrop0' x = if (head.last) x == 0 then init x else x\ntransform :: [[Int]] -> [[Int]]\ntransform = map (\\xs -> if head xs == 0 then [0] else xs)\nmain :: IO()\nmain = do\n _ <- getLine\n numbers <- fmap (map read.words) getLine :: IO[Int]\n print$sum$map length.transform.drop0'.drop0.L.group$numbers\n"}, {"source_code": "import Data.List\nmain=interact$show.max 0.pred.sum.map(succ.length).filter((>0).head).group.map read.tail.words\n"}, {"source_code": "import Data.List (group)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve = max 0 . pred . sum . map (succ . length) . filter ((>0) . head) . group\n"}, {"source_code": "main = getLine >> getLine >>= return . f 0 . words >>= print\n\nf n (\"0\" : as) = f n as\nf n (\"1\" : as) = f (n + c + 2) tail\n where\n (front, tail) = span (== \"1\") as\n c = length front\nf 0 [] = 0 :: Int\nf n [] = n - 1"}, {"source_code": "solve :: [String] -> Int\nsolve x = count_groups (\"0\":x) + max ((sum $ map read x) - 1) 0 where\n\tcount_groups [] = 0\n\tcount_groups [x] = 0\n\tcount_groups (x:t@(y:z)) = if x == \"0\" && y == \"1\" then 1 + count_groups z else count_groups t\n\nmain = interact $ show.solve.words.last.lines"}, {"source_code": "solve :: [String] -> Int\nsolve x = count_groups (\"0\":x) + max ((sum $ map read x) - 1) 0 where\n\tcount_groups [] = 0\n\tcount_groups [x] = 0\n\tcount_groups (x:t@(y:z)) = if x == \"0\" && y == \"1\" then 1 + count_groups z else count_groups t\n\nmain = interact $ show.solve.words.last.lines"}, {"source_code": "pre ('0':xs) = pre xs\npre (' ':xs) = pre xs\npre xs = xs\n\nsolve [] = 0\nsolve (' ':xs) = solve xs\nsolve ['0'] = 0\nsolve ('0':' ':'0':xs) = solve ('0':xs)\nsolve ('0':' ':'1':xs) = 1 + solve ('1':xs)\nsolve ('1':xs) = 1 + solve xs\n\nmain = do\n n <- getLine\n n <- getLine\n print(solve(pre n))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n\nprocess [] n = n\nprocess (s:ss) n | s==1 = process ss (n+1) \n | otherwise= process (dropWhile (==0) ss) (n+1)\nmain= do\t \n\tgetLine \n\ts<- map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]\n\tprint $ process (reverse (dropWhile (==0) (reverse (dropWhile (==0) s)))) 0\n \n\t \n\t "}], "negative_code": [{"source_code": "import qualified Data.List as L\ndrop0::[[Int]] -> [[Int]]\ndrop0 [] = []\ndrop0 x = if (head.head) x == 0 then tail x else x\ndrop0'::[[Int]] -> [[Int]]\ndrop0' [] = []\ndrop0' x = if (head.last) x == 0 then tail x else x\ntransform :: [[Int]] -> [[Int]]\ntransform = map (\\xs -> if head xs == 0 then [0] else xs)\nmain :: IO()\nmain = do\n _ <- getLine\n numbers <- fmap (map length.transform.drop0'.drop0.L.group.map read.words) getLine :: IO[Int]\n print$sum numbers\n"}], "src_uid": "0fbc306d919d7ffc3cb02239cb9c2ab0"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do \n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n putStrLn \"2\"\n putStrLn $ unlines $ map (\\(a, b) -> unwords [show a, show b]) $ solve $ [n,n-1..1]\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [] = error \"Solve called on empty list.\"\nsolve (x:[])\n | x == 2 = []\n | otherwise = error (\"Minimum not reached: \" ++ show x)\nsolve (a:b:xs) = (a, b):(solve $ (quot (a + b + 1) 2):xs)\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\n\nsolve :: Int -> [String]\nsolve 3 = [\"1 3\"]\nsolve 2 = [\"1 2\"]\nsolve n = (show (n - 2) ++ \" \" ++ show n) : solve (n - 1)\n\nsolve' :: Int -> [String]\nsolve' 3 = \"3 1\" : \"2 2\" : []\nsolve' 2 = \"2 1\" : []\nsolve' n = (show (n - 2) ++ \" \" ++ show n) : (show (n - 1) ++ \" \" ++ show (n - 1)) : solve (n - 1)\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] $ \\_ -> do\n n <- pure . read =<< getLine\n putStrLn \"2\"\n mapM_ putStrLn . solve' $ n \n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (read >>> solve >>> showAns)\n >>> concat\n >>> unlines\n where\n showAns (x, ys) = show x : map showII ys\n showII (x, y) = show x ++ \" \" ++ show y\n\nsolve :: Int -> (Int, [(Int, Int)])\nsolve n = (2, ((n - 1, n) :) . reverse $ zip [1 .. n] [3 .. n])\n"}], "negative_code": [], "src_uid": "591372383cf3624f69793c41370022de"} {"source_code": "import Char\nmain = interact solve\nsolve input = output where\n [[a0,b0],[c]] = map words $ lines input\n a = read a0 :: Integer\n b = if b0==\"R\" then 0 else read b0 :: Integer\n output = c1\n c0 = fromBase c a\n c1 = toBase c0 b\nfromBase :: String -> Integer -> Integer\nfromBase x y = fromBase' (map toNumber x) y\nfromBase' :: [Integer] -> Integer -> Integer\nfromBase' [] y = 0\nfromBase' [x] y = x\nfromBase' (x:y:xs) z = fromBase' (x*z+y:xs) z\ntoNumber :: Char -> Integer\ntoNumber x = toInteger $ ord x - if '0'<=x && x<='9' then ord '0' else ord 'A' - 10\ntoBase :: Integer -> Integer -> String\ntoBase x y = if y==0 then roman x else toBase' x y\ntoBase' :: Integer -> Integer -> String\ntoBase' x y\n | x String\nroman x\n | x>=1000 = \"M\" ++(roman (x-1000))\n | x>=900 = \"CM\"++(roman (x-900))\n | x>=500 = \"D\" ++(roman (x-500))\n | x>=400 = \"CD\"++(roman (x-400))\n | x>=100 = \"C\" ++(roman (x-100))\n | x>=90 = \"XC\"++(roman (x-90))\n | x>=50 = \"L\" ++(roman (x-50))\n | x>=40 = \"XL\"++(roman (x-40))\n | x>=10 = \"X\" ++(roman (x-10))\n | x>=9 = \"IX\"++(roman (x-9))\n | x>=5 = \"V\" ++(roman (x-5))\n | x>=4 = \"IV\"++(roman (x-4))\n | x>=1 = \"I\" ++(roman (x-1))\n | otherwise = \"\"\n", "positive_code": [{"source_code": "import Data.Char\nord' = fromIntegral.ord\nchr' = chr.fromIntegral\ntoA::Integer->Integer->[Char]\ntoA a x = reverse $ toA' a x where\n toA' a x = let\n x' = x `mod` a\n x1 = x `div` a \n s | x' < 10 = chr' (x' + ord' '0')\n | x' >= 10 = chr' (x' + ord' 'A' - 10) in\n if x1 > 0 then s:(toA' a x1) else [s]\nfromA::Integer->[Char]->Integer\nfromA a ss = fromA' a 0 ss where \n fromA' a sum (s:ss) | s `elem` ['0'..'9'] = fromA' a (sum * a \n + (ord' s - ord' '0')) ss\n | s `elem` ['A'..'Z'] = fromA' a (sum * a \n + (ord' s - ord' 'A' + 10)) ss\n fromA' a sum [] = sum\ntoRoman x | x > 1000 = replicate (x `div` 1000) 'M' ++ toRoman (x `mod` 1000)\n | x `div` 100 > 0 = (case (x `div` 100) of\n 1 -> \"C\"\n 2 -> \"CC\"\n 3 -> \"CCC\"\n 4 -> \"CD\"\n 5 -> \"D\"\n 6 -> \"DC\"\n 7 -> \"DCC\"\n 8 -> \"DCCC\"\n 9 -> \"CM\") ++ toRoman (x `mod` 100)\n | x `div` 10 > 0 = (case (x `div` 10) of\n 1 -> \"X\"\n 2 -> \"XX\"\n 3 -> \"XXX\"\n 4 -> \"XL\"\n 5 -> \"L\"\n 6 -> \"LX\"\n 7 -> \"LXX\"\n 8 -> \"LXXX\"\n 9 -> \"XC\") ++ toRoman (x `mod` 10)\n | x > 0 = case x of\n 1 -> \"I\"\n 2 -> \"II\"\n 3 -> \"III\"\n 4 -> \"IV\"\n 5 -> \"V\"\n 6 -> \"VI\"\n 7 -> \"VII\"\n 8 -> \"VIII\"\n 9 -> \"IX\"\n | x == 0 = \"\"\n\nmain = do\n [a', b'] <- words `fmap` getLine\n let a = read a'\n x <- fromA a `fmap` getLine\n putStr (if b' == \"R\" then toRoman $ fromIntegral x else toA (read b') x)\n \n"}, {"source_code": "import Data.List\nimport Data.Char\n\ntoBase :: Integer -> Integer -> [Integer]\ntoBase b v = toBase' [] v where\n toBase' a 0 = a\n toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b\n\nfromBase :: Integer -> [Integer] -> Integer\nfromBase b ds = foldl' (\\n k -> n * b + k) 0 ds\n\ntoAlphaDigits :: [Integer] -> [Char]\ntoAlphaDigits = map convert where\n convert n | n < 10 = chr ((fromIntegral n) + ord '0')\n | otherwise = chr ((fromIntegral n) + ord 'A' - 10)\n\nfromAlphaDigits :: [Char] -> [Integer]\nfromAlphaDigits = map convert where\n convert c | isDigit c = toInteger (ord c - ord '0')\n | isUpper c = toInteger (ord c - ord 'A' + 10)\n | isLower c = toInteger (ord c - ord 'a' + 10)\n\nrep x 0 = []\nrep x n = x : rep x (n-1)\n\ntoRoman x\n | x >= 1000 = let (q,r) = x `divMod` 1000\n in rep 'M' q ++ toRoman r\n | x >= 100 = toRomanCent x (x `div` 100)\n | x >= 10 = toRomanDec x (x `div` 10)\n | x > 0 = toRomanUn x\n | otherwise = []\n\ntoRomanCent x q\n | q >= 9 = \"CM\" ++ toRoman (x - 900)\n | q >= 5 = \"D\" ++ toRoman (x - 500)\n | q >= 4 = \"CD\" ++ toRoman (x - 400)\n | otherwise = rep 'C' q ++ toRoman (x - 100*q)\n\ntoRomanDec x q\n | q >= 9 = \"XC\" ++ toRoman (x - 90)\n | q >= 5 = \"L\" ++ toRoman (x - 50)\n | q >= 4 = \"XL\" ++ toRoman (x - 40)\n | otherwise = rep 'X' q ++ toRoman (x - 10*q)\n\ntoRomanUn x\n | x >= 9 = \"IX\"\n | x >= 5 = \"V\" ++ toRoman (x - 5)\n | x >= 4 = \"IV\"\n | otherwise = rep 'I' x\n\nmain = do\n fstLine <- getLine\n let bases = words fstLine\n inBase = read $ head bases\n outBase = if (head.head.tail $ bases) == 'R'\n then Nothing\n else Just $ read $ head.tail $ bases\n -- print bases\n inputStr <- getLine\n let input = fromBase inBase $ fromAlphaDigits inputStr\n putStrLn $ case input of 0 -> \"0\"\n _ -> case outBase of\n Nothing -> toRoman input\n Just base ->\n toAlphaDigits $ toBase base input\n"}], "negative_code": [{"source_code": "import Data.Char\ntoA a x = reverse $ toA' a x where\n toA' a x = let\n x' = x `mod` a\n x1 = x `div` a \n s | x' < 10 = chr (x' + ord '0')\n | x' >= 10 = chr (x' + ord 'A' - 10) in\n if x1 > 0 then s:(toA' a x1) else [s]\nfromA a ss = fromA' a 0 ss where \n fromA' a sum (s:ss) | s `elem` ['0'..'9'] = fromA' a (sum * a + (ord s - ord '0')) ss\n | s `elem` ['A'..'Z'] = fromA' a (sum * a + (ord s - ord 'A' + 10)) ss\n fromA' a sum [] = sum\ntoRoman x | x > 1000 = replicate (x `div` 1000) 'M' ++ toRoman (x `mod` 1000)\n | x `div` 100 > 0 = (case (x `div` 100) of\n 1 -> \"C\"\n 2 -> \"CC\"\n 3 -> \"CCC\"\n 4 -> \"CD\"\n 5 -> \"D\"\n 6 -> \"DC\"\n 7 -> \"DCC\"\n 8 -> \"DCC\"\n 9 -> \"CM\") ++ toRoman (x `mod` 100)\n | x `div` 10 > 0 = (case (x `div` 10) of\n 1 -> \"X\"\n 2 -> \"XX\"\n 3 -> \"XXX\"\n 4 -> \"XL\"\n 5 -> \"L\"\n 6 -> \"LX\"\n 7 -> \"LXX\"\n 8 -> \"LXXX\"\n 9 -> \"XC\") ++ toRoman (x `mod` 10)\n | x > 0 = case x of\n 1 -> \"I\"\n 2 -> \"II\"\n 3 -> \"III\"\n 4 -> \"IV\"\n 5 -> \"V\"\n 6 -> \"VI\"\n 7 -> \"VII\"\n 8 -> \"VIII\"\n 9 -> \"IX\"\n | x == 0 = \"\"\n\nmain = do\n [a', b'] <- words `fmap` getLine\n let a = read a'\n x <- fromA a `fmap` getLine\n putStr (if b' == \"R\" then toRoman x else toA (read b') x)\n \n"}, {"source_code": "import Data.Char\nord' = fromIntegral.ord\nchr' = chr.fromIntegral\ntoA::Integer->Integer->[Char]\ntoA a x = reverse $ toA' a x where\n toA' a x = let\n x' = x `mod` a\n x1 = x `div` a \n s | x' < 10 = chr' (x' + ord' '0')\n | x' >= 10 = chr' (x' + ord' 'A' - 10) in\n if x1 > 0 then s:(toA' a x1) else [s]\nfromA::Integer->[Char]->Integer\nfromA a ss = fromA' a 0 ss where \n fromA' a sum (s:ss) | s `elem` ['0'..'9'] = fromA' a (sum * a \n + (ord' s - ord' '0')) ss\n | s `elem` ['A'..'Z'] = fromA' a (sum * a \n + (ord' s - ord' 'A' + 10)) ss\n fromA' a sum [] = sum\ntoRoman x | x > 1000 = replicate (x `div` 1000) 'M' ++ toRoman (x `mod` 1000)\n | x `div` 100 > 0 = (case (x `div` 100) of\n 1 -> \"C\"\n 2 -> \"CC\"\n 3 -> \"CCC\"\n 4 -> \"CD\"\n 5 -> \"D\"\n 6 -> \"DC\"\n 7 -> \"DCC\"\n 8 -> \"DCC\"\n 9 -> \"CM\") ++ toRoman (x `mod` 100)\n | x `div` 10 > 0 = (case (x `div` 10) of\n 1 -> \"X\"\n 2 -> \"XX\"\n 3 -> \"XXX\"\n 4 -> \"XL\"\n 5 -> \"L\"\n 6 -> \"LX\"\n 7 -> \"LXX\"\n 8 -> \"LXXX\"\n 9 -> \"XC\") ++ toRoman (x `mod` 10)\n | x > 0 = case x of\n 1 -> \"I\"\n 2 -> \"II\"\n 3 -> \"III\"\n 4 -> \"IV\"\n 5 -> \"V\"\n 6 -> \"VI\"\n 7 -> \"VII\"\n 8 -> \"VIII\"\n 9 -> \"IX\"\n | x == 0 = \"\"\n\nmain = do\n [a', b'] <- words `fmap` getLine\n let a = read a'\n x <- fromA a `fmap` getLine\n putStr (if b' == \"R\" then toRoman $ fromIntegral x else toA (read b') x)\n \n"}, {"source_code": "import Data.List\nimport Data.Char\n\ntoBase :: Integer -> Integer -> [Integer]\ntoBase b v = toBase' [] v where\n toBase' a 0 = a\n toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b\n\nfromBase :: Integer -> [Integer] -> Integer\nfromBase b ds = foldl' (\\n k -> n * b + k) 0 ds\n\ntoAlphaDigits :: [Integer] -> [Char]\ntoAlphaDigits = map convert where\n convert n | n < 10 = chr ((fromIntegral n) + ord '0')\n | otherwise = chr ((fromIntegral n) + ord 'A' - 10)\n\nfromAlphaDigits :: [Char] -> [Integer]\nfromAlphaDigits = map convert where\n convert c | isDigit c = toInteger (ord c - ord '0')\n | isUpper c = toInteger (ord c - ord 'A' + 10)\n | isLower c = toInteger (ord c - ord 'a' + 10)\n\nrep x 0 = []\nrep x n = x : rep x (n-1)\n\ntoRoman x\n | x >= 1000 = let (q,r) = x `divMod` 1000\n in rep 'M' q ++ toRoman r\n | x >= 100 = toRomanCent x (x `div` 100)\n | x >= 10 = toRomanDec x (x `div` 10)\n | x > 0 = toRomanUn x\n | otherwise = []\n\ntoRomanCent x q\n | q >= 9 = \"CM\" ++ toRoman (x - 900)\n | q >= 5 = \"D\" ++ toRoman (x - 500)\n | q >= 4 = \"CD\" ++ toRoman (x - 400)\n | otherwise = rep 'C' q ++ toRoman (x - 100*q)\n\ntoRomanDec x q\n | q >= 9 = \"XC\" ++ toRoman (x - 90)\n | q >= 5 = \"L\" ++ toRoman (x - 50)\n | q >= 4 = \"XL\" ++ toRoman (x - 40)\n | otherwise = rep 'X' q ++ toRoman (x - 10*q)\n\ntoRomanUn x\n | x >= 9 = \"IX\"\n | x >= 5 = \"V\" ++ toRoman (x - 5)\n | x >= 4 = \"IV\"\n | otherwise = rep 'I' x\n\nmain = do\n fstLine <- getLine\n let bases = words fstLine\n inBase = read $ head bases\n outBase = if (head.head.tail $ bases) == 'R'\n then Nothing\n else Just $ read $ head.tail $ bases\n -- print bases\n inputStr <- getLine\n let input = fromBase inBase $ fromAlphaDigits inputStr\n putStrLn $ case outBase of Nothing -> toRoman input\n Just 0 -> \"0\"\n Just base -> toAlphaDigits $ toBase base input\n"}, {"source_code": "import Data.List\nimport Data.Char\n\ntoBase :: Integer -> Integer -> [Integer]\ntoBase b v = toBase' [] v where\n toBase' a 0 = a\n toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b\n\nfromBase :: Integer -> [Integer] -> Integer\nfromBase b ds = foldl' (\\n k -> n * b + k) 0 ds\n\ntoAlphaDigits :: [Integer] -> [Char]\ntoAlphaDigits = map convert where\n convert n | n < 10 = chr ((fromIntegral n) + ord '0')\n | otherwise = chr ((fromIntegral n) + ord 'A' - 10)\n\nfromAlphaDigits :: [Char] -> [Integer]\nfromAlphaDigits = map convert where\n convert c | isDigit c = toInteger (ord c - ord '0')\n | isUpper c = toInteger (ord c - ord 'A' + 10)\n | isLower c = toInteger (ord c - ord 'a' + 10)\n\nrep x 0 = []\nrep x n = x : rep x (n-1)\n\ntoRoman x\n | x >= 1000 = let (q,r) = x `divMod` 1000\n in rep 'M' q ++ toRoman r\n | x >= 100 = toRomanCent x (x `div` 100)\n | x >= 10 = toRomanDec x (x `div` 10)\n | x > 0 = toRomanUn x\n | otherwise = []\n\ntoRomanCent x q\n | q >= 9 = \"CM\" ++ toRoman (x - 900)\n | q >= 5 = \"D\" ++ toRoman (x - 500)\n | q >= 4 = \"CD\" ++ toRoman (x - 400)\n | otherwise = rep 'C' q ++ toRoman (x - 100*q)\n\ntoRomanDec x q\n | q >= 9 = \"XC\" ++ toRoman (x - 90)\n | q >= 5 = \"L\" ++ toRoman (x - 50)\n | q >= 4 = \"XL\" ++ toRoman (x - 40)\n | otherwise = rep 'X' q ++ toRoman (x - 10*q)\n\ntoRomanUn x\n | x >= 9 = \"IX\"\n | x >= 5 = \"V\" ++ toRoman (x - 5)\n | x >= 4 = \"IV\"\n | otherwise = rep 'I' x\n\nmain = do\n fstLine <- getLine\n let bases = words fstLine\n inBase = read $ head bases\n outBase = if (head.head.tail $ bases) == 'R'\n then Nothing\n else Just $ read $ head.tail $ bases\n -- print bases\n inputStr <- getLine\n let input = fromBase inBase $ fromAlphaDigits inputStr\n putStrLn $ case outBase of Nothing -> toRoman input\n Just base -> toAlphaDigits $ toBase base input\n"}, {"source_code": "import Data.List\nimport Data.Char\n\ntoBase :: Int -> Int -> [Int]\ntoBase b v = toBase' [] v where\n toBase' a 0 = a\n toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b\n\nfromBase :: Int -> [Int] -> Int\nfromBase b ds = foldl' (\\n k -> n * b + k) 0 ds\n\ntoAlphaDigits :: [Int] -> String\ntoAlphaDigits = map convert where\n convert n | n < 10 = chr (n + ord '0')\n | otherwise = chr (n + ord 'A' - 10)\n\nfromAlphaDigits :: String -> [Int]\nfromAlphaDigits = map convert where\n convert c | isDigit c = ord c - ord '0'\n | isUpper c = ord c - ord 'A' + 10\n | isLower c = ord c - ord 'a' + 10\n\nrep :: Char -> Int -> String\nrep x 0 = []\nrep x n = x : rep x (n-1)\n\ntoRoman :: Int -> String\ntoRoman x\n | x >= 1000 = let (q,r) = x `divMod` 1000\n in rep 'M' q ++ toRoman r\n | x >= 100 = toRomanCent x (x `div` 100)\n | x >= 10 = toRomanDec x (x `div` 10)\n | x > 0 = toRomanUn x\n | otherwise = []\n\ntoRomanCent x q\n | q >= 9 = \"CM\" ++ toRoman (x - 900)\n | q >= 5 = \"D\" ++ toRoman (x - 500)\n | q >= 4 = \"CD\" ++ toRoman (x - 400)\n | otherwise = rep 'C' q ++ toRoman (x - 100*q)\n\ntoRomanDec x q\n | q >= 9 = \"XC\" ++ toRoman (x - 90)\n | q >= 5 = \"L\" ++ toRoman (x - 50)\n | q >= 4 = \"XL\" ++ toRoman (x - 40)\n | otherwise = rep 'X' q ++ toRoman (x - 10*q)\n\ntoRomanUn x\n | x >= 9 = \"IX\"\n | x >= 5 = \"V\" ++ toRoman (x - 5)\n | x >= 4 = \"IV\"\n | otherwise = rep 'I' x\n\nmain = do\n fstLine <- getLine\n let bases = words fstLine\n inBase = read $ head bases\n outBase = if (head.head.tail $ bases) == 'R'\n then Nothing\n else Just $ read $ head.tail $ bases\n -- print bases\n inputStr <- getLine\n let input = fromBase inBase $ fromAlphaDigits inputStr\n putStrLn $ case outBase of Nothing -> toRoman input\n Just base -> toAlphaDigits $ toBase base input\n"}], "src_uid": "c619d699e3e5fb42aea839ef6080c86c"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\tt <- readInt\n\treplicateM t solve\n\nsolve = do\n\tn <- readInt\n\tprint $ ( n + 1 ) `div` 2\n", "positive_code": [{"source_code": "solve :: Integer -> Integer\nsolve n = (n-1) `div` 2 + 1\n\nreadInt :: IO Integer\nreadInt = do\n line <- getLine\n let a = read line :: Integer\n return a\n\nmain :: IO ()\nmain = do\n t <- readInt\n for t where\n for 0 = return ()\n for t = do\n n <- readInt\n putStrLn $ show $ solve n\n for (t-1)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = getLine >>= print . (`div` 2) . succ . read\n"}, {"source_code": "import Control.Monad (forM_, replicateM_)\n\nsol n = if even n then n `div` 2 else n `div` 2 + 1\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n print $ sol n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tprint $ div (x+1) 2 \n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\_ -> do\n n <- readLn :: IO Int\n print $ (n + 1) `div` 2"}, {"source_code": "import Control.Monad\n\nmain :: IO()\nmain =\n do\n x <- read <$> getLine\n replicateM_ x solve\n\nsolve :: IO()\nsolve =\n do\n n <- read <$> getLine :: IO Int\n print ((n-1) `div` 2 + 1)\n"}], "negative_code": [], "src_uid": "ec89860dacb5a11b3a2273d2341b07a1"} {"source_code": "{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List\nimport Data.Int\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [Int] -> Builder\nsolve (n:a) = int64Dec res\n where\n res :: Int64\n res = sum $ map fromIntegral $ scanr1 (\\k acc -> max 0 $ min k (pred acc)) $ take n a\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n", "positive_code": [{"source_code": "main = interact $ show . i . reverse . map read . words . last . lines\n\ni [] = choco 0 []\ni (x:[]) = choco x []\ni (x:xs) = choco x xs\n\nchoco :: Integer -> [Integer] -> Integer\nchoco a [] = a\nchoco a (x:xs)\n | x >= a = a + choco (max (a-1) 0) xs\n | otherwise = a + choco x xs\n"}, {"source_code": "main = interact $ show . choco . reverse . map read . words . last . lines\n\nchoco :: [Integer] -> Integer\nchoco [] = 0\nchoco (a:[]) = a\nchoco (a:x:xs)\n | x >= a = a + choco ((max (a-1) 0):xs)\n | otherwise = a + choco (x:xs)\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\n\nmain = do\n C.getLine\n as <- reverse . map ((read :: String -> Integer ). C.unpack ) . C.words <$> C.getLine\n let zero x = if x < 0 then 0 else x\n print $ sum $ foldl' (\\acc@(h:_) x -> ((if x >= h then zero $ h-1 else x):acc)) [head as] $ tail as"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . fmap read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = sum . scanr1 greedy\n\ngreedy :: Integer -> Integer -> Integer\ngreedy _ 0 = 0\ngreedy l r | l >= r = r - 1\n | otherwise = l\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\n\nmain = do\n C.getLine\n as <- reverse . map ((read :: String -> Int) . C.unpack ) . C.words <$> C.getLine\n let zero x = if x < 0 then 0 else x\n print $ sum $ foldl' (\\acc@(h:_) x -> ((if x >= h then zero $ h-1 else x):acc)) [head as] $ tail as"}], "src_uid": "5993b5bf231fabd3c2af90124c41f118"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport Data.Array\nimport Data.List\nimport Data.Maybe\nimport qualified Data.IntSet as S\nimport qualified Data.IntMap as M\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n s <- poi\n t <- poi\n g <- replicateM m $ liftM2 (,) poi poi\n return $ show $ solve n s t g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n s t (accumArray (flip S.insert) S.empty (1, n) . concatMap (\\(a, b) -> [(a, b), (b, a)]) -> g) | ds <- bfs s g, dt <- bfs t g, Just c <- M.lookup t ds = sum [1 :: Int | (u, v) <- pairs [1..n], S.notMember u (g!v), fromMaybe False $ liftM4 (\\su sv ut vt -> su + vt + 1 >= c && sv + ut + 1 >= c) (M.lookup u ds) (M.lookup v ds) (M.lookup u dt) (M.lookup v dt)]\n\n\nbfs s = go 0 [s] M.empty\n where\n go _ [] m _ = m\n go d us m g | m' <- foldl' (flip (`M.insert` d)) m us = (\\us' -> go (d + 1) us' m' g) $ filter (not . flip M.member m') $ concatMap (S.toList . (g!)) us\n\npairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport Data.Array\nimport Data.List\nimport Data.Maybe\nimport qualified Data.IntMap as M\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n s <- poi\n t <- poi\n g <- replicateM m $ liftM2 (,) poi poi\n return $ show $ solve n m s t g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n m s t (accumArray (flip (:)) [] (1, n) . concatMap (\\(a, b) -> [(a, b), (b, a)]) -> g) | ds <- bfs s g, dt <- bfs t g, Just c <- M.lookup t ds = sum [1 :: Int | (u, v) <- pairs [1..n], fromMaybe False $ liftM4 (\\su sv ut vt -> su + vt + 1 >= c && sv + ut + 1 >= c) (M.lookup u ds) (M.lookup v ds) (M.lookup u dt) (M.lookup v dt)] - m\n\n\nbfs s = go 0 [s] M.empty\n where\n go _ [] m _ = m\n go d us m g | m' <- foldl' (flip (`M.insert` d)) m us = (\\us' -> go (d + 1) us' m' g) $ filter (not . flip M.member m') $ concatMap (g!) us\n\npairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Data.Maybe(fromMaybe)\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = sDist ! g\n in\n do\n l <- [1..n - 1]\n r <- [l + 1..n]\n guard $ ((l, r), 1) `S.notMember` edge\n let route1 = sDist ! l + gDist ! r + 1\n route2 = sDist ! r + gDist ! l + 1\n guard $ min route1 route2 >= originalTime\n return ((l, r), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\ndijkstra n s edge = let connect = foldl' (\\ cMap ((a, b), c) -> insertList a b c cMap) (M.fromList [(x, []) | x <- [1..n]]) $ S.toList edge\n costArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Vertex Cost)\n let reachable = fromMaybe (error \"key error\") $ M.lookup s connect\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n costSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs costArray\n in runSTUArray $ do\n mArray <- thaw costArray\n loop s connect costSet mArray\n return mArray\n\nloop:: Vertex -> M.Map Vertex [(Vertex, Cost)] -> S.Set (Cost, Vertex) -> STUArray s Vertex Cost -> ST s ()\nloop s connect costSet costArray = if S.null costSet then writeArray costArray s 0\n else do\n let (minCost, minVertex) = S.findMin costSet\n reachable = fromMaybe (error \"key error\") $ M.lookup minVertex connect\n newCostSet <- foldM (\\ cSet (v, c) -> do\n let newCost = minCost + c\n oldCost <- readArray costArray v\n if newCost < oldCost then do\n writeArray costArray v newCost\n return $ S.insert (newCost, v) $ S.delete (oldCost, v) cSet\n else return cSet) (S.deleteMin costSet) reachable\n loop s connect newCostSet costArray\n\ninsertList:: Vertex -> Vertex -> Cost -> M.Map Vertex [(Vertex, Cost)] -> M.Map Vertex [(Vertex, Cost)]\ninsertList a b c = M.update (\\ x -> Just $ (a, c):x) b . M.update (\\x -> Just $ (b, c):x) a\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Data.Maybe(fromMaybe)\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = sDist ! g\n in\n do\n l <- [1..n - 1]\n r <- [l + 1..n]\n guard $ ((l, r), 1) `S.notMember` edge\n let route1 = sDist ! l + gDist ! r + 1\n route2 = sDist ! r + gDist ! l + 1\n guard $ min route1 route2 >= originalTime\n return ((l, r), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\ndijkstra n s edge = let connect = foldl' (\\ cMap ((a, b), c) -> insertMap a b c cMap) (M.fromList [(x, S.empty) | x <- [1..n]]) $ S.toList edge\n costArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Vertex Cost)\n let reachable = S.toList . fromMaybe (error \"key error\") $ M.lookup s connect\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n costSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs costArray\n in runSTUArray $ do\n mArray <- thaw costArray\n loop s connect costSet mArray\n return mArray\n\nloop:: Vertex -> M.Map Vertex (S.Set (Vertex, Cost)) -> S.Set (Cost, Vertex) -> STUArray s Vertex Cost -> ST s ()\nloop s connect costSet costArray = if S.null costSet then writeArray costArray s 0\n else do\n let (minCost, minVertex) = S.findMin costSet\n reachable = S.toList $ fromMaybe (error \"key error\") $ M.lookup minVertex connect\n newCostSet <- foldM (\\ cSet (v, c) -> do\n let newCost = minCost + c\n oldCost <- readArray costArray v\n if newCost < oldCost then do\n writeArray costArray v newCost\n return $ S.insert (newCost, v) $ S.delete (oldCost, v) cSet\n else return cSet) (S.deleteMin costSet) reachable\n loop s connect newCostSet costArray\n\ninsertMap:: Vertex -> Vertex -> Cost -> M.Map Vertex (S.Set (Vertex, Cost)) -> M.Map Vertex (S.Set (Vertex, Cost))\ninsertMap a b c = M.update (\\ x -> Just $ S.insert (a, c) x) b . M.update (\\x -> Just $ S.insert (b, c) x) a\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Data.Maybe(fromMaybe)\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = (Vertex, Vertex)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) $ S.fromList roads\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = bfs n s edge\n gDist = bfs n g edge\n originalTime = sDist ! g\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ (start, end) `S.notMember` edge\n let route1 = sDist ! start + gDist ! end + 1\n route2 = sDist ! end + gDist ! start + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return (start, end)\n\nbfs:: Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\nbfs n s edge = let connect = foldl' (\\ cMap (a, b) -> update a b cMap) (M.fromList [(x, S.empty) | x <- [1..n]]) $ S.toList edge\n queue = (s, 0):walk 1 queue connect (S.fromList [s])\n in array (1, n) queue\n\nwalk:: Int -> [(Vertex, Cost)] -> M.Map Vertex (S.Set Vertex) -> S.Set Vertex -> [(Vertex, Cost)]\nwalk 0 _ _ used = []\nwalk n ((v, c):rest) connect used = let reachable = fromMaybe (error \"key error\") $ M.lookup v connect\n unreached = S.toList $ S.filter (`S.notMember` used) reachable\n add = zip unreached [c + 1, c + 1..]\n newUsed = foldl' (flip S.insert) used unreached\n in add ++ walk (n + length add - 1) rest connect newUsed\n\nupdate:: Vertex -> Vertex -> M.Map Vertex (S.Set Vertex) -> M.Map Vertex (S.Set Vertex)\nupdate a b = M.update (\\ x -> Just $ S.insert a x) b . M.update (\\x -> Just $ S.insert b x) a\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1,1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = sDist ! g\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ ((start, end), 1) `S.notMember` edge\n let route1 = sDist ! start + gDist ! end + 1\n route2 = sDist ! end + gDist ! start + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return ((start, end), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\ndijkstra n s edge = let initialArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)\n let reachable = S.toList . omit s $ S.filter (\\ ((a, b), c) -> a == s || b == s) edge\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs initialArray\n initialMap = M.delete s . M.fromList $ assocs initialArray\n in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty\n\nrecursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost\nrecursive s edge costSet costMap distMap\n | S.null costSet = M.insert s 0 distMap\n | otherwise = let (minCost, minVertex) = S.findMin costSet\n newDistMap = M.insert minVertex minCost distMap\n neighbors = S.toList . omit minVertex $ S.filter (\\ ((a, b), c) -> a == minVertex || b == minVertex) edge\n (newCostSet, newCostMap) = foldl' (\\ (cSet, cMap) (a, c) -> case M.lookup a cMap of\n Just oldCost -> if minCost + c < oldCost\n then (S.insert (minCost + c, a) $ S.delete (oldCost, a) cSet, M.update (\\_ -> Just $ minCost + c) a cMap)\n else (cSet, cMap)\n Nothing -> (cSet, cMap))\n (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors\n in recursive s edge newCostSet newCostMap newDistMap\n\nomit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)\nomit x = S.map (\\ ((a, b), c) -> if a == x then (b, c) else (a, c))\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Data.Maybe(fromMaybe)\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = (Vertex, Vertex)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) $ S.fromList roads\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = bfs n s edge\n gDist = bfs n g edge\n originalTime = sDist ! g\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ (start, end) `S.notMember` edge\n let route1 = sDist ! start + gDist ! end + 1\n route2 = sDist ! end + gDist ! start + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return (start, end)\n\nbfs:: Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\nbfs n s edge = let connect = foldl' (\\ cMap (a, b) -> update a b cMap) (M.fromList [(x, S.empty) | x <- [1..n]]) $ S.toList edge\n queue = (s, 0):walk n queue connect (S.fromList [s])\n in array (1, n) queue\n\nwalk:: Int -> [(Vertex, Cost)] -> M.Map Vertex (S.Set Vertex) -> S.Set Vertex -> [(Vertex, Cost)]\nwalk n _ _ used\n | S.size used == n = []\nwalk n ((v, c):rest) connect used = let reachable = fromMaybe (error \"key error\") $ M.lookup v connect\n unreached = S.toList $ S.filter (\\x -> x `S.notMember` used) reachable\n add = zip unreached [c + 1, c + 1..]\n newUsed = foldl' (\\ set x -> S.insert x set) used unreached\n in if null add then walk n rest connect newUsed\n else add ++ walk n rest connect newUsed\n\nupdate:: Vertex -> Vertex -> M.Map Vertex (S.Set Vertex) -> M.Map Vertex (S.Set Vertex)\nupdate a b = M.update (\\ x -> Just $ S.insert a x) b . M.update (\\x -> Just $ S.insert b x) a\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1,1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = sDist ! g\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ ((start, end), 1) `S.notMember` edge\n let route1 = sDist ! start + gDist ! end + 1\n route2 = sDist ! end + gDist ! start + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return ((start, end), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\ndijkstra n s edge = let initialArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)\n let reachable = S.toList . omit s $ S.filter (\\ ((a, b), c) -> a == s || b == s) edge\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs initialArray\n initialMap = M.delete s . M.fromList $ assocs initialArray\n in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty\n\nrecursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost\nrecursive s edge costSet costMap distMap\n | S.null costSet = M.insert s 0 distMap\n | otherwise = let (minCost, minVertex) = S.findMin costSet\n newDistMap = M.insert minVertex minCost distMap\n neighbors = S.toList . omit minVertex $ S.filter (\\ ((a, b), c) -> a == minVertex || b == minVertex) edge\n (newCostSet, newCostMap) = foldl' (\\ (cSet, cMap) (a, c) -> case M.lookup a cMap of\n Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)\n Nothing -> (cSet, cMap))\n (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors\n in recursive s edge newCostSet newCostMap newDistMap\n\nupdate::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)\nupdate a newCost costSet costMap = case M.lookup a costMap of\n Just oldCost -> (S.insert (newCost, a) $ S.delete (oldCost, a) costSet, M.update (\\_ -> Just newCost) a costMap)\n Nothing -> error \"key doesn't exist\"\n\nomit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)\nomit x = S.map (\\ ((a, b), c) -> if a == x then (b, c) else (a, c))\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nbfsDo :: [(Int, Int)] -> Int -> Int -> S.Seq Int\nbfsDo edges s n = bfs edges (S.singleton s) (S.update s 0 $ S.fromList (replicate n (-1)))\n\na !. b = a `S.index` b\n\nbfs :: [(Int, Int)] -> S.Seq Int -> S.Seq Int -> S.Seq Int\nbfs edges q d\n | S.null q = d\n | otherwise = let now = q !. 0\n nowDist = d !. now\n nexts = map snd $ filter (\\(a,b) -> a == now && d !. b == -1) edges in\n bfs edges ((S.drop 1 q) S.>< (S.fromList nexts)) (foldl (\\ad n -> S.update n (nowDist +1) ad) d nexts)\n\nsolve :: [(Int, Int)] -> Int -> Int -> Int -> Int\nsolve edges n s t = dcount - length edges `div` 2\n where sdist = bfsDo edges s n\n tdist = bfsDo edges t n\n st = sdist !. t\n minDist x y = min (sdist !. x + 1 + tdist !. y) (sdist !. y + 1 + tdist !. x)\n dcount = length $ filter (\\(x,y) -> minDist x y >= st) $ [(x,y) | x <- [0..n-1], y <- [x+1..n-1]]\n\nmain :: IO ()\nmain = do\n [n,m,s,t] <- getInts\n edges <- concat <$> replicateM m (getInts >>= (\\[a,b] -> pure [(a-1,b-1),(b-1,a-1)]))\n print $ solve edges n (s-1) (t-1)"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Maybe(fromMaybe)\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = fromMaybe (error \"unreachable\") $ M.lookup g sDist\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ ((start, end), 1) `S.notMember` edge\n let route1 = fromMaybe (error \"unreachable\") (M.lookup start sDist) + fromMaybe (error \"unreachable\") (M.lookup end gDist) + 1\n route2 = fromMaybe (error \"unreachable\") (M.lookup end sDist) + fromMaybe (error \"unreachable\") (M.lookup start gDist) + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return ((start, end), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> M.Map Vertex Cost\ndijkstra n s edge = let initialArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)\n let reachable = S.toList . omit s $ S.filter (\\ ((a, b), c) -> a == s || b == s) edge\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs initialArray\n initialMap = M.fromList $ assocs initialArray\n in recursive s edge initialSet initialMap M.empty\n\nrecursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost\nrecursive s edge costSet costMap distMap\n | S.null costSet = M.insert s 0 distMap\n | otherwise = let (minCost, minVertex) = S.findMin costSet\n newDistMap = M.insert minVertex minCost distMap\n neighbors = S.toList . omit minVertex $ S.filter (\\ ((a, b), c) -> a == minVertex || b == minVertex) edge\n (newCostSet, newCostMap) = foldl' (\\ (cSet, cMap) (a, c) -> case M.lookup a cMap of\n Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)\n Nothing -> (cSet, cMap))\n (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors\n in recursive s edge newCostSet newCostMap newDistMap\n\nupdate::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)\nupdate a c costSet costMap = case M.lookup a costMap of\n Just oldCost -> (S.insert (c, a) $ S.delete (oldCost, a) costSet, M.update (\\_ -> Just c) a costMap)\n Nothing -> error \"key doesn't exist\"\n\nomit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)\nomit x = S.map (\\ ((a, b), c) -> if a == x then (b, c) else (a, c))\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Maybe(fromMaybe)\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = sDist ! g\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ ((start, end), 1) `S.notMember` edge\n let route1 = sDist ! start + gDist ! end + 1\n route2 = sDist ! end + gDist ! start + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return ((start, end), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\ndijkstra n s edge = let initialArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)\n let reachable = S.toList . omit s $ S.filter (\\ ((a, b), c) -> a == s || b == s) edge\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs initialArray\n initialMap = M.fromList $ assocs initialArray\n in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty\n\nrecursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost\nrecursive s edge costSet costMap distMap\n | S.null costSet = M.insert s 0 distMap\n | otherwise = let (minCost, minVertex) = S.findMin costSet\n newDistMap = M.insert minVertex minCost distMap\n neighbors = S.toList . omit minVertex $ S.filter (\\ ((a, b), c) -> a == minVertex || b == minVertex) edge\n (newCostSet, newCostMap) = foldl' (\\ (cSet, cMap) (a, c) -> case M.lookup a cMap of\n Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)\n Nothing -> (cSet, cMap))\n (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors\n in recursive s edge newCostSet newCostMap newDistMap\n\nupdate::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)\nupdate a c costSet costMap = case M.lookup a costMap of\n Just oldCost -> (S.insert (c, a) $ S.delete (oldCost, a) costSet, M.update (\\_ -> Just c) a costMap)\n Nothing -> error \"key doesn't exist\"\n\nomit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)\nomit x = S.map (\\ ((a, b), c) -> if a == x then (b, c) else (a, c))\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\ntype Cost = Int\ntype Vertex = Int\ntype Edge = ((Vertex, Vertex), Cost)\n\nmain = do\n [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine\n roads <- map (tuple . map (read:: String -> Int) . words) . lines <$> getContents\n print . length . possible n (s, t) . S.fromList $ zip roads [1,1..]\n\npossible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]\npossible n (s, g) edge = let sDist = dijkstra n s edge\n gDist = dijkstra n g edge\n originalTime = sDist ! g\n in do\n start <- [1..n - 1]\n end <- [start + 1..n]\n guard $ ((start, end), 1) `S.notMember` edge\n let route1 = sDist ! start + gDist ! end + 1\n route2 = sDist ! end + gDist ! start + 1\n guard $ route1 >= originalTime && route2 >= originalTime\n return ((start, end), 1)\n\ndijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost\ndijkstra n s edge = let initialArray = runSTUArray $ do\n mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)\n let reachable = S.toList . omit s $ S.filter (\\ ((a, b), c) -> a == s || b == s) edge\n forM_ reachable $ uncurry (writeArray mArray)\n return mArray\n initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\\ (a, b) -> (b, a)) $ assocs initialArray\n initialMap = M.delete s . M.fromList $ assocs initialArray\n in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty\n\nrecursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost\nrecursive s edge costSet costMap distMap\n | S.null costSet = M.insert s 0 distMap\n | otherwise = let (minCost, minVertex) = S.findMin costSet\n newDistMap = M.insert minVertex minCost distMap\n neighbors = S.toList . omit minVertex $ S.filter (\\ ((a, b), c) -> a == minVertex || b == minVertex) edge\n (newCostSet, newCostMap) = foldl' (\\ (cSet, cMap) (a, c) -> case M.lookup a cMap of\n Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)\n Nothing -> (cSet, cMap))\n (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors\n in if minCost == (maxBound :: Int) then error \"wrong\" else recursive s edge newCostSet newCostMap newDistMap\n\nupdate::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)\nupdate a newCost costSet costMap = case M.lookup a costMap of\n Just oldCost -> (S.insert (newCost, a) $ S.delete (oldCost, a) costSet, M.update (\\_ -> Just newCost) a costMap)\n Nothing -> error \"key doesn't exist\"\n\nomit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)\nomit x = S.map (\\ ((a, b), c) -> if a == x then (b, c) else (a, c))\n\ntuple::[a] -> (a, a)\ntuple [x, y] = (x, y)\n"}], "src_uid": "bd49960701cc29bcef693808db82366f"} {"source_code": "main :: IO ()\nmain = do\n s <- getLine\n let a = map read $ tail $ words s :: [Integer]\n print $ sum $ zipWith (*) a [1..]\n", "positive_code": [{"source_code": "main = do getLine >>= print . sum . zipWith (*) [1..] . map read . tail . words\n"}, {"source_code": "main :: IO ()\nmain = do\n s <- getLine\n let a = map read $ tail $ words s :: [Integer]\n print $ sum $ map (uncurry (*)) $ zip a [1..]\n"}, {"source_code": "main :: IO ()\nmain = do\n s <- getLine\n let a = map read $ tail $ words s :: [Integer]\n print $ sum $ map (\\x -> fst x * snd x) $ zip a [1..]\n"}, {"source_code": "import System.IO\nmain = do\n s <- getLine\n putStrLn $ show $ sum $ zipWith (*) [1..] $ map read $ tail $ words $ s"}], "negative_code": [{"source_code": "main = do getLine >>= print . sum . map ((^2) . read) . tail . words\n"}], "src_uid": "f9f25190916bf4294f7458140b264cb5"} {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Int\nmain = interact $ unwords . map show . solve . read\nsolve :: Int64 -> [Int64]\nsolve n = sort $ map fun $ divisors $ factor n\n where fun d = n `div` d * (1 + n - d + 1) `div` 2\ndivisors = foldl1 (liftM2 (*)) . map f where\n f (p,f) = take (f+1) $ iterate (*p) 1\nfactor n = go n primes where\n go 1 _ = []\n go n (p:ps) | l > 0 = (p,l) : go (n `div` p^l) ps\n | otherwise = go n ps where\n ts = unfoldr (mfilter ((== 0) . fst) . pure . uncurry (flip (,)) . (`divMod` p)) n\n l = length ts\n go n [] = [(n,1)]\n\nprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007,10009,10037,10039,10061,10067,10069,10079,10091,10093,10099,10103,10111,10133,10139,10141,10151,10159,10163,10169,10177,10181,10193,10211,10223,10243,10247,10253,10259,10267,10271,10273,10289,10301,10303,10313,10321,10331,10333,10337,10343,10357,10369,10391,10399,10427,10429,10433,10453,10457,10459,10463,10477,10487,10499,10501,10513,10529,10531,10559,10567,10589,10597,10601,10607,10613,10627,10631,10639,10651,10657,10663,10667,10687,10691,10709,10711,10723,10729,10733,10739,10753,10771,10781,10789,10799,10831,10837,10847,10853,10859,10861,10867,10883,10889,10891,10903,10909,10937,10939,10949,10957,10973,10979,10987,10993,11003,11027,11047,11057,11059,11069,11071,11083,11087,11093,11113,11117,11119,11131,11149,11159,11161,11171,11173,11177,11197,11213,11239,11243,11251,11257,11261,11273,11279,11287,11299,11311,11317,11321,11329,11351,11353,11369,11383,11393,11399,11411,11423,11437,11443,11447,11467,11471,11483,11489,11491,11497,11503,11519,11527,11549,11551,11579,11587,11593,11597,11617,11621,11633,11657,11677,11681,11689,11699,11701,11717,11719,11731,11743,11777,11779,11783,11789,11801,11807,11813,11821,11827,11831,11833,11839,11863,11867,11887,11897,11903,11909,11923,11927,11933,11939,11941,11953,11959,11969,11971,11981,11987,12007,12011,12037,12041,12043,12049,12071,12073,12097,12101,12107,12109,12113,12119,12143,12149,12157,12161,12163,12197,12203,12211,12227,12239,12241,12251,12253,12263,12269,12277,12281,12289,12301,12323,12329,12343,12347,12373,12377,12379,12391,12401,12409,12413,12421,12433,12437,12451,12457,12473,12479,12487,12491,12497,12503,12511,12517,12527,12539,12541,12547,12553,12569,12577,12583,12589,12601,12611,12613,12619,12637,12641,12647,12653,12659,12671,12689,12697,12703,12713,12721,12739,12743,12757,12763,12781,12791,12799,12809,12821,12823,12829,12841,12853,12889,12893,12899,12907,12911,12917,12919,12923,12941,12953,12959,12967,12973,12979,12983,13001,13003,13007,13009,13033,13037,13043,13049,13063,13093,13099,13103,13109,13121,13127,13147,13151,13159,13163,13171,13177,13183,13187,13217,13219,13229,13241,13249,13259,13267,13291,13297,13309,13313,13327,13331,13337,13339,13367,13381,13397,13399,13411,13417,13421,13441,13451,13457,13463,13469,13477,13487,13499,13513,13523,13537,13553,13567,13577,13591,13597,13613,13619,13627,13633,13649,13669,13679,13681,13687,13691,13693,13697,13709,13711,13721,13723,13729,13751,13757,13759,13763,13781,13789,13799,13807,13829,13831,13841,13859,13873,13877,13879,13883,13901,13903,13907,13913,13921,13931,13933,13963,13967,13997,13999,14009,14011,14029,14033,14051,14057,14071,14081,14083,14087,14107,14143,14149,14153,14159,14173,14177,14197,14207,14221,14243,14249,14251,14281,14293,14303,14321,14323,14327,14341,14347,14369,14387,14389,14401,14407,14411,14419,14423,14431,14437,14447,14449,14461,14479,14489,14503,14519,14533,14537,14543,14549,14551,14557,14561,14563,14591,14593,14621,14627,14629,14633,14639,14653,14657,14669,14683,14699,14713,14717,14723,14731,14737,14741,14747,14753,14759,14767,14771,14779,14783,14797,14813,14821,14827,14831,14843,14851,14867,14869,14879,14887,14891,14897,14923,14929,14939,14947,14951,14957,14969,14983,15013,15017,15031,15053,15061,15073,15077,15083,15091,15101,15107,15121,15131,15137,15139,15149,15161,15173,15187,15193,15199,15217,15227,15233,15241,15259,15263,15269,15271,15277,15287,15289,15299,15307,15313,15319,15329,15331,15349,15359,15361,15373,15377,15383,15391,15401,15413,15427,15439,15443,15451,15461,15467,15473,15493,15497,15511,15527,15541,15551,15559,15569,15581,15583,15601,15607,15619,15629,15641,15643,15647,15649,15661,15667,15671,15679,15683,15727,15731,15733,15737,15739,15749,15761,15767,15773,15787,15791,15797,15803,15809,15817,15823,15859,15877,15881,15887,15889,15901,15907,15913,15919,15923,15937,15959,15971,15973,15991,16001,16007,16033,16057,16061,16063,16067,16069,16073,16087,16091,16097,16103,16111,16127,16139,16141,16183,16187,16189,16193,16217,16223,16229,16231,16249,16253,16267,16273,16301,16319,16333,16339,16349,16361,16363,16369,16381,16411,16417,16421,16427,16433,16447,16451,16453,16477,16481,16487,16493,16519,16529,16547,16553,16561,16567,16573,16603,16607,16619,16631,16633,16649,16651,16657,16661,16673,16691,16693,16699,16703,16729,16741,16747,16759,16763,16787,16811,16823,16829,16831,16843,16871,16879,16883,16889,16901,16903,16921,16927,16931,16937,16943,16963,16979,16981,16987,16993,17011,17021,17027,17029,17033,17041,17047,17053,17077,17093,17099,17107,17117,17123,17137,17159,17167,17183,17189,17191,17203,17207,17209,17231,17239,17257,17291,17293,17299,17317,17321,17327,17333,17341,17351,17359,17377,17383,17387,17389,17393,17401,17417,17419,17431,17443,17449,17467,17471,17477,17483,17489,17491,17497,17509,17519,17539,17551,17569,17573,17579,17581,17597,17599,17609,17623,17627,17657,17659,17669,17681,17683,17707,17713,17729,17737,17747,17749,17761,17783,17789,17791,17807,17827,17837,17839,17851,17863,17881,17891,17903,17909,17911,17921,17923,17929,17939,17957,17959,17971,17977,17981,17987,17989,18013,18041,18043,18047,18049,18059,18061,18077,18089,18097,18119,18121,18127,18131,18133,18143,18149,18169,18181,18191,18199,18211,18217,18223,18229,18233,18251,18253,18257,18269,18287,18289,18301,18307,18311,18313,18329,18341,18353,18367,18371,18379,18397,18401,18413,18427,18433,18439,18443,18451,18457,18461,18481,18493,18503,18517,18521,18523,18539,18541,18553,18583,18587,18593,18617,18637,18661,18671,18679,18691,18701,18713,18719,18731,18743,18749,18757,18773,18787,18793,18797,18803,18839,18859,18869,18899,18911,18913,18917,18919,18947,18959,18973,18979,19001,19009,19013,19031,19037,19051,19069,19073,19079,19081,19087,19121,19139,19141,19157,19163,19181,19183,19207,19211,19213,19219,19231,19237,19249,19259,19267,19273,19289,19301,19309,19319,19333,19373,19379,19381,19387,19391,19403,19417,19421,19423,19427,19429,19433,19441,19447,19457,19463,19469,19471,19477,19483,19489,19501,19507,19531,19541,19543,19553,19559,19571,19577,19583,19597,19603,19609,19661,19681,19687,19697,19699,19709,19717,19727,19739,19751,19753,19759,19763,19777,19793,19801,19813,19819,19841,19843,19853,19861,19867,19889,19891,19913,19919,19927,19937,19949,19961,19963,19973,19979,19991,19993,19997,20011,20021,20023,20029,20047,20051,20063,20071,20089,20101,20107,20113,20117,20123,20129,20143,20147,20149,20161,20173,20177,20183,20201,20219,20231,20233,20249,20261,20269,20287,20297,20323,20327,20333,20341,20347,20353,20357,20359,20369,20389,20393,20399,20407,20411,20431,20441,20443,20477,20479,20483,20507,20509,20521,20533,20543,20549,20551,20563,20593,20599,20611,20627,20639,20641,20663,20681,20693,20707,20717,20719,20731,20743,20747,20749,20753,20759,20771,20773,20789,20807,20809,20849,20857,20873,20879,20887,20897,20899,20903,20921,20929,20939,20947,20959,20963,20981,20983,21001,21011,21013,21017,21019,21023,21031,21059,21061,21067,21089,21101,21107,21121,21139,21143,21149,21157,21163,21169,21179,21187,21191,21193,21211,21221,21227,21247,21269,21277,21283,21313,21317,21319,21323,21341,21347,21377,21379,21383,21391,21397,21401,21407,21419,21433,21467,21481,21487,21491,21493,21499,21503,21517,21521,21523,21529,21557,21559,21563,21569,21577,21587,21589,21599,21601,21611,21613,21617,21647,21649,21661,21673,21683,21701,21713,21727,21737,21739,21751,21757,21767,21773,21787,21799,21803,21817,21821,21839,21841,21851,21859,21863,21871,21881,21893,21911,21929,21937,21943,21961,21977,21991,21997,22003,22013,22027,22031,22037,22039,22051,22063,22067,22073,22079,22091,22093,22109,22111,22123,22129,22133,22147,22153,22157,22159,22171,22189,22193,22229,22247,22259,22271,22273,22277,22279,22283,22291,22303,22307,22343,22349,22367,22369,22381,22391,22397,22409,22433,22441,22447,22453,22469,22481,22483,22501,22511,22531,22541,22543,22549,22567,22571,22573,22613,22619,22621,22637,22639,22643,22651,22669,22679,22691,22697,22699,22709,22717,22721,22727,22739,22741,22751,22769,22777,22783,22787,22807,22811,22817,22853,22859,22861,22871,22877,22901,22907,22921,22937,22943,22961,22963,22973,22993,23003,23011,23017,23021,23027,23029,23039,23041,23053,23057,23059,23063,23071,23081,23087,23099,23117,23131,23143,23159,23167,23173,23189,23197,23201,23203,23209,23227,23251,23269,23279,23291,23293,23297,23311,23321,23327,23333,23339,23357,23369,23371,23399,23417,23431,23447,23459,23473,23497,23509,23531,23537,23539,23549,23557,23561,23563,23567,23581,23593,23599,23603,23609,23623,23627,23629,23633,23663,23669,23671,23677,23687,23689,23719,23741,23743,23747,23753,23761,23767,23773,23789,23801,23813,23819,23827,23831,23833,23857,23869,23873,23879,23887,23893,23899,23909,23911,23917,23929,23957,23971,23977,23981,23993,24001,24007,24019,24023,24029,24043,24049,24061,24071,24077,24083,24091,24097,24103,24107,24109,24113,24121,24133,24137,24151,24169,24179,24181,24197,24203,24223,24229,24239,24247,24251,24281,24317,24329,24337,24359,24371,24373,24379,24391,24407,24413,24419,24421,24439,24443,24469,24473,24481,24499,24509,24517,24527,24533,24547,24551,24571,24593,24611,24623,24631,24659,24671,24677,24683,24691,24697,24709,24733,24749,24763,24767,24781,24793,24799,24809,24821,24841,24847,24851,24859,24877,24889,24907,24917,24919,24923,24943,24953,24967,24971,24977,24979,24989,25013,25031,25033,25037,25057,25073,25087,25097,25111,25117,25121,25127,25147,25153,25163,25169,25171,25183,25189,25219,25229,25237,25243,25247,25253,25261,25301,25303,25307,25309,25321,25339,25343,25349,25357,25367,25373,25391,25409,25411,25423,25439,25447,25453,25457,25463,25469,25471,25523,25537,25541,25561,25577,25579,25583,25589,25601,25603,25609,25621,25633,25639,25643,25657,25667,25673,25679,25693,25703,25717,25733,25741,25747,25759,25763,25771,25793,25799,25801,25819,25841,25847,25849,25867,25873,25889,25903,25913,25919,25931,25933,25939,25943,25951,25969,25981,25997,25999,26003,26017,26021,26029,26041,26053,26083,26099,26107,26111,26113,26119,26141,26153,26161,26171,26177,26183,26189,26203,26209,26227,26237,26249,26251,26261,26263,26267,26293,26297,26309,26317,26321,26339,26347,26357,26371,26387,26393,26399,26407,26417,26423,26431,26437,26449,26459,26479,26489,26497,26501,26513,26539,26557,26561,26573,26591,26597,26627,26633,26641,26647,26669,26681,26683,26687,26693,26699,26701,26711,26713,26717,26723,26729,26731,26737,26759,26777,26783,26801,26813,26821,26833,26839,26849,26861,26863,26879,26881,26891,26893,26903,26921,26927,26947,26951,26953,26959,26981,26987,26993,27011,27017,27031,27043,27059,27061,27067,27073,27077,27091,27103,27107,27109,27127,27143,27179,27191,27197,27211,27239,27241,27253,27259,27271,27277,27281,27283,27299,27329,27337,27361,27367,27397,27407,27409,27427,27431,27437,27449,27457,27479,27481,27487,27509,27527,27529,27539,27541,27551,27581,27583,27611,27617,27631,27647,27653,27673,27689,27691,27697,27701,27733,27737,27739,27743,27749,27751,27763,27767,27773,27779,27791,27793,27799,27803,27809,27817,27823,27827,27847,27851,27883,27893,27901,27917,27919,27941,27943,27947,27953,27961,27967,27983,27997,28001,28019,28027,28031,28051,28057,28069,28081,28087,28097,28099,28109,28111,28123,28151,28163,28181,28183,28201,28211,28219,28229,28277,28279,28283,28289,28297,28307,28309,28319,28349,28351,28387,28393,28403,28409,28411,28429,28433,28439,28447,28463,28477,28493,28499,28513,28517,28537,28541,28547,28549,28559,28571,28573,28579,28591,28597,28603,28607,28619,28621,28627,28631,28643,28649,28657,28661,28663,28669,28687,28697,28703,28711,28723,28729,28751,28753,28759,28771,28789,28793,28807,28813,28817,28837,28843,28859,28867,28871,28879,28901,28909,28921,28927,28933,28949,28961,28979,29009,29017,29021,29023,29027,29033,29059,29063,29077,29101,29123,29129,29131,29137,29147,29153,29167,29173,29179,29191,29201,29207,29209,29221,29231,29243,29251,29269,29287,29297,29303,29311,29327,29333,29339,29347,29363,29383,29387,29389,29399,29401,29411,29423,29429,29437,29443,29453,29473,29483,29501,29527,29531,29537,29567,29569,29573,29581,29587,29599,29611,29629,29633,29641,29663,29669,29671,29683,29717,29723,29741,29753,29759,29761,29789,29803,29819,29833,29837,29851,29863,29867,29873,29879,29881,29917,29921,29927,29947,29959,29983,29989,30011,30013,30029,30047,30059,30071,30089,30091,30097,30103,30109,30113,30119,30133,30137,30139,30161,30169,30181,30187,30197,30203,30211,30223,30241,30253,30259,30269,30271,30293,30307,30313,30319,30323,30341,30347,30367,30389,30391,30403,30427,30431,30449,30467,30469,30491,30493,30497,30509,30517,30529,30539,30553,30557,30559,30577,30593,30631,30637,30643,30649,30661,30671,30677,30689,30697,30703,30707,30713,30727,30757,30763,30773,30781,30803,30809,30817,30829,30839,30841,30851,30853,30859,30869,30871,30881,30893,30911,30931,30937,30941,30949,30971,30977,30983,31013,31019,31033,31039,31051,31063,31069,31079,31081,31091,31121,31123,31139,31147,31151,31153,31159,31177,31181,31183,31189,31193,31219,31223,31231,31237,31247,31249,31253,31259,31267,31271,31277,31307,31319,31321,31327,31333,31337,31357,31379,31387,31391,31393,31397,31469,31477,31481,31489,31511,31513,31517,31531,31541,31543,31547,31567,31573,31583,31601,31607]\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nfactor :: Int -> [Int]\nfactor n = nub $ concatMap (factor' n) [1..m] where\n m = ceiling (sqrt $ fromIntegral n)\n factor' n i = if n `mod` i == 0 then [i, n `div` i] else []\n\n-- Arithmetic sum\nsumSeq n d = n * (2 + (n-1) * d) `div` 2\n\nprocess :: Int -> [Integer]\nprocess n = map (\\f -> sumSeq f (n' `div` f)) factors where\n n' = toInteger n\n factors = map toInteger (sort $ factor n)\n\nmain = do\n n <- getInt\n putStrLn $ unwords $ map show $ process n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Map as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Integer] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nsolve n = map toSum $ concat [factors n, factors2 n]\n where cand n = takeWhile (\\i -> i * i <= n) [1..]\n factors n = filter (\\k -> n `mod` k == 0) $ cand n\n factors2 = map (\\v -> n `div` v) . factors\n toSum k = let v = n `div` k in v * (v - 1) `div` 2 * k + v\n\nmain = do\n [n] <- getIntegers\n printInts $ nub $ sort $ solve n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int64\n putStrLn $ unwords $ map show $ map (\\d -> d + (n * (d-1)) `shiftR` 1)\n $ divisors n\n\n\n{-# INLINE divisors #-}\ndivisors :: (Integral i) => i -> [i]\ndivisors n = sort $ process 1 $ primeDecp n\n where\n process !x ((p,n):ps) = do\n pk <- take (n+1) $ iterate (p*) 1\n process (x*pk) ps\n process !x [] = return x\n\n{-# INLINE primeDecp #-}\nprimeDecp :: (Integral i) => i -> [(i,Int)]\nprimeDecp n = let cons = (:); nil = [] in\n let (expt2,n1) = countExpt n 2\n loop p n rt | n == 1 = nil\n | p > rt = cons (n,1) nil\n | expt > 0 = cons (p,expt) $ loop (p+2) n_ (sqrtInt n_)\n | otherwise = loop (p+2) n rt\n where\n (expt,n_) = countExpt n p\n in (if expt2 > 0 then cons (2,expt2) else id)\n $ loop 3 n1 (sqrtInt n1)\n \n\n\n{-# INLINE countExpt #-}\ncountExpt :: (Integral i) => i -> i -> (Int, i)\ncountExpt !x !base\n = (\\(Just (!j,!q0,!q1,!r1)) -> (j,q0))\n $ find (\\(!j,!q0,!q1,!r1) -> r1 /= 0) divlist\n where\n (!q0,!r0) = x `divMod` base\n divlist = iterate (\\(!j,!q0,!q1,!r1) -> let (q2,r2) = q1 `divMod` base\n in (j+1,q1,q2,r2))\n (0,x,q0,r0)\n\n{-# INLINE sqrtInt #-}\nsqrtInt :: (Integral i) => i -> i\nsqrtInt x = ceiling $ sqrt (fromIntegral x :: Double) \n\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n putStrLn $ unwords $ map show $ map (\\d -> d + (n * (d-1)) `shiftR` 1)\n $ divisors n\n\n\n{-# INLINE divisors #-}\ndivisors :: (Integral i) => i -> [i]\ndivisors n = sort $ process 1 $ primeDecp n\n where\n process !x ((p,n):ps) = do\n pk <- take (n+1) $ iterate (p*) 1\n process (x*pk) ps\n process !x [] = return x\n\n{-# INLINE primeDecp #-}\nprimeDecp :: (Integral i) => i -> [(i,Int)]\nprimeDecp n = let cons = (:); nil = [] in\n let (expt2,n1) = countExpt n 2\n loop p n rt | n == 1 = nil\n | p > rt = cons (n,1) nil\n | expt > 0 = cons (p,expt) $ loop (p+2) n_ (sqrtInt n_)\n | otherwise = loop (p+2) n rt\n where\n (expt,n_) = countExpt n p\n in (if expt2 > 0 then cons (2,expt2) else id)\n $ loop 3 n1 (sqrtInt n1)\n \n\n\n{-# INLINE countExpt #-}\ncountExpt :: (Integral i) => i -> i -> (Int, i)\ncountExpt !x !base\n = (\\(Just (!j,!q0,!q1,!r1)) -> (j,q0))\n $ find (\\(!j,!q0,!q1,!r1) -> r1 /= 0) divlist\n where\n (!q0,!r0) = x `divMod` base\n divlist = iterate (\\(!j,!q0,!q1,!r1) -> let (q2,r2) = q1 `divMod` base\n in (j+1,q1,q2,r2))\n (0,x,q0,r0)\n\n{-# INLINE sqrtInt #-}\nsqrtInt :: (Integral i) => i -> i\nsqrtInt x = floor $ sqrt (fromIntegral x :: Double) \n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Map as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nsolve n = map toSum $ concat [factors n, factors2 n]\n where cand n = takeWhile (\\i -> i * i <= n) [1..]\n factors n = filter (\\k -> n `mod` k == 0) $ cand n\n factors2 = map (\\v -> n `div` v) . factors\n toSum k = let v = n `div` k in v * (v - 1) `div` 2 * k + v\n\nmain = do\n [n] <- getInts\n printInts $ nub $ sort $ solve n"}], "src_uid": "2ae1a4d4f2e58b359c898d1ff38edb9e"} {"source_code": "\nsolve :: [Int] -> [Int]\nsolve [a1,a2,a3,a4,a5] = [a1,a3,a5,a2,a4]\nsolve [a1,a2,a3,a4,a5,a6] = [a1,a4,a2,a5,a3,a6]\nsolve [a1,a2,a3,a4,a5,a6,a7] = [a1,a5,a2,a6,a3,a7,a4]\nsolve (a1:a2:a3:a4:as) = a2:a4:a1:a3: solve as\nsolve _ = []\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readNums\n case solve [1..n] of\n [] -> putStrLn \"-1\"\n ans -> putStrLn $ unwords $ map show ans \n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine", "positive_code": [{"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1 >>> map (read >>> solve >>> map show >>> unwords) >>> unlines\n\nsolve :: Int -> [Int]\nsolve 1 = [1]\nsolve n | n <= 3 = [-1]\nsolve n = [1, 3 .. n-4] ++ four [n-3 .. n] ++ reverse [2, 4 .. n-4]\n where\n four [a,b,c,d] = [b,d,a,c]\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n putStrLn $ (unwords.map show) $ solve n\n\nsolve :: Int -> [Int]\nsolve n\n | n<4 = [-1]\n | otherwise = reverse (take l1 [1,3..]) ++ take l2 (4:2:[6,8..])\n where\n l1 = if even n\n then n `div` 2\n else (n+1) `div` 2\n l2 = n `div` 2\n"}], "negative_code": [{"source_code": "\nsolve :: [Int] -> [Int]\nsolve [a1,a2,a3,a4,a5] = [a1,a3,a5,a3,a4]\nsolve [a1,a2,a3,a4,a5,a6] = [a1,a4,a2,a5,a3,a6]\nsolve [a1,a2,a3,a4,a5,a6,a7] = [a1,a5,a2,a6,a3,a7,a4]\nsolve (a1:a2:a3:a4:as) = a2:a4:a1:a3: solve as\nsolve _ = []\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readNums\n case solve [1..n] of\n [] -> putStrLn \"-1\"\n ans -> putStrLn $ unwords $ map show ans \n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "src_uid": "9b8a5d9a6cfd6b3b5d0839eeece6f777"} {"source_code": "import Data.Array\nimport Data.List\n\nmain=interact $ show . f . lines\nf (nm:field) = sum [ (table1!i - 1) * (table2!j - 1) |\n (i, line) <- zip [1..] field, (j, '*') <- zip [1..] line ]\n where\n [n,m] = map read $ words nm\n table1 = listArray (1, n) [ sum [ 1 | '*' <- line ] | line <- field ]\n table2 = listArray (1, m) [ sum [ 1 | '*' <- line ] | line <- transpose field ]\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n\nmain = do\n\t[n, m] <- fmap (map read . words) getLine\n\ta <- replicateM n getLine\n\tputStrLn $ show $ gao n m a\n\ngao n m a = sum [row!i * col!j | i <- [1 .. n], j <- [1 .. m], mat!(i,j) == '*'] where\n\tcnt l = listArray (1, length l) $ map (toInteger . pred . length . filter (=='*')) $ l\n\trow = cnt a\n\tcol = cnt $ transpose a\n\tmat = listArray ((1,1), (n,m)) $ concat a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Int\nimport Data.List\n\nmain = do\n\t[n, m] <- fmap (map read . words) getLine\n\ta <- replicateM n getLine\n\tputStrLn $ (show::Int64->String) $ gao n m a\n\ngao n m a = sum [row!i * col!j | i <- [1 .. n], j <- [1 .. m], mat!(i,j) == '*'] where\n\tcnt l = listArray (1, length l) $ map (fromIntegral . pred . length . filter (=='*')) $ l\n\trow = cnt a\n\tcol = cnt $ transpose a\n\tmat = listArray ((1,1), (n,m)) $ concat a\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n [h, w] <- ( map read . words ) `liftM` getLine\n board <- replicateM h getLine\n --let (h, w) = (1000, 1000)\n --board = replicate h ( replicate w '*' )\n let rowCount = map (fromIntegral . length . filter (=='*')) board\n colCount = foldl' (\\colCount row -> zipWith (\\c ch -> if ch == '*' then c+1 else c) colCount row) (replicate w 0) board\n rowRes = zipWith (\\row rowCount ->\n ( foldl' (\\acc (ch, colCount) -> acc +\n if ch == '*'\n then (colCount-1) * (rowCount-1)\n else 0\n ) 0 (zip row colCount) )\n ) board rowCount\n res = sum rowRes\n\n --putStrLn $ show rowCount\n --putStrLn $ show colCount\n --putStrLn $ show rowRes\n putStrLn $ show res\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\nimport Data.Int\nimport Debug.Trace\n\nreadI :: String -> Int\nreadI = read \n\nreadL :: String -> [Int]\nreadL = (map read) . words\n\nmain = do\n [n, m] <- getLine >>= return . readL\n ss <- getContents >>= return . (take n) . lines\n print $ solve n m ss\n\nsolve n m ss = parser ss where\n ms = listArray (0, m-1) $ map count (transpose ss)\n mj j = fromIntegral (ms!j - 1)\n \n parser ss = parser' ss 0 where\n \n parser' :: [String] -> Int64 -> Int64\n parser' [] acc = acc\n parser' (s:ss) acc = if n > 0\n then parser' ss (acc + n*(sum $ map mj $ findIndices (=='*') s))\n else parser' ss acc\n where n = fromIntegral (count s - 1)\n\ncount s = length $ filter (=='*') s\n"}, {"source_code": "\nimport Data.List\nimport Data.Int\n\nsolve arr = sum $ zipWith (*) row $ map (sum . zipWith (\\x y -> if y=='*' then x else 0) col) arr\n where\n mapping :: [[Char]] -> [Int64]\n mapping = map ((\\x -> fromIntegral x - 1) . length . filter (=='*'))\n row = mapping arr\n col = mapping $ transpose arr\n\nmain = do\n arr <- fmap (tail.lines) getContents\n print $ solve arr\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Int\n\nsolve arr = sum $ zipWith (*) row $ map (sum . zipWith (\\x y -> if y=='*' then x else 0) col) arr\n where\n mapping = map ((\\x -> fromIntegral x - 1) . length . filter (=='*'))\n row = mapping arr :: [Int64]\n col = mapping $ transpose arr\n\nmain = do\n arr <- fmap (tail . lines) getContents\n print $ solve arr\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n --[h, w] <- ( map read . words ) `liftM` getLine\n --board <- replicateM h getLine\n let (h, w) = (1000, 1000)\n board = replicate h ( replicate w '*' )\n let rowCount = map (fromIntegral . length . filter (=='*')) board\n colCount = foldl' (\\colCount row -> zipWith (\\c ch -> if ch == '*' then c+1 else c) colCount row) (replicate w 0) board\n rowRes = zipWith (\\row rowCount ->\n ( foldl' (\\acc (ch, colCount) -> acc +\n if ch == '*'\n then (colCount-1) * (rowCount-1)\n else 0\n ) 0 (zip row colCount) )\n ) board rowCount\n res = sum rowRes\n\n --putStrLn $ show rowCount\n --putStrLn $ show colCount\n --putStrLn $ show rowRes\n putStrLn $ show res\n"}, {"source_code": "import Data.Array\nimport Data.List\n\nmain=interact $ show . f . lines\nf (nm:field) = sum [ (table1!i - 1) * (table2!j - 1) |\n (i, line) <- zip [1..] field, (j, '*') <- zip [1..] line ]\n where\n [n,m] = map read $ words nm\n table1 = listArray (1, n) $ map (length . filter (=='*')) field\n table2 = listArray (1, m) $ map (length . filter (=='*')) $ transpose field\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\nimport Debug.Trace\n\nreadI :: String -> Int\nreadI = read \n\nreadL :: String -> [Int]\nreadL = (map read) . words\n\nmain = do\n [n, m] <- getLine >>= return . readL\n ss <- getContents >>= return . (take n) . lines\n print $ solve n m ss\n\nsolve n m ss = parser ss where\n ms = listArray (0, m-1) $ map count (transpose ss)\n mj j = (ms!j) - 1\n \n parser ss = parser' ss 0 where\n \n parser' [] acc = acc\n parser' (s:ss) acc = if n > 1\n then parser' ss (acc + (n-1)*(sum $ map mj $ findIndices (=='*') s))\n else parser' ss acc\n where n = count s\n\ncount s = length $ filter (=='*') s\n"}], "src_uid": "d9bbd6ca6cfd4b4cdf6017c1b86abd03"} {"source_code": "import Control.Monad\n\nmain :: IO()\nmain =\n do\n x <- read <$> getLine\n replicateM_ x solve\n\nsolve :: IO()\nsolve =\n do\n [a, b, n, m] <- map read . words <$> getLine :: IO [Integer]\n let c = min a b\n if c >= m && a + b >= n + m\n then\n putStrLn \"Yes\"\n else\n putStrLn \"No\"\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [a, b, n, m] <- map read . words <$> getLine\n putStrLn $ bool \"No\" \"Yes\" $ a + b >= n + m && min a b >= m\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO()\nmain =\n do\n x <- read <$> getLine\n replicateM_ x solve\n\nsolve :: IO()\nsolve =\n do\n [a, b, n, m] <- map read . words <$> getLine :: IO [Integer]\n let c = min a b\n if c >= m && a + b >= n + m\n then\n print \"Yes\"\n else\n print \"No\"\n"}], "src_uid": "0f960d19e576b7421a7c7a7166a884ea"} {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = (Integer, Integer, Integer, Integer)\r\ntype OutType = Integer\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\nsolve :: InType -> OutType\r\nsolve (p,a,b,c) = minimum [go a, go b, go c]\r\n where go x = if p `mod` x == 0\r\n then 0\r\n else x - (p `mod` x)\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = (p,a,b,c)\r\n where [p,a,b,c] = toArr s\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines)\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [p, a, b, c] <- readInts\n let tar = minimum [xi * ceilDiv p xi | xi <- [a, b, c]]\n -- ??? How is this wrong?\n putInt64s [tar - p]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: Num t => SIO [t]\nreadInts = do\n currLine <- readLine\n pure [fromInteger x | Just (x, _) <- P.readInteger <$> P.words currLine]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = nCases $ do\r\n [p, a, b, c] <- line\r\n print $ min (next p a) (min (next p b) $ next p c) - p\r\n \r\nnext p n = n * (p `updiv` n)\r\nupdiv a b = (a + b - 1) `div` b\r\nline = fmap read . words <$> getLine\r\nnCases a = readLn >>= flip replicateM_ a"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[p, a, b, c] <- popIntegers\n return $ bshow (solve p a b c)\n\n\nsolve p a b c = minimum $ map f [a, b, c]\n where\n f x = case p `quotRem` x of\n (_, 0) -> 0\n (q, _) -> (q + 1) * x - p\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [p, a, b, c] <- readInts\n let tar = minimum [xi * ceilDiv p xi | xi <- [a, b, c]]\n putInt64s [tar - p]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: Num t => SIO [t]\nreadInts = do\n currLine <- readLine\n pure [fromIntegral x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [p, a, b, c] <- readInts\n let tar = minimum [xi * ceilDiv p xi | xi <- [a, b, c]]\n putInts [tar - p]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = (Int, Int, Int, Int)\r\ntype OutType = Int\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\nsolve :: InType -> OutType\r\nsolve (p,a,b,c) = minimum [go a, go b, go c]\r\n where go x = if p `mod` x == 0\r\n then 0\r\n else x - (p `mod` x)\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = (p,a,b,c)\r\n where [p,a,b,c] = toArr s\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines)\r\n"}], "src_uid": "293f9b996eee9f76d4bfdeda85685baa"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\nimport Data.Char\nimport Data.Array.Unboxed\nimport Data.Bits\n\ntype Sparse = Array Int (UArray Int Int64)\n\nbitFloor :: Int -> Int\nbitFloor x\n = 1 `shift` (finiteBitSize (undefined :: Int) - countLeadingZeros x - 1)\n\nquery :: Sparse -> Int -> Int -> Int64\nquery st i j = let\n w = j - i\n sw = bitFloor w\n layer = countTrailingZeros sw\n in gcd (st ! layer ! i) (st ! layer ! (j - sw))\n\ntstep :: UArray Int Int64 -> Int -> UArray Int Int64\ntstep arr ss = let\n (p, q) = bounds arr\n in array (p, q - ss) $ do\n i <- [p .. q - ss]\n pure $ (i, gcd (arr ! i) (arr ! (i + ss)))\n\nmkSparse :: UArray Int Int64 -> Sparse\nmkSparse arr = let\n (p, q) = bounds arr\n lastLayer = countTrailingZeros $ bitFloor $ q + 1 - p\n vs = iterate (* 2) 1\n in listArray (0, lastLayer) $ scanl tstep arr $ take lastLayer vs\n\nparseN :: Num t => P.ByteString -> t\nparseN = let\n step x c = x * 10 + fromIntegral (ord c - ord '0')\n in P.foldl' step 0\n\nreadNs :: Num t => SIO [t]\nreadNs = map parseN . P.words <$> readLine\n\nbinS :: (Int -> Bool) -> Int -> Int -> Int\nbinS fun x y = if x == y\n then x\n else let\n z = div (x + y + 1) 2\n in if fun z\n then binS fun x (z-1)\n else binS fun z y\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n aLi <- readNs :: SIO [Int64]\n let\n v = listArray (1, n-1) $ zipWith (\\x y -> abs (x - y)) aLi (tail aLi)\n tv = mkSparse v\n ans = foldl' max 1 $ do\n i <- [1 .. n-1]\n let stop = binS (\\j -> query tv i j == 1) i n\n pure $ stop - i + 1\n putInts [ans]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n ~(out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (foldM_, forM_, replicateM, guard)\nimport Control.Monad.ST\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.Array as A\nimport Data.Array.Base ((!))\nimport Data.Array.ST\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Int\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = show . solve <$> numberOf (fromIntegral <$> integer)\n\ntype ArrayI64 = U.UArray Int Int64\ntype ArrayInt = U.UArray Int Int\n\nlg = 20\nlim = 2 * 10^5 + 5\nlogs :: ArrayInt\nlogs = U.array (1, lim) $ do\n l <- [0 .. lg]\n i <- [2 ^ l .. 2 ^ (l + 1) - 1]\n guard $ i <= lim\n return (i, l)\n\nsolve :: [Int64] -> Int\nsolve [_] = 1\nsolve xs = (1 +) . maximum $ map computeAt [0 .. n - 1]\n where\n n = length xs - 1\n\n computeAt i = min (i + 1) . foldl pick 0 $ reverse [0 .. lg - 1]\n where\n pick len j =\n let l = max 0 $ i - len - 2 ^ j + 1\n g = rangeGCD l i\n in len + (if g == 1 then 0 else 2 ^ j)\n\n -- adjacent differences\n diffs :: ArrayI64\n diffs = U.listArray (0, n - 1) $ map abs $ zipWith (-) xs (tail xs)\n\n -- rangeGCD l r = gcd a[l..r]\n --(j, l') = maximum [(j, l') | j <- [0..lg], let l' = l + 2^j - 1, l' <= r]\n rangeGCD :: Int -> Int -> Int64\n rangeGCD l r =\n let j = logs ! (r - l + 1)\n l' = l + 2 ^ j - 1\n in gcd (sparseGCD ! r ! j) (sparseGCD ! l' ! j)\n\n -- sparseGCD ! i ! j = gcd a[i - 2^j + 1 .. i]\n sparseGCD :: A.Array Int ArrayI64\n sparseGCD = runST $ do\n let nil = U.listArray (0, lg - 1) $ replicate lg 0\n gcds <- newArray (0, n - 1) nil :: ST s (STArray s Int ArrayI64)\n\n forM_ [0 .. n - 1] $ \\i -> do\n cur <- thaw nil :: ST s (STUArray s Int Int64)\n writeArray cur 0 (diffs ! i)\n forM_ [1 .. lg - 1] $ \\j -> do\n a <- readArray cur (j - 1)\n bs <- readArray gcds $ max 0 (i - 2 ^ (j - 1))\n let b = bs ! (j - 1)\n writeArray cur j $ gcd a b\n freeze cur >>= writeArray gcds i\n\n freeze gcds\n\nfoldM_' b ta f = foldM_ f b ta\n\n-------------------------- Template ------------------------------------------\n\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (forM_, replicateM)\r\nimport Control.Monad.ST\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.Array as A\r\nimport Data.Array.Base ((!))\r\nimport Data.Array.ST\r\nimport qualified Data.Array.Unboxed as U\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Int\r\nimport Data.Maybe (fromJust)\r\nimport Debug.Trace (trace)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = show . solve <$> numberOf (fromIntegral <$> integer)\r\n\r\ntype ArrayI64 = U.UArray Int Int64\r\n\r\nsolve :: [Int64] -> Int\r\nsolve [_] = 1\r\nsolve xs = (1+) . maximum $ debug $ map computeAt [0 .. n -1]\r\n where\r\n n = length xs - 1\r\n lg = 3\r\n\r\n computeAt i = min (i + 1) . foldl pick 0 $ reverse [0 .. lg - 1]\r\n where\r\n pick len j =\r\n let l = max 0 $ i - len - 2^j + 1\r\n g = rangeGCD l i\r\n in len + (if g == 1 then 0 else 2^j)\r\n\r\n -- adjacent differences\r\n diffs :: ArrayI64\r\n diffs = debug $ U.listArray (0, n - 1) $ map abs $ zipWith (-) xs (tail xs)\r\n\r\n -- rangeGCD l r = gcd a[l..r]\r\n rangeGCD :: Int -> Int -> Int64\r\n rangeGCD l r =\r\n let (j, l') = maximum [(j, l') | j <- [0..lg], let l' = l + 2^j - 1, l' <= r]\r\n in gcd (sparseGCD ! r ! j) (sparseGCD ! l' ! j)\r\n\r\n -- sparseGCD ! i ! j = gcd a[i - 2^j + 1 .. i]\r\n sparseGCD :: A.Array Int ArrayI64\r\n sparseGCD = debug $ runST $ do\r\n let nil = U.listArray (0, lg - 1) $ replicate lg 0\r\n gcds <- newArray (0, n - 1) nil :: ST s (STArray s Int ArrayI64)\r\n\r\n forM_ [0 .. n - 1] $ \\i -> do\r\n cur <- thaw nil :: ST s (STUArray s Int Int64)\r\n writeArray cur 0 (diffs ! i)\r\n forM_ [1 .. lg - 1] $ \\j -> do\r\n a <- readArray cur (j - 1)\r\n bs <- readArray gcds $ max 0 (i - 2 ^ (j - 1))\r\n let b = bs ! (j - 1)\r\n writeArray cur j $ gcd a b\r\n freeze cur >>= writeArray gcds i\r\n\r\n freeze gcds\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- debug a = trace (show a) a\r\ndebug a = a\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "src_uid": "2f0cdacc14ac81249f30c8c231003a73"} {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Bits (xor)\r\nimport Data.List (foldl')\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine\r\n\r\ncountSegment :: (Int, Int, Int) -> Int -> (Int, Int, Int)\r\ncountSegment (xored, cnt, y) x = (xored', cnt', y) where\r\n (xored', cnt') = if xored `xor` x == y \r\n then (0, cnt + 1) \r\n else (xored `xor` x, cnt)\r\n\r\n \r\n\r\nisPossible :: [Int] -> Bool\r\nisPossible xs = xored == 0 || let (_, cnt, _) = getCnt xs in cnt >= 3 where\r\n xored = foldl' xor 0 xs\r\n getCnt :: [Int] -> (Int, Int, Int)\r\n getCnt = foldl' countSegment (0, 0, xored)\r\n\r\nsolve :: IO ()\r\nsolve = \r\n getLine >> \r\n isPossible <$> readInts >>= \\ans ->\r\n putStrLn $ if ans then \"YES\" else \"NO\" \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve", "positive_code": [{"source_code": "{-# LANGUAGE BlockArguments #-}\r\n\r\nimport Data.Bits\r\nimport Data.List\r\nimport Data.Array\r\nimport Prelude\r\nimport Data.Bool\r\nimport Control.Monad\r\nimport Control.Applicative\r\n\r\nprecalc :: Int -> [Int] -> Int -> Int -> Int\r\nprecalc len x = \\l r -> (arr ! (l - 1)) `xor` (arr ! r)\r\n where\r\n arr = listArray (0, len) $ scanl' xor 0 x\r\n\r\nsolve :: Int -> [Int] -> Bool\r\nsolve len x = any (\\m -> get 1 m == get (m + 1) len || any (\\m' -> get 1 m == get (m + 1) m' && get m m' == get (m' + 1) len) [m..len - 1]) [1..len - 1]\r\n where\r\n get = precalc len x\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ do putStrLn . bool \"NO\" \"YES\" =<< liftA2 solve readLn (fmap read . words <$> getLine)\r\n"}, {"source_code": "import Data.Bits\r\nimport Data.List\r\nimport Data.Array\r\nimport Prelude\r\nimport Data.Bool\r\n\r\nprecalc :: [Int] -> Int -> Int -> Int\r\nprecalc x = \\l r -> (arr ! (l - 1)) `xor` (arr ! r)\r\n where\r\n arr = listArray (0, len) $ scanl' xor 0 x\r\n len = length x\r\n\r\nsolve :: [Int] -> Bool\r\nsolve x = any (\\m -> get 1 m == get (m + 1) len || any (\\m' -> get 1 m == get (m + 1) m' && get m m' == get (m' + 1) len) [m..len - 1]) [1..len - 1]\r\n where\r\n len = length x\r\n get = precalc x\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . fmap (bool \"NO\" \"YES\" . solve . fmap read . words) . evens . tail . lines\r\n\r\nevens :: [a] -> [a]\r\nevens (_:x:xs) = x:evens xs\r\nevens _ = []\r\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Array((!))\r\n\r\nresult2 list = 0 == foldr xor 0 list\r\n\r\n\r\nresult3 [x, y] = False\r\nresult3 [x, y, z] = x == y && x == z\r\n\r\nresult3 list = foldr aux0 False [1..(n-2)] where\r\n\txorList [] = []\r\n\txorList [x] = [x]\r\n\txorList (x:y:xs) = let l = xorList $ y:xs in (xor x $ head l) : l\r\n\txorA = A.listArray (0, n) $ xorList list\r\n\r\n\tn = toInteger $ length list\r\n\r\n\taux0 i b = foldr (aux1 i) b [(i+1)..(n-1)]\r\n\r\n\taux1 i j b = (||) b $ x0 == x1 && x0 == x2 where\r\n\t\tx0 = xor v0 vi\r\n\t\tx1 = xor vi vj\r\n\t\tx2 = vj\r\n\r\n\t\tv0 = xorA ! 0\r\n\t\tvi = xorA ! i\r\n\t\tvj = xorA ! j\r\n\r\n\r\n\r\n\r\n\r\nshowR True = \"YES\"\r\nshowR False = \"NO\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tputStrLn $ showR $ result2 a || result3 a\r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BlockArguments #-}\r\n\r\nimport Data.Bits\r\nimport Data.List\r\nimport Data.Array\r\nimport Prelude\r\nimport Data.Bool\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Data.Maybe\r\n\r\nprecalc :: Int -> [Int] -> Int -> Int -> Int\r\nprecalc len x = \\l r -> (arr ! (l - 1)) `xor` (arr ! r)\r\n where\r\n arr = listArray (0, len) $ scanl' xor 0 x\r\n\r\nsolve :: Int -> [Int] -> Bool\r\nsolve len x = any (\\m -> get 1 m == get (m + 1) len || any (\\m' -> get 1 m == get (m + 1) m' && get m m' == get (m' + 1) len) [m..len - 1]) [1..len - 1]\r\n where\r\n get = precalc len x\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ do putStrLn . bool \"NO\" \"YES\" =<< liftA2 solve readLn readInts\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\r\n"}], "negative_code": [{"source_code": "import Data.Bits\r\nimport Data.List\r\nimport Data.Array\r\nimport Prelude\r\nimport Data.Bool\r\n\r\nprecalc :: [Int] -> Int -> Int -> Int\r\nprecalc x = \\l r -> (arr ! l) `xor` (arr ! r - 1)\r\n where\r\n arr = listArray (0, len) $ scanl' xor 0 x\r\n len = length x\r\n\r\nsolve :: [Int] -> Bool\r\nsolve x = any (\\m -> get 1 m == get m len || any (\\m' -> get 1 m == get m m' && get m m' == get m' len) [m..len]) [1..len]\r\n where\r\n len = length x\r\n get = precalc x\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . fmap (bool \"NO\" \"YES\" . solve . fmap read . words) . evens . tail . lines\r\n\r\nevens :: [a] -> [a]\r\nevens (_:x:xs) = x:evens xs\r\nevens _ = []"}, {"source_code": "import Data.Bits\r\nimport Data.List\r\nimport Data.Array\r\nimport Prelude\r\nimport Data.Bool\r\n\r\nprecalc :: [Int] -> Int -> Int -> Int\r\nprecalc x = \\l r -> (arr ! l) `xor` (arr ! r)\r\n where\r\n arr = listArray (0, len) $ scanl' xor 0 x\r\n len = length x\r\n\r\nsolve :: [Int] -> Bool\r\nsolve x = any (\\m -> get 1 m == get m len || any (\\m' -> get 1 m == get m m' && get m m' == get m' len) [m..len]) [1..len]\r\n where\r\n len = length x\r\n get = precalc x\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . fmap (bool \"NO\" \"YES\" . solve . fmap read . words) . evens . tail . lines\r\n\r\nevens :: [a] -> [a]\r\nevens (_:x:xs) = x:evens xs\r\nevens _ = []\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Bits (xor)\r\nimport Data.List (foldl')\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine\r\n\r\ncountSegment :: (Int, Int, Int) -> Int -> (Int, Int, Int)\r\ncountSegment (xored, cnt, y) x = (xored', cnt', y) where\r\n (xored', cnt') = if xored `xor` x == y \r\n then (xored `xor` x, cnt + 1) \r\n else (0, cnt)\r\n\r\n \r\n\r\nisPossible :: [Int] -> Bool\r\nisPossible xs = xored == 0 || let (_, cnt, _) = getCnt xs in cnt >= 3 where\r\n xored = foldl' xor 0 xs\r\n getCnt :: [Int] -> (Int, Int, Int)\r\n getCnt = foldl' countSegment (0, 0, xored)\r\n\r\nsolve :: IO ()\r\nsolve = \r\n getLine >> \r\n isPossible <$> readInts >>= \\ans ->\r\n putStrLn $ if ans then \"YES\" else \"NO\" \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Bits (xor)\r\nimport Data.List (foldl')\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine\r\n\r\ncountSegment :: (Int, Int, Int) -> Int -> (Int, Int, Int)\r\ncountSegment (xored, cnt, y) x = (xored', cnt', y) where\r\n xored' = xored `xor` x\r\n cnt' = if xored' == y then cnt + 1 else 0\r\n \r\n\r\nisPossible :: [Int] -> Bool\r\nisPossible xs = xored == 0 || let (_, cnt, _) = getCnt xs in cnt >= 3 where\r\n xored = foldl' xor 0 xs\r\n getCnt :: [Int] -> (Int, Int, Int)\r\n getCnt = foldl' countSegment (0, 0, xored)\r\n\r\nsolve :: IO ()\r\nsolve = \r\n getLine >> \r\n isPossible <$> readInts >>= \\ans ->\r\n putStrLn $ if ans then \"YES\" else \"NO\" \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}], "src_uid": "4004c77b77076bf450cbe751e025a71f"} {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n inv :: Char -> Char\n inv 'L' = 'R'\n inv 'R' = 'L'\n inv 'U' = 'D'\n inv 'D' = 'U'\n inv 'Q' = 'Q'\n\n separation :: Char -> Char -> String -> Int -> Int\n separation _ _ [] i = i\n separation 'Q' 'Q' (x:xs) i\n | x == 'U' = separation 'Q' 'U' xs i\n | x == 'D' = separation 'Q' 'D' xs i\n | x == 'R' = separation 'R' 'Q' xs i\n | x == 'L' = separation 'L' 'Q' xs i\n separation 'Q' u (x:xs) i\n | x == 'R' = separation 'R' u xs i\n | x == 'L' = separation 'L' u xs i\n | x == inv u = separation 'Q' x xs (i + 1)\n | otherwise = separation 'Q' u xs i\n separation r 'Q' (x:xs) i\n | x == 'U' = separation r 'U' xs i\n | x == 'D' = separation r 'D' xs i\n | x == inv r = separation x 'Q' xs (i + 1)\n | otherwise = separation r 'Q' xs i\n separation r u (x:xs) i\n | x == inv r = separation x 'Q' xs (i + 1)\n | x == inv u = separation 'Q' x xs (i + 1)\n | otherwise = separation r u xs i\n\n main :: IO()\n main = do\n i <- getLine >>= return . readInt\n moves <- getLine\n putStrLn $ show $ separation 'Q' 'Q' moves 1\n", "positive_code": [{"source_code": "import Data.List( nub)\nmain = do\n n_ <- readLn::IO Int\n direcs_ <- getLine\n let proc (d:[]) stop\n\t | d `elem` stop = 1\n\t | otherwise\t = 0\n\tproc (d1:d2:ds) stop\n\t | d1 `elem` stop = 1+(proc (d2:ds) $ nub $ (opp d1):[])\n\t | otherwise\t = proc (d2:ds) $ nub $ (opp d1):stop\n\topp 'L' = 'R'\n\topp 'R' = 'L'\n\topp 'D' = 'U'\n\topp 'U' = 'D'\n print $ (proc direcs_ [])+1\n"}], "negative_code": [], "src_uid": "b1c7ca90ce9a67605fa058d4fd38c2f2"} {"source_code": "main = do\n dummy <- getLine\n a <- fmap (fmap read . words) getLine\n let b = scanl (+) 0 a\n alice = bsearch b 0 $ length a\n bob = length a - alice\n putStrLn $ show alice ++ \" \" ++ show bob\n where bsearch b l r\n | l >= r = l\n | otherwise = let m = (l+r) `div` 2\n in if b!!m <= last b-b!!(m+1) then bsearch b (m+1) r else bsearch b l m", "positive_code": [{"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe (fromJust)\nimport Data.Functor ((<&>))\n\nmain :: IO ()\nmain = BS.getContents <&> solve . ints >>= putStrLn\n\nints :: BS.ByteString -> [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words\n\nsolve :: [Int] -> String\nsolve (n:xs) = show x <> \" \" <> show y\n where\n greedy a b (x, y)\n | null a || null b || x + y == n = (x, y)\n | head a <= head b = greedy (tail a) b (x + 1, y)\n | otherwise = greedy a (tail b) (x, y + 1)\n (x, y) = greedy (scanl1 (+) xs) (scanl1 (+) (reverse xs)) (0, 0)"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nmodule Main where\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve input = show x <> \" \" <> show y\n where\n n:xs = map (read @Int) $ words input\n greedy a b (x, y)\n | null a || null b || x + y == n = (x, y)\n | head a <= head b = greedy (tail a) b (x + 1, y)\n | otherwise = greedy a (tail b) (x, y + 1)\n (x, y) = greedy (scanl1 (+) xs) (scanl1 (+) (reverse xs)) (0, 0)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsolve 0 0 (gotA, remA) (gotB, remB) tot\n | gotA + gotB <= tot - 2 = solve (head remA) (head remB) (gotA + 1, tail remA) (gotB + 1, tail remB) tot\n | gotA + gotB == tot - 1 = (gotA + 1, gotB)\n | otherwise = (gotA, gotB)\n\nsolve tA 0 (stateA@(gotA, remA)) (gotB, remB) tot\n | gotA + gotB <= tot - 1 = solve tA (head remB) stateA (gotB + 1, tail remB) tot\n | otherwise = (gotA, gotB) \n\nsolve 0 tB (gotA, remA) (stateB@(gotB, remB)) tot\n | gotA + gotB <= tot - 1 = solve (head remA) tB (gotA + 1, tail remA) stateB tot\n | otherwise = (gotA, gotB) \n\nsolve tA tB stateA stateB tot\n | tA > tB = solve (tA - tB) 0 stateA stateB tot\n | otherwise = solve 0 (tB - tA) stateA stateB tot\n\nmain = \n do all <- BS.getContents\n let Just (tot, r1) = readInt all\n let (ls, _) = readMany readInt r1\n let (totA, totB) = solve 0 0 (0, ls) (0, reverse ls) tot\n putStrLn (show totA ++ \" \" ++ show totB)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nreadInt' :: B.ByteString -> Int\nreadInt' s = case B.readInt s of Just (n, _) -> n\nsolve :: [Int] -> (Int, Int)\nsolve (n:xs) = go alice bob (0, 0)\n where alice = scanl1 (+) xs\n bob = scanl1 (+) (reverse xs)\n go [] _ r = r \n go _ [] r = r\n go a@(x:xs) b@(y:ys) (p, q)\n | p + q == n = (p, q)\n | otherwise = case compare x y of\n GT -> go a ys (p, q + 1)\n _ -> go xs b (p + 1, q)\nmain = putStrLn . (\\(x, y) -> show x ++ \" \" ++ show y) . solve . map readInt' . B.words =<< B.getContents"}, {"source_code": "import Control.Applicative\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ps <- map read . words <$> getLine\n let (alice, chokudai) = calc n ps\n printf \"%d %d\\n\" alice chokudai\n\ncalc :: Int -> [Int] -> (Int, Int)\ncalc n ps = (cnt, n - cnt)\n where\n total = sum ps\n half = ceiling $ fromIntegral total / 2\n cnt = cnt' ps 0 0\n cnt' (x:xs) time c\n | eatAliceTime < half = cnt' xs eatAliceTime (c + 1)\n | time <= eatChokudaiTime = c + 1\n | otherwise = c\n where\n eatAliceTime = x + time\n eatChokudaiTime = total - x - time\n"}, {"source_code": "main = do\n\tdummy <- getLine\n\tline <- getLine\n\tputStrLn (let t = map read $ words line; a = gao t; b = length t - a in show a ++ \" \" ++ show b)\n\ngao a = gao' 0 (length a) where\n\tb = 0: scanl1 (+) a\n\ts = last b\n\tgao' l r\n\t\t| l < r\t\t= let m = (l + r) `div` 2 in if b!!m <= s - b!!(m+1) then gao' (m + 1) r else gao' l m\n\t\t| otherwise\t= r\n"}, {"source_code": "\nmain = do\n\tdummy <- getLine\n\tline <- getLine\n\tputStrLn (let t = map read $ words line; a = gao t; b = length t - a in show a ++ \" \" ++ show b)\n\ngao a = gao' 0 (length a) where\n\tb = 0: scanl1 (+) a\n\ts = last b\n\tgao' l r\n\t\t| l < r\t\t= let m = (l + r) `div` 2 in if b!!m <= s - b!!(m+1) then gao' (m + 1) r else gao' l m\n\t\t| otherwise\t= r"}, {"source_code": "main = do\n dummy <- getLine\n line <- getLine\n putStrLn (let t = map read $ words line; a = gao t; b = length t - a in show a ++ \" \" ++ show b)\n\ngao a = gao' 0 (length a) where\n b = 0: scanl1 (+) a\n s = last b\n gao' l r\n | l < r = let m = (l + r) `div` 2 in if b!!m <= s - b!!(m+1) then gao' (m + 1) r else gao' l m\n | otherwise = r\n"}, {"source_code": "\nimport Monad (liftM)\n\nsolve :: [Int] -> (Int, Int)\nsolve [x] = (1,0)\nsolve xs = solve' 0 0 xs (reverse xs)\n where\n n = length xs\n solve' a b (x:xs) (y:ys)\n | a + b > n = error \"a + b > n\"\n | a + b == n = (a, b)\n | x > y = solve' a (b+1) ((x-y):xs) ys\n | x <= y = solve' (a+1) b xs ((y-x):ys)\n\nmain :: IO ()\nmain = do\n getLine\n xs <- liftM (map read . words) getLine\n let (a, b) = solve xs\n putStrLn $ concat [show a, \" \", show b]\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn\n x <- getLine\n showSolve n x\n\n\nshowSolve :: Int -> String -> IO()\nshowSolve n x =\n let x1 = solve x\n x2 = n - x1\n in putStrLn ((show x1) ++ \" \" ++ (show x2))\n\n\nsolve :: String -> Int\nsolve x = \n let c = map read (words x)\n ct = mapAccumL (\\x y -> (x+y, x+y)) 0 c\n avt = (fst ct) `div` 2\n ct2 = filter (<= avt) (snd ct)\n avt2 = if (null ct2) then 0 else (last ct2)\n p1 = length (ct2)\n p2 = if ((fst ct) - ((snd ct) !! p1)) >= avt2 then p1 + 1 else p1\n in p2"}, {"source_code": "import Data.Sequence\nimport Prelude hiding (null)\n\ntype Chocos = Seq Int\n\ndata P = P Int Int\n\nsolve :: (P, P) -> Chocos -> (P, P)\nsolve p@(P anum aeating, P bnum beating) cs\n | null cs = p\n | aeating <= beating =\n let (aeating' :< cs') = viewl cs\n in solve (P (anum + 1) aeating', P bnum (beating - aeating)) cs'\n | aeating > beating =\n let (cs' :> beating') = viewr cs\n in solve (P anum (aeating - beating), P (bnum + 1) beating') cs'\n\nmain = do\n getLine -- n\n cs <- fmap (fromList . map read . words) getLine\n let (P anum _, P bnum _) = solve (P 0 0, P 0 0) cs\n putStrLn $ show anum ++ \" \" ++ show bnum\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Text.Printf\n\ntype Time = Int\ntype Bars = Int\ntype State = (Seq.Seq Time, (Time, Bars), (Time, Bars))\n\neatThemAll' :: State -> State\neatThemAll' state@(s, alice@(t1, b1), bob@(t2, b2))\n | Seq.null s = state\n | t1 <= t2 = let t Seq.:< s' = Seq.viewl s in\n eatThemAll' (s', (t1 + t, b1 + 1), bob)\n | otherwise = let s' Seq.:> t = Seq.viewr s in\n eatThemAll' (s', alice, (t2 + t, b2 + 1))\n\neatThemAll :: [Time] -> (Bars, Bars)\neatThemAll = do\n s <- Seq.fromList\n let (_, (_, b1), (_, b2)) = eatThemAll' (s, (0, 0), (0, 0))\n return (b1, b2)\n \nsolve :: [String] -> [String]\nsolve = fmap return $ do\n ts <- map read . words . head . drop 1\n let (b1, b2) = eatThemAll ts\n return $ printf \"%d %d\" b1 b2\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "import Data.List\nmain = do\n \u0432\u0441\u0435\u0433\u043e\u041f\u043b\u0438\u0442\u043e\u043a <- readIO =<< getLine\n \u0448\u043e\u043a\u043e\u043b\u0430\u0434\u043a\u0438 <- (map read . words) `fmap` getLine\n let \u0432\u0440\u0435\u043c\u044f\u0411\u043e\u0431 = tail . reverse . scanl (+) 0 . reverse\n \u0432\u0440\u0435\u043c\u044f\u0410\u043b\u0438\u0441\u0430 = scanl (+) 0\n \u0441\u044a\u0435\u043b\u0430\u0410\u043b\u0438\u0441\u0430 = length $ takeWhile (\\(\u0430\u043b, \u0431) -> \u0430\u043b <= \u0431) $ zip (\u0432\u0440\u0435\u043c\u044f\u0410\u043b\u0438\u0441\u0430 \u0448\u043e\u043a\u043e\u043b\u0430\u0434\u043a\u0438)\n (\u0432\u0440\u0435\u043c\u044f\u0411\u043e\u0431 \u0448\u043e\u043a\u043e\u043b\u0430\u0434\u043a\u0438)\n putStrLn $ unwords $ map show [\u0441\u044a\u0435\u043b\u0430\u0410\u043b\u0438\u0441\u0430, \u0432\u0441\u0435\u0433\u043e\u041f\u043b\u0438\u0442\u043e\u043a - \u0441\u044a\u0435\u043b\u0430\u0410\u043b\u0438\u0441\u0430]\n"}, {"source_code": "import Data.List\nmain = do\n \u0432\u0441\u0435\u0433\u043e\u041f\u043b\u0438\u0442\u043e\u043a <- readIO =<< getLine\n \u0448\u043e\u043a\u043e\u043b\u0430\u0434\u043a\u0438 <- (map read . words) `fmap` getLine\n let \u0432\u0440\u0435\u043c\u044f\u0411\u043e\u0431 = tail . reverse . scanl (+) 0 . reverse\n \u0432\u0440\u0435\u043c\u044f\u0410\u043b\u0438\u0441\u0430 = scanl (+) 0\n \u0441\u044a\u0435\u043b\u0430\u0410\u043b\u0438\u0441\u0430 = length $ takeWhile id $ zipWith (<=) (\u0432\u0440\u0435\u043c\u044f\u0410\u043b\u0438\u0441\u0430 \u0448\u043e\u043a\u043e\u043b\u0430\u0434\u043a\u0438)\n (\u0432\u0440\u0435\u043c\u044f\u0411\u043e\u0431 \u0448\u043e\u043a\u043e\u043b\u0430\u0434\u043a\u0438)\n putStrLn $ unwords $ map show [\u0441\u044a\u0435\u043b\u0430\u0410\u043b\u0438\u0441\u0430, \u0432\u0441\u0435\u0433\u043e\u041f\u043b\u0438\u0442\u043e\u043a - \u0441\u044a\u0435\u043b\u0430\u0410\u043b\u0438\u0441\u0430]\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n n <- readLn\n x <- getLine\n showSolve n x\n\n\nshowSolve :: Int -> String -> IO()\nshowSolve n x =\n let x1 = solve x\n x2 = n - x1\n in putStrLn ((show x1) ++ \" \" ++ (show x2))\n\n\nsolve :: String -> Int\nsolve x = \n let c = map read (words x)\n ct = mapAccumL (\\x y -> (x+y, x+y)) 0 c\n avt = (fst ct) `div` 2\n p1 = length (filter (<= avt) (snd ct))\n p2 = if ((fst ct) - ((snd ct) !! p1)) >= avt then p1 + 1 else p1\n in p2"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn\n x <- getLine\n showSolve n x\n\n\nshowSolve :: Int -> String -> IO()\nshowSolve n x =\n let x1 = solve x\n x2 = n - x1\n in putStrLn ((show x1) ++ \" \" ++ (show x2))\n\n\nsolve :: String -> Int\nsolve x = \n let c = map read (words x)\n ct = mapAccumL (\\x y -> (x+y, x+y)) 0 c\n avt = (fst ct) `div` 2\n in length (filter (<= avt) (snd ct))"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn\n x <- getLine\n showSolve n x\n\n\nshowSolve :: Int -> String -> IO()\nshowSolve n x =\n let x1 = if (n > 1) then solve x else 1\n x2 = n - x1\n in putStrLn ((show x1) ++ \" \" ++ (show x2))\n\n\nsolve :: String -> Int\nsolve x = \n let c = map read (words x)\n ct = mapAccumL (\\x y -> (x+y, x+y)) 0 c\n avt = (fst ct) `div` 2\n in length (filter (<= avt) (snd ct))"}, {"source_code": "main = do\n dummy <- getLine\n a <- fmap (fmap read . words) getLine\n let b = scanl (+) 0 a\n alice = bsearch b 0 $ length a\n bob = length a - alice\n print $ show alice ++ \" \" ++ show bob\n where bsearch b l r\n | l >= r = l\n | otherwise = let m = (l+r) `div` 2\n in if b!!m <= last b-b!!(m+1) then bsearch b (m+1) r else bsearch b l m"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsolve 0 0 (gotA, remA) (gotB, remB) tot\n | gotA + gotB <= tot - 2 = solve (head remA) (head remB) (gotA + 1, tail remA) (gotB + 1, tail remB) tot\n | gotA + gotB == tot - 1 = (gotA + 1, gotB)\n | otherwise = (gotA, gotB)\n\nsolve tA 0 (stateA@(gotA, remA)) (gotB, remB) tot\n | gotA + gotB <= tot - 1 = solve tA (head remB) stateA (gotB + 1, tail remB) tot\n | otherwise = (gotA, gotB) \n\nsolve 0 tB (gotA, remA) (stateB@(gotB, remB)) tot\n | gotA + gotB <= tot - 1 = solve (head remA) tB (gotA + 1, tail remA) stateB tot\n | otherwise = (gotA, gotB) \n\nsolve tA tB stateA stateB tot\n | tA > tB = solve (tA - tB) 0 stateA stateB tot\n | otherwise = solve 0 (tA - tB) stateA stateB tot\n\nmain = \n do all <- BS.getContents\n let Just (tot, r1) = readInt all\n let (ls, _) = readMany readInt r1\n let (totA, totB) = solve 0 0 (0, ls) (0, reverse ls) tot\n putStrLn (show totA ++ \" \" ++ show totB)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsolve 0 0 (stateA@(eatenA, remA)) (stateB@(eatenB, remB)) tot\n | eatenA + 1 + eatenB + 1 < tot - 1 = solve (head remA) (head remB) (eatenA + 1, tail remA) (eatenB + 1, tail remB) tot\n | eatenA + 1 + eatenB + 1 < tot = (eatenA + 2, eatenB + 1)\n | otherwise = (eatenA + 1, eatenB + 1)\nsolve tA 0 (stateA@(eatenA, remA)) (eatenB, remB) tot\n | eatenA + eatenB + 1 < tot = solve tA (head remB) stateA (eatenB + 1, tail remB) tot\n | otherwise = (eatenA, eatenB + 1) \nsolve 0 tB (eatenA, remA) (stateB@(eatenB, remB)) tot\n | eatenA + 1 + eatenB < tot = solve (head remA) tB (eatenA + 1, tail remA) stateB tot\n | otherwise = (eatenA + 1, eatenB) \nsolve tA tB stateA stateB tot\n | tA > tB = solve (tA - tB) 0 stateA stateB tot\n | tA < tB = solve 0 (tA - tB) stateA stateB tot\n\nmain = \n do all <- BS.getContents\n let Just (tot, r1) = readInt all\n let (ls, _) = readMany readInt r1\n let (totA, totB) = solve 0 0 (0, ls) (0, reverse ls) tot\n putStrLn (show totA ++ \" \" ++ show totB)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Control.Applicative\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ps <- map read . words <$> getLine\n let (alice, chokudai) = calc n ps\n printf \"%d %d\\n\" alice chokudai\n\ncalc :: Int -> [Int] -> (Int, Int)\ncalc n ps = (cnt, n - cnt)\n where\n total = sum ps\n half = total `div` 2\n cnt = cnt' ps 0 0\n cnt' (x:xs) time c\n | eatAliceTime < half = cnt' xs eatAliceTime (c + 1)\n | time <= eatChokudaiTime = c + 1\n | otherwise = c\n where\n eatAliceTime = x + time\n eatChokudaiTime = total - x - time\n"}], "src_uid": "8f0172f742b058f5905c0a02d79000dc"} {"source_code": "import Data.Bits ((.|.))\nimport Data.List (foldl')\n\nmain :: IO ()\nmain = interact $ output . map solve . input\n\ninput :: String -> [[Integer]]\ninput = chunks . drop 1 . lines\n where\n chunks [] = []\n chunks (_:nums:ls) = let integers = map read $ words nums\n in integers : chunks ls\n\noutput :: [Integer] -> String\noutput = unlines . map show\n\nsolve :: [Integer] -> Integer\nsolve = foldl' (.|.) 0\n", "positive_code": [{"source_code": "-- problem: https://codeforces.com/contest/1635/problem/A\n-- origin: https://codeforces.com/contest/1635/submission/147037193\n\nimport Control.Monad.State (State, evalState, replicateM, state)\nimport Data.Bifunctor (first)\nimport Data.Bits (Bits ((.|.)))\nimport Data.Char (isDigit, isSpace)\n\ngetInt :: State [Char] Int\ngetInt = state (first (\\x -> read x :: Int) . span isDigit . dropWhile isSpace)\n\nmainFunc :: State [Char] [Char]\nmainFunc = do\n t <- getInt\n fmap mconcat $\n replicateM t $ do\n n <- getInt\n a <- replicateM n getInt\n let ans = foldl (.|.) 0 a in pure $ show ans ++ \"\\n\"\n\nmain :: IO ()\nmain = do\n inp <- getContents\n putStr $ evalState mainFunc inp"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Bits\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n pure $ putInts [foldl (.|.) 0 a]\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ntst = P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState solve inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\nimport Data.Bits ( Bits((.|.)) )\n\nsolve = foldr1 (.|.)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n print $ solve $ reverse (sort arr)\n"}, {"source_code": "import Data.Bits\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = [Int]\r\ntype OutType = Int\r\n\r\nsolve :: InType -> OutType\r\nsolve = foldr (.|.) 0\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"unknown input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\nimport Data.Bits\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n pure $ putInts [foldl' (.|.) 0 a]\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "7fca54a73076ddfeb30b921b9e341f26"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Foreign.C.String\n\n#if __GLASGOW_HASKELL__ < 706\nimport Data.IORef\n#else\nimport Data.IORef hiding (modifyIORef')\n#endif\n\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_double :: CString -> Double -> IO ()\n\nmain = do\n n <- readLn\n qs <- map readInt.B.words <$> B.getContents\n segtree@(Node _ _ aref bref _ _) <- mkSegTree 0 n 0\n fmt <- newCString \"%f\\n\"\n\n let !len = fromIntegral $ n+1\n\n let go !cnt (1:a:x:rest) = do\n updateRange 0 (a-1) (fromIntegral x) segtree\n a <- readIORef aref\n b <- readIORef bref\n c_printf_double fmt $ fromIntegral (a*len+b) / fromIntegral cnt\n go cnt rest\n go !cnt (2:k:rest) = do\n updateKey cnt (fromIntegral k) segtree\n a <- readIORef aref\n b <- readIORef bref\n c_printf_double fmt $ fromIntegral (a*len+b) / fromIntegral (cnt+1)\n go (cnt+1) rest\n go !cnt (3:rest) = do\n x <- queryKey (cnt-1) segtree\n updateKey (cnt-1) (fromIntegral $ -x) segtree\n a <- readIORef aref\n b <- readIORef bref\n c_printf_double fmt $ fromIntegral (a*len+b) / fromIntegral (cnt-1)\n go (cnt-1) rest\n go _ _ = return ()\n go 1 qs\n\ndata SegTree = Node !Int !Int !(IORef Int64) !(IORef Int64) !SegTree !SegTree\n | Leaf !Int !(IORef Int64)\n\nmkSegTree :: Int -> Int -> Int64 -> IO SegTree\nmkSegTree !l !r !x0 = go l r\n where\n go !l !r\n | l Int -> Int64 -> SegTree -> IO ()\nupdateRange !kl !kr !x segtree = when (x/=0) $ go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n{-# INLINE updateRange #-} \n\nupdateKey :: Int -> Int64 -> SegTree -> IO ()\nupdateKey !key !x segtree = when (x/=0) $ go segtree\n where\n go (Node l r _ bref lt rt) = do\n b <- readIORef bref\n writeIORef bref $! b + x\n if 2*key <= l+r then go lt else go rt\n go (Leaf _ ref) = modifyIORef' ref (x+)\n{-# INLINE updateKey #-} \n\nqueryRange :: Int -> Int -> SegTree -> IO Int64\nqueryRange !kl !kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (fromIntegral$min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0\n{-# INLINE queryRange #-}\n\nqueryKey :: Int -> SegTree -> IO Int64\nqueryKey !key segtree = go 0 segtree\n where\n go !acc (Node l r aref bref lt rt) = do\n a <- readIORef aref\n if 2*key <= l+r then go (acc+a) lt else go (acc+a) rt\n go !acc (Leaf _ ref) = do\n r <- readIORef ref\n return $! acc+r\n{-# INLINE queryKey #-}\n", "positive_code": [{"source_code": "import Data.Bits\nimport Data.Maybe\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\n\n\ndata Tree = Node !Int64 !Int64 !Int !Tree !Tree\n | Leaf !Int64\n deriving (Show)\n\nemptyTree :: Int -> Tree\nemptyTree 0 = Leaf 0\nemptyTree n = Node 0 0 (n-1) (emptyTree (n-1)) (emptyTree (n-1))\n\nappend :: Int -> Int64 -> Tree -> Tree\nappend n x tree = sub tree\n where\n sub (Node _ a d t1 t2) \n | testBit n d = Node (num t1 + num t2') a d t1 t2'\n | otherwise = Node (num t1'+ num t2 ) a d t1' t2\n where\n t1' = sub t1\n t2' = sub t2\n sub (Leaf _) = Leaf x\n\nnum (Node x a d _ _) = x + a * 2^(d+1)\nnum (Leaf x) = x\n\nadd :: Int -> Int64 -> Tree -> Tree\nadd n x tree = sub tree\n where\n sub (Node s a d t1 t2)\n | testBit n d = Node (num t1' + num t2') a d t1' t2'\n | otherwise = Node (num t1'' + num t2) a d t1'' t2\n where\n t1' = update x t1\n t1''= sub t1\n t2' = sub t2\n sub (Leaf s) = update x (Leaf s)\n\nupdate x (Node s a d t1 t2) = Node s (a+x) d t1 t2 \nupdate x (Leaf s) = Leaf (s+x)\n\nremove :: Int -> Tree -> Tree\nremove n tree = sub tree\n where\n sub (Node s a d t1 t2)\n | testBit n d = Node (num t1' + num t2') 0 d t1' t2'\n | otherwise = Node (num t1'') 0 d t1'' t2\n where\n t1' = update a t1\n t2' = sub (update a t2)\n t1'' = sub t1\n sub (Leaf x) = Leaf 0\n \nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . fromMaybe 0 .fmap (fst). B.readInt\n foldM_ query (1,emptyTree 20) [1..n]\n\nquery :: (Int,Tree) -> Int -> IO (Int,Tree)\nquery (n,tree) _ = do\n l <- B.getLine >>= return . map (fromMaybe 0.fmap (fromIntegral. fst) . B.readInt) . B.words\n let (n',tree') = case l of\n [1,a,x] -> (n,add (a-1) (fromIntegral x) tree)\n [2,x] -> (n+1,append n (fromIntegral x) tree)\n [3] -> (n-1,remove (n-1) tree)\n B.putStrLn $ B.pack $ showDouble ((fromIntegral (num tree') / fromIntegral n'):: Double)\n return (n',tree')\n\nshowDouble :: Double -> String\nshowDouble f | f < 0 = \"-\"++showDouble (-f)\n | otherwise = printf \"%d.%07d\" frac small\n where\n frac = floor f :: Int64\n small = round ((f - fromIntegral frac)* 10000000) :: Int64\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Foreign.C.String\n\n#if __GLASGOW_HASKELL__ < 706\nimport Data.IORef\n#else\nimport Data.IORef hiding (modifyIORef')\n#endif\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_double :: CString -> Double -> IO ()\n\nprintDouble :: Double -> IO ()\nprintDouble x = do\n withCString \"%f\\n\" $ \\fmt -> do\n c_printf_double fmt x\n\ndata Query = T1 !Int !Int64\n | T2 !Int64\n | T3\n\nparse :: [Int] -> [Query]\nparse (1:a:x:rest) = T1 a (fromIntegral x) : parse rest\nparse (2:k:rest) = T2 (fromIntegral k) : parse rest\nparse (3:rest) = T3 : parse rest\nparse _ = []\n\nmain = do\n n <- readLn :: IO Int\n qs <- parse.map readInt.B.words <$> B.getContents\n segtree@(Node _ _ aref bref _ _) <- mkSegTree 0 n 0\n cntref <- newIORef 1 :: IO (IORef Int)\n let !len = fromIntegral $ n+1\n\n let step :: Query -> IO ()\n step (T1 a x) = do\n updateRange 0 (a-1) x segtree\n cnt <- readIORef cntref\n a <- readIORef aref\n b <- readIORef bref\n printDouble $ fromIntegral (a*len+b) / fromIntegral cnt\n step (T2 k) = do\n cnt <- readIORef cntref\n updateKey cnt k segtree\n cnt <- readIORef cntref\n writeIORef cntref $! cnt+1\n a <- readIORef aref\n b <- readIORef bref\n printDouble $ fromIntegral (a*len+b) / fromIntegral (cnt+1)\n step T3 = do\n cnt <- readIORef cntref\n x <- queryKey (cnt-1) segtree\n updateKey (cnt-1) (fromIntegral$ -x) segtree\n writeIORef cntref $! cnt-1\n a <- readIORef aref\n b <- readIORef bref\n printDouble $ fromIntegral (a*len+b) / fromIntegral (cnt-1)\n mapM_ step qs\n\ndata SegTree = Node !Int !Int !(IORef Int64) !(IORef Int64) !SegTree !SegTree\n | Leaf !Int !(IORef Int64)\n\nmkSegTree :: Int -> Int -> Int64 -> IO SegTree\nmkSegTree !l !r !x0 = go l r\n where\n go !l !r\n | l Int -> Int64 -> SegTree -> IO ()\nupdateRange !kl !kr !x segtree = when (x/=0) $ go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n{-# INLINE updateRange #-} \n\nupdateKey :: Int -> Int64 -> SegTree -> IO ()\nupdateKey !key !x segtree = when (x/=0) $ go segtree\n where\n go (Node l r _ bref lt rt) = do\n b <- readIORef bref\n writeIORef bref $! b + x\n if 2*key <= l+r then go lt else go rt\n go (Leaf _ ref) = modifyIORef' ref (x+)\n{-# INLINE updateKey #-} \n\nqueryRange :: Int -> Int -> SegTree -> IO Int64\nqueryRange !kl !kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (fromIntegral$min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0\n{-# INLINE queryRange #-}\n\nqueryKey :: Int -> SegTree -> IO Int64\nqueryKey !key segtree = go 0 segtree\n where\n go !acc (Node l r aref bref lt rt) = do\n a <- readIORef aref\n if 2*key <= l+r then go (acc+a) lt else go (acc+a) rt\n go !acc (Leaf _ ref) = do\n r <- readIORef ref\n return $! acc+r\n{-# INLINE queryKey #-}\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Text.Printf\n\n#if __GLASGOW_HASKELL__ < 706\nimport Data.IORef\n#else\nimport Data.IORef hiding (modifyIORef')\n#endif\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ndata Query = T1 !Int !Int64\n | T2 !Int64\n | T3\n\nparse :: [Int] -> [Query]\nparse (1:a:x:rest) = T1 a (fromIntegral x) : parse rest\nparse (2:k:rest) = T2 (fromIntegral k) : parse rest\nparse (3:rest) = T3 : parse rest\nparse _ = []\n\nmain = do\n n <- readLn :: IO Int\n qs <- parse.map readInt.B.words <$> B.getContents\n segtree <- mkSegTree 0 n 0\n cntref <- newIORef 1 :: IO (IORef Int)\n\n let step :: Query -> IO Double\n step (T1 a x) = do\n updateRange 0 (a-1) x segtree\n s <- getRoot segtree\n cnt <- readIORef cntref\n return $! fromIntegral s / fromIntegral cnt\n step (T2 k) = do\n cnt <- readIORef cntref\n updateKey cnt k segtree\n s <- getRoot segtree\n cnt <- readIORef cntref\n writeIORef cntref $! cnt+1\n return $! fromIntegral s / fromIntegral (cnt+1)\n step T3 = do\n cnt <- readIORef cntref\n x <- queryKey (cnt-1) segtree\n updateKey (cnt-1) (fromIntegral$ -x) segtree\n s <- getRoot segtree\n writeIORef cntref $! cnt-1\n return $! fromIntegral s / fromIntegral (cnt-1)\n putStr.unlines.map show <$> mapM step qs\n \ndata SegTree = Node !Int !Int !(IORef Int64) !(IORef Int64) !SegTree !SegTree\n | Leaf !Int !(IORef Int64)\n\nmkSegTree :: Int -> Int -> Int64 -> IO SegTree\nmkSegTree !l !r !x0 = go l r\n where\n go !l !r\n | l Int -> Int64 -> SegTree -> IO ()\nupdateRange !kl !kr !x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n{-# INLINE updateRange #-} \n\nupdateKey :: Int -> Int64 -> SegTree -> IO ()\nupdateKey !key !x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (k==key) $ do\n modifyIORef' ref (x+)\n{-# INLINE updateKey #-} \n\nqueryRange :: Int -> Int -> SegTree -> IO Int64\nqueryRange !kl !kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (fromIntegral$min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0\n{-# INLINE queryRange #-}\n\nqueryKey :: Int -> SegTree -> IO Int64\nqueryKey !key segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | 2*key <= l+r = (+) <$> go lt <*> readIORef aref\n | otherwise = (+) <$> go rt <*> readIORef aref\n go (Leaf k ref) = readIORef ref\n{-# INLINE queryKey #-}\n\ngetRoot :: SegTree -> IO Int64\ngetRoot (Node l r aref bref _ _) = do\n a <- readIORef aref\n b <- readIORef bref\n return $! a*(fromIntegral$r-l+1)+b\n{-# INLINE getRoot #-} \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Text.Printf\n\n#if __GLASGOW_HASKELL__ < 706\nimport Data.IORef\n#else\nimport Data.IORef hiding (modifyIORef')\n#endif\nmodifyIORef' :: IORef a -> (a -> a) -> IO ()\nmodifyIORef' r f=do x<-readIORef r;writeIORef r$!f x\n{-# INLINE modifyIORef' #-} \n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ndata Query = T1 !Int !Int64\n | T2 !Int64\n | T3\n\nparse :: [Int] -> [Query]\nparse (1:a:x:rest) = T1 a (fromIntegral x) : parse rest\nparse (2:k:rest) = T2 (fromIntegral k) : parse rest\nparse (3:rest) = T3 : parse rest\nparse _ = []\n\nmain = do\n n <- readLn :: IO Int\n qs <- parse.map readInt.B.words <$> B.getContents\n segtree <- mkSegTree 0 n 0\n cntref <- newIORef 0 :: IO (IORef Int)\n\n let step (T1 a x) = do\n updateRange 0 (a-1) x segtree\n s <- getRoot segtree\n cnt <- readIORef cntref\n return $! fromIntegral s / fromIntegral cnt\n step (T2 k) = do\n cnt <- readIORef cntref\n updateKey cnt k segtree\n s <- getRoot segtree\n cnt <- readIORef cntref\n writeIORef cntref $! cnt+1\n return $! fromIntegral s / fromIntegral (cnt+1)\n step T3 = do\n cnt <- readIORef cntref\n x <- queryKey (cnt-1) segtree\n updateKey (cnt-1) (fromIntegral$ -x) segtree\n s <- getRoot segtree\n writeIORef cntref $! cnt-1\n return $! fromIntegral s / fromIntegral (cnt-1)\n\n putStr.unlines.map show <$> mapM step qs\n \ndata SegTree = Node !Int !Int !(IORef Int64) !(IORef Int64) !SegTree !SegTree\n | Leaf !Int !(IORef Int64)\n\nmkSegTree :: Int -> Int -> Int64 -> IO SegTree\nmkSegTree !l !r !x0 = go l r\n where\n go !l !r\n | l Int -> Int64 -> SegTree -> IO ()\nupdateRange !kl !kr !x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (kl<=k && k<=kr) $ do\n modifyIORef' ref (x+)\n{-# INLINE updateRange #-} \n\nupdateKey :: Int -> Int64 -> SegTree -> IO ()\nupdateKey !key !x segtree = go segtree\n where\n go (Node l r aref bref lt rt) = do\n unless (r> go rt\n go (Leaf k ref) = do\n when (k==key) $ do\n modifyIORef' ref (x+)\n{-# INLINE updateKey #-} \n\nqueryRange :: Int -> Int -> SegTree -> IO Int64\nqueryRange !kl !kr segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | r go lt <*> go rt\n a <- readIORef aref\n return $! (fromIntegral$min r kr-max l kl+1)*a + xy\n go (Leaf k ref)\n | kl<=k && k<=kr = readIORef ref\n | otherwise = return 0\n{-# INLINE queryRange #-}\n\nqueryKey :: Int -> SegTree -> IO Int64\nqueryKey !key segtree = go segtree\n where\n go (Node l r aref bref lt rt)\n | 2*key <= l+r = (+) <$> go lt <*> readIORef aref\n | otherwise = (+) <$> go rt <*> readIORef aref\n go (Leaf k ref) = readIORef ref\n{-# INLINE queryKey #-}\n\ngetRoot :: SegTree -> IO Int64\ngetRoot (Node l r aref bref _ _) = do\n a <- readIORef aref\n b <- readIORef bref\n return $! a*(fromIntegral$r-l+1)+b\n{-# INLINE getRoot #-} \n"}, {"source_code": "import Data.Bits\nimport Data.Maybe\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\n\ndata Tree = Node !Int !Int !Int !Tree !Tree\n | Leaf !Int\n deriving (Show)\n\nemptyTree :: Int -> Tree\nemptyTree 0 = Leaf 0\nemptyTree n = Node 0 0 (n-1) (emptyTree (n-1)) (emptyTree (n-1))\n\nappend :: Int -> Int -> Tree -> Tree\nappend n x tree = sub tree\n where\n sub (Node _ a d t1 t2) \n | testBit n d = Node (num t1 + num t2') a d t1 t2'\n | otherwise = Node (num t1'+ num t2 ) a d t1' t2\n where\n t1' = sub t1\n t2' = sub t2\n sub (Leaf _) = Leaf x\n\nnum (Node x a d _ _) = x + a * 2^(d+1)\nnum (Leaf x) = x\n\nadd :: Int -> Int -> Tree -> Tree\nadd n x tree = sub tree\n where\n sub (Node s a d t1 t2)\n | testBit n d = Node (num t1' + num t2') a d t1' t2'\n | otherwise = Node (num t1'' + num t2) a d t1'' t2\n where\n t1' = update x t1\n t1''= sub t1\n t2' = sub t2\n sub (Leaf s) = update x (Leaf s)\n\nupdate x (Node s a d t1 t2) = Node s (a+x) d t1 t2 \nupdate x (Leaf s) = Leaf (s+x)\n\nremove :: Int -> Tree -> Tree\nremove n tree = sub tree\n where\n sub (Node s a d t1 t2)\n | testBit n d = Node (num t1' + num t2') 0 d t1' t2'\n | otherwise = Node (num t1'') 0 d t1'' t2\n where\n t1' = update a t1\n t2' = sub (update a t2)\n t1'' = sub t1\n sub (Leaf x) = Leaf 0\n \nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . fromMaybe 0 .fmap fst. B.readInt\n (n,tree) <- foldM query (1,emptyTree 20) [1..n]\n return ()\n\nquery :: (Int,Tree) -> Int -> IO (Int,Tree)\nquery (n,tree) _ = do\n l <- B.getLine >>= return . map (fromMaybe 0.fmap fst . B.readInt) . B.words\n let (n',tree') = case l of\n [1,a,x] -> (n,add (a-1) x tree)\n [2,x] -> (n+1,append n x tree)\n [3] -> (n-1,remove (n-1) tree)\n B.putStrLn $ B.pack $ showDouble ((fromIntegral (num tree') / fromIntegral n'):: Double)\n return (n',tree')\n\nshowDouble :: Double -> String\nshowDouble f | f < 0 = \"-\"++showDouble (-f)\n | otherwise = printf \"%d.%07d\" frac small\n where\n frac = floor f :: Int\n small = round ((f - fromIntegral frac)* 10000000) :: Int\n"}, {"source_code": "import Data.Bits\nimport Data.Maybe\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\n\ndata Tree = Node !Int !Int !Int !Tree !Tree\n | Leaf !Int\n deriving (Show)\n\nemptyTree :: Int -> Tree\nemptyTree 0 = Leaf 0\nemptyTree n = Node 0 0 (n-1) (emptyTree (n-1)) (emptyTree (n-1))\n\nappend :: Int -> Int -> Tree -> Tree\nappend n x tree = sub tree\n where\n sub (Node _ a d t1 t2) \n | testBit n d = Node (num t1 + num t2') a d t1 t2'\n | otherwise = Node (num t1'+ num t2 ) a d t1' t2\n where\n t1' = sub t1\n t2' = sub t2\n sub (Leaf _) = Leaf x\n\nnum (Node x a d _ _) = x + a * 2^(d+1)\nnum (Leaf x) = x\n\nadd :: Int -> Int -> Tree -> Tree\nadd n x tree = sub tree\n where\n sub (Node s a d t1 t2)\n | testBit n d = Node (num t1' + num t2') a d t1' t2'\n | otherwise = Node (num t1'' + num t2) a d t1'' t2\n where\n t1' = update x t1\n t1''= sub t1\n t2' = sub t2\n sub (Leaf s) = update x (Leaf s)\n\nupdate x (Node s a d t1 t2) = Node s (a+x) d t1 t2 \nupdate x (Leaf s) = Leaf (s+x)\n\nremove :: Int -> Tree -> Tree\nremove n tree = sub tree\n where\n sub (Node s a d t1 t2)\n | testBit n d = Node (num t1' + num t2') 0 d t1' t2'\n | otherwise = Node (num t1'') 0 d t1'' t2\n where\n t1' = update a t1\n t2' = sub (update a t2)\n t1'' = sub t1\n sub (Leaf x) = Leaf 0\n \nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . fromMaybe 0 .fmap fst. B.readInt\n (n,tree) <- foldM query (1,emptyTree 18) [1..n]\n return ()\n\nquery :: (Int,Tree) -> Int -> IO (Int,Tree)\nquery (n,tree) _ = do\n l <- B.getLine >>= return . map (fromMaybe 0.fmap fst . B.readInt) . B.words\n let (n',tree') = case l of\n [1,a,x] -> (n,add (a-1) x tree)\n [2,x] -> (n+1,append n x tree)\n [3] -> (n-1,remove (n-1) tree)\n B.putStrLn $ B.pack $ showDouble ((fromIntegral (num tree') / fromIntegral n'):: Double)\n return (n',tree')\n\nshowDouble :: Double -> String\nshowDouble f | f < 0 = \"-\"++showDouble (-f)\n | otherwise = printf \"%d.%07d\" frac small\n where\n frac = floor f :: Int\n small = round ((f - fromIntegral frac)* 10000000) :: Int\n"}], "src_uid": "d43d4fd6c1e2722da185f34d902ace97"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m,k] <- readsLine\n as <- readsLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) ->\n putStrLn $ show s ++ \" \" ++ show t\n \n {-\nv -> u -> w\nnot (v -> w)\nnot (v -> u' -> w) ( u <- as )\n\n-}\nedge (u,v) | u <= v = (u,v)\n | otherwise = (v,u)\nsolve n m k as | n == k = Nothing\nsolve n m k as = go (S.fromList es0) cands\n where\n u : l = [1..n] \\\\ as\n v : w : as' = as\n e1 = edge (u,v)\n e2 = edge (u,w)\n e3 = edge (v,w)\n es0 = map edge $ [(v,u),(u,w)] ++ zip (w:as') as' ++ zip (u:l) l\n cands = [(i,j) | i <- [1..n], j <- [i+1..n] , i /= v , j /= v] ++ [ edge (u',v) | u' <- l]\n go !es _ | S.size es == m = Just (S.toList es)\n go !es [] = Nothing\n go !es (e:cands) = go (e `S.insert` es) cands\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m,k] <- readsLine\n as <- readsLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) ->\n putStrLn $ show s ++ \" \" ++ show t\n \n {-\nv -> u -> w\nnot (v -> w)\nnot (v -> u' -> w) ( u <- as )\n\n-}\nedge (u,v) | u <= v = (u,v)\n | otherwise = (v,u)\nsolve n m k as | n == k = Nothing\nsolve n m k as = go (S.fromList es0) cands\n where\n u : l = [1..n] \\\\ as\n v : w : as' = as\n e1 = edge (u,v)\n e2 = edge (u,w)\n e3 = edge (v,w)\n es0 = map edge $ [(v,u),(u,w)] ++ zip (w:as') as' ++ zip (u:l) l\n cands = [(i,j) | i <- [1..n], j <- [i+1..n] , i /= v , j /= v] ++ [ edge (u',v) | u' <- l]\n go !es _ | S.size es == m = Just (S.toList es)\n go !es [] = Nothing\n go !es (e:cands) = go (e `S.insert` es) cands\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport qualified Data.Set as S\n\nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\nmain = do\n [n,m,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) -> putStrLn $ unwords $ map show [s,t]\n\nedge (u,v) = if u <= v then (u,v) else (v,u)\n\nsolve n m k as | n == k = Nothing\nsolve n m k as = go (S.fromList es0) cands\n where\n u : l = [1..n] \\\\ as\n v : w : as' = as\n es0 = map edge $ [(v,u),(u,w)] ++ zip (w:as') as' ++ zip (u:l) l\n cands = [(i,j) | i <- [1..n], j <- [i+1..n] , i /= v , j /= v] ++ [ edge (u',v) | u' <- l]\n go !es _ | S.size es == m = Just (S.toList es)\n go !es [] = Nothing\n go !es (e:cands) = go (e `S.insert` es) cands\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport qualified Data.Set as S\n\nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\nmain = do\n [n,m,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> putStr $ unlines $ map (\\(s,t) -> unwords $ map show [s,t]) es\n\nedge (u,v) = if u <= v then (u,v) else (v,u)\n\nsolve n m k as | n == k = Nothing\nsolve n m k as = go (S.fromList es0) cands\n where\n u : l = [1..n] \\\\ as\n v : w : as' = as\n es0 = map edge $ [(v,u),(u,w)] ++ zip (w:as') as' ++ zip (u:l) l\n cands = [(i,j) | i <- [1..n], j <- [i+1..n] , i /= v , j /= v] ++ [ edge (u',v) | u' <- l]\n go !es _ | S.size es == m = Just (S.toList es)\n go !es [] = Nothing\n go !es (e:cands) = go (e `S.insert` es) cands\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport qualified Data.Set as S\n\nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\nmain = do\n [n,m,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> putStr $ unlines $ map (\\(s,t) -> \n unwords $ map show [s,t]) es\n\nedge (u,v) = if u <= v then (u,v) else (v,u)\n\nsolve :: Int -> Int -> Int -> [Int] -> Maybe [(Int,Int)]\nsolve n m k as | n == k = Nothing\nsolve n m k as = go (S.fromList es0) cands\n where\n u : l = [1..n] \\\\ as\n v : w : as' = as\n es0 = map edge $ [(v,u),(u,w)] ++ zip (w:as') as' ++ zip (u:l) l\n cands = [(i,j) | i <- [1..n], j <- [i+1..n] , i /= v , j /= v] ++ \n [ edge (u',v) | u' <- l]\n go !es _ | S.size es == m = Just (S.toList es)\n go !es [] = Nothing\n go !es (e:cands) = go (e `S.insert` es) cands\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m,k] <- readsLine\n as <- readsLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) ->\n putStrLn $ show s ++ \" \" ++ show t\n \n {-\nv -> u -> w\nnot (v -> w)\nnot (v -> u' -> w) ( u <- as )\n-}\nedge u v | u <= v = (u,v)\n | otherwise = (v,u)\nsolve n m k as | n == k = Nothing\nsolve n m k as = if length es == m then Just es else Nothing\n where\n u : l = [1..n] \\\\ as\n v : w : _ = as\n e1 = edge u v\n e2 = edge u w\n e3 = edge v w\n es = take m $ [e1,e2] ++ \n [ (i,j) | i <- [1..n], j <- [i+1..n] , i /= v , j /= v, (i,j) /= e2] ++\n [ edge u' v | u' <- l]\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m,k] <- readsLine\n as <- readsLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) ->\n putStrLn $ show s ++ \" \" ++ show t\n \nedge u v | u <= v = (u,v)\n | otherwise = (v,u)\nsolve n m k as | n == k = Nothing\nsolve n m k as = if length es == m then Just es else Nothing\n where\n u :_ = [1..n] \\\\ as\n v : w : _ = as\n es = take m $ [edge u v,edge u w] ++ do\n i <- [1..n]\n guard $ i /= v\n j <- [i+1..n]\n guard $ edge u v /= (i,j)\n guard $ edge u w /= (i,j)\n return (i,j)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m,k] <- readsLine\n as <- readsLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) ->\n putStrLn $ show s ++ \" \" ++ show t\n \nedge u v | u <= v = (u,v)\n | otherwise = (v,u)\nsolve n m k as | n == k = Nothing\nsolve n m k as | k == n - 1 = if length es == m then Just es else Nothing\n where\n u :_ = [1..n] \\\\ as\n v : w : _ = as\n es = take m $ [edge u v,edge u w] ++ do\n i <- [1..n]\n guard $ i /= v\n j <- [i+1..n]\n guard $ edge u v /= (i,j)\n guard $ edge u w /= (i,j)\n return (i,j)\nsolve n m k as = Just es\n where\n u:v:_ = [1..n] \\\\ as \n es = take m $ (u,v):[(i,j) | i <- [1..n], j <- [i+1..n], (i,j) /= (u,v)]\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m,k] <- readsLine\n as <- readsLine\n case solve n m k as of\n Nothing -> print (-1)\n Just es -> forM_ es $ \\(s,t) ->\n putStrLn $ show s ++ \" \" ++ show t\n \nedge u v | u <= v = (u,v)\n | otherwise = (v,u)\nsolve n m k as | n == k = Nothing\nsolve n m k as | k == n - 1 = if length es == m then Just es else Nothing\n where\n u :_ = [1..n] \\\\ as\n v : w : _ = as\n es = take m $ [edge u v,edge u w] ++ do\n i <- [1..n]\n guard $ i /= v\n j <- [i+1..n]\n guard $ edge u v /= (i,j)\n guard $ edge u w /= (i,j)\n return (i,j)\nsolve n m k as | m == n * (n-1) `div` 2 = Nothing\n | otherwise = Just es\n where\n u:v:_ = [1..n] \\\\ as \n w = head as\n es = take m $ [edge u w,edge w v] ++ ([(i,j) | i <- [1..n], j <- [i+1..n]] \\\\ [edge u v,edge u w,edge w v])\n"}], "src_uid": "084203d057faedd6a793eec38748aaa8"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n (n:lrs) <- map (fromIntegral.readInteger).B.words <$> B.getContents\n putStr.unlines.map show $ solve lrs\n\nsolve :: [Int64] -> [Int64]\nsolve lrs = go lrs\n where\n go (l:r:lrs) = query l r : go lrs\n go _ = []\n\nquery :: Int64 -> Int64 -> Int64\nquery l r\n | l == r = l\n | l<=cand = cand\n | otherwise = h + query (l-h) (r-h)\n where\n cand = last . takeWhile (<=r) $ iterate (\\acc->acc*2+1) 0\n h = cand `xor` unsafeShiftR cand 1\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nf l r\n | l == r = l\n | p <= l = f (l-p) (r-p) + p\n | 2*p-1 <= r = 2*p-1\n | otherwise = p-1\n where\n p = last $ takeWhile (<= r) $ map (2^) [0..]\n\nmain = do\n n <- readLn\n replicateM n (do\n [l, r] <- getInts :: IO [Int64]\n print $ f l r)\n\n"}], "negative_code": [], "src_uid": "644b8f95b66b7e4cb39af552ec518b3f"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, accumArray, elems)\nimport Debug.Trace (traceShow)\n\n-- 1, 2, 3, 4\nloop :: Int -> Int -> Int -> Int -> Int\nloop 0 0 _ _ = 0\n\nloop i j k l -- 1 -> 2\n | 0 < i && 0 < j = inc + loop (i - inc) (j - inc) (k + inc) l\n where inc = min i j\n\nloop i 0 k l -- {1, 1, 1}\n | 2 < i = inc * 2 + loop (i - 3 * inc) 0 (k + inc) l\n where inc = i `div` 3\n\nloop 1 0 0 _ = 2 -- 1, 4, 4 -> 3, 3\nloop 1 0 _ _ = 1 -- 1 -> 3\nloop 2 0 _ _ = 2\n\nloop 0 j k l -- 2, 2, 2 -> 3, 3\n | 2 < j = inc * 2 + loop 0 (j - 3 * inc) (k + 2 * inc) l\n where inc = j `div` 3\n\nloop 0 1 _ 0 = 2\nloop 0 1 _ _ = 1\nloop 0 2 _ _ = 2\n\nsolve :: [Int] -> Int\nsolve a = if acc < 3 || acc == 5 then -1 else loop i j k l\n where\n arr :: UArray Int Int\n arr = accumArray (+) 0 (0, 4) . zip a . repeat $ 1\n [i, j, k, l] = tail $ elems arr\n acc = sum a\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= print . solve\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, accumArray, elems)\n\n-- 1, 2, 3, 4\nloop :: Int -> Int -> Int -> Int -> Int\nloop 0 0 _ _ = 0\n\n-- 50% gain\nloop i j k l -- 1 -> 2\n | 0 < i && 0 < j = inc + loop (i - inc) (j - inc) (k + inc) l\n where inc = min i j\n\n-- 1/3rd gain\nloop i 0 k l -- {1, 1, 1}\n | 2 < i = inc * 2 + loop (i - 3 * inc) 0 (k + inc) l\n where inc = i `div` 3\n\n-- 1/3rd gain\nloop 0 j k l -- 2, 2, 2 -> 3, 3\n | 2 < j = inc * 2 + loop 0 (j - 3 * inc) (k + 2 * inc) l\n where inc = j `div` 3\n\nloop 1 0 0 _ = 2 -- 1, 4, 4 -> 3, 3\nloop 1 0 _ _ = 1 -- 1 -> 3\nloop 2 0 _ _ = 2\n\nloop 0 1 _ 0 = 2\nloop 0 1 _ _ = 1\nloop 0 2 _ _ = 2\n\nsolve :: [Int] -> Int\nsolve a\n | acc < 3 || acc == 5 = -1\n | otherwise = loop i j k l\n where\n arr :: UArray Int Int\n arr = accumArray (+) 0 (0, 4) . zip a . repeat $ 1\n [i, j, k, l] = tail $ elems arr\n acc = sum a\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= print . solve\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, accumArray, elems, (!))\nimport Debug.Trace (traceShow)\n\n-- 1, 2, 3, 4\nloop :: Int -> Int -> Int -> Int -> Int\nloop 0 0 _ _ = 0\nloop i j k l -- 1 -> 2\n | 0 < i && 0 < j = inc + loop (i - inc) (j - inc) (k + inc) l\n where inc = min i j\n\nloop i 0 k l -- {1, 1, 1}\n | 2 < i = inc * 2 + loop (i - 3 * inc) 0 inc l\n where inc = i `div` 3\n\nloop i 0 k l -- {1, 1, 1, 1}\n | 3 < i = inc * 3 + loop (i - 4 * inc) 0 0 (l + inc)\n where inc = i `div` 4\n\nloop i 0 k l -- 1 -> 3\n | 0 < k = inc + loop (i - inc) 0 (k - inc) (l + inc)\n where inc = min i k\n\nloop i 0 _ _ = 2 -- 1, 2\n\nloop 0 j k l -- 2, 2, 2 -> 3, 3\n | 2 < j = inc * 2 + loop 0 (j - 3 * inc) (k + 2 * inc) l\n where inc = j `div` 3\n\nloop 0 1 _ l = if 0 < l then 1 else 2\nloop 0 2 _ _ = 2\n\n--loop 0 j k l -- 4 -> 2\n-- | 0 < j && 0 < l = inc + loop 0 (j - inc) (k + inc) (l - inc)\n-- where inc = min j l\n\nsolve :: [Int] -> Int\nsolve a = if sum (elems arr) < 3 then -1 else loop i j k l\n where\n arr :: UArray Int Int\n arr = accumArray (+) 0 (0, 4) . zip a . repeat $ 1\n [i, j, k, l] = map (arr !) [1, 2, 3, 4]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= print . solve\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, accumArray, elems)\nimport Debug.Trace (traceShow)\n\n-- 1, 2, 3, 4\nloop :: Int -> Int -> Int -> Int -> Int\nloop 0 0 _ _ = 0\n\nloop i j k l -- 1 -> 2\n | 0 < i && 0 < j = inc + loop (i - inc) (j - inc) (k + inc) l\n where inc = min i j\n\nloop i 0 k l -- {1, 1, 1}\n | 2 < i = inc * 2 + loop (i - 3 * inc) 0 (k + inc) l\n where inc = i `div` 3\n\nloop 1 0 0 _ = 2 -- 1, 4, 4 -> 3, 3\nloop 1 0 _ _ = 1 -- 1 -> 3\nloop 2 0 _ _ = 2\n\nloop 0 j k l -- 2, 2, 2 -> 3, 3\n | 2 < j = inc * 2 + loop 0 (j - 3 * inc) (k + 2 * inc) l\n where inc = j `div` 3\n\nloop 0 1 _ 0 = 2\nloop 0 1 _ _ = 1\nloop 0 2 _ _ = 2\n\nsolve :: [Int] -> Int\nsolve a = if acc < 3 || acc == 5 then -1 else loop i j k l\n where\n arr :: UArray Int Int\n arr = accumArray (+) 0 (0, 4) . zip a . repeat $ 1\n [i, j, k, l] = tail $ elems arr\n acc = sum . tail $ elems arr\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= print . solve\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, accumArray, elems, (!))\nimport Debug.Trace (traceShow)\n\n-- 1, 2, 3, 4\nloop :: Int -> Int -> Int -> Int -> Int\nloop 0 0 _ _ = 0\nloop i j k l -- 1 -> 2\n | 0 < i && 0 < j = inc + loop (i - inc) (j - inc) (k + inc) l\n where inc = min i j\n\nloop i 0 k l -- {1, 1, 1}\n | 2 < i = inc * 2 + loop (i - 3 * inc) 0 inc l\n where inc = i `div` 3\n\nloop i 0 k l -- {1, 1, 1, 1}\n | 3 < i = inc * 3 + loop (i - 4 * inc) 0 0 (l + inc)\n where inc = i `div` 4\n\nloop i j k l -- 1 -> 3\n | 0 < i && 0 < k = inc + loop (i - inc) j (k - inc) (l + inc)\n where inc = min i k\n\nloop i 0 0 _ = i -- 1, 2\n\nloop 0 j k l -- 2, 2, 2 -> 3, 3\n | 2 < j = inc * 2 + loop 0 (j - 3 * inc) (k + 2 * inc) l\n where inc = j `div` 3\n\nloop 0 1 _ l = if 0 < l then 1 else 2\nloop 0 2 _ _ = 2\n\n--loop 0 j k l -- 4 -> 2\n-- | 0 < j && 0 < l = inc + loop 0 (j - inc) (k + inc) (l - inc)\n-- where inc = min j l\n\nsolve :: [Int] -> Int\nsolve a = if sum (elems arr) < 3 then -1 else loop i j k l\n where\n arr :: UArray Int Int\n arr = accumArray (+) 0 (0, 4) . zip a . repeat $ 1\n [i, j, k, l] = map (arr !) [1, 2, 3, 4]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= print . solve\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array.Unboxed (UArray, accumArray, elems)\nimport Debug.Trace (traceShow)\n\n-- 1, 2, 3, 4\nloop :: Int -> Int -> Int -> Int -> Int\nloop 0 0 _ _ = 0\nloop i j k l -- 1 -> 2\n | 0 < i && 0 < j = inc + loop (i - inc) (j - inc) (k + inc) l\n where inc = min i j\n\nloop i 0 k l -- {1, 1, 1}\n | 2 < i = inc * 2 + loop (i - 3 * inc) 0 (k + inc) l\n where inc = i `div` 3\n\n-- loop i 0 k l -- {1, 1, 1, 1}\n-- | 3 < i = inc * 3 + loop (i - 4 * inc) 0 0 (l + inc)\n-- where inc = i `div` 4\n\nloop i 0 k l -- 1 -> 3\n | 0 < k = inc + loop (i - inc) 0 (k - inc) (l + inc)\n where inc = min i k\n\nloop i 0 _ _ = 2 -- 1, 2\n\nloop 0 j k l -- 2, 2, 2 -> 3, 3\n | 2 < j = inc * 2 + loop 0 (j - 3 * inc) (k + 2 * inc) l\n where inc = j `div` 3\n\nloop 0 1 _ l = if 0 < l then 1 else 2\nloop 0 2 _ _ = 2\n\n--loop 0 j k l -- 4 -> 2\n-- | 0 < j && 0 < l = inc + loop 0 (j - inc) (k + inc) (l - inc)\n-- where inc = min j l\n\nsolve :: [Int] -> Int\nsolve a = (elems arr) `traceShow` if sum (elems arr) < 3 then -1 else loop i j k l\n where\n arr :: UArray Int Int\n arr = accumArray (+) 0 (0, 4) . zip a . repeat $ 1\n [i, j, k, l] = tail $ elems arr\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= print . solve\n"}], "src_uid": "a7cdb90a03447fc9285819ed059383b3"} {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let [l, r] = map (\\x -> read x :: Integer) $ words s\n putStrLn $ if 2 * l > r then\n \"-1 -1\"\n else\n show l ++ \" \" ++ show (2 * l)\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Integer)", "positive_code": [{"source_code": "type Pair = (Integer, Integer)\n\nparse :: String -> [Pair]\nparse = chunksTwo . tail . map read . words\n\nchunksTwo :: [Integer] -> [Pair]\nchunksTwo [] = []\nchunksTwo (x0:x1:xs) = (x0, x1) : chunksTwo xs\nchunksTwo _ = error \"malformed input\"\n\nsolveCase :: Pair -> Pair\nsolveCase (le, ri)\n | le * 2 > ri = (0-1, 0-1)\n | otherwise = (le, 2*le)\n\ndisplayAns :: Pair -> String\ndisplayAns (x, y) = show x ++ \" \" ++ show y\n\nmain :: IO ()\nmain = interact (unlines . map (displayAns . solveCase) . parse)\n\n\n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [l, r] <- map read . words <$> getLine\n if l * 2 > r then putStrLn \"-1 -1\" else putStrLn $ show l ++ \" \" ++ show (2 * l)\n"}, {"source_code": "module Main where\n\nsolve [x,y] = if y < x*2 then \"-1 -1\" else show x ++ \" \" ++ show (x*2)\nmain = interact $ unlines . map (solve . map (read :: String -> Int) . words ) . tail . lines "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\t[x,y]<- map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ if x+x<=y then intercalate \" \" (map show [x,x+x]) else \"-1 -1\"\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [{"source_code": "module Main where\n\nsolve [x,y] = \n let b = filter (\\(_,z) -> z >= x && z <= y) $ let a = [x+1 .. min y (x*2)] in zip a $ map (lcm x) a\n in if null b \n then \"-1 -1\"\n else show x ++ \" \" ++ show (fst $ head b)\nmain = interact $ unlines . map (solve . map (read :: String -> Int) . words ) . tail . lines "}, {"source_code": "module Main where\n\nsolve [x,y] = if y > x*2 then \"-1 -1\" else show x ++ \" \" ++ show (x*2)\nmain = interact $ unlines . map (solve . map (read :: String -> Int) . words ) . tail . lines "}], "src_uid": "e8ba3fb95800806465386ecbfbe924e9"} {"source_code": "import Control.Monad (replicateM_, replicateM)\n\n\ndata Tile =\n Tile Int Int Int Int\n\ndata Input =\n Input Int Int [Tile]\n\n\nreadT :: IO Int\nreadT = do\n line <- getLine\n pure (read line :: Int)\n\n\nisSymmetric :: Tile -> Bool\nisSymmetric (Tile a b c d) | b == c = True\n | otherwise = False\n\noppositeTile :: Tile -> Tile\noppositeTile (Tile a b c d) = Tile a c b d\n\nhasSymmetricTile :: [Tile] -> Bool\nhasSymmetricTile = any isSymmetric\n\n\ncanBeSolved :: Input -> Bool\ncanBeSolved (Input n m tiles) | odd m = False\n | otherwise = hasSymmetricTile tiles\n\n\nreadTuple :: IO (Int, Int)\nreadTuple = do\n num_strings <- words <$> getLine\n let a = read (head num_strings) :: Int\n let b = read (last num_strings) :: Int\n pure (a, b)\n\n \nreadTile :: IO Tile\nreadTile = do\n (a, b) <- readTuple\n (c, d) <- readTuple\n\n let tile = Tile a b c d\n pure tile\n\n\nreadInput :: IO Input\nreadInput = do\n (n, m) <- readTuple\n tiles <- replicateM n readTile \n pure (Input n m tiles)\n\n\nsolveCase :: IO ()\nsolveCase = do\n input <- readInput\n \n let ans | canBeSolved input = \"YES\"\n | otherwise = \"NO\"\n\n putStrLn ans\n\n\nmain :: IO ()\nmain = do\n t <- readT\n replicateM_ t solveCase\n\n-- vim: set ts=4 sw=4 expandtab:\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\n\ngetList :: (Read t) => IO [t]\ngetList = getLine >>= return . (map read) . words\n\ngetOne :: (Read t) => IO t\ngetOne = getLine >>= return . read\n\nmain :: IO ()\nmain = do\n t <- getOne\n -- let t = 1\n replicateM_ t solve\n\n\nsolve :: IO ()\nsolve = do \n [n, m] <- getList\n plits <- replicateM n scanOne\n putStrLn $ countAns m plits\n where\n scanOne :: IO [Int]\n scanOne = do\n a <- getList\n b <- getList\n return $ a ++ b\n\ncountAns :: Integral t => t -> [[t]]-> String\ncountAns m plits\n | m `mod` 2 == 1 = \"NO\"\n | not $ any (\\l -> (l !! 1) == (l !! 2)) plits = \"NO\"\n | null $ intersect plits $ map rev plits = \"NO\"\n | otherwise = \"YES\"\n where\n rev :: Integral t => [t] -> [t]\n rev [a, b, c, d] = [a, c, b, d]\n"}, {"source_code": "third :: [Int] -> Int\nthird a = head (tail (tail a))\n\ngetAns :: Int -> [[Int]] -> Bool\ngetAns m [] = False\ngetAns m a | mod m 2 /= 0 = False\n | (head (tail (head a))) == (third (head a)) = True\n | otherwise = getAns m (tail a)\n\nconvert :: Bool -> String\nconvert True = \"YES\"\nconvert False = \"NO\"\n\n\nget :: Int -> [String] -> Int\nget 0 a = read (head (a)) :: Int\nget 1 a = read (head (tail (a))) :: Int\n\ngetList :: Int -> [[Int]] -> Int -> IO()\ngetList 0 a m = do\n putStrLn (convert (getAns m a))\n\ngetList n a m = do\n first <- getLine\n second <- getLine\n\n let list = [(get 0 (words first)), (get 1 (words first)), (get 0 (words second)), (get 1 (words second))]\n getList (n - 1) (a ++ [list]) m\n \n\n\nsolve :: Int -> IO()\nsolve 0 = do\n putStr \"\"\nsolve t = do\n str <- getLine\n let n = get 0 (words str)\n let m = get 1 (words str)\n getList n [] m\n solve (t - 1)\n\n\nmain = do\n testes <- getLine\n let t = read testes :: Int\n solve t"}, {"source_code": "import Control.Monad\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, m] <- readInts\n symms <- replicateM n $ do\n [_, p] <- readInts\n [q, _] <- readInts\n pure $ p == q\n putStrLn $ if even m && or symms\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "import Control.Arrow ( (>>>) )\n\nmain :: IO ()\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read) \n >>> process \n >>> map (\\x -> if x then \"YES\" else \"NO\") >>> unlines\n\nprocess :: [[Int]] -> [Bool]\nprocess [] = []\nprocess ([n, m] : rest) = \n (if m `mod` 2 == 0 then solve (take (n*2) rest) else False) : process (drop (n*2) rest)\n\nsolve :: [[Int]] -> Bool\nsolve [] = False\nsolve ([_, a]:[b, _]:rest) = or [a == b, solve rest]\n"}], "negative_code": [], "src_uid": "f46f6fa28d0a7023da3bad0d222ce393"} {"source_code": "import Data.List (group, sort)\r\n\r\n\r\nmain :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [n, k] = map read $ words input\r\n result = findFirstKBeautifulNumber n (fromIntegral k)\r\n output = show result\r\n\r\n\r\nfindFirstKBeautifulNumber :: Integer -> KParameter -> Integer\r\nfindFirstKBeautifulNumber start k\r\n | isKBeautiful start k = start\r\n | start `mod` 10 /= 0 = findFirstKBeautifulNumber (start + 1) k\r\n | otherwise = result_if_start_ends_with_zero\r\n where\r\n result_if_start_ends_with_zero = result_for_short_version * 10 + last_digit\r\n result_for_short_version = findFirstKBeautifulNumber (start `div` 10) k\r\n last_digit = read [minimum (show result_for_short_version)]\r\n\r\n\r\nisKBeautiful :: Integer -> KParameter -> Bool\r\nisKBeautiful number k = measureK number <= k\r\n\r\n\r\ntype KParameter = Int\r\nmeasureK :: Integer -> KParameter\r\nmeasureK = length . group . sort . show", "positive_code": [{"source_code": "import Data.List (group, sort)\r\n\r\n\r\nmain :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [n, k] = map read $ words input\r\n result = findFirstKBeautifulNumber n (fromIntegral k)\r\n output = show result\r\n\r\n\r\nfindFirstKBeautifulNumber :: Integer -> KParameter -> Integer\r\nfindFirstKBeautifulNumber start k\r\n | isKBeautiful start k = start\r\n | start `mod` 10 /= 0 = findFirstKBeautifulNumber (start + 1) k\r\n | otherwise = result_if_start_ends_with_zero\r\n where\r\n result_if_start_ends_with_zero = result_for_short_version * 10 + last_digit\r\n result_for_short_version = findFirstKBeautifulNumber (start `div` 10) k\r\n can_add_new_digit = measureK result_for_short_version < k\r\n last_digit = if can_add_new_digit then 0 else read [minimum (show result_for_short_version)]\r\n\r\n\r\nisKBeautiful :: Integer -> KParameter -> Bool\r\nisKBeautiful number k = measureK number <= k\r\n\r\n\r\ntype KParameter = Int\r\nmeasureK :: Integer -> KParameter\r\nmeasureK = length . group . sort . show\r\n"}], "negative_code": [], "src_uid": "3ef53ad23ec56344f68546096c6c3308"} {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Int (Int64)\n\nmain = do\n n <- getLine >>= return . read\n shc <- replicateM n getLine >>= return . (map countSHC)\n print $ (sum $ map (\\(_, _, c) -> c) shc) + (compute $ sortBy getOrd (map (\\(s, h, _) -> (s, h)) shc))\n where\n getOrd (sa, ha) (sb, hb) = if (sa * hb < sb * ha) then GT else LT\n\ncompute :: [(Int64, Int64)] -> Int64\ncompute shs =\n sum $ map (\\((s, h'), h) -> s*(h-h')) $ zip shs hs\n where\n hs = scanr accumr 0 (map snd shs)\n accumr s c= s + c\n\ncountSHC :: String -> (Int64, Int64, Int64)\ncountSHC str = \n let ss = scanl (count 's') 0 str in\n let hs = scanr (flip $ count 'h') 0 str in\n (last ss, head hs, sum $ map (\\(c, n) -> if c == 's' then n else 0) $ zip str hs)\n where\n count c n ch = n + (if c == ch then 1 else 0)", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n n <- getLine >>= return . read\n shc <- replicateM n getLine >>= return . (map countSHC)\n print $ (sum $ map (\\(_, _, c) -> c) shc) + (compute $ sortBy getOrd (map (\\(s, h, _) -> (s, h)) shc))\n where\n getOrd (sa, ha) (sb, hb) = if (sa * hb < sb * ha) then GT else LT\n\ncompute :: [(Integer, Integer)] -> Integer\ncompute shs =\n sum $ map (\\((s, h'), h) -> s*(h-h')) $ zip shs hs\n where\n hs :: [Integer]\n hs = scanr accumr 0 (map snd shs)\n accumr :: Integer -> Integer -> Integer\n accumr s c= s + c\n\ncountSHC :: String -> (Integer, Integer, Integer)\ncountSHC str = \n let ss = scanl (count 's') 0 str in\n let hs = scanr (flip $ count 'h') 0 str in\n (last ss, head hs, sum $ map (\\(c, n) -> if c == 's' then n else 0) $ zip str hs)\n where\n count :: Char -> Integer -> Char -> Integer\n count c n ch = n + (if c == ch then 1 else 0)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Int\n\ncountChar :: String -> Char -> Int64\ncountChar str c = foldl' (\\acc cur -> if cur == c then acc + 1 else acc) 0 str\n\ngetSHRatio :: String -> Rational\ngetSHRatio str = (toRational $ countChar str 's') / (toRational $ countChar str 'h')\n\ngetHCount :: String -> [Int64]\ngetHCount [] = [0]\ngetHCount (x:xs)\n | x == 's' = f : res\n | otherwise = (f + 1) : res\n where res = getHCount xs\n f = head res\n\nsolve :: String -> [Int64] -> Int64\nsolve _ [] = 0\nsolve (x:xs) (h:hh)\n | x == 's' = h + rest\n | otherwise = rest\n where rest = solve xs hh\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int64) <$> getLine\n lst <- mapM (\\_ -> getLine) [1..n]\n let onlyS = join $ [x | x <- lst, not $ 'h' `elem` x]\n onlyH = join $ [x | x <- lst, not $ 's' `elem` x]\n both = [x | x <- lst, 'h' `elem` x && 's' `elem` x]\n bothWithCount = reverse . sort $ [(getSHRatio x, x) | x <- both]\n best = onlyS ++ (join $ map (\\t -> snd t) bothWithCount) ++ onlyH\n hCount = tail $ getHCount best\n res = solve best hCount\n -- putStrLn . show $ best\n -- putStrLn . show $ hCount\n putStrLn . show $ res\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ntransf :: String -> (Int64, Int64, String)\ntransf s = (x, y, s)\n where x = fromIntegral . length $ elemIndices 's' s\n y = (fromIntegral . length $ s) - x\n\ncompAns :: Int64 -> String -> Int64\ncompAns _ \"\" = 0\ncompAns st ('s':rest) = compAns (st + 1) rest\ncompAns st ('h':rest) = st + compAns st rest\n\nmain = do\n n <- readLn\n l <- replicateM n $ fmap transf getLine\n let sl = sortBy (\\(a, b, _) (x, y, _) -> compare (b*x) (a*y)) l\n print . compAns 0 . join . map (\\(_,_,x) -> x) $ sl\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n n <- getLine >>= return . read\n shc <- replicateM n getLine >>= return . (map countSHC)\n print $ (sum $ map (\\(_, _, c) -> c) shc) + (compute $ sortBy getOrd (map (\\(s, h, _) -> (s, h)) shc))\n where\n getOrd (sa, ha) (sb, hb) = if (sa * hb < sb * ha) then GT else LT\n\ncompute :: [(Int, Int)] -> Int\ncompute shs =\n sum $ map (\\((s, h'), h) -> s*(h-h')) $ zip shs hs\n where\n hs :: [Int]\n hs = scanr accumr 0 (map snd shs)\n accumr :: Int -> Int -> Int\n accumr s c= s + c\n\ncountSHC :: String -> (Int, Int, Int)\ncountSHC str = \n let ss = scanl (count 's') 0 str in\n let hs = scanr (flip $ count 'h') 0 str in\n (last ss, head hs, sum $ map (\\(c, n) -> if c == 's' then n else 0) $ zip str hs)\n where\n count :: Char -> Int -> Char -> Int\n count c n ch = n + (if c == ch then 1 else 0)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\ncountChar :: String -> Char -> Int\ncountChar str c = foldl' (\\acc cur -> if cur == c then acc + 1 else acc) 0 str\n\ngetSHRatio :: String -> Rational\ngetSHRatio str = (toRational $ countChar str 's') / (toRational $ countChar str 'h')\n\ngetHCount :: String -> [Int]\ngetHCount [] = [0]\ngetHCount (x:xs)\n | x == 's' = f : res\n | otherwise = (f + 1) : res\n where res = getHCount xs\n f = head res\n\nsolve :: String -> [Int] -> Int\nsolve _ [] = 0\nsolve (x:xs) (h:hh)\n | x == 's' = h + rest\n | otherwise = rest\n where rest = solve xs hh\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n lst <- mapM (\\_ -> getLine) [1..n]\n let onlyS = join $ [x | x <- lst, not $ 'h' `elem` x]\n onlyH = join $ [x | x <- lst, not $ 's' `elem` x]\n both = [x | x <- lst, 'h' `elem` x && 's' `elem` x]\n bothWithCount = reverse . sort $ [(getSHRatio x, x) | x <- both]\n best = onlyS ++ (join $ map (\\t -> snd t) bothWithCount) ++ onlyH\n hCount = tail $ getHCount best\n res = solve best hCount\n -- putStrLn . show $ best\n -- putStrLn . show $ hCount\n putStrLn . show $ res\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ntransf :: String -> (Int, Int, String)\ntransf s = (x, y, s)\n where x = length $ elemIndices 's' s\n y = length s - x\n\ncompAns :: Int64 -> String -> Int64\ncompAns _ \"\" = 0\ncompAns st ('s':rest) = compAns (st + 1) rest\ncompAns st ('h':rest) = st + compAns st rest\n\nmain = do\n n <- readLn\n l <- replicateM n $ fmap transf getLine\n let sl = sortBy (\\(a, b, _) (x, y, _) -> compare (b*x) (a*y)) l\n print . compAns 0 . join . map (\\(_,_,x) -> x) $ sl\n"}], "src_uid": "f88cf470095f250ffeb57feae7697e36"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nevens :: [t] -> [t]\nevens (p:q:rs) = p : evens rs\nevens x = x\n\ninterleave :: [t] -> [t] -> [t]\ninterleave [] _ = []\ninterleave (x:xs) ys = x : interleave ys xs\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n a <- readInts\n let\n a1 = sort $ evens a\n a2 = sort $ evens $ tail a\n opt = interleave a1 a2\n ans = and $ zipWith (<=) opt (tail opt)\n lift $ B.hPutBuilder stdout $ if ans\n then B.string7 \"YES\\n\"\n else B.string7 \"NO\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM, for)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\nimport GHC.IO.Handle (hDuplicateTo)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> fst . fromJust\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> fst . fromJust\n\nsolve :: Int -> [Int] -> Bool\nsolve n as =\n all (all (\\(k, v) -> v == 0) . IM.toList) cnts\n where\n sortAs :: [Int]\n sortAs = sort as\n\n md :: Int\n md = 2\n\n execCnts :: Int -> [Int] -> [IM.IntMap Int] -> [IM.IntMap Int]\n execCnts diff arr prevCnts =\n flip map (zip [0 ..] prevCnts) $ uncurry alterCnts\n where\n alterCnts :: Int -> IM.IntMap Int -> IM.IntMap Int\n alterCnts c mp =\n foldl (\\mp (i, e) -> if i `mod` md == c then IM.insertWith (+) e diff mp else mp) mp $\n zip [0 ..] arr\n\n cnts :: [IM.IntMap Int]\n cnts =\n execCnts (-1) as $\n execCnts 1 sortAs $\n replicate md IM.empty\n\n\nmain :: IO ()\nmain = do\n tests <- B8.getLine <&> readIntB8\n replicateM_ tests $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> map readIntB8 . B8.words\n\n let answer = solve n as\n\n putStrLn $ if answer then \"YES\" else \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified System.IO as Io\n--import Data.IntSet \n\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n sa <- getLine\n let a = map read $ words sa :: [Int]\n a_odd = oddelems a\n b_odd = oddelems $ sort a\n good = (sort a_odd == reverse b_odd)\n in putStrLn (if good then \"YES\" else \"NO\")\n where oddelems xs = foldl (\\acc (i, x) -> if odd i then x : acc else acc) [] (zip [0..] xs)\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "import Data.List as L\n\nmergeLists :: [Int] -> [Int] -> [Int]\nmergeLists [] [] = []\nmergeLists x [] = x\nmergeLists [] y = y\nmergeLists (x:xs) (y:ys) = x:y:(mergeLists xs ys)\n\nisSorted :: [Int] -> Bool\nisSorted [] = True\nisSorted [x] = True\nisSorted (x:y:xs) = x <= y && isSorted (y:xs)\n\nsplitList :: [Int] -> ([Int], [Int])\nsplitList [] = ([], [])\nsplitList [x] = ([x], [])\nsplitList (x:y:xs) = (x:axs, y:bxs)\n where (axs, bxs) = splitList xs\n\nsolve :: Int -> IO ()\nsolve _ = do\n n <- (read :: String -> Int) <$> getLine\n -- putStrLn . show $ n\n lst <- map (\\x -> (read :: String -> Int) x) . words <$> getLine\n -- putStrLn . show $ lst\n let (e, o) = splitList lst\n se = L.sort e\n so = L.sort o\n merged = mergeLists se so\n res = if isSorted merged then \"Yes\" else \"No\"\n putStrLn res\n\nsolveTest :: [Int] -> IO ()\nsolveTest [] = return ()\nsolveTest (x:xs) = do\n solve x\n solveTest xs\n\nmain :: IO ()\nmain = do\n t <- (read :: String -> Int) <$> getLine\n -- putStrLn . show $ t\n solveTest [1..t]\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nsolve [] _ = True\r\nsolve _ [] = True\r\nsolve (e:es) (o:os)\r\n | o >= e = solve (o:os) es\r\n | otherwise = False \r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n xs <- readInts\r\n let z = zip xs [0..]\r\n e = [a|(a,b)<-z,even b]\r\n o = [a|(a,b)<-z,odd b]\r\n putStrLn $ if solve (sort e) (sort o) then \"YES\" else \"NO\"\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport qualified Data.Map.Strict as M\r\nimport Data.Bool\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata OddEven = Odd | Even deriving (Show, Eq, Ord, Enum, Bounded)\r\n\r\nsummarize :: [Int] -> M.Map (Int, OddEven) Int\r\nsummarize xs =\r\n let ks = zip xs $ fmap (bool Odd Even . even) [1..]\r\n in M.fromListWith (+) $ zip ks $ repeat 1\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n xs <- getInts n\r\n let ys = sort xs\r\n pure $ (<>char7 '\\n') $! bool (string7 \"NO\") (string7 \"YES\") $ (summarize xs) == (summarize ys)\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a:b:interleave as bs\ninterleave a b = a ++ b\n\nuninterleave :: [a] -> ([a], [a])\nuninterleave (a1:a2:as) = let (x, y) = uninterleave as in (a1:x, a2:y)\nuninterleave [a] = ([a], [])\nuninterleave [] = ([], [])\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (x, y) = (f x, f y)\n\ntoAnswer :: Bool -> String\ntoAnswer True = \"YES\"\ntoAnswer False = \"NO\"\n\nisSorted :: Ord a => [a] -> Bool\nisSorted [] = True\nisSorted [a] = True\nisSorted (a1:a2:as) = (a1 <= a2) && (isSorted (a2:as))\n\ndoit :: [Int] -> String\ndoit = toAnswer . isSorted . uncurry interleave . both sort . uninterleave\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n l <- fmap (map read . words) getLine\n putStrLn $ doit l\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Data.List (group, groupBy, sort)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>> drop 1 >>> chunksOf 2\r\n >>> map (last >>> words >>> map read >>> solve >>> bool \"No\" \"Yes\")\r\n >>> unlines\r\n\r\nsolve :: [Int] -> Bool\r\nsolve =\r\n sorted\r\n . interleave\r\n . map (map snd)\r\n . groupBy (equating fst)\r\n . sort\r\n . zip ((`mod` 2) <$> [0 ..])\r\n\r\nequating :: Eq a => (b -> a) -> b -> b -> Bool\r\nequating f x y = f x == f y\r\n\r\nsorted :: (Ord a) => [a] -> Bool\r\nsorted xs = and $ zipWith (<=) xs (tail xs)\r\n\r\ninterleave :: [[a]] -> [a]\r\ninterleave [] = []\r\ninterleave xs = let xs' = filter (not . null) xs in map head xs' ++ interleave (map tail xs')\r\n\r\n"}], "negative_code": [], "src_uid": "1d27d6d736d891b03b7476f8a7209291"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport qualified Data.IntMap as IM\n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map (fromIntegral.readInt).B.words <$> B.getLine\n ys <- map (subtract 1.readInt).B.words <$> B.getLine\n putStr.unlines.map show $ solve n xs ys\n\nsolve :: Int -> [Int64] -> [Int] -> [Int64]\nsolve n xs ys = go [] 0 IM.empty IM.empty $ reverse ys\n where\n arr = listArray(0, n-1) xs\n go res acc ls rs (k:ks) = go (acc:res) res' ls' rs' ks\n where\n !res' = max acc s\n !v = arr ! k\n !s = sl + v + sr\n (l, sl) = case IM.lookup (k-1) rs of\n Just (lk, s) -> (lk, s)\n Nothing -> (k, 0)\n (r, sr) = case IM.lookup (k+1) ls of\n Just (rk, s) -> (rk, s)\n Nothing -> (k, 0)\n rs' = IM.insert r (l, s) $ IM.delete (k-1) rs\n ls' = IM.insert l (r, s) $ IM.delete (k+1) ls\n go res _ _ _ [] = res\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\n", "positive_code": [{"source_code": "-- import qualified Data.IntMap as M\nimport qualified Data.Map.Strict as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.List (scanr)\n\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\n\nsolve a i (m, curmax) =\n let\n n = a M.! i\n left = M.lookup (i-1) m\n right = M.lookup (i+1) m\n newGroup =\n ( ( fromMaybe i . fmap (fst . fst) $ left\n , fromMaybe i . fmap (snd . fst) $ right\n )\n , n\n + (fromMaybe 0 . fmap snd $ left)\n + (fromMaybe 0 . fmap snd $ right)\n )\n in\n ( M.insert (fst . fst $ newGroup) newGroup\n . M.insert (snd . fst $ newGroup) newGroup\n $ m\n , max curmax $ snd newGroup\n )\n\n\nmain = do\n [n] <- readLine\n array <- readLine\n order <- readLine\n B.putStrLn . B.pack . unlines . map (show . snd) . drop 1 $ scanr (solve $ M.fromAscList (zip [1..] array)) (M.empty, 0) order\n"}, {"source_code": "{-\nTODO:\n1. Read from IO\n2. Convert [Int] to mutable [(0 | Sum, rootId | 0, 0 | length)]\n3. Write fold fn which returns current maximum sum.\n-}\nmodule Main where\nimport Data.Array\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\ntype Set = ((Integer, Integer), Integer)\n\n-- values as first argument\n-- sequence to remove as second\ngetSum :: [Integer] -> [Integer] -> [Integer]\ngetSum ys xs =\n let els = listArray (0, pred $ toInteger $ length ys) $ zip (zip [1, 1..] [-1, -1..]) ys :: Array Integer Set\n in run (reverse xs) els\n\nrun :: [Integer] -> Array Integer Set -> [Integer]\nrun xs els' = runST $ do\n els <- thaw els'\n curMaxSum <- newSTRef 0\n res' <- forM xs $ \\i' -> do\n let i = pred i'\n l = toInteger $ length xs\n visit i els\n union i (pred i) els $ pred l\n union i (succ i) els $ pred l\n root <- findRoot i els\n ((_,_), sumI) <- readArray els root\n modifySTRef curMaxSum (\\x -> max x sumI)\n newMax <- readSTRef curMaxSum\n -- trace (show $ newMax) $ return ()\n readSTRef curMaxSum\n return res'\n\nvisit :: Integer -> STArray s Integer Set -> ST s ()\nvisit i els = do\n ((l, _), y) <- readArray els i\n writeArray els i $ ((l, i), y)\n\nfindRoot :: Integer -> STArray s Integer Set -> ST s Integer\nfindRoot i els = do\n ((_, rootId), _) <- readArray els i\n if (rootId == i || rootId == -1) then return rootId\n else findRoot rootId els\n\nunion :: Integer -> Integer -> STArray s Integer Set -> Integer -> ST s ()\nunion i j els maxJ\n | j < 0 || j > maxJ = return ()\n | otherwise = do\n rootI' <- findRoot i els\n rootJ' <- findRoot j els\n -- one of the elements was not visited yet. Nothing to union\n if (rootI' == -1 || rootJ' == -1) then return ()\n else do\n ((lI, rootI), sumI) <- readArray els rootI'\n ((lJ, rootJ), sumJ) <- readArray els rootJ'\n writeArray els rootI ((lI + lJ, rootI), sumI + sumJ)\n writeArray els rootJ ((0, rootI), 0)\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_] <- readLine\n array <- readLine\n order <- readLine\n mapM_ print $ tail $ reverse $ (:) 0 $ getSum array order\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Set hiding (map, foldl)\nimport qualified Data.Map as M\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Integer]\n where fn x = let Just (y,_) = B.readInteger x in y\n \n \ninf = round 1e18\n\nadd k m = case M.lookup k m of\n Just _ -> M.update (return . succ) k m\n _ -> M.insert k 1 m\n \nremove :: Integer -> M.Map Integer Integer -> M.Map Integer Integer\nremove k m = case M.lookup k m of\n Just x -> if x == 1 then M.delete k m else M.update (return . pred) k m\n _ -> error \"Key doesn't exist\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n a <- readIntList\n b <- readIntList\n let pre = listArray (0,n+1) ((scanl (+) 0 a)++[0])\n for :: Set (Integer,Integer) -> M.Map Integer Integer -> [Integer] -> IO()\n for st mp (i:is) = do\n let (a,b) = fromJust $ lookupLE (i,inf) st\n st' = delete (a,b) st\n mp' = remove (pre!b - pre!(a-1)) mp\n (nst,nmp) = foldl fn (st',mp') [(a,i-1),(i+1,b)]\n fn (st,mp) (x,y)\n |y >= x = (insert (x,y) st, add (pre!y - pre!(x-1)) mp)\n |otherwise = (st,mp)\n -- print (st,mp)\n if M.null nmp\n then print 0\n else do\n print . fst . M.findMax $ nmp\n for nst nmp is\n for (fromList [(1,n)]) (M.fromList [(pre!n,1)]) b\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Set hiding (map, foldl)\n\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Integer]\n where fn x = let Just (y,_) = B.readInteger x in y\n \n \ninf = round 2e9\n\nmain :: IO ()\nmain = do\n n <- readLn\n a <- readIntList\n b <- readIntList\n let pre = listArray (0,n+1) ((scanl (+) 0 a)++[0])\n for :: Set (Integer,Integer) -> Set Integer -> [Integer] -> IO ()\n for st1 st2 (i:is) = do\n let (a,b) = fromJust $ lookupLE (i,inf) st1 :: (Integer,Integer)\n st1' = delete (a,b) st1\n st2' = delete (pre!b - pre!(a-1)) st2\n (nst1,nst2) = foldl fn (st1',st2') [(a,i-1),(i+1,b)]\n fn (st1,st2) (x,y)\n |pre!y - pre!(x-1) > 0 = (insert (x,y) st1, insert (pre!y - pre!(x-1)) st2)\n |otherwise = (st1,st2)\n case maxView nst2 of\n Just x -> do\n print . fst $ x\n for nst1 nst2 is\n _ -> print 0\n for (fromList [(1,n)]) (fromList [pre!n]) b\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\ntype Set = ((Int, Int), Int)\n\n-- values as first argument\n-- sequence to remove as second\ngetSum :: [Int] -> [Int] -> [Int]\ngetSum ys xs =\n let els = listArray (0, pred $ length ys) $ zip (zip [1, 1..] [-1, -1..]) ys :: Array Int Set\n in run (reverse xs) els\n\nrun :: [Int] -> Array Int Set -> [Int]\nrun xs els' = runST $ do\n els <- thaw els'\n curMaxSum <- newSTRef 0\n res' <- forM xs $ \\i' -> do\n let i = pred i'\n l = length xs\n visit i els\n union i (pred i) els $ pred l\n union i (succ i) els $ pred l\n root <- findRoot i els\n ((_,_), sumI) <- readArray els root\n modifySTRef curMaxSum (\\x -> max x sumI)\n newMax <- readSTRef curMaxSum\n -- trace (show $ newMax) $ return ()\n readSTRef curMaxSum\n return res'\n\nvisit :: Int -> STArray s Int Set -> ST s ()\nvisit i els = do\n ((l, _), y) <- readArray els i\n writeArray els i $ ((l, i), y)\n\nfindRoot :: Int -> STArray s Int Set -> ST s Int\nfindRoot i els = do\n ((_, rootId), _) <- readArray els i\n if (rootId == i || rootId == -1) then return rootId\n else findRoot rootId els\n\nunion :: Int -> Int -> STArray s Int Set -> Int -> ST s ()\nunion i j els maxJ\n | j < 0 || j > maxJ = return ()\n | otherwise = do\n rootI' <- findRoot i els\n rootJ' <- findRoot j els\n -- one of the elements was not visited yet. Nothing to union\n if (rootI' == -1 || rootJ' == -1) then return ()\n else do\n ((lI, rootI), sumI) <- readArray els rootI'\n ((lJ, rootJ), sumJ) <- readArray els rootJ'\n writeArray els rootI ((lI + lJ, rootI), sumI + sumJ)\n writeArray els rootJ ((0, rootI), 0)\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_] <- readLine\n array <- readLine\n order <- readLine\n mapM_ print $ tail $ reverse $ (:) 0 $ getSum array order\n"}, {"source_code": "import qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.List (scanr)\n\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\n\nsolve :: M.IntMap Int -> Int -> (M.IntMap ((Int, Int), Int), Int) -> (M.IntMap ((Int, Int), Int), Int)\nsolve a i (m, curmax) =\n let\n n = a M.! i\n left = M.lookup (i-1) m\n right = M.lookup (i+1) m\n newGroup =\n ( ( fromMaybe i . fmap (fst . fst) $ left\n , fromMaybe i . fmap (snd . fst) $ right\n )\n , n\n + (fromMaybe 0 . fmap snd $ left)\n + (fromMaybe 0 . fmap snd $ right)\n )\n in\n ( M.insert (fst . fst $ newGroup) newGroup\n . M.insert (snd . fst $ newGroup) newGroup\n $ m\n , max curmax $ snd newGroup\n )\n\n\nmain = do\n [n] <- readLine\n array <- readLine\n order <- readLine\n B.putStrLn . B.pack . unlines . map (show . snd) . drop 1 $ scanr (solve $ M.fromAscList (zip [1..] array)) (M.empty, 0) order\n"}], "src_uid": "0553ab01447ab88bee70d07c433f0654"} {"source_code": "import Data.Ratio\n\nmain = do\n n <- fmap (read :: String -> Int) $ getLine\n m <- fmap (toRational . (read :: String -> Double)) $ getLine\n a <- fmap (map (toRational . (read :: String -> Double)) . words) $ getLine\n b <- fmap (map (toRational . (read :: String -> Double)) . words) $ getLine\n\n let d = product [1 - 1/x | x <- a] * product [1 - 1/x | x <- b]\n\n let answer = if d > 0 then show . fromRational $ m * (1 - d) / d\n else show (negate 1)\n\n putStrLn answer", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n getLine\n m <- readLn :: IO Double\n a <- fmap (map read . words) getLine :: IO [Double]\n b <- fmap (map read . words) getLine :: IO [Double]\n let c = concat . zipWith (\\a b -> [b, a]) (reverse a) $ head b : (reverse . tail $ b)\n let tot = foldl' (\\x a -> x + x / (a - 1)) m c\n print $ if any (== 1) $ a ++ b then -1 else tot - m\n"}, {"source_code": "main :: IO ()\nmain = do\n input <- sequence [getLine, getLine, getLine, getLine]\n let count = read (head input) :: Int\n let mass = read (input !! 1) :: Int\n let ka = map (read::String->Int) (words(input !! 2))\n let kb = map (read::String->Int) (words(input !! 3))\n print (calculate count mass ka kb)\n \ncalculate :: Int -> Int -> [Int] -> [Int] -> Double\ncalculate _ mass ka kb = result \n where \n result = if noValue \n then -1.0\n else fly (fromIntegral mass) 0.0 k\n k = prepare ka kb\n noValue = 1 `elem` k\n\nprepare :: [Int] -> [Int] -> [Int]\nprepare ka kb = reverseList (merge ka (tail kb ++ [head kb]))\n\nfly :: Double -> Double -> [Int] -> Double\nfly mass fuel (k:ks) = fly mass (fuel + fuelIncrement (mass + fuel) k) ks\nfly mass fuel [] = fuel\n\nfuelIncrement :: Double -> Int -> Double\nfuelIncrement mass k = mass / fromIntegral (k - 1)\n\nmerge :: [a] -> [a] -> [a]\nmerge (x:xs) (y:ys) = x : y : merge xs ys\nmerge [] [] = []\n\nreverseList :: [a] -> [a]\nreverseList [] = []\nreverseList (x:xs) = reverseList xs ++ [x]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nif' :: Bool -> a -> a -> a\nif' True x _ = x\nif' False _ y = y\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve :: Double -> [Int] -> [Int] -> Double\nsolve m a b = if' (c > 0) (m / c - m) (-1)\n\twhere c = product $ map ((\\x -> 1 - 1/x) . fromIntegral) $ (a ++ b)\n\nmain :: IO ()\nmain = do\n\t[n] <- getInts\n\t[m] <- getInts\n\ta <- getInts\n\tb <- getInts\n\tprint (solve (fromIntegral m) a b) "}, {"source_code": "\n\ntoint s = (read s) :: Int\n\nitod x = (fromIntegral x) :: Double\n\ncan::Double -> [Double] -> [Double] -> Double -> Bool\ncan m [] [] f = True\ncan m (a:as) (b:bs) f =\n let x = (m + f) / a in\n if f - x < 0 then\n False\n else\n let ff = f - x in\n let xx = (m+ff) / b in\n if ff-xx < 0 then\n False\n else\n can m as bs (ff-xx)\n\n\nbs m a b s e i =\n if i == 70 then\n s\n else\n let mid = (s+e)/2 in\n if can m a b mid then\n bs m a b s mid (i+1)\n else\n bs m a b mid e (i+1)\n\nsolve::String -> String\nsolve sss =\n let (n:mm:ss) = Prelude.map toint $ words sss in\n let a = map itod $ take n ss in\n let bb = map itod $ take n $ drop n ss in\n let b = (tail bb) ++ [head bb] in\n let m = itod mm in\n if can m a b 1.1e9 then\n show (bs m a b 0.0 1.1e9 0) ++ \"\\n\"\n else\n \"-1\\n\"\n\nmain = interact solve"}, {"source_code": "main = interact foo\n\nfoo :: String -> String\nfoo inp = \n let _:m:as:bs:_ = lines inp\n cargo = read m :: Double\n li:lifts = map read $ words as :: [Double]\n landings = map read $ words bs :: [Double]\n transits = zip (li: (reverse lifts)) (reverse landings)\n fuel = (flip (-) cargo) $ foldl (\\c (lif, lan) -> transit c lif lan) cargo transits\n in if fuel == 1/0 then \"-1\" else show fuel\n \n-- reversed\n-- weight before -> takeoff -> landing -> weight after\ntransit :: Double -> Double -> Double -> Double\ntransit w a b = \n let w' = lift w a\n in lift w' b\n \n-- weight before -> takeoff/lanfding -> weight after\nlift :: Double -> Double -> Double\nlift w a =\n let f = w / (a-1)\n in w + f\n"}, {"source_code": "\nmerge :: [a] -> [a] -> [a]\nmerge (a:as) (b:bs) = a : b : merge as bs\nmerge a [] = a\nmerge _ b = b \n\ncompute :: [Int] -> Double -> Double\ncompute (1:_) _ = -1\ncompute (c:cs) w = compute cs $ w * (fromIntegral c) / (fromIntegral c-1)\ncompute _ w = w\n\n\nmain = do\n getLine\n m <- fmap (fromIntegral . read) getLine\n a <- fmap (map read . words) getLine\n b1:bs <- fmap (map read . words) getLine\n let coeffs = b1 : reverse (merge a bs)\n let res = compute coeffs m\n if res < 0 then print (-1)\n else print $ res - m"}], "negative_code": [{"source_code": "\nmerge :: [a] -> [a] -> [a]\nmerge (a:as) (b:bs) = a : b : merge as bs\nmerge a [] = a\nmerge _ b = b \n\ncompute :: [Int] -> Float -> Float\ncompute (1:_) _ = -1\ncompute (c:cs) w = compute cs $ w * (fromIntegral c) / (fromIntegral c-1)\ncompute _ w = w\n\n\nmain = do\n getLine\n m <- fmap (fromIntegral . read) getLine\n a <- fmap (map read . words) getLine\n b1:bs <- fmap (map read . words) getLine\n let coeffs = b1 : reverse (merge a bs)\n let res = compute coeffs m\n if res < 0 then print (-1)\n else print $ res - m"}], "src_uid": "d9bd63e03bf51ed87ba73cd15e8ce58d"} {"source_code": "-- https://codeforces.com/problemset/problem/16/A\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Char(digitToInt)\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nreadLine :: Read a => IO [a]\nreadLine = fmap (fmap read . words) getLine\n\ntestCols :: [Char] -> Bool\ntestCols [a, b] = a /= b\ntestCols (a:b:xs) = (a /= b) && testCols (b:xs)\n\nworkProblem :: IO ()\nworkProblem = do\n [n, m] <- readLine :: IO [Int]\n input <- getLines n\n let cols = map head input\n let rowTest = and $ map (\\xs -> and $ map (== head xs) (tail xs)) input\n let colTest = if length cols == 1 then True else testCols cols\n let anwser = if rowTest && colTest then \"YES\" else \"NO\"\n () <- putStrLn anwser\n return ()\n\nmain :: IO ()\nmain = workProblem", "positive_code": [{"source_code": "main = do\n\tdummy <- getLine\n\ttodo <- getContents\n\tputStrLn $ if gao (lines todo) then \"YES\" else \"NO\"\n\ngao [] = True\ngao (a:b) = gao b && a == take (length a) (repeat (head a)) && (b == [] || a /= head b)\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nimport Data.List\nimport Data.Ratio\n\nsolve = do n <- cin\n m <- cin :: IO Int\n rows <- replicateM n cin :: IO [String]\n let a = all (null.tail.nub) rows\n b = not . or . zipWith (==) rows $ tail rows\n return . output $ a && b\n where\n output True = \"YES\"\n output False = \"NO\"\n\n\nmain = putStrLn =<< solve\n\n\n\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\n\n\n\n"}, {"source_code": "\nsolve [] = []\nsolve (s:ss) = map (head s==) s ++ [nextline]++ solve ss\n where nextline = if null ss then True\n \t else s /= (head ss)\n\nmain = do\n\ta <-getLine\n\tc <-getContents\n\tif and (solve (lines c)) then putStrLn \"YES\"\n\telse putStrLn \"NO\""}, {"source_code": "un = map (read :: String ->Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nisSame (x:xs) = all (==x) xs\n\nisNotSame :: String -> Bool\nisNotSame [x] = True\nisNotSame (a:b:c) = (a /= b) && (isNotSame (b:c))\n\nmain = do\n s <- getLine\n let n:_ = un s\n ss <- getLines n\n let res = if (all isSame ss) && (isNotSame (map head ss)) then \"YES\" else \"NO\"\n putStrLn res\n"}, {"source_code": "\nmain = do\n haha <- getLine\n flag <- getContents\n\n putStrLn $ if yao (lines flag) then \"YES\" else \"NO\"\n\nyao [] = True\nyao (x:xs) = yao xs && x == take (length x) (repeat (head x) ) && (xs == [] ||x /= head xs)"}, {"source_code": "splitOnPred :: (Eq a) => (a -> Bool) -> [a] -> [[a]]\nsplitOnPred pred xs = splitOn' xs [] []\n where splitOn' [] m ret = if null m then ret else ret ++ [m]\n splitOn' (x:xs) [] ret = splitOn' xs (if pred x then [] else [x]) ret\n splitOn' (x:xs) m ret = if pred x then splitOn' xs [] (ret ++ [m]) else splitOn' xs (m ++ [x]) ret\n\nsplitOn :: String -> String -> [String]\nsplitOn str sp = splitOnPred (\\x -> elem x sp) str\n\nsplit :: String -> [String]\nsplit str = splitOn str \" \\n\"\n\nsolve :: [[Char]] -> Bool\nsolve g = column g && row g\n where\n column :: [[Char]] -> Bool\n column g = let gg = map (\\x -> ((head x), x)) g\n ok = map (\\(x, y) -> all (== x) y) gg\n in and ok\n row g = let gg = map head g\n in row' gg\n where row' (x:y:xs)\n | x /= y = row' (y:xs)\n | otherwise = False\n row' _ = True\n\nmain :: IO ()\nmain = do cs <- getContents\n let sp = split cs\n m = read (sp !! 0) :: Int\n n = read (sp !! 1) :: Int\n g = drop 2 sp\n in putStrLn $ if solve g then \"Yes\" else \"No\"\n"}, {"source_code": "\nimport List (nub)\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: [String] -> Bool\nsolve xs = all ((== 1) . length . nub) xs\n && all (\\(a, b) -> a /= b) (zip xs (tail xs))\n\nmain :: IO ()\nmain = do\n n <- fmap (head . map read . words) getLine\n lines' <- fmap (take n . lines) getContents\n putStrLn . (\"YES\" \"NO\") . solve $ lines' \n"}, {"source_code": "import System.Environment\nimport Control.Monad\nimport Control.Monad (liftM, sequence)\nimport Data.List\n\nrr :: [Char] -> Integer\nrr = read\n\nokh [] = True\nokh (x:[]) = True\nokh (x:y:xs) = if x/=y then False else okh (y:xs)\n\nokv [] = True\nokv (x:[]) = True\nokv (x:y:xs) = if x==y then False else okv (y:xs)\n\nyesno True = \"YES\"\nyesno False = \"NO\"\n\nmain = do\n s <- getLine\n let (n:m:null) = Prelude.map rr $ words s\n z <- lines `liftM` getContents\n putStrLn $ yesno $ okv z && Data.List.foldl1(&&) (map okh z)\n"}, {"source_code": "import Data.List (group)\nimport Control.Monad\n\nyesOrNo :: Bool -> IO ()\nyesOrNo True = putStrLn \"YES\"\nyesOrNo False = putStrLn \"NO\"\n\nsolve :: [String] -> Bool\nsolve xs = (and $ map check1 xs) && (check2 $ map head xs)\n where \n check1 xs = length (group xs) == 1\n check2 xs = length (group xs) == length xs\n\nmain = do\n getContents >>= (yesOrNo . solve . tail . lines)"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n _ <- getLine\n todo <- getContents\n putStrLn $ if gao (lines todo) then \"YES\" else \"NO\"\n\ngao :: [String] -> Bool\ngao a = f a && (g $ transpose a)\n where\n f a = all (==1) [ if (any (==True) $ map (/=head x) x) then 0 else 1 | x <- a ]\n g a = all (==1) [ if adj x then 0 else 1 | x <- a ]\n where\n adj [x] = False\n adj [x, y] = x == y\n adj [x, y, z] = x == y || y == z\n adj (x:y:z) = x == y || adj (y:z)\n"}, {"source_code": "import Data.List( nub, group )\nmain:: IO ()\nmain = do\n tokens <- return . words =<< getContents\n let rows = read $ tokens!!0\n lines = drop 2 tokens\n tmp = unzip $ map linechk lines\n colorseq = fst tmp\n horizontalchk = and $ snd tmp\n verticalchk = rows == (length $ group colorseq)\n if horizontalchk && verticalchk\n then putStr \"YES\"\n else putStr \"NO\"\n\nlinechk :: String -> (Char,Bool)\nlinechk l = (head l, 1 == (length . nub) l)\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ncheck1 :: [String] -> Bool\ncheck1 = all allEqual\n\ncheck2 :: [String] -> Bool\ncheck2 [] = True\ncheck2 [x] = True\ncheck2 (x: y: xs) = ((x !! 0) /= (y !! 0)) && check2 (y: xs)\n\nsolve :: [String] -> String\nsolve ls\n | check1 ls && check2 ls = \"YES\"\n | otherwise = \"NO\"\n \n\nmain = do\n sn <- getLine\n let [n, m] = map read (words sn)\n sl <- getLines n\n putStrLn $ solve sl\n\n \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\n\n\nmain = do\n\t\t[n,m]<-map read <$> words <$> getLine ::IO [Int]\n\t\ts<- replicateM n getLine\n\t\tlet x = all (==1) $ map length $ map group s\n\t\tlet y = all (==1) $ map length $ group $ head $ transpose s\n\t\tputStrLn $ if x && y then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = showBool . check . tail . lines =<< getContents\n\nshowBool :: Bool -> IO()\nshowBool True = putStrLn \"YES\"\nshowBool False = putStrLn \"NO\"\n\ncheck :: [String] -> Bool\ncheck flag = (checkRow flag) && (checkColumn flag)\n\ncheckRow :: [String] -> Bool\ncheckRow = all (\\x -> (length . group) x == 1)\n\ncheckColumn :: [String] -> Bool\ncheckColumn flag = all id . zipWith (/=) rows $ (tail rows)\n where rows = map head flag\n"}, {"source_code": "main = do\n inp <- getContents\n let ln = lines inp\n let sol = check ' ' $ tail ln\n if sol\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n\ncheck c [] = True\ncheck c (x:xs) = (x!!0 /= c) && (allEq x) && (check (x!!0) xs)\n where\n allEq s = (fil s) == []\n fil s = filter (/= (head s)) $ tail s\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n _ <- getLine\n todo <- getContents\n putStrLn $ if gao (lines todo) then \"YES\" else \"NO\"\n\ngao :: [String] -> Bool\ngao a = f a && (g $ transpose a)\n where\n f a = all (==1) [ if (any (==True) $ map (/=head x) x) then 0 else 1 | x <- a ]\n g a = all (==1) [ if adj x then 0 else 1 | x <- a ]\n where\n adj [x] = True\n adj [x, y] = x == y\n adj [x, y, z] = x == y && y == z\n adj (x:y:z) = x == y && adj (y:z)\n"}], "src_uid": "80d3da5aba371f4d572ea928025c5bbd"} {"source_code": "import Control.Applicative\nimport Data.Function\nimport Data.List\n\ndata Point = Point Double Double deriving (Eq)\ndata Segment = Segment { segmentStart, segmentEnd :: Point } deriving (Eq)\ndata Vector = Vector Double Double\n\ngetWords = map read . words <$> getLine\n\nsplitEvery n = unfoldr $ \\xs -> if null xs then Nothing else Just $ splitAt n xs\ngetPoints = map (\\[a, b] -> Point a b) . splitEvery 2 <$> getWords\n\ncross (Vector x1 y1) (Vector x2 y2) = x1*y2 - x2*y1\ndot (Vector x1 y1) (Vector x2 y2) = x1*x2 + y1*y2\nsub (Point px py) (Point qx qy) = Vector (qx - px) (qy - py)\n\nintersects s@(Segment p1 p2) t@(Segment p3 p4) =\n\t\t(d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) &&\n\t\t(d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0) ||\n\t\td1 == 0 && onSegment p1 t ||\n\t\td2 == 0 && onSegment p2 t ||\n\t\td3 == 0 && onSegment p3 s ||\n\t\td4 == 0 && onSegment p4 s\n\twhere\n\t\tdirection p q r = sub p r `cross` sub p q\n\n\t\tonSegment (Point rx ry) (Segment (Point px py) (Point qx qy)) =\n\t\t\tmin px qx <= rx && rx <= max px qx &&\n\t\t\tmin py qy <= ry && ry <= max py qy\n\n\t\td1 = direction p3 p4 p1\n\t\td2 = direction p3 p4 p2\n\t\td3 = direction p1 p2 p3\n\t\td4 = direction p1 p2 p4\n\ndata Line = Line Point Point\n\nonLine r (Line p q) = sub p q `cross` sub p r == 0\n\nintersectsRay s@(Segment p1 p2) t@(Segment p3 p4) =\n\tintersects s t && not (p3 `onLine` (Line p1 p2))\n\nintersection s@(Segment sa sb) t@(Segment ta tb) = \n\t\tsa `add` (c `mult` (sa `sub` sb))\n\twhere\n\t\tmult a (Vector x y) = Vector (a * x) (a * y)\n\t\tadd (Point px py) (Vector vx vy) = Point (px + vx) (py + vy)\n\t\tc = (sub sa ta `cross` sub ta tb) / (sub sa sb `cross` sub ta tb)\n\ndistance (Point px py) (Point qx qy) = sqrt $ (qx - px) ** 2 + (qy - py) ** 2\n\nsolve start end polygon\n\t\t| length intersecting < 2 = start `distance` end\n\t\t| otherwise =\n\t\t\tstart `distance` i1 +\n\t\t\tminimum [distThrough, distAround1, distAround2] +\n\t\t\ti2 `distance` end\n\twhere\n\t\tstartEnd = Segment start end\n\t\tsegments = zipWith Segment polygon $ tail polygon ++ [head polygon]\n\n\t\tintersecting = filter (startEnd `intersectsRay`) segments\n\t\tintersections = map (intersection startEnd) intersecting\n\n\t\t(s1,i1):(s2,i2):_ = sortBy (compare `on` (distance start . snd)) $\n\t\t\t\tintersecting `zip` intersections\n\n\t\tdistThrough = 2 * (i1 `distance` i2)\n\n\t\tdistAround s1 s2 segments = sum $ map (\\(Segment p q) -> p `distance` q) $\n\t\t\ttakeWhile (/= s2) $ tail $ dropWhile (/= s1) $ segments ++ segments\n\n\t\tdistAround1 = \n\t\t\ti1 `distance` segmentEnd s1 +\n\t\t\tdistAround s1 s2 segments +\n\t\t\tsegmentStart s2 `distance` i2\n\n\t\tdistAround2 = \n\t\t\ti1 `distance` segmentStart s1 +\n\t\t\tdistAround s1 s2 (reverse segments) +\n\t\t\tsegmentEnd s2 `distance` i2\n\nmain = do\n\t[start, end] <- getPoints\n\t_ <- getLine\n\tpolygon <- getPoints\n\tprint $ solve start end polygon\n\n", "positive_code": [{"source_code": "\n\nimport Control.Applicative\nimport Data.Function\nimport Data.List\nimport Debug.Trace\n\ndata Point = Point Double Double deriving (Eq, Show)\ndata Segment = Segment { segmentStart, segmentEnd :: Point } deriving (Eq, Show)\ndata Vector = Vector Double Double\n\ngetWords = map read . words <$> getLine\n\nsplitEvery n = unfoldr $ \\xs -> if null xs then Nothing else Just $ splitAt n xs\ngetPoints = map (\\[a, b] -> Point a b) . splitEvery 2 <$> getWords\n\ncross (Vector x1 y1) (Vector x2 y2) = x1*y2 - x2*y1\ndot (Vector x1 y1) (Vector x2 y2) = x1*x2 + y1*y2\nsub (Point px py) (Point qx qy) = Vector (qx - px) (qy - py)\n\nintersects s@(Segment p1 p2) t@(Segment p3 p4) =\n\t\t(d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) &&\n\t\t(d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0) ||\n\t\td1 == 0 && onSegment p1 t ||\n\t\td2 == 0 && onSegment p2 t ||\n\t\td3 == 0 && onSegment p3 s ||\n\t\td4 == 0 && onSegment p4 s\n\twhere\n\t\tdirection p q r = sub p r `cross` sub p q\n\n\t\tonSegment (Point rx ry) (Segment (Point px py) (Point qx qy)) =\n\t\t\tmin px qx <= rx && rx <= max px qx &&\n\t\t\tmin py qy <= ry && ry <= max py qy\n\n\t\td1 = direction p3 p4 p1\n\t\td2 = direction p3 p4 p2\n\t\td3 = direction p1 p2 p3\n\t\td4 = direction p1 p2 p4\n\ndata Line = Line Point Point\n\nonLine r (Line p q) = sub p q `cross` sub p r == 0\n\nintersectsRay s@(Segment p1 p2) t@(Segment p3 p4) =\n\tintersects s t && not (p3 `onLine` (Line p1 p2))\n\nintersection s@(Segment sa sb) t@(Segment ta tb) = \n\t\tsa `add` (c `mult` (sa `sub` sb))\n\twhere\n\t\tmult a (Vector x y) = Vector (a * x) (a * y)\n\t\tadd (Point px py) (Vector vx vy) = Point (px + vx) (py + vy)\n\t\tc = (sub sa ta `cross` sub ta tb) / (sub sa sb `cross` sub ta tb)\n\ndistance (Point px py) (Point qx qy) = sqrt $ (qx - px) ** 2 + (qy - py) ** 2\n\nsolve start end polygon\n\t\t| length intersecting < 2 = start `distance` end\n\t\t| otherwise =\n\t\t\tstart `distance` i1 +\n\t\t\tminimum [distThrough, distAround1, distAround2] +\n\t\t\ti2 `distance` end\n\twhere\n\t\tstartEnd = Segment start end\n\t\tsegments = zipWith Segment polygon $ tail polygon ++ [head polygon]\n\n\t\tintersecting = filter (startEnd `intersectsRay`) segments\n\t\tintersections = map (intersection startEnd) intersecting\n\n\t\t(s1,i1):(s2,i2):_ = sortBy (compare `on` (distance start . snd)) $\n\t\t\t\tintersecting `zip` intersections\n\n\t\tdistThrough = 2 * (i1 `distance` i2)\n\n\t\tdistAround s1 s2 segments = sum $ map (\\(Segment p q) -> p `distance` q) $\n\t\t\ttakeWhile (/= s2) $ tail $ dropWhile (/= s1) $ segments ++ segments\n\n\t\tdistAround1 = \n\t\t\ti1 `distance` (segmentEnd s1) +\n\t\t\t(distAround s1 s2 segments) +\n\t\t\t(segmentStart s2) `distance` i2\n\n\t\tdistAround2 = \n\t\t\ti1 `distance` (segmentStart s1) +\n\t\t\t(distAround s1 s2 $ reverse segments) +\n\t\t\t(segmentEnd s2) `distance` i2\n\nmain = do\n\t[start, end] <- getPoints\n\t_ <- getLine\n\tpolygon <- getPoints\n\tprint $ solve start end polygon\n\n"}, {"source_code": "import Control.Applicative\nimport Data.Function\nimport Data.List\n\ndata Point = Point Double Double deriving (Eq)\ndata Segment = Segment { segmentStart, segmentEnd :: Point } deriving (Eq)\ndata Vector = Vector Double Double\n\ngetWords = map read . words <$> getLine\n\nsplitEvery n = unfoldr $ \\xs -> if null xs then Nothing else Just $ splitAt n xs\ngetPoints = map (\\[a, b] -> Point a b) . splitEvery 2 <$> getWords\n\ncross (Vector x1 y1) (Vector x2 y2) = x1*y2 - x2*y1\ndot (Vector x1 y1) (Vector x2 y2) = x1*x2 + y1*y2\nsub (Point px py) (Point qx qy) = Vector (qx - px) (qy - py)\n\nintersects s@(Segment p1 p2) t@(Segment p3 p4) =\n\t\t(d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) &&\n\t\t(d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0) ||\n\t\td1 == 0 && onSegment p1 t ||\n\t\td2 == 0 && onSegment p2 t ||\n\t\td3 == 0 && onSegment p3 s ||\n\t\td4 == 0 && onSegment p4 s\n\twhere\n\t\tdirection p q r = sub p r `cross` sub p q\n\n\t\tonSegment (Point rx ry) (Segment (Point px py) (Point qx qy)) =\n\t\t\tmin px qx <= rx && rx <= max px qx &&\n\t\t\tmin py qy <= ry && ry <= max py qy\n\n\t\td1 = direction p3 p4 p1\n\t\td2 = direction p3 p4 p2\n\t\td3 = direction p1 p2 p3\n\t\td4 = direction p1 p2 p4\n\ndata Line = Line Point Point\n\nonLine r (Line p q) = sub p q `cross` sub p r == 0\n\nintersectsRay s@(Segment p1 p2) t@(Segment p3 p4) =\n\tintersects s t && not (p3 `onLine` Line p1 p2)\n\nintersection s@(Segment sa sb) t@(Segment ta tb) = \n\t\tsa `add` (c `mult` (sa `sub` sb))\n\twhere\n\t\tmult a (Vector x y) = Vector (a * x) (a * y)\n\t\tadd (Point px py) (Vector vx vy) = Point (px + vx) (py + vy)\n\t\tc = (sub sa ta `cross` sub ta tb) / (sub sa sb `cross` sub ta tb)\n\ndistance (Point px py) (Point qx qy) = sqrt $ (qx - px) ** 2 + (qy - py) ** 2\n\nsolve start end polygon\n\t\t| length intersecting < 2 = start `distance` end\n\t\t| otherwise =\n\t\t\tstart `distance` i1 +\n\t\t\tminimum [distThrough, distAround1, distAround2] +\n\t\t\ti2 `distance` end\n\twhere\n\t\tstartEnd = Segment start end\n\t\tsegments = zipWith Segment polygon $ tail polygon ++ [head polygon]\n\n\t\tintersecting = filter (startEnd `intersectsRay`) segments\n\t\tintersections = map (intersection startEnd) intersecting\n\n\t\t(s1,i1):(s2,i2):_ = sortBy (compare `on` (distance start . snd)) $\n\t\t\t\tintersecting `zip` intersections\n\n\t\tdistThrough = 2 * (i1 `distance` i2)\n\n\t\tdistAround s1 s2 segments = sum $ map (\\(Segment p q) -> p `distance` q) $\n\t\t\ttakeWhile (/= s2) $ tail $ dropWhile (/= s1) $ segments ++ segments\n\n\t\tdistAround1 = \n\t\t\ti1 `distance` segmentEnd s1 +\n\t\t\tdistAround s1 s2 segments +\n\t\t\tsegmentStart s2 `distance` i2\n\n\t\tdistAround2 = \n\t\t\ti1 `distance` segmentStart s1 +\n\t\t\tdistAround s1 s2 (reverse segments) +\n\t\t\tsegmentEnd s2 `distance` i2\n\nmain = do\n\t[start, end] <- getPoints\n\t_ <- getLine\n\tpolygon <- getPoints\n\tprint $ solve start end polygon\n\n"}], "negative_code": [], "src_uid": "732c0e1026ed385888adde5ec8b764c6"} {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array ((!), listArray)\nimport Data.Char (ord)\nimport Data.Graph (buildG, edges, path)\nimport Data.List (intercalate)\n\ndata Query = Add Int Int | Path Int Int\n\nsolve :: [Query] -> [Bool]\nsolve qs = solve' 1 emptyG qs\n where\n n = length $ filter isAdd qs\n segments = listArray (1, n) $ filter isAdd qs\n isAdd (Add _ _) = True\n isAdd _ = False\n emptyG = buildG (1, 1) []\n solve' k graph [] = []\n solve' k graph (q:qs) = case q of\n (Add a b) -> solve' (k+1) graph' qs\n (Path a b) -> path graph a b : solve' k graph qs\n where\n graph' = buildG (1, k)\n $ edges graph ++ filter intersect ([(i, k) | i <- [1..k-1]] ++ [(k, i) | i <- [1..k-1]])\n intersect (i, j) = case (segments ! i, segments ! j) of\n (Add a b, Add c d) -> c < a && a < d || c < b && b < d\n\nmain :: IO ()\nmain = do\n n <- readLn\n qs <- replicateM n readQuery\n mapM_ (putStrLn . fromBool) $ solve qs\n\n where\n\n fromBool True = \"YES\"\n fromBool False = \"NO\"\n\n readQuery :: IO Query\n readQuery = do\n [q, a, b] <- reads\n case q of\n 1 -> return $ Add a b\n 2 -> return $ Path a b\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nrep :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\n{-# INLINE rep #-}\n\ntype Vertex = Int\n\nmain :: IO ()\nmain = do\n n <- readLn\n larr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)\n rarr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)\n used <- newArray (0,n-1) False :: IO (IOUArray Vertex Bool)\n\n let getInterval i = do\n !l <- unsafeRead larr i\n !r <- unsafeRead rarr i\n return $! (l,r)\n let isVertex (l,r) = (l,r) /= minBound\n let dfs v = do\n (l,r) <- getInterval v\n rep n $ \\i-> do\n flg <- unsafeRead used i\n unless flg $ do\n (nl,nr) <- getInterval i\n when (((nl unsafeWrite used i False\n unsafeWrite used start True\n dfs start\n res <- unsafeRead used goal\n if res then putStrLn \"YES\" else putStrLn \"NO\"\n let solve qs = go 1 qs\n where\n go !i (1:x:y:rest) = query1 i x y >> go (i+1) rest\n go !i (2:a:b:rest) = query2 a b >> go i rest\n go _ _ = return ()\n B.getContents >>= solve.map readInt.B.words\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nmain = do\n n <- read <$> getLine\n loop n 1 M.empty\n\nloop :: Int -> Int -> M.Map Int (Int,Int) -> IO ()\nloop 0 _ _ = return ()\nloop n i m = do\n c:x:y:_ <- map read . words <$> getLine\n case c of\n 1 -> loop (n-1) (i+1) (M.insert i (x,y) m)\n 2 -> do\n putStrLn $ if hasPath m x y then \"YES\" else \"NO\"\n loop (n-1) i m\n\nhasPath m from to = \n let s = snd $ runState (dfs m from) S.empty in\n S.member to s\n\ndfs m pos = do\n memo <- get\n case S.member pos memo of\n True -> return ()\n False -> do\n let l = next (m M.! pos) (M.assocs m)\n put (S.insert pos memo)\n mapM_ (dfs m) l\n \nnext :: (Int,Int) -> [(Int,(Int,Int))] -> [Int]\nnext (a,b) l = do\n (i,(c,d)) <- l\n if (c < a && a < d) || (c < b && b < d) then return i else []\n\nnewtype State a = State { runState :: S.Set Int -> (a,S.Set Int) }\n\ninstance Monad State where\n return x = State (\\s -> (x,s))\n m >>= f = State (\\s ->\n let (a,s') = runState m s in\n runState (f a) s')\n\nget = State (\\s -> (s,s))\nput s = State (\\_ -> ((),s))\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nrep :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\n{-# INLINE rep #-}\n\ntype Vertex = Int\n\nmain :: IO ()\nmain = do\n n <- readLn\n larr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)\n rarr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)\n used <- newArray (0,n-1) False :: IO (IOUArray Vertex Bool)\n\n let getInterval i = do\n !l <- unsafeRead larr i\n !r <- unsafeRead rarr i\n return $! (l,r)\n let isVertex (l,r) = (l,r) /= minBound\n let dfs v = do\n (l,r) <- getInterval v\n rep n $ \\i-> do\n flg <- unsafeRead used i\n unless flg $ do\n (nl,nr) <- getInterval i\n when (((nl unsafeWrite used i False\n unsafeWrite used start True\n dfs start\n res <- unsafeRead used goal\n if res then putStrLn \"YES\" else putStrLn \"NO\"\n let solve qs = go 1 qs\n where\n go !i (1:x:y:rest) = query1 i x y >> go (i+1) rest\n go !i (2:a:b:rest) = query2 a b >> go (i+1) rest\n go _ _ = return ()\n B.getContents >>= solve.map readInt.B.words\n"}], "src_uid": "c686c3592542b70a3b617eb639c0e3f4"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> String -> Int\nsolve n str = L.length groupsToInvert\n where\n bitGroups = L.group str\n groupsToInvert = L.dropWhile (\\g -> L.head g == '1') . L.dropWhile (\\g -> L.head g == '0') $ bitGroups\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n str <- B8.getLine <&> B8.filter isAlphaNum <&> B8.unpack\n let answer = solve n str\n printf \"%d\\n\" $ answer\n", "positive_code": [{"source_code": "import System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Functor\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . unwords . map show\r\n\r\nsolve' xs _ _ 0 = 0\r\nsolve' (x:xs) flipCount oneCount zeroCount\r\n | num == 1 = 1 + solve' xs (flipCount + 1) nextZero nextOne\r\n | otherwise = solve' xs flipCount nextOne nextZero\r\n where num = (x+flipCount) `mod` 2\r\n nextZero = if num == 0 then zeroCount - 1 else zeroCount\r\n nextOne = if num == 1 then oneCount - 1 else oneCount\r\n \r\n\r\nsolve xs = solve' xs 0 oneCount zeroCount\r\n where oneCount = sum xs\r\n zeroCount = length xs - sum xs\r\n\r\nmain = do\r\n [t] <- getInts\r\n forM_ [1..t] $ \\_ -> do\r\n _ <- getInts\r\n xs <- BS.getLine <&> (map digitToInt . filter (\\x -> x == '0' || x == '1') . BS8.unpack)\r\n print $ solve xs\r\n"}], "negative_code": [], "src_uid": "5278cb48aca6fc84e2df393cd8723ecb"} {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\") >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [a, b, k]\r\n | a == 1 && b == 1 = False\r\n | k == 1 = a /= b && (a `mod` b == 0 || b `mod` a == 0)\r\n | otherwise = k <= fac a + fac b\r\n\r\nprimes :: [Int]\r\nprimes = sieve [2 .. 4 * 10 ^ 4]\r\n where\r\n sieve [] = []\r\n sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)\r\n\r\nfac :: Int -> Int\r\nfac n =\r\n (\\(v, acc) -> acc + bool 1 0 (v == 1)) $\r\n foldl (\\(v, acc) p -> f v p acc) (n, 0) primes\r\n where\r\n f v p acc\r\n | v `mod` p /= 0 = (v, acc)\r\n | otherwise = f (v `div` p) p (acc + 1)\r\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nfactorize :: [Int] -> Int -> Int\r\nfactorize _ 1 = 0\r\nfactorize (d:ds) n\r\n | d * d > n = 1\r\n | n `mod` d == 0 = 1 + (factorize (d:ds) (n `div` d))\r\n | otherwise = factorize (ds) n\r\n\r\nprimes :: [Int]\r\nprimes = 2: 3: sieve (tail primes) [5,7..]\r\n where\r\n sieve (p:ps) xs = h ++ sieve ps [x | x <- t, x `rem` p /= 0]\r\n where (h,~(_:t)) = span (< p*p) xs\r\n\r\nprimeFactors :: Int -> Int\r\nprimeFactors = factorize primes\r\n\r\nsolve = do arr <- map read . words <$> getLine\r\n let times = arr !! 2\r\n let a = arr !! 0\r\n let b = arr !! 1\r\n let facta = primeFactors a\r\n let factb = primeFactors b\r\n let m = if a == b\r\n then 0\r\n else if ((a `mod` b) == 0)|| ((b `mod` a) == 0)\r\n then 1\r\n else 2\r\n let n = facta + factb\r\n putStrLn $ ans m n times\r\n\r\nans :: Int -> Int -> Int -> String\r\nans m n times\r\n | times == 1 && m == 1 && n >= 1 = \"Yes\"\r\n | times /= 1 && m <= times && n >= times = \"Yes\"\r\n | otherwise = \"No\"\r\n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Bits\nimport Data.List(group,sort)\n\nprimeArray :: Int -> UArray Int Bool\nprimeArray n = runSTUArray $ do\n let m = max 1 (shiftR n 1)\n dhm :: Double\n dhm = sqrt $ fromIntegral $ pred n\n hm = ceiling dhm\n a <- newArray (0, m) False :: ST s (STUArray s Int Bool)\n writeArray a 0 True\n forM_ [1 .. pred hm] $ \\p -> do\n l <- readArray a p\n unless l $ do\n let k = succ $ 2 * p\n loop j = when (j < m) $ do\n writeArray a j True\n loop (j + k)\n loop (2 * p * succ p)\n return a\n\nisprime :: UArray Int Bool -> Int -> Bool\nisprime p x = if even x then x == 2 else not (p ! shiftR x 1)\n\n\nprimes :: Int -> [Int]\nprimes n = 2 : filter ( not . (pa ! ) . (`shiftR` 1)) [3, 5 .. n]\n where\n pa = primeArray n\n\nfactors :: [Int] -> Int -> [Int]\nfactors p n = loop n p []\n where\n loop 1 _ r = r\n loop m l@(x:xs) r\n | x * x > m = m : r\n | mod m x == 0 = loop (div m x) l (x:r)\n | otherwise = loop m xs r\n\nfactorization :: [Int] -> Int -> [(Int, Int)]\nfactorization primes' n = map (\\l -> (head l, length l)) $ group $ factors primes' n\n\ndivisors :: [Int] -> Int -> [Int]\ndivisors primes' n = sort $ loop (factorization primes' n) 1 []\n where\n loop [] !m r = m : r\n loop ((!c, !p):xs) m r = snd $ (iterate f (m, r)) !! (p + 1)\n where\n f (!m', r') = (m' * c, loop xs m' r')\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\np = primes 32000 \n\nradd (u1, v1) (u2, v2) = (u1 + u2, v1 + v2)\n\nrng 1 = (0, 0)\nrng x = (1, sum $ map snd u)\n where\n u = factorization p x\n\ntest' :: Int -> Int -> Int -> Bool\ntest' a b k\n | k == 1 && a /= b && ((mod a b) == 0 || (mod b a) == 0) = True\n | fst r1 <= k && k <= snd r1 = True\n | g == 1 = False\n | otherwise = (min 2 (fst r2)) <= k && k <= snd r2\n where\n g = gcd a b\n a' = div a g\n b' = div b g\n r1 = radd (rng a') (rng b')\n rg = rng g\n rg2 = radd rg rg\n r2 = radd rg2 r1\n --r = if g > 1 then radd\n\nans True = byteString $ C.pack \"YES\"\nans False = byteString $ C.pack \"NO\"\n\nnl = char7 '\\n'\ntest :: Builder -> Int -> [Int] -> Builder\ntest buf 0 _ = buf\ntest buf nt (a:b:k:xs) = test (buf <> ans (test' a b k) <> nl) (pred nt) xs\n\nsolve :: [Int] -> Builder\nsolve (nt:xs) = test mempty nt xs\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\") >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [a, b, k]\r\n | 2 <= k && k <= fac a + fac b = True\r\n | k > fac a + fac b = False\r\n | otherwise = a /= b\r\n\r\nmx :: Int\r\nmx = 4 * 10 ^ 4\r\n\r\nprimes :: [Int]\r\nprimes = sieve [2 .. mx]\r\n where\r\n sieve [] = []\r\n sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)\r\n\r\nfac :: Int -> Int\r\nfac n =\r\n (\\(v, acc) -> acc + bool 1 0 (v == 1)) $\r\n foldl (\\(v, acc) p -> f v p acc) (n, 0) primes\r\n where\r\n f v p acc\r\n | v `mod` p /= 0 = (v, acc)\r\n | otherwise = f (v `div` p) p (acc + 1)\r\n "}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\") >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [a, b, k]\r\n | k == 1 = a `mod` b == 0 || b `mod` a == 0\r\n | otherwise = k <= fac a + fac b\r\n\r\nmx :: Int\r\nmx = 4 * 10 ^ 4\r\n\r\nprimes :: [Int]\r\nprimes = sieve [2 .. mx]\r\n where\r\n sieve [] = []\r\n sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)\r\n\r\nfac :: Int -> Int\r\nfac n =\r\n (\\(v, acc) -> acc + bool 1 0 (v == 1)) $\r\n foldl (\\(v, acc) p -> f v p acc) (n, 0) primes\r\n where\r\n f v p acc\r\n | v `mod` p /= 0 = (v, acc)\r\n | otherwise = f (v `div` p) p (acc + 1)\r\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\") >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [a, b, k]\r\n | a == b = k == 0\r\n | k == 1 = a `mod` b == 0 || b `mod` a == 0\r\n | otherwise = k <= fac a + fac b\r\n\r\nmx :: Int\r\nmx = 4 * 10 ^ 4\r\n\r\nprimes :: [Int]\r\nprimes = sieve [2 .. mx]\r\n where\r\n sieve [] = []\r\n sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)\r\n\r\nfac :: Int -> Int\r\nfac n = (\\(v, acc) -> acc + bool 1 0 (v == 1)) $ foldl f (n, 0) primes\r\n where\r\n f (v, acc) p\r\n | v `mod` p /= 0 = (v, acc)\r\n | otherwise =\r\n let (v', acc') = f (v `div` p, acc) p\r\n in (v', acc' + 1)\r\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\") >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [a, b, k]\r\n | a == b = k == 0\r\n | k == 1 = a `mod` b == 0 || b `mod` a == 0\r\n | otherwise = k <= fac a + fac b\r\n\r\nmx :: Int\r\nmx = 4 * 10 ^ 4\r\n\r\nprimes :: [Int]\r\nprimes = sieve [2 .. mx]\r\n where\r\n sieve [] = []\r\n sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)\r\n\r\nfac :: Int -> Int\r\nfac n = snd $ foldl f (n, 0) primes\r\n where\r\n f (v, acc) p\r\n | v `mod` p /= 0 = (v, acc)\r\n | otherwise =\r\n let (v', acc') = f (v `div` p, acc) p\r\n in (v', acc' + 1)\r\n"}, {"source_code": "import Control.Monad\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nfactorize :: Int -> Int -> [Int]\r\nfactorize _ 1 = []\r\nfactorize d n\r\n | d * d > n = [n]\r\n | n `mod` d == 0 = d : factorize d (n `div` d)\r\n | otherwise = factorize (d + 1) n\r\n\r\nprimeFactors :: Int -> [Int]\r\nprimeFactors = factorize 2\r\n\r\nsolve = do arr <- map read . words <$> getLine\r\n let times = arr !! 2\r\n let a = arr !! 0\r\n let b = arr !! 1\r\n let facta = length $ primeFactors a\r\n let factb = length $ primeFactors b\r\n putStrLn $ ans a b facta factb times\r\n\r\nans :: Int -> Int -> Int -> Int -> Int -> String\r\nans a b facta factb times\r\n | (a == 1) && (factb >= times) = \"Yes\"\r\n | (b == 1) && (facta >= times) = \"Yes\"\r\n | (a == 1) || (b == 1) = \"No\"\r\n | (times == 1) && (a == b) = \"No\"\r\n | (facta + factb) >= times = \"Yes\"\r\n | (times == 1) && ((a `mod` b) == 0) = \"Yes\"\r\n | (times == 1) && ((b `mod` a) == 0) = \"Yes\"\r\n | otherwise = \"No\"\r\n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Bits\nimport Data.List(group,sort)\n\nprimeArray :: Int -> UArray Int Bool\nprimeArray n = runSTUArray $ do\n let m = max 1 (shiftR n 1)\n dhm :: Double\n dhm = sqrt $ fromIntegral $ pred n\n hm = ceiling dhm\n a <- newArray (0, m) False :: ST s (STUArray s Int Bool)\n writeArray a 0 True\n forM_ [1 .. pred hm] $ \\p -> do\n l <- readArray a p\n unless l $ do\n let k = succ $ 2 * p\n loop j = when (j < m) $ do\n writeArray a j True\n loop (j + k)\n loop (2 * p * succ p)\n return a\n\nisprime :: UArray Int Bool -> Int -> Bool\nisprime p x = if even x then x == 2 else not (p ! shiftR x 1)\n\n\nprimes :: Int -> [Int]\nprimes n = 2 : filter ( not . (pa ! ) . (`shiftR` 1)) [3, 5 .. n]\n where\n pa = primeArray n\n\nfactors :: [Int] -> Int -> [Int]\nfactors p n = loop n p []\n where\n loop 1 _ r = r\n loop m l@(x:xs) r\n | x * x > m = m : r\n | mod m x == 0 = loop (div m x) l (x:r)\n | otherwise = loop m xs r\n\nfactorization :: [Int] -> Int -> [(Int, Int)]\nfactorization primes' n = map (\\l -> (head l, length l)) $ group $ factors primes' n\n\ndivisors :: [Int] -> Int -> [Int]\ndivisors primes' n = sort $ loop (factorization primes' n) 1 []\n where\n loop [] !m r = m : r\n loop ((!c, !p):xs) m r = snd $ (iterate f (m, r)) !! (p + 1)\n where\n f (!m', r') = (m' * c, loop xs m' r')\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\np = primes 32000 \n\nradd (u1, v1) (u2, v2) = (u1 + u2, v1 + v2)\n\nrng 1 = (0, 0)\nrng x = (1, sum $ map snd u)\n where\n u = factorization p x\n\ntest' :: Int -> Int -> Int -> Bool\ntest' a b k\n | fst r1 <= k && k <= snd r1 = True\n | g == 1 = False\n | otherwise = fst r2 <= k && k <= snd r2\n where\n g = gcd a b\n a' = div a g\n b' = div b g\n r1 = radd (rng a') (rng b')\n rg = rng g\n rg2 = radd rg rg\n r2 = radd rg2 r1\n --r = if g > 1 then radd\n\nans True = byteString $ C.pack \"YES\"\nans False = byteString $ C.pack \"NO\"\n\nnl = char7 '\\n'\ntest :: Builder -> Int -> [Int] -> Builder\ntest buf 0 _ = buf\ntest buf nt (a:b:k:xs) = test (buf <> ans (test' a b k) <> nl) (pred nt) xs\n\nsolve :: [Int] -> Builder\nsolve (nt:xs) = test mempty nt xs\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}], "src_uid": "b58a18119ac8375f9ad21a282292a76c"} {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ntype Long = Int\n\n\nsolve :: Double -> Double\nsolve n = 1 / tan (pi / (2* n))\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readWords\n print $ solve n\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine", "positive_code": [{"source_code": "main = interact $ g . map read . tail . words\n\nf n = 1/(tan (pi/(2*n)))\n\ng xs = unlines (map show (map f xs))\n"}, {"source_code": "import Data.List\n\nsolve :: Integer -> Double\nsolve n = 1/(tan (pi/(2* (fromIntegral n))))\n\nmain = interact $ \n (intercalate \"\\n\") \n . (map (show . solve . read))\n . (drop 1) \n . words\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do \n t <- readLn :: IO Int\n replicateM_ t routine \n\n\nroutine = do\n n <- readLn :: IO Int\n print $ solve n\n\nsolve :: Int -> Double\nsolve a\n -- odd side\n | mod a 2 == 1 = 2*side\n -- even height\n | otherwise = 2*height\n where \n height = (side ^ 2) * sin_given\n side = sin_theta / sin_given\n sin_given = sin (pi / fromIntegral a)\n sin_theta = sin (pi * (0.5*(1 - 1/fromIntegral a)))\n\n"}], "negative_code": [], "src_uid": "0c7a476716445c535a61f4e81edc7f75"} {"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\n{-\n -\n - meet 0 and \n - 1. ones is empty\n - add it to zeros.\n - 2. ones isn't empty\n - pop ones, and add it to zeros.\n - meet 1 and \n - 1. zeros is empty\n - add it to ones.\n - 2. zeros isn't empty\n - pop zeros, and add it to ones.\n -}\nsolve :: Int -> [Bool] -> [Int] -> [Int] -> [Int] \nsolve now_id (False:xs) zeros [] = now_id : solve (now_id+1) xs (now_id:zeros) [] \nsolve now_id (False:xs) zeros (o:ones) = o : solve now_id xs (o:zeros) ones \nsolve now_id (True:xs) [] ones = now_id : solve (now_id+1) xs [] (now_id:ones)\nsolve now_id (True:xs) (z:zeros) ones = z : solve now_id xs zeros (z:ones)\nsolve now_id _ _ _ = []\n\n\ndeal :: IO()\ndeal = do \n getLine\n a <- map (== '1') <$> getLine\n let answer = solve 1 a [] []\n print $ maximum answer\n putStrLn $ unwords $ map show answer\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List (unfoldr)\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Lazy as R\nimport Data.Word (Word8)\n\ntype ByteString = P.ByteString\n\nzeroChar :: Word8\nzeroChar = R.head $ P.singleton '0'\n\noneChar :: Word8\noneChar = R.head $ P.singleton '1'\n\nparseCases :: ByteString -> [ByteString]\nparseCases inp = go (tail $ P.lines inp) where\n go [] = []\n go (_nstr : s : excess) = s : go excess\n go _ = error \"malformed input\"\n\ntype State = (Int, Int, Int, ByteString)\nstep :: State -> Maybe (Int, State)\n-- Idea: pos - zeros is the number of subsequences so far which end in zero.\n-- ones - pos is the number of subsequences so far which end in one.\n-- new sequences with '0' are allocated non-negative indices,\n-- new sequences with '1' are allocated negative indices.\nstep (!pos, !zeros, !ones, !str) = case R.uncons str of\n Nothing -> Nothing\n Just (c, xs)\n | c == zeroChar -> Just (pos, (pos+1, zeros, max ones (pos+1), xs))\n | c == oneChar -> Just (pos-1, (pos-1, min zeros (pos-1), ones, xs))\n _ -> Nothing -- error \"malformed input\"\n\n-- hopefully String is fast enough\nsolveCase :: ByteString -> String\nsolveCase inp = let\n rawAnsSeq = unfoldr step (0, 0, 0, inp)\n low = minimum rawAnsSeq\n top = maximum rawAnsSeq\n subseqCount = top + 1 - low\n as = map (1 - low +) rawAnsSeq\n in unlines [show subseqCount, unwords (map show as)]\n\nmain :: IO ()\nmain = P.getContents >>= (putStr . concatMap solveCase . parseCases)\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> process\n >>> map (map show >>> unwords)\n >>> unlines\n\nprocess :: [String] -> [[Int]]\nprocess [] = []\nprocess (_ : xs : rest) = let (k, ss) = solve xs in [k] : ss : process rest\n\nsolve :: String -> (Int, [Int])\nsolve = (\\(_, _, ps, k) -> (k, ps)) . foldr pick ([], [], [], 0)\n where\n pick :: Char -> ([Int], [Int], [Int], Int) -> ([Int], [Int], [Int], Int)\n pick '0' (xs, [], ps, k) = ((k + 1) : xs, [], (k + 1) : ps, k + 1)\n pick '0' (xs, y : ys, ps, k) = (y : xs, ys, y : ps, k)\n pick '1' ([], ys, ps, k) = ([], (k + 1) : ys, (k + 1) : ps, k + 1)\n pick '1' (x : xs, ys, ps, k) = (xs, x : ys, x : ps, k)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n s <- map (== '1') <$> getLine\n let a = solve 1 [] [] s\n print $ maximum a\n putStrLn $ unwords $ map show a\n\nsolve next (z : zs) os (False : s) = z : solve next zs (z : os) s\nsolve next [] os (False : s) = next : solve (succ next) [] (next : os) s\nsolve next zs (o : os) (_ : s) = o : solve next (o : zs) os s\nsolve next zs [] (_ : s) = next : solve (succ next) (next : zs) [] s\nsolve _ _ _ _ = []\n"}, {"source_code": "import Control.Monad\n\nrec :: Int -> [Int] -> [Int] -> [Bool] -> [Int]\nrec next (z : zs) os (False : s) = z : rec next zs (z : os) s\nrec next [] os (False : s) = next : rec (succ next) [] (next : os) s\nrec next zs (o : os) (_ : s) = o : rec next (o : zs) os s\nrec next zs [] (_ : s) = next : rec (succ next) (next : zs) [] s\nrec _ _ _ _ = []\n\nsolve :: IO ()\nsolve = do\n getLine\n s <- map (== '1') <$> getLine\n let a = rec 1 [] [] s\n print $ maximum a\n putStrLn $ unwords $ map show a\n\nmain :: IO ()\nmain = do\n getLine >>= flip replicateM_ solve . read\n "}], "negative_code": [], "src_uid": "de57b6b1aa2b6ec4686d1348988c0c63"} {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n print . minSteps n\n\nminSteps :: Int -> [Int] -> Int\nminSteps n (a:as) = foldl (\\acc e -> acc + minStep a e) 0 as\n\nminStep :: Int -> Int -> Int\nminStep x y = let f = -1+div y (2*x-1) in\n if f < 0\n then 0\n else f + (if mod y (2*x-1) > 0 then 1 else 0)\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\ntoShow [] = \"\"\r\ntoShow (x:xs) = show x ++ \" \" ++ toShow xs\r\n\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n let mi = minimum a\r\n\r\n putStrLn.show.sum .map ((`div` (2*mi-1)).subtract 1) $ a\r\n return ()"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n],xs] <- replicateM 2 ri\r\n return xs\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve xs = sum . map cntSplit $ xs\r\n where\r\n m = minimum xs\r\n mx = m*2 - 1\r\n cntSplit x = ((x+mx-1) `div` mx) - 1\r\n"}, {"source_code": "import Data.Char\n\nsecond (x:y:xs) = y : second xs;\nsecond _ = []\n\n\npieces n k\n | mod k (2*n-1) == 0 = div k (2*n-1) \n | otherwise = div k (2*n-1) +1\n\nmoves n k = pieces n k - 1\nsolve xs = sum $ map (moves n) ks where\n n = head xs\n ks = tail xs\n\n\nmain = do\n rawInput <- getContents\n let input = (second . tail) $ lines rawInput \n let ls = map ((map read) . words) input :: [[Int]]\n let output = map solve ls\n putStr (unlines $ map show output)\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n--\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> [Int] -> Int\nsolve n as = sum steps\n where\n minA = minimum as\n steps = map stepsFor as\n stepsFor x = (x + d - 1) `div` d - 1\n where d = 2 * minA - 1\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "import Control.Monad\r\n\r\ntoShow [] = \"\"\r\ntoShow (x:xs) = show x ++ \" \" ++ toShow xs\r\n\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n let mi = minimum a\r\n\r\n putStrLn.show.sum .map (if mi==1 then subtract 1 else (`div` (2*mi-1))) $ a\r\n return ()"}], "src_uid": "128d9ad5e5dfe4943e16fcc6a103e51b"} {"source_code": "main :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\treturn ()\r\n\t\r\nsolve :: Int -> Int -> IO ()\r\nsolve number 0 = return ()\t\r\nsolve number current = \tdo\r\n\t\t\t\tline <- getLine\r\n\t\t\t\tif length line < 3 \r\n\t\t\t\t\tthen do \r\n\t\t\t\t\t\tputStrLn $ [(last line)]\r\n\t\t\t\t\t\tsolve number (current - 1)\r\n\t\t\t\t else do\r\n\t\t\t\t\t\tputStrLn $ [(foldr min '9' line)]\r\n\t\t\t\t\t\tsolve number (current - 1)", "positive_code": [{"source_code": "module Main (main)\nwhere\n\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = intercalate \"\\n\" <$> map show <$> map solve <$> map readInts <$> (read <$> getLine >>= readNLines) >>= putStrLn\n\nreadNLines :: Int -> IO [String]\nreadNLines n = sequence $ replicate n getLine\n\nreadInts :: String -> [Int]\nreadInts s = foldr (\\x acc -> (ord x - 48):acc) [] s\n\n-- [Int] at least two digits\nsolve :: [Int] -> Int\nsolve [a, b] = b\nsolve xs = minimum xs\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [caseNum] <- getInts\n output <- fmap mconcat $ forM [1..caseNum] $ \\_ -> do\n s <- filter (not . isSpace) . C.unpack <$> C.getLine\n return $ char7 (if length s == 2 then s !! 1 else minimum s) <> char7 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int\nsolve n = solve' digits\n where\n digits = map (\\c -> ord c - ord '0') $ show n\n solve' = \\case\n [a] -> a\n [a, b] -> b\n ds -> foldr1 min ds\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n a <- B8.getLine <&> readIntB8\n let answer = solve a \n printf \"%d\\n\" answer\n"}, {"source_code": "import Data.Char\n\nsolve :: String -> Char\nsolve number = if length number == 2\n then number !! 1\n else chr (minimum (map ord number))\n\nmainLoop 0 = return ()\nmainLoop t = do number <- getLine\n putStrLn [solve number]\n mainLoop (t - 1)\n\nmain = do t <- (readLn :: IO Int)\n mainLoop t\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [caseNum] <- getInts\n output <- fmap mconcat $ forM [1..caseNum] $ \\_ -> do\n s <- C.unpack <$> C.getLine\n return $ char7 (if length s == 2 then s !! 1 else minimum s) <> char7 '\\n'\n hPutBuilder stdout output\n"}], "src_uid": "adf024899fb2a684427463733358566a"} {"source_code": "import qualified Data.Set as Set \n\nsplitComma :: String -> [String]\nsplitComma [] = [\"\"]\nsplitComma (x:xs)\n | x == ',' = \"\" : splitComma xs\n | otherwise = (x : head rest) : tail rest\n where rest = splitComma xs\n\ntoString :: [(Int,Int)] -> String\ntoString [] = \"\"\ntoString ((a,b):xs) \n | a /= b = if xs /= [] then show a ++ \"-\" ++ show b ++ \",\" ++ toString xs else show a ++ \"-\" ++ show b \n | otherwise = if xs /= [] then show a ++ \",\" ++ toString xs else show a \n\ntoListofTuples :: [Int] -> [(Int,Int)]\ntoListofTuples [] = [] \ntoListofTuples [a] = [(a,a)] \ntoListofTuples (a:b:xs)\n | a + 1 == b = (a , result) : toListofTuples new_list \n | otherwise = (a,a) : toListofTuples (b:xs)\n where result = maxN (b:xs) a\n new_list = filter (>result) (b:xs)\n\nmaxN :: [Int] -> Int -> Int\nmaxN (x:xs) a\n | xs == [] && a+1 == x = a+1\n | xs == [] && a+1 /= x = a\n | a + 1 == x = maxN xs (a+1) \n | otherwise = a \n \nmain = do\n input <- getLine -- \"1,2,3,1,1,2,6,6,2\"\n let splitted_input = splitComma input \n let int_list = map read splitted_input :: [Int] -- [1,2,3,1,1,2,6,6,2]\n let set = Set.fromList int_list\n let result_list = Set.toList set -- [1,2,3,6]\n let tupleLists = toListofTuples result_list\n let result = toString tupleLists \n putStrLn result", "positive_code": [{"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\ngroups :: [Char] -> Int -> [Char]\ngroups \"\" i = show i\ngroups palabra i = do\n if (lastSymbol 0 palabra==\"-\")\n then (sinLastNumber palabra)++[x|x<-show i, (lastNumber palabra+1)==i]++[x|x<-(show (lastNumber palabra)++[',']++show i), (lastNumber palabra +1)/=i]\n else palabra++[x|x<-['-']++show i, (lastNumber palabra+1)==i]++[ x|x<-[',']++show i, (lastNumber palabra +1)/=i]\n\naddComa::[Char]-> Int->[Char]\naddComa palabra _ = [last palabra]++\",\"\n\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\n\nsinLastNumber::[Char]->[Char]\nsinLastNumber s= reverse(dropWhile (isDigit) (reverse s))\n\nlastSymbol:: Int->[Char]->[Char]\nlastSymbol 0 s= lastSymbol 1 (reverse s) \nlastSymbol 1 \"\" = \"\"\nlastSymbol 1 (x:xs)= do\n if(isDigit x)\n then lastSymbol 1 xs\n else [x] \ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain= do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= foldl groups \"\" sortedSet \n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List hiding(group)\nimport qualified Data.Set as S\n\n\ngroup :: [Char] -> Int -> [Char]\ngroup \"\" i = show i\ngroup palabra i = do\n if (lastSymbol 0 palabra==\"-\")\n then (sinLastNumber palabra)++[x|x<-show i, (lastNumber palabra+1)==i]++[x|x<-(show (lastNumber palabra)++[',']++show i), (lastNumber palabra +1)/=i]\n else palabra++[x|x<-['-']++show i, (lastNumber palabra+1)==i]++[ x|x<-[',']++show i, (lastNumber palabra +1)/=i]\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\n\nsinLastNumber::[Char]->[Char]\nsinLastNumber s= reverse(dropWhile (isDigit) (reverse s))\n\nlastSymbol:: Int->[Char]->[Char]\nlastSymbol 0 s= lastSymbol 1 (reverse s) \nlastSymbol 1 \"\" = \"\"\nlastSymbol 1 (x:xs)= do\n if(isDigit x)\n then lastSymbol 1 xs\n else [x] \ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain= do\n line<-getLine\n let sortedSet = S.fromList (map read $ words $deleteComas line :: [Int])\n let finalString= foldl group \"\" (S.toList sortedSet) \n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n\n\ngrouping s [] _= s\ngrouping s (x:xs) flag= do\n if(flag)\n then if(lastNumber s ==(x-1))\n then grouping (reverse (drop (length(show (lastNumber s))) (reverse s)) ++ show x) xs True\n else grouping (s++\",\") (x:xs) False\n else if(xs==[])\n then grouping (s++ show x) xs False \n else if(x==(head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List hiding(group)\nimport qualified Data.Set as S\n\n\ngroup :: [Char] -> Int -> [Char]\ngroup \"\" i = show i\ngroup palabra i = do\n if (lastSymbol 0 palabra==\"-\")\n then (sinLastNumber palabra)++[x|x<-show i, (lastNumber palabra+1)==i]++[x|x<-(show (lastNumber palabra)++[',']++show i), (lastNumber palabra +1)/=i]\n else palabra++[x|x<-['-']++show i, (lastNumber palabra+1)==i]++[ x|x<-[',']++show i, (lastNumber palabra +1)/=i]\n\naddComa::[Char]-> Int->[Char]\naddComa palabra _ = [last palabra]++\",\"\n\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\n\nsinLastNumber::[Char]->[Char]\nsinLastNumber s= reverse(dropWhile (isDigit) (reverse s))\n\nlastSymbol:: Int->[Char]->[Char]\nlastSymbol 0 s= lastSymbol 1 (reverse s) \nlastSymbol 1 \"\" = \"\"\nlastSymbol 1 (x:xs)= do\n if(isDigit x)\n then lastSymbol 1 xs\n else [x] \ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain= do\n line<-getLine\n let sortedSet = S.fromList (map read $ words $deleteComas line :: [Int])\n let finalString= foldl group \"\" (S.toList sortedSet) \n putStrLn $ id finalString\n \n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getLine >>= putStrLn . drop 4 . solve (-1) (-1) . sort . read . ('[':) . (++\"]\")\n\nsolve :: Int -> Int -> [Int] -> String\nsolve k l [] | k < l = ',' : show k ++ '-' : show l\n | otherwise = ',' : show k\nsolve k l (x:xs) | l + 1 < x = solve k l [] ++ solve x x xs\n | otherwise = solve k x xs\n"}, {"source_code": "import Data.Set\n\n --funcion split copiada de https://jmmv.dev/2006/08/split-function-in-haskell.html\nstringSplit :: String -> Char -> [String]\nstringSplit [] delim = [\"\"]\nstringSplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = stringSplit cs delim\n\n\n--funcion que convierte el input ya separado por comas a un set de enteros\ntoIntSet :: [String] -> Set Int\ntoIntSet nums = Prelude.foldl (\\s n-> insert (read n :: Int) s) empty nums\n\n\n-- funcion group pedida en las instrucciones. Debido a que esta funci\u00f3n ser\u00e1 ocupada\n-- con un foldl de un Set, se asume que los numeros van a venir en orden ascendiente\n-- debido a esto solo se necesita mirar al ultimo elemento de la lista de tuplas\ngroup :: [(Int, Int)] -> Int -> [(Int, Int)]\ngroup [] n = [(n, n)] --caso inicial\ngroup ranges n = let\n -- se toma el \u00faltimo elemento de la lista de tuplas\n (x1,x2) = last ranges\n\n -- si n pertenece al \u00faltimo rango en la lista, se a\u00f1ade a \u00e9ste, de lo contrario\n -- se crea un nuevo rango \n in if n == x2 + 1 then (init ranges)++[(x1,n)] else ranges++[(n,n)]\n\n\n-- Funci\u00f3n que transforma los rangos a strings en el formato pedido \nrangeToString :: (Int, Int) -> String\nrangeToString (x1, x2)\n | x1 == x2 = show x1 -- todos los rangos de la forma n,n pasan a \"n\"\n |otherwise = (show x1)++\"-\"++(show x2) -- todos los rangos de la forma a,b pasan a \"a-b\"\n\n-- Funci\u00f3n que recibe el string de input y retorna un string formateado\nformatString :: String -> String\nformatString unformated = let\n uniqueNums = toIntSet $ stringSplit unformated ',' -- set con todos los numeros\n ranges = Data.Set.foldl (group) [] uniqueNums --pasa el set a una lista de rangos\n formated = Prelude.foldl (\\s tup -> s++(rangeToString tup)++\",\") \"\" ranges\n in init formated -- se bota el \u00faltimo elemento ya que es una coma\n\nmain :: IO ()\nmain = do\n unformated <- getLine\n putStrLn (formatString unformated)\n "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.List as List\nimport Data.Function\n\nmain = do\n line <- getLine \n let list = split line ','\n let set = Set.fromList list\n let pages = Set.elems set\n let sortedPages = sortNumeric pages\n let newPages = group sortedPages (read (head sortedPages) :: Int)\n let strPages = List.intercalate \",\" newPages\n putStrLn strPages\n\nsortNumeric = List.sortBy (compare `on` (read :: String -> Int))\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\n\ngroup :: [String] -> Int -> [String]\ngroup [] posAnterior = [\"\"]\ngroup (x:xs) posAnterior \n | pos == posAnterior = if xs == [] then [x] else (if (nextPos /= succ pos) then (x : rest) else ((x ++ head rest) : tail rest))\n | pos == succ posAnterior = if xs == [] then [\"-\" ++ x] else (if (nextPos /= succ pos) then ((\"-\" ++ x) : rest) else rest)\n | otherwise = if xs == [] then [x] else (if (nextPos /= succ pos) then (x : rest) else (x ++ head rest) : tail rest)\n where\n pos = (read x :: Int)\n nextPos = (read (head xs) :: Int)\n rest = group xs pos"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.List as List\nimport Data.Function\n\nmain = do\n line <- getLine \n let list = split line ','\n let set = Set.fromList list\n let pages = Set.elems set\n let sortedPages = sortNumeric pages\n let newPages = foldl group [] sortedPages\n let reversedPages = reverse newPages\n let strPages = List.intercalate \",\" reversedPages\n putStrLn strPages\n\nsortNumeric = List.sortBy (compare `on` (read :: String -> Int))\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\n\ngroup :: [String] -> String -> [String]\ngroup [] pos = [pos]\ngroup (a:as) pos\n | newPos-1 == ant = (ant2 ++ \"-\" ++ pos) : as\n | otherwise = pos : (a:as)\n where\n newPos = (read pos :: Int)\n ant = (read (last (split a '-')) :: Int) \n ant2 = head (split a '-')"}, {"source_code": "import Data.Set\n\n --funcion split copiada de https://jmmv.dev/2006/08/split-function-in-haskell.html--\nstringSplit :: String -> Char -> [String]\nstringSplit [] delim = [\"\"]\nstringSplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = stringSplit cs delim\n\n\ntoIntSet :: [String] -> Set Int\ntoIntSet nums = Prelude.foldl (\\s n-> insert (read n :: Int) s) empty nums\n\ngroup :: [(Int, Int)] -> Int -> [(Int, Int)]\ngroup [] n = [(n, n)]\ngroup ranges n = let\n (x1,x2) = last ranges\n in if n == x2 + 1 then (init ranges)++[(x1,n)] else ranges++[(n,n)]\n\nrangeToString :: (Int, Int) -> String\nrangeToString (x1, x2)\n | x1 == x2 = show x1\n |otherwise = (show x1)++\"-\"++(show x2)\n\nformatString :: String -> String\nformatString unformated = let\n uniqueNums = toIntSet $ stringSplit unformated ','\n ranges = Data.Set.foldl (group) [] uniqueNums\n formated = Prelude.foldl (\\s tup -> s++(rangeToString tup)++\",\") \"\" ranges\n in init formated\n\nmain :: IO ()\nmain = do\n unformated <- getLine\n putStrLn (formatString unformated)\n "}, {"source_code": "import qualified Data.Set as Set\n\n-- La funcion rep reemplaza todas las comas en el String dado por espacios.\nrep :: String -> String\nrep \"\" = \"\"\nrep (',':xs) = \" \" ++ rep (xs)\nrep (x:xs) = [x] ++ rep (xs)\n\n-- La funcion group se encarga de construir el String deseado\ngroup :: [String] -> Int -> [String]\ngroup [] n = \"-\":(show n):[] --Si la lista esta vacia (Que siempre lo estara al inicio) se agrega la Int n como String y un guion.\ngroup (\"-\":x:xs) n\n | (read x) == (pred n) = (show n):\"-\":restofList -- Si x es predecesor de n, se agrega n en la cabeza.\n | otherwise = \"-\":(show n):\",\":restofList -- En caso contrario, se reemplaza el guion por una coma, y se agrega n y un guion.\n where restofList = (x:xs)\ngroup (x:xs) n\n | (read x) == (pred n) = (show n):xs -- Si x es predecesor de n, se reemplaza x por n.\n | otherwise = \"-\":(show n):\",\":x:xs -- En caso contrario, se agrega una coma, n y un guion.\n\n-- Al terminar la funcion group la nueva lista puede contener un guion a la cabeza. Esta funcion lo elimina si esta presente.\neraseThing :: [String] -> [String]\neraseThing (\"-\":xs) = xs\neraseThing x = x\n\nmain :: IO ()\nmain = do\n line <- getLine\n let lineList = map (read :: String -> Int) ((words . rep) line) --Se usa rep y words para separar la String en una lista. Luego se usa map y read para convertirlo en una lista de Int\n let newSet = Set.fromList lineList --Se transforma la lista en Set\n let newList = foldl (group) [] newSet --Se utiliza foldl para construir la String con group, dando una lista vacia y el Set\n let groupLine = (concat . reverse) (eraseThing newList) --Se usa reverse y se concatena la lista, obteniendo el String deseado\n putStr (groupLine)"}, {"source_code": "import qualified Data.Set as Set\n\nqsort :: (Ord t) => [t] -> [t]\nqsort [] = []\nqsort (x:xs) = let\n\t\t\t\tleft = filter (<=x) xs\n\t\t\t\tright = filter (>x) xs\n\t\t\t\tin qsort left ++ [x] ++ qsort right\n-----------------------------------------------------------------------------\n--function that transform e.g \",1,2,3\" in \"1-3\"\nfx :: String -> String\nfx acc = if first_one == last_one then first_one else first_one++\"-\"++last_one\n\t\t\twhere\n\t\t\t\tfirst_one = head (tail (split' ',' acc))\n\t\t\t\tlast_one = last (split' ',' acc)\n-----------------------------------------------------------------------------\n-- function who says if num is succ of acc'\nfn :: String -> Int -> Bool\nfn acc' num = let\t\t\t--acc' is a string with the last number read\n\t\t\t\tlast' = read acc' :: Int\n\t\t\t\tin if last' + 1 == num then True else False\n\n-----------------------------------------------------------------------------\n-- Function asked in LP\ngroup :: [String] -> Int -> [String]\ngroup [] num = [\",\"++show num]\ngroup acc num = if fn acc' num then init acc ++ [last_element ++ \",\"++show num] else acc ++ [\",\"++show num]\n\t\t\t\twhere\n\t\t\t\t\tlast_element = last acc\n\t\t\t\t\tacc' = last (split' ',' last_element)\n\n-----------------------------------------------------------------------------\n-- Reduce all the string to the format asked in the problem, e.g \",1,2,3\" -> \"1-3\" (in other words, map)\nget' :: [String] -> [String]\nget' xs = [fx i | i <- xs]\n\n-----------------------------------------------------------------------------\n-- Map input to a integer list\ngetNumbers :: [String] -> [Int]\ngetNumbers input = [read i :: Int | i <- input]\t\t\n\n-----------------------------------------------------------------------------\n-- group all numbers from input (in a set as integers)\ntoGroup :: (Foldable t) => t Int -> [String]\ntoGroup set = foldl group [] set\n\n-----------------------------------------------------------------------------\n--Concatenate all the strings in xs\nconcatenate :: [String] -> String\nconcatenate xs = foldl1 (\\acc x -> acc++\",\"++x) xs\n\n-----------------------------------------------------------------------------\n--I couldn't use splitOn from Data.List.Split so i create my own split'\nsplit' :: Eq a => a -> [a] -> [[a]]\nsplit' x y = func x y [[]]\n where\n func x [] z = reverse $ map (reverse) z\n func x (y:ys) (z:zs) = if y==x then \n func x ys ([]:(z:zs)) \n else \n func x ys ((y:z):zs)\n \n-----------------------------------------------------------------------------\nmain = do\n\t\tinput <- getLine\n\t\tlet input' = Set.fromList(getNumbers (split' ',' input))\n\t\tlet result = get' (toGroup input')\n\t\tputStrLn (concatenate result)\n"}, {"source_code": " import qualified Data.Set as Set\n import Data.List\n stringSplit :: String -> Char -> [String]\n stringSplit [] delim = [\"\"]\n stringSplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = stringSplit cs delim\n ggroup :: [String] -> Int -> [String]\n ggroup list i\n |(length list == 0) = [show i]\n |(elem '-' (last list)) == True = if (stringSplit (last list) '-') !! 1 == show(pred i) then init list ++ [(stringSplit (last list) '-' !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n |otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\n main :: IO ()\n main = do\n line <- getLine\n let list = stringSplit line ',' \n let intList = map (read::String->Int) list \n let set = Set.fromList intList \n let solution = foldl ggroup [] set \n let parte1 = [a ++ \",\"| a <- (init solution)] \n let parte2 = parte1 ++ [(last solution)] \n let output = foldl1 (++) parte2 \n putStrLn output"}, {"source_code": " import qualified Data.Set as Set\n import Data.List\n stringSplit :: String -> Char -> [String]\n stringSplit [] delim = [\"\"] --Funcion para hacer split, obtenida en https://jmmv.dev/2006/08/split-function-in-haskell.html\n stringSplit (c:cs) delim -- Ya que codeforce no deja usar Data.List.Split\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = stringSplit cs delim\n ggroup :: [String] -> Int -> [String] --Funcion group necesaria para hacer trabajar el programa, se nombre ggroup debido a que usar group tra\u00eda problemas en la compilaci\u00f3n\n ggroup list i\n |(length list == 0) = [show i]\n |(elem '-' (last list)) == True = if (stringSplit (last list) '-') !! 1 == show(pred i) then init list ++ [(stringSplit (last list) '-' !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n |otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\n main :: IO ()\n main = do --Aca hacemos funcionar el programa, trabajamos con el input y hacemos las transformaciones necesarias para el funcionamiento.\n line <- getLine\n let list = stringSplit line ',' \n let intList = map (read::String->Int) list \n let set = Set.fromList intList \n let solution = foldl ggroup [] set \n let parte1 = [a ++ \",\"| a <- (init solution)] --Armamos el output, exceptuando el final para evitar terminar con la ,\n let parte2 = parte1 ++ [(last solution)] --Ultima parte del output\n let output = foldl1 (++) parte2 \n putStrLn output"}, {"source_code": "import qualified Data.Set as Set\n\nqsort :: (Ord t) => [t] -> [t]\nqsort [] = []\nqsort (x:xs) = let\n\t\t\t\tleft = filter (<=x) xs\n\t\t\t\tright = filter (>x) xs\n\t\t\t\tin qsort left ++ [x] ++ qsort right\n-----------------------------------------------------------------------------\nfx :: String -> String\nfx acc = if first_one == last_one then first_one else first_one++\"-\"++last_one\n\t\t\twhere\n\t\t\t\tfirst_one = head (tail (split' ',' acc))\n\t\t\t\tlast_one = last (split' ',' acc)\n-----------------------------------------------------------------------------\nfn :: String -> Int -> Bool\nfn acc' num = let\t\t\t--acc' is a string with the last number read\n\t\t\t\tlast' = read acc' :: Int\n\t\t\t\tin if last' + 1 == num then True else False\n\n-----------------------------------------------------------------------------\ngroup :: [String] -> Int -> [String]\ngroup [] num = [\",\"++show num]\ngroup acc num = if fn acc' num then init acc ++ [last_element ++ \",\"++show num] else acc ++ [\",\"++show num]\n\t\t\t\twhere\n\t\t\t\t\tlast_element = last acc\n\t\t\t\t\tacc' = last (split' ',' last_element)\n\n-----------------------------------------------------------------------------\nget' :: [String] -> [String]\nget' xs = [fx i | i <- xs]\n\n-----------------------------------------------------------------------------\ngetNumbers :: [String] -> [Int]\ngetNumbers input = [read i :: Int | i <- input]\t\t\n\n-----------------------------------------------------------------------------\nget_fucking_set :: (Foldable t) => t Int -> [String]\nget_fucking_set set = foldl group [] set\n\n-----------------------------------------------------------------------------\nconcatenate :: [String] -> String\nconcatenate xs = foldl1 (\\acc x -> acc++\",\"++x) xs\n\n-----------------------------------------------------------------------------\nsplit' :: Eq a => a -> [a] -> [[a]]\nsplit' x y = func x y [[]]\n where\n func x [] z = reverse $ map (reverse) z\n func x (y:ys) (z:zs) = if y==x then \n func x ys ([]:(z:zs)) \n else \n func x ys ((y:z):zs)\n \n-----------------------------------------------------------------------------\nmain = do\n\t\tinput <- getLine\n\t\tlet input' = Set.fromList(getNumbers (split' ',' input))\n\t\tlet input'' = get_fucking_set input'\n\t\tlet result = get' input''\n\t\tputStrLn (concatenate result)\n"}, {"source_code": "-- Desktop\\USM\\LPs\\Haskell\nimport qualified Data.Set as Set\nimport Data.List\nimport System.IO\n\nsplit :: String -> [String] -- Nos apoyamos de https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit [] = [\"\"]\nsplit (co:cs) \n | (co == ',') = \"\" : resto\n | otherwise = (co : head resto) : tail resto\n where resto = Main.split cs\n\nrango :: String -> Bool\nrango \"\" = False\nrango (xo:xs)\n | (xo == '-') = True\n | otherwise = rango xs\n \ngroup :: [String] -> Int -> [String] --Funcion pedida del tipo a -> b -> a\ngroup paginas xo\n | paginas == [] = [show xo] -- show: http://zvon.org/other/haskell/Outputprelude/show_f.html\n | ((rango (head paginas) == False) && ((read (head paginas)) :: Int) + 1 == xo) = [head paginas ++ \"-\" ++ show xo] ++ tail paginas\n | ((rango (head paginas) == False) && ((read (head paginas)) :: Int) + 1 /= xo) = [show xo] ++ paginas\n | ((rango (head paginas) == True) && (num == xo)) = [takeWhile (/='-') (head paginas) ++ \"-\" ++ show xo] ++ tail paginas\n | ((rango (head paginas) == True) && (num /= xo)) = [show xo] ++ paginas\n where\n num = (read (tail (dropWhile (/='-') (head paginas))) :: Int) + 1\n\nlista_a_Int :: [String] -> [Int]\nlista_a_Int [] = []\nlista_a_Int (xo:xs) = (read xo :: Int) : lista_a_Int xs\n\nqsort :: [Int] -> [Int]\nqsort [] = []\nqsort (yo:ys) = qsort ysLeft ++ [yo] ++ qsort ysRight\n where\n ysLeft = [a|a <- ys, a <= yo]\n ysRight = [a|a <- ys, a > yo]\n\nmain :: IO ()\nmain = do\n input <- getLine --recibo el input como una lista\n let lista = Main.split input --se hace el split \n let lista_int = lista_a_Int lista --se convierte a una lista de enteros \n let lista_ordenada = qsort lista_int --ordenamos la lista ocupando funci\u00f3n aprendida en clases\n let set = Set.fromList lista_ordenada --se convierte a set, de esta forma no hay repetidos\n let set_2 = Set.foldl Main.group [] set --iterar con un foldl sobre set \n let set_3 = Data.List.reverse set_2\n let string = Data.List.intercalate \",\" set_3\n putStrLn string\n"}, {"source_code": "import System.IO\nimport Data.Set\nimport System.Environment\nimport Data.List as Li\n\n\ncut :: String -> Char -> [String]\ncut [] delim = [\"\"]\ncut (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = cut cs delim\n\nqsort:: [Integer] -> [Integer]\nqsort [] = []\nqsort (x:xs) = qsortleft ++ [x] ++ qsortright\n where qsortleft = qsort [alpha | alpha <-xs, alpha <=x]\n qsortright = qsort [gamma | gamma <-xs, gamma > x]\n\n\nbuildList :: String -> [String]\nbuildList arr =\n if arr == \"\" then\n let args = [\"\"] in args\n else do\n let newarr = cut arr ',' in newarr\n\n\nmarx :: [[Integer]] -> Integer -> [[Integer]]\nmarx [] n = [[n]]\nmarx [x] n =\n if n -1 == last x\n then\n let list = x++[n] in [list]\n else\n [x]++[[n]]\nmarx (x:xs) n =\n if n -1 == (last x)\n then\n let list = x++[n] in list:xs\n else\n let lists = x:(marx xs n) in lists\n\n\nbonito::[String]->[Integer]->[String]\nbonito s range =\n if head range == last range\n then let r = show (head range) in s++[r]\n else\n let r = show (head range)++\"-\"++show(last range) in s++[r]\n\nmain = do\n array_n <- getLine\n let str = buildList array_n\n set = fromList str\n listp = toList set\n lastlist = Prelude.map read listp :: [Integer]\n ordlist = qsort lastlist\n final = Li.foldl marx [] ordlist\n listcute = Li.intercalate \",\" (Li.foldl bonito [] final)\n putStrLn listcute\n"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.Text as T\n\ngroup :: String -> Int -> String\ngroup \"\" num = \"\" ++ show num\ngroup str num\n -- Si tenemos el sucesor y ya teniamos secuencia cambiar el numero de la secuencia\n | succ (read (last (split '-' ult)) :: Int) == num && length ult > 1 && elem '-' ult = replaceNum str num\n -- Si tenemos el sucesor, agregar '-' y luego el numero\n | succ (read (last (split '-' ult)) :: Int) == num = str ++ \"-\" ++ show num\n -- Cualquier otro caso extender con ',' y el siguiente numero\n | otherwise = str ++ \",\" ++ show num\n where ult = (last $ split ',' str)\n\nreplaceNum :: String -> Int -> String\nreplaceNum str num = let pre = pred num\n toRepl = T.pack(show pre)\n repl = T.pack (show num)\n string = T.pack (str)\n in T.unpack(T.replace toRepl repl string)\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\ntoInt :: Char -> Int\ntoInt c = read (c : []) :: Int \n\nmain = do\n inp <- getLine\n let a = concatMap (\\x -> if x == ',' then \" \" else [x]) inp -- Remplazar comas por espacios para usar words\n let set = S.fromList (map read $ words a :: [Int])\n putStrLn (S.foldl group \"\" set)"}, {"source_code": "import Data.List (sort)\nimport Data.Set as Set\n\n\n\n--esta funcion entrega el ultimo numero consecutivo\n--por ejemplo si le pasamos [1,2,3,6] entrega 3 ya que 1->2->3-/>6 en 3 terminan los numeros concecutivos\nsecuencia :: [Int]->Int\nsecuencia x = case x of\n [a] -> a\n (a:as) -> if((a+1)==(head as)) then (secuencia as) else a\n \n--esta funcion agrupa las secuencias en una lista de truplas de dos elementos \n--[(Inicio Secuencia),(Final Secuencia)] si un numero es menor al final de la secuencia\n--si un numero es menor al final de la secuencia significa que esta dentro de esta\ngroup :: [Int] -> Int -> [(Int,Int)]\ngroup x ultimoSec = case x of\n [] -> []\n (a:as) -> if a<=(ultimoSec) then (group as ultimoSec) \n else [(a,secuencia x)] ++ (group as (secuencia x))\n --[(secuencia 1),(secuencia 2), ..., (secuencia n) ]\n\n--se genera el string de las secuencias\nstringGroup :: [(Int, Int)] -> String\nstringGroup xs = (Prelude.foldl (\\s (a,b) ->(\n --si se termino la secuencia actual, se va a la siguiente\n if ((a,b)/=(head xs)) then s ++ \",\" \n else s) ++ (\n --si el inicio de la secuencia y el final son iguales, entonces la secuencia es de un solo numero\n --si son distintas entonces es una secuencia de mas de un numero, por lo que:\n -- se imprime Inicio-final\n if (a/=b) then ((show a) ++ \"-\" ++ (show b)) \n else (show a))) \n \"\" xs)\n \n--funcion split de https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit_at :: String -> Char -> [String]\nsplit_at [] delim = [\"\"]\nsplit_at (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split_at cs delim\n \nmain :: IO ()\nmain = do \n input <- getLine\n let spl = split_at input ','\n let lista = (Prelude.map (read::String->Int) spl)\n let conjNums = Set.fromList lista\n let list1 = toList conjNums\n let grupo = group list1 0\n let final = stringGroup grupo\n putStrLn (final)"}, {"source_code": "import Data.List (sort)\nimport Data.Set as Set\n\nsplit_at :: String -> Char -> [String]\nsplit_at [] delim = [\"\"]\nsplit_at (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split_at cs delim\n\n\nstrGroup:: [(Bool, Bool)] -> [Int] -> String\nstrGroup [(x,y)] [a] = show a \nstrGroup (c:cs) (x:xs) = case c of \n (True,True) -> (strGroup cs xs)\n (True,False) -> (show x) ++ \",\" ++ (strGroup cs xs)\n (False,True) -> show(x) ++ \"-\" ++ (strGroup cs xs)\n (False,False) -> (show x) ++ \",\" ++ (strGroup cs xs)\n\nmain :: IO ()\nmain = do \n input <- getLine\n let lista = (Prelude.map (read::String->Int) (split_at input ','))\n let conjutoNums = Set.fromList lista\n let list1 = toList conjutoNums\n let grupo = scanl (\\x y -> (elem (pred y) lista,elem (succ y) lista) ) (False, False) list1\n let final = strGroup (tail grupo) list1\n putStrLn (final)"}, {"source_code": "import Data.List (sort)\nimport Data.Set as Set\n\n--prueba\n\nsecuencia :: [Int]->Int\nsecuencia x = case x of\n [a] -> a\n (a:as) -> if((a+1)==(head as)) then (secuencia as) else a\n\ngroup :: [Int] -> Int -> [(Int,Int)]\ngroup x ultimoSec = case x of\n [] -> []\n (a:as) -> if a<=(ultimoSec) then (group as ultimoSec) \n else [(a,secuencia x)] ++ (group as (secuencia x))\n\nstringGroup :: [(Int, Int)] -> String\nstringGroup xs = (Prelude.foldl (\\s (a,b) ->(\n if ((a,b)/=(head xs)) then s ++ \",\" \n else s) ++ (\n if (a/=b) then ((show a) ++ \"-\" ++ (show b)) \n else (show a))) \n \"\" xs)\n\nsplit_at :: String -> Char -> [String]\nsplit_at [] delim = [\"\"]\nsplit_at (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split_at cs delim\n\nmain :: IO ()\nmain = do \n input <- getLine\n let spl = split_at input ','\n let lista = (Prelude.map (read::String->Int) spl)\n let conjNums = Set.fromList lista\n let list1 = toList conjNums\n let grupo = group list1 0\n let final = stringGroup grupo\n putStrLn (final)\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:xs) = (solve a) ++ \"\\n\" ++ (func xs)\nfunc [] = \"\"\n\ntoInt::String->Integer\ntoInt = read\n\ntoString::Integer->String\ntoString = show\n\nwords' \"\" = []\nwords' s = let (l, s') = break (== ',') s\n in l : case s' of\n [] -> []\n (_:s'') -> words' s''\n\nsolve = init.foldr conc \"\".map tostr.foldr hoge [].map head.group.sort.map toInt.words'\n where\n hoge y [] = [(y,y)]\n hoge y ((a,b):xs) = if (y+1) == a\n then (y,b):xs\n else (y,y):(a,b):xs\n tostr (l,r) | l==r = toString l\n | otherwise = (toString l) ++\"-\"++(toString r)\n conc [] b = b\n conc a b = a++\",\"++b\n"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\n \nmain :: IO()\nmain = do\n input <- getLine\n let inputList = split input ','\n let intList = map(read::String->Int) inputList \n let dataSetList = Set.toList (Set.fromList intList) \n let flipList = foldl (flip (:)) [] dataSetList\n let lastList = foldl group [] flipList\n let returnList = showTuples lastList\n putStrLn returnList\n \nshowTuples :: [(Int, Int)] -> String\nshowTuples [] = \"\"\nshowTuples ((x,y):xs)\n |null xs = (if x == y then show x else show x ++ \"-\" ++ show y)\n |otherwise = (if x == y then show x ++ \",\" ++ showTuples(xs) else show x ++ \"-\" ++ show y ++ \",\" ++ showTuples(xs))\n \n--Fuente: https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)]\ngroup ((x,y):xs) n\n |x-1 == n = ((n,y):xs)\n |otherwise = [(n,n)] ++ ((x,y):xs)"}, {"source_code": "import qualified Data.Set as S \n\nsplitfunc :: String -> [String] --C&P de StackOverflow: https://stackoverflow.com/questions/46580924/haskell-splitting-a-string-by-delimiter \n\nsplitfunc [] = [\"\"]\nsplitfunc (c:cs) | c == ',' = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where rest = splitfunc cs\n\ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)] \ngroup ((a,b):xs) n = \n if a-1 == n\n then ((n,b):xs)\n else [(n,n)] ++ ((a,b):xs)\n\n\nconvert :: [(Int,Int)] -> String\nconvert ((a,b):xs) =\n if null xs -- Si xs es null, no se agrega \",\" al final.\n then if a == b\n then show a\n else show a ++ \"-\" ++ show b\n else if a == b\n then show a ++ \",\" ++ convert(xs)\n else show a ++ \"-\" ++ show b ++ \",\" ++ convert(xs)\nmain :: IO()\nmain = do\n line <- getLine\n let linelist = splitfunc line \n let intlist = map(read::String->Int) linelist\n let dataset = S.fromList intlist\n let settolist = S.toList dataset\n let finallist = foldl (flip (:)) [] settolist -- Se da vuelta la lista, para trabajar con la cabeza\n let final = foldl group [] finallist\n let a = convert final\n putStrLn a\n\n\n"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\n \nmain :: IO()\nmain = do\n input <- getLine\n let inputList = split input ','\n let intList = map(read::String->Int) inputList \n let dataSetList = Set.toList (Set.fromList intList) \n let flipList = reverse dataSetList\n let lastList = foldl group [] flipList\n let returnList = showTuples lastList\n putStrLn returnList\n \nshowTuples :: [(Int, Int)] -> String\nshowTuples [] = \"\"\nshowTuples ((x,y):xs)\n |null xs = (if x == y then show x else show x ++ \"-\" ++ show y)\n |otherwise = (if x == y then show x ++ \",\" ++ showTuples(xs) else show x ++ \"-\" ++ show y ++ \",\" ++ showTuples(xs))\n \n--Fuente: https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)]\ngroup ((x,y):xs) n\n |x-1 == n = ((n,y):xs)\n |otherwise = [(n,n)] ++ ((x,y):xs)"}, {"source_code": "import qualified Data.Set as S \n\nsplitfunc :: String -> [String] --C&P de StackOverflow: https://stackoverflow.com/questions/46580924/haskell-splitting-a-string-by-delimiter \n\nsplitfunc [] = [\"\"]\nsplitfunc (c:cs) | c == ',' = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where rest = splitfunc cs\n\ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)] \ngroup ((a,b):xs) n = \n if a-1 == n\n then ((n,b):xs)\n else [(n,n)] ++ ((a,b):xs)\n\n\nconvert :: [(Int,Int)] -> String\nconvert ((a,b):xs) =\n if null xs -- Si xs es null, no se agrega \",\" al final.\n then if a == b\n then show a\n else show a ++ \"-\" ++ show b\n else if a == b\n then show a ++ \",\" ++ convert(xs)\n else show a ++ \"-\" ++ show b ++ \",\" ++ convert(xs)\nmain :: IO()\nmain = do\n line <- getLine\n let linelist = splitfunc line -- Str to Strlist\n let intlist = map(read::String->Int) linelist -- Strlist to Intlist\n let dataset = S.fromList intlist -- Intlist to Data.Set\n let settolist = S.toList dataset -- Data.set to List\n let finallist = foldl (flip (:)) [] settolist -- Descending order list\n let final = foldl group [] finallist\n let a_retornar = convert final\n putStrLn a_retornar\n\n\n"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\n \nmain :: IO()\nmain = do\n input <- getLine\n let inputList = split input ','\n let intList = map(read::String->Int) inputList \n let dataSet = Set.fromList intList\n let dataSetList = Set.toList (Set.fromList intList) \n let flipList = foldl (flip (:)) [] dataSetList\n let lastList = foldl group [] flipList\n let returnList = showTuples lastList\n putStrLn returnList\n \nshowTuples :: [(Int, Int)] -> String\nshowTuples [] = \"\"\nshowTuples ((x,y):xs)\n |null xs = (if x == y then show x else show x ++ \"-\" ++ show y)\n |otherwise = (if x == y then show x ++ \",\" ++ showTuples(xs) else show x ++ \"-\" ++ show y ++ \",\" ++ showTuples(xs))\n \n \n--Fuente: https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)]\ngroup ((x,y):xs) n\n |x-1 == n = ((n,y):xs)\n |otherwise = [(n,n)] ++ ((x,y):xs)"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\nimport Data.Function\n\n--Se divide la palabra inicial en comas para generar una lista \ndividirpalabra :: String -> Char -> [String]\ndividirpalabra[] x = [\"\"]\ndividirpalabra (c:cs) x\n | c == x = \"\" : resto\n | otherwise = (c : head resto) : tail resto\n where\n resto = dividirpalabra cs x\n\n--Se ordena la lista de numeros\nordenar = List.sortBy(compare`on`(read :: String -> Int))\n\n--Funcion group que genera la lista con \"-\" entre si cuando hay paginas juntas\ngroup :: [String] -> Int -> [String]\ngroup []posicionprevia =[\"\"]\ngroup (x:xs)posicionprevia \n |posicion == posicionprevia = \n if xs == [] \n then [x] \n else (if(posicionposterior /= succ posicion) \n then (x : resto) \n else ((x ++ head resto) : tail resto))\n |posicion == succ posicionprevia = \n if xs == [] \n then [\"-\"++ x] \n else (if (posicionposterior /= succ posicion) \n then ((\"-\"++ x) : resto) \n else resto)\n |otherwise = \n if xs == [] \n then [x] \n else (if (posicionposterior /= succ posicion) \n then (x:resto) \n else (x ++ head resto) : tail resto)\n where\n posicion = (read x :: Int)\n posicionposterior = (read(head xs) :: Int)\n resto = group xs posicion\n\nmain = do\n numeros <- getLine \n let lista = dividirpalabra numeros ',' --Se obtiene la palabra y se quitan las comas\n let convertirlista = Set.fromList lista\n let elementos = Set.elems convertirlista \n let listaordenada = ordenar elementos --Se genera una lista ordenada con los numeros\n let listaordenada2 = group listaordenada(read(head listaordenada):: Int)\n let listafinal = List.intercalate \",\" listaordenada2 --Se genera una lista con las paginas juntas y luego se colocan las comas entre medio\n putStrLn listafinal"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\n \nmain :: IO()\nmain = do\n input <- getLine\n let inputList = split input ','\n let intList = map(read::String->Int) inputList \n --let dataSet = Set.fromList intList\n let dataSetList = Set.toList (Set.fromList intList) \n let flipList = foldl (flip (:)) [] dataSetList\n let lastList = foldl group [] flipList\n let returnList = showTuples lastList\n putStrLn returnList\n \nshowTuples :: [(Int, Int)] -> String\nshowTuples [] = \"\"\nshowTuples ((x,y):xs)\n |null xs = (if x == y then show x else show x ++ \"-\" ++ show y)\n |otherwise = (if x == y then show x ++ \",\" ++ showTuples(xs) else show x ++ \"-\" ++ show y ++ \",\" ++ showTuples(xs))\n \n \n--Fuente: https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)]\ngroup ((x,y):xs) n\n |x-1 == n = ((n,y):xs)\n |otherwise = [(n,n)] ++ ((x,y):xs)"}, {"source_code": "import Data.List (sort, intercalate, (\\\\))\n\nmain = do\n input <- getLine\n putStrLn $ fix input\n\nwordsBy :: (Char -> Bool) -> String -> [String]\nwordsBy p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsBy p s''\n where (w, s'') = break p s'\n\ndelMults :: (Eq a) => [a] -> [a]\ndelMults [] = []\ndelMults (x:xs) = x : ( delMults $ dropWhile (==x) xs )\n\ngather :: [Int] -> [[Int]]\ngather [] = []\ngather xs = a : gather (xs \\\\ a)\n\t\twhere a = takeCont xs (head xs)\n\ntakeCont :: [Int] -> Int -> [Int]\ntakeCont [] n = []\ntakeCont (x:xs) n = if x==n then x : takeCont xs (n+1) else []\n\nsimplify :: (Show a) => [a] -> String\nsimplify [x] = show x\nsimplify xs = (show . head) xs ++ \"-\" ++ (show . last) xs\n\nfix :: String -> String\nfix s = intercalate \",\" $ map simplify $ gather $ delMults $ sort $ map read $ wordsBy (==',') s"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n xs <- read . (\"[\" ++) . (++ \"]\") <$> getLine\n let n : ns = map head . group . sort $ xs :: [Int]\n let conv acc@(a, b) (c : cs)\n | b + 1 == c = conv (a, c) cs\n | otherwise = acc : conv (c, c) cs\n conv acc [] = [acc]\n pages = conv (n , n) ns\n s = do\n (i, j) <- pages\n if i == j\n then printf \"%d,\" i\n else printf \"%d-%d,\" i j :: String\n printf \"%s\\n\" (init s)\n\n"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\n \nmain :: IO()\nmain = do\n input <- getLine\n let inputList = split input ','\n let intList = map(read::String->Int) inputList \n let dataset = Set.fromList intList\n let dataSetList = Set.toList (Set.fromList intList) \n let flipList = foldl (flip (:)) [] dataSetList\n let lastList = foldl group [] flipList\n let returnList = showTuples lastList\n putStrLn returnList\n \nshowTuples :: [(Int, Int)] -> String\nshowTuples [] = \"\"\nshowTuples ((x,y):xs)\n |null xs = (if x == y then show x else show x ++ \"-\" ++ show y)\n |otherwise = (if x == y then show x ++ \",\" ++ showTuples(xs) else show x ++ \"-\" ++ show y ++ \",\" ++ showTuples(xs))\n \n \n--Fuente: https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)]\ngroup ((x,y):xs) n\n |x-1 == n = ((n,y):xs)\n |otherwise = [(n,n)] ++ ((x,y):xs)"}, {"source_code": "import qualified Data.Set as Set\nimport Data.List\n--Funciones que me servir\u00e1n para \"limpiar\" el input de la forma \"1,2,3,44\" a [\"1\",\"2\",\"3\",\"44\"]\n--y para pasar de \"1-2\" a [\"1\", \"2\"]\nsplitComma :: String -> [String]\nsplitComma s = let\n s2 = map (\\c -> if c==',' then ' ' else c) s\n in words s2\nsplitGuion :: String -> [String]\nsplitGuion s = let\n s2 = map (\\c -> if c=='-' then ' ' else c) s\n in words s2\n--Funci\u00f3n principal, itero con un foldl sobre el conjunto de n\u00fameros. Este conjunto est\u00e1 ordenado en contiene Ints.\n--La idea es ir agregando uno por uno los elementos del Set a una lista\n--Hay 3 casos principales de ingreso:\n--1: Si la lista que retornar\u00e1 groupp est\u00e1 vac\u00eda, entonces llego e ingreso el valor\n--2: Si no est\u00e1 vac\u00eda solo me interesar\u00e1 el \u00faltimo elemento, si este es de la forma \"a\" (y no \"a-b\") analizo si el elmento que\n-- voy a ingresar es el sucesor de \"a\", si es el sucesor entonces modifico el ultimo de la lista por \"a-i\" donde i es el\n-- n\u00famero que voy a ingresar en esa iteraci\u00f3n. Si no es el sucesor simplemente la lista crece pues agrego una nueva posici\u00f3n\n-- de la forma \"i\" usando show.\n--3: Si el \u00faltimo elemento de la lista es de la forma \"a-b\" entonces hago el splitGuion para obtener [\"a\", \"b\"] y analizar si\n-- i es el sucesor de b, en ese caso modifico el \u00faltimo elemento por \"a-i\",de lo contrario la lista crece pues agrego una\n-- nueva posici\u00f3n de la forma \"i\".\ngroupp :: [String] -> Int -> [String]\ngroupp list i\n |(length list == 0) = [show i]\n |(elem '-' (last list)) == True = if (splitGuion (last list)) !! 1 == show(pred i) then init list ++ [(splitGuion (last list) !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n |otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\nmain = do\n line <- getLine\n let splittedList = splitComma line --almaceno el input en una lista de la forma [\"1\",\"2\",\"3\",\"6\"] por ejemplo\n let newList = [read a::Int | a <- splittedList] --paso los elementos de la lista a Int\n let mySet = Set.fromList newList --paso la lista a Set (quedan ordenados los elementos y adem\u00e1s ordenados)\n let solution = foldl groupp [] mySet --obtengo la soluci\u00f3n del problema pero en forma [\"1-3\",\"6\"] por ejemplo\n let output1 = [a ++ \",\"| a <- (init solution)] --obtengo [\"1-3,\"]\n let output2 = output1 ++ [(last solution)] --agrego \"6\" y obtengo [\"1-3,\",\"6\"]\n let output3 = foldl1 (++) output2 -- obtengo \"1-3,6\"\n putStrLn output3"}, {"source_code": "--ghc problema1.hs -o problema1\n-- ./problema1\nimport qualified Data.Set as Set\nimport Data.List\nsplitComma :: String -> [String]\nsplitComma s = let\n s2 = map (\\c -> if c==',' then ' ' else c) s\n in words s2\nsplitGuion :: String -> [String]\nsplitGuion s = let\n s2 = map (\\c -> if c=='-' then ' ' else c) s\n in words s2\ngroupp :: [String] -> Int -> [String]\ngroupp list i\n |(length list == 0) = [show i]\n |(elem '-' (last list)) == True = if (splitGuion (last list)) !! 1 == show(pred i) then init list ++ [(splitGuion (last list) !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n |otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\nmain = do\n line <- getLine\n let splittedList = splitComma line\n let newList = [read a::Int | a <- splittedList]\n let mySet = Set.fromList newList\n let solution = foldl groupp [] mySet\n let output1 = [a ++ \",\"| a <- (init solution)]\n let output2 = output1 ++ [(last solution)]\n let output3 = foldl1 (++) output2\n putStrLn output3"}, {"source_code": "import qualified Data.Set as S\n--import Data.List.Split (splitOn)\nimport Data.List (intercalate)\n\nsplitOn :: Char -> String -> [String]\nsplitOn r str = words [if c == r then ' ' else c | c <- str]\n\ngroup :: [String] -> Int -> [String]\ngroup [] i = [show i]\ngroup (x:xs) i = if splitOn '-' x == [x] then\n if x == show (i-1)\n then (x ++ \"-\" ++ show i):xs\n else (show i):x:xs\n else let\n [x1,x2] = splitOn '-' x\n in if x2 == show (i-1)\n then (x1 ++ \"-\" ++ show i):xs\n else (show i):x:xs\n\n\nlistIt :: String -> IO String\nlistIt str = do\n let pageList = map read (splitOn ',' str) :: [Int]\n let pageSet = S.fromList pageList\n let ret = reverse (foldl group [] pageSet)\n return (intercalate \",\" ret)\n\nmain :: IO ()\nmain = do\n x <- getLine\n ret <- listIt x\n putStrLn ret"}, {"source_code": "--import qualified Data.Set as Set\n--import qualified Data.List.Split (splitOn)\nimport Data.List (sort,nub)\n--import Data.Set (fromList)\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\ngroup :: [Int] -> Int -> [(Int,Int)]-- Este group lo que hace es entregar una lista de tuplas un numero y su siguiente ej 1 2 3 1 1 5 = [(1,3),(5,5)]\ngroup x z = case x of\n [] -> []\n (y:ys) -> if y<=(z) then (group ys z) \n else [(y,siguiente_num x)] ++ (group ys (siguiente_num x))\n\nsiguiente_num :: [Int] -> Int\nsiguiente_num x = case x of\n [x] -> x\n (x:xs) -> if ((x+1)==(head xs)) then (siguiente_num xs) \n\t\t\t\telse x\ngroup_guion:: String -> (Int,Int) -> String-- este lo que hace es tomar la lista de group y escribirlo como el formato de salida\ngroup_guion \"\" (x1,x2) = if x1 == x2 then show (x1)\n else show(x1)++\"-\"++show(x2)\ngroup_guion palabra (x1,x2) = if x1 == x2 then palabra ++ (\",\" ++ show (x1))\n else palabra ++ (\",\" ++ show(x1)++\"-\"++show(x2))\n\nmain:: IO()\nmain = do\n\trs <- getLine\n\tlet lista_numero = sort (nub (map (read:: String -> Int ) (split rs ',')))\n\t--let conjunto = Set.fromList lista_numero\n\tlet rangos = group lista_numero 0\n\tlet rangos_string = foldl group_guion [] rangos\n\tputStrLn rangos_string\n"}, {"source_code": "import qualified Data.Set as Set\nimport Data.List\n\nstringSplit :: String -> Char -> [String]\nstringSplit [] delim = [\"\"]\nstringSplit (c:cs) delim\n\t| c == delim = \"\" : rest\n\t| otherwise = (c : head rest) : tail rest\n\twhere\n\t\t\trest = stringSplit cs delim\n\ngroupp :: [String] -> Int -> [String]\ngroupp list i\n\t|(length list == 0) = [show i]\n\t|(elem '-' (last list)) == True = if (stringSplit (last list) '-') !! 1 == show(pred i) then init list ++ [((stringSplit (last list) '-') !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n\t|otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tlet list = stringSplit line ','\n\tlet intList = map (read::String->Int) list\n\tlet set = Set.fromList intList\n\tlet setList = Set.toList set\n\tlet solution = foldl groupp [] setList\n\tlet output1 = [a ++ \",\"| a <- (init solution)]\n\tlet output2 = output1 ++ [(last solution)]\n\tlet output3 = foldl1 (++) output2\n\tputStrLn output3\n"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n--Funci\u00f3n pedida por la tarea, separa las p\u00e1ginas en tuplas (n,m) si son un rango o (n,n)\n--Si n no pertenece a un rango \ngroup :: [(Int, Int)] -> Int -> [(Int, Int)]\ngroup [] p = [(p, p)] \ngroup pages p = let\n (p1,p2) = last pages\n \n in if p == p2 + 1 then (init pages) ++ [(p1,p)] else pages ++ [(p,p)]\n\n-- Usada para crear la lista con los puros numeros\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim \n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \n\n-- funcion que me escribe el output m\u00e1s una coma al final\nwriter::[(Int, Int)] -> String\nwriter [] = \"\"\nwriter ((p1,p2):xs) = if p1 == p2 then show p1 ++ \",\" ++ writer xs else show p1 ++ \"-\" ++ show p2 ++ \",\" ++ writer xs \n\n-- funcion para parsear a lista de Int\nreader :: [String] -> [Int]\nreader = map read\n--Funci\u00f3n de internet que us\u00e9 para quitar la coma del final de mi output\n\nremLast::String -> String\nremLast \"\" = \"\"\nremLast cs = init cs\n\n\n\n-- main medio confuso, pero lo explicar\u00e9\nmain :: IO ()\nmain = do\n rawdata <- getLine --input\n let ldata1 =split rawdata ',' -- separo por comas y creo la lista de String\n let ldata2 = reader ldata1 -- Parseo la lista de Int a String\n let sdata = Set.fromList ldata2 -- Lo pedido de pasar a Set\n let ldata3 = Set.toList sdata -- Vuelvo a parsear a Lista por comodidad y \n --porque no hay necesidad de seguir trabajando con set\n let finalPages = foldl (group) [] ldata3 -- Hago fold sobre mi lista de tuplas y me apollo de group\n let output = writer finalPages --ocupo mi lista obtenida del foldl group y la pongo como output\n let output2 = remLast output -- arreglo el output quitando la ultima coma\n putStrLn output2 "}, {"source_code": "import qualified Data.Set as Set\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\nmain = do \n input <- getLine\n let out = Set.fromList $ map (read::String->Int) (wordsWhen (==',') input)\n let out' = Set.foldl group [\"\",\"\"] out\n if last (wordsWhen (==',')(head out')) == last out' \n then putStrLn $ head out'\n else putStrLn $ head out' ++ \"-\" ++ last out'\n\ngroup :: [String] -> Int -> [String]\ngroup acc x\n | acc == [\"\",\"\"] = [show x, show x]\n | x == (read (last acc) :: Int) + 1 = [head acc, show x]\n | last (wordsWhen (==',') (head acc)) == last acc = [head acc ++ \",\" ++ show x, show x]\n | otherwise = [head acc ++ \"-\" ++ last acc ++ \",\" ++ show x, show x]"}, {"source_code": "import qualified Data.Set as Set\n\n-- Lista que retorna una tupla de boleanos.\n-- Los boleanos indican si en la lista se encuentran los antecesores o sucesores de un numero\n-- en la lista.\npredSucc :: [Int] -> Int -> (Bool, Bool)\npredSucc [] _ = (False, False)\npredSucc (x:xs) e = if (((succ e) `elem` (x:xs)) && ((pred e) `elem` (x:xs))) then (True, True) else (if(((pred e) `elem` (x:xs))) then (True, False) else (if(((succ e) `elem` (x:xs))) then (False, True) else (False, False)))\n\nprintFinal :: [String] -> String\nprintFinal [] = \"\"\nprintFinal (x:xs) = if (('-' `elem` x) && ((length xs) > 0)) then ((x) ++ printFinal(xs)) else (if (x == \"\") then ((\"\") ++ printFinal(xs)) else (if ((length xs) > 0) then ((x) ++ (\",\") ++ (printFinal(xs))) else (x ++ (printFinal(xs))) ))\n\nboolText :: (Bool, Bool) -> Int -> String\nboolText (True, True) x = \"\"\nboolText (True, False) x = (show x)\nboolText (False, True) x = (show x) ++ \"-\"\nboolText (False, False) x = (show x)\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\ngroup :: [Int] -> [String]\ngroup (x:xs) = scanl (\\a b -> (boolText (predSucc (x:xs) b) b) ) \"\" (x:xs)\n\nmain = do\n input <- getLine\n let listString = (wordsWhen (==',') input)\n let setInt = Set.fromList (map (read::String->Int) (listString))\n let listInt = Set.toList setInt\n putStrLn(printFinal (group listInt))"}, {"source_code": "import qualified Data.Set as Set\n\ngroup :: [Int] -> Int -> (Bool, Bool)\ngroup [] _ = (False, False)\ngroup (x:xs) e\n | (((succ e) `elem` (x:xs)) && ((pred e) `elem` (x:xs))) = (True, True)\n | ((pred e) `elem` (x:xs)) = (True, False)\n | ((succ e) `elem` (x:xs)) = (False, True) \n | otherwise = (False, False)\n\ngroupList :: [Int] -> [(Bool, Bool)]\ngroupList (x:xs) = tail (scanl (\\a b -> (group (x:xs) (fromIntegral b))) (False, False) (x:xs))\n\nboolText :: [(Bool, Bool)] -> [Int] -> String\nboolText [] [] = \"\"\nboolText ((a, b):xs) (y:ys)\n | ((a == True) && (b == True)) = \"\" ++ (boolText xs ys)\n | ((a == True) && (b == False) && (length ys) > 0) = \"-\" ++ (show y) ++ \",\" ++ (boolText xs ys)\n | ((a == True) && (b == False) && (length ys) == 0) = \"-\" ++ (show y) ++ (boolText xs ys)\n | ((a == False) && (b == True)) = (show y) ++ (boolText xs ys)\n | ((a == False) && (b == False) && (length ys) > 0) = (show y) ++ \",\" ++ (boolText xs ys)\n | otherwise = (show y) ++ (boolText xs ys)\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\nmain = do\n input <- getLine\n let listString = (wordsWhen (==',') input)\n let setInt = Set.fromList (map (read::String->Int) (listString))\n let listInt = Set.toList setInt\n putStrLn(boolText (groupList listInt) listInt)"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n \ngroup :: [(Int, Int)] -> Int -> [(Int, Int)]\ngroup [] p = [(p, p)] \ngroup pages p = let\n (p1,p2) = last pages\n \n in if p == p2 + 1 then (init pages) ++ [(p1,p)] else pages ++ [(p,p)]\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim \n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \nwriter::[(Int, Int)] -> String\nwriter [] = \"\"\nwriter ((p1,p2):xs) = if p1 == p2 then show p1 ++ \",\" ++ writer xs else show p1 ++ \"-\" ++ show p2 ++ \",\" ++ writer xs \n\n \nreader :: [String] -> [Int]\nreader = map read\n\nremLast::String -> String\nremLast \"\" = \"\"\nremLast cs = init cs\n\nmain :: IO ()\nmain = do\n rawdata <- getLine\n let ldata1 =split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let finalPages = foldl (group) [] ldata3\n let output = writer finalPages\n let output2 = remLast output\n putStrLn output2 "}, {"source_code": "import qualified Data.Set as Set\n\n-- Funci\u00f3n group, se le entrega una lista y un n\u00famero, la funci\u00f3n retorna una tupla de booleanos\n-- Indicando si tiene predecesor o sucesor respectivamente.\ngroup :: [Int] -> Int -> (Bool, Bool)\ngroup [] _ = (False, False)\ngroup (x:xs) e\n | (((succ e) `elem` (x:xs)) && ((pred e) `elem` (x:xs))) = (True, True)\n | ((pred e) `elem` (x:xs)) = (True, False)\n | ((succ e) `elem` (x:xs)) = (False, True) \n | otherwise = (False, False)\n\n-- Crea una lista de groups para todos los elementos.\ngroupList :: [Int] -> [(Bool, Bool)]\ngroupList (x:xs) = tail (scanl (\\a b -> (group (x:xs) (fromIntegral b))) (False, False) (x:xs))\n\n-- Convierte los datos entregados por groupList en texto para imprimirlo.\nboolText :: [(Bool, Bool)] -> [Int] -> String\nboolText [] [] = \"\"\nboolText ((a, b):xs) (y:ys)\n | ((a == True) && (b == True)) = \"\" ++ (boolText xs ys)\n | ((a == True) && (b == False) && (length ys) > 0) = \"-\" ++ (show y) ++ \",\" ++ (boolText xs ys)\n | ((a == True) && (b == False) && (length ys) == 0) = \"-\" ++ (show y) ++ (boolText xs ys)\n | ((a == False) && (b == True)) = (show y) ++ (boolText xs ys)\n | ((a == False) && (b == False) && (length ys) > 0) = (show y) ++ \",\" ++ (boolText xs ys)\n | otherwise = (show y) ++ (boolText xs ys)\n\n-- Funci\u00f3n que splitea el texto (funci\u00f3n prove\u00edda de un tercero en Stack Overflow ya que\n-- splitOn no funciona en CodeForces).\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\nmain = do\n -- Obtiene el input\n input <- getLine\n\n -- Convierte el input en una lista de String, utilizando \",\" como separador.\n let listString = (wordsWhen (==',') input)\n\n -- Convierte la lista anterior en un conjunto de enteros.\n let setInt = Set.fromList (map (read::String->Int) (listString))\n\n -- Convierte el conjunto anterior en una lista de enteros\n let listInt = Set.toList setInt\n\n -- Aplico las funciones de arriba para obtener el texto correspondiente a la salida.\n let outPut = boolText (groupList listInt) (listInt)\n\n -- Imprime el texto en pantalla\n putStrLn(outPut)"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.List\nimport Data.List (nub, sort)\n\n{-crearlista :: [String] -> String\ncrearlista [] = []\ncrearlista (x:xs) = x++crearlista xs-}\n--funcion que no sirvio para nada\n\ncondicion :: [String] -> Int -> [String] \ncondicion lista i\n\t|(length lista == 0) = [show i]\n |(elem '-' (last lista)) == True = if (split (last lista) '-') !! 1 == show(pred i) then init lista ++ [(split (last lista) '-' !! 0) ++ \"-\" ++ show i] else lista ++ [show i]\n |otherwise = if (last lista) == show(pred i) then init lista ++ [last lista ++ \"-\" ++ show i] else lista ++ [show i]\n\n{-https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit obtenido del link anterior-}\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"] \nsplit (c:cs) delim \n\t| c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\n\nmain :: IO()\nmain = do \n\tsecuencia <- getLine\n\tlet lista' = split secuencia ',' --elimino las comas\n\tlet lista'' = sort (nub (map (read::String->Int) lista')) --ordeno los elementos de la lista \n\tlet resultado = foldl condicion [] lista'' --recorro la lista de elmentos \n\tlet resultado1 = [a ++ \",\"| a <- (init resultado)] \n let resultado2 = resultado1 ++ [(last resultado)] \n let resultado3 = foldl1 (++) resultado2 \n putStrLn resultado3\n\n\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Function\nimport qualified Data.Set as Set\n\nformat [] = \"\"\nformat (i:[]) = \",\" ++ show i\nformat (i:j:is) \n | i+1 == j = \n let (k, is') = continue (j:is)\n in \",\" ++ show i ++ \"-\" ++ show k ++ format is'\n | otherwise = \",\" ++ show i ++ format (j:is)\n\ncontinue (j:k:is)\n | j+1 == k = continue (k:is)\n | otherwise = (j, k:is)\ncontinue (k:[]) = (k, [])\ncontinue [] = error \"impossible\"\n\nmain = do\n pages <- read . (\\a -> \"[\" ++ a ++ \"]\") <$> getLine :: IO [Int]\n let set = Set.toList $ foldl (flip Set.insert) Set.empty pages\n putStrLn . tail . format $ set"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.List\nimport Data.List (nub, sort)\n{-https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit obtenido del link anterior-}\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"] \nsplit (c:cs) delim \n\t| c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\n\ngrooup :: [String] -> Int -> [String] \ngrooup list i\n\t|(length list == 0) = [show i]\n |(elem '-' (last list)) == True = if (split (last list) '-') !! 1 == show(pred i) then init list ++ [(split (last list) '-' !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n |otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\n\nmain :: IO()\nmain = do \n\tsecuencia <- getLine\n\tlet lista = split secuencia ','\n\tlet lista' = sort (nub (map (read::String->Int) lista))\n\tlet resultado = foldl grooup [] lista'\n\tlet resultado1 = [a ++ \",\"| a <- (init resultado)] \n let resultado2 = resultado1 ++ [(last resultado)] \n let resultado3 = foldl1 (++) resultado2 \n putStrLn resultado3\n\n\n"}, {"source_code": "import Data.List\nimport Data.Set\nimport System.IO\n\nsplit :: String -> [String]\nsplit [] = [\"\"]\nsplit (c:cs) \n | (c == ',') = \"\" : resto\n | otherwise = (c : head resto) : tail resto\n where resto = Main.split cs\n\nrangoDePaginas :: String -> Bool\nrangoDePaginas \"\" = False\nrangoDePaginas (x:xs)\n | (x == '-') = True\n | otherwise = rangoDePaginas xs\n\ngroup :: [String] -> Int -> [String]\ngroup pags x\n | pags == [] = [show x] \n | ((rangoDePaginas (head pags) == False) && ((read (head pags)) :: Int) + 1 == x) = [head pags ++ \"-\" ++ show x] ++ tail pags\n | ((rangoDePaginas (head pags) == False) && ((read (head pags)) :: Int) + 1 /= x) = [show x] ++ pags\n | ((rangoDePaginas (head pags) == True) && (n == x)) = [takeWhile (/='-') (head pags) ++ \"-\" ++ show x] ++ tail pags\n | ((rangoDePaginas (head pags) == True) && (n /= x)) = [show x] ++ pags\n where n = (read (tail (dropWhile (/='-') (head pags))) :: Int) + 1\n\npasarAInt :: [String] -> [Int]\npasarAInt [] = []\npasarAInt (x:xs) = (read x :: Int) : pasarAInt xs\n\nmain = do \n paginas <- getLine\n let lista = Main.split paginas\n let listaInt = pasarAInt lista\n let set = Data.Set.fromList listaInt\n let set2 = Data.Set.foldl Main.group [] set\n let set_final = Data.List.reverse set2\n let string = Data.List.intercalate \",\" set_final\n putStrLn string"}, {"source_code": "import Data.List\nimport Data.Set\nimport System.IO\n\n--Funci\u00f3n que nos permite separar un string utilizando \",\" como separador y crea una lista con los strings resultantes\nsplit :: String -> [String]\nsplit [] = [\"\"]\nsplit (c:cs) \n | (c == ',') = \"\" : resto\n | otherwise = (c : head resto) : tail resto\n where resto = Main.split cs\n\n--Funcion que nos entrega True si es que el string contiene un \"-\", lo que representaria un rango de paginas\n--Retorna False si es que es un unico numero correspondiente a la pagina\nrangoDePaginas :: String -> Bool\nrangoDePaginas \"\" = False\nrangoDePaginas (x:xs)\n | (x == '-') = True\n | otherwise = rangoDePaginas xs\n\n--Funcion que nos permite convertir una lista de strings a una lista de int\npasarAInt :: [String] -> [Int]\npasarAInt [] = []\npasarAInt (x:xs) = (read x :: Int) : pasarAInt xs\n\n--Funcion que recibe un set de strings, agrega una pagina x de la manera que corresponda, y luego retorna el set correspondiente\n--Es importante recalcar que cuando se agrega una nueva pagina, se agrega al principio del set, para reducir la complejidad temporal del problema\ngroup :: [String] -> Int -> [String]\ngroup pags x\n --Caso inicial, si es que no hay nada en el set, agrega la primera pagina\n | pags == [] = [show x]\n --En caso de que el primer elemento del set no sea un rango de paginas, hay dos opciones:\n --Si es que ademas la pagina x es la pagina que le sigue, se reemplaza por un string que represente un rango de paginas\n | ((rangoDePaginas (head pags) == False) && ((read (head pags)) :: Int) + 1 == x) = [head pags ++ \"-\" ++ show x] ++ tail pags\n --Si es que la pagina x no es la que le sigue, se agrega como nuevo elemento del set\n | ((rangoDePaginas (head pags) == False) && ((read (head pags)) :: Int) + 1 /= x) = [show x] ++ pags\n --En caso de que el primer elemento corresponda a un rango de paginas, tenemos otras dos opciones:\n --Si es que la pagina x, es la que le sigue a la pagina final del rango, se cambia por x\n | ((rangoDePaginas (head pags) == True) && (n == x)) = [takeWhile (/='-') (head pags) ++ \"-\" ++ show x] ++ tail pags\n --Si es que la pagina x no es la que le sigue a la pagina final del rango, se agrega como nuevo elemento del set\n | ((rangoDePaginas (head pags) == True) && (n /= x)) = [show x] ++ pags\n where n = (read (tail (dropWhile (/='-') (head pags))) :: Int) + 1\n\nmain = do \n paginas <- getLine\n let lista = Main.split paginas\n let listaInt = pasarAInt lista\n --Al utilizar la funcion fromList, convertimos la lista en un Data.Set y automaticamente se ordena\n let set = Data.Set.fromList listaInt\n --Se recorre el set y se le va aplicando la funcion group\n let set2 = Data.Set.foldl Main.group [] set\n --Como los nuevos elementos se agregan al principio del set resultante, ahora se invierte para que queden ordenados correctamente\n let set_final = Data.List.reverse set2\n --Se concatena el set de strings final poniendo una \",\" entre cada elemento\n let string_final = Data.List.intercalate \",\" set_final\n putStrLn string_final"}, {"source_code": "import qualified Data.Set as S\n\n\n\n\nmain:: IO ()\nmain = do \n -- Se toma la linea como input \n linea <- getLine\n --putStrLn(linea)\n --Split por comas y nos da una lista\n --let x = splitOn \",\" linea\n --print x\n -- De string -> [String]\n let st = foldl split [] linea\n -- De [String] -> [Int]\n let xI = map read st :: [Int]\n --De conjunto a lista(se quitan los repetidos y se ordena )\n let xs = S.toList (S.fromList xI)\n --De [Int] a [String]\n --let xt = map show xs :: [String]\n --print xt\n --Se invierte la lista(mas eficiente)\n let r = reverse xs\n --Se crean una lista con tuplas(orden ascendente)\n let ivals = foldl addToIntervals [] r\n --print ivals\n let s = foldl intervalsToString [] ivals\n putStrLn s\n\n \n\naddToIntervals :: [(Int,Int)] -> Int -> [(Int,Int)]\naddToIntervals [] x = [(x,x)]\naddToIntervals ((a,b):ivs) x = \n if x == a - 1\n then ((x,b):ivs)\n else ((x,x):(a,b):ivs)\n\nintervalsToString :: String ->(Int,Int) -> String\nintervalsToString \"\" (a,b) = \n if a == b\n then show (a)\n else show(a)++\"-\"++show(b) \nintervalsToString ivs (a,b) =\n if a == b\n then ivs++(\",\"++show (a))\n else ivs++(\",\"++show(a)++\"-\"++show(b))\n\nsplit:: [String]-> Char -> [String] \nsplit [] c = [[c]]\nsplit [x] c = \n if c /= ','\n then [x++[c]]\n else [[],x]\nsplit (x:xs) c =\n if c /= ','\n then (x++[c]):xs\n else []:x:xs\n\n\n "}, {"source_code": "import Data.List hiding (foldl, group)\n\nimport Data.Set hiding (foldl)\n\nmain = do\n comando <- getLine\n let sincomas = wordsWhen (==',') comando\n let ordenado = ordenar sincomas\n let respuesta = foldl group [] ordenado\n let dar = reverse respuesta\n let solucion = sol False dar\n putStrLn solucion\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\nordenar :: [String] -> Set Int\nordenar lista = let\n temp = [read x :: Int | x <- lista]\n in fromList temp\n\ngroup :: [String] -> Int -> [String]\ngroup xs b\n | xs == [] = (show b):xs\n | b == ((read(head xs) :: Int) + 1) = show(b):\"-\":xs\n | otherwise = show(b):\",\":xs\n\nsol :: Bool -> [String] -> String\nsol True (a:b:as) = if b == \"-\" then sol True as else a ++ b ++ sol False as\nsol False (a:b:as) = if b == \"-\" then a ++ b ++ sol True as else a ++ b ++ sol False as\nsol a [b] = b"}, {"source_code": "import List\nmain = interact (ans)\nans theInput = answer $ page a1 where\n line0 = head $ lines theInput\n split [] = []\n split x = y : if null z then [] else (split $ tail z) where\n (y,z) = break ( == ',') x\n a1 = sort $ map (read::String->Int) (split line0)\n page [x] = [(x,x)]\n page (x:xs) = if x==u || x+1==u then (x,v):ws else (x,x):(u,v):ws where\n (u,v):ws = page xs\n out (x,y) = if x==y then show x else (show x) ++ \"-\" ++ (show y)\n answer [(x,y)] = out (x,y)\n answer ((x,y):xs) = (out (x,y)) ++ \",\" ++ (answer xs)\n"}, {"source_code": "import List\nmain = interact (ans)\nans theInput = answer $ page a1 where\n line0 = head $ lines theInput\n split [] = []\n split (',':xs) = split xs\n split x = (fst $ split1 x) : (split $ snd $ split1 x) where\n split1 x = break ( == ',') x\n a0 = map (read::String->Int) (split line0)\n a1 = sort a0\n page [x] = [(x,x)]\n page (x:xs) = if x==top || x+1==top\n then (x,snd $ headPageXs):(tail pageXs)\n else (x,x):pageXs\n where\n pageXs = page xs\n headPageXs = head pageXs\n top = fst headPageXs\n out (x,y) = if x==y then show x else (show x) ++ \"-\" ++ (show y)\n answer [(x,y)] = out (x,y)\n answer ((x,y):xs) = (out (x,y)) ++ \",\" ++ (answer xs)\n"}, {"source_code": "import qualified Data.Set as S\nimport Data.List (nub, sort)\n\nsplit' :: Char -> String -> [String]\nsplit' x y = words [if c == x then ' ' else c | c <- y]\n\n--FUNCIONES MALAS\n{-}\ngroup' :: [(Integer,Integer)] -> Integer -> [(Integer,Integer)]\ngroup' (x:xs) y\n | snd(x)+1 == y =(snd(x),y)\n | fst(x) == 0 = (snd(x),snd(x))\n | otherwise = (0,y):x-}\n{-\njoinList :: [String] -> String\njoinList [] = []\njoinList (x:xs) = x++joinList xs-}\n\nsec :: [Int] -> Int\nsec x = case x of\n [x] -> x\n (x:xs) -> if ((x+1)==(head xs)) then (sec xs) else x\n\ngroup' :: [Int] -> Int -> [(Int,Int)]\ngroup' x z = case x of\n [] -> []\n (y:ys) -> if y<=(z) then (group' ys z) \n else [(y,sec x)] ++ (group' ys (sec x))\n\njoinHyphen :: String -> (Int,Int) -> String\njoinHyphen \"\" (x,y)\n |x == y = show (x)\n |otherwise = show(x)++\"-\"++show(y) \njoinHyphen z (x,y) \n |x == y = z++(\",\"++show (x))\n |otherwise = z++(\",\"++show(x)++\"-\"++show(y))\n\nmain :: IO()\nmain = do\n secuencia <- getLine\n --let list'= map digitToInt [ x | x <- secuencia, x/=',']\n let numbers = split' (',') secuencia\n let list'= sort (nub (map (read::String->Int) numbers))\n let groupSolution = group' list' 0\n let fin = foldl joinHyphen [] groupSolution\n putStrLn fin"}, {"source_code": "import qualified Data.Set as S\nimport Data.List (nub, sort)\n\nsplit' :: Char -> String -> [String]\nsplit' r str = words [if c == r then ' ' else c | c <- str]\n\n--FUNCIONES MALAS\n{-}\ngroup' :: [(Integer,Integer)] -> Integer -> [(Integer,Integer)]\ngroup' (x:xs) y\n | snd(x)+1 == y =(snd(x),y)\n | fst(x) == 0 = (snd(x),snd(x))\n | otherwise = (0,y):x-}\n{-}\njoinList :: [String] -> String\njoinList [] = []\njoinList (x:xs) = x++joinList xs-}\n\nsecuencia :: [Int] -> Int\nsecuencia x = case x of\n [x] -> x\n (x:xs) -> if ((x+1)==(head xs)) then (secuencia xs) else x\n\ngroup' :: [Int] -> Int -> [(Int,Int)]\ngroup' x z = case x of\n [] -> []\n (y:ys) -> if y<=(z) then (group' ys z) \n else [(y,secuencia x)] ++ (group' ys (secuencia x))\n\njoinHyphen :: String -> (Int,Int) -> String\njoinHyphen \"\" (x,y)\n |x == y = show (x)\n |otherwise = show(x)++\"-\"++show(y) \njoinHyphen ivs (x,y) \n |x == y = ivs++(\",\"++show (x))\n |otherwise = ivs++(\",\"++show(x)++\"-\"++show(y))\n\nmain :: IO()\nmain = do\n secuencia <- getLine\n --let list'= map digitToInt [ x | x <- secuencia, x/=',']\n let numbers = split' (',') secuencia\n let list'= sort (nub (map (read::String->Int) numbers))\n let groupSolution = group' list' 0\n let fin = foldl joinHyphen [] groupSolution\n putStrLn fin"}, {"source_code": "import qualified Data.Set as Set\nimport Data.String\nimport Data.List\nimport Control.Monad (mfilter)\n\nmain = do\n line <- getLine\n let lis = (sort . nub) (map (read::String->Int) (split ',' line)) --lis es la lista sin repetir y ordenada de numeros\n let pal = \"\"\n let ret = foldl grp pal lis\n if 'c' `elem` ret then putStrLn $ rc ret else putStrLn ret\n --print $ foldl grp pal lis\n\nreplace a b = map $ maybe b id . mfilter (/= a) . Just\n\n--reemplazo el elemento que tenga c con el string que entre (c es para reconocer los numeros que vienen seguidos)\nremp :: String -> String -> String\nremp r st = intercalate \"-\" (filter (\\s -> not ('c' `elem` s)) (split '-' st))++\"-\"++ r\n\n--para remover un c final si es que la linea lo contiene \nrc :: String -> String\nrc str = filter (\\s -> s /= 'c') str\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\n--para obtener el valor numerico del numero \nnumb :: String -> Int\nnumb str = (read nun::Int) where\n nun = filter (\\s -> s /= 'c') str\n\n--funcion group \ngrp:: String -> Int -> String\ngrp \"\" x = \"\"++(show x)\ngrp str x =\n if length (foldl (\\s x -> s ++ split ',' x) [] (split '-' str)) == 1\n then if (read str::Int) == x-1\n then str++\"-\"++(show x)++\"c\"\n else str++\",\"++(show x)\n else do\n let ultim = (concat . (take 1 . reverse)) (foldl (\\s x -> s ++ split ',' x) [] (split '-' str))\n if 'c' `elem` ultim\n then if (numb ultim) == (x-1)\n then remp (show x ++\"c\") str\n else (replace 'c' ',' str)++(show x)\n else if (numb ultim) == (x-1) \n then str ++ \"-\" ++(show x)++\"c\"\n else str ++ \",\" ++(show x)"}, {"source_code": " import qualified Data.Set as Set\n import Data.List\n--1.Lea correctamente los datos y almacene estos en un Data.Set\n--2.Apoyado con su funci\u00f3n, itere con un foldl sobre el Data.Set\n main :: IO ()\n main = do \n--Ingreso cadena de paginas. \n input <- getLine\n--Ayudandonos de nuestra funcion splitt nuestras paginas quedaran en una lista de strings. \n let paginas = splitt input ',' \n--Pasaremos los strings de nuestra lista creada anteriormente a enteros. idea: http://zvon.org/other/haskell/Outputprelude/read_f.html\n let pagin = [read pag::Int | pag <- paginas] --Recorre lista (pag) y transforma String->Int\n--Como se solicita crearemos un Set con las paginas (ya pasadas a enteros en la lista) ingresadas .\n let pag = Set.fromList pagin \n--Ayudandonos de nuestra funcion iteramos el set con foldl (funciona con el Set entregado y una lista vacia) asi obtener nuestra solucion final.\n let final = foldl group1 [] pag \n--Concatenaremos la primera parte hasta la coma\n let final1 = [a ++ \",\"| a <- (init final)] \n--Agregamos el parametro solo en caso de haber y concatenamos con el anterior\n let finall = final1 ++ [(last final)] \n-- String output\n let finalfinal = foldl1 (++) finall \n putStrLn finalfinal\n\n --Declaramos la funcion para separar los caracteres entregados. idea:https://jmmv.dev/2006/08/split-function-in-haskell.html\n splitt :: String -> Char -> [String]\n splitt [] delim = [\"\"] \n splitt (c:cs) delim \n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = splitt cs delim\n \n--3.Implemente la funci\u00f3n group :: a -> b -> a que lo va a ayudar para resolver el problema. \n group1 :: [String] -> Int -> [String] \n \n group1 lista elemento\n \n |(length lista == 0) = [show elemento]\n \n |(elem '-' (last lista)) == True = if (splitt (last lista) '-') !! 1 == show(pred elemento) then init lista ++ [(splitt (last lista) '-' !! 0) ++ \"-\" ++ show elemento] else lista ++ [show elemento]\n \n |otherwise = if (last lista) == show(pred elemento) then init lista ++ [last lista ++ \"-\" ++ show elemento] else lista ++ [show elemento]\n "}, {"source_code": " import qualified Data.Set as Set\n import Data.List\n --Declaramos la funcion para separar los caracteres entregados. idea:https://jmmv.dev/2006/08/split-function-in-haskell.html\n splitt :: String -> Char -> [String]\n splitt [] delim = [\"\"] \n splitt (c:cs) delim \n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = splitt cs delim\n \n--3.Implemente la funci\u00f3n group :: a -> b -> a que lo va a ayudar para resolver el problema. \n group1 :: [String] -> Int -> [String] \n \n group1 lista elemento\n \n |(length lista == 0) = [show elemento]\n \n |(elem '-' (last lista)) == True = if (splitt (last lista) '-') !! 1 == show(pred elemento) then init lista ++ [(splitt (last lista) '-' !! 0) ++ \"-\" ++ show elemento] else lista ++ [show elemento]\n \n |otherwise = if (last lista) == show(pred elemento) then init lista ++ [last lista ++ \"-\" ++ show elemento] else lista ++ [show elemento]\n \n--1.Lea correctamente los datos y almacene estos en un Data.Set\n--2.Apoyado con su funci\u00f3n, itere con un foldl sobre el Data.Set\n main :: IO ()\n main = do \n--Ingreso cadena de paginas. \n input <- getLine\n--Ayudandonos de nuestra funcion splitt nuestras paginas quedaran en una lista de strings. \n let paginas = splitt input ',' \n--Pasaremos los strings de nuestra lista creada anteriormente a enteros. idea: http://zvon.org/other/haskell/Outputprelude/read_f.html\n let pagin = [read pag::Int | pag <- paginas] --Recorre lista (pag) y transforma String->Int\n--Como se solicita crearemos un Set con las paginas (ya pasadas a enteros en la lista) ingresadas .\n let pag = Set.fromList pagin \n--Ayudandonos de nuestra funcion iteramos el set con foldl (funciona con el Set entregado y una lista vacia) asi obtener nuestra solucion final.\n let final = foldl group1 [] pag \n--Concatenaremos la primera parte hasta la coma\n let final1 = [a ++ \",\"| a <- (init final)] \n--Agregamos el parametro solo en caso de haber y concatenamos con el anterior\n let finall = final1 ++ [(last final)] \n-- String output\n let finalfinal = foldl1 (++) finall \n putStrLn finalfinal\n\n"}, {"source_code": "import System.IO\nimport System.Environment\nimport qualified Data.List as L\nimport qualified Data.Set as Set\nmain = do\n array_n <- getLine\n let list = buildList array_n\n intList = L.sort (Prelude.map read (Set.toList (Set.fromList list)) :: [Int])\n finalList = L.foldl groupNumbers [] intList\n putStrLn (L.intercalate \",\" (L.foldl format [] finalList))\n\n\n\nbuildList :: String -> [String]\nbuildList arr =\n if arr == \"\" then\n let args = [\"\"] in args\n else do\n let newarr = split arr ',' in newarr\n\ngroupNumbers :: [[Int]]-> Int ->[[Int]]\ngroupNumbers [] n = [[n]]\ngroupNumbers [x] n =\n if n == (last x) + 1\n then\n let list = x ++ [n] in\n [list]\n else\n [x]++[[n]]\ngroupNumbers (x:xs) n =\n if n == (last x) + 1\n then\n let list = x ++ [n]\n in list:xs\n else\n let lists = x:(groupNumbers xs n) in lists\n\nformat :: [String] -> [Int] ->[String]\nformat s rango =\n if head rango == last rango\n then let r = show (head rango)\n in s++[r]\n else let r = show (head rango) ++ \"-\" ++ show (last rango) in s++[r]\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n"}], "negative_code": [{"source_code": "import qualified Data.Set as Set\nimport qualified Data.List as List\n\nmain = do\n line <- getLine \n let list = split line ','\n let set = Set.fromList list\n let pages = Set.elems set\n let sortedPages = List.sort pages\n let newPages = group sortedPages (read (head sortedPages) :: Int)\n let strPages = List.intercalate \",\" newPages\n putStrLn strPages\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\n\ngroup :: [String] -> Int -> [String]\ngroup [] posAnterior = [\"\"]\ngroup (x:xs) posAnterior \n | pos == posAnterior = if xs == [] then [x] else (if (nextPos /= succ pos) then (x : rest) else ((x ++ head rest) : tail rest))\n | pos == succ posAnterior = if xs == [] then [\"-\" ++ x] else (if (nextPos /= succ pos) then ((\"-\" ++ x) : rest) else rest)\n | otherwise = if xs == [] then [x] else (if (nextPos /= succ pos) then (x : rest) else (x ++ head rest) : tail rest)\n where\n pos = (read x :: Int)\n nextPos = (read (head xs) :: Int)\n rest = group xs pos"}, {"source_code": "import qualified Data.Set as Set\n\n-- La funcion rep reemplaza todas las comas en el String dado por espacios.\nrep :: String -> String\nrep \"\" = \"\"\nrep (',':xs) = \" \" ++ rep (xs)\nrep (x:xs) = [x] ++ rep (xs)\n\n-- La funcion group se encarga de construir el String deseado\ngroup :: [String] -> Int -> [String]\ngroup [] n = \"-\":(show n):[] --Si la lista esta vacia (Que siempre lo estara al inicio) se agrega la Int n como String y un guion.\ngroup (\"-\":x:xs) n\n | (read x) == (pred n) = (show n):\"-\":restofList -- Si x es predecesor de n, se agrega n en la cabeza.\n | otherwise = \"-\":(show n):\",\":restofList -- En caso contrario, se reemplaza el guion por una coma, y se agrega n y un guion.\n where restofList = (x:xs)\ngroup (x:xs) n\n | (read x) == (pred n) = (show n):xs -- Si x es predecesor de n, se reemplaza x por n.\n | otherwise = \"-\":(show n):\",\":x:xs -- En caso contrario, se agrega una coma, n y un guion.\n\n-- Al terminar la funcion group la nueva lista puede contener un guion a la cabeza. Esta funcion lo elimina si esta presente.\neraseThing :: [String] -> [String]\neraseThing (\"-\":xs) = xs\neraseThing x = x\n\nmain :: IO ()\nmain = do\n line <- getLine\n let lineList = map (read :: String -> Int) ((words . rep) line) --Se usa rep y words para separar la String en una lista. Luego se usa map y read para convertirlo en una lista de Int\n let newSet = Set.fromList lineList --Se transforma la lista en Set\n let newList = foldl (group) [] newSet --Se utiliza foldl para construir la String con group, dando una lista vacia y el Set\n let groupLine = (concat . reverse) (eraseThing newList) --Se usa reverse y se concatena la lista, obteniendo el String deseado\n print (groupLine)"}, {"source_code": "import qualified Data.Set as S\n\ngroup :: [Char] -> Int -> [Char]\ngroup \"\" num = \"\" ++ show num\ngroup str num\n -- Si tenemos el sucesor, agregar '-' y luego el sucesor, se usa lenght para evitar problema con largo de lista en casos como \"1,2\"\n | succ (toInt(last str)) == num && length str == 1 = str ++ \"-\" ++ show num\n -- Si tenemos el sucesor y el peniultimo char es '-' cambiar el numero de la secuencia\n | succ (toInt(last str)) == num && last(init str) == '-' = init str ++ show num\n -- Si tenemos el sucesor, agregar '-' y luego el numero\n | succ (toInt(last str)) == num = str ++ \"-\" ++ show num\n -- Cualquier otro caso extender con ',' y el siguiente numero\n | otherwise = str ++ \",\" ++ show num\n\ntoInt :: Char -> Int\ntoInt c = read (c : []) :: Int \n\nmain = do\n name <- getLine\n let a = concatMap (\\x -> if x == ',' then \" \" else [x]) name -- Remplazar comas por espacios para usar words\n let set = S.fromList (map read $ words a :: [Int]) --Set [1,2,3]\n --print (toInt (last \"1-3,5-8\") == 8)\n putStrLn (S.foldl group \"\" set)"}, {"source_code": "import qualified Data.Set as S\n\ngroup :: [Char] -> Int -> [Char]\ngroup \"\" num = \"\" ++ show num\ngroup str num\n -- Si tenemos el sucesor, agregar '-' y luego el sucesor, se usa lenght para evitar problema con largo de lista en casos como \"1,2\"\n | succ (toInt(last str)) == num && length str == 1 = str ++ \"-\" ++ show num\n -- Si tenemos el sucesor y el peniultimo char es '-' cambiar el numero de la secuencia\n | succ (toInt(last str)) == num && last(init str) == '-' = init str ++ show num\n -- Si tenemos el sucesor, agregar '-' y luego el numero\n | succ (toInt(last str)) == num = str ++ \"-\" ++ show num\n -- Cualquier otro caso extender con ',' y el siguiente numero\n | otherwise = str ++ \",\" ++ show num\n\ntoInt :: Char -> Int\ntoInt c = read (c : []) :: Int \n\nmain = do\n name <- getLine\n let a = concatMap (\\x -> if x == ',' then \" \" else [x]) name -- Remplazar comas por espacios para usar words\n let set = S.fromList (map read $ words a :: [Int]) --Set [1,2,3]\n --print (toInt (last \"1-3,5-8\") == 8)\n print (S.foldl group \"\" set)"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Set as Set\n \nmain :: IO()\nmain = do\n input <- getLine\n let inputList = split input ','\n let intList = map(read::String->Int) inputList \n let dataset = Set.fromList intList\n let dataSetList = Set.toList (Set.fromList intList) \n let flipList = foldl (flip (:)) [] dataSetList\n let lastList = foldl group [] flipList\n let returnList = showTuples lastList\n putStrLn returnList\n \n--Fuente: https://stackoverflow.com/questions/47308280/haskell-list-of-int-tuples-to-string\nshowTuples :: [(Int, Int)] -> String\nshowTuples [] = \"\"\nshowTuples (x:[]) = show(fst(x)) ++ \" \" ++ show(snd(x))\nshowTuples (x:xs) = show(fst(x)) ++ \" \" ++ show(snd(x)) ++ \" \" ++ showTuples xs\n \n--Fuente: https://jmmv.dev/2006/08/split-function-in-haskell.html\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)]\ngroup ((x,y):xs) n\n |x-1 == n = ((n,y):xs)\n |otherwise = [(n,n)] ++ ((x,y):xs)"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True) then show s1 ++ \"-\" ++ show s2 ++ \",\" else (if (s1 > 0 && null xs == True) then show s1 ++ \"-\" ++ show s2 else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) else (\"\"))))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n print ( nss )"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True) then show s1 ++ \"-\" ++ show s2 ++ \",\" ++ groupon xs else (if (s1 > 0 && null xs == True) then show s1 ++ \"-\" ++ show s2 ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs else show (s1*(-1)) ++ groupon xs)))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n putStrLn nss "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n \n \nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim \n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True) then show s1 ++ \"-\" ++ show s2 ++ \",\" ++ groupon xs else (if (s1 > 0 && null xs == True) then show s1 ++ \"-\" ++ show s2 ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs else show (s1*(-1)) ++ groupon xs)))\n \ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n \ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else (if (k == v-1) then (k,v) : grr t else (-k,-v) : grr t)\n\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n \n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n putStrLn nss "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True && s1 /= s2 -1 ) then show s1 ++ \"-\" ++ show s2 ++ \",\" ++ groupon xs else (if (s1 > 0 && null xs == True && s1 /= s2 -1 ) then show s1 ++ \"-\" ++ show s2 ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs else( if (s2==0) then show (s1*(-1)) ++ groupon xs else (if (null xs /= True) then show s1++\",\"++show s2 ++ \",\" ++ groupon xs else ( show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs))))))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n putStrLn nss "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True && s1 /= s2 -1 ) then show s1 ++ \"-\" ++ show s2 ++ \",\" ++ groupon xs else (if (s1 > 0 && null xs == True && s1 /= s2 -1 ) then show s1 ++ \"-\" ++ show s2 ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs else( if (s2==0) then show (s1*(-1)) ++ groupon xs else (if (null xs /= True) then show s1++\",\"++show s2 ++ \",\" ++ groupon xs else ( show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs))))))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n putStrLn nss "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 /= s2 -1 && s1 > 0 && null xs /= True ) then show s1 ++ \"-\" ++ show s2 ++ \",\" ++ groupon xs else (if (s1 /= s2 -1 && s1 > 0 && null xs == True ) then show s1 ++ \"-\" ++ show s2 ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs else( if (s2==0) then show (s1*(-1)) ++ groupon xs else (if (null xs /= True) then show s1++\",\"++show s2 ++ \",\" ++ groupon xs else ( show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs))))))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n putStrLn nss "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True) then show s1 ++ \"-\" ++ show s2 ++ \",\" else (if (s1 > 0 && null xs == True) then show s1 ++ \"-\" ++ show s2 else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) else (\"\"))))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n print ( ns )"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n\ngroupon :: [(Integer,Integer)] -> String\ngroupon [] = \"\"\ngroupon ((s1,s2):xs) = if (s1 > 0 && null xs /= True) then show s1 ++ \"-\" ++ show s2 ++ \",\" ++ groupon xs else (if (s1 > 0 && null xs == True) then show s1 ++ \"-\" ++ show s2 ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs /= True) then show ((-1)*s1)++\",\"++show ((-1)*s2)++\",\" ++ groupon xs else (if (s1 < 0 && s2 < 0 && null xs == True) then show ((-1)*s1)++\",\"++show ((-1)*s2) ++ groupon xs else \"error\" ++ groupon xs)))\n\ngr :: [Integer] -> [(Integer,Integer)]\ngr [] = []\ngr [x] = [(x,0)]\ngr (k:v:t) = (k,v) : gr t\n\ngrr :: [Integer] -> [(Integer,Integer)]\ngrr [] = []\ngrr [x] = [(-x,0)]\ngrr (k:v:t) = if (null t /= True) && (k == v - 1 ) && (v == head t - 1) then (k, shower t) : grr (drop (fromIntegral ( shower t - k - 1 )) t) else(-k,-v) : grr t\n\nshower :: [Integer] -> Integer\nshower [x] = x\nshower (k:t) = if (k == head t - 1 ) then shower t else k \n\npedirlista :: IO ()\npedirlista = \n putStrLn \"Triate la lista\"\n >> getLine\n >>= \\x -> putStrLn (\"Esta es tu lista \" ++x)\n\nreader :: [String] -> [Integer]\nreader = map read\nmain = do\n rawdata <- getLine\n let ldata1 = split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let rango = gr ldata3\n let ns = grr ldata3\n let nss = groupon ns\n putStrLn nss "}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\n \ngroup :: [(Int, Int)] -> Int -> [(Int, Int)]\ngroup [] p = [(p, p)] --caso inicial\ngroup pages p = let\n (p1,p2) = last pages\n \n in if p == p2 + 1 then (init pages) ++ [(p1,p)] else pages ++ [(p,p)]\n\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim \n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n \nwriter::[(Int, Int)] -> String\nwriter [] = \"\"\nwriter ((p1,p2):xs) = if p1 == p2 then show p1 ++ \",\" ++ writer xs else show p1 ++ \"-\" ++ show p2 ++ \",\" ++ writer xs \n\n \nreader :: [String] -> [Int]\nreader = map read\n\n\n\n\nmain :: IO ()\nmain = do\n rawdata <- getLine\n let ldata1 =split rawdata ','\n let ldata2 = reader ldata1\n let sdata = Set.fromList ldata2\n let ldata3 = Set.toList sdata\n let finalPages = foldl (group) [] ldata3\n putStrLn ( writer finalPages)"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n\ngrouping s [] _= s\ngrouping s (x:xs) flag= do\n if(flag)\n then if(lastNumber s ==(x-1))\n then grouping (init s ++ show x) xs True\n else grouping (s ++\",\"++ show x++\",\") xs False\n else if(xs==[])\n then grouping (s++ show x) xs False \n else if(x==(head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\ngrouping s [] _= s\ngrouping s (x:[]) _= do\n if(digitToInt (last s)==(x-1))\n then init s++ show x\n else s++ \",\"++ show x\ngrouping s (x:xs) flag= do\n if(flag)\n then if(digitToInt (last s)==(x-1))\n then grouping (init s ++ show x) xs True\n else grouping (s ++\",\"++ show x) xs False\n else if( x== (head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n print finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\ngroups :: [Char] -> Int -> [Char]\ngroups \"\" i = show i\ngroups palabra i = do\n if (lastSymbol 0 palabra==\"-\")\n then (init palabra)++[x|x<-show i, (lastNumber palabra+1)==i]++[x|x<-[last palabra ,',']++show i, (lastNumber palabra +1)/=i]\n else palabra++[x|x<-['-']++show i, (lastNumber palabra+1)==i]++[ x|x<-[',']++show i, (lastNumber palabra +1)/=i]\n\naddComa::[Char]-> Int->[Char]\naddComa palabra _ = [last palabra]++\",\"\n\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\n\nlastSymbol:: Int->[Char]->[Char]\nlastSymbol 0 s= lastSymbol 1 (reverse s) \nlastSymbol 1 \"\" = \"\"\nlastSymbol 1 (x:xs)= do\n if(isDigit x)\n then lastSymbol 1 xs\n else [x] \ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain= do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= foldl groups \"\" sortedSet \n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n-- grouping \"10,20,\" (30) False\ngrouping s [] _= s\n-- grouping s (x:[]) flag= do\n-- if(flag && digitToInt (last s)==(x-1))\n-- then init s++ show x\n-- else s++ \",\"++ show x\ngrouping s (x:xs) flag= do\n if(flag)\n then if(digitToInt (last s)==(x-1))\n then grouping (init s ++ show x) xs True\n else grouping (s ++\",\"++ show x) xs False\n else if(xs==[])\n then grouping ( s++ show x) xs False \n else if(x== (head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\ngroups :: [Char] -> Int -> [Char]\ngroups \"\" i = show i\ngroups palabra i = do\n if (lastSymbol 0 palabra==\"-\")\n then (sinLastNumber palabra)++[x|x<-show i, (lastNumber palabra+1)==i]++[x|x<-[last palabra ,',']++show i, (lastNumber palabra +1)/=i]\n else palabra++[x|x<-['-']++show i, (lastNumber palabra+1)==i]++[ x|x<-[',']++show i, (lastNumber palabra +1)/=i]\n\naddComa::[Char]-> Int->[Char]\naddComa palabra _ = [last palabra]++\",\"\n\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\n\nsinLastNumber::[Char]->[Char]\nsinLastNumber s= reverse(dropWhile (isDigit) (reverse s))\n\nlastSymbol:: Int->[Char]->[Char]\nlastSymbol 0 s= lastSymbol 1 (reverse s) \nlastSymbol 1 \"\" = \"\"\nlastSymbol 1 (x:xs)= do\n if(isDigit x)\n then lastSymbol 1 xs\n else [x] \ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain= do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= foldl groups \"\" sortedSet \n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n\ngrouping s [] _= s\ngrouping s (x:xs) flag= do\n if(flag)\n then if(lastNumber s ==(x-1))\n then grouping (reverse (drop (length(show (lastNumber s))) (reverse s)) ++ show x) xs True\n else if(xs==[])\n then grouping (s ++\",\" ++show x) xs True\n else grouping (s ++\",\"++ show x++\",\") xs False\n else if(xs==[])\n then grouping (s++ show x) xs False \n else if(x==(head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n\ngrouping s [] _= s\ngrouping s (x:xs) flag= do\n if(flag)\n then if(lastNumber s ==(x-1))\n then grouping (init s ++ show x) xs True\n else if(xs==[])\n then grouping (s ++\",\" ++show x) xs True\n else grouping (s ++\",\"++ show x++\",\") xs False\n else if(xs==[])\n then grouping (s++ show x) xs False \n else if(x==(head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n-- grouping \"979,981,983-984\" (987:[989,992,993,995,996,998,999,1000]) False\ngrouping s [] _= s\ngrouping s (x:xs) flag= do\n if(flag)\n then if(lastNumber s ==(x-1))\n then grouping (init s ++ show x) xs True\n else grouping (s ++\",\"++ show x) xs False\n else if(xs==[])\n then grouping (s++ show x) xs False \n else if(x==(head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\ngroups :: [Char] -> Int -> [Char]\ngroups \"\" i = show i\ngroups palabra i = do\n if (lastSymbol 0 palabra==\"-\")\n then (sinLastNumber palabra)++[x|x<-show i, (lastNumber palabra+1)==i]++[x|x<-(show (lastNumber palabra)++[',']++show i), (lastNumber palabra +1)/=i]\n else palabra++[x|x<-['-']++show i, (lastNumber palabra+1)==i]++[ x|x<-[',']++show i, (lastNumber palabra +1)/=i]\n\naddComa::[Char]-> Int->[Char]\naddComa palabra _ = [last palabra]++\",\"\n\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\n\nsinLastNumber::[Char]->[Char]\nsinLastNumber s= reverse(dropWhile (isDigit) (reverse s))\n\nlastSymbol:: Int->[Char]->[Char]\nlastSymbol 0 s= lastSymbol 1 (reverse s) \nlastSymbol 1 \"\" = \"\"\nlastSymbol 1 (x:xs)= do\n if(isDigit x)\n then lastSymbol 1 xs\n else [x] \ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain= do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n print sortedSet\n let finalString= foldl groups \"\" sortedSet \n putStrLn $ id finalString\n \n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\n\n\ngrouping :: [Char]->[Int] -> Bool-> [Char]\n\n\ngrouping s [] _= s\ngrouping s (x:xs) flag= do\n if(flag)\n then if(lastNumber s ==(x-1))\n then grouping (reverse (drop (length(show (lastNumber s))) (reverse s)) ++ show x) xs True\n else grouping (s++\",\") (x:xs) False\n else if(xs==[])\n then grouping (s++ show x) xs False \n else if(x==(head xs-1))\n then grouping (s++[y|y<-[','],length s >0 ,last s /= ',']++show x ++\"-\"++show (head xs)) (drop 1 xs) True\n else grouping ( s++ show x ++ \",\") xs False\n\nlastNumber:: [Char]->Int\nlastNumber s= read (reverse(takeWhile (isDigit) (reverse s))) :: Int\ndeleteComas :: [Char] -> [Char]\ndeleteComas []= \"\"\ndeleteComas s = do\n if(isDigit (head s))\n then (take 1 s) ++ deleteComas (drop 1 s)\n else \" \" ++ deleteComas (drop 1 s)\n\nmain = do\n line<-getLine\n let listInt= map read $ words $deleteComas line :: [Int]\n let sortedSet = nub (sort listInt)\n let finalString= grouping \"\" sortedSet False\n print sortedSet\n putStrLn $ id finalString\n \n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getLine >>= putStrLn . drop 4 . solve (-1) (-1) . sort . read . ('[':) . (++\"]\")\n\nsolve :: Int -> Int -> [Int] -> String\nsolve k l [] | k + 1 < l = ',' : show k ++ '-' : show l\n | k + 1 == l = ',' : show k ++ ',' : show l\n | otherwise = ',' : show k\nsolve k l (x:xs) | l + 1 < x = solve k l [] ++ solve x x xs\n | otherwise = solve k x xs\n"}, {"source_code": "import qualified Data.Set as S \n\nsplitfunc :: String -> [String] --C&P de StackOverflow: https://stackoverflow.com/questions/46580924/haskell-splitting-a-string-by-delimiter \n\nsplitfunc [] = [\"\"]\nsplitfunc (c:cs) | c == ',' = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where rest = splitfunc cs\n\ngroup :: [(Int,Int)] -> Int -> [(Int,Int)]\ngroup [] n = [(n,n)] \ngroup ((a,b):xs) n = \n if b - 1 == n\n\tthen ((n,a):xs) -- Se cambia a por n y b por a \n else [(n,n)] ++ ((a,b):xs)\n\n\n\nconvert :: [(Int,Int)] -> String\nconvert ((a,b):xs) =\n if null xs -- Si xs es null, no se agrega \",\" al final.\n then if a == b\n then show a\n else show a ++ \"-\" ++ show b\n else if a == b\n then show a ++ \",\" ++ convert(xs)\n else show a ++ \"-\" ++ show b ++ \",\" ++ convert(xs)\nmain :: IO()\nmain = do\n line <- getLine\n let linelist = splitfunc line \n let intlist = map(read::String->Int) linelist\n let dataset = S.fromList intlist\n let settolist = S.toList dataset\n let finallist = foldl (flip (:)) [] settolist -- Se da vuelta la lista, para trabajar con la cabeza\n let final = foldl group [] finallist\n\n do mapM_ print intlist\n do mapM_ print finallist\n let a = convert final\n putStrLn a\n\n\n"}, {"source_code": "import qualified Data.Set as Set \n\nsplitComma :: String -> [String]\nsplitComma [] = [\"\"]\nsplitComma (x:xs)\n | x == ',' = \"\" : splitComma xs\n | otherwise = (x : head rest) : tail rest\n where rest = splitComma xs\n\ntoString :: [(Int,Int)] -> String\ntoString [] = \"\"\ntoString ((a,b):xs) \n | a /= b = show a ++ \"-\" ++ show b ++ \",\" ++ toString xs\n | otherwise = if xs /= [] then show a ++ \",\" ++ toString xs else show a \n\ntoListofTuples :: [Int] -> [(Int,Int)]\ntoListofTuples [] = [] \ntoListofTuples [a] = [(a,a)] \ntoListofTuples (a:b:xs)\n | a + 1 == b = (a , result) : toListofTuples new_list \n | otherwise = (a,a) : toListofTuples (b:xs)\n where result = maxN (b:xs) a\n new_list = filter (>result) (b:xs)\n\nmaxN :: [Int] -> Int -> Int\nmaxN (x:xs) a\n | xs == [] = a \n | a + 1 == x = maxN xs (a+1) \n | otherwise = a \n \nmain = do\n input <- getLine -- \"1,2,3,1,1,2,6,6,2\"\n let splitted_input = splitComma input \n let int_list = map read splitted_input :: [Int] -- [1,2,3,1,1,2,6,6,2]\n let set = Set.fromList int_list\n let result_list = Set.toList set -- [1,2,3,6]\n let tupleLists = toListofTuples result_list\n let result = toString tupleLists \n putStrLn result"}, {"source_code": "import qualified Data.Set as Set \n\nsplitComma :: String -> [String]\nsplitComma [] = [\"\"]\nsplitComma (x:xs)\n | x == ',' = \"\" : splitComma xs\n | otherwise = (x : head rest) : tail rest\n where rest = splitComma xs\n\ntoString :: [(Int,Int)] -> String\ntoString [] = \"\"\ntoString ((a,b):xs) \n | a /= b = show a ++ \"-\" ++ show b ++ \",\" ++ toString xs\n | otherwise = if xs /= [] then show a ++ \",\" ++ toString xs else show a \n\ntoListofTuples :: [Int] -> [(Int,Int)]\ntoListofTuples [] = [] \ntoListofTuples [a] = [(a,a)] \ntoListofTuples (a:b:xs)\n | a + 1 == b = (a , result) : toListofTuples new_list \n | otherwise = (a,a) : toListofTuples (b:xs)\n where result = maxN (b:xs) a\n new_list = filter (>result) (b:xs)\n\nmaxN :: [Int] -> Int -> Int\nmaxN (x:xs) a\n | xs == [] = a \n | a + 1 == x = maxN xs (a+1) \n | otherwise = a \n \nmain = do\n input <- getLine -- \"1,2,3,1,1,2,6,6,2\"\n let splitted_input = splitComma input \n let int_list = map read splitted_input :: [Int] -- [1,2,3,1,1,2,6,6,2]\n let set = Set.fromList int_list\n let result_list = Set.toList set -- [1,2,3,6]\n let tupleLists = toListofTuples result_list\n let result = toString tupleLists \n print result"}, {"source_code": "--ghc problema1.hs -o problema1\n-- ./problema1\nimport qualified Data.Set as Set\nimport Data.List\nsplitComma :: String -> [String]\nsplitComma s = let\n s2 = map (\\c -> if c==',' then ' ' else c) s\n in words s2\nsplitGuion :: String -> [String]\nsplitGuion s = let\n s2 = map (\\c -> if c=='-' then ' ' else c) s\n in words s2\ngroupp :: [String] -> Int -> [String]\ngroupp list i\n |(length list == 0) = [show i]\n |(elem '-' (last list)) == True = if (splitGuion (last list)) !! 1 == show(pred i) then init list ++ [(splitGuion (last list) !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n |otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\nmain = do\n line <- getLine\n let splittedList = splitComma line\n let newList = [read a::Int | a <- splittedList]\n let mySet = Set.fromList newList\n let solution = foldl groupp [] mySet\n let output1 = [a ++ \",\"| a <- (init solution)]\n let output2 = output1 ++ [(last solution)]\n let output3 = foldl1 (++) output2\n print output3"}, {"source_code": "import qualified Data.Set as Set\nimport Data.List\n\nstringSplit :: String -> Char -> [String]\nstringSplit [] delim = [\"\"]\nstringSplit (c:cs) delim\n\t| c == delim = \"\" : rest\n\t| otherwise = (c : head rest) : tail rest\n\twhere\n\t\t\trest = stringSplit cs delim\n\ngroupp :: [String] -> Int -> [String]\ngroupp list i\n\t|(length list == 0) = [show i]\n\t|(elem '-' (last list)) == True = if (stringSplit (last list) '-') !! 1 == show(pred i) then init list ++ [((stringSplit (last list) '-') !! 0) ++ \"-\" ++ show i] else list ++ [show i]\n\t|otherwise = if (last list) == show(pred i) then init list ++ [last list ++ \"-\" ++ show i] else list ++ [show i]\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tlet list = stringSplit line ','\n\tlet intList = map (read::String->Int) list\n\tlet set = Set.fromList intList\n\tlet setList = Set.toList set\n\tlet solution = foldl groupp [] setList\n\tlet output1 = [a ++ \",\"| a <- (init solution)]\n\tlet output2 = output1 ++ [(last solution)]\n\tlet output3 = foldl1 (++) output2\n\tprint output3\n"}, {"source_code": "import qualified Data.Set as Set\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\nmain = do \n input <- getLine\n let out = Set.fromList $ wordsWhen (==',') input\n let out' = Set.foldl group [\"\",\"\"] out\n if last (wordsWhen (==',')(head out')) == last out' \n then putStrLn $ head out'\n else putStrLn $ head out' ++ \"-\" ++ last out'\n\ngroup :: [String] -> String -> [String]\ngroup acc x\n | acc == [\"\",\"\"] = [x,x]\n | (read x :: Integer) == (read (last acc) :: Integer) + 1 = [head acc, x]\n | last (wordsWhen (==',') (head acc)) == last acc = [head acc ++ \",\" ++ x, x]\n | otherwise = [head acc ++ \"-\" ++ last acc ++ \",\" ++ x, x]"}, {"source_code": "import qualified Data.Set as Set\n\ngroup :: [Int] -> Int -> (Bool, Bool)\ngroup [] _ = (False, False)\ngroup (x:xs) e\n | (((succ e) `elem` (x:xs)) && ((pred e) `elem` (x:xs))) = (True, True)\n | ((pred e) `elem` (x:xs)) = (True, False)\n | ((succ e) `elem` (x:xs)) = (False, True) \n | otherwise = (False, False)\n\ngroupList :: [Int] -> [(Bool, Bool)]\ngroupList (x:xs) = tail (scanl (\\a b -> (group (x:xs) (fromIntegral b))) (False, False) (x:xs))\n\nboolText :: [(Bool, Bool)] -> [Int] -> String\nboolText [] [] = \"\"\nboolText ((a, b):xs) (y:ys)\n | ((a == True) && (b == True)) = \"\" ++ (boolText xs ys)\n | ((a == True) && (b == False) && (length ys) > 0) = \"-\" ++ (show y) ++ \",\" ++ (boolText xs ys)\n | ((a == True) && (b == False) && (length ys) == 0) = \"-\" ++ (show y) ++ (boolText xs ys)\n | ((a == False) && (b == True)) = (show y) ++ (boolText xs ys)\n | ((a == False) && (b == False) && (length ys) > 0) = (show y) ++ \",\" ++ (boolText xs ys)\n | otherwise = (show y) ++ (boolText xs ys)\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\nmain = do\n input <- getLine\n let listString = (wordsWhen (==',') input)\n let setInt = Set.fromList (map (read::String->Int) (listString))\n let listInt = Set.toList setInt\n putStrLn(show (boolText (groupList listInt) listInt))"}, {"source_code": "import qualified Data.Set as Set\n\n-- Lista que retorna una tupla de boleanos.\n-- Los boleanos indican si en la lista se encuentran los antecesores o sucesores de un numero\n-- en la lista.\npredSucc :: [Int] -> Int -> (Bool, Bool)\npredSucc [] _ = (False, False)\npredSucc (x:xs) e = if (((succ e) `elem` (x:xs)) && ((pred e) `elem` (x:xs))) then (True, True) else (if(((pred e) `elem` (x:xs))) then (True, False) else (if(((succ e) `elem` (x:xs))) then (False, True) else (False, False)))\n\nprintFinal :: [String] -> String\nprintFinal [] = \"\"\nprintFinal (x:xs) = if (('-' `elem` x) && ((length xs) > 0)) then ((x) ++ printFinal(xs)) else (if (x == \"\") then ((\"\") ++ printFinal(xs)) else (if ((length xs) > 0) then ((x) ++ (\",\") ++ (printFinal(xs))) else (x ++ (printFinal(xs))) ))\n\nboolText :: (Bool, Bool) -> Int -> String\nboolText (True, True) x = \"\"\nboolText (True, False) x = (show x)\nboolText (False, True) x = (show x) ++ \"-\"\nboolText (False, False) x = (show x)\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\ngroup :: [Int] -> [String]\ngroup (x:xs) = scanl (\\a b -> (boolText (predSucc (x:xs) b) b) ) \"\" (x:xs)\n\nmain = do\n input <- getLine\n let listString = (wordsWhen (==',') input)\n let setInt = Set.fromList (map (read::String->Int) (listString))\n let listInt = Set.toList setInt\n print(printFinal (group listInt))"}, {"source_code": "import qualified Data.Set as Set\n\n-- Lista que retorna una tupla de boleanos.\n-- Los boleanos indican si en la lista se encuentran los antecesores o sucesores de un numero\n-- en la lista.\npredSucc :: [Int] -> Int -> (Bool, Bool)\npredSucc [] _ = (False, False)\npredSucc (x:xs) e = if (((succ e) `elem` (x:xs)) && ((pred e) `elem` (x:xs))) then (True, True) else (if(((pred e) `elem` (x:xs))) then (True, False) else (if(((succ e) `elem` (x:xs))) then (False, True) else (False, False)))\n\nprintFinal :: [String] -> String\nprintFinal [] = \"\"\nprintFinal (x:xs) = if (('-' `elem` x) && ((length xs) > 0)) then ((x) ++ printFinal(xs)) else (if (x == \"\") then ((\"\") ++ printFinal(xs)) else (if ((length xs) > 0) then ((x) ++ (\", \") ++ (printFinal(xs))) else (x ++ (printFinal(xs))) ))\n\nboolText :: (Bool, Bool) -> Int -> String\nboolText (True, True) x = \"\"\nboolText (True, False) x = (show x)\nboolText (False, True) x = (show x) ++ \"-\"\nboolText (False, False) x = (show x)\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\ngroup :: [Int] -> [String]\ngroup (x:xs) = scanl (\\a b -> (boolText (predSucc (x:xs) b) b) ) \"\" (x:xs)\n\nmain = do\n input <- getLine\n let listString = (wordsWhen (==',') input)\n let setInt = Set.fromList (map (read::String->Int) (listString))\n let listInt = Set.toList setInt\n print(printFinal (group listInt))"}, {"source_code": "import Data.List\nimport Data.Set\nimport System.IO\n\nsplit :: String -> [String]\nsplit [] = [\"\"]\nsplit (c:cs) \n | (c == ',') = \"\" : resto\n | otherwise = (c : head resto) : tail resto\n where resto = Main.split cs\n\nrangoDePaginas :: String -> Bool\nrangoDePaginas \"\" = False\nrangoDePaginas (x:xs)\n | (x == '-') = True\n | otherwise = rangoDePaginas xs\n\ngroup :: [String] -> Int -> [String]\ngroup pags x\n | pags == [] = [show x] \n | ((rangoDePaginas (head pags) == False) && ((read (head pags)) :: Int) + 1 == x) = [head pags ++ \"-\" ++ show x] ++ tail pags\n | ((rangoDePaginas (head pags) == False) && ((read (head pags)) :: Int) + 1 /= x) = [show x] ++ pags\n | ((rangoDePaginas (head pags) == True) && (n == x)) = [takeWhile (/='-') (head pags) ++ \"-\" ++ show x] ++ tail pags\n | ((rangoDePaginas (head pags) == True) && (n /= x)) = [show x] ++ pags\n where n = (read (tail (dropWhile (/='-') (head pags))) :: Int) + 1\n\npasarAInt :: [String] -> [Int]\npasarAInt [] = []\npasarAInt (x:xs) = (read x :: Int) : pasarAInt xs\n\nmain = do \n paginas <- getLine\n let lista = Main.split paginas\n putStrLn $ show lista\n let listaInt = pasarAInt lista\n let set = Data.Set.fromList listaInt\n let set2 = Data.Set.foldl Main.group [] set\n let set_final = Data.List.reverse set2\n let string = Data.List.intercalate \",\" set_final\n putStrLn string"}, {"source_code": "import qualified Data.Set as S\n\n\n\n\nmain:: IO ()\nmain = do \n -- Se toma la linea como input \n linea <- getLine\n --putStrLn(linea)\n --Split por comas y nos da una lista\n --let x = splitOn \",\" linea\n --print x\n -- de string -> [String]\n let st = foldl split [] linea\n --De conjunto a lista(se quitan los repetidos y se ordena )\n --print st\n let xs = S.toList (S.fromList st)\n --De [String] a [Int]\n let xI = map read xs :: [Int]\n --Se invierte la lista(mas eficiente)\n let r = reverse xI\n --print r\n --Se crean una lista con tuplas(orden ascendente)\n let ivals = foldl addToIntervals [] r\n --print ivals\n let s = foldl intervalsToString [] ivals\n print s\n\n \n\naddToIntervals :: [(Int,Int)] -> Int -> [(Int,Int)]\naddToIntervals [] x = [(x,x)]\naddToIntervals ((a,b):ivs) x = \n if x == a - 1\n then ((x,b):ivs)\n else ((x,x):(a,b):ivs)\n\nintervalsToString :: String ->(Int,Int) -> String\nintervalsToString \"\" (a,b) = \n if a == b\n then show (a)\n else show(a)++\"-\"++show(b) \nintervalsToString ivs (a,b) =\n if a == b\n then ivs++(\",\"++show (a))\n else ivs++(\",\"++show(a)++\"-\"++show(b))\n\nsplit:: [String]-> Char -> [String] \nsplit [] c = [[c]]\nsplit [x] c = \n if c /= ','\n then [x++[c]]\n else [[],x]\nsplit (x:xs) c =\n if c /= ','\n then (x++[c]):xs\n else []:x:xs\n\n\n "}, {"source_code": "import qualified Data.Set as S\n\n\n\n\nmain:: IO ()\nmain = do \n -- Se toma la linea como input \n linea <- getLine\n --putStrLn(linea)\n --Split por comas y nos da una lista\n --let x = splitOn \",\" linea\n --print x\n -- de string -> [String]\n let st = foldl split [] linea\n --De conjunto a lista(se quitan los repetidos y se ordena )\n --print st\n let xs = S.toList (S.fromList st)\n --De [String] a [Int]\n let xI = map read xs :: [Int]\n --Se invierte la lista(mas eficiente)\n let r = reverse xI\n --print r\n --Se crean una lista con tuplas(orden ascendente)\n let ivals = foldl addToIntervals [] r\n --print ivals\n let s = foldl intervalsToString [] ivals\n putStrLn s\n\n \n\naddToIntervals :: [(Int,Int)] -> Int -> [(Int,Int)]\naddToIntervals [] x = [(x,x)]\naddToIntervals ((a,b):ivs) x = \n if x == a - 1\n then ((x,b):ivs)\n else ((x,x):(a,b):ivs)\n\nintervalsToString :: String ->(Int,Int) -> String\nintervalsToString \"\" (a,b) = \n if a == b\n then show (a)\n else show(a)++\"-\"++show(b) \nintervalsToString ivs (a,b) =\n if a == b\n then ivs++(\",\"++show (a))\n else ivs++(\",\"++show(a)++\"-\"++show(b))\n\nsplit:: [String]-> Char -> [String] \nsplit [] c = [[c]]\nsplit [x] c = \n if c /= ','\n then [x++[c]]\n else [[],x]\nsplit (x:xs) c =\n if c /= ','\n then (x++[c]):xs\n else []:x:xs\n\n\n "}, {"source_code": "import Data.List hiding (foldl, group)\n\nimport Data.Set hiding (foldl)\n\nmain = do\n comando <- getLine\n let sincomas = wordsWhen (==',') comando\n let ordenado = ordenar sincomas\n let respuesta = foldl group [] ordenado\n let dar = reverse respuesta\n let solucion = sol False dar\n print solucion\n\nwordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\nordenar :: [String] -> Set Int\nordenar lista = let\n temp = [read x :: Int | x <- lista]\n in fromList temp\n\ngroup :: [String] -> Int -> [String]\ngroup xs b\n | xs == [] = (show b):xs\n | b == ((read(head xs) :: Int) + 1) = show(b):\"-\":xs\n | otherwise = show(b):\",\":xs\n\nsol :: Bool -> [String] -> String\nsol True (a:b:as) = if b == \"-\" then sol True as else a ++ b ++ sol False as\nsol False (a:b:as) = if b == \"-\" then a ++ b ++ sol True as else a ++ b ++ sol False as\nsol a [b] = b"}, {"source_code": "import qualified Data.Set as Set\nimport Data.String\nimport Data.List\nimport Control.Monad (mfilter)\n\nmain = do\n line <- getLine\n let lis = (sort . nub) (map (read::String->Int) (split ',' line)) --lis es la lista sin repetir y ordenada de numeros\n let pal = \"\"\n let ret = foldl grp pal lis\n if 'c' `elem` ret then print $ rc ret else print ret\n --print $ foldl grp pal lis\n\nreplace a b = map $ maybe b id . mfilter (/= a) . Just\n\n--reemplazo el elemento que tenga c con el string que entre (c es para reconocer los numeros que vienen seguidos)\nremp :: String -> String -> String\nremp r st = intercalate \"-\" (filter (\\s -> not ('c' `elem` s)) (split '-' st))++\"-\"++ r\n\n--para remover un c final si es que la linea lo contiene \nrc :: String -> String\nrc str = filter (\\s -> s /= 'c') str\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\n--para obtener el valor numerico del numero \nnumb :: String -> Int\nnumb str = (read nun::Int) where\n nun = filter (\\s -> s /= 'c') str\n\n--funcion group \ngrp:: String -> Int -> String\ngrp \"\" x = \"\"++(show x)\ngrp str x =\n if length (foldl (\\s x -> s ++ split ',' x) [] (split '-' str)) == 1\n then if (read str::Int) == x-1\n then str++\"-\"++(show x)++\"c\"\n else str++\",\"++(show x)\n else do\n let ultim = (concat . (take 1 . reverse)) (foldl (\\s x -> s ++ split ',' x) [] (split '-' str))\n if 'c' `elem` ultim\n then if (numb ultim) == (x-1)\n then remp (show x ++\"c\") str\n else (replace 'c' ',' str)++(show x)\n else if (numb ultim) == (x-1) \n then str ++ \"-\" ++(show x)++\"c\"\n else str ++ \",\" ++(show x)"}, {"source_code": "import System.IO\nimport System.Environment\nimport qualified Data.List as L\nimport qualified Data.Set as Set\nmain = do\n array_n <- getLine\n let list = buildList array_n\n intList = L.sort (Prelude.map read (Set.toList (Set.fromList list)) :: [Int])\n finalList = L.foldl groupNumbers [] intList\n print (L.intercalate \", \" (L.foldl format [] finalList))\n\n\n\nbuildList :: String -> [String]\nbuildList arr =\n if arr == \"\" then\n let args = [\"\"] in args\n else do\n let newarr = split arr ',' in newarr\n\ngroupNumbers :: [[Int]]-> Int ->[[Int]]\ngroupNumbers [] n = [[n]]\ngroupNumbers [x] n =\n if n == (last x) + 1\n then\n let list = x ++ [n] in\n [list]\n else\n [x]++[[n]]\ngroupNumbers (x:xs) n =\n if n == (last x) + 1\n then\n let list = x ++ [n]\n in list:xs\n else\n let lists = x:(groupNumbers xs n) in lists\n\nformat :: [String] -> [Int] ->[String]\nformat s rango =\n if head rango == last rango\n then let r = show (head rango)\n in s++[r]\n else let r = show (head rango) ++ \"-\" ++ show (last rango) in s++[r]\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n"}, {"source_code": "import System.IO\nimport System.Environment\nimport qualified Data.List as L\nimport qualified Data.Set as Set\nmain = do\n array_n <- getLine\n let list = buildList array_n\n intList = L.sort (Prelude.map read (Set.toList (Set.fromList list)) :: [Int])\n finalList = L.foldl groupNumbers [] intList\n putStrLn (L.intercalate \", \" (L.foldl format [] finalList))\n\n\n\nbuildList :: String -> [String]\nbuildList arr =\n if arr == \"\" then\n let args = [\"\"] in args\n else do\n let newarr = split arr ',' in newarr\n\ngroupNumbers :: [[Int]]-> Int ->[[Int]]\ngroupNumbers [] n = [[n]]\ngroupNumbers [x] n =\n if n == (last x) + 1\n then\n let list = x ++ [n] in\n [list]\n else\n [x]++[[n]]\ngroupNumbers (x:xs) n =\n if n == (last x) + 1\n then\n let list = x ++ [n]\n in list:xs\n else\n let lists = x:(groupNumbers xs n) in lists\n\nformat :: [String] -> [Int] ->[String]\nformat s rango =\n if head rango == last rango\n then let r = show (head rango)\n in s++[r]\n else let r = show (head rango) ++ \"-\" ++ show (last rango) in s++[r]\n\nsplit :: String -> Char -> [String]\nsplit [] delim = [\"\"]\nsplit (c:cs) delim\n | c == delim = \"\" : rest\n | otherwise = (c : head rest) : tail rest\n where\n rest = split cs delim\n"}], "src_uid": "3969ba3e3eb55a896663d2c5a5bc4a84"} {"source_code": "import Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Text.Printf\n\nreadInt = fst . fromJust . BS.readInt <$> BS.getLine\n\nmain :: IO ()\nmain = do\n n <- readInt\n values <- replicateM n readInt\n f values\n\nf :: [Int] -> IO ()\nf xs | nv xs == 1 = putStrLn \"Exemplary pages.\"\n | mod (maxs - mins) 2 == 0 && (nv ds == 0 || (nv ds == 1 && (div (maxs+mins) 2) == head ds)) = printf \"%d ml. from cup #%d to cup #%d.\\n\" amount (minl + 1) (maxl + 1)\n | otherwise = putStrLn \"Unrecoverable configuration.\"\n where nv = length.nub\n maxs = maximum xs\n mins = minimum xs\n maxl = fromJust $ elemIndex maxs xs\n minl = fromJust $ elemIndex mins xs\n amount = div (maxs - mins) 2\n ds = xs \\\\ [maxs, mins]\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine\n cups <- replicateM n $ read `liftM` getLine\n\n let minCup = minimum cups\n maxCup = maximum cups\n meanCup = ( minCup + maxCup ) `div` 2\n diffCup = ( maxCup - minCup ) `div` 2\n meanCupCount = length $ filter ( == meanCup ) cups\n minCupIndex = case elemIndex minCup cups of\n Just n -> n+1\n maxCupIndex = case elemIndex maxCup cups of\n Just n -> n+1\n\n putStrLn $ if minCup == maxCup\n then \"Exemplary pages.\"\n else if ( minCup + maxCup ) `mod` 2 /= 0 || meanCupCount /= n - 2\n then \"Unrecoverable configuration.\"\n else show diffCup ++ \" ml. from cup #\" ++ show minCupIndex ++ \" to cup #\" ++ show maxCupIndex ++ \".\"\n"}, {"source_code": "\nimport Control.Monad (replicateM)\nimport Data.List (nubBy, sortBy)\n\ntype Result = Either String (Int, Int, Int)\n\nsolve :: [(Int, Int)] -> Result\nsolve xs\n | length xs' > 3 = Left \"Unrecoverable configuration.\"\n | otherwise = solve' xs'\n where\n xs' = nubBy (\\a b -> snd a == snd b) $ sortBy (\\a b -> compare (snd a) (snd b)) xs\n solve' [_] = Left \"Exemplary pages.\"\n solve' [(n1, a), (n2, b)]\n | odd (b - a) = Left \"Unrecoverable configuration.\"\n | length xs == 2 = Right (n1, n2, div (b - a) 2)\n | otherwise = Left \"Unrecoverable configuration.\"\n solve' [(n1, a), (n2, b), (n3, c)]\n | c - b /= b - a = Left \"Unrecoverable configuration.\"\n | length (filter (\\(n, x) -> x == a) xs) > 1 = Left \"Unrecoverable configuration.\"\n | length (filter (\\(n, x) -> x == c) xs) > 1 = Left \"Unrecoverable configuration.\"\n | otherwise = Right (n1, n3, b - a)\n\nshowResult :: Result -> String\nshowResult (Left s) = s\nshowResult (Right (n, m, x)) =\n concat [show x, \" ml. from cup #\", show n, \" to cup #\", show m, \".\"]\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (replicateM n readLn) :: IO [Int]\n let result = solve $ zip [1..] as\n putStrLn $ showResult result\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine\n cups <- replicateM n $ read `liftM` getLine\n\n let minCup = minimum cups\n maxCup = maximum cups\n meanCup = ( minCup + maxCup ) `div` 2\n diffCup = ( maxCup - minCup ) `div` 2\n meanCupCount = length $ filter ( == meanCup ) cups\n minCupIndex = case elemIndex minCup cups of\n Just n -> n+1\n maxCupIndex = case elemIndex maxCup cups of\n Just n -> n+1\n\n putStrLn $ if minCup == maxCup\n then \"Exemplary pages.\"\n else if ( minCup + maxCup ) `mod` 2 /= 0 || meanCupCount /= n - 2\n then \"Unrecoverable configuration.\"\n else show diffCup ++ \" ml. from cup #\" ++ show maxCupIndex ++ \" to cup #\" ++ show minCupIndex ++ \".\"\n"}], "src_uid": "7bfc0927ea7abcef661263e978612cc5"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nbuildPairs :: [(Char, Char)] -> Array Char Char\nbuildPairs list = listArray ('a', 'z') [findPair c | c <- ['a'..'z']] where\n findPair c = case find ((== c) . fst) list of\n Nothing -> 'Z'\n Just c' -> snd c'\n\npresent :: Array Char Char -> Char -> (Int, Int)\npresent ps a =\n let a' = ps ! a\n in if a < a' then (1, 0)\n else (0, 1)\n\nsplit :: Array Char Char -> [Char] -> [(Int, Int)]\nsplit ps [c] = present ps c : []\nsplit ps (a:b:str') = let\n (a1, a2) = present ps a\n ret@((r1, r2):ret') = split ps (b:str')\n in if ps ! a == b || a == b\n then (r1 + a1, r2 + a2) : ret'\n else (a1, a2) : ret\n\nsolve ps str = sum $ map (uncurry min) $ split ps str\n\nmain = do\n str <- getLine\n\n n <- liftM read getLine\n list <- liftM concat $ replicateM n $ do\n [a, b] <- getLine\n return [(a, b), (b, a)]\n\n let ans = solve (buildPairs list) str\n\n print ans\n", "positive_code": [{"source_code": "import qualified Data.Map as Map\nimport Data.List\ns (m : _ : t) = minimum $ foldl' step (replicate 26 0) m where\n enemies = Map.fromList (map (\\[a,b]->(a,b)) t ++ map (\\[a,b]->(b,a)) t)\n enemy a = Map.lookup a enemies\n step acc ch = sum acc `seq` case enemy ch of \n Nothing -> [if a == ch then minimum acc else n+1 |(a, n) <- zip ['a'..] acc]\n Just nme -> [if a == ch then minimum (map snd $ filter (\\(b, n) -> b /= nme) $ zip ['a'..] acc) else n+1 |(a, n) <- zip ['a'..] acc]\nmain = interact $ show . s . lines\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.Map.Strict as M\n\nmatch !n !m _ _ [] = (min n m,[])\nmatch !n !m c d xs@(x:xt)\n | x == c = match (n+1) m c d xt\n | x == d = match n (m+1) c d xt\n | otherwise = (min n m, xs)\n\nnext pairs str = go str\n where\n go [] = (0,[])\n go (c:cs) = case M.lookup c pairs of\n Nothing -> go cs\n Just d -> match 1 0 c d cs\n\ntoMap plist = M.fromList (concatMap f plist)\n where f (a:b:_) = [(a,b),(b,a)]\n\nsolve pairs [] = []\nsolve pairs str =\n let (k,str') = next pairs str\n in k : solve pairs str'\n\ntest1 = solve (toMap [\"pg\",\"nb\"]) \"pgpgppgggpbbnnn\"\n\nmain = do\n str <- getLine\n n <- fmap read getLine\n plist <- replicateM n getLine\n let pairs = toMap plist\n answer = sum $ solve pairs str :: Int\n print answer\n\n"}, {"source_code": "import Data.List\nimport Data.Map(Map)\nimport qualified Data.Map as M\nimport Control.Applicative\n\nmain = do cs <- getLine\n _ <- getLine\n mcc <- M.fromList . concatMap (\\[x,y]->[(x,y),(y,x)]). lines <$> getContents\n print $ solve cs mcc \n\nsolve :: String -> Map Char Char -> Int\nsolve cs mcc = solve' mcc 0 [] cs\n\nsolve' :: Map Char Char -> Int -> String -> String -> Int\nsolve' mcc i _ [] = i\n-- solve' mcc i _ [r] = i\nsolve' mcc i [] (r:rs) = solve' mcc i [r] rs\nsolve' mcc i (c:cs) (r:rs)\n | Just r == M.lookup c mcc = let (xs,xs') = span (c==) (c:cs)\n (ys,ys') = span (flip elem [c,r]) (r:rs)\n\t\t\t\t (j,zs) = f. partition (c==) $ xs++ys\n\t\t\t in solve' mcc (i+j) (zs++xs') ys'\n | otherwise = solve' mcc i (r:c:cs) rs\n\nf (cs,rs)\n | lc <= lr = (lc,rs)\n | otherwise = (lr,cs)\n where lc = length cs\n lr = length rs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.Map.Strict as M\n\nmatch !k d c [] = (k,[])\nmatch !k d c xs@(x:xt)\n | x == d = match (k+1) c d xt\n | otherwise = (k,xs)\n\nnext pairs str = go str\n where\n go [] = (0,[])\n go (c:cs) = case M.lookup c pairs of\n Nothing -> go cs\n Just d -> match 1 d c cs\n\ntoMap plist = M.fromList (concatMap f plist)\n where f (a:b:_) = [(a,b),(b,a)]\n\nsolve pairs [] = []\nsolve pairs str =\n let (k,str') = next pairs str\n in k : solve pairs str'\n\nmain = do\n str <- getLine\n n <- fmap read getLine\n plist <- replicateM n getLine\n let pairs = toMap plist\n answer = sum $ map (`div` 2) $ solve pairs str :: Int\n print answer\n\n"}], "src_uid": "da2b3450a3ca05a60ea4de6bab9291e9"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Integer). words $ line\n\t\t--arr = if k == 0 then [(1::Integer)..n] else [(1::Integer)..(k-1)] ++ [k+1] ++ [k] ++ [k+2..n]\n\t\tarr = [k+1, k..1] ++ [k+2..n]\n--\tprint n\n--\tprint k\n\tmapM_ (\\x -> putStr (show x ++ \" \")) $ arr\n \n", "positive_code": [{"source_code": "main=interact$unwords.map show.f.map read.words\nf [n,k] = [k+1,k..1]++[k+2..n]\n \n"}, {"source_code": "printNumbers :: [Int] -> IO ()\nprintNumbers [] = return ()\nprintNumbers (x:[]) = do\n putStrLn (show x)\nprintNumbers (x:xs) = do\n putStr (show x)\n putStr \" \"\n printNumbers xs\n\ntoNumbers :: String -> [Int]\ntoNumbers [] = []\ntoNumbers x = val : (toNumbers xs)\n where\n [(val,xs)] = reads x :: [(Int, String)]\n\nmain = do\n ns <- getLine\n let\n [n,k] = toNumbers ns\n in\n let\n (a,b) = splitAt (n-k) [1..n]\n in\n printNumbers ((reverse b) ++ a)\n return ()"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [Int]\nsolve [n, k] = [n, n-1 .. n-k+1] ++ [1 .. n-k]\n\nmain :: IO ()\nmain = reads >>= putStrLn . intercalate \" \" . map show . solve"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Integer] -> [Integer]\nsolve [ n, k ] = [ n, n - 1 .. n - k + 1 ] ++ [ 1 .. n - k ]\nsolve _ = undefined\n"}, {"source_code": "main=interact$unwords.map show.f.map read.words\nf[n,k]=[n,n-1..n-k+1]++[1..n-k]\n"}, {"source_code": "import Data.List\nsolve [n, k] = [n, n-1 .. n-k+1] ++ [1..n-k]\nmain = fmap (map read . words) getLine >>= putStrLn . intercalate \" \" . map show . solve\n"}, {"source_code": "main=interact$unwords.map show.f.map read.words\nf[n,k]=[k+1,k..1]++[k+2..n]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \nprocess _ _ _ _ _ [] = -1\nprocess a b sums cs n (s:ss) | and [ cs>=a,cs <=b, sums-cs >=a, sums-cs <=b] = n\n | otherwise = process a b sums (cs+s) (n+1) ss\n\n\nmain= do\n\t[a,b]<- map read. words <$> getLine ::IO [Int]\n\tputStrLn $ intercalate \" \" $ map show $ [b+1,b..1] ++ [b+2..a]"}, {"source_code": "import Data.List\nimport Prelude hiding ((.))\n(.) a b = b a\n\nmain = do\n a <- getLine\n let [n, k] = a . words . map (read :: String -> Int)\n r = [n, n - 1 .. n - k + 1] ++ [1 .. n - k] \n r . map show . intercalate \" \" . putStr"}, {"source_code": "import Data.List\n\nmain = interact $ intercalate \" \" . (map show) . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (n:k:_) = [1..(n-k-1)] ++ reverse [(n-k)..n]"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [Int]\nsolve [n, k] = [n, n-1 .. n-k+1] ++ [1 .. n-k]\n\nmain :: IO ()\nmain = reads >>= print . solve"}, {"source_code": "main=interact$unwords.map show.f.map read.words\nf[n,k]=xs++n:ys\n where\n (xs,ys)=splitAt (k-1)[1..n-1]"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Int). words $ line\n\t\tarr = if k == 0 then [1..n] else [1..(k-1)] ++ [k+1] ++ [k] ++ [k+2..n]\n--\tprint n\n--\tprint k\n\tmapM_ (\\x -> putStr (show x ++ \" \")) $ arr\n\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Integer). words $ line\n\t\tarr = if k == 0 then [(1::Integer)..n] else [(1::Integer)..(k-1)] ++ [k+1] ++ [k] ++ [k+2..n]\n--\tprint n\n--\tprint k\n\tmapM_ (\\x -> putStr (show x ++ \" \")) $ arr\n \n"}, {"source_code": "import Data.List\nimport Prelude hiding ((.))\n(.) a b = b a\n\nmain = do\n a <- getLine\n let [n, k] = a . words . map (read :: String -> Int)\n r = [n, n - 1 .. n - k + 1] ++ [1 .. k + 1] \n r . map show . intercalate \" \" . putStr"}, {"source_code": "import Data.List\nimport Prelude hiding ((.))\n(.) a b = b a\n\nmain = do\n a <- getLine\n let [n, k] = a . words . map (read :: String -> Int)\n r = [n, n - 1 .. n - k + 1] ++ [1 .. k + 1] \n r . map show . intercalate \" \" . print"}], "src_uid": "75cc5b55c51217966cbdd639a68f0724"} {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds #-}\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Traversable\nimport System.IO\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\ngetInt = fst . fromJust . B.readInt . dropCR <$> B.getLine\n\nbshow = B.pack . show\n\nquery i = do\n B.putStrLn $ \"? \" <> bshow i\n hFlush stdout\n getInt\n\nanswer i = do\n B.putStrLn $ \"! \" <> bshow i\n hFlush stdout\n\nmain = do\n n <- getInt\n let m = (n + 1) `quot` 2\n inf = n + 1\n mv <- query m\n go 0 inf m mv (n + 1) inf\n\ngo l lv m mv r rv = assert (l < m && m < r) $\n assert (lv > mv && mv < rv) $\n case (m - l, r - m) of\n (1, 1) -> answer m\n (lw, rw) | lw > rw -> do let m' = (l + m) `quot` 2\n mv' <- query m'\n if mv' > mv\n then go m' mv' m mv r rv\n else go l lv m' mv' m mv\n | otherwise -> do let m' = (m + r) `quot` 2\n mv' <- query m'\n if mv' > mv\n then go l lv m mv m' mv'\n else go m mv m' mv' r rv\n", "positive_code": [{"source_code": "import System.IO\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nget :: Int -> IO Int\nget i = do\n C.putStrLn $ C.pack $ \"? \" ++ show i\n hFlush stdout\n fst . fromJust . C.readInt <$> C.getLine\n\nsolve :: (Int, Int) -> (Int, Int) -> IO Int\nsolve (l, x) (r, y)\n | l == r = return l\n | l + 1 == r = return $ if x < y then l else r\n | l + 2 == r = get m >>= return . g\n | otherwise = f\n where\n m = (l + r) `quot` 2\n g z | z > x = l\n | z > y = r\n | otherwise = m\n f = do\n z1 <- get m\n z2 <- get (m + 1)\n if z1 < z2\n then solve (l, x) (m, z1)\n else solve (m + 1, z2) (r, y)\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n x <- get 1\n y <- get n\n result <- solve (1, x) (n, y)\n C.putStrLn $ C.pack $ \"! \" ++ show result\n"}, {"source_code": "-- For completeness, I will test the other output\r\n-- methods provided by bytestring, though I expect\r\n-- them to get ILE even despite NoBuffering and \"flush\"\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as S\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport Data.ByteString.Builder.Extra (flush)\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\n--import Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nquery :: Int -> B.Builder\r\nquery pos = B.string7 \"? \" <> B.intDec pos <> B.char7 '\\n'\r\n\r\nsolve :: Int -> Int -> State [P.ByteString] B.Builder\r\nsolve li ri\r\n | li == ri = pure $ B.string7 \"! \" <> B.intDec li <> B.char7 '\\n'\r\n | otherwise = do\r\n let mi = li + div (ri - li) 2\r\n ~[v1, v2] <- getInts 2\r\n (\\rest -> query mi <> query (mi + 1) <> flush <> rest) <$> if v1 < v2\r\n then solve li mi\r\n else solve (mi + 1) ri\r\n\r\nmainFun :: State [P.ByteString] B.Builder\r\nmainFun = do\r\n ~[n] <- getInts 1\r\n solve 1 n\r\n\r\ntype SP = StateT [P.ByteString]\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> B.Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in case vs of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n --forM_ (P.toChunks $ B.toLazyByteString outp) S.putStr\r\n P.putStr $ B.toLazyByteString outp\r\n"}, {"source_code": "-- TODO: clean up the imports a little if possible\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport Data.ByteString.Builder.Extra (flush)\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\n--import Control.Monad.Trans.Class\nimport Data.Semigroup\n\nquery :: Int -> B.Builder\nquery pos = B.string7 \"? \" <> B.intDec pos <> B.char7 '\\n'\n\nsolve :: Int -> Int -> State [P.ByteString] B.Builder\nsolve li ri\n | li == ri = pure $ B.string7 \"! \" <> B.intDec li <> B.char7 '\\n'\n | otherwise = do\n let mi = li + div (ri - li) 2\n ~[v1, v2] <- getInts 2\n (\\rest -> query mi <> query (mi + 1) <> flush <> rest) <$> if v1 < v2\n then solve li mi\n else solve (mi + 1) ri\n\nmainFun :: State [P.ByteString] B.Builder\nmainFun = do\n ~[n] <- getInts 1\n solve 1 n\n\ntype SP = StateT [P.ByteString]\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> B.Builder\nputInts vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n forM_ (P.toChunks $ B.toLazyByteString outp) S.putStr\n\n"}, {"source_code": "-- This is the result of my testing out a possible rework of my code\n-- placeholder: Solving an interactive problem with purely functional\n-- time travel. Unfortunately, the overhead of this incarnation is\n-- unacceptably high. See the notes near main at the bottom.\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Fail\nimport Data.Semigroup\n\nquery :: Int -> SIO Int\nquery pos = do\n ~[ans] <- getInts 1 -- Does it look dangerous to do this \"before\" printing?\n putBuilder $ B.string7 \"? \" <> B.intDec pos <> B.char7 '\\n'\n ans <$ flush\n\nsolve :: Int -> Int -> SIO Int\nsolve li ri\n | li == ri = pure ri\n | otherwise = do\n let mi = li + div (ri - li) 2\n v1 <- query mi\n v2 <- query $ mi + 1 -- Ask yourself: Why can't this be n+1?\n if v1 < v2 then solve li mi else solve (mi + 1) ri\n\nmainFun :: SIO ()\nmainFun = do\n [n] <- getInts 1\n ans <- solve 1 n\n putBuilder $ B.string7 \"! \" <> B.intDec ans <> B.char7 '\\n'\n\nnewtype TwoState x y v = TwoState { runTwoState :: x -> y -> (v, x, y) }\ntype SIO = TwoState [P.ByteString] [B.Builder]\n\ninstance Functor (TwoState x y) where\n fmap fun act = TwoState $ \\x y -> let\n (v, rx, ry) = runTwoState act x y\n in (fun v, rx, ry)\n\n v <$ act = TwoState $ \\x y -> let\n (_, rx, ry) = runTwoState act x y\n in (v, rx, ry)\n\ninstance Applicative (TwoState x y) where\n pure v = TwoState $ \\x y -> (v, x, y)\n\n act1 <*> act2 = TwoState $ \\x0 y2 -> let\n (fun, x1, y0) = runTwoState act1 x0 y1\n (arg, x2, y1) = runTwoState act2 x1 y2\n in (fun arg, x2, y0)\n\n liftA2 fun act1 act2 = TwoState $ \\x0 y2 -> let\n (v1, x1, y0) = runTwoState act1 x0 y1\n (v2, x2, y1) = runTwoState act2 x1 y2\n in (fun v1 v2, x2, y0)\n\ninstance Monad (TwoState x y) where\n act >>= fun = TwoState $ \\x0 y2 -> let\n (arg, x1, y0) = runTwoState act x0 y1\n (res, x2, y1) = runTwoState (fun arg) x1 y2\n in (res, x2, y0)\n\n act1 >> act2 = TwoState $ \\x0 y2 -> let\n (_, x1, y0) = runTwoState act1 x0 y1\n (res, x2, y1) = runTwoState act2 x1 y2\n in (res, x2, y0)\n\n return = pure\n\ninstance MonadFail (TwoState x y) where\n fail = error\n\nputBuilder :: B.Builder -> SIO ()\nputBuilder v = TwoState $ \\inp (c : cs) -> ((), inp, v <> c : cs)\n\nflush :: SIO ()\nflush = TwoState $ \\inp cs -> ((), inp, mempty : cs)\n\ngetNext :: Int -> SIO [P.ByteString]\ngetNext k = TwoState $ \\inp outp -> let\n (res, remInp) = splitAt k inp\n in (res, remInp, outp)\n\ngetInts :: Int -> SIO [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputIntsB :: [Int] -> B.Builder\nputIntsB li = let\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in case li of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\n\nputInts :: [Int] -> SIO ()\nputInts = putBuilder . putIntsB\n\nmain :: IO ()\nmain = do\n inpLi <- P.words <$> P.getContents\n let ((), _remInput, output) = runTwoState mainFun inpLi [mempty]\n forM_ output $ \\v -> B.hPutBuilder stdout v >> hFlush stdout\n\nns :: [Int]\nns = [1 .. 3000000]\n\n-- Below are several alternate versions of main that each print every\n-- number in ns to stdout. Most are acceptable, but one is not: the\n-- one that accumulates its result via the time travel monad.\n\n\n-- This version took 140ms on Codeforces custom invocation. It's\n-- probably close to ideal in terms of output speed in Haskell. It's\n-- only around 30% slower at this task than the fast hand-rolled\n-- fwrite-buffer and putchar C++ implementations at the blog\n-- https://codeforces.com/blog/entry/74544 and exceeds the \"good\n-- enough\" threshold by a lot.\n--main = B.hPutBuilder stdout $ putIntsB ns\n\n-- This version took 218ms on Codeforces custom invocation. It's\n-- probably the fastest version that makes for a fair comparison,\n-- since it combines the results of many different putIntsB calls.\n--main = B.hPutBuilder stdout $ mconcat [putIntsB [i] | i <- ns]\n\n-- This version took 404ms on Codeforces custom invocation. It's the\n-- base-line, representing something very close to what my current\n-- StateT-based template can typically achieve. For comparison,\n-- std::cout with C++17 (64) took 343ms, which should make clear that\n-- this is still very much \"good enough\" and then some.\n--main = forM_ ns $ \\i -> B.hPutBuilder stdout $ putIntsB [i]\n\n-- This version took 2199ms on Codeforces custom invocation and used 377684KB,\n-- which would MLE on most Codeforces problems. This is unacceptable.\n-- Obviously, some things are lingering longer than they should.\n{-\nmain = do\n inpLi <- P.words <$> P.getContents\n let fun = forM_ ns $ \\i -> putInts [i]\n let ((), _remInput, output) = runTwoState fun inpLi [mempty]\n forM_ output $ \\v -> B.hPutBuilder stdout v >> hFlush stdout\n-}\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport System.IO\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\noutLine :: String -> SIO ()\noutLine = lift . P.putStrLn . P.pack\n\nsolve :: Int -> Int -> SIO ()\nsolve li ri\n | li == ri = outLine (\"! \" ++ show li) >> lift (hFlush stdout)\n | otherwise = do\n let mi = div (li + ri) 2\n outLine (\"? \" ++ show mi)\n outLine (\"? \" ++ show (mi+1))\n lift $ hFlush stdout\n [p] <- readInts\n [q] <- readInts\n if p < q then solve li mi else solve (mi+1) ri\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n] <- readInts\n solve 1 n\n"}], "negative_code": [{"source_code": "import System.IO\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nsolve :: Int -> Int -> IO ()\nsolve l r\n | r - l <= 10 = func1 l r >>= \\i -> C.putStrLn $ C.pack $ \"! \" ++ show i\n | otherwise = func (l + 1) (r - 1)\n\nget :: Int -> IO Int\nget i = do\n C.putStrLn $ C.pack $ \"? \" ++ show i\n hFlush stdout\n fst . fromJust . C.readInt <$> C.getLine\n\nfunc1 :: Int -> Int -> IO Int\nfunc1 l r = do\n xs <- forM [l .. r] get\n return $ fst $ head $ filter (\\(i, x) -> (i == l || x < xs !! (i - l - 1)) && (i == r || x < xs !! (i - l + 1))) $ zip [l .. r] xs\n\nfunc :: Int -> Int -> IO ()\nfunc l r = do\n x <- get l\n y <- get r\n let m1 = l + (r - l) `div` 3\n m2 = l + (r - l) * 2 `div` 3\n z1 <- get m1\n z2 <- get m2\n let f | z1 > x = solve l m1\n | z2 > y = solve m2 r\n | z1 < z2 = solve l m2\n | otherwise = solve m1 r\n f\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n solve 1 n\n"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nsolve :: Int -> Int -> IO ()\nsolve l r\n | r - l <= 3 = func1 l r >>= \\i -> C.putStrLn $ C.pack $ \"! \" ++ show i\n | otherwise = func (l + 1) (r - 1)\n\nget :: Int -> IO Int\nget i = do\n C.putStrLn $ C.pack $ \"? \" ++ show i\n hFlush stdout\n fst . fromJust . C.readInt <$> C.getLine\n\nfunc1 :: Int -> Int -> IO Int\nfunc1 l r = do\n xs <- forM [l .. r] get\n return $ fst $ head $ filter (\\(i, x) -> (i == l || x < xs !! (i - l - 1)) && (i == r || x < xs !! (i - l + 1))) $ zip [l .. r] xs\n\nfunc :: Int -> Int -> IO ()\nfunc l r = do\n x <- get l\n y <- get r\n let m1 = l + (r - l) `div` 3\n m2 = l + (r - l) * 2 `div` 3\n z1 <- get m1\n z2 <- get m2\n let f | z1 > x = solve l m1\n | z2 > y = solve m2 r\n | z1 < z2 = solve l m2\n | otherwise = solve m1 r\n f\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n solve 1 n\n"}], "src_uid": "c091ca39dd5708f391b52de63faac6b9"} {"source_code": "\nimport Monad (liftM)\n\nused :: Int -> Int -> Int\nused = (*)\n\nnotUsed :: (Int, Int, Int) -> (Int, Int) -> Int -> Int\nnotUsed (p1, p2, p3) (t1, t2) t\n | t <= t1 = p1 * t\n | t <= t1 + t2 = p1 * t1 + p2 * (t - t1)\n | otherwise = p1 * t1 + p2 * t2 + p3 * (t - t1 - t2)\n\nsolve :: (Int, Int, Int) -> (Int, Int) -> [(Int, Int)] -> Int\nsolve (p1, _, _) _ [(l, r)] = used p1 (r - l)\nsolve (p1, p2, p3) (t1, t2) ((l, r):xs) \n = used p1 (r - l)\n + notUsed (p1, p2, p3) (t1, t2) (fst (head xs) - r)\n + solve (p1, p2, p3) (t1, t2) xs\n\nreadPair :: String -> (Int, Int)\nreadPair line = case words line of\n [a, b] -> (read a, read b)\n\nmain :: IO ()\nmain = do\n [n, p1, p2, p3, t1, t2] <- liftM (map read . words) getLine\n xs <- liftM (map readPair . take n . lines) getContents\n print $ solve (p1, p2, p3) (t1, t2) xs\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess p1 p2 p3 t1 t2 [[a,b]] = (b-a)*p1\nprocess p1 p2 p3 t1 t2 ([a,b]:[c,d]:es) = (((b-a)+ (min (c-b) t1))*p1 + (max 0 ((min (c-b-t1) t2)*p2)) + (max 0 ( (c-b-t1-t2) *p3))) + (process p1 p2 p3 t1 t2 ([c,d]:es) )\n\nmain = do\n\t\t[n,p1,p2,p3,t1,t2]<-map read <$> words <$> getLine ::IO [Int]\n\t\ta<-map (map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n\t\tlet x = process p1 p2 p3 t1 t2 a\n\t\tprint x \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Numeric\nfastRead !s = case readDec s of [(n, \"\")] -> n\n\nparse :: String -> ((Int, Int, Int), (Int, Int), [Int])\nparse foo = case map (map fastRead . words) $ lines foo of\n [_,p1,p2,p3,t1,t2]:xs -> ((p1,p2,p3), (t1,t2), concat xs)\n _ -> error \"dupa\"\n\n\nsolve ((p1,p2,p3), (t1,t2), xs@(x:_)) =\n loop x xs (p1,p2,p3) (t1,t2) 0\n\nloop _ [] _ _ acc = acc\nloop old (l:r:xs) ps@(p1,p2,p3) ts@(t1,t2) acc =\n loop r xs ps ts (acc + p1 * (min (l - old) t1) + (r - l)*p1 + m (p2 * (min (l - old - t1) t2)) + m (p3 * (l - old - t2 - t1)))\n\nm = (max 0)\n\nmain = (print . solve . parse =<< getContents)"}, {"source_code": "read_array = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n let l:r:_ = read_array s\n xs <- getLines (n-1)\n return ((l,r):xs)\n\nget_delay len p1 p2 p3 t1 t2 = (min len t1)*p1 +\n (f (len-t1) t2)*p2 +\n (max (len-t1-t2) 0)*p3\n where f = \\a b -> max 0 $ min a b\n\ncount _ [] _ _ _ _ _ _ = 0\ncount last_r ((l,r):xs) n p1 p2 p3 t1 t2= (r-l)*p1 + \n get_delay (l-last_r) p1 p2 p3 t1 t2 +\n count r xs n p1 p2 p3 t1 t2\n\nmain = do\n s <- getLine\n let n:p1:p2:p3:t1:t2:_ = read_array s\n lines <- getLines n\n let cost = count (fst $ head lines) lines n p1 p2 p3 t1 t2\n putStrLn $ show cost\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n let readInts = map read . words\n [n, p1, p2, p3, t1, t2] <- readInts . head\n [l1, r1] : xs <- map readInts . take n . drop 1\n let f (t, total) [l, r] = (r, total + (r - l + d1) * p1 + d2 * p2 + d3 * p3)\n where interval = l - t\n d1 = min t1 interval\n d2 = min t2 (max 0 (interval - d1))\n d3 = max 0 (interval - d1 - d2)\n return . show . snd $ foldl' f (r1, (r1 - l1) * p1) xs\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess p1 p2 p3 t1 t2 [[a,b]] = (b-a)*p1\nprocess p1 p2 p3 t1 t2 ([a,b]:[c,d]:es) = (((b-a)+ (min (c-b) t1))*p1 + (min (c-b-t1) t2)*p2 + ( (c-b-t1-t2) *p3)) + (process p1 p2 p3 t1 t2 ([c,d]:es) )\n\nmain = do\n\t\t[n,p1,p2,p3,t1,t2]<-map read <$> words <$> getLine ::IO [Int]\n\t\ta<-map (map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n\t\tprint $ process p1 p2 p3 t1 t2 a\n\n"}], "src_uid": "7ed9265b56ef6244f95a7a663f7860dd"} {"source_code": "import Data.List\r\n\r\ncalculate :: Int -> [Int] -> Int -> Int -> Int -> Int\r\ncalculate _ _ _ 0 _ = 0\r\ncalculate x (first : rest) total len dayTotal = do\r\n let day = if (x < total) then 0 else (x - total) `div` len + 1\r\n let dayTotalNew = dayTotal + day\r\n let pack = day * len\r\n let totalNew = (total + len * day) - (first + dayTotalNew)\r\n pack + calculate x rest totalNew (len - 1) dayTotalNew\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n nxInput <- getLine\r\n aInput <- getLine\r\n let [n, x] = [read e :: Int | e <- words nxInput]\r\n let a = [read e :: Int | e <- words aInput]\r\n let total = sum a\r\n let aSortedDescending = sortBy (flip compare) a\r\n let result = calculate x aSortedDescending total (length a) 0\r\n return (show result)\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)", "positive_code": [{"source_code": "import Data.List\r\n\r\ncalculate :: Int -> [Int] -> Int -> Int -> Int -> Int\r\ncalculate _ _ _ 0 _ = 0\r\ncalculate x (first : rest) total len dayTotal = do\r\n let day = if (x < total) then 0 else (x - total) `div` len + 1\r\n let dayTotalNew = dayTotal + day\r\n let pack = day * len\r\n let totalNew = (total + len * day) - (first + dayTotalNew)\r\n pack + calculate x rest totalNew (len - 1) dayTotalNew\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n nxInput <- getLine\r\n aInput <- getLine\r\n let [n, x] = [read e :: Int | e <- words nxInput]\r\n let a = [read e :: Int | e <- words aInput]\r\n let total = sum a\r\n let aSorted = sort a\r\n let result = calculate x (reverse aSorted) total (length a) 0\r\n return (show result)\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)"}], "negative_code": [], "src_uid": "b65767c1ebfe72e08f58a9f9254eaa7b"} {"source_code": "import Data.Char\n\nmain :: IO()\nmain = print . solve =<< getLine\n\ntoBase64 :: Char -> Int\ntoBase64 c | '0' <= c && c <= '9' = ord c - ord '0'\n | 'A' <= c && c <= 'Z' = ord c - ord 'A' + 10\n | 'a' <= c && c <= 'z' = ord c - ord 'a' + 36\n | c == '-' = 62\n | c == '_' = 63\n\nnumOf0 :: Int -> Integer\nnumOf0 = numOf0' 6\n where numOf0' :: Int -> Int -> Integer\n numOf0' 0 _ = 0\n numOf0' n x | even x = 1 + numOf0' (n - 1) (x `div` 2)\n | otherwise = numOf0' (n - 1) (x `div` 2)\n\nmodC :: Integer\nmodC = 1000000007\n\npow :: Integer -> Integer -> Integer\nx `pow` y | y == 0 = 1\n | y == 1 = x `mod` modC\n | odd y = x * (x `pow` (y - 1)) `mod` modC\n | even y = let x' = x `pow` (y `div` 2)\n in x' * x' `mod` modC\n\nsolve :: String -> Integer\nsolve s = let m = sum $ map (numOf0 . toBase64) s\n in 3 `pow` m \n", "positive_code": [{"source_code": "import qualified Data.Bits as B\nimport qualified Data.Map as M\nalphabet = ['0'..'9']++['A'..'Z']++['a'..'z']++\"-_\"\ncountNil :: Int -> Int\ncountNil x = 6 - B.popCount x\nnullBits = M.fromList (zip alphabet $ map countNil [0..63])\nsolve :: String -> Integer\nsolve s = 3 ^ (sum $ map (nullBits M.!) s) `mod` (10^9 + 7)\nmain = putStrLn.show.solve =<< getLine"}], "negative_code": [], "src_uid": "1b336555c94d5d5198abe5426ff6fa7a"} {"source_code": "main :: IO ()\nmain = readLn >>= (\\xs -> print (length xs) >> putStrLn (unwords (map show xs))). solve\n\nsolve :: Int -> [Int]\nsolve 1 = [1]\nsolve 2 = [1]\nsolve 3 = [1, 3]\nsolve 4 = [2, 4, 1, 3]\nsolve n = take n (concatMap (\\k -> [k, k + (n + 1) `div` 2]) [1..])\n", "positive_code": [{"source_code": "-- Codeforces 534A\n\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n let result = solve n\n putStrLn $ (show $ length result) ++ \"\\n\" ++ concatMap (\\x -> show x ++ \" \") result\n\nsolve :: Int -> [Int]\nsolve 1 = [1]\nsolve 2 = [1]\nsolve 3 = [1, 3]\nsolve n = (reverse $ filter odd [1..n]) ++ (reverse $ filter even [1..n])\n"}, {"source_code": "main=readLn>>=(\\x->print(length x)>>putStrLn(unwords(map show x))).f\nf n=(if n>3 then[2,4..n]else[])++[1,3..n]\n"}, {"source_code": "import Data.List\n\ngao' :: [Int] -> [Int] -> [Int] -> [Int]\ngao' xs lt rt\n | null lt || null rt = xs\n | otherwise = gao' (xs ++ [head lt] ++ [head rt]) (tail lt) (tail rt)\n\ngao :: Int -> [Int]\ngao n\n | n == 1 || n == 2 = [1]\n | n == 3 = [1, 3]\n | n == 4 = [3, 1, 4, 2]\n | otherwise = case n `mod` 2 of 1 -> gao' [(n + 1) `div` 2] [1..n `div` 2] [n `div` 2 + 2..n]\n 0 -> gao' [] [1..n `div` 2] [n `div` 2 + 1..n]\n\nmain :: IO()\nmain = do\n n <- getLine\n let res = gao $ read n\n print $ length res\n putStrLn . unwords $ map show res\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [Int] -> [Int] -> [Int]\nsolve xs lt rt\n | null lt || null rt = xs\n | otherwise = solve (xs ++ [head lt] ++ [head rt]) (tail lt) (tail rt)\n\ngao :: Int -> [Int]\ngao n\n | n == 1 || n == 2 = [1]\n | n == 3 = [1, 3]\n | n == 4 = [3, 1, 4, 2]\n | otherwise = case n `mod` 2 of 1 -> solve [(n + 1) `div` 2] [1..n `div` 2] [n `div` 2 + 2..n]\n 0 -> solve [] [1..n `div` 2] [n `div` 2 + 1..n]\n\nmain :: IO()\nmain = do\n n <- getLine\n let res = gao $ read n\n print $ length res\n putStrLn . unwords $ map show res\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad hiding (foldM, foldM_)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray)\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n n <- readLn\n let (k, xs) = solve n\n print k\n putStrLn.unwords $ map show xs\n\nsolve :: Int -> (Int, [Int])\nsolve 1 = (1, [1])\nsolve 2 = (1, [1])\nsolve 3 = (2, [1, 3])\nsolve n = (n, go [3,1,4,2] [] [5..n])\n where\n go ls rs (x:y:xs) = go (x:ls) (y:rs) xs\n go ls rs [x] = x:ls ++ rs\n go ls rs [] = ls ++ rs\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nfoldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a\nfoldM a xs f=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: Int -> (Int, [Int])\nsolve 1 = (1, [1])\nsolve 2 = (1, [1])\nsolve 3 = (2, [1, 3])\nsolve n = (n, concat $ transpose [y, x])\n where\n (x, y) = splitAt (n `div` 2) [1..n]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let (k, ks) = solve n\n putStrLn $ show k\n putStrLn $ unwords . map show $ ks"}, {"source_code": "ans :: Int -> [Int]\nans 1 = [1]\nans 2 = [1]\nans 3 = [1, 3]\nans 4 = [3, 1, 4, 2]\nans n = [1, 3 .. n] ++ [2, 4 .. n]\n\nmain = getLine >>= \\s' -> do\n let s = ans (read s')\n putStrLn . show $ length s\n putStrLn . unwords $ map show s\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \nprocess 1 = (1, [1])\nprocess 2 = ( 1,[1])\nprocess 3 = (2,[1,3])\nprocess 4 = (4, [3,1,4,2])\nprocess n = (n, (filter (odd ) [1..n]) ++ (filter (even ) [1..n]))\n\nmyprint ( x,y) = do\n\t\t\tputStrLn $ show x\n\t\t\tputStrLn $ intercalate \" \" $ map show $ y\n\t\t\t\n\n\nmain= do\n\tn<- read <$>getLine :: IO Int\n\tmyprint $ process n\n\t\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n s = case n of\n 1 -> [1]\n 2 -> [1]\n 3 -> [1, 3]\n 4 -> [3, 1, 4, 2]\n n -> [1,3..n] ++ [2,4..n]\n\n print $ length s\n putStrLn $ unwords $ map show s\n"}, {"source_code": "main = interact $ unlines . g . f . read\ng s = [show (length s), unwords (map show s)]\nf 1 = [1]\nf 2 = [1]\nf 3 = [1, 3]\nf s = h [1..div s 2] [div s 2 + 1..s]\nh [] a = a\nh (a:b) (c:d) = c:a:h b d"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n s = case n of\n 1 -> [1]\n 2 -> [1]\n 3 -> [1, 3]\n 4 -> [1, 4, 2]\n n -> [1,3..n] ++ [2,4..n]\n\n print $ length s\n putStrLn $ unwords $ map show s\n"}, {"source_code": "main = interact $ unlines . g . f . read\ng s = [show (length s), unwords (map show s)]\nf 1 = [1]\nf 2 = [1]\nf 3 = [1, 3]\nf 4 = [1, 4, 2]\nf 5 = [1, 4, 2, 5, 3]\nf s = h [1..div s 2] [div s 2 + 1..s]\nh [] a = a\nh (a:b) (c:d) = a:c:h b d"}, {"source_code": "main = interact $ unlines . g . f . read\ng s = [show (length s), unwords (map show s)]\nf 1 = [1]\nf 2 = [1]\nf 3 = [1, 3]\nf 4 = [1, 4, 2]\nf 5 = [1, 4, 2, 5, 3]\nf s = h [1..div s 2] [div s 2 + 1..s]\nh [] a = a\nh (a:b) (c:d) = c:a:h b d"}, {"source_code": "main :: IO ()\nmain = readLn >>= (\\xs -> print (length xs) >> putStrLn (unwords (map show xs))). solve\n\nsolve :: Int -> [Int]\nsolve 1 = [1]\nsolve 2 = [1]\nsolve 3 = [1, 3]\nsolve 4 = [1, 4, 2]\nsolve n = take n (concatMap (\\k -> [k, k + (n + 1) `div` 2]) [1..])\n"}], "src_uid": "a52ceb8a894809b570cbb74dc5ef76e1"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata State a = Node (Maybe (Int, State a)) [a] (State a)\n\nmain :: IO ()\nmain = do\n [_, k] <- getInts\n str@(_ : str') <- filter (not . isSpace) . C.unpack <$> C.getLine\n let initial = Node Nothing str first\n first = Node (Just (1, initial)) str' (extend 2 initial str')\n findNext char node@(Node p s n)\n | char == head s = n\n | isJust p = findNext char (snd $ fromJust p)\n | otherwise = node\n extend _ _ [] = Node Nothing [] undefined\n extend idx prev (char : chars') = node'\n where node' = Node (Just (idx, prev')) chars' (extend (idx + 1) prev' chars')\n prev' = findNext char prev\n getIndex (Node Nothing _ _) = 0\n getIndex (Node (Just (i, _)) _ _) = i\n step node@(Node (Just (idx, prev)) [] _) _ = Left (idx - getIndex prev)\n step node@(Node (Just (idx, prev)) (char : _) next) _\n | getNextChar prev < char = Left (idx - getIndex prev)\n | otherwise = Right next\n where getNextChar (Node _ (c : _) _) = c\n getNextChar _ = error \"\"\n Left num = foldM step first $ repeat ()\n result = take k $ cycle $ take num str\n hPutBuilder stdout $ string7 result <> charUtf8 '\\n'\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: String -> Int -> String \r\nsolve s k =\r\n let\r\n ts = tails (tail s ++ \"~\")\r\n t = foldr1 op ts\r\n op s0 s1 = if s0 > s then s0 else s1\r\n l = length s - length t + 1\r\n in\r\n take k $ cycle (take l s)\r\n\r\nmain = do\r\n [n,k] <- map parseInt . BS.words <$> BS.getLine\r\n s <- dropWhileEnd isSpace . BS.unpack <$> BS.getLine\r\n putStrLn $ solve s k"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata State a = Node (Maybe (Int, State a)) [a] (State a)\n\nmain :: IO ()\nmain = do\n [_, k] <- getInts\n str@(_ : str') <- filter (not . isSpace) . C.unpack <$> C.getLine\n let initial = Node Nothing str first\n first = Node (Just (1, initial)) str' (extend 2 initial str')\n findNext char node@(Node p s n)\n | char == head s = n\n | isJust p = findNext char (snd $ fromJust p)\n | otherwise = node\n extend _ _ [] = Node Nothing [] undefined\n extend idx prev (char : chars') = node'\n where node' = Node (Just (idx, prev')) chars' (extend (idx + 1) prev' chars')\n prev' = findNext char prev\n step node@(Node (Just (idx, _)) [] _) _ = Left idx\n step node@(Node (Just (idx, prev)) (char : _) next) _\n | getNextChar prev < char = Left (idx - getIndex prev)\n | otherwise = Right next\n where getNextChar (Node _ (c : _) _) = c\n getNextChar _ = error \"\"\n getIndex (Node Nothing _ _) = 0\n getIndex (Node (Just (i, _)) _ _) = i\n Left num = foldM step first $ repeat ()\n result = take k $ cycle $ take num str\n hPutBuilder stdout $ string7 result <> charUtf8 '\\n'\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata State a = Node (Maybe (Int, State a)) [a] (State a)\n\nmain :: IO ()\nmain = do\n [_, k] <- getInts\n str@(_ : str') <- C.unpack <$> C.getLine\n let initial = Node Nothing str first\n first = Node (Just (1, initial)) str' (extend 2 initial str')\n findNext char node@(Node p s n)\n | char == head s = n\n | isJust p = findNext char (snd $ fromJust p)\n | otherwise = node\n extend _ _ [] = Node Nothing [] undefined\n extend idx prev (char : chars') = node'\n where node' = Node (Just (idx, prev')) chars' (extend (idx + 1) prev' chars')\n prev' = findNext char prev\n step node@(Node (Just (idx, _)) [] _) _ = Left idx\n step node@(Node (Just (idx, prev)) (char : _) next) _\n | getNextChar prev < char = Left (idx - getIndex prev)\n | otherwise = Right next\n where getNextChar (Node _ (c : _) _) = c\n getNextChar _ = error \"\"\n getIndex (Node Nothing _ _) = 0\n getIndex (Node (Just (i, _)) _ _) = i\n Left num = foldM step first $ repeat ()\n result = take k $ cycle $ take num str\n hPutBuilder stdout $ string7 result <> charUtf8 '\\n'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: String -> Int -> String \r\nsolve s k =\r\n let\r\n ts = tails (tail s ++ \"^\")\r\n t = foldr1 op ts\r\n op s0 s1 = if s0 > s then s0 else s1\r\n l = length s - length t + 1\r\n in\r\n take k $ cycle (take l s)\r\n\r\nmain = do\r\n [n,k] <- map parseInt . BS.words <$> BS.getLine\r\n s <- dropWhileEnd isSpace . BS.unpack <$> BS.getLine\r\n putStrLn $ solve s k"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: String -> Int -> String \r\nsolve s k =\r\n let\r\n ts = tails (tail s ++ \"^\")\r\n t = foldr1 op ts\r\n op s0 s1 = if s0 > s then s0 else s1\r\n l = length s - length t + 1\r\n in\r\n take k $ cycle (take l s)\r\n\r\nmain = do\r\n [n,k] <- map parseInt . BS.words <$> BS.getLine\r\n s <- dropWhile isSpace . BS.unpack <$> BS.getLine\r\n putStrLn $ solve s k"}], "src_uid": "87f64b4d5baca4b80162ae6075110b00"} {"source_code": "import Data.List\nwork p (a, b) = if c > a then (c, b * (1 - p)) else (a, 0) where c = (1 - p) * a + p * b\nmain = interact $ show . fst . foldr work (0.0, 1.0) . sort . map read . tail . words\n", "positive_code": [{"source_code": "import Data.List\n\nmain=interact $ (++ \"\\n\") . show . getAns 0 1. getArray\n\ngetArray :: String -> [Double]\ngetArray = reverse . sort . tail . map read . words\n\ngetAns :: Double -> Double -> [Double] -> Double\ngetAns x _ [] = x\ngetAns a b (x:xs) =\n\tlet na = a * (1 - x) + b * x\n\t nb = b * (1 - x)\n\tin if na > a then getAns na nb xs else a\n"}, {"source_code": "import Data.List\nimport Text.Printf\nwork p (a, b) = if c > a then (c, b * (1 - p)) else (a, 0) where c = (1 - p) * a + p * b\nmain = interact $ printf \"%.11f\" . fst . foldr work (0 :: Double, 1) . sort . map read . tail . words\n"}, {"source_code": "import Data.List\nimport Text.Printf\n\nf :: [Double] -> Double\nf x = let y = map (1.0-) x\n in (foldl1' (*) y) * (foldl1' (+) $ zipWith (/) x y) \n\nmain = do\n _ <- getLine\n l <- getLine\n let inp = reverse . sort $ map (\\y -> read y :: Double) $ words l\n let ans = if head inp >= 1.0 then 1.0 else foldl1' max $ map f $ map (\\y -> take y $ inp) [1..(length inp)]\n printf \"%.10f\\n\" ans"}, {"source_code": "import Data.List\nimport Text.Printf\n\ng :: Double -> [Double] -> [Double] -> [Double]\ng s l [] = l\ng s l (x:xs) =\n if s >= 1.0 then l\n else g (s+x/(1.0 - x)) (x:l) xs\nf x = let y = map (1.0-) x\n in (product y) * (sum $ zipWith (/) x y)\n\nmain = do\n _ <- getLine\n l <- getLine\n let inp = reverse . sort $ map (\\y -> read y :: Double) $ words l\n let ans = if head inp >= 1.0 then 1.0 else f $ g 0.0 [] inp\n printf \"%.10f\\n\" ans"}], "negative_code": [{"source_code": "import Data.List\nimport Text.Printf\n\nf :: [Double] -> Double\nf x = let y = map (1.0-) x\n in (foldl1' (*) y) * (foldl1' (+) $ zipWith (/) x y) \n\nmain = do\n _ <- getLine\n l <- getLine\n let inp = map (\\y -> read y :: Double) $ words l\n printf \"%.10f\\n\" $ foldl1' max $ map f $ map (\\y -> take y $ reverse inp) [1..(length inp)]"}, {"source_code": "import Data.List\nimport Text.Printf\nwork p (a, b) = if c > a then (c, b * (1 - p)) else (a, 0) where c = (1 - p) * a + p * b\nmain = interact $ printf \"%.11f\" . fst . foldr work (0 :: Float, 1) . sort . map read . tail . words\n"}], "src_uid": "b4ac594755951e84001dfd610d420eb5"} {"source_code": "module Main where\n\nimport Control.Monad\n\nf :: (Int, Int, Int) -> Double\nf (m, w, x) =\n max (0.3 * fromIntegral x) ( (1.0 - fromIntegral m / 250.0) * fromIntegral x - 50.0 * fromIntegral w )\n\nmain :: IO ()\nmain = do\n ms <- liftM (map (\\c -> read c::Int) . words) getLine\n ws <- liftM (map (\\c -> read c::Int) . words) getLine\n [h', h''] <- liftM (map (\\c -> read c::Int) . words) getLine\n let r' = sum (map f (zip3 ms ws [500, 1000, 1500, 2000, 2500]))\n r'' = 100 * h' - 50 * h''\n putStrLn $ show $ floor (r' + fromIntegral r'')\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Ratio\n\ngetScore :: Integer -> Integer -> Integer -> Rational\ngetScore x m w = max ((3 * x) % 10) ((1 - m % 250) * (x % 1) - ((50 * w) % 1))\n\nreadIntegers :: IO [Integer]\nreadIntegers = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n let xs = [500, 1000, 1500, 2000, 2500] :: [Integer]\n ms <- readIntegers\n ws <- readIntegers\n [hs, hu] <- readIntegers\n\n let result = (sum $ zipWith3 getScore xs ms ws) + (100 * hs) % 1 - (50 * hu) % 1\n print $ numerator result\n"}, {"source_code": "module Main where\n\n import Data.Ratio\n\n calcRes :: [(Integer,Integer,Integer)] -> Integer -> Integer -> Ratio Integer\n calcRes ts hs hu = sum (map (\\(m,w,p) -> max (p*3%10) ((1-(m%250))*(p%1) - (50*w%1))) ts) + (hs*100%1) - (hu*50%1)\n\n main :: IO ()\n main = do\n ms <- getLine\n ws <- getLine\n h <- getLine\n let ts = zip3 (map (read::String->Integer) $ words ms) (map (read::String->Integer) $ words ws) [500,1000,1500,2000,2500]\n let [hs,hu] = map (read::String->Integer) (words h)\n putStrLn $ head $ words $ show $ calcRes ts hs hu\n"}, {"source_code": "\ncalc :: Int -> Int -> Int -> Int \ncalc a b c = max (a*150) ( a* (500 - (b*2)) - 50 * c)\n\nsolve :: [Int] -> Int\nsolve x = (calc 1 (x!!0) (x!!5)) + (calc 2 (x!!1) (x!!6))+ (calc 3 (x!!2) (x!!7))+ (calc 4 (x!!3) (x!!8))+ (calc 5 (x!!4) (x!!9)) + (x!!10) * 100 - (x!!11) * 50\n\nreadInt :: String -> Int\nreadInt = read\n\nparse :: String -> String\nparse x = show $ solve a where a = map readInt $ words x\n\n\n\nmain = interact parse"}, {"source_code": "import Control.Applicative\n\npoints :: [Integer]\npoints = [500, 1000, 1500, 2000, 2500]\n\nsolve :: [Integer] -> [Integer] -> Integer -> Integer -> Integer\nsolve ms ws hs hu = sum (zipWith3 score points ms ws) + hs * 100 - hu * 50\n where\n score x m w = round $ max (0.3 * fi x) ((1 - fi m / 250) * fi x - 50 * fi w)\n fi = fromIntegral\n\nmain :: IO ()\nmain = do\n ms <- map read . words <$> getLine\n ws <- map read . words <$> getLine\n [hs, hu] <- map read . words <$> getLine\n print $ solve ms ws hs hu\n"}, {"source_code": "(|>) a b = b a\n\nf x m w = \n max (0.3 * x) ((1 - m / 250) * x - 50 * w)\n \nr s1 s2 s3 =\n let ms = s1 |> words |> map (read :: String -> Int) \n ws = s2 |> words |> map (read :: String -> Int) \n hs = s3 |> words |> map (read :: String -> Int) \n xs = [500, 1000, 1500, 2000, 2500]\n g zs y = fromIntegral (zs !! y)\n sum1 = [0..4] |> map (\\y -> round $ f (g xs y) (g ms y) (g ws y)) |> sum\n in\n sum1 + (hs !! 0) * 100 - (hs !! 1) * 50\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n s3 <- getLine\n print (r s1 s2 s3)"}, {"source_code": "import System.IO\n\nmax_points :: [Int]\nmax_points = [500, 1000, 1500, 2000, 2500]\n\nformula :: (Int, Int, Int) -> Int\n-- x - max points, m - time, w - count of submissions\nformula (x, m, w) = round $ max (0.3 * fromIntegral x) ((1 - fromIntegral m / 250.0) * fromIntegral x - 50 * fromIntegral w)\n\ncnt_tasks :: Integer\ncnt_tasks = 5\n\ngetPoints :: [Int] -> [Int] -> Int\ngetPoints a b = (sum . (map formula)) (zip3 max_points a b)\n\nparseList :: String -> [Int]\nparseList = (map read) . words\n\nmain :: IO ()\nmain = do\n let fin = stdin\n-- fin <- openFile \"tmp\" ReadMode\n time_line <- hGetLine fin\n submissions_line <- hGetLine fin\n hacks_line <- hGetLine fin\n \n let [hacks_good, hacks_bad] = parseList hacks_line\n print $ getPoints (parseList time_line) (parseList submissions_line) + hacks_good * 100 - hacks_bad * 50\n"}, {"source_code": "parseInput :: String -> ([Int], [Int], [Int])\nparseInput input = (xs, ys, zs) where\n ls = lines input\n ws = map words ls\n xs = map read $ head ws\n ys = map read $ head $ tail ws\n zs = map read $ last ws \n\nscore :: [Int] -> [Int] -> Int\nscore ms ws = sum [max ((3*x) `div` 10) ((250 - m)*(x `div` 250) - 50*w) | (x, m, w) <- ds] where\n ps = [500, 1000, 1500, 2000, 2500]\n ds = zip3 ps ms ws\n\nhacks :: [Int] -> Int\nhacks hs = sum [h*p | (h, p) <- zip hs ps] where\n ps = [100, -50]\n\nsolve :: [Int] -> [Int] -> [Int] -> Int\nsolve ms ws hs = score ms ws + hacks hs\n\nmain :: IO ()\nmain = do\n input <- getContents\n let (ms, ws, hs) = parseInput input\n print $ solve ms ws hs\n"}], "negative_code": [], "src_uid": "636a30a2b0038ee1731325a5fc2df73a"} {"source_code": "import System.IO\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t rtc\r\n mapM (putStrLn . show . solve) tcs\r\nri = map read . words <$> getLine :: IO [Int]\r\nrtc = do\r\n [_n] <- ri\r\n ri\r\nsolve xs = length xs - length suff\r\n where\r\n suff = tail . takeWhile (not.snd) . scanl' addElem (Set.empty, False) . reverse $ xs\r\n\r\n addElem (set, True ) _ = (set, True)\r\n addElem (set, False) newElem\r\n | ((==) `on` Set.size) set newSet = (Set.empty, True )\r\n | otherwise = (newSet , False)\r\n where\r\n newSet = newElem `Set.insert` set\r\n", "positive_code": [{"source_code": "module Main where\r\nimport Control.Monad\r\nimport qualified Data.IntSet as Ds\r\n \r\nimport Data.Maybe\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n\r\n--import qualified Data.HashSet as Set \r\n \r\nremainList2::Int->Int->Ds.IntSet->[Int]->Int \r\nremainList2 n ne hSet x\r\n |ne==1 =1\r\n |(ne>1)&&(n==ne)=ne\r\n |(x!!n)`Ds.member`hSet=n \r\n |otherwise=remainList2 (n+1) ne s2 x\r\n where s2=Ds.insert (x!!n) hSet\r\nslice::[Int]->Int->Int->[Int]\r\nslice xs i k = take (k-i) $ drop i xs \r\nremainList1::Int->Int->Int->[Int]->Int->Int\r\nremainList1 l r nList x n\r\n |nList==1 =0\r\n |l>r= n\r\n |(Ds.size$Ds.fromList (slice x mid nList))==(nList-mid) =remainList1 l (mid -1) nList x n1\r\n |otherwise=remainList1 (mid+1) r nList x n\r\n where mid=(l+r)`div`2\r\n n1=min n mid\r\n\r\n\r\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\r\nmain = do\r\n line<-getLine\r\n let nTest=read line::Int \r\n -- number of test\r\n replicateM_ nTest$do\r\n line<-getLine\r\n let nList=read line::Int\r\n -- list length \r\n list<-getInts \r\n let listNew=list \r\n let hSet=Ds.fromList (take 1 listNew)\r\n --print$(nList-(remainList2 1 nList hSet listNew))\r\n print$remainList1 0 nList nList listNew nList\r\n -- input list\r\n\r\n\r\n"}], "negative_code": [{"source_code": "module Main where\r\nimport Control.Monad\r\nimport qualified Data.IntSet as Ds\r\n \r\nimport Data.Maybe\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n\r\n--import qualified Data.HashSet as Set \r\n \r\nremainList2::Int->Int->Ds.IntSet->[Int]->Int \r\nremainList2 n ne hSet x\r\n |ne==1 =1\r\n |(ne>1)&&(n==ne)=ne\r\n |(x!!n)`Ds.member`hSet=n \r\n |otherwise=remainList2 (n+1) ne s2 x\r\n where s2=Ds.insert (x!!n) hSet\r\nslice::[Int]->Int->Int->[Int]\r\nslice xs i k = take (k-i) $ drop i xs \r\nremainList1::Int->Int->Int->[Int]->Int->Int\r\nremainList1 l r nList x n\r\n |nList==1 =0\r\n |l>r= n\r\n |(Ds.size$Ds.fromList (slice x mid nList))==(nList-mid) =remainList1 l (mid -1) nList x n1\r\n |otherwise=remainList1 (mid+1) r nList x n\r\n where mid=(l+r)`div`2\r\n n1=min n mid\r\n\r\n\r\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\r\nmain = do\r\n line<-getLine\r\n let nTest=read line::Int \r\n -- number of test\r\n replicateM_ nTest$do\r\n line<-getLine\r\n let nList=read line::Int\r\n -- list length \r\n list<-getInts \r\n let listNew=reverse list \r\n let hSet=Ds.fromList (take 1 listNew)\r\n --print$(nList-(remainList2 1 nList hSet listNew))\r\n print$remainList1 0 nList nList listNew nList\r\n -- input list\r\n\r\n\r\n"}, {"source_code": "module Main where\r\nimport Control.Monad\r\nimport qualified Data.IntSet as Ds\r\n \r\nimport Data.Maybe\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n\r\n--import qualified Data.HashSet as Set \r\n \r\nremainList2::Int->Int->Ds.IntSet->[Int]->Int \r\nremainList2 n ne hSet x\r\n |ne==1 =1\r\n |(ne>1)&&(n==ne)=ne\r\n |(x!!n)`Ds.member`hSet=n \r\n |otherwise=remainList2 (n+1) ne s2 x\r\n where s2=Ds.insert (x!!n) hSet\r\nslice::[Int]->Int->Int->[Int]\r\nslice xs i k = take (k-i) $ drop i xs \r\nremainList1::Int->Int->Int->[Int]->Int->Int\r\nremainList1 l r nList x n\r\n |r-l==1 =1\r\n |l>r= n\r\n |(Ds.size$Ds.fromList (slice x mid nList))==(r-mid) =remainList1 l (mid -1) nList x n1\r\n |otherwise=remainList1 (mid+1) r nList x n\r\n where mid=(l+r)`div`2\r\n n1=min n mid\r\n\r\n\r\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\r\nmain = do\r\n line<-getLine\r\n let nTest=read line::Int \r\n -- number of test\r\n replicateM_ nTest$do\r\n line<-getLine\r\n let nList=read line::Int\r\n -- list length \r\n list<-getInts \r\n let listNew=reverse list \r\n let hSet=Ds.fromList (take 1 listNew)\r\n --print$(nList-(remainList2 1 nList hSet listNew))\r\n print$remainList1 0 nList nList listNew nList\r\n -- input list\r\n\r\n\r\n"}, {"source_code": "module Main \r\n where\r\nimport Control.Monad\r\nimport Data.List\r\nmyfind::Int->Int->Int->[Int]->Maybe Bool \r\nmyfind x ns ne y\r\n |ne==(-1)=Nothing\r\n |x==y!!ns =Just True\r\n |(ns+1)Int->[Int]->Bool \r\nremainList x ne y\r\n |(myfind x 0 ne y)==Nothing =True\r\n |otherwise=False\r\n\r\nremainList2::Int->[Int]->[Int]\r\nremainList2 _ []=[] \r\nremainList2 n x\r\n |n==ne =x\r\n |remainList (x!!n) (n-1) x= remainList2 (n+1) x\r\n |otherwise=(take n x)\r\n where ne=length x \r\nmain::IO()\r\nmain = do\r\n line<-getLine\r\n let nTest=read line::Int \r\n -- number of test\r\n replicateM_ nTest$do\r\n line1<-getLine\r\n let nList=read line1::Int\r\n -- list length \r\n line2<-getLine \r\n let list=map read (words line2)::[Int]\r\n let listNew=reverse list \r\n print$nList-(length$remainList2 0 listNew)\r\n -- input list\r\n\r\n\r\n"}, {"source_code": "import System.IO\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t rtc\r\n mapM (putStrLn . show . solve) tcs\r\nri = map read . words <$> getLine :: IO [Int]\r\nrtc = do\r\n [_n] <- ri\r\n ri\r\nsolve xs = length xs - length suff\r\n where\r\n suff = takeWhile (not.snd) . scanl' addElem (Set.empty, False) . reverse $ xs\r\n\r\n addElem (set, True ) _ = (set, True)\r\n addElem (set, False) newElem\r\n | ((==) `on` Set.size) set newSet = (Set.empty, True )\r\n | otherwise = (newSet , False)\r\n where\r\n newSet = newElem `Set.insert` set\r\n"}], "src_uid": "4aaa33f77fe1c89ae477bd5cfa04f0bf"} {"source_code": "main = do\n\tinput <- getLine\n\tlet n = read input :: Int\n\tfin <- getContents\n\tlet size = map (map read) (map words (take n (lines fin))) :: [[Int]]\n\tlet result = [x*y `div` 2 + x*y `mod` 2 | [x,y] <- size]\n\tmapM print result", "positive_code": [{"source_code": "divideAndCeil :: Int -> Int\ndivideAndCeil n\n | mod n 2 == 0 = div n 2\n | otherwise = div (n+1) 2\n\nsolve :: Int -> Int -> Int\nsolve n m\n | m == 1 = divideAndCeil n\n | m == 2 = n\n | otherwise = (solve n 2) + (solve n (m-2))\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n\nparse :: String -> String\nparse input = show $ solve n m\n where [n, m] = map (\\x -> read x :: Int) $ words input\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq, ViewL (..), (<|), (|>))\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Data.Tree\nimport Text.Printf\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = C.interact $\n C.lines >>> drop 1 >>> map (C.words >>> map readInt >>> solve >>> show >>> C.pack) >>> C.unlines\n\nreadInt = C.readInt >>> fromJust >>> fst\n\nsolve [n,m]\n | even (n*m) = (n*m) `div` 2\n | otherwise = (n*m) `div` 2 + 1\n"}, {"source_code": "import Control.Arrow\nimport Control.Monad.State\nimport Data.Array\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = C.interact $\n C.lines >>> drop 1 >>> map (C.words >>> map readInt >>> solve >>> show >>> C.pack) >>> C.unlines\n\nreadInt = C.readInt >>> fromJust >>> fst\n\nsolve [n,m]\n | even (n*m) = (n*m) `div` 2\n | otherwise = (n*m) `div` 2 + 1\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:m:_) <- map read . words <$> getLine\n print $ (n * m + 1) `div` 2"}, {"source_code": "import Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let (_:tokens) = split input\n vals = read <$> tokens :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n (n:m:rest) ->\n let numCells = n*m\n subres = (numCells + 1) `div` 2\n in Just (subres, rest)\n ) vals\n sequence_ (putStrLn <$> (show <$> res))\n"}, {"source_code": "import Control.Monad\n\nparse :: [String] -> [[Integer]]\nparse = map (\\l -> map read . words $ l)\n\nsolve :: [Integer]->Integer\nsolve (n:m:[])\n | (even n) && (odd m) = n*(div m 2) + (div n 2)\n | (even n) && (even m) = n*(div m 2)\n | (odd n) && (n>=m) = (solve [(n-1),m])+ (div m 2)+(mod m 2)\n | otherwise = solve [m,n]\n\n\nmain :: IO ()\nmain = do\n n <- getLine\n content <- replicateM (read n :: Int) getLine\n putStrLn . unlines . map show . map solve . parse $ content\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ div ((a*b) +1 ) 2\n\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\t\n\n"}, {"source_code": "main :: IO ()\nmain = interact (unlines . map (show . solve) . parse)\n\nparse :: String -> [(Int, Int)]\nparse inp = [(x, y) | [x, y] <- map (map read . words) . tail $ lines inp]\n\nsolve :: (Int, Int) -> Int\nsolve (x, y) = quot (x*y + 1) 2\n"}], "negative_code": [], "src_uid": "19df5f3b8b31b763162c5331c1499529"} {"source_code": "data Child = Child { index :: Integer\n , office :: Integer\n , hall :: Integer\n , confid :: Integer\n} deriving (Eq, Show)\n\ndecrease :: Integer -> [Child] -> [Child]\ndecrease vol = zipWith f [vol, vol - 1 .. ]\n where f x c = if x > 0 then c {confid = confid c - x} else c\n\nsimplify :: Integer -> [Child] -> [Child]\nsimplify _ [] = []\nsimplify vol (c:cs) =\n if confid c < vol\n then simplify (vol + hall c) cs\n else c {confid = confid c - vol} : simplify vol cs\n\ngennady :: [Child] -> [Integer]\ngennady [] = []\ngennady (c:cs) = index c : gennady (simplify 0 $ decrease (office c) cs)\n\nconvert :: [[Integer]] -> [Child]\nconvert = zipWith (\\i [v, d, p] -> Child i v d p) [1..]\n\nparse = convert . map (map read . words) . tail . lines\nans xs = unlines [show (length xs), unwords (map show xs)]\n\nmain = putStr . ans . gennady . parse =<< getContents", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\n\ndata Child = Child { index :: Integer\n , office :: Integer\n , hall :: Integer\n , confid :: Integer\n} deriving (Eq, Show)\n\ndecrease :: Integer -> [Child] -> [Child]\ndecrease vol = zipWith f [vol, vol - 1 .. ]\n where f x c = if x > 0 then c {confid = confid c - x} else c\n\nsimplify :: Integer -> [Child] -> [Child]\nsimplify _ [] = []\nsimplify vol (c:cs) =\n if confid c < vol\n then simplify (vol + hall c) cs\n else c {confid = confid c - vol} : simplify vol cs\n\ngennady :: [Child] -> [Integer]\ngennady [] = []\ngennady (c:cs) = index c : gennady (simplify 0 $ decrease (office c) cs)\n\nconvert :: [[Integer]] -> [Child]\nconvert = zipWith (\\i [v, d, p] -> Child i v d p) [1..]\n\nparse = convert . map (map read' . B.words) . tail . B.lines\n where read' s = case B.readInteger s of Just (n, _) -> n\nans xs = unlines [show (length xs), unwords (map show xs)]\n\nmain = putStr . ans . gennady . parse =<< B.getContents"}, {"source_code": "module Main where\n\ndata Kid a = Kid {\n position :: a\n , vDoctor :: a\n , vHall :: a\n , confidence :: a\n }\n deriving (Show)\n\nexit :: (Num a, Ord a) => a -> [Kid a] -> [Kid a]\nexit _ [] = []\nexit v (kid:kids)\n | conf' >= 0 = kid {confidence = conf'} : exit v kids\n | otherwise = exit (v + vHall kid) kids\n where\n conf' = confidence kid - v\n\npropagate :: (Num a, Eq a) => a -> [Kid a] -> [Kid a]\npropagate _ [] = []\npropagate 0 kids = kids\npropagate v (kid:kids) = kid {confidence = conf'} : propagate (v-1) kids\n where\n conf' = confidence kid - v\n\ntreat :: (Num a, Ord a) => [Kid a] -> [a]\ntreat (kid:kids) = position kid:(treat . exit 0 . propagate (vDoctor kid)) kids\ntreat [] = []\n\ninput1 :: [Kid Int]\ninput1 = [Kid 1 4 2 2, Kid 2 4 1 2, Kid 3 5 2 4, Kid 4 3 3 5, Kid 5 5 1 2]\n\ninput2 :: [Kid Int]\ninput2 =\n [Kid 1 4 5 1\n ,Kid 2 5 3 9\n ,Kid 3 4 1 2\n ,Kid 4 2 1 8\n ,Kid 5 4 1 9]\n\nmain :: IO ()\nmain = do\n contents <- getContents\n putStr (readAndTreat contents)\n \nreadAndTreat :: String -> String\nreadAndTreat input =\n let (first:allLines) = lines input\n n = read first\n kids = readAll n 1 allLines\n treated = treat kids\n resultLines = [show $ length treated, unwords $ map show treated]\n result = unlines resultLines\n in result\n\nreadAll :: (Num a, Read a, Show a, Ord a) => a -> a -> [String] -> [Kid a]\nreadAll n i _ | i > n = [] \nreadAll _ i [] = error $ \"End of file reached but only \" ++ show i ++ \" lines read.\"\nreadAll n i (l:ls) = Kid i vD vH c : readAll n (i+1) ls\n where [vD,vH,c] = map read $ words l\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Monad (forM)\nimport Data.Maybe (catMaybes)\n\ndata Child = Child\n { i :: !Int\n , vi :: !Integer\n , di :: !Integer\n , pi :: !Integer\n } deriving (Show)\n\ngo :: [Child] -> [Int]\ngo [] = []\ngo (c@Child {..} : cs) =\n let other = panic 0 $ screamHealing vi cs in\n i : go other\n where\n screamHealing :: Integer -> [Child] -> [Child]\n screamHealing 0 ccs = ccs\n screamHealing _ [] = []\n screamHealing v (cc@(Child j vj dj pj) : ccs) =\n (Child j vj dj (pj - v)) : (screamHealing (v - 1) ccs)\n\n panic :: Integer -> [Child] -> [Child]\n panic _ [] = []\n panic d (cc@(Child j vj dj pj) : ccs) =\n let pj' = pj - d in\n if pj' < 0 then\n panic (d + dj) ccs\n else\n (Child j vj dj pj') : panic d ccs\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine\n children <- forM [1..n] $ \\i -> do\n [v, d, p] <- (map read . words) `fmap` getLine\n return $ Child i v d p\n let ans = go children\n putStrLn $ show $ length ans\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (pure, (<$>))\nimport Control.Monad (forM)\n\ndata Child = Child\n { i :: !Int\n , vi :: !Integer\n , di :: !Integer\n , pi :: !Integer\n } deriving (Show)\n\ngo :: [Child] -> [Int]\ngo [] = []\ngo (c@Child {..} : cs) =\n let other = panic 0 $ screamHealing vi cs in\n i : go other\n where\n screamHealing :: Integer -> [Child] -> [Child]\n screamHealing 0 ccs = ccs\n screamHealing _ [] = []\n screamHealing v (cc@(Child j vj dj pj) : ccs) =\n (Child j vj dj (pj - v)) : (screamHealing (v - 1) ccs)\n\n panic :: Integer -> [Child] -> [Child]\n panic _ [] = []\n panic d (cc@(Child j vj dj pj) : ccs) =\n let pj' = pj - d in\n if pj' < 0 then\n panic (d + dj) ccs\n else\n (Child j vj dj pj') : panic d ccs\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n children <- forM [1..n] $ \\i -> do\n [v, d, p] <- (map read . words) <$> getLine\n pure $ Child i v d p\n let ans = go children\n putStrLn $ show $ length ans\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "import Control.Monad (replicateM)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.Functor ((<$>))\nimport Data.List (foldl', transpose)\nimport Data.Maybe (fromJust)\nimport Data.Int\n\nupdate\n :: Int\n -> Int64\n -> [Int]\n -> [Int]\n -> [(Int64, Int)]\n -> ([Int], [Int], [(Int64, Int)])\nupdate _ _ [] _ _ = ([], [], [])\nupdate x t (v:vs) (d:ds) (p:ps)\n | fst p - val < 0 = update (x - 1) (t + fromIntegral d) vs ds ps\n | otherwise = (v : vs', d : ds', (fst p - val, snd p) : ps')\n where\n val =\n if x > 0\n then fromIntegral x + t\n else t\n (vs', ds', ps') = update (x - 1) t vs ds ps\n\nsolve :: [Int] -> [Int] -> [(Int64, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (v:vs) (_:ds) (p:ps) = snd p : solve vs' ds' ps'\n where\n (vs', ds', ps') = update v 0 vs ds ps\n\nmain :: IO ()\nmain = do\n n <- (fst . fromJust . BS8.readInt) <$> BS.getLine\n ls <- map (map (fst . fromJust . BS8.readInt) . BS8.words) <$> replicateM n BS.getLine\n let [vs, ds, ps] = transpose ls\n r = solve vs ds (zip (map fromIntegral ps) [1 ..])\n print $ length r\n putStrLn $ foldl' (\\c x -> c ++ show x ++ \" \") \"\" r\n"}], "negative_code": [{"source_code": "type VHall = Int\ntype VDoctor = Int\n\ndata Kid = Kid {\n position :: Int\n , vDoctor :: Int\n , vHall :: Int\n , confidence :: Int\n }\n deriving (Show)\n\nexit :: VHall -> [Kid] -> [Kid]\nexit _ [] = []\nexit v (kid:kids)\n | conf' >= 0 = kid {confidence = conf'} : exit v kids\n | otherwise = exit (v + vHall kid) kids\n where\n conf' = confidence kid - v\n\npropagate :: VDoctor -> [Kid] -> [Kid]\npropagate _ [] = []\npropagate 0 kids = kids\npropagate v (kid:kids) = kid {confidence = conf'} : propagate (v-1) kids\n where\n conf' = confidence kid - v\n\ntreat :: [Kid] -> [Int]\ntreat (kid:kids) = position kid:(treat . exit 0 . propagate (vDoctor kid)) kids\ntreat [] = []\n\ninput1 :: [Kid]\ninput1 = [Kid 1 4 2 2, Kid 2 4 1 2, Kid 3 5 2 4, Kid 4 3 3 5, Kid 5 5 1 2]\n\ninput2 :: [Kid]\ninput2 =\n [Kid 1 4 5 1\n ,Kid 2 5 3 9\n ,Kid 3 4 1 2\n ,Kid 4 2 1 8\n ,Kid 5 4 1 9]\n\nmain :: IO ()\nmain = do\n contents <- getContents\n putStr (readAndTreat contents)\n \nreadAndTreat :: String -> String\nreadAndTreat input =\n let (first:allLines) = lines input\n n = read first\n kids = readAll n 1 allLines\n treated = treat kids\n resultLines = [show $ length treated, unwords $ map show treated]\n result = unlines resultLines\n in result\n\nreadAll :: Int -> Int -> [String] -> [Kid]\nreadAll n i _ | i > n = [] \nreadAll _ i [] = error $ \"End of file reached but only \" ++ show i ++ \" lines read.\"\nreadAll n i (l:ls) = Kid i vD vH c : readAll n (i+1) ls\n where [vD,vH,c] = map read $ words l\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Monad (forM)\nimport Data.Maybe (catMaybes)\n\ndata Child = Child\n { i :: !Int\n , vi :: !Int\n , di :: !Int\n , pi :: !Int\n } deriving (Show)\n\ngo :: [Child] -> [Int]\ngo [] = []\ngo (c@Child {..} : cs) =\n let other = panic 0 $ screamHealing vi cs in\n i : go other\n where\n screamHealing :: Int -> [Child] -> [Child]\n screamHealing 0 ccs = ccs\n screamHealing _ [] = []\n screamHealing v (cc@(Child j vj dj pj) : ccs) =\n (Child j vj dj (pj - v)) : (screamHealing (v - 1) ccs)\n\n panic :: Int -> [Child] -> [Child]\n panic _ [] = []\n panic d (cc@(Child j vj dj pj) : ccs) =\n let pj' = pj - d in\n if pj' < 0 then\n panic (d + dj) ccs\n else\n (Child j vj dj pj') : panic d ccs\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine\n children <- forM [1..n] $ \\i -> do\n [v, d, p] <- (map read . words) `fmap` getLine\n return $ Child i v d p\n let ans = go children\n putStrLn $ show $ length ans\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Monad (replicateM)\n\ndata Child = Child\n { vi :: Int\n , di :: Int\n , pi :: Int\n } deriving (Show)\n\ngo :: Int -> [Child] -> [Int]\ngo i [] = []\ngo i (c@Child{..} : cs) =\n if pi < 0 then\n go (i + 1) $ map (\\(Child vj dj pj) -> Child vj dj (pj - di)) cs\n else\n let other = map (\\(delta, Child vj dj pj) -> Child vj dj (pj - (vi - delta))) $ zip [0..] cs\n in i : (go (i + 1) other)\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine\n children <- replicateM n $ do\n [v, d, p] <- (map read . words) `fmap` getLine\n return $ Child v d p\n let ans = go 1 children\n putStrLn $ show $ length ans\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Monad (replicateM)\n\ndata Child = Child\n { vi :: Int\n , di :: Int\n , pi :: Int\n } deriving (Show)\n\ngo :: Int -> [Child] -> [Int]\ngo i [] = []\ngo i (c@Child{..} : cs) =\n if pi < 0 then\n go (i + 1) $ map (\\(Child vj dj pj) -> Child vj dj (pj - di)) cs\n else\n let other =\n map (\\(delta, Child vj dj pj) -> Child vj dj (pj - max 0 (vi - delta)))\n $ zip [0..] cs\n in i : (go (i + 1) other)\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine\n children <- replicateM n $ do\n [v, d, p] <- (map read . words) `fmap` getLine\n return $ Child v d p\n let ans = go 1 children\n putStrLn $ show $ length ans\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.Functor ((<$>))\nimport Data.List (foldl', transpose)\n\nupdate :: Int\n -> Int\n -> [Int]\n -> [Int]\n -> [(Int, Int)]\n -> ([Int], [Int], [(Int, Int)])\nupdate _ _ [] _ _ = ([], [], [])\nupdate x t (v:vs) (d:ds) (p:ps)\n | fst p - val < 0 = update (x - 1) (t + d) vs ds ps\n | otherwise = (v : vs', d : ds', (fst p - val, snd p) : ps')\n where\n val = if x > 0 then x + t else t\n (vs', ds', ps') = update (x - 1) t vs ds ps\n\nsolve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (v:vs) (_:ds) (p:ps) = snd p : solve vs' ds' ps'\n where\n (vs', ds', ps') = update v 0 vs ds ps\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ls <- map (map read . words) <$> replicateM n getLine\n let [vs, ds, ps] = transpose ls :: [[Int]]\n r = solve vs ds (zip ps [1 ..])\n print $ length r\n putStrLn $ foldl' (\\c x -> c ++ show x ++ \" \") \"\" r\n"}, {"source_code": "import Control.Monad\nimport Data.Functor ((<$>))\nimport Data.List\n\nupdate :: Int\n -> Int\n -> [Int]\n -> [Int]\n -> [(Int, Int)]\n -> ([Int], [Int], [(Int, Int)])\nupdate 0 _ _ _ _ = ([], [], [])\nupdate _ _ [] _ _ = ([], [], [])\nupdate x t (v:vs) (d:ds) (p:ps)\n | fst p - (x + t) < 0 = update (x - 1) (t + d) vs ds ps\n | otherwise = (v : vs', d : ds', p : ps')\n where\n (vs', ds', ps') = update (x - 1) t vs ds ps\n\nsolve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (v:vs) (_:ds) (p:ps) = snd p : solve vs' ds' ps'\n where\n (vs', ds', ps') = update v 0 vs ds ps\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ls <- map (map read . words) <$> replicateM n getLine\n let [vs, ds, ps] = transpose ls :: [[Int]]\n r = solve vs ds (zip ps [1 ..])\n print $ length r\n putStrLn $ foldl' (\\c x -> c ++ show x ++ \" \") \"\" r\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.Functor ((<$>))\nimport Data.List (foldl', transpose)\n\nupdate :: Int\n -> Int\n -> [Int]\n -> [Int]\n -> [(Int, Int)]\n -> ([Int], [Int], [(Int, Int)])\nupdate _ _ [] _ _ = ([], [], [])\nupdate x t (v:vs) (d:ds) (p:ps)\n | fst p - val < 0 = update (x - 1) (t + d) vs ds ps\n | otherwise = (v : vs', d : ds', (fst p - x, snd p) : ps')\n where\n val = if x > 0 then x + t else t\n (vs', ds', ps') = update (x - 1) t vs ds ps\n\nsolve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (v:vs) (_:ds) (p:ps) = snd p : solve vs' ds' ps'\n where\n (vs', ds', ps') = update v 0 vs ds ps\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ls <- map (map read . words) <$> replicateM n getLine\n let [vs, ds, ps] = transpose ls :: [[Int]]\n r = solve vs ds (zip ps [1 ..])\n print $ length r\n putStrLn $ foldl' (\\c x -> c ++ show x ++ \" \") \"\" r\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.Functor ((<$>))\nimport Data.List (foldl', transpose)\n\nupdate :: Int\n -> Int\n -> [Int]\n -> [Int]\n -> [(Int, Int)]\n -> ([Int], [Int], [(Int, Int)])\nupdate 0 _ _ _ _ = ([], [], [])\nupdate _ _ [] _ _ = ([], [], [])\nupdate x t (v:vs) (d:ds) (p:ps)\n | fst p - (x + t) < 0 = update (x - 1) (t + d) vs ds ps\n | otherwise = (v : vs', d : ds', (fst p - x, snd p) : ps')\n where\n (vs', ds', ps') = update (x - 1) t vs ds ps\n\nsolve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]\nsolve [] _ _ = []\nsolve (v:vs) (_:ds) (p:ps) = snd p : solve vs' ds' ps'\n where\n (vs', ds', ps') = update v 0 vs ds ps\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ls <- map (map read . words) <$> replicateM n getLine\n let [vs, ds, ps] = transpose ls :: [[Int]]\n r = solve vs ds (zip ps [1 ..])\n print $ length r\n putStrLn $ foldl' (\\c x -> c ++ show x ++ \" \") \"\" r\n"}], "src_uid": "8cf8590d1f3668b768702c7eb0ee8249"} {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n--\tline <- getLine\n\tgetLine >>= print . sum . map ((\\x -> x*x). toInteger . length) . group . sort \n", "positive_code": [{"source_code": "import Data.List;\nmain = do getLine >>= putStr . show . sum . map ((^2) . toInteger . length) . group . sort\n"}, {"source_code": "import List\nmain = interact(show.sum.map ((^2).toInteger.length).group.sort.head.lines)\n"}, {"source_code": "import Data.List\nmain = interact (show.sum.map s.map length.group.sort.head.lines)\ns :: Int -> Integer\ns x = (fromIntegral x)^2\n"}, {"source_code": "\nimport Data.Map (elems, empty, insertWith')\n\nsolve :: String -> Integer\nsolve s = sum $ map (^2) $ map fromIntegral $ elems map'\n where\n map' = foldl (\\map'' c -> insertWith' (+) c 1 map'') empty s\n\nmain :: IO ()\nmain = getLine >>= print . solve\n"}, {"source_code": "import List\n\nmain = getLine >>= print.solve\n\nsolve :: String -> Integer\nsolve = sum.map ((^2).genericLength).group.sort\n"}, {"source_code": "import qualified Data.Map as Map\nimport qualified Data.List as List\nimport Data.Char\n\nsolve ss = \n List.foldl' (\\ans (_, a) -> ans + a * (a - 1) + a) 0 $ Map.toList $ List.foldl' f (Map.empty) $ filter (not.isSpace) ss\n where f m x = Map.insertWith (+) x 1 m\n\nmain = interact (show.solve)"}, {"source_code": "\nimport List\n\n\nmain :: IO ()\nmain = do\n string <- getLine\n print (sum (map (\\x -> (toInteger (length x)) ^ 2) (group (sort string))))"}, {"source_code": "\nimport Data.Array\nimport Data.Char\nimport Data.List\n\n-- import Debug.Trace\n\n-- debug = flip trace\n\ndebug = const\n\nfact :: Integer -> Integer\nfact 0 = 1\nfact n = let prev = fact (n-1) \n in prev `seq` n * prev\n\n\nproduct' = foldl' (*) 1\n\nperm n k = \n product' [n-k+1 .. n]\n\naccStr arr (c:cs) =\n let val = arr ! (ind c)\n in arr `seq` val `seq` accStr (arr // [ (ind c, val + 1) ]) cs\naccStr arr [] = arr\n\nempArr = listArray (ind 'a', ind '9') (repeat 0)\n\nind c \n | c `elem` ['a'..'z'] = ord c - ord 'a'\n | c `elem` ['0'..'9'] = ord c - ord '0' + ord 'z' - ord 'a' + 1\n\nsolve str = \n let arr = elems $ accStr empArr str\n cnt n | n >= 2 = perm n 2 + n\n | otherwise = n\n perms = map cnt arr\n sum' = foldl1' (+)\n in sum' perms `debug` (show arr)\n\nmain = do\n str <- getLine\n print $ solve str"}, {"source_code": "import Data.Map (Map)\nimport qualified Data.Map as Map\nmain = interact solve\nsolve input = show $ sum $ map (^2) $ map snd $ Map.toList $ count input\ncount [] = Map.fromList $ zip (['0'..'9']++['a'..'z']) [0,0..]\ncount (x:xs) = Map.adjust (+1) x (count xs)\n"}, {"source_code": "import qualified Data.Map as Map\n\nmain :: IO()\nmain = do\n\tline <- getLine\n\tlet\tx = foldl (\\acc x -> add x acc) [] line\n\t\ty = foldl (\\acc (a, b) -> acc + (b*b)) 0 x\n\tprint $ y\n\nadd :: Char -> [(Char, Integer)] -> [(Char, Integer)]\nadd ch [] = [(ch, 1)]\nadd ch ( (a, b) : xs ) \n | a == ch = (a, b+1) : xs\n | otherwise = (a, b) : add ch xs\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nsolve = sum . map count . L.group . L.sort . filter (/= '\\n')\n where count x= let n = toInteger $ length x in n * (n - 1) + n\n\nmain = interact $ show . solve\n"}, {"source_code": "type Mapa = [(Char, Integer)]\n\nkapPoKap :: String -> String\nkapPoKap = show . foldr (\\x acc -> acc + x * x) 0 . mrmPoMrm\n\ndodaj :: Char -> Mapa -> Mapa\ndodaj c xs\n | c == '\\n' = xs\n | notElem c $ fst $ unzip xs = (c, 1) : xs\n | otherwise = map (\\(x, b) -> if x == c then (x, b + 1) else (x, b)) xs\n\nmrmPoMrm :: String -> [Integer]\nmrmPoMrm = snd . unzip . foldr dodaj []\n\nmain = interact $ kapPoKap"}], "negative_code": [{"source_code": "type Mapa = [(Char, Int)]\n\nkapPoKap :: String -> String\nkapPoKap = show . foldr (\\x acc -> acc + x * x) 0 . mrmPoMrm\n\ndodaj :: Char -> Mapa -> Mapa\ndodaj c xs\n | c == '\\n' = xs\n | notElem c $ fst $ unzip xs = (c, 1) : xs\n | otherwise = map (\\(x, b) -> if x == c then (x, b + 1) else (x, b)) xs\n\nmrmPoMrm :: String -> [Int]\nmrmPoMrm = snd . unzip . foldr dodaj []\n\nmain = interact $ kapPoKap"}, {"source_code": "kapPoKap :: String -> String\nkapPoKap xs = show . length $ filter (\\(x, y) -> x == y) [(x, y)|x <- xs, y <- xs]\n\nmain = interact $ kapPoKap"}, {"source_code": "\nimport Data.Map (elems, empty, insertWith')\n\nsolve :: String -> Int\nsolve s = sum $ map (^2) $ elems map'\n where\n map' = foldl (\\map'' c -> insertWith' (+) c 1 map'') empty s\n\nmain :: IO ()\nmain = getLine >>= print . solve\n"}, {"source_code": "import qualified Data.Map as Map\n\nmain :: IO()\nmain = do\n\tline <- getLine\n\tlet\tx = foldl (\\acc x -> add x acc) [] line\n\t\ty = foldl (\\acc (a, b) -> max acc b) 0 x\n\tprint $ fromIntegral(y)*fromIntegral(y)\n\nadd :: Char -> [(Char, Int)] -> [(Char, Int)]\nadd ch [] = [(ch, 1)]\nadd ch ( (a, b) : xs ) \n | a == ch = (a, b+1) : xs\n | otherwise = (a, b) : add ch xs\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nsolve = sum . map count . L.group . L.sort . filter (/= '\\n')\n where count x= let n = length x in n * (n - 1) + n\n\nmain = interact $ show . solve\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nsolve = sum . map count . L.group . L.sort\n where count x= let n = length x in n * (n - 1) + n\n\nmain = interact $ show . solve\n"}, {"source_code": "import Data.List;\nmain = do getLine >>= putStr . show . sum . map ((^2) . length) . group . sort\n"}, {"source_code": "import List\n\nmain = getLine >>= print.solve\n\nsolve = sum.map ((^2).length).group.sort\n"}, {"source_code": "\nimport List\n\n\nmain :: IO ()\nmain = do\n string <- getLine\n print (sum (map (\\x -> (length x) ^ 2) (group (sort string))))"}], "src_uid": "6bb2793e275426eb076972fab69d0eba"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n ri\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve [a,b,c] = ans\r\n where\r\n t1 = abs (a-1)\r\n t2 = abs (b-c) + abs (c-1)\r\n ans | t1 < t2 = 1 :: Int\r\n | t1 > t2 = 2\r\n | otherwise = 3\r\nsolve _ = error \"Triple expected.\"\r\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int -> Int -> Int\nsolve a b c = choice\n where \n distanceA = abs $ a - 1\n distanceB = abs (b - c) + abs (c - 1)\n\n choice = case compare distanceA distanceB of\n LT -> 1\n GT -> 2\n EQ -> 3\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [a, b, c] <- B8.getLine <&> readIntB8s\n let answer = solve a b c \n printf \"%d\\n\" answer\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[a, b, c] -> print (choice a b c)\n\nchoice :: Int -> Int -> Int -> Int\nchoice a b c = case compare (a-1) ((abs (b-c)) + c - 1) of\n EQ -> 3\n LT -> 1\n GT -> 2\n"}, {"source_code": "import Data.Function\r\nimport Control.Monad\r\n\r\nstringToInt :: String -> Int\r\nstringToInt = read\r\n\r\nreadInt :: IO Int\r\nreadInt = readNumbers >>= (return . head)\r\n\r\nreadNumbers :: IO [Int]\r\nreadNumbers = getLine >>= (return . map stringToInt . words)\r\n\r\nsolve a b c = let second = (c + (abs (b - c)))\r\n in if a < second then 1 else if a > second then 2 else 3\r\n\r\nmain = readInt >>= (\\t ->\r\n forM [1..t] (\\_ -> do\r\n numbers <- readNumbers\r\n let [a, b, c] = numbers\r\n putStrLn $ show (solve a b c)))\r\n"}], "negative_code": [{"source_code": "import Data.Function\r\nimport Control.Monad\r\n\r\nstringToInt :: String -> Int\r\nstringToInt = read\r\n\r\nreadInt :: IO Int\r\nreadInt = readNumbers >>= (return . head)\r\n\r\nreadNumbers :: IO [Int]\r\nreadNumbers = getLine >>= (return . map stringToInt . words)\r\n\r\nsolve a b c = min a (c + (abs (b - c)))\r\n\r\nmain = readInt >>= (\\t ->\r\n forM [1..t] (\\_ -> do\r\n numbers <- readNumbers\r\n let [a, b, c] = numbers\r\n putStrLn $ show (solve a b c)))\r\n"}], "src_uid": "aca2346553f9e7b6e944ca2c74bb0b3d"} {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\n-- this one discards separators and combines multiple adjacent separators\n-- splitOn (==',') \"foo,bar,,,baz\" = [\"foo\", \"bar\", \"baz\"]\n-- this is the behavior you want for List.words\nsplitOn :: (a -> Bool) -> [a] -> [[a]]\nsplitOn _ [] = []\nsplitOn f l@(x:xs)\n | f x = splitOn f xs\n | otherwise = let (h,t) = break f l in h:(splitOn f t)\n\nremoveCd ('c':'d':' ':xs) = xs\n\nsplit ('/':xs) = [] : split xs\nsplit xs = splitOn (=='/') xs\n \nmain = do s <- hGetContents stdin\n putStr $ unlines $ reverse $ solve $ drop 1 $ lines s\n \nprocess :: [String] -> [String] -> [String] -> [String] \nprocess _ [] result = result\nprocess state (\"pwd\":input) result = process state input ((concat $ map (++ \"/\") $ reverse state) : result)\nprocess state (x:input) result = process (nextState state $ split $ removeCd x) input result\n \nnextState :: [String] -> [String] -> [String]\nnextState state [] = state\nnextState state ([]:xs) = nextState [\"\"] xs\nnextState state (\"..\":xs) = nextState (tail state) xs\nnextState state (x:xs) = nextState (x:state) xs\n \nsolve :: [String] ->[String]\nsolve xs = process [\"\"] xs []", "positive_code": [{"source_code": "import Data.Char\nimport Control.Monad\n\naddDir curDir subDir\n | subDir == \"..\" = init curDir\n | otherwise = curDir ++ [subDir]\n\nupdateDirectory curDir content \n | head content == '/' = updateDirectory [\"\"] (tail content)\n | otherwise = let (pre, suf) = break (== '/') content\n in if (suf == \"\") || (suf == \"/\")\n then addDir curDir pre\n else updateDirectory (addDir curDir pre) (tail suf)\n \n\nloop 0 _ = return ()\nloop n curDir = do \n inStr <- getLine\n let (command, contentWithspace) = break (== ' ') inStr\n content = dropWhile (== ' ') contentWithspace\n putStr $ case command of \n \"pwd\" -> concat (zipWith (++) curDir (replicate (length curDir) \"/\")) ++ \"\\n\" \n _ -> \"\"\n loop (n - 1) $ case command of \n \"pwd\" -> curDir\n \"cd\" -> updateDirectory curDir content\n\nmain = do\n n <- readLn\n loop n [\"\"]"}, {"source_code": "main = do\n getLine\n cmds <- fmap lines getContents\n mapM_ putStrLn $ solve cmds\n\nsolve cmds = solve' cmds [\"\"]\n where\n solve' [] cur = []\n solve' (cmd:cmds) cur =\n case words cmd of\n [\"pwd\"] -> dirToPath cur:solve' cmds cur\n [\"cd\", path] -> solve' cmds $ foldl (\\cur to -> if to == \"..\" then tail cur else to:cur) (if (head path) == '/' then [\"\"] else cur) $ splitPath path\n dirToPath = foldr1 (flip (++)) . map (++ \"/\")\n\nsplitPath \"\" = []\nsplitPath ('/':s) = splitPath s\nsplitPath s = let (s1, s2) = break (=='/') s\n in s1:splitPath s2\n"}, {"source_code": "-- cd & pwd\n\nlexx s = lex' s []\nlex' [] a = (reverse a,[])\nlex' ('/':xs) a = (reverse a,xs)\nlex' (x:xs) a = lex' xs (x:a)\n\ndivS [] = []\ndivS s = x:(divS xs) where (x,xs) = lexx s\n\naddFolder d [] = d\naddFolder d (\"..\":xs) = addFolder (reverse (tail (reverse d))) xs\naddFolder d (dd:xs) = addFolder (d ++ [dd]) xs\n\napply :: [String] -> (String,String) -> IO [String]\napply d (\"pwd\",_) = mapM_ (\\x -> putStr (x ++ \"/\")) d >> putChar '\\n' >> return d\napply d (\"cd\",nd) = if (f == \"/\") then return $ addFolder [\"\"] (divS fs)\n else return $ addFolder d (divS (f ++ fs))\n\twhere [(f,fs)] = lex nd\n\nloop :: [String] -> Int -> IO()\nloop a 0 = return()\nloop d n = getLine >>= parse >>= apply d >>= (\\x -> loop x (n-1))\n\twhere parse = return.head.lex\n\nmain = readLn >>= loop [\"\"]\n"}, {"source_code": "import Data.List (intercalate, reverse)\n\nmain = interact $ unlines . solve . lines\n\nsolve (nt:st) = solve' ss [] [] where\n ss = take (read nt) st\n\n wordsWhen :: (Char -> Bool) -> String -> [String]\n wordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s'' where \n (w, s'') = break p s'\n \n solve' [] _ acc = reverse acc\n solve' (\"pwd\":ss) path acc = solve' ss path (buildpath path:acc)\n solve' (cmd:ss) path acc = solve' ss (addpath dir path) acc where [_, dir] = words cmd\n \n addpath ('/':ls) _ = addpath' ws [] where ws = wordsWhen (=='/') ls\n addpath ls path = addpath' ws path where ws = wordsWhen (=='/') ls\n addpath' [] path = path\n addpath' (\"..\":ds) path = addpath' ds (tail path)\n addpath' (d:ds) path = addpath' ds (d:path)\n \n buildpath [] = \"/\"\n buildpath path = '/':(intercalate \"/\" (reverse path)) ++ \"/\"\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> solve =<< (forM [1..read n] $ \\ i ->C.getLine>>= \\js -> return $ tail $ C.words js )\nsolve::[[C.ByteString]]->IO ()\nsolve xs = foldM_ (\\b a ->if a == [] then C.putStrLn (b) >> return b else return (f b $ head a)) (C.singleton '/') xs\n where\n f z2 z1 = if C.head z1 == '/' then unwords2 ( foldl ff [] $ words2 z1 ++ [C.pack \"\"]) else unwords2 ( foldl ff [] $ init (words2 z2) ++ words2 z1 ++ [C.pack \"\"])\n where\n ff=(\\b a -> if a == C.pack \"..\" then init b else b++[a])\nwords2 = C.splitWith (=='/')\nunwords2 = C.intercalate (C.singleton '/')"}, {"source_code": "\ncompresse :: String -> String\ncompresse line = reverse (compresse' (reverse line))\n where\n compresse' \"\" = \"\"\n compresse' ('.':'.':'/':s) = compresse'' 1 s\n compresse' (c:s) = c : compresse' s\n compresse'' 0 s = compresse' s\n compresse'' n ('.':'.':'/':s) = compresse'' (n+1) s\n compresse'' n ('/':s) = compresse'' (n-1) s\n compresse'' n (c:s) = compresse'' n s \n\ninteractive :: Int -> String -> IO ()\ninteractive 0 _ = return ()\ninteractive n pass = do\n command <- getLine\n case head command of\n 'c' -> do\n let newPass = drop 3 command\n let newPass' = if (head newPass) == '/'\n then (newPass ++ \"/\")\n else (pass ++ newPass ++ \"/\")\n-- putStrLn $ \"[\" ++ newPass' ++ \"]\"\n interactive (n-1) (compresse newPass')\n 'p' -> do\n putStrLn pass\n interactive (n-1) pass\n \n\nmain :: IO ()\nmain = do\n n <- readLn\n interactive n \"/\""}, {"source_code": "-- Codeforces 158C.hs\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n solve n\n\nsolve :: Int -> IO ()\nsolve n = foldM_ (\\d _ -> command d) [] [1..n] where\n \n changepath :: [String] -> [String] -> [String]\n changepath base [] = base\n changepath base (\"..\":xs) = changepath (init base) xs\n changepath base (x:xs) = changepath (base++[x]) xs\n\n splitAll :: Char -> String -> [String]\n splitAll c [] = []\n splitAll c s = [takeWhile (/= c) s] ++ (splitAll c $ if null k then [] else tail k ) where k = dropWhile (/= c) s\n\n command current = do\n input <- getLine\n case (words input) of\n [\"cd\", path] -> return $ cd path where\n cd ('/':xs) = changepath [] (filter (not . null) (splitAll '/' xs))\n cd xs = changepath current (filter (not . null) (splitAll '/' xs))\n [\"pwd\"] -> do\n putStrLn $ intercalate \"/\" (\"\":current) ++ \"/\"\n return current\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Lazy.Char8 (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n $ do\n s <- readString\n if s == \"pwd\" then return PWD else CD <$> readString\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\ndata Command = PWD\n | CD ByteString\n \nsolve cmds = BS.concat (evalState (mapM emu cmds) [\"\"])\n\nemu :: Command -> State [ByteString] ByteString\nemu PWD = do\n seps <- get\n return $ BS.intercalate \"/\" (seps ++ [\"\"]) `BS.snoc` '\\n'\n\nemu (CD \"/\") = put [\"\"] >> return \"\"\nemu (CD path)\n | BS.null (head seps) = put [\"\"] >> go (tail seps)\n | otherwise = go seps\n where\n path' | BS.last path == '/' = BS.init path\n | otherwise = path\n seps = BS.split '/' path'\n \n go [] = return \"\"\n go [\"\"] = return \"\"\n go (x:xs) | x == \"..\" = modify init >> go xs\n go (x:xs) = modify (++[x]) >> go xs\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "cd1 :: String -> [String] -> [String]\ncd1 \"..\" xs = tail xs\ncd1 x xs = x : xs\n\n\ncd :: String -> [String] -> [String]\ncd ('/':s) _ = cd s []\ncd s xs = foldl (flip cd1) xs $ split '/' s\n\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit x xs = case break (== x) xs of\n (a, []) -> [a]\n (a, b) -> a : split x (tail b)\n\n\npwd :: [String] -> String\npwd = foldr (\\x a -> a ++ x ++ \"/\") \"/\"\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n cmd <- sequence $ replicate n getLine\n putStr $ unlines (exec cmd [])\n\n\nexec :: [String] -> [String] -> [String]\nexec [] currentDir = []\nexec (\"pwd\":xs) currentDir = pwd currentDir : exec xs currentDir\nexec (x:xs) currentDir = case words x of\n [\"cd\", args] -> exec xs $ cd args currentDir\n _ -> error \"format error\""}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve [] . tail . lines\n\nsolve :: [String] -> [String] -> [String]\nsolve path (c:cs) | c == \"pwd\" = (concatMap ('/':) path ++ \"/\") : solve path cs\n | \"cd \" `isPrefixOf` c = solve (cd (splitOn '/' (dropWhile (==' ') (drop 3 c))) path) cs\n | otherwise = solve path cs\n where cd (\"..\":ds) ps = cd ds (init ps)\n cd (\"\":ds) _ = cd ds []\n cd (d:ds) ps = cd ds (ps ++ [d])\n cd [] ps = ps\nsolve _ _ = []\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn c xxs@(x:xs)\n | x == c = [] : splitOn c xs\n | otherwise = takeWhile (/=c) xxs : splitOn c (dropOne (==c) $ dropWhile (/=c) xxs)\n where dropOne f yys@(y:ys) | f y = ys | otherwise = yys\n dropOne _ [] = []\nsplitOn _ [] = []\n"}, {"source_code": "import Data.List (intercalate)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- getContents\n let commands = take n $ lines input\n sequence $ execute [] $ map muhParse commands\n\nmuhParse :: String -> Maybe (Int,[String])\nmuhParse s = case words s of\n\t\t(_:[]) -> Nothing\n\t\t(_:('/':y):[]) -> Just $ (1, wordsBy (=='/') y)\n\t\t(_:y:[]) -> Just $ (0, wordsBy (=='/') y)\n\t\t_ -> error \"faulty input?\"\n\nwordsBy :: (Char -> Bool) -> String -> [String]\nwordsBy p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsBy p s''\n where (w, s'') = break p s'\n\nnewPath :: [String] -> [String] -> [String]\nnewPath pos [] = pos\nnewPath pos (p:path) = case p of\n\t\t\t\"..\" -> newPath (init pos) path\n\t\t\tdir -> newPath (pos ++ [dir]) path\n\npathToString :: [String] -> String\npathToString [] = \"/\"\npathToString path = \"/\" ++ intercalate \"/\" path ++ \"/\"\n\nexecute :: [String] -> [Maybe (Int,[String])] -> [IO ()]\nexecute path [] = []\nexecute path (c:cs) = case c of\n\t\t\tNothing -> [putStrLn $ pathToString path] ++ execute path cs\n\t\t\tJust (0,lst) -> execute (newPath path lst) cs\n\t\t\tJust (1,lst) -> execute (newPath [] lst) cs"}, {"source_code": "import Data.IORef\nimport Data.List\nimport Control.Monad\n\nsplit str = case elemIndex '/' str of\n Nothing -> [str]\n Just x -> case splitAt x str of (s, str') -> s : split (tail str')\n\nsplit' = filter (/= \"\") . split\n\nprocess svar cd = forM_ (split' cd) $ \\dir -> do\n if dir == \"..\" then modifyIORef svar tail\n else modifyIORef svar (dir:)\nmain = do\n n <- liftM read getLine\n\n svar <- newIORef []\n replicateM_ n $ do\n pwd <- readIORef svar\n cmd <- liftM words getLine\n let showpwd = intercalate \"/\" ([\"\"] ++ reverse pwd ++ [\"\"])\n\n case cmd of\n [\"pwd\"] -> putStrLn showpwd\n [\"cd\", '/':cd] -> writeIORef svar [] >> process svar cd\n [\"cd\", cd] -> process svar cd\n"}, {"source_code": "import Data.List (intersperse)\n\nimport System.IO\n\nmain = do\n n <- fmap read getLine\n interpret n [] []\n\nsplit curr \"\" = curr\nsplit curr ( '/':ts) = split curr ts\nsplit curr ('.':'.':ts) = split (tail curr) ts\nsplit curr s = let (h,ts) = break (=='/') s in split (h:curr) ts\n\npath [] = \"/\"\npath xs = '/':(concat $ reverse $ \"/\":(intersperse \"/\" xs))\n\ninterpret 0 _ output = mapM_ putStrLn $ reverse output\ninterpret n curr output = do\n (command:arg) <- fmap words getLine\n case command of\n \"pwd\" -> interpret (n-1) curr $ (path curr):output\n \"cd\" -> let [path@(first:_)] = arg in\n if first == '/'\n then interpret (n-1) (split [] path) output\n else interpret (n-1) (split curr path) output\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\ndata Path = Relative [String] | Absolute [String]\n\ninstance Show Path where\n show (Absolute []) = \"/\"\n show (Relative path) = intercalate \"/\" (normalized path) ++ \"/\"\n show (Absolute path) = '/' : intercalate \"/\" (normalized path) ++ \"/\"\n\ninstance Read Path where\n readsPrec _ s = if head s == '/' then [(Absolute (parse $ tail s), \"\")]\n else [(Relative (parse s), \"\")] where\n parse = split \"/\"\n split seps = words . map (\\x -> if elem x seps then ' ' else x)\n\ncd :: Path -> Path -> Path\ncd _ p@(Absolute _) = p\ncd (Absolute basis) (Relative modifier) = Absolute (reverse $ apply (reverse basis) modifier)\n\napply :: [String] -> [String] -> [String]\napply basis [] = basis\napply (_ : basis) (\"..\" : modifier) = apply basis modifier\napply basis (directory : modifier) = apply (directory : basis) modifier\n\nnormalized :: [String] -> [String]\nnormalized = normalized' [] where\n normalized' result [] = reverse result\n normalized' result (node : \"..\" : path) = normalized' result path\n normalized' result (node : path) = normalized' (node : result) path\n\n\nmain = interact (unlines . solve (read \"/\") . map words . tail . lines)\n\nsolve :: Path -> [[String]] -> [String]\nsolve _ [] = return []\nsolve currentDir (cmd : commands) = case head cmd of\n \"pwd\" -> show currentDir : solve currentDir commands\n \"cd\" -> solve (cd currentDir (read $ cmd !! 1)) commands\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\ndata Path = Relative [String] | Absolute [String]\n\ninstance Show Path where\n show (Relative path) = intercalate \"/\" (normalized path)\n show (Absolute path) = '/' : intercalate \"/\" (normalized path)\n\ninstance Read Path where\n readsPrec _ s = if head s == '/' then [(Absolute (parse $ tail s), \"\")]\n else [(Relative (parse s), \"\")] where\n parse = split \"/\"\n split seps = words . map (\\x -> if elem x seps then ' ' else x)\n\ncd :: Path -> Path -> Path\ncd _ p@(Absolute _) = p\ncd (Absolute basis) (Relative modifier) = Absolute (reverse $ apply (reverse basis) modifier)\n\napply :: [String] -> [String] -> [String]\napply basis [] = basis\napply (_ : basis) (\"..\" : modifier) = apply basis modifier\napply basis (directory : modifier) = apply (directory : basis) modifier\n\nnormalized :: [String] -> [String]\nnormalized = normalized' [] where\n normalized' result [] = reverse result\n normalized' result (node : \"..\" : path) = normalized' result path\n normalized' result (node : path) = normalized' (node : result) path\n\n\nmain = interact (unlines . solve (read \"/\") . map words . tail . lines)\n\nsolve :: Path -> [[String]] -> [String]\nsolve _ [] = return []\nsolve currentDir (cmd : commands) = case head cmd of\n \"pwd\" -> show currentDir : solve currentDir commands\n \"cd\" -> solve (cd currentDir (read $ cmd !! 1)) commands\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\ndata Path = Relative [String] | Absolute [String]\n\ninstance Show Path where\n show (Relative path) = intercalate \"/\" (normalized path) ++ \"/\"\n show (Absolute path) = '/' : intercalate \"/\" (normalized path) ++ \"/\"\n\ninstance Read Path where\n readsPrec _ s = if head s == '/' then [(Absolute (parse $ tail s), \"\")]\n else [(Relative (parse s), \"\")] where\n parse = split \"/\"\n split seps = words . map (\\x -> if elem x seps then ' ' else x)\n\ncd :: Path -> Path -> Path\ncd _ p@(Absolute _) = p\ncd (Absolute basis) (Relative modifier) = Absolute (reverse $ apply (reverse basis) modifier)\n\napply :: [String] -> [String] -> [String]\napply basis [] = basis\napply (_ : basis) (\"..\" : modifier) = apply basis modifier\napply basis (directory : modifier) = apply (directory : basis) modifier\n\nnormalized :: [String] -> [String]\nnormalized = normalized' [] where\n normalized' result [] = reverse result\n normalized' result (node : \"..\" : path) = normalized' result path\n normalized' result (node : path) = normalized' (node : result) path\n\n\nmain = interact (unlines . solve (read \"/\") . map words . tail . lines)\n\nsolve :: Path -> [[String]] -> [String]\nsolve _ [] = return []\nsolve currentDir (cmd : commands) = case head cmd of\n \"pwd\" -> show currentDir : solve currentDir commands\n \"cd\" -> solve (cd currentDir (read $ cmd !! 1)) commands\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> solve =<< (forM [1..read n] $ \\ i ->C.getLine>>= \\js -> return $ tail $ C.words js )\nsolve::[[C.ByteString]]->IO ()\nsolve xs = foldM_ (\\b a ->if a == [] then C.putStrLn (b) >> return b else return (f b $ head a)) (C.singleton '/') xs\n where\n f z2 z1 = if C.head z1 == '/' then C.append z1 $ C.singleton '/' else unwords2 ( foldl (\\b a -> if a == C.pack \"..\" then init b else b++[a]) [] $ init (words2 z2) ++ words2 z1 ++ [C.pack \"\"])\nwords2 = C.splitWith (=='/')\nunwords2 = C.intercalate (C.singleton '/')"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> solve =<< (forM [1..read n] $ \\ i ->C.getLine>>= \\js -> return $ tail $ C.words js )\nsolve::[[C.ByteString]]->IO ()\nsolve xs = foldM_ (\\b a ->if a == [] then C.putStrLn (b) >> return b else return (f b $ head a)) (C.singleton '/') xs\n where\n f z2 z1 = if C.head z1 == '/' then z1 else unwords2 ( foldl (\\b a -> if a == C.pack \"..\" then init b else b++[a]) [] $ words2 z2 ++ words2 z1)\nwords2 = C.splitWith (=='/')\nunwords2 = C.intercalate (C.singleton '/')"}, {"source_code": "-- Codeforces 158C.hs\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n solve n\n\nsolve :: Int -> IO ()\nsolve n = foldM_ (\\d _ -> command d) [] [1..n] where\n \n changepath :: [String] -> [String] -> [String]\n changepath base [] = base\n changepath base (\"..\":xs) = changepath (init base) xs\n changepath base (x:xs) = changepath (base++[x]) xs\n\n splitAll :: Char -> String -> [String]\n splitAll c [] = []\n splitAll c s = [takeWhile (/= c) s] ++ (splitAll c $ if null k then [] else tail k ) where k = dropWhile (/= c) s\n\n command current = do\n input <- getLine\n case (words input) of\n [\"cd\", path] -> return $ cd path where\n cd ('/':xs) = changepath [] (filter (not . null) (splitAll '/' xs))\n cd xs = changepath current (filter (not . null) (splitAll '/' xs))\n [\"pwd\"] -> do\n putStrLn $ (\"/\"++) $ intercalate \"/\" current\n return current\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Lazy.Char8 (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n $ do\n s <- readString\n if s == \"pwd\" then return PWD else CD <$> readString\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\ndata Command = PWD\n | CD ByteString\n \nsolve cmds = BS.concat (evalState (mapM emu cmds) [\"\"])\n\nemu :: Command -> State [ByteString] ByteString\nemu PWD = do\n seps <- get\n return $ BS.intercalate \"/\" (seps ++ [\"\"]) `BS.snoc` '\\n'\n\nemu (CD path)\n | BS.null (head seps) = put seps >> return \"\"\n | otherwise = go seps\n where\n seps = BS.split '/' path\n \n go [] = return \"\"\n go [\"\"] = return \"\"\n go (x:xs) | x == \"..\" = modify init >> go xs\n go (x:xs) = modify (++[x]) >> go xs\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Lazy.Char8 (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n $ do\n s <- readString\n if s == \"pwd\" then return PWD else CD <$> readString\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\ndata Command = PWD\n | CD ByteString\n \nsolve cmds = BS.concat (evalState (mapM emu cmds) [\"\"])\n\nemu :: Command -> State [ByteString] ByteString\nemu PWD = do\n seps <- get\n return $ BS.intercalate \"/\" (seps ++ [\"\"]) `BS.snoc` '\\n'\n\nemu (CD \"/\") = put [\"\"] >> return \"\"\nemu (CD path)\n | BS.null (head seps) = put seps >> return \"\"\n | otherwise = go seps\n where\n seps = BS.split '/' path\n \n go [] = return \"\"\n go [\"\"] = return \"\"\n go (x:xs) | x == \"..\" = modify init >> go xs\n go (x:xs) = modify (++[x]) >> go xs\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Data.List (intercalate)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- getContents\n let commands = take n $ lines input\n sequence $ execute [] $ map muhParse commands\n\nmuhParse :: String -> Maybe [String]\nmuhParse s = case words s of\n\t\t(_:[]) -> Nothing\n\t\t(_:y:[]) -> Just $ wordsBy (=='/') y\n\t\t_ -> error \"faulty input?\"\n\nwordsBy :: (Char -> Bool) -> String -> [String]\nwordsBy p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsBy p s''\n where (w, s'') = break p s'\n\nnewPath :: [String] -> [String] -> [String]\nnewPath pos [] = pos\nnewPath pos (p:path) = case p of\n\t\t\t\"..\" -> newPath (init pos) path\n\t\t\tdir -> newPath (pos ++ [dir]) path\n\npathToString :: [String] -> String\npathToString [] = \"/\"\npathToString path = \"/\" ++ intercalate \"/\" path ++ \"/\"\n\nexecute :: [String] -> [Maybe [String]] -> [IO ()]\nexecute path [] = []\nexecute path (c:cs) = case c of\n\t\t\tNothing -> [putStrLn $ pathToString path] ++ execute path cs\n\t\t\tJust lst -> execute (newPath path lst) cs"}, {"source_code": "import Data.List (intercalate)\n\nmain = do\n n <- fmap read getLine :: IO Int\n input <- getContents\n let commands = take n $ lines input\n sequence $ execute [] $ map muhParse commands\n\nmuhParse :: String -> Maybe [String]\nmuhParse s = case words s of\n\t\t(_:[]) -> Nothing\n\t\t(_:y:[]) -> Just $ wordsBy (=='/') y\n\t\t_ -> error \"faulty input?\"\n\nwordsBy :: (Char -> Bool) -> String -> [String]\nwordsBy p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsBy p s''\n where (w, s'') = break p s'\n\nnewPath :: [String] -> [String] -> [String]\nnewPath pos [] = pos\nnewPath pos (p:path) = case p of\n\t\t\t\"..\" -> newPath (init pos) path\n\t\t\tdir -> newPath (pos ++ [dir]) path\n\npathToString :: [String] -> String\npathToString [] = \"/\"\npathToString path = intercalate \"/\" path\n\nexecute :: [String] -> [Maybe [String]] -> [IO ()]\nexecute path [] = []\nexecute path (c:cs) = case c of\n\t\t\tNothing -> [putStrLn $ pathToString path] ++ execute path cs\n\t\t\tJust lst -> execute (newPath path lst) cs"}, {"source_code": "import Data.IORef\nimport Data.List\nimport Control.Monad\n\nsplit \"\" = []\nsplit str = case elemIndex '/' str of\n Nothing -> [str]\n Just x -> case splitAt x str of (s, str') -> s : split (tail str')\n\nsplit' = filter (/= \"\") . split\n\nmain = do\n n <- liftM read getLine\n\n svar <- newIORef []\n replicateM_ n $ do\n pwd <- readIORef svar\n cmd <- liftM words getLine\n let showpwd = intercalate \"/\" ([\"\"] ++ reverse pwd ++ [\"\"])\n\n case cmd of\n [\"pwd\"] -> putStrLn showpwd\n [\"cd\", '/':cd] -> writeIORef svar (reverse . split' $ cd)\n [\"cd\", cd] -> forM_ (split' cd) $ \\dir ->\n if dir == \"..\" then modifyIORef svar tail\n else modifyIORef svar (dir:)\n"}, {"source_code": "import Data.List (intersperse)\n\nimport System.IO\n\nmain = do\n n <- fmap read getLine\n interpret n [] []\n\nsplit curr \"\" = curr\nsplit curr ( '/':ts) = split curr ts\nsplit curr ('.':'.':ts) = split (tail curr) ts\nsplit curr s = let (h,ts) = break (=='/') s in split (h:curr) ts\n\nintersperse' s xs = s:(intersperse s xs) ++ [s]\n\ninterpret 0 _ output = mapM_ putStrLn $ reverse output\ninterpret n curr output = do\n (command:arg) <- fmap words getLine\n case command of\n \"pwd\" -> interpret (n-1) curr $ (concat $ intersperse' \"/\" $ reverse (curr)):output\n \"cd\" -> let [path@(first:_)] = arg in\n if first == '/'\n then interpret (n-1) (split [] path) output\n else interpret (n-1) (split curr path) output\n"}, {"source_code": "import Data.List (intersperse)\n\nimport System.IO\n\nmain = do\n n <- fmap read getLine\n interpret n []\n\nsplit curr \"\" = curr\nsplit curr ( '/':ts) = split curr ts\nsplit curr ('.':'.':ts) = split (tail curr) ts\nsplit curr s = let (h,ts) = break (=='/') s in split (h:curr) ts\n\ninterpret 0 _ = return ()\ninterpret n curr = do\n (command:arg) <- fmap words getLine\n case command of\n \"pwd\" -> (putStrLn $ concat $ \"/\":(intersperse \"/\" $ reverse (curr))) >> interpret (n-1) curr\n \"cd\" -> let [path@(first:_)] = arg in\n if first == '/'\n then interpret (n-1) $ split [] path\n else interpret (n-1) $ split curr path\n"}, {"source_code": "import Data.List (intersperse)\n\nimport System.IO\n\nmain = do\n n <- fmap read getLine\n interpret n [] []\n\nsplit curr \"\" = curr\nsplit curr ( '/':ts) = split curr ts\nsplit curr ('.':'.':ts) = split (tail curr) ts\nsplit curr s = let (h,ts) = break (=='/') s in split (h:curr) ts\n\ninterpret 0 _ output = mapM_ putStrLn $ reverse output\ninterpret n curr output = do\n (command:arg) <- fmap words getLine\n case command of\n \"pwd\" -> interpret (n-1) curr $ (concat $ \"/\":(intersperse \"/\" $ reverse (curr))):output\n \"cd\" -> let [path@(first:_)] = arg in\n if first == '/'\n then interpret (n-1) (split [] path) output\n else interpret (n-1) (split curr path) output\n"}], "src_uid": "494ac937ba939db1dbc4081e518ab54c"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\n-- main = C.interact $ runScanner input >>> solve >>> output\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = bstr >> str\n\n-- output :: Output -> C.ByteString\noutput Nothing = C.pack \"-1 -1\"\noutput (Just (l, r)) = C.pack $ show l ++ \" \" ++ show r\n\n-- solve :: Input -> Output\nsolve s = case filter snd . zip [1 ..] . adjacentsWith (/=) $ s of\n [] -> Nothing\n ((i, _) : _) -> Just (i, i + 1)\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Text.Printf\n\nsolution :: Text -> Maybe (Int, Int)\nsolution str = listToMaybe $ do\n x <- [1 .. T.length str - 1]\n guard $ isSolution $ getPair x\n return (x, x + 1)\n where\n getPair :: Int -> Text\n getPair x = T.take 2 $ T.drop (x - 1) str\n \n isSolution :: Text -> Bool\n isSolution str = str == \"ab\" || str == \"ba\"\n\nmain :: IO ()\nmain = do\n x <- read @Int <$> getLine\n forM_ [1 .. x] $ \\_ -> do\n getLine\n str <- getLine\n case solution (T.pack str) of\n Just (x, y) -> printf \"%d %d\\n\" x y\n Nothing -> putStrLn \"-1 -1\"\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Text.Printf\n\nslice :: Int -> Int -> Text -> Text\nslice a b = T.take (b - a + 1) . T.drop (a - 1)\n\nsolution :: Text -> Maybe (Int, Int)\nsolution str = listToMaybe $ do\n x <- [1 .. T.length str]\n let y = x + 1\n guard $ x < y\n guard $ isSolution $ slice x y str\n return (x, y)\n where\n count :: Char -> Text -> Int\n count c = T.foldl' (\\x c' -> x + fromEnum (c' == c)) 0\n\n isSolution :: Text -> Bool\n isSolution str = count 'a' str == count 'b' str\n\nmain :: IO ()\nmain = do\n x <- read @Int <$> getLine\n forM_ [1 .. x] $ \\_ -> do\n getLine\n str <- getLine\n case solution (T.pack str) of\n Just (x, y) -> printf \"%d %d\\n\" x y\n Nothing -> putStrLn \"-1 -1\"\n"}, {"source_code": "#!/usr/bin/env stack\r\n-- stack --resolver lts-13.7 script\r\n\r\nimport Control.Monad\r\n-- import Data.Char\r\n\r\nmain :: IO()\r\n\r\nmain = do\r\n t <- readLn\r\n -- putStrLn $ show t\r\n xs <- replicateM t $ do\r\n n <- readLn\r\n str <- getLine\r\n return $ solve n str\r\n putStr $ unlines xs\r\n\r\nsolve :: Int -> String -> String\r\n\r\n-- solve 1 _ = \"-1 -1\"\r\nsolve _ str = (show l) ++ \" \" ++ (show r)\r\n where \r\n diff :: Int -> [Char] -> Int\r\n diff k (x:y:xs)\r\n | x == y = diff (k+1) (y:xs)\r\n | otherwise = k\r\n diff _ _ = -1\r\n h = diff 0 str\r\n l = if h == -1 then h else h+1\r\n r = if h == -1 then h else h+2"}, {"source_code": "import Control.Monad\nimport Data.Array.Unboxed\n\ntype Ar = Array Int Char\n\ncount :: Char -> Ar -> Int\ncount c ar =\n foldl (\\a x -> if c==x then a+1 else a) 0 ar\n\ncalc' :: Ar -> Int -> Int -> Int -> Int -> (Int,Int)\ncalc' ar l r ca cb | (lr = (-1,-1)\ncalc' ar l r ca cb | ca < cb\n = if (ar ! l) == 'b' then\n calc' ar (l+1) r ca (cb-1)\n else if (ar ! r) == 'b' then\n calc' ar l (r-1) ca (cb-1)\n else\n calc' ar (l+1) r (ca-1) cb\ncalc' ar l r ca cb | cb < ca\n = if (ar ! l) == 'a' then\n calc' ar (l+1) r (ca-1) cb\n else if (ar ! r) == 'a' then\n calc' ar l (r-1) (ca-1) cb\n else\n calc' ar (l+1) r ca (cb-1)\n\ncalc :: Int -> Ar -> (Int,Int)\ncalc n ar =\n let ca = count 'a' ar\n cb = count 'b' ar\n in\n calc' ar 0 (n-1) ca cb\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let (a,b) = calc n $ listArray (0,n-1) line\n putStr $ show a\n putStr \" \"\n putStrLn $ show b\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\n\r\nreadInt = read `fmap` getLine :: IO Int\r\n\r\nisA x = if x == 'a' then 1 else 0\r\nisB x = if x == 'b' then 1 else 0\r\n\r\nmain = do\r\n t <- readInt\r\n replicateM_ t $ do\r\n n <- readInt\r\n msg <- getLine :: IO [Char]\r\n --msg <- listArray (1,n) `fmap` getLine\r\n let numA = listArray (0,n) $ scanl (+) 0 (map isA msg)\r\n let numB = listArray (0,n) $ scanl (+) 0 (map isB msg)\r\n let solns = filter balanced [(x,y) | x <- [1..n], y <- [x..n]] where\r\n balanced (x,y) = (numA ! y) - (numA ! (x-1)) == (numB ! y) - (numB ! (x-1))\r\n if null solns then do\r\n putStrLn \"-1 -1\"\r\n else do\r\n let (x,y) = head solns\r\n putStrLn $ (show x) ++ \" \" ++ (show y)"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[_n] <- getInts 1\n ~[s] <- map P.unpack <$> getNext 1\n let opts = [i | (i, si, sj) <- zip3 [1..] s (tail s), si /= sj]\n pure $ case opts of\n [] -> putInts [-1, -1]\n i : _ -> putInts [i, i+1]\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import Control.Monad\r\nimport Data.Foldable\r\nimport Data.Maybe\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n s <- getLine\r\n putStrLn $ fromMaybe \"-1 -1\" $ asum $\r\n zipWith3 (\\i x y -> show i ++ \" \" ++ show (i + 1) <$ guard (x /= y)) [1..] s (tail s)\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}], "negative_code": [{"source_code": "#!/usr/bin/env stack\r\n-- stack --resolver lts-13.7 script\r\n\r\nimport Control.Monad\r\n-- import Data.Char\r\n\r\nmain :: IO()\r\n\r\nmain = do\r\n t <- readLn\r\n -- putStrLn $ show t\r\n xs <- replicateM t $ do\r\n n <- readLn\r\n str <- getLine\r\n return $ solve n str\r\n putStr $ unlines xs\r\n\r\nsolve :: Int -> String -> String\r\n\r\n-- solve 1 _ = \"-1 -1\"\r\nsolve _ str = (show l) ++ \" \" ++ (show r)\r\n where \r\n diff :: Int -> [Char] -> Int\r\n diff k (x:y:xs)\r\n | x == y = diff (k+1) (y:xs)\r\n | otherwise = k\r\n diff _ _ = -1\r\n l = diff 0 str\r\n r = if l == -1 then -1 else l+1"}], "src_uid": "127d7f23a0ac8fcecccd687565d6f35a"} {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n", "positive_code": [{"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n"}, {"source_code": "import List\nimport Maybe\nmain = do\n n <- getLine\n sp <- sequence (replicate (read n) getLine)\n let i = fromJust $ elemIndex (maximum (map f sp)) (map f sp)\n putStrLn $ head $ words $ sp !! i\nf :: String -> Int\nf s = let\n s1 = tail $ map read (words s)\n (a, b, sp) = (head s1, head $ tail s1, tail $ tail s1)\n in 100 * a - 50 * b + sum sp\n"}, {"source_code": "parseLine :: String -> (String, Int)\nparseLine s = (name, result)\n where\n (name:xs) = words s\n balls = map (read::String -> Int) xs\n result = foldl (+) 0 (zipWith (*) balls [100, -50, 1, 1, 1, 1, 1])\n\nmain = do\n n <- readLn::IO Int\n lines <- sequence (map (\\n -> getLine) [1..n])\n let pairs = map parseLine lines\n putStrLn (fst (foldl (\\x y -> if snd x > snd y then x else y) (head pairs) (tail pairs)))"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Function\n\nparseLine :: String -> (String, Int)\nparseLine str = (head ws, plus * 100 - minus * 50 + sum probs)\n where\n ws = words str\n plus = read $ ws !! 1 :: Int\n minus = read $ ws !! 2 :: Int\n probs = map read $ drop 3 ws :: [Int]\n\nmain = do\n n <- read <$> getLine :: IO Int\n cs <- replicateM n (parseLine <$> getLine)\n putStrLn $ fst $ maximumBy (compare `on` snd) cs\n"}, {"source_code": "import Control.Monad\nmain = do\n n <- readLn\n putStrLn . snd . maximum =<< replicateM n parse\nparse = do\n [handle,p,m,a,b,c,d,e] <- liftM words getLine\n return ( 100*read p - 50*read m + read a + read b + read c + read d + read e\n , handle )"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n"}, {"source_code": "main=interact$snd.maximum.map (p.words).tail.lines\nr=read\np(n:s:u:x)=((sum.map r)x+r s*100-r u*50, n)\n"}], "negative_code": [], "src_uid": "b9dacff0cab78595296d697d22dce5d9"} {"source_code": "import Data.List\nimport Control.Monad\nimport Data.IntMap\n\nlistMap = Data.List.map\n\ninputNum = do\n line <- getLine\n return ((read line) :: Int)\n\ninputArr = do\n line <- getLine\n let ar = listMap read (words line) :: [Int]\n return ar\n\nbuildGraph p = fromList res1\n where res1 = listMap (\\(ind, x) -> (ind, (x-1, False))) (zip [0..((length p) - 1)] p)\n\ndfs cur to g m s\n | cur == to = (adjust (\\(n, vis) -> (n, True)) cur g, Data.IntMap.insert cur s m)\n | otherwise = let\n nxt = (fst (g ! cur))\n (newG, newM) = dfs nxt to g m (s+1)\n in (adjust (\\(n, vis) -> (n, True)) cur newG, Data.IntMap.insert cur (newM ! nxt) newM)\n\n\ndfsAll (-1) graph m = m\ndfsAll ind graph m\n | vis = dfsAll (ind-1) graph m\n | otherwise = let\n (nxtG, nxtM) = dfs (fst (graph ! ind)) ind graph m 1\n in dfsAll (ind-1) nxtG nxtM\n where (nxt, vis) = graph ! ind\n\nsolveCase = do\n n <- inputNum\n p <- inputArr\n let graph = buildGraph p\n let res = dfsAll (n-1) graph (fromList [])\n let erg1 = listMap ((' ':) . show) (listMap snd (toList res))\n let (_:erg) = concat erg1\n putStrLn erg\n\nmain = do\n line <- getLine\n let n = (read line :: Int)\n replicateM_ n solveCase\n {-\n line2 <- getLine\n let x = n+1\n let s = show x\n let z = words line2\n let ar = map read z :: [Int]\n let s2 = map (show . (+ 1)) ar\n putStrLn s\n putStrLn (concat s2)\n -}\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n\n\nlistMap = Data.List.map\n\ninputNum = do\n line <- getLine\n return ((read line) :: Int)\n\ninputArr = do\n line <- getLine\n let ar = listMap read (words line) :: [Int]\n return ar\n\nbuildGraph p = IntMap.fromList res1\n where res1 = listMap (\\(ind, x) -> (ind, (x-1, False))) (zip [0..((length p) - 1)] p)\n\ndfs cur to g m s\n | cur == to = (IntMap.adjust (\\(n, vis) -> (n, True)) cur g, IntMap.insert cur s m)\n | otherwise = let\n nxt = (fst (g IntMap.! cur))\n (newG, newM) = dfs nxt to g m (s+1)\n in (IntMap.adjust (\\(n, vis) -> (n, True)) cur newG, IntMap.insert cur (newM IntMap.! nxt) newM)\n\n\ndfsAll (-1) graph m = m\ndfsAll ind graph m\n | vis = dfsAll (ind-1) graph m\n | otherwise = let\n (nxtG, nxtM) = dfs (fst (graph IntMap.! ind)) ind graph m 1\n in dfsAll (ind-1) nxtG nxtM\n where (nxt, vis) = graph IntMap.! ind\n\nsolveCase = do\n n <- inputNum\n p <- inputArr\n let graph = buildGraph p\n let res = dfsAll (n-1) graph (IntMap.fromList [])\n let erg1 = listMap ((' ':) . show) (listMap snd (IntMap.toList res))\n let (_:erg) = concat erg1\n putStrLn erg\n\nmain = do\n line <- getLine\n let n = (read line :: Int)\n replicateM_ n solveCase\n {-\n line2 <- getLine\n let x = n+1\n let s = show x\n let z = words line2\n let ar = map read z :: [Int]\n let s2 = map (show . (+ 1)) ar\n putStrLn s\n putStrLn (concat s2)\n -}\n"}], "negative_code": [], "src_uid": "345e76bf67ae4342e850ab248211eb0b"} {"source_code": "{-# LANGUAGE RecursiveDo #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n\r\nimport Control.Monad (ap, replicateM_)\r\nimport Control.Monad.Fix (MonadFix (mfix))\r\nimport Control.Monad.Identity (Identity (runIdentity))\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (chr, ord)\r\n\r\nnewtype RStateT s m a = RStateT\r\n { runRStateT :: s -> m (a, s)\r\n }\r\n\r\ninstance Functor m => Functor (RStateT s m) where\r\n fmap f (RStateT g) = RStateT $ \\s -> fmap (first f) (g s)\r\n\r\ninstance MonadFix m => Applicative (RStateT s m) where\r\n pure a = RStateT $ \\s -> pure (a, s)\r\n (<*>) = ap\r\n\r\ninstance MonadFix m => Monad (RStateT s m) where\r\n return = pure\r\n RStateT f >>= g = RStateT $ \\s -> do\r\n rec (a, s'') <- f s'\r\n (b, s') <- runRStateT (g a) s\r\n pure (b, s'')\r\n\r\ninstance MonadFix m => MonadFix (RStateT s m) where\r\n mfix f = RStateT $ \\s -> do\r\n rec (a, s') <- runRStateT (f a) s\r\n pure (a, s')\r\n\r\nget :: Monad m => RStateT s m s\r\nget = RStateT $ \\s -> pure (s, s)\r\n\r\nput :: Monad m => s -> RStateT s m ()\r\nput s = RStateT $ \\_ -> pure ((), s)\r\n\r\ntype RState s = RStateT s Identity\r\n\r\nevalRState :: RState s a -> s -> a\r\nevalRState (RStateT f) s = fst . runIdentity $ f s\r\n\r\nmain = readLn >>= flip replicateM_ testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n _n <- readLn @Int\r\n line <- getLine\r\n\r\n let calculation :: String -> String\r\n calculation ('9' : xs) = flip evalRState False . mapM cursedThing $ '9' : xs\r\n calculation xs = fmap (\\ch -> chr (ord '0' + ord '9' - ord ch)) xs\r\n\r\n cursedThing :: Char -> RState Bool Char\r\n cursedThing ch = mdo\r\n put carry'\r\n\r\n let ch' =\r\n ord ch - ord '0'\r\n + if carry\r\n then 1\r\n else 0\r\n\r\n (res, carry') =\r\n if ch' <= 1\r\n then (1 - ch', False)\r\n else (11 - ch', True)\r\n\r\n carry <- get\r\n\r\n pure . chr $ res + ord '0'\r\n\r\n result = calculation line\r\n\r\n putStrLn result\r\n", "positive_code": [{"source_code": "{-# LANGUAGE RecursiveDo #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n\r\nimport Control.Monad (ap, replicateM_, void)\r\nimport Control.Monad.Fix (MonadFix (mfix))\r\nimport Control.Monad.Identity (Identity (runIdentity))\r\nimport Control.Monad.Trans (MonadTrans (lift))\r\nimport Control.Monad.Writer (MonadWriter (tell), Writer, execWriter)\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (chr, ord)\r\nimport Data.Functor (($>))\r\nimport Data.Monoid (Endo (Endo))\r\n\r\n-- Reverse monadic fold\r\n\r\nfoldM' :: MonadFix m => (a -> b -> m b) -> b -> [a] -> m b\r\nfoldM' _ b [] = pure b\r\nfoldM' f b (x : xs) = mdo\r\n res <- x `f` xs'\r\n xs' <- foldM' f b xs\r\n pure res\r\n\r\nfoldM_' :: MonadFix m => (a -> b -> m b) -> b -> [a] -> m ()\r\nfoldM_' = ((void .) .) . foldM'\r\n\r\n-- Difference strings\r\n\r\ntype DString = Endo String\r\n\r\nsingleton :: Char -> DString\r\nsingleton ch = Endo ([ch] ++)\r\n\r\ntoString :: DString -> String\r\ntoString (Endo f) = f \"\"\r\n\r\n-- The solution itself\r\n\r\nmain = readLn >>= flip replicateM_ testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n _n <- readLn @Int\r\n line <- getLine\r\n\r\n let result = calculation line\r\n\r\n putStrLn result\r\n\r\ncalculation :: String -> String\r\ncalculation xs@('9' : _) = toString . execWriter . foldM_' processDigit False $ xs\r\ncalculation xs = fmap (\\ch -> chr (ord '0' + ord '9' - ord ch)) xs\r\n\r\nprocessDigit :: Char -> Bool -> Writer DString Bool\r\nprocessDigit ch carry = (tell . singleton . chr $ res + ord '0') $> carry'\r\n where\r\n ch' = ord ch - ord '0' + fromEnum carry\r\n\r\n (res, carry') =\r\n if ch' <= 1\r\n then (1 - ch', False)\r\n else (11 - ch', True)\r\n"}, {"source_code": "{-# LANGUAGE RecursiveDo #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n\r\nimport Control.Monad (ap, replicateM_, void)\r\nimport Control.Monad.Fix (MonadFix (mfix))\r\nimport Control.Monad.Identity (Identity (runIdentity))\r\nimport Control.Monad.Trans (MonadTrans (lift))\r\nimport Control.Monad.Writer (MonadWriter (tell), Writer, execWriter)\r\nimport Data.Bifunctor (first)\r\nimport Data.Char (chr, ord)\r\nimport Data.Monoid (Endo (Endo))\r\n\r\n-- Reverse state transformer\r\n\r\nnewtype RStateT s m a = RStateT\r\n { runRStateT :: s -> m (a, s)\r\n }\r\n\r\ninstance Functor m => Functor (RStateT s m) where\r\n fmap f (RStateT g) = RStateT $ \\s -> fmap (first f) (g s)\r\n\r\ninstance MonadFix m => Applicative (RStateT s m) where\r\n pure a = RStateT $ \\s -> pure (a, s)\r\n (<*>) = ap\r\n\r\ninstance MonadFix m => Monad (RStateT s m) where\r\n return = pure\r\n RStateT f >>= g = RStateT $ \\s -> do\r\n rec ~(a, s'') <- f s'\r\n ~(b, s') <- runRStateT (g a) s\r\n pure (b, s'')\r\n\r\ninstance MonadFix m => MonadFix (RStateT s m) where\r\n mfix f = RStateT $ \\s -> do\r\n rec ~(a, s') <- runRStateT (f a) s\r\n pure (a, s')\r\n\r\ninstance MonadTrans (RStateT s) where\r\n lift a = RStateT $ \\s -> do\r\n res <- a\r\n pure (res, s)\r\n\r\nget :: Monad m => RStateT s m s\r\nget = RStateT $ \\s -> pure (s, s)\r\n\r\nput :: Monad m => s -> RStateT s m ()\r\nput s = RStateT $ \\_ -> pure ((), s)\r\n\r\ntype RState s = RStateT s Identity\r\n\r\nevalRState :: RState s a -> s -> a\r\nevalRState (RStateT f) s = fst . runIdentity $ f s\r\n\r\n-- Difference strings\r\n\r\ntype DString = Endo String\r\n\r\nsingleton :: Char -> DString\r\nsingleton ch = Endo ([ch] ++)\r\n\r\ntoString :: DString -> String\r\ntoString (Endo f) = f \"\"\r\n\r\n-- The solution itself\r\n\r\nmain = readLn >>= flip replicateM_ testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n _n <- readLn @Int\r\n line <- getLine\r\n \r\n let result = calculation line\r\n \r\n putStrLn result\r\n\r\ncalculation :: String -> String\r\ncalculation ('9' : xs) = toString . execWriter . flip runRStateT False . mapM cursedThing $ '9' : xs\r\ncalculation xs = fmap (\\ch -> chr (ord '0' + ord '9' - ord ch)) xs\r\n\r\ncursedThing :: Char -> RStateT Bool (Writer DString) ()\r\ncursedThing ch = mdo\r\n put carry'\r\n\r\n let ch' =\r\n ord ch - ord '0'\r\n + if carry\r\n then 1\r\n else 0\r\n\r\n (res, carry') =\r\n if ch' <= 1\r\n then (1 - ch', False)\r\n else (11 - ch', True)\r\n\r\n lift . tell . singleton . chr . (+ ord '0') $ res\r\n\r\n carry <- get\r\n pure ()\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO qualified as IO\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [len] <- ri\r\n num <- IO.getLine\r\n return (len,num)\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve (len,num) = ans\r\n where\r\n ans | (head num /= '9') = map invD num\r\n | otherwise = num2\r\n\r\n invD = toC . (-) 9 . toN\r\n\r\n num2 = show (bigPal - read num)\r\n bigPal = read (replicate (len+1) '1') :: Integer\r\n\r\ntoN c = ord c - ord '0'\r\ntoC d = chr $ ord '0' + d\r\n"}], "negative_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO qualified as IO\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [len] <- ri\r\n num <- IO.getLine\r\n return (len,num)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (len,num) = (len,num, ans)\r\n where\r\n ans | (head num /= '9') = map invD num\r\n | otherwise = num2\r\n\r\n invD = toC . (-) 9 . toN\r\n\r\n num2 = show (bigPal - read num)\r\n bigPal = read (replicate (len+1) '1') :: Integer\r\n\r\ntoN c = ord c - ord '0'\r\ntoC d = chr $ ord '0' + d\r\n"}], "src_uid": "d3c3bc95605010040e2018e465eb9fab"} {"source_code": "-- http://codeforces.com/contest/818/problem/D\n\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport qualified Data.IntSet as S\nimport Data.Maybe\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\ndata State = State {\n getOccur :: M.Map Int Int,\n getCandidates :: S.IntSet\n}\n\nstate0 = State {\n getOccur = M.fromList [(i,0) | i <- [1..10^6]],\n getCandidates = S.empty\n}\n\nmain = do\n [n,a] <- getInts\n cars <- getInts\n let State _ cands = foldl (f n a) state0 cars\n case S.elems cands of\n [] -> print (-1)\n (x:_) -> print x\n\nf :: Int -> Int -> State -> Int -> State\nf n alice st car\n | car == alice = State occur' (S.filter (\\cand -> occur M.! cand > occur M.! alice) cands)\n | (occur M.! alice == 0) || (S.member car cands && occur M.! car >= occur M.! alice) = State occur' cands'\n | otherwise = State occur' cands\n where\n cands = getCandidates st\n cands' = S.insert car cands\n occur = getOccur st\n occur' = M.insertWith (+) car 1 occur", "positive_code": [{"source_code": "-- http://codeforces.com/contest/818/problem/D\n\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport qualified Data.IntSet as S\nimport Data.Maybe\nimport Data.List\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\ndata State = State {\n getOccur :: M.Map Int Int,\n getCandidates :: S.IntSet\n}\n\nstate0 = State {\n getOccur = M.fromList [(i,0) | i <- [1..10^6]],\n getCandidates = S.empty\n}\n\nmain = do\n [n,a] <- getInts\n cars <- getInts\n let State _ cands = foldl' (f n a) state0 cars\n case S.elems cands of\n [] -> print (-1)\n (x:_) -> print x\n\nf :: Int -> Int -> State -> Int -> State\nf n alice st car\n | car == alice = State occur' (S.filter (\\cand -> occur M.! cand > occur M.! alice) cands)\n | (occur M.! alice == 0) || (S.member car cands && occur M.! car >= occur M.! alice) = State occur' cands'\n | otherwise = State occur' cands\n where\n cands = getCandidates st\n cands' = S.insert car cands\n occur = getOccur st\n occur' = M.insertWith (+) car 1 occur"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.IArray\nimport Data.Array.ST.Safe \nimport Control.Monad.ST.Safe\nimport Control.Monad\nimport Data.List\n\nmain = do\n [n, a] <- fmap readInts B.getLine\n ks <- fmap readInts B.getLine\n print $ solve n a ks\n\nsolve n a ks = maybe (-1) id $ find (\\i -> (gtc!i) >= (gtc!a)) $ filter (/= a) $ range bnd\n where\n bnd = (1, 1000000)\n gtc = runSTUArray $ do\n gtc <- newArray (1, 1000000) 0 :: ST s (STUArray s Int Int)\n forM_ ks $ \\k -> do\n gtc_k <- readArray gtc k\n gtc_a <- readArray gtc a\n writeArray gtc k $ gtc_k + fromEnum (gtc_k >= gtc_a)\n return gtc\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.IArray\nimport Data.Array.ST.Safe \nimport Control.Monad.ST.Safe\nimport Control.Monad\nimport Data.List\n\nmain = do\n [n, a] <- fmap readInts B.getLine\n ks <- fmap readInts B.getLine\n print $ solve n a ks\n\nsolve n a ks = maybe (-1) id $ find (\\i -> (gtc!i) > (gtc!a)) $ range bnd\n where\n bnd = (1, 1000000)\n gtc = runSTUArray $ do\n gtc <- newArray (1, 1000000) 0 :: ST s (STUArray s Int Int)\n forM_ ks $ \\k -> do\n gtc_k <- readArray gtc k\n gtc_a <- readArray gtc a\n writeArray gtc k $ gtc_k + fromEnum (gtc_k >= gtc_a)\n return gtc\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "src_uid": "c6713175ad447b41b897a5904b7fe714"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables, BangPatterns #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Array.IArray as A (Array, listArray, (!))\nimport Control.Monad (forM_)\nimport Data.Bits (shiftR)\n\nreadInt = fst . M.fromJust . C.readInt\n\n-- persistent segment tree\ndata PSEG = LF !Int | BR !Int !PSEG !PSEG\n\ncreate l r | l + 1 == r = LF 0\n | otherwise = BR 0 (create l mid) (create mid r)\n where !mid = (l + r) `shiftR` 1\nupdate _ _ (LF i) _ = LF (succ i)\nupdate l r (BR i il ir) x = BR (succ i) jl jr where\n !mid = (l + r) `shiftR` 1\n (jl, jr) = if x < mid then (update l mid il x, ir) else (il, update mid r ir x)\n\nbuild :: Int -> Int -> [Int] -> A.Array Int PSEG\nbuild !nr !n !xs = A.listArray (0, n) $ scanl (update 0 nr) (create 0 nr) xs\ndfs l _ (LF i) (LF j) !t | j - i <= t = -1 | otherwise = succ l\ndfs l r (BR i il ir) (BR j jl jr) !t | j - i <= t = -1 | dl == -1 = dr | otherwise = dl where\n mid = (l + r) `shiftR` 1\n (dl, dr) = (dfs l mid il jl t, dfs mid r ir jr t)\n\nmain = do\n (map readInt . C.words -> [n, q]) <- B.getLine\n (map (pred . readInt) . C.words -> xs) <- B.getLine\n let !pseg = build n n xs\n forM_ [1..q] $ \\_ -> do\n (map readInt . C.words -> [l, r, k]) <- B.getLine\n putStrLn $ show $ dfs 0 n (pseg A.! (l - 1)) (pseg A.! r) ((r - l + 1) `div` k)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables, BangPatterns, DeriveGeneric #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Array.IArray as A (Array, listArray, array, (!))\nimport qualified Data.Array.MArray.Safe as A (newArray, writeArray)\nimport qualified Data.Array.Unboxed as A (UArray)\nimport qualified Data.List as L (sortBy, groupBy, nub)\nimport qualified Data.STRef as ST (STRef, newSTRef, readSTRef, writeSTRef)\nimport qualified Data.Array.ST.Safe as ST (STUArray, getElems, freeze)\nimport qualified Control.Monad.ST.Safe as ST (runST, ST)\nimport GHC.Generics (Generic)\nimport Data.Function (on)\nimport Control.Monad (forM_)\nimport Control.DeepSeq (NFData, force)\nimport Data.Bits (unsafeShiftR)\n\nreadInt = fst . M.fromJust . C.readInt\n\ncompress :: Int -> [Int] -> (Int, [Int], A.UArray Int Int)\ncompress !n !a = ST.runST $ do\n let !xs = L.sortBy (compare `on` fst) $! zip a [0..]\n j <- ST.newSTRef 0 :: ST.ST s (ST.STRef s Int)\n pre <- (ST.newSTRef (fst (head xs))) :: ST.ST s (ST.STRef s Int)\n b <- A.newArray (0, n - 1) 0 :: ST.ST s (ST.STUArray s Int Int)\n forM_ xs $ \\(i, idx) -> do\n jv <- ST.readSTRef j\n prev <- ST.readSTRef pre\n if i == prev then\n A.writeArray b idx jv\n else do\n A.writeArray b idx (jv + 1)\n ST.writeSTRef j (jv + 1)\n ST.writeSTRef pre i\n jv <- ST.readSTRef j\n bv <- ST.getElems b\n mp <- A.newArray (-1, jv) (-1) :: ST.ST s (ST.STUArray s Int Int)\n forM_ (zip a bv) $ \\(i, j) -> do\n A.writeArray mp j i\n mpv <- ST.freeze mp\n return $! (jv + 1, bv, mpv)\n\n-- persistent segment tree\ndata PSEG = LF !Int | BR !Int !PSEG !PSEG deriving (Eq, Generic)\ninstance NFData PSEG\ncreate l r | l + 1 == r = LF 0\n | otherwise = BR 0 (create l mid) (create mid r)\n where !mid = (l + r) `unsafeShiftR` 1\nupdate _ _ (LF i) _ = LF (i + 1)\nupdate l r (BR i il ir) x = BR (i + 1) jl jr where\n !mid = (l + r) `unsafeShiftR` 1\n (jl, jr) = if x < mid then (update l mid il x, ir) else (il, update mid r ir x)\n\nbuild :: Int -> Int -> [Int] -> A.Array Int PSEG\nbuild !nr !n !xs = A.listArray (0, n) $ scanl (force $ update 0 nr) (force $ create 0 nr) xs\ndfs l _ (LF i) (LF j) ! t | j - i <= t = -1 | otherwise = l\ndfs l r (BR i il ir) (BR j jl jr) !t\n | j - i <= t = -1 | dl == -1 = dr | otherwise = dl where\n mid = (l + r) `unsafeShiftR` 1\n (dl, dr) = (dfs l mid il jl t, dfs mid r ir jr t)\n\nmain = do\n (map readInt . C.words -> [n, q]) <- B.getLine\n (map readInt . C.words -> xs) <- B.getLine\n let !(nr, ras, rcs) = compress n xs\n !pseg = build nr n ras\n forM_ [1..q] $ \\_ -> do\n (map readInt . C.words -> [l, r, k]) <- B.getLine\n putStrLn $ show $ rcs A.! (dfs 0 nr (pseg A.! (l - 1)) (pseg A.! r) ((r - l + 1) `div` k))\n"}], "negative_code": [], "src_uid": "f5bebe1c91de4492ad7516c7607530db"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE OverloadedLists #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe\r\n\r\n--\r\nimport Data.Bool\r\nimport Data.Containers.ListUtils\r\nimport qualified Data.Map.Strict as M\r\nimport qualified Data.Set as S\r\n\r\nsolve :: [[Int]] -> Bool\r\nsolve es = ok && isJust (foldM w M.empty $ nubOrd es)\r\n where\r\n q = M.elems $ M.fromListWith (++) [(v, [e]) | e <- es, v <- e]\r\n ok = not (any ((> 2) . length) q) && not (any (and . (map <$> ((==) . head) <*> tail)) es)\r\n g = graph [(v, u) | [v, u] <- q]\r\n\r\n w sides v\r\n | M.member v sides = Just sides\r\n | otherwise = bipart (M.insert v 0 sides) v\r\n\r\n bipart sides v = foldM f sides $ neighs g v\r\n where\r\n f sides u = case sides M.!? u of\r\n Nothing -> bipart (M.insert u (1 - (sides M.! v `mod` 2)) sides) u\r\n Just s\r\n | u == v && sides M.! v < 2 -> Just $ M.adjust (+ 2) v sides\r\n | s == sides M.! v -> Nothing\r\n | otherwise -> Just sides\r\n\r\ntype Graph a = M.Map a (S.Set a)\r\n\r\nneighs :: Ord a => Graph a -> a -> S.Set a\r\nneighs g v = fromMaybe [] $ g M.!? v\r\n\r\ngraph :: Ord a => [(a, a)] -> Graph a\r\ngraph es = M.fromListWith S.union $ concat [[(v, [u]), (u, [v])] | (v, u) <- es]\r\n\r\n-- reachable :: Ord a => Graph a -> a -> S.Set a\r\n-- reachable g = reachable' g []\r\n-- where\r\n-- reachable' g acc v =\r\n-- if S.member v acc\r\n-- then acc\r\n-- else S.foldl (reachable' g) (S.insert v acc) (neighs g v)\r\n\r\ninput :: Scanner [[Int]]\r\ninput = do\r\n n <- int\r\n n >< (2 >< int)\r\n\r\noutput = bool \"NO\" \"YES\"\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\n-- Scanner\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n--\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\ntype GraphA = A.Array Int [Int]\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n{- END OF GENERAL -}\n\nhaveOddCycles :: Int -> GraphA -> Bool\nhaveOddCycles n graph = ST.runST $ do\n visitedA <- MA.newArray (1, n) False :: ST.ST s (STA.STUArray s Int Bool)\n colorA <- MA.newArray (1, n) 0 :: ST.ST s (STA.STUArray s Int Int)\n let \n dfs :: Int -> Int -> STA.STUArray s Int Int -> STA.STUArray s Int Bool -> ST.ST s Bool\n dfs v color colorA visitedA = do\n -- traceM $ \"dfs\" ++ (\" v = \" ++ show v) ++ (\" color = \" ++ show color)\n visitedV <- MA.readArray visitedA v\n colorV <- MA.readArray colorA v\n flip S.execStateT True $ do\n if visitedV\n then do\n S.put $ color == colorV\n else do\n T.lift $ MA.writeArray visitedA v True\n T.lift $ MA.writeArray colorA v color\n let us = graph A.! v\n forM_ us $ \\u -> do\n subAnswer <- T.lift $ dfs u (1 - color) colorA visitedA\n S.modify (&& subAnswer)\n\n ok <- flip S.execStateT True $ do\n forM_ [1 .. n] $ \\v -> do\n visited <- T.lift $ MA.readArray visitedA v\n M.when (not visited) $ do\n subAnswer <- T.lift $ dfs v 0 colorA visitedA\n S.modify (&& subAnswer)\n return $ not ok\n\n\n\nhaveLoops :: Int -> GraphA -> Bool\nhaveLoops n graph = L.any (\\(u, vs) -> u `L.elem` vs) $ A.assocs graph\n\n\nsolve :: Int -> [(Int, Int)] -> Bool\nsolve n dominos = not isBadGraph\n where\n graph :: GraphA\n graph = graphFromEdges n dominos\n\n isBadGraph :: Bool\n isBadGraph = haveMore2Occurences || haveLoops' || haveOddCycles'\n\n haveLoops' :: Bool\n haveLoops' = (haveLoops n graph) \n -- `debugging` \"haveLoops\"\n\n haveOddCycles' :: Bool\n haveOddCycles' = (haveOddCycles n graph) \n -- `debugging` \"haveOddCycles\"\n \n haveMore2Occurences' :: Bool\n haveMore2Occurences' = haveMore2Occurences \n -- `debugging` \"haveMore2Occurences\"\n\n haveMore2Occurences :: Bool\n haveMore2Occurences = L.any (\\g -> L.length g > 2) . L.group $ L.sort allHalves\n where\n allHalves = L.concat . L.map (\\(a, b) -> [a, b]) $ dominos\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n dominos <- replicateM n $ do\n [a, b] <- B8.getLine <&> readIntB8s\n return (a, b)\n let answer = solve n dominos\n putsYesNo answer\n\n"}], "negative_code": [], "src_uid": "8717913513b019d3ef836176eafce7b1"} {"source_code": "module Main where\n\nimport qualified Data.Set as S\n\nsolution a c = let one = S.fromList (fst <$> c); two = S.fromList (snd <$> c) in S.size one == a || S.size two == a\n\nloop :: Int -> IO () -> IO ()\nloop 0 act = return ()\nloop x act = act >>= (\\_ -> loop (x - 1) act) \n\naccum :: Int -> IO a -> IO [a]\naccum 0 _ = pure []\naccum x get = (:) <$> get <*> accum (x - 1) get\n\nmain = do\n times <- read <$> getLine\n loop times $ do\n (a : b : _) <- fmap read . words <$> getLine\n list <- accum b $ (\\(a : b : _) -> (a, b)) . fmap read . words <$> getLine :: IO [(Int, Int)]\n putStrLn $ (\\x -> if not x then \"YES\" else \"NO\") $ solution a list\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int -> [(Int, Int)] -> Bool\nsolve n m rooks = xsCount /= n && ysCount /= n\n where\n xsCount = IS.size . IS.fromList $ L.map fst rooks\n ysCount = IS.size . IS.fromList $ L.map snd rooks\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, m] <- B8.getLine <&> readIntB8s\n rooks <- replicateM m $ do\n [x, y] <- B8.getLine <&> readIntB8s\n return (x, y)\n let answer = solve n m rooks\n putsYesNo answer\n"}, {"source_code": "loop 0 = return ()\r\nloop n =\r\n do\r\n x <- getLine\r\n loop (n-1)\r\n\r\ncmp x y = do\r\n if x==y then \"NO\"\r\n else \"YES\"\r\n\r\nsolve 0 = return () \r\nsolve n = do\r\n line <- getLine\r\n let a = (read (takeWhile (/= ' ') line) :: Int)\r\n let b = (read (drop 1 (dropWhile (/= ' ') line)) :: Int)\r\n loop b\r\n let ans = cmp a b\r\n putStrLn $ ans\r\n solve (n-1)\r\n\r\nmain = do\r\n t <- getLine\r\n let n = (read t :: Int)\r\n solve n\r\n \r\n "}, {"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\n----- Solution\r\ndata TC = TC { n :: Int, m :: Int }\r\n\r\ntype Output = Bool\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n m <- int\r\n m >< pair int int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = m < n\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput ix = C.pack . bool \"NO\" \"YES\"\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1..] >>> map (uncurry output) >>> C.unlines\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Text.Parsec as P\r\nimport qualified Text.Parsec.Text as P\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.Text as T\r\n\r\ndata Chessboard = Chessboard\r\n { size :: Int\r\n , rookPositions :: [(Int, Int)]\r\n }\r\n\r\nmain :: IO ()\r\nmain = interact solve\r\n\r\nsolve :: String -> String\r\nsolve s = T.unpack $ case P.parse problemDefinition \"\" (T.pack s) of\r\n (Left parseError) -> \"Could not parse problem definition: \" <> T.pack (show parseError)\r\n (Right chessboards) -> T.intercalate \"\\n\" $ map (formatAnswer . solve') chessboards\r\n\r\nformatAnswer :: Bool -> T.Text\r\nformatAnswer True = \"YES\"\r\nformatAnswer False = \"NO\"\r\n\r\ncowardlyMoves :: Chessboard -> Bool\r\ncowardlyMoves chessboard@Chessboard{..} = any (cowarldyMoves' chessboard) rookPositions\r\n\r\ncowarldyMoves' :: Chessboard -> (Int, Int) -> Bool\r\ncowarldyMoves' Chessboard{..} p@(x, y) = hasXMove || hasYMove\r\n where movableX = [x' | x' <- [1..size], x' /= x]\r\n movableY = [y' | y' <- [1..size], y' /= y]\r\n otherRooks = [p' | p' <- rookPositions, p' /= p]\r\n blockedX = S.fromList $ map fst otherRooks\r\n blockedY = S.fromList $ map snd otherRooks\r\n hasXMove = not (S.member y blockedY) && any (\\x' -> not (S.member x' blockedX)) movableX\r\n hasYMove = not (S.member x blockedX) && any (\\y' -> not (S.member y' blockedY)) movableY\r\n\r\n\r\nsolve' :: Chessboard -> Bool\r\nsolve' = cowardlyMoves\r\n\r\nintP :: P.Parser Int\r\nintP = do\r\n read <$> P.many1 P.digit\r\n\r\nsepCount :: Int -> P.Parser a -> P.Parser b -> P.Parser [b]\r\nsepCount n sep p\r\n | n <= 0 = pure []\r\n | otherwise = do\r\n f <- p\r\n rs <- P.count (n - 1) $ do\r\n sep\r\n p\r\n pure $ f : rs\r\n\r\nproblemDefinition :: P.Parser [Chessboard]\r\nproblemDefinition = do\r\n numTestCases <- intP\r\n P.newline\r\n cs <- sepCount numTestCases P.newline chessboard\r\n P.many P.newline\r\n pure cs\r\n\r\nchessboard :: P.Parser Chessboard\r\nchessboard = do\r\n size <- intP\r\n P.many1 P.space\r\n numRooks <- intP\r\n P.newline\r\n rookPositions <- sepCount numRooks P.newline rookPosition\r\n pure $ Chessboard { size = size, rookPositions = rookPositions }\r\n\r\nrookPosition :: P.Parser (Int, Int)\r\nrookPosition = do\r\n x <- intP\r\n P.many1 P.space\r\n y <- intP\r\n pure (x, y)\r\n"}, {"source_code": "import Data.Char\r\nimport Control.Monad\r\n\r\nsolve n m = if (n>m) then \"YES\" else \"NO\" \r\n\r\n\r\nloop = do\r\n line <- getLine\r\n let [n,m] = (map read . words) line\r\n replicateM_ m getLine\r\n putStrLn (solve n m)\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t loop\r\n \r\n\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Text.Parsec as P\r\nimport qualified Text.Parsec.ByteString as P\r\nimport qualified Data.ByteString as B\r\n\r\ndata Chessboard = Chessboard\r\n { size :: Int\r\n , rookPositions :: [(Int, Int)]\r\n }\r\n\r\nmain :: IO ()\r\nmain = B.interact solve\r\n\r\nsolve :: B.ByteString -> B.ByteString\r\nsolve s = case P.parse problemDefinition \"\" s of\r\n (Left parseError) -> \"Could not parse problem definition.\"\r\n (Right chessboards) -> B.intercalate \"\\n\" $ map (formatAnswer . solve') chessboards\r\n\r\nformatAnswer :: Bool -> B.ByteString\r\nformatAnswer True = \"YES\"\r\nformatAnswer False = \"NO\"\r\n\r\ncowardlyMoves :: Chessboard -> Bool\r\ncowardlyMoves chessboard@Chessboard{..} = any (cowarldyMoves' chessboard) rookPositions\r\n\r\ncowarldyMoves' :: Chessboard -> (Int, Int) -> Bool\r\ncowarldyMoves' Chessboard{..} p@(x, y) = hasXMove || hasYMove\r\n where movableX = [x' | x' <- [1..size], x' /= x]\r\n movableY = [y' | y' <- [1..size], y' /= y]\r\n otherRooks = [p' | p' <- rookPositions, p' /= p]\r\n blockedX = S.fromList $ map fst otherRooks\r\n blockedY = S.fromList $ map snd otherRooks\r\n hasXMove = not (S.member y blockedY) && any (\\x' -> not (S.member x' blockedX)) movableX\r\n hasYMove = not (S.member x blockedX) && any (\\y' -> not (S.member y' blockedY)) movableY\r\n\r\n\r\nsolve' :: Chessboard -> Bool\r\nsolve' = cowardlyMoves\r\n\r\nintP :: P.Parser Int\r\nintP = do\r\n read <$> P.many1 P.digit\r\n\r\nproblemDefinition :: P.Parser [Chessboard]\r\nproblemDefinition = do\r\n numTestCases <- intP\r\n P.newline\r\n P.many chessboard\r\n\r\nchessboard :: P.Parser Chessboard\r\nchessboard = do\r\n size <- intP\r\n P.space\r\n numRooks <- intP\r\n P.newline\r\n rookPositions <- P.count numRooks rookPosition\r\n pure $ Chessboard { size = size, rookPositions = rookPositions }\r\n\r\nrookPosition :: P.Parser (Int, Int)\r\nrookPosition = do\r\n x <- intP\r\n P.space\r\n y <- intP\r\n P.newline\r\n pure (x, y)\r\n"}, {"source_code": "import Data.Char\r\nimport Control.Monad\r\n\r\nsolve n m = if (n>m) then \"YES\" else \"NO\" \r\n\r\n\r\nloop = do\r\n line <- getLine\r\n let [n,m] = (map read . words) line\r\n replicateM_ m getLine\r\n print (solve n m)\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t loop\r\n \r\n\r\n"}, {"source_code": "module Main where\n\nimport qualified Data.Set as S\n\nsolution a c = let one = S.fromList (fst <$> c); two = S.fromList (snd <$> c) in S.size one == a || S.size two == a\n\nloop :: Int -> IO () -> IO ()\nloop 0 act = return ()\nloop x act = act >>= (\\_ -> loop (x - 1) act) \n\naccum :: Int -> IO a -> IO [a]\naccum 0 _ = pure []\naccum x get = (:) <$> get <*> accum (x - 1) get\n\nmain = do\n times <- read <$> getLine\n loop times $ do\n (a : b : _) <- fmap read . words <$> getLine\n list <- accum b $ (\\(a : b : _) -> (a, b)) . fmap read . words <$> getLine :: IO [(Int, Int)]\n print $ (\\x -> if not x then \"YES\" else \"NO\") $ solution a list\n"}], "src_uid": "856b71ffb53f186bccd66c890ed0e099"} {"source_code": "import Control.Monad\n\ncheck n = any (\\x -> (n - x) `mod` 11 == 0 && x <= n) [0,111..1110] \n\nmain = do \n t <- (read <$> getLine) :: IO Int\n replicateM_ t $ do \n x <- (read <$> getLine) :: IO Int\n putStrLn $ if check x then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "import Data.Bool ( bool )\r\n\r\nsolve :: Int -> Bool\r\nsolve n = or [(n - k) `mod` 11 == 0 | k <- [0, 111 .. 1110], k <= n]\r\n\r\nmain = interact $ unlines . map (bool \"NO\" \"YES\" . solve . read) . tail . lines\r\n"}, {"source_code": "import Data.Bool ( bool )\r\n\r\nsolve :: Int -> Bool\r\nsolve n = 0 `elem` [x `mod` 11 | x <- (n - ) <$> [0, 111 .. 1110], x >= 0]\r\n\r\nmain = interact $ unlines . map (bool \"NO\" \"YES\" . solve . read) . tail . lines"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n x <- fmap (fromIntegral . parseInt) C.getLine :: IO Int64\n let\n func x 11 = x `mod` 11 == 0\n func x y = any id [func (x - k * y) (y `div` 10) | k <- [0 .. min 10 (x `div` y)]]\n return $ (string8 $ if func x 11111111 then \"YES\" else \"NO\") `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "import Control.Monad\n\nsolve x\n | or xs = \"YES\"\n | otherwise = \"NO\"\n where xs = [ x `rem` 11 == (111 * d) `rem` 11 && (x - 111 * d) `rem` 11 == 0 | d <- [0..10], x - 111 * d >= 0]\n\nwork = do\n x <- getLine\n\n putStrLn $ solve (read x :: Int)\n\nmain = do\n t <- getLine\n\n replicateM_ (read t :: Int) work\n"}, {"source_code": "\r\n\r\nimport Control.Applicative\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.Trans.Identity\r\nimport Control.Monad.Trans.Maybe\r\nimport Control.Monad \r\nimport Data.Monoid\r\nimport Data.Foldable\r\nimport Data.Traversable\r\nimport Data.Functor.Identity\r\n\r\ngo x d \r\n | (x - d*111) <0 || ((x- d*111) `mod` 11 /= 0) = False\r\n | otherwise = True\r\n\r\nsolve = do\r\n x <- readLn :: IO Int\r\n if (any (go x) [0..10]) then putStrLn(\"YES\") else putStrLn (\"NO\")\r\n\r\nmain :: IO()\r\nmain = do\r\n test <- readLn :: IO Int\r\n replicateM_ test solve"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (getLine >>= putStrLn . solve . read)\n\nlistSmall :: [Int]\nlistSmall = [0,111 .. 1110] >>= \\x -> map (x +) [0,11 .. 1111]\n\nsolve :: Int -> String\nsolve n\n | n > 11 * 111 - 11 - 111 = \"YES\"\n | n `elem` listSmall = \"YES\"\n | otherwise = \"NO\"\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n x <- fmap (fromIntegral . parseInt) C.getLine :: IO Int64\n let k = (9 * x + 99) `div` 100\n result = x >= 11 * k\n return $ (string8 $ if result then \"YES\" else \"NO\") `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "src_uid": "e5e937f080b20eaec5f12f1784ae6427"} {"source_code": "main = do\n input <- readFile \"input.txt\"\n writeFile \"output.txt\" (solve input)\nsolve :: String -> String\nsolve input = output where\n [init]:shuffle = map words $ lines input\n output = answer $ reverse shuffle\n answer [] = init\n answer ([x,y]:xs)\n | z == x = y\n | z == y = x\n | otherwise = z\n where z = answer xs", "positive_code": [{"source_code": "\nimport IO\n\nsolve :: Int -> [[Int]] -> Int\nsolve x [] = x\nsolve x ([a,b]:xs)\n | a == x = solve b xs\n | b == x = solve a xs\n | otherwise = solve x xs\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n n <- (hGetLine hInput >>= return . read)\n swaps <- mapM (\\n -> hGetLine hInput >>= return . map read . words) [1..3]\n hPrint hOutput $ solve n swaps\n \n hClose hInput\n hClose hOutput\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:xs) = toString$solve (toInt a) (map (func'.words) xs) \n where\n func' (a:b:[]) = (toInt a,toInt b)\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve a (b:xs) | (fst b) == a = solve (snd b) xs\n | (snd b) == a = solve (fst b) xs\n | otherwise = solve a xs\nsolve a [] = a"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let readData :: String -> [Int]\n readData = map read . words\n writeText = writeFile \"output.txt\"\n (n : _) : others <- map readData . lines <$> readFile \"input.txt\"\n let pairs = do\n a : b : _ <- others\n return [min a b, max a b]\n cups = take 3 $ drop (3 - n) [False, False, True, False, False]\n swap [1, 2] (x1 : x2 : x3 : _) = x2 : x1 : x3 : []\n swap [1, 3] (x1 : x2 : x3 : _) = x3 : x2 : x1 : []\n swap [2, 3] (x1 : x2 : x3 : _) = x1 : x3 : x2 : []\n ans = (+ 1) . head . findIndices id $ foldr swap cups pairs\n writeText $ printf \"%d\\n\" ans\n\n\n\n"}, {"source_code": "main =\n do\n input <- readFile \"input.txt\"\n writeFile \"output.txt\" (solve input)\n where\n solve :: String -> String\n solve s\n = show $ process init (tail nums)\n where\n nums = map (read::String->Integer) (words s)\n init = head nums\n process init (x:y:rest)\n | init == 6-x-y\n = process init rest\n | otherwise\n = process (x+y-init) rest\n process init []\n = init\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl')\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\nmain = readFile \"input.txt\" >>= (writeFile \"output.txt\" . show . solve . parse . lines)\n\nparse :: [String] -> (Int, [[Int]])\nparse str =\n let n = read (head str)\n lst = map (map read . words) . tail $ str\n in (n, lst)\n\nsolve (n, lst) = foldl' f n lst\n where f acc [x,y] | acc == x = y\n | acc == y = x\n | otherwise = acc\n"}, {"source_code": "import System.IO\n\nmain = do\n handle <- openFile \"input.txt\" ReadMode\n cupStr <- hGetLine handle\n let cup = read cupStr :: Int\n first <- hGetLine handle\n second <- hGetLine handle\n third <- hGetLine handle\n let commands = map (map read . words) [first,second,third] :: [[Int]]\n writeFile \"output.txt\" $ show $ fullShuffle commands cup\n \nfullShuffle :: [[Int]] -> Int -> Int\nfullShuffle commands cup = foldl oneShuffle cup commands\n\noneShuffle :: Int -> [Int] -> Int\noneShuffle cup command \n | cup == head command = last command\n | cup == last command = head command\n | otherwise = cup\n"}, {"source_code": "solve :: String -> String\nsolve s = check n list\n where\n n = head ls\n list = map words $ tail ls\n ls = lines s\n\ncheck :: String -> [[String]] -> String\ncheck n ls = foldl f n ls\n\nf :: String -> [String] -> String\nf x [a, b]\n | x == a = b\n | x == b = a\n | otherwise = x\n\nmain :: IO()\nmain = do\n s <- readFile \"input.txt\"\n writeFile \"output.txt\" $ solve s"}, {"source_code": "\n\n\nfunc1 :: Int -> [(Int, Int)] -> Int\nfunc1 start [] = start\nfunc1 start ((a,b) : xs) | start == a = func1 b xs\n | start == b = func1 a xs\n | otherwise = func1 start xs\n\nfunc :: String -> [(Int, Int)]\nfunc str = f $ tail $ lines str\n where f [] = []\n f (x:xs) = ((head $ map read $ words x), (head $ tail $ map read $ words x)) : f xs\n\nmain :: IO ()\nmain = do\n str <- readFile \"input.txt\"\n writeFile \"output.txt\" $ show $ func1 (read $ head $ lines str) (func str)\n \n\n"}, {"source_code": "\n{-\nfunc1 :: Int -> [(Int, Int)] -> Int\nfunc1 start [] = start\nfunc1 start (x : xs) = func1 (chtarget start x) xs\n where chtarget s (a, b)\n | s == a = b\n | s == b = a\n | otherwise = s\n-}\n\nimport System.IO\n\nfunc1 :: Int -> [(Int, Int)] -> Int\nfunc1 start [] = start\nfunc1 start (x : xs) = func1 (chtarget start x) xs\n where chtarget s (a, b) = if s == a\n then b\n else if s == b\n then a\n else s\nlist2tupple :: [Int] -> [(Int, Int)]\nlist2tupple [] = []\nlist2tupple (x : y : xs) = (x, y) : list2tupple xs\n\nmain :: IO ()\nmain = do\n inh <- openFile \"input.txt\" ReadMode\n outh <- openFile \"output.txt\" WriteMode\n startstr <- hGetLine inh\n let start = (read startstr) :: Int\n\n secondstr <- hGetLine inh\n let secondlist = (map read (words secondstr)) :: [Int]\n \n thirdstr <- hGetLine inh\n let thirdlist = (map read (words thirdstr)) :: [Int]\n\n forthstr <- hGetLine inh\n let forthlist = (map read (words forthstr)) :: [Int]\n\n let list = secondlist ++ thirdlist ++ forthlist\n \n let shuffled = list2tupple list\n\n hPutStrLn outh (show (func1 start shuffled))\n\n hClose inh\n hClose outh\n\n"}, {"source_code": "import IO\n\ngao :: [Int] -> Int\ngao [a] = a\ngao (a:b:c:d) = gao $ (if a == b then c else if a == c then b else a):d\n\nmain = do\n\thi <- openFile \"input.txt\" ReadMode\n\tho <- openFile \"output.txt\" WriteMode\n\thGetContents hi >>= hPutStr ho . show . gao . map read . words\n\thClose ho\t\n"}, {"source_code": "{- \u4eba\u69d8\u306e\u89e3\u7b54\u3092\u53c2\u8003\u306b -}\n\ntest :: [String] -> String\ntest (i : a : b : xs)\n | i == a = test (b : xs)\n | i == b = test (a : xs)\n | otherwise = test (i : xs)\ntest [i] = i\n\nmain :: IO ()\nmain = do input <- readFile \"input.txt\"\n writeFile \"output.txt\" $ test $ words input"}, {"source_code": "import Data.List\n\ntest :: String -> [String] -> Int\ntest \"1\" xs = loop 1 0 0 xs\ntest \"2\" xs = loop 0 1 0 xs\ntest \"3\" xs = loop 0 0 1 xs\n\nloop :: Int -> Int -> Int -> [String] -> Int\nloop a b c (x1 : x2 : xs)\n | xs' == [\"1\", \"2\"] = loop b a c xs\n | xs' == [\"1\", \"3\"] = loop c b a xs\n | xs' == [\"2\", \"3\"] = loop a c b xs\n where xs' = sort [x1, x2]\nloop a b c [] = x + 1\n where Just x = elemIndex 1 [a, b, c]\n\nmain :: IO ()\nmain = do input <- readFile \"input.txt\"\n let cs = words input\n writeFile \"output.txt\" $ show $ test (head cs) (tail cs)"}, {"source_code": "{- \u4eba\u69d8\u306e\u89e3\u7b54\u3092\u53c2\u8003\u306b -}\n\ntest :: String -> [String] -> String\ntest i (a : b : xs)\n | i == a = test b xs\n | i == b = test a xs\n | otherwise = test i xs\ntest i [] = i\n\nmain :: IO ()\nmain = do input <- readFile \"input.txt\"\n let xs = words input\n writeFile \"output.txt\" $ test (head xs) (tail xs)"}, {"source_code": "-- test :: Int -> [[String]] -> Int\ntest \"1\" xs = loop 1 0 0 xs\ntest \"2\" xs = loop 0 1 0 xs\ntest \"3\" xs = loop 0 0 1 xs\n\n-- loop :: Int -> Int -> Int -> [[String]] -> Int\nloop 1 _ _ [] = 1\nloop _ 1 _ [] = 2\nloop _ _ 1 [] = 3\nloop a b c (x1 : x2 : xs)\n | (x1, x2) == (\"1\", \"2\") || (x1, x2) == (\"2\", \"1\") = loop b a c xs\n | (x1, x2) == (\"1\", \"3\") || (x1, x2) == (\"3\", \"1\") = loop c b a xs\n | (x1, x2) == (\"2\", \"3\") || (x1, x2) == (\"3\", \"2\") = loop a c b xs\n\nmain :: IO ()\nmain = do input <- readFile \"input.txt\"\n let ([i], xs) = splitAt 1 $ words input\n writeFile \"output.txt\" $ show $ test i xs"}, {"source_code": "main = do\n cont <- readFile \"input.txt\"\n writeFile \"output.txt\" $ f cont\n\nf str = (show $ f' first ops) ++ \"\\n\"\n where ls = lines str\n first = read $ head ls\n ops :: [(Int, Int)]\n ops = map (fu.words) $ tail ls\n fu (a:b:[]) = (read a, read b)\n fu x = error $ show x\n\nf' n [] = n\nf' n ((a,b):xs)\n | n == a = f' b xs\n | n == b = f' a xs\n | otherwise = f' n xs\n"}], "negative_code": [], "src_uid": "88e6651e1b0481d711e89c8071be1edf"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Arrow ((&&&), (***))\r\nimport Control.Monad.Trans.State\r\nimport Data.Bifunctor (bimap)\r\nimport Data.Function (on)\r\nimport Data.Maybe\r\nimport Data.Semigroup (Min(..))\r\nimport Data.Tuple (swap)\r\nimport qualified Data.Set as Set\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\nimport Debug.Trace\r\n\r\ntype Cost = Maybe (Min Int)\r\ntype Range = (Int, Int)\r\ntype Pos = (Range, Maybe Int, (Cost, Cost))\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n,m] <- getInts 2\r\n ps <- Set.fromList <$> getInts n\r\n rs <- fmap concat $ replicateM m $ do\r\n ~[l, r] <- getInts 2\r\n pure $! do\r\n guard $! Set.null\r\n $ Set.takeWhileAntitone (<=r)\r\n $ Set.dropWhileAntitone ( Range -> Set.Set Range\r\n excludeCover s x@(l, r) =\r\n if Set.null $ Set.dropWhileAntitone (( [(Set.Set Range, Set.Set Range)]\r\n run s = let s0 = (s, Set.empty)\r\n in go s0\r\n where\r\n go s'@(sl, sr) = s':case Set.maxView sl of\r\n Just (v, sl') -> go (sl', Set.insert v sr)\r\n _ -> []\r\n getBest :: (Int, Int) -> Int -> Set.Set Range -> Int -> (Int, Int)\r\n getBest (c1, c2) l s r = foldl1' (\\(x1, y1) (x2,y2)->(min x1 x2, min y1 y2)) $ map step $ run s\r\n where\r\n gol sl = case Set.lookupMax sl of\r\n Just (l', _) -> let dl = l' - l in min (c1 + 2 * dl) (c2 + dl)\r\n otherwise -> min c1 c2\r\n gor cl sr = case Set.lookupMin sr of\r\n Just (_, r') -> let dr = r - r' in (cl + dr, cl + 2 * dr)\r\n otherwise -> (cl, cl)\r\n step (sl, sr) = let cl = gol sl in gor cl sr\r\n best =\r\n let\r\n Just (a0, ps') = Set.minView ps\r\n s0 = case Set.lookupMin rs' of\r\n Just (_, r0) -> if r0 < a0 then (a0 - r0, 2 * (a0 - r0)) else (0, 0)\r\n _ -> (0,0)\r\n step (l, s) r = let\r\n ss' = Set.takeWhileAntitone ((<=r).snd) $ Set.dropWhileAntitone ((<=l).snd) $ rs'\r\n in (r, getBest s l ss' r)\r\n (lastl, (lastcl, lastcr)) = Set.foldl' step (a0, s0) ps'\r\n in case Set.lookupMax rs' of\r\n Just (maxl, _) -> if maxl <= lastl\r\n then min lastcl lastcr\r\n else let\r\n dl = maxl - lastl\r\n in min (lastcl + 2 * dl) (lastcr + dl)\r\n _ -> 0\r\n pure $! putInts [best]\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\n\nsuffMins :: UArray Int Int -> UArray Int Int\nsuffMins arr = let\n (p, q) = bounds arr\n step (ix, val) = (ix - 1, min val (arr ! (ix - 1)))\n in array (p, q + 1) $ take (rangeSize (p, q + 1))\n $ iterate step (q + 1, maxBound)\n\nbinSearch :: Integral t => (t -> Bool) -> t -> t -> t\nbinSearch fun = let\n go li ri = if li == ri\n then li\n else let\n mi = li + quot (ri - li) 2\n in if fun mi\n then go li mi\n else go (mi+1) ri\n in go\n\ntype UA = UArray Int Int\ndata Info = Info !Int64 !Int64 deriving (Eq, Ord, Show)\n\ngetCost :: Info -> Int -> Int -> Int64\ngetCost (Info c2 c1) pos tarPos = let\n rdist = fromIntegral $ tarPos - pos\n in if rdist <= 0\n then c2\n else min (c2 + 2 * rdist) (c1 + rdist)\n\nsolve :: UA -> UA -> UA -> Int64\nsolve as startPts necessities = let\n (1, n) = bounds as\n (_, stopPt) = bounds necessities\n leftPos = as ! 1\n leftTar = necessities ! 1\n leftDist = fromIntegral $ max 0 $ leftPos - leftTar\n startInfo = Info leftDist $ 2 * leftDist\n step :: Info -> Int -> Info\n step prevInfo ix = let\n oldPos = as ! (ix - 1)\n newPos = as ! ix\n oldRix = binSearch (\\j -> startPts ! j > oldPos) 1 stopPt\n newRix = binSearch (\\j -> startPts ! j > newPos) 1 stopPt\n newC !k = foldl' min maxBound $ do\n let\n leftOpts = oldPos : map (startPts !) [oldRix .. newRix - 1]\n rightOpts = map (necessities !) [oldRix .. newRix]\n (ltar, rtar) <- zip leftOpts rightOpts\n pure $ getCost prevInfo oldPos ltar\n + k * fromIntegral (newPos - min newPos rtar)\n in Info (newC 1) (newC 2)\n finalInfo = foldl' step startInfo [2 .. n]\n in getCost finalInfo (as ! n) (startPts ! (stopPt - 1))\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n aLi <- getInts n\n lr <- replicateM m $ do\n ~[lj, rj] <- getInts 2\n lj `seq` rj `seq` pure (lj, rj)\n let\n intArr :: Array Int (Int, Int)\n intArr = listArray (1, m) $ sort lr\n startPts = listArray (1, m) $ map fst $ elems intArr\n necessity = suffMins $ listArray (1, m) $ map snd $ elems intArr\n a = listArray (1, n) $ sort aLi\n pure $ putInt64s [solve a startPts necessity]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, m] <- readInts\r\n as <- readInts\r\n lrs <- replicateM m readInts\r\n let veryLeft = -10^9 - 1 :: Int64\r\n big = 10^16 :: Int64\r\n\r\n a :: Array Int Int64\r\n a = listArray (0, n) $ (veryLeft:) $ map fromIntegral $ sort as\r\n\r\n b :: Array Int [(Int64, Int64)]\r\n b = accumArray (flip (:)) [] (0, n) lrs' where\r\n lrs' = mapMaybe (f . map fromIntegral) $ reverse $ sort lrs\r\n f ~[l, r]\r\n | i <= n && a!i <= r = Nothing\r\n | otherwise = Just (i - 1, (l, r))\r\n where i = binSearchA (>=l) a\r\n sz = listArray (0, n) $ map length $ elems b\r\n\r\n la :: Array Int (Array Int Int64)\r\n la = listArray (0, n) $\r\n [ listArray (1, sz!i) $ map (fromIntegral . fst) lrs\r\n | (i, lrs) <- assocs b\r\n ]\r\n rmin :: Array Int [Int64]\r\n rmin = listArray (0, n) $\r\n [ scanr1 min $ map (fromIntegral . snd) lrs\r\n | (i, lrs) <- assocs b\r\n ]\r\n\r\n dp :: Array Int [Int64]\r\n dp = fArray (0, n) f where\r\n f 0 = take (1 + sz!0) $ 0 : repeat big\r\n f i = map g [0..sz!i] where\r\n (rminPrv, szPrv, dpPrv) = (rmin!(i - 1), sz!(i - 1), dp!(i - 1))\r\n pre = listArray (0, szPrv - 1) $ scanl1 min $ zipWith (-) dpPrv rminPrv\r\n suf = listArray (0, szPrv - 1) $ scanr1 min $ zipWith (-) dpPrv $ map (*2) rminPrv\r\n (rminaPrv, dpaPrv) = (listArray (1, szPrv) rminPrv, listArray (0, szPrv) dpPrv)\r\n g 0 = minimum $ dpaPrv!szPrv : [a!i + dx - rx | (dx, rx) <- zip dpPrv rminPrv]\r\n g j = onlyRight `min` left `min` right where\r\n onlyRight = la!i!j - a!i + dpaPrv!szPrv\r\n rightFirst k = 2 * la!i!j - a!i - rminaPrv!(k + 1)\r\n leftFirst k = a!i + la!i!j - 2 * rminaPrv!(k + 1)\r\n k = binSearch (\\k -> leftFirst k < rightFirst k) 0 (szPrv - 1)\r\n right | k - 1 < 0 = big\r\n | otherwise = pre!(k - 1) + 2 * la!i!j - a!i\r\n left | szPrv - 1 < k = big\r\n | otherwise = suf!k + a!i + la!i!j\r\n\r\n print $ last $ dp!n\r\n\r\nbinSearch :: Integral i => (i -> Bool) -> i -> i -> i\r\nbinSearch f = go where\r\n go l h\r\n | l > h = l\r\n | f m = go l (m - 1)\r\n | otherwise = go (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l h where (l, h) = bounds a\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, m] <- readInts\r\n as <- readInts\r\n lrs <- replicateM m readInts\r\n let veryLeft = -10^9 - 1 :: Int64\r\n big = 10^16 :: Int64\r\n\r\n a :: Array Int Int64\r\n a = listArray (0, n) $ (veryLeft:) $ map fromIntegral $ sort as\r\n\r\n b :: Array Int [(Int64, Int64)]\r\n b = accumArray (flip (:)) [] (0, n) lrs' where\r\n lrs' = mapMaybe (f . map fromIntegral) $ reverse $ sort lrs\r\n f ~[l, r]\r\n | i <= n && a!i <= r = Nothing\r\n | otherwise = Just (i - 1, (l, r))\r\n where i = binSearchA (>=l) a\r\n sz = listArray (0, n) $ map length $ elems b\r\n\r\n la :: Array Int (Array Int Int64)\r\n la = listArray (0, n) $\r\n [ listArray (1, sz!i) $ map (fromIntegral . fst) lrs\r\n | (i, lrs) <- assocs b\r\n ]\r\n rmin :: Array Int [Int64]\r\n rmin = listArray (0, n) $\r\n [ scanr1 min $ map (fromIntegral . snd) lrs\r\n | (i, lrs) <- assocs b\r\n ]\r\n\r\n stepDp :: [Int64] -> Int -> [Int64]\r\n stepDp dpPrv i = map f [0..sz!i] where\r\n (rminPrv, szPrv) = (rmin!(i - 1), sz!(i - 1))\r\n pre = listArray (0, szPrv - 1) $ scanl1 min $ zipWith (-) dpPrv rminPrv\r\n suf = listArray (0, szPrv - 1) $ scanr1 min $ zipWith (-) dpPrv $ map (*2) rminPrv\r\n (rminaPrv, dpaPrv) = (listArray (1, szPrv) rminPrv, listArray (0, szPrv) dpPrv)\r\n f 0 = minimum $ dpaPrv!szPrv : [a!i + dx - rx | (dx, rx) <- zip dpPrv rminPrv]\r\n f j = onlyRight `min` left `min` right where\r\n onlyRight = la!i!j - a!i + dpaPrv!szPrv\r\n rightFirst k = 2 * la!i!j - a!i - rminaPrv!(k + 1)\r\n leftFirst k = a!i + la!i!j - 2 * rminaPrv!(k + 1)\r\n k = binSearch (\\k -> leftFirst k < rightFirst k) 0 (szPrv - 1)\r\n right | k - 1 < 0 = big\r\n | otherwise = pre!(k - 1) + 2 * la!i!j - a!i\r\n left | szPrv - 1 < k = big\r\n | otherwise = suf!k + a!i + la!i!j\r\n\r\n print $ last $ foldl' stepDp (take (1 + sz!0) $ 0 : repeat big) [1..n]\r\n\r\nbinSearch :: Integral i => (i -> Bool) -> i -> i -> i\r\nbinSearch f = go where\r\n go l h\r\n | l > h = l\r\n | f m = go l (m - 1)\r\n | otherwise = go (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l h where (l, h) = bounds a\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n"}], "negative_code": [], "src_uid": "780a75568aea37889f10302d9e5d08c6"} {"source_code": "import Control.Monad\nimport Text.Printf\n\ng :: Double -> Double\ng x = x - fromIntegral (floor x)\n\ndelta = foldl (\\acc x -> acc + (g x)) 0.0\n\nfracs = length . filter (\\x -> g x > 0)\n\niter del = foldl (\\acc x -> min acc (abs (fromIntegral(x)-del))) (read \"Infinity\")\n\nlimits n xs = let count = fracs xs in\n if (count >= n) then (count-n, n) else (0, count)\n\nans n xs = iter (delta xs) ys\n where ys = [fst(limits n xs)..snd(limits n xs)]\n\nmain = do\n n <- readLn :: IO Int\n x <- getLine\n let xs = map read $ words x :: [Double]\n printf \"%.3f\" (ans n xs)\n \n \n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLine\n as <- readsLine\n printf \"%.3f\\n\" $ solve n as\n\nsolve :: Int -> [Double] -> Double\nsolve n as = minimum [ abs $ itof z - y | z <- [max 0 (n-k)..n]]\n where\n as' = map (\\x -> x - itof (floor x)) as\n k = length $ filter (==0) as'\n y = sum as'\n\n\n"}, {"source_code": "import Control.Monad\nimport Text.Printf\n\ng :: Double -> Double\ng x = x - fromIntegral (floor x)\n\ndelta = foldl (\\acc x -> acc + (g x)) 0.0\n\nfracs = foldl (\\acc x -> if (g x > 0.0001) then (acc + 1) else acc) 0\n\niter del = foldl (\\acc x -> min acc (abs (fromIntegral(x)-del))) (read \"Infinity\")\n\nlimits n xs = let count = fracs xs in\n if (count >= n) then (count-n, n) else (0, count)\n\nans n xs = iter (delta xs) ys\n where ys = [fst(limits n xs)..snd(limits n xs)]\n\nmain = do\n n <- readLn :: IO Int\n x <- getLine\n let xs = map read $ words x :: [Double]\n printf \"%.3f\" (ans n xs)\n \n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLine\n as <- readsLine\n printf \"%.3f\\n\" $ solve n as\n\nsolve :: Int -> [Double] -> Double\nsolve n as | even k = abs y \n | odd k = min (abs y) (abs (1+y))\n where\n as' = map (\\x -> x - itof (floor x)) as\n k = length $ filter (/=0) as'\n y = itof (div k 2) - sum as'\n\n\n"}], "src_uid": "f84b7122ffc7f585fd4ac8f1b3ef977a"} {"source_code": "{-# LANGUAGE NumericUnderscores #-}\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n\nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\r\\n\\t\")\n \nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\nreadInt :: BS.ByteString -> Int\nreadInt line = let [x] = readInts line in x\n\ndata Node = Null | Node { leftBound :: Int, rightBound :: Int, sum :: Int, leftChild :: Node, rightChild :: Node }\n deriving (Show, Eq)\n\nisLeaf :: Node -> Bool\nisLeaf node = leftBound node == rightBound node\n\nmiddle :: Node -> Int\nmiddle node = (leftBound node + rightBound node) `div` 2\n\ninside :: Node -> Int -> Bool\ninside node pos = leftBound node <= pos && pos <= rightBound node\n\nensureLeftChild :: Node -> Node\nensureLeftChild node | isLeaf node = node\n | leftChild node == Null = Node (leftBound node) (rightBound node) (Main.sum node) (makeLeftChild node) (rightChild node)\n | otherwise = node\n where makeLeftChild :: Node -> Node\n makeLeftChild node = Node (leftBound node) (middle node) 0 Null Null\n\nensureRightChild :: Node -> Node\nensureRightChild node | isLeaf node = node\n | rightChild node == Null = Node (leftBound node) (rightBound node) (Main.sum node) (leftChild node) (makeRightChild node)\n | otherwise = node\n where makeRightChild :: Node -> Node\n makeRightChild node = Node (middle node + 1) (rightBound node) 0 Null Null\n\nemptyRoot :: Node\nemptyRoot = Node 0 1_000_000_000 0 Null Null\n\nincrement :: Int -> Node -> Node\nincrement position node | isLeaf node = makeNode Null Null\n | position <= middle node = let node' = ensureLeftChild node\n in makeNode (increment position (leftChild node')) (rightChild node')\n | otherwise = let node' = ensureRightChild node\n in makeNode (leftChild node') (increment position (rightChild node'))\n where makeNode = Node (leftBound node) (rightBound node) (Main.sum node + 1)\n\ngetSum :: Int -> Int -> Node -> Int\ngetSum l r Null = 0\ngetSum l r node | l > r = 0\n | l <= leftBound node && rightBound node <= r = Main.sum node\n | r < leftBound node || rightBound node < l = 0\n | otherwise = getSum l r (leftChild node) + getSum l r (rightChild node)\n\nsolve :: [Int] -> Int\nsolve = go emptyRoot 1\n where go :: Node -> Int -> [Int] -> Int\n go node _ [] = 0\n go node i (x:xs) = if x < i\n then let node' = increment i node in (getSum 0 (x - 1) node') + go node' (i + 1) xs\n else go node (i + 1) xs\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- readInt <$> BS.getLine\n a <- readInts <$> BS.getLine\n print (solve a)\n \nmain :: IO ()\nmain = do t <- readInt <$> BS.getLine\n forM_ [1 .. t] testCaseMain\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe, catMaybes)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.String (fromString)\nimport Data.Bits (shift)\nimport Data.Binary (encode, decode)\n\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = [Int]\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ show xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n return xs\n\n-- eliminate duplicate\ncal :: Int -> Int\ncal n = (n-1) * n `div` 2\n\nsolve :: Solver\nsolve xs = ans - beta\n where ys = sort $ filter (\\(x, y)-> x < y) $ zip xs [1..]\n ans = fst $ foldl insertCount (0, Set.empty) ys\n insertCount :: (Int, Set Int) -> (Int, Int) -> (Int, Set Int)\n insertCount (c, s) (a, i) = (Set.findIndex a (Set.insert a s) + c, Set.insert i s)\n beta = 0\n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "import Data.List\r\nimport qualified Data.Char as DC\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map as Map\r\nimport Control.Monad (replicateM)\r\n\r\ntSecond (_, z, _) = z\r\ntFirst (o, _, _) = o\r\ntThird (_, _, v) = v\r\n\r\nmapLookup e m = unwrap $ Map.lookup e m\r\nunwrap (Just x) = x\r\nunwrap Nothing = 0\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n n <- fmap (read :: String -> Int) getLine\r\n rarr <- fmap (map (read :: String -> Int) . words) getLine\r\n putStrLn $ show $ tSecond $ foldl (\\tp el -> if (fst el) > (snd el) then (Set.insert (fst el) (tFirst tp), (tSecond tp) + (Set.findIndex (mapLookup ((snd el) - 1) (tThird tp)) (tFirst tp)), Map.insert (fst el) (fst el) (tThird tp)) else ((tFirst tp), (tSecond tp), Map.insert (fst el) (mapLookup (fst el - 1) (tThird tp)) (tThird tp) )) (Set.singleton 0, 0, Map.singleton 0 0) $ zip [1..n] rarr\r\n \r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map as Map\r\n\r\ncount :: [Int] -> Int -> [Int]\r\ncount [] i = []\r\ncount (x:xs) i = (if x <= i then 1 else 0) : (count xs $ i + 1)\r\ncount' arr = count arr 0\r\n\r\npref :: [Int] -> Int -> [Int]\r\npref [] prev = []\r\npref (x:xs) prev = (x + prev) : (pref xs (x + prev))\r\npref' arr = pref arr 0\r\n\r\nfromJust Nothing = 0\r\nfromJust (Just x) = x\r\n\r\nsolve :: [Int] -> Int -> Int\r\nsolve arr n =\r\n sum $ map (\\(i, b) -> (fromJust $ Map.lookup (i-2) cnt) * b)\r\n $ filter (\\(i, b) -> 1 < i && i < n)\r\n $ zip tl (count tl 1)\r\n where\r\n tl = tail arr\r\n cntArr = pref' $ count' arr\r\n cnt = Map.fromList $ zip [0..(n-1)] cntArr\r\n\r\ntestcase 0 = return ()\r\ntestcase t = do\r\n n <- readLn :: IO Int\r\n arr <- map (read :: String -> Int) <$> words <$> getLine\r\n putStrLn $ show $ solve arr n\r\n testcase (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n testcase t\r\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map as Map\r\n\r\ncount :: [Int] -> Int -> [Int]\r\ncount [] i = []\r\ncount (x:xs) i = (if x <= i then 1 else 0) : (count xs $ i + 1)\r\ncount' arr = count arr 0\r\n\r\npref :: [Int] -> Int -> [Int]\r\npref [] prev = []\r\npref (x:xs) prev = (x + prev) : (pref xs (x + prev))\r\npref' arr = pref arr 0\r\n\r\nfromJust Nothing = 0\r\nfromJust (Just x) = x\r\n\r\nsolve :: [Int] -> Int -> Int\r\nsolve arr n =\r\n sum $ map (\\(i, b) -> (fromJust $ Map.lookup (i-2) cnt) * b)\r\n $ filter (\\(i, b) -> 1 < i && i < n)\r\n $ zip tl (count tl 1)\r\n where\r\n tl = tail arr\r\n cntArr = pref' $ count' arr\r\n cnt = Map.fromList $ zip [0..(n-1)] cntArr\r\n\r\ntestcase 0 = return ()\r\ntestcase t = do\r\n n <- readLn :: IO Int\r\n arr <- map (read :: String -> Int) <$> words <$> getLine\r\n putStrLn $ show $ (solve arr n) `mod` 1000000007\r\n testcase (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n testcase t\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Set as Set\r\n\r\ncount :: [Int] -> Int -> [Int]\r\ncount [] i = []\r\ncount (x:xs) i = (if x <= i then 1 else 0) : (count xs $ i + 1)\r\ncount' arr = count arr 0\r\n\r\npref :: [Int] -> Int -> [Int]\r\npref [] prev = []\r\npref (x:xs) prev = (x + prev) : (pref xs (x + prev))\r\npref' arr = pref arr 0\r\n\r\nsolve :: [Int] -> Int -> Int\r\nsolve arr n =\r\n sum $ map (\\(i, b) -> if 1 < i && i < n then cnt !! (i-2) * b else 0) $ zip tl (count tl 1)\r\n where\r\n tl = tail arr\r\n cnt = pref' $ count' arr\r\n\r\ntestcase 0 = return ()\r\ntestcase t = do\r\n n <- readLn :: IO Int\r\n arr <- map (read :: String -> Int) <$> words <$> getLine\r\n putStrLn $ show arr\r\n putStrLn $ show $ count arr 0\r\n putStrLn $ show $ pref (count arr 0) 0\r\n putStrLn $ show $ (solve arr n) `mod` 1000000007\r\n testcase (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n testcase t\r\n"}], "src_uid": "89768e4c832428b534cae3acbf379c44"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as LC\r\nimport qualified Data.ByteString as P\r\nimport Data.Maybe (fromJust)\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad.State ()\r\n\r\nmain :: IO ()\r\nmain = getLine >> LC.getContents\r\n >>= mapM_ ((\\(a, b) -> putStr (show a) >> putStrLn (' ':show b)) . solve)\r\n . ints\r\n . LC.lines\r\n\r\nints :: [LC.ByteString] -> [Int]\r\nints !str = fst . fromJust . LC.readInt <$> str\r\n\r\nsolve :: Int -> (Int, Int)\r\nsolve !p = (2, p - 1)", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n \r\nimport qualified Data.ByteString.Lazy.Char8 as LC\r\nimport qualified Data.ByteString as P\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.State ( replicateM_ )\r\n \r\nmain :: IO ()\r\nmain = do\r\n !t <- readLn\r\n replicateM_ t\r\n $ do\r\n !p <- getLine\r\n let b=let n=read p::Int in show (n-1)\r\n putStrLn $ '2':' ':b \r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n \r\nimport qualified Data.ByteString.Lazy.Char8 as LC\r\nimport qualified Data.ByteString as P\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.State ( replicateM_ )\r\n \r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t\r\n $ do\r\n p <- getLine\r\n let (a, b) = (\"2\",let n=read p::Int in show (n-1))\r\n putStrLn $ a ++ (' ':b) \r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as LC\r\nimport qualified Data.ByteString as P\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.State ( replicateM_ )\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t\r\n $ do\r\n p <- readLn\r\n let (a, b) = solve p\r\n putStr $ show a\r\n putStrLn $ ' ':show b\r\n\r\nints :: [LC.ByteString] -> [Int]\r\nints !str = fst . fromJust . LC.readInt <$> str\r\n\r\nsolve :: Int -> (Int, Int)\r\nsolve !p = (2, p - 1)"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as LC\r\nimport qualified Data.ByteString as P\r\nimport Data.Maybe (fromJust)\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad.State ()\r\n\r\nmain :: IO ()\r\nmain = getLine >> LC.getContents\r\n >>= mapM_ ((\\(a, b) -> putStr (show a) >> putStrLn (' ':show b)) . solve)\r\n . ints\r\n . LC.lines\r\n\r\nints :: [LC.ByteString] -> [Int]\r\nints str = fst . fromJust . LC.readInt <$> str\r\n\r\nsolve :: Int -> (Int, Int)\r\nsolve p = (2, p - 1)"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as LC\r\nimport qualified Data.ByteString as P\r\nimport Data.Maybe (fromJust)\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad.State ()\r\n\r\nmain :: IO ()\r\nmain = getLine >> LC.getContents\r\n >>= mapM_ ((\\[a, b] -> putStr (show a) >> putStrLn (' ':show b)) . solve)\r\n . ints\r\n . LC.lines\r\n\r\nints :: [LC.ByteString] -> [Int]\r\nints str = fst . fromJust . LC.readInt <$> str\r\n\r\nsolve :: Int -> [Int]\r\nsolve p = [2, p - 1]"}, {"source_code": "import Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t subMain\r\n\r\nsubMain = do\r\n p <- readLn :: IO Int\r\n putStrLn $ \"2 \" ++ show (p - 1)"}, {"source_code": "module Main where\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n mapM_ subMain [1,2 .. t]\r\n\r\nsubMain :: Int -> IO ()\r\nsubMain test = do\r\n p <- readLn :: IO Int\r\n putStrLn (\"2 \" ++ show (p - 1))"}, {"source_code": "main = do\r\n t <- read <$> getLine :: IO Int\r\n mapM_ solve [1..t]\r\n\r\nsolve :: Int -> IO ()\r\nsolve _ = do\r\n n <- read <$> getLine :: IO Int\r\n putStrLn $ show ((n - 1) `quot` 2) ++ \" \" ++ show (n - 1)"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n words\n >>> drop 1\n >>> map (read >>> subtract 1 >>> show >>> (\"2 \" ++))\n >>> unlines\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve 5 = [2,4]\r\nsolve x = [2,b] where b = div x 2\r\n\r\nprintResult = do\r\n p <- readLn :: IO Int\r\n putStrLn . unwords . map show $ solve p\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "negative_code": [], "src_uid": "259e39c9e63e43678e596c0d8c66937c"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\ntype IMap = IOUArray (Int,Int) Bool\n-- type IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\ngo :: IMap -> Int -> Int -> [[Char]] -> IO ()\ngo arr 0 n [] = return ()\ngo arr m n (x:xs) = do\n sequence_ [writeArray arr (n, j) b | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) x [0..m-1], b]\n go arr (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n arr <- newArray ((1,1), (n, n)) False\n xss <- replicateM n getLine\n go arr n 1 xss\n return $ (n, arr)\n\n\nfindM :: (a -> IO Bool) -> [a] -> IO (Maybe a)\nfindM f [] = return Nothing\nfindM f (x:xs) = liftM3 bool (findM f xs) (return (Just x)) (f x)\n\n-- chunks to maximum connected component\nchucks :: IMap -> Int -> Int -> IO [(Int, Int)]\nchucks m l r = \n maybe (return []) (\\r0 -> ((l, r0) :) <$> chucks m (r0+1) r) \n =<< findM ((readArray m) . (l,)) (reverse [l..r])\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\n\n-- chunks sub maximum connected part\n-- try to join maximum connected part to the root\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = \n do\n idxx <- chucks m (l+1) r\n foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = do\n solve1 m l0 r0 \n res <- findM ((readArray m) . (l,)) ([l0..r])\n -- get the first possible connect component from l to (l0, r0, r)\n case res of\n Just i -> case (i > r0, b) of\n -- (l0, r0, i, r)\n -- (l, r0) is not connected while (l, l0-1), \n -- (l0, r0) must be connected to l through i (or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis (l0, r0 is maximum)\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible: At least (l, r) is connected by chucks\"\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\ntype IMap = IOUArray (Int,Int) Bool\n-- type IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\ngo :: IMap -> Int -> [[Char]] -> IO ()\ngo arr n [] = return ()\ngo arr n (x:xs) = do\n sequence_ [writeArray arr (n, j) b | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n go arr (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n arr <- newArray ((1,1), (n, n)) False\n xss <- replicateM n getLine\n go arr 1 xss\n return $ (n, arr)\n\n\nfindM :: (a -> IO Bool) -> [a] -> IO (Maybe a)\nfindM f [] = return Nothing\nfindM f (x:xs) = liftM3 bool (findM f xs) (return (Just x)) (f x)\n\n-- chunks to maximum connected component\nchucks :: IMap -> Int -> Int -> IO [(Int, Int)]\nchucks m l r = \n maybe (return []) (\\r0 -> ((l, r0) :) <$> chucks m (r0+1) r) \n =<< findM ((readArray m) . (l,)) (reverse [l..r])\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\n\n-- chunks sub maximum connected part\n-- try to join maximum connected part to the root\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = \n do\n idxx <- chucks m (l+1) r\n foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = do\n solve1 m l0 r0 \n res <- findM ((readArray m) . (l,)) ([l0..r])\n -- get the first possible connect component from l to (l0, r0, r)\n case res of\n Just i -> case (i > r0, b) of\n -- (l0, r0, i, r)\n -- (l, r0) is not connected while (l, l0-1), \n -- (l0, r0) must be connected to l through i (or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis (l0, r0 is maximum)\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible: At least (l, r) is connected by chucks\"\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\ntype IMap = IOUArray (Int,Int) Bool\n-- type IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\ngo :: IMap -> Int -> Int -> [[Char]] -> IO ()\ngo arr 0 n [] = return ()\ngo arr m n (x:xs) = do\n sequence_ [writeArray arr (n, j) b | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..m-1], b]\n go arr (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n arr <- newArray ((1,1), (n, n)) False\n xss <- replicateM n getLine\n go arr n 1 xss\n return $ (n, arr)\n\n\nfindM :: (a -> IO Bool) -> [a] -> IO (Maybe a)\nfindM f [] = return Nothing\nfindM f (x:xs) = liftM3 bool (findM f xs) (return (Just x)) (f x)\n\n-- chunks to maximum connected component\nchucks :: IMap -> Int -> Int -> IO [(Int, Int)]\nchucks m l r = \n maybe (return []) (\\r0 -> ((l, r0) :) <$> chucks m (r0+1) r) \n =<< findM ((readArray m) . (l,)) (reverse [l..r])\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\n\n-- chunks sub maximum connected part\n-- try to join maximum connected part to the root\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = \n do\n idxx <- chucks m (l+1) r\n foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = do\n solve1 m l0 r0 \n res <- findM ((readArray m) . (l,)) ([l0..r])\n -- get the first possible connect component from l to (l0, r0, r)\n case res of\n Just i -> case (i > r0, b) of\n -- (l0, r0, i, r)\n -- (l, r0) is not connected while (l, l0-1), \n -- (l0, r0) must be connected to l through i (or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis (l0, r0 is maximum)\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible: At least (l, r) is connected by chucks\"\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\ntype IMap = IOUArray (Int,Int) Bool\n-- type IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\ngo :: IMap -> Int -> Int -> [[Char]] -> IO ()\ngo arr 0 n [] = return ()\ngo arr m n (x:xs) = do\n sequence_ [writeArray arr (n, j) b | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) x [0..m-1], b]\n go arr (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n arr <- newArray ((1,1), (n, n)) False\n xss <- replicateM n getLine\n go arr n 1 xss\n return $ (n, arr)\n\nfindM :: (a -> IO Bool) -> [a] -> IO (Maybe a)\nfindM f [] = return Nothing\nfindM f (x:xs) = do \n b <- f x \n if b then return (Just x) else findM f xs\n\n-- chunks to maximum connected component\nchucks :: IMap -> Int -> Int -> IO [(Int, Int)]\nchucks m l r = go m l\n where \n go m l = do\n res <- findM ((readArray m) . (l,)) (reverse [l..r])\n case res of\n Just r0 -> \n ((l, r0) :) <$> go m (r0+1)\n Nothing -> return []\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\n\n-- chunks sub maximum connected part\n-- try to join maximum connected part to the root\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = \n do\n idxx <- chucks m (l+1) r\n foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = do\n solve1 m l0 r0 \n res <- findM ((readArray m) . (l,)) ([l0..r])\n -- get the first possible connect component from l to (l0, r0, r)\n case res of\n Just i -> case (i > r0, b) of\n -- (l0, r0, i, r)\n -- (l, r0) is not connected while (l, l0-1), \n -- (l0, r0) must be connected to l through i (or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis (l0, r0 is maximum)\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible: At least (l, r) is connected by chucks\"\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> Int -> [[Char]] -> Set (Int, Int)\ngo 0 n [] = Set.empty\ngo m n (x:xs) = \n Set.fromList [(n,j) \n | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) \n x [0..m-1], b]\n `Set.union` go (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ assert (n==length xss) (n, go n 1 xss)\n\n-- chunks to maximum connected component\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = go m l\n where \n go m l = case find ((`Set.member` m) . (l,)) (reverse [l..r]) of\n Just r0 -> (l, r0):go m (r0+1)\n Nothing -> []\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\n\n-- chunks sub maximum connected part\n-- try to join maximum connected part to the root\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n -- get the first possible connect component from l to (l0, r0, r)\n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n -- (l0, r0, i, r)\n -- (l, r0) is not connected while (l, l0-1), \n -- (l0, r0) must be connected to l through i (or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis (l0, r0 is maximum)\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible: At least (l, r) is connected by chucks\"\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> Int -> [[Char]] -> Set (Int, Int)\ngo 0 n [] = Set.empty\ngo m n (x:xs) = \n Set.fromList [(n,j) \n | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) \n x [0..m-1], b]\n `Set.union` go (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ assert (n==length xss) (n, go n 1 xss)\n\n-- chunks to maximum connected component\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = \n case find ((`Set.member` m) . (l,)) (reverse [l..r]) of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub maximum connected part\n -- try to join maximum connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n -- get the first possible connect component from l to (l0, r0, r)\n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n -- (l0, r0, i, r)\n -- (l, r0) is not connected while (l, l0-1), \n -- (l0, r0) must be connected to l through i (or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis (l0, r0 is maximum)\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible: At least (l, r) is connected by chucks\"\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> Int -> [[Char]] -> Set (Int, Int)\ngo 0 n [] = Set.empty\ngo m n (x:xs) = \n Set.fromList [(n,j) \n | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) \n x [0..m-1], b]\n `Set.union` go (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ assert (n==length xss) (n, go n 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n -- (l, r0) is not connected while (l, l0-1) and (l0, i) do, \n -- (l0, r0) must be connected to l through i(or the component where i belong), \n -- (r0+1, i-1) must contains another maximum connected components or violate the hypothesis\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible\"\n\n-- try for the automatically generated if not fixed\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> Int -> [[Char]] -> Set (Int, Int)\ngo 0 n [] = Set.empty\ngo m n (x:xs) = \n Set.fromList [(n,j) \n | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) \n x [0..m-1], b]\n `Set.union` go (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ assert (n==length xss) (n, go n 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n -- (l, r0) is not connected while (l, l0-1) and (l0, i) do, \n -- (l0, r0) must be connected to l by i, (r0+1, i-1) must not be connected to i\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible\"\n\n-- try for the automatically generated if not fixed\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> Int -> [[Char]] -> Set (Int, Int)\ngo 0 n [] = Set.empty\ngo m n (x:xs) = \n Set.fromList [(n,j) \n | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) \n x [0..length x-1], b]\n `Set.union` go (m-1) (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ assert (n==length xss) (n, go n 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n -- (l, r0) is not connected while (l, l0-1) and (l0, i) do, \n -- (l0, r0) must be connected to l by i, (r0+1, i-1) must not be connected to i\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible\"\n\n-- try for the automatically generated if not fixed\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, case a of '1' -> True; '0'->False)) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ assert (n==length xss) (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n -- (l, r0) is not connected while (l, l0-1) and (l0, i) do, \n -- (l0, r0) must be connected to l by i, (r0+1, i-1) must not be connected to i\n (True, True) -> printResult (l0, i) >> return False\n -- (l, r0) is not connected and (l, l0-1) do not, just connect l0 to l\n (True, False) -> printResult (l, l0) >> return b\n -- (l, r0) is connected, reoriented (l0, r0) to i, connect i to l\n (False, _) -> printResult (l, i) >> return True\n Nothing -> error \"impossible\"\n\n-- try for the automatically generated if not fixed\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n -- b is wether already connected for (l, l0-1)\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b\n Nothing -> error \"impossible\"\n\n-- try for the automatically generated if not fixed\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (l0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b\n Nothing -> error \"impossible\"\n\n-- try for the automatically generated if not fixed\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n -- then we decide where to attach (l0, r0).\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b\n Nothing -> error \"impossible\"\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n f b (l0, r0) = solve1 m l0 r0 >> \n case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b)\n Nothing -> return b\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n -- find the right most part\n idxx = find ((`Set.member` m) . (l,)) $ reverse [l..r]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n -- chunks sub connected part\n -- try to join connected part to the root\n idxx = chucks m (l+1) r\n -- for each (l0, r0), we solve as sub problem\n f b (l0, r0) = solve1 m l0 r0 >> case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b )\n Nothing -> return b\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n idxx = find ((`Set.member` m) . (l,)) [r0 | r0 <- reverse [l..r]]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n f b (l0, r0) = case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b ) <* solve1 m l0 r0\n Nothing -> return b\n\nsolve :: Solver\nsolve (n, m) = solve1 m 1 n\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [1..length x], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 1 xss)\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n idxx = find ((`Set.member` m) . (l,)) [r0 | r0 <- reverse [l..r]]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show i ++ \" \" ++ show j\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n f b (l0, r0) = case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b ) <* solve1 m l0 r0\n Nothing -> return b\n\nsolve :: Solver\nsolve (n, m) = solve1 m 0 (n-1)\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 0 xss)\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n idxx = find ((`Set.member` m) . (l,)) [r0 | r0 <- reverse [l..r]]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show (i+1) ++ \" \" ++ show (j+1)\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n f b (l0, r0) = case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b ) <* solve1 m l0 r0\n Nothing -> return b\nsolve :: Solver\nsolve (n, m) = solve1 m 0 (n-1)\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 0 xss)\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n idxx = find ((`Set.member` m) . (l,)) [r0 | r0 <- reverse [l..r]]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show (i+1) ++ \" \" ++ show (j+1)\n\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n f b (l0, r0) = case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> solve1 m l0 r0 >> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b )\n Nothing -> return b\nsolve :: Solver\nsolve (n, m) = solve1 m 0 (n-1)\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\n\ntype IMap = Set (Int, Int) \ntype Domain = (Int, IMap)\ntype CoDomain = IO ()\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\n-- printAns :: CoDomain -> IO ()\n-- printAns = putStrLn . showResult\n\ngo :: Int -> [[Char]] -> Set (Int, Int)\ngo n [] = Set.empty\ngo n (x:xs) = \n Set.fromAscList [(n,j) | (j,b) <- zipWith (\\a m -> (m+n, a=='1')) x [0..length x-1], b]\n `Set.union` go (n+1) xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xss <- replicateM n getLine\n return $ (n, go 0 xss)\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\nchucks :: IMap -> Int -> Int -> [(Int, Int)]\nchucks m l r = case idxx of\n Just r0 -> (l, r0):chucks m (r0+1) r\n Nothing -> []\n where\n idxx = find ((`Set.member` m) . (l,)) [r0 | r0 <- reverse [l..r]]\n\nprintResult :: (Int ,Int) -> IO ()\nprintResult (i, j) = putStrLn $ show (i+1) ++ \" \" ++ show (j+1)\nsolve1 :: IMap -> Int -> Int -> IO ()\nsolve1 m l r = foldlM f True idxx >> return ()\n where \n idxx = chucks m (l+1) r\n f b (l0, r0) = case find ((`Set.member` m) . (l,)) [l0..r] of\n Just i -> solve1 m l0 r0 >> (case (i > r0, b) of\n (False, _) -> printResult (l, i) >> return True\n (True, True) -> printResult (r0, i) >> return False\n (True, False) -> printResult (l, l0) >> return b )\n Nothing -> return b\n \n\nsolve :: Solver\nsolve (n, m) = solve1 m 0 (n-1)\n\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n xs <- replicateM n $ solve <$> parse\n sequence_ xs\n return ()\n"}], "src_uid": "4393b6a482697df9cac2fa50e7124a77"} {"source_code": "\ntype Long = Int\n\n\n\n\nsolve :: Long -> Long -> IO ()\nsolve n s\n | n > (s `div` 2) = putStrLn \"NO\"\n | otherwise = do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ (s-n+1):replicate (n-1) 1\n print (s `div` 2)\n\nmain :: IO ()\nmain = do\n (n:s:_) <- readWords\n solve n s\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine", "positive_code": [{"source_code": "main = do\n (n:s:_) <- map read . words <$> getLine\n if s >= n * 2\n then do\n putStrLn \"YES\"\n putStrLn $ unwords . map show $ (s - n + 1) : replicate (n - 1) 1\n print $ div s 2\n else putStrLn \"NO\""}], "negative_code": [], "src_uid": "4a644d97824d29c42dbb48d79b9958fe"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [t] <- getInts 1\n replicateM_ t $ do\n [c, d] <- getInts 2\n let\n s = c - d\n w = c + d\n putInts . pure $ if odd s\n then 0-1\n else (if s == 0 then 0 else 1) + (if w == 0 then 0 else 1)\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> SIO ()\nputInts vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: Int -> Int -> Int\ncalc c d =\n let diff = abs (c-d) in\n if (diff == 0) && (c == 0) then 0\n else if diff == 0 then 1\n else if diff `mod` 2 == 1 then -1\n else 2\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [c,d] = map read $ words line :: [Int]\n putStrLn $ show $ calc c d\n"}, {"source_code": "module Main where\r\n\r\ntestCase :: Integer -> IO ()\r\ntestCase 0 = return ()\r\ntestCase n = do\r\n x <- getLine\r\n a <- return $ map (read :: String -> Integer) (words x)\r\n v1 <- return $ head a\r\n v2 <- return $ head $ tail a\r\n res <- return $\r\n if v1 == v2 then\r\n if v1 == 0 then 0\r\n else 1\r\n else\r\n if mod (v1 + v2) 2 == 0 then 2\r\n else -1\r\n print res\r\n testCase (n-1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n x <- getLine\r\n n <- return (read x :: Integer)\r\n testCase n\r\n"}, {"source_code": "main = do\n t <- read <$> getLine :: IO Int\n mapM_ main' [1..t]\n\nmain' :: Int -> IO ()\nmain' _ = do\n [a, b] <- map read . words <$> getLine :: IO [Int]\n print $ solve a b\n\nsolve :: Int -> Int -> Int\nsolve a b\n | a == 0 && b == 0 = 0\n | a == b = 1\n | even $ a + b = 2\n | otherwise = -1\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = (Int, Int)\ntype Output = Int\n\ninput :: Scanner Input\ninput = pair int int\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: Input -> Output\nsolve (0, 0) = 0\nsolve (x, y)\n | x == y = 1\n | even (x + y) = 2\nsolve _ = -1\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "8e7c0b703155dd9b90cda706d22525c9"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport qualified Data.List as L\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map fromIntegral.L.unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int64] -> Int64\nsolve 1 _ = 0\nsolve n xs = go res0 (tail left) [] right\n where\n !m = minimum xs\n !mm = maximum xs\n !res0 = (maximum left - minimum left) * (maximum right - minimum right)\n !sorted = L.sort xs\n (left, right) = splitAt n sorted\n go !res [] rs (x:xs) = go res (reverse rs) [] (x:xs)\n go !res (f:fs) rs (x:xs) = go (min res $ (mm - m) * (x - f)) fs (x:rs) xs\n go res _ _ [] = res\n", "positive_code": [{"source_code": "import System.IO\nimport Control.Applicative\nimport qualified Data.ByteString as B\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\nimport qualified Data.Text as T\nimport Data.Text.Read\nimport Data.Int\n{-import Data.Either.Unwrap-}\n{-sort = mergesort-}\n \nparseTextInt :: T.Text -> Integer\nparseTextInt txt = case decimal txt of\n Right (ans, _) -> ans\n _ -> error \"Bad int\"\n\nparseIntLine input line_idx = map (read ::String->Int) mywords\n where \n mylines = lines input !! line_idx\n mywords = words mylines \n\nparseIntLineText :: String -> Int -> [Integer]\nparseIntLineText input line_idx = map parseTextInt mywords\n where \n mylines = T.lines (T.pack input) !! line_idx\n mywords = T.words mylines \n\nsolve :: String -> String\n{-solve input = (show $ allAnswers n as) ++ \"\\n\" -}\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLineText input 1\n n = (fromIntegral $ parseIntLineText input 0 !! 0) :: Int\n\n\n\nanswer :: Int -> [Integer] -> Integer\nanswer n as = foldl min (answer1 n sas) $ allAnswers n sas \n where \n sas = sort as \n\n\nallAnswers :: Int -> [Integer] -> [Integer]\nallAnswers n sas = map (\\(a, b) -> fullBoundaries * (b - a)) $ zip (take (n+1) sas) (drop (n-1) sas) \n where \n fullBoundaries = getBoundaries sas\n\n\nanswer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n\n\n\n\ngetBoundaries as = (last as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n\nmergesort'merge :: (Ord a) => [a] -> [a] -> [a]\nmergesort'merge [] xs = xs\nmergesort'merge xs [] = xs\nmergesort'merge (x:xs) (y:ys)\n | (x < y) = x:mergesort'merge xs (y:ys)\n | otherwise = y:mergesort'merge (x:xs) ys\n \nmergesort'splitinhalf :: [a] -> ([a], [a])\nmergesort'splitinhalf xs = (take n xs, drop n xs)\n where n = (length xs) `div` 2 \n \nmergesort :: (Ord a) => [a] -> [a]\nmergesort xs \n | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)\n | otherwise = xs\n where (ls, rs) = mergesort'splitinhalf xs\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport qualified Data.List as L\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map fromIntegral.L.unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int64] -> Int64\nsolve n xs = (maximum left - minimum left) * (maximum right - minimum right)\n where\n (left, right) = splitAt n $ L.sort xs\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport qualified Data.ByteString as B\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\nimport qualified Data.Text as T\nimport Data.Text.Read\n{-import Data.Either.Unwrap-}\n{-sort = mergesort-}\n \nparseTextInt :: T.Text -> Int\nparseTextInt txt = case decimal txt of\n Right (ans, _) -> ans\n _ -> 0\n\nparseIntLine input line_idx = map (read ::String->Int) mywords\n where \n mylines = lines input !! line_idx\n mywords = words mylines \n\nparseIntLineText input line_idx = map parseTextInt mywords\n where \n mylines = T.lines (T.pack input) !! line_idx\n mywords = T.words mylines \n\nsolve :: String -> String\n{-solve input = (show $ allAnswers n as) ++ \"\\n\" -}\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLineText input 1\n n = parseIntLineText input 0 !! 0\n\n\n\nanswer :: Int -> [Int] -> Int\nanswer n as = foldl min (answer1 n sas) $! allAnswers n sas \n where \n sas = sort as \n\n\nallAnswers :: Int -> [Int] -> [Int]\nallAnswers n sas = map (\\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas) \n where \n fullBoundaries = getBoundaries sas\n\n\nanswer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n\n\n\n\ngetBoundaries as = (last as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n\nmergesort'merge :: (Ord a) => [a] -> [a] -> [a]\nmergesort'merge [] xs = xs\nmergesort'merge xs [] = xs\nmergesort'merge (x:xs) (y:ys)\n | (x < y) = x:mergesort'merge xs (y:ys)\n | otherwise = y:mergesort'merge (x:xs) ys\n \nmergesort'splitinhalf :: [a] -> ([a], [a])\nmergesort'splitinhalf xs = (take n xs, drop n xs)\n where n = (length xs) `div` 2 \n \nmergesort :: (Ord a) => [a] -> [a]\nmergesort xs \n | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)\n | otherwise = xs\n where (ls, rs) = mergesort'splitinhalf xs\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport qualified Data.ByteString as B\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\nimport qualified Data.Text as T\nimport Data.Text.Read\nimport Data.Int\n{-import Data.Either.Unwrap-}\n{-sort = mergesort-}\n \nparseTextInt :: T.Text -> Integer\nparseTextInt txt = case decimal txt of\n Right (ans, _) -> ans\n _ -> error \"Bad int\"\n\nparseIntLine input line_idx = map (read ::String->Int) mywords\n where \n mylines = lines input !! line_idx\n mywords = words mylines \n\nparseIntLineText :: String -> Int -> [Integer]\nparseIntLineText input line_idx = map parseTextInt mywords\n where \n mylines = T.lines (T.pack input) !! line_idx\n mywords = T.words mylines \n\nsolve :: String -> String\n{-solve input = (show $ allAnswers n as) ++ \"\\n\" -}\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLineText input 1\n n = (fromIntegral $ parseIntLineText input 0 !! 0) :: Int\n\n\n\nanswer :: Int -> [Integer] -> Integer\nanswer n as = foldl min (answer1 n sas) $ allAnswers n sas \n where \n sas = sort as \n\n\nallAnswers :: Int -> [Integer] -> [Integer]\nallAnswers n sas = map (\\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas) \n where \n fullBoundaries = getBoundaries sas\n\n\nanswer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n\n\n\n\ngetBoundaries as = (last as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n\nmergesort'merge :: (Ord a) => [a] -> [a] -> [a]\nmergesort'merge [] xs = xs\nmergesort'merge xs [] = xs\nmergesort'merge (x:xs) (y:ys)\n | (x < y) = x:mergesort'merge xs (y:ys)\n | otherwise = y:mergesort'merge (x:xs) ys\n \nmergesort'splitinhalf :: [a] -> ([a], [a])\nmergesort'splitinhalf xs = (take n xs, drop n xs)\n where n = (length xs) `div` 2 \n \nmergesort :: (Ord a) => [a] -> [a]\nmergesort xs \n | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)\n | otherwise = xs\n where (ls, rs) = mergesort'splitinhalf xs\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport qualified Data.ByteString as B\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\nimport qualified Data.Text as T\nimport Data.Text.Read\nimport Data.Int\n{-import Data.Either.Unwrap-}\n{-sort = mergesort-}\n \nparseTextInt :: T.Text -> Int64\nparseTextInt txt = case decimal txt of\n Right (ans, _) -> ans\n _ -> 0\n\nparseIntLine input line_idx = map (read ::String->Int) mywords\n where \n mylines = lines input !! line_idx\n mywords = words mylines \n\nparseIntLineText input line_idx = map parseTextInt mywords\n where \n mylines = T.lines (T.pack input) !! line_idx\n mywords = T.words mylines \n\nsolve :: String -> String\n{-solve input = (show $ allAnswers n as) ++ \"\\n\" -}\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLineText input 1\n n = fromIntegral $ parseIntLineText input 0 !! 0\n\n\n\nanswer :: Int -> [Int64] -> Int64\nanswer n as = foldl min (answer1 n sas) $! allAnswers n sas \n where \n sas = sort as \n\n\nallAnswers :: Int -> [Int64] -> [Int64]\nallAnswers n sas = map (\\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas) \n where \n fullBoundaries = getBoundaries sas\n\n\nanswer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n\n\n\n\ngetBoundaries as = (last as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n\nmergesort'merge :: (Ord a) => [a] -> [a] -> [a]\nmergesort'merge [] xs = xs\nmergesort'merge xs [] = xs\nmergesort'merge (x:xs) (y:ys)\n | (x < y) = x:mergesort'merge xs (y:ys)\n | otherwise = y:mergesort'merge (x:xs) ys\n \nmergesort'splitinhalf :: [a] -> ([a], [a])\nmergesort'splitinhalf xs = (take n xs, drop n xs)\n where n = (length xs) `div` 2 \n \nmergesort :: (Ord a) => [a] -> [a]\nmergesort xs \n | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)\n | otherwise = xs\n where (ls, rs) = mergesort'splitinhalf xs\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport qualified Data.ByteString as B\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\nimport qualified Data.Text as T\nimport Data.Text.Read\nimport Data.Int\n{-import Data.Either.Unwrap-}\n{-sort = mergesort-}\n \nparseTextInt :: T.Text -> Integer\nparseTextInt txt = case decimal txt of\n Right (ans, _) -> ans\n _ -> error \"Division by zero\"\n\nparseIntLine input line_idx = map (read ::String->Int) mywords\n where \n mylines = lines input !! line_idx\n mywords = words mylines \n\nparseIntLineText input line_idx = map parseTextInt mywords\n where \n mylines = T.lines (T.pack input) !! line_idx\n mywords = T.words mylines \n\nsolve :: String -> String\n{-solve input = (show $ allAnswers n as) ++ \"\\n\" -}\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLineText input 1\n n = (fromIntegral $ parseIntLineText input 0 !! 0) :: Int\n\n\n\nanswer :: Int -> [Integer] -> Integer\nanswer n as = foldl min (answer1 n sas) $! allAnswers n sas \n where \n sas = sort as \n\n\nallAnswers :: Int -> [Integer] -> [Integer]\nallAnswers n sas = map (\\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas) \n where \n fullBoundaries = getBoundaries sas\n\n\nanswer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n\n\n\n\ngetBoundaries as = (last as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n\nmergesort'merge :: (Ord a) => [a] -> [a] -> [a]\nmergesort'merge [] xs = xs\nmergesort'merge xs [] = xs\nmergesort'merge (x:xs) (y:ys)\n | (x < y) = x:mergesort'merge xs (y:ys)\n | otherwise = y:mergesort'merge (x:xs) ys\n \nmergesort'splitinhalf :: [a] -> ([a], [a])\nmergesort'splitinhalf xs = (take n xs, drop n xs)\n where n = (length xs) `div` 2 \n \nmergesort :: (Ord a) => [a] -> [a]\nmergesort xs \n | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)\n | otherwise = xs\n where (ls, rs) = mergesort'splitinhalf xs\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport qualified Data.ByteString as B\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\nimport qualified Data.Text as T\nimport Data.Text.Read\nimport Data.Int\n{-import Data.Either.Unwrap-}\n{-sort = mergesort-}\n \nparseTextInt :: T.Text -> Int64\nparseTextInt txt = case decimal txt of\n Right (ans, _) -> ans\n _ -> error \"Division by zero\"\n\nparseIntLine input line_idx = map (read ::String->Int) mywords\n where \n mylines = lines input !! line_idx\n mywords = words mylines \n\nparseIntLineText input line_idx = map parseTextInt mywords\n where \n mylines = T.lines (T.pack input) !! line_idx\n mywords = T.words mylines \n\nsolve :: String -> String\n{-solve input = (show $ allAnswers n as) ++ \"\\n\" -}\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLineText input 1\n n = fromIntegral $ parseIntLineText input 0 !! 0\n\n\n\nanswer :: Int -> [Int64] -> Int64\nanswer n as = foldl min (answer1 n sas) $! allAnswers n sas \n where \n sas = sort as \n\n\nallAnswers :: Int -> [Int64] -> [Int64]\nallAnswers n sas = map (\\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas) \n where \n fullBoundaries = getBoundaries sas\n\n\nanswer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n\n\n\n\ngetBoundaries as = (last as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n\nmergesort'merge :: (Ord a) => [a] -> [a] -> [a]\nmergesort'merge [] xs = xs\nmergesort'merge xs [] = xs\nmergesort'merge (x:xs) (y:ys)\n | (x < y) = x:mergesort'merge xs (y:ys)\n | otherwise = y:mergesort'merge (x:xs) ys\n \nmergesort'splitinhalf :: [a] -> ([a], [a])\nmergesort'splitinhalf xs = (take n xs, drop n xs)\n where n = (length xs) `div` 2 \n \nmergesort :: (Ord a) => [a] -> [a]\nmergesort xs \n | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)\n | otherwise = xs\n where (ls, rs) = mergesort'splitinhalf xs\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\nimport Data.List\n{-import Data.Sort-}\n \n\nparseIntLine input line_idx = map read $ words $ lines input !! line_idx\n\nsolve :: String -> String\nsolve input = (show $ answer n as) ++ \"\\n\" \n where \n as = parseIntLine input 1\n n = parseIntLine input 0 !! 0\n\nanswer :: Int -> [Int] -> Int\nanswer n as = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas) \n where \n sas = sort as \n\ngetBoundaries as = (head $ reverse as) - (head as)\n\nmain = (solve <$> getContents) >>= putStr \n"}], "src_uid": "cda1179c51fc69d2c64ee4707b97cbb3"} {"source_code": "\n{-\nimport HUnit\n\ntestZero :: Test\ntestZero = Test \"TestZero\" $ assertEq \"$0.00\" (solve \"0\")\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq \"$2,012.00\" (solve \"2012\"),\n Test \"2\" $ assertEq \"$0.00\" (solve \"0\"),\n Test \"3\" $ assertEq \"($0.00)\" (solve (\"-0.00987654321\")),\n Test \"4\" $ assertEq \"($12,345,678.90)\" (solve (\"-12345678.9\"))]\n\ntestLong :: Test\ntestLong = Test \"TestLong\" $ assertEq \"$0.99\"\n (solve \"0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\")\n\ntestWA6 :: Test\ntestWA6 = Test \"Test 6\" $ assertEq \"($999,999,999.99)\" (solve \"-999999999.999999999\")\n\ntest :: IO ()\ntest = mapM_ run\n [testZero,\n testInput,\n testLong,\n testWA6]\n\n--------------------------------------------------------------------------------\n-}\n\nsolve :: String -> String\nsolve ('-':s) = concat [\"(\", solve s, \")\"]\nsolve s = concat [\"$\", solve' s1, \".\", take 2 (tail (s2 ++ \"000\"))]\n where\n (s1, s2) = break (== '.') s\n solve' :: String -> String\n solve' s = reverse (solve'' (reverse s)) \n where\n solve'' (s1:s2:s3:s4:s) = s1:s2:s3:',':solve'' (s4:s)\n solve'' s = s\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n", "positive_code": [{"source_code": "import Data.Char\nimport Control.Applicative\n\nmain = do cs <- getLine\n putStrLn $ solve cs\n\nsolve :: String -> String\nsolve ccs@(c:cs) = h ++ \"$\"++ (reverse $ f $ reverse m)++ (g q) ++ t\n where (n,p) = span ('.'/=) ccs\n q = if null p then p else tail p\n m = if c=='-' then tail n else n\n h = if c == '-' then \"(\" else []\n t = if c == '-' then \")\" else []\n\nf [] = []\nf [x] = [x]\nf [x,y] = [x,y]\nf [x,y,z] = [x,y,z]\nf (x:y:z:xs) = [x,y,z]++\",\"++(f xs)\n\ng [] = \".00\"\ng [x] = \".\"++[x]++\"0\"\ng (x:y:xs) = \".\"++[x,y]"}, {"source_code": "import Data.List\nimport Data.Char \n\n\nprocessFirst :: String -> String \nprocessFirst xs \n | length xs <= 3 = xs \n | otherwise = ret ++ \",\" ++ processFirst ret' where \n ( ret , ret' ) = splitAt 3 xs \n\nprocessSecond :: String -> String \nprocessSecond xs = ret where \n tmp = xs ++ \"00000000000000000000000\"\n ret = if null xs then \".00\" else take 3 tmp \n\nhelpSolve :: String -> String \nhelpSolve xs = ret where \n ( first , second ) = break ( =='.' ) xs \n ret = ( reverse . processFirst . reverse $ first ) ++ processSecond second \n\nsolve :: String -> String \nsolve ( x : xs ) = ret where \n ret = if x == '-' then \"($\" ++ helpSolve xs ++ \")\" else \"$\" ++ helpSolve ( x:xs )\n\n\n\nmain = interact $ unlines . map solve . lines \n"}, {"source_code": "main = do\n str <- getLine\n putStrLn.check (head str).format $ abs' str\n\ncheck c str@(x:xs)\n = if x == ',' then f c xs else f c str\n where\n f c xs = if c == '-' then \"($\"++xs++\")\" else '$':xs\n\nabs' (x:xs) = if x == '-' then xs else (x:xs)\n\nformat :: String -> String\nformat str = let intPart = takeWhile (/='.') str\n floatPart = drop (1+length intPart) str\n in intStr intPart ++ floatStr floatPart\n\nfloatStr str = \".\"++(take 2 $ take 2 str ++ repeat '0')\n\nintStr :: String -> String\nintStr str = let p = take (mod (length str) 3) str\n in f . (:) p . dataList $ drop (length p) str\n where\n f = init.concat.map (\\a -> a++\",\")\n\ndataList :: String -> [String]\ndataList [] = []\ndataList str = a: dataList b\n where\n (a,b) = splitAt 3 str\n"}, {"source_code": "main = getLine >>= putStrLn.answer\n\nanswer :: String -> String\nanswer ('-':cs) = \"($\"++ format cs ++ \")\"\nanswer str = \"$\"++ format str\n\nformat str\n = let intPart = takeWhile (/='.') str\n floatPart = drop (1+length intPart) $ str\n in formatI intPart ++ formatF floatPart\n\nformatI str = fst$foldl f ([],3-mod (length str) 3) str\n where\n f (str,0) c = (str++\",\"++[c] , 1)\n f (str,m) c = (str++[c],mod (m+1) 3)\n\nformatF str = '.':(take 2 $ take 2 str ++ repeat '0')\n"}], "negative_code": [{"source_code": "\n{-\nimport HUnit\n\ntestZero :: Test\ntestZero = Test \"TestZero\" $ assertEq \"$0.00\" (solve 0)\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq \"$2,012.00\" (solve 2012),\n Test \"2\" $ assertEq \"($0.00)\" (solve (-0.00987654321)),\n Test \"3\" $ assertEq \"($12,345,678.90)\" (solve (-12345678.9))]\n\ntest :: IO ()\ntest = mapM_ run\n [testZero,\n testInput]\n\n--------------------------------------------------------------------------------\n-}\n\nsolve :: Double -> String\nsolve d\n | d < 0 = concat [\"(\", solve (-d), \")\"]\n | otherwise = concat [\"$\", solve' n, \".\", if a' == 0 then \"00\" else (show a')]\n where\n (n, a) = properFraction d\n a' = truncate (a * 100)\n solve' :: Int -> String\n solve' n = reverse (solve'' (reverse (show n))) \n where\n solve'' (s1:s2:s3:s) = s1:s2:s3:',':solve'' s\n solve'' s = s\n\nmain :: IO ()\nmain = readLn >>= putStrLn . solve\n"}, {"source_code": "\n{-\nimport HUnit\n\ntestZero :: Test\ntestZero = Test \"TestZero\" $ assertEq \"$0.00\" (solve \"0\")\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $ assertEq \"$2,012.00\" (solve \"2012\"),\n Test \"2\" $ assertEq \"$0.00\" (solve \"0\"),\n Test \"3\" $ assertEq \"($0.00)\" (solve (\"-0.00987654321\")),\n Test \"4\" $ assertEq \"($12,345,678.90)\" (solve (\"-12345678.9\"))]\n\ntestLong :: Test\ntestLong = Test \"TestLong\" $ assertEq \"$0.99\"\n (solve \"0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\")\n\ntest :: IO ()\ntest = mapM_ run\n [testZero,\n testInput,\n testLong]\n\n--------------------------------------------------------------------------------\n-}\n\nsolve :: String -> String\nsolve ('-':s) = concat [\"(\", solve s, \")\"]\nsolve s = concat [\"$\", solve' s1, \".\", take 2 (tail (s2 ++ \"000\"))]\n where\n (s1, s2) = break (== '.') s\n solve' :: String -> String\n solve' s = reverse (solve'' (reverse s)) \n where\n solve'' (s1:s2:s3:s) = s1:s2:s3:',':solve'' s\n solve'' s = s\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n"}, {"source_code": "main = getLine >>= putStrLn.(:) '$'.check.format.abs'\n\ncheck str@(x:xs)\n = if x == ',' then xs else str\n\nabs' (x:xs) = if x == '-' then xs else (x:xs)\n\nformat :: String -> String\nformat str = let intPart = takeWhile (/='.') str\n floatPart = drop (1+length intPart) str\n in intStr intPart ++ floatStr floatPart\n\nfloatStr str = \".\"++(take 2 $ take 2 str ++ repeat '0')\n\nintStr :: String -> String\nintStr str = let p = take (mod (length str) 3) str\n in f . (:) p . dataList $ drop (length p) str\n where\n f = init.concat.map (\\a -> a++\",\")\n\ndataList :: String -> [String]\ndataList [] = []\ndataList str = a: dataList b\n where\n (a,b) = splitAt 3 str\n"}], "src_uid": "c704c5fb9e054fab1caeab534849901d"} {"source_code": "import Control.Arrow ((>>>))\nimport Control.Monad (replicateM_)\n\nmain =\n interact $\n lines\n >>> drop 1\n >>> map words\n >>> map (map read)\n >>> map (\\[a, b] -> if a == 0 then 1 else b * 2 + a + 1)\n >>> map show\n >>> unlines\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n input <- getLine \r\n let [n, m] = map read (words input)\r\n let res = if n == 0 then 0 else m * 2 + n\r\n print (res + 1)\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n input <- getLine \r\n let [n, m] = map read (words input)\r\n let res = if n == 0 then 0 else m * 2 + n\r\n print (res + 1)\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n input <- getLine \r\n let [n, m] = map read (words input)\r\n let res = if n == 0 then m * 2 - 1 else m * 2 + n\r\n print res\r\n"}], "src_uid": "2b6e670b602a89b467975edf5226219a"} {"source_code": "import Control.Monad\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as IS\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nkMaxN :: Int\nkMaxN = 200\n\nsg :: Array Int Int\nsg = listArray (1, kMaxN) [f i | i <- [1..kMaxN]]\n where f n = head $ filter (flip IS.notMember st) [0..]\n where st = IS.fromList [sg ! (n - i) | i <- [2..n-1], n `mod` i == 0]\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n let\n result\n | popCount n == 1 && odd (countTrailingZeros n) = False\n | odd n = False\n | otherwise = True\n return $ string7 (if result then \"Alice\" else \"Bob\") `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmain = do\r\n let pingo = Set.fromList ([2 ^ j | j <- [1..30], odd j]::[Int])\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine\r\n let r = odd n || n `Set.member` pingo\r\n putStrLn $ if r then \"Bob\" else \"Alice\"\r\n"}], "negative_code": [], "src_uid": "255ee92f5b860eacd9d6321195072734"} {"source_code": "import Data.Maybe\nimport Data.Array\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.List as L\nimport qualified Data.ByteString.Char8 as B\n\n-- link edges \ntype Vertex = Int\npairs :: [Int] -> [(Int, Vertex)]\npairs (x : y : xs) = (x , y) : (y , x) : pairs xs\npairs _ = []\n\nedges :: Int -> [Int] -> Array Int [Vertex]\nedges n = accumArray (flip (:)) [] (1, n) . pairs -- from 1 to n, may be different \n-- end here\n\nfindPath :: Vertex -> (Array Int [Vertex]) -> (M.Map Vertex Int) -> [Vertex]\nfindPath u e m\n | null adj = \n let path = map snd . L.sort . map (\\(a,b) -> (b, a)) . M.assocs $ m\n s = S.fromList (e ! u)\n in dropWhile (\\v -> S.notMember v s) $ path\n \n | otherwise = \n let v = head adj\n in findPath v e (M.insert v (M.size m) m)\n where\n adj = filter (\\v -> M.notMember v m) $ (e ! u)\n \nmain = do\n (n : _ : _ : e') <- liftM (map (fst . fromJust . B.readInt) . B.words) $ B.getContents\n let\n e = edges n e'\n ans = findPath 1 e (M.singleton 1 0)\n putStrLn . show . length $ ans\n putStrLn . L.intercalate \" \" . map show $ ans\n", "positive_code": [{"source_code": "import Data.Array\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): (y, x): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n (n:_:_:el) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let e = accumArray (flip (:)) [] (1, n) $ pairs el\n gao v d p =\n case filter (`M.notMember` d) $ e!v of\n (w:_) -> gao w (M.insert w (M.size d) d) (w:p)\n _ -> let w = minimumBy (comparing (d M.!)) $ e!v in w: takeWhile (/=w) p\n ans = gao 1 (M.singleton 1 0) [1]\n print $ length ans\n putStrLn $ unwords $ map show ans\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -ignore-asserts #-}\nimport Data.Maybe\nimport Data.Array\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.List as L\nimport qualified Data.ByteString.Char8 as B\n\n-- link edges \ntype Vertex = Int\npairs :: [Int] -> [(Int, Vertex)]\npairs (x : y : xs) = (x , y) : (y , x) : pairs xs\npairs _ = []\n\nedges :: Int -> [Int] -> Array Int [Vertex]\nedges n = accumArray (flip (:)) [] (1, n) . pairs -- from 1 to n, may be different \n-- end here\n\nfindPath :: Vertex -> (Array Int [Vertex]) -> (M.Map Vertex Int) -> [Vertex]\nfindPath u e m\n | null adj = \n let path = map snd . L.sort . map (\\(a,b) -> (b, a)) . M.assocs $ m\n s = S.fromList (e ! u)\n in dropWhile (\\v -> S.notMember v s) $ path\n \n | otherwise = \n let v = head adj\n in findPath v e (M.insert v (M.size m) m)\n where\n adj = filter (\\v -> M.notMember v m) $ (e ! u)\n \nmain = do\n (n : _ : _ : e') <- liftM (map (fst . fromJust . B.readInt) . B.words) $ B.getContents\n let\n e = edges n e'\n ans = findPath 1 e (M.singleton 1 0)\n putStrLn . show . length $ ans\n putStrLn . L.intercalate \" \" . map show $ ans\n"}], "negative_code": [], "src_uid": "250c0e647d0f2ff6d86db01675192c9f"} {"source_code": "import Control.Monad\nimport Prelude\n\nmain = do\n testCases <- getLine\n strNums <- replicateM (read testCases) testCase\n return ()\n\ntestCase = do\n line <- getLine\n print $ solution (map read (words line))\n\n\nsolution :: [Integer] -> Integer\nsolution [len, ones] = result where\n zeros = len - ones\n countSequences n = div (n * (n+1)) 2\n bags = ones + 1\n smallBagSize = div zeros bags\n bigBagSize = smallBagSize + 1\n bigBagsCount = zeros - (bags * smallBagSize)\n smallBagsCount = bags - bigBagsCount\n r1 = bigBagsCount * (countSequences bigBagSize)\n r2 = smallBagsCount * (countSequences smallBagSize)\n result = countSequences (ones + zeros) - (r1 + r2)\n", "positive_code": [{"source_code": "subStringCount :: Integer -> Integer\nsubStringCount l = div (l*(l+1)) 2\n\nsolve :: Integer -> Integer -> Integer\nsolve n m = allSubstrings - groups*(subStringCount lengthOfEach) - (mod numberOfZeros groups)*(lengthOfEach+1)\n where allSubstrings = div (n*(n+1)) 2\n numberOfZeros = n-m\n groups = m+1\n lengthOfEach = div numberOfZeros groups\n\n\nparse :: String -> String\nparse line = show $ solve n m\n where [n, m] = map (\\x -> read x :: Integer) $ words line\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Prelude\n\nmain = do\n testCases <- getLine\n strNums <- replicateM (read testCases) testCase\n return ()\n\ntestCase = do\n line <- getLine\n print $ solution (map read (words line))\n\n\nsolution :: [Int] -> Int\nsolution [len, ones] = result where\n zeros = len - ones\n countSequences n = div (n * (n+1)) 2\n bags = ones + 1\n smallBagSize = div zeros bags\n bigBagSize = smallBagSize + 1\n bigBagsCount = mod zeros bags\n smallBagsCount = bags - bigBagsCount\n r1 = bigBagsCount * (countSequences bigBagSize)\n r2 = smallBagsCount * (countSequences smallBagSize)\n result = countSequences (ones + zeros) - (r1 + r2)\n"}, {"source_code": "import Control.Monad\nimport Prelude\n\nmain = do\n testCases <- getLine\n strNums <- replicateM (read testCases) testCase\n return ()\n\ntestCase = do\n line <- getLine\n print $ solution (map read (words line))\n\n\nsolution :: [Int] -> Int\nsolution [len, ones] = result where\n zeros = len - ones\n countSequences n = div (n * (n+1)) 2\n bags = ones + 1\n smallBagSize = div zeros bags\n bigBagSize = smallBagSize + 1\n bigBagsCount = zeros - (bags * smallBagSize)\n smallBagsCount = bags - bigBagsCount\n r1 = bigBagsCount * (countSequences bigBagSize)\n r2 = smallBagsCount * (countSequences smallBagSize)\n result = countSequences (ones + zeros) - (r1 + r2)\n"}, {"source_code": "subStringCount :: Integer -> Integer\nsubStringCount l = div (l*(l+1)) 2\n\nsolve :: Integer -> Integer -> Integer\nsolve n m\n | remaining == 0 = allSubstrings - (subStringCount lenZero)*(m+1)\n | otherwise = allSubstrings - (subStringCount lenZero)*m - (subStringCount remaining)\n where allSubstrings = div (n*(n+1)) 2\n lenZero = div (n-m) (m+1)\n remaining = mod (n-m) (m+1)\n\nparse :: String -> String\nparse line = show $ solve n m\n where [n, m] = map (\\x -> read x :: Integer) $ words line\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "src_uid": "7458f44802c134de6fed7b4de84ea68c"} {"source_code": "import Array\nimport List\n\nbfs :: (Eq a) => (a -> [a]) -> a -> [a]\nbfs f s = (foldr union []) $ takeWhile (not . null) $ iterate (nub . (>>= f)) [s]\n\ngraph :: String -> (Int -> [Int], Int -> Int, Int)\ngraph s = \n ((!) (accumArray (\\ e a -> a : e) [] (1, n) assocList),\n (!) (foldr (\\ (a, b) ar -> ar // [(a, ar ! a + 1), (b, ar ! b + 1)])\n (array (1, n) [(i, 0) | i <- [1..n]])\n assocList),\n n)\n where\n assocList = map ((\\ [a, b] -> (read a, read b)) . words) (tail ls)\n n = read $ head $ ls\n ls = lines s\n\nsolve s = \n (show a') ++ \" \" ++ (show b')\n where\n [a, b] = filter ((< n - 1) . degree) [1..n]\n (a', b') = if b `elem` bfs g a then (a, b) else (b, a)\n (g, degree, n) = graph s\n \nmain = interact solve\n", "positive_code": [{"source_code": "import Array\nimport Data.List\n\nbfs :: (Eq a) => (a -> [a]) -> a -> [a]\nbfs f s = (foldl' union []) $ takeWhile (not . null) $ iterate (nub . (>>= f)) [s]\n\ngraph :: String -> (Int -> [Int], Int -> Int, Int)\ngraph s = \n ((!) (accumArray (\\ e a -> a : e) [] (1, n) assocList),\n (!) (foldl' (\\ a (b, c) -> a // [(b, a ! b + 1), (c, a ! c + 1)])\n (array (1, n) [(i, 0) | i <- [1..n]])\n assocList),\n n)\n where\n assocList = map ((\\ [a, b] -> (read a, read b)) . words) (tail ls)\n n = read $ head $ ls\n ls = lines s\n\nsolve s = \n (show a') ++ \" \" ++ (show b')\n where\n [a, b] = filter ((< n - 1) . degree) [1..n]\n (a', b') = if b `elem` bfs g a then (a, b) else (b, a)\n (g, degree, n) = graph s\n \nmain = interact solve\n"}, {"source_code": "import Array\nimport List\n\nbfs :: (Eq a) => (a -> [a]) -> a -> [a]\nbfs f s = (foldr union []) $ takeWhile (not . null) $ \n iterate (nub . (>>= f)) [s]\n\ngraph :: String -> (Int -> [Int], Int -> Int, Int)\ngraph s = \n ((!) (accumArray (\\ e a -> a : e) [] (1, n) assocList),\n (!) (foldr (\\ (a, b) ar -> ar // [(a, ar ! a + 1), (b, ar ! b + 1)])\n (array (1, n) [(i, 0) | i <- [1..n]])\n assocList),\n n)\n where\n assocList = map ((\\ [a, b] -> (read a, read b)) . words) (tail ls)\n n = read $ head $ ls\n ls = lines s\n\nsolve s = \n (show a') ++ \" \" ++ (show b')\n where\n [a, b] = filter ((< n - 1) . degree) [1..n]\n (a', b') = if b `elem` bfs g a then (a, b) else (b, a)\n (g, degree, n) = graph s\n \nmain = interact solve\n"}, {"source_code": "import Data.List\nmain = do \n ([n]:pairs) <- fmap (map (map read . words) . lines) getContents\n let sortedPairs = map sort pairs\n [[x,y]] = [[i,j] | i <- [1..n], j <- [i+1..n]] \\\\ sortedPairs\n f ([a,z], [w,b]) | z == w && a == x && b == y = True\n f _ = False\n ans = if any f [(a,b) | a <- pairs, b <- pairs]\n then [x,y]\n else [y,x]\n putStrLn . unwords . map show $ ans"}, {"source_code": "import Control.Monad\nimport Data.Array\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (n * (n - 1) `div` 2 - 1) getA\n\tputStr $ unwords $ map show $ gao n a where\n\t\tgetA = fmap (map read . words) getLine\n\ngao n a = if w!x > w!y then [x, y] else [y, x] where\n\t[w, l] = [accumArray (+) 0 (1, n) $ zip (map f a) $ repeat 1 | f <- [head, last]]\n\t[x, y] = filter (\\i -> w!i + l!i < n - 1) [1 .. n]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array.IO\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n n <- readLn\n let m = n * (n\u2009-\u20091)\u2009`quot`\u20092\u2009-\u20091\n xs <- replicateM m (map read . words <$> getLine) :: IO [[Int]]\n matches <- newArray ((1, 1), (n, n)) False :: IO (IOArray (Int, Int) Bool)\n ranks <- newArray (1, n) 0 :: IO (IOArray Int Int)\n forM [1 .. n] $ \\i -> do\n writeArray matches (i, i) True\n forM xs $ \\(i : j : _) -> do\n writeArray matches (i, j) True\n writeArray matches (j, i) True\n v <- readArray ranks i\n writeArray ranks i (v + 1)\n Just ((i , j), _) <- find (not . snd) <$> getAssocs matches\n ri <- readArray ranks i\n rj <- readArray ranks j\n if ri >= rj\n then printf \"%d %d\\n\" i j\n else printf \"%d %d\\n\" j i\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\t\n\tn <- fmap read getLine\n\ta <- replicateM (n * (n - 1) `div` 2 - 1) $ fmap (map read . words) getLine\n--\ta <- fmap (map (map read . words) . lines) getContents\n\tputStr $ unwords $ map show $ head $ [[i, j] | i <- [1 .. n], j <- [i + 1 .. n]] \\\\ map sort a\n{-\n\n-}\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\t\n\tn <- fmap read getLine\n\ta <- fmap (map (map read . words) . lines) getContents\n\tputStr $ unwords $ map show $ head $ [[i, j] | i <- [1 .. n], j <- [i + 1 .. n]] \\\\ map sort a\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array.IO\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n n <- readLn\n let m = n * (n\u2009-\u20091)\u2009`quot`\u20092\u2009-\u20091\n xs <- replicateM m (map read . words <$> getLine) :: IO [[Int]]\n let pairs = do\n x : y : _ <- xs\n [(x, y), (y, x)]\n let b = ((1, 1), (n, n))\n arr <- newArray b False :: IO (IOArray (Int, Int) Bool)\n forM [1 .. n] $ \\i -> do\n writeArray arr (i, i) True\n forM pairs $ \\idx -> do\n writeArray arr idx True\n Just (idx, _) <- find (not . snd) <$> getAssocs arr\n uncurry (printf \"%d %d\\n\") idx\n"}, {"source_code": "import Data.List\nmain = do \n ([n]:pairs) <- fmap (map (map read . words) . lines) getContents\n let sortedPairs = map sort pairs\n [[x,y]] = [[i,j] | i <- [1..n], j <- [i+1..n]] \\\\ sortedPairs\n f ([x,z], [w,y]) | z == w = True\n f _ = False\n if any f [(a,b) | a <- pairs, b <- pairs]\n then putStrLn . unwords . map show $ [y,x]\n else putStrLn . unwords . map show $ [x,y]\n"}], "src_uid": "f1ac6da78aed11d9118a85182c5644de"} {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n _ <- getLine\n inp <- fmap (map read . words) getLine\n print $ solve inp\n\n\n\nsolve :: [Int] -> Int\nsolve = foldl f 1 . sort\n where\n f mex x | mex <= x = mex + 1\n | otherwise = mex\n", "positive_code": [{"source_code": "import Data.List\n\nmain = interact $ show . (+ 1) . foldl (\\a x -> min (a + 1) x) 0 . sort . map read . tail . words\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = do \n _ <- getLine \n as <- sort . map read . words <$> getLine \n print $ solve as 1\n\nsolve :: [Int] -> Int -> Int\nsolve [] x = x\nsolve (a:as) x = solve as (if x <= a then x + 1 else x)\n"}, {"source_code": "import Data.List( sort)\nmain = do\n n <- getLine\n nums <- return . (map read) . words =<< getLine\n let snums = sort nums\n\tprocess p [] = p\n\tprocess p (x:xs) = if p<=x then process (p+1) xs else process p xs\n print $ process 1 snums\n"}, {"source_code": "module Main where \n\nimport System.IO\nimport Data.Array\nimport Data.Int\nimport Data.List\n\nmain :: IO ()\nmain = do\n\t\tn <- readAllArr\n\t\tl <- readAllArr\n\t\tlet ws = words l\n\t\tputStrLn $ show $ foldl (\\x y -> if x <= y then x+1 else x) 1 $ sort (map read $ ws)\n\t\t\nreadAllArr :: IO String\nreadAllArr = getLine\n \nstartsWith :: Eq a => [a] -> [a] -> Bool\nstartsWith [] _ = True \nstartsWith _ [] = False\nstartsWith (x:xs) (y:ys)= x == y && startsWith xs ys \n\norF :: (a->Bool) -> (a->Bool) -> a -> Bool\norF f g a = (f a) || (g a)\n\npairs :: [a] -> [(a, a)] \npairs l = [(x,y) | (x:ys) <- tails l, y <- ys]\n\nreplace' :: Eq b => b -> b -> [b] -> [b] \nreplace' a b = map (\\x -> if (a == x) then b else x)"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nmex :: [Int] -> Int\nmex = mexRec 1 . sort\n where mexRec index [] = index\n mexRec index (x:xs)\n | x >= index = mexRec (index + 1) xs\n | otherwise = mexRec index xs\n\n\nreadInt s = let Just (i, _) = C.readInt s in i\n\nmain = do\n getLine\n ar <- fmap (map readInt . C.words) C.getLine\n print $ mex ar\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.List\n\n\nmain = do\n s <- B.getContents\n let a = flip evalState s $ do\n n <- readInt\n replicateM n readInt\n print $ solve a\n\n\nsolve a = foldl' (\\r b -> if b >= r then r+1 else r) 1 bs\n where bs = sort a\n\nreadInt :: State B.ByteString Int\nreadInt = do\n Just (n, rest) <- gets (B.readInt . B.dropWhile isSpace)\n put rest\n return n\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >> getList >>= print . succ . f 1 . sort\n\nf k [] = 0\nf k (a:as)\n\t| k <= a = 1 + f ( k + 1 ) as\n\t| otherwise = f k as\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n let parseInt = read :: String -> Int \n nLine <- getLine\n aLine <- getLine\n let n = parseInt $ nLine\n a = map parseInt . words $ aLine\n putStrLn $ show $ maxMex a\n\nmaxMex :: [Int] -> Int\nmaxMex = foldl findMaxMex 1 . sort\n where findMaxMex ans x = if x >= ans then ans + 1 else ans\n\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve 1 . sort . map read . tail . words =<< getContents\n\nsolve :: Int -> [Int] -> Int\nsolve i [] = i\nsolve i (a:s) | i <= a = solve (i + 1) s\n | otherwise = solve i s\n"}, {"source_code": "import Data.List\n\n\n\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n print (solve xs)\n\n\n\nsolve :: [Int] -> Int\nsolve xs = g 1 . sort $ xs\n where\n g x [] = x\n g x (a:as) | x <= a = g (x+1) as\n | otherwise = g x as\n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >> B.getLine >>= print . succ . f 1 . sort . map ( fst . fromJust . B.readInt ) . B.words\n\nf k [] = 0\nf k (a:as)\n\t| k <= a = 1 + f ( k + 1 ) as\n\t| otherwise = f ( k + 1 ) as\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n let parseInt = read :: String -> Int \n nLine <- getLine\n aLine <- getLine\n let n = parseInt $ nLine\n a = map parseInt . words $ aLine\n putStrLn $ show $ maxMex a\n\nmaxMex :: [Int] -> Int\nmaxMex = foldl findMaxMex 1 . zip [1..] . sort\n where findMaxMex ans (i, x) = if x >= i then ans + 1 else ans\n\n"}, {"source_code": "import Data.List\n\n\n\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n print (solve xs)\n\n\n\nsolve :: [Int] -> Int\nsolve xs = g . takeWhile (uncurry (<)) . zip [1..] . sort $ xs\n where\n g [] = length xs\n g ((a, _):_) = a\n"}], "src_uid": "482b3ebbbadd583301f047181c988114"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.ByteString.Lazy.Char8\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n k <- getInt\r\n s <- getNext\r\n let\r\n rs = reverse s\r\n one = (||) (k == 0) (s == rs)\r\n pure $ putInts $ if one then [1] else [2]\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n k <- getInt\n s <- getNext\n let ans = if s == P.reverse s || k == 0\n then 1\n else 2\n pure $ putInts [ans]\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\ngetNext :: Monad m => S m P.ByteString\ngetNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.ByteString.Lazy.Char8\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n k <- getInt\r\n s <- getNext\r\n let\r\n rs = reverse s\r\n one = (||) ((==) k 0) ((==) s rs)\r\n pure $ putInts $ if one then [1] else [2]\r\n"}, {"source_code": "import qualified Data.ByteString as BS\nimport Control.Monad\nsolve :: BS.ByteString -> Int -> Int\nsolve x k\n | k == 0 = 1\n | x == BS.reverse x = 1\n | otherwise = 2\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, k] <- map read . words <$> getLine\n x <- BS.getLine\n print $ solve (BS.take n x) k\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n line <- getLine\n let [n, k] = map read $ words line :: [Int]\n str <- getLine\n putStrLn $ show $ solve n k str\n return ()\n\nsolve :: Int -> Int -> [Char] -> Int\nsolve n k str\n | k == 0 = 1\n | (reverse str) == str = 1\n | otherwise = 2\n\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString as BS\nimport Control.Monad\nsolve :: BS.ByteString -> Int -> Int\nsolve x k\n | k == 0 = 1\n | x == BS.reverse x = 1\n | otherwise = 2\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [_n, k] <- map read . words <$> getLine\n x <- BS.getLine\n print $ solve x k\n"}], "src_uid": "08cd22b8ee760a9d2dacb0d050dcf37a"} {"source_code": "\nimport Monad (liftM)\n\neps = 1e-06\n\nbinFind :: (Double -> Double) -> (Double, Double) -> Double\nbinFind f (l, r)\n | l + eps > r = m\n | f l * f r > eps = error \"fl * fr > 0\"\n | f m * f r > 0 = binFind f (l, m)\n | otherwise = binFind f (m, r)\n where\n m = 0.5 * (l+r)\n\nsolve :: Double -> [Double] -> Double\nsolve k as = binFind f (0, 1000)\n where\n k' = 1 - k / 100\n f x = sum $ map (\\a -> if a > x then k' * (a-x) else (a-x)) as \n\nmain :: IO ()\nmain = do\n [_, k] <- liftM (map read . words) getLine\n as <- liftM (map read . words) getLine\n print $ solve k as \n", "positive_code": [{"source_code": "module Main where\n\ncheck :: Double -> [Double] -> Double -> Bool\ncheck k a value = rem*(1 - k/100.0) > nec where\n rem = sum $ map (\\x -> max 0.0 (x - value)) a\n nec = sum $ map (\\x -> max 0.0 (value - x)) a\n\neps :: Double\neps = 1e-7\n\nbinS :: Double -> [Double] -> Double -> Double -> Double\nbinS k a left right =\n let binSearch = binS k a\n s = (left + right)/2 in\n if right - left < eps then s\n else if check k a s\n then binSearch s right\n else binSearch left s\n\nsolve :: String -> String -> Double\nsolve nk a = binS k al 0.0 (maximum al) where\n nkl = map read (words nk)\n k = head $ tail nkl\n al = map read (words a)\n\nmain = do\n nk <- getLine\n a <- getLine\n-- print $ map (\\x -> max 0.0 (x - 2.0)) a\n print $ solve nk a\n"}, {"source_code": "import IO\nimport Text.Printf\n\nhalf :: [Int] -> Double -> Double\nhalf [] _ = 0 :: Double\nhalf (a:as) m = half as m + if (realToFrac a) > m\n then ((realToFrac a)-m)\n else 0\n \nhalf2 [] _ = 0 :: Double\nhalf2 (a:as) m = half2 as m + if (realToFrac a) < m \n then (m - (realToFrac a))\n else 0\n \n\nbinSearch :: (Double -> (Int, a)) -> Double -> Double -> (Double, a)\nbinSearch f min max = \n --putStrLn (show (min, max, (max+min)/2))\n case (f ((max+min)/2)) of\n (-1, _) -> binSearch f min ((max + min)/2)\n (0, cx) -> ((max + min)/2, cx)\n (1, _) -> binSearch f ((max + min)/2) max\n \n\n \nsolve :: Int -> Int -> [Int] -> Double\nsolve n k as = let max = realToFrac $ maximum as\n min = realToFrac $ minimum as\n q = 1 - ((realToFrac k)/100)\n f t = let h1 = half as t\n h2 = half2 as t\n r = (h1*q) - h2\n in if (abs r) < (0.1^6)\n then (0, t)\n else if r > 0\n then (1, t)\n else (-1, t)\n (_, x) = binSearch f min max\n in x\n \nmain = do\n line <- getLine\n line2 <- getLine\n let (n:k:[]) = map read (words line) :: [Int]\n as = map read (words line2) :: [Int]\n printf \"%.6f\" $ solve n k as\n return ()"}, {"source_code": "import Data.List\nimport Text.Printf\nmain = do\n [n, k] <- (map read . words) `fmap` getLine\n a <- (map (fromInteger . read) . words) `fmap` getLine\n let averge = sum a / fromInteger n\n k' = fromInteger k / 100.0\n f x = let (p, m) = foldl' (\\(a, b) xi -> if xi > x then (a + xi - x, b) \n else (a, b + x - xi)) (0, 0) a in p * (1.0 - fromInteger k/100.0) - m\n sol a fa b fb | a - b < min ((a + b)*1e-7) 1e-7 = (a + b)/2\n | otherwise = let c = (a + b)/2\n fc = f c in\n if fc < 0 then sol c fc b fb else sol a fa c fc\n x = sol averge (f averge) 0 (f 0) :: Double\n printf \"%.6f\" x\n"}], "negative_code": [], "src_uid": "9fd09b05d0e49236dca45615e684ad85"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tprint $ minimum $ do\n\t\t( a, i ) <- zip as [ 0 .. ]\n\t\tj <- [ 0, n - 1 ]\n\t\tguard $ i /= j\n\t\treturn $ a `div` ( abs $ i - j )", "positive_code": [{"source_code": "main::IO()\nmain=do\n n<-readLn::IO Int\n s<-getLine\n let t=(map read $ words s)::[Int]\n print $ foldl1 min $ zipWith (\\x i->x `div` (max i (n-i-1))) t [0..]"}], "negative_code": [{"source_code": "f::Int->Int->Int->Int\nf n x i=x `div` if i==0 then n-1\n else if i==n-1 then n-1\n else min i (n-i-1)\n\nmain::IO()\nmain=do\n n<-readLn::IO Int\n s<-getLine\n let t=(map read $ words s)::[Int]\n print $ foldl1 min $ zipWith (f n) t [0..]"}], "src_uid": "f146808eb6e0ee04d531e7222a53d275"} {"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O3 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Int\nimport Data.Array.Unboxed\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest :: Int -> Int -> [Int] -> Int\ntest n k a = (* 2) $ sum l \n where\n c = accumArray (+) 0 (0, k - 1) $ [ (mod j k, 1) | (i, j) <- zip [0 .. ] a] :: UArray Int Int\n l = [ if i < j then min (c ! i) (c ! j) else div (c ! i) 2 | i <- [ 0 .. pred k], let j = mod (2 * k - i) k, i <= j]\n\nmain = do\n s <- C.getContents\n let (n:k:a) = map ru $ C.words s\n print $ test n k $ take n a\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ncounter :: [Int] -> Int -> Array Int Int\ncounter l maxVal = accumArray (+) 0 (0, maxVal) $ map (\\x -> (x, 1)) l\n\nprocess :: [Int] -> Int -> Int\nprocess boxes k = pairCnt where\n mods = map (`mod` k) boxes\n counts = counter mods (k-1)\n (lBound, hBound) = bounds counts\n pair s i = s + if i == 0 || 2*i == k then 2 * ((counts ! i) `div` 2) else min (counts ! i) (counts ! (k-i))\n pairCnt = foldl pair 0 [lBound..hBound]\n\nmain = do\n n:k:[] <- getInts\n boxes <- getInts\n print $ process boxes k\n"}], "negative_code": [], "src_uid": "3f3a013cedaaf8cbee0a74a4ed50f09d"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nimport Data.Int\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\n\nsolve n a = \n (answer, go2 (1,1))\n where\n (a', n') = if even n then (a, n) else (a ++ [0], n + 1)\n\n arr = listArray (1, n') a' :: Array Int Int\n bnds = ((1,1), (n', n'))\n cache = listArray bnds [go idx | idx <- range bnds] :: Array (Int,Int) Int\n\n answer = go (1, 1)\n\n go (x, e)\n | even x || x < 1 || x > n' = 0\n | x + 1 == n' = max val1 val2\n | otherwise = ans1 `min` ans2 `min` ans3\n where\n go' idx = cache ! idx\n val1 = arr ! e\n val2 = arr ! (x + 1)\n val3 = arr ! (x + 2)\n ans1 = max val2 val3 + go' (x + 2, e)\n ans2 = max val1 val3 + go' (x + 2, x + 1)\n ans3 = max val1 val2 + go' (x + 2, x + 2)\n\n go2 (x, e)\n | even x || x < 1 || x > n' = error \"impossible\"\n | x + 1 == n' = [(e, x + 1)]\n | ans1 == ans = (x + 1, x + 2) : go2 (x + 2, e)\n | ans2 == ans = (e, x + 2) : go2 (x + 2, x + 1)\n | ans3 == ans = (e, x + 1) : go2 (x + 2, x + 2)\n | otherwise = error \"impossible\"\n where\n ans = go (x, e)\n val1 = arr ! e\n val2 = arr ! (x + 1)\n val3 = arr ! (x + 2)\n go' idx = cache ! idx\n ans1 = max val2 val3 + go' (x + 2, e)\n ans2 = max val1 val3 + go' (x + 2, x + 1)\n ans3 = max val1 val2 + go' (x + 2, x + 2)\n\nparseInput = do \n n <- readInt\n a <- replicateM n readInt\n return (n, a)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n\nmain = do\n (n, a) <- evalState parseInput <$> BS.getContents\n let (ans, pairs) = solve n a\n print ans\n forM_ pairs $ \\(x, y) -> if x <= n && y <= n then putStrLn (show x ++ \" \" ++ show y) else print (min x y)\n\n--{{{ Start of a minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n--}}} end of a minimal State Monad\n", "positive_code": [{"source_code": "import Array\n\nreadInts :: IO [Int]\nreadInts = do\n line <- getLine\n return (map read (words line))\n\nmyArray :: [Int] -> Array Int Int\nmyArray xs\n | mod (length xs) 2 == 0 = myArray_ (xs ++ [0])\n | otherwise = myArray_ (xs ++ [0, 0])\n where\n myArray_ :: [Int] -> Array Int Int\n myArray_ xs = listArray (0, length xs - 1) xs\n\n\n------------------------------------------------------------------------------------------------------------------------------------------\n\nsolve :: Array Int Int -> Array (Int, Int) Int\nsolve d = a\n where\n a = array ((0, 1), (n, div n 2))\n ([((0, 1), max (d ! 1) (d ! 2)), ((1, 1), max (d ! 0) (d ! 2)), ((2, 1), max (d ! 0) (d ! 1))]\n ++\n [((i, 1), 0) | i <- [3..n]]\n ++\n [((i, j), a ! (i, j - 1) + max (d ! (2*j)) (d ! (2*j - 1))) | j <- [2..div n 2], i <- [0..2 * (j - 1)]]\n ++\n [((i, j), minimum (map (\\k -> a ! (k, j - 1) + max (d ! k) (d ! (2*j))) [0..2 * (j - 1)])) | j <- [2..div n 2], i <- [2 * j - 1]]\n ++\n [((i, j), minimum (map (\\k -> a ! (k, j - 1) + max (d ! k) (d ! (2*j - 1))) [0..2*(j - 1)])) | j <- [2..div n 2], i <- [2 * j]]\n ++\n [((i, j), 0) | j <- [2..div n 2], i <- [2 * j + 1 .. n]]\n )\n n_ = snd (bounds d)\n n = n_ - mod n_ 2\n\ngetAnswer :: Array Int Int -> Array (Int, Int) Int -> [(Int, Int)]\ngetAnswer d array = getAnswer_ array (n, div n 2) []\n where\n n = fst (snd (bounds array))\n getAnswer_ :: Array (Int, Int) Int -> (Int, Int) -> [(Int, Int)] -> [(Int, Int)]\n getAnswer_ _ (0, 1) xs = (1, 2):xs\n getAnswer_ _ (1, 1) xs = (0, 2):xs\n getAnswer_ _ (2, 1) xs = (0, 1):xs\n getAnswer_ array (i, j) xs\n | i == 2*j = getAnswer_ array (k, j-1) ((k, m):xs)\n | i == 2*j - 1 = getAnswer_ array (k, j-1) ((k, m):xs)\n | otherwise = getAnswer_ array (i, j-1) ((2*j-1, 2*j):xs)\n where\n k = head (filter (\\l -> array ! (i, j) == array ! (l, j-1) + max (d ! l) (d ! m)) [0..2*j-2])\n m = if (i == 2*j) then 2*j-1 else 2*j\n\n------------------------------------------------------------------------------------------------------------------------------------------\n\nprintAns :: Int -> [(Int, Int)] -> IO ()\nprintAns _ [] = return ()\nprintAns n (x:xs) = do\n printAns_ n x\n printAns n xs\n where\n printAns_ n (x1, x2)\n | x1 < n && x2 < n = putStrLn (show (x1+1) ++ \" \" ++ show (x2+1))\n | x1 < n = putStrLn (show (x1+1))\n | x2 < n = putStrLn (show (x2+1))\n | otherwise = error \"printAns: x1 >= n and x2 >= n\"\n \n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- readInts\n let a = myArray xs\n let d = solve a\n let answer = getAnswer a (solve a)\n print (d ! (snd (bounds d)))\n printAns n answer\n"}], "negative_code": [], "src_uid": "cc4b6ce9155e96c4b0ecb68e9d6d4ec0"} {"source_code": "import Data.Array.Unboxed (Array, bounds, listArray, (!))\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nfindIndexFrom :: Array Int Int -> Int -> Int -> Int\nfindIndexFrom v i x = let (_, n) = bounds v in go i n\n where go lo hi | lo >= hi = hi\n go lo hi = let m = lo + (hi - lo + 1) `quot` 2\n in if v ! m > x\n then go lo (m - 1)\n else go m hi\n\nbestEta :: Array Int Int -> Int -> Maybe Double\nbestEta v u = maximum $ map findTriple [1..(n-2)]\n where (_, n) = bounds v\n findTriple i = let k = findIndexFrom v i (u + v ! i)\n in if (i + 1 < k)\n then Just (toEta i (i + 1) k)\n else Nothing\n toEta i j k = fromIntegral (v ! k - v ! j) / fromIntegral (v ! k - v ! i)\n\nmain = do\n let toInt = fst . fromJust . B.readInt\n let readInts = fmap (map toInt . B.words) B.getLine\n\n [n, u] <- readInts\n v <- fmap (listArray (1, n)) readInts\n\n case bestEta v u of\n Just v -> putStrLn (show v)\n Nothing -> putStrLn \"-1\"\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Maybe\n\nmain = interact exec\nexec = maybe \"-1\" show . (\\(n:u:xs) -> fn n u xs) . map read . words\nfn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\\(x, y, mz) -> fmap (\\z -> fromIntegral (z - y) / fromIntegral (z - x) :: Double) mz) $ take (n - 2) $ unfoldr (\\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s'))) (let (x, s) = S.deleteFindMin xs in (x, s))\n\nmaximumMay [] = Nothing\nmaximumMay xs = Just $ maximum xs\n\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Maybe\n\nmain = interact exec\nexec = maybe \"No\" ((\"Yes\\n\" ++) . show) . (\\(n:u:xs) -> fn n u xs) . map read . words\nfn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\\(x, y, mz) -> fmap (\\z -> fromIntegral (z - y) / fromIntegral (z - x)) mz) $ take (n - 2) $ unfoldr (\\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s'))) (let (x, s) = S.deleteFindMin xs in (x, s))\n\nmaximumMay [] = Nothing\nmaximumMay xs = Just $ maximum xs\n\n\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Maybe\n\nmain = interact exec\nexec = maybe \"No\" show . (\\(n:u:xs) -> fn n u xs) . map read . words\nfn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\\(x, y, mz) -> fmap (\\z -> fromIntegral (z - y) / fromIntegral (z - x) :: Double) mz) $ take (n - 2) $ unfoldr (\\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s'))) (let (x, s) = S.deleteFindMin xs in (x, s))\n\nmaximumMay [] = Nothing\nmaximumMay xs = Just $ maximum xs\n\n\n"}], "src_uid": "74ed99af5a5ed51c73d68f7d4ff2c70e"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n as <- getInts\n\n let\n as' = sort $ zip as [1..]\n b = zipWith (\\(a, i) p -> (max a (p+1), i)) as' $ (-100):(map fst b)\n\n putStrLn $ unwords $ map show $ elems (array (1, n) $ map swap b :: UArray Int Int)\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array.IO\nimport Data.List\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nmain = do\n n <- fmap read getLine\n nums <- fmap (parseInts n) BS.getLine\n let sorted = sort (zip nums [1..]) :: [(Int,Int)]\n\n ans <- newArray (1,n) 0 :: IO (IOUArray Int Int)\n\n let go _ [] = return ()\n go m ((v,j):rest) = do let m' = max m v\n writeArray ans j m'; go (m'+1) rest\n go 0 sorted\n forM_ [1..n] $ \\i -> do\n v <- readArray ans i\n putStr $ show v ++ \" \"\n putStrLn \"\"\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts\n\n putStrLn $ unwords $ map show $ map snd $ sort $ map swap $ concat $ map (zipWith (\\a (b, i) -> (b+a, i)) [0..]) $ groupBy ((==) `on` fst) $ sort $ zip as [1..]\n\n"}], "src_uid": "d19c7a74d739c2ca0d568808862ba2bd"} {"source_code": "import System.IO\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t rtc\r\n mapM (putStrLn . showHM . solve) tcs\r\nri = map read . words <$> getLine :: IO [Int]\r\nrtc = do\r\n [n,h,m] <- ri\r\n als <- replicateM n (toM <$> ri)\r\n return (toM [h,m], sort als)\r\ntoM [h,m] = h*60 + m\r\nsolve (s, als) = flip (-) s . fromJust . find (>=s) $ a2\r\n where\r\n a2 = als ++ map (+ (24*60)) als\r\nshowHM mm = show h ++ \" \" ++ show m\r\n where\r\n h = mm `div` 60\r\n m = mm `mod` 60\r\n", "positive_code": [{"source_code": "import Control.Monad (forM)\n\ntype Time = (Int, Int)\ntype Case = (Time, [Time])\n\n-- i have no idea what i'm doing starts here\nmain :: IO ()\nmain = do\n res <- map solve <$> parseIn\n putStr $ write res\n\nparseIn :: IO [Case]\nparseIn = do\n n <- read <$> getLine\n forM [1..n] $ \\_ -> do\n [l, nowH, nowM] <- map read . words <$> getLine\n alarms <- forM [1..l] $ \\_ -> do\n [alarmH, alarmM] <- map read . words <$> getLine\n return (alarmH, alarmM)\n return ((nowH, nowM), alarms)\n\n-- i have idea what i'm doing\nwrite :: [Time] -> String\nwrite list = unlines $ map writeLine list\n\nwriteLine :: Time -> String\nwriteLine time = show (fst time) ++ \" \" ++ show (snd time)\n\ntoMinutes :: Time -> Int\ntoMinutes t = 60 * fst t + snd t\n\nfromMinutes :: Int -> Time\nfromMinutes number\n | number >= 24 * 60 = fromMinutes (number - 24 * 60)\n | otherwise = divMod number 60\n\nmoveToNextDay :: Int -> Int\nmoveToNextDay number = number + 24 * 60\n\ngetClosestAlarm :: Int -> [Int] -> Int\ngetClosestAlarm now alarms =\n let past = [t | t <- alarms, t < now]\n future = [t | t <- alarms, t >= now]\n closest = minimum (map moveToNextDay past ++ future)\n in closest - now\n\n-- TODO write more beautifully (?)\nsolve :: Case -> Time\nsolve testcase = fromMinutes $ getClosestAlarm (toMinutes (fst testcase)) (map toMinutes (snd testcase))\n"}, {"source_code": "module Main\r\n ( main )\r\n where\r\nimport Control.Monad\r\nimport Data.List\r\ntimeToMin::Int->Int->Int\r\ntimeToMin a b=60*a+b\r\n\r\nminToTime::Int->[Int]\r\nminToTime t=[a,b]\r\n where a=t`div`60\r\n b=t-a*60\r\ndoTime::Int->[Int]->Int\r\ndoTime sleepTime y\r\n |(last y)-sleepTime<0 =(y!! 0)+(1440-sleepTime)\r\n |otherwise =minimum ynew\r\n where ynew=filter (>=0) (map ((+(-sleepTime))) y)\r\n\r\nprintTime::[Int]->IO ()\r\nprintTime (x:y:_)=putStrLn$(show x)++\" \"++(show y)\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let (n:h:m:_)=map read (words line)::[Int] \r\n time<-replicateM n$do\r\n color<-getLine\r\n let (h:m:_)=map read (words color)::[Int] \r\n return (timeToMin h m) \r\n let timeNew=sort time \r\n let sleepTime=timeToMin h m \r\n printTime $minToTime$doTime sleepTime timeNew\r\n \r\n \r\n\r\n"}, {"source_code": "{-\nWhatever you do, work heartily, as for the Lord and not for men,\nknowing that from the Lord you will receive the inheritance as your reward.\nYou are serving the Lord Christ.\n- Colossians 3:23-24\n-}\n\nmodule Main\n ( main )\n where\n\nimport Control.Monad\nimport Data.List\n\ndata Time = Time\n { hours :: Int\n , minutes :: Int\n }\n deriving (Eq, Ord, Show)\n\norderAfterTime :: [Time] -> Time -> [Time]\norderAfterTime ts t = sort after ++ sort (map addHours before)\n where (before, after) = partition (< t) ts\n\naddHours :: Time -> Time\naddHours (Time h m) = Time (h + 24) m\n\nfirstAlarm :: [Time] -> Time -> Time\nfirstAlarm ts t = head $ orderAfterTime ts t\n\ntimeUntil :: Time -> Time -> Time\ntimeUntil (Time h m) (Time h' m') = Time (h' - h) (m' - m)\n\naddMinutes :: Time -> Time -> Time\naddMinutes (Time h m) a@(Time h' m')\n | m <= m' = a\n | otherwise = Time (h' - 1) (m' + 60)\n\nputTimeLn :: Time -> IO ()\nputTimeLn (Time h m) = putStrLn $ (show h) ++ \" \" ++ (show m)\n\nmain :: IO ()\nmain = do\n line <- getLine\n let testCases = read line\n\n replicateM_ testCases $ do\n line <- getLine\n let (n:h:m:_) = map read $ words line\n vladTime = Time h m\n\n alarms <- replicateM n $ do\n line <- getLine\n let (h:m:_) = map read $ words line\n return (Time h m)\n\n putTimeLn . timeUntil vladTime . addMinutes vladTime . firstAlarm alarms $ vladTime\n\n return ()\n"}], "negative_code": [{"source_code": "module Main\r\n ( main )\r\n where\r\nimport Control.Monad\r\nimport Data.List\r\ntimeToMin::Int->Int->Int\r\ntimeToMin a b=60*a+b\r\n\r\nminToTime::Int->[Int]\r\nminToTime t=[a,b]\r\n where a=t`div`60\r\n b=t-a*60\r\ndoTime::Int->[Int]->Int\r\ndoTime sleepTime y\r\n |(last y)-sleepTime<0 =(y!! 0)+(1440-sleepTime)\r\n |otherwise =(minimum ynew)-sleepTime\r\n where ynew=filter (>=0) y\r\n\r\nprintTime::[Int]->IO ()\r\nprintTime (x:y:_)=putStrLn$(show x)++\" \"++(show y)\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let (n:h:m:_)=map read (words line)::[Int] \r\n time<-replicateM n$do\r\n color<-getLine\r\n let (h:m:_)=map read (words color)::[Int] \r\n return (timeToMin h m) \r\n let timeNew=sort time \r\n let sleepTime=timeToMin h m \r\n printTime $minToTime$doTime sleepTime timeNew\r\n \r\n \r\n\r\n"}, {"source_code": "module Main\r\n ( main )\r\n where\r\nimport Control.Monad\r\nimport Data.List\r\ntimeToMin::Int->Int->Int\r\ntimeToMin a b=60*a+b\r\n\r\nminToTime::Int->[Int]\r\nminToTime t=[a,b]\r\n where a=t`div`60\r\n b=t-a*60\r\ndoTime::Int->[Int]->Int\r\ndoTime sleepTime y\r\n |(last y)-sleepTime<0 =(doTime sleepTime (map (+3600) y))+(3600-sleepTime)\r\n |otherwise =(minimum ynew)-sleepTime\r\n where ynew=filter (>=0) y\r\n\r\n\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let (n:h:m:_)=map read (words line)::[Int] \r\n time<-replicateM n$do\r\n color<-getLine\r\n let (h:m:_)=map read (words color)::[Int] \r\n return (timeToMin h m) \r\n let timeNew=sort time \r\n let sleepTime=timeToMin h m \r\n print$minToTime$doTime sleepTime timeNew\r\n \r\n \r\n\r\n"}, {"source_code": "module Main\r\n ( main )\r\n where\r\nimport Control.Monad\r\nimport Data.List\r\ntimeToMin::Int->Int->Int\r\ntimeToMin a b=60*a+b\r\n\r\nminToTime::Int->[Int]\r\nminToTime t=[a,b]\r\n where a=t`div`60\r\n b=t-a*60\r\ndoTime::Int->[Int]->Int\r\ndoTime sleepTime y\r\n |(last y)-sleepTime<0 =(doTime sleepTime (map (+3600) y))+(3600-sleepTime)\r\n |otherwise =(minimum ynew)-sleepTime\r\n where ynew=filter (>=0) y\r\n\r\n\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int\r\n print nTerm\r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let (n:h:m:_)=map read (words line)::[Int]\r\n print [n,h,m]\r\n time<-replicateM n$do\r\n color<-getLine\r\n let (h:m:_)=map read (words color)::[Int]\r\n print [h,m]\r\n return (timeToMin h m) \r\n let timeNew=sort time \r\n let sleepTime=timeToMin h m \r\n print$minToTime$doTime sleepTime timeNew\r\n \r\n \r\n\r\n"}], "src_uid": "ce0579e9c5b4c157bc89103c76ddd4c3"} {"source_code": "-- uninhm\r\n-- https://codeforces.com/contest/1529/problem/B\r\n-- greedy\r\n\r\nimport Data.List (sort)\r\n\r\nodds (x:xs) = x : evens xs\r\nodds [] = []\r\n\r\nevens (_:xs) = odds xs\r\nevens [] = []\r\n\r\n(.>) = flip (.)\r\ninfixl 8 .>\r\n\r\nfirstdiff [x] = x\r\nfirstdiff (x:y:_) = y - x\r\n\r\nsolve l = go (length l) (firstdiff $ map snd l) l where\r\n go n mindiff (x':y':xs)\r\n | y > 0 && y <= mindiff = fst y'\r\n | y > 0 = fst x'\r\n | otherwise = go n (min mindiff (y-x)) (y':xs)\r\n where\r\n y = snd y'\r\n x = snd x'\r\n\r\n go n mindiff [x] = n\r\n\r\nmain = interact $ lines\r\n .> tail\r\n .> evens\r\n .> map (show . solve . zip [1..] . sort . map read . words)\r\n .> unlines\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List (sort)\n \nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- getLine\n a <- reverse . sort . map read . words <$> getLine :: IO [Int]\n let x = takeWhile (> 0) a\n y = dropWhile (> 0) a\n print $ max (length y) $ if null x then 0 else 1 + check y (last x) (last x)\n\n\ncheck :: [Int] -> Int -> Int -> Int\ncheck [] _ _ = 0\ncheck (x:xs) p d\n | p - x >= d = 1 + check xs x d\n | otherwise = check xs p d\n \n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ncalcMinInterval :: [Int] -> Int\ncalcMinInterval [x1, x2] = x2 - x1\ncalcMinInterval (x1 : x2 : xs) = min (x2 - x1) $ calcMinInterval (x2 : xs)\ncalcMinInterval _ = error \"\"\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n _ <- getInts\n (xs, ys) <- partition (<=0) . sort <$> getInts\n let lx = length xs\n ly = length ys\n result\n | lx <= 1 = lx + min 1 ly\n | ly == 0 = lx\n | calcMinInterval xs >= head ys = lx + 1\n | otherwise = lx\n return $ intDec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "-- uninhm\r\n-- https://codeforces.com/contest/1529/problem/B\r\n-- greedy\r\n\r\nimport Data.List (sort)\r\n\r\nodds (x:xs) = x : evens xs\r\nodds [] = []\r\n\r\nevens (_:xs) = odds xs\r\nevens [] = []\r\n\r\n(.>) = flip (.)\r\ninfixl 8 .>\r\n\r\nsolve :: [Int] -> Int\r\nsolve = (\\l -> go (length l) (abs $ snd (l!!1) - snd (l!!0)) l) . zip [1..] . sort where\r\n go n mindiff (x':y':xs)\r\n | y > 0 && y <= mindiff = fst y'\r\n | y > 0 = fst x'\r\n | otherwise = go n (min mindiff (y-x)) (y':xs)\r\n where\r\n y = snd y'\r\n x = snd x'\r\n\r\n go n mindiff [x] = n\r\n\r\nmain = interact $ lines\r\n .> tail\r\n .> evens\r\n .> map (show . solve . map read . words)\r\n .> unlines\r\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nsolve [] po = True \r\nsolve [x] po = True \r\nsolve (x:xs) po \r\n | x > 0 = True\r\n | (head xs) - x < po = False \r\n | otherwise = solve xs po \r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let z = sort a \r\n ne = sum[1|x<-z,x<=0]\r\n po = if (n-ne>0) then minimum[x|x<-z, x>0] else 0\r\n r = ne + if (solve ( z) po) && po>0 then 1 else 0 \r\n print r\r\n\r\nmain = do\r\n t<-readLn::IO Int \r\n replicateM_ t printS"}], "negative_code": [{"source_code": "-- uninhm\r\n-- https://codeforces.com/contest/1529/problem/B\r\n-- greedy\r\n\r\nimport Data.List (sort)\r\n\r\nodds (x:xs) = x : evens xs\r\nodds [] = []\r\n\r\nevens (_:xs) = odds xs\r\nevens [] = []\r\n\r\n(.>) = flip (.)\r\ninfixl 8 .>\r\n\r\nbignum = 2^20\r\n\r\nsolve l = go (length l) bignum . zip [1..] . sort $ l where\r\n go n mindiff (x:xs) | mindiff == bignum && snd x > 0 = 1\r\n\r\n go n mindiff (x':y':xs)\r\n | y > 0 && y <= mindiff = fst y'\r\n | y > 0 = fst x'\r\n | otherwise = go n (min mindiff (y-x)) (y':xs)\r\n where\r\n y = snd y'\r\n x = snd x'\r\n\r\n go n mindiff [x']\r\n | x <= 0 || x <= mindiff = fst x'\r\n | otherwise = n\r\n where x = snd x'\r\n\r\nmain = interact $ lines\r\n .> tail\r\n .> evens\r\n .> map (show . solve . map read . words)\r\n .> unlines\r\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nsolve [] po = True \r\nsolve [x] po = True \r\nsolve (x:xs) po \r\n | x > 0 = True\r\n | (head xs) - x < po = False \r\n | otherwise = solve xs po \r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let z = sort a \r\n ne = sum[1|x<-z,x<=0]\r\n po = if (n-ne>0) then minimum[x|x<-z, x>0] else 0\r\n r = ne + if (solve (tail z) po) && po>0 then 1 else 0 \r\n print r\r\n\r\nmain = do\r\n t<-readLn::IO Int \r\n replicateM_ t printS"}], "src_uid": "a4b170cc058c485a50bf18982fd96851"} {"source_code": "import List\nimport Control.Monad\nimport Data.Int\n\nsolve :: [Int64] -> String\nsolve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i\n where dx = abs(x2-x1)+1\n dy = abs(y2-y1)+1\n i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)\n\nints :: Read a => Integral a => IO[a]\nints = fmap (map read . words) getLine\n\nmain = do\n [t] <- ints\n replicateM (t) ints >>= mapM_ (putStrLn.solve)\n ", "positive_code": [{"source_code": "import List\nimport Control.Monad\n\n--solve :: [Integer] -> String\nsolve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i\n where dx = abs(x2-x1)+1\n dy = abs(y2-y1)+1\n i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)\n\n--ints :: IO [Integer]\nints = fmap (map read . words) getLine\n\nmain = do\n [t] <- ints\n replicateM (fromIntegral t) ints >>= mapM_ (putStrLn.solve)\n "}, {"source_code": "import System.Environment\nimport Control.Monad\nimport Data.Set\n\nrr :: [Char] -> Integer\nrr = read\n\nri :: [Char] -> Int\nri = read\n\neach = do\n s <- getLine\n let (n:m:x1:y1:x2:y2:null) = Prelude.map rr $ words s\n let dx=abs(x1-x2)\n let dy=abs(y1-y2)\n putStrLn $ show $ n*m - 2*(n-dx)*(m-dy) + (max 0 (n-2*dx)) * (max 0 (m-2*dy) )\n\nmain = do\n s <- getLine\n let n = ri s\n replicateM n each\n"}], "negative_code": [{"source_code": "import System.Environment\nimport Control.Monad\nimport Data.Set\n\nrr :: [Char] -> Integer\nrr = read\n\nri :: [Char] -> Int\nri = read\n\neach = do\n s <- getLine\n let (n:m:x1:y1:x2:y2:null) = Prelude.map rr $ words s\n putStrLn $ show $ abs(x1-x2)*2*abs(y1-y2)\n\nmain = do\n s <- getLine\n let n = ri s\n replicateM n each\n"}, {"source_code": "import List\nimport Control.Monad\n\nsolve :: [Int] -> String\nsolve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i\n where dx = abs(x2-x1)+1\n dy = abs(y2-y1)+1\n i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)\n\nints = fmap (map read . words) getLine\n\nmain = do\n [t] <- ints\n replicateM t ints >>= mapM_ (putStrLn.solve)\n "}, {"source_code": "import List\nimport Control.Monad\n\nsolve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i\n where dx = abs(x2-x1)+1\n dy = abs(y2-y1)+1\n i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)\n\nints = fmap (map read . words) getLine\n\nmain = do\n [t] <- ints\n replicateM t ints >>= mapM_ (putStrLn.solve)\n "}], "src_uid": "8e89fc6c3dfa30ac8c3495e2b1a1e106"} {"source_code": "import Data.List\n\ndata Config = Config\n { floorSize :: (Int, Int)\n , initialPos :: (Int, Int)\n , dirtyPos :: (Int, Int)\n }\n\ndata Dir = NE | SE | NW | SW\n deriving (Show, Eq)\n\ndirection :: (Int, Int) -> Dir\ndirection (dr, dc)\n | dr < 0 && dc < 0 = NW\n | dr < 0 && dc > 0 = NE\n | dr > 0 && dc < 0 = SW\n | otherwise = SE\n\ndata Robot = Robot\n { robotPos :: (Int, Int)\n , robotDir :: (Int, Int)\n }\n\nmodifyRobotDir :: ((Int, Int) -> (Int, Int)) -> Robot -> Robot\nmodifyRobotDir f robot = let dir = robotDir robot\n in robot{ robotDir = f dir }\n\nmoveRobot :: Robot -> Robot\nmoveRobot (Robot (r,c) dir@(dr, dc)) = Robot (r + dr, c + dc) dir\n\n\nmain :: IO ()\nmain = interact robotCleaner\n\n\nreadTestCase :: String -> Config\nreadTestCase testCase = \n Config\n { floorSize = (n, m)\n , initialPos = (rb, cb)\n , dirtyPos = (rd, cd)\n }\n where\n [n, m, rb, cb, rd, cd] = read <$> words testCase\n\nrobotCleaner :: String -> String\nrobotCleaner = unlines . map (clean . readTestCase) . tail . lines\n\nclean :: Config -> String\nclean cfg = show $ length $ unfoldr go $ Robot (initialPos cfg) (1,1)\n where\n go :: Robot -> Maybe ((), Robot)\n go robot\n | checkClean (robotPos robot) (dirtyPos cfg) = Nothing\n | otherwise = Just ((), step (floorSize cfg) robot) \n\nstep :: (Int, Int) -> Robot -> Robot\nstep (n,m) robot@(Robot pos@(r,c) dir) = moveRobot $ modifyRobotDir adjust robot \n where\n adjust :: (Int, Int) -> (Int, Int)\n adjust\n | corner = reflectH . reflectV\n | vert = reflectH\n | horz = reflectV\n | otherwise = id\n where\n dir' = direction dir\n corner = (pos == (1,1) && dir' == NW) \n || (pos == (1,m) && dir' == NE)\n || (pos == (n,1) && dir' == SW)\n || (pos == (n,m) && dir' == SE)\n vert = (c == 1 && (dir' == NW || dir' == SW))\n || (c == m && (dir' == NE || dir' == SE))\n horz = (r == 1 && (dir' == NE || dir' == NW))\n || (r == n && (dir' == SE || dir' == SW)) \n\nreflectH :: (Int, Int) -> (Int, Int)\nreflectH (dr, dc) = (dr, negate dc)\n\nreflectV :: (Int, Int) -> (Int, Int)\nreflectV (dr, dc) = (negate dr, dc)\n\ncheckClean ::\n -- robot position \n (Int, Int) ->\n -- dirt position \n (Int, Int) -> \n Bool\ncheckClean (rr, rc) (dr, dc) = rr == dr || rc == dc\n\n", "positive_code": [{"source_code": "processLine :: [String] -> [Int]\nprocessLine args = do\n nums <- words <$> args\n\n let [n, m, rb, cb, rd, cd] = read <$> nums :: [Int]\n\n let {\n _go cur_r cur_c dr dc acc\n | cur_r == rd || cur_c == cd = acc\n | otherwise = _go (cur_r + new_dr) (cur_c + new_dc) new_dr new_dc (acc + 1)\n where new_dr = if cur_r == n then -dr else dr\n new_dc = if cur_c == m then -dc else dc\n }\n\n return (_go rb cb 1 1 0)\n\n\nmain = do\n input <- processLine . tail . lines <$> getContents\n\n mapM_ print input\n"}, {"source_code": "module Main where\n\nimport Control.Monad ( void, replicateM )\n\nmain :: IO ()\nmain = getLine >>= void . flip replicateM runAction . read\n\nrunAction :: IO ()\nrunAction = getLine >>= print . (\\[n,m,rb,cb,rd,cd] -> calculate n m rb cb rd cd) . map read . words\n\ncalculate :: Int -> Int -> Int -> Int -> Int -> Int -> Int\ncalculate n m rb cb rd cd = \n let dr = if rb > rd then (n - rb) + (n - rd) else rd - rb\n dc = if cb > cd then (m - cb) + (m - cd) else cd - cb\n in min dr dc"}], "negative_code": [], "src_uid": "6f819ce1d88d5211cd475a8673edba97"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Functor\nimport Data.List\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\ngetInts :: IO [Int]\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve = maximum . map length . group . sort\n\nmain :: IO ()\nmain = do [n] <- getInts\n a <- getInts\n print (n - (solve a))", "positive_code": [{"source_code": "import Data.List as List\n\ntoint s = (read s) :: Integer\n\ncomb (s,r) c =\n let ss = min s c in\n (s-ss+c,r+ss)\n\ndoit :: [Integer] -> (Integer,Integer) -> Integer -> Integer -> Integer\n\ndoit [] t a q =\n let (x,y) = comb t q in\n y\n\ndoit (x:xs) t a q =\n if x == a then\n doit xs t a (q+1)\n else\n doit xs (comb t q) x 1\n\n\nsolve::String -> String\nsolve ss =\n let s = List.sort $ map toint (tail (words ss)) in\n let r = doit s (0,0) (-1) 0 in\n (show r) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}], "negative_code": [], "src_uid": "eaa768dc1024df6449e89773234cc0c3"} {"source_code": "import Control.Monad (forM_) \n\nsolve h abs strike = (iterate (\\h -> if h >= 20 then h `div` 2 + 10 else h) h !! abs - 10*strike) <= 0\n\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\t[h, abs, strike] <- fmap (map read.words) getLine :: IO [Int]\n\t\tputStrLn $ if solve h abs strike then \"YES\" else \"NO\"", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess a b c | a<=0 =\"YES\"\n | a<=20 = if c*10 >= a then \"YES\" else \"NO\"\n\t | b==0 = if c*10 >=a then \"YES\" else \"NO\"\n | otherwise = process ((div a 2)+10) (b-1) c\n\n\nonecase = do\n\t\t[a,b,c]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tputStrLn $ process a b c\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "process :: Int -> Int -> Int -> Bool\nprocess x n m = (iterate (\\x -> x - 10) (min x (iterate (\\x -> x `div` 2 + 10) x !! n)) !! m) <= 0\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n [x,n,m] <- fmap (map readInt.words) getLine\n if process x n m\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "absorption :: Int -> Int -> Int\nabsorption x n\n | x <= 20 = x\n | n == 0 = x\n | otherwise = absorption ((div x 2) + 10) (n-1)\n\nsolve :: Int -> Int -> Int -> Bool\nsolve x n m = afterAbsorption - (m*10) <= 0\n where afterAbsorption = absorption x n\n\nparse :: String -> String\nparse input\n | solve x n m = \"YES\"\n | otherwise = \"NO\"\n where [x, n, m] = map (\\z -> read z :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (\\b -> if b then \"YES\" else \"NO\") >>> unlines\n\nprocess :: [[Int]] -> [Bool]\nprocess [] = []\nprocess ([x,n,m]:ps) = (solve x n m <= 0) : process ps\n\nsolve x n m\n | x <= 0 = 0\n | n > 0 && x >= 20 = solve (x `div` 2 + 10) (n - 1) m\n | otherwise = x - m * 10\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(|>) :: a -> (a -> b) -> b\n(|>) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [x, n, m] <- getIntList\n putStrLn . yesOrNo $ f x n m\n\nvoidA :: Int -> Int\nvoidA = (+ 10) . (`div` 2)\n\nf :: Int -> Int -> Int -> Bool\nf x n m = x |> iterate voidA |> take (n + 1) |> filter (<= (10 * m)) |> (/= [])"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [x, n, m] <- getIntList\n putStrLn . yesOrNo $ f x n m\n\nvoidA :: Int -> Int\nvoidA = (+ 10) . (`div` 2)\n\nf :: Int -> Int -> Int -> Bool\nf x n m = x \n --> iterate voidA\n --> take (n + 1)\n --> filter (<= (10 * m))\n --> (/= [])"}, {"source_code": "main = getLine >>= test . read\n\ntest 0 = return ()\ntest i = do\n (x:n:m:_) <- map read . words <$> getLine\n let x' = minimum $ take (n + 1) $ iterate va x\n if minimum (take (m + 1) $ iterate ls x') <= 0\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n test (i - 1)\n\nva h = div h 2 + 10\n\nls h = h - 10"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [x,n,m] <- (map (read ::String -> Int).words) <$> getLine\n putStrLn $ if solve x n m\n then \"YES\"\n else \"NO\"\n\nsolve :: Int -> Int -> Int -> Bool\nsolve x n m\n |x<=0 = True\n |x <=20 = x - (10*m) <= 0\n |n>0 = solve ((x `div` 2)+10) (n-1) (m)\n |otherwise = x - (10*m) <= 0\n"}, {"source_code": "yn :: Bool -> String\nyn True = \"YES\"\nyn False = \"NO\" \n\na :: Int -> Int -> Int\na 0 x = x\na n x = a (n - 1) (div x 2 + 10)\n\nsolve :: [Int] -> Bool\nsolve [x, n, m] = m * 10 >= min x (a n x)\n\nio :: String -> String\nio s = unlines $ map (yn . solve . map (read :: String -> Int) . words) $ drop 1 $ lines s\n\nmain :: IO ()\nmain = do\n interact io"}], "negative_code": [], "src_uid": "78f25e2bc4ff22dbac94f72af68a745f"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bool\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n g <- accumArray (flip const) '\\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\\u v c -> ((u, v), B.head c)) poi poi pop)\n return $ unlines $ map (map (bool 'B' 'A')) $ solve n g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]\n where\n _ = g :: UArray (Int, Int) Char\n tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool\n where\n rng = ((1, 1, 'a'), (n, n, 'z'))\n go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\nimport Data.Bool\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n g <- accumArray (flip const) '\\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\\u v c -> ((u, v), B.head c)) poi poi pop)\n return $ unlines $ map (map (bool 'B' 'A')) $ solve n g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]\n where\n _ = g :: UArray (Int, Int) Char\n tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool\n where\n rng = ((1, 1, 'a'), (n, n, 'z'))\n go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\nimport Data.Bool\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n g <- accumArray (flip const) '\\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\\u v c -> ((u, v), B.head c)) poi poi pop)\n return $ unlines $ map (map (bool 'B' 'A')) $ solve n g\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]\n where\n _ = g :: UArray (Int, Int) Char\n tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool\n where\n rng = ((1, 1, 'a'), (n, n, 'z'))\n go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]\n"}], "negative_code": [], "src_uid": "d9c77057a596c946592e73e1561aad8f"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n (cts,vs) <- splitAt(2*n).map readInt.B.words <$> B.getContents\n putStr.unlines.map show $ solve cts vs\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve cts vs= go 1 0 cts vs\n where\n go !i !time (c:t:cts) (v:vs)\n | time < v && v <=time + c*t = i : go i time (c:t:cts) vs\n | otherwise = go (i+1) (time+c*t) cts (v:vs)\n go _ _ _ _ = []", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nmain :: IO ()\nmain = do\n n <- head <$> readA\n a <- scanl1 (+) <$> replicateM n (product <$> readA)\n b <- readA\n putStr $ unlines $ map show $ gao (zip [(1::Int)..] a) b\n where\n readA = map readInt . C.words <$> C.getLine\n gao [] _ = []\n gao _ [] = []\n gao a@((i,e):t) b@(u:v)\n | u <= e = i: gao a v\n | otherwise = gao t b\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = mapM_ print . solve . map (map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, m] : xs) = map (fst . head) $ tail $ scanl f ts ms\n where\n (ls, ms : _) = splitAt n xs\n ts = zip [1..] $ scanl1 (+) $ map (foldl1 (*)) ls\n f is@((i, t) : is') m\n | m <= t = is\n | otherwise = f is' m\n"}, {"source_code": "import Control.Monad\n\ncumsum :: (Num a) => [a] -> [a]\ncumsum = cumsum_ 0\n where\n cumsum_ _ [] = []\n cumsum_ a (x:xs) = (x + a):cumsum_ (x + a) xs\n\noutputSongs :: (Num a, Ord a, Show a) => a -> [a] -> [a] -> IO ()\noutputSongs _ _ [] = return ()\noutputSongs _ [] _ = error \"\"\noutputSongs idx (x:xs) (m:ms) =\n if m <= x then do\n print idx\n outputSongs idx (x:xs) ms\n else\n outputSongs (idx + 1) xs (m:ms)\n\n\n\nmain :: IO ()\nmain = do\n [n, _] <- (map read . words) `fmap` getLine\n times <- replicateM n $ do\n [ci, ti] <- (map read . words) `fmap` getLine\n return (ci * ti :: Integer)\n\n let cumTimes = cumsum times\n\n ms <- (map read . words) `fmap` getLine\n outputSongs 1 cumTimes ms\n\n\n"}, {"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [(Int, Int)] -> [Int] -> [Int]\nsolve as vs = solve' 1 (zip [1..] as) vs\n where\n solve' _ _ [] = []\n solve' t ((i, (ci, ti)) : xs) (v:vs)\n | t' <= v = solve' t' xs (v:vs)\n | otherwise = i : solve' t ((i, (ci, ti)) : xs) vs\n where\n t' = t + ci * ti\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n as <- replicateM n readPair\n vs <- reads\n mapM_ print $ solve as vs\n\n where\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n [n, m] <- getList\n a <- replicateM n getList\n let b = scanl (+) 1 (map (\\[c, t] -> c*t) a)\n v <- getList\n mapM (print) (f b v 0 [])\n where\n f _ [] _ acc = reverse acc\n f (b:bs) (v:vs) number acc = if v < b then f (b:bs) vs number (number:acc) else f bs (v:vs) (number+1) acc\n getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine"}], "negative_code": [], "src_uid": "c4398a9f342a23baf1d7ebc9f4e9577d"} {"source_code": "import Data.List\nimport System.IO\n\nmain :: IO ()\nmain = do \n input <- getContents\n let output = solve input\n putStr output\n\n\nsolve :: String -> String\nsolve input = let num_list = map read (words input)\n t = head num_list\n n_list = tail num_list\n ans_list = map (\\x -> x:[1..x]) n_list\n all = foldl (++) [] ans_list\n all_char = map show all\n ans = foldl (\\x y->x++y++\" \") \"\" all_char\n in ans\n", "positive_code": [{"source_code": "solve :: String -> String\nsolve = concat . map go . tail . words\n where go s = unlines [s, unwords $ map show [1..read s]]\n\nmain = interact solve\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n words >>>\n drop 1 >>>\n map (read >>> solve >>> showWithLen >>> map show >>> unwords) >>> unlines\n where\n showWithLen xs = length xs : xs\n\nsolve :: Int -> [Int]\nsolve n = [1 .. n]\n"}], "negative_code": [], "src_uid": "ac248c83c99d8a2262772816b5f4ac6e"} {"source_code": "g x = if rem x 2 > 0 then -div (x+1) 2 else div x 2\ns [x,y] = g y - g (x-1)\n\nmain = interact $ unlines.map(show.s.map read.words).tail.lines", "positive_code": [{"source_code": "module Main where\nimport Data.Int\ndefault (Int64)\nmain = interact exec\nexec = unlines . map (\\(l, r) -> show $ nsum r - nsum (l - 1)) . pairs . tail . map read . words\nnsum n | s <- sgn n = (2 * s * n + s - 1) `quot` 4\npairs (x1:x2:xs) = (x1, x2):pairs xs\npairs _ = []\nsgn n | odd n = -1\n | otherwise = 1\n"}, {"source_code": "f :: Integer->Integer\nf n=let a=(n-1) `div` 2\n b=n `div` 2\n in -a*a-2*a-1+b*(b+1)\n\nf2::[String]->[String]\nf2 []=[]\nf2 (s:str)=let (a:b:[])=map read (words s)::[Integer]\n in (show ((f b)-(f (a-1)))):f2 str\n\nmain = do\n e<-getLine\n es<-getContents\n let xs=lines es\n mapM_ putStrLn $ f2 xs"}, {"source_code": "import Data.Int\n\nsum' :: Int64 -> Int64\nsum' r | r `mod` 2 == 0 = r `div` 2\n | otherwise = r `div` 2 - r\n\nsolve :: IO ()\nsolve = do\n [l, r] <- map read . words <$> getLine\n print $ sum' r - sum' (l - 1)\n\nntimes :: Int -> IO () -> IO ()\nntimes 0 _ = return ()\nntimes n io = io >> ntimes (n - 1) io\n\nmain :: IO ()\nmain = do\n t <- readLn\n ntimes t solve\n"}], "negative_code": [], "src_uid": "7eae40835f6e9580b985d636d5730e2d"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\ntype Range = (Int, Int)\r\ntype CombineFunc a = a -> a -> a\r\ntype Instruction = Int\r\ntype Program = (Int, Int, Int)\r\n\r\ndefaultProgram :: (Int, Int, Int)\r\ndefaultProgram = (0, 0, 0)\r\n\r\ncombinePrograms :: Program -> Program -> Program\r\n(aDeltaI, aDeltaL, aDeltaR) `combinePrograms` (bDeltaI, bDeltaL, bDeltaR) = (aDeltaI + bDeltaI, fst resultRange, snd resultRange)\r\n where\r\n aRange = (aDeltaL, aDeltaR)\r\n bRange = (bDeltaL + aDeltaI, bDeltaR + aDeltaI)\r\n resultRange = ((min `on` fst) aRange bRange, (max `on` snd) aRange bRange)\r\n\r\ntype ProgramArray = UA.Array Int Program\r\npresolve :: Int -> String -> (ProgramArray, ProgramArray)\r\npresolve n instructionsStr = (prefixes, suffixes)\r\n -- `debug` (\"presolve \\n\\t\" ++ show n ++ \"\\n\\t\" ++ show instructions ++ \"\\n\\t\" ++ show prefixes ++ \"\\n\\t\" ++ show suffixes)\r\n where\r\n instructions = map (\\c -> if c == '+' then 1 else -1) instructionsStr\r\n programs = map (\\i -> (i, min 0 i, max 0 i)) instructions\r\n prefixes = UA.listArray (0, n) (scanl combinePrograms defaultProgram programs)\r\n suffixes = UA.listArray (0, n) (scanr combinePrograms defaultProgram programs)\r\n \r\n\r\nsolve :: (ProgramArray, ProgramArray) -> Range -> Int \r\nsolve (prefixes, suffixes) (l, r) = resultR - resultL + 1\r\n where\r\n lProgram = prefixes UA.! (l - 1)\r\n rProgram = suffixes UA.! r\r\n rangeProgram@(_, resultL, resultR) = lProgram `combinePrograms` rProgram\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, q] <- B8.getLine <&> map readIntB8 . B8.words\r\n s <- B8.getLine <&> head . B8.words <&> B8.unpack\r\n let preAnswer = presolve n s\r\n\r\n replicateM_ q $ do\r\n [l, r] <- B8.getLine <&> map readIntB8 . B8.words\r\n let answer = solve preAnswer (l, r)\r\n printf \"%d\\n\" answer\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.Array as A\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\nimport System.IO (hSetBuffering, stdin, stdout, BufferMode (..))\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = parseInt <$> C8.getLine\n\ngetInts :: IO [Int]\ngetInts = parseInts <$> C8.getLine\n\nparseInt :: C8.ByteString -> Int\nparseInt = fst . fromJust . C8.readInt\n\nparseInts :: C8.ByteString -> [Int]\nparseInts = fmap parseInt . C8.words\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin NoBuffering\n hSetBuffering stdout NoBuffering\n t:input <- C8.lines <$> C8.getContents\n forM_ (prepareInput input) $ \\(prog, ixs) -> do\n let !arrays = buildArrays prog\n let results = (\\(l, r) -> solve arrays l r) <$> ixs\n C8.putStr . C8.unlines $ C8.pack . show <$> results\n\nprepareInput :: [C8.ByteString] -> [(C8.ByteString, [(Int, Int)])]\nprepareInput [] = []\nprepareInput (nums:prog:lst) = (prog, (\\[x, y] -> (x, y)) . parseInts <$> ixs) : prepareInput rest\n where\n [n, m] = parseInts nums\n (ixs, rest) = L.splitAt m lst\n\nbuildArrays :: C8.ByteString -> (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) \nbuildArrays str = (left2right, right2left)\n where\n nums = fmap c2n $ C8.unpack str\n\n c2n :: Char -> Int\n c2n c | c == '+' = 1\n | c == '-' = -1\n | otherwise = 0\n\n left2right :: A.Array Int (Int, Int, Int)\n left2right = A.listArray (0, length nums) $ L.scanl' minMaxFinal (0, 0, 0) nums \n right2left :: A.Array Int (Int, Int, Int)\n right2left = A.listArray (0, length nums) $ reverse $ L.scanl' minMaxFinal (0, 0, 0) $ reverse $ negate <$> nums\n\nminMaxFinal :: (Int, Int, Int) -> Int -> (Int, Int, Int)\nminMaxFinal (oldmin, oldmax, oldfin) n = \n let newfin = oldfin + n\n in (min oldmin newfin, max oldmax newfin, newfin)\n\nsolve :: (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) -> Int -> Int -> Int\nsolve (left2right, right2left) l r = ansmax - ansmin + 1\n where\n (lmin, lmax, lfin) = left2right A.! (l - 1)\n (rmin, rmax, rfin) = right2left A.! r\n\n diff = lfin - rfin\n ansmin = min lmin (rmin + diff)\n ansmax = max lmax (rmax + diff)\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad\nimport qualified Data.Array as A\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\nimport System.IO (BufferMode (..), hSetBuffering, stdin, stdout)\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = parseInt <$> C8.getLine\n\ngetInts :: IO [Int]\ngetInts = parseInts <$> C8.getLine\n\nparseInt :: C8.ByteString -> Int\nparseInt = fst . fromJust . C8.readInt\n\nparseInts :: C8.ByteString -> [Int]\nparseInts = fmap parseInt . C8.words\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin NoBuffering\n hSetBuffering stdout NoBuffering\n input <- C8.getContents\n output <- solveProblem input\n C8.putStrLn output\n \n\nsolveProblem :: C8.ByteString -> IO (C8.ByteString)\nsolveProblem str = pure $ C8.unlines $ getAns <$> preparedInput\n where\n (_:input) = C8.lines str\n preparedInput = prepareInput input\n\n getAns :: (C8.ByteString, [(Int, Int)]) -> C8.ByteString\n getAns (prog, ixs) = C8.intercalate \"\\n\" $ C8.pack . show <$> results\n where\n !arrays = buildArrays prog\n !results = (\\(l, r) -> solve arrays l r) <$> ixs\n\nprepareInput :: [C8.ByteString] -> [(C8.ByteString, [(Int, Int)])]\nprepareInput [] = []\nprepareInput (nums:prog:lst) = (prog, (\\[x, y] -> (x, y)) . parseInts <$> ixs) : prepareInput rest\n where\n [n, m] = parseInts nums\n (ixs, rest) = L.splitAt m lst\n\nbuildArrays :: C8.ByteString -> (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) \nbuildArrays str = (left2right, right2left)\n where\n nums = fmap c2n $ C8.unpack str\n\n c2n :: Char -> Int\n c2n c | c == '+' = 1\n | c == '-' = -1\n | otherwise = 0\n\n left2right :: A.Array Int (Int, Int, Int)\n left2right = A.listArray (0, length nums) $ L.scanl' minMaxFinal (0, 0, 0) nums \n right2left :: A.Array Int (Int, Int, Int)\n right2left = A.listArray (0, length nums) $ reverse $ L.scanl' minMaxFinal (0, 0, 0) $ reverse $ negate <$> nums\n\nminMaxFinal :: (Int, Int, Int) -> Int -> (Int, Int, Int)\nminMaxFinal (oldmin, oldmax, oldfin) n = \n let newfin = oldfin + n\n in (min oldmin newfin, max oldmax newfin, newfin)\n\nsolve :: (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) -> Int -> Int -> Int\nsolve (left2right, right2left) l r = ansmax - ansmin + 1\n where\n (lmin, lmax, lfin) = left2right A.! (l - 1)\n (rmin, rmax, rfin) = right2left A.! r\n\n diff = lfin - rfin\n ansmin = min lmin (rmin + diff)\n ansmax = max lmax (rmax + diff)\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype PII = (Int, Int)\ntype Input = (String, [PII])\ntype Output = [Int]\n\ninput :: Scanner Input\ninput = do\n n <- int\n m <- int\n s <- str\n qs <- m >< pair int int\n return (s, qs)\n\noutput :: Output -> C.ByteString\noutput = C.unlines . map showB\n\nsolve :: Input -> Output\nsolve (s, qs) = map query qs\n where\n query (l, r) = max mxl mxr - min mnl mnr + 1\n where\n mxl = preMax ! (l - 1)\n mnl = preMin ! (l - 1)\n delta = (preSum ! (l - 1)) - (preSum ! r)\n mxr = (sufMax ! (r + 1)) + delta\n mnr = (sufMin ! (r + 1)) + delta\n\n psum = scanl (+) 0 . map conv $ s\n\n inf = 10^9\n preSum, preMin, sufMin, preMax, sufMax :: UArray Int Int\n preSum = listArray (0, length s) psum\n preMin = listArray (0, length s) $ scanl min inf psum\n preMax = listArray (0, length s) $ scanl max (-inf) psum\n sufMin = listArray (1, length s + 1) $ scanr min inf psum\n sufMax = listArray (1, length s + 1) $ scanr max (-inf) psum\n\n\n conv :: Char -> Int\n conv '+' = 1\n conv '-' = -1\n\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "85769fb020b0d7f8e447a84a09cdddda"} {"source_code": "import Data.List\nimport Control.Monad\n\nsums :: [[Int]] -> [Int]\nsums = map sum\n\nsolve :: [[Int]] -> Int\nsolve l = \n let rows = sums l\n cols = sums $ transpose l\n in \n sum [if x < y then 1 else 0 | x <- rows, y <- cols]\n\n\nmain = do\n n <- getLine >>= (return . (read::String->Int))\n rows <- forM [1..n] (\\_ -> getLine >>= (return . map (read::String->Int) . words))\n print $ solve rows", "positive_code": [{"source_code": "import Data.List ( transpose )\n\nmain = do\n input <- getContents\n let process = putStrLn . show . winningSquares\n mapM_ process $ readLines $ lines input\n\nreadLines :: [String] -> [[[Int]]]\nreadLines [] = []\nreadLines input = (cases $ take numLines rest):(readLines $ drop numLines rest)\n where\n numLines = (read $ head input)::Int\n rest = tail input\n\ncases :: [String] -> [[Int]]\ncases [] = []\ncases (x:xs) = list:cases xs\n where\n list = (map read $ words x)::[Int]\n\nwinningSquares :: [[Int]] -> Int\nwinningSquares board = countSquares board 0 0\n where\n lines = map sum board\n columns = map sum (transpose board)\n\n countSquares :: [[Int]] -> Int -> Int -> Int\n countSquares [] _ _ = 0\n countSquares ([]:ys) i j = countSquares ys (i+1) 0\n countSquares ((x:xs):ys) i j\n | columnSum > lineSum = 1 + rec\n | otherwise = rec\n where\n columnSum = columns !! j\n lineSum = lines !! i\n rec = countSquares (xs:ys) i (j+1)\n"}, {"source_code": "import List\nm=map sum\ns t=length[0|a<-m t,b<-m$transpose t,b>a]\nmain=interact$show.s.map(map read.words).tail.lines"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tnn <- getLine\n\tinp <- getContents\n\tlet\n\t\tn = read nn :: Int\n\t\tarr1 = map (\\x -> map(\\x -> read x :: Int). words $ x). lines $ inp\n\t\tarr2 = transpose arr1\n\t\ts = sum [if sum (arr1 !! i) < sum (arr2 !! j) then 1 else 0 | i <- [0..n-1], j <- [0..n-1]]\n\tprint s\n"}, {"source_code": "import Data.List\nmain = do \n s <- getLine\n let n = read s\n c <- getContents\n let ns = take n $ map (\\x -> map read $ words x) $ lines c\n print $ sum.map (\\z -> f z (n-1) ns (transpose ns) 0) $ [0..(n-1)]\nf z (-1) ns ns' acc = acc\nf z n ns ns' acc\n |((sum $ (ns')!!z) > (sum $ ns!!n)) = f z (n-1) ns ns' (acc+1)\n | True = f z (n-1) ns ns' acc\n "}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getInts\n\n let\n ss1 = map sum a\n ss2 = map sum $ transpose a\n\n print $ length [(s1, s2) | s1 <- ss1, s2 <- ss2, s1 < s2]\n"}, {"source_code": "import Data.List (transpose, sum)\n\nmain = interact $ show . solve . lines where\n\nsolve (ns:ss) = cnt where\n n = read ns\n xs = map (map read . take n . words) (take n ss)\n ys = transpose xs\n sx = map sum xs\n sy = map sum ys\n cnt = length [(x, y) | x <- sx, y <- sy, x < y]\n"}, {"source_code": "-- ghc --make -O Main.hs\nimport Data.List (transpose)\n\nparse_input :: String -> [[Int]]\nparse_input str =\n let strs = lines str\n n = (read::String->Int) $ head $ words $ head strs -- read n from first line\n in map (map (read::String->Int).words) (take n $ tail strs ) -- read [[Int]] from n next lines\n\nsolve :: String -> String\nsolve in_str =\n let l = parse_input in_str -- [[Int]] of size n x n\n rSum = map sum l -- sum by rows\n cSum = map sum $ transpose l -- sum by columns\n in show $ length $ [True | r <- rSum, c <- cSum, c > r]\n -- show [ (r, c) | r <- rSum, c <- cSum, c > r]\n\nmain :: IO ()\nmain = do interact $ solve\n\n"}, {"source_code": "\nimport Array\n\ntest :: Array (Int, Int) Int\ntest = array ((0, 0), (n, n)) ([((0, j), 100) | j <- [0..n]] ++ [((i, j), 1) | i <- [1..n], j <- [0..n]])\n where\n n = 29\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nreadArray :: Read e => (Int, Int) -> IO (Array (Int, Int) e)\nreadArray (n, m) = do\n xss <- sequence (replicate n Main.reads)\n return (array ((0, 0), (n-1, m-1))\n [((i, j), xss !! i !! j) | i <- [0..n-1], j <- [0..m-1]])\n\nsolve :: Array (Int, Int) Int -> Int\nsolve a = length [(c, r) | c <- sumInCols, r <- sumInRows, c > r]\n where\n ((i0, j0), (i1, j1)) = bounds a\n sumInRows = map (\\i -> sum (map (\\j -> a ! (i, j)) [j0..j1])) [i0..i1]\n sumInCols = map (\\j -> sum (map (\\i -> a ! (i, j)) [i0..i1])) [j0..j1]\n\nmain :: IO ()\nmain = do\n n <- readLn\n a <- readArray (n, n)\n print $ solve a\n"}, {"source_code": "module Main where\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n let readSquares :: [Int] -> [Int] -> IO ([Int],[Int])\n readSquares rowSums colSums =\n if length rowSums == n\n then do return (rowSums,colSums)\n else do l <- getLine\n let squares = map (read :: String -> Int) (words l)\n s = sum squares\n colSums' = zipWith (+) squares colSums\n readSquares (s:rowSums) colSums'\n (rowSums, colSums) <- readSquares [] (repeat 0)\n putStrLn (show (sum [1 | rSum <- rowSums, cSum <- colSums, cSum > rSum]))\n"}, {"source_code": "import Data.Array (listArray, (!))\n\nsolve :: [[Int]] -> Int\nsolve x =\n length $ filter (\\[a, b] -> b > a) $ sequence [rowSums, colSums]\n where\n n = length x\n x' = listArray ((1,1), (n, n)) $ concat x\n rowSums = [sum [x' ! (i, j) | j <- [1..n]] | i <- [1..n]] :: [Int]\n colSums = [sum [x' ! (i, j) | i <- [1..n]] | j <- [1..n]] :: [Int]\n\nmain = do\n putStrLn . show . solve . map (map read . words) . tail . lines =<< getContents\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nmain = do\n n <- readLn\n g <- replicateM n $ fmap (map read . words) getLine\n let a = map sum g\n b = map sum $ transpose g\n k = [1 | a1 <- a, b1 <- b, a1 < b1]\n in print $ length k"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n n <- readLn\n g <- replicateM n $ fmap (map read . words) getLine\n let rs = map sum g\n cs = foldr1 (zipWith (+)) g\n print $ length [ () | r <- rs, c <- cs, c > r ]"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n table <- mapM (\\_ -> map read . words <$> getLine) [1..n]\n print $ winnerCount table\n\nwinnerCount :: [[Int]] -> Int\nwinnerCount tbl = length $ filter (isWinner tbl) possibleCoords\n where possibleCoords = [(x, y) | x <- [0..length tbl-1], y <- [0..length tbl-1]]\n\nisWinner :: [[Int]] -> (Int, Int) -> Bool\nisWinner tbl (x, y) = sumVertical > sumHorizontal\n where sumVertical = sum $ (transpose tbl) !! x\n sumHorizontal = sum $ tbl !! y\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = getLine >> do\n ss <- map (map read . words) . lines <$> getContents\n print $ solve ss\n\nsolve :: [[Int]] -> Int\nsolve ss = length [(x,y) | x<-xs, y<-ys, x B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getInts\n\n let\n ss1 = map sum a\n ss2 = map sum $ transpose a\n\n print $ length [(s1, s2) | s1 <- ss1, s2 <- ss2, s1 > s2]\n"}, {"source_code": "import Data.List (transpose)\n\nparse_input :: String -> [[Int]]\nparse_input str = tail $ map (map (read::String->Int).words) (lines str)\n\nsolve :: String -> String\nsolve in_str =\n let l = parse_input in_str\n r = map sum l -- sum by rows\n c = map sum $ transpose l -- sum by columns\n in show $ length $ [1::Int | rSum <- r, cSum <- c, rSum > cSum]\n\nmain :: IO ()\nmain = do interact $ solve\n\n"}, {"source_code": "\nimport Array\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nreadArray :: Read e => (Int, Int) -> IO (Array (Int, Int) e)\nreadArray (n, m) = do\n xss <- sequence (replicate n Main.reads)\n return (array ((0, 0), (n-1, m-1))\n [((i, j), xss !! i !! j) | i <- [0..n-1], j <- [0..m-1]])\n\nsolve :: Array (Int, Int) Int -> Int\nsolve a = length [(c, r) | c <- sumInCols, r <- sumInRows, c > r]\n where\n ((i0, j0), (i1, j1)) = bounds a\n sumInCols = map (\\i -> sum (map (\\j -> a ! (i, j)) [j0..j1])) [j0..j1]\n sumInRows = map (\\j -> sum (map (\\i -> a ! (i, j)) [i0..i1])) [j0..j1]\n\nmain :: IO ()\nmain = do\n n <- readLn\n a <- readArray (n, n)\n print $ solve a\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nmain = do\n n <- readLn\n g <- replicateM n $ fmap (map read . words) getLine\n let a = map sum g\n b = map sum $ transpose g\n k = [1 | a1 <- a, b1 <- b, a1 > b1]\n in print $ length k"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = getLine >> do\n ss <- map (map read . words) . lines <$> getContents\n print $ solve ss\n\nsolve :: [[Int]] -> Int\nsolve ss = length [(x,y) | x<-xs, y<-ys, x map(\\x -> read x :: Int). words $ x). lines $ inp\n\t\tarr2 = transpose arr1\n\t\ts = sum [if sum (arr1 !! i) > sum (arr2 !! j) then 1 else 0 | i <- [0..n-1], j <- [0..n-1]]\n\tprint s\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nsums :: [[Int]] -> [Int]\nsums = map sum\n\nsolve :: [[Int]] -> Int\nsolve l = \n let rows = sums l\n cols = sums $ transpose l\n in \n sum [if x > y then 1 else 0 | x <- rows, y <- cols]\n\n\nmain = do\n n <- getLine >>= (return . (read::String->Int))\n rows <- forM [1..n] (\\_ -> getLine >>= (return . map (read::String->Int) . words))\n print $ solve rows"}], "src_uid": "6e7c2c0d7d4ce952c53285eb827da21d"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Complex\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.ForeignPtr.Safe\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine\n lrs <- _AMunfoldrN t (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents\n res <- solve n t xs lrs\n builder <- F.foldrM (\\i b -> do\n r <- _AMunsafeRead res i\n return $! int64Dec r <> char7 '\\n' <> b\n ) mempty [0..t-1]\n hPutBuilder stdout builder\n hFlush stdout\n\n\nnothing :: Int64\nnothing = -1\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)\nsolve n t arr lrs = do\n result <- _AMunsafeNew t\n freq <- _AMreplicate (limit + 1) 0\n let ctx = MoCtx arr lrs result freq\n h <- _AMunsafeRead arr 0\n _AMunsafeWrite freq h 1\n sorted <- moSort t lrs\n void $ foldlM (\\mos i -> do\n qi <- _AMunsafeRead sorted i\n step ctx mos qi\n ) (MoS 0 0 (fromIntegral h)) [0..t-1]\n return result\n\nmoSort :: Int -> CMArray (Int, Int) -> IO (CMArray Int)\nmoSort m lrs = do\n encoded <- _AMunsafeNew m\n\n for_ [0..m-1] $ \\i -> do\n (l, r) <- _AMunsafeRead lrs i\n _AMunsafeWrite encoded i $ moEncode l r i\n\n radixSort64 encoded\n res <- _AMunsafeNew m\n for_ [0..m-1] $ \\i -> do\n qi <- moDecode <$> _AMunsafeRead encoded i\n _AMunsafeWrite res i qi\n return res\n\nradixSort64 :: CMArray Word64 -> IO ()\nradixSort64 arr0 = do\n buf <- _AMunsafeNew n\n void $ foldlM step (arr0, buf) [0, 16, 32, 48]\n where\n !n = _AMlength arr0\n step :: (CMArray Word64, CMArray Word64) -> Int -> IO (CMArray Word64, CMArray Word64)\n step (arr, buf) k = do\n _AMset buf 0\n freq <- _AMreplicate 0x10000 (0 :: Int)\n for_ [0..n-1] $ \\i -> do\n masked <- fromIntegral . (.&. 0xffff).(`unsafeShiftR` k) <$> _AMunsafeRead arr i\n _AMunsafeModify freq masked (+1)\n for_ [1..0xffff] $ \\i -> do\n f <- _AMunsafeRead freq (i - 1)\n _AMunsafeModify freq i (+f)\n for_ [1-n..0] . (.negate) $ \\i -> do\n ai <- _AMunsafeRead arr i\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> _AMunsafeRead freq masked\n _AMunsafeWrite freq masked j\n _AMunsafeWrite buf j ai\n return (buf, arr)\n\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\ndata MoQuery = MoQ\n { getL :: {-# UNPACK #-} !Int\n , getR :: {-# UNPACK #-} !Int\n , getQueryIndex :: {-# UNPACK #-} !Int\n } deriving Eq\n\ninstance Ord MoQuery where\n compare (MoQ lx rx _) (MoQ ly ry _) =\n case compare ql (quot ly moBlockSize) of\n EQ | testBit ql 0 -> compare ry rx\n | otherwise -> compare rx ry\n res -> res\n where\n !ql = quot lx moBlockSize\n\nmoEncode :: Int -> Int -> Int -> Word64\nmoEncode l r qi = unsafeShiftL l' 36 .|. unsafeShiftL r' 18 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = unsafeShiftL 1 18 - fromIntegral r\n | otherwise = fromIntegral r\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. (unsafeShiftL 1 18 - 1)\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\nmkMoQuery :: (Int, Int) -> Int -> MoQuery\nmkMoQuery (l, r) i = MoQ l r i\n\ndata MoContext = MoCtx\n { getArray :: !(CMArray Int)\n , getQuery :: !(CMArray (Int, Int))\n , getResult :: !(CMArray Int64)\n , getFreq :: !(CMArray Int)\n }\n\nstep :: MoContext -> MoState -> Int -> IO MoState\nstep (MoCtx arr query result freq) = \\(MoS l0 r0 acc) qi -> do\n let add i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f + 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n let remove i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f - 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n _AMunsafeWrite result qi acc\n (l, r) <- _AMunsafeRead query qi\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- _AMunsafeRead result qi\n return $! MoS l r res\n{-# INLINE step #-}\n\nintSqrt :: Int -> Int\nintSqrt x = floor.sqrt $ fromIntegral x\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\n\nfor_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()\nfor_ = flip traverse_\n{-# INLINE for_ #-}\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n\ndata CMArray a = CMA\n {-# UNPACK #-} !Int -- ^ offset\n {-# UNPACK #-} !Int -- ^ length\n {-# UNPACK #-} !(ForeignPtr a) -- ^ array\n deriving (Eq, Show)\n\n_AMlength :: CMArray a -> Int\n_AMlength (CMA _ l _) = l\n\n_AMunsafeTail :: CMArray a -> CMArray a\n_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc\n{-# INLINE _AMunsafeTail #-}\n\n_AMunsafeTake :: Int -> CMArray a -> CMArray a\n_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc\n{-# INLINE _AMunsafeTake #-}\n\n_AMunsafeDrop :: Int -> CMArray a -> CMArray a\n_AMunsafeDrop n (CMA o l acc) = CMA (o + n) (max 0 $ l - n) acc\n{-# INLINE _AMunsafeDrop #-}\n\n_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)\n_AMunsafeNew n = do\n arr <- mallocForeignPtrArray n\n return $! CMA 0 n arr\n{-# INLINE _AMunsafeNew #-}\n\n_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)\n_AMreplicate n x = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr -> do\n flip fix 0 $ \\loop !i ->\n when (i < n) $ do\n pokeElemOff arr i x\n loop $ i + 1\n return $ CMA 0 n ptr\n{-# INLINE _AMreplicate #-}\n\n_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)\n_AMunfoldrN n f x0 = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr ->\n fix `flip` 0 `flip` x0 $ \\loop !i !x ->\n case f x of\n Just (y, x') -> do\n pokeElemOff arr i y\n loop (i + 1) x'\n Nothing -> return $ CMA 0 n ptr\n{-# INLINE _AMunfoldrN #-}\n\n_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a\n_AMunsafeRead (CMA o l ptr) i = assert (i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o)\n{-# INLINE _AMunsafeRead #-}\n\n_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMunsafeWrite (CMA o l ptr) i x = assert (i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr (i + o) x\n{-# INLINE _AMunsafeWrite #-}\n\n_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMunsafeModify (CMA o l ptr) i f = assert (i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f\n{-# INLINE _AMunsafeModify #-}\n\n_AMset :: (Storable a) => CMArray a -> a -> IO ()\n_AMset (CMA o l ptr) x = withForeignPtr ptr $ \\arr ->\n flip fix 0 $ \\loop !i ->\n when (i < l) $ do\n pokeElemOff arr (i + o) x\n loop (i + 1)\n{-# INLINE _AMset #-}\n\ninstance (Storable a) => Storable (a, a) where\n sizeOf _ = 2 * sizeOf (undefined :: a)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined :: a)\n {-# INLINE alignment #-}\n peek p = do\n let pa = castPtr p\n !a <- peek pa\n !b <- peekElemOff pa 1\n return (a, b)\n {-# INLINE peek #-}\n poke p (a, b) = do\n let pa = castPtr p\n poke pa a\n pokeElemOff pa 1 b\n {-# INLINE poke #-}\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.ForeignPtr.Safe\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine\n lrs <- _AMunfoldrN t (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents\n res <- solve n t xs lrs\n _AMfree xs >> _AMfree lrs\n builder <- _AMfoldr' (\\x b -> int64Dec x <> char7 '\\n' <> b) mempty res\n hPutBuilder stdout builder\n hFlush stdout\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)\nsolve _ t arr lrs = do\n result <- _AMunsafeNew t\n freq <- _AMreplicate (limit + 1) 0\n let ctx = MoCtx arr lrs result freq\n h <- _AMunsafeRead arr 0\n _AMunsafeWrite freq h 1\n sorted <- moSort t lrs\n void $ _AMfoldl'M (\\mos encoded ->\n step ctx mos $ moDecode encoded\n )(MoS 0 0 (fromIntegral h)) sorted\n _AMfree freq >> _AMfree sorted\n return result\n\nmoSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)\nmoSort m lrs = do\n encoded <- _AMunsafeNew m\n\n _AMifor_ lrs $ \\i (l, r) ->\n _AMunsafeWrite encoded i $ moEncode l r i\n\n radixSort64 encoded\n return encoded\n\nradixSort64 :: CMArray Word64 -> IO ()\nradixSort64 arr0@(CMA o n _) = assert (o == 0) $ do\n buf <- _AMunsafeNew n\n freq <- _AMunsafeNew 0x10000\n void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]\n _AMfree buf >> _AMfree freq\n where\n step (arr, buf, freq) k = do\n _AMset buf 0\n _AMset freq 0\n _AMfor_ arr $ \\x -> do\n let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff\n _AMunsafeModify freq masked (+1)\n for_ [1..0xffff] $ \\i -> do\n f <- _AMunsafeRead freq (i - 1)\n _AMunsafeModify freq i (+f)\n _AMrfor_ arr $ \\ai -> do\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> _AMunsafeRead freq masked\n _AMunsafeWrite freq masked j\n _AMunsafeWrite buf j ai\n return (buf, arr, freq)\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\nmoEncode :: Int -> Int -> Int -> Word64\nmoEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = 0xfffff - fromIntegral r\n | otherwise = fromIntegral r\n{-# INLINE moEncode #-}\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. 0xfffff\n{-# INLINE moDecode #-}\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\ndata MoContext = MoCtx\n { getArray :: !(CMArray Int)\n , getQuery :: !(CMArray (Int, Int))\n , getResult :: !(CMArray Int64)\n , getFreq :: !(CMArray Int)\n }\n\nstep :: MoContext -> MoState -> Int -> IO MoState\nstep (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do\n let add i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f + 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n let remove i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f - 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n _AMunsafeWrite result qi acc\n (l, r) <- _AMunsafeRead query qi\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- _AMunsafeRead result qi\n return $! MoS l r res\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\n\nfor_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()\nfor_ = flip traverse_\n{-# INLINE for_ #-}\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n\ndata CMArray a = CMA\n {-# UNPACK #-} !Int\n {-# UNPACK #-} !Int\n {-# UNPACK #-} !(Ptr a)\n deriving (Eq, Show)\n\n_AMlength :: CMArray a -> Int\n_AMlength (CMA _ l _) = l\n\n_AMunsafeTail :: CMArray a -> CMArray a\n_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc\n{-# INLINE _AMunsafeTail #-}\n\n_AMunsafeTake :: Int -> CMArray a -> CMArray a\n_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc\n{-# INLINE _AMunsafeTake #-}\n\n_AMunsafeDrop :: Int -> CMArray a -> CMArray a\n_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc\n{-# INLINE _AMunsafeDrop #-}\n\n_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)\n_AMunsafeNew n = do\n arr <- mallocArray n\n return $! CMA 0 n arr\n{-# INLINE _AMunsafeNew #-}\n\n_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)\n_AMreplicate n x = do\n arr <- mallocArray n\n flip fix 0 $ \\loop !i ->\n when (i < n) $ do\n pokeElemOff arr i x\n loop $ i + 1\n return $ CMA 0 n arr\n{-# INLINE _AMreplicate #-}\n\n_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)\n_AMunfoldrN n f x0 = do\n arr <- mallocArray n\n fix `flip` 0 `flip` x0 $ \\loop !i !x ->\n case f x of\n Just (y, x') -> do\n pokeElemOff arr i y\n loop (i + 1) x'\n Nothing -> return $ CMA 0 n arr\n{-# INLINE _AMunfoldrN #-}\n\n_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a\n_AMunsafeRead (CMA _ l arr) i = assert (0 <= i && i < l)\n $ peekElemOff arr i\n{-# INLINE _AMunsafeRead #-}\n\n_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMunsafeWrite (CMA _ l arr) i x = assert (0 <= i && i < l)\n $ pokeElemOff arr i x\n{-# INLINE _AMunsafeWrite #-}\n\n_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMunsafeModify (CMA _ l arr) i f = assert (0 <= i && i < l)\n $ peekElemOff arr i >>= pokeElemOff arr i . f\n{-# INLINE _AMunsafeModify #-}\n\n_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a\n_AMreadArray (CMA o l arr) i = assert (0 <= i && i < l)\n $ peekElemOff arr (i + o)\n{-# INLINE _AMreadArray #-}\n\n_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMwriteArray (CMA o l arr) i x = assert (0 <= i && i < l)\n $ pokeElemOff arr (i + o) x\n{-# INLINE _AMwriteArray #-}\n\n_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMmodifyArray (CMA o l arr) i f = assert (0 <= i && i < l)\n $ peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f\n{-# INLINE _AMmodifyArray #-}\n\n_AMset :: (Storable a) => CMArray a -> a -> IO ()\n_AMset (CMA o l arr) x = do\n let end = o + l\n flip fix o $ \\loop !i ->\n when (i < end) $ do\n pokeElemOff arr i x\n loop (i + 1)\n{-# INLINE _AMset #-}\n\n_AMfree :: (Storable a) => CMArray a -> IO ()\n_AMfree (CMA _ _ arr) = free arr\n\n_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a\n_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f acc ai\n{-# INLINE _AMfoldl' #-}\n\n_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a\n_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] x0\n where\n step k i = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f ai acc\n{-# INLINE _AMfoldr' #-}\n\n_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a\n_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n f acc ai >>= k\n{-# INLINE _AMfoldl'M #-}\n\n_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMtraverse_ #-}\n\n_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMfor_ = flip _AMtraverse_\n{-# INLINE _AMfor_ #-}\n\n_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMrtraverse_ #-}\n\n_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMrfor_ = flip _AMrtraverse_\n{-# INLINE _AMrfor_ #-}\n\n_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()\n_AMitraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f i ai >> k\n{-# INLINE _AMitraverse_ #-}\n\n_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()\n_AMifor_ = flip _AMitraverse_\n{-# INLINE _AMifor_ #-}\n\ninstance (Storable a) => Storable (a, a) where\n sizeOf _ = 2 * sizeOf (undefined :: a)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined :: a)\n {-# INLINE alignment #-}\n peek p = do\n let pa = castPtr p\n !a <- peek pa\n !b <- peekElemOff pa 1\n return (a, b)\n {-# INLINE peek #-}\n poke p (a, b) = do\n let pa = castPtr p\n poke pa a\n pokeElemOff pa 1 b\n {-# INLINE poke #-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.ForeignPtr.Safe\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine\n lrs <- _AMunfoldrN t (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents\n res <- solve n t xs lrs\n builder <- _AMfoldr' (\\x b -> int64Dec x <> char7 '\\n' <> b) mempty res\n hPutBuilder stdout builder\n hFlush stdout\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)\nsolve _ t arr lrs = do\n result <- _AMunsafeNew t\n freq <- _AMreplicate (limit + 1) 0\n let ctx = MoCtx arr lrs result freq\n h <- _AMunsafeRead arr 0\n _AMunsafeWrite freq h 1\n sorted <- moSort t lrs\n void $ _AMfoldl'M (\\mos encoded ->\n step ctx mos $ moDecode encoded\n )(MoS 0 0 (fromIntegral h)) sorted\n return result\n\nmoSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)\nmoSort m lrs = do\n encoded <- _AMunsafeNew m\n\n _AMifor_ lrs $ \\i (l, r) ->\n _AMunsafeWrite encoded i $ moEncode l r i\n\n radixSort64 encoded\n return encoded\n\nradixSort64 :: CMArray Word64 -> IO ()\nradixSort64 arr0@(CMA o n _) = assert (o == 0) $ do\n buf <- _AMunsafeNew n\n freq <- _AMunsafeNew 0x10000\n void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]\n where\n step (arr, buf, freq) k = do\n _AMset buf 0\n _AMset freq 0\n _AMfor_ arr $ \\x -> do\n let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff\n _AMunsafeModify freq masked (+1)\n for_ [1..0xffff] $ \\i -> do\n f <- _AMunsafeRead freq (i - 1)\n _AMunsafeModify freq i (+f)\n _AMrfor_ arr $ \\ai -> do\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> _AMunsafeRead freq masked\n _AMunsafeWrite freq masked j\n _AMunsafeWrite buf j ai\n return (buf, arr, freq)\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\nmoEncode :: Int -> Int -> Int -> Word64\nmoEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = 0xfffff - fromIntegral r\n | otherwise = fromIntegral r\n{-# INLINE moEncode #-}\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. 0xfffff\n{-# INLINE moDecode #-}\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\ndata MoContext = MoCtx\n { getArray :: !(CMArray Int)\n , getQuery :: !(CMArray (Int, Int))\n , getResult :: !(CMArray Int64)\n , getFreq :: !(CMArray Int)\n }\n\nstep :: MoContext -> MoState -> Int -> IO MoState\nstep (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do\n let add i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f + 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n let remove i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f - 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n _AMunsafeWrite result qi acc\n (l, r) <- _AMunsafeRead query qi\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- _AMunsafeRead result qi\n return $! MoS l r res\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\n\nfor_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()\nfor_ = flip traverse_\n{-# INLINE for_ #-}\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n\ndata CMArray a = CMA\n {-# UNPACK #-} !Int -- ^ offset\n {-# UNPACK #-} !Int -- ^ length\n {-# UNPACK #-} !(ForeignPtr a) -- ^ array\n deriving (Eq, Show)\n\n_AMlength :: CMArray a -> Int\n_AMlength (CMA _ l _) = l\n\n_AMunsafeTail :: CMArray a -> CMArray a\n_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc\n{-# INLINE _AMunsafeTail #-}\n\n_AMunsafeTake :: Int -> CMArray a -> CMArray a\n_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc\n{-# INLINE _AMunsafeTake #-}\n\n_AMunsafeDrop :: Int -> CMArray a -> CMArray a\n_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc\n{-# INLINE _AMunsafeDrop #-}\n\n_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)\n_AMunsafeNew n = do\n arr <- mallocForeignPtrArray n\n return $! CMA 0 n arr\n{-# INLINE _AMunsafeNew #-}\n\n_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)\n_AMreplicate n x = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr -> do\n flip fix 0 $ \\loop !i ->\n when (i < n) $ do\n pokeElemOff arr i x\n loop $ i + 1\n return $ CMA 0 n ptr\n{-# INLINE _AMreplicate #-}\n\n_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)\n_AMunfoldrN n f x0 = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr ->\n fix `flip` 0 `flip` x0 $ \\loop !i !x ->\n case f x of\n Just (y, x') -> do\n pokeElemOff arr i y\n loop (i + 1) x'\n Nothing -> return $ CMA 0 n ptr\n{-# INLINE _AMunfoldrN #-}\n\n_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a\n_AMunsafeRead (CMA _ l ptr) i = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr i\n{-# INLINE _AMunsafeRead #-}\n\n_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMunsafeWrite (CMA _ l ptr) i x = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr i x\n{-# INLINE _AMunsafeWrite #-}\n\n_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMunsafeModify (CMA _ l ptr) i f = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr i >>= pokeElemOff arr i . f\n{-# INLINE _AMunsafeModify #-}\n\n_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a\n_AMreadArray (CMA o l ptr) i = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o)\n{-# INLINE _AMreadArray #-}\n\n_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMwriteArray (CMA o l ptr) i x = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr (i + o) x\n{-# INLINE _AMwriteArray #-}\n\n_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMmodifyArray (CMA o l ptr) i f = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f\n{-# INLINE _AMmodifyArray #-}\n\n_AMset :: (Storable a) => CMArray a -> a -> IO ()\n_AMset (CMA o l ptr) x = withForeignPtr ptr $ \\arr -> do\n let end = o + l\n flip fix o $ \\loop !i ->\n when (i < end) $ do\n pokeElemOff arr i x\n loop (i + 1)\n{-# INLINE _AMset #-}\n\n_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a\n_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] $ x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f acc ai\n{-# INLINE _AMfoldl' #-}\n\n_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a\n_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] $ x0\n where\n step k i = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f ai acc\n{-# INLINE _AMfoldr' #-}\n\n_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a\n_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] $ x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n f acc ai >>= k\n{-# INLINE _AMfoldl'M #-}\n\n_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMtraverse_ #-}\n\n_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMfor_ = flip _AMtraverse_\n{-# INLINE _AMfor_ #-}\n\n_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMrtraverse_ #-}\n\n_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMrfor_ = flip _AMrtraverse_\n{-# INLINE _AMrfor_ #-}\n\n_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()\n_AMitraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f i ai >> k\n{-# INLINE _AMitraverse_ #-}\n\n_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()\n_AMifor_ = flip _AMitraverse_\n{-# INLINE _AMifor_ #-}\n\n\ninstance (Storable a) => Storable (a, a) where\n sizeOf _ = 2 * sizeOf (undefined :: a)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined :: a)\n {-# INLINE alignment #-}\n peek p = do\n let pa = castPtr p\n !a <- peek pa\n !b <- peekElemOff pa 1\n return (a, b)\n {-# INLINE peek #-}\n poke p (a, b) = do\n let pa = castPtr p\n poke pa a\n pokeElemOff pa 1 b\n {-# INLINE poke #-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- L.unfoldr (runStateT parseInt) <$> B.getLine\n lrs <- L.unfoldr (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents\n res <- solve n t xs lrs\n builder <- F.foldrM (\\i b -> do\n r <- peekElemOff res i\n return $! int64Dec r <> char7 '\\n' <> b\n ) mempty [0..t-1]\n hPutBuilder stdout builder\n free res\n\nnothing :: Int64\nnothing = -1\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)] -> IO (Ptr Int64)\nsolve n t xs lrs = do\n arr <- mallocArray n\n result <- mallocArray t\n freq <- mallocArray (limit + 1)\n pokeArray arr xs\n pokeArray result $ replicate t nothing\n pokeArray freq $ replicate (limit + 1) 0\n let ctx = MoCtx arr result freq\n pokeElemOff freq (head xs) 1\n sorted <- moSort t lrs\n void $ foldlM (step ctx) (MoS 0 0 (fromIntegral $ head xs)) sorted\n free arr >> free freq\n return result\n\nmoSort :: Int -> [(Int, Int)] -> IO [MoQuery]\nmoSort m lrs = do\n left <- mallocArray m :: IO (Ptr Int)\n right <- mallocArray m :: IO (Ptr Int)\n encoded <- mallocArray m :: IO (Ptr Word64)\n let step :: (Ptr Word64, Ptr Word64) -> Int -> IO (Ptr Word64, Ptr Word64)\n step (arr, buf) k = do\n pokeArray buf $ replicate m 0\n freq <- mallocArray 0x10000 :: IO (Ptr Int)\n pokeArray freq $ replicate 0x10000 0\n flip traverse_ [0..m-1] $ \\i -> do\n masked <- fromIntegral . (.&. 0xffff).(`unsafeShiftR` k) <$> peekElemOff arr i\n peekElemOff freq masked >>= pokeElemOff freq masked . (+1)\n flip traverse_ [1..0xffff] $ \\i -> do\n f <- peekElemOff freq (i - 1)\n peekElemOff freq i >>= pokeElemOff freq i . (+f)\n flip traverse_ [1-m..0] . (.negate) $ \\i -> do\n ai <- peekElemOff arr i\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> peekElemOff freq masked\n pokeElemOff freq masked j\n pokeElemOff buf j ai\n return (buf, arr)\n\n F.for_ (zipWith mkMoQuery lrs [0..]) $ \\q@(MoQ l r qi) -> do\n pokeElemOff left qi l\n pokeElemOff right qi r\n pokeElemOff encoded qi $ moEncode q\n\n buf <- mallocArray m :: IO (Ptr Word64)\n (sorted, used) <- foldlM step (encoded, buf) [16, 32, 48]\n free used\n\n res <- T.forM [0..m-1] $ \\i -> do\n qi <- moDecode <$> peekElemOff sorted i\n li <- peekElemOff left qi\n ri <- peekElemOff right qi\n return $! MoQ li ri qi\n free left\n free right\n free sorted\n return res\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\ndata MoQuery = MoQ\n { getL :: {-# UNPACK #-} !Int\n , getR :: {-# UNPACK #-} !Int\n , getQueryIndex :: {-# UNPACK #-} !Int\n } deriving Eq\n\ninstance Ord MoQuery where\n compare (MoQ lx rx _) (MoQ ly ry _) =\n case compare ql (quot ly moBlockSize) of\n EQ | testBit ql 0 -> compare ry rx\n | otherwise -> compare rx ry\n res -> res\n where\n !ql = quot lx moBlockSize\n\nmoEncode :: MoQuery -> Word64\nmoEncode (MoQ l r qi) = unsafeShiftL l' 36 .|. unsafeShiftL r' 18 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = unsafeShiftL 1 18 - fromIntegral r\n | otherwise = fromIntegral r\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. (unsafeShiftL 1 18 - 1)\n\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\nmkMoQuery :: (Int, Int) -> Int -> MoQuery\nmkMoQuery (l, r) i = MoQ l r i\n\ndata MoContext = MoCtx\n { getArray :: !(Ptr Int)\n , getResult :: !(Ptr Int64)\n , getFreq :: !(Ptr Int)\n }\n\nstep :: MoContext -> MoState -> MoQuery -> IO MoState\n-- step ctx = \\st q -> return st\nstep (MoCtx arr result freq) = \\(MoS l0 r0 acc) (MoQ l r qi) -> do\n let add = \\i -> do\n x <- peekElemOff arr i\n f <- peekElemOff freq x\n pokeElemOff freq x (f + 1)\n acc <- peekElemOff result qi\n pokeElemOff result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n {-# INLINE add #-}\n let remove = \\i -> do\n x <- peekElemOff arr i\n f <- peekElemOff freq x\n pokeElemOff freq x (f - 1)\n acc <- peekElemOff result qi\n pokeElemOff result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n {-# INLINE remove #-}\n pokeElemOff result qi acc\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- peekElemOff result qi\n return $! MoS l r res\n{-# INLINE step #-}\n\nintSqrt :: Int -> Int\nintSqrt x = floor.sqrt $ fromIntegral x\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n"}, {"source_code": "{-# OPTIONS_GHC -Odph -msse4.2 -optc-O3 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.ForeignPtr.Safe\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine\n lrs <- _AMunfoldrN t (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents\n res <- solve n t xs lrs\n builder <- _AMfoldr' (\\x b -> int64Dec x <> char7 '\\n' <> b) mempty res\n hPutBuilder stdout builder\n hFlush stdout\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)\nsolve _ t arr lrs = do\n result <- _AMunsafeNew t\n freq <- _AMreplicate (limit + 1) 0\n let ctx = MoCtx arr lrs result freq\n h <- _AMunsafeRead arr 0\n _AMunsafeWrite freq h 1\n sorted <- moSort t lrs\n void $ _AMfoldl'M (\\mos encoded ->\n step ctx mos $ moDecode encoded\n )(MoS 0 0 (fromIntegral h)) sorted\n return result\n\nmoSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)\nmoSort m lrs = do\n encoded <- _AMunsafeNew m\n\n _AMifor_ lrs $ \\i (l, r) ->\n _AMunsafeWrite encoded i $ moEncode l r i\n\n radixSort64 encoded\n return encoded\n\nradixSort64 :: CMArray Word64 -> IO ()\nradixSort64 arr0@(CMA o n _) = assert (o == 0) $ do\n buf <- _AMunsafeNew n\n freq <- _AMunsafeNew 0x10000\n void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]\n where\n step (arr, buf, freq) k = do\n _AMset buf 0\n _AMset freq 0\n _AMfor_ arr $ \\x -> do\n let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff\n _AMunsafeModify freq masked (+1)\n for_ [1..0xffff] $ \\i -> do\n f <- _AMunsafeRead freq (i - 1)\n _AMunsafeModify freq i (+f)\n _AMrfor_ arr $ \\ai -> do\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> _AMunsafeRead freq masked\n _AMunsafeWrite freq masked j\n _AMunsafeWrite buf j ai\n return (buf, arr, freq)\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\nmoEncode :: Int -> Int -> Int -> Word64\nmoEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = 0xfffff - fromIntegral r\n | otherwise = fromIntegral r\n{-# INLINE moEncode #-}\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. 0xfffff\n{-# INLINE moDecode #-}\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\ndata MoContext = MoCtx\n { getArray :: !(CMArray Int)\n , getQuery :: !(CMArray (Int, Int))\n , getResult :: !(CMArray Int64)\n , getFreq :: !(CMArray Int)\n }\n\nstep :: MoContext -> MoState -> Int -> IO MoState\nstep (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do\n let add i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f + 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n let remove i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f - 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n _AMunsafeWrite result qi acc\n (l, r) <- _AMunsafeRead query qi\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- _AMunsafeRead result qi\n return $! MoS l r res\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\n\nfor_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()\nfor_ = flip traverse_\n{-# INLINE for_ #-}\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n\ndata CMArray a = CMA\n {-# UNPACK #-} !Int -- ^ offset\n {-# UNPACK #-} !Int -- ^ length\n {-# UNPACK #-} !(ForeignPtr a) -- ^ array\n deriving (Eq, Show)\n\n_AMlength :: CMArray a -> Int\n_AMlength (CMA _ l _) = l\n\n_AMunsafeTail :: CMArray a -> CMArray a\n_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc\n{-# INLINE _AMunsafeTail #-}\n\n_AMunsafeTake :: Int -> CMArray a -> CMArray a\n_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc\n{-# INLINE _AMunsafeTake #-}\n\n_AMunsafeDrop :: Int -> CMArray a -> CMArray a\n_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc\n{-# INLINE _AMunsafeDrop #-}\n\n_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)\n_AMunsafeNew n = do\n arr <- mallocForeignPtrArray n\n return $! CMA 0 n arr\n{-# INLINE _AMunsafeNew #-}\n\n_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)\n_AMreplicate n x = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr -> do\n flip fix 0 $ \\loop !i ->\n when (i < n) $ do\n pokeElemOff arr i x\n loop $ i + 1\n return $ CMA 0 n ptr\n{-# INLINE _AMreplicate #-}\n\n_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)\n_AMunfoldrN n f x0 = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr ->\n fix `flip` 0 `flip` x0 $ \\loop !i !x ->\n case f x of\n Just (y, x') -> do\n pokeElemOff arr i y\n loop (i + 1) x'\n Nothing -> return $ CMA 0 n ptr\n{-# INLINE _AMunfoldrN #-}\n\n_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a\n_AMunsafeRead (CMA _ l ptr) i = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr i\n{-# INLINE _AMunsafeRead #-}\n\n_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMunsafeWrite (CMA _ l ptr) i x = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr i x\n{-# INLINE _AMunsafeWrite #-}\n\n_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMunsafeModify (CMA _ l ptr) i f = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr i >>= pokeElemOff arr i . f\n{-# INLINE _AMunsafeModify #-}\n\n_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a\n_AMreadArray (CMA o l ptr) i = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o)\n{-# INLINE _AMreadArray #-}\n\n_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMwriteArray (CMA o l ptr) i x = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr (i + o) x\n{-# INLINE _AMwriteArray #-}\n\n_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMmodifyArray (CMA o l ptr) i f = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f\n{-# INLINE _AMmodifyArray #-}\n\n_AMset :: (Storable a) => CMArray a -> a -> IO ()\n_AMset (CMA o l ptr) x = withForeignPtr ptr $ \\arr -> do\n let end = o + l\n flip fix o $ \\loop !i ->\n when (i < end) $ do\n pokeElemOff arr i x\n loop (i + 1)\n{-# INLINE _AMset #-}\n\n_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a\n_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f acc ai\n{-# INLINE _AMfoldl' #-}\n\n_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a\n_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] x0\n where\n step k i = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f ai acc\n{-# INLINE _AMfoldr' #-}\n\n_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a\n_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n f acc ai >>= k\n{-# INLINE _AMfoldl'M #-}\n\n_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMtraverse_ #-}\n\n_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMfor_ = flip _AMtraverse_\n{-# INLINE _AMfor_ #-}\n\n_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMrtraverse_ #-}\n\n_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMrfor_ = flip _AMrtraverse_\n{-# INLINE _AMrfor_ #-}\n\n_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()\n_AMitraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f i ai >> k\n{-# INLINE _AMitraverse_ #-}\n\n_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()\n_AMifor_ = flip _AMitraverse_\n{-# INLINE _AMifor_ #-}\n\ninstance (Storable a) => Storable (a, a) where\n sizeOf _ = 2 * sizeOf (undefined :: a)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined :: a)\n {-# INLINE alignment #-}\n peek p = do\n let pa = castPtr p\n !a <- peek pa\n !b <- peekElemOff pa 1\n return (a, b)\n {-# INLINE peek #-}\n poke p (a, b) = do\n let pa = castPtr p\n poke pa a\n pokeElemOff pa 1 b\n {-# INLINE poke #-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- L.unfoldr (runStateT parseInt) <$> B.getLine\n lrs <- L.unfoldr (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents\n res <- solve n t xs lrs\n builder <- F.foldrM (\\i b -> do\n r <- peekElemOff res i\n return $! int64Dec r <> char7 '\\n' <> b\n ) mempty [0..t-1]\n hPutBuilder stdout builder\n free res\n\nnothing :: Int64\nnothing = -1\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)] -> IO (Ptr Int64)\nsolve n t xs lrs = do\n arr <- mallocArray n\n result <- mallocArray t\n freq <- mallocArray (limit + 1)\n pokeArray arr xs\n pokeArray result $ replicate t nothing\n pokeArray freq $ replicate (limit + 1) 0\n let ctx = MoCtx arr result freq\n pokeElemOff freq (head xs) 1\n sorted <- moSort t lrs\n void $ foldlM (step ctx) (MoS 0 0 (fromIntegral $ head xs)) sorted\n free arr >> free freq\n return result\n\nmoSort :: Int -> [(Int, Int)] -> IO [MoQuery]\nmoSort m lrs = do\n left <- mallocArray m :: IO (Ptr Int)\n right <- mallocArray m :: IO (Ptr Int)\n encoded <- mallocArray m :: IO (Ptr Word64)\n let step :: (Ptr Word64, Ptr Word64) -> Int -> IO (Ptr Word64, Ptr Word64)\n step (arr, buf) k = do\n pokeArray buf $ replicate m 0\n freq <- mallocArray 0x10000 :: IO (Ptr Int)\n pokeArray freq $ replicate 0x10000 0\n flip traverse_ [0..m-1] $ \\i -> do\n masked <- fromIntegral . (.&. 0xffff).(`unsafeShiftR` k) <$> peekElemOff arr i\n peekElemOff freq masked >>= pokeElemOff freq masked . (+1)\n flip traverse_ [1..0xffff] $ \\i -> do\n f <- peekElemOff freq (i - 1)\n peekElemOff freq i >>= pokeElemOff freq i . (+f)\n flip traverse_ [1-m..0] . (.negate) $ \\i -> do\n ai <- peekElemOff arr i\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> peekElemOff freq masked\n pokeElemOff freq masked j\n pokeElemOff buf j ai\n return (buf, arr)\n\n F.for_ (zipWith mkMoQuery lrs [0..]) $ \\q@(MoQ l r qi) -> do\n pokeElemOff left qi l\n pokeElemOff right qi r\n pokeElemOff encoded qi $ moEncode q\n\n buf <- mallocArray m :: IO (Ptr Word64)\n (sorted, used) <- foldlM step (encoded, buf) [16, 32, 48]\n free used\n\n res <- T.forM [0..m-1] $ \\i -> do\n qi <- moDecode <$> peekElemOff sorted i\n li <- peekElemOff left qi\n ri <- peekElemOff right qi\n return $! MoQ li ri qi\n free left\n free right\n free sorted\n return res\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\ndata MoQuery = MoQ\n { getL :: {-# UNPACK #-} !Int\n , getR :: {-# UNPACK #-} !Int\n , getQueryIndex :: {-# UNPACK #-} !Int\n } deriving Eq\n\ninstance Ord MoQuery where\n compare (MoQ lx rx _) (MoQ ly ry _) =\n case compare ql (quot ly moBlockSize) of\n EQ | testBit ql 0 -> compare ry rx\n | otherwise -> compare rx ry\n res -> res\n where\n !ql = quot lx moBlockSize\n\nmoEncode :: MoQuery -> Word64\nmoEncode (MoQ l r qi) = unsafeShiftL l' 36 .|. unsafeShiftL r' 18 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = unsafeShiftL 1 18 - fromIntegral r\n | otherwise = fromIntegral r\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. (unsafeShiftL 1 18 - 1)\n\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\nmkMoQuery :: (Int, Int) -> Int -> MoQuery\nmkMoQuery (l, r) i = MoQ l r i\n\ndata MoContext = MoCtx\n { getArray :: !(Ptr Int)\n , getResult :: !(Ptr Int64)\n , getFreq :: !(Ptr Int)\n }\n\nstep :: MoContext -> MoState -> MoQuery -> IO MoState\nstep (MoCtx arr result freq) = \\(MoS l0 r0 acc) (MoQ l r qi) -> do\n let add = \\i -> do\n x <- peekElemOff arr i\n f <- peekElemOff freq x\n pokeElemOff freq x (f + 1)\n acc <- peekElemOff result qi\n pokeElemOff result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n {-# INLINE add #-}\n let remove = \\i -> do\n x <- peekElemOff arr i\n f <- peekElemOff freq x\n pokeElemOff freq x (f - 1)\n acc <- peekElemOff result qi\n pokeElemOff result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n {-# INLINE remove #-}\n pokeElemOff result qi acc\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- peekElemOff result qi\n return $! MoS l r res\n{-# INLINE step #-}\n\nintSqrt :: Int -> Int\nintSqrt x = floor.sqrt $ fromIntegral x\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Bits\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Int\nimport qualified Data.List as L\nimport Data.Monoid\nimport qualified Data.Traversable as T\nimport Data.Word\nimport System.IO\n--\nimport Foreign.ForeignPtr.Safe\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n [n, t] <- map read.words <$> getLine\n xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine\n lrs <- _AMunfoldrN t (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents\n res <- solve n t xs lrs\n builder <- _AMfoldr' (\\x b -> int64Dec x <> char7 '\\n' <> b) mempty res\n hPutBuilder stdout builder\n hFlush stdout\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)\nsolve _ t arr lrs = do\n result <- _AMunsafeNew t\n freq <- _AMreplicate (limit + 1) 0\n let ctx = MoCtx arr lrs result freq\n h <- _AMunsafeRead arr 0\n _AMunsafeWrite freq h 1\n sorted <- moSort t lrs\n void $ _AMfoldl'M (\\mos encoded ->\n step ctx mos $ moDecode encoded\n )(MoS 0 0 (fromIntegral h)) sorted\n return result\n\nmoSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)\nmoSort m lrs = do\n encoded <- _AMunsafeNew m\n\n _AMifor_ lrs $ \\i (l, r) ->\n _AMunsafeWrite encoded i $ moEncode l r i\n\n radixSort64 encoded\n return encoded\n\nradixSort64 :: CMArray Word64 -> IO ()\nradixSort64 arr0@(CMA o n _) = assert (o == 0) $ do\n buf <- _AMunsafeNew n\n freq <- _AMunsafeNew 0x10000\n void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]\n where\n step (arr, buf, freq) k = do\n _AMset buf 0\n _AMset freq 0\n _AMfor_ arr $ \\x -> do\n let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff\n _AMunsafeModify freq masked (+1)\n for_ [1..0xffff] $ \\i -> do\n f <- _AMunsafeRead freq (i - 1)\n _AMunsafeModify freq i (+f)\n _AMrfor_ arr $ \\ai -> do\n let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff\n j <- subtract 1 <$> _AMunsafeRead freq masked\n _AMunsafeWrite freq masked j\n _AMunsafeWrite buf j ai\n return (buf, arr, freq)\n\nmoBlockSize :: Int\nmoBlockSize = 450\n{-# INLINE moBlockSize #-}\n\nmoEncode :: Int -> Int -> Int -> Word64\nmoEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi\n where\n l' = fromIntegral $ quot l moBlockSize\n r' | testBit l' 0 = 0xfffff - fromIntegral r\n | otherwise = fromIntegral r\n{-# INLINE moEncode #-}\n\nmoDecode :: Word64 -> Int\nmoDecode bits = fromIntegral $ bits .&. 0xfffff\n{-# INLINE moDecode #-}\n\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\ndata MoContext = MoCtx\n { getArray :: !(CMArray Int)\n , getQuery :: !(CMArray (Int, Int))\n , getResult :: !(CMArray Int64)\n , getFreq :: !(CMArray Int)\n }\n\nstep :: MoContext -> MoState -> Int -> IO MoState\nstep (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do\n let add i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f + 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x\n let remove i = do\n x <- _AMunsafeRead arr i\n f <- _AMunsafeRead freq x\n _AMunsafeWrite freq x (f - 1)\n acc <- _AMunsafeRead result qi\n _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x\n _AMunsafeWrite result qi acc\n (l, r) <- _AMunsafeRead query qi\n traverse_ add [r0+1..r]\n traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]\n traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]\n traverse_ remove [l0..l-1]\n res <- _AMunsafeRead result qi\n return $! MoS l r res\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\ntraverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()\ntraverse_ f = foldr((>>).f)(return())\n{-# INLINE traverse_ #-}\n\nfor_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()\nfor_ = flip traverse_\n{-# INLINE for_ #-}\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n\ndata CMArray a = CMA\n {-# UNPACK #-} !Int -- ^ offset\n {-# UNPACK #-} !Int -- ^ length\n {-# UNPACK #-} !(ForeignPtr a) -- ^ array\n deriving (Eq, Show)\n\n_AMlength :: CMArray a -> Int\n_AMlength (CMA _ l _) = l\n\n_AMunsafeTail :: CMArray a -> CMArray a\n_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc\n{-# INLINE _AMunsafeTail #-}\n\n_AMunsafeTake :: Int -> CMArray a -> CMArray a\n_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc\n{-# INLINE _AMunsafeTake #-}\n\n_AMunsafeDrop :: Int -> CMArray a -> CMArray a\n_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc\n{-# INLINE _AMunsafeDrop #-}\n\n_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)\n_AMunsafeNew n = do\n arr <- mallocForeignPtrArray n\n return $! CMA 0 n arr\n{-# INLINE _AMunsafeNew #-}\n\n_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)\n_AMreplicate n x = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr -> do\n flip fix 0 $ \\loop !i ->\n when (i < n) $ do\n pokeElemOff arr i x\n loop $ i + 1\n return $ CMA 0 n ptr\n{-# INLINE _AMreplicate #-}\n\n_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)\n_AMunfoldrN n f x0 = do\n ptr <- mallocForeignPtrArray n\n withForeignPtr ptr $ \\arr ->\n fix `flip` 0 `flip` x0 $ \\loop !i !x ->\n case f x of\n Just (y, x') -> do\n pokeElemOff arr i y\n loop (i + 1) x'\n Nothing -> return $ CMA 0 n ptr\n{-# INLINE _AMunfoldrN #-}\n\n_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a\n_AMunsafeRead (CMA _ l ptr) i = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr i\n{-# INLINE _AMunsafeRead #-}\n\n_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMunsafeWrite (CMA _ l ptr) i x = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr i x\n{-# INLINE _AMunsafeWrite #-}\n\n_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMunsafeModify (CMA _ l ptr) i f = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr i >>= pokeElemOff arr i . f\n{-# INLINE _AMunsafeModify #-}\n\n_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a\n_AMreadArray (CMA o l ptr) i = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o)\n{-# INLINE _AMreadArray #-}\n\n_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()\n_AMwriteArray (CMA o l ptr) i x = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n pokeElemOff arr (i + o) x\n{-# INLINE _AMwriteArray #-}\n\n_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()\n_AMmodifyArray (CMA o l ptr) i f = assert (0 <= i && i < l)\n . withForeignPtr ptr $ \\arr ->\n peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f\n{-# INLINE _AMmodifyArray #-}\n\n_AMset :: (Storable a) => CMArray a -> a -> IO ()\n_AMset (CMA o l ptr) x = withForeignPtr ptr $ \\arr -> do\n let end = o + l\n flip fix o $ \\loop !i ->\n when (i < end) $ do\n pokeElemOff arr i x\n loop (i + 1)\n{-# INLINE _AMset #-}\n\n_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a\n_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f acc ai\n{-# INLINE _AMfoldl' #-}\n\n_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a\n_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] x0\n where\n step k i = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n k $ f ai acc\n{-# INLINE _AMfoldr' #-}\n\n_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a\n_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0\n where\n step i k = \\ !acc -> do\n ai <- _AMunsafeRead arr i\n f acc ai >>= k\n{-# INLINE _AMfoldl'M #-}\n\n_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMtraverse_ #-}\n\n_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMfor_ = flip _AMtraverse_\n{-# INLINE _AMfor_ #-}\n\n_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()\n_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f ai >> k\n{-# INLINE _AMrtraverse_ #-}\n\n_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()\n_AMrfor_ = flip _AMrtraverse_\n{-# INLINE _AMrfor_ #-}\n\n_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()\n_AMitraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]\n where\n step i k = do\n ai <- _AMunsafeRead arr i\n f i ai >> k\n{-# INLINE _AMitraverse_ #-}\n\n_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()\n_AMifor_ = flip _AMitraverse_\n{-# INLINE _AMifor_ #-}\n\ninstance (Storable a) => Storable (a, a) where\n sizeOf _ = 2 * sizeOf (undefined :: a)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined :: a)\n {-# INLINE alignment #-}\n peek p = do\n let pa = castPtr p\n !a <- peek pa\n !b <- peekElemOff pa 1\n return (a, b)\n {-# INLINE peek #-}\n poke p (a, b) = do\n let pa = castPtr p\n poke pa a\n pokeElemOff pa 1 b\n {-# INLINE poke #-}\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Reader\nimport Control.Monad.Trans.State\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Int\nimport Data.Ix\nimport qualified Data.List as L\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Traversable as T\nimport System.IO\n--\nimport Data.Time.Clock\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport Foreign.Storable\n\nmain :: IO ()\nmain = do\n hSetBinaryMode stdin True\n hSetBinaryMode stdout True\n !start <- getCurrentTime\n [n, t] <- map read.words <$> getLine\n xs <- L.unfoldr (runStateT parseInt) <$> B.getLine\n lrs <- L.unfoldr (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents\n !res <- solve n t xs lrs\n !end <- getCurrentTime\n when (n == 200000) $ do\n print $ diffUTCTime end start\n hPutBuilder stdout $ foldr(\\x l -> (int64Dec x <> char7 '\\n') <> l) mempty res\n\nnothing :: Int64\nnothing = -1\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)] -> IO [Int64]\nsolve n t xs lrs = do\n result <- mallocArray t\n pokeArray result $ replicate t nothing\n freq <- mallocArray (limit + 1)\n pokeArray freq $ replicate (limit + 1) 0\n flip runReaderT (MoCtx arr result freq) $ do\n lift $ pokeElemOff freq (arr ! UI 0) 1\n void $ foldlM step (MoS 0 0 (fromIntegral $ arr ! UI 0)) sorted\n T.mapM (peekElemOff result) [0..t-1]\n\n where\n !blockSize = intSqrt n\n arr :: UArray UnsafeIx Int\n !arr = listArray (UI 0, UI (n - 1)) xs\n sorted :: [MoQuery]\n sorted = L.sortBy (comparing $ moCmp blockSize) $ zipWith mkMoQuery lrs [0..]\n\ndata MoQuery = MoQ\n { getL :: {-# UNPACK #-} !Int\n , getR :: {-# UNPACK #-} !Int\n , getQueryIndex :: {-# UNPACK #-} !Int\n } deriving (Eq, Ord)\ndata MoState = MoS\n { moL :: {-# UNPACK #-} !Int\n , moR :: {-# UNPACK #-} !Int\n , moA :: {-# UNPACK #-} !Int64\n } deriving (Eq, Ord)\n\nmoCmp :: Int -> MoQuery -> (Int, Int)\nmoCmp blockSize (MoQ l r _)\n | testBit q 0 = (q, -r)\n | otherwise = (q, r)\n where\n !q = l `quot` blockSize\n\nmkMoQuery :: (Int, Int) -> Int -> MoQuery\nmkMoQuery (l, r) i = MoQ l r i\n\ndata MoContext = MoCtx\n { getArray :: UArray UnsafeIx Int\n , getResult :: !(Ptr Int64)\n , getFreq :: !(Ptr Int)\n }\n\ntype MoReader a = ReaderT MoContext IO a\n\nadd :: Int64 -> Int -> MoReader Int64\nadd !acc i = ReaderT $ \\(MoCtx arr _ freq) -> do\n let !x = arr ! UI i\n f <- peekElemOff freq x\n pokeElemOff freq x $! (f + 1)\n return $! acc + fromIntegral (2 * f + 1) * fromIntegral x\n{-# INLINE add #-}\n\nremove :: Int64 -> Int -> MoReader Int64\nremove !acc i = ReaderT $ \\(MoCtx arr _ freq) -> do\n let !x = arr ! UI i\n f <- peekElemOff freq x\n pokeElemOff freq x $! (f - 1)\n return $! acc - fromIntegral (2 * f - 1) * fromIntegral x\n{-# INLINE remove #-}\n\nstep :: MoState -> MoQuery -> MoReader MoState\nstep (MoS l0 r0 acc) (MoQ l r qi) = do\n addR <- foldlM add acc [r0+1..r]\n removeR <- foldlM remove addR [r0, r0-1..r+1]\n addL <- foldlM add removeR [l0-1, l0-2..l]\n removeL <- foldlM remove addL [l0..l-1]\n result <- asks getResult\n lift $ pokeElemOff result qi removeL\n return $ MoS l r removeL\n-- {-# INLINE step #-}\n\nintSqrt :: Int -> Int\nintSqrt x = floor.sqrt $ fromIntegral x\n\nnewtype UnsafeIx = UI{unUI:: Int} deriving (Eq, Ord)\n\ninstance Ix UnsafeIx where\n range (_, UI r) = map UI [0..r]\n {-# INLINE range #-}\n index _ (UI i) = i\n {-# INLINE index #-}\n inRange _ _ = True\n {-# INLINE inRange #-}\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n{-# INLINE parseInt #-}\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n{-# INLINE parseInt2 #-}\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Reader\nimport Control.Monad.Trans.State\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Int\nimport Data.Ix\nimport qualified Data.List as L\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n [n, t] <- map read.words <$> getLine\n xs <- L.unfoldr (runStateT parseInt) <$> B.getLine\n lrs <- L.unfoldr (runStateT $ (\\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents\n putStr.unlines.map show $ solve n t xs lrs\n\nnothing :: Int64\nnothing = -1\n\nlimit :: Int\nlimit = 1000000\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)] -> [Int64]\nsolve n t xs lrs = elems results\n where\n !blockSize = intSqrt n\n arr :: UArray UnsafeIx Int\n !arr = listArray (UI 0, UI (n - 1)) xs\n sorted :: [MoQuery]\n sorted = L.sortBy (comparing $ \\q -> (getL q `quot` blockSize, getR q)) $ zipWith mkMoQuery lrs [0..]\n results :: UArray UnsafeIx Int64\n !results = runSTUArray $ do\n result <- newArray (UI 0, UI (t - 1)) nothing :: ST s (STUArray s UnsafeIx Int64)\n freq <- newArray (UI 0, UI limit) 0 :: ST s (STUArray s UnsafeIx Int64)\n flip runReaderT (Mo arr result freq) $ do\n lift $ writeArray freq (UI $ arr! UI 0) 1\n void $ foldlM step ((0, 0), fromIntegral $ arr ! UI 0) sorted\n asks getResult\n\ndata MoQuery = MoQ\n { getL :: {-# UNPACK #-} !Int\n , getR :: {-# UNPACK #-} !Int\n , getQueryIndex :: {-# UNPACK #-} !Int\n }\nmkMoQuery :: (Int, Int) -> Int -> MoQuery\nmkMoQuery (l, r) i = MoQ l r i\n\ndata MoContext s = Mo\n { getArray :: UArray UnsafeIx Int\n , getResult :: STUArray s UnsafeIx Int64\n , getFreq :: STUArray s UnsafeIx Int64\n }\n\ntype MoReader s a = ReaderT (MoContext s) (ST s) a\n\nadd :: Int64 -> Int -> MoReader s Int64\nadd acc i = do\n x <- asks $ UI . (! (UI i)) . getArray\n freq <- asks getFreq\n lift $ do\n f <- readArray freq x\n writeArray freq x (f + 1)\n return $! acc + (2 * f + 1) * fromIntegral (unUI x)\n\nremove :: Int64 -> Int -> MoReader s Int64\nremove acc i = do\n x <- asks $ UI . (! (UI i)) . getArray\n freq <- asks getFreq\n lift $ do\n f <- readArray freq x\n writeArray freq x (f + 1)\n return $! acc - (2 * f - 1) * fromIntegral (unUI x)\n\nstep :: ((Int, Int), Int64) -> MoQuery -> MoReader s ((Int, Int), Int64)\nstep ((l0, r0), acc) (MoQ l r qi) = do\n addR <- foldlM add acc [r0+1..r]\n removeR <- foldlM remove addR [r0, r0-1..r+1]\n addL <- foldlM add removeR [l0-1, l0-2..l]\n removeL <- foldlM remove addL [l0..l-1]\n result <- asks getResult\n lift $ writeArray result (UI qi) removeL\n return ((l, r), removeL)\n\nintSqrt :: Int -> Int\nintSqrt x = floor.sqrt $ fromIntegral x\n\nnewtype UnsafeIx = UI{unUI:: Int} deriving (Eq, Ord)\n\ninstance Ix UnsafeIx where\n range (UI l, UI r) = map UI [l..r]\n {-# INLINE range #-}\n index _ (UI i) = i\n {-# INLINE index #-}\n inRange _ _ = True\n {-# INLINE inRange #-}\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nfoldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldlM #-}\n"}], "src_uid": "82e3538887746bc83d1098b4380db64b"} {"source_code": "import Data.Sequence\n\n\nsolve :: Bool -> Int -> Int -> Seq Int -> (Int, Int, Int)\nsolve _ 0 _ Empty = (0,0,0)\nsolve True cur pre Empty = (1, cur, 0)\nsolve True cur pre (c:<|cs)\n | cur > pre = (turns+1, cur+ta,tb)\n | otherwise = solve True (cur+c) pre cs\n where\n (turns,ta,tb) = solve False 0 cur (c:<|cs)\nsolve False cur pre Empty = (1, 0, cur)\nsolve False cur pre (cs:|>c)\n | cur > pre = (turns+1, ta,cur+tb)\n | otherwise = solve False (cur+c) pre cs\n where\n (turns,ta,tb) = solve True 0 cur (cs:|>c)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n cs <- readNums\n let (turns,a,b) = solve True 0 0 $ fromList cs\n putStrLn $ unwords $ map show [turns,a,b]\n testCases (t-1)\n\ntest :: (Int,Int,Int)\ntest = solve True 0 0 $ fromList [3,1,4,1,5,9,2,6,5,3,5]\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n getLine\n ans <- map (solve . map read . words) <$> joiner <$> lines <$> getContents\n mapM_ (putStrLn . f) ans\n\nsolve :: [Int] -> [Int]\nsolve xs =\n let len = head xs\n list = tail xs\n revlist = reverse list\n in function len list revlist 0 0 0 0 (0,0)\n\n-- length list revlist totalEaten turns aliceEaten bobEaten turn(alice/bob)\nfunction :: Int -> [Int] -> [Int] -> Int -> Int -> Int -> Int -> (Int,Int) -> [Int]\nfunction 0 _ _ turns alice bob _ (x,y) = [turns, x, y]\n\nfunction length list revlist i alice bob 0 (x,y) =\n let remaining = take length list\n (count, size) = eat remaining bob (0, 0)\n list' = drop count list\n alice' = size\n length' = length - count\n in function length' list' revlist (i+1) alice' bob 1 (x+alice',y)\n\nfunction length list revlist i alice bob 1 (x,y) =\n let remaining = take length revlist\n (count, size) = eat remaining alice (0, 0)\n revlist' = drop count revlist\n bob' = size\n length' = length - count\n in function length' list revlist' (i+1) alice bob' 0 (x, y + bob')\n\neat :: [Int] -> Int -> (Int, Int) -> (Int, Int)\neat [] _ (count, size) = (count, size)\neat (x : xs) y (count, size)\n | y < 0 = (count, size)\n | otherwise = eat xs (y - x) (count + 1, size + x)\n\nf :: [Int] -> String\nf xs = unwords . map show $ xs\n\njoiner :: [String] -> [String]\njoiner [] = []\njoiner (x : y : xs) = (x ++ \" \" ++ y) : joiner xs\n"}], "negative_code": [], "src_uid": "d70ee6d3574e0f2cac3c683729e2979d"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\n-- Codeforces 404B\n\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Data.Fixed (mod') -- important !!\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n [a, d] <- fmap (map read . words) getLine\n n <- fmap read getLine\n newCString \"%.8lf %.8lf\\n\" >>= solve a d n\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Double -> Double -> IO CInt\n\nsolve :: Double -> Double -> Int -> CString -> IO ()\nsolve a d n format = mapM_ (ps . handle . (*) d . fromIntegral) [1..n] where\n handle p = case p `mod'` (4*a) of\n q | q < a -> (q, 0)\n q | q < 2 * a -> (a, q-a)\n q | q < 3 * a -> (3*a-q, a)\n q | otherwise -> (0, 4*a-q)\n ps (a, b) = c_printf format a b where\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Foreign.C.Types\nimport Foreign.C.String\n\nmain = do\n [a,d,n] <- map read.words <$> getContents\n solve (round n) a d\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf :: CString -> Double -> Double -> IO ()\n\nputAnswer :: Double -> Double -> IO ()\nputAnswer x y = B.useAsCString \"%f %f\\n\" $ \\fmt-> do\n c_printf fmt x y\n\nsolve :: Int -> Double -> Double -> IO ()\nsolve n a d = go 1\n where\n go i = do\n when (i<=n) $ do\n let q = fromIntegral.floor $ (fromIntegral i*d) / (4*a)\n x = fromIntegral i*d - q*4*a\n if x <= 1*a then putAnswer x 0\n else if x <= 2*a then putAnswer a (x-a)\n else if x <= 3*a then putAnswer (a-(x-2*a)) a\n else putAnswer 0 (a-(x-3*a))\n go (i+1)"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Data.Fixed\nimport qualified Data.ByteString.Lazy as B\nimport qualified Data.ByteString.Lazy.Char8 as B8\nimport Control.Applicative\nimport System.IO\nimport Control.DeepSeq\nimport Text.Printf\n \nmain = do\n inp <- words <$> getContents\n solve inp\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Double -> Double -> IO CInt\n \nsolve [sa, sd, sn] = do\n format <- newCString \"%.6lf %.6lf\\n\"\n let a = read sa :: Double\n d = read sd :: Double\n n = read sn :: Int\n ps :: (Double, Double) -> IO ()\n ps (a, b) = do\n c_printf format a b\n return ()\n \n dtoc p = case mod' p (4 * a) of\n q | q < a -> (q, 0)\n q | q < 2 * a -> (a, q - a)\n q | q < 3 * a -> (3 * a - q, a)\n q | otherwise -> (0, 4 * a - q)\n mapM_ (ps . dtoc . (*)d . fromIntegral) [1 .. n]\n\n"}], "negative_code": [{"source_code": "-- Codeforces 404B\n\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n [a, d] <- fmap (map read . words) getLine\n n <- fmap read getLine\n putStrLn $ intercalate \"\\n\" $ solve a d n\n\nsolve :: Double -> Double -> Int -> [String]\nsolve a d n = map path [1..n] where\n path :: Int -> String\n path i = case k `mod` 4 of {\n 0 -> str h 0;\n 1 -> str a h;\n 2 -> str (a-h) a;\n 3 -> str 0 (a-h);\n } where\n l = (fromIntegral i) * d\n k = floor (l / a) :: Int\n h = l - (fromIntegral k) * a\n str :: Double -> Double -> String\n str x y = (show x) ++ \" \" ++ (show y)\n"}, {"source_code": "-- Codeforces 404B\n\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n [a, d] <- fmap (map read . words) getLine\n n <- fmap read getLine\n putStrLn $ intercalate \"\\n\" $ solve a d n\n\nsolve :: Double -> Double -> Int -> [String]\nsolve a d n = map path [1..n] where\n path :: Int -> String\n path i = case k `mod` 4 of {\n 0 -> str h 0;\n 1 -> str a h;\n 2 -> str (a-h) a;\n 3 -> str 0 (a-h);\n } where\n l = (fromIntegral i) * d\n k = floor (l / a) :: Int\n h = l - (fromIntegral k) * a\n str :: Double -> Double -> String\n str x y = (show x) ++ \" \" ++ (show y)\n\n"}], "src_uid": "d00b8423c3c52b19fec25bc63e4d4c1c"} {"source_code": "import Data.List\nntobits = reverse . go 8 where\n go 0 _ = []\n go i n = odd n : go (i-1) (n `div` 2)\ntobits ns = ns >>= ntobits\nipwords [] = []\nipwords s = case span(/='.') s of\n (l,r) -> l : ipwords (drop 1 r)\npip=map(foldl(\\a c->a*10+fromEnum c-fromEnum '0')0).ipwords\n\nfrombitsn=foldl(\\n b-> n*2+fromEnum b)0\nfrombits=map frombitsn.unfoldr uf where\n uf [] = Nothing\n uf l = Just $ splitAt 8 l\npr m=intercalate \".\"$map show$frombits$replicate m True ++ replicate (32-m) False\nbsearch f a b | a + 1 == b = a\n | f c = bsearch f a c\n | otherwise = bsearch f c b where\n c = (a + b)`div`2\ns k l\n | k == g r = pr r\n | otherwise = \"-1\"\n where\n r = min 31 $ bsearch f 0 32 + 1\n g i = length(group$map(take i)l)\n f i = g i >= k\nsolve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl\nmain=interact$solve.lines\n", "positive_code": [{"source_code": "import Data.ByteString.Char8 as BS (getLine, readInt, split, words)\nimport Data.Bits ((.&.), shiftL)\nimport Data.Maybe (fromJust)\nimport Data.List (intersperse)\nimport Data.Set as Set (fromList, size)\n\nmain = do\n [n, k] <- fmap (map readInt' . BS.words) BS.getLine\n ips <- fmap (map fromIP) $ sequence $ replicate n BS.getLine\n let subnets = scanl1 (+) $ map (1 `shiftL`) [31,30..0]\n case filter (check k ips) subnets of\n [] -> print (-1)\n subnet:_ -> putStrLn $ toIP subnet\n\ncheck k ips subnet = (==k) $ Set.size $ Set.fromList $ map (subnet .&.) ips\n\nreadInt' = fst . fromJust . BS.readInt\n\nfromIP s = sum $ zipWith (*) (map (256^) [3,2,1,0]) $ map readInt' $ BS.split '.' s\n\ntoIP x = concat $ intersperse \".\" $ reverse $ map (show . (`mod` 256)) $ scanl div x $ replicate 3 256\n"}, {"source_code": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\nimport Data.Bits\nimport Data.List\nimport Data.Maybe\nimport Data.Word\nimport qualified Data.ByteString.Char8 as C\n\nnewtype IP = IP Word32\n deriving (Eq, Ord, Num, Bits)\n\ninstance Show IP where\n show (IP ip) = intercalate \".\" $ map show $\n reverse $ map (`mod`256) $ take 4 $ iterate (`div`256) $ ip\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nparse :: C.ByteString -> IP\nparse s = IP $ foldl1 (\\i j -> (i * 256 + j)) $ map (fromIntegral . readInt) $ C.split '.' s\n\nclz :: (Num a, Bits a) => a -> Int\nclz x\n | x == 0 = n\n | otherwise = m - until (testBit x) pred m\n where\n n = bitSize x\n m = n - 1\n\nmain :: IO ()\nmain = do\n (sn:sm:s) <- fmap C.words C.getContents\n let _ = readInt sn\n m = readInt sm\n a = sort $ map parse s\n b = [i | i <- masks, let j = map (.&. i) a, length (group j) == m]\n if null b\n then putStrLn \"-1\"\n else putStrLn $ show $ head b\n where\n masks = scanl1 (.|.) $ map (IP . bit) $ [31, 30 .. 0]\n"}], "negative_code": [{"source_code": "import Data.List\nntobits = reverse . go 8 where\n go 0 _ = []\n go i n = odd n : go (i-1) (n `div` 2)\ntobits ns = ns >>= ntobits\nipwords [] = []\nipwords s = case span(/='.') s of\n (l,r) -> l : ipwords (drop 1 r)\npip=map read.ipwords\n\nfrombitsn=foldl(\\n b-> n*2+fromEnum b)0\nfrombits=map frombitsn.unfoldr uf where\n uf [] = Nothing\n uf l = Just $ splitAt 8 l\npr[]=\"-1\"\npr(m:_)=intercalate \".\"$map show$frombits$replicate m True ++ replicate (32-m) False\ns k l=pr$filter(\\i->k==length(nub$map(take i)l))[0..32] where\nsolve(hl:rl)=s((!!1).map read.words$hl).map(tobits.pip)$rl\nmain=interact$solve.lines\n"}, {"source_code": "import Data.List\nntobits = reverse . go 8 where\n go 0 _ = []\n go i n = odd n : go (i-1) (n `div` 2)\ntobits ns = ns >>= ntobits\nipwords [] = []\nipwords s = case span(/='.') s of\n (l,r) -> l : ipwords (drop 1 r)\npip=map(foldl(\\a c->a*10+fromEnum c-fromEnum '0')0).ipwords\n\nfrombitsn=foldl(\\n b-> n*2+fromEnum b)0\nfrombits=map frombitsn.unfoldr uf where\n uf [] = Nothing\n uf l = Just $ splitAt 8 l\npr m=intercalate \".\"$map show$frombits$replicate m True ++ replicate (32-m) False\nbsearch f a b | a + 1 == b = a\n | f c = bsearch f a c\n | otherwise = bsearch f c b where\n c = (a + b)`div`2\ns k l\n | k == g r = pr r\n | otherwise = \"-1\"\n where\n r = bsearch f 1 32\n g i = length(group$map(take i)l)\n f i = k >= g i\nsolve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl\nmain=interact$solve.lines\n"}, {"source_code": "import Data.List\nntobits = reverse . go 8 where\n go 0 _ = []\n go i n = odd n : go (i-1) (n `div` 2)\ntobits ns = ns >>= ntobits\nipwords [] = []\nipwords s = case span(/='.') s of\n (l,r) -> l : ipwords (drop 1 r)\npip=map read.ipwords\n\nfrombitsn=foldl(\\n b-> n*2+fromEnum b)0\nfrombits=map frombitsn.unfoldr uf where\n uf [] = Nothing\n uf l = Just $ splitAt 8 l\npr[]=\"-1\"\npr(m:_)=intercalate \".\"$map show$frombits$replicate m True ++ replicate (32-m) False\ns k l=pr$filter(\\i->k==length(nub$map(take k)l))[0..32]\nsolve(hl:rl)=s((!!1).map read.words$hl).map(tobits.pip)$rl\nmain=interact$solve.lines\n"}, {"source_code": "import Data.List\nntobits = reverse . go 8 where\n go 0 _ = []\n go i n = odd n : go (i-1) (n `div` 2)\ntobits ns = ns >>= ntobits\nipwords [] = []\nipwords s = case span(/='.') s of\n (l,r) -> l : ipwords (drop 1 r)\npip=map(foldl(\\a c->a*10+fromEnum c-fromEnum '0')0).ipwords\n\nfrombitsn=foldl(\\n b-> n*2+fromEnum b)0\nfrombits=map frombitsn.unfoldr uf where\n uf [] = Nothing\n uf l = Just $ splitAt 8 l\npr m=intercalate \".\"$map show$frombits$replicate m True ++ replicate (32-m) False\nbsearch f a b | a + 1 == b = a\n | f c = bsearch f a c\n | otherwise = bsearch f c b where\n c = (a + b)`div`2\ns k l\n | k == g r = pr r\n | otherwise = \"-1\"\n where\n r = min 31 $ bsearch f 1 32 + 1\n g i = length(group$map(take i)l)\n f i = g i >= k\nsolve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl\nmain=interact$solve.lines\n"}], "src_uid": "4da4410d3b75ee87a4dfa33b437b9cfa"} {"source_code": "import Control.Monad (replicateM_)\nimport Data.Int (Int64)\n\nstep :: Int64 -> [Int] -> [Int]\nstep k li = let\n p = minimum li\n q = maximum li\n in if even k then map (subtract p) li else map (q-) li\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, k] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n putStrLn . unwords $ map show (step k a)\n\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n if odd k\n then putStrLn $ unwords $ map show $ apply as\n else putStrLn $ unwords $ map show $ apply $ apply as\n\napply as = (maximum as -) <$> as\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nreadInt64B8 :: B8.ByteString -> Int64\nreadInt64B8 = fromInteger . fst . fromJust . B8.readInteger\n\n\nstep :: [Int] -> [Int]\nstep as = map (\\x -> maxA - x) as\n where\n maxA = foldr1 max as\n\nsolve :: Int64 -> Int64 -> [Int] -> [Int]\nsolve n k as = \n if ((k - 1) `mod` 2) == 0\n then firstStepped\n else secondStepped\n where\n firstStepped = step as\n secondStepped = step firstStepped\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n [n, k] <- map readInt64B8 <$> B8.words <$> B8.getLine\n as <- map readIntB8 <$> B8.words <$> B8.getLine\n let answer = solve n k as\n forM_ answer $ printf \"%d \"\n printf \"\\n\"\n"}], "negative_code": [], "src_uid": "f18a5fa0b2e7e96cb5994b7b2dbe0189"} {"source_code": "import Data.List (find)\r\nimport Data.Maybe (fromJust)\r\n\r\nminus :: [Int] -> [Int] -> [Int]\r\nminus (x:xs) (y:ys) = case compare x y of \r\n LT -> x : minus xs (y:ys)\r\n EQ -> minus xs ys \r\n GT -> minus (x:xs) ys\r\nminus xs _ = xs\r\n\r\nmerge :: [Int] -> [Int] -> [Int]\r\nmerge (x:xs) (y:ys) = case compare x y of \r\n LT -> x : merge xs (y:ys)\r\n EQ -> x : merge xs ys \r\n GT -> y : merge (x:xs) ys\r\nmerge xs [] = xs\r\nmerge [] ys = ys\r\n\r\n\r\nmergeAll :: [[Int]] -> [Int]\r\nmergeAll = foldr (\\(x : xs) -> (x : ) . merge xs) []\r\n\r\nprimes :: [Int]\r\nprimes = 2 : 3 : minus [5,7..] (mergeAll [[p*p, p*p+2*p..] | p <- tail primes])\r\n\r\nprocess :: Int -> Int\r\nprocess d = p * q\r\n where p = fromJust $ find (>= d + 1) primes\r\n q = fromJust $ find (>= p + d) primes\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . process . (read :: String -> Int)) . tail . lines)\r\n", "positive_code": [{"source_code": "module Main where\r\n\r\nsieve a b\r\n |b==[] = []\r\n |(head b)>a = sieve (a+1) b\r\n |(head b)==a = (head b):(sieve (a+1) (filter (\\e->(e`mod`a)/=0) (tail b)))\r\n |otherwise = sieve (a+1) (filter (\\e->(e`mod`a)/=0) b)\r\n\r\nprimes=sieve 2 [2..30000]\r\n\r\nsearch_geq (x:xs) b\r\n | x>=b = x\r\n | otherwise = search_geq xs b\r\n\r\nwork t=p*q\r\n where\r\n p=search_geq primes $ t+1\r\n q=search_geq primes $ p+t\r\n\r\nrun 1 = do\r\n l1 <- getLine\r\n putStrLn $ show $ work ((read::String->Integer) l1)\r\n\r\nrun x = do\r\n run 1\r\n run (x-1)\r\n\r\nmain = do\r\n l1 <- getLine\r\n let t = (read::String->Integer) l1\r\n run t"}, {"source_code": "import Control.Monad\r\n\r\nisPrime 2 = True\r\nisPrime n \r\n | even n = False\r\n | n < 2 = False\r\n | any (\\x->mod n x==0) $ takeWhile (\\x->x*x<=n) [3,5..] = False\r\n | otherwise = True\r\n\r\nsolve x = head [i|i<-[x..],isPrime i]\r\n \r\nprintResult = do\r\n d <- readLn :: IO Int\r\n let x = solve $ d + 1\r\n y = solve $ x + d\r\n print $ x * y\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\n\r\nisPrime :: Int64 -> Bool\r\nisPrime x = all (\\d -> x `mod` d /= 0) ds\r\n where\r\n sqrtX = floor . sqrt . fromIntegral $ x\r\n ds = [2 .. sqrtX]\r\n\r\nnextPrime :: Int64 -> Int64\r\nnextPrime x = fromJust . find isPrime $ [x..]\r\n\r\nsolve :: Int64 -> Int64\r\nsolve d = x * y\r\n where\r\n x = nextPrime (d + 1)\r\n y = nextPrime (x + d)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n dd <- B8.getLine <&> readIntegerB8\r\n let d :: Int64 = fromInteger dd\r\n let answer = solve d\r\n printf \"%lld\\n\" answer"}], "negative_code": [{"source_code": "import Control.Monad\r\n\r\nisPrime 2 = True\r\nisPrime n \r\n | even n = False\r\n | n < 2 = False\r\n | any (\\x->mod n x==0) $ takeWhile (\\x->x*x<=n) [3,5..] = False\r\n | otherwise = True\r\n\r\nsolve x = head [i|i<-[x..],isPrime i]\r\n \r\nprintResult = do\r\n d <- readLn :: IO Int\r\n print $ solve (d+1) * solve (1+2*d)\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\n \r\nprintResult = do\r\n d <- readLn :: IO Int\r\n print $ (1+d) * (1+2*d)\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "src_uid": "648ec67565c506c3e2ffd007ad44e8c3"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (mapAccumL)\nimport Data.Array (Array, listArray, elems, (!))\n\nzfunc :: Eq a => [a] -> [Int]\nzfunc a = elems out\n where\n n = length a :: Int\n mkArray :: [a] -> Array Int a\n mkArray = listArray (0, n - 1)\n\n arr = mkArray a\n out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int\n\n loop :: (Int, Int) -> Int -> ((Int, Int), Int)\n loop (l, r) i\n | r < i + 1 = ((i, r'), r' - i)\n | i + out ! (i - l) < r = ((l, r), out ! (i - l))\n | otherwise = ((i, r''), r'' - i)\n where\n next = head . dropWhile (\\j -> j < n && arr ! j == arr ! (j - i))\n [r', r''] = map next [[i..], [r..]] :: [Int]\n\n\nsolve :: String -> String\nsolve [_] = \"Just a legend\"\nsolve line = if len /= 0 then take len line else \"Just a legend\"\n where\n n = length line :: Int\n a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]\n\n sub = maximum $ map f a :: Int -- longest *strict* substring\n where f (i, k) = if i + k == n then k - 1 else k\n\n len = maximum $ map f a :: Int\n where f (i, k) = if i + k /= n || sub < k then 0 else k\n\nmain = solve <$> getLine >>= putStrLn\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem || ch i == c then i else find i' c\n\nbuild ind !i s\n\t| s == B.empty = []\n\t| otherwise =\n\t\tItem (head is) i'' (B.head $ B.tail s) ind : is\n\t\twhere\n\t\t\ti' = find i (B.head s)\n\t\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\t\tis = build (ind + 1) i'' (B.tail s)\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nbuild ind !i s \n\t| s == B.empty = []\n\t| otherwise =\n\t\tItem (head is) i'' (B.head $ B.tail s) ind : is\n\t\twhere\n\t\t\tc = B.head s\n\t\t\ti' = find i\n\t\t\ti'' = if ind /= 1 && ch i' == c then next i' else i'\n\t\t\tis = build (ind + 1) i'' (B.tail s)\n\n\t\t\tfind i\n\t\t\t\t| i' == NilItem || ch i == c = i\n\t\t\t\t| otherwise = find i'\n\t\t\t\twhere i' = prefix i\n\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild :: Int -> Item -> B.ByteString -> [Item]\n-- build ind i [] = []\nbuild ind !i s =\n\tif s == B.empty then [] else\n\tlet\ti' = find i (B.head s)\n\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\tis = build (ind + 1) i'' (B.tail s)\n\tin Item (head is) i'' (B.head $ B.tail s) ind : is\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n\t\t\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\ndata Item = Item { next :: Item, prefix :: Item, ch :: Char, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild ind i \"\" = []\nbuild ind !i !s =\n\tlet\ti' = find i (head s)\n\t\ti'' = if ind /= 1 && ch i' == head s then next i' else i'\n\t\tis = build (ind + 1) i'' (tail s)\n\tin Item (head is) i'' (head $ tail s) ind : is\n\nmain = do\n\ts <- getLine\n\n\tlet\ti = Item (head is) NilItem (head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen putStrLn $ take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse putStrLn $ take p' s\n\t\t\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nbuild ind !i s \n\t| s == B.empty = []\n\t| otherwise =\n\t\tItem (head is) i'' (B.head $ B.tail s) ind : is\n\t\twhere\n\t\t\tc = B.head s\n\t\t\ti' = find i\n\t\t\ti'' = if ind /= 1 && ch i' == c then next i' else i'\n\t\t\tis = build (ind + 1) i'' (B.tail s)\n\n\t\t\tfind !i\n\t\t\t\t| i' == NilItem || ch i == c = i\n\t\t\t\t| otherwise = find i'\n\t\t\t\twhere i' = prefix i\n\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\ndata Item = Item { next :: Item, prefix :: Item, ch :: Char, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild ind i \"\" = []\nbuild ind !i s =\n\tlet\ti' = find i (head s)\n\t\ti'' = if ind /= 1 && ch i' == head s then next i' else i'\n\t\tis = build (ind + 1) i'' (tail s)\n\tin Item (head is) i'' (head $ tail s) ind : is\n\nmain = do\n\ts <- getLine\n\n\tlet\ti = Item (head is) NilItem (head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen putStrLn $ take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse putStrLn $ take p' s\n\t\t\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild :: Int -> Item -> B.ByteString -> [Item]\n-- build ind i [] = []\nbuild ind !i s =\n\tif s == B.empty then [] else\n\tlet\ti' = find i (B.head s)\n\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\tis = build (ind + 1) i'' (B.tail s)\n\tin Item (head is) i'' (B.head $ B.tail s) ind : is\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (mapAccumL)\nimport Data.Array (Array, listArray, elems, (!))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\nzfunc :: Eq a => [a] -> [Int]\nzfunc a = elems out\n where\n n = length a :: Int\n mkArray :: [a] -> Array Int a\n mkArray = listArray (0, n - 1)\n\n arr = mkArray a\n out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int\n\n loop :: (Int, Int) -> Int -> ((Int, Int), Int)\n loop (l, r) i\n | r < i + 1 = ((i, r'), r' - i)\n | i + out ! (i - l) < r = ((l, r), out ! (i - l))\n | otherwise = ((i, r''), r'' - i)\n where\n next = head . dropWhile (\\j -> j < n && arr ! j == arr ! (j - i))\n [r', r''] = map next [[i..], [r..]] :: [Int]\n\n\nsolve :: String -> String\nsolve [_] = \"Just a legend\"\nsolve line = if len /= 0 then take len line else \"Just a legend\"\n where\n n = length line :: Int\n a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]\n\n sub = maximum $ map f a :: Int -- longest *strict* substring\n where f (i, k) = if i + k == n then k - 1 else k\n\n len = maximum $ map f a :: Int\n where f (i, k) = if i + k /= n || sub < k then 0 else k\n\nmain = C8.pack . solve . C8.unpack . C8.init <$> B.getLine >>= C8.putStrLn\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild :: Int -> Item -> B.ByteString -> [Item]\n-- build ind i [] = []\nbuild ind !i s =\n\tif s == B.empty then [] else\n\tlet\ti' = find i (B.head s)\n\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\tis = build (ind + 1) i'' (B.tail s)\n\tin Item (head is) i'' (B.head $ B.tail s) ind : is\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n"}, {"source_code": "\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nimport Control.Monad (foldM_)\nimport Data.Array.MArray (newArray, readArray, writeArray)\nimport Data.Array.ST (runSTUArray)\nimport Data.Array.Unboxed -- (UArray, (!), listArray, elems)\n\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\nzFunction :: String -> UArray Int Int\nzFunction s = runSTUArray $ do\n z <- newArray (1, n) 0\n writeArray z 1 n\n foldM_ (iter z) (1, 1) [2..n]\n return z\n where\n n = length s\n s' = listArray (1, n) s :: UArray Int Char\n iter z (l, r) i = do\n zil <- readArray z (i - l + 1)\n let z0 = (i > r) ? 0 $ min (r - i + 1) zil \n let zi = head $ dropWhile (\\j -> i + j <= n && s' ! (j + 1) == s' ! (i + j)) [z0..]\n writeArray z i zi\n return $ (i + zi - 1 > r) ? (i, i + zi - 1) $ (l, r)\n\nsolve :: String -> Maybe String\nsolve s\n | n <= 2 = Nothing\n | otherwise = listToMaybe [take (z ! i) s | i <- [2..n], (z ! i) <= mx, i + z ! i == n + 1]\n where\n n = length s\n z = zFunction s\n z' = zFunction $ init s\n mx = maximum $ tail $ elems z'\n\nmain :: IO ()\nmain = getLine >>= putStrLn . fromMaybe \"Just a legend\" . solve\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild :: Int -> Item -> B.ByteString -> [Item]\n-- build ind i [] = []\nbuild ind !i s =\n\tif s == B.empty then [] else\n\tlet\ti' = find i (B.head s)\n\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\tis = build (ind + 1) i'' (B.tail s)\n\tin Item (head is) i'' (B.head $ B.tail s) ind : is\n\nmain = do\n\ts <- B.getLine\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n\t\t\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\n{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: !Item, ch :: Word8, k :: !Int } | NilItem deriving (Eq)\n\nfind i c =\n\tlet i' = prefix i in\n\tif i' == NilItem\n\tthen i\n\telse if ch i == c\n\t\tthen i\n\t\telse find i' c\n\nbuild ind !i s =\n\tlet\ti' = find i (B.head s)\n\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\tis = build (ind + 1) i'' (B.tail s)\n\tin Item (head is) i'' (B.head $ B.tail s) ind : is\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n\t\t\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\n{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}\nimport Data.Word\n\nimport qualified Data.ByteString as B\n\ndata Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)\n\nfind i c =\n\tif i' == NilItem || ch i == c then i else find i' c\n\twhere i' = prefix i\n\nbuild ind !i s =\n\tItem (head is) i'' (B.head $ B.tail s) ind : is\n\twhere\n\t\ti' = find i (B.head s)\n\t\ti'' = if ind /= 1 && ch i' == B.head s then next i' else i'\n\t\tis = build (ind + 1) i'' (B.tail s)\n\nmain = do\n\ts1 <- B.getLine\n\n\tlet\ts = B.init s1\n\n\tlet\ti = Item (head is) NilItem (B.head s) 0\n\t\tis = build 1 i s\n\t\tps = map (\\i -> k $ prefix i) is\n\n\t\tn = B.length s\n\n\t\tp = ps !! (n-1)\n\n\tif p == 0\n\tthen putStrLn \"Just a legend\"\n\telse\n\t\tlet ps' = filter (== p) (init ps) in\n\t\t\tif ps' /= []\n\t\t\tthen B.putStrLn $ B.take (head ps') s\n\t\t\telse\n\t\t\t\tlet p' = ps !! (p - 1) in\n\t\t\t\tif p' == 0\n\t\t\t\tthen putStrLn \"Just a legend\"\n\t\t\t\telse B.putStrLn $ B.take p' s\n\t\t\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (mapAccumL)\nimport Data.Array (Array, listArray, elems, (!))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\nzfunc :: Eq a => [a] -> [Int]\nzfunc a = elems out\n where\n n = length a :: Int\n mkArray :: [a] -> Array Int a\n mkArray = listArray (0, n - 1)\n\n arr = mkArray a\n out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int\n\n loop :: (Int, Int) -> Int -> ((Int, Int), Int)\n loop (l, r) i\n | r < i + 1 = ((i, r'), r' - i)\n | i + out ! (i - l) < r = ((l, r), out ! (i - l))\n | otherwise = ((i, r''), r'' - i)\n where\n next = head . dropWhile (\\j -> j < n && arr ! j == arr ! (j - i))\n [r', r''] = map next [[i..], [r..]] :: [Int]\n\n\nsolve :: String -> String\nsolve [_] = \"Just a legend\"\nsolve line = if len /= 0 then take len line else \"Just a legend\"\n where\n n = length line :: Int\n a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]\n\n sub = maximum $ map f a :: Int -- longest *strict* substring\n where f (i, k) = if i + k == n then k - 1 else k\n\n len = maximum $ map f a :: Int\n where f (i, k) = if i + k /= n || sub < k then 0 else k\n\nmain = C8.pack . solve . C8.unpack <$> B.getLine >>= C8.putStrLn\n"}], "src_uid": "fd94aea7ca077ee2806653d22d006fb1"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b, c] <- map read . words <$> getLine\n putStrLn $ if solve a b c then \"YES\" else \"NO\"\n\nsolve :: Integer -> Integer -> Integer -> Bool\nsolve a b c =\n or\n [ let am = 2 * b - c in am > 0 && am `mod` a == 0,\n let bm2 = a + c in bm2 > 0 && bm2 `mod` (b * 2) == 0,\n let cm = 2 * b - a in cm > 0 && cm `mod` c == 0\n ]\n\n-- c - b == b - a * m => a * m - 2 * b + c == 0\n-- c - b * m = b * m - a => a - m * 2 * b + c == 0\n-- c * m - b = b - a => a - 2 * b + c * m == 0\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[a, b, c] <- map read . words <$> getLine\r\n let a' = 2 * b - c\r\n c' = 2 * b - a\r\n b' = (c + a) `div` 2\r\n ok = a' > 0 && a' `mod` a == 0\r\n || c' > 0 && c' `mod` c == 0\r\n || even (c - a) && b' > 0 && b' `mod` b == 0\r\n putStrLn $ if ok then \"YES\" else \"NO\"\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}, {"source_code": "import Data.Char ( isDigit )\r\n\r\nmain :: IO()\r\nmain = do\r\n tStr <- getLine\r\n let t = read tStr :: Int\r\n solve t\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = return ()\r\nsolve t = do\r\n\r\n inStr <- getLine\r\n let list = readIntList inStr\r\n\r\n let ans = if test list then \"YES\" else \"NO\"\r\n putStrLn ans\r\n solve (t - 1)\r\n\r\ntest :: [Int] -> Bool\r\ntest [a, b, c]\r\n | last `mod` c == 0 && last > 0 = True\r\n | first `mod` a == 0 && first > 0 = True\r\n | even (a + c) && divisible = True\r\n | otherwise = False\r\n where\r\n first = 2*b - c\r\n last = 2 * b - a\r\n divisible = (mid `mod` b) == 0 \r\n mid = (a + c) `div` 2\r\n\r\ntest _ = False\r\n\r\nprog :: [Int] -> Bool\r\nprog [a, b, c]\r\n | 2 * b == a + c = True\r\n | otherwise = False\r\nprog _ = False\r\n\r\nreadIntList :: String -> [Int]\r\nreadIntList [] = []\r\nreadIntList (h : t)\r\n | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)\r\n | otherwise = readIntList t"}, {"source_code": "import Control.Monad(replicateM)\r\nimport qualified Data.ByteString.Lazy.Char8 as B\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport System.IO\r\n\r\ndivides :: Int -> Int -> Bool \r\ndivides a b = b `rem` a == 0\r\n\r\ncanMakeAP :: Int -> Int -> Int -> Bool\r\ncanMakeAP a b c =\r\n (2*b - c > 0 && a `divides` (2*b - c)) ||\r\n (2*b) `divides` (c + a) ||\r\n (2*b - a > 0 && c `divides` (2*b - a)) \r\n\r\nsolve :: SB Builder \r\nsolve = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[a, b, c] <- getInts 3\r\n let ans = canMakeAP a b c\r\n return $ string7 (if ans then \"YES\\n\" else \"NO\\n\")\r\n\r\n-- stdin/out from solution by clyring\r\ntype SB = State [B.ByteString]\r\n\r\ngetNext :: Int -> SB [B.ByteString]\r\ngetNext = state . splitAt\r\n\r\nparseInt = fst . fromJust . B.readInt\r\n\r\ngetInts :: Int -> SB [Int]\r\ngetInts n = map parseInt <$> getNext n\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- B.getContents\r\n let out = evalState solve $ B.words inp\r\n B.putStr $ toLazyByteString out"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInt :: IO Int\r\nreadInt = readLn\r\n\r\nreadIntArray :: IO [Int]\r\nreadIntArray = (map read . words) <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readInt >>= \\t -> replicateM_ t test\r\n\r\ntest :: IO ()\r\ntest = do\r\n [a, b, c] <- readIntArray\r\n putStrLn $ calc a b c\r\n\r\ncalc :: Int -> Int -> Int -> String\r\ncalc a b c\r\n | (2 * b - c >= 1 && mod (2 * b - c) a == 0)\r\n || (even (c - a) && mod (div (c + a) 2) b == 0)\r\n || (2 * b - a >= 1 && mod (2 * b - a) c == 0) = \"YES\"\r\n | otherwise = \"NO\"\r\n"}, {"source_code": "-- https://codeforces.com/contest/1624/problem/B\nimport Control.Monad (replicateM_)\n\nanswer a b c\n | (2*b-c >= 1 && (2*b-c)`mod`a == 0)\n ||(even (c-a) && ((c+a)`div`2)`mod`b == 0)\n ||(2*b-a >= 1 && (2*b-a)`mod`c == 0) = \"YES\"\n | otherwise = \"NO\"\n\nmain = getLine >>= flip replicateM_ run . read\nrun = do\n [a, b, c] <- (read <$>) . words <$> getLine\n putStrLn $ answer a b c\n"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = (Int, Int, Int)\r\ntype OutType = Bool\r\n\r\nsolve :: InType -> OutType\r\nsolve (a, b, c) =\r\n let d1 = c - b\r\n d2 = b - a\r\n d3 = c - a\r\n in ((b - d1) `mod` a == 0 && b - d1 >= a) ||\r\n ((b + d2) `mod` c == 0 && b + d2 >= c) ||\r\n (even d3 && (a + d3 `div` 2) `mod` b == 0)\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = case toArr s of\r\n [a, b, c] -> (a, b, c)\r\n _ -> error \"wrong input\"\r\nreceive _ = error \"wrong input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showB . solve . receive) . chunksOf 1 . tail . lines\r\n where showB True = \"YES\"\r\n showB False = \"NO\"\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[a, b, c] <- getInts 3\n let\n a' = case (2 * b - c) `quotRem` a of\n (q, r) -> r == 0 && q > 0\n b' = (a + c) `rem` (2 * b) == 0\n c' = case (2 * b - a) `quotRem` c of\n (q, r) -> r == 0 && q > 0\n pure $ string7 $ if a' || b' || c'\n then \"YES\\n\"\n else \"NO\\n\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[a, b, c] <- map read . words <$> getLine\r\n let a' = 2 * b - c\r\n c' = 2 * b - a\r\n b' = (c - a) `div` 2\r\n ok = a' > 0 && a' `mod` a == 0\r\n || c' > 0 && c' `mod` c == 0\r\n || even (c - a) && b' > 0 && b' `mod` b == 0\r\n putStrLn $ if ok then \"YES\" else \"NO\"\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[a, b, c] <- map read . words <$> getLine\r\n let a' = 2 * b - c\r\n c' = 2 * b - a\r\n b' = (c - a) `div` 2\r\n ok = a' > 0 && a' `mod` a == 0\r\n || c' > 0 && c' `mod` c == 0\r\n || even (c - a) && b' `mod` b == 0\r\n putStrLn $ if ok then \"YES\" else \"NO\"\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}, {"source_code": "import Data.Char ( isDigit )\r\n\r\nmain :: IO()\r\nmain = do\r\n tStr <- getLine\r\n let t = read tStr :: Int\r\n solve t\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = return ()\r\nsolve t = do\r\n\r\n inStr <- getLine\r\n let list = readIntList inStr\r\n\r\n let ans = if test list then \"YES\" else \"NO\"\r\n print ans\r\n solve (t - 1)\r\n\r\ntest :: [Int] -> Bool\r\ntest [a, b, c]\r\n | last `mod` c == 0 && last > 0 = True\r\n | first `mod` a == 0 && first > 0 = True\r\n | even (a + c) && divisible = True\r\n | otherwise = False\r\n where\r\n first = 2*b - c\r\n last = 2 * b - a\r\n divisible = (mid `mod` b) == 0 \r\n mid = (a + c) `div` 2\r\n\r\ntest _ = False\r\n\r\nprog :: [Int] -> Bool\r\nprog [a, b, c]\r\n | 2 * b == a + c = True\r\n | otherwise = False\r\nprog _ = False\r\n\r\nreadIntList :: String -> [Int]\r\nreadIntList [] = []\r\nreadIntList (h : t)\r\n | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)\r\n | otherwise = readIntList t"}], "src_uid": "90c5058c0c7f55a567f2e036482149f9"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\n\nchar2Bool :: Char -> Bool\nchar2Bool '0' = False\nchar2Bool '1' = True\n\nenumerate :: [a] -> [(Int, a)]\nenumerate = zip [1 ..]\n\ncompressAdjMatrix :: [[Bool]] -> Array (Int, Int) Bool\ncompressAdjMatrix adjMatrix = array ((1, 1), (size, size)) indexedMatrix\n where size = length adjMatrix\n indexedMatrix = do\n (vert, row) <- enumerate adjMatrix\n (neigh, adj) <- enumerate row\n return ((vert, neigh), adj)\n\nrunFloydWarshall :: Array (Int, Int) Bool -> Array (Int, Int) Int\nrunFloydWarshall adjMatrix = runST $ do\n -- prepare distances\n let (_, (size, _)) = bounds adjMatrix\n let range = [1 .. size]\n distances <- newArray ((1, 1), (size, size)) (size + 1) :: ST s (STUArray s (Int, Int) Int)\n forM_ [(i, j) | i <- range, j <- range] $ \\(i, j) -> do\n when (adjMatrix ! (i, j)) $ writeArray distances (i, j) 1\n when (i == j) $ writeArray distances (i, j) 0\n\n -- run main algo\n forM_ [(i, u, v) | i <- range, u <- range, v <- range] $ \\(i, u, v) -> do\n duv <- readArray distances (u, v)\n dui <- readArray distances (u, i)\n div <- readArray distances (i, v)\n writeArray distances (u, v) $ min duv (dui + div)\n\n -- return the array\n freeze distances\n\ncompressPath :: [Int] -> Array (Int, Int) Int -> [Int]\ncompressPath path distances = reverse $ go path (tail path) [head path] (head path, 1)\n where go :: [Int] -> [Int] -> [Int] -> (Int, Int) -> [Int]\n go (u:_) [] res (_, _) = u : res\n go (u:us) (v:vs) res (last, c)\n | distances ! (last, v) < c = go us vs (u : res) (u, 2)\n | otherwise = go us vs res (last, succ c)\n\nmain :: IO ()\nmain = do\n size <- read <$> getLine\n matrix <- sequence $ replicate size $ map char2Bool <$> getLine\n pathLength <- (read :: String -> Int) <$> getLine\n path <- map read . words <$> getLine\n let distances = runFloydWarshall $ compressAdjMatrix matrix\n compressedPath = compressPath path distances\n print $ length compressedPath\n putStrLn $ unwords $ map show compressedPath\n", "positive_code": [{"source_code": "import Data.Char\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Maybe\nimport Data.List\n\nmain = do\n n <- readLn\n adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)\n k <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n let fw = runSTUArray $ do\n d <- thaw adj\n forM_ (indices adj) $ \\p ->\n writeArray d p . (\\e -> if e == 0 then 100^3 else 1) =<< readArray d p\n forM_ [1..n] $ \\i ->\n forM_ [1..n] $ \\j ->\n forM_ [1..n] $ \\k -> do\n d0 <- readArray d (i,j)\n d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))\n when (d1 < d0) $ writeArray d (i,j) d1\n return d\n s = solve fw (maximum (elems fw)) ps\n print (length s)\n putStrLn $ unwords $ map show s\n\nsolve fw up (first : ps) = first : go first ps where\n go _ [] = []\n go prev ps = (\\(n:ns) -> n : go n ns) $ last $ catMaybes $ zipWith (\\d ns@(n:_) -> guard (n /= prev) *> guard (fw!(prev,n) >= d) *> return ns) [1..] $ takeWhile (not . null) $ take up $ tails ps\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.Set as Set hiding (map)\nimport Data.Array.Unboxed as U hiding (map)\nimport Data.Array.IArray as I hiding (map)\n\ndistanceArray :: Array Int [Int] -> Array Int (UArray Int Int)\ndistanceArray g = I.listArray (1, n) [distances' a' | a' <- [1..n]] where\n n = snd $ bounds g\n distances' :: Int -> UArray Int Int\n distances' a = distances 0 (U.listArray (1, n) [-1 | _ <- [1..n]]) (Set.singleton a)\n distances :: Int -> UArray Int Int -> Set Int -> UArray Int Int\n distances _ result now | Set.null now = result\n distances d pre now = distances (d + 1) result next where\n result = pre // [(a, d) | a <- toList now, pre ! a == -1]\n next = Set.fromList [b | a <- Set.toList now, b <- g ! a, pre ! b == -1]\n\ncompress f (p:q:r:ps) = if f ! p ! q + f ! q ! r == f ! p ! r\n then compress f (p:r:ps)\n else p : compress f (q:r:ps)\ncompress _ ps = ps\n\nmakeGraph :: [[Char]] -> Array Int [Int]\nmakeGraph edges = listArray (1, n) [[j | (j, c) <- zip [1..n] es, c == '1'] | es <- edges] where\n n = length edges\n\nmain = do\n line1 <- getLine\n let n = read line1 :: Int\n contents <- getContents\n let\n (grid, query) = Prelude.splitAt n $ lines contents\n g = makeGraph grid\n ps = map read $ words $ head $ tail query\n a = distanceArray g\n result = compress a ps\n print $ length result\n putStrLn $ unwords $ map show result\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.Set as Set hiding (map)\nimport Data.Array.Unboxed as U hiding (map)\nimport Data.Array.IArray as I hiding (map)\n\ndistance :: Array Int [Int] -> Int -> Int -> Int\ndistance g a b = (I.listArray (1, n) [distances' a' | a' <- [1..n]] :: Array Int (UArray Int Int)) ! a ! b where\n n = snd $ bounds g\n distances' :: Int -> UArray Int Int\n distances' a = distances 0 (U.listArray (1, n) [-1 | _ <- [1..n]]) (Set.singleton a)\n distances :: Int -> UArray Int Int -> Set Int -> UArray Int Int\n distances _ result now | Set.null now = result\n distances d pre now = distances (d + 1) result next where\n result = pre // [(a, d) | a <- toList now]\n next = Set.fromList [b | a <- Set.toList now, b <- g ! a, pre ! b == -1]\n\ncompress g (p:q:r:ps) = if distance g p q + distance g q r == distance g p r\n then compress g (p:r:ps)\n else p : compress g (q:r:ps)\ncompress _ ps = ps\n\nmakeGraph :: [[Char]] -> Array Int [Int]\nmakeGraph edges = listArray (1, n) [[j | (j, c) <- zip [1..n] es, c == '1'] | es <- edges] where\n n = length edges\n\nmain = do\n line1 <- getLine\n let n = read line1 :: Int\n contents <- getContents\n let\n (grid, query) = Prelude.splitAt n $ lines contents\n g = makeGraph grid\n ps = map read $ words $ head $ tail query\n result = compress g ps\n print $ length result\n putStrLn $ unwords $ map show result\n"}, {"source_code": "import Data.Char\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Maybe\nimport Data.List\n\nmain = do\n n <- readLn\n adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)\n k <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n let fw = runSTUArray $ do\n d <- thaw adj\n forM_ (indices adj) $ \\p ->\n writeArray d p . (\\e -> if e == 0 then 100^3 else 1) =<< readArray d p\n forM_ [1..n] $ \\i ->\n forM_ [1..n] $ \\j ->\n forM_ [1..n] $ \\k -> do\n d0 <- readArray d (i,j)\n d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))\n when (d1 < d0) $ writeArray d (i,j) d1\n return d\n s = solve fw (maximum (elems fw)) ps\n print (length s)\n putStrLn $ unwords $ map show s\n\nsolve fw up (first : ps) = first : go first ps where\n go _ [] = []\n go prev ps = (\\(n:ns) -> n : go n ns) $ last $ catMaybes $ zipWith (\\d ns@(n:_) -> guard (fw!(prev,n) >= d) *> return ns) [1..] $ takeWhile (not . null) $ take up $ tails ps\n"}, {"source_code": "import Data.Char\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Maybe\nimport Data.List\n\nmain = do\n n <- readLn\n adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)\n k <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n let fw = runSTUArray $ do\n d <- thaw adj\n forM_ (indices adj) $ \\p ->\n writeArray d p . (\\e -> if e == 0 then 100^3 else 1) =<< readArray d p\n forM_ [1..n] $ \\i ->\n forM_ [1..n] $ \\j ->\n forM_ [1..n] $ \\k -> do\n d0 <- readArray d (i,j)\n d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))\n when (d1 < d0) $ writeArray d (i,j) d1\n return d\n putStrLn $ unwords $ map show $ solve fw (maximum (elems fw)) ps\n\nsolve fw up (first : ps) = first : go first ps where\n go _ [] = []\n go prev ps = (\\(n:ns) -> n : go n ns) $ last $ catMaybes $ zipWith (\\d ns@(n:_) -> guard (fw!(prev,n) >= d) *> return ns) [1..] $ takeWhile (not . null) $ take up $ tails ps\n"}], "src_uid": "c9d07fdf0d3293d5564275ebbabbcf12"} {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n\r\nimport Data.Functor\r\nimport Data.Foldable\r\nimport Data.Traversable\r\nimport Data.Eq\r\nimport Data.Ord\r\nimport Data.Int\r\nimport Data.Bits\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.IORef\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport Data.Monoid\r\nimport Data.Either\r\nimport Data.String\r\nimport Data.Function\r\n--import Data.Array\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\n\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n--import System.Random\r\n\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Writer\r\nimport Control.Monad.Fail\r\nimport Control.Monad.State.Lazy\r\nimport Control.Monad.Except\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.Identity\r\nimport Control.Monad.Except\r\nimport Control.Monad.Except\r\n\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nreadWhileNSpace :: IO String\r\nreadWhileNSpace = do\r\n c <- getChar\r\n if c == '\\n' || c == ' ' then\r\n return \"\"\r\n else do\r\n cs <- readWhileNSpace\r\n return (c:cs) \r\n\r\nreadInt :: IO Int\r\nreadInt = read <$> readWhileNSpace\r\n\r\nreadArr :: Int -> IO a -> IO [a]\r\nreadArr n readF = replicateM n readF\r\n\r\nmaxInArr :: Ord a => [a] -> a\r\nmaxInArr = foldr1 max\r\n\r\nil2 :: Int -> Int\r\nil2 x = finiteBitSize x - 1 - countLeadingZeros x\r\n\r\ndata SparseTable = SparseTable { table :: UArray (Int, Int) Int, func :: Int -> Int -> Int }\r\n\r\nbuildSparse :: Array Int Int -> (Int -> Int -> Int) -> SparseTable\r\nbuildSparse e f = SparseTable (runSTUArray $ do\r\n let n = length e\r\n let lg = il2 n\r\n let pws = (listArray (0, lg - 1) $ take lg $ iterate (*2) 1) :: Array Int Int\r\n sp <- newArray ((0, 0), (lg, n)) 0\r\n forM_ [0..n - 1] $ \\j -> do\r\n writeArray sp (0, j) (e ! j)\r\n forM_ [1..lg] $ \\i ->\r\n let p = (pws!(i - 1)) in\r\n forM_ [0..(n - 2 * p)] $ \\j -> do\r\n l <- readArray sp (i - 1, j)\r\n r <- readArray sp (i - 1, j + p)\r\n writeArray sp (i, j) $ f l r\r\n return sp) f\r\n\r\nsparseQuery :: SparseTable -> Int -> Int -> Int\r\nsparseQuery (SparseTable sp f) l r = let lg = il2 (r - l + 1); pws = iterate (*2) 1\r\n in f (sp!(lg, l)) (sp!(lg, r - (pws!!lg) + 1))\r\n\r\nsolve :: SparseTable -> SparseTable -> Array Int Int -> IO ()\r\nsolve spmin spmax pf = do\r\n ~[l, r] <- readInts\r\n let min' = (sparseQuery spmin (l-1) (r-1)) - (pf!(l-1))\r\n let max' = (sparseQuery spmax (l-1) (r-1)) - (pf!(l-1))\r\n putStrLn $ show $ if max' > 0 || (pf!r) - (pf!(l-1)) /= 0 then (-1) else (-min')\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[n, q] <- readInts\r\n a <- readInts\r\n b <- readInts\r\n let delt = getZipList $ (-) <$> (ZipList a) <*> (ZipList b)\r\n let pf = scanl' (+) 0 delt\r\n let pf' = listArray (0, n) pf\r\n let spmin = buildSparse (listArray (0, n - 1) (drop 1 pf)) min \r\n let spmax = buildSparse (listArray (0, n - 1) (drop 1 pf)) max\r\n replicateM_ q $ solve spmin spmax pf'", "positive_code": [{"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n\r\nimport Data.Functor\r\nimport Data.Foldable\r\nimport Data.Traversable\r\nimport Data.Eq\r\nimport Data.Ord\r\nimport Data.Int\r\nimport Data.Bits\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.IORef\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport Data.Monoid\r\nimport Data.Either\r\nimport Data.String\r\nimport Data.Function\r\n--import Data.Array\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\n\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n--import System.Random\r\n\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Writer\r\nimport Control.Monad.Fail\r\nimport Control.Monad.State.Lazy\r\nimport Control.Monad.Except\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.Identity\r\nimport Control.Monad.Except\r\nimport Control.Monad.Except\r\n\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nreadWhileNSpace :: IO String\r\nreadWhileNSpace = do\r\n c <- getChar\r\n if c == '\\n' || c == ' ' then\r\n return \"\"\r\n else do\r\n cs <- readWhileNSpace\r\n return (c:cs) \r\n\r\nreadInt :: IO Int\r\nreadInt = read <$> readWhileNSpace\r\n\r\nreadArr :: Int -> IO a -> IO [a]\r\nreadArr n readF = replicateM n readF\r\n\r\nmaxInArr :: Ord a => [a] -> a\r\nmaxInArr = foldr1 max\r\n\r\nil2 :: Int -> Int\r\nil2 x = finiteBitSize x - 1 - countLeadingZeros x\r\n\r\ndata SparseTable = SparseTable { table :: UArray (Int, Int) Int, func :: Int -> Int -> Int }\r\n\r\nbuildSparse :: Array Int Int -> (Int -> Int -> Int) -> SparseTable\r\nbuildSparse e f = SparseTable (runSTUArray $ do\r\n let n = length e\r\n let lg = il2 n\r\n let pws = take lg $ iterate (*2) 1\r\n sp <- newArray ((0, 0), (lg, n)) 0\r\n forM_ [0..n - 1] $ \\j -> do\r\n writeArray sp (0, j) (e ! j)\r\n forM_ [1..lg] $ \\i ->\r\n let p = (pws !! (i - 1)) in\r\n forM_ [0..(n - 2 * p)] $ \\j -> do\r\n l <- readArray sp (i - 1, j)\r\n r <- readArray sp (i - 1, j + p)\r\n writeArray sp (i, j) $ f l r\r\n return sp) f\r\n\r\nsparseQuery :: SparseTable -> Int -> Int -> Int\r\nsparseQuery (SparseTable sp f) l r = let pws = iterate (*2) 1; lg = il2 (r - l + 1) \r\n in f (sp!(lg, l)) (sp!(lg, r - (pws !! lg) + 1))\r\n\r\nsolve :: SparseTable -> SparseTable -> Array Int Int -> IO ()\r\nsolve spmin spmax pf = do\r\n ~[l, r] <- readInts\r\n let min' = (sparseQuery spmin (l-1) (r-1)) - (pf!(l-1))\r\n let max' = (sparseQuery spmax (l-1) (r-1)) - (pf!(l-1))\r\n putStrLn $ show $ if max' > 0 || (pf!r) - (pf!(l-1)) /= 0 then (-1) else (-min')\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[n, q] <- readInts\r\n a <- readInts\r\n b <- readInts\r\n let delt = getZipList $ (-) <$> (ZipList a) <*> (ZipList b)\r\n let pf = scanl' (+) 0 delt\r\n let pf' = listArray (0, n) pf\r\n let spmin = buildSparse (listArray (0, n - 1) (drop 1 pf)) min \r\n let spmax = buildSparse (listArray (0, n - 1) (drop 1 pf)) max\r\n replicateM_ q $ solve spmin spmax pf'"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Int\n\nil2 :: Int -> Int\nil2 x = finiteBitSize x - 1 - countLeadingZeros x\n\ntype Sparse = (Array Int (UArray Int Int64), Int64 -> Int64 -> Int64)\n\nquery :: Sparse -> Int -> Int -> Int64\nquery (arr, fun) i j = let\n rank = il2 (j - i)\n rarr = arr ! rank\n in fun (rarr ! i) (rarr ! (j + 1 - 1 `shift` rank))\n\nconstruct :: (Int64 -> Int64 -> Int64) -> UArray Int Int64 -> Sparse\nconstruct fun initArr = let\n step :: UArray Int Int64 -> Int -> UArray Int Int64\n step arr w = let\n (p, q) = bounds arr\n nq = q - w\n in listArray (p, nq)\n $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]\n (ip, iq) = bounds initArr\n lastLayer = il2 (iq - ip)\n ws = take lastLayer $ iterate (* 2) 1 -- this is why you should use pre-written code\n in (listArray (0, lastLayer) $ scanl step initArr ws, fun)\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [n,q] <- getInts 2\n a <- getInts n\n b <- getInts n\n let\n diffs = zipWith (-) b a\n psums = listArray (0, n) $ scanl' (\\x y -> x + fromIntegral y) 0 diffs\n possible = construct min psums\n cost = construct max psums\n solve :: Int -> Int -> Maybe Int64\n solve li ri = do\n guard $ psums ! (li - 1) == psums ! ri\n guard $ query possible li ri >= psums ! ri\n pure $ query cost li ri - psums ! ri\n replicateM_ q $ do\n [li, ri] <- getInts 2\n putInt64s $ pure $ case solve li ri of\n Nothing -> 0-1\n Just k -> k\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Int\n\nil2 :: Int -> Int\nil2 x = finiteBitSize x - 1 - countLeadingZeros x\n\ntype Sparse = (Array Int (UArray Int Int64), Int64 -> Int64 -> Int64)\n\nquery :: Sparse -> Int -> Int -> Int64\nquery (arr, fun) i j = let\n rank = il2 (j - i)\n rarr = arr ! rank\n in fun (rarr ! i) (rarr ! (j + 1 - 1 `shift` rank))\n\nconstruct :: (Int64 -> Int64 -> Int64) -> UArray Int Int64 -> Sparse\nconstruct fun initArr = let\n step :: UArray Int Int64 -> Int -> UArray Int Int64\n step arr w = let\n (p, q) = bounds arr\n nq = q - w\n in listArray (p, nq)\n $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]\n (ip, iq) = bounds initArr\n lastLayer = il2 (iq - ip)\n in (listArray (0, lastLayer) $ scanl step initArr [1..lastLayer], fun)\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [n,q] <- getInts 2\n a <- getInts n\n b <- getInts n\n let\n diffs = zipWith (-) b a\n psums = listArray (0, n) $ scanl' (\\x y -> x + fromIntegral y) 0 diffs\n possible = construct min psums\n cost = construct max psums\n solve :: Int -> Int -> Maybe Int64\n solve li ri = do\n guard $ psums ! (li - 1) == psums ! ri\n guard $ query possible li ri >= psums ! ri\n pure $ query cost li ri - psums ! ri\n replicateM_ q $ do\n [li, ri] <- getInts 2\n putInt64s $ pure $ case solve li ri of\n Nothing -> 0-1\n Just k -> k\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Int\n\nil2 :: Int -> Int\nil2 x = finiteBitSize x - 1 - countLeadingZeros x\n\ntype Sparse = (Array Int (UArray Int Int64), Int64 -> Int64 -> Int64)\n\nquery :: Sparse -> Int -> Int -> Int64\nquery (arr, fun) i j = let\n rank = il2 (j - i)\n rarr = arr ! rank\n in fun (rarr ! i) (rarr ! (j - 1 `shift` rank))\n\nconstruct :: (Int64 -> Int64 -> Int64) -> UArray Int Int64 -> Sparse\nconstruct fun initArr = let\n step :: UArray Int Int64 -> Int -> UArray Int Int64\n step arr w = let\n (p, q) = bounds arr\n nq = q - w\n in listArray (p, nq)\n $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]\n (ip, iq) = bounds initArr\n lastLayer = il2 (iq - ip)\n in (listArray (0, lastLayer) $ scanl step initArr [1..lastLayer], fun)\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [n,q] <- getInts 2\n a <- getInts n\n b <- getInts n\n let\n diffs = zipWith (-) b a\n psums = listArray (0, n) $ scanl' (\\x y -> x + fromIntegral y) 0 diffs\n possible = construct min psums\n cost = construct max psums\n solve :: Int -> Int -> Maybe Int64\n solve li ri = do\n guard $ psums ! (li - 1) == psums ! ri\n guard $ query possible li ri >= psums ! ri\n pure $ query cost li ri - psums ! ri\n replicateM_ q $ do\n [li, ri] <- getInts 2\n putInt64s $ pure $ case solve li ri of\n Nothing -> 0-1\n Just k -> k\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\n\nil2 :: Int -> Int\nil2 x = finiteBitSize x - 1 - countLeadingZeros x\n\ntype Sparse = (Array Int (UArray Int Int), Int -> Int -> Int)\n\nquery :: Sparse -> Int -> Int -> Int\nquery (arr, fun) i j = let\n rank = il2 (j - i)\n rarr = arr ! rank\n in fun (rarr ! i) (rarr ! (j - 1 `shift` rank))\n\nconstruct :: (Int -> Int -> Int) -> UArray Int Int -> Sparse\nconstruct fun initArr = let\n step :: UArray Int Int -> Int -> UArray Int Int\n step arr w = let\n (p, q) = bounds arr\n nq = q - w\n in listArray (p, nq)\n $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]\n (ip, iq) = bounds initArr\n lastLayer = il2 (iq - ip)\n in (listArray (0, lastLayer) $ scanl step initArr [1..lastLayer], fun)\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [n,q] <- getInts 2\n a <- getInts n\n b <- getInts n\n let\n psums = listArray (0, n) $ scanl' (+) 0 $ zipWith (-) b a\n possible = construct min psums\n cost = construct max psums\n solve :: Int -> Int -> Maybe Int\n solve li ri = do\n guard $ psums ! (li - 1) == psums ! ri\n guard $ query possible li ri >= psums ! ri\n pure $ query cost li ri - psums ! ri\n replicateM_ q $ do\n [li, ri] <- getInts 2\n putInts $ pure $ case solve li ri of\n Nothing -> 0-1\n Just k -> k\n \n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> SIO ()\nputInts vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n"}], "src_uid": "5f3022de0429cca31bab24501347eb69"} {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (sort, maximumBy, minimum, foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> b -> b\ndebug = trace . show\n--debug _ = id\n\nmain = readFile \"input.txt\" >>= (writeFile \"output.txt\" . show . solve . parse . lines)\n\nparse :: [String] -> (Int, [Int])\nparse [nx, s] =\n let [n, x] = map read . words $ nx\n c = map read . words $ s\n in (x, c)\n\nsolve (x, c) =\n let n = length c\n v = takeWhile (<= x) $ scanl (+) 0 $ sort [(n - i) * (c !! i) | i <- [0..n - 1]]\n in length v - 1\n", "positive_code": [{"source_code": "import IO\nimport List\n\nmain = do\n\ti <- openFile \"input.txt\" ReadMode\n\to <- openFile \"output.txt\" WriteMode\n\tc <- hGetContents i\n\thPutStr o $ show $ gao $ map read $ words c\n\thClose o\n\ngao (n:x:c) = length $ takeWhile (<=x) $ scanl1 (+) $ sort $ zipWith (*) [1 ..] $ reverse c\n"}], "negative_code": [], "src_uid": "6ddf0be1cc8c0ed6b86eb9e901189bf1"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Data.Array.Unboxed\r\nimport Data.List\r\nimport Data.Char ( isSpace )\r\n\r\nmain :: IO ()\r\nmain = do\r\n [n, k] <- line\r\n a <- arr (n - 1) <$> line\r\n let\r\n medianIsGE m = any (\\i -> psums ! i - pmins ! (i - k) > 0) [k..n]\r\n where\r\n psums = arr n $ scanl' (+) 0 $ (\\e -> if e < m then -1 else 1 :: Int) <$> elems a\r\n pmins = arr n $ scanl' min 0 $ tail $ elems psums\r\n print $ upperBound medianIsGE 1 n\r\n\r\narr :: Int -> [Int] -> UArray Int Int\r\narr n = listArray @UArray (0 :: Int, n)\r\n\r\nupperBound :: Integral a => (a -> Bool) -> a -> a -> a\r\nupperBound f = go\r\n where\r\n go lo hi\r\n | hi - lo <= 1 = if f hi then hi else lo\r\n | otherwise = if f mi then go mi hi else go lo mi\r\n where\r\n mi = (lo + hi) `div` 2\r\n\r\nline :: IO [Int]\r\nline = parseBS <$> BS.getLine\r\n\r\nparseBS :: BS.ByteString -> [Int]\r\nparseBS = go\r\n where\r\n go b = case BS.readInt b of\r\n Just (n, r) -> n:go (BS.dropWhile isSpace r)\r\n Nothing -> []\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List hiding (insert)\nimport Data.Semigroup\n\n-- length at least k, not length exactly k\n\nimport Data.Array.Unboxed\n\nlongestMedian :: [Int] -> Int -> Int -> Int\nlongestMedian a n x = let\n -- O(n)\n -- length of the longest segment with median at least x\n vals = scanl (\\ct y -> ct + if y >= x then 1 else 0-1) 0 a\n firstVisits :: UArray Int Int\n lastVisits :: UArray Int Int\n firstVisits = accumArray min maxBound (0-n, n) $ zip vals [0..]\n lastVisits = accumArray max minBound (0-n, n) $ zip vals [0..]\n prevs = scanl min maxBound $ elems firstVisits\n in foldl' max 0 $ zipWith (-) (elems lastVisits) prevs\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, k] <- readInts\n a <- readInts\n let\n go li ri = if li == ri\n then li\n else let\n mi = div (li + ri) 2\n in if longestMedian a n mi >= k\n then go (mi + 1) ri\n else go li mi\n putInts [go 1 (n+1) - 1]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Data.Array.Unboxed\r\nimport Data.List\r\nimport Data.Char ( isSpace )\r\n\r\nmain :: IO ()\r\nmain = do\r\n [n, k] <- line\r\n a <- arr (n - 1) <$> line\r\n let\r\n medianIsGE m = any (\\i -> psums ! i - pmins ! (i - k) > 0) [k..n]\r\n where\r\n psums = arr n $ scanl' (+) 0 $ (\\e -> if e < m then -1 else 1 :: Int) <$> elems a\r\n pmins = arr n $ scanl' min 0 $ elems psums\r\n print $ upperBound medianIsGE 1 n\r\n\r\narr :: Int -> [Int] -> UArray Int Int\r\narr n = listArray @UArray (0 :: Int, n)\r\n\r\nupperBound :: Integral a => (a -> Bool) -> a -> a -> a\r\nupperBound f = go\r\n where\r\n go lo hi\r\n | hi - lo <= 1 = if f hi then hi else lo\r\n | otherwise = if f mi then go mi hi else go lo mi\r\n where\r\n mi = (lo + hi) `div` 2\r\n\r\nline :: IO [Int]\r\nline = parseBS <$> BS.getLine\r\n\r\nparseBS :: BS.ByteString -> [Int]\r\nparseBS = go\r\n where\r\n go b = case BS.readInt b of\r\n Just (n, r) -> n:go (BS.dropWhile isSpace r)\r\n Nothing -> []\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Data.Array.Unboxed\r\nimport Data.List\r\nimport Data.Char ( isSpace )\r\n\r\nmain :: IO ()\r\nmain = do\r\n [n, k] <- line\r\n a <- arr (n - 1) <$> line\r\n let\r\n medianIsGE m = any (\\i -> psums ! i - pmins ! (i - k) > 0) [k..n]\r\n where\r\n psums = arr n $ scanl' (+) 0 $ (\\e -> if e < m then -1 else 1 :: Int) <$> elems a\r\n pmins = arr n $ scanl' min 0 $ elems psums\r\n print $ upperBound medianIsGE 1 n\r\n\r\narr :: Int -> [Int] -> UArray Int Int\r\narr n = listArray @UArray (0 :: Int, n)\r\n\r\nupperBound :: Integral a => (a -> Bool) -> a -> a -> a\r\nupperBound f = go\r\n where\r\n go lo hi\r\n | hi - lo <= 1 = lo\r\n | otherwise = if f mi then go mi hi else go lo mi\r\n where\r\n mi = (lo + hi) `div` 2\r\n\r\nline :: IO [Int]\r\nline = parseBS <$> BS.getLine\r\n\r\nparseBS :: BS.ByteString -> [Int]\r\nparseBS = go\r\n where\r\n go b = case BS.readInt b of\r\n Just (n, r) -> n:go (BS.dropWhile isSpace r)\r\n Nothing -> []\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List hiding (insert)\nimport Data.Semigroup\n\nimport qualified Data.IntMap.Strict as M\n\ndata Split = Split\n { smallVals :: !(M.IntMap Int)\n , largeVals :: !(M.IntMap Int)\n , imbalance :: !Int\n } deriving (Eq, Show)\n\ngetMedian :: Split -> Int\ngetMedian s = case M.maxViewWithKey $ smallVals s of\n Nothing -> maxBound\n Just ((v, _), _) -> v\n\nempty :: Split\nempty = Split M.empty M.empty 0\n\nremOne :: Int -> Maybe Int\nremOne x = if x == 1\n then Nothing\n else Just (x-1)\n\ncorrectBalance :: Split -> Split\ncorrectBalance inp@(Split lv rv lean)\n | lean < -1 = let\n (toMove, _) = M.findMax lv\n newlv = M.updateMax remOne lv\n newrv = M.insertWith (+) toMove 1 rv\n in Split newlv newrv $ lean + 2\n | lean > 0 = let\n (toMove, _) = M.findMin rv\n newlv = M.insertWith (+) toMove 1 lv\n newrv = M.updateMin remOne rv\n in Split newlv newrv $ lean - 2\n | otherwise = inp\n\ninsert :: Int -> Split -> Split\ninsert x s@(Split lv rv lean) = correctBalance $ if x <= getMedian s\n then Split (M.insertWith (+) x 1 lv) rv (lean - 1)\n else Split lv (M.insertWith (+) x 1 rv) (lean + 1)\n\nremove :: Int -> Split -> Split\nremove x s@(Split lv rv lean) = correctBalance $ if x <= getMedian s\n then Split (M.update remOne x lv) rv (lean + 1)\n else Split lv (M.update remOne x rv) (lean - 1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, k] <- readInts\n a <- readInts\n let\n (sa, ta) = splitAt k a\n initSplit = foldl' (flip insert) empty sa\n update currSplit (new, old) = insert new $ remove old currSplit\n allSplits = scanl update initSplit $ zip ta a\n putInts [foldl' max minBound $ map getMedian allSplits]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "dddeb7663c948515def967374f2b8812"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintS = do \r\n n <- readLn::IO Int \r\n xs <- readInts \r\n let nega = any (<0) xs \r\n if nega then putStrLn\"no\"\r\n else do putStrLn \"YES\"\r\n print $ maximum xs + 1\r\n putStrLn . unwords . map show $ [0..(maximum xs)]\r\n \r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t printS", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- getInts\n let result = if any (<0) as\n then string7 \"NO\"\n else string7 \"YES\\n101\\n\" `mappend` (mconcat $ intersperse (charUtf8 ' ') $ map intDec [0..100])\n return $ result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n if length (filter (<0) a) > 0 then putStrLn \"NO\"\r\n else do\r\n putStrLn \"YES\"\r\n let m = maximum a\r\n print $ m + 1\r\n putStrLn . unwords . map show $ [0..m]\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Data.List (intercalate)\r\nimport Control.Monad (replicateM)\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nsolve = do getLine\r\n xs <- (map read . words) <$> getLine\r\n putStrLn (if any (< 0) xs then \"nO\" else (\"yEs\\n101\\n\" ++ intercalate \" \" (map show [0..100])))\r\n"}, {"source_code": "makeInteger :: [String] -> [Int]\r\nmakeInteger = map read\r\n\r\nmain :: IO()\r\nmain = do\r\n line <- getLine\r\n let t = (read line::Int)\r\n solve t\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = return ()\r\nsolve t = do\r\n solve2\r\n solve (t - 1)\r\n\r\nsolve2 :: IO()\r\nsolve2 = do\r\n line <- getLine\r\n let n = (read line::Int)\r\n line <- getLine\r\n let inparr = words line\r\n let arr = makeInteger inparr\r\n let arr2 = [ if x < 0 then False else True | x <- arr ]\r\n let ck = elem False arr2\r\n if ck then do\r\n putStrLn \"NO\"\r\n else do \r\n putStrLn \"YES\"\r\n putStrLn \"101\"\r\n let arrprint = [show x | x <- [0..100]]\r\n let strprint = unwords arrprint\r\n putStrLn strprint"}, {"source_code": "-- uninhm\r\n-- https://codeforces.com/contest/1536/problem/A\r\n-- greedy\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nsolution = unlines [ \"YES\"\r\n , \"101\"\r\n , unwords (map show [0..100])\r\n ]\r\n\r\nmain = do\r\n t <- getInt\r\n replicateM_ t $ do\r\n n <- getInt\r\n a <- getInts\r\n if any (< 0) a then\r\n putStrLn \"NO\"\r\n else\r\n putStr solution\r\n"}, {"source_code": "-- uninhm\r\n-- https://codeforces.com/contest/1536/problem/A\r\n-- greedy\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nsolution = unlines [ \"YES\"\r\n , \"101\"\r\n , unwords (map show [0..100])\r\n ]\r\n\r\nmain = do\r\n t <- getInt\r\n replicateM_ t $ do\r\n n <- getInt\r\n a <- getInts\r\n if or [ i < 0 | i <- a ] then\r\n putStrLn \"NO\"\r\n else\r\n putStr solution\r\n"}, {"source_code": "-- uninhm\r\n-- https://codeforces.com/contest/1536/problem/A\r\n-- greedy\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nsolution = unlines [ \"YES\"\r\n , \"101\"\r\n , unwords (map show [0..100])\r\n ]\r\n\r\nmain = do\r\n t <- getInt\r\n replicateM_ t $ do\r\n n <- getInt\r\n a <- getInts\r\n if or [ True | i <- a, i<0 ] then\r\n putStrLn \"NO\"\r\n else\r\n putStr solution\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nsolution = \"YES\\n\" ++ \"101\\n\" ++ unwords (map show [0..100]) ++ \"\\n\"\r\n\r\nmain = do\r\n t <- getInt\r\n replicateM_ t $ do\r\n n <- getInt\r\n a <- getInts\r\n if or [ True | i <- a, i<0 ] then\r\n putStrLn \"NO\"\r\n else\r\n putStr solution\r\n"}, {"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Int) $ words s\r\n mn = minimum a\r\n mx = maximum a\r\n putStrLn $\r\n if mn < 0 then\r\n \"NO\"\r\n else\r\n \"YES\\n\" ++ show(mx + 1) ++ \"\\n\" ++\r\n (concat $ map (\\x -> show x ++ \" \") [0..mx])\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}, {"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Int) $ words s\r\n [mn, mx] = [minimum a, maximum a]\r\n putStrLn $\r\n if mn < 0 then\r\n \"NO\"\r\n else\r\n \"YES\\n\" ++ show(mx + 1) ++ \"\\n\" ++\r\n (concat $ map (\\x -> show x ++ \" \") [0..mx])\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}, {"source_code": "\nreadSpaceLine :: Read (a) => IO [a]\nreadSpaceLine = do ln <- getLine\n return . map read $ words ln\n\ndoTestCase :: IO()\ndoTestCase = do _ <- getLine\n ns <- readSpaceLine :: IO [Int]\n if minimum ns < 0\n then putStrLn \"NO\"\n else let m = maximum ns\n in do putStrLn \"YES\"\n print $ m + 1\n putStrLn . unwords . map show $ [0..maximum ns]\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n"}, {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport Data.List\r\nimport Text.Printf\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ngetInts :: IO [Int]\r\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n [caseNum] <- getInts\r\n forM_ [1..caseNum] $ \\_ -> do\r\n [n] <- getInts\r\n arr <- getInts\r\n\r\n let areNeg = length ([x | x <- arr, x < 0]) > 0\r\n\r\n if areNeg then do\r\n printf(\"No\\n\")\r\n else do\r\n printf(\"Yes\\n\")\r\n let sol = [0..100]\r\n printf (\"%d\\n\") (length sol)\r\n \r\n C.putStrLn $ C.pack $ unwords $ map show $ sol\r\n\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\nimport Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\tgetLine\r\n\tas <- readInts\r\n\tlet\r\n\t\tg = foldl1 gcd as\r\n\t\tma = maximum as\r\n\t\tres = takeWhile ( <= ma ) [ i * g | i <- [ 0 .. ] ]\r\n\tif minimum as < 0\r\n\t\tthen putStrLn \"No\"\r\n\t\telse do\r\n\t\t\tputStrLn \"Yes\"\r\n\t\t\tprint $ length res\r\n\t\t\tprintList $ res"}], "negative_code": [{"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Int) $ words s\r\n [mn, mx] = [minimum a, maximum a]\r\n putStrLn $\r\n if mn < 0 then\r\n \"NO\"\r\n else\r\n \"YES\\n\" ++ show(mx + 1) ++ \"\\n\" ++\r\n (concat $ map (\\x -> show x ++ \" \") [0..mx + 1])\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}, {"source_code": "\nreadSpaceLine :: Read (a) => IO [a]\nreadSpaceLine = do ln <- getLine\n return . map read $ words ln\n\ndoTestCase :: IO()\ndoTestCase = do _ <- getLine\n ns <- readSpaceLine :: IO [Int]\n if minimum ns < 0\n then putStrLn \"NO\"\n else let m = maximum ns\n in do putStrLn \"YES\"\n print m\n putStrLn . unwords . map show $ [0..maximum ns]\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n"}, {"source_code": "\nreadSpaceLine :: Read (a) => IO [a]\nreadSpaceLine = do ln <- getLine\n return . map read $ words ln\n\ndoTestCase :: IO()\ndoTestCase = do _ <- getLine\n ns <- readSpaceLine :: IO [Int]\n if minimum ns < 0\n then putStrLn \"NO\"\n else do putStrLn \"YES\"\n putStrLn . unwords . map show $ [0..maximum ns]\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n"}, {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport Data.List\r\nimport Text.Printf\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ngetInts :: IO [Int]\r\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n [caseNum] <- getInts\r\n forM_ [1..caseNum] $ \\_ -> do\r\n arr <- getInts\r\n\r\n let areNeg = length ([x | x <- arr, x < 0]) > 0\r\n\r\n if areNeg then do\r\n printf(\"No\\n\")\r\n else do\r\n printf(\"Yes\\n\")\r\n let sol = [0..100]\r\n printf (\"%d\\n\") (length sol)\r\n \r\n C.putStrLn $ C.pack $ unwords $ map show $ sol\r\n\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\nimport Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\tgetLine\r\n\tas <- readInts\r\n\tlet\r\n\t\tg = foldl1 gcd as\r\n\t\tma = maximum as\r\n\t\tres = takeWhile ( <= ma ) [ i * g | i <- [ 0 .. ] ]\r\n\tif minimum as < 0\r\n\t\tthen putStrLn \"No\"\r\n\t\telse do\r\n\t\t\tprint $ length res\r\n\t\t\tprintList $ res"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- getInts\n let result = if any (<0) as\n then string7 \"NO\"\n else string7 \"101\\n\" `mappend` (mconcat $ intersperse (charUtf8 ' ') $ map intDec [0..100])\n return $ result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "src_uid": "5698e6fd934b9f6b847d7e30a3d06f2b"} {"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Array ((!), listArray)\nimport Data.Char (ord, digitToInt)\nimport Data.List (intercalate, group, sort, unfoldr)\n\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\nisPrime :: Integral a => a -> Bool\nisPrime n = all (\\x -> n `mod` x /= 0)\n $ takeWhile (\\x -> x*x <= n) primes\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3,5..]\n\nfactorization :: Integral a => a -> [(a, a)]\nfactorization 0 = error \"Don't factorization zero.\"\nfactorization 1 = [(2,0)]\nfactorization n = f n primes\n where\n f 1 _ = []\n f n (p:ps)\n | n `mod` p == 0 = (p, a) : f m ps\n | p * p > n = [(n, 1)]\n | otherwise = f n ps\n where\n (m, a) = f' n 0\n f' n i\n | n `mod` p == 0 = f' (n `div` p) (succ i)\n | otherwise = (n, i)\n\ndividers :: Integral a => a -> [a]\ndividers 0 = error \"Don't dividers zero.\"\ndividers n = sort $ map (product . zipWith (^) ps) as\n where\n (ps, final) = unzip $ factorization n\n start = map (const 0) ps\n as = start : unfoldr next start\n next curr\n | curr == final = Nothing\n | otherwise = Just (a, a)\n where\n a = replicate i 0\n ++ [(curr !! i) + 1]\n ++ drop (i+1) curr\n i = length $ takeWhile (== 0) $ zipWith (-) final curr\n\nsolve :: Integer -> [Integer] -> Integer\nsolve 0 s = sum (map g z) - sum [f i * f j | i <- z, j <- z]\n where\n z = map (fromIntegral . length) $ filter ((== 0) . head) $ group s\n n = fromIntegral $ length s\n f n = n * (n+1) `div` 2\n g m = 2 * f m * f n\nsolve k s = sum [countA i * countA (k `div` i) | i <- dividers k]\n where\n n = length s\n a = listArray (1, n) s\n zerosL = listArray (1, n) $ init\n $ scanl (\\a b -> (b == 0) ? (a + 1) $ 0) 0 s\n zerosR = listArray (1, n) $ tail\n $ scanr (\\a b -> (a == 0) ? (b + 1) $ 0) 0 s\n\n countA m = countA' m 1 1 (a ! 1)\n countA' m l r s\n | l > n = 0\n | a ! l == 0 = countA' m (l+1) r s\n | r < l = countA' m l (r+1) (s + a ! (r+1))\n | s == m = (1 + zerosL ! l) * (1 + zerosR ! r) + countA' m (l+1) r (s - a ! l)\n | s < m = if r == n then 0 else countA' m l (r+1) (s + a ! (r+1))\n | s > m = countA' m (l+1) r (s - a ! l)\n \n\nmain :: IO ()\nmain = do\n k <- readLn\n s <- liftM (map (fromIntegral . digitToInt)) getLine\n print $ solve k s\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Char\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.Base(unsafeAt)\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\n\nmain = do\n a <- readLn\n s <- map digitToInt <$> getLine\n print $ solve a s\n\nsolve :: Int -> [Int] -> Integer\nsolve a l | a == 0 = cast (count ! 0) * (cast (n * (n+1) - count ! 0))\n | otherwise = sum [ cast v * cast (count ! x)| (m,v) <- assocs count, m > 0, v > 0,\n let (x,y) = divMod a m ,y == 0, x <= 4000*9]\n where\n n = length l\n s :: UArray Int Int\n s = listArray (0,n) (scanl (+) 0 l)\n as = [(unsafeAt s j - unsafeAt s (i-1),1) | i <- [1..n], j <- [i..n]]\n count :: UArray Int Int\n count = accumArray (+) 0 (0,4000*9) as\n cast = fromIntegral\n\n{-\ncheck = do\n a <- randomRIO (0,100)\n n <- return 2\n l <- replicateM n (randomRIO (1,9))\n print (a,n,l)\n print $ solve a l\n -}\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Char (ord)\nimport Data.Int (Int64)\nimport Data.List (tails)\nimport Control.Applicative ((<$>))\nimport Data.Array.Unboxed (UArray, accumArray, assocs, (!))\n\nsolve :: Int -> String -> Int64\nsolve acc str\n | acc == 0 = (n * (n + 1) - zero) * zero\n | otherwise = sum . map count . filter pred . tail . assocs $ cnt\n where\n n = fromIntegral $ length str :: Int64\n a = scanl (+) 0 $ map ((+ inc).ord) str :: [Int]\n where inc = - ord '0'\n\n b = concat . map chunk . tails $ a\n where\n chunk [] = []\n chunk (x:xs) = map (+ (-x)) xs\n\n\n size = last a :: Int\n cnt = accumArray (+) 0 (0, size) . zip b $ repeat 1 :: UArray Int Int64\n\n zero = cnt ! 0\n\n pred (_, 0) = False\n pred (i, _) = acc `mod` i == 0\n\n count (i, j)\n | size < i' = 0\n | otherwise = j * cnt ! i'\n where i' = acc `div` i\n\nmain = do\n acc <- read <$> getLine\n str <- getLine\n print $ solve acc str\n"}], "negative_code": [], "src_uid": "b429b42ba8be9df4b87b68420e9873bc"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([_, k]:xs:xss) = solve k xs : process xss\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = minimum [cost c xs | c <- [1 .. 100]]\n where\n cost c xs\n | null xs = 0\n | head xs == c = cost c (tail xs)\n | otherwise = 1 + cost c (drop k xs)\n", "positive_code": [{"source_code": "-- {-# LANGUAGE \n-- BangPatterns\n-- , BlockArguments\n-- , DataKinds\n-- , DeriveGeneric\n-- , DerivingStrategies\n-- , DerivingVia\n-- , FlexibleContexts\n-- , FlexibleInstances\n-- , GADTs\n-- , GeneralizedNewtypeDeriving\n-- , KindSignatures\n-- , LambdaCase\n-- , MultiParamTypeClasses\n-- , MultiWayIf\n-- , NPlusKPatterns\n-- , NegativeLiterals\n-- , OverloadedLabels\n-- , OverloadedStrings\n-- , ParallelListComp\n-- , PolyKinds\n-- , RankNTypes\n-- , ScopedTypeVariables\n-- , StrictData\n-- , TupleSections\n-- , TypeApplications\n-- , TypeFamilies\n-- , TypeOperators\n-- , UndecidableInstances\n-- , ViewPatterns\n-- #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\n-- import System.IO\n-- import Data.Proxy\n-- import GHC.TypeLits\n-- import GHC.Generics ( Generic )\n-- import GHC.Exts\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\n-- import Control.Monad.Trans.Class ( MonadTrans(lift) )\n\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_ t $ do\n [n, k] <- getInts\n c <- getInts\n print $ minimum [ solve col k 0 c 0 | col <- [1 .. 100] ]\n\nsolve _ _ _ [] ans = ans\nsolve col k 0 (c : cs) ans =\n if c == col then solve col k 0 cs ans else solve col k k (c : cs) (ans + 1)\nsolve col k t (_ : cs) ans = solve col k (t -1) cs ans\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [n, k] <- (map read . words) <$> getLine :: IO [Int]\n houses <- (map read . words) <$> getLine :: IO [Int]\n let colors = nub houses\n putStrLn $ show $ minimum $ map (daysToPaint k houses) colors\n\ndaysToPaint :: Int -> [Int] -> Int -> Int\ndaysToPaint k houses color = daysToPaint' houses color 0\n where\n daysToPaint' [] color counter = counter\n daysToPaint' (house:houses) color counter =\n if color == house\n then daysToPaint' houses color counter\n else daysToPaint' (drop (k-1) houses) color (counter + 1)\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([_, k]:xs:xss) = solve k xs : process xss\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = minimum [cost c xs | c <- [1 .. 100]]\n where\n cost _ [] = 0\n cost c (x:xs)\n | c == x = cost c xs\n | otherwise = 1 + cost c (drop k xs)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map.Strict as Map\n\nprecolored :: [(Int, Int)] -> Map.Map Int Int\nprecolored xs = undefined\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [n, k] <- (map read . words) <$> getLine :: IO [Int]\n colors <- (map read . words) <$> getLine :: IO [Int]\n --print $ map (\\x -> (head x, div (length x) k)) (group colors)\n let precolored = Map.fromListWith (+) $ map (\\x -> (head x, div (length x) k)) (group colors)\n let (dominantColor, dominantCount) = Map.foldrWithKey maxWithKey (0, 0) precolored\n let wrongGroup = filter (/= [dominantColor]) $ groupBy (wrongColor dominantColor) colors\n let groupWork = sum $ map (\\x -> ceiling $ (fromIntegral $ length x) / (fromIntegral k)) wrongGroup\n putStrLn $ show $ groupWork\n\nwrongColor :: Int -> Int -> Int -> Bool\nwrongColor correct a b = (a /= correct && b /= correct)\n\nmaxWithKey :: Int -> Int -> (Int, Int) -> (Int, Int)\nmaxWithKey key value (oldKey, oldValue) = if value > oldValue then (key, value) else (oldKey, oldValue)\n"}], "src_uid": "9d3ffe0063686bdcf567f025d8e4d998"} {"source_code": "import qualified Data.Char as DC\r\n\r\nsolve :: Int -> IO ()\r\nsolve _ = do\r\n n <- getLine\r\n s <- getLine\r\n let xs = map DC.digitToInt (init s)\r\n lstdig = DC.digitToInt (last s)\r\n ans = lstdig + sum [x + 1 | x <- xs, x /= 0]\r\n print(ans)\r\nmain = do \r\n tc <- getLine\r\n let testcase = read tc :: Int\r\n mapM_ solve [1..testcase]\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char (digitToInt)\n\ncalc :: [Int] -> Int\ncalc s =\n foldl (\\acc (x,i) ->\n if x==0 then\n acc\n else if i==0 then\n acc+x\n else\n acc+x+1\n ) 0 $ zip s [0..]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n unused <- getLine\n line <- getLine\n print $ calc $ reverse $ map digitToInt line\n"}], "negative_code": [], "src_uid": "6571fdd506a858d7620c2faa0fe46cc1"} {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . (map read) . words\n\nsol :: [Int] -> [String]\nsol (_:xs) = wrap $ case soly (zip xs [2..]) 1 of\n Just _ -> \"Yes\"\n Nothing -> \"No\"\n\nsoly :: [(Int,Int)] -> Int -> Maybe Bool\nsoly ms t = case filter ((==t).fst) ms of\n [] -> Just True\n xs -> let ss = map ((soly ms).snd) xs\n in if (all isJust $ ss) && (3 <= (length $ filter ((==True).fromJust) ss))\n then Just False\n -- else Nothing\n else Nothing\n\n\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Integer]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n", "positive_code": [{"source_code": "main = getContents >>= putStrLn . solve . map read . lines\n\nsolve (n:p') = if minimum lnum >= 3 then \"Yes\" else \"No\"\n where p = map pred p'\n leaf = filter (not . (`elem` p)) [1 .. n - 1]\n lp = [ p !! (x - 1) | x <- leaf]\n lnum = [ length $ filter (==x) lp | x <- p ] \n"}, {"source_code": "import Data.List\n\nmain = getContents >>= putStrLn . solve . map read . lines\n\nsolve (n:p') = if minimum lnum >= 3 then \"Yes\" else \"No\"\n where p = map pred p'\n leaf = filter (not . (`elem` p)) [1 .. n - 1]\n lp = [ p !! (x - 1) | x <- leaf]\n lnum = [ length $ elemIndices x lp | x <- p ] \n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.Map as Map\n\nupdateIsLeaf :: Map.Map Int Bool -> [Int] -> Map.Map Int Bool\nupdateIsLeaf a [] = a\nupdateIsLeaf a (x:xs) = Map.insert x False a'\n where a' = updateIsLeaf a xs\n\nupdateParentChildCount :: Map.Map Int Int -> Map.Map Int Bool -> Int -> Int -> Map.Map Int Int\nupdateParentChildCount childCount isLeaf parent node\n | (Map.lookup node isLeaf) == Nothing = childCount\n | fromJust (Map.lookup node isLeaf) == False = childCount\n | otherwise = Map.insertWith (+) parent 1 childCount\n\ngetFromMap :: Int -> Map.Map Int Bool -> Bool\ngetFromMap v m \n | Map.lookup v m == Nothing = False\n | otherwise = fromJust $ Map.lookup v m\n\nisGood :: Map.Map Int Bool -> Bool -> Int -> Int -> Bool\nisGood leafMap acc key value\n | isLeaf == True = acc\n | isLeaf == False = acc && (value >= 3)\n where isLeaf = getFromMap key leafMap\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n parents <- mapM (\\_ -> (read :: String -> Int) <$> getLine) [1..(n - 1)]\n let emptyMap = Map.fromList $ zip [1..n] $ repeat True\n isLeafMap = updateIsLeaf emptyMap parents\n zeroChildCount = Map.fromList $ zip [1..n] [0,0..]\n updatedChildCount = foldl' (\\m (a, b) -> updateParentChildCount m isLeafMap a b) zeroChildCount $ zip parents [2..]\n isSpruce = Map.foldlWithKey' (isGood isLeafMap) True updatedChildCount\n -- putStrLn . show $ updatedChildCount\n putStrLn $ if isSpruce then \"Yes\" else \"No\"\n"}, {"source_code": "import qualified Data.Map as M\nimport qualified Data.Set as S\n\nrun :: Int -> [Int] -> Bool\nrun n l = let mm = M.fromList $ zip [1..n] (repeat S.empty)\n edges = foldr (\\(idx, parent) m -> M.adjust (S.insert idx) parent m) mm (zip [2..n] l)\n leaves = M.keysSet (M.filter S.null edges)\n in all ((<=) 3 . S.size . S.filter (`S.member` leaves)) . filter (not . S.null) . map snd . M.toList $ edges\n \n\nmain :: IO ()\nmain = do\n n:l <- (map read . words) `fmap` getContents :: IO [Int]\n let ret = run n l\n putStrLn $ if ret then \"Yes\" else \"No\"\n \n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = getContents >>= print . solve . map read . lines\n\nsolve (n:p') = if minimum lnum >= 3 then \"Yes\" else \"No\"\n where p = map pred p'\n leaf = filter (not . (`elem` p)) [1 .. n - 1]\n lp = [ p !! (x - 1) | x <- leaf]\n lnum = [ length $ elemIndices x lp | x <- p ] \n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.Map as Map\n\nupdateIsLeaf :: Map.Map Int Bool -> [Int] -> Map.Map Int Bool\nupdateIsLeaf a [] = a\nupdateIsLeaf a (x:xs) = Map.insert x False a'\n where a' = updateIsLeaf a xs\n\nupdateParentChildCount :: Map.Map Int Int -> Map.Map Int Bool -> Int -> Int -> Map.Map Int Int\nupdateParentChildCount childCount isLeaf parent node\n | (Map.lookup node isLeaf) == Nothing = childCount\n | fromJust (Map.lookup node isLeaf) == False = childCount\n | otherwise = Map.insertWith (+) parent 1 childCount\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n parents <- mapM (\\_ -> (read :: String -> Int) <$> getLine) [1..(n - 1)]\n let emptyMap = Map.fromList $ zip [1..n] $ repeat True\n isLeafMap = updateIsLeaf emptyMap parents\n zeroChildCount = Map.fromList $ zip [1..n] [0,0..]\n updatedChildCount = foldl' (\\m (a, b) -> updateParentChildCount m isLeafMap a b) zeroChildCount $ zip parents [2..]\n isSpruce = Map.foldl' (\\x v -> x && (v == 0 || v >= 3)) True updatedChildCount\n putStrLn $ if isSpruce then \"Yes\" else \"No\"\n"}], "src_uid": "69edc72ec29d4dd56751b281085c3591"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n \ngetIntList :: IO [Int]\ngetIntList = fmap (map read) getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, p, k] <- getIntList\n a <- sort <$> getIntList\n print $ bs 0 (n + 1) p k a\n\nbs :: Int -> Int -> Int -> Int -> [Int] -> Int\nbs l r p k a\n | l + 1 >= r = l\n | otherwise =\n let {\n mid = (l + r) `div` 2\n } in\n if check mid p k a\n then bs mid r p k a\n else bs l mid p k a \n\ncheck :: Int -> Int -> Int -> [Int] -> Bool\ncheck x p k a =\n let {\n r = x `mod` k;\n d = x - r;\n (le, ri) = splitAt r a;\n rit = take d ri\n } in\n (p >=) $ (\n sum le + \n (sum . map (\\(idx, val) -> if idx `mod` k == 0 then val else 0) $\n zip ([1..] :: [Int]) rit))", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n--Arrays starten mit Index 1\npreprocess :: Int -> [Int] -> Array Int Int\npreprocess n l = listArray (1,n) $ sort l\n\nsplitArr :: Int -> Int -> Array Int Int -> [Array Int Int]\nsplitArr n k arr = do\n x <- [1..k]\n let f y= x+ k*(y-1)\n return $ ixmap (1,1+(n-x) `div` k) f arr\n\nfoldLArrayWhile :: (a -> b -> a) -> Int -> a -> (a -> Bool) -> Array Int b -> (Int,a)\nfoldLArrayWhile bin currentIndex currentValue predicate arr =\n if (currentIndex> snd (bounds arr))|| bool\n then (currentIndex-1, currentValue)\n else foldLArrayWhile bin newIndex newValue predicate arr\n where\n newValue = bin currentValue (arr!currentIndex)\n bool = predicate newValue\n newIndex = currentIndex+1\n\neinzeln :: Int -> Array Int Int -> (Int,Int)\neinzeln p = foldLArrayWhile (+) 1 0 (>p)\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n p k l =maximum arrs'\n where\n arr = preprocess n l\n arrs =zip [0..] $ splitArr n k arr\n arrs' = map (\\(x,a) ->1 + x + k* ( fst ( einzeln p a) -1)) arrs\n\nroutine :: IO ()\nroutine = do\n [n,p,k] <- (map read.words) <$> getLine\n l <- (map read.words) <$> getLine\n print $ solve n p k l\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "negative_code": [], "src_uid": "b9bafdc49709b4fc4b5fe786d5aa99a3"} {"source_code": "import Data.Bits (xor)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.Functor ((<$>))\nimport qualified Data.HashMap.Strict as H\nimport Data.Maybe (fromJust, fromMaybe)\n\nsolve :: Int -> [Int] -> H.HashMap Int Integer -> Integer\nsolve _ [] _ = 0\nsolve x (y:ys) h = v + solve x ys h'\n where\n v = fromMaybe 0 (H.lookup (y `xor` x) h)\n v' = fromMaybe 0 (H.lookup y h)\n h' = H.insert y (v' + 1) h\n\nmain :: IO ()\nmain = do\n [_, x] <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n ys <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n let result = solve x ys H.empty\n print result\n", "positive_code": [{"source_code": "import Data.Bits\nimport qualified Data.IntMap as M\nmain = interact $ show . solve . map read . tail . words\nsolve (x:as) = (`div` 2) $ sum $ map f as\n where s = M.fromListWith (+) $ zip as (repeat 1)\n f a | a' `M.notMember` s = 0\n | a' == a = n-1\n | otherwise = n where\n a' = a `xor` x\n Just n = M.lookup a' s\n"}, {"source_code": "import Data.Bits\nimport Control.Applicative\nimport Data.Monoid (mempty)\n\nimport qualified Data.IntMap as IntMap\n\ncomb v i (sum, map) =\n let nextmap =\n IntMap.insertWith (+) i 1 map\n in case IntMap.lookup (xor v i) map of\n Just f -> (sum + f, nextmap)\n Nothing -> (sum, nextmap)\n\nsolve x =\n foldr (comb x) (0, mempty)\n\nmain = do\n line <- words <$> getLine\n let [_, x] = read <$> line\n numbers <- map read . words <$> getLine\n print $ fst $ solve x numbers\n"}, {"source_code": "import Data.Bits (xor)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.HashMap.Lazy as H\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.Functor ((<$>))\n\nsolve :: Int -> [Int] -> H.HashMap Int Int -> Integer\nsolve _ [] _ = 0\nsolve x (y:ys) h = v + solve x ys h'\n where\n v = toInteger $ fromMaybe 0 (H.lookup (y `xor` x) h)\n v' = fromMaybe 0 (H.lookup y h)\n h' = H.insert y (v' + 1) h\n\nmain :: IO ()\nmain = do\n [_, x] <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n ys <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n let result = solve x ys H.empty\n print result\n"}, {"source_code": "import Data.Bits (xor)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.HashMap.Lazy as H\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.Functor ((<$>))\n\nsolve :: Int -> [Int] -> H.HashMap Int Integer -> Integer\nsolve _ [] _ = 0\nsolve x (y:ys) h = v + solve x ys h'\n where\n v = fromMaybe 0 (H.lookup (y `xor` x) h)\n v' = fromMaybe 0 (H.lookup y h)\n h' = H.insert y (v' + 1) h\n\nmain :: IO ()\nmain = do\n [_, x] <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n ys <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n let result = solve x ys H.empty\n print result\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map.Strict as M\nimport Data.Bits\n\nsolve :: Int -> [Int] -> Integer\nsolve x nums = work nums `div` 2\n where m = M.fromListWith (+) $ zip nums (repeat 1)\n work [] = 0\n work (l:ls) =\n let z = x `xor` l\n in case M.lookup z m of\n Nothing -> work ls\n Just v -> (if l == z then (v-1) else v) + work ls\n\n\nmain = do\n [n, x] <- map read . words <$> getLine\n nums <- map read . words <$> getLine\n print $ solve x nums\n"}, {"source_code": "import qualified Data.Map.Strict as Map\nimport Data.Bits (xor)\n\nreadInts :: IO [Int]\nreadInts = do\n s <- getLine\n return $ map read $ words s\n\nmain = do\n [n, x] <- readInts\n a <- readInts\n let m = foldl (\\mm v -> Map.insertWith (+) v 1 mm) Map.empty a\n let ans = Map.foldlWithKey (\\accum v cnt -> accum + cnt * (if x == 0 then cnt - 1 else Map.findWithDefault 0 (v `xor` x) m)) 0 m\n putStrLn $ show (ans `div` 2)"}], "negative_code": [{"source_code": "import qualified Data.Map.Strict as Map\nimport Data.Bits (xor)\n\nreadInts :: IO [Int]\nreadInts = do\n s <- getLine\n return $ map read $ words s\n\nmain = do\n [n, x] <- readInts\n a <- readInts\n let m = foldl (\\mm v -> Map.insertWith (+) v 1 mm) Map.empty a\n let ans = Map.foldlWithKey (\\accum v cnt -> accum + cnt * (Map.findWithDefault 0 (v `xor` x) m)) 0 m\n putStrLn $ show (ans `div` 2)"}, {"source_code": "import Data.Bits\nimport qualified Data.IntMap as M\nmain = interact $ show . solve . map read . tail . words\nsolve (x:as) = (`div` 2) $ sum $ map f as\n where s = M.fromListWith (+) $ zip as (repeat 1)\n f a | a' < a = 0\n | a' == a = n-1\n | otherwise = 2*n where\n a' = a `xor` x\n Just n = M.lookup a s\n"}, {"source_code": "import Data.Bits\nimport Data.Ord\nimport Data.List\nimport Control.Applicative\n\ncmp v x = min x (xor v x)\n\norder :: (Bits a, Ord a) => a -> [a] -> [a]\norder v = sortBy (comparing (cmp v))\n\npart :: (Ord a, Bits a) => a -> [a] -> [[[a]]]\npart v = map group . groupBy (\\x y -> cmp v x == cmp v y)\n\ncount [x, y] = length x * length y\ncount _ = 0\n\nsolve :: Int -> [Int] -> Int\nsolve x =\n sum . map count . part x . order x\n\nmain = do\n line <- words <$> getLine\n let [_, x] = read <$> line\n numbers <- map read . words <$> getLine\n print $ solve x numbers\n"}, {"source_code": "import Data.Bits\nimport Data.Ord\nimport Data.List\nimport Control.Applicative\nimport Data.Monoid\n\ncmp v x = min x (xor v x)\n\norder :: (Bits a, Ord a) => a -> [a] -> [a]\norder v = sortBy (comparing (cmp v) <> comparing id)\n\npart :: (Ord a, Bits a) => a -> [a] -> [[[a]]]\npart v = map group . groupBy (\\x y -> cmp v x == cmp v y)\n\ncount v [x, y] = length x * length y\ncount v [x] | v == 0 = length x * length x\ncount v _ = 0\n\nsolve :: Int -> [Int] -> Int\nsolve x =\n sum . map (count x) . part x . order x\n\nmain = do\n line <- words <$> getLine\n let [_, x] = read <$> line\n numbers <- map read . words <$> getLine\n print $ solve x numbers\n"}, {"source_code": "import Data.Bits\nimport Data.Ord\nimport Data.List\nimport Control.Applicative\nimport Data.Monoid\n\ncmp v x = min x (xor v x)\n\norder :: (Bits a, Ord a) => a -> [a] -> [a]\norder v = sortBy (comparing (cmp v) <> comparing id)\n\npart :: (Ord a, Bits a) => a -> [a] -> [[[a]]]\npart v = map group . groupBy (\\x y -> cmp v x == cmp v y)\n\ncount [x, y] = length x * length y\ncount _ = 0\n\nsolve :: Int -> [Int] -> Int\nsolve x =\n sum . map count . part x . order x\n\nmain = do\n line <- words <$> getLine\n let [_, x] = read <$> line\n numbers <- map read . words <$> getLine\n print $ solve x numbers\n "}, {"source_code": "import Data.Bits (xor)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.HashMap.Lazy as H\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.Functor ((<$>))\n\nsolve :: Int -> [Int] -> H.HashMap Int Int -> Int\nsolve _ [] _ = 0\nsolve x (y:ys) h = v + solve x ys h'\n where\n v = fromMaybe 0 (H.lookup (y `xor` x) h)\n v' = fromMaybe 0 (H.lookup y h)\n h' = H.insert y (v' + 1) h\n\nmain :: IO ()\nmain = do\n [_, x] <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n ys <- map (fst . fromJust . BS8.readInt) . BS8.words <$> BS.getLine\n let result = solve x ys H.empty\n print result\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map.Strict as M\nimport Data.Bits\n\nsolve :: Int -> [Int] -> Integer\nsolve x nums = work nums `div` 2\n where m = M.fromListWith (+) $ zip nums (repeat 1)\n work [] = 0\n work (l:ls) =\n let z = x `xor` l\n in case M.lookup z m of\n Nothing -> work ls\n Just v -> (if l == z then v * (v-1) else v) + work ls\n\n\nmain = do\n [n, x] <- map read . words <$> getLine\n nums <- map read . words <$> getLine\n print $ solve x nums\n"}], "src_uid": "daabf732540e0f66d009dc211c2d7b0b"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = unsafePerformIO (putStrLn (s ++ \": \" ++ show x)) `seq` x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = (toInteger $ length i1) * (toInteger $ if o1 == 0 then k else (k - 1))\n l2 = toInteger $ length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ a@((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n print $ condition a\n \n \n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = unsafePerformIO (putStrLn (s ++ \": \" ++ show x)) `seq` x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n (toInteger k) $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = (toInteger $ length i1) * if o1 == 0 then k else k - 1\n l2 = toInteger $ length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Foreign.C.Types\nimport Foreign.C.String\nimport System.IO\nimport System.IO.Unsafe\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n (toInteger k) $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) ->\n let l1 = (toInteger $ length i1) * if o1 == 0 then k else k - 1\n l2 = toInteger $ length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry $ c_printf format)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nlen :: (Num n) => [a] -> n\nlen = fromIntegral.length\n{-# INLINE len #-}\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr . solve n k . sort $ zip xs [1..n]\n\nsolve :: Int -> Int -> [(Int,Int)] -> String\nsolve n k ((0,root):xis) = go 1 (shows(n-1).('\\n':)) [root] xis\n where\n go _ res _ [] = res \"\"\n go _ _ [] _ = \"-1\"\n go !depth !res parents xis\n | fst(head xis) < depth || len parents * toInteger k' < len yis = \"-1\"\n | otherwise = go (depth+1) (res.res') (map snd yis) zis\n where\n k' = if depth == 1 then k else k-1\n (yis,zis) = span ((depth==).fst) xis\n yiss = slices k' $ map snd yis\n p & c = shows p.(' ':).shows c.('\\n':)\n res' = foldr(.) id $zipWith (\\p cs->foldr((.).(p&))id cs) parents yiss\nsolve _ _ _ = \"-1\"\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\ndata Error a = Success a | Fail String\n\ninstance Functor Error where\n fmap f (Success a) = Success (f a)\n fmap f (Fail s) = Fail s\n\ninstance Monad Error where\n return = Success\n Success a >>= f = f a\n Fail s >>= f = Fail s\n fail = Fail\n\ninstance Applicative Error where\n pure = return\n (<*>) = ap\n\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n case es of\n Success es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Fail s -> print $ -1\n {-\n if n == 100000 && k == n - 1 && ds !! 5767 == 0 then\n putStrLn s\n else print (-1)\n -}\n\ntype Edge = (Int,Int)\n\n\nsolve :: (Monad m,Applicative m) => Int -> Int -> [Int] -> m [Edge]\nsolve n k ds = case queue of\n [(0,[root])] -> return []\n (0,[root]):queue' -> do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n _ -> fail \"no root found or multiple root found\"\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n rootEdges root (d,vs) | d /= 1 || length vs > k = \n fail $ printf \"root vertices %d %d\" d (length vs)\n | otherwise = return $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || fromIntegral (length vs1) * fromIntegral (k-1) < (fromIntegral (length vs2) :: Integer) = \n fail $ printf \"non root vertices %d %d %d %d\" d1 (length vs1) d2 (length vs2)\n | otherwise = \n return $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\ndata Error a = Success a | Fail String\n\ninstance Functor Error where\n fmap f (Success a) = Success (f a)\n fmap f (Fail s) = Fail s\n\ninstance Monad Error where\n return = Success\n Success a >>= f = f a\n Fail s >>= f = Fail s\n fail = Fail\n\ninstance Applicative Error where\n pure = return\n (<*>) = ap\n\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n case es of\n Success es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Fail s -> \n if n == 100000 && k == n - 1 && ds !! 5767 == 0 then\n putStrLn s\n else print (-1)\n\ntype Edge = (Int,Int)\n\n\nsolve :: (Monad m,Applicative m) => Int -> Int -> [Int] -> m [Edge]\nsolve n k ds = case queue of\n [(0,[root])] -> return []\n (0,[root]):queue' -> do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n _ -> fail \"no root found or multiple root found\"\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n rootEdges root (d,vs) | d /= 1 || length vs > k = \n fail $ printf \"root vertices %d %d\" d (length vs)\n | otherwise = return $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || length vs1 * (k-1) < length vs2 = \n fail $ printf \"non root vertices %d %d %d %d\" d1 (length vs1) d2 (length vs2)\n | otherwise = \n return $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n if n == 100000 && k == n - 1 then\n let go [] = return ()\n go l = putStrLn (unwords $ map show $l1) >> go l2\n where (l1,l2) = splitAt 100 l\n in go ds\n else \n case es of\n Just es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Nothing -> print $ -1\n\ntype Edge = (Int,Int)\nsolve :: Int -> Int -> [Int] -> Maybe [Edge]\nsolve n k ds = case queue of\n [(0,[root])] -> Just []\n (0,[root]):queue' -> do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n _ -> Nothing\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n rootEdges root (d,vs) | d /= 1 || length vs > k = Nothing\n | otherwise = Just $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || length vs1 * (k-1) < length vs2 = Nothing\n | otherwise = \n Just $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\ndata Error a = Success a | Fail String\n\ninstance Functor Error where\n fmap f (Success a) = Success (f a)\n fmap f (Fail s) = Fail s\n\ninstance Monad Error where\n return = Success\n Success a >>= f = f a\n Fail s >>= f = Fail s\n fail = Fail\n\ninstance Applicative Error where\n pure = return\n (<*>) = ap\n\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n case es of\n Success es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Fail s -> \n if n == 100000 && k == n - 1 && ds !! 5767 == 0 then\n let go [] = return ()\n go l = putStrLn (unwords $ map show $l1) >> go l2\n where (l1,l2) = splitAt 80 l\n in go ds\n else print (-1)\n\ntype Edge = (Int,Int)\n\n\nsolve :: (Monad m,Applicative m) => Int -> Int -> [Int] -> m [Edge]\nsolve n k ds = case queue of\n [(0,[root])] -> return []\n (0,[root]):queue' -> do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n _ -> fail \"no root found or multiple root found\"\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n rootEdges root (d,vs) | d /= 1 || length vs > k = \n fail $ printf \"root vertices %d %d\" d (length vs)\n | otherwise = return $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || length vs1 * (k-1) < length vs2 = \n fail $ printf \"non root vertices %d %d %d %d\" d1 (length vs1) d2 (length vs2)\n | otherwise = \n return $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n case es of\n Just es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Nothing -> print $ -1\n\ntype Edge = (Int,Int)\nsolve :: Int -> Int -> [Int] -> Maybe [Edge]\nsolve n k ds = case queue of\n [(0,[root])] -> Just []\n (0,[root]):queue' -> do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n _ -> Nothing\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n rootEdges root (d,vs) | d /= 1 || length vs > k = Nothing\n | otherwise = Just $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || length vs1 * (k-1) < length vs2 = Nothing\n | otherwise = \n Just $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n case es of\n Just es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Nothing -> print $ -1\n\ntype Edge = (Int,Int)\nsolve :: Int -> Int -> [Int] -> Maybe [Edge]\nsolve n k ds | length (snd $ head queue) /= 1 || \n (fst $ head queue) /= 0 = Nothing\n | length ds == 1 = if head ds == 0 then Just [] else Nothing\n | otherwise = do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n (0,[root]):queue' = queue\n rootEdges root (d,vs) | d /= 1 || length vs > k = Nothing\n | otherwise = Just $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || length vs1 * (k-1) < length vs2 = Nothing\n | otherwise = \n Just $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\neqFst (a,_) (b,_) = a == b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n ds <- readInts\n let es = solve n k ds\n if n == 100000 && k == n - 1 && ds !! 5767 == 0 then\n let go [] = return ()\n go l = putStrLn (unwords $ map show $l1) >> go l2\n where (l1,l2) = splitAt 100 l\n in go ds\n else \n case es of\n Just es -> do\n print $ length es\n putStr $ unlines $ map (unwords . map show . p2l) es\n Nothing -> print $ -1\n\ntype Edge = (Int,Int)\nsolve :: Int -> Int -> [Int] -> Maybe [Edge]\nsolve n k ds = case queue of\n [(0,[root])] -> Just []\n (0,[root]):queue' -> do\n es1 <- rootEdges root (head queue')\n es2 <- concat <$> zipWithM f queue' (tail queue')\n return $ es1 ++ es2\n _ -> Nothing\n where\n queue = map ((head *** id) . unzip) $ groupBy eqFst $ sort $ zip ds [1..]\n rootEdges root (d,vs) | d /= 1 || length vs > k = Nothing\n | otherwise = Just $ map (root,) vs\n f (d1,vs1) (d2,vs2) \n | d2 - d1 /= 1 || length vs1 * (k-1) < length vs2 = Nothing\n | otherwise = \n Just $ zip (concat $ map (take (k-1) . repeat) vs1) vs2\n \n\n\n\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = unsafePerformIO (putStrLn (s ++ \": \" ++ show x)) `seq` x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition2 ((o1, i1), (o2, i2)) =\n let l1 = debug \"l1\" $ (length i1) * (if o1 == 0 then k else (k - 1))\n l2 = debug \"l2\" $ length i2\n in (debug \"f1\" (o1 + 1 == o2)) && (debug \"f2\" (l1 >= l2))\n condition ((o1, i1), (o2, i2)) =\n let l1 = (length i1) * (if o1 == 0 then k else (k - 1))\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ a@((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n print $ condition2 a\n \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = unsafePerformIO (putStrLn (s ++ \": \" ++ show x)) `seq` x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition2 ((o1, i1), (o2, i2)) =\n let l1 = debug \"l1\" $ (toInteger $ length i1) * (toInteger $ if o1 == 0 then k else (k - 1))\n l2 = debug \"l2\" $ toInteger $ length i2\n in (debug \"f1\" (o1 + 1 == o2)) && (debug \"f2\" (l1 >= l2))\n condition ((o1, i1), (o2, i2)) =\n let l1 = (length i1) * (if o1 == 0 then k else (k - 1))\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ a@((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n print $ condition2 a\n \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) -> \n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = (length i1) * (if o1 == 0 then k else (k - 1))\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ a@((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n print $ condition a\n \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ take n $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) -> \n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n print $ filter (not . condition) con2\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ ((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n print $ filter condition con2\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) -> \n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) -> \n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n print $ head condense\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition2 ((o1, i1), (o2, i2)) =\n let l1 = debug \"l1\" $ (length i1) * (if o1 == 0 then k else (k - 1))\n l2 = debug \"l2\" $ length i2\n in (debug \"f1\" (o1 + 1 == o2)) && (debug \"f2\" (l1 >= l2))\n condition ((o1, i1), (o2, i2)) =\n let l1 = (length i1) * (if o1 == 0 then k else (k - 1))\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ a@((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n print $ condition2 a\n \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) -> \n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n forM_ (reverse con2) $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = unsafePerformIO (putStrLn (s ++ \": \" ++ show x)) `seq` x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int32]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else putStrLn \"-1\"\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = (fromIntegral $ length i1) * if o1 == 0 then k else k - 1\n l2 = fromIntegral $ length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ map condition con2\n condition ((o1, i1), (o2, i2)) =\n let l1 = length i1 * if o1 == 0 then k else (k - 1)\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n when (n == 100000 && k == 99999) $ do\n print checkSize\n forM_ (filter (not . condition) con2) $ \\ ((o1, i1), (o2, i2)) -> do\n print \"--\"\n print o1\n print $ length i1\n print o2\n print $ length i2\n \n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Debug.Trace\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\n\nforeign import ccall \"stdio.h printf\"\n c_printf :: CString -> Int -> Int -> IO CInt\n\nformat = unsafePerformIO $ newCString \"%d %d\\n\"\nprintf = c_printf format\n\ndebug s x = trace (s ++ \": \" ++ show x) x\nfor = flip map\n\nmain = do\n n:k:d <- map read <$> words <$> getContents :: IO [Int]\n solve n k $ sort $ zip d [1..]\n\nsolve n k d = if hasSolution then printSolution else printError\n where\n pack ((order, inds) : tail) (order', ind)\n | order == order' = (order, ind : inds) : tail\n | otherwise = (order', [ind]) : (order, inds) : tail\n condense = reverse $ foldl' pack [(0, [])] d\n con2 = zip condense $ tail condense\n hasSolution = (length $ snd $ head condense) == 1 && checkSize\n checkSize = and $ for con2 $ \\((o1, i1), (o2, i2)) -> \n let l1 = length i1 * if o1 == 0 then k else k - 1\n l2 = length i2\n in (o1 + 1 == o2) && (l1 >= l2)\n printSolution = do\n print (n - 1)\n hFlush stdout\n forM_ con2 $ \\((o1, i1), (o2, i2)) -> \n forM_ (zip (cycle i1) i2) (uncurry printf)\n printError = do\n putStrLn \"-1\"\n print checkSize\n print $ head condense\n \n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr . solve n k . sort $ zip xs [1..n]\n\nsolve :: Int -> Int -> [(Int,Int)] -> String\nsolve n k ((0,root):xis) = go 1 (shows(n-1).('\\n':)) [root] xis\n where\n go _ res _ [] = res \"\"\n go _ _ [] _ = \"-1\"\n go !depth !res parents xis\n | fst(head xis) < depth || length parents * k < length yis = \"-1\"\n | otherwise = go (depth+1) (res.res') (map snd yis) zis\n where\n (yis,zis) = span ((depth==).fst) xis\n yiss = slices k $ map snd yis\n p & c = shows p.(' ':).shows c.('\\n':)\n res' = foldr(.) id $zipWith (\\p cs->foldr((.).(p&))id cs) parents yiss\nsolve _ _ _ = \"-1\"\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr . solve n k . sort $ zip xs [1..n]\n\nsolve :: Int -> Int -> [(Int,Int)] -> String\nsolve n k ((0,root):xis) = go 1 (shows(n-1).('\\n':)) [root] xis\n where\n go _ res _ [] = res \"\"\n go _ _ [] _ = \"-1\"\n go !depth !res parents xis\n | fst(head xis) < depth || length parents * k' < length yis = \"-1\"\n | otherwise = go (depth+1) (res.res') (map snd yis) zis\n where\n k' = if depth == 1 then k else k-1\n (yis,zis) = span ((depth==).fst) xis\n yiss = slices k' $ map snd yis\n p & c = shows p.(' ':).shows c.('\\n':)\n res' = foldr(.) id $zipWith (\\p cs->foldr((.).(p&))id cs) parents yiss\nsolve _ _ _ = \"-1\"\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr . solve n k . sort $ zip xs [1..n]\n\nsolve :: Int -> Int -> [(Int,Int)] -> String\nsolve n k ((0,root):xis) = go 1 (shows(n-1).('\\n':)) [root] xis\n where\n go _ res _ [] = res \"\"\n go !depth !res parents xis\n | null yis || length parents * k < length yis = \"-1\"\n | otherwise = go (depth+1) (res.res') (map snd yis) zis\n where\n (yis,zis) = span ((depth==).fst) xis\n yiss = slices k $ map snd yis\n res' = foldr(.) id $zipWith (\\p cs->foldr(.)id[shows p.(' ':).shows c.('\\n':)|c<-cs]) parents yiss\nsolve _ _ _ = \"-1\"\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr . solve n k . sort $ zip xs [1..n]\n\nsolve :: Int -> Int -> [(Int,Int)] -> String\nsolve n k ((0,root):xis) = go 1 (shows(n-1).('\\n':)) [root] xis\n where\n go _ res _ [] = res \"\"\n go !depth !res parents xis\n | fst(head xis) < depth || length parents * k < length yis = \"-1\"\n | otherwise = go (depth+1) (res.res') (map snd yis) zis\n where\n (yis,zis) = span ((depth==).fst) xis\n yiss = slices k $ map snd yis\n res' = foldr(.) id $zipWith (\\p cs->foldr(.)id[shows p.(' ':).shows c.('\\n':)|c<-cs]) parents yiss\nsolve _ _ _ = \"-1\"\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}"}], "src_uid": "73668a75036dce819ff27c316de378af"} {"source_code": "main = do\n n <- getLine\n a <- getLine\n if (solve n $ words a) then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve _n _a = judge [0, 0, 0] _a where\n judge _ [] = True\n judge [c25, c50, c100] (a:as)\n | a == \"100\" =\n if c50 > 0 && c25 > 0 then judge [c25-1, c50-1, c100+1] as\n else if c25 > 2 then judge [c25-3, c50, c100+1] as\n else False\n | a == \"50\" = \n if c25 > 0 then judge [c25-1, c50+1, c100] as\n else False\n | otherwise = judge [c25+1, c50, c100] as\n", "positive_code": [{"source_code": "main = putStrLn . solve 0 0 0 . map read . tail . words =<< getContents\nsolve f h q (25:bs) = solve f h (q+1) bs\nsolve f h 0 (50:bs) = \"NO\"\nsolve f h q (50:bs) = solve f (h+1) (q-1) bs\nsolve f 0 q (100:bs) | q >= 3 = solve (f+1) 0 (q-3) bs\n | otherwise = \"NO\"\nsolve f h q (100:bs) | h >= 1 && q >= 1 = solve (f+1) (h-1) (q-1) bs\n | otherwise = \"NO\"\nsolve _ _ _ [] = \"YES\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = interact $ booking . tail . words\n\nbooking = maybe \"NO\" (const \"YES\") . foldM_ change (0, 0)\n\nchange (x, y) b = case b of\n\t\"25\" -> Just (x + 1, y)\n\t\"50\" -> guard (x > 0) >> Just (x - 1, y + 1)\n\t\"100\" -> (guard (x > 0 && y > 0) >> Just (x - 1, y - 1))\n\t\t<|> (guard (x > 2) >> Just (x - 3, y))"}, {"source_code": "import Control.Applicative ((<|>))\nimport Control.Monad (guard, foldM)\n\ndata Bill = R25 | R50 | R100\ndata Result = YES | NO deriving (Show)\n\nmain = interact $ show . booking . map readBill . tail . words\n\nbooking :: [Bill] -> Result\nbooking = maybe NO (const YES) . foldM change (0, 0)\n\nchange :: (Int, Int) -> Bill -> Maybe (Int, Int)\nchange (n25, n50) bill = case bill of\n\tR25 -> return (n25 + 1, n50)\n\tR50 -> guard (n25 > 0) >> return (n25 - 1, n50 + 1)\n\tR100 -> (guard (n50 > 0 && n25 > 0) >> return (n25 - 1, n50 - 1))\n\t\t<|> (guard (n25 > 2) >> return (n25 - 3, n50))\n\nreadBill :: String -> Bill\nreadBill s = case s of\n\t\"25\" -> R25\n\t\"50\" -> R50\n\t\"100\" -> R100\n"}, {"source_code": "import Control.Monad (foldM)\n\ndata Bill = R25 | R50 | R100\ndata Result = YES | NO deriving (Show)\n\nmain = interact $ show . booking . map readBill . tail . words\n\nbooking :: [Bill] -> Result\nbooking = maybe NO (const YES) . foldM (flip change) (0, 0)\n\nchange :: Bill -> (Int, Int) -> Maybe (Int, Int)\nchange R25 (n25, n50) = Just (n25 + 1, n50)\nchange R50 (n25, n50)\n\t| n25 > 0 = Just (n25 - 1, n50 + 1)\n\t| otherwise = Nothing\nchange R100 (n25, n50)\n\t| n50 > 0 && n25 > 0 = Just (n25 - 1, n50 - 1)\n\t| n25 > 2 = Just (n25 - 3, n50)\n\t| otherwise = Nothing\n\nreadBill :: String -> Bill\nreadBill s = case s of\n\t\"25\" -> R25\n\t\"50\" -> R50\n\t\"100\" -> R100\n"}, {"source_code": "\ndata Bill = R25 | R50 | R100\ndata Result = YES | NO deriving (Show)\n\nmain = interact $ show . booking . map readBill . tail . words\n\nbooking :: [Bill] -> Result\nbooking = go (0, 0) where\n\tgo _ [] = YES\n\tgo n (x:xs) = case change x n of\n\t\tJust n' -> go n' xs\n\t\tNothing -> NO\n\nreadBill :: String -> Bill\nreadBill s = case s of\n\t\"25\" -> R25\n\t\"50\" -> R50\n\t\"100\" -> R100\n\nchange :: Bill -> (Int, Int) -> Maybe (Int, Int)\nchange R25 (n25, n50) = Just (n25 + 1, n50)\nchange R50 (n25, n50) = if n25 > 0\n\tthen Just (n25 - 1, n50 + 1)\n\telse Nothing\nchange R100 (n25, n50) = if n50 > 0\n\tthen if n25 > 0\n\t\tthen Just (n25 - 1, n50 - 1)\n\t\telse Nothing\n\telse if n25 > 2\n\t\tthen Just (n25 - 3, n50)\n\t\telse Nothing"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Control.Monad\n\nmain = interact $ booking . tail . words\n\nbooking = maybe \"NO\" (const \"YES\") . foldM_ change (0, 0)\n\nchange (!x, !y) b = case b of\n\t\"25\" -> Just (x + 1, y)\n\t\"50\" -> guard (x > 0) >> Just (x - 1, y + 1)\n\t\"100\" -> (guard (x > 0 && y > 0) >> Just (x - 1, y - 1))\n\t\t<|> (guard (x > 2) >> Just (x - 3, y))"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = interact $ booking . tail . words\n\nbooking = maybe \"NO\" (const \"YES\") . foldM change (0, 0)\n\nchange (x, y) b = case b of\n\t\"25\" -> Just (x + 1, y)\n\t\"50\" -> guard (x > 0) >> Just (x - 1, y + 1)\n\t\"100\" -> (guard (x > 0 && y > 0) >> Just (x - 1, y - 1))\n\t\t<|> (guard (x > 2) >> Just (x - 3, y))"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = interact $ booking . tail . words\n\nbooking = maybe \"NO\" (const \"YES\") . foldM change (0, 0)\n\nchange (x, y) b = case b of\n\t\"25\" -> Just $! (x + 1, y)\n\t\"50\" -> guard (x > 0) >> (Just $! (x - 1, y + 1))\n\t\"100\" -> (guard (x > 0 && y > 0) >> (Just $! (x - 1, y - 1)))\n\t\t<|> (guard (x > 2) >> (Just $! (x - 3, y)))"}, {"source_code": "import Control.Applicative ((<|>))\nimport Control.Monad (guard, foldM)\n\nmain = interact $ booking . tail . words\n\nbooking = maybe \"NO\" (const \"YES\") . foldM change (0, 0)\n\nchange (n25, n50) bill = case bill of\n\t\"25\" -> return (n25 + 1, n50)\n\t\"50\" -> guard (n25 > 0) >> return (n25 - 1, n50 + 1)\n\t\"100\" -> (guard (n50 > 0 && n25 > 0) >> return (n25 - 1, n50 - 1))\n\t\t<|> (guard (n25 > 2) >> return (n25 - 3, n50))"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\n-- |Model the change state. First entry is number of 25 notes, second number\n-- of 50 notes\ntype Change = (Int,Int)\n\n-- * Solver\n-- |Solve a test case\nsolve :: [Int] -> String\nsolve xs = case solve' xs of\n (Just _) -> \"YES\"\n Nothing -> \"NO\"\n where solve' xs = foldl (>>=) (return (0,0)) $ map process xs\n\n-- |Process one consumer\nprocess :: Int -- ^ Note of consumer\n -> Change -- ^ Old 'Change' state\n -> Maybe Change -- ^ New 'Change' state or 'Nothing' if transaction is \n -- impossible\nprocess 25 (a,b) = return (a+1,b)\nprocess 50 (a,b) = guard (a >= 1) >> return (a-1,b+1)\nprocess 100 (a,b)\n | b > 0 = guard (a >= 1) >> return (a-1,b-1)\n | otherwise = guard (a >= 3) >> return (a-3,b)\n\n-- * Input/Output\n-- |Ignore the first line and parse the test case\nmain :: IO ()\nmain = do\n B.getLine\n xs <- getIntList\n putStrLn $ solve xs\n\n-- |Read an Int list from the standard input device\ngetIntList :: IO [Int]\ngetIntList = readIntList `fmap` B.getLine\n\n-- * Converting from ByteString\n-- |Cast ByteString to Int\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\n-- |Cast ByteString to Int list\nreadIntList :: C.ByteString -> [Int]\nreadIntList = map readInt . C.words"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\ntype Change = (Int,Int)\n\nsolve :: [Int] -> String\nsolve xs = case solve' xs of\n (Just _) -> \"YES\"\n Nothing -> \"NO\"\n where solve' xs = foldM process (0,0) xs\n\nprocess :: Change -> Int -> Maybe Change\nprocess (a,b) 25 = return $! (a+1,b)\nprocess (a,b) 50 = guard (a >= 1) >> (return $! (a-1,b+1))\nprocess (a,b) 100\n | b > 0 = guard (a >= 1) >> (return $! (a-1,b-1))\n | otherwise = guard (a >= 3) >> (return $! (a-3,b))\n\nmain :: IO ()\nmain = do\n B.getLine\n xs <- getIntList\n putStrLn $ solve xs\n\ngetIntList :: IO [Int]\ngetIntList = readIntList `fmap` B.getLine\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nreadIntList :: C.ByteString -> [Int]\nreadIntList = map readInt . C.words"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: [Int] -> String\nsolve xs = if solve' (0,0) xs then \"YES\" else \"NO\"\n\nsolve' :: (Int,Int) -> [Int] -> Bool\nsolve' (a,b) _ | a < 0 || b < 0 = False\nsolve' _ [] = True\nsolve' (a,b) (25:xs) = solve' (a+1,b) xs\nsolve' (a,b) (50:xs) = solve' (a-1,b+1) xs\nsolve' (a,b) (100:xs) = if b > 0 then solve' (a-1,b-1) xs else solve' (a-3,b) xs\n\nmain :: IO ()\nmain = do\n\tB.getLine\n\tls <- B.getLine\n\tputStrLn . solve . map readInt . C.words $ ls \n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve [] = []\nsolve (c1:c2:cs) = (f (0,0) . map read . words $ c2): solve cs\n where\n f rs [] = \"YES\"\n f (r1,r2) (n:ns) =\n if n==25 then f (r1+1,r2) ns\n else if n==50 && r1>0 then f (r1-1,r2+1) ns\n else if n==100 && r1>0 && r2>0 then f (r1-1,r2-1) ns\n else if n==100 && r1>2 then f (r1-3,r2) ns\n else \"NO\"\n"}, {"source_code": "solve :: [Integer] -> Integer -> Integer -> Bool\nsolve [] _ _ = True\nsolve (25:xs) q h = solve xs (q + 1) h\nsolve (50:xs) 0 _ = False\nsolve (50:xs) q h = solve xs (q - 1) (h + 1)\nsolve (100:xs) q h \n | q > 0 && h > 0 = solve xs (q - 1) (h - 1)\n | q > 2 = solve xs (q - 3) h\n | otherwise = False\n\nmain = do\n n <- getLine\n a <- getLine\n if solve (map read $ words a) 0 0 then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}, {"source_code": "work m n xs = if m < 0 || n < 0\n then \"NO\"\n else \n if null xs\n then \"YES\"\n else\n case (head xs) of\n 100 -> if n > 0\n then work (m-1) (n-1) (tail xs)\n else work (m-3) n (tail xs)\n 50 -> work (m-1) (n+1) (tail xs)\n 25 -> work (m+1) n (tail xs)\n\nmain = do s <- getLine\n s <- getLine\n let xs = map (\\x -> read x :: Int) (words s)\n putStrLn (work 0 0 xs)\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\ndata Result = YES | NO deriving (Eq,Show)\n\nmain = do\n getLine\n l <- map read <$>words <$> getLine\n print $ solve (0, 0) l\n\n\nsolve :: (Int, Int) -> [Int] -> Result\nsolve _ [] = YES\nsolve (a,b) (25:xs) = solve (a+1,b) xs\nsolve (a,b) (50:xs) | a > 0 = solve (a-1,b+1) xs\n | otherwise = NO\nsolve (a,b) (100:xs)| b > 0 && a > 0 = solve (a-1, b-1) xs\n | a > 2 = solve (a-3,b) xs\n | otherwise = NO\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \nprocess x y z [] = \"YES\"\nprocess x y z (a:as) | a==25 = process (x+1) y z as\n\t | a==50 && x>0 = process (x-1) (y+1) z as\n\t\t | a==50 = \"NO\"\n\t\t | a==100 && y>0 && x>0 = process (x-1) (y-1) (z+1) as\n | a==100 && x>=3 = process (x-3) y (z+1) as\n | otherwise = \"NO\"\t\n \nmain=do\t \n\tgetLine\n\ts<-map (fst.fromJust.C.readInt). C.words<$> C.getLine::IO [Int]\n\tputStrLn $ process 0 0 0 s\t "}, {"source_code": "main = do\n (_:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ f 0 0 a\nf _ _ [] = \"YES\"\nf x y (a:as)\n | a == 25 = f (x + 1) y as\n | a == 50 = if x > 0 then f (x - 1) (y + 1) as else \"NO\"\n | otherwise = if y > 0 && x > 0 then f (x - 1) (y - 1) as else if x > 2 then f (x - 3) y as else \"NO\""}, {"source_code": "import Data.List\n\ncal ls = let bills = map (+0) $ map read $ words $ ls !! 1\n neededChange = map ( + (-25)) bills\n\t in sell bills 0 0\n\nsell bills c25 c50\n\t| c25<0 || c50 <0 = \"NO\"\n\t| bills == [] = \"YES\"\n\t| (head bills) == 25 = sell (tail bills) (c25+1) c50 \n\t| (head bills) == 50 = sell (tail bills) (c25-1) (c50+1)\n\t| c50 >0 = sell (tail bills) (c25 -1) (c50-1)\n\t| otherwise = sell (tail bills) (c25 -3) c50\n\nmain = interact ( cal . lines)\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.List (foldl')\n\ntype Change = (Int,Int)\n\nrush :: [Int] -> Bool\nrush = isJust . foldl' f (Just (0,0))\n where f :: Maybe Change -> Int -> Maybe Change\n f (Just (a,b)) 25 = Just (a+1,b)\n f (Just (a,b)) 50 = if a > 0 then Just (a - 1, b + 1)\n else Nothing\n f (Just (a,b)) 100\n | b >= 1 && a >= 1 = Just (a - 1, b - 1)\n | a >= 3 = Just (a - 3, b)\n | otherwise = Nothing\n f _ _ = Nothing\n\nmain :: IO ()\nmain = do\n _:l <- fmap (map read . words) getContents\n putStrLn $ if rush l then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\n\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) x f = x >>= (return.f); infixl 1 ||>\nref = (!!)\n\ngo :: [Int] -> (Int,Int) -> Bool\ngo [] _ = True\ngo (25:xs) (a,b) = go xs (a+1,b)\ngo (50:xs) (a,b)\n | a < 1 = False\n | True = go xs (a-1,b+1)\ngo (100:xs) (a,b)\n | a>0 && b>0 = go xs (a-1,b-1)\n | a >= 3 = go xs (a-3,b)\n | True = False\n\nmain = do\n ls <- getContents ||> lines\n n <- head ls |> readIO :: IO Int\n xs <- (ref ls 1) |> words |> map read |> return :: IO [Int]\n putStrLn (if (go xs (0,0)) then \"YES\" else \"NO\")\n\n-- vim: set ft=haskell:"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\ntoDigit n = chr (48 + n)\n\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\n\ngo :: [Int] -> (Int,Int) -> Bool\ngo [] _ = True\ngo (25:xs) (a,b) = go xs (a+1,b)\ngo (50:xs) (a,b)\n | a < 1 = False\n | True = go xs (a-1,b+1)\ngo (100:xs) (a,b)\n | a>0 && b>0 = go xs (a-1,b-1)\n | a >= 3 = go xs (a-3,b)\n | True = False\n\nmain = do\n ls <- B.getContents ||> B.lines\n n <- head ls |> B.readInt |> fromJust |> fst |> return :: IO Int\n xs <- (ref ls 1) |> B.words |> map (fst . fromJust . B.readInt) |> return :: IO [Int]\n putStrLn (if (go xs (0,0)) then \"YES\" else \"NO\")\n\n-- vim: set ft=haskell:"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) x f = x >>= (return.f); infixl 1 ||>\nref = (!!)\n\ngo [] _ = True\ngo (\"25\":xs) (a,b) = go xs (a+1,b)\ngo (\"50\":xs) (a,b)\n | a < 1 = False\n | True = go xs (a-1,b+1)\ngo (\"100\":xs) (a,b)\n | a>0 && b>0 = go xs (a-1,b-1)\n | a >= 3 = go xs (a-3,b)\n | True = False\n\nmain = do\n ls <- getContents ||> lines\n n <- head ls |> readIO :: IO Int\n xs <- (ref ls 1) |> words |> return :: IO [String]\n putStrLn (if (go xs (0,0)) then \"YES\" else \"NO\")\n\n-- vim: set ft=haskell:\n"}, {"source_code": "main = do\n n <- getLine\n a <- getLine\n if (solve n $ words a) then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve _n _a = judge [0, 0, 0] _a where\n judge _ [] = True\n judge (c25:c50:c100:[]) (a:as)\n | a == \"100\" =\n if c50 > 0 && c25 > 0 then judge (c25-1:c50-1:c100+1:[]) as\n else if c25 > 2 then judge (c25-3:c50:c100+1:[]) as\n else False\n | a == \"50\" = \n if c25 > 0 then judge (c25-1:c50+1:c100:[]) as\n else False\n | otherwise = judge (c25+1:c50:c100:[]) as\n"}, {"source_code": "main = do\n n <- getLine\n a <- getLine\n if (solve n $ words a) then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve _n _a = judge 0 0 0 _a where\n judge _ _ _ [] = True\n judge c25 c50 c100 (a:as) =\n case a of\n \"100\" ->\n if c50 > 0 && c25 > 0 then (judge (c25-1) (c50-1) (c100+1) as)\n else if c25 > 2 then (judge (c25-3) c50 (c100+1) as)\n else False\n \"50\" -> \n if c25 > 0 then (judge (c25-1) (c50+1) c100 as)\n else False\n \"25\" -> (judge (c25+1) c50 c100 as)\n"}, {"source_code": "main = do\n n <- getLine\n a <- getLine\n if (solve n $ words a) then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve _n _a = judge 0 0 0 _a where\n judge _ _ _ [] = True\n judge c25 c50 c100 (a:as)\n | a == \"100\" =\n if c50 > 0 && c25 > 0 then judge (c25-1) (c50-1) (c100+1) as\n else if c25 > 2 then judge (c25-3) c50 (c100+1) as\n else False\n | a == \"50\" = \n if c25 > 0 then judge (c25-1) (c50+1) c100 as\n else False\n | otherwise = judge (c25+1) c50 c100 as\n"}, {"source_code": "import Data.List (foldl')\n\nmain = do\n n <- getLine\n a <- getLine\n let rv = (solve n $ words a)\n if snd rv == True then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve n xs = foldl' go ((0, 0, 0), True) xs where\n go ((_, _, _), b) \"\" = ((0, 0, 0), True && b)\n go ((c25, c50, c100), b) x\n | x == \"100\" =\n if c50 > 0 && c25 > 0 then ((c25-1, c50-1, c100+1), b)\n else if c25 > 2 then ((c25-3, c50, c100+1), b)\n else ((0, 0, 0), False)\n | x == \"50\" = \n if c25 > 0 then ((c25-1, c50+1, c100), b)\n else ((0, 0, 0), False)\n | otherwise = ((c25+1, c50, c100), b)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\tgetLine\n\tas <- map read . words <$> getLine\n\tlet\n\t\tres = solve 0 0 0 as\n\tputStrLn res\n\nsolve _ _ _ [] = \"YES\"\nsolve c25 c50 c100 (a:as)\n\t| a == 25 = solve ( c25 + 1 ) c50 c100 as\n\t| a == 50 = if c25 == 0\n\t\tthen \"NO\"\n\t\telse solve ( c25 - 1 ) ( c50 + 1 ) c100 as\n\t| a == 100 && 1 <= c25 && 1 <= c50 = solve ( c25 - 1 ) ( c50 -1 ) ( c100 + 1 ) as\n\t| a == 100 && 3 <= c25 = solve ( c25 - 3 ) c50 ( c100 + 1 ) as\n\t| otherwise = \"NO\"\n"}, {"source_code": "import Control.Applicative\nget :: IO [Int]\nget = fmap (map read.words) getContents\n\nsolve :: Int -> Int -> Int -> [Int] -> String\nsolve a b c []\n | a < 0 || b < 0 || c < 0 = \"NO\"\n | otherwise = \"YES\"\nsolve a b c (x:xs) -- 25, 50, 100 demonination change\n | a < 0 || b < 0 || c < 0 = \"NO\"\n | x == 25 = solve (a+1) b c xs\n | x == 50 = solve (a-1) (b+1) c xs\n | x == 100 = if b > 0\n then solve (a-1) (b-1) (c+1) xs\n else solve (a-3) b (c+1) xs\n \nmain :: IO ()\nmain=do\n (_:line) <- get\n putStrLn (solve 0 0 0 line)\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do \n getLine \n xs <- map read <$> words <$> getLine \n if solve 0 0 0 xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n \n\nsolve :: Int -> Int -> Int -> [Int] -> Bool\nsolve _ _ _ [] = True \nsolve d100 d50 d25 (x:xs) \n | x == 25 = solve d100 d50 (d25 + 1) xs\n | x == 50 && d25 >= 1 = solve d100 (d50 + 1) (d25 - 1) xs\n | x == 100 && d50 >= 1 && d25 >= 1 = solve (d100 + 1) (d50 - 1) (d25 - 1) xs\n | x == 100 && d25 >= 3 = solve (d100 + 1) d50 (d25 - 3) xs\n | otherwise = False\n"}, {"source_code": "check :: [Int] -> (Int, Int) -> String\ncheck [] _ = \"YES\"\ncheck (x:xs) (d, p)\n | x == 25 = check xs (d+1, p)\n | x == 50 && (d > 0) = check xs (d-1, p+1)\n | x == 100 && (d > 0 && p > 0) = check xs (d-1, p-1)\n | x == 100 && (d > 2) = check xs (d-3, p)\n | otherwise = \"NO\"\n\nmain = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n getLine\n putStrLn . solve (0, 0) . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: (Int, Int) -> [Int] -> String\nsolve (q, h) _ | q <0 || h < 0 = \"NO\"\nsolve (q, h) [] = \"YES\"\nsolve (q, h) (25 : bs) = solve (q + 1, h) bs\nsolve (q, h) (50 : bs) = solve (q - 1, h + 1) bs\nsolve (q, 0) (100 : bs) = solve (q - 3, 0) bs\nsolve (q, h) (100 : bs) = solve (q - 1, h - 1) bs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- getInts\n\n let\n r = f (0, 0, 0) xs\n where\n f _ [] = True\n f (a, b, c) (25:xs) = f (a+1, b, c) xs\n f (a, b, c) (50:xs)\n | a >= 1 = f (a-1, b+1, c) xs\n | otherwise = False\n f (a, b, c) (100:xs)\n | b >= 1 && a >= 1 = f (a-1, b-1, c+1) xs\n | a >= 3 = f (a-3, b, c+1) xs\n | otherwise = False\n\n putStrLn $ if r then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n-> (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve xs = if slv1 xs (0,0) then putStr \"YES\" else putStr \"NO\"\nslv1 [] _ = True\nslv1 (x:xs) (y25,y50) | x ==25 = slv1 xs (y25+1,y50) \n | x ==50 && y25==0 = False\n | x ==50 && y25/=0 = slv1 xs (y25-1,y50+1)\n | x ==100 && y50>0 && y25>0 = slv1 xs (y25-1,y50-1)\n | x ==100 && y50==0 && y25>2 = slv1 xs (y25-3,y50)\n | otherwise = False"}, {"source_code": "import Control.Monad (liftM)\nimport Data.Char (ord)\nimport Prelude hiding (reads)\n\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n where\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + ord c - ord '0'\n\nsolve :: [Int] -> Bool\nsolve as = solve' 0 0 as\n where\n solve' _ _ [] = True\n solve' a b (25:as) = solve' (a+1) b as\n solve' a b (50:as)\n | a > 0 = solve' (a-1) (b+1) as\n | otherwise = False\n solve' a b (100:as)\n | a > 0 && b > 0 = solve' (a-1) (b-1) as\n | a > 2 = solve' (a-3) b as\n | otherwise = False\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n if solve as then\n putStrLn \"YES\"\n else\n putStrLn \"NO\""}, {"source_code": "module Main where\nimport Control.Applicative\nimport Control.Monad\nimport Data.ByteString.Lazy as B\nimport Data.ByteString.Lazy.Char8 as C\nmain :: IO ()\nmain = do\n _ <- getLine\n bills <- (Prelude.map ((\\ (Just (i,_)) -> i) . C.readInt) . C.words) <$> B.getContents :: IO [Int]\n let cando (twfs,fifs) 25 = Just (twfs+1,fifs)\n cando (twfs,fifs) 50\n | twfs > 0 = Just (twfs-1,fifs+1)\n | otherwise = Nothing \n cando (twfs,fifs) 100\n | twfs >= 1 && fifs >= 1 = Just (twfs-1,fifs-1)\n | twfs >= 3 = Just (twfs-3,fifs)\n | otherwise = Nothing\n Prelude.putStrLn (case foldM cando (0,0) bills of\n Nothing -> \"NO\"\n _ -> \"YES\")\n"}, {"source_code": "main = do\n getLine\n input <- getLine >>= return.(map read).words\n putStrLn $ solve input 0 0\n\nsolve :: [Int] -> Int -> Int -> String\nsolve [] _ _ = \"YES\"\nsolve (25:xs) a b = solve xs (a+1) b\nsolve (50:xs) a b\n | a==0 = \"NO\"\n | otherwise = solve xs (a-1) (b+1)\nsolve (100:xs) a b\n | a>0 && b>0 = solve xs (a-1) (b-1)\n | a>2 = solve xs (a-3) b\n | otherwise = \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Bool\nsolve = all g . scanl f (0 :: Int, 0 :: Int)\n where f (a, b) 25 = (a + 1, b)\n f (a, b) 50 = (a - 1, b + 1)\n f (a, b) 100 | b > 0 = (a - 1, b - 1)\n | otherwise = (a - 3, b)\n f ab _ = ab\n g (a, b) = a >= 0 && b >= 0\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}], "negative_code": [{"source_code": "import Control.Applicative\nget :: IO [Int]\nget = fmap (map read.words) getContents\n\nsolve :: Int -> Int -> Int -> [Int] -> String\nsolve a b c []\n | a < 0 || b < 0 || c < 0 = \"NO\"\n | otherwise = \"YES\"\nsolve a b c (x:xs) -- 25, 50, 100 demonination change\n | a < 0 || b < 0 || c < 0 = \"NO\"\n | x == 25 = solve (a+1) b c xs\n | x == 50 = solve (a-1) (b+1) c xs\n | x == 100 = if b > 1\n then solve (a-1) (b-1) (c+1) xs\n else solve (a-3) b (c+1) xs\n \nmain :: IO ()\nmain=do\n (_:line) <- get\n putStrLn (solve 0 0 0 line)\n"}, {"source_code": "check :: [Int] -> (Int, Int) -> String\ncheck [] _ = \"YES\"\ncheck (x:xs) (d, p)\n | x == 25 = check xs (d+1, p)\n | x == 50 = check xs (d-1, p+1)\n | x == 100 && (d > 1 && p > 1) = check xs (d-1, p-1)\n | x == 10 && (d > 4) = check xs (d-3, p)\n | otherwise = \"NO\"\n\nmain = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn\n\n"}, {"source_code": "check :: [Int] -> (Int, Int) -> String\ncheck [] _ = \"YES\"\ncheck (x:xs) (d, p)\n | x == 25 = check xs (d+1, p)\n | x == 50 && (d > 0) = check xs (d-1, p+1)\n | x == 100 && (d > 1 && p > 1) = check xs (d-1, p-1)\n | x == 10 && (d > 4) = check xs (d-3, p)\n | otherwise = \"NO\"\n\nmain = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn\n\n"}, {"source_code": "check :: [Int] -> (Int, Int) -> String\ncheck [] _ = \"YES\"\ncheck (x:xs) (d, p)\n | x == 25 = check xs (d+1, p)\n | x == 50 && (d > 1) = check xs (d-1, p+1)\n | x == 100 && (d > 1 && p > 1) = check xs (d-1, p-1)\n | x == 10 && (d > 4) = check xs (d-3, p)\n | otherwise = \"NO\"\n\nmain = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn\n\n"}, {"source_code": "module Main where\n-- import Control.Monad\n-- import Data.List\n-- import Data.Array\nimport Control.Applicative\nimport Control.Monad\nmain :: IO ()\nmain = do\n _ <- getLine\n bills <- (map read . words) <$> getLine :: IO [Int]\n let cando (twfs,fifs,hunnas) 25 = Just (twfs+1,fifs,hunnas)\n cando (twfs,fifs,hunnas) 50\n | twfs == 0 = Nothing\n | otherwise = Just (twfs-1,fifs,hunnas)\n cando (twfs,fifs,hunnas) 100\n | twfs >= 1 && fifs >= 1 = Just (twfs-1,fifs-1,hunnas)\n | twfs >= 3 = Just (twfs-3,fifs,hunnas)\n | otherwise = Nothing\n case foldM cando (0,0,0) bills of\n Nothing -> putStrLn \"NO\"\n _ -> putStrLn \"YES\"\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Bool\nsolve = all g . scanl f (0 :: Int, 0 :: Int)\n where f (a, b) 25 = (a + 1, b)\n f (a, b) 50 = (a - 1, b + 1)\n f (a, b) 100 | b >= 0 = (a - 1, b - 1)\n | otherwise = (a - 3, b)\n f ab _ = ab\n g (a, b) = a >= 0 && b >= 0\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Bool\nsolve = and . zipWith (>=) [25,50..]\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Bool\nsolve = all (>=0) . scanl (\\a b -> a + b - 25) 0\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\n-- |Model the change state. First entry is number of 25 notes, second number\n-- of 50 notes\ntype Change = (Int,Int)\n\n-- * Solver\n-- |Solve a test case\nsolve :: [Int] -> String\nsolve xs = case solve' xs of\n (Just _) -> \"YES\"\n Nothing -> \"NO\"\n where solve' xs = foldl (>>=) (return (0,0)) $ map process xs\n\n-- |Process one consumer\nprocess :: Int -- ^ Note of consumer\n -> Change -- ^ Old 'Change' state\n -> Maybe Change -- ^ New 'Change' state or 'Nothing' if transaction is \n -- impossible\nprocess 25 (a,b) = return (a+1,b)\nprocess 50 (a,b) = guard (a >= 1) >> return (a-1,b+1)\nprocess 100 (a,b)\n | b > 0 = guard (a >= 0) >> return (a-1,b-1)\n | otherwise = guard (a >= 2) >> return (a-3,b)\n\n-- * Input/Output\n-- |Ignore the first line and parse the test case\nmain :: IO ()\nmain = do\n B.getLine\n xs <- getIntList\n putStrLn $ solve xs\n\n-- |Read an Int list from the standard input device\ngetIntList :: IO [Int]\ngetIntList = readIntList `fmap` B.getLine\n\n-- * Converting from ByteString\n-- |Cast ByteString to Int\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\n-- |Cast ByteString to Int list\nreadIntList :: C.ByteString -> [Int]\nreadIntList = map readInt . C.words"}, {"source_code": "work m n xs = if m < 0 || n < 0\n then \"NO\"\n else \n if null xs\n then \"YES\"\n else\n case (head xs) of\n 100 -> work (m-1) (n-1) (tail xs)\n 50 -> work (m-1) (n+1) (tail xs)\n 25 -> work (m+1) n (tail xs)\n\nmain = do s <- getLine\n s <- getLine\n let a = map (\\x -> read x :: Int) (words s)\n putStrLn (work 0 0 a)\n"}, {"source_code": "work m n xs = if m < 0 || n < 0\n then \"NO\"\n else \n if null xs\n then \"YES\"\n else\n case (head xs) of\n 100 -> if n > 0\n then work (m-1) (n-1) (tail xs)\n else work (m-1) n (tail xs)\n 50 -> work (m-1) (n+1) (tail xs)\n 25 -> work (m+1) n (tail xs)\n\nmain = do s <- getLine\n s <- getLine\n let xs = map (\\x -> read x :: Int) (words s)\n putStrLn (work 0 0 xs)\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\ndata Result = YES | NO deriving (Eq,Show)\n\nmain = do\n getLine\n l <- map read <$>words <$> getLine\n print $ solve (0, 0) l\n\n\nsolve :: (Int, Int) -> [Int] -> Result\nsolve _ [] = YES\nsolve (a,b) (25:xs) = solve (a+1,b) xs\nsolve (a,b) (50:xs) | a > 0 = solve (a-1,b+1) xs\n | otherwise = NO\nsolve (a,b) (100:xs)| b > 0 && a > 0 = solve (a-1, b-1) xs\n | a > 1 = solve (a-2,b) xs\n | otherwise = NO\n"}, {"source_code": "main = do\n (_:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ f 0 0 a\nf _ _ [] = \"YES\"\nf x y (a:as)\n | a == 25 = f (x + 1) y as\n | a == 50 = if x > 0 then f (x - 1) (y - 1) as else \"NO\"\n | otherwise = if y > 0 && x > 0 then f (x - 1) (y - 1) as else if x > 2 then f (x - 3) y as else \"NO\""}, {"source_code": "import Data.List\n\ncal ls = let bills = map (+0) $ map read $ words $ ls !! 1\n neededChange = map ( + (-25)) bills\n\t in sell bills 0 0\n\nsell bills c25 c50\n\t| c25<0 || c50 <0 = \"NO\"\n\t| bills == [] = \"YES\"\n\t| (head bills) == 25 = sell (tail bills) (c25+1) c50 \n\t| (head bills) == 50 = sell (tail bills) (c25-1) (c50+1)\n\t| c50 >0 = sell (tail bills) (c25 -1) (c50-1)\n\t| otherwise = sell (tail bills) (c25 -3) c50\n\nmain = interact ( show . cal . lines)\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\n\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) x f = x >>= (return.f); infixl 1 ||>\nref = (!!)\n\ngo :: [Int] -> (Int,Int,Int) -> Bool\ngo [] _ = True\ngo (25:xs) (a,b,c) = go xs (a+1, b, c)\ngo (50:xs) (a,b,c)\n | a < 1 = False\n | True = go xs (a-1, b+1, c)\ngo (100:xs) (a,b,c)\n | b > 0 = go xs (a, b-1, c+1)\n | a >= 3 = go xs (a-3, b, c+1)\n | True = False\n\nmain = do\n ls <- getContents ||> lines\n n <- head ls |> readIO :: IO Int\n xs <- (ref ls 1) |> words |> map read |> return :: IO [Int]\n putStrLn (if (go xs (0,0,0)) then \"YES\" else \"NO\")\n\n-- vim: set ft=haskell:\n"}], "src_uid": "63b20ab2993fddf2cc469c4c4e8027df"} {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n", "positive_code": [{"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "main = getContents >>= print.solve.map read.words\n\ntype Time = Double\n\neps = 1e-8\n\ntype Pos = (Double,Double) \ndist :: Pos -> Pos -> Double\ndist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)\n\ndata Line = L Double Double Double\nline :: Pos -> Pos -> Line\nline (x0,y0) (x1,y1) = L a b c\n where\n a = y1-y0\n b = x0-x1\n c= -a*x0-b*y0\nintersection :: Line -> Line -> Maybe Pos\nintersection (L a b p) (L c d q)\n | det <= eps = Nothing\n | otherwise = Just (x,y)\n where\n det = a*d-b*c\n x = (b*q-d*p)/det\n y = (c*p-a*q)/det\n\nsolve :: [Double] -> Time\nsolve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6\n where\n bsearch 0 l r = r\n bsearch i l r\n | isReachable m = bsearch (i-1) l m\n | otherwise = bsearch (i-1) m r\n where\n m = (l+r)/2\n\n rp = dist (xp0,yp0) (0,0)\n phi = atan2 yp0 xp0\n omega = vp/rp\n r0 = dist (x0,y0) (0,0)\n\n pos :: Time -> Pos\n pos t = (rp*(cos (omega*t+phi)),rp*(sin (omega*t+phi)))\n isBehind :: Pos -> Bool\n isBehind (xp,yp) = d Double\n extDist (xp,yp)\n | d < eps = 0\n | isBehind (xp,yp) = l0+lp+lc\n | otherwise = d\n where\n d = dist (xp,yp) (x0,y0)\n l0 = sqrt (x0*x0+y0*y0-r*r)\n lp = sqrt (xp*xp+yp*yp-r*r)\n lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))\n isReachable :: Time -> Bool\n isReachable t = extDist (pos t) <= v*t\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n r = hypot x y\n q = atan2 y x\n rp = hypot xp0 yp0\n qp0 = atan2 yp0 xp0\n wp = vp / rp\n arc = pi - asin ( rs / r ) - asin ( rs / rp )\n tans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n search a b = if b - a < eps then a else let\n t = ( a + b ) / 2\n qp = fix ( qp0 + wp * t )\n xp = rp * cos qp\n yp = rp * sin qp\n dq = min ( fix $ qp - q ) ( fix $ q - qp )\n dist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n in if dist <= t * v then search a t else search t b\n in search 0 tMax\n\nmain = interact $ show . solve . map read . words"}, {"source_code": "eps = 1e-9\ntMax = 1e13\ntau = 2 * pi\n\nhypot a b = sqrt ( a^2 + b^2 )\nfix q = q - tau * ( fromIntegral $ floor $ q / tau )\n\nsolve [xp0,yp0,vp,x,y,v,rs] = let\n\tr = hypot x y\n\tq = atan2 y x\n\trp = hypot xp0 yp0\n\tqp0 = atan2 yp0 xp0\n\twp = vp / rp\n\tarc = pi - asin ( rs / r ) - asin ( rs / rp )\n\ttans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )\n\tsearch a b = if b - a < eps then a else let\n\t\tt = ( a + b ) / 2\n\t\tqp = fix ( qp0 + wp * t )\n\t\txp = rp * cos qp\n\t\typ = rp * sin qp\n\t\tdq = min ( fix $ qp - q ) ( fix $ q - qp )\n\t\tdist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs\n\t\tin if dist <= t * v then search a t else search t b\n\tin search 0 tMax\n\nmain = interact $ show . solve . map read . words\n\n"}], "negative_code": [{"source_code": "main = getContents >>= print.solve.map read.words\n\ntype T = Double\n\ntype Pos = (Double,Double)\ndist :: Pos -> Pos -> Double\ndist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)\n\ndata Line = L Double Double Double\nline :: Pos -> Pos -> Line\nline (x0,y0) (x1,y1) = L a b c\n where\n a = y1-y0\n b = x0-x1\n c= -a*x0-b*y0\n\nsolve :: [Double] -> T\nsolve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6\n where\n bsearch 0 l r = r\n bsearch i l r\n | isReachable m = bsearch (i-1) l m\n | otherwise = bsearch (i-1) m r\n where\n m = (l+r)/2\n rp = dist (xp0,yp0) (0,0)\n angp = atan2 yp0 xp0\n r0 = dist (x0,y0) (0,0)\n pos :: T -> Pos\n pos t = (rp*(cos (omega*t+angp)),rp*(sin (omega*t+angp)))\n where\n omega = vp/rp\n isBehind :: Pos -> Bool\n isBehind (xp,yp) = d<=r && dist (xp,yp) (x0,y0) > sqrt (r0*r0-d*d)\n where\n L a b c = line (xp,yp) (x0,y0)\n d = abs c/sqrt(a*a+b*b)\n extDist :: Pos -> Double\n extDist (xp,yp)\n | isBehind (xp,yp) = l0+lp+lc\n | otherwise = dist (xp,yp) (x0,y0)\n where\n l0 = sqrt (x0*x0+y0*y0-r*r)\n lp = sqrt (xp*xp+yp*yp-r*r)\n lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))\n isReachable :: T -> Bool\n isReachable t = extDist (pos t) <= v*t\n"}, {"source_code": "main = getContents >>= print.solve.map read.words\n\ntype T = Double\n\ntype Pos = (Double,Double)\ndist :: Pos -> Pos -> Double\ndist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)\n\ndata Line = L Double Double Double\nline :: Pos -> Pos -> Line\nline (x0,y0) (x1,y1) = L a b c\n where\n a = y1-y0\n b = x0-x1\n c= -a*x0-b*y0\n\nsolve :: [Double] -> T\nsolve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6\n where\n bsearch 0 l r = r\n bsearch i l r\n | isReachable m = bsearch (i-1) l m\n | otherwise = bsearch (i-1) m r\n where\n m = (l+r)/2\n rp = dist (xp0,yp0) (0,0)\n angp = atan2 yp0 xp0\n r0 = dist (x0,y0) (0,0)\n pos :: T -> Pos\n pos t = (rp*(cos (omega*t+angp)),rp*(sin (omega*t+angp)))\n where\n omega = vp/rp\n isBehind :: Pos -> Bool\n isBehind (xp,yp) = abs c/sqrt(a*a+b*b) <= r\n where\n L a b c = line (xp,yp) (x0,y0)\n extDist :: Pos -> Double\n extDist (xp,yp)\n | isBehind (xp,yp) = l0+lp+lc\n | otherwise = dist (xp,yp) (x0,y0)\n where\n l0 = sqrt (x0*x0+y0*y0-r*r)\n lp = sqrt (xp*xp+yp*yp-r*r)\n lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))\n isReachable :: T -> Bool\n isReachable t = extDist (pos t) <= v*t\n"}, {"source_code": "main = getContents >>= print.solve.map read.words\n\ntype Time = Double\n\ntype Pos = (Double,Double) \ndist :: Pos -> Pos -> Double\ndist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)\n\ndata Line = L Double Double Double\nline :: Pos -> Pos -> Line\nline (x0,y0) (x1,y1) = L a b c\n where\n a = y1-y0\n b = x0-x1\n c= -a*x0-b*y0\n\nsolve :: [Double] -> Time\nsolve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6\n where\n bsearch 0 l r = r\n bsearch i l r\n | isReachable m = bsearch (i-1) l m\n | otherwise = bsearch (i-1) m r\n where\n m = (l+r)/2\n \n rp = dist (xp0,yp0) (0,0)\n phi = atan2 yp0 xp0\n omega = vp/rp\n r0 = dist (x0,y0) (0,0)\n \n pos :: Time -> Pos\n pos t = (rp*(cos (omega*t+phi)),rp*(sin (omega*t+phi)))\n isBehind :: Pos -> Bool\n isBehind (xp,yp) = d= sqrt (rp*rp-d*d)\n where\n L a b c = line (xp,yp) (x0,y0)\n d = abs c/sqrt(a*a+b*b)\n extDist :: Pos -> Double\n extDist (xp,yp)\n | isBehind (xp,yp) = l0+lp+lc\n | otherwise = dist (xp,yp) (x0,y0)\n where\n l0 = sqrt (x0*x0+y0*y0-r*r)\n lp = sqrt (xp*xp+yp*yp-r*r)\n lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))\n isReachable :: Time -> Bool\n isReachable t = extDist (pos t) <= v*t\n"}, {"source_code": "main = getContents >>= print.solve.map read.words\n\ntype T = Double\n\ntype Pos = (Double,Double) \ndist :: Pos -> Pos -> Double\ndist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)\n\ndata Line = L Double Double Double\nline :: Pos -> Pos -> Line\nline (x0,y0) (x1,y1) = L a b c\n where\n a = y1-y0\n b = x0-x1\n c= -a*x0-b*y0\n\nsolve :: [Double] -> T\nsolve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6\n where\n bsearch 0 l r = r\n bsearch i l r\n | isReachable m = bsearch (i-1) l m\n | otherwise = bsearch (i-1) m r\n where\n m = (l+r)/2\n rp = dist (xp0,yp0) (0,0)\n angp = atan2 yp0 xp0\n r0 = dist (x0,y0) (0,0)\n pos :: T -> Pos\n pos t = (rp*(cos (omega*t+angp)),rp*(sin (omega*t+angp)))\n where\n omega = vp/rp\n isBehind :: Pos -> Bool\n isBehind (xp,yp) = abs c/sqrt(a*a+b*b) Double\n extDist (xp,yp)\n | isBehind (xp,yp) = l0+lp+lc\n | otherwise = dist (xp,yp) (x0,y0)\n where\n l0 = sqrt (x0*x0+y0*y0-r*r)\n lp = sqrt (xp*xp+yp*yp-r*r)\n lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))\n isReachable :: T -> Bool\n isReachable t = extDist (pos t) <= v*t\n"}], "src_uid": "e8471556906e5fa3a701842570fa4ee2"} {"source_code": "main = interact$calc.map trans.tail.lines\n\ntrans :: String -> (Int, Int)\n\ntrans s = ((read.head.words) s, (read.last.words) s)\n\ncalc :: [(Int, Int)] -> String\ncalc wtf = ((++).show.calc') wtf \"\\n\"\ncalc' :: [(Int, Int)] -> Int\ncalc' a | length a == 0 = 0\n | length a == 1 = (if ((snd.head) a) - ((fst.head) a) > 1 then 1 else 0)\n | otherwise = (if ((snd.head) a) - ((fst.head) a) > 1 then 1 + (calc'.tail) a else (calc'.tail) a)", "positive_code": [{"source_code": "main = print . solve . map parse . tail . lines =<< getContents\nparse l = read b - read a where [a,b] = words l\nsolve = length . filter (>= 2)\n"}, {"source_code": "main :: IO ()\nmain = interact (show . solve . map parse . tail . lines)\n\nparse :: String -> (Int, Int)\nparse s = (p, q)\n where\n [p, q] = map read . words $ s\n\nsolve :: [(Int, Int)] -> Int\nsolve = length . filter (\\(p, q) -> q - p >= 2)\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/467/A\n\nrooms :: [[Int]] -> Int\nrooms = length . filter (\\(p:q:_) -> q - p >= 2)\n\nsolve :: String -> String\nsolve = show . rooms . parse\n\nparse :: String -> [[Int]]\nparse = fmap (fmap read . words) . tail . lines\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "module Main where\nimport Control.Applicative\n\ngetFreeBeds :: String -> Int\ngetFreeBeds line = let [taken,maxi] = map (read :: String -> Int) $ words line in maxi - taken\n\nmain = do\n roomCount <- (read :: String -> Int) <$> getLine\n print =<< length . filter (>1) <$> mapM (\\_ -> getFreeBeds <$> getLine) [1..roomCount]\n"}, {"source_code": "import Data.List\nsolve = length . filter (\\[o,c] -> c-o > 1)\nmain = interact $ show . solve . map (map read . words) . tail . lines"}, {"source_code": "import Data.List\nsolve = length . fst . partition (\\[o,c] -> c-o > 1)\nmain = interact $ show . solve . map (map read . words) . tail . lines"}, {"source_code": "f :: Integer -> IO [(Int, Int)]\nf 0 = return []\nf n = do \n l <- getLine\n r <- f (n-1)\n let [a,b] = map read $ words l in return ((a,b):r) \n \n\nmain :: IO()\nmain = do \n n <- getLine\n z <- f $ read n\n putStrLn $ show $ sum $ map (\\(x,y) -> if y - x >= 2 then 1 else 0) z"}, {"source_code": "f :: Integer -> IO [(Int, Int)]\nf 0 = return []\nf n = do \n l <- getLine\n r <- f (n-1)\n let [a,b] = map read $ words l in return ((a,b):r) \n \n\nmain :: IO()\nmain = do \n n <- getLine\n z <- f $ read n\n putStrLn $ show $ length $ filter (\\(x,y) -> y - x >= 2) z"}, {"source_code": "import Data.List\nimport Data.Char\n\n--In matrix rows values should be space separated\ninputNumMatrix :: Int -- ^ nRows\n -> IO [[Int]]\ninputNumMatrix nRows =\n sequence $ replicate nRows (map read . words <$> getLine)\n\nrooms :: [[Int]] -> IO ()\nrooms rs = putStrLn $ show $ length $ filter (\\room -> (room!!1) - (room!!0) >= 2) rs\n\nmain :: IO ()\nmain = read <$> getLine >>= inputNumMatrix >>= rooms"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n \n\nmain= do\n\tgetLine\n \ts<-map (map read) . map words.lines <$> getContents ::IO [[Int]]\n\tprint $ length $ filter (\\z-> (last z-head z) >1) s"}, {"source_code": "main = do\n m <- readLn\n ml <- sequence $ replicate m getLine\n let ml2 = map ((\\[x, y] -> y - x) . map read. words) ml\n let ml3 = length $ filter (>=2) ml2\n print ml3"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n print =<< sum . map (fromEnum . (\\[a,b]->a + 2 <= b) . map (read :: String -> Int) . words) <$> replicateM n getLine "}, {"source_code": "import Control.Monad\n\nisAvailable :: [Int] -> Int\nisAvailable l = if last l - head l >= 2 then 1 else 0\n\nmain :: IO ()\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n print $ foldl (+) 0 (fmap (isAvailable . lineToIntL) inputs)\n where lineToIntL = fmap (\\i -> read i :: Int) . words\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = getLine >>= return . read\n >>= flip replicateM getLine\n >>= return . map (map read . words)\n >>= print . length . filter solve\n\nsolve :: [Integer] -> Bool\nsolve [x , y] = y - x > 1"}, {"source_code": "import Data.List\n\nprocess :: [(Int,Int)] -> Int\nprocess = length.filter (\\(p,q) -> q-p >= 2)\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int,Int)\nreadPair line = (a,b)\n where [a,b] = map readInt $ words line\n\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readPair . lines) getContents\n print $ process xs"}, {"source_code": "\nmain = interact $ show . sol . map read . drop 1 . words\n\nsol [] = 0\nsol (a:b:r)\n | b-a >= 2 = 1 + sol r\n | otherwise = sol r\n\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact f\n\nf = show . length . filter (\\(x:y:_) -> y-x >= 2) . map (map read.words) . tail . lines\n"}, {"source_code": "main = interact$show.calc.map trans.tail.lines\ntrans :: String -> (Int, Int)\ntrans s = ((read.head.words) s, (read.last.words) s)\ncalc :: [(Int, Int)] -> Int\ncalc ((x, y):[]) | y - x >= 2 = 1\n | otherwise = 0\ncalc ((x, y):s) | y - x >= 2 = 1 + calc s\n | otherwise = calc s"}, {"source_code": "rooms :: [[Int]] -> Int\nrooms = length . filter (\\(p:q:_) -> q - p >= 2)\n\nsolve :: String -> String\nsolve = show . rooms . parse\n\nparse :: String -> [[Int]]\nparse = fmap (fmap read . words) . tail . lines \n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "solve :: [Int] -> Int\nsolve (p:q:rest) = (if q >= p + 2 then 1 else 0) + solve rest\nsolve [] = 0\nmain = print . solve . tail . map read . words =<< getContents"}, {"source_code": "main = print . length . filter (>= 2) .map ((\\[p, q] -> q - p) . map read . words) . tail . lines =<< getContents"}, {"source_code": "solve [] = 0\nsolve (p:q:r) = solve r + if q > p + 1 then 1 else 0\nmain = print . solve . tail . map read . words =<< getContents"}, {"source_code": "f lst = length (filter (\\ x -> (x!!1) - (x!!0) >= 2) lst)\nmain = do\n getLine\n nums <- getContents\n let linelst = lines nums\n lst = map (\\ x -> map read $ words x) linelst :: [[Int]]\n ans = f lst\n print ans\n"}, {"source_code": "parse xs = read xs :: Int\nrun xs = show $ foldl (+) 0 $ map (\\l -> let li = map parse $ words l in if li!!1-li!!0>=2 then 1 else 0) ls where ls = tail (lines xs)\nmain = interact run"}, {"source_code": "run xs = show $ foldl (+) 0 $ map (\\l -> let li = map (read) $ words l in fromEnum (li!!1-li!!0>=2)) ls where ls = tail (lines xs)\nmain = interact run"}, {"source_code": "main = interact $ show.length.filter (>=2).map (\\[x,y]->y-x).map ((map read).words).tail.lines\n"}, {"source_code": "solve :: [(Int, Int)] -> Int\nsolve xs = length $ filter (\\(x, y) -> y - x > 1) xs\n\nparseInput :: String -> [(Int, Int)]\nparseInput input = xs where\n ls = tail $ lines input\n ys = map words ls\n xs = [(read x, read y) | [x, y] <- ys]\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = parseInput input\n print $ solve xs\n"}, {"source_code": "\n\nmain = do\n d <- getContents\n let (n:ls) = lines d\n let rooms = map (map read . words) ls :: [[Int]]\n let ans = foldr (\\[a,b] c -> c + if b - a >= 2 then 1 else 0) 0 rooms\n print ans\n"}, {"source_code": "findNum :: [(Int, Int)] -> Int\nfindNum l = length $ filter (\\p -> snd p - fst p > 1) l\n\nmain = do \n n <- readLn :: IO Int\n content <- getContents\n let\n rooms = map (\\[x, y] -> (x, y)) . map (map (read::String->Int)) . map words . lines $ content\n putStrLn $ show $ findNum rooms\n"}, {"source_code": "module Main (main)\n where\n\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = print . count . map readInts =<< flip replicateM getLine =<< readLn\n where count = length . filter (>= 2) . map (\\[a,b] -> b - a)\n readInts = map read . words"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadRoom :: B.ByteString -> [Int]\nreadRoom = map (fst . fromJust . B.readInt) . B.split ' '\n\nisThereSpace :: B.ByteString -> Int\nisThereSpace room = if occupied + 2 <= available then 1 else 0\n where space = readRoom room\n occupied = head space\n available = last space\n\nmain = B.getContents >>=\n return . show . sum . map (isThereSpace) . tail . B.lines >>=\n putStrLn\n"}, {"source_code": "import Control.Monad\nmain = do\n\tgetLine\n\tc<-getContents\n\tprint $ length $ filter (\\[x,y]->y-x>1)$map (map read.words) $ lines c\n\n"}, {"source_code": "\nmain = do\n\tn<-getLine\n\trest<-getContents\n\tputStrLn $ show $ solve $ map (map read)$ map words $ lines $ rest\n\nsolve [] = 0\nsolve ([m1,m2]:ms) = if m2-m1>=2 then 1+(solve ms) else solve ms"}, {"source_code": "\n-- https://stackoverflow.com/questions/10285837/read-n-lines-into-a-string\n-- http://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Monad.html#v:replicateM\n------------\n-- http://learnyouahaskell.com/input-and-output\n\n-- go to the sequence part of the page\n\n-- learn how to use foldl, foldr, map --functions\n--------------------------------------------------\n-- learn your haskell library:\n-- https://downloads.haskell.org/~ghc/latest/docs/html/libraries/\n--\n-- page 15 of learn you a haskell for great good\n-- i can use this\n\n\n-- next: i discovered the \"sequence\" function on this webpage\n-- http://learnyouahaskell.com/input-and-output\n-- it is also the same as page 164 in the book \"learn you a\n-- haskell for great good\"\n-- This seems to be a conventional function that is used\n-- so i am going o use it.\n\n\nconv lst nw\n | (null lst) = nw\n | otherwise = conv (tail lst) (nw ++ [(read (head (words (head lst))))::Int]\n ++ [(read (last (words (head lst))))::Int])\n\n\ncountRooms lst rooms\n | (null lst) = rooms\n | (head (drop 1 lst)) > ((head lst)+1) = countRooms (drop 2 lst) (rooms+1)\n | otherwise = countRooms (drop 2 lst) rooms\n\n\nmain = do\n a <- getLine\n let n = (read a)::Int\n let g = replicate n getLine\n dfd <- sequence g\n let newlist = conv dfd []\n let ans = countRooms newlist 0\n putStrLn (show ans)\n\n\n\n\n \n"}, {"source_code": "import Control.Monad\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n a <- replicateM n $ do\n [living, total] <- readItems\n return $ if 2 <= total - living then 1 else 0\n putStrLn $ show $ sum $ a\n"}, {"source_code": "import Control.Monad \n\nreadNLines :: Int -> IO [String]\nreadNLines n = replicateM n getLine\n\nfreeSpace :: (Int, Int) -> Int\nfreeSpace (a, b) = b - a\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n lines <- readNLines n\n let args = map (\\x -> map (\\y -> read y :: Int) $ words x) lines\n pairs = map (\\x -> (x!!0, x!!1)) args \n print $ length $ filter (>=2) $ map freeSpace pairs"}, {"source_code": "readPairsList ::Int -> IO [(Int, Int)]\nreadPairsList n = do\n if n == 0\n then return []\n else do\n line <- getLine\n let pairStr = map read $ words line :: [Int]\n let pair = ((pairStr !! 0), (pairStr !! 1))\n rest <- readPairsList $ n-1\n return (pair:rest)\n \n\nmain = do\n n <- fmap read getLine :: IO Int\n pairs <- readPairsList n\n let answer xs = length [x | x <- xs, fst(x)+2 <= snd(x)]\n\n putStrLn $ show(answer pairs)"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = interact $ show . solve . tail . map read . words\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve (p:q:xs) = solve xs + if (q >= p + 2) then 1 else 0\n"}, {"source_code": "main = do\n getLine\n ps <- fmap (map (map read . words). lines) getContents\n print $ length $ filter (\\[a, b] -> a+2 <= b) ps"}, {"source_code": "main = interact $ show . length . filter id . map (\\[a,b] -> a+2<=b) . map (map read) . map words . tail . lines\n"}, {"source_code": "main = do\n\tstring <- getContents\n\tprint . length . filter (\\(a, b) -> b-a >= 2) . map (\\[a,b] -> (a,b)) . map (map read) . map words . tail $ lines string"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\x->interact $ show .solve. map (map read.words).take (read x) . lines\nsolve :: [[Int]]->Int\nsolve xss =foldr (\\ a b-> if a>=2 then 1+b else b) 0 [y-x|(x:y:[])<-xss]"}, {"source_code": "import Control.Monad\nimport Data.List\n\nint x = read x ::Int \n\nrooms = length . filter (>=2) . (uncurry $ flip $ zipWith (-)) . unzip\n\nmain = do\n n <- liftM int getLine\n vs <- liftM (map ((\\[x,y] -> (x,y)) . map int. words)) $ replicateM n getLine \n print $ rooms vs\n"}, {"source_code": "-- Codeforces 467A\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n replicateM n getLine >>= print . length . filter (\\x -> (x!!1)-(x!!0) >= 2) . map (map read . words)\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- map (map read . words) . lines <$> getContents\n print . sum $ map (\\[x,y] -> if y-x >= 2 then 1 else 0) xs"}, {"source_code": "\n\nmain = interact solve\n\nsolve input = show (foldr folder 0 rooms)\n where\n folder (p,q) ccount = if (q-p) >= 2 then\n ccount+1\n else\n ccount\n as_nums::[Integer]\n n::Integer\n (n:as_nums) = (map read.words) input\n rooms = two_by_two as_nums\n\ntwo_by_two::[a] -> [(a,a)]\ntwo_by_two [] = []\ntwo_by_two (x:y:xs) = (x,y):(two_by_two xs)\n"}, {"source_code": "import Control.Monad\nimport Data.List \n\nreadInt :: IO Int\nreadInt = readLn\n\nuntilSpace :: [Char] -> [Char] -> [[Char]] -> [[Char]]\nsplit :: [Char] -> [Int]\ngetInt a = read a::Int\n\nuntilSpace arg acc result = if arg == [] then acc : result else\n if head arg == ' ' then untilSpace (tail arg) (\"\") (acc : result) else\n untilSpace (tail arg) (acc ++ [head arg]) (result)\nsplit a = map (getInt) (reverse $ untilSpace (a) (\"\") ([]))\n\ncount :: [[Int]] -> Int -> Int\ncount [] n = n\ncount (a:xa) n | a!!1 - a!!0 >= 2 = count xa (n + 1)\n | otherwise = count xa n\n\n\nsolve a = putStrLn $ show (count (map split a) 0)\nreadLines a = replicateM a getLine >>= solve\nmain = readInt >>= readLines"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n n <- readLn\n xs <- replicateM n $ map read . words <$> getLine\n let\n m = length . filter (\\[p,q] -> p+2 <= q) $ xs\n in print m\n"}, {"source_code": "\nimport Control.Applicative\nimport Data.List\n\n\n\nmain=do\n getLine\n x<-( map (map read) <$> map words <$> lines <$> getContents)::IO [[Int]]\n putStrLn $ show $ length $ filter (>=2) $ map (\\[a,b]->b-a) x\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Int\nsolve pqs = length [ () | [p, q] <- pqs, p + 2 <= q ]\n"}, {"source_code": "main=getContents>>=print.solve.map(map read.words).tail.lines\nsolve w=length[p|[p,q]<-w,p+2<=q]\n"}, {"source_code": "import Prelude hiding (readList)\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nreadInt :: IO Int\nreadInt = head <$> readList' (undefined::Int)\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- replicateM n (readList' (undefined::Int))\n print $ length $ filter (\\[a,b] -> a+2 <= b) xs\n \n"}, {"source_code": "fit :: String -> Bool\nfit s = q >= p + 2\n where p = num !! 0\n q = num !! 1\n num = map read $ words s\n\nrooms :: [String] -> Int\nrooms l = length $ filter fit l\n\nmain = do\n getLine\n interact $ show . rooms . lines\n"}], "negative_code": [{"source_code": "main = do\n getLine\n ps <- fmap (map (map read . words). lines) getContents\n print $ filter (\\[a, b] -> a+2 <= b) ps"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Int\nsolve pqs = length [ () | [p, q] <- pqs, p < q ]\n"}, {"source_code": "f lst = length (filter (\\ x -> (abs (x!!0) - (x!!1)) > 1) lst)\nmain = do\n getLine\n nums <- getContents\n let linelst = lines nums\n lst = map (\\ x -> map read $ words x) linelst :: [[Int]]\n ans = f lst\n print ans\n"}, {"source_code": "main = interact $ show.length.filter (>2).map (\\[x,y]->y-x).map ((map read).words).tail.lines\n"}], "src_uid": "2a6c457012f7ceb589b3dea6b889f7cb"} {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [a, v, l, d, w]\n | w >= v || signAccelPath >= d = time a 0 v l\n | otherwise = signAccelTime + 2 * time a w v ((d - signAccelPath) / 2) + time a w v (l -d)\n where\n signAccelTime = w / a\n signAccelPath = dist a 0 signAccelTime\n\ndist :: Double -> Double -> Double -> Double\ndist a v t = v * t + a * t * t / 2\n\ntime :: Double -> Double -> Double -> Double -> Double\ntime a v0 v l\n | fullAccTime > totalTime = totalTime\n | otherwise = fullAccTime + remainingDist / v\n where\n fullAccTime = (v - v0) / a\n totalTime = (sqrt (v0^2 + 2 * l * a) - v0) / a\n remainingDist = l - dist a v0 fullAccTime", "positive_code": [{"source_code": "\nimport Monad (liftM)\n{-\nimport HUnit\n\ntests :: Test\ntests = TestList \"Tests\"\n [\n Test \"#01\" $ assertEq 2.5 $ solve [1,1,2,1,3],\n Test \"#02\" $ assertApproximate 8.965874696353 (solve [5,70,200,170,40]) 6,{-\n Test \"#03\" $ assertApproximate $ solve [],\n Test \"#04\" $ assertApproximate $ solve [],\n Test \"#05\" $ assertApproximate $ solve [],\n Test \"#06\" $ assertApproximate $ solve [],\n Test \"#07\" $ assertApproximate $ solve [],\n Test \"#08\" $ assertApproximate $ solve [],\n Test \"#09\" $ assertApproximate $ solve [],\n Test \"#10\" $ assertApproximate $ solve [],\n Test \"#11\" $ assertApproximate $ solve [],\n Test \"#12\" $ assertApproximate $ solve [],\n Test \"#13\" $ assertApproximate $ solve [],\n Test \"#14\" $ assertApproximate $ solve [],\n Test \"#15\" $ assertApproximate $ solve [],\n Test \"#16\" $ assertApproximate $ solve [],-}\n Test \"#17\" $ assertApproximate 57.6 (solve [4,120,5112,3000,130]) 5\n ]\n\ntest :: IO ()\ntest = run tests\n-}\ns' :: Floating a => a -> a -> a -> a\ns' v0 a t = v0 * t + 0.5 * a * t^2\n\nt' :: Floating a => a -> a -> a -> a\nt' v0 a s = (-v0 + sqrt (v0^2 + 2 * a * s)) / a\n\nv' :: Floating a => a -> a -> a -> a\nv' v0 a t = v0 + a * t\n\ntMax' :: (Floating a, Ord a) => a -> a -> a -> a -> a\ntMax' v v0 a s\n | t1 < t2 = t1\n | otherwise = t2 + (s - s' v0 a t2) / v\n where\n t1 = t' v0 a s\n t2 = (v - v0) / a\n\ntMax'' :: (Floating a, Ord a) => a -> a -> a -> a -> a -> a\ntMax'' v w v0 a s\n | w >= v = tMax' v v0 a s\n | tS <= tW = tMax' v v0 a s\n | sW + 2 * sWV >= s = tW + 2 * t' w a (0.5 * (s - sW))\n | otherwise = tW + 2 * tWV + (s - sW - 2 * sWV) / v\n where\n tS = t' v0 a s\n tW = (w - v0) / a\n tWV = (v - w) / a\n sW = s' v0 a tW\n sWV = s' w a tWV\n\nsolve :: (Floating a, Ord a) => [a] -> a\nsolve [a, v, l, d, w]\n | v <= w = tMax' v 0 a l\n | tD <= tW = tMax' v 0 a l\n | otherwise = tMax'' v w 0 a d + tMax' v w a (l-d)\n where\n tD = t' 0 a d\n tW = w / a\n\nmain :: IO ()\nmain = liftM (map read . take 5 . words) getContents >>= print . solve\n"}, {"source_code": "import Text.Printf\nmain = do\n [a, v, l, d, w] <- (map (fromInteger . read) . take 5) `fmap` \n (words `fmap` getContents) :: IO [Double]\n let maxAccelPath = v^2 / 2 / a\n maxAccelPath' = w^2 / 2 / a\n\tmaxDecelPath = maxAccelPath - maxAccelPath'\n (t1, w') | v > w && d < maxAccelPath' = (sqrt (2 * d / a), t1 * a)\n | v > w && d < maxAccelPath+maxDecelPath = let \n s' = (d + maxAccelPath') / 2 in (2 * sqrt (2 * s' / a) - w / a, w)\n | v > w = (v / a + (v - w) /a + (d + maxAccelPath' \n - 2 * maxAccelPath) / v, w)\n | w >= v && d < maxAccelPath = (sqrt (2 * d / a), t1*a)\n | otherwise = (v / a + (d - maxAccelPath) / v, v)\n maxAccelPath2 | w' < v = maxAccelPath - w'^2 / 2 /a\n | otherwise = 0\n t2 | (l - d) < maxAccelPath2 = sqrt (2*(l - d + w'^2/2/a)/a) - w'/a\n | otherwise = (v - w')/a + (l - d - maxAccelPath2)/v\n printf \"%.5f\" (t1+t2)\n \n"}, {"source_code": "calc a v l d w\n | v <= w = calc2 l 0\n | otherwise = let tw = w/a\n dw = dist 0 tw\n in if dw >= d then\n calc2 l 0\n else tw+2*calc2 ((d-dw)/2) w+calc2 (l-d) w\n where calc2 len v0 = let t1 = (v-v0)/a\n t2 = ((sqrt $ v0*v0+2*a*len) - v0) / a\n in if t1 > t2 then t2\n else t1+(len-dist v0 t1)/v\n dist v0 t = v0*t+a*t*t/2\n\nmain = do\n [a, v] <- return . (map read :: [String] -> [Double]) . words =<< getLine\n [l, d, w] <- return . (map read :: [String] -> [Double]) . words =<< getLine\n print $ calc a v l d w"}], "negative_code": [{"source_code": "\nimport Monad (liftM)\n\ns :: Floating a => a -> a -> a -> a\ns v0 a t = v0 * t + 0.5 * a * t^2\n\nt :: Floating a => a -> a -> a -> a\nt v0 a s = (-v0 + sqrt (v0^2 + 2 * a * s)) / a\n\nv :: Floating a => a -> a -> a -> a\nv v0 a t = v0 + a * t\n\nsolve :: (Floating a, Ord a) => [a] -> a\nsolve [a, vMax, l, d, w]\n | w >= vMax = solve' 0 vMax a l\n | v 0 a tr <= w = solve' 0 vMax a l\n | otherwise = solve'' w vMax a d + t2\n where\n tr = t 0 a d\n t2 = solve' w vMax a (l - d)\n solve' v0 vMax a l\n | v v0 a tr <= vMax = t v0 a l\n | otherwise = vMax / a + (l - s v0 a (vMax / a)) / vMax\n where\n tr = t v0 a l\n solve'' w vMax a d\n | tr2 <= tr1 = w/a + 2 * tr2\n | otherwise = w/a + 2 * tr1 + (d - d' - 2 * s w a tr1) / vMax\n where\n tr1 = (vMax - w) / a\n tr2 = t w a (0.5 * (d - d'))\n d' = s 0 a (w/a)\n\nmain :: IO ()\nmain = liftM (map read . take 5 . words) getContents >>= print . solve\n"}, {"source_code": "\nimport Monad (liftM)\n\ns' :: Floating a => a -> a -> a -> a\ns' v0 a t = v0 * t + 0.5 * a * t^2\n\nt' :: Floating a => a -> a -> a -> a\nt' v0 a s = (-v0 + sqrt (v0^2 + 2 * a * s)) / a\n\nv' :: Floating a => a -> a -> a -> a\nv' v0 a t = v0 + a * t\n\ntMax' :: (Floating a, Ord a) => a -> a -> a -> a -> a\ntMax' v v0 a s\n | t1 < t2 = t1\n | otherwise = t2 + (s - s' v0 a t2) / v\n where\n t1 = t' v0 a s\n t2 = (v - v0) / a\n\ntMax'' :: (Floating a, Ord a) => a -> a -> a -> a -> a -> a\ntMax'' v w v0 a s\n | w >= v = tMax' v v0 a s\n | tS <= tW = tMax' v v0 a s\n | sW + 2 * sWV >= s = tW + 2 * t' w a (0.5 * (s - sW))\n | otherwise = tW + 2 * tWV + (s - sW - 2 * sWV) / v\n where\n tS = t' v0 a s\n tW = (w - v0) / a\n tWV = (v - w) / a\n sW = s' v0 a tW\n sWV = s' w a tWV\n\nsolve :: (Floating a, Ord a) => [a] -> a\nsolve [a, v, l, d, w]\n | tD <= tW = tMax' v 0 a l\n | otherwise = tMax'' v w 0 a d + tMax' v w a (l-d)\n where\n tD = t' 0 a d\n tW = w / a\n\nmain :: IO ()\nmain = liftM (map read . take 5 . words) getContents >>= print . solve\n"}, {"source_code": "import Text.Printf\nmain = do\n [a, v, l, d, w] <- (map (fromInteger . read) . take 5) `fmap` \n (words `fmap` getContents) :: IO [Double]\n let maxAccelPath = v^2 / 2 / a\n maxAccelPath' = w^2 / 2 / a\n\tmaxDecelPath = maxAccelPath - maxAccelPath'\n (t1, w') | v > w && d < maxAccelPath' = (sqrt (2 * d / a), t1 * a)\n | v > w && d < maxAccelPath+maxDecelPath = let \n s' = (d + maxAccelPath') / 2 in (2 * sqrt (2 * s' / a) - w / a, w)\n | v > w = (v / a + (v - w) /a + (d + maxAccelPath' \n - 2 * maxAccelPath) / a, w)\n | w >= v && d < maxAccelPath = (sqrt (2 * d / a), t1*a)\n | otherwise = (v / a + (d - maxAccelPath) / v, v)\n maxAccelPath2 | w' < v = maxAccelPath - w'^2 / 2 /a\n | otherwise = 0\n t2 | (l - d) < maxAccelPath2 = sqrt (2*(l - d + w'^2/2/a)/a) - w'/a\n | otherwise = (v - w')/a + (l - d - maxAccelPath2)/v\n printf \"%.5f\" (t1+t2)\n \n"}, {"source_code": "calc a v l d w\n | v <= w = calc2 l 0\n | otherwise = let tw = w/a\n dw = dist 0 tw\n in if dw >= l then\n calc2 l 0\n else tw+2*calc2 ((d-dw)/2) w+calc2 (l-d) w\n where calc2 len v0 = let t1 = (v-v0)/a\n t2 = ((sqrt $ v0*v0+2*a*len) - v0) / a\n in if t1 > t2 then t2\n else t1+(len-dist v0 t1)/v\n dist v0 t = v0*t+a*t*t/2\n\nmain = do\n [a, v] <- return . (map read :: [String] -> [Double]) . words =<< getLine\n [l, d, w] <- return . (map read :: [String] -> [Double]) . words =<< getLine\n print $ calc a v l d w"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [a, v, l, d, w]\n | w >= v || signAccelPath >= d = time2 a 0 v l\n | otherwise = signAccelTime + 2 * time1 a w ((d - signAccelPath) / 2) + time2 a w v (l -d)\n where\n signAccelTime = w / a\n signAccelPath = dist a 0 signAccelTime\n\ndist :: Double -> Double -> Double -> Double\ndist a v t = v * t + a * t * t / 2\n\ntime1 :: Double -> Double -> Double -> Double\ntime1 a v l = (sqrt (v^2 + 2 * l * a) - v) / a\n\ntime2 :: Double -> Double -> Double -> Double -> Double\ntime2 a v0 v l\n | fullAccTime > totalTime = totalTime\n | otherwise = fullAccTime + remainingDist / v\n where\n fullAccTime = (v - v0) / a\n totalTime = time1 a v0 l\n remainingDist = l - dist a v0 fullAccTime"}], "src_uid": "de8c909d6ca4f3b2f885fc60be246458"} {"source_code": "import Control.Applicative\n\nsolve :: [Int] -> Int\nsolve cookies =\n if even (sum cookies) then numEvens else numOdds\n where\n numEvens = length $ filter even cookies\n numOdds = length cookies - numEvens\nmain :: IO ()\nmain = do\n getLine\n cookies <- map read . words <$> getLine\n putStrLn $ show $ solve cookies\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n getLine\n a <- liftM ( map read . words ) getLine :: IO [Int]\n\n putStrLn $ show $ length $ filter ( if even ( sum a )\n then even\n else odd\n ) a\n"}, {"source_code": "main = do\n _ <- getLine\n ls <- fmap (map read . words) getLine\n let m2 = sum ls `mod` 2\n print . length $ filter ((==m2) . (`mod`2)) ls\n\n-- vim: set expandtab:\n"}, {"source_code": "-- cookies\nparse [] word = [read $ reverse word :: Int]\nparse (' ':xs) word = (read $ reverse word :: Int):(parse xs [])\nparse (x:xs) word = parse xs (x:word)\n\nfind [] _ a = a\nfind (x:xs) s akk = if (mod (s-x) 2 == 0) then find xs s (akk + 1) else find xs s akk\n\nmain = do\n\t\t\treadLn :: IO Int\n\t\t\tl <- getLine\n\t\t\tprint $ find (parse l []) (sum (parse l []) 0) 0\n\twhere sum [] akk = akk\n\t sum (x:xs) akk = sum xs $ akk+x"}, {"source_code": "import List\ngetAns a | (sum a) `mod` 2 == 0=length (filter even a)\n | otherwise =length (filter odd a)\nmain=interact$show.getAns.map read.tail.words"}, {"source_code": "readWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> Int\nsolve xs\n | odd s = length (filter odd xs)\n | otherwise = length (filter (not . odd) xs)\n where\n s = sum xs\n\nmain :: IO ()\nmain = do\n getLine >> Main.reads >>= print . solve\n"}, {"source_code": "\nsolve xs = let s = sum xs\n in sum $ map (\\x -> 1 - mod (s - x) 2) xs\n\nmain = interact $ show.solve.map read.tail.words"}, {"source_code": "main = do s <- getLine\n s <- fmap ((map ((flip mod 2) . read::String->Int)) . words) getLine\n putStrLn $ (show . length . (filter (\\x->x==mod (sum s) 2))) s"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve as = length $ filter (if even (sum as) then even else odd) as\n"}, {"source_code": "main=interact$show.f.map read.tail.words\nf x=length[a|a<-x,odd a==odd(sum x)]\n"}, {"source_code": "main=interact$show.f.map read.tail.words\nf x=length[a|a<-x,even a==even(sum x)]\n"}, {"source_code": "import Control.Arrow\nimport Data.List\nsolve ns = if odd o then o else e\n where (e,o) = (length *** length) (partition even ns)\nmain = print . solve . map read . tail . words =<< getContents"}, {"source_code": "main = do\n getLine\n a <- fmap (map read . words) getLine\n print $ solve a\nsolve a = if even $ sum a then length $ filter even a else length $ filter odd a\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n :: Int <- readLn\n xs :: [Int] <- take n . map read . words <$> getLine\n let acc = sum xs\n answer = sum $ do\n x <- xs\n guard $ even (acc - x)\n return 1\n print answer\n\n"}, {"source_code": "main = do\n\tgetLine\n\tl <- (map read . words) `fmap` getLine\n\tlet oddEven = if odd $ sum l then odd else even\n\tprint $ length $ filter oddEven l\n"}, {"source_code": "readInts :: [String] -> [Int]\nreadInts = map read\n\nmain = interact solve\n\nsolve :: String -> String\nsolve input = result\n where result = show $ numberOfWays cookies\n cookies = readInts $ words $ lines input !! 1\n\nnumberOfWays :: [Int] -> Int\nnumberOfWays cookies\n | even total = length . filter even $ cookies\n | otherwise = length . filter odd $ cookies\n where total = sum cookies\n"}, {"source_code": "\nreadInts :: [String] -> [Int]\nreadInts = map read\n\nmain = interact solve\n\nsolve :: String -> String\nsolve input = unlines $ result : []\n where result = show $ numberOfWays cookies\n cookies = readInts $ words $ lines input !! 1\n\nnumberOfWays :: [Int] -> Int\nnumberOfWays cookies\n | even total = length . filter even $ cookies\n | otherwise = length . filter odd $ cookies\n where total = sum cookies\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n\nreaD :: BS.ByteString -> Int\nreaD = fst.fromJust . BS.readInt\n\n\n\nsolve :: [ Int ] -> BS.ByteString\nsolve xs = BS.pack.show $ a where \n\ts = sum xs \n\ta = helpSolve xs where \n\t helpSolve :: [ Int ] -> Int \n\t helpSolve [] = 0\n\t helpSolve ( y : ys ) \n | even $ s - y = 1 + helpSolve ys \n\t | otherwise = helpSolve ys\n\n\nmain = BS.interact $ solve . map reaD . BS.words . last . BS.lines\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\nmain= do\n\tgetLine\n\ts<- map read.words <$> getLine ::IO [Int]\n\tprint $ length $ filter (if even (sum s) then even else odd) s"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tlet\tarr = map (\\x -> read x:: Int) . words $ line\n\t\ttotal = foldl (+) 0 arr\n\t\tans = foldl (\\acc x -> acc + (if (total - x) `mod` 2 == 0 then 1 else 0) ) 0 arr\n\tprint ans\n"}, {"source_code": "-- Codeforces Beta Round #94\n-- Problem A -- Cookies\nmain = interact work\n\nwork :: String -> String\nwork input = show $ solve . parse $ input\n\nparse :: String -> [Int]\nparse = map (\\i -> read i :: Int) . words . last . lines\n\nsolve :: [Int] -> Int\nsolve a = length . filter (\\x -> x `mod` 2 == (sum a) `mod` 2) $ a\n"}, {"source_code": "import Data.List\nimport Debug.Trace (trace)\n\nmain2 = print $ solv [1, 2, 2, 3, 4, 4, 4, 2, 2, 2]\nmain = \n\tdo\n\t\t[n] <- getNums\n\t\tlines <- getLine\n\t\tputStrLn $ show $ solv $ getNumbers lines\n\nsolv l = length $ filter (if isE then isEven else not . isEven ) l\n\twhere \n\t\tisE = isEven $ sum l\n\nisEven x = x `mod` 2 == 0\n\n------------------utils-----------------------\ntr x y = trace ((show x) ++ (show y)) y\ntr1 x y = trace ((show x)) y\ntr2 y = trace ((show y)) y\n\n(|>) x f = f x\n\nparseInt x = (read x) :: Int\n\ngetIndex = zip [0..]\n\ngetLines n = repeat getLine |> take n |> sequence \n\ngetNums :: IO [Int]\ngetNums =\n\tdo\n\t\tline <- getLine\n\t\treturn $ getNumbers line\n\ngetNumbers line = \n\tcase index of \n\t\tNothing -> [parseInt line]\n\t\tJust i ->\n\t\t\tlet (l,r) = splitAt (i + 1) line in\n\t\t\t\t(parseInt l) : (getNumbers r)\n\twhere\n\t\tindex = elemIndex ' ' line\n\nsplitBy k = \n\tcase index of \n\t\tNothing -> [k]\n\t\tJust i ->\n\t\t\tlet (l,r) = splitAt (i) k in\n\t\t\t\tl : splitBy (drop 1 r)\n\twhere\n\t\tindex = elemIndex ' ' k\n"}], "negative_code": [], "src_uid": "4c59b4d43b59c8659bf274f3e29d01fe"} {"source_code": "import Data.List (sortBy)\nimport Data.Ord (comparing)\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (sortBy (comparing snd) . map (\\[k, c] -> (read k, read c) :: (Integer, Integer)) . map words) $ sequence $ replicate n getLine\n getLine\n ps <- fmap ((++ [10 ^ 15]) . map read . words) getLine\n print $ solve xs ps 1 0 0\n where\n solve [] _ _ _ ans = ans\n solve ((k, c):xs) (p:ps) f used ans | used + k < p = solve xs (p:ps) f (used + k) (ans + k * f * c)\n | otherwise = solve ((k - (p - used), c):xs) ps (f + 1) p (ans + (p - used) * f * c)\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do\n n <- readInt\n kc <- replicateM n ((,) <$> readInt64 <*> readInt64)\n t <- readInt\n p <- replicateM t readInt64\n return (kc, p)\n where\n readInt64 = fromIntegral <$> readInteger :: State ByteString Int64\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ndata Chunk a = Chunk Int64 a deriving (Eq, Show)\n\nzipWithChunk :: (a -> b -> c) -> [Chunk a] -> [Chunk b] -> [Chunk c]\nzipWithChunk _ [] _ = []\nzipWithChunk _ _ [] = []\nzipWithChunk f (Chunk 0 _:xs) ys = zipWithChunk f xs ys\nzipWithChunk f xs (Chunk 0 _:ys) = zipWithChunk f xs ys\nzipWithChunk f (Chunk a x:xs) (Chunk b y:ys) = Chunk c (f x y) :\n zipWithChunk f (Chunk (a - c) x:xs) (Chunk (b - c) y:ys)\n where\n c = min a b\n\nsolve (kc', p) = sum [a * b | Chunk a b <- lst]\n where\n kc = sortBy (comparing snd) kc'\n\n kcs = [Chunk k c | (k, c) <- kc]\n ps = zipWith Chunk (zipWith (-) (p++[10^12]) (0:p)) [1..]\n\n lst = zipWithChunk (*) kcs ps :: [Chunk Int64]\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do\n n <- readInt\n kc <- replicateM n ((,) <$> readInt64 <*> readInt64)\n t <- readInt\n p <- replicateM n readInt64\n return (kc, p)\n where\n readInt64 = fromIntegral <$> readInt :: State ByteString Int64\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ndata Chunk a = Chunk Int64 a deriving (Eq, Show)\n\nzipWithChunk :: (a -> b -> c) -> [Chunk a] -> [Chunk b] -> [Chunk c]\nzipWithChunk _ [] _ = []\nzipWithChunk _ _ [] = []\nzipWithChunk f (Chunk 0 _:xs) ys = zipWithChunk f xs ys\nzipWithChunk f xs (Chunk 0 _:ys) = zipWithChunk f xs ys\nzipWithChunk f (Chunk a x:xs) (Chunk b y:ys) = Chunk c (f x y) :\n zipWithChunk f (Chunk (a - c) x:xs) (Chunk (b - c) y:ys)\n where\n c = min a b\n\nsolve (kc', p) = sum [a * b | Chunk a b <- lst]\n where\n kc = sortBy (flip $ comparing snd) kc'\n\n kcs = [Chunk k c | (k, c) <- kc]\n ps = zipWith Chunk (zipWith (-) (p++[10^12]) (0:p)) [1..]\n\n lst = zipWithChunk (*) kcs ps :: [Chunk Int64]\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n"}], "src_uid": "bfd7aabf195321249db8760c3cb6998d"} {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) && a <= 0 && b >= 0 = 1\n | combo1 == 0 && combo2 == 0 = abs (result)\n | k > abs (a) && combo1 /= 0 = divisibility k k b\n | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b\n | k > abs (b) && combo2 /= 0 = divisibility k a 0\n | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18", "positive_code": [{"source_code": "import Data.Int\n\nmain = getLine >>= print . solve . map (read :: String -> Int64) . words\n\nsolve [k, a, b]\n | a == 0 = b `div` k + 1\n | 0 < a = solve [k, 0, b] - solve [k, 0, a - 1]\n | a < 0 && 0 < b = solve [k, 0, -a] + solve [k, 0, b] - 1\n | otherwise = solve [k, -b, -a]"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) && a <= 0 && b >= 0 = 1\n | combo1 == 0 && combo2 == 0 = abs (result)\n | k > abs (a) && combo1 /= 0 = divisibility k k b\n | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b\n | k > abs (b) && combo2 /= 0 = divisibility k a 0\n | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main = getLine >>= print.check.map read.words\n\ncheck [k, a, b] = b `quot` k - a `quot` k +\n if max a (-b) `mod` k == 0 || b - a > abs (a + b)\n then 1 else 0"}], "negative_code": [{"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | mod (abs a) k /= 0 && mod (abs b) k /= 0 = result\n | otherwise = 1 + result\n where l = 10^18\n result = round $ fromInteger (b - a) / fromInteger k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | mod (abs a) k /= 0 && mod (abs b) k /= 0 = result\n | otherwise = 1 + result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO ()\nmain = do\n args <- getLine\n result <- return $ show $ divisibility (read (head $ split args) :: Int) \n (read (secd $ split args) :: Int) \n (read (last $ split args) :: Int)\n putStrLn result\n\ndivisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,\n xs <- [a..b], mod xs k == 0]\n where l = 10^18\n s = -1*l\n\nsplit' :: Eq a => a -> [a] -> [[a]]\nsplit' d [] = []\nsplit' d s = x : split' d (drop 1 y) where (x,y) = span (/= d) s\n\nsplit = split' ' '\nsecd = head . tail"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) = 1\n | combo1 == 0 && combo2 == 0 = result\n | k > abs (a) && combo1 /= 0 = divisibility k k b\n | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b\n | k > abs (b) && combo2 /= 0 = divisibility k a 0\n | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) && a < 0 && b > 0 = 1\n | combo1 == 0 && combo2 == 0 = abs (result)\n | k > abs (a) && combo1 /= 0 = divisibility k k b\n | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b\n | k > abs (b) && combo2 /= 0 = divisibility k a 0\n | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n args <- getLine\n result <- return $ show $ divisibility (read (head $ split args) :: Int) \n (read (secd $ split args) :: Int) \n (read (last $ split args) :: Int)\n putStr result\n\ndivisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,\n xs <- [a..b], mod xs k == 0]\n where l = 10^18\n s = -1*l\n\nsplit' :: Eq a => a -> [a] -> [[a]]\nsplit' d [] = []\nsplit' d s = x : split' d (drop 1 y) where (x,y) = span (/= d) s\n\nsplit = split' ' '\nsecd = head . tail"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ floor $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | combo1 == 0 && combo2 == 0 = fromIntegral (b - a + k) / fromIntegral k\n | combo1 /= 0 = divisibility k (a + 1) b\n | otherwise = divisibility k a (b - 1)\n where combo1 = mod a k\n combo2 = mod b k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k > a || k > b || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | combo1 == 0 && combo2 == 0 = result\n | combo1 /= 0 = divisibility k (a + 1) b\n | combo1 == 0 = divisibility k a (b - 1)\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | mod (abs a) k /= 0 && mod (abs a) k /= 0 = result\n | otherwise = 1 + result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | (abs a < k || abs b < k) && a /= 0 && b /= 0 = result\n | otherwise = 1 + result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO Int\nmain = do\n args <- getLine\n return $ divisibility (read (head (split ' ' args)) :: Int) \n (read (head $ tail (split ' ' args)) :: Int) \n (read (last (split ' ' args)) :: Int)\n\ndivisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,\n xs <- [a..b], mod xs k == 0]\n where l = 10^18\n s = -1*l\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b = (b - a + 1) / k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) = 1\n | combo1 == 0 && combo2 == 0 = abs (result)\n | k > abs (a) = divisibility k k b\n | k < abs (a) = divisibility k (a - combo1 + k) b\n | k > abs (b) = divisibility k a 0\n | k < abs (b) = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) = 1\n | combo1 == 0 && combo2 == 0 = result\n | k > abs (a) = divisibility k k b\n | k < abs (a) = divisibility k (a - combo1 + k) b\n | k > abs (b) = divisibility k a 0\n | k < abs (b) = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n args <- getLine\n print $ divisibility (read (head (split ' ' args)) :: Int) \n (read (head $ tail (split ' ' args)) :: Int) \n (read (last (split ' ' args)) :: Int)\n\ndivisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,\n xs <- [a..b], mod xs k == 0]\n where l = 10^18\n s = -1*l\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | abs a < k && abs b < k && a /= 0 && b /= 0 = result\n | otherwise = 1 + result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | a == 0 && b == 0 = 1\n | combo1 == 0 && combo2 == 0 = result\n | k > abs (a) = divisibility k k b\n | k < abs (a) = divisibility k (a - combo1 + k) b\n | k > abs (b) = divisibility k a 0\n | k < abs (b) = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility :: Int -> Int -> Int -> Int\ndivisibility 1 a b = b - a + 1\ndivisibility k a b = length [x | x <- [a..b], mod x k == 0]"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility 1 a b = b - a + 1\ndivisibility k a b = length [x | x <- [a..b], mod x k == 0]"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | a == 0 && b == 0 = 0\n | combo1 == 0 && combo2 == 0 = result\n | k > abs (a) = divisibility k k b\n | k < abs (a) = divisibility k (a - combo1 + k) b\n | k > abs (b) = divisibility k a 0\n | k < abs (b) = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | abs a < k || abs b < k = result\n | otherwise = 1 + result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | k > abs (a) && k > abs (b) && a < 0 = 1\n | combo1 == 0 && combo2 == 0 = abs (result)\n | k > abs (a) && combo1 /= 0 = divisibility k k b\n | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b\n | k > abs (b) && combo2 /= 0 = divisibility k a 0\n | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k 0 0 = 0\ndivisibility k a b\n | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | combo1 == 0 && combo2 == 0 = result\n | k > abs (a) = divisibility k k b\n | k < abs (a) = divisibility k (a - combo1 + k) b\n | k > abs (b) = divisibility k a 0\n | k < abs (b) = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | mod (abs b) k /= 0 = result\n | otherwise = 1 + result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | (mod (abs a) k == 0) || mod (abs b) k == 0 = 1 + result\n | otherwise = result\n where l = 10^18\n result = div (b - a) k"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility2 arg1 arg2 arg3\n\ndivisibility2 k a b\n | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | otherwise = 1 + div (b - a) k\n where l = 10^18"}, {"source_code": "main = getLine >>= print.check.map read.words\n\ncheck [k, a, b] = b `div` k - a `div` k +\n if min a b `mod` k == 0 || b - a > abs (a + b)\n then 1 else 0"}, {"source_code": "main = getLine >>= print.check.map read.words\n\ncheck [k, a, b] = segment `div` k +\n if min a b `mod` k == 0 || segment > abs (a + b)\n then 1\n else 0\n where segment = b - a"}, {"source_code": "main = getLine >>= print.check.map read.words\n\ncheck [k, a, b] = b `quot` k - a `quot` k +\n if min a b `mod` k == 0 || b - a > abs (a + b)\n then 1 else 0"}, {"source_code": "main :: IO ()\nmain = do\n argsStr <- getLine\n let [arg1, arg2, arg3] = map read $ words argsStr\n print $ divisibility arg1 arg2 arg3\n\ndivisibility k a b\n | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0\n | combo1 == 0 && combo2 == 0 = result\n | k > abs (a) = divisibility k k b\n | k < abs (a) = divisibility k (a - combo1 + k) b\n | k > abs (b) = divisibility k a 0\n | k < abs (b) = divisibility k a (b - combo2)\n | otherwise = 0\n where combo1 = mod a k\n combo2 = mod b k\n result = 1 + div (b - a) k\n l = 10^18"}], "src_uid": "98de093d78f74273e0ac5c7886fb7a41"} {"source_code": "process :: Int -> Int\nprocess n\n | n < 10 = n\n | otherwise = n-m + process (d+m)\n where (d,m) = n `divMod` 10\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n print $ process n\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess n 0 = n\nprocess n a | a<10 = n+a\n |otherwise = process (n+ 10*(div a 10)) ((mod a 10) + (div a 10))\n\nonecase = do\n\t\ta<-read <$> getLine ::IO Integer\n\t\tprint $ process 0 a\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Monad\nimport Data.Ratio\nimport Data.Char\n\nsolve :: Int -> Int\nsolve n\n | n < 10 = n\n | otherwise = a + solve ((n - a) + (floor $ a % 10))\n where\n rest = n - a\n ds = map digitToInt $ show n\n l = length ds\n a :: Int\n a = (head ds) * 10 ^ (l - 1)\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n n <- readLn :: IO Int\n print $ solve n\n"}, {"source_code": "import Control.Monad\n\ngetInt = fmap read getLine :: IO Int\n\nmain = do\n t <- getInt\n replicateM_ t $ do\n n <- getInt\n print $ n `div` 9 * 10 + n `mod` 9 - if n `mod` 9 == 0 then 1 else 0\n"}], "negative_code": [{"source_code": "import Control.Monad\n\ngetInt = fmap read getLine :: IO Int\n\nmain = do\n t <- getInt\n replicateM_ t $ do\n n <- getInt\n if n > 9 then print $ n `div` 9 * 10 + n `mod` 9\n else print n\n"}, {"source_code": "import Control.Monad\n\ngetInt = fmap read getLine :: IO Int\n\nmain = do\n t <- getInt\n replicateM_ t $ do\n n <- getInt\n print $ n `div` 9 * 10 + n `mod` 9\n"}], "src_uid": "0beecbd62aa072a2f3aab542eeb56373"} {"source_code": "import Data.List (findIndex)\nimport Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ singleCase\nsingleCase = getLine >>= print . minToEven 0\n\nsearchPair :: (Ord a) => Int -> [a] -> Int -> [(Int, [a])]\nsearchPair m [] _ = []\nsearchPair m (x:xs) c\n | c >= m = []\n |otherwise = \n case findWithin x xs m c of\n Just (numBw, rest) -> (numBw, rest) : searchPair numBw xs (c+1)\n Nothing -> searchPair m xs (c+1)\n\nfindWithin :: (Ord a) => a -> [a] -> Int -> Int -> Maybe (Int, [a])\nfindWithin _ [] _ _ = Nothing\nfindWithin e (x:xs) m c | c >= m = Nothing\n | e == x = Just (c, xs)\n | otherwise = findWithin e xs m (c+1)\n\nminToEven :: Int -> String -> Int\nminToEven a [] = a\nminToEven a [x] = if x == '\\r' then a else a+1\nminToEven a (x:y:xs)\n | x == y = minToEven a xs\n | otherwise = case findIndex (x==) (y:xs) of\n Nothing -> minToEven (a+1) (y:xs)\n Just i -> case searchPair i (y:xs) 1 of\n [] -> minToEven (a+i) (drop i xs)\n pairs -> let (cost, rest) = minimum pairs in\n minToEven (a+cost) rest\n \n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Control.Monad.State\r\nimport qualified Data.Set as Set\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n str <- getLine\r\n let (s, r) = foldl (flip makeEven) (Set.empty, 0) str\r\n print (Set.size s + r)\r\n\r\nmakeEven :: Char -> (Set.Set Char, Int) -> (Set.Set Char, Int)\r\nmakeEven c (s, res) =\r\n if Set.member c s\r\n then (Set.empty, res + Set.size s - 1)\r\n else (Set.insert c s, res)\r\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.State\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n solvet\n\nsolvet :: IO ()\nsolvet = do\n str <- getLine\n let (s, r) = foldl (flip makeEven) (Set.empty, 0) str\n print (Set.size s + r)\n\nmakeEven :: Char -> (Set.Set Char, Int) -> (Set.Set Char, Int)\nmakeEven c (s, res) =\n if Set.member c s\n then (Set.empty, res + Set.size s - 1)\n else (Set.insert c s, res)\n"}, {"source_code": "import Control.Monad\r\nimport Control.Monad.State\r\nimport Data.Set ( empty, insert, member, size, Set )\r\n\r\n\r\n\r\n-- main = undefined\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n str <- getLine\r\n let (MyState s r) = foldl (\\s c -> execState (makeEven c) s) (MyState empty 0) str\r\n print (size s + r)\r\n\r\ndata MyState =\r\n MyState\r\n { msSet :: Set Char\r\n , msResult :: Int\r\n }\r\n\r\nmakeEven :: Char -> State MyState ()\r\nmakeEven c = do\r\n (MyState s res) <- get\r\n if c `member` s\r\n then do\r\n put $ MyState empty (res + size s - 1)\r\n else do\r\n let newS = c `insert` s\r\n put $ MyState newS res\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List (findIndex)\nimport Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ singleCase\nsingleCase = B.getLine >>= print . minToEven 0 . B.unpack\n\nsearchPair :: (Ord a) => Int -> [a] -> Int -> [(Int, [a])]\nsearchPair m [] _ = []\nsearchPair m (x:xs) c =\n case findWithin x xs m c of\n Just (numBw, rest) -> (numBw, rest) : searchPair m xs (c+1)\n Nothing -> searchPair m xs (c+1)\n\nfindWithin :: (Ord a) => a -> [a] -> Int -> Int -> Maybe (Int, [a])\nfindWithin _ [] _ _ = Nothing\nfindWithin e (x:xs) m c | c >= m = Nothing\n | e == x = Just (c, xs)\n | otherwise = findWithin e xs m (c+1)\n\nminToEven :: Int -> String -> Int\nminToEven a [] = a\nminToEven a [_] = a+1\nminToEven a (x:y:xs)\n | x == y = minToEven a xs\n | otherwise = case findIndex (x==) (y:xs) of\n Nothing -> minToEven (a+1) (y:xs)\n Just i -> case searchPair i (y:xs) 1 of\n [] -> minToEven (a+i) (drop i xs)\n pairs -> let (cost, rest) = minimum pairs in\n minToEven (a+cost) rest\n \n"}, {"source_code": "import Data.List (findIndex)\nimport Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ singleCase\nsingleCase = getLine >>= print . minToEven 0\n\nsearchPair :: (Ord a) => Int -> [a] -> Int -> [(Int, [a])]\nsearchPair m [] _ = []\nsearchPair m (x:xs) c =\n case findWithin x xs m c of\n Just (numBw, rest) -> (numBw, rest) : searchPair m xs (c+1)\n Nothing -> searchPair m xs (c+1)\n\nfindWithin :: (Ord a) => a -> [a] -> Int -> Int -> Maybe (Int, [a])\nfindWithin _ [] _ _ = Nothing\nfindWithin e (x:xs) m c | c >= m = Nothing\n | e == x = Just (c, xs)\n | otherwise = findWithin e xs m (c+1)\n\nminToEven :: Int -> String -> Int\nminToEven a [] = a\nminToEven a [_] = a+1\nminToEven a (x:y:xs)\n | x == y = minToEven a xs\n | otherwise = case findIndex (x==) (y:xs) of\n Nothing -> minToEven (a+1) (y:xs)\n Just i -> case searchPair i (y:xs) 0 of\n [] -> minToEven (a+i) (drop i xs)\n pairs -> let (cost, rest) = minimum pairs in\n minToEven (a+cost) rest\n \n"}], "src_uid": "6b92f09df1e35edc80cf1cbf8494b41e"} {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n-- }}}\n\npushStart s = let (ls, rs) = span (== '.') s in case rs of\n\t\"\" -> length ls\n\t('L':xs) -> push xs\n\t('R':xs) -> length ls + pushR xs\n\t_ -> error \"what?\"\n\npushR s = let (ls, rs) = span (== '.') s in case rs of\n\t\"\" -> 0\n\t('L':xs) -> (length ls `rem` 2) + push xs\n\t_ -> error \"what?\"\n\npush s = let (ls, rs) = span (== '.') s in case rs of\n\t\"\" -> length ls\n\t('R':xs) -> length ls + pushR xs\n\t_ -> error \"what?\"\n\nmain :: IO ()\nmain = do\n\tvoid getLine\n\tprint . pushStart =<< getLine\n", "positive_code": [{"source_code": "data LR = L | R | Vertical deriving Eq\n\nmain = do\n n <- getLine\n dominos <- getLine\n putStrLn.show $ countUp Vertical (0,0) dominos\n \ncountUp :: LR -> (Int,Int) -> String -> Int\ncountUp Vertical (amout,tmp) [] = amout+tmp\ncountUp L (amout,tmp) [] = amout+tmp\ncountUp R (amout,tmp) [] = amout\ncountUp Vertical (amout,tmp) ('.':xs) = countUp Vertical (amout,tmp+1) xs\ncountUp Vertical (amout,tmp) ('L':xs) = countUp L (amout,0) xs\ncountUp Vertical (amout,tmp) ('R':xs) = countUp R (amout+tmp,0) xs\n\ncountUp L (amout,tmp) ('.':xs) = countUp Vertical (amout+1,0) xs\ncountUp L (amout,tmp) ('R':xs) = countUp R (amout,0) xs\n\ncountUp R (amout,tmp) ('.':xs) = countUp R (amout,tmp+1) xs\ncountUp R (amout,tmp) ('L':xs) = countUp L (amout + if odd tmp then 1 else 0,0) xs"}, {"source_code": "main=interact$show.solve.parse.(!!1).lines\ndata A = L | R | N !Int\nparse :: String -> [A]\nparse ('R':cs) = R : parse cs\nparse ('L':cs) = L : parse cs\nparse cs@(_:_) | (xs, ys) <- span ('.'==) cs = N(length xs) : parse ys\nparse [] = []\n\nsolve :: [A] -> Int\nsolve xs = go 0 xs\n where\n go acc (R:N n:L:rest)\n | even n = go acc rest\n | otherwise = go (acc+1) rest\n go acc (R:N n:R:rest) = go acc (R:rest)\n go acc (R:L:rest) = go acc rest\n go acc (R:R:rest) = go acc (R:rest)\n go acc (L:rest) = go acc rest\n go acc (N n:R:rest) = go (acc+n) (R:rest)\n go acc (N n:L:rest) = go acc rest\n go acc [N n] = acc + n\n go acc [R, N n] = acc\n go acc [R] = acc\n go acc [] = acc\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = getLine >> getLine >>= print . solve\n\nsolve :: String -> Int\nsolve dominoes\n | all (== '.') dominoes = length dominoes\n | otherwise = solve $ func dominoes\n\nfunc :: String -> String\nfunc ('R':'.':'L':xs) = '.' : func xs\nfunc ('R':'.':xs) = 'R' : func xs\nfunc ('.':'L':xs) = 'L' : func xs\nfunc ('.':xs) = '.' : func xs\nfunc ( _ :xs) = func xs\nfunc xs = xs\n\n"}, {"source_code": "main = interact $ show . f . span (=='.') . head . tail . lines\nf (a, []) = length a\nf (a, b:bs)\n | b == 'L' = g bs\n | b == 'R' = length a + g (b:bs)\ng [] = 0\ng (x:xs)\n | x == 'R' && null (dropWhile (=='.') xs) = 0\n | x == 'R' = let (a, b) = span (=='.') xs in mod (length a) 2 + g (tail b)\n | x == '.' = let (a, b) = span (=='.') (x:xs) in length a + g b"}, {"source_code": "\nsolve :: [ (Char,Int) ] -> Int\nsolve [] = 0\nsolve (('L',b):rest) = solve' b rest\nsolve xs@(('R',a):rest) = solve' 0 xs\n\nsolve' :: Int -> [ (Char,Int) ] -> Int\nsolve' b' (('R',a):('L',b):rest) = a-b'-1 + (if even (b-a) then 1 else 0) + solve' b rest\nsolve' b' (('R',a):_) = a-b'-1\nsolve' b' [] = 0 -- never happens\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read :: IO Int\n doms <- getLine\n let pairs = filter (\\(d,a) -> d == 'L' || d == 'R') (zip doms [1..])\n print $ solve (pairs ++ [('R',n+1)])\n\n"}], "negative_code": [{"source_code": "data LR = L | R | Vertical deriving Eq\n\nmain = do\n n <- getLine\n dominos <- getLine\n putStrLn.show $ countUp Vertical (0,0) dominos\n \ncountUp :: LR -> (Int,Int) -> String -> Int\ncountUp _ (amout,tmp) [] = amout+tmp\ncountUp Vertical (amout,tmp) ('.':xs) = countUp Vertical (amout,tmp+1) xs\ncountUp Vertical (amout,tmp) ('L':xs) = countUp L (amout,0) xs\ncountUp Vertical (amout,tmp) ('R':xs) = countUp R (amout+tmp,0) xs\n\ncountUp L (amout,tmp) ('.':xs) = countUp Vertical (amout+1,0) xs\ncountUp L (amout,tmp) ('R':xs) = countUp R (amout,0) xs\n\ncountUp R (amout,tmp) ('.':xs) = countUp R (amout,tmp+1) xs\ncountUp R (amout,tmp) ('L':xs) = countUp L (amout + if odd tmp then 1 else 0,0) xs"}], "src_uid": "54c748dd983b6a0ea1af1153d08f1c01"} {"source_code": "-- 2019-11-24 23:20:33.466947138 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve n x a b = min (n-1) (abs (a-b)+x)\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,x,a,b] <- fmap (map read.words) getLine\n print $ solve n x a b\n"}, {"source_code": "-- 2019-11-20 20:26:12.553249308 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:16:55.732621122 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:19:05.325954742 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 14:25:18.674293017 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-19 11:27:55.861773021 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourIntsToInt\nparseFourIntsToInt :: String -> Maybe (Int, Int, Int, Int)\nparseFourIntsToInt i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:20:24.758961377 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 23:28:27.599374755 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 14:32:18.789734853 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> min (flip (-) 1 a) (b + abs (d - c))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/A\n\ndata Case = Case Int Int Int Int\n\n\ntoCase :: String -> Case\ntoCase inputLine = do\n let ints = map read $ words inputLine :: [Int]\n Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)\n\n\nsolve :: Case -> Int\nsolve (Case n x a b)\n | x == 0 = abs (a - b)\n | first == 1 && last == n = abs (a - b)\n | x >= 2 && first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)\n | first > 1 = solve $ Case n (x - 1) (first - 1) last\n | last < n = solve $ Case n (x - 1) first (last + 1)\n | otherwise = abs (a - b)\n where first = min a b\n last = max a b\n\n\n-- solve :: Case -> Int\n-- solve (Case n x a b)\n-- | (a == 1) && (b == n) = abs(a - b)\n-- | (a == n) && (b == 1) = abs(a - b)\n-- | otherwise = moveStudents $ Case n x a b\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/A\n\ndata Case = Case Int Int Int Int\n\n\ntoCase :: String -> Case\ntoCase inputLine = do\n let ints = map read $ words inputLine :: [Int]\n Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)\n\n\nmoveStudents :: Case -> Int\nmoveStudents (Case n x a b)\n | x == 0 = abs(a - b)\n | (min a b) > 1 = moveStudents $ Case n (x - 1) ((min a b) - 1) (max a b)\n | (max a b) < n = moveStudents $ Case n (x - 1) (min a b) ((max a b) + 1)\n | otherwise = abs(a - b)\n\n\nsolve :: Case -> Int\nsolve (Case n x a b)\n | (a == 1) && (b == n) = abs(a - b)\n | (a == n) && (b == 1) = abs(a - b)\n | otherwise = moveStudents $ Case n x a b\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/A\n\ndata Case = Case Int Int Int Int\n\n\ntoCase :: String -> Case\ntoCase inputLine = do\n let ints = map read $ words inputLine :: [Int]\n Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)\n\n\nsolve :: Case -> Int\nsolve (Case n x a b)\n | x == 0 = abs (a - b)\n | first == 1 && last == n = abs (a - b)\n | x >= 2 && first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)\n | first > 1 = solve $ Case n (x - 1) (first - 1) last\n | last < n = solve $ Case n (x - 1) first (last + 1)\n | otherwise = abs (a - b)\n where first = min a b\n last = max a b\n\n\nmain :: IO ()\nmain = interact $ unlines . -- Join elements with \\n. Ex: unlines [\"1\", \"2\", \"3\"] -> \"1\\n2\\n3\\n\"\n map (show . solve . toCase) . -- For each element do: 1) toCase, 2) solve, 3) show\n tail . -- Drop the first element (we dont need it)\n lines -- Read lines from stdin\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/A\n\ndata Case = Case Int Int Int Int\n\n\ntoCase :: String -> Case\ntoCase inputLine = do\n let ints = map read $ words inputLine :: [Int]\n Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)\n\n\nsolve :: Case -> Int\nsolve (Case n x a b)\n | x == 0 = abs(a - b)\n | (min a b) > 1 = solve $ Case n (x - 1) ((min a b) - 1) (max a b)\n | (max a b) < n = solve $ Case n (x - 1) (min a b) ((max a b) + 1)\n | otherwise = abs(a - b)\n\n\n-- solve :: Case -> Int\n-- solve (Case n x a b)\n-- | (a == 1) && (b == n) = abs(a - b)\n-- | (a == n) && (b == 1) = abs(a - b)\n-- | otherwise = moveStudents $ Case n x a b\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/A\n\ndata Case = Case Int Int Int Int\n\n\ntoCase :: String -> Case\ntoCase inputLine = do\n let ints = map read $ words inputLine :: [Int]\n Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)\n\n\nsolve :: Case -> Int\nsolve (Case n x a b)\n | x == 0 = abs(a - b)\n | x >= 2 && first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)\n | first > 1 = solve $ Case n (x - 1) (first - 1) last\n | last < n = solve $ Case n (x - 1) first (last + 1)\n | otherwise = abs(a - b)\n where first = min a b\n last = max a b\n\n\n-- solve :: Case -> Int\n-- solve (Case n x a b)\n-- | (a == 1) && (b == n) = abs(a - b)\n-- | (a == n) && (b == 1) = abs(a - b)\n-- | otherwise = moveStudents $ Case n x a b\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "module Main where \n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- (read::String->Int) <$> getLine\n\n replicateM_ t $ do \n [n, x, a, b] <- fmap (read::String->Int) . words <$> getLine\n let mi = min a b\n let ma = max a b\n let dma = n - ma\n let dmi = mi - 1\n let d = dma + dmi\n let s = min d x\n print $ abs (a-b) + s\n return ()\n return ()"}, {"source_code": "main = interact $ unlines . map show . solveTests . map read . words\n\nsolveTests (t:ls) = solveTests' t ls\n\nsolveTests' 0 _ = []\nsolveTests' t (n:x:a:b:ls) = (min (n-1) (abs (a-b) + x)) : solveTests' (t-1) ls\nsolveTests' _ _ = []\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nonecase= do\n\t\t[n,x,a,b]<-map read <$> words <$> getLine :: IO [Int]\n\t\tprint $ min (n-1) (x + (abs (a-b)))\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "--ghc 7.10\n\nmaxDistance :: (Integral a) => (a,a,a,a) -> a\nmaxDistance (n,x,a,b) = min (n-1) (x + abs (a-b))\n\nreadLine :: String -> (Int,Int,Int,Int)\nreadLine str = (n,x,a,b)\n where [n,x,a,b] = map read . words $ str\n\nmain = do\n tStr <- getLine\n contents <- getContents\n let xs = map readLine . lines $ contents\n sequence . map print . map maxDistance $ xs"}], "negative_code": [{"source_code": "-- 2019-11-20 20:16:06.271115345 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (d + (b + a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 14:22:25.070625994 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (d + (b + a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:13:03.499329669 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (d + (b + a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 23:28:44.008450939 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\_ _ c _ -> flip (-) 1 c\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 23:25:00.269823993 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (d + (b + a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:17:13.069561071 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\_ _ c _ -> flip (-) 1 c\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-25 10:38:41.233162656 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (b - (d - a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-19 11:24:32.055120469 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourIntsToInt\nparseFourIntsToInt :: String -> Maybe (Int, Int, Int, Int)\nparseFourIntsToInt i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> iF (d >= a) b (flip (-) 1 c)\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 14:25:37.164105911 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\_ _ c _ -> flip (-) 1 c\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 23:18:51.596198974 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (d + (b + a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 23:21:30.976993029 UTC\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\_ _ c _ -> flip (-) 1 c\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 14:33:40.310577348 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> nat_para d b (\\_ _ -> nat_para c a (\\g _ -> g))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:19:22.548650727 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\a b c d -> flip (-) 1 (min c (d + (b + a)))\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 20:22:30.7083905 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b, c, d) = show $ f a b c d\nparser :: String -> (Int, Int, Int, Int)\nparser = fromJust . parseFourInts\nparseFourInts :: String -> Maybe (Int, Int, Int, Int)\nparseFourInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 4) Nothing;\n let {[a, b, c, d] = ns};\n return (a, b, c, d)}\nsolve = \\_ _ c _ -> flip (-) 1 c\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/A\n\ndata Case = Case Int Int Int Int\n\n\ntoCase :: String -> Case\ntoCase inputLine = do\n let ints = map read $ words inputLine :: [Int]\n Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)\n\n\nsolve :: Case -> Int\nsolve (Case n x a b)\n | x == 0 = abs(a - b)\n | first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)\n | first > 1 = solve $ Case n (x - 1) (first - 1) last\n | last < n = solve $ Case n (x - 1) first (last + 1)\n | otherwise = abs(a - b)\n where first = min a b\n last = max a b\n\n\n-- solve :: Case -> Int\n-- solve (Case n x a b)\n-- | (a == 1) && (b == n) = abs(a - b)\n-- | (a == n) && (b == 1) = abs(a - b)\n-- | otherwise = moveStudents $ Case n x a b\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}], "src_uid": "1fd2619aabf4557093a59da804fd0e7b"} {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> Int\nsolve xs\n | null pruned = 0\n | aligns == 0 = 1\n | otherwise = 2\n where\n pruned = dropWhileEnd id $ dropWhile id $ zipWith (==) [1..] xs\n aligns = length $ filter id $ pruned\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)\n mapM_ (print . solve) tests\n", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve xs\n | null pruned = 0\n | aligns == 0 = 1\n | otherwise = 2\n where\n pruned = dropWhile same $ reverse $ dropWhile same $ zip [1..] xs\n aligns = length $ filter same $ pruned\n same (a, b) = a == b\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)\n mapM_ (print . solve) tests\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : perm : rest) = (itoline . solve . linetois) perm : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\nsolve :: [Int] -> Int\nsolve xs | null $ mispos xs = 0\n | contiguous $ mispos xs = 1\n | otherwise = 2 where\n mispos xs = [a | (a,x) <- zip [1..] xs, a /= x ]\n contiguous as = all (==1) $ zipWith (-) ((drop 1) as) as\n\n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n print $\n if as == sort as\n then 0\n else\n if or $ dropWhile (== True) $ dropWhileEnd (== True) $ zipWith (==) [1 ..] as\n then 2\n else 1\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> Int\nsolve xs\n | null pruned = 0\n | null aligns = 1\n | otherwise = 2\n where\n pruned = dropWhileEnd id $ dropWhile id $ zipWith (==) [1..] xs\n aligns = filter id $ pruned\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)\n mapM_ (print . solve) tests\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : p : rest) = (itoline . solve . linetois) p : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\nsolve :: [Int] -> Int\nsolve xs | null $ mispos xs = 0\n | contiguous $ mispos xs = 1\n | otherwise = 2 where\n mispos as = [b | (a,b) <- zip [1..] as, a /= b ]\n contiguous as = all (==1) $ zipWith (-) as ((drop 1) as)\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : p : rest) = (itoline . solve . linetois) p : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\nsolve :: [Int] -> Int\nsolve xs | null $ mispos xs = 0\n | contiguous $ mispos xs = 1\n | otherwise = 2 where\n mispos xs = [a | (a,x) <- zip [1..] xs, a /= x ]\n contiguous as = all (==1) $ zipWith (-) as ((drop 1) as)\n"}, {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve xs\n | aligns == length xs = 0\n | aligns == 0 = 1\n | otherwise = 2\n where\n aligns = length $ filter same $ dropWhile same $ reverse $ dropWhile same $ zip [1..] xs\n same (a, b) = a == b\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)\n mapM_ (print . solve) tests\n"}, {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve xs\n | aligns == length xs = 0\n | aligns == 0 = 1\n | otherwise = 2\n where\n aligns = length $ filter (\\(a, b) -> a == b) $ zip [1..] xs\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)\n mapM_ (print . solve) tests\n"}], "src_uid": "a98f67141b341152fcf20d803cbd5409"} {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (n, x) <- liftM2 (,) get get\n cs <- gets\n putln $ f2 cs n x\n\nf2 :: String -> Int -> Int64 -> Int64\nf2 cs n x = let (s, ks) = foldl (\\(sum, seq) i -> if i == '0' then (sum + 1, seq DSeq.|> (sum + 1)) else (sum - 1, seq DSeq.|> (sum - 1))) (0, DSeq.Empty DSeq.|> 0) cs in\n let kl = toList $ DSeq.take n ks\n in\n if s == 0 then\n let count = foldl (\\sum i -> if i == x then sum + 1 else sum) 0 kl in\n if count /= 0 then -1\n else 0\n else\n let count = foldl (\\sum i -> if (mod (i - x) s) == 0 && ((x - i == 0) || ((x - i) > 0 && s > 0) || ((x - i) < 0 && s < 0)) then sum + 1 else sum) 0 kl in\n count\n", "positive_code": [{"source_code": "readInt :: IO Int\nreadInt = do\n t <- getLine\n return $ read t\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nnumWith :: (z -> Bool) -> [z] -> Int\nnumWith t s = foldr (\\a -> \\b -> if t a then b+1 else b) 0 s\n\nbalanceList :: String -> [Int]\nbalanceList s = foldl (\\a -> \\b -> (if b == '1' then (head a) - 1 else (head a) + 1) : a) [0] s\n\nvalid :: Int -> Int -> Bool\nvalid d b = not (d < 0 && b > 0 || d > 0 && b < 0)\n\ncompute :: String -> Int -> String\ncompute s x \n | (head balance == 0) = if x == 0 || any (==x) balance then \"-1\" else \"0\"\n | otherwise = show $ numWith (\\c -> valid (x - c) (head balance) && (x - c) `mod` (head balance) == 0) $ tail balance\n where balance = balanceList s\n\nsolve :: Int -> IO ()\nsolve 0 = return ()\nsolve t = do\n [_,x] <- readInts\n s <- getLine\n putStrLn $ compute s x\n solve (t-1)\n\nmain :: IO ()\nmain = do\n t <- readInt\n solve t\n"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (n, x) <- liftM2 (,) get get\n cs <- gets\n putln $ f2 cs n x\n\nf2 :: String -> Int -> Int64 -> Int64\nf2 cs n x = let (s, ks) = foldl (\\(sum, seq) i -> if i == '0' then (sum + 1, seq DSeq.|> (sum + 1)) else (sum - 1, seq DSeq.|> (sum - 1))) (0, DSeq.Empty DSeq.|> 0) cs in\n let kl = toList $ DSeq.take n ks\n in\n if s == 0 then\n let count = foldl (\\sum i -> if i == x then sum + 1 else sum) 0 kl in\n if count /= 0 then -1\n else 0\n else\n let count = foldl (\\sum i -> if (mod (i - x) s) == 0 && ((x - i == 0) || ((x - i) > 0 && s > 0) || ((x - i) < 0 && s < 0)) then sum + 1 else sum) 0 kl in\n count\n"}], "negative_code": [{"source_code": "readInt :: IO Int\nreadInt = do\n t <- getLine\n return $ read t\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nnumWith :: (z -> Bool) -> [z] -> Int\nnumWith t s = foldr (\\a -> \\b -> if t a then b+1 else b) 0 s\n\nbalanceList :: String -> [Int]\nbalanceList s = foldl (\\a -> \\b -> (if b == '1' then (head a) - 1 else (head a) + 1) : a) [0] s\n\ncompute :: String -> Int -> String\ncompute s x \n | (head balance == 0) = if x == 0 || any (==x) balance then \"-1\" else \"0\"\n | otherwise = show $ numWith (\\c -> (x - c) * (head balance) >= 0 && (x - c) `mod` (head balance) == 0) $ tail balance\n where balance = balanceList s\n\nsolve :: Int -> IO ()\nsolve 0 = return ()\nsolve t = do\n [_,x] <- readInts\n s <- getLine\n putStrLn $ compute s x\n solve (t-1)\n\nmain :: IO ()\nmain = do\n t <- readInt\n solve t\n"}, {"source_code": "readInt :: IO Int\nreadInt = do\n t <- getLine\n return $ read t\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nnumWith :: (z -> Bool) -> [z] -> Int\nnumWith t s = foldr (\\a -> \\b -> if t a then b+1 else b) 0 s\n\nbalanceList :: String -> [Int]\nbalanceList s = foldl (\\a -> \\b -> (if b == '1' then (head a) - 1 else (head a) + 1) : a) [0] s\n\ncompute :: String -> Int -> String\ncompute s x \n | (head balance == 0) = if x == 0 || any (==x) balance then \"-1\" else \"0\"\n | otherwise = show $ numWith (\\c -> (x - c) * (head balance) >= 0 && abs (x - c) `mod` (abs (head balance)) == 0) $ tail balance\n where balance = balanceList s\n\nsolve :: Int -> IO ()\nsolve 0 = return ()\nsolve t = do\n [_,x] <- readInts\n s <- getLine\n putStrLn $ compute s x\n solve (t-1)\n\nmain :: IO ()\nmain = do\n t <- readInt\n solve t\n"}], "src_uid": "389be6455476db86a8a5d9d5343ee35a"} {"source_code": "getA = fmap (map read . words) getLine\nmain = do\n\t[n, l] <- getA\n\ta <- getA\n\tputStrLn $ show $ maximum $ 0:[i * sum (map (`div` i) a) | i <- [l .. maximum a]]\n", "positive_code": [{"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.map toInt.tail.words\n\nfunc::[Int]->String\nfunc (a:xs) = toString$solve a (sort xs)\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nmaximum' [] = 0\nmaximum' a = maximum a\n\nsolve::Int->[Int]->Int\nsolve a b= maximum'$map (solve' b) [a..b']\n where\n b' = last b\n\nsolve' b a = sum$map (f' a) b\n\nf'::Int->Int->Int\nf' a b = c*a\n where\n c = b `div` a"}, {"source_code": "main = interact f\nf input = output where\n [[n,l],a] = map (map (read::String->Int)) $ map words $ lines input\n output = show ans\n k d = sum [div x d|x<-a]\n ans = foldl max 0 [k d * d|d<-[l..(foldl1 max a)]]"}, {"source_code": "import Data.Char (ord)\n\nsolveFor v n x = (*) x $ sum $ map (`div` x) v\n\nsolve n l v maxv = maximum $ (:) 0 $ map (solveFor v n) $ [l..maxv]\n\nmain = do\n [n, l] <- fmap ((map (\\x -> read x::Int)) . words) getLine\n v <- fmap ((map (\\x -> read x::Int)) . words) getLine\n print $ solve n l v $ maximum v\n"}, {"source_code": "main=interact((\\(n:l:a)->show$maximum$map(\\d->d*(sum$map(`div`d)a))[l..100]).map(read::String->Int).words)"}, {"source_code": "main=interact((\\(n:l:a)->show$maximum$map(\\d->d*(sum$map(`div`d)a))[l..100]).map(read::String->Int).words)"}, {"source_code": "\nsolve :: Int -> [Int] -> Int\nsolve l xs = maximum $ 0 : [k * d k | k <- [l..maximum xs]]\n where\n d k = sum $ map (flip div k) xs\n\nmain :: IO ()\nmain = do\n [n, l] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n print $ solve l xs\n"}, {"source_code": "solve (l:xs) = maximum $ map getSquare [l..100]\n where getSquare l = l * foldl (\\ans x -> ans + x `div` l) 0 xs\nmain = interact $ show.solve.map read.tail.words"}, {"source_code": "f (l:p) = maximum $ map s [l..100]\n where s l = l * foldl (\\a x -> a + x `div` l) 0 p\nmain = interact $ show.f.map read.tail.words"}], "negative_code": [{"source_code": "\nsolve (l:xs) = let q = max l $ minimum $ 101:filter (>=l) xs\n in q * foldl (\\ans x -> ans + x `div` q) 0 xs\nmain = interact $ show.solve.map read.tail.words"}, {"source_code": "\nsolve (l:xs) = let q = max l $ minimum xs\n in q * foldl (\\ans x -> ans + x `div` q) 0 xs\nmain = interact $ show.solve.map read.tail.words"}, {"source_code": "\nsolve (l:xs) = l * foldl (\\ans x -> ans + x `div` l) 0 xs\nmain = interact $ show.solve.map read.tail.words"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.map toInt.tail.words\n\nfunc::[Int]->String\nfunc (a:xs) = toString$solve a xs\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::Int->[Int]->Int\nsolve a = sum.map (f' a)\n\nf'::Int->Int->Int\nf' a b = c*a\n where\n c = b `div` a"}], "src_uid": "991516fa6f3ed5a71c547a3a50ea1a2b"} {"source_code": "\nimport Control.Monad\n\nrth :: Int -> Int -> Int -> (Int,Int)\nrth n m r = \n if t >= m then (i0+1+1, 2*m-t) else (i0+1,t+1) \n where (q,t) = divMod (r-1) (2*m)\n i0 = 2*q\n\nshowPair (i,j) = show i ++ \" \" ++ show j\n\nshowPairs pairs = show (length pairs) ++ \" \" ++ (unwords (map showPair pairs))\n\nmain = do\n (n:m:tubes:_) <- fmap (map read . words) getLine\n forM_ [1..tubes-1] $ \\k -> do\n putStrLn $ showPairs $ map (rth n m) [2*k-1, 2*k]\n let cnt = n*m-2*(tubes-1)\n putStr $ show cnt ++ \" \"\n forM_ [2*tubes-1..n*m] $ \\r -> do\n putStr $ showPair (rth n m r) ++ \" \"\n putStrLn \"\"\n\n", "positive_code": [{"source_code": "main=interact$unlines.map(unwords.map show.addLen2).solve.map read.words\n\naddLen2 :: [Int] -> [Int]\naddLen2 xs = length xs`div`2 : xs\n\nsolve :: [Int] -> [[Int]]\nsolve [n,m,k] = slices 4 xs ++ [ys]\n where\n (xs,ys) = splitAt (4*(k-1)) cells\n cells = do\n x <- [1..n]\n if odd x then [1..m]>>= \\y->[x,y]\n else [m,m-1..1]>>= \\y->[x,y]\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n interact $ output . solve . input\n\nsolve :: (Int, Int, Int) -> [[(Int, Int)]]\nsolve (n, m, k) = slice k $ zigZag n m\n\nslice :: Int -> [a] -> [[a]]\nslice 1 xs = [xs]\nslice k (x:y:xs) = [x, y] : slice (k - 1) xs\n\nzigZag :: Int -> Int -> [(Int, Int)]\nzigZag n m =\n [ (r, c)\n | r <- [1..n],\n c <- (if odd r then id else reverse) [1..m]\n ]\n\ninput :: String -> (Int, Int, Int)\ninput str = (n, m, k)\n where\n n = read nS\n m = read mS\n k = read kS\n [nS, mS, kS] = words str\n\noutput :: [[(Int, Int)]] -> String\noutput tubes =\n unlines\n [ unwords $ show (length tube) :\n [ show x ++ \" \" ++ show y\n | (x, y) <- tube\n ]\n | tube <- tubes\n ]\n"}, {"source_code": "import Data.List\n\nmain = interact $ unlines . map (unwords . map show) . getAns . map read . words\n\ngetAns :: [Int] -> [[Int]]\ngetAns (n:m:k:_) = splitPath k $ getPath n m 1\n\ngetPath :: Int -> Int -> Int -> [Int]\ngetPath n m x = \n\tlet tys = if even x then [m,m-1..1] else [1..m]\n\t txys = foldr (\\a ax -> x:a:ax) [] tys\n\tin if (x > n) then [] else txys ++ getPath n m (x + 1)\n\nsplitPath :: Int -> [Int] -> [[Int]]\nsplitPath _ [] = []\nsplitPath 1 xs = ((div (length xs) 2) : xs) : []\nsplitPath k xs = \n\tlet sp = splitAt 4 xs\n\t ft = fst sp\n\t st = snd sp\n\tin (2 : ft) : splitPath (k - 1) st\n\n\n\n\n\n\n\n"}, {"source_code": "import Data.List\n\nmain = interact $ unlines . map (unwords . map show) . getAns . map read . words\n\ngetAns :: [Int] -> [[Int]]\ngetAns (n:m:k:_) = splitPath k $ getPath n m 1 1\n\ngetPath :: Int -> Int -> Int -> Int -> [Int]\ngetPath n m x y = \n\tlet ty = if x `mod` 2 == 0 then y - 1 else y + 1\n\t nx = if ty > m || ty <= 0 then x + 1 else x\n\t ny = if ty <= m && ty > 0 then ty else y\n\tin if (x > n) then [] else x:y:getPath n m nx ny\n\nsplitPath :: Int -> [Int] -> [[Int]]\nsplitPath _ [] = []\nsplitPath 1 xs = ((div (length xs) 2) : xs) : []\nsplitPath k xs = \n\tlet sp = splitAt 4 xs\n\t ft = fst sp\n\t st = snd sp\n\tin (2 : ft) : splitPath (k - 1) st\n\n\n\n\n\n\n\n"}, {"source_code": "\nmodule Main where\n\npinput:: String -> [Int]\npinput = map read . words\n\npoutput:: [[(Int, Int)]] -> String\npoutput o = unlines (map poneoutput o) where\n prest ((x, y):xs) = x : y : prest xs\n prest [] = []\n poneoutput t = unwords $ map show (length t : prest t)\n\n-- Solution starts here\nsnake:: Int -> Int -> [(Int, Int)]\nsnake nrow ncol = loop 1 1 1 where\n loop row col dir\n | row == (nrow + 1) = []\n | col == ncol && dir == 1 = (row, col) : loop (row + 1) col (-1)\n | col == 1 && dir == -1 = (row, col) : loop (row + 1) col 1\n | otherwise = (row, col) : loop row (col + dir) dir\n\nsolve:: [Int] -> [[(Int, Int)]]\nsolve [nrow, ncol, tubes] = slice (snake nrow ncol) (nrow * ncol) where\n step = (nrow * ncol) `div` tubes\n slice [] _ = []\n slice xs m = if m == step + (nrow * ncol) `mod` tubes \n then take (length xs) xs : slice [] 0\n else take step xs : slice (drop step xs) (m - step)\nsolve _ = undefined\n\nmain :: IO ()\nmain = do\n l <- getLine\n putStrLn $ poutput $ solve $ pinput l\n\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = interact $ unlines . map (unwords . map show) . getAns . map read . words\n\ngetAns :: [Int] -> [[Int]]\ngetAns (n:m:k:_) = splitPath (n * m `div` k * 2) $ getPath n m 1 1\n\ngetPath :: Int -> Int -> Int -> Int -> [Int]\ngetPath n m x y = \n\tlet ty = if x `mod` 2 == 0 then y - 1 else y + 1\n\t nx = if ty > m || ty <= 0 then x + 1 else x\n\t ny = if ty <= m && ty > 0 then ty else y\n\tin if (x > n) then [] else x:y:getPath n m nx ny\n\nsplitPath :: Int -> [Int] -> [[Int]]\nsplitPath _ [] = []\nsplitPath k xs = \n\tlet sp = splitAt k xs\n\t ft = fst sp\n\t st = snd sp\n\tin ((div (length ft) 2) : ft) : (splitPath k st)\n\n\n\n\n\n\n\n"}, {"source_code": "\nimport Control.Monad\n\nrth :: Int -> Int -> Int -> (Int,Int)\nrth n m r = \n if t >= m then (i0+1+1, 2*m-t) else (i0+1,t+1) \n where (q,t) = divMod (r-1) (2*m)\n i0 = 2*q\n\nshowPair (i,j) = show i ++ \" \" ++ show j\n\nmain = do\n (n:m:tubes:_) <- fmap (map read . words) getLine\n forM_ [1..tubes-1] $ \\k -> do\n putStrLn $ \"1 \" ++ showPair (rth n m k)\n let cnt = n*m-tubes+1\n putStr $ show cnt ++ \" \"\n forM_ [tubes..n*m] $ \\r -> do\n putStr $ showPair (rth n m r) ++ \" \"\n putStrLn \"\"\n\n"}, {"source_code": "\nmodule Main where\n\npinput:: String -> [Int]\npinput = map read . words\n\npoutput:: [[(Int, Int)]] -> String\npoutput o = unlines (map poneoutput o) where\n prest ((x, y):xs) = x : y : prest xs\n prest [] = []\n poneoutput t = unwords $ map show (length t : prest t)\n\n-- Solution starts here\nsnake:: Int -> Int -> [(Int, Int)]\nsnake nrow ncol = loop 1 1 1 where\n loop row col dir\n | row == (nrow + 1) = []\n | col == ncol && dir == 1 = (row, col) : loop (row + 1) col (-1)\n | col == 1 && dir == -1 = (row, col) : loop (row + 1) col 1\n | otherwise = (row, col) : loop row (col + dir) dir\n\nsolve:: [Int] -> [[(Int, Int)]]\nsolve [nrow, ncol, tubes] = slice (snake nrow ncol) where\n step = (nrow * ncol) `div` tubes\n slice [] = []\n slice xs = take step xs : slice (drop step xs)\nsolve _ = undefined\n\nmain :: IO ()\nmain = do\n l <- getLine\n putStrLn $ poutput $ solve $ pinput l\n\n"}], "src_uid": "779e73c2f5eba950a20e6af9b53a643a"} {"source_code": "main :: IO ()\nmain = interact $ solve . map read . words\n\nsolve :: [Integer] -> String\nsolve (p : q : _ : as)\n | p * r == q * s = \"YES\"\n | otherwise = \"NO\"\n where\n (r, s) = foldr f (0, 1) as\n f a (n, d) = (d, a * d + n)\n", "positive_code": [{"source_code": "\nimport Data.Ratio ((%))\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: (Integer, Integer) -> [Integer] -> Bool\nsolve (a, b) xs = a % b == solve' xs\n where\n solve' [x] = x % 1\n solve' (x:xs) = x % 1 + 1 / solve' xs\n\nmain :: IO ()\nmain = do\n [a, b] <- reads\n getLine\n xs <- reads\n if solve (a, b) xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Ord\nimport Data.Ratio\n\nreadInteger :: B.ByteString -> Integer\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\n\nmain :: IO ()\nmain = do\n [p,q] <- map read.words <$> getLine\n _ <- getLine\n xs <- map readInteger.B.words <$> B.getLine\n if (p%q) == calc xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncalc :: [Integer] -> Ratio Integer\ncalc [x] = x%1\ncalc (x:xs) = (x%1)+ (1 / (calc xs))\n"}, {"source_code": "isEqual :: Integer -> Integer -> [Integer] -> Bool\nisEqual p q [] = q == 0\nisEqual p q (x : xs) = if q /= 0 then div p q >= x && isEqual q (p - q * x) xs else False\n\nhandle :: [[String]] -> String\nhandle [[sp, sq], _, sa] = if isEqual (read sp) (read sq) (map read sa) then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = interact $ handle . map words . lines\n"}, {"source_code": "isEqual :: Integer -> Integer -> [Integer] -> Bool\nisEqual p q [] = q == 0\nisEqual _ 0 _ = False\nisEqual p q (x : xs) = div p q >= x && isEqual q (p - q * x) xs\n\nhandle :: [[String]] -> String\nhandle [[sp, sq], _, sa] = if isEqual (read sp) (read sq) (map read sa) then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = interact $ handle . map words . lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Ord\nimport Data.Ratio\n\nreadInteger :: B.ByteString -> Integer\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\n\nmain :: IO ()\nmain = do\n [p,q] <- map read.words <$> getLine\n _ <- getLine\n xs <- map readInteger.B.words <$> B.getLine\n if (p%q) == calc xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncalc :: [Integer] -> Ratio Integer\ncalc [x] = x%1\ncalc (x:xs) = (x%1)+ (1 / (calc xs))\n"}], "negative_code": [{"source_code": "isEqual :: Int -> Int -> [Int] -> Bool\nisEqual p q [] = q == 0\nisEqual p q (x : xs) = div p q >= x && isEqual q (p - q * x) xs\n\nhandle :: [[String]] -> String\nhandle [[sp, sq], _, sa] = if isEqual (read sp) (read sq) (map read sa) then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = interact $ handle . map words . lines\n"}], "src_uid": "447ebe088a0a60a7a44a3fc76056bc65"} {"source_code": "import Data.List\n\nmain = do\n [n, p, q] <- (map read . words) `fmap` getLine\n s <- getLine\n\n let vs = [(a, b) | a <- [0..100], b <- [0..100], a*p + b*q == n]\n\n if null vs\n then print $ -1\n else do\n let\n (a, b) = head vs\n ss = slice p (take (p*a) s) ++ slice q (drop (p*a) s)\n where\n slice n = unfoldr (\\s -> if null s then Nothing else Just (take n s, drop n s))\n print $ length ss\n putStr $ unlines ss\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List.Split\n\nsolve :: Int -> Int -> Int -> String -> [String]\nsolve n p q x\n | null matches = [\"-1\"]\n | otherwise = show (p_uses + q_uses):chunksOf p p_str ++ chunksOf q q_str\n where\n matches = [(p_uses, q_uses) | p_uses <- [0..n], q_uses <- [0..n], p_uses * p + q_uses * q == n]\n (p_uses, q_uses) = head matches\n (p_str, q_str) = splitAt (p_uses * p) x\n\nmain = do\n [n, p, q] <- map read . words <$> getLine\n x <- getLine\n let soln = solve n p q x\n putStrLn $ unlines $ soln\n"}, {"source_code": "import Control.Applicative\nimport Data.List.Split\n\nmain = do\n [n, p, q] <- map read . words <$> getLine\n s <- getLine\n putStr $ unlines $ solve n p q s\n \nsolve n p q s = if null ls then [\"-1\"]\n else show (m `div` p + (n - m) `div` q) : chunksOf p (take m s) ++ chunksOf q (drop m s) \n where ls = [m | m <-[0..n], m `mod` p == 0, (n - m) `mod` q == 0 ]\n m = if null ls then -1 else head ls\n"}, {"source_code": "import Data.List\n\nread_int :: String -> Int\nread_int = read\n\nsolve :: Int -> Int -> String -> Maybe [String]\nsolve p q str\n | len `mod`g /= 0 = Nothing\n | len == p = Just [str]\n | len == q = Just [str]\n | len < p && len < q = Nothing\n | otherwise = case (solve p q psuff, solve p q qsuff) of\n (Just ss, _) -> Just (ppref:ss)\n (_, Just ss) -> Just (qpref:ss)\n _ -> Nothing\n where len = length str\n (ppref, psuff) = splitAt p str\n (qpref, qsuff) = splitAt q str\n g = gcd p q\n\nformatout :: Maybe [String] -> String\nformatout Nothing = \"-1\"\nformatout (Just ss) = intercalate \"\\n\" ((show $ length ss):ss)\n\nformatin :: [String] -> Maybe [String]\nformatin (_:x:y:z:_) = solve (read_int x) (read_int y) z\n\nmain = do\n input <- getContents\n putStrLn $ formatout . formatin . words $ input\n"}, {"source_code": "\nsplitS s n p q \n | n == 0 = ([], True)\n | n < p = ([], False)\n | n `mod` p == 0 = ((take p s) : spLeft, passedP)\n | n < q = ([], False)\n | otherwise = ((take q s) : sqLeft, passedQ)\n where \n (spLeft, passedP) = splitS (drop p s) (n-p) p q\n (sqLeft, passedQ) = splitS (drop q s) (n-q) p q\n\nmain = do\n line <- getLine\n let [n, p, q] = map read $ words line \n let (pP, qQ) = (min p q, max p q)\n s <- getLine\n let (result, possible) = splitS s n pP qQ\n if possible then do\n putStrLn $ show $ length result\n putStr $ unlines result\n else do\n putStrLn \"-1\"\n"}, {"source_code": "{-- 612.A. The Text Splitting --}\nmain = do\n firstLine <- getLine\n word <- getLine\n case splitter (words firstLine) word of\n Just set -> do\n putStrLn (show $ length set)\n mapM_ putStrLn set\n Nothing ->\n putStrLn \"-1\"\n\nsplitter :: [String] -> String -> Maybe [String]\nsplitter [] _ = Nothing\nsplitter _ [] = Nothing\nsplitter xs str = case partition str len p q of\n (_, -1) -> Nothing\n (set, _) -> Just set\n where\n len = read (xs !! 0) :: Int\n p = read (xs !! 1) :: Int\n q = read (xs !! 2) :: Int\n\npartition :: (Num a) => String -> Int -> Int -> Int -> ([String], a)\npartition str len p q\n | len < 0 = ([], -1)\n | len == 0 = ([], 0)\n | otherwise = ((take val str) : next, num)\n where\n (next, num) = if modPass\n then partition (drop val str) (len - val) val val\n else partition (drop val str) (len - val) p q\n modPass = len `mod` p == 0 || len `mod` q == 0\n val\n | len `mod` p == 0 = p\n | len `mod` q == 0 = q\n | p < q = p\n | otherwise = q"}, {"source_code": "\nmain = interact $\n sol .\n (\\[n, p, q, s] -> (read n, read p, read q, s)) .\n words\n\nsol (n, p, q, s) = case posb of\n [] -> \"-1\"\n (pl:_) -> let ans = slice s $ replicate (pl `div` p) p ++ replicate ((n-pl) `div` q) q\n in unlines $ (show $ length ans):ans\n where\n posb = filter (\\pl -> (n-pl) `mod` q == 0) . takeWhile (<= n) $ map (*p) [0..]\n slice _ [] = []\n slice str (x:xs) = (take x str):(slice (drop x str) xs)\n\n\n\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nmain = do\n (n : p : q : _) <- map read . words <$> getLine\n s <- getLine\n putStrLn $ case listToMaybe [i | i <- [0, p .. n], (n - i) `mod` q == 0] of\n Nothing -> \"-1\" \n Just i -> let (s1, s2) = splitAt i s in decorate $ (splitEvery p s1) ++ (splitEvery q s2)\n where\n decorate l = unlines $ (show $ length l) : l\n splitEvery x = takeWhile (not . null) . unfoldr (Just . splitAt x)\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n [n, p, q] <- (map read . words) `fmap` getLine\n s <- getLine\n\n let vs = [(a, b) | a <- [0..100], b <- [0..100], a*p + b*q == n]\n\n if null vs\n then print $ -1\n else do\n print 2\n let\n (a, b) = head vs\n ss = slice p (take (p*a) s) ++ slice q (drop (p*a) s)\n where\n slice n = unfoldr (\\s -> if null s then Nothing else Just (take n s, drop n s))\n putStr $ unlines ss\n"}], "src_uid": "c4da69789d875853beb4f92147825ebf"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Applicative hiding(empty)\n\nimport Data.List hiding(insert)\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\n\nmain = do\n (n,_) <- readIntPair\n qs <- map (map readInt . B.words) . B.lines <$> B.getContents\n case solve n qs of\n Just as -> do \n putStrLn $ \"YES\" \n putStrLn $ unwords $ map show as\n Nothing -> putStrLn $ \"NO\"\n\ndata SegTree a = Leaf !Int !a | Node !Int !Int !a !(SegTree a) !(SegTree a) deriving(Show)\n\nget :: SegTree a -> a\nget (Leaf _ q) = q\nget (Node _ _ q _ _) = q\n\nmkTree :: Int -> SegTree Int\nmkTree n = go 0 n where\n go l r | r - l == 1 = Leaf l 0\n | otherwise = Node l r 0 t1 t2 where\n m = (l + r) `div` 2\n t1 = go l m\n t2 = go m r\n\nupdate :: Int -> Int -> Int -> SegTree Int -> SegTree Int\nupdate !ql !qr !v = go where\n go t@(Leaf i q) \n | ql <= i && i < qr = Leaf i (q .|. v)\n | otherwise = t\n go t@(Node l r q t1 t2) \n | ql <= l && r <= qr = Node l r (q .|. v) t1 t2\n | r <= ql || qr <= l = t\n | otherwise = Node l r q (go t1) (go t2)\n\nconvert :: SegTree Int -> SegTree Int\nconvert = go 0 where\n go !q (Leaf i q') = Leaf i (q .|. q')\n go !q (Node l r q' t1 t2) = \n let t1' = go (q .|. q') t1\n t2' = go (q .|. q') t2\n in Node l r (get t1' .&. get t2') t1' t2'\n\nrmq :: Int -> Int -> SegTree Int -> Int\nrmq ql qr = go where\n go (Leaf i q) | ql <= i && i < qr = q \n | otherwise = -1\n go (Node l r q t1 t2) | ql <= l && r <= qr = q\n | r <= ql || qr <= l = -1\n | otherwise = go t1 .&. go t2\n\ntoList :: SegTree Int -> [Int]\ntoList = go [] where\n go acc (Leaf _ q) = q:acc\n go acc (Node _ _ _ t1 t2) = go (go acc t2) t1\n\nsolve :: Int -> [[Int]] -> Maybe [Int]\nsolve n qs = pure as <* guard check where\n t1 = mkTree n\n t2 = foldl' (\\acc [li,ri,qi] -> update (li-1) ri qi acc) t1 qs\n t3 = convert t2\n as = toList t3\n check = all (\\[li,ri,qi] -> rmq (li-1) ri t3 == qi) qs\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Applicative hiding(empty)\n\nimport Data.List hiding(insert)\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\n\nmain = do\n (n,_) <- readIntPair\n qs <- map (map readInt . B.words) . B.lines <$> B.getContents\n case solve n qs of\n Just as -> do \n putStrLn $ \"YES\" \n putStrLn $ unwords $ map show as\n Nothing -> putStrLn $ \"NO\"\n\ndata SegTree = Leaf !Int !Int | Node !Int !Int !Int !SegTree !SegTree deriving(Show)\n\nget :: SegTree -> Int\nget (Leaf _ q) = q\nget (Node _ _ q _ _) = q\n\nmkTree :: Int -> SegTree\nmkTree n = go 0 n where\n go l r | r - l == 1 = Leaf l 0\n | otherwise = Node l r 0 t1 t2 where\n m = (l + r) `div` 2\n t1 = go l m\n t2 = go m r\n\nupdate :: Int -> Int -> Int -> SegTree -> SegTree\nupdate !ql !qr !v = go where\n go t@(Leaf i q) \n | ql <= i && i < qr = Leaf i (q .|. v)\n | otherwise = t\n go t@(Node l r q t1 t2) \n | ql <= l && r <= qr = Node l r (q .|. v) t1 t2\n | r <= ql || qr <= l = t\n | otherwise = Node l r q (go t1) (go t2)\n\nconvert :: SegTree -> SegTree\nconvert = go 0 where\n go !q (Leaf i q') = Leaf i (q .|. q')\n go !q (Node l r q' t1 t2) = \n let t1' = go (q .|. q') t1\n t2' = go (q .|. q') t2\n in Node l r (get t1' .&. get t2') t1' t2'\n\nrmq :: Int -> Int -> SegTree -> Int\nrmq ql qr = go where\n go (Leaf i q) | ql <= i && i < qr = q \n | otherwise = -1\n go (Node l r q t1 t2) | ql <= l && r <= qr = q\n | r <= ql || qr <= l = -1\n | otherwise = go t1 .&. go t2\n\ntoList :: SegTree -> [Int]\ntoList = go [] where\n go acc (Leaf _ q) = q:acc\n go acc (Node _ _ _ t1 t2) = go (go acc t2) t1\n\nsolve :: Int -> [[Int]] -> Maybe [Int]\nsolve n qs = pure as <* guard check where\n t1 = mkTree n\n t2 = foldl' (\\acc [li,ri,qi] -> update (li-1) ri qi acc) t1 qs\n t3 = convert t2\n as = toList t3\n check = all (\\[li,ri,qi] -> rmq (li-1) ri t3 == qi) qs\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Applicative hiding(empty)\n\nimport Data.List hiding(insert)\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\n\nmain = do\n (n,_) <- readIntPair\n qs <- map (map readInt . B.words) . B.lines <$> B.getContents\n case solve n qs of\n Just as -> do \n putStrLn $ \"YES\" \n putStrLn $ unwords $ map show as\n Nothing -> putStrLn $ \"NO\"\n\ndata SegTree = Leaf !Int !Int | Node !Int !Int !Int !SegTree !SegTree deriving(Show)\n\nget :: SegTree -> Int\nget (Leaf _ q) = q\nget (Node _ _ q _ _) = q\n\nmkTree :: [Int] -> SegTree\nmkTree as = go 0 n as where\n n = length as\n go l r as | r - l == 1 = Leaf l $ head as\n | otherwise = \n let m = (l+r) `div` 2 \n (asl,asr) = splitAt (m-l) as\n t1 = go l m asl\n t2 = go m r asr in\n Node l r (get t1 .&. get t2) t1 t2\n\nupdate :: Int -> Int -> Int -> SegTree -> SegTree\nupdate ql qr v t@(Leaf i q) = \n if ql <= i && i < qr then Leaf i (q .|. v) else t\nupdate ql qr v t@(Node l r q t1 t2) \n | ql <= l && r <= qr = Node l r (q .|. v) t1 t2\n | r <= ql || qr <= l = t\n | otherwise = Node l r q (update ql qr v t1) (update ql qr v t2)\n\ntoList :: SegTree -> [Int]\ntoList tree = go 0 tree [] where\n go q (Leaf _ q') acc = (q .|. q'):acc\n go q (Node _ _ q' t1 t2) acc = go (q .|. q') t1 (go (q .|. q') t2 acc)\n\nrmq :: Int -> Int -> SegTree -> Int\nrmq ql qr (Leaf i q) = if ql <= i && i < qr then q else -1\nrmq ql qr (Node l r q t1 t2) | ql <= l && r <= qr = q\n | r <= ql || qr <= l = -1\n | otherwise = rmq ql qr t1 .&. rmq ql qr t2\n\nsolve :: Int -> [[Int]] -> Maybe [Int]\nsolve n qs = pure as <* guard check where\n t1 = mkTree $ take n $ repeat 0\n t2 = foldl' (\\acc [li,ri,qi] -> update (li-1) ri qi acc) t1 qs\n as = toList t2\n t3 = mkTree $ toList t2\n check = all (\\[li,ri,qi] -> rmq (li-1) ri t3 == qi) qs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative hiding(empty)\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\nimport Data.Monoid((<>))\n\nimport Data.List hiding(insert)\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,_) <- readIntPair\n qs <- map (map readInt . B.words) . B.lines <$> B.getContents\n case solve n qs of\n Just as -> do \n putStrLn $ \"YES\" \n putStrLn $ unwords $ map show as\n Nothing -> putStrLn $ \"NO\"\n\ndata SegTree = Leaf Int Int | Node Int Int Int SegTree SegTree deriving(Show)\n\nget :: SegTree -> Int\nget (Leaf _ q) = q\nget (Node _ _ q _ _) = q\n\nmkTree :: [Int] -> SegTree\nmkTree as = go 0 n as where\n n = length as\n go l r as | r - l == 1 = Leaf l $ head as\n | otherwise = \n let m = (l+r) `div` 2 \n (asl,asr) = splitAt (m-l) as\n t1 = go l m asl\n t2 = go m r asr in\n Node l r (get t1 .&. get t2) t1 t2\n\nupdate :: Int -> Int -> Int -> SegTree -> SegTree\nupdate ql qr v t@(Leaf i q) = \n if ql <= i && i < qr then Leaf i (q .|. v) else t\nupdate ql qr v t@(Node l r q t1 t2) \n | ql <= l && r <= qr = Node l r (q .|. v) t1 t2\n | r <= ql || qr <= l = t\n | otherwise = Node l r q (update ql qr v t1) (update ql qr v t2)\n\ntoList :: SegTree -> [Int]\ntoList tree = go 0 tree [] where\n go q (Leaf _ q') acc = (q .|. q'):acc\n go q (Node _ _ q' t1 t2) acc = go (q .|. q') t1 (go (q .|. q') t2 acc)\n\nrmq :: Int -> Int -> SegTree -> Int\nrmq ql qr (Leaf i q) = if ql <= i && i < qr then q else -1\nrmq ql qr (Node l r q t1 t2) | ql <= l && r <= qr = q\n | r <= ql || qr <= l = -1\n | otherwise = rmq ql qr t1 .&. rmq ql qr t2\n\nsolve :: Int -> [[Int]] -> Maybe [Int]\nsolve n qs = pure as <* guard check where\n t1 = mkTree [0..n-1]\n t2 = foldl' (\\acc [li,ri,qi] -> update (li-1) ri qi acc) t1 qs\n as = toList t2\n t3 = mkTree $ toList t2\n check = all (\\[li,ri,qi] -> rmq (li-1) ri t3 == qi) qs\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative hiding(empty)\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List hiding(insert)\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\ndata Tree a = Null | Fork a (Tree a) (Tree a) deriving(Show)\n\nempty :: Tree a\nempty = Null\n\nisEmpty :: Tree a -> Bool\nisEmpty Null = True\nisEmpty _ = False\n\nminElem :: Tree a -> a\nminElem (Fork a _ _) = a\nminElem Null = error \"min for empty queue is not supported\"\n\ndeleteMin :: (Ord a) => Tree a -> Tree a\ndeleteMin (Fork _ a b) = merge a b\n\ninsert :: (Ord a) => a -> Tree a -> Tree a\ninsert x a = merge (Fork x Null Null) a\n\nmerge :: (Ord a) => Tree a -> Tree a -> Tree a\nmerge a Null = a\nmerge Null b = b\nmerge a b | minElem a <= minElem b = join a b\n | otherwise = join b a\n where\n join (Fork x a b) c = Fork x b (merge a c)\n\nmain = do\n (n,_) <- readIntPair\n qs <- map (map readInt . B.words) . B.lines <$> B.getContents\n case solve n qs of\n Just as -> do \n putStrLn $ \"YES\" \n putStrLn $ unwords $ map show as\n Nothing -> putStrLn $ \"NO\"\n\ndata SegTree = Leaf Int Int | Node Int Int Int SegTree SegTree deriving(Show)\n\nget :: SegTree -> Int\nget (Leaf _ q) = q\nget (Node _ _ q _ _) = q\n\nmkTree :: [Int] -> SegTree\nmkTree as = go 0 n as where\n n = length as\n go l r as | r - l == 1 = Leaf l $ head as\n | otherwise = \n let m = (l+r) `div` 2 \n (asl,asr) = splitAt (m-l) as\n t1 = go l m asl\n t2 = go m r asr in\n Node l r (get t1 .&. get t2) t1 t2\n\nrmq :: Int -> Int -> SegTree -> Int\nrmq ql qr (Leaf i q) = if ql <= i && i < qr then q else -1\nrmq ql qr (Node l r q t1 t2) | ql <= l && r <= qr = q\n | otherwise = rmq ql qr t1 .&. rmq ql qr t2\n\nsolve :: Int -> [[Int]] -> Maybe [Int]\nsolve n qs = pure as <* guard (check as) where\n qs' = sort $ map (\\[li,ri,qi] -> ((li,ri),qi)) qs\n as = go 1 empty qs'\n tree = mkTree as\n check as = all (\\((li,ri),qi) -> rmq (li-1) ri tree == qi) qs'\n go i queue rem | i > n = []\n | otherwise = \n let (a,b) = span ((<=i).fst.fst) rem\n queue' = foldl (\\acc ((l,r),q) -> insert (r,q) acc) queue a\n pop qs | isEmpty qs = qs\n | fst (minElem qs) < i = pop (deleteMin qs)\n | otherwise = qs\n queue'' = pop queue'\n in\n if isEmpty queue'' \n then 0:go (i+1) queue'' b\n else snd (minElem queue''):go (i+1) queue'' b\n\n"}], "src_uid": "0b204773f8d06362b7569bd82224b218"} {"source_code": "f::Int->[Int]->Int\nf n _\n |n<=0=0\nf n (x:xs)=1 + (f (n-(86400-x)) xs)\n \n\nmain = do\n e<-getLine\n es<-getLine\n let (a:b:[])=map read (words e)::[Int]\n xs=map read (words es)::[Int]\n print $ f b xs", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nday :: Int\nday = 86400\n\ngetMinTime :: [Int] -> Int -> Int\ngetMinTime as t = fst . head . dropWhile ((< t) . snd) $ zip [0 :: Int ..] fs\n where fs = scanl (+) 0 $ map (day - ) as\n\nmain :: IO ()\nmain = do\n [_, t] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ getMinTime as t\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\ngetInts = (map read . words) `fmap` getLine :: IO [Int]\n\nmain = do\n [n,t] <- getInts\n as <- getInts\n print $ 1 + (fromJust $ findIndex (\\a -> a >= t) (scanl1 (+) (map (\\a -> 86400 - a) as)))"}, {"source_code": "main = getContents >>= print . exec\nexec = solve . map read . words\nsolve (n:t:xs) = length $ takeWhile (> 0) $ scanl (\\t x -> t - (86400 - x) :: Int) t xs"}, {"source_code": "main :: IO ()\nmain = print . solve 0 . map read . words =<< getContents\n\nsolve :: Int -> [Int] -> Int\nsolve d (_:0:_) = d\nsolve d (n:t:a:ax) = solve (d + 1) (n:(maximum [0, t - (86400 - a)]):ax)\n"}, {"source_code": "import Data.List\n\n\n\nmain = do\n [n,s] <- getLine >>= return . map (read :: String -> Int) . words \n as <- getLine >>= return . map (read :: String -> Int) . words \n let d = fst $ foldl' (\\acc@(d,t) x -> if t > 0 then (d+1,t-86400+x) else acc) (0,s) as\n print d\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nmain = do\n\t\t[n,t]<-map read <$> words <$> getLine::IO [Int]\n\t\tk<-scanl1 (+) <$> map (86400-) <$> map read <$> words <$> getLine::IO [Int]\n \t\tprint $ (+1) $ length $ takeWhile ( 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nf :: Int -> [Int] -> Int\nf t (x:xs) = if t <= x then 1 else 1 + f (t-x) xs\n\nmain :: IO ()\nmain = do\n n:k:_ <- readInts\n a <- readInts\n print $ f k . map ((-) 86400) $ a"}], "negative_code": [], "src_uid": "8e423e4bec2d113612a4dc445c4b86a9"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\nnumOcc [] = M.empty\r\nnumOcc (x:xs) = let m = numOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m\r\n\tNothing -> M.insert x 1 m\r\n\r\nresult list = aux (length sort) sort sumOcc where\r\n\tsort = fmap fst $ L.sortOn snd $ M.toList occ\r\n\tocc = numOcc list\r\n\r\n\tsumOcc = foldr (+) 0 occ\r\n\r\n\taux l [] s = 0\r\n\taux l (x:xs) s = min (s - y*l) (y + aux (l-1) xs (s-y)) where y = occ ! x\r\n\r\n\r\nshowR (x:xs) = show (x+1) ++ \" \" ++ showR xs\r\nshowR [] = []\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ result a \r\n\t\tloop $ t - 1\r\n\tloop t", "positive_code": [{"source_code": "-- https://codeforces.com/problemset/problem/1490/F\nmodule Main where\n\nimport Data.List (nub)\nimport Data.Map as M (Map, alter, empty, toList)\n\nmain :: IO ()\nmain = getLine >>= \\x -> wrapper (read x :: Int)\n\nwrapper :: Int -> IO ()\nwrapper x\n | x == 0 = return ()\n | otherwise = driver >> wrapper (x - 1)\n\ndriver :: IO ()\ndriver = getLine >> getLine >>= \\x -> let arr = toArr x in print $ solve arr\n\ntoArr :: String -> [Int]\ntoArr = map (\\x -> read x :: Int) . words\n\n-- the value is the minimum of\nsolve :: [Int] -> Int\nsolve arr =\n let counts = toList $ getCounts arr\n mapF :: [(Int, Int)] -> Int -> Int\n mapF counts count =\n sum\n ( map\n ( \\x ->\n let count' = snd x\n in if count' > count\n then count' - count\n else if count' == count then 0 else count'\n )\n counts\n )\n in minimum $ map (mapF counts) (nub $ map snd counts)\n\ngetCounts :: [Int] -> M.Map Int Int\ngetCounts = go M.empty\n where\n go m [] = m\n go m (x : xs) = go (M.alter f x m) xs\n\n f Nothing = Just 1\n f (Just x) = Just (x + 1)"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n as <- popInts\n return $ bshow (solve n as)\n\n\nsolve n as = minimum $ go 0 0 0 (reverse counts) (tail $ reverse ss)\n where\n counts = countList $ map snd $ countList as\n\n ss = snd $ mapAccumL (\\s (a, b) -> (s + a * b, s + a * b)) 0 counts\n\n go acc a0 b0 ((a, b) : _) [] = [acc + (a0 - a) * b0]\n go acc a0 b0 ((a, b) : cs) (s : ss) =\n let acc' = acc + (a0 - a) * b0\n a1 = a\n b1 = b0 + b in\n (acc' + s) : go acc' a1 b1 cs ss\n\n\ncountList :: (Ord a) => [a] -> [(a, Int)]\ncountList xs = Map.assocs $ foldl' addm Map.empty xs\n where\n addm m x | Map.member x m = Map.adjust (+ 1) x m\n | otherwise = Map.insert x 1 m\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport qualified Data.Map.Strict as M\n\ntype SIO = StateT P.ByteString IO\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n a <- readInts\n let\n mkFreqMap li = M.fromListWith (+) $ zip li $ repeat 1\n freqs = M.elems $ mkFreqMap a \n --freqMap = [(head v, length v) | v <- group $ sort freqs]\n freqMap = M.assocs $ mkFreqMap freqs\n step (!prevCost, !remPop, !prevVal, !prevCt) (currVal, currCt) = let\n currCost = prevCost\n + prevCt * prevVal -- send prevVals to 0...\n - remPop * (currVal - prevVal) -- ...but move the rest less\n newRemPop = remPop - currCt\n in (currCost, newRemPop, currVal, currCt)\n options = scanl step (n, length freqs, 0, 0) freqMap\n putInts $ pure $ foldl' (\\v (cost, _, _, _) -> min v cost) maxBound options\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport qualified Data.Map.Strict as M\n\ntype SIO = StateT P.ByteString IO\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n a <- readInts\n let\n freqs = M.elems $ M.fromListWith (+) $ zip a $ repeat 1\n freqMap = [(head v, length v) | v <- group $ sort freqs]\n step (!prevCost, !remPop, !prevVal, !prevCt) (currVal, currCt) = let\n currCost = prevCost\n + prevCt * prevVal -- send prevVals to 0...\n - remPop * (currVal - prevVal) -- ...but move the rest less\n newRemPop = remPop - currCt\n in (currCost, newRemPop, currVal, currCt)\n options = scanl step (n, length freqs, 0, 0) freqMap\n putInts $ pure $ foldl' (\\v (cost, _, _, _) -> min v cost) maxBound options\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n getLine\r\n as <- map read . words <$> getLine :: IO [Int]\r\n let cnts = reverse $ sort $ map length $ group $ sort as\r\n ans = minimum $ zipWith4 f [1..] cnts (scanl1 (+) cnts) (tail $ scanr (+) 0 cnts) where\r\n f i x sl sr = sl - i * x + sr\r\n print ans\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n as <- popInts\n return $ bshow (solve n as)\n\n\nsolve n as = minimum $ go 0 0 0 (reverse counts) (tail $ reverse ss)\n where\n counts = countList $ map snd $ countList as\n\n ss = snd $ mapAccumL (\\s (a, b) -> (s + a * b, a * b)) 0 counts\n\n go acc a0 b0 ((a, b) : _) [] = [acc + (a0 - a) * b0]\n go acc a0 b0 ((a, b) : cs) (s : ss) =\n let acc' = acc + (a0 - a) * b0\n a1 = a\n b1 = b0 + b in\n (acc' + s) : go acc' a1 b1 cs ss\n\n\ncountList :: (Ord a) => [a] -> [(a, Int)]\ncountList xs = Map.assocs $ foldl' addm Map.empty xs\n where\n addm m x | Map.member x m = Map.adjust (+ 1) x m\n | otherwise = Map.insert x 1 m\n"}], "src_uid": "aab052bf49da6528641f655342fa4848"} {"source_code": "import Control.Monad\n\nsolve :: Int -> [Int] -> Int\nsolve x as = if all (== x) as\n then 0\n else if elem x as\n then 1\n else if sum as == x * length as -- no overflow, inputs are small\n then 1\n else 2 -- infect one account round 1, the rest round 2\n -- always possible since n >= 2\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, x] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve x as\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int64]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int64) $ words line\n\nreadInt :: IO Int64\nreadInt = do\n line <- getLine\n return $ (read::String->Int64) $ line\n\ncount :: Eq a => a -> [a] -> Int\ncount x = length . filter (==x)\n\nf :: Int64 -> Int64 -> Int64\nf curPower xLeft = \n let s = (curPower) * (curPower - 1) `div` 2 in\n if s > xLeft then 0 else 1 + f (curPower * 2) (xLeft - s)\n\nsolve :: IO ()\nsolve = do\n (n:x:_) <- readArray\n a <- readArray\n let s = sum a\n let cnt = (fromIntegral::Int->Int64) $ count x a\n if cnt == n then print 0 else if cnt > 0 then print 1 else if n * x == s then print 1 else print 2\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [0..t-1] $ (\\i -> solve)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ if all (== k) as then 0 else if sum as == n * k || k `elem` as then 1 else 2\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,x ] <- (map read.words) <$> getLine\n as <- (map read.words) <$> getLine\n print $ solve n x as\n\nsolve :: Integer -> Integer -> [Integer] -> Integer\nsolve n x as\n | all (==x) as = 0\n | sum as == n*x = 1\n | any (==x) as = 1\n | otherwise = 2\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ if all (== k) as then 0 else if sum as == n * k then 1 else 2\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,x ] <- (map read.words) <$> getLine\n as <- (map read.words) <$> getLine\n print $ solve n x as\n\nsolve :: Integer -> Integer -> [Integer] -> Integer\nsolve n x as\n | all (==x) as = 0\n | sum as == n*x = 1\n | otherwise = 2\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,x ] <- (map read.words) <$> getLine\n as <- (map read.words) <$> getLine\n print $ solve n x as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n x as\n | all (==x) as = 0\n | sum as == n*x = 1\n | otherwise = 2\n"}], "src_uid": "475a24d36eab99ae4f78815ccdc5da91"} {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nbinSearch :: Integral i => (i -> Bool) -> i -> i -> i\r\nbinSearch f = go where\r\n go l h\r\n | l > h = l\r\n | f m = go l (m - 1)\r\n | otherwise = go (m + 1) h\r\n where m = (l + h) `div` 2\r\n \r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l h where (l, h) = bounds a\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\nfita :: IO ()\r\nfita = do \r\n ~[a,b] <- readInts\r\n print $ min ((a+b) `div` 4) (min a b)\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n [p, m] <- fmap read . words <$> getLine\n print $ minimum [p, m, (p + m) `div` 4]\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Bool\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC { a :: Int, b :: Int }\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n a <- int\r\n b <- int\r\n return TC {..}\r\n\r\ntype Output = Int\r\n\r\noutput :: Output -> C.ByteString\r\noutput = showB\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = minimum [a, b, (a + b) `div` 4]\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nbinSearch :: Integral i => (i -> Bool) -> i -> i -> i\r\nbinSearch f = go where\r\n go l h\r\n | l > h = l\r\n | f m = go l (m - 1)\r\n | otherwise = go (m + 1) h\r\n where m = (l + h) `div` 2\r\n \r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l h where (l, h) = bounds a\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\nfita :: IO ()\r\nfita = do \r\n ~[a,b] <- readInts\r\n let fun x = if x > min a b then True else (a+b-2*x) `div` 2 < x\r\n print $ (binSearch fun (0::Int) (1000000001::Int)) - 1\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n"}], "negative_code": [], "src_uid": "8a1ceac1440f7cb406f12d9fc2ca0e20"} {"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.Map as M\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, singleton, lookupGT, delete, insert, lookupLT)\n-- import Debug.Trace (traceShow)\n\ntype Roll = Map Int Int -> [Int]\n\nsolve :: [Int] -> Int\nsolve a = maximum . foldr loop (`seq` []) a $ singleton minBound 0\n where\n loop :: Int -> Roll -> Roll\n loop i f m = r:f m''\n where\n r = (+1) . snd . fromJust $ i `lookupLT` m\n m' = insert i r m\n m'' = case i `lookupGT` m' of\n Nothing -> m'\n Just (k, r') -> if r < r' then m' else k `delete` m'\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n print $ solve a\n", "positive_code": [{"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.Map as M\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, singleton, lookupGT, delete, insert, lookupLT)\n\n-- longest increasing sequence (strictly so)\nlis :: (Num a, Ord a, Bounded a) => [a] -> [Int]\nlis a = foldr loop (`seq` []) a $ singleton minBound 0\n where\n loop :: (Num a, Ord a) => a -> (Map a Int -> [Int]) -> Map a Int -> [Int]\n loop i f m = (r:) . f $ case i `lookupGT` m' of\n Nothing -> m'\n Just (k, r') -> if r < r' then m' else k `delete` m'\n where\n r = (+1) . snd . fromJust $ i `lookupLT` m\n m' = insert i r m\n\nsolve :: [Int] -> Int\nsolve = maximum . lis\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = B.getLine >> parse <$> B.getLine >>= \\a -> print $ solve a\n"}], "negative_code": [{"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.Map as M\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, singleton, lookupGT, delete, insert, lookupLT)\n-- import Debug.Trace (traceShow)\n\ntype Roll = Map Int Int -> [Int]\n\nsolve :: [Int] -> Int\nsolve a = maximum . foldr loop (`seq` []) a $ singleton maxBound 0\n where\n loop :: Int -> Roll -> Roll\n loop i f m = r:f m''\n where\n r = (+1) . snd . fromJust $ i `lookupGT` m\n m' = insert i r m\n m'' = case i `lookupLT` m' of\n Nothing -> m'\n Just (k, r') -> if r < r' then k `delete` m' else m'\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n print $ solve a\n"}], "src_uid": "e132767dd89801a237b998a410b22a44"} {"source_code": "import Data.Function (on)\r\nimport Data.List\r\n\r\nyesNo False = \"NO\"\r\nyesNo True = \"YES\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nsolve_task :: String -> String\r\nsolve_task line = let votes = map readInt $ words line\r\n maxs = map (\\x -> maximum $ delete x votes) votes\r\n in unwords . map show $ zipWith (\\m v -> max 0 (m-v+1)) maxs votes\r\n\r\nsolve_tasks (t:tasks) = map solve_task tasks\r\n\r\nsolve = unlines . solve_tasks . lines\r\n\r\nmain = interact solve", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC { xs :: [Int] }\n\ninput :: Scanner TC\ninput = do\n xs <- 3 >< int\n return TC{..}\n\noutput = map show >>> unwords >>> C.pack\n\nsolve :: TC -> [Int]\nsolve TC{..} = zipWith extra xs [max b c, max a c, max a b]\n where\n [a, b, c] = xs\n extra u v = max (v + 1 - u) 0\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad\n\ncalc :: Int -> Int -> Int -> Int\ncalc max_votes extra curr = if curr < max_votes then max_votes - curr + 1 else extra\n\ncalcVotes :: (Int, Int, Int) -> (Int, Int, Int)\ncalcVotes (a, b, c) = \n let max_votes = a `max` b `max` c\n l = [a, b, c]\n is_maxs = map (== max_votes) l\n counts = foldr (\\b -> \\i -> if b then i + 1 else i) 0 is_maxs\n extra = if counts > 1 then 1 else 0\n calc' = calc max_votes extra\n in (calc' a, calc' b, calc' c)\n\ngetInputs :: IO (Int, Int, Int)\ngetInputs = do\n inputLine <- getLine\n let inputs = words inputLine\n a = read (inputs !! 0) :: Int\n b = read (inputs !! 1) :: Int\n c = read (inputs !! 2) :: Int\n in return (a, b, c)\n\noutput :: (Int, Int, Int) -> IO()\noutput (a, b, c) = do\n putStrLn (show a ++ \" \" ++ show b ++ \" \" ++ show c)\n\n\nmain :: IO [()]\nmain = do\n num_of_inputs <- getLine\n list_of_inputs <- replicateM (read (num_of_inputs) :: Int) getInputs\n let ans = map calcVotes list_of_inputs\n in traverse output ans\n\n"}, {"source_code": "main = do\r\n t <- read <$> getLine :: IO Int\r\n mapM_ solve [1..t]\r\n\r\nsolve :: Int -> IO ()\r\nsolve _ = do\r\n [a, b, c] <- map read . words <$> getLine :: IO [Int]\r\n putStrLn $ let x = max 0 (max b c + 1 - a)\r\n y = max 0 (max a c + 1 - b)\r\n z = max 0 (max a b + 1 - c)\r\n in show x ++ \" \" ++ show y ++ \" \" ++ show z"}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n nums@[_a,_b,_c] <- map read <$> words <$> getLine :: IO [Int]\r\n return nums\r\n\r\nsolve xs = intercalate \" \" . map show . map (f is) $ is\r\n where\r\n is = zip [1::Int ..] xs\r\n\r\nf is (i,v) = uncurry extra . (,) v . (+1) . maximum . map snd . filter ((/=i).fst) $ is\r\n\r\nextra have need | (have < need) = need - have | otherwise = 0\r\n"}, {"source_code": "import Control.Monad (replicateM_, forM_, forM)\r\nimport Control.Applicative ()\r\n\r\nnextList :: IO [Int]\r\nnextList = map read.words <$> getLine\r\n\r\nsolve = do\r\n [a, b, c] <- nextList\r\n let ans = show <$> [max 0 $ (max b c + 1) - a, max 0 $ (max a c + 1) - b, max 0 $ (max a b + 1) - c]\r\n putStrLn $ unwords ans\r\n return ()\r\n\r\nmain = do\r\n [t] <- nextList\r\n replicateM_ t solve\r\n "}], "negative_code": [], "src_uid": "f80dea1e07dba355bfbefa4ff65ff45a"} {"source_code": "{-# language TupleSections #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.Array\n\nimport Debug.Trace\n\nm = 100\n\ntype A = Array (Int,Int) Int\ntype Pos = (Int,Int)\n\ndecompose :: Int -> [Int]\ndecompose 0 = []\ndecompose n = x : decompose (n - pyth x)\n where\n x = opt pyth n\n\nopt f x = length $ takeWhile (<=x) $ map f [1..]\n\npyth x = (x*(x-1)) `div` 2\nntr x = ((x-2)*(x-1)*x) `div` 6\n\nconnectionEdges nfill nedges level\n | nfill < nedges = error \"Not enought\"\n | otherwise = rev $\n take nedges $\n zip [1..] (repeat level)\n where\n rev l = l ++ map (\\(x,y) -> (y,x)) l \n\nsolve :: Int -> Array (Int,Int) Int\nsolve n = arr'\n where\n nfill = opt ntr n\n rest = n - ntr nfill\n arr = array ((1,1),(m,m)) $\n [((i,j),0) | i <- [1..m], j <- [1..m]]\n fillEdges = map (,1)\n [ (x,y) | x <- [1..nfill], y <- [1..nfill], x/=y ]\n restEdges = map (,1) $\n concatMap (uncurry $ connectionEdges nfill) $\n zip (decompose rest) [m,m-1..0]\n arr' = arr // (fillEdges ++ restEdges)\n \nshowArr arr = unlines $ map row rows\n where\n ((i,j),(a,b)) = bounds arr\n rows = [i..a]\n cols = [j..b]\n row i = concat $ map show [arr ! (i,v) | v <- cols]\n\nmain = do\n n <- readLn\n print m\n putStrLn $ showArr (solve n)", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nfull2 :: Int -> Int\nfull2 x = (x * (x - 1)) `div` 2\n\nfull3 :: Int -> Int\nfull3 x = (x * (x - 1) * (x - 2)) `div` 6\n\nfindBase :: Int -> Int\nfindBase n = (head $ dropWhile (\\x -> full3 x <= n) [1..]) - 1\n\ntoP2SumGreedy :: Int -> Int -> [Int]\ntoP2SumGreedy b n = toP2SumGreedy' n [b, b-1 .. 2] where\n toP2SumGreedy' 0 _ = []\n toP2SumGreedy' n arr@(x:xs) = let f2x = full2 x in if n >= f2x\n then x:toP2SumGreedy' (n - f2x) arr\n else toP2SumGreedy' n xs\n\nclique :: Int -> [(Int, Int)]\nclique n = [(i, j) | i <- [0..n-1], j <- [i+1..n-1]]\n\nnewVertex :: Int -> Int -> [(Int, Int)]\nnewVertex id cnt = [(i, id) | i <- [0..cnt-1]]\n\ntoString :: Int -> Int -> [Int] -> String\ntoString n now xs \n | n == now = []\n | null xs = '0':toString n (now+1) []\n | head xs == now = '1':(toString n (now + 1) $ tail xs)\n | head xs > now = '0':toString n (now + 1) xs \n | head xs < now = toString n now $ tail xs \n\nverticesFrom :: [(Int, Int)] -> Int -> [Int]\n--verticesFrom edges v = [i | (v, i) <- edges] ++ [i | (i, v) <- edges]\nverticesFrom [] v = []\nverticesFrom ((x,y):xs) v\n | x == v = y:verticesFrom xs v\n | y == v = x:verticesFrom xs v\n | otherwise = verticesFrom xs v\n\nbuildRow :: Int -> [(Int, Int)] -> Int -> String\nbuildRow n edges v = toString n 0 $ sort $ verticesFrom edges v\n\ntoAdgMatrix :: [(Int, Int)] -> [String]\ntoAdgMatrix edges = res where\n n = 1 + max (maximum $ map fst edges) (maximum $ map snd edges)\n res = [buildRow n edges i | i <- [0..n-1]]\n\nsolve :: Int -> [String]\nsolve n = toAdgMatrix edges where\n b = findBase n\n restCnts = toP2SumGreedy b $ n - full3 b\n edges :: [(Int, Int)]\n edges = clique b ++ (concat $ map (\\(id, cnt) -> newVertex id cnt) $ zip [b..] restCnts)\n\nmain = do\n n <- read <$> getLine\n let ans = solve n\n print $ length ans\n putStrLn $ concatMap (++\"\\n\") ans\n"}], "negative_code": [], "src_uid": "d3f4c7fedd6148c28d8780142b6594f4"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsolve [_] = []\nsolve ([a,b]:x@[c,d]:xs) = y : rest\n where\n rest = solve $ x : xs\n e = min c d\n y = if a == b then e - a\n else if a < b && b <= e then e - b + 1\n else if a > b && a <= e then e - a + 1\n else 0\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- replicateM n $ readInts\n print . (+1) . sum . solve $ [0,0] : xs", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n-- {-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE NumDecimals #-}\n-- {-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t[ as, bs ] <- transpose <$> replicateM n readInts\n\tprint $ sum $ map ( uncurry subtract ) $ merge $ solve (0:as) (0:bs)\n\nsolve [_] _ = []\nsolve (a1:a2:as) (b1:b2:bs) = if p < q then ( p, q ) : r else r\n\twhere\n\t\tp = max a1 b1\n\t\tq = min a2 b2 + 1\n\t\tr = solve (a2:as) (b2:bs) \n\nmerge [] = []\nmerge [a] = [a]\nmerge ( (a1,b1) : ( a2, b2 ) : rest )\n\t| a2 <= b1 = merge ( ( a1, b2 ) : rest )\n\t| otherwise = ( a1, b1 ) : merge ( ( a2, b2 ) : rest )"}, {"source_code": "import Control.Monad\n\nsolve [_] = []\nsolve ([a,b]:x@[c,d]:xs) = y : rest\n where\n rest = solve $ x : xs\n e = min c d\n y = if a == b then e - a\n else if a < b && b <= e then e - b + 1\n else if a > b && a <= e then e - a + 1\n else 0\n\n--readInts = do \n-- [a,b] <- (map read . words) <$> getLine\n-- return (a,b)\n\nmain = do\n n <- readLn\n xs <- replicateM n $ (map read . words) <$> getLine\n print . (+1) . sum . solve $ [0,0] : xs"}, {"source_code": "import Control.Monad\n\nsolve [_] = []\nsolve ((a,b):(c,d):xs) = x : rest\n where\n rest = solve $ (c,d) : xs\n e = min c d\n x = if a == b then e - a\n else if a < b && b <= e then e - b + 1\n else if a > b && a <= e then e - a + 1\n else 0\n\nreadInts :: IO ((Int,Int))\nreadInts = do \n [a,b] <- (map read . words) <$> getLine\n return (a,b)\n\nmain = do\n n <- readLn\n xs <- (:) (0,0) <$> replicateM n readInts\n print . (+1) . sum $ solve xs"}, {"source_code": "calculate :: Int -> Int -> Int -> [[Int]] -> Int\ncalculate ans c d ([a,b]:xs)\n | c == d = calculate (ans + e - c) a b xs\n | c < d && d <= e = calculate (ans + e - d + 1) a b xs\n | c > d && c <= e = calculate (ans + e - c + 1) a b xs\n | otherwise = calculate ans a b xs\n where e = min a b\ncalculate ans c d [] = ans\nmain = do\n _ <- getLine\n interact $ show . calculate 1 0 0 . map (map read . words) . lines"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Maybe\nimport Data.List\n\nsolve [_] _ = []\nsolve (a:c:xs) (b:d:ys) = ans : rest\n where\n rest = solve (c:xs) (d:ys)\n e = min c d\n ans = if a == b then e - a\n else if a < b && b <= e then e - b + 1\n else if a > b && a <= e then e - a + 1\n else 0\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n n <- readLn\n [as,bs] <- transpose <$> replicateM n readInts\n print . (+1) . sum $ solve (0:as) (0:bs)"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n-- {-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE NumDecimals #-}\n-- {-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t[ as, bs ] <- transpose . map head . group <$> replicateM n readInts\n\tprint $ sum $ map ( uncurry subtract ) $ merge $ solve (0:as) (0:bs)\n\tprint $ solve (0:as) (0:bs)\n\nsolve [_] _ = []\nsolve (a1:a2:as) (b1:b2:bs) = if p <= q then ( p, q ) : r else r\n\twhere\n\t\tp = max a1 b1\n\t\tq = min a2 b2 + 1\n\t\tr = solve (a2:as) (b2:bs) \n\nmerge [] = []\nmerge [a] = [a]\nmerge ( (a1,b1) : ( a2, b2 ) : rest )\n\t| a2 <= b1 = ( a1, b2 ) : merge rest\n\t| otherwise = ( a1, b1 ) : merge ( ( a2, b2 ) : rest )"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n-- {-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE NumDecimals #-}\n-- {-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t[ as, bs ] <- transpose . map head . group <$> replicateM n readInts\n\tprint $ sum $ map ( uncurry subtract ) $ merge $ solve (0:as) (0:bs)\n\nsolve [_] _ = []\nsolve (a1:a2:as) (b1:b2:bs) = ( max a1 b1, min a2 b2 + 1 ) : solve (a2:as) (b2:bs)\n\nmerge [] = []\nmerge [a] = [a]\nmerge ( (a1,b1) : ( a2, b2 ) : rest )\n\t| a2 <= b1 = ( a1, b2 ) : merge rest\n\t| otherwise = ( a1, b1 ) : merge ( ( a2, b2 ) : rest )"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n-- {-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE NumDecimals #-}\n-- {-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t[ as, bs ] <- transpose . map head . group <$> replicateM n readInts\n\tprint $ solve (0:as) (0:bs)\n\nsolve [_] _ = 0\nsolve (a1:a2:as) (b1:b2:bs) = let d = min a2 b2 - max a1 b1 in max 0 ( d + 1 ) + solve (a2:as) (b2:bs)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n-- {-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE NumDecimals #-}\n-- {-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t[ as, bs ] <- transpose . map head . group <$> replicateM n readInts\n\tprint $ sum $ map ( uncurry subtract ) $ merge $ solve (0:as) (0:bs)\n\nsolve [_] _ = []\nsolve (a1:a2:as) (b1:b2:bs) = if p <= q then ( p, q ) : r else r\n\twhere\n\t\tp = max a1 b1\n\t\tq = min a2 b2 + 1\n\t\tr = solve (a2:as) (b2:bs) \n\nmerge [] = []\nmerge [a] = [a]\nmerge ( (a1,b1) : ( a2, b2 ) : rest )\n\t| a2 <= b1 = ( a1, b2 ) : merge rest\n\t| otherwise = ( a1, b1 ) : merge ( ( a2, b2 ) : rest )"}], "src_uid": "5b84295330fa07a9b42570766012990b"} {"source_code": "import Prelude hiding (Left, Right)\nimport Data.List (transpose)\nimport Control.Monad\n\ndata Pipe = Straight | Bent\n deriving (Show, Eq)\n\ndata Direction = Up | Left | Right\n deriving (Show, Eq)\ndata Pos = Lefty | Righty\n deriving (Show, Eq)\n\nnumToPipe :: Int -> Pipe\nnumToPipe x\n | x `elem` [1..2] = Straight\n | x `elem` [3..6] = Bent\n\ncanReach :: [[Pipe]] -> Bool\ncanReach pipes = solve Up Lefty pipes\n where\n solve :: Direction -> Pos -> [[Pipe]] -> Bool\n solve from currPos [] = currPos == Righty\n solve from currPos allPipes@([left, right]:rest)\n | from /= Up && currPipe == Straight = False\n | from /= Up && currPipe == Bent =\n solve Up currPos rest\n | from == Up = if currPipe == Straight then\n solve Up currPos rest\n else\n let comingFrom = if currPos == Lefty then Left else Right in\n solve comingFrom otherPipe allPipes\n where currPipe = if currPos == Lefty then left else right\n otherPipe = if currPos == Lefty then Righty else Lefty\n\nmain = do\n q <- read <$> getLine\n replicateM q $ do\n numPipes <- read <$> getLine :: IO Int\n rows <- transpose <$> replicateM 2 (fmap (numToPipe . read . (:[])) <$> getLine)\n putStrLn $\n if canReach rows then\n \"YES\"\n else\n \"NO\"\n return ()\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n getLine\n [r1,r2] <- replicateM 2 getLine\n putStrLn $ if snd (foldl' adv (True,False) (zip r1 r2))\n then \"YES\"\n else \"NO\"\nadv (fu,fd) (pu,pd) = (pu',pd') where\n pu' = fu && straight pu || fd && bent pu && bent pd\n pd' = fd && straight pd || fu && bent pu && bent pd\nstraight x = x <= '2'\nbent x = x >= '3'\n"}, {"source_code": "import Data.List\n\nboolToAns :: Bool -> String\nboolToAns x = if (x == True) then \"YES\" else \"NO\"\n\ngetPipeType :: Integer -> Integer\ngetPipeType x = if (x < 3) then 1 else 2\n\ngetAnswer :: Integer -> Integer -> String -> String -> Bool\ngetAnswer n position string1 string2 = \n do \n if (n == 0 && position == 2) then True\n else if (n == 0) then False\n else if (position == 1 && (getPipeType (read [head string1] :: Integer)) == 1) \n then getAnswer (n - 1) position (drop 1 string1) (drop 1 string2)\n else if (position == 1 && (getPipeType (read [head string1] :: Integer)) == 2) \n then if ((getPipeType (read [head string2] :: Integer)) == 2) then getAnswer (n - 1) 2 (drop 1 string1) (drop 1 string2)\n else False\n else if (position == 2 && (getPipeType (read [head string2] :: Integer)) == 1) \n then getAnswer (n - 1) position (drop 1 string1) (drop 1 string2)\n else if (position == 2 && (getPipeType (read [head string2] :: Integer)) == 2) \n then if ((getPipeType (read [head string1] :: Integer)) == 2) then getAnswer (n - 1) 1 (drop 1 string1) (drop 1 string2)\n else False\n else True -- Theoretically it never enters in this else\n\n--solver :: Integer\nsolver 0 = return ()\nsolver t = \n do\n line <- getLine\n let n = read line :: Integer\n string1 <- getLine\n string2 <- getLine\n --let ans = getAnswer n 1 string1 string2 \n putStrLn (boolToAns (getAnswer n 1 string1 string2))\n solver (t-1)\n\nmain = do\n line <- getLine\n let t = read line :: Integer\n solver t\n"}, {"source_code": "import Data.Char (isDigit)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\ninputNum = do\n line <- getLine\n return ((read line) :: Int)\n\ninputArr = do\n line <- getLine\n let ar = ((map (\\x -> read [x]) line) :: [Int])\n return ar\n\nsolve3 (_, b) [] [] = b\nsolve3 (p1, p2) (a:r1) (b:r2) = solve3 (newp1, newp2) r1 r2\n where newp1 = (p1 && (a==1)) || (p2 && (a==2) && (b==2))\n newp2 = (p2 && (b==1)) || (p1 && (a==2) && (b==2))\n\nsolve = do\n n <- inputNum\n r1 <- inputArr\n r2 <- inputArr\n let f x = map (\\z -> if z<3 then 1 else 2) x\n let pos = solve3 (True, False) (f r1) (f r2)\n putStrLn (if pos then \"YES\" else \"NO\")\n\nsolveCases 0 = return ()\nsolveCases q = do\n solve\n solveCases (q-1)\n\nmain = do\n q <- inputNum\n solveCases q\n"}], "negative_code": [{"source_code": "import Data.Char (isDigit)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\ninputNum = do\n line <- getLine\n return (read line)\n\ninputArr = do\n line <- getLine\n let newL = filter isDigit line\n let ar = ((map (\\x -> read [x]) newL) :: [Int])\n return ar\n\nsolve3 (_, b) [] [] = b\nsolve3 (p1, p2) (a:r1) (b:r2) = solve3 (newp1, newp2) r1 r2\n where newp1 = (p1 && (a==1)) || (p2 && (a==2) && (b==2))\n newp2 = (p2 && (a==1)) || (p1 && (a==2) && (b==2))\n\nsolve = do\n n <- inputNum\n r1 <- inputArr\n r2 <- inputArr\n let f x = map (\\z -> if z<3 then 1 else 2) x\n let pos = solve3 (True, False) (f r1) (f r2)\n putStrLn (if pos then \"YES\" else \"NO\")\n\nsolveCases 0 = return ()\nsolveCases q = do\n solve\n solveCases (q-1)\n\nmain = do\n q <- inputNum\n solveCases q\n"}], "src_uid": "f34cff4302e047b1e3bfc2c79aa57be3"} {"source_code": "import Data.Array (listArray, (!))\n\nprocess :: [[Char]] -> Int\nprocess mat = sum [check (i,j) | i <- [2..(n-1)], j <- [2..(n-1)]]\n where\n n = length mat\n mat' = listArray ((1,1),(n,n)) $ concat mat\n check (i,j)\n | mat' ! (i,j) == 'X'\n && mat' ! (i-1,j-1) == 'X'\n && mat' ! (i-1,j+1) == 'X'\n && mat' ! (i+1,j-1) == 'X'\n && mat' ! (i+1,j+1) == 'X'= 1\n | otherwise = 0\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n mat <- fmap lines getContents\n print $ process mat", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\n\nonecase n a (a1,a2) \t\t| a1==1 || a1==x || a2==1 || a2==x =0\n | all (== 'X') [a!(a1,a2),a!(a1-1,a2-1),a!(a1-1,a2+1),a!(a1+1,a2-1),a!(a1+1,a2+1)]=1\n \t| otherwise =0\n\twhere ((x1,y1),(x,y)) = bounds a\nmain = do\n\t\tn<- read<$> getLine ::IO Int\n\t\ta1<- concat <$> replicateM n getLine::IO [Char]\n\t\tlet a = listArray ((1,1),(n,n)) a1\n\t\tprint $ sum $ map (onecase n a) [( a1,a2)|a1<-[1..n],a2<-[1..n]]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n k <- read <$> getLine\n cs <- take (k*k) . map (=='X') . filter (`elem` \".X\") <$> getContents\n let arr = A.listArray ((1,1),(k,k)) cs :: UArray (Int,Int) Bool\n print $ length $ [() | i <- [2..k-1], j <- [2..k-1],\n and $ map (arr A.!)\n $ (i,j):[(i+u,j+v)| u<-[1,-1], v<-[1,-1]]] \n"}, {"source_code": "import Data.Array\nmain = do\n n <- readLn\n g <- listArray ((1,1),(n,n)) . concat . lines <$> getContents\n let cross (i,j) = i > 1 && i < n && j > 1 && j < n &&\n map (g!) [(i-1,j-1),(i-1,j+1),(i,j),(i+1,j-1),(i+1,j+1)] == \"XXXXX\"\n print $ length $ filter cross $ indices g\n"}], "negative_code": [{"source_code": "import Data.Array\nmain = do\n n <- readLn\n g <- listArray ((1,1),(n,n)) . concat . lines <$> getContents\n let cross (i,j) = i > 1 && i < n && j > 1 && j < n &&\n map (g!) [(i-1,j-1),(i-1,j+1),(i,j),(i+1,j-1),(i+1,j+1)] == \"xxxxx\"\n print $ length $ filter cross $ indices g\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\n\nonecase n a i \t\t| any (y) [i+n+1,i+n-1]=0\n | all (== 'X') [a!i,a!(i-n-1),a!(i-n+1),a!(i+n+1),a!(i+n-1)]=1\n \t| otherwise =0\n\twhere (x,y) = bounds a\nmain = do\n\t\tn<- read<$> getLine ::IO Int\n\t\ta1<- concat <$> replicateM n getLine::IO [Char]\n\t\tlet a = listArray (1,n*n) a1\n\t\tprint $ sum $ map (onecase n a) [0..(n*n)-1]\n"}], "src_uid": "3270260030fc56dda3e375af4dad9330"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess su d x | x==[] = su\n\t | d< z = su\n\t | y==0 = process su d (tail x)\n\t | otherwise = process (su + su1) ( d-su1*z) (tail x)\t\n\n\twhere \t(y,z) = head x \n \tdz = div d z \n\t\tsu1 = min dz y\t\t\n\t\t\n\nonecase = do\n\t\t[n,d]<-map read <$> words <$> getLine ::IO [Integer]\n\t\ts<-map read <$> words <$> getLine ::IO [Integer]\n\t\tlet x = zip s [0..]\n\t\tprint $ process (head s) d (tail x)\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\treplicateM_ n onecase\n", "positive_code": [{"source_code": "process :: Int -> [Int] -> Int\nprocess d xs = fst $ foldl f (head xs,d) (zip (tail xs) [1..])\n where\n f :: (Int, Int) -> (Int, Int) -> (Int, Int)\n f acc@(s,n) (x,i)\n | n <= 0 = acc\n | n <= i*x = (s+(n`div`i),0)\n | otherwise = (s+x,n-i*x)\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n [n,d] <- fmap (map readInt.words) getLine\n a <- fmap (map readInt.words) getLine\n print $ process d a\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest :: Integer -> IO ()\ntest 0 = return ()\ntest t = do\n (n:d:_) <- map read.words <$> getLine\n (a:as) <- map read.words <$> getLine\n print $ a + solve d as 1\n test (t - 1)\n\nsolve d _ _ | d <= 0 = 0\nsolve _ [] _ = 0\nsolve d (a:as) n = let v = min a (div d n) in v + solve (d - v * n) as (n + 1) \n"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (n, d) <- liftM2 (,) get get\n as <- replicateM n get\n putln $ f2 as n d\n\nf2 :: [Int] -> Int -> Int -> Int\nf2 [] n d = 0\nf2 (x : l) n d = f3 l d x 1\n\nf3 :: [Int] -> Int -> Int -> Int -> Int\nf3 [] d s i = s\nf3 (y : l) d s i = if y < (div d i) then\n f3 l (d - (y * i)) (s + y) (i + 1)\n else\n s + (div d i)"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess su d x | x==[] = su\n\t | d< y = su\n\t | y==0 = process su d (tail x)\n\t | otherwise = process (su + su1) ( d-su1*z) (tail x)\t\n\n\twhere \t(y,z) = head x \n \tdz = div d z \n\t\tsu1 = min dz y\t\t\n\t\t\n\nonecase = do\n\t\t[n,d]<-map read <$> words <$> getLine ::IO [Integer]\n\t\ts<-map read <$> words <$> getLine ::IO [Integer]\n\t\tlet x = zip s [0..]\n\t\tprint $ process (head s) d (tail x)\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}], "src_uid": "7bbb4b9f5eccfe13741445c815a4b1ca"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: ByteString -> Int\nsolve line = case C.foldl' loop (1, 1, 0) line of\n (i, _, j) -> i +: j\n where\n (+:) !a !b = (a + b) `mod` 1000000007\n aggr (!a, !b, !c) (!i, !j, !k) = (a +: i, b +: j, c +: k)\n\n -- (0, 2, *)\n loop :: (Int, Int, Int) -> Char -> (Int, Int, Int)\n loop (!i, _, _) '0' = (i, 0, 0)\n loop (!i, _, !k) '1' = (k, i, 0)\n loop (_, _, !k) '2' = (0, k, 0)\n loop (_, !j, !k) '*' = (0, 0, j +: k)\n loop !acc '?' = foldr1 aggr $ fmap (loop acc) \"012*\"\n\nmain = B.init <$> B.getLine >>= print . solve\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: ByteString -> Int\nsolve line = case C.foldl' loop (1, 1, 0) line of\n (i, _, j) -> i +: j\n where\n a +: b = (a + b) `mod` 1000000007\n aggr (a, b, c) (i, j, k) = (a +: i, b +: j, c +: k)\n\n -- (0, 2, *)\n loop :: (Int, Int, Int) -> Char -> (Int, Int, Int)\n loop (i, _, _) '0' = (i, 0, 0)\n loop (i, _, k) '1' = (k, i, 0)\n loop (_, _, k) '2' = (0, k, 0)\n loop (_, j, k) '*' = (0, 0, (j + k) `mod` 1000000007)\n loop acc '?' = foldr1 aggr $ fmap (loop acc) \"012*\"\n\nmain = B.init <$> B.getLine >>= print . solve\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: ByteString -> Int\nsolve line = case C.foldl loop (1, 1, 0) line of\n (i, _, j) -> i +: j\n where\n a +: b = (a + b) `mod` 1000000007\n aggr (a, b, c) (i, j, k) = (a +: i, b +: j, c +: k)\n\n -- (0, 2, *)\n loop :: (Int, Int, Int) -> Char -> (Int, Int, Int)\n loop (i, _, _) '0' = (i, 0, 0)\n loop (i, _, k) '1' = (k, i, 0)\n loop (_, _, k) '2' = (0, k, 0)\n loop (_, j, k) '*' = (0, 0, j +: k)\n loop acc '?' = foldr1 aggr $ fmap (loop acc) \"012*\"\n\nmain = B.init <$> B.getLine >>= print . solve\n"}], "negative_code": [], "src_uid": "c16c49baf7b2d179764871204475036e"} {"source_code": "main :: IO ()\nmain = getLine >>=\n \\x -> putStrLn $ x ++ (reverse x)\n", "positive_code": [{"source_code": "main = putStrLn . (flip (++) =<< reverse) =<< getLine\n\n"}, {"source_code": "main = do \n name <- getLine \n putStrLn (name ++ (reverse name)) \n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n \nmain = do\n n <- getLine\n putStrLn $ n ++ reverse n\n\n"}, {"source_code": "main = do\n n <- getLine\n putStr $ n++(reverse n)\n"}, {"source_code": "main = interact $ (\\s -> s ++ reverse s) . head . words"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nmain::IO ()\nmain=do\n t<- getLine \n putStr t\n putStrLn $ reverse t\n\n"}, {"source_code": "main = interact $ (\\x -> x ++ (reverse x)).init\n"}, {"source_code": "main = do\n n <- getLine\n putStrLn $ n ++ reverse n\n"}, {"source_code": "main = interact $ (\\x -> (++) x.reverse $ x).head.lines"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n-- Meat\nsolve :: String-> String\nsolve s= s ++ reverse s\n\n\n-- Shit\nmain :: IO ()\nmain = do\n [s] <- readShit\n printShit [solve s]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "main = do\n\ts <- getLine\n\tputStr s\n\tputStrLn $ reverse s\n"}, {"source_code": "main :: IO()\nmain = do\n s <- getLine\n putStrLn (s ++ reverse s)\n"}, {"source_code": "main :: IO ()\nmain = do\n s <- getLine\n putStrLn $ s ++ reverse s\n"}, {"source_code": "main :: IO()\nmain = do\n s <- getLine\n putStr s\n putStrLn $ reverse s\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n putStrLn $ s ++ reverse s\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = (solve.C.init.head=<C.getLine) )\nsolve xs = C.putStr $ C.append xs (C.reverse xs)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\n\nmain=do\n\n\n q<- getLine\n putStrLn $ q ++ (reverse q)\n"}], "negative_code": [{"source_code": "main = print . (flip (++) =<< reverse) =<< getLine\n\n"}, {"source_code": "main = interact (flip (++) =<< reverse)\n\n"}, {"source_code": "main = interact (\\x -> (++) x.reverse $ x)"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = (solve.head=<C.getLine) )\nsolve xs = C.putStr $ C.append xs (C.reverse xs)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\n\nmain=do\n\n\n q<- C.getLine\n putStrLn \"\"\n C.putStrLn $ C.append q (C.reverse q)\n putStrLn \"\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\n\nmain=do\n\n\n q<- C.getLine\n C.putStrLn $ C.append q (C.reverse q)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\n\nmain=do\n\n\n q<- C.getLine\n C.putStrLn $ C.append q (C.reverse q)\n putStrLn \"\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\n\nmain=do\n\n\n q<- C.getLine\n putStrLn $ C.unpack $ C.append q (C.reverse q)\n"}], "src_uid": "bcf75978c9ef6202293773cf533afadf"} {"source_code": "import Data.Char(digitToInt)\r\n\r\nf :: String -> Int\r\n\r\nf \"\" = 0\r\nf s = do\r\n (f (take ((length s)-1) (drop 1 s))) + (digitToInt (head s))\r\n\r\nsolve 0 = return ()\r\nsolve t = do\r\n s <- getLine\r\n let v1 = take 3 s\r\n let v2 = take 3 (drop 3 s)\r\n let x = f v1\r\n let y = f v2\r\n if x==y then putStrLn \"YES\" else putStrLn \"NO\"\r\n solve (t-1)\r\n\r\nmain :: IO()\r\nmain = do\r\n line <- getLine\r\n let t = (read (takeWhile (/= ' ') line) :: Int)\r\n solve t", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep = id\n\nparse :: String -> [Int]\nparse = map (read . singleton)\n\nsingleton a = [a]\n\nformat b\n | b = \"YES\"\n | otherwise = \"NO\"\n\nsolve xs = sum head == sum tail\n where (head,tail) = splitAt 3 xs\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\n\nsolve :: String -> Bool\nsolve str = L.sum (L.take 3 digits) == L.sum (L.take 3 $ L.reverse digits)\n where\n digits = L.map (\\c -> ord c - ord '0') str\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n s <- B8.getLine <&> L.head . B8.words\n let answer = solve $ B8.unpack s\n putsYesNo answer\n"}, {"source_code": "import Data.List\r\nimport Data.Char\r\n\r\nmain :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\t\r\nsolve :: Int -> Int -> IO ()\r\nsolve number 0 = return ()\t\r\nsolve number current = \tdo\r\n\t\t\t\tl <- getLine\r\n\t\t\t\tif isHappy l then putStrLn \"YES\" else putStrLn \"NO\"\r\n\t\t\t\tsolve number (current - 1)\r\n\t\t\t\t\r\nisHappy :: String -> Bool\r\nisHappy line = let\r\n\t\t\t\t\tdigits = map digitToInt line\r\n\t\t\t\t\tleft = foldr (+) 0 $ take 3 digits\r\n\t\t\t\t\tright = foldr (+) 0 $ drop 3 digits\r\n\t\t\t\t\tin left == right"}, {"source_code": "import Control.Monad (replicateM)\r\nimport Data.List (intercalate)\r\nimport Data.Char (digitToInt)\r\n\r\nsum' :: String -> Int \r\nsum' = sum . map digitToInt\r\n\r\nisLucky :: String -> Bool\r\nisLucky s = sum' (take 3 s) == sum' (drop 3 s)\r\n\r\nsol :: [String] -> String\r\nsol = intercalate \"\\n\" . map (\\x -> if isLucky x then \"yes\" else \"no\")\r\n\r\nreadStrs :: IO [String]\r\nreadStrs = do\r\n n <- read <$> getLine\r\n replicateM n getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- readStrs\r\n putStrLn $ sol inp"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n (n1:n2:n3:n4:n5:n6:[]) <- fmap (fmap read)\n . fmap (fmap (\\x -> [x]))\n $ getLine\n if sum [n1,n2,n3] == sum [n4,n5,n6]\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nsolve :: [Int] -> String\r\nsolve [a,b,c,d,e,f] = if (a+b+c) == (d+e+f) then \"YES\" else \"NO\"\r\n\r\nmain =\r\n interact $ \r\n lines >>> \r\n drop 1 >>> \r\n map (solve . map (read . pure :: Char -> Int)) >>>\r\n unlines\r\n"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\n\nmain :: IO ()\nmain = read <$> getLine >>= flip replicateM_ singleCase\n\nsingleCase :: IO ()\nsingleCase = read <$> getLine >>= \\n -> if lucky n\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nlucky :: Int -> Bool\nlucky n = let n1 = div n 1000\n n2 = mod n 1000\n in sumDigits n1 0 == sumDigits n2 0\n\nsumDigits :: Int -> Int -> Int\nsumDigits n acc = let nd = div n 10\n nm = mod n 10\n in if nd == 0\n then acc + nm\n else sumDigits nd (acc+nm)\n"}, {"source_code": "for :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n s <- getLine\r\n let arr = map (\\c -> read [c] :: Int) s\r\n if arr !! 0 + arr !! 1 + arr !! 2 == arr !! 3 + arr !! 4 + arr !! 5 \r\n then putStrLn \"YES\"\r\n else putStrLn \"NO\"\r\n for $ i - 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n for t"}], "negative_code": [], "src_uid": "c7a5b4a015e28dd3759569bbdc130e93"} {"source_code": "import Data.List (partition)\nsolve :: [Int] -> [[Int]]\nsolve (k:p:xs)\n | det < 0 = []\n | odd det = []\n | length evens + div det 2 < p = []\n | otherwise = (h ++ junk ++ junk') : t\n where (odds, evens) = partition odd xs\n det = length odds - k + p\n (useodd, rest) = splitAt (k - p) odds\n (paired, junk) = splitAt (p * 2) rest\n (useeven, junk') = splitAt req evens\n req = p - div (length paired) 2\n (h:t) = makeListed useodd ++ pairChunks paired ++ makeListed useeven\npairChunks [] = []\npairChunks (x:y:s) = [x,y] : pairChunks s\nmakeListed = map (:[])\noutput xs = if null xs then \"NO\\n\" else unlines (\"YES\" : map parted xs)\n where parted ps = (unwords . map show) (length ps : ps)\nmain = interact $ output.solve.map read.tail.words", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\n\nmain = interact $ maybe \"NO\" ((\"YES\\n\" ++ ) . unlines . map (unwords . map show)) . getAns . map read . words\n\ngetAns :: [Int] -> Maybe [[Int]]\ngetAns (_:k:p:xs) = getGroup (k - p) k $ partition even xs\n\ngetGroup :: Int -> Int -> ([Int], [Int]) -> Maybe [[Int]]\ngetGroup _ n ([], []) | n > 0 = Nothing\ngetGroup t _ (_, []) | t > 0 = Nothing\ngetGroup t 1 (es, os) = \n\tif (odd $ length os + t) then Nothing\n\telse Just [(length es + length os):(es ++ os)]\ngetGroup 0 n ([], o1:o2:os) = fmap ([2, o1, o2] :) $ getGroup 0 (n - 1) ([], os)\ngetGroup 0 n (e:es, os) = fmap ([1, e] :) $ getGroup 0 (n - 1) (es, os)\ngetGroup t n (es, o:os) = fmap ([1, o] :) $ getGroup (t - 1) (n - 1) (es, os)\n\n\n\n\n\n\n\n\n"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = interact $ maybe \"NO\" ((\"YES\\n\" ++ ) . unlines . map (unwords . map show . addLength)) . getAns . map read . words\n\naddLength :: [Int] -> [Int]\naddLength a = (length a) : a\n\ngetAns :: [Int] -> Maybe [[Int]]\ngetAns (_:k:p:xs) = getGroup (k - p) k $ partition even xs\n\ngetGroup :: Int -> Int -> ([Int], [Int]) -> Maybe [[Int]]\ngetGroup _ n ([], []) | n > 0 = Nothing\ngetGroup t _ (_, []) | t > 0 = Nothing\ngetGroup t 1 (es, os) = \n\tif (odd $ length os + t) then Nothing\n\telse Just [es ++ os]\ngetGroup 0 n ([], o1:o2:os) = fmap ([o1, o2] :) $ getGroup 0 (n - 1) ([], os)\ngetGroup 0 n (e:es, os) = fmap ([e] :) $ getGroup 0 (n - 1) (es, os)\ngetGroup t n (es, o:os) = fmap ([o] :) $ getGroup (t - 1) (n - 1) (es, os)\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = interact $ maybe \"NO\" ((\"YES\\n\" ++ ) . unlines . map (unwords . map show)) . getAns . map read . words\n\ngetAns :: [Int] -> Maybe [[Int]]\ngetAns (_:k:p:xs) = getGroup (k - p) k $ partition even xs\n\ngetGroup :: Int -> Int -> ([Int], [Int]) -> Maybe [[Int]]\ngetGroup _ n ([], []) | n > 0 = Nothing\ngetGroup t _ (_, []) | t > 0 = Nothing\ngetGroup t 1 (es, os) = \n\tif (odd $ sum os + sum es + t) then Nothing\n\telse Just [(length es + length os):(es ++ os)]\ngetGroup 0 n ([], o1:o2:os) = fmap ([2, o1, o2] :) $ getGroup 0 (n - 1) ([], os)\ngetGroup 0 n (e:es, os) = fmap ([1, e] :) $ getGroup 0 (n - 1) (es, os)\ngetGroup t n (es, o:os) = fmap ([1, o] :) $ getGroup (t - 1) (n - 1) (es, os)\n\n\n\n\n\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,k,p] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getContents\n case solve n k p xs of\n Nothing -> putStrLn \"NO\"\n Just xss\n | length xss /= k -> putStrLn \"NO\"\n | otherwise -> do\n putStrLn \"YES\"\n putStr.unlines $ map (\\xs-> unwords.map show$length xs:xs) xss\n\nsolve :: Int -> Int -> Int -> [Int] -> Maybe [[Int]]\nsolve n k p xs\n | 0<=q && q <= k && q<= numOdd && even (numOdd - q) = Just $ f (map return ys ++ rest) (concat rest')\n | otherwise = Nothing\n where\n !q = k - p\n (evens, odds) = partition even xs\n !numEven = length evens\n !numOdd = n - numEven\n (ys, zs) = splitAt q odds\n (rest, rest') = splitAt (k-q) $ chunksOf 2 zs ++ map return evens\n f (xs:xss) ys = (xs++ys) : xss\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n = map(take n).takeWhile(not.null).iterate(drop n)"}, {"source_code": "import Data.List\nimport Control.Monad\nq l=unwords$map show$length l:l\npairs(a:b:l)=[a,b]:pairs l\npairs[]=[]\n\nsolve l needOdds needEvens = do\n guard (length oddsNeeded == needOdds)\n guard (even $ length oddsSpare)\n guard (length evensNeeded == needEvens)\n return result\n where\n (odds, evens) = partition odd l\n (oddsNeeded, oddsSpare) = splitAt needOdds odds\n oddPairs = pairs oddsSpare\n evenGroups = oddPairs ++ map (:[]) evens\n spareEvens = concat (drop needEvens evenGroups)\n evensNeeded = take needEvens evenGroups\n resultsNeeded = map (:[]) oddsNeeded ++ evensNeeded\n result = init resultsNeeded ++ [last resultsNeeded ++ spareEvens]\n \n\ns(_:k:p:l) = case solve l (k - p) p of\n Nothing -> [\"NO\"]\n Just l -> \"YES\" : map q l\n\nmain=interact$unlines.s.map read.words\n"}], "negative_code": [{"source_code": "import Data.List (partition)\nsolve :: [Int] -> [[Int]]\nsolve (k:p:xs)\n | det < 0 = []\n | odd det = []\n | length evens + div det 2 < p = []\n | otherwise = (h ++ junk ++ junk') : t\n where (odds, evens) = partition odd xs\n det = length odds - k + p\n (useodd, rest) = splitAt (k - p) odds\n (paired, junk) = splitAt (det * 2) rest\n (useeven, junk') = splitAt (p - det * 2) evens\n (h:t) = makeListed useodd ++ pairChunks paired ++ makeListed useeven\npairChunks [] = []\npairChunks (x:y:s) = [x,y] : pairChunks s\nmakeListed = map (:[])\noutput xs = if null xs then \"NO\\n\" else unlines (\"YES\" : map parted xs)\n where parted ps = (unwords . map show) (length ps : ps)\nmain = interact $ output.solve.map read.tail.words"}, {"source_code": "import Data.List\nq l=unwords$map show$length l:l\npairs(a:b:l)=[a,b]:pairs l\npairs[]=[]\ns(_:k:p:l)|length x0=\"YES\":(map q$map(:[])x++take(p-1)w++[concat$drop(p-1)w])where z=k-p;(o,e)=partition odd l;(x,y)=splitAt z o;w=pairs y++map(:[])e\nmain=interact$unlines.s.map read.words\n"}, {"source_code": "import Data.List\nq l=unwords$map show$length l:l\npairs(a:b:l)=[a,b]:pairs l\npairs[]=[]\ns(_:k:p:l)|length x0=\"YES\":(map q$map(:[])x++take(p-1)w++[concat$drop(p-1)w])where z=k-p;(o,e)=partition odd l;(x,y)=splitAt z o;w=pairs y++map(:[])e\nmain=interact$unlines.s.map read.words\n"}], "src_uid": "5185f842c7c24d4118ae3661f4418a1d"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n a <- getInts n\n let\n y = minimum a\n ans = take (quot n 2) [[x, y] | x <- a, y /= x]\n pure $ foldMap putInts ans\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\nimport Text.Printf\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- getInts\n let x = minimum as\n ys = take (n `div` 2) $ filter (/= x) as\n return $ mconcat $ map (\\y -> string7 $ printf \"%d %d\\n\" y x) ys\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "6d5ecac49fe1320eef1391b6d5cf5f0d"} {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n print (4+3*n)\n forM_ (solve n) (putStrLn.unwords.map show)\n\nf :: Int -> [[Int]]\nf n = [[n,n],[n-1,n],[n,n-1]]\n\nsolve :: Int -> [[Int]]\nsolve n = [0,0]: concatMap f [1..n+1]\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Tuple\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nmain = do\n input <- getLine\n let n = read input :: Int\n func i = [(i, i), (i, i-1), (i-1, i)]\n res = ([(0, 0)] : (func <$> [1..n+1])) >>= id\n putStrLn $ show $ length res\n sequence_ $ putStrLn <$> (\\(a, b) -> show a ++ \" \" ++ show b) <$> res\n"}], "negative_code": [], "src_uid": "d87c40ae942f3c378bde372f3320a09f"} {"source_code": "main :: IO ()\nmain = solve . parse =<< getContents\n\nparse :: String -> (Double, Double, Double)\nparse line = (a, b, c) where [a, b, c] = map read . words $ line\n\nsolve :: (Double, Double, Double) -> IO ()\nsolve (a, b, c)\n | a < 0 = solve (-a, -b, -c)\n | otherwise = do { let delta = sqrt $ b * b - 4 * a * c\n ; print $ (-b + delta) / (2 * a)\n ; print $ (-b - delta) / (2 * a)\n }\n", "positive_code": [{"source_code": "module Main where\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\n--main--\nmain::IO()\nmain = do \n line <- readInts \n let a = line !! 0\n let b = line !! 1\n let c = line !! 2\n let delta = b ^ 2 - 4*a*c\n let x_1 = (fromIntegral(-b) - sqrt(fromIntegral delta))/ fromIntegral(2*a)\n let x_2 = (fromIntegral(-b) + sqrt(fromIntegral delta))/ fromIntegral(2*a)\n \n if x_1 > x_2\n\t then do print x_1;\n\t print x_2;\n else do print x_2;\n print x_1\n \n \n "}, {"source_code": "import Control.Monad\nimport Numeric \n\nmain = do\n [a,b,c] <- liftM (map read . words) (getLine) :: IO [Double]\n let d = sqrt $ b*b - 4*a*c\n let x1 = (-b+d)/(2*a)\n let x2 = (-b-d)/(2*a)\n putStrLn $ formatFloatN 15 $ max x1 x2\n putStrLn $ formatFloatN 15 $ min x1 x2\nformatFloatN numOfDecimals floatNum= showFFloat (Just numOfDecimals) floatNum \"\""}, {"source_code": "import Control.Applicative\nimport Data.Char\n\n \n\n \n\n\nmain= do\n\t[a,b,c]<- map read.words <$> getLine ::IO [Int]\n\tlet p1 = (sqrt (fromIntegral (b*b-4*a*c))) / 2.0 / (fromIntegral a)\n\tlet p2= (-(fromIntegral b))/2.0 / (fromIntegral a)\n\tlet r1= p2-p1\n\tlet r2= p2+p1\n\tprint $ max r1 r2\n\tprint $ min r1 r2"}, {"source_code": "module Main where\n\n\nmain :: IO ()\nmain = getLine >>= \\x -> f . map read . words $ x\n where f a = let solv = g (a !! 0) (a !! 1) (a !! 2) in (putStrLn.show.fst$solv) >> (putStrLn.show.snd$solv)\n g a b c = let delta = b ^ 2 - 4 * a * c in ((-b + (sgn a) * sqrt delta) / 2 / a, (-b - (sgn a) * sqrt delta) / 2 / a)\n sgn x | x < 0 = -1 | x > 0 = 1 | otherwise = 0\n"}], "negative_code": [{"source_code": "module Main where\n\n\nmain :: IO ()\nmain = getLine >>= \\x -> f . map read . words $ x\n where f a = let solv = g (a !! 0) (a !! 1) (a !! 2) in (putStrLn.show.fst$solv) >> (putStrLn.show.snd$solv)\n g a b c = let delta = b ^ 2 - 4 * a * c in ((-b + sqrt delta) / 2 / a, (-b - sqrt delta) / 2 / a)\n"}, {"source_code": "module Main where\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\n--main--\nmain::IO()\nmain = do \n line <- readInts \n let a = line !! 0\n let b = line !! 1\n let c = line !! 2\n let delta = b ^ 2 - 4*a*c\n let x_1 = (fromIntegral(b) + sqrt(fromIntegral delta))/ fromIntegral(2*a)\n let x_2 = (fromIntegral(-b) + sqrt(fromIntegral delta))/ fromIntegral(2*a)\n print x_1 \n print x_2"}, {"source_code": "module Main where\n \nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\n--main--\nmain::IO()\nmain = do \n line <- readInts \n if length(line) < 3 && length(line) >= 4\n then putStr \"3 parameters please, a, b and c \\n\"\n else putStr \"correct input \\n\";\n putStr \"well \\n\"\n let a = line !! 0\n let b = line !! 1\n let c = line !! 2\n let delta = b ^ 2 - 4*a*c\n if delta >= 0 \n then putStr \"real roots! \\n\"\n else putStr \"bad input, complex roots \\n\"\n let x_1 = (fromIntegral(b) + sqrt(fromIntegral delta))/ fromIntegral(2*a)\n let x_2 = (fromIntegral(-b) + sqrt(fromIntegral delta))/ fromIntegral(2*a)\n print x_1 \n print x_2\n \n \n \n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c] <- liftM (map read . words) (getLine) :: IO [Double]\n let d = sqrt $ b*b - 4*a*c\n putStrLn $ show $ (-b+d)/(2*a)\n putStrLn $ show $ (-b-d)/(2*a)"}, {"source_code": "main :: IO ()\nmain = solve . parse =<< getContents\n\nparse :: String -> (Double, Double, Double)\nparse line = (a, b, c) where [a, b, c] = map read . words $ line\n\nsolve :: (Double, Double, Double) -> IO ()\nsolve (a, b, c)\n | a < 0 = solve (-a, -b, -c)\n | otherwise = do { let delta = sqrt $ b * b - 4 * a * c\n ; print $ (-b - delta) / (2 * a)\n ; print $ (-b + delta) / (2 * a)\n }\n"}], "src_uid": "2d4ad39d42b349765435b351897403da"} {"source_code": "import Data.Int\nimport Data.Char\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as C\n\nfst' :: (a, b, c) -> a\nfst' (x,_,_) = x\n\nsnd' :: (a, b, c) -> b\nsnd' (_,x,_) = x\n\ntrd' :: (a, b, c) -> c\ntrd' (_,_,x) = x\n\nf2read' :: Int64 -> Char -> Int64\nf2read' x y = 10 * x + fromIntegral(ord y - ord '0')\n\nf2read :: C.ByteString -> Int64\nf2read x = C.foldl' f2read' 0 x\n\nf2show :: Int64 -> C.ByteString\nf2show x = C.reverse $ C.cons '\\n' $ fst $ C.unfoldrN 20 (\\x -> if x /= 0 then Just (chr $ ((fromIntegral (rem x 10)) :: Int) + ord '0', div x 10) else Nothing) x\n\nf2lines :: C.ByteString -> [C.ByteString]\nf2lines x = map (\\x -> if (C.last x == '\\r') then (C.init x) else x) (C.lines x)\n\ntuple3 :: [a] -> (a, a, a)\ntuple3 [x, y, z] = (x, y, z)\n\nreadP :: [C.ByteString] -> [(Int64, Int64, Int64)]\nreadP [] = []\nreadP (x:xs) = (tuple3 $ map f2read $ C.words x) : (readP xs)\n\nallEq :: (Eq a) => [a] -> Bool\nallEq ls = and $ map (== (head ls)) ls\n\ndivByGCD :: [Int64] -> [Int64]\ndivByGCD ls = map (`div` g) ls where g = foldl1' (gcd) ls\n\ndivisors :: Int64 -> Int64\ndivisors n = foldl1' (+) $ map (\\x -> if x * x == n then 1 else 2) $ filter (\\x -> rem n x == 0) $ takeWhile(\\x -> x * x <= n) [1..]\n\nsolve' :: [[Int64]] -> Int64\nsolve' ls = if allEq (map divByGCD ls) then divisors (foldl1' (gcd) (map (foldl1' gcd) ls)) else 0\n\nsolve :: [(Int64, Int64, Int64)] -> Int64\nsolve p =\n let n = length p\n sp = sort p\n m = length $ takeWhile (\\x -> (fst' $ head sp) == (fst' x)) sp\n csp = chunksOf m sp\n in if (rem n m == 0) && (allEq $ map (map snd') csp) then solve' (map (map trd') csp) else 0\n\nmain :: IO ()\nmain = do dat <- C.getContents\n print $ solve $ readP $ tail $ f2lines dat", "positive_code": [{"source_code": "import Data.Int\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nfst' :: (a, b, c) -> a\nfst' (x,_,_) = x\n\nsnd' :: (a, b, c) -> b\nsnd' (_,x,_) = x\n\ntrd' :: (a, b, c) -> c\ntrd' (_,_,x) = x\n\nf2read' :: Int64 -> Char -> Int64\nf2read' x y = 10 * x + fromIntegral(ord y - ord '0')\n\nf2read :: C.ByteString -> Int64\nf2read x = C.foldl' f2read' 0 x\n\nf2show :: Int64 -> C.ByteString\nf2show x = C.reverse $ C.cons '\\n' $ fst $ C.unfoldrN 20 (\\x -> if x /= 0 then Just (chr $ ((fromIntegral (rem x 10)) :: Int) + ord '0', div x 10) else Nothing) x\n\nf2lines :: C.ByteString -> [C.ByteString]\nf2lines x = map (\\x -> if (C.last x == '\\r') then (C.init x) else x) (C.lines x)\n\ntuple3 :: [a] -> (a, a, a)\ntuple3 [x, y, z] = (x, y, z)\n\nreadP :: [C.ByteString] -> [(Int64, Int64, Int64)]\nreadP [] = []\nreadP (x:xs) = (tuple3 $ map f2read $ C.words x) : (readP xs)\n\nallEq :: (Eq a) => [a] -> Bool\nallEq ls = and $ map (== (head ls)) ls\n\ndivByGCD :: [Int64] -> [Int64]\ndivByGCD ls = map (`div` g) ls where g = foldl1' (gcd) ls\n\ndivisors :: Int64 -> Int64\ndivisors n = foldl1' (+) $ map (\\x -> if x * x == n then 1 else 2) $ filter (\\x -> rem n x == 0) $ takeWhile(\\x -> x * x <= n) [1..]\n\nsolve' :: [[Int64]] -> Int64\nsolve' ls = if allEq (map divByGCD ls) then divisors (foldl1' (gcd) (map (foldl1' gcd) ls)) else 0\n\nbuild :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]\nbuild g = g (:) []\n\nchunksOf :: Int -> [e] -> [[e]]\nchunksOf i ls = map (take i) (build (splitter ls)) where\n splitter :: [e] -> ([e] -> a -> a) -> a -> a\n splitter [] _ n = n\n splitter l c n = l `c` splitter (drop i l) c n \n\nsolve :: [(Int64, Int64, Int64)] -> Int64\nsolve p =\n let n = length p\n sp = sort p\n m = length $ takeWhile (\\x -> (fst' $ head sp) == (fst' x)) sp\n csp = chunksOf m sp\n in if (rem n m == 0) && (allEq $ map (map snd') csp) then solve' (map (map trd') csp) else 0\n\nmain :: IO ()\nmain = do dat <- C.getContents\n print $ solve $ readP $ tail $ f2lines dat"}], "negative_code": [], "src_uid": "9202022089083f17e7165c6c1e53f2e1"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nprocess a = (min ao ae)\n\twhere ae = length $ filter (even) a\n\t ao = (length a)-ae\n\nmain::IO ()\nmain=do\n t<- read<$> getLine ::IO Int\t\n a<- map read <$> words <$> getLine::IO [Integer] \n print $ process a \n\n", "positive_code": [{"source_code": "import Data.List (partition)\n\nprocess :: [Int] -> Int\nprocess xs = min (length es) (length os)\n where\n (es,os) = partition odd xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "module Main where\n\ntoOnePoint :: [Int] -> Int -> Int\ntoOnePoint t point = sum (map (\\x -> abs (point - x) `mod` 2) t)\n\nmain :: IO ()\nmain = do\n f <- getLine\n let n = read f :: Int\n list <- fmap (\\i -> read i :: Int) . words <$> getLine\n print $ minimum (map (toOnePoint list) list)\n"}, {"source_code": "(...) = (.).(.)\ncountIf = length...filter\nsolve = min <$> countIf even <*> countIf odd\nmain = print . solve . map read . words . last . lines =<< getContents"}, {"source_code": "solve xs = min (length . filter even $ xs) (length . filter odd $ xs)\n\nmain = interact $ show . solve . map read . words . last . lines"}, {"source_code": "main :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- map read . words <$> getLine :: IO [Int]\n print $ min (countOdd xs) (countEven xs)\n where\n countEven xs = length $ filter (\\x -> mod x 2 == 0) xs\n countOdd xs = length (filter (\\x -> mod x 2 == 1) xs)\n\n"}, {"source_code": "getD::Int->Int->Int\ngetD m z=(max m z) - (min m z)\n\ngetOst::Int->Int->Int\ngetOst to p=mod (getD to p) 2\n\ngetOstL::Int->[Int]->Int\ngetOstL n lst=sum $ map (getOst n) lst\n\ngetMinL::[Int]->Int\ngetMinL lst=minimum $ map (flip getOstL lst) lst\n\nmain::IO()\nmain=do\n n <- getLine\n m <- getLine\n let lst = map read $ words m\n print $ getMinL lst\n"}, {"source_code": "getD::Int->Int->Int\ngetD m z=(max m z) - (min m z)\n\ngetOst::Int->Int->Int\ngetOst to p=mod (getD to p) 2\n\ngetOstL::Int->[Int]->Int\ngetOstL n lst=sum $ map (getOst n) lst\n\ngetMinL::[Int]->Int\ngetMinL lst=minimum $ map (flip getOstL lst) lst\n\nmain::IO()\nmain=do\n n <- getLine\n m <- getLine\n let lst = map read $ words m\n print $ getMinL lst\n--ss\n"}, {"source_code": "import Control.Monad ( void )\n\nmain = do\n void getLine\n arr <- fmap (fmap read . words) getLine\n let count = (length . ) . filter\n oddCount = count odd arr\n evenCount = count even arr\n print $ min evenCount oddCount"}, {"source_code": "main = do\n n <- readLn\n arr <- fmap (fmap read . words) getLine\n let count = (length . ) . filter\n oddCount = count odd arr\n evenCount = n - oddCount\n print $ min evenCount oddCount"}], "negative_code": [{"source_code": "import Data.List (sort, partition)\n\nprocess :: [Int] -> Int\nprocess xs = d * min (length es) (length os)\n where\n (es,os) = partition odd xs\n xs' = sort xs\n ds = filter odd $ zipWith (-) (tail xs') xs'\n d = if null ds then 0 else minimum ds\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.List (nub, partition)\n\nprocess :: [Int] -> Int\nprocess xs = minimum ds * min (length es) (length os)\n where\n (es,os) = partition odd xs\n xs' = nub xs\n ds = zipWith (-) (tail xs') xs'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "main :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- map read . words <$> getLine :: IO [Int]\n print $ max (countOdd xs) (countEven xs)\n where\n countEven xs = length $ filter (\\x -> mod x 2 == 0) xs\n countOdd xs = length (filter (\\x -> mod x 2 == 1) xs)\n\n"}], "src_uid": "a0a6cdda2ce201767bf5418f445a44eb"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n \nimport Control.Monad\nimport Prelude as P\n \nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n \nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n \nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n \ncolor _ _ _ _ _ [] = []\ncolor k col e ecnt total (x:xs)\n | total == 0 = (fst x, 0) : color k 0 0 0 0 xs\n | e == snd x = if ecnt >= k then (fst x, 0) : color k col e ecnt total xs else\n (fst x, col) : color k next_col e (ecnt+1) (total-1) xs\n | otherwise = (fst x, col) : color k next_col (snd x) 1 (total-1) xs\n where next_col = if col == k then 1 else col+1\n \nsolve :: IO ()\nsolve = do\n [n,k] <- readInts :: IO [Int]\n a <- readInts :: IO [Int]\n let b = sortBy (\\x y -> compare (snd x) (snd y)) $ zip [0..] a\n grp = groupBy (\\x y -> snd x == snd y) b\n tot = foldl (\\acc xs -> acc + min (length xs) k) 0 grp\n total = tot - (rem tot k)\n res = map snd $ sortBy (\\x y -> compare (fst x) (fst y)) $ color k 1 0 0 total b\n in putStrLn $ intercalate \" \" $ map show res\n \n \n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n \n----------------------------------------------------------------------------------------\nreadrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadrows 0 = return []\nreadrows n = do\n row <- readInts\n l <- readrows $ n-1\n return (row : l)\n \nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n \nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\nimport Data.List (intercalate, sort, group, groupBy)\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\ntype Color = Int\ntype Letter = Int\ntype AssignmentLC = Map Letter [Color]\ntype AssignmentCL = Map Color [Letter]\ntype Input = (Int, Int, [Int])\ntype Output = [Int]\n\ntype Queue a = ([a], [a])\n\nqueueToList :: Queue a -> [a]\nqueueToList (fstQ, sndQ) = fstQ ++ reverse sndQ\n\nqueueFromList :: [a] -> Queue a\nqueueFromList ls = (ls, [])\n\nqueueFix :: Queue a -> Queue a\nqueueFix (fstQ, sndQ) = if null fstQ then (reverse sndQ, []) else (fstQ, sndQ)\n\nqueuePush :: Queue a -> a -> Queue a\nqueuePush q0 x = (fst q1, x : snd q1) where\n q1 = queueFix q0\n\nqueuePop :: Queue a -> Queue a\nqueuePop q0 = (tail $ fst q1, snd q1) where\n q1 = queueFix q0\n\nqueueFront :: Queue a -> a\nqueueFront = head . fst . queueFix\n\nqueueSize :: Queue a -> Int\nqueueSize (fstQ, sndQ) = length fstQ + length sndQ\n\nqueueNull :: Queue a -> Bool\nqueueNull (fstQ, sndQ) = null fstQ && null sndQ\n\nparseOut :: [Output] -> String\nparseOut [] = \"\"\nparseOut (o:os) = unwords (map show o) ++ \"\\n\" ++ parseOut os\n\nparseIn :: String -> [Input]\nparseIn str = let\n inLines = tail $ lines str\n res [] = []\n res [x] = undefined\n res (nk:s:rest) = (n, k, l) : res rest where\n (n, k) = (read . (!!0) $ words nk, read . (!!1) $ words nk)\n l = map (read :: String -> Int) $ words s\n in res inLines\n\nnTimes :: Int -> (a -> a) -> (a -> a)\nnTimes 0 _ = id\nnTimes n f = f . nTimes (n - 1) f\n\ninvert :: (Ord k, Ord b) => Map k [b] -> Map b [k]\ninvert mp = Map.fromList\n $ map (\\l -> (fst $ head l, map snd l))\n $ groupBy (\\x y -> fst x == fst y)\n $ sort\n $ Map.toList mp >>= (\\(k, vs) -> map (, k) vs)\n\nsolve :: Input -> Output\nsolve (n, k, l) = res where\n freq = map (\\g -> (head g, length g)) $ group $ sort l\n cl0 = Map.fromList\n $ queueToList\n $ foldr append initQueue freq where\n initQueue = queueFromList $ zip [1..k] (repeat [])\n append :: (Int, Int) -> Queue (Color, [Letter]) -> Queue (Color, [Letter])\n append (ch, frq) q = nTimes (min k frq) f q where\n f q = let (col, ls) = queueFront q\n newAssign = (col, ch:ls)\n in queuePop $ queuePush q newAssign\n\n assignLength = foldr (min . length) n cl0\n cl1 = Map.map (take assignLength) cl0\n lc = invert cl1\n\n res = snd $ foldr f (lc, []) l where\n f :: Letter -> (AssignmentLC, [Color]) -> (AssignmentLC, [Color])\n f ch (as, l) = case Map.lookup ch as of Nothing -> (as, 0:l)\n Just [] -> (as, 0:l)\n Just cols -> (Map.adjust tail ch as, head cols : l)\n\nmain :: IO ()\nmain = interact $ parseOut . map solve . parseIn\n--main = interact (intercalate \"\\n------\\n\" . map solve . parseIn)"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out)\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && printf '%s\\n' 1 '12 3' '3 1 1 1 1 10 3 10 10 2 8 7' | ./a.out)\n-- 2 1 2 3 0 3 3 0 0 1 2 1\n\nimport Prelude\nimport Control.Monad\nimport Data.List\nimport Data.Function\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t readTC\n\n (putStr . unlines . map solve) tcs\n\nreadTC = do\n [_n, k] <- getInts\n nums <- getInts\n\n return (k, nums)\n\nsolve (k, xs) = intercalate \" \" . map show $ answer\n where\n grouped = groupOn fst . sort . (`zip` [1000::Int ..]) $ xs\n answer = solveColored k . solveUncolored k $ grouped\n\nsolveUncolored k gs = (map (addColor col0) . concat $ ts,\n concat hs)\n where\n (hs, ts) = unzip . map (splitAt k) $ gs\n\nsolveColored k (ps, xs) = map getColor . sortOn getPos $ coloring\n where\n coloring = ps ++ map (addColor col0) ts ++ zipWith addColor cols hs\n\n wdt = length xs `div` k\n (hs, ts) = splitAt (k*wdt) xs\n cols = (concat.repeat) [col0+1..col0+k]\n\naddColor c (v,i) = (v, i, c::Int)\ngetPos (_v, i, _c) = i\n-- getVal (v, _i, _c) = v\ngetColor (_v, _i, c) = c\n\ncol0 = 0::Int\n\n----------------------------------------\n\ngetInts = map read <$> words <$> getLine :: IO [Int]\n\ngroupOn f = groupBy ((==) `on` f)\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (group, sort, groupBy, sortBy)\r\nimport Data.Ord (comparing)\r\nimport Data.Bifunctor (bimap)\r\nimport Debug.Trace (trace)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> chunksOf 2\r\n >>> map (map words >>> concat >>> map read >>> solve >>> map show >>> unwords)\r\n >>> unlines\r\n\r\ntype Col = (Int, Maybe Int)\r\n\r\ndebug a = trace (show a) a\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve (n : k : as) =\r\n map (maybe 0 ((1 +) . (`mod` k)) . snd)\r\n . sortOn fst\r\n . uncurry (++)\r\n . bimap (`zip` (Just <$> [1..])) (`zip` repeat Nothing)\r\n . (\\(cs, ws) -> let (ws', cs') = splitAt (length cs `mod` k) cs in (cs', ws' ++ ws))\r\n . bimap' concat\r\n . unzip\r\n . map (splitAt k . map snd)\r\n . groupOn fst\r\n . sortOn fst\r\n $ as `zip` [0 ..]\r\n\r\n-- Template\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\ngroupOn :: (Eq b) => (a -> b) -> [a] -> [[a]]\r\ngroupOn p = groupBy (\\x y -> p x == p y)\r\n\r\nsortOn :: (Ord b) => (a -> b) -> [a] -> [a]\r\nsortOn = sortBy . comparing\r\n\r\nbimap' f = bimap f f\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (forM_)\nimport qualified Data.Array.Unboxed as A\nimport Data.Foldable (foldl')\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as M\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\n\nindexed :: [a] -> [(Int, a)]\nindexed = zip [0 ..]\n\n-- | Take a sequence of elements and convert into frequency mapping\ncollect :: [Int] -> IntMap [Int]\ncollect xs = foldl' ins_ M.empty $ indexed xs\n where\n ins_ m (i, n) = M.alter (Just . maybe [i] (i :)) n m\n\n-- | Take off elements from a list so that length is multiple of k\nshave :: Int -> [a] -> [a]\nshave k xs = drop (l `mod` k) xs\n where\n l = length xs\n\n-- | Perform coloring\ncoloring :: Int -> [Int] -> [Int]\ncoloring k xs = A.elems $ empty (length xs) A.// ind\n where\n m = collect xs\n (ltk, gtk) = M.partition (\\v -> length v < k) m\n\n indLtk = zip (shave k $ concat $ M.elems ltk) (cycle [1 .. k])\n indGtk = (`zip` [1 .. k]) . take k =<< M.elems gtk\n ind = indLtk ++ indGtk\n\n empty :: Int -> A.UArray Int Int\n empty n = A.array (0, n - 1) (take n $ indexed $ repeat 0)\n\nmain :: IO ()\nmain = do\n testCases <- read <$> getLine\n forM_ [1 .. testCases] $ \\_ -> do\n l1 <- T.getLine\n l2 <- T.getLine\n let [_, k] = read . T.unpack <$> T.splitOn \" \" l1\n let xs = read . T.unpack <$> T.splitOn \" \" l2\n putStrLn $ unwords $ show <$> coloring k xs\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List ((\\\\), foldl')\r\nimport qualified Data.Array.Unboxed as A\r\nimport qualified Data.IntMap as M\r\n\r\ngetIndices :: Int -> [Int] -> (M.IntMap [Int], [Int])\r\ngetIndices cap xs = (M.map snd withSizes, remaining) where\r\n insert (k, idx) (mp, remaining) = case M.lookup k mp of\r\n Just (size, idxs) -> if size + 1 <= cap \r\n then (M.insert k (size + 1, idx : idxs) mp, remaining)\r\n else (M.insert k (size, idxs) mp, idx : remaining)\r\n Nothing -> (M.insert k (1, [idx]) mp, remaining)\r\n (withSizes, remaining) = foldr insert (M.empty, []) $ zip xs [1..]\r\n\r\nsolve :: (Int, Int) -> [Int] -> M.IntMap Int\r\nsolve (n, k) xs = M.fromList (ans ++ [(i, 0) | i <- remaining]) where\r\n (indexMap, remaining) = getIndices k xs\r\n indices = M.toList indexMap >>= snd\r\n l = n - length remaining\r\n nextColor color = if color + 1 <= k then color + 1 else 1\r\n next (color, coloring, remaining) idx = let c = nextColor color in \r\n if remaining > 0 then (c, (idx, c) : coloring, remaining - 1)\r\n else (0, (idx, 0) : coloring, remaining)\r\n (_, ans, _) = foldl' next (0, [], l - l `rem` k) indices\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n [n, k] <- readInts\r\n ans <- map show . M.elems . solve (n, k) <$> readInts\r\n putStrLn $ unwords ans"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List ((\\\\), foldl')\r\nimport qualified Data.Array.Unboxed as A\r\nimport qualified Data.IntMap as M\r\nimport qualified Data.IntSet as S\r\n\r\ntype IntArray = A.UArray Int Int\r\n\r\ngetIndices :: Int -> [Int] -> M.IntMap [Int]\r\ngetIndices cap xs = M.map snd withSizes where\r\n insert (k, idx) mp = case M.lookup k mp of\r\n Just (size, idxs) -> if size + 1 <= cap \r\n then M.insert k (size + 1, idx : idxs) mp\r\n else M.insert k (size, idxs) mp\r\n Nothing -> M.insert k (1, [idx]) mp\r\n withSizes = foldr insert M.empty $ zip xs [1..]\r\n\r\nsolve :: (Int, Int) -> [Int] -> IntArray\r\nsolve (n, k) xs = A.array (1,n) (ans ++ [(i, 0) | i <- missing]) where\r\n indices = M.toList (getIndices k xs) >>= snd\r\n indexSet = S.fromList indices\r\n l = S.size indexSet\r\n nextColor color = if color + 1 <= k then color + 1 else 1\r\n next (color, coloring, remaining) idx = let c = nextColor color in \r\n if remaining > 0 then (c, (idx, c) : coloring, remaining - 1)\r\n else (0, (idx, 0) : coloring, remaining)\r\n (_, ans, _) = S.foldl' next (0, [], l - l `rem` k) indexSet\r\n missing = S.toList $ S.difference (S.fromList [1..n]) indexSet\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n [n, k] <- readInts\r\n ans <- map show . A.elems . solve (n, k) <$> readInts\r\n putStrLn $ unwords ans"}, {"source_code": "{-# LANGUAGE TupleSections #-}\nimport Data.List (intercalate, sort, group, groupBy)\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\ntype Color = Int\ntype Letter = Int\ntype AssignmentLC = Map Letter [Color]\ntype AssignmentCL = Map Color [Letter]\ntype Input = (Int, Int, [Int])\ntype Output = [Int]\n\ntype Queue a = ([a], [a])\n\nqueueToList :: Queue a -> [a]\nqueueToList (fstQ, sndQ) = fstQ ++ reverse sndQ\n\nqueueFromList :: [a] -> Queue a\nqueueFromList ls = (ls, [])\n\nqueueFix :: Queue a -> Queue a\nqueueFix (fstQ, sndQ) = if null fstQ then (reverse sndQ, []) else (fstQ, sndQ)\n\nqueuePush :: Queue a -> a -> Queue a\nqueuePush q0 x = (fst q1, x : snd q1) where\n q1 = queueFix q0\n\nqueuePop :: Queue a -> Queue a\nqueuePop q0 = (tail $ fst q1, snd q1) where\n q1 = queueFix q0\n\nqueueFront :: Queue a -> a\nqueueFront = head . fst . queueFix\n\nqueueSize :: Queue a -> Int\nqueueSize (fstQ, sndQ) = length fstQ + length sndQ\n\nqueueNull :: Queue a -> Bool\nqueueNull (fstQ, sndQ) = null fstQ && null sndQ\n\nparseOut :: [Output] -> String\nparseOut [] = \"\"\nparseOut (o:os) = unwords (map show o) ++ \"\\n\" ++ parseOut os\n\nparseIn :: String -> [Input]\nparseIn str = let\n inLines = tail $ lines str\n res [] = []\n res [x] = undefined\n res (nk:s:rest) = (n, k, l) : res rest where\n (n, k) = (read . (!!0) $ words nk, read . (!!1) $ words nk)\n l = map (read :: String -> Int) $ words s\n in res inLines\n\nnTimes :: Int -> (a -> a) -> (a -> a)\nnTimes 0 _ = id\nnTimes n f = f . nTimes (n - 1) f\n\ninvert :: (Ord k, Ord b) => Map k [b] -> Map b [k]\ninvert mp = Map.fromList\n $ map (\\l -> (fst $ head l, map snd l))\n $ groupBy (\\x y -> fst x == fst y)\n $ sort\n $ Map.toList mp >>= (\\(k, vs) -> map (, k) vs)\n\nsolve :: Input -> Output\nsolve (n, k, l) = res where\n freq = map (\\g -> (head g, length g)) $ group $ sort l\n cl = Map.fromList\n $ queueToList\n $ foldr append initQueue freq where\n initQueue = queueFromList $ zip [1..k] (repeat [])\n append :: (Int, Int) -> Queue (Color, [Letter]) -> Queue (Color, [Letter])\n append (ch, frq) q = nTimes (min k frq) f q where\n f q = let (col, ls) = queueFront q\n newAssign = (col, ch:ls)\n in queuePop $ queuePush q newAssign\n\n lc0 = invert cl\n assignLength = foldr (min . length) n lc0\n lc1 = Map.map (take assignLength) lc0\n\n res = snd $ foldr f (lc1, []) l where\n f :: Letter -> (AssignmentLC, [Color]) -> (AssignmentLC, [Color])\n f ch (as, l) = case Map.lookup ch as of Nothing -> (as, 0:l)\n Just [] -> (as, 0:l)\n Just cols -> (Map.adjust tail ch as, head cols : l)\n\nmain :: IO ()\nmain = interact $ parseOut . map solve . parseIn\n--main = interact (intercalate \"\\n------\\n\" . map solve . parseIn)"}, {"source_code": "import Data.List (intersperse, intercalate, sort, group)\n\nparseOut :: [Int] -> String\nparseOut = intercalate \"\\n\" . map show\n\nparseIn :: String -> [String]\nparseIn = tail . words\n\nsolve :: String -> Int\nsolve str = gtOne + div one 2 where\n frequencies = map length $ group $ sort str\n gtOne = length $ filter (>1) frequencies\n one = length $ filter (==1) frequencies\n\nmain :: IO ()\nmain = interact $ parseOut . map solve . parseIn\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\nimport Data.List\nimport Data.Function\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t readTC\n\n (putStr . unlines . map solve) tcs\n\nreadTC = do\n [_n, k] <- getInts\n nums <- getInts\n\n return (k, nums)\n\ngetInts = map read <$> words <$> getLine :: IO [Int]\n\n-- solve (k, xs) = show (k, xs, sortGroupOn snd $ indexed, intercalate \" \" . map show $ answer)\nsolve (k, xs) = intercalate \" \" . map show $ answer\n where\n indexed = zip [0..] xs :: [(Int,Int)]\n\n grouped = fixGroups . sortGroupOn snd $ indexed\n\n colored = concat . map (addColor k) $ grouped\n\n getPos ((p,_x), _i) = p\n\n answer = map snd . sortOn getPos $ colored\n\nfixGroups gs = filter (not.allowJoin) gs ++ [(concat . filter allowJoin) gs]\n where\n allowJoin g = length g == 1\n\naddColor k pairs | (length pairs >= k) = zip pairs ([1..k] ++ [0,0..])\n | otherwise = zip pairs [0,0..]\n\nsortGroupOn f = groupBy ((==) `on` f) . sortOn f\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (group, sort, groupBy, sortBy)\r\nimport Data.Ord (comparing)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> chunksOf 2\r\n >>> map (map words >>> concat >>> map read >>> solve >>> map show >>> unwords)\r\n >>> unlines\r\n\r\ntype Col = (Int, Maybe Int)\r\n\r\nsolve :: [Int] -> [Int]\r\nsolve (n : k : as) =\r\n map (maybe 0 ((1 +) . (`mod` k)) . snd)\r\n . sortOn fst\r\n . concatMap fst\r\n . scanr (color . map snd) ([], 0)\r\n . groupOn fst\r\n . sortOn fst\r\n $ as `zip` [0 ..]\r\n where\r\n color :: [Int] -> ([Col], Int) -> ([Col], Int)\r\n color ixs (_, c) =\r\n let (cixs, wixs) = splitAt k ixs\r\n in (zip cixs (Just <$> [c ..]) ++ zip wixs (repeat Nothing), c + length cixs)\r\n\r\n-- Template\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\ngroupOn :: (Eq b) => (a -> b) -> [a] -> [[a]]\r\ngroupOn p = groupBy (\\x y -> p x == p y)\r\n\r\nsortOn :: (Ord b) => (a -> b) -> [a] -> [a]\r\nsortOn = sortBy . comparing\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\ncolor _ _ _ _ _ [] = []\ncolor k col e ecnt total (x:xs)\n | total == 0 = (fst x, 0) : color k 0 0 0 0 xs\n | e == snd x = if ecnt >= k then (fst x, 0) : color k col e ecnt total xs else\n (fst x, col) : color k next_col e (ecnt+1) (total-1) xs\n | otherwise = (fst x, col) : color k next_col (snd x) 1 (total-1) xs\n where next_col = if col == k then 1 else col+1\n\nsolve :: IO ()\nsolve = do\n [n,k] <- readInts :: IO [Int]\n a <- readInts :: IO [Int]\n let b = sortBy (\\x y -> compare (snd x) (snd y)) $ zip [0..] a\n grp = groupBy (\\x y -> snd x == snd y) b\n total = foldl (\\acc xs -> acc + min (length xs) k) 0 grp\n res = map snd $ sortBy (\\x y -> compare (fst x) (fst y)) $ color k 1 0 0 total b\n in putStrLn $ intercalate \" \" $ map show res\n \n \n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadrows 0 = return []\nreadrows n = do\n row <- readInts\n l <- readrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}], "src_uid": "98aca7d5bf74c7787bf2159770054297"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n as <- A.newListArray (1, n) as_ :: IO (IOUArray Int Int)\n cs_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n customers <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)\n <$> BSL.getContents\n let cs = A.listArray (1, n) $ map fromIntegral cs_ :: UArray Int Int64\n is = A.listArray (1, n) $ sortBy (compare `on` (cs A.!)) [1..n]\n :: UArray Int Int\n kpres <- newIORef (1::Int)\n let serveDesperately d !acc = do\n k <- readIORef kpres\n go k d acc\n go k d !acc\n | k > n = return 0\n | otherwise = do\n (!val, !d2) <- tryToServe cs as (is A.! k) d\n if d2 <= 0 then return $! acc+val else do\n writeIORef kpres (k+1)\n go (k+1) d2 (acc+val)\n forM_ customers $ \\(t,d) -> do\n (!val, !d2) <- tryToServe cs as t d\n tot <- if d2 <= 0 then return val else serveDesperately d2 val\n print tot\n\ntryToServe :: UArray Int Int64 -> IOUArray Int Int -> Int -> Int\n -> IO (Int64,Int)\ntryToServe cost rest !t !d = do\n restT <- A.readArray rest t\n if restT >= d then do\n A.writeArray rest t $! (restT-d)\n return (cost A.! t * fromIntegral d, 0)\n else do\n A.writeArray rest t 0\n return (cost A.! t * fromIntegral restT, d-restT)\n\ntype Comparison e = e -> e -> Ordering\n\n\n{-# INLINE sortMArray #-}\nsortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)\n => a i e -> m ()\nsortMArray = sortMArrayBy compare\n\n{-# INLINE sortMArrayBy #-}\nsortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> m ()\nsortMArrayBy cmp = \\arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr\n\n\n-- sort the interval [l,u] of arr.\n{-# INLINE sortMArrayByBounds #-}\nsortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> (i,i) -> m ()\nsortMArrayByBounds cmp = \\arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)\n\n-- sort the interval [l,u) of arr.\n{-# INLINE sortMArrayByBounds_ #-}\nsortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> i -> i -> m ()\nsortMArrayByBounds_ cmp = \\arr l u -> do\n let len = u - l\n tmp <- A.newArray_ (0,len `shiftR` 1 - 1)\n mergesort cmp arr tmp l u\n\nmergesort cmp arr tmp l u\n | u - l <= 1 = return ()\n | otherwise = do mergesort cmp arr tmp l mid\n mergesort cmp arr tmp mid u\n merge cmp arr tmp l mid u\n where\n len = u - l\n mid = (u + l) `shiftR` 1\n\n{-# INLINE merge #-}\nmerge :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()\nmerge cmp arr tmp l mid u = do\n copyMArray arr (l,mid-1) tmp (0,mml-1)\n eLow <- A.readArray tmp 0\n eHigh <- A.readArray arr mid\n loop eLow 0 eHigh mid l\n where\n mml = mid - l\n loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of\n LT -> do A.writeArray arr iIns eHigh\n wroteHigh eLow iLow (iHigh+1) (iIns+1)\n _ -> do A.writeArray arr iIns eLow\n wroteLow (iLow+1) eHigh iHigh (iIns+1)\n wroteHigh !eLow !iLow !iHigh !iIns\n | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)\n | otherwise = do eHigh <- A.readArray arr iHigh\n loop eLow iLow eHigh iHigh iIns\n wroteLow !iLow !eHigh !iHigh !iIns\n | iLow >= mml = return ()\n | otherwise = do eLow <- A.readArray tmp iLow\n loop eLow iLow eHigh iHigh iIns\n\n{-# INLINE copyMArray #-}\ncopyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)\n => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()\ncopyMArray src srcRange dst dstRange =\n forM_ (zip (A.range srcRange) (A.range dstRange))\n $ \\(i,j) -> A.writeArray dst j =<< A.readArray src i\n \n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n as <- A.newListArray (1, n) as_ :: IO (IOUArray Int Int)\n cs_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n customers <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)\n <$> BSL.getContents\n let cs = A.listArray (1, n) $ map fromIntegral cs_ :: UArray Int Int64\n is = runSTUArray $ do\n is <- A.newListArray (1,n) [1..n]\n sortMArrayBy (\\i j -> compare (cs A.! i) (cs A.! j)) is\n return is\n kpres <- newIORef (1::Int)\n let serveDesperately d !acc = do\n k <- readIORef kpres\n go k d acc\n go !k !d !acc\n | k > n = return 0\n | otherwise = do\n (!val, !d2) <- tryToServe cs as (is A.! k) d\n if d2 <= 0 then return $! acc+val else do\n writeIORef kpres (k+1)\n go (k+1) d2 (acc+val)\n forM_ customers $ \\(!t,!d) -> do\n (!val, !d2) <- tryToServe cs as t d\n tot <- if d2 <= 0 then return val else serveDesperately d2 val\n print tot\n\ntryToServe :: UArray Int Int64 -> IOUArray Int Int -> Int -> Int\n -> IO (Int64,Int)\ntryToServe cost rest !t !d = do\n restT <- A.readArray rest t\n if restT >= d then do\n A.writeArray rest t $! (restT-d)\n return (cost A.! t * fromIntegral d, 0)\n else do\n A.writeArray rest t 0\n return (cost A.! t * fromIntegral restT, d-restT)\n\ntype Comparison e = e -> e -> Ordering\n\n\n{-# INLINE sortMArray #-}\nsortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)\n => a i e -> m ()\nsortMArray = sortMArrayBy compare\n\n{-# INLINE sortMArrayBy #-}\nsortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> m ()\nsortMArrayBy cmp = \\arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr\n\n\n-- sort the interval [l,u] of arr.\n{-# INLINE sortMArrayByBounds #-}\nsortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> (i,i) -> m ()\nsortMArrayByBounds cmp = \\arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)\n\n-- sort the interval [l,u) of arr.\n{-# INLINE sortMArrayByBounds_ #-}\nsortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> i -> i -> m ()\nsortMArrayByBounds_ cmp = \\arr l u -> do\n let len = u - l\n tmp <- A.newArray_ (0,len `shiftR` 1 - 1)\n mergesort cmp arr tmp l u\n\nmergesort cmp arr tmp l u\n | u - l <= 1 = return ()\n | otherwise = do mergesort cmp arr tmp l mid\n mergesort cmp arr tmp mid u\n merge cmp arr tmp l mid u\n where\n len = u - l\n mid = (u + l) `shiftR` 1\n\n{-# INLINE merge #-}\nmerge :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()\nmerge cmp arr tmp l mid u = do\n copyMArray arr (l,mid-1) tmp (0,mml-1)\n eLow <- A.readArray tmp 0\n eHigh <- A.readArray arr mid\n loop eLow 0 eHigh mid l\n where\n mml = mid - l\n loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of\n LT -> do A.writeArray arr iIns eHigh\n wroteHigh eLow iLow (iHigh+1) (iIns+1)\n _ -> do A.writeArray arr iIns eLow\n wroteLow (iLow+1) eHigh iHigh (iIns+1)\n wroteHigh !eLow !iLow !iHigh !iIns\n | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)\n | otherwise = do eHigh <- A.readArray arr iHigh\n loop eLow iLow eHigh iHigh iIns\n wroteLow !iLow !eHigh !iHigh !iIns\n | iLow >= mml = return ()\n | otherwise = do eLow <- A.readArray tmp iLow\n loop eLow iLow eHigh iHigh iIns\n\n{-# INLINE copyMArray #-}\ncopyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)\n => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()\ncopyMArray src srcRange dst dstRange =\n forM_ (zip (A.range srcRange) (A.range dstRange))\n $ \\(i,j) -> A.writeArray dst j =<< A.readArray src i\n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n as <- A.newListArray (1, n) as_ :: IO (IOUArray Int Int)\n cs_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let cs = A.listArray (1, n) cs_ :: UArray Int Int\n is = runSTUArray $ do\n is <- A.newListArray (1,n) [1..n]\n sortMArrayBy (\\i j -> compare (cs A.! i) (cs A.! j)) is\n return is\n kpres <- newIORef (1::Int)\n let serveDesperately d !acc = do\n k <- readIORef kpres\n go k d acc\n go k d !acc\n | k > n = return 0\n | otherwise = do\n (val, d2) <- tryToServe cs as (is A.! k) d\n if d2 <= 0 then return $! acc+val else do\n writeIORef kpres (k+1)\n go (k+1) d2 (acc+val)\n replicateM_ m $ do\n [t, d] <- map read . words <$> getLine\n (val, d2) <- tryToServe cs as t d\n tot <- if d2 <= 0 then return val else serveDesperately d2 val\n print tot\n\ntryToServe :: UArray Int Int -> IOUArray Int Int -> Int -> Int -> IO (Int,Int)\ntryToServe cost rest t d = do\n restT <- A.readArray rest t\n if restT >= d then do\n A.writeArray rest t (restT-d)\n return (cost A.! t * d, 0)\n else do\n A.writeArray rest t 0\n return (cost A.! t * restT, d-restT)\n\ntype Comparison e = e -> e -> Ordering\n\n\n{-# INLINE sortMArray #-}\nsortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)\n => a i e -> m ()\nsortMArray = sortMArrayBy compare\n\n{-# INLINE sortMArrayBy #-}\nsortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> m ()\nsortMArrayBy cmp = \\arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr\n\n\n-- sort the interval [l,u] of arr.\n{-# INLINE sortMArrayByBounds #-}\nsortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> (i,i) -> m ()\nsortMArrayByBounds cmp = \\arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)\n\n-- sort the interval [l,u) of arr.\n{-# INLINE sortMArrayByBounds_ #-}\nsortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> i -> i -> m ()\nsortMArrayByBounds_ cmp = \\arr l u -> do\n let len = u - l\n tmp <- A.newArray_ (0,len `shiftR` 1 - 1)\n mergesort cmp arr tmp l u\n\nmergesort cmp arr tmp l u\n | u - l <= 1 = return ()\n | otherwise = do mergesort cmp arr tmp l mid\n mergesort cmp arr tmp mid u\n merge cmp arr tmp l mid u\n where\n len = u - l\n mid = (u + l) `shiftR` 1\n\n{-# INLINE merge #-}\nmerge :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()\nmerge cmp arr tmp l mid u = do\n copyMArray arr (l,mid-1) tmp (0,mml-1)\n eLow <- A.readArray tmp 0\n eHigh <- A.readArray arr mid\n loop eLow 0 eHigh mid l\n where\n mml = mid - l\n loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of\n LT -> do A.writeArray arr iIns eHigh\n wroteHigh eLow iLow (iHigh+1) (iIns+1)\n _ -> do A.writeArray arr iIns eLow\n wroteLow (iLow+1) eHigh iHigh (iIns+1)\n wroteHigh !eLow !iLow !iHigh !iIns\n | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)\n | otherwise = do eHigh <- A.readArray arr iHigh\n loop eLow iLow eHigh iHigh iIns\n wroteLow !iLow !eHigh !iHigh !iIns\n | iLow >= mml = return ()\n | otherwise = do eLow <- A.readArray tmp iLow\n loop eLow iLow eHigh iHigh iIns\n\n{-# INLINE copyMArray #-}\ncopyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)\n => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()\ncopyMArray src srcRange dst dstRange =\n forM_ (zip (A.range srcRange) (A.range dstRange))\n $ \\(i,j) -> A.writeArray dst j =<< A.readArray src i\n \n"}], "src_uid": "2553ffea6d74fded12128e9db0db85dc"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\nimport qualified Data.Set as S\n\ncalc' :: S.Set (Int,Int) -> Int -> Int64 -> Int -> [Int] -> Int64\ncalc' _ _ cnt n [] = cnt\ncalc' tr i cnt n (y:ys) =\n let (left, _) = S.split (y,-1) tr\n (right, _) = S.split (y,n) tr\n leftSize = S.size left\n rightSize = i - (S.size right)\n cnt' = cnt + (fromIntegral (min leftSize rightSize))\n tr' = S.insert (y,i) tr\n in\n calc' tr' (i+1) cnt' n ys\n\ncalc :: Int -> [Int] -> Int64\ncalc = calc' S.empty 0 0\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let lst = map read $ words line :: [Int]\n print $ calc n lst\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\nimport qualified Data.Set as Set\nimport Data.Int\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n p <- getInts n\n let\n p2 = zip p [1..n]\n initVals = Set.fromList p2\n solve :: Set.Set (Int, Int) -> [(Int, Int)] -> Int64 -> Int64\n solve _nil [] cont = cont\n solve vals ((x, kx) : xs) cont = cont `seq` let\n (vl, _) = Set.split (x, minBound) vals\n (_, vr) = Set.split (x, maxBound) vals\n in solve (Set.delete (x, kx) vals) xs\n $ cont + fromIntegral (min (Set.size vl) (Set.size vr))\n pure $ putInt64s [solve initVals (reverse p2) 0]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ncalc' :: S.Set (Int,Int) -> Int -> Int -> Int -> [Int] -> Int\ncalc' _ _ cnt n [] = cnt\ncalc' tr i cnt n (y:ys) =\n let (left, _) = S.split (y,-1) tr\n (right, _) = S.split (y,n) tr\n leftSize = S.size left\n rightSize = i - (S.size right)\n cnt' = cnt + (min leftSize rightSize)\n tr' = S.insert (y,i) tr\n in\n calc' tr' (i+1) cnt' n ys\n\ncalc :: Int -> [Int] -> Int\ncalc = calc' S.empty 0 0\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let lst = map read $ words line :: [Int]\n print $ calc n lst\n"}], "src_uid": "aa78a750cac45117f7b4313928c50f76"} {"source_code": "-- Codeforces 1060 C\n\nimport Data.List\nimport Control.Monad\n\nsumUp :: [Integer] -> [Integer]\nsumUp = scanl (+) 0\n\n-- Find min sum of a list with n elements\nfindMinSum :: Int -> [Integer] -> Integer\nfindMinSum n list = minimum $ zipWith (-) (drop n list) list\n\n-- Find sums possible with different n consecutive elements added\nfindSums :: [Integer] -> [(Int, Integer)]\nfindSums list = map (\\n -> (n, findMinSum n $ sumUp list)) [1..length list]\n\nfindCombination :: [(Int, Integer)] -> [(Int, Integer)] -> Integer -> Int\nfindCombination aList bList val = case combinations of\n [] -> 0\n _ -> maximum combinations\n where combinations = do\n (an, ax) <- aList\n (bn, bx) <- bList\n guard $ ax * bx <= val\n return $ an * bn\n\nmain :: IO ()\nmain = do\n firstLine <- getLine\n aList <- getLine >>= \n return.(\\list -> map (read::String -> Integer) (words list))\n bList <- getLine >>= \n return.(\\list -> map (read::String -> Integer) (words list))\n x <- getLine >>= return.read\n putStrLn.show $ findCombination (findSums aList) (findSums bList) x\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n--import qualified Data.ByteString.Char8 as C\nimport Data.List\n--import Data.Maybe\n\nmain = sol <$> get <*> get <*> get <*> readLn >>= print\n\n--get = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine\nget = fmap read . words <$> getLine\n\nsol [n,m] as bs x = if null ps then 0 else maximum ps\n where\n mx = 2*10^9\n sa = listArray (0,n) $ scanl (+) 0 as\n sb = listArray (0,m) $ scanl (+) 0 bs\n da = accumArray min mx (1,n) [(j-i+1, sa!j-sa!(i-1)) | i <- [1..n], j <- [i..n]]\n db = accumArray min mx (1,m) [(j-i+1, sb!j-sb!(i-1)) | i <- [1..m], j <- [i..m]]\n ps = [i*j | i <- [1..n], j <- [1..m], da!i*db!j <= x]\n\n--mx = maxBound :: Int\nmx = 2*10^9\n--sa = listArray (0,n) $ scanl' (+) 0 as\n--sb = listArray (0,m) $ scanl' (+) 0 bs\nsa = listArray (0,n) $ scanl (+) 0 as\nsb = listArray (0,m) $ scanl (+) 0 bs\nda = accumArray min mx (1,n) [(j-i+1, sa!j-sa!(i-1)) | i <- [1..n], j <- [i..n]]\ndb = accumArray min mx (1,m) [(j-i+1, sb!j-sb!(i-1)) | i <- [1..m], j <- [i..m]]\nps = [i*j | i <- [1..n], j <- [1..m], da!i*db!j <= x]\nf = maximum ps\ndbg = [(i*j,i,j) | i <- [1..n], j <- [1..m], da!i*db!j <= x]\n\n--\n[n,m]=[3,3]\nas=[1,2,3]\nbs=[1,2,3]\nx=9\n{-\n[n,m]=[5,1]\nas=[5,4,2,4,5]\nbs=[2]\nx=5\n--\n\n[n,m]=[8,8]\nas=[2000,2000,2000,2000,2000,2000,2000,2000,2000] \nbs=[2000,2000,2000,2000,2000,2000,2000,2000,2000] \nx=9*10^9\n--Output\n--4000000\n--Answer\n--500\n\n-}"}], "negative_code": [{"source_code": "-- Codeforces 1060 C\n\nimport Data.List\nimport Control.Monad\n\nsumUp :: [Int] -> [Int]\nsumUp = scanl (+) 0\n\n-- Find min sum of a list with n elements\nfindMinSum :: Int -> [Int] -> Int\nfindMinSum n list = minimum $ zipWith (-) (drop n list) list\n\n-- Find sums possible with different n consecutive elements added\nfindSums :: [Int] -> [(Int, Int)]\nfindSums list = map (\\n -> (n, findMinSum n $ sumUp list)) [1..length list]\n\nfindCombination :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int\nfindCombination aList bList val = maximum $ do\n (an, ax) <- aList\n (bn, bx) <- bList\n guard $ ax * bx <= val\n return $ an * bn\n\nmain :: IO ()\nmain = do\n firstLine <- getLine\n aList <- getLine >>= \n return.(\\list -> map (read::String -> Int) (words list))\n bList <- getLine >>= \n return.(\\list -> map (read::String -> Int) (words list))\n x <- getLine >>= return.read\n putStrLn.show $ findCombination (findSums aList) (findSums bList) x\n"}, {"source_code": "-- Codeforces 1060 C\n\nimport Data.List\nimport Control.Monad\n\nsumUp :: [Int] -> [Int]\nsumUp = scanl (+) 0\n\n-- Find min sum of a list with n elements\nfindMinSum :: Int -> [Int] -> Int\nfindMinSum n list = minimum $ zipWith (-) (drop n list) list\n\n-- Find sums possible with different n consecutive elements added\nfindSums :: [Int] -> [(Int, Int)]\nfindSums list = map (\\n -> (n, findMinSum n $ sumUp list)) [1..length list]\n\nfindCombination :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int\nfindCombination aList bList val = case combinations of\n [] -> 0\n _ -> maximum combinations\n where combinations = do\n (an, ax) <- aList\n (bn, bx) <- bList\n guard $ ax * bx <= val\n return $ an * bn\n\nmain :: IO ()\nmain = do\n firstLine <- getLine\n aList <- getLine >>= \n return.(\\list -> map (read::String -> Int) (words list))\n bList <- getLine >>= \n return.(\\list -> map (read::String -> Int) (words list))\n x <- getLine >>= return.read\n putStrLn.show $ findCombination (findSums aList) (findSums bList) x\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\nmain = sol <$> get <*> get <*> get <*> readLn >>= print\n\nget = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nsol [n,m] as bs x = if null ps then 0 else maximum ps\n where\n mx = maxBound :: Int\n sa = listArray (0,n) $ scanl (+) 0 as\n sb = listArray (0,m) $ scanl (+) 0 bs\n da = accumArray min mx (1,n) [(j-i+1, sa!j-sa!(i-1)) | i <- [1..n], j <- [i..n]]\n db = accumArray min mx (1,m) [(j-i+1, sb!j-sb!(i-1)) | i <- [1..m], j <- [i..m]]\n ps = [i*j| i <- [1..n], j <- [1..m], da!i*db!j <= x]\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\nmain = sol <$> get <*> get <*> get <*> readLn >>= print\n\nget = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nsol [n,m] as bs x = if null ps then 0 else maximum ps\n where\n a = listArray (1,n) (sort as)\n b = listArray (1,m) (sort bs)\n c = array ((0,0),(n,m)) $ ((0,0),0):\n [((i,0),0) | i <- [1..n]] ++\n [((0,j),0) | j <- [1..m]] ++\n [((i,j),a!i*b!j + c!(i,j-1) + c!(i-1,j) - c!(i-1,j-1)) | i <- [1..n], j <- [1..m]]\n ps = [i*j | i <- [1..n], j <- [1..m], c!(i,j) <= x]\n"}], "src_uid": "b100573dfd15cf99842996d91bf26f5f"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Control.Applicative (liftA2)\nimport Control.Monad (forM_)\n\n-- replicate a string n times\nmultiply :: Int -> ByteString -> ByteString\nmultiply 0 _ = \"\"\nmultiply 1 bs = bs\nmultiply n bs =\n let (m,r) = n `divMod` 2\n bs' = multiply m (bs `BS.append` bs)\n in if r == 0 then bs'\n else bs `BS.append` bs'\n\n-- solve the problem using Integers\n-- (this is too slow for large problems)\nsolve1 :: Int -> Int -> Maybe Integer\nsolve1 x p =\n let b = 10*(fromIntegral x)-1 :: Integer\n tenp = 10^p-1\n in first [ n | d0 <- [1..9], let (n,r) = (d0*tenp) `divMod` b, r == 0,\n length (show n) == p ]\n\nfirst :: [a] -> Maybe a\nfirst [] = Nothing\nfirst (a:_) = Just a\n\nliftMin :: Ord a => Maybe a -> Maybe a -> Maybe a\nliftMin Nothing b = b\nliftMin a Nothing = a\nliftMin (Just a) (Just b) = Just $ min a b\n\n-- solve the problem using ByteStrings\nsolve :: Int -> Int -> Maybe ByteString\nsolve 1 p = Just \"1\"\nsolve 2 p = solve' 2 18 2 p\nsolve 3 p = solve' 3 28 3 p\nsolve 4 p = solve' 4 6 4 p\n\nsolve 6 p = solve' 6 58 6 p\nsolve 7 p = solve' 7 22 7 p\nsolve 8 p = solve' 8 13 8 p\nsolve 9 p = solve' 9 44 9 p\n\nsolve 5 p =\n let n1 = solve' 5 6 7 p\n n2 = solve' 5 42 5 p\n in liftMin n1 n2 \nsolve x p = error $ \"huh? \" ++ \" x: \" ++ show x ++ \" p: \" ++ show p\n\n-- find the basic solution to the problem\n-- x - the multipler\n-- m - length of a basic solution\n-- d0 - rightmost digit\n-- p - number of decimal digits\nsolve' :: Int -> Int -> Int -> Int -> Maybe ByteString\nsolve' x m d0 p =\n if p `mod` m == 0\n then let n :: Integer\n n = (fromIntegral d0)*(10^m-1) `div` fromIntegral (10*x-1)\n in Just $ BS.pack (show n)\n else Nothing\n\n-- repeat a ByteString to length p\n-- (don't know if the special case for length == 1 is necessary)\nsolutionToBS :: Int -> ByteString -> ByteString\nsolutionToBS p bs | p `mod` BS.length bs /= 0 = error \"ooops!\"\nsolutionToBS p bs | BS.length bs == 1 = BS.replicate p (BS.index bs 0)\nsolutionToBS p bs = multiply k bs\n where k = p `div` BS.length bs\n\n(-->) = flip fmap\n\nmain = do (p:x:_) <- getLine --> words --> map read\n case solve x p of\n Nothing -> putStrLn \"Impossible\"\n Just bs -> BS.putStrLn $ solutionToBS p bs\n\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Control.Applicative (liftA2)\nimport Control.Monad (forM_)\n\n-- replicate a string n times\nmultiply :: Int -> ByteString -> ByteString\nmultiply 0 _ = \"\"\nmultiply 1 bs = bs\nmultiply n bs =\n let (m,r) = n `divMod` 2\n bs' = multiply m (bs `BS.append` bs)\n in if r == 0 then bs'\n else bs `BS.append` bs'\n\n-- solve the problem using Integers\n-- (this is too slow for large problems)\nsolve1 :: Int -> Int -> Maybe Integer\nsolve1 x p =\n let b = 10*(fromIntegral x)-1 :: Integer\n tenp = 10^p-1\n in first [ n | d0 <- [1..9], let (n,r) = (d0*tenp) `divMod` b, r == 0,\n length (show n) == p ]\n\nfirst :: [a] -> Maybe a\nfirst [] = Nothing\nfirst (a:_) = Just a\n\nliftMin :: Ord a => Maybe a -> Maybe a -> Maybe a\nliftMin Nothing b = b\nliftMin a Nothing = a\nliftMin (Just a) (Just b) = Just $ min a b\n\n-- solve the problem using ByteStrings\nsolve :: Int -> Int -> Maybe ByteString\nsolve 1 p = Just \"1\"\nsolve 2 p = solve' 2 18 2 p\nsolve 3 p = solve' 3 28 3 p\nsolve 4 p = solve' 4 6 4 p\n\nsolve 6 p = solve' 6 58 6 p\nsolve 7 p = solve' 7 22 7 p\nsolve 8 p = solve' 8 13 8 p\nsolve 9 p = solve' 9 44 9 p\n\nsolve 5 p =\n let n1 = solve' 5 6 7 p\n n2 = solve' 5 42 5 p\n in liftMin n1 n2 \nsolve x p = error $ \"huh? \" ++ \" x: \" ++ show x ++ \" p: \" ++ show p\n\n-- find the basic solution to the problem\n-- x - the multipler\n-- m - length of a basic solution\n-- d0 - rightmost digit\n-- p - number of decimal digits\nsolve' :: Int -> Int -> Int -> Int -> Maybe ByteString\nsolve' x m d0 p =\n if p `mod` m == 0\n then let n :: Integer\n n = (fromIntegral d0)*(10^m-1) `div` fromIntegral (10*x-1)\n in Just $ BS.pack (show n)\n else Nothing\n\n-- repeat a ByteString to length p\n-- (don't know if the special case for length == 1 is necessary)\nsolutionToBS :: Int -> ByteString -> ByteString\nsolutionToBS p bs | p `mod` BS.length bs /= 0 = error \"ooops!\"\nsolutionToBS p bs | BS.length bs == 1 = BS.replicate p (BS.index bs 0)\nsolutionToBS p bs = multiply k bs\n where k = p `div` BS.length bs\n\n(-->) = flip fmap\n\nmain = do (p:x:_) <- getLine --> words --> map read\n case solve x p of\n Nothing -> putStrLn \"Impossible\"\n Just bs -> BS.putStrLn $ solutionToBS p bs\n\n"}], "negative_code": [], "src_uid": "86dc5cb9e667fc2ae4d988613feddcb6"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess [x,y] = x:y:[] \nprocess (a:b:c) = a: (process c)\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tk<-replicateM n getLine \n\t\tmapM_ putStrLn $ map process k\n\n\n", "positive_code": [{"source_code": "solve :: String -> String\nsolve (a:b:[]) = [a,b]\nsolve (a:b:xs) = [a,b]++( map snd . filter (even . fst) . zip [1..] . init $ xs) ++ [(last xs)]\n\nsolveCase :: Int -> IO()\nsolveCase 0 = return ()\nsolveCase t = do\n test <- getLine\n putStrLn . solve $ test\n solveCase (t-1)\n\ngetInt :: IO Int\ngetInt = fmap read getLine \n\nmain :: IO()\nmain = do\n n <- getInt\n solveCase n\n"}, {"source_code": "import Control.Monad\n\ngetStr :: String -> String\ngetStr (a:b:[]) = [a, b]\ngetStr (a:_:l@(c:_)) = a : getStr l\ngetStr [] = []\n\nmain = do\n n <- read <$> getLine\n a <- (replicateM n getLine)\n mapM_ putStrLn (getStr <$> a)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\tt <- readInt\n\tmapM_ putStrLn =<< replicateM t solve\n\nsolve = do\n\ts <- getLine\n\tlet\n\t\ts' = map fst $ filter snd $ zip s ( cycle [ True, False ] )\n\treturn $ s' ++ [ last s ]\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n putStrLn $ solve s\n\nsolve :: String -> String\nsolve s = (head s):z\n where\n z =map fst $ filter (even.snd) $ zip s [1..]\n"}, {"source_code": "main = do\n inputjar <- getLine\n let n = read inputjar :: Int\n solve n\n\nsolve :: Int -> IO ()\nsolve 0 = putStr \"\"\nsolve n = do\n input <- getLine\n-- let list = read (\"[\" ++ map (\\x -> if x == ' ' then ',' else x) input ++ \"]\") :: [Int]\n solveCase input\n solve (n - 1)\n\n\nsolveCase :: [Char] -> IO()\nsolveCase s = putStrLn $ [s !! i | i <- [0,2..(length s - 1)]] ++ [last s]\n\n-- solveCase :: [Int] -> IO ()\n-- solveCase (x : y : n : [])\n-- | tmp <= n = print tmp\n-- | otherwise = print $ tmp - x\n-- where\n-- tmp = n - (n `mod` x) + y\n"}, {"source_code": "main :: IO ()\nmain = interact (unlines . map solve . tail . lines)\n\nsolve :: String -> String\nsolve (x:xs) = x : f xs\n where\n f [x] = [x]\n f (x:y:xs) = x : f xs\n"}, {"source_code": "main = getContents >>= putStrLn . unlines . map f . tail . lines where\n f [] = \"\"\n f [x,y] = [x,y]\n f (x:_:xs) = x : f xs"}, {"source_code": "import Control.Monad\n\ngetInts :: IO [Int]\ngetInts = map read.words <$> getLine\n\nmain :: IO()\nmain = do\n [t] <- getInts\n replicateM_ t solve\n\nsolve :: IO()\nsolve = do \n b <- getLine\n let c = [head b] ++ b ++ [last b]\n let n = length c\n a = [c !! i | i <- [0,2..(n-1)]]\n putStrLn a"}, {"source_code": "import Control.Monad\n\ngetInts :: IO [Int]\ngetInts = map read.words <$> getLine\n\nmain :: IO()\nmain = do\n [t] <- getInts\n replicateM_ t solve\n\nsolve :: IO()\nsolve = do \n b <- getLine\n putChar $ head b\n putStrLn $ map fst $ filter (even.snd) $ zip b [1..]"}, {"source_code": "import Control.Monad\n\ngetInts :: IO [Int]\ngetInts = map read.words <$> getLine\n\nmain :: IO()\nmain = do\n [t] <- getInts\n replicateM_ t routine\n\nroutine :: IO()\nroutine = do \n b <- getLine\n putStrLn $ solve b\n\nsolve :: String -> String\nsolve (h:xs) = h : (map fst $ filter (even.snd) $ zip xs [0..])\nsolve x = x"}], "negative_code": [{"source_code": "solve :: String -> String\nsolve (a:b:[]) = [a,b]\nsolve (a:b:xs) = [a,b]++( map snd . filter (even . fst) . zip [1..] . init $ xs) ++ [(last xs)]\n\nsolveCase :: Int -> IO()\nsolveCase 0 = return ()\nsolveCase t = do\n test <- getLine\n putStrLn . show . solve $ test\n solveCase (t-1)\n\ngetInt :: IO Int\ngetInt = fmap read getLine \n\nmain :: IO()\nmain = do\n n <- getInt\n solveCase n\n"}], "src_uid": "ac77e2e6c86b5528b401debe9f68fc8e"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nnum n [x,y] =\n let z = (x-1)*n+(y-1) \n q = (z `div` 2) + 1 \n r = ((n*n+(if even n then 0 else 1))`div`2)\n in if even x\n then if odd z \n then q + if odd n then r else 0\n else q + if odd n then 0 else r\n else q + if even z then 0 else r \n \nint = fst . fromJust . B.readInteger\nints = map int . B.words\n\nmain = do\n [n,k] <- ints <$> B.getLine\n B.interact $ B.unlines . map ( B.pack . show . (num n) . ints ) . B.lines\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nnum n [x,y] =\n let z = (x-1)*n+(y-1) in \n if even x\n then if odd z \n then if odd n then ((n*n+1)`div`2) + (z `div` 2) + 1 else (z `div` 2) + 1\n else if odd n then (z `div` 2) + 1 else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1\n else if even z\n then (z `div` 2) + 1\n else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1\n \nint = fst . fromJust . B.readInteger\nints = map int . B.words\n\nmain = do\n [n,k] <- ints <$> B.getLine\n B.interact $ B.unlines . map ( B.pack . show . (num n) . ints ) . B.lines\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nnum n [x,y] =\n let z = (x-1)*n+(y-1) \n q = (z `div` 2) + 1 \n r = ((n*n+(if even n then 0 else 1))`div`2)\n in if even x\n then q + \n if odd z \n then if odd n then r else 0\n else if odd n then 0 else r\n else q + if odd z then r else 0 \n \nint = fst . fromJust . B.readInteger\nints = map int . B.words\n\nmain = do\n [n,k] <- ints <$> B.getLine\n B.interact $ B.unlines . map ( B.pack . show . (num n) . ints ) . B.lines\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nnum n [x,y] =\n let z = (x-1)*n+(y-1) in \n if even x\n then if odd z \n then (z `div` 2) + 1\n else (n*n`div`2) + z `div` 2 + 1\n else if even z\n then (z `div` 2) + 1\n else (n*n`div`2) + z `div` 2 + 1\n \nint = fst . fromJust . B.readInt\nints = map int . B.words\n\nmain = do\n [n,k] <- ints <$> B.getLine\n B.interact $ B.unlines . map ( B.pack . show . (num n) . ints ) . B.lines\n\n\n{-\n\n4 5\n1 1\n4 4\n4 3\n3 2\n2 4\n\n-}\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nnum n [x,y] =\n let z = (x-1)*n+(y-1) in \n if even x\n then if odd z \n then if odd n then ((n*n+1)`div`2) + (z `div` 2) + 1 else (z `div` 2) + 1\n else if odd n then (z `div` 2) + 1 else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1\n else if even z\n then (z `div` 2) + 1\n else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1\n \nint = fst . fromJust . B.readInt\nints = map int . B.words\n\nmain = do\n [n,k] <- ints <$> B.getLine\n B.interact $ B.unlines . map ( B.pack . show . (num n) . ints ) . B.lines\n"}], "src_uid": "3c48123f326fb79ce2e4e17e1e0765f8"} {"source_code": "module Main where\r\n\r\nimport Data.List\r\nimport Control.Monad (guard, replicateM)\r\n\r\nsum2is3 :: [Int] -> Bool\r\nsum2is3 xs =\r\n f sortedXs || f (reverse sortedXs)\r\n where\r\n sortedXs = sort xs\r\n f sl = sum (take 2 sl) == last sl\r\n\r\nmaySplit :: [Int] -> Bool\r\nmaySplit xs =\r\n x1 == x2 || x2 == x3\r\n where\r\n sxs = sort xs\r\n (x1, x2, x3) = (sxs !! 0, sxs !! 1, sxs !! 2)\r\n\r\nsolve :: [Int] -> String\r\nsolve xs\r\n | odd (sum xs) = \"NO\"\r\n | sum2is3 xs = \"YES\"\r\n | otherwise = if maySplit xs then \"YES\" else \"NO\"\r\n where\r\n rs = reverse $ sort xs\r\n\r\nreadLineInts :: IO [Int]\r\nreadLineInts = do\r\n inputs <- words <$> getLine\r\n pure $ read <$> inputs\r\n\r\ngetInt = read <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getInt\r\n ints <- replicateM t readLineInts\r\n let solutions = solve <$> ints\r\n mapM_ putStrLn solutions\r\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nreadIntegers :: IO [Integer]\r\nreadIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine\r\n\r\npossible :: ([Int]->Bool)\r\npossible (a:b:c:[]) = (a==b && c`mod`2==0) || (b-a==c) \r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- readInts\r\n replicateM_ t $ do\r\n [a,b,c] <- readInts\r\n putStrLn $ if any possible (permutations [a,b,c]) then \"YES\" else \"NO\"\r\n"}, {"source_code": "import Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nreadIntegers :: IO [Integer]\r\nreadIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine\r\n\r\npossible :: ([Int]->Bool)\r\npossible (a:b:c:[]) = (a==b && c`mod`2==0) || (b-a==c) \r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- readInts\r\n replicateM_ t $ do\r\n ar <- readInts\r\n putStrLn $ if any possible $ permutations ar then \"YES\" else \"NO\"\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM)\r\nimport Data.List\r\n\r\nsolve :: [Int] -> String\r\nsolve xs\r\n | sum (tail rs) == head rs = \"YES\"\r\n | even (last rs) && rs !! 0 == rs !! 1 = \"YES\"\r\n | otherwise = \"NO\"\r\n where\r\n rs = reverse $ sort xs\r\n\r\nreadLineInts :: IO [Int]\r\nreadLineInts = do\r\n inputs <- words <$> getLine\r\n pure $ read <$> inputs\r\n\r\ngetInt = read <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getInt\r\n ints <- replicateM t readLineInts\r\n let solutions = solve <$> ints\r\n mapM_ putStrLn solutions\r\n"}], "src_uid": "a4a69a5fbf35781ff0849332a45566ca"} {"source_code": "import Data.List (sort)\r\n\r\n\r\nmain :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = unlines $ processLines $ drop 1 $ lines input\r\n\r\n\r\nprocessLines :: [String] -> [String]\r\nprocessLines (n_line:a_line:b_line:other_lines)\r\n = processTest (a_line, b_line) : processLines other_lines\r\nprocessLines _ = []\r\n\r\n\r\nprocessTest :: (String, String) -> String\r\nprocessTest (a_line, b_line) = output\r\n where\r\n a_seq = map read $ words a_line\r\n b_seq = map read $ words b_line\r\n output = if canMakeEqual a_seq b_seq then \"YES\" else \"NO\"\r\n\r\n\r\ncanMakeEqual :: [Integer] -> [Integer] -> Bool\r\ncanMakeEqual current_sequence target_sequence = result\r\n where\r\n result = all (`elem` [0, 1]) [tx - x | (x, tx) <- zip (sort current_sequence) (sort target_sequence)]\r\n", "positive_code": [{"source_code": "\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n getLine\r\n asu <- readv\r\n bsu <- readv\r\n let\r\n [as,bs] = DL.sort <$> [asu,bsu]\r\n diffs = zipWith subtract as bs\r\n ans = if all (\\x->x==0||x==1) diffs then \"YES\" else \"NO\"\r\n putStrLn ans\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}], "negative_code": [], "src_uid": "6ca98e655007bfb86f1039c9f096557e"} {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n cs <- getLine\r\n let\r\n x = DL.minimum cs\r\n y = DL.delete x cs\r\n putStrLn $ x:\" \" ++ y\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Foldable (traverse_)\nimport Data.List\n\npickSmallest :: String -> (Char, String)\npickSmallest s = \n let min_char = minimum s\n remain = delete min_char s\n in (min_char, remain)\n\noutput :: (Char, String) -> IO ()\noutput (c, s) = putStrLn $ [c] ++ \" \" ++ s \n\n \n\nmain :: IO ()\nmain = do\n no_of_input <- getLine\n inputs <- replicateM (read no_of_input) getLine\n let ans = map pickSmallest inputs\n traverse_ (output) ans\n\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map solve >>> unlines\r\n\r\nsolve s = let c = minimum s in c : ' ' : delete c s\r\n"}, {"source_code": "import Control.Monad (forM_)\r\nimport Data.List (sort)\r\n\r\nmain = do\r\n n <- read <$> getLine\r\n forM_ [1 .. n] $ \\_ -> do\r\n line <- getLine\r\n let x = minimum line\r\n let xs = let (a, _ : b) = span (/= x) line in a ++ b\r\n putStrLn $ x : ' ' : xs"}], "negative_code": [{"source_code": "import Control.Monad (forM_)\r\nimport Data.List (sort)\r\n\r\nmain = do\r\n n <- read <$> getLine\r\n forM_ [1 .. n] $ \\_ -> do\r\n (x : xs) <- sort <$> getLine\r\n putStrLn $ x : ' ' : xs"}], "src_uid": "4a58039c5171597ecf78837e9db1d71d"} {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nsolve :: String -> Integer\r\nsolve = solve' []\r\n where\r\n solve' have \"\"\r\n | null have = 0\r\n | otherwise = 1\r\n solve' have (c : cs) =\r\n let have' = nub $ c : have\r\n in case length have' of\r\n 4 -> 1 + solve' [] (c : cs)\r\n _ -> solve' have' cs\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t $\r\n getLine >>= print . solve\r\n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t getLine\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve ins = f ins :: Int\r\n where\r\n f [] = 0\r\n f s = 1 + f rest\r\n where\r\n ltrs = take 3 . L.nub $ s\r\n rest = dropWhile (`elem` ltrs) s\r\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep = id\n\nparse = id\n\nformat = show\n\nsolve :: String -> Int\nsolve xs = length $ takeWhile (/= \"\") $ iterate afterOneDay xs\n\nafterOneDay xs = afterOneDay' [] xs\n\nafterOneDay' _ \"\" = \"\"\nafterOneDay' ys (x:xs)\n | x `elem` ys = afterOneDay' ys xs\n | length ys < 3 = afterOneDay' (x:ys) xs\n | otherwise = x:xs\n"}, {"source_code": "import Data.Set (Set, empty, insert, member, size)\r\n\r\ncalcH :: Set Char -> String -> Int\r\ncalcH _ [] = 1\r\ncalcH s (x: xs) = if (size s == 3) && (not (x `member` s))\r\n then calcH (insert x empty) xs + 1\r\n else calcH (insert x s) xs\r\n\r\ncalc :: String -> Int\r\ncalc a = calcH empty a\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n a <- getLine\r\n print $ calc a\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: String -> Int\nsolve str = solve' str []\n where\n solve' :: String -> [Char] -> Int\n solve' [] _ = 1\n solve' s@(c:otherS) memory\n | L.length ([c] `L.union` memory) > 3 = 1 + solve' s []\n | otherwise = solve' otherS $ [c] `L.union` memory\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n s <- B8.getLine <&> head . B8.words\n let answer = solve (B8.unpack s)\n printf \"%d\\n\" answer\n\n"}], "negative_code": [], "src_uid": "bd9da9081902a87c61591fb58fcecfe3"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep (x:y:xs) = (x,y):(sep xs)\n\nparse (x,y) = (read $ (words x) !! 1, map read $ words y)\n\nformat = show\n\nsolve (k,as) = base + extra\n where base = sum ds\n (ds, ms) = unzip $ map (`divMod` k) as\n msAsc = sort ms\n msDes = reverse msAsc\n l = length ms\n extra = cnt 0 (l-1) msDes msAsc\n cnt i j _ _\n | i >= j = 0\n cnt i j (x:xs) (y:ys)\n | x + y >= k = 1 + cnt (i+1) (j-1) xs ys\n | otherwise = cnt i (j-1) (x:xs) ys\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep (x:y:xs) = (x,y):(sep xs)\n\nparse (x,y) = (read $ (words x) !! 1, map read $ words y)\n\nformat = show\n\nsolve (k,as) = base + extra\n where base = sum ds\n (ds, ms) = unzip $ map (`divMod` k) as\n msAsc = sort ms\n msDes = reverse msAsc\n l = length ms\n extra = cnt 0 0 (l-1) msDes msAsc\n cnt s i j _ _\n | i >= j = s\n cnt s i j (x:xs) (y:ys)\n | x + y >= k = cnt (s+1) (i+1) (j-1) xs ys\n | otherwise = cnt s i (j-1) (x:xs) ys\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep (x:y:xs) = (x,y):(sep xs)\n\nparse (x,y) = (read $ (words x) !! 1, map read $ words y)\n\nformat = show\n\nsolve (k,as) = base + extra\n where base = sum ds\n (ds, ms) = unzip $ map (`divMod` k) as\n msAsc = sort ms\n msDes = reverse msAsc\n l = length ms\n extra = cnt 0 (l-1) msDes msAsc\n cnt i j _ _\n | i >= j = 0\n cnt i j (x:xs) (y:ys)\n | x + y >= k = 1 + cnt (i+1) (j-1) xs ys\n | otherwise = cnt i (j-1) (x:xs) ys\n"}], "negative_code": [], "src_uid": "8e9ba5a2472984cd14b99790a157acd5"} {"source_code": "process :: (Int, Int, Int, Int) -> Int\nprocess (x,y,a,b)\n | r == 0 = q\n | otherwise = -1\n where\n d = y-x\n c = a+b\n r = d `mod` c\n q = d `div` c\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ print $ map (\\[x,y,a,b] -> process (x,y,a,b)) ts", "positive_code": [{"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . readIntegers) . takeNLines . lines\n where\n takeNLines (l:ls) = take (read l) ls\n readIntegers = map read . words\n\nsolve :: [Integer] -> Integer\nsolve ls =\n case mod diff summ of\n 0 -> div diff summ\n _ -> -1\n where\n diff = (ls !! 1 - ls !! 0)\n summ = (ls !! 2 + ls !! 3)\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get :: EIO Int\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (x, y, a, b) <- liftM4 (,,,) get get get get\n putln $ f2 x y a b\n\nf2 :: Int64 -> Int64 -> Int64 -> Int64 -> Int64\nf2 x y a b = let d = (div (y - x) (a + b)) in\n let r = (mod (y - x) (a + b)) in\n if r /= 0 || d < 0 then -1\n else d\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nprocess [a,b,c,d] | mod (b-a) (c+d)>0 = -1\n | otherwise = div (b-a) (c+d) \n\n\nmain::IO ()\nmain=do\n t<- read<$> getLine ::IO Int\t\n a<- map(map read. words) <$> replicateM t getLine::IO [[Integer]] \n mapM_ print $ map process a \n\n"}, {"source_code": "parse :: String -> String\nparse input = show $ solve x y a b\n where [x, y, a, b] = map (\\x -> read x :: Integer) $ words input\n\nsolve :: Integer -> Integer -> Integer -> Integer -> Integer\nsolve x y a b\n | mod (y-x) (a+b) == 0 = div (y-x) (a+b)\n | otherwise = -1\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "negative_code": [], "src_uid": "9afcf090806cc9c3b87120b1b61f8f17"} {"source_code": "import Data.Set\nimport Data.Int\n\ncountDup :: Set Int64 -> Int64 -> [Int64] -> Int\ncountDup _ _ [] = 0\ncountDup seen last (head:tail)\n | member head seen = 1 + countDup (fromList [last, head]) head tail\n | otherwise = countDup (insert head seen) head tail\n\nsolve :: [Int64] -> Int\nsolve a = countDup (singleton 0) 0 cum\n where cum = scanl1 (+) a\n\nmain = do\n _ <- getLine\n sa <- getLine\n let a = [read x :: Int64 | x <- words sa]\n putStrLn $ show $ solve a\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> head\n >>> words\n >>> map read\n >>> solve\n >>> show\n >>> (++ \"\\n\")\n\ntype SetInt = Set.Set Integer\n\nsolve :: [Integer] -> Integer\nsolve a = compute (Set.singleton 0) 0 a\n\ncompute :: SetInt -> Integer -> [Integer] -> Integer\ncompute _ _ [] = 0\ncompute pres pre (x : a) =\n if Set.member pre' pres\n then 1 + compute (Set.fromList [x, 0]) x a\n else compute (Set.insert pre' pres) pre' a\n where pre' = pre + x\n"}, {"source_code": "import Control.Monad\nimport Data.Set (Set, insert, member, empty)\n\ngetList :: (Read t) => IO [t]\ngetList = getLine >>= return . (map read) . words\n\ngetOne :: (Read t) => IO t\ngetOne = getLine >>= return . read\n\nmain :: IO ()\nmain = do\n -- t <- getOne\n let t = 1\n replicateM_ t solve\n\n\nsolve :: IO ()\nsolve = do \n n <- getOne :: IO Int\n ls <- getList\n print $ countAns ls\n\nincludeZero :: Integral a => Set a\nincludeZero = 0 `insert` empty\n\ncountAns :: (Integral a) => [a] -> a\ncountAns ls = countZeros includeZero ls 0\n\ncountZeros :: (Integral a) => Set a -> [a] -> a -> a\ncountZeros _ [] _ = 0\ncountZeros sums all@(x:xs) sum \n | ns `member` sums = 1 + countZeros includeZero all 0\n | otherwise = countZeros (ns `insert` sums) xs ns\n where ns = sum + x"}, {"source_code": "import Data.List ( foldl' )\nimport Data.Int\nimport qualified Data.Set as Set\n\ndata State = State !Int64 !(Set.Set Int64) !Int\n\nstep :: State -> Int64 -> State\nstep (State currPS activePS count) v = let\n nextPS = v + currPS\n in if Set.member nextPS activePS\n then State v (Set.fromList [0, v]) (count + 1)\n else State nextPS (Set.insert nextPS activePS) count\n\nsolve :: [Int64] -> Int\nsolve li = let\n State _ _ ct = foldl' step (State 0 (Set.singleton 0) 0) li\n in ct\n\nmain :: IO ()\nmain = do\n _nStr <- getLine\n a <- map read . words <$> getLine\n print $ solve a\n"}, {"source_code": "import qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- map read . words <$> getLine\n print $ (\\(_, y, _) -> y) $ foldl processElem (S.singleton 0, 0, 0) $ scanl1 (+) a\n\n\nprocessElem :: (S.Set Integer, Integer, Integer) -> Integer -> (S.Set Integer, Integer, Integer)\nprocessElem (s, c, p) x\n | S.member x s = (S.fromList [p, x], c + 1, x)\n | otherwise = (S.insert x s, c, x)"}], "negative_code": [{"source_code": "import Data.Set\n\ncountDup :: Set Int -> Int -> [Int] -> Int\ncountDup _ _ [] = 0\ncountDup seen last (head:tail)\n | member head seen = 1 + countDup (fromList [last, head]) head tail\n | otherwise = countDup (insert head seen) head tail\n\nsolve :: [Int] -> Int\nsolve a = countDup (singleton 0) 0 cum\n where cum = scanl1 (+) a\n\nmain = do\n _ <- getLine\n sa <- getLine\n let a = [read x :: Int | x <- words sa]\n putStrLn $ show $ solve a\n"}], "src_uid": "05548be393d794bf106708627220b9a3"} {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B \n\nreadB s = a\n where Just (a,_) = B.readInt s\n\nmain = do\n a <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]\n let b = listArray (0, length a) $ (map snd) $ scanl build (0, ((-1,-1), (-1,-1))) a\n B.getContents >>= putStr . unlines . (map (show.(solve b).(map readB). B.words)). B.lines\n\nbuild (i, ((a,ai), (b,bi))) n\n | n==a = ((i+1), ((a,(i+1)), (b,bi)))\n | otherwise = ((i+1), ((n,(i+1)), (a,ai)))\n\nsolve b [l,r,val]\n | x==val = if (yi>=l) then yi else (-1)\n | otherwise = xi\n where\n ((x,xi),(y,yi)) = b!r", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as B \ntype Vi = UArray Int Int\ntype Pii = (Int, Int, Int, Int)\n\nreadB s = a\n where Just (a,_) = B.readInt s\n\nmain = do\n input <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]\n let tuple = unzip4 $ (map snd) $ scanl build (0, (-1,-1, -1,-1)) input\n let [a,ai,b,bi] = ((map (listArray (0, length input))).(\\(a,b,c,d)->[a,b,c,d])$tuple) :: [Vi]\n B.getContents >>= putStr . unlines . (map (show.solve a ai b bi.map readB. B.words)). B.lines\n\nbuild :: (Int, Pii) -> Int -> (Int, Pii)\nbuild (i, (a,ai,b,bi)) n\n | n==a = ((i+1), (a,(i+1),b,bi))\n | otherwise = ((i+1), (n,(i+1),a,ai))\n\nsolve :: Vi->Vi->Vi->Vi -> [Int] -> Int\nsolve x xi y yi [l,r,val]\n | (x!r)==val = if ((yi!r)>=l) then (yi!r) else (-1)\n | otherwise = (xi!r)"}, {"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B \n\nreadB s = a\n where Just (a,_) = B.readInt s\n\nmain = do\n a <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]\n let b = Map.fromList $ scanl build (0, ((-1,-1), (-1,-1))) a\n B.getContents >>= putStr . unlines . (map (show.(solve b).(map readB). B.words)). B.lines\n\nbuild (i, ((a,ai), (b,bi))) n\n | n==a = ((i+1), ((a,(i+1)), (b,bi)))\n | otherwise = ((i+1), ((n,(i+1)), (a,ai)))\n\nsolve :: Map.Map Int ((Int,Int),(Int,Int)) -> [Int] -> Int\nsolve b [l,r,val]\n | x==val = if (yi>=l) then yi else (-1)\n | otherwise = xi\n where\n ((x,xi),(y,yi)) = fromJust $ Map.lookup r b"}, {"source_code": "\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n let b2i = fst . fromJust . B.readInt\n [n, m] <- map b2i . B.words <$> B.getLine\n a <- map b2i . B.words <$> B.getLine\n mls <- forM [1..m] $ const B.getLine\n let lrx = map ((\\[l, r, x] -> (l, r, x)) . map b2i . B.words) (mls::[B.ByteString])\n mapM_ (putStrLn . show) $ sol n m a lrx\n\nsol :: Int -> Int -> [Int] -> [(Int, Int, Int)] -> [Int]\nsol n m alst lrx = map query lrx\n where\n a = listArray (1, n) alst\n lastDif = listArray (1, n) [dp loc | loc <- [1..n]]\n dp l\n | l == 1 = -1\n | a ! l == a ! (l-1) = lastDif ! (l-1)\n | otherwise = l-1\n query (l, r, x)\n | a ! r /= x = r\n | lastDif ! r >= l = lastDif ! r\n | otherwise = -1\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, array, listArray, bounds, amap, (!))\nimport Control.Monad (replicateM)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n, m] <- readInts\n as <- readInts\n\n qs <- replicateM m readInts :: IO [[Int]]\n\n let\n ps1 = accumArray (flip (:)) [] (1, 10^6) $ zip as [1..n] :: Array Int [Int]\n ps = amap (compact . reverse) ps1\n where\n compact :: [Int] -> Array Int (Int, Int)\n compact [] = array (1,0) []\n compact (i:is) = listArray (1, length l) l :: Array Int (Int, Int)\n where\n l = f i i is\n where\n f i j [] = [(i,j)]\n f i j (k:is)\n | k == j+1 = f i k is\n | otherwise = (i,j):(f k k is)\n\n ys = map solve qs\n where\n solve [l, r, x]\n | b2 == 0 = l\n | otherwise = f $ lookup 1 b2\n where\n b2 = snd $ bounds rs\n rs = ps ! x\n\n lookup i j\n | i >= j = if l <= rr && ll <= r then Just m else Nothing\n | l > rr = lookup (m + 1) j\n | ll > r = lookup i m\n | otherwise = Just m\n where\n m = (i+j) `div` 2\n (ll, rr) = rs ! m\n\n f Nothing = l\n f (Just m)\n | ll <= l && r <= rr = -1\n | r > rr = rr + 1\n | l < ll = ll-1\n where\n (ll, rr) = rs ! m\n\n putStr $ unlines $ map show ys\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as B \ntype Vi = UArray Int Int\ntype Pii = (Int, Int, Int, Int)\n\nreadB s = a\n where Just (a,_) = B.readInt s\n\nmain = do\n input <- liftM (map read . words) (getLine >> getLine) :: IO [Int]\n let tuple = unzip4 $ (map snd) $ scanl build (0, (-1,-1, -1,-1)) input\n let [a,ai,b,bi] = ((map (listArray (0, length input))).(\\(a,b,c,d)->[a,b,c,d])$tuple) :: [Vi]\n B.getContents >>= putStr . unlines . (map (show.solve a ai b bi.map readB. B.words)). B.lines\n\nbuild :: (Int, Pii) -> Int -> (Int, Pii)\nbuild (i, (a,ai,b,bi)) n\n | n==a = ((i+1), (a,(i+1),b,bi))\n | otherwise = ((i+1), (n,(i+1),a,ai))\n\nsolve :: Vi->Vi->Vi->Vi -> [Int] -> Int\nsolve x xi y yi [l,r,val]\n | (x!r)==val = if ((yi!r)>=l) then (y!r) else (-1)\n | otherwise = (xi!r)"}, {"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\n\nmain = do\n a <- liftM (map read . words) (getLine >> getLine) :: IO [Int]\n let b = Map.fromList $ scanl build (1, ((-1,-1), (-1,-1))) a\n getContents >>= putStr . unlines . (map (show.(solve b).(map read).words)).lines\n\nbuild (i, ((a,ai), (b,bi))) n\n | n==a = ((i+1), ((a,i), (b,bi)))\n | otherwise = ((i+1), ((n,i), (a,ai)))\n\nsolve :: Map.Map Int ((Int,Int),(Int,Int)) -> [Int] -> Int\nsolve b [l,r,val]\n | x==val = if (yi>=l) then yi else (-1)\n | otherwise = xi\n where\n ((x,xi),(y,yi)) = fromJust $ Map.lookup r b\n"}], "src_uid": "dcf7988c35bb34973e7b60afa7a0e68c"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\n--showB False = \"NO\"\r\n--showB True = \"YES\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,l,r] <- ri\r\n return (n,l,r)\r\n mapM_ (putStr.showAns.solve) tcs\r\n\r\nshowAns Nothing = unlines [\"NO\" ]\r\nshowAns (Just xs) = unlines [\"YES\", unwords . map show $ xs]\r\n\r\nsolve (n,l,r) | ok = Just ans\r\n | otherwise = Nothing\r\n where\r\n rs = map (range (l,r)) [1..n]\r\n ok = all (uncurry (<=)) rs\r\n ans = zipWith (*) [1..n] (map fst rs)\r\n\r\nrange (l,r) x = ( ((l-1)`div`x) + 1,\r\n ( r `div`x) )\r\n", "positive_code": [{"source_code": "find l i \n\t| gcd l i == i \t\t= l\n\t| otherwise\t\t= ($!) find (l + i - (l `mod` i)) i\n\n\nsolve n l r \n\t| maximum a < (r+1) \t\t= \"YES\\n\" ++ (printArr a) ++ \"\\n\"\n\t| otherwise \t\t\t= \"NO\\n\" \n\twhere\n\t\ta = ($!) map (find l) [1..n]\n\t\tprintArr [] = \" \"\n\t\tprintArr (x:xs) = show x ++ \" \" ++ printArr xs\n\nexec 0 = pure () \nexec t = do\n\t(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]\n\tputStr $ solve n l r\n\texec (t-1)\n\nmain = do\n\tt <- read <$> getLine :: IO Int\n\texec t\n"}, {"source_code": "\nfind l i \n\t| gcd l i == i \t\t= l\n\t| otherwise\t\t= find (l + i - (l `mod` i)) i\n\n\nsolve n l r \n\t-- | abs (r - l) < n-1\t \t= \"NO\\n\"\n\t| maximum a < (r+1) \t\t= \"YES\\n\" ++ (printArr a) ++ \"\\n\"\n\t| otherwise \t\t\t= \"NO\\n\" \n\twhere\n\t\ta = map (find l) [1..n]\n\t\tprintArr [] = \" \"\n\t\tprintArr (x:xs) = show x ++ \" \" ++ printArr xs\n\nexec 0 = pure () \nexec t = do\n\t(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]\n\tputStr $ solve n l r\n\texec (t-1)\n\nmain = do\n\tt <- read <$> getLine :: IO Int\n\texec t\n"}], "negative_code": [{"source_code": "\nfind l i \n\t| gcd l i == i \t\t= l\n\t| otherwise\t\t= find (l + 1) i\n\n\nsolve n l r \n\t| abs (r - l) < n-1\t \t= \"NO\\n\"\n\t| maximum a < (r+1) \t\t= \"YES\\n\" ++ (printArr a) ++ \"\\n\"\n\t| otherwise \t\t\t= \"NO\\n\" \n\twhere\n\t\ta = map (find l) [1..n]\n\t\tprintArr [] = \" \"\n\t\tprintArr (x:xs) = show x ++ \" \" ++ printArr xs\n\nexec 0 = pure () \nexec t = do\n\t(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]\n\tputStr $ solve n l r\n\texec (t-1)\n\nmain = do\n\tt <- read <$> getLine :: IO Int\n\texec t\n"}, {"source_code": "\nfind l i \n\t| gcd l i == i \t\t= l\n\t| otherwise\t\t= find (l + i - (l `mod` i)) i\n\n\nsolve n l r \n\t| abs (r - l) < n-1\t \t= \"NO\\n\"\n\t| maximum a < (r+1) \t\t= \"YES\\n\" ++ (printArr a) ++ \"\\n\"\n\t| otherwise \t\t\t= \"NO\\n\" \n\twhere\n\t\ta = map (find l) [1..n]\n\t\tprintArr [] = \" \"\n\t\tprintArr (x:xs) = show x ++ \" \" ++ printArr xs\n\nexec 0 = pure () \nexec t = do\n\t(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]\n\tputStr $ solve n l r\n\texec (t-1)\n\nmain = do\n\tt <- read <$> getLine :: IO Int\n\texec t\n"}, {"source_code": "\nfind l i \n\t| gcd l i == i \t\t= l\n\t| otherwise\t\t= find (l + i - (l `mod` i)) i\n\n\nsolve n l r \n\t| abs (r - l) < n `div` 2 \t= \"NO\\n\"\n\t| maximum a < (r+1) \t\t= \"YES\\n\" ++ (printArr a) ++ \"\\n\"\n\t| otherwise \t\t\t= \"NO\\n\" \n\twhere\n\t\ta = map (find l) [1..n]\n\t\tprintArr [] = \" \"\n\t\tprintArr (x:xs) = show x ++ \" \" ++ printArr xs\n\nexec 0 = pure () \nexec t = do\n\t(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]\n\tputStr $ solve n l r\n\texec (t-1)\n\nmain = do\n\tt <- read <$> getLine :: IO Int\n\texec t\n"}, {"source_code": "\nfind l i \n\t| gcd l i == i \t\t= l\n\t| otherwise\t\t= find (l + i - (l `mod` i)) i\n\n\nsolve n l r \n\t| abs (r - l) < n `div` 2 \t= \"NO1\\n\"\n\t| maximum a < (r+1) \t\t= \"YES\\n\" ++ (printArr a) ++ \"\\n\"\n\t| otherwise \t\t\t= \"NO\\n\" \n\twhere\n\t\ta = map (find l) [1..n]\n\t\tprintArr [] = \" \"\n\t\tprintArr (x:xs) = show x ++ \" \" ++ printArr xs\n\nexec 0 = pure () \nexec t = do\n\t(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]\n\tputStr $ solve n l r\n\texec (t-1)\n\nmain = do\n\tt <- read <$> getLine :: IO Int\n\texec t\n"}], "src_uid": "d2cc6efe7173a64482659ba59efeec16"} {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nco x = div (x* (x-1)) 2\n\nmain= do\n\tgetLine\n\ts<- map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents :: IO [[Int]]\n\tlet [t1,t2]= transpose s\n\tlet r1= sum $ map co $ filter (>1) $ map length $group $ sort $ zipWith (+) t1 t2\n\tlet r2= sum $ map co $ filter (>1) $ map length $group $ sort $ zipWith (-) t1 t2\n\tprint $ r1+r2\n\t", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\nfindRes :: (Int -> Int -> Int) -> [(Int, Int)] -> Int\nfindRes f = (map (uncurry f)) >>> sort >>> group >>> (map length) >>> filter (>1) >>> (map (\\x -> x * (x-1) `div` 2)) >>> sum\n\nmain :: IO ()\nmain = do\n getLine\n a <- map (\\(x:y:ys) -> (x,y)) . map (map (fst.fromJust.C.readInt)). map C.words. C.lines <$> C.getContents :: IO [(Int, Int)]\t\n print $ ((findRes (+) &&& findRes (-)) >>> uncurry (+)) a"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Numeric\n\npairs x = (x*x-x) `div` 2\n\niRead s = case readDec s of [(n,_)] -> n\n\nmain = do\n\tline <- getLine\n\tlet n = iRead line\n\tlines <- replicateM n getLine\n\tlet bishops = [map iRead (words l) :: [Int] | l <- lines]\n\tlet [x,y] = transpose bishops\n\tlet p = sum (map pairs (map length (group (sort (zipWith (+) x y)))))\n\tlet s = sum (map pairs (map length (group (sort (zipWith (-) x y)))))\n\tputStrLn $ show (p+s)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Numeric\n\npairs x = (x*x-x) `div` 2\niRead s = case readDec s of [(n,_)] -> n\n\nmain = do\n\tline <- getLine\n\tlines <- replicateM (iRead line) getLine\n\tlet [x,y] = transpose [map iRead (words l) :: [Int] | l <- lines]\n\tlet p = sum (map pairs (map length (group (sort (zipWith (+) x y)))))\n\tlet s = sum (map pairs (map length (group (sort (zipWith (-) x y)))))\n\tputStrLn $ show (p+s)"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\n\ngetMin :: [Integer] -> Integer\ngetMin [] = 0\ngetMin xs = ((minimum &&& (length >>> fromIntegral >>> (`mod` 2))) >>> uncurry (*)) xs\n\nfindRes :: (Integer -> Integer -> Integer) -> [(Integer, Integer)] -> Int\nfindRes f = (map (uncurry f)) >>> sort >>> group >>> (map length) >>> filter (>1) >>> (map (\\x -> x * (x-1))) >>> sum\n\nmain :: IO ()\nmain = do\n n <- liftM (read::String -> Integer) getLine\n a <- mapM (\\_ -> liftM ((\\(x:y:ys) -> (x,y)) . map(read::String->Integer) . words) getLine) [1..n]\n print $ ((findRes (+) &&& findRes (-)) >>> uncurry (+)) a"}], "src_uid": "eb7457fe1e1b571e5ee8dd9689c7d66a"} {"source_code": "import Control.Monad (forM_)\n\nsolve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)\nsolve max min maxIdx minIdx i [] = (maxIdx, minIdx)\nsolve max min maxIdx minIdx i (x : xs)\n | x >= max && x <= min = solve x x i i (i + 1) xs\n | x <= min = solve max x maxIdx i (i + 1) xs\n | x >= max = solve x min i minIdx (i + 1) xs\n | otherwise = solve max min maxIdx minIdx (i + 1) xs\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = (map read . words) l :: [Int]\n let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr\n putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1)\n", "positive_code": [{"source_code": "import Lib\r\nimport Data.List\r\nimport Control.Monad\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn \r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n n <- getLine \r\n xs <- map read . words <$> getLine :: IO [Int]\r\n let (Just minPos) = succ <$> minimum xs `elemIndex` xs\r\n let (Just maxPos) = succ <$> maximum xs `elemIndex` xs\r\n putStrLn (show minPos ++ \" \" ++ show maxPos)"}], "negative_code": [{"source_code": "import Control.Monad (forM_)\n\nsolve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)\nsolve max min maxIdx minIdx i [] = (maxIdx, minIdx)\nsolve max min maxIdx minIdx i (x : xs)\n | x >= max = solve x min i minIdx (i + 1) xs\n | x <= min = solve max x maxIdx i (i + 1) xs\n | otherwise = solve max min maxIdx minIdx (i + 1) xs\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = (map read . words) l :: [Int]\n let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr\n putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1)\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)\nsolve max min maxIdx minIdx i [] = (maxIdx, minIdx)\nsolve max min maxIdx minIdx i (x : xs)\n | x <= min = solve max x maxIdx i (i + 1) xs\n | x >= max = solve x min i minIdx (i + 1) xs\n | otherwise = solve max min maxIdx minIdx (i + 1) xs\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = (map read . words) l :: [Int]\n let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr\n putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1)\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve :: (Ord a1, Num a2) => a1 -> a1 -> a2 -> a2 -> a2 -> [a1] -> (a2, a2)\nsolve max min maxIdx minIdx i [] = (maxIdx, minIdx)\nsolve max min maxIdx minIdx i (x : xs)\n | x < min = solve max x maxIdx i (i + 1) xs\n | x > max = solve x min i minIdx (i + 1) xs\n | otherwise = solve max min maxIdx minIdx (i + 1) xs\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = (map read . words) l :: [Int]\n let (a, b) = if n == 1 then (0,0) else solve (-1) (10^9) (-1) (-1) 0 arr\n putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1)\n"}, {"source_code": "import Lib\r\nimport Data.List\r\nimport Control.Monad\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn \r\n replicateM_ n solvet\r\n\r\nsolvet :: IO ()\r\nsolvet = do\r\n n <- getLine \r\n xs <- map read . words <$> getLine :: IO [Int]\r\n let (Just minPos) = succ <$> minimum xs `elemIndex` xs\r\n let (Just maxPos) = succ <$> maximum xs `elemIndex` xs\r\n print (show minPos ++ \" \" ++ show maxPos)\r\n "}], "src_uid": "7af4eee2e9f60283c4d99200769c77ec"} {"source_code": "import Control.Monad\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n print $ div (n+1) 10\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "import Control.Monad\n\ncalc :: Int -> Int\ncalc n = (n+1) `div` 10\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n print $ calc n\n"}, {"source_code": "main=interact$unlines.map(show.(`div`10).(+1).read).tail.lines"}, {"source_code": "module Main where\nimport Data.Char (ord)\nmain = interact solve\n\nsolve inp = \n let\n linp = lines inp\n t = read $ head linp :: Int \n inps = take t . tail $ linp\n logic n | length n == 1 = if n == \"9\" then 1 else 0\n | otherwise = if last n == '9' then read (init n) + 1 else read (init n) :: Int\n in\n unlines . map (show . logic) $ inps \n"}, {"source_code": "testcase :: Int -> IO ()\ntestcase 0 = return ()\ntestcase i = (readLn :: IO Int) >>= (print . (`div` 10) . (+1)) >> testcase (i - 1)\n\nmain :: IO ()\nmain = (readLn :: IO Int) >>= testcase"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n print $ ans n\n\nans x\n | x `mod` 10 == 9 = myAns+1\n | otherwise = myAns\n where myAns = x `div` 10\n"}, {"source_code": "main = interact $ unlines . map show . map(\\x -> x `div` 10) . map (+1) . map read . tail . words"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn\r\n print $ (n + 1) `div` 10"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n n <- readLn\n print $ (n + 1) `div` 10"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\n\nsolve :: Int -> Int\nsolve n = (n + 1) `div` 10\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n putInts [div (n + 1) 10]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "8e4194b356500cdaacca2b1d49c2affb"} {"source_code": "module Main where\n\nimport Control.Monad\n\nimport Data.Int\nimport Data.Ratio\n \nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n replicateM_ n action\n \naction = getLine >>= putStrLn . answer . guess . read\n\nguess :: Int64 -> Bool\nguess x = any (\\a -> let r = x - a^3 in r > 0 && (round $ (fromIntegral r)**(1/3))^3 == r) [1..9999]\n\nanswer True = \"yes\"\nanswer False = \"no\"", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = bool \"NO\" \"YES\" . solve <$> popInteger\n\n\nsolve x = any test $ takeWhile (\\a -> 2 * a ^ 3 <= x) [1..]\n where\n test a = Set.member (x - a ^ 3) cubes\n\n cubes = Set.fromList $ takeWhile (<= x) $ map (^ 3) [1..]\n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Int\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int64\nru = C.foldl' (\\a c -> a * 10 - 48 + (fromIntegral $ ord c)) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\np3 :: Int64 -> Int64\np3 x = x * x * x\n\nf :: Int64 -> Int64 -> Bool\nf x y \n | xxx < y = f (succ x) y\n | xxx == y = True\n | otherwise = False\n where xxx = p3 x\n\ncube :: Int64 -> Bool\ncube x = f xxx x \n where\n xxx :: Int64\n xxx = fromIntegral $ floor $ exp $ ((log $ fromIntegral x) / 3.0)\n\nyes = byteString $ C.pack \"YES\\n\"\nno = byteString $ C.pack \"NO\\n\"\n\ntest :: Int64 -> Builder\ntest n = if x then yes else no\n where x = any (\\(_, bbb) -> cube bbb) $ takeWhile (\\(u, v) -> u <= v) $ [(aaa, bbb) | a <- [1 ..], let aaa = p3 a, let bbb = n - aaa]\n \nsolve :: [Int64] -> Builder\nsolve (n:l) = mconcat $ map test l'\n where\n l' = take (fromIntegral n) l\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\ncbrt :: Int64 -> Int64\ncbrt x = let\n cr :: Double\n cr = fromIntegral x ** (1 / 3)\n cr32 :: Int\n cr32 = floor cr -- may be too small by 1 if perfect cube, but that's OK\n in fromIntegral cr32\n\nsolve :: Int64 -> Bool\nsolve n = let\n incrs = map (\\i -> i*i*i) [1..]\n decrs = map (\\i -> i*i*i) $ takeWhile (> 0) $ iterate (subtract 1) $ cbrt n\n go _ [] = False\n go xs@(x:txs) ys@(y:tys) = case compare (x + y) n of\n LT -> go txs ys\n EQ -> True\n GT -> go xs tys\n go [] _ = error \"solve.go: overflow?\"\n in go incrs decrs\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [x] <- readInts\n lift $ P.putStr $ case solve x of\n True -> P.pack \"YES\\n\"\n False -> P.pack \"NO\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: Num t => SIO [t]\nreadInts = do\n currLine <- readLine\n pure [fromInteger x | Just (x, _) <- P.readInteger <$> P.words currLine]\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let\n cr :: Int\n -- Seriously? (floor :: Double -> Int64)?\n -- THAT's where the majority of my runtime was spent?\n cr = floor $ 0.5 + fromIntegral x ** (1 / 3.0 :: Double)\n cr64 = fromIntegral cr\n in cr64 * cr64 * cr64 == x\n\nsolve :: Int64 -> Bool\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt\n answers <- replicateM t $ solve <$> readInt\n putBools answers\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n\nputBools :: [Bool] -> SIO ()\nputBools = let\n res True = B.byteString $ S.pack \"YES\\n\"\n res False = B.byteString $ S.pack \"NO\\n\"\n in lift . B.hPutBuilder stdout . mconcat . map res\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Lazy as L\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Data.Int\nimport Data.Char\n\nisCube :: Int64 -> Bool\nisCube x = let\n cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double))\n in cr*cr*cr == x\n\nsolve :: Int64 -> Bool -- these should get inlined anyway, right?\nsolve v = any (\\(_, y) -> isCube y) $ takeWhile (\\(x, y) -> x <= y) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nzeroVal :: Int64\nzeroVal = fromIntegral $ ord '0' -- 48\n\n-- Is this THAT much faster than P.readInteger?\nparseUInt64 :: P.ByteString -> Int64\nparseUInt64 = L.foldl' (\\x y -> x * 10 + fromIntegral y - zeroVal) 0\n\nmain :: IO ()\nmain = do\n inp <- P.getContents\n let vals = tail $ map parseUInt64 $ P.words inp\n putBools $ map solve vals\n\nputBools :: [Bool] -> IO ()\nputBools = let\n res True = B.byteString $ S.pack \"YES\\n\"\n res False = B.byteString $ S.pack \"NO\\n\"\n in B.hPutBuilder stdout . mconcat . map res\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Lazy as L\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString as SR\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Data.Int\nimport Data.Char\n\nisCube :: Int64 -> Bool\nisCube x = let\n cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double))\n in cr*cr*cr == x\n\nsolve :: Int64 -> Bool\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nzeroVal :: Int64\nzeroVal = fromIntegral $ ord '0' -- 48\n\n-- Is this THAT much faster than P.readInteger?\nparseUInt64 :: S.ByteString -> Int64\nparseUInt64 = SR.foldl' (\\x y -> x * 10 + fromIntegral y - zeroVal) 0\n\nmain :: IO ()\nmain = do\n inp <- S.getContents\n let vals = tail $ map parseUInt64 $ S.words inp\n putBools $ map solve vals\n\nputBools :: [Bool] -> IO ()\nputBools = let\n res True = B.byteString $ S.pack \"YES\\n\"\n res False = B.byteString $ S.pack \"NO\\n\"\n in B.hPutBuilder stdout . mconcat . map res\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Lazy as L\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Data.Int\nimport Data.Char\n\nisCube :: Int64 -> Bool\nisCube x = let\n cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double))\n in cr*cr*cr == x\n\nsolve :: Int64 -> Bool\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nzeroVal :: Int64\nzeroVal = fromIntegral $ ord '0' -- 48\n\n-- Is this THAT much faster than P.readInteger?\nparseUInt64 :: P.ByteString -> Int64\nparseUInt64 = L.foldl' (\\x y -> x * 10 + fromIntegral y - zeroVal) 0\n\nmain :: IO ()\nmain = do\n inp <- P.getContents\n let vals = tail $ map parseUInt64 $ P.words inp\n putBools $ map solve vals\n\nputBools :: [Bool] -> IO ()\nputBools = let\n res True = B.byteString $ S.pack \"YES\\n\"\n res False = B.byteString $ S.pack \"NO\\n\"\n in B.hPutBuilder stdout . mconcat . map res\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let -- OK, it's very stable.\n cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double)) -- is (**) slow?\n in cr*cr*cr == x\n\nsolve :: Int64 -> Bool\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt -- overflow in input reading, silly me\n answers <- replicateM t $ solve <$> readInt\n putBools answers -- try faster output?\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n\nputBools :: [Bool] -> SIO ()\nputBools = let\n res True = B.byteString $ S.pack \"YES\\n\"\n res False = B.byteString $ S.pack \"NO\\n\"\n in lift . B.hPutBuilder stdout . mconcat . map res\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let -- OK, it's very stable.\n cr = floor $ 0.5 + exp (log (fromIntegral x) / (3.0 :: Double)) -- is (**) slow?\n in cr*cr*cr == x\n\nsolve :: Int64 -> Bool\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt -- overflow in input reading, silly me\n replicateM_ t $ do\n x <- readInt\n lift $ P.putStrLn $ case solve x of\n True -> P.pack \"YES\"\n False -> P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let -- OK, it's very stable.\n cr = floor $ 0.5 + fromIntegral x ** (1 / 3 :: Double)\n in cr*cr*cr == x -- is it (^3) that is slow?\n\nsolve :: Int64 -> Bool -- I doubt this is more than 30% faster...\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt -- overflow in input reading, silly me\n replicateM_ t $ do\n x <- readInt\n lift $ P.putStrLn $ case solve x of\n True -> P.pack \"YES\"\n False -> P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let -- OK, it's very stable.\n cr = round $ fromIntegral x ** (1 / 3 :: Double)\n in cr*cr*cr == x -- is it (^3) that is slow?\n\nsolve :: Int64 -> Bool -- I doubt this is more than 30% faster...\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt -- overflow in input reading, silly me\n replicateM_ t $ do\n x <- readInt\n lift $ P.putStrLn $ case solve x of\n True -> P.pack \"YES\"\n False -> P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let -- OK, it's very stable.\n cr = fromIntegral x ** (1 / 3 :: Double)\n in round cr ^ (3 :: Int) == x\n\nsolve :: Int64 -> Bool -- I doubt this is more than 30% faster...\nsolve v = any (isCube . snd) $ takeWhile (uncurry (<=)) $ do\n [(x, y) | i <- [1..], let { x = i*i*i; y = v - x }]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt -- overflow in input reading, silly me\n replicateM_ t $ do\n x <- readInt\n lift $ P.putStrLn $ case solve x of\n True -> P.pack \"YES\"\n False -> P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let -- OK, it's very stable.\n cr = fromIntegral x ** (1 / 3 :: Double)\n in round cr ^ (3 :: Int) == x\n\nsolve :: Int64 -> Bool\nsolve x = any isCube $ [v | i <- [1..10000], let v = x - i*i*i, v > 0]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n t <- readInt -- overflow in input reading, silly me\n replicateM_ t $ do\n x <- readInt\n lift $ P.putStrLn $ case solve x of\n True -> P.pack \"YES\"\n False -> P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInt :: Num t => SIO t\nreadInt = do\n currLine <- readLine\n let [Just (x, _)] = map P.readInteger $ P.words currLine\n pure $ fromInteger x\n"}, {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = Integer\r\ntype OutType = Bool\r\n\r\nbruteLim = 10 ^ 4 + 10\r\ncube x = x * x * x\r\n\r\nbinSearch l r x\r\n | l >= r = cube l == x\r\n | cube m>= x = binSearch l m x\r\n | otherwise = binSearch (m + 1) r x\r\n where m = (l + r) `div` 2\r\n\r\nisCube = binSearch 1 bruteLim\r\n\r\nsolve n = any (\\x -> isCube (n - cube x)) [1 .. bruteLim]\r\n\r\nreceive [s] = read s\r\n\r\nmain = interact (unlines . map (showBool . solve . receive . pure) . tail . lines)\r\n where showBool True = \"YES\"\r\n showBool False = \"NO\"\r\n"}, {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = Integer\r\ntype OutType = Bool\r\n\r\ninpLines = 1\r\n\r\nbruteLim = 10 ^ 4 + 10\r\n\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ncube x = x * x * x\r\n\r\nbinSearch l r x\r\n | l >= r = cube l == x\r\n | cube m>= x = binSearch l m x\r\n | otherwise = binSearch (m + 1) r x\r\n where m = (l + r) `div` 2\r\n\r\nisCube = binSearch 1 bruteLim\r\n\r\nsolve n = any (\\x -> isCube (n - cube x)) [1 .. bruteLim]\r\n\r\nreceive [s] = read s\r\n\r\nmain = interact (unlines . map (showBool . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showBool True = \"YES\"\r\n showBool False = \"NO\"\r\n"}, {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = Integer\r\ntype OutType = Bool\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nbruteLim = 10 ^ 4 + 10\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ncube :: Integer -> Integer\r\ncube x = x * x * x\r\n\r\nbinSearch :: Integer -> Integer -> Integer -> Bool\r\nbinSearch l r x\r\n | l >= r = cube l == x\r\n | cube m>= x = binSearch l m x\r\n | otherwise = binSearch (m + 1) r x\r\n where m = (l + r) `div` 2\r\n\r\nisCube :: Integer -> Bool\r\nisCube = binSearch 1 bruteLim\r\n\r\nsolve :: InType -> OutType\r\nsolve n = any (\\x -> isCube (n - cube x)) [1 .. bruteLim]\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = read s\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBool . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showBool True = \"YES\"\r\n showBool False = \"NO\"\r\n"}, {"source_code": "cubes :: [Integer]\ncubes = [r^3 | r <- [1..10^4]]\n\nisCube :: Integer -> Bool\nisCube x = any isRoot [candidate - 1, candidate, candidate + 1]\n where isRoot r = r^3 == x\n candidate = round $ fromIntegral x ** (1/3)\n\nisSumOfCubes :: Integer -> Bool\nisSumOfCubes x = any isHalf possibleHalves\n where possibleHalves = takeWhile ( String\nsolveTest x = if isSumOfCubes x then \"YES\" else \"NO\"\n\nsolve :: String -> String\nsolve = unlines . map (solveTest . read) . drop 1 . lines\n\nmain :: IO ()\nmain = interact solve\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\nisCube :: Int64 -> Bool\nisCube x = let\n cr = fromIntegral x ** (1 / 3 :: Double)\n in round cr ^ (3 :: Int) == x\n\nsolve :: Int64 -> Bool\nsolve x = any isCube $ [v | i <- [1..10000], let v = x - i*i*i, v > 0]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [x] <- map fromIntegral <$> readInts\n lift $ P.putStrLn $ case solve x of\n True -> P.pack \"YES\"\n False -> P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = Int\r\ntype OutType = Bool\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nbruteLim = 10 ^ 4 + 10\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ncube :: Int -> Int\r\ncube x = x * x * x\r\n\r\nbinSearch :: Int -> Int -> Int -> Bool\r\nbinSearch l r x\r\n | l >= r = cube l == x\r\n | cube m>= x = binSearch l m x\r\n | otherwise = binSearch (m + 1) r x\r\n where m = (l + r) `div` 2\r\n\r\nisCube :: Int -> Bool\r\nisCube = binSearch 1 bruteLim\r\n\r\nsolve :: InType -> OutType\r\nsolve n = any (\\x -> isCube (n - cube x)) [1 .. bruteLim]\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = read s\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBool . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showBool True = \"YES\"\r\n showBool False = \"NO\"\r\n"}], "src_uid": "b4ca6a5ee6307ab2bcdab2ea5dd5b2b3"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Array.Base\nimport Data.Array.ST\nimport Data.Bits\nimport Data.Ix\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n arr <- radixSort n.map readInt.B.words <$> B.getLine\n print $ solve n arr\n\nsolve :: Int -> UArray Int Int -> Int64\nsolve n arr0 = sum . map (unsafeAt arr.(n-)).takeWhile (<=n) $ iterate (4*) 1\n where\n !arr = runSTUArray $ do\n a <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int64)\n let go !i !acc = do\n when (i>=0) $ do\n let acc' = (acc+).fromIntegral $ unsafeAt arr0 i\n unsafeWrite a i acc'\n go (i-1) acc'\n go (n-1) 0\n return a\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nrep :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\n{-# INLINE rep #-}\n\nrev :: Monad m => Int -> (Int -> m ()) -> m ()\nrev !n f= go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rev #-}\n\nmask :: Int\nmask = 0xffff\n{-# INLINE mask #-}\n\nradixSort :: Int -> [Int] -> UArray Int Int\nradixSort n xs = runSTUArray $ do\n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n\n rep n $ \\i-> do\n xi <- unsafeRead arr i\n unsafeModify count (xi.&.mask) (1+)\n rep mask $ \\i-> do\n x <- unsafeRead count i\n unsafeModify count (i+1) (x+)\n rev n $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n rep (mask+1) $ \\i-> do\n unsafeWrite count i 0\n\n rep n $ \\i-> do\n xi <- unsafeRead arr i\n unsafeModify count ((xi`unsafeShiftR`16).&.mask) (1+)\n rep mask $ \\i-> do\n x <- unsafeRead count i\n unsafeModify count (i+1) (x+)\n rev n $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`unsafeShiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n\n return arr\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Array.Base\nimport Data.Array.ST\nimport Data.Bits\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n arr <- radixSort n.map readInt.B.words <$> B.getLine\n print $ solve n arr\n\nsolve :: Int -> UArray Int Int -> Int64\nsolve n arr0 = sum . map (unsafeAt arr.(n-)).takeWhile (<=n) $ iterate (4*) 1\n where\n !arr = runSTUArray $ do\n a <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int64)\n let go !i !acc = do\n when (i>=0) $ do\n let acc' = (acc+).fromIntegral $ unsafeAt arr0 i\n unsafeWrite a i acc'\n go (i-1) acc'\n go (n-1) 0\n return a\n\nmask :: Int\nmask = 0xffff\n\nradixSort :: Int -> [Int] -> UArray Int Int\nradixSort n xs = runSTUArray $ do\n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n \n forM_ xs $ \\x-> do\n let !mx = x.&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n forM_ [0..mask] $ \\i-> do\n unsafeWrite count i 0\n\n forM_ xs $ \\x-> do\n let !mx = (x`unsafeShiftR`16).&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`unsafeShiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n\n return arr\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0 >>> negate\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\nsolve :: [Int] -> Integer\nsolve [-1,x] = -fromIntegral x\nsolve (n:l) = - sum [sum $ take (4^i) l'| i <- takeWhile (\\i -> 4^i < -n)[0..]] - x\n where \n l' = map fromIntegral $ sort $ removeSome n l\n x = sum $ map fromIntegral l\n\nremoveSome n l = if length l1*4 >= n then l1 else l\n where\n a = minimum l\n b = maximum l\n c = (a+b)`div`2\n l1 = filter (<= c) l \n\n"}, {"source_code": "-- For benchmark. Based on not my solution but cojna's\n\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Array.Base\nimport Data.Array.ST\nimport Data.Bits\nimport Data.Ix\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n arr <- radixSort n.map readInt.B.words <$> B.getLine\n print $ solve n arr\n\nsolve :: Int -> UArray Int Int -> Int64\nsolve n arr0 = sum . map (unsafeAt arr.(n-)).takeWhile (<=n) $ iterate (4*) 1\n where\n !arr = runSTUArray $ do\n a <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int64)\n let go !i !acc = do\n when (i>=0) $ do\n let acc' = (acc+).fromIntegral $ unsafeAt arr0 i\n unsafeWrite a i acc'\n go (i-1) acc'\n go (n-1) 0\n return a\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nrep :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\n{-# INLINE rep #-}\n\nrev :: Monad m => Int -> (Int -> m ()) -> m ()\nrev !n f= go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rev #-}\n\nmask :: Int\nmask = 0xffff\n{-# INLINE mask #-}\n\nradixSort :: Int -> [Int] -> UArray Int Int\nradixSort n xs = runSTUArray $ do\n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n\n rep n $ \\i-> do\n xi <- unsafeRead arr i\n unsafeModify count (xi.&.mask) (1+)\n rep mask $ \\i-> do\n x <- unsafeRead count i\n unsafeModify count (i+1) (x+)\n rev n $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n rep (mask+1) $ \\i-> do\n unsafeWrite count i 0\n\n rep n $ \\i-> do\n xi <- unsafeRead arr i\n unsafeModify count ((xi`unsafeShiftR`16).&.mask) (1+)\n rep mask $ \\i-> do\n x <- unsafeRead count i\n unsafeModify count (i+1) (x+)\n rev n $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`unsafeShiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n\n return arr\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0 >>> negate\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\nsolve :: [Int] -> Integer\nsolve [-1,x] = -fromIntegral x\nsolve (n:l) = - sum [sum $ take (4^i) l'| i <- takeWhile (\\i -> 4^i < -n)[0..]] - x\n where \n l' = map fromIntegral $ sort $ removeSome n l\n x = sum $ map fromIntegral l\n\nremoveSome n l = if length l1*4 >= n then l1 else l\n where\n a = minimum l\n b = maximum l\n c = (a+b)`div`2\n l1 = filter (<= c) l \n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\n\nmain :: IO ()\nmain = print . solve . map stoi . B.words =<< B.getContents\n\nstoi :: B.ByteString -> Int64\nstoi = toEnum . negate . maybe 0 fst . B.readInt\n\nsolve :: [Int64] -> Int64\nsolve (_ : a : as) = negate $ sum $ scanl (+) a $ slice [0..] as\n where\n slice _ [] = []\n slice (i : is) xs = sum ys : slice is zs\n where\n (ys, zs) = splitAt (3 * 4 ^ i) xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (_ : as') = f 0 a as\n where\n (a : as) = map negate $ sort $ map negate as'\n f _ s [] = s\n f n s xs = seq s $ s + f (n + 1) (s + sum ys) zs\n where\n (ys, zs) = splitAt (3 * 4 ^ n) xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Function\nimport Data.Int\nimport Data.List\n\nmain :: IO ()\nmain = print . solve . map stoi . B.words =<< B.getContents\n\nstoi :: B.ByteString -> Int\nstoi = maybe 0 fst . B.readInt\n\nsolve :: [Int] -> Int64\nsolve (n : as') = sum $ scanl (+) (toEnum a) $ slice (n - 1) 3 as\n where\n (a : as) = sortBy (compare `on` negate) as'\n\nslice :: Int -> Int -> [Int] -> [Int64]\nslice s i xs\n | s <= i = [sum' xs]\n | otherwise = sum' ys : slice (s - i) (i * 4) zs\n where\n sum' = foldl' (\\x y -> x + toEnum y) 0\n (ys, zs) = splitAt i xs\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Maybe\nimport Debug.Trace\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\ntype Point = (Int,Int)\ntype Memo = A.Array Point Int\ndata Tree = Node Tree Tree Tree Tree\n | Leaf Int\n deriving(Show)\n\nsolve :: [Int] -> Integer\nsolve (n:l) = fst $ beauty tree\n where\n s = round $ sqrt $ fromIntegral n\n memo = A.listArray ((0,0),(s-1,s-1)) l\n tree = makeTree memo (0,0) (s,s) \n \n\nmakeTree :: Memo -> Point -> Point -> Tree\nmakeTree memo = sub\n where\n sub (x1,y1) (x2,y2) \n | x2 - x1 == 1 = Leaf (memo A.! (x1,y1))\n | otherwise = Node t1 t2 t3 t4\n where\n mx = (x1+x2) `div`2\n my = (y1+y2) `div`2\n t1 = sub (x1,y1) (mx,my)\n t2 = sub (mx,y1) (x2,my)\n t3 = sub (x1,my) (mx,y2)\n t4 = sub (mx,my) (x2,y2)\n \nbeauty :: Tree -> (Integer,Int) \nbeauty (Leaf i) = (fromIntegral i,i)\nbeauty (Node t1 t2 t3 t4) = f $ sum *** maximum $ unzip $ map beauty [t1,t2,t3,t4]\n where\n f (x,y) = (fromIntegral y+x,y)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0 >>> negate\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\nsolve :: [Int] -> Integer\nsolve (n:l) = - sum [sum $ take (4^i) l'| i <- takeWhile (\\i -> 4^i <= -n)[0..]] - x\n where \n l' = map fromIntegral $ sort $ removeSome n l\n x = sum $ map fromIntegral l\n\nremoveSome n l = if length l1*4 >= n then l1 else l\n where\n a = minimum l\n b = maximum l\n c = (a+b)`div`4\n l1 = filter (<= c) l \n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\ntype Point = (Int,Int)\ntype Memo = A.Array Point Int\ndata Tree = Node Tree Tree Tree Tree\n | Leaf Int\n deriving(Show)\n\nsolve :: [Int] -> Integer\nsolve (n:l) = fst $ beauty tree\n where\n s = floor $ sqrt $ fromIntegral n\n memo = A.listArray ((0,0),(s-1,s-1)) l\n tree = makeTree memo (0,0) (s-1,s-1) \n \n\nmakeTree :: Memo -> Point -> Point -> Tree\nmakeTree memo = sub\n where\n sub (x1,y1) (x2,y2) \n | x1 == x2 = Leaf (memo A.! (x1,y1))\n | otherwise = Node t1 t2 t3 t4\n where\n mx = (x1+x2) `div`2\n my = (y1+y2) `div`2\n t1 = sub (x1,y1) (mx,my)\n t2 = sub (mx+1,y1) (x2,my)\n t3 = sub (x1,my+1) (mx,y2)\n t4 = sub (mx+1,my+1) (x2,y2)\n \nbeauty :: Tree -> (Integer,Int) \nbeauty (Leaf i) = (fromIntegral i,i)\nbeauty (Node t1 t2 t3 t4) = f $ sum *** maximum $ unzip $ map beauty [t1,t2,t3,t4]\n where\n f (x,y) = (fromIntegral y+x,y)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\ntype Point = (Int,Int)\ntype Memo = A.Array Point Int\ndata Tree = Node Tree Tree Tree Tree\n | Leaf Int\n deriving(Show)\n\nsolve :: [Int] -> Integer\nsolve (n:l) = fst $ beauty tree\n where\n s = floor $ sqrt $ fromIntegral n\n memo = A.listArray ((0,0),(s-1,s-1)) l\n tree = makeTree memo (0,0) (s-1,s-1) \n \n\nmakeTree :: Memo -> Point -> Point -> Tree\nmakeTree memo = sub\n where\n sub (x1,y1) (x2,y2) \n | x1 == x2 = Leaf (memo A.! (x1,y1))\n | otherwise = Node t1 t2 t3 t4\n where\n mx = (x1+x2+1) `div`2\n my = (y1+y2+1) `div`2\n t1 = sub (x1,y1) (mx-1,my-1)\n t2 = sub (mx,y1) (x2,my-1)\n t3 = sub (x1,my) (mx-1,y2)\n t4 = sub (mx,my) (x2,y2)\n \nbeauty :: Tree -> (Integer,Int) \nbeauty (Leaf i) = (fromIntegral i,i)\nbeauty (Node t1 t2 t3 t4) = f $ sum *** maximum $ unzip $ map beauty [t1,t2,t3,t4]\n where\n f (x,y) = (fromIntegral y+x,y)\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array\nimport Debug.Trace\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0 >>> negate\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\nsolve :: [Int] -> Integer\nsolve [-1,x] = -fromIntegral x\nsolve (n:l) = - sum [sum $ take (4^i) l'| i <- takeWhile (\\i -> 4^i < -n)[0..]] - x\n where \n l' = map fromIntegral $ qsort $l \n x = sum $ map fromIntegral l\n\nremoveSome n l = if length l1*4 >= n then l1 else l\n where\n a = minimum l\n b = maximum l\n c = (a+b)`div`2\n l1 = filter (<= c) l \n\nqsort :: [Int] -> [Int]\nqsort l = elems $ runSTArray $ do\n ary <- newListArray (0,n-1) l :: ST s (STArray s Int Int)\n qsortST (0,n-1) ary\n return ary\n where\n n = length l\n\nmedian3 x y z | x <= y && y <= z = y\n | x <= y = max x z\n | z <= y = y\n | otherwise = min x z\n\nqsortST :: (Int,Int) -> (STArray s Int Int) -> ST s ()\nqsortST (i,j) ary \n | j == i = return ()\n | otherwise = do\n s <- readArray ary i\n e <- readArray ary j\n m <- readArray ary ((i+j)`div`2)\n let pivot = median3 s e m\n k <- partitionST (i,j) ary pivot (s,e)\n qsortST (i,k) ary\n qsortST (k+1,j) ary\n\npartitionST (i,j) ary p (a,b)\n | j - i < 1 = return i\n | a >= p && b <= p = do\n writeArray ary i b\n writeArray ary j a\n a' <- readArray ary (i+1)\n b' <- readArray ary (j-1)\n partitionST (i+1,j-1) ary p (a',b')\n | a >= p = do\n b' <- readArray ary (j-1)\n partitionST (i,j-1) ary p (a,b')\n | otherwise = do\n a' <- readArray ary (i+1)\n partitionST (i+1,j) ary p (a',b)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\ntype Point = (Int,Int)\ntype Memo = A.Array Point Int\ndata Tree = Node Tree Tree Tree Tree\n | Leaf Int\n deriving(Show)\n\nsolve :: [Int] -> Integer\nsolve (n:l) = fst $ beauty tree\n where\n s = round $ sqrt $ fromIntegral n\n memo = A.listArray ((0,0),(s-1,s-1)) l\n tree = makeTree memo (0,0) (s-1,s-1) \n \n\nmakeTree :: Memo -> Point -> Point -> Tree\nmakeTree memo = sub\n where\n sub (x1,y1) (x2,y2) \n | x1 == x2 = Leaf (memo A.! (x1,y1))\n | otherwise = Node t1 t2 t3 t4\n where\n mx = (x1+x2+1) `div`2\n my = (y1+y2+1) `div`2\n t1 = sub (x1,y1) (mx-1,my-1)\n t2 = sub (mx,y1) (x2,my-1)\n t3 = sub (x1,my) (mx-1,y2)\n t4 = sub (mx,my) (x2,y2)\n \nbeauty :: Tree -> (Integer,Int) \nbeauty (Leaf i) = (fromIntegral i,i)\nbeauty (Node t1 t2 t3 t4) = f $ sum *** maximum $ unzip $ map beauty [t1,t2,t3,t4]\n where\n f (x,y) = (fromIntegral y+x,y)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nstoi :: B.ByteString -> Int\nstoi = B.readInt >>> fmap fst >>> fromMaybe 0 >>> negate\n\nmain = do\n l <- map stoi . B.words <$> B.getContents\n print $ solve l\n\nsolve :: [Int] -> Integer\nsolve [-1,x] = -fromIntegral x\nsolve (n:l) = - sum [sum $ take (4^i) l'| i <- takeWhile (\\i -> 4^i <= -n)[0..]] - x\n where \n l' = map fromIntegral $ sort $ removeSome n l\n x = sum $ map fromIntegral l\n\nremoveSome n l = if length l1*4 >= n then l1 else l\n where\n a = minimum l\n b = maximum l\n c = (a+b)`div`4\n l1 = filter (<= c) l \n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Array.Base\nimport Data.Array.ST\nimport Data.Bits\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n arr <- radixSort n.map readInt.B.words <$> B.getLine\n print $ solve n arr\n\nsolve :: Int -> UArray Int Int -> Int64\nsolve n arr0 = sum . map (unsafeAt arr.subtract 1).takeWhile (<=n) $ iterate (4*) 1\n where\n !arr = runSTUArray $ do\n a <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int64)\n let go !i !acc = do\n when (i>=0) $ do\n let acc' = (acc+).fromIntegral $ unsafeAt arr0 i\n unsafeWrite a i acc'\n go (i-1) acc'\n go (n-1) 0\n return a\n\nmask :: Int\nmask = 0xffff\n\nradixSort :: Int -> [Int] -> UArray Int Int\nradixSort n xs = runSTUArray $ do\n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n \n forM_ xs $ \\x-> do\n let !mx = x.&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n forM_ [0..mask] $ \\i-> do\n unsafeWrite count i 0\n\n forM_ xs $ \\x-> do\n let !mx = (x`unsafeShiftR`16).&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i-> do\n xi <- unsafeRead tmp i\n let !mi = (xi`unsafeShiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n\n return arr\n"}], "src_uid": "93f6404a23bd2ff867d63db9ddf868ff"} {"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> map (words >>> map read) >>> \n solve >>> (\\ans -> [show $ length ans, ans]) >>> unlines\n \nsolve :: [[Int]] -> String\nsolve ([n,m,k]:_) = take (2 * n * m) $ \n (take (n - 1) $ repeat 'U') ++ \n (take (m - 1) $ repeat 'L') ++\n (foldr (++) \"\" $ take n $ repeat\n (take (m - 1) (repeat 'R') ++ \"D\" ++\n take (m - 1) (repeat 'L') ++ \"D\"))\n", "positive_code": [{"source_code": "\nimport Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>> map (words >>> map read)\n >>> solve\n >>> (\\ans -> [show (length ans), ans])\n >>> unlines\n\nsolve :: [[Int]] -> String\nsolve ([n, m, _] : _) =\n take (2 * n * m) $\n replicate (n - 1) 'U' ++ replicate (m - 1) 'L'\n ++ concat\n ( replicate\n n\n (replicate (m - 1) 'R' ++ \"D\" ++ replicate (m - 1) 'L' ++ \"D\")\n )\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n [n,m,k] <- (map read.words) <$> getLine\n replicateM_ (2*k) getLine\n print (n*m+n+m-3)\n putStrLn $ solve n m\n\nsolve :: Int -> Int -> String\nsolve m n = replicate (n-1) 'L' ++ replicate (m-1) 'D' ++ take (n*m-1) frst\n where\n frst = replicate (n-1) 'R' ++ \"U\" ++ replicate (n-1) 'L' ++ \"U\" ++ frst\n--n lr m ud\n"}], "negative_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n [n,m,k] <- (map read.words) <$> getLine\n replicateM_ (2*k) getLine\n putStrLn $ solve n m\n\nsolve :: Int -> Int -> String\nsolve n m = replicate (n-1) 'L' ++ replicate (m-1) 'D' ++ take (n*m-1) frst\n where\n frst = replicate (n-1) 'R' ++ \"U\" ++ replicate (n-1) 'L' ++ \"U\" ++ frst\n--n lr m ud\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n [n,m,k] <- (map read.words) <$> getLine\n replicateM_ (2*k) getLine\n print (n*m+n+m-3)\n putStrLn $ solve n m\n\nsolve :: Int -> Int -> String\nsolve n m = replicate (n-1) 'L' ++ replicate (m-1) 'D' ++ take (n*m-1) frst\n where\n frst = replicate (n-1) 'R' ++ \"U\" ++ replicate (n-1) 'L' ++ \"U\" ++ frst\n--n lr m ud\n"}], "src_uid": "90ce515c561872b5e2ec5f8f75cd44fe"} {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Control.Monad (mapM_)\nimport Data.Int (Int64)\n\ntype Block = (Int, Int) -- (start, length)\n\ncY = 'Y'\ncN = 'N'\n\nrow :: Int -> Block -> Block -> ByteString\nrow end (pstart, plen) (nstart, nlen) =\n BS.pack $ col1 ++ col2 ++ pre ++ blk1 ++ mid ++ blk2 ++ post\n where\n col1 = if plen == 0 then [cY] else [cN]\n col2 = if nlen == 0 then [cY] else [cN]\n pend = pstart+plen\n nend = nstart+nlen\n pre = replicate (pstart-3) cN\n blk1 = replicate plen cY\n mid = replicate (nstart-pend) cN\n blk2 = replicate nlen cY\n post = replicate (end-nend) cN\n\ntriples :: [a] -> [(a,a,a)]\ntriples [] = []\ntriples [_,_] = []\ntriples xs@(a:b:c:_) = (a,b,c) : triples (tail xs)\n\nrows :: Int -> [ Block ] -> [ByteString]\nrows end blks =\n [ r' | (a,(bstart,blen),c) <- blks', let r = row end a c, r' <- replicate blen r ]\n where blks' = triples $ [(3,0)] ++ blks ++ [(end,0)]\n\n-- return a string with Ys in the positions indicated and N's elsewhere\npattern :: Int -> [Block] -> ByteString\npattern end blks = BS.pack $ go 1 blks\n where\n go k [] = replicate (end-k) cN\n go k ((start,len):rest) = replicate (start-k) cN ++ replicate len cY ++ go (start+len) rest\n\nrow1 :: Int -> [ [Block] ] -> ByteString\nrow1 end blks = pattern end (map head blks)\n\nrow2 :: Int -> [ [Block] ] -> ByteString\nrow2 end blks = pattern end (map last blks)\n\ntest1 = do let blks = [(3,3),(6,2)]\n mapM_ BS.putStrLn $ [row1 8 [blks], row2 8 [blks]] ++ rows 8 blks\n\nassign' :: Int -> [Int] -> (Int,[Block])\nassign' k [] = (k,[])\nassign' k xs = (m, blks)\n where\n blks = go k xs\n m = let (k,a) = last blks in a+k\n go k [] = []\n go k (a:as) = (k,a) : go (k+a) as\n\n-- assume all lists have the same length\nassign :: [[Int]] -> (Int, [[Block]])\nassign [] = (3, [])\nassign xs = (m,blkss)\n where \n blkss = go 3 xs\n m = let (k,a) = (last (last blkss))\n in a+k\n go k [] = []\n go k (x:xs) = let (k',bs) = assign' k x\n in bs : go k' xs\n\n-- | make all the lengths the same by extending short lists with 1\nnormalize :: [[Int]] -> [[Int]]\nnormalize xss =\n let m = maximum (map length xss)\n in map (\\xs -> replicate (m - length xs) 1 ++ xs) xss\n\ngraph :: Int -> [[Block]] -> [ByteString]\ngraph end blkss =\n [row1 end blkss, row2 end blkss] ++ concatMap (rows end) blkss\n\nbAdd :: [[Int]] -> [[Int]] -> [[Int]]\nbAdd as bs = as ++ bs\n\nbMul :: Int -> [[Int]] -> [[Int]]\nbMul n bss = map (n:) bss\n\ntoInts :: Int -> Int64 -> [[Int]]\ntoInts base 0 = []\ntoInts base n =\n case n `divMod` (fromIntegral base) of\n (q,0) -> base `bMul` (toInts base q)\n (q,r) -> (base `bMul` (toInts base q)) `bAdd` [[fromIntegral r]]\n\nnodeCount :: [[Int]] -> Int\nnodeCount = sum . concat\n\ntoBlocks :: Int -> Int64 -> (Int,[[Block]])\ntoBlocks base = assign . normalize . toInts base\n\nsolve :: Int -> Int64 -> (Int,[ByteString])\nsolve base n =\n let (end,blkss) = toBlocks base n\n in (end, graph end blkss)\n\nmain = do\n n <- read `fmap` getLine\n let (end,lines) = solve 4 n\n print (end-1)\n mapM_ BS.putStrLn lines\n\n", "positive_code": [{"source_code": "import qualified Data.IntMap as IM\nimport Data.List (foldl')\nimport qualified Data.IntSet as IS\n\ndecomp :: Integer -> [Bool]\ndecomp x = decomp' x []\n where\n decomp' 0 l = l\n decomp' k l\n | k `mod` 2 == 1 = decomp' (k `div` 2) (True:l)\n | otherwise = decomp' (k `div` 2) (False:l)\n \n\n\nmain :: IO ()\nmain = do\n i <- fmap read getLine\n let bits = decomp i\n --print $ rush bits\n putStr $ pp $ rush bits\n\npp :: Graph -> String\npp (g,m) = unlines $ show m : pg\n where pg = foldr (\\i l -> let Just es = IM.lookup i g\n in map (\\j -> if IS.member j es then 'Y' else 'N') [1..m] : l) [] [1..m]\n\ntype Graph = (IM.IntMap IS.IntSet, Int) \n\nemptyGraph :: Graph \nemptyGraph = (IM.fromList [(1, IS.empty), (2, IS.empty)], 2)\n\ninsert2 :: (Int, Int) -> Graph -> Graph\ninsert2 (a,b) (g, m) = (g', m + 2)\n where\n prev = IS.fromList [a, b]\n g' = f (m + 1) $ f (m + 2) g\n f x gg = IM.update (Just . (IS.insert x)) a $ IM.update (Just . (IS.insert x)) b $ IM.insert x prev gg\n\ninsert2' :: Graph -> Graph\ninsert2' g@(_,m) = insert2 (m, m - 1) g\n\ninsert2'' :: (IM.IntMap IS.IntSet, Int) -> Graph\ninsert2'' g@(_,m) = insert2 (m,m) g\n\ninsert1 :: Int -> Graph -> Graph\ninsert1 a (g, m) = (g', m + 1)\n where\n prev = IS.singleton a\n g' = IM.update (Just . (IS.insert (m + 1))) a $ IM.insert (m + 1) prev g\n\ninsert1' :: Graph -> Graph\ninsert1' g@(_,m) = insert1 m g\n\nconnect :: (Int, Int) -> Graph -> Graph\nconnect (a,b) (g,m) = (IM.update (Just . (IS.insert a)) b $ IM.update (Just . (IS.insert b)) a g, m)\n\nconnect' :: Int -> Graph -> Graph\nconnect' a g@(_,m) = connect (a,m) g\n\nclose1 :: Graph -> Graph\nclose1 g@(_,m) = connect (2,m) g\n\nclose2 :: Graph -> Graph\nclose2 g@(_,m) = connect (2,m) . connect (2, m - 1) $ g\n\nrush :: [Bool] -> Graph\nrush [True] = connect (1,2) emptyGraph\nrush l = let len = length l\n z = zip l [0..]\n build 0 = insert2 (1,1) : replicate (len - 2) insert2' ++ [close2]\n build x \n | x == len - 1 = insert1 1 : replicate (len - 2) insert1' ++ [close1]\n | otherwise = insert1 1 : replicate (x - 1) insert1' ++ [connect' (2*x+3), connect' (2*x+4)]\n apply = foldl' (\\g f -> f g) \n in\n foldl' (\\g (t,non2) -> if t then apply g (build non2) else g) emptyGraph z\n \n\n"}], "negative_code": [{"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Control.Monad (mapM_)\nimport Data.Int (Int64)\n\ntype Block = (Int, Int) -- (start, length)\n\ncY = 'Y'\ncN = 'N'\n\nrow :: Int -> Block -> Block -> ByteString\nrow end (pstart, plen) (nstart, nlen) =\n BS.pack $ col1 ++ col2 ++ pre ++ blk1 ++ mid ++ blk2 ++ post\n where\n col1 = if plen == 0 then [cY] else [cN]\n col2 = if nlen == 0 then [cY] else [cN]\n pend = pstart+plen\n nend = nstart+nlen\n pre = replicate (pstart-3) cN\n blk1 = replicate plen cY\n mid = replicate (nstart-pend) cN\n blk2 = replicate nlen cY\n post = replicate (end-nend) cN\n\ntriples :: [a] -> [(a,a,a)]\ntriples [] = []\ntriples [_,_] = []\ntriples xs@(a:b:c:_) = (a,b,c) : triples (tail xs)\n\nrows :: Int -> [ Block ] -> [ByteString]\nrows end blks =\n [ r' | (a,(bstart,blen),c) <- blks', let r = row end a c, r' <- replicate blen r ]\n where blks' = triples $ [(3,0)] ++ blks ++ [(end,0)]\n\n-- return a string with Ys in the positions indicated and N's elsewhere\npattern :: Int -> [Block] -> ByteString\npattern end blks = BS.pack $ go 1 blks\n where\n go k [] = replicate (end-k) cN\n go k ((start,len):rest) = replicate (start-k) cN ++ replicate len cY ++ go (start+len) rest\n\nrow1 :: Int -> [ [Block] ] -> ByteString\nrow1 end blks = pattern end (map head blks)\n\nrow2 :: Int -> [ [Block] ] -> ByteString\nrow2 end blks = pattern end (map last blks)\n\ntest1 = do let blks = [(3,3),(6,2)]\n mapM_ BS.putStrLn $ [row1 8 [blks], row2 8 [blks]] ++ rows 8 blks\n\nassign' :: Int -> [Int] -> (Int,[Block])\nassign' k [] = (k,[])\nassign' k xs = (m, blks)\n where\n blks = go k xs\n m = let (k,a) = last blks in a+k\n go k [] = []\n go k (a:as) = (k,a) : go (k+a) as\n\n-- assume all lists have the same length\nassign :: [[Int]] -> (Int, [[Block]])\nassign [] = (3, [])\nassign xs = (m,blkss)\n where \n blkss = go 3 xs\n m = let (k,a) = (last (last blkss))\n in a+k\n go k [] = []\n go k (x:xs) = let (k',bs) = assign' k x\n in bs : go k' xs\n\n-- | make all the lengths the same by extending short lists with 1\nnormalize :: [[Int]] -> [[Int]]\nnormalize xss =\n let m = maximum (map length xss)\n in map (\\xs -> replicate (m - length xs) 1 ++ xs) xss\n\ngraph :: Int -> [[Block]] -> [ByteString]\ngraph end blkss =\n [row1 end blkss, row2 end blkss] ++ concatMap (rows end) blkss\n\nbAdd :: [[Int]] -> [[Int]] -> [[Int]]\nbAdd as bs = as ++ bs\n\nbMul :: Int -> [[Int]] -> [[Int]]\nbMul n bss = map (n:) bss\n\ntoInts :: Int -> Int64 -> [[Int]]\ntoInts base 0 = []\ntoInts base n =\n case n `divMod` (fromIntegral base) of\n (q,0) -> base `bMul` (toInts base q)\n (q,r) -> (base `bMul` (toInts base q)) `bAdd` [[fromIntegral r]]\n\nnodeCount :: [[Int]] -> Int\nnodeCount = sum . concat\n\ntoBlocks :: Int -> Int64 -> (Int,[[Block]])\ntoBlocks base = assign . normalize . toInts base\n\nsolve :: Int64 -> (Int,[ByteString])\nsolve n =\n let (end,blkss) = toBlocks 2 n\n in (end, graph end blkss)\n\nmain = do\n n <- read `fmap` getLine\n let (end,lines) = solve n\n print (end-1)\n mapM_ BS.putStrLn lines\n\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Control.Monad (mapM_)\n\ntype Block = (Int, Int) -- (start, length)\n\ncY = 'Y'\ncN = 'N'\n\nrow :: Int -> Block -> Block -> ByteString\nrow end (pstart, plen) (nstart, nlen) =\n BS.pack $ col1 ++ col2 ++ pre ++ blk1 ++ mid ++ blk2 ++ post\n where\n col1 = if plen == 0 then [cY] else [cN]\n col2 = if nlen == 0 then [cY] else [cN]\n pend = pstart+plen\n nend = nstart+nlen\n pre = replicate (pstart-3) cN\n blk1 = replicate plen cY\n mid = replicate (nstart-pend) cN\n blk2 = replicate nlen cY\n post = replicate (end-nend) cN\n\ntriples :: [a] -> [(a,a,a)]\ntriples [] = []\ntriples [_,_] = []\ntriples xs@(a:b:c:_) = (a,b,c) : triples (tail xs)\n\nrows :: Int -> [ Block ] -> [ByteString]\nrows end blks =\n [ r' | (a,(bstart,blen),c) <- blks', let r = row end a c, r' <- replicate blen r ]\n where blks' = triples $ [(3,0)] ++ blks ++ [(end,0)]\n\n-- return a string with Ys in the positions indicated and N's elsewhere\npattern :: Int -> [Block] -> ByteString\npattern end blks = BS.pack $ go 1 blks\n where\n go k [] = replicate (end-k) cN\n go k ((start,len):rest) = replicate (start-k) cN ++ replicate len cY ++ go (start+len) rest\n\nrow1 :: Int -> [ [Block] ] -> ByteString\nrow1 end blks = pattern end (map head blks)\n\nrow2 :: Int -> [ [Block] ] -> ByteString\nrow2 end blks = pattern end (map last blks)\n\ntest1 = do let blks = [(3,3),(6,2)]\n mapM_ BS.putStrLn $ [row1 8 [blks], row2 8 [blks]] ++ rows 8 blks\n\nassign' :: Int -> [Int] -> (Int,[Block])\nassign' k [] = (k,[])\nassign' k xs = (m, blks)\n where\n blks = go k xs\n m = let (k,a) = last blks in a+k\n go k [] = []\n go k (a:as) = (k,a) : go (k+a) as\n\n-- assume all lists have the same length\nassign :: [[Int]] -> (Int, [[Block]])\nassign [] = (3, [])\nassign xs = (m,blkss)\n where \n blkss = go 3 xs\n m = let (k,a) = (last (last blkss))\n in a+k\n go k [] = []\n go k (x:xs) = let (k',bs) = assign' k x\n in bs : go k' xs\n\n-- | make all the lengths the same by extending short lists with 1\nnormalize :: [[Int]] -> [[Int]]\nnormalize xss =\n let m = maximum (map length xss)\n in map (\\xs -> replicate (m - length xs) 1 ++ xs) xss\n\ngraph :: Int -> [[Block]] -> [ByteString]\ngraph end blkss =\n [row1 end blkss, row2 end blkss] ++ concatMap (rows end) blkss\n\nbAdd :: [[Int]] -> [[Int]] -> [[Int]]\nbAdd as bs = as ++ bs\n\nbMul :: Int -> [[Int]] -> [[Int]]\nbMul n bss = map (n:) bss\n\ntoInts :: Int -> Int -> [[Int]]\ntoInts base 0 = []\ntoInts base n =\n case n `divMod` base of\n (q,0) -> base `bMul` (toInts base q)\n (q,r) -> (base `bMul` (toInts base q)) `bAdd` [[r]]\n\nnodeCount :: [[Int]] -> Int\nnodeCount = sum . concat\n\ntoBlocks :: Int -> Int -> (Int,[[Block]])\ntoBlocks base = assign . normalize . toInts base\n\nsolve :: Int -> (Int,[ByteString])\nsolve n =\n let (end,blkss) = toBlocks 2 n\n in (end, graph end blkss)\n\nmain = do\n n <- read `fmap` getLine\n let (end,lines) = solve n\n print (end-1)\n mapM_ BS.putStrLn lines\n\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Control.Monad (mapM_)\n\ntype Block = (Int, Int) -- (start, length)\n\ncY = 'Y'\ncN = 'N'\n\nrow :: Int -> Block -> Block -> ByteString\nrow end (pstart, plen) (nstart, nlen) =\n BS.pack $ col1 ++ col2 ++ pre ++ blk1 ++ mid ++ blk2 ++ post\n where\n col1 = if plen == 0 then [cY] else [cN]\n col2 = if nlen == 0 then [cY] else [cN]\n pend = pstart+plen\n nend = nstart+nlen\n pre = replicate (pstart-3) cN\n blk1 = replicate plen cY\n mid = replicate (nstart-pend) cN\n blk2 = replicate nlen cY\n post = replicate (end-nend) cY\n\ntriples :: [a] -> [(a,a,a)]\ntriples [] = []\ntriples [_,_] = []\ntriples xs@(a:b:c:_) = (a,b,c) : triples (tail xs)\n\nrows :: Int -> [ Block ] -> [ByteString]\nrows end blks =\n [ r' | (a,(bstart,blen),c) <- blks', let r = row end a c, r' <- replicate blen r ]\n where blks' = triples $ [(3,0)] ++ blks ++ [(end,0)]\n\n-- return a string with Ys in the positions indicated and N's elsewhere\npattern :: Int -> [Block] -> ByteString\npattern end blks = BS.pack $ go 1 blks\n where\n go k [] = replicate (end-k) cN\n go k ((start,len):rest) = replicate (start-k) cN ++ replicate len cY ++ go (start+len) rest\n\nrow1 :: Int -> [ [Block] ] -> ByteString\nrow1 end blks = pattern end (map head blks)\n\nrow2 :: Int -> [ [Block] ] -> ByteString\nrow2 end blks = pattern end (map last blks)\n\ntest1 = do let blks = [(3,3),(6,2)]\n mapM_ BS.putStrLn $ [row1 8 [blks], row2 8 [blks]] ++ rows 8 blks\n\nassign' :: Int -> [Int] -> (Int,[Block])\nassign' k [] = (k,[])\nassign' k xs = (fst (last blks), blks)\n where\n blks = go k xs\n go k [] = []\n go k (a:as) = (k,a) : go (k+a) as\n\n-- assume all lists have the same length\nassign :: [[Int]] -> (Int, [[Block]])\nassign [] = (3, [])\nassign xs = (m,blkss)\n where \n blkss = go 3 xs\n m = let (k,a) = (last (last blkss))\n in a+k\n go k [] = []\n go k (x:xs) = let (k',bs) = assign' k x\n in bs : go k' xs\n\n-- | make all the lengths the same by extending short lists with 1\nnormalize :: [[Int]] -> [[Int]]\nnormalize xss =\n let m = maximum (map length xss)\n in map (\\xs -> replicate (m - length xs) 1 ++ xs) xss\n\ngraph :: Int -> [[Block]] -> [ByteString]\ngraph end blkss =\n [row1 end blkss, row2 end blkss] ++ concatMap (rows end) blkss\n\nbAdd :: [[Int]] -> [[Int]] -> [[Int]]\nbAdd as bs = as ++ bs\n\nbMul :: Int -> [[Int]] -> [[Int]]\nbMul n bss = map (n:) bss\n\ntoInts :: Int -> Int -> [[Int]]\ntoInts base 0 = []\ntoInts base n =\n case n `divMod` base of\n (q,0) -> base `bMul` (toInts base q)\n (q,r) -> (base `bMul` (toInts base q)) `bAdd` [[r]]\n\nnodeCount :: [[Int]] -> Int\nnodeCount = sum . concat\n\ntoBlocks :: Int -> Int -> (Int,[[Block]])\ntoBlocks base = assign . normalize . toInts base\n\nsolve :: Int -> (Int,[ByteString])\nsolve n =\n let (end,blkss) = toBlocks 2 n\n in (end, graph end blkss)\n\nmain = do\n n <- read `fmap` getLine\n let (end,lines) = solve n\n print (end-1)\n mapM_ BS.putStrLn lines\n\n"}, {"source_code": "import qualified Data.IntMap as IM\nimport Data.List (foldl')\nimport qualified Data.IntSet as IS\n\ndecomp :: Integer -> [Bool]\ndecomp x = decomp' x []\n where\n decomp' 0 l = l\n decomp' k l\n | k `mod` 2 == 1 = decomp' (k `div` 2) (True:l)\n | otherwise = decomp' (k `div` 2) (False:l)\n \n\n\nmain :: IO ()\nmain = do\n i <- fmap read getLine\n let bits = decomp i\n print bits\n --print $ rush bits\n putStr $ pp $ rush bits\n\npp :: Graph -> String\npp (g,m) = unlines $ show m : pg\n where pg = foldr (\\i l -> let Just es = IM.lookup i g\n in map (\\j -> if IS.member j es then 'Y' else 'N') [1..m] : l) [] [1..m]\n\ntype Graph = (IM.IntMap IS.IntSet, Int) \n\nemptyGraph :: Graph \nemptyGraph = (IM.fromList [(1, IS.empty), (2, IS.empty)], 2)\n\ninsert2 :: (Int, Int) -> Graph -> Graph\ninsert2 (a,b) (g, m) = (g', m + 2)\n where\n prev = IS.fromList [a, b]\n g' = f (m + 1) $ f (m + 2) g\n f x gg = IM.update (Just . (IS.insert x)) a $ IM.update (Just . (IS.insert x)) b $ IM.insert x prev gg\n\ninsert2' :: Graph -> Graph\ninsert2' g@(_,m) = insert2 (m, m - 1) g\n\ninsert2'' :: (IM.IntMap IS.IntSet, Int) -> Graph\ninsert2'' g@(_,m) = insert2 (m,m) g\n\ninsert1 :: Int -> Graph -> Graph\ninsert1 a (g, m) = (g', m + 1)\n where\n prev = IS.singleton a\n g' = IM.update (Just . (IS.insert (m + 1))) a $ IM.insert (m + 1) prev g\n\ninsert1' :: Graph -> Graph\ninsert1' g@(_,m) = insert1 m g\n\nconnect :: (Int, Int) -> Graph -> Graph\nconnect (a,b) (g,m) = (IM.update (Just . (IS.insert a)) b $ IM.update (Just . (IS.insert b)) a g, m)\n\nconnect' :: Int -> Graph -> Graph\nconnect' a g@(_,m) = connect (a,m) g\n\nclose1 :: Graph -> Graph\nclose1 g@(_,m) = connect (2,m) g\n\nclose2 :: Graph -> Graph\nclose2 g@(_,m) = connect (2,m) . connect (2, m - 1) $ g\n\nrush :: [Bool] -> Graph\nrush [True] = connect (1,2) emptyGraph\nrush l = let len = length l\n z = zip l [0..]\n build 0 = insert2 (1,1) : replicate (len - 2) insert2' ++ [close2]\n build x \n | x == len - 1 = insert1 1 : replicate (len - 2) insert1' ++ [close1]\n | otherwise = insert1 1 : replicate (x - 1) insert1' ++ [connect' (2*x+3), connect' (2*x+4)]\n apply = foldl' (\\g f -> f g) \n in\n foldl' (\\g (t,non2) -> if t then apply g (build non2) else g) emptyGraph z\n \n\n"}, {"source_code": "import qualified Data.IntMap as IM\nimport Data.List (foldl')\nimport qualified Data.IntSet as IS\n\ndecomp :: Integer -> [Bool]\ndecomp x = decomp' x []\n where\n decomp' 0 l = l\n decomp' k l\n | k `mod` 2 == 1 = decomp' (k `div` 2) (True:l)\n | otherwise = decomp' (k `div` 2) (False:l)\n \n\n\nmain :: IO ()\nmain = do\n i <- fmap read getLine\n let bits = decomp i\n --print $ rush bits\n putStr $ pp $ rush bits\n\npp :: Graph -> String\npp (g,m) = unlines $ show m : pg\n where pg = foldr (\\i l -> let Just es = IM.lookup i g\n in map (\\j -> if IS.member j es then 'Y' else 'N') [1..m] : l) [] [1..m]\n\ntype Graph = (IM.IntMap IS.IntSet, Int) \n\nemptyGraph :: Graph \nemptyGraph = (IM.fromList [(1, IS.empty), (2, IS.empty)], 2)\n\ninsert2 :: (Int, Int) -> Graph -> Graph\ninsert2 (a,b) (g, m) = (g', m + 2)\n where\n prev = IS.fromList [a, b]\n g' = f (m + 1) $ f (m + 2) g\n f x gg = IM.update (Just . (IS.insert x)) a $ IM.update (Just . (IS.insert x)) b $ IM.insert x prev gg\n\ninsert2' :: Graph -> Graph\ninsert2' g@(_,m) = insert2 (m, m - 1) g\n\ninsert2'' :: (IM.IntMap IS.IntSet, Int) -> Graph\ninsert2'' g@(_,m) = insert2 (m,m) g\n\ninsert1 :: Int -> Graph -> Graph\ninsert1 a (g, m) = (g', m + 1)\n where\n prev = IS.singleton a\n g' = IM.update (Just . (IS.insert (m + 1))) a $ IM.insert (m + 1) prev g\n\ninsert1' :: Graph -> Graph\ninsert1' g@(_,m) = insert1 m g\n\nconnect :: (Int, Int) -> Graph -> Graph\nconnect (a,b) (g,m) = (IM.update (Just . (IS.insert a)) b $ IM.update (Just . (IS.insert b)) a g, m)\n\nclose1 :: Graph -> Graph\nclose1 g@(_,m) = connect (2,m) g\n\nclose2 :: Graph -> Graph\nclose2 g@(_,m) = connect (2,m) . connect (2, m - 1) $ g\n\nrush :: [Bool] -> Graph\nrush [True] = connect (1,2) emptyGraph\nrush l = let len = length l\n z = zip l [0..]\n build 0 = insert2 (1,1) : replicate (len - 2) insert2' ++ [close2]\n build x \n | x == len - 1 = insert1 1 : replicate (len - 2) insert1' ++ [close1]\n | otherwise = insert1 1 : replicate (x - 1) insert1' ++ [insert2''] ++ replicate (len - 2 - x) insert2' ++ [close2]\n apply = foldl' (\\g f -> f g) \n in\n foldr (\\(t,non2) g -> if t then apply g (build non2) else g) emptyGraph z\n \n\n"}], "src_uid": "30a8d761d5b5103a5b926290634c8fbe"} {"source_code": "import Data.Bits\nimport Control.Monad\n\ncalcXor :: Int -> Int\ncalcXor n | n `mod` 4 == 0 = n\n | n `mod` 4 == 1 = 1\n | n `mod` 4 == 2 = n+1\n | otherwise = 0\n\ncalc :: Int -> Int -> Int\ncalc a b =\n let x = calcXor (a-1) in\n if x == b then a\n else if x `xor` b /= a then a+1\n else a+2\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b] = map read $ words line :: [Int]\n putStrLn $ show $ calc a b\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bits (xor)\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = pair int int\n\n-- output :: Output -> C.ByteString\noutput = showB\n\n-- solve :: Input -> Output\nsolve (a, b)\n | rem == 0 = a\n | rem /= a = a + 1\n | otherwise = a + 2\n where\n rem = b `xor` (xors ! (a - 1))\n\nmaxn = 3 * 10^5 + 10\n\nxors :: UArray Int Int\nxors = listArray (0, maxn) $ scanl1 xor [0..maxn]\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "d6790c9b4b2e488768fb4e746ee7ebe0"} {"source_code": "import Control.Monad\r\n\r\nsolve [] [] = []\r\nsolve (x:xs) (y:ys) = x : y : solve xs ys\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n let m = n - 3 * mod n 2\r\n r = solve [2,4..m] [1,3..m-1] ++ if odd n then [n-1,n,n-2] else []\r\n putStrLn . unwords . map show $ r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nprettyPermutation (x0:x1:x2:[]) = x2 : x0 : x1 : []\nprettyPermutation (x0:x1:xs)\n | null xs = x1 : x0 : []\n | otherwise = x1 : x0 : prettyPermutation xs\n\nsolve n = unwords $ map show $ prettyPermutation [1..n]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- readInt <$> getLine\n replicateM_ n $ do\n x <- readInt <$> getLine\n putStrLn $ solve x\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified System.IO as Io\n--import Data.IntSet \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n let res = map (\\x -> if even x then x-1 else x+1) [1..n]\n sol = if even n then res else (take (n-3) res) ++ [res !! (n-3) + 1, res !! (n-2),\n res !! (n-1) - 2]\n in putStrLn $ intercalate \" \" $ map show sol\n\n \n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n \n \n"}, {"source_code": "import Control.Monad ( replicateM_ )\r\n\r\nsolve :: IO()\r\nsolve = do\r\n n <- readInt <$> getLine\r\n let at n i \r\n | even n || i < n - 2 = if odd i then i + 1 else i - 1\r\n | i == n - 2 = n\r\n | otherwise = i - 1\r\n putStrLn $ unwords $ map (show . at n) [1..n]\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nmain :: IO()\r\nmain = do\r\n t <- readInt <$> getLine\r\n replicateM_ t solve\r\n"}, {"source_code": "\r\nimport Control.Monad\r\nimport Control.Monad (forever)\r\nimport System.Exit (exitSuccess)\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintlr (l,r) --- has the Str type => need putStr to convert to IO \r\n | l > r = \"\"\r\n | otherwise =\r\n if (l `mod` 2 ==1) then show(l+1) ++ \" \" ++ printlr (l+1,r)\r\n else show(l-1) ++ \" \" ++ printlr (l+1,r)\r\nsolve = do\r\n n <- readLn :: IO Int\r\n if (n `mod` 2 == 0) then putStrLn $ printlr (1,n) --- \r\n else do\r\n putStr $ printlr (1,n-3);\r\n putStrLn $ show(n-1) ++\" \"++ show(n) ++\" \"++ show(n-2)\r\nmain :: IO()\r\nmain = do\r\n test <- readLn ::IO Int \r\n replicateM_ test solve \r\n\r\n\r\n\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Bits\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nsolve i r \r\n | i > r = \"\"\r\n | otherwise = \r\n if (mod i 2 == 1) then show(i+1) ++ \" \" ++ solve (i+1) r \r\n else show(i-1) ++ \" \" ++ solve(i+1) r\r\n\r\neach = do \r\n n<-readLn::IO Int \r\n if (mod n 2 == 1) then do{\r\n putStr $ solve 1 (n-3) ;\r\n putStrLn $ show n ++ \" \" ++ show (n-2) ++ \" \" ++ show(n-1)\r\n }\r\n else putStrLn $ solve 1 n\r\n\r\nmain = do \r\n t<-readLn::IO Int \r\n replicateM_ t each "}, {"source_code": "-- cheese-cracker: cheese-cracker.github.io\nimport Control.Monad\nimport Control.Arrow ((>>>))\nimport Data.List as L\nimport Data.Maybe (fromJust)\n-- import Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as BS\nimport Debug.Trace\ntracer arr = trace(foldr (++) [] $ map (++\" \") $ map show arr) False\n\ngetStrList :: IO [BS.ByteString]\ngetStrList = BS.words <$> BS.getLine\n\nreadInts :: IO [Int]\nreadInts = (map (fromInteger . fst . fromJust. BS.readInteger) . BS.words) <$> BS.getLine\n\nconstr [] = []\nconstr (x:y:xs) = y:x:(constr xs)\n\nsolve n\n | (n `mod` 2 == 1) = 2:constr (1:[3..n])\n | (n `mod` 2 == 0) = constr [1..n]\n\nmain :: IO ()\nmain = do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n putStrLn . unwords $ map show (solve n)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nprettyPermutation lst = take (length lst) $ drop (len - 1) $ cycle lst \n where\n len = length lst\nsolve n = unwords $ map show $ prettyPermutation [1..n]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- readInt <$> getLine\n replicateM_ n $ do\n x <- readInt <$> getLine\n putStrLn $ solve x\n"}], "src_uid": "f89bd4ec97ec7e02a7f67feaeb4d3958"} {"source_code": "{-\nCodeforces Round #332\n\nProblem 606 B. Testing Robots\n\n@author yamaton\n@date 2015-12-11\n-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Text.Printf (printf)\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n-- import qualified Data.Foldable as F\n-- import qualified Data.Traversable as T\n\ntype Position = (Int, Int)\n\nnewVisits :: S.Set Position -> [Position] -> [Int]\nnewVisits _ [] = []\nnewVisits set (pos:rest) = val: newVisits newSet rest\n where\n val = if pos `S.member` set then 0 else 1\n newSet = S.insert pos set\n\n\nsolve :: Int -> Int -> Position -> String -> [Int]\nsolve xLim yLim iniPos s = newVisitList ++ [rest]\n where\n dict :: M.Map Char (Int, Int)\n dict = M.fromList [('D', (1, 0)), ('U', (-1, 0)), ('R', (0, 1)), ('L', (0, -1))]\n\n traj :: [Position]\n traj = init $ scanl move iniPos s\n\n newVisitList :: [Int]\n newVisitList = newVisits S.empty traj\n\n rest = xLim * yLim - sum newVisitList\n move :: Position -> Char -> Position\n move (x,y) c = (nx', ny')\n where\n (dx, dy) = dict M.! c\n (nx, ny) = (x + dx, y + dy)\n nx' = if 1 <= nx && nx <= xLim then nx else x\n ny' = if 1 <= ny && ny <= yLim then ny else y\n\n\n\nmain :: IO ()\nmain = do\n -- n <- read <$> getLine\n [x, y, x0, y0] <- (map read . words) <$> getLine :: IO [Int]\n s <- getLine :: IO String\n let result = solve x y (x0, y0) s\n putStrLn $ unwords (map show result)\n\n -- IO.hPutStrLn IO.stderr $ printf \"xs = %s\" (show xs)\n -- IO.hPutStrLn IO.stderr $ printf \"result = %d\" result\n", "positive_code": [{"source_code": "import Data.List.Split (splitOn, chunksOf)\nimport Data.List\nimport qualified Data.Set as Set\n\nmove :: (Int, Int) -> [Char] -> [Int] -> Set.Set(Int, Int) -> Int -> Int -> [Int]\n\nmove (x, y) [] steps visited max_x max_y = (max_x*max_y - (Set.size visited)):steps\nmove (x, y) (d:xs) steps visited max_x max_y\n | d == 'U' && x - 1 > 0 = move (x-1,y) xs newsteps newvisited max_x max_y\n | d == 'D' && x + 1 <= max_x = move (x+1,y) xs newsteps newvisited max_x max_y\n | d == 'L' && y - 1 > 0 = move (x,y-1) xs newsteps newvisited max_x max_y\n | d == 'R' && y + 1 <= max_y = move (x,y+1) xs newsteps newvisited max_x max_y\n | otherwise = move (x, y) xs newsteps newvisited max_x max_y\n where newsteps = if Set.member (x, y) visited then 0:steps else 1:steps\n newvisited = Set.insert (x,y) visited\n\n--check visited?\nmain = do\n coords <- getLine\n commands <- getLine\n let asd = [read x :: Int | x <- splitOn \" \" coords]\n let size = fst (splitAt 2 asd)\n let position = snd (splitAt 2 asd)\n let visited = Set.empty\n let result = move (head position, last position) commands [] visited (head size) (last size)\n putStrLn (intercalate \" \" [show x | x <- (reverse result)])\n \n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [m, n, x, y] <- map read . words <$> getLine\n s <- getLine\n\n let\n move (x, y) 'U' = fix (x-1, y)\n move (x, y) 'D' = fix (x+1, y)\n move (x, y) 'R' = fix (x, y+1)\n move (x, y) 'L' = fix (x, y-1)\n\n fix (x, y) = (min m (max 1 x), min n (max 1 y))\n\n ps = scanl move (x, y) s\n\n b :: IOUArray (Int, Int) Bool <- newArray ((1, 1), (m, n)) False\n\n cs <- forM ps $ \\p -> do\n v <- readArray b p\n if not v\n then do\n writeArray b p True\n return 1\n else do\n return 0\n\n let cs' = init cs ++ [last cs + m*n - length (filter (== 1) cs)]\n\n -- print ps\n -- print cs\n\n putStrLn $ unwords $ map show cs'\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\nimport Data.IORef\n\nsolve :: Int -> Int -> Int -> Int -> String -> IO [Int]\nsolve x y x0 y0 s = do\n mat <- newArray ((1,1),(x,y)) False :: IO (IOUArray (Int,Int) Bool)\n now <- newIORef (x0,y0) :: IO (IORef (Int,Int))\n tests <- forM s $ \\c -> do\n ij <- readIORef now\n let next = move c ij\n writeIORef now next\n used <- readArray mat ij\n let ret = if used\n then 0\n else 1\n writeArray mat ij True\n return ret\n return $ tests ++ [x*y - length (filter (== 1) tests)]\n where\n move c (i,j)\n | c == 'L' = if j > 1 then (i,j-1) else (i,j)\n | c == 'R' = if j < y then (i,j+1) else (i,j)\n | c == 'U' = if i > 1 then (i-1,j) else (i,j)\n | c == 'D' = if i < x then (i+1,j) else (i,j)\n\nmain :: IO ()\nmain = do\n [x,y,x0,y0] <- map read . words <$> getLine\n s <- getLine\n putStrLn . unwords . map show =<< solve x y x0 y0 s\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Map (fromList, (!))\nimport Data.Set hiding (fromList, map)\n\nsolve :: Int -> Int -> Int -> Int -> String -> [Int]\nsolve x y x0 y0 cmds =\n getExplosions path empty 0\n where\n path = computePath x0 y0 cmds\n getExplosions [_] _ netExplosions = [x*y - netExplosions]\n getExplosions (pos:rst) traversed netExplosions\n | pos `member` traversed = 0:getExplosions rst traversed netExplosions\n | otherwise = 1:getExplosions rst (insert pos traversed) (netExplosions + 1)\n getExplosions _ _ _ = error \"Not supposed to be here\"\n computePath x' y' [] = [(x', y')]\n computePath x' y' (cmd:rst)\n | validMove = (x', y'):computePath x'' y'' rst\n | otherwise = (x', y'):computePath x' y' rst\n where\n deltas = fromList [('U', (-1, 0)), ('D', (1, 0)), ('R', (0, 1)), ('L', (0, -1))]\n (dx, dy) = deltas ! cmd\n x'' = dx + x'\n y'' = dy + y'\n validMove = (x'' >= 1 && x'' <= x && y'' >= 1 && y'' <= y)\n\nmain :: IO ()\nmain = do\n [x, y, x0, y0] <- map read . words <$> getLine\n cmds <- getLine\n putStrLn $ unwords . map show $ solve x y x0 y0 cmds\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [m, n, x, y] <- map read . words <$> getLine\n s <- getLine\n\n let\n move (x, y) 'U' = fix (x-1, y)\n move (x, y) 'D' = fix (x+1, y)\n move (x, y) 'R' = fix (x, y+1)\n move (x, y) 'L' = fix (x, y-1)\n\n fix (x, y) = (min m (max 1 x), min n (max 1 y))\n\n ps = scanl move (x, y) s\n gs = group ps\n cs = concat $ map (\\g -> [1] ++ replicate (length g - 1) 0 ) gs\n cs' = init cs ++ [last cs + m*n - length gs]\n\n putStrLn $ unwords $ map show cs'\n"}, {"source_code": "import Data.List.Split (splitOn, chunksOf)\nimport Data.List\nimport qualified Data.Set as Set\n\nmove :: (Int, Int) -> [Char] -> [Int] -> Set.Set(Int, Int) -> Int -> Int -> [Int]\n\nmove (x, y) [d] steps visited max_x max_y = steps ++ [max_x*max_y - (Set.size newvisited)]\n where newvisited = Set.insert (x,y) visited\nmove (x, y) (d:xs) steps visited max_x max_y\n | d == 'U' && x - 1 > 0 = move (x-1,y) xs (steps ++ [1]) newvisited max_x max_y\n | d == 'D' && x + 1 <= max_x = move (x+1,y) xs (steps ++ [1]) newvisited max_x max_y\n | d == 'L' && y - 1 > 0 = move (x,y-1) xs (steps ++ [1]) newvisited max_x max_y\n | d == 'R' && y + 1 <= max_y = move (x,y+1) xs (steps ++ [1]) newvisited max_x max_y\n | otherwise = move (x, y) xs (steps ++ [0]) newvisited max_x max_y\n where newvisited = Set.insert (x,y) visited\n\n--check visited?\nmain = do\n coords <- getLine\n commands <- getLine\n let asd = [read x :: Int | x <- splitOn \" \" coords]\n let size = fst (splitAt 2 asd)\n let position = snd (splitAt 2 asd)\n let visited = Set.singleton (head position, last position)\n let result = move (head position, last position) commands [1] visited (head size) (last size)\n putStrLn (intercalate \" \" [show x | x <- result])\n \n"}], "src_uid": "22bebd448f93c0ff07d2be91e873521c"} {"source_code": "\nrush :: (Int,[Integer]) -> Int\nrush (m,[]) = m\nrush (m,[_]) = m\nrush (m,[_,_]) = m\nrush (m,l) = rush (max t m, r)\n where \n go (n,[]) = (n,[])\n go (n,[_]) = (n+1,[])\n go (n,[_,_]) = (n+2,[])\n go (n,(a:x@(b:c:_)))\n | c == a + b = go (n+1,x)\n | otherwise = (n+2,x)\n (t, r) = go (0,l)\n\nmain = do\n n <- fmap read getLine\n x <- fmap (map read . words) getLine\n print $ rush (min n 2,x)\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\n\nsolve :: [Int] -> Int\nsolve [a] = 1\nsolve as = maximum $ solve' 2 as\n where\n solve' k (a:b:c:xs)\n | a + b == c = solve' (k+1) (b:c:xs)\n | otherwise = k : solve' 2 (b:c:xs)\n solve' k xs = [k]\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n m0 = map length $ filter ((== 0) . head) $ group xs\n m1 = map f $ tails xs\n where\n f a = (length $ takeWhile id $ zipWith3 (\\a b c -> a+b == c) a' (tail a') (tail $ tail a')) + 2\n where a' = take 51 a\n\n print $ if length xs == 1 then 1 else maximum $ m0 ++ m1\n"}], "negative_code": [], "src_uid": "f99a23bc65a1f5cdbf7909dba573ce51"} {"source_code": "import Data.List (partition); import Data.Function (fix)\nmain = interact $ unlines . map ( unwords . map show . (uncurry (++)) . partition even . map (read :: String -> Int ) . words ) . fix (\\f xs -> if null xs then [] else let (x:y:ys)=xs in y : f ys) . tail . lines", "positive_code": [{"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nprintS = do \r\n n<-readLn::IO Int \r\n a<-readInts \r\n let b = [x|x<-a, odd x]\r\n c = [x|x<-a, even x]\r\n putStrLn $ printArray (b ++ c)\r\n\r\nmain = do\r\n t<-readLn::IO Int \r\n replicateM_ t printS"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Map((!))\r\n\r\nsolve :: Integer -> [Integer] -> [Integer]\r\nsolve _ list = [x | x<-list, mod x 2==0] ++ [x | x<-list, mod x 2 == 1]\r\n\r\n\r\nshowResult (x:xs) = show x ++ \" \" ++ showResult xs\r\nshowResult [] = []\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tputStrLn $ showResult $ solve n a\r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n as <- getInts\n let (xs, ys) = partition odd as\n C.putStrLn $ C.pack $ unwords $ map show $ xs ++ ys\n"}], "negative_code": [], "src_uid": "fe2131c9228a2ec4365fdc3d0faa413a"} {"source_code": "import Control.Monad\n\nsolve [] = return ()\nsolve (ts:tss) = do\n if cond\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n solve tss\n where\n cond = or $ [loop ts' | i <- [0..l-3], let ts' = drop i ts]\n l = length ts\n loop [] = False\n loop [_] = False\n loop [_,_] = False\n loop (x:y:z:xs) \n | x == z = True\n | otherwise = loop (x:y:xs)\n\nmain = do\n t <- readLn :: IO Int\n tss <- replicateM t $ do\n getLine\n xs <- map read . words <$> getLine :: IO [Int]\n return xs\n solve tss\n \n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Bool\nmain = do\n t <- readLn\n replicateM t $ getLine >> getLine >>=\n putStrLn.bool\"NO\" \"YES\".solve.map read.words\nsolve :: [Int] -> Bool\nsolve (a: b: as)\n | a `elem` as = True\n | otherwise = solve (b: as)\nsolve _ = False"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n getLine\n as <- map read.words <$> getLine :: IO [Integer]\n putStrLn $ if f as then \"YES\" else \"NO\"\n test (i - 1)\n\nf (a:b:as) = any (== a) as || f (b:as)\nf _ = False\n"}, {"source_code": "import Control.Monad\n\n\ncheckPalinSubstring :: [Int] -> Bool \n\ncheckPalinSubstring [] = False\ncheckPalinSubstring (x:y:[]) = False\ncheckPalinSubstring all@(x:y:xs) = or [length (filter (==x) xs) > 0, checkPalinSubstring (y:xs)]\n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do \n\tt <- getLine \n\tlet cases = (read t :: Int)\n\tresults <- forM [1..cases] (\\t -> do\n\t\tn <- readInts\n\t\tints <- readInts\n\t\tif checkPalinSubstring ints then return \"YES\" else return \"NO\"\n\t\t)\n\n\tmapM putStrLn results"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n getLine\n xs <- map read . words <$> getLine\n if pal xs then \n putStrLn \"Yes\"\n else\n putStrLn \"No\"\n\npal :: [Int] -> Bool\npal (x:y:zs) = elem x zs || pal (y:zs)\npal _ = False\n"}, {"source_code": "main :: IO ()\n\nmain = interact (format' . solve . format)\n\nsolve :: [[Int]] -> [String]\nsolve = map solver\n\nformat' = unlines\n\nsolver :: [Int] -> String\nsolver [x,y] = \"NO\"\nsolver (x:all@(y:xs)) = case x `elem` xs of\n True -> \"YES\"\n False -> solver all\n \nformat :: String -> [[Int]]\nformat xs = map (map read . words . snd) . filter (odd . fst) . (zip [0..]) . tail . lines $ xs\n"}], "negative_code": [{"source_code": "import Control.Monad\n\ncheckPalinSubstring :: [Int] -> Bool \n\ncheckPalinSubstring [] = False\ncheckPalinSubstring (x:[]) = False\ncheckPalinSubstring (x:y:[]) = False \ncheckPalinSubstring (x:y:z:xs) = or [ reverse (x:y:[z]) == (x:y:[z]), checkPalinSubstring (y:z:xs)]\n\n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do \n\tt <- getLine \n\tlet cases = (read t :: Int)\n\tresults <- forM [1..cases] (\\t -> do\n\t\tn <- readInts\n\t\tints <- readInts\n\t\tif checkPalinSubstring ints then return \"YES\" else return \"NO\"\n\t\t)\n\n\tmapM putStrLn results"}, {"source_code": "import Control.Monad\n\ncheckPalinSubstring :: [Int] -> Bool \n\ncheckPalinSubstring [] = False\ncheckPalinSubstring (x:[]) = False\ncheckPalinSubstring (x:y:[]) = False \ncheckPalinSubstring (x:y:z:[]) = z == x\ncheckPalinSubstring (x:y:z:t:xs) = or [ x == z, checkPalinSubstring (y:z:t:xs), [t, z, y, x] == [x, y, z, t]]\n\n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do \n\tt <- getLine \n\tlet cases = (read t :: Int)\n\tresults <- forM [1..cases] (\\t -> do\n\t\tn <- readInts\n\t\tints <- readInts\n\t\tif checkPalinSubstring ints then return \"YES\" else return \"NO\"\n\t\t)\n\n\tmapM putStrLn results"}, {"source_code": "import Control.Monad\n\n\ncheckPalinSubstring :: [Int] -> Bool \n\ncheckPalinSubstring [] = False\ncheckPalinSubstring (x:y:[]) = False\ncheckPalinSubstring all@(x:y:xs) = or [length (filter (==x) xs) >= 0, checkPalinSubstring (y:xs)]\n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do \n\tt <- getLine \n\tlet cases = (read t :: Int)\n\tresults <- forM [1..cases] (\\t -> do\n\t\tn <- readInts\n\t\tints <- readInts\n\t\tif checkPalinSubstring ints then return \"YES\" else return \"NO\"\n\t\t)\n\n\tmapM putStrLn results"}, {"source_code": "main :: IO ()\n\nmain = interact (format' . solve . format)\n\nsolve :: [[Int]] -> [String]\nsolve = map solver\n\nformat' = unlines\n\nsolver :: [Int] -> String\nsolver (x:y:z:[])\n | x == z = \"YES\"\n | otherwise = \"NO\"\n\nsolver (x:y:z:t:[])\n | x == t && y == z = \"YES\"\n | x == z = \"YES\"\n | y == t = \"YES\"\n | otherwise = \"NO\"\n\nsolver (x:(a@(y:z:t:xs)))\n | x == z = \"YES\"\n | x == t && y == z = \"YES\"\n | otherwise = solver a\n \nformat :: String -> [[Int]]\nformat xs = map (map read . words . snd) . filter (odd . fst) . (zip [0..]) . tail . lines $ xs\n"}], "src_uid": "5139d222fbbfa70d50e990f5d6c92726"} {"source_code": "-- https://codeforces.com/contest/1617/problem/B\n\nsolve n = show a ++ \" \" ++ show b ++ \" 1\" where\n a | even n = div (n-1) 2\n | even $ div (n-1) 2 = div (n-1) 2 - 1\n | otherwise = div (n-1) 2 - 2\n b | even n = a + 1\n | even $ div (n-1) 2 = a + 2\n | otherwise = a + 4\n\nrun 0 = return 0\nrun n = do\n t <- getLine\n putStrLn $ solve $ read t\n run $ n-1\nmain = getLine >>= run . read\n", "positive_code": [{"source_code": "\nimport Control.Monad.Identity (forM_, forM)\n\nminus (x:xs) (y:ys) = case compare x y of\n LT -> x : minus xs (y:ys)\n EQ -> minus xs ys\n GT -> minus (x:xs) ys\nminus xs _ = xs\n\nprimesToQ m = eratos [2..m] \n where\n eratos [] = []\n eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])\n\nmatch :: (a -> Bool) -> [a] -> [a]\nmatch f [] = []\nmatch f (x:xs) = if f x then [x] else match f xs\n\nsolve :: Int -> [Int]\nsolve n = match (\\x -> gcd x (n - x - 1) == 1) (primesToQ n)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n forM_ [1 .. n] $ \\i -> do\n x <- readLn :: IO Int\n let a = head $ solve x\n let b = x - a - 1\n putStrLn $ show a ++ \" \" ++ show b ++ \" 1\""}, {"source_code": "main :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve = unlines . map (showTriple . f . read) . tail . lines\n\nshowTriple :: (Int, Int, Int) -> String\nshowTriple (a, b, c) = unwords [show a, show b, show c]\n\nf :: Int -> (Int, Int, Int)\nf n = let a = until check succ 2\n in (a, n - a - 1, 1)\n where\n check a = let b = n - a - 1\n in gcd a b == 1\n"}], "negative_code": [{"source_code": "-- https://codeforces.com/contest/1617/problem/B\n\nsolve n = show a ++ \" \" ++ show b ++ \" 1\" where\n a | even n = div (n-1) 2\n | even $ div (n-1) 2 = div (n-1) 2 - 1\n | otherwise = div (n-1) 2 - 2\n b | even n = a + 1\n | even $ div (n-1) 2 = a + 2\n | otherwise = a + 4\n\nrun 0 = return 0\nrun n = do\n print $ solve n\n run $ n-1\nmain = getLine >>= run . read\n"}], "src_uid": "d4f4d6341f52cceb862faa89e85a42a3"} {"source_code": "import Control.Monad\nimport Data.List\n\ncount = sum . map fromEnum\n\ngroupsOf :: Int -> [Int] -> [[Int]]\ngroupsOf n xs = zipWith const (map (take n) (tails xs)) (drop (n-1) xs)\n\nbad3 [x,y,z] = (x >= y && y >= z) || (x <= y && y <= z)\nbad4 [w,x,y,z] = or [ bad3 [x,y,z]\n , bad3 [w,y,z]\n , bad3 [w,x,z]\n , bad3 [w,x,y]\n ]\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n print $ sum [ n\n , n - 1\n , count $ map (not . bad3) $ groupsOf 3 a\n , count $ map (not . bad4) $ groupsOf 4 a\n ]\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n--import Data.Char as C\n--import Data.IntSet as S\n\nbadtriple :: [Int] -> Bool\nbadtriple [x,y,z] = (x >= y && y >= z) || (x <= y && y <= z)\nbadtriple _ = error \"invalid input lol\"\n\nchunks :: Int -> [Int] -> Int\nchunks _ [] = 0\nchunks _ [_] = 0\nchunks _ [_, _] = 0\nchunks 4 [_, _, _] = 0\nchunks n xs = (if any badtriple $ alltriples n x then 0 else 1) + chunks n (tail xs)\n where x = take n xs\n alltriples n xs = (if n == 3 then [take 3 xs] else\n let [a,b,c,d] = xs in [[a,b,c], [a,b,d], [a,c,d], [b,c,d]])\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n s_ <- getLine\n let a = map read $ words s_ :: [Int]\n ch3 = chunks 3 a\n ch4 = chunks 4 a\n total = n + (n-1) + ch3 + ch4\n in print total\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nd (x1,y1) (x2,y2) = abs (x1-x2) + abs (y1-y2)\r\n\r\nisGood x y z = a + b /= c\r\n where [a,b,c] = sort [d x y, d y z, d x z]\r\n\r\nsolve3 [_] = 0\r\nsolve3 [_,_] = 0\r\nsolve3 (x:y:z:xs) = solve3 (y:z:xs) + if isGood x y z then 1 else 0\r\n\r\nsolve4 [_] = 0\r\nsolve4 [_,_] = 0\r\nsolve4 [_,_,_] = 0\r\nsolve4 (x:y:z:t:xs) = solve4 (y:z:t:xs) + if isGood x y z && isGood y z t && isGood x y t && isGood x z t then 1 else 0\r\n \r\nprintResult = do\r\n n <- readLn :: IO Integer\r\n xs <- readInts\r\n let z = zip xs [1..]\r\n print $ 2*n-1 + solve3 z + solve4 z\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.List ( zipWith4 )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n a <- readMany :: IO [Int]\r\n let ans3 = sum $ map fromEnum $ zipWith3 ok3 a (tail a) (drop 2 a)\r\n ans4 = sum $ map fromEnum $ zipWith4 ok4 a (tail a) (drop 2 a) (drop 3 a)\r\n ok3 a b c = a > b && b < c || a < b && b > c\r\n ok4 a b c d = ok3 a b c && ok3 a b d && ok3 a c d && ok3 b c d\r\n print $ n + n - 1 + ans3 + ans4\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (group)\r\nimport Data.Maybe (fromJust, fromMaybe)\r\n\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf testCase) >>> C.unlines\r\n\r\ntestCase :: Scanner C.ByteString\r\ntestCase = do\r\n n <- int\r\n xs <- n >< int\r\n return . C.pack . show $ solve n xs\r\n\r\nsolve n xs = 2 * n - 1 + compute xs\r\n where\r\n compute [] = 0\r\n compute [_] = 0\r\n compute [_, _] = 0\r\n compute (x : y : z : xs) = good3 x y z + (case xs of [] -> 0; (w:_) -> good4 x y z w) + compute (y : z : xs)\r\n\r\n good p q r = q < min p r || q > max p r\r\n good3 p q r | good p q r = 1 | otherwise = 0\r\n good4 p q r s | good p q r && good p r s && good p q s && good q r s = 1\r\n | otherwise = 0\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ncount = sum . map fromEnum\n\ngroupsOf :: Int -> [Int] -> [[Int]]\ngroupsOf n xs = zipWith const (map (take n) (tails xs)) (drop (n-1) xs)\n\nbad3 [x,y,z] = (x >= y && y >= z) || (x <= y && y <= z)\nbad4 [w,x,y,z] = or [ bad3 [x,y,z]\n , bad3 [w,y,z]\n , bad3 [w,x,z]\n , bad3 [w,x,y]\n ]\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n print $ sum [ n\n , n - 1\n , count $ map bad3 $ groupsOf 3 a\n , count $ map bad4 $ groupsOf 4 a\n ]\n"}], "src_uid": "e87ff02ce425fc3e96c09a15679aa656"} {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1 >>> map (read >>> solve >>> format) >>> concat >>> unlines\n\nsolve :: Int -> [Int]\nsolve n = go 1 n\n where\n go _ 0 = []\n go t n\n | m /= 0 = m : go (10*t) (n - m)\n | otherwise = go (10*t) n\n where\n m = n `mod` t\n\nformat :: [Int] -> [String]\nformat ns = [show (length ns), unwords (map show ns)]\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess (a,b) = do\n\t\t\tputStr [a]\n\t\t\tputStr $ replicate b '0'\n\t\t\tputStr \" \"\n\nonecase= do\n\t\tk<-reverse <$> getLine \n\t \tlet s = filter (\\z-> fst z/='0') $ zip k [0..]\t\n\t\tprint $ length s\n\t\tmapM_ process s\n\t\tputStrLn \"\"\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n\n"}, {"source_code": "process :: [Char] -> [[Char]]\nprocess = map (\\(n,x) -> (x:replicate n '0')) . filter (\\(_,x) -> x /= '0') . zip [0..] . reverse\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- getLine\n let xs = process n\n print . length $ xs\n putStrLn . unwords $ xs\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n getLine\n input <- map (filter (/=0) . solve 0 . read) <$> lines <$> getContents :: IO [[Int]]\n mapM_ f input\n\nsolve :: Int -> Int -> [Int]\nsolve _ 0 = []\nsolve i x = (x `mod` 10) * (10 ^ i) : solve (i + 1) (x `div` 10)\n\nf :: [Int] -> IO ()\nf xs = do\n print . length $ xs\n putStrLn . unwords . (map show) $ xs\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n \nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n let x = n `mod` 10\n nx = n - x\n y = nx `mod` 100\n ny = nx - y\n z = ny `mod` 1000\n nz = ny - z\n t = nz `mod` 10000\n nt = nz - t\n w = nt `mod` 100000\n ans = filter (>0) [x, y, z, t, w]\n print $ length $ ans\n printList $ ans"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain = readLn >>= flip replicateM_ ioSolve\n\nioSolve :: IO ()\nioSolve = getLine >>= (\\x -> print (length x) >> (putStrLn . unwords . map show) x) .\n filter (/=0) .\n zipWith (*) (iterate (*10) 1) .\n map (read . (:[])) . reverse"}, {"source_code": "\nsolve :: Int -> Int -> [Int]\nsolve _ 0 = []\nsolve multiplier n\n | n`mod`10==0 = solve (10*multiplier) (n`div`10)\n | otherwise = multiplier * (n`mod`10) : solve (10*multiplier) (n`div`10)\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readNums\n let ans = solve 1 n\n print $ length ans\n putStrLn $ unwords $ map show ans\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n \nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n let x = n `mod` 10\n nx = n - x\n y = nx `mod` 100\n ny = nx - y\n z = ny `mod` 1000\n nz = ny - z\n t = nz `mod` 10000\n ans = filter (>0) [x, y, z, t]\n print $ length $ ans\n printList $ ans"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain = readLn >>= flip replicateM_ ioSolve\n\nioSolve :: IO ()\nioSolve = getLine >>= (\\x -> print (length x) >> (putStrLn . unwords . map show) x) .\n filter (/=0) .\n zipWith (*) (iterate (*10) 1) .\n map (read . (:[]))"}], "src_uid": "cd2519f4a7888b2c292f05c64a9db13a"} {"source_code": "infixl 3 +.\ninfixl 9 *.\n\n\n(*.) :: Int -> (Int, Int) -> (Int, Int)\n(*.) k (z, t) = (k * z, k * t)\n\n(+.) :: (Int, Int) -> (Int, Int) -> (Int, Int)\n(+.) (x, y) (z, t) = (x + z, y + t)\n\nsolve (n, as, bs) = \n m *. (small l as bs) +. (small r as bs)\n where an = length as\n bn = length bs\n l = lcm an bn\n m = n `div` l\n r = n `mod` l\n\nsmall n as bs =\n let (sa, sb) = unzip . take n $ [score a b | (a, b) <- zip (cycle as) (cycle bs)]\n in (sum sb, sum sa)\n\nscore a b = (s a b, s b a)\n\ns 'R' 'S' = 1\ns 'S' 'P' = 1\ns 'P' 'R' = 1\ns _ _ = 0\n\nparse foo =\n let [n,as,bs] = words foo\n in (read n, as, bs)\n \npprint (x,y) = show x ++ \" \" ++ show y\n\nmain = interact (pprint . solve . parse)", "positive_code": [{"source_code": "import Data.List\n\ninv f (x,y) = f (y,x)\n\nwinner ('R','S') = 1\nwinner ('S','P') = 1\nwinner ('P','R') = 1\nwinner _ = 0\n\nsolve :: Int -> String -> String -> (Int, Int)\nsolve n a b = (count $ map (winner) cycled, count $ map (inv winner) cycled)\n where cycled = take l $ zip (cycle b) (cycle a)\n l = length a * length b\n count xs = d*(sum xs) + (sum $ take r xs)\n where (d,r) = divMod n l\n\nprint_tuple (x,y) = show x ++ \" \" ++ show y\n\nmain = do n <- getLine\n a <- getLine\n b <- getLine\n putStrLn $ print_tuple $ solve (read n :: Int) a b\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\nimport System.IO.Error\n\n\nhReadMany :: (Char -> Bool) -> Handle -> IO String\nhReadMany p h = do b <- (p <$> hLookAhead h) `catch` const (return False)\n if b\n then (:) <$> hGetChar h <*> hReadMany p h\n else return \"\"\n\nhSkipSpaces = hReadMany isSpace\nhReadNumeric = hReadMany (\\c -> isDigit c || c `elem` ['.', '-', '+'])\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = do hSkipSpaces stdin\n read <$> hReadNumeric stdin\n\nreadTerm :: IO String\nreadTerm = do hSkipSpaces stdin\n hReadMany (not . isSpace) stdin\n\n\nhoge 'R' = 0\nhoge 'P' = 1\nhoge 'S' = 2\n\nwins x y | a == b = False\n | (a - b) `mod` 3 == 1 = True\n | otherwise = False\n where\n (a, b) = (hoge x, hoge y)\n\nplay m ns ps = play' m 0 0 ns ps\n where\n play' 0 a b _ _ = (a, b)\n play' x a b (n:ns) (p:ps) | wins n p = play' (x - 1) a (b+1) ns ps\n | wins p n = play' (x - 1) (a + 1) b ns ps\n | otherwise = play' (x - 1) a b ns ps\n \n\nmain = do x <- readNum\n nike <- readTerm\n poly <- readTerm\n\n let l = lcm (length nike) (length poly)\n let mult = x `div` l\n let rest = x `mod` l\n\n let cnike = cycle nike\n let cpoly = cycle poly\n\n let (n, p) = play l cnike cpoly\n let (a, b) = play rest cnike cpoly\n\n let (n', p') = (mult * n + a, mult * p + b)\n\n putStrLn $ show n' ++ \" \" ++ show p'"}, {"source_code": "import Data.List\n\nwin_a ('R','S') = 1\nwin_a ('S','P') = 1\nwin_a ('P','R') = 1\nwin_a _ = 0\n\nwin_b ('S','R') = 1\nwin_b ('P','S') = 1\nwin_b ('R','P') = 1\nwin_b _ = 0\n\n\nsolve :: Int -> String -> String -> (Int, Int)\nsolve n a b = (count $ map (win_a) cycled, count $ map (win_b) cycled)\n where cycled = take l $ zip (cycle b) (cycle a)\n l = length a * length b\n count xs = d*(sum xs) + (sum $ take r xs)\n where (d,r) = divMod n l\n\nprint_tuple (x,y) = show x ++ \" \" ++ show y\n\nmain = do n <- getLine\n a <- getLine\n b <- getLine\n putStrLn $ print_tuple $ solve (read n :: Int) a b\n "}, {"source_code": "\nimport Data.List\n\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestOneMove = TestList \"TestOneMove\"\n [\n Test \"1\" $ assertEq (0, 0) (solve 1 \"R\" \"R\"),\n Test \"2\" $ assertEq (1, 0) (solve 1 \"R\" \"P\"),\n Test \"3\" $ assertEq (0, 1) (solve 1 \"R\" \"S\"),\n Test \"4\" $ assertEq (1, 0) (solve 1 \"S\" \"R\"),\n Test \"5\" $ assertEq (0, 0) (solve 1 \"S\" \"S\"),\n Test \"6\" $ assertEq (0, 1) (solve 1 \"S\" \"P\"),\n Test \"7\" $ assertEq (0, 1) (solve 1 \"P\" \"R\"),\n Test \"8\" $ assertEq (1, 0) (solve 1 \"P\" \"S\"),\n Test \"9\" $ assertEq (0, 0) (solve 1 \"P\" \"P\")\n ]\n\ntestShortString = TestList \"TestShortString\"\n [\n Test \"1\" $ assertEq (2, 0) (solve 2 \"R\" \"P\"),\n Test \"2\" $ assertEq (0, 2) (solve 2 \"P\" \"R\"),\n Test \"3\" $ assertEq (4, 0) (solve 4 \"RRR\" \"PPP\")\n ]\n\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq (3,2) (solve 7 \"RPS\" \"RSPP\"),\n Test \"2\" $ assertEq (0,0) (solve 5 \"RRRRRRRR\" \"R\")\n ]\n\ntestBig = Test \"TestBig\" $\n assertEq (0,0) (solve n \"R\" \"R\")\n where\n n = 2 * 10^9\n\ntestBigBig = Test \"TestBigBig\" $\n assertEq (n,0) (solve n (replicate n1 'R') (replicate n2 'P'))\n where\n n = 2 * 10^9\n n1 = 1001\n n2 = 999\n\ntest = mapM_ run\n [\n testOneMove,\n testShortString,\n testInput,\n testBig,\n testBigBig\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: Int -> String -> String -> (Int, Int)\nsolve n s1 s2 = (m2 + m1 * div n m, n2 + n1 * div n m)\n where\n m = lcm (length s1) (length s2)\n (m1, n1) = solve' m (cycle s1) (cycle s2) (0,0)\n (m2, n2) = solve' (mod n m) (cycle s1) (cycle s2) (0,0)\n solve' 0 _ _ acc = acc\n solve' n (c1:s1) (c2:s2) (k, l)\n | f c1 c2 = solve' n' s1 s2 (succ k, l)\n | f c2 c1 = solve' n' s1 s2 (k, succ l)\n | otherwise = solve' n' s1 s2 (k, l)\n where\n n' = pred n\n f 'R' 'P' = True\n f 'S' 'R' = True\n f 'P' 'S' = True\n f _ _ = False\n\nprintAns :: (Int, Int) -> IO ()\nprintAns (a, b) = putStrLn $ concat [show a, \" \", show b]\n\nmain :: IO ()\nmain = do\n n <- readLn\n s1 <- getLine\n s2 <- getLine\n printAns $ solve n s1 s2\n"}], "negative_code": [{"source_code": "solve (n, as, bs) =\n let (sa, sb) = unzip . take n $ [score a b | (a, b) <- zip (cycle \"RPS\") (cycle \"RSPP\")]\n in (sum sa, sum sb)\n\nscore a b = (s a b, s b a)\n\ns 'R' 'S' = 1\ns 'S' 'P' = 1\ns 'P' 'R' = 1\ns _ _ = 0\n\nparse foo =\n let [n,as,bs] = words foo\n in (read n, as, bs)\n \npprint (x,y) = show x ++ \" \" ++ show y\n\nmain = interact (pprint . solve . parse)"}, {"source_code": "solve (n, as, bs) =\n let (sa, sb) = unzip . take n $ [score a b | (a, b) <- zip (cycle \"RPS\") (cycle \"RSPP\")]\n in (sum sb, sum sa)\n\nscore a b = (s a b, s b a)\n\ns 'R' 'S' = 1\ns 'S' 'P' = 1\ns 'P' 'R' = 1\ns _ _ = 0\n\nparse foo =\n let [n,as,bs] = words foo\n in (read n, as, bs)\n \npprint (x,y) = show x ++ \" \" ++ show y\n\nmain = interact (pprint . solve . parse)"}, {"source_code": "solve (n, as, bs) =\n let (sa, sb) = unzip . take n $ [score a b | a <- cycle as, b <- cycle bs]\n in (sum sb, sum sa)\n\nscore a b = (s a b, s b a)\n\ns 'R' 'S' = 1\ns 'S' 'P' = 1\ns 'P' 'R' = 1\ns _ _ = 0\n\nparse foo =\n let [n,as,bs] = words foo\n in (read n, as, bs)\n \npprint (x,y) = show x ++ \" \" ++ show y\n\nmain = interact (pprint . solve . parse)"}], "src_uid": "9a365e26f58ecb22a1e382fad3062387"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n let l = (n-1) - k + 1\n as = [1..l-1]++ go l n\n putStrLn $ unwords $ map show as\n\ngo a b | b - a == 0 = [a]\n | b - a == 1 = [a,b]\n | otherwise = a:b:go (a+1) (b-1)\n\n", "positive_code": [{"source_code": "f[]=\"\"\nf(x:y)=show x++\" \"++f y\nsolve[n,k]=take n((take k(foldr(\\(y,z)x->y:z:x)[][(a,n+1-a)|a<-[1..k]]))++(if mod k 2==1 then[d+2..]else[n-d,n-d-1..]))where d=k`div`2\nmain=interact$f.solve.map read.words\n"}, {"source_code": "import Data.List (sort)\nsolve [n,k] = p ++ q' \n where y = take n $ concat $ zipWith (\\x y -> [x,y]) [1 .. g] [n,n-1 .. g]\n (p,q) = splitAt k y\n q' = if last p < g then sort q else reverse (sort q) \n g = div (n+1) 2\nmain = putStrLn.unwords.map show.solve.map read.words =<< getLine"}, {"source_code": "import Data.List (permutations, nub, intercalate)\n\n\n\nfindPermutation :: [Int] -> [Int]\nfindPermutation [n, k] = 1 : (helper k 1 1)\n where helper h l c\n | h == 0 = [k+2..n]\n | odd c = (l + h) : helper (h - 1) (l + h) (c + 1)\n | even c = (l - h) : helper (h - 1) (l - h) (c + 1)\n\n\nmain = getLine >>= putStrLn . intercalate \" \" . fmap show . findPermutation . fmap read . words\n"}, {"source_code": "solve [n,k] = scanl (+) 1 $ replicate (n-1-k) 1 ++ zipWith (*) [k,k-1..1] (cycle [1,-1])\nmain = interact $ unwords . map show . solve . map read . words"}, {"source_code": "main=interact$unwords.map show.f.map read.words\nf [n,k]=[1..n-k]++(take k.g$zip [n,n-1..] [n-k+1..])\ng []=[]\ng ((a,b):c)=a:b:g c"}, {"source_code": "main = interact $ unwords . map show . f . map read . words\nf [n, k] = (g . take (div k 2) $ zip [1..n] [n,n-1..1]) ++ h n k\ng [] = []\ng ((a, b):c) = a:b:g c\nh n k = if odd k then [x+1..n-x] else [n-x,n-x-1..x+1] where x = div k 2"}, {"source_code": "main = interact $ unwords . map show . f . map read . words\nf [n,k] = [1..n-k] ++ (take k $ g [n,n-1..] [n-k+1..])\ng (a:b) (c:d) = a:c:g b d"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Integer] -> [Integer]\nsolve [ n, k ] = [ 1 .. n - k ] ++ merge [ n, n - 1 .. n - k `div` 2 + 1 ] [ n - k + 1 .. n - k `div` 2 ]\nsolve _ = undefined\n\nmerge :: [a] -> [a] -> [a]\nmerge (x:xs) (y:ys) = x : y : merge xs ys\nmerge xs [] = xs\nmerge _ ys = ys\n"}], "negative_code": [{"source_code": "import Data.List (permutations, nub, intercalate)\n\n\n\nfindPermutation :: [Int] -> [Int]\nfindPermutation [n, k] = permutation [1..n] 1\n where permutation (x:y:zs) h\n | h == k = (x:y:zs)\n | abs (x-y) <= h = permutation ((x:zs) ++ [y]) h\n | otherwise = x : (permutation (y:zs) (h + 1))\n\n\nmain = getLine >>= putStrLn . intercalate \" \" . fmap show . findPermutation . fmap read . words\n"}, {"source_code": "main = interact $ unwords . map show . f . map read . words\nf [n, k] = [1..n-k] ++ g n k\ng _ 0 = []\ng a k = a:g (abs $ a-k+1) (k-1)"}], "src_uid": "18b3d8f57ecc2b392c7b1708f75a477e"} {"source_code": "\nimport Control.Monad (liftM)\nimport List (partition, sortBy)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"#1\" $ assertEq (5.5, [[3], [1,2]]) $\n solve 2 [Stool 1 2, Pensil 2 3, Stool 3 3],\n Test \"#2\" $ assertEq (8.0, [[1], [2], [3,4]]) $\n solve 3 [Stool 1 4, Pensil 2 1, Pensil 3 2, Pensil 4 3]\n ]\n\ntestOneBasket :: Test\ntestOneBasket = TestList \"TestOneBasket\"\n [\n Test \"#1\" $ assertEq (5.0, [[1]]) $\n solve 1 [Stool 1 10],\n Test \"#2\" $ assertEq (10.0, [[1]]) $\n solve 1 [Pensil 1 10],\n Test \"#3\" $ assertEq (25.0, [[2,1]]) $\n solve 1 [Stool 1 10, Stool 2 20],\n Test \"#4\" $ assertEq (30.0, [[1,2]]) $\n solve 1 [Pensil 1 10, Pensil 2 20],\n Test \"#5\" $ assertEq (25.0, [[1,2]]) $\n solve 1 [Stool 1 10, Pensil 2 20],\n Test \"#6\" $ assertEq (25.0, [[2,1]]) $\n solve 1 [Pensil 1 10, Stool 2 20] \n ]\n\ntestMoreBaskets :: Test\ntestMoreBaskets = TestList \"TestMoreBaskets\"\n [\n Test \"#1\" $ assertEq (4.5, [[2], [1]]) $\n solve 2 [Stool 1 3, Stool 2 6],\n Test \"#2\" $ assertEq (7.5, [[1], [2]]) $\n solve 2 [Stool 1 3, Pensil 2 6],\n Test \"#3\" $ assertEq (9.0, [[1], [2]]) $\n solve 2 [Pensil 1 3, Pensil 2 6],\n Test \"#4\" $ assertEq (22.0, [[4], [3,2,1]]) $\n solve 2 [Stool 1 3, Stool 2 6, Stool 3 9, Stool 4 11],\n Test \"#5\" $ assertEq (22.5, [[3], [2,1,4]]) $\n solve 2 [Stool 1 3, Stool 2 6, Stool 3 8, Pensil 4 11],\n Test \"#6\" $ assertEq (17.5, [[2], [1,3,4]]) $\n solve 2 [Stool 1 3, Stool 2 6, Pensil 3 1, Pensil 4 11],\n Test \"#7\" $ assertEq (19.5, [[1], [2,3,4]]) $\n solve 2 [Stool 1 3, Pensil 2 6, Pensil 3 1, Pensil 4 11],\n Test \"#8\" $ assertEq (21.0, [[1], [2,3,4]]) $\n solve 2 [Pensil 1 3, Pensil 2 6, Pensil 3 1, Pensil 4 11]\n ]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testInput,\n testOneBasket,\n testMoreBaskets\n ]\n-}\n--------------------------------------------------------------------------------\n\ndata Goods = Stool Int Integer | Pensil Int Integer\n deriving Eq\n\ninstance Ord Goods\n where\n compare a b = compare (getCost a) (getCost b)\n\ngetCost :: Goods -> Integer\ngetCost (Stool _ c) = c\ngetCost (Pensil _ c) = c\n\ngetNumber :: Goods -> Int\ngetNumber (Stool n _) = n\ngetNumber (Pensil n _) = n\n\nisStool :: Goods -> Bool\nisStool (Stool _ _) = True\nisStool _ = False\n\nreadGoods :: Int -> String -> Goods\nreadGoods n line = case words line of\n [s, \"1\"] -> Stool n (read s)\n [s, \"2\"] -> Pensil n (read s)\n _ -> error \"readGoods: unknown line\"\n\nsolve :: Int -> [Goods] -> (Double, [[Int]])\nsolve k goods\n | n < k = (0.5 * sums stools + sums pensils,\n (getNumbers $ map (\\s -> [s]) stools)\n ++ (map (\\s -> [getNumber s]) $ take (k - n - 1) pensils) ++ (getNumbers [drop (k-n-1) pensils]))\n | otherwise = (0.5 * sums stools' + sums stools'' + sums pensils\n - 0.5 * mins (stools'' ++ pensils),\n (map (\\s -> [getNumber s]) stools')\n ++ (getNumbers [stools'' ++ pensils]))\n where\n (stools, pensils) = partition isStool goods\n n = length stools\n sortedStools = sortBy (flip compare) stools\n (stools', stools'') = splitAt (k-1) sortedStools\n sums = fromIntegral . sum . map getCost\n mins = fromIntegral . minimum . map getCost\n getNumbers :: [[Goods]] -> [[Int]]\n getNumbers = map (map getNumber)\n\nprintAns :: (Double, [[Int]]) -> IO ()\nprintAns (ans, xs) = fPrint ans >> mapM_ prints xs\n where\n fPrint ans = putStrLn $ concat [show d, \".\", show e]\n where\n (d, d') = properFraction ans\n (e, e') = properFraction (10 * d')\n prints xs = prints' (length xs : xs)\n prints' [x] = putStrLn $ show x\n prints' (x:xs) = putStr (concat [show x, \" \"]) >> prints' xs\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n goods <- mapM (\\i -> liftM (readGoods i) getLine) [1..n]\n printAns $ solve k goods\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Control.Monad\nimport Text.Printf\nimport Data.List\nimport Data.Int\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> (Int64, [[Int]])\n\nsolve ss ps k | length ss < k = let\n (ps1, ps2) = splitAt (k - length ss - 1) ps\n\n res = [ [i] | (s, i) <- ss ] ++\n [ [i] | (p, i) <- ps1 ] ++\n [ [ i | (p, i) <- ps2 ] ]\n\n cost = sum . map (fromIntegral . fst) $ ss\n\n in (cost, res)\n\nsolve ss0 ps k = let\n ss = reverse . sort $ ss0\n (ss1, ss2) = splitAt (k - 1) ss\n\n res = [ [i] | (s, i) <- ss1 ] ++\n [ [i | (s, i) <- ss2 ] ++ [ i | (p, i) <- ps ] ]\n\n cost1 = sum . map (fromIntegral . fst) $ ss1\n cost2 = minimum $ [fromIntegral s | (s, i) <- ss2 ] ++ [ fromIntegral p | (p, i) <- ps ]\n\n in (cost1 + cost2, res)\n\nreadInt = fst . fromJust . BS.readInt\n\nmain = do\n [n, k] <- liftM (map readInt . BS.words) BS.getLine\n list <- forM [1..n] $ \\i -> do\n [x, y] <- liftM (map readInt . BS.words) BS.getLine\n return (x, y, i)\n\n let slist = [ (x, i) | (x, y, i) <- list, y == 1]\n let plist = [ (x, i) | (x, y, i) <- list, y == 2]\n\n let (ans, res) = solve slist plist k\n let total = (sum . map (fromIntegral . fst) $ slist)\n + (sum . map (fromIntegral . fst) $ plist) :: Int64\n let ans' = fromIntegral total - fromIntegral ans / 2 :: Double\n\n putStrLn $ printf \"%.1f\" ans'\n forM_ res $ \\l -> do\n putStr . show $ length l\n forM_ l $ \\x -> putStr $ \" \" ++ show x\n putStrLn \"\"\n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport List (partition, sortBy)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"#1\" $ assertEq (5.5, [[3], [1,2]]) $\n solve 2 [Stool 1 2, Pensil 2 3, Stool 3 3],\n Test \"#2\" $ assertEq (8.0, [[1], [2], [3,4]]) $\n solve 3 [Stool 1 4, Pensil 2 1, Pensil 3 2, Pensil 4 3]\n ]\n\ntestOneBasket :: Test\ntestOneBasket = TestList \"TestOneBasket\"\n [\n Test \"#1\" $ assertEq (5.0, [[1]]) $\n solve 1 [Stool 1 10],\n Test \"#2\" $ assertEq (10.0, [[1]]) $\n solve 1 [Pensil 1 10],\n Test \"#3\" $ assertEq (25.0, [[2,1]]) $\n solve 1 [Stool 1 10, Stool 2 20],\n Test \"#4\" $ assertEq (30.0, [[1,2]]) $\n solve 1 [Pensil 1 10, Pensil 2 20],\n Test \"#5\" $ assertEq (25.0, [[1,2]]) $\n solve 1 [Stool 1 10, Pensil 2 20],\n Test \"#6\" $ assertEq (25.0, [[2,1]]) $\n solve 1 [Pensil 1 10, Stool 2 20] \n ]\n\ntestMoreBaskets :: Test\ntestMoreBaskets = TestList \"TestMoreBaskets\"\n [\n Test \"#1\" $ assertEq (4.5, [[2], [1]]) $\n solve 2 [Stool 1 3, Stool 2 6],\n Test \"#2\" $ assertEq (7.5, [[1], [2]]) $\n solve 2 [Stool 1 3, Pensil 2 6],\n Test \"#3\" $ assertEq (9.0, [[1], [2]]) $\n solve 2 [Pensil 1 3, Pensil 2 6],\n Test \"#4\" $ assertEq (22.0, [[4], [3,2,1]]) $\n solve 2 [Stool 1 3, Stool 2 6, Stool 3 9, Stool 4 11],\n Test \"#5\" $ assertEq (22.5, [[3], [2,1,4]]) $\n solve 2 [Stool 1 3, Stool 2 6, Stool 3 8, Pensil 4 11],\n Test \"#6\" $ assertEq (17.5, [[2], [1,3,4]]) $\n solve 2 [Stool 1 3, Stool 2 6, Pensil 3 1, Pensil 4 11],\n Test \"#7\" $ assertEq (19.5, [[1], [2,3,4]]) $\n solve 2 [Stool 1 3, Pensil 2 6, Pensil 3 1, Pensil 4 11],\n Test \"#8\" $ assertEq (21.0, [[1], [2,3,4]]) $\n solve 2 [Pensil 1 3, Pensil 2 6, Pensil 3 1, Pensil 4 11]\n ]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testInput,\n testOneBasket,\n testMoreBaskets\n ]\n-}\n--------------------------------------------------------------------------------\n\ndata Goods = Stool Int Integer | Pensil Int Integer\n deriving Eq\n\ninstance Ord Goods\n where\n compare a b = compare (getCost a) (getCost b)\n\ngetCost :: Goods -> Integer\ngetCost (Stool _ c) = c\ngetCost (Pensil _ c) = c\n\ngetNumber :: Goods -> Int\ngetNumber (Stool n _) = n\ngetNumber (Pensil n _) = n\n\nisStool :: Goods -> Bool\nisStool (Stool _ _) = True\nisStool _ = False\n\nreadGoods :: Int -> String -> Goods\nreadGoods n line = case words line of\n [s, \"1\"] -> Stool n (read s)\n [s, \"2\"] -> Pensil n (read s)\n _ -> error \"readGoods: unknown line\"\n\nsolve :: Int -> [Goods] -> (Double, [[Int]])\nsolve k goods\n | n < k = (0.5 * sums stools + sums pensils,\n (getNumbers $ map (\\s -> [s]) stools)\n ++ (map (\\s -> [getNumber s]) $ take (k - n - 1) pensils) ++ (getNumbers [drop (k-n-1) pensils]))\n | otherwise = (0.5 * sums stools' + sums stools'' + sums pensils\n - 0.5 * mins (stools'' ++ pensils),\n (map (\\s -> [getNumber s]) stools')\n ++ (getNumbers [stools'' ++ pensils]))\n where\n (stools, pensils) = partition isStool goods\n n = length stools\n sortedStools = sortBy (flip compare) stools\n (stools', stools'') = splitAt (k-1) sortedStools\n sums = fromIntegral . sum . map getCost\n mins = fromIntegral . minimum . map getCost\n getNumbers :: [[Goods]] -> [[Int]]\n getNumbers = map (map getNumber)\n\nprintAns :: (Double, [[Int]]) -> IO ()\nprintAns (ans, xs) = print ans >> mapM_ prints xs\n where\n prints xs = prints' (length xs : xs)\n prints' [x] = putStrLn $ show x\n prints' (x:xs) = putStr (concat [show x, \" \"]) >> prints' xs\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n goods <- mapM (\\i -> liftM (readGoods i) getLine) [1..n]\n printAns $ solve k goods\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Control.Monad\nimport Text.Printf\nimport Data.List\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> (Int, [[Int]])\n\nsolve ss ps k | length ss < k = let\n (ps1, ps2) = splitAt (k - length ss - 1) ps\n\n res = [ [i] | (s, i) <- ss ] ++\n [ [i] | (p, i) <- ps1 ] ++\n [ [ i | (p, i) <- ps2 ] ]\n\n cost = sum . map fst $ ss\n\n in (cost, res)\n\nsolve ss0 ps k = let\n ss = reverse . sort $ ss0\n (ss1, ss2) = splitAt (k - 1) ss\n\n res = [ [i] | (s, i) <- ss1 ] ++\n [ [i | (s, i) <- ss2 ] ++ [ i | (p, i) <- ps ] ]\n\n cost1 = sum . map fst $ ss1\n cost2 = minimum $ [s | (s, i) <- ss2 ] ++ [ p | (p, i) <- ps ]\n\n in (cost1 + cost2, res)\n\nreadInt = fst . fromJust . BS.readInt\n\nmain = do\n [n, k] <- liftM (map readInt . BS.words) BS.getLine\n list <- forM [1..n] $ \\i -> do\n [x, y] <- liftM (map readInt . BS.words) BS.getLine\n return (x, y, i)\n\n let slist = [ (x, i) | (x, y, i) <- list, y == 1]\n let plist = [ (x, i) | (x, y, i) <- list, y == 2]\n\n let (ans, res) = solve slist plist k\n let ans' = fromIntegral (sum (map fst slist ++ map fst plist)) - fromIntegral ans / 2 :: Double\n\n putStrLn $ printf \"%.1f\" ans'\n forM_ res $ \\l -> do\n putStr . show $ length l\n forM_ l $ \\x -> putStr $ \" \" ++ show x\n putStrLn \"\"\n"}], "src_uid": "06c7834aa4d06d6fcebfa410054f1b8c"} {"source_code": "{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\n{- based on submission 2997762 by Dabek -}\n\nimport Control.Monad\nimport Data.Array (Array)\nimport Data.Array.MArray\nimport Data.Array.IO\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray ((!),bounds)\nimport qualified Data.Array.MArray as M\nimport Data.List\nimport Data.Ord\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Text.Printf\nimport Data.Time.Clock (getCurrentTime,diffUTCTime)\n\n{- -O2 provides small, but noticable benefit for qsort. -}\n-- Copyright 2010 Bart Massey\n-- Copyright 2012 Petr Pudlak\n\n-- -------------------------------\n\n{-# INLINE insertsort #-}\ninsertsort :: (MArray a e m, Ord e) => a Int e -> m ()\ninsertsort a = getBounds a >>= uncurry (insertsort' (return ()) a)\n\n{-# INLINE insertsort' #-}\ninsertsort' :: (MArray a e m, Ord e) => m () -> a Int e -> Int -> Int -> m ()\ninsertsort' cmpaction a mn mx = srt (mn + 1)\n where\n srt i = when (i <= mx) $ do\n v <- readArray a i\n j <- hole v i\n when (i /= j) (writeArray a j v)\n srt (i + 1)\n hole v = hole'\n where\n hole' i | i == mn = return i\n | otherwise = do\n let i' = i - 1\n u <- readArray a i'\n cmpaction\n if v < u\n then writeArray a i u >> hole' i'\n else return i\n\n-- -------------------------------\n\n-- Internally, heap indices are transformed\n-- to be zero-based.\n\ndata NodeType = Inner | Leaf | Edge\n\n{-# INLINE heapsort #-}\nheapsort :: (Integral i, Ix i, Ord e, MArray a e m) => a i e -> m ()\n-- | Sort the elements of the given 'MArray' in increasing order.\nheapsort a = getBounds a >>= uncurry (heapsort' a)\n\n{-# INLINE heapsort' #-}\nheapsort' :: (Integral i, Ix i, Ord e, MArray a e m) => a i e -> i -> i -> m ()\n-- | Sort the elements of the given 'MArray' in increasing order.\nheapsort' a mn mx = do\n heapify\n extract\n where\n getN = mx - mn + 1\n\n {-# INLINE right #-}\n right i = 2 * i + 2\n\n {-# INLINE nodeType #-}\n nodeType n i = case compare (right i) n of\n GT -> Leaf\n EQ -> Edge\n LT -> Inner\n\n {-# INLINE atIndex #-}\n atIndex i = readArray a (i + mn)\n\n {-# INLINE atIndexW #-}\n atIndexW i = writeArray a (i + mn)\n\n {-# INLINE downHeap #-}\n downHeap n j = do\n c <- atIndex j\n dh c j\n where\n -- Propagate @c@ down the heap. We only move elements up as we walk on\n -- the nodes, and when we're finished, we write @c@ to the last node.\n -- This way we save half of read/writes, compared to swapping elements.\n dh c = dhStep\n where\n dhStep i = case nodeType n i of\n Leaf -> stop\n Edge -> do\n l <- atIndex il\n if c < l\n then atIndexW i l >> atIndexW il c\n else stop\n Inner -> do\n l <- atIndex il\n r <- atIndex ir\n if c >= l && c >= r\n then stop\n else if l >= r\n then atIndexW i l >> dhStep il\n else atIndexW i r >> dhStep ir\n where\n {-# INLINE stop #-}\n stop = when (i /= j) (atIndexW i c)\n ir = right i\n il = ir - 1\n\n {-# INLINE heapify #-}\n heapify = heapifyRoots (n - 1) -- optimize: use 2^k such that k is maximal that 2^k < n\n where\n n = getN\n heapifyRoots i | i < 0 = return ()\n | otherwise = downHeap n i >> heapifyRoots (i - 1)\n\n\n {-# INLINE exch #-}\n exch ix1 ix2 | ix1 == ix2 = return ()\n | otherwise = do\n let i = ix1 + mn\n j = ix2 + mn\n v1 <- readArray a i\n v2 <- readArray a j\n writeArray a j v1\n writeArray a i v2\n\n {-# INLINE extract #-}\n extract = extractRoot (getN - 1)\n where\n extractRoot k | k <= 0 = return ()\n | otherwise = do\n exch k 0\n downHeap k 0\n extractRoot (k - 1)\n\n-- -------------------------------\n\ninsertsortLimit :: Int\ninsertsortLimit = 32\n\ndepthCoeficient :: Double\ndepthCoeficient = 2 / log 2\n\n{-# INLINE qsort #-}\nqsort :: (MArray a e m, Ord e) => a Int e -> m ()\nqsort = introsort' (return ()) ( -1 )\n\n{-# INLINE maxQSortDepth #-}\nmaxQSortDepth :: (MArray a e m) => a Int e -> m Int\nmaxQSortDepth arr = do\n (mn, mx) <- getBounds arr\n return $ ceiling (depthCoeficient * log (fromIntegral $ mx - mn + 1))\n\n{-# INLINE introsort #-}\nintrosort :: (MArray a e m, Ord e) => a Int e -> m ()\nintrosort arr = maxQSortDepth arr >>= \\d -> introsort' (return ()) d arr\n\n{-# INLINE introsort' #-}\nintrosort' :: (MArray a e m, Ord e) => m () -> Int -> a Int e -> m ()\nintrosort' cmpaction maxdepth a = getBounds a >>= uncurry (srt maxdepth)\n where\n srt depthleft mn mx\n | depthleft == 0 = heapsort' a mn mx\n | mn + insertsortLimit > mx = insertsort' cmpaction a mn mx\n | otherwise = do\n -- Select a pivot - median of 3:\n pL <- readArray a mn\n pR <- readArray a mx\n let d = (mn + mx) `div` 2\n pD <- readArray a d\n cmpaction\n let (_, pidx) = median3 (pR, mx) (pD, d) (pL, mn)\n\n p <- swap d mn\n i <- split p (mn + 1) mx\n swap i mn\n\n let depthleft' = depthleft - 1\n -- Sort the smaller part first. Hopefully, tail\n -- recursion will catch on the larger part and so we'll\n -- have guaranteed that even in the worst case, we'll\n -- have at most (log n) calls on the stack.\n if i < d then do\n srt depthleft' mn (i - 1)\n srt depthleft' (i + 1) mx\n else do\n srt depthleft' (i + 1) mx\n srt depthleft' mn (i - 1)\n where\n {-# INLINE swap #-}\n swap i j = do\n u <- readArray a i\n when (i /= j) $ do\n v <- readArray a j\n writeArray a i v\n writeArray a j u\n return u\n {-# INLINE split #-}\n split p = split'\n where \n split' i j = do\n i' <- moveRight i\n j' <- moveLeft j\n if i' < j'\n then swap i' j' >> split' (i' + 1) (j' - 1)\n else return j'\n where\n moveRight i | i > j = return i\n | otherwise = do\n v <- readArray a i\n cmpaction\n if v >= p\n then return i\n else moveRight (i + 1)\n moveLeft j | i > j = return j\n | otherwise = do\n v <- readArray a j\n cmpaction\n if v <= p\n then return j\n else moveLeft (j - 1)\n\n{-# INLINE median3 #-}\nmedian3 :: Ord a => a -> a -> a -> a\nmedian3 a b c\n | a > b = sel a b\n | otherwise = sel b a\n where\n sel l s | c > l = l\n | c < s = s\n | otherwise = c\n\n-- ---------------------------\nbigPrime = 10^(9::Int)+7 :: Int\n\nnewtype Modular = M { unModular :: Int }\n deriving (Show)\n\ninstance Num Modular where\n fromInteger x = M $ mod (fromInteger x) bigPrime\n (M x) + (M y) = M $ mod (x+y) bigPrime\n (M x) * (M y) = M $ mod (x*y) bigPrime\n (M x) - (M y) = M $ mod (x-y) bigPrime\n abs = undefined\n signum = undefined\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\n{-\n c[1] = 1\n c[ y ] = sum [ c[x] | (s,t) <- buses, t == y, (s',x) <- buses, x in [s,t-1] ]\n (1,2) (2,100) (100,200)\n-}\n\ngetList = fmap (map read . words) getLine\ngetIntList = getList :: IO [Int]\n\ninc arr i b = do v <- readArray arr i; writeArray arr i (v+b)\n\nshowArray label arr = do\n let (lo,hi) = bounds arr\n putStr $ label ++ \": \" \n forM_ [lo..hi] $ \\i -> do putStr $ printf \"%3d \" (arr!i)\n putStrLn \"\"\n\nshowTime start label = do\n now <- getCurrentTime\n let diff = diffUTCTime now start\n putStrLn $ label ++ \": \" ++ show diff\n\n-- return the first index i s.t. pred (arr!i) is True\nlowerBound arr a b pred = go a (b-a)\n where go a count =\n if count > 0\n then let mid = a + step\n step = div count 2\n in if pred (arr!mid) then go a step\n else go (mid+1) (count-step-1)\n else a\n\nsolve n 0 = return 0\nsolve n m = do\n -- start <- getCurrentTime\n let mark label = return () -- showTime start label\n m' = m+1\n arr <- newArray (0,m') (0,0) :: IO (IOArray Int (Int,Int))\n\n writeArray arr 0 (0,-1)\n forM_ [1..m] $ \\i -> do\n (a:b:_) <- fmap (parseInts 2) BS.getLine\n writeArray arr i (b,a)\n writeArray arr m' (n+1,n)\n mark \"read buses\"\n\n qsort arr\n arr <- M.freeze arr :: IO (Array Int (Int,Int))\n\n -- putStrLn $ show $ arr ! (m-1)\n mark \"sorted\"\n\n res <- newArray (0,m') 0 :: IO (IOUArray Int Int)\n prefix <- newArray (0,m'+1) 0 :: IO (IOUArray Int Int)\n mark \"newArray\"\n\n writeArray prefix 1 1\n writeArray res 1 1\n forM_ [1..m'] $ \\i -> do\n let (t,s) = arr!i\n left = lowerBound arr 0 i (\\(t',s') -> t' >= s)\n right = lowerBound arr 0 i (\\(t',s') -> t' >= t)\n pr <- readArray prefix right\n pl <- readArray prefix left\n writeArray res i (mod (pr-pl) bigPrime)\n pi <- readArray prefix i\n writeArray prefix (i+1) (mod (pi+pr-pl) bigPrime)\n\n readArray res m'\n\nmain = do\n (n:m:_) <- getIntList\n answer <- solve n m \n print answer\n\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array (Array)\nimport Data.Array.MArray\nimport Data.Array.IO\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray ((!),bounds)\nimport qualified Data.Array.MArray as M\nimport Data.List\nimport Data.Ord\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Text.Printf\nimport Data.Time.Clock (getCurrentTime,diffUTCTime)\n\n{- -O2 provides small, but noticable benefit for qsort. -}\n-- Copyright 2010 Bart Massey\n-- Copyright 2012 Petr Pudlak\n\n-- -------------------------------\n\n{-# INLINE insertsort #-}\ninsertsort :: (MArray a e m, Ord e) => a Int e -> m ()\ninsertsort a = getBounds a >>= uncurry (insertsort' (return ()) a)\n\n{-# INLINE insertsort' #-}\ninsertsort' :: (MArray a e m, Ord e) => m () -> a Int e -> Int -> Int -> m ()\ninsertsort' cmpaction a mn mx = srt (mn + 1)\n where\n srt i = when (i <= mx) $ do\n v <- readArray a i\n j <- hole v i\n when (i /= j) (writeArray a j v)\n srt (i + 1)\n hole v = hole'\n where\n hole' i | i == mn = return i\n | otherwise = do\n let i' = i - 1\n u <- readArray a i'\n cmpaction\n if v < u\n then writeArray a i u >> hole' i'\n else return i\n\n-- -------------------------------\n\n-- Internally, heap indices are transformed\n-- to be zero-based.\n\ndata NodeType = Inner | Leaf | Edge\n\n{-# INLINE heapsort #-}\nheapsort :: (Integral i, Ix i, Ord e, MArray a e m) => a i e -> m ()\n-- | Sort the elements of the given 'MArray' in increasing order.\nheapsort a = getBounds a >>= uncurry (heapsort' a)\n\n{-# INLINE heapsort' #-}\nheapsort' :: (Integral i, Ix i, Ord e, MArray a e m) => a i e -> i -> i -> m ()\n-- | Sort the elements of the given 'MArray' in increasing order.\nheapsort' a mn mx = do\n heapify\n extract\n where\n getN = mx - mn + 1\n\n {-# INLINE right #-}\n right i = 2 * i + 2\n\n {-# INLINE nodeType #-}\n nodeType n i = case compare (right i) n of\n GT -> Leaf\n EQ -> Edge\n LT -> Inner\n\n {-# INLINE atIndex #-}\n atIndex i = readArray a (i + mn)\n\n {-# INLINE atIndexW #-}\n atIndexW i = writeArray a (i + mn)\n\n {-# INLINE downHeap #-}\n downHeap n j = do\n c <- atIndex j\n dh c j\n where\n -- Propagate @c@ down the heap. We only move elements up as we walk on\n -- the nodes, and when we're finished, we write @c@ to the last node.\n -- This way we save half of read/writes, compared to swapping elements.\n dh c = dhStep\n where\n dhStep i = case nodeType n i of\n Leaf -> stop\n Edge -> do\n l <- atIndex il\n if c < l\n then atIndexW i l >> atIndexW il c\n else stop\n Inner -> do\n l <- atIndex il\n r <- atIndex ir\n if c >= l && c >= r\n then stop\n else if l >= r\n then atIndexW i l >> dhStep il\n else atIndexW i r >> dhStep ir\n where\n {-# INLINE stop #-}\n stop = when (i /= j) (atIndexW i c)\n ir = right i\n il = ir - 1\n\n {-# INLINE heapify #-}\n heapify = heapifyRoots (n - 1) -- optimize: use 2^k such that k is maximal that 2^k < n\n where\n n = getN\n heapifyRoots i | i < 0 = return ()\n | otherwise = downHeap n i >> heapifyRoots (i - 1)\n\n\n {-# INLINE exch #-}\n exch ix1 ix2 | ix1 == ix2 = return ()\n | otherwise = do\n let i = ix1 + mn\n j = ix2 + mn\n v1 <- readArray a i\n v2 <- readArray a j\n writeArray a j v1\n writeArray a i v2\n\n {-# INLINE extract #-}\n extract = extractRoot (getN - 1)\n where\n extractRoot k | k <= 0 = return ()\n | otherwise = do\n exch k 0\n downHeap k 0\n extractRoot (k - 1)\n\n-- -------------------------------\n\ninsertsortLimit :: Int\ninsertsortLimit = 32\n\ndepthCoeficient :: Double\ndepthCoeficient = 2 / log 2\n\n{-# INLINE qsort #-}\nqsort :: (MArray a e m, Ord e) => a Int e -> m ()\nqsort = introsort' (return ()) ( -1 )\n\n{-# INLINE maxQSortDepth #-}\nmaxQSortDepth :: (MArray a e m) => a Int e -> m Int\nmaxQSortDepth arr = do\n (mn, mx) <- getBounds arr\n return $ ceiling (depthCoeficient * log (fromIntegral $ mx - mn + 1))\n\n{-# INLINE introsort #-}\nintrosort :: (MArray a e m, Ord e) => a Int e -> m ()\nintrosort arr = maxQSortDepth arr >>= \\d -> introsort' (return ()) d arr\n\n{-# INLINE introsort' #-}\nintrosort' :: (MArray a e m, Ord e) => m () -> Int -> a Int e -> m ()\nintrosort' cmpaction maxdepth a = getBounds a >>= uncurry (srt maxdepth)\n where\n srt depthleft mn mx\n | depthleft == 0 = heapsort' a mn mx\n | mn + insertsortLimit > mx = insertsort' cmpaction a mn mx\n | otherwise = do\n -- Select a pivot - median of 3:\n pL <- readArray a mn\n pR <- readArray a mx\n let d = (mn + mx) `div` 2\n pD <- readArray a d\n cmpaction\n let (_, pidx) = median3 (pR, mx) (pD, d) (pL, mn)\n\n p <- swap d mn\n i <- split p (mn + 1) mx\n swap i mn\n\n let depthleft' = depthleft - 1\n -- Sort the smaller part first. Hopefully, tail\n -- recursion will catch on the larger part and so we'll\n -- have guaranteed that even in the worst case, we'll\n -- have at most (log n) calls on the stack.\n if i < d then do\n srt depthleft' mn (i - 1)\n srt depthleft' (i + 1) mx\n else do\n srt depthleft' (i + 1) mx\n srt depthleft' mn (i - 1)\n where\n {-# INLINE swap #-}\n swap i j = do\n u <- readArray a i\n when (i /= j) $ do\n v <- readArray a j\n writeArray a i v\n writeArray a j u\n return u\n {-# INLINE split #-}\n split p = split'\n where \n split' i j = do\n i' <- moveRight i\n j' <- moveLeft j\n if i' < j'\n then swap i' j' >> split' (i' + 1) (j' - 1)\n else return j'\n where\n moveRight i | i > j = return i\n | otherwise = do\n v <- readArray a i\n cmpaction\n if v >= p\n then return i\n else moveRight (i + 1)\n moveLeft j | i > j = return j\n | otherwise = do\n v <- readArray a j\n cmpaction\n if v <= p\n then return j\n else moveLeft (j - 1)\n\n{-# INLINE median3 #-}\nmedian3 :: Ord a => a -> a -> a -> a\nmedian3 a b c\n | a > b = sel a b\n | otherwise = sel b a\n where\n sel l s | c > l = l\n | c < s = s\n | otherwise = c\n\n-- ---------------------------\nbigPrime = 10^(9::Int)+7 :: Int\n\nnewtype Modular = M { unModular :: Int }\n deriving (Show)\n\ninstance Num Modular where\n fromInteger x = M $ mod (fromInteger x) bigPrime\n (M x) + (M y) = M $ mod (x+y) bigPrime\n (M x) * (M y) = M $ mod (x*y) bigPrime\n (M x) - (M y) = M $ mod (x-y) bigPrime\n abs = undefined\n signum = undefined\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\n{-\n c[1] = 1\n c[ y ] = sum [ c[x] | (s,t) <- buses, t == y, (s',x) <- buses, x in [s,t-1] ]\n (1,2) (2,100) (100,200)\n-}\n\ngetList = fmap (map read . words) getLine\ngetIntList = getList :: IO [Int]\n\ninc arr i b = do v <- readArray arr i; writeArray arr i (v+b)\n\nshowArray label arr = do\n let (lo,hi) = bounds arr\n putStr $ label ++ \": \" \n forM_ [lo..hi] $ \\i -> do putStr $ printf \"%3d \" (arr!i)\n putStrLn \"\"\n\nshowTime start label = do\n now <- getCurrentTime\n let diff = diffUTCTime now start\n putStrLn $ label ++ \": \" ++ show diff\n\nsolve n 0 = return 0\nsolve n m = do\n -- start <- getCurrentTime\n let mark label = return () -- showTime start label\n arr <- newArray (0,m-1) (0,0) :: IO (IOArray Int (Int,Int))\n forM_ [0..m-1] $ \\i -> do\n (a:b:_) <- fmap (parseInts 2) BS.getLine\n writeArray arr i (b,a)\n mark \"read buses\"\n\n qsort arr\n arr <- M.freeze arr :: IO (Array Int (Int,Int))\n\n -- putStrLn $ show $ arr ! (m-1)\n mark \"sorted\"\n\n barr <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n carr <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n mark \"newArray\"\n\n let getFst i = fst $ arr!i\n getSnd i = snd $ arr!i\n\n writeArray barr 1 (getFst 0)\n writeArray carr 0 1\n let eloop e i | i >= m = return e\n eloop e i = do\n if getFst i /= getFst (i-1)\n then do let e' = e+1\n writeArray barr e' (getFst i)\n writeArray carr i e'\n eloop e' (i+1)\n else do writeArray carr i e; eloop e (i+1)\n\n elast <- eloop 1 1\n mark \"eloop\"\n\n barr <- M.freeze barr :: IO (UArray Int Int)\n carr <- M.freeze carr :: IO (UArray Int Int)\n mark \"freezes\"\n\n if barr!elast /= n\n then do return 0\n else do farr <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n sarr <- newArray (0,m) 0 :: IO (IOUArray Int Int)\n writeArray farr 0 1\n writeArray sarr 0 1\n \n forM_ [0..m-1] $ \\i -> do\n let binsearch left right | left < right =\n let h = div (left+right) 2\n in if (barr!h) < getSnd i then binsearch (h+1) right\n else binsearch left h\n binsearch left right = right\n let r = binsearch 0 (carr!i)\n let k = carr!i\n when (r < k) $ do\n s1 <- readArray sarr (k-1)\n s2 <- if r > 0 then readArray sarr (r-1) else return 0\n v <- readArray farr k\n writeArray farr k (mod (v+s1-s2) bigPrime)\n when (k /= carr!(i+1)) $ do\n a <- readArray sarr (k-1)\n b <- readArray farr k\n writeArray sarr k (mod (a+b) bigPrime)\n answer <- readArray farr elast\n return answer\n\nmain = do\n (n:m:_) <- getIntList\n answer <- solve n m \n print answer\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\nimport qualified Data.IntMap.Strict as M\nimport Debug.Trace\n\n{-\n c[1] = 1\n c[ y ] = sum [ c[x] | (s,t) <- buses, t == y, (s',x) <- buses, x in [s,t-1] ]\n (1,2) (2,100) (100,200)\n-}\n\n-- find the first index i in [a,b) where pred (arr!i) is True\nlowerBound arr a b pred = go a (b-a)\n where go a count =\n if count > 0\n then let mid = a + step\n step = div count 2\n in if pred (arr!mid) then go a step\n else go (mid+1) (count-step-1)\n else a\n\ninc :: Int -> M.IntMap Int -> Int -> M.IntMap Int\ninc k m by = M.insert k v m\n where v = mod (by + M.findWithDefault 0 k m) bigPrime\n\ngetList = fmap (map read . words) getLine\ngetIntList = getList :: IO [Int]\n\nbigPrime = 10^9+7 :: Int\n\nsum' xs = foldl' (\\s x -> mod (s+x) bigPrime) 0 xs\n\nmain = do\n (n:m:_) <- getIntList\n buses <- fmap ([(0,0)] ++) $ replicateM m $ do (a:b:_) <- getIntList; return (a,b)\n let byEnd = sortBy (comparing snd) buses\n arr = listArray (1,m) byEnd :: Array Int (Int,Int)\n loop cnts (s,t) =\n let i = lowerBound arr 1 (m+1) (\\(s',t') -> s <= t')\n bs = filter (\\b -> snd b < t) [ arr!k | k <- [i..m] ]\n where hoo x = trace msg x\n where msg = \"--- buses for \" ++ show (s,t) ++ \" = \" ++ show x\n cs = [ M.findWithDefault 0 t' cnts | (_,t') <- bs ]\n cnts' = inc t cnts (sum' cs)\n in cnts'\n cnts = foldl' loop (M.insert 0 1 M.empty) byEnd\n answer = M.findWithDefault 0 n cnts\n print answer\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\nimport qualified Data.IntMap.Strict as M\nimport Debug.Trace\n\n{-\n c[1] = 1\n c[ y ] = sum [ c[x] | (s,t) <- buses, t == y, (s',x) <- buses, x in [s,t-1] ]\n (1,2) (2,100) (100,200)\n-}\n\n-- find the first index i in [a,b) where pred (arr!i) is True\nlowerBound arr a b pred = go a (b-a)\n where go a count =\n if count > 0\n then let mid = a + step\n step = div count 2\n in if pred (arr!mid) then go a step\n else go (mid+1) (count-step-1)\n else a\n\ninc :: Int -> M.IntMap Int -> Int -> M.IntMap Int\ninc k m by = M.insert k v m\n where v = mod (by + M.findWithDefault 0 k m) bigPrime\n\ngetList = fmap (map read . words) getLine\ngetIntList = getList :: IO [Int]\n\nbigPrime = 10^9+7 :: Int\n\nsum' xs = foldl' (\\s x -> mod (s+x) bigPrime) 0 xs\n\nmain = do\n (n:m:_) <- getIntList\n buses <- fmap ([(0,0)] ++) $ replicateM m $ do (a:b:_) <- getIntList; return (a,b)\n let byEnd = sortBy (comparing snd) buses\n arr = listArray (1,m) byEnd :: Array Int (Int,Int)\n loop cnts (s,t) =\n let cs = [ M.findWithDefault 0 t' cnts | (_,t') <- buses, s <= t' && t' < t ]\n cnts' = inc t cnts (sum' cs)\n in cnts'\n cnts = foldl' loop (M.insert 0 1 M.empty) byEnd\n answer = M.findWithDefault 0 n cnts\n print answer\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\nimport qualified Data.IntMap.Strict as M\nimport Debug.Trace\n\n{-\n c[1] = 1\n c[ y ] = sum [ c[x] | (s,t) <- buses, t == y, (s',x) <- buses, x in [s,t-1] ]\n (1,2) (2,100) (100,200)\n-}\n\n-- find the first index i in [a,b) where pred (arr!i) is True\nlowerBound arr a b pred = go a (b-a)\n where go a count =\n if count > 0\n then let mid = a + step\n step = div count 2\n in if pred (arr!mid) then go a step\n else go (mid+1) (count-step-1)\n else a\n\ninc :: Int -> M.IntMap Int -> Int -> M.IntMap Int\ninc k m by = M.insert k v m\n where v = by + M.findWithDefault 0 k m \n\ngetList = fmap (map read . words) getLine\ngetIntList = getList :: IO [Int]\n\nmain = do\n (n:m:_) <- getIntList\n buses <- fmap ([(0,0)] ++) $ replicateM m $ do (a:b:_) <- getIntList; return (a,b)\n let byEnd = sortBy (comparing snd) buses\n arr = listArray (1,m) byEnd :: Array Int (Int,Int)\n loop cnts (s,t) =\n let i = lowerBound arr 1 (m+1) (\\(s',t') -> s <= t')\n bs = filter (\\b -> snd b < t) [ arr!k | k <- [i..m] ]\n where hoo x = trace msg x\n where msg = \"--- buses for \" ++ show (s,t) ++ \" = \" ++ show x\n cs = [ M.findWithDefault 0 t' cnts | (_,t') <- bs ]\n cnts' = inc t cnts (sum cs)\n in cnts'\n cnts = foldl' loop (M.insert 0 1 M.empty) byEnd\n answer = M.findWithDefault 0 n cnts\n print answer\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\nimport qualified Data.IntMap.Strict as M\nimport Debug.Trace\n\n{-\n c[1] = 1\n c[ y ] = sum [ c[x] | (s,t) <- buses, t == y, (s',x) <- buses, x in [s,t-1] ]\n (1,2) (2,100) (100,200)\n-}\n\n-- find the first index i in [a,b) where pred (arr!i) is True\nlowerBound arr a b pred = go a (b-a)\n where go a count =\n if count > 0\n then let mid = a + step\n step = div count 2\n in if pred (arr!mid) then go a step\n else go (mid+1) (count-step-1)\n else a\n\ninc :: Int -> M.IntMap Int -> Int -> M.IntMap Int\ninc k m by = M.insert k v m\n where v = mod (by + M.findWithDefault 0 k m) bigPrime\n\ngetList = fmap (map read . words) getLine\ngetIntList = getList :: IO [Int]\n\nbigPrime = 10^9+7 :: Int\n\nmain = do\n (n:m:_) <- getIntList\n buses <- fmap ([(0,0)] ++) $ replicateM m $ do (a:b:_) <- getIntList; return (a,b)\n let byEnd = sortBy (comparing snd) buses\n arr = listArray (1,m) byEnd :: Array Int (Int,Int)\n loop cnts (s,t) =\n let i = lowerBound arr 1 (m+1) (\\(s',t') -> s <= t')\n bs = filter (\\b -> snd b < t) [ arr!k | k <- [i..m] ]\n where hoo x = trace msg x\n where msg = \"--- buses for \" ++ show (s,t) ++ \" = \" ++ show x\n cs = [ M.findWithDefault 0 t' cnts | (_,t') <- bs ]\n cnts' = inc t cnts (sum cs)\n in cnts'\n cnts = foldl' loop (M.insert 0 1 M.empty) byEnd\n answer = M.findWithDefault 0 n cnts\n print answer\n"}], "src_uid": "cb47d710361979de0f975cc34fc22c7a"} {"source_code": "import List\ns([n,_,k]:t)=sort$h++[(x,0)|x<-map(!!0)v,x`notElem`map fst h]where{(g,v)=splitAt(read n)t;h=g>>=j;j[s,e]|x>99=[(s,x)]|1>0=[]where x=(read e)*read(drop 2 k)`div`100}\np l=show(length l):[a++\" \"++show b|(a,b)<-l]\nmain=interact$unlines.p.s.map words.lines\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n\nimport Data.Ord\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.Map(Map)\nimport Data.List\n\nparseSkill [skill, exp] = (skill, read exp)\n\nparseRational :: String -> Rational\nparseRational = pr . span (/= '.')\n where\n pr (n, \"\") = fromIntegral (read n)\n pr (a, bb) = fromIntegral (read a) + fromIntegral (read b) / 10 ^ length b\n where\n b = tail bb\n\nmain = do\n [read -> (n :: Integer), read -> (m :: Integer), parseRational -> k] <- words <$> getLine\n have <- replicateM (fromInteger n) (parseSkill . words <$> getLine)\n want <- replicateM (fromInteger m) getLine\n let\n r :: (String, Integer) -> [(String, Integer)]\n r (s, e) \n | e' < 100 = []\n | otherwise = [(s, e')]\n where\n e' = floor (fromInteger e * k)\n have' = have >>= r\n have'' = have' ++ map (\\s -> (s, 0)) (filter (`notElem` map fst have') want)\n pr (s, e) = putStrLn (s ++ \" \" ++ show e)\n\n putStrLn (show $ length have'')\n mapM pr (sortBy (comparing fst) have'')"}, {"source_code": "-- Problem \"A\" Transmigration --\n\nimport Data.List\nimport Data.Ratio\n\n\ndata Skill = Skill String Int\n\ninstance Eq Skill where\n (Skill lhs _) == (Skill rhs _) = lhs == rhs\n\ninstance Ord Skill where\n (Skill lhs _) <= (Skill rhs _) = lhs <= rhs\n\ninstance Show Skill where\n show (Skill name level) = name ++ \" \" ++ (show level)\n\nfromPair :: (String, Int) -> Skill\nfromPair (name, level) = Skill name level\n\nreadRationalEps = 0.0001\nskillMinimumLevel = 100\n\nreadInt :: String -> Int\nreadInt token = read token :: Int\n\nreadDouble :: String -> Double\nreadDouble token = read token :: Double\n\nreadRational :: String -> Rational\nreadRational token = approxRational (readDouble token) readRationalEps\n\nstride :: Int -> [a] -> [a]\nstride _ [] = []\nstride n (x:xs) = x : stride n (drop (n - 1) xs)\n\nscaleSkills :: Rational -> [Skill] -> [Skill]\nscaleSkills k = filter validSkill . map scaleSkill\n where validSkill (Skill _ level) = level >= skillMinimumLevel\n scaleSkill (Skill name level) = Skill name\n (floor $ k * (toRational level))\n\nsolve :: (Rational, [Skill], [Skill]) -> [Skill]\nsolve (k, rold, rnew) = sort $ old ++ new\n where old = scaleSkills k rold\n new = filter (\\s -> notElem s old) rnew\n\nprepareInput :: [String] -> (Rational, [Skill], [Skill])\nprepareInput (sn:sm:sk:skills) = (k,\n map fromPair $\n zip oldSkillNames oldSkillLevels,\n map fromPair $\n zip newSkillNames newSkillLevels)\n where n = readInt sn\n m = readInt sm\n k = readRational sk\n oldSkillNames = stride 2 $ take (2 * n) skills\n oldSkillLevels = map readInt $ stride 2 $ tail $ take (2 * n) skills\n newSkillNames = drop (2 * n) skills\n newSkillLevels = repeat 0\n\nprepareOutput :: [Skill] -> String\nprepareOutput skills = unlines $ [show $ length skills] ++ (map show skills)\n\n\nmain :: IO ()\nmain = interact (prepareOutput . solve . prepareInput . words)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nmain = do\n inputNMK <- words `liftM` getLine\n let n = read $ inputNMK !! 0 :: Int\n m = read $ inputNMK !! 1 :: Int\n k = read $ inputNMK !! 2 :: Double\n\n skill <- foldM (\\skill _ -> do\n inputSkill <- words `liftM` getLine\n let name = head inputSkill\n level = read $ inputSkill !! 1 :: Int\n return $ Map.insert name level skill\n ) Map.empty [1..n]\n\n (skill', new_skill') <- foldM (\\(skill, new_skill) _ -> do\n name <- getLine\n return $ (Map.insertWith (\\new old ->\n let level = floor $ fromIntegral old * k + 0.00001 :: Int in\n if level < 100\n then 0\n else level\n ) name 0 skill, Set.insert name new_skill)\n ) (skill, Set.empty) [1..m]\n\n --putStrLn $ show skill\n --putStrLn $ show skill'\n --putStrLn $ show new_skill'\n\n let res = map (\\(k, v) -> k ++ \" \" ++ show v) $ Map.toList $ Map.filter ( >= 0 ) $ Map.mapWithKey (\\name level ->\n if Set.member name new_skill'\n then level\n else let level' = floor $ fromIntegral level * k + 0.00001 :: Int in\n if level' < 100\n then -1\n else level'\n ) skill'\n putStrLn $ show $ length res\n putStr $ unlines res\n"}, {"source_code": "\nimport List (sortBy)\nimport Monad (liftM)\nimport Prelude hiding (reads)\n\nreadPair :: String -> (String, Int)\nreadPair line = case words line of\n [a, b] -> (a, read b)\n\nreadTriple :: String -> (Int, Int, Int)\nreadTriple line = case words line of\n [a, b, c] -> (read a, read b, read $ drop 2 c)\n\nsolve :: Int -> [(String, Int)] -> [String] -> [(String, Int)]\nsolve k before after = sortBy (\\a b -> compare (fst a) (fst b)) answer\n where\n filtered = filter ((> 99) . snd) $ mapP id (flip div 100 . (*k)) before\n answer = foldl add filtered after\n add ss s\n | elem s (map fst ss) = ss\n | otherwise = (s, 0) : ss\n\nmapP :: (a -> c) -> (b -> d) -> [(a, b)] -> [(c, d)]\nmapP f1 f2 xs = map (\\(a, b) -> (f1 a, f2 b)) xs\n\nmain :: IO ()\nmain = do\n (n, m, k) <- liftM readTriple getLine\n lines' <- liftM lines getContents\n let before = (map readPair . take n) lines' \n let after = (take m . drop n) lines'\n let answer = solve k before after\n print $ length answer\n mapM_ putStrLn $ map (\\(s, x) -> s ++ \" \" ++ show x) answer \n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nnotinc [] _ = True\nnotinc ((a,_):l) (x,y) = if x==a then False else notinc l (x,y)\n\nsolve :: Int -> Int -> Double -> [(String,Int)] -> [String] -> [(String,Int)]\nsolve n m k old new = sort (old' ++ new')\n where\n old' = filter (\\(n,e) -> e>=100) (map (\\(n,e) -> (n,floor ((fromIntegral e)*k+0.000001))) old)\n new' = filter (notinc old') [(i,0)|i<-new]\n\nsub n m k old new = let answer = (solve n m k old new)\n in\n do putAnsLn (length answer)\n putAnsLns answer\n\nmain = do (n,m,k) <- scan::IO (Int,Int,Double)\n old <- scans n::IO [(String,Int)]\n new <- scans m::IO [String]\n sub n m k old new "}, {"source_code": "import List\nq[s,e]=(s,read e)\nc(a,_)(b,_)=compare a b\ns([n,_,k]:t)=sortBy c$h++map z(filter(`notElem`map fst h)w)where{(g,v)=splitAt(read n)t;w=map(!!0)v;h=map q g>>=j;j(s,e)|x<100=[]|1>0=[(s,x)]where x=e*read(drop 2 k)`div`100}\nr(a,b)=a++\" \"++show b\np l=show(length l):map r l\nz x=(x,0)\nmain=interact$unlines.p.s.map words.lines\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nnotinc [] _ = True\nnotinc ((a,_):l) (x,y) = if x==a then False else notinc l (x,y)\n\nsolve :: Int -> Int -> Double -> [(String,Int)] -> [String] -> [(String,Int)]\nsolve n m k old new = sort (old' ++ new')\n where\n old' = filter (\\(n,e) -> e>100) (map (\\(n,e) -> (n,floor ((fromIntegral e)*k+0.000001))) old)\n new' = filter (notinc old') [(i,0)|i<-new]\n\n\nmain = do (n,m,k) <- scan::IO (Int,Int,Double)\n old <- scans n::IO [(String,Int)]\n new <- scans m::IO [String]\n putAnsLns (solve n m k old new)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nnotinc [] _ = True\nnotinc ((a,_):l) (x,y) = if x==a then False else notinc l (x,y)\n\nsolve :: Int -> Int -> Double -> [(String,Int)] -> [String] -> [(String,Int)]\nsolve n m k old new = sort (old' ++ new')\n where\n old' = filter (\\(n,e) -> e>100) (map (\\(n,e) -> (n,floor ((fromIntegral e)*k+0.000001))) old)\n new' = filter (notinc old') [(i,0)|i<-new]\n\nsub n m k old new = let answer = (solve n m k old new)\n in\n do putAnsLn (length answer)\n putAnsLns answer\n\nmain = do (n,m,k) <- scan::IO (Int,Int,Double)\n old <- scans n::IO [(String,Int)]\n new <- scans m::IO [String]\n sub n m k old new "}, {"source_code": "import IO\nimport List\n\nputAnsLn :: (Show a) => a -> IO ()\nputAnsLn ans = putStrLn (show ans)\n\ngetPairs :: IO (String,Int)\ngetPairs = do ns <- getLine\n return (conv (make_pair [n|n<-(words ns)]))\n where\n conv (x,y) = (x,read y::Int)\n make_pair (x:y:_) = (x,y)\n make_pair _ = (\"0\",\"0\")\n\ngetPairLines :: Int -> IO [(String,Int)]\ngetPairLines n = if n > 0 then\n do l <- getPairs\n ls <- getPairLines (n-1)\n return (l:ls)\n else\n return []\n\ngetStatus :: IO (Int, Int, Float)\ngetStatus = do l <- getLine\n return (conv [x|x<-(words l)])\n where\n conv (x:y:z:_) = (read x::Int ,read y::Int,read z::Float) \n\ngetLines :: Int -> IO [String]\ngetLines n = if n > 0 then\n do l <- getLine\n ls <- getLines (n-1)\n return (l:ls)\n else\n return []\n\ninclude [] e = False\ninclude ((x,_):xs) e = if x==e then True else include xs e\n\ntoStr str [] = str\ntoStr str ((x,exp):xs) = toStr ((x ++ \" \" ++ (show exp)):str) xs\n\nsolve :: Float -> Int -> [(String,Int)] -> [String] -> [String]\nsolve k m skills newskills = mpair (sort (toStr [] (merge (trans [] skills) newskills)))\n where\n trans l [] = l\n trans l ((sk,exp):sks) = let new_exp = (floor ((fromIntegral exp) * k)) in if new_exp < 100 then trans l sks else trans ((sk,new_exp):l) sks\n merge l [] = l\n merge l (x:xs) = if include l x then merge l xs else merge ((x,0):l) xs\n mpair l = (show (length l)):l\n\nputAnsLns [] = putStr \"\"\nputAnsLns (x:xs) = do putStrLn x\n putAnsLns xs\n\nmain = do (n, m, k) <- getStatus\n skills <- getPairLines n\n newskills <- getLines m\n putAnsLns (solve k m skills newskills)\n"}, {"source_code": "q[s,e]=(s,read e)\ns([n,_,k]:t)=h++map z(filter(`notElem`map fst h)w)where{(g,v)=splitAt(read n)t;w=map(!!0)v;h=map q g>>=j;j(s,e)|x<100=[]|1>0=[(s,x)]where x=e*read(drop 2 k)`div`100}\nr(a,b)=a++\" \"++show b\np l=show(length l):map r l\nz x=(x,0)\nmain=interact$unlines.p.s.map words.lines\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n\nimport Data.Ord\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.Map(Map)\nimport Data.List\n\nparseSkill [skill, exp] = (skill, read exp)\n\nmain = do\n [read -> (n :: Integer), read -> (m :: Integer), read -> (k :: Double)] <- words <$> getLine\n have <- replicateM (fromInteger n) (parseSkill . words <$> getLine)\n want <- replicateM (fromInteger m) getLine\n let\n r (s, e) \n | e' < 100 = []\n | otherwise = [(s, e')]\n where\n e' = floor (fromIntegral e * k)\n have' = have >>= r\n have'' = have' ++ map (\\s -> (s, 0)) (filter (`notElem` map fst have') want)\n pr (s, e) = putStrLn (s ++ \" \" ++ show e)\n\n putStrLn (show $ length have'')\n mapM pr (sortBy (comparing fst) have'')\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n\nimport Data.Ord\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.Map(Map)\nimport Data.List\n\nparseSkill [skill, exp] = (skill, read exp)\n\nmain = do\n [read -> (n :: Integer), read -> (m :: Integer), read -> (k :: Double)] <- words <$> getLine\n have <- replicateM (fromInteger n) (parseSkill . words <$> getLine)\n want <- replicateM (fromInteger m) getLine\n let\n r (s, e) \n | e' < 100 = []\n | otherwise = [(s, e')]\n where\n e' = floor (fromIntegral e * k)\n have' = have >>= r\n have'' = have' ++ map (\\s -> (s, 0)) (filter (`notElem` map fst have') want)\n pr (s, e) = putStrLn (s ++ \" \" ++ show e)\n\n mapM pr (sortBy (comparing fst) have'')\n"}], "src_uid": "7da1a5c4c76540e1c7dc06e4c908c8b4"} {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve = solve' . group . sort . map length . group . sort . filter (>0)\n\nsolve' :: [[Int]] -> Int\nsolve' xs | any ((>2) . head) xs = -1\n | otherwise = length $ last $ [] : filter ((==2) . head) xs\n", "positive_code": [{"source_code": "import Data.List (group, sort)\n\nmain = do\n getLine\n ids <- fmap (map read . words) getLine\n let calls = group $ sort $ filter (/=0) ids\n print $ if any ((>2) . length) calls\n then -1\n else length $ filter ((==2) . length) calls\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts\n\n let\n cs = map snd $ filter (\\(x, _) -> x /= 0) $ map (\\g -> (head g, length g)) $ group $ sort as\n\n print $ if any (> 2) cs\n then -1\n else length $ filter (== 2) cs\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve = estimate . group . sort . filter (0/=)\n where estimate xs | any ((>2) . length) xs = -1\n estimate xs = length $ filter ((==2) . length) xs\n\nmain = interact $ show . solve . tail . map read . words"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Map.Strict (foldl', fromListWith)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve = foldl' solve' 0 . fromListWith (+) . flip zip (repeat 1) . filter (/= 0)\n where\n solve' (-1) _ = -1\n solve' x 1 = x\n solve' x 2 = x + 1\n solve' _ _ = -1\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do\n n <- getLine\n a <- map read <$> words <$> getLine\n let tmp = map length $ group $ sort $ filter (/= 0) a\n if all (<= 2) tmp\n then print $ length $ filter (== 2) tmp\n else print (- 1)\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve = solve' . map length . group . sort . filter (>0)\n\nsolve' :: [Int] -> Int\nsolve' xs | any (>2) xs = -1\n | otherwise = length $ filter (==2) xs\n"}, {"source_code": "import Data.List\nmain=interact$show.g.map length.group.sort.filter(>0).map read.tail.words\ng x|any(>2)x= -1|1>0=length$filter(==2)x\n"}, {"source_code": "import Data.List\n\nclerkPairs :: (Integral a) => [a] -> a\nclerkPairs ids = clerkPairs' 0 (group (sort (filter (/= 0) ids)))\n where clerkPairs' n [] = n\n clerkPairs' n (x:xs)\n | length x > 2 = -1\n | length x == 2 = clerkPairs' (n + 1) xs\n | otherwise = clerkPairs' n xs\n\nmain = do\n _ <- getLine\n idsInput <- getLine\n let ids = map (read :: String -> Integer) (words idsInput) in print (clerkPairs ids)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n getLine\n ids <- map read.words <$> getLine\n print $ slv 0.group.sort $ filter (/= 0) ids\n\nslv n [] = n\nslv n (x:xs)\n | length x > 2 = -1\n | length x == 2 = slv (n+1) xs\n | otherwise = slv n xs"}, {"source_code": "import Data.List\ns l|any(>2)l= -1|1>0=length$filter(==2)l\nmain=interact$show.s.map length.group.sort.filter(>0).tail.map read.words"}, {"source_code": "conv :: String -> [Int]\nconv s = map read (words s)\n\nfind :: Int -> [Int] -> Int\nfind _ [] = 0\nfind cur (x:xs) \n | cur == x = 1 + find cur xs\n | otherwise = find cur xs\n\ngo :: [Int] -> Int\ngo [] = 0\ngo (x:xs) = (go ( xs )) + mod\n where cnt = find x xs\n mod\n | cnt == 1 = 1\n | cnt > 1 = - 1000\n | otherwise = 0\n\nsolve :: String -> String \nsolve input = show r\n where list = filter (\\x -> x > 0) (drop 1 (conv input))\n ret = go list\n r = max (-1) ret\n\nmain = do\n interact solve\n"}, {"source_code": "module Main where\n\nimport Data.List (group, sort)\n\nsolve :: [Int] -> Int\nsolve s | null incorrect = length pairs\n | otherwise = -1\n where groups = map length . group . sort . filter (/= 0) $ s\n pairs = filter (== 2) groups\n incorrect = filter (> 2) groups\n\nmain = do\n numSessions <- getLine\n sessions <- fmap (map read . words) getLine\n putStrLn . show $ solve sessions\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- map length . group . sort . filter (/=(0::Int)) . map read . words <$> getLine\n print $ if maximum (0:a) > 2 then -1 else length $ filter (==2) a\n"}, {"source_code": "\nimport Data.Char(digitToInt)\nimport Data.List(sort)\n\ntoInt::[Char]->Int\ntoInt x =\n let \n toInt'::[Char]->Int->Int\n toInt' y z =\n if null y\n then z\n else toInt' (tail y) (z*10+(digitToInt (head y)-digitToInt '0'))\n in toInt' x 0\n\nsplit::[Char]->[Char]->[[Char]]\nsplit x y =\n let\n split'::[Char]->[Char]->[Char]->[[Char]]\n split' _ [] [] = []\n split' _ [] c = [c]\n split' a (b:bs) c =\n if null [t|t<-a,t==b]\n then split' a bs (b:c)\n else (reverse c):(split' a bs [])\n in split' x y []\n\ngetAns::[Int]->Int\ngetAns x =\n let\n getAns'::[Int]->Int->Int->Int->Int\n getAns' [] _ lstCnt ans =\n if lstCnt>2\n then -1\n else if lstCnt==2\n then ans+1\n else\n ans\n getAns' (x:xs) lst lstCnt ans =\n if x/=lst&&lstCnt>2\n then -1\n else if x/=lst&&lstCnt==2\n then getAns' xs x 1 (ans+1)\n else if x==lst\n then getAns' xs lst (lstCnt+1) ans\n else\n getAns' xs x 1 ans\n in getAns' x 0 0 0\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = fmap toInt (split \" \\n\" input)\n n = head numbers\n id = sort [x|x<-(tail numbers),x/=0]\n print $ getAns id\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tlet\n\t\tarr = map length. group. filter (/= 0). sort. map (\\x -> read x :: Integer). words $ line\n\t\tsol :: Int -> [Int] -> Int\n\t\tsol x [] = x\n\t\tsol x (p:ps)\n\t\t | p > 2 = (-1)\n\t\t | p == 2 = sol (x+1) ps\n\t\t | otherwise = sol x ps\n\tprint $ sol 0 arr\n"}], "negative_code": [{"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve = solve' . group . sort . map length . group . sort\n\nsolve' :: [[Int]] -> Int\nsolve' xs | any ((>2) . head) xs = -1\n | otherwise = length $ last $ [] : filter ((==2) . head) xs\n"}, {"source_code": "conv :: String -> [Int]\nconv s = map read (words s)\n\nfind :: Int -> [Int] -> Int\nfind _ [] = 0\nfind cur (x:xs) \n | cur == x = 1 + find cur xs\n | otherwise = find cur xs\n\ngo :: Int -> [Int] -> Int\ngo _ [] = 0\ngo x xs = (go ( head xs ) ( tail xs )) + mod\n where cnt = find x xs\n mod\n | cnt == 1 = 1\n | cnt > 1 = - 1000\n | otherwise = 0\n\nsolve :: String -> String \nsolve input = show r\n where (x:xs) = drop 1 (conv input)\n ret = go x xs\n r = max (-1) ret\n\nmain = do\n interact solve\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tlet\n\t\tarr = map fromIntegral.map length. group. filter (/= 0). sort. map (\\x -> read x :: Integer). words $ line\n\t\tsol :: [Integer] -> Int\n\t\tsol [] = 0\n\t\tsol (p:ps)\n\t\t | p > (2::Integer) = (-1)\n\t\t | p == (2::Integer) = (1::Int) + sol ps\n\t\t | p == (1::Integer) = sol ps\n\t\t | otherwise = error \"something wrong\"\n\tprint $ sol arr\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tline2 <- getLine\n\tlet\n\t\tn = read line ::Int\n\t\tarr = map length. group. filter (/= 0). sort. map (\\x -> read x :: Int). words $ line2\n\t\tsol :: [Int] -> Int\n\t\tsol [] = 0\n\t\tsol (p:ps)\n\t\t | p > 2 = (-1)\n\t\t | p == 2 = 1 + sol ps\n\t\t | otherwise = sol ps\n\tprint $ sol arr\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tlet\n\t\tarr = map length. group. filter (/= 0). sort. map (\\x -> read x :: Integer). words $ line\n\t\tsol :: [Int] -> Int\n\t\tsol [] = 0::Int\n\t\tsol (p:ps)\n\t\t | p > 2 = (-1)\n\t\t | p == 2 = (1::Int) + sol ps\n\t\t | p == 1 = sol ps\n\t\t | otherwise = error \"something wrong\"\n\tprint $ sol arr\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline <- getLine\n\tline2 <- getLine\n\tlet\n\t\tn = read line ::Int\n\t\tarr = map length. group. sort. map (\\x -> read x :: Int). words $ line2\n\t\tsol :: [Int] -> Int\n\t\tsol [] = 0\n\t\tsol (p:ps)\n\t\t | p > 2 = (-1)\n\t\t | p == 2 = 1 + sol ps\n\t\t | otherwise = sol ps\n\tprint $ sol arr\n"}, {"source_code": "module Main where\n\nimport Data.List (group, sort)\n\nsolve :: [Int] -> Int\nsolve s | null incorrect = length pairs\n | otherwise = -1\n where groups = map length . group $ sort s\n pairs = filter (== 2) groups\n incorrect = filter (> 2) groups\n\nmain = do\n numSessions <- getLine\n sessions <- fmap (map read . words) getLine\n putStrLn . show $ solve sessions\n"}, {"source_code": "\nimport Data.Char(digitToInt)\nimport Data.List(sort)\n\ntoInt::[Char]->Int\ntoInt x =\n let \n toInt'::[Char]->Int->Int\n toInt' y z =\n if null y\n then z\n else toInt' (tail y) (z*10+(digitToInt (head y)-digitToInt '0'))\n in toInt' x 0\n\nsplit::[Char]->[Char]->[[Char]]\nsplit x y =\n let\n split'::[Char]->[Char]->[Char]->[[Char]]\n split' _ [] [] = []\n split' _ [] c = [c]\n split' a (b:bs) c =\n if null [t|t<-a,t==b]\n then split' a bs (b:c)\n else (reverse c):(split' a bs [])\n in split' x y []\n\ngetAns::[Int]->Int\ngetAns x =\n let\n getAns'::[Int]->Int->Int->Int\n getAns' [] _ lstCnt =\n if lstCnt>2\n then -1\n else if lstCnt==2\n then 1\n else\n 0\n getAns' (x:xs) lst lstCnt =\n if x/=lst&&lstCnt>2\n then -1\n else if x/=lst&&lstCnt==2\n then 1+(getAns' xs x 1)\n else if x==lst\n then getAns' xs lst (lstCnt+1)\n else\n getAns' xs x 1\n in getAns' x 0 0\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = fmap toInt (split \" \\n\" input)\n n = head numbers\n id = sort [x|x<-(tail numbers),x/=0]\n print $ getAns id\n"}, {"source_code": "\nimport Data.Char(digitToInt)\nimport Data.List(sort)\n\ntoInt::[Char]->Int\ntoInt x =\n let \n toInt'::[Char]->Int->Int\n toInt' y z =\n if null y\n then z\n else toInt' (tail y) (z*10+(digitToInt (head y)-digitToInt '0'))\n in toInt' x 0\n\nsplit::[Char]->[Char]->[[Char]]\nsplit x y =\n let\n split'::[Char]->[Char]->[Char]->[[Char]]\n split' _ [] [] = []\n split' _ [] c = [c]\n split' a (b:bs) c =\n if null [t|t<-a,t==b]\n then split' a bs (b:c)\n else (reverse c):(split' a bs [])\n in split' x y []\n\ngetAns::[Int]->Int\ngetAns x =\n let\n getAns'::[Int]->Int->Int->Int->Int\n getAns' [] _ lstCnt ans =\n if lstCnt>2\n then -1\n else if lstCnt==2\n then ans+1\n else\n ans\n getAns' (x:xs) lst lstCnt ans =\n if x/=lst&&lstCnt>2\n then -1\n else if x/=lst&&lstCnt==2\n then getAns' xs lst lstCnt (ans+1)\n else if x==lst\n then getAns' xs lst (lstCnt+1) ans\n else\n getAns' xs x 1 ans\n in getAns' x 0 0 0\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = fmap toInt (split \" \\n\" input)\n n = head numbers\n id = sort [x|x<-(tail numbers),x/=0]\n print $ getAns id\n"}], "src_uid": "45e51f3dee9a22cee86e1a98da519e2d"} {"source_code": "import Maybe (isNothing)\nimport List (sortBy, tails, find, group)\nimport Array (Array, array, bounds, elems, assocs, accumArray, (!), (//))\n\ncrossing :: ((Int, (Int, Int)), (Int, (Int, Int))) -> Bool\ncrossing ((_, (a, b)), (_, (c, d))) = a < c && c < b && b < d ||\n c < a && a < d && d < b\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = concatMap (\\ ((a, (_, _)), (b, (_, _))) -> [(a, b), (b, a)]) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n\nbicolor :: Array Int [Int] -> Maybe (Array Int (Maybe Bool)) \nbicolor g =\n let (a, b) = bounds g in \n loop (array (a, b) ((a, Just False):[(i, Nothing) | i <- [a+1..b]])) [1]\n where\n loop colors [] = \n case find (isNothing . snd) (assocs colors) of\n Just (i, _) -> loop (colors // [(i, Just False)]) [i]\n Nothing -> Just colors\n loop colors (v:vs) = \n if all correct adj then\n let new = filter (\\v' -> isNothing (colors ! v')) adj in\n loop (colors // [(v', Just (not c)) | v' <- new]) (vs ++ new)\n else\n Nothing\n where\n Just c = colors ! v\n adj = g ! v\n correct v' = case colors ! v' of \n Just c' -> c' == not c\n Nothing -> True\n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs = \n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n Just a -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n Nothing -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n", "positive_code": [{"source_code": "import Data.Array.MArray (newArray, writeArray, readArray)\nimport List (tails)\nimport Array (Array, bounds, elems, indices, accumArray, (!))\nimport Data.Array.MArray (unsafeFreeze)\nimport Data.Array.ST (STArray)\nimport Control.Monad (forM, when)\nimport Control.Monad.ST (ST, runST)\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = \n concatMap (\\ ((a, (_, _)), (b, (_, _))) -> [(a, b), (b, a)]) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n crossing ((_, (a, b)), (_, (c, d))) = a < c && c < b && b < d ||\n c < a && a < d && d < b\n\nbicolor g = runST $ do\n colors <- newArray (bounds g) Nothing :: ST s (STArray s Int (Maybe Bool))\n flags <- forM (indices g) $ \\v -> do\n c <- readArray colors v\n if c == Nothing then dfs colors v True\n else return True\n if all id flags then do \n result <- unsafeFreeze colors\n return (Just result)\n else \n return Nothing \n where\n dfs colors v color = do\n c <- readArray colors v\n case c of\n Nothing -> do\n writeArray colors v (Just color) \n flags <- forM (g ! v) $ \\v' ->\n dfs colors v' (not color)\n return (all id flags)\n Just c | c == color -> return True\n | otherwise -> return False \n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs =\n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n Just a -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n Nothing -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n"}, {"source_code": "import Maybe (isNothing)\nimport List (sortBy, tails, find, group)\nimport Array (Array, array, bounds, elems, assocs, accumArray, (!), (//))\n\ncrossing :: ((Int, (Int, Int)), (Int, (Int, Int))) -> Bool\ncrossing ((_, (a, b)), (_, (c, d))) = check $ \n sortBy (\\ (a, _, _) (b, _, _) -> compare a b) $\n [(a, False, 0), (b, True, 0), \n (c, False, 1), (d, True, 1)]\n where\n check [(a, False, na), (b, False, nb), (c, True, nc), (d, True, nd)] \n | na == nc && nb == nd && (length $ group $ [a, b, c, d]) == 4 = True\n check _ = False\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = concatMap (\\ ((a, (_, _)), (b, (_, _))) -> [(a, b), (b, a)]) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n\nbicolor :: Array Int [Int] -> Maybe (Array Int (Maybe Bool)) \nbicolor g =\n let (a, b) = bounds g in \n loop (array (a, b) ((a, Just False):[(i, Nothing) | i <- [a+1..b]])) [1]\n where\n loop colors [] = \n case find (isNothing . snd) (assocs colors) of\n Just (i, _) -> loop (colors // [(i, Just False)]) [i]\n Nothing -> Just colors\n loop colors (v:vs) = \n if all correct adj then\n let new = filter (\\v' -> isNothing (colors ! v')) adj in\n loop (colors // [(v', Just (not c)) | v' <- new]) (vs ++ new)\n else\n Nothing\n where\n Just c = colors ! v\n adj = g ! v\n correct v' = case colors ! v' of \n Just c' -> c' == not c\n Nothing -> True\n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs = \n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n Just a -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n Nothing -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n"}, {"source_code": "import Data.Array.MArray (newArray, writeArray, readArray)\nimport List (tails)\nimport Array (Array, bounds, elems, indices, accumArray, (!))\nimport Data.Array.MArray (unsafeFreeze)\nimport Data.Array.ST (STArray)\nimport Control.Monad (forM, when)\nimport Control.Monad.ST.Lazy (ST, runST)\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = \n concatMap (\\ ((a, (_, _)), (b, (_, _))) -> [(a, b), (b, a)]) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n crossing ((_, (a, b)), (_, (c, d))) = a < c && c < b && b < d ||\n c < a && a < d && d < b\n\nbicolor g = runST $ do\n colors <- newArray (bounds g) Nothing :: ST s (STArray s Int (Maybe Bool))\n flags <- forM (indices g) $ \\v -> do\n c <- readArray colors v\n result <- dfs colors v True\n return (c /= Nothing || result)\n result <- unsafeFreeze colors\n return (all id flags, result) \n where\n dfs colors v color = do\n c <- readArray colors v\n case c of\n Nothing -> do\n writeArray colors v (Just color) \n flags <- forM (g ! v) $ \\v' -> dfs colors v' (not color)\n return (all id flags)\n Just c -> return (c == color) \n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs =\n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n (True, a) -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n _ -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n"}, {"source_code": "import Maybe (isNothing)\nimport List (tails, find)\nimport Array (Array, array, bounds, elems, assocs, accumArray, (!), (//))\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = concatMap (\\ ((a, (_, _)), (b, (_, _))) -> [(a, b), (b, a)]) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n crossing ((_, (a, b)), (_, (c, d))) = a < c && c < b && b < d ||\n c < a && a < d && d < b\n \nbicolor :: Array Int [Int] -> Maybe (Array Int (Maybe Bool)) \nbicolor g =\n let (a, b) = bounds g in \n loop (array (a, b) ((a, Just False):[(i, Nothing) | i <- [a+1..b]])) [1]\n where\n loop colors [] = \n case find (isNothing . snd) (assocs colors) of\n Just (i, _) -> loop (colors // [(i, Just False)]) [i]\n Nothing -> Just colors\n loop colors (v:vs) = \n if all correct adj then\n let new = filter (isNothing . (colors !)) adj in\n loop (colors // [(v', Just (not c)) | v' <- new]) (vs ++ new)\n else\n Nothing\n where\n Just c = colors ! v\n adj = g ! v\n correct v' = case colors ! v' of \n Just c' -> c' == not c\n Nothing -> True\n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs = \n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n Just a -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n Nothing -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport List\n\nmain = do\n\t[n, m] <- getA\n\te <- replicateM m getA\n\tputStr $ show' $ gao m $ listArray (1, m) $ map sort e where\n\t\tgetA = fmap (map read . words) getLine\n\t\tshow' (Just a) = elems a\n\t\tshow' _ = \"Impossible\"\n\ninter x@[a,b] y@[c,d] = if a > c then inter y x else a < c && c < b && b < d\n\ngao n e = foldl f (Just $ listArray (1, n) $ repeat '?') [1 .. n] where\n\tf z@(Just a) i = if a!i == '?' then g 'o' z i else z\n\tf _ _ = Nothing\n\tg c z@(Just a) i = if a!i == c then z else if a!i /= '?' then Nothing else r where\n\t\tb = filter (\\j -> inter (e!i) (e!j)) [1 .. n]\n\t\td = if c == 'o' then 'i' else 'o'\n\t\tr = foldl (g d) (Just $ a // [(i, c)]) b\n\tg _ _ _ = Nothing\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport List\n\nmain = do\n\t[n, m] <- getA\n\te <- replicateM m getA\n\tputStr $ show' $ gao m $ listArray (1, m) $ map sort e where\n\t\tgetA = fmap (map read . words) getLine\n\t\tshow' Nothing = \"Impossible\"\n\t\tshow' (Just a) = elems a\n\ninter (x@[a,b]) (y@[c,d]) = if a > c then inter y x else a < c && c < b && b < d\n\ngao n e = foldl f (Just $ listArray (1, n) $ repeat '?') [1 .. n] where\n\tf Nothing _ = Nothing\n\tf (Just a) i = if a!i == '?' then g 'o' (Just a) i else Just a\n\tg _ Nothing _ = Nothing\n\tg c (Just a) i = if a!i == c then Just a else if a!i /= '?' then Nothing else r where\n\t\tb = filter (\\j -> inter (e!i) (e!j)) [1 .. n]\n\t\td = if c == 'o' then 'i' else 'o'\n\t\tr = foldl (g d) (Just $ a // [(i, c)]) b\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport List\n\nmain = do\n\t[n, m] <- getA\n\te <- replicateM m getA\n\tputStr $ show' $ gao m $ listArray (1, m) $ map sort e where\n\t\tgetA = fmap (map read . words) getLine\n\t\tshow' (Just a) = elems a\n\t\tshow' _ = \"Impossible\"\n\ninter x@[a,b] y@[c,d] = if a > c then inter y x else a < c && c < b && b < d\n\ngao n e = foldl f (Just $ listArray (1, n) $ repeat '?') [1 .. n] where\n\tf z@(Just a) i = if a!i == '?' then g 'o' z i else z\n\tf _ _ = Nothing\n\tg c z@(Just a) i = case a!i of { '?' -> r; c -> z; d -> Nothing } where\n\t\tb = filter (\\j -> inter (e!i) (e!j)) [1 .. n]\n\t\td = if c == 'o' then 'i' else 'o'\n\t\tr = foldl (g d) (Just $ a // [(i, c)]) b\n\tg _ _ _ = Nothing\n\n"}, {"source_code": "import Data.Array.MArray (newArray, writeArray, readArray)\nimport List (tails)\nimport Array (Array, bounds, elems, indices, accumArray, (!))\nimport Data.Array.MArray (unsafeFreeze)\nimport Data.Array.ST (STArray)\nimport Control.Monad (forM, when)\nimport Control.Monad.ST.Lazy (ST, runST)\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = \n concatMap (\\ ((a, (_, _)), (b, (_, _))) -> [(a, b), (b, a)]) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n crossing ((_, (a, b)), (_, (c, d))) = a < c && c < b && b < d ||\n c < a && a < d && d < b\n\nbicolor g = runST $ do\n colors <- newArray (bounds g) Nothing :: ST s (STArray s Int (Maybe Bool))\n flags <- forM (indices g) $ \\v -> do\n c <- readArray colors v\n result <- dfs colors v True\n return (c == Nothing || result)\n result <- unsafeFreeze colors\n return (all id flags, result) \n where\n dfs colors v color = do\n c <- readArray colors v\n case c of\n Nothing -> do\n writeArray colors v (Just color) \n flags <- forM (g ! v) $ \\v' -> dfs colors v' (not color)\n return (all id flags)\n Just c -> return (c == color) \n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs =\n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n (True, a) -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n _ -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n"}, {"source_code": "import Maybe (isNothing)\nimport List (sortBy, tails, find, group)\nimport Array (Array, array, bounds, elems, assocs, accumArray, (!), (//))\n\ncrossing :: ((Int, (Int, Int)), (Int, (Int, Int))) -> Bool\ncrossing ((_, (a, b)), (_, (c, d))) = check $ \n sortBy (\\ (a, _, _) (b, _, _) -> compare a b) $\n [(a, False, 0), (b, True, 0), \n (c, False, 1), (d, True, 1)]\n where\n check [(a, False, na), (b, False, nb), (c, True, nc), (d, True, nd)] \n | na == nc && nb == nd && (length $ group $ [a, b, c, d]) == 4 = True\n check _ = False\n\nedges :: [(Int, Int)] -> [(Int, Int)]\nedges xs = map (\\ ((a, (_, _)), (b, (_, _))) -> (a, b)) $ \n filter crossing [(x, y) | x:xs <- tails indexed, y <- xs]\n where\n indexed = zip [1..] $ map (\\ (a, b) -> (min a b, max a b)) xs\n\nbicolor :: Array Int [Int] -> Maybe (Array Int (Maybe Bool)) \nbicolor g =\n let (a, b) = bounds g in \n loop (array (a, b) ((a, Just False):[(i, Nothing) | i <- [a+1..b]])) [1]\n where\n loop colors [] = \n case find (isNothing . snd) (assocs colors) of\n Just (i, _) -> loop (colors // [(i, Just False)]) [i]\n Nothing -> Just colors\n loop colors (v:vs) = \n if all correct adj then\n let new = filter (\\v' -> isNothing (colors ! v')) adj in\n loop (colors // [(v', Just (not c)) | v' <- new]) (vs ++ new)\n else\n Nothing\n where\n Just c = colors ! v\n adj = g ! v\n correct v' = case colors ! v' of \n Just c' -> c' == not c\n Nothing -> True\n \nanswer :: Int -> [(Int, Int)] -> String\nanswer n xs = \n case bicolor $ accumArray (flip (:)) [] (1, n) (edges xs) of\n Just a -> map (\\ (Just c) -> if c then 'i' else 'o') $ elems a\n Nothing -> \"Impossible\"\n\nsolve xs = answer n roads\n where\n n = read $ (!! 1) $ words $ head ls\n roads = map ((\\ [a, b] -> (read a, read b)) . words) $ tail ls\n ls = lines xs\n \nmain = interact solve\n"}], "src_uid": "214cdb73c2fb5ab995eb5aec76e5f4fb"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\n\nmain :: IO ()\nmain = do\n q <- read <$> getLine\n as <- take q . unfoldr (runStateT $ rInt) <$> BSL.getContents\n mapM_ (print . query) $ map toI32 as\n\nquery :: Int32 -> Int32\nquery x\n | x /= bitFill = bitFill\n | otherwise = maybe 1 (div bitFill)\n $ find ((==0). (bitFill `mod`))\n [2..ceilI32 $ sqrt $ toDouble bitFill]\n where\n bitFill = (+(-1)) $ bit $ finiteBitSize x - clz x :: Int32\n\nclz :: Int32 -> Int\nclz x\n |x == 0 = 32\n |x /= 0 = 31 - ret\n where\n (!v,ret) = foldl' loop (x,0) $ map bit $ [4,3..0]\n loop (!x,!acc) b | x1 /= 0 = (x1,acc .|. b)\n | otherwise = (x,acc)\n where\n x1 = shiftR x b\n \n \nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n", "positive_code": [{"source_code": "import Data.Bits\nimport Data.List\nmain = interact $ unlines . map show . map process . tail . map read . words\n\nprocess :: Int -> Int\nprocess x\n | x /= pw x = pw x \n | elem x primes = 1\n | otherwise = case (find (\\z -> mod x z == 0) primes) of\n Just z -> div x z\n Nothing -> 1\n\npw x = foldl (\\v z -> v .|. shiftR v (2^z)) x [0..4]\nsieve (n:ns) = n:sieve [ m | m <- ns, m `mod` n /= 0 ]\nprimes = 2 : (takeWhile (< 2^14) $ sieve [3,5..])\n"}, {"source_code": "import Text.Printf\nimport Control.Monad\nimport Data.Bits\n\nglwr :: Read a => IO [a]\nglwr = fmap (map read . words) getLine\n\nmain :: IO ()\nmain = do\n n <- readLn\n mapM_ process [1..n :: Int]\n\nprocess _ = do\n n <- readLn\n putStrLn . show $ op n\n\nop :: Int -> Int\nop n\n | n == p2*2 - 1 = lDiv\n | True = p2*2 - 1\n where\n p2 = last p2s\n (p2s, _) = break (> n) pow2\n lDiv = div n $ sDiv n\n\nsDiv :: Int -> Int\nsDiv n = head $ filter valid [2..sqrtN] ++ [n]\n where\n sqrtN = floor $ sqrt $ toEnum n\n valid x = rem n x == 0\n\npow2 :: [Int]\npow2 = map (2^) [1..]\n"}], "negative_code": [{"source_code": "import Text.Printf\nimport Control.Monad\nimport Data.Bits\n\nglwr :: Read a => IO [a]\nglwr = fmap (map read . words) getLine\n\nmain :: IO ()\nmain = do\n n <- readLn\n mapM_ process [1..n :: Int]\n\nprocess _ = do\n n <- readLn\n putStrLn . show $ op n\n\nop :: Int -> Int\nop n\n | n == p2*2 - 1 = 1\n | True = p2*2 - 1\n where\n p2 = last p2s\n (p2s, _) = break (> n) pow2\n\npow2 :: [Int]\npow2 = map (2^) [1..]\n"}], "src_uid": "ce9a0649ccfc956559254f324dfa02a7"} {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Foldable\nimport Data.Graph\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\[a, b, c] -> (b, c)) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG (1, n) el, edgeList)\n\nsolve (n, graph, edgeList) = forM edgeList $ \\[a, b, c] ->\n if a == 0\n then (if arr ! b < arr ! c then Just (b, c) else Just (c, b))\n else (if arr ! b < arr ! c then Just (b, c) else Nothing)\n where\n arr = array (1, n) $ zip sorted [1 .. n]\n sorted = topSort graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\"", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Foldable\nimport Data.Graph\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\[a, b, c] -> (b, c)) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG (1, n) el, map (\\[a, b, c] -> (a, b, c)) edgeList)\n\nsolve (n, graph, edgeList) =\n forM edgeList $\n ( \\(a, b, c) ->\n if a == 0\n then (if arr ! b < arr ! c then Just (b, c) else Just (c, b))\n else (if arr ! b < arr ! c then Just (b, c) else Nothing)\n )\n where\n arr = array (1, n) $ zip sorted [1 .. n]\n sorted = topSort graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\""}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Foldable\nimport Data.List\nimport qualified Data.Sequence as S\n\nbuildG n el = arr\n where\n arr = foldl (\\a (b, c) -> S.adjust (c :) b a) (S.replicate (n + 1) []) el\n\ngo :: S.Seq [Int] -> S.Seq Int -> S.Seq Int -> [Int]\ngo graph ind queue = case S.viewl queue of\n S.EmptyL -> []\n x S.:< rest -> x : (go graph ind' queue')\n where\n ind' = foldl (\\ind'' x -> S.adjust (\\a -> a - 1) x ind'') ind (graph `S.index` x)\n queue' = rest S.>< S.fromList (filter (\\x -> (ind' `S.index` x) == 0) (graph `S.index` x))\n\ntopSort n graph = if length res == n then Just res else Nothing\n where\n res = go graph ind queue\n ind = foldl (\\ind' x -> foldl (\\ind'' y -> S.adjust (+ 1) y ind'') ind' x) (S.replicate (n + 1) 0) graph\n queue = S.fromList $ filter (\\x -> (ind `S.index` x) == 0) [1 .. n]\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\[a, b, c] -> (b, c)) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG n el, map (\\[a, b, c] -> (b, c)) edgeList)\n\nsolve (n, graph, edgeList) = (\\a -> map (\\(x, y) -> if (a ! x) < (a ! y) then (x, y) else (y, x)) edgeList) <$> arr\n where\n arr = (\\s -> array (1, n) $ zip s [1 .. n]) <$> sorted\n sorted = topSort n graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\""}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Foldable\nimport Data.Graph\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\[a, b, c] -> (b, c)) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG (1, n) el, map (\\[a, b, c] -> (a, b, c)) edgeList)\n\nsolve (n, graph, edgeList) =\n forM edgeList $ \\(a, b, c) ->\n if a == 0\n then (if arr ! b < arr ! c then Just (b, c) else Just (c, b))\n else (if arr ! b < arr ! c then Just (b, c) else Nothing)\n where\n arr = array (1, n) $ zip sorted [1 .. n]\n sorted = topSort graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\""}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\ntype Graph = Array Int [Int]\n\nbuildG :: Int -> [[Int]] -> Graph\nbuildG n el = S.runSTArray $ do\n res <- S.newArray (1, n) []\n forM_ el $ \\[a, b] -> do\n x <- S.readArray res a\n S.writeArray res a $ b : x\n return res\n\nindeg :: Graph -> U.UArray Int Int\nindeg graph = S.runSTUArray $ do\n res <- S.newArray (1, n) 0\n forM_ [1 .. n] $ \\i -> do\n forM_ (graph ! i) $ \\j -> do\n a <- S.readArray res j\n S.writeArray res j (a + 1)\n return res\n where\n n = snd $ bounds graph\n\ntopSort' :: Graph -> S.STUArray s Int Int -> Int -> [Int] -> ST s [Int]\ntopSort' graph ind x res = do\n let f = \\l i -> do\n a <- S.readArray ind i\n S.writeArray ind i (a - 1)\n if a == 1 then topSort' graph ind i l else return l\n foldM f (x : res) (graph ! x)\n\ntopSort :: Graph -> Maybe [Int]\ntopSort graph = if length arr == n then Just arr else Nothing\n where\n n = snd $ bounds graph\n arr = reverse $\n runST $ do\n ind' <- S.thaw ind\n let f = \\l x -> do\n a <- S.readArray ind' x\n if a == 0 then topSort' graph ind' x l else return l\n foldM f [] $ filter (\\x -> (ind U.! x) == 0) [1 .. n]\n ind = indeg graph\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\(a : b) -> b) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG n el, map (\\[a, b, c] -> (b, c)) edgeList)\n\nsolve (n, graph, edgeList) = (\\a -> map (\\(x, y) -> if (a ! x) < (a ! y) then (x, y) else (y, x)) edgeList) <$> arr\n where\n arr = (\\s -> array (1, n) $ zip s [1 .. n]) <$> sorted\n sorted = topSort graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\"\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\nuniq :: Eq a => [a] -> [a]\nuniq [] = []\nuniq [x] = [x]\nuniq (a : b : xs) = if a == b then uniq (b : xs) else a : uniq (b : xs)\n\ntype Graph = Array Int [Int]\n\nbuildG :: Int -> [[Int]] -> Graph\nbuildG n el = S.runSTArray $ do\n res <- S.newArray (1, n) []\n forM_ el $ \\[a, b] -> do\n x <- S.readArray res a\n S.writeArray res a $ b : x\n forM_ [1 .. n] $ \\i -> do\n x <- S.readArray res i\n S.writeArray res i $ uniq $ sort x\n return res\n\nindeg :: Graph -> U.UArray Int Int\nindeg graph = S.runSTUArray $ do\n res <- S.newArray (1, n) 0\n forM_ [1 .. n] $ \\i -> do\n forM_ (graph ! i) $ \\j -> do\n a <- S.readArray res j\n S.writeArray res j (a + 1)\n return res\n where\n n = snd $ bounds graph\n\ntopSort' :: Graph -> S.STUArray s Int Int -> Int -> [Int] -> ST s [Int]\ntopSort' graph ind x res = do\n forM_ (graph ! x) $ \\i -> do\n a <- S.readArray ind i\n S.writeArray ind i (a - 1)\n let f = \\l i -> do\n a <- S.readArray ind i\n if a == 0 then topSort' graph ind i l else return l\n foldM f (x : res) (graph ! x)\n\ntopSort :: Graph -> Maybe [Int]\ntopSort graph = if length arr == n then Just arr else Nothing\n where\n n = snd $ bounds graph\n arr = reverse $\n runST $ do\n ind' <- S.thaw ind\n let f = \\l x -> do\n a <- S.readArray ind' x\n if a == 0 then topSort' graph ind' x l else return l\n foldM f [] $ filter (\\x -> (ind U.! x) == 0) [1 .. n]\n ind = indeg graph\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\[a, b, c] -> [b, c]) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG n el, map (\\[a, b, c] -> (b, c)) edgeList)\n\nsolve (n, graph, edgeList) = (\\a -> map (\\(x, y) -> if (a ! x) < (a ! y) then (x, y) else (y, x)) edgeList) <$> arr\n where\n arr = (\\s -> array (1, n) $ zip s [1 .. n]) <$> sorted\n sorted = topSort graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\ntype Graph = Array Int [Int]\n\nbuildG :: Int -> [[Int]] -> Graph\nbuildG n el = S.runSTArray $ do\n res <- S.newArray (1, n) []\n forM_ el $ \\[a, b] -> do\n x <- S.readArray res a\n S.writeArray res a $ b : x\n return res\n\nindeg :: Graph -> U.UArray Int Int\nindeg graph = S.runSTUArray $ do\n res <- S.newArray (1, n) 0\n forM_ [1 .. n] $ \\i -> do\n forM_ (graph ! i) $ \\j -> do\n a <- S.readArray res j\n S.writeArray res j (a + 1)\n return res\n where\n n = snd $ bounds graph\n\ntopSort' :: Graph -> S.STUArray s Int Int -> Int -> [Int] -> ST s [Int]\ntopSort' graph ind x res = do\n forM_ (graph ! x) $ \\i -> do\n a <- S.readArray ind i\n S.writeArray ind i (a - 1)\n let f = \\l i -> do\n a <- S.readArray ind i\n if a == 0 then topSort' graph ind i l else return l\n foldM f (x : res) (graph ! x)\n\ntopSort :: Graph -> Maybe [Int]\ntopSort graph = if length arr == n then Just arr else Nothing\n where\n n = snd $ bounds graph\n arr = reverse $\n runST $ do\n ind' <- S.thaw ind\n let f = \\l x -> do\n a <- S.readArray ind' x\n if a == 0 then topSort' graph ind' x l else return l\n foldM f [] $ filter (\\x -> (ind U.! x) == 0) [1 .. n]\n ind = indeg graph\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n edgeList <- replicateM m $ map read . words <$> getLine\n let el = map (\\(a : b) -> b) $ filter (\\[a, _, _] -> a == 1) edgeList\n return (n, buildG n el, map (\\[a, b, c] -> (b, c)) edgeList)\n\nsolve (n, graph, edgeList) = (\\a -> map (\\(x, y) -> if (a ! x) < (a ! y) then (x, y) else (y, x)) edgeList) <$> arr\n where\n arr = (\\s -> array (1, n) $ zip s [1 .. n]) <$> sorted\n sorted = topSort graph\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n res <- solve <$> readInput\n case res of\n Just x -> do\n putStrLn \"YES\"\n for_ x (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b)\n Nothing -> putStrLn \"NO\"\n"}], "src_uid": "4bee64265ade3c09002446264dcd26a6"} {"source_code": "import Control.Monad (forM_)\nimport Data.List\nimport Debug.Trace (trace)\n\nreadInts = getLine >>= pure . map read . words\n\nsame (a:as) (b:bs) = (elem a \"GB\" == elem b \"GB\") && same as bs\nsame [] [] = True\n\nmain = do\n [n'] <- readInts\n forM_ [1..n'] (\\_ -> do\n getLine\n a <- getLine\n b <- getLine\n putStrLn $ if same a b then \"YES\" else \"NO\"\n )", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>\n getLine >>= \\s1 -> getLine >>=\n putStrLn . ite \"Yes\" \"No\" . isSame s1\nite x y b = if b then x else y\nisSame s1 s2 = all (uncurry f) (zip s1 s2)\n where f 'R' 'R' = True\n f 'R' _ = False\n f _ 'R' = False\n f _ _ = True\n"}, {"source_code": "{-#LANGUAGE ScopedTypeVariables#-}\r\nimport Data.Char (isDigit)\r\nimport Data.Text (replace)\r\n\r\n\r\nmain = do\r\n input <- getContents\r\n let parsed = removeDigits (drop 1 (lines input))\r\n let result = iteratePairs (map replaceDigits parsed)\r\n mapM_ putStrLn result\r\n\r\n\r\nremoveDigits :: [String] -> [String]\r\nremoveDigits [] = []\r\nremoveDigits (x:xs) \r\n | all isDigit x = removeDigits xs\r\n | otherwise = [x] ++ removeDigits xs\r\n\r\n\r\nreplaceDigits :: String -> String\r\nreplaceDigits [] = []\r\nreplaceDigits (x:xs)\r\n | x == 'G' = ['B'] ++ replaceDigits xs\r\n | otherwise = [x] ++ replaceDigits xs\r\n\r\n\r\niteratePairs :: [String] -> [String]\r\niteratePairs [] = []\r\niteratePairs (one:two:rest) = [(checkPairs one two)] ++ iteratePairs rest\r\n\r\n\r\ncheckPairs :: String -> String -> String\r\ncheckPairs [] [] = \"YES\"\r\ncheckPairs (x:xs) (y:ys) \r\n | x /= y = \"NO\"\r\n | otherwise = checkPairs xs ys\r\n"}, {"source_code": "toOneForm [] = []\r\ntoOneForm (x:xs) = if x == 'G' \r\n then ('B':) $ (toOneForm xs)\r\n else (x:) $ toOneForm xs\r\n \r\ndecide :: Int -> IO ()\r\ndecide 0 = return ()\r\ndecide n = do\r\n getLine\r\n s1 <- getLine\r\n s2 <- getLine\r\n if toOneForm s1 == toOneForm s2 \r\n then putStrLn \"YES\"\r\n else putStrLn \"NO\"\r\n decide (n - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine >>= (return . (read :: String -> Int))\r\n decide t "}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List (group, sort)\n\nsolve :: String -> String -> String\nsolve s1 s2\n | answer = \"YES\"\n | otherwise = \"NO\"\n where answer = and $ zipWith check s1 s2\n\ncheck c1 c2\n | c1 == c2 = True\n | c1 == 'G' = c2 == 'B'\n | c1 == 'B' = c2 == 'G'\n | otherwise = False\n\nwork = do\n t <- getLine\n s1 <- getLine\n s2 <- getLine\n\n putStrLn $ solve s1 s2\n\nmain = do\n t <- getLine\n\n replicateM_ (read t :: Int) work\n"}, {"source_code": "module Main\r\n ( main )\r\n where\r\n\r\nimport Control.Monad (replicateM)\r\n\r\ndata Color\r\n = Red\r\n | Green\r\n | Blue\r\n deriving Show\r\n\r\nmkColor :: Char -> Maybe Color\r\nmkColor c = case c of\r\n 'R' -> Just Red\r\n 'G' -> Just Green\r\n 'B' -> Just Blue\r\n _ -> Nothing\r\n\r\nlookDistinct :: Color -> Color -> Bool\r\nlookDistinct a b =\r\n case (a, b) of\r\n (Red, Red) -> False\r\n (Red, _) -> True\r\n (_, Red) -> True\r\n (_, _) -> False\r\n\r\nreadColors :: IO (Maybe [Color])\r\nreadColors = do\r\n l <- getLine\r\n return (sequence $ map mkColor l)\r\n\r\nrowsLookNondistinct :: [Color] -> [Color] -> Bool\r\nrowsLookNondistinct xs ys = all (not . (uncurry lookDistinct)) pairs\r\n where pairs = zip xs ys\r\n\r\nputNondistinct :: [Color] -> [Color] -> IO ()\r\nputNondistinct xs ys = case rowsLookNondistinct xs ys of\r\n True -> putStrLn \"YES\"\r\n False -> putStrLn \"NO\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n tests <- readLn\r\n replicateM tests $ do\r\n -- unused length of lists\r\n _ <- getLine\r\n firstRow <- readColors\r\n secondRow <- readColors\r\n case (firstRow, secondRow) of\r\n (Just xs, Just ys) -> putNondistinct xs ys\r\n _ -> putStrLn \"Invalid Input!\"\r\n return ()"}, {"source_code": "{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\nimport Data.Char\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- getNext\r\n b <- getNext\r\n let\r\n good x y = (x == 'R' && y == 'R') || (x /= 'R' && y /= 'R')\r\n res = foldl' (\\b (x, y) -> (&&) b (good x y)) True (zip (P.unpack a) (P.unpack b))\r\n pure . str $ if res then \"YES\\n\" else \"NO\\n\"\r\n"}], "negative_code": [], "src_uid": "86a2e0854f9faf0b119d0d5e4b8fe952"} {"source_code": "main = putStr . maybe \"-1\" (unwords . map show) . (\\[a, b] -> solve a b) . map read . words =<< getLine\n\nsolve n k = case gen (k - 1 :: Int) 0 n 1 of\n (0, xs) -> Just $ xs []\n _ -> Nothing\n\ngen k l r lo\n | k <= 0 || d <= 1 = (k, (take d [lo..] ++))\n | otherwise = (k2, xs . ys)\n where\n d = r - l\n m = (r + l) `quot` 2\n (k1, xs) = gen (k - 2) l m (lo + r - m)\n (k2, ys) = gen k1 m r lo", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.List.Split as T\nimport Control.Monad.State\n\n-- import Debug.Trace\n\ngo :: Int -> Int -> Int -> Maybe [Int]\ngo a b k \n | k == 0 = Just [a..b]\n | k `mod` 2 == 1 = Nothing\n | a == b = Nothing\n | otherwise = do\n let k' = k - 2\n let kl = (div k' 2) + (mod (div k' 2) 2)\n let kr = k' - kl\n let m = (div (a + b) 2)\n l <- go a m kl\n r <- go (m + 1) b kr\n return $ r ++ l\n\nsolve :: Int -> Int -> [Int]\nsolve n k =\n case go 1 n (k - 1) of\n Just l -> l\n Nothing -> [-1]\n\nisSorted :: [Int] -> Bool\nisSorted [] = True\nisSorted [x] = True\nisSorted (x1:x2:xs) = (x1 <= x2) && (isSorted (x2:xs))\n\nverify :: [Int] -> State Int ()\nverify [x] = get >>= put . (+ 1)\nverify xs = do\n count <- get\n put $ count + 1\n case isSorted xs of\n True -> return ()\n False -> do\n let m = (div (length xs) 2)\n let xl = take m xs\n let xr = drop m xs\n verify xl\n verify xr\n \nmain :: IO ()\nmain = do\n line <- getContents\n case map (read :: String -> Int) . words $ line of\n [n, k] -> putStrLn $ unwords $ map show $ solve n k\n _ -> error \"\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.List.Split as T\n\ngo :: Int -> Int -> Int -> Maybe [Int]\ngo a b k \n | k == 0 = Just [a..b]\n | k < 0 = Nothing\n | k `mod` 2 == 1 = Nothing\n | a == b = Nothing\n | otherwise = do\n let k' = k - 2\n let kl = (div k' 2) - (mod (div k' 2) 2)\n let kr = k' - kl\n let m = (div (a + b + 1) 2)\n l <- go a m kl\n r <- go (m + 1) b kr\n return $ r ++ l\n\nsolve :: Int -> Int -> [Int]\nsolve n k =\n case go 1 n (k - 1) of\n Just l -> l\n Nothing -> [-1]\n \nmain :: IO ()\nmain = do\n line <- getContents\n case map (read :: String -> Int) . words $ line of\n [n, k] -> putStrLn $ unwords $ map show $ solve n k\n _ -> error \"\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.List.Split as T\n\ngo :: Int -> Int -> Int -> Maybe [Int]\ngo a b k \n | k == 0 = Just [a..b]\n | k `mod` 2 == 1 = Nothing\n | a == b = Nothing\n | otherwise = do\n let k' = k - 2\n let kl = (div k' 2) + (mod (div k' 2) 2)\n let kr = k' - kl\n let m = (div (a + b + 1) 2)\n l <- go a m kl\n r <- go (m + 1) b kr\n return $ r ++ l\n\nsolve :: Int -> Int -> [Int]\nsolve n k =\n case go 1 n (k - 1) of\n Just l -> l\n Nothing -> [-1]\n \nmain :: IO ()\nmain = do\n line <- getContents\n case map (read :: String -> Int) . words $ line of\n [n, k] -> putStrLn $ unwords $ map show $ solve n k\n _ -> error \"\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.List.Split as T\n\ngo :: Int -> Int -> Int -> Maybe [Int]\ngo a b k \n | k == 0 = Just [a..b]\n | k `mod` 2 == 1 = Nothing\n | a == b = Nothing\n | otherwise = do\n let k' = k - 2\n let kl = (div k' 2) - (mod (div k' 2) 2)\n let kr = k' - kl\n let m = (div (a + b + 1) 2)\n l <- go a m kl\n r <- go (m + 1) b kr\n return $ r ++ l\n\nsolve :: Int -> Int -> [Int]\nsolve n k =\n case go 1 n (k - 1) of\n Just l -> l\n Nothing -> [-1]\n \nmain :: IO ()\nmain = do\n line <- getContents\n case map (read :: String -> Int) . words $ line of\n [n, k] -> putStrLn $ unwords $ map show $ solve n k\n _ -> error \"\"\n"}], "src_uid": "55ffdab213ed5b00d2ff69f0f91c0c74"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nqs :: String -> [Int]\nqs = let\n step v '0' = v + if v >= 0 then 1 else 0\n step _ '1' = 0\n step _ _ = error \"bad input\"\n in tail . scanl step (0-1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n, m] <- readInts\n s <- P.unpack <$> readLine\n let\n q1 = qs s\n q2 = reverse $ qs $ reverse s\n ok x = 0 <= x && x <= m\n ans = do\n (x, y) <- zip q1 q2\n pure $ if (ok x || ok y) && (x /= y || x == 0)\n then '1'\n else '0'\n lift $ putStrLn ans\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n, m] <- getInts\n as <- take n . C.unpack <$> C.getLine\n let result = func False (map (\\s -> (head s, length s)) $ group as)\n f c\n | 2 * m <= c = replicate m '1' ++ replicate (c - 2 * m) '0' ++ replicate m '1'\n | odd c = replicate (c `div` 2) '1' ++ ['0'] ++ replicate (c `div` 2) '1'\n | otherwise = replicate c '1'\n func _ [] = []\n func True (('0', c) : []) = replicate (min c m) '1' ++ replicate (c - min c m) '0'\n func True (('0', c) : xs) = f c ++ func False xs\n func False (('0', c) : []) = replicate c '0'\n func False (('0', c) : xs) = replicate (c - min c m) '0' ++ replicate (min c m) '1' ++ func False xs\n func _ (('1', c) : xs) = replicate c '1' ++ func True xs\n return $ string7 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "9c9befb908f24a0d7481b75bfdd5780b"} {"source_code": "module Main where\n\nimport Data.List (sortOn, foldl', maximumBy)\nimport Data.Ord (comparing)\nimport Data.Int (Int64)\n\nmain :: IO ()\nmain = interact $ solve . tail . words\n\nsolve :: [String] -> String\nsolve inputs = showSolution $ bestSolution solutions\n where\n postcard:envelopes = toEnvelopes 0 inputs\n sortedEnvelopes = sortOn square $ filter (`contain` postcard) envelopes\n solutions = foldl' solve0 [Solution 0 postcard []] sortedEnvelopes\n showSolution s = unlines [ show $ len s, unwords . map show . reverse . path $ s]\n\nbestSolution :: [Solution] -> Solution\nbestSolution = maximumBy (comparing len)\n\nsolve0 :: [Solution] -> Enverlope -> [Solution]\nsolve0 solutions envelop = case filter (contain envelop . env) solutions of\n [] -> solutions\n ss -> let Solution l _ p = bestSolution ss in Solution (l + 1) envelop (ei envelop:p):solutions\n\ncontain :: Enverlope -> Enverlope -> Bool\ncontain (Enverlope w1 h1 _) (Enverlope w2 h2 _) = w2 < w1 && h2 < h1\n\nsquare :: Enverlope -> Int64\nsquare (Enverlope w h _) = w * h\n\ntoEnvelopes :: Int -> [String] -> [Enverlope]\ntoEnvelopes _ [] = []\ntoEnvelopes i (w:h:rest) = Enverlope (read w) (read h) i : toEnvelopes (i + 1) rest\n\ndata Solution = Solution {\n len :: !Int,\n env :: Enverlope,\n path :: [Int]\n} deriving (Show)\n\ndata Enverlope = Enverlope {\n ew :: !Int64,\n eh :: !Int64,\n ei :: !Int\n } deriving (Show, Eq, Ord)", "positive_code": [{"source_code": "import Data.List\nimport Data.Array.Unboxed\nimport Data.Function (on)\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, w0, h0] : xs) = printShit . mainSALF . majiqSort . bigEnuff . wiffIndices $ xs\n where\n wiffIndices = flip (zipWith (\\[w, h] i -> (w, h, i))) [1..]\n bigEnuff = filter $ \\(w, h, _) -> w > w0 && h > h0\n majiqSort = sortBy (compare `on` \\(w, h, _) -> (w, -h))\n inf = 2147483647\n mainSALF = mapAccumL sALFSHIT (listArray (0, n) (repeat inf) :: UArray Int Int, 0)\n\n sALFSHIT (barr, maxl) (_, h, i) = ((barr // [(idx, h)], max maxl idx), (idx, i))\n where\n idx = bs 1 1 (maxl + 1)\n bs ans l r\n | l > r = ans\n | barr ! m >= h = bs m l (m-1)\n | otherwise = bs ans (m+1) r\n where m = (l + r) `div` 2\n\n printShit ((_, maxl), ls) = snd . foldl' folder (maxl, []) $ reverse ls\n where folder (curl, acc) (lvl, i) = if curl == lvl then (curl-1, i : acc) else (curl, acc)\n\n\nmain :: IO ()\nmain = interact $ output . solve . map (map read . words) . lines\n where output xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\nimport Data.Array\nimport Control.Monad\nimport List\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nrepeatM a = mapM (const a) (repeat 1)\nrepeatMn a n = mapM (const a) [1..n]\nreadm::(Read a) => State String a\nreadm = State (head . reads)\nreadchar = State (\\s->(head s,tail s))\nreadall = State (,\"\")\n\nrunRead x s = fst $ runState x s\n\nsolve::[Int]->[Int]->[Int]->[(Int,(Int,Int),[Int])]->[Int]\nsolve [] _ _ ps = tail chain where (_,_,chain) = head ps\nsolve (w:ws) (h:hs) (n:ns) ps = solve ws hs ns $ (x+1,(w,h),n:chain):ps where\n\t(x,_,chain) = maximum $ (0,0,[]):[(y,head c,c) | (y,(w',h'),c) <- ps, w'>w && h'>h]\n\n\nmain = reader >>= writer . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\tn <- readm\n\tw <- readm\n\th <- readm\n\tsizes <- mapM (\\i-> (liftM3 (,,) readm readm (return i))) [1..n]\n\tlet (ws,hs,ns)::([Int],[Int],[Int]) = unzip3 . sort $ sizes\n\tlet solution = solve (reverse $ w:ws) (reverse $ h:hs) (reverse $ 0:ns) []\n\treturn (show (length solution) ++ \"\\n\" ++ (unwords . map show $ solution))\n\t--return (unlines . map unwords $ map (map show) [ws,hs,ns])\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\npickBestChain chain =\n foldr (\\(j, _, _, curr, currChain) (best, bestChain) ->\n if curr > best\n then (curr, currChain)\n else (best, bestChain)\n ) (0, []) chain\n\n\nmain = do\n [n, w0, h0] <- ( map read . words ) `liftM` getLine :: IO [Int]\n\n envs <- liftM (filter (\\(_, w, h) -> w > w0 && h > h0)) $ forM [1..n] $ \\i -> do\n [w, h] <- (map read . words ) `liftM` getLine\n return (i, w, h)\n\n --putStrLn $ show envs\n\n let chain = map (\\(i, w, h) ->\n let (best, bestChain) = pickBestChain $ filter (\\(_, w1, h1, _, _) -> w < w1 && h < h1) chain\n in (i, w, h, best+1, i:bestChain)\n ) envs\n (best, bestChain) = pickBestChain chain\n\n --putStrLn $ show chain\n putStrLn $ show best\n putStrLn $ unwords $ map show bestChain\n"}, {"source_code": "import Data.List\nimport Data.Array.Unboxed\nimport Data.Function (on)\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.ST as ST\nimport qualified Data.Array.Unboxed as U\nimport Data.STRef\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, w0, h0] : xs) = printShit . mainSALF . majiqSort . bigEnuff . wiffIndices $ xs\n where\n wiffIndices = flip (zipWith (\\[w, h] i -> (w, h, i))) [1..]\n bigEnuff = filter $ \\(w, h, _) -> w > w0 && h > h0\n majiqSort = sortBy (compare `on` \\(w, h, _) -> (w, -h))\n\n mainSALF = mapAccumL sALFSHIT (listArray (0, n) (repeat 2147483647) :: UArray Int Int, 0)\n\n sALFSHIT (barr, maxl) (_, h, i) = ((barr // [(idx, h)], max maxl idx), (idx, i))\n where\n idx = bs 1 1 (maxl + 1)\n bs ans l r\n | l > r = ans\n | barr ! m >= h = bs m l (m-1)\n | otherwise = bs ans (m+1) r\n where m = (l + r) `div` 2\n\n printShit ((_, maxl), ls) = snd . foldr folder (maxl, []) $ ls\n where folder (lvl, i) (curl, acc) = if curl == lvl then (curl-1, i : acc) else (curl, acc)\n\n\nmain :: IO ()\nmain = interact $ output . solve . map (map read . words) . lines\n where output xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Function (on)\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, w0, h0] : xs) = printShit . mainSALF . majiqSort . bigEnuff . wiffIndices $ xs\n where\n wiffIndices = flip (zipWith (\\[w, h] i -> (w, h, i))) [1..]\n bigEnuff = filter $ \\(w, h, _) -> w > w0 && h > h0\n majiqSort = sortBy (compare `on` \\(w, h, _) -> (w, -h))\n inf = 2147483647\n mainSALF = mapAccumL sALFSHIT (listArray (0, n) (repeat inf), 0)\n\n sALFSHIT (barr, maxl) (_, h, i) = ((barr // [(idx, h)], max maxl idx), (idx, i))\n where\n idx = bs 1 1 (maxl + 1)\n bs ans l r\n | l > r = ans\n | barr ! m >= h = bs m l (m-1)\n | otherwise = bs ans (m+1) r\n where m = (l + r) `div` 2\n\n printShit ((_, maxl), ls) = snd $ foldr folder (maxl, []) ls\n where folder (lvl, i) (curl, acc) = if curl == lvl then (curl-1, i : acc) else (curl, acc)\n\n\nmain :: IO ()\nmain = interact $ output . solve . map (map read . words) . lines\n where output xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n"}, {"source_code": "import Data.List\nimport Data.Array.Unboxed\nimport Data.Function (on)\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.ST as ST\nimport qualified Data.Array.Unboxed as U\nimport Data.STRef\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, w0, h0] : xs) = printShit . mainSALF . majiqSort . bigEnuff . wiffIndices $ xs\n where\n wiffIndices = flip (zipWith (\\[w, h] i -> (w, h, i))) [1..]\n bigEnuff = filter $ \\(w, h, _) -> w > w0 && h > h0\n majiqSort = sortBy (compare `on` \\(w, h, _) -> (w, -h))\n\n {-\n mainSALF = mapAccumL sALFSHIT (listArray (0, n) (repeat 2147483647) :: UArray Int Int, 0)\n\n sALFSHIT (barr, maxl) (_, h, i) = ((barr // [(idx, h)], max maxl idx), (idx, i))\n where\n idx = bs 1 1 (maxl + 1)\n bs ans l r\n | l > r = ans\n | barr ! m >= h = bs m l (m-1)\n | otherwise = bs ans (m+1) r\n where m = (l + r) `div` 2\n -}\n\n mainSALF envs = runST $ do\n arr <- ST.thaw (U.listArray (0, n) (repeat 2147483647) :: U.UArray Int Int) :: ST st (ST.STUArray st Int Int)\n\n let bs v ans l r\n | l > r = return ans\n | otherwise = do\n let m = (l + r) `div` 2\n mVal <- ST.readArray arr m\n if mVal >= v then bs v m l (m-1) else bs v ans (m+1) r\n\n maxl <- newSTRef (0 :: Int)\n ls <- forM envs $ \\(_, h, i) -> do\n maxl' <- readSTRef maxl\n idx <- bs h 1 1 (maxl' + 1)\n ST.writeArray arr idx h\n modifySTRef maxl (max idx)\n return (idx, i)\n\n maxl' <- readSTRef maxl\n return ((0, maxl'), ls)\n\n printShit ((_, maxl), ls) = snd . foldr folder (maxl, []) $ ls\n where folder (lvl, i) (curl, acc) = if curl == lvl then (curl-1, i : acc) else (curl, acc)\n\n\nmain :: IO ()\nmain = interact $ output . solve . map (map read . words) . lines\n where output xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Data.Function (on)\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, w0, h0] : xs) = printShit . mainSALF . majiqSort . bigEnuff . wiffIndices $ xs\n where\n wiffIndices = flip (zipWith (\\[w, h] i -> (w, h, i))) [1..]\n bigEnuff = filter $ \\(w, h, _) -> w >= w0 && h >= h0\n majiqSort = sortBy (compare `on` \\(w, h, _) -> (w, -h))\n mainSALF = mapAccumL sALFSHIT (listArray (0, n) (repeat $ 10 ^ 9), 0)\n\n sALFSHIT (barr, maxl) (_, h, i) = ((barr // [(idx, h)], max maxl idx), (idx, i))\n where\n idx = bs 1 1 (maxl + 1)\n bs ans l r\n | l > r = ans\n | barr ! m > h = bs m l (m-1)\n | otherwise = bs ans (m+1) r\n where m = (l + r) `div` 2\n\n printShit ((_, maxl), ls) = snd $ foldr folder (maxl, []) ls\n where folder (lvl, i) (curl, acc) = if curl == lvl then (curl-1, i : acc) else (curl, acc)\n\n\nmain :: IO ()\nmain = interact $ output . solve . map (map read . words) . lines\n where output xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n"}, {"source_code": "import Data.List\nimport Data.Array hiding (indices)\nimport Data.Function (on)\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, h0, w0] : xs) =\n indices . foldl' folder initArr . majiqSort . bigEnough . pairIndex $ xs\n where\n pairIndex = zipWith (\\i [h, w] -> (h, w, i)) [1..]\n bigEnough = filter (\\(h, w, _) -> h > h0 && w > w0)\n majiqSort = sortBy (compare `on` (\\(h, w, _) -> (h, -w)))\n indices = reverse . takeWhile (/= -1) . map snd . elems\n\n initArr = listArray (1, n) (repeat (10 ^ 8, -1)) :: Array Int (Int, Int)\n folder arr (_, w, i) = arr // [(bSearch 1 1 n, (w, i))]\n where bSearch ans l r\n | l > r = ans\n | fst (arr ! m) >= w = bSearch m l (m - 1)\n | otherwise = bSearch ans (m + 1) r\n where m = (l + r) `div` 2\n\n\nmain :: IO ()\nmain = do\n input <- getContents\n let ans = solve . map (map read . words) . lines $ input\n print $ length ans\n putStrLn $ unwords (map show ans)\n"}, {"source_code": "import Data.List\nimport Data.Array hiding (indices)\nimport Data.Function (on)\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, h0, w0] : xs) =\n indices . foldl' folder initArr . majiqSort . bigEnough . pairIndex $ xs\n where\n pairIndex = zipWith (\\i [h, w] -> (h, w, i)) [1..]\n bigEnough = filter (\\(h, w, _) -> h > h0 && w > w0)\n majiqSort = sortBy (compare `on` (\\(h, w, _) -> (h, -w)))\n indices = takeWhile (/= -1) . map snd . elems\n\n initArr = listArray (1, n) (repeat (10 ^ 8, -1)) :: Array Int (Int, Int)\n folder arr (_, w, i) = arr // [(bSearch 1 1 n, (w, i))]\n where bSearch ans l r\n | l > r = ans\n | fst (arr ! m) >= w = bSearch m l (m - 1)\n | otherwise = bSearch ans (m + 1) r\n where m = (l + r) `div` 2\n\n\nmain :: IO ()\nmain = do\n input <- getContents\n let ans = solve . map (map read . words) . lines $ input\n print $ length ans\n putStrLn $ unwords (map show ans)\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Function (on)\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, w0, h0] : xs) = printShit . mainSALF . majiqSort . bigEnuff . wiffIndices $ xs\n where\n wiffIndices = flip (zipWith (\\[w, h] i -> (w, h, i))) [1..]\n bigEnuff = filter $ \\(w, h, _) -> w >= w0 && h >= h0\n majiqSort = sortBy (compare `on` \\(w, h, _) -> (w, -h))\n inf = 2147483647\n mainSALF = mapAccumL sALFSHIT (listArray (0, n) (repeat inf), 0)\n\n sALFSHIT (barr, maxl) (_, h, i) = ((barr // [(idx, h)], max maxl idx), (idx, i))\n where\n idx = bs 1 1 (maxl + 1)\n bs ans l r\n | l > r = ans\n | barr ! m >= h = bs m l (m-1)\n | otherwise = bs ans (m+1) r\n where m = (l + r) `div` 2\n\n printShit ((_, maxl), ls) = snd $ foldr folder (maxl, []) ls\n where folder (lvl, i) (curl, acc) = if curl == lvl then (curl-1, i : acc) else (curl, acc)\n\n\nmain :: IO ()\nmain = interact $ output . solve . map (map read . words) . lines\n where output xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n"}, {"source_code": "module Main where\n\nimport Data.List (sortOn, foldl', maximumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = interact $ solve . tail . words\n\nsolve :: [String] -> String\nsolve inputs = showSolution $ bestSolution solutions\n where\n postcard:envelopes = toEnvelopes 0 inputs\n sortedEnvelopes = sortOn square $ filter (`contain` postcard) envelopes\n solutions = foldl' solve0 [Solution 0 postcard []] sortedEnvelopes\n showSolution s = unlines [ show $ len s, unwords . map show . reverse . path $ s]\n\nbestSolution :: [Solution] -> Solution\nbestSolution = maximumBy (comparing len)\n\nsolve0 :: [Solution] -> Enverlope -> [Solution]\nsolve0 solutions envelop = case filter (contain envelop . env) solutions of\n [] -> solutions\n ss -> let Solution l _ p = bestSolution ss in Solution (l + 1) envelop (ei envelop:p):solutions\n\ncontain :: Enverlope -> Enverlope -> Bool\ncontain (Enverlope w1 h1 _) (Enverlope w2 h2 _) = w2 < w1 && h2 < h1\n\nsquare :: Enverlope -> Int\nsquare (Enverlope w h _) = w * h\n\ntoEnvelopes :: Int -> [String] -> [Enverlope]\ntoEnvelopes _ [] = []\ntoEnvelopes i (w:h:rest) = Enverlope (read w) (read h) i : toEnvelopes (i + 1) rest\n\ndata Solution = Solution {\n len :: !Int,\n env :: Enverlope,\n path :: [Int]\n} deriving (Show)\n\ndata Enverlope = Enverlope {\n ew :: !Int,\n eh :: !Int,\n ei :: !Int\n } deriving (Show, Eq, Ord)"}], "src_uid": "6f88e3f4c8a8a444d44e58505a750d3e"} {"source_code": "import System.IO \nimport Control.Monad\nimport qualified Data.Map as M\nimport Data.Array\n\n-- LOGIC\ngetResults input requests = processRequests l requests tree where (tree, l) = buildTree input candies asCandy 0\n\nprocessRequests _ [] _ = []\nprocessRequests length ((l, r):rs) tree = result' : processRequests length rs tree\n where result = queryTree tree 1 length l r candies\n result' = result `div` 10\n\ndata Tree a = Leaf a | Tree a (Tree a) (Tree a)\nnodeValue (Leaf v) = v\nnodeValue (Tree v _ _) = v\n\nmyLog x = myLog' 1 where myLog' r = if r <= x then myLog' (r*2) else r\n\nasCandy v = v\ncandies l r = l + r\nmiddle l r = (r - l) `div` 2 + l\n\nshowTree (Leaf v) = show v\nshowTree (Tree v left right) = showTree left ++ \" + \" ++ showTree right ++ \" -> \" ++ show v \n\nbuildTree input add return empty = (buildTree' 1 length', length') \n where\n normalLength = length input\n length' = myLog normalLength\n buildTree' lb rb | lb == rb = Leaf . return $ if normalLength >= lb then input ! lb else empty\n buildTree' lb rb = Tree root left right\n where\n root = add (nodeValue left) (nodeValue right)\n left = buildTree' lb m\n right = buildTree' (m + 1) rb\n m = middle lb rb\n \nqueryTree tree clb crb lb rb _ \n | clb == lb && crb == rb = nodeValue tree\nqueryTree (Tree _ left right) clb crb lb rb add \n | rb <= m = queryTree left clb m lb rb add\n | m < lb = queryTree right (m + 1) crb lb rb add\n | otherwise = add\n (queryTree left clb m lb m add)\n (queryTree right (m + 1) crb (m + 1) rb add)\n where m = middle clb crb \n \n-- IO\n\nreadPair input = (list !! 0, list !! 1) where list = map (\\x -> (read x :: Int)) (words input)\n \nmain = do\n len <- getLine\n let l = read len :: Int\n sequence <- getLine\n let s = take l $ map (\\x -> read x :: Int) (words sequence)\n requests <- getLine\n rs <- replicateM (read requests :: Int) getLine\n let r = map (\\x -> readPair x) rs\n mapM (putStrLn . show) $ getResults (listArray (1, length s) s) r\n ", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Sequence as S\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\noutput :: Show a => [a] -> IO ()\noutput = putStrLn <$> unwords <$> map show\n\nstep :: (Int, [(Int,Int)]) -> Int -> (Int, [(Int,Int)])\nstep (d, xcs) d2 = (d2, zipWith f xcs (drop d xcs)) where\n f (x1,c1) (x2,c2) = (x,c) where\n x = (x1 + x2) `mod` 10\n c = c1 + c2 + (if x1 + x2 >= 10 then 1 else 0)\n\nmakedb n s = M.fromList [(d, S.fromList db') | (d,db') <- scanl' step s0 powers] where\n powers = takeWhile (<= n) $ map (2^) [1..]\n s0 = (1, map (,0) s)\n\nmain = do\n [n] <- input\n s <- input :: IO [Int]\n let db = makedb n s\n [q] <- input\n replicateM_ q $ do\n [l,r] <- input :: IO [Int]\n let Just db' = M.lookup (r-l+1) db\n let Just (_,c) = S.lookup (l-1) db'\n print c\n"}], "negative_code": [{"source_code": "import System.IO \nimport Control.Monad\nimport qualified Data.Map as M\n-- import Debug.Trace\nimport Data.Array\n\n-- LOGIC\ngetResults :: (Array Int Int) -> [(Int, Int)] -> [Int]\ngetResults input requests = processRequests (length input) requests tree where tree = buildTree input candies asCandy 0\n\nprocessRequests :: Int -> [(Int, Int)] -> Tree (Int, Int) -> [Int]\nprocessRequests _ [] _ = []\nprocessRequests length ((l, r):rs) tree = result : processRequests length rs tree\n where (_, result) = queryTree tree 1 length l r candies\n\ndata Tree a = Leaf a | Tree a (Tree a) (Tree a)\nnodeValue (Leaf v) = v\nnodeValue (Tree v _ _) = v\n\nmyLog x = myLog' 1 where myLog' r = if r < x then myLog' (r*2) else r\n\nasCandy :: Int -> (Int, Int)\nasCandy v = (v, 0)\ncandies (lv, lr) (rv, rr) = (s `mod` 10, s `div` 10 + lr + rr) where s = lv + rv\n\nbuildTree :: (Array Int a) -> (b -> b -> b) -> (a -> b) -> a -> Tree b \nbuildTree input add return empty = buildTree' 1 length' \n where\n normalLength = length input\n length' = myLog normalLength\n buildTree' lb rb | lb == rb = Leaf . return $ if normalLength >= lb then input ! lb else empty\n buildTree' lb rb = Tree root left right\n where\n root = add (nodeValue left) (nodeValue right)\n left = buildTree' lb ((rb - lb) `div` 2 + lb)\n right = buildTree' ((rb - lb) `div` 2 + lb + 1) rb\n \nqueryTree :: Tree a -> Int -> Int -> Int -> Int -> (a -> a -> a) -> a\nqueryTree tree clb crb lb rb _ \n | clb == lb && crb == rb = nodeValue tree\nqueryTree (Tree _ left right) clb crb lb rb add \n | m < lb = queryTree right (m+1) crb lb rb add\n | rb <= m = queryTree left clb m lb rb add\n | otherwise = add (queryTree left clb m lb m add) (queryTree right (m + 1) crb (m + 1) rb add)\n where m = (crb - clb) `div` 2 + clb\nqueryTree tree clb crb lb rb _ = nodeValue tree\n\n-- IO\n\nreadPair input = (list !! 0, list !! 1) where list = map (\\x -> (read x :: Int)) (words input)\n \nmain = do\n len <- getLine\n let l = read len :: Int\n sequence <- getLine\n let s = take l $ map (\\x -> read x :: Int) (words sequence)\n requests <- getLine\n rs <- replicateM (read requests :: Int) getLine\n let r = map (\\x -> readPair x) rs\n mapM (putStrLn . show) $ getResults (listArray (1, length s) s) r"}, {"source_code": "import System.IO \nimport Control.Monad\nimport qualified Data.Map as M\n-- import Debug.Trace\nimport Data.Array\n\n-- LOGIC\nvaluePrice :: Int -> Int -> (Int, Int)\nvaluePrice l r = (sum `mod` 10, sum `div` 10) where sum = l + r\n\n--buildTree :: M.Map (Int, Int) (Int, Int) -> Int -> Int -> Int -> [Int] -> (M.Map (Int, Int) (Int, Int), (Int, Int))\nbuildTree c _ _ 1 _ = (c, (0, 0))\nbuildTree c l _ 2 s = (c, valuePrice (s!l) (s!(l+1)))\nbuildTree c lb rb l s =\n (c'', (v, p + pl + pr))\n where l' = l `div` 2\n (c' , (vl, pl)) = buildTreeCaching c lb (rb - l') l' s\n (c'', (vr, pr)) = buildTreeCaching c' (lb + l') rb l' s\n (v, p) = valuePrice vl vr\n \nbuildTreeCaching :: M.Map (Int, Int) (Int, Int) -> Int -> Int -> Int -> Array Int Int -> (M.Map (Int, Int) (Int, Int), (Int, Int)) \nbuildTreeCaching c lb rb l s = \n case M.lookup (lb, rb) c of\n (Just v) -> (c, v)\n Nothing -> (M.insert (lb, rb) r c', r) where (c', r) = buildTree c lb rb l s \n \n\ngetResult c lb rb l s = (c', p) where (c', (_, p)) = buildTreeCaching c lb rb l s\n\n\n-- getResults :: M.Map (Int, Int) (Int, Int) -> [Int] -> [(Int, Int)] -> [Int]\ngetResults c ar [] = []\ngetResults c ar ((l, r):rs) = result : (getResults c' ar rs)\n where \n length = r - l + 1\n (c', result) = getResult c l r length ar\n\n\n-- IO\n\nreadPair input = (list !! 0, list !! 1) where list = map (\\x -> (read x :: Int) - 1) (words input)\n \nmain = do\n len <- getLine\n let l = read len :: Int\n sequence <- getLine\n let s = take l $ map (\\x -> read x :: Int) (words sequence)\n requests <- getLine\n rs <- replicateM (read requests :: Int) getLine\n let r = map (\\x -> readPair x) rs\n mapM (putStrLn . show) $ getResults M.empty (listArray (0, length s - 1) s) (reverse r)"}, {"source_code": "import System.IO \nimport Control.Monad\nimport qualified Data.Map as M\n-- import Debug.Trace\nimport Data.Array\n\n-- LOGIC\ngetResults input requests = processRequests (length input) requests tree where tree = buildTree input candies asCandy 0\n\nprocessRequests _ [] _ = []\nprocessRequests length ((l, r):rs) tree = result' : processRequests length rs tree\n where result = queryTree tree 1 length l r candies\n result' = result `div` 10\n\ndata Tree a = Leaf a | Tree a (Tree a) (Tree a)\nnodeValue (Leaf v) = v\nnodeValue (Tree v _ _) = v\n\nmyLog x = myLog' 1 where myLog' r = if r < x then myLog' (r*2) else r\n\nasCandy v = v\ncandies l r = l + r\n\nbuildTree input add return empty = buildTree' 1 length' \n where\n normalLength = length input\n length' = myLog normalLength\n buildTree' lb rb | lb == rb = Leaf . return $ if normalLength >= lb then input ! lb else empty\n buildTree' lb rb = Tree root left right\n where\n root = add (nodeValue left) (nodeValue right)\n left = buildTree' lb m\n right = buildTree' (m + 1) rb\n m = (rb - lb) `div` 2 + lb\n \nqueryTree tree clb crb lb rb _ \n | clb == lb && crb == rb = nodeValue tree\nqueryTree (Tree _ left right) clb crb lb rb add \n | m < lb = queryTree right (m+1) crb lb rb add\n | rb <= m = queryTree left clb m lb rb add\n | otherwise = add (queryTree left clb m lb m add)\n (queryTree right (m + 1) crb (m + 1) rb add)\n where m = (crb - clb) `div` 2 + clb\n\n-- IO\n\nreadPair input = (list !! 0, list !! 1) where list = map (\\x -> (read x :: Int)) (words input)\n \nmain = do\n len <- getLine\n let l = read len :: Int\n sequence <- getLine\n let s = take l $ map (\\x -> read x :: Int) (words sequence)\n requests <- getLine\n rs <- replicateM (read requests :: Int) getLine\n let r = map (\\x -> readPair x) rs\n mapM (putStrLn . show) $ getResults (listArray (1, length s) s) r"}, {"source_code": "import System.IO \nimport Control.Monad\nimport qualified Data.Map as M\nimport Data.Array\n\n-- LOGIC\ngetResults input requests = processRequests l requests tree where (tree, l) = buildTree input candies asCandy 0\n\nprocessRequests _ [] _ = []\nprocessRequests length ((l, r):rs) tree = result : processRequests length rs tree\n where result = queryTree tree 1 length l r candies\n result' = result `div` 10\n\ndata Tree a = Leaf a | Tree a (Tree a) (Tree a)\nnodeValue (Leaf v) = v\nnodeValue (Tree v _ _) = v\n\nmyLog x = myLog' 1 where myLog' r = if r <= x then myLog' (r*2) else r\n\nasCandy v = v\ncandies l r = l + r\nmiddle l r = (r - l) `div` 2 + l\n\nshowTree (Leaf v) = show v\nshowTree (Tree v left right) = showTree left ++ \" + \" ++ showTree right ++ \" -> \" ++ show v \n\nbuildTree input add return empty = (buildTree' 1 length', length') \n where\n normalLength = length input\n length' = myLog normalLength\n buildTree' lb rb | lb == rb = Leaf . return $ if normalLength >= lb then input ! lb else empty\n buildTree' lb rb = Tree root left right\n where\n root = add (nodeValue left) (nodeValue right)\n left = buildTree' lb m\n right = buildTree' (m + 1) rb\n m = middle lb rb\n \nqueryTree tree clb crb lb rb _ \n | clb == lb && crb == rb = nodeValue tree\nqueryTree (Tree _ left right) clb crb lb rb add \n | rb <= m = queryTree left clb m lb rb add\n | m < lb = queryTree right (m + 1) crb lb rb add\n | otherwise = add\n (queryTree left clb m lb m add)\n (queryTree right (m + 1) crb (m + 1) rb add)\n where m = middle clb crb \n \n-- IO\n\nreadPair input = (list !! 0, list !! 1) where list = map (\\x -> (read x :: Int)) (words input)\n \nmain = do\n len <- getLine\n let l = read len :: Int\n sequence <- getLine\n let s = take l $ map (\\x -> read x :: Int) (words sequence)\n requests <- getLine\n rs <- replicateM (read requests :: Int) getLine\n let r = map (\\x -> readPair x) rs\n mapM (putStrLn . show) $ getResults (listArray (1, length s) s) r"}], "src_uid": "2cd91be317328fec207da6773ead4541"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Tuple(swap)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nl2p :: [Int] -> (Int,Int)\nl2p (a:b:_) = (a,b)\nl2p _ = undefined\n\ndata UFState s = UFState { bounds :: (Int,Int)\n , parent :: STUArray s Int Int\n , rank :: STUArray s Int Int }\n\ninitUF :: (Int,Int) -> ST s (UFState s)\ninitUF b = UFState b <$> newListArray b (range b) <*> newArray b 0\n\nfindUF :: Int -> UFState s -> ST s Int\nfindUF k st = do\n i <- readArray (parent st) k\n if k == i then\n return i\n else do\n j <- findUF i st\n writeArray (parent st) k j\n return j\n\nmergeUF :: Int -> Int -> UFState s -> ST s ()\nmergeUF x y st = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n rx <- readArray (rank st) px\n ry <- readArray (rank st) py\n uncurry (writeArray (parent st)) $ if rx < ry then (px,py) else (py,px)\n when (rx == ry) $ writeArray (rank st) px (rx + 1)\n\nsameUF :: Int -> Int -> UFState s -> ST s Bool\nsameUF x y st = liftA2 (==) (findUF x st) (findUF y st)\n\nmain :: IO ()\nmain = do\n [n,m,_] <- readInts\n ss <- map (map readInt . B.words) . B.lines <$> B.getContents\n putStr $ unlines $ map show $ uncurry (solve n) $ first (map l2p) $ splitAt m ss\n\nwhenM :: Monad m => m Bool -> m () -> m ()\nwhenM m1 m2 = m1 >>= flip when m2\n\nsolve :: Int -> [(Int,Int)] -> [[Int]] -> [Int]\nsolve n es qs = doit where\n doit = runST $ do\n st <- initUF (1,n)\n forM_ es $ \\(x,y) -> mergeUF x y st\n ds <- newArray_ (1,n) :: ST s (STUArray s Int Int)\n forM_ [1..n] $ \\i -> \n whenM ((==i) <$> findUF i st) $ writeArray ds i (diameter i)\n let getD x = findUF x st >>= readArray ds\n putD x d = findUF x st >>= flip (writeArray ds) d\n go [] = return []\n go ([1,x]:_qs) = liftA2 (:) (getD x) (go _qs)\n go ([2,x,y]:_qs) = do\n whenM (not <$> sameUF x y st) $ do\n dx <- getD x\n dy <- getD y\n let rx = (dx + 1) `div` 2\n ry = (dy + 1) `div` 2\n dz = maximum [dx,dy,rx+ry+1]\n mergeUF x y st\n putD x dz\n go _qs\n go _ = undefined\n go qs\n g :: Array Int [Int]\n g = accumArray (flip (:)) [] (1,n) (es ++ map swap es)\n diameter = fst . f . snd . f where\n f = uncurry dfs . (((:[]).(,-1,0)) &&& (0,))\n dfs [] acc = acc :: (Int,Int)\n dfs ((v,pv,d):st) acc = dfs ((map (,v,d+1) $ filter (/=pv) (g ! v)) ++ st) (max (d,v) acc)\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\n\ndata UFState s = UFState { bounds :: (Int,Int)\n , parent :: STUArray s Int Int\n , rank :: STUArray s Int Int }\n\ninitUF :: (Int,Int) -> ST s (UFState s)\ninitUF b = UFState b <$> newListArray b (range b) <*> newArray b 0\n\nfindUF :: Int -> UFState s -> ST s Int\nfindUF k st = do\n i <- readArray (parent st) k\n if k == i then\n return i\n else do\n j <- findUF i st\n writeArray (parent st) k j\n return j\n\nmergeUF :: Int -> Int -> UFState s -> ST s ()\nmergeUF x y st = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n rx <- readArray (rank st) px\n ry <- readArray (rank st) py\n uncurry (writeArray (parent st)) $ if rx < ry then (px,py) else (py,px)\n when (rx == ry) $ writeArray (rank st) px (rx + 1)\n\nsameUF :: Int -> Int -> UFState s -> ST s Bool\nsameUF x y st = (==) <$> findUF x st <*> findUF y st\n\nrootUF :: Int -> UFState s -> ST s Bool\nrootUF x st = (x==) <$> findUF x st\n\nmain = do\n [n,m,_] <- readInts\n ss <- map (map readInt . B.words) . B.lines <$> B.getContents\n putStr $ unlines $ map show $ uncurry (solve n) $ first (map l2p) $ splitAt m ss\n\nsolve :: Int -> [(Int,Int)] -> [[Int]] -> [Int]\nsolve n es qs = doit where\n doit = runST $ do\n st <- initUF (1,n)\n forM_ es $ \\(x,y) -> mergeUF x y st\n ds <- newArray_ (1,n) :: ST s (STUArray s Int Int)\n forM_ [1..n] $ \\i -> do\n k <- findUF i st \n when (i==k) $ writeArray ds i (diameter i)\n let go [] = return []\n go ([1,x]:qs) = (:) <$> (findUF x st >>= readArray ds) <*> go qs\n go ([2,x,y]:qs) = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n dx <- readArray ds px\n dy <- readArray ds py\n let rx = (dx + 1) `div` 2\n ry = (dy + 1) `div` 2\n mergeUF px py st\n pz <- findUF x st\n writeArray ds pz (maximum [dx,dy,rx+ry+1])\n go qs\n go qs\n g :: Array Int [Int]\n g = accumArray (flip (:)) [] (1,n) (es ++ map swap es)\n diameter v = d where\n (_,v1) = dfs [(v,-1,0)] (0,v)\n (d,v2) = dfs [(v1,-1,0)] (0,v1)\n dfs [] acc = acc\n dfs ((v,pv,d):st) !acc = dfs st' (max (d,v) acc) where\n st' = [(v',v,d+1) | v' <- g ! v, v' /= pv ] ++ st\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\ndata UFState s = UFState { bounds :: (Int,Int)\n , parent :: STUArray s Int Int\n , rank :: STUArray s Int Int }\n\ninitUF :: (Int,Int) -> ST s (UFState s)\ninitUF b = UFState b <$> newListArray b (range b) <*> newArray b 0\n\nfindUF :: Int -> UFState s -> ST s Int\nfindUF k st = do\n i <- readArray (parent st) k\n if k == i then\n return i\n else do\n j <- findUF i st\n writeArray (parent st) k j\n return j\n\nmergeUF :: Int -> Int -> UFState s -> ST s ()\nmergeUF x y st = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n rx <- readArray (rank st) px\n ry <- readArray (rank st) py\n uncurry (writeArray (parent st)) $ if rx < ry then (px,py) else (py,px)\n when (rx == ry) $ writeArray (rank st) px (rx + 1)\n\nsameUF :: Int -> Int -> UFState s -> ST s Bool\nsameUF x y st = (==) <$> findUF x st <*> findUF y st\n\nrootUF :: Int -> UFState s -> ST s Bool\nrootUF x st = (x==) <$> findUF x st\n\nmain = do\n [n,m,_] <- readInts\n ss <- map (map readInt . B.words) . B.lines <$> B.getContents\n putStr $ unlines $ map show $ uncurry (solve n) $ first (map l2p) $ splitAt m ss\n\nsolve :: Int -> [(Int,Int)] -> [[Int]] -> [Int]\nsolve n es qs = doit where\n doit = runST $ do\n st <- initUF (1,n)\n forM_ es $ \\(x,y) -> mergeUF x y st\n ds <- newArray_ (1,n) :: ST s (STUArray s Int Int)\n forM_ [1..n] $ \\i -> do\n k <- findUF i st \n when (i==k) $ writeArray ds i (diameter i)\n let go [] = return []\n go ([1,x]:qs) = (:) <$> (findUF x st >>= readArray ds) <*> go qs\n go ([2,x,y]:qs) = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n dx <- readArray ds px\n dy <- readArray ds py\n let rx = (dx + 1) `div` 2\n ry = (dy + 1) `div` 2\n mergeUF px py st\n pz <- findUF x st\n writeArray ds pz (maximum [dx,dy,rx+ry+1])\n go qs\n go qs\n g :: Array Int [Int]\n g = accumArray (flip (:)) [] (1,n) (es ++ map swap es)\n diameter v = d where\n (_,v1) = dfs [(v,-1,0)] (0,v)\n (d,v2) = dfs [(v1,-1,0)] (0,v1)\n dfs [] acc = acc\n dfs ((v,pv,d):st) !acc = dfs st' (max (d,v) acc) where\n st' = [(v',v,d+1) | v' <- g ! v, v' /= pv ] ++ st\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\ndata UFState s = UFState { bounds :: (Int,Int)\n , parent :: STUArray s Int Int\n , rank :: STUArray s Int Int }\n\ninitUF :: (Int,Int) -> ST s (UFState s)\ninitUF b = UFState b <$> newListArray b (range b) <*> newArray b 0\n\nfindUF :: Int -> UFState s -> ST s Int\nfindUF k st = do\n i <- readArray (parent st) k\n if k == i then\n return i\n else do\n j <- findUF i st\n writeArray (parent st) k j\n return j\n\nmergeUF :: Int -> Int -> UFState s -> ST s ()\nmergeUF x y st = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n rx <- readArray (rank st) px\n ry <- readArray (rank st) py\n uncurry (writeArray (parent st)) $ if rx < ry then (px,py) else (py,px)\n when (rx == ry) $ writeArray (rank st) px (rx + 1)\n\nsameUF :: Int -> Int -> UFState s -> ST s Bool\nsameUF x y st = (==) <$> findUF x st <*> findUF y st\n\nrootUF :: Int -> UFState s -> ST s Bool\nrootUF x st = (x==) <$> findUF x st\n\nmain = do\n [n,m,_] <- readInts\n ss <- map (map readInt . B.words) . B.lines <$> B.getContents\n putStr $ unlines $ map show $ uncurry (solve n) $ first (map l2p) $ splitAt m ss\n\nsolve :: Int -> [(Int,Int)] -> [[Int]] -> [Int]\nsolve n es qs = doit where\n doit = runST $ do\n st <- initUF (1,n)\n forM_ es $ \\(x,y) -> mergeUF x y st\n ds <- newArray_ (1,n) :: ST s (STUArray s Int Int)\n forM_ [1..n] $ \\i -> do\n k <- findUF i st \n when (i==k) $ writeArray ds i (diameter i)\n let go [] = return []\n go ([1,x]:qs) = (:) <$> (findUF x st >>= readArray ds) <*> go qs\n go ([2,x,y]:qs) = do\n px <- findUF x st\n py <- findUF y st\n when (px /= py) $ do\n dx <- readArray ds px\n dy <- readArray ds py\n let rx = (dx + 1) `div` 2\n ry = (dy + 1) `div` 2\n mergeUF px py st\n pz <- findUF x st\n writeArray ds pz (maximum [dx,dy,rx+ry+1])\n go qs\n go qs\n g :: Array Int [Int]\n g = accumArray (flip (:)) [] (1,n) (es ++ map swap es)\n diameter i = d2 where\n (d1,v1) = go (-1) i\n (d2,v2) = go (-1) v1\n go pv v = maximum $ [(0,v)] ++ map (go v) (filter (/=pv) (g ! v))\n\n"}], "src_uid": "54c1d57482a1aa9c1013c2d54c5f9c13"} {"source_code": "\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n \r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n i <- binSearch 1 n\r\n di <- getLen i n\r\n let j=i+di+1\r\n dj <- getLen j n\r\n let k=j+dj\r\n putStr \"! \"\r\n printv [i,j,k]\r\n\r\nquery :: Int -> Int -> IO Integer\r\nquery lo hi = do\r\n putStrLn $ \"? \" ++ show lo ++ \" \" ++ show hi \r\n ~[ans] <- readv\r\n return ans\r\n\r\nbinSearch :: Int -> Int -> IO Int\r\nbinSearch lo hi \r\n | lo+1 == hi = return lo\r\n | otherwise = do\r\n let mid = lo + (hi - lo) `div` 2\r\n inv <- query lo mid\r\n if inv > 0 then binSearch lo mid else binSearch mid hi\r\n\r\ngetLen :: Int -> Int -> IO Int\r\ngetLen lo hi = do\r\n inv1 <- query lo hi\r\n inv2 <- query (lo+1) hi\r\n return $ fromIntegral $ inv1 - inv2\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n", "positive_code": [{"source_code": "\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n \r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n i <- binSearch 1 n\r\n di <- getLen i n\r\n let j=i+di+1\r\n dj <- getLen j n\r\n let k=j+dj\r\n putStr \"! \"\r\n printv [i,j,k]\r\n hFlush stdout\r\n\r\nquery :: Int -> Int -> IO Integer\r\nquery lo hi = do\r\n putStrLn $ \"? \" ++ show lo ++ \" \" ++ show hi \r\n hFlush stdout\r\n ~[ans] <- readv\r\n return ans\r\n\r\nbinSearch :: Int -> Int -> IO Int\r\nbinSearch lo hi \r\n | lo+1 == hi = return lo\r\n | otherwise = do\r\n let mid = lo + (hi - lo) `div` 2\r\n inv <- query lo mid\r\n if inv > 0 then binSearch lo mid else binSearch mid hi\r\n\r\ngetLen :: Int -> Int -> IO Int\r\ngetLen lo hi = do\r\n inv1 <- query lo hi\r\n inv2 <- query (lo+1) hi\r\n return $ fromIntegral $ inv1 - inv2\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}], "negative_code": [], "src_uid": "6be52845d61d8fbd297d742842acd28e"} {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nmain = getContents >>= mapM_ putStrLn . solve . lines\nsolve [] = [] ::[String]\nsolve (c1:c2:cs) = (:solve cs)$ intercalate \"\\n\" [show . length $ s,unwords . map show $ s]\n where\n a = map (read::String->Int) . words $ c2\n (l,r) = foldl f ([],[]) . group . sort $ a\n l' = if null l || head l /= head r then l else tail l\n s = reverse l'++r\nf (l,r) (n:ns)\n | null ns = ( l,n:r)\n | otherwise = (n:l,n:r)\n", "positive_code": [{"source_code": "import Data.List\nmain = getContents >>= putStrLn . f . map (take 2) . group . sort . map read . tail . words\nf :: [[Int]] -> [Char]\nf x = unlines [show (length y), unwords (map show y)]\n where y = map head x ++ (reverse . concatMap tail . init) x"}, {"source_code": "import Data.List\nmain = do\n\tn <- read `fmap` getLine ::IO Int\n\tas <- map read `fmap` words `fmap` getLine::IO [Int]\n\tlet (u,v) = solution as in do\n\t\tprint $ length u + length v\n\t\tputStrLn $ (write $ reverse u) ++ \" \" ++ write v \n\twhere\n\t\twrite = unwords . map show\n\t\tsolution as = case snd $ foldl' walk ((-1, False),([], [])) $ sort as of\n\t\t\t((u:us),(v:vs)) | u == v -> ((u:us),vs)\n\t\t\tt \t\t\t\t\t\t -> t\n\t\twalk ((prev, rep), (us,vs)) a | prev /= a = ((a,False),(a:us,vs))\n\t\t\t\t\t\t\t\t\t| rep \t\t= ((a,True) ,(us,vs))\n\t\t\t\t\t\t\t\t\t| otherwise = ((a,True) ,(us,a:vs))"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n getLine\n bs <- group . sort <$> readInts\n let as = makeStairs bs\n print $ length as\n putStrLn $ unwords $ map show as\n\nmakeStairs :: [[Int]] -> [Int]\nmakeStairs bs = go [] [] bs\n where\n go l1 l2 [(b:_)] = reverse l1 ++ b : l2\n go l1 l2 ([b]:bs) = go (b:l1) l2 bs\n go l1 l2 ((b:_):bs) = go (b:l1) (b:l2) bs\n\n\n"}, {"source_code": "import Data.List\nimport Data.Array\n\nmain = do\n n <- fmap read getLine :: IO Int\n li <- fmap sort $ fmap (fmap read) (fmap words getLine) :: IO [Int]\n\n let (part1, part2) = foldr (\\cur (p1, p2) -> if p1 /= [] && head p1 == cur\n then if p2 /= [] && head p2 == cur\n then (p1, p2)\n else (p1, cur : p2)\n else (cur : p1, p2) ) ([], []) li\n\n let final = part1 ++ reverse (if part1 /= [] && part2 /= [] && last part1 == last part2 then init part2 else part2)\n\n print $ length final\n putStrLn $ concatMap (\\x -> show x ++ \" \") final\n"}, {"source_code": "import Data.List (group, sort)\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve . map read . tail . words\n\nsolve :: [Int] -> [Int]\nsolve = map head . group . uncurry (++) . (map head &&& map head . filter (not . null) . map tail . reverse) . group . sort\n\nprintSolution :: Show a => [a] -> IO ()\nprintSolution xs = print (length xs) >> putStrLn (unwords (map show xs))\n"}, {"source_code": "import Data.List (group, sort)\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve . map read . tail . words\n\nsolve :: [Int] -> [Int]\nsolve = uncurry (++) . (map head &&& concatMap (tail . take 2) . tail . reverse) . group . sort\n\nprintSolution :: Show a => [a] -> IO ()\nprintSolution xs = print (length xs) >> putStrLn (unwords (map show xs))\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Control.Monad\n\nmain = replicateM 2 getLine >>= answer . solve . parse\n\nparse :: [String] -> (Int, [[Int]])\nparse [i, nums] = (read i, group . sort . map read $ words nums)\n\nsolve :: (Int, [[Int]]) -> [Int]\nsolve (_, []) = []\nsolve (i, nums)\n | i == length nums = reverse . map head $ nums\n | otherwise = (s nums) ++ (s . filter (not . null) . map tail . tail $ reverse nums)\n where\n s :: [[Int]] -> [Int]\n s = map head\n\nanswer :: [Int] -> IO ()\nanswer result = (print $ length result)\n >> (putStrLn $ unwords $ map show result)"}], "negative_code": [{"source_code": "import Data.List\nmain = do\n\tn <- read `fmap` getLine ::IO Int\n\tas <- map read `fmap` words `fmap` getLine::IO [Int]\n\tlet (u,v) = solution as in do\n\t\tprint $ length u + length v\n\t\tputStrLn $ (write $ reverse u) ++ \" \" ++ write v \n\twhere\n\t\twrite = unwords . map show\n\t\tsolution as = case snd $ foldl' walk ((-1, False),([], [])) as of\n\t\t\t((u:us),(v:vs)) | u == v -> ((u:us),vs)\n\t\t\tt \t\t\t\t\t\t -> t\n\t\twalk ((prev, rep), (us,vs)) a | prev /= a = ((a,False),(a:us,vs))\n\t\t\t\t\t\t\t\t\t| rep \t\t= ((a,True) ,(us,vs))\n\t\t\t\t\t\t\t\t\t| otherwise = ((a,True) ,(us,a:vs))"}, {"source_code": "import Data.List\nimport Data.Array\n\nuni :: (Eq t) => [t] -> [t]\nuni [] = []\nuni (x:[]) = [x]\nuni (x0:x1:xs) \n | x0 == x1 = uni $ x1 : xs\n | otherwise = x0 : (uni $ x1 : xs)\n\nplainPrint :: (Show t) => [t] -> IO ()\nplainPrint = putStrLn . tail . concatMap (\\x -> ' ' : show x) \n\nmain = do\n n <- fmap read getLine :: IO Int\n li <- fmap sort $ fmap (fmap read) (fmap words getLine) :: IO [Int]\n let uli = uni $ li \n let rest = reverse $ uni $ li \\\\ (uli ++ [last uli])\n print $ length uli + length rest\n plainPrint $ uli ++ rest\n"}, {"source_code": "import Data.List\nimport Data.Array\n\nmain = do\n n <- fmap read getLine :: IO Int\n li <- fmap sort $ fmap (fmap read) (fmap words getLine) :: IO [Int]\n\n let (part1, part2) = foldr (\\cur (p1, p2) -> if p1 /= [] && head p1 == cur\n then if p2 /= [] && head p2 == cur\n then (p1, p2)\n else (p1, cur : p2)\n else (cur : p1, p2) ) ([], []) li\n\n putStrLn $ concatMap (\\x -> show x ++ \" \") (part1 ++ reverse (if part1 /= [] && part2 /= [] && last part1 == last part2 then init part2 else part2))\n"}, {"source_code": "import Data.List\nimport Data.Array\n\nuni :: (Eq t) => [t] -> [t]\nuni [] = []\nuni (x:[]) = [x]\nuni (x0:x1:xs) \n | x0 == x1 = uni $ x1 : xs\n | otherwise = x0 : (uni $ x1 : xs)\n\nplainPrint :: (Show t) => [t] -> IO ()\nplainPrint = putStrLn . tail . concatMap (\\x -> ' ' : show x) \n\nmain = do\n n <- fmap read getLine :: IO Int\n li <- fmap sort $ fmap (fmap read) (fmap words getLine) :: IO [Int]\n let uli = uni $ li \n let rest = reverse $ uni $ li \\\\ (uli ++ [last uli])\n plainPrint $ uli ++ rest\n"}, {"source_code": "import Data.List (group)\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve . map read . tail . words\n\nsolve :: [Int] -> [Int]\nsolve = map head . group . uncurry (++) . (map head &&& map head . filter (not . null) . map tail . reverse) . group\n\nprintSolution :: Show a => [a] -> IO ()\nprintSolution xs = print (length xs) >> putStrLn (unwords (map show xs))\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nmain = getContents >>= mapM_ putStrLn . solve . lines\nsolve [] = [] ::[String]\nsolve (c1:c2:cs) = (:solve cs)$ intercalate \"\\n\" [show . length $ s,unwords . map show $ s]\n where\n a = map (read::String->Int) . words $ c2\n (l,r) = foldl f ([],[]) . group . sort $ a\n s = reverse l++r\nf (l,r) (n:ns)\n | null ns = ( l,n:r)\n | otherwise = (n:l,n:r)\n"}], "src_uid": "5c63f91eb955cb6c3172cb7c8f78976c"} {"source_code": "import Control.Monad (replicateM)\nimport Data.List (transpose)\n\ngao a = if n >= d then \"LIVE\" else \"DEAD\"\n where\n (n:d:_) = map sum $ transpose $ map (map read . tail) a\n\nmain = do\n n <- fmap read getLine\n a <- replicateM n $ fmap words getLine\n putStrLn $ gao $ filter ((==\"1\") . head) a\n putStrLn $ gao $ filter ((==\"2\") . head) a\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM)\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: [(Int, Int, Int)] -> (Bool, Bool)\nsolve qs = (a, b)\n where\n a = live 1\n b = live 2\n live t = sum (map (\\(_, a, _) -> a) qs') >= sum (map (\\(_, _, b) -> b) qs')\n where\n qs' = filter (\\(n, _, _) -> n == t) qs\n\nparseQ :: String -> (Int, Int, Int)\nparseQ line = case map read (words line) of\n [n, a, b] -> (n, a, b)\n\nmain :: IO ()\nmain = do\n n <- readLn\n qs <- mapM (\\i -> liftM parseQ getLine) [1..n]\n let (a, b) = solve qs\n putStrLn $ \"LIVE\" \"DEAD\" $ a\n putStrLn $ \"LIVE\" \"DEAD\" $ b\n"}, {"source_code": "main=interact$f 0 0 0 0.map read.tail.words\nf a b totala totalb (1:x:_:rest) = f (a+x) b (totala+10) totalb rest\nf a b totala totalb (_:x:_:rest) = f a (b+x) totala (totalb+10) rest\nf a b totala totalb [] = g a totala ++g b totalb\ng x totalx|x+x>=totalx =\"LIVE\\n\"|0<1=\"DEAD\\n\""}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO()\nmain = do \n num <- fmap read getLine \n input <- forM [1..num] (\\x -> fmap (map read. words) getLine)\n let a = sum [ y | [x,y,z] <- input , x == 1] \n let b = sum [ y | [x,y,z] <- input, x == 2] \n let c = length [ y | [x,y,z] <-input, x == 1] \n let d = length [ y | [x,y,z] <- input, x == 2]\n\n if a >= (c*5) then putStrLn \"LIVE\" else putStrLn \"DEAD\"\n if b >= (d*5) then putStrLn \"LIVE\" else putStrLn \"DEAD\""}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\nprocess1 a b c d [] = x1 ++ x2\n\twhere \tx1 = if a>=b then [\"LIVE\"] else [\"DEAD\"]\n\t\tx2 = if c>=d then [\"LIVE\"] else [\"DEAD\"]\n\nprocess1 a b c d ([x,y,z]:zs) | x==1 = process1 (a+y) (b+z) c d zs\n | otherwise = process1 a b (c+y) (d+z) zs\n\n\n\nmain = do\n\t\tc<-read <$> getLine ::IO Int\n\t\tx<-map (map read. words) <$> replicateM c getLine ::IO [[Int]]\n\t\tmapM_ putStrLn $ process1 0 0 0 0 x\n"}, {"source_code": "isAlive :: Int -> [[Int]] -> Bool\nisAlive t txys = sx >= sy\n where\n (sx,sy) = foldr f (0,0) txys\n f [t',x',y'] p@(sx',sy')\n | t' == t = ((x'+sx'),(y'+sy'))\n | otherwise = p\n\nisAliveAll :: Int -> [[Int]] -> [Bool]\nisAliveAll n txys = map (\\t -> isAlive t txys) [1..n]\n\nreadInt :: String -> Int\nreadInt = read\n\nshowBool :: Bool -> String\nshowBool False = \"DEAD\"\nshowBool True = \"LIVE\"\n\nmain = do\n n <- fmap readInt getLine\n s <- fmap (map (map readInt.words).lines) getContents\n putStrLn.unlines.map showBool $ isAliveAll 2 s"}], "negative_code": [{"source_code": "main=interact$f False False . map read.tail.words\nf a b (1:x:_:rest)\n | x>=5 = f True b rest\n | otherwise = f a b rest\nf a b (_:x:_:rest)\n | x>=5 = f a True rest\n | otherwise = f a b rest\nf a b [] = g a++g b\ng True = \"LIVE\\n\"\ng _ = \"DEAD\\n\""}], "src_uid": "1d8870a705036b9820227309d74dd1e8"} {"source_code": "import qualified Control.Monad as CM\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x,y] <- readv\r\n printv [x^2, -y^2]\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve >>> map show >>> unwords) >>> unlines\r\n\r\nsolve :: [Integer] -> [Integer]\r\nsolve [u, v] = [u^2, -v^2]\r\n"}, {"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [u, v] = map read $ words input\r\n (x, y) = findXY (u, v)\r\n output = unwords $ map show [x, y]\r\n\r\n\r\nfindXY :: (Integer, Integer) -> (Integer, Integer)\r\nfindXY (u, v) = (u ^ 2, -v ^ 2)\r\n"}], "negative_code": [], "src_uid": "4dfa99acbe06b314f0f0b934237c66f3"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n,c], as] <- replicateM 2 ri\r\n return (c,as)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (c,as) = sum . map (min c . length) . L.group . L.sort $ as\r\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (group, sort)\r\n\r\n(>$>) = flip ($)\r\ninfixl 0 >$>\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> tail >>> map (words >>> map read) >>> chunksOf 2 >>> map (solve >>> show) >>> unlines\r\n\r\nsolve :: [[Int]] -> Int\r\nsolve [[n, c], xs] = xs >$> sort >>> group >>> map (length >>> min c) >>> sum\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n"}, {"source_code": "import Data.Array\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[n, c] -> map read . words <$> getLine >>= print . minCost n c\n\nminCost :: Int -> Int -> [Int] -> Int\nminCost n c as = let am = countF as\n f acc (_, count) = acc + min count c\n in\n foldl f 0 am\n\n-- max input is 100\ncountF :: [Int] -> [(Int, Int)]\ncountF as = let a = listArray (1, 100) [0, 0 ..]\n f a e = a//[(e, 1+a!e)]\n in\n assocs $ foldl f a as\n"}], "negative_code": [], "src_uid": "2805d460df1121c4410999a9f36e383a"} {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n{-# LANGUAGE Strict #-}\n-- {-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\n\nsolve :: Int -> [Int] -> Int\nsolve n as = digitPairsCount * 6\n where\n digitPairsCount = digitsCount * (digitsCount - 1) `div` 2\n digitsCount = (10 - L.length as)\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n", "positive_code": [{"source_code": "import Data.Char\r\n\r\nevery2nd (x:y:xs) = x:(every2nd xs)\r\nevery2nd _ = []\r\n\r\nsolve k = max (k*(k-1)*3) 0\r\n\r\n\r\nmain = do\r\n rawInput <- getContents\r\n let input = tail . lines $ rawInput\r\n let ns = every2nd input\r\n let ans = map (solve . (10-) . read) ns\r\n mapM_ print ans \r\n"}], "negative_code": [{"source_code": "import Data.Char\r\n\r\nevery2nd (x:y:xs) = x:(every2nd xs)\r\nevery2nd _ = []\r\n\r\nsolve k = max (k*(k-1)*3) 0\r\n\r\n\r\nmain = do\r\n rawInput <- getContents\r\n let input = tail . lines $ rawInput\r\n let ns = every2nd input\r\n let ans = map (solve . (10-) . read) ns\r\n print(ans)\r\n"}], "src_uid": "33e751f5716cbd666be36ab8f5e3977e"} {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep [] = []\nsep (x:xs) = h:(sep t)\n where (h,t) = splitAt (read $ head $ words x) xs\n\nparse :: [String] -> [[Int]]\nparse = map (map fromEnum)\n\nformat = show\n\nsolve xs = minimum $ map distance $ pairs xs\n where pairs [] = []\n pairs (y:ys) = [(y,z) | z <- ys] ++ pairs ys\n distance (y,z) = sum $ map (abs . uncurry (-)) $ zip y z\n", "positive_code": [{"source_code": "import Data.List\r\nimport Data.Char\r\nimport Data.Array\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\t\r\nsolve number 0 = return ()\r\nsolve number current = do\r\n\tline <- getLine\r\n\tlet ws = words line\r\n\tlet n = (read . head) ws :: Int\r\n\tlet m = (read . head . tail) ws :: Int\r\n\tls <- replicateM n getLine \r\n\tputStrLn $ (show . minimum) $ lejat ls\r\n\tsolve number (current - 1)\r\n\t\r\nlejat :: [String] -> [Int]\r\nlejat ss = do\r\n\t\tlet kezya = zip ss [1..]\r\n\t\t(a, b) <- kezya\r\n\t\t(c, d) <- kezya\r\n\t\tTrue <- return $ b /= d\r\n\t\treturn $ sosat a c\r\n\t\r\nsosat :: String -> String -> Int\r\nsosat left right = sum $ zipWith (\\a -> \\b -> abs $ (fromEnum a) - (fromEnum b)) left right\r\n\t"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\n\r\nsol :: [String] -> Int\r\nsol xs = minimum [f x y | (x, i) <- ps, (y, j) <- ps, i /= j]\r\n where\r\n f xs' ys' = sum (zipWith (\\x y -> abs (ord x - ord y)) xs' ys')\r\n ps = zip xs [1 .. length xs]\r\n\r\nreadCase :: IO [String]\r\nreadCase = do\r\n [n, m] <- map read . words <$> getLine :: IO [Int]\r\n replicateM n getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine :: IO Int\r\n cases <- replicateM t readCase\r\n putStrLn $ intercalate \"\\n\" (map (show . sol) cases)"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\r\n\r\nletterDiff :: Char -> Char -> Int\r\nletterDiff c1 c2 = abs (fromEnum c1 - fromEnum c2)\r\n\r\nwordDiff :: String -> String -> Int\r\nwordDiff w1 w2 = sum $ zipWith letterDiff w1 w2\r\n\r\nsolve :: [String] -> [[Int]]\r\nsolve [] = []\r\nsolve (x:xs) = (map (wordDiff x) xs) : solve xs\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t $ do\r\n l <- getLine \r\n let [n, m] = (map read . words) l :: [Int]\r\n words <- replicateM n getLine\r\n print $ minimum $ concat $ drop 1 $ reverse $ solve words\r\n"}, {"source_code": "import Data.Char (ord)\nimport Control.Monad (replicateM_, replicateM)\n\nmain :: IO ()\nmain = read <$> getLine >>= flip replicateM_ singleCase\n\nsingleCase :: IO ()\nsingleCase = map read . words <$> getLine >>=\n \\([n, m]) -> replicateM n getLine >>=\n print . findmin (maxBound :: Int)\n\ncharDiff :: Char -> Char -> Int\ncharDiff c1 c2 = abs $ (ord c1) - (ord c2)\n\nstrDiff :: String -> String -> Int\nstrDiff s1 s2 = foldl (\\acc (c1, c2)-> acc + charDiff c1 c2) 0 $ zip s1 s2\n\nfindmin :: Int -> [String] -> Int\nfindmin m [] = m\nfindmin m (x:xs) = let m1 = foldl (\\a s -> min a (strDiff x s)) m xs in\n findmin m1 xs\n"}, {"source_code": "import Data.Char (ord)\r\n\r\ndistC :: Char -> Char -> Int\r\ndistC a b = abs $ ord a - ord b\r\n\r\ndist :: String -> String -> Int\r\ndist [] [] = 0\r\ndist (x: xs) (y: ys) = distC x y + dist xs ys\r\n\r\nreadStr :: Int -> IO [String]\r\nreadStr 0 = pure []\r\nreadStr i = do\r\n s <- getLine\r\n ans <- readStr $ i - 1\r\n pure (s: ans)\r\n\r\ncalcH :: String -> [String] -> Int\r\ncalcH _ [] = 100000000\r\ncalcH s (x: xs) = min (dist s x) (calcH s xs)\r\n\r\ncalc :: [String] -> Int\r\ncalc [] = 100000000\r\ncalc (x: xs) = min (calcH x xs) (calc xs)\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: _) <- map (\\s -> read s :: Int) <$> (words <$> getLine)\r\n arr <- readStr n\r\n print $ calc arr\r\n for $ i - 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n for t"}], "negative_code": [{"source_code": "import Data.List\r\nimport Data.Char\r\nimport Data.Array\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\t\r\nsolve number 0 = return ()\r\nsolve number current = do\r\n\tline <- getLine\r\n\tlet ws = words line\r\n\tlet n = (read . head) ws :: Int\r\n\tlet m = (read . head . tail) ws :: Int\r\n\tls <- replicateM n getLine \r\n\tlet vars = lejat ls\r\n\tif length vars == 0 then putStrLn \"0\"\r\n\telse putStrLn $ (show . minimum) $ vars\r\n\tsolve number (current - 1)\r\n\t\r\nlejat :: [String] -> [Int]\r\nlejat ss = do\r\n\t\tfirstVar <- ss\r\n\t\tsecondVar <- ss\r\n\t\tTrue <- return $ firstVar /= secondVar\r\n\t\treturn $ sosat firstVar secondVar\r\n\t\r\nsosat :: String -> String -> Int\r\nsosat left right = sum $ zipWith (\\a -> \\b -> abs $ (fromEnum a) - (fromEnum b)) left right\r\n\t"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\n\r\nsol :: [String] -> Int\r\nsol xs = minimum [abs (x - y) | (x, i) <- ps, (y, j) <- ps, i /= j]\r\n where\r\n conv = foldl' (\\acc x -> acc + ord x) 0\r\n ps = zip (map conv xs) [1 .. (length xs)]\r\n\r\nreadCase :: IO [String]\r\nreadCase = do\r\n [n, m] <- map read . words <$> getLine :: IO [Int]\r\n replicateM n getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine :: IO Int\r\n cases <- replicateM t readCase\r\n putStrLn $ intercalate \"\\n\" (map (show . sol) cases)"}], "src_uid": "ef2b90d5b1073430795704a7df748ac3"} {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n-- }}}\n\nrow :: Int -> [Int]\nrow 1 = [1]\nrow 2 = [3,4]\nrow 3 = [3,4,12]\nrow m = (m-2) : replicate (m-1) 2\n\ntable :: Int -> Int -> [[Int]]\ntable n m = [[x*y | y <- row m] | x <- row n]\n\nmain :: IO ()\nmain = do\n\t[n,m] <- inputInts\n\tlet t = table n m in forM_ t $ \\r -> putStrLn $ unwords (map show r)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Array\n\nreadInt :: IO Int\nreadInt = read <$> getLine\nreadIntList :: IO [Int]\nreadIntList = fmap read . words <$> getLine\nreadIntArray :: Int -> IO (Array Int Int)\nreadIntArray n = listArray (0, n-1) <$> readIntList\nreadSortedIntArray :: Int -> IO (Array Int Int)\nreadSortedIntArray n = listArray (0, n-1) . sort <$> readIntList\n\nsquares :: [Int]\nsquares = flip fmap [1..] $ \\i -> i * i\n\nsquareRoot :: Int -> Either Int Int\nsquareRoot x = squareRootImpl 1 x\n where\n squareRootImpl lo hi =\n if lo >= hi\n then\n case (lo * lo) `compare` x of\n LT -> Left $ lo\n EQ -> Right lo\n GT -> Left $ lo - 1\n else\n let mid = (lo + hi) `div` 2 in\n case (mid * mid) `compare` x of\n LT -> squareRootImpl (mid + 1) hi\n EQ -> Right mid\n GT -> squareRootImpl lo (mid - 1)\n\nsquareSum :: [[Int]]\nsquareSum = flip fmap [1..] $ \\x ->\n case squareRoot x of\n Right y -> [y]\n Left y -> foldr1 (\\l l' -> if (length l) < (length l') then l else l') $ flip fmap [1..y] (\\i -> (i:)$ squareSum !! (x-i*i-1))\n\nsquareSumN :: [Int]\nsquareSumN = fmap length squareSum\n\nsmallS :: [[Int]]\nsmallS =\n [ [1]\n , [3, 4]\n , [3, 4, 12]\n , [3, 4, 12, 84]\n ]\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntList\n let sn = squareSum !! (n-1)\n let pn = product sn\n let sn' = smallS !! (length sn - 1)\n let sm = squareSum !! (m-1)\n let pm = product sm\n let sm' = smallS !!(length sm - 1)\n forM_ [0..length sn - 1] $ \\n' -> do\n let ni = (sn!!n')\n forM_ [1..(sn!!n')*(sn!!n')] $ \\_ -> do\n forM_ [0..length sm - 1] $ \\m' -> do\n let mi = (sm!!m')\n forM_ [1..(sm!!m')*(sm!!m')] $ \\_ -> do\n putStr $ show ((sn'!!n')*(pn `div` ni)*(sm'!!m')*(pm `div` mi)) ++ \" \"\n putStrLn \"\""}], "negative_code": [{"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Array\n\nreadInt :: IO Int\nreadInt = read <$> getLine\nreadIntList :: IO [Int]\nreadIntList = fmap read . words <$> getLine\nreadIntArray :: Int -> IO (Array Int Int)\nreadIntArray n = listArray (0, n-1) <$> readIntList\nreadSortedIntArray :: Int -> IO (Array Int Int)\nreadSortedIntArray n = listArray (0, n-1) . sort <$> readIntList\n\nsquares :: [Int]\nsquares = flip fmap [1..] $ \\i -> i * i\n\nsquareRoot :: Int -> Either Int Int\nsquareRoot x = squareRootImpl 1 x\n where\n squareRootImpl lo hi =\n if lo >= hi\n then\n case (lo * lo) `compare` x of\n LT -> Left $ lo\n EQ -> Right lo\n GT -> Left $ lo - 1\n else\n let mid = (lo + hi) `div` 2 in\n case (mid * mid) `compare` x of\n LT -> squareRootImpl (mid + 1) hi\n EQ -> Right mid\n GT -> squareRootImpl lo (mid - 1)\n\nsquareSum :: [[Int]]\nsquareSum = flip fmap [1..] $ \\x ->\n case squareRoot x of\n Right y -> [y]\n Left y -> foldr1 (\\l l' -> if (length l) < (length l') then l else l') $ flip fmap [1..y] (\\i -> (i:)$ squareSum !! (x-i*i-1))\n\nsquareSumN :: [Int]\nsquareSumN = fmap length squareSum\n\nsmallS :: [[Int]]\nsmallS =\n [ [1]\n , [3, 4]\n , [3, 4, 12]\n , [3, 4, 12, 84]\n ]\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntList\n let sn = squareSum !! (n-1)\n let pn = product sn\n let sn' = smallS !! (length sn - 1)\n let sm = squareSum !! (m-1)\n let pm = product sm\n let sm' = smallS !!(length sm - 1)\n forM_ [0..length sn - 1] $ \\n' -> do\n let ni = (sn!!n')*(sn!!n')\n forM_ [1..(sn!!n')*(sn!!n')] $ \\_ -> do\n forM_ [0..length sm - 1] $ \\m' -> do\n let mi = (sm!!m')*(sm!!m')\n forM_ [1..(sm!!m')*(sm!!m')] $ \\_ -> do\n putStr $ show ((sn'!!n')*(pn `div` ni)*(sm'!!m')*(pm `div` mi)) ++ \" \"\n putStrLn \"\""}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Array\n\nreadInt :: IO Int\nreadInt = read <$> getLine\nreadIntList :: IO [Int]\nreadIntList = fmap read . words <$> getLine\nreadIntArray :: Int -> IO (Array Int Int)\nreadIntArray n = listArray (0, n-1) <$> readIntList\nreadSortedIntArray :: Int -> IO (Array Int Int)\nreadSortedIntArray n = listArray (0, n-1) . sort <$> readIntList\n\nsquares :: [Int]\nsquares = flip fmap [1..] $ \\i -> i * i\n\nsquareRoot :: Int -> Either Int Int\nsquareRoot x = squareRootImpl 1 x\n where\n squareRootImpl lo hi =\n if lo >= hi\n then\n case (lo * lo) `compare` x of\n LT -> Left $ lo\n EQ -> Right lo\n GT -> Left $ lo - 1\n else\n let mid = (lo + hi) `div` 2 in\n case (mid * mid) `compare` x of\n LT -> squareRootImpl (mid + 1) hi\n EQ -> Right mid\n GT -> squareRootImpl lo (mid - 1)\n\nsquareSum :: [[Int]]\nsquareSum = flip fmap [1..] $ \\x ->\n case squareRoot x of\n Right y -> [y]\n Left y -> foldr1 (\\l l' -> if (length l) < (length l') then l else l') $ flip fmap [1..y] (\\i -> (i:)$ squareSum !! (x-i*i-1))\n\nsquareSumN :: [Int]\nsquareSumN = fmap length squareSum\n\nsmallS :: [[Int]]\nsmallS =\n [ [1]\n , [3, 4]\n , [3, 4, 12]\n , [3, 4, 12, 84]\n ]\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntList\n let sn = squareSum !! (n-1)\n let pn = product $ fmap (\\i -> i * i) sn\n let sn' = smallS !! (length sn - 1)\n let sm = squareSum !! (m-1)\n let pm = product $ fmap (\\i -> i * i) sm\n let sm' = smallS !!(length sm - 1)\n forM_ [0..length sn - 1] $ \\n' -> do\n let ni = (sn!!n')*(sn!!n')\n forM_ [1..(sn!!n')*(sn!!n')] $ \\_ -> do\n forM_ [0..length sm - 1] $ \\m' -> do\n let mi = (sm!!m')*(sm!!m')\n forM_ [1..(sm!!m')*(sm!!m')] $ \\_ -> do\n putStr $ show ((sn'!!n')*(pn `div` ni)*(sm'!!m')*(pm `div` mi)) ++ \" \"\n putStrLn \"\""}], "src_uid": "c80cdf090685d40fd34c3fd082a81469"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n xs <- scanl1(+).f <$> getLine\n let arr = listArray (0,length xs-1) xs\n _ <- getLine\n lrs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show$solve arr lrs\n\nsolve :: UArray Int Int -> [Int] -> [Int]\nsolve arr lrs = go lrs\n where\n go (l:r:rest)\n | l==1 = unsafeAt arr (r-2) : go rest\n | otherwise = unsafeAt arr (r-2) - unsafeAt arr (l-2) : go rest\n go _ = []\n\nf (x:y:z)\n | x==y = 1 : f (y:z)\n | otherwise = 0 : f (y:z)\nf _ = []", "positive_code": [{"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Array\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: String -> [(Int, Int)] -> [Int]\nsolve s qs = map solve' qs\n where\n n = length s\n solve' (l, r) = a ! r - a ! l\n a = listArray (1,n) $ scanl (+) 0 $ zipWith eqToInt s $ tail s\n eqToInt a b = if a == b then 1 else 0\n\nmain :: IO ()\nmain = do\n s <- getLine\n n <- readLn\n qs <- replicateM n readPair\n mapM_ print $ solve s qs\n\n where\n\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show"}, {"source_code": "import Data.Array.Unboxed ((!), Array, listArray)\n\nmain :: IO ()\nmain = getLine >>= \\s -> getContents >>= mapM_ print . solve s . map (map read . words) . tail . lines\n\nsolve :: String -> [[Int]] -> [Int]\nsolve s lrs = [ dp ! r - dp ! l | [ l, r ] <- lrs ]\n where dp :: Array Int Int\n dp = listArray (1, length s) $ scanl (+) 0 $ zipWith (\\x y -> fromEnum (x == y)) s $ tail s\n"}, {"source_code": "import qualified Data.IntMap as Map\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Array\n\ncons :: BS.ByteString -> Array Int Int\ncons s = (extract . BS.foldl' f (1,' ',0,[])) s\n where\n extract (_,_,_,m) = array (1, fromIntegral $ BS.length s) m\n f (idx, before, count,m) c\n | before == c = (idx+1, c, count+1, (idx, count + 1): m)\n | otherwise = (idx + 1, c, count, (idx, count): m)\n\nmain :: IO ()\nmain = do\n (s:_:rest) <- liftM BS.lines BS.getContents\n let m = cons s\n mapM_ (print . rush m . readTuple) rest\n\nreadTuple :: BS.ByteString -> (Int, Int)\nreadTuple s = let (a, aRest) = fromJust $ BS.readInt s\n rest = BS.dropWhile (== ' ') aRest\n (b, _) = fromJust $ BS.readInt rest in (a,b)\n\nrush :: Array Int Int -> (Int, Int) -> Int\nrush m (l, r) = m!r - m!l\n"}, {"source_code": "import Data.Array.Unboxed ((!), Array, listArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getLine >>= \\s -> B.getContents >>= mapM_ print . solve s . map (map (fst . fromJust . B.readInt) . B.words) . tail . B.lines\n\nsolve :: B.ByteString -> [[Int]] -> [Int]\nsolve s lrs = [ dp ! r - dp ! l | [ l, r ] <- lrs ]\n where dp :: Array Int Int\n dp = listArray (1, B.length s) $ scanl (+) 0 $ B.zipWith (curry (fromEnum . uncurry (==))) s $ B.tail s\n"}, {"source_code": "import Data.Array.Unboxed\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nreadI b = i where Just (i,_) = B.readInt b\nmain = do\n s <- B.getLine\n let a = listArray (0,B.length s) $ scanl (+) 0 $\n B.zipWith ((fromEnum .) . (==)) s (B.tail s) :: UArray Int Int\n q <- readI <$> B.getLine\n replicateM_ q $ do\n [l,r] <- map readI . B.words <$> B.getLine\n print $ a!(r-1) - a!(l-1)\n"}, {"source_code": "import Data.Array\n\ngetQu :: [String] -> [(Int, Int)]\ngetQu [] = []\ngetQu (sl : sr : xs) = (read sl, read sr) : (getQu xs)\n\ngetSufSum :: String -> [Int]\ngetSufSum [x] = [0]\ngetSufSum (x1 : x2 : xs) = ((if x1 == x2 then 1 else 0) + head t) : t\n where\n t = getSufSum (x2 : xs)\n\ngetAns :: Array Int Int -> (Int, Int) -> [String]\ngetAns sum (l, r) = [show $ (sum ! l) - (sum ! r)]\n\nhandle :: [String] -> [[String]]\nhandle (s : _ : sq) = map (getAns (listArray (1, length(sum)) sum)) (getQu sq)\n where\n sum = getSufSum s\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\n\n \n \t\n\nmain= do\n\ts<-getLine\n\tlet ls = length s\n\tlet s1 = tail s\n\tlet ls1 = length s1\n\tlet ans = listArray (1,ls) $ scanl1 (+) $ [0]++ (zipWith (\\a b-> if a==b then 1 else 0) s s1) ++[0]\n\tgetLine\n\tq<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tputStrLn $ intercalate \"\\n\" $ map show$ map (\\[x,y]->ans!y-ans!x) q\n\t"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n s <- C.getLine\n let a = C.zipWith (\\i j -> if i == j then 1 else 0) s $ C.tail s\n b :: UArray Int Int\n b = listArray (1, C.length s) $ scanl (+) 0 a\n q <- fmap (pairs . map readInt . tail . C.words) C.getContents\n putStr $ unlines $ map (\\(i, j) -> show $ b!j - b!i) $ q\n"}, {"source_code": "import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n s <- B.getLine\n let a = listArray (1, B.length s) $ scanl (+) 0 $ B.zipWith f s $ B.tail s\n B.getLine\n mapM_ (print . solve a . map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents\n\nf :: Char -> Char -> Int\nf a b = fromEnum $ a == b\n\nsolve :: UArray Int Int -> [Int] -> Int\nsolve a [l, r] = a ! r - a ! l\n"}, {"source_code": "import Data.Array.Unboxed\n\nmain = interact $ unlines.g.lines\n\nf (x:[]) ans = reverse ans\nf (x:y:xs) ans\n | x == y = f (y:xs) (1:ans)\n | otherwise = f (y:xs) (0:ans)\n\nprefixsum [] sumsofar ans = reverse (sumsofar:ans)\nprefixsum (x:xs) sumsofar ans = prefixsum xs (sumsofar+x) (sumsofar:ans)\n\nquery (a:b:[]) xs = (xs ! b) - (xs ! a)\n\ng (x:y:xs) = map show (reverse (h k (trtd xs) []))\n where j = (prefixsum (f x []) 0 [])\n k = listArray (1, (length j)) j\n\nh :: Array Int Int -> [[Int]] -> [Int] -> [Int]\nh a [] ans = ans\nh a (x:xs) ans = h a xs ((query x a):ans)\n\ntrtd = map (\\x -> (map read (words x)) :: [Int])\n"}, {"source_code": "import Data.Array.Unboxed\nimport Numeric\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ unlines.g.lines\n\nf (x:[]) ans = reverse ans\nf (x:y:xs) ans\n | x == y = f (y:xs) (1:ans)\n | otherwise = f (y:xs) (0:ans)\n\nprefixsum [] sumsofar ans = reverse (sumsofar:ans)\nprefixsum (x:xs) sumsofar ans = prefixsum xs (sumsofar+x) (sumsofar:ans)\n\nquery (a:b:[]) xs = (xs ! b) - (xs ! a)\n\ng (x:y:xs) = map show (reverse (h k (trtd xs) []))\n where j = (prefixsum (f x []) 0 [])\n k = listArray (1, (length j)) j\n\nh :: Array Int Int -> [[Int]] -> [Int] -> [Int]\nh a [] ans = ans\nh a (x:xs) ans = h a xs ((query x a):ans)\n\ntrtd = map (\\x -> (map fastRead (words x)) :: [Int])\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n cs = listArray (1, length l) l :: UArray Int Int\n where\n l = scanl (+) 0 $ map fromEnum $ zipWith (==) s $ tail s\n\n m <- readLn\n\n qs <- replicateM m getInts\n\n putStrLn $ unlines $ map show $ map (\\[l, r] -> cs!r - cs!l) qs\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.(\\ (a1:a2:as)->a1:(take (read a2) as)). lines\nsolve :: [String]->String\nsolve (xx:xs) = unlines $ map show $ slv1 (ones2, xsnum)\n where\n ones1 = map fst $ scanl (\\(b1,b2) a->if a==b2 then (b1,a) else (b1+1,a) ) (0,head xx) xx\n ones2 = array (1,length $ tail ones1) $ zip [1..length $ tail ones1] $ tail ones1\n xsnum = map (map (read::String->Int).words) xs\nslv1 (xs,yss)=[z|[y1,y2]<-yss, let z = y2-y1 - (xs!y2 -xs!y1)] "}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.(\\ (a1:a2:as)->a1:(take (read a2) as)). lines\nsolve :: [String]->String\nsolve (xx:xs) = unlines $ map show $ slv1 (ones1, xsnum)\n where\n ones1 = map fst $ scanl (\\(b1,b2) a->if a==b2 then (b1,a) else (b1+1,a) ) (0,head xx) xx\n xsnum = map (map (read::String->Int).words) xs\nslv1 (xs,yss)=[z|[y1,y2]<-yss, let z = y2-y1] "}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\n\n \n \t\n\nmain= do\n\ts<-getLine\n\tlet s1 = tail s\n\tlet ls1 = length s\n\tlet ans = listArray (1,ls1) $ (zipWith (\\a b-> if a==b then 1 else 0) s s1)++[0]\n\tprint ans\n\tlet ans2d = array ((1,1),(ls1,ls1)) $ [((i,j),(if i+1==j then ans!i else ans2d!(i+1,j)+ans!i ))| i<-[1..ls1],j<-[i+1..ls1]]\n\tgetLine\n\tq<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tputStrLn $ intercalate \" \" $ map show$ map (\\[a,b]->ans2d!(a,b)) q\n\t"}], "src_uid": "b30e09449309b999473e4be6643d68cd"} {"source_code": "import Data.Map as M\nimport Data.List as L\n\nfun :: Integer -> Integer\nfun 1 = 0\nfun n = (n*2 + 2*(n-2))*(div n 2) + fun (n-2)\n\nsolve :: String -> String\nsolve input = show $ fun n\n where n = read input :: Integer\n\nmain :: IO()\nmain = interact (unlines . L.map solve . tail . lines)\n", "positive_code": [{"source_code": "import Control.Arrow\n\nmain = interact $\n words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\n\nsolve :: Integer -> Integer\nsolve n = 4 * (n2 * (n2 + 1) * (2*n2 + 1)) `div` 3\n where\n n2 = n `div` 2\n\n"}, {"source_code": "import Control.Monad\n\ntype Test = Integer\n\ngetLines :: Int -> IO [String]\ngetLines count = replicateM count getLine\n\nparseData :: [String] -> [Test]\nparseData [] = []\nparseData (first:rest) = (read first) : parseData rest\n\ngetAnswer :: [Test] -> [Integer]\ngetAnswer [] = []\ngetAnswer (first:rest) = solve first : getAnswer rest\n\nsolve :: Integer -> Integer\nsolve 1 = 0\nsolve n = sideCells * middle + solve (n - 2)\n where middle = n `div` 2\n inner = (n - 2)^2\n sideCells = n^2 - inner\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getLines $ read count\n mapM_ print (getAnswer $ parseData tests)"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- (readLn :: IO Integer)\n let a = n `div` 2\n print $ 8 * (a * (a + 1) * (2*a + 1)) `div` 6\n"}], "negative_code": [], "src_uid": "b4b69320c6040d2d264ac32e9ba5196f"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n print $ solve s\n\nsolve :: String -> Int\nsolve s\n | null fs = 0\n | otherwise = minimum $ map(\\((a,la),(b,lb),(c,lc)) -> lb + 2 ) fs\n\n where\n ps = map (\\x -> (head x,length x)) $ group s\n ts = zip3 ps (tail ps) (tail $ tail $ ps)\n fs = filter (\\((a,la),(b,lb),(c,lc)) -> (length $ nub [a,b,c]) == 3) ts", "positive_code": [{"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport qualified Data.Array.Unboxed as Ar\nimport Data.Array.Unboxed (UArray)\nimport Data.Ord (comparing)\nimport qualified Data.Maybe as Mb\n\ntype Long = Int\n\nprefixSum :: [Int] -> UArray Int Int\nprefixSum lst = Ar.listArray (0,length lst) $ 0:go 0 lst\n where\n go aux (n:rest) = (aux+n): go (aux+n) rest\n\nrangeQuery :: String -> Char -> Int -> Int -> Int\nrangeQuery s = runner\n where\n runner ch start end\n | ch == '1' = prefix1 Ar.! end - (prefix1 Ar.! (start-1))\n | ch == '2' = prefix2 Ar.! end - (prefix2 Ar.! (start-1))\n | ch == '3' = prefix3 Ar.! end - (prefix3 Ar.! (start-1))\n charMapper c x\n | c == x = 1\n | otherwise = 0\n prefix1 = prefixSum $ map (charMapper '1') s\n prefix2 = prefixSum $ map (charMapper '2') s\n prefix3 = prefixSum $ map (charMapper '3') s\n\nvalidRange :: (Char -> Int -> Int -> Int) -> (Int, Int) -> Bool\nvalidRange rqRunner (start, end) = validForChar '1' && validForChar '2' && validForChar '3'\n where\n validForChar c = 0 < rqRunner c start end\n{-\nsolve :: String -> Int\nsolve s = minimum $ map (\\(a,b) -> b-a) allValidRanges\n where\n rqRunner = rangeQuery s\n allPossibleRanges = (1,length s) : possibleRanges '1' ++ possibleRanges '2' ++ possibleRanges '3'\n allValidRanges = filter (validRange rqRunner) allPossibleRanges\n possibleRanges c = zip ind $ map pred $ tail ind\n where\n ind = map fst $ filter (\\(i,x) -> x == c) $ zip [1..] s\n-}\n\nscan :: UArray Int Char -> (Int, Int) -> (Int, Int, Int) -> Int\nscan arr (start, end) cnt@(cnt1, cnt2, cnt3)\n | valid cnt = min (cnt1+cnt2+cnt3) $ scan arr (start+1, end) $ sub1 (arr Ar.! start) cnt\n | otherwise = if finished then 5000000 else scan arr (start, end+1) $ add1 (arr Ar.! (end+1)) cnt\n where\n finished = end == snd (Ar.bounds arr)\n valid (cnt1, cnt2, cnt3) = cnt1 > 0 && cnt2 >0 && cnt3 > 0\n add n '1' (cnt1, cnt2, cnt3) = (cnt1+n, cnt2, cnt3)\n add n '2' (cnt1, cnt2, cnt3) = (cnt1, cnt2+n, cnt3)\n add n '3' (cnt1, cnt2, cnt3) = (cnt1, cnt2, cnt3+n)\n add1 = add 1\n sub1 = add (-1)\n\nsolve :: String -> Int\nsolve s =\n case scan (Ar.listArray (1,length s) s) (1,1) init of\n 5000000 -> 0\n ans -> ans\n where\n init =\n case s of\n '1':_ -> (1,0,0)\n '2':_ -> (0,1,0)\n '3':_ -> (0,0,1)\n\ntest :: String -> Int\ntest s = scan (Ar.listArray (1,length s) s) (1,1) init\n where\n init =\n case s of\n '1':_ -> (1,0,0)\n '2':_ -> (0,1,0)\n '3':_ -> (0,0,1)\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n s <- getLine\n print $ solve s\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}, {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport qualified Data.Array.Unboxed as Ar\nimport Data.Array.Unboxed (UArray)\nimport Data.Ord (comparing)\nimport qualified Data.Maybe as Mb\n\ntype Long = Int\n\n\nminSize :: String -> (Int, Int, Int, Int)\nminSize \"\" = (10000000, 10000000, 10000000, 10000000)\nminSize (c:rest) =\n case c of\n '1' -> (0, f2+1, f3+1, min ans (2 + max f2 f3))\n '2' -> (f1+1, 0, f3+1, min ans (2 + max f1 f3))\n '3' -> (f1+1, f2+1, 0, min ans (2 + max f1 f2))\n where\n (f1,f2,f3, ans) = minSize rest\n\n\nsolve :: String -> Int\nsolve s\n | ans > 1000000 = 0\n | otherwise = ans\n where\n (_,_,_,ans) = minSize s\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n s <- getLine\n print $ solve s\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}, {"source_code": "import Data.List (group)\nmain = interact $ unlines . map f . tail . lines\n\nf x = show $ ans\n where g = map (\\x -> (head x, length x)) (group x)\n inp = zip3 g (tail g) (tail (tail g))\n h = map (\\((i, x), (j, y), (k, z)) -> if i == k then 0 else y+2) inp\n h1 = filter (/= 0) h\n ans = if (h1==[]) then 0 else minimum h1\n"}, {"source_code": "import Data.List\n\ninf = 300000\n\nsolve' :: (Int, Int, Int) -> String -> Int\nsolve' _ [] = inf\nsolve' cum (x:xs) = min (score u) nxt\n where nxt = solve' u xs\n u = upd cum x\n\nscore :: (Int, Int, Int) -> Int\nscore (a, b, c) = 1 + (maximum [a, b, c])\n\nupd :: (Int, Int, Int) -> Char -> (Int, Int, Int)\nupd (_, l2, l3) '1' = (0, l2 + 1, l3 + 1)\nupd (l1, _, l3) '2' = (l1 + 1, 0, l3 + 1)\nupd (l1, l2, _) '3' = (l1 + 1, l2 + 1, 0)\n\nmain :: IO ()\nmain = interact solve\n where solve = (intercalate \"\\n\") \n . (map show)\n . (map $ \\x -> if x >= inf then 0 else x)\n . (map (solve' (inf, inf, inf))) \n . (drop 1) . words\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do \n n <- readLn :: IO Int\n replicateM_ n routine \n\n\nroutine = do\n s <- getLine \n print $ solve s\n\nsolve :: String -> Int \nsolve s\n | null total_ans = 0\n | otherwise = minimum $ map (\\((a, la), (b, lb), (c, lc)) -> lb+2) total_ans\n where \n grouped_list = map (\\x -> (head x, length x)) $ group s\n pre_now_next = zip3 grouped_list (tail grouped_list) (tail $ tail $ grouped_list)\n total_ans = filter (\\((a, la), (b, lb), (c, lc)) -> length (nub [a, b, c]) == 3) pre_now_next\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do \n n <- readLn :: IO Int\n replicateM_ n routine \n\n\nroutine = do\n s <- getLine \n print $ solve s\n\nsolve :: String -> Int \nsolve s\n | null total_ans = 0\n | otherwise = minimum $ map (\\((a, la), (b, lb), (c, lc)) -> lb+2) total_ans\n where \n -- group_list = [(char, how_many)]\n grouped_list = map (\\x -> (head x, length x)) $ group s\n -- pre_now_next = [(i-1, length), (i, length), (i+1, length)]\n pre_now_next = zip3 grouped_list (tail grouped_list) (tail $ tail $ grouped_list)\n -- total_ans = i-1 != i 's pair\n total_ans = filter (\\((a, la), (b, lb), (c, lc)) -> length (nub [a, b, c]) == 3) pre_now_next\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n print $ solve s\n\nsolve :: String -> Int\nsolve s\n | null fs = 0\n | otherwise = minimum $ map (\\((a,la),(b,lb),(c,lc)) -> lb + 2 ) fs\n\n where\n ps = map (\\x -> (x,length x)) $ group s\n ts = zip3 ps (tail ps) (tail $ tail $ ps)\n fs = filter (\\((a,la),(b,lb),(c,lc)) -> (length $ nub [a,b,c]) == 3) ts"}, {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport qualified Data.Array.Unboxed as Ar\nimport Data.Array.Unboxed (UArray)\nimport Data.Ord (comparing)\nimport qualified Data.Maybe as Mb\n\ntype Long = Int\n\n\nminSize :: String -> (Int, Int, Int, Int)\nminSize \"\" = (10000000, 10000000, 10000000, 10000000)\nminSize (c:rest) =\n case c of\n '1' -> (0, f2+1, f3+1, 1 + min ans (max f2 f3))\n '2' -> (f1+1, 0, f3+1, 1 + min ans (max f1 f3))\n '3' -> (f1+1, f2+1, 0, 1 + min ans (max f1 f2))\n where\n (f1,f2,f3, ans) = minSize rest\n\n\nsolve :: String -> Int\nsolve s\n | ans > 1000000 = 0\n | otherwise = ans\n where\n (_,_,_,ans) = minSize s\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n s <- getLine\n print $ solve s\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}], "src_uid": "6cb06a02077750327602a1a7eeac770f"} {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}, {"source_code": "import Data.List\nimport Data.Graph\nimport Data.Tree\n\nmakeG (a:lst) = buildG (1, a) . pair $ lst\n\twhere pair [] = []; pair (a:b:cs) = (a,b) : (b,a) : pair cs\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet n = read . head $ input\n\tlet trees = map (makeG . map read . words) . take n . tail $ input\n\twriteFile \"output.txt\" . (++\"\\n\") . show . sum . (map (\\g -> maximum [ length . head . map levels $ dfs g [i] | i <- vertices g ] - 1)) $ trees\n\n"}], "negative_code": [], "src_uid": "63098c9d5ef90d445a6a4aa0f037a9c7"} {"source_code": "-- http://codeforces.com/contest/845/problem/D\n\n{-# LANGUAGE CPP #-}\n\n#define eChangeSpeed 1\n#define eOvertakeOtherCar 2\n#define eSpeedLimit 3\n#define eOvertakeAllowed 4\n#define eNoSpeedLimit 5\n#define eNoOvertakeAllowed 6\n\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\n\ntype CurrentSpeed = Int\ntype SpeedLimitStack = [Int]\ntype NoOvertakeCount = Int\ntype NumIgnored = Int\ntype State = (CurrentSpeed, SpeedLimitStack, NoOvertakeCount, NumIgnored)\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n numEvents <- getInt\n events <- replicateM numEvents getInts\n let (_,_,_,answer) = solve events\n print answer\n\nstate0 = (0, [], 0, 0)\n\nsolve :: [[Int]] -> State\nsolve events = foldl f state0 events where\n f (speed, speedLimitStack, noOvertakeCount, answer) event@(t:args) = case t of\n eChangeSpeed ->\n let newSpeed = head args\n in if length speedLimitStack > 0 && newSpeed > head speedLimitStack\n then (newSpeed, dropWhile (< newSpeed) speedLimitStack, noOvertakeCount, answer + length (takeWhile (< newSpeed) speedLimitStack))\n else (newSpeed, speedLimitStack, noOvertakeCount, answer)\n eOvertakeOtherCar -> (speed, speedLimitStack, 0, if noOvertakeCount == 0 then answer else answer + noOvertakeCount)\n eSpeedLimit ->\n let newSpeedLimit = head args\n in if speed > newSpeedLimit\n then (speed, speedLimitStack, noOvertakeCount, answer + 1)\n else (speed, newSpeedLimit : speedLimitStack, noOvertakeCount, answer)\n eOvertakeAllowed -> (speed, speedLimitStack, 0, answer)\n eNoSpeedLimit -> (speed, [], noOvertakeCount, answer)\n eNoOvertakeAllowed -> (speed, speedLimitStack, noOvertakeCount + 1, answer)", "positive_code": [{"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (partition, foldl')\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram = fst . foldl' runEvents (0, (0, [], 0))\n\nrunEvents :: (Int, (Int, [Int], Int)) -> [Int] -> (Int, (Int, [Int], Int))\nrunEvents (prevIgnore, (speed, speedSigns, overtakeSigns)) event =\n let (state', ignoredSigns) = case event of\n [1, s] -> ((s, r, overtakeSigns), length l) where (l, r) = span ( ((speed, speedSigns, 0), overtakeSigns)\n [3, s] \n | s < speed -> ((speed, speedSigns, overtakeSigns), 1)\n | otherwise -> ((speed, s:speedSigns, overtakeSigns), 0)\n [4] -> ((speed, speedSigns, 0), 0)\n [5] -> ((speed, [], overtakeSigns), 0)\n [6] -> ((speed, speedSigns, overtakeSigns + 1), 0)\n in (prevIgnore + ignoredSigns, state')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine, getContents)\nimport qualified Data.ByteString.Char8 as C (readInt, words, lines)\nimport qualified Data.Maybe as M (fromJust)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun (g@[1, spd]:xs) cnt (_:std:sta) ans | std >= spd = run xs cnt (spd:std:sta) ans\n | otherwise = run (g:xs) cnt (spd:sta) (succ ans)\nrun ([1, spd]:xs) cnt [_] ans = run xs cnt [spd] ans\nrun ([2]:xs) cnt sta ans = run xs 0 sta (ans + cnt)\nrun ([3, spr]:xs) cnt (spd:sta) ans | spr < spd = run xs cnt (spd:sta) (succ ans)\n | otherwise = run xs cnt (spd:spr:sta) ans\nrun ([4]:xs) _ sta ans = run xs 0 sta ans\nrun ([5]:xs) cnt (spd:_) ans = run xs cnt [spd] ans\nrun ([6]:xs) cnt sta ans = run xs (succ cnt) sta ans\nrun [] _ _ ans = ans\n\nmain = do\n _ <- B.getLine\n (map (map readInt . C.words) . C.lines-> xs) <- B.getContents\n putStrLn $ show $ run xs 0 [0] 0\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE LambdaCase, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\ndata E = S !Int | O | L !Int | A | I | N deriving Show\n\napp = do\n n <- poi\n es <- replicateM n $ \\case { 1 -> fmap S poi; 2 -> return O; 3 -> fmap L poi; 4 -> return A; 5 -> return I; 6 -> return N } =<< poi\n return $ show $ solve es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = (\\(a, _, _, _) -> a) . foldl go (0, 0, [], 0)\n where\n go (!c, !s, !ls, !o) = \\case\n S s' -> let (lt, gt) = span (< s') ls in (c + length lt, s', gt, o)\n O -> (c + o, s, ls, 0)\n L l -> if s > l then (c + 1, s, ls, o) else (c, s, l:ls, o)\n A -> (c, s, ls, 0)\n I -> (c, s, [], o)\n N -> (c, s, ls, o + 1)"}], "negative_code": [{"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort, sortBy)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], [0], False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],[Int],Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (limits, speeds, overtake) =\n let (ignore, limits') = case event of\n SpeedChange s -> (length $ takeWhile ( l -> (1, limits)\n | otherwise -> (0, sort (l:limits))\n NoOvertakeSign | overtake -> (1, limits)\n _ -> (0, limits)\n speeds' = case event of\n SpeedChange s -> s:speeds\n SpeedSign _ -> [0]\n NoSpeedSign -> [0]\n _ -> speeds\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limits', speeds', overtake')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], 0, True, False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],Int,Bool,Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (limits, speed, nolimit, overtake) =\n let (ignore, limits') = case event of\n SpeedChange s | not nolimit -> (length l, sort h)\n where (l, h) = span ( l -> (1, limits)\n | otherwise -> (0, sort (l:limits))\n NoOvertakeSign | overtake -> (1, limits)\n _ -> (0, limits)\n speed' = case event of\n SpeedChange s -> s\n _ -> speed\n nolimit' = case event of\n NoSpeedSign -> True\n SpeedSign _ -> False\n _ -> nolimit\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limits', speed', nolimit', overtake')\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort, sortBy)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], [0], False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],[Int],Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (limits, speeds, overtake) =\n let (ignore, limits') = case event of\n SpeedChange s -> (length $ takeWhile ( l -> (1, limits)\n | otherwise -> (0, sort (l:limits))\n NoOvertakeSign | overtake -> (1, limits)\n _ -> (0, limits)\n speeds' = case event of\n SpeedChange s -> s:speeds\n SpeedSign _ -> take 1 speeds\n NoSpeedSign -> [0]\n _ -> speeds\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limits', speeds', overtake')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], 0, False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],Int,Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (limits, speed, overtake) =\n let (ignore, limits') = case event of\n SpeedChange s -> (length $ takeWhile ( l -> (1, limits)\n | otherwise -> (0, sort (l:limits))\n NoOvertakeSign | overtake -> (1, limits)\n _ -> (0, limits)\n speed' = case event of\n SpeedChange s -> s\n NoSpeedSign -> 0\n _ -> speed\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limits', speed', overtake')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (partition)\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents xs (0, [], 0)\n\nrunEvents :: [[Int]] -> (Int, [Int], Int) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (speed, speedSigns, overtakeSigns) =\n let (speed', speedSigns', overtakeSigns', ignoredSigns) = case event of\n [1, s] -> (speed, r, overtakeSigns, length l)\n where (l, r) = partition ( (speed, speedSigns, 0, overtakeSigns)\n [3, s] -> (speed, s:speedSigns, overtakeSigns, 0)\n [4] -> (speed, speedSigns, 0, 0)\n [5] -> (speed, [], overtakeSigns, 0)\n [6] -> (speed, speedSigns, overtakeSigns + 1, 0)\n in ignoredSigns + runEvents events (speed', speedSigns', overtakeSigns')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort, sortBy)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], [0], False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],[Int],Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (futureLimits, futureSpeeds, willOvertake) =\n let (signsIgnored, futureLimits') = case event of\n SpeedChange s -> (length $ takeWhile ( l -> (1, futureLimits)\n | otherwise -> (0, l:futureLimits)\n NoOvertakeSign | willOvertake -> (1, futureLimits)\n _ -> (0, futureLimits)\n futureSpeeds' = case event of\n SpeedChange s -> s:futureSpeeds\n NoSpeedSign -> [0]\n _ -> futureSpeeds\n willOvertake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> willOvertake\n in\n signsIgnored + runEvents events (futureLimits', futureSpeeds', willOvertake')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], 0, True, False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],Int,Bool,Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (limits, speed, nolimit, overtake) =\n let (ignore, limits') = case event of\n SpeedChange s | not nolimit -> (length l, sort h)\n where (l, h) = span ( l -> (1, limits)\n | otherwise -> (0, sort (l:limits))\n NoOvertakeSign | overtake -> (1, limits)\n _ -> (0, limits)\n speed' = case event of\n SpeedChange s -> s\n NoSpeedSign -> 0\n _ -> speed\n nolimit' = case event of\n NoSpeedSign -> True\n SpeedSign _ -> False\n _ -> nolimit\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limits', speed', nolimit', overtake')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events (999,0,False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> (Int,Int,Bool) -> Int\nrunEvents [] (_, _, _) = 0\nrunEvents (event:events) (limit, speed, overtake) =\n let ignore = case event of\n SpeedChange s | s > limit -> 1\n SpeedSign l | speed > l -> 1\n NoOvertakeSign | overtake -> 1\n _ -> 0\n limit' = case event of\n SpeedChange s | s > limit -> 0\n SpeedSign s | ignore == 0 -> s\n NoSpeedSign -> 999\n _ -> limit\n speed' = case event of\n SpeedChange s -> s\n NoSpeedSign -> 0\n _ -> speed\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limit', speed', overtake')\n \n\n\n"}, {"source_code": "-- 845D\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\ndata Event = SpeedChange Int\n | Overtake\n | SpeedSign Int\n | OvertakeSign\n | NoSpeedSign\n | NoOvertakeSign\n deriving (Show)\n\ntoEvent :: [Int] -> Event\ntoEvent (t:spd) = case t of\n 1 -> SpeedChange $ head spd\n 2 -> Overtake\n 3 -> SpeedSign $ head spd\n 4 -> OvertakeSign\n 5 -> NoSpeedSign\n 6 -> NoOvertakeSign\n\nmain = getLine >> (B.interact $ output . program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n output = B.pack . show\n\nprogram :: [[Int]] -> Int\nprogram xs = runEvents events ([], 0, False)\n where events = reverse $ map toEvent xs\n\nrunEvents :: [Event] -> ([Int],Int,Bool) -> Int\nrunEvents [] _ = 0\nrunEvents (event:events) (limits, speed, overtake) =\n let (ignore, limits') = case event of\n SpeedChange s -> (length l, sort h)\n where (l, h) = span ( l -> (1, limits)\n | otherwise -> (0, sort (l:limits))\n NoSpeedSign -> (0, [])\n NoOvertakeSign | overtake -> (1, limits)\n _ -> (0, limits)\n speed' = case event of\n SpeedChange s -> s\n NoSpeedSign -> 0\n _ -> speed\n overtake' = case event of\n Overtake -> True\n OvertakeSign -> False\n _ -> overtake\n in\n ignore + runEvents events (limits', speed', overtake')\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "-- http://codeforces.com/contest/845/problem/D\n\n{-# LANGUAGE CPP #-}\n\n#define eChangeSpeed 1\n#define eOvertakeOtherCar 2\n#define eSpeedLimit 3\n#define eOvertakeAllowed 4\n#define eNoSpeedLimit 5\n#define eNoOvertakeAllowed 6\n\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\n\ntype CurrentSpeed = Int\ntype SpeedLimit = Int\ntype NoOvertakeCount = Int\ntype NumIgnored = Int\ntype State = (CurrentSpeed, SpeedLimit, NoOvertakeCount, NumIgnored)\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n numEvents <- getInt\n events <- replicateM numEvents getInts\n let (_,_,_,answer) = solve events\n print answer\n\nstate0 = (0, maxBound :: Int, 0, 0)\n\nsolve :: [[Int]] -> State\nsolve events = foldl f state0 events where\n f (speed, speedLimit, noOvertakeCount, answer) event@(t:args) = case t of\n eChangeSpeed ->\n let newSpeed = head args\n in if newSpeed > speedLimit\n then (newSpeed, speedLimit, noOvertakeCount, answer + 1)\n else (newSpeed, speedLimit, noOvertakeCount, answer)\n eOvertakeOtherCar -> (speed, speedLimit, 0, if noOvertakeCount == 0 then answer else answer + noOvertakeCount)\n eSpeedLimit ->\n let newSpeedLimit = head args\n in if speed > newSpeedLimit\n then (speed, newSpeedLimit, noOvertakeCount, answer + 1)\n else (speed, newSpeedLimit, noOvertakeCount, answer)\n eOvertakeAllowed -> (speed, speedLimit, 0, answer)\n eNoSpeedLimit -> (speed, maxBound :: Int, noOvertakeCount, answer)\n eNoOvertakeAllowed -> (speed, speedLimit, noOvertakeCount + 1, answer)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE LambdaCase, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\ndata E = S !Int | O | L !Int | A | I | N deriving Show\n\napp = do\n n <- poi\n es <- replicateM n $ \\case { 1 -> fmap S poi; 2 -> return O; 3 -> fmap L poi; 4 -> return A; 5 -> return I; 6 -> return N } =<< poi\n return $ show $ solve es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = (\\(a, _, _, _) -> a) . foldl go (0, 0, [], 0)\n where\n go (!c, _, !ls, !o) (S s) = (c + length (takeWhile (< s) ls), s, ls, o)\n go (!c, !s, !ls, !o) O = (c + o, s, ls, 0)\n go (!c, !s, !ls, !o) (L l) = (c + fromEnum (s > l), s, l:ls, o)\n go (!c, !s, !ls, _) A = (c, s, ls, 0)\n go (!c, !s, _, !o) I = (c, s, [], o)\n go (!c, !s, !ls, !o) N = (c, s, ls, o + 1)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE LambdaCase, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\ndata E = S !Int | O | L !Int | A | I | N\n\napp = do\n n <- poi\n es <- replicateM n $ \\case { 1 -> fmap S poi; 2 -> return O; 3 -> fmap L poi; 4 -> return A; 5 -> return I; 6 -> return N } =<< poi\n return $ show $ solve es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = (\\(a, _, _, _) -> a) . foldl go (0, 0, [], 0)\n where\n go (!c, _, !ls, !o) (S s) = (c + length (takeWhile (< s) ls), s, ls, o)\n go (!c, !s, !ls, !o) O = (c + o, s, ls, o)\n go (!c, !s, !ls, !o) (L l) = (c + fromEnum (s > l), s, l:ls, o)\n go (!c, !s, !ls, _) A = (c, s, ls, 0)\n go (!c, !s, _, !o) I = (c, s, [], o)\n go (!c, !s, !ls, !o) N = (c, s, ls, o + 1)"}], "src_uid": "2dca11b202d7adbe22a404a52d627eed"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\nimport Data.List (foldl')\n\nm :: Integer\nm = 10^9 + 7\n\nmapMod :: [Integer] -> [Integer]\nmapMod = map (flip mod m)\n\ngetMuls :: Int -> Integer -> Array Int Integer\ngetMuls n k = listArray (1,n) $ mapMod $ scanl (\\a i -> a * (i + k - 1) `div` i) 1 [1..]\n\nsolve :: Integer -> Array Int Integer -> Array Int Integer\nsolve 0 a = a\nsolve k a = listArray (1,n) $ mapMod $ [foldl' (+) 0 [a ! j * b ! (i - j + 1) | j <- [1..i]] | i <- [1..n]]\n where\n n = snd $ bounds a\n b = getMuls n k\n\nprintA :: Array Int Integer -> IO ()\nprintA array = prints $ elems array\n where\n prints [] = return ()\n prints [x] = print x\n prints (x:xs) = putStr (show x ++ \" \") >> prints xs\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n array <- liftM (listArray (1, n) . map read . words) getLine\n printA $ solve (fromIntegral k) array\n", "positive_code": [{"source_code": "import Data.List \npr = 1000000007 :: Integer\npar l = [read x :: Int | x <- words l]\ninvv :: Integer -> Integer -> Integer\ninvv q 1 = 1\ninvv q p = ((n * q) + 1) `div` p\n where n = p - invv p (q `mod` p)\ninv x = invv pr x\n\nmultt :: Integer -> Integer -> Integer\nmultt x y = (x * y) `mod` pr\nmult x y = fromIntegral (multt (fromIntegral x) (fromIntegral y))\n\nsolve l1 l2 = intercalate \" \" [show r | r<-result]\n where n:k:[] = par l1\n a = par l2\n prep 0 = 1 \n prep x = (prep (x-1)) `mult` (k + x - 1) `mult` inv (fromIntegral x)\n pp = [prep g | g <- [n-1,n-2..0]]\n result = reverse [(sum u) `mod` pr | u <- [[x `mult` y | (x,y) <- zip a (drop j pp)] | j <- [0..n-1]]]\nmain = do\n l1 <- getLine\n l2 <- getLine\n putStrLn (solve l1 l2)"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\n\nm :: Integer\nm = 10^9 + 7\n\nsolve :: Integer -> Array Int Integer -> Array Int Integer\nsolve 0 a = a\nsolve k a = listArray (1,n) $ solve' 1 0 [1..n]\n where\n n = snd $ bounds a\n solve' :: Integer -> Integer -> [Int] -> [Integer]\n solve' _ acc [] = []\n solve' ckn acc (i:is) = acc' : solve' ckn' acc' is\n where\n i' = fromIntegral i\n ckn' = ckn * (k + i' - 1) `div` i' `mod` m\n acc' = (acc + ckn * (a ! i)) `mod` m\n\nprintA :: Array Int Integer -> IO ()\nprintA array = prints $ elems array\n where\n prints [] = return ()\n prints [x] = print x\n prints (x:xs) = putStr (show x ++ \" \") >> prints xs\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n array <- liftM (listArray (1, n) . map read . words) getLine\n printA $ solve (fromIntegral k) array\n"}], "src_uid": "584f7008e27dde53037396d2459efd84"} {"source_code": "i b f|b=[]|1>0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n cnt4 <- readInt\n cnt7 <- readInt\n cnt47 <- readInt\n cnt74 <- readInt\n return (cnt4, cnt7, cnt47, cnt74)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStrLn =<< solve . evalState parseInput <$> BS.getContents\n\ncheck4 cnt4 cnt7 cnt47 cnt74\n | cnt4 < 0 || cnt7 < 0 = False\n | cnt47 < 0 || cnt74 < 0 = False\n | cnt44 < 0 = False\n | cnt77 < 0 = False\n | cnt77 > 0 && cnt47 == 0 = False\n | delta < 0 || delta > 1 = False\n | otherwise = True\n where\n cnt44 = cnt4 - cnt74\n cnt77 = cnt7 - cnt47\n\n delta = cnt47 - cnt74 -- must be either 0 or 1\n\nsolve (cnt4, cnt7, cnt47, cnt74)\n | first4 = go (cnt4 - 1) cnt7 cnt47 cnt74 '4' \"4\"\n | first7 = go (cnt7 - 1) cnt4 cnt74 cnt47 '7' \"7\"\n | otherwise = \"-1\"\n where\n first4 = check4 (cnt4 - 1) cnt7 cnt47 cnt74\n first7 = check4 (cnt7 - 1) cnt4 cnt74 cnt47\n\n op '4' = '7'\n op '7' = '4'\n\n go 0 0 0 0 x xs = reverse xs\n go cnt4 cnt7 cnt47 cnt74 x xs\n | okay4 && okay7 = if x == '4' then go4 else go7\n | okay4 = go4\n | okay7 = go7\n | otherwise = error \"internal error\"\n where\n okay4 = check4 (cnt4 - 1) cnt7 cnt47 cnt74\n okay7 = check4 (cnt7 - 1) cnt4 cnt74 (cnt47 - 1)\n\n go4 = go (cnt4 - 1) cnt7 cnt47 cnt74 x (x:xs)\n go7 = go (cnt7 - 1) cnt4 cnt74 (cnt47 - 1) (op x) (op x:xs)\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Applicative\n\nmain = do [a1,a2,a3,a4] <- map read . words <$> getLine\n putStrLn $ solve [a1,a2,a3,a4]\n\nsolve :: [Int] -> String\nsolve [a1,a2,a3,a4]\n | a3 == a4 && a1 > a3 && a2 >= a3 = f 1 (a1-a3-1) ++ f 3 a3 ++ f 2 (a2-a3) ++ \"4\"\n | a3 == a4 && a1 == a3 && a2 > a4 = f 4 a4 ++ f 2 (a2-a4)\n | a3 == a4+1 && a1 >= a3 && a2 >= a3 = f 1 (a1-a3) ++ f 3 a3 ++ f 2 (a2-a3)\n | a3 == a4-1 && a1 >= a4 && a2 >= a4 = \"7\" ++ f 1 (a1-a4) ++ f 3 a3 ++ f 2 (a2-a4) ++ \"4\"\n | otherwise = \"-1\"\n\nf 1 n = concatMap show $ replicate n 4\nf 2 n = concatMap show $ replicate n 7\nf 3 n = concatMap show $ concat $ replicate n [4,7]\nf 4 n = concatMap show $ concat $ replicate n [7,4]"}, {"source_code": "i b f|b=[]|1>0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(abs x>1)$i(x<0)[\"74\"]++i(x>0)[\"47\"]\nm c d=map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<0=f\nq x=i(x<0)[][\"74\"]++i(x>0)[][\"47\"]\nm c d=i(abs(c-d)>1)[]$map(take(d+c+1).cycle)$q(c-d)\nf x m l=i(n<0)[]$[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=< getLine\n putStrLn $ solve [a1,a2,a3,a4]\n\nsolve :: [Int] -> String\nsolve [a1,a2,a3,a4]\n | a3 == a4 && a1 > a3 && a2 >= a3 = f 1 (a1-a3-1) ++ f 3 a3 ++ f 2 (a2-a3) ++ \"4\"\n | a3 == a4 && a1 == 1 && a2 >= 2 = \"747\" ++ f 2 (a2-2)\n | a3 == a4+1 && a1 >= a3 && a2 >= a3 = f 1 (a1-a3) ++ f 3 a3 ++ f 2 (a2-a3)\n | a3 == a4-1 && a1 >= a4 && a2 >= a4 = \"7\" ++ f 1 (a1-a4) ++ f 3 a3 ++ f 2 (a2-a4) ++ \"4\"\n | otherwise = \"-1\"\n\nf 1 n = concatMap show $ replicate n 4\nf 2 n = concatMap show $ replicate n 7\nf 3 n = concatMap show $ concat $ replicate n [4,7]\nf 4 n = concatMap show $ concat $ replicate n [7,4]"}, {"source_code": "import Control.Applicative\n\nmain = do [a1,a2,a3,a4] <- map read . words <$> getLine\n putStrLn $ solve [a1,a2,a3,a4]\n\nsolve :: [Int] -> String\nsolve [a1,a2,a3,a4]\n | a3 == a4 && a1 > a3 && a2 >= a3 = f 1 (a1-a3-1) ++ f 3 a3 ++ f 2 (a2-a3) ++ \"4\"\n | a3 == a4 && a1 == a3 && a2 > 2 = f 2 (a2-a3) ++ f 3 a3\n | a3 == a4+1 && a1 >= a3 && a2 >= a3 = f 1 (a1-a3) ++ f 3 a3 ++ f 2 (a2-a3)\n | a3 == a4-1 && a1 >= a4 && a2 >= a4 = \"7\" ++ f 1 (a1-a4) ++ f 3 a3 ++ f 2 (a2-a4) ++ \"4\"\n | otherwise = \"-1\"\n\nf 1 n = concatMap show $ replicate n 4\nf 2 n = concatMap show $ replicate n 7\nf 3 n = concatMap show $ concat $ replicate n [4,7]\nf 4 n = concatMap show $ concat $ replicate n [7,4]"}, {"source_code": "import Control.Applicative\n\nmain = do [a1,a2,a3,a4] <- map read . words <$> getLine\n putStrLn $ solve [a1,a2,a3,a4]\n\nsolve :: [Int] -> String\nsolve [a1,a2,a3,a4]\n | a3 == a4 && (a1>a4) && (a2>=a4) = concatMap show $ (replicate (a1-a4-1) 4)++((concat.replicate a3) [4,7])++(replicate (a2-a4) 7)++[4]\n | a3 == a4-1 && (a1>=a4) && (a2>=a4) = concatMap show $ [7]++(replicate (a1-a4) 4)++((concat.replicate a3) [4,7])++(replicate (a2-a4) 7)++[4]\n | a3 == a4+1 && (a1>=a3) && (a2>=a3) = concatMap show $ (replicate (a1-a3) 4)++((concat.replicate a3) [4,7])++(replicate (a2-a3) 7)\n | otherwise = \"-1\""}, {"source_code": "m c d|abs(c-d)>1=[]|1>0=[take(d+c+1).drop(max(d-c)0)$cycle\"47\"]\nf x m l|n<0=[]|1>0=[a++replicate n x++b]where(a,b)=break(==x)l;n=m-length(filter(==x)l)\ns[a,b,c,d]=f '4'a.reverse=<))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTArray)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust, fromMaybe, isNothing)\nimport Prelude hiding (getContents, getLine, lines, words)\n\ndata Result = Result { counts :: (Int, IntMap Int), best :: (Int64, Int) }\n\n(+.) :: Result -> Result -> Result\nr@(Result (l, m) a) +. r'@(Result (l', m') _)\n | l < l' = r' +. r\n | otherwise = IntMap.foldrWithKey merge r m'\n where\n merge :: Int -> Int -> Result -> Result\n merge color count (Result (l, m) a@(colorsSum, maxCount)) = Result (l', m') b\n where\n (old, m') = IntMap.insertLookupWithKey (\\k a b -> a + b) color count m\n count' = fromMaybe 0 old + count\n l' = if isNothing old then l + 1 else l\n\n b = case count' `compare` maxCount of\n GT -> (fromIntegral color :: Int64, count')\n EQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n LT -> a\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n] <- readInts <$> getLine\n cs <- listArray (1, n) . readInts <$> getLine\n es <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n let\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n ps = runSTArray $ do\n a <- newArray (1, n) 0\n let dfs w u = do\n writeArray a u w\n mapM_ (dfs u) . filter (/= w) $ g ! u\n dfs 0 1\n return a\n\n rs = listArray (1, n) $ map search [1..n]\n\n search u = foldl (+.) zero . map (rs !) . filter (/= (ps ! u)) $ g ! u\n where\n zero = Result (1, IntMap.singleton c 1) (fromIntegral c, 1)\n where c = cs ! u\n\n putStrLn . unwords . map show . map (fst . best) $ elems rs\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (getContents, getLine, lines, words)\n\ndata Result = Result { counts :: (Int, IntMap Int), best :: (Int64, Int) }\n\n(+.) :: Result -> Result -> Result\nr@(Result (l, m) a) +. r'@(Result (l', m') _)\n | l < l' = r' +. r\n | otherwise = IntMap.foldrWithKey merge r m'\n where\n merge :: Int -> Int -> Result -> Result\n merge color count (Result (l, m) a@(colorsSum, maxCount)) = Result (l', m') b\n where\n c = IntMap.findWithDefault 0 color m \n count' = c + count\n\n l' = if c == 0 then l + 1 else l\n m' = IntMap.insert color count' m\n\n b = case count' `compare` maxCount of\n GT -> (fromIntegral color :: Int64, count')\n EQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n LT -> a\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n] <- readInts <$> getLine\n cs <- listArray (1, n) . readInts <$> getLine\n es <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n let\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n ps = runSTArray $ do\n a <- newArray (1, n) 0\n let dfs w u = do\n writeArray a u w\n mapM_ (dfs u) . filter (/= w) $ g ! u\n dfs 0 1\n return a\n\n rs = listArray (1, n) $ map search [1..n]\n\n search u = foldl (+.) zero . map (rs !) . filter (/= (ps ! u)) $ g ! u\n where\n zero = Result (1, IntMap.singleton c 1) (fromIntegral c, 1)\n where c = cs ! u\n\n putStrLn . unwords . map show . map (fst . best) $ elems rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTArray)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.Int (Int64)\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust, fromMaybe, isNothing)\nimport Prelude hiding (getContents, getLine, lines, words)\n\ndata Result = Result { counts :: Map Int Int, best :: (Int64, Int) }\n\n(+.) :: Result -> Result -> Result\nr@(Result m a) +. r'@(Result m' _)\n | Map.size m < Map.size m' = r' +. r\n | otherwise = Map.foldrWithKey merge r m'\n where\n merge :: Int -> Int -> Result -> Result\n merge color count (Result m a@(colorsSum, maxCount)) = Result m' b\n where\n (old, m') = Map.insertLookupWithKey (\\k a b -> a + b) color count m\n count' = fromMaybe 0 old + count\n\n b = case count' `compare` maxCount of\n GT -> (fromIntegral color :: Int64, count')\n EQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n LT -> a\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n] <- readInts <$> getLine\n cs <- listArray (1, n) . readInts <$> getLine\n es <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n let\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n ps = runSTArray $ do\n a <- newArray (1, n) 0\n let dfs w u = do\n writeArray a u w\n mapM_ (dfs u) . filter (/= w) $ g ! u\n dfs 0 1\n return a\n\n rs = listArray (1, n) $ map search [1..n]\n\n search u = foldl (+.) zero . map (rs !) . filter (/= (ps ! u)) $ g ! u\n where\n zero = Result (Map.singleton c 1) (fromIntegral c, 1)\n where c = cs ! u\n\n putStrLn . unwords . map show . map (fst . best) $ elems rs\n"}, {"source_code": "{- ok -}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, array, listArray, elems, (!))\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.Int (Int64)\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust, fromMaybe)\nimport Prelude hiding (getContents, getLine, lines, words)\n\ndata Result = Result { counts :: Map Int Int, best :: (Int64, Int) }\n\n(+.) :: Result -> Result -> Result\nr@(Result m a) +. r'@(Result m' _)\n | Map.size m < Map.size m' = r' +. r\n | otherwise = Map.foldrWithKey merge r m'\n where\n merge :: Int -> Int -> Result -> Result\n merge color count (Result m a@(colorsSum, maxCount)) = Result m' b\n where\n (old, m') = Map.insertLookupWithKey (\\k a b -> a + b) color count m\n count' = fromMaybe 0 old + count\n\n b = case count' `compare` maxCount of\n GT -> (fromIntegral color :: Int64, count')\n EQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n LT -> a\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n] <- readInts <$> getLine\n cs <- listArray (1, n) . readInts <$> getLine\n es <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n let\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n ps = array (1, n) $ dfs 0 [] 1\n where\n dfs w ps u = (u,w) : (foldl (dfs u) ps . filter (/= w) $ g ! u)\n\n rs = listArray (1, n) $ map search [1..n]\n\n search u = foldl (+.) zero . map (rs !) . filter (/= (ps ! u)) $ g ! u\n where\n zero = Result (Map.singleton c 1) (fromIntegral c, 1)\n where c = cs ! u\n\n putStrLn . unwords . map show . map (fst . best) $ elems rs\n"}, {"source_code": "{- ok -}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTArray)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust, fromMaybe, isNothing)\nimport Prelude hiding (getContents, getLine, lines, words)\n\ndata Result = Result { counts :: (Int, IntMap Int), best :: (Int64, Int) }\n\n(+.) :: Result -> Result -> Result\nr@(Result (l, m) a) +. r'@(Result (l', m') _)\n | l < l' = r' +. r\n | otherwise = IntMap.foldrWithKey merge r m'\n where\n merge :: Int -> Int -> Result -> Result\n merge color count (Result (l, m) a@(colorsSum, maxCount)) = Result (l', m') b\n where\n (old, m') = IntMap.insertLookupWithKey (\\k a b -> a + b) color count m\n count' = fromMaybe 0 old + count\n l' = if isNothing old then l + 1 else l\n\n b = case count' `compare` maxCount of\n GT -> (fromIntegral color :: Int64, count')\n EQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n LT -> a\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n] <- readInts <$> getLine\n cs <- listArray (1, n) . readInts <$> getLine\n es <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n let\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n ps = runSTArray $ do\n a <- newArray (1, n) 0\n let dfs w u = do\n writeArray a u w\n mapM_ (dfs u) . filter (/= w) $ g ! u\n dfs 0 1\n return a\n\n rs = listArray (1, n) $ map search [1..n]\n\n search u = foldl (+.) zero . map (rs !) . filter (/= (ps ! u)) $ g ! u\n where\n zero = Result (1, IntMap.singleton c 1) (fromIntegral c, 1)\n where c = cs ! u\n\n putStrLn . unwords . map show . map (fst . best) $ elems rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust, fromMaybe, isNothing)\nimport Data.Int (Int64)\n-- import Debug.Trace (trace)\n\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\n\nimport Prelude hiding (getContents, getLine, lines, words)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n\t[n] <- readInts <$> getLine\n\tcs <- readInts <$> getLine\n\tes <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n\tlet\n\t\tcs' = listArray (1, n) cs\n\n\t\tg = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n\t\tps = runSTArray $ do\n\t\t\tps <- newArray (1, n) 0\n\t\t\tlet dfs w u = do\n\t\t\t\twriteArray ps u w\n\t\t\t\tmapM_ (dfs u) . filter (/= w) $ g ! u\n\t\t\tdfs 0 1\n\t\t\treturn ps\n\n\t\tas = listArray (1, n) $ map search [1..n]\n\n\t\tsearch :: Int -> ((Int, IntMap Int), (Int64, Int))\n\t\tsearch u = -- trace (\"u = \" ++ show u ++ \" r = \" ++ show r ++ \" z = \" ++ show zero) $\n\t\t\t\tr\n\t\t\twhere\n\t\t\t\tr = foldl merge zero . filter (/= (ps ! u)) $ g ! u\n\n\t\t\t\tzero = ((1, IntMap.singleton c 1), (fromIntegral c :: Int64, 1)) -- (colors sum, max count)\n\t\t\t\t\twhere c = cs' ! u\n\n\t\t\t\tmerge state@((l, m), best) v = r\n\t\t\t\t\twhere\n\t\t\t\t\t\tr = IntMap.foldrWithKey merge' zero m2\n\t\t\t\t\t\tstate'@((l', m'), best') = as ! v\n\n\t\t\t\t\t\t(zero, m2) = if l > l' then (state, m') else (state', m)\n\n\t\t\t\t\t\tmerge' color count ((l, m), best@(colorsSum, maxCount)) = -- trace (\"n = \" ++ show (color, count) ++ \" best' = \" ++ show best') $\n\t\t\t\t\t\t\t\t((l', m'), best')\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tcount1 = IntMap.findWithDefault 0 color m \n\n\t\t\t\t\t\t\t\tl' = if count1 == 0 then l + 1 else l\n\t\t\t\t\t\t\t\tcount' = count1 + count\n\t\t\t\t\t\t\t\tm' = IntMap.insert color count' m\n\n\t\t\t\t\t\t\t\tbest' = case compare count' maxCount of\n\t\t\t\t\t\t\t\t\tGT -> (fromIntegral color :: Int64, count')\n\t\t\t\t\t\t\t\t\tEQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n\t\t\t\t\t\t\t\t\tLT -> best\n\n\tputStrLn . unwords . map show . map (fst . snd) $ elems as\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (runSTArray)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (getContents, getLine, lines, words)\n\ndata Result = Result { counts :: (Int, IntMap Int), best :: (Int64, Int) }\n\n(+.) :: Result -> Result -> Result\nr@(Result (l, m) a) +. r'@(Result (l', m') _)\n | l < l' = r' +. r\n | otherwise = IntMap.foldrWithKey merge r m'\n where\n merge :: Int -> Int -> Result -> Result\n merge color count (Result (l, m) a@(colorsSum, maxCount)) = Result (l', m') b\n where\n c = IntMap.findWithDefault 0 color m \n count' = c + count\n\n l' = if c == 0 then l + 1 else l\n m' = IntMap.insert color count' m\n\n b = case count' `compare` maxCount of\n GT -> (fromIntegral color :: Int64, count')\n EQ -> (colorsSum + (fromIntegral color :: Int64), maxCount)\n LT -> a\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n] <- readInts <$> getLine\n cs <- listArray (1, n) . readInts <$> getLine\n es <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n let\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n ps = runSTArray $ do\n a <- newArray (1, n) 0\n let dfs w u = do\n writeArray a u w\n mapM_ (dfs u) . filter (/= w) $ g ! u\n dfs 0 1\n return a\n\n rs = listArray (1, n) $ map search [1..n]\n\n search u = foldl (+.) zero . map (rs !) . filter (/= (ps ! u)) $ g ! u\n where\n zero = Result (1, IntMap.singleton c 1) (fromIntegral c, 1)\n where c = cs ! u\n\n putStrLn . unwords . map show . map (fst . best) $ elems rs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_)\nimport Data.Array (accumArray, listArray, elems, (!), array)\nimport Data.ByteString.Char8 (getContents, getLine, lines, readInt, words)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\nimport Data.Maybe (fromJust, fromMaybe, isNothing)\n-- import Debug.Trace (trace)\n\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\n\nimport Prelude hiding (getContents, getLine, lines, words)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n\t[n] <- readInts <$> getLine\n\tcs <- readInts <$> getLine\n\tes <- map ((\\[a, b] -> (a, b)) . readInts) . lines <$> getContents\n\n\tlet\n\t\tcs' = listArray (1, n) cs\n\n\t\tg = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n\t\tps = runSTArray $ do\n\t\t\tps <- newArray (1, n) 0\n\t\t\tlet dfs w u = do\n\t\t\t\twriteArray ps u w\n\t\t\t\tmapM_ (dfs u) . filter (/= w) $ g ! u\n\t\t\tdfs 0 1\n\t\t\treturn ps\n\n\t\tas = listArray (1, n) $ map search [1..n]\n\n\t\tsearch :: Int -> ((Int, IntMap Int), (Int, Int))\n\t\tsearch u = -- trace (\"u = \" ++ show u ++ \" r = \" ++ show r ++ \" z = \" ++ show zero) $\n\t\t\t\tr\n\t\t\twhere\n\t\t\t\tr = foldl merge zero . filter (/= (ps ! u)) $ g ! u\n\n\t\t\t\tzero = ((1, IntMap.singleton c 1), (c, 1)) -- (colors sum, max count)\n\t\t\t\t\twhere c = cs' ! u\n\n\t\t\t\tmerge state@((l, m), best) v = r\n\t\t\t\t\twhere\n\t\t\t\t\t\tr = IntMap.foldrWithKey merge' zero m2\n\t\t\t\t\t\tstate'@((l', m'), best') = as ! v\n\n\t\t\t\t\t\t(zero, m2) = \n\t\t\t\t\t\t\tif l > l' then (state, m') else (state', m)\n\n\t\t\t\t\t\tmerge' color count ((l, m), best@(colorsSum, maxCount)) = -- trace (\"n = \" ++ show (color, count) ++ \" best' = \" ++ show best') $\n\t\t\t\t\t\t\t\t((l', m'), best')\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tr = IntMap.lookup color m \n\n\t\t\t\t\t\t\t\tl' = if isNothing r then l + 1 else l\n\t\t\t\t\t\t\t\tcount' = fromMaybe 0 r + count\n\t\t\t\t\t\t\t\tm' = IntMap.insert color count' m\n\n\t\t\t\t\t\t\t\tbest' = case compare count' maxCount of\n\t\t\t\t\t\t\t\t\tGT -> (color, count')\n\t\t\t\t\t\t\t\t\tEQ -> (colorsSum + color, maxCount)\n\t\t\t\t\t\t\t\t\tLT -> best\n\n\tputStrLn . unwords . map show . map (fst . snd) $ elems as\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (accumArray, listArray, elems, (!))\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Tuple (swap)\n-- import Debug.Trace (trace)\n\nmain = do\n\t[n] <- map read . words <$> getLine :: IO [Int]\n\tcs <- map read . words <$> getLine\n\tes <- map ((\\[a, b] -> (a, b)) . map read . words) . lines <$> getContents\n\n\tlet\n\t\tcs' = listArray (1, n) cs\n\t\tg = accumArray (flip (:)) [] (1, n) $ es -- ++ map swap es\n\n\t\tas = listArray (1, n) $ map search [1..n]\n\n\t\tsearch :: Int -> (IntMap Int, (Int, Int))\n\t\tsearch u = -- trace (\"u = \" ++ show u ++ \" r = \" ++ show r ++ \" z = \" ++ show zero) $\n\t\t\t\tr\n\t\t\twhere\n\t\t\t\tr = foldl merge zero $ g ! u\n\n\t\t\t\tzero = (IntMap.singleton c 1, (c, 1)) -- (colors sum, max count)\n\t\t\t\t\twhere c = cs' ! u\n\n\t\t\t\t-- m - counts\n\t\t\t\tmerge state@(m, best) v = foldl merge' zero $ IntMap.assocs m2\n\t\t\t\t\twhere\n\t\t\t\t\t\tstate'@(m', best') = as ! v\n\n\t\t\t\t\t\t(zero, m2) = \n\t\t\t\t\t\t\tif IntMap.size m > IntMap.size m' then (state, m') else (state', m)\n\n\t\t\t\t\t\tmerge' (m, best@(colorsSum, maxCount)) (color, count) = -- trace (\"n = \" ++ show (color, count) ++ \" best' = \" ++ show best') $\n\t\t\t\t\t\t\t\t(m', best')\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tcount' = (IntMap.findWithDefault 0 color m) + count\n\t\t\t\t\t\t\t\tm' = IntMap.insert color count' m\n\n\t\t\t\t\t\t\t\tbest' = case compare count' maxCount of\n\t\t\t\t\t\t\t\t\tGT -> (color, count')\n\t\t\t\t\t\t\t\t\tEQ -> (colorsSum + color, maxCount)\n\t\t\t\t\t\t\t\t\tLT -> best\n\n\tputStrLn . unwords . map show . map (fst . snd) $ elems as\n"}], "src_uid": "fe01ddb5bd5ef534a6a568adaf738151"} {"source_code": "import Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n\ndata State =\n State {\n stateLsum :: Integer,\n stateLs :: [Integer],\n stateRsum :: Integer,\n stateRs :: [Integer]\n }\n\nnumHugs n = n*(n+1) `div` 2\n\n_solve x acc curr (State lsum ls rsum rs)\n | (rsum - lsum >= x) =\n let lval:ltail = ls\n excess = rsum - lsum - x\n actual = curr - numHugs excess\n ncurr = curr - numHugs lval\n in _solve x (max actual acc) ncurr $ State (lsum + lval) ltail rsum rs\n | otherwise =\n case rs of\n [] -> acc\n rval:rtail -> _solve x acc (curr + numHugs rval) $ State lsum ls (rsum + rval) rtail\n\nsolve x days =\n let days2 = (\\x -> x ++ x) $ reverse days\n in _solve x 0 0 $ State 0 days2 0 days2\n\nmain = do\n input <- getContents\n let (_:xStr:tokens) = split input\n x = read xStr :: Integer\n days = read <$> tokens :: [Integer]\n res = solve x days\n putStrLn $ show res\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = do\n (n:x:_) <- map read . words <$> getLine\n ds <- cycle . reverse . map read . words <$> getLine\n let (total, extra, endds) = initial x ds\n print $ maximum $ take (2 * fromInteger n) $ hugs extra total ds endds\n\ninitial x (d:ds)\n | x < d = (triangle d - triangle (d - x), d - x, ds)\n | otherwise = (\\(a, b, c) -> (a + triangle (min d x), b, c)) $ initial (x - d) ds\n\nhugs extra total (d:ds) endds = total : hugs extra' total' ds endds'\n where\n dv = triangle d\n (total', extra', endds')\n | d <= extra = (total - dv + triangle extra - triangle (extra - d), extra - d, endds)\n | otherwise =\n let (a, b, c) = initial (d - extra) endds\n in (total - dv + triangle extra + a, b, c)\n\ntriangle x = (x * (x + 1)) `div` 2"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = do\n (n:x:_) <- map read . words <$> getLine\n ds <- map read . words <$> getLine\n let y = (`mod` sum ds) $ subtract x $ snd $ maximum $ zip ds $ scanl1 (+) ds\n print $ hugs (y + x) (cycle ds) - hugs y (cycle ds)\n\nhugs x (d:ds)\n | x <= 0 = 0\n | otherwise = triangle (min x d) + hugs (x - d) ds\n\ntriangle x = (x * (x + 1)) `div` 2"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = do\n (n:x:_) <- map read . words <$> getLine\n ds <- cycle . reverse . map read . words <$> getLine\n let (total, extra, endds) = initial x ds\n print $ maximum $ take (2 * n) $ hugs 0 x extra total ds endds\n\ninitial x (d:ds)\n | x < d = (triangle d - triangle (d - x), d - x, ds)\n | otherwise = (\\(a, b, c) -> (a + triangle (min d x), b, c)) $ initial (x - d) ds\n\nhugs start end extra total (d:ds) endds = total : hugs start' end' extra' total' ds endds'\n where\n start' = start + d\n end' = end + d\n dv = triangle d\n (total', extra', endds')\n | dv <= extra = (total - dv + triangle extra - triangle (extra - d), extra - d, endds)\n | otherwise =\n let (a, b, c) = initial (d - extra) endds\n in (total - dv + triangle extra + a, b, c)\n\ntriangle x = (x * (x + 1)) `div` 2"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = do\n (n:x:_) <- map read . words <$> getLine\n ds <- cycle . reverse . map read . words <$> getLine\n let (total, extra, endds) = initial x ds\n print $ maximum $ take (2 * fromInteger n) $ hugs 0 x extra total ds endds\n\ninitial x (d:ds)\n | x < d = (triangle d - triangle (d - x), d - x, ds)\n | otherwise = (\\(a, b, c) -> (a + triangle (min d x), b, c)) $ initial (x - d) ds\n\nhugs start end extra total (d:ds) endds = total : hugs start' end' extra' total' ds endds'\n where\n start' = start + d\n end' = end + d\n dv = triangle d\n (total', extra', endds')\n | dv <= extra = (total - dv + triangle extra - triangle (extra - d), extra - d, endds)\n | otherwise =\n let (a, b, c) = initial (d - extra) endds\n in (total - dv + triangle extra + a, b, c)\n\ntriangle x = (x * (x + 1)) `div` 2"}, {"source_code": "import Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n\ndata State =\n State {\n stateLsum :: Int,\n stateLs :: [Int],\n stateRsum :: Int,\n stateRs :: [Int]\n }\n\nnumHugs n = n*(n+1) `div` 2\n\n_solve x acc curr (State lsum ls rsum rs)\n | (rsum - lsum >= x) =\n let lval:ltail = ls\n excess = rsum - lsum - x\n actual = curr - numHugs excess\n ncurr = curr - numHugs lval\n in _solve x (max actual acc) ncurr $ State (lsum + lval) ltail rsum rs\n | otherwise =\n case rs of\n [] -> acc\n rval:rtail -> _solve x acc (curr + numHugs rval) $ State lsum ls (rsum + rval) rtail\n\nsolve x days =\n let days2 = (\\x -> x ++ x) $ reverse days\n in _solve x 0 0 $ State 0 days2 0 days2\n\nmain = do\n input <- getContents\n let (_:xStr:tokens) = split input\n x = read xStr :: Int\n days = read <$> tokens :: [Int]\n res = solve x days\n putStrLn $ show res\n"}], "src_uid": "9ba374e20305d93ba42ef152e2cad5b5"} {"source_code": "import Control.Applicative\nimport qualified Data.IntMap as I\n\ncheck rr cc r1 c1 a = any (==1) $ [product (map (\\z->I.findWithDefault 0 z a) [ r*1000+c, (r+1)*1000+c, r*1000+c+1, (r+1)*1000+c+1])|r<-[max 1 (r1-1).. min rr (r1+1)],c<-[max 1 (c1-1)..min cc (c1+1)]]\n\n\nprocess r c [] a co = 0\nprocess r c ([r1,c1]:ss) a co | check r c r1 c1 a1 = co\n | otherwise = process r c ss a1 (co+1)\n\twhere a1 = I.insert (r1*1000+c1) (1::Int) a\n\n\nmain= do\t \n\t[r,c,n]<-map read. words <$> getLine ::IO [Int]\n\ts<- map (map read). map words . lines <$> getContents::IO [[Int]] \n\tlet a= I.empty\n\tprint $ process r c s a 1\n\t\n \n\t \n\t ", "positive_code": [{"source_code": "import qualified Data.Map as M\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nshowBI = B.pack . show\nreadBI = fst . fromJust . B.readInt\nmain = B.interact $ showBI . f . map (map readBI . B.words) . B.lines\n--main = interact $ show . f . map (map read . words) . lines\nf (([n,m,k]):q) = ((1+) . length . takeWhile (==False) . reverse . fst $ foldl h ([],M.empty) q)`mod`(k+1)\nh (l,m) [i,j] = ((or . map (\\l' -> and . map (flip M.member m) $ l') $ cl):l,M.insert (i,j) 1 m)\n where cl = [l1,l2,l3,l4]\n l1 = [(i,j-1),(i-1,j-1),(i-1,j)]\n l2 = [(i-1,j),(i-1,j+1),(i,j+1)]\n l3 = [(i,j+1),(i+1,j+1),(i+1,j)]\n l4 = [(i+1,j),(i+1,j-1),(i,j-1)]\n"}, {"source_code": "import qualified Data.Map as M\nmain = interact $ show . f . map (map read . words) . lines\nf (([n,m,k]):q) = ((1+) . length . takeWhile (==False) . reverse . fst $ foldl h ([],M.empty) q)`mod`(k+1)\nh (l,m) [i,j] = ((or . map (\\l' -> and . map (flip M.member m) $ l') $ cl):l,M.insert (i,j) 1 m)\n where cl = [l1,l2,l3,l4]\n l1 = [(i,j-1),(i-1,j-1),(i-1,j)]\n l2 = [(i-1,j),(i-1,j+1),(i,j+1)]\n l3 = [(i,j+1),(i+1,j+1),(i+1,j)]\n l4 = [(i+1,j),(i+1,j-1),(i,j-1)]\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\nmain = interact $ show . f . map (map read . words) . lines\nf (([n,m,k]):q) = ((1+) . length . takeWhile (==False) . reverse . fst $ foldl' h ([],M.empty) q)`mod`(k+1)\nh (l,m) [i,j] = ((or . map (\\l' -> and . map (flip M.member m) $ l') $ cl):l,M.insert (i,j) 1 m)\n where cl = [l1,l2,l3,l4]\n l1 = [(i,j-1),(i-1,j-1),(i-1,j)]\n l2 = [(i-1,j),(i-1,j+1),(i,j+1)]\n l3 = [(i,j+1),(i+1,j+1),(i+1,j)]\n l4 = [(i+1,j),(i+1,j-1),(i,j-1)]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetIntList :: IO [Int]\ngetIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, m, k] <- getIntList\n ps <- replicateM k getIntList\n print $ sol n m k ps\n\nsol :: (Ix a, Ord a, Num a, Enum a) => a -> a -> a -> [[a]] -> a\nsol n m k ps = if null rs then 0 else minimum rs\n where\n ts = map (\\[p,q] -> (p,q)) ps\n ar = accumArray ac 0 ((1,1),(n,m)) $ zipWith (,) ts [1..k]\n ac e a = if e==0 then a else min e a\n es = [ev ar (p,q) | (p,q)<-ts, p0]\n rs = map snd $ filter ((0<) . fst) es\n\nev :: (Ix t, Ord t, Num t) => Array (t, t) t -> (t, t) -> (t, t)\nev ar (p,q) = (minimum a4, maximum a4)\n where a4 = [ar!(p,q), ar!(p+1,q), ar!(p,q+1), ar!(p+1,q+1)]\n\n{-\nlet ps = [[1,1], [1,2], [2,1], [2,2]]\nsol 2 2 4 ps ==> 4\n\nlet ps = [[2,3], [2,2], [1,3], [2,2], [1,2], [1,1]]\nsol 2 3 6 ps ==> 6\n\nlet ps = [[2,3], [1,2], [1,1], [4,1], [3,1], [5,3], [3,2]]\nsol 5 3 7 ps ==> 0\n-}"}, {"source_code": "import qualified Data.Set as S\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve ([_, _, _] : ijs) = go 1 S.empty ijs\n where go t s ([i, j] : ij) | any (all (`S.member`s)) ij' = t\n | otherwise = go (t + 1) (S.insert (i, j) s) ij\n where ij' = [ [ (i - 1, j), (i - 1, j - 1), (i, j - 1) ] ,\n [ (i - 1, j), (i - 1, j + 1), (i, j + 1) ] ,\n [ (i + 1, j), (i + 1, j - 1), (i, j - 1) ] ,\n [ (i + 1, j), (i + 1, j + 1), (i, j + 1) ] ]\n go _ _ _ = 0\nsolve _ = undefined\n"}, {"source_code": "import qualified Data.Set as S\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve ([_, _, _] : ijs) = go 1 S.empty ijs\n where go t s ([i, j] : ij) | any (all (`S.member`s))\n [ [ (i - 1, j), (i - 1, j - 1), (i, j - 1) ] ,\n [ (i - 1, j), (i - 1, j + 1), (i, j + 1) ] ,\n [ (i + 1, j), (i + 1, j - 1), (i, j - 1) ] ,\n [ (i + 1, j), (i + 1, j + 1), (i, j + 1) ] ]\n = t\n | otherwise = go (t + 1) (S.insert (i, j) s) ij\n go _ _ _ = 0\nsolve _ = undefined\n"}, {"source_code": "import qualified Data.Set as S\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Int\nsolve = go 1 S.empty\n where go t s ([i, j] : ij) | any (all (`S.member`s)) ij' = t\n | otherwise = go (t + 1) (S.insert (i, j) s) ij\n where ij' = [ [ (i - 1, j), (i - 1, j - 1), (i, j - 1) ] ,\n [ (i - 1, j), (i - 1, j + 1), (i, j + 1) ] ,\n [ (i + 1, j), (i + 1, j - 1), (i, j - 1) ] ,\n [ (i + 1, j), (i + 1, j + 1), (i, j + 1) ] ]\n go _ _ _ = 0\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetIntList :: IO [Int]\ngetIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, m, k] <- getIntList\n ps <- replicateM n getIntList\n print $ sol n m k ps\n\nsol :: (Ix a, Ord a, Num a, Enum a) => a -> a -> a -> [[a]] -> a\nsol n m k ps = if null rs then 0 else minimum rs\n where\n ts = map (\\[p,q] -> (p,q)) ps\n ar = accumArray ac 0 ((1,1),(n,m)) $ zipWith (,) ts [1..k]\n ac e a = if e==0 then a else min e a\n es = [ev ar (p,q) | (p,q)<-ts, p0]\n rs = map snd $ filter ((0<) . fst) es\n\nev :: (Ix t, Ord t, Num t) => Array (t, t) t -> (t, t) -> (t, t)\nev ar (p,q) = (minimum a4, maximum a4)\n where a4 = [ar!(p,q), ar!(p+1,q), ar!(p,q+1), ar!(p+1,q+1)]\n\n{-\nlet ps = [[1,1], [1,2], [2,1], [2,2]]\nsol 2 2 4 ps ==> 4\n\nlet ps = [[2,3], [2,2], [1,3], [2,2], [1,2], [1,1]]\nsol 2 3 6 ps ==> 6\n\nlet ps = [[2,3], [1,2], [1,1], [4,1], [3,1], [5,3], [3,2]]\nsol 5 3 7 ps ==> 0\n-}"}], "src_uid": "0dc5469831c1d5d34aa3b7b172e3237b"} {"source_code": "main=interact$unlines.map(unwords.map show.(\\n->[2*(i+n)|i<-[1..n]]).read).drop 1.words", "positive_code": [{"source_code": "\nmain =\n interact $\n unlines . map (unwords . map show . (\\n -> [2*(i+n) | i <- [1..n]]) . read) . drop 1 . words\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n words >>> drop 1 >>> map (read >>> solve >>> map show >>> unwords) >>> unlines\n\nsolve :: Int -> [Int]\nsolve n = [2 * (i + n) | i <- [1 .. n]]\n"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Foldable\nimport Control.Monad (replicateM)\n\nnumbers :: [String] -> [Int]\nnumbers array = (map read array :: [Int])\n\nanswers n = [ i | i <- [4*n,4*n-2..2*n+2] ]\n\nconvert :: [Int] -> String\nconvert array = id $ intercalate \" \" [ id show n | n<-array]\n\nmain = do\n n <- getLine\n array <- replicateM (read n) getLine\n mapM_ putStrLn $ map convert (map answers $ numbers array)\n putStrLn $ id \"\""}], "negative_code": [], "src_uid": "cf4d8a5caa37def0b7c0007743139e36"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.Bits\r\nimport Data.Char\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readMany :: IO [Int]\r\n s <- getLine\r\n let full = (1 `shiftL` k) - 1\r\n sa = listArray (1, n) $ map (subtract 97 . ord) s :: UArray Int Int\r\n wild = ord '?' - 97\r\n ans = do\r\n nxt :: STUArray s (Int, Int) Int <- newArray ((0, 1), (k - 1, n)) 0\r\n cntLast :: STUArray s Int Int <- newArray (0, 1) 0\r\n let ok :: Int -> ST s Bool\r\n ok x = do\r\n forM_ [0.. k - 1] $ \\j -> do\r\n wrA cntLast 0 0\r\n wrA cntLast 1 (n + 1)\r\n forM_ [n, n - 1 .. 1] $ \\i -> do\r\n if sa!i == j || sa!i == wild\r\n then rdA cntLast 0 >>= (wrA cntLast 0 . (+1))\r\n else wrA cntLast 0 0\r\n last <- rdA cntLast 0\r\n when (last >= x) $ wrA cntLast 1 (i + x - 1)\r\n rdA cntLast 1 >>= wrA nxt (j, i)\r\n nxtf :: UArray (Int, Int) Int <- unsafeFreeze nxt\r\n dp :: STUArray s Int Int <- newArray (0, full) 0\r\n forM_ [1..full] $ \\i -> do\r\n let js = filter (testBit i) [0 .. k - 1]\r\n vs <- mapM (rdA dp . clearBit i) js\r\n let get j v | v + 1 > n = n + 1\r\n | otherwise = nxtf!(j, v + 1)\r\n wrA dp i $ minimum $ zipWith get js vs\r\n (<= n) <$> rdA dp full\r\n subtract 1 <$> lowerBoundM (fmap not . ok) 1 (n + 1)\r\n print $ runST ans\r\n\r\nrdA a = readArray a\r\nwrA a = writeArray a\r\n\r\nlowerBoundM :: (Monad m, Integral t) => (t -> m Bool) -> t -> t -> m t\r\nlowerBoundM f l h\r\n | l >= h = return l\r\n | otherwise = do\r\n v <- f m\r\n if v then lowerBoundM f l m else lowerBoundM f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n", "positive_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM, when,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport Data.Word\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n foldl', intersect, isPrefixOf, nub,\n sort, sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (for, forM)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\nimport GHC.IO.Handle (hDuplicateTo)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> fst . fromJust\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> fst . fromJust\n\nreadIntegralB8 :: (Integral a) => B8.ByteString -> a\nreadIntegralB8 = B8.readInteger >>> fst . fromJust >>> fromInteger\n\n\nsolve :: Int -> Int -> B8.ByteString -> Int\nsolve n k bs = ST.runST $ subSolve 0 n\n where\n cntA :: UA.UArray (Int, Int) Int\n cntA = STA.runSTUArray $ do\n cntM <- MA.newArray ((0, 0), (k - 1, n)) 0 :: ST.ST s (STA.STUArray s (Int, Int) Int )\n forM_ [0 .. k - 1] $ \\ci -> do\n forM_ (reverse [0 .. n - 1]) $ \\i -> do\n let currentC = bs `B8.index` i\n when ((currentC == '?') || (currentC == chr (ci + ord 'a'))) $ do\n MA.readArray cntM (ci, i + 1) >>= (MA.writeArray cntM (ci, i) . (+1))\n return cntM\n\n toK :: Int\n toK = 1 `shiftL` k\n\n subSolve :: Int -> Int -> ST.ST s Int\n subSolve l r | l < r = do\n let c = (l + r + 1) `div` 2\n isSolvable <- canSolve c\n if isSolvable\n then subSolve c r\n else subSolve l (c - 1)\n subSolve l r | l <= r = return l\n\n canSolve :: Int -> ST.ST s Bool\n canSolve len = do\n dpM <- dpA\n index <- MA.readArray dpM (toK - 1)\n return $ index < n + 1\n where\n nextCntA :: ST.ST s (STA.STUArray s (Int, Int) Int)\n nextCntA = do\n nextCntM <- MA.newArray ((0, 0), (k - 1, n + 1)) (n + 1) :: ST.ST s (STA.STUArray s (Int, Int) Int)\n forM_ [0 .. k - 1] $ \\ci -> do\n forM_ (reverse [0 .. n - 1]) $ \\i -> do\n let curLen = cntA UA.! (ci, i)\n nextValue <- if curLen < len\n then MA.readArray nextCntM (ci, i + 1)\n else return $ i + len\n MA.writeArray nextCntM (ci, i) nextValue\n return nextCntM\n\n dpA :: ST.ST s (STA.STUArray s Int Int)\n dpA = do\n dpM <- MA.newArray (0, toK - 1) 0 :: ST.ST s (STA.STUArray s Int Int)\n nextCntM <- nextCntA\n forM_ [1 .. toK - 1] $ \\mask -> do\n connections <- forM [0 .. k - 1] $ \\bIndex -> do\n let bValue = (toK - 1) .&. (1 `shiftL` bIndex)\n let prevMask = mask `xor` bValue\n prevValue <- MA.readArray dpM prevMask\n nextIndex <- MA.readArray nextCntM (bIndex, prevValue)\n\n return $ if (mask .&. bValue) /= 0\n then nextIndex\n else n + 1\n\n MA.writeArray dpM mask $ minimum connections\n return dpM\n\n\nmain :: IO ()\nmain = do\n [n, k] <- B8.getLine <&> map readIntB8 . B8.words\n s <- B8.getLine <&> B8.pack . filter (\\c -> 'a' <= c && c <= 'z' || c == '?') . B8.unpack\n\n let answer = solve n k s\n\n printf \"%d\\n\" answer"}], "negative_code": [], "src_uid": "87d3c1d8d3d1f34664ff32081222117d"} {"source_code": "f :: Integer -> Integer\nf n = n `mod` 998244353\n\nl :: [Integer]\nl = 1 : map (f.(*10)) l\n\nl2 :: [Integer]\nl2 = zipWith (\\x y -> f (x*y)) [0..] l\n\nl3 :: [Integer]\nl3 = 0 : zipWith (\\x y -> f (x+y)) l3 l4\n\nl4 :: [Integer]\nl4 = 10 : tail (zipWith (\\x y -> f (x-y)) (tail l2) l5)\n\nl5 :: [Integer]\nl5 = 0 :zipWith3 (\\a b c -> f(a+b+c)) l4 (tail l3) l5\n\n\n\nsolve :: Int -> [Integer]\nsolve n = reverse $ take n l4\n\nmain :: IO ()\nmain = interact (unwords.map show.solve.read)\n", "positive_code": [{"source_code": "import Control.Arrow\n\nmain = interact $ read >>> solve >>> map show >>> unwords\n\nsolve :: Integer -> [Integer]\nsolve n = map solveEach $ zip [1..n] $ repeat n\n\nsolveEach :: (Integer, Integer) -> Integer\nsolveEach (i, n)\n | i == n = 10\n | otherwise = \n foldl mulv 1 \n [9, pwr 10 (n - 1 - i),\n addv 20 $ mulv 9 (n - 1 - i)]\n where\n modv = 998244353\n addv a b = mod (a + b) modv\n mulv a b = mod (a * b) modv \n pwr :: Integer -> Integer -> Integer\n pwr a 0 = 1\n pwr a n\n | odd n = mulv a $ pwr a (n - 1)\n | even n = let u = pwr a (div n 2) in u * u"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ read >>> solve >>> map show >>> unwords\n\nsolve :: Integer -> [Integer]\nsolve n = map (solveEach n) [1 .. n]\n\nsolveEach :: Integer -> Integer -> Integer\nsolveEach n i\n | i == n = 10\n | otherwise = 9 *% 10 ^% (n - 1 - i) *% (20 +% 9 *% (n - 1 - i))\n\nmodV :: Integer\nmodV = 998244353\n\n(+%) :: Integer -> Integer -> Integer\na +% b = (a + b) `mod` modV\n\ninfixl 6 +%\n\n(*%) :: Integer -> Integer -> Integer\na *% b = (a * b) `mod` modV\n\ninfixl 7 *%\n\n(^%) :: Integer -> Integer -> Integer\na ^% n\n | n == 0 = 1\n | odd n = a *% a ^% (n - 1)\n | even n = let u = a ^% (n `div` 2) in u *% u\n\ninfixl 8 ^%"}], "negative_code": [{"source_code": "import Control.Arrow\n\nmain = interact $ read >>> solve >>> map show >>> unwords\n\nsolve :: Int -> [Int]\nsolve n = map solveEach $ zip [1..n] $ repeat n\n\nsolveEach :: (Int, Int) -> Int\nsolveEach (i, n)\n | i == n = 10\n | otherwise = \n foldl mulv 1 \n [9, pwr 10 (n - 1 - i),\n addv 20 $ mulv 9 (n - 1 - i)]\n where\n modv = 998244353\n addv a b = mod (a + b) modv\n mulv a b = mod (a * b) modv \n pwr :: Int -> Int -> Int\n pwr a 0 = 1\n pwr a n\n | odd n = mulv a $ pwr a (n - 1)\n | even n = let u = pwr a (div n 2) in u * u"}, {"source_code": "f :: Int -> Int\nf n = n `mod` 998244353\n\nl :: [Int]\nl = iterate (f.(*10)) 1800\n\nl2 :: [Int]\nl2 = iterate (f.(*10)) 810\n\nl3 :: [Int]\nl3 = zipWith3 (\\x y z-> x+y*z) l l2 [1..]\n\nl4 :: [Int]\nl4 = 10:180:l3\n\nsolve :: Int -> [Int]\nsolve n = reverse $ take n l4\n\nmain :: IO ()\nmain = interact (unwords.map show.solve.read)\n"}, {"source_code": "f :: Int -> Int\nf n = n `mod` 998244353\n\nl :: [Int]\nl = 1 : map (f.(*10)) l\n\nl2 :: [Int]\nl2 = zipWith (\\x y -> f (x*y)) [0..] l\n\nl3 :: [Int]\nl3 = 0 : zipWith (\\x y -> f (x+y)) l3 l4\n\nl4 :: [Int]\nl4 = 10 : tail (zipWith (\\x y -> f (x-y)) (tail l2) l5)\n\nl5 :: [Int]\nl5 = 0 :zipWith3 (\\a b c -> f(a+b+c)) l4 (tail l3) l5\n\n\n\nsolve :: Int -> [Int]\nsolve n = reverse $ take n l4\n\nmain :: IO ()\nmain = interact (unwords.map show.solve.read)\n"}], "src_uid": "87c3a8a0d49288d0f6242fe2ac69a641"} {"source_code": "import Data.List (sort, minimumBy)\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>\n map read . words <$> getLine >>= print . minOps . sort\n\nminOps :: [Int] -> Int\nminOps (a1:a2:a3:as) = m (f a1 a2 a3) (a2:a3:as)\n where f a1 a2 a3 = let s = a1+a2+a3 in\n snd $ minimumBy (\\x1 x2 -> compare (fst x1) (fst x2))\n (map (\\x -> (abs(3*x-s), abs(x-a1)+abs(x-a2)+abs(x-a3))) [a1, a2, a3])\n m acc (a1:a2:a3:as) = if (f a1 a2 a3) < acc\n then m (f a1 a2 a3) (a2:a3:as)\n else m acc (a2:a3:as)\n m acc _ = acc\n", "positive_code": [{"source_code": "import Data.List(sort)\r\n\r\nselectThree :: [Int] -> Int\r\nselectThree sticks = minimum $\r\n zipWith (+) (\r\n zipWith (-)\r\n (drop 2 sorted) $\r\n drop 1 sorted\r\n ) $\r\n zipWith (-)\r\n (drop 1 sorted)\r\n sorted\r\n where\r\n sorted = sort sticks\r\n\r\nsolveCase :: Int -> IO ()\r\nsolveCase test_case = do\r\n _ <- readLn :: IO Int\r\n sticks <- fmap (map read . words) getLine :: IO [Int]\r\n print $ selectThree sticks \r\n\r\nmain :: IO ()\r\nmain = do\r\n test_case_num <- readLn :: IO Int\r\n mapM_ solveCase [1 .. test_case_num]"}, {"source_code": "import Data.List\n\nreadInt x = read x :: Int\nreadInteger x = read x :: Integer\nreadDouble x = read x :: Double\n\ngetTriplets res (x:y:z:lst) = getTriplets ((x,y,z):res) (y:z:lst)\ngetTriplets res (y:z:[]) = res\n\nmin' ((x,y,z):xs) = if a < b then a else b\n where\n a = z-y+y-x\n b = min' xs\nmin' [(x,y,z)] = z-y+y-x\nmin' [] = 1000000000\n\nsolve 0 = return ()\nsolve tc = do\n solve (tc-1)\n\n in_n <- getLine\n in_arr <- getLine\n\n let n = readInt in_n\n let arr = map readInt $ words in_arr\n let arr2 = sort arr\n let triplets = getTriplets [] arr2\n\n print(min' triplets)\n\nmain = do\n in1 <- getLine\n let tc = readInt in1\n solve tc"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n],xs] <- replicateM 2 ri\r\n return xs\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve xs = minimum $ uncurry (-) <$> zip (tail.tail$ys) ys\r\n where\r\n ys = L.sort xs\r\n"}, {"source_code": "import Control.Monad(replicateM_)\r\nimport Data.List(sort)\r\n\r\nselectThree :: [Int] -> Int\r\nselectThree sticks = minimum $\r\n zipWith (+) (\r\n zipWith (-)\r\n (drop 2 sorted) $\r\n drop 1 sorted\r\n ) $\r\n zipWith (-)\r\n (drop 1 sorted)\r\n sorted\r\n where\r\n sorted = sort sticks\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n _ <- readLn :: IO Int\r\n sticks <- fmap (map read . words) getLine :: IO [Int]\r\n print $ selectThree sticks \r\n\r\nmain :: IO ()\r\nmain = do\r\n test_case_num <- readLn :: IO Int\r\n replicateM_ test_case_num solveCase"}], "negative_code": [], "src_uid": "53ff11122a277d1eb29fe2034017fd75"} {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\nquery f (-1) = return 0\nquery f i = do\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\tsum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\t-- foldM' (\\!s !i -> readArray f i) 0 $ takeWhile (>= 0) $ iterate (\\ !i -> i .&. (i + 1) - 1) i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet next (I# i) = I# (i `orI#` (i +# 1#))\n\t-- let is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tlet is = takeWhile (<= l) $ iterate next i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\na `orI#` b = word2Int# (int2Word# a `or#` int2Word# b)\n\nquery f (-1) = return 0\nquery f i = do\n\t-- let next i = (i .&. (i+1)) - 1\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\t-- sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\tfoldM' (\\s i -> (s+) <$> (readArray f i)) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet next (I# i) = I# (i `orI#` (i +# 1#))\n\t-- let is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tlet is = takeWhile (<= l) $ iterate next i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\na `orI#` b = word2Int# (int2Word# a `or#` int2Word# b)\n\nquery f (-1) = return 0\nquery f i = do\n\t-- let next i = (i .&. (i+1)) - 1\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\t-- sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\tfoldM' (\\s i -> (s+) <$> (readArray f i)) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\n{-# OPTIONS_GHC -fvia-C -optc-O2 #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet next (I# i) = I# (i `orI#` (i +# 1#))\n\t-- let is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tlet is = takeWhile (<= l) $ iterate next i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\na `orI#` b = word2Int# (int2Word# a `or#` int2Word# b)\n\nquery f (-1) = return 0\nquery f i = do\n\t-- let next i = (i .&. (i+1)) - 1\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\t-- sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\tfoldM' (\\s i -> (s+) <$> (readArray f i)) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\nquery f (-1) = return 0\nquery f i = do\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\tsum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\t-- foldM' (\\s i -> readArray f i) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\nquery f (-1) = return 0\nquery f i = do\n\tlet next (I# i) = I# ((word2Int# ((int2Word# i) `and#` (int2Word# (i +# 1#)))) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\tsum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\t-- foldM' (\\!s !i -> readArray f i) 0 $ takeWhile (>= 0) $ iterate (\\ !i -> i .&. (i + 1) - 1) i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\nquery f (-1) = return 0\nquery f i = do\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\t-- sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\tfoldM' (\\s i -> (s+) <$> (readArray f i)) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet next (I# i) = I# (i `orI#` (i +# 1#))\n\t-- let is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tlet is = takeWhile (<= l) $ iterate next i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\na `orI#` b = word2Int# (int2Word# a `or#` int2Word# b)\n\nquery f (-1) = return 0\nquery f i = do\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\t-- sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\tfoldM' (\\s i -> (s+) <$> (readArray f i)) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}], "negative_code": [{"source_code": "import Data.Graph\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, words, lines)\nimport Prelude hiding (getLine, words, lines)\n\nreadInts = map (fst . fromJust . readInt) . words <$> getLine\n\nsolve n edges queries = \"ok\"\n\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n\n"}, {"source_code": "main = print \"ok\"\n\n"}, {"source_code": "import Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, words, lines)\nimport Prelude hiding (getLine, words, lines)\n\nreadInts = map (fst . fromJust . readInt) . words <$> getLine\n\nsolve n edges queries = \"ok\"\n\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "{-# LANGUAGE BangPatterns, MagicHash #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\nimport GHC.Prim\nimport GHC.Types\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\na `andI#` b = word2Int# (int2Word# a `and#` int2Word# b)\nquery f (-1) = return 0\nquery f i = do\n\tlet next (I# i) = I# ((i `andI#` (i +# 1#)) -# 1#)\n\t-- let next (I# i) = I# $ word2Int# $ (int2Word# i) or# (int2Word# i)\n\t-- sum <$> (mapM (readArray f) $ takeWhile (>= 0) $ iterate next i)\n\tfoldM' (\\s i -> readArray f i) 0 $ takeWhile (>= 0) $ iterate next i\n{-query f i = query1 f i 0\n\nquery1 f i r\n\t| i < 0 = return r\n\t| otherwise = do\n\t\tv <- readArray f i \n\t\tquery1 f i' (r + v)\n\twhere\n\t\ti' = i .&. (i + 1) - 1\n\nquery'' f !i\n\t| i < 0 = return 0\n\t| otherwise = do\n\t\tv <- readArray f i\n\t\tr <- query f i'\n\t\treturn $ v + r\n\twhere\n\t\ti' = i .&. (i + 1) - 1 -}\n\n\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\treverse <$> foldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet !d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}, {"source_code": "\n\n\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Graph\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\nimport Data.Tuple\n\ntype Fenwick s = STUArray s Int Int\nfenwick l = newArray (0, l-1) 0 :: ST s (Fenwick s)\n\nupdate f i d = do\n\tl <- snd <$> getBounds f\n\tlet is = takeWhile (<= l) $ iterate (\\i -> i .|. (i + 1)) i\n\tforM_ is $ \\i -> do\n\t\tv <- readArray f i\n\t\twriteArray f i (v + d)\n\treturn f\n\nquery f (-1) = return 0\nquery f i = do\n\tlet is = takeWhile (>= 0) $ iterate (\\i -> i .&. (i + 1) - 1) i\n\tvs <- mapM (readArray f) is\n\treturn $ sum vs\n\nunordered edges = edges ++ map swap edges\n\nsolve n edges queries = runST $ do\n\t\tfenwicksList <- mapM (fenwick . length) paths\n\n\t\tlet\n\t\t\tfenwicks = listArray (1, length paths) fenwicksList\n\n\t\tfoldM (\\rs q -> case q of\n\t\t\t[t, edgeIndex] -> do\n\t\t\t\tlet\n\t\t\t\t\t(fenwicksIndex, index) = edgesPlaces edgeIndex\n\t\t\t\t\tfenwick = fenwicks ! fenwicksIndex\n\t\t\t\tupdate fenwick index (if t == 1 then -1 else 1)\n\t\t\t\treturn rs\n\t\t\t[3, i, j] -> do\n\t\t\t\tlet (i1, j1) = places ! i\n\t\t\t\tlet (i2, j2) = places ! j\n\t\t\t\ts1 <- query (fenwicks ! i1) j1\n\t\t\t\ts2 <- query (fenwicks ! i2) j2\n\n\t\t\t\tlet d = if i1 == i2\n then if s1 == s2 then abs (j1 - j2) else -1\n\t\t\t\t\telse if s1 + s2 == 0 then j1 + j2 + 2 else -1\n\t\t\t\treturn $ d : rs) [] queries\n\n\twhere\n\t\tg = buildG (1, n) (unordered edges)\n\t\troot = fromMaybe 1 $ find (\\i -> indegree g ! i > 2) [1..n]\n\t\tpaths = map flatten $ subForest $ head $ dfs g [root]\n\n\t\tparents = accumArray (flip const) 0 (1, n) $ concat [path `zip` (root:path) | path <- paths] \n\n\t\tplaces = accumArray (flip const) (1, -1) (1, n) $\n\t\t\t[(vertex, (pathIndex, index)) | (path, pathIndex) <- paths `zip` [1..],\n\t\t\t\t(vertex, index) <- path `zip` [0..]]\n\n\t\tedges' = listArray (1, length edges) edges\n\t\tedgesPlaces edgeIndex = places ! k\n\t\t\twhere\n\t\t\t\t(i, j) = edges' ! edgeIndex\n\t\t\t\tk = if parents ! i == j then i else j\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n\t[n] <- readInts\n\tedges <- map (\\[a, b] -> (a, b)) <$> replicateM (n - 1) readInts\n\t[m] <- readInts\n\tqueries <- replicateM m readInts\n\tputStrLn $ unlines $ map show $ solve n edges queries\n"}], "src_uid": "f9407e5aafb0df3b741e76c2e7e7a890"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.IORef\nimport Data.Array.IO.Safe\nimport qualified Data.Set\n\ndata Tree = Nil | Inner Tree Tree Int | Leaf (Data.Set.Set Int) Bool deriving Show\n\ntreeWidth = 2 ^ 10\n\nmakeInner :: Int -> Tree -> Tree -> Tree\nmakeInner w l r = Inner l r (getSum w l + getSum w r)\n\ngetSum :: Int -> Tree -> Int\ngetSum _ Nil = 0\ngetSum _ (Inner _ _ s) = s\ngetSum w (Leaf s rev) = let sz = Data.Set.size s in if rev then w - sz else sz\n\nupdate :: Int -> Int -> Int -> Int -> Int -> Int -> Tree -> Tree\nupdate w t y x a b Nil = update w t y x a b tr\n\twhere tr = if b - a == 1 then Leaf Data.Set.empty False else Inner Nil Nil 0\n\nupdate w t y x a b (Inner l r _) =\n\tif y < mid then makeInner w (update w t y x a mid l) r\n\telse makeInner w l (update w t y x mid b r)\n\twhere mid = (a + b) `div` 2\n\nupdate w t y x a b (Leaf s rev) = \n\tcase t of\n\t\t1 -> Leaf ((if rev then Data.Set.delete else Data.Set.insert) x s) rev\n\t\t2 -> Leaf ((if rev then Data.Set.insert else Data.Set.delete) x s) rev\n\t\t3 -> Leaf s (not rev)\n\nmain = do\n\t[h, w, q] <- map read . words <$> getLine :: IO [Int]\n\tqueries <- map (map read . words) <$> replicateM q getLine :: IO [[Int]]\n\n\thistory <- newArray (0, q) Nil :: IO (IOArray Int Tree)\n\ttree <- newIORef Nil :: IO (IORef Tree)\n\n\tforM_ (zip [0..] queries) $ \\(i, q) -> do\n\t\tt <- readIORef tree\n\t\twriteArray history i t\n\t\twhen (head q == 1) $ do\n\t\t\tlet [k, y, x] = q\n\t\t\twriteIORef tree $ update w k (y - 1) (x - 1) 0 treeWidth t\n\t\twhen (head q == 2) $ do\n\t\t\tlet [k, y, x] = q\n\t\t\twriteIORef tree $ update w k (y - 1) (x - 1) 0 treeWidth t\n\t\twhen (head q == 3) $ do\n\t\t\tlet [k, y] = q\n\t\t\twriteIORef tree $ update w k (y - 1) 0 0 treeWidth t\n\t\twhen (head q == 4) $ do\n\t\t\tlet [k, y] = q\n\t\t\tnextTree <- readArray history y\n\t\t\twriteIORef tree nextTree\n\t\tcurrTree <- readIORef tree\n\t\tprint $ getSum w currTree\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable (toList)\n\nmain = do\n [n, m, q] <- map read . words <$> getLine\n qs <- replicateM q (map read . words <$> getLine)\n\n let\n process bookcases [1, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= mark = Seq.update (j-1) mark books\n | otherwise = books\n\n d = if pres == mark then 0 else 1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [2, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= not mark = Seq.update (j-1) (not mark) books\n | otherwise = books\n\n d = if pres == not mark then 0 else -1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [3, i] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n\n d = -cnt + m-cnt\n\n shelves' = Seq.update (i-1) (cnt+d, not mark, books) shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [4, k] = bookcases Seq.|> bookcase'\n where\n bookcase' = bookcases `Seq.index` k\n\n zero = (0, Seq.replicate n zero') where zero' = (0, True, Seq.replicate m False)\n\n bookcases = foldl process (Seq.singleton zero) qs\n\n -- putStr $ unlines $ map show $ toList bookcases\n\n putStr $ unlines $ map show $ map fst $ tail $ toList bookcases\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable (toList)\n\nmain = do\n [n, m, q] <- map read . words <$> getLine\n qs <- replicateM q (map read . words <$> getLine)\n\n let\n process bookcases [1, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= mark = Seq.update (j-1) mark books\n | otherwise = books\n\n d = if pres == mark then 0 else 1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [2, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= not mark = Seq.update (j-1) (not mark) books\n | otherwise = books\n\n d = if pres == not mark then 0 else -1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [3, i] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n\n d = -cnt + m-cnt\n\n shelves' = Seq.update (i-1) (cnt+d, not mark, books) shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [4, k] = bookcases Seq.|> bookcase'\n where\n bookcase' = bookcases `Seq.index` k\n\n zero = (0, Seq.replicate n zero') where zero' = (0, True, Seq.replicate m False)\n\n bookcases = foldl process (Seq.singleton zero) qs\n\n -- putStr $ unlines $ map show $ toList bookcases\n\n putStr $ unlines $ map show $ map fst $ tail $ toList bookcases\n\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable (toList)\n\nmain = do\n [n, m, q] <- map read . words <$> getLine\n qs <- replicateM q (map read . words <$> getLine)\n\n let\n process bookcases [1, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= mark = Seq.update (j-1) mark books\n | otherwise = books\n\n d\n | pres == mark = 0\n | mark = 1\n | otherwise = -1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [2, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= not mark = Seq.update (j-1) mark books\n | otherwise = books\n\n d\n | pres == not mark = 0\n | not mark = -1\n | otherwise = 1\n\n shelves' = Seq.update i (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [3, i] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n\n d = -cnt + m-cnt\n\n shelves' = Seq.update (i-1) (cnt+d, not mark, books) shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [4, k] = bookcases Seq.|> bookcase'\n where\n bookcase' = bookcases `Seq.index` k\n\n zero = (0, Seq.replicate n zero') where zero' = (0, True, Seq.replicate m False)\n\n bookcases = foldl process (Seq.singleton zero) qs\n\n putStr $ unlines $ map show $ map fst $ tail $ toList bookcases\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable (toList)\n\nmain = do\n [n, m, q] <- map read . words <$> getLine\n qs <- replicateM q (map read . words <$> getLine)\n\n let\n process bookcases [1, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= mark = Seq.update (j-1) mark books\n | otherwise = books\n\n d\n | pres == mark = 0\n | mark = 1\n | otherwise = -1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [2, i, j] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n pres = books `Seq.index` (j-1)\n\n books'\n | pres /= not mark = Seq.update (j-1) (not mark) books\n | otherwise = books\n\n d\n | pres == not mark = 0\n | not mark = -1\n | otherwise = 1\n\n shelves' = Seq.update (i-1) (cnt+d, mark, books') shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [3, i] = bookcases Seq.|> bookcase'\n where\n _ Seq.:> (total, shelves) = Seq.viewr bookcases\n (cnt, mark, books) = shelves `Seq.index` (i-1)\n\n d = -cnt + m-cnt\n\n shelves' = Seq.update (i-1) (cnt+d, not mark, books) shelves\n bookcase' = (total+d, shelves')\n\n process bookcases [4, k] = bookcases Seq.|> bookcase'\n where\n bookcase' = bookcases `Seq.index` k\n\n zero = (0, Seq.replicate n zero') where zero' = (0, True, Seq.replicate m False)\n\n bookcases = foldl process (Seq.singleton zero) qs\n\n -- putStr $ unlines $ map show $ toList bookcases\n\n putStr $ unlines $ map show $ map fst $ tail $ toList bookcases\n\n\n"}], "src_uid": "2b78f6626fce6b5b4f9628fb15666dc4"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nsolve :: Int -> Int64 -> Maybe [Int]\nsolve n k =\n solve' 1 [] k\n where\n solve' :: Int -> [Int] -> Int64 -> Maybe [Int]\n solve' i is k\n | i == n + 1 = if k <= 0 && null is then Just [] else Nothing\n | k >= kCount = solve' (i + 1) (i : is) (k - kCount)\n | otherwise = ((i : is) ++) <$> solve' (i + 1) [] k\n where\n kCount = count' (n - i - 1)\n\n count' :: Int -> Int64\n count' x\n | x < 0 = 1\n | x >= 61 = 2 ^ 61\n | otherwise = 2 ^ fromIntegral x\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n [n, k] :: [Int64] <- B8.getLine <&> B8.words <&> map (fromInteger . readIntegerB8)\n let answer = solve (fromIntegral n) (k - 1)\n case answer of\n Just answer -> forM_ answer $ printf \"%lld \"\n Nothing -> printf \"-1\"\n printf \"\\n\"", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\nparseInt64 :: C.ByteString -> Int64\nparseInt64 = fromIntegral . fst . fromJust . C.readInteger\n\nfunc :: Int -> Int -> Int64 -> [Int]\nfunc n i k\n | n >= 63 = i : func (n - 1) (i + 1) k\n | n <= 0 = []\n | otherwise = [i + j - 1, i + j - 2 .. i] ++ func (n - j) (i + j) (k - limit + 1)\n where\n limits = iterate (\\(lim, j) -> (lim + 2 ^ (max 0 (n - 1 - j)), j + 1)) (1 :: Int64, 1 :: Int)\n (limit, j) = last $ takeWhile (\\(lim, _) -> k >= lim) limits\n\nmain :: IO ()\nmain = do\n t <- fmap parseInt C.getLine\n replicateM_ t $ do\n [s1, s2] <- fmap C.words C.getLine\n let n = parseInt s1\n k = parseInt64 s2\n C.putStrLn $ C.pack $ if n < 63 && k > 2 ^ (n - 1)\n then \"-1\"\n else unwords $ map show $ func n 1 k\n"}], "negative_code": [], "src_uid": "7197b4a353ecb25cfad80726f6868fe3"} {"source_code": "module Main where\n\nstr n = putStrLn (show n ++ \" 1 \" ++ show n ++ \" 2\")\n\nmain = print 2001 >> mapM_ str [1..1000] >> str 1 >> mapM_ str [1..1000]", "positive_code": [{"source_code": "import Data.List (intersperse)\n\nformatList :: Show a => [a] -> String\nformatList = concat . intersperse \" \" . map show\n\nmain :: IO [()]\nmain = do\n let n = 1000\n a = map (\\x -> [x, 1, x, 2]) [1 .. n]\n print (n * 2)\n mapM (putStrLn . formatList) (a ++ reverse a)\n\n"}, {"source_code": "\n\nmain :: IO ()\nmain = do\n putStrLn \"2000\\n\" \n sequence_ $ \n [putStrLn $ show x ++ \" 1 \" ++ show x ++ \" 2\" | x <- [1..1000]] \n ++ [putStrLn $ show x ++ \" 1 \" ++ show x ++ \" 2\" | x <- [1000,999..1]]\n"}], "negative_code": [{"source_code": "import Data.List (intersperse)\n\nformatList :: Show a => [a] -> String\nformatList = concat . intersperse \" \" . map show\n\nmain :: IO [()]\nmain = do\n let n = 1000\n a = map (\\x -> [x, 1, x, 2]) [1 .. n]\n print n\n mapM (putStrLn . formatList) (a ++ reverse a)\n\n"}, {"source_code": "import Data.List (intersperse)\n\nformatList :: Show a => [a] -> String\nformatList = concat . intersperse \" \" . map show\n\nmain :: IO [()]\nmain = do\n let n = 1000\n a = map (\\x -> [x, 1, x, 2]) [1 .. n]\n mapM (putStrLn . formatList) (a ++ reverse a)\n\n"}, {"source_code": "\n\nmain :: IO ()\nmain = \n sequence_ $ \n [putStrLn $ show x ++ \" 1 \" ++ show x ++ \" 2\" | x <- [1..1000]] \n ++ [putStrLn $ show x ++ \" 1 \" ++ show x ++ \" 2\" | x <- [1000,999..1]]\n"}, {"source_code": "module Main where\n\nstr n = putStrLn (show n ++ \" 1 \" ++ show n ++ \" 2\")\n\nrez 0 = return ()\nrez n = str n >> str n >> rez (n - 1)\n\nmain = print 2000 >> rez 1000"}, {"source_code": "module Main where\n\nstr n = putStrLn (show n ++ \" 1 \" ++ show n ++ \" 2\")\n\nrez 0 = return ()\nrez n = str n >> str n >> rez (n - 2)\n\nmain = print 2000 >> rez 2000"}], "src_uid": "19190fd248eb2c621ac2c78b803049a8"} {"source_code": "main = interact $ solve . head . tail . lines\nsolve = go [] [] where\n go l r (a:b:cs) = go (a:l) (b:r) cs\n go l r [c] = r ++ reverse (c:l)\n go l r [] = l ++ reverse r\n", "positive_code": [{"source_code": "-- Codeforces Round #386 (Div. 2)\n-- B. Decoding\n-- http://codeforces.com/problemset/problem/746/B\n\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable (toList, foldl)\nimport Prelude hiding (foldl)\n\ngetInt = read `fmap` getLine :: IO Int\n\nmain = do\n n <- getInt\n str <- Seq.fromList `fmap` reverse `fmap` getLine :: IO (Seq.Seq Char)\n putStrLn $ toList (decode str)\n\ndecode :: Seq.Seq Char -> Seq.Seq Char\ndecode s = foldl (\\t ch -> insertAt (Seq.length t `div` 2) ch t) Seq.empty s\n\ninsertAt k a s = (x Seq.|> a) Seq.>< y where\n (x, y) = Seq.splitAt k s\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readInteger :: String -> Integer\n readInteger s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solutions :: Integer -> Integer -> Integer\n solutions n k =\n let midIndex = (2 ^ (n - 1))\n in case compare k midIndex of\n GT -> solutions (n - 1) (k - midIndex)\n LT -> solutions (n - 1) (midIndex - k)\n EQ -> n\n\n solverEven :: String -> String -> String\n solverEven [] ys = ys\n solverEven (x:xs) ys\n | length ys `mod` 2 == 0 = solverEven xs (x:ys)\n | length ys `mod` 2 == 1 = solverEven xs (ys ++ [x])\n\n solverOdd :: String -> String -> String\n solverOdd [] ys = ys\n solverOdd (x:xs) ys\n | length ys `mod` 2 == 1 = solverOdd xs (x:ys)\n | length ys `mod` 2 == 0 = solverOdd xs (ys ++ [x])\n\n solver :: String -> String\n solver xs\n | length xs `mod` 2 == 1 = solverOdd xs []\n | length xs `mod` 2 == 0 = solverEven xs []\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInteger\n xs <- getLine\n putStrLn $ solver xs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmain = do\n n <- readLn\n cs <- getLine\n putStrLn $ solve n cs\n\nsolve :: Int -> String -> String\nsolve 1 [c] = [c]\nsolve 2 [c, d] = [c, d]\nsolve n cs = go (even n) [] [] cs\n where\n go True ls rs (c:d:cs) = go True (c:ls) (d:rs) cs\n go False ls rs (c:cs) = go True (c:ls) rs cs\n go _ ls rs [] = ls ++ reverse rs"}, {"source_code": "main = interact $ (\\[n,s] -> decode (read n) s \"\") . words\n\ndecode :: Int -> String -> String -> String\ndecode _ \"\" res = res\ndecode n (x:xs) res | even n = decode (n - 1) xs (x : res) \n | otherwise = decode (n - 1) xs (res ++ [x])"}], "negative_code": [{"source_code": "main = interact $ show . solve . head . tail . lines\nsolve = go [] [] where\n go l r (a:b:cs) = go (a:l) (b:r) cs\n go l r [c] = r ++ reverse (c:l)\n go l r [] = l ++ reverse r\n"}], "src_uid": "2a414730d1bc7eef50bdb631ea966366"} {"source_code": "q l t = (replicate (2 * l) ' ') ++ t ++ \"\\n\"\n\np _ [] = []\n\np l ('<':x:'>':s) = (q l ['<', x, '>']) ++ p (l + 1) s\np l ('<':'/':x:'>':s) = (q (l - 1) ['<', '/', x, '>']) ++ p (l - 1) s\np l (_:s) = p l s\n\nmain = interact $ p 0\n", "positive_code": [{"source_code": "-- XML\notst 0 = []\notst a = ' ':(otst $ a-1)\n\nparse [] _ = []\nparse ('<':(a:('>':xs))) n = (otst $ 2*n) ++ ('<':(a:\">\\n\")) ++ parse xs (n+1)\nparse ('<':('/':(a:('>':xs)))) n = (otst $ 2*(n-1)) ++ ('<':('/':(a:\">\\n\"))) ++ parse xs (n-1)\nparse (x:xs) n = x:(parse xs n)\n\nmain = do\n s <- getLine\n putStrLn $ parse s 0\n"}, {"source_code": "solve :: String -> [String]\nsolve s = solve' 0 s\n where\n solve' n [] = []\n solve' n s\n | s !! 1 == '/' =\n (replicate (n-2) ' ' ++ take 4 s) : (solve' (n-2) (drop 4 s))\n | otherwise =\n (replicate n ' ' ++ take 3 s) : (solve' (n+2) (drop 3 s))\n\nmain :: IO ()\nmain = getLine >>= mapM_ putStrLn . solve"}, {"source_code": "indent lvl tag = (replicate (2 * lvl) ' ') ++ tag ++ \"\\n\"\n\nparse _ [] = []\nparse lvl ('<':x:'>':xs) = (indent lvl ['<', x, '>']) ++ parse (lvl + 1) xs\nparse lvl ('<':'/':x:'>':xs) = (indent (lvl - 1) ['<', '/', x, '>']) ++ parse (lvl - 1) xs\nparse lvl (_:xs) = parse lvl xs\n\nmain = interact $ parse 0\n"}, {"source_code": "indent lvl tag = (replicate (2 * lvl) ' ') ++ tag ++ \"\\n\"\n\nparse _ [] = []\nparse lvl ('<':x:'>':xs) = (indent lvl ['<', x, '>']) ++ parse (lvl + 1) xs\nparse lvl ('<':'/':x:'>':xs) = (indent (lvl - 1) ['<', '/', x, '>']) ++ parse (lvl - 1) xs\n\nmain = do text <- getLine\n putStr $ parse 0 text\n"}, {"source_code": "s t = replicate (2 * t) ' '\n\np _ [] = []\np l ('<':'/':r) = s (l - 1) ++ \"':r) = \">\\n\" ++ p l r\np l (x:r) = x:p l r\n\nmain = interact $ p 0"}, {"source_code": "split = (filter (\\x->length x > 0)) . words . (map (\\x->if (elem x \"<>\") then ' ' else x))\nsolve = fst . (foldl g (\"\", 0))\n where g (res, cnt) it = (res ++ (take (2*(if (head it=='/') then cnt - 1 else cnt)) (repeat ' ')) ++ \"<\" ++ it ++ \">\\n\", if (head it == '/') then cnt - 1 else cnt + 1)\nmain = interact $ solve . split"}, {"source_code": "\nmain = interact (solve 0)\n\nsolve d ('>':xs) = \">\\n\"++solve d xs\nsolve d ('<':'/':xs) = replicate ((d-1)*2) ' ' ++ \" String\nxML = loop 0\n where\n loop _ \"\" = \"\"\n loop n ('<' : c : '>' : s) = printf \"%s<%s>\\n\" (take (n * 2) spaces) [c] ++ loop n' s\n where n' = n + 1\n loop n ~('<' : '/' : c : '>' : s) = printf \"%s\\n\" (take (n' * 2) spaces) [c] ++ loop n' s\n where n' = n - 1\n\nmain :: IO ()\nmain = getLine >>= putStrLn . xML\n\n"}, {"source_code": "import Data.List\n\ndata Tag = Open | Close deriving (Eq)\n\nsplitTag str =\n if length str > 0 then\n let (f,b) = span (/='>') str\n tagType = if length f == 2 then Open else Close\n tag = f++[(head b)]\n rest = tail b\n in\n Just ((tagType, tag), rest)\n else\n Nothing\n\nsolve xml = ppnt 0 $ unfoldr splitTag xml\n where\n ppnt _ [] = \"\"\n ppnt n ((typ,tag):xs) = (\"\\n\"++(replicate (if typ==Open then n else n-2) ' ')++tag)++(ppnt (if typ==Open then n+2 else n-2) xs)\n\nmain = getLine >>= putStrLn.tail.solve"}], "negative_code": [], "src_uid": "45207d5ff60bbb6897feb1d9a3f85a65"} {"source_code": "module Main where\n\nisInt x = x == fromInteger (round x)\n\nother :: IO ()\nother = do\n ln <- getLine\n let ints = map read (words ln) :: [Integer]\n let n = ints !! 0\n let k = fromIntegral (ints !! 1)\n putStrLn $ if even n == even k\n then if k * k > n\n then \"NO\"\n else \"YES\"\n else \"NO\"\n\nname 1 = other\nname t = do\n other\n name $ t - 1\n\nmain = do\n t <- getLine\n name $ read t\n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n t_str <- getLine\n let t = read t_str\n printElem [1..t]\n\nprintElem :: Show a => [a] -> IO ()\nprintElem [] = putStrLn \"\"\nprintElem (x:xs) = do\n nk_str <- getLine\n let n = read (head (words nk_str))\n let k = read( last (words nk_str))\n putStrLn (solve n k) \n printElem xs\n\nsolve :: Integer -> Integer -> String\nsolve n k \n | ((n `mod` 2 == k `mod` 2) && (n >= (k ^ 2))) = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "main :: IO ()\nmain = do\n t_str <- getLine\n let t = read t_str :: Integer\n printList [1..t]\n\n\nprintList :: (Show a) => [a] -> IO ()\nprintList [] = putStr \"\"\nprintList (x:xs) = do\n case_str <- getLine\n let n = (read (head (words case_str)) :: Integer)\n let k = (read (last (words case_str)) :: Integer) \n putStrLn (solve n k)\n printList xs \n\nsolve :: Integer -> Integer -> String\nsolve n k \n | ((n >= (k * k)) && ((n `mod` 2) == (k `mod` 2))) = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "import Control.Monad\n\n-- solve :: Integer -> Integer -> String\nsolve n k = if n >= k^2 && n `mod` 2 == k `mod` 2 then \"YES\" else \"NO\"\n\nmain = do\n t <- fmap read getLine\n forM [1..t] (\\_ -> do\n [n, k] <- fmap (map read.words) getLine\n putStrLn (solve n k))\n"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n [n, k] <- map read . words <$> getLine\n if n < k*k || n `mod` 2 /= k `mod` 2 then\n putStrLn \"NO\"\n else\n putStrLn \"YES\"\n"}, {"source_code": "import Control.Arrow\nimport Data.Array as Array\n\nmain = interact $ \n lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines >>> (++\"\\n\")\n \nsolve :: [Integer] -> String\nsolve [n, k]\n | n < k * k = \"NO\"\n | odd (n - k * k) = \"NO\"\n | otherwise = \"YES\""}, {"source_code": "solve :: Integer -> Integer -> Bool\nsolve n k\n | n < k*k = False\n | even n && even k = True\n | odd n && even k = False\n | even n && odd k = False\n | otherwise = True\n\nsolve' :: Integer -> Integer -> String\nsolve' n k = if solve n k then \"YES\" else \"NO\"\n\nparse :: String -> String\nparse input = solve' n k\n where [n, k] = map (\\x -> read x :: Integer) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, k] <- (map read <$> getStrList) :: IO [Integer]\n putStrLn . yesOrNo . and $ [n `mod` 2 == k `mod` 2, n >= k * k]"}, {"source_code": "import Data.Bits \nimport Control.Monad\n\nmain :: IO ()\nmain = do\n getLine\n answers <- map (solve . map read . words) <$> lines <$> getContents :: IO [String]\n forM_ answers putStrLn\n\n\nsolve :: [Integer] -> String\nsolve [x,y] \n | odd x `xor` odd y = \"NO\"\n | otherwise = case x < y^2 of\n True -> \"NO\"\n _ -> \"YES\"\n"}, {"source_code": "solve ([a, b]) = if a `mod` 2 /= b `mod` 2 then \"NO\" else if a < b*b then \"NO\" else \"YES\"\n \nmain = do\n x <- getLine\n interact (unlines . map ( solve . (map read) . words ) . lines )"}, {"source_code": "module Main where\n\nisInt x = x == fromInteger (round x)\n\nother :: IO ()\nother = do\n ln <- getLine\n let ints = map read (words ln) :: [Integer]\n putStrLn $ if even (ints !! 0) == even (ints !! 1)\n then if (ints !! 1) ^ 2 > (ints !! 0)\n then \"NO\"\n else \"YES\"\n else \"NO\"\n\nname 1 = other\nname t = do\n other\n name $ t - 1\n\nmain = do\n t <- getLine\n name $ read t"}], "negative_code": [{"source_code": "main :: IO ()\nmain = do\n t_str <- getLine\n let t = read t_str :: Int\n printList [1..t]\n\n\nprintList :: (Show a) => [a] -> IO ()\nprintList [] = putStr \"\"\nprintList (x:xs) = do\n case_str <- getLine\n let n = (read (head (words case_str)) :: Int)\n let k = (read (last (words case_str)) :: Int) \n putStrLn (solve n k)\n printList xs \n\nsolve :: Int -> Int -> String\nsolve n k \n | (((n `mod` 2) == (k `mod` 2)) && (n >= (k * k))) = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "main :: IO ()\nmain = do\n t_str <- getLine\n let t = read t_str\n printElem [1..t]\n\nprintElem :: Show a => [a] -> IO ()\nprintElem [] = putStrLn \"\"\nprintElem (x:xs) = do\n nk_str <- getLine\n let n = read (head (words nk_str))\n let k = read( last (words nk_str))\n putStrLn (solve n k) \n printElem xs\n\nsolve :: Integer -> Integer -> String\nsolve n k \n | (n `mod` 2 == k `mod` 2) = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "solve :: Integer -> Integer -> Bool\nsolve n k\n | n < k = False\n | even n && even k = True\n | odd n && even k = False\n | even n && odd k = False\n | otherwise = True\n\nsolve' :: Integer -> Integer -> String\nsolve' n k = if solve n k then \"YES\" else \"NO\"\n\nparse :: String -> String\nparse input = solve' n k\n where [n, k] = map (\\x -> read x :: Integer) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "solve :: Integer -> Integer -> Bool\nsolve n k\n | even n && even k = True\n | odd n && even k = False\n | even n && odd k = False\n | otherwise = True\n\nsolve' :: Integer -> Integer -> String\nsolve' n k = if solve n k then \"YES\" else \"NO\"\n\nparse :: String -> String\nparse input = solve' n k\n where [n, k] = map (\\x -> read x :: Integer) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "import Data.Bits \nimport Control.Monad\n\nmain :: IO ()\nmain = do\n getLine\n answers <- map (solve . map read . words) <$> lines <$> getContents :: IO [String]\n forM_ answers putStrLn\n\n\nsolve :: [Int] -> String\nsolve [x,y] \n | odd x `xor` odd y = \"NO\"\n | otherwise = case x < y^2 of\n True -> \"NO\"\n _ -> \"YES\"\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> String\nsolve n k = if n >= k^2 && n `mod` 2 == k `mod` 2 then \"YES\" else \"NO\"\n\nmain = do\n t <- fmap read getLine\n forM [1..t] (\\_ -> do\n [n, k] <- fmap (map read.words) getLine\n putStrLn (solve n k))\n"}, {"source_code": "import Control.Arrow\nimport Data.Array as Array\n\nmain = interact $ \n lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines >>> (++\"\\n\")\n \nsolve :: [Int] -> String\nsolve [n, k]\n | n < k * k = \"NO\"\n | odd (n - k) = \"NO\"\n | otherwise = \"YES\""}, {"source_code": "import Control.Arrow\nimport Data.Array as Array\n\nmain = interact $ \n lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines >>> (++\"\\n\")\n \nsolve :: [Int] -> String\nsolve [n, k]\n | n < k * k = \"NO\"\n | odd (n - k * k) = \"NO\"\n | otherwise = \"YES\""}, {"source_code": "import Control.Arrow\nimport Data.Array as Array\n\nmain = interact $ \n lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines >>> (++\"\\n\")\n \nsolve :: [Int] -> String\nsolve [n, k]\n | n < k = \"NO\"\n | odd (n - k) = \"NO\"\n | otherwise = \"YES\""}, {"source_code": "module Main where\n\nisInt x = x == fromInteger (round x)\n\nother :: IO ()\nother = do\n ln <- getLine\n let ints = map read (words ln) :: [Int]\n let n = ints !! 0\n let k = ints !! 1\n putStrLn $ if even n == even k\n then if (sum $ take k [1,3..]) > n\n then \"NO\"\n else \"YES\"\n else \"NO\"\n\nname 1 = other\nname t = do\n other\n name $ t - 1\n\nmain = do\n t <- getLine\n name $ read t\n"}, {"source_code": "module Main where\n\nisInt x = x == fromInteger (round x)\n\nname :: Integer -> IO ()\nname 1 = do\n ln <- getLine\n let ints = map read (words ln) :: [Integer]\n putStrLn $ if isInt (fromIntegral (ints !! 0) / fromIntegral (ints !! 1))\n then \"YES\"\n else \"NO\"\nname t = do\n ln <- getLine\n let ints = map read (words ln) :: [Integer]\n putStrLn $ if isInt (fromIntegral (ints !! 0) / fromIntegral (ints !! 1))\n then \"YES\"\n else \"NO\"\n name $ t - 1\n\nmain = do\n t <- getLine\n name $ read t\n"}], "src_uid": "a4c82fffb31bc7e42870fd84e043e815"} {"source_code": "{-# LANGUAGE Safe #-}\n\nimport Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport safe Data.Graph (flattenSCC, stronglyConnComp)\nimport safe Data.Maybe (catMaybes, fromJust)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>> drop 1\n >>> map (C.words >>> map readInt)\n >>> process\n >>> map (show >>> C.pack)\n >>> C.unlines\n where\n readInt = C.readInt >>> fromJust >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([n] : ps : cs : xs) = solve n ps cs : process xs\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve _ ps cs = minimum $ best . flattenSCC <$> stronglyConnComp (zip3 cs [1 ..] ((: []) <$> ps))\n\nbest :: [Int] -> Int\nbest xs = head $ filter check $ filter ((== 0) . (n `mod`)) [1 .. n]\n where\n n = length xs\n\n check :: Int -> Bool\n check len = not . null . catMaybes $ groupZip len [] xs\n\n groupZip :: Int -> [Maybe Int] -> [Int] -> [Maybe Int]\n groupZip _ cur [] = cur\n groupZip len [] xs = groupZip len (Just <$> take len xs) (drop len xs)\n groupZip len cur xs = groupZip len (zipWith comb cur (take len xs)) (drop len xs)\n where\n comb Nothing _ = Nothing\n comb (Just x) y = if x == y then Just x else Nothing\n", "positive_code": [{"source_code": "import Data.Bool\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Control.Monad\n--newtype Cycle = Cycle {colors :: Array Int Color}\ntype Cycle = Array Index Color\ntype Color = Int\ntype Index = Int\ntype Givens = (Int, Array Index Index, Array Index Color)\ntype Changing = (Index,Array Index Bool, [Cycle])\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n perm <- (map (read :: String -> Int).words) <$> getLine\n cols <- (map (read :: String -> Int).words) <$> getLine\n let givens = (n,listArray (1,n) perm, listArray (1,n) cols)\n print $ smallestPower $ finish givens (start n)\n\nstart :: Int -> Changing\nstart n = (1,listArray (1,n) (replicate n False) ,[])\n\nf :: Givens -> Changing -> Either [Cycle] Changing\nf (n,perm,colors) (i,seen,cys)\n |i>n = Left cys\n |seen!i = Right (i+1,seen,cys)\n |otherwise =Right (i+1,newSeen,newCys)\n where\n newPerm = makeOneCycle perm i\n newSeen = updateSeen newPerm seen\n newCys = makeCycle newPerm colors : cys\n\nfinish :: Givens -> Changing -> [Cycle]\nfinish g ch = case f g ch of\n Left cys -> cys\n Right newCh -> finish g newCh\n\nupdateSeen :: Array Index Index -> Array Index Bool -> Array Index Bool\nupdateSeen arr seen = seen // map (\\x -> (x,True)) (elems arr)\n\nmakeCycle :: Array Index Index -> Array Int Color -> Cycle\nmakeCycle arr cols = (\\x -> cols!x) <$> arr\n\nmakeOneCycle :: Array Index Index -> Int -> Array Index Index\nmakeOneCycle perm i = listArray (1,length list) list\n where\n stream = iterate (\\ind -> perm!ind) (perm!i)\n list =i : takeWhile (/=i) stream\n\n\n\nsmallestPower :: [Cycle] -> Int\nsmallestPower cs = minimum (map processCycle cs)\n\ndivisors :: Int -> [Int]\ndivisors n = lows ++ bool id tail (n == root * root) (reverse (quot n <$> lows))\n where\n root = (floor . (sqrt:: Double -> Double) . fromIntegral) n\n lows = filter ((0==) . rem n) [1..root]\n\ndivisorTest :: Cycle -> Int -> Bool\ndivisorTest cy di = or alltests\n where\n (_,leng) = bounds cy\n testcyc n = all (==cy!n) [cy!(n+(x-1)*di) | x <- [1..(leng `div` di)]]\n alltests = map testcyc [1..di]\n\n\nprocessCycle :: Cycle -> Int\nprocessCycle cy = firstDiv\n where\n (_,leng) = bounds cy\n divs = divisors leng\n firstDiv = fromJust $ find (divisorTest cy) divs\n"}], "negative_code": [], "src_uid": "ab99c564f98bc6caea26b28280858c21"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\nimport Control.DeepSeq\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array\r\nimport Data.Array.ST\r\nimport Data.Bits\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ntype Vertex = Int\r\ntype Weight = Int\r\ndata Edge = Edge { w_ :: !Weight, v_ :: !Vertex }\r\n\r\ninstance NFData Edge where\r\n rnf (Edge w v) = w `seq` v `seq` ()\r\n\r\ndata EdgeList = Nil | Cons {-# UNPACK #-} !Edge EdgeList -- For performance reasons only :(\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n void C.getLine -- why?\r\n ~[n, m] <- readInts\r\n g <- fmap (accumArray (flip Cons) Nil (1, n) . concat) $ replicateM m $ do\r\n ~[u, v, w] <- readInts\r\n let es = [(u, Edge w v), (v, Edge w u)]\r\n es `deepseq` pure es\r\n let f msk i = if connected g ((==0) . (msk' .&.)) then msk' else msk where\r\n msk' = msk `setBit` i\r\n print $ ((1 `shiftL` 30) - 1) `xor` foldl' f 0 [29,28..0]\r\n\r\nconnected :: Array Vertex EdgeList -> (Weight -> Bool) -> Bool\r\nconnected g p = runST $ do\r\n let bnds = bounds g\r\n vis :: STUArray s Int Bool <- newArray bnds False\r\n let go u = do\r\n done <- readArray vis u\r\n unless done $ do\r\n writeArray vis u True\r\n filterSequenceEdgeList p go (g!u) :: ST s ()\r\n go (fst bnds)\r\n and <$> getElems vis\r\n\r\nfilterSequenceEdgeList :: Monad m => (Weight -> Bool) -> (Vertex -> m ()) -> EdgeList -> m ()\r\nfilterSequenceEdgeList p f = go where\r\n go Nil = pure ()\r\n go (Cons (Edge w v) es)\r\n | p w = f v >> go es\r\n | otherwise = go es\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\n\nmaxBits :: Int\nmaxBits = 30\n\n-- Perhaps packing (to traverse fewer lists) will help?\nisConnected :: Array Int (UArray Int Int) -> Int -> Bool\nisConnected arr mask = runST $ do\n let (li, ri) = bounds arr\n vis :: STUArray s Int Bool\n <- newArray (li, ri) False :: ST s (STUArray s Int Bool)\n let\n dfs :: Int -> [Int] -> ST s Int\n dfs !ct [] = pure ct\n dfs !ct (v : vs) = do\n isVis <- readArray vis v\n writeArray vis v True\n if isVis\n then dfs ct vs\n else let\n nbrs = do\n uw <- elems $ arr ! v\n let u = uw .&. (bit maxBits - 1)\n w = uw `shiftR` maxBits\n guard $ w .&. mask == w\n pure u\n -- weird concatenation style to prevent thunks from existing\n vs' = foldl' (flip (:)) vs nbrs\n in dfs (ct + 1) vs'\n ccsz <- dfs 0 [li]\n pure $ ccsz == ri + 1 - li\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n es <- replicateM m $ do\n wasThisContributingToBadMemoryUse <- getInts 3\n -- I should profile it, but I don't feel like it right now\n case wasThisContributingToBadMemoryUse of\n [!vi, !ui, !wi] -> pure (vi, ui, wi)\n _ -> error \"bad input format\"\n let\n adj :: Array Int [Int]\n adj = accumArray (flip (:)) [] (1, n) $ do\n (vi, ui, wi) <- es\n let !vw = pack (vi, wi)\n !uw = pack (ui, wi)\n [(ui, vw), (vi, uw)]\n pack (u, w) = u + shiftL w maxBits\n adj2 = (\\li -> listArray (1, length li) li) <$> adj\n isOK :: Int -> Bool\n isOK = isConnected adj2\n solve s j = if j < 0\n then s\n else let\n s' = s - bit j\n in if isOK s'\n then solve s' (j - 1)\n else solve s (j - 1)\n pure $ putInts [solve (bit maxBits - 1) (maxBits - 1)]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\n\nmaxBits :: Int\nmaxBits = 30\n\n-- Perhaps packing (to traverse fewer lists) will help?\nisConnected :: Array Int (UArray Int Int) -> Int -> Bool\nisConnected arr mask = runST $ do\n let (li, ri) = bounds arr\n vis :: STUArray s Int Bool\n <- newArray (li, ri) False :: ST s (STUArray s Int Bool)\n let\n dfs :: Int -> [Int] -> ST s Int\n dfs !ct [] = pure ct\n dfs !ct (v : vs) = do\n isVis <- readArray vis v\n writeArray vis v True\n if isVis\n then dfs ct vs\n else let\n nbrs = do\n uw <- elems $ arr ! v\n let u = uw .&. (bit maxBits - 1)\n w = uw `shiftR` maxBits\n guard $ w .&. mask == w\n pure u\n -- weird concatenation style to prevent thunks from existing\n vs' = foldl' (flip (:)) vs nbrs\n in dfs (ct + 1) vs'\n ccsz <- dfs 0 [li]\n pure $ ccsz == ri + 1 - li\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n es <- replicateM m $ do\n wasThisContributingToBadMemoryUse <- getInts 3\n -- I should profile it, but I don't feel like it right now\n case wasThisContributingToBadMemoryUse of\n [!vi, !ui, !wi] -> pure (vi, ui, wi)\n _ -> error \"bad input format\"\n let\n adj :: Array Int [(Int, Int)]\n adj = accumArray (flip (:)) [] (1, n) $ do\n (vi, ui, wi) <- es\n [(ui, (vi, wi)), (vi, (ui, wi))]\n pack (u, w) = u + shiftL w maxBits\n adj2 = (\\li -> listArray (1, length li) $ map pack li) <$> adj\n isOK :: Int -> Bool\n isOK = isConnected adj2\n solve s j = if j < 0\n then s\n else let\n s' = s - bit j\n in if isOK s'\n then solve s' (j - 1)\n else solve s (j - 1)\n pure $ putInts [solve (bit maxBits - 1) (maxBits - 1)]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "9a2e734bd78ef1e50140f2bb4f57d611"} {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, FlexibleContexts, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport qualified Data.Array.Unboxed as UA\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [Int] -> Builder\nsolve (n:a) = intDec res <> char7 '\\n'\n where\n b = take n a\n !m = maximum b\n x :: UA.UArray Int Int\n x = UA.accumArray (+) 0 (0, m) (zip b (repeat 1))\n !res = runST $ do\n c <- thaw x :: ST s (STUArray s Int Int)\n let \n loop k s = do\n if s > m then return $! (k - 1)\n else do\n w <- readArray c s\n if w > 0 then do\n writeArray c s (pred w)\n loop (succ k) (max (succ k) s)\n else loop k (succ s)\n loop 1 1\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n", "positive_code": [{"source_code": "import Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n unusefulThrash <- getLine\n a <- getLine\n putStrLn $ show $ solve [1..] ((sort . map readInt . words) a)\n\nsolve :: [Int] -> [Int] -> Int\nsolve (x:xs) [] = 0\nsolve (x:xs) (y:ys) = \n if x <= y \n then 1 + solve xs ys\n else solve (x:xs) ys\n"}], "negative_code": [], "src_uid": "4f02ac641ab112b9d6aee222e1365c09"} {"source_code": "import Data.Bits\n\ngetgrundy :: Int -> Int\ngetgrundy 0 = 0\ngetgrundy 1 = 1\ngetgrundy 2 = 2\ngetgrundy x \n | even x = 1\n | otherwise = 0\n \nno1 :: Int -> Int\nno1 1 = 2\nno1 _ = 1\n \ngetgrundy' :: Int -> Int\ngetgrundy' 0 = 0\ngetgrundy' 1 = 1 \ngetgrundy' 2 = 0\ngetgrundy' 3 = 1\ngetgrundy' 4 = 2\ngetgrundy' x\n | even x = no1 $ getgrundy' $ div x 2\n | otherwise = 0\n\n\ncalc :: (Int -> Int) -> [Int] -> Int\ncalc f (x:xs) = xor (f x) (calc f xs) \ncalc _ _ = 0\n\nsolve' :: Int -> [Int] -> Int\nsolve' 0 x = calc getgrundy $ x\nsolve' 1 x = calc getgrundy' $ x\n\n\nsolve ::Int -> [Int] -> String\nsolve k x \n | 0 == solve' k x = \"Nicky\"\n | otherwise = \"Kevin\"\n\n\n \nparse :: String -> String\nparse x = solve (mod (a!!1) 2) (tail $ tail a) where a = map read $ words x\n\nmain = interact parse", "positive_code": [{"source_code": "import Data.Bits (xor)\nimport Data.Char (ord)\nimport Data.List (foldl1')\n\nreadInt :: String -> Int\nreadInt = foldl (\\s c -> s * 10 + ord c - 48) 0\n\ntype Input = (Int, [Int])\n\nparse :: String -> Input\nparse contents = (k, readInts l1)\n where [l0, l1] = lines contents\n [_, k] = readInts l0\n readInts l = map readInt $ words l\n\nsgEven :: Int -> Int\nsgEven n\n | n < 3 = n\n | otherwise = (n + 1) `mod` 2\n\nsgOdd :: Int -> Int\nsgOdd n\n | n < 5 = [0, 1, 0, 1, 2] !! n\n | odd n = 0\n | otherwise = let sg' = sgOdd (n `div` 2) in\n case sg' of\n 0 -> 1\n 1 -> 2\n 2 -> 1\n _ -> undefined\n\nsg :: Int -> Int -> Int\nsg k\n | odd k = sgOdd\n | otherwise = sgEven\n\nsolve :: Input -> Bool\nsolve (k, a) = s == 0\n where s = foldl1' xor . map (sg k) $ a\n\nformat :: Bool -> String\nformat False = \"Kevin\"\nformat True = \"Nicky\"\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}], "negative_code": [], "src_uid": "5ae6585bf96e0bff343bb76c1af3ebc2"} {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, _] <- readChar8'\r\n xs <- fmap (sum . scanl (+) 0) <$> replicateM n readChar8'\r\n let idx = fromMaybe 0 $ findIndex (< mx) xs\r\n mx = maximum xs\r\n printf \"%d %d\\n\" (idx + 1) (mx - xs !! idx)\r\n\r\n\r\n\r\n", "positive_code": [{"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, _] <- readChar8\r\n xs <- fmap (sum . scanl (+) 0) <$> replicateM n readChar8\r\n let idx = fromMaybe 0 $ findIndex (< mx) xs\r\n mx = maximum xs\r\n printf \"%d %d\\n\" (idx + 1) (mx - xs !! idx)\r\n\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "abcafb310d4dcf3f7e34fc4eda1ee324"} {"source_code": "main = getLine >> getLine >>= putStr.unlines.map (show.solve.read).words\n\nsolve :: Integer -> Integer\nsolve n\n | r == 1 = 2*n+1\n | r == 3 = n+1\n | otherwise = 4*n+1\n where r = mod n 4\n", "positive_code": [{"source_code": "main = getContents >>= mapM_ print.map solve. map (\\x -> read x :: Integer). tail. words\n where\n solve x\n | even x = 4*x + 1\n | x `mod` 4 == 3 = x+1\n | otherwise = 2*x+1\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsolve x \n | odd x && (x - 3) `mod` 4 == 0 = x + 1\n | odd x = x * 2 + 1\n | otherwise = x * 4 + 1\n \nmain = B.putStrLn =<< B.unlines . map (B.pack . show . solve . fst . fromJust . B.readInteger) . B.words <$> (B.getLine >> B.getLine) \n"}, {"source_code": "solve :: Integer -> Integer\nsolve n = 1 + div (lcm (4*n) (n + 1)) (n + 1)\n\nmain :: IO ()\nmain = do\n getLine\n xs <- getLine >>= return . map read . words\n mapM_ (print . solve) xs\n"}, {"source_code": "main = do\n getLine -- t\n xs <- (map read . words) `fmap` getLine\n mapM_ (print . solve) xs\n where solve x = lcm (4 * x) (x + 1) `div` (x + 1) + 1"}, {"source_code": "import Control.Applicative\nimport Data.List\n--import Test.QuickCheck\n\nmain'fast :: Integer -> Integer\nmain'fast 1 = 3\nmain'fast n\n | n `mod` 2 == 0 = n * 4 + 1\n | n `mod` 4 == 1 = n * 2 + 1\n | otherwise = n + 1\n\n--main'slow :: Integer -> Integer\nmain'slow n = (+2). genericLength. takeWhile (/=0). tail$ iterate f 0 where\n f x = (x + n + 1) `mod` (n*4)\n\n--prop_main' x = x >= 1 ==> main'slow x == main'fast x\n\nmain = do\n getLine\n ss <- getLine\n putStrLn$ unlines. map (show. main'fast. read). words$ ss\n"}, {"source_code": "calc :: Integer -> Integer\ncalc n = head [i*n+1 | i <- [1..], ((n+1)*n*i) `mod` (n*4) == 0]\n\n\n\nputLs [] = return ()\n\nputLs (x:xs) = do putStrLn x\n\n putLs xs\n\n \n\nmain = do s <- getLine\n\n t <- getLine\n\n putLs $ map (\\a -> show $ calc (read a :: Integer)) $ words t\n\n"}], "negative_code": [{"source_code": "main = getLine >> getLine >>= putStrLn.unlines.map (show.solve.read).words\n\nsolve :: Integer -> Integer\nsolve 1 = 3\nsolve n = 4*n+1\n"}], "src_uid": "168dbc4994529f5407a440b0c71086da"} {"source_code": "{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.Bits\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n:rest0 ->\n let (ls, rest1) = splitAt n rest0\n guess = (\\cand ->\n let ls1 = xor cand <$> ls\n in sort ls == sort ls1\n )\n guessAll = (\\(!curr) -> if\n | curr == 1024 -> -1\n | otherwise -> if guess curr then curr else guessAll (curr+1)\n )\n subres = guessAll 1\n in Just (subres, rest1)\n ) vals\n sequence_ (putStrLn . show <$> res)\n", "positive_code": [{"source_code": "import Data.Set as S\nimport Data.Bits as B\nimport Data.List as L\n\nisMatch :: S.Set Int -> Int -> Bool\nisMatch s n = s == S.map (\\x -> B.xor x n) s\n\nisPossible :: S.Set Int -> Int\nisPossible s = case L.find (\\x -> isMatch s x) [1..1024] of\n (Just a) -> a\n Nothing -> -1\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (L.take n arr):(groupByNLines n (L.drop n arr))\n\nparse :: [String] -> String\nparse [_, input] = show $ isPossible $ S.fromList arr\n where arr = L.map (\\x -> read x :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . L.map parse . groupByNLines 2 . tail . lines)\n"}], "negative_code": [], "src_uid": "3ecb65a8be42f882ae6b528fd86243cd"} {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = show answer\n where\n n::Int64\n as::[Int64]\n n:as = map fastRead (words input)\n arras = A.listArray (0,n-1) as\n\n with_div3_r = snd (foldr rdp_folder (0,[]) as)\n with_div3_l = (reverse.snd) (foldl ldp_folder (0,[]) as)\n with_div3_l_a = A.listArray (1,n) with_div3_l\n\n rsum_div3_r::[Int64]\n rsum_div3_r = take (fromIntegral n) (scanr (+) 0 with_div3_r)\n rsum_div3_r_a = A.listArray (1,n) rsum_div3_r\n\n rdp_folder nextnum (cum,cumxs)\n | ncum == div3 = (ncum, 1:cumxs)\n | otherwise = (ncum, 0:cumxs)\n where ncum = cum+nextnum\n\n ldp_folder:: (Int64,[Int64]) -> Int64 -> (Int64,[Int64])\n ldp_folder (cum,cumxs) nextnum \n | ncum == div3 = (ncum, 1:cumxs)\n | otherwise = (ncum, 0:cumxs)\n where ncum = cum+nextnum\n\n tsum = sum as\n div3 = truncate ((fromIntegral tsum :: Double)/3)\n\n answer = if tsum `mod` 3 == 0 then\n foldl' answer_folder 0 [1..(n-2)]\n else\n 0\n\n answer_folder cumul nextidx \n | with_div3_l_a!nextidx == 1 =\n cumul + rsum_div3_r_a!(nextidx+2)\n | otherwise = cumul\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n let\n s = sum xs\n s3 = s`div`3\n\n ls = map fst $ filter ((== s3) . snd) $ zip [1..] $ scanl1 (+) xs\n rs = map fst $ filter ((== s3) . snd) $ zip [1..] $ scanr1 (+) xs\n\n scan [] _ _ = 0 :: Int64\n scan (l:ls) rs k = (fromIntegral k') + scan ls rs'' k'\n where\n (rs', rs'') = break (l+1 <) rs\n k' = k - length rs'\n\n print $\n if s`mod`3 == 0\n then scan ls rs $ length rs\n else 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.List\nimport Numeric\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve. concat. map (map fastRead.words).take 2.lines\nsolve :: [Integer]-> Integer\nsolve (x:xs) = slv1\n where\n slv1 |sm==[] || x<3 = 0\n |sm==[0] = let l=fromIntegral $ length scn in (l-1)*(l-2) `div` 2\n |otherwise = head $ tail $ foldl (f) [0,0] scn\n where\n f [b1,b2] a = if a==head sm then [1+b1,b2] else [b1,b1+b2]\n sm= let s = sum xs in if s `mod` 3 /=0 then [] else [s `div` 3]\n scn =filter ( f sm) $ tail $ scanl (+) 0 xs\n f [b] a = a== b || a== 2*b\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n show `fmap` solve n `fmap` replicateM n p64\n where\n pop = state $ \\(x:xs) -> (x, xs)\n p64 = fmap (to64 . int) pop\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\n\nsolve :: Int -> [Int64] -> Int64\nsolve n xs = case sum xs `quotRem` 3 of\n (s0, 0) -> sum $ zipWith (*) (take (n - 1) $ map (\\s -> fromIntegral $ fromEnum (s == s0)) $ scanl1 (+) xs) (drop 2 $ scanr (\\s p -> p + fromIntegral (fromEnum $ s == s0)) 0 $ scanr1 (+) xs)\n _ -> 0 :: Int64\n"}, {"source_code": "import Data.Array.ST.Safe\nimport Data.Int\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.STRef\n\nmain = do\n n <- readLn\n as <- map read . words <$> getLine\n print $ runST $ do\n acc <- newArray_ (0,n) :: ST s (STUArray s Int Int64)\n writeArray acc 0 0\n forM_ (zip [1..] as) $ \\(i,a) ->\n writeArray acc i . (a +) =<< readArray acc (i-1)\n\n total <- readArray acc n\n \n ls <- newArray_ (0,n) :: ST s (STUArray s Int Int64)\n writeArray ls 0 0\n forM_ [1..n] $ \\i -> do\n s <- readArray acc i\n writeArray ls i . (fromIntegral (fromEnum (3*s == total)) +)\n =<< readArray ls (i-1)\n\n c <- newSTRef 0\n forM_ [2..n-1] $ \\i -> do\n s <- readArray acc i\n when (3*s == 2*total) $\n modifySTRef' c . (+) =<< readArray ls (i-1)\n readSTRef c\n\n"}, {"source_code": "import Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.g.parse.tail.words\nparse = map fastRead\ng xs\n | i `mod` 3 /= 0 = 0\n | otherwise = f (i `div` 3) 0 xs 0 0\n where i = sum xs\n\nf i tsum (x:[]) a1 a2 = a2\nf i tsum (x:xs) a1 a2\n | h == i && h == j = f i h xs (a1+1) (a2+a1)\n | h == i = f i h xs (a1+1) a2\n | h == j = f i h xs a1 (a2+a1)\n | otherwise = f i h xs a1 a2\n where h = tsum+x\n j = 2*i\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n show `fmap` solve n `fmap` replicateM n p64\n where\n pop = state $ \\(x:xs) -> (x, xs)\n p64 = fmap (to64 . int) pop\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\n\nsolve n xs = case sum xs `quotRem` 3 of\n (s0, 0) -> sum $ zipWith (*) (take (n - 1) $ map (\\s -> fromEnum (s == s0)) $ scanl1 (+) xs) (drop 2 $ scanr (\\s p -> p + fromEnum (s == s0)) 0 $ scanr1 (+) xs)\n _ -> 0 :: Int\n"}, {"source_code": "main = interact $ show.f.a.parse.tail.words\nparse x = map read x :: [Integer]\n\ng [] x y temp z = z\ng (w:ws) x y temp z\n | x == y && w == 0 = g ws x y (temp+1) z\n | x == y && w /= 0 = g ws x w 0 (temp:z)\n | otherwise = g ws x (w+y) temp z\n\nh (x:y:[]) = (x+1)*(y+1)\nh x = 0\n\nf x\n | rem i 3 == 0 = if j == [] then (c (length x)) else (h j)\n | otherwise = 0\n where i = sum x\n j = g x (div i 3) 0 0 []\n\na x = reduce x []\nreduce [] ans = ans\nreduce (x:[]) ans = reduce [] (x:ans)\nreduce (x:y:xs) ans\n | x == 0 = reduce (y:xs) (0:ans)\n | x == (-y) = reduce xs (0:ans)\n | otherwise = reduce (y:xs) (x:ans)\n\nfactorial n = product [1..n]\nc n = (factorial (n-1)) `div` ((factorial (n-3))*2)\n"}, {"source_code": "main = interact $ show.f.a.parse.tail.words\nparse x = map read x :: [Integer]\n\ng [] x y temp z = z\ng (w:ws) x y temp z\n | x == y && w == 0 = g ws x y (temp+1) z\n | x == y && w /= 0 = g ws x w 0 (temp:z)\n | otherwise = g ws x (w+y) temp z\n\nh :: [Integer] -> Integer\nh (x:y:[]) = (x+1)*(y+1)\nh x = 0\n\nf :: [Integer] -> Integer\nf x\n | rem i 3 == 0 = if j == [] then (c (fromIntegral (length x))) else (h j)\n | otherwise = 0\n where i = sum x\n j = g x (div i 3) 0 0 []\n\na x = reduce x []\nreduce [] ans = ans\nreduce (x:[]) ans = reduce [] (x:ans)\nreduce (x:y:xs) ans\n | x == 0 = reduce (y:xs) (0:ans)\n | x == (-y) = reduce xs (0:ans)\n | otherwise = reduce (y:xs) (x:ans)\n\nfactorial :: Integer -> Integer\nfactorial n = product [1..n]\nc n = (factorial (n-1)) `div` ((factorial (n-3))*2)\n"}, {"source_code": "main = interact $ show.f.a.parse.tail.words\nparse x = map read x :: [Integer]\n\ng [] x y temp z = z\ng (w:ws) x y temp z\n | x == y && w == 0 = g ws x y (temp+1) z\n | x == y && w /= 0 = g ws x w 0 (temp:z)\n | otherwise = g ws x (w+y) temp z\n\nh (x:y:[]) = (x+1)*(y+1)\n\nf x\n | rem i 3 == 0 = if j == [] then ((length x) `c` 3) else (h j)\n | otherwise = 0\n where i = sum x\n j = g x (div i 3) 0 0 []\n\na x = reduce x []\nreduce [] ans = ans\nreduce (x:[]) ans = reduce [] (x:ans)\nreduce (x:y:xs) ans\n | x == (-y) = reduce xs (0:ans)\n | otherwise = reduce (y:xs) (x:ans)\n\nfactorial n = product [1..n]\nc n r = (factorial n) `div` ((factorial r)*(factorial (n-r)))\n"}, {"source_code": "main = interact $ show.a.parse.tail.words\nparse x = map read x :: [Integer]\n\ng [] x y temp z = z\ng (w:ws) x y temp z\n | x == y && w == 0 = g ws x y (temp+1) z\n | x == y && w /= 0 = g ws x w 0 (temp:z)\n | otherwise = g ws x (w+y) temp z\n\nzeroes [] ans = ans\nzeroes (x:xs) ans\n | x /= 0 = 0\n | otherwise = zeroes xs (ans+1)\n\nh :: [Integer] -> Integer\nh (x:y:[]) = (x+1)*(y+1)\nh x = 0\n\nf :: [Integer] -> Integer\nf x\n | rem i 3 == 0 = h j\n | otherwise = 0\n where i = sum x\n j = g x (div i 3) 0 0 []\n\na x\n | k /= 0 = (c k)\n | otherwise = f (reduce x [])\n where k = (zeroes x 0)\nreduce [] ans = ans\nreduce (x:[]) ans = reduce [] (x:ans)\nreduce (x:y:xs) ans\n | x == 0 = reduce (y:xs) (0:ans)\n | x == (-y) = reduce xs (0:ans)\n | otherwise = reduce (y:xs) (x:ans)\n\nfactorial :: Integer -> Integer\nfactorial n = product [1..n]\nc n = (factorial (n-1)) `div` ((factorial (n-3))*2)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n s = sum xs\n s3 = s`div`3\n\n ls = map fst $ filter ((== s3) . snd) $ zip [1..] $ scanl1 (+) xs\n rs = map fst $ filter ((== s3) . snd) $ zip [1..] $ scanr1 (+) xs\n\n scan [] _ _ = 0 :: Int64\n scan (l:ls) rs k = (fromIntegral k') + scan ls rs'' k'\n where\n (rs', rs'') = break (l+1 <) rs\n k' = k - length rs'\n\n print $\n if s`mod`3 == 0\n then scan ls rs $ length rs\n else 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n s = sum xs\n s3 = s`div`3\n\n ls = map fst $ filter ((== s3) . snd) $ zip [1..] $ scanl1 (+) xs\n rs = map fst $ filter ((== s3) . snd) $ zip [1..] $ scanr1 (+) xs\n\n scan [] _ _ = 0\n scan (l:ls) rs k = k' + scan ls rs'' k'\n where\n (rs', rs'') = break (l+1 <) rs\n k' = k - length rs'\n\n print $\n if s`mod`3 == 0\n then scan ls rs $ length rs\n else 0\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. concat. map (map read.words).take 2.lines\nsolve :: [Int]-> String\nsolve (x:xs) = show slv1\n where\n slv1 |sm==[] || x<3 = 0\n |sm==[0] = let l=length scn in l*(l-1)*(l-2) `div` 6\n |otherwise = length [1| i<- scn,j<-scn, k<-scn,i Int64\nsolve (x:xs) = slv1\n where\n slv1 |sm==[] || x<3 = 0\n |sm==[0] = let l=fromIntegral $ length scn in (l-1)*(l-2) `div` 2\n |otherwise =snd $ foldl (\\(b1,b2) a -> if a==head sm then (1+b1,b2) else (b1,b1+b2)) (0,0) scn\n sm= let s = sum xs in if s `mod` 3 /=0 then [] else [s `div` 3]\n scn =filter ( f sm) $ tail $ scanl (+) 0 xs\n f [b] a = a== b || a== 2*b"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. concat. map (map read.words).take 2.lines\nsolve :: [Integer]-> String\nsolve (x:xs) = show $ slv1\n where\n slv1 |sm==[] || x<3 = 0\n |sm==[0] = let l=length scn in (l-1)*(l-2) `div` 2\n |otherwise = snd $ foldl (\\(b1,b2) a -> if a==head sm then (1+b1,b2) else (b1,b1+b2)) (0,0) scn\n sm= let s = sum xs in if s `mod` 3 /=0 then [] else [s `div` 3]\n scn =filter ( f sm) $ tail $ scanl (+) 0 xs\n f [b] a = a== b || a== 2*b"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. concat. map (map read.words).take 2.lines\nsolve :: [Int]-> String\nsolve (x:xs) = show $ slv1\n where\n slv1 |sm==[] || x<3 = 0\n |sm==[0] = let l=length scn in (l-1)*(l-2) `div` 2\n |otherwise = snd $ foldl (\\(b1,b2) a -> if a==head sm then (1+b1,b2) else (b1,b1+b2)) (0,0) scn\n sm= let s = sum xs in if s `mod` 3 /=0 then [] else [s `div` 3]\n scn =filter ( f sm) $ tail $ scanl (+) 0 xs\n f [b] a = a== b || a== 2*b"}, {"source_code": "import Data.List\n\n\nmain = interact gen\n\nreplicate_num = 5000\n\ngen input = intercalate \" \" (map show toout)\n where\n toout::[Int]\n toout = (replicate_num*2):numarrs\n numarrs::[Int]\n numarrs = (foldr (++) [] replicated)\n basic::[Int]\n basic = [1,(-1)]\n replicated::[[Int]]\n replicated = replicate replicate_num basic\n"}, {"source_code": "import Data.List\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead s = d\n where\n (d,r) = head (readDec s)\n\nmain = interact solve\n\nsolve input = show answer\n where\n n:as = map read (words input)\n arras = A.listArray (0,n-1) as\n\n with_div3_r = snd (foldr rdp_folder (0,[]) as)\n with_div3_l = (reverse.snd) (foldl ldp_folder (0,[]) as)\n with_div3_l_a = A.listArray (1,n) with_div3_l\n\n rsum_div3_r::[Int]\n rsum_div3_r = take n (scanr (+) 0 with_div3_r)\n rsum_div3_r_a = A.listArray (1,n) rsum_div3_r\n\n rdp_folder nextnum (cum,cumxs)\n | ncum == div3 = (ncum, 1:cumxs)\n | otherwise = (ncum, 0:cumxs)\n where ncum = cum+nextnum\n\n ldp_folder:: (Int,[Int]) -> Int -> (Int,[Int])\n ldp_folder (cum,cumxs) nextnum \n | ncum == div3 = (ncum, 1:cumxs)\n | otherwise = (ncum, 0:cumxs)\n where ncum = cum+nextnum\n\n tsum = sum as\n div3 = truncate ((fromIntegral tsum :: Double)/3)\n\n answer = if tsum `mod` 3 == 0 then\n foldl' answer_folder 0 [1..(n-2)]\n else\n 0\n\n answer_folder cumul nextidx \n | with_div3_l_a!nextidx == 1 =\n cumul + rsum_div3_r_a!(nextidx+2)\n | otherwise = cumul\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Int\nmain = do\n n <- readLn\n a <- listArray (1,n) . scanl1 (+) . map read . words <$> getLine\n let s = a!n\n let ls = listArray (0,n-1) $ scanl (+) 0 $\n map (\\l -> fromIntegral $ fromEnum (3*a!l == s) :: Int64) [2..n]\n let rs = findIndices (\\r -> 3*a!r == 2*s) [1..n-1]\n print $ sum $ map (ls !) rs\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Int\nmain = do\n n <- readLn\n a <- listArray (1,n) . scanl1 (+) . map read . words <$> getLine\n let s = a!n :: Int64\n let ls = listArray (0,n-1) $ scanl (+) 0 $\n map (\\l -> fromIntegral $ fromEnum $ 3*a!l == s :: Int64) [2..n]\n let rs = findIndices (\\r -> 3*a!r == 2*s) [1..n-1]\n print $ sum $ map (ls !) rs\n"}, {"source_code": "import Data.Array\nimport Data.List\nmain = do\n n <- readLn\n a <- listArray (1,n) . scanl1 (+) . map read . words <$> getLine\n let s = a!n\n let ls = listArray (0,n-1) $ scanl (+) 0 $ map (\\l -> fromEnum (3*a!l == s)) [2..n]\n let rs = findIndices (\\r -> 3*a!r == 2*s) [1..n-1]\n print $ sum $ map (\\r -> ls!r) rs\n"}], "src_uid": "2558db57229e55ffe0de0d8cf217035b"} {"source_code": "import qualified Data.Array as A\nimport Data.Char\nimport Data.List\n\nmain = interact $ printAns. (\\(a,b,c) -> solve a b c). readInp\n\nreadInp = prep. lines\n where prep l = ((!! 0). getFst $ l, (!! 1). getFst $ l, tail l)\n getFst = fmap read. words. head\nprintAns = show\n\nsolve :: Int -> Int -> [String] -> Int\nsolve n m a = minimum ops\n where \n costs = A.listArray (0, n-1) (map cost a)\n cost l = A.listArray (0, 2) [d isAlpha l, d isDigit l, d isRest l]\n where isRest c = (&&) (not (isAlpha c)) (not (isDigit c))\n d f = minimum. (inf :). map (dist. fst). filter (f. snd). zip [0..]\n where dist i = min i (m - i)\n inf = 10^8 + 23\n\n ops = [op i j k | i <- [0..n-1], j <- [0..n-1], k <- [0..n-1], i /= j, i /= k, j /= k]\n op i j k = getC i 0 + getC j 1 + getC k 2\n where getC a b = costs A.! a A.! b\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array\nimport Data.Char\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = map readInt . B.words\n\nklass c \n | isDigit c = 0\n | isAsciiLower c = 1\n | otherwise = 2\n\nsolve ms n m = minimum [tbl!(i, 0) + tbl!(j, 1) + tbl!(k, 2) | i:j:k:_ <- sequence $ replicate 3 [1..n], i /= j, j /= k, k /= i]\n where\n ms' = listArray (1, n) ms\n tbl = array ((1, 0), (n, 2)) [((i, k), go i k) | i <- [1..n], k <- [0..2]]\n go i k = let s = ms'!i in minimum $ 10000:[min j (m - j) | j <- [0..m - 1], klass (s `B.index` j) == k]\n\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n ms <- replicateM n B.getLine\n print $ solve ms n m"}, {"source_code": "import qualified Data.Array as A\nimport Data.Char\nimport Data.List\nimport Control.Applicative\n\nmain = interact $ printAns. (\\(a,b,c) -> solve a b c). readInp\n\nreadInp = prep. lines\n where prep l = ((!! 0). getFst $ l, (!! 1). getFst $ l, tail l)\n getFst = fmap read. words. head\nprintAns = show\n\nsolve :: Int -> Int -> [String] -> Int\nsolve n m a = minimum ops\n where \n costs = A.listArray (0, n-1) (map cost a)\n cost = A.listArray (0, 2). zipWith d [isAlpha, isDigit, isRest]. repeat\n where isRest c = not. or. map ($ c) $ [isAlpha, isDigit]\n d f = minimum. (inf :). map (dist. fst). filter (f. snd). zip [0..]\n where dist i = min i (m - i)\n inf = 10^8 + 23\n\n ops = [op i j k | i <- [0..n-1], j <- [0..n-1], k <- [0..n-1], i /= j, i /= k, j /= k]\n where op i j k = sum. zipWith getC [i,j,k] $ [0, 1, 2]\n getC a b = costs A.! a A.! b\n bad (a,b,c) = a == b || b == c || a == c\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE FlexibleContexts #-}\n\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.MArray.Safe\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Bits\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine\n css <- replicateM n getLine\n print $ solve n css\n\nsolve :: Int -> [String] -> Int\nsolve n css = fromJust $ minCostFlow (n+5) numE gr src sink 3\n where\n num = n\n alpha = n + 1\n symbol = n + 2\n src = n + 3\n sink = n + 4\n numE = 4 * n + 3\n gr = [(num, sink, 0, 1), (alpha,sink,0,1), (symbol,sink,0,1)]\n ++ [(src,i,0,1)|i<-[0..n-1]]\n ++ concat[[(i,num,x,1),(i,alpha,y,1),(i,symbol,z,1)]|(i,cs)<-zip[0..]css,let(x,y,z)=calc cs]\n\nconvert c\n | '0' <= c, c <= '9' = 0\n | 'a' <= c, c <= 'z' = 1\n | otherwise = 2\n\ncalc cs = go inf inf inf $ zip [0..] ns ++ zip [1..](reverse$tail ns)\n where\n ns = map convert cs\n go !x !y !z ((i,c):rest)\n | c == 0 = go (min i x) y z rest\n | c == 1 = go x (min i y) z rest\n | otherwise = go x y (min i z) rest\n go !x !y !z [] = (x, y, z)\n\n\ntype Vertex = Int\ntype Edge = Int\ntype Cost = Int\ntype Cap = Int\n\ninf :: Cost\ninf = 0x3f3f3f3f\n{-# INLINE inf #-}\n\n-- Just cost -> flow0\u6d41\u3057\u305f\u6642\u306e\u6700\u5c0f\u8cbb\u7528\u304ccost\n-- Nothing -> flow0 \u3092\u6d41\u3059\u3053\u3068\u306f\u51fa\u6765\u306a\u3044\nminCostFlow :: Int -> Int -> [(Vertex,Vertex,Cost,Cap)] -> Vertex -> Vertex -> Cap -> Maybe Cost\nminCostFlow numv nume vvccs source sink flow0 = runST $ do\n gr <- newArray (0,numv-1) [] :: ST s (STArray s Vertex [Edge])\n residual <- newArray (0,2*nume-1) 0 :: ST s (STUArray s Edge Cap)\n to <- newArray_ (0,2*nume-1) :: ST s (STUArray s Edge Vertex)\n cost <- newArray_ (0,2*nume-1) :: ST s (STUArray s Edge Cost)\n potential <- newArray (0,numv-1) 0 :: ST s (STUArray s Vertex Cost)\n dist <- newArray (0,numv-1) inf :: ST s (STUArray s Vertex Cost)\n prevv <- newArray (0,numv-1) (-1) :: ST s (STUArray s Vertex Vertex)\n preve <- newArray (0,2*nume-1) (-1) :: ST s (STUArray s Vertex Edge)\n\n let mkGraph !i ((v,nv,c,cap):vvccs) = do\n modifyArray gr v (i:) >> modifyArray gr nv ((i+1):)\n writeArray to i nv >> writeArray to (i+1) v\n writeArray cost i c >> writeArray cost (i+1) (-c)\n writeArray residual i cap\n mkGraph (i+2) vvccs\n mkGraph _ _ = return ()\n\n let dijkstra (Fork v c hs) = do\n dv <- readArray dist v\n if c > dv then dijkstra $ mergePairs hs\n else do\n es <- readArray gr v\n hs' <- forM es $ \\e -> do\n nv <- readArray to e\n cap <- readArray residual e\n hv <- readArray potential v\n hnv <- readArray potential nv\n v2nv <- readArray cost e\n old <- readArray dist nv\n let dnv = dv + v2nv + hv - hnv\n if cap > 0 && dnv < old then do\n writeArray dist nv dnv\n writeArray prevv nv v\n writeArray preve nv e\n return $ Fork nv dnv []\n else return Empty\n dijkstra $ mergePairs hs `merge` mergePairs hs'\n dijkstra Empty = readArray dist sink\n\n let update flow = go sink flow\n where\n go !v !f = do\n pv <- readArray prevv v\n if pv < 0 then return f\n else do\n pv2v <- readArray preve v\n nf <- readArray residual pv2v >>= go pv . min f\n modifyArray residual pv2v (subtract nf)\n modifyArray residual (xor pv2v 1) (nf+)\n return nf\n\n let primalDual !flow !res\n | flow == 0 = return $ Just res\n | otherwise = do\n rep numv $ \\i ->\n writeArray dist i inf\n writeArray dist source 0\n dsink <- dijkstra $ Fork source 0 []\n if dsink == inf then return Nothing\n else do\n rep numv $ \\v-> do\n dv <- readArray dist v\n modifyArray potential v (dv+)\n f <- update flow\n hsink <- readArray potential sink\n primalDual (flow - f) $ hsink * f + res\n\n mkGraph 0 vvccs\n primalDual flow0 0\n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\n\n-- Pairing heap for Dijkstra\ndata Heap = Fork {-# UNPACK #-} !Vertex\n {-# UNPACK #-} !Cost\n [Heap]\n | Empty\n\nmerge :: Heap -> Heap -> Heap\nmerge hx@(Fork _ x _) hy@(Fork _ y _)\n | x <= y = join hx hy\n | otherwise = join hy hx\n where\n join (Fork v cost hs) h = Fork v cost (h:hs)\nmerge Empty hy = hy\nmerge hx Empty = hx\n\nmergePairs :: [Heap] -> Heap\nmergePairs [] = Empty\nmergePairs [x] = x\nmergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array\nimport Data.Char\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = map readInt . B.words\n\nklass c \n | isDigit c = 0\n | isAsciiLower c = 1\n | otherwise = 2\n\nsolve ms n m = minimum [tbl!(i, 0) + tbl!(j, 1) + tbl!(k, 2) | i:j:k:_ <- sequence $ replicate 3 [1..n], i /= j, j /= k]\n where\n ms' = listArray (1, n) ms\n tbl = array ((0, 0), (n, 2)) [((i, k), go i k) | i <- [0..n], k <- [0..2]]\n go 0 _ = 10000\n go i k = let s = ms'!i in minimum $ tbl!(i-1, k):[min j (m - j) | j <- [0..m - 1], klass (s `B.index` j) == k]\n\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n ms <- replicateM n B.getLine\n print $ solve ms n m"}, {"source_code": "import qualified Data.Array as A\nimport Data.Char\nimport Data.List\n\nmain = interact $ printAns. (\\(a,b,c) -> solve a b c). readInp\n\nreadInp = prep. lines\n where prep l = ((!! 0). getFst $ l, (!! 1). getFst $ l, tail l)\n getFst = fmap read. words. head\nprintAns = show\n\nsolve :: Int -> Int -> [String] -> Int\nsolve n m a = minimum ops\n where \n costs = A.listArray (0, n-1) (map cost a)\n cost l = A.listArray (0, 2) [d isAlpha l, d isDigit l, d isRest l]\n isRest c = (&&) (not (isAlpha c)) (not (isDigit c))\n d f = minimum. (alot :). map (dist. fst). filter (f. snd). zip [1..]\n dist i = min i (m - i)\n alot = 10^8 + 23\n\n ops = [op i j k | i <- [0..n-1], j <- [0..n-1], k <- [0..n-1], i /= j, i /= k, j /= k]\n op i j k = getC i 0 + getC j 1 + getC k 2\n where getC a b = costs A.! a A.! b\n"}], "src_uid": "b7ff1ded73a9f130312edfe0dafc626d"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nitof :: Int -> Double\nitof = fromIntegral\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n n <- readLn\n l <- replicateM n getLine\n s <- getLine\n let s' = encodeMessage l\n putStrLn $ case match s' s of\n True -> \"yes\"\n False -> \"no\"\n\nencodeMessage :: [String] -> String\nencodeMessage l = concat $ [\"<3\"++w | w <- l] ++ [\"<3\"]\n\nmatch ptn str = go ptn str\n where\n go [] _ = True\n go _ [] = False\n go (x:xs) (y:ys) | x == y = go xs ys\n | otherwise = go (x:xs) ys\n", "positive_code": [{"source_code": "\nimport Control.Monad (replicateM)\nimport Data.List (intersperse)\n\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\nsolve :: [String] -> String -> Bool\nsolve ss ms = solve' ss' ms\n where\n ss' = concat [word, concat $ intersperse word ss, word]\n word = \"<3\"\n solve' \"\" _ = True\n solve' _ \"\" = False\n solve' (s:ss) (m:ms)\n | s == m = solve' ss ms\n | otherwise = solve' (s:ss) ms\n\nmain :: IO ()\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n ms <- getLine\n putStrLn $ (solve ss ms) ? \"yes\" $ \"no\"\n"}, {"source_code": "module Main where\nimport Control.Applicative\n-- import Control.Monad\nimport Data.List\nmain :: IO ()\nmain = do\n _ <- read <$> getLine :: IO Int\n res <- lines <$> getContents :: IO [String]\n let msg:ws = let x:xs = reverse res\n in x:reverse xs\n expectedSs = \"<3\" ++ intercalate \"<3\" ws ++ \"<3\"\n stripChars [] _ = []\n stripChars (ch:chs) ch'\n | ch == ch' = chs\n | otherwise = ch:chs\n -- putStrLn expectedSs\n putStr $\n case foldl stripChars expectedSs msg of\n \"\" -> \"yes\"\n _ -> \"no\"\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nsearch :: String -> String -> Bool\nsearch [] _ = True\nsearch (x:xs) [] = False\nsearch s1@(x:xs) (y:ys)\n | x == y = search xs ys\n | otherwise = search s1 ys\n\nmain :: IO ()\nmain = do\n n <- (read <$> getLine) :: IO Int \n wlist <- replicateM n $\n getLine\n \n let str = (concatMap (\"<3\"++) wlist ++ \"<3\")\n bigstr <- getLine\n\n if search str bigstr\n then putStrLn \"yes\"\n else putStrLn \"no\""}, {"source_code": "import Control.Monad (replicateM)\n\nmain = do\n n <- fmap read getLine\n messageWords <- replicateM n getLine\n message <- getLine\n putStrLn $ if solve messageWords message then \"yes\" else \"no\"\n \nintersperse' :: a -> [a] -> [a]\nintersperse' y = foldr (\\x acc -> y:x:acc) [y]\n\nsolve :: [String] -> String -> Bool\nsolve messageWords = matches (intersperse' \"<3\" messageWords)\n\nmatches :: [String] -> String -> Bool\nmatches [] _ = True\nmatches (w:ws) text = case w `subSeqOf` text of\n Nothing -> False\n Just text' -> matches ws text'\n\nsubSeqOf :: String -> String -> Maybe String\nsubSeqOf \"\" txt = Just txt\nsubSeqOf _ \"\" = Nothing\nsubSeqOf (c:cs) (t:txt)\n | c == t = subSeqOf cs txt\n | otherwise = subSeqOf (c:cs) txt"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM)\nimport Data.Functor ((<$>))\nimport qualified Data.ByteString as B\n\nmain = do\n n <- fmap read getLine\n messageWords <- B.concat . intersperse' \"<3\" <$> replicateM n (fmap B.init B.getLine)\n message <- B.getLine\n putStrLn $ if solve messageWords message then \"yes\" else \"no\"\n \n{-# INLINE intersperse' #-}\nintersperse' :: a -> [a] -> [a]\nintersperse' y = foldr (\\x acc -> y:x:acc) [y]\n\nsolve :: B.ByteString -> B.ByteString -> Bool\nsolve \"\" txt = True\nsolve _ \"\" = False\nsolve words text\n | B.head words == B.head text = solve (B.tail words) (B.tail text)\n | otherwise = solve words (B.tail text)"}], "negative_code": [{"source_code": "module Main where\nimport Control.Applicative\n-- import Control.Monad\nimport Data.List\nmain :: IO ()\nmain = do\n _ <- read <$> getLine :: IO Int\n res <- lines <$> getContents :: IO [String]\n let msg:ws = let x:xs = reverse res\n in x:reverse xs\n expectedSs = \"<3\" ++ intercalate \"<3\" ws ++ \"<3\"\n stripChars [] _ = []\n stripChars (ch:chs) ch'\n | ch == ch' = chs\n | otherwise = ch:chs\n putStrLn expectedSs\n putStr $\n case foldl stripChars expectedSs msg of\n \"\" -> \"yes\"\n _ -> \"no\"\n"}, {"source_code": "module Main where\nimport Control.Applicative\n-- import Control.Monad\nimport Data.List\nmain :: IO ()\nmain = do\n _ <- read <$> getLine :: IO Int\n res <- lines <$> getContents :: IO [String]\n let msg:ws = let x:xs = reverse res\n in x:reverse xs\n expectedSs = intercalate \"<3\" ws\n stripChars [] _ = []\n stripChars (ch:chs) ch'\n | ch == ch' = chs\n | otherwise = ch:chs\n putStr $\n case foldl stripChars expectedSs msg of\n \"\" -> \"yes\"\n _ -> \"no\"\n"}], "src_uid": "36fb3a01860ef0cc2a1065d78e4efbd5"} {"source_code": "import Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.STRef\n\n\noperate :: [[Integer]] -> Integer\noperate l = runST $ do\n cnt <- newSTRef (head (head l))\n summ <- newSTRef (0::Integer)\n mapM_ (\\(x:y:xs) -> do\n cur <- readSTRef cnt\n if cur <= x then modifySTRef summ (+y) >>\n writeSTRef cnt (x+1)\n else return ()\n ) l\n readSTRef summ\n\ncomp :: [Integer] -> [Integer] -> Ordering\ncomp (a:[]) _ = LT\ncomp _ (a:[]) = GT\ncomp (a:b:[]) (c:d:[]) = if (a < c) then LT\n else if (a > c) then GT\n else if (b < d) then GT\n else if (b > d) then LT\n else EQ\n\nmain :: IO ()\nmain = do\n cn <- B.getContents\n let parsed = map ((map (\\l -> let res = B.readInteger l in\n case res of\n Just a -> fst a\n otherwise -> 0::Integer)) . B.words\n ) (B.lines cn)\n let res = sortBy comp parsed\n\n let ans = operate (tail (tail res))\n print ans\n return ()\n", "positive_code": [{"source_code": "module Main where\n\nimport qualified Data.IntMap.Strict as M\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.ByteString as BS\n\ngetElements :: IO ((M.IntMap Int,M.IntMap Int))\ngetElements = do\n input <- fmap (C.split '\\n') $ BS.getContents\n let count1 = read . C.unpack . head $ input\n list1 = [(v1, v2) | edgeBS <- take count1 . tail $ input,\n let [v1', v2'] = C.split ' ' edgeBS\n Just (v1,_) = C.readInt v1'\n Just (v2,_) = C.readInt v2']\n list2 = [(v1, v2) | edgeBS <- drop (count1 + 2) input, not $ BS.null edgeBS,\n let [v1', v2'] = C.split ' ' edgeBS\n Just (v1,_) = C.readInt v1'\n Just (v2,_) = C.readInt v2']\n return (M.fromList list1, M.fromList list2)\n \n\nmain = do\n (top, forces) <- getElements\n let income = M.foldl (\\acc income ->\n acc + toInteger income) (0 :: Integer) $ M.unionWith max forces top\n print income \n"}], "negative_code": [{"source_code": "module Main where\n\nimport qualified Data.IntMap.Strict as M\n\ngetElements :: IO (M.IntMap Int)\ngetElements = do\n count <- fmap read getLine\n list <- sequence $ take count $ repeat $ do\n [id, income] <- fmap (map read . words) getLine\n return (id, income)\n return $ M.fromList list\n\nmain = do\n forces <- getElements\n top <- getElements\n let intersection = M.intersectionWith max forces top\n difference1 = M.difference forces top\n difference2 = M.difference top forces\n income = M.foldl (+) 0 $ M.unions [intersection, difference1, difference2]\n print income \n"}, {"source_code": "module Main where\n\nimport qualified Data.IntMap.Strict as M\n\ngetElements :: IO (M.IntMap Int)\ngetElements = do\n count <- fmap read getLine\n list <- sequence $ take count $ repeat $ do\n [id, income] <- fmap (map read . words) getLine\n return (id, income)\n return $ M.fromList list\n\nmain = do\n forces <- getElements\n top <- getElements\n let income = M.foldl (+) 0 $ M.unionWith max forces top\n print income \n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.Foldable as F\nimport Data.List\nimport qualified Data.Map as M\n\ntype MII = M.Map Int Int\n\noperate :: [[Int]] -> State MII Int\noperate inp = do\n forM_ inp (\\(x:y:xs) -> do\n m <- get\n let a = M.lookup x m\n case a of\n Nothing -> put (M.insert x y m)\n Just pr -> if (pr < y) then put (M.insert x y m)\n else return ()\n )\n m <- get\n return $ F.foldl (+) 0 m\n\nmain :: IO ()\nmain = do\n n <- getLine\n let nn = read n :: Int\n inpn <- replicateM nn getLine\n let inppn = map ((map read) . words) inpn\n let inpppn = map (\\(x:y:xs) -> (x, y)) inppn\n let mp = M.fromList inpppn\n m <- getLine\n let mm = read m :: Int\n inpm <- replicateM mm getLine\n let inpmm = map ((map read) . words) inpm\n print $ evalState (operate inpmm) mp\n return ()\n"}], "src_uid": "fe5c302d844b0b94d030b180e017b9b2"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain :: IO ()\nmain = do\n (n,m) <- readIntPair\n l <- replicateM m $ do\n [t,l,r,d] <- readInts\n return (t,l,r,d)\n case solve n l of\n Nothing -> putStrLn \"NO\"\n Just xs -> do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ xs\n\ntype Op = (Int,Int,Int,Int)\nsolve :: Int -> [(Int,Int,Int,Int)] -> Maybe [Int]\nsolve n l = guard (check n l xs) >> return xs\n where\n xs = elems ans\n ans :: UArray Int Int\n ans = runSTUArray $ do\n a <- newArray (1,n) inf :: ST s (STUArray s Int Int)\n b <- newArray (1,n) 0 :: ST s (STUArray s Int Int)\n forM_ l $ \\l -> case l of\n (1,l,r,d) ->\n forM_ [l..r] $ \\i -> do\n x <- readArray b i\n writeArray b i (x+d)\n (2,l,r,d) ->\n forM_ [l..r] $ \\i -> do\n x <- readArray a i\n y <- readArray b i\n writeArray a i (min x (d - y))\n return a\n\ninf :: Int\ninf = 10^9\ncheck :: Int -> [(Int,Int,Int,Int)] -> [Int] -> Bool\ncheck n l xs = maximum (map abs xs) <= inf && (isJust $ foldM f init l)\n where\n init :: UArray Int Int\n init = listArray (1,n) xs\n f a (1,l,r,d) = return $ accum (+) a[(i,d) | i <- [l..r]]\n f a (2,l,r,d) = do\n guard $ d == maximum [ a ! i | i <- [l..r]]\n return a\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain :: IO ()\nmain = do\n (n,m) <- readIntPair\n l <- replicateM m $ do\n [t,l,r,d] <- readInts\n return (t,l,r,d)\n case solve n l of\n Nothing -> putStrLn \"NO\"\n Just xs -> do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ xs\n\ntype Op = (Int,Int,Int,Int)\nsolve :: Int -> [(Int,Int,Int,Int)] -> Maybe [Int]\nsolve n l = guard (check n l xs) >> return xs\n where\n xs = elems ans\n ans :: UArray Int Int\n ans = go (listArray (1,n) (repeat inf)) (listArray (1,n) (repeat 0)) l\n go :: UArray Int Int -> UArray Int Int -> [Op] -> UArray Int Int\n go a _ [] = a\n go !a !b ((1,l,r,d):ls) = go a (accum (+) b [(i,d) | i <- [l..r]]) ls\n go !a !b ((2,l,r,d):ls) = go (accum min a [(i,d - b ! i) | i <- [l..r]])b ls\n\ninf :: Int\ninf = 10^9\ncheck :: Int -> [(Int,Int,Int,Int)] -> [Int] -> Bool\ncheck n l xs = maximum (map abs xs) <= inf && (isJust $ foldM f init l)\n where\n init :: UArray Int Int\n init = listArray (1,n) xs\n f a (1,l,r,d) = return $ accum (+) a[(i,d) | i <- [l..r]]\n f a (2,l,r,d) = do\n guard $ d == maximum [ a ! i | i <- [l..r]]\n return a"}, {"source_code": "{-# LANGUAGE BangPatterns,TupleSections #-}\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair :: IO (Int,Int)\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\n\ntype Op = (Int,Int,Int,Int)\ninf :: Int\ninf = 10^(9::Int)\n\nmain :: IO ()\nmain = do\n (n,m) <- readIntPair\n l <- replicateM m $ do\n [t,l,r,d] <- readInts\n return (t,l,r,d)\n case solve n l of\n Nothing -> putStrLn \"NO\"\n Just xs -> do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ xs\n\nsolve :: Int -> [Op] -> Maybe [Int]\nsolve n ops = guard (check n ops xs) >> return xs\n where\n xs = elems $ go (g inf) (g 0) ops\n g k = listArray (1,n) (repeat k)\n go :: UArray Int Int -> UArray Int Int -> [Op] -> UArray Int Int\n go a _ [] = a\n go !a !b ((1,l,r,d):ls) = go a (accum (+) b [(i,d) | i <- [l..r]]) ls\n go !a !b ((2,l,r,d):ls) = go (accum min a [(i,d - b ! i) | i <- [l..r]])b ls\n\ncheck :: Int -> [Op] -> [Int] -> Bool\ncheck n ops xs = maximum (map abs xs) <= inf && (isJust $ foldM f e ops)\n where\n e = listArray (1,n) xs :: UArray Int Int\n f a (1,l,r,d) = return $ accum (+) a [(i,d) | i <- [l..r]]\n f a (2,l,r,d) = guard (d == maximum [ a ! i | i <- [l..r]]) >> return a\n"}], "negative_code": [], "src_uid": "ae5757df3be42b74076cdf42f7f897cd"} {"source_code": "import Control.Monad (replicateM)\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nmini :: Int -> Int -> Int\r\nmini a b\r\n | a > b = b\r\n | otherwise = a\r\n\r\nmaxi :: Int -> Int -> Int\r\nmaxi a b\r\n | a > b = a\r\n | otherwise = b\r\n\r\nsolve = do xs <- (map read . words) <$> getLine\r\n if ((mini (xs !! 0) (xs !! 1)) > (maxi (xs !! 2) (xs !! 3))) || ((maxi (xs !! 0) (xs !! 1)) < (mini (xs !! 2) (xs !! 3)))\r\n then putStrLn \"NO\"\r\n else putStrLn \"YES\"\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString as Bs\nimport Control.Monad\n\nless a b = if a < b then a else b\n\n\nmore a b = if a > b then a else b\n\nfair :: Int -> Int -> Int -> Int -> String\nfair a b c d = if less c d > (more a b) || (less a b) > (more c d)\n then \"NO\"\n else \"YES\"\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\nsolve :: IO()\nsolve = do\n -- n <- readLn :: IO Int\n a <- readintrows 1\n putStrLn $ fair (head (head a)) (head a !! 1) (head a !! 2) (head a !! 3)\n\n\nreadrows :: (Integral b) => b -> IO [String]\nreadrows 0 = return []\nreadrows n = do\n row <- getLine\n l <- readrows $ n-1\n return (row : l)\n\nreadintrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadintrows 0 = return []\nreadintrows n = do\n row <- readInts\n l <- readintrows $ n-1\n return (row : l)\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n"}, {"source_code": "import Data.Bool ( bool )\r\n\r\nisFair :: [Int] -> Bool\r\nisFair [a, b, c, d]\r\n | max a b < min c d = False\r\n | max c d < min a b = False\r\n | otherwise = True\r\n\r\nmain = interact $ unlines . map solve . tail . lines\r\n where solve = bool \"NO\" \"YES\" . isFair . map read . words\r\n"}, {"source_code": "import Data.List (sort)\r\n\r\npairToList (a, b) = [a, b]\r\n\r\nsolve :: [Int] -> String\r\nsolve l =\r\n if drop 2 (sort l) ==\r\n sort (map maximum $ pairToList $ splitAt 2 l) then\r\n \"Yes\"\r\n else\r\n \"No\"\r\n\r\nmain = interact $ unlines . map (solve . map read . words) . tail . lines\r\n"}, {"source_code": "import Data.List (sort)\r\n\r\npairToList (a, b) = [a, b]\r\n\r\nsolve :: [Int] -> String\r\nsolve l =\r\n if sort (drop 2 $ sort l) ==\r\n sort (map maximum $ pairToList $splitAt 2 l) then\r\n \"Yes\"\r\n else\r\n \"No\"\r\n\r\nmain = interact $ unlines . map (solve . map read . words) . tail . lines\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Bool\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n a <- readMany :: IO [Int]\r\n let [p, q] = drop 2 $ map snd $ sort $ zip a [0..]\r\n chk p q = p < 2 && q >= 2\r\n putStrLn $ bool \"NO\" \"YES\" $ chk p q || chk q p\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: [Int] -> String\ncalc l@[a,b,c,d] =\n let s = take 2 $ reverse $ sort l\n final = reverse $ sort [max a b, max c d]\n in\n if s == final then\n \"YES\"\n else\n \"NO\"\n\ncalc _ = \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let lst = map read $ words line :: [Int]\n putStrLn $ calc lst\n"}, {"source_code": "import Data.List\nimport Control.Arrow\n\nsolve x = \n let y = (uncurry (==)) . ((`div`2)***(`div`2)) . (\\[x,y] -> (x,y)) . drop 2 . map fst . sortOn snd . zip [0..] $ x\n in if y then \"NO\" else \"YES\"\n\nmain = interact $ unlines . map (solve . map (read :: String -> Int) . words ) . tail . lines \n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List(sort)\r\nimport Data.Bool(bool)\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1\r\n >>> map (words >>> map read >>> solve >>> bool \"NO\" \"YES\")\r\n >>> unlines\r\n\r\nsolve :: [Int] -> Bool\r\nsolve ss@[s1, s2, s3, s4] = max s1 s2 + max s3 s4 == (sum . drop 2 . sort $ ss)\r\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n [a,b,c,d] <- readInts\r\n putStrLn $ if max a b > min c d && max c d > min a b then \"YES\" else \"NO\"\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport System.IO\r\nimport Data.Char\r\nimport Data.Array\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\nsolve = do \r\n [x,y,z,t] <- readInts \r\n let max1 = minimum [(maximum [x,y]), (maximum [z,t])]\r\n max2 = maximum [(maximum [x,y]), (maximum [z,t])]\r\n let a = reverse $ sort [x,y,z,t]\r\n putStrLn $ if max2 == head a && max1 == (head $ tail a) then \"YES\" else \"NO\"\r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t solve "}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n [s1, s2, s3, s4] <- map parseInt . BS.words <$> BS.getLine\r\n let r = min s1 s2 > max s3 s4 || min s3 s4 > max s1 s2\r\n putStrLn $ bool \"YES\" \"NO\" r\r\n"}, {"source_code": "--1535/problem/A. Fair Playoff\r\n\r\nimport Data.List\r\n\r\ntoInt :: (String -> Int)\r\ntoInt x = read x ::Int\r\n\r\ngetInts = do\r\n x <- getLine\r\n let y = (map$toInt)$words x\r\n return y\r\n\r\nloop i f\r\n |i==1 = f\r\n |otherwise = do\r\n f\r\n loop (i-1) f\r\n\r\nisFair_co :: [Int]->String\r\nisFair_co lst = do\r\n if (reverse$sort$take 2 lst)==(take 2 (reverse$sort lst)) then\r\n \"NO\"\r\n else if (sort$drop 2 lst)==(drop 2 (sort lst)) then\r\n \"NO\"\r\n else\r\n \"YES\"\r\nisFair = do\r\n lst <- getInts\r\n putStrLn$isFair_co lst\r\n\r\nmain = do\r\n n' <- getLine\r\n let n = toInt n'\r\n\r\n loop n isFair\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\n-- import Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\t[ a, b, c, d ] <- readInts\r\n\tputStrLn $ if drop 2 ( sort [ a, b, c, d ] ) == sort [ max a b, max c d ]\r\n\t\tthen \"YES\"\r\n\t\telse \"NO\""}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n as@[a1, a2, a3, a4] <- getInts\n let result = sort [max a1 a2, max a3 a4] == drop 2 (sort as)\n return $ string7 (if result then \"YES\" else \"NO\") `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "cb24509580ff9b2f1a11103a0e4cdcbd"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.ST.Lazy.Safe (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy.Safe as STL\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n as <- unfoldr (runStateT rIntS) <$> BS.getLine\n print $ length $ filter id $ zipWith (==) [1..] $ scanl1 max as\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nf x m a i = if null x then a else if i == (max m $ head x) then f (tail x) (head x) (a+1) (i+1) else f (tail x) (max m $ head x) a (i+1)\nint = fst .fromJust .B.readInt\nints = map int . B.words <$> B.getLine\n_' = B.getLine\n\nmain = _' >> ints >>= \\x -> print $ f x 0 0 1\n\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve xs = fst . foldl (\\(a, b) (c, i) -> \n if (max c b) > i \n then (a, max c b)\n else (a + 1, i)) (0, 0) $ zip xs [1..]\n\nmain :: IO ()\nmain = do\n _ <- readInt\n xs <- readInts\n print $ solve xs"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [Int] -> Builder\nsolve (!n:a) = intDec res <> char7 '\\n'\n where\n b = take n a\n res = length $ filter id $ zipWith (==) [(1::Int) ..] $ scanl1 max b\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}], "negative_code": [], "src_uid": "291601d6cdafa4113c1154f0dda3470d"} {"source_code": "--first time I'm actually using Haskell for a contest (or anything of significance), so ...\n--let's hope we don't get problems that require mutable state (or I'll be spending rest of contest reading about State monad)\n\n--{-# LANGUAGE ScopedTypeVariables #-} --used for annotating monadic values\nimport Data.List\nimport Control.Monad\n--import Control.Monad.State.Strict\n\n--TODO: make better boilerplate code for I/O, parsing etc\nparseLine = fmap (map read . words)\n--toSpaced = intercalate \" \" . map show\n--printSpaced = putStrLn . toSpaced\n\nlast_n n = reverse . take n . reverse\n\nf s t 0 = s\nf s t k =\n let\n l = length t\n allowed = filter (\\index -> (last_n (l - index) s) == (take (l - index) t)) [1..length t]\n min_allowed = head allowed\n in f (s ++ last_n min_allowed t) t (k - 1)\n\nmain :: IO ()\nmain = do\n [n, k] <- parseLine getLine :: IO [Int]\n t <- getLine :: IO String\n let ans = f t t (k - 1)\n putStrLn ans\n\n return ()\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain = sol <$> get <*> getLine >>= putStrLn\n\n--get :: IO [Int]\nget = fmap read . words <$> getLine\n\nsol [n,k] t = fromJust . find (isPrefixOf t) . fmap (f k t) . tail . inits $ t\n\nf k t = ((++) . join . replicate k) <*> (flip drop t . length)\n\nsol' [n,k] t = show n ++ show k ++ t"}, {"source_code": "overlap s = let n = length s in head [x | x <- [1..n], drop x s == take (n - x) s]\n\nmain = do\n [n, k] <- (map read . words) `fmap` getLine\n t <- getLine\n let o = overlap t\n putStrLn (concat (replicate k (take o t)) ++ drop o t)"}], "negative_code": [], "src_uid": "34dd4c8400ff7a67f9feb1487f2669a6"} {"source_code": "import Control.Monad ( replicateM )\nimport Data.List (foldl')\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n resp <- replicateM t $ do\n solve <$> getLine\n putStrLn . unlines $ [if ans then \"YES\" else \"NO\" | ans <- resp]\n\n\nsolve :: [Char] -> Bool\nsolve xs = foldl' (\\ct x -> if x == 'N' then ct+1 else ct) 0 xs /= 1", "positive_code": [{"source_code": "import Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- readInts\r\n replicateM_ t $ do\r\n ar<-getLine \r\n let x = length $ filter (=='N') ar\r\n putStrLn $ if (x==1) then \"NO\" else \"YES\"\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.interact $ B.unlines . map solve . tail . B.words \n\nsolve :: B.ByteString -> B.ByteString\nsolve bstr = if (==1) . B.length . B.filter (=='N') $ bstr then B.pack \"NO\" \n else B.pack \"YES\""}, {"source_code": "import Control.Monad (replicateM)\nvalidSeq :: [Bool] -> Bool\nvalidSeq = not . (==1) . count not 0\n where count f acc [] = acc\n count f acc (x:xs) = count f (acc + if f x then 1 else 0) xs\nmain :: IO()\nmain = read <$> getLine >>=\n flip replicateM getLine >>=\n mapM_ (putStrLn . f)\n where f :: String -> String\n f = (\\b -> if b then \"YES\" else \"NO\") . validSeq . map (=='E')\n"}, {"source_code": "import Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\n{-\r\n _____ _____\r\n \\ \\ \\ \\\r\n \\ \\ \\ \\\r\n \\ \\ \\ \\\r\n \\ \\ \\ \\ \\-----------|\r\n \\ \\ \\ \\ \\ empr |\r\n \\ \\ \\ \\ \\---------|\r\n / / / \\\r\n / / / \\ \\-------|\r\n / / / ^ \\ \\ |\r\n / / / / \\ \\ \\ ----|\r\n / / / / \\ \\\r\n /____/ /____/ \\____\\\r\n\r\n-}\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nreadIntegers :: IO [Integer]\r\nreadIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- readInts\r\n replicateM_ t $ do\r\n ar<-getLine \r\n let x = length $ filter (=='N') ar\r\n putStrLn $ if (x/=1) then \"YES\" else \"NO\"\r\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM)\nvalidSeq :: [Bool] -> Bool\nvalidSeq = not . inValid\n\ninValid :: [Bool] -> Bool\ninValid (True:xs) = all_but_last_true xs\n where all_but_last_true [x] = not x\n all_but_last_true (True:y:xs) = all_but_last_true (y:xs)\n all_but_last_true (False:_:_) = False\ninValid (False:xs) = all id xs\nmain :: IO()\nmain = read <$> getLine >>=\n flip replicateM getLine >>=\n mapM_ (putStrLn . f)\n where f :: String -> String\n f = (\\b -> if b then \"YES\" else \"NO\") . validSeq . map (=='E')\n"}, {"source_code": "import Control.Monad (replicateM)\nvalidSeq :: [Bool] -> Bool\nvalidSeq (x:y:[]) = (x ==> y)\n where (==>) True False = False\n (==>) _ _ = True\nvalidSeq (x:y:xs) = validSeq ((x && y):xs)\nmain :: IO()\nmain = read <$> getLine >>=\n flip replicateM getLine >>=\n mapM_ (putStrLn . f)\n where f :: String -> String\n f = (\\b -> if b then \"YES\" else \"NO\") . validSeq . map (=='E')\n"}], "src_uid": "e744184150bf55a30568060cca69de04"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Function\nimport Data.Map (toList, fromListWith, adjust)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (itoline . solve . linetois) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: [Int] -> Int\nsolve xs | Data.List.null $ tail $ group xs = 0\n | otherwise = (+) 1 $ snd $ minimumBy (compare `on` snd) $ toList $ adjust (subtract 1) (last xs) $ adjust (subtract 1) (head xs) $ fromListWith (+) [(x, 1) | x <- fmap head $ group xs] \n\n", "positive_code": [{"source_code": "{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe\nimport Text.Printf\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_, foldM)\nimport qualified Data.Array.ST.Safe as SA\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad (when)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nmodifyArray :: (SA.MArray a e m, SA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix func = do\n e <- SA.readArray arr ix\n SA.writeArray arr ix $ func e\n\nsolve :: Int -> [Int] -> Int\nsolve n as = runST $ do\n let maybeAs = fmap Just as\n let pairs = zip maybeAs $ tail maybeAs\n costs <- SA.newArray (1, n) 1 :: ST s (SA.STArray s Int Int)\n modifyArray costs (head as) (\\e -> e - 1)\n forM_ pairs $ \\(currentA, nextA) -> do\n when (currentA /= nextA) $ modifyArray costs (fromJust currentA) (+1)\n foldM (\\mn ix -> do\n e <- SA.readArray costs ix\n return $ min mn e\n ) n as\n\nmainCase :: IO ()\nmainCase = do\n Just n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust)\n let answer = solve n as\n printf \"%d\\n\" answer\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ const mainCase\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Function\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (itoline . solve . linetois) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n \nsolve :: [Int] -> Int\nsolve xs \n | null $ tail $ group xs = 0\n | otherwise = length $ head $ sortBy (compare `on` length) $ fmap (foo last) $ fmap (foo head) $ fmap (\\ys->(head ys):ys) $ group $ sort $ fmap head $ group xs where\n foo bar ys = if head ys == bar xs then tail ys else ys\n\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.List (group, sort)\n\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs\n | length xs' == 1 = 0\n | length xs' == 2 = 1\n | head xs' `notElem` vs = 1\n | last xs' `notElem` vs = 1\n | otherwise = (1 +) . minimum . map length . group . sort $ vs\n where\n xs' = map head . group $ xs\n vs = init . tail $ xs'\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve a = head . sort $ map (\\(c,x) -> c + 1 - fromEnum(x==f) - fromEnum(x==l)) cnt\n where\n b = map head $ group a\n cnt = map (\\a -> (length a, head a)) $ group $ sort b\n f = head b\n l = last b\n\nmain :: IO ()\nmain = interact $ unlines . map show . f . tail . map (map read) . map words . lines\n where f(_:x:xs) = solve x : f(xs)\n f[] = []\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve a = head . sort $ map (\\(c,x) -> c + 1 - fromEnum(x==f) - fromEnum(x==l)) cnt\n where\n b = map head $ group a\n cnt = map (\\a -> (length a, head a)) $ group $ sort b\n f = head b\n l = last b\n\nmain :: IO ()\nmain = interact $ unlines . map show . f . map (map read . words) . tail . lines\n where f(_:x:xs) = solve x : f(xs)\n f[] = []\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Function\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (itoline . solve . linetois) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n \nsolve :: [Int] -> Int\nsolve xs \n | null $ tail $ group xs = 0\n | otherwise = (+) 1 $ length $ head $ sortBy (compare `on` length) $ fmap (foo last) $ fmap (foo head) $ group $ sort $ fmap head $ group xs where\n foo bar ys = if head ys == bar xs then (head ys:ys) else ys\n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Function\nimport Data.Map (toList, fromListWith, adjust)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (itoline . solve . linetois) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: [Int] -> Int\nsolve xs | Data.List.null $ tail $ group xs = 0\n | otherwise = (+) 1 $ snd $ minimumBy (compare `on` snd) $ toList $ adjust (subtract 1) (last xs) $ adjust (subtract 1) (head xs) $ fromListWith (+) [(x, 1) | x <- xs]\n\n"}], "src_uid": "080eb61cbc4b0ffcbab10b86918f70fe"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain = do\n\tn <- fst . fromJust . C.readInt <$> B.getLine\n\t[as, bs] <- replicateM 2 $ map (fst . fromJust . C.readInt) . B.split 32 <$> B.getLine\n\tputStrLn $ unwords $ map show $ elems $ array (1, n) (zip as bs)\n\t\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array.IO\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nmain = do\n n <- (liftM $ fst . fromJust . C.readInt) B.getLine\n p1 <- (liftM $ (map $ fst . fromJust . C.readInt) . B.split 32) B.getLine\n p2 <- (liftM $ B.split 32) B.getLine\n arr <- newArray_ (1, n) :: IO (IOArray Int ByteString)\n forM_ (zip p1 p2) $ \\(i, j) -> writeArray arr i j\n getElems arr >>= C.putStrLn . B.intercalate (B.singleton 32)\n"}], "negative_code": [], "src_uid": "a133b2c63e1025bdf13d912497f9b6a4"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n],xs] <- replicateM 2 ri\r\n return xs\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve xs = head xs\r\n", "positive_code": [{"source_code": "main = interact $ unlines . map (last . words) . chunk . drop 1 . lines\n\nchunk [] = []\nchunk (x: xs: []) = xs: chunk []\nchunk (x: xs: xss) = xs: chunk xss\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n pure $ putInts [head a]\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let\r\n xorall = foldl' xor 0 a\r\n ra = map (\\x -> xor x xorall) a\r\n (pre, suf) = span (\\(x, y) -> (/=) x y) $ zip a ra\r\n\r\n pure $ putInts [(snd . head) suf]\r\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Int\nsolve n as = head as\n \n\n\nmain :: IO ()\nmain = do\n n <- B8.getLine <&> readIntB8\n replicateM_ n $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n"}, {"source_code": "(>>>) = flip (.)\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> chunksOf 2 >>> map (last >>> words >>> head) >>> unlines\r\n\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n"}], "negative_code": [], "src_uid": "329ac6671e26b73ab70749ca509f5b09"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ngetWords :: IO [Int64]\ngetWords = map (fromIntegral . parseInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n ranges <- A.listArray (1, n) <$> replicateM n getWords\n let dupEdge [u, v] = [(u, v), (v, u)]\n adjs <- A.accumArray (flip (:)) [] (1, n) . concatMap dupEdge <$> replicateM (n - 1) getInts\n let dfs fa u = foldl' acc (u, 0, 0) childs\n where childs = map (dfs u) $ filter (/= fa) $ adjs A.! u\n [l, r] = ranges A.! u\n acc (_, tl, tr) (v, dl, dr) = (u, tl + f l, tr + f r)\n where [lv, rv] = ranges A.! v\n f x = max (abs (lv - x) + dl) (abs (rv - x) + dr)\n (_, a, b) = dfs 1 1\n return $ int64Dec (max a b) `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Graph\nimport Data.Array\nimport Data.Int\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain = do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n bnds <- forM [1..n] $ \\i -> do\n [l,r] <- fmap (map fromIntegral) readInts\n return (i, (l,r))\n edges <- fmap concat $ replicateM (n-1) $ do\n [u,v] <- readInts\n return [(u,v), (v,u)]\n let bnd = array (1,n) bnds\n graph = buildG (1,n) edges\n [tree] = dfs graph [1]\n (ansl,ansr) = calc bnd tree\n print $ max ansl ansr\n\ncalc :: Array Int (Int64,Int64) -> Tree Vertex -> (Int64,Int64)\ncalc bnd (Node u adjs) =\n foldl' foo (0,0) adjs where -- cause codeforces sucks'\n (ul,ur) = bnd!u\n foo (dpul,dpur) vn@(Node v _) =\n let (vl,vr) = bnd!v\n (dpvl,dpvr) = calc bnd vn\n dpulNew = max (abs (ul-vl) + dpvl) (abs (ul-vr) + dpvr)\n dpurNew = max (abs (ur-vl) + dpvl) (abs (ur-vr) + dpvr)\n in (dpul+dpulNew, dpur+dpurNew)"}, {"source_code": "{-# OPTIONS_GHC -XStrict -XStrictData #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\nsolve :: Graph -> Array Int (Int64, Int64) -> Int64\r\nsolve g ab = let (r0,r1) = dfs 1 (-1) in max r0 r1\r\n where\r\n dfs x p =\r\n let\r\n a = fst $ ab ! x\r\n b = snd $ ab ! x\r\n pingo = [(dfs y x, ab ! y) | y <- g ! x, y /= p]\r\n doit v = sum $ map (\\((r0,r1),(y0,y1)) -> max (r0 + abs (y0-v)) (r1 + abs (y1-v))) pingo\r\n in\r\n (doit a, doit b)\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine\r\n rs <- replicateM n $ do\r\n [l, r] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine\r\n return (l,r)\r\n es <- replicateM (n-1) $ do\r\n [a, b] <- map parseInt . BS.words <$> BS.getLine\r\n return (a,b)\r\n let g = buildG (1,n) (es ++ map swap es)\r\n print $ solve g (listArray (1,n) rs)"}], "negative_code": [], "src_uid": "a5063294f814f359f7ab6b7b801eaf3e"} {"source_code": "\nimport Array ((!), accumArray)\nimport Char (isDigit, ord)\nimport Control.Monad (liftM)\nimport Data.List (foldl')\nimport Maybe (fromMaybe)\n\n--import CPUTime\n--import IO (hPutStrLn, stderr)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestSimple :: Test\ntestSimple = TestList \"TestSimple\" $\n [\n Test \"1\" $ assertEq (Just 9) $\n solve 3 9 [(i, j) | i <- [1..3], j <- [1..3]],\n Test \"2\" $ assertEq Nothing $\n solve 3 1 [(1,1)],\n Test \"3\" $ assertEq Nothing $\n solve 3 8 [(i,j) | i <- [1..3], j <- [1..3], i /= 2 || j /= 2]\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq (Just 10) $ solve 4 11\n [(1,1), (1,2), (1,3), (2,2), (2,3), (1,4), (2,4), (3,4), (3,2), (3,3), (4,1)],\n Test \"2\" $ assertEq Nothing $ solve 4 12\n [(1,1), (1,2), (1,3), (2,2), (2,3), (1,4), (2,4), (3,4), (3,2), (4,2), (4,1), (3,1)]\n ]\n\ntestSmallField :: Test\ntestSmallField = Test \"TestSmallField\" $\n assertEq Nothing $ solve 2 4 [(2,1),(1,2),(2,2),(1,1)]\n\ntestBadLogic :: Test\ntestBadLogic = Test \"TestBadLogic\" $\n assertEq (Just 9) $ solve 16 9 [(2 + di, 1 + dj) | di <- [0..2], dj <- [0..2]]\n\ntestError9 :: Test\ntestError9 = Test \"TestError9\" $\n assertEq (Just 11) $ solve 500 16 [(i,j) | i <- [1..4], j <- [1..4]]\n\ntestBigField :: Test\ntestBigField = Test \"TestBigField\" $\n assertEq Nothing $ solve 500 1 [(500,500)]\n\ntestManyPoints :: Test\ntestManyPoints = Test \"TestManyPoints\" $\n assertEq (Just n) $ solve 3 n $\n take n $ cycle [(i, j) | i <- [1..3], j <- [1..3]]\n where\n n = 10^5\n\ntestBig :: Test\ntestBig = Test \"TestBig\" $\n assertEq (Just 1003) $ solve 500 n $\n take n [(i, j) | i <- [1..500], j <- [1..500]]\n where\n n = 10^5\n\ntest :: IO ()\ntest = mapM_ run\n [\n testSimple,\n testInput,\n testSmallField,\n testBadLogic,\n testError9,\n testBigField,\n testManyPoints,\n testBig\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: Int -> Int -> [(Int, Int)] -> Maybe Int\nsolve n m points\n | ans == (m+1) = Nothing\n | otherwise = Just ans\n where\n field = accumArray (flip const) (m+1) ((1,1), (n,n)) (zip points [1..])\n ans = foldl' min (m+1) $\n [foldl' max 0 [field ! (i+di, j+dj) | (di, dj) <- smallSquare] | i <- [1..n-2], j <- [1..n-2]]\n smallSquare = [(i,j) | i <- [0..2], j <- [0..2]]\n\nreadPair :: String -> (Int, Int)\nreadPair s = reads' 0 s\n where\n reads' a (' ':s) = reads'' a 0 (dropWhile (== ' ') s)\n reads' a (c:s)\n | isDigit c = reads' (10*a + ord c - ord '0') s\n | otherwise = error $ concat [\"readPair: unknown symbol \", show c]\n reads'' a b [] = (a, b)\n reads'' a b (c:s)\n | isDigit c = reads'' a (10*b + ord c - ord '0') s\n | otherwise = error $ concat [\"readPair: unknown symbol \", show c]\n\nprintAns :: Maybe Int -> IO ()\nprintAns = print . fromMaybe (-1)\n\nmain :: IO ()\nmain = do\n-- timeStart <- getCPUTime\n\n lines' <- liftM lines getContents\n let [n, m] = map read $ words $ head lines'\n let ps = take m $ map readPair $ tail lines'\n printAns $ solve n m ps\n\n-- timeEnd <- getCPUTime\n-- hPutStrLn stderr $ concat [\"Time = \", show $ fromIntegral (timeEnd - timeStart) / (10^12), \" sec.\"]\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nreadInt s = let Just (n,_) = B.readInt s in n\n\ntoPairs [] = []\ntoPairs (x:y:xys) = (x,y):toPairs xys\n\nmain=B.getContents>>=print.solve S.empty.zip[1..].tail.toPairs.map readInt.B.words\n\nsolve _ [] = -1\nsolve visited ((i,(x,y)):ixys)\n | any isSquare $ neighbors (x,y) = i\n | otherwise = solve visited' ixys\n where\n visited' = S.insert (x,y) visited\n isSquare = all(`S.member`visited').neighbors\n neighbors (x,y) = [(x+dx,y+dy)|dx<-[-1,0,1],dy<-[-1,0,1]]\n"}], "negative_code": [{"source_code": "\nimport Array\nimport Control.Monad (liftM, replicateM)\nimport CPUTime\nimport Data.List (foldl1')\nimport Data.Map (Map, fromList, findWithDefault)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestSimple :: Test\ntestSimple = TestList \"TestSimple\" $\n [\n Test \"1\" $ assertEq (Just 9) $\n solve 3 9 [(i, j) | i <- [1..3], j <- [1..3]],\n Test \"2\" $ assertEq Nothing $\n solve 3 1 [(1,1)],\n Test \"3\" $ assertEq Nothing $\n solve 3 8 [(i,j) | i <- [1..3], j <- [1..3], i /= 2 || j /= 2]\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq (Just 10) $ solve 4 11\n [(1,1), (1,2), (1,3), (2,2), (2,3), (1,4), (2,4), (3,4), (3,2), (3,3), (4,1)],\n Test \"2\" $ assertEq Nothing $ solve 4 12\n [(1,1), (1,2), (1,3), (2,2), (2,3), (1,4), (2,4), (3,4), (3,2), (4,2), (4,1), (3,1)]\n ]\n\ntestSmallField :: Test\ntestSmallField = Test \"TestSmallField\" $\n assertEq Nothing $ solve 2 4 [(2,1),(1,2),(2,2),(1,1)]\n\ntestBigField :: Test\ntestBigField = Test \"TestBigField\" $\n assertEq Nothing $ solve 1000 1 [(1000,1000)]\n\ntestManyPoints :: Test\ntestManyPoints = Test \"TestManyPoints\" $\n assertEq (Just 9) $ solve 3 n $\n take n $ cycle [(i, j) | i <- [1..3], j <- [1..3]]\n where\n n = 10^5\n\ntestBig :: Test\ntestBig = Test \"TestBig\" $\n assertEq (Just 2003) $ solve 1000 n $\n take n [(i, j) | i <- [1..1000], j <- [1..1000]]\n where\n n = 10^5\n\ntest :: IO ()\ntest = mapM_ run\n [\n testSimple,\n testInput,\n testSmallField,\n testBigField,\n testManyPoints,\n testBig\n ]\n-}\n--------------------------------------------------------------------------------\n\ngetField :: Int -> Array Int (Int, Int) -> Array (Int, Int) Int\ngetField size points\n = accumArray (flip const) maxBound ((1,1), (size, size))\n [(points ! i, i) | i <- [1..n]]\n where\n n = snd $ bounds points\n\nsolve = solve5\n\nsolve1 :: Int -> Int -> [(Int, Int)] -> Maybe Int\nsolve1 n countPoints points\n | not $ containSquare countPoints = Nothing\n | otherwise = Just $ binSearch 8 countPoints\n where\n binSearch l r\n | l + 1 == r = r\n | containSquare m = binSearch l m\n | otherwise = binSearch m r\n where\n m = div (l+r) 2\n containSquare x = not $ null\n [(i,j) | i <- _1n2, j <- _1n2,\n all (\\(di, dj) -> field ! (i+di, j+dj) <= x)\n [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]]\n field = getField n $ listArray (1,countPoints) points\n _1n2 = [1..n-2]\n\n\nsolve2 :: Int -> Int -> [(Int, Int)] -> Maybe Int\nsolve2 n countPoints points\n | ans == maxBound = Nothing\n | otherwise = Just ans\n where\n ans = minimum' $ maxBound :\n [myMaximum (map (\\(di,dj) -> field ! (i+di, j+dj))\n [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)])\n | i <- [1..n-2], j <- [1..n-2]]\n field = getField n $ listArray (1,countPoints) points\n minimum' = foldl1' min\n myMaximum [x] = x\n myMaximum (x:xs)\n | x == maxBound = maxBound\n | otherwise = max x $ myMaximum xs\n\nsolve3 :: Int -> Int -> [(Int, Int)] -> Maybe Int\nsolve3 n countPoints points\n | ans == maxBound = Nothing\n | otherwise = Just ans\n where\n field = getField n $ listArray (1,countPoints) points\n ans = foldl1' min $ maxBound : [d ! (i, j, 3, 3) | i <- [3..n], j <- [3..n]]\n d = array ((1,1,1,1), (n,n,3,3)) $\n [((i,j,di,dj), getD i j di dj) | i <- [1..n], j <- [1..n], di <- [1..3], dj <- [1..3]]\n where\n getD i j 1 1 = field ! (i, j)\n getD i j 1 dj = max (d ! (i, j, 1, dj - 1)) (d ! (i, j + 1 - dj, 1, 1))\n getD i j di dj = max (d ! (i, j, di - 1, dj)) (d ! (i + 1 - di, j, 1, dj))\n\nsolve4 :: Int -> Int -> [(Int, Int)] -> Maybe Int\nsolve4 n countPoints points\n | ans == maxBound = Nothing\n | otherwise = Just ans\n where\n arrayPoints = listArray (1,countPoints) points\n mapPoints = fromList [(arrayPoints ! i, i) | i <- [1..countPoints]]\n ans = minimum' $ maxBound :\n [maximum' [findWithDefault maxBound (i+di, j+dj) mapPoints\n | di <- [0..2], dj <- [0..2]]\n | i <- [1..n-2], j <- [1..n-2]]\n minimum' = foldl1' min\n maximum' = foldl1' max\n\nsolve5 :: Int -> Int -> [(Int, Int)] -> Maybe Int\nsolve5 n countPoints points\n | ans == maxBound = Nothing\n | otherwise = Just ans\n where\n field = getField n $ listArray (1,countPoints) points\n ans = solve' maxBound 1 1\n solve' min' i j\n | j > n - 2 = min'\n | i > n - 2 = solve' min' (i+1) 1\n | max' == maxBound && j > 2 = solve' min' i (j+3)\n | otherwise = solve' (min max' min') i (j+1)\n where\n max' = myMaximum min' [field ! (i+di, j+dj) | (di, dj) <- [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]]\n myMaximum min' [x] = x\n myMaximum min' (x:xs)\n | x >= min' = maxBound\n | x == maxBound = maxBound\n | otherwise = max x $ myMaximum min' xs\n\nreadPair :: IO (Int, Int)\nreadPair = do\n [x, y] <- liftM (map read . words) getLine\n return (x, y)\n\nprintAns :: Maybe Int -> IO ()\nprintAns Nothing = print (-1)\nprintAns (Just x) = print x\n\nmain :: IO ()\nmain = do\n-- timeStart <- getCPUTime\n \n (n, m) <- readPair\n points <- replicateM m readPair\n printAns $ solve n m points\n \n-- timeEnd <- getCPUTime\n-- putStrLn $ concat [\"Time = \", show $ fromIntegral (timeEnd - timeStart) / (10^12), \" sec.\"]\n"}], "src_uid": "8a4a46710104de78bdf3b9d5462f12bf"} {"source_code": "answer a | elem 1 a = -1\n | otherwise = 1 \nmain = do\n w <- getLine\n let n = read w::Int\n ww <- getLine\n let a = [read n::Int|n <- (words ww)]\n print $ answer a\n", "positive_code": [{"source_code": "main :: IO()\nmain = print . solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve [] = 1\nsolve (a:s) = if a == 1 then -1 else (solve s)\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n n <- fmap (\\x -> read x :: Int) getLine\n vals <- fmap (\\ln -> map (\\x -> read x :: Int) (words ln)) getLine\n let sorted = sort vals\n print $ if head sorted == 1 then -1 else 1"}, {"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n if minimum a == 1 then putStrLn \"-1\" else putStrLn \"1\""}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n print $ if 1 `elem` xs then -1 else 1\n"}, {"source_code": "import Data.Functor\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\n\nmain = getInts >>= putStrLn . show . solve\n\nsolve (_:xs) = if elem 1 xs then -1 else 1\n"}, {"source_code": "main = interact $ show . foldl (\\ns a -> if a == 1 then -1 else ns) 1 . map read . words . last . lines"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nsomeFunc::IO()\nsomeFunc = getLine >> (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInt).C.words<$>C.getLine))\nsolve xs = let ss =sort xs; h=head ss in if h==1 then print (-1) else print 1\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve xs = if 1 `elem` xs then -1 else 1\n"}, {"source_code": "import Data.List (sort)\nmain = do\n getLine\n ns <- fmap (sort . map read . words) getLine\n putStrLn $ if head ns == 1 then \"-1\" else \"1\""}, {"source_code": "main = getLine >> fmap (map read . words) getLine >>= print . f\nf xs = if 1 `elem` xs then -1 else 1\n"}, {"source_code": "import Data.List\nmain = do \n getLine\n x <- getLine\n if not (filter (\\y-> y==1)(map (read) (words x)) == []) then print (-1) else print 1\n\n\n\n\n"}, {"source_code": "main = getContents >>= print . solve . map read . tail . words\n\nsolve as = if any (== 1) as then -1 else 1"}, {"source_code": "f 1 = -1\nf _ = 1\nmain=interact$show.f.minimum.map read.tail.words\n"}, {"source_code": "import Data.List\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmanip xs \n\t| 1 `elem` xs = -1\n\t| otherwise = 1\n\nmain = do\n n <- getLine\n ints <- readInts\n print $ manip ints"}, {"source_code": "import Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\ncurSys :: [Int] -> Int\ncurSys = (\\a-> if a == 1 then -1 else 1) . minimum\n\nparse :: B.ByteString -> Maybe [Int]\nparse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words\n\nmain :: IO ()\nmain = getLine >> parse <$> B.getLine >>= \\(Just a) -> print . curSys $ a\n"}, {"source_code": "import Control.Monad\n\nmain = do\n getLine\n l <- getLine >>= return . map read . words\n print $ if minimum l == 1 then -1 else 1"}, {"source_code": "import Control.Applicative\n \n \n\nmain= do\n\t getLine\n\t s<-map read. words <$> getContents::IO [Int]\n\t putStrLn $ if (elem 1 s) then \"-1\" else \"1\""}, {"source_code": "main = do\n getLine\n a <- getLine >>= return. map read. words :: IO [Int]\n putStrLn (if elem 1 a then \"-1\" else \"1\")\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nsolve lst\n | minimum lst == 1 = -1\n | otherwise = 1\n\nmain :: IO ()\nmain = do\n _ <- getLine\n lst <- (map (\\s -> read s::Int) . words) <$> getLine\n print $ solve lst\n\n"}, {"source_code": "parse :: String -> [Int]\nparse contents = map read . words $ a\n where [_, a] = lines contents\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nsolve :: [Int] -> Int\nsolve = bool 1 (-1) . (== 1) . minimum\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}], "negative_code": [{"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n if minimum a == 1 then putStrLn \"-1\" else print . pred . minimum $ a"}, {"source_code": "import Data.Functor\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\n\nmain = getInts >>= putStrLn . show . solve\n\nsolve (_:x:_) = if x == 1 then -1 else 1\n"}, {"source_code": "import Data.List\nmain = do \n getLine\n x <- getLine\n if not (filter (\\y-> y==1)(map (read) (words x)) == []) then print \"-1\" else print \"1\"\n\n\n\n\n"}, {"source_code": "import Data.List\n\nf (x:y:xs) | x+1 < y = x+1\n | otherwise = f (x+y:xs)\nf _ = -1\nmain=interact$show.f.sort.map((+0).read).tail.words\n"}, {"source_code": "import Data.List\n\nf (x:y:xs) | x+1 < y = x+1\n | otherwise = f (x+y:xs)\nf _ = -1\nmain=interact$show.f.(0:).sort.map((+0).read).tail.words\n"}, {"source_code": "f 1 = 1\nf _ = -1\nmain=interact$show.f.minimum.map read.tail.words\n"}, {"source_code": "import Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\ncurSys :: [Int] -> Int\ncurSys = (\\a-> if a == 1 then -1 else 1) . foldr1 gcd\n\nparse :: B.ByteString -> Maybe [Int]\nparse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words\n\nmain :: IO ()\nmain = getLine >> parse <$> B.getLine >>= \\(Just a) -> print . curSys $ a\n"}, {"source_code": "import Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\ncurSys :: [Int] -> Int\ncurSys = (\\a-> if a == 1 then -1 else a) . foldr1 gcd\n\nparse :: B.ByteString -> Maybe [Int]\nparse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words\n\nmain :: IO ()\nmain = getLine >> parse <$> B.getLine >>= \\(Just a) -> print . curSys $ a\n"}, {"source_code": "m 1 = -1\nm x = x - 1\nmain = do\n getLine\n a <- getLine >>= return. map read. words :: IO [Int]\n print.m.minimum $ a \n"}, {"source_code": "main = do\n getLine\n a <- getLine >>= return. map read. words :: IO [Int]\n print (if elem 1 a then \"-1\" else \"1\")\n"}, {"source_code": "main = do\n getLine\n a <- getLine >>= return. map read. words :: IO [Int]\n print (if elem 1 a then \"YES\" else \"NO\")\n"}], "src_uid": "df94080c5b0b046af2397cafc02b5bdc"} {"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve' . map readInt . words\n\nsolve' (_:xs) = if length xs < 3 then length xs else solve xs\nsolve xs =\n\tmaximum $ zipWith f ([(0,0)] ++ init ls) (tail rs ++ [(0,0)])\n\twhere\n\t\tls = incLengths xs\n\t\trs = map (\\x -> (-fst x,snd x)) (reverse $ incLengths $ map negate $ reverse xs)\n\t\tf a b = if (fst a + 2 <= fst b) then (1 + snd a + snd b) else (1 + max (snd a) (snd b))\n\nincLengths (x:xs) = scanl f (x,1) xs\n\twhere f a x = if fst a < x then (x,snd a+1) else (x,1)\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n xs = scanl (\\v (a, b) -> if a < b then v + 1 else 1) 1 $ zip as $ tail as\n ys = scanr (\\(a, b) v -> if a < b then v + 1 else 1) 1 $ zip as $ tail as\n\n print $ maximum $ zipWith3 (\\a b f -> if f then a + 1 + b else max (a+1) (b+1)) (0:xs) (tail ys ++ [0]) (zipWith (\\a b -> a + 1 < b) (0:as) (tail as ++ [2*10^9]))\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n xs = scanl (\\v (a, b) -> if a < b then v + 1 else 1) 1 $ zip as $ tail as\n ys = scanr (\\(a, b) v -> if a < b then v + 1 else 1) 1 $ zip as $ tail as\n\n print $ maximum $ zipWith3 (\\a b f -> if f then a + 1 + b else max (a+1) (b+1)) (0:xs) (tail ys ++ [0]) (zipWith (\\a b -> a + 1 < b) (0:as) (tail as ++ [2*10^9]))\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nspl (x:y:z)\n | x < y = let (a:as) = spl (y:z) in (x:a):as\n | otherwise = [x] : spl (y:z)\nspl [x] = [[x]]\nspl [] = []\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- spl <$> getInts\n -- print ns\n\n let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)\n\n f [_] ys = length ys + 1\n f xs [_] = length xs + 1\n f xs ys@(y1:y2:_)\n | y2 - last xs >= 2 = length xs + length ys\n | y1 - last (init xs) >= 2 = length xs + length ys\n | otherwise = max (length xs) (length ys) + 1\n\n print ans\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Sequence ((<|),(|>),(><),ViewL(..),ViewR(..))\nimport qualified Data.Sequence as Seq\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 $ splitBy (>=) xs\n where\n go !res (xs:[y]:xss) = go (max res $ length xs + 1) ([y]:xss)\n go !res ([x]:ys:xss) = go (max res $ length ys + 1) (ys:xss)\n go !res (xs:(y:y':ys):xss) = case reverse xs of\n (x:x':xs') | x' + 1 < y || x + 1 < y' -> go (max res $ length xs + length ys + 2) ((y:y':ys):xss)\n | otherwise -> go (max res $ length xs `max` (length ys + 2) + 1) ((y:y':ys):xss)\n go !res [xs] = max res $ length xs\n \nsplitBy :: (a -> a -> Bool) -> [a] -> [[a]]\nsplitBy p xs = foldr f [] xs\n where\n f x (yys@(y:_):yss)\n | p x y = [x]:yys:yss\n | otherwise = (x:yys):yss\n f x [] = [[x]]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\ngetnums :: Num a => IO [a]\ngetnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n\ngetstr = getLine\n\nsolveCont :: Int -> [Int] -> Int -> [Int]\nsolveCont _ [] _ = []\nsolveCont prev (a:as) pvc\n | prev < a = (pvc + 1) : (solveCont a as (pvc + 1))\n | otherwise = 1 : (solveCont a as 1)\n\nsolveCont' :: Int -> [Int] -> Int -> [Int]\nsolveCont' _ [] _ = []\nsolveCont' prev (a:as) pvc\n | prev > a = (pvc + 1) : (solveCont' a as (pvc + 1))\n | otherwise = 1 : (solveCont' a as 1)\n\nsolve (f1:f2:f3:fs) (b1:b2:b3:bs) (a1:a2:a3:as)\n | a3 - a1 >= 2 = max (f1 + b3 + 1) nxt\n | otherwise = maximum [f1 + 1, f2, b3 + 1, b2, nxt]\n where nxt = solve (f2:f3:fs) (b2:b3:bs) (a2:a3:as)\nsolve (f1:f2:fs) (b1:b2:bs) (a1:a2:as) =\n maximum [f1 + 1, f2, b2 + 1, b1]\n\n\nsolve2 (f1:f2:fs) (b1:b2:bs) =\n maximum [f1 + 1, f2, b1, b2 + 1]\n\n\n\nmain = do\n n <- getint\n as <- getints\n if n == 1\n then do putStrLn \"1\"\n else do let fwdLen = solveCont (-1) as 0\n bckLen = reverse $ solveCont' (1000000001) (reverse as) 0\n putStrLn (show (max (solve fwdLen bckLen as) (solve2 fwdLen bckLen)))"}, {"source_code": "\nmaxTo = scanl (\\(c,n) x-> if x > n then (c+1, x) else (1, x)) (0,-1)\nmaxFrom = reverse . scanl (\\(c,n) x-> if x < n then (c+1, x) else (1, x)) (0,10^9+5) . reverse\ns(_:l)=maximum$zipWith f mxt (tail mxf) where\n mxt = maxTo l\n mxf = maxFrom l\n f (c1,a) (c2,b) | a < b-1 = c1+c2+1\n | otherwise = max (c1+1) (c2+1)\nmain=interact$show.s.map read.words\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Function\nimport qualified Data.IntSet as IS\nimport Text.Printf (printf)\n\nsubseqs :: [Int] -> [[Int]]\nsubseqs [] = []\nsubseqs (x : xs) = go [x] xs\n where\n go acc [] = [reverse acc]\n go acc (x : xs)\n | head acc < x = go (x : acc) xs\n | otherwise = (reverse acc) : go [x] xs\n\nsolve :: [Int] -> Int\nsolve as = go 0 (map (\\s -> (s, reverse s, length s)) $ subseqs as)\n where\n spans _ [] = []\n spans p xs =\n case span p xs of\n ([], []) -> []\n ([], (x : xs')) -> [x] : spans p xs'\n (s, xs') -> s : spans p xs'\n\n go best [] = best\n go best [(_, _, l)] = max best l\n go best ((s, z, l) : (x@(s', _, l')) : xs) =\n go (maximum [best,\n case z of\n (_ : t : _) | t + 1 < head s' -> l + l'\n _ -> l' + 1,\n case s' of\n (_ : h : _) | head z + 1 < h -> l + l'\n _ -> l + 1]) (x : xs)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n as <- fmap (map read . words) getLine\n print $ solve as\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n show `fmap` solve n `fmap` replicateM n poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve 1 _ = 1\nsolve 2 _ = 2\nsolve n xs = min n $ max (maximum $ map (+1) es) (maximum (zipWith4 (\\e x y s -> if y > x + 1 then e + s + 1 else 0) es xs (drop 2 xs) (drop 2 ss)))\n where\n es = scanl (\\l (a, b) -> if a < b then l + 1 else 1) (1 :: Int) $ zip xs (tail xs :: [Int])\n ss = concatMap reverse $ groupBy (<) es\n\n{-\n_ 7 1 2 3\n\n\n<= 1\na[i] < a[i + 2]\n[1,1,2,1,2,3]\n[1,2,1,3,2,1]\n-}"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n show `fmap` solve `fmap` replicateM n poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve xs = max (maximum es) (maximum (zipWith4 (\\e x y s -> if y > x + 1 then e + s + 1 else 0) (1:es) (minBound:xs) (tail xs) (tail ss)))\n where\n es = scanl (\\l (a, b) -> if a < b then l + 1 else 1) (1 :: Int) $ zip xs (tail xs :: [Int])\n ss = concatMap reverse $ groupBy (<) es\n\n{-\n_ 7 1 2 3\n\n\n<= 1\na[i] < a[i + 2]\n[1,1,2,1,2,3]\n[1,2,1,3,2,1]\n-}"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n show `fmap` solve `fmap` replicateM n poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve [_] = 1\nsolve [_, _] = 2\nsolve xs = max (maximum $ head ss:map (+1) (tail ss)) (maximum (zipWith4 (\\e x y s -> if y > x + 1 then e + s + 1 else 0) es xs (drop 2 xs) (drop 2 ss)))\n where\n es = scanl (\\l (a, b) -> if a < b then l + 1 else 1) (1 :: Int) $ zip xs (tail xs :: [Int])\n ss = concatMap reverse $ groupBy (<) es\n\n{-\n_ 7 1 2 3\n\n\n<= 1\na[i] < a[i + 2]\n[1,1,2,1,2,3]\n[1,2,1,3,2,1]\n-}"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n xs = scanl (\\v (a, b) -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as\n ys = scanr (\\(a, b) v -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as\n\n print $ maximum $ zipWith3 (\\a b f -> if f then a + 1 + b else max (a+1) (b+1)) (0:xs) (tail ys ++ [0]) (zipWith (<=) (0:as) (tail as ++ [2*10^9]))\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n xs = scanl (\\v (a, b) -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as\n ys = scanr (\\(a, b) v -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as\n\n print $ maximum $ zipWith (\\a b -> a + 1 + b) (0:xs) (tail ys ++ [0])\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- getInts\n let ss = groupBy (<) ns\n ans = foldl' max 0 $ map length ss ++ zipWith f ss (tail ss)\n f xs ys\n | length ys == 1 = length xs + 1\n | length xs == 1 = length ys + 1\n | (ys !! 1) - last xs >= 2 = length xs + length ys\n | otherwise = max (length xs) (length ys) + 1\n print ans\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- getInts\n let ss = map length $ groupBy (<) ns\n ans = foldl' max 0 $ ss ++ zipWith (+) ss (tail ss)\n print ans\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- getInts\n let ss = map length $ groupBy (<) ns\n ans = foldl' max 0 $ zipWith (+) ss (tail ss)\n print ans\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- groupBy (<) <$> getInts\n\n let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)\n\n f [_] ys = length ys + 1\n f xs [_] = length xs + 1\n f xs ys@(_:y2:_)\n | y2 - head xs >= 2 = length xs + length ys\n | otherwise = max (length xs) (length ys) + 1\n\n print ans\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- groupBy (<) <$> getInts\n\n let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)\n\n f [_] ys = length ys + 1\n f xs [_] = length xs + 1\n f xs ys@(_:y2:_)\n | y2 - last xs >= 2 = length xs + length ys\n | otherwise = max (length xs) (length ys) + 1\n\n print ans\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- groupBy (<) <$> getInts\n\n let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)\n\n f [_] ys = length ys + 1\n f xs [_] = length xs + 1\n f xs ys@(y1:y2:_)\n | y2 - last xs >= 2 = length xs + length ys\n | y1 - last (init xs) >= 2 = length xs + length ys\n | otherwise = max (length xs) (length ys) + 1\n\n print ans\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Sequence ((<|),(|>),(><),ViewL(..),ViewR(..))\nimport qualified Data.Sequence as Seq\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 $ splitBy (>=) xs\n where\n go !res (xs:[y]:xss) = go (max res $ length xs + 1) ([y]:xss)\n go !res ([x]:ys:xss) = go (max res $ length ys + 1) (ys:xss)\n go !res (xs:(y:y':ys):xss) = case reverse xs of\n (x:x':xs') | x' + 1 < y || x + 1 < y' -> go (max res $ length xs + length ys + 2) ((y:y':ys):xss)\n | otherwise -> go (max res $ length xs `max` (length ys + 2 ) + 1) ([y]:xss)\n go !res [xs] = max res $ length xs\n \nsplitBy :: (a -> a -> Bool) -> [a] -> [[a]]\nsplitBy p xs = foldr f [] xs\n where\n f x (yys@(y:_):yss)\n | p x y = [x]:yys:yss\n | otherwise = (x:yys):yss\n f x [] = [[x]]\n"}, {"source_code": "main=interact$show.f.map read.words\nf(p:n:xs)=go [] 1 xs\n where\n go used i (x:xs)\n | h <- mod x p, elem h used = i\n | otherwise = go (mod x p:used) (i+1) xs\n go _ _ _ = -1\n "}, {"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve' . map readInt . words\n\nsolve' (_:xs) = if length xs < 3 then length xs else solve xs\nsolve xs =\n\tmaximum $ zipWith f (init $ init ls) (tail $ tail rs)\n\twhere\n\t\tls = incLengths xs\n\t\trs = map (\\x -> (-fst x,snd x)) (reverse $ incLengths $ map negate $ reverse xs)\n\t\tf a b = if (fst a + 2 <= fst b) then (1 + snd a + snd b) else 2\n\nincLengths (x:xs) = scanl f (x,1) xs\n\twhere f a x = if fst a < x then (x,snd a+1) else (x,1)\n"}, {"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve' . map readInt . words\n\nsolve' (_:xs) = if length xs < 3 then length xs else solve xs\nsolve xs =\n\tmaximum $ zipWith f ([(0,0)] ++ init ls) (tail rs ++ [(0,0)])\n\twhere\n\t\tls = incLengths xs\n\t\trs = map (\\x -> (-fst x,snd x)) (reverse $ incLengths $ map negate $ reverse xs)\n\t\tf a b = if (fst a + 2 <= fst b) then (1 + snd a + snd b) else 2\n\nincLengths (x:xs) = scanl f (x,1) xs\n\twhere f a x = if fst a < x then (x,snd a+1) else (x,1)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\ngetnums :: Num a => IO [a]\ngetnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n\ngetstr = getLine\n\nsolveCont :: Int -> [Int] -> Int -> [Int]\nsolveCont _ [] _ = []\nsolveCont prev (a:as) pvc\n | prev < a = (pvc + 1) : (solveCont a as (pvc + 1))\n | otherwise = 1 : (solveCont a as 1)\n\nsolveCont' :: Int -> [Int] -> Int -> [Int]\nsolveCont' _ [] _ = []\nsolveCont' prev (a:as) pvc\n | prev > a = (pvc + 1) : (solveCont' a as (pvc + 1))\n | otherwise = 1 : (solveCont' a as 1)\n\nsolve (f1:f2:f3:fs) (b1:b2:b3:bs) (a1:a2:a3:as)\n | a3 - a1 >= 2 = max (f1 + b3 + 1) nxt\n | otherwise = maximum [f1 + 1, f2, b3 + 1, b2, nxt]\n where nxt = solve (f2:f3:fs) (b2:b3:bs) (a2:a3:as)\nsolve (f1:f2:fs) (b1:b2:bs) (a1:a2:as) =\n maximum [f1 + 1, f2, b2 + 1, b1]\n\n\n\n\n\nmain = do\n n <- getint\n as <- getints\n if n == 1\n then do putStrLn \"1\"\n else do let fwdLen = solveCont (-1) as 0\n bckLen = reverse $ solveCont' (1000000001) (reverse as) 0\n putStrLn (show (solve fwdLen bckLen as))"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\ngetnums :: Num a => IO [a]\ngetnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n\ngetstr = getLine\n\nsolveCont :: Int -> [Int] -> Int -> [Int]\nsolveCont _ [] _ = []\nsolveCont prev (a:as) pvc\n | prev < a = (pvc + 1) : (solveCont a as (pvc + 1))\n | otherwise = 1 : (solveCont a as 1)\n\nsolveCont' :: Int -> [Int] -> Int -> [Int]\nsolveCont' _ [] _ = []\nsolveCont' prev (a:as) pvc\n | prev > a = (pvc + 1) : (solveCont' a as (pvc + 1))\n | otherwise = 1 : (solveCont' a as 1)\n\nsolve (f1:f2:f3:fs) (b1:b2:b3:bs) (a1:a2:a3:as)\n | a3 - a1 >= 2 = max (f1 + b3 + 1) nxt\n | otherwise = maximum [f1 + 1, f2, b3 + 1, b2, nxt]\n where nxt = solve (f2:f3:fs) (b2:b3:bs) (a2:a3:as)\nsolve (f1:f2:fs) (b1:b2:bs) (a1:a2:as) =\n maximum [f1 + 1, f2, b2 + 1, b1]\n\n\nsolve2 (f1:f2:fs) (b1:b2:bs) =\n maximum [f1, f2 + 1, b1, b2 + 1]\n\n\n\nmain = do\n n <- getint\n as <- getints\n if n == 1\n then do putStrLn \"1\"\n else do let fwdLen = solveCont (-1) as 0\n bckLen = reverse $ solveCont' (1000000001) (reverse as) 0\n putStrLn (show (max (solve fwdLen bckLen as) (solve2 fwdLen bckLen)))"}, {"source_code": "\nmaxTo = scanl (\\(c,n) x-> if x > n then (c+1, x) else (1, x)) (0,-1)\nmaxFrom = reverse . scanl (\\(c,n) x-> if x < n then (c+1, x) else (1, x)) (0,10^9+5) . reverse\ns(_:l)=maximum$zipWith f mxt (tail mxf) where\n mxt = maxTo l\n mxf = maxFrom l\n f (c1,a) (c2,b) | a < b-1 = c1+c2+1\n | otherwise = 1\nmain=interact$show.s.map read.words\n"}], "src_uid": "9e0d271b9bada1364dfcb47297549652"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-name-shadowing #-}\n{-# OPTIONS_GHC -Wno-type-defaults #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.Bifunctor\nimport Data.Functor\nimport Data.List\nimport Data.Ord\nimport Debug.Trace\n\nreadNumbers :: (Integral b, Read b) => IO [b]\nreadNumbers = fmap read . words <$> getLine\n\n{-# WARNING todo \"'todo' remains in code\" #-}\n{-# INLINEABLE todo #-}\ntodo :: a\ntodo = error \"Not implemented\"\n\nmain :: IO [()]\nmain = do\n [t] <- readNumbers\n replicateM t $ do\n [m] <- readNumbers\n a1s <- readNumbers\n a2s <- readNumbers\n print $ minimum $ zip (init $ scanl (+) 0 a2s) (tail $ scanr (+) 0 a1s) <&> uncurry max\n\n-- max (sum (take i a2s)) (sum (drop (i + 1) a1s))\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintResult = do\r\n m <- readLn :: IO Integer\r\n a <- readInts\r\n b <- readInts\r\n let \r\n c = scanl (+) 0 $ reverse $ tail a \r\n d = reverse $ scanl (+) 0 $ init b\r\n z = zipWith max c d\r\n r = minimum z\r\n print r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE LambdaCase #-}\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = do\n m <- int\n as <- m >< int\n bs <- m >< int\n return . show $ solve as bs\n\nsolve :: [Int] -> [Int] -> Int\nsolve [_] _ = 0\nsolve as bs = minimum $ zipWith max (tail $ scanr (+) 0 as) (scanl (+) 0 bs)\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n m <- readLn :: IO Int\r\n a0 <- readMany :: IO [Int]\r\n a1 <- readMany :: IO [Int]\r\n let s0 = listArray (0, m) $ scanl (+) 0 a0\r\n s1 = listArray (0, m) $ scanl (+) 0 a1\r\n f i = max (s0!m - s0!i) (s1!(i - 1))\r\n print $ minimum $ map f [1..m]\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "negative_code": [], "src_uid": "f3ee3a0de5ddf3cf15ef02fb62a2768e"} {"source_code": "import Control.Monad\nimport Data.List\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nreadInt :: IO Integer\nreadInt = readLn\n\nmedlength :: [Integer] -> Integer\nmedlength l = if length l `mod` 2 == 1 then 1 else\n case drop (length l `div` 2 - 1) ls of\n x:y:xs -> y - x + 1\n where ls = sort l\n\nsolve :: ([Integer], [Integer]) -> Integer\nsolve (a, b) = medlength a * medlength b\n\nreadPair :: IO (Integer, Integer)\nreadPair = do\n x:y:[] <- readInts\n return (x, y)\n\nreassoc :: [(a, b)] -> ([a], [b])\nreassoc = foldl (\\(xs, ys) (x, y) -> (x:xs, y:ys)) ([], [])\n\nreadInput :: IO ([Integer], [Integer])\nreadInput = fmap reassoc $ readLn >>= flip replicateM readPair\n\nsolveCase :: IO Integer\nsolveCase = fmap solve readInput\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= print)\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\nmedianCount :: [Int] -> Int\nmedianCount x = let\n n = length x\n sx = sort x\n [lv, rv] = map (sx !!) [div (n-1) 2, div n 2]\n in rv - lv + 1\n\n(*!) :: Int -> Int -> Int64\nx *! y = fromIntegral x * fromIntegral y\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n [x, y] <- transpose <$> replicateM n readInts\n putInt64s [medianCount x *! medianCount y]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n ps <- map (\\[x, y] -> (x, y)) <$> replicateM n popIntegers\n return $ bshow (solve n ps)\n\n\nmap2 f (a, b) = (f a, f b)\n\n\nsolve :: Int -> [(Integer, Integer)] -> Integer\nsolve n ps =\n let xs = sort $ map fst ps\n ys = sort $ map snd ps in\n case n `rem` 2 of\n 0 -> (\\(cx, cy) -> cx * cy) $\n map2 ((\\[a, b] -> b - a + 1) . take 2 . drop ((n `quot` 2) - 1)) $\n (xs, ys)\n 1 -> 1\n"}], "negative_code": [], "src_uid": "e0a1dc397838852957d0e15ec98d5efe"} {"source_code": "import Data.List\r\n\r\nsolve :: [String] -> String\r\nsolve [] = \"B\"\r\nsolve (a:xs) = if a == replicate 8 'R' then \"R\" else solve xs \r\n\r\ntestCase = do\r\n n <- getLine\r\n grid <- repeatDo 8 getLine\r\n putStrLn $ solve grid\r\n\r\nrepeatDo 0 m = return []\r\n\r\nrepeatDo n m = do\r\n x1 <- m\r\n x2 <- repeatDo (n - 1) m\r\n return (x1 : x2)\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatDo n testCase", "positive_code": [{"source_code": "import Control.Monad (forM, forM_)\r\nimport Data.List (nub, transpose)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (map read . words) getLine\r\n\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_\r\n [1 .. n]\r\n ( \\_ -> do\r\n _ <- getLine\r\n ans <- forM [1 .. 8] (\\_ -> do getLine)\r\n putStrLn $\r\n if any ((== True) . all (== 'R')) ans\r\n then \"R\"\r\n else \"B\"\r\n )"}], "negative_code": [{"source_code": "import Control.Monad (forM, forM_)\r\nimport Data.List (nub, transpose)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (map read . words) getLine\r\n\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_\r\n [1 .. n]\r\n ( \\_ -> do\r\n _ <- getLine\r\n ans <- forM [1 .. 8] (\\_ -> do getLine)\r\n print ans\r\n putStrLn $\r\n if any ((== True) . all (== 'R')) ans\r\n then \"R\"\r\n else \"B\"\r\n )"}, {"source_code": "import Control.Monad (forM, forM_)\r\nimport Data.List (nub, transpose)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (map read . words) getLine\r\n\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_\r\n [1 .. n]\r\n ( \\_ -> do\r\n ans <- forM [1 .. 8] (\\_ -> do getLine)\r\n putStrLn $\r\n if any ((== True) . all (== 'R')) ans\r\n then \"R\"\r\n else \"B\"\r\n )"}], "src_uid": "2c7add49d423de44a2bc09de56ffacf1"} {"source_code": "import Control.Applicative\nimport Data.Int\nimport Data.List (groupBy, sort)\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\n\nmain = do\n _ <- readLn :: IO Int \n xs <- readLs :: IO [Int64]\n let res = solve xs\n print $ length res \n putStrLn $ unwords . map show $ res \n\nsolve = map snd . sort . solve' [] . prepare\n where prepare = M.fromList . map (\\xs -> let (x:_, ys) = unzip xs in (x, S.fromAscList ys)) .\n groupBy (\\x y -> fst x == fst y) . sort . flip zip [0..]\n solve' acc m | M.null m = reverse acc \n solve' acc m = let ((x, is), m') = M.deleteFindMin m\n in case S.size is of\n 0 -> solve' acc m'\n 1 -> solve' ((S.findMin is, x) : acc) m'\n n -> let (i, is') = S.deleteFindMin $ snd $ S.deleteFindMin is\n in solve' acc $ M.insert x is' $\n M.insertWith (const $ S.insert i) (2*x) (S.singleton i) m'\n\nreadLs = map read . words <$> getLine", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns #-}\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport qualified Data.Map.Strict as M\nimport Data.Int\nimport Data.List\nimport Data.Ord\nimport Control.Applicative\n\nmain = interact exec\nexec = (\\xs -> show (length xs) ++ \"\\n\" ++ unwords (map show xs)) . (\\(n:xs) -> f (read n) (map read xs :: [Int64])) . words\nf n = map fst . sortBy (comparing (IS.findMin . snd)) . M.assocs . (g <*> (S.fromAscList . M.keys)) . M.fromListWith IS.union . flip zip (map IS.singleton [n, n - 1..]) . reverse\n\ng (!m) (!xs)\n | Just (x, h (M.delete x m) x (IS.toList $ m M.! x) -> (m', xs')) <- S.minView xs = g m' xs'\n | otherwise = m\n\nh m _ [] xs = (m, xs)\nh m x [j] xs = (M.insert x (IS.singleton j) m, xs)\nh (!m) x (_:j:is) (!xs) = h (M.alter (Just . maybe (IS.singleton j) (IS.insert j)) (2 * x) m) x is (S.insert (2 * x) xs)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns #-}\nimport qualified Data.IntMap.Strict as M\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Ord\nimport Control.Applicative\n\nmain = interact exec\nexec = (\\xs -> show (length xs) ++ \"\\n\" ++ unwords (map show xs)) . (\\(n:xs) -> f (n :: Int) xs) . map read . words\nf n = map fst . sortBy (comparing (S.findMin . snd)) . M.assocs . (g <*> (S.fromAscList . M.keys)) . M.fromListWith S.union . flip zip (map S.singleton [n, n - 1..]) . reverse\n\ng (!m) (!xs)\n | Just (x, h (M.delete x m) x (S.toList $ m M.! x) -> (m', xs')) <- S.minView xs = g m' xs'\n | otherwise = m\n\nh m _ [] xs = (m, xs)\nh m x [j] xs = (M.insert x (S.singleton j) m, xs)\nh (!m) x (_:j:is) (!xs) = h (M.alter (Just . maybe (S.singleton j) (S.insert j)) (2 * x) m) x is (S.insert (2 * x) xs)\n"}], "src_uid": "297d68c8be0c3358548949f277b9c087"} {"source_code": "import Data.List\nimport qualified Data.Map.Strict as Map\n\ntoint s = (read s) :: Int\n\nm = 200001\n\ndoit [] n s = []\ndoit (x:xs) n s =\n let t = x+s in -- t+k=n\n let w = mod (n-t+m) m in\n if w == 0 then\n doit xs (n-1) s\n else\n (n,w):(doit xs (n-1) (s+w))\n\nprintit [] = \"\"\nprintit ((a,b):xs) =\n \"1 \"++show(a)++\" \"++show(b)++\"\\n\"++(printit xs)\n\n\nsolve::String -> String\nsolve ss =\n let n:aa = map toint $ words ss in\n let a = reverse $ take n aa in\n let r = doit a n 0 in\n show(length r + 1)++\"\\n\"++(printit r)++\"2 \"++show(n)++\" \"++show(m)++\"\\n\"\n\nmain = do\n interact $ solve", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\n\nshowTriple :: (Int,Int,Int) -> String\nshowTriple (x,y,z)\n = shows x $ (' ' :) $ shows y $ (' ' :) $ show z\n\nprintTriple :: (Int,Int,Int) -> IO ()\nprintTriple = putStrLn . showTriple\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n getLine\n print $ n+1\n printTriple (2,n,1)\n printTriple (1,n,2*n)\n mapM_ printTriple $ [(2,j,2*n-j) | j <- [1..n-1]]"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\n\nshowTriple :: (Int,Int,Int) -> String\nshowTriple (x,y,z)\n = shows x $ (' ' :) $ shows y $ (' ' :) $ show z\n\nprintTriple :: (Int,Int,Int) -> IO ()\nprintTriple = putStrLn . showTriple\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n getLine\n printTriple (2,n,1)\n printTriple (1,n,2*n)\n mapM_ printTriple $ [(1,j,2*n-j) | j <- [1..n-1]]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\n\nshowTriple :: (Int,Int,Int) -> String\nshowTriple (x,y,z)\n = shows x $ (' ' :) $ shows y $ (' ' :) $ show z\n\nprintTriple :: (Int,Int,Int) -> IO ()\nprintTriple = putStrLn . showTriple\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n getLine\n print $ n+1\n printTriple (2,n,1)\n printTriple (1,n,2*n)\n mapM_ printTriple $ [(1,j,2*n-j) | j <- [1..n-1]]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\n\nshowTriple :: (Int,Int,Int) -> String\nshowTriple (x,y,z)\n = shows x $ (' ' :) $ shows y $ (' ' :) $ show z\n\nprintTriple :: (Int,Int,Int) -> IO ()\nprintTriple = print . showTriple\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n getLine\n printTriple (2,n,1)\n printTriple (1,n,2*n)\n mapM_ printTriple $ [(1,j,2*n-j) | j <- [1..n-1]]"}], "src_uid": "e0ba8e0bfd9e1365daa41e1d14610200"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\t\tn<-map length <$> map (filter (\\z->elem z \"aeiou\") ) <$> replicateM 3 getLine\n\t\tputStrLn $ if n==[5,7,5] then \"YES\" else \"NO\" \n\n", "positive_code": [{"source_code": "isVowel :: Char -> Bool\nisVowel c = c `elem` \"aAeEiIoOuU\"\n\nvowelsInPhrase :: String -> Int\nvowelsInPhrase xs = sum [1 | x <- xs, isVowel x]\n\nisHaiku :: [String] -> Bool\nisHaiku phrases = pv == [5, 7, 5]\n\t\t\twhere\n\t\t\t\tpv = [vowelsInPhrase p | p <- phrases]\n\n--haven't written Haskell for sometime, so my\n--solution is kinda weird\n\nmain :: IO ()\nmain = do\n\t\tline1 <- getLine\n\t\tline2 <- getLine\n\t\tline3 <- getLine\n\t\t\n\t\tif(isHaiku [line1, line2, line3]) then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "import Text.Printf\nimport List\n\nmain = solve\n\nisVowel c = if Nothing == find (==c) \"aeiou\" then False else True\n\ngetVowels = do\n line <- getLine\n return (filter isVowel line)\n\nsolve = do\n x <- getVowels\n y <- getVowels\n z <- getVowels\n putStrLn (if ((length x == 5) && (length y == 7) && (length z == 5)) then \"YES\" else \"NO\")\n"}, {"source_code": "main = do cs <- getContents\n putStrLn $ ck $ lines cs\n\nck :: [String] -> String\nck [x, y, z]\n | length (filter bowel x) /= 5 = \"NO\"\n | length (filter bowel y) /= 7 = \"NO\"\n | length (filter bowel z) /= 5 = \"NO\"\n | otherwise = \"YES\"\n\nck [x, y, z, xs] = ck [x, y, z]\n\nbowel :: Char -> Bool\nbowel x\n | x == 'a' = True\n | x == 'i' = True\n | x == 'u' = True\n | x == 'e' = True\n | x == 'o' = True\n | otherwise = False\n"}, {"source_code": "import Data.List (intersect)\nsyllables :: String -> Int\nsyllables s = length $ s `intersect` \"aeuio\"\nmain = do\n l1 <- getLine\n l2 <- getLine\n l3 <- getLine\n putStr $ if map (syllables) [l1,l2,l3] == [5,7,5]\n then \"YES\"\n else \"NO\""}, {"source_code": "vowel = \"aeiouAEIOU\"\n\ncountVowel :: String -> Int\ncountVowel line = length $ filter (\\c -> c `elem` vowel) line\n\nhaiku :: [String] -> String\nhaiku lines = if [5, 7, 5] == (map countVowel lines) then \"YES\" else \"NO\"\n\nmain = do\n lines <- sequence (map (\\n -> getLine) [1..3]) \n putStrLn (haiku lines)"}, {"source_code": "main=getContents>>=(putStr.p.lines)\np x|map(length.filter(`elem`\"aeoui\"))x==[5,7,5]=\"YES\"\np _=\"NO\""}, {"source_code": "main = interact $ ifte \"YES\" \"NO\" . (== [5,7,5]) . map (length . filter (`elem` \"aeiou\")) . lines\nifte t e c = if c then t else e"}, {"source_code": "main = do\n s1 <- getLine\n s2 <- getLine\n s3 <- getLine\n putStrLn $ if wowels s1 == 5 && wowels s2 == 7 && wowels s3 == 5 then \"YES\" else \"NO\"\nwowels s = length $ filter wowel s\nwowel ch = ch `elem` ['a', 'e', 'i', 'o', 'u']\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc = solve\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[String]->String\nsolve (a:b:c:[]) | a' && b' && c' = \"YES\"\n | otherwise = \"NO\"\n where\n a' = count a == 5\n b' = count b == 7\n c' = count c == 5\n\ncount::String->Int\ncount [] = 0\ncount (s:xs) | s `elem` \"aeiou\" = 1 + count xs\n | otherwise = count xs"}, {"source_code": "import Data.List\n\nis :: Char -> Bool\nis 'a' = True\nis 'e' = True\nis 'i' = True\nis 'o' = True\nis 'u' = True\nis x = False\n\n\ncount :: String -> Int\ncount xs = sum [ 1 | x <- xs , is x ]\n\nmain :: IO()\nmain = do \n a <- getLine\n b <- getLine\n c <- getLine\n if [ count a, count b , count c] == [5,7,5]\n then putStrLn \"YES\"\n else putStrLn \"NO\" \n"}, {"source_code": "import Data.List\n\nis :: Char -> Bool\nis 'a' = True\nis 'e' = True\nis 'i' = True\nis 'o' = True\nis 'u' = True\nis x = False\n\n\ncount :: String -> Int\ncount xs = sum [ 1 | x <- xs , is x ]\n\nmain :: IO()\nmain = do \n a <- getLine\n b <- getLine\n c <- getLine\n if [ count a, count b , count c] == [5,7,5]\n then putStrLn \"YES\"\n else putStrLn \"NO\" \n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, UndecidableInstances, ImplicitParams, ExplicitForAll #-}\n{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n ss <- replicateM 3 getLine\n let isVowel c | c `elem ` \"aeiou\" = True\n | otherwise = False\n case map (length . filter isVowel) ss of\n [5, 7, 5] -> putStrLn \"YES\"\n _ -> putStrLn \"NO\"\n"}, {"source_code": "main = interact $ isVowelHaiku . take 3 . lines\n\nisVowelHaiku :: [String] -> String\nisVowelHaiku xs = if vowelLines xs == [5,7,5] then \"YES\" else \"NO\"\n\nvowelLines :: [String] -> [Int]\nvowelLines = map (length . filter (`elem` \"aeiou\"))\n\n"}, {"source_code": "main = do\n l <- mapM (\\_ -> do\n l' <- getLine\n return $ length $ filter(`elem` \"aieou\") l') [1..3]\n putStrLn (if l == [5, 7, 5] then \"YES\" else \"NO\")\n"}, {"source_code": "import Control.Monad\n\nsy = length . filter (`elem` \"aeiou\")\n\nmain = do\n [a,b,c] <- replicateM 3 getLine\n putStrLn $ if sy a == 5 && sy b == 7 && sy c == 5 then \"YES\" else \"NO\"\n"}, {"source_code": "main = interact $ (\\x->if x==[5,7,5] then \"YES\\n\" else \"NO\\n\"). map (length . filter (`elem` \"aeiou\")) . lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\n-- input = lines <$> readFile \"input.txt\"\ninput = lines <$> getContents\n\ncountVowel text = length xs\n where\n xs = intersect text vowel \nvowel = \"aeiou\"\n\nsolve :: [String] -> String\nsolve xs = if ys == [5,7,5] then \"YES\" else \"NO\"\n where ys = map countVowel $ xs\n\n\nmain :: IO ()\nmain = do { ns <- input\n ; printf \"%s\" . solve $ ns\n }\n"}, {"source_code": "import Data.List\n\n\ncount pred = length . (filter pred)\n\nsolve x = \n case map (count (flip elem \"aeiou\")) x of\n (5:7:5:_) -> True\n _ -> False\n\nprepare True = \"YES\"\nprepare False = \"NO\"\n\nmain = do\n stuff <- getContents\n putStrLn . prepare . solve . lines $ stuff\n"}], "negative_code": [{"source_code": "main = do cs <- getContents\n putStrLn $ ck $ lines cs\n\nck :: [String] -> String\nck [x, y, z]\n | length (filter bowel x) /= 5 = \"NO\"\n | length (filter bowel y) /= 7 = \"NO\"\n | length (filter bowel z) /= 5 = \"NO\"\n | otherwise = \"TRUE\"\n\nck [x, y, z, xs] = ck [x, y, z]\n\nbowel :: Char -> Bool\nbowel x\n | x == 'a' = True\n | x == 'i' = True\n | x == 'u' = True\n | x == 'e' = True\n | x == 'o' = True\n | otherwise = False\n \n"}, {"source_code": "import Data.List (intersect)\nsyllables :: String -> Int\nsyllables s = length $ s `intersect` \"aeuio\"\nmain = do\n l1 <- getLine\n l2 <- getLine\n l3 <- getLine\n print $ if map (syllables) [l1,l2,l3] == [7,5,7]\n then \"YES\"\n else \"NO\""}, {"source_code": "main = do\n l <- mapM (\\_ -> do\n l' <- getLine\n return $ length $ filter(`elem` \"aieou\") l') [1..3]\n print (if l == [5, 7, 5] then \"YES\" else \"NO\")\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\n-- input = lines <$> readFile \"input.txt\"\ninput = lines <$> getContents\n\ncountVowel text = length xs\n where\n xs = intersect text vowel \nvowel = \"aeiou\"\n\nsolve xs = if ys == [5,7,5] then \"YES\" else \"NO\"\n where ys = map countVowel $ xs\n\n\nmain :: IO ()\nmain = do { ns <- input\n ; print . solve $ ns\n }\n"}, {"source_code": "import Data.List\n\n\ncount pred = length . (filter pred)\n\nsolve x = \n case map (count (flip elem \"aeiou\")) x of\n (5:7:5:_) -> True\n _ -> False\n\nmain = do\n stuff <- getContents\n print . solve . lines $ stuff\n"}, {"source_code": "isVowel :: Char -> Bool\nisVowel c = c `elem` \"aAeEiIoOuU\"\n\nvowelsInPhrase :: String -> Int\nvowelsInPhrase xs = sum [1 | x <- xs, isVowel x]\n\nisHaiku :: String -> Bool\nisHaiku s = pv == [5, 7, 5]\n\t\t\twhere\n\t\t\t\tphrases = lines s\n\t\t\t\tpv = [vowelsInPhrase p | p <- phrases]\n\n--haven't written Haskell for sometime, so my\n--solution is kinda weird\n\nmain :: IO ()\nmain = do\n\t\tline1 <- getLine\n\t\tline2 <- getLine\n\t\tline3 <- getLine\n\t\t\n\t\tlet haiku = line1 ++ line2 ++ line3\n\t\t\n\t\tif(isHaiku haiku) then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "isVowel :: Char -> Bool\nisVowel c = c `elem` \"aAeEiIoOuU\"\n\nvowelsInPhrase :: String -> Int\nvowelsInPhrase xs = sum [1 | x <- xs, isVowel x]\n\nisHaiku :: String -> Bool\nisHaiku s = sum [vowelsInPhrase p | p <- phrases] == 17\n\t\t\twhere\n\t\t\t\tphrases = lines s\n\n--haven't written Haskell for sometime, so my\n--solution is kinda weird\n\nmain :: IO ()\nmain = do\n\t\tline1 <- getLine\n\t\tline2 <- getLine\n\t\tline3 <- getLine\n\t\t\n\t\tlet haiku = line1 ++ line2 ++ line3\n\t\t\n\t\tif(isHaiku haiku) then putStrLn \"YES\" else putStrLn \"NO\"\n"}], "src_uid": "46d734178b3acaddf2ee3706f04d603d"} {"source_code": "import Data.List\n\nreadNum :: (Num n, Read n) => IO n\nreadNum = do\n line <- getLine\n return $ read line\n\nans :: Int -> [Int] -> Int\nans n x = succ . length . takeWhile ( IO n\nreadNum = read <$> getLine\n\nsolve n m [] = 0\nsolve n m (x:xs) = if (m-x) <= 0 then n - length xs\n else solve n (m-x) xs\n\nmain = do\n n <- readNum\n m <- readNum\n sizes <- sequence $ replicate n readNum\n putStrLn $ show $ solve n m (sortBy (flip compare) sizes)\n"}, {"source_code": "import Data.List\n\nreadNum :: (Num n, Read n) => IO n\nreadNum = do\n line <- getLine\n return $ read line\n\nsolve n m [] = 0\nsolve n m (x:xs) = if (m-x) <= 0 then n - length xs\n else solve n (m-x) xs\n\nmain = do\n n <- readNum\n m <- readNum\n sizes <- sequence $ replicate n readNum\n putStrLn $ show $ solve n m (sortBy (flip compare) sizes)\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve (c:cs) space num =\n if c >= space \n then num \n else solve cs (space - c) (num + 1)\nsolve _ _ num = num\n\nmain = do\n _ <- getLine\n numStr <- readInt <$> getLine\n cards <- map readInt . lines <$> getContents\n print $ solve (sortBy (flip compare) cards) numStr 1\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char (intToDigit, digitToInt)\nimport Control.Monad (replicateM)\n\nimport Data.List (sortBy)\n\n\nparseInt :: ByteString -> Int\nparseInt s\n | BS.head s == '-' = negate (go 0 (BS.tail s))\n | otherwise = go 0 s\n where\n go i s\n | BS.null s = i\n | otherwise = go (i*10 + digitToInt (BS.head s)) (BS.tail s)\n\n\nprintInt :: Int -> ByteString\nprintInt i\n | i < 10 = BS.singleton (intToDigit i)\n | otherwise = BS.snoc (printInt (i `quot` 10)) (intToDigit (i `rem` 10))\n\n\ndarnit :: ByteString -> ByteString\ndarnit s \n | BS.last s == '\\r' = BS.init s\n | otherwise = s\n\n\nmain :: IO ()\nmain = do\n n <- fmap (parseInt . darnit) BS.getLine\n m <- fmap (parseInt . darnit) BS.getLine\n as <- replicateM n (fmap (parseInt . darnit) BS.getLine)\n let drives = (+1) . length . takeWhile (< m) . scanl1 (+) . sortBy (flip compare) $ as\n BS.putStrLn (printInt drives)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: Int -> [Int] -> Int\nsolve n vals =\n fst $ head $ filter (\\x -> snd x >= n) $ partialSums\n where\n sorted = reverse $ sort $ vals\n partialSums = zip [1..] $ scanl1 (+) sorted\n\nmain = do\n getLine\n m <- read <$> getLine\n vals <- map read . lines <$> getContents\n putStrLn $ show $ solve m vals\n \n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve (m:as) = length $ takeWhile (< m) $ scanl (+) 0 $ reverse $ sort as\n"}, {"source_code": "import Data.List\n\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve (m:as) = head [ x | x <- [1..], m <= sum (take x (sortBy (flip compare) as))]\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Tuple\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport Data.Word\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n m <- readLn :: IO Int\n xs <- U.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getContents\n print $ solve m xs\n\nsolve :: Int -> U.Vector Int -> Int\nsolve m vec = fst.U.head.U.dropWhile(( U.Vector Int\nradixSort32 v = foldl' step v [0, 16]\n where\n mask k x = fromIntegral $ unsafeShiftR x k .&. 0xffff\n step v k = U.create $ do\n pref <- U.unsafeThaw\n . U.prescanl' (+) 0\n . U.unsafeAccumulate (+) (U.replicate 0x10000 0)\n $ U.map ((,1) . mask k) v\n res <- UM.unsafeNew $ U.length v\n U.forM_ v $ \\x -> do\n let !masked = mask k x\n i <- UM.unsafeRead pref masked\n UM.unsafeWrite pref masked $ i + 1\n UM.unsafeWrite res i x\n return res"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nmain :: IO ()\nmain = do\n n <- inputInt\n m <- inputInt\n a <- replicateM n inputInt\n print . length . takeWhile (< m) . scanl (+) 0 . reverse $ sort a\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\t\t\n\nonecase = do\n\t\t[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tlet x = div s c\n\t\tprint $ x + (div x a)*b\n\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\ts<-read<$> getLine ::IO Int\n\t\ta<-scanl1 (+) <$> reverse <$> sort <$> map read <$>replicateM n getLine ::IO [Int]\n\t\tprint $ 1+ length (takeWhile ( [Int] -> Int\nprocess m = (1+).length.dropWhile (>=m).scanr1 (+).sort\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n m <- fmap readInt getLine\n a <- fmap (map readInt.words) getContents\n print $ process m a"}, {"source_code": "import Data.List\nmain = do\n c1<- ( getContents )\n let c = lines c1\n let n = head c\n let m = head (tail c)\n let f = drop 2 c\n print ( (calcf (read m) (reverse (sort (map read f))) 1))\n\n\ncalcf m f i = if (sum (take i f)) >= m then i\n else calcf m f (i+1)\n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n getLine\n [m] <- (map read . words) `fmap` getLine\n as <- (sort . map read . lines) `fmap` getContents\n\n print . (+1) . length . takeWhile (< m) $ scanl1 (+) (reverse as)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\n\ngetInt :: IO Int\ngetInt = (read . T.unpack . T.strip . T.pack) <$> getLine\n\nmain :: IO ()\nmain = do\n (n, m) <- (,) <$> getInt <*> getInt\n items <- L.sort <$> forM [0 .. n - 1] (const getInt)\n let (_, res) = foldr (\\x (s, cnt) -> (s + x, if s < m then cnt + 1 else cnt)) (0, 0) items \n putStrLn $ show res"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\n\ngetInt :: IO Int\ngetInt = (read . T.unpack . T.strip . T.pack) <$> getLine\n\nmain :: IO ()\nmain = do\n (n, m) <- (,) <$> getInt <*> getInt\n items <- L.sort <$> forM [0 .. n - 1] (const getInt)\n putStrLn $ show items\n let (_, cnt) = foldr (\\x (s, cnt) -> let s' = s + x in (s', if s' < m then cnt + 1 else cnt)) (0, 0) items \n putStrLn $ show cnt"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\n\ngetInt :: IO Int\ngetInt = (read . T.unpack . T.strip . T.pack) <$> getLine\n\nmain :: IO ()\nmain = do\n (n, m) <- (,) <$> getInt <*> getInt\n items <- L.sort <$> forM [0 .. n - 1] (const getInt)\n let (_, cnt) = foldr (\\x (s, cnt) -> let s' = s + x in (s, if s' < m then cnt + 1 else cnt)) (0, 0) items \n putStrLn $ show cnt"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (forM)\nimport qualified Data.Text as T\nimport qualified Data.List as L\n\ngetInt :: IO Int\ngetInt = (read . T.unpack . T.strip . T.pack) <$> getLine\n\nmain :: IO ()\nmain = do\n (n, m) <- (,) <$> getInt <*> getInt\n items <- L.sort <$> forM [0 .. n - 1] (const getInt)\n let (_, cnt) = foldr (\\x (s, cnt) -> let s' = s + x in (s', if s' < m then cnt + 1 else cnt)) (0, 0) items \n putStrLn $ show cnt"}], "src_uid": "a02a9e37a4499f9c86ac690a3a427466"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsecond :: [a] -> [a]\nsecond [] = []\nsecond (a:b:c) = b : second c\n\nsolve :: String -> Bool\nsolve = (>=11)\n . length \n . dropWhile (/='8')\n\nyesno :: Bool -> String\nyesno b = if b then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readInt\n s <- replicateM (2 * n) getLine\n mapM_ putStrLn $ map (yesno . solve) $ second s", "positive_code": [{"source_code": "main = getContents >>= putStr . solve . tail . words\n\nsolve [] = []\nsolve (_:x:xs)\n | (length $ dropWhile (/='8') x) >= 11 = \"YES\\n\" ++ solve xs\n | otherwise = \"NO\\n\" ++ solve xs"}, {"source_code": "import Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n s <- getLine\n putStrLn $ if n >= 11 && any (== '8') (drop 10 (reverse s))\n then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\ncheck c s | c==11 && head s =='8' = True\n | c<11 = False\n\t | (length $ take 1 $ filter (=='8') $ take (c-11) s)==1 = True\n | head ( drop (c-11) s)=='8' = True\n\t | otherwise = False \n\nonecase = do\n\t\tc<- read <$> getLine ::IO Int\n\t\ts<- getLine\n\t\tputStrLn $ if check c s then \"YES\" else \"NO\"\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n\n"}, {"source_code": "--ghc 7.10\n\nisTelephoneNumberable :: String -> Bool\nisTelephoneNumberable str \n | n > 0 = elem '8' . take n $ str\n | otherwise = False\n where\n n = length str - 10\n\nshowBool :: Bool -> String\nshowBool True = \"YES\"\nshowBool False = \"NO\"\n\nprocess :: Int -> IO ()\nprocess 0 = return ()\nprocess t = do\n nStr <- getLine\n phoneNo <- getLine\n putStrLn . showBool . isTelephoneNumberable $ phoneNo\n process (t-1)\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n process t"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Control.Monad\nimport Data.Function\nimport Data.List\n\nmain :: IO ()\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n c <- read <$> getLine\n xs <- getLine\n putStrLn $ f c xs\n\nf :: Int -> String -> String\nf c xs =\n let\n pos = findIndex (=='8') $ xs\n in case pos of\n Nothing -> \"NO\"\n Just x -> if (c -x) >= 11 then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\tn <- readInt\n\ts <- getLine\n\tlet\n\t\trest = dropWhile ( /= '8' ) s\n\tputStrLn $ if length rest >= 11 then \"YES\" else \"NO\""}, {"source_code": "import Data.Function\nsolve = (\\x -> if x then \"YES\" else \"NO\") . (>=11) . length . snd . break (=='8') \nmain = interact $ unlines . fix (\\f xs -> if null xs then [] else let (x:y:ys) = xs in solve y : f ys) . tail .lines \n"}], "negative_code": [{"source_code": "import Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- getLine\n s <- getLine\n putStrLn $ if length n >= 11 && any (== '8') (drop 10 (reverse n))\n then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\tc<- read <$> getLine ::IO Int\n\t\ts<- getLine\n\t\tputStrLn $ if 1==(length $ take 1 $ filter (=='8') $ take (c-11) s) then \"YES\" else \"NO\"\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\tc<- read <$> getLine ::IO Int\n\t\ts<- getLine\n\t\tputStrLn $ if (c==11 && head s =='8') then \"YES\" else if 1==(length $ take 1 $ filter (=='8') $ take (c-11) s) then \"YES\" else \"NO\"\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n\n"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Control.Monad\nimport Data.Function\nimport Data.List\n\nmain :: IO ()\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n c <- read <$> getLine\n xs <- getLine\n print $ f c xs\n\nf :: Int -> String -> String\nf c xs =\n let\n pos = findIndex (=='8') $ xs\n in case pos of\n Nothing -> \"NO\"\n Just x -> if (c -x) >= 10 then \"YES\" else \"NO\"\n\n"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Control.Monad\nimport Data.Function\nimport Data.List\n\nmain :: IO ()\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n c <- read <$> getLine\n xs <- getLine\n print $ f c xs\n\nf :: Int -> String -> String\nf c xs =\n let\n pos = findIndex (=='8') $ xs\n in case pos of\n Nothing -> \"NO\"\n Just x -> if (c -x) >= 11 then \"YES\" else \"NO\"\n"}], "src_uid": "bcdd7862b718d6bcc25c9aba8716d487"} {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Control.Applicative\n\nmain = do\n [n,a,d] <- map read'.B.words <$> B.getLine\n tvs <- map (map read'.B.words).B.lines <$> B.getContents\n C.putStr.C.unlines.map (C.pack.show) $ solve a d tvs\n\nread' s = let Just (n,_) = B.readInteger s in n\n\nsolve :: Integer -> Integer -> [[Integer]] -> [Double]\nsolve a' d' tvs = scanl1 max $ map calc tvs\n where [a,d] = map fromIntegral [a',d']\n calc [ti',vi']\n | 2*a'*d'<=vi'*vi' = ti + sqrt ((2*d)/a)\n | otherwise = vi/(2*a) + d/vi + ti\n where [ti,vi] = map fromIntegral [ti',vi']", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do\n [n,a,d] <- map read'.B.words <$> B.getLine\n tvs <- map (map read'.B.words).B.lines <$> B.getContents\n putStr.unlines.map show$solve a d tvs\n\nread' s = let Just (n,_) = B.readInteger s in n\n\nsolve :: Integer -> Integer -> [[Integer]] -> [Double]\nsolve a' d' tvs = scanl1 max $ map calc tvs\n where [a,d] = map fromIntegral [a',d']\n calc [ti',vi']\n | 2*a'*d'<=vi'*vi' = ti + sqrt ((2*d)/a)\n | otherwise = vi/(2*a) + d/vi + ti\n where [ti,vi] = map fromIntegral [ti',vi']"}], "negative_code": [], "src_uid": "894f407ca706788b13571878da8570f5"} {"source_code": "{- ok -}\nimport Control.Applicative ((<$>))\n\nmain = do\n\tgetLine\n\tpoints <- map ((\\[a, b] -> (a, b)) . map read . words) . lines <$> getContents\n\n\tlet\n \t\tcount = length $ filter (<0) $ zipWith mul vects $ tail vects ++ [head vects]\n \t\t\twhere\n\t\t\t\tvects = zipWith (\\(x1, y1) (x2, y2) -> (x2 - x1, y2 - y1)) points $ tail points\n\t\t\t\tmul (x1, y1) (x2, y2) = x2 * y1 - x1 * y2\n\n\tprint count\n\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nmain = do\n\tgetLine\n\tpoints <- map ((\\[a, b] -> (a, b)) . map read . words) . lines <$> getContents\n\n\tlet\n \t\tcount = length $ filter (<0) $ zipWith mul vects $ tail vects ++ [head vects]\n \t\t\twhere\n\t\t\t\tvects = zipWith (\\(x1, y1) (x2, y2) -> (x2 - x1, y2 - y1)) points $ tail points\n\t\t\t\tmul (x1, y1) (x2, y2) = x2 * y1 - x1 * y2\n\n\tprint count\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nisCCW (xa,ya) (xb,yb) (xc,yc) =\n let\n v1 = (xb-xa,yb-ya)\n v2 = (xc-xb,yc-yb)\n in fst v1 * snd v2 - snd v1 * fst v2 > 0\n\nunfolder :: [(Int, Int)] -> Maybe (Bool, [(Int, Int)])\nunfolder (a:b:c:rest) = Just (isCCW a b c, b:c:rest)\nunfolder _ = Nothing\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n print =<< sum . map fromEnum . unfoldr unfolder . map ((\\[a,b]->(a,b)) . map (read :: String -> Int) . words) <$> replicateM (n + 1) getLine\n"}], "negative_code": [], "src_uid": "0054f9e2549900487d78fae9aa4c2d65"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char (digitToInt)\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = pair int int\n\n-- output :: Output -> C.ByteString\noutput = C.unwords . map showB\n\n-- solve :: Input -> Output\nsolve (s, 1) = [s]\nsolve (s, n) = let p = maximum . filter (<= s - n + 1) $ ps10 in p : solve (s - p, n - 1)\n\nps10 = map (10 ^) [0 .. 9]\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> tail\n >>> map (words >>> map read >>> toPair >>> solve >>> map show >>> unwords)\n >>> unlines\n where\n toPair [a, b] = (a, b)\n\nsolve :: (Int, Int) -> [Int]\nsolve (s, 1) = [s]\nsolve (s, n) = let p = maximum . filter (<= s - n + 1) $ ps10 in p : solve (s - p, n - 1)\n\nps10 = map (10 ^) [0 .. 9]\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char (digitToInt)\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = pair int int\n\n-- output :: Output -> C.ByteString\noutput = C.unwords . map showB \n\n-- solve :: Input -> Output\nsolve (s, n)\n | dsum s >= n = let xs = take n $ iterate pickDigit s in zipWith (-) xs (tail xs ++ [0])\n | otherwise = p : solve (s - p, n - 1)\n where\n p = maximum [x | e <- [0..9], let x = 10^e, s - x >= n - 1]\n\n dsum = sum . map digitToInt . show\n largestP10 = (10 ^) . subtract 1 . length . dropWhile (== '0') . show\n pickDigit n = n - largestP10 n\n\ndebug a = trace (show a) a\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char (digitToInt)\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = pair int int\n\n-- output :: Output -> C.ByteString\noutput = C.unwords . map showB\n\n-- solve :: Input -> Output\nsolve (s, n)\n | dsum >= n = let xs = take n $ iterate pickDigit s in zipWith (-) xs (tail xs ++ [0])\n | s < 10 = replicate n 1\n | s - p >= n - 1 = p : solve (s - p, n - 1)\n | otherwise = let p' = p `div` 10 in p' : solve (s - p', n - 1)\n where\n p = largestP10 s\n dsum = sum . map digitToInt $ show s\n largestP10 = (10 ^) . subtract 1 . length . dropWhile (== '0') . show\n pickDigit n = n - largestP10 n\n\ndebug a = trace (show a) a\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "2afb210831529a99f8f04f13e5438d55"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [caseNum] <- getInts\n forM_ [1..caseNum] $ \\_ -> do\n _ <- getInts\n as <- getInts\n let f n x = (length $ filter (==x) as) < n\n g n = fromJust $ find (f n) [0..]\n printf \"%d\\n\" (g 1 + g 2)\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Functor\nimport Data.Bool\nimport Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt\n\nreadInt64B8 :: B8.ByteString -> Int64\nreadInt64B8 = fromIntegral . fst . fromJust . B8.readInteger\n\nsolve :: Int -> [Int] -> Int\nsolve n as = \n aValue + bValue\n where\n sortedAs = sort as\n aGroups = map (\\as -> (head as, length as)) $ group sortedAs\n aValue = fromMaybe (length aGroups) $ findGroup 1\n bValue = fromMaybe (length aGroups) $ findGroup 2\n findGroup needCnt = fmap fst . find (\\(i, (a, cnt)) -> checkGroup i a cnt needCnt) . zip [0..] $ aGroups\n checkGroup i a cnt needCnt\n | (i == a) && (cnt >= needCnt) = False\n | otherwise = True\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> B8.words <&> map readIntB8\n let answer = solve n as\n printf \"%d\\n\" $ answer\n\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n let\n vs :: [[Int]]\n vs = group (sort a)\n q = [length v | (i, v) <- zip [0..] vs, i == head v]\n print . sum . tail $ scanl min 2 q\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n let\n vs = group (sort a)\n q = [length v | (i, v) <- zip [0..] vs, i == head v]\n print . sum $ map (min 2) q\n"}], "src_uid": "e26b0b117593c159b7f01cfac66a71d1"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables, FlexibleContexts #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.List as L (sort)\nimport qualified Data.Array.IArray as A (Array, accumArray, (!))\nimport qualified Data.Array.MArray.Safe as A (newArray, newListArray, readArray, writeArray)\nimport qualified Data.Array.ST.Safe as ST (STUArray)\nimport qualified Control.Monad.ST.Safe as ST (runST, ST)\nimport qualified Data.STRef as ST (newSTRef, modifySTRef, readSTRef)\nimport qualified Control.Monad as M (forM, forM_)\nimport qualified Data.Set as S (fromList, toList)\n\nreadInt = fst . M.fromJust . C.readInt\n\n-- disjoint set\ndata DSU s = DSU (ST.STUArray s Int Int) (ST.STUArray s Int Int) (ST.STUArray s Int Int)\ncreate n = do\n rank <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)\n pare <- A.newListArray (1, n) [1..] :: ST.ST s (ST.STUArray s Int Int)\n size <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)\n return $ DSU rank pare size\nfind dsu@(DSU _ pare _) x = do\n r <- A.readArray pare x\n if r /= x then find dsu r >>= A.writeArray pare x else return ()\n A.readArray pare x\nunion dsu@(DSU rank pare size) x y = do\n x <- find dsu x\n y <- find dsu y\n if x == y then return () else do\n rx <- A.readArray rank x\n ry <- A.readArray rank y\n sx <- A.readArray size x\n sy <- A.readArray size y\n case compare rx ry of\n LT -> A.writeArray pare x y >> A.writeArray size y (sx + sy)\n GT -> A.writeArray pare y x >> A.writeArray size x (sx + sy)\n EQ -> do\n A.writeArray pare y x >> A.writeArray size x (sx + sy)\n A.writeArray rank x (rx + 1)\n\nrun n nr ag rs = ST.runST $ do\n xn <- ST.newSTRef (0 :: I.Int64)\n xsum <- ST.newSTRef (0 :: I.Int64)\n xsumsq <- ST.newSTRef (0 :: I.Int64)\n dsu@(DSU _ _ size) <- create n\n (((-1) -) . snd . maximum -> r) <- M.forM [1..nr] $ \\i -> do\n M.forM_ (ag A.! i) $ \\j -> do\n ST.modifySTRef xn succ\n ST.modifySTRef xsum succ\n ST.modifySTRef xsumsq succ\n A.writeArray size j 1\n M.forM_ (ag A.! i) $ \\j -> do\n if j /= 1 then do\n (fromIntegral -> sjp) <- find dsu (j - 1) >>= A.readArray size\n (fromIntegral -> sjq) <- find dsu j >>= A.readArray size\n if sjp /= 0 then do\n ST.modifySTRef xn pred\n ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))\n union dsu (j - 1) j\n else return ()\n else return ()\n if j /= n then do\n (fromIntegral -> sjp) <- find dsu j >>= A.readArray size\n (fromIntegral -> sjq) <- find dsu (j + 1) >>= A.readArray size\n if sjq /= 0 then do\n ST.modifySTRef xn pred\n ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))\n union dsu j (j + 1)\n else return ()\n else return ()\n xnv <- ST.readSTRef xn\n xsumv <- ST.readSTRef xsum\n xsumsqv <- ST.readSTRef xsumsq\n return (if xsumsqv * xnv - xsumv * xsumv == 0 then xnv else 0, -i)\n return $ rs !! r + 1\n\nmain = do\n (readInt -> n) <- B.getLine\n (L.sort . (flip zip) [1..] . map readInt . C.words -> xs) <- B.getLine\n let rs = S.toList . S.fromList . map fst $ xs\n nr = length rs\n gs = (\\(_, _, x) -> reverse x) $ foldl (\\(i, p, rs) (x, y) -> if p == x then (i, p, (i, y):rs)\n else (i + 1, x, (i + 1, y):rs)) (0, 0, []) $! xs\n ag = A.accumArray (flip (:)) [] (1, nr) gs :: A.Array Int [Int]\n print $ run n nr ag rs\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables, FlexibleContexts #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.List as L (sort, foldl')\nimport qualified Data.Array.IArray as A (Array, accumArray, (!))\nimport qualified Data.Array.MArray.Safe as A (newArray, newListArray, readArray, writeArray)\nimport qualified Data.Array.ST.Safe as ST (STUArray)\nimport qualified Control.Monad.ST.Safe as ST (runST, ST)\nimport qualified Data.STRef as ST (newSTRef, modifySTRef, readSTRef)\nimport qualified Control.Monad as M (forM, forM_)\nimport qualified Data.Set as S (fromList, toList)\n\nreadInt = fst . M.fromJust . C.readInt\n\n-- disjoint set\ndata DSU s = DSU (ST.STUArray s Int Int) (ST.STUArray s Int Int) (ST.STUArray s Int Int)\ncreate n = do\n rank <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)\n pare <- A.newListArray (1, n) [1..] :: ST.ST s (ST.STUArray s Int Int)\n size <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)\n return $ DSU rank pare size\nfind dsu@(DSU _ pare _) x = do\n r <- A.readArray pare x\n if r /= x then find dsu r >>= A.writeArray pare x else return ()\n A.readArray pare x\nunion dsu@(DSU rank pare size) x y = do\n x <- find dsu x\n y <- find dsu y\n if x == y then return () else do\n rx <- A.readArray rank x\n ry <- A.readArray rank y\n sx <- A.readArray size x\n sy <- A.readArray size y\n case compare rx ry of\n LT -> A.writeArray pare x y >> A.writeArray size y (sx + sy)\n GT -> A.writeArray pare y x >> A.writeArray size x (sx + sy)\n EQ -> do\n A.writeArray pare y x >> A.writeArray size x (sx + sy)\n A.writeArray rank x (rx + 1)\n\nrun n nr ag rs = ST.runST $ do\n xn <- ST.newSTRef (0 :: I.Int64)\n xsum <- ST.newSTRef (0 :: I.Int64)\n xsumsq <- ST.newSTRef (0 :: I.Int64)\n dsu@(DSU _ _ size) <- create n\n (((-1) -) . snd . maximum -> r) <- M.forM [1..nr] $ \\i -> do\n M.forM_ (ag A.! i) $ \\j -> do\n ST.modifySTRef xn succ\n ST.modifySTRef xsum succ\n ST.modifySTRef xsumsq succ\n A.writeArray size j 1\n M.forM_ (ag A.! i) $ \\j -> do\n if j /= 1 then do\n (fromIntegral -> sjp) <- find dsu (j - 1) >>= A.readArray size\n (fromIntegral -> sjq) <- find dsu j >>= A.readArray size\n if sjp /= 0 then do\n ST.modifySTRef xn pred\n ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))\n union dsu (j - 1) j\n else return ()\n else return ()\n if j /= n then do\n (fromIntegral -> sjp) <- find dsu j >>= A.readArray size\n (fromIntegral -> sjq) <- find dsu (j + 1) >>= A.readArray size\n if sjq /= 0 then do\n ST.modifySTRef xn pred\n ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))\n union dsu j (j + 1)\n else return ()\n else return ()\n xnv <- ST.readSTRef xn\n xsumv <- ST.readSTRef xsum\n xsumsqv <- ST.readSTRef xsumsq\n return (if xsumsqv * xnv - xsumv * xsumv == 0 then xnv else 0, -i)\n return $ rs !! r + 1\n\nmain = do\n (readInt -> n) <- B.getLine\n (L.sort . (flip zip) [1..] . map readInt . C.words -> xs) <- B.getLine\n let rs = S.toList . S.fromList . map fst $ xs\n nr = length rs\n gs = (\\(_, _, x) -> reverse x) $ L.foldl' (\\(i, p, rs) (x, y) -> if p == x then (i, p, (i, y):rs)\n else (i + 1, x, (i + 1, y):rs)) (0, 0, []) xs\n ag = A.accumArray (flip (:)) [] (1, nr) gs :: A.Array Int [Int]\n print $ run n nr ag rs\n"}], "negative_code": [], "src_uid": "b3d093272fcb289108fe45be8c72f38e"} {"source_code": "mergeStr :: String -> String -> String\nmergeStr a b\n | a < b = a ++ b\n | otherwise = b ++ a\n\nstrSort :: String -> String\nstrSort [x] = [x]\nstrSort x\n | odd len = x\n | otherwise = mergeStr (strSort l) (strSort r)\n where\n len = length x\n l = take mid x\n r = drop mid x\n mid = len `div` 2\n\nmain :: IO()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $\n if strSort a == strSort b\n then \"YES\"\n else \"NO\"\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nreduce :: ByteString -> ByteString\nreduce a = loop 0 (B.length a)\n where\n loop i j\n | odd (j - i) = C.take (j - i) $ C.drop i a\n | a1 < a2 = B.concat [a1, a2]\n | otherwise = B.concat [a2, a1]\n where\n a1 = loop i k\n a2 = loop k j\n k = (i + j) `div` 2\n\nmain = do\n a <- B.init <$> B.getLine\n b <- B.init <$> B.getLine\n putStrLn $ if reduce a == reduce b then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Arrow\n\nsort str\n | odd l = str\n | a < b = a ++ b\n | True = b ++ a\n where l = length str\n (a,b) = (sort *** sort) $ splitAt (l`quot`2) str\n\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $\n if\n sort a == sort b\n then\n \"YES\"\n else\n \"NO\""}, {"source_code": "module Main(main) where\n\nnorm :: String -> String\nnorm str\n\t| (length str) `mod` 2 == 1 = str\n\t| otherwise = let\n\t\t\tl = (length $ str) `quot` 2\n\t\t\ta = norm $ take l str\n\t\t\tb = norm $ drop l str\n\t\tin if a String\nsmallest str \n | mod (length str) 2 == 1 = str\n | otherwise = if (str1 < str2) then (str1 ++ str2) else (str2 ++ str1) where\n str1 = smallest (take (div (length str) 2) str)\n str2 = smallest (drop (div (length str) 2) str)\n \n"}, {"source_code": "data Tree = Node { left :: Tree,\n s :: String,\n right :: Tree}\n | Nil deriving (Eq, Show)\n\nsolve :: String -> String\nconstruct :: String -> Tree\nreify :: Tree -> Tree\neq :: Tree -> Tree -> Bool\n\nmain = interact solve\n\nsolve str = let\n lns = lines str\n s = lns !! 0\n t = lns !! 1\n in\n if (eq (reify $ construct s) (reify $ construct t)) then \"YES\" else \"NO\"\n\nconstruct str = if (length str) `mod` 2 == 1 then Node Nil str Nil else\n let\n half = (length str) `div` 2\n left = take half str\n right = drop half str\n in\n Node (construct left) str (construct right)\n\nreify Nil = Nil\nreify (Node l st r) =\n if l == Nil then Node l st r else\n let\n lef = reify l\n righ = reify r\n in\n if (s lef) < (s righ) then (Node lef ((s lef) ++ (s righ)) righ)\n else Node righ ((s righ) ++ (s lef)) lef\n\neq Nil Nil = True\neq Nil _ = False\neq _ Nil = False\neq (Node ll ls lr) (Node rl rs rr) =\n if ll == Nil then ls == rs else (eq ll rl) && (eq lr rr)\n\nshow :: Tree -> String\nshow Nil = \"nil\"\nshow (Node l s r) =\n Main.show l ++ \" \" ++ s ++ \" \" ++ Main.show r\n"}, {"source_code": "\nmain = do\n\ta <- getLine\n\tb <- getLine\n\tputStrLn $ solve a b\n\nsolve a b = let ln = length a in fromBool $ (eq ln a) == (eq ln b)\n\twhere\n\teq len str\n\t\t | len `rem` 2 == 1 \t= str\n\t\t | left < right \t= left ++ right\n\t\t | otherwise\t\t= right ++ left\n\t\t where\n\t\t half = len `div` 2\n\t\t (left,right) = both (eq half) $ splitAt half str\n\nboth f (a,b) = (f a, f b)\nfromBool True = \"YES\"\nfromBool False = \"NO\"\n\n\t\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n t <- getLine\n\n let\n f :: String -> String\n f [] = []\n f [a] = [a]\n f s\n | odd n = s\n | s1' < s2' = s1'++s2'\n | otherwise = s2'++s1'\n where\n n = length s\n (s1, s2) = splitAt (n `div` 2) s\n s1' = f s1\n s2' = f s2\n\n putStrLn $ if f s == f t then \"YES\" else \"NO\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n t <- getLine\n\n let\n f :: String -> String\n f [] = []\n f [a] = [a]\n f s = if s1' < s2' then s1'++s2' else s2'++s1'\n where\n n = length s\n (s1, s2) = splitAt (n `div` 2) s\n s1' = f s1\n s2' = f s2\n\n putStrLn $ if f s == f t then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nreduce :: ByteString -> ByteString\nreduce a = loop 0 (B.length a)\n where\n loop i j\n | odd (j - i) = C.take (j - i) $ C.drop i a\n | a1 < a2 = B.concat [a1, a2]\n | otherwise = B.concat [a2, a1]\n where\n a1 = loop i k\n a2 = loop k j\n k = (i + j) `div` 2\n\nmain = do\n a <- B.getLine\n b <- B.getLine\n putStrLn $ if reduce a == reduce b then \"YES\" else \"NO\"\n"}, {"source_code": "mergeStr :: String -> String -> String\nmergeStr a b\n | a < b = a ++ b\n | otherwise = b ++ a\n\nstrSort :: String -> String\nstrSort [x] = [x]\nstrSort x = mergeStr (strSort l) (strSort r)\n where\n l = take midlen x\n r = drop midlen x\n midlen = length x `div` 2\n\nmain :: IO()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $\n if strSort a == strSort b\n then \"YES\"\n else \"NO\"\n"}], "src_uid": "21c0e12347d8be7dd19cb9f43a31be85"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.List (genericLength, sort, foldl1')\nimport Data.Ratio\nimport Text.Printf\n\ntype Ps = [(Int,Integer)]\n\nmerge::[Ps]->Ps\nmerge = foldl1' go where\n go xs [] = xs\n go [] ys = ys\n go xs'@((x, a):xs) ys'@((y, b):ys) = case compare x y of\n LT -> (x, a) : go xs ys'\n GT -> (y, b) : go xs' ys\n EQ -> (x, a + b): go xs ys\n\n\ndiffs::[Int]->Ps\ndiffs = merge . go . sort where\n go [] = []\n go (x: xs) = map (sub x) xs : go xs\n sub x y = (y - x, 1)\n\n\nsumms2::Ps->Ps\nsumms2 xs = merge $ map (flip map xs . sumtup) xs where\n sumtup (a1, b1) (a2, b2) = (a1 + a2, b1 * b2)\n\ncount::[Int]->Double\ncount xs = fromRational $ marked % (cmb ^ (3::Int)) where\n n = genericLength xs\n cmb = n * (n - 1) `div` 2\n marked = go 0 0 sums difs\n difs = diffs xs\n sums = summs2 difs\n go _ total _ [] = total\n go acc total [] ds = total + acc * sum (map snd ds)\n go acc total ss'@((s,sc) :ss) ds'@((d, dc):ds)\n | s < d = go (acc + sc) total ss ds'\n | otherwise = go acc (total + dc * acc) ss' ds\n\nmain::IO ()\nmain = getLine >> getLine >>= printf \"%.10f\" . count . map read .words\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Data.List (genericLength, sort, foldl1')\nimport Data.Ratio\nimport Text.Printf\n\ntype Ps = [Pair]\ndata Pair = Pair {-# UNPACK #-} !Int {-# UNPACK #-} !Integer\n\nmerge::[Ps]->Ps\nmerge = foldl1' go where\n go xs [] = xs\n go [] ys = ys\n go xs'@(Pair x a:xs) ys'@(Pair y b:ys) = case compare x y of\n LT -> Pair x a : go xs ys'\n GT -> Pair y b : go xs' ys\n EQ -> Pair x (a + b): go xs ys\n\n\ndiffs::[Int]->Ps\ndiffs = merge . go . sort where\n go [] = []\n go (x: xs) = map (sub x) xs : go xs\n sub x y = Pair (y - x) 1\n\n\nsumms2::Ps->Ps\nsumms2 xs = merge $ map (flip map xs . sumtup) xs where\n sumtup (Pair a1 b1) (Pair a2 b2) = Pair (a1 + a2) (b1 * b2)\n\ncount::[Int]->Double\ncount xs = fromRational $ marked % (cmb ^ (3::Int)) where\n n = genericLength xs\n cmb = n * (n - 1) `div` 2\n marked = go 0 0 sums difs\n difs = diffs xs\n sums = summs2 difs\n psnd (Pair _ x) = x\n go _ total _ [] = total\n go acc total [] ds = total + acc * sum (map psnd ds)\n go acc total ss'@(Pair s sc :ss) ds'@(Pair d dc:ds)\n | s < d = go (acc + sc) total ss ds'\n | otherwise = go acc (total + dc * acc) ss' ds\n\nmain::IO ()\nmain = getLine >> getLine >>= printf \"%.10f\" . count . map read .words\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow\nimport Control.Monad\nimport Data.List (genericLength)\nimport qualified Data.Map as Map\nimport Data.Ratio\nimport Text.Printf\n\ncomb2::[a]->[(a,a)]\ncomb2 [] = []\ncomb2 (x:xs) = map (x, ) xs ++ comb2 xs\n\ntype Ps a = [(a,a)]\n\ncollect::(Num a, Ord a)=>Ps a->Ps a\ncollect = Map.toAscList . Map.fromListWith (+)\n\ndiffs::(Num a, Ord a)=>[a]->Ps a\ndiffs = collect . map ((,1) . uncurry subtract). comb2\n\nsumms2::(Num a, Ord a)=>Ps a->Ps a\nsumms2 = collect . uncurry (liftM2 sumtup) . (id &&& id) where\n sumtup (a1, b1) (a2, b2) = (a1 + a2, b1 + b2)\n\ncount::[Integer]->Double\ncount xs = fromRational $ marked % (cmb ^ (3::Int)) / 2 where\n n = genericLength xs\n cmb = n * (n - 1) `div` 2\n marked = go 0 0 sums difs\n difs = diffs xs\n sums = summs2 difs\n go _ total _ [] = total\n go acc total [] ds = (total +). sum . map ((* acc) .snd) $ ds\n go acc total ss'@((s,sc) :ss) ds'@((d, dc):ds)\n | s < d = go (acc + sc) total ss ds'\n | otherwise = go acc (total + dc * acc) ss' ds\n\nmain::IO ()\nmain = getLine >> getLine >>= printf \"%.10f\" . count . map read .words\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow\nimport Control.Monad\nimport Data.List (genericLength, sort)\nimport qualified Data.IntMap.Strict as Map\nimport Data.Ratio\nimport Text.Printf\n\ncomb2::[a]->[(a,a)]\ncomb2 [] = []\ncomb2 (x:xs) = map (x, ) xs ++ comb2 xs\n\ntype Ps = [(Int,Int)]\n\ncollect::Ps->Ps\ncollect = Map.toAscList . Map.fromListWith (+)\n\ndiffs::[Int]->Ps\ndiffs = collect . map ((,1) . uncurry subtract). comb2. sort\n\nsumms2::Ps->Ps\nsumms2 = collect . uncurry (liftM2 sumtup) . (id &&& id) where\n sumtup (a1, b1) (a2, b2) = (a1 + a2, b1 * b2)\n\nconvRatio::(Integral a, Integral b) => Ratio a->Ratio b\nconvRatio n =fromIntegral (numerator n) % fromIntegral (denominator n)\n\ncount::[Int]->Double\ncount xs = fromRational $ convRatio $ marked % (cmb ^ (3::Int)) where\n n = genericLength xs\n cmb = n * (n - 1) `div` 2\n marked = go 0 0 sums difs\n difs = diffs xs\n sums = summs2 difs\n go _ total _ [] = total\n go acc total [] ds = total + fromIntegral acc * sum (map snd ds)\n go acc total ss'@((s,sc) :ss) ds'@((d, dc):ds)\n | s < d = go (acc + sc) total ss ds'\n | otherwise = go acc (total + dc * fromIntegral acc) ss' ds\n\nmain::IO ()\nmain = getLine >> getLine >>= printf \"%.10f\" . count . map read .words\n"}], "src_uid": "9d55b98c75e703a554051d3088a68e59"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n [n,t] <- map readInt . words <$> getLine\n bs <- take n . unfoldr (runStateT $ (,) <$> rInt <*> rInt)\n <$> BSL.getContents\n let arr = (`zip` [1..])\n $ map (\\(s,d) -> if s >= t then s else s + d * div (t - s + d - 1) d)\n $ bs\n print $ snd $ minimum $ arr\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "--\nmain = interact $ show.helper.(map read).words\n\nhelper (b:t:xs) =minin 1 1 1000000 $ f xs\n where f [] = []\n f (x:y:ar) = (head $ filter (>=t) [x, x + y..]):(f ar)\n\n\n\nminin res i m [] = res\nminin res i m (x:xs) = if x < m then minin i (i+1) x xs else minin res (i+1) m xs"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f t) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tl <- replicateM n $ fmap ((map read).words) getLine\n\tputStrLn $ show $ solve n t l\n\n\n\t\n\t"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tl <- replicateM n $ fmap ((map read).words) getLine\n\tputStrLn $ show $ solve n t l\n\t\n\t"}, {"source_code": "form :: String -> [[Int]]\nform s = map (map read) $ (map words) $ lines $ s\nsolve :: [[Int]] -> Int\nsolve ([n,t]:xs) =1+ (snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (ceiling $ intdiv (t-s) d)*d+s\n \nintdiv :: Fractional a => Int -> Int -> a\nintdiv a b = (fromIntegral a)/(fromIntegral b)\n\nmain = interact $ show.solve.form"}, {"source_code": "form :: String -> [[Int]]\nform s = map (map read) $ (map words) $ lines $ s\nsolve :: [[Int]] -> Int\nsolve ([n,t]:xs) =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (ceiling $ intdiv (t-s) d)*d+s\n \nintdiv :: Fractional a => Int -> Int -> a\nintdiv a b = (fromIntegral a)/(fromIntegral b)\n\nmain = interact $ show.solve.form"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tif n ==90 \n\tthen do \n\t\tl <- replicateM n $ fmap ((map read).words) getLine\n\t\tputStrLn $ show $ solve n t l\n\telse interact id\n\t\n\t"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tif n /=90 \n\tthen (do \n\t\tl <- replicateM n $ fmap ((map read).words) getLine\n\t\tputStrLn $ show $ solve n t l)\n\telse (\n\t\tinteract id)\n\t\n\t"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tif n /=90 \n\tthen (do \n\t\tl <- replicateM n $ fmap ((map read).words) getLine\n\t\tputStrLn $ show $ solve n t l)\n\telse (\n\t\tinteract soos)\n\nsoos :: String -> String \nsoos s =unlines $ (drop 76) $ lines s\n\t\n\t"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 = a `div` b\n\t| otherwise = a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tl <- replicateM n $ fmap ((map read).words) getLine\n\tputStrLn $ show $ solve n t l\n\t\n\t"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tif n ==90 \n\tthen do \n\t\tl <- replicateM n $ fmap ((map read).words) getLine\n\t\tputStrLn $ show $ solve n t l\n\telse \n\t\tinteract id\n\t\n\t"}, {"source_code": "import Control.Monad\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (intdivceil (t-s) d)*d+s\n \n{-\nintdiv :: Fractional a => Int -> Int -> a \nintdiv a b = (fromIntegral a)/(fromIntegral b)-}\nintdivceil a b\n\t| a `mod` b == 0 =max 0 $ a `div` b\n\t| otherwise =max 0 $ a `div` b +1\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tif n /=90 \n\tthen (do \n\t\tl <- replicateM n $ fmap ((map read).words) getLine\n\t\tputStrLn $ show $ solve n t l)\n\telse (\n\t\tinteract soos)\n\nsoos :: String -> String \nsoos s =unlines $ (drop 38) $ lines s\n\t\n\t"}, {"source_code": "import Control.Monad\n\nform :: String -> [[Int]]\nform s = map (map read) $ (map words) $ lines $ s\n\n\nsolve :: Int->Int->[[Int]] -> Int\nsolve n t xs =(snd $ foldl (f n) (0,0) $ zip xs [1..])\n\nf :: Int -> ((Int,Int) -> ([Int],Int) ->(Int,Int))\nf t acc ([s,d],index) \n |fst acc ==0 = (h,index)\n |otherwise = \n if (fst acc)>h\n then (h,index)\n else acc\n where\n h = (ceiling $ intdiv (t-s) d)*d+s\n \nintdiv :: Fractional a => Int -> Int -> a\nintdiv a b = (fromIntegral a)/(fromIntegral b)\n\nmain = do\n\t[n,t] <- fmap ((map read).words) getLine\n\tl <- replicateM n $ fmap ((map read).words) getLine\n\tputStrLn $ show $ solve n t l\n\t\n\t"}], "src_uid": "71be4cccd3b8c494ad7cc2d8a00cf5ed"} {"source_code": "import Control.Monad (replicateM_)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Char (ord)\nimport Data.Ratio (denominator, numerator)\n\nparseInt = foldl (\\acc c -> acc * 10 + toInteger (ord c) - 48) 0\n\nparseInts = fmap parseInt . words\n\nmm = 10 ^ 9 + 7 :: Integer\n\nnewtype FiniteField =\n FiniteField Integer\n\ninstance Show FiniteField where\n show (FiniteField a) = show a\n\ninstance Num FiniteField where\n (+) (FiniteField a) (FiniteField b) =\n FiniteField\n (if a + b >= mm\n then a + b - mm\n else a + b)\n (*) (FiniteField a) (FiniteField b) = FiniteField ((a * b) `mod` mm)\n fromInteger = FiniteField . norm\n where\n norm = (`mod` mm) . (+ mm) . (`mod` mm)\n negate (FiniteField a) =\n FiniteField\n (if a == 0\n then 0\n else mm - a)\n abs = id\n signum _ = 1\n\ninstance Fractional FiniteField where\n recip (FiniteField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (FiniteField q) * recip (FiniteField r)\n where\n (q, r) = mm `divMod` a\n fromRational f = fromInteger (numerator f) / fromInteger (denominator f)\n\nprob :: Integer -> State (Integer, Integer, FiniteField, FiniteField) FiniteField\nprob ti = do\n (n, m, prefix, last) <- get\n let n' = n + 1\n m' = m - ti\n if m' < 0\n then do\n put (n', m', 0, 0)\n return 0\n else if m' >= n'\n then do\n put (n', m', 1, last / 2)\n return 1\n else do\n let prefix' =\n if m > n\n then prefix\n else prefix - last / 2\n last' =\n if m > n\n then last / 2\n else last / 2 * fromInteger n' / fromInteger (n' - m)\n remove k (prefix, last) =\n (prefix - last, last / fromInteger (n' - k + 1) * fromInteger k)\n (prefix'', last'') =\n foldr remove (prefix', last') [m' + 1 .. minimum [m, n']]\n put (n', m', prefix'', last'')\n return prefix''\n\nmain = do\n [n, s] <- fmap parseInts getLine\n t <- fmap parseInts getLine\n print . sum . evalState (mapM prob t) $ (0, s, 1, 1)\n", "positive_code": [{"source_code": "{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n\nimport Control.Monad (replicateM_)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Char (ord)\nimport Data.Ratio (denominator, numerator)\nimport GHC.TypeNats\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + toInteger (ord c) - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational f = fromInteger (numerator f) / fromInteger (denominator f)\n\ntype MField = PrimeField (10 ^ 9 + 7)\n\nprob :: Integer -> State (Integer, Integer, MField, MField) MField\nprob ti = do\n (n, m, prefix, last) <- get\n let n' = n + 1\n m' = m - ti\n if m' < 0\n then do\n put (n', m', 0, 0)\n return 0\n else if m' >= n'\n then do\n put (n', m', 1, last / 2)\n return 1\n else do\n let prefix' =\n if m > n\n then prefix\n else prefix - last / 2\n last' =\n if m > n\n then last / 2\n else last / 2 * fromInteger n' / fromInteger (n' - m)\n remove k (prefix, last) =\n ( prefix - last\n , last / fromInteger (n' - k + 1) * fromInteger k)\n (prefix'', last'') =\n foldr remove (prefix', last') [m' + 1 .. minimum [m, n']]\n put (n', m', prefix'', last'')\n return prefix''\n\nmain = do\n [n, s] <- fmap parseInts getLine\n t <- fmap parseInts getLine\n print . sum . evalState (mapM prob t) $ (0, s, 1, 1)\n"}, {"source_code": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n\nimport Control.Monad (replicateM_)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Char (ord)\nimport Data.Ratio (denominator, numerator)\nimport GHC.TypeNats\n\nparseInt = foldl (\\acc c -> acc * 10 + toInteger (ord c) - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype FiniteField (p :: Nat) = FiniteField Integer deriving (Eq)\n\nchar :: KnownNat p => FiniteField p -> Integer\nchar = toInteger . natVal\n\ninstance KnownNat p => Show (FiniteField p) where\n show (FiniteField a) = show a\n\ninstance KnownNat p => Num (FiniteField p) where\n (+) x@(FiniteField a) (FiniteField b) =\n FiniteField\n (if a + b >= mm\n then a + b - mm\n else a + b)\n where\n mm = char x\n (*) x@(FiniteField a) (FiniteField b) = FiniteField ((a * b) `mod` mm)\n where\n mm = char x\n fromInteger a = ret\n where\n mm = char ret\n ret = FiniteField . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(FiniteField a) =\n FiniteField\n (if a == 0\n then 0\n else mm - a)\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (FiniteField p) where\n recip x@(FiniteField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (FiniteField q) * recip (FiniteField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational f = fromInteger (numerator f) / fromInteger (denominator f)\n\ntype MField = FiniteField (10 ^ 9 + 7)\n\nprob :: Integer -> State (Integer, Integer, MField, MField) MField\nprob ti = do\n (n, m, prefix, last) <- get\n let n' = n + 1\n m' = m - ti\n if m' < 0\n then do\n put (n', m', 0, 0)\n return 0\n else if m' >= n'\n then do\n put (n', m', 1, last / 2)\n return 1\n else do\n let prefix' =\n if m > n\n then prefix\n else prefix - last / 2\n last' =\n if m > n\n then last / 2\n else last / 2 * fromInteger n' / fromInteger (n' - m)\n remove k (prefix, last) =\n (prefix - last, last / fromInteger (n' - k + 1) * fromInteger k)\n (prefix'', last'') =\n foldr remove (prefix', last') [m' + 1 .. minimum [m, n']]\n put (n', m', prefix'', last'')\n return prefix''\n\nmain = do\n [n, s] <- fmap parseInts getLine\n t <- fmap parseInts getLine\n print . sum . evalState (mapM prob t) $ (0, s, 1, 1)\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Char (ord)\nimport Data.Ratio (denominator, numerator)\n\nparseInt = toInteger . foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nmm = 10 ^ 9 + 7 :: Integer\n\nnewtype FiniteField =\n FiniteField Integer\n\ninstance Show FiniteField where\n show (FiniteField a) = show a\n\ninstance Num FiniteField where\n (+) (FiniteField a) (FiniteField b) =\n FiniteField\n (if a + b >= mm\n then a + b - mm\n else a + b)\n (*) (FiniteField a) (FiniteField b) = FiniteField ((a * b) `mod` mm)\n fromInteger = FiniteField . norm\n where\n norm = (`mod` mm) . (+ mm) . (`mod` mm)\n negate (FiniteField a) =\n FiniteField\n (if a == 0\n then 0\n else mm - a)\n abs = id\n signum _ = 1\n\ninstance Fractional FiniteField where\n recip (FiniteField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (FiniteField q) * recip (FiniteField r)\n where\n (q, r) = mm `divMod` a\n fromRational f = fromInteger (numerator f) / fromInteger (denominator f)\n\nprob :: Integer -> State (Integer, Integer, FiniteField, FiniteField) FiniteField\nprob ti = do\n (n, m, prefix, last) <- get\n let n' = n + 1\n m' = m - ti\n if m' < 0\n then do\n put (n', m', 0, 0)\n return 0\n else if m' >= n'\n then do\n put (n', m', 1, last / 2)\n return 1\n else do\n let prefix' =\n if m > n\n then prefix\n else prefix - last / 2\n last' =\n if m > n\n then last / 2\n else last / 2 * fromInteger n' / fromInteger (n' - m)\n remove k (prefix, last) =\n (prefix - last, last / fromInteger (n' - k + 1) * fromInteger k)\n (prefix'', last'') =\n foldr remove (prefix', last') [m' + 1 .. minimum [m, n']]\n put (n', m', prefix'', last'')\n return prefix''\n\nmain = do\n [n, s] <- fmap parseInts getLine\n t <- fmap parseInts getLine\n print . sum . evalState (mapM prob t) $ (0, s, 1, 1)\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Char (ord)\nimport Data.Ratio (denominator, numerator)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nmm = 10 ^ 9 + 7 :: Int\n\nnewtype FiniteField =\n FiniteField Int\n\ninstance Show FiniteField where\n show (FiniteField a) = show a\n\ninstance Num FiniteField where\n (+) (FiniteField a) (FiniteField b) =\n FiniteField\n (if a + b >= mm\n then a + b - mm\n else a + b)\n (*) (FiniteField a) (FiniteField b) = FiniteField ((a * b) `mod` mm)\n fromInteger = FiniteField . fromInteger . norm\n where\n norm = (`mod` mm') . (+ mm') . (`mod` mm')\n where\n mm' = toInteger mm\n negate (FiniteField a) =\n FiniteField\n (if a == 0\n then 0\n else mm - a)\n abs = id\n signum _ = 1\n\ninstance Fractional FiniteField where\n recip (FiniteField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (FiniteField q) * recip (FiniteField r)\n where\n (q, r) = mm `divMod` a\n fromRational f = fromInteger (numerator f) / fromInteger (denominator f)\n\nfromInt = fromInteger . toInteger\n\nprob :: Int -> State (Int, Int, FiniteField, FiniteField) FiniteField\nprob ti = do\n (n, m, prefix, last) <- get\n let n' = n + 1\n m' = m - ti\n if m' < 0\n then do\n put (n', m', 0, 0)\n return 0\n else if m' >= n'\n then do\n put (n', m', 1, last / 2)\n return 1\n else do\n let prefix' =\n if m > n\n then prefix\n else prefix - last / 2\n last' =\n if m > n\n then last / 2\n else last / 2 * fromInt n' / fromInt (n' - m)\n remove k (prefix, last) =\n (prefix - last, last / fromInt (n' - k + 1) * fromInt k)\n (prefix'', last'') =\n foldr remove (prefix', last') [m' + 1 .. minimum [m, n']]\n put (n', m', prefix'', last'')\n return prefix''\n\nmain = do\n [n, s] <- fmap parseInts getLine\n t <- fmap parseInts getLine\n print . sum . evalState (mapM prob t) $ (0, s, 1, 1)\n"}], "src_uid": "a44cba5685500b16e24b8fba30451bc5"} {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine\r\n\r\nfindSmallest :: (Int, Int) -> [Int] -> [Int]\r\nfindSmallest (_, ops) [x] = [x + ops]\r\nfindSmallest (0, ops) (x : xs) = x : findSmallest (0, ops) xs\r\nfindSmallest (k, ops) (x : xs) = x' : findSmallest (k', ops') xs where\r\n (x', k', ops') = if k > x then (0, k - x, ops + x) else (x - k, 0, ops + k)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readInts\r\n ans <- findSmallest (k, 0) <$> readInts\r\n putStrLn $ unwords $ map show ans\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t solve", "positive_code": [{"source_code": "import Control.Monad(replicateM)\r\n\r\nmain = getLine >>= (flip replicateM) runTest . read\r\n\r\nrunTest :: IO ()\r\nrunTest = do \r\n\tl <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n\ta <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n\tputStrLn $ foldr (\\i s -> show i ++ \" \" ++ s) \"\" (result (l!!1) a)\r\n\r\nresult k [] = []\r\nresult k [x] = [x]\r\nresult 0 list = list\r\nresult k (0:xs) = 0 : result k xs\r\nresult k (x:xs) = (max 0 $ x-k) : result (max 0 $ k-x) (init xs ++ [last xs + (min x k)])\r\n"}], "negative_code": [], "src_uid": "6854ad3597f9f41d475aacb774b823ed"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.List as L (intercalate)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun i (x:xs) d | x == 0 = run 1 xs (0:d)\n | otherwise = run (i + 1) xs (i:d)\nrun _ [] d = d\n\nmain = do\n (readInt -> n) <- B.getLine\n (map readInt . C.words -> xs) <- B.getLine\n putStrLn $ L.intercalate \" \" $ map show $ zipWith min (reverse (run n xs [])) (run n (reverse xs) [])\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n B.putStr $ B.unwords $ map (B.pack . show) $ solve n xs\n\nsolve n xs = snd $ mapAccumL (\\is i -> case is of { [i0] -> (is, abs $ i - i0); (i0:i1:_) -> if abs (i - i0) > abs (i - i1) then (tail is, abs (i - i1)) else (is, abs (i - i0)) } ) (map fst $ filter ((== 0) . snd) $ zip [1..] xs) [1..n]\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Control.Applicative\n\ninf = 1000000\n\nf p x = if x == 0 then 0 else p + 1\n\nmain = do\n n <- read <$> getLine :: IO Int\n a <- map read . words <$> getLine :: IO [Int]\n let ans = zipWith min (tail $ scanl f inf a) (scanr (flip f) inf a)\n putStrLn $ unwords $ map show ans\n return ()"}], "negative_code": [], "src_uid": "2031f2ac5652609fda77830e93ffcc2c"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Maybe\n\n\nprocess s | take 2 s == \"op\" = \"FILIPINO\"\n\t | take 4 s == \"used\" = \"JAPANESE\"\n\t | take 4 s ==\"usam\" = \"JAPANESE\"\n\t | otherwise = \"KOREAN\"\n\n\nmain = do\n\t\tgetLine\n\t\ts<-map reverse <$> lines <$> getContents\n\t\tmapM_ putStrLn $ map process s\n", "positive_code": [{"source_code": "import Control.Monad\n\ndecide :: String -> String\ndecide s\n |l=='o' = \"FILIPINO\"\n |l=='a' = \"KOREAN\"\n |otherwise = \"JAPANESE\"\n where l = last s\n\nroutine :: IO ()\nroutine = do\n n <- getLine\n putStrLn $ decide n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "--ghc 7.10\n\ndata Language = UNKNOWN | FILIPINO | JAPANESE | KOREAN deriving (Show)\n\ndetectLanguage :: String -> Language\ndetectLanguage \"po\" = FILIPINO\ndetectLanguage \"desu\" = JAPANESE\ndetectLanguage \"masu\" = JAPANESE\ndetectLanguage \"mnida\" = KOREAN\ndetectLanguage (x:xs) = detectLanguage xs\ndetectLanguage _ = UNKNOWN\n\ndetectLanguages :: [String] -> [Language]\ndetectLanguages = map detectLanguage\n\nmain = do\n tStr <- getLine\n contents <- getContents\n let languages = words contents\n sequence . map print . detectLanguages $ languages\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n \ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n s <- getLine\n putStrLn $ solve s\n where solve s\n | \"po\" `isSuffixOf` s = \"FILIPINO\"\n | or [\"desu\" `isSuffixOf` s, \"masu\" `isSuffixOf` s] = \"JAPANESE\"\n | otherwise = \"KOREAN\""}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n s <- getLine\n putStrLn $ f s\n\nf s | c == 'o' = \"FILIPINO\"\n | c == 'u' = \"JAPANESE\"\n | c == 'a' = \"KOREAN\"\n where\n c = last s\n"}], "negative_code": [], "src_uid": "816907d873bce3573ce1e5ae3f494768"} {"source_code": "\n\nsolve :: Int -> Int\nsolve n = 2 ^ (n `div` 2 + 1) - 2\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . read) . tail . lines\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\ncount :: (Eq a) => a -> [a] -> Int\ncount x = length . filter (== x)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n let a = take n $ iterate (*2) 2\n rev_a = reverse a\n print $ abs\n $ (head rev_a + (sum $ take (n `div` 2 - 1) a))\n - sum (drop (n `div` 2 - 1) . take (n - 1) $ a)"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n print $\n sum\n [ if div n 2 <= i && i < n\n then -(2 ^ i)\n else 2 ^ i\n | i <- [1 .. n]\n ]"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do \n n <- readLn\n print $ (2^((n `div` 2)+1)) - 2"}, {"source_code": "solve :: Int -> Int\nsolve n = \n f - s\n where\n f = 2^n + sum [2^k | k <- [1 .. (div n 2 - 1)]]\n s = sum [2^k | k <- [div n 2 .. n - 1]]\n\n\nhandle_tests :: Int -> IO()\nhandle_tests 0 = do return ()\nhandle_tests t = do\n n <- getLine \n print . solve . read $ n\n handle_tests $ t - 1\n\n\nmain = do\n t <- getLine\n handle_tests (read t)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess a= do\n\t\tlet s = 2^(a+1)-2\n\t\tlet s1 = 2^a +2^(div a 2)-2\n\t\tlet s2 = s-s1\n\t\tprint $ abs (s1-s2)\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\ta<-map read <$> replicateM n getLine ::IO [Int]\n\t\tmapM_ process a\n\n"}, {"source_code": "\nmain = interact $ unlines . map (show . solveFast . read) . tail . lines\n\n\nsolveFast :: Int->Int\nsolveFast x =(2^(x+1)-2)-2*(\n sum $\n take (x `div` 2) $\n drop 1 $\n cycle $\n reverse [2^n | n<-[1..x]])\n"}, {"source_code": "process :: Int -> Int\nprocess n = 2 ^ (n`div`2 + 1) - 2\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n xs <- fmap (map readInt.words) getContents\n mapM_ print $ map process $ xs"}, {"source_code": "solution :: Integer -> Integer\nsolution n = (last numbers) + sum (take m numbers) - (sum $ drop m $ init numbers)\n where numbers = [2^i | i <- [1..n]]\n m = fromIntegral (div n 2) - 1\n\nparser :: [String]-> [String]\nparser rawNumbers = map show $ map solution numbers\n where (cases:numbers) = map read rawNumbers\n\nmain :: IO ()\nmain = interact (unlines . parser . lines)\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess a= do\n\t\tlet x = zip [2^i| i<-[1..a]] (cycle [1,2,2,1])\n\t\tlet s = sum [2^i|i<-[1..a]]\t\n\t\tlet s1 = sum $ map fst $ filter (\\z-> snd z==1) x\n\t\tlet s2 = s-s1\n\t\tprint $ abs $ s1-s2\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\ta<-map read <$> replicateM n getLine ::IO [Int]\n\t\tmapM_ process a\n\n"}, {"source_code": "\nmain = interact $ unlines . map (show . solveFast . read) . lines\n\n\nsolveFast :: Int->Int\nsolveFast x =(2^(x+1)-2)-2*(\n sum $\n take (x `div` 2) $\n drop 1 $\n cycle $\n reverse [2^n | n<-[1..x]])\n"}], "src_uid": "787a45f427c2db98b2ddb78925e0e0f1"} {"source_code": "{-# LANGUAGE NPlusKPatterns #-}\n\nmodule Main where\n\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n [n, x] <- getIntegers\n cs <- getIntegers\n print $ solve cs x\n\n\ngetIntegers :: IO [Integer]\ngetIntegers = do\n txt <- getLine -- String\n let ws = words txt -- [String]\n return $ fmap read ws -- [Integer]\n\ncountDown 1 = 1 : countDown 1\ncountDown (n + 1) = (n + 1) : countDown n\n\ndot :: [Integer] -> [Integer] -> Integer\ndot u v = dot' u v 0\n\ndot' :: [Integer] -> [Integer] -> Integer -> Integer\ndot' [] _ x = x\ndot' _ [] x = x\ndot' (a : as) (b : bs) x = dot' as bs (x + a * b)\n\nsolve :: [Integer] -> Integer -> Integer\nsolve cs x = sort cs `dot` countDown x\n\nsortDecr :: Ord a => [a] -> [a]\nsortDecr = reverse . sort\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Integer] -> Integer\nsolve (n:x:c) = solve' (sort c) x\n where\n solve' :: [Integer] -> Integer -> Integer\n solve' [] _ = 0\n solve' (c:cs) x = x * c + (solve' cs (max 1 (x - 1)))\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x c = sum $ zipWith (*) (map (max 1) [x, x-1 ..]) (sort c)\n\nmain :: IO ()\nmain = do\n [n, x] <- map fromIntegral <$> getInts\n c <- map fromIntegral <$> getInts\n print $ solve x c\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List (sort, insertBy)\nimport Data.Maybe (mapMaybe)\nimport Data.Monoid\nimport Debug.Trace\n\nreadInt64s :: B.ByteString -> [Int64]\nreadInt64s = map (fromIntegral . fst) . mapMaybe B.readInt . B.words\n\ngetInt64s :: IO [Int64]\ngetInt64s = readInt64s <$> B.getLine\n\nmain = do\n [_, x] <- getInt64s\n cs <- getInt64s\n let\n f c g t = c * t + g (max 1 (t-1))\n in print $ foldr f (const 0) (sort cs) x\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Integer] -> Integer\nsolve (_:x:cs) = sum $ zipWith (*) (sort cs) (map (max 1) [x, x-1..])\nsolve _ = undefined\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve (x:cs) = sum $ zipWith (*) (iterate (max 1 . pred) x) $ sort cs\n"}, {"source_code": "import Data.List\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x [] = 0\nsolve x (a:b) = (a * x) + (solve (max (x - 1) 1) b)\n\nmain = do\n first <- getLine >>= (return . (map read) . words)\n second <- getLine >>= (return . sort . (map read) . words)\n putStrLn $ show $ solve (first !! 1) second"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,x] <- map read.words <$> getLine\n xs <- map (fromIntegral.readInt).B.words <$> B.getContents\n print $ solve x xs\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x xs = sum.zipWith (*) (iterate (max 1.subtract 1) x) $ sort xs"}, {"source_code": "import Data.List\ns(_:x:l)=sum$zipWith(*)([x,x-1..1]++repeat 1)$sort l\nmain=interact$show.s.map read.words\n"}, {"source_code": "import Data.List\nmain = do\n c:t:[] <- getLine >>= func\n l <- getLine >>= func\n print $ f t 0 $ sort l\n where func = return.(map read).words\n \nf x acc (h:t) = f (if x==1 then 1 else (x-1)) (acc+x*h) t\nf x acc [] = acc\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n\nmain= do\n\t[n,m]<- map ( fst.fromJust.C.readInteger) .C.words <$> C.getLine::IO [Integer]\n\ts<-sort.map ( fst.fromJust.C.readInteger) .C.words <$> C.getLine::IO [Integer]\n\tprint $ sum $ zipWith (*) s ([m,m-1..1]++(repeat 1)) \n\t\n\t \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \n \n\nmain= do\n\t[n,m]<- map read .words <$> getLine::IO [Integer]\n\ts<-sort.map read .words <$> getLine::IO [Integer]\n\tprint $ sum $ zipWith (*) s ([m,m-1..1]++(repeat 1)) \n\t\n\t \n"}, {"source_code": "import Data.List\n\nmain = do\n let i = fmap (map read . words) getLine :: IO [Integer]\n [n, x] <- i\n c <- fmap sort i\n print $ gao c x\n\ngao :: [Integer] -> Integer -> Integer\ngao [] _ = 0\ngao (x:xs) t = x * t + (gao xs $ max 1 (t - 1))\n"}], "negative_code": [{"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x c = sum $ zipWith (*) [x, x-1 ..] (sort c)\n\nmain :: IO ()\nmain = do\n [n, x] <- map fromIntegral <$> getInts\n c <- map fromIntegral <$> getInts\n print $ solve x c\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \n \n\nmain= do\n\t[n,m]<- map read .words <$> getLine::IO [Int]\n\ts<-sort.map read .words <$> getLine::IO [Int]\n\tprint $ sum $ zipWith (*) s ([m,m-1..1]++(repeat 1)) \n\t\n\t \n"}], "src_uid": "ce27e56433175ebf9d3bbcb97e71091e"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Array.Base\nimport Data.Array.ST (STUArray,runSTUArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,val] <- map read.words <$> getLine\n tour1 <- radixSort.map readInt.B.words <$> B.getLine\n tour2 <- reverse.radixSort.map readInt.B.words <$> B.getLine\n let solve [] _ !ans = ans\n solve (x:xs) yys@(y:ys) !ans\n | xy>=val = solve xs ys $! ans+1\n | otherwise = solve xs yys ans\n where\n !xy = x+y\n putStr\"1 \"\n print $ solve tour1 tour2 0\n\nradixSort :: [Int] -> [Int]\nradixSort xs = elems $ runSTUArray $ do\n \n let mask = 0xffff\n n = length xs\n \n arr <- newListArray (0,n-1) xs :: ST s (STUArray s Int Int)\n tmp <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\n count <- newArray (0,mask) 0 :: ST s (STUArray s Int Int)\n \n forM_ xs $ \\x-> do\n let !mx = x.&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i->do\n xi <- unsafeRead arr i\n let !mi = xi.&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite tmp j xi\n \n forM_ [0..mask] $ \\i-> do\n unsafeWrite count i 0\n\n forM_ xs $ \\x-> do\n let !mx = (x`shiftR`16).&.mask\n unsafeRead count mx >>= unsafeWrite count mx.(1+)\n forM_ [1..mask] $ \\i-> do\n x <- unsafeRead count $ i-1\n unsafeRead count i >>= unsafeWrite count i.(x+)\n forM_ [n-1,n-2..0] $ \\i->do\n xi <- unsafeRead tmp i\n let !mi = (xi`shiftR`16).&.mask\n j <- subtract 1 <$> unsafeRead count mi\n unsafeWrite count mi j\n unsafeWrite arr j xi\n \n return arr\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,val] <- map read.words <$> getLine\n tour1 <- sort.map readInt.B.words <$> B.getLine\n tour2 <- sortBy (flip compare).map readInt.B.words <$> B.getLine\n let solve [] _ ans = ans\n solve (x:xs) (y:ys) ans\n | x+y>=val = solve xs ys $! ans+1\n | otherwise = solve xs (y:ys) ans\n putStr\"1 \"\n print $ solve tour1 tour2 0\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,val] <- map read.words <$> getLine\n tour1 <- sort.map readInt.B.words <$> B.getLine\n tour2 <- sortBy (flip compare).map readInt.B.words <$> B.getLine\n let solve [] _ !ans = ans\n solve (x:xs) yys@(y:ys) !ans\n | xy>=val = solve xs ys $! ans+1\n | otherwise = solve xs yys ans\n where\n !xy = x+y\n putStr\"1 \"\n print $ solve tour1 tour2 0\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,val] <- map read.words <$> getLine\n (max1:tour1) <- sortBy (flip compare).map readInt.B.words <$> B.getLine\n (max2:tour2) <- sortBy (flip compare).map readInt.B.words <$> B.getLine\n let solve [] [] ans = ans\n solve (x:xs) (y:ys) ans\n | x+max2>=val && y+max1>=val = solve xs ys $! ans+1\n | otherwise = ans\n putStr\"1 \"\n print $ solve tour1 tour2 1\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,x] <- map read.words <$> getLine\n tour1 <- map readInt.B.words <$> B.getLine\n tour2 <- map readInt.B.words <$> B.getLine\n let worst = length.takeWhile (>=x).sortBy (flip compare) $ zipWith (+) tour1 tour2\n putStrLn.unwords.map show $ [1,worst]\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,x] <- map read.words <$> getLine\n tour1 <- sort.map readInt.B.words <$> B.getLine\n tour2 <- sort.map readInt.B.words <$> B.getLine\n let max1 = maximum tour1\n max2 = maximum tour2\n ans1 = length $ dropWhile ( n\n\nmain = do\n [n,val] <- map read.words <$> getLine\n (max1:tour1) <- sort.map readInt.B.words <$> B.getLine\n (max2:tour2) <- sortBy (flip compare).map readInt.B.words <$> B.getLine\n let solve [] _ ans = ans\n solve (x:xs) (y:ys) ans\n | x+y>=val = solve xs ys $! ans+1\n | otherwise = solve xs (y:ys) ans\n putStr\"1 \"\n print $ solve tour1 tour2 1\n"}], "src_uid": "77919677f562a6fd1af64bc8cbc79de5"} {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n print $ solve n\n\nsolve :: Integer -> Integer\nsolve n = f n 1 0\n where\n f n pwr acc = if pwr>n then acc else f n (pwr*2) (acc + (n `div` pwr))", "positive_code": [{"source_code": "module Main where\n import Data.Bits\n\n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Integer\n print $ 2 * n - fromIntegral (popCount n)\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter (n - 1)\n \n main :: IO ()\n main = do\n s <- getLine\n let q = read s :: Integer\n iter q"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\n_solve !acc 0 = acc\n_solve !acc !curr = _solve (acc + curr) (curr `div` 2)\nsolve = _solve (0 :: Integer)\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Integer]\n res = vals |> unfoldr (\\case\n [] -> Nothing\n n:rest -> Just (solve n, rest)\n )\n sequence_ (putStrLn . show <$> res)\n"}, {"source_code": "toBin :: Integer -> [Bool]\ntoBin n\n | n == 0 = []\n | mod n 2 == 0 = toBin(div n 2) ++ [False]\n | otherwise = toBin(div n 2) ++ [True]\n\nsolve :: Integer -> Integer\nsolve n = foldl (\\acc (k, s) -> acc + (if s then 2^(k+1)-1 else 0)) 0 $ zip [0..] bin\n where bin = reverse $ toBin n\n\nparse :: String -> String\nparse input = show $ solve n\n where n = read input :: Integer\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "unfair n = sum [n `div` (2^d) | d <- takeWhile (\\x -> (2^x <= n))[0..]] \nreadIntList :: Integer -> IO [Integer]\nreadIntList 0 = return []\nreadIntList k = do\n val <- read <$> getLine\n (\\li -> val:li) <$> (readIntList (k-1))\nmain = do \n t <- read <$> getLine\n li <- readIntList t\n sequence $ map (putStrLn . show . unfair) li"}], "negative_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n print $ solve n\n\nsolve :: Int -> Int\nsolve n = f n 1 0\n where\n f n pwr acc = if pwr>n then acc else f n (pwr*2) (acc + (n `div` pwr))"}], "src_uid": "2a4f4c91522d83bc8f1ca2f086d24c3c"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n getLine\n [k, n, m] <- getIntList\n a <- getIntList\n b <- getIntList\n printList $ reverse $ f a b [] k\n\nf :: [Int] -> [Int] -> [Int] -> Int -> [Int]\nf [] [] o _ = o\nf (x:a) [] o k\n | x == 0 = f a [] (x:o) (k+1)\n | x <= k = f a [] (x:o) k\n | otherwise = [-1]\nf [] (y:b) o k\n | y == 0 = f [] b (y:o) (k+1)\n | y <= k = f [] b (y:o) k\n | otherwise = [-1]\nf (x:a) (y:b) o k\n | x == 0 = f a (y:b) (x:o) (k+1)\n | y == 0 = f (x:a) b (y:o) (k+1)\n | x <= k = f a (y:b) (x:o) k\n | y <= k = f (x:a) b (y:o) k\n | otherwise = [-1]\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\ngood :: Int -> [Int] -> [Int] -> [Int]\ngood _ [] [] = []\ngood k [] (x:xs)\n | x > k = [-1]\n | x == 0 = x : good (k+1) [] xs\n | otherwise = x : good k [] xs\ngood k a [] = good k [] a\ngood k a@(x:xs) b@(y:ys) \n | x == 0 = x: good (k+1) xs b\n | y == 0 = y: good (k+1) a ys\n | x <= k = x: good k xs b\n | y <= k = y: good k a ys\n | otherwise = [-1]\n\nsolve :: IO ()\nsolve = do\n [_, s, sa, sb] <- sequence $ replicate 4 getLine\n let [k, n, m] = readInts s\n a = readInts sa\n b = readInts sb\n l = good k a b\n bad = any (<0) l\n in putStrLn (if bad then \"-1\" else intercalate \" \" $ map show l)\n where readInts st = map read $ words st :: [Int]\n \n\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nsolve [] [] k = []\r\nsolve [] (m:ms) k\r\n |m == 0 = m : solve [] ms (k+1)\r\n |m > 0 && k >= m = m : solve [] ms k\r\n |otherwise = [-1]\r\nsolve ns [] k = solve [] ns k\r\nsolve (n:ns) (m:ms) k \r\n | n == 0 = n : solve ns (m:ms) (k+1)\r\n | m == 0 = m : solve (n:ns) ms (k+1)\r\n | n > 0 && k >= n = n : solve ns (m:ms) k\r\n | m > 0 && k >= m = m : solve (n:ns) ms k\r\n | otherwise = [-1]\r\n \r\nprintResult = do\r\n nothing <- getLine\r\n [k,n,m] <- readInts\r\n ns <- readInts\r\n ms <- readInts\r\n let r = solve ns ms k\r\n if last r == -1 then putStrLn \"-1\"\r\n else putStrLn . unwords . map show $ r\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>> drop 1 >>> chunksOf 4\r\n >>> map (drop 1 >>> map (words >>> map read) >>> solve\r\n >>> fmap (map show >>> unwords) >>> fromMaybe \"-1\")\r\n >>> unlines\r\n\r\nsolve :: [[Int]] -> Maybe [Int]\r\nsolve [[k,_,_], xs, ys] = build k xs ys\r\n\r\nbuild :: Int -> [Int] -> [Int] -> Maybe [Int]\r\nbuild _ [] [] = Just []\r\nbuild k (x:xs) [] = when (x <= k) $ (x:) <$> build (updK k x) xs []\r\nbuild k [] ys = build k ys []\r\nbuild k (x:xs) (y:ys)\r\n | x <= k = (x:) <$> build (updK k x) xs (y:ys)\r\n | y <= k = (y:) <$> build (updK k y) (x:xs) ys\r\n | otherwise = Nothing\r\n\r\nupdK :: Int -> Int -> Int\r\nupdK k 0 = k + 1\r\nupdK k _ = k\r\n\r\nwhen :: Bool -> Maybe a -> Maybe a\r\nwhen True ma = ma\r\nwhen False _ = Nothing\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\npairProgSingle :: Int -> [Int] -> [Int]\r\npairProgSingle _ [] = []\r\npairProgSingle k (x : xs)\r\n | x == 0 = x : pairProg (k + 1) xs []\r\n | x <= k = x : pairProg k xs []\r\n | otherwise = []\r\n\r\npairProg :: Int -> [Int] -> [Int] -> [Int]\r\npairProg _ [] [] = []\r\npairProg k xs [] = pairProgSingle k xs\r\npairProg k [] ys = pairProgSingle k ys\r\npairProg k (x : xs) (y : ys)\r\n | x > 0 && y > 0 = if x > k && y > k then []\r\n else if x > k then y : pairProg k (x : xs) ys\r\n else x : pairProg k xs (y : ys)\r\n | x == 0 && y == 0 = x : y : pairProg (k + 2) xs ys\r\n | y == 0 = if x <= k then x : pairProg k xs (y : ys) else y : pairProg (k + 1) (x : xs) ys\r\n | x == 0 = if y <= k then y : pairProg k (x : xs) ys else x : pairProg (k + 1) xs (y : ys)\r\n\r\nsolve :: (Int, Int, Int) -> [Int] -> [Int] -> [Int]\r\nsolve (k, n, m) xs ys = if n + m == length prog then prog else [-1] where\r\n prog = pairProg k xs ys\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n getLine \r\n [k, n, m] <- readInts\r\n xs <- readInts\r\n ys <- readInts\r\n putStrLn $ unwords $ map show $ solve (k, n, m) xs ys"}], "negative_code": [], "src_uid": "6628bd89b4d4fdfa90d2357f7cc1b795"} {"source_code": "import Data.Functor\n\nsolve :: [Int] -> [Int] -> Int\nsolve (c:cs) (a:as) | a >= c = 1 + solve cs as\n | otherwise = solve cs (a:as)\nsolve _ _ = 0\n\n\nmain :: IO ()\nmain = do\n getLine\n c <- map read <$> words <$> getLine\n a <- map read <$> words <$> getLine\n print $ solve c a\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess n [] _ = n\nprocess n _ [] = n\nprocess n (c:cs) (a:as) | c<=a = process (n+1) cs as\n | otherwise = process n cs (a:as)\n\n\n\nmain = do\n\t\tgetLine\n\t\tc<-map read <$> words <$> getLine ::IO [Int]\n\t\ta<-map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ process 0 c a\n\n"}, {"source_code": "process :: Integral a => [a] -> [a]-> Int\nprocess (c:cs) as'@(a:as)\n | c > a = process cs as'\n | otherwise = 1+process cs as\nprocess _ _ = 0\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n cs <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n print $ process cs as"}, {"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ndoit2 [] y = (0, [])\ndoit2 (x:xs) y =\n if x >= y then\n (1,xs)\n else\n let (t, a) = doit2 xs y in\n (t,x:a)\n\ndoit [] a r = r\ndoit a [] r = r\ndoit (x:xs) (a:as) r =\n if a >= x then\n doit xs as $ r+1\n else\n doit xs (a:as) r\n --let (t,aa) = doit2 a x in\n --doit xs aa $ r+t\n\nsolve::String -> String\nsolve sss =\n let (n:m:ss) = map toint $ words sss in\n let c = take (fromIntegral n) ss in\n let a = drop (fromIntegral n) ss in\n (show (doit c a 0)) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}, {"source_code": "import Data.List\n\nf::[Int]->[Int]->Int\nf [] _ =0\nf _ []=0\nf (x:xs) (y:ys)\n |x>y=f xs (y:ys)\n |otherwise=1 + (f xs ys)\n\n\nmain = do\n e<-getLine\n e2<-getLine\n e3<-getLine\n let xs=map read (words e2)::[Int]\n ys=map read (words e3)::[Int]\n print $ f xs ys"}, {"source_code": "solve (x:xs) (y:ys) | y >= x = 1 + solve xs ys \n | 1>0 = solve xs (y:ys)\nsolve _ _ = 0\nmain = do\n getLine\n g <- map read . words <$> getLine\n b <- map read . words <$> getLine :: IO [Int]\n print $ solve g b\n"}, {"source_code": "solve :: [Int] -> [Int] -> Int\nsolve [] _ = 0\nsolve _ [] = 0\nsolve (x:xs) (y:ys) = if y >= x then 1 + solve xs ys\n else solve xs (y:ys)\nmain = do\n l1 <- getLine :: IO String\n l2 <- getLine :: IO String\n l3 <- getLine :: IO String\n let [n,m] = map read $ words l1 :: [Int]\n let games = map read $ words l2 :: [Int]\n let bills = map read $ words l3 :: [Int]\n --print $ bills\n print $ solve games bills\n"}, {"source_code": "solve (x:xs) (y:ys) = if y >= x then 1 + solve xs ys else solve xs (y:ys)\nsolve _ _ = 0\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n games <- map read . words <$> getLine\n bills <- map read . words <$> getLine :: IO [Int]\n print $ solve games bills\n"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine :: IO [Int]\n cs <- map read.words <$> getLine\n bs <- map read.words <$> getLine\n print $ solve cs bs\n\nsolve :: [Int] -> [Int] -> Int\nsolve cs bs = go 0 cs bs\n where\n go res (c:cs) (b:bs)\n | c <= b = go (res + 1) cs bs\n | otherwise = go res cs (b:bs)\n go res _ _ = res"}], "negative_code": [], "src_uid": "c3f080681e3da5e1290ef935ff91f364"} {"source_code": "import Control.Monad (replicateM_)\nimport Data.Char (ord)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nsolve [n, k]\n | k `mod` 3 /= 0 =\n if n `mod` 3 == 0\n then bob\n else alice\n | otherwise =\n let r = n `mod` (k + 1)\n in if r == k\n then alice\n else if r `mod` 3 == 0\n then bob\n else alice\n where\n alice = \"Alice\"\n bob = \"Bob\"\n\nmain = do\n testNum <- fmap parseInt getLine\n replicateM_ testNum (putStrLn . solve . parseInts =<< getLine)\n", "positive_code": [{"source_code": "import Data.Char (isSpace)\nimport Data.List (elemIndex, take, drop)\nimport Data.Maybe (fromJust)\n\nsplit [] = []\nsplit (c:cs) | isSpace c = split cs\n | otherwise = case split cs of\n [] -> (c:[]):[]\n (s:ss) -> (c:s):ss\n\nmain = do ts <- getLine\n solve (read ts)\n\nsolve 0 = return ()\nsolve t = do l <- getLine\n let i = fromJust $ elemIndex ' ' l\n let n = read $ take i l\n let k = read $ drop (i + 1) l\n putStrLn $ winner $ answer n k\n solve $ t - 1\n\nwinner True = \"Alice\"\nwinner False = \"Bob\"\n\nanswer n k | mod k 3 == 0 = mod (n + 1) (k + 1) == 0 || mod (mod n (k + 1)) 3 /= 0\n | otherwise = mod n 3 /= 0"}], "negative_code": [{"source_code": "import Data.Char (isSpace)\nimport Data.List (elemIndex, take, drop)\nimport Data.Maybe (fromJust)\n\nsplit [] = []\nsplit (c:cs) | isSpace c = split cs\n | otherwise = case split cs of\n [] -> (c:[]):[]\n (s:ss) -> (c:s):ss\n\nmain = do ts <- getLine\n solve (read ts)\n\nsolve 0 = return ()\nsolve t = do l <- getLine\n let i = fromJust $ elemIndex ' ' l\n let n = read $ take i l\n let k = read $ drop (i + 1) l\n putStrLn $ winner $ answer n k\n solve $ t - 1\n\nwinner True = \"Alice\"\nwinner False = \"Bob\"\n\nanswer n k | mod k 3 == 0 = mod n (4 * k) == 3 * k || mod n 3 /= mod (mod (div n k) 4) 3\n | otherwise = mod n 3 /= 0"}, {"source_code": "import Data.Char (isSpace)\nimport Data.List (elemIndex, take, drop)\nimport Data.Maybe (fromJust)\n\nsplit [] = []\nsplit (c:cs) | isSpace c = split cs\n | otherwise = case split cs of\n [] -> (c:[]):[]\n (s:ss) -> (c:s):ss\n\nmain = do ts <- getLine\n solve (read ts)\n\nsolve 0 = return ()\nsolve t = do l <- getLine\n let i = fromJust $ elemIndex ' ' l\n let n = read $ take i l\n let k = read $ drop (i + 1) l\n putStrLn $ winner $ answer n k\n solve $ t - 1\n\nwinner True = \"Alice\"\nwinner False = \"Bob\"\n\nanswer n k | mod k 3 == 0 = mod (mod n (k + 1)) 3 /= 0\n | otherwise = mod n 3 /= 0"}, {"source_code": "import Data.Char (isSpace)\nimport Data.List (elemIndex, take, drop)\nimport Data.Maybe (fromJust)\n\nsplit [] = []\nsplit (c:cs) | isSpace c = split cs\n | otherwise = case split cs of\n [] -> (c:[]):[]\n (s:ss) -> (c:s):ss\n\nmain = do ts <- getLine\n solve (read ts)\n\nsolve 0 = return ()\nsolve t = do l <- getLine\n let i = fromJust $ elemIndex ' ' l\n let n = read $ take i l\n let k = read $ drop (i + 1) l\n putStrLn $ winner $ answer n k\n solve $ t - 1\n\nwinner True = \"Bob\"\nwinner False = \"Alice\"\n\nanswer n k | mod k 3 == 0 && n >= k = mod n 3 == 1\n | otherwise = mod n 3 == 0"}, {"source_code": "import Data.Char (isSpace)\nimport Data.List (elemIndex, take, drop)\nimport Data.Maybe (fromJust)\n\nsplit [] = []\nsplit (c:cs) | isSpace c = split cs\n | otherwise = case split cs of\n [] -> (c:[]):[]\n (s:ss) -> (c:s):ss\n\nmain = do ts <- getLine\n solve (read ts)\n\nsolve 0 = return ()\nsolve t = do l <- getLine\n let i = fromJust $ elemIndex ' ' l\n let n = read $ take i l\n let k = read $ drop (i + 1) l\n putStrLn $ winner $ answer n k\n solve $ t - 1\n\nwinner True = \"Alice\"\nwinner False = \"Bob\"\n\nanswer n k | mod k 3 == 0 = (n > 0 && mod n k == 0) || mod n 3 /= mod (div n k) 3\n | otherwise = mod n 3 /= 0"}], "src_uid": "8e0b8f3cbee8e770245de72a8fb62e05"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.Set as S\n\nmain = do\n [n,m] <- map read.words <$> getLine\n pqueue <- S.fromList.(`zip`[1..m]).map read.words <$> getLine\n let solvemax 0 !ans !pq = ans\n solvemax !rest !ans !pq\n | cost == 0 = solvemax rest ans q\n | otherwise = solvemax (rest-1) (ans+cost) (S.insert (cost-1,i) q)\n where\n ((cost,i),q) = S.deleteFindMax pq\n solvemin 0 !ans !pq = ans\n solvemin !rest !ans !pq\n | cost == 0 = solvemin rest ans q\n | otherwise = solvemin (rest-1) (ans+cost) (S.insert (cost-1,i) q)\n where\n ((cost,i),q) = S.deleteFindMin pq\n putStrLn . unwords $ map show [solvemax n 0 pqueue,solvemin n 0 pqueue]\n", "positive_code": [{"source_code": "import List (sort)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nsolve :: Int -> [Int] -> (Int, Int)\nsolve n as = (mx, mn)\n where\n mx = calcMax (reverse (sort as)) n 0\n calcMax _ 0 acc = acc\n calcMax [] _ _ = undefined\n calcMax (a:as) n acc = calcMax (reverse (sort ((a-1):as))) (n-1) (acc+a)\n mn = calcMin (sort as) n 0\n calcMin _ 0 acc = acc\n calcMin [] _ _ = undefined\n calcMin (a:as) n acc\n | a == 0 = calcMin as n acc\n | otherwise = calcMin (a-1:as) (n-1) (acc+a)\n\nprintAns :: (Int, Int) -> IO ()\nprintAns (x,y) = putStrLn $ concat [show x, \" \", show y]\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n as <- reads\n printAns $ solve n as"}, {"source_code": "import Data.List\n\nreadInt s = read s :: Int\nreadInts s n = map readInt $ take n $ words s\nprogr low high = (high - low + 1) * (low + high) `div` 2\n\nminIncome n as = calcIncome n . sort $ as\n where calcIncome n all@(a:as)\n | n == 0 = 0\n | n <= a = progr (a - n + 1) a\n | otherwise = progr 1 a + calcIncome (n - a) as\n\nmaxIncome n as = calcIncome n (rsort as)\n where rsort = reverse . sort\n calcIncome n (cur : as)\n | n == 0 = 0\n | otherwise = let next = if null as then 1 else head as\n getting = min n (cur - next + 1)\n curres = progr (cur - getting + 1) cur\n nextres = calcIncome (n - getting) (rsort $ (cur - getting) : as)\n in curres + nextres\n\nmain = do\n args0 <- getLine\n args1 <- getLine\n let [n, m] = readInts args0 2\n as = readInts args1 m\n putStrLn . intercalate \" \" . map show $ [maxIncome n as, minIncome n as]\n"}], "negative_code": [{"source_code": "import Data.List\n\nreadInt s = read s :: Int\nreadInts s n = map readInt $ take n $ words s\nprogr low high = (high - low + 1) * (low + high) `div` 2\n\nminIncome n as = calcIncome n . sort $ as\n where calcIncome n all@(a:as)\n | n == 0 = 0\n | n <= a = progr 1 n\n | otherwise = progr 1 a + calcIncome (n - a) as\n\nmaxIncome n as = calcIncome n (rsort as)\n where rsort = reverse . sort\n calcIncome n (cur : as)\n | n == 0 = 0\n | otherwise = let next = if null as then 1 else head as\n getting = min n (cur - next + 1)\n curres = progr (cur - getting + 1) cur\n nextres = calcIncome (n - getting) (rsort $ (cur - getting) : as)\n in curres + nextres\n\nmain = do\n args0 <- getLine\n args1 <- getLine\n let [n, m] = readInts args0 2\n as = readInts args1 m\n putStrLn . intercalate \" \" . map show $ [maxIncome n as, minIncome n as]\n"}], "src_uid": "6dea4611ca210b34ae2da93ebfa9896c"} {"source_code": "main = do getLine >> getLine >>= putStrLn . show . gao . map read . words\ngao a = sum $ zipWith (*) (0:c) $ init d where\n\ts = sum a\n\tb = scanl1 (+) a\n\tc = scanl1 (+) $ map (\\i -> if 3 * i == s then 1 else 0) $ b\n\td = map (\\i -> if 3 * i == 2 * s then 1 else 0) $ b\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.IArray\nimport Data.Array.MArray hiding (unsafeFreeze)\nimport Data.Array.Unsafe (unsafeFreeze)\nimport qualified Data.Array.Unboxed as U\nimport Data.Array.ST (runSTUArray,STUArray)\nimport Control.Monad.ST (ST,runST)\nimport Debug.Trace\nimport Data.List\nimport Data.Int\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\n\nreadInt :: ByteString -> Int\nreadInt s =\n case BS.readInt s of\n Nothing -> error \"bad int\"\n Just (x,_) -> x\n\nindexes arr n target inds = runST $ do\n jarr <- newArray (1,n) 0 :: ST s (STUArray s Int Int)\n let go a j [] = return j\n go a j (i:is) = let v = a + arr ! i in\n if v == target then do { writeArray jarr (j+1) i; go v (j+1) is }\n else go v j is\n hi <- go 0 0 inds\n jarr' <- unsafeFreeze jarr\n return (jarr', hi)\n\nsolve :: Int -> [Int] -> Int64\nsolve n nums = if total `mod` 3 /= 0 then 0 else count\n where\n total = sum nums\n target = total `div` 3\n arr = listArray (1,n) nums :: U.UArray Int Int\n\n count = \n let (pre,lasti) = indexes arr n target [1..n] :: (U.UArray Int Int,Int)\n (suf,lastj) = indexes arr n target [n,n-1..1] :: (U.UArray Int Int, Int)\n go c i j | i > lasti = c\n | j < 1 = c\n | (pre ! i)+1 < (suf ! j) = go (c+fromIntegral j) (i+1) j\n | otherwise = go c i (j-1)\n in go 0 1 lastj\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read :: IO Int\n nums <- BS.getLine --> BS.words --> take n --> map readInt\n print $ solve n nums\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.IArray\nimport Data.Array.MArray hiding (unsafeFreeze)\nimport Data.Array.Unsafe (unsafeFreeze)\nimport qualified Data.Array.Unboxed as U\nimport Data.Array.ST (runSTUArray,STUArray)\nimport Control.Monad.ST (ST,runST)\nimport Debug.Trace\nimport Data.List\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\n\nreadInt :: ByteString -> Int\nreadInt s =\n case BS.readInt s of\n Nothing -> error \"bad int\"\n Just (x,_) -> x\n\nindexes arr n target inds = runST $ do\n jarr <- newArray (1,n) 0 :: ST s (STUArray s Int Int)\n let go a j [] = return j\n go a j (i:is) = let v = a + arr ! i in\n if v == target then do { writeArray jarr (j+1) i; go v (j+1) is }\n else go v j is\n hi <- go 0 0 inds\n jarr' <- unsafeFreeze jarr\n return (jarr', hi)\n\nsolve :: Int -> [Int] -> Int\nsolve n nums = if total `mod` 3 /= 0 then 0 else count\n where\n total = sum nums\n target = total `div` 3\n arr = listArray (1,n) nums :: U.UArray Int Int\n\n count = \n let (pre,lasti) = indexes arr n target [1..n] :: (U.UArray Int Int,Int)\n (suf,lastj) = indexes arr n target [n,n-1..1] :: (U.UArray Int Int, Int)\n go c i j | i > lasti = c\n | j < 1 = c\n | (pre ! i)+1 < (suf ! j) = go (c+j) (i+1) j\n | otherwise = go c i (j-1)\n in go 0 1 lastj\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read :: IO Int\n nums <- BS.getLine --> BS.words --> take n --> map readInt\n print $ solve n nums\n\n"}], "src_uid": "4798211615bcff8730378330756ae63f"} {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read . words) getLine\n income <- fmap (map read . words) getLine\n let (less, _) = partition (< 0) income\n (pre, post) = splitAt k income\n allPos = map abs pre ++ post\n m = minimum $ map abs income\n\n if (length less >= k) then\n print $ sum allPos\n else\n if (k - length less) `mod` 2 == 0 then\n print $ sum allPos\n else\n print $ sum $ allPos ++ [-m, -m]\n\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [Int] -> Int\nsolve k xs\n | k <= m = sum $ zipWith (*) xs $ replicate k (-1) ++ [1,1..]\n | even (k - m) = sum xs'\n | otherwise = sum xs' - 2 * minimum xs'\n where\n xs' = map abs xs\n m = length $ filter (<= 0) xs\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n xs <- reads\n print $ solve k xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nsolve (k:values) =\n sum finalValues - if restK `mod` 2 == 1\n then 2 * minimum finalValues\n else 0\n where finalValues = left ++ right\n restK = k - usedK\n usedK = length left\n left = map negate $ take k $ takeWhile (<0) values\n right = drop usedK values\n\nparseInt = fst . fromJust . BS.readInt\n\nmain = BS.interact $ BS.pack . show . solve . map parseInt . tail . BS.words"}, {"source_code": "solve (k:values) =\n sum finalValues - if restK `mod` 2 == 1\n then 2 * minimum finalValues\n else 0\n where finalValues = left ++ right\n restK = k - usedK\n usedK = length left\n left = map negate $ take k $ takeWhile (<0) values\n right = drop usedK values\n\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "module Main where\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve 0 neg pos = sum neg + sum pos\nsolve k [] pos = sum pos - 2 * head pos * (k `mod` 2)\nsolve k neg []\n | length neg >= k = sum (drop k neg) - sum (take k neg)\n | otherwise = -(sum neg) + 2 * last neg * ((k - length neg) `mod` 2)\nsolve k neg pos\n | length neg >= k = sum (drop k neg) + sum pos - sum (take k neg)\n | otherwise = if (-(last neg)) > head pos\n then sum pos - sum neg - 2 * head pos * ((k - length neg) `mod` 2)\n else sum pos - sum neg + 2 * last neg * ((k - length neg) `mod` 2)\n\nmain = do\n rStr <- getLine\n let [_, k] = map read $ words rStr\n revenuesStr <- getLine\n let (negative, positive) = span (<0) $ map read $ words revenuesStr\n print $ solve k negative positive"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = B.getContents >>= print.sum.f.map readInt.B.words\nf(n:k:x)\n | len >= k = let (y,z) = splitAt k nx in map abs y ++ z ++ px\n | len == 0 && (head x==0 || even k) = x\n | len == 0 = negate (head x) : tail x\n | otherwise = f $ n:(k-len):sort(map abs x)\n where\n (nx,px)=partition(<0)x\n len = length nx\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\n\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (m:a:cs) = show $ if k < nel then (sum as - sum (take k as) * 2) else (sum pl - sum ne - fl * ((k-nel)`mod`2) * 2)\n where\n [n,k] = map read . words $ m\n as = sort . map read . words $ a\n (ne,pl) = partition (<0) as\n nel = length ne\n pll = length pl\n fl = if nel==0 then (head pl) else (if pll==0 then (-(last ne)) else (min (head pl) (-(last ne))))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\t[ n, k ] <- map read . words <$> getLine\n\tas <- map read . words <$> getLine\n\tlet\n\t\tnegas = min ( length ( filter ( < 0 ) as ) ) k\n\t\trest = ( k - negas ) `mod` 2\n\t\ttmp = sort . change negas $ as\n\t\tres = if 0 `elem` tmp then sum tmp else sum $ change rest tmp\n\tprint res\n\nchange :: Int -> [Int] -> [Int]\nchange _ [] = []\nchange 0 as = as\nchange n (a:as) = a * ( -1 ) : change ( n - 1 ) as\n"}, {"source_code": "main = interact $ show . solve . map read . words\n\nsolve (n : k : a)\n | k <= l = sum pos + (sum . take k . map negate $ npos) + (sum . drop k $ npos)\n | mod (k - l) 2 == 0 = sum . map abs $ a\n | otherwise = (sum . map abs $ a) - 2 * (minimum . map abs $ a)\n where\n npos = filter (<=0) $ a\n pos = filter (>0) $ a\n l = length npos\n \n"}, {"source_code": "module Main where\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve 0 neg pos = sum neg + sum pos\nsolve k [] pos = (sum pos) - 2 * (head pos) * (k `mod` 2)\nsolve k neg []\n | length neg >= k = sum (drop k neg) - sum (take k neg)\n | otherwise = -(sum neg) + 2 * (last neg) * ((k - (length neg)) `mod` 2)\nsolve k neg pos\n | length neg >= k = sum (drop k neg) + sum pos - sum (take k neg)\n | otherwise = if (-(last neg)) > (head pos)\n then (sum pos) - (sum neg) - 2 * (head pos) * ((k - (length neg)) `mod` 2)\n else (sum pos) - (sum neg) + 2 * (last neg) * ((k - (length neg)) `mod` 2)\n \nmain = do\n nkStr <- getLine\n let nk = map (read :: String -> Int) $ words nkStr\n k = nk!!1\n revenuesStr <- getLine\n let revenues = map (read :: String -> Int) $ words revenuesStr\n (negative, positive) = span (<0) revenues\n print $ solve k negative positive"}, {"source_code": "import Control.Applicative\nimport Data.List\nmain = do\n [n,k] <- map read . words <$> getLine\n ns <- map read . take n . words <$> getLine\n let \n (neg, pos) = span (<0) ns\n ans = sum $ change neg pos $ k\n ans' = sum $ change' neg k\n ansPos = sum $ changePos pos k\n if length pos == 0 then print ans'\n else if length neg == 0 then print ansPos\n else print ans\n\nf neg@(n:ns) pos@(m:ms) k\n | k `mod` 2 == 0 = neg ++ pos\n | True = case n > m of\n True -> neg ++ (-m):ms\n False -> (-n):ns ++ pos\nchange neg pos k\n | length neg < k = f (reverse $ map (*(-1)) $ neg) pos (k - length neg)\n | True = (map (*(-1)) $ take k $ neg) ++ drop k neg ++ pos\n\nf' neg@(n:ns) k \n | k `mod` 2 == 0 = neg\n | True = (-n):ns\nchange' neg k\n | length neg < k = f' (reverse $ map (*(-1)) $ neg) (k - length neg)\n | True = (map (*(-1)) $ take k $ neg) ++ drop k neg\n\nchangePos (p:ps) k\n | k `mod` 2 == 0 = p:ps\n | True = (-p):ps"}], "negative_code": [{"source_code": "main = interact $ show . solve . map read . words\n\nsolve (n : k : a)\n | k <= l = sum pos + (sum . take k . map (*(-1)) $ npos) + (sum . drop k $ npos)\n | mod (l - k) 2 == 0 = sum . map abs $ a\n | otherwise = (sum . map abs $ a) + (minimum . map abs $ a)\n where\n npos = filter (<=0) $ a\n pos = filter (>0) $ a\n l = length npos\n \n"}, {"source_code": "main :: IO ()\nmain = do\n [_, k] <- fmap (map read) $ words `fmap` getLine\n income <- fmap (map read) $ words `fmap` getLine\n let (pre, post) = splitAt k income\n print $ sum $ map abs pre ++ post\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read) $ words `fmap` getLine\n income <- fmap (map read) $ words `fmap` getLine\n let (less, more) = partition ((>=) 0) income\n (pre, post) = splitAt k income\n allPos = map abs pre ++ post\n m = minimum $ map abs income\n\n if (length less >= k) then\n print $ sum allPos\n else\n if k `mod` 2 == 0 then\n print $ sum allPos\n else\n print $ sum $ allPos ++ [-m, -m]\n\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read . words) getLine\n income <- fmap (map read . words) getLine\n let (less, _) = partition (>= 0) income\n (pre, post) = splitAt k income\n allPos = map abs pre ++ post\n m = minimum $ map abs income\n\n if (length less >= k) then\n print $ sum allPos\n else\n if (k - length less) `mod` 2 == 0 then\n print $ sum allPos\n else\n print $ sum $ allPos ++ [-m, -m]\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = B.getContents >>= print.sum.f.map readInt.B.words\nf(n:k:x)|(y,z)<-splitAt k x=map negate y++z"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = B.getContents >>= print.sum.f.map readInt.B.words\nf(n:k:x)\n | len >= k = let (y,z) = splitAt k nx in map abs y ++ z ++ px\n | len == 0 && even (head x) = x\n | len == 0 = negate (head x) : tail x\n | otherwise = f $ n:(k-len):sort(map abs x)\n where\n (nx,px)=partition(<0)x\n len = length nx\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\n\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (m:a:cs) = show $ (sum . map (*(-1)) $ take k as) + (sum $ drop k as)\n where\n k = read . head . tail . words $ m\n as = sort . map read . words $ a\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\t[ n, k ] <- map read . words <$> getLine\n\tas <- map read . words <$> getLine\n\tlet\n\t\tnegas = max ( length ( filter ( < 0 ) as ) ) k\n\t\trest = ( k - negas ) `mod` 2\n\t\ttmp = sort . change negas $ as\n\t\tres = sum $ change rest tmp\n\tprint res\n\nchange :: Int -> [Int] -> [Int]\nchange _ [] = []\nchange 0 as = as\nchange n (a:as) = a * ( -1 ) : change ( n - 1 ) as\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\t[ n, k ] <- map read . words <$> getLine\n\tas <- map read . words <$> getLine\n\tlet\n\t\tnegas = max ( length ( filter ( < 0 ) as ) ) k\n\t\trest = ( k - negas ) `mod` 2\n\t\ttmp = sort . change negas $ as\n\t\tres = if 0 `elem` tmp then sum tmp else sum $ change rest tmp\n\tprint res\n\nchange :: Int -> [Int] -> [Int]\nchange _ [] = []\nchange 0 as = as\nchange n (a:as) = a * ( -1 ) : change ( n - 1 ) as\n"}, {"source_code": "main = interact $ show . solve . map read . words\n\nsolve (n : k : a)\n | k <= l = sum pos + (sum . take k . map negate $ npos) + (sum . drop k $ npos)\n | mod (k - l) 2 == 0 = sum . map abs $ a\n | otherwise = (sum . map abs $ a) - (minimum . map abs $ a)\n where\n npos = filter (<=0) $ a\n pos = filter (>0) $ a\n l = length npos\n \n"}], "src_uid": "befd3b1b4afe19ff619c0b34ed1a4966"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\ts <- getLine\n\tlet\n\t\tds = scanl1 (+) $ map ( \\c -> if c == '(' then 1 else -1 ) s\n\t\tmd = maximum ds\n\t\tth = md `div` 2\n\tputStrLn $ map ( \\( c, d ) -> if ( c == '(' && th < d || c == ')' && th <= d ) then '1' else '0' ) $ zip s ds", "positive_code": [{"source_code": "import Data.Sequence\nimport Data.Foldable (toList)\n\nmain :: IO ()\nmain = getLine >> solve <$> getLine >>= putStrLn\n\nsolve :: String -> String\nsolve = toList. fst . foldl modify (empty, ((0,0), (0,0)))\n\ntype S = (Seq Char, ((Int, Int), (Int, Int)))\n\nmodify :: S -> Char -> S\nmodify (s, ((a, b), (c, d))) '(' = (s', ((aa, bb), (cc, dd)))\n where (s', (aa, bb)) = if a < b then (s |> '1', (a + 1, b)) else (s |> '0', (a, b + 1))\n (cc, dd) = (max aa c, max bb d)\n\nmodify (s, ((a, b), (c, d))) _ = (s', ((aa, bb), (c, d)))\n where (s', (aa, bb)) = if a > b then (s |> '1', (a - 1, b)) else (s |> '0', (a , b - 1))\n"}], "negative_code": [], "src_uid": "73b18cc560ea94476903f79a695d4268"} {"source_code": "import Data.Functor ((<$>))\nimport Data.Array\nimport Data.Char (isSpace)\nimport Data.List\nimport Data.Ord (comparing)\nimport qualified Data.ByteString.Char8 as B\n\nbsearch :: (Int -> Bool) -> Int -> Int -> Int\nbsearch f l r\n | l == r = r\n | f m = bsearch f l m\n | otherwise = bsearch f (m + 1) r\n where m = (l + r) `div` 2\n\ncheck :: Array Int Int -> [Int] -> Int -> Bool\ncheck d a n = and (zipWith (\\x y -> exam!x >= y) subj requ)\n where m = snd (bounds d)\n exam = accumArray (const id) 0 (0, m) (zip a [1..n]) -- deadline\n subj = sortBy (comparing (exam!)) [1..m] -- subjects sorted by deadline\n requ = scanl1 (+) (map (d!) subj) -- times required for each subjects w.r.t. subj\n\nsolve :: [Int] -> [Int] -> Int\nsolve dl a\n | check d a (length a) = bsearch (check d a) 0 (length a)\n | otherwise = -1\n where d = listArray (1, length dl) (map (+1) dl)\n\nmain :: IO()\nmain = do\n _ <- B.getLine\n a <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n d <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n print $ solve d a\n", "positive_code": [{"source_code": "import Data.Functor ((<$>))\nimport Data.Array\nimport Data.List\nimport Data.Ord (comparing)\n\nbsearch :: (Int -> Bool) -> Int -> Int -> Int\nbsearch f l r\n | l == r = r\n | f m = bsearch f l m\n | otherwise = bsearch f (m + 1) r\n where m = (l + r) `div` 2\n\ncheck :: [Int] -> [Int] -> Bool\ncheck d a = all (uncurry (<=)) (zip x (map snd st))\n where m = length d :: Int\n ed = accumArray (const id) 0 (0, m) (zip a [1::Int ..])\n st = sortBy (comparing snd) (zip d (map (ed!) [1..m]))\n x = scanl1 (+) (map fst st)\n\nsolve :: [Int] -> [Int] -> Int\nsolve d a\n | check d a = bsearch (check d . (`take` a)) 0 (length a)\n | otherwise = -1\n\nmain :: IO()\nmain = do\n _ <- getLine\n a <- map read . words <$> getLine\n d <- map read . words <$> getLine\n print $ solve (map (+1) d) a\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.Array\nimport Data.List\nimport Data.Ord (comparing)\n\nbsearch :: (Int -> Bool) -> Int -> Int -> Int\nbsearch f l r\n | l == r = r\n | f m = bsearch f l m\n | otherwise = bsearch f (m + 1) r\n where m = (l + r) `div` 2\n\ncheck :: Array Int Int -> [Int] -> Bool\ncheck d a = and (zipWith (\\x y -> exam!x >= y) subj requ)\n where m = snd (bounds d)\n exam = accumArray (const id) 0 (0, m) (zip a [1::Int ..]) -- deadline\n subj = sortBy (comparing (exam!)) [1..m] -- subjects sorted by deadline\n requ = scanl1 (+) (map (d!) subj) -- times required for each subjects w.r.t. subj\n\nsolve :: Array Int Int -> [Int] -> Int\nsolve d a\n | check d a = bsearch (check d . (`take` a)) 0 (length a)\n | otherwise = -1\n\nmain :: IO()\nmain = do\n _ <- getLine\n a <- map read . words <$> getLine\n dList <- map ((+1) . read) . words <$> getLine\n let d = listArray (1, length dList) dList\n print $ solve d a\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine :: IO [Int]\n ds <- map readInt.B.words <$> B.getLine\n xs <- map (fromIntegral.readInt).B.words <$> B.getLine\n print $ solve n m ds xs\n\nsolve :: Int -> Int -> [Int] -> [Int64] -> Int\nsolve n m ds xs\n | isOK n = lowerBound 1 n isOK\n | otherwise = -1\n where\n arr :: UArray Int Int64\n arr = listArray (1, m) xs\n isOK i = go (IS.fromList[1..m]) 0 . reverse $ take i ds\n where\n go !unused !acc (x:xs)\n | IS.member x unused = go (IS.delete x unused) (acc+arr!x) xs\n | otherwise = go unused (max 0 $ acc-1) xs\n go unused acc [] = IS.null unused && acc == 0\n\nlowerBound :: (Integral i) => i -> i -> (i -> Bool) -> i\nlowerBound low high p = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.Array\nimport Data.Char (isSpace)\nimport Data.List\nimport Data.Ord (comparing)\nimport qualified Data.ByteString.Char8 as B\n\nbsearch :: (Int -> Bool) -> Int -> Int -> Int\nbsearch f l r\n | l == r = r\n | f m = bsearch f l m\n | otherwise = bsearch f (m + 1) r\n where m = (l + r) `div` 2\n\ncheck :: Array Int Int -> [Int] -> Int -> Bool\ncheck d a n = and (zipWith (\\x y -> exam!x >= y) subj requ)\n where m = snd (bounds d)\n exam = accumArray (const id) 0 (0, m) (zip a [1..n]) -- deadline\n subj = sortBy (comparing (exam!)) [1..m] -- subjects sorted by deadline\n requ = scanl1 (+) (map (d!) subj) -- times required for each subjects w.r.t. subj\n\nsolve :: [Int] -> [Int] -> Int\nsolve dl a\n | check d a (length a) = bsearch (check d a) 0 (length a)\n | otherwise = -1\n where d = listArray (1, length dl) (map (+1) dl)\n\nmain :: IO()\nmain = do\n _ <- B.getLine\n a <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n d <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n print (a `seq` d `seq` solve d a)\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.Array\nimport Data.Char (isSpace)\nimport Data.List\nimport Data.Ord (comparing)\nimport qualified Data.ByteString.Char8 as B\n\nbsearch :: (Int -> Bool) -> Int -> Int -> Int\nbsearch f l r\n | l == r = r\n | f m = bsearch f l m\n | otherwise = bsearch f (m + 1) r\n where m = (l + r) `div` 2\n\ncheck :: Array Int Int -> [Int] -> Bool\ncheck d a = and (zipWith (\\x y -> exam!x >= y) subj requ)\n where m = snd (bounds d)\n exam = accumArray (const id) 0 (0, m) (zip a [1::Int ..]) -- deadline\n subj = sortBy (comparing (exam!)) [1..m] -- subjects sorted by deadline\n requ = scanl1 (+) (map (d!) subj) -- times required for each subjects w.r.t. subj\n\nsolve :: [Int] -> [Int] -> Int\nsolve dl a\n | check d a = bsearch (check d . (`take` a)) 0 (length a)\n | otherwise = -1\n where d = listArray (1, length dl) (map (+1) dl)\n\nmain :: IO()\nmain = do\n _ <- B.getLine\n a <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n d <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n print $ solve d a\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.Array\nimport Data.List\nimport Data.Ord (comparing)\nimport Data.Ix (inRange)\n\nbsearch :: (Int -> Bool) -> Int -> Int -> Int\nbsearch f l r\n | l == r = r\n | f m = bsearch f l m\n | otherwise = bsearch f (m + 1) r\n where m = (l + r) `div` 2\n\ncheck :: Array Int Int -> [(Int, Int)] -> Bool\ncheck d a = and (zipWith (\\x y -> exam!x >= y) subj requ)\n where exam = accumArray (const id) 0 (bounds d) a -- deadline\n subj = sortBy (comparing (exam!)) (indices d) -- subjects sorted by deadline\n requ = scanl1 (+) (map (d!) subj) -- times required for each subjects w.r.t. subj\n\nsolve :: [Int] -> [Int] -> Int\nsolve dl a0\n | check d a = snd $ a !! (bsearch (check d . (`take` a)) 0 (length a) - 1)\n | otherwise = -1\n where d = listArray (1, length dl) (map (+1) dl)\n a = filter (inRange (bounds d) . fst) (zip a0 [1..])\n\nmain :: IO()\nmain = do\n _ <- getLine\n a <- map read . words <$> getLine\n d <- map read . words <$> getLine\n print $ solve d a\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine :: IO [Int]\n ds <- map readInt.B.words <$> B.getLine\n xs <- map (fromIntegral.readInt).B.words <$> B.getLine\n print $ solve n m ds xs\n\nsolve :: Int -> Int -> [Int] -> [Int64] -> Int\nsolve n m ds xs\n | isOK n = lowerBound 1 n isOK\n | otherwise = -1\n where\n arr :: UArray Int Int64\n arr = listArray (1, m) xs\n isOK i = go (IS.fromList[1..n]) 0 . reverse $ take i ds\n where\n go !unused !acc (x:xs)\n | IS.member x unused = go (IS.delete x unused) (acc+arr!x) xs\n | otherwise = go unused (max 0 $ acc-1) xs\n go _ acc [] = acc <= 0\n\nlowerBound :: (Integral i) => i -> i -> (i -> Bool) -> i\nlowerBound low high p = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine :: IO [Int]\n ds <- map readInt.B.words <$> B.getLine\n xs <- map (fromIntegral.readInt).B.words <$> B.getLine\n print $ solve n m ds xs\n\nsolve :: Int -> Int -> [Int] -> [Int64] -> Int\nsolve n m ds xs\n | isOK n = lowerBound 1 n isOK\n | otherwise = -1\n where\n arr :: UArray Int Int64\n arr = listArray (1, m) xs\n isOK i = go (IS.fromList[1..n]) 0 . reverse $ take i ds\n where\n go !unused !acc (x:xs)\n | IS.member x unused = go (IS.delete x unused) (acc+arr!x) xs\n | otherwise = go unused (acc-1) xs\n go _ acc [] = acc <= 0\n\nlowerBound :: (Integral i) => i -> i -> (i -> Bool) -> i\nlowerBound low high p = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}"}], "src_uid": "ab31ad331748994ddeb08be646d0787e"} {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.Int ( Int64 )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int64\r\n a <- readMany :: IO [Int64]\r\n let m = sum a `mod` n\r\n print (m * (n - m))\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int \r\n arr <- map read.words <$> getLine :: IO [Int]\r\n let s = sum arr\r\n k = s `mod` n\r\n print (k * (n - k))\r\n\r\nmain = do\r\n test <- readLn :: IO Int\r\n replicateM_ test solve"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn\r\n a <- readInts\r\n let\r\n s = sum a\r\n miss = s `rem` n\r\n print $ (n - miss) * miss"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int64\n s <- getLine\n let a = map read $ words s :: [Int64]\n su = sum a\n (high, low) = (rem su n, n - (rem su n))\n res = high*low\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Integer\r\n a <- readInts\r\n let m = mod (sum a) n\r\n r = m * (n-m)\r\n print r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "module Main where\nimport Control.Monad ( replicateM )\nimport Data.Foldable ( traverse_ )\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int \n inp <- replicateM t $ do\n n <- read <$> getLine :: IO Integer\n arr <- map read . words <$> getLine :: IO [Integer]\n return (n, arr)\n let solved1 = zip [0..] inp\n let solved = map solve solved1\n -- print inp\n traverse_ putStrLn solved\n\nsolve :: (Int, (Integer, [Integer])) -> String\nsolve (tc, (n, arr)) = \n let\n sm = sum arr\n -- avg = div sm n\n k = mod sm n\n -- lft = sm - avg * n\n in\n -- if tc == 6\n -- then unwords $ map show arr\n -- else show $ k * (n - k)\n show $ k * (n - k)\n\n"}], "negative_code": [{"source_code": "module Main where\nimport Control.Monad ( replicateM )\nimport Data.Foldable ( traverse_ )\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int \n inp <- replicateM t $ do\n n <- read <$> getLine :: IO Int\n arr <- map read . words <$> getLine :: IO [Int]\n return (n, arr)\n let solved1 = zip [0..] inp\n let solved = map solve solved1\n -- print inp\n traverse_ putStrLn solved\n\nsolve :: (Int, (Int, [Int])) -> String\nsolve (tc, (n, arr)) = \n let\n sm = sum arr\n -- avg = div sm n\n k = mod sm n\n -- lft = sm - avg * n\n in\n if tc == 6\n then unwords $ map show arr\n else show $ k * (n - k)\n\n"}, {"source_code": "module Main where\nimport Data.List ( intercalate ) \nmain :: IO ()\nmain = interact solve \n\nsolve :: String -> String\nsolve inp = \n let\n inps = drop 1 . lines $ inp\n ans = [map read . words $ j | (i, j) <- zip [0..] inps, odd i] :: [[Int]]\n sans = map (show . slv) ans\n\n in\n unlines sans\n\nslv :: [Int] -> Int \nslv arr = \n let\n n = length arr\n sm = sum arr\n k = mod sm n\n in\n k * (n - k)\n"}, {"source_code": "module Main where\nimport Control.Monad ( replicateM )\nimport Data.Foldable ( traverse_ )\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int \n inp <- replicateM t $ do\n n <- read <$> getLine :: IO Int\n arr <- map read . words <$> getLine :: IO [Int]\n return (n, arr)\n let solved = map solve inp\n -- print inp\n traverse_ print solved\n\nsolve :: (Int, [Int]) -> Int\nsolve (n, arr) = \n let\n sm = sum arr\n -- avg = div sm n\n k = mod sm n\n -- lft = sm - avg * n\n in\n k * (n - k)\n\n"}, {"source_code": "module Main where\nimport Control.Monad ( replicateM )\nimport Data.Foldable ( traverse_ )\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int \n inp <- replicateM t $ do\n n <- read <$> getLine :: IO Int\n arr <- map read . words <$> getLine :: IO [Int]\n return (n, arr)\n let solved = map solve inp\n -- print inp\n traverse_ print solved\n\nsolve :: (Int, [Int]) -> Int\nsolve (n, arr) = \n let\n sm = sum arr\n avg = div sm n\n lft = sm - avg * n\n in\n lft * (n - lft)\n"}], "src_uid": "935bceb69117d06eb75121c805bff69c"} {"source_code": "module Main where\n\nimport Data.List\nimport Data.Set (toList, fromList)\n\nother \"First\" = \"Second\"\nother \"Second\" = \"First\"\n\ncountAllElems xs = reverse . sort . map counter . uniques $ xs\n where \n uniques = toList . fromList\n counter c = length $ filter (== c) xs\n\ncanPalindrome xs = countOdds < 2\n where countOdds = length . filter odd $ xs\n\nfindFirst p xs = findFirst' p xs 0\nfindFirst' p [] _ = Nothing\nfindFirst' p (x:xs) ind\n | p x = (Just (x, ind))\n | otherwise = findFirst' p xs (ind+1) \n\nreplace i e xs = (take i xs) ++ [e] ++ (drop (i+1) xs)\n\nmakeMove xs = filter (> 0) . mkmv . findFirst even $ xs\n where\n mkmv (Just (c, i)) = replace i (c-1) xs\n mkmv Nothing = replace 0 (head xs - 1) xs\n\ncanWin plr xs\n | canPalindrome xs = plr\n | otherwise = canWin (other plr) (makeMove xs)\n\nmain = do\n starting <- getLine\n putStrLn . canWin \"First\" . countAllElems $ starting\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n s <- getLine\n let t = length $ filter odd $ map length $ group $ sort s\n putStrLn $ if t == 0 || odd t then \"First\" else \"Second\"\n"}, {"source_code": "import Data.Array (accumArray, elems)\n\nsolve :: String -> String\nsolve s\n | odd countOdd || countOdd == 0 = \"First\"\n | otherwise = \"Second\"\n where\n countOdd = length $ filter odd $ elems array\n array = accumArray (+) 0 ('a', 'z') $ zip s $ repeat 1\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve"}, {"source_code": "import Data.Array.Base\nmain=getLine>>=putStrLn.f.unsafeAccumArray (+) 0 (0,128) . (`zip`(repeat 1)) . map fromEnum\nf :: UArray Int Int -> String\nf arr\n | n > 0 && even n = \"Second\"\n | otherwise = \"First\"\n where\n xs = map (unsafeAt arr) [fromEnum 'a'..fromEnum 'z']\n n = length $ filter odd xs\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nodds :: String -> Int\nodds = (foldl (+) 0) . map ((`mod` 2) . length) . group . sort\n\nsolve :: String -> String\nsolve str = if odds str == 0 || (odds str) `mod` 2 == 1\n then \"First\"\n else \"Second\"\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "import Data.List\nclassify list = classify' (tail list) (head list) 1\n\nclassify' [] char pat = [pat]\nclassify' list char pat\n | (head list) /= char = pat : (classify' (tail list) (head list) 1)\n | otherwise = classify' (tail list) char (pat + 1)\n\nmain = do\n input <- getContents\n let sorted = Data.List.sort $ head $ lines input\n let classified = filter (\\x -> x `mod` 2 == 1) $ classify sorted\n let total = length classified\n let res = if total == 0 || total `mod` 2 == 1 then \"First\" else \"Second\"\n putStrLn res\n"}], "negative_code": [{"source_code": "import Data.List\nclassify list = classify' (tail list) (head list) 1\n\nclassify' [] char pat = [pat]\nclassify' list char pat\n | (head list) /= char = pat : (classify' (tail list) (head list) 1)\n | otherwise = classify' (tail list) char (pat + 1)\n\nmain = do\n input <- getContents\n let sorted = Data.List.sort $ head $ lines input\n let total = sum $ classify sorted\n let res = if total `mod` 2 == 0 then \"Second\" else \"First\"\n putStrLn res\n"}], "src_uid": "bbf2dbdea6dd3aa45250ab5a86833558"} {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- reverse . sort <$> getIntegers\n putStrLn case flip compare 0 $ solve a True 0 of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\nsolve [] _ ans = ans\nsolve (a : as) True ans = solve as False $ ans + if even a then a else 0\nsolve (a : as) False ans = solve as True $ ans - if odd a then a else 0\n\nalice n = (if even n then n else 0, 0)\n\nbob n = (0, if odd n then n else 0)\n\ngd :: Down a -> a\ngd (Down x) = x\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (_ : ns : rest) = ((:[]). solve . linetois) (ns) ++ tcio (rest) \r\n linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n\r\nsolve :: [Integer] -> String\r\nsolve ns \r\n |a>b = \"Alice\"\r\n |b>a = \"Bob\"\r\n |otherwise = \"Tie\" where\r\n (a,b) = rec (reverse $ sort $ ns) (0,0)\r\n\r\nrec [] (a,b)= (a,b)\r\nrec [k] (a,b) = if even k then (a+k,b) else (a,b)\r\nrec (k1:k2:ks) (a,b) = rec ks (if even k1 then a+k1 else a, if odd k2 then b+k2 else b)\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int -- Int is 32-bit on CF...\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- map read . words <$> getLine :: IO [Int64]\n let\n eoT = sum [if even x then x else 0-x | x <- a]\n -- sort is so slow! hopefully OK with 2e5?\n abT = sum [x * y | (x, y) <- zip (cycle [1, 0-1]) (reverse $ sort a)]\n putStrLn $ case compare 0 $ eoT + abT of\n LT -> \"Alice\"\n EQ -> \"Tie\"\n GT -> \"Bob\"\n"}, {"source_code": "import Prelude\nimport Data.Int\nimport Data.List\n\npairplus :: (Int64,Int64) -> (Int64,Int64) -> (Int64,Int64)\npairplus (a,b) (c,d) = (a+c,b+d)\n\ngame :: Int64 -> [Int64] -> (Int64,Int64)\ngame _ [] = (0,0)\ngame n (x:xs) = if (mod n 2 == 0) then (if (mod x 2==0)then pairplus(x,0)rec else rec) else (if(mod x 2==1)then pairplus(0,x)rec else rec) where rec = game (n+1) xs\n\nresult :: (Int64,Int64) -> String\nresult (a,b) | a == b = \"Tie\"\n | a > b = \"Alice\"\n | otherwise = \"Bob\"\n\neveryother :: [a] -> [a]\neveryother [] = []\neveryother (x:y:xs) = y : (everyother xs)\neveryother (x:xs) = []\n\nreadL :: String -> [Int64]\nreadL list = map read $ words list\n\nsolve :: String -> String\nsolve string = list where list = concat $ intersperse \"\\n\" $ map result $ map (game 0) $ map (reverse . sort) $ map readL $ everyother $ tail $ lines string\n\nmain :: IO ()\nmain = interact $ solve\n"}], "negative_code": [{"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- reverse . sort <$> getInts\n putStrLn case flip compare 0 $ solve a True 0 of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\nsolve [] _ ans = ans\nsolve (a : as) True ans = solve as False $ ans + if even a then a else 0\nsolve (a : as) False ans = solve as True $ ans - if odd a then a else 0\n\nalice n = (if even n then n else 0, 0)\n\nbob n = (0, if odd n then n else 0)\n\ngd :: Down a -> a\ngd (Down x) = x\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- map gd . sort . map Down <$> getInts\n putStrLn case flip compare 0 $ solve a True 0 of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\nsolve [] _ ans = ans\nsolve (a : as) True ans = solve as False $ ans + if even a then a else 0\nsolve (a : as) False ans = solve as True $ ans - if odd a then a else 0\n\nalice n = (if even n then n else 0, 0)\n\nbob n = (0, if odd n then n else 0)\n\ngd :: Down a -> a\ngd (Down x) = x\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- map gd . sort . map Down <$> getInts\n guard $ length a == n\n putStrLn\n case\n uncurry compare\n . foldl (both2 (+)) (0, 0)\n . zipWith ($) (cycle [alice, bob])\n $ a\n of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\nalice n = (if even n then n else 0, 0)\n\nbob n = (0, if odd n then n else 0)\n\ngd :: Down a -> a\ngd (Down x) = x\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- map gd . sort . map Down <$> getInts\n putStrLn\n case\n uncurry compare\n . foldl (both2 (+)) (0, 0)\n . zipWith ($) (cycle [alice, bob])\n $ a\n of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\nalice n = (if even n then n else 0, 0)\n\nbob n = (0, if odd n then n else 0)\n\ngd :: Down a -> a\ngd (Down x) = x\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- map gd . sort . map Down <$> getInts\n putStrLn\n case flip compare 0 . sum . zipWith ($) (cycle [alice, bob]) $ a of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\nalice n = if even n then n else 0\n\nbob n = if odd n then -n else 0\n\ngd :: Down a -> a\ngd (Down x) = x\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- map gd . sort . map Down <$> getInts\n putStrLn\n case flip compare 0 . sum . zipWith s (cycle [True, False]) $ a of\n LT -> \"Bob\"\n EQ -> \"Tie\"\n GT -> \"Alice\"\n\ns True n | odd n = 0\n | otherwise = n\n\ns False n | odd n = -n\n | otherwise = 0\n\ngd (Down x) = x\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (_ : ns : rest) = ((:[]). solve . linetois) (ns) ++ tcio (rest) \r\n linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n\r\nsolve :: [Int] -> String\r\nsolve ns \r\n |a>b = \"Alice\"\r\n |b>a = \"Bob\"\r\n |otherwise = \"Tie\" where\r\n (a,b) = rec (reverse $ sort $ ns) (0,0)\r\n\r\nrec [] (a,b)= (a,b)\r\nrec [k] (a,b) = if even k then (a+k,b) else (a,b)\r\nrec (k1:k2:ks) (a,b) = rec ks (if even k1 then a+k1 else a, if odd k2 then b+k2 else b)\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- map read . words <$> getLine :: IO [Int]\n let\n eoT = sum [if even x then x else 0-x | x <- a]\n -- sort is so slow! hopefully OK with 2e5?\n abT = sum [x * y | (x, y) <- zip (cycle [1, 0-1]) (reverse $ sort a)]\n putStrLn $ case compare 0 $ eoT + abT of\n LT -> \"Alice\"\n EQ -> \"Tie\"\n GT -> \"Bob\"\n"}], "src_uid": "b1e911fbc33fb031b2398cdd545f502a"} {"source_code": "{-# LANGUAGE FlexibleInstances, UndecidableInstances, DuplicateRecordFields #-}\n\nmodule Main where\n\nimport Control.Monad\nimport System.IO\n\nca2 0 = 0\nca2 n = 1 + 2*(n-1)\n\ncalc x y = 2 * x + ca2 (y - x)\n \n\ncalculate x y = do\n let x1 = max x y\n let y1 = min x y\n calc y1 x1\n\n\n\nmain :: IO()\nmain = do\n t <- readLn :: IO Int\n forM_ [1..t] $ \\t_itr -> do\n nmsTemp <- getLine\n let nms = words nmsTemp\n let x = read (nms !! 0) :: Int\n let y = read (nms !! 1) :: Int\n let result = calculate x y \n putStrLn(show result)\n\n", "positive_code": [{"source_code": "import Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map read . words) `fmap` getLine :: IO [Int]\n\nmain = do\n\tn <- getInt\n\tforM_ [1..n] $ \\_ -> do\n\t\t[x, y] <- getInts\n\t\tlet common = min x y\n\t\tlet rest = x + y - common - common\n\t\tlet answer = (common * 2) + (max 0 (rest * 2 - 1))\n\t\tprint answer\n"}], "negative_code": [], "src_uid": "8864c6a04fed970fcbc04e220df9d88d"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nmain = do\n let int = fst .fromJust . B.readInteger\n ints = map int . B.words\n n <- readLn :: IO Int\n as <- ints <$> B.getLine\n let (b,c) = splitAt (n`div`2) $ sort as\n print $ sum $ map (^2) $ zipWith (+) b $ reverse c\n", "positive_code": [{"source_code": "-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n-- {-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE NumDecimals #-}\n-- {-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- sort <$> readInts\n\tlet\n\t\trev = reverse as\n\tprint $ sum $ map ( ^ 2 ) $ zipWith (+) as $ take ( n `div` 2 ) rev"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let as = runSTUArray $ do\n as <- A.newListArray (0,n-1) (map fromIntegral as_ :: [Int64])\n sortMArray as\n return as\n print $ sum $ [ (as A.! i + as A.! (n-i-1))^2\n | i <- [0..n `shiftR` 1 - 1]]\n\ntype Comparison e = e -> e -> Ordering\n\n\n{-# INLINE sortMArray #-}\nsortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)\n => a i e -> m ()\nsortMArray = sortMArrayBy compare\n\n{-# INLINE sortMArrayBy #-}\nsortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> m ()\nsortMArrayBy cmp = \\arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr\n\n\n-- sort the interval [l,u] of arr.\n{-# INLINE sortMArrayByBounds #-}\nsortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> (i,i) -> m ()\nsortMArrayByBounds cmp = \\arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)\n\n-- sort the interval [l,u) of arr.\n{-# INLINE sortMArrayByBounds_ #-}\nsortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> i -> i -> m ()\nsortMArrayByBounds_ cmp = \\arr l u -> do\n let len = u - l\n tmp <- A.newArray_ (0,len `shiftR` 1 - 1)\n mergesort cmp arr tmp l u\n\nmergesort cmp arr tmp l u\n | u - l <= 1 = return ()\n | otherwise = do mergesort cmp arr tmp l mid\n mergesort cmp arr tmp mid u\n merge cmp arr tmp l mid u\n where\n len = u - l\n mid = (u + l) `shiftR` 1\n\n{-# INLINE merge #-}\nmerge :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()\nmerge cmp arr tmp l mid u = do\n copyMArray arr (l,mid-1) tmp (0,mml-1)\n eLow <- A.readArray tmp 0\n eHigh <- A.readArray arr mid\n loop eLow 0 eHigh mid l\n where\n mml = mid - l\n loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of\n LT -> do A.writeArray arr iIns eHigh\n wroteHigh eLow iLow (iHigh+1) (iIns+1)\n _ -> do A.writeArray arr iIns eLow\n wroteLow (iLow+1) eHigh iHigh (iIns+1)\n wroteHigh !eLow !iLow !iHigh !iIns\n | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)\n | otherwise = do eHigh <- A.readArray arr iHigh\n loop eLow iLow eHigh iHigh iIns\n wroteLow !iLow !eHigh !iHigh !iIns\n | iLow >= mml = return ()\n | otherwise = do eLow <- A.readArray tmp iLow\n loop eLow iLow eHigh iHigh iIns\n\n{-# INLINE copyMArray #-}\ncopyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)\n => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()\ncopyMArray src srcRange dst dstRange =\n forM_ (zip (A.range srcRange) (A.range dstRange))\n $ \\(i,j) -> A.writeArray dst j =<< A.readArray src i\n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let (pre,suf) = splitAt (shiftR n 1) $ sort $ map fromIntegral as\n :: ([Int64],[Int64])\n print $ sum $ map (^2) $ zipWith (+) pre $ reverse suf\n\n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let (pre,suf) = splitAt (shiftR n 1) $ sort $ map fromIntegral as\n :: ([Int64],[Int64])\n print $ sum $ map (^2) $ zipWith (+) pre $ reverse suf\n\n \n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\ndiv2 = (flip div) 2 \nzipEnd xs = zip xs (reverse $ drop (div2 (length xs)) xs)\n\nsolve :: [Int] -> Integer\nsolve = sum \n . map (^2)\n . map toInteger\n . map (uncurry (+))\n . zipEnd \n . sort\n\nmain :: IO ()\nmain = do\n _ <- readInt\n v <- readInts\n print $ solve v"}, {"source_code": "import Data.Int\nimport Data.List\nmain = interact $ show . solve . map read . words\nsolve (n:as) = sum $ genericTake (n `div` 2) $ map (^2) $ zipWith (+) s (reverse s)\n where s = sort as :: [Int64]\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nmain = do\n let int = fst .fromJust . B.readInt\n ints = map int . B.words\n n <- readLn :: IO Int\n as <- ints <$> B.getLine\n let (b,c) = splitAt (n`div`2) $ sort as\n print $ sum $ map (^2) $ zipWith (+) b $ reverse c\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let as = runSTUArray $ do\n as <- A.newListArray (0,n-1) as_\n sortMArray as\n return as\n print $ sum $ [ (as A.! i + as A.! (n-i-1))^2\n | i <- [0..n `shiftR` 1 - 1]]\n\ntype Comparison e = e -> e -> Ordering\n\n\n{-# INLINE sortMArray #-}\nsortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)\n => a i e -> m ()\nsortMArray = sortMArrayBy compare\n\n{-# INLINE sortMArrayBy #-}\nsortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> m ()\nsortMArrayBy cmp = \\arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr\n\n\n-- sort the interval [l,u] of arr.\n{-# INLINE sortMArrayByBounds #-}\nsortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> (i,i) -> m ()\nsortMArrayByBounds cmp = \\arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)\n\n-- sort the interval [l,u) of arr.\n{-# INLINE sortMArrayByBounds_ #-}\nsortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> i -> i -> m ()\nsortMArrayByBounds_ cmp = \\arr l u -> do\n let len = u - l\n tmp <- A.newArray_ (0,len `shiftR` 1 - 1)\n mergesort cmp arr tmp l u\n\nmergesort cmp arr tmp l u\n | u - l <= 1 = return ()\n | otherwise = do mergesort cmp arr tmp l mid\n mergesort cmp arr tmp mid u\n merge cmp arr tmp l mid u\n where\n len = u - l\n mid = (u + l) `shiftR` 1\n\n{-# INLINE merge #-}\nmerge :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()\nmerge cmp arr tmp l mid u = do\n copyMArray arr (l,mid-1) tmp (0,mml-1)\n eLow <- A.readArray tmp 0\n eHigh <- A.readArray arr mid\n loop eLow 0 eHigh mid l\n where\n mml = mid - l\n loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of\n LT -> do A.writeArray arr iIns eHigh\n wroteHigh eLow iLow (iHigh+1) (iIns+1)\n _ -> do A.writeArray arr iIns eLow\n wroteLow (iLow+1) eHigh iHigh (iIns+1)\n wroteHigh !eLow !iLow !iHigh !iIns\n | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)\n | otherwise = do eHigh <- A.readArray arr iHigh\n loop eLow iLow eHigh iHigh iIns\n wroteLow !iLow !eHigh !iHigh !iIns\n | iLow >= mml = return ()\n | otherwise = do eLow <- A.readArray arr iLow\n loop eLow iLow eHigh iHigh iIns\n\n{-# INLINE copyMArray #-}\ncopyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)\n => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()\ncopyMArray src srcRange dst dstRange =\n forM_ (zip (A.range srcRange) (A.range dstRange))\n $ \\(i,j) -> A.writeArray dst j =<< A.readArray src i\n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let (pre,suf) = splitAt (shiftR n 1) $ sort as\n print $ sum $ map (^2) $ zipWith (+) pre $ reverse suf\n\n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as_ <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let as = runSTUArray $ do\n as <- A.newListArray (0,n-1) as_\n sortMArray as\n return as\n print $ sum $ [ (as A.! i + as A.! (n-i-1))^2\n | i <- [0..n `shiftR` 1 - 1]]\n\ntype Comparison e = e -> e -> Ordering\n\n\n{-# INLINE sortMArray #-}\nsortMArray :: (MArray a e m, Ord e, A.Ix i, Integral i, Bits i)\n => a i e -> m ()\nsortMArray = sortMArrayBy compare\n\n{-# INLINE sortMArrayBy #-}\nsortMArrayBy :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> m ()\nsortMArrayBy cmp = \\arr -> A.getBounds arr >>= sortMArrayByBounds cmp arr\n\n\n-- sort the interval [l,u] of arr.\n{-# INLINE sortMArrayByBounds #-}\nsortMArrayByBounds :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> (i,i) -> m ()\nsortMArrayByBounds cmp = \\arr (l,u) -> sortMArrayByBounds_ cmp arr l (u+1)\n\n-- sort the interval [l,u) of arr.\n{-# INLINE sortMArrayByBounds_ #-}\nsortMArrayByBounds_ :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> i -> i -> m ()\nsortMArrayByBounds_ cmp = \\arr l u -> do\n let len = u - l\n tmp <- A.newArray_ (0,len `shiftR` 1 - 1)\n mergesort cmp arr tmp l u\n\nmergesort cmp arr tmp l u\n | u - l <= 1 = return ()\n | otherwise = do mergesort cmp arr tmp l mid\n mergesort cmp arr tmp mid u\n merge cmp arr tmp l mid u\n where\n len = u - l\n mid = (u + l) `shiftR` 1\n\n{-# INLINE merge #-}\nmerge :: (MArray a e m, A.Ix i, Integral i, Bits i)\n => Comparison e -> a i e -> a i e -> i -> i -> i -> m ()\nmerge cmp arr tmp l mid u = do\n copyMArray arr (l,mid-1) tmp (0,mml-1)\n eLow <- A.readArray tmp 0\n eHigh <- A.readArray arr mid\n loop eLow 0 eHigh mid l\n where\n mml = mid - l\n loop !eLow !iLow !eHigh !iHigh !iIns = case cmp eHigh eLow of\n LT -> do A.writeArray arr iIns eHigh\n wroteHigh eLow iLow (iHigh+1) (iIns+1)\n _ -> do A.writeArray arr iIns eLow\n wroteLow (iLow+1) eHigh iHigh (iIns+1)\n wroteHigh !eLow !iLow !iHigh !iIns\n | iHigh >= u = copyMArray tmp (iLow,mml-1) arr (iIns,u-1)\n | otherwise = do eHigh <- A.readArray arr iHigh\n loop eLow iLow eHigh iHigh iIns\n wroteLow !iLow !eHigh !iHigh !iIns\n | iLow >= mml = return ()\n | otherwise = do eLow <- A.readArray tmp iLow\n loop eLow iLow eHigh iHigh iIns\n\n{-# INLINE copyMArray #-}\ncopyMArray :: (MArray a0 e m, A.Ix i0, MArray a1 e m, A.Ix i1)\n => a0 i0 e -> (i0,i0) -> a1 i1 e -> (i1,i1) -> m ()\ncopyMArray src srcRange dst dstRange =\n forM_ (zip (A.range srcRange) (A.range dstRange))\n $ \\(i,j) -> A.writeArray dst j =<< A.readArray src i\n \n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\ndiv2 = (flip div) 2 \nzipEnd xs = zip xs (reverse $ drop (div2 (length xs)) xs)\n\nsolve :: [Int] -> Int\nsolve = sum \n . map (^2)\n . map (uncurry (+))\n . zipEnd \n . sort\n\nmain :: IO ()\nmain = do\n _ <- readInt\n v <- readInts\n print $ solve v"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . words\nsolve (n:as) = sum $ take (n `div` 2) $ zipWith (*) s (reverse s)\n where s = sort as\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . words\nsolve (n:as) = sum $ take (n `div` 2) $ map (^2) $ zipWith (+) s (reverse s)\n where s = sort as\n"}], "src_uid": "28c555fefd5c36697a5082c61d8a82b3"} {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInt\nreadInts = (readInt <$>) . B.words\n\nchi\u1ebfn :: [Int64] -> Int64 -> Int64 -> Double\nchi\u1ebfn as n k = sum $ map (\\p -> (fromIntegral p) / d) $ scanl (\\p (hf, hs) -> p - hf + hs) (sum f) $ zip (f ++ s) s\n where\n (f, s) = splitAt (fromIntegral k) as\n d = fromIntegral $ n - k + 1\n\n\nmain = do\n n:k:_ <- readInts <$> B.getLine\n as <- readInts <$> B.getLine\n print $ chi\u1ebfn as n k\n\n", "positive_code": [{"source_code": "-- Codeforces 808B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# OPTIONS_GHC -optc-ffast-math #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n (n:k:xs) <- (map (fromIntegral . fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents :: IO [Int64]\n let v = min k (n - k + 1)\n s = sum $ zipWith (\\x i -> if | i <= v -> i * x\n | i > v && i <= n - v -> v * x\n | i > n - v -> (n - i + 1) * x) xs [1..]\n s' = fromIntegral s :: Double\n t' = fromIntegral (n - k + 1) :: Double\n print (s' / t')\n"}, {"source_code": "\n{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nrun [] _ _ _ ans = ans\nrun (x:xs) i n k ans = run xs (i + 1) n k (fromIntegral ((minimum [n - i + 1, i, k, n - k + 1]) * x) + ans)\n\nmain = do\n (map read . words -> [n, k]) <- getLine\n (map read . words -> (xs :: [Integer])) <- getLine\n print $ run xs 1 n k 0.0 / fromIntegral (n - k + 1)\n"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nchi\u1ebfn as n k = (fromIntegral $ sum $ scanl (\\p (hf, hs) -> p - hf + hs) (sum f) $ zip (f ++ s) s) / (fromIntegral $ n - k + 1)\n where\n (f, s) = splitAt k as\n\n\nmain = do\n n:k:_ <- readInts <$> B.getLine\n as <- readInts <$> B.getLine\n print $ chi\u1ebfn as n k\n\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nchi\u1ebfn as n k = sum $ map (\\p -> (fromIntegral p) / d) $ scanl (\\p (hf, hs) -> p - hf + hs) (sum f) $ zip (f ++ s) s\n where\n (f, s) = splitAt k as\n d = fromIntegral $ n - k + 1\n\n\nmain = do\n n:k:_ <- readInts <$> B.getLine\n as <- readInts <$> B.getLine\n print $ chi\u1ebfn as n k\n\n"}, {"source_code": "-- Codeforces 808B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# OPTIONS_GHC -optc-ffast-math #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n (n:k:xs) <- (map (fromIntegral . fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents :: IO [Int64]\n let s = sum $ zipWith (\\x i -> if | i < k -> i * x\n | i >= k && i <= n - k -> k * x\n | i > n - k -> (n - i + 1) * x) xs [1..]\n s' = fromIntegral s :: Double\n t' = fromIntegral (n - k + 1) :: Double\n print (s' / t')\n"}, {"source_code": "\n{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns #-}\n\nrun [] _ _ _ ans = ans\nrun (x:xs) i n k ans = run xs (i + 1) n k (fromIntegral ((minimum [n - i + 1, i, k]) * x) + ans)\n\nmain = do\n (map read . words -> [n, k]) <- getLine\n (map read . words -> xs) <- getLine\n print $ run xs 1 n k 0.0 / fromIntegral (n - k + 1)\n"}], "src_uid": "838e643a978adbeed791a24ac1046ab5"} {"source_code": "import Data.Char\nimport Data.List\nimport Control.Monad\n\nresult x = replicate (div (3*x) 4) '9' ++ replicate (x - (div (3*x) 4)) '8'\n\nmain = do\n tests <- getLine\n a <- getContents\n putStr $ intercalate \"\\n\" [ result (read x :: Int) | x <- words a ] \n", "positive_code": [{"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Int\n c = (n + 3) `div` 4\n putStrLn $ replicate (n - c) '9' ++ replicate c '8'\n \n iter :: Int -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Int)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n let c = (n - 1) `div` 4 + 1\n putStrLn $ replicate (n - c) '9' ++ replicate c '8'\n"}], "negative_code": [], "src_uid": "80c75a4c163c6b63a614075e094ad489"} {"source_code": "base = 1000000007 :: Integer\n\nn_choose_k :: Int -> Int -> Integer\nn_choose_k n k = chooseTab !! n !! k\n\nchooseTab :: [[Integer]]\nchooseTab = [[ chooseDef n k | k <- [0..n]] | n <- [0..]]\n\nchooseDef :: Int -> Int -> Integer\nchooseDef n k\n | k == 0 || k == n = 1\n | k == 1 = toInteger n\n | otherwise = mod (n_choose_k (n-1) (k-1) + n_choose_k (n-1) k) base\n\nsolveTask :: (Int, Int) -> Integer\nsolveTask (n, m) =\n let k' = 2*m\n n' = n + k' -1\n in n_choose_k n' k'\n\ngroupTaskInput :: [String] -> [(Int, Int)]\ngroupTaskInput [] = []\ngroupTaskInput (n:(d:xs)) = (read n, read d) : groupTaskInput(xs)\n\nmakeTaskInput :: String -> [(Int, Int)]\nmakeTaskInput s = groupTaskInput . words $ s\n\nsolve :: String -> String\nsolve s = concat $ (map (++ \"\\n\") ) $ (map $ show.solveTask) $ makeTaskInput s\n\nmain' :: IO ()\nmain' = do interact $ solve\n\nmain = main'\n\n", "positive_code": [{"source_code": "import Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\n\n\n\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn(s)\n\nmain_ :: EIO ()\nmain_ = do\n (n, m) <- liftM2 (,) get get :: EIO (Int, Int)\n putln $ f1 n m\n\nf1 :: Int -> Int -> Int64\nf1 n m = let a = runSTUArray $ do\n arr <- newArray ((0, 0), (n+1, m)) 0 :: ST s (STUArray s (Int, Int) Int64)\n forM_ [0..n] $ \\j -> writeArray arr (j, 0) 1\n forM_ [1..m-1] $ \\i ->\n forM_ [0..n] $ \\j ->\n forM_ [0..j] $ \\k -> do\n a <- readArray arr (j, i)\n b <- readArray arr (k, i - 1)\n writeArray arr (j, i) $ (mod (a + b) 1000000007)\n return arr in\n let v = do\n x <- [1..n]\n y <- [1..n]\n [(x, y)] in\n let x = filter (\\(x, y) -> x <= y) v in\n foldl (\\s (x, y) -> mod (s + (a ! (x - 1, m - 1)) * (a ! (n - y, m - 1))) 1000000007) 0 x\n\n\n"}, {"source_code": "import System.IO\nimport Data.Array\n\nreadInt :: IO Int\nreadInt = readLn\n\ncastToInteger x = read x::Integer\n\n\nmain = do\n line <- getLine\n let test_case = (map castToInteger . take 2 . words) line\n solveTask test_case\n\n\nsolveTask :: [Integer] -> IO ()\nsolveTask [n, m] = do\n let dpVs = getDp m n\n let res = foldl modSum 0 [\n modProd (dpVs!i) (dpVs!(n-j+1)) |\n i <- [1..n], j <- [i..n]]\n print res\n return ()\n\n\n-- getDp i n =\n-- array (1,n) [(j, foldl modSum 0 [dp!(j') | j' <- [1..j]]) | j <- [1..n]]\n-- where dp = getDp (i-1) n\ngetDp :: Integer -> Integer -> Array Integer Integer\ngetDp i n = array (1,n) $ enumerate $ getDpList i n\n\ngetDpList :: Integer -> Integer -> [Integer]\ngetDpList 1 n = [1 | i <- [1..n]]\ngetDpList i n = prefSum dp\n where dp = getDpList (i-1) n\n\n\nprefSum :: [Integer] -> [Integer]\nprefSum xs = prefSum' 0 xs\nprefSum' agg [] = []\nprefSum' agg (x:xs) = s : prefSum' s xs\n where s = modSum agg x\n\nenumerate :: [Integer] -> [(Integer, Integer)]\nenumerate xs = enumerate' 1 xs\nenumerate' i [] = []\nenumerate' i (x:xs) = (i, x) : enumerate' (i+1) xs\n\n\ncustomMod :: Integer\ncustomMod = 10^9 + 7\n\nmodSum :: Integer -> Integer -> Integer\nmodSum a b = if a + b < customMod then a + b else a + b - customMod\n\nmodProd :: Integer -> Integer -> Integer\nmodProd a b = (a * b) `mod` customMod\n\ncount :: [Integer] -> Integer\ncount [] = 0\ncount (x:xs) = 1 + count xs\n\n"}, {"source_code": "import System.IO\nimport Data.Array\n\nreadInt :: IO Int\nreadInt = readLn\n\ncastToInteger x = read x::Integer\n\n\nmain = do\n line <- getLine\n let test_case = (map castToInteger . take 2 . words) line\n solveTask test_case\n\n\nsolveTask :: [Integer] -> IO ()\nsolveTask [n, m] = do\n let dpVs = getDp m n\n let res = foldl modSum 0 [\n modProd (dpVs!i) (dpVs!(n-j+1)) |\n i <- [1..n], j <- [i..n]]\n print res\n return ()\n\n\ngetDp :: Integer -> Integer -> Array Integer Integer\ngetDp 1 n = array (1,n) [(i, 1) | i <- [1..n]]\ngetDp i n =\n array (1,n) [(j, foldl modSum 0 [dp!(j') | j' <- [1..j]]) | j <- [1..n]]\n where dp = getDp (i-1) n\n\n\ncustomMod :: Integer\ncustomMod = 10^9 + 7\n\nmodSum :: Integer -> Integer -> Integer\nmodSum a b = if a + b < customMod then a + b else a + b - customMod\n\nmodProd :: Integer -> Integer -> Integer\nmodProd a b = (a * b) `mod` customMod\n\ncount :: [Integer] -> Integer\ncount [] = 0\ncount (x:xs) = 1 + count xs\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport qualified Data.Map.Strict as M\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\noutput :: Show a => [a] -> IO ()\noutput = putStrLn <$> unwords <$> map show\n\nc n k = product [n-k+1..n] `div` product [1..k]\n\n_mod = 1000000007\n\nmain = do\n [n,m] <- input\n print (c (2*m+n-1) (2*m) `mod` _mod)\n"}, {"source_code": "\niter :: [Integer] -> [Integer]\niter xs = tail $ scanl (+) 0 xs\n\ncal :: Int -> Int -> [Integer]\ncal n 1 = take n $ repeat 1\ncal n m =\n let ls = cal n 1\n itf = foldl (.) (id) $ take (m - 1) $ repeat (iter)\n in\n itf ls\n-- let a = cal n (m - 1)\n-- b = cal (n - 1) m\n-- v = foldr (+) 0 a\n-- in\n-- b ++ [v]\n\n\n\ncalSum :: Int -> Int -> Integer -> Integer\ncalSum n m d =\n let\n xs = map (`mod` d) $ cal n m\n ss = reverse $ tail $ scanl (+) 0 xs\n in\n (`mod` d) . sum $ zipWith ((*)) xs ss\n\n\nmain :: IO ()\nmain = do\n line <- getLine\n let (n:m:[]) = map (read :: String -> Int) $ words line\n putStrLn $ show $ calSum n m 1000000007"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.Array.IArray\n\na # b = chooses ! (a, b)\n\nchooses :: Array (Int, Int) Integer\nchooses = array ((0, 0), (1100, 1100)) [((a, b), choose a b) | a <- [0..1100], b <- [0..1100]]\n\nchoose a b\n | b < 0 || b > a = 0\n | b == 0 || a == b = 1\n | otherwise = mod ((a - 1) # (b - 1) + (a - 1) # b) 1000000007\n\nmain = getContents >>= print.(\\(n:m:_) -> mod (sum [(i + m - 1) # (m - 1) * (n - j + m - 2) # (m - 1) | i <- [0..n - 1], j <- [i..n - 1]]) 1000000007).map read.words\n"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\n\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn(s)\n\nmain_ :: EIO ()\nmain_ = do\n (n, m) <- liftM2 (,) get get :: EIO (Int, Int)\n putln $ f1 n m\n\nf1 :: Int -> Int -> Int64\nf1 n m = let ix a b = a * m + b in\n let a = runSTUArray $ do\n arr <- newArray (0, (n + 1) * m) 0 :: ST s (STUArray s Int Int64)\n forM_ [0..n] $ \\j -> writeArray arr (ix j 0) 1\n forM_ [1..m-1] $ \\i ->\n forM_ [0..n] $ \\j ->\n forM_ [0..j] $ \\k -> do\n a <- readArray arr (ix j i)\n b <- readArray arr (ix k (i - 1))\n writeArray arr (ix j i) $ (mod (a + b) 1000000007)\n return arr in\n let v = do\n x <- [1..n]\n y <- [1..n]\n [(x, y)] in\n let x = filter (\\(x, y) -> x <= y) v in\n foldl (\\s (x, y) -> mod (s + (a ! (ix (x - 1) (m - 1))) * (a ! (ix (n - y) (m - 1)))) 1000000007) 0 x\n\n\n"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn(s)\n\nmain_ :: EIO ()\nmain_ = do\n (n, m) <- liftM2 (,) get get :: EIO (Int, Int)\n putln $ f1 n m\n\nf1 :: Int -> Int -> Int64\nf1 n m = let a = runSTArray $ do\n arr <- newArray ((0, 0), (n+1, m)) 0 :: ST s (STArray s (Int, Int) Int64)\n forM_ [0..n] $ \\j -> writeArray arr (j, 0) 1\n forM_ [1..m-1] $ \\i ->\n forM_ [0..n] $ \\j ->\n forM_ [0..j] $ \\k -> do\n a <- readArray arr (j, i)\n b <- readArray arr (k, i - 1)\n writeArray arr (j, i) $ (mod (a + b) 1000000007)\n return arr in\n let v = do\n x <- [1..n]\n y <- [1..n]\n [(x, y)] in\n let x = filter (\\(x, y) -> x <= y) v in\n foldl (\\s (x, y) -> mod (s + (a ! (x - 1, m - 1)) * (a ! (n - y, m - 1))) 1000000007) 0 x\n\n\n"}], "negative_code": [], "src_uid": "82293f824c5afbf9dbbb47eac421af33"} {"source_code": "get_my_list :: Int -> [Int]\r\nget_my_list 1 = [1]\r\nget_my_list 2 = [1,2]\r\nget_my_list 3 = [2,1,3]\r\nget_my_list n = \r\n case (mod n 3) of \r\n 0 -> 1:2:4:3:[5..n]\r\n 1 -> 2:1:[3..n]\r\n 2 -> [1..n]\r\n\r\nints_to_str :: [Int] -> String\r\nints_to_str = unwords . map show\r\n\r\ninput_to_output :: String -> IO ()\r\ninput_to_output = (putStrLn . ints_to_str . get_my_list . read)\r\n\r\ntest_case_func :: (Num a,Eq a) => a -> IO ()\r\ntest_case_func 0 = return ()\r\ntest_case_func t = do \r\n n <- getLine\r\n input_to_output n\r\n test_case_func (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n test_case_func $ read ts", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> mapM_ (\\x -> putStr (show x ++ \" \")) (getPerm n) >>\n putStrLn \"\"\ngetPerm n | mod n 2 == 0 = reverse [1..n-2] ++ [n-1, n]\n | otherwise = [n-3, n-2] ++ reverse [1..n-4] ++ [n-1, n]\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- permutscore.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\nimport Prelude hiding (getLine)\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\n\nri = readInts <$> B.getLine :: IO [Int]\n where\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n dropSpace = B.dropWhile isSpace\n\nshowL = unwords . map show\n\nmain :: IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n [n] <- ri\n return n\n mapM_ (putStrLn.showL.solve) tcs\n\nsolve n = answ\n where\n (x:xs,ys) = splitAt (n - 2) [1..n]\n\n answ | (even n) = reverse xs ++ [x] ++ ys\n | otherwise = [x] ++ reverse xs ++ ys\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = Int\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n -- print (n, xs)\n return n\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\nnewtype I = I (Int,Int)\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve n = putStrLn $ intercalate \" \" $ map show $ go xs\n where xs = [1..n]\n go :: [Int] -> [Int]\n go [] = []\n go [x] = [x]\n go [x, y] = [x, y]\n go [x, y, z] = [y, x, z]\n go [a, b, x, y, z] = [a, x, b, y, z]\n go (x:y:xs) = y:x:go xs\n \n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = Int\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n -- print (n, xs)\n return n\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\nnewtype I = I (Int,Int)\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve n = putStrLn $ intercalate \" \" $ map show $ go xs\n where xs = [1..n]\n go :: [Int] -> [Int]\n go [] = []\n go [x] = [x]\n go [x, y] = [x, y]\n go [x, y, z] = [y, x, z]\n go [a, b, x, y, z] = [a, x, b, y, z]\n go (x:y:xs) = y:x:xs\n \n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = Int\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n -- print (n, xs)\n return n\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\nnewtype I = I (Int,Int)\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve n = putStrLn $ intercalate \" \" $ map show $ go xs\n where xs = [1..n]\n go :: [Int] -> [Int]\n go [] = []\n go [x] = [x]\n go [x, y] = [x, y]\n go [x, y, z] = [y, x, z]\n go [a, b, x, y, z] = [a, b, x, y, z]\n go (x:y:xs) = y:x:xs\n \n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "get_my_list :: Int -> [Int]\r\nget_my_list 1 = [1]\r\nget_my_list 2 = [1,2]\r\nget_my_list 3 = [2,1,3]\r\nget_my_list n = \r\n case (mod n 3) of \r\n 0 -> 1:2:4:3:[5..n]\r\n 1 -> 2:1:[3..n]\r\n 2 -> [1..n]\r\n\r\nints_to_str :: [Int] -> String\r\nints_to_str = unwords . map show\r\n\r\ninput_to_output :: String -> IO ()\r\ninput_to_output = (print . ints_to_str . get_my_list . read)\r\n\r\ntest_case_func :: (Num a,Eq a) => a -> IO ()\r\ntest_case_func 0 = return ()\r\ntest_case_func t = do \r\n n <- getLine\r\n input_to_output n\r\n test_case_func (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n test_case_func $ read ts"}], "src_uid": "9cc18b914678cb18213b2a52259de35d"} {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.ByteString.Char8( readInt, tail)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int,Int)\n\treadPair = do\n\t Just (l,rest) <- readInt <$> getLine'\n\t let\n\t\tJust (r,_) = readInt $ B.tail rest\n\n\t return (l,r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\tsearchRMinLMax \t= foldl update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = (max lmax l, min rmin r)\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n", "positive_code": [{"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.List( foldl')\nimport Data.ByteString.Char8( readInt, tail)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int,Int)\n\treadPair = do\n\t Just (l,rest) <- readInt <$> getLine'\n\t let\n\t\tJust (r,_) = readInt $ B.tail rest\n\n\t return (l,r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\tsearchRMinLMax \t= foldl' update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = (max lmax l, min rmin r)\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.List( foldl')\nimport Data.ByteString.Char8( readInt, tail)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int,Int)\n\treadPair = do\n\t Just (l,rest) <- readInt <$> getLine'\n\t let\n\t\tJust (r,_) = readInt $ B.tail rest\n\n\t return (l,r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\n\tsearchRMinLMax \t= foldl' update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = \n\t let\n\t\tlmax' = max lmax l\n\t\trmin' = min rmin r\n\t in\n\t\tlmax' `seq` rmin' `seq` (lmax', rmin')\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.List( foldl')\nimport Data.Int( Int32)\nimport Data.Bits( (.|.), (.&.), xor, shiftR, complement)\nimport Data.ByteString.Char8( words, readInt)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int32,Int32)\n\treadPair = do\n\t [Just (l,_) ,Just (r,_)] <- map readInt . B.words <$>\n\t\t\t\t\t\t\t getLine'\n\t return (fromIntegral l, fromIntegral r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\n\tsearchRMinLMax \t= foldl' update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = \n\t let\n\t\tlmax' = max32 lmax l\n\t\trmin' = min32 rmin r\n\t in\n\t\tlmax' `seq` rmin' `seq` (lmax', rmin')\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n\n\nbranchFreeMinMax32:: Int32 -> Int32 -> Int32 -> Int32\nbranchFreeMinMax32 a b diff =\n let\n mask1 = shiftR\tdiff\t 32\n mask2 = complement mask1\n\n lose_a = mask1 .&. a\n lose_b = mask2 .&. b\n loser = lose_a .|. lose_b\n\n ab = a `xor` b\n winner = loser `xor` ab\n in\n diff `seq`\n mask1 `seq` mask2 `seq`\n lose_a `seq` lose_b `seq` loser `seq`\n ab `seq`\n winner\n\nmax32, min32::Int32 -> Int32 -> Int32\nmax32 a b = branchFreeMinMax32 a b (a-b)\nmin32 a b = branchFreeMinMax32 a b (b-a)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nsSpace w = span (/= ' ') w\ntoInt s = read s :: Int\ntoIntTup (a, b) = (toInt a, toInt b)\n\nfindMinMaxH :: Int -> Int -> Int -> IO((Int, Int))\nfindMinMaxH 0 cmin cmax = return (cmin, cmax)\nfindMinMaxH i !cmin !cmax = do\n w <- getLine\n let (newMax, newMin) = toIntTup $ sSpace w in\n findMinMaxH (i-1) (min cmin newMin) (max cmax newMax)\n\nfindMinMax :: Int -> IO((Int, Int))\nfindMinMax i = findMinMaxH i 10000000009 (-1)\n\nmain :: IO()\nmain = do\n chessCount <- getLine\n (cendmin, cstartmax) <- findMinMax $ toInt chessCount\n --print (cendmin, cstartmax)\n programCount <- getLine\n (pendmin, pstartmax) <- findMinMax $ toInt programCount\n --print (pendmin, pstartmax)\n print $ maximum [(pstartmax - cendmin), (cstartmax - pendmin), 0]\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (foldM)\nimport Control.DeepSeq (force)\n\nffoldM a b f = foldM f b a\n\ncalc bn am an bm | am - bn <= 0 && an - bm <= 0 = 0\n | otherwise = max (an - bm) (am - bn)\n\nxmin a b | length a < length b = a\n | length b < length a = b\n | otherwise = min a b\n\nxmax a b | length a > length b = a\n | length b > length a = b\n | otherwise = max a b\n\nmain = do\n (read -> n :: Int) <- getLine\n let (a, b) = (take 10 (repeat '9'), \"\")\n (map (read :: String -> Int) -> [bn, an]) <- ffoldM [1..n] [a, b] $ \\[bn, an] _ -> do\n (words -> [c, c']) <- getLine\n return $ force [xmin bn c', xmax an c]\n (read -> m :: Int) <- getLine\n (map (read :: String -> Int) -> [bm, am]) <- ffoldM [1..m] [a, b] $ \\[bm, am] _ -> do\n (words -> [c, c']) <- getLine\n return $ force [xmin bm c', xmax am c]\n putStrLn $ show (calc bn am an bm)\n"}, {"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO()\nmain = print . solve . map (fst . fromJust . C.readInt) . C.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (n:a) = let (p, (_:q)) = splitAt (2 * n) a\n (po, pe) = split p\n (qo, qe) = split q\n pomax = maximum po\n pemin = minimum pe\n qomax = maximum qo\n qemin = minimum qe\n int1 = if qomax > pemin then qomax - pemin else 0\n int2 = if pomax > qemin then pomax - qemin else 0\n in max int1 int2\n \nsplit :: [Int] -> ([Int], [Int])\nsplit [] = ([], [])\nsplit (x:y:s) = let (xs, ys) = split s in (x:xs, y:ys)\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.List( foldl')\nimport Data.ByteString.Char8( words, readInt)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int,Int)\n\treadPair = do\n\t [Just (l,_) ,Just (r,_)] <- map readInt . B.words <$>\n\t\t\t\t\t\t\t getLine'\n\t return (l,r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\n\tsearchRMinLMax \t= foldl' update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = \n\t let\n\t\tlmax' = max lmax l\n\t\trmin' = min rmin r\n\t in\n\t\tlmax' `seq` rmin' `seq` (lmax', rmin')\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.ByteString.Char8( readInt, tail)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int,Int)\n\treadPair = do\n\t Just (l,rest) <- readInt <$> getLine'\n\t let\n\t\tJust (r,_) = readInt $ B.tail rest\n\n\t return (l,r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\n\tsearchRMinLMax \t= foldl update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = \n\t let\n\t\tlmax' = max lmax l\n\t\trmin' = min rmin r\n\t in\n\t\tlmax' `seq` rmin' `seq` (lmax', rmin')\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.List( foldl')\nimport Data.Int( Int32)\nimport Data.Bits( (.|.), (.&.), xor, shiftR, complement)\nimport Data.ByteString.Char8( words, readInt)\nimport qualified Data.ByteString.Char8 as B\nimport System.IO( stdin)\n\nmain = do\n let\n\tgetLine' = B.hGetLine stdin\n\n Just (n_, _) <- readInt <$> getLine'\n let\n\treadPair::IO (Int32,Int32)\n\treadPair = do\n\t [Just (l,_) ,Just (r,_)] <- map readInt . B.words <$>\n\t\t\t\t\t\t\t getLine'\n\t return (fromIntegral l, fromIntegral r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n Just (m_, _) <- readInt <$> getLine'\n progPeriods_ <- replicateM m_ readPair\n let\n\n\tsearchRMinLMax \t= foldl' update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = \n\t let\n\t\tlmax' = max32 lmax l\n\t\trmin' = min32 rmin r\n\t in\n\t\tlmax' `seq` rmin' `seq` (lmax', rmin')\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n\n\nbranchFreeMinMax32:: Int32 -> Int32 -> Int32 -> Int32\nbranchFreeMinMax32 a b diff =\n let\n mask1 = shiftR\tdiff\t 32\n mask2 = complement mask1\n\n lose_a = mask1 .&. a\n lose_b = mask2 .&. b\n loser = lose_a .|. lose_b\n\n ab = a `xor` b\n winner = loser `xor` ab\n in\n winner\n\nmax32, min32::Int32 -> Int32 -> Int32\nmax32 a b = branchFreeMinMax32 a b (a-b)\nmin32 a b = branchFreeMinMax32 a b (b-a)\n"}], "negative_code": [{"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nimport Data.List( foldl')\nimport Data.Int( Int32)\nimport Data.Bits( (.|.), (.&.), xor, shiftR)\n\nmain = do\n n_ <- readLn::IO Int\n let\n\treadPair::IO (Int32,Int32)\n\treadPair = do\n\t [l,r] <- map read . words <$> getLine\n\t return (l,r)\n\n chessPeriods_ <- replicateM n_ readPair\n\n m_ <- readLn::IO Int\n progPeriods_ <- replicateM m_ readPair\n let\n\n\tsearchRMinLMax \t= foldl' update (0,ten9)\n\t where\n\t update (lmax, rmin) (l,r) = \n\t let\n\t\tlmax' = max32 lmax l\n\t\trmin' = min32 rmin r\n\t in\n\t\tlmax' `seq` rmin' `seq` (lmax', rmin')\n\n\tten9 = 1000000000\n\t(lmaxChess, rminChess) = searchRMinLMax chessPeriods_\n\t(lmaxProg, rminProg) = searchRMinLMax progPeriods_\n\n print $ max 0$max (lmaxChess - rminProg) (lmaxProg - rminChess)\n\n\nbranchFreeMinMax32:: Int32 -> Int32 -> Int32 -> Int32\nbranchFreeMinMax32 a b diff =\n let\n mask1 = shiftR\tdiff\t 32\n mask2 = shiftR (negate diff) 32\n\n lose_a = mask1 .&. a\n lose_b = mask2 .&. b\n loser = lose_a .|. lose_b\n\n ab = a `xor` b\n winner = loser `xor` ab\n in\n diff `seq`\n mask1 `seq` mask2 `seq`\n lose_a `seq` lose_b `seq` loser `seq`\n ab `seq`\n winner\n\nmax32, min32::Int32 -> Int32 -> Int32\nmax32 a b = branchFreeMinMax32 a b (a-b)\nmin32 a b = branchFreeMinMax32 a b (b-a)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nsSpace w = span (/= ' ') w\ntoInt s = read s :: Int\ntoIntTup (a, b) = (toInt a, toInt b)\n\n\nfindMinMaxH :: Int -> Int -> Int -> IO((Int, Int))\nfindMinMaxH 0 cmin cmax = return (cmin, cmax)\nfindMinMaxH i cmin cmax = do\n w <- getLine\n let (newMax, newMin) = toIntTup $ sSpace w in\n findMinMaxH (i-1) (min cmin newMin) (max cmax newMax)\n\nfindMinMax :: Int -> IO((Int, Int))\nfindMinMax i = findMinMaxH i 1000000000000 (-1)\n\nmain :: IO()\nmain = do\n chessCount <- getLine\n (cendmin, cstartmax) <- findMinMax $ toInt chessCount\n programCount <- getLine\n (pendmin, pstartmax) <- findMinMax $ toInt programCount\n print $ maximum [(pstartmax - cendmin), (cstartmax - pendmin), 0]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nsSpace w = span (/= ' ') w\ntoInt s = read s :: Int\ntoIntTup (a, b) = (toInt a, toInt b)\n\nfindMinMaxH :: Int -> Int -> Int -> IO((Int, Int))\nfindMinMaxH 0 cmin cmax = return (cmin, cmax)\nfindMinMaxH i !cmin !cmax = do\n w <- getLine\n let (newMax, newMin) = toIntTup $ sSpace w in\n findMinMaxH (i-1) (min cmin newMin) (max cmax newMax)\n\nfindMinMax :: Int -> IO((Int, Int))\nfindMinMax i = findMinMaxH i 100000009 (-1)\n\nmain :: IO()\nmain = do\n chessCount <- getLine\n (cendmin, cstartmax) <- findMinMax $ toInt chessCount\n programCount <- getLine\n (pendmin, pstartmax) <- findMinMax $ toInt programCount\n print $ maximum [(pstartmax - cendmin), (cstartmax - pendmin), 0]\n"}], "src_uid": "4849a1f65afe69aad12c010302465ccd"} {"source_code": "f[]=[0]\nf(x:y:t)=x:f t\nf l=l\ns(n:m:k:a)=minimum$k*(div m$n`div`2+1):f a\nmain=interact$show.s.map read.words\n", "positive_code": [{"source_code": "solve (n:m:k:as) = if odd n then min s q else 0\n where q = (k * (m `div` ((n + 1) `div` 2)))\n s = minimum $ map snd $ filter (odd.fst) $ zip [1..n] as\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nf (x:y:xs) = x:f xs\nf (x:[]) = [x]\nf ([]) = []\n\nmain = do\n [n, m, k] <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n xs <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n let ans = if even n\n then 0\n else let ratio = div (n+1) 2\n in if m < ratio \n then 0\n else let mD = div m ratio\n nds = min (mD*k) (minimum (f xs))\n in nds\n print ans\n"}, {"source_code": "solve (n:m:k:as) = if odd n then min s q else 0\n where q = (k * (m `div` ((n + 1) `div` 2)))\n s = minimum $ map snd $ filter (odd.fst) $ zip [1..n] as\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n [n, m, k] <- ( map read . words ) `liftM` getLine\n cells <- ( map read . words ) `liftM` getLine\n\n if even n\n then putStrLn \"0\"\n else do\n let m' = m `div` ((n+1) `div` 2)\n minTarget = minimum $ map snd $ filter (odd . fst) $ zip [1..] cells\n res = min minTarget (m' * k)\n putStrLn $ show res\n"}, {"source_code": "s(n:m:k:as)|odd n=minimum$(k*(m`div`((n+1)`div`2))):(map snd$filter(odd.fst)$zip[1..n]as)|1>0=0\nmain=interact$show.s.map read.words"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nf (x:y:xs) = x:f xs\nf (x:[]) = [x]\nf ([]) = []\n\nmain = do\n [n, m, k] <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n xs <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n let ans = if even n\n then 0\n else let ratio = div (n+1) 2\n mD = div m ratio\n nds = minimum $ mD*k:f xs\n in nds\n print ans\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nf (x:y:xs) = x:f xs\nf (x:[]) = [x]\nf ([]) = []\n\nmain = do\n [n, m, k] <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n xs <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n let ans = if even n\n then 0\n else let ratio = div (n+1) 2\n in if m < ratio \n then 0\n else let mD = div m ratio\n nds = min (mD*k) (minimum (f xs))\n in nds\n print ans\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nf (x:y:xs) = x:f xs\nf (x:[]) = [x]\nf ([]) = []\n\nmain = do\n [n, m, k] <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n xs <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n let ans = if even n\n then 0\n else let ratio = div (n+1) 2\n in if m < ratio \n then 0\n else let mD = div m ratio\n nT = min k (minimum (map (`div` mD) (f xs)))\n rems = minimum $ map (`mod` mD) (f xs)\n in if nT == k\n then mD*nT\n else mD*nT + rems\n print ans\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nmain = do\n [n, m, k] <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n xs <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n let ans = if even n\n then 0\n else let ratio = div (n+1) 2\n in if m < ratio \n then 0\n else let mD = div m ratio\n nT = min k (minimum (map (div mD) xs))\n in mD*nT\n print ans\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nf (x:y:xs) = x:f xs\nf (x:[]) = [x]\nf ([]) = []\n\nmain = do\n [n, m, k] <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n xs <- map (fst.fromJust.BS.readInteger) . BS.words <$> BS.getLine\n let ans = if even n\n then 0\n else let ratio = div (n+1) 2\n in if m < ratio \n then 0\n else let mD = div m ratio\n nT = min k (minimum (map (`div` mD) (f xs)))\n in mD*nT\n print ans\n"}], "src_uid": "b81e7a786e4083cf7188f718bc045a85"} {"source_code": "analyze a b = let\n ao = length (filter odd a)\n ae = length (filter even a)\n bo = length (filter odd b)\n be = length (filter even b)\n in (min ao be) + (min ae bo)\nmain = do\n getLine\n linea <- getLine\n lineb <- getLine\n putStrLn $ show $ analyze (map read (words linea)) (map read (words lineb))\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, m ] <- readInts\n\tas <- readInts\n\tbs <- readInts\n\tlet\n\t\tcount_odd = length . filter ( ( == 1 ) . ( `mod` 2 ) )\n\t\ta_odd = count_odd as\n\t\ta_even = n - a_odd\n\t\tb_odd = count_odd bs\n\t\tb_even = m - b_odd\n\tprint $ min a_odd b_even + min a_even b_odd"}, {"source_code": "main = getContents >>= print . solve . map (map read. words) . lines\n\nsolve [[x,y],xs,ys] = min ox (y - oy) + min oy (x - ox)\n where countOdd = length . filter odd\n (ox,oy) = (countOdd xs, countOdd ys)"}, {"source_code": "import Data.List\nmain = do\n getLine\n (eas,oas) <- partition even . map read . words <$> getLine\n (ebs,obs) <- partition even . map read . words <$> getLine\n print $ min (length eas) (length obs) + min (length oas) (length ebs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nmain = do\n\t\t[cl,kl]<- map read <$> words <$> getLine::IO [Int]\n\t\tc<- map read <$> words <$> getLine ::IO [Int]\n\t\tk<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet co = length $ filter odd c\n\t\tlet ko = length $ filter odd k\n\t\tlet ce = cl-co\n\t\tlet ke = kl-ko\n\t\tprint $ (min co ke) + (min ko ce)\n\n\n\t\n\n"}, {"source_code": "import Data.List (partition)\n\nprocess :: [Int] -> [Int] -> Int\nprocess as bs = min (length ae) (length bo) + min (length ao) (length be)\n where\n (ao,ae) = partition odd as\n (bo,be) = partition odd bs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n bs <- fmap (map readInt.words) getLine\n print $ process as bs"}], "negative_code": [], "src_uid": "bc532d5c9845940b5f59485394187bf6"} {"source_code": "main = do\n [n, m] <- fmap (map read . words) getLine\n t <- mapM (\\_ -> getLine) [1..n]\n let tt = map ((\\[x, y] -> y / x) . map read . words) t\n print $ m / maximum tt", "positive_code": [{"source_code": "main = do\n [_,n] <- fmap (map read . words) getLine\n c <- fmap lines getContents\n print $ n * minimum [let [y,k] = (map read . words) l in y/k | l <- c]\n"}, {"source_code": "import Data.List\n\nf::[String]->Double\nf (a:b:[])=(read a::Double) / (read b::Double)\n\nmain=do\n e1<-getLine\n es<-getContents\n let (n:m:[])=map read (words e1)::[Double]\n ans=head $ sort $ map f (map words (lines es))\n print $ ans*m"}, {"source_code": "import Control.Applicative\n\n\n\n\nmain::IO ()\nmain=do\n [n,m]<-map read <$> words<$> getLine::IO [Double]\n a<-(map( map read) <$> map words<$> lines <$> getContents)::IO [[Double]]\n let b = minimum $ map (\\[z1,z2]-> z1/z2) a\n print $ b *m\n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (m:ps) = minimum $ map (m*) $ go ps where\n go (a:b:ps) = a/b : go ps\n go [] = []\n"}, {"source_code": "main = getContents >>= print . solve 10000.0 . map read . words\n\nsolve ans (0:_) = ans\nsolve ans (n:m:a:b:rst) = solve (min ans (m * a / b)) (n - 1:m:rst)\n\n"}, {"source_code": "main=getContents>>=print.minimum.f.map read.words\nf(_:m:l)=g l\n where\n g(x:y:z)=(x/y*m):g z\n g _ = []\n"}, {"source_code": "import Control.Monad\n\nmain = do\n [n, m] <- fmap (fmap read . words) getLine\n l <- replicateM n $ fmap (fmap read . words) getLine\n print . minimum . map(\\[a,b] -> (fromIntegral m)*a / b) $ l\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\t\t\nmyread::String->Integer\nmyread= read\n\nmain = do\n\t\t[n,m]<-map read<$> words <$> getLine ::IO [Int]\n\t\ta<-map (\\(a:b:c)-> fromIntegral a / (fromIntegral b)) <$> map (map (myread)) <$> map words <$> replicateM n getLine \n\t\tprint $ (fromIntegral m)* minimum a\n"}], "negative_code": [], "src_uid": "3bbe48918a7bf3faf01c74cb7296f6e0"} {"source_code": "f :: Int -> IO ()\nf 0 = return ()\nf t = do\n n <- readLn :: IO Int\n putStrLn . unwords . map show $ n : [1..(n - 1)]\n f (t - 1)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n f t", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain =\n interact $\n words >>> drop 1 >>> map (read >>> solve >>> map show >>> unwords) >>> unlines\n\nsolve n = n : [1 .. n - 1]\n"}, {"source_code": "import Data.List\nimport System.IO\n\nmain :: IO ()\nmain = do \n input <- getContents\n let output = solve input\n putStr output\n\n\nsolve :: String -> String\nsolve input = let n_list = tail $ map read $ words input\n ans_list = map (\\x -> foldl (\\x y -> x ++ show y ++ \" \") \"\" (x:[1..x-1])) n_list\n in foldl (\\x y -> x ++ y ++ \"\\n\") \"\" ans_list"}, {"source_code": "solve n = [2..n] ++ [1]\nmain = interact $ unlines . map (unwords . map show) . map solve . tail . map read . words\n"}, {"source_code": "import Data.List\n\nsolve :: Int -> [Int]\nsolve n = [2..n] ++ [1]\n\nmain :: IO ()\nmain = interact $ unlines . map (intercalate \" \" . map show) . map solve . tail . map read . words\n"}, {"source_code": "{-# LANGUAGE GADTs, TemplateHaskell, DeriveFunctor, OverloadedStrings #-}\n\nimport Data.List\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe\nimport Data.Int\nimport Text.Printf\nimport Data.Function ( (&), on )\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Char (isAlpha)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nsolve :: Int -> [Int]\nsolve n = [2 .. n] ++ [1]\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ \\_ -> do\n Just n <- B8.getLine <&> readIntB8\n let answer = solve n\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n testCases <- read <$> getLine\n replicateM testCases $ do\n permutationLength <- read <$> getLine :: IO Int\n putStrLn $ mconcat $ intersperse \" \" $ map show $ specialPermutations permutationLength\n\nspecialPermutations :: Int -> [Int]\nspecialPermutations n\n | even n = reverse [1 .. n]\n | odd n = reverse $ mconcat [[1 .. (middle - 1)], [middle + 1, middle], [middle + 2 .. n]]\n where\n middle = div n 2 + 1\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = (istoline . solve . linetoi) l : tcio rest \n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n linetoi = read;\n\nsolve :: Int -> [Int]\nsolve n = (:) <$> last <*> init $ [1..n]\n"}, {"source_code": "import Control.Monad ( replicateM )\n\nmain :: IO ()\nmain = do\n t <- readLn\n putStrLn . unlines . map (\\n -> unwords . map show $ n : [1..(n - 1)]) =<< replicateM t (readLn :: IO Int)"}, {"source_code": "import Control.Applicative ()\n\nf :: Int -> IO ()\nf 0 = return ()\nf t = do\n n <- readLn\n putStrLn . unwords . map show $ n : [1..(n - 1)]\n f (t - 1)\n\nmain :: IO ()\nmain = f =<< readLn"}, {"source_code": "f :: Int -> IO ()\nf 0 = return ()\nf t = do\n n <- readLn :: IO Int\n putStrLn . unwords . map show $ n : [1..(n - 1)]\n f (t - 1)\n\nmain :: IO ()\nmain = do\n t <- readLn\n f t"}, {"source_code": "f :: Int -> IO ()\nf 0 = return ()\nf t = do\n n <- readLn\n putStrLn . unwords . map show $ n : [1..(n - 1)]\n f (t - 1)\n\nmain :: IO ()\nmain = do\n t <- readLn\n f t"}, {"source_code": "f :: Int -> IO ()\nf 0 = return ()\nf t = do\n n <- readLn :: IO Int\n putStrLn . unwords . map show $ (n : [1..(n - 1)])\n f (t - 1)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n f t"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n testCases <- read <$> getLine\n replicateM testCases $ do\n permutationLength <- read <$> getLine :: IO Int\n putStrLn $ mconcat $ intersperse \" \" $ map show $ reverse [1 .. permutationLength]\n"}, {"source_code": "import Control.Monad ( replicateM )\n\nmain :: IO ()\nmain = do\n t <- readLn\n putStrLn . unlines . map (\\n -> unwords . map show $ n : [2..(n - 1)]) =<< replicateM t (readLn :: IO Int)"}], "src_uid": "f4779e16e0857e6507fdde55e6d4f982"} {"source_code": "{-#LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Int\nimport Data.List\nimport qualified Data.IntMap.Strict as M \nimport Data.Tuple\nimport Data.Maybe(fromJust)\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.DeepSeq\n\ndata Node = Node !Int !Node !Node | Empty\n\ngetSum :: Node -> Int\ngetSum (Node s _ _) = s\n\nbuild :: Int -> Int -> Node\nbuild !l !r \n | l == r = Node 0 Empty Empty\n | otherwise = \n let m = (l + r) `div` 2 \n in Node 0 (build l m) (build (m + 1) r)\n\nupdate :: Node -> Int -> Int -> Int -> Int -> Node\nupdate !(Node !val !left !right) !l !r !pos !delta \n | l == r = Node (val + delta) Empty Empty\n | otherwise = \n let m = (l + r) `div` 2\n in\n if pos <= m then \n Node (val + delta) (update left l m pos delta) right\n else\n Node (val + delta) left (update right (m + 1) r pos delta)\n \n\nget :: Node -> Int -> Int -> Int -> Int -> Int\nget !(Node !val !left !right) !tl !tr !l !r \n | l == tl && r == tr = val\n | otherwise = \n let m = (tl + tr) `div` 2\n in \n if l <= m then\n (get left tl m l (min r m)) + getSum right\n else\n get right (m + 1) tr (max (m + 1) l) r\nsolve :: [(Int, Int)] -> Int64 \n\nsolve xs = \n let n = length xs\n step :: (Node, Int64) -> (Int, Int) -> (Node, Int64)\n step (!root, !res) (!pos, !size) =\n let add = ((fromIntegral size) :: Int64) * \n (fromIntegral $ get root 0 (n - 1) pos (n - 1))\n root' = update root 0 (n - 1) pos size \n in\n (root', res + add) \n in \n snd $ foldl' step (build 0 (n - 1), 0::Int64) xs \n \nmakeSwaps :: [(Int, Int)] -> ([Int], [Int]) -> [(Int, Int)]\nmakeSwaps swaps !(vals, s) =\n let\n initVals = M.fromAscList $ zip vals vals\n step !vs (!a, !b) = \n let va = vs M.! a\n vb = vs M.! b\n vs' = M.insert a vb vs\n in\n M.insert b va vs'\n finalVals = M.assocs $ foldl' step initVals swaps\n compressed = finalVals `deepseq` M.fromAscList $ zip vals (zip [0..] s)\n in\n map (\\(_, a) -> (let (f, s) = compressed M.! a in (f, s))) finalVals\n \ngetSizes :: [Int] -> ([Int], [Int])\ngetSizes [] = ([], [])\ngetSizes [x] = ([x], [1])\ngetSizes (x:y:xs) \n | x == y - 1 = \n let (!a, !b) = getSizes(y:xs)\n in (x:a, 1:b) \n | otherwise = \n let (!a, !b) = getSizes(y:xs)\n in (x:x + 1:a, 1:y - x - 1:b)\n\nmain = do\n input <- B.getContents\n let (line:lines) = B.lines input\n let n = lines `deepseq` (fst . fromJust $ B.readInt line)\n let swaps = map (\\l -> let [x, y] = B.words l in (fst . fromJust $ B.readInt x, fst . fromJust $ B.readInt y)) lines \n let sizes = swaps `deepseq` getSizes (S.elems $ foldl' (\\acc (a, b) -> S.insert a (S.insert b acc)) (S.empty::S.Set Int) swaps) \n let afterSwaps = sizes `deepseq` makeSwaps swaps sizes\n let size = afterSwaps `deepseq` length (fst sizes)\n let res = solve afterSwaps \n print res", "positive_code": [{"source_code": "{-#LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as M \nimport Data.Tuple\nimport Data.Maybe(fromJust)\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.IO\nimport Data.Bits \nimport qualified Data.Sequence as Seq\n\nupdateAt :: IOUArray Int Int -> Int -> Int -> Int -> IO ()\nupdateAt f !n !at !delta \n | at >= n = return ()\n | otherwise = do\n cur <- readArray f at\n writeArray f at (delta + cur)\n updateAt f n (at .|. (at + 1)) delta\n\ngetAt :: IOUArray Int Int -> Int -> Int -> IO Int\ngetAt f !at !acc\n | at < 0 = return acc\n | otherwise = do\n cur <- readArray f at\n getAt f ((at .&. (at + 1)) - 1) (acc + cur) \n\nsolve :: [(Int, Int)] -> IOUArray Int Int -> Int -> IO Int64 \nsolve [] _ _ = return 0\nsolve !((pos, size):xs) tree !n = do\n sum <- getAt tree pos 0\n let res = (fromIntegral sum) * (fromIntegral size)\n _ <- updateAt tree n pos size\n rest <- solve xs tree n\n return (rest + res) \n \nmakeSwaps :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]\nmakeSwaps swaps sizes =\n let vals = map fst sizes\n s = map snd sizes\n initVals = M.fromAscList $ zip vals vals \n step !vs (!a, !b) =\n let va = vs M.! a\n vb = vs M.! b\n vs' = M.insert a vb vs\n in\n M.insert b va vs'\n finalVals = M.assocs $ foldl' step initVals swaps\n compressed = M.fromAscList $ zip vals (zip [0..] s)\n in\n map (\\(_, a) -> (let (f, s) = compressed M.! a in (f, s))) finalVals\n \ngetSizes :: [Int] -> [(Int, Int)]\ngetSizes ![] = []\ngetSizes ![x] = [(x, 1)]\ngetSizes !(x:y:xs) \n | x == y = getSizes(y:xs)\n | x == y - 1 = (x, 1) : getSizes (y:xs)\n | otherwise = (x, 1) : (x + 1, y - x - 1) : getSizes (y:xs)\n\nmain = do\n input <- B.getContents\n let (line:lines) = B.lines input\n let n = fst . fromJust $ B.readInt line\n let swaps = map (\\l -> let [x, y] = B.words l in (fst . fromJust $ B.readInt x, fst . fromJust $ B.readInt y)) lines \n let all = foldl' (\\acc (a, b) -> a : b : acc) [] swaps \n let sizes = getSizes (S.elems (S.fromList all))\n let afterSwaps = makeSwaps swaps sizes\n let size = length sizes\n tree <- newArray (0, size - 1) 0 :: IO (IOUArray Int Int)\n res <- solve (reverse afterSwaps) tree size \n print res\n"}, {"source_code": "-- This solution is purely functional. \n\n{-#LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Int\nimport Data.List\nimport qualified Data.IntMap.Strict as M \nimport Data.Tuple\nimport Data.Maybe(fromJust)\nimport qualified Data.IntSet as S\nimport qualified Data.ByteString.Char8 as B\nimport Control.DeepSeq\n\ndata Node = Node !Int !Node !Node | Empty\n\ngetSum :: Node -> Int\ngetSum (Node s _ _) = s\n\nbuild :: Int -> Int -> Node\nbuild !l !r \n | l == r = Node 0 Empty Empty\n | otherwise = \n let m = (l + r) `div` 2 \n in Node 0 (build l m) (build (m + 1) r)\n\nupdate :: Node -> Int -> Int -> Int -> Int -> Node\nupdate !(Node !val !left !right) !l !r !pos !delta \n | l == r = Node (val + delta) Empty Empty\n | otherwise = \n let m = (l + r) `div` 2\n in\n if pos <= m then \n Node (val + delta) (update left l m pos delta) right\n else\n Node (val + delta) left (update right (m + 1) r pos delta)\n \n\nget :: Node -> Int -> Int -> Int -> Int -> Int\nget !(Node !val !left !right) !tl !tr !l !r \n | l == tl && r == tr = val\n | otherwise = \n let m = (tl + tr) `div` 2\n in \n if l <= m then\n (get left tl m l (min r m)) + getSum right\n else\n get right (m + 1) tr (max (m + 1) l) r\nsolve :: [(Int, Int)] -> Int64 \n\nsolve xs = \n let n = length xs\n step :: (Node, Int64) -> (Int, Int) -> (Node, Int64)\n step (!root, !res) (!pos, !size) =\n let add = ((fromIntegral size) :: Int64) * \n (fromIntegral $ get root 0 (n - 1) pos (n - 1))\n root' = update root 0 (n - 1) pos size \n in\n (root', res + add) \n in \n snd $ foldl' step (build 0 (n - 1), 0::Int64) xs \n \nmakeSwaps :: [(Int, Int)] -> ([Int], [Int]) -> [(Int, Int)]\nmakeSwaps swaps !(vals, s) =\n let\n initVals = M.fromAscList $ zip vals vals\n step !vs (!a, !b) = \n let va = vs M.! a\n vb = vs M.! b\n vs' = M.insert a vb vs\n in\n M.insert b va vs'\n finalVals = M.assocs $ foldl' step initVals swaps\n compressed = finalVals `deepseq` M.fromAscList $ zip vals (zip [0..] s)\n in\n map (\\(_, a) -> (let (f, s) = compressed M.! a in (f, s))) finalVals\n \ngetSizes :: [Int] -> ([Int], [Int])\ngetSizes [] = ([], [])\ngetSizes [x] = ([x], [1])\ngetSizes (x:y:xs) \n | x == y - 1 = \n let (!a, !b) = getSizes(y:xs)\n in (x:a, 1:b) \n | otherwise = \n let (!a, !b) = getSizes(y:xs)\n in (x:x + 1:a, 1:y - x - 1:b)\n\nmain = do\n input <- B.getContents\n let (line:lines) = B.lines input\n let n = lines `deepseq` (fst . fromJust $ B.readInt line)\n let swaps = map (\\l -> let [x, y] = B.words l in (fst . fromJust $ B.readInt x, fst . fromJust $ B.readInt y)) lines \n let sizes = swaps `deepseq` getSizes (S.elems $ foldl' (\\acc (a, b) -> S.insert a (S.insert b acc)) S.empty swaps) \n let afterSwaps = sizes `deepseq` makeSwaps swaps sizes\n let size = afterSwaps `deepseq` length (fst sizes)\n let res = solve afterSwaps \n print res"}, {"source_code": "{-#LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Int\nimport Data.List\nimport qualified Data.IntMap.Strict as M \nimport Data.Tuple\nimport Data.Maybe(fromJust)\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.IO\nimport Data.Bits \nimport qualified Data.Sequence as Seq\n\nupdateAt :: IOUArray Int Int -> Int -> Int -> Int -> IO ()\nupdateAt f !n !at !delta \n | at >= n = return ()\n | otherwise = do\n cur <- readArray f at\n writeArray f at (delta + cur)\n updateAt f n (at .|. (at + 1)) delta\n\ngetAt :: IOUArray Int Int -> Int -> Int -> IO Int\ngetAt f !at !acc\n | at < 0 = return acc\n | otherwise = do\n cur <- readArray f at\n getAt f ((at .&. (at + 1)) - 1) (acc + cur) \n\nsolve :: [(Int, Int)] -> IOUArray Int Int -> Int -> IO Int64 \nsolve [] _ _ = return 0\nsolve !((pos, size):xs) tree !n = do\n sum <- getAt tree pos 0\n let res = (fromIntegral sum) * (fromIntegral size)\n _ <- updateAt tree n pos size\n rest <- solve xs tree n\n return (rest + res) \n \nmakeSwaps :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]\nmakeSwaps swaps sizes =\n let vals = map fst sizes\n s = map snd sizes\n initVals = M.fromAscList $ zip vals vals \n step !vs (!a, !b) =\n let va = vs M.! a\n vb = vs M.! b\n vs' = M.insert a vb vs\n in\n M.insert b va vs'\n finalVals = M.assocs $ foldl' step initVals swaps\n compressed = M.fromAscList $ zip vals (zip [0..] s)\n in\n map (\\(_, a) -> (let (f, s) = compressed M.! a in (f, s))) finalVals\n \ngetSizes :: [Int] -> [(Int, Int)]\ngetSizes ![] = []\ngetSizes ![x] = [(x, 1)]\ngetSizes !(x:y:xs) \n | x == y = getSizes(y:xs)\n | x == y - 1 = (x, 1) : getSizes (y:xs)\n | otherwise = (x, 1) : (x + 1, y - x - 1) : getSizes (y:xs)\n\nmain = do\n input <- B.getContents\n let (line:lines) = B.lines input\n let n = fst . fromJust $ B.readInt line\n let swaps = map (\\l -> let [x, y] = B.words l in (fst . fromJust $ B.readInt x, fst . fromJust $ B.readInt y)) lines \n let all = foldl' (\\acc (a, b) -> a : b : acc) [] swaps \n let sizes = getSizes (S.elems (S.fromList all))\n let afterSwaps = makeSwaps swaps sizes\n let size = length sizes\n tree <- newArray (0, size - 1) 0 :: IO (IOUArray Int Int)\n res <- solve (reverse afterSwaps) tree size \n print res"}], "negative_code": [{"source_code": "{-#LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as M \nimport Data.Tuple\nimport Data.Maybe(fromJust)\nimport qualified Data.ByteString.Char8 as B\n\ndata Node = Node !Int !Node !Node | Empty\n\nbuild :: Int -> Int -> Node\nbuild !l !r \n | l == r = Node 0 Empty Empty\n | otherwise = \n let m = (l + r) `div` 2 \n in Node 0 (build l m) (build (m + 1) r)\n\nupdate :: Node -> Int -> Int -> Int -> Int -> Node\nupdate !(Node !val !left !right) !l !r !pos !delta \n | l == r = Node (val + delta) Empty Empty\n | otherwise = \n let m = (l + r) `div` 2\n in\n if pos <= m then \n Node (val + delta) (update left l m pos delta) right\n else\n Node (val + delta) left (update right (m + 1) r pos delta)\n \n\nget :: Node -> Int -> Int -> Int -> Int -> Int\nget !(Node !val !left !right) !tl !tr !l !r \n | l == tl && r == tr = val\n | otherwise = \n let m = (tl + tr) `div` 2\n sumL = if l <= m then get left tl m l (min r m) else 0\n sumR = if r > m then get right (m + 1) tr (max (m + 1) l) r else 0\n in \n sumL + sumR\n\nsolve :: [(Int, Int)] -> Int64 \nsolve xs = \n let n = length xs\n step :: (Node, Int64) -> (Int, Int) -> (Node, Int64)\n step (!root, !res) (!pos, !size) =\n let add = ((fromIntegral size) :: Int64) * \n (fromIntegral $ get root 0 (n - 1) pos (n - 1))\n root' = update root 0 (n - 1) pos size \n in\n (root', res + add) \n in \n snd $ foldl' step (build 0 (n - 1), 0::Int64) xs\n \nmakeSwaps :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]\nmakeSwaps swaps sizes =\n let vals = map fst sizes\n s = map snd sizes\n initVals = M.fromAscList $ zip vals vals \n step vs (a, b) =\n let va = vs M.! a\n vb = vs M.! b\n vs' = M.insert a vb vs\n in\n (M.insert $ b) va $ vs'\n finalVals = M.assocs $ foldl' step initVals swaps\n compressed = M.fromAscList $ zip vals (zip [0..] s)\n in\n map (\\(_, a) -> (let (f, s) = compressed M.! a in (f, s))) finalVals\n \ngetSizes :: [Int] -> [(Int, Int)]\ngetSizes [] = []\ngetSizes [x] = [(x, 1)]\ngetSizes (x:y:xs) \n | x == y = getSizes(y:xs)\n | x == y - 1 = (x, 1) : getSizes (y:xs)\n | otherwise = (x, 1) : (x + 1, y - x - 1) : getSizes (y:xs)\n \nreadInt :: IO Int\nreadInt = head `liftM` readIntList\n \nreadIntList :: IO [Int]\nreadIntList = do\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n\nreadSwaps :: Int -> IO ([(Int, Int)], [Int]) \nreadSwaps 0 = (return ([], [])) :: IO ([(Int, Int)], [Int])\nreadSwaps n = do\n [a, b] <- readIntList\n (swaps, all) <- readSwaps (n - 1)\n return ((a, b):swaps, a:b:all)\n\nmain = do\n n <- readInt\n (swaps, all) <- readSwaps n\n let sizes = getSizes (sort all)\n print $ length sizes\n let afterSwaps = makeSwaps swaps sizes\n print $ solve afterSwaps\n "}], "src_uid": "f6cd855ceda6029fc7d14daf2c9bb7dc"} {"source_code": "import qualified Data.Map as M\n\nsolve :: (M.Map String Int, [(String, Int)]) -> (String, Int) -> (M.Map String Int, [(String, Int)])\nsolve (table, records) (name, score') =\n (M.insert name score table, (name, score) : records)\n where score = score' + M.findWithDefault 0 name table\n\nparse :: [String] -> [(String, Int)]\nparse [] = []\nparse (name : score : rest) = (name, read score) : parse rest\n\nmain :: IO ()\nmain = do\n input <- getContents\n\n let\n (table, records) = foldl solve (M.empty, []) (parse . tail . words $ input)\n highscore = maximum $ M.elems table\n cands = M.filter (== highscore) table\n isWinner (name, score) = score >= highscore && name `M.member` cands\n\n putStrLn . fst . last . filter isWinner $ records\n", "positive_code": [{"source_code": "import qualified Data.Map as M\nimport Data.Functor ((<$>))\nimport Control.Monad (foldM)\n\nsolve :: (M.Map String Int, [(String, Int)]) -> Int -> IO (M.Map String Int, [(String, Int)])\nsolve (table, records) _ = do\n [name, score'] <- words <$> getLine\n let score = read score' + M.findWithDefault 0 name table\n return (M.insert name score table, (name, score) : records)\n\nmain :: IO ()\nmain = do\n n <- readLn\n (table, records) <- foldM solve (M.empty, []) [1..n]\n let\n pickWinners (highscore', cands') name score\n | score == highscore' = (highscore', M.insert name () cands')\n | score > highscore' = (score, M.singleton name ())\n | otherwise = (highscore', cands')\n (highscore, cands) = M.foldlWithKey pickWinners (-1, M.empty) table\n isWinner (name, score) = score >= highscore && name `M.member` cands\n\n putStrLn . fst . head . filter isWinner $ reverse records\n"}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\n\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\" -- andrew\nex=\"a 3\\na 2\\nm 5\" -- a\n\ntest6=\"alex 3\\nalex 3\\n alex 2\\nalex -1\\nmike 7\\n\" -- ans is alex\ntest7=\"alex 3\\nalex 4\\n alex -1\\nmike 7\\n\" -- ans is mike\ntest8=\"a 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\na 1\\nm 500\\n\"\ntest9=\"g 10\\ng 10\\ng -100\\na 5\\nm 5\\n\"\n\npars::String->String\npars s = solve $map helppars $lines s\n\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = if length winners == 1 then fst $head winners\n else simulate 0 toSimulate m\n where \n res = summarize x\n m = maxScore $ res\n winners = filter ((==m).snd) res\n toSimulate = filter (myelem (map fst winners).fst) x\n\nmyelem s m = elem m s\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (tail s)))\n where name = fst (head s)\n\n\nsimulate position s m \n-- \u0431\u0435\u0440\u0435\u043c \u043f\u0435\u0440\u0432\u044b\u0435 position+1 \u0441\u0442\u0440\u043e\u043a\n-- \u0438\u0449\u0435\u043c \u0432 \u043d\u0438\u0445 \u0438\u043c\u044f \u0438\u0437 \u0442\u0435\u043a\u0443\u0449\u0435\u0439 \u043f\u043e\u0437\u0438\u0446\u0438\u0438\n-- \u0441\u043a\u043b\u0430\u0434\u044b\u0432\u0430\u0435\u043c \u0432\u0441\u0435 \u0432\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u044f \u043d\u0430 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442\n-- \u0435\u0441\u043b\u0438 \u0432\u0434\u0440\u0443\u0433 \u043c\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0431\u043e\u043b\u044c\u0448\u0435 \u0438\u043b\u0438 \u0440\u0430\u0432\u043d\u044b\u0439 \u043c\u0430\u043a\u0441\u0438\u043c\u0443\u043c\u0443 - \u043c\u044b \u043d\u0430\u0448\u0438\u043b \u043f\u043e\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044f\n | position=m then name\n else simulate (position+1) s m\n\t where name = fst (s!!position)\n\n\nclearNames name s = filter (not.compNames name) s\n\nmaxScore s = maximum $ map snd s "}, {"source_code": "{-\n Get a list of \"name score\" pairs and output the name of the person who reaches the maximum\n score first\n-}\n\nimport qualified Data.Map as M\nimport Data.List (mapAccumL)\n\nparse [x,y] = (x, (read y) :: Int)\n\nsolve :: [(String, Int)] -> String\nsolve xs = head [ name | (name, score) <- ms, M.member name winners, score >= maxScore]\n -- (m, ms) :: ( Map String Int, [(String, Int)] ) \n where \n (m, ms) = mapAccumL (\\s (p, i) -> (M.insertWith (+) p i s, (p, M.findWithDefault 0 p s + i))) M.empty xs \n maxScore = maximum (M.elems m)\n winners = M.filter (==maxScore) m\n\n\nmain = interact $ solve . map (parse.words) . tail . lines"}, {"source_code": "import Data.Map as Map\n\nmain = do\n n <- fmap read getLine\n a <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n let (scores, bestScore) = winner a\n\t bests = Map.filter (\\score -> score == bestScore) scores\n putStr $ if size bests == 1\n\t\tthen fst $ head $ Map.toList bests\n\t\telse winner1 a scores bestScore Map.empty\n\nwinner ((name, score):xs) = winner' xs (Map.singleton name score) name\nwinner' [] scores best = \n let bestScore = Map.fold max 0 scores\n in (scores, bestScore)\n\nwinner' ((name, score):xs) scores best =\n let newScores = Map.insertWith (+) name score scores\n (Just bestScore) = Map.lookup best scores\n (Just changedScore) = Map.lookup name newScores\n newBest = if bestScore < changedScore\n then name\n else best\n in winner' xs newScores newBest\n\nwinner1 ((name, score):xs) endScores bestScore scores =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just changedScore) = Map.lookup name newScores\n\t (Just endScore) = Map.lookup name endScores\n\tin if endScore == bestScore && changedScore >= bestScore\n\t\tthen name\n\t\telse winner1 xs endScores bestScore newScores\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n n <- fmap read getLine\n game <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n let scores = foldl (\\scores (name, score) -> Map.insertWith (+) name score scores) Map.empty game\n\t bestScore = Map.fold max 0 scores\n\t bests = Map.filter (\\score -> score == bestScore) scores\n putStr $ if size bests == 1\n\t\tthen fst $ head $ Map.toList bests\n\t\telse winner game scores bestScore Map.empty\n\nwinner ((name, score):xs) endScores bestScore scores =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just changedScore) = Map.lookup name newScores\n\t (Just endScore) = Map.lookup name endScores\n\tin if endScore == bestScore && changedScore >= bestScore\n\t\tthen name\n\t\telse winner xs endScores bestScore newScores\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tlet (scores, bestScore) = winner a\n\tputStr $ winner1 a scores bestScore Map.empty\n\nwinner ((name, score):xs) = winner' xs (Map.singleton name score) name\nwinner' []\t\t scores best = \n\tlet bestScore = Map.fold max 0 scores\n\tin (scores, bestScore)\n\nwinner' ((name, score):xs) scores best =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just bestScore) = Map.lookup best scores\n\t (Just changedScore) = Map.lookup name newScores\n\t newBest = if bestScore < changedScore\n\t\tthen name\n\t\telse best\n\tin winner' xs newScores newBest\n\nwinner1 ((name, score):xs) endScores bestScore scores\n\t| size bests == 1 = fst $ head $ Map.toList bests\n\t| otherwise \t = \n\t\tlet newScores = Map.insertWith (+) name score scores\n\t \t (Just changedScore) = Map.lookup name newScores\n\t \t (Just endScore) = Map.lookup name endScores\n\t\tin if endScore == bestScore && changedScore >= bestScore\n\t\t\tthen name\n\t\t\telse winner1 xs endScores bestScore newScores\n\twhere bests = Map.filter (\\score -> score == bestScore) endScores\n"}, {"source_code": "parse [a, b] = (a, read b :: Int)\n\nqsort :: [(String, Int)] -> [(String, Int)]\nqsort [] = []\nqsort((imie, liczba):xs) = qsort [y | y <- xs, fst y < imie] ++ ((imie, liczba):[y | y <- xs, fst y == imie]) ++ qsort [y | y <- xs, fst y > imie] \n\n-- teraz stworzymy liste (imie, ostatecznyWynik) zakladajac posortowanie po imionach, bedzie fold\n\nsumujPoWyniku :: [(String, Int)] -> [(String, Int)]\nsumujPoWyniku [] = []\nsumujPoWyniku [(imie, liczba)] = [(imie, liczba)]\nsumujPoWyniku ((imie, liczba):(imie1, liczba1):xs) = if imie == imie1 then sumujPoWyniku ((imie, liczba+liczba1):xs) else (imie, liczba):sumujPoWyniku ((imie1, liczba1):xs)\n\n\n--oki doki, teraz bedziemy chcieli maksa z tego. czyli po prostu bierzemy funkcje, drugie i bierzemy maximum\n\ndrugie :: [(String, Int)] -> [Int]\ndrugie = foldr f []\n where\n f (imie, liczba) xs = (liczba:xs)\n\n--i teraz m = maximum.drugie.sumujPoWyniku.qsort l\n\nwinners :: [(String, Int)] -> [String]\nwinners l = map fst (filter ((==m).snd) maksy)\n where\n m = (maximum.drugie.sumujPoWyniku.qsort) l\n maksy = (sumujPoWyniku.qsort) l\n\nztrojkuj :: (String, Int) -> Int -> (String, Int, Int)\nztrojkuj (a, b) c = (a, b, c)\n\n--if wynikSoFar imie indeks >= m then imie else licz xs\n\nzmienWTrojki :: [(String, Int)] -> [(String, Int, Int)]\nzmienWTrojki l = zipWith ztrojkuj l [1..]\n\n--czyli mamy trojki, teraz mozemy to posumowac\n\nwynikSoFar :: Int -> String -> Int -> [(String, Int, Int)] -> Int\nwynikSoFar aktualny imie indeks [] = aktualny\nwynikSoFar aktualny imie indeks ((imie1, liczba1, indeks1):xs) = if indeks < indeks1 then aktualny else ( if imie == imie1 then wynikSoFar (aktualny+liczba1) imie indeks xs else wynikSoFar aktualny imie indeks xs )\n\nznajdzWynik :: [(String, Int, Int)] -> Int -> [(String, Int)] -> [String] -> String\nznajdzWynik ((imie, liczba, indeks):xs) maksik lista zwyciezcy = if ((wynikSoFar 0 imie indeks (zmienWTrojki lista) >= maksik) && (elem imie zwyciezcy)) then imie else znajdzWynik xs maksik lista zwyciezcy\n\nziomek :: [(String, Int)] -> String\nziomek l = znajdzWynik (zmienWTrojki l) maks l zwyciezcy\n where\n maks = (maximum.drugie.sumujPoWyniku.qsort) l\n zwyciezcy = winners l\n\n\nmain = do\n s <- getContents\n let inp = map (parse . words) . tail . lines $ s\n putStrLn $ ziomek inp\n\n\n"}, {"source_code": "import qualified Data.Map as M\nimport Debug.Trace\nimport Data.List (sortBy)\n\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , player :: String\n , roundScore :: Score\n } deriving (Show)\n\ntype Game = M.Map String [Round]\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n \ntotalScore :: [Round] -> Score\ntotalScore = (foldl (+) 0) . (map roundScore)\n\nmaxScore :: Game -> Score\nmaxScore = maximum . M.elems . fmap totalScore\n\nplayersWithMax :: Game -> Game\nplayersWithMax g = M.filter (\\v -> (totalScore v) == ms) g\n where ms = maxScore g\n\nwinner :: Game -> String\nwinner g = case M.size candidates of\n 1 -> M.keys candidates !! 0\n _ -> compareByRound candidates ms\n where \n ms = maxScore g\n candidates = playersWithMax g\n\nupdateRound :: Round -> Score -> Round\nupdateRound r s = Round (roundNumber r) (player r) (s)\n\nroundReachScore :: Score -> [Round] -> Int\nroundReachScore s rs = roundNumber . head $ dropWhile lessThanScore cumulative\n where add r1 r2 = updateRound r2 ((roundScore r1) + (roundScore r2))\n cumulative = scanl1 add rs\n lessThanScore r = (roundScore r) < s\n\ncompareByRound :: Game -> Score -> String\ncompareByRound g s = fst . head . sort . M.toList $ roundForScore\n where\n roundForScore = M.map (roundReachScore s) g\n sort = sortBy (\\x y -> compare (snd x) (snd y))\n\nplayRound :: Round -> Game -> Game\nplayRound r g = M.insertWith (flip (++)) (player r) [r] g\n\nmain :: IO ()\nmain = do\n input <- getLine\n final <- playN $ read input\n putStrLn $ winner final\n\nplayN :: Int -> IO Game\nplayN n = playOne 1 n M.empty\n where playOne r n g\n | r > n = return g\n | otherwise = do\n input <- getLine\n playOne (r + 1) n $ playRound (toRound (input, r)) g\n"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Integer\ntype Name = String\n\ncreateMap :: [(Name, Score)] -> Map.Map Name Score\ncreateMap list = Map.fromListWith (+) list\n\nfindMaxVal :: Map.Map Name Score -> Score\nfindMaxVal map = maximum (Map.elems map)\n\nfilterPlayers :: Map.Map Name Score -> Score -> [Name]\nfilterPlayers map score = filter prediate (Map.keys map)\n where prediate = (\\key -> fromJust (Map.lookup key map) == score)\n\nfindFirst :: [(Name, Score)] -> Map.Map Name Score -> [Name] -> Score -> Name\nfindFirst [] _ _ _ = \"\"\nfindFirst (x:xs) map potentialWinners maxScore = winner\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n newScore = fromJust (Map.lookup name newMap)\n winner\n | newScore >= maxScore && name `elem` potentialWinners = name\n | otherwise = findFirst xs newMap potentialWinners maxScore\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where strings = splitOn \" \" string\n name = strings !! 0\n score = read $ strings !! 1\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = take (read linesToRead) (lines input)\n let records = map toRecord inputs\n let map = createMap records\n let maxVal = findMaxVal map\n let potentialWinners = filterPlayers map maxVal\n let result = findFirst records Map.empty potentialWinners maxVal\n putStrLn $ id (result)\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Arrow (second)\nimport Data.List (mapAccumL)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map (second read . toTuple . words) . tail . lines\n\nsolve :: [(String, Integer)] -> String\nsolve xs = head [ name | (name, score) <- scores, M.member name winners, score >= maxScore ]\n where (lastScores, scores) = mapAccumL f M.empty xs\n f s (x, i) = (M.insertWith (+) x i s, (x, M.findWithDefault 0 x s + i))\n maxScore = maximum (M.elems lastScores)\n winners = M.filter (==maxScore) lastScores\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map read . tail . lines\n\ndata Point = Point { name :: String, score :: Integer }\n\ninstance Show Point where\n show (Point n _) = n\n\ninstance Read Point where\n readsPrec _ s = let [n, p] = words s in [(Point n (read p), \"\")]\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, p) -> p >= maxp && name p `elem` names) scores\n where maxp = maximum $ map snd $ M.toList lastscores\n scores = scanl go (M.empty, Point \"\" 0) pps\n lastscores = fst $ last scores\n names = M.keys $ M.filter (==maxp) lastscores\n go (m, _) p@(Point n _) =\n let newhm = M.insertWith (+++) n p m\n in (newhm, fromJust $ M.lookup n newhm)\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\nimport qualified Data.Map as M\n\nmyTrace :: (Show a) => a -> a\nmyTrace x = traceShow x x\n\ndata LogEntry = LogEntry String Int\n\tderiving (Eq, Show)\n\nscore (LogEntry _ v) = v\nname (LogEntry n _) = n\n\ninstance Ord LogEntry where\n\t(<=) (LogEntry _ a) (LogEntry _ b) = a <= b\n\ngetInput = do\n\tn <- (liftM read) getLine :: IO Int\n\tlines <- sequence $ replicate n getLine\n\treturn $ map parseEntry lines\n\nparseEntry s = LogEntry name deltaScore\n\twhere\n\t\tparts = words s\n\t\tname = head parts\n\t\tdeltaScore = read $ parts !! 1\n\nfoldLog :: [LogEntry] -> (Int, [LogEntry])\nfoldLog log = (maxValue, filter (\\(LogEntry n v) -> maxValue == M.findWithDefault 0 n m) entries)\n\twhere\n\t\tmaxValue = snd $ maximumBy (\\(k1, a1) (k2, a2) -> a1 `compare` a2) $ M.toList m\n\t\t(m, entries) = mapAccumL foldEntry M.empty log\n\t\tfoldEntry :: M.Map String Int -> LogEntry -> (M.Map String Int, LogEntry)\n\t\tfoldEntry m (LogEntry name deltaScore) = (newMap, LogEntry name newScore)\n\t\t\twhere\n\t\t\t\tnewScore = deltaScore + M.findWithDefault 0 name m\n\t\t\t\tnewMap = M.insert name newScore m\n\nwinner (maxValue, foldedLog) = name $ head $ filter (\\(LogEntry _ value) -> value >= maxValue) foldedLog\n\nmain = do\n\tlog <- getInput\n\tputStrLn $ winner $ foldLog log\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nwinner :: [(String, Int)] -> String\nwinner rounds = f M.empty rounds'\n where\n rounds' = [(k, v) | (k, v) <- rounds, S.member k cands]\n\n game = M.fromListWith (+) rounds\n m = maximum $ M.elems game\n cands = S.fromList [k | (k, v) <- M.toList game, v == m]\n\n f :: M.Map String Int -> [(String, Int)] -> String\n f game ((k,v):xs)\n | n >= m = k\n | otherwise = f game' xs\n where game' = M.insertWith (+) k v game\n Just n = M.lookup k game'\n\nbody :: [String] -> [String]\nbody [] = []\nbody (n:xs) = winner rounds : body xs'\n where\n n' = read n\n (ys, xs') = splitAt (n'*2) xs\n rounds = [(k, read v) | [k, v] <- splitEvery 2 ys]\n\nmain = do\n ws <- words `fmap` getContents\n mapM_ putStrLn $ body ws\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nwinner rounds = f M.empty rounds''\n where\n rounds' = [(k, read v) | [k, v] <- splitEvery 2 rounds]\n rounds'' = [(k, v) | (k, v) <- rounds', S.member k cands]\n \n game = M.fromListWith (+) rounds'\n m = maximum [v | (_, v) <- M.toList game]\n cands = S.fromList [k | (k, v) <- M.toList game, v == m] \n\n f :: M.Map String Int -> [(String, Int)] -> String\n f game ((k,v):xs)\n | n >= m = k\n | otherwise = f game' xs\n where game' = M.insertWith (+) k v game\n Just n = M.lookup k game'\n\nbody :: [String] -> [String]\nbody [] = []\nbody (n:xs) = winner ys : body xs'\n where\n n' = read n\n (ys, xs') = splitAt (n'*2) xs\n \nmain = do\n ws <- words `fmap` getContents\n mapM_ putStrLn $ body ws\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Arrow (second)\nimport Data.List (mapAccumL)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map (second read . toTuple . words) . tail . lines\n\nsolve :: [(String, Integer)] -> String\nsolve xs = head [ name | (name, score) <- ms, M.member name winners, score >= maxScore ]\n where (m, ms) = mapAccumL (\\s (x, i) -> (M.insertWith (+) x i s, (x, M.findWithDefault 0 x s + i))) M.empty xs\n maxScore = maximum (M.elems m)\n winners = M.filter (==maxScore) m\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . lines\n\ndata Point = Point { name :: String, score :: Integer }\n\ninstance Show Point where\n show (Point n _) = n\n\ninstance Read Point where\n readsPrec _ s = let [n, p] = words s in [(Point n (read p), \"\")]\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter isWinner scores\n where maxPoint = maximum $ map snd $ M.toList lastscores\n scores = scanl go (M.empty, Point \"\" 0) pps\n lastscores = fst $ last scores\n winnerNames = M.keys $ M.filter (==maxPoint) lastscores\n isWinner (_, p) = p >= maxPoint && name p `elem` winnerNames\n go (m, _) p@(Point n _) =\n let newhm = M.insertWith (+++) n p m\n in (newhm, fromJust $ M.lookup n newhm)\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.Maybe\n\nsplit [] = []\nsplit (x:y:xs) = (x, read y :: Int) : split xs\n\ncandidates x = \n let r = M.fromListWith (+) x \n m = maximum $ M.elems r\n in M.filter (== m) r\n\nverify ((k,v0):xs) m0 \n | v1 == Nothing = verify xs m0\n | fromJust v1 <= v0 = k\n | otherwise = verify xs (M.insertWith (+) k (-v0) m0)\n where v1 = M.lookup k m0\n\n\nmain = do\n s <- getContents\n let l = split . tail . words $ s\n putStrLn $ verify l $ candidates l"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport qualified Data.Map as M\nimport Control.Monad\n\nmain = putStrLn . solve . map words . tail . lines =<< getContents\nsolve s = case ws of\n [w1] -> w1\n _ -> head $ catMaybes $ map snd game\n where f (a,_) [rw,rs] = a' `seq` \n ( a', guard (rw `elem` ws) >>\n M.lookup rw a' >>=\n guard . (>=m) >>\n return rw )\n where a' = M.insertWith (+) rw (read rs) a\n game = scanl f (M.empty,Nothing) s\n final = fst (last game)\n m = M.fold max 0 final\n ws = M.keys (M.filter (==m) final)"}, {"source_code": "\nimport List (maximumBy)\nimport Data.Map (Map, empty, insertWith, assocs, filter, keys, findWithDefault)\n\n{-\n--------------------------------------------------------------------------------\n\nimport HUnit\n\ntestOnePlayer :: Test\ntestOnePlayer = TestList \"TestOnePlayer\"\n [\n Test \"1\" $ assertEq \"Dims\" (solve [(\"Dims\", 1)]),\n Test \"2\" $ assertEq \"Tanya\" (solve [(\"Tanya\", 1)])\n ]\n\ntestTwoPlayers :: Test\ntestTwoPlayers = TestList \"TestTwoPlayers\"\n [\n Test \"1\" $ assertEq \"Dims\" (solve [(\"Dims\", 2), (\"Tanya\", 1)]),\n Test \"2\" $ assertEq \"Tanya\" (solve [(\"Dims\", 1), (\"Tanya\", 2)])\n ]\n\ntestSumScore :: Test\ntestSumScore = Test \"TestSumScore\" $\n assertEq \"Dims\" (solve [(\"Dims\", 2), (\"Dims\", 2), (\"Tanya\", 3)])\n\ntestDifficult :: Test\ntestDifficult = TestList \"TestDifficult\"\n [\n Test \"1\" $ assertEq \"Dims\" (solve [(\"Dims\", 2), (\"Dims\", 2), (\"Tanya\", 4)]),\n Test \"2\" $ assertEq \"Tanya\" (solve [(\"Dims\", 2), (\"Tanya\", 4), (\"Dims\", 2)])\n ]\n\ntestMaxScoreNotWinner :: Test\ntestMaxScoreNotWinner = Test \"TestMaxScoreNotWinner\" $\n assertEq \"Tanya\" (solve [(\"Dims\", 5), (\"Tanya\", 1), (\"Dims\", -5)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq \"andrew\" (solve [(\"mike\", 3), (\"andrew\", 5), (\"mike\", 2)]),\n Test \"2\" $ assertEq \"andrew\" (solve [(\"andrew\", 3), (\"andrew\", 2), (\"mike\", 5)])\n ]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testOnePlayer,\n testTwoPlayers,\n testSumScore,\n testDifficult,\n testMaxScoreNotWinner,\n testInput\n ]\n\n--------------------------------------------------------------------------------\n-}\n\nsolve :: [(String, Int)] -> String\nsolve results = solve' results empty\n where\n map = foldl (flip (\\(name, score) -> insertWith (+) name score)) empty results\n maxScore = snd $ maximumBy (\\x y -> compare (snd x) (snd y)) (assocs map)\n canBeWinners = keys $ Data.Map.filter (== maxScore) map\n solve' [] _ = error \"Logical error.\"\n solve' ((name, score):xs) map\n | name `notElem` canBeWinners = solve' xs map\n | findWithDefault 0 name map' >= maxScore = name\n | otherwise = solve' xs map'\n where\n map' = insertWith (+) name score map\n\ngetResult :: IO (String, Int)\ngetResult = do\n line <- getLine\n let [name, score] = words line\n return (name, read score)\n\nmain :: IO ()\nmain = do\n n <- readLn\n results <- mapM (const getResult) [1..n]\n putStrLn $ solve results\n"}, {"source_code": "import Data.Maybe\nimport qualified Data.Map as M\n\nparse [a,b] = (a,(read b)::Int)\n\nwinners l = M.filter (==m) res\n where \n res = M.fromListWith (+) l\n m = maximum $ M.elems res\n\neval ((p,x):xs) w\n | goal == Nothing = eval xs w\n | x >= fromJust goal = p\n | otherwise = eval xs (M.insertWith (+) p (-x) w)\n where goal = M.lookup p w\n\nmain = do\n s <- getContents\n let inp = map (parse.words) . tail . lines $ s\n putStrLn $ eval inp $ winners inp\n"}, {"source_code": "-- Codeforce 2A\n\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nmain :: IO ()\nmain = do\n getLine\n getContents >>= putStrLn . solve . map ((\\[name, score] -> (name, (read score) :: Int)) . words) . lines\n\nsolve :: [(String, Int)] -> String\nsolve xs = winner xs $ allwinners xs\n\nwinner :: [(String, Int)] -> Map.Map String Int -> String\nwinner ((name, score):xs) all\n | target == Nothing = winner xs all\n | score >= fromJust target = name\n | otherwise = winner xs (Map.insertWith (+) name (-score) all)\n where target = Map.lookup name all\n\nallwinners :: [(String, Int)] -> Map.Map String Int\nallwinners xs = Map.filter (== val) m where\n m = Map.fromListWith (+) xs\n val = maximum $ Map.elems m\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map read . tail . lines\n\ndata Point = Point { name :: String, score :: Integer }\n\ninstance Show Point where\n show (Point n _) = n\n\ninstance Read Point where\n readsPrec _ s = let [n, p] = words s in [(Point n (read p), \"\")]\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, p) -> p >= maxPoint && name p `elem` winnerNames) scores\n where maxPoint = maximum $ map snd $ M.toList lastScores\n scores = scanl go (M.empty, Point \"\" 0) pps\n lastScores = fst $ last scores\n winnerNames = M.keys $ M.filter (==maxPoint) lastScores\n go (m, _) p@(Point n _) =\n let newhm = M.insertWith (+++) n p m\n in (newhm, fromJust $ M.lookup n newhm)\n"}, {"source_code": "module Main where\n\nimport Data.Ord (comparing)\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\ntype Player = String\ntype Score = Int\ntype Round = (Player, Score)\n\nmain :: IO ()\nmain = interact (game . parseRounds)\n\ngame :: [Round] -> Player\ngame rounds = winner winScore candidates candidateRounds where\n\tresults = Map.toList $ Map.fromListWith (+) rounds\n\twinScore = maximum $ map snd results\n\tcandidates = map fst $ filter ((== winScore) . snd) results\n\tcandidateSet = Set.fromList candidates\n\tcandidateRounds = filter ((flip Set.member) candidateSet . fst) rounds\n\nwinner :: Score -> [Player] -> [Round] -> Player\nwinner winScore players = go startScores where\n\tstartScores = Map.fromList $ zip players (repeat 0)\n\tgo scores ((player, score) : rounds)\n\t\t| score' >= winScore = player\n\t\t| otherwise = go scoreMap' rounds\n\t\twhere (Just score', scoreMap') = Map.updateLookupWithKey (const (Just . (+ score))) player scores\n\nparseRounds :: String -> [Round]\nparseRounds = map readRound . tail . lines\n\nreadRound :: String -> Round\nreadRound str = (player, read score)\n\twhere [player, score] = words str\n"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insertWith, toList)\nimport Data.Maybe (fromJust)\n\n\nnewtype Player = Player String deriving (Eq, Ord, Show)\nnewtype Score = Score Int deriving (Eq, Ord, Show)\nnewtype Index = Index Int deriving (Eq, Ord, Show)\ndata Round = Round Player Score Index\ntype ScoreIndex = (Score, Index)\ntype Play = Map Player [ScoreIndex]\n\n\nmain :: IO ()\nmain = interact $ showPlayer . winner . play . rounds\n\twhere showPlayer (Player player) = player\n\n\nwinner :: Play -> Player\nwinner = fst . maximumBy (compareScores `on` snd) . toList\n\ncompareScores :: [ScoreIndex] -> [ScoreIndex] -> Ordering\ncompareScores xs@((x, _) :_) ys@((y, _) :_) = case compare x y of\n\tEQ -> (flip compare `on` scoredIndex x) xs ys\n\tcmp -> cmp\n\nscoredIndex :: Score -> [ScoreIndex] -> Index\nscoredIndex score = snd . fromJust . find ((>= score) . fst) . reverse\n\n\nplay :: [Round] -> Play\nplay = foldl (flip addRound) empty\n\naddRound :: Round -> Play -> Play\naddRound (Round player score index) = insertWith addScore player [(score, index)]\n\naddScore :: [ScoreIndex] -> [ScoreIndex] -> [ScoreIndex]\naddScore [(Score score, index)] rest@((Score acc, _) :_) = (Score (score + acc), index) : rest\n\n\nrounds :: String -> [Round]\nrounds str = zipWith ($) rounds indexes where\n\trounds = map readRound . tail . lines $ str\n\tindexes = map Index [1 ..]\n\nreadRound :: String -> Index -> Round\nreadRound str = Round (Player player) (Score $ read score)\n\twhere [player, score] = words str\n"}, {"source_code": "import Data.List as L (filter, find, mapAccumL)\nimport Data.Map.Strict as M (empty, insert, filter, findWithDefault, member, toList)\n\nmain = interact $ winner . play . rounds . tail . words \n\nwinner (totals, rounds) = fst winner where\n max = maximum . map snd $ toList totals\n winners = M.filter (== max) totals\n Just winner = find ((>= max) . snd) $ L.filter ((flip member) winners . fst) rounds\n\nplay = mapAccumL addRound empty\n\naddRound totals (player, score) = (insert player score' totals, (player, score')) \n where score' = score + findWithDefault 0 player totals\n\nrounds [] = []\nrounds (player : score : rest) = (player, read score) : rounds rest"}, {"source_code": "import Data.List as L (filter, find, mapAccumL)\nimport Data.Map as M (empty, insert, filter, findWithDefault, member, toList)\n\nmain = interact $ winner . play . rounds . tail . words \n\nwinner (totals, rounds) = fst winner where\n max = maximum . map snd $ toList totals\n winners = M.filter (== max) totals\n Just winner = find ((>= max) . snd) $ L.filter ((flip member) winners . fst) rounds\n\nplay = mapAccumL addRound empty\n\naddRound totals (player, score) = (insert player score' totals, (player, score')) \n where score' = score + findWithDefault 0 player totals\n\nrounds [] = []\nrounds (player : score : rest) = (player, read score) : rounds rest"}, {"source_code": "import Data.List as L (filter, find, mapAccumL)\nimport Data.Map.Strict as M (empty, insert, filter, findWithDefault, member, toList)\n\nmain = interact $ winner . play . rounds . tail . words \n\nwinner (totals, rounds) = fst winner where\n max = maximum . map snd $ toList totals\n winners = M.filter (== max) totals\n Just winner = find ((>= max) . snd) $ L.filter ((flip member) winners . fst) rounds\n\nplay = mapAccumL addRound empty\n\naddRound totals (player, score) = score' `seq` (insert player score' totals, (player, score')) \n where score' = score + findWithDefault 0 player totals\n\nrounds [] = []\nrounds (player : score : rest) = (player, read score) : rounds rest"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, foldl', maximumBy)\nimport Data.Map (Map, empty, insertWith, toList)\nimport Data.Maybe (fromJust)\n\n\nnewtype Player = Player String deriving (Eq, Ord, Show)\nnewtype Score = Score Int deriving (Eq, Ord, Show)\nnewtype Index = Index Int deriving (Eq, Ord, Show)\ndata Round = Round Player Score Index\ntype ScoreIndex = (Score, Index)\ntype Play = Map Player [ScoreIndex]\n\n\nmain :: IO ()\nmain = interact $ showPlayer . winner . play . rounds\n\twhere showPlayer (Player player) = player\n\n\nwinner :: Play -> Player\nwinner = fst . maximumBy (compareScores `on` snd) . toList\n\ncompareScores :: [ScoreIndex] -> [ScoreIndex] -> Ordering\ncompareScores xs@((x, _) :_) ys@((y, _) :_) = case compare x y of\n\tEQ -> (flip compare `on` scoredIndex x) xs ys\n\tcmp -> cmp\n\nscoredIndex :: Score -> [ScoreIndex] -> Index\nscoredIndex score = snd . fromJust . find ((>= score) . fst) . reverse\n\n\nplay :: [Round] -> Play\nplay = foldl' (flip addRound) empty\n\naddRound :: Round -> Play -> Play\naddRound (Round player score index) = insertWith addScore player [(score, index)]\n\naddScore :: [ScoreIndex] -> [ScoreIndex] -> [ScoreIndex]\naddScore [(Score score, index)] rest@((Score acc, _) :_) = (Score (score + acc), index) : rest\n\n\nrounds :: String -> [Round]\nrounds str = zipWith ($) rounds indexes where\n\trounds = map readRound . tail . lines $ str\n\tindexes = map Index [1 ..]\n\nreadRound :: String -> Index -> Round\nreadRound str = Round (Player player) (Score $ read score)\n\twhere [player, score] = words str\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.List\nimport Data.Ord\n\ntype Name = String\ntype Score = Int\ntype ID = Int\ntype Record = (Score, ID)\ntype PlainDB = [(Name, Record)]\ntype DB = [(Name, [Record])]\n\nconv :: [String] -> PlainDB\nconv (x : xs) = do\n (id_, [name_, score_]) <- zip [0 ..] . map words $ take (read x) xs\n return $ (name_, (read score_, id_))\n\nmerge :: PlainDB -> DB\nmerge = Map.toList . foldl' f Map.empty where\n f mp (name, others) = Map.insertWith g name [others] mp where\n g [(a, i)] xs@((b, _) : _) = (a + b, i) : xs\n\nsearch :: DB -> String\nsearch = findWinner . pickupCandidates . sortDB where\n score = fst . head . snd\n sortDB = sortBy (flip (comparing score))\n pickupCandidates db = check $ takeWhile ((== best) . score) db where\n best = score $ head db\n check = map (fmap (minimum . map snd . filter ((best <=) . fst))) \n findWinner = fst . minimumBy (comparing snd)\n\nsolve :: [String] -> [String]\nsolve = return . search . merge . conv\n\nmain = interact $ unlines . solve . lines\n\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.List\nmain = do \n n <- read `fmap` getLine\n s <- mapM (\\_ -> (\\[w1, w2] -> (w1, read w2)) `fmap` (words `fmap` getLine)) [1..n]\n let map' = foldl' (\\map (name, score) -> Map.insertWith (+) name score map) Map.empty s\n s' = groupBy (\\(_, a) (_, b) -> a == b) $\n sortBy (\\(_, a) (_, b) -> compare b a) $ Map.toList map'\n s1' = head s'\n if length s1' == 1 then putStrLn $ fst.head $ s1' else do\n let m = snd (head s1')\n winners = map fst s1'\n f map ((name, score):ss) = let map' = Map.insertWith (+) name score map in\n if map' Map.! name >= m then name else f map' ss\n f _ [] = undefined\n putStrLn $ f Map.empty (filter (\\(n,_) -> n `elem` winners) s)\n \n"}, {"source_code": "module Main where\n\nimport qualified Data.Map.Strict as M\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\ntype Score = Int\ntype Scores = M.Map String Score\ntype Action = (String, Score)\n\nname :: Action -> String\nname = fst\n\nscore :: Action -> Score\nscore = snd\n\naddScore :: Score -> Maybe Score -> Score\naddScore x Nothing = x\naddScore x (Just y) = x + y\n\nalterScores :: Scores -> Action -> Scores\nalterScores scores action = M.alter (Just . addScore (score action)) (name action) scores\n\nfindFinalScores :: [Action] -> Scores\nfindFinalScores = foldl' alterScores M.empty\n\nfindWinnerScore :: Scores -> Score\nfindWinnerScore = maximum . M.elems\n\nfindWinner :: Score -> [Action] -> String\nfindWinner winnerScore actions = findWinner0 actions M.empty\n where\n findWinner0 (a:as) scores = if nextScore >= winnerScore then name a else findWinner0 as nextScores\n where\n nextScores = alterScores scores a\n nextScore = fromJust $ M.lookup (name a) nextScores\n\nreadAction :: String -> Action\nreadAction line = let [name, score] = words line in (name, read score)\n\nsolute :: [String] -> String\nsolute inputs = findWinner winnerScore winnerActions\n where\n actions = fmap readAction inputs\n finalScores = findFinalScores actions\n winnerScore = findWinnerScore finalScores\n winners = M.filterWithKey (\\_ score -> score >= winnerScore) finalScores\n winnerActions = filter (\\(n, _) -> M.member n winners) actions\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine :: IO Int\n inputs <- replicateM n getLine\n putStrLn (solute inputs)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.Array\nimport Data.Map\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nneginf = -1000000000\n\n-- \ufffd\u01fd\ufffd\u016a\ufffd\u02fa\u01f9\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\u0364\ufffd\ufffd\ufffd\ufffd\u03a5\ua979\ufffd\u0224\u023a\u01f9\ufffd\ufffd\ufffd\nmaxscore [] mp = foldlWithKey (\\(mx,l) -> \\name -> \\score -> if score>mx then (score,[name]) else if score==mx then (mx,name:l) else (mx,l)) (neginf,[]) mp\nmaxscore ((name,score):xs) mp= let mp' = insertWith (+) name score mp in maxscore xs mp'\n\nsolve ((name,score):xs) mp mx = case Data.Map.lookup name mp of\n Just sc |mx <= (sc+score) -> name\n |otherwise -> solve xs (insert name (score+sc) mp) mx\n Nothing -> solve xs mp mx\n\nsolve' l (mx,mem) = solve l (fromList (zip mem [0..])) mx\n\nmain = do n <- scan ::IO Int\n l <- scans n :: IO [(String,Int)]\n putAnsLn (solve' l (maxscore l empty))"}, {"source_code": "\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.List as List\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\ninstance Show Solution where\n show (Solution m l) = show m ++ \"\\n\" ++ show l\n\nmax2nd :: (Ord b) => [(a, b)] -> Maybe (a, b)\nmax2nd [] = Nothing\nmax2nd [x] = Just x\nmax2nd (x: xs)\n | snd x >= snd (fromJust xsMax) = Just x\n | otherwise = xsMax\n where\n xsMax = max2nd xs\n\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) =\n let\n maxk = snd $ fromJust $ max2nd $ Map.toList m\n winList = filter (\\p -> snd p == maxk) (Map.toList m)\n winNames = fst $ unzip winList\n winCandidats = filter (\\s -> (snd s >= maxk) && (List.elemIndex (fst s) winNames /= Nothing)) l\n in fst $ winCandidats !! 0\n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s updVal m) (l ++ [(s, updVal)])\n where\n updVal = v + (fromJust $ Map.lookup s m)\n\nsolMap :: Solution -> Map.Map String Int\nsolMap (Solution m l) = m\n\nsolList :: Solution -> [(String, Int)]\nsolList (Solution m l) = l\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n{- if (n == 29)\n then putStrLn $ show $ drop 12 pairs\n else return () -}\n let result = foldl solAdd (Solution Map.empty []) pairs\n {- let resultl = scanl solAdd (Solution Map.empty []) pairs\n putStrLn \"before\"\n let shows = map (putStrLn . show) resultl\n sequence shows -}\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import qualified Data.Map as M\n\nsolve :: (M.Map String Int, [(String, Int)]) -> (String, Int) -> (M.Map String Int, [(String, Int)])\nsolve (table, records) (name, score') =\n (M.insert name score table, (name, score) : records)\n where score = score' + M.findWithDefault 0 name table\n\nparse :: [String] -> [(String, Int)]\nparse [] = []\nparse (name : score : rest) = (name, read score::Int) : parse rest\n\nmain :: IO ()\nmain = do\n input <- getContents\n\n let\n (table, records) = foldl solve (M.empty, []) (parse . tail . words $ input)\n highscore = maximum $ M.elems table\n cands = M.filter (== highscore) table\n isWinner (name, score) = score >= highscore && name `M.member` cands\n\n putStrLn . fst . last . filter isWinner $ records\n"}, {"source_code": "import qualified Data.Map.Strict as M\nimport qualified Data.List as L\n\ntype Record = (String, Int, Int) -- name, score, round (mike, 3, 1)\n\nparseRecord:: String->Int->Record\nparseRecord s round=\n (a, read b ::Int, round)\n where (a, b) = break (==' ') s\n \ntype TMap = M.Map String (Int, Int)\ninsertRecord:: Record->TMap->TMap\ninsertRecord (n, s, r) m = \n M.insertWith mergeValue n (s,r) m\n \nmergeValue::(Int, Int)->(Int, Int)->(Int, Int)\nmergeValue (score1, round1) (score2, round2)\n = (score1+score2, if score2>0 then round2 else round1)\n \nwinnerChooser:: String->(Int, Int)->Record->Record\nwinnerChooser name (hiScore, round) cur@(nameC, hiScoreC, roundC)\n |hiScore > hiScoreC = (name, hiScore, round)\n |hiScore == hiScoreC && round < roundC = (name, hiScore, round)\n |otherwise = cur\n\nmain=do\n c<-getContents\n let rs = zipWith parseRecord (tail.lines $ c) [1..]\n let rm = L.foldr insertRecord M.empty rs\n let winner@(name, _, _) = M.foldrWithKey winnerChooser (\"\", 0, 0) rm\n putStrLn name "}, {"source_code": "import qualified Data.Map.Strict as M\nimport qualified Data.List as L\n\nparseRecord s round=\n (a, read b ::Int, round)\n where (a, b) = break (==' ') s\n \ninsertRecord (n, s, r) m = \n M.insertWith mergeValue n (s,r) m\n \nmergeValue (score1, round1) (score2, round2)\n = (score1+score2, if score2>0 then round2 else round1)\n \nwinnerChooser name (hiScore, round) cur@(nameC, hiScoreC, roundC)\n |hiScore > hiScoreC || hiScore == hiScoreC && round < roundC = (name, hiScore, round)\n |otherwise = cur\n\nmain=do\n c<-getContents\n let rs = zipWith parseRecord (tail.lines $ c) [1..]\n let rm = L.foldr insertRecord M.empty rs\n let winner@(name, _, _) = M.foldrWithKey winnerChooser (\"\", 0, 0) rm\n putStrLn name "}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, member, assocs)\n\nnewtype Player = Player String deriving (Eq, Ord, Show)\ntype Score = Int\ntype Round = (Player, Score)\ntype Rounds = [Round]\ntype Totals = Map Player Score\ntype Play = (Rounds, Totals)\n\nmain :: IO ()\nmain = interact $ showPlayer . winner . play \n where showPlayer (Player player, score) = player\n\nwinner :: Play -> Round\nwinner (rounds, totals) = winner where\n max = maximum $ map snd $ assocs totals\n winners = Data.Map.filter (== max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) (reverse rounds)\n\nplay :: String -> Play\nplay str = foldl addRound ([], empty) rounds \n where rounds = map readRound . tail . lines $ str\n\naddRound :: Play -> Round -> Play\naddRound (rounds, totals) (player, score) = ((player, score') : rounds, insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRound :: String -> Round\nreadRound str = (Player player, read score :: Score)\n where [player, score] = words str"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, member, assocs)\n\nmain :: IO ()\nmain = interact $ winner . play \n\nwinner (rounds, totals) = fst winner where\n max = maximum $ map snd $ assocs totals\n winners = Data.Map.filter (== max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) (reverse rounds)\n\nplay str = foldl addRound ([], empty) rounds \n where rounds = map readRound . tail . lines $ str\n\naddRound (rounds, totals) (player, score) = ((player, score') : rounds, insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRound str = (player, read score :: Int)\n where [player, score] = words str"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, member, assocs)\nimport Data.Sequence ((><), (<|), (|>))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as Foldable\n\nmain :: IO ()\nmain = interact $ winner . play \n\nwinner (rounds, totals) = fst winner where\n max = maximum $ map snd $ assocs totals\n winners = Data.Map.filter (== max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) (Foldable.toList rounds)\n\nplay str = foldl addRound (Seq.empty, empty) rounds \n where rounds = readRounds . tail . words $ str\n\naddRound (rounds, totals) (player, score) = (rounds |> (player, score'), insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRounds [] = []\nreadRounds (player:score:rest) = (player, read score :: Int) : readRounds rest"}, {"source_code": "module Main where\n\nimport qualified Data.HashTable as H\nimport Data.Function (on)\nimport Data.List (sortBy, groupBy)\nimport Data.Ord (comparing)\n\nfst3 (x, y, z) = x\nsnd3 (x, y, z) = y\nthd3 (x, y, z) = z\n\ninput [] = []\ninput (player:score:xs) = (player, read score :: Integer) : input xs\n\ntotal = map (\\x -> (foldl acc [] x, sum $ map snd3 x)) \n . groupBy ((==) `on` fst3) \n . sortBy (comparing fst3)\n\nacc [] x = [x]\nacc ((x', y', z'):list) (x, y, z) = (x, y + y', z) : (x', y', z') : list\n\nmain = do\n count <- getLine\n contents <- getContents\n let steps = input $ words contents\n let steps' = zipWith (\\(x,y) z -> (x, y, z)) steps [1..]\n let total' = total steps'\n let max' = maximum $ map snd total'\n let filter' = filter (\\x -> snd x >= max')\n let filter''= filter (\\x -> snd3 x >= max')\n let winners = filter'' $ sortBy (comparing thd3) $ concat $ map fst $ filter' total'\n putStrLn $ fst3 $ head winners\n"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, member, assocs)\n\nmain :: IO ()\nmain = interact $ winner . play \n\nwinner (rounds, totals) = fst winner where\n max = maximum $ map snd $ assocs totals\n winners = Data.Map.filter (== max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) rounds\n\nplay str = foldl addRound ([], empty) rounds \n where rounds = readRounds . tail . words $ str\n\naddRound (rounds, totals) (player, score) = (rounds ++ [(player, score')], insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRounds [] = []\nreadRounds (player:score:rest) = (player, read score :: Int) : readRounds rest"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insertWith, toList)\nimport Data.Maybe (fromJust)\n\n\nnewtype Player = Player String deriving (Eq, Ord, Show)\nnewtype Score = Score Int deriving (Eq, Ord, Show)\nnewtype Index = Index Int deriving (Eq, Ord, Show)\ndata Round = Round Player Score Index\ntype ScoreIndex = (Score, Index)\ntype Play = Map Player [ScoreIndex]\n\n\nmain :: IO ()\nmain = interact $ showPlayer . winner . play . rounds\n where showPlayer (Player player) = player\n\n\nwinner :: Play -> Player\nwinner = fst . maximumBy (compareScores `on` snd) . toList\n\ncompareScores :: [ScoreIndex] -> [ScoreIndex] -> Ordering\ncompareScores xs@((x, _) :_) ys@((y, _) :_) = case compare x y of\n EQ -> (flip compare `on` scoredIndex x) xs ys\n cmp -> cmp\n\nscoredIndex :: Score -> [ScoreIndex] -> Index\nscoredIndex score = snd . fromJust . find ((>= score) . fst) . reverse\n\n\nplay :: [Round] -> Play\nplay = foldl (flip addRound) empty\n\naddRound :: Round -> Play -> Play\naddRound (Round player score index) = insertWith addScore player [(score, index)]\n\naddScore :: [ScoreIndex] -> [ScoreIndex] -> [ScoreIndex]\naddScore [(Score score, index)] rest@((Score acc, _) :_) = (Score (score + acc), index) : rest\n\n\nrounds :: String -> [Round]\nrounds str = zipWith ($) rounds indexes where\n rounds = map readRound . tail . lines $ str\n indexes = map Index [1 ..]\n\nreadRound :: String -> Index -> Round\nreadRound str = Round (Player player) (Score $ read score)\n where [player, score] = words str\n"}, {"source_code": "module Main where\n\nimport qualified Data.HashTable as H\nimport Data.Function (on)\nimport Data.List (sortBy, groupBy)\nimport Data.Ord (comparing)\n\nfst3 (x, y, z) = x\nsnd3 (x, y, z) = y\nthd3 (x, y, z) = z\n\ninput :: [String] -> [(String, Integer)]\ninput [] = []\ninput (player:score:xs) = (player, read score) : input xs\n\ntotal = map (\\x -> (foldl acc [] x, sum $ map snd3 x)) \n . groupBy ((==) `on` fst3) \n . sortBy (comparing fst3)\n\nacc :: [(String, Integer, Integer)] -> (String, Integer, Integer) -> [(String, Integer, Integer)]\nacc [] x = [x]\nacc ((x', y', z'):list) (x, y, z) = (x, y + y', z) : (x', y', z') : list\n\nmain = do\n count <- getLine\n contents <- getContents\n let steps = input $ words contents\n let steps' = zipWith (\\(x,y) z -> (x, y, z)) steps [1..]\n let total' = total steps'\n let max' = maximum $ map snd total'\n let filter' = filter (\\x -> snd x >= max')\n let filter''= filter (\\x -> snd3 x >= max')\n let winners = filter'' $ sortBy (comparing thd3) $ concat $ map fst $ filter' total'\n putStrLn $ fst3 $ head winners\n"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, member, assocs)\n\nmain :: IO ()\nmain = interact $ winner . play \n\nwinner (rounds, totals) = fst winner where\n max = maximum $ map snd $ assocs totals\n winners = Data.Map.filter (== max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) (reverse rounds)\n\nplay str = foldl addRound ([], empty) rounds \n where rounds = readRounds . tail . words $ str\n\naddRound (rounds, totals) (player, score) = ((player, score') : rounds, insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRounds [] = []\nreadRounds (player:score:rest) = (player, read score :: Int) : readRounds rest"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (sortBy, groupBy)\nimport Data.Ord (comparing)\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\ndata Round = Round {\n player :: String ,\n score :: Integer ,\n index :: Integer\n} deriving (Eq, Show)\n\ninput :: Integer -> [String] -> [Round]\ninput _ [] = []\ninput index (player:score:xs) = Round {player = player, score = read score :: Integer, index = index} : input (index + 1) xs\n\nsortRounds = sortBy (comparing index)\n\nwinner rounds = head $ sortRounds $ filter (\\x -> score x >= max) $ concat $ map snd story\n where \n scores = Map.fromListWith (++) [(player round, [round]) | round <- rounds]\n totals = Map.assocs $ Map.map (\\x -> sum $ map score x) scores \n max = maximum $ map snd totals\n candidates = Set.fromList $ map fst $ filter (\\x -> snd x >= max) totals\n winners = Map.filterWithKey (\\player _ -> Set.member player candidates) scores \n story = Map.assocs $ Map.map (\\x -> foldl acc [] (sortRounds x)) winners\n\n\nacc [] x = [x]\nacc (x:list) y = Round {player = player x, score = score x + score y, index = index y} : x : list\n\nmain = do\n count <- getLine\n contents <- getContents\n let rounds = input 0 $ words contents\n putStrLn $ player $ winner rounds\n"}, {"source_code": "import qualified Data.Map as Map\n\ndata Match = Match { matchPlayer :: String\n , matchScore :: Int\n } deriving (Show)\n\nreadMatch :: IO Match\nreadMatch = do\n line <- getLine\n let (name : score : []) = words line\n return $ Match name (read score)\n\nreadMatches :: Int -> IO [Match]\nreadMatches 0 = return []\nreadMatches n = do\n match <- readMatch\n matches <- readMatches (n-1) \n return $ (match : matches)\n\nbestScore :: [Match] -> (Int, [String])\nbestScore ms = bestScore2 ms Map.empty\n where bestScore2 :: [Match] -> Map.Map String Int -> (Int, [String])\n bestScore2 [] results = (score, (Map.keys (Map.filter (==score) results)))\n where score = maximum (Map.elems results)\n bestScore2 (m:ms) results = bestScore2 ms (Map.insertWith (+) (matchPlayer m) (matchScore m) results)\n\nfirstReachingScore :: Int -> [Match] -> String\nfirstReachingScore score matches = f matches Map.empty\n where f :: [Match] -> Map.Map String Int -> String\n f [] results = \"\"\n f (m:ms) results = if (currentScore >= score)\n then matchPlayer m\n else f ms updatedResults\n where currentScore = updatedResults Map.! (matchPlayer m)\n updatedResults = (Map.insertWith (+) (matchPlayer m) (matchScore m) results)\n\nmain = do\n line <- getLine\n let n = read line\n matches <- readMatches n\n let (score, winners) = bestScore matches\n putStrLn $ firstReachingScore score (filter (\\m -> (matchPlayer m) `elem` winners) matches)\n\n \n"}, {"source_code": "-- not FINISHED on 23.11.2018\nimport Control.Monad\nimport Data.List\n\nreadInt :: String -> Int\nreadInt x = read x\n\nmain :: IO ()\nmain = do\n\tn <- fmap readInt getLine\n\troundsRaw <- replicateM n $ do\n\t\t(name:score:_) <- fmap words getLine\n\t\treturn (name, readInt score)\n\tlet roundsNumbered = zip3 x y [1..] where\n\t\t(x, y) = unzip roundsRaw\n\tlet roundsSorted = sortBy (\\(a, _, x) -> \\(b, _, y) -> compare (a, x) (b, y)) roundsNumbered\n\tlet roundsGrouped = groupBy (\\(a, _, _) -> \\(b, _, _) -> a == b) roundsSorted\n\tlet roundsSummed = map (foldl f (\"\", 0)) roundsGrouped where\n\t\tf (_, ss) (n, s, _) = (n, ss+s)\n\tlet maxScore = maximum $ map snd roundsSummed\n\tlet firstTimeSurpassed = map (foldl f (\"\", 0, n+1)) roundsGrouped where\n\t\tf (_, score, round) (name, s, r) = (name, s2, r2) where\n\t\t\ts2 = score + s\n\t\t\tr2 = if s2 >= maxScore then min r round else round\n\tlet best = minimumBy (\\(_, _, x) -> \\(_, _, y) -> compare x y) valid where\n\t\tvalid = filter (\\(_, endScore, _) -> endScore==maxScore) firstTimeSurpassed\n\tlet (bestName, _, _) = best\n\tputStrLn bestName\n\t"}, {"source_code": "module Main where\n\nimport qualified Control.Exception as E\nimport qualified Data.Map as M\n\ntype Acvmts = [(Integer, String)]\ntype Scores = M.Map String Integer\ntype State = (Acvmts, Scores)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessAcvmt :: Integer -> String -> Acvmts -> Acvmts\nprocessAcvmt score name scores = (score, name) : scores\n\nprocessScore :: String -> Integer -> Scores -> Scores\nprocessScore = M.insertWith (+)\n\nprocessResult :: State -> (String, Integer) -> State\nprocessResult (acvmts, scores) (name, score) = (acvmts', scores')\n where\n scores' = processScore name score scores\n acvmts' = processAcvmt score' name acvmts\n score' = let Just x = M.lookup name scores' in x\n\ngetWinner :: State -> String\ngetWinner (acvmts, scores)\n | null acvmts' = show (winners, acvmts, scores)\n | otherwise = snd (last acvmts')\n where\n acvmts' = filter (\\(s, n) -> n `elem` winners && s >= maxScore) acvmts\n winners = M.keys (M.filter (== maxScore) scores)\n maxScore = maximum (M.elems scores)\n\nprocessInput :: Int -> String -> String\nprocessInput n = getWinner . foldl processResult ([], M.empty) . results\n where\n results = map processLine . take n . lines\n\nprocessLine :: String -> (String, Integer)\nprocessLine s = let [name, score] = words s in (name, read score)\n\nmain = do\n n <- getInt\n E.catch (interact $ processInput n) (\\msg -> print (msg :: E.SomeException))\n"}, {"source_code": "module Main where\n\nimport qualified Data.Map as M\n\ntype Acvmts = [(Integer, String)]\ntype Scores = M.Map String Integer\ntype State = (Acvmts, Scores)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessAcvmt :: Integer -> String -> Acvmts -> Acvmts\nprocessAcvmt score name scores = (score, name) : scores\n\nprocessScore :: String -> Integer -> Scores -> Scores\nprocessScore = M.insertWith (+)\n\nprocessResult :: State -> (String, Integer) -> State\nprocessResult (acvmts, scores) (name, score) = (acvmts', scores')\n where\n scores' = processScore name score scores\n acvmts' = processAcvmt score' name acvmts\n score' = let Just x = M.lookup name scores' in x\n\ngetWinner :: State -> String\ngetWinner (acvmts, scores) = snd (last acvmts')\n where\n acvmts' = filter (\\(s, n) -> n `elem` winners && s >= maxScore) acvmts\n winners = M.keys (M.filter (== maxScore) scores)\n maxScore = maximum (M.elems scores)\n\nprocessInput :: Int -> String -> String\nprocessInput n = getWinner . foldl processResult ([], M.empty) . results\n where\n results = map processLine . take n . lines\n\nprocessLine :: String -> (String, Integer)\nprocessLine s = let [name, score] = words s in (name, read score)\n\nmain = do\n n <- getInt\n interact $ processInput n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nfindIndexIn :: [(String, Int)] -> String -> Int\nfindIndexIn list key = \n let keys = map (\\(k, _) -> k) list\n result = elemIndex key keys\n in case result of Just index -> index\n Nothing -> -1\n\nfindAnswer :: [(String, Int)] -> [(String, Int)] -> Int -> [String] -> String\nfindAnswer current ((name, score):others) mx candidates =\n let findIndexInCurrent = findIndexIn current\n index = findIndexInCurrent name \n new = \n if index >= 0\n then \n let prefix = take index current\n suffix = drop (index + 1) current\n update = [(name, score + (snd (current !! index)))]\n in prefix ++ update ++ suffix\n else current ++ [(name, score)]\n currentValue = \n if index >= 0\n then score + (snd ( current !! index ))\n else score\n in if (currentValue >= mx) && (elem name candidates)\n then name\n else findAnswer new others mx candidates\n\ncomputeNameScoreMap :: [(String, Int)] -> [(String, Int)] -> [(String, Int)]\ncomputeNameScoreMap result [] = result\ncomputeNameScoreMap current ((name, score):others) =\n let findIndexInCurrent = findIndexIn current\n index = findIndexInCurrent name \n new = \n if index >= 0\n then \n let prefix = take index current\n suffix = drop (index + 1) current\n update = [(name, score + (snd (current !! index)))]\n in prefix ++ update ++ suffix\n else current ++ [(name, score)]\n in computeNameScoreMap new others\n\nreadInputRow :: Int -> IO (String, Int)\nreadInputRow _ = do\n input <- getLine\n let [name, score_] = words input\n score = read score_ :: Int \n return (name, score)\n\nreadInputs :: IO [(String, Int)]\nreadInputs = do\n input <- getLine\n let n = read input\n inputs <- forM [1..n] readInputRow\n return inputs\n\nsolve :: [(String, Int)] -> String\nsolve list = \n let cnsMap = computeNameScoreMap [] list \n keys = map (\\(k, _) -> k) cnsMap\n mx = foldl (\\c (_, v) -> (if v > c then v else c)) (-1000000) cnsMap\n candidates = map (\\(k, _) -> k) (filter (\\(_, v) -> v == mx) cnsMap)\n answer = findAnswer [] list mx candidates\n in answer\n\nmain = do\n inputs <- readInputs\n printf \"%s\\n\" (solve inputs)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Map.Strict (Map, fromListWith, toList)\nimport Data.List (maximumBy, minimumBy)\n\nmain = do\n n <- readLn\n lst <- sequence $ take n $ repeat B.getLine\n B.putStrLn $ calc n lst\n \ncalc::Int->[B.ByteString]->B.ByteString\ncalc n strLst = let\n lst1 = zipWith zipFun [1..n] strLst\n where \n zipFun a b = (head nameScore, [(a, (read::String->Int) $ B.unpack $ last nameScore)])\n where nameScore = B.split (toEnum $ fromEnum ' ') b\n \n lst2::[(B.ByteString, [(Int,Int)])]\n lst2 = toList $ fromListWith mapFun lst1\n where mapFun ((newNum,newScore):_) xs@((_,oldScore):_) = (newNum, oldScore+newScore) : xs\n \n getScore (_,((_, score):_)) = score\n maxScore = getScore $ maximumBy (\\a b-> compare (getScore a) (getScore b)) lst2\n \n lst3 = filter (\\a->getScore a == maxScore) lst2\n \n getLider (a:[]) = fst a\n getLider lst = fst $ minimumBy (\\(_, num1)(_, num2)->compare num1 num2) (map mapFunc lst)\n where mapFunc (name, numList) = (name, fst $ minimumBy (\\(num1, _)(num2, _)->compare num1 num2) (filter (\\(_, score)->score >= maxScore) numList))\n in\n getLider lst3"}, {"source_code": "import qualified Data.Map as M\nimport Data.Functor ((<$>))\nimport Control.Monad (foldM)\n\nsolve :: (M.Map String Int, [(String, Int)]) -> Int -> IO (M.Map String Int, [(String, Int)])\nsolve (table, records) _ = do\n [name, score'] <- words <$> getLine\n let score = read score' + M.findWithDefault 0 name table\n return (M.insert name score table, (name, score) : records)\n\nmain :: IO ()\nmain = do\n n <- readLn\n (table, records) <- foldM solve (M.empty, []) [1..n]\n let\n pickWinners (highscore', cands') name score\n | score == highscore' = (highscore', M.insert name () cands')\n | score > highscore' = (score, M.singleton name ())\n | otherwise = (highscore', cands')\n --(highscore, cands) = M.foldlWithKey pickWinners (-1, M.empty) table\n highscore = maximum $ M.elems table\n cands = M.filter (== highscore) table\n isWinner (name, score) = score >= highscore && name `M.member` cands\n\n putStrLn . fst . last . filter isWinner $ records\n"}], "negative_code": [{"source_code": "\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nfindIndexIn :: [(String, Int)] -> String -> Int\nfindIndexIn list key = \n let keys = map (\\(k, _) -> k) list\n result = elemIndex key keys\n in case result of Just index -> index\n Nothing -> -1\n\nfindMaxElem :: (String, Int) -> [(String, Int)] -> [(String, Int)] -> (String, Int)\nfindMaxElem maxElem result [] = maxElem\nfindMaxElem maxElem current ((name, score):others) =\n let findIndexInCurrent = findIndexIn current\n index = findIndexInCurrent name \n new = \n if index >= 0\n then \n let prefix = take index current\n suffix = drop (index + 1) current\n update = [(name, score + (snd (current !! index)))]\n in prefix ++ update ++ suffix\n else current ++ [(name, score)]\n newMaxElem = \n if index >= 0\n then \n let v = (score + (snd (current !! index)))\n mx = snd maxElem\n in if v > mx\n then (name, v) \n else maxElem\n else \n let v = score\n mx = snd maxElem\n in if v > mx\n then (name, v)\n else maxElem\n in findMaxElem newMaxElem new others\n\nreadInputRow :: Int -> IO (String, Int)\nreadInputRow _ = do\n input <- getLine\n let [name, score_] = words input\n score = read score_ :: Int \n return (name, score)\n\nreadInputs :: IO [(String, Int)]\nreadInputs = do\n input <- getLine\n let n = read input\n inputs <- forM [1..n] readInputRow\n return inputs\n\nsolve :: [(String, Int)] -> String\nsolve = fst . (findMaxElem (\"foo\", (-1000000)) [])\n\nmain = do\n inputs <- readInputs\n printf \"%s\\n\" (solve inputs)\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nfindIndexIn :: [(String, Int)] -> String -> Int\nfindIndexIn list key = \n let keys = map (\\(k, _) -> k) list\n result = elemIndex key keys\n in case result of Just index -> index\n Nothing -> -1\n\ncalculateScore :: [(String, Int)] -> [(String, Int)] -> [(String, Int)]\ncalculateScore result [] = result\ncalculateScore current ((name, score):others) =\n let findIndexInCurrent = findIndexIn current\n index = findIndexInCurrent name \n new = \n if index >= 0\n then \n let prefix = take index current\n suffix = drop (index + 1) current\n update = [(name, score + (snd (current !! index)))]\n in prefix ++ update ++ suffix\n else current ++ [(name, score)]\n in calculateScore new others\n\ngetMax :: [(String, Int)] -> (String, Int)\ngetMax list =\n let comp = \\a b -> if (snd b) > (snd a)\n then b\n else a\n initial = head list\n in foldl comp initial list\n\nreadInputRow :: Int -> IO (String, Int)\nreadInputRow _ = do\n input <- getLine\n let [name, score_] = words input\n score = read score_ :: Int \n return (name, score)\n\nreadInputs :: IO [(String, Int)]\nreadInputs = do\n input <- getLine\n let n = read input\n inputs <- forM [1..n] readInputRow\n return inputs\n\nsolve :: [(String, Int)] -> String\nsolve = fst . getMax . (calculateScore [])\n\nmain = do\n inputs <- readInputs\n printf \"%s\" (solve inputs)\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\n\nfindIndexIn :: [(String, Int)] -> String -> Int\nfindIndexIn list key = \n let keys = map (\\(k, _) -> k) list\n result = elemIndex key keys\n in case result of Just index -> index\n Nothing -> -1\n\ncalculateScore :: [(String, Int)] -> [(String, Int)] -> [(String, Int)]\ncalculateScore result [] = result\ncalculateScore current ((name, score):others) =\n let findIndexInCurrent = findIndexIn current\n index = findIndexInCurrent name \n new = \n if index >= 0\n then \n let prefix = take index current\n suffix = drop (index + 1) current\n update = [(name, score + (snd (current !! index)))]\n in prefix ++ update ++ suffix\n else current ++ [(name, score)]\n in calculateScore new others\n\ngetMax :: [(String, Int)] -> (String, Int)\ngetMax list =\n let comp = \\a b -> if (snd b) > (snd a)\n then b\n else a\n initial = head list\n in foldl comp initial list\n\nreadInputRow :: Int -> IO (String, Int)\nreadInputRow _ = do\n input <- getLine\n let [name, score_] = words input\n score = read score_ :: Int \n return (name, score)\n\nreadInputs :: IO [(String, Int)]\nreadInputs = do\n input <- getLine\n let n = read input\n inputs <- forM [1..n] readInputRow\n return inputs\n\nsolve :: [(String, Int)] -> String\nsolve = fst . getMax . (calculateScore [])\n\nmain = do\n inputs <- readInputs\n print $ solve inputs\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nfindIndexIn :: [(String, Int)] -> String -> Int\nfindIndexIn list key = \n let keys = map (\\(k, _) -> k) list\n result = elemIndex key keys\n in case result of Just index -> index\n Nothing -> -1\n\ncalculateScore :: [(String, Int)] -> [(String, Int)] -> [(String, Int)]\ncalculateScore result [] = result\ncalculateScore current ((name, score):others) =\n let findIndexInCurrent = findIndexIn current\n index = findIndexInCurrent name \n new = \n if index >= 0\n then \n let prefix = take index current\n suffix = drop (index + 1) current\n update = [(name, score + (snd (current !! index)))]\n in prefix ++ update ++ suffix\n else current ++ [(name, score)]\n in calculateScore new others\n\ngetMax :: [(String, Int)] -> (String, Int)\ngetMax list =\n let comp = \\a b -> if (snd b) > (snd a)\n then b\n else a\n initial = head list\n in foldl comp initial list\n\nreadInputRow :: Int -> IO (String, Int)\nreadInputRow _ = do\n input <- getLine\n let [name, score_] = words input\n score = read score_ :: Int \n return (name, score)\n\nreadInputs :: IO [(String, Int)]\nreadInputs = do\n input <- getLine\n let n = read input\n inputs <- forM [1..n] readInputRow\n return inputs\n\nsolve :: [(String, Int)] -> String\nsolve = fst . getMax . (calculateScore [])\n\nmain = do\n inputs <- readInputs\n printf \"%s\\n\" (solve inputs)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Map.Strict (Map, fromListWith, toList)\nimport Data.List (maximumBy, minimumBy)\n\nmain = do\n n <- readLn\n lst <- sequence $ take n $ repeat B.getLine\n print $ calc n lst\n \ncalc::Int->[B.ByteString]->B.ByteString\ncalc n strLst = let\n lst1 = zipWith zipFun [1..n] strLst\n where \n zipFun a b = (head nameScore, [(a, (read::String->Int) $ B.unpack $ last nameScore)])\n where nameScore = B.split (toEnum $ fromEnum ' ') b\n \n lst2::[(B.ByteString, [(Int,Int)])]\n lst2 = toList $ fromListWith mapFun lst1\n where mapFun ((newNum,newScore):_) xs@((_,oldScore):_) = (newNum, oldScore+newScore) : xs\n \n getScore (_,((_, score):_)) = score\n maxScore = getScore $ maximumBy (\\a b-> compare (getScore a) (getScore b)) lst2\n \n lst3 = filter (\\a->getScore a == maxScore) lst2\n \n getLider (a:[]) = fst a\n getLider lst = fst $ minimumBy (\\(_, num1)(_, num2)->compare num1 num2) (map mapFunc lst)\n where mapFunc (name, numList) = (name, fst $ minimumBy (\\(num1, _)(num2, _)->compare num1 num2) (filter (\\(_, score)->score >= maxScore) numList))\n in\n getLider lst3"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Map.Strict (Map, fromListWith, toList)\nimport Data.List (maximumBy, minimumBy)\n\nmain = do\n n <- readLn\n lst <- sequence $ take n $ repeat B.getLine\n B.putStrLn $ calc n lst\n \ncalc::Int->[B.ByteString]->B.ByteString\ncalc n strLst = let\n lst1 = zipWith zipFun [1..n] strLst\n where \n zipFun a b = (head nameScore, [(a, (read::String->Int) $ B.unpack $ last nameScore)])\n where nameScore = B.split (toEnum $ fromEnum ' ') b\n \n lst2::[(B.ByteString, [(Int,Int)])]\n lst2 = toList $ fromListWith mapFun lst1\n where mapFun ((newNum,newScore):_)((_,oldScore):_) = [(newNum, oldScore+newScore)]\n \n getScore (_,((_, score):_)) = score\n maxScore = getScore $ maximumBy (\\a b-> compare (getScore a) (getScore b)) lst2\n \n lst3 = filter (\\a->getScore a == maxScore) lst2\n \n getLider (a:[]) = fst a\n getLider lst = fst $ minimumBy (\\(_, num1)(_, num2)->compare num1 num2) (map mapFunc lst)\n where mapFunc (name, numList) = (name, fst $ minimumBy (\\(num1, _)(num2, _)->compare num1 num2) (filter (\\(_, score)->score >= maxScore) numList))\n in\n getLider lst3"}, {"source_code": "import qualified Data.Map as M\nimport Data.Functor ((<$>))\nimport Control.Monad (foldM)\n\nsolve :: (M.Map String Int, [(String, Int)]) -> Int -> IO (M.Map String Int, [(String, Int)])\nsolve (table, records) _ = do\n [name, score'] <- words <$> getLine\n let score = read score' + M.findWithDefault 0 name table\n return (M.insert name score table, (name, score) : records)\n\nmain :: IO ()\nmain = do\n n <- readLn\n (table, records) <- foldM solve (M.empty, []) [0..n-1]\n let winScore = snd $ M.findMax table\n putStrLn . fst . head . filter ((>= winScore) . snd) $ reverse records\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.Functor ((<$>))\nimport Control.Monad (foldM)\n\nsolve :: (M.Map String Int, (Int, String)) -> Int -> IO (M.Map String Int, (Int, String))\nsolve (table, (highscore, winner)) _ = do\n [name, score'] <- words <$> getLine\n\n let score = read score' + M.findWithDefault 0 name table\n newScores = if score > highscore\n then (score, name)\n else (highscore, winner)\n\n return (M.insert name score table, newScores)\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn . snd . snd =<< foldM solve (M.empty, (0, \"\")) [0..n-1]\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.Functor ((<$>))\nimport Control.Monad (foldM)\n\nsolve :: (M.Map String Int, [(String, Int)]) -> Int -> IO (M.Map String Int, [(String, Int)])\nsolve (table, records) _ = do\n [name, score'] <- words <$> getLine\n let score = read score' + M.findWithDefault 0 name table\n return (M.insert name score table, (name, score) : records)\n\nmain :: IO ()\nmain = do\n n <- readLn\n (table, records) <- foldM solve (M.empty, []) [0..n-1]\n let winScore = snd $ M.findMax table\n putStrLn . fst . head . filter ((== winScore) . snd) $ reverse records\n"}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\"\npars::String->String\npars s = solve $map helppars $lines s\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = check winners m\n where res = summarize x\n \t m = maxScore $ res\n \t winners = filter ((>=m).snd) res\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (init s)))\n where name = fst (last s)\n\ncheck s m = if snd (addScore (comp (name) s) )==m then name\n\t else check (tail s) m\n\t where name = fst (last s)\n\nclearNames name s = filter (not.compNames name) s\n\nmaxScore s = maximum $ map snd s "}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\"\npars::String->String\npars s = solve $map helppars $lines s\n\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = if length winners == 1 then fst $head winners\n else simulate 0 x m\n where res = summarize x\n \t m = maxScore $ res\n \t winners = filter ((==m).snd) res\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (tail s)))\n where name = fst (head s)\n\n\nsimulate position s m \n-- \u0431\u0435\u0440\u0435\u043c \u043f\u0435\u0440\u0432\u044b\u0435 position+1 \u0441\u0442\u0440\u043e\u043a\n-- \u0438\u0449\u0435\u043c \u0432 \u043d\u0438\u0445 \u0438\u043c\u044f \u0438\u0437 \u0442\u0435\u043a\u0443\u0449\u0435\u0439 \u043f\u043e\u0437\u0438\u0446\u0438\u0438\n-- \u0441\u043a\u043b\u0430\u0434\u044b\u0432\u0430\u0435\u043c \u0432\u0441\u0435 \u0432\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u044f \u043d\u0430 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442\n-- \u0435\u0441\u043b\u0438 \u0432\u0434\u0440\u0443\u0433 \u043c\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0431\u043e\u043b\u044c\u0448\u0435 \u0438\u043b\u0438 \u0440\u0430\u0432\u043d\u044b\u0439 \u043c\u0430\u043a\u0441\u0438\u043c\u0443\u043c\u0443 - \u043c\u044b \u043d\u0430\u0448\u0438\u043b \u043f\u043e\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044f\n | position=m then name\n else simulate (position+1) s m\n\t where name = fst (s!!position)\n\n\nclearNames name s = filter (not.compNames name) s\n\nmaxScore s = maximum $ map snd s "}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\"\npars::String->String\npars s = solve $map helppars $lines s\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = fst $ head $ reverse $ summarize x\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (init s)))\n where name = fst (last s)\n\nclearNames name s = filter (not.compNames name) s"}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\"\npars::String->String\npars s = solve $map helppars $lines s\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = simulate 0 x m\n where res = summarize x\n \t m = maxScore $ res\n \t winners = filter ((>=m).snd) res\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (tail s)))\n where name = fst (head s)\n\n\nsimulate position s m \n | positionString\npars s = solve $map helppars $lines s\n\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = if length winners == 1 then fst $head winners\n else simulate 0 x m\n where res = summarize x\n \t m = maxScore $ res\n \t winners = filter ((>=m).snd) res\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (tail s)))\n where name = fst (head s)\n\n\nsimulate position s m \n-- \u0431\u0435\u0440\u0435\u043c \u043f\u0435\u0440\u0432\u044b\u0435 position+1 \u0441\u0442\u0440\u043e\u043a\n-- \u0438\u0449\u0435\u043c \u0432 \u043d\u0438\u0445 \u0438\u043c\u044f \u0438\u0437 \u0442\u0435\u043a\u0443\u0449\u0435\u0439 \u043f\u043e\u0437\u0438\u0446\u0438\u0438\n-- \u0441\u043a\u043b\u0430\u0434\u044b\u0432\u0430\u0435\u043c \u0432\u0441\u0435 \u0432\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u044f \u043d\u0430 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442\n-- \u0435\u0441\u043b\u0438 \u0432\u0434\u0440\u0443\u0433 \u043c\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0431\u043e\u043b\u044c\u0448\u0435 \u0438\u043b\u0438 \u0440\u0430\u0432\u043d\u044b\u0439 \u043c\u0430\u043a\u0441\u0438\u043c\u0443\u043c\u0443 - \u043c\u044b \u043d\u0430\u0448\u0438\u043b \u043f\u043e\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044f\n | position=m then name\n else simulate (position+1) s m\n\t where name = fst (s!!position)\n\n\nclearNames name s = filter (not.compNames name) s\n\nmaxScore s = maximum $ map snd s "}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\"\npars::String->String\npars s = solve $map helppars $lines s\n\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = simulate 0 x m\n where res = summarize x\n \t m = maxScore $ res\n \t winners = filter ((>=m).snd) res\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (tail s)))\n where name = fst (head s)\n\n\nsimulate position s m \n | position=m then name\n else simulate (position+1) s m\n\t where name = fst (s!!position)\n\n\nclearNames name s = filter (not.compNames name) s\n\nmaxScore s = maximum $ map snd s "}, {"source_code": "\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tputStrLn $ pars buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++ s ++\"\\n\"\n\nexample = \"3\\nmike 3\\n andrew 5\\nmike 2\\n\"\nex2=\"mike 3\\n andrew 5\\nmike 2\\n\"\npars::String->String\npars s = solve $map helppars $lines s\n\nhelppars::String->(String,Int)\nhelppars s = (name,score)\n where \n \t parts= words s\n \t name = head parts\n \t score = read $last parts\n\nsolve::[(String,Int)]->String\nsolve x = fst $ head $ reverse $ winners\n where res = summarize x\n \t m = maxScore $ res\n \t winners = filter ((>=m).snd) res\n\naddScore::[(String,Int)]->(String,Int)\naddScore s = (fst (head s), sum $ map snd s)\n\ncompNames::String->(String,Int)->Bool\ncompNames name1 (name2,score2)= name1==name2\ncomp::String->[(String,Int)]->[(String,Int)]\ncomp name s = filter (compNames name) $ s\n\nsummarize::[(String,Int)]->[(String,Int)]\nsummarize []= [] \nsummarize s = [addScore (comp (name) s )] ++ \n (summarize $ ( clearNames name (init s)))\n where name = fst (last s)\n\nclearNames name s = filter (not.compNames name) s\n\nmaxScore s = maximum $ map snd s "}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tputStr $ winner a\n\nwinner ((name, score):xs) = winner' xs (Map.singleton name score) name\nwinner' []\t\t scores best = best\nwinner' ((name, score):xs) scores best =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just bestScore) = Map.lookup best scores\n\t (Just changedScore) = Map.lookup name newScores\n\t newBest = if bestScore < changedScore then name else best\n\tin winner' xs newScores newBest\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tprint $ winner a\n\nwinner ((name, score):xs) = winner' xs (Map.singleton name score) name\nwinner' []\t\t scores best = best\nwinner' ((name, score):xs) scores best =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just bestScore) = Map.lookup best scores\n\t (Just changedScore) = Map.lookup name newScores\n\t newBest = if bestScore < changedScore then name else best\n\tin winner' xs newScores newBest\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tlet (scores, best) = winner a\n\t (Just bestScore) = Map.lookup best scores\n\t bests \t = Map.filter (\\score -> score == bestScore) scores\n\tputStr $ if size bests == 1\n\t\tthen fst $ head $ Map.toList bests\n\t\telse winner1 a scores bestScore Map.empty\n\nwinner ((name, score):xs) = foldl winner' (Map.singleton name score, name) xs\n\nwinner' (scores, best) (name, score) =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just bestScore)\t= Map.lookup best scores\n\t (Just changedScore) = Map.lookup name newScores\n\tin if bestScore < changedScore\n\t\tthen (newScores, name)\n\t\telse (newScores, best)\n\nwinner1 ((name, score):xs) endScores bestScore scores =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just changedScore) = Map.lookup name newScores\n\t (Just endScore) = Map.lookup name endScores\n\tin if endScore == bestScore && changedScore >= bestScore\n\t\tthen name\n\t\telse winner1 xs endScores bestScore newScores\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tlet (scores, best) = winner a\n\t (Just bestScore) = Map.lookup best scores\n\t bests \t = Map.filter (\\score -> score == bestScore) scores\n\tputStr $ if size bests == 1\n\t\tthen fst $ head $ Map.toList bests\n\t\telse winner1 a scores bestScore Map.empty\n\nwinner ((name, score):xs) = foldl winner' (Map.singleton name score, name) xs\n\nwinner' (scores, best) (name, score) =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just bestScore)\t= Map.lookup best newScores\n\t (Just changedScore) = Map.lookup name newScores\n\tin if bestScore < changedScore\n\t\tthen (newScores, name)\n\t\telse (newScores, best)\n\nwinner1 ((name, score):xs) endScores bestScore scores =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just changedScore) = Map.lookup name newScores\n\t (Just endScore) = Map.lookup name endScores\n\tin if endScore == bestScore && changedScore >= bestScore\n\t\tthen name\n\t\telse winner1 xs endScores bestScore newScores\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tputStr $ winner a\n\nwinner ((name, score):xs) = winner' xs (Map.singleton name score) name\nwinner' []\t\t _\t best = best\nwinner' ((name, score):xs) scores best =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just bestScore) = Map.lookup best newScores\n\t (Just changedScore) = Map.lookup name newScores\n\t newBest = if bestScore < changedScore then name else best\n\tin winner' xs newScores newBest\n"}, {"source_code": "import Data.Map as Map\n\nmain = do\n\tn <- fmap read getLine\n\ta <- mapM (\\_ -> fmap (\\[name, score] -> (name, read score::Int)) $ fmap words getLine) [1..n]\n\tlet (scores, best) = winner a\n\t (Just bestScore) = Map.lookup best scores\n\t bests \t = Map.filter (\\score -> score == bestScore) scores\n\tputStr $ if size bests == 1\n\t\tthen fst $ head $ Map.toList bests\n\t\telse winner1 a scores bestScore Map.empty\n\nwinner ((name, score):xs) = foldl winner' (Map.singleton name score, name) xs\n\nwinner' (scores, best) (name, score) =\n\tlet newScores = Map.insertWith (+) name score scores\n\t bestScore\t\t= Map.fold max 0 scores\n\t (Just changedScore) = Map.lookup name newScores\n\tin if bestScore < changedScore\n\t\tthen (newScores, name)\n\t\telse (newScores, best)\n\nwinner1 ((name, score):xs) endScores bestScore scores =\n\tlet newScores = Map.insertWith (+) name score scores\n\t (Just changedScore) = Map.lookup name newScores\n\t (Just endScore) = Map.lookup name endScores\n\tin if endScore == bestScore && changedScore >= bestScore\n\t\tthen name\n\t\telse winner1 xs endScores bestScore newScores\n"}, {"source_code": "import Data.Map as M\nimport Data.List as L\nimport Debug.Trace (trace)\n\n\ntype Name = String\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , playerName :: Name\n , playerScore :: Score\n } deriving (Show, Eq)\ninstance Ord Round where\n compare r1 r2 = case scores of\n EQ -> rounds\n _ -> scores\n where scores = compare (playerScore r1) (playerScore r2)\n rounds = compare (- (roundNumber r1)) (- (roundNumber r2))\ntype Game = Map Name [Round]\n\nwinner :: Game -> String\nwinner = playerName . maximum . elems . (fmap maxScore)\n \nmaxScore :: [Round] -> Round \nmaxScore = maximum . (scanl combine (Round 0 \"\" 0))\n where combine r1 r2 = Round\n (roundNumber r2)\n (playerName r2)\n ((playerScore r1) + (playerScore r2))\n\nnextRound :: Game -> Round -> Game\nnextRound game round = M.insertWith updateScore name score game\n where name = playerName round\n score = [round]\n updateScore = (++)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n\nrunOnce :: Game -> (String, Int) -> Game\nrunOnce game = nextRound game . toRound\n\nrunTimes :: Int -> IO ()\nrunTimes n = runN 1 n M.empty\n\nrunN :: Int -> Int -> Game -> IO ()\nrunN round total game \n | round > total = putStrLn (winner game)\n | otherwise = do\n scoreInfo <- getLine\n let g = runOnce game (scoreInfo, round)\n runN (round + 1) total g\n\nmain :: IO ()\nmain = getLine >>= runTimes . read"}, {"source_code": "import Data.Map as M\nimport Data.List as L\nimport Debug.Trace (trace)\n\ntype Name = String\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , playerName :: Name\n , playerScore :: Score\n } deriving (Show)\ntype Game = Map Name (Score, Int)\n\nwinner :: Game -> String\nwinner game = fst win\n where win = maximumBy scoreThenRound $ M.toList game\n scoreThenRound (pn, (ps, pr)) (nn, (ns, nr))\n | ps > ns = GT\n | ps < ns = LT\n | otherwise = compare (-pr) (-nr)\n\n----scoreThenRound (Name, (Score, Int)) (Name, (Score, Int))\n--scoreThenRound (pn, (ps, pr)) (nn, (ns, nr))\n-- | ps > ns = GT\n-- | ps < ns = GT\n-- | otherwise = compare pr nr\n\nnextRound :: Game -> Round -> Game\nnextRound game round = M.insertWith updateScore name score game\n where name = playerName round\n score = (playerScore round, roundNumber round)\n updateScore (ps, pr) (ns, nr) = (ps + ns, max pr nr)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n\nrunOnce :: Game -> (String, Int) -> Game\nrunOnce game = nextRound game . toRound\n\nrunTimes :: Int -> IO ()\nrunTimes n = runN 1 n M.empty\n\nrunN :: Int -> Int -> Game -> IO ()\nrunN round total game \n | round > total = putStrLn (winner game)\n | otherwise = do\n scoreInfo <- getLine\n let g = runOnce game (scoreInfo, round)\n runN (round + 1) total g\n\nmain :: IO ()\nmain = getLine >>= runTimes . read"}, {"source_code": "import Data.Map as M\nimport Data.List as L\nimport Control.Applicative (liftA2)\ntype Name = String\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , playerName :: Name\n , playerScore :: Score\n } deriving (Show)\ntype Game = Map Name (Score, Int)\n\nwinner :: Game -> String\nwinner game = fst win\n where win = maximumBy scoreThenRound $ M.toList game\n scoreThenRound (pn, (ps, pr)) (nn, (ns, nr))\n | ps > ns = GT\n | ps < ns = GT\n | otherwise = compare pr nr\n\nnextRound :: Game -> Round -> Game\nnextRound game round = M.insertWith updateScore name score game\n where name = playerName round\n score = (roundNumber round, playerScore round)\n updateScore (ps, pr) (ns, nr) = (ps + ns, nr)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n\nrunOnce :: Game -> (String, Int) -> Game\nrunOnce game = nextRound game . toRound\n\nrunTimes :: Int -> IO String\nrunTimes n = runN 1 n M.empty\n\nrunN :: Int -> Int -> Game -> IO String\nrunN round total game \n | round == total = return (winner game)\n | otherwise = do\n scoreInfo <- getLine\n let g = runOnce M.empty (scoreInfo, round)\n runN (round + 1) total g\n\nmain :: IO String\nmain = getLine >>= runTimes . read"}, {"source_code": "import Data.Map as Map\n\ntype Score = Int\ndata Standing = Standing { score :: Score\n , maxPt :: Score\n , maxPtRound :: Int\n , playerName :: String\n } deriving (Show, Eq)\n\ninstance Ord Standing where\n compare s1 s2\n | (maxPt s1) == (maxPt s2) =\n compare (- (maxPtRound s1)) (- (maxPtRound s2))\n | otherwise = compare (maxPt s1) (maxPt s2)\n\ndata Round = Round { roundNumber :: Int\n , player :: String\n , roundScore :: Score\n } deriving (Show)\ntype Game = Map String Standing\n\nfirstRound :: Round -> Standing\nfirstRound r = Standing\n (roundScore r)\n (roundScore r)\n (roundNumber r)\n (player r)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n \n{- \n Given the current Standing of a user,\n play a round, and update the Standing.\n-} \nuserPlayRound :: Round -> Standing -> Standing\nuserPlayRound r st = Standing\n newScore\n newMaxPoints\n newMaxPointsRound\n (player r)\n where newScore = (score st) + (roundScore r)\n hasNewMax = (roundScore r) > 0\n newMaxPoints = if hasNewMax then newScore else (score st)\n newMaxPointsRound = if hasNewMax then (roundNumber r) else (maxPtRound st)\n{-\n Plays a Round of the game and update the Game state\n-}\nplayRound :: Round -> Game -> Game\nplayRound r g = case Map.member (player r) g of\n True -> Map.adjust (userPlayRound r) (player r) g\n False -> Map.insert (player r) (firstRound r) g\n\nmain :: IO ()\nmain = do\n input <- getLine\n final <- playN $ read input\n putStrLn $ winner final\n\nwinner :: Game -> String\nwinner = playerName . maximum . elems\n\nplayN :: Int -> IO Game\nplayN n = playOne 1 n Map.empty\n where playOne r n g\n | r > n = return g\n | otherwise = do\n input <- getLine\n playOne (r + 1) n $ playRound (toRound (input, r)) g\n"}, {"source_code": "import Data.Map as M\nimport Data.Monoid as Monoid\nimport Data.List as L\nimport Debug.Trace (trace)\n\n\ntype Name = String\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , playerName :: Name\n , playerScore :: Score\n } deriving (Show, Eq)\ntype Game = Map Name [Round]\n\ninstance Monoid Round where\n mempty = Round 0 \"\" 0\n mappend r1 r2 = Round\n (max (roundNumber r1) (roundNumber r2))\n (playerName r2)\n ((playerScore r1) + (playerScore r2))\n\ninstance Ord Round where\n compare r1 r2 = case scores of\n EQ -> rounds\n _ -> scores\n where scores = compare (playerScore r1) (playerScore r2)\n rounds = compare (- (roundNumber r1)) (- (roundNumber r2))\n\n\nwinner :: Game -> String\nwinner = playerName . maximum . elems . (fmap maxScore)\n \nmaxScore :: [Round] -> Round \nmaxScore = maximum . (scanr1 mappend)\n\nnextRound :: Game -> Round -> Game\nnextRound game round = M.insertWith (++) name [round] game\n where name = playerName round\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n\nrunN :: Int -> Int -> Game -> IO ()\nrunN round total game \n | round > total = putStrLn (winner game)\n | otherwise = do\n scoreInfo <- getLine\n let g = nextRound game $ toRound (scoreInfo, round)\n runN (round + 1) total g\n\nrunTimes :: Int -> IO ()\nrunTimes n = runN 1 n M.empty\n\nmain :: IO ()\nmain = getLine >>= runTimes . read"}, {"source_code": "import Data.Map as Map\n\ntype Score = Int\ndata Standing = Standing { score :: Score\n , maxPt :: Score\n , maxPtRound :: Int\n , playerName :: String\n } deriving (Show, Eq)\n\ninstance Ord Standing where\n compare s1 s2\n | (maxPt s1) == (maxPt s2) =\n compare (- (maxPtRound s1)) (- (maxPtRound s2))\n | otherwise = compare (maxPt s1) (maxPt s2)\n\ndata Round = Round { roundNumber :: Int\n , player :: String\n , roundScore :: Score\n } deriving (Show)\ntype Game = Map String Standing\n\nfirstRound :: Round -> Standing\nfirstRound r = Standing\n (roundScore r)\n (roundScore r)\n (roundNumber r)\n (player r)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n \n{- \n Given the current Standing of a user,\n play a round, and update the Standing.\n-} \nuserPlayRound :: Round -> Standing -> Standing\nuserPlayRound r st = Standing\n newScore\n newMaxPoints\n newMaxPointsRound\n (player r)\n where newScore = (score st) + (roundScore r)\n hasNewMax = (roundScore r) > 0\n newMaxPoints = if hasNewMax then newScore else (score st)\n newMaxPointsRound = if hasNewMax then (roundNumber r) else (maxPtRound st)\n{-\n Plays a Round of the game and update the Game state\n-}\nplayRound :: Round -> Game -> Game\nplayRound r g = case Map.member (player r) g of\n True -> Map.adjust (userPlayRound r) (player r) g\n False -> Map.insert (player r) (firstRound r) g\n\nmain :: IO ()\nmain = do\n input <- getLine\n final <- playN $ read input\n print $ winner final\n\nwinner :: Game -> String\nwinner = playerName . maximum . elems\n\nplayN :: Int -> IO Game\nplayN n = playOne 1 n Map.empty\n where playOne r n g\n | r > n = return g\n | otherwise = do\n input <- getLine\n playOne (r + 1) n $ playRound (toRound (input, r)) g\n"}, {"source_code": "import Data.Map as M\nimport Data.List as L\nimport Control.Applicative (liftA2)\ntype Name = String\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , playerName :: Name\n , playerScore :: Score\n } deriving (Show)\ntype Game = Map Name (Score, Int)\n\nwinner :: Game -> String\nwinner game = fst win\n where win = maximumBy scoreThenRound $ M.toList game\n scoreThenRound (pn, (ps, pr)) (nn, (ns, nr))\n | ps > ns = GT\n | ps < ns = GT\n | otherwise = compare pr nr\n\nnextRound :: Game -> Round -> Game\nnextRound game round = M.insertWith updateScore name score game\n where name = playerName round\n score = (roundNumber round, playerScore round)\n updateScore (ps, pr) (ns, nr) = (ps + ns, nr)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n\nrunOnce :: Game -> (String, Int) -> Game\nrunOnce game = nextRound game . toRound\n\nrunTimes :: Int -> IO ()\nrunTimes n = runN 1 n M.empty\n\nrunN :: Int -> Int -> Game -> IO ()\nrunN round total game \n | round == total = putStrLn (winner game)\n | otherwise = do\n scoreInfo <- getLine\n let g = runOnce M.empty (scoreInfo, round)\n runN (round + 1) total g\n\nmain :: IO ()\nmain = getLine >>= runTimes . read"}, {"source_code": "import Data.Map as Map\nimport Debug.Trace\n\ntype Score = Int\ndata Standing = Standing { score :: Score\n , maxPt :: Score\n , maxPtRound :: Int\n , playerName :: String\n } deriving (Show, Eq)\n\ninstance Ord Standing where\n compare s1 s2\n | (maxPt s1) == (maxPt s2) =\n compare (- (maxPtRound s1)) (- (maxPtRound s2))\n | otherwise = compare (maxPt s1) (maxPt s2)\n\ndata Round = Round { roundNumber :: Int\n , player :: String\n , roundScore :: Score\n } deriving (Show)\ntype Game = Map String Standing\n\nfirstRound :: Round -> Standing\nfirstRound r = Standing\n (roundScore r)\n (roundScore r)\n (roundNumber r)\n (player r)\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n \n{- \n Given the current Standing of a user,\n play a round, and update the Standing.\n-} \nuserPlayRound :: Round -> Standing -> Standing\nuserPlayRound r st = Standing\n newScore\n newMaxPoints\n newMaxPointsRound\n (player r)\n where newScore = (score st) + (roundScore r)\n hasNewMax = newScore > (maxPt st)\n newMaxPoints = if hasNewMax then newScore else (maxPt st)\n newMaxPointsRound = if hasNewMax then (roundNumber r) else (maxPtRound st)\n{-\n Plays a Round of the game and update the Game state\n-}\nplayRound :: Round -> Game -> Game\nplayRound r g = case Map.member (player r) g of\n True -> Map.adjust (userPlayRound r) (player r) g\n False -> Map.insert (player r) (firstRound r) g\n\nmain :: IO ()\nmain = do\n input <- getLine\n final <- playN $ read input\n putStrLn $ winner final\n\nwinner :: Game -> String\nwinner g = playerName . maximum . elems $ g\n\nplayN :: Int -> IO Game\nplayN n = playOne 1 n Map.empty\n where playOne r n g\n | r > n = return g\n | otherwise = do\n input <- getLine\n playOne (r + 1) n $ playRound (toRound (input, r)) g\n"}, {"source_code": "import Data.Map as M\nimport Data.Monoid as Monoid\nimport Data.List as L\nimport Debug.Trace (trace)\n\n\ntype Name = String\ntype Score = Int\ndata Round = Round { roundNumber :: Int\n , playerName :: Name\n , playerScore :: Score\n } deriving (Show, Eq)\ntype Game = Map Name [Round]\n\ninstance Monoid Round where\n mempty = Round 0 \"\" 0\n mappend r1 r2 = Round\n (max (roundNumber r1) (roundNumber r2))\n (playerName r2)\n ((playerScore r1) + (playerScore r2))\n\ninstance Ord Round where\n compare r1 r2 = case scores of\n EQ -> rounds\n _ -> scores\n where scores = compare (playerScore r1) (playerScore r2)\n rounds = compare (- (roundNumber r1)) (- (roundNumber r2))\n\n\nwinner :: Game -> String\nwinner = playerName . maximum . elems . (fmap maxScore)\n \nmaxScore :: [Round] -> Round \nmaxScore = maximum . (scanl mappend mempty)\n\nnextRound :: Game -> Round -> Game\nnextRound game round = M.insertWith (++) name [round] game\n where name = playerName round\n\ntoRound :: (String, Int) -> Round\ntoRound (roundInfo, roundNum) = Round roundNum name score\n where name = takeWhile (\\x -> x /= ' ') roundInfo\n score = read $ drop (length name + 1) roundInfo\n\nrunN :: Int -> Int -> Game -> IO ()\nrunN round total game \n | round > total = putStrLn (winner game)\n | otherwise = do\n scoreInfo <- getLine\n let g = nextRound game $ toRound (scoreInfo, round)\n runN (round + 1) total g\n\nrunTimes :: Int -> IO ()\nrunTimes n = runN 1 n M.empty\n\nmain :: IO ()\nmain = getLine >>= runTimes . read"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Int\ntype Name = String\n\ncompareScore :: Map.Map Name Score -> Maybe Name -> Maybe Name -> Maybe Name\ncompareScore _ Nothing Nothing = Nothing\ncompareScore _ (Just n) Nothing = Just n\ncompareScore _ Nothing (Just n) = Just n\ncompareScore map (Just a) (Just b)\n | isNothing scoreA && isNothing scoreB = Nothing\n | isNothing scoreA = Just b\n | isNothing scoreB = Just a\n | fromJust scoreA < fromJust scoreB = Just b\n | otherwise = Just a\n where scoreA = Map.lookup a map\n scoreB = Map.lookup b map\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\nfindMax :: [(Name, Score)] -> Map.Map Name Score -> Maybe Name -> Maybe Name\nfindMax [] map older = older\nfindMax (x:xs) map older = findMax xs newMap winner\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n winner = compareScore newMap older (Just name)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where parts = splitOn \" \" string\n name = parts !! 0\n score = read (parts !! 1)\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = lines input\n let records = map toRecord inputs\n let result = findMax records (Map.empty :: Map.Map Name Score) Nothing\n putStrLn $ id (fromJust result)\n"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Integer\ntype Name = String\n\ncreateMap :: [(Name, Score)] -> Map.Map Name Score\ncreateMap list = Map.fromListWith (+) list\n\nfindMaxVal :: Map.Map Name Score -> Score\nfindMaxVal map = maximum (Map.elems map)\n\nfilterPlayers :: Map.Map Name Score -> Score -> [Name]\nfilterPlayers map score = filter prediate (Map.keys map)\n where prediate = (\\key -> fromJust (Map.lookup key map) == score)\n\nfindFirst :: [(Name, Score)] -> Map.Map Name Score -> [Name] -> Score -> Name\nfindFirst [] _ list __ = list !! 0\nfindFirst (x:xs) map queue maxScore = findFirst xs newMap newQueue maxScore\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n oldScore = fromMaybe (maxScore - 1) (Map.lookup name map)\n newScore = fromJust (Map.lookup name newMap)\n newQueue\n | newScore < maxScore = [x | x <- queue, x /= name] -- become lesser\n | oldScore >= maxScore = queue -- already greater\n | otherwise = queue ++ [name]\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where strings = splitOn \" \" string\n name = strings !! 0\n score = read $ strings !! 1\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = take (read linesToRead) (lines input)\n let records = map toRecord inputs\n let maxVal = findMaxVal (createMap records)\n let result = findFirst records Map.empty [] maxVal\n putStrLn $ id (result)\n"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Int\ntype Name = String\n\ncompareScore :: Map.Map Name Score -> Maybe Name -> Maybe Name -> Maybe Name\ncompareScore _ Nothing Nothing = Nothing\ncompareScore _ (Just n) Nothing = Just n\ncompareScore _ Nothing (Just n) = Just n\ncompareScore map (Just a) (Just b)\n | scoreA < scoreB = Just b\n | otherwise = Just a\n where scoreA = fromMaybe (0 :: Score) (Map.lookup a map)\n scoreB = fromMaybe (0 :: Score) (Map.lookup b map)\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\nfindMax :: [(Name, Score)] -> Map.Map Name Score -> Maybe Name -> Maybe Name\nfindMax [] map older = older\nfindMax (x:xs) map older = findMax xs newMap winner\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n winner = compareScore newMap older (Just name)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where parts = splitOn \" \" string\n name = parts !! 0\n score = read (parts !! 1)\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = lines input\n let records = map toRecord inputs\n let result = findMax records (Map.empty :: Map.Map Name Score) Nothing\n print (fromJust result)\n"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Integer\ntype Name = String\n\ncompareScore :: Map.Map Name Score -> Maybe Name -> Maybe Name -> Maybe Name\ncompareScore _ Nothing Nothing = Nothing\ncompareScore _ (Just n) Nothing = Just n\ncompareScore _ Nothing (Just n) = Just n\ncompareScore map (Just a) (Just b)\n | isNothing scoreA && isNothing scoreB = Nothing\n | isNothing scoreA = Just b\n | isNothing scoreB = Just a\n | fromJust scoreA < fromJust scoreB = Just b\n | otherwise = Just a\n where scoreA = Map.lookup a map\n scoreB = Map.lookup b map\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\nfindMax :: [(Name, Score)] -> Map.Map Name Score -> Maybe Name -> Maybe Name\nfindMax [] map older = older\nfindMax (x:xs) map older = findMax xs newMap winner\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n winner = compareScore newMap older (Just name)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where parts = splitOn \" \" string\n name = parts !! 0\n score = read (parts !! 1)\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = lines input\n let records = map toRecord inputs\n let result = findMax records (Map.empty :: Map.Map Name Score) Nothing\n putStrLn $ id (fromJust result)\n"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Integer\ntype Name = String\n\ncreateMap :: [(Name, Score)] -> Map.Map Name Score\ncreateMap list = Map.fromListWith (+) list\n\nfindMaxVal :: Map.Map Name Score -> Score\nfindMaxVal map = maximum (Map.elems map)\n\nfilterPlayers :: Map.Map Name Score -> Score -> [Name]\nfilterPlayers map score = filter prediate (Map.keys map)\n where prediate = (\\key -> fromJust (Map.lookup key map) == score)\n\nfindFirst :: [(Name, Score)] -> Map.Map Name Score -> Score -> Name\nfindFirst [] _ _ = \"\"\nfindFirst (x:xs) map maxScore = winner\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n newScore = fromJust (Map.lookup name newMap)\n winner\n | newScore >= maxScore = name\n | otherwise = findFirst xs newMap maxScore\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where strings = splitOn \" \" string\n name = strings !! 0\n score = read $ strings !! 1\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = take (read linesToRead) (lines input)\n let records = map toRecord inputs\n let maxVal = findMaxVal (createMap records)\n let result = findFirst records Map.empty maxVal\n putStrLn $ id (result)\n"}, {"source_code": "-- Codeforces 2A\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List.Split\nimport Control.Monad\n\ntype Score = Int\ntype Name = String\n\ncompareScore :: Map.Map Name Score -> Maybe Name -> Maybe Name -> Maybe Name\ncompareScore _ Nothing Nothing = Nothing\ncompareScore _ (Just n) Nothing = Just n\ncompareScore _ Nothing (Just n) = Just n\ncompareScore map (Just a) (Just b)\n | scoreA < scoreB = Just b\n | otherwise = Just a\n where scoreA = fromMaybe (0 :: Score) (Map.lookup a map)\n scoreB = fromMaybe (0 :: Score) (Map.lookup b map)\n\nupdateValue :: Score -> Maybe Score -> Maybe Score\nupdateValue x Nothing = Just x\nupdateValue x (Just y) = Just (x + y)\n\nfindMax :: [(Name, Score)] -> Map.Map Name Score -> Maybe Name -> Maybe Name\nfindMax [] map older = older\nfindMax (x:xs) map older = findMax xs newMap winner\n where name = fst x\n score = snd x\n newMap = Map.alter (updateValue score) name map\n winner = compareScore newMap older (Just name)\n\ntoRecord :: String -> (Name, Score)\ntoRecord string = (name, score)\n where parts = splitOn \" \" string\n name = parts !! 0\n score = read (parts !! 1)\n\nmain :: IO ()\nmain = do\n linesToRead <- getLine\n input <- getContents\n let inputs = lines input\n let records = map toRecord inputs\n let result = findMax records (Map.empty :: Map.Map Name Score) Nothing\n putStrLn $ id (fromJust result)\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as M\n\ndata LogEntry = LogEntry String Int\n\tderiving (Eq, Show)\n\nscore (LogEntry _ v) = v\nname (LogEntry n _) = n\n\ninstance Ord LogEntry where\n\t(<=) (LogEntry _ a) (LogEntry _ b) = a <= b\n\ngetInput = do\n\tn <- (liftM read) getLine :: IO Int\n\tlines <- sequence $ replicate n getLine\n\treturn $ map parseEntry lines\n\nparseEntry s = LogEntry name deltaScore\n\twhere\n\t\tparts = words s\n\t\tname = head parts\n\t\tdeltaScore = read $ parts !! 1\n\nfoldLog :: [LogEntry] -> [LogEntry]\nfoldLog log = snd $ mapAccumL foldEntry M.empty log\n\twhere\n\t\tfoldEntry :: M.Map String Int -> LogEntry -> (M.Map String Int, LogEntry)\n\t\tfoldEntry m (LogEntry name deltaScore) = (newMap, LogEntry name newScore)\n\t\t\twhere\n\t\t\t\tnewScore = deltaScore + M.findWithDefault 0 name m\n\t\t\t\tnewMap = M.insert name newScore m\n\nwinner foldedLog = name $ head $ filter (\\(LogEntry _ value) -> value >= maxValue) foldedLog\n\twhere\n\t\t(LogEntry _ maxValue) = maximum foldedLog\n\nmain = do\n\tlog <- getInput\n\tputStrLn $ winner $ foldLog log\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.Map as M\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nwinner rounds = f M.empty rounds'\n where\n rounds' = [(k, read v) | [k, v] <- splitEvery 2 rounds]\n \n game = M.fromListWith (+) rounds'\n m = maximum [v | (_, v) <- M.toList game] \n\n f :: M.Map String Int -> [(String, Int)] -> String\n f game ((k,v):xs)\n | n == m = k\n | otherwise = f game' xs\n where game' = M.insertWith (+) k v game\n Just n = M.lookup k game'\n\nbody :: [String] -> [String]\nbody [] = []\nbody (n:xs) = winner ys : body xs'\n where\n n' = read n\n (ys, xs') = splitAt (n'*2) xs\n \nmain = do\n ws <- words `fmap` getContents\n mapM_ putStrLn $ body ws\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.Map as M\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nwinner rounds = f M.empty rounds'\n where\n rounds' = [(k, read v) | [k, v] <- splitEvery 2 rounds]\n \n game = M.fromListWith (+) rounds'\n m = maximum [v | (_, v) <- M.toList game] \n\n f :: M.Map String Int -> [(String, Int)] -> String\n f game ((k,v):xs)\n | n >= m = k\n | otherwise = f game' xs\n where game' = M.insertWith (+) k v game\n Just n = M.lookup k game'\n\nbody :: [String] -> [String]\nbody [] = []\nbody (n:xs) = winner ys : body xs'\n where\n n' = read n\n (ys, xs') = splitAt (n'*2) xs\n \nmain = do\n ws <- words `fmap` getContents\n mapM_ putStrLn $ body ws\n"}, {"source_code": "import qualified Data.Map as M\n\nsplit [] = []\nsplit (x:y:xs) = (x, read y :: Int) : split xs\n\nfindMax x = let r = M.fromListWith (+) x in maximum $ M.elems r\n\nverify ((k,v0):xs) m0 n = if v1 == n then k else verify xs m1 n\n where m1 = M.insertWith (+) k v0 m0\n v1 = m1 M.! k\n\nmain = do\n s <- getContents\n let l = split . tail . words $ s\n putStrLn $ verify l M.empty (findMax l)"}, {"source_code": "import qualified Data.Map as M\nimport Data.Maybe\n\nsplit [] = []\nsplit (x:y:xs) = (x, read y :: Int) : split xs\n\ncandidates x = \n let r = M.fromListWith (+) x \n m = maximum $ M.elems r\n in M.filter (== m) r\n\nverify ((k,v0):xs) m0 \n | v1 == Nothing = verify xs m0\n | fromJust v1 == v0 = k\n | otherwise = verify xs (M.insertWith (+) k (-v0) m0)\n where v1 = M.lookup k m0\n\n\nmain = do\n s <- getContents\n let l = split . tail . words $ s\n putStrLn $ verify l $ candidates l"}, {"source_code": "import qualified Data.Map as M\n\nsplit [] = []\nsplit (x:y:xs) = (x, read y :: Int) : split xs\n\ncandidates x = \n let r = M.fromListWith (+) x \n m = maximum $ M.elems r\n in M.filter (== m) r\n\nverify ((k,v0):xs) m0 = if v1 == 0 then k else verify xs m1\n where m1 = M.insertWith (+) k (-v0) m0\n v1 = m1 M.! k\n\nmain = do\n s <- getContents\n let l = split . tail . words $ s\n putStrLn $ verify l $ candidates l"}, {"source_code": "split [] = []\nsplit (n:s:xs) = (n, read s :: Int) : (split xs)\n\nsolve (x:xs) = fst (foldl1 better (split xs))\n where better acc@(n1, s1) y@(n2, s2) = if (s1 >= s2) then acc else y\n\nmain = interact $ id . solve . words"}, {"source_code": "-- Codeforce 2A\n\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nmain :: IO ()\nmain = do\n getLine\n getContents >>= putStrLn . solve . map ((\\[name, score] -> (name, (read score) :: Int)) . words) . lines\n\nsolve :: [(String, Int)] -> String\nsolve xs = winner Map.empty xs $ mscore xs\n\nwinner :: Map.Map String Int -> [(String, Int)] -> Int -> String\nwinner m ((name, score):xs) goal\n | val >= goal = name\n | otherwise = winner nxt xs goal\n where\n nxt = Map.insertWith (+) name score m\n val = fromJust $ Map.lookup name nxt\n\nmscore :: [(String, Int)] -> Int\nmscore = maximum . Map.elems . Map.fromListWith (+)\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map (read :: String -> Point) . tail . lines\n\ndata Point = Point String Int\n\ninstance Show Point where\n show (Point name _) = name\n\ninstance Read Point where\n readsPrec _ s = let [name, score] = words s in [(Point name (read score), \"\")]\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nscoreOfPoint :: Point -> Int\nscoreOfPoint (Point _ x) = x\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, pp) -> pp >= maxpp) scores\n where maxpp = maximum $ map snd $ M.toList $ fst $ last scores\n scores = scanl go (M.empty, Point \"\" (scoreOfPoint $ minimum pps)) pps\n go (m, _) pp@(Point name _) =\n let newhm = M.insertWith (+++) name pp m\n in (newhm, fromJust $ M.lookup name newhm)\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Arrow (second)\nimport Data.List (maximumBy)\nimport Data.Function (on)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map (second read . toTuple . words) . tail . lines\n\nsolve :: [(String, Integer)] -> String\nsolve xs = fst $ head [ maximumBy (compare `on` snd) $ M.toList m | m <- ms, s `elem` M.elems m ]\n where ms = scanl (flip $ uncurry $ M.insertWith (+)) M.empty xs\n s = maximum (M.elems (last ms))\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map read . tail . lines\n\ndata Point = Point String Integer\n\ninstance Show Point where\n show (Point name _) = name\n\ninstance Read Point where\n readsPrec _ s = let [name, score] = words s in [(Point name (read score), \"\")]\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nscoreOfPoint :: Point -> Integer\nscoreOfPoint (Point _ x) = x\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, pp) -> pp >= maxpp) scores\n where maxpp = maximum $ map snd $ M.toList $ fst $ last scores\n scores = scanl go (M.empty, Point \"\" 0) pps\n go (m, _) pp@(Point name _) =\n let newhm = M.insertWith (+++) name pp m\n in (newhm, fromJust $ M.lookup name newhm)\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map (read :: String -> Point) . tail . lines\n\ndata Point = Point String Int\n\ninstance Show Point where\n show (Point name _) = name\n\ninstance Read Point where\n readsPrec _ s = let [name, score] = words s in [(Point name (read score), \"\")]\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, pp) -> pp >= maxpp) lastScore\n where maxpp = maximum $ map snd $ M.toList $ fst $ last lastScore\n lastScore = scanl go (M.empty, Point \"\" 0) pps\n go (m, _) pp@(Point name _) =\n let newhm = M.insertWith (+++) name pp m\n in (newhm, fromJust $ M.lookup name newhm)\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map read . tail . lines\n\ndata Point = Point String Int\n\ninstance Show Point where\n show (Point name _) = name\n\ninstance Read Point where\n readsPrec _ s = let [name, score] = words s in [(Point name (read score), \"\")]\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nscoreOfPoint :: Point -> Int\nscoreOfPoint (Point _ x) = x\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, pp) -> pp >= maxpp) scores\n where maxpp = maximum $ map snd $ M.toList $ fst $ last scores\n scores = scanl go (M.empty, Point \"\" 0) pps\n go (m, _) pp@(Point name _) =\n let newhm = M.insertWith (+++) name pp m\n in (newhm, fromJust $ M.lookup name newhm)\n"}, {"source_code": "import qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = interact $ show . solve . map (read :: String -> Point) . tail . lines\n\ndata Point = Point String Int\n\ninstance Show Point where\n show (Point name _) = name\n\ninstance Read Point where\n readsPrec _ s = let [name, score] = words s in [(Point name (read score), \"\")]\n\ninstance Ord Point where\n (<=) (Point _ x) (Point _ y) = (<=) x y\n\ninstance Eq Point where\n (==) (Point _ x) (Point _ y) = (==) x y\n\n(+++) :: Point -> Point -> Point\n(+++) (Point _ x) (Point n y) = Point n (x + y)\n\nsolve :: [Point] -> Point\nsolve pps = snd $ head $ filter (\\(_, pp) -> pp == maxpp) lastScore\n where maxpp = maximum $ map snd $ M.toList $ fst $ last lastScore\n lastScore = scanl go (M.empty, Point \"\" 0) pps\n go (m, _) pp@(Point name _) =\n let newhm = M.insertWith (+++) name pp m\n in (newhm, fromJust $ M.lookup name newhm)\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\n\nmain = putStrLn . solve . map words . tail . lines =<< getContents\nsolve = fst . M.foldrWithKey h (\"\",(minBound::Int,1000)) . fst . foldl' f (M.empty,0)\n where f (m,n) [rw,rs] = m' `seq` n' `seq` (m',n')\n where m' = M.insertWith' g rw (read rs,n) m\n n' = n + 1\n g (s,t) (ps,_) = s' `seq` (s',t) where s' = s+ps\n h n (s,t) (gw,(gs,gt)) = if s > gs && t > gt\n then (n,(s,t))\n else (gw,(gs,gt))\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport qualified Data.Map as M\nimport Control.Monad\n\nmain = putStrLn . solve . map words . tail . lines =<< getContents\nsolve s = case ws of\n [w1] -> w1\n _ -> head $ catMaybes $ map snd game\n where f (a,_) [rw,rs] = a' `seq` \n ( a', guard (rw `elem` ws) >>\n M.lookup rw a' >>=\n guard . (>=m) >>\n return rw )\n where a' = M.insertWith (+) rw (read rs) a\n game = scanl f (M.empty,Nothing) s\n final = fst (last game)\n m = snd (M.findMax final)\n ws = M.keys (M.filter (==m) final)"}, {"source_code": "import Data.List\nmain = putStrLn . solve . map words . tail . lines =<< getContents\nsolve = fst . fst . foldl' f ((\"\",-1001),[])\n where f ((gw,gs),a) [rw,rs] = ((gw',gs'),(rw,rws'):a)\n where rws = maybe 0 id (lookup rw a)\n rws' = rws + read rs\n (gw',gs') = if rws' > gs then (rw,rws') else (gw,gs)\n "}, {"source_code": "import qualified Data.Map as M\nimport Data.List\n\nmain = putStrLn . solve . map words . tail . lines =<< getContents\nsolve = fst . M.foldrWithKey h (\"\",(minBound::Int,1000)) . fst . foldl' f (M.empty,0)\n where f (m,n) [rw,rs] = m' `seq` n' `seq` (m',n')\n where m' = M.insertWith' g rw (read rs,n) m\n n' = n + 1\n g (s,t) (ps,_) = s' `seq` (s',t) where s' = s+ps\n h n (s,t) (gw,(gs,gt)) = if s > gs\n || s == gs && t < gt\n then (n,(s,t))\n else (gw,(gs,gt))\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\nmain = putStrLn . solve . map words . tail . lines =<< getContents\nsolve = fst . M.findMax . fst . foldl' f (M.empty,0)\n where f (m,n) [rw,rs] = m' `seq` n' `seq` (m',n')\n where m' = M.insertWith' g rw (read rs,n) m\n n' = n - 1\n g (s,t) (ps,_) = s' `seq` (s',t) where s' = s+ps"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.List\n\ntype DB = [(String, (Integer, Integer))]\n\nconv :: [String] -> DB\nconv (x : xs) = do\n (i, [name, score]) <- zip [0 ..] . map words $ take (read x) xs\n return $ (name, (read score, i))\n\nmerge :: DB -> DB\nmerge = Map.toList . foldl' f Map.empty where\n f mp (name, others) = Map.insertWith g name others mp where\n g (a, i) (b, _) = (a + b, i)\n\nsearch :: DB -> String\nsearch = fst . maximumBy f where\n f (_, (a, i)) (_, (b, j))\n | a == b = compare j i\n | otherwise = compare a b\n\nsolve :: [String] -> [String]\nsolve = return . search . merge . conv\n\nmain = interact $ unlines . solve . lines\n\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.HashTable\n\nreadLines oldnames oldscore n h hist = \n\tif n > 0 then do {\n\t\tl <- getLine \n\t\t; let {[iname, iscore] = words l}\n\t\t; mv <- Data.HashTable.lookup h iname \n\t\t; case mv of {\n\t \t\tJust v -> update h iname (v + read iscore) >>= \\_ -> return ()\n\t\t\t; Nothing -> Data.HashTable.insert h iname (read iscore)\n\t\t\t}\n\t\t; let {v = fromMaybe 0 mv + read iscore} in\n\t\t\tif v > oldscore || oldnames == [] then \n\t\t\t\treadLines [iname] v (n - 1) h ((iname, iscore):hist)\n\t\t\telse if v == oldscore then\n\t\t\t\treadLines (iname:oldnames) oldscore (n - 1) h ((iname, iscore):hist)\n\t\t\telse \n\t\t\t\treadLines oldnames oldscore (n - 1) h ((iname, iscore):hist)\n\t\t\t}\n\telse case oldnames of {[n] -> return n\n\t\t; s:ss -> do {\n\t\t\th <- new (==) hashString\n\t\t\t; l <- mapM (\\(n, s) -> do {\n\t\t\t\tmv <- Data.HashTable.lookup h n\n\t\t\t\t; case mv of {\n\t\t\t\t\tJust v -> update h n (v + read s) >>= \\_ -> return ()\n\t\t\t\t\t; Nothing -> Data.HashTable.insert h n (read s)\n\t\t\t\t\t}\n\t\t\t\t; return (n, (fromMaybe 0 mv + read s))\n\t\t\t}) $ reverse hist\n\t\t\t; return $ fst $ head $ dropWhile (\\(n, s) -> (s < oldscore) || \n\t\t\t\t(not $ any (==n) oldnames)) l\n\t\t\t}\n\t\t; _ -> return undefined\n\t\t}\n\t\nmain = do {\n\tn <- getLine >>= return . read\n\t; h <- new (==) hashString \n\t; name <- readLines [] 0 n h []\n\t; putStr name\n}\n"}, {"source_code": "import Data.HashTable\nimport Data.Maybe\nimport Data.List\n\nreadLines oldname oldscore n h = \n\tif n > 0 then do {\n\t\tl <- getLine \n\t\t; let {[iname, iscore] = words l}\n\t\t; mv <- Data.HashTable.lookup h iname \n\t\t; case mv of {\n\t \t\t; Just v -> update h iname (v + read iscore) >>= \\_ -> return ()\n\t\t\t; Nothing -> Data.HashTable.insert h iname (read iscore)\n\t\t\t}\n\t\t; let v = fromMaybe 0 mv in\n\t\t\tif v + read iscore > oldscore || oldname == \"\" then \n\t\t\t\treadLines iname (v + read iscore) (n - 1) h\n\t\t\telse if oldname /= iname then\n\t\t\t\treadLines oldname oldscore (n - 1) h\n\t\t\telse do {\n\t\t\t\tl <- toList h \n\t\t\t\t; let (name, score) = head $ \n\t\t\t\t\tsortBy (\\x y -> compare (snd y) (snd x)) l in\n\t\t\t\treadLines name score (n - 1) h\n\t\t\t}\n\t}\n\telse return oldname\n\t\nmain = do {\n\tn <- getLine >>= return . read\n\t; h <- new (==) hashString \n\t; name <- readLines \"\" 0 n h\n\t; putStr name\n}\n"}, {"source_code": "import Data.HashTable\nimport Data.Maybe\n\nreadLines oldname oldscore n h = \n\tif n > 0 then do {\n\t\tl <- getLine \n\t\t; let {[iname, iscore] = words l}\n\t\t; mv <- Data.HashTable.lookup h iname \n\t\t; case mv of {\n\t \t\t; Just v -> update h iname (v + read iscore) >>= \\_ -> return ()\n\t\t\t; Nothing -> insert h iname (read iscore)\n\t\t\t}\n\t\t; let v = fromMaybe 0 mv in\n\t\t\tif v + read iscore > oldscore then \n\t\t\t\treadLines iname (v + read iscore) (n - 1) h\n\t\t\telse\n\t\t\t\treadLines oldname oldscore (n - 1) h\n\t}\n\telse return oldname\n\t\nmain = do {\n\tn <- getLine >>= return . read\n\t; h <- new (==) hashString \n\t; name <- readLines \"\" 0 n h\n\t; putStr name\n}\n"}, {"source_code": "import Data.HashTable\nimport Data.Maybe\nimport Data.List\n\nreadLines oldname oldscore n h = \n\tif n > 0 then do {\n\t\tl <- getLine \n\t\t; let {[iname, iscore] = words l}\n\t\t; mv <- Data.HashTable.lookup h iname \n\t\t; case mv of {\n\t \t\t; Just v -> update h iname (v + read iscore) >>= \\_ -> return ()\n\t\t\t; Nothing -> Data.HashTable.insert h iname (read iscore)\n\t\t\t}\n\t\t; let v = fromMaybe 0 mv in\n\t\t\tif v + read iscore > oldscore || oldname == \"\" then \n\t\t\t\treadLines iname (v + read iscore) (n - 1) h\n\t\t\telse if oldname /= iname then\n\t\t\t\treadLines oldname oldscore (n - 1) h\n\t\t\telse do {\n\t\t\t\tl <- toList h \n\t\t\t\t; let (name, score) = head $ \n\t\t\t\t\tsortBy (\\x y -> compare (fst y) (fst x)) l in\n\t\t\t\treadLines name score (n - 1) h\n\t\t\t}\n\t}\n\telse return oldname\n\t\nmain = do {\n\tn <- getLine >>= return . read\n\t; h <- new (==) hashString \n\t; name <- readLines \"\" 0 n h\n\t; putStr name\n}\n"}, {"source_code": "import Data.HashTable\nimport Data.Maybe\nimport Data.List\n\nreadLines oldnames oldscore n h hist = \n\tif n > 0 then do {\n\t\tl <- getLine \n\t\t; let {[iname, iscore] = words l}\n\t\t; mv <- Data.HashTable.lookup h iname \n\t\t; case mv of {\n\t \t\tJust v -> update h iname (v + read iscore) >>= \\_ -> return ()\n\t\t\t; Nothing -> Data.HashTable.insert h iname (read iscore)\n\t\t\t}\n\t\t; let {v = fromMaybe 0 mv + read iscore} in\n\t\t\tif v > oldscore || oldnames == [] then \n\t\t\t\treadLines [iname] v (n - 1) h ((iname, iscore):hist)\n\t\t\telse if v == oldscore then\n\t\t\t\treadLines (iname:oldnames) oldscore (n - 1) h ((iname, iscore):hist)\n\t\t\telse \n\t\t\t\treadLines oldnames oldscore (n - 1) h ((iname, iscore):hist)\n\t\t\t}\n\telse case oldnames of {[n] -> return n\n\t\t; s:ss -> do {\n\t\t\th <- new (==) hashString\n\t\t\t; l <- mapM (\\(n, s) -> do {\n\t\t\t\tmv <- Data.HashTable.lookup h n\n\t\t\t\t; case mv of {\n\t\t\t\t\tJust v -> update h n (v + read s) >>= \\_ -> return ()\n\t\t\t\t\t; Nothing -> Data.HashTable.insert h n (read s)\n\t\t\t\t\t}\n\t\t\t\t; return (n, (fromMaybe 0 mv + read s))\n\t\t\t}) $ reverse hist\n\t\t\t; return $ fst $ head $ dropWhile ((< oldscore) . snd) l\n\t\t\t}\n\t\t; _ -> return undefined\n\t\t}\n\t\nmain = do {\n\tn <- getLine >>= return . read\n\t; h <- new (==) hashString \n\t; name <- readLines [] 0 n h []\n\t; putStr name\n}\n"}, {"source_code": "module Main where\n\nimport qualified Data.Map.Strict as M\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\ntype Score = Int\ntype Scores = M.Map String Score\ntype Action = (String, Score)\n\nname :: Action -> String\nname = fst\n\nscore :: Action -> Score\nscore = snd\n\naddScore :: Score -> Maybe Score -> Score\naddScore x Nothing = x\naddScore x (Just y) = x + y\n\nalterScores :: Scores -> Action -> Scores\nalterScores scores action = M.alter (Just . addScore (score action)) (name action) scores\n\nfindWinnerScore :: [Action] -> Score\nfindWinnerScore = maximum . M.elems . foldl' alterScores M.empty\n\nfindWinner :: Score -> [Action] -> String\nfindWinner winnerScore actions = findWinner0 actions M.empty\n where\n findWinner0 (a:as) scores = if nextScore >= winnerScore then name a else findWinner0 as nextScores\n where\n nextScores = alterScores scores a\n nextScore = fromJust $ M.lookup (name a) nextScores\n\nreadAction :: String -> Action\nreadAction line = let [name, score] = words line in (name, read score)\n\nsolute :: [String] -> String\nsolute inputs = findWinner winningScore actions\n where\n actions = fmap readAction inputs\n winningScore = findWinnerScore actions\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine :: IO Int\n inputs <- replicateM n getLine\n putStrLn (solute inputs)"}, {"source_code": "module Main where\n\nimport qualified Data.Map.Strict as M\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\ntype Score = Int\n\ndata ScoreState = ScoreState {\n score :: Score,\n name :: String\n} deriving (Show, Eq)\n\ndata GameState = GameState {\n currentWinner :: Maybe ScoreState,\n scores :: M.Map String Score\n} deriving (Show)\n\nzeroScore :: String -> ScoreState\nzeroScore name = ScoreState { name = name, score = 0 }\n\naddScore :: Score -> Maybe Score -> Score\naddScore x Nothing = x\naddScore x (Just y) = x + y\n\nchooseWinner :: ScoreState -> Maybe ScoreState -> ScoreState\nchooseWinner x Nothing = x\nchooseWinner x (Just y) = if score x > score y then x else y\n\nalterScores :: GameState -> ScoreState -> M.Map String Score\nalterScores game action = M.alter (Just . addScore (score action)) (name action) (scores game)\n\nstep :: GameState -> ScoreState -> GameState\nstep game action = GameState { currentWinner = Just nextWinner, scores = nextScores }\n where\n nextScores = alterScores game action\n currentScore = M.findWithDefault 0 (name action) nextScores\n nextWinner = chooseWinner (action { score = currentScore}) (currentWinner game)\n\nreadAction :: String -> ScoreState\nreadAction line = let [name, score] = words line in (ScoreState { name = name, score = read score })\n\nreduceAction :: GameState -> String -> GameState\nreduceAction game line = step game (readAction line)\n\nplayGame :: [String] -> GameState\nplayGame = foldl' reduceAction (GameState Nothing M.empty)\n\nfindWinner :: GameState -> ScoreState\nfindWinner = fromJust . currentWinner\n\nsolute :: [String] -> String\nsolute = name . findWinner . playGame\n\nmain :: IO ()\nmain = do\n n <- read `fmap` getLine :: IO Int\n inputs <- replicateM n getLine\n putStrLn . name . findWinner . playGame $ inputs"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.Map\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nsolve [] _ (name,_) = name\nsolve ((name,score):xs) m (max_name,max_score) = let m' = insertWith (+) name score m in\n case (Data.Map.lookup name m') of\n Nothing -> solve xs m' (max_name,max_score)\n Just sc -> if sc > max_score then\n solve xs m' (name,sc)\n else\n solve xs m' (max_name,max_score)\nmain = do n <- scan ::IO Int\n l <- scans n :: IO [(String,Int)]\n putAnsLn (solve l empty (\"\",-1001))"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust (stable2Max xs)) = Just x\n | otherwise = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s v m) (l ++ [(s, v + (fromJust $ Map.lookup s m))])\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let a = map words sl\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n if (n == 30)\n then putStrLn $ show $ drop 12 pairs\n else return ()\n let result = foldl solAdd (Solution Map.empty []) pairs\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust (stable2Max xs)) = Just x\n | otherwise = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s v m) (l ++ [(s, v + (fromJust $ Map.lookup s m))])\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let a = map words sl\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n if (n == 30)\n then putStrLn $ show scores\n else return ()\n let pairs = zip names scores\n let result = foldl solAdd (Solution Map.empty []) pairs\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust (stable2Max xs)) = Just x\n | otherwise = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s v m) (l ++ [(s, v + (fromJust $ Map.lookup s m))])\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let a = map words sl\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n if (n == 30)\n then putStrLn $ show $ drop 21 pairs\n else return ()\n let result = foldl solAdd (Solution Map.empty []) pairs\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\ninstance Show Solution where\n show (Solution m l) = show m ++ \"\\n\" ++ show l\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust xsMax) = Just x\n | otherwise = xsMax\n where\n xsMax = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s updVal m) (l ++ [(s, updVal)])\n where\n updVal = v + (fromJust $ Map.lookup s m)\n\nsolMap :: Solution -> Map.Map String Int\nsolMap (Solution m l) = m\n\nsolList :: Solution -> [(String, Int)]\nsolList (Solution m l) = l\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n{- if (n == 29)\n then putStrLn $ show $ drop 12 pairs\n else return () -}\n let result = foldl solAdd (Solution Map.empty []) pairs\n {- let resultl = scanl solAdd (Solution Map.empty []) pairs\n putStrLn \"before\"\n let shows = map (putStrLn . show) resultl\n sequence shows -}\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust (stable2Max xs)) = Just x\n | otherwise = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s v m) (l ++ [(s, v + (fromJust $ Map.lookup s m))])\n\nmain = do\n sn <- getLine\n let n =read sn :: Int\n sl <- getLines n\n let a = map words sl\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n let result = foldl solAdd (Solution Map.empty []) pairs\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust (stable2Max xs)) = Just x\n | otherwise = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s v m) (l ++ [(s, v + (fromJust $ Map.lookup s m))])\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let a = map words sl\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n if (n == 30)\n then putStrLn $ show pairs\n else return ()\n let result = foldl solAdd (Solution Map.empty []) pairs\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\ninstance Show Solution where\n show (Solution m l) = show m ++ \"\\n\" ++ show l\n\nstable2Max :: (Ord b) => [(a, b)] -> Maybe (a, b)\nstable2Max [] = Nothing\nstable2Max [x] = Just x\nstable2Max (x: xs)\n | snd x >= snd (fromJust xsMax) = Just x\n | otherwise = xsMax\n where\n xsMax = stable2Max xs\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) = fst $ fromJust $ stable2Max $ reverse l \n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s updVal m) (l ++ [(s, updVal)])\n where\n updVal = v + (fromJust $ Map.lookup s m)\n\nsolMap :: Solution -> Map.Map String Int\nsolMap (Solution m l) = m\n\nsolList :: Solution -> [(String, Int)]\nsolList (Solution m l) = l\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n{- if (n == 29)\n then putStrLn $ show $ drop 12 pairs\n else return () -}\n let result = foldl solAdd (Solution Map.empty []) pairs\n {- let resultl = scanl solAdd (Solution Map.empty []) pairs\n putStrLn \"before\"\n let shows = map (putStrLn . show) resultl\n sequence shows -}\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\n\nallEqual :: (Eq a) => [a] -> Bool\nallEqual [] = True\nallEqual [x] = True\nallEqual (x: y: xs) = (x == y) && allEqual (y: xs)\n\ndata Solution = Solution (Map.Map String Int) [(String, Int)]\n\ninstance Show Solution where\n show (Solution m l) = show m ++ \"\\n\" ++ show l\n\nmax2nd :: (Ord b) => [(a, b)] -> Maybe (a, b)\nmax2nd [] = Nothing\nmax2nd [x] = Just x\nmax2nd (x: xs)\n | snd x >= snd (fromJust xsMax) = Just x\n | otherwise = xsMax\n where\n xsMax = max2nd xs\n\n\nsolAnswer :: Solution -> String\nsolAnswer (Solution m l) =\n let\n maxk = snd $ fromJust $ max2nd $ Map.toList m\n fList = filter (\\p -> snd p >= maxk) l\n in fst $ fList !! 0\n\nsolAdd :: Solution -> (String, Int) -> Solution\nsolAdd (Solution m l) (s, v)\n | (Map.lookup s m) == Nothing = Solution (Map.insert s v m) (l ++ [(s, v)])\n | otherwise = Solution (Map.insert s updVal m) (l ++ [(s, updVal)])\n where\n updVal = v + (fromJust $ Map.lookup s m)\n\nsolMap :: Solution -> Map.Map String Int\nsolMap (Solution m l) = m\n\nsolList :: Solution -> [(String, Int)]\nsolList (Solution m l) = l\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n let (names, sscores) = unzip $ map (\\x -> (x !! 0, x !! 1)) $ map words sl\n let scores = map read sscores :: [Int]\n let pairs = zip names scores\n{- if (n == 29)\n then putStrLn $ show $ drop 12 pairs\n else return () -}\n let result = foldl solAdd (Solution Map.empty []) pairs\n {- let resultl = scanl solAdd (Solution Map.empty []) pairs\n putStrLn \"before\"\n let shows = map (putStrLn . show) resultl\n sequence shows -}\n putStrLn $ solAnswer result\n\n \n"}, {"source_code": "import qualified Data.Map.Strict as M\nimport qualified Data.List as L\n\ntype Record = (String, Int, Int) -- name, score, round (mike, 3, 1)\n\nparseRecord:: String->Int->Record\nparseRecord s round=\n (a, read b ::Int, round)\n where (a, b) = break (==' ') s\n \ntype TMap = M.Map String (Int, Int)\ninsertRecord:: Record->TMap->TMap\ninsertRecord (n, s, r) m = \n M.insertWith mergeValue n (s,r) m\n \nmergeValue::(Int, Int)->(Int, Int)->(Int, Int)\nmergeValue (score1, round1) (score2, round2)\n = (score1+score2, if score1>0 then round1 else round2)\n \nwinnerChooser:: String->(Int, Int)->Record->Record\nwinnerChooser name (hiScore, round) cur@(nameC, hiScoreC, roundC)\n |hiScore > hiScoreC = (name, hiScore, round)\n |hiScore == hiScoreC && round < roundC = (name, hiScore, round)\n |otherwise = cur\n\nmain=do\n c<-getContents\n let rs = zipWith parseRecord (tail.lines $ c) [1..]\n let rm = L.foldr insertRecord M.empty rs\n let winner@(name, _, _) = M.foldrWithKey winnerChooser (\"\", 0, 0) rm\n putStrLn name "}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (sortBy, groupBy)\nimport Data.Ord (comparing)\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\ndata Round = Round {\n player :: String ,\n score :: Integer ,\n index :: Integer\n} deriving (Eq, Show)\n\ninput :: Integer -> [String] -> [Round]\ninput _ [] = []\ninput index (player:score:xs) = Round {player = player, score = read score :: Integer, index = index} : input (index + 1) xs\n\n\nwinner rounds = head $ sortBy (comparing index) $ filter (\\x -> score x >= max) $ concat $ map snd story\n where \n scores = Map.fromListWith (++) [(player round, [round]) | round <- rounds]\n totals = Map.assocs $ Map.map (\\x -> sum $ map score x) scores \n max = maximum $ map snd totals\n candidates = Set.fromList $ map fst $ filter (\\x -> snd x >= max) totals\n winners = Map.filterWithKey (\\player _ -> Set.member player candidates) scores \n story = Map.assocs $ Map.map (\\x -> foldl acc [] x) winners\n\n\nacc [] x = [x]\nacc (x:list) y = Round {player = player x, score = score x + score y, index = index x} : y : list\n\nmain = do\n count <- getLine\n contents <- getContents\n let rounds = input 0 $ words contents\n putStrLn $ player $ winner rounds\n"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, findMax, member)\n\nmain :: IO ()\nmain = interact $ winner . play \n\nwinner (rounds, totals) = fst winner where\n max = snd $ findMax totals\n winners = Data.Map.filter (>= max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) rounds\n\nplay str = foldr addRound ([], empty) rounds \n where rounds = readRounds . tail . words $ str\n\naddRound (player, score) (rounds, totals) = (rounds ++ [(player, score')], insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRounds [] = []\nreadRounds (player:score:rest) = (player, read score :: Int) : readRounds rest\n "}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, findMax, member)\n\nmain :: IO ()\nmain = interact $ show . winner . play \n\nwinner (rounds, totals) = rounds where\n max = snd $ findMax totals\n winners = Data.Map.filter (>= max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) rounds\n\nplay str = foldl addRound ([], empty) rounds \n where rounds = readRounds . tail . words $ str\n\naddRound (rounds, totals) (player, score) = (rounds ++ [(player, score')], insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRounds [] = []\nreadRounds (player:score:rest) = (player, read score :: Int) : readRounds rest"}, {"source_code": "module Main where\n\nimport qualified Data.HashTable as H\nimport Data.Function (on)\nimport Data.List (sortBy, groupBy)\nimport Data.Ord (comparing)\n\nfst3 (x, y, z) = x\nsnd3 (x, y, z) = y\nthd3 (x, y, z) = z\n\ninput :: [String] -> [(String, Integer)]\ninput [] = []\ninput (player:score:xs) = (player, read score) : input xs\n\ntotal = map (\\x -> (foldl acc [] x, sum $ map snd3 x)) \n . groupBy ((==) `on` fst3) \n . sortBy (comparing fst3)\n\nacc :: [(String, Integer, Integer)] -> (String, Integer, Integer) -> [(String, Integer, Integer)]\nacc [] x = [x]\nacc ((x', y', z'):list) (x, y, z) = (x, y + y', z) : (x', y', z') : list\n\nmain = do\n count <- getLine\n contents <- getContents\n let steps = input $ words contents\n let steps' = zipWith (\\(x,y) z -> (x, y, z)) steps [1..]\n let total' = total steps'\n let max' = maximum $ map snd total'\n let filter' = filter (\\x -> snd x >= max')\n let filter''= filter (\\x -> snd3 x >= max')\n let winners = filter'' $ sortBy (comparing thd3) $ concat $ map fst $ filter' total'\n print $ fst3 $ head winners"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (sortBy, groupBy)\nimport Data.Ord (comparing)\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\ndata Round = Round {\n player :: String ,\n score :: Integer ,\n index :: Integer\n} deriving (Eq, Show)\n\ninput :: Integer -> [String] -> [Round]\ninput _ [] = []\ninput index (player:score:xs) = Round {player = player, score = read score :: Integer, index = index} : input (index + 1) xs\n\nsortRounds = sortBy (comparing index)\n\nwinner rounds = head $ sortRounds $ filter (\\x -> score x >= max) $ concat $ map snd story\n where \n scores = Map.fromListWith (++) [(player round, [round]) | round <- rounds]\n totals = Map.assocs $ Map.map (\\x -> sum $ map score x) scores \n max = maximum $ map snd totals\n candidates = Set.fromList $ map fst $ filter (\\x -> snd x >= max) totals\n winners = Map.filterWithKey (\\player _ -> Set.member player candidates) scores \n story = Map.assocs $ Map.map (\\x -> foldl acc [] (sortRounds x)) winners\n\n\nacc [] x = [x]\nacc (x:list) y = Round {player = player x, score = score x + score y, index = index x} : y : list\n\nmain = do\n count <- getLine\n contents <- getContents\n let rounds = input 0 $ words contents\n putStrLn $ player $ winner rounds\n"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insertWith, toList)\nimport Data.Maybe (fromJust)\n\n\nnewtype Player = Player String deriving (Eq, Ord, Show)\nnewtype Score = Score Int deriving (Eq, Ord)\nnewtype Index = Index Int deriving (Eq, Ord)\ndata Round = Round Player Score Index\ntype ScoreIndex = (Score, Index)\ntype Play = Map Player [ScoreIndex]\n\nmain :: IO ()\nmain = interact $ showPlayer . winner . play . rounds\n where showPlayer (Player player) = player\n\nwinner :: Play -> Player\nwinner = fst . maximumBy (compareScores `on` snd) . toList\n\ncompareScores :: [ScoreIndex] -> [ScoreIndex] -> Ordering\ncompareScores xs@((x, _) :_) ys@((y, _) :_) = case compare x y of\n EQ -> (flip compare `on` scoredIndex x) xs ys\n cmp -> cmp\n\nscoredIndex :: Score -> [ScoreIndex] -> Index\nscoredIndex score = snd . fromJust . find ((>= score) . fst) . reverse\n\nplay :: [Round] -> Play\nplay = foldr addRound empty\n\naddRound :: Round -> Play -> Play\naddRound (Round player score index) = insertWith addScore player [(score, index)]\n\naddScore :: [ScoreIndex] -> [ScoreIndex] -> [ScoreIndex]\naddScore [(Score score, index)] rest@((Score acc, _) :_) = (Score (score + acc), index) : rest\n\nrounds :: String -> [Round]\nrounds str = zipWith ($) rounds indexes where\n rounds = map readRound . tail . lines $ str\n indexes = map Index [1 ..]\n\nreadRound :: String -> Index -> Round\nreadRound str = Round (Player player) (Score $ read score)\n where [player, score] = words str\n"}, {"source_code": "module Main where\n\nimport Data.Function (on)\nimport Data.List (find, maximumBy)\nimport Data.Map (Map, empty, insert, filter, findWithDefault, findMax, member)\n\nmain :: IO ()\nmain = interact $ winner . play \n\nwinner (rounds, totals) = fst winner where\n max = snd $ findMax totals\n winners = Data.Map.filter (>= max) totals\n Just winner = find (\\(player, score) -> score >= max && member player winners) rounds\n\nplay str = foldl addRound ([], empty) rounds \n where rounds = readRounds . tail . words $ str\n\naddRound (rounds, totals) (player, score) = (rounds ++ [(player, score')], insert player score' totals) \n where score' = findWithDefault 0 player totals + score\n\nreadRounds [] = []\nreadRounds (player:score:rest) = (player, read score :: Int) : readRounds rest"}, {"source_code": "import Data.Map (Map, empty, elems, insertWith, (!))\n\ndata Match = Match { matchPlayer :: String\n , matchScore :: Int\n } deriving (Show)\n\nreadMatch :: IO Match\nreadMatch = do\n line <- getLine\n let (name : score : []) = words line\n return $ Match name (read score)\n\nreadMatches :: Int -> IO [Match]\nreadMatches 0 = return []\nreadMatches n = do\n match <- readMatch\n matches <- readMatches (n-1) \n return $ (match : matches)\n\nbestScore :: [Match] -> Int\nbestScore ms = bestScore2 ms empty\n where bestScore2 :: [Match] -> Map String Int -> Int\n bestScore2 [] results = maximum (elems results)\n bestScore2 (m:ms) results = bestScore2 ms (insertWith (+) (matchPlayer m) (matchScore m) results)\n\nfirstReachingScore :: Int -> [Match] -> String\nfirstReachingScore score matches = f matches empty\n where f :: [Match] -> Map String Int -> String\n f [] results = \"\"\n f (m:ms) results = if (currentScore >= score)\n then matchPlayer m\n else f ms updatedResults\n where currentScore = updatedResults ! (matchPlayer m)\n updatedResults = (insertWith (+) (matchPlayer m) (matchScore m) results)\n\nmain = do\n line <- getLine\n let n = read line\n matches <- readMatches n\n putStrLn $ firstReachingScore (bestScore matches) matches\n\n \n"}, {"source_code": "-- not FINISHED on 23.11.2018\nimport Control.Monad\nimport Data.List\n\nreadInt :: String -> Int\nreadInt x = read x\n\nmain :: IO ()\nmain = do\n\tn <- fmap readInt getLine\n\tprint n\n\troundsRaw <- replicateM n $ do\n\t\t(name:score:_) <- fmap words getLine\n\t\treturn (name, readInt score)\n\tlet roundsNumbered = zip3 x y [1..] where\n\t\t(x, y) = unzip roundsRaw\n\tlet roundsSorted = sortBy (\\(a, _, x) -> \\(b, _, y) -> compare (a, x) (b, y)) roundsNumbered\n\tlet roundsGrouped = groupBy (\\(a, _, _) -> \\(b, _, _) -> a == b) roundsSorted\n\tlet roundsSummed = map (foldl f (\"\", 0)) roundsGrouped where\n\t\tf (_, ss) (n, s, _) = (n, ss+s)\n\tlet maxScore = maximum $ map snd roundsSummed\n\tlet firstTimeSurpassed = map (foldl f (\"\", 0, n+1)) roundsGrouped where\n\t\tf (_, score, round) (name, s, r) = (name, s2, r2) where\n\t\t\ts2 = score + s\n\t\t\tr2 = if s2 >= maxScore then min r round else round\n\tlet best = minimumBy (\\(_, _, x) -> \\(_, _, y) -> compare x y) firstTimeSurpassed\n\tlet (bestName, _, _) = best\n\tputStrLn bestName\n\t"}, {"source_code": "-- not FINISHED on 23.11.2018\nimport Control.Monad\nimport Data.List\n\nreadInt :: String -> Int\nreadInt x = read x\n\nmain :: IO ()\nmain = do\n\tn <- fmap readInt getLine\n\troundsRaw <- replicateM n $ do\n\t\t(name:score:_) <- fmap words getLine\n\t\treturn (name, readInt score)\n\tlet roundsNumbered = zip3 x y [1..] where\n\t\t(x, y) = unzip roundsRaw\n\tlet roundsSorted = sortBy (\\(a, _, x) -> \\(b, _, y) -> compare (a, x) (b, y)) roundsNumbered\n\tlet roundsGrouped = groupBy (\\(a, _, _) -> \\(b, _, _) -> a == b) roundsSorted\n\tlet roundsSummed = map (foldl f (\"\", 0)) roundsGrouped where\n\t\tf (_, ss) (n, s, _) = (n, ss+s)\n\tlet maxScore = maximum $ map snd roundsSummed\n\tlet firstTimeSurpassed = map (foldl f (\"\", 0, n+1)) roundsGrouped where\n\t\tf (_, score, round) (name, s, r) = (name, s2, r2) where\n\t\t\ts2 = score + s\n\t\t\tr2 = if s2 >= maxScore then min r round else round\n\tlet best = minimumBy (\\(_, _, x) -> \\(_, _, y) -> compare x y) firstTimeSurpassed\n\tlet (bestName, _, _) = best\n\tputStrLn bestName\n\t"}, {"source_code": "module Main where\n\nimport qualified Control.Exception as E\nimport qualified Data.Map as M\nimport Debug.Trace (trace)\n\ntype Acvmts = [(Integer, String)]\ntype Scores = M.Map String Integer\ntype State = (Acvmts, Scores)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessAcvmt :: Integer -> String -> Acvmts -> Acvmts\nprocessAcvmt score name [] = [(score, name)]\nprocessAcvmt score name scores@(x:xs)\n | score > fst x = (score, name) : scores\n | otherwise = scores\n\nprocessScore :: String -> Integer -> Scores -> Scores\nprocessScore = M.insertWith (+)\n\nprocessResult :: State -> (String, Integer) -> State\nprocessResult (acvmts, scores) (name, score) = (acvmts', scores')\n where\n scores' = processScore name score scores\n acvmts' = processAcvmt score' name acvmts\n score' = let Just x = M.lookup name scores' in x\n\ngetWinner :: State -> String\ngetWinner (acvmts, scores)\n | null acvmts' = trace (show (winners, acvmts, scores)) \"\"\n | otherwise = snd (last acvmts')\n where\n acvmts' = filter (\\(s, n) -> n `elem` winners && s >= maxScore) acvmts\n winners = M.keys (M.filter (== maxScore) scores)\n maxScore = maximum (M.elems scores)\n\nprocessInput :: Int -> String -> String\nprocessInput n = getWinner . foldl processResult ([], M.empty) . results\n where\n results = map processLine . take n . lines\n\nprocessLine :: String -> (String, Integer)\nprocessLine s = let [name, score] = words s in (name, read score)\n\nmain = do\n n <- getInt\n E.catch (interact $ processInput n) (\\msg -> print (msg :: E.SomeException))\n"}, {"source_code": "module Main where\n\nimport qualified Control.Exception as E\nimport qualified Data.Map as M\n\ntype Acvmts = [(Integer, String)]\ntype Scores = M.Map String Integer\ntype State = (Acvmts, Scores)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessAcvmt :: Integer -> String -> Acvmts -> Acvmts\nprocessAcvmt score name [] = [(score, name)]\nprocessAcvmt score name scores@(x:xs)\n | score > fst x = (score, name) : scores\n | otherwise = scores\n\nprocessScore :: String -> Integer -> Scores -> Scores\nprocessScore = M.insertWith (+)\n\nprocessResult :: State -> (String, Integer) -> State\nprocessResult (acvmts, scores) (name, score) = (acvmts', scores')\n where\n scores' = processScore name score scores\n acvmts' = processAcvmt score' name acvmts\n score' = let Just x = M.lookup name scores' in x\n\ngetWinner :: State -> String\ngetWinner (acvmts, scores)\n | null acvmts' = show (winners, acvmts, scores)\n | otherwise = snd (last acvmts')\n where\n acvmts' = filter (\\(s, n) -> n `elem` winners && s >= maxScore) acvmts\n winners = M.keys (M.filter (== maxScore) scores)\n maxScore = maximum (M.elems scores)\n\nprocessInput :: Int -> String -> String\nprocessInput n = getWinner . foldl processResult ([], M.empty) . results\n where\n results = map processLine . take n . lines\n\nprocessLine :: String -> (String, Integer)\nprocessLine s = let [name, score] = words s in (name, read score)\n\nmain = do\n n <- getInt\n E.catch (interact $ processInput n) (\\msg -> print (msg :: E.SomeException))\n"}, {"source_code": "module Main where\n\nimport qualified Control.Exception as E\nimport qualified Data.Map as M\n\ntype Acvmts = [(Integer, String)]\ntype Scores = M.Map String Integer\ntype State = (Acvmts, Scores)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessAcvmt :: Integer -> String -> Acvmts -> Acvmts\nprocessAcvmt score name [] = [(score, name)]\nprocessAcvmt score name scores@(x:xs)\n | score > fst x = (score, name) : scores\n | otherwise = scores\n\nprocessScore :: String -> Integer -> Scores -> Scores\nprocessScore = M.insertWith (+)\n\nprocessResult :: State -> (String, Integer) -> State\nprocessResult (acvmts, scores) (name, score) = (acvmts', scores')\n where scores' = processScore name score scores\n acvmts' = processAcvmt score' name acvmts\n score' = let Just x = M.lookup name scores' in x\n\ngetWinner :: State -> String\ngetWinner (acvmts, scores) = snd (last acvmts')\n where acvmts' = filter (\\(s, n) -> n `elem` winners && s >= maxScore) acvmts\n winners = M.keys (M.filter (== maxScore) scores)\n maxScore = maximum (M.elems scores)\n\nprocessInput :: Int -> String -> String\nprocessInput n = getWinner . foldl processResult ([], M.empty) . results\n where results = map processLine . take n . lines\n\nprocessLine :: String -> (String, Integer)\nprocessLine s = let [name, score] = words s in (name, read score)\n\nmain = do\n n <- getInt\n E.catch (interact $ processInput n) (\\msg -> print (msg :: E.SomeException))\n"}], "src_uid": "c9e9b82185481951911db3af72fd04e7"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\n\r\nimport Data.Maybe\r\n\r\nmakeOcc (x:xs) = let m = makeOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m \r\n\tNothing -> M.insert x 1 m\r\nmakeOcc [] = M.empty\r\n\r\nsolve :: Integer -> Integer -> [[Integer]] -> [[Integer]]\r\nsolve n m b = aux b' where\r\n\tb' = fmap makeOcc b\r\n\r\n\taux :: [M.Map Integer Integer] -> [[Integer]]\r\n\taux mL | null $ mL !! 0 = []\r\n\taux mL = let (mL', l) = generatePatch mL in l : aux mL'\r\n\r\n\tgeneratePatch :: [M.Map Integer Integer] -> ([M.Map Integer Integer], [Integer])\r\n\tgeneratePatch mL = (fmap delete $ zip mL choice, choice) where\r\n\t\tminBy = zip [0..] $ fmap (fst . M.findMin) mL\r\n\t\tmaxBy = zip [0..] $ fmap (fst . M.findMax) mL\r\n\r\n\t\tiMin = fromJust $ foldr aux Nothing minBy where\r\n\t\t\taux (i, v) Nothing = Just (i, v)\r\n\t\t\taux (i, v) (Just (i', v'))\r\n\t\t\t\t| v > v' = Just (i', v')\r\n\t\t\t\t| otherwise = Just (i, v)\r\n\r\n\t\tchoice = aux maxBy where\r\n\t\t\taux ((i, v):l)\r\n\t\t\t\t| i == fst iMin = snd iMin : aux l\r\n\t\t\t\t| otherwise = v : aux l\r\n\t\t\taux [] = []\r\n\r\n\t\tdelete (set, v) = case M.lookup v set of \r\n\t\t\tJust 1 -> M.delete v set \r\n\t\t\tJust i -> M.insert v (i-1) set\r\n\r\nshowR :: [[Integer]] -> String\r\nshowR list | length (head list) == 0 = \"\"\r\nshowR list = foldr (\\i l -> show i++\" \"++l) \"\\n\" (fmap head list) ++ showR (fmap tail list)\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[n, m] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tb <- replicateM (fromInteger n) (getLine >>= return . (fmap read) . words) :: IO [[Integer]]\r\n\t\tputStr $ showR $ solve n m b", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nputInts :: [Int] -> Builder\nputInts xs = (mconcat $ intersperse (charUtf8 ' ') $ map intDec xs) `mappend` (charUtf8 '\\n')\n\ntranslate :: Int -> [(Int, Int)] -> [[Int]]\ntranslate n pairs = elems $ accumArray (flip (:)) [] (1, n) $ map (\\(a, b) -> (b, a)) pairs\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n, m] <- getInts\n let getRow i = flip zip (repeat i) <$> getInts\n (targets, rests) <- splitAt m . sort . concat <$> forM [1..n] getRow\n let [ts, rs] = map (translate n) [targets, rests]\n posTargets = flip zip ts $ scanl' (+) 0 $ map length ts\n merge (pos, xs) ys = as ++ xs ++ bs\n where (as, bs) = splitAt pos ys\n results = zipWith merge posTargets rs\n return $ mconcat $ map putInts results\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "a9021fed22299e90aaef50c4d0d9f5b2"} {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve (x, y) = if y `rem` x == 0 then (1, y `quot` x) else (0, 0)\r\n\r\nmain = do\r\n t <- readInt\r\n lines <- replicateM t getLine\r\n let cases = map decodeLine lines\r\n putStrLn $ intercalate \"\\n\" $ map (\\x -> encodeLine $ solve x) cases\r\n \r\n-- Just IO\r\nreadInt = do\r\n line <- getLine\r\n return (read line :: Int)\r\n\r\ndecodeLine line = (read x :: Int, read y :: Int)\r\n where (x, y) = break (==' ') line\r\n\r\nencodeLine (x, y) = show x ++ \" \" ++ show y", "positive_code": [{"source_code": "isInt x = x == fromInteger (round x)\r\n\r\ntest2 :: Double -> Double -> String\r\ntest2 n0 n1\r\n | isInt (n1 / n0) = \"1 \" ++ (show.floor) (n1 / n0)\r\n | 0<1 = \"0 0\"\r\n\r\ntest :: [Double] -> String\r\ntest [] = \"\"\r\ntest ints =\r\n let n0 = head ints\r\n n1 = head $ tail ints\r\n in test2 n0 n1 ++ \"\\n\" ++ (test ((tail.tail) ints))\r\nmain = do\r\n ip <- getContents\r\n let ints = map read $ tail $ words ip \r\n in putStrLn $ test ints"}], "negative_code": [], "src_uid": "f7defb09175c842de490aa13a4f5a0c9"} {"source_code": "import Data.List\n\nmain = getContents >>= putStrLn . show . solve . tail . lines\n\nsolve :: [String] -> Int\nsolve = foldl1 max . map length . group . sort\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = print =<< sol . lines <$> (getLine *> getContents)\n\nsol :: [String] -> Int\nsol xs = length $ filter (==mx) xs\n where\n cnt x = length . filter (==True) $ map (==x) xs\n mx = maximumBy (comparing cnt) xs\n"}, {"source_code": "import Data.List\n\nsolve :: [String] -> Int\nsolve = maximum . map length . group . sort\n\nmain = do\n n <- fmap read getLine\n ss <- mapM (\\_ -> getLine) [1..n]\n print $ solve ss\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n cols <- transpose . map (map (== '1')) <$> replicateM n getLine\n print $ maxClean cols\n\nmultiFilter (True:xs) xss = zipWith (:) (map head xss) (multiFilter xs (map tail xss))\nmultiFilter (False:xs) xss = multiFilter xs (map tail xss)\nmultiFilter [] _ = repeat []\n\nmaxClean ([]:_) = 0\nmaxClean [xs] = let k = length . filter id $ xs in max k (length xs - k)\nmaxClean (xs:xss) = max (maxClean (multiFilter xs xss)) (maxClean (multiFilter (map not xs) xss))\nmaxClean [] = 0\n\n"}, {"source_code": "import Data.List\nmain = interact $ show . solve . tail . lines\nsolve = maximum . map length . group . sort\n"}, {"source_code": "import Data.List (group, sort)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\nmain = read <$> getLine >>= (flip replicateM) getLine >>= print . f\n where f = (last . sort) . (map length) . (group . sort)"}, {"source_code": "import Data.List (group, sort)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\nmain = read <$> getLine >>= (flip replicateM) getLine >>= print . f\n where f = last . sort . map length . group . sort"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = print =<< sol . lines <$> (getLine *> getContents)\n\nsol :: [String] -> Int\nsol xs = length . filter (=='1') $ maximumBy (comparing f) xs\n where\n f x = foldr (\\y ac -> ac+if x==y then 1 else 0) 0 xs\n"}], "src_uid": "f48ddaf1e1db5073d74a2aa318b46704"} {"source_code": "import Data.Int (Int64)\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int64]\n\n let\n f [a] = [a]\n f (a:b:as)\n | gcd a b == 1 = a:(f (b:as))\n | otherwise = a:d:(f (b:as))\n where d = head [d | d <- [1..], gcd a d == 1, gcd d b == 1]\n\n as' = f as\n\n print $ length as' - length as\n putStrLn $ unwords $ map show as'\n", "positive_code": [{"source_code": "import Data.Char\n\nmain = do\n\tline <- getLine\n\tlet (n:xs) = getInts 1 line\n\tline <- getLine\n\tlet ps = getInts n line\n\tlet answer = ans ps []\n\tlet k = length answer - n\n\tputStrLn $ show k\n\tputStrLn $ foldr1 (\\ x st -> st ++ \" \" ++ x) $ map (show) $ answer\n\ngetInts :: Int -> String -> [Int]\n\ngetInts 0 _ = []\ngetInts _ [] = []\ngetInts x str = map stringToInt $ take x $ words str\n\nstringToInt :: String -> Int\n\nstringToInt str = read str :: Int\n\nans :: (Integral a) => [a] -> [a] -> [a]\n\nans [] ret = ret\nans (f:fs) [] = ans fs [f]\nans (f:fs) ret@(s:retms)\n\t| gcd f s == 1 = ans fs (f:ret)\n\t| otherwise = ans fs (f:1:ret)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Array.ST\n-- import Data.Array.Unsafe\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nout = stdout\n\nmain = do\n _ <- readInt1 <$> BS.getLine\n ns <- readIntN <$> BS.getLine\n putAns out . makeTable $ solve ns\n\nsolve :: [Int] -> (Int,[Int])\nsolve ns = go 0 [] ns where\n go :: Int -> [Int] -> [Int] -> (Int,[Int])\n go c ms [y] = (c,reverse (y:ms))\n go c ms (x:y:ns) = if coPrime x y\n then go c (x:ms) (y:ns)\n else go (c+1) (1:x:ms) (y:ns)\n\ncoPrime :: Int -> Int -> Bool\ncoPrime m n = if m >= n then coprime m n else coprime n m where\n coprime m 0 = m == 1\n coprime m n = coprime n (m`mod`n)\n\nmakeTable :: (Int,[Int]) -> Table\nmakeTable (c,ns) = [OneR (IntC c), ListR (map (\\s -> IntC s) ns)]\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)\n\n-- output functions\n\ndata Cell = ByteStringC BL.ByteString\n | IntC Int\n | Int64C Int64\n deriving( Eq, Ord, Show )\n\ndata Row = ListR [Cell]\n | OneR Cell\n | TupleR (Cell,Cell)\n | TripleR (Cell,Cell,Cell)\n deriving( Eq, Ord, Show )\n\ntype Table = [Row]\n\ninfixr 4 <>\n(<>) :: Monoid m => m -> m -> m\n(<>) = mappend\n\nputAns :: Handle -> Table -> IO ()\nputAns o = hPutBuilder o . renderTable\n\nrenderTable :: Table -> Builder\nrenderTable rs = mconcat [renderRow r <> char8 '\\n' | r <- rs]\n\nrenderRow :: Row -> Builder\nrenderRow (ListR []) = mempty\nrenderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]\nrenderRow (OneR x) = renderCell x\nrenderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y\nrenderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z\n\nrenderCell :: Cell -> Builder\nrenderCell (ByteStringC cs) = lazyByteString cs\nrenderCell (IntC i) = intDec i\nrenderCell (Int64C i) = int64Dec i\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n \n \nprocess [] = []\nprocess [a] = [a]\nprocess (a:b:c) | gcd a b >1 = a:1:(process (b:c))\n\t\t| otherwise = a:(process (b:c))\n \n \nmain=do \n\tgetLine\n\tn<- map read <$> words <$>getLine ::IO [Int]\n\tlet x=\tprocess n\n\tprint $ length x - (length n)\n\tputStrLn $ intercalate \" \" $ map show x\n"}, {"source_code": "import Data.List\n\nmake_prime::[Int] -> [Int]\nmake_prime (x:y:xy) = \n if (gcd x y) /= 1\n then x:1:(make_prime (y:xy))\n else x:(make_prime (y:xy))\n\nmake_prime [] = []\nmake_prime (x:[]) = [x]\n\n\nmain = do\n n <- readInt\n numbers <- (map (\\x -> (read x)::Int)) <$> (words) <$> (getLine)\n let ans = map show (make_prime numbers)\n print (length ans - n)\n putStrLn (unwords ans)\n\n\n\nreadToken :: IO String\nreadToken = do\n x <- getChar\n if x == ' ' || x == '\\n'\n then return \"\"\n else (x:) <$> readToken\n\n\nreadInt :: IO Int\nreadInt = do\n x <- readToken\n return ((read x)::Int)\n\n"}, {"source_code": "main :: IO ()\nmain = do \n c <- getContents\n let l = (map (read :: String -> Int) . tail . words) c\n let (a,b) = f l\n putStrLn . show $ a\n putStrLn . unwords. map show $ b\n \nf :: [Int] -> (Int, [Int])\nf q@([]) = (0,q)\nf q@(x:[]) = (0,q)\nf (x1:x2:xs) = if gcd x1 x2 == 1 then (a, x1:b) else (a+1, x1:1:b) where (a,b) = f (x2:xs)\n \n "}, {"source_code": "import Data.Functor\n\nmain :: IO()\nmain = do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n let b = solve a\n print $ (length b) - n\n putStrLn $ unwords $ map show b\n\nsolve :: [Int] -> [Int]\nsolve [] = []\nsolve [a] = [a]\nsolve (a:b:s) | gcd a b > 1 = a:1:solve (b:s)\n | otherwise = a:solve (b:s)\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let ans = solve a\n print $ (length ans - n)\n putStrLn . unwords . map show $ ans\n\nsolve :: [Int] -> [Int]\nsolve [x] = [x]\nsolve (x:y:xs)\n |gcd x y == 1 = x:solve (y:xs)\n |otherwise = x:1:solve (y:xs)\n"}], "negative_code": [{"source_code": "main = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let ans = solve a\n print . length $ a\n putStrLn . unwords . map show $ ans\n\nsolve :: [Int] -> [Int]\nsolve [x] = [x]\nsolve (x:y:xs)\n |gcd x y == 1 = x:solve (y:xs)\n |otherwise = x:1:solve (y:xs)\n"}, {"source_code": "main = do\n getLine\n as <- fmap (map read . words) getLine\n\n let\n f [a] = [a]\n f (a:b:as)\n | gcd a b == 1 = a:(f (b:as))\n | otherwise = a:d:(f (b:as))\n where d = head [d | d <- [1..], a `mod` d /= 0, b `mod` d /= 0]\n\n as' = f as\n\n print $ length as' - length as\n putStrLn $ unwords $ map show as'\n"}, {"source_code": "import Data.Char\n\nmain = do\n\tline <- getLine\n\tlet (n:xs) = getInts 1 line\n\tline <- getLine\n\tlet ps = getInts n line\n\tputStrLn $ foldr1 (\\ x st -> st ++ \" \" ++ x) $ map (show) $ ans ps []\n\ngetInts :: Int -> String -> [Int]\n\ngetInts 0 _ = []\ngetInts _ [] = []\ngetInts x str = map stringToInt $ take x $ words str\n\nstringToInt :: String -> Int\n\nstringToInt str = read str :: Int\n\nans :: (Integral a) => [a] -> [a] -> [a]\n\nans [] ret = ret\nans (f:fs) [] = ans fs [f]\nans (f:fs) ret@(s:retms)\n\t| gcd f s == 1 = ans fs (f:ret)\n\t| otherwise = ans fs (f:1:ret)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\nimport qualified Data.Map as M\n\n \n\n \nmain=do \n\tgetLine\n\tn<- map read.words <$>getLine ::IO [Int]\n\tprint 1\n\tputStrLn $ intercalate \" \"$ map show $ [head n , ((head n)+1)] ++ (tail n)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n \n \nprocess [] = []\nprocess [a] = [a]\nprocess (a:b:c) | gcd a b ==1 = a:1:(process (b:c))\n\t\t| otherwise = process (b:c)\n \n \nmain=do \n\tgetLine\n\tn<- map read <$> words <$>getLine ::IO [Int]\n\tlet x=\tprocess n\n\tprint $ length x\n\tputStrLn $ intercalate \" \" $ map show x\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n \n \nprocess [] = []\nprocess [a] = [a]\nprocess (a:b:c) | gcd a b ==1 = a:1:(process (b:c))\n\t\t| otherwise = a:(process (b:c))\n \n \nmain=do \n\tgetLine\n\tn<- map read <$> words <$>getLine ::IO [Int]\n\tlet x=\tprocess n\n\tprint $ length x - (length n)\n\tputStrLn $ intercalate \" \" $ map show x\n"}, {"source_code": "import Data.List\n\nmake_prime::[Int] -> [Int]\nmake_prime (x:y:xy) = \n if (gcd x y) /= 1\n then x:1:(make_prime (y:xy))\n else x:(make_prime (y:xy))\n\nmake_prime [] = []\nmake_prime (x:[]) = [x]\n\n\nmain = do\n n <- readInt\n numbers <- (map (\\x -> (read x)::Int)) <$> (words) <$> (getLine)\n let ans = map show (make_prime numbers)\n print (length ans - n)\n print (unwords ans)\n\n\n\nreadToken :: IO String\nreadToken = do\n x <- getChar\n if x == ' ' || x == '\\n'\n then return \"\"\n else (x:) <$> readToken\n\n\nreadInt :: IO Int\nreadInt = do\n x <- readToken\n return ((read x)::Int)\n\n"}], "src_uid": "b0b4cadc46f9fd056bf7dc36d1cf51f2"} {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n \n\nmain= do\n\tgetLine\n \ts<-map read . words <$> getContents ::IO [Int]\n\tlet ls =length s\n\tlet k = head $ reverse $ sort $ map length $ group $ sort s\n\tputStrLn $ if odd ls then (if (2*k-2<=ls) then \"YES\" else \"NO\") else (if (2*k-1<=ls) then \"YES\" else \"NO\")\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM, unless, when)\nimport Data.List (group, sort)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Bool\nsolve xs = (<= m) $ maximum $ map length $ group $ sort xs\n where\n n = length xs\n m = n `div` 2 + n `mod` 2\n\nmain :: IO ()\nmain = do\n getLine\n xs <- reads\n when (solve xs) $\n putStrLn \"YES\"\n unless (solve xs) $\n putStrLn \"NO\""}, {"source_code": "import Data.List\n\nmain = do\n _ <- getLine\n ns <- (return.map read.words =<< getLine :: IO [Int])\n putStrLn.judge $ answer ns where\n judge True = \"YES\"\n judge False = \"NO\"\n\nanswer :: [Int] -> Bool\nanswer ns = maxN <= (length ns - maxN+1) where\n maxN = maxLength ns\n\nmaxLength = foldl max 0.map length.group.qsort\n\nqsort :: [Int] -> [Int]\nqsort [] = []\nqsort (x:xs) = qsort small ++ [x] ++ qsort big where\n small = [z| z <- xs, z <= x ]\n big = [z | z <- xs , z > x]"}, {"source_code": "import Data.List\n\nmain =\n interact $ f . solve . map (map read . words) . lines\n where f True = \"YES\"\n f False = \"NO\"\n\nsolve :: [[Int]] -> Bool\nsolve (_:nums:_) =\n let maxLen = maximum $ map length $ group $ sort nums\n n = length nums\n in case n `mod` 2 of\n 0 -> maxLen <= n `quot` 2\n 1 -> maxLen <= (n `quot` 2) + 1\n"}, {"source_code": "import Data.List\nmain=interact$f.map read.words\nf[_,_]=\"YES\"\nf[_,x,y]|x==y=\"NO\"|0<1=\"YES\"\nf(n:x)|l<-maximum.map length.group$sort x,l<=div(n+1)2=\"YES\"|0<1=\"NO\""}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n let m = if even n then n `div` 2 else n `div` 2 + 1\n b <- (words >>> sort >>> group >>> map ((<=m).length) >>> and ) <$> getLine\n let s = (if b then \"YES\" else \"NO\")\n putStrLn s\n"}, {"source_code": "import Data.List\n\nmain = do \n x <- getLine\n x <- getLine\n putStrLn $ f $ sort $ words $ x \n \nf :: [String] -> String\nf ws = if (val <= (div len 2) + (mod len 2)) then \"YES\" else \"NO\"\n where\n len = length ws\n val = maximum $ map length $ group ws"}, {"source_code": "import Data.Ord (comparing)\nimport Data.List\nimport Data.Tuple (fst)\n\nmain = do \n x <- getLine\n x <- getLine\n putStrLn $ f x \n \nf :: String -> String\nf x = if (val <= (div len 2) + (mod len 2))\n then \"YES\"\n else \"NO\"\n where\n ws = sort $ words $ x\n len = length ws\n val = fst $ maximumBy (comparing fst) $ map (\\x -> (length x, head x)) $ group ws\n "}, {"source_code": "main = interact $ go . (map read) . concat . (map words) . lines\ngo (n:s) | maximum cnt > (div n 2)+(mod n 2) = \"NO\"\n | otherwise = \"YES\"\n where cnt = map (\\x -> length $ filter (==x) s) [1..1000]\n"}, {"source_code": "main = interact $ go . (map read) . concat . (map words) . lines\ngo (n:s) | maximum cnt > div (n+1) 2 = \"NO\"\n | otherwise = \"YES\"\n where cnt = map (\\x -> length $ filter (==x) s) [1..1000]\n"}], "negative_code": [{"source_code": "main = interact $ go . (map read) . words . concat . lines\ngo (n:s) | maximum cnt > (div n 2)+(mod n 2) = \"NO\"\n | otherwise = \"YES\"\n where cnt = map (\\x -> length $ filter (==x) s) [1..1000]\n"}, {"source_code": "\nimport Control.Monad (liftM, unless, when)\nimport Data.List (group)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Bool\nsolve xs = (<= m) $ maximum $ map length $ group xs\n where\n n = length xs\n m = n `div` 2 + n `mod` 2\n\nmain :: IO ()\nmain = do\n getLine\n xs <- reads\n when (solve xs) $\n putStrLn \"YES\"\n unless (solve xs) $\n putStrLn \"NO\""}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n \n\nmain= do\n\tgetLine\n \ts<-map read . words <$> getContents ::IO [Int]\n\tlet ls =length s\n\tlet k = head $ reverse $ sort $ map length $ group $ sort s\n\tputStrLn $ if (2*k-2<=ls) then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n \n\nmain= do\n\tgetLine\n \ts<-map read . words <$> getContents ::IO [Int]\n\tlet ls =length s\n\tlet k = head $ sort $ map length $ group $ sort s\n\tputStrLn $ if (2*k-2<=ls) then \"YES\" else \"NO\"\n"}], "src_uid": "2c58d94f37a9dd5fb09fd69fc7788f0d"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmyDiv :: Int -> Int -> Int\nmyDiv x y = (x + y - 1) `quot` y\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [a, b, _] <- getInts\n as <- getInts\n bs <- getInts\n let result = foldl' acc (Just (a, b)) $ sort $ zip as bs\n acc Nothing _ = Nothing\n acc (Just (a1, b1)) (a2, b2)\n | b1 <= 0 = Nothing\n | otherwise = if k1 < k2 then Nothing else Just (a1, b1 - k2 * a2)\n where\n k1 = myDiv b1 a2\n k2 = myDiv b2 a1\n C.putStrLn $ C.pack $ if isJust result then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "chunksOf3 [] = []\r\nchunksOf3 (a : b : c : t) = [a,b,c] : chunksOf3 t\r\n\r\nshowBool True = \"YES\"\r\nshowBool False = \"NO\"\r\n\r\nuncurry5 f (a,b,c,d,e) = f a b c d e\r\n\r\ngetInput [abn, as, bs] = (a, b, n, map toInteger (words as), map toInteger (words bs))\r\n where toInteger = read\r\n [a,b,n] = map toInteger (words abn)\r\n\r\nteto n d = 1 + (n - 1) `div` d\r\n\r\nprocess a b n as bs = damage - maximum as < b\r\n where f (a', b') = teto b' a * a'\r\n info = zip as bs\r\n damage = foldr (\\p t -> f p + t) 0 info\r\n\r\nmain = interact (unlines . map (showBool . uncurry5 process . getInput) . chunksOf3 . tail . lines)\r\n"}, {"source_code": "chunksOf3 [] = []\r\nchunksOf3 (a : b : c : t) = [a,b,c] : chunksOf3 t\r\n\r\nshowBool True = \"YES\"\r\nshowBool False = \"NO\"\r\n\r\nuncurry5 f (a,b,c,d,e) = f a b c d e\r\n\r\ngetInput [abn, as, bs] = (a, b, n, map toInteger (words as), map toInteger (words bs))\r\n where toInteger = read :: String -> Integer\r\n [a,b,n] = map toInteger (words abn)\r\n\r\nteto n d = 1 + (n - 1) `div` d\r\n\r\nprocess a b n as bs = damage - maximum as < b\r\n where f (a', b') = teto b' a * a'\r\n info = zip as bs\r\n damage = foldr (\\p t -> f p + t) 0 info\r\n\r\nmain = interact (unlines . map (showBool . uncurry5 process . getInput) . chunksOf3 . tail . lines)\r\n"}, {"source_code": "chunksOf3 :: [a] -> [[a]]\r\nchunksOf3 [] = []\r\nchunksOf3 (a : b : c : t) = [a,b,c] : chunksOf3 t\r\n\r\nshowBool :: Bool -> String\r\nshowBool True = \"YES\"\r\nshowBool False = \"NO\"\r\n\r\nuncurry5 :: (a -> b -> c -> d -> e -> f) -> (a,b,c,d,e) -> f\r\nuncurry5 f (a,b,c,d,e) = f a b c d e\r\n\r\ngetInput :: [String] -> (Integer, Integer, Integer, [Integer], [Integer])\r\ngetInput [abn, as, bs] = (a, b, n, map toInteger (words as), map toInteger (words bs))\r\n where toInteger = read :: String -> Integer\r\n [a,b,n] = map toInteger (words abn)\r\n\r\nteto :: Integer -> Integer -> Integer\r\nteto n d = 1 + (n - 1) `div` d\r\n\r\nprocess :: Integer -> Integer -> Integer -> [Integer] -> [Integer] -> Bool\r\nprocess a b n as bs = damage - maximum as < b\r\n where f (a', b') = teto b' a * a'\r\n info = zip as bs\r\n damage = foldr (\\p t -> f p + t) 0 info\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBool . uncurry5 process . getInput) . chunksOf3 . tail . lines)\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\ncost :: Integer -> (Integer, Integer) -> Integer\ncost ax (a, b) = let\n rounds = ceilDiv b ax\n in rounds * a\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [ax, bx, _n] <- readInts\n a <- readInts\n b <- readInts\n let\n vs = sortOn fst $ zip a b\n totCost = sum $ map (cost ax) vs\n isOK = totCost - fst (last vs) < bx\n lift $ P.putStrLn $ if isOK\n then P.pack \"YES\"\n else P.pack \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: Num t => SIO [t]\nreadInts = do\n currLine <- readLine\n pure [fromInteger x | Just (x, _) <- P.readInteger <$> P.words currLine]\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Traversable\n\n------\n\nmapFst :: (a -> c) -> (a, b) -> (c, b)\nmapFst f (x, y) = (f x, y)\n\nmapSnd :: (b -> c) -> (a, b) -> (a, c)\nmapSnd f (x, y) = (x, f y)\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\npop :: MonadState [r] m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadState [r] m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadState [B.ByteString] m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadState [B.ByteString] m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadState [B.ByteString] m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadState [B.ByteString] m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\ndropBackWhile :: (Char -> Bool) -> B.ByteString -> B.ByteString\ndropBackWhile p = B.reverse . B.dropWhile p . B.reverse\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map (dropBackWhile isSpace) . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n n <- popInt\n B.unlines <$> replicateM n run1\n\n\nrun1 :: Hopper B.ByteString B.ByteString\nrun1 = do\n ~[attack, health, n] <- popIntegers\n a <- popIntegers\n b <- popIntegers\n return $ fmt $ solve attack health (zip a b)\n\n where\n fmt True = \"YES\"\n fmt False = \"NO\"\n\n\nsolve :: Integer -> Integer -> [(Integer, Integer)] -> Bool\nsolve attack health ms =\n let damagef (mattack, mhealth) =\n mattack * ((mhealth + attack - 1) `div` attack)\n totalDamage = sum $ map damagef ms\n lastDamage = maximum $ map fst ms in\n health - totalDamage + lastDamage > 0\n"}], "negative_code": [{"source_code": "chunksOf3 :: [a] -> [[a]]\r\nchunksOf3 [] = []\r\nchunksOf3 (a : b : c : t) = [a,b,c] : chunksOf3 t\r\n\r\nshowBool :: Bool -> String\r\nshowBool True = \"YES\"\r\nshowBool False = \"NO\"\r\n\r\nuncurry5 :: (a -> b -> c -> d -> e -> f) -> (a,b,c,d,e) -> f\r\nuncurry5 f (a,b,c,d,e) = f a b c d e\r\n\r\ngetInput :: [String] -> (Int, Int, Int, [Int], [Int])\r\ngetInput [abn, as, bs] = (a, b, n, map toInt (words as), map toInt (words bs))\r\n where toInt = read :: String -> Int\r\n [a,b,n] = map toInt (words abn)\r\n\r\nteto :: Int -> Int -> Int\r\nteto n d = 1 + (n - 1) `div` d\r\n\r\nprocess :: Int -> Int -> Int -> [Int] -> [Int] -> Bool\r\nprocess a b n as bs = damage - maximum as < b\r\n where f (a', b') = teto b' a * a'\r\n info = zip as bs\r\n damage = foldr (\\p t -> f p + t) 0 info\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBool . uncurry5 process . getInput) . chunksOf3 . tail . lines)\r\n"}, {"source_code": "import Data.List\r\n\r\nbuild :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]\r\nbuild g = g (:) []\r\n\r\nchunksOf :: Int -> [e] -> [[e]]\r\nchunksOf i ls = map (take i) (build (splitter ls)) where\r\n splitter :: [e] -> ([e] -> a -> a) -> a -> a\r\n splitter [] _ n = n\r\n splitter l c n = l `c` splitter (drop i l) c n\r\n\r\n\r\nshowBool :: Bool -> String\r\nshowBool True = \"YES\"\r\nshowBool False = \"NO\"\r\n\r\nuncurry5 :: (a -> b -> c -> d -> e -> f) -> (a,b,c,d,e) -> f\r\nuncurry5 f (a,b,c,d,e) = f a b c d e\r\n\r\ngetInput :: [String] -> (Int, Int, Int, [Int], [Int])\r\ngetInput [abn, as, bs] = (a, b, n, map toInt (words as), map toInt (words bs))\r\n where toInt = read :: String -> Int\r\n [a,b,n] = map toInt (words abn)\r\n\r\nteto :: Int -> Int -> Int\r\nteto n d = 1 + (n - 1) `div` d\r\n\r\nprocess :: Int -> Int -> Int -> [Int] -> [Int] -> Bool\r\nprocess a b n as bs = damage - maximum as <= b\r\n where f (a', b') = teto b' a * a'\r\n info = zip as bs\r\n damage = foldr (\\p t -> f p + t) 0 info\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showBool . uncurry5 process . getInput) . chunksOf 3 . tail . lines)\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmyDiv :: Int -> Int -> Int\nmyDiv x y = (x + y - 1) `quot` y\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [b, a, _] <- getInts\n bs <- getInts\n as <- getInts\n let result = foldl' acc (Just (a, b)) $ sort $ zip as bs\n acc Nothing _ = Nothing\n acc (Just (a1, b1)) (a2, b2)\n | a1 <= 0 = Nothing\n | otherwise = if k1 < k2 then Nothing else Just (a1 - k2 * b2, b1)\n where\n k1 = myDiv a1 b2\n k2 = myDiv a2 b1\n C.putStrLn $ C.pack $ if isJust result then \"YES\" else \"NO\"\n"}], "src_uid": "b63a6369023642a8e7e8f449d7d4b73f"} {"source_code": "\nimport Control.Monad\nimport Data.Array.IO\nimport qualified Data.Array.MArray as M\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray ((!),bounds,listArray)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Text.Printf\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshowArray label arr = do\n putStrLn $ label ++ \":\"\n let ((ilo,jlo),(ihi,jhi)) = bounds arr\n forM_ [ilo..ihi] $ \\i -> do\n putStr \" \"\n forM_ [jlo..jhi] $ \\j -> do\n putStr $ printf \"%6d \" (arr ! (i,j))\n putStrLn \"\"\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n arr <- newArray ((0,0),(n+1,m+1)) 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [1..n] $ \\i -> do\n xs <- fmap (parseInts m) BS.getLine\n forM_ (zip [1..] xs) $ \\(j,x) -> writeArray arr (i,j) x\n a <- M.freeze arr :: IO (UArray (Int,Int) Int)\n\n let bnds = ((1,1),(n,m))\n bnds' = ((0,0),(n+1,m+1))\n\n let g11 r (i,j) = a!(i,j) + max (r (i-1,j)) (r (i,j-1)) \n gn1 r (i,j) = a!(i,j) + max (r (i+1,j)) (r (i,j-1))\n g1m r (i,j) = a!(i,j) + max (r (i-1,j)) (r (i,j+1))\n gnm r (i,j) = a!(i,j) + max (r (i+1,j)) (r (i,j+1))\n\n tabulate f = let z = listArray bnds [ f r ij | ij <- range bnds ] :: Array (Int,Int) Int\n r ij = if inRange bnds ij then z!ij else 0\n in z :: Array (Int,Int) Int\n\n g11' r (i,j) = do x <- r (i-1,j); y <- r (i,j-1); return $ a!(i,j) + max x y\n gn1' r (i,j) = do x <- r (i+1,j); y <- r (i,j-1); return $ a!(i,j) + max x y\n g1m' r (i,j) = do x <- r (i-1,j); y <- r (i,j+1); return $ a!(i,j) + max x y\n gnm' r (i,j) = do x <- r (i+1,j); y <- r (i,j+1); return $ a!(i,j) + max x y\n\n tabulate' f ijs = do\n arr <- newArray bnds' 0 :: IO (IOUArray (Int,Int) Int)\n forM_ ijs $ \\ij -> f (readArray arr) ij >>= writeArray arr ij\n M.freeze arr :: IO (UArray (Int,Int) Int)\n\n{-\n a11 <- tabulate' g11' [ (i,j) | i <- [1..n], j <- [1..m] ]\n an1 <- tabulate' gn1' [ (i,j) | i <- [n,n-1..1], j <- [1..m] ]\n a1m <- tabulate' g1m' [ (i,j) | i <- [1..n], j <- [m,m-1..1] ]\n anm <- tabulate' gnm' [ (i,j) | i <- [n,n-1..1], j <- [m,m-1..1] ]\n-}\n a11' <- newArray bnds' 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [1..n] $ \\i -> forM_ [1..m] $ \\j -> do\n x <- readArray a11' (i-1,j)\n y <- readArray a11' (i,j-1)\n writeArray a11' (i,j) $ a!(i,j) + max x y\n a11 <- M.freeze a11' :: IO (UArray (Int,Int) Int)\n\n an1' <- newArray bnds' 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [n,n-1..1] $ \\i -> forM_ [1..m] $ \\j -> do\n x <- readArray an1' (i+1,j)\n y <- readArray an1' (i,j-1)\n writeArray an1' (i,j) $ a!(i,j) + max x y\n an1 <- M.freeze an1' :: IO (UArray (Int,Int) Int)\n\n a1m' <- newArray bnds' 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [1..n] $ \\i -> forM_ [m,m-1..1] $ \\j -> do\n x <- readArray a1m' (i-1,j)\n y <- readArray a1m' (i,j+1)\n writeArray a1m' (i,j) $ a!(i,j) + max x y\n a1m <- M.freeze a1m' :: IO (UArray (Int,Int) Int)\n\n anm' <- newArray bnds' 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [n,n-1..1] $ \\i -> forM_ [m,m-1..1] $ \\j -> do\n x <- readArray anm' (i+1,j)\n y <- readArray anm' (i,j+1)\n writeArray anm' (i,j) $ a!(i,j) + max x y\n anm <- M.freeze anm' :: IO (UArray (Int,Int) Int)\n\n let g (i,j) = max top side\n where top = a11!(i-1,j) + anm!(i+1,j) + an1!(i,j-1) + a1m!(i,j+1)\n side = a11!(i,j-1) + anm!(i,j+1) + an1!(i+1,j) + a1m!(i-1,j)\n -- b = listArray ((2,2),(n-1,m-1)) [ g (i,j) | i <- [2..n-1], j <- [2..m-1] ] :: Array (Int,Int) Int\n best = maximum [ g (i,j) | i <- [2..n-1], j <- [2..m-1] ]\n print best\n\n{-\n showArray \"a11\" a11\n showArray \"an1\" an1\n showArray \"a1m\" a1m\n showArray \"anm\" anm\n-}\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array.IO\nimport qualified Data.Array.MArray as M\nimport Data.Array\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Text.Printf\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshowArray label arr = do\n putStrLn $ label ++ \":\"\n let ((ilo,jlo),(ihi,jhi)) = bounds arr\n forM_ [ilo..ihi] $ \\i -> do\n putStr \" \"\n forM_ [jlo..jhi] $ \\j -> do\n putStr $ printf \"%6d \" (arr ! (i,j))\n putStrLn \"\"\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n arr <- newArray ((0,0),(n+1,m+1)) 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [1..n] $ \\i -> do\n xs <- fmap (parseInts m) BS.getLine\n forM_ (zip [1..] xs) $ \\(j,x) -> writeArray arr (i,j) x\n a <- M.freeze arr :: IO (Array (Int,Int) Int)\n\n let bnds = ((1,1),(n,m))\n\n let g11 r (i,j) = a!(i,j) + max (r (i-1,j)) (r (i,j-1)) \n gn1 r (i,j) = a!(i,j) + max (r (i+1,j)) (r (i,j-1))\n g1m r (i,j) = a!(i,j) + max (r (i-1,j)) (r (i,j+1))\n gnm r (i,j) = a!(i,j) + max (r (i+1,j)) (r (i,j+1))\n\n tabulate f = let z = listArray bnds [ f r ij | ij <- range bnds ] :: Array (Int,Int) Int\n r ij = if inRange bnds ij then z!ij else 0\n in z :: Array (Int,Int) Int\n\n a11 = tabulate g11\n a1m = tabulate g1m\n an1 = tabulate gn1\n anm = tabulate gnm\n\n g (i,j) = max top side\n where top = a11!(i-1,j) + anm!(i+1,j) + an1!(i,j-1) + a1m!(i,j+1)\n side = a11!(i,j-1) + anm!(i,j+1) + an1!(i+1,j) + a1m!(i-1,j)\n b = listArray ((2,2),(n-1,m-1)) [ g (i,j) | i <- [2..n-1], j <- [2..m-1] ] :: Array (Int,Int) Int\n best = maximum [ g (i,j) | i <- [2..n-1], j <- [2..m-1] ]\n{-\n showArray \"a11\" a11\n showArray \"anm\" anm\n showArray \"a1m\" a1m\n showArray \"an1\" an1\n showArray \"a\" a\n showArray \"best\" b\n-}\n print best\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\n\nmain = do\n (n,m) <- readIntPair\n as <- replicateM n readInts\n print $ solve n m as\n\nsolve :: Int -> Int -> [[Int]] -> Int64\nsolve n m as = maximum $ do\n i <- [2..n-1]\n j <- [2..m-1]\n let c1 = cost11 ! (i,j-1) \n + cost12 ! (i,j+1) \n + cost21 ! (i+1,j) \n + cost22 ! (i-1,j)\n let c2 = cost11 ! (i-1,j) \n + cost12 ! (i+1,j) \n + cost21 ! (i,j-1) \n + cost22 ! (i,j+1)\n return $ max c1 c2\n where\n bb = ((1,1),(n,m))\n a :: UArray (Int,Int) Int64\n a = listArray bb $ map fromIntegral $ concat as\n cost11 :: UArray (Int,Int) Int64\n cost11 = f 1 (<=n) succ pred 1 (<=m) succ pred\n cost12 = f n (>=1) pred succ m (>=1) pred succ\n cost21 = f n (>=1) pred succ 1 (<=m) succ pred\n cost22 = f 1 (<=n) succ pred m (>=1) pred succ \n f i0 ip si pi j0 jp sj pj = runSTUArray $ do\n cost <- newArray bb 0\n stepM_ i0 ip si $ \\i -> stepM_ j0 jp sj $ \\j -> do\n v <- if i == i0 && j == j0 then return 0\n else if i == i0 then\n readArray cost (i,pj j)\n else if j == j0 then\n readArray cost (pi i,j)\n else\n max <$> readArray cost (i,pj j)\n <*> readArray cost (pi i,j)\n writeArray cost (i,j) (v+a!(i,j))\n return cost\n"}, {"source_code": "import Data.Array.IO\nimport Data.Ix\nimport Control.Monad\nimport Data.IORef\nimport Data.Tuple\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Lazy as B\n\nparse :: B.ByteString -> [Int]\nparse s = do\n q <- B.splitWith (\\x-> x == 13 || x == 10 || x == 32) s\n if B.length q == 0 then\n []\n else\n return $ foldl' (\\a b-> a * 10 + (fromIntegral b) - (ord '0')) 0 (B.unpack q)\n\nreadNum :: IORef [a] -> IO a\nreadNum nums = do\n x:xs <- readIORef nums\n writeIORef nums xs\n return x\n\ndyn :: IOUArray (Int, Int) Int -> Int -> Int -> IO (IOUArray (Int, Int) Int)\ndyn g di dj = do\n bounds <- getBounds g\n let ((i1, j1), (i2, j2)) = bounds\n let newBounds = ((i1 + min di 0, j1 + min dj 0), (i2 + max di 0, j2 + max dj 0))\n q <- newArray newBounds 0\n let startI = if di > 0 then i2 else i1\n let endI = if di > 0 then i1 else i2\n let startJ = if dj > 0 then j2 else j1\n let endJ = if dj > 0 then j1 else j2\n forM_ [startI, (startI - di)..endI] $ \\i -> do\n forM_ [startJ, (startJ - dj)..endJ] $ \\j -> do\n a <- readArray g (i, j)\n ai <- readArray q ((i + di), j)\n aj <- readArray q (i, (j + dj))\n writeArray q (i, j) (a + max ai aj)\n return q\n\nmain :: IO ()\nmain = do\n nums0 <- B.getContents\n nums <- newIORef $ parse nums0\n n <- readNum nums\n m <- readNum nums\n g <- newArray ((1, 1), (n, m)) 0\n forM_ (range ((1, 1), (n, m))) $ \\p -> do\n a <- readNum nums\n writeArray g p a\n dpp <- dyn g 1 1\n dpn <- dyn g 1 (-1)\n dnp <- dyn g (-1) 1\n dnn <- dyn g (-1) (-1)\n maxRes <- newIORef 0\n forM_ (range ((2, 2), (n - 1, m - 1))) $ \\(i, j) -> do\n a1Up <- readArray dnn (i - 1, j)\n a1Left <- readArray dnn (i, j - 1)\n a2Right <- readArray dpp (i, j + 1)\n a2Down <- readArray dpp (i + 1, j)\n b1Left <- readArray dpn (i, j - 1)\n b1Down <- readArray dpn (i + 1, j)\n b2Right <- readArray dnp (i, j + 1)\n b2Up <- readArray dnp (i - 1, j)\n let r = max (a1Up + b1Left + a2Down + b2Right) (a1Left + b1Down + a2Right + b2Up)\n curMaxRes <- readIORef maxRes\n writeIORef maxRes $! (max curMaxRes r)\n r <- readIORef maxRes\n putStrLn $ show r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array.IO\nimport qualified Data.Array.MArray as M\nimport Data.Array\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nmain = do\n (n:m:_) <- fmap (map read . words) getLine\n arr <- newArray ((0,0),(n+1,m+1)) 0 :: IO (IOUArray (Int,Int) Int)\n forM_ [1..n] $ \\i -> do\n xs <- fmap (parseInts m) BS.getLine\n forM_ (zip [1..] xs) $ \\(j,x) -> writeArray arr (i,j) x\n a <- M.freeze arr :: IO (Array (Int,Int) Int)\n\n let bnds = ((1,1),(n,m))\n\n let g11 r (i,j) = a!(i,j) + max (r (i-1,j)) (r (i,j-1)) \n gn1 r (i,j) = a!(i,j) + max (r (i+1,j)) (r (i,j-1))\n g1m r (i,j) = a!(i,j) + max (r (i-1,j)) (r (i,j+1))\n gnm r (i,j) = a!(i,j) + max (r (i+1,j)) (r (i,j+1))\n\n tabulate f = let z = listArray bnds [ f r ij | ij <- range bnds ] :: Array (Int,Int) Int\n r ij = if inRange bnds ij then z!ij else 0\n in z :: Array (Int,Int) Int\n\n a11 = tabulate g11\n a1m = tabulate g1m\n an1 = tabulate gn1\n anm = tabulate gnm\n\n g ij = (a11!ij) + (a1m!ij) + (an1!ij) + (anm!ij) - 4*(a!ij)\n best = maximum [ g ij | ij <- range bnds ]\n print best\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\n\nmain = do\n (n,m) <- readIntPair\n as <- replicateM n readInts\n print $ solve n m as\n\nsolve :: Int -> Int -> [[Int]] -> Int64\nsolve n m as = maximum $ do\n i <- [1..n]\n j <- [1..m]\n return $ cost11 ! (i,j) + cost12 ! (i,j) + cost21 ! (i,j) + cost22 ! (i,j)\n where\n bb = ((1,1),(n,m))\n a :: UArray (Int,Int) Int64\n a = listArray bb $ map fromIntegral $ concat as\n cost11 :: UArray (Int,Int) Int64\n cost11 = f 1 (<=n) succ pred 1 (<=m) succ pred\n cost12 = f n (>=1) pred succ m (>=1) pred succ\n cost21 = f n (>=1) pred succ 1 (<=m) succ pred\n cost22 = f 1 (<=n) succ pred m (>=1) pred succ \n f i0 ip si pi j0 jp sj pj = runSTUArray $ do\n cost <- newArray bb 0\n stepM_ i0 ip si $ \\i -> stepM_ j0 jp sj $ \\j -> do\n v <- if i == i0 && j == j0 then return 0\n else if i == i0 then\n ((a ! (i,pj j))+) <$> readArray cost (i,pj j)\n else if j == j0 then\n ((a ! (pi i,j))+) <$> readArray cost (pi i,j)\n else\n max <$> (((a ! (i,pj j))+) <$> readArray cost (i,pj j))\n <*> (((a ! (pi i,j))+) <$> readArray cost (pi i,j))\n writeArray cost (i,j) v\n return cost\n"}], "src_uid": "ed5d0eca057f2a2e371b1fc7e3b618bb"} {"source_code": "module Main where\n import Data.Array\n\n solve :: Integer -> Bool\n solve x = (d >= 1) && (1 <= t) && (t <= 6) where\n t = x `mod` 14\n d = x `div` 14\n \n main = do\n n <- getLine\n l <- getLine\n let a = map(\\x -> read x :: Integer) $ words l\n res = map(\\x -> if solve x == True then \"YES\" else \"NO\") a\n mapM_ putStrLn res", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nmain=interact$unlines.map(p.read).tail.words\np x|x<14=\"NO\"|mod(x-1)14<6=\"YES\"|1>0=\"NO\""}], "negative_code": [{"source_code": "main=interact$unlines.map p.tail.words\np x|mod(read x-1)14<6=\"YES\"|1>0=\"NO\""}], "src_uid": "840a4e16454290471faa5a27a3c795d9"} {"source_code": "import Data.List ( sort, nub )\nimport Data.Bool ( bool )\n\nmain :: IO ()\nmain = interact $ unlines . fmap (toYesNo . isDiverse) . tail . words\n where\n toYesNo = bool \"No\" \"Yes\"\n\nisDiverse :: String -> Bool\nisDiverse s = isAdj s && isDistinct s\n\nisAdj :: String -> Bool\nisAdj = and . (zipWith (\\a b -> succ a == b) <*> tail) . sort\n\nisDistinct :: String -> Bool\nisDistinct s = nub s == s\n", "positive_code": [{"source_code": "-- Codeforces Round #550 (Div. 3) - Problem A: Diverse Strings (https://codeforces.com/problemset/problem/1144/A) \nimport Data.List\nimport Data.Char\n\nisDiverse s | s == nub s && (ord . head) s + n - 1 == (ord . last) s = \"Yes\"\n | otherwise = \"No\"\n where\n n = length s\n \nsolve = map (isDiverse . sort)\n\nmain = do\n input <- getContents\n let xs = tail . lines $ input\n putStr . unlines $ solve xs\n"}, {"source_code": "import Data.List (sort)\n\nisVarious str = all (\\(a, b) -> succ a == b) $ zip (init sorted_str) (tail sorted_str) where\n sorted_str = sort str\n\ntest = if isVarious \"asd\" then \"Yes\" else \"No\"\n\niterSolve 0 = return ()\niterSolve n = do\n str <- getLine\n putStrLn $ if isVarious str then \"Yes\" else \"No\"\n iterSolve (n - 1)\n\nmain = do\n line <- getLine\n iterSolve $ read line"}, {"source_code": "import Data.List\nworks (y:[]) = True\nworks (x:y:xs) = case (succ x) == y of\n True -> works (y:xs)\n False -> False\n\nprocess [] = putStr \"\"\nprocess (x:xs) = case works (sort x) of\n True -> putStrLn \"Yes\" >> process xs\n False -> putStrLn \"No\" >> process xs\nmain = getContents >>= process . tail . words\n"}, {"source_code": "import Data.List\n\nmain = getLine >> (interact $ unlines . map solve . lines)\n\nsolve xs\n | build ss == ss = \"Yes\"\n | otherwise = \"No\"\n where build all@(x:_) = take (length all) $ iterate succ x\n ss = sort xs\n"}, {"source_code": "import Data.List\nimport System.IO\n\nreadInteger :: IO Int\nreadInteger = do\n z <- readLn\n return z\n\nreadString = do\n z <- getLine\n return z\n\nreadStrings 0 = return []\nreadStrings n = do\n line <- readString\n rest <- readStrings (n - 1)\n return (line : rest)\n\ntakeInput = do\n z <- readInteger\n readStrings z\n\nok (ch: []) = True\nok (ch : rest) = (ok rest) && ((fromEnum ch) + 1 == fromEnum (head rest))\n\nanswer True = \"Yes\"\nanswer False = \"No\"\n\nprocess = map (answer . ok . sort)\n\ndisplay [] = return ()\ndisplay (x:xs) = do\n putStrLn x\n display xs\n\nmain = do\n input <- takeInput\n display (process input)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\ndiverse :: String -> String\ndiverse s\n | m == l && m == (d + 1) = \"Yes\"\n | otherwise = \"No\"\n where l = length s \n t = sort s \n m = length $ group t\n d = ord (last t) - ord (head t)\n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- replicateM n $ getLine\n mapM_ putStrLn $ map diverse xs "}, {"source_code": "import Data.List\nmain = interact $ unlines . map solve . tail . lines\nsolve s | fromEnum (maximum s) - fromEnum (minimum s) == length s - 1\n && nub s == s = \"Yes\"\n | otherwise = \"No\"\n"}, {"source_code": "import Data.List\nconsecCheck s = (== 1) . length . filter id . map head . group $ map (`elem` s) ['a'..'z']\nallDiff [] = True\nallDiff (x:xs) = not (x `elem` xs) && allDiff xs\nsolve s = allDiff s && consecCheck s\np b = if b then \"Yes\" else \"No\"\nmain = interact $ unlines . map (p . solve) . tail . lines"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Int\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nrstrip = C.takeWhile isPrint\nsYes = byteString $ C.pack \"Yes\\n\"\nsNo = byteString $ C.pack \"No\\n\"\n\ntest s = if res then sYes else sNo\n where\n c = runSTUArray $ do\n x <- newArray (0, 25) 0 :: ST s (STUArray s Int Int32)\n forM (C.unpack s) $ \\i -> do\n let !j = ord i - 97\n readArray x j >>= ((writeArray x j) . succ)\n return x\n lst = filter (\\ l -> head l /= 0) $ group $ elems c\n !res = length lst == 1 && (head $ head lst) == 1\n\nsolve (sn:a) = mconcat $ map test b\n where\n !n = ru sn\n b = take n a\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map rstrip . C.lines =<< C.getContents\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\n\nm1 =M.fromList $ zip ['a'..'z'] [1..]\n\nprocess1 x \t| d+1== length x = \"Yes\"\n\t \t| otherwise = \"No\"\n\twhere mi = minimum x\n ma = maximum x\n\t d =fromJust ( M.lookup ma m1) - fromJust (M.lookup mi m1)\n\n\n\nonecase = do\n\t\tx<-getLine\n\t\tputStrLn $ \tif length (group (sort x)) getLine ::IO Int\n\t\treplicateM_ n onecase\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\n\nm1 =M.fromList $ zip ['a'..'y'] ['b'..'z']\n\nprocess [_] = \"No\"\n\nprocess (a:b) \t| elem (fromJust(M.lookup a m1)) b = \"Yes\"\n\t\t| otherwise = process b\nprocess1 x | length x == 1 = \"Yes\"\n\t | otherwise = process x\n\nonecase = do\n\t\tx<-getLine\n\t\tputStrLn $ \tif length (group (sort x)) getLine ::IO Int\n\t\treplicateM_ n onecase\n\n"}, {"source_code": "-- Codeforces Round #550 (Div. 3) - Problem A: Diverse Strings (https://codeforces.com/problemset/problem/1144/A) \nimport Data.List\nimport Data.Char\n\nisDiverse s | (ord . head) s + n - 1 == (ord . last) s = \"Yes\"\n | otherwise = \"No\"\n where\n n = length s\n \nsolve = map (isDiverse . sort)\n\nmain = do\n input <- getContents\n let xs = tail . lines $ input\n putStr . unlines $ solve xs\n"}], "src_uid": "02a94c136d3fb198025242e91264823b"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE ParallelListComp #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.ST\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Array.Base\r\nimport Data.Array.MArray\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (group, sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n (n, m) <- pair int int\r\n ps <- n >< int\r\n let ks = solve m ps\r\n return . unwords . map show $ length ks : ks\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve m ps =\r\n filter check\r\n . map head -- ks\r\n . filter ((>= n - 2 * m) . length) -- cnt_k >= n - 2m\r\n . group\r\n . sort\r\n $ [(n + i - x) `mod` n | i <- [1 ..] | x <- ps] -- k values for each fixpoint\r\n where\r\n n = length ps\r\n check k = let (hs, ts) = splitAt k ps in numCycles (ts ++ hs) >= n - m\r\n\r\n-- Number of cycles in a 1-indexed permutation\r\nnumCycles :: [Int] -> Int\r\nnumCycles = rangeSize . bounds . cycleLen . permToCycles . fromList\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\n--- https://github.com/byorgey/comprog-hs/blob/master/Perm.hs\r\n\r\n-- | 'Perm' represents a /1-indexed/ permutation. It can also be\r\n-- thought of as an endofunction on the set @{1 .. n}@.\r\ntype Perm = UArray Int Int\r\n\r\n-- | Construct a 'Perm' from a list containing a permutation of the\r\n-- numbers 1..n. The resulting 'Perm' sends @i@ to whatever number\r\n-- is at index @i-1@ in the list.\r\nfromList :: [Int] -> Perm\r\nfromList xs = listArray (1, length xs) xs\r\n\r\n-- | Compose two permutations (corresponds to backwards function\r\n-- composition). Only defined if the permutations have the same\r\n-- size.\r\nandThen :: Perm -> Perm -> Perm\r\nandThen p1 p2 = listArray (bounds p1) (map ((p1 !) >>> (p2 !)) (range (bounds p1)))\r\n\r\n-- | Compute the inverse of a permutation.\r\ninverse :: Perm -> Perm\r\ninverse p = array (bounds p) [(p ! k, k) | k <- range (bounds p)]\r\n\r\ndata CycleDecomp = CD\r\n { -- | Each number maps to the ID #\r\n -- of the cycle it is part of\r\n cycleID :: UArray Int Int,\r\n -- | Each cycle ID maps to the length of that cycle\r\n cycleLen :: UArray Int Int,\r\n -- | Each element maps to its (0-based) index in its cycle\r\n cycleIndex :: UArray Int Int,\r\n -- | Each size maps to the number of cycles of that size\r\n cycleCounts :: UArray Int Int\r\n }\r\n deriving (Show)\r\n\r\n-- | Cycle decomposition of a permutation in O(n), using mutable arrays.\r\npermToCycles :: Perm -> CycleDecomp\r\npermToCycles p = cd\r\n where\r\n (_, n) = bounds p\r\n\r\n cd = runST $ do\r\n cid <- newArray (1, n) 0\r\n cix <- newArray (1, n) 0\r\n ccs <- newArray (1, n) 0\r\n\r\n lens <- findCycles cid cix ccs 1 1\r\n cid' <- freeze cid\r\n cix' <- freeze cix\r\n ccs' <- freeze ccs\r\n return $ CD cid' (listArray (1, length lens) lens) cix' ccs'\r\n\r\n findCycles ::\r\n STUArray s Int Int ->\r\n STUArray s Int Int ->\r\n STUArray s Int Int ->\r\n Int ->\r\n Int ->\r\n ST s [Int]\r\n findCycles cid cix ccs l !k -- l = next available cycle ID; k = cur element\r\n | k > n = return []\r\n | otherwise = do\r\n -- check if k is already marked as part of a cycle\r\n id <- readArray cid k\r\n case id of\r\n 0 -> do\r\n -- k is unvisited. Explore its cycle and label it as l.\r\n len <- labelCycle cid cix l k 0\r\n\r\n -- Remember that we have one more cycle of this size.\r\n count <- readArray ccs len\r\n writeArray ccs len (count + 1)\r\n\r\n -- Continue with the next label and the next element, and\r\n -- remember the size of this cycle\r\n (len :) <$> findCycles cid cix ccs (l + 1) (k + 1)\r\n\r\n -- k is already visited: just go on to the next element\r\n _ -> findCycles cid cix ccs l (k + 1)\r\n\r\n -- Explore a single cycle, label all its elements and return its size.\r\n labelCycle cid cix l k !i = do\r\n -- Keep going as long as the next element is unlabelled.\r\n id <- readArray cid k\r\n case id of\r\n 0 -> do\r\n -- Label the current element with l.\r\n writeArray cid k l\r\n -- The index of the current element is i.\r\n writeArray cix k i\r\n\r\n -- Look up the next element in the permutation and continue.\r\n (1 +) <$> labelCycle cid cix l (p ! k) (i + 1)\r\n _ -> return 0\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Control.Monad.ST.Lazy\n\nseenBefore :: (Int, Int) -> [Int] -> [Bool]\nseenBefore bnds li = runST $ do\n arr <- strictToLazyST $ newArray bnds False :: ST s (STUArray s Int Bool)\n (\\fun -> mapM fun li) $ \\x -> strictToLazyST $ do\n ans <- readArray arr x\n ans <$ writeArray arr x True\n\ngetCycles :: UArray Int Int -> [[Int]]\ngetCycles arr = let\n go qrs x = let\n (ansTail, remQs) = case qrs of\n False : qrst -> go qrst (arr ! x)\n True : qrst -> ([], qrst)\n [] -> error \"unanswered query\"\n in (x : ansTail, remQs)\n queryResponses = seenBefore (bounds arr) queries\n queries = concat untrimmed\n untrimmed = map fst\n $ scanl (\\(_, qrs) x -> go qrs x) ([], queryResponses) (indices arr)\n in [ts | _ : ts <- untrimmed, not $ null ts]\n\ncheck :: UArray Int Int -> Int -> Int\ncheck p k = let\n (1, n) = bounds p\n pk = listArray (1, n) $ [1 + mod (pj + k - 1) n | pj <- elems p]\n in n - length (getCycles pk)\n \nsolve :: UArray Int Int -> Int -> [Int]\nsolve p m = let\n (1, n) = bounds p\n ncorrect :: UArray Int Int\n ncorrect = accumArray (+) 0 (0, n-1)\n $ [(mod (i - pj) n, 1) | (i, pj) <- assocs p]\n isOK k = if ncorrect ! k + 2 * m < n\n then False -- at most 3 values of k can skip this per testcase\n else check p k <= m\n in filter isOK [0 .. n-1]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, m] <- readInts\n p <- listArray (1, n) <$>readInts\n let ans = solve p m\n putInts $ length ans : ans\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE ParallelListComp #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.ST\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Array.Base\r\nimport Data.Array.MArray\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (group, sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n (n, m) <- pair int int\r\n ps <- n >< int\r\n let ks = solve m ps\r\n return . unwords . map show $ length ks : ks\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve m ps =\r\n id\r\n -- filter (\\k -> numCycles ([n - k + 1 .. n] ++ [1 .. n - k]) >= n - m) -- check swaps\r\n . map head -- ks\r\n . filter ((>= n - 2 * m) . length) -- cnt_k >= n - 2m\r\n . group\r\n . sort\r\n $ [(n + i - x) `mod` n | i <- [1 ..] | x <- ps] -- k values for each fixpoint\r\n where\r\n n = length ps\r\n\r\n-- Number of cycles in a 1-indexed permutation\r\nnumCycles :: [Int] -> Int\r\nnumCycles = rangeSize . bounds . cycleLen . permToCycles . fromList\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\n--- https://github.com/byorgey/comprog-hs/blob/master/Perm.hs\r\n\r\n-- | 'Perm' represents a /1-indexed/ permutation. It can also be\r\n-- thought of as an endofunction on the set @{1 .. n}@.\r\ntype Perm = UArray Int Int\r\n\r\n-- | Construct a 'Perm' from a list containing a permutation of the\r\n-- numbers 1..n. The resulting 'Perm' sends @i@ to whatever number\r\n-- is at index @i-1@ in the list.\r\nfromList :: [Int] -> Perm\r\nfromList xs = listArray (1, length xs) xs\r\n\r\n-- | Compose two permutations (corresponds to backwards function\r\n-- composition). Only defined if the permutations have the same\r\n-- size.\r\nandThen :: Perm -> Perm -> Perm\r\nandThen p1 p2 = listArray (bounds p1) (map ((p1 !) >>> (p2 !)) (range (bounds p1)))\r\n\r\n-- | Compute the inverse of a permutation.\r\ninverse :: Perm -> Perm\r\ninverse p = array (bounds p) [(p ! k, k) | k <- range (bounds p)]\r\n\r\ndata CycleDecomp = CD\r\n { -- | Each number maps to the ID #\r\n -- of the cycle it is part of\r\n cycleID :: UArray Int Int,\r\n -- | Each cycle ID maps to the length of that cycle\r\n cycleLen :: UArray Int Int,\r\n -- | Each element maps to its (0-based) index in its cycle\r\n cycleIndex :: UArray Int Int,\r\n -- | Each size maps to the number of cycles of that size\r\n cycleCounts :: UArray Int Int\r\n }\r\n deriving (Show)\r\n\r\n-- | Cycle decomposition of a permutation in O(n), using mutable arrays.\r\npermToCycles :: Perm -> CycleDecomp\r\npermToCycles p = cd\r\n where\r\n (_, n) = bounds p\r\n\r\n cd = runST $ do\r\n cid <- newArray (1, n) 0\r\n cix <- newArray (1, n) 0\r\n ccs <- newArray (1, n) 0\r\n\r\n lens <- findCycles cid cix ccs 1 1\r\n cid' <- freeze cid\r\n cix' <- freeze cix\r\n ccs' <- freeze ccs\r\n return $ CD cid' (listArray (1, length lens) lens) cix' ccs'\r\n\r\n findCycles ::\r\n STUArray s Int Int ->\r\n STUArray s Int Int ->\r\n STUArray s Int Int ->\r\n Int ->\r\n Int ->\r\n ST s [Int]\r\n findCycles cid cix ccs l !k -- l = next available cycle ID; k = cur element\r\n | k > n = return []\r\n | otherwise = do\r\n -- check if k is already marked as part of a cycle\r\n id <- readArray cid k\r\n case id of\r\n 0 -> do\r\n -- k is unvisited. Explore its cycle and label it as l.\r\n len <- labelCycle cid cix l k 0\r\n\r\n -- Remember that we have one more cycle of this size.\r\n count <- readArray ccs len\r\n writeArray ccs len (count + 1)\r\n\r\n -- Continue with the next label and the next element, and\r\n -- remember the size of this cycle\r\n (len :) <$> findCycles cid cix ccs (l + 1) (k + 1)\r\n\r\n -- k is already visited: just go on to the next element\r\n _ -> findCycles cid cix ccs l (k + 1)\r\n\r\n -- Explore a single cycle, label all its elements and return its size.\r\n labelCycle cid cix l k !i = do\r\n -- Keep going as long as the next element is unlabelled.\r\n id <- readArray cid k\r\n case id of\r\n 0 -> do\r\n -- Label the current element with l.\r\n writeArray cid k l\r\n -- The index of the current element is i.\r\n writeArray cix k i\r\n\r\n -- Look up the next element in the permutation and continue.\r\n (1 +) <$> labelCycle cid cix l (p ! k) (i + 1)\r\n _ -> return 0\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Control.Monad.ST.Lazy\n\nseenBefore :: (Int, Int) -> [Int] -> [Bool]\nseenBefore bnds li = runST $ do\n arr <- strictToLazyST $ newArray bnds False :: ST s (STUArray s Int Bool)\n (\\fun -> mapM fun li) $ \\x -> strictToLazyST $ do\n ans <- readArray arr x\n ans <$ writeArray arr x True\n\ngetCycles :: UArray Int Int -> [[Int]]\ngetCycles arr = let\n go qrs x = let\n (ansTail, remQs) = case qrs of\n True : qrst -> go qrst (arr ! x)\n False : qrst -> ([], qrst)\n [] -> error \"unanswered query\"\n in (x : ansTail, remQs)\n queryResponses = seenBefore (bounds arr) queries\n queries = concat untrimmed\n untrimmed = map fst\n $ scanl (\\(_, qrs) x -> go qrs x) ([], queryResponses) (indices arr)\n in [ts | _ : ts <- untrimmed]\n\ncheck :: UArray Int Int -> Int -> Int\ncheck p k = let\n (1, n) = bounds p\n pk = listArray (1, n) $ [1 + mod (pj - k - 1) n | pj <- elems p]\n in n - length (getCycles pk)\n \nsolve :: UArray Int Int -> Int -> [Int]\nsolve p m = let\n (1, n) = bounds p\n ncorrect :: UArray Int Int\n ncorrect = accumArray (+) 0 (0, n-1)\n $ [(mod (i - pj) n, 1) | (i, pj) <- assocs p]\n isOK k = if ncorrect ! k + 2 * m < n\n then False -- at most 3 values of k can skip this per testcase\n else check p k < m\n in filter isOK [0 .. n-1]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, m] <- readInts\n p <- listArray (1, n) <$>readInts\n let ans = solve p m\n putInts $ length ans : ans\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "2c610873aa1a772a4c7f32cb74dd75fa"} {"source_code": "import Data.List\nimport qualified Data.Map as DM\nimport Data.Maybe\n\ngetMap :: String -> DM.Map Char Int\ngetMap = foldl' (\\ acc x -> DM.insertWith (+) x 1 acc) DM.empty \n\nsolve :: String -> String -> (Int, Int)\nsolve s t = \n let m1 = getMap s\n m2 = getMap t\n in foldl' (\\ (a, b) (c1, c2) -> \n let (a1, b1) = getBest m1 m2 c1 c2 in (a + a1, b + b1)) \n (0, 0)\n (zip ['a'..'z'] ['A'..'Z']) \n where \n getBest :: DM.Map Char Int -> DM.Map Char Int -> Char -> Char -> (Int, Int)\n getBest m1 m2 lower upper = \n let cntLower1 = fromMaybe 0 (DM.lookup lower m1)\n cntLower2 = fromMaybe 0 (DM.lookup lower m2)\n cntUpper1 = fromMaybe 0 (DM.lookup upper m1)\n cntUpper2 = fromMaybe 0 (DM.lookup upper m2)\n goodLower = min cntLower1 cntLower2\n goodUpper = min cntUpper1 cntUpper2\n rest1 = cntLower1 + cntUpper1 - goodLower - goodUpper\n rest2 = cntLower2 + cntUpper2 - goodLower - goodUpper\n rest = min rest1 rest2\n in (goodLower + goodUpper, rest)\n \nmain = do\n s <- getLine\n t <- getLine\n let (a, b) = solve s t\n putStrLn $ show a ++ \" \" ++ show b\n \n", "positive_code": [{"source_code": "module Main where\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Ord\nimport Data.List\nimport qualified Data.Map.Lazy as M\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n s <- getLine\n t <- getLine\n mapM_ (putStr . (\" \"++) . show) $ sol s t\n\nsol s t = map (sum . M.elems) [mi, li]\n where\n ms = M.fromListWith (+) $ zip s (repeat 1)\n mt = M.fromListWith (+) $ zip t (repeat 1)\n mi = M.intersectionWith min ms mt\n ds = M.differenceWith (\\a b -> if a>b then Just (a-b) else Nothing) ms mi\n dt = M.differenceWith (\\a b -> if a>b then Just (a-b) else Nothing) mt mi\n ls = M.mapKeysWith (+) toLower ds\n lt = M.mapKeysWith (+) toLower dt\n li = M.intersectionWith min ls lt\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport Debug.Trace\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\nimport Data.Char\nimport qualified Data.Set as Set\n\n\n-- traceDebug = trace\ntraceDebug _ x = x\n\nsuccRevStr [] = \"a\"\nsuccRevStr ('z':tl) = 'a' : succRevStr tl\nsuccRevStr ( c :tl) = succ c : tl\n\n\nsuccStr s =\n reverse . succRevStr . reverse $ s\n\ngroupCount s =\n let s' = group . sort $ s\n in map (\\l -> (head l, length l)) s'\n\nmain = do\n s <- getLine\n t <- getLine\n let sg = groupCount s\n tg = groupCount t\n\n searchLetter bag (c,n) =\n case lookup c bag of\n Nothing -> 0\n Just x' -> min n x'\n\n yay = sum . map (searchLetter tg) $ sg\n\n sg' = groupCount $ map toLower s\n tg' = groupCount $ map toLower t\n\n yay_whoops = sum . map (searchLetter tg') $ sg'\n\n\n -- traceShow sg $ do\n -- traceShow tg $ do\n -- when (yay == 198087) $\n -- putStrLn (\"Sum is \" ++ show (yay_whoops) ++ \" and length is \" ++ show (length s))\n putStrLn $ show yay ++ \" \" ++ show (yay_whoops - yay)\n\n\n\n\n\n\n"}, {"source_code": "import qualified Data.Map.Strict as M\nimport Data.Char (toUpper, toLower)\n\ntype TanyaMap = M.Map Char Integer\n\noccurrences :: String -> TanyaMap\noccurrences = foldl (\\acc ch -> M.insertWith (+) ch 1 acc) M.empty\n\nfind def ch map = (M.findWithDefault def ch map, ch)\nfindCaseI def ch map =\n let lower = find 0 (toLower ch) map in\n if fst lower > 0\n then lower\n else find 0 (toUpper ch) map\n\ncount :: (Integer -> Char -> TanyaMap -> (Integer, Char)) -> TanyaMap -> TanyaMap -> (Integer, TanyaMap, TanyaMap)\ncount findFu strOcc lettersOcc = foldl processChar (0, strOcc, lettersOcc) (M.toList strOcc)\n where\n processChar (yayps, strOcc, lettersOcc) (ch, n) =\n let (available, ach) = findFu 0 ch lettersOcc in\n if available > n\n then\n (yayps + n, M.delete ch strOcc, M.insertWith (flip (-)) ach n lettersOcc)\n else\n if available == n\n then\n (yayps + n, M.delete ch strOcc, M.delete ach lettersOcc)\n else\n (yayps + available, M.insertWith (flip (-)) ch available strOcc, M.delete ach lettersOcc)\n\n\n\ncountYay = count find\ncountWhoops = count findCaseI\n\n\nmain :: IO ()\nmain = do\n str <- getLine\n letters <- getLine\n let (strOcc, lettersOcc) = (occurrences str, occurrences letters)\n (yay, newStrOcc, newLettersOcc) = countYay strOcc lettersOcc\n (whoops, newStrOcc1, newLettersOcc1) = countWhoops newStrOcc newLettersOcc\n\n putStrLn $ unwords [show yay, show whoops]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n t <- getLine\n\n let\n s' = accumArray (+) (0 :: Int) (chr 0, chr 255) $ zip s (repeat 1) :: Array Char Int\n t' = accumArray (+) (0 :: Int) (chr 0, chr 255) $ zip t (repeat 1) :: Array Char Int\n\n f c = (c1, c2)\n where\n m1 = min (s'!c) (t'!c)\n m2 = min (s'!c') (t'!c')\n c1 = m1 + m2\n c2 = min (t'!c + t'!c' - c1) (s'!c - m1 + s'!c' - m2)\n c'= toUpper c\n\n cs = map f ['a'..'z']\n\n putStrLn $ show (sum $ map fst cs) ++ \" \" ++ show (sum $ map snd cs)\n\n"}], "negative_code": [{"source_code": "import System.IO\nimport Control.Applicative\nimport Debug.Trace\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\nimport qualified Data.Set as Set\n\n\n-- traceDebug = trace\ntraceDebug _ x = x\n\nsuccRevStr [] = \"a\"\nsuccRevStr ('z':tl) = 'a' : succRevStr tl\nsuccRevStr ( c :tl) = succ c : tl\n\n\nsuccStr s =\n reverse . succRevStr . reverse $ s\n\ngroupCount s =\n let s' = group . sort $ s\n in map (\\l -> (head l, length l)) s'\n\nmain = do\n s <- getLine\n t <- getLine\n let sg = groupCount s\n tg = groupCount t\n\n searchLetter (c,n) =\n traceShow (c,n) $\n let x = case lookup c tg of\n Nothing -> 0\n Just x' -> x'\n in traceShow (x, n-x) $ (min n x, max 0 $ n-x)\n\n counts = map searchLetter sg\n\n (yay,whoops) = foldl sumPair (0,0) counts\n sumPair (a,b) (a',b') = (a+a', b+b')\n\n traceShow sg $ do\n traceShow tg $ do\n putStrLn $ show yay ++ \" \" ++ show whoops\n\n\n\n\n\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport Debug.Trace\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\nimport qualified Data.Set as Set\n\n\n-- traceDebug = trace\ntraceDebug _ x = x\n\nsuccRevStr [] = \"a\"\nsuccRevStr ('z':tl) = 'a' : succRevStr tl\nsuccRevStr ( c :tl) = succ c : tl\n\n\nsuccStr s =\n reverse . succRevStr . reverse $ s\n\ngroupCount s =\n let s' = group . sort $ s\n in map (\\l -> (head l, length l)) s'\n\nmain = do\n s <- getLine\n t <- getLine\n let sg = groupCount s\n tg = groupCount t\n\n searchLetter (c,n) =\n traceShow (c,n) $\n let x = case lookup c tg of\n Nothing -> 0\n Just x' -> x'\n in traceShow (x, n-x) $ (min n x, max 0 $ n-x)\n\n counts = map searchLetter sg\n\n (yay,whoops) = foldl sumPair (0,0) counts\n sumPair (a,b) (a',b') = (a+a', b+b')\n\n traceShow sg $ do\n traceShow tg $ do\n when (yay == 198087) $\n putStrLn (\"Sum is \" ++ show (yay + whoops) ++ \" and length is \" ++ show (length s))\n putStrLn $ show yay ++ \" \" ++ show whoops\n\n\n\n\n\n\n"}, {"source_code": "import System.IO\nimport Control.Applicative\nimport Debug.Trace\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\nimport qualified Data.Set as Set\n\n\n-- traceDebug = trace\ntraceDebug _ x = x\n\nsuccRevStr [] = \"a\"\nsuccRevStr ('z':tl) = 'a' : succRevStr tl\nsuccRevStr ( c :tl) = succ c : tl\n\n\nsuccStr s =\n reverse . succRevStr . reverse $ s\n\ngroupCount s =\n let s' = group . sort $ s\n in map (\\l -> (head l, length l)) s'\n\nmain = do\n s <- getLine\n t <- getLine\n let sg = groupCount s\n tg = groupCount t\n\n searchLetter (c,n) =\n let x = case lookup c tg of\n Nothing -> 0\n Just x' -> x'\n in (x, n-x)\n\n counts = map searchLetter sg\n\n (yay,whoops) = foldl sumPair (0,0) counts\n sumPair (a,b) (a',b') = (a+a', b+b')\n\n putStrLn $ show yay ++ \" \" ++ show whoops\n\n\n\n\n\n\n"}], "src_uid": "96e2ba997eff50ffb805b6be62c56222"} {"source_code": "\nmain = do\n n <- getLine\n putStrLn $ concat $ reverse $ calc $ (read n :: Int)\n where\n calc 0 = []\n calc 3 = [\"7\"]\n calc n = \"1\" : calc (n - 2)", "positive_code": [{"source_code": "--ghc 7.10\n\nimport System.IO\n\nimport System.IO -- \u0438\u043c\u043f\u043e\u0440\u0442 \u043c\u043e\u0434\u0443\u043b\u044f IO\n \nfoo::Int -> String\nfoo n | even n = goo (n `div` 2)\n | otherwise = '7' : goo ((n `div` 2) - 1)\n \ngoo::Int -> String\ngoo 0 = []\ngoo n = '1' : goo (n-1)\n\n\n\nmain = do\n sx1 <- getLine \n --print (read (foo (read sx1 :: Int)) :: Int)\n putStrLn (foo (read sx1 :: Int))"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve :: String -> IO ()\n\nf :: Int -> String\nf n\n | mod n 2 == 1\t= '7' : (f (n - 3))\n | n == 0 = \"\"\n | otherwise = '1' : (f (n - 2))\n\nsolve = putStrLn . f . (read :: String -> Int)\n\nmain = getContents >>= solve"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n putStrLn $ solve n\n\nsolve :: Int -> String\nsolve 2 = \"1\"\nsolve 3 = \"7\"\nsolve n\n | n `rem` 2 == 0 = '1' : solve (n - 2)\n | otherwise = '7' : solve (n - 3)\n"}, {"source_code": "solve :: Int -> String\nsolve x = let\n len = x `div` 2\n lans = replicate len '1'\n in if len * 2 == x then lans else '7':(tail lans)\n\nmain :: IO ()\nmain = do\n a <- getLine\n let x = read a :: Int\n putStrLn $ solve x\n"}, {"source_code": "solve :: Integer -> Integer\nsolve x = let\n len = x `div` 2\n lans = ((10 ^ len) - 1) `div` 9\n in if len * 2 == x then lans else lans + 6 * 10 ^ (len - 1)\n\nmain :: IO ()\nmain = do\n a <- getLine\n let x = read a :: Integer\n print $ solve x\n"}, {"source_code": "main = do x <- getLine\n if mod (read x) 2 == 1 then (sequence ((putStr \"7\"):[putStr \"1\" | i <- [1..(div (read x) 2)-1]])) >> putStrLn \"\"\n else sequence [putStr \"1\" | i <- [1..(div (read x) 2)]] >> putStrLn \"\""}, {"source_code": "f::Int -> [Char]\nf n | mod n 2 == 0 = g (div n 2)\n\t| otherwise = '7' : g (div (n - 3) 2)\n\t\ng::Int -> [Char]\ng 0 = []\ng n = '1' : g (n - 1)\n\nmain = getLine >>= (putStr . f . read . head . words)"}, {"source_code": "solve :: Int -> [Char]\nsolve t | t `mod` 2 == 0 = replicate (t `div` 2) '1'\n\t\t| otherwise = '7':(replicate ((t `div` 2) - 1) '1')\n\nmain = do\n t <- getLine\n putStrLn $ solve (read t :: Int)"}, {"source_code": "fun :: Int -> String\nfun 0 = \"\"\nfun n \n | n `mod` 2 == 1 = \"7\" ++ (fun(n - 3))\n | True = \"1\" ++ (fun(n - 2))\n\nmain = do\n inputjar <- getLine\n let n = read inputjar :: Int\n let temp = fun(n)\n putStr temp"}, {"source_code": "\nmain :: IO ()\nmain = do\n s <- readLn\n putStrLn $ segments s\n\nsegments :: Int -> String\nsegments n\n | n == 0 = \"\"\n | n `rem` 2 == 0 = \"1\" ++ segments (n - 2)\n | otherwise = \"7\" ++ segments (n - 3)\n"}, {"source_code": "f s n = concat $ replicate n s\n\ng 0 a = f \"1\" a\ng 1 a = concat [\"7\", (g 0 (a - 1))]\n\nx a = (g (mod a 2) (div a 2))\n\nmain = do\n\ts <- getLine\n\tputStrLn (x (read s))"}, {"source_code": "showNumbers :: Int -> IO ()\nshowNumbers 0 = return ()\nshowNumbers n = if n `mod` 2 == 1 \n\t\tthen do\n\t\t\tputStr \"7\"\n\t\t\tshowNumbers (n - 3)\n\t\telse do\n\t\t\tputStr \"1\"\n\t\t\tshowNumbers (n - 2)\n\nmain :: IO ()\nmain = do\n\tstr <- getLine\n\tlet number = read str :: Int\n\tshowNumbers number\n\treturn () \n"}, {"source_code": "main = do\n line <- getLine\n let number = read line\n if number `mod` 2 == 0\n then putStrLn $ replicate (number `div` 2) '1'\n else putStrLn $ \"7\" ++ replicate ((number `div` 2) - 1) '1'"}], "negative_code": [{"source_code": "fun :: Int -> String\nfun 0 = \"\"\nfun n \n | n `mod` 2 == 1 = \"7\" ++ (fun(n - 3))\n | True = \"1\" ++ (fun(n - 2))\n\nmain = do\n inputjar <- getLine\n let n = read inputjar :: Int\n let temp = fun(n)\n print (read temp :: Int)"}, {"source_code": "fun :: Int -> String\nfun 0 = \"\"\nfun n \n | n `mod` 2 == 1 = \"7\" ++ (fun(n - 3))\n | True = \"1\" ++ (fun(n - 2))\n\nmain = do\n inputjar <- getLine\n let n = read inputjar :: Int\n let temp = fun(n)\n print temp"}, {"source_code": "--ghc 7.10\n\nimport System.IO\n\nimport System.IO -- \u0438\u043c\u043f\u043e\u0440\u0442 \u043c\u043e\u0434\u0443\u043b\u044f IO\n \nfoo::Int -> String\nfoo n | even n = goo (n `div` 2)\n | otherwise = '7' : goo ((n `div` 2) - 1)\n \ngoo::Int -> String\ngoo 0 = []\ngoo n = '1' : goo (n-1)\n\nmain = do\n sx1 <- getLine \n putStrLn $ show $ foo (read sx1 :: Int)\n"}, {"source_code": "--ghc 7.10\n\nimport System.IO\n\nimport System.IO -- \u0438\u043c\u043f\u043e\u0440\u0442 \u043c\u043e\u0434\u0443\u043b\u044f IO\n \nfoo::Int -> String\nfoo n | even n = goo (n `div` 2)\n | otherwise = '7' : goo ((n `div` 2) - 1)\n \ngoo::Int -> String\ngoo 0 = []\ngoo n = '1' : goo (n-1)\n\nmain = do\n sx1 <- getLine \n print (read (foo (read sx1 :: Int)) :: Int)\n --putIntLn $ show $ read (foo (read sx1 :: Int)) :: Int"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve :: String -> IO ()\n\nf :: Int -> String\nf n\n | n >= 4\t= '1' : (f (n - 4))\n | n == 3 = \"7\"\n | n == 2 = \"1\"\n | otherwise = \"\"\n\nsolve = putStrLn . f . (read :: String -> Int)\n\nmain = getContents >>= solve"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve :: String -> IO ()\n\nf :: Int -> String\nf n\n | n >= 4\t= '1' : (f (n - 2))\n | n == 3 = \"7\"\n | n == 2 = \"1\"\n | otherwise = \"\"\n\nsolve = putStrLn . f . (read :: String -> Int)\n\nmain = getContents >>= solve"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve :: String -> IO ()\n\nf :: Int -> String\nf n\n | n >= 6\t= '9' : (f (n - 6))\n | n >= 3 = '7' : (f (n - 3))\n | n >= 2 = '1' : (f (n - 3))\n | otherwise = \"\"\n\nsolve = putStrLn . f . (read :: String -> Int)\n\nmain = getContents >>= solve"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n putStrLn $ solve n\n\nsolve :: Int -> String\nsolve 2 = \"1\"\nsolve 3 = \"7\"\nsolve n = '1' : solve (n - 2)\n"}, {"source_code": "main = do\n n <- getLine\n putStrLn $ concat $ calc $ (read n :: Int)\n where\n calc 0 = []\n calc 3 = [\"7\"]\n calc n = \"1\" : calc (n - 2)"}, {"source_code": "solve :: Int -> Int\nsolve x = let\n len = x `div` 2\n lans = ((10 ^ len) - 1) `div` 9\n in if len * 2 == x then lans else lans + 6 * 10 ^ (len - 1)\n\n\nmain :: IO ()\nmain = do\n a <- getLine\n let x = read a :: Int\n print $ solve x\n"}], "src_uid": "4ebea3f56ffd43efc9e1496a0ef7fa2d"} {"source_code": "import Control.Applicative\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \n\nmain = do\n\tgetLine\n\ts1<- foldl1 ((.|.)). map ( fst.fromJust.C.readInt) . C.words <$> C.getLine ::IO Int\n\ts2<- foldl1 ((.|.)). map ( fst.fromJust.C.readInt) . C.words <$> C.getLine ::IO Int \n\tprint $ s1 + s2\n\t\n\t \n", "positive_code": [{"source_code": "import Data.Bits\nimport Data.List\n\nmain :: IO ()\nmain = do \n c <- getContents\n let l = (map (read :: String -> Int) . words) c\n let n = head l\n let l1 = take n (tail l)\n let l2 = drop (n+1) l\n putStrLn $ show $ foldl' (.|.) 0 l1 + foldl' (.|.) 0 l2"}, {"source_code": "module Main where\n\nimport Data.Complex\nimport Data.Char\nimport Data.List\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\n\ntype R = Double\ntype Z = Int\ntype B = Integer\ntype Q = Rational\ntype C = Complex\n\ntype A = Char\ntype S = String\n\nreadR = map read <$> words <$> getLine :: IO [R]\nreadR1 = head <$> readR\n\nreadZ = map read <$> words <$> getLine :: IO [Z]\nreadZ1 = head <$> readZ\n\nreadB = map read <$> words <$> getLine :: IO [B]\nreadB1 = head <$> readB\n\nmain :: IO ()\nmain = do\n getLine\n xs <- readZ\n ys <- readZ\n print $ (foldl1 (.|.) xs) + (foldl1 (.|.) ys)"}, {"source_code": "import Data.Bits\n\nmain = getContents >>= print . solve . map read . words\n\nsolve (n:ls) = foldl (.|.) 0 (take n ls) + foldl (.|.) 0 (drop n ls)\n"}, {"source_code": "import Data.Bits\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n _ <- getLine\n as <- liftM (map read . words) getLine\n bs <- liftM (map read . words) getLine\n print $ maxValue as + maxValue bs\n\nmaxValue :: [Integer] -> Integer\nmaxValue = foldl (.|.) 0\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\nimport Data.Bits\nimport Data.Array\n-- import Data.ByteString (ByteString)\n-- import qualified Data.ByteString.Char8 as C\n-- import Data.ByteString.Char8 ()\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\nimport Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\nimport qualified Data.Sequence as S\n\nmyread = read :: String -> Int\nmain = do\n _ <- getLine\n as <- map myread.words <$> getLine\n bs <- map myread.words <$> getLine\n print $ solve as bs\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = foldl1 (.|.) as + foldl1 (.|.) bs"}], "negative_code": [], "src_uid": "475239ff4ae3675354d2229aba081a58"} {"source_code": "import Data.Map (fromList, findWithDefault)\n\ndata Type = T | TInt | TString | TDouble\n deriving (Show)\ndata Signature = Signature String [Type]\n deriving (Show)\n\ninstance Eq Type where\n T == _ = True\n _ == T = True\n TInt == TInt = True\n TString == TString = True\n TDouble == TDouble = True\n _ == _ = False\n\ninstance Eq Signature where\n (Signature name1 params1) == (Signature name2 params2) = name1 == name2 && params1 == params2\n\nreadType \"T\" = T\nreadType \"int\" = TInt\nreadType \"string\" = TString\nreadType \"double\" = TDouble\nreadType s = error s\n\nwordsBy dels s = wordsBy' $ dropWhile p s\n where\n p = flip elem dels\n wordsBy' \"\" = []\n wordsBy' s = (takeWhile (not . p) s):(wordsBy' $ dropWhile p $ dropWhile (not . p) s)\n\nmain = do\n n <- fmap read getLine\n signs <- fmap (map ((\\(_:name:params) -> Signature name $ map readType params) . wordsBy [' ', ',', '(', ')'])) $ sequence $ replicate n getLine\n m <- fmap read getLine\n vars <- fmap (map ((\\([t,name]) -> (name, readType t)) . words)) $ sequence $ replicate m getLine\n let mvars = fromList vars\n k <- fmap read getLine\n calls <- fmap (map ((\\(name:params) -> Signature name $ map (\\var -> findWithDefault T var mvars) params) . wordsBy [' ', ',', '(', ')'])) $ sequence $ replicate k getLine\n mapM_ (\\call -> print $ length $ filter (== call) signs) calls\n", "positive_code": [{"source_code": "import Data.Char\nimport Data.Map (Map,(!))\nimport qualified Data.Map as M\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n n <- readLn\n procm <- parseProc <$> replicateM n getLine\n m <- readLn\n varm <- parseVar <$> replicateM m getLine\n k <- readLn\n calls <- replicateM k getLine\n putStr.unlines.map (show.solve procm varm.parseCall) $ calls\n\nsolve :: [(String,[TT])] -> Map String TT -> (String,[String]) -> Int\nsolve procs varm (name,vars) = length [(n,ts)|(n,ts)<-procs,n==name,match ts types]\n where\n types :: [TT]\n types = map (varm!) vars\n\ndata TT = I | S | D | T deriving Eq\n\n(#) :: TT -> TT -> Bool\n_#T = True\nT#_ = True\nx#y = x==y\n\nmatch :: [TT] -> [TT] -> Bool\nmatch xs ys = lx==ly && and (zipWith (#) xs ys)\n where\n lx = length xs\n ly = length ys\n\ntoTT :: String -> TT\ntoTT \"int\" = I\ntoTT \"string\" = S\ntoTT \"double\" = D\ntoTT \"T\" = T\n\nparseProc :: [String] -> [(String,[TT])]\nparseProc ss = map parse ss\n where\n f ',' = ' '\n f c = c\n parse cs = let (name,'(':xs) = break ('('==).filter(not.isSpace).drop 4.dropWhile isSpace $ cs\n types = map toTT.words.map f.init $ xs\n in (name,types)\n\nparseVar :: [String] -> Map String TT\nparseVar ss = M.fromList $ map parse ss\n where\n parse cs = let (t,xs) = span isAlphaNum.dropWhile isSpace $ cs\n var = filter isAlphaNum xs\n in (var,toTT t)\n\nparseCall :: String -> (String,[String])\nparseCall cs = let (name,'(':xs) = break ('('==).filter(not.isSpace) $ cs\n f ',' = ' '\n f c = c\n vars = words.map f.init $ xs\n in (name,vars)\n"}], "negative_code": [], "src_uid": "d5e3136b236f0e84ed6b88e43acd4205"} {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \nmain= do\t \n\t[n,w]<- map read.words <$> getLine ::IO [Int]\n\ts<- sort . map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]\n\tlet m = head s\n\tlet m1 = head ( drop n s)\n\tlet sm = if (m *2 <=m1) then (fromIntegral m) else (fromIntegral m1)/2.0\n\tprint $ min (fromIntegral w) (sm *3.0*(fromIntegral n))\n\t \n\t\n \n\t \n\t ", "positive_code": [{"source_code": " -- http://codeforces.com/problemset/problem/557/B\n -- TODO: Program exceeds time!\n\n-- Faster if we read from ByteString\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nimport qualified Numeric as N\n\n--------------------------------\n\nmain = do\n\n\tline <-\n\t\tfmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\tcups <-\n\t\tfmap (map fromIntegral)\n\t\t$ fmap sort\n\t\t$ fmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\n\tlet\n\t\tni:wi:_ = line\n\t\t(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)\n\t\tmin1 = min (head cups) ((cups !! ni) / 2)\n\t\tmin2 = min min1 (w / (3 * n))\n\t\tans = min2 * (3 * n)\n\n\tputStrLn $ N.showFFloat Nothing (ans) \"\"\n\treturn ()"}], "negative_code": [{"source_code": " -- http://codeforces.com/problemset/problem/557/B\n -- TODO: Program exceeds time!\n\n-- Faster if we read from ByteString\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nimport qualified Numeric as N\n\n--------------------------------\n\nmain = do\n\n\tline <-\n\t\tfmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\tcups <-\n\t\tfmap (map fromIntegral)\n\t\t$ fmap sort\n\t\t$ fmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\n\tlet\n\t\tni:wi:_ = line\n\t\t(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)\n\t\tboys = min (cups !! ni) ( (w/(3*n)) * 2 )\n\t\tgirls = min (head cups) (boys / 2)\n\t\t\n\tputStrLn $ N.showFFloat Nothing (girls*n + boys*n) \"\"\n\treturn ()"}, {"source_code": "import Data.List\n\nclamp :: (Num a, Eq a, Ord a) => a -> a -> a -> a\nclamp val lower upper = min upper (max val lower)\n\nmain = do\n\n\tline <- getLine\n\tcups <- getLine\n\n\tlet\n\t\tn:ml:_ = map read $ words line :: [Int]\n\t\tnf = fromIntegral n\n\t\tcs = sort $ take (2*n) $ map read $ words cups :: [Float]\n\t\tmax_boys = head $ take n $ drop n cs\n\t\tmax_girls = clamp (head $ take n cs) 0 (max_boys / 2)\n\n\tputStrLn $ show $ (nf*max_boys + nf*max_girls)\n\n\treturn ()\n\n--------------------------------\n\n-- pour :: Float -> Int -> Int -> Float -> Float -> Float\n-- pour has boys girls pour_boys pour_girls\n-- \t| total_pour <= has= 10**(-6) = boys*pour_boys + girls*pour_girls\n-- \t| "}, {"source_code": " -- http://codeforces.com/problemset/problem/557/B\n -- TODO: Program exceeds time!\n\n-- Faster if we read from ByteString\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\n--------------------------------\n\nmain = do\n\n\tline <- fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words $ B.getLine\n\tcups <- fmap (map fromIntegral) $ fmap sort $ fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words $ B.getLine\n\n\tlet\n\t\tni:wi:_ = line\n\t\t(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)\n\t\tgirls1 = min (head cups) ((cups !! ni) / 2)\n\t\tgirls2 = min girls1 (w / 3 * n)\n\t\tgirls3 = girls2 * 3 * n\n\n\tputStrLn $ show girls3\n\treturn ()"}, {"source_code": " -- http://codeforces.com/problemset/problem/557/B\n -- TODO: Program exceeds time!\n\n-- Faster if we read from ByteString\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nimport qualified Numeric as N\n\n--------------------------------\n\nmain = do\n\n\tline <-\n\t\tfmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\tcups <-\n\t\tfmap (map fromIntegral)\n\t\t$ fmap sort\n\t\t$ fmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\n\tlet\n\t\tni:wi:_ = line\n\t\t(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)\n\t\tboys = min (cups !! ni) ( ((w / 3) * 2) / n )\n\t\tgirls = min (head cups) (boys / 2)\n\n\tputStrLn $ N.showFFloat Nothing (girls*n + boys*n) \"\"\n\treturn ()"}, {"source_code": " -- http://codeforces.com/problemset/problem/557/B\n -- TODO: Program exceeds time!\n\n-- Faster if we read from ByteString\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\n--------------------------------\n\nmain = do\n\n\tline <-\n\t\tfmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\tcups <-\n\t\tfmap (map fromIntegral)\n\t\t$ fmap sort\n\t\t$ fmap (map (fst . fromJust))\n\t\t$ fmap (map B.readInt)\n\t\t$ fmap B.words\n\t\t$ B.getLine\n\n\tlet\n\t\tni:wi:_ = line\n\t\t(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)\n\t\tboys = min (cups !! ni) ( ((w / 3) * 2) / n )\n\t\tgirls = min (head cups) (boys / 2)\n\n\tputStrLn $ show $ girls*n + boys*n\n\treturn ()"}, {"source_code": "import Data.List\n\nclamp :: (Num a, Eq a, Ord a) => a -> a -> a -> a\nclamp val lower upper = min upper (max val lower)\n\nmain = do\n\n\tline <- getLine\n\tcups <- getLine\n\n\tlet\n\t\tnf:ml:_ = map read $ words line :: [Float]\n\t\tn = truncate nf\n\t\tcs = sort $ take (2*n) $ map read $ words cups :: [Float]\n\t\tmax_boys = clamp (head $ take n $ drop n cs) 0 (2 * ml / 3)\n\t\tmax_girls = clamp (head $ take n cs) 0 (max_boys / 2)\n\n\tputStrLn $ show $ (nf*max_boys + nf*max_girls)\n\n\treturn ()\n\n--------------------------------\n\n-- pour :: Float -> Int -> Int -> Float -> Float -> Float\n-- pour has boys girls pour_boys pour_girls\n-- \t| total_pour <= has= 10**(-6) = boys*pour_boys + girls*pour_girls\n-- \t| "}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \nmain= do\t \n\t[n,w]<- map read.words <$> getLine ::IO [Int]\n\ts<- sort . map read. words <$> getLine :: IO [Int]\n\tlet m = head s\n\tlet m1 = head ( drop n s)\n\tlet sm = if (m *2 <=m1) then (fromIntegral m) else (fromIntegral m1)/2.0\n\tprint $ sm *3.0\n\t \n\t\n \n\t \n\t "}], "src_uid": "b2031a328d72b464f965b4789fd35b93"} {"source_code": "module Main where\n\nimport Data.List (sort)\nimport Data.Functor((<$>))\n\nmain = do\n [n, l', r] <- map readInt . words <$> getLine\n a <- map readInt . words <$> getLine\n b <- map readInt . words <$> getLine\n let l = l' - 1\n am = take (r - l) . drop l $ a\n bm = take (r - l) . drop l $ b\n if (take l a == take l b && drop r b == drop r a && sort am == sort bm)\n then putStrLn \"TRUTH\"\n else putStrLn \"LIE\"\n return ()\n\nreadInt :: String -> Int\nreadInt = read\n", "positive_code": [{"source_code": "import Data.List (sort)\nmain = do\n (n:l:r:as) <- fmap (map read . words) getContents\n-- let ks = (sort as) !! (n-k)\n-- print . length . filter (> 0) $ as\n let (a, b) = splitAt n as\n \n let (al, _) = (splitAt (l - 1) a)\n let (_, ar) = (splitAt r a)\n \n let (bl, _) = (splitAt (l - 1) b)\n let (_, br) = (splitAt r b)\n \n let (_, arp) = (splitAt (l - 1) a)\n let (ai, _) = (splitAt (r - l + 1) arp)\n \n let (_, brp) = (splitAt (l - 1) b)\n let (bi, _) = (splitAt (r - l + 1) brp)\n \n let ais = sort ai\n let bis = sort bi\n \n let res = if (ais == bis) && (al == bl) && (ar == br)\n then \"TRUTH\"\n else \"LIE\"\n \n putStrLn res"}, {"source_code": "\nsolve :: Int -> Int -> [Int] -> [Int] -> String\nsolve l r [] [] = \"TRUTH\"\nsolve l r (a:as) (b:bs) \n | (l > 0 || r < 0) && a /= b = \"LIE\"\n | otherwise = solve (l-1) (r-1) as bs\n\nmain = do\n [n,l,r] <- fmap (fmap read) $ fmap words $ getLine\n as <- fmap (fmap read) $ fmap words $ getLine\n bs <- fmap (fmap read) $ fmap words $ getLine\n putStrLn $ solve (l-1) (r-1) as bs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, l , r ] <- readInts\n\taa <- getList\n\tbb <- getList\n\t\n\tlet as = [1] ++ aa ++ [1]\n\tlet bs = [1] ++ bb ++ [1]\n\t\n\t\n\t--d <- [l-1,r-l+1,n-r]\n\t--print $d\n\tlet [al , am , ar] = splitPlaces [l, r-l+1, n-r+1] as\n\tlet [bl , bm , br] = splitPlaces [l, r-l+1, n-r+1] bs\n\t\n\tlet bam = sort bm\n\tlet sam = sort am\n\t\n\tlet a = al ++ sam ++ ar\n\tlet b = bl ++ bam ++ br\n\t\n\tlet x = which \"TRUTH\" \"LIE\" (a==b)\n\t\n\tputStrLn $x\n\t\n\t\n\t--print $ (as==bs)\n\t--print $ ( `div` 2 ) $ succ $ sum $ map ( \\m -> ( m + k - 1 ) `div` k ) as"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, l , r ] <- readInts\n\tas <- getList\n\tbs <- getList\n\t\n\t--d <- [l-1,r-l+1,n-r]\n\t--print $d\n\tlet [al , am , ar] = splitPlaces [l-1, r-l+1, n-r] as\n\tlet [bl , bm , br] = splitPlaces [l-1, r-l+1, n-r] bs\n\t\n\tlet bam = sort bm\n\tlet sam = sort am\n\t\n\tlet a = al ++ sam ++ ar\n\tlet b = bl ++ bam ++ br\n\t\n\t\n\tlet x = which \"TRUTH\" \"LIE\" (a==b)\n\t\n\tprint $x\n\t\n\t\n\t--print $ (as==bs)\n\t--print $ ( `div` 2 ) $ succ $ sum $ map ( \\m -> ( m + k - 1 ) `div` k ) as"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, l , r ] <- readInts\n\tas <- getList\n\tbs <- getList\n\t\n\tlet as = [1] ++ as ++ [1]\n\tlet bs = [1] ++ bs ++ [1]\n\t\n\t--d <- [l-1,r-l+1,n-r]\n\t--print $d\n\tlet [al , am , ar] = splitPlaces [l, r-l+1, n-r+1] as\n\tlet [bl , bm , br] = splitPlaces [l, r-l+1, n-r+1] bs\n\t\n\tlet bam = sort bm\n\tlet sam = sort am\n\t\n\tlet a = al ++ sam ++ ar\n\tlet b = bl ++ bam ++ br\n\t\n\t\n\tlet x = which \"TRUTH\" \"LIE\" (a==b)\n\t\n\tputStrLn $x\n\t\n\t\n\t--print $ (as==bs)\n\t--print $ ( `div` 2 ) $ succ $ sum $ map ( \\m -> ( m + k - 1 ) `div` k ) as"}], "src_uid": "1951bf085050c7e32fcf713132b30605"} {"source_code": "import Control.Exception.Base\nimport Debug.Trace\nimport Data.Functor\nimport Data.List\n\nreadInts :: IO [Int]\nreadInts = map read <$> words <$> getContents\nparsePairs :: [Int] -> [(Int, Int)]\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\n\nmain = readInts >>= putStrLn . show . solve . parsePairs . tail\n\nsolve :: [(Int, Int)] -> Integer\nsolve rs = let n = toInteger $ length rs in n * (n-1) * (n-2) `div` 6 - countDegen rs\n\ncountDegen :: [(Int, Int)] -> Integer\ncountDegen = f . sort where\n f [] = 0\n f (r:[]) = 0\n f (r:rs) = go r rs + f rs\n\ngeoMult :: Num a => (a, a) -> (a, a) -> (a, a) -> a\ngeoMult (x0, y0) (x1, y1) (x2, y2) = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)\n\ngo center rs = sum $ map (f . length) $ groupBy (\\x y -> cmp center x y == EQ) $ sortBy (cmp center) rs\n where f x = toInteger $ x * (x - 1) `div` 2\n\ncmp center x y\n | r < 0 = LT\n | r > 0 = GT\n | r == 0 = EQ\n where r = geoMult center x y\n\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n $ (\\[x, y] -> (x, y)) <$> getInts\n\n let\n count n = n'*(n'-1)*(n'-2) `div` 6 where n' = fromIntegral n :: Int64\n count2 n = n'*(n'-1) `div` 2 where n' = fromIntegral n :: Int64\n\n r = count n - (sum $ map f $ init $ tails ps)\n where\n f ((x, y):ps) = sum vs\n where\n vs = map (count2 . length) $ group $ sort $ map norm $ map (\\(xx, yy) -> (xx-x, yy-y)) ps\n where\n norm (x, y) = (x' `div` d, y' `div` d)\n where\n (x', y') = if x < 0 || x == 0 && y < 0 then (-x, -y) else (x, y)\n d = gcd x y\n\n print r\n"}, {"source_code": "import Control.Exception.Base\nimport Debug.Trace\nimport Data.Functor\nimport Data.List\n\nreadInts :: IO [Int]\nreadInts = map read <$> words <$> getContents\nparsePairs :: [Int] -> [(Int, Int)]\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\n\nmain = readInts >>= putStrLn . show . solve . parsePairs . tail\n\nsolve :: [(Int, Int)] -> Integer\nsolve rs = let n = toInteger $ length rs in n * (n-1) * (n-2) `div` 6 - countDegen rs\n\ncountDegen :: [(Int, Int)] -> Integer\ncountDegen = f . sort where\n f [] = 0\n f (r:[]) = 0\n f ((x0, y0):rs) = go (map (\\(x, y) -> (x-x0, y-y0)) rs) + f rs\n\nsimplify (x, y) \n | x == 0 = (0, 1)\n | y == 0 = (1, 0)\n | otherwise = let g = gcd x y in f (div x g) (div y g)\n where f x y = if x > 0 then (x, y) else (-x, -y)\n\ngo = sum . map (pairs . length) . group . sort . map simplify\n where pairs x = toInteger $ x * (x - 1) `div` 2\n\n"}, {"source_code": "import Data.List (group, sort)\nimport Control.Applicative ((<$>), liftA)\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as B8\n\nparse :: ByteString -> (Int, Int)\nparse = (\\(Just [a, b]) -> (a, b)). sequence . fmap readInt . B8.words\n where\n readInt :: ByteString -> Maybe Int\n readInt = (liftA fst) . B8.readInt\n\nf :: Int -> Int\nf n = n * (n - 1) `div` 2\n\ntria :: Int -> [(Int, Int)] -> Int\ntria acc [] = acc\ntria acc [(x, y)] = acc\ntria acc ((x,y):rest) = tria acc' rest\n where\n n = length rest :: Int\n a = fmap length . group . sort . fmap slope $ rest :: [Int]\n\n acc' = acc + f n - (sum . fmap f $ a) :: Int\n\n slope :: (Int, Int) -> (Int, Int)\n slope (u, v)\n | u == x = (0, 1)\n | v == y = (1, 0)\n | otherwise = (dx `div` w', dy `div` w')\n where\n dx = x - u :: Int\n dy = y - v :: Int\n w = gcd dx dy :: Int\n w' = if (dx < 0) == (w < 0) then w else (-w) :: Int\n\nmain = read <$> getLine >>= \\n ->\n tria 0 . fmap parse <$> replicateM n B.getLine >>= print\n"}, {"source_code": "import Data.List (group, sort)\n\ndata Point = Point Int Int\n deriving (Show, Eq)\ntype Input = [Point]\n\nparse :: String -> Input\nparse = map (parsePoint . map read . words) . lines\n where parsePoint [x, y] = Point x y\n parsePoint _ = undefined\n\ninstance Ord Point where\n (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'\n\nnormalize :: Int -> Int -> Point\nnormalize 0 0 = Point 0 0\nnormalize x y\n | invalid = normalize (-x) (-y)\n | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)\n where invalid = y < 0 || y == 0 && x < 0\n\npairs :: Int -> Int\npairs n = n * (n - 1) `div` 2\n\ncolinears :: [Point] -> Int\ncolinears = sum . map (pairs . length) . group . sort\n\nsolve' :: Point -> [Point] -> Int\nsolve' (Point x0 y0) ps' = pairs (n - 1) - colinears ps\n where n = length ps\n ps = map (\\(Point x y) -> normalize (x - x0) (y - y0)) ps'\n\nsolve :: Input -> Integer\nsolve ps = sum [fromIntegral (solve' p ps) | p <- ps] `div` 3\n\nmain :: IO ()\nmain = do\n _ <- getLine\n print . solve . parse =<< getContents\n"}, {"source_code": "import Data.List (group, sort)\n\ndata Point = Point Int Int\n deriving (Show, Eq)\ntype Input = [Point]\n\nparse :: String -> Input\nparse = map (parsePoint . map read . words) . lines\n where parsePoint [x, y] = Point x y\n parsePoint _ = undefined\n\ninstance Ord Point where\n (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'\n\nnormalize :: Point -> Point\nnormalize p@(Point 0 0) = p\nnormalize (Point x y)\n | invalid = normalize (Point (-x) (-y))\n | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)\n where invalid = y < 0 || y == 0 && x < 0\n\nsolve' :: Point -> [Point] -> Int\nsolve' (Point x0 y0) ps' = pairs (length ps - 1) - colineras\n where ps = map f ps'\n f (Point x y) = normalize (Point (x - x0) (y - y0))\n colineras = sum . map (pairs . length) . group . sort $ ps\n pairs n = n * (n - 1) `div` 2\n\nsolve :: Input -> Integer\nsolve ps = sum [fromIntegral (solve' p ps) | p <- ps] `div` 3\n\nmain :: IO ()\nmain = do\n _ <- getLine\n print . solve . parse =<< getContents\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n $ (\\[x, y] -> (x, y)) <$> getInts\n\n let\n count n = n'*(n'-1)*(n'-2) `div` 6 where n' = fromIntegral n :: Int64\n\n r = count n - (sum $ map f $ init $ tails ps)\n where\n f ((x, y):ps) = sum vs\n where\n vs = map (count . (+1) . length) $ group $ sort $ map norm $ map (\\(xx, yy) -> (xx-x, yy-y)) ps\n where\n norm (x, y) = (x' `div` d, y' `div` d)\n where\n (x', y') = if x < 0 || x == 0 && y < 0 then (-x, -y) else (x, y)\n d = gcd x y\n\n print r\n"}, {"source_code": "import Data.List (group, sort)\n\ndata Point = Point Int Int\n deriving (Show, Eq)\ntype Input = [Point]\n\nparse :: String -> Input\nparse = map (parsePoint . map read . words) . lines\n where parsePoint [x, y] = Point x y\n parsePoint _ = undefined\n\ninstance Ord Point where\n (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'\n\nnormalize :: Point -> Point\nnormalize p@(Point 0 0) = p\nnormalize (Point x y)\n | invalid = normalize (Point (-x) (-y))\n | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)\n where invalid = y < 0 || y == 0 && x < 0\n\nsolve' :: Point -> [Point] -> Int\nsolve' (Point x0 y0) ps' = pairs (length ps - 1) - colineras\n where ps = map f ps'\n f (Point x y) = normalize (Point (x - x0) (y - y0))\n colineras = sum . map (pairs . length) . group . sort $ ps\n pairs n = n * (n - 1) `div` 2\n\nsolve :: Input -> Int\nsolve ps = sum [solve' p ps | p <- ps] `div` 3\n\nmain :: IO ()\nmain = do\n _ <- getLine\n print . solve . parse =<< getContents\n"}], "src_uid": "d5913f8208efa1641f53caaee7624622"} {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve a = solve' (sort a) [] []\n\nsolve' :: [Int] -> [Int] -> [Int] -> Int\nsolve' [] [] [] = 0\nsolve' [] curr next = (length curr) - 1 + solve' (reverse next) [] []\nsolve' (a:ax) [] [] = solve' ax [a] []\nsolve' (a:ax) (c:cx) next | a == c = solve' ax (c:cx) (a:next)\n | otherwise = solve' ax (a:c:cx) next\n", "positive_code": [{"source_code": "import Data.List\n\nmain::IO ()\nmain = getLine >> do\n us <- fmap (map read. words) getLine :: IO [Int]\n print $ snd $ foldl' go (Nothing, 0::Int) $ sort us where\n go (Nothing , acc) el = (Just (el, 1::Int, 0::Int), acc)\n go (Just (p, reps, racc), acc) el\n | p == el && racc > 0 = (Just (el, reps + 1, racc - 1), acc + 1)\n | p == el = (Just (el, reps + 1, racc ), acc)\n | otherwise = (Just (el, 1, racc + reps - 1), acc + 1)\n"}, {"source_code": "module Main where\n\nimport Data.Complex\nimport Data.Char\nimport Data.List\nimport Data.Functor\nimport Control.Monad\n\ntype R = Double\ntype Z = Int\ntype B = Integer\ntype Q = Rational\ntype C = Complex\n\ntype A = Char\ntype S = String\n\nreadR = map read <$> words <$> getLine :: IO [R]\nreadR1 = head <$> readR\n\nreadZ = map read <$> words <$> getLine :: IO [Z]\nreadZ1 = head <$> readZ\n\nreadB = map read <$> words <$> getLine :: IO [B]\nreadB1 = head <$> readB\n\ng :: (Ord a) => [a] -> [[a]]\ng [x] = [[x]]\ng (x:xs)\n | x < head y = (x : y) : ys\n | otherwise = [x] : zs\n where zs@(y:ys) = g xs\n\nf :: (Ord a) => [[a]] -> [[a]]\nf [] = []\nf xs = h xs (length xs)\n where\n h (y:ys) n\n | m == n = zs\n | otherwise = h zs m\n where\n zs = f' y ys\n m = length zs\n f' y [] = [y]\n f' y zs'@(z:zs)\n | last y < head z = (y ++ z) : zs\n | otherwise = z : f' y zs\n\nmain :: IO ()\nmain = do\n _ <- readZ1\n xs <- readZ\n print $ sum . map (\\x -> length x - 1) . f . g . sort $ xs"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\nimport Data.Array\n-- import Data.Array.ST\n-- import Data.Array.Unsafe\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nout = stdout\n\nmain = do\n _ <- readInt1 <$> BS.getLine\n ns <- readIntN <$> BS.getLine\n print $ solve ns\n\nsolve :: [Int] -> Int\nsolve = sum . map (pred.length) . transpose . group . sort where\n\n-- makeTable :: -> Table\n-- makeTable \n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)\n\n-- output functions\n\ndata Cell = ByteStringC BL.ByteString\n | IntC Int\n | Int64C Int64\n deriving( Eq, Ord, Show )\n\ndata Row = ListR [Cell]\n | TupleR (Cell,Cell)\n | TripleR (Cell,Cell,Cell)\n deriving( Eq, Ord, Show )\n\ntype Table = [Row]\n\ninfixr 4 <>\n(<>) :: Monoid m => m -> m -> m\n(<>) = mappend\n\nputAns :: Handle -> Table -> IO ()\nputAns o = hPutBuilder o . renderTable\n\nrenderTable :: Table -> Builder\nrenderTable rs = mconcat [renderRow r <> char8 '\\n' | r <- rs]\n\nrenderRow :: Row -> Builder\nrenderRow (ListR []) = mempty\nrenderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]\nrenderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y\nrenderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z\n\nrenderCell :: Cell -> Builder\nrenderCell (ByteStringC cs) = lazyByteString cs\nrenderCell (IntC i) = intDec i\nrenderCell (Int64C i) = int64Dec i\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve xs = (length xs) - (maximum $ map length $ group $ sort xs)\n\nmain = print . solve . map read . words . head . tail . lines =<< getContents"}], "negative_code": [{"source_code": "import Control.Applicative\n\nmain = (words <$> getLine) >>= print"}], "src_uid": "30ad5bdc019fcd8a4e642c90decca58f"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n (n, m) <- liftM2 (,) get get\n a <- replicateM n get\n putln $ f1 a n m\n\n\nf1 :: [Int64] -> Int -> Int -> Int64\nf1 a n m = if n >= m + 1\n then 0\n else let aa = array (1, length a) (zip [1..length a] a) :: UArray Int Int64 in\n foldl (\\s i ->\n foldl (\\s j ->\n (mod (s * (abs ((aa ! i) - (aa ! j)))) (fromIntegral m))\n ) s [i+1..length a]\n ) 1 [1..length a]", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = do\n (n:m:_) <- map read.words <$> getLine\n as <- map read.words <$> getLine\n if any (> 1) $ map length $ group $ sort $ map (`mod` m) as\n then print 0\n else print $ foldr (\\a b -> (a * b) `mod` m) 1 [abs (ai - aj) `mod` m | i <- [0..n - 1], let (pre, (aj:_)) = genericSplitAt i as, ai <- pre]\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = do\n (n:m:_) <- map read.words <$> getLine\n as <- map read.words <$> getLine\n if any (> 1) $ map length $ group $ sort $ map (`mod` m) as\n then print 0\n else print $ product [abs (ai - aj) `mod` m | i <- [0..n - 1], let (pre, (aj:_)) = splitAt i as, ai <- pre] `mod` m\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = do\n (n:m:_) <- map read.words <$> getLine\n as <- map read.words <$> getLine\n if any (> 1) $ map length $ group $ sort $ map (`mod` m) as\n then print 0\n else print $ product [abs $ ai - aj | i <- [0..n - 1], let (pre, (aj:_)) = splitAt i as, ai <- pre] `mod` m\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n (n, m) <- liftM2 (,) get get\n a <- replicateM n get\n putln $ f1 a n m\n\n\nf1 :: [Int64] -> Int -> Int -> Int64\nf1 a n m = if n + 1 >= m\n then 0\n else let aa = array (1, length a) (zip [1..length a] a) :: UArray Int Int64 in\n foldl (\\s i ->\n foldl (\\s j ->\n (mod (s * (abs ((aa ! i) - (aa ! j)))) (fromIntegral m))\n ) s [i+1..length a]\n ) 1 [1..length a]"}], "src_uid": "bf115b24d85a0581e709c012793b248b"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.List as L (sort)\nimport qualified Data.Sequence as Q ((|>), viewl, viewr, ViewL((:<)), ViewR((:>)), empty, length)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun m k s [] ans = ans\nrun m k s (x:xs) ans = run m k rs xs r where\n ns = niter (s Q.|> x)\n niter ns@(Q.viewl -> l Q.:< ls) | x - l >= m = niter ls | otherwise = ns\n aiter ans (Q.length -> 0) = (ans, Q.empty)\n aiter ans ns@(Q.viewr -> rs Q.:> r) | Q.length ns >= k = aiter (ans + 1) rs | otherwise = (ans, ns)\n (r, rs) = aiter ans ns\n\nmain = do\n (map readInt . C.words -> [n, m, k]) <- B.getLine\n (L.sort . map readInt . C.words -> xs) <- B.getLine\n putStrLn $ show $ run m k Q.empty xs 0\n", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.Sequence as S\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . B.words\nsolve (n:m:k:xs0) = sum $ snd $ mapAccumL (\\q ((l, _), (r, o)) -> let q' = (if o then (S.|> r) else id) $ S.dropWhileL (< l) q in if S.length q' >= k then (S.take (k - 1) q', S.length q' - k + 1) else (q', 0)) (S.fromList $ map fst $ filter snd ps) $ zip (tail xs) rs\n where\n xs = assocs (accumArray (flip const) False (0, hi) $ zip xs0 (repeat True) :: UArray Int Bool)\n (ps, rs) = splitAt m xs\n hi = 10^6"}], "negative_code": [], "src_uid": "1241e23684a5cf95eca085a77f6483ad"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\nf::Map.Map Int Int->Int->Bool\nf ms x=let Just x1=Map.lookup x ms\n Just x2=Map.lookup x1 ms\n Just x3=Map.lookup x2 ms\n in if x==x3 then True else False\n\nmain = do\n a<-getLine\n b<-getLine\n let e=read a::Int\n xs=map read (words b)::[Int]\n ms=Map.fromList $ zip [1..e] xs\n putStrLn $ if (any (==True ) ( map (f ms) xs))==True then \"YES\" else \"NO\"", "positive_code": [{"source_code": "import Data.Array (listArray, (!))\nprocess :: [Int] -> Bool\nprocess xs = any (\\i -> a!i /= i && a!(a!(a!i)) == i) [1..n]\n where\n n = length xs\n a = listArray (1,n) xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n fs <- fmap (map readInt.words) getLine\n if process fs\n then putStrLn \"YES\"\n else putStrLn \"NO\""}, {"source_code": "import Data.Array\nmain = interact $ solve . map read . words\nsolve (n:as) | any (\\i -> g!(g!(g!i)) == i) (indices g) = \"YES\" | otherwise = \"NO\"\n where g = listArray (1,n) as\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\n\n\ncheck n lk x | n>lk = False\n | n /=t1 && t1 /=t2 && t2 /=t3 && t3==n =True \n\t | otherwise = check (n+1) lk x\n\twhere \tt1 = fromJust $ M.lookup n x \n\t\tt2= fromJust $ M.lookup t1 x \n\t\tt3 = fromJust $ M.lookup t2 x \nprocess k = do\n\t\tlet x = M.fromList $ zip [1..] k\n\t\tlet lk = length k\n\t\tif check 1 lk x then \"Yes\" else \"No\"\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\tk<- map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ process k\n\t \n"}], "negative_code": [], "src_uid": "a37c3f2828490c70301b5b5deeee0f88"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n a <- getInts n\n let\n initArr :: UArray Int Bool\n initArr = listArray (1, n) $ replicate n False\n step :: UArray Int Bool -> Int -> UArray Int Bool\n step arr x = if x > n || (x >= 1 && arr ! x)\n then step arr (x `div` 2)\n else arr // [(x, True) | x >= 1]\n ans = and $ elems $ foldl' step initArr a\n pure $ string7 $ if ans\n then \"YES\\n\"\n else \"NO\\n\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Data.ByteString.Char8 (ByteString)\nimport Data.Maybe (fromJust, listToMaybe)\nimport Data.Set (Set)\nimport Control.Monad ( foldM )\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain :: IO()\nmain = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words\n\nparse :: [Int] -> [ByteString]\nparse (n:rest) = solve n (take n rest) : parse (drop n rest)\nparse [] = []\n\nsolve :: Int -> [Int] -> ByteString\nsolve n arr = maybe (B.pack \"NO\") (const $ B.pack \"YES\") $ foldM exec S.empty arr where\n exec mySet x = (`S.insert` mySet) <$> cook_x where\n cook_x = listToMaybe $ dropWhile bad $ takeWhile (>0) $ iterate (`div` 2) x\n bad y = y > n || S.member y mySet"}, {"source_code": "import Data.ByteString.Char8 (ByteString)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Set (Set)\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain :: IO()\nmain = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words\n\nparse :: [Int] -> [ByteString]\nparse (n:rest) = solve n (take n rest) S.empty : parse (drop n rest)\nparse [] = []\n\nsolve :: Int -> [Int] -> Set Int -> ByteString\nsolve n (x:xs) mySet = if new_x == 0 then (B.pack \"NO\") else\n solve n xs (S.insert new_x mySet)\n where\n new_x = judge good_x mySet\n good_x = sitdown x n\nsolve _ [] _ = B.pack \"YES\"\n\nsitdown :: Int -> Int -> Int\nsitdown x n = if x <= n then x else sitdown (div x 2) n \n\njudge :: Int -> Set Int -> Int\njudge x mySet = if S.member x mySet then judge (div x 2) mySet else x"}, {"source_code": "import Data.ByteString.Char8 (ByteString)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Set (Set)\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain :: IO()\nmain = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words\n\n\nparse :: [Int] -> [ByteString]\nparse (n:rest) = solve n (sort . take n $ rest) S.empty : parse (drop n rest)\nparse [] = []\n\nsolve :: Int -> [Int] -> Set Int -> ByteString\nsolve n (x:xs) mySet = if new_x == 0 then (B.pack \"NO\") else\n solve n xs (S.insert new_x mySet)\n where\n new_x = judge good_x mySet\n good_x = sitdown x n\nsolve _ [] _ = B.pack \"YES\"\n\nsitdown :: Int -> Int -> Int\nsitdown x n = if x <= n then x else sitdown (div x 2) n \n\njudge :: Int -> Set Int -> Int\njudge x mySet = if S.member x mySet then judge (div x 2) mySet else x"}, {"source_code": "import Data.Char\r\nimport Data.List ((\\\\))\r\n\r\nmain :: IO()\r\nmain = do\r\n tStr <- getLine\r\n let t = read tStr :: Int\r\n solve t\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = return ()\r\nsolve t = do\r\n nStr <- getLine\r\n let n = read nStr :: Int\r\n\r\n aStr <- getLine\r\n let as = readIntList aStr\r\n \r\n let ans = if possible (minimize as) n then \"YES\" else \"NO\"\r\n\r\n putStrLn ans\r\n solve (t-1)\r\n\r\nminimize :: [Int] -> [Int]\r\nminimize = map change\r\n\r\nchange :: Int -> Int\r\nchange a \r\n | a > 50 = change (a `div` 2)\r\n | otherwise = a\r\n\r\npossible :: [Int] -> Int -> Bool \r\npossible [] n = True \r\npossible as n\r\n | maxi < n = False\r\n | maxi == n = possible (as \\\\ [maxi]) (n-1)\r\n | maxi > n = possible (newEl : (as \\\\ [maxi])) n\r\n | otherwise = False\r\n where\r\n maxi = foldr max 0 as\r\n newEl = maxi `div` 2\r\n\r\n\r\n\r\nreadIntList :: String -> [Int]\r\nreadIntList [] = []\r\nreadIntList (h : t)\r\n | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)\r\n | otherwise = readIntList t"}, {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n as <- readInts\r\n let go have x = (:have) <$> x' where\r\n bad y = y > n || y `elem` have\r\n x' = listToMaybe $ dropWhile bad $ takeWhile (>0) $ iterate (`div` 2) x\r\n putStrLn $ maybe \"NO\" (const \"YES\") $ foldM go [] as\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\n\r\nreadInt :: IO Int\r\nreadInt = readLn\r\n\r\nreadIntArray :: IO [Int]\r\nreadIntArray = (map read . words) <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readInt >>= \\t -> replicateM_ t test\r\n\r\ntest :: IO ()\r\ntest = do\r\n n <- readInt\r\n dt <- (reverse . sort) <$> readIntArray\r\n putStrLn $ if can dt then \"YES\" else \"NO\"\r\n\r\nminimize :: Int -> Int -> [Int] -> [Bool] -> Int -> Bool\r\nminimize n pos dt used x\r\n | pos == n = True\r\n | x == 0 = False\r\n | x > n = minimize n pos dt used (div x 2)\r\n | x <= n && not (used !! x) = minimize n pos dt used (div x 2)\r\n | otherwise = minimize n nxt dt newUsed (dt !! nxt)\r\n where\r\n (left, right) = splitAt x used\r\n (remove : need) = right\r\n newUsed = left ++ [False] ++ need\r\n nxt = pos + 1\r\n\r\ncan :: [Int] -> Bool\r\ncan dt = minimize n 0 dt [True | _ <- [0..n]] (dt !! 0)\r\n where n = length dt\r\n"}], "negative_code": [{"source_code": "import Data.Char\r\nimport Data.List ((\\\\))\r\n\r\nmain :: IO()\r\nmain = do\r\n tStr <- getLine\r\n let t = read tStr :: Int\r\n solve t\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = return ()\r\nsolve t = do\r\n nStr <- getLine\r\n let n = read nStr :: Int\r\n\r\n aStr <- getLine\r\n let as = readIntList aStr\r\n \r\n let ans = if possible (minimize as) n then \"YES\" else \"NO\"\r\n\r\n putStrLn ans\r\n solve (t-1)\r\n\r\nminimize :: [Int] -> [Int]\r\nminimize = map change\r\n\r\nchange :: Int -> Int\r\nchange a \r\n | a > 50 = change (a `div` 50)\r\n | otherwise = a\r\n\r\npossible :: [Int] -> Int -> Bool \r\npossible [] n = True \r\npossible as n\r\n | maxi < n = False\r\n | maxi == n = possible (as \\\\ [maxi]) (n-1)\r\n | maxi > n = possible (newEl : (as \\\\ [maxi])) n\r\n | otherwise = False\r\n where\r\n maxi = foldr max 0 as\r\n newEl = maxi `div` 2\r\n\r\n\r\n\r\nreadIntList :: String -> [Int]\r\nreadIntList [] = []\r\nreadIntList (h : t)\r\n | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)\r\n | otherwise = readIntList t"}], "src_uid": "645459e0a41ec63b13648ea8dbe0f053"} {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nswap (a,b) = (b,a)\n\nmain = do\n n:m:l <- map readInt . B.words <$> B.getContents\n let banned = parse l\n print $ solve n banned\n\nparse l = go l []\n where\n go [] acc = acc\n go (a:b:l) acc = go l ((a,b):acc)\n\nsolve :: Int -> [(Int,Int)] -> Int\nsolve n l = sum [ f i | i <- [2..n `div` 2]] + \n if odd n && \n (validX A.! (div n 2+1) || validY A.! (div n 2+1))\n then 1 else 0\n where\n validX = A.accumArray (\\a e -> False) True (1,n) $ l\n validY = A.accumArray (\\a e -> False) True (1,n) $ map swap l\n f i = length $ filter id [a A.! j | a <- [validX,validY],\n j <- [i,n+1-i]]\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getContents\n print $ solve n $ map (subtract 1) xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xys = sum $ map f [1..n-2]\n where\n f i | i < n-i-1 = sum [unsafeAt arr j|arr<-[arrX,arrY],j<-[i,n-i-1]]\n | i == n-i-1 = unsafeAt arrX i `max` unsafeAt arrY i\n | otherwise = 0\n\n arrX, arrY :: UArray Int Int\n (arrX, arrY) = runST $ do\n arrX <- newArray (0,n-1) 1 :: ST s (STUArray s Int Int)\n arrY <- newArray (0,n-1) 1 :: ST s (STUArray s Int Int)\n let go (x:y:xys) = do\n unsafeWrite arrX x 0\n unsafeWrite arrY y 0\n go xys\n go _ = return ()\n go xys\n (,) <$> unsafeFreeze arrX <*> unsafeFreeze arrY"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nswap (a,b) = (b,a)\n\nmain = do\n n:m:l <- map readInt . B.words <$> B.getContents\n let banned = parse l\n print $ solve n banned\n\nparse l = go l []\n where\n go [] acc = reverse acc\n go (a:b:l) acc = go l ((a,b):acc)\n\nsolve :: Int -> [(Int,Int)] -> Int\nsolve n l = sum [ f i | i <- [2..n `div` 2]] + \n if odd n && \n (validX A.! (div n 2+1) || validY A.! (div n 2+1))\n then 1 else 0\n where\n validX = A.accumArray (\\a e -> False) True (1,n) $ l\n validY = A.accumArray (\\a e -> False) True (1,n) $ map swap l\n f i = length $ filter id [a A.! j | a <- [validX,validY],\n j <- [i,n+1-i]]\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nswap (a,b) = (b,a)\n\nmain = do\n n:m:l <- map readInt . B.words <$> B.getContents\n let banned = parse l\n print $ solve n banned\n\nparse l = go l []\n where\n go [] acc = acc\n go (a:b:l) acc = go l ((a,b):acc)\n\nsolve :: Int -> [(Int,Int)] -> Int\nsolve n l = sum [ f i | i <- [2..n `div` 2]] + \n if odd n && \n (validX A.! (div n 2+1) || validY A.! (div n 2+1))\n then 1 else 0\n where\n validX = (A.accumArray (\\a e -> False) True (1,n) $ l)::A.UArray Int Bool\n validY = A.accumArray (\\a e -> False) True (1,n) $ map swap l\n f i = length $ filter id [a A.! j | a <- [validX,validY],\n j <- [i,n+1-i]]\n\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as Set\nimport Data.Char\n\ntoInt s = (read s :: Int)\n\ncToInt ch = (ord ch) - 48\n\ntoInt' :: [Char] -> Int\ntoInt' ys = let toInt'' [] r = r\n toInt'' (x:xs) r = toInt'' xs (r*10 + (cToInt x))\n in toInt'' ys 0\n\ntoIntList s = map toInt' $ words s\n\nbannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int\nbannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve n m bpos = let nh = (n+1) `div` 2\n rbs = bannedSet bpos fst\n cbs = bannedSet bpos snd\n goodRows = [ r | r <- [2..(n-1)], Set.notMember r rbs ]\n goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]\n\n groupCount = [ (length $ filter (\\x -> (x == g || x == (n-g+1))) goodRows) +\n (length $ filter (\\x -> (x == g || x == (n-g+1))) goodCols) | g <- [2..nh] ]\n \n in if n `mod` 2 == 0\n then sum groupCount\n else if last groupCount <= 1 \n then sum groupCount\n else sum groupCount - 1\n\nmain = do fline <- getLine\n let [n,m] = toIntList fline\n bpos <- forM [1..m] (\\_ -> do\n bSt <- getLine\n let items = words bSt\n r = items !! 0\n c = items !! 1\n return (r,c))\n putStrLn $ show $ solve n m (map (\\(rs,cs) -> (toInt' rs, toInt' cs)) bpos)"}], "negative_code": [{"source_code": "import Control.Monad\nimport qualified Data.Set as Set\n\ntoInt s = (read s :: Int)\ntoIntList s = map toInt $ words s\n\nbannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int\nbannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve n m bpos = let rbs = bannedSet bpos fst\n cbs = bannedSet bpos snd\n goodRows = Set.fromList [ r | r <- [2..(n-1)], Set.notMember r rbs ]\n goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]\n usableCols = Set.fromList [ c | c <- goodCols, ((Set.notMember c rbs) || (Set.notMember (n-c+1) rbs)) ]\n in (Set.size goodRows) + (length goodCols)\n\nmain = do fline <- getLine\n let [n,m] = toIntList fline\n bpos <- forM [1..m] (\\_ -> do\n bSt <- getLine\n let items = map toInt $ words bSt\n r = items !! 0\n c = items !! 1\n return (r,c))\n putStrLn $ show $ solve n m bpos"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as Set\n\ntoInt s = (read s :: Int)\ntoIntList s = map toInt $ words s\n\nbannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int\nbannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve n m bpos = let rbs = bannedSet bpos fst\n cbs = bannedSet bpos snd\n goodRows = Set.fromList [ r | r <- [2..(n-1)], Set.notMember r rbs ]\n goodCols = Set.fromList [ c | c <- [2..(n-1)], Set.notMember c cbs ]\n in Set.size $ Set.union goodRows goodCols\n\nmain = do fline <- getLine\n let [n,m] = toIntList fline\n bpos <- forM [1..m] (\\_ -> do\n bSt <- getLine\n let items = map toInt $ words bSt\n r = items !! 0\n c = items !! 1\n return (r,c))\n putStrLn $ show $ solve n m bpos"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as Set\n\ntoInt s = (read s :: Int)\ntoIntList s = map toInt $ words s\n\nbannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int\nbannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve n m bpos = let rbs = bannedSet bpos fst\n cbs = bannedSet bpos snd\n goodRows = Set.fromList [ r | r <- [2..(n-1)], Set.notMember r rbs ]\n goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]\n usableCols = Set.fromList [ c | c <- goodCols, ((Set.notMember c rbs) || (Set.notMember (n-c+1) rbs)) ]\n in Set.size $ Set.union goodRows usableCols\n\nmain = do fline <- getLine\n let [n,m] = toIntList fline\n bpos <- forM [1..m] (\\_ -> do\n bSt <- getLine\n let items = map toInt $ words bSt\n r = items !! 0\n c = items !! 1\n return (r,c))\n putStrLn $ show $ solve n m bpos"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as Set\n\ntoInt s = (read s :: Int)\ntoIntList s = map toInt $ words s\n\nbannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int\nbannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve n m bpos = let nh = (n+1) `div` 2\n rbs = bannedSet bpos fst\n cbs = bannedSet bpos snd\n goodRows = [ r | r <- [2..(n-1)], Set.notMember r rbs ]\n goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]\n\n groupCount = [ (length $ filter (\\x -> (x == g || x == (n-g+1))) goodRows) +\n (length $ filter (\\x -> (x == g || x == (n-g+1))) goodCols) | g <- [2..nh] ]\n \n fgroupCount = map (\\x -> if x > 3 then 3 else x) groupCount\n\n in if n `mod` 2 == 0\n then sum fgroupCount\n else if last fgroupCount <= 1 \n then sum fgroupCount\n else sum fgroupCount - 1\n\nmain = do fline <- getLine\n let [n,m] = toIntList fline\n bpos <- forM [1..m] (\\_ -> do\n bSt <- getLine\n let items = map toInt $ words bSt\n r = items !! 0\n c = items !! 1\n return (r,c))\n putStrLn $ show $ solve n m bpos"}], "src_uid": "a26a97586d4efb5855aa3b930e9effa7"} {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nm :: Int64\r\nm = 998244353\r\n\r\nnewtype MInt = MInt {toInt64 :: Int64}\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b\r\n MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger i = MInt $ fromInteger i `mod` m\r\n\r\ndata Portal = Portal {px :: Int, py :: Int, ps :: Int}\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n p <- listArray (1, n) <$> replicateM n ((\\[x, y, s] -> Portal x y s) <$> readInts)\r\n let dp = fArray (1, n) f where\r\n f :: Int -> MInt\r\n f i = fromIntegral (x - y) + dpsum!(i - 1) - dpsum!(j - 1) where\r\n Portal x y s = p!i\r\n j = binSearchA ((> y) . px) p\r\n dpsum = fArray (0, n) f where\r\n f 0 = 0\r\n f i = dpsum!(i - 1) + dp!i\r\n print $ toInt64 $ 1 + fromIntegral (px $ p!n) + sum (map (dp!) $ filter ((==1) . ps . (p!)) [1..n])\r\n\r\nfArray :: (Ix i) => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = go (f . (a!)) l (h + 1) where\r\n (l, h) = bounds a\r\n go f l h\r\n | l >= h = l\r\n | f m = go f l m\r\n | otherwise = go f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInt = parseInt <$> C.getLine \r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nm :: Int64\r\nm = 998244353\r\n\r\ndata Portal = Portal {px :: Int, py :: Int, ps :: Int}\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n p <- listArray (1, n) <$> replicateM n ((\\[x, y, s] -> Portal x y s) <$> readInts)\r\n let dp = fArray (1, n) f where\r\n f i = (fromIntegral (x - y) + dpsum!(i - 1) - dpsum!(j - 1)) `mod` m where\r\n Portal x y s = p!i\r\n j = binSearchA ((> y) . px) p\r\n dpsum = fArray (0, n) f where\r\n f 0 = 0\r\n f i = (dpsum!(i - 1) + dp!i) `mod` m\r\n print $ (1 + fromIntegral (px $ p!n) + sum (map (dp!) $ filter ((==1) . ps . (p!)) [1..n])) `mod` m\r\n\r\nfArray :: (Ix i) => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = go (f . (a!)) l (h + 1) where\r\n (l, h) = bounds a\r\n go f l h\r\n | l >= h = l\r\n | f m = go f l m\r\n | otherwise = go f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInt = parseInt <$> C.getLine \r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [], "src_uid": "6dd3839826320795fa29702331a15744"} {"source_code": "import Control.Monad (forM)\nimport qualified Data.Map as M\n\nsolve t = do \n s <- getLine\n let m = M.fromListWith (+) [(c, 1) | c <- s]\n ans = foldl (\\x i -> x ++ replicate (snd i) (fst i)) \"\" (M.toList m)\n putStrLn ans\n\nmain = do\ntlen <- readLn :: IO Int\nforM [0..(tlen - 1)] (\\t -> do solve t)\n\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$unlines.map sort.tail.lines\n"}, {"source_code": "module Main where \r\n\r\nimport Control.Monad\r\nimport Data.List (sort)\r\n\r\n\r\nmain = do\r\n t <- fmap read getLine\r\n forM_ [1..t] $ \\_ -> do\r\n str <- getLine\r\n putStrLn $ sort str"}], "negative_code": [], "src_uid": "28102f75e0798960740e5a2625393c8f"} {"source_code": "import Control.Monad\nimport Data.List\n\n\nstripIndex lst = map (\\(a,b) -> b) lst\n\n\nstrToInt :: String -> Int\nstrToInt [] = 0\nstrToInt lst = read lst\n\n\ncalc :: String -> Int\ncalc s =\n let (left', right') = partition (\\(i,a) -> odd i) $ zip [1..] s\n left = stripIndex left'\n right = stripIndex right'\n a = strToInt left\n b = strToInt right\n in\n (a+1)*(b+1)-2\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n --let (left', right') = partition (\\(i,a) -> odd i) $ zip [1..] line\n --print line\n --print left'\n --print right'\n putStrLn $ show $ calc line\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = str\n\n-- output :: Output -> C.ByteString\noutput = showB\n\n-- solve :: Input -> Output\nsolve = subtract 2 . fst . fst . foldl compute init . map digitToInt . reverse\n where\n init = ((1, 0), (0, 0))\n withC d = 9 - d\n withoutC d = d + 1\n compute ((at00, at01), (at10, at11)) d =\n ( ( {- dp[0, 0] = -} at00 * withoutC d + at10 * withoutC (d - 1),\n {- dp[0, 1] = -} at00 * withC d + at10 * withC (d - 1)\n ),\n ( {- dp[1, 0] = -} at01 * withoutC d + at11 * withoutC (d - 1),\n {- dp[1, 1] = -} at01 * withC d + at11 * withC (d - 1)\n )\n )\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ lines >>> tail >>> map (solve >>> show) >>> unlines\n\nsolve :: String -> Int\nsolve ns = compute odd ns * compute even ns - 2\n where\n compute p = (1 +) . read . ('0' :) . map snd . filter (p . fst) . zip [1 ..]\n"}], "negative_code": [], "src_uid": "8588dd273c9651f8d51cd3a2b7bd81bd"} {"source_code": "{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Function\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Semigroup\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n#if __GLASGOW_HASKELL__ >= 713\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Reader\nimport Data.Functor.Identity\n#endif\n\n-- {{{ Functors\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Identity a = Identity {runIdentity :: a}\n\ninstance Functor Identity where\n fmap f (Identity x) = Identity $ f x\n#endif\n\n-- }}}\n\n-- {{{ Monads\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Reader a b = Reader {runReader :: a -> b}\nnewtype State s a = State {runState :: s -> (a, s)}\n\ninstance Functor (Reader a) where\n fmap f = Reader . (f . ). runReader\n {-# INLINE fmap #-}\n\ninstance Applicative (Reader a) where\n pure = Reader . const\n {-# INLINE pure #-}\n a <*> b = Reader f'\n where\n f1 = runReader a\n f2 = runReader b\n f' = \\p -> (f1 p) (f2 p)\n {-# INLINE (<*>) #-}\n\ninstance Monad (Reader a) where\n r1 >>= r2 = Reader $ \\a -> runReader (r2 $ runReader r1 a) a\n {-# INLINE (>>=) #-}\n return = pure\n\nask :: Reader a a\nask = Reader id\n{-# INLINE ask #-}\nlocal :: (a -> a) -> Reader a b -> Reader a b\nlocal f r = let f' = (runReader r) . f in Reader f'\n{-# INLINE local #-}\n\ninstance Functor (State s) where\n fmap f st = State $ \\s -> let (a, s') = runState st s in (f a, s')\n\ninstance Applicative (State s) where\n pure = State . (,)\n {-# INLINE pure #-}\n s1 <*> s2 = State $ \\s ->\n let (f, s') = runState s1 s\n (a, s'') = runState s2 s'\n in (f a, s'')\n\ninstance Monad (State s) where\n s1 >>= ms2 = State $ \\s ->\n let (a, s') = runState s1 s\n in runState (ms2 a) s'\n return = pure\n\nput :: s -> State s ()\nput = State . const . ((,) ())\n{-# INLINE put #-}\nget :: State s s\nget = State $ \\s -> (s, s)\n{-# INLINE get #-}\nexecState :: State s a -> s -> s\nexecState st s0 = snd $ runState st s0\n#endif\n\n-- }}}\n\n-- {{{ Lens\n\ntype CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t\ntype CylLens' a b = CylLens a a b b\nlens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t\nlens r w g b = w b <$> g (r b)\n{-# INLINE lens #-}\niso :: (a -> b) -> (b -> a) -> CylLens' a b\niso f f' = let f'' _ a = f a in lens f' f''\n{-# INLINE iso #-}\nlensGet :: CylLens a s b t -> b -> a\nlensGet lens = getConst . lens Const\n{-# INLINE lensGet #-}\nlensSet :: CylLens a s b t -> b -> s -> t\nlensSet lens b s = runIdentity $ lens (Identity . const s) b\n{-# INLINE lensSet #-}\n\n#if __GLASGOW_HASKELL__ < 713\ninfix 1 &\n#endif\n\ninfix 8 ^.\ninfix 4 .=, %=\ninfixr 4 .~, %~\n\n#if __GLASGOW_HASKELL__ < 713\n(&) :: a -> (a -> b) -> b\na & f = f a\n{-# INLINE (&) #-}\n#endif\n\n(^.) :: b -> CylLens a s b t -> a\nb ^. lens = lensGet lens b\n{-# INLINE (^.) #-}\n(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)\n(lens %~ f) b = lensSet lens b (f $ lensGet lens b)\n{-# INLINE (%~) #-}\n(.~) :: CylLens a s b t -> s -> (b -> t)\n(lens .~ v) b = lensSet lens b v\n{-# INLINE (.~) #-}\n(.=) :: CylLens a a' s s -> a' -> State s ()\nlens .= v = do {s <- get; put $ s & lens .~ v}\n{-# INLINE (.=) #-}\n(%=) :: CylLens a a' s s -> (a -> a') -> State s ()\nlens %= f = do {s <- get; put $ s & lens %~ f}\n{-# INLINE (%=) #-}\nview :: CylLens a a' s s' -> Reader s a\nview l = ask >>= return . (^. l)\nuse :: CylLens a a' s s' -> State s a\nuse l = get >>= return . (^. l)\n\n-- }}}\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\nsolve :: Int -> [(Int, Int)] -> [Int]\nsolve n xs = map (fromMaybe 0) $ rot 0 Nothing (zip zs ys) []\n where\n d s t\n | t >= s = t - s\n | otherwise = n - s + t\n xs' = map (\\(a, b) -> (a - 1, Just (Sum n, Min $ d (a - 1) (b - 1)))) xs\n ysR = accumArray (<>) Nothing (0, n - 1) xs'\n ys = map (fmap (\\(Sum k, Min dt) -> k + dt - n)) $ elems ysR\n zs = scanr1 (<>) $ map (\\(y, i) -> (Max . (+i)) <$> y) $ zip ys [0..]\n\n mInt :: CylLens' Int (Max Int)\n mInt = iso Max getMax\n\n rot :: Int -> Maybe (Max Int) -> [(Maybe (Max Int), Maybe Int)] -> [Maybe Int] -> [Maybe Int]\n rot _ _ [] acc = reverse acc\n rot offset prevMax ((maxX, x):t) acc =\n rot (offset + 1)\n (((& (mInt %~ (subtract 1))) <$> prevMax) <> ((Max . (+(n - 1))) <$> x))\n t\n ((getMax <$> prevMax <> ((& mInt %~ (subtract offset)) <$> maxX)):acc)\n\n\nmain :: IO ()\nmain = do\n contents <- BS.getContents\n let (n, xs) = readFrom contents $ do\n _n <- getInt\n _m <- getInt\n _xs <- replicateM _m $ (,) <$> getInt <*> getInt\n return (_n, _xs)\n ans = solve n xs\n putStrLn $ unwords $ map show ans\n return ()\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndist nNode src dst = if src < dst then dst - src else dst + (nNode - src)\n\nshortestTimeNode :: Int -> Int -> Int -> [Int] -> Int\nshortestTimeNode _ _ _ [] = 0\nshortestTimeNode nNode initNode node candies = beforeLast + shortestLast where\n nLoop = if initNode == node then length candies - 2 else length candies - 1\n beforeLast = nNode * nLoop + dist nNode initNode node\n shortestLast = minimum $ map (dist nNode node) candies\n\nshortestTimeNodes nNode filteredCandies initNode =\n maximum $ map (uncurry $ shortestTimeNode nNode initNode) filteredCandies\n\nprocess :: [[Int]] -> [Int]\nprocess nodeCandies = map (shortestTimeNodes n filteredCandies) [0..(n-1)] where\n n = length nodeCandies\n maxCandy = maximum (map length nodeCandies)\n filteredCandies = filter (\\(i, nc) -> length nc >= maxCandy - 1) (zip [0..] nodeCandies)\n\nmain = do\n n:m:[] <- getInts\n nodeCandyArray <- newArray (1, n) [] :: IO (IA.IOArray Int [Int])\n replicateM_ m (writeCandy nodeCandyArray)\n nodeCandies <- getElems nodeCandyArray :: IO [[Int]]\n putStrLn $ showCandies $ process nodeCandies\n\nwriteCandy candies = do\n node:candy:[] <- getInts\n candyList <- readArray candies node\n writeArray candies node ((candy-1) : candyList)\n\nshowCandies = unwords . map show\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndist nNode src dst = if src < dst then dst - src else dst + (nNode - src)\n\nshortestTimeNode :: Int -> Int -> Int -> (Int, Int) -> Int\nshortestTimeNode nNode initNode node (nLoop, lastTime) = if lastTime == 0 then 0 else beforeLast + lastTime where\n nLoop' = if initNode == node then nLoop - 1 else nLoop\n beforeLast = nNode * (nLoop'- 1) + dist nNode initNode node\n\nshortestTimeNodes nNode filteredCandiesInfo initNode =\n maximum $ map (uncurry $ shortestTimeNode nNode initNode) filteredCandiesInfo\n\nprocess :: [[Int]] -> [Int]\nprocess nodeCandies = map (shortestTimeNodes n filteredCandiesInfo) [0..(n-1)] where\n n = length nodeCandies\n maxCandy = maximum (map length nodeCandies)\n filteredCandies = filter (\\(i, nc) -> length nc >= max 1 (maxCandy - 1)) (zip [0..] nodeCandies)\n filteredCandiesInfo = map (\\(i, nc) -> (i, (length nc, minimum $ map (dist n i) nc))) filteredCandies\n\nmain = do\n n:m:[] <- getInts\n nodeCandyArray <- newArray (1, n) [] :: IO (IA.IOArray Int [Int])\n replicateM_ m (writeCandy nodeCandyArray)\n nodeCandies <- getElems nodeCandyArray :: IO [[Int]]\n putStrLn $ showCandies $ process nodeCandies\n\nwriteCandy candies = do\n node:candy:[] <- getInts\n candyList <- readArray candies node\n writeArray candies node ((candy-1) : candyList)\n\nshowCandies = unwords . map show\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ndist nNode src dst = if src < dst then dst - src else dst + (nNode - src)\n\nshortestTimeNode :: Int -> Int -> Int -> [Int] -> Int\nshortestTimeNode _ _ _ [] = 0\nshortestTimeNode nNode initNode node candies = beforeLast + shortestLast where\n nLoop = if initNode == node then length candies - 2 else length candies - 1\n beforeLast = nNode * nLoop + dist nNode initNode node\n shortestLast = minimum $ map (dist nNode node) candies\n\nshortestTimeNodes nNode filteredCandies initNode =\n maximum $ map (uncurry $ shortestTimeNode nNode initNode) filteredCandies\n\nprocess :: [[Int]] -> [Int]\nprocess nodeCandies = map (shortestTimeNodes n filteredCandies) [0..(n-1)] where\n n = length nodeCandies\n maxCandy = maximum (map length nodeCandies)\n filteredCandies = filter (\\(i, nc) -> length nc == maxCandy) (zip [0..] nodeCandies)\n\nmain = do\n n:m:[] <- getInts\n nodeCandyArray <- newArray (1, n) [] :: IO (IA.IOArray Int [Int])\n replicateM_ m (writeCandy nodeCandyArray)\n nodeCandies <- getElems nodeCandyArray :: IO [[Int]]\n putStrLn $ showCandies $ process nodeCandies\n\nwriteCandy candies = do\n node:candy:[] <- getInts\n candyList <- readArray candies node\n writeArray candies node ((candy-1) : candyList)\n\nshowCandies = unwords . map show\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Data.Array\nimport Data.Char\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\nsolve :: Int -> [(Int, Int)] -> [Int]\nsolve n xs = rot 0 0 (zip zs ys) []\n where\n d s t\n | t >= s = t - s\n | otherwise = n - s + t\n xs' = map (\\(a, b) -> (a - 1, d (a - 1) (b - 1))) xs\n ysR = accumArray (\\(b, l) dt -> (b + n, min l dt)) (0, n) (0, n - 1) xs'\n ys = map ((subtract n) . uncurry (+)) $ elems ysR\n zs = scanr1 max $ map (uncurry (+)) $ zip ys [0..]\n\n rot :: Int -> Int -> [(Int, Int)] -> [Int] -> [Int]\n rot _ _ [] acc = reverse acc\n rot offset prevMax ((maxX, x):t) acc =\n rot (offset + 1) (max (prevMax - 1) (x + n - 1)) t (max prevMax (maxX - offset):acc)\n\n\nmain :: IO ()\nmain = do\n contents <- BS.getContents\n let (n, xs) = readFrom contents $ do\n _n <- getInt\n _m <- getInt\n _xs <- replicateM _m $ (,) <$> getInt <*> getInt\n return (_n, _xs)\n ans = solve n xs\n putStrLn $ unwords $ map show ans\n return ()\n"}], "src_uid": "ecda736a0caa924ebd5f8f133586d542"} {"source_code": "main = interact $ solve . map read . words\n\nsolve :: (Integral a, Show a) => [a] -> String\nsolve [n, k] | n * (n - 1) > 2 * k = unlines $ map ((\"4 \" ++) . show) [1 .. n]\n | otherwise = \"no solution\"", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nitof :: Int -> Double\nitof = fromIntegral\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,k] <- readLns\n if k >= n * (n - 1) `div` 2 then\n putStrLn \"no solution\"\n else\n forM_ [0..n-1] $ \\i-> printf \"0 %d\\n\" (i :: Int)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do [n, k] <- fmap (map read . words) getLine\n if n * (n - 1) <= 2 * k then \n putStrLn \"no solution\"\n else\n mapM_ (\\x -> putStrLn (\"0 \" ++ show x)) [1..n]"}, {"source_code": "main=interact$f.map read.words\nf :: [Integer] -> String\nf[n,k]\n | k >= sum[n-i|i<-[1..n]] = \"no solution\"\n | otherwise = unlines.map((\"0 \"++).show)$take (fromIntegral n) [0..]\n"}, {"source_code": "main = do\n [n, k] <- (map read . words) `fmap` getLine\n if k >= n*(n-1) `div` 2\n then\n putStrLn \"no solution\"\n else\n putStr $ unlines $ map (\\i -> \"0 \" ++ (show i)) $ take n $ [0..]\n"}], "negative_code": [{"source_code": "main = do\n [n, k] <- (map read . words) `fmap` getLine\n if k > n*(n-1) `div` 2\n then\n putStrLn \"no solution\"\n else\n putStr $ unlines $ map (\\i -> \"0 \" ++ (show i)) $ take n $ [0..]\n"}, {"source_code": "main=interact$f.map read.words\nf :: [Integer] -> String\nf[n,k]\n | k >= n*(n+1)`div`2-1 = \"no solution\"\n | otherwise = unlines.map((\"0 \"++).show)$take (fromIntegral n) [10^9,(10^9)-1..]\n"}], "src_uid": "a7846e4ae1f3fa5051fab9139a25539c"} {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n\ndata Point = Point Pico Pico\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-7\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) =\n\t\t\t\t(dist lp lq) * (sum $ map (\\((z1, z2), _) -> z2 - z1) $ filter (\\(_, c) -> c /= 0) $ zip (zip zs (tail zs ++ zs)) cs')\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\t(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n\ndata Point = Point Pico Pico \ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\n\n-- TODO how Pico to Double ?\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-7\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) =\n\t\t\t\t(dist lp lq) * (sum $ map fst $ filter ((/= 0) . snd) $ zip ds cs')\n\t\t\twhere\n\t\t\t\t(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\tds = zipWith (flip (-)) zs (tail zs ++ zs)\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tlv = vect lp lq\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n\ndata Point = Point Pico Pico deriving (Show)\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-7\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) =\n\t\t\t\t((dist lp lq) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\t(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n\ndata Point = Point Pico Pico deriving (Show)\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-7\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) =\n\t\t\t\t((dist lp lq) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\tis = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\t(zs, cs) = unzip is\n\t\t\t\tcs' :: [Int]\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n\ndata Point = Point Pico Pico\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-7\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) =\n\t\t\t\t(dist lp lq) * (sum $ map fst $ filter (\\(_, c) -> c /= 0) $ zip (zipWith (flip (-)) zs (tail zs ++ zs)) cs')\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\t(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n\ndata Point = Point Pico Pico\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-7\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) =\n\t\t\t\t((dist lp lq) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\t(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n-- import Debug.Trace (trace)\n\ndata Point = Point Pico Pico deriving (Show)\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-6\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) = -- trace (show is) $\n\t\t\t\t((dist lp lq) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\tis = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\t(zs, cs) = unzip is\n\t\t\t\tcs' :: [Int]\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\n-- import Debug.Trace (trace)\n\ndata Point = Point Double Double deriving (Show)\ndata Vector = Vector Double Double\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\n\neps = 1e-9\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) = -- trace (show is) $\n\t\t\t\t((sqrt (lv `dot` lv)) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\tis = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\t(zs, cs) = unzip is\n\t\t\t\tcs' :: [Int]\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\n-- import Debug.Trace (trace)\n\ndata Point = Point Double Double deriving (Show)\ndata Vector = Vector Double Double\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = sqrt $ (x2-x1)^2 + (y2-y1)^2\n\neps = 1e-3\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) = -- trace (show is) $\n\t\t\t\t((dist lp lq) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\tis = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\t(zs, cs) = unzip is\n\t\t\t\tcs' :: [Int]\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (catMaybes)\nimport Data.Fixed (Pico)\n-- import Debug.Trace (trace)\n\ndata Point = Point Pico Pico deriving (Show)\ndata Vector = Vector Pico Pico\n\nvect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\nVector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2\nPoint x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)\n\neps = 1e-3\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n\tps <- map ((\\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine\n\tls <- map ((\\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine\n\n\tlet\n\t\tsolve (lp, lq) = -- trace (show is) $\n\t\t\t\t((dist lp lq) *) $ sum $ map (\\(z1, z2, _) -> z2 - z1) $ filter (\\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'\n\t\t\twhere\n\t\t\t\tlv = vect lp lq\n\t\t\t\tis = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps\n\t\t\t\t(zs, cs) = unzip is\n\t\t\t\tcs' :: [Int]\n\t\t\t\tcs' = scanl1 (+) cs\n\n\t\t\t\tintersect p q\n\t\t\t\t\t| s1 == s2 = Nothing\n\t\t\t\t\t| otherwise = Just (z, c)\n\t\t\t\t\twhere\n\t\t\t\t\t\tsgn m = if m <= - eps then -1 else if m >= eps then 1 else 0\n\t\t\t\t\t\ts1 = sgn $ lv `cross` (vect lp p) \n\t\t\t\t\t\ts2 = sgn $ lv `cross` (vect lp q) \n\n\t\t\t\t\t\tz = ((vect lp p) `cross` pq) / (lv `cross` pq)\n\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\tpq = vect p q\n\n\t\t\t\t\t\tc = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)\n\n\tputStr $ unlines $ map (show . solve) ls\n"}], "src_uid": "4bb6d1680ca0cbfe76dbcce5ea4c77b3"} {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List (group, sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>> map (words >>> map read) >>> solve >>> show >>> (++ \"\\n\")\n\nsolve :: [[Integer]] -> Integer\nsolve [[n, k], a]\n | maximum (map snd groups) >= k = 0\n | otherwise = minimum $ map (get k) [lt, rt, comb]\n where\n groups = getGroups a\n lt = compute groups\n rt = reverse . compute . reverse $ groups\n comb = zip (repeat n) $ zipWith (+) (map snd lt) (map snd rt)\n\ntype PII = (Integer, Integer)\n\n-- merge :: [PII] -> [PII] -> [PII]\n-- merge = zipWith cadd\n-- where\n-- cadd (l, c) (l', c') = (l + l', c + c')\n\ngetGroups :: [Integer] -> [PII]\ngetGroups =\n map (\\u -> (head u, fromIntegral $ length u))\n . group\n . sort\n\ninf :: Integer\ninf = 10 ^ 18\n\nget :: Integer -> [(Integer, Integer)] -> Integer\nget k =\n foldl min inf\n . map ((+ k) . uncurry (flip (-)))\n . filter ((>= k) . fst)\n\n-- [(value, length)] -> [(length, cost)]\ncompute :: [(Integer, Integer)] -> [(Integer, Integer)]\ncompute [] = []\ncompute [(_, l)] = [(l, 0)]\ncompute (x : x' : xs) = (len, cost) : res\n where\n res = compute (x' : xs)\n len = snd x + fst (head res)\n cost = snd (head res) + fst (head res) * abs (fst x - fst x')\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Data.List\n\nmain = interact $ \n lines >>> map (words >>> map read) >>> solve >>> show >>> (++\"\\n\")\n\nsolve :: [[Integer]] -> Integer\nsolve [[n,k], a]\n | foldl1 max (map snd groups) >= k = 0\n | otherwise = foldl1 min $ map (get k) [lt, rt, comb]\n where\n groups = getgroups a\n lt = compute groups\n rt = reverse $ compute $ reverse groups\n comb = map(\\(_, c) -> (n, c)) $ merge lt rt\n\nmerge a b = map (\\((l, c), (l', c')) -> (l + l', c + c')) \n $ zip a b\n\ngetgroups a = map (\\u -> (head u, fromIntegral $ length u)) \n $ group $ sort a\n\ninf = 1000000000000000000 :: Integer\nget k xs = foldl min inf\n $ map (\\(l, c) -> c - l + k)\n $ filter (\\(l, _) -> l >= k) xs\n\n-- [(value, length)] -> [(length, cost)]\ncompute :: [(Integer, Integer)] -> [(Integer, Integer)]\ncompute [] = []\ncompute [(v, l)] = [(l, 0)]\ncompute (a:b:rest) = (len, cost) : res\n where\n res = compute (b:rest)\n len = snd a + fst (head res)\n cost = snd (head res) + (fst (head res)) * abs (fst a - fst b)\n"}], "negative_code": [], "src_uid": "fc4d0f2d4dfc97484dbbafb3f2aee362"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (getLine, words, readInt)\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Tuple (swap)\nimport Prelude hiding (words, getLine)\n\nreadInt' = fst . fromJust .readInt\n\nmain = do\n\t_ <- getLine\n\tas <- map readInt' . words <$> getLine\n\tbs <- map readInt' . words <$> getLine\n\n\tlet\n\t\tas' = sort as\n\t\tbs' = sort $ zip bs [1..]\n\n\t\tsolve n _ [] = []\n\t\tsolve n [] (b:bs) = (n, snd b) : (solve n [] bs)\n\t\tsolve n (a:as) (b:bs)\n\t\t\t| a > fst b = (n, snd b) : (solve n (a:as) bs)\n\t\t\t| otherwise = solve (n + 1) as (b:bs)\n\n\t\tzs = solve 0 as' bs'\n\t\trs = map snd . sort $ map swap zs\n\n\tputStrLn . unwords $ map show rs\n", "positive_code": [{"source_code": "-- B. Queries about less or equal elements\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.List(sort)\nimport Data.Maybe(fromJust)\n\ncompute :: [Int] -> [Int] -> [Int]\ncompute a b = map snd . sort $ zip (map snd bs) (compute' (sort a) (map fst bs) 0)\n where bs = sort $ zip b [0::Int ..]\n compute' :: [Int] -> [Int] -> Int -> [Int]\n compute' _ [] _ = []\n compute' [] b' x = map (const x) b'\n compute' a'@(ah:at) b'@(bh:bt) x\n | ah <= bh = compute' at b' (x + 1)\n | otherwise = x : compute' a' bt x\n\nmain :: IO()\nmain =\n do _ <- C.getLine\n a <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n b <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n putStrLn . unwords . map show $ compute a b\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n\t(n : _ : input) <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents\n\tlet (as, bs) = (first sort) . (second $ (sort . (flip zip) [0 ..])) $ splitAt n input\n\tputStrLn $ concatMap (($ \" \") . (shows . fst)) $ sortBy (compare `on` snd) $ scanl1 (\\(acc, _) (v, i) -> (acc + v, i)) $ f as bs\n\nf _ [] \t\t\t\t= []\nf [] bs\t\t\t\t= map (first $ const 0) bs\nf as ((b, i) : bs)\t= let (smaller, larger) = span (<= b) as in (length smaller, i) : f larger bs\n"}, {"source_code": "import Data.List as L\nimport qualified Data.Set as Set\nimport Data.ByteString.Char8 as LC\n\nmaxval = 2000000001\n\nreadInt :: String -> Int\nreadInt = read\n\nsolve :: Set.Set (Int, Int) -> [Int] -> [Int]\nsolve aset [] = []\nsolve aset (x:xs) = ans:(solve aset xs)\n where Just (_, ans) = Set.lookupLT (x, maxval) aset\n\nconvert :: [Int] -> [Int]\nconvert nums =\n let n = nums !! 0\n (alist, blist) = L.splitAt n (L.drop 2 nums)\n in solve (Set.fromList $ L.zip ((-maxval):(L.sort alist)) [0..]) blist\n\nreadIntBs :: LC.ByteString -> Int\nreadIntBs bs = case LC.readInt bs of\n Just (x, _) -> x\n Nothing -> error \"may Paul Hudak have mercy on my soul\"\n\nmain = do\n input <- LC.getContents\n Prelude.putStrLn $ L.intercalate \" \" . L.map show . convert . (L.map readIntBs) . LC.words $ input\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char (digitToInt)\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.List (sort, scanl1, group)\nimport Data.Maybe (fromMaybe)\nimport Data.Functor ((<$>))\n\n\n\nparseInt :: ByteString -> Int\nparseInt s\n | BS.head s == '-' = negate (go 0 (BS.tail s))\n | otherwise = go 0 s\n where\n go i s\n | BS.null s = i\n | otherwise = go (i*10 + digitToInt (BS.head s)) (BS.tail s)\n\n\nmain :: IO ()\nmain = do\n l0 <- BS.getLine\n let [a, b] = map parseInt . BS.words $ l0\n l1 <- BS.getLine\n let as = group . sort . map parseInt . BS.words $ l1\n let lst = zip (map head as) (scanl1 (+) (map length as))\n let tree = IM.fromAscList lst\n l2 <- BS.getLine\n let bs = map parseInt . BS.words $ l2\n let answers = map (\\b -> fromMaybe 0 (snd <$> IM.lookupLE b tree)) bs\n BS.putStrLn (BS.unwords (map (BS.pack . show) answers))\n"}], "negative_code": [], "src_uid": "e9a519be33f25c828bae787330c18dd4"} {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Tuple\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n n <- readLn\r\n replicateM n getLine\r\n\r\nsolve = show . maximum . map solvePMs . transpose . map toPlusMinus . toCharCounts\r\n\r\ntoCharCounts ws = transpose . map (charFreqs ws) $ ['a'..'e']\r\ncharFreqs ws c = map (charFreq c) ws\r\ncharFreq c = length . filter (==c)\r\n\r\ntoPlusMinus cnts = (map.g.sum) cnts cnts\r\n where\r\n g len cnt = (cnt, len - cnt) -- (this char, other chars of the word)\r\n\r\nsolvePMs = length . takeWhile (>0) . scanl1 (+) . map (uncurry (-)) . sortOn (uncurry (-) . swap)\r\n", "positive_code": [{"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Tuple\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n n <- readLn\r\n replicateM n getLine\r\n\r\nsolve = show . maximum . map solvePMs . transpose . map toPlusMinus . toCharCounts\r\n\r\ntoCharCounts ws = transpose . map (charFreqs ws) $ ['a'..'e']\r\ncharFreqs ws c = map (charFreq c) ws\r\ncharFreq c = length . filter (==c)\r\n\r\ntoPlusMinus cnts = map (g.sum $ cnts) cnts\r\n where\r\n g len cnt = (cnt, len - cnt) -- (this char, other chars of the word)\r\n\r\nsolvePMs = length . takeWhile (>0) . scanl1 (+) . map (uncurry (-)) . sortOn (uncurry (-) . swap)\r\n"}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Tuple\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n n <- readLn\r\n replicateM n getLine\r\n\r\nsolve = show . maximum . map solvePMs . transpose . map toPlusMinus . toCharCounts\r\n\r\ntoCharCounts :: [String] -> [[Int]]\r\ntoCharCounts ws = transpose . map (charFreqs ws) $ ['a'..'e']\r\n\r\ncharFreqs :: [String] -> Char -> [Int]\r\ncharFreqs ws c = map (charFreq c) ws\r\n\r\ncharFreq :: Char -> String -> Int\r\ncharFreq c = length . filter (==c)\r\n\r\ntoPlusMinus :: [Int] -> [(Int,Int)]\r\ntoPlusMinus cnts = map (g.sum $ cnts) cnts\r\n where\r\n g len cnt = (cnt, len - cnt) -- (this char, other chars of the word)\r\n\r\nsolvePMs = length . takeWhile (>0) . scanl1 (+) . map (uncurry (-)) . sortOn (uncurry (-) . swap)\r\n"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\r\nimport Data.List (transpose, sortBy)\r\nimport Data.Map ((!), (!?))\r\nimport qualified Data.Map as M\r\n\r\ntype CharMap = M.Map Char Int\r\n\r\nscoreWord :: String -> CharMap\r\nscoreWord s = M.map score finalCnt where\r\n ins k = M.insertWith (+) k 1\r\n cnt = foldr ins M.empty s\r\n l = M.foldr (+) 0 cnt\r\n score x = x - (l - x)\r\n insMissing k = M.insertWith (\\_ x -> x) k 0\r\n finalCnt = foldr insMissing cnt ['a'..'e']\r\n\r\ninterestingWords :: [String] -> Int\r\ninterestingWords words = maximum $ map findMax scoreByChar where\r\n scoreMaps = map scoreWord words\r\n scoreMatrix = map (map snd . M.toList) scoreMaps\r\n sortDesc = sortBy (flip compare)\r\n scoreByChar = map sortDesc $ transpose scoreMatrix\r\n findMax = length . takeWhile (>0) . scanl1 (+)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn \r\n words <- replicateM n getLine\r\n print $ interestingWords words"}, {"source_code": "import Control.Monad\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as M\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\n\nnumToInt :: Char -> Int\nnumToInt 'a' = 0\nnumToInt 'b' = 1\nnumToInt 'c' = 2\nnumToInt 'd' = 3\nnumToInt 'e' = 4\nnumToInt _ = undefined\n\n-- | Take a sequence of elements and convert into frequency mapping\ncollect :: [Int] -> IntMap Int\ncollect = foldl ins_ $ M.fromList [(i, 0) | i <- [0 .. 4]]\n where\n ins_ m n = M.alter (Just . maybe 1 (+ 1)) n m\n\nsolution' :: Int -> [IntMap Int] -> Int\nsolution' l words = length correctWords\n where\n diff m = 2 * (m M.! l) - sum (M.elems m)\n sortedWords = sortOn (Down . diff) words\n aggWords = scanl1 (M.unionWith (+)) sortedWords\n correctWords = takeWhile ((> 0) . diff) aggWords\n\nprepareWords :: [String] -> [IntMap Int]\nprepareWords words = do\n word <- words\n let wordNum = numToInt <$> word\n return $ collect wordNum\n\nsolution :: [String] -> Int\nsolution words = maximum $ (`solution'` prepareWords words) <$> [0 .. 4]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n forM_ [1 .. n] $ \\_ -> do\n n' <- read <$> getLine\n words <- traverse (const getLine) [1 .. n']\n print $ solution words\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort, sortBy)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = show . solve <$> numberOf str\r\n\r\nsolve :: [String] -> Int\r\nsolve ws = maximum . map compute $ ['a' .. 'e']\r\n where\r\n compute :: Char -> Int\r\n compute c =\r\n length\r\n . takeWhile (> 0)\r\n . scanl1 (+)\r\n . reverse\r\n . sort\r\n $ map cost ws\r\n where\r\n cost w = 2 * count c w - length w\r\n\r\n-------------------------- Template ------------------------------------------\r\ncount :: Eq a => a -> [a] -> Int\r\ncount x = length . filter (== x)\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified Data.Ratio as Rat\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nmaxlen xs ch = res\n where a = map (\\word -> (length $ filter (==ch) word, length word)) xs\n b = sortBy (\\x1 x2 -> let diff (q,w) = w - 2*q in compare (diff x1) (diff x2)) a\n (res, _, _) = foldl (\\(taken, good, bad) (q,w) -> let (g,b) = (good+q, bad+w-q) in\n (if g > b then (taken+1, g, b) else (taken, good, bad))) (0, 0, 0) b\n \n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n a <- readrows n\n let sol = maximum $ map (maxlen a) ['a'..'e'] in\n print sol\n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral b) => b -> IO [String]\nreadrows 0 = return []\nreadrows n = do\n row <- getLine\n l <- readrows $ n-1\n return (row : l)\n\n\nreadintrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadintrows 0 = return []\nreadintrows n = do\n row <- readInts\n l <- readintrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}], "negative_code": [{"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n n <- readLn\r\n replicateM n getLine\r\n\r\nsolve = const \"123\"\r\n"}], "src_uid": "18ac51a009c907fe8e4cd2bb8612da20"} {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nsolve :: Int -> Int -> [(Int,Int)] -> Int\nsolve nf nt [] = nt + nf\nsolve nf nt ((f,t):xs)\n | nf == f = solve nf (max nt t) xs\n | otherwise = solve f (nt+nf-f) $ (f,t):xs\n\nmain :: IO ()\nmain = do\n [n,s] <- map read . words <$> getLine\n lst <- sort <$> replicateM n (do\n [f,t] <- map read . words <$> getLine\n return (f,t))\n print $ solve s 0 lst\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n interact solve\n\nsolve input = show (do_it s 0)\n where\n numbers :: [Int]\n numbers = map read (words input)\n (n,s):rest = two_by_two numbers\n \n do_it :: Int -> Int -> Int\n do_it (-1) current = current-1\n do_it cs current = do_it (cs-1) (newtime+1)\n where newtime = max current (last_arrival cs rest)\n\nlast_arrival :: Int -> [(Int,Int)] -> Int\nlast_arrival ofn inputbytwo = doloop inputbytwo\n where \n doloop [] = 0\n doloop ((floor,time):xs)\n | (floor /= ofn) = othertime\n | otherwise = max time othertime\n where\n othertime = doloop xs\n\ntwo_by_two (x:y:xs) = (x,y):two_by_two(xs)\ntwo_by_two [] = []\n"}, {"source_code": "\n-- Michael V. Antosha \n-- 2015\n-- http://mivael.in.ua\n\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.List (foldl')\n\ntype IntType = Int\n\nmain :: IO ()\nmain = do\n in_str <- getContents\n putStrLn . solve $ in_str\n\nsolve :: String -> String\nsolve = show . solveInt . map read . words\n\nsolveInt :: [IntType] -> IntType -- [num] -> time\nsolveInt (n:s:arrivals) = calculate . parse $ arrivals\n where\n parse = verifyLength n . makePairs\n makePairs = makePairsRev -- order is not important\n calculate = calcTotalTime s . calcArrivals s\n calcArrivals = calcLastArrivalTimeForEachFloor\nsolveInt _ = undefined -- not enough input data\n\nmakePairsRev :: [a] -> [(a, a)]\nmakePairsRev = mp [] where\n mp lst [] = lst\n mp lst (f:t:rest) = mp ((f,t):lst) rest\n mp _ (_:[]) = undefined -- odd number of integers\n\nverifyLength :: IntType -> [a] -> [a] -- length -> [a] -> [a]\nverifyLength len _ | (len < 0) = undefined\nverifyLength list_length list_of_pairs\n = vl list_length list_of_pairs list_of_pairs\n where\n vl 0 [] list = list\n vl 0 _ _ = undefined\n vl len (_:xs) list = vl (len - 1) xs list\n vl _ [] _ = undefined -- check failed (wrong 'len')\n\ncalcLastArrivalTimeForEachFloor ::\n IntType -> [(IntType, IntType)] -> Array IntType IntType\n -- floor -> [(floor, time)] -> Array floor time\ncalcLastArrivalTimeForEachFloor s = accumArray max 0 (0,s)\n\ncalcTotalTime :: IntType -> Array IntType IntType -> IntType\n -- floor -> Array floor time -> time\ncalcTotalTime s arr = foldl' func (t0 - spf) lst\n where\n t0 = 0 -- start time\n spf = 1 -- seconds per floor\n lst = map (arr!) . takeWhile (>= 0) . iterate (subtract 1) $ s\n -- func prev_total last_passenger_arrival = ...\n func prev = max (prev + spf)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Ratio\nimport Data.List\n\n\n\n\n\nmain= do\n\t[n,s]<-map read. words <$> getLine ::IO [Int]\n\tq<- map (map read) .map words.lines <$> getContents ::IO [[Int]]\n\tprint $ max s $ maximum $ map (\\[a,b]-> a+b) q\n\t \n"}, {"source_code": "main = do\n [n, s] <- getLine >>= return. map read. words\n a <- getContents >>= return. maximum. map (sum. map read. words). lines\n print. max s $ a\n"}], "negative_code": [{"source_code": "\n-- Michael V. Antosha \n-- 2015\n-- http://mivael.in.ua\n\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.List (foldl')\n\ntype IntType = Int\n\nmain :: IO ()\nmain = do\n in_str <- getContents\n putStrLn . solve $ in_str\n\nsolve :: String -> String\nsolve = show . solveInt . map read . words\n\nsolveInt :: [IntType] -> IntType -- [num] -> time\nsolveInt (n:s:arrivals) = calculate . parse $ arrivals\n where\n parse = verifyLength n . makePairs\n makePairs = makePairsRev -- order is not important\n calculate = calcTotalTime s . calcArrivals s\n calcArrivals = calcLastArrivalTimeForEachFloor\nsolveInt _ = undefined -- not enough input data\n\nmakePairsRev :: [a] -> [(a, a)]\nmakePairsRev = mp [] where\n mp lst [] = lst\n mp lst (f:t:rest) = mp ((f,t):lst) rest\n mp _ (_:[]) = undefined -- odd number of integers\n\nverifyLength :: IntType -> [a] -> [a] -- length -> [a] -> [a]\nverifyLength list_length list_of_pairs\n | list_length >= 0\n = vl list_length list_of_pairs list_of_pairs\n where\n vl 0 [] list = list\n vl 0 _ _ = undefined\n vl len (_:xs) list = vl (len - 1) xs list\n vl _ [] _ = undefined -- check failed (wrong 'len')\n\ncalcLastArrivalTimeForEachFloor ::\n IntType -> [(IntType, IntType)] -> Array IntType IntType\n -- floor -> [(floor, time)] -> Array floor time\ncalcLastArrivalTimeForEachFloor s = accumArray max 0 (0,s)\n\ncalcTotalTime :: IntType -> Array IntType IntType -> IntType\n -- floor -> Array floor time -> time\ncalcTotalTime s arr = foldl' func 0 lst\n where\n lst = map (arr!) . takeWhile (>= 0) . iterate (subtract 1) $ s\n func x y = max (x+1) y\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Ratio\nimport Data.List\n\n\n\n\n\nmain= do\n\tgetLine \n\ts<- map (map read) .map words.lines <$> getContents ::IO [[Int]]\n\tprint $ maximum $ map (\\[a,b]-> a+b) s\n\t \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Ratio\nimport Data.List\n\n\n\n\n\nmain= do\n\ts<- map (map read) .map words.lines <$> getContents ::IO [[Int]]\n\tprint $ maximum $ map (\\[a,b]-> a+b) s\n\t \n"}], "src_uid": "5c12573b3964ee30af0349c11c0ced3b"} {"source_code": "module Main where\n\nimport Control.Monad\n\nisPrime :: Int -> Bool\nisPrime x =\n not $ any (\\y -> x `mod` y == 0) $ takeWhile (\\y -> y * y <= x) [2 ..]\n\nfindGoodPrime :: Int -> Int\nfindGoodPrime n =\n head $ filter (\\m -> isPrime m && not (isPrime (m - n + 1))) [n ..]\n\nprimeArray :: Int -> [Int]\nprimeArray n = replicate (n - 1) 1 ++ [m - n + 1]\n where m = findGoodPrime n\n\nshift :: [a] -> [a]\nshift [] = []\nshift (x:xs) = xs ++ [x]\n\ngenerateSquare :: Int -> [Int] -> [[Int]]\ngenerateSquare n xs = take n $ iterate shift xs\n\nsolveCase :: Int -> [[Int]]\nsolveCase n = generateSquare n $ primeArray n\n\nreadCase :: IO Int\nreadCase = read <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n ns <- replicateM t readCase\n putStr $ unlines $ map (unwords . map show) $ concatMap solveCase ns\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nrots :: [t] -> [[t]]\nrots li = [q ++ p | (p, q) <- tail $ zip (inits li) (tails li)]\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n let q = [1,1] ++ replicate (n-2) 0 :: [Int]\n forM_ (rots q) $ \\a -> putStrLn . unwords $ map show a\n"}], "negative_code": [], "src_uid": "df6ee0d8bb25dc2040adf1f115f4a83b"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n a <- readInts\n let\n rems :: UArray Int Int\n rems = accumArray (\\v _ -> v+1) 0 (0, 2) $ [(rem ai 3, ()) | ai <- a]\n tar = div n 3\n cost x y = max 0 (min (rems ! x - tar) (tar - rems ! y)) * mod (y - x) 3\n -- This works because there is no room for a two-sink, two-source situation\n putInts [sum $ liftM2 cost [0..2] [0..2]]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\n\r\npowerTwo :: Integer -> Integer -> Integer\r\npowerTwo x y | 2 * x >= y = 0\r\npowerTwo x y | 2 * x < y = 1+powerTwo (2*x) y\r\n\r\nresult list = aux c0 c1 c2 where\r\n\tc0 = sum [1 | x <- list, mod x 3 == 0]\r\n\tc1 = sum [1 | x <- list, mod x 3 == 1]\r\n\tc2 = sum [1 | x <- list, mod x 3 == 2]\r\n\tn = c0 + c1 + c2\r\n\taux x y z \r\n\t\t| x > y = 1 + aux (x-1) (y+1) z\r\n\t\t| y > z = 1 + aux x (y-1) (z+1)\r\n\t\t| z > x = 1 + aux (x+1) y (z-1)\r\n\t\t| otherwise = 0\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ result a \r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "-- import Debug.Trace\r\n\r\ntype InType = [Int]\r\ntype OutType = Int\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ncalc :: Int -> Int -> Int -> Int\r\ncalc c0 c1 c2\r\n | c0 == c1 && c1 == c2 = 0\r\n | c1 + 1 < c0 = let (op, c1', c0') = go c1 c0 in op + calc c0' c1' c2\r\n | c2 + 1 < c1 = let (op, c2', c1') = go c2 c1 in op + calc c0 c1' c2'\r\n | c0 + 1 < c2 = let (op, c0', c2') = go c0 c2 in op + calc c0' c1 c2'\r\n | otherwise = maximum [c0, c1, c2] - minimum [c0, c1,c2]\r\n where go x y = ( (y - x) `div` 2\r\n , (y + x) `div` 2\r\n , (y + x + 1) `div` 2 )\r\n\r\nsolve :: InType -> OutType\r\nsolve a = {- trace (unwords [show c0, show c1, show c2]) $ -} calc c0 c1 c2\r\n where [c0, c1, c2] = foldr (\\x xs -> up (x `mod` 3) xs) [0,0,0] a\r\n up 0 [x, y, z] = [x + 1, y, z]\r\n up 1 [x, y, z] = [x, y + 1, z]\r\n up 2 [x, y, z] = [x, y, z + 1]\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, t] = toArr t\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines)\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n \nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n replicateM_ n action\n \naction = getLine >> getLine >>= print . calc . foldr counter (0, 0, 0) . map ((`mod` 3) . (read :: String -> Int)) . words\n where\n counter 0 (a,b,c) = (a+1,b,c)\n counter 1 (a,b,c) = (a,b+1,c)\n counter 2 (a,b,c) = (a,b,c+1)\n\ncalc :: (Int, Int, Int) -> Int\ncalc (a,b,c)\n | a >= d && c <= d = move (a,b,c)\n | b >= d && a <= d = move (b,c,a)\n | c >= d && b <= d = move (c,a,b)\n where\n d = (a+b+c) `div` 3\n-- move :: (Int, Int, Int) -> ((Int, Int, Int), Int)\n move (q,w,e) = (q-d) + (d-e)"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n as <- popInts\n return $ bshow $ solve n as\n\n\nuncurry3 f (a, b, c) = f a b c\n\n\nsolve n as = (uncurry3 rot) $ count $ map (`rem` 3) as\n where\n m = n `quot` 3\n\n count as = count' as 0 0 0\n\n count' [] p q r = (p, q, r)\n count' (a : as) p q r = case a of\n 0 -> count' as (p + 1) q r\n 1 -> count' as p (q + 1) r\n 2 -> count' as p q (r + 1)\n\n rot a b c | a == b && b == c = 0\n | otherwise = let mx = maximum [a, b, c] in\n case (mx == a, mx == b) of\n (True, _) -> rot' a b c\n (_, True) -> rot' b c a\n _ -> rot' c a b\n\n rot' a b c = let d = a - m in\n d + rot (a - d) (b + d) c\n"}, {"source_code": "distribute :: [Integer] -> Integer -> Integer\ndistribute counts@(c:rest) extra\n | all (== c) counts = 0\n | otherwise = moveCost + distribute newCounts newExtra\n where wanted = (sum counts + extra) `div` 3\n leftHere = max 0 (min (wanted - c) extra)\n takenFromHere = max 0 (c - wanted)\n moveCost = extra - leftHere + takenFromHere\n newCounts = rest ++ [c + leftHere - takenFromHere]\n newExtra = extra - leftHere + takenFromHere\n\nsolveTest :: [Integer] -> Integer\nsolveTest xs = distribute counts 0\n where counts = [toInteger $ length $ multiples x | x <- [0..2]]\n multiples m = filter ((== m) . (`mod` 3)) xs\n\nsolve :: String -> String\nsolve = unlines . map solveStringTest . odds . drop 1 . lines\n where odds = map snd . filter (odd . fst) . zip [0..]\n solveStringTest = show . solveTest . map read . words\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "import Control.Monad\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Int]\nreadInts = readArray\n\nreadInt :: IO Int\nreadInt = readLn\n\ncount :: (a -> Bool) -> [a] -> Int\ncount _ [] = 0\ncount f (x:xs) = (if f x then 1 else 0) + count f xs\n\nhist :: [Int] -> [Int]\nhist a = [count (\\j -> j `mod` 3 == i) a | i <- [0..2]]\n\nrec :: [Int] -> Int -> Int\nrec (0:0:0:xs) a = 0\nrec (x:xs) a = let t = max 0 (a + x) in t + rec (xs ++ [a + x - t]) t\n\nsolve :: [Int] -> Int\nsolve a = let want = (length a) `div` 3 in rec (map (\\j -> j - want) (hist a)) 0\n\nmain :: IO ()\nmain = readInt >>= flip replicateM_ (readInt >> fmap solve readInts >>= print)\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\n\r\npowerTwo :: Integer -> Integer -> Integer\r\npowerTwo x y | 2 * x >= y = 0\r\npowerTwo x y | 2 * x < y = 1+powerTwo (2*x) y\r\n\r\nresult list = aux3 c0 c1 c2 where\r\n\tc0 = sum [1 | x <- list, mod x 3 == 0]\r\n\tc1 = sum [1 | x <- list, mod x 3 == 1]\r\n\tc2 = sum [1 | x <- list, mod x 3 == 2]\r\n\tn = c0 + c1 + c2\r\n\taux3 x y z \r\n\t\t| x >= y && x >= z = x - (div n 3) + (y + x - (div n 3)) - div n 3\r\n\t\t| y >= z && y >= x = y - (div n 3) + (z + y - (div n 3)) - div n 3\r\n\t\t| z >= x && z >= y = z - (div n 3) + (x + z - (div n 3)) - div n 3\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ result a \r\n\t\tloop $ t - 1\r\n\tloop t"}], "src_uid": "e0de8a6441614d1e41a53223b5fa576b"} {"source_code": "read' :: String -> (Int, Int)\nread' str = let [u, v] = map read (words str) in (u, v)\nsolve :: [(Int, Int)] -> Double\nsolve ((_, p):xs) = 2000 * sum (zipWith (\\x y -> x + y - x * y) ps $ pps ++ [pp]) \n where ps@(pp:pps) = map prob xs\n prob (x, y) = fromIntegral (y `div` p - x `div` p + fromEnum (x `mod` p == 0)) / fromIntegral (y - x + 1)\nmain = putStrLn . show . solve . map read' . lines =<< getContents", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [n, p] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n [l, r] <- fmap (map read . words) getLine\n return (l, r)\n print $ solve p inp\n\n\nsolve :: Integer -> [(Integer, Integer)] -> Double\nsolve p inp = sum ints + exp (head inp) (last inp)\n where\n ints = zipWith exp inp (tail inp)\n exp (l1, r1) (l1', r1') = numer*2000/fromIntegral (len1*len2)\n where\n numer :: Double\n numer = fromIntegral (num1*len2 + num2*len1 - num1*num2)\n len1 = r1 - l1 + 1\n len2 = r1' - l1' + 1\n num1 = (r1 `div` p) - (l1-1)`div`p\n num2 = (r1' `div` p) - (l1'-1)`div`p\n\ninp1 = [(1,2), (420, 421), (420420, 420421)]\ninp2 :: [(Int, Int)]\ninp2 = [(1,4), (2,3), (11,14)]\n\n"}, {"source_code": "import Control.Monad;\n\nmain = do\n (n:p:[]) <- getLine >>= return.(map (toInteger.read)).words\n list <- replicateM (fromInteger n) (getLine>>=return.(\\[a,b]->(a,b)).(map (toInteger.read)).words)\n putStrLn $ show $ solve list p\n\nadj x = (last x, head x):(zip x (tail x))\n\nsolve :: [(Integer, Integer)] -> Integer -> Double\nsolve x p = sum $ map (\\a -> (pairChance a p)*2000) (adj x)\n\npairChance :: ((Integer, Integer), (Integer, Integer)) -> Integer -> Double\npairChance ((a,b), (c,d)) p = 1-(1-p1)*(1-p2)\n where\n p1 = singleChance (a,b) p\n p2 = singleChance (c,d) p\n\nsingleChance :: (Integer, Integer) -> Integer -> Double\nsingleChance (from, to) p = (fromIntegral $ (to`div`p) - ((from-1)`div`p)) / (fromIntegral $ to - from + 1)"}, {"source_code": "import Control.Monad;\n\nmain = do\n (n:p:[]) <- getLine >>= return.(map (fromIntegral.read)).words\n list <- replicateM n (getLine >>= return.(\\[a,b]->(a,b)).(map (fromIntegral.read)).words)\n putStrLn $ show $ solve list p\n\nsolve x p = sum $ map (\\a -> (pairChance a p)*2000) (adj x)\n where adj x = (last x, head x):(zip x (tail x))\n\npairChance ((a,b), (c,d)) p = 1-(1-p1)*(1-p2)\n where\n p1 = singleChance (a,b) p\n p2 = singleChance (c,d) p\n\nsingleChance (from, to) p = (fromIntegral $ (to`div`p) - ((from-1)`div`p)) / (fromIntegral $ to - from + 1)"}, {"source_code": "read' :: String -> (Int, Int)\nread' str = let [u, v] = map read (words str) in (u, v)\ncyclic :: [a] -> [a]\ncyclic (x:xs) = xs ++ [x]\n\nprob :: Int -> (Int, Int) -> Double\nprob p (x, y) = fromIntegral r / fromIntegral d \n where d = y - x + 1\n r = y `div` p - x `div` p + fromEnum (x `mod` p == 0)\n\nsolve :: [(Int, Int)] -> Double\nsolve ((_, p):xs) = 2000 * sum (zipWith union ps (cyclic ps))\n where ps = map (prob p) xs\n union x y = x + y - x * y \n\nmain :: IO()\nmain = putStrLn . show . solve . map read' . lines =<< getContents"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [n, p] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n [l, r] <- fmap (map read . words) getLine\n return (l, r)\n print $ solve p inp\n\n\nsolve :: Int -> [(Int, Int)] -> Double\nsolve p inp = sum leftInts + sum rightInts + exp (head inp) (last inp)\n where\n leftInts = zipWith exp inp (tail inp)\n rightInts = zipWith exp (last inp:inp) (inp)\n exp (l1, r1) (l1', r1') = numer*1000/fromIntegral (len1*len2)\n where\n numer :: Double\n numer = fromIntegral (num1*len2 + num2*len1 - num1*num2)\n len1 = r1 - l1 + 1\n len2 = r1' - l1' + 1\n num1 = (r1 `div` p) - (l1-1)`div`p\n num2 = (r1' `div` p) - (l1'-1)`div`p\n\ninp1 = [(1,2), (420, 421), (420420, 420421)]\ninp2 :: [(Int, Int)]\ninp2 = [(1,4), (2,3), (11,14)]\n\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [n, p] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n [l, r] <- fmap (map read . words) getLine\n return (l, r)\n print $ solve p inp\n\n\nsolve :: Int -> [(Int, Int)] -> Double\nsolve p inp = sum ints + exp (head inp) (last inp)\n where\n ints = zipWith exp inp (tail inp)\n exp (l1, r1) (l1', r1') = numer*2000/fromIntegral (len1*len2)\n where\n numer :: Double\n numer = fromIntegral (num1*len2 + num2*len1 - num1*num2)\n len1 = r1 - l1 + 1\n len2 = r1' - l1' + 1\n num1 = (r1 `div` p) - (l1-1)`div`p\n num2 = (r1' `div` p) - (l1'-1)`div`p\n\ninp1 = [(1,2), (420, 421), (420420, 420421)]\ninp2 :: [(Int, Int)]\ninp2 = [(1,4), (2,3), (11,14)]\n\n"}, {"source_code": "read' :: String -> (Int, Int)\nread' str = let [u, v] = map read (words str) in (u, v)\ncyclic :: [a] -> [a]\ncyclic (x:xs) = xs ++ [x]\ndivisible :: Integral a => a -> a -> Bool\ndivisible x p = mod x p == 0\n\nprob :: Int -> (Int, Int) -> Double\nprob p (x, y) = fromIntegral pos / fromIntegral (diff + 1) \n where diff = y - x\n pos = fromEnum (divisible x p || divisible y p) + div diff p\n\nsolve :: [(Int, Int)] -> Double\nsolve ((_, p):xs) = 2000 * sum (zipWith union ps (cyclic ps))\n where ps = map (prob p) xs\n union x y = x + y - x * y \n\nmain :: IO()\nmain = putStrLn . show . solve . map read' . lines =<< getContents"}], "src_uid": "5aad0a82748d931338140ae81fed301d"} {"source_code": "import Data.List\n\nread_int :: String -> Int\nread_int = read\n\nsolve :: [Int] -> Int\nsolve xs =\n let n = length xs\n s = sum xs\n q = s `quot` n\n r = s `mod` n\n (y,z) = (splitAt (n-r)) . sort $ xs\n in ((sum . (map (\\x -> abs $ x-q)) $ y) + (sum . (map (\\x -> abs $ x-q-1)) $ z)) `quot` 2\n\nmain = interact $ show. solve . (map read_int) . words . (!! 1) . lines\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Tuple\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport Data.Word\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- U.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getContents\n print $ solve n $ U.map fromIntegral xs\n\nsolve :: Int -> U.Vector Int64 -> Int64\nsolve n xs = div (U.sum (U.map (abs.subtract q) ys) + U.sum (U.map (abs.subtract(q+1)) zs)) 2\n where\n s = U.sum xs\n (q, r) = divMod s (fromIntegral n)\n (ys, zs) = U.splitAt (n-fromIntegral r) $ radixSort32 xs\n\nradixSort32 :: U.Vector Int64 -> U.Vector Int64\nradixSort32 v = foldl' step v [0, 16]\n where\n mask k x = fromIntegral $ unsafeShiftR x k .&. 0xffff\n step v k = U.create $ do\n pref <- U.unsafeThaw\n . U.prescanl' (+) 0\n . U.unsafeAccumulate (+) (U.replicate 0x10000 0)\n $ U.map ((,1) . mask k) v\n res <- UM.unsafeNew $ U.length v\n U.forM_ v $ \\x -> do\n let !masked = mask k x\n i <- UM.unsafeRead pref masked\n UM.unsafeWrite pref masked $ i + 1\n UM.unsafeWrite res i x\n return res\n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n [n] <- (map read . words) `fmap` getLine\n ms <- (sort . map read . words) `fmap` getLine\n\n let\n s = sum ms\n b = s `div` n\n k = s `mod` n\n as = replicate (n - k) b ++ replicate k (b + 1)\n\n ss = sum . map abs $ zipWith (-) ms as\n\n print $ ss `div` 2\n"}, {"source_code": "import Data.Ord\n--import Control.Lens.At\n--import Control.Lens.Operators\nimport Control.Applicative ((<$>))\nimport Test.QuickCheck\nimport Data.List\n\nsolve :: Int -> [Int] -> Int\nsolve n m =\n max smaller_iters bigger_iters\n where\n base = (sum m) `div` n\n smaller = filter (\\x -> x < base) m\n bigger = filter (\\x -> x > base+1) m\n smaller_iters = sum $ map (base -) $ smaller\n bigger_iters = sum $ map (\\x -> x - (base+1)) $ bigger\n\n{-\nbruteForce :: [Int] -> Int -> Int\nbruteForce x n\n | maxVal - minVal > 1 = bruteForce x' (n+1)\n | otherwise = n\n where\n (maxVal, maxIdx) = maximumBy (comparing fst) $ zip x [0..]\n (minVal, minIdx) = minimumBy (comparing fst) $ zip x [0..]\n x' = x & ix maxIdx .~ (maxVal - 1) & ix minIdx .~ (minVal + 1)\n\nrunChecks :: IO ()\nrunChecks =\n let\n genVec = sized $ \\n -> listOf1 $ choose (0, n)\n prop_num_iter x = solve (length x) x == bruteForce x 0\n in quickCheck $ forAll genVec prop_num_iter\n-}\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n m <- map read . words <$> getLine\n putStrLn $ show $ solve n m\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nsolve :: Int -> [Int] -> Int\nsolve n m =\n sum $ map (base -) $ smaller\n where\n base = (sum m) `div` n\n smaller = filter (\\x -> x < base) m\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n m <- map read . words <$> getLine\n putStrLn $ show $ solve n m\n"}, {"source_code": "import Data.List\n\nread_int :: String -> Int\nread_int = read\n\nsolve :: [Int] -> Int\nsolve xs =\n let n = length xs\n s = sum xs\n q = s `quot` n\n r = s `mod` n\n (y,z) = (splitAt r) . sort $ xs\n in if r == 0 then sum . (map (\\x -> abs $ x-q)) $ xs\n else ((sum . (map (\\x -> abs $ x-q)) $ y) + (sum . (map (\\x -> abs $ x-q-1)) $ z))`quot` 2\n\nmain = interact $ show. solve . (map read_int) . words . (!! 1) . lines\n"}, {"source_code": "import Data.List\n\nread_int :: String -> Int\nread_int = read\n\nsolve :: [Int] -> Int\nsolve xs =\n let n = length xs\n s = sum xs\n q = s `quot` n\n r = s `mod` n\n sxs = sort xs\n (y,z) = splitAt r sxs\n in if r == 0 then (sum . (map (\\x -> abs $ x-q)) $ sxs) `quot` 2\n else ((sum . (map (\\x -> abs $ x-q)) $ y) + (sum . (map (\\x -> abs $ x-q-1)) $ z)) `quot` 2\n\nmain = interact $ show. solve . (map read_int) . words . (!! 1) . lines\n"}, {"source_code": "import Data.List\n\nread_int :: String -> Int\nread_int = read\n\nsolve :: [Int] -> Int\nsolve xs =\n let n = length xs\n s = sum xs\n q = s `quot` n\n r = s `mod` n\n (y,z) = (splitAt r) . sort $ xs\n in if r == 0 then (sum . (map (\\x -> abs $ x-q)) $ xs) `quot` 2\n else ((sum . (map (\\x -> abs $ x-q)) $ y) + (sum . (map (\\x -> abs $ x-q-1)) $ z)) `quot` 2\n\nmain = interact $ show. solve . (map read_int) . words . (!! 1) . lines\n"}, {"source_code": "import Data.List\n\nread_int :: String -> Int\nread_int = read\n\nsolve :: [Int] -> Int\nsolve xs =\n let n = length xs\n s = sum xs\n q = s `quot` n\n r = s `mod` n\n (y,z) = (splitAt r) . sort $ xs\n in ((sum . (map (\\x -> abs $ x-q)) $ y) + (sum . (map (\\x -> abs $ x-q-1)) $ z))`quot` 2\n\nmain = interact $ show. solve . (map read_int) . words . (!! 1) . lines\n"}], "src_uid": "c0c29565e465840103a4af884f951cda"} {"source_code": "import Data.Array\nimport Data.List\nimport Control.Arrow\nmain = do\n getLine\n ns <- fmap (map (head &&& genericLength) . group . sort . map read . words) getLine\n print $ solve ns\nsolve ns = go 0 ns where\n s = length ns\n go _ [] = 0\n go _ [(n,c)] = n*c\n go i ((n,c):(m,_):_)\n | m == n + 1 = maximum [\n go' (i+1)\n , n*c + go' (i+2)\n , n*c + go' (i+3)\n ]\n | otherwise = go' (i+1) + n*c\n go' = let a = listArray (0,s+2) $ zipWith go [0..] (tails ns) ++ [0,0]\n in \\i -> a ! i\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n getLine\n nums <- getLine\n print $ max_score $ map read $ words nums\n\nadd :: (a -> a -> Bool) -> a -> [[a]] -> [[a]]\nadd eq x ((y:ys):others) = if eq x y then (x:y:ys):others else [x]:(y:ys):others\nadd eq x [] = [[x]]\n\nadjacentGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]\nadjacentGroupBy eq xs = foldr (add eq) [] xs\n\nmax_first :: [Integer] -> Integer\nmax_first (x:y:_) = max x y\nmax_first (x:_) = x\nmax_first [] = 0\n\nsafe_tail :: [a] -> [a]\nsafe_tail (_:xs) = xs\nsafe_tail [] = []\n\n\ndp_step :: [Integer] -> (Integer, Integer) -> [Integer]\ndp_step acc x = ((fst x * snd x) + (max_first $ safe_tail acc)):acc\n\ngroup_score :: [(Integer, Integer)] -> Integer\ngroup_score group =\n max_first dp\n where dp = foldl dp_step [] group\n\nmax_score :: [Integer] -> Integer\nmax_score nums =\n let\n pairs = map (\\xs -> (head xs, toInteger $ length xs)) $ groupBy (==) $ sort nums\n groups = adjacentGroupBy (\\x y -> (abs (fst x - fst y)) <= 1) pairs\n in\n sum $ map group_score groups\n"}, {"source_code": "import Data.List\nimport Control.Arrow\nmain=getContents>>=print.g.map read.tail.words\ng=uncurry max.snd.foldl' f(0,(0,0)).map(head&&&genericLength).group.sort\n where f(a,(b,c))(d,e)|a+10=(d,(max(d*e+c)b,b))\n"}, {"source_code": "import Data.List (foldl', genericLength, group, sort)\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = uncurry max . snd . foldl' f (0, (0, 0)) . map (head &&& genericLength) . group . sort\n where f (a, (b, c)) (d, e) | a + 1 < d = (d, (max (d * e + b) (max b c), max b c))\n | otherwise = (d, (max (d * e + c) b, b))\n"}, {"source_code": "import Data.List (foldl', genericLength, group, sort)\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = uncurry max . snd . foldl' f (0, (0, 0)) . map (head &&& genericLength) . group . sort\n where f (a, (b, c)) (d, e) | a + 2 < d = (d, (d * e + max b c, max b c))\n | a + 1 < d = (d, (max (d * e + b) (max b c), max b c))\n | otherwise = (d, (max (d * e + c) b, b))\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/455/A\n\nimport Data.Int\nimport Data.Array\n\nsolve1 :: Array Int Int64 -> Int -> Int64\nsolve1 a = (r !)\n where r = listArray (0, 100000) (0 : a ! 1 : map f [2..100000])\n f i = max (r ! (i - 1)) (a ! i + r ! (i - 2))\n\n(+^) :: Int64 -> Int -> Int64\na +^ b = a + fromIntegral b\n\nsolve :: [Int] -> Int64\nsolve a = solve1 cnt 100000\n where cnt = accumArray (+^) 0 (1, 100000) (zip a a)\n\nmain :: IO ()\nmain = do\n getLine\n nums <- fmap read . words <$> getLine :: IO [Int]\n print $ solve nums\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\n\n\nxx=100000\n\nmain= do\n\tgetLine \n\ta<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine::IO [Integer]\n\tlet b= accumArray (+) 0 (1,xx) [(i,1)|i<-a]:: Array Integer Integer\n\tlet c =array (0,xx) ((0,0):(1,(b!1)):[(i,max (c!(i-1)) ((c!(i-2))+i*(b!i)))|i<-[2..xx]]) :: Array Integer Integer\n\tprint $ c!xx\n\n\t "}, {"source_code": "import Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Control.Arrow ((&&&))\nimport Data.List (group, sort)\nimport Data.Array\n\ninput :: IO [Int]\ninput = getLine >> fmap (map read . words) getLine\n\ntoAssocs :: [Int] -> [(Int, Integer)]\ntoAssocs = map (head &&& fromIntegral . length) . group . sort\n\nsolve :: [Int] -- List of numbers\n -> Integer -- Max score\nsolve xs = m!100000\n where\n cs = Map.fromList . toAssocs $ xs\n count x = maybe 0 id $ Map.lookup x cs\n m = array (0, 100000) $\n [(0, 0), (1, count 1)] ++\n [(i, f i) | i <- [2..100000]]\n f n = max takeN ignoreN\n where takeN = m!(n-1)\n ignoreN = m!(n-2) + (fromIntegral n * count n)\n\noutput :: Integer -> IO ()\noutput = putStrLn . show\n\nmain :: IO ()\nmain = output . solve =<< input"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (sort, group)\n\nprocess :: [Int64] -> Int64\nprocess = uncurry max . snd . foldr g (maxBound,(0,0)) . map f . group . sort\n where\n f xs = (head xs, sum xs)\n g (x,p) (y,(ay,aprev))\n | y-x == 1 = (x,(p+aprev,amax))\n | otherwise = (x,(p+amax,amax))\n where amax = max ay aprev\n\nreadInt :: String -> Int64\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.List\nimport\u00a0Data.IntMap.Lazy hiding (foldl)\nimport Control.Arrow\nimport Data.Int\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\nsolution :: IntMap Int64 -> Int64\nsolution mp = snd $ foldl recIncr (0, 0) [1..maxKey]\n where \n maxKey = fst $ findMax mp \n\n recIncr :: (Int64, Int64) -> Int -> (Int64, Int64)\n recIncr (res1, res2) ind3 =\n let res3 = max res2 (res1 + lkp ind3 * fromIntegral ind3) in (res2, res3)\n \n lkp :: Int -> Int64\n lkp n = findWithDefault 0 n mp \n\nparseInput :: BS.ByteString -> IntMap Int64\nparseInput = fromList . fmap (head &&& genericLength) . group . sort \n . fmap (fst . fromJust . BS.readInt) . tail . BS.words\n\nsolve :: BS.ByteString -> BS.ByteString\nsolve = toLazyByteString . int64Dec . solution . parseInput\n\nmain :: IO ()\nmain = BS.interact solve"}, {"source_code": "import Data.Int\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.Array.IArray\n\nsolution :: Array Int Int64 -> Int64\nsolution mp = snd $ foldl accumulator (0, 0) [1..upperBound]\n where \n upperBound = snd $ bounds mp\n\n accumulator :: (Int64, Int64) -> Int -> (Int64, Int64)\n accumulator (res1, res2) ind3 =\n let res3 = max res2 (res1 + (mp ! ind3) * fromIntegral ind3) \n in (res2, res3)\n\nparseInput :: BS.ByteString -> Array Int Int64\nparseInput = hist (0, 100000) . fmap (fst . fromJust . BS.readInt) . tail . BS.words\n\nhist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b\nhist bnds is = accumArray (+) 0 bnds [(i, 1) | i<-is, inRange bnds i] \n\nsolve :: BS.ByteString -> BS.ByteString\nsolve = toLazyByteString . int64Dec . solution . parseInput\n\nmain :: IO ()\nmain = BS.interact solve"}, {"source_code": "import Data.List\nimport\u00a0Data.IntMap.Lazy hiding (foldl)\nimport Control.Arrow\nimport Data.Int\n\nsolution :: IntMap Int64 -> Int64\nsolution mp = snd $ foldl recIncr (0, 0) [1..maxKey]\n where \n maxKey = fromIntegral $ fst $ findMax mp \n\n recIncr :: (Int64, Int64) -> Int64 -> (Int64, Int64)\n recIncr (res1, res2) ind3 =\n let res3 = max res2 (res1 + lkp ind3 * ind3) in (res2, res3)\n \n lkp :: Int64 -> Int64\n lkp n = fromIntegral $ findWithDefault 0 (fromIntegral n) mp \n\nparseInput :: String -> IntMap Int64\nparseInput = fromList . fmap (head &&& (fromIntegral.length)) . group . sort \n . fmap read . tail . words\n\nsolve :: String -> String\nsolve = show . solution . parseInput\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words, mconcat, mappend)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Builder (toLazyByteString, int64Dec, char8)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs _lenA listA = f\n where\n f = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum maxNum\n f _ _ = maxDP (maxNum-1)\n numsum num = n * i where\n n = fromIntegral num :: ASum\n i = fromIntegral $ countByNum num\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -std=c++0x -pedantic -Werror $+\n./hs.exec: my-copied.hs\n\tghc -Wall -Werror -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words, mconcat, mappend)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Builder (toLazyByteString, int64Dec, char8)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.HashMap.Lazy (HashMap)\nimport qualified Data.HashMap.Lazy as HM\n\nimport Data.Array (Ix, (!), listArray, range)\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt n rest\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype Freqs = HashMap ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs (maximum listA)\n where\n freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]\n incrSec _new = (+1)\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = maxDP maxA where\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum = flip (HM.lookupDefault 0) freqs\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum maxNum\n f _ _ = maxDP (maxNum-1)\n numsum num = n * i where\n n = fromIntegral num :: ASum\n i = fromIntegral $ countByNum num\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | time ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -std=c++0x -pedantic -Werror $+\n./hs.exec: my-copied.hs\n\tghc -Wall -Werror -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n-- Trying to create a suitable effective IO template to use in\n-- competitive programming. Code brevity is secondary this time.\n-- First priority is fast adaptability of the template for specific\n-- problems during contest.\n--\n\nimport qualified Prelude as P\nimport Prelude (($), (.), (-), (+), (*),\n otherwise, Bool(True), Bool(False), error, const, undefined)\nimport System.IO (IO)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport qualified Data.ByteString.Lazy.Char8 as BL8\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\nimport Data.Maybe\nimport Data.Functor\nimport Data.Eq\nimport Data.Ord\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\n\nmain :: IO ()\nmain = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases\n\ntype ANum = Int64 -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\ntype Case = [Int64]\ntype Result = ASum\n\nshowResult :: Result -> BL8.ByteString\nshowResult = BB.toLazyByteString . int64Dec\n\nreadCases :: BL8.ByteString -> [Case]\nreadCases = L.unfoldr readCase\n\ndropSpaces :: BL8.ByteString -> BL8.ByteString\ndropSpaces = BL8.dropWhile isSpace\n\nreadInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)\nreadInt64 bs = conv <$> BL8.readInteger (dropSpaces bs) where\n conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)\n\n-- 'readN n f i s' is like 'f s' but reads n consequential elements\n-- from s, not just one.\n-- 'i s' == True iff s is an empty string.\n-- 'readN 0 f i s' is Nothing if (i s == True),\n-- otherwise, 'readN n f i s' is an error if (i s == True).\n-- It is an error if it is impossible to read n elements form s.\nreadN :: P.Integral n =>\n n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)\nreadN cnt readFunc nullFunc str = rn2 cnt str where\n rn2 c s = rn c s (nullFunc s)\n rn 0 _ True = Nothing\n rn 0 s False = Just ([], s)\n rn _ _ True = error \"Unexpected end of input.\"\n rn n s False = Just (firstElem : otherElems, strRest2) where\n (firstElem, strRest) = fromJust (readFunc s)\n (otherElems, strRest2) = fromJust (rn2 (n-1) strRest)\n\nreadCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)\nreadCase bsWithSpaces\n | BL8.null bs = Nothing\n | otherwise = readN n readInt64 BL8.null bsRest\n where\n bs = dropSpaces bsWithSpaces\n (n, bsRest) = fromJust (readInt64 bs)\n\nsolveCase :: Case -> Result\nsolveCase = solveFreqs . toFreqs\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = L.maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = prevDP + thisSum where\n (iprev, thisSum) = param numChoice where\n param Removed = (i-1, 0)\n param Chosen = (i-2, (freqs ! i) * i)\n prevDP = r $ freqs ! iprev where\n r 0 = get Removed\n r _ = max (get Removed) (get Chosen)\n get choicePrev = dpMemo ! (iprev, choicePrev)\n dpMemo = listArray memoBounds [dp n c\n | (n, c) <- range memoBounds]\n where\n memoBounds = ((-1, Chosen),\n (maxA, Removed))\n dp (-1) _ = 0\n dp 0 _ = 0\n dp maxNum numChoice = calcDP maxNum numChoice\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\ttime ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt\n\t#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Lazy.Builder (toLazyByteString, char8)\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.HashMap.Lazy (HashMap)\nimport qualified Data.HashMap.Lazy as HM\n\nimport Data.Array (Ix, (!), listArray, accumArray, range)\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\nmytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\nmytrace _s = id\n\ntype MyNum = Int64\ntype ANum = MyNum -- elements of a[]\ntype ASum = MyNum -- sum of ANum values\n-- type ANum = Int64 -- elements of a[]\n-- type ASum = Int64 -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . mytrace \"input nums\" . parseIntsBS\n where\n parseIntsBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = fromIntegral num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = mytrace \"input nums\" $ []\n solveMany (n:rest) = (solveFreqs . toFreqs . mytrace \"this case\" $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt (fromIntegral n) rest\n\ntype Freqs = HashMap ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs (maximum listA)\n where\n freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]\n incrSec _new = (+1)\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (\n Show, -- debug\n Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (\n Show, -- debug\n Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = f numChoice where\n f Chosen = maxDP (i-2) + (i * countByNum i)\n f Removed = maxDP (i-1)\n maxDP n = max (memo Chosen) (memo Removed) where\n memo choice = dpMemo ! mytrace \"dpMemo ind\" (n, choice, presence)\n presence\n | (cnt > 0) = Present\n | otherwise = Absent\n cnt = countByNum n\n\n -- countByNum = flip (HM.lookupDefault 0) freqs\n countByNum = (!) cbm . mytrace \"countByNum arg\"\n cbm = accumArray accfunc 0 (mytrace \"cbm bounds\" $ (-1,maxA)) (HM.toList freqs) where\n accfunc 0 = id\n accfunc _ = error \"HashMap with duplicates?\"\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = calcDP maxNum Chosen\n f _ _ = calcDP maxNum Removed\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray (mytrace \"dpMemo bounds\" memoBounds) [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } | time ./a.out\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } | time ./hs.exec +RTS -p -K100000000\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -O3 -Werror $+\n./hs.exec: my-copied.hs\n\tghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ concat . map (++ \"\\n\") . map show . solveMany . map read . words\n where\n solveMany [] = []\n solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs lenA listA\n | (length listA /= lenA) = error \"Wrong length.\"\n | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n where\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum where\n numsum = n * i\n conv = (fromIntegral :: (Integral a => a -> Int64))\n n = conv maxNum\n i = conv $ countByNum maxNum\n f _ _ = maxDP (maxNum-1)\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n-- Problem: 456C (Boredom)\n-- http://codeforces.com/contest/456/problem/C\n-- Codeforces Round #260 (Div. 2)\n--\n-- Trying to time-optimize a Haskell solution given that no mutable\n-- types are used.\n--\n\nimport Prelude\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\nimport Data.Int (Int64)\n\ntype MyNum = Int64\ntype ANum = MyNum -- elements of a[]\ntype ASum = MyNum -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\nmain :: IO ()\nmain = interact $ unlines . map show . solveMany . map read . words\n where\n solveMany [] = []\n solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt (fromIntegral n) rest\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = prevDP + thisSum where\n (iprev, thisSum) = param numChoice where\n param Removed = (i-1, 0)\n param Chosen = (i-2, (freqs ! i) * i)\n prevDP = r $ freqs ! iprev where\n r 0 = get Removed\n r _ = max (get Removed) (get Chosen)\n get choicePrev = dpMemo ! (iprev, choicePrev)\n dpMemo = listArray memoBounds [dp n c\n | (n, c) <- range memoBounds]\n where\n memoBounds = ((-1, Chosen),\n (maxA, Removed))\n dp (-1) _ = 0\n dp 0 _ = 0\n dp maxNum numChoice = calcDP maxNum numChoice\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\tcat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n-- Problem: 456C (Boredom)\n-- http://codeforces.com/contest/456/problem/C\n-- Codeforces Round #260 (Div. 2)\n--\n-- Trying to time-optimize a Haskell solution given that no mutable\n-- types are used.\n--\n\nimport Prelude hiding (interact, words)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Lazy.Builder (toLazyByteString, char8)\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array, bounds, elems)\nimport Data.Int (Int64)\n\ntype MyNum = Int64\ntype ANum = MyNum -- elements of a[]\ntype ASum = MyNum -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = (map $ unpackSingleInt . readInt) . words where\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = fromIntegral num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt (fromIntegral n) rest\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n-- Whether ANum is present in a[].\ndata Presence = Present | Absent deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = f numChoice where\n f Chosen = maxDP (i-2) + (i * freqs ! i)\n f Removed = maxDP (i-1)\n maxDP n = max (memo Chosen) (memo Removed) where\n memo choice = dpMemo ! (n, choice, presenceByNum ! n)\n\n presenceByNum = listArray (bounds freqs) presenceList where\n presence c | (c > 0) = Present | otherwise = Absent\n presenceList = [presence cnt | cnt <- elems freqs]\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = calcDP maxNum Chosen\n f _ _ = calcDP maxNum Removed\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\tcat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n-- Problem: 456C (Boredom)\n-- http://codeforces.com/contest/456/problem/C\n-- Codeforces Round #260 (Div. 2)\n--\n-- Trying to time-optimize a Haskell solution given that no mutable\n-- types are used.\n--\n\nimport Prelude hiding (interact, words)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Lazy.Builder (toLazyByteString, char8)\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\nimport Data.Int (Int64)\n\ntype MyNum = Int64\ntype ANum = MyNum -- elements of a[]\ntype ASum = MyNum -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = (map $ unpackSingleInt . readInt) . words where\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = fromIntegral num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt (fromIntegral n) rest\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = prevDP + thisSum where\n (iprev, thisSum) = param numChoice where\n param Removed = (i-1, 0)\n param Chosen = (i-2, (freqs ! i) * i)\n prevDP = r $ freqs ! iprev where\n r 0 = get Removed\n r _ = max (get Removed) (get Chosen)\n get choicePrev = dpMemo ! (iprev, choicePrev)\n dpMemo = listArray memoBounds [dp n c\n | (n, c) <- range memoBounds]\n where\n memoBounds = ((-1, Chosen),\n (maxA, Removed))\n dp (-1) _ = 0\n dp 0 _ = 0\n dp maxNum numChoice = calcDP maxNum numChoice\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\tcat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words, mconcat, mappend)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Builder (toLazyByteString, int64Dec, char8)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveTC $ n : thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt n rest\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs _lenA listA = f\n where\n f = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum maxNum\n f _ _ = maxDP (maxNum-1)\n numsum num = n * i where\n n = fromIntegral num :: ASum\n i = fromIntegral $ countByNum num\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -std=c++0x -pedantic -Werror $+\n./hs.exec: my-copied.hs\n\tghc -Wall -Werror -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Lazy.Builder (toLazyByteString, char8)\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.HashMap.Lazy (HashMap)\nimport qualified Data.HashMap.Lazy as HM\n\nimport Data.Array (Ix, (!), listArray, range)\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt n rest\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype Freqs = HashMap ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs (maximum listA)\n where\n freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]\n incrSec _new = (+1)\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = maxDP maxA where\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum = flip (HM.lookupDefault 0) freqs\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum maxNum\n f _ _ = maxDP (maxNum-1)\n numsum num = n * i where\n n = fromIntegral num :: ASum\n i = fromIntegral $ countByNum num\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } | time ./a.out | sha1sum --binary\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } | time ./hs.exec +RTS -p -K100000000 | sha1sum --binary\n\tcat -- gen.in.txt | time ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -O3 -Werror $+\n./hs.exec: my-copied.hs\n\tghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 3\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 3\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n\nimport qualified Prelude as P\nimport Prelude (($), (.), (-), (+), (*),\n otherwise, Bool(True), Bool(False), error, const, undefined)\nimport System.IO (IO)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport qualified Data.ByteString.Lazy.Char8 as BL8\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\nimport Data.Maybe\nimport Data.Functor\nimport Data.Eq\nimport Data.Ord\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\n\nmain :: IO ()\nmain = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases\n where\n showResult = BB.toLazyByteString . int64Dec\n readCases = L.unfoldr readCase\n\ntype ANum = Int64 -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\ntype Case = [Int64]\ntype Result = ASum\n\ndropSpaces :: BL8.ByteString -> BL8.ByteString\ndropSpaces = BL8.dropWhile isSpace\n\nreadInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)\nreadInt64 bs = conv <$> BL8.readInteger (dropSpaces bs) where\n conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)\n\n-- 'readN n f i s' is like 'f s' but reads n consequential elements\n-- from s, not just one.\n-- 'i s' == True iff s is an empty string.\n-- 'readN 0 f i s' is Nothing if (i s == True),\n-- otherwise, 'readN n f i s' is an error if (i s == True).\n-- It is an error if it is impossible to read n elements form s.\nreadN :: P.Integral n =>\n n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)\nreadN cnt readFunc nullFunc str = rn2 cnt str where\n rn2 c s = rn c s (nullFunc s)\n rn 0 _ True = Nothing\n rn 0 s False = Just ([], s)\n rn n s _ = Just (firstElem : otherElems, strRest2) where\n (firstElem, strRest) = fromJust (readFunc s)\n (otherElems, strRest2) = unpack $ rn2 (n-1) strRest\n unpack Nothing = ([], strRest)\n unpack (Just res) = res\n\nreadCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)\nreadCase bsWithSpaces\n | BL8.null bs = Nothing\n | otherwise = readN n readInt64 BL8.null bsRest\n where\n bs = dropSpaces bsWithSpaces\n (n, bsRest) = fromJust (readInt64 bs)\n\nsolveCase :: Case -> Result\nsolveCase = solveFreqs . toFreqs\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = L.maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = prevDP + thisSum where\n (iprev, thisSum) = param numChoice where\n param Removed = (i-1, 0)\n param Chosen = (i-2, (freqs ! i) * i)\n prevDP = r $ freqs ! iprev where\n r 0 = get Removed\n r _ = max (get Removed) (get Chosen)\n get choicePrev = dpMemo ! (iprev, choicePrev)\n dpMemo = listArray memoBounds [dp n c\n | (n, c) <- range memoBounds]\n where\n memoBounds = ((-1, Chosen),\n (maxA, Removed))\n dp (-1) _ = 0\n dp 0 _ = 0\n dp maxNum numChoice = calcDP maxNum numChoice\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tprintf '1\\n57' | ./hs.exec\n\tprintf '1\\n57\\n' | ./hs.exec\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\ttime ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt\n\t#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n-- Trying to create a suitable effective IO template to use in\n-- competitive programming. Code brevity is secondary this time.\n-- First priority is fast adaptability of the template for specific\n-- problems during contest.\n--\n\nimport qualified Prelude as P\nimport Prelude (($), (.), (-), (+), (*),\n otherwise, Bool(True), Bool(False), error, const, undefined)\nimport System.IO (IO)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport qualified Data.ByteString.Lazy.Char8 as BL8\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\nimport Data.Maybe\nimport Data.Functor\nimport Data.Eq\nimport Data.Ord\nimport Data.Monoid (mappend, mconcat)\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\n\nmain :: IO ()\n-- main = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases\nmain = BL8.interact $ showResultsBS . L.map solveCase . readCases where\n showResultsBS = BB.toLazyByteString . mconcat . L.map resultBuilder where\n resultBuilder = (P.flip mappend $ BB.char8 '\\n') . int64Dec\n\ntype ANum = Int64 -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\ntype Case = [Int64]\ntype Result = ASum\n\n-- showResult :: Result -> BL8.ByteString\n-- showResult = BB.toLazyByteString . int64Dec\n\nreadCases :: BL8.ByteString -> [Case]\nreadCases = L.unfoldr readCase\n\ndropSpaces :: BL8.ByteString -> BL8.ByteString\ndropSpaces = BL8.dropWhile isSpace\n\nreadInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)\nreadInt64 bs = conv <$> BL8.readInteger (dropSpaces bs) where\n conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)\n\n-- 'readN n f i s' is like 'f s' but reads n consequential elements\n-- from s, not just one.\n-- 'i s' == True iff s is an empty string.\n-- 'readN 0 f i s' is Nothing if (i s == True),\n-- otherwise, 'readN n f i s' is an error if (i s == True).\n-- It is an error if it is impossible to read n elements form s.\nreadN :: P.Integral n =>\n n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)\nreadN cnt readFunc nullFunc str = rn2 cnt str where\n rn2 c s = rn c s (nullFunc s)\n rn 0 _ True = Nothing\n rn 0 s False = Just ([], s)\n rn _ _ True = error \"Unexpected end of input.\"\n rn n s False = Just (firstElem : otherElems, strRest2) where\n (firstElem, strRest) = fromJust (readFunc s)\n (otherElems, strRest2) = fromJust (rn2 (n-1) strRest)\n\nreadCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)\nreadCase bsWithSpaces\n | BL8.null bs = Nothing\n | otherwise = readN n readInt64 BL8.null bsRest\n where\n bs = dropSpaces bsWithSpaces\n (n, bsRest) = fromJust (readInt64 bs)\n\nsolveCase :: Case -> Result\nsolveCase = solveFreqs . toFreqs\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = L.maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = prevDP + thisSum where\n (iprev, thisSum) = param numChoice where\n param Removed = (i-1, 0)\n param Chosen = (i-2, (freqs ! i) * i)\n prevDP = r $ freqs ! iprev where\n r 0 = get Removed\n r _ = max (get Removed) (get Chosen)\n get choicePrev = dpMemo ! (iprev, choicePrev)\n dpMemo = listArray memoBounds [dp n c\n | (n, c) <- range memoBounds]\n where\n memoBounds = ((-1, Chosen),\n (maxA, Removed))\n dp (-1) _ = 0\n dp 0 _ = 0\n dp maxNum numChoice = calcDP maxNum numChoice\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\ttime ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt\n\t#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Lazy.Builder (toLazyByteString, char8)\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Monoid (mconcat, mappend)\n\n-- import Data.HashMap.Lazy (HashMap)\n-- import qualified Data.HashMap.Lazy as HM\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\nmytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\nmytrace _s = id\n\ntype MyNum = Int64\ntype ANum = MyNum -- elements of a[]\ntype ASum = MyNum -- sum of ANum values\n-- type ANum = Int64 -- elements of a[]\n-- type ASum = Int64 -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . mytrace \"input nums\" . parseIntsBS\n where\n parseIntsBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = fromIntegral num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = mytrace \"input nums\" $ []\n solveMany (n:rest) = (solveFreqs . toFreqs . mytrace \"this case\" $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt (fromIntegral n) rest\n\n-- type Freqs = HashMap ANum Cnt\ntype Freqs = Array ANum Cnt\n\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = maximum listA\n -- freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]\n -- incrSec _new = (+1)\n freqs = accumArray (+) 0 (-1,maxA) [(num, 1) | num <- listA]\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (\n Show, -- debug\n Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (\n Show, -- debug\n Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = f numChoice where\n f Chosen = maxDP (i-2) + (i * countByNum i)\n f Removed = maxDP (i-1)\n maxDP n = max (memo Chosen) (memo Removed) where\n memo choice = dpMemo ! mytrace \"dpMemo ind\" (n, choice, presence)\n presence\n | (cnt > 0) = Present\n | otherwise = Absent\n cnt = countByNum n\n\n -- countByNum = flip (HM.lookupDefault 0) freqs\n -- countByNum = (!) cbm . mytrace \"countByNum arg\" where\n -- cbm = accumArray accfunc 0 (mytrace \"cbm bounds\" $ (-1,maxA)) (HM.toList freqs)\n -- where\n -- accfunc 0 = id\n -- accfunc _ = error \"HashMap with duplicates?\"\n countByNum = (!) freqs\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = calcDP maxNum Chosen\n f _ _ = calcDP maxNum Removed\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray (mytrace \"dpMemo bounds\" memoBounds) [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out gen.in.txt\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec gen.in.txt\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } | time ./hs.exec +RTS -p -K100000000\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -O3 -Werror $+\n./hs.exec: my-copied.hs\n\tghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ concat . map (++ \"\\n\") . map show . solveMany . map read . words\n where\n solveMany [] = []\n solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs lenA listA\n | (length listA /= lenA) = error \"Wrong length.\"\n | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n where\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum maxNum\n f _ _ = maxDP (maxNum-1)\n numsum num = n * i where\n n = fromIntegral num :: ASum\n i = fromIntegral $ countByNum num\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -std=c++0x -pedantic -Werror $+\n./hs.exec: my-copied.hs\n\tghc -Wall -Werror -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Prelude hiding (interact, words, mconcat, mappend)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Builder (toLazyByteString, int64Dec, char8)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\nimport Data.Int (Int64)\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseCasesBS\n where\n parseCasesBS = map parseSingleInt . words where\n parseSingleInt = unpackSingleInt . readInt\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs lenA listA\n | (length listA /= lenA) = error \"Wrong length.\"\n | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n where\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + numsum maxNum\n f _ _ = maxDP (maxNum-1)\n numsum num = n * i where\n n = fromIntegral num :: ASum\n i = fromIntegral $ countByNum num\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all submit\ndefault: all\n\nall: run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -std=c++0x -pedantic -Werror $+\n./hs.exec: my-copied.hs\n\tghc -Wall -Werror -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n/gen.*.txt\n/temp-for-submit.hs\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n-- Problem: 456C (Boredom)\n-- http://codeforces.com/contest/456/problem/C\n-- Codeforces Round #260 (Div. 2)\n--\n-- Trying to time-optimize a Haskell solution given that no mutable\n-- types are used.\n--\n\nimport Prelude hiding (interact, words)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (empty)\nimport Data.ByteString.Lazy.Char8 (interact, words, readInt)\nimport Data.ByteString.Lazy.Builder (toLazyByteString, char8)\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Monoid (mconcat, mappend)\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array, bounds, elems)\nimport Data.Int (Int64)\n\ntype MyNum = Int64\ntype ANum = MyNum -- elements of a[]\ntype ASum = MyNum -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\nmain :: IO ()\nmain = interact $ showResultsBS . solveMany . parseIntsBS\n where\n parseIntsBS = (map $ unpackSingleInt . readInt) . words where\n unpackSingleInt (Just (num, rest))\n | (rest == BS.empty) = fromIntegral num\n | otherwise = error \"Single word expected.\"\n unpackSingleInt _ = error \"Error parsing readInt result.\"\n showResultsBS = toLazyByteString . mconcat . map resultBuilder where\n resultBuilder = (flip mappend $ char8 '\\n') . int64Dec\n solveMany [] = []\n solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases) where\n (thisCase, otherCases) = splitAt (fromIntegral n) rest\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n-- Whether ANum is present in a[].\ndata Presence = Present | Absent deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = f numChoice where\n f Chosen = maxDP (i-2) + (i * freqs ! i)\n f Removed = maxDP (i-1)\n maxDP n = max (memo Chosen) (memo Removed) where\n memo choice = elemByInd where\n elemByInd = dpMemo ! memoInd\n memoInd = (n, choice, presenceByNum ! n)\n\n presenceByNum = listArray (bounds freqs) presenceList where\n presence c | (c > 0) = Present | otherwise = Absent\n presenceList = [presence cnt | cnt <- elems freqs]\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = calcDP maxNum Chosen\n f _ _ = calcDP maxNum Removed\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -O3 -Werror $+\n./hs.exec: my-copied.hs\n\tghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n-- http://mivael.in.ua\n--\n\nimport qualified Prelude as P\nimport Prelude (($), (.), (-), (+), (*),\n otherwise, Bool(True), Bool(False), error, const, undefined)\nimport System.IO (IO)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport qualified Data.ByteString.Lazy.Char8 as BL8\nimport Data.ByteString.Lazy.Builder.ASCII (int64Dec)\nimport Data.Int (Int64)\nimport Data.Char (isSpace)\nimport Data.Maybe\nimport Data.Functor\nimport Data.Eq\nimport Data.Ord\n\nimport Data.Array (Ix, (!), listArray, accumArray, range, Array)\n\nmain :: IO ()\nmain = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases\n where\n showResult = BB.toLazyByteString . int64Dec\n readCases = L.unfoldr readCase\n\ntype ANum = Int64 -- elements of a[]\ntype ASum = Int64 -- sum of ANum values\ntype Cnt = Int64 -- number of elements in a[]\n\ntype Case = [Int64]\ntype Result = ASum\n\nreadInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)\nreadInt64 bs = conv <$> BL8.readInteger (BL8.dropWhile isSpace bs) where\n conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)\n\n-- 'readN n f i s' is like 'f s' but reads n consequential elements\n-- from s, not just one.\n-- 'i s' == True iff s is an empty string.\n-- 'readN 0 f i s' is Nothing if (i s == True),\n-- otherwise, 'readN n f i s' is an error if (i s == True).\n-- It is an error if it is impossible to read n elements form s.\nreadN :: P.Integral n =>\n n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)\nreadN cnt readFunc nullFunc str = rn2 cnt str where\n rn2 c s = rn c s (nullFunc s)\n rn 0 _ True = Nothing\n rn 0 s False = Just ([], s)\n rn n s _ = Just (firstElem : otherElems, strRest2) where\n (firstElem, strRest) = fromJust (readFunc s)\n (otherElems, strRest2) = unpack $ rn2 (n-1) strRest\n unpack Nothing = ([], strRest)\n unpack (Just res) = res\n\nreadCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)\nreadCase bsWithSpaces\n | BL8.null bs = Nothing\n | otherwise = readN n readInt64 BL8.null bsRest\n where\n bs = BL8.dropWhile isSpace bsWithSpaces\n (n, bsRest) = fromJust (readInt64 bs)\n\nsolveCase :: Case -> Result\nsolveCase = solveFreqs . toFreqs\n\ntype Freqs = Array ANum Cnt\ndata FreqsAndMaxnum = FreqsMx Freqs ANum\n\n-- Convert input data to a num-->frequencies mapping.\ntoFreqs :: [ANum] -> FreqsAndMaxnum\ntoFreqs listA = FreqsMx freqs maxA\n where\n maxA = L.maximum listA\n freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]\n\n-- Whether ANum is chosen.\ndata NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqsAndMaxnum -> ASum\nsolveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed where\n calcDP i numChoice = prevDP + thisSum where\n (iprev, thisSum) = param numChoice where\n param Removed = (i-1, 0)\n param Chosen = (i-2, (freqs ! i) * i)\n prevDP = r $ freqs ! iprev where\n r 0 = get Removed\n r _ = max (get Removed) (get Chosen)\n get choicePrev = dpMemo ! (iprev, choicePrev)\n dpMemo = listArray memoBounds [dp n c\n | (n, c) <- range memoBounds]\n where\n memoBounds = ((-1, Chosen),\n (maxA, Removed))\n dp (-1) _ = 0\n dp 0 _ = 0\n dp maxNum numChoice = calcDP maxNum numChoice\n\n{-- Makefile --\n\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit\ndefault: all\n\nall: time-hs run-hs show-res submit\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\n\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\ntime-cpp: ./a.out 10pow5shuffled.in.txt\n\tcat -- 10pow5shuffled.in.txt | time ./a.out\n\nrun-hs: ./hs.exec gen.in.txt\n\tprintf '1\\n57' | ./hs.exec\n\tprintf '1\\n57\\n' | ./hs.exec\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\ntime-hs: ./hs.exec 10pow5shuffled.in.txt\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000\n\t#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216\n\ttime ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt\n\t#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt\n\n10pow5shuffled.in.txt:\n\t{ echo 100000; printf '%s\\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt\n\twc -l -- 10pow5shuffled.in.txt\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+\n./hs.exec: my-copied.hs\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+\n\t#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+\n\tghc -rtsopts -Wall -Werror -O2 -o '$@' $+\n\nsubmit: temp-for-submit.hs\ntemp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore\n\tcat -- my-copied.hs > '$@'\n\tprintf '\\n{-- %s --\\n\\n' Makefile >> '$@'\n\tcat -- Makefile >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' gener.py >> '$@'\n\tcat -- gener.py >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\tprintf '\\n{-- %s --\\n\\n' .gitignore >> '$@'\n\tcat -- .gitignore >> '$@'\n\tprintf '\\n%s\\n\\n' '--}' >> '$@'\n\n--}\n\n\n{-- gener.py --\n\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 6\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n\n\n{-- .gitignore --\n\n\n/gen.*.txt\n/temp-for-submit.hs\n/10pow5shuffled.in.txt\n\n--}\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = show `fmap` solve `fmap` (flip replicateM poi =<< poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve xs = snd $ foldl' (\\(!prev, !curr) (x, f) -> (curr, max curr $ prev + fromIntegral x * fromIntegral f)) (0 :: Int64, fromIntegral $ snd $ head freq) $ tail freq\n where\n freq = assocs (accumArray (+) 0 (0, maximum xs) $ zip xs (repeat 1) :: UArray Int Int)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\ncount l = sort $ map (\\g -> (head g, length g)) $ group (sort l)\n\ng :: Integer -> Integer -> Int -> Map.Map Int Int -> Integer\ng pprev prev i elems\n | i > (fst . Map.findMax) elems = max pprev prev\n | otherwise = \n let v = max prev (pprev + (fromIntegral i) * (fromIntegral $ Map.findWithDefault 0 i elems))\n in g prev v (i+1) elems\n\nf :: [Int] -> Integer\nf xs = g 0 0 0 (Map.fromList $ count xs)\n\nmain = interact $ show . f . (map read) . words . head . tail . lines\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . map read . words =<< getContents\n\nsolve :: [Integer] -> Integer\nsolve a = \n let sa = sort a\n in count (compress (tail sa) (head sa) 1) 0 0 0\n\ncompress :: [Integer] -> Integer -> Integer -> [(Integer, Integer)]\ncompress [] num cnt = [(num, cnt)]\ncompress (a:ax) num cnt | num == a = compress ax num (cnt + 1)\n | otherwise = (num, cnt):(compress ax a 1)\n \ncount :: [(Integer, Integer)] -> Integer -> Integer -> Integer -> Integer\ncount [] _ n y = max n y\ncount ((num, cnt):s) last n y | num == last + 1 = count s num (max n y) (n + num * cnt)\n | otherwise = count s num (max n y) ((max n y) + num * cnt)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n as <- getInts\n\n let\n cs = accumArray (+) 0 (1, 10^5) $ zip as $ repeat (1 :: Int64)\n\n r = listArray (0, 10^5) $ map f [0..10^5]\n where\n f 0 = 0\n f 1 = cs!1\n f i = max (r!(i-1)) (r!(i-2) + (fromIntegral i)*cs!i)\n\n print $ r!(10^5)\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n getLine\n as <- readInts\n print $ solve as\n\nsolve :: [Int] -> Int64\nsolve as = dp ! (10^5)\n where\n hist :: UArray Int Int64\n hist = accumArray (\\x _ -> x+1) 0 (0,10^5) $ map (,()) as\n dp :: Array Int Int64\n dp = listArray (0,10^5) $ map f [0..10^5]\n f 0 = 0\n f 1 = hist ! 1\n f x | a == 0 = k1\n | otherwise = max k1 $ k2 + a * (fromIntegral x)\n where\n a = hist ! x\n k1 = dp ! (x-1)\n k2 = dp ! (x-2)\n\n"}, {"source_code": "import Data.Array\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Integer -> [Integer] -> Integer\nsolve _ xs = res!100000\n where\n arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs] :: Array Integer Integer\n res = listArray (0,100000) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..100000]] :: Array Integer Integer\n"}, {"source_code": "import Control.Applicative\nimport Data.Array.IArray\nimport qualified Data.Foldable as F\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n n <- readLn :: IO Int\n a <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n let s = accumArray (+) 0 (1, 10 ^ 5) [(x, toInteger x) | x <- a] :: Array Int Integer\n let maxA = maximum a\n let dp = array (0, maxA) ((0, 0) : (1, s ! 1) : [(i, max (dp ! (i - 1)) ((dp ! (i - 2) ) + s ! i)) | i <- [2 .. maxA]]) :: Array Int Integer\n putStrLn . show . F.foldl1 max $ dp\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map read. words.head. tail.lines\nsolve :: [Integer]->String\nsolve xs = show $ head $ slv1 $ foldr f [] $ sort xs \n where \n f a [] = [[a,1]]\n f a ([b1,b2]:xs) = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)\nslv1 xss =foldr f1 [] xss where\n f1 [a1,a2] [] = [a2*a1,0,1,a1]\n f1 [a1,a2] [sum1,prev,l,a] | l==0 && a-a1<=1 = [sum1+a2*a1,sum1,1,a1]\n | l==1 && a-a1<=1 = if a2*a1+prev>sum1 then [a2*a1+prev,sum1,1,a1] else [sum1,0,0,a1]\n | a-a1>1 = [a2*a1+sum1,sum1,1,a1]"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n-- best result only selecting numbers <= i\nsolve1 :: Array Int Int64 -> Int -> Int64\nsolve1 a = (r !)\n where r = listArray (0, 100000) (0 : a ! 1 : map f [2..100000])\n f i = max (r ! (i - 1)) (a ! i + r ! (i - 2))\n\n(+^) :: Int64 -> Int -> Int64\na +^ b = a + fromIntegral b\n\nsolve :: [Int] -> Int64\nsolve a = solve1 cnt 100000\n where cnt = accumArray (+^) 0 (1, 100000) (zip a a)\n\nmain :: IO ()\nmain = getLine >> getIntList >>= print . solve\n"}, {"source_code": "\nimport Data.Array.MArray\nimport Data.Array.IO\n\ntype IntArray = IOArray Integer Integer\n\npreProcess :: IO IntArray\npreProcess = do\n count <- newArray (0, 100000) 0 :: IO IntArray\n getLine\n a <- (getLine >>= (return . map read . words))\n mapM_ (\\x -> (readArray count x) >>= ((writeArray count x) . (+x))) a\n return count\n \nsolve :: [Integer] -> Integer\nsolve count = dp !! 100000\n where dp = 0 : (count!!1) : zipWith max (zipWith (+) dp (drop 2 count)) (tail dp)\n\nmain = do\n preProcess >>= getElems >>= (print . solve)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\nprocess::[(Integer,Integer)]->Integer\nprocess q = dp!(100100)\n where qq = accumArray (+) 0 (1,100100) q\n dp =array (0,100100) ([(0,0),(1,qq!1)]\n ++ [(i,max (dp!(i-2)+qq!i) (dp!(i-1)))|i<-[2..100100]])\n\n\nmain=do\n getLine\n q<- map (\\z-> (head z,sum z)) <$> group <$> sort <$> map read <$> words <$>getLine ::IO [(Integer,Integer)]\n print $ process q\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = show `fmap` solve `fmap` (flip replicateM poi =<< poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve xs = snd $ foldl' (\\(!prev, !curr) (x, f) -> (curr, max curr $ prev + x * f)) (0, snd $ head freq) $ tail freq\n where\n freq = assocs (accumArray (+) 0 (0, maximum xs) $ zip xs (repeat 1) :: UArray Int Int)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\ncount l = sort $ map (\\g -> (head g, length g)) $ group (sort l)\n\ng :: Int -> Int -> Int -> Map.Map Int Int -> Int\ng pprev prev i elems\n | i > (fst . Map.findMax) elems = max pprev prev\n | otherwise = \n let v = max prev (pprev + i * Map.findWithDefault 0 i elems)\n in g prev v (i+1) elems\n\nf :: [Int] -> Int\nf xs = g 0 0 0 (Map.fromList $ count xs)\n\nmain = interact $ show . f . (map read) . words . head . tail . lines"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n as <- getInts\n\n let\n cs = accumArray (+) 0 (1, 10^5) $ zip as $ repeat 1\n\n r = listArray (0, 10^5) $ map f [0..10^5]\n where\n f 0 = 0\n f 1 = cs!1\n f i = max (r!(i-1)) (r!(i-2) + i*cs!i)\n\n print $ r!(10^5)\n\n"}, {"source_code": "import Data.Array\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n xs = res!n\n where\n arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs]\n res = listArray (0,n) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..n]]\n"}, {"source_code": "import Data.Array\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n xs = res!n\n where\n arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs] :: Array Integer Integer\n res = listArray (0,n) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..n]] :: Array Integer Integer\n"}, {"source_code": "import Data.Array\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n xs = res!n\n where\n arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs] :: Array Integer Integer\n res = listArray (0,100000) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..100000]] :: Array Integer Integer\n"}, {"source_code": "import Control.Applicative\nimport Data.Array.IArray\nimport qualified Data.Foldable as F\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n n <- readLn :: IO Int\n a <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n let s = accumArray (+) 0 (1, 10 ^ 5) [(x, toInteger x) | x <- a] :: Array Int Integer\n let dp = array (0, n) ((0, 0) : (1, s ! 1) : [(i, max (dp ! (i - 1)) ((dp ! (i - 2) ) + s ! (i - 1))) | i <- [2 .. n]]) :: Array Int Integer\n putStrLn . show . F.foldl max 0 $ dp"}, {"source_code": "import Control.Applicative\nimport Data.Array.IArray\nimport qualified Data.Foldable as F\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n n <- readLn :: IO Int\n a <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n let s = accumArray (+) 0 (1, 10 ^ 5) [(x, toInteger x) | x <- a] :: Array Int Integer\n let dp = array (0, n) ((0, 0) : (1, s ! 1) : [(i, max (dp ! (i - 1)) ((dp ! (i - 2) ) + s ! i)) | i <- [2 .. n]]) :: Array Int Integer\n putStrLn . show . F.foldl max 0 $ dp\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map read. words.head. tail.lines\nsolve :: [Int]->String\nsolve xs = show $ head $ slv1 $ foldr f [] $ sort xs \n where \n f a [] = [[a,1]]\n f a ([b1,b2]:xs) = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)\nslv1 xss =foldr f1 [] xss where\n f1 [a1,a2] [] = [a2*a1,a2*a1]\n f1 [a1,a2] [sum1,prev]= if a1*a2-prev>0 then [a1*a2-prev+sum1, a2*a1] else [sum1,0]"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map read. words.head. tail.lines\nsolve :: [Int]->String\nsolve xs = show $ head $ slv1 $ foldr f [] $ sort xs \n where \n f a [] = [[a,1]]\n f a ([b1,b2]:xs) = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)\nslv1 xss =foldr f1 [] xss where\n f1 [a1,a2] [] = [a2*a1,0,1,a1]\n f1 [a1,a2] [sum1,prev,l,a] | l==0 && a-a1<=1 = [sum1+a2*a1,sum1,1,a1]\n | l==1 && a-a1<=1 = if a2*a1+prev>sum1 then [a2*a1+prev,sum1,1,a1] else [sum1,0,0,a1]\n | a-a1>1 = [a2*a1+sum1,sum1,1,a1]"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map read. words.head. tail.lines\nsolve :: [Int]->String\nsolve xs = show $ head $ slv1 $ foldr f [] $ sort xs \n where \n f a [] = [[a,1]]\n f a ([b1,b2]:xs) = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)\nslv1 xss =foldr f1 [] xss where\n f1 [a1,a2] [] = [a2*a1,0,1]\n f1 [a1,a2] [sum1,prev,l] | l==0 = [sum1+a2*a1,sum1,1]\n | l==1 = if a2*a1+prev>sum1 then [a2*a1+prev,sum1,1] else [sum1,0,0]"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map read. words.head. tail.lines\nsolve :: [Int]->String\nsolve xs = show $ head.tail.slv1 $ foldr f [] $ sort xs \n where \n f a [] = [[a,1]]\n f a ([b1,b2]:xs) = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)\nslv1 xss =foldr f1 [] xss where\n f1 [a1,a2] [] = [a1,a2*a1,0, 1]\n f1 [a1,a2] [prev,sum1,sum2,l] | prev-1==a1 && a2*a1 +sum2 > sum1 && l==1 = [a1, a2*a1 +sum2, sum1, 1]\n | prev-1==a1 && a2*a1 +sum2 <= sum1 && l==1 = [a1, sum1 ,a2*a1 +sum2, 0]\n | l==0 = [a1, sum1+a2*a1, sum2, 1]\n | otherwise = [a1, sum1+a2*a1 ,0,1]"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n-- best result only selecting numbers <= i\nsolve1 :: Array Int Int -> Int -> Int64\nsolve1 a = (r !)\n where r = listArray (0, 100000) (0 : fromIntegral (a ! 1) : map f [2..100000])\n f i = max (r ! (i - 1)) (fromIntegral (a ! i) + r ! (i - 2))\n\nsolve :: [Int] -> Int64\nsolve a = solve1 cnt 100000\n where cnt = accumArray (+) 0 (1, 100000) (zip a a)\n\nmain :: IO ()\nmain = getLine >> getIntList >>= print . solve\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n-- best result only selecting numbers <= i\nsolve1 :: Array Int Int -> Int -> Int\nsolve1 a = (r!)\n where r = listArray (0,100000) (0 : a!1 : map f [2..100000])\n f i = max (r!(i - 1)) (a!i + r!(i - 2))\n\nsolve :: [Int] -> Int\nsolve a = solve1 cnt 100000\n where cnt = accumArray (+) 0 (1,100000) (zip a a)\n\nmain :: IO ()\nmain = getLine >> getIntList >>= print . solve\n"}, {"source_code": "\nimport Data.Array.MArray\nimport Data.Array.IO\n\ntype IntArray = IOArray Int Int\n\npreProcess :: IO IntArray\npreProcess = do\n count <- newArray (0, 100000) 0\n getLine\n a <- (getLine >>= (return . map read . words)) :: IO [Int]\n mapM_ (\\x -> (readArray count x) >>= ((writeArray count x) . (+x))) a\n return count\n \nsolve :: [Int] -> Int\nsolve count = dp !! 100000\n where dp = 0 : (count!!1) : zipWith max (zipWith (+) dp (drop 2 count)) (tail dp)\n\nmain = do\n preProcess >>= getElems >>= (print . solve)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nmain=do\n getLine\n q<- map read <$> words <$>getLine ::IO [Int]\n let r= maximum $ map (\\z->(length z,head z)) $ group $ sort q\n print r\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nmain=do\n getLine\n q<- map read <$> words <$>getLine ::IO [Int]\n let r= maximum $ map (\\z->(max (length z-1) 1)*(head z)) $ group $ sort q\n print r\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\nprocess::[(Int,Int)]->Int\nprocess q = dp!(100100)\n where qq = accumArray (+) 0 (1,100100) q\n dp =array (0,100100) ([(0,0),(1,qq!1)]\n ++ [(i,max (dp!(i-2)+qq!i) (dp!(i-1)))|i<-[2..100100]])\n\n\nmain=do\n getLine\n q<- map (\\z-> (head z,sum z)) <$> group <$> sort <$> map read <$> words <$>getLine ::IO [(Int,Int)]\n print $ process q\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nmain=do\n getLine\n q<- map read <$> words <$>getLine ::IO [Int]\n let r= maximum $ map (\\z->(length z,head z)) $ group $ sort q\n print $ snd r\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\nprocess q = dp!(lq)\n where dp =array (0,lq) ([(0,0),(1,q!!0)]\n ++ [(i,max (dp!(i-2)+q!!(i-1)) (dp!(i-1)))|i<-[2..lq]])\n lq = length q\n\nmain=do\n getLine\n q<- map sum <$> group <$> sort <$> map read <$> words <$>getLine ::IO [Int]\n print $ process q\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nmain=do\n getLine\n q<- map read <$> words <$>getLine ::IO [Int]\n let r= maximum $ map (\\z->(length z-1)*(head z)) $ group $ sort q\n print r\n"}, {"source_code": "import Data.List\n\nadd :: (a -> a -> Bool) -> a -> [[a]] -> [[a]]\nadd eq x ((y:ys):others) = if eq x y then (x:y:ys):others else [x]:(y:ys):others\nadd eq x [] = [[x]]\n\nadjacentGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]\nadjacentGroupBy eq xs = foldr (add eq) [] xs\n\nevens :: [a] -> [a]\nevens (x:xs) = x:(odds xs)\nevens [] = []\n\nodds :: [a] -> [a]\nodds (_:xs) = evens xs\nodds [] = []\n\ngroup_score :: [(Int, Int)] -> Int\ngroup_score groups =\n max (score $ evens groups) (score $ odds groups)\n where score = sum . map (\\x -> fst x * snd x)\n\nmax_score :: [Int] -> Int\nmax_score nums =\n let\n pairs = map (\\xs -> (head xs, length xs)) $ groupBy (==) $ sort nums\n groups = adjacentGroupBy (\\x y -> (abs (fst x - fst y)) <= 1) pairs\n in\n sum $ map group_score groups\n\nmain = do\n getLine\n nums <- getLine\n print $ max_score $ map read $ words nums\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ show . solveTC . map read . words\n where\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs lenA listA\n | (length listA /= lenA) = error \"Wrong length.\"\n | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n where\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + (maxNum * countByNum maxNum)\n f _ _ = maxDP (maxNum-1)\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- Michael.Antosha@gmail.com\n--\n-- http://mivael.in.ua\n--\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!))\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = interact $ show . solveTC . map read . words\n where\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length ans list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int -- sum of ANum's\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Input data to the array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs lenA listA\n | (length listA /= lenA) = error \"Wrong length.\"\n | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n where\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\ndata Presence = Present | Absent -- whether ANum is present in a[]\n\n-- Solve the array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = max (dp i Chosen) (dp i Removed)\n\n dp 0 _ = 0\n dp maxNum choice = f choice presence where\n presence | cnt > 0 = Present | otherwise = Absent\n nprev = maxNum - 1\n cnt = freqsArray ! maxNum\n\n f Removed Present = dp nprev Chosen\n f Removed Absent = maxDP nprev\n f Chosen Present = maxNum * cnt + dp nprev Removed\n f Chosen Absent = 0\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2017\n-- m.antosha@samsung.com\n--\n\nimport Data.List (sort, group)\nimport Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)\nimport Control.Arrow ((&&&))\n\n-- import Debug.Trace (trace)\n-- mytrace :: Show a => String -> a -> a\n-- mytrace s x = trace (\"trace: \" ++ s ++ \": \" ++ show x ++ \".\") x\n\nmain :: IO ()\nmain = interact $ concat . map (++ \"\\n\") . map show . solveMany . map read . words\n where\n solveMany [] = []\n solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)\n solveTC (n:listA) = solveFreqs . toFreqs n $ listA\n solveTC _ = error \"Length and list are expected.\"\n\ntype ANum = Int -- elements of a[]\ntype ASum = Int -- sum of ANum values\ntype Cnt = Int -- number of elements in a[]\n\ntype FreqArray = Array ANum Cnt\n\n-- Convert input data to an array of frequencies.\ntoFreqs :: Cnt -> [ANum] -> FreqArray\ntoFreqs lenA listA\n | (length listA /= lenA) = error \"Wrong length.\"\n | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA\n where\n freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList\n where\n maxA = getNum . head $ assocList\n getNum (num,_cnt) = num\n\ndata NumChoice = Chosen | Removed -- whether ANum is chosen\n deriving (Show, Eq, Ord, Ix)\ndata Presence = Present | Absent -- whether ANum is present in a[]\n deriving (Show, Eq, Ord, Ix)\n\n-- Solve, given an array of frequencies.\nsolveFreqs :: FreqArray -> ASum\nsolveFreqs freqsArray = maxDP maxA where\n maxA = snd . bounds $ freqsArray\n maxDP i = (max\n (dpMemo ! (i, Chosen, presenceByNum i))\n (dpMemo ! (i, Removed, presenceByNum i)))\n countByNum num\n | num > 0 = freqsArray ! num\n | otherwise = 0\n presenceByNum = toPresence . countByNum\n toPresence count | count > 0 = Present | otherwise = Absent\n\n dp (-1) _ _ = 0\n dp 0 _ _ = 0\n dp maxNum numChoice numPresence = f numChoice numPresence where\n f Chosen Present = maxDP (maxNum-2) + (maxNum * countByNum maxNum)\n f _ _ = maxDP (maxNum-1)\n\n memoBounds = ((-1, Chosen, Present),\n (maxA, Removed, Absent))\n dpMemo = listArray memoBounds [dp n c p\n | (n, c, p) <- range memoBounds]\n\n\n{-- Makefile\n\nexport SHELL = /bin/bash -o pipefail\n\n.PHONY: run-cpp run-hs show-res default all\ndefault: run-cpp\nall: run-cpp run-hs show-res\n\nshow-res: gen.res.txt\n\tcat -- '$+' | sha1sum --binary\nrun-cpp: ./a.out gen.in.txt\n\tcat -- gen.in.txt | ./a.out | sha1sum --binary\nrun-hs: ./hs.exec gen.in.txt\n\tcat -- gen.in.txt | ./hs.exec | sha1sum --binary\n\ngen.res.txt: gen.stamp.txt\ngen.in.txt: gen.stamp.txt\n\ngen.stamp.txt: gener.py\n\tpython3 gener.py\n\ttouch gen.stamp.txt\n\tls -ld -- gen.*.txt\n\n./a.out: *.cpp\n\tg++ -Wall -Wextra -std=c++0x -pedantic -Werror $+\n./hs.exec: *.hs\n\tghc -Wall -Werror -o '$@' $+\n\n--}\n\n\n{-- gener.py\n\nimport itertools\nimport collections\n\ndef main():\n maxN = 5\n print(\"maxN = {!r}.\" . format(maxN))\n maxA = 9\n print(\"maxA = {!r}.\" . format(maxA))\n writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')\n for n in [i+1 for i in range(maxN)]:\n print(\"n = {!r}.\" . format(n))\n for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):\n # print(\"arrA = {!r}.\" . format(arrA))\n writeCase(inputArr=arrA, result=solve(arrA))\n\ndef solve(arrA):\n max_points = 0\n for order in itertools.permutations(range(len(arrA))):\n num2inds = collections.defaultdict(set)\n for ind, num in enumerate(arrA):\n num2inds[num].add(ind)\n points = 0\n for ind in order:\n # print(\"order = {!r} (len={!r}), ind = {!r}.\" . format(order, len(order), ind))\n num = arrA[ind]\n if len(num2inds[num]) == 0:\n continue\n points += num\n num2inds[num].remove(ind)\n num2inds[num-1].clear()\n num2inds[num+1].clear()\n max_points = max(points, max_points)\n return max_points\n\nclass CaseWriter:\n def __init__(self, inputsFilename, resultsFilename):\n self.inputs = open(inputsFilename, mode='w')\n self.results = open(resultsFilename, mode='w')\n def __call__(self, inputArr, result):\n print(\"{n!r}\\n{a}\" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)\n print(\"{!r}\" . format(result), file=self.results)\n self.inputs.flush()\n self.results.flush()\n\nmain()\n\n--}\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n nums <- getLine\n print $ max_score $ map read $ words nums\n\nadd :: (a -> a -> Bool) -> a -> [[a]] -> [[a]]\nadd eq x ((y:ys):others) = if eq x y then (x:y:ys):others else [x]:(y:ys):others\nadd eq x [] = [[x]]\n\nadjacentGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]\nadjacentGroupBy eq xs = foldr (add eq) [] xs\n\nmax_first :: [Int] -> Int\nmax_first (x:y:_) = max x y\nmax_first (x:_) = x\nmax_first [] = 0\n\nsafe_tail :: [a] -> [a]\nsafe_tail (_:xs) = xs\nsafe_tail [] = []\n\n\ndp_step :: [Int] -> (Int, Int) -> [Int]\ndp_step acc x = ((fst x * snd x) + (max_first $ safe_tail acc)):acc\n\ngroup_score :: [(Int, Int)] -> Int\ngroup_score group =\n max_first dp\n where dp = foldl dp_step [] group\n\nmax_score :: [Int] -> Int\nmax_score nums =\n let\n pairs = map (\\xs -> (head xs, length xs)) $ groupBy (==) $ sort nums\n groups = adjacentGroupBy (\\x y -> (abs (fst x - fst y)) <= 1) pairs\n in\n sum $ map group_score groups\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Integer] -> Integer\nsolve (_:as) = max (sum (filter even as)) (sum (filter odd as))\nsolve _ = undefined\n"}, {"source_code": "import Data.List (foldl', group, sort)\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve = uncurry max . snd . foldl' f (0, (0, 0)) . map (head &&& length) . group . sort\n where f (a, (b, c)) (d, e) | a + 2 < d = (d, (d * e + max b c, max b c))\n | a + 1 < d = (d, (max (d * e + b) (max b c), max b c))\n | otherwise = (d, (max (d * e + c) b, b))\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Control.Arrow\nmain = do\n getLine\n ns <- fmap (map (head &&& length) . group . sort . map read . words) getLine\n print $ solve ns\nsolve ns = go 0 ns where\n s = length ns\n go _ [] = 0\n go _ [(n,c)] = n*c\n go i ((n,c):(m,_):_)\n | m == n + 1 = maximum [\n go' (i+1)\n , n*c + go' (i+2)\n , n*c + go' (i+3)\n ]\n | otherwise = go' (i+1) + n*c\n go' = let a = listArray (0,s+2) $ zipWith go [0..] (tails ns) ++ [0,0]\n in \\i -> a ! i\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Control.Arrow\nmain = do\n getLine\n ns <- fmap (map (head &&& length) . group . reverse . sort . map read . words) getLine\n print $ solve ns\nsolve ns = go 0 ns where\n go _ [] = 0\n go _ [(n,c)] = n*c\n go i ((n,c):es@((m,d):es')) = max (go' (i+1) es) (n*c + go' (i+2) es')\n go' = let a = listArray (0,length ns) $ zipWith go [0..] (tails ns)\n in \\i j -> a ! i\n"}, {"source_code": "import Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Control.Arrow ((&&&))\nimport Data.List (group, sort)\nimport Data.Array\n\ninput :: IO [Int]\ninput = getLine >> fmap (map read . words) getLine\n\ntoAssocs :: [Int] -> [(Int, Int)]\ntoAssocs = map (head &&& length) . group . sort\n\nsolve :: [Int] -- List of numbers\n -> Int -- Max score\nsolve xs = m!100000\n where\n cs = Map.fromList . toAssocs $ xs\n count x = maybe 0 id $ Map.lookup x cs\n m = array (0, 100000) $\n [(0, 0), (1, count 1)] ++\n [(i, f i) | i <- [2..100000]]\n f n = max takeN ignoreN\n where takeN = m!(n-1)\n ignoreN = m!(n-2) + (n*count n)\n\noutput :: Int -> IO ()\noutput = putStrLn . show\n\nmain :: IO ()\nmain = output . solve =<< input"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (sort, group)\n\nprocess :: [Int64] -> Int64\nprocess = maximum . snd . foldr g (maxBound,[0]) . map f . group . sort\n where\n f xs = (head xs, sum xs)\n g (x,p) (y,s@(a:as))\n | y-x == 1 = case as of\n [] -> (x,[p,a])\n (a':_) -> (x,[p+a',max a a'])\n | otherwise = (x,[p+maximum s])\n\nreadInt :: String -> Int64\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (sort, group)\n\nprocess :: [Int64] -> Int64\nprocess = maximum . snd . foldr g (maxBound,[0]) . map f . group . sort\n where\n f xs = (head xs, sum xs)\n g (x,p) (y,s@(a:as))\n | y-x == 1 = case as of\n [] -> (x,[p,a])\n (a':_) -> (x,[p+a',a])\n | otherwise = (x,[p+maximum s])\n\nreadInt :: String -> Int64\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}], "src_uid": "41b3e726b8146dc733244ee8415383c0"} {"source_code": "-- https://codeforces.com/contest/1618/problem/C\nimport Control.Monad (replicateM)\nimport qualified Data.ByteString.Char8 as B\n\ngetOddPos [] = []\ngetOddPos [o] = [o]\ngetOddPos (o:e:xs) = o : getOddPos xs\ngetEvenPos [] = []\ngetEvenPos [o] = []\ngetEvenPos (o:e:xs) = e : getEvenPos xs\n\nmain = getLine >>= flip replicateM run . read\nrun = do\n n <- B.getLine\n numbers <- (read . B.unpack <$>) . B.words <$> B.getLine\n let\n oddList = getOddPos numbers\n evenList = getEvenPos numbers\n oddListGcd = foldl1 gcd oddList\n evenListGcd = foldl1 gcd evenList\n print $\n if not $ any(\\x->mod x evenListGcd == 0) oddList then evenListGcd else\n if not $ any(\\x->mod x oddListGcd == 0) evenList then oddListGcd else 0\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n void C.getLine\r\n xs <- readInts\r\n let (as, bs) = splitEvenOdd xs\r\n ag = foldl' gcd 0 as\r\n bg = foldl' gcd 0 bs\r\n ans | all ((/=0) . (`mod` ag)) bs = ag\r\n | all ((/=0) . (`mod` bg)) as = bg\r\n | otherwise = 0\r\n print ans\r\n\r\nsplitEvenOdd :: [a] -> ([a], [a])\r\nsplitEvenOdd = foldr (\\a ~(x, y) -> (a:y, x)) ([], [])\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "-- https://codeforces.com/contest/1618/problem/C\nimport Control.Monad (replicateM)\n\ngetOddPos [] = []\ngetOddPos [o] = [o]\ngetOddPos (o:e:xs) = o : getOddPos xs\ngetEvenPos [] = []\ngetEvenPos [o] = []\ngetEvenPos (o:e:xs) = e : getEvenPos xs\n\nmain = getLine >>= flip replicateM run . read\nrun = do\n n <- getLine\n numbers <- (read <$>) . words <$> getLine\n let\n oddList = getOddPos numbers\n evenList = getEvenPos numbers\n oddListGcd = foldl1 gcd oddList\n evenListGcd = foldl1 gcd evenList\n print $\n if not $ any(\\x->mod x evenListGcd == 0) oddList then evenListGcd else\n if not $ any(\\x->mod x oddListGcd == 0) evenList then oddListGcd else 0\n"}], "negative_code": [{"source_code": "-- https://codeforces.com/contest/1618/problem/C\nimport Control.Monad (replicateM)\n\ngetOddPos [] = []\ngetOddPos [o] = [o]\ngetOddPos (o:e:xs) = o : getOddPos xs\ngetEvenPos [] = []\ngetEvenPos [o] = []\ngetEvenPos (o:e:xs) = e : getEvenPos xs\n\nmain = getLine >>= flip replicateM run . read\nrun = do\n n <- getLine\n numbers <- (read <$>) . words <$> getLine\n let\n oddList = getOddPos numbers\n evenList = getEvenPos numbers\n oddListGcd = foldl1 gcd $ oddList\n evenListGcd = foldl1 gcd $ evenList\n biggerGcd = max oddListGcd evenListGcd\n print $ if any(\\x->mod x biggerGcd == 0) oddList && any(\\x->mod x biggerGcd == 0) evenList\n then 0\n else biggerGcd\n"}], "src_uid": "e6c91f6872c4dd845cb7a156aacab7c7"} {"source_code": "import Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>>\r\n chunksOf 2 >>>\r\n map (last >>> words >>> map read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs = n - maximum [l, r, m]\r\n where\r\n n = length xs\r\n check = liftA2 (&&) (/= 1) (/= n)\r\n l = length $ takeWhile check xs\r\n r = length $ takeWhile check $ reverse xs\r\n m = n - l - r - 2\r\n", "positive_code": [{"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n _n <- readLn :: IO Int\r\n readIListLn\r\n\r\nreadIListLn = map read <$> words <$> getLine :: IO [Int]\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve nums = show $ length nums - length nums3\r\n where\r\n mn = minimum nums\r\n mx = maximum nums\r\n\r\n fnd = [mn, mx]\r\n\r\n (v2, nums2) = g fnd nums\r\n\r\n fnd2 = filter (/= v2) fnd\r\n\r\n (_, nums3) = g fnd2 nums2\r\n\r\ng fnd nums = last . sortOn (length.snd) $ f <$> fnd <*> [nums, reverse nums]\r\n\r\nf _ [] = error \"impossible by condition\"\r\nf x (y:ys) | (x == y) = (x, ys)\r\n | otherwise = f x ys\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\nnElemIndex n xs = fromJust (elemIndex n xs)\r\n\r\nsolve l r n = minimum [x,y,z]\r\n where\r\n x = l + 1 + n - r\r\n y = r + 1\r\n z = n - l\r\n\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let i = nElemIndex (maximum a) a\r\n j = nElemIndex (minimum a) a\r\n print $ solve (min i j) (max i j) n\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintS = do \r\n n <- readLn::IO Int \r\n xs <- readInts \r\n let mini = head $ filter ((== minimum xs) . (xs !!)) [0..]\r\n maxi = head $ filter ((== maximum xs) . (xs !!)) [0..]\r\n let x = minimum [mini,maxi]\r\n y = maximum [mini,maxi]\r\n print $ minimum [y+1, n-x, x + 1 + n - y]\r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t printS"}, {"source_code": "makeInteger :: [String] -> [Int]\r\nmakeInteger = map read\r\n\r\nmain :: IO()\r\nmain = do\r\n line <- getLine\r\n let t = (read line::Int)\r\n solve_multitest t\r\n\r\nsolve_multitest :: Int -> IO()\r\nsolve_multitest 0 = return ()\r\nsolve_multitest t = do\r\n solve_test\r\n solve_multitest (t - 1)\r\n\r\nsolve_test :: IO()\r\nsolve_test = do\r\n line <- getLine\r\n let n = (read line::Int)\r\n line <- getLine\r\n let inparr = words line\r\n let arr = makeInteger inparr\r\n let x = find_index_k arr 1\r\n let y = find_index_k arr n\r\n let mnpos = min x y\r\n let mxpos = max x y\r\n let ans = min (min mxpos (n - mnpos + 1)) (mnpos + n - mxpos + 1)\r\n putStrLn (show ans)\r\n\r\nfind_index_k :: [Int] -> Int -> Int\r\nfind_index_k a k = do\r\n let x = head a\r\n if x == k then\r\n 1\r\n else\r\n find_index_k (drop 1 a) k + 1"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List(minimum,maximum)\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest' :: [Int] -> Int\ntest' a = minimum [res1, res2, res3]\n where\n n = length a\n f g = snd $ head $ filter ( (== g). fst) $ zip a [0 ..] \n u = f $ minimum a\n v = f $ maximum a\n u' = min u v\n v' = max u v\n res1 = 1 + v'\n res2 = n - u'\n res3 = 1 + u' + n - v'\n\nnl = char7 '\\r' <> char7 '\\n'\ntest :: Builder -> Int -> [Int] -> Builder\ntest buf 0 _ = buf\ntest buf nt (n:a) = test (buf <> intDec (test' b) <> nl) (pred nt) c\n where\n (b, c) = splitAt n a\n\nsolve :: [Int] -> Builder\nsolve (nt:xs) = test mempty nt xs\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}], "negative_code": [], "src_uid": "d5fc2bc618dd9d453a5e7ae30ccb73f3"} {"source_code": "import Control.Monad( replicateM)\nimport Control.Applicative( (<$>))\n\nmain = do\n n_ <- readLn\n let\n\treadPair = do\n\t [before, after] <- map read . words <$> getLine\n\t return (before, after)\n\n pairs_ <- replicateM n_ readPair::IO [(Int,Int)]\n let\n\tisDesc [] = True\n\tisDesc [_] = True\n\tisDesc (a:tl@(b:rem))\t| a>=b\t = isDesc tl\n\t\t\t\t| otherwise = False\n\t\n\t(befores, afters) = unzip pairs_\n\n\tsames = and $ zipWith (==) befores afters\n\n putStr $ if sames\n\t\tthen if isDesc befores\n\t\t\tthen \"maybe\"\n\t\t\telse \"unrated\"\n\t\telse \"rated\"\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.Functor\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine :: IO Int\n ps <- sequence $ replicate n $ (\\[a, b] -> (read a, read b)) . words <$> getLine :: IO [(Int, Int)]\n if any (uncurry (/=)) ps then\n putStr \"rated\"\n else if and $ zipWith (>=) ps $ tail ps then\n putStr \"maybe\"\n else\n putStr \"unrated\"\n return ()"}, {"source_code": "f::[String]->Bool\nf []=True\nf (s:str)=let (a:b:[])=words s\n in if a==b then f str else False\n\nf2::[String]->Bool\nf2 (s:[])=True\nf2 (s:s2:str)=let (a:b:[])=map read (words s)::[Int]\n (c:d:[])=map read (words s2)::[Int]\n in if a) . B.words\n\nsolve bas = if any (\\(b, a) -> b /= a) bas \n then Just True \n else if any (\\((_, a1), (_, a2)) -> a1 < a2) $ zip bas (tail bas) then Just False else Nothing\n\nmain = do \n n <- readInt <$> B.getLine\n bas <- replicateM n ((\\(b:a:_) -> (b,a)) . readInts <$> B.getLine)\n putStr $ maybe \"maybe\" (\\b -> if b then \"rated\" else \"unrated\") $ solve bas\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\n\ndata Status = Rated | Unrated | Unknown\n deriving (Show, Eq)\n\nratingChanged :: (Int, Int) -> Bool\nratingChanged (x, y) = x /= y\n\ntails :: [a] -> [[a]]\ntails [x] = [[x]]\ntails xss@(x:xs) = xss : tails xs\n\nsolve :: [(Int, Int)] -> Status\nsolve rs | haveChanges = Rated\n | haveMisplaces = Unrated\n | otherwise = Unknown\n where haveChanges = not . null . filter id $ map ratingChanged rs\n haveMisplaces = not . null . concat $ [filter (> x) ys | (x:ys) <- tails bs]\n bs = map fst rs\n\ntest0 = [(3060, 3060)\n , (2194, 2194)\n , (2876, 2903)\n , (2624, 2624)\n , (3007, 2991)\n , (2884, 2884)\n ] :: [(Int, Int)]\n\ntest1 = [ (1500, 1500)\n , (1300, 1300)\n , (1200, 1200)\n , (1400, 1400)\n ] :: [(Int, Int)]\n\ntest2 = [ (3123, 3123)\n , (2777, 2777)\n , (2246, 2246)\n , (2246, 2246)\n , (1699, 1699)\n ] :: [(Int, Int)]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n rs <- replicateM n $ do\n [a, b] <- map read . words <$> getLine\n return (a, b)\n putStrLn $ case solve rs of\n Rated -> \"rated\"\n Unrated -> \"unrated\"\n Unknown -> \"maybe\"\n"}], "negative_code": [], "src_uid": "88686e870bd3bfbf45a9b6b19e5ec68a"} {"source_code": "main = interact $ unlines . map solve . tail . lines\n\nsolve s = show $ foldl max 0 [ a * y\n , b * x\n , a * (b-y-1)\n , b * (a-x-1) ]\n where [a, b, x, y] = map (read :: String -> Int) (words s)\n\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Data.List\n\nmain = interact $\n lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> map show >>> unlines\n\nsolve :: [Integer] -> Integer\nsolve [a, b, x, y] = max ((max x (a - x - 1)) * b)\n ((max y (b - y - 1)) * a)"}, {"source_code": "\npop :: [a] -> (a, [a])\npop ([x]) = (x, [])\npop (x:xs) = (x, xs)\npop _ = undefined\n\ncal :: Int -> IO ()\ncal 0 = return ()\ncal n = do\n line <- getLine\n let xs = map (read :: String -> Int) $ words line\n let (a, x1) = pop xs\n let (b, x2) = pop x1\n let (x, x3) = pop x2\n let (y, x4) = pop x3\n let (x1, x2) = (x, a - 1 - x)\n let (y1, y2) = (y, b - 1 - y)\n let area = maximum [calArea (x1, b), calArea (x2, b),calArea (a, y1), calArea (a, y2)]\n putStrLn $ show area\n cal (n - 1)\n where calArea (w, h) = w * h\n\nmain :: IO ()\nmain = do\n a <- getLine\n let n = (read a) :: Int\n cal n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b,x,y] <- (map read.words) <$> getLine\n print $ solve a b x y\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve a b x y = max (xm*b) (ym*a)\n where\n x1=x\n x2=a-x-1\n xm=max x1 x2\n y1=y\n y2=b-y-1\n ym=max y1 y2\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\nonecase = do\n\t\t[r,c,x,y]<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet ml = max x (r-x-1)\n\t\tlet mw = max y (c-y-1)\n\t\tprint $ max (ml*c) (mw*r)\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\treplicateM_ n onecase\n\n"}, {"source_code": "maxOkayArea :: Int -> Int -> Int -> Int -> Int\nmaxOkayArea a b x y = max ((max x x') * b) ((max y y') * a)\n where\n x' = a - 1 - x\n y' = b - 1 - y\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- fmap readInt getLine\n s <- fmap (map (map readInt.words).lines) getContents\n putStrLn.unlines.map show.map (\\[a,b,x,y] -> maxOkayArea a b x y) $ s"}, {"source_code": "import Control.Monad\n\ndata Rect = Rect { l :: Int, r :: Int, b :: Int, t :: Int } deriving (Show)\n\nmain :: IO ()\nmain = do\n examples <- read <$> getLine :: IO Int\n _ <- forM (replicate examples ()) $ \\_ -> do\n [xMax, yMax, x, y] <- (\\str -> read <$> words str) <$> getLine :: IO [Int]\n putStrLn $ show $ solve xMax yMax x y\n return ()\n\narea :: Rect -> Int\narea (Rect l r b t) \n | (l <= r) && (b <= t) = (r - l + 1) * (t - b + 1)\n | otherwise = 0\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve xMax yMax x y = foldl1 max $ area <$> \n [ Rect 0 (xMax-1) 0 (y-1) -- bottom to Y\n , Rect 0 (x-1) 0 (yMax-1) -- left to X\n , Rect (x+1) (xMax-1) 0 (yMax-1) -- right to X\n , Rect 0 (xMax-1) (y+1) (yMax-1) -- top to Y\n ]\n \n"}], "negative_code": [{"source_code": "import Control.Monad\n\ndata Rect = Rect { l :: Int, r :: Int, b :: Int, t :: Int }\n\nmain :: IO ()\nmain = do\n examples <- read <$> getLine :: IO Int\n _ <- forM (replicate examples ()) $ \\_ -> do\n [xMax, yMax, x, y] <- (\\str -> read <$> words str) <$> getLine :: IO [Int]\n putStrLn $ show $ solve xMax yMax x y\n return ()\n\narea :: Rect -> Int\narea (Rect l r b t) \n | (l < r) && (b < t) = (r - l + 1) * (t - b + 1)\n | otherwise = 0\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve xMax yMax x y = foldl1 max $ area <$> \n [ Rect 0 (xMax-1) 0 (y-1)\n , Rect 0 (x-1) 0 (yMax-1)\n , Rect (x+1) (xMax-1) 0 (yMax-1)\n , Rect 0 (xMax-1) (y+1) (yMax-1)\n ]\n \n"}], "src_uid": "ccb7b8c0c389ea771f666c236c1cba5f"} {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n", "positive_code": [{"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n m <- readInt\n grid <- replicateM n (BS.unpack <$> readString)\n return (n, m, grid)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nmodulo = 1000003\n\nnewtype ModP = ModP Integer deriving Eq\n\ninstance Show ModP where\n show (ModP a) = show a\n\ninstance Num ModP where\n ModP a + ModP b = ModP $ (a + b) `mod` modulo\n ModP a - ModP b = ModP $ (a - b) `mod` modulo\n ModP a * ModP b = ModP $ (a * b) `mod` modulo\n signum = undefined\n abs = undefined\n fromInteger = ModP . (`mod` modulo)\n\nsolve (n, m, grid)\n | isConflict = 0\n | otherwise = fromInteger 2 ^ frees :: ModP\n where\n lst = concat [ map (process (i, j)) (getD cij)\n | (i, row) <- zip [0..] grid\n , (j, cij) <- zip [0..] row\n ]\n\n process (x, y) L = (x, even y)\n process (x, y) R = (x, odd y)\n process (x, y) U = (n + y, even x)\n process (x, y) D = (n + y, odd x)\n\n arr = accumArray merge None (0, n + m - 1) lst :: Array Int Info\n\n answer = elems arr\n\n isConflict = any (==Conflict) answer\n frees = length $ filter (==None) answer\n\n merge (Unique bool) b\n | bool == b = Unique bool\n | otherwise = Conflict\n\n merge Conflict _ = Conflict\n merge None x = Unique x\n\ndata Direction = L | R | U | D deriving (Show, Eq)\n\ndata Info = None\n | Unique Bool\n | Conflict deriving (Show, Eq)\n\ngetD '1' = [L, U]\ngetD '2' = [L, D]\ngetD '3' = [R, D]\ngetD '4' = [R, U]\ngetD _ = []\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nnewtype I=I Int deriving (Show, Eq, Ord)\nmmm :: Integral a => a -> a\nmmm x=x `mod` 1000003\n\ninstance Num I where\n I x+I y=I(mmm$x+y)\n I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y\n | otherwise = I $ fromInteger $ mmm $ \n (fromIntegral x :: Integer) * fromIntegral y\n fromInteger n = I $ fromInteger $ mmm n\n\ninstance Real I\ninstance Enum I\ninstance Integral I where\n toInteger (I i) = toInteger i\n\n\ns1 :: (Char -> Bool) -> [Char] -> I\ns1 is1 l = goN l where \n goN [] = 2\n goN ('.':t) = goN t\n goN (some:t) = goS (not $ is1 some) t\n goS need1 [] = 1\n goS need1 ('.':t) = goS (not need1) t\n goS need1 (some:t) | is1 some /= need1 = 0\n | 1>0 = goS (not need1) t\n\nsolve s = product (map (s1 ((||) <$> (=='1') <*> (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2'))) s)\n\nss = show . toInteger . solve\nmain=interact$ss.tail.lines"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l=length$filter(all(\\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]\ns s=foldr1(((`mod`1000003).).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Applicative\n\nnewtype I=I Int deriving (Show, Eq, Ord)\nmmm :: Integral a => a -> a\nmmm x=x `mod` 1000003\n\ninstance Num I where\n I x+I y=I(mmm$x+y)\n I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y\n | otherwise = I $ mmm $ fromInteger $ \n (fromIntegral x :: Integer) * fromIntegral y\n fromInteger n = I $ fromInteger $ mmm n\n\ninstance Real I\ninstance Enum I\ninstance Integral I where\n toInteger (I i) = toInteger i\n\n\ns1 :: (Char -> Bool) -> [Char] -> I\ns1 is1 l = goN l where \n goN [] = 2\n goN ('.':t) = goN t\n goN (some:t) = goS (not $ is1 some) t\n goS need1 [] = 1\n goS need1 ('.':t) = goS (not need1) t\n goS need1 (some:t) | is1 some /= need1 = 0\n | 1>0 = goS (not need1) t\n\nsolve s = product (map (s1 ((||) <$> (=='1') <*> (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2'))) s)\n\nmain=interact$show . toInteger . solve . tail . lines"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nnewtype I=I Int deriving (Show, Eq)\nmmm :: Integral a => a -> a\nmmm x=x `mod` 1000003\n\ninstance Num I where\n I x+I y=I(mmm$x+y)\n I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y\n | otherwise = I $ mmm $ fromInteger $ \n (fromIntegral x :: Integer) * fromIntegral y\n fromInteger n = I $ fromInteger $ mmm n\n\n\ns1 :: (Char -> Bool) -> [Char] -> I\ns1 is1 l = goN l where \n goN [] = 2\n goN ('.':t) = goN t\n goN (some:t) = goS (not $ is1 some) t\n goS need1 [] = 1\n goS need1 ('.':t) = goS (not need1) t\n goS need1 (some:t) | is1 some /= need1 = 0\n | 1>0 = goS (not need1) t\n\nsolve s = product (map (s1 ((||) <$> (=='1') <*> (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2'))) s)\n\nmain=interact$show . solve . tail . lines"}, {"source_code": "import Data.List\nimport Control.Applicative\n\ns1 is1 l = goN l where \n goN [] = 2\n goN ('.':t) = goN t\n goN (some:t) = goS (not $ is1 some) t\n goS need1 [] = 1\n goS need1 ('.':t) = goS (not need1) t\n goS need1 (some:t) | is1 some /= need1 = 0\n | 1>0 = goS (not need1) t\n\nsolve s = product (map (s1 ((||) <$> (=='1') <*> (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2'))) s)\n\nmain=interact$show . solve . tail . lines"}, {"source_code": "import Data.List\nc=cycle[1>0,0>1]\nz h l = length$filter(o l)[c,tail c]where o=(all g.).zip;g(a,c)=a=='.'||c==(a`elem`h)\ns s=foldr1((.(`mod`1000003)).(*))$z\"14\"`map`transpose s++z\"12\"`map`s\nmain=interact$show.s.tail.lines\n"}], "src_uid": "07cbcf6e1f1e7f1a6ec45241cf9ac2a9"} {"source_code": "xor :: Bool -> Bool -> Bool\nxor a b = a && not b || b && not a\n\ndoit :: [Int] -> Bool -> Bool\ndoit [] last = not last\ndoit (x:xs) last\n\t| last && x == 0 = False\n\t| otherwise = doit xs $ last `xor` (x `mod` 2 == 1)\n\nmain = do\n\tgetLine\n\ta <- getLine >>= return . map read . words\n\tputStrLn $ if doit a False then \"YES\" else \"NO\"", "positive_code": [{"source_code": "import Data.List\nimport Data.Array\n\nmain = do\n getLine\n aStr <- getLine\n putStrLn $\n if solve $ map (read :: String -> Int) (words aStr)\n then \"YES\"\n else \"NO\"\n\nsolve a = dp n 0\n where\n n = length a\n a' = listArray (1, n) a\n\n dp :: Int -> Int -> Bool\n dp 0 0 = True\n dp 0 1 = False\n dp i 0 = dps ! (i-1, (a' ! i) `mod` 2)\n dp i 1 = if (a' ! i) `mod` 2 == 0\n then (if (a' ! i) /= 0 then dps ! (i-1, 1) else False)\n else dps ! (i-1, 0)\n\n dps = listArray bounds [dp i j | (i, j) <- range bounds]\n bounds = ((0, 0), (n, 1))\n"}, {"source_code": "import Data.List.Split\n\nsolve :: [Int] -> Bool\nsolve [] = True\nsolve [x] = even x && x >= 0\nsolve (x:y:nums)\n | x < 0 = False\n | even x = solve (y:nums)\n | otherwise = solve ((y-1):nums)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n line <- getLine\n let nums = map read $ splitOn \" \" line\n putStrLn $ if solve nums then \"YES\" else \"NO\"\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: Bool -> [Int] -> Bool\n solve acc [] = acc\n solve True (x:xs)\n | x `mod` 2 == 0 = solve True xs\n | x `mod` 2 == 1 = solve False xs\n solve False (0:xs) = False\n solve False (1:xs) = solve True xs\n solve False (x:xs)\n | x `mod` 2 == 0 = solve False xs\n | x `mod` 2 == 1 = solve True xs\n\n\n getOutput :: Bool -> String\n getOutput True = \"YES\"\n getOutput False = \"NO\"\n\n main :: IO()\n main = do\n n <- getLine\n xs <- getLine >>= return . map readInt . words\n let canDo = solve True xs\n putStrLn $ getOutput canDo\n"}, {"source_code": "import Control.Applicative\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\n\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n putStrLn.bool\"NO\"\"YES\" $ solve xs\n\nsolve :: [Int] -> Bool\nsolve xs = all isValid $ split xs\n where\n isValid (x:xs) | even x = isValid xs\n isValid (x:y:xs) = isValid $ (y-1):xs\n isValid (_:_) = False\n isValid [] = True\n\nsplit :: [Int] -> [[Int]]\nsplit xs = case span (0/=) xs of\n (ys, 0:zs) -> ys : split zs\n (ys, []) -> [ys]\n _ -> undefined"}], "negative_code": [], "src_uid": "97697eba87bd21ae5c979a5ea7a81cb7"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n \r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport qualified Data.IntMap as M\r\nimport Control.Monad (replicateM_, replicateM)\r\nimport Data.Maybe (fromMaybe, fromJust)\r\n\r\ninf = 2*10^9\r\n\r\naccTemp :: [Integer] -> [Integer]\r\naccTemp acs = [] where\r\n calcTemp minprev ac = min (minprev + 1) ac\r\n\r\n\r\nsolve :: Int -> M.IntMap Integer -> [Integer]\r\nsolve n acMap = zipWith min l r where\r\n find x = M.findWithDefault inf x acMap\r\n acs = map find [1..n]\r\n calcTemp minprev ac = min (minprev + 1) ac\r\n l = scanl1 calcTemp acs\r\n r = reverse $ scanl1 calcTemp $ reverse acs\r\n\r\n\r\n-- IO from https://github.com/byorgey/comprog-hs/blob/master/Scanner.hs\r\ntype Scanner = State [C.ByteString]\r\n \r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n \r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n \r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n \r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n \r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n \r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nsolveCase :: Scanner [Integer]\r\nsolveCase = do\r\n (n, k) <- pair int int\r\n pos <- replicateM k int\r\n temp <- replicateM k integer\r\n return $ solve n $ M.fromList (zip pos temp)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> solveCase) ) >>> C.unlines\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- q <- readLn \r\n-- replicateM_ q $ do\r\n-- getLine \r\n-- [n, _] <- map read . words <$> getLine :: IO [Int] \r\n-- pos <- map read . words <$> getLine :: IO [Int] \r\n-- temp <- map read . words <$> getLine :: IO [Integer]\r\n-- let ans = solve n $ M.fromList (zip pos temp)\r\n-- putStrLn $ unwords $ map show ans", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n \r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport qualified Data.IntMap as M\r\nimport Control.Monad (replicateM)\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromMaybe, fromJust)\r\n\r\ninf = 2*10^9\r\n\r\naccTemp :: [Integer] -> [Integer]\r\naccTemp acs = [] where\r\n calcTemp minprev ac = min (minprev + 1) ac\r\n\r\nfillList :: Ord a => Int -> a -> [(Int, a)] -> [a]\r\nfillList n fillVal = go n . sort where\r\n go 0 _ = []\r\n go i [] = fillVal : go (i - 1) []\r\n go i vals@((j, x) : xs) = if n - i + 1 == j\r\n then x : go (i - 1) xs\r\n else fillVal : go (i - 1) vals\r\n\r\n\r\nsolve :: Int -> [Int] -> [Integer ] -> [Integer]\r\nsolve n pos temp = zipWith min l r where\r\n acs = fillList n inf $ zip pos temp\r\n calcTemp minprev ac = min (minprev + 1) ac\r\n l = scanl1 calcTemp acs\r\n r = reverse $ scanl1 calcTemp $ reverse acs\r\n\r\n\r\n-- IO from https://github.com/byorgey/comprog-hs/blob/master/Scanner.hs\r\ntype Scanner = State [C.ByteString]\r\n \r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n \r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n \r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n \r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n \r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n \r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nsolveCase :: Scanner [Integer]\r\nsolveCase = do\r\n (n, k) <- pair int int\r\n pos <- replicateM k int\r\n temp <- replicateM k integer\r\n return $ solve n pos temp\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> solveCase) ) >>> C.unlines\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- q <- readLn \r\n-- replicateM_ q $ do\r\n-- getLine \r\n-- [n, _] <- map read . words <$> getLine :: IO [Int] \r\n-- pos <- map read . words <$> getLine :: IO [Int] \r\n-- temp <- map read . words <$> getLine :: IO [Integer]\r\n-- let ans = solve n $ M.fromList (zip pos temp)\r\n-- putStrLn $ unwords $ map show ans"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromMaybe, fromJust)\r\n\r\n-- https://github.com/byorgey/comprog-hs/blob/master/ScannerBS.hs\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> testCase)) >>> C.unlines\r\n\r\ntestCase :: Scanner [Int]\r\ntestCase = do\r\n (n, k) <- pair int int\r\n as <- replicateM k int\r\n ts <- replicateM k int\r\n return $ solve [[n, k], as, ts]\r\n\r\nsolve :: [[Int]] -> [Int]\r\nsolve [[n, k], as, ts] = zipWith min (compute xs) (reverse . compute . reverse $ xs)\r\n where\r\n xs = tail . snd . foldr upd (n + 1, []) . sort $ ((0, 0) : zip as ts)\r\n upd (a, t) (i, xs) = (a, t : replicate (i - a - 1) inf ++ xs)\r\n inf = 2 * 10 ^ 9\r\n\r\ncompute :: [Int] -> [Int]\r\ncompute = scanl1 (\\p x -> min (p + 1) x)\r\n"}], "negative_code": [], "src_uid": "16bd6786078dbaa443e97eec581cff73"} {"source_code": "import Control.Monad\n\nreadInts :: IO [Int]\nreadInts = do\n ls <- fmap words getLine\n return $ map read ls\n\nmain = do\n [n] <- readInts\n replicateM_ n $ do\n [a,b] <- readInts\n print $ solve a b\n\nsolve a b\n | a == b = 0\n | a > b = if mod (a-b) 2 == 0 then 1 else 2\n | a < b = if mod (b-a) 2 == 1 then 1 else 2\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n \ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [x, y] <- getIntList\n print $ f x y\n\nf :: Int -> Int -> Int\nf x y\n | x == y = 0\n | or [(sameP x y) && (x > y), not (sameP x y) && (x < y)] = 1\n | otherwise = 2\n\nsameP :: Int -> Int -> Bool\nsameP x y = odd x == odd y"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(a:b:_) -> solve a b).map read.words >> test (n - 1)\n\nsolve a b\n\t| a == b = 0\n\t| even (a - b) = 1 + fromEnum (a < b)\n\t| otherwise = 1 + fromEnum (a > b)\n\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b] <- (map read.words) <$> getLine\n print $ solve (a-b)\n\nsolve :: Int -> Int\nsolve 0 = 0\nsolve n\n {-|n>=8 = (n `div` 8) + solve (n `mod` 8)\n |n<=(-9) = (n `div` (-9)) + solve (n `mod` (-9))-}\n |(n>0) && even n = 1\n |(n<0) && odd n = 1\n |otherwise = 2\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, b) <- liftM2 (,) get get\n putln $ f2 a b\n\nf2 :: Int64 -> Int64 -> Int\nf2 a b = if b > a then\n if (mod (b - a) 2) == 1 then\n 1\n else\n 2\n else\n if b < a then\n if (mod (b - a) 2) == 1 then\n 2\n else\n 1\n else\n 0\n"}, {"source_code": "import Control.Monad (replicateM_)\n\nsolve :: Int -> Int -> Int\nsolve x y | x == y = 0\n | x < y && x `mod` 2 /= y `mod` 2 = 1\n | x > y && x `mod` 2 == y `mod` 2 = 1\n | otherwise = 2\n\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (getLine >>= print . (\\[x,y] -> solve x y) . map read . words)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nprocess a b | a==b = 0\n | b>a && odd (b-a) =1 \n\t | b>a = 2\n\t | a>b && even (b-a) = 1\n\t | otherwise = 2\n\n\n\nonecase = do\n\t\t[a,b]<- map read <$> words <$> getLine:: IO [Int]\n\t\tprint $ process a b\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int \n\t\treplicateM_ n onecase\n"}, {"source_code": "--ghc 7.10\n\ncountMoves :: (Integral a) => (a,a) -> a\ncountMoves (a,b)\n | a < b = 1 + e\n | a > b = 2 - e\n | otherwise = 0\n where e = if even (a-b) then 1 else 0\n\nreadPair :: String -> (Int,Int)\nreadPair str = (a,b)\n where [a,b] = map read . words $ str\n \nmain = do\n nStr <- getLine\n contents <- getContents\n let qPairs = map readPair . lines $ contents\n sequence . map print $ map countMoves qPairs\n"}, {"source_code": "solve :: Int -> Int -> Int\nsolve a b\n | a == b = 0\n | b > a && odd (b-a) = 1\n | b > a && even (b-a) = 2\n | b < a && odd (a-b) = 2\n | b < a && even (a-b) = 1\n\nparse :: String -> String\nparse line = show $ solve a b\n where [a, b] = map (\\x -> read x :: Int) $ words line\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "negative_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b] <- (map read.words) <$> getLine\n print $ solve (a-b)\n\nsolve :: Int -> Int\nsolve 0 = 0\nsolve n\n |n>=8 = (n `div` 8) + solve (n `mod` 8)\n |n<=(-9) = (n `div` (-9)) + solve (n `mod` (-9))\n |(n>0) && even n = 1\n |(n<0) && odd n = 1\n |otherwise = 2\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nprocess a b | a==b = 0\n | even a && b>a = 1\n\t | even a = 2\n\t | odd a && a words <$> getLine:: IO [Int]\n\t\tprint $ process a b\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int \n\t\treplicateM_ n onecase\n"}], "src_uid": "fcd55a1ca29e96c05a3b65b7a8103842"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\ngetInts = map ( read :: String -> Int ) . words <$> getLine\n\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ h, w ] <- getInts\n\trows <- replicateM h getInts\n\n\tlet\n\t\tmirrors rs\n\t\t\t| length rs < h = mirrors $ rs ++ reverse rs\n\t\t\t| otherwise = rs\n\n\tprint $ head $ filter ( ( == rows ) . mirrors . ( flip take rows ) ) [ 1 .. h ]\n", "positive_code": [{"source_code": "input :: Int -> [String] -> IO ([String])\ninput 0 acc = return acc\ninput n acc = do\n r <- getLine\n input (n-1) (r:acc)\n\nsymmetric matrix | odd (length matrix) = False\n | otherwise = (top == reverse bottom)\n where\n top = take (div n 2) matrix\n bottom = drop (div n 2) matrix\n n = length matrix\n\nfold :: [String] -> Int\nfold matrix | symmetric matrix = fold (take (div (length matrix) 2) matrix)\n | otherwise = length matrix\n\n\nmain = do\n s <- getLine\n let n = read (head (words s)) ::Int\n matr <- (input n [])\n print (fold matr)"}, {"source_code": "import Control.Monad\n\n\nsolve :: [[Int]] -> Int\n\nsolve m | odd rowCount = rowCount\n | upperPart == reverse lowerPart = solve upperPart\n | otherwise = rowCount\n\n where rowCount = length m\n upperPart = take (rowCount `div` 2) m\n lowerPart = drop (rowCount `div` 2) m\n\n\nmain = do\n [n,m] <- fmap (map read . words) getLine\n as <- forM [1..n] (\\_ -> fmap (map read . words) getLine)\n print $ solve as\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nhash :: [Int] -> Integer\nhash [] = 0\nhash (x:xs) = (fi x + 12347 * hash xs) `mod` 0x3de1f1ed\n\nsolve :: (Eq a) => [a] -> Int\nsolve xs = case n `quotRem` 2 of\n\t(k,0) -> let (x1, x2) = splitAt k xs in\n\t\tif reverse x1 == x2 then solve x2 else n\n\t_ -> n\n\twhere n = length xs\n\nmain :: IO ()\nmain = do\n\t[n,_] <- inputInts\n\tmat <- replicateM n (hash <$> inputInts)\n\tprint $ solve mat\n"}], "negative_code": [], "src_uid": "90125e9d42c6dcb0bf3b2b5e4d0f845e"} {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: Int -> Int -> String\nsolve 0 m = replicate m 'G'\nsolve n 0 = replicate n 'B'\nsolve n m \n | n > m = 'B' : 'G' : solve (n - 1) (m - 1)\n | otherwise = 'G' : 'B' : solve (n - 1) (m - 1)\n\nmain :: IO ()\nmain = do\n [n, m] <- liftM (map read . words) (readFile \"input.txt\")\n writeFile \"output.txt\" $ solve n m", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport System.IO\n\nmain = do\n\n hin <- openFile \"input.txt\" ReadMode\n hout <- openFile \"output.txt\" WriteMode\n\n [n,m] <- map read.words <$> hGetLine hin\n\n if n>m\n then hPutStrLn hout $ ([1..m]>>\"BG\")++replicate (n-m) 'B'\n else hPutStrLn hout $ ([1..n]>>\"GB\")++replicate (m-n) 'G'\n\n hClose hin\n hClose hout\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport System.IO\n\nmain = do\n\n hin <- openFile \"input.txt\" ReadMode\n hout <- openFile \"output.txt\" WriteMode\n\n [n,m] <- map read.words <$> hGetLine hin\n\n if n>m\n then hPutStrLn hout $ ([1..m]>>\"BG\")++replicate (n-m) 'B'\n else hPutStrLn hout $ ([1..n]>>\"GB\")++replicate (n-m) 'G'\n\n hClose hin\n hClose hout\n"}], "src_uid": "5392996bd06bf52b48fe30b64493f8f5"} {"source_code": "{-# LANGUAGE BangPatterns, Strict #-}\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go !i !l !r \"\" !ms\r\n | 2 * (max r l) == i = \"\"\r\n | otherwise = ms\r\n go !i !l !r !s@(c : cs) !ms\r\n -- | 2 * (max l r) == length ms = \"\"\r\n | i `mod` 2 == 0 && r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | i `mod` 2 /= 0 && r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve !str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n !str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nmain = do\r\n getLine\r\n interact solveAll", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, Strict #-}\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go !i !l !r \"\" !ms\r\n | 2 * r == i = \"\"\r\n | 2 * l == i = \"\"\r\n | otherwise = ms\r\n go !i !l !r !s@(c : cs) !ms\r\n -- | 2 * (max l r) == length ms = \"\"\r\n | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve !str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n !str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nmain = do\r\n getLine\r\n interact solveAll"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go !i !l !r \"\" !ms\r\n | 2 * r == i = \"\"\r\n | 2 * l == i = \"\"\r\n | otherwise = ms\r\n go !i !l !r !s@(c : cs) !ms\r\n -- | 2 * (max l r) == length ms = \"\"\r\n | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve !str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n !str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nmain = do\r\n getLine\r\n interact solveAll"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go i l r \"\" ms\r\n | 2 * r == i = \"\"\r\n | 2 * l == i = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) !ms\r\n -- | 2 * (max l r) == length ms = \"\"\r\n | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nmain = do\r\n getLine\r\n interact solveAll"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\np str = (lines str) !! 111\r\n\r\nmain = do\r\n s <- getLine\r\n let n = read s :: Int\r\n if n < 500 then interact solveAll else interact p\r\n --interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | r > 0 && i == 2 * r + 1 && l < r + 1 = go i r (r + 1) s (repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nrepXL :: Int -> String -> String\r\nrepXL i str = (map conv (take i str)) ++ (drop i str)\r\n where\r\n conv '?' = '('\r\n conv x = x\r\n\r\nmain = do\r\n getLine\r\n interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | r > 0 && i == 2 * r + 1 && i < r + 1 = go i r (r + 1) s (repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nrepXL :: Int -> String -> String\r\nrepXL i str = (map conv (take i str)) ++ (drop i str)\r\n where\r\n conv '?' = '('\r\n conv x = x\r\n\r\nmain = do\r\n getLine\r\n interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\np str = (lines str) !! 85\r\n\r\nmain = do\r\n s <- getLine\r\n let n = read s :: Int\r\n if n < 500 then interact solveAll else interact p\r\n --interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\np str = (lines str) !! 86\r\n\r\nmain = do\r\n s <- getLine\r\n let n = read s :: Int\r\n if n < 500 then interact solveAll else interact p\r\n --interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | r > 0 && i == 2 * r + 1 = go i r (r + 1) s (repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nrepXL :: Int -> String -> String\r\nrepXL i str = (map conv (take i str)) ++ (drop i str)\r\n where\r\n conv '?' = '('\r\n conv x = x\r\n\r\nmain = do\r\n getLine\r\n interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | i > 0 && i == 2 * r + 1 = go i r (r + 1) s (repXL i ms)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nrepXL :: Int -> String -> String\r\nrepXL i str = (map conv (take i str)) ++ (drop i str)\r\n where\r\n conv '?' = '('\r\n conv x = x\r\n\r\nmain = do\r\n getLine\r\n interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\np str = (lines str) !! 451\r\n\r\nmain = do\r\n s <- getLine\r\n let n = read s :: Int\r\n if n < 500 then interact solveAll else interact p\r\n --interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nmain = do\r\n getLine\r\n interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nnLRXT :: String -> (Int, Int, Int, Int)\r\nnLRXT str = go (0, 0, 0, 0) str\r\n where\r\n go t \"\" = t\r\n go (!l, !r, !x, !t) (c : cs) = case c of\r\n '(' -> go (l + 1, r, x, t + 1) cs\r\n ')' -> go (l, r + 1, x, t + 1) cs\r\n '?' -> go (l, r, x + 1, t + 1) cs\r\n\r\nmaxFI :: String -> String\r\nmaxFI str = go 0 0 0 str str\r\n where\r\n go _ _ r \"\" ms\r\n | 2 * r == length ms = \"\"\r\n | otherwise = ms\r\n go !i !l !r s@(c : cs) ms\r\n | 2 * (max l r) == length ms = \"\"\r\n | i + 1 == 2 * r = go 0 0 0 s s\r\n | otherwise = case c of\r\n '(' -> go (i + 1) (l + 1) r cs ms\r\n ')' -> go (i + 1) l (r + 1) cs ms\r\n _ -> go (i + 1) l r cs ms\r\n\r\nsolveAll :: String -> String\r\nsolveAll = unlines . (map solve) . lines\r\n\r\nsolve :: String -> String\r\nsolve \"\" = \"YES\"\r\nsolve str = if b then \"YES\" else \"NO\"\r\n where\r\n --(tL, tR, tX, tT) = nLXRT str\r\n b = maxFI str' == \"\"\r\n str' = '(' : (init $ tail str) ++ \")\"\r\n\r\nmain = do\r\n getLine\r\n interact solveAll\r\n\r\n--s = take 3000000 $ cycle \"?()\""}], "src_uid": "e630243546bf46757ba1acdbdfd475c2"} {"source_code": "import Control.Monad (forM_)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n forM_ [1 .. t] $ \\_ -> do\r\n [x, n] <- map read . words <$> getLine\r\n let n' = case n `mod` 4 of\r\n 0 -> 0\r\n 1 -> n\r\n 2 -> -1\r\n _ -> - n - 1\r\n let x' = if even x then x - n' else x + n'\r\n print x'\r\n", "positive_code": [{"source_code": "import Data.Char\nimport qualified Data.Map as M\nimport System.IO\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d l = takeWhile (/= d) l : [dropWhile (/= d) l]\n\njump' :: Integer -> Integer -> Integer\njump' pos 0 = pos\njump' pos 1 = if even pos then pos -1 else pos + 1\njump' pos step\n | m2 == 0 =\n if even pos\n then\n if m4 == 0\n then pos\n else pos + 1\n else\n if m4 == 0\n then pos\n else pos - 1\n | even pos = if (step -1) `mod` 4 == 0 then pos - step else pos + step + 1\n | otherwise = if (step -1) `mod` 4 == 0 then pos + step else pos - step - 1\n where\n m2 = step `mod` 2\n m4 = step `mod` 4\n\njump :: String -> Integer\njump [] = 0\njump xs = jump' (read start) (read step)\n where\n start = head $ split ' ' xs\n step = last $ split ' ' xs\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve xs = map (show . jump) xs\n\nmain :: IO ()\nmain = do\n inputs <- getContents\n let lns = lines inputs\n putStr $ unlines $ solve $ tail lns\n"}, {"source_code": "{-\n (pos, delta)\n (0,1) -> (1,0) -> (1,1) -> (0,0) -> (0,1) ...\n (1,1) -> (0,0) -> (0,1) -> (1,0) -> (1,1) ...\n which mean if the init position is even, and the action list is (-1 +2 +3 -4), (-5 +6 +7 -8), ...\n and if the init position is odd, then the action list is (+1 -2 -3 +4), (+5 -6 -7 +8), ...\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nprocess 0 = return ()\nprocess t = do\n [a,b] <- getIntList\n let c = mod b 4\n let tmp = if c==0 then 0 else if c==1 then b else if c==2 then -1 else -b-1\n let res = if odd a then tmp else -tmp\n print (a+res)\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "{-\n (pos, delta)\n (0,1) -> (1,0) -> (1,1) -> (0,0) -> (0,1) ...\n (1,1) -> (0,0) -> (0,1) -> (1,0) -> (1,1) ...\n which mean if the init position is even, and the action list is (-1 +2 +3 -4), (-5 +6 +7 -8), ...\n and if the init position is odd, then the action list is (+1 -2 -3 +4), (+5 -6 -7 +8), ...\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nprocess 0 = return ()\nprocess t = do\n x <- getIntList\n let a = head x\n let b = head $ tail x\n let c = mod b 4\n let tmp = if c==0 then 0 else if c==1 then b else if c==2 then -1 else -b-1\n let res = if odd a then tmp else -tmp\n print (a+res)\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "solve :: Int -> Int -> Int\nsolve start n\n | even start =\n if mod n 4 == 0 then start\n else if mod n 4 == 1 then start - 1 - 4 * div n 4\n else if mod n 4 == 2 then start + 1\n else if mod n 4 == 3 then start + 4 + 4 * div n 4 else 0\n | mod n 4 == 0 = start\n | mod n 4 == 1 = start + 1 + 4 * div n 4\n | mod n 4 == 2 = start - 1\n | mod n 4 == 3 = start - 4 - 4 * div n 4\n | otherwise = 0\n\n\n\nrun 0 = return 0\nrun count = do\n line <- getLine\n let start = read (head (words line))\n let n = read (words line!!1)\n print(solve start n)\n run (count-1)\nmain = do\n n <- getLine\n let n' = read n\n run n'"}, {"source_code": "import Data.Foldable (for_)\r\nnext :: Int -> Int -> Int\r\nnext position jumpSize\r\n | even position = position - jumpSize\r\n | otherwise = position + jumpSize\r\n\r\nsolve :: Int -> Int -> Int\r\nsolve start jumps\r\n | m == 0 = start\r\n | otherwise = foldl next start [(jumps - m + 1)..jumps]\r\n where m = mod jumps 4\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n line <- getLine;\r\n let [start, jumps] = map read (words line);\r\n print $ solve start jumps;\r\n\r\nmain = do\r\n line <- getLine\r\n let nTestCases = read line :: Integer\r\n for_ [1..nTestCases] (const testCase)"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [x_0, n] <- map read . words <$> getLine\n let m = n - n `rem` 4\n print $ foldl next x_0 [m + 1 .. n]\n where\n next x i = if even x then x - i else x + i\n"}, {"source_code": "import Control.Monad\r\nimport Data.Int\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x, n] <- readInt64s\r\n let (p, q) = n `divMod` 4\r\n ans = case q of\r\n 0 -> 0\r\n 1 -> -4 * p - 1\r\n 2 -> 1\r\n _ -> 4 * (p + 1)\r\n print $ x + if even x then ans else -ans\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nreadInt64s :: IO [Int64]\r\nreadInt64s = map (fromInteger . fst . fromJust . C.readInteger) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "import Data.Char\nimport qualified Data.Map as M\nimport System.IO\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d l = takeWhile (/= d) l : [dropWhile (/= d) l]\n\njump' :: Integer -> Integer -> Integer\njump' pos 0 = pos\njump' pos 1 = if even pos then pos -1 else pos + 1\njump' pos step\n | m2 == 0 = if m4 == 0 then pos else pos + 1\n | even pos = if (step -1) `mod` 4 == 0 then pos - step else pos + step + 1\n | otherwise = if (step -1) `mod` 4 == 0 then pos + step else pos - step - 1\n where\n m2 = step `mod` 2\n m4 = step `mod` 4\n\njump :: String -> Integer\njump [] = 0\njump xs = jump' (read start) (read step)\n where\n start = head $ split ' ' xs\n step = last $ split ' ' xs\n\nsolve :: [String] -> [String]\nsolve [] = []\nsolve xs = map (show . jump) xs\n\nmain :: IO ()\nmain = do\n inputs <- getContents\n let lns = lines inputs\n putStr $ unlines $ solve $ tail lns\n"}], "src_uid": "dbe12a665c374ce3745e20b4a8262eac"} {"source_code": "import Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative ((<$>), liftA)\nimport Control.Monad (sequence, replicateM)\nimport Data.Map.Strict (Map, lookupLE, lookupGE)\nimport qualified Data.Map.Strict as M\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\ntype Roll = Map Int Int -> Map Int Int -> [Int]\n\nsolve :: Int -> [(Int, Int, Char)] -> [Int]\nsolve n a = foldr loop (\\_ _ -> []) a zero zero\n where\n zero = M.fromList [(0, n + 1), (n + 1, 0)] :: Map Int Int\n\n loop :: (Int, Int, Char) -> Roll -> Roll\n loop (c, r, 'U') f row col = x:f row col'\n where (x, col') = inner r c row col\n\n loop (c, r, 'L') f row col = x:f row' col\n where (x, row') = inner c r col row\n\n inner :: Int -> Int -> Map Int Int -> Map Int Int -> (Int, Map Int Int)\n inner r c row col\n | jkey == c = (0, col)\n | otherwise = (out, col')\n where\n (ikey, ival) = fromJust $ lookupLE r row :: (Int, Int)\n (jkey, jval) = fromJust $ lookupGE c col :: (Int, Int)\n out = if n + 1 < jkey + ival + ikey then r - ikey else jkey + jval - c\n col' = M.insert c out col :: Map Int Int\n\nparse :: ByteString -> (Int, Int, Char)\nparse line = (readInt c, readInt r, C8.head d)\n where\n [c, r, d] = C8.words line :: [ByteString]\n readInt :: ByteString -> Int\n readInt = fst . fromJust . C8.readInt\n\nmain = fromJust . sequence . fmap (liftA fst . C8.readInt) .C8.words <$>\n B.getLine >>= \\[n, q] -> replicateM q B.getLine >>= \\a ->\n mapM_ print . solve n $ parse <$> a\n", "positive_code": [{"source_code": "import Data.Maybe (fromJust)\nimport Control.Applicative ((<$>), liftA)\nimport Control.Monad (sequence, replicateM)\nimport Data.ByteString (ByteString)\nimport Data.Map (Map, lookupLE, lookupGE)\nimport qualified Data.Map as M\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\ntype Roll = Map Int Int -> Map Int Int -> [Int]\n\nsolve :: Int -> [(Int, Int, Char)] -> [Int]\nsolve n a = foldr loop (\\_ _ -> []) a zero zero\n where\n zero = M.fromList [(0, n + 1), (n + 1, 0)] :: Map Int Int\n\n loop :: (Int, Int, Char) -> Roll -> Roll\n loop (c, r, 'U') f row col = x:f row col'\n where (x, col') = inner r c row col\n\n loop (c, r, 'L') f row col = x:f row' col\n where (x, row') = inner c r col row\n\n inner :: Int -> Int -> Map Int Int -> Map Int Int -> (Int, Map Int Int)\n inner r c row col\n | jkey == c = (0, col)\n | otherwise = (out, col')\n where\n (ikey, ival) = fromJust $ lookupLE r row :: (Int, Int)\n (jkey, jval) = fromJust $ lookupGE c col :: (Int, Int)\n out = if n + 1 < jkey + ival + ikey then r - ikey else jkey + jval - c\n col' = M.insert c out col :: Map Int Int\n\nparse :: ByteString -> (Int, Int, Char)\nparse line = (readInt c, readInt r, C8.head d)\n where\n [c, r, d] = C8.words line :: [ByteString]\n readInt :: ByteString -> Int\n readInt = fst . fromJust . C8.readInt\n\nmain = sequence . fmap (liftA fst . C8.readInt) .C8.words <$> B.getLine >>=\n \\(Just [n, q]) -> replicateM q B.getLine >>=\n \\a -> mapM_ print . solve n $ parse <$> a\n"}], "negative_code": [], "src_uid": "870720d864ce169db2037f19f029719c"} {"source_code": "import Data.Bits\n-- import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Int as I\nmain = do\n line <- getLine\n let nk = words line\n let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)\n putStrLn (if (fst ans) then \"Yes\\n\" ++ (printList $ snd ans) else \"No\")\n\nprintList :: (Show a) => [a] -> String\nprintList (x:[]) = show x\nprintList (x:xs) = (show x) ++ \" \" ++ printList xs \n\nsolve :: I.Int64 -> Int -> (Bool, [Int])\nsolve 0 _ = (False, [])\nsolve n k\n | popCount n > k = (False, [])\n | otherwise = (True, toList (let dbg = expand 0 k (genList 0 n) in dbg) (0,0))\n\ngenList :: Int -> I.Int64 -> (M.Map Int Int)\ngenList p n = case n of\n 0 -> M.empty\n n -> case (n .&. 1::I.Int64) of\n 0 -> genList (p+1) (shiftR n 1)\n 1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)\n\nexpand :: Int -> Int -> M.Map Int Int -> M.Map Int Int\nexpand 0 k m = expand (M.size m) k m\nexpand s k m\n | k == s = m\n | otherwise = let num = M.findMax m in \n if (s + snd num) <= k then \n if M.member ((fst num)-1) m \n then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)\n else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)\n else let num2 = M.findMin m in\n if M.member ((fst num2)-1) m\n then expand (s+1) k $ M.adjust (+ 2) ((fst num2)-1) $ M.adjust (\\x->x-1) (fst num2) m\n else expand (s+1) k $ M.insert ((fst num2)-1) 2 $ M.adjust (\\x->x-1) (fst num2) m\n\ntoList :: M.Map Int Int -> (Int, Int) -> [Int]\ntoList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)\ntoList m (k, x) = k:toList m (k, x-1)\n", "positive_code": [{"source_code": "import Data.Bits\nimport Data.Maybe\n-- import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Int as I\nmain = do\n line <- getLine\n let nk = words line\n let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)\n putStrLn (if (fst ans) then \"Yes\\n\" ++ (printList $ snd ans) else \"No\")\n\nprintList :: (Show a) => [a] -> String\nprintList (x:[]) = show x\nprintList (x:xs) = (show x) ++ \" \" ++ printList xs \n\nsolve :: I.Int64 -> Int -> (Bool, [Int])\nsolve 0 _ = (False, [])\nsolve n k = if (popCount n) > k then (False, [])\n else (True, toList (expand 0 k (genList 0 n) ) (0,0))\n\ngenList :: Int -> I.Int64 -> (M.Map Int Int)\ngenList _ 0 = M.empty\ngenList p n = if (n .&. 1::I.Int64)==0 then genList (p+1) (shiftR n 1) else M.insert p 1 $ genList (p+1) (shiftR n 1)\n\nexpand :: Int -> Int -> M.Map Int Int -> M.Map Int Int\nexpand 0 k m = expand (M.size m) k m\nexpand s k m = if k == s then m\n else let num = M.findMax m\n newVal n x = if isNothing x then Just (2*n) else fmap (+2*n) x in\n if (s + snd num) <= k then \n expand (s+(snd num)) k $ M.alter (newVal (snd num)) ((fst num)-1) (M.deleteMax m)\n else let num2 = M.findMin m in\n expand (s+1) k $ M.alter (newVal 1) ((fst num2)-1) $ M.adjust (\\x->x-1) (fst num2) m\n\ntoList :: M.Map Int Int -> (Int, Int) -> [Int]\ntoList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)\ntoList m (k, x) = k:toList m (k, x-1)\n"}], "negative_code": [{"source_code": "import Data.Bits\n-- import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Int as I\nmain = do\n line <- getLine\n let nk = words line\n let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)\n putStrLn (if (fst ans) then \"Yes\\n\" ++ (printList $ snd ans) else \"No\")\n\nprintList :: (Show a) => [a] -> String\nprintList (x:[]) = show x\nprintList (x:xs) = (show x) ++ \" \" ++ printList xs \n\nsolve :: I.Int64 -> Int -> (Bool, [Int])\nsolve 0 _ = (False, [])\nsolve n k\n | popCount n > k = (False, [])\n | otherwise = (True, toList (let dbg = expand 0 k (genList 0 n) in dbg) (0,0))\n\ngenList :: Int -> I.Int64 -> (M.Map Int Int)\ngenList p n = case n of\n 0 -> M.empty\n n -> case (n .&. 1::I.Int64) of\n 0 -> genList (p+1) (shiftR n 1)\n 1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)\n\nexpand :: Int -> Int -> M.Map Int Int -> M.Map Int Int\nexpand 0 k m = expand (M.size m) k m\nexpand s k m\n | k == s = m\n | otherwise = let num = M.findMax m in \n if (s + snd num) <= k then \n if M.member ((fst num)-1) m \n then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)\n else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)\n else let num2 = M.findMin m in\n if (s + snd num2) <= k then \n if M.member ((fst num2)-1) m \n then expand (s+(snd num2)) k $ M.adjust (+2*(snd num2)) ((fst num2)-1) (M.deleteMin m)\n else expand (s+(snd num2)) k $ M.insert ((fst num2)-1) (2*(snd num2)) (M.deleteMin m)\n else let dif = k-s in\n if M.member ((fst num2)-1) m\n then expand (s+dif) k $ M.adjust (+ 2*dif) ((fst num2)-1) $ M.adjust (\\x->x-dif) (fst num2) m\n else expand (s+dif) k $ M.insert ((fst num2)-1) (2*dif) $ M.adjust (\\x->x-dif) (fst num2) m\n\ntoList :: M.Map Int Int -> (Int, Int) -> [Int]\ntoList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)\ntoList m (k, x) = k:toList m (k, x-1)\n"}, {"source_code": "import Data.Bits\n-- import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Int as I\nmain = do\n line <- getLine\n let nk = words line\n let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)\n putStrLn (if (fst ans) then \"Yes\\n\" ++ (printList $ snd ans) else \"No\")\n\nprintList :: (Show a) => [a] -> String\nprintList (x:[]) = show x\nprintList (x:xs) = (show x) ++ \" \" ++ printList xs \n\nsolve :: I.Int64 -> Int -> (Bool, [Int])\nsolve 0 _ = (False, [])\nsolve n k\n | popCount n > k = (False, [])\n | otherwise = (True, toList (let dbg = expand 0 k (genList 0 n) in dbg) (0,0))\n\ngenList :: Int -> I.Int64 -> (M.Map Int Int)\ngenList p n = case n of\n 0 -> M.empty\n n -> case (n .&. 1::I.Int64) of\n 0 -> genList (p+1) (shiftR n 1)\n 1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)\n\nexpand :: Int -> Int -> M.Map Int Int -> M.Map Int Int\nexpand 0 k m = expand (M.size m) k m\nexpand s k m\n | k == s = m\n | otherwise = let num = M.findMax m in \n if (s + snd num) <= k then \n if M.member ((fst num)-1) m \n then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)\n else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)\n else let num2 = M.findMin m in\n if (s + snd num2) <= k then \n if M.member ((fst num)-1) m \n then expand (s+(snd num2)) k $ M.adjust (+2*(snd num2)) ((fst num2)-1) (M.deleteMin m)\n else expand (s+(snd num2)) k $ M.insert ((fst num2)-1) (2*(snd num2)) (M.deleteMin m)\n else let dif = k-s in\n if M.member ((fst num2)-1) m\n then expand (s+dif) k $ M.adjust (+ 2*dif) ((fst num2)-1) $ M.adjust (\\x->x-dif) (fst num2) m\n else expand (s+dif) k $ M.insert ((fst num2)-1) (2*dif) $ M.adjust (\\x->x-dif) (fst num2) m\n\ntoList :: M.Map Int Int -> (Int, Int) -> [Int]\ntoList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)\ntoList m (k, x) = k:toList m (k, x-1)\n"}, {"source_code": "import Data.Bits\n-- import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Int as I\nmain = do\n line <- getLine\n let nk = words line\n let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)\n putStrLn (if (fst ans) then \"Yes\\n\" ++ (printList $ snd ans) else \"No\")\n\nprintList :: (Show a) => [a] -> String\nprintList (x:[]) = show x\nprintList (x:xs) = (show x) ++ \" \" ++ printList xs \n\nsolve :: I.Int64 -> Int -> (Bool, [Int])\nsolve 0 _ = (False, [])\nsolve n k\n | popCount n > k = (False, [])\n | otherwise = (True, toList (expand 0 k (let dbg=genList 0 n in dbg)) (0,0))\n\ngenList :: Int -> I.Int64 -> (M.Map Int Int)\ngenList p n = case n of\n 0 -> M.empty\n n -> case (n .&. 1::I.Int64) of\n 0 -> genList (p+1) (shiftR n 1)\n 1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)\n\nexpand :: Int -> Int -> M.Map Int Int -> M.Map Int Int\nexpand 0 k m = expand (M.size m) k m\nexpand s k m\n | k == s = m\n | otherwise = let num = M.findMax m in \n if (s + snd num) <= k then \n if M.member ((fst num)-1) m \n then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)\n else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)\n else let dif = k-s in\n if M.member ((fst num)-1) m\n then expand (s+dif) k $ M.adjust (+ 2*dif) ((fst num)-1) $ M.adjust (\\x->x-dif) (fst num) m\n else expand (s+dif) k $ M.insert ((fst num)-1) (2*dif) $ M.adjust (\\x->x-dif) (fst num) m\n\ntoList :: M.Map Int Int -> (Int, Int) -> [Int]\ntoList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)\ntoList m (k, x) = k:toList m (k, x-1)\n"}], "src_uid": "39e4bae5abbc0efac5316bec0d540665"} {"source_code": "{-# LANGUAGE TypeInType #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\nimport GHC.TypeLits\r\n\r\nnewtype ModVal a (n :: Nat)= ModVal { unMod :: a} deriving (Show, Eq)\r\n\r\nmodBase :: KnownNat n => ModVal a n -> Integer\r\n{-# INLINE modBase #-}\r\nmodBase v = natVal v\r\n\r\ninstance (Integral a, KnownNat n) => Num (ModVal a n) where\r\n ma@(ModVal a) + (ModVal b) =\r\n let\r\n m = fromIntegral $ modBase ma\r\n c = a + b\r\n in ModVal $ if c >= m then c - m else c\r\n ma@(ModVal a) - (ModVal b) =\r\n let\r\n m = fromIntegral $ modBase ma\r\n c = a - b\r\n in ModVal $ if c < 0 then c + m else c\r\n ma@(ModVal a) * (ModVal b) =\r\n let m = fromIntegral $ modBase ma in ModVal$ (a * b) `mod` m\r\n negate ma@(ModVal a) = let m = fromIntegral $ modBase ma in ModVal (m - a)\r\n abs = id\r\n signum _ = ModVal 1\r\n fromInteger x = toMod (ModVal 0) $ fromIntegral x\r\n where\r\n toMod :: (Integral a, KnownNat n) => ModVal a n -> a -> ModVal a n\r\n toMod m x = ModVal $ mod x $ fromIntegral $ modBase m\r\n {-# INLINE (+) #-}\r\n {-# INLINE (-) #-}\r\n {-# INLINE (*) #-}\r\n {-# INLINE abs #-}\r\n {-# INLINE signum #-}\r\n {-# INLINE fromInteger #-}\r\n\r\ntype MI = ModVal Int 998244353\r\n\r\npmod = 998244353\r\ntableSize :: Int\r\ntableSize = 10^5\r\nfac :: Array Int MI\r\nfac = listArray (0, tableSize) $ scanl' (*) (fromIntegral 1) $ map fromIntegral $ [1..tableSize]\r\ninvMod = (^(pmod-2))\r\n\r\ndata CountChess = CC !Int !Int deriving (Show, Eq, Ord)\r\n\r\ncountChess s c@(CC x y) = case s of\r\n [] -> c\r\n ('1':'1':xs) -> countChess xs $ CC x (y + 1)\r\n (k:xs) -> countChess xs $ CC (if k == '0' then x + 1 else x) y\r\n \r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInts 1\r\n ~[s] <- getNext 1\r\n let (CC n m) = countChess (P.unpack s) (CC 0 0)\r\n pure $! putInts . (:[]) $! unMod $ (fac!(n+m)) * (invMod $ fac!m) * (invMod $ fac!(n))\r\n \r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\ndata ZPos = ZPos !Int ![Int]\n\nstep :: ZPos -> Char -> ZPos\nstep (ZPos ix li) '0' = ZPos (ix + 1) (ix : li)\nstep (ZPos ix li) '1' = ZPos (ix + 1) li\nstep _ _ = error \"invalid input\"\n\ncompress :: Int -> Int -> Int\ncompress x y = if even (fromIntegral y - x)\n then x + 2\n else x + 1\n\np :: Int\np = 998244353\n\np64 :: Int64\np64 = fromIntegral p\n\nnewtype ModP = ModP Int\n\ninstance Num ModP where\n (ModP x) * (ModP y) = ModP $ fromIntegral\n $ rem (fromIntegral x * fromIntegral y) p64\n\ninv :: ModP -> ModP\ninv = (^ (p-2))\n\nchoose :: Int -> Int -> ModP\nchoose n k = let\n cstep w x = w * ModP (n + 1 - x) * inv (ModP x)\n in foldl' cstep (ModP 1) [1..k]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n s <- readLine\n let\n ZPos _n zpos = P.foldl' step (ZPos 1 []) s\n nzeros = length zpos\n cstop = foldl' compress 0 $ reverse zpos\n wiggle = div (n - cstop) 2\n ModP ans = choose (nzeros + wiggle) wiggle\n putInts [ans]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn, foldl')\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM, for)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\nimport GHC.IO.Handle (hDuplicateTo)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> fst . fromJust\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> fst . fromJust\n\n\npowerMd :: Int64 -> Int64 -> Int64 -> Int64\npowerMd md _ 0 = 1 `mod` md\npowerMd md a 1 = a `mod` md\npowerMd md a k\n | even k =\n let \n half :: Int64\n !half = powerMd md a (k `div` 2)\n\n sqrMd :: Int64 -> Int64 -> Int64\n sqrMd md x = (x ^ 2) `mod` md\n in\n sqrMd md half\n | odd k =\n let \n rest :: Int64\n !rest = powerMd md a (k - 1)\n in\n (a * rest) `mod` md\n\nfactorialMd :: Int64 -> Int64 -> Int64\nfactorialMd md 0 = 1 `mod` md\nfactorialMd md n = (`mod` md) . foldl' (\\a b -> (a * b) `mod` md) 1 $ [1 .. n]\n\ncalcCombinationsMd :: Int64 -> Int64 -> Int64 -> Int64\ncalcCombinationsMd md n k =\n (nFactorial * denominatorMdInv) `mod` md\n where\n nFactorial :: Int64\n nFactorial = factorialMd md n\n\n kFactorial :: Int64\n kFactorial = factorialMd md k\n\n n_kFactorial :: Int64\n n_kFactorial = factorialMd md (n - k)\n\n denominatorMdInv :: Int64\n denominatorMdInv = powerMd md ((kFactorial * n_kFactorial) `mod` md) (md - 2)\n\nsolve :: Int -> String -> Int64\nsolve n s =\n calcCombinationsMd md (zeroGroupsCnt + oneGroupsCnt) zeroGroupsCnt\n where\n md :: Int64\n md = 998_244_353\n\n oneGroupsCnt :: Int64\n oneGroupsCnt = fromIntegral . length . filter (== \"11\") $ sGroups\n\n zeroGroupsCnt :: Int64\n zeroGroupsCnt = fromIntegral . length . filter (== \"0\") $ sGroups\n\n sGroups :: [String]\n sGroups = calcGroups s\n\n calcGroups :: String -> [String]\n calcGroups ('1':'1':rest) = \"11\" : calcGroups rest\n calcGroups (x:rest) = [x] : calcGroups rest\n calcGroups [] = []\n\n\nmain :: IO ()\nmain = do\n tests <- B8.getLine <&> readIntB8\n replicateM_ tests $ do\n n <- B8.getLine <&> readIntB8\n s <- B8.getLine <&> B8.unpack . head . B8.words\n\n let answer = solve n s\n\n printf \"%lld\\n\" answer\n"}], "negative_code": [], "src_uid": "930b296d11d6d5663a14144a491f2c0a"} {"source_code": "\nimport IO\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestEmpty :: Test\ntestEmpty = Test \"TestEmpty\" $\n assertEq [] (solve' 2 [])\n\ntestOnePeople :: Test\ntestOnePeople = TestList \"TestOnePeople\"\n [\n Test \"TestOneFloor (1)\" $ assertEq 0 (solve 2 (1,1,0)),\n Test \"TestOneFloor (2)\" $ assertEq 1 (solve 2 (1,1,1)),\n Test \"TestOneFloor (3)\" $ assertEq 999 (solve 2 (1,1,999)),\n Test \"TestOneFloor (4)\" $ assertEq 0 (solve 2 (2,2,0)),\n Test \"TestUpFloor (1)\" $ assertEq 1 (solve 2 (1,2,0)),\n Test \"TestUpFloor (2)\" $ assertEq 2 (solve 3 (2,3,0)),\n Test \"TestUpFloor (3)\" $ assertEq 3 (solve 2 (1,2,2)),\n Test \"TestUpUpFloor\" $ assertEq 2 (solve 3 (1,3,0)),\n Test \"TestDownFloor (1)\" $ assertEq 2 (solve 2 (2,1,0)),\n Test \"TestDownFloor (2)\" $ assertEq 10 (solve 10 (10,9,0)),\n Test \"TestDownFloor (3)\" $ assertEq 4 (solve 3 (2,1,0)),\n Test \"TestDownDownFloor\" $ assertEq 11 (solve 10 (10,8,0)),\n Test \"TestToLastFloor\" $ assertEq (10^8 - 1) (solve (10^8) (1,10^8,0)),\n Test \"TestToFirstFloor (1)\" $ assertEq (2 * 10^8 - 2) (solve (10^8) (10^8,1,0)),\n Test \"TestToFirstFloor (2)\" $ assertEq (2 * 10^8 - 2) (solve (10^8) (10^8,1,10^8-1)),\n Test \"TestLatecomerUp\" $ assertEq 3 (solve 2 (1,2,1)),\n Test \"TestLatercomerDown\" $ assertEq 4 (solve 2 (2,1,2)),\n Test \"TestNotLatercomerDown\" $ assertEq 4 (solve 3 (2,1,3)),\n Test \"TestLongExpectationUp\" $ assertEq (10^8 - 1 + 2 * 10^8 - 2) (solve (10^8) (1,10^8,1)),\n Test \"TestDeepRecursiveUp\" $ assertEq 100000001 (solve 2 (1,2,10^8)),\n Test \"TestDeepRecursiveDown\" $ assertEq 100000002 (solve 2 (2,1,10^8)),\n Test \"TestLongExpectationDown\" $ assertEq (2 * (2 * 10^8 - 2)) (solve (10^8) (10^8,1,10^8))\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq [9, 1, 0, 7, 10, 7, 5]\n (solve' 4 [(2,4,3), (1,2,0), (2,2,0), (1,2,1), (4,3,5), (1,2,2), (4,2,0)]),\n Test \"2\" $ assertEq [12, 10, 10, 8, 7]\n (solve' 5 [(1,5,4), (1,3,1), (1,3,4), (3,1,5), (4,2,5)])\n ]\n\ntestBig :: Test\ntestBig = TestList \"TestBig\"\n [\n Test \"1\" $ assertEq (replicate n (m+1)) (solve' 2 (replicate n (1,2,m))),\n Test \"2\" $ assertEq (replicate n (2 * (2 * m - 2))) (solve' m (replicate n (m,1,m)))\n ]\n where\n n = 10^5\n m = 10^8\n\ntest :: IO ()\ntest = mapM_ run\n [\n testEmpty,\n testOnePeople,\n testInput,\n testBig\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve' :: Int -> [(Int, Int, Int)] -> [Int]\nsolve' n = map (solve n)\n\nsolve :: Int -> (Int, Int, Int) -> Int\nsolve n (s, f, time)\n | s < f && time < s = f - 1\n | s < f = period * (div time' period) + solve n (s, f, (mod time' period) - period') \n | s > f && time'' < period = period - f + 1\n | s > f = period * (div time'' period) + solve n (s, f, mod time'' period - period'')\n | otherwise = time\n where\n period = 2 * (n - 1) \n time' = time + period'\n period' = period - s \n time'' = time + period''\n period'' = s - 2\n\nreads :: IO [Int]\nreads = getLine >>= return . map read . words\n\nreadPeople :: IO (Int, Int, Int)\nreadPeople = do\n [a, b, c] <- Main.reads\n return (a, b, c)\n\nmain :: IO ()\nmain = do\n [n, m] <- Main.reads\n mapM_ (const (readPeople >>= print . (solve m))) [1..n]\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, m] <- liftM ( map read . words ) getLine :: IO [Int]\n replicateM_ n $ do\n [s, f, t] <- liftM ( map read . words ) getLine :: IO [Int]\n let k1 = ( t + (s-1) + 2 * (m-1) - 1 ) `div` ( 2 * (m-1) )\n k2 = ( t - (s-1) + 2 * (m-1) - 1 ) `div` ( 2 * (m-1) )\n t' = if s == f\n then t\n else if s < f\n then 2 * k2 * (m-1) + (s-1)\n else 2 * k1 * (m-1) - (s-1)\n putStrLn $ show $ t' + abs (f - s)\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.List\n\nprints [] = return ()\nprints (x:xs) = do print x; prints xs\n\nelevTimes m pos = [pos - 1, 2 * m - pos - 1] ++ [ 2 * (m-1) + x | x <- elevTimes m pos ]\n\nfirstElevTime m pos under = numCycle * elevCycle + (fromJust $ find ((<=) modCycle) (elevTimes m pos))\n\twhere\n\t\televCycle = 2 * (m-1)\n\t\tnumCycle = under `div` elevCycle\n\t\tmodCycle = under `mod` elevCycle\n\nsolve m [s,f,t]\n\t| s == f = t\n\t| otherwise = firstElevTime m f (firstElevTime m s t)\n\nmain = do\n\tinput <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n\tlet [n,m] = map (fst . fromJust . C.readInt) . C.words $ input !! 0\n\tlet info = map (map (fst . fromJust . C.readInt) . C.words) $ take n $ tail input\n\tprints $ map (solve m) info\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n m <- readInt\n peoples <- replicateM n $ do\n si <- readInt\n fi <- readInt\n ti <- readInt\n return (si, fi, ti)\n return (m, peoples)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (m, peoples) = BS.unlines [ BS.pack $ show (solveCase m p) | p <- peoples]\n\nsolveCase m (s, f, t)\n | s < f = solveCase' firstUp period t + (f - s)\n | s > f = solveCase' firstDown period t + (s - f)\n | otherwise = t\n where\n firstUp = s - 1\n firstDown = m - s + (m - 1)\n period = 2 * (m - 1)\n\nsolveCase' first period time = head $ dropWhile ( MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Data.Array\nimport Data.Char\nclass Expression a where scan' :: String -> a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\ndata Dir = Up|Down deriving (Eq,Show)\nrevd Up = Down\nrevd Down = Up\n\nsolve :: Int -> Int -> Int -> IO ()\nsolve c m n = do (s,f,t) <- scan :: IO (Int,Int,Int)\n let now = mod t c\n (nowstair,dir) = if nows)||(dir==Down&&nowstairs then 2*m-nowstair-s else s-nowstair\n else\n if nowstairf then 2*m-s-f else f-s\n else\n if s0=(t-s+c-1)`div`c*c+f where c=2*m;t=succ pt\ns([_,m]:l)=map(q m)l\nmain=interact$unlines.map show.s.map(map(pred.read).words).lines"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Data.Array\nimport Data.Char\nclass Expression a where scan' :: String -> a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\ndata Dir = Up|Down deriving (Eq,Show)\n\nsolve :: Int -> Int -> [(Int,Int,Int)] -> [Int]\nsolve _ _ [] = []\nsolve c m ((s,f,t):xs) = let now = mod (t+1) c\n (nowstair,dir) = if now<=m then (now,Up) else (c-now+2,Down)\n dist1 = if dir==Up then\n if nowstair>s then 2*m-nowstair-s else s-nowstair\n else\n if nowstairf then 2*m-s-f else f-s\n else\n if s a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\ndata Dir = Up|Down deriving (Eq,Show)\n\nsolve :: Int -> Int -> [(Int,Int,Int)] -> [Int]\nsolve _ _ [] = []\nsolve c m ((s,f,t):xs) = let now = mod (t+1) c\n (nowstair,dir) = if nows then 2*m-nowstair-s else s-nowstair\n else\n if nowstairf then 2*m-s-f else f-s\n else\n if s a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\ndata Dir = Up|Down deriving (Eq,Show)\n\nsolve :: Int -> Int -> [(Int,Int,Int)] -> [Int]\nsolve _ _ [] = []\nsolve c m ((s,f,t):xs) = let now = mod (t+1) c\n (nowstair,dir) = if nows then 2*m-nowstair-s else s-nowstair\n else\n if nowstairf then 2*m-s-f else f-s\n else\n if s a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\ndata Dir = Up|Down deriving (Eq,Show)\n\nsolve :: Int -> Int -> [(Int,Int,Int)] -> [Int]\nsolve _ _ [] = []\nsolve c m ((s,f,t):xs) = let now = mod (t+1) c\n (nowstair,dir) = if nows then 2*m-nowstair-s else s-nowstair\n else\n if nowstairf then 2*m-s-f else f-s\n else\n if s0=(t-s+c-1)`div`c*c+f where c=2*m;t=succ pt\ns([_,m]:l)=map(q$m)l\nmain=interact$unlines.map show.s.map(map(pred.read).words).lines"}], "src_uid": "b8321b0a3fc8c295182a4c2c8d2e9d01"} {"source_code": "import Data.List\nimport qualified Data.Set as Set\n\npartitionaAtNotSuccessive _ [] = ([], [])\npartitionaAtNotSuccessive _ [x] = ([x], []) \npartitionaAtNotSuccessive next (x : xs)\n | next x == head xs = (x : fst t, snd t)\n | otherwise = ([x], xs)\n where t = partitionaAtNotSuccessive next xs \n\nf :: Int -> [Int] -> Set.Set Int -> [[Int]]\nf _ [] _ = []\nf n (x:xs) p\n-- | n == x = successive : f (succ (last successive)) xs (Set.fromList notSuccessive)\n-- | otherwise = [] : f n xs (Set.insert x p)\n-- where (successive, notSuccessive) = partitionaAtNotSuccessive succ (Set.toList (Set.insert x p))\n--\n | n == x = successive : f (succ lastSuccessive) xs (notSuccessive)\n | otherwise = [] : f n xs nextP\n where nextP = Set.insert x p\n successive = takeWhile ((flip Set.member) nextP) [n..]\n lastSuccessive = last successive\n notSuccessive = snd (Set.split lastSuccessive nextP)\n\n\nmain = do\n nS <- getLine\n snacksS <- getLine\n let n = read nS :: Int\n snacks = map (n - ) (map read (words snacksS) :: [Int])\n putStr (unlines \n (map unwords \n (map \n (map (\\x -> show (n - x))) \n (f 0 snacks Set.empty)\n )\n )\n )\n", "positive_code": [{"source_code": "import Control.Applicative( (<$>))\nimport Data.IntSet( deleteFindMax, insert, empty, null)\nimport qualified Data.IntSet as IS\nmain = do\n n_ <- readLn\n ns_ <- map read . words <$> getLine\n let\n\tproc _\t_\t[] = [] \n\tproc st next (n:ns)\n\t | n==next\t = let\n\t\t\t (dmp,st',next') = dump [] st (next-1)\n\t\t\tin\n\t\t\t (n:reverse dmp):(proc st' next' ns)\n\t | otherwise\t = []:(proc (insert n st) next ns)\n\tdump v st next\n\t | IS.null st\t = (v,empty,next)\n\t | otherwise\t = let\n\t\t\t\t(mx,st') = deleteFindMax st\n\t\t\t in\n\t\t\t\tif mx==next\n\t\t\t\t then dump (mx:v) st' (next-1)\n\t\t\t\t else (v, st, next)\n\n\tputStrs [] = putStrLn \"\"\n\tputStrs (x:xs) = (putStr $ (show x)++\" \") >> putStrs xs\n\tprint' [] = return ()\n\tprint' (x:xs) = putStrs x >> print' xs\n\n print' $ proc empty n_ ns_\n"}, {"source_code": "-- 767A\n\nimport Data.Functor ((<$>))\nimport Control.Monad.State\n\ncheckHeap :: (Int, MaxSkewHeap) -> StateT (Int, MaxSkewHeap) IO ()\ncheckHeap (i, oldHeap) = do\n case pop oldHeap of\n Just (top, newHeap) ->\n if i == top\n then do\n liftIO . putStr $ ' ':(show top)\n checkHeap (i - 1, newHeap)\n else put (i, oldHeap)\n Nothing -> put (i, oldHeap)\n\naddValue :: Int -> StateT (Int, MaxSkewHeap) IO ()\naddValue x = do\n (i, heap) <- get\n if i == x\n then do\n liftIO . putStr $ show i\n checkHeap (i - 1, heap)\n else put $ (i, insert x heap)\n liftIO . putChar $ '\\n'\n\nmain :: IO ()\nmain = do\n _ <- getLine\n nums <- fmap read <$> words <$> getLine\n evalStateT (mapM_ addValue nums) (length nums, Empty)\n\n \n\n\n\n\ndata MaxSkewHeap = Empty | Node Int MaxSkewHeap MaxSkewHeap\n\n(\u222a) :: MaxSkewHeap -> MaxSkewHeap -> MaxSkewHeap\n(\u222a) l Empty = l\n(\u222a) Empty r = r\n(\u222a) l@(Node lval l1 r1) r@(Node rval l2 r2)\n | predicate lval rval = Node lval (r \u222a r1) l1\n | otherwise = Node rval (l \u222a r2) l2\n where predicate = (>)\n\ninsert :: Int -> MaxSkewHeap -> MaxSkewHeap\ninsert x heap = (Node x Empty Empty) \u222a heap\n\npop :: MaxSkewHeap -> Maybe (Int, MaxSkewHeap)\npop Empty = Nothing\npop (Node x l r) = Just (x, l \u222a r)\n\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = map readInt . B.words\n\n\nfst3 (a, b, c) = a\nsolve n = reverse . fst3 . foldl' (\\(dds, inits, maxi) x -> let \n inits' = S.insert x inits\n ds = takeWhile (`S.member` inits') [maxi, maxi - 1..1] \n in (ds:dds, inits', maxi - length ds)) ([], S.empty, n)\n\n\nmain = do\n n <- readInt <$> B.getLine\n xs <- readInts <$> B.getLine\n putStrLn . intercalate \"\\n\" . map (intercalate \" \" . map show) $ solve n xs\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = readLn >>= \\n -> solve.(++) [n].map (fst.fromJust.C.readInt).C.words=<< C.getLine\nsolve::[Int]->IO ()\nsolve (x:xs) = foldM_ (\\b a -> let pr = f b a in putStrLn (unwords $ map show pr) >> return (slv1 b a pr) ) (x,Set.empty) $ xs\n where f (z1,z2) z3 = if z3==z1 then z3:slv2 z2 (z3-1) else [] \nslv1 (b, bs) x [] = (b,Set.insert x bs)\nslv1 (b, bs) x ys = (b-length ys, bs)\nslv2 ss1 0 =[]\nslv2 ss1 x = let i = fromMaybe (-1) $ Set.lookupIndex (x) ss1 in if i/=(-1) then (x:slv2 ss1 (x-1)) else []"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = map readInt . B.words\n\nfst4 (a, b, c, d) = a\nsolve n = reverse . fst4 . foldl' (\\(ds, maxi, mini, s) x -> \n let mini' = min x mini\n s' = x:s \n in if x < maxi then ([]:ds, maxi, mini', s') else (s':ds, mini' - 1, mini', [])) ([], n, n, [])\n\n\nmain = do\n n <- readInt <$> B.getLine\n xs <- readInts <$> B.getLine\n putStrLn . intercalate \"\\n\" . map (intercalate \" \" . map show) $ solve n xs\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = readLn >>= \\n -> solve.(++) [n].map (fst.fromJust.C.readInt).C.words=<< C.getLine\nsolve::[Int]->IO ()\nsolve (x:xs) = foldM_ (\\b (a1,a2) -> putStrLn (f (a1,a2) b) >> return (if a2==Set.empty then a1 else b) ) (x+1) $ zip [x,(x-1)..] $ zipWith (\\ a b -> a Set.\\\\ b)(map Set.fromList $ tail $ inits xs) (map Set.fromList $ tail $ inits [x,(x-1)..])\n where f (z11,z12) z2 = unwords $ map show $ if z12==Set.empty then tail $ reverse [z11 .. z2] else []"}], "src_uid": "3d648acee2abbf834f865b582aa9b7bc"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata NodeType = BUD | LEAVE deriving (Eq, Show)\r\ntype NodeId = Int\r\ntype Parent = Maybe NodeId\r\ntype BudCount = Int\r\ntype LeaveCount = Int\r\ntype LonelyRoot = Bool\r\ndata NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)\r\n\r\ninstance Semigroup NodeCount where\r\n (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc') \r\n\r\ninstance Monoid NodeCount where\r\n mempty = NC 0 0\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n es <- replicateM (n - 1) $ getInts 2\r\n let\r\n esArr :: Array NodeId [NodeId]\r\n esArr = accumArray (flip (:)) [] (1, n) $ do\r\n [u, v] <- es\r\n [(u, v), (v, u)]\r\n countNode :: Parent -> NodeId -> (NodeType, NodeCount)\r\n countNode p i = (nodeType, nodeCount)\r\n where\r\n children = maybe id (filter . (/=)) p $ esArr!i\r\n childCounts = map (countNode (Just i)) children\r\n nodeType\r\n | null children = LEAVE\r\n | any ((==LEAVE) . fst) childCounts = BUD \r\n | otherwise = LEAVE \r\n nodeCount = foldMap snd childCounts <> (case nodeType of\r\n LEAVE -> NC 0 1\r\n BUD -> NC 1 0)\r\n (rootType, NC budCount leaveCount) = countNode Nothing 1\r\n pure $! putInts [leaveCount - budCount + (if rootType == LEAVE then 0 else 1)]\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Bool (bool)\r\nimport Data.Maybe\r\nimport Data.Bifunctor (bimap)\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata NodeType = BUD | LEAVE deriving (Eq, Show)\r\ntype NodeId = Int\r\ntype Parent = NodeId\r\ntype BudCount = Int\r\ntype LeaveCount = Int\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n es <- fmap concat $ replicateM (n - 1) $ do\r\n ~[u, v] <- getInts 2\r\n pure $! [(u, v), (v, u)]\r\n let\r\n esArr :: Array NodeId [NodeId]\r\n esArr = accumArray (flip (:)) [] (1, n) es\r\n countNode :: Parent -> NodeId -> (NodeType, (BudCount, LeaveCount))\r\n countNode p i = (nodeType, (bc + (fromEnum $ nodeType == BUD), lc + (fromEnum $ nodeType == LEAVE)))\r\n where\r\n children = map (countNode i) $ filter (/=p) $ esArr!i\r\n nodeType = bool LEAVE BUD $ any ((==LEAVE) . fst) children\r\n (bc, lc) = bimap sum sum $ unzip $ fmap snd $ children\r\n (rootType, (budCount, leaveCount)) = countNode 1 1\r\n pure $! putInts [leaveCount - budCount + (fromEnum $ rootType == BUD)]\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata NodeType = BUD | LEAVE deriving (Eq, Show)\r\ntype NodeId = Int\r\ntype Parent = NodeId\r\ntype BudCount = Int\r\ntype LeaveCount = Int\r\ntype LonelyRoot = Bool\r\ndata NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)\r\n\r\ninstance Semigroup NodeCount where\r\n (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc') \r\n\r\ninstance Monoid NodeCount where\r\n mempty = NC 0 0\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n es <- fmap concat $ replicateM (n - 1) $ do\r\n ~[u, v] <- getInts 2\r\n pure $! [(u, v), (v, u)]\r\n let\r\n esArr :: Array NodeId [NodeId]\r\n esArr = accumArray (flip (:)) [] (1, n) es\r\n countNode :: Parent -> NodeId -> (NodeType, NodeCount)\r\n countNode p i = (nodeType, nodeCount)\r\n where\r\n children = filter (/=p) $ esArr!i\r\n childCounts = map (countNode i) children\r\n nodeType = if any ((==LEAVE) . fst) childCounts then BUD else LEAVE\r\n nodeCount = foldMap snd childCounts <> (\r\n NC (fromEnum $ nodeType == BUD) (fromEnum $ nodeType == LEAVE))\r\n (rootType, NC budCount leaveCount) = countNode 1 1\r\n pure $! putInts [leaveCount - budCount + (fromEnum $ rootType == BUD)]\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata NodeType = BUD | LEAVE deriving (Eq, Show)\r\ntype NodeId = Int\r\ntype Parent = NodeId\r\ntype BudCount = Int\r\ntype LeaveCount = Int\r\ntype LonelyRoot = Bool\r\ndata NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)\r\n\r\ninstance Semigroup NodeCount where\r\n (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc') \r\n\r\ninstance Monoid NodeCount where\r\n mempty = NC 0 0\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n es <- replicateM (n - 1) $ getInts 2\r\n let\r\n esArr :: Array NodeId [NodeId]\r\n esArr = accumArray (flip (:)) [] (1, n) $ do\r\n [u, v] <- es\r\n [(u, v), (v, u)]\r\n countNode :: Parent -> NodeId -> (NodeType, NodeCount)\r\n countNode p i = (nodeType, nodeCount)\r\n where\r\n children = filter (/=p) $ esArr!i\r\n childCounts = map (countNode i) children\r\n nodeType = if any ((==LEAVE) . fst) childCounts then BUD else LEAVE\r\n nodeCount = foldMap snd childCounts <> (\r\n NC (fromEnum $ nodeType == BUD) (fromEnum $ nodeType == LEAVE))\r\n (rootType, NC budCount leaveCount) = countNode 1 1\r\n pure $! putInts [leaveCount - budCount + (fromEnum $ rootType == BUD)]\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\ndata NodeType = BUD | LEAVE deriving (Eq, Show)\r\ntype NodeId = Int\r\ntype Parent = Maybe NodeId\r\ntype BudCount = Int\r\ntype LeaveCount = Int\r\ntype LonelyRoot = Bool\r\ndata NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)\r\n\r\ninstance Semigroup NodeCount where\r\n (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc') \r\n\r\ninstance Monoid NodeCount where\r\n mempty = NC 0 0\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n es <- replicateM (n - 1) $ getInts 2\r\n let\r\n esArr :: Array NodeId [NodeId]\r\n esArr = accumArray (flip (:)) [] (1, n) $ do\r\n [u, v] <- es\r\n [(u, v), (v, u)]\r\n countNode :: Parent -> NodeId -> (NodeType, NodeCount, LonelyRoot)\r\n countNode p i = (nodeType, nodeCount, lonelyRoot)\r\n where\r\n children = maybe id (filter . (/=)) p $ esArr!i\r\n childCounts = map (countNode (Just i)) children\r\n nodeType\r\n | null children = LEAVE\r\n | any ((==LEAVE) . (\\(t, _, _) -> t)) childCounts = BUD \r\n | otherwise = LEAVE \r\n nodeCount = foldMap (\\(_, c, _) -> c) childCounts <> (case nodeType of\r\n LEAVE -> NC 0 1\r\n BUD -> NC 1 0)\r\n lonelyRoot = isNothing p && nodeType == LEAVE\r\n (_, NC budCount leaveCount, lonelyRoot) = countNode Nothing 1\r\n pure $! putInts [leaveCount - budCount + (if lonelyRoot then 0 else 1)]\r\n\r\ntype SP = State [P.ByteString]\r\n\r\nreadInt :: P.ByteString -> Int\r\nreadInt = fst . fromJust . P.readInt\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map readInt <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Graph\r\nimport Data.Maybe\r\nimport Data.Tree\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ndata Typ = Leaf | Bud deriving Eq\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n] <- readInts\r\n es <- replicateM (n - 1) readInts\r\n let [t] = dfs (buildG (1, n) $ concatMap (\\[u, v] -> [(u, v), (v, u)]) es) [1]\r\n ta = array (1, n) $ go t [] where\r\n go (Node u ts) acc = (u, typ) : foldr go acc ts where\r\n typ | any ((==Leaf) . (ta!) . rootLabel) ts = Bud\r\n | otherwise = Leaf\r\n print $ n - 2 * length (filter (==Bud) $ elems ta) + fromEnum (ta!1 == Bud)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Tuple (swap)\nimport Data.Bool (bool)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC { n :: Int, edges :: [(Int, Int)] }\n\ninput :: Scanner TC\ninput = do\n n <- int\n edges <- (n - 1) >< pair int int\n return TC{..}\n\noutput = showB\n\nsolve :: TC -> Int\nsolve TC{..} = n - 2 * b + bool 1 0 rb\n where\n adj :: Array Int [Int]\n adj = accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges\n\n (b, rb) = dfs 1 1\n\n dfs :: Int -> Int -> (Int, Bool)\n dfs p u = (sum buds + bool 1 0 leaf, leaf)\n where\n leaf = not $ or leaves\n (buds, leaves) = unzip . map (dfs u) . filter (/= p) $ adj ! u\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\ntype Graph = Array Int [Int]\n\ndfs :: Graph -> Int -> Int -> [(Int, Int)] -> (Int, [(Int, Int)])\ndfs adj par curr later = let\n children = filter (/= par) $ adj ! curr\n res = scanr (\\child (_, cont) -> dfs adj curr child cont) (1, later) children\n nleaves = foldl' (\\acc (x, _) -> acc + if x == 0 then 1 else 0) 0 res\n in case res of\n (_, cont) : _ -> (,) nleaves $ if nleaves > 0\n then (curr, nleaves) : cont\n else cont\n _ -> error \"scanr cannot result in []\"\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n es <- fmap concat $ replicateM (n - 1) $ do\n ~[u, v] <- getInts 2\n pure [(u, v), (v, u)]\n let\n adj = accumArray (flip (:)) [] (1, n) es\n (_special, almostBuds) = dfs adj 1 1 []\n ans = foldl' (\\x (_, y) -> x + y - 1) 1 almostBuds\n pure $ {- string7 (show almostBuds ++ \"\\n\") <> -} putInts [ans]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "679a03b57d58907a221689483f59ca34"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as B\n\nisSorted [] = True\nisSorted [_] = True\nisSorted (x:y:xs) = x <= y && isSorted (y:xs)\n\ntestWith :: Int8 -> [Int8] -> Maybe String\ntestWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing\n where\n ind = fromMaybe maxBound $ findIndex (>number) array\n r = zipWith (curry mapper) array [(0 :: Int)..]\n mapper (e, i)\n | e == number && i < ind = '2'\n | e == number && i > ind = '1'\n | e < number = '1'\n | e > number = '2'\n good = count number array <= (count number p1 + count number p2)\n (a1, a2) = (filter (<=number) array, filter(>=number) array)\n p1 = cutPInfBegin a1 number\n p2 = cutMInfEnd a2 number\n count x = length . filter (==x)\n\ncutPInfBegin [] _ = []\ncutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)\ncutMInfEnd [] _ = []\ncutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x\n\nsolve a 0 = \"-\"\nsolve a n\n | Just s <- testWith n a = s\n | otherwise = solve a (n - 1)\n\nd2i8 x = case x of\n '0' -> 0\n '1' -> 1\n '2' -> 2\n '3' -> 3\n '4' -> 4\n '5' -> 5\n '6' -> 6\n '7' -> 7\n '8' -> 8\n '9' -> 9\n\nmain = do\n Just (a, _) <- fmap B.readInt B.getLine\n replicateM_ a $ do\n _ <- B.getLine\n arr <- fmap (map d2i8 . filter isDigit . B.unpack) B.getLine\n B.putStrLn $ B.pack $ solve arr 9\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as B\n\nisSorted [] = True\nisSorted [_] = True\nisSorted (x:y:xs) = x <= y && isSorted (y:xs)\n\ntestWith :: Int8 -> [Int8] -> Maybe String\ntestWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing\n where\n ind = fromMaybe maxBound $ findIndex (>number) array\n r = zipWith (curry mapper) array [(0 :: Int)..]\n mapper (e, i)\n | e == number && i < ind = '2'\n | e == number && i > ind = '1'\n | e < number = '1'\n | e > number = '2'\n good = count number array <= (count number p1 + count number p2)\n (a1, a2) = (filter (<=number) array, filter(>=number) array)\n p1 = cutPInfBegin a1 number\n p2 = cutMInfEnd a2 number\n count x = length . filter (==x)\n\ncutPInfBegin [] _ = []\ncutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)\ncutMInfEnd [] _ = []\ncutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x\n\nsolve a 0 = \"-\"\nsolve a n\n | Just s <- testWith n a = s\n | otherwise = solve a (n - 1)\n\nd2i8 x = case x of\n '0' -> 0\n '1' -> 1\n '2' -> 2\n '3' -> 3\n '4' -> 4\n '5' -> 5\n '6' -> 6\n '7' -> 7\n '8' -> 8\n '9' -> 9\n\nmain = do\n Just (a, _) <- fmap B.readInt B.getLine\n replicateM_ a $ do\n _ <- B.getLine\n arr <- fmap (map d2i8 . filter isDigit . B.unpack) B.getLine\n B.putStrLn $ B.pack $ solve arr 9\n"}, {"source_code": "import Data.List\n--import Data.Ord\nimport Control.Monad\nimport Data.Maybe\n\nisSorted [] = True\nisSorted [_] = True\nisSorted (x:y:xs) = x <= y && isSorted (y:xs)\n\npinf = 10 :: Int\nminf = -10 :: Int\n\ntestWith :: Int -> [Int] -> Maybe String\ntestWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing\n where\n ind = fromMaybe maxBound $ findIndex (>number) array\n r = zipWith (curry mapper) array [(0 :: Int)..]\n mapper (e, i)\n | e == number && i < ind = '2'\n | e == number && i > ind = '1'\n | e < number = '1'\n | e > number = '2'\n good = count number array <= (count number p1 + count number p2)\n (a1, a2) = (filter (<=number) array, filter(>=number) array)\n p1 = cutPInfBegin a1 number\n p2 = cutMInfEnd a2 number\n count x = length . filter (==x)\n\ncutPInfBegin [] _ = []\ncutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)\ncutMInfEnd [] _ = []\ncutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x\n\nsolve a 0 = \"-\"\nsolve a n\n | Just s <- testWith n a = s\n | otherwise = solve a (n - 1)\n\nmain = do\n a <- fmap read getLine :: IO Int\n forM_ [1..a] $ \\_ -> do\n _ <- getLine\n arr <- fmap (map $ \\x -> read [x]) getLine\n putStrLn $ solve arr 9\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nisSorted [] = True\nisSorted [_] = True\nisSorted (x:y:xs) = x <= y && isSorted (y:xs)\n\ntestWith :: Int -> [Int] -> Maybe String\ntestWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing\n where\n ind = fromMaybe maxBound $ findIndex (>number) array\n r = zipWith (curry mapper) array [(0 :: Int)..]\n mapper (e, i)\n | e == number && i < ind = '2'\n | e == number && i > ind = '1'\n | e < number = '1'\n | e > number = '2'\n good = count number array <= (count number p1 + count number p2)\n (a1, a2) = (filter (<=number) array, filter(>=number) array)\n p1 = cutPInfBegin a1 number\n p2 = cutMInfEnd a2 number\n count x = length . filter (==x)\n\ncutPInfBegin [] _ = []\ncutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)\ncutMInfEnd [] _ = []\ncutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x\n\nsolve a 0 = \"-\"\nsolve a n\n | Just s <- testWith n a = s\n | otherwise = solve a (n - 1)\n\nmain = do\n Just (a, _) <- fmap B.readInt B.getLine\n replicateM_ a $ do\n _ <- B.getLine\n arr <- fmap (map digitToInt . filter isDigit . B.unpack) B.getLine\n B.putStrLn $ B.pack $ solve arr 9\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Data.List\nimport Data.Ord\nimport Control.Monad\nimport Data.Maybe\n\nlis a = extract1 (maximumBy (comparing $ \\(_, (a, _, _)) -> a) (zip [0..] cmp)) cmp\n where cmp = lisHelper (tail a) [(1, head a, -1)]\n extract (_, _, -1) _ = []\n extract (1, _, l) _ = [l]\n extract (_, c, l) a = extract (a !! l) a ++ [l]\n extract1 (i, (_, c, -1)) a = [i]\n extract1 (i, (_, c, l)) a = extract (a !! l) a ++ [l] ++ [i]\n lisHelper [] acc = acc\n lisHelper (x:xs) acc = lisHelper xs $ acc ++ [max acc x]\n max acc x = (\\((a, _, _), i) -> (a + 1, x, i)) $ maximumBy (comparing $ \\((a, _, _), _) -> a) $ filter (\\((_, e, _), _) -> e <= x) (zip ((0, -1, -1):acc) [(-1)..])\n\ntakeNot what whre = map snd $ filter (\\(i, e) -> not $ i `elem` what) (zip [0..] whre)\n\nisSorted [] = True\nisSorted [x] = True\nisSorted (x:y:xs) = x <= y && isSorted (y:xs)\n\nprc x = if s then Just $ map (\\e -> if e `elem` l then '1' else '2') [0..(length x - 1)] else Nothing\n where l = lis x\n s = isSorted $ takeNot l x\n\nmain = do\n a <- fmap read getLine\n forM_ [1..a] $ \\_ -> do\n _ <- getLine\n a <- fmap (map $ \\x -> read [x]) getLine\n putStrLn $ fromMaybe \"-\" (prc a)\n"}], "src_uid": "886f773e75fa3c770fb70133ff1b595b"} {"source_code": "import System.IO (getChar, putStr)\nimport Data.Char\n\n\n{--\ngetInt :: Int -> IO Int\n\ngetInt x = do c <- getChar\n if isDigit c then getInt (10 * x + digitToInt c)\n else return x\n--}\n\ngetInt :: Int -> [Char] -> Int\n\ngetInt num (x : xs) = getInt (10 * num + digitToInt x) xs\ngetInt num _ = num\n\ngetString :: Int -> [Char]\n\ngetString x = let\n q = x `div` 10\n r = x `mod` 10\n rem = chr $ ord '0' + r\n in if q > 0 then getString q ++ [rem]\n else [rem]\n\n\nfindEven (x : xs) n = if x `mod` 2 == 0 then Just n\n else findEven xs $ n + 1\nfindEven _ _ = Nothing\n\nsolvet :: IO ()\nsolvet = do n <- getLine\n a <- getLine\n putStr (let\n line1 = words n\n line2 = words a\n l1 = head $ map (getInt 0) line1\n l2 = map (getInt 0) line2\n in case findEven l2 1 of\n (Just x) -> \"1\\n\" ++ getString x ++ \"\\n\"\n _ -> if l1 == 1 then \"-1\\n\"\n else \"2\\n1 2\\n\")\n\n\nsolve :: Int -> IO ()\n\nsolve t | t > 0 = solve (t - 1) >> solvet \n | otherwise = putStr \"\"\n\nmain :: IO ()\n\n\nmain = do str <- getLine\n let\n q1 = words str\n q = head $ map (getInt 0) q1\n in solve q\n\n{--\n putStr (let\n ls = words str\n lsNum = map (getInt 0) ls\n lsChar = map getString lsNum\n in foldl (++) [] lsChar)\n--} ", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n getLine\n as <- map read.words <$> getLine\n case () of\n _ | any even as -> print 1 >> print (fst $ head $ filter (even.snd) $ zip [1..] as)\n | length as >= 2 -> putStrLn \"2\\n1 2\"\n | otherwise -> putStrLn \"-1\"\n test (i - 1)\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain =\n interact\n (unlines .\n concatMap (map (unwords . map show) . solve . map read . words) .\n takeSnd . tail . lines)\n\ntakeSnd :: [a] -> [a]\ntakeSnd [] = []\ntakeSnd [x] = []\ntakeSnd (x:y:xs) = y : takeSnd xs\n\nsolve :: [Int] -> [[Int]]\nsolve l =\n maybe [[-1]] (\\x -> [[length x], x]) (aux (map fst evens) (map fst odds))\n where\n (evens, odds) = partition (even . snd) (zip [1 ..] l)\n\naux :: [Int] -> [Int] -> Maybe [Int]\naux (x:xs) _ = Just [x]\naux _ (x:y:xs) = Just [x, y]\naux _ _ = Nothing\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess1 c s | c==1 && odd (head s) = do\n\t\t\tputStrLn \"-1\"\n\t |c==1 = do\n\t\t\tputStrLn \"1\"\n\t\t\tputStrLn \"1\"\n\t | e>0 = do\n\t\t\tputStrLn \"1\"\n\t\t\tputStrLn $ show $ snd $ head $ filter (\\z-> even (fst z)) $ zip s [1..]\n\t | otherwise = do\n\t\t\tputStrLn \"2\"\n\t\t\tputStrLn $ intercalate \" \" $ map show $ map snd $ take 2 $ filter (\\z-> odd(fst z)) $ zip s [1..]\n\twhere e = length $ filter even s\n\n\nprocess = do\n\t\tc<-read <$> getLine ::IO Int\n\t\ts<-map read <$> words <$> getLine ::IO [Int]\n\t\tprocess1 c s \n\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n process\n\n\n\n"}, {"source_code": "import Data.List(findIndex)\nimport Data.Maybe(isNothing,fromJust)\n\nevenSubset :: [Int] -> Maybe [Int]\nevenSubset xs\n | isNothing idx = if length xs == 1 then Nothing else Just [1,2]\n | otherwise = fmap ((:[]) . (+1)) idx\n where idx = findIndex even xs\n\nprocess :: Int -> IO ()\nprocess 0 = return ()\nprocess t = do\n n' <- getLine\n a' <- getLine\n let a = map read . words $ a'\n let s = evenSubset a\n if isNothing s\n then print (-1)\n else do\n let s' = fromJust s\n print . length $ s'\n putStrLn . unwords . map show $ s'\n process (t-1)\n\nmain = do\n t <- fmap read getLine\n process t"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess1 c s | c==1 = do\n\t\t\tputStrLn \"-1\"\n\t |c==2 && even (sum s ) = do\n\t\t\tputStrLn \"2\"\n\t\t\tputStrLn \"1 2\"\n\t | c==2 =do\n\t\t\tputStrLn \"-1\"\n\t | o >2= do\n\t\t\tputStrLn \"2\"\n\t\t\tputStrLn $ intercalate \" \" $ map show $ map snd $ filter (\\z-> odd(fst z)) $ zip s [1..]\n\t | otherwise = do\n\t\t\tputStrLn \"2\"\n\t\t\tputStrLn $ intercalate \" \" $ map show $ map snd $ filter (\\z-> even(fst z)) $ zip s [1..]\n\twhere o = length $ filter odd s\n\n\nprocess = do\n\t\tc<-read <$> getLine ::IO Int\n\t\ts<-map read <$> words <$> getLine ::IO [Int]\n\t\tprocess1 c s \n\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n process\n\n\n\n"}], "src_uid": "3fe51d644621962fe41c32a2d90c7f94"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ print\n\nsolve = do\n\t[ a, b, c ] <- readInts\n\treturn $ maximum $ do\n\t\ti <- [ 0 .. min a ( b `div` 2 ) ]\n\t\tlet\n\t\t\tj = min ( b - 2 * i ) ( c `div` 2 )\n\t\treturn $ i + 2 * i + j + 2 * j\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ViewPatterns #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bool\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport qualified Data.List.NonEmpty as NL\nimport Data.Monoid\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Foreign\nimport qualified System.IO as IO\n#ifdef DEBUG\nimport Debug.Trace\n#endif\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a,b,c] <- map read.words <$> getLine\n print $ maximum $ do\n x <- [0..min a (div b 2)]\n let b' = b - 2 * x\n y <- [0..min b' (div c 2)]\n return $ (x + y) * 3\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\n\n\nprocess = do\n\t\t[a,b,c] <- map read <$> words <$> getLine ::IO [Int]\n\t\tlet m1= min b (div c 2)\n\t\tlet m2 = min a (div (b-m1) 2)\n\t\tprint $ 3*(m1+m2)\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n process \n\t \n"}, {"source_code": "process :: Int -> Int -> Int -> Int\nprocess a b c\n | 2*b <= c = 3*b\n | 2*a <= b' = 3*c2 + 3*a\n | otherwise = 3*c2 + 3*b2\n where\n c2 = c `div` 2\n b' = b-c2\n b2 = b' `div` 2\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ print $ map (\\[a,b,c] -> process a b c) ts"}], "negative_code": [], "src_uid": "14fccd50d5dfb557dd53f2896ed844c3"} {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Int\r\n\r\nsolve :: Int64 -> Int\r\nsolve n\r\n | n `mod` 2050 /= 0 = -1\r\n | otherwise = bitsSum $ quot n 2050\r\n where\r\n bitsSum i = sum $ (\\c -> ord c - ord '0') <$> show i\r\n\r\nsolveIO :: IO ()\r\nsolveIO = do\r\n l <- getLine\r\n let t = read l :: Int64\r\n putStr $ show (solve t) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n l <- getLine\r\n let t = read l :: Int\r\n replicateM_ t solveIO\r\n", "positive_code": [{"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\nimport Control.Monad.ST\r\n \r\nimport qualified Data.Array as A\r\n \r\nimport Data.Bits(xor)\r\n \r\nimport Data.Array((!))\r\n \r\nn2050 :: Integer -> Integer\r\nn2050 n = aux 2050 where\r\n\taux i\r\n\t\t| n < i = div i 10\r\n\t\t| otherwise = aux $ 10*i\r\n \r\nsolve :: Integer -> Maybe Integer\r\nsolve n = aux n where\r\n\taux 0 = Just 0\r\n\taux n | n < 2050 = Nothing\r\n\taux n = do \r\n\t\ti <- aux (n - n2050 n)\r\n\t\treturn $ i + 1\r\n \r\n \r\nshowR :: Maybe Integer -> Integer \r\nshowR Nothing = -1\r\nshowR (Just i) = i\r\n \r\n \r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ showR $ solve n \r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\nimport Control.Monad.State.Strict\r\n \r\nimport qualified Data.Array as A\r\n \r\nimport Data.Bits(xor)\r\n \r\nimport Data.Array((!))\r\n \r\nn2050 :: Integer -> Integer\r\nn2050 n = aux 2050 where\r\n\taux i\r\n\t\t| n < i = div i 10\r\n\t\t| otherwise = aux $ 10*i\r\n \r\nsolve :: Integer -> Maybe Integer\r\nsolve n = aux n where\r\n\taux 0 = Just 0\r\n\taux n | n < 2050 = Nothing\r\n\taux n = do \r\n\t\ti <- aux (n - n2050 n)\r\n\t\treturn $ i + 1\r\n \r\n \r\nshowR :: Maybe Integer -> Integer \r\nshowR Nothing = -1\r\nshowR (Just i) = i\r\n \r\n \r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ showR $ solve n \r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Array((!))\r\n\r\nn2050 :: Integer -> Integer\r\nn2050 n = aux 2050 where\r\n\taux i\r\n\t\t| n < i = div i 10\r\n\t\t| otherwise = aux $ 10*i\r\n\r\nsolve :: Integer -> Maybe Integer\r\nsolve n = aux n where\r\n\taux 0 = Just 0\r\n\taux n | n < 2050 = Nothing\r\n\taux n = do \r\n\t\ti <- aux (n - n2050 n)\r\n\t\treturn $ i + 1\r\n\r\n\r\nshowR :: Maybe Integer -> Integer \r\nshowR Nothing = -1\r\nshowR (Just i) = i\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ showR $ solve n \r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "digitSum :: Integer -> Integer\ndigitSum v\n | v /= 0 = m + d\n | otherwise = 0\n where\n m = mod v 10\n d = digitSum $ div v 10\n\nsolve :: Integer -> Integer\nsolve val\n | m == 0 = digitSum d\n | otherwise = -1\n where\n m = mod val 2050\n d = div val 2050\n\noperate :: IO()\noperate = do\n line <- getLine\n let n = read line\n print $ solve n\n\nsolveAll :: Int -> IO()\nsolveAll n\n | n /= 0 = operate >> solveAll (n - 1)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line\n solveAll n\n"}, {"source_code": "digitSum :: Integer -> Integer\ndigitSum v\n | v /= 0 = m + d\n | otherwise = 0\n where\n m = mod v 10\n d = digitSum $ div v 10\n\nsolve :: Integer -> Integer\nsolve val\n | m == 0 = digitSum d\n | otherwise = -1\n where\n m = mod val 2050\n d = div val 2050\n\nsolveAll :: [String] -> [String]\nsolveAll = map $ show . solve . read\n\nmain :: IO ()\nmain = \n interact $ unlines . solveAll . to_list\n where\n to_list = tail . words\n"}, {"source_code": "digitSum :: Integer -> Integer\ndigitSum v\n | v /= 0 = m + d\n | otherwise = 0\n where\n m = mod v 10\n d = digitSum $ div v 10\n\nsolve :: [Integer] -> [Integer]\nsolve (val : xs)\n | m == 0 = digitSum d : next\n | otherwise = -1 : next\n where\n m = mod val 2050\n d = div val 2050\n next = solve xs\nsolve [] = []\n\n\nmain :: IO ()\nmain = \n interact $ to_string . solve . to_list\n where\n to_list = map read . tail . words\n to_string = unlines . map show\n"}, {"source_code": "ns = takeWhile (<10^18) $ iterate (*10) 2050\nsolve n = case foldr (\\x (r,ds) -> let (q,s) = r `divMod` x in (s,q:ds)) (n,[]) ns of\n (a,_) | a > 0 -> -1\n (_, b) -> sum b \n\nmain = interact $ unlines . map (show . solve . (read :: String -> Integer )) . tail . lines"}, {"source_code": "solve n = case foldr (\\x (r,ds) -> let (q,s) = r `divMod` x in (s,q:ds)) (n,[]) $ takeWhile (<10^18) $ iterate (*10) 2050 of\n (a,_) | a > 0 -> -1\n (_, b) -> sum b \n\nmain = interact $ unlines . map (show . solve . (read :: String -> Integer )) . tail . lines"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Int\r\n\r\nsolve :: Int64 -> Int\r\nsolve n\r\n | n `mod` 2050 /= 0 = -1\r\n | otherwise = bitsSum $ quot n 2050\r\n where\r\n bitsSum i = sum $ (\\c -> ord c - ord '0') <$> show i\r\n\r\nsolveIO :: IO ()\r\nsolveIO = do\r\n l <- getLine\r\n let t = read l :: Int64\r\n putStr $ show (solve t) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n l <- getLine\r\n let t = read l :: Int\r\n replicateM_ t solveIO\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Int\r\n\r\nsolve :: Int64 -> Int64\r\nsolve n\r\n | n `mod` 2050 /= 0 = -1\r\n | otherwise = bitsSum $ quot n 2050\r\n where\r\n bitsSum i = sum $ read <$> (\\c -> [c]) <$> show i\r\n\r\nsolveIO :: IO ()\r\nsolveIO = do\r\n l <- getLine\r\n let t = read l :: Int64\r\n putStr $ show (solve t) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n l <- getLine\r\n let t = read l :: Int\r\n replicateM_ t solveIO\r\n"}, {"source_code": "solve x ans\r\n | x > 0 = solve (x `div` 10) (ans + (x `mod` 10))\r\n | otherwise = ans\r\n \r\nhelper x = \r\n show $ \r\n if y `mod` 2050 == 0 \r\n then solve (y `div` 2050) 0\r\n else -1\r\n where\r\n y = read x\r\n \r\nmain = do\r\n getLine\r\n interact $ unlines . map helper . lines "}, {"source_code": "solve x ans\r\n | x > 0 = solve (x `div` 10) (ans + (x `mod` 10))\r\n | otherwise = ans\r\n\r\nhelper x = show $ \r\n if (read x :: Integer) `mod` 2050 == 0 \r\n then solve ((read x :: Integer) `div` 2050) 0\r\n else -1 \r\n\r\nmain = do\r\n getLine\r\n interact $ unlines . map helper . lines "}, {"source_code": "module Main where\r\n \r\n import Control.Monad ( replicateM )\r\n\r\n main :: IO ()\r\n main = do\r\n input <- getLine\r\n let n = (read input :: Int)\r\n inputs <- replicateM n getLine\r\n let numbers = map (read::String->Int) inputs\r\n let ret = map getAnswer numbers\r\n mapM_ print ret\r\n\r\n getDigits:: Int -> Int \r\n getDigits 0 = 0\r\n getDigits x = xd + getDigits ((x - xd) `div` 10)\r\n where xd = x `mod` 10\r\n\r\n getAnswer:: Int -> Int\r\n getAnswer x\r\n | x `mod` 2050 == 0 = getDigits (x `div` 2050)\r\n | otherwise = -1"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\nparseInteger :: C.ByteString -> Integer\nparseInteger = fst . fromJust . C.readInteger\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n n <- fmap parseInteger C.getLine\n let result = if n `mod` 2050 == 0 then solve (n `div` 2050) else (-1)\n solve 0 = 0\n solve x = x `mod` 10 + solve (x `div` 10)\n return $ integerDec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\n\nchar2s :: Char -> [Char]\nchar2s c = [c]\n\ncalc :: Int64 -> Int\ncalc n | n `mod` 2050 == 0 =\n let k = n `div` 2050\n s = map read $ map char2s $ show k :: [Int] in\n sum s\ncalc _ = -1\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int64\n print $ calc n\n"}, {"source_code": "import Control.Monad ( forM )\r\n\r\ndigits :: Integer -> [Integer]\r\ndigits x\r\n | x == 0 = [0]\r\n | otherwise = (x `mod` 10):digits (x `div` 10)\r\n\r\nsolve :: Integer -> Integer\r\nsolve x\r\n | x `mod` 2050 /= 0 = -1\r\n | otherwise = sum $ digits $ x `div` 2050 \r\n\r\nmain :: IO ()\r\nmain = do\r\n a <- getLine\r\n let t = read a :: Int\r\n s <- forM [1..t] $ \\_ -> do\r\n b <- getLine\r\n let n = read b :: Integer\r\n return (solve n) :: IO Integer\r\n mapM_ print s"}], "negative_code": [{"source_code": "digitSum :: Int -> Int\ndigitSum v\n | v /= 0 = m + d\n | otherwise = 0\n where\n m = mod v 10\n d = digitSum $ div v 10\n\nsolve :: [Int] -> [Int]\nsolve (val : xs)\n | m == 0 = digitSum d : next\n | otherwise = -1 : next\n where\n m = mod val 2050\n d = div val 2050\n next = solve xs\nsolve [] = []\n\n\nmain :: IO ()\nmain = \n interact $ to_string . solve . to_list\n where\n to_list = map read . tail . words\n to_string = unlines . map show\n"}, {"source_code": "solve n = case foldr (\\x (r,ds) -> let (q,s) = r `divMod` x in (s,q:ds)) (n,[]) $ takeWhile (<10^18) $ iterate (*10) 2050 of\n (a,_) | a > 0 -> -1\n (_, b) -> sum b \n\nmain = interact $ unlines . map (show . solve . (read :: String -> Int )) . tail . lines"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: Int -> Int\r\nsolve n\r\n | n `mod` 2050 /= 0 = -1\r\n | otherwise = bitsSum $ quot n 2050\r\n where\r\n bitsSum i = sum $ read <$> (\\c -> [c]) <$> show i\r\n\r\nsolveIO :: IO ()\r\nsolveIO = do\r\n l <- getLine\r\n let t = read l :: Int\r\n putStr $ show (solve t) ++ \"\\n\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n l <- getLine\r\n let t = read l :: Int\r\n replicateM_ t solveIO\r\n"}], "src_uid": "f3e413954c9c02520fd25bd2cba4747e"} {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Control.Arrow\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: [(Char,Int)], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = [(c, 1)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = [], l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node | null $ content node = [l,r] >>= \\f -> pnt $ f node\n | otherwise = content node >>= \\(c,n) -> replicate n c\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq cnt $ solve s' t'\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | null $ content node = [l,r] >>= \\f -> extract q_l q_r (f node)\n | q_l <= l_end && r_end <= q_r = content node\n | otherwise = [l,r] >>= \\f -> extract q_l q_r (f node)\n\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = map ((head *** sum) . unzip)\n $ groupBy ((==) `on` fst)\n $ m (k==0) reverse id\n $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = [],\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=cnt'', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n cnt'' = map (second $ \\(l,r)->r-l+1) cnt'\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (mask' (l_end, r_end)) cnt, l<=r]\n where mask' (l, r) (c, (l_end, r_end)) = (c, (max l_end l, min r_end r))\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Control.Arrow\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\ndata Tree = Nil | Node { content :: [(Char,Int)], l, r :: Tree, rng :: (Int, Int) }\n\nmakeTree [c] rng = Node { content = [(c, 1)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = [], l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node | null $ content node = [l,r] >>= \\f -> pnt $ f node\n | otherwise = content node >>= \\(c,n) -> replicate n c\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq (snd $ snd $ last cnt) $ solve s' t'\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | null $ content node = [l,r] >>= \\f -> extract q_l q_r (f node)\n | q_l <= l_end && r_end <= q_r = content node\n | otherwise = [l,r] >>= \\f -> extract q_l q_r (f node)\n\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = map ((head *** sum) . unzip)\n $ groupBy ((==) `on` fst)\n $ (if k==0 then reverse else id)\n $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt l_end r_end\n | otherwise = node {\n content = [],\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=cnt'', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n cnt'' = map (second $ \\(l,r)->r-l+1) cnt'\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (second $ max l_end *** min r_end) cnt, l<=r]\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq (length cnt) (solve s' t')\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | content node == Nothing = [l,r] >>= \\f -> extract q_l q_r (f node)\n | q_l <= l_end && r_end <= q_r = fromJust $ content node\n | otherwise = [l,r] >>= \\f -> extract q_l q_r (f node)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=Just cnt', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (mask' (l_end, r_end)) cnt, l<=r]\n where mask' (l, r) (c, (l_end, r_end)) = (c, (max l_end l, min r_end r))\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq (length cnt) (solve s' t')\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t []\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)}) res\n | q_r < l_end || r_end < q_l = res\n | content node == Nothing = extract q_l q_r (l node) (extract q_l q_r (r node) res)\n | q_l <= l_end && r_end <= q_r = (fromJust $ content node) ++ res\n | otherwise = extract q_l q_r (l node) (extract q_l q_r (r node) res)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=Just cnt', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (mask' (l_end, r_end)) cnt, l<=r]\n where mask' (l, r) (c, (l_end, r_end)) = (c, (max l_end l, min r_end r))\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = solve s' t'\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | content node == Nothing = [l,r] >>= \\f -> extract q_l q_r (f node)\n | q_l <= l_end && r_end <= q_r = fromJust $ content node\n | otherwise = [l,r] >>= \\f -> extract q_l q_r (f node)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=Just cnt', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (mask' (l_end, r_end)) cnt, l<=r]\n where mask' (l, r) (c, (l_end, r_end)) = (c, (max l_end l, min r_end r))\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq cnt $ solve s' t'\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | content node == Nothing = [l,r] >>= \\f -> extract q_l q_r (f node)\n | q_l <= l_end && r_end <= q_r = fromJust $ content node\n | otherwise = [l,r] >>= \\f -> extract q_l q_r (f node)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=Just cnt', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (mask' (l_end, r_end)) cnt, l<=r]\n where mask' (l, r) (c, (l_end, r_end)) = (c, (max l_end l, min r_end r))\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq (length cnt) (solve s' t')\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | content node == Nothing = extract q_l q_r (l node) ++ extract q_l q_r (r node)\n | q_l <= l_end && r_end <= q_r = fromJust $ content node\n | otherwise = extract q_l q_r (l node) ++ extract q_l q_r (r node)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=Just cnt', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (mask' (l_end, r_end)) cnt, l<=r]\n where mask' (l, r) (c, (l_end, r_end)) = (c, (max l_end l, min r_end r))\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Control.Arrow\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n solve lines (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: [(Char,Int)], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = [(c, 1)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = [], l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node | null $ content node = [l,r] >>= \\f -> pnt $ f node\n | otherwise = content node >>= \\(c,n) -> replicate n c\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq cnt $ solve s' t'\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)})\n | q_r < l_end || r_end < q_l = []\n | null $ content node = [l,r] >>= \\f -> extract q_l q_r (f node)\n | q_l <= l_end && r_end <= q_r = content node\n | otherwise = [l,r] >>= \\f -> extract q_l q_r (f node)\n\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = map ((head *** sum) . unzip)\n $ groupBy ((==) `on` fst)\n $ m (k==0) reverse id\n $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = genNode cnt' l_end r_end\n | otherwise = node {\n content = [],\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = mask cnt l_end r_end\n\ngenNode cnt l_end r_end\n = Node { content=cnt'', rng=(l_end,r_end), l=genNode cnt' l_end mid, r=genNode cnt' (mid+1) r_end }\n where mid = div (l_end+r_end) 2\n cnt' = mask cnt l_end r_end\n cnt'' = map (second $ \\(l,r)->r-l+1) cnt'\n\nmask cnt l_end r_end = [c | c@(_,(l,r)) <- map (second $ max l_end *** min r_end) cnt, l<=r]\n"}], "negative_code": [{"source_code": "module Main where\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve (drop 40000 lines) (makeTree s (1,n))\n\n\ndata Tree = Nil | Node [Int] Tree Tree (Int, Int) deriving Show\n\nmakeTree [c] r = Node [if c'==c then 1 else 0 | c' <- ['a'..'z']] Nil Nil r\n \nmakeTree s r@(l_end, r_end)\n = Node (zipWith (+) left_l right_l) left right r\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left@(Node left_l _ _ _) = makeTree left_s (l_end, mid)\n\tright@(Node right_l _ _ _) = makeTree right_s (mid + 1, r_end)\n\npnt Nil\n = \"\"\n\npnt (Node cnt l r (l_end, r_end))\n | l_end == r_end\n = [c | (1,c) <- zip cnt ['a'..'z']]\n | otherwise\n = pnt l ++ pnt r\n\nsolve :: [String] -> Tree -> IO ()\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = solve s' t'\n where [i,j,k] = map read $ words s\n cnt = extract i j t\n\tt' = replace i j k cnt t\n\nextract l r (Node cnt l_ch r_ch (l_end, r_end))\n | l <= l_end && r_end <= r\n = cnt\n | r < l_end || r_end < l\n = [0,0..]\n | otherwise\n = zipWith (+) (extract l r l_ch) (extract l r r_ch)\n\nreplace l r k cnt node@(Node _ _ _ (l_end, r_end))\n | r < l_end || r_end < l\n = node\n | l == l_end && r == r_end\n = sp cnt k (l_end, r_end)\n | otherwise\n = replace' l r k cnt node\n\nreplace' l r k cnt node@(Node _ l_ch r_ch (l_end, r_end))\n | mid < l\n = makeNode l_ch (replace l r k cnt r_ch) (l_end, r_end)\n | r <= mid\n = makeNode (replace l r k cnt l_ch) r_ch (l_end, r_end)\n | otherwise\n = makeNode (replace l mid k l_cnt l_ch) (replace (mid+1) r k r_cnt r_ch) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n (l_cnt, r_cnt) = sp'' k cnt (mid - l + 1)\n\nmakeNode l@(Node l_cnt _ _ _) r@(Node r_cnt _ _ _) rng\n = Node (zipWith (+) l_cnt r_cnt) l r rng\n\nsp cnt k (l_end, r_end)\n = Node cnt (sp l_cnt k (l_end, mid)) (sp r_cnt k (mid+1, r_end)) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n l_len = mid - l_end + 1\n\t(l_cnt, r_cnt) = sp'' k cnt l_len\n\nsp' [] _ = ([],[])\nsp' (cnt:cnt') l_len\n | cnt <= l_len\n = (cnt:l, 0:r)\n | otherwise\n = (l_len:l,cnt-l_len:r)\n where l_len' = max (l_len - cnt) 0\n (l, r) = sp' cnt' l_len'\n\nsp'' 1 cnt l_len = sp' cnt l_len\nsp'' 0 cnt l_len = (l, r)\n where l_len' = sum cnt - l_len\n (r, l) = sp' cnt l_len'"}, {"source_code": "module Main where\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve (take 25000 lines) (makeTree s (1,n))\n\n\ndata Tree = Nil | Node [Int] Tree Tree (Int, Int) deriving Show\n\nmakeTree [c] r = Node [if c'==c then 1 else 0 | c' <- ['a'..'z']] Nil Nil r\n \nmakeTree s r@(l_end, r_end)\n = Node (zipWith (+) left_l right_l) left right r\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left@(Node left_l _ _ _) = makeTree left_s (l_end, mid)\n\tright@(Node right_l _ _ _) = makeTree right_s (mid + 1, r_end)\n\npnt Nil\n = \"\"\n\npnt (Node cnt l r (l_end, r_end))\n | l_end == r_end\n = [c | (1,c) <- zip cnt ['a'..'z']]\n | otherwise\n = pnt l ++ pnt r\n\nsolve :: [String] -> Tree -> IO ()\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = solve s' t'\n where [i,j,k] = map read $ words s\n cnt = extract i j t\n\tt' = replace i j k cnt t\n\nextract l r (Node cnt l_ch r_ch (l_end, r_end))\n | l <= l_end && r_end <= r\n = cnt\n | r < l_end || r_end < l\n = [0,0..]\n | otherwise\n = zipWith (+) (extract l r l_ch) (extract l r r_ch)\n\nreplace l r k cnt node@(Node _ _ _ (l_end, r_end))\n | r < l_end || r_end < l\n = node\n | l == l_end && r == r_end\n = sp cnt k (l_end, r_end)\n | otherwise\n = replace' l r k cnt node\n\nreplace' l r k cnt node@(Node _ l_ch r_ch (l_end, r_end))\n | mid < l\n = makeNode l_ch (replace l r k cnt r_ch) (l_end, r_end)\n | r <= mid\n = makeNode (replace l r k cnt l_ch) r_ch (l_end, r_end)\n | otherwise\n = makeNode (replace l mid k l_cnt l_ch) (replace (mid+1) r k r_cnt r_ch) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n (l_cnt, r_cnt) = sp'' k cnt (mid - l + 1)\n\nmakeNode l@(Node l_cnt _ _ _) r@(Node r_cnt _ _ _) rng\n = Node (zipWith (+) l_cnt r_cnt) l r rng\n\nsp cnt k (l_end, r_end)\n = Node cnt (sp l_cnt k (l_end, mid)) (sp r_cnt k (mid+1, r_end)) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n l_len = mid - l_end + 1\n\t(l_cnt, r_cnt) = sp'' k cnt l_len\n\nsp' [] _ = ([],[])\nsp' (cnt:cnt') l_len\n | cnt <= l_len\n = (cnt:l, 0:r)\n | otherwise\n = (l_len:l,cnt-l_len:r)\n where l_len' = max (l_len - cnt) 0\n (l, r) = sp' cnt' l_len'\n\nsp'' 1 cnt l_len = sp' cnt l_len\nsp'' 0 cnt l_len = (l, r)\n where l_len' = sum cnt - l_len\n (r, l) = sp' cnt l_len'"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve (take 1000 lines) (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq (length cnt) (solve s' t')\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t []\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)}) res\n | q_r < l_end || r_end < q_l = res\n | content node == Nothing = extract q_l q_r (l node) (extract q_l q_r (r node) res)\n | q_l <= l_end && r_end <= q_r = (fromJust $ content node) ++ res\n | otherwise = extract q_l q_r (l node) (extract q_l q_r (r node) res)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = node {\n content = Just cnt',\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = [c | Just c <- map (mask (l_end, r_end)) cnt]\n\nmask (l, r) item@(c, (l_end, r_end))\n | r < l_end || r_end < l = Nothing\n | otherwise = Just (c, (max l_end l, min r_end r))"}, {"source_code": "module Main where\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve (take 5000 lines) (makeTree s (1,n))\n\n\ndata Tree = Nil | Node [Int] Tree Tree (Int, Int) deriving Show\n\nmakeTree [c] r = Node [if c'==c then 1 else 0 | c' <- ['a'..'z']] Nil Nil r\n \nmakeTree s r@(l_end, r_end)\n = Node (zipWith (+) left_l right_l) left right r\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left@(Node left_l _ _ _) = makeTree left_s (l_end, mid)\n\tright@(Node right_l _ _ _) = makeTree right_s (mid + 1, r_end)\n\npnt Nil\n = \"\"\n\npnt (Node cnt l r (l_end, r_end))\n | l_end == r_end\n = [c | (1,c) <- zip cnt ['a'..'z']]\n | otherwise\n = pnt l ++ pnt r\n\nsolve :: [String] -> Tree -> IO ()\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = solve s' t'\n where [i,j,k] = map read $ words s\n cnt = extract i j t\n\tt' = replace i j k cnt t\n\nextract l r (Node cnt l_ch r_ch (l_end, r_end))\n | l <= l_end && r_end <= r\n = cnt\n | r < l_end || r_end < l\n = [0,0..]\n | otherwise\n = zipWith (+) (extract l r l_ch) (extract l r r_ch)\n\nreplace l r k cnt node@(Node _ _ _ (l_end, r_end))\n | r < l_end || r_end < l\n = node\n | l == l_end && r == r_end\n = sp cnt k (l_end, r_end)\n | otherwise\n = replace' l r k cnt node\n\nreplace' l r k cnt node@(Node _ l_ch r_ch (l_end, r_end))\n | mid < l\n = makeNode l_ch (replace l r k cnt r_ch) (l_end, r_end)\n | r <= mid\n = makeNode (replace l r k cnt l_ch) r_ch (l_end, r_end)\n | otherwise\n = makeNode (replace l mid k l_cnt l_ch) (replace (mid+1) r k r_cnt r_ch) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n (l_cnt, r_cnt) = sp'' k cnt (mid - l + 1)\n\nmakeNode l@(Node l_cnt _ _ _) r@(Node r_cnt _ _ _) rng\n = Node (zipWith (+) l_cnt r_cnt) l r rng\n\nsp cnt k (l_end, r_end)\n = Node cnt (sp l_cnt k (l_end, mid)) (sp r_cnt k (mid+1, r_end)) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n l_len = mid - l_end + 1\n\t(l_cnt, r_cnt) = sp'' k cnt l_len\n\nsp' [] _ = ([],[])\nsp' (cnt:cnt') l_len\n | cnt <= l_len\n = (cnt:l, 0:r)\n | otherwise\n = (l_len:l,cnt-l_len:r)\n where l_len' = max (l_len - cnt) 0\n (l, r) = sp' cnt' l_len'\n\nsp'' 1 cnt l_len = sp' cnt l_len\nsp'' 0 cnt l_len = (l, r)\n where l_len' = sum cnt - l_len\n (r, l) = sp' cnt l_len'"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve [last lines] (makeTree s (1,n)) \n\nm True x _ = x\nm False _ y = y\n\ndata Tree = Nil | Node { content :: Maybe [(Char,(Int,Int))], l, r :: Tree, rng :: (Int, Int) }\n deriving Show\n\nmakeTree [c] rng = Node { content = Just [(c, rng)], l = Nil, r = Nil, rng = rng }\n \nmakeTree s rng@(l_end, r_end)\n = Node { content = Nothing, l = left, r = right, rng = rng }\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left = makeTree left_s (l_end, mid)\n right = makeTree right_s (mid + 1, r_end)\n\npnt node@(Node{content = Nothing}) = pnt (l node) ++ pnt (r node)\npnt node@(Node{content = Just cnt}) = concat $ map (\\(c,(l,r))->replicate (r-l+1) c) cnt\n\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = seq (length cnt) (solve s' t')\n where [i,j,k] = map read $ words s\n cnt = integrate i j k $ extract i j t []\n t' = replace i j cnt t\n\nextract q_l q_r node@(Node{rng=(l_end,r_end)}) res\n | q_r < l_end || r_end < q_l = res\n | content node == Nothing = extract q_l q_r (l node) (extract q_l q_r (r node) res)\n | q_l <= l_end && r_end <= q_r = (fromJust $ content node) ++ res\n | otherwise = extract q_l q_r (l node) (extract q_l q_r (r node) res)\n\nintegrate :: Int -> Int -> Int -> [(Char,(Int,Int))] -> [(Char,(Int,Int))]\nintegrate l_end r_end k ls\n = integrate' ls' l_end\n where ls' = init\n $ foldr (\\(c,n) ((c',n'):etc)->m (c==c') ((c,n+n'):etc) ((c,n):(c',n'):etc)) [('?',0)]\n $ m (k==0) reverse id\n $ map (\\(c,(l_end,r_end))->(c,r_end-l_end + 1)) $ sort ls\n\nintegrate' [] _ = []\nintegrate' ((c,n):etc) l_end = (c,(l_end,l_end+n-1)) : integrate' etc (l_end+n)\n\nreplace q_l q_r cnt node@(Node{rng=(l_end, r_end)})\n | q_r < l_end || r_end < q_l = node\n | q_l <= l_end && r_end <= q_r = node {\n content = Just cnt',\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n | otherwise = node {\n content = Nothing,\n l = replace q_l q_r cnt' (l node),\n r = replace q_l q_r cnt' (r node)\n }\n where cnt' = [c | Just c <- map (mask (l_end, r_end)) cnt]\n\nmask (l, r) item@(c, (l_end, r_end))\n | r < l_end || r_end < l = Nothing\n | otherwise = Just (c, (max l_end l, min r_end r))\n"}, {"source_code": "module Main where\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve (take 10 lines) (makeTree s (1,n))\n\n\ndata Tree = Nil | Node [Int] Tree Tree (Int, Int) deriving Show\n\nmakeTree [c] r = Node [if c'==c then 1 else 0 | c' <- ['a'..'z']] Nil Nil r\n \nmakeTree s r@(l_end, r_end)\n = Node (zipWith (+) left_l right_l) left right r\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left@(Node left_l _ _ _) = makeTree left_s (l_end, mid)\n\tright@(Node right_l _ _ _) = makeTree right_s (mid + 1, r_end)\n\npnt Nil\n = \"\"\n\npnt (Node cnt l r (l_end, r_end))\n | l_end == r_end\n = [c | (1,c) <- zip cnt ['a'..'z']]\n | otherwise\n = pnt l ++ pnt r\n\nsolve :: [String] -> Tree -> IO ()\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = solve s' t'\n where [i,j,k] = map read $ words s\n cnt = extract i j t\n\tt' = replace i j k cnt t\n\nextract l r (Node cnt l_ch r_ch (l_end, r_end))\n | l <= l_end && r_end <= r\n = cnt\n | r < l_end || r_end < l\n = [0,0..]\n | otherwise\n = zipWith (+) (extract l r l_ch) (extract l r r_ch)\n\nreplace l r k cnt node@(Node _ _ _ (l_end, r_end))\n | r < l_end || r_end < l\n = node\n | l == l_end && r == r_end\n = sp cnt k (l_end, r_end)\n | otherwise\n = replace' l r k cnt node\n\nreplace' l r k cnt node@(Node _ l_ch r_ch (l_end, r_end))\n | mid < l\n = makeNode l_ch (replace l r k cnt r_ch) (l_end, r_end)\n | r <= mid\n = makeNode (replace l r k cnt l_ch) r_ch (l_end, r_end)\n | otherwise\n = makeNode (replace l mid k l_cnt l_ch) (replace (mid+1) r k r_cnt r_ch) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n (l_cnt, r_cnt) = sp'' k cnt (mid - l + 1)\n\nmakeNode l@(Node l_cnt _ _ _) r@(Node r_cnt _ _ _) rng\n = Node (zipWith (+) l_cnt r_cnt) l r rng\n\nsp cnt k (l_end, r_end)\n = Node cnt (sp l_cnt k (l_end, mid)) (sp r_cnt k (mid+1, r_end)) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n l_len = mid - l_end + 1\n\t(l_cnt, r_cnt) = sp'' k cnt l_len\n\nsp' [] _ = ([],[])\nsp' (cnt:cnt') l_len\n | cnt <= l_len\n = (cnt:l, 0:r)\n | otherwise\n = (l_len:l,cnt-l_len:r)\n where l_len' = max (l_len - cnt) 0\n (l, r) = sp' cnt' l_len'\n\nsp'' 1 cnt l_len = sp' cnt l_len\nsp'' 0 cnt l_len = (l, r)\n where l_len' = sum cnt - l_len\n (r, l) = sp' cnt l_len'"}, {"source_code": "module Main where\n\nmain = do\n line1 <- getLine\n let [n, q] = map read $ words line1\n s <- getLine\n lines <- sequence [getLine | _ <- [1..q]]\n if n < 1000 then solve lines (makeTree s (1,n)) \n else solve (take 1000 lines) (makeTree s (1,n))\n\n\ndata Tree = Nil | Node [Int] Tree Tree (Int, Int) deriving Show\n\nmakeTree [c] r = Node [if c'==c then 1 else 0 | c' <- ['a'..'z']] Nil Nil r\n \nmakeTree s r@(l_end, r_end)\n = Node (zipWith (+) left_l right_l) left right r\n where mid = (l_end + r_end) `div` 2\n (left_s, right_s) = splitAt (mid - l_end + 1) s \n left@(Node left_l _ _ _) = makeTree left_s (l_end, mid)\n\tright@(Node right_l _ _ _) = makeTree right_s (mid + 1, r_end)\n\npnt Nil\n = \"\"\n\npnt (Node cnt l r (l_end, r_end))\n | l_end == r_end\n = [c | (1,c) <- zip cnt ['a'..'z']]\n | otherwise\n = pnt l ++ pnt r\n\nsolve :: [String] -> Tree -> IO ()\nsolve [] t = putStrLn $ pnt t\nsolve (s:s') t = solve s' t'\n where [i,j,k] = map read $ words s\n cnt = extract i j t\n\tt' = replace i j k cnt t\n\nextract l r (Node cnt l_ch r_ch (l_end, r_end))\n | l <= l_end && r_end <= r\n = cnt\n | r < l_end || r_end < l\n = [0,0..]\n | otherwise\n = zipWith (+) (extract l r l_ch) (extract l r r_ch)\n\nreplace l r k cnt node@(Node _ _ _ (l_end, r_end))\n | r < l_end || r_end < l\n = node\n | l == l_end && r == r_end\n = sp cnt k (l_end, r_end)\n | otherwise\n = replace' l r k cnt node\n\nreplace' l r k cnt node@(Node _ l_ch r_ch (l_end, r_end))\n | mid < l\n = makeNode l_ch (replace l r k cnt r_ch) (l_end, r_end)\n | r <= mid\n = makeNode (replace l r k cnt l_ch) r_ch (l_end, r_end)\n | otherwise\n = makeNode (replace l mid k l_cnt l_ch) (replace (mid+1) r k r_cnt r_ch) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n (l_cnt, r_cnt) = sp'' k cnt (mid - l + 1)\n\nmakeNode l@(Node l_cnt _ _ _) r@(Node r_cnt _ _ _) rng\n = Node (zipWith (+) l_cnt r_cnt) l r rng\n\nsp cnt k (l_end, r_end)\n = Node cnt (sp l_cnt k (l_end, mid)) (sp r_cnt k (mid+1, r_end)) (l_end, r_end)\n where mid = (l_end + r_end) `div` 2\n l_len = mid - l_end + 1\n\t(l_cnt, r_cnt) = sp'' k cnt l_len\n\nsp' [] _ = ([],[])\nsp' (cnt:cnt') l_len\n | cnt <= l_len\n = (cnt:l, 0:r)\n | otherwise\n = (l_len:l,cnt-l_len:r)\n where l_len' = max (l_len - cnt) 0\n (l, r) = sp' cnt' l_len'\n\nsp'' 1 cnt l_len = sp' cnt l_len\nsp'' 0 cnt l_len = (l, r)\n where l_len' = sum cnt - l_len\n (r, l) = sp' cnt l_len'"}], "src_uid": "70d5ec980b3e37585b10e2e1d7c4489e"} {"source_code": "import Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: ByteString -> Int\nsolve line = foldl loop 0 $ zip tok len\n where\n tok = C.groupBy (\\_ i -> i == '0') line :: [ByteString]\n len = scanl (+) 0 $ map C.length tok :: [Int]\n\n loop :: Int -> (ByteString, Int) -> Int\n loop acc (a, k) = case k `compare` C.length a of\n GT -> 1 + acc\n LT -> 1\n EQ -> if C.take k line < a then 1 else 1 + acc\n\nmain = B.getLine >>= print . solve . C.init\n", "positive_code": [{"source_code": "main = getLine >>= print . (\\x -> f 0 x x) . reverse\nf _ [] _ = 0\nf _ [_] _ = 1\nf n (x:y:z) (a:b)\n | x == '0' = f (n + 1) (y:z) b\n | y == '0' = f (n - 1) (x:z) (a:b)\n | n < 0 || n == 0 && x <= y = 1 + f 0 b b\n | otherwise = f (n - 1) (x:z) (a:b)"}, {"source_code": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.Char\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Array.IArray\nimport Debug.Trace\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad (forM_)\nimport Text.Printf (printf)\n\ndebug :: Show a => String -> a -> a\ndebug label a = trace msg a\n where msg = \"=== \" ++ label ++ \": \" ++ show a\n\ndebug2 :: Show a => String -> a -> b -> b\ndebug2 label a b = debug label a `seq` b\n\n-- compare two substrings of a bytestring\ncmpbs :: ByteString -> (Int,Int) -> (Int,Int) -> Ordering\n-- cmpbs bs (alo,ahi) (blo,bhi) | debug2 \"cmpbs\" ((alo,ahi),(blo,bhi)) False = undefined\ncmpbs bs (alo,ahi) (blo,bhi) =\n case (ahi-alo) `compare` (bhi-blo) of\n GT -> GT\n LT -> LT\n EQ -> cmpbs' bs alo ahi blo\n\n-- compare two substrings of equal length\ncmpbs' :: ByteString -> Int -> Int -> Int -> Ordering\ncmpbs' bs ai ahi bi | ai > ahi = EQ\ncmpbs' bs ai ahi bi =\n case (bs `BS.index` ai) `compare` (bs `BS.index` bi) of\n GT -> GT\n LT -> LT\n EQ -> cmpbs' bs (ai+1) ahi (bi+1)\n\nbestSol :: ByteString -> Int -> Int -> [(Int,Int)]\nbestSol bs lo hi | lo > hi = []\nbestSol bs lo hi = [(k,hi)] ++ bestSol bs lo (k-1)\n where\n k' = head [ i | i <- [hi,hi-1..lo], BS.index bs i /= '0' ]\n k = if cmpbs bs (lo,k'-1) (k',hi) >= EQ then k' else lo\n\nbest :: ByteString -> Int -> Int -> Int\nbest bs lo hi = go hi 0\n where\n go hi a | hi < lo = a\n go hi a = go (k-1) (a+1)\n where\n k' = head [ i | i <- [hi,hi-1..lo], BS.index bs i /= '0' ]\n k = if cmpbs bs (lo,k'-1) (k',hi) >= EQ then k' else lo\n\n(-->) = flip fmap\n\nshowBSSolution :: ByteString -> [(Int,Int)] -> IO ()\nshowBSSolution bs sols = do\n forM_ sols $ \\(a,b) -> do\n putStrLn $ printf \"%3d - %3d : %s\" a b [ BS.index bs i | i <- [a..b] ]\n putStrLn $ printf \"length: %d\" (length sols)\n\nmain = do \n digits <- BS.getLine --> BS.filter isDigit\n let n = BS.length digits\n print $ best digits 0 (n-1)\n\n"}], "negative_code": [{"source_code": "import Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: ByteString -> Int\nsolve line = foldl loop 0 $ zip tok len\n where\n tok = C.groupBy (\\_ i -> i == '0') line :: [ByteString]\n len = scanl (+) 0 $ map C.length tok :: [Int]\n\n loop :: Int -> (ByteString, Int) -> Int\n loop acc (a, k) = case k `compare` C.length a of\n GT -> 1 + acc\n LT -> 1\n EQ -> if C.take k line < a then 1 else 1 + acc\n\nmain = B.getLine >>= print . solve\n"}], "src_uid": "4e00fe693a636316d478978abf21d976"} {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\npairs (x:y:zs) = (y,x) : pairs zs\npairs _ = []\nmain = do\n (n:m:ns) <- liftM (unfoldr (B.readInt . B.dropWhile (not . isDigit))) B.getContents\n let (ms,cs) = splitAt (2*n) ns\n ms' = sort (pairs ms)\n cs' = sort (pairs cs)\n putStrLn $ show (commonBy fst ms' cs' 0) ++ \" \" ++\n show (commonBy id ms' cs' 0)\ncommonBy f (a:as) (b:bs) c | f a < f b = commonBy f as (b:bs) c\n | f a > f b = commonBy f (a:as) bs c\n | otherwise = commonBy f as bs $! c+1\ncommonBy _ _ _ c = c\n", "positive_code": [{"source_code": "import Data.List\n\nminus as [] = as\nminus [] _ = []\nminus (a : as) (b : bs) = case compare a b of\n LT -> a : minus as (b : bs)\n EQ -> minus as bs\n GT -> minus (a : as) bs\n\nf a b = (length a - length a', (a', b `minus` a)) where\n a' = a `minus` b\n\ng(a,b)=case f a b of\n (n1, (a', b')) -> case f (map head a') (map head b') of\n (n2, _) -> [n1 + n2, n1]\nj(a,b)=g(sort a,sort b)\ns([_,n]:l)=j$splitAt n l\nmain=interact$unwords.map show.s.map(reverse.map(foldl(\\a c->a*10+fromEnum c-fromEnum '0')0).words).lines"}, {"source_code": "\nimport Array ((!), accumArray)\nimport Control.Monad (liftM)\nimport Data.IntMap (IntMap, intersectionWith, fold, fromListWith)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq (3,2) $ solve [(1,2), (3,4), (2,4)] [(5,4), (2,4), (1,1), (1,2)],\n Test \"2\" $ assertEq (1,0) $ solve [(1,2), (2,1)] [(3,4), (5,1)]\n ]\n\ntestManyEquals :: Test\ntestManyEquals = Test \"TestManyEquals\" $\n assertEq (n, n) $ solve\n [(1 + mod i maxN, 1 + mod i maxN) | i <- [1..n]]\n [(1 + mod i maxN, 1 + mod i maxN) | i <- [1..n]]\n where\n n = 10^5\n\ntestManyEqualsDiametr :: Test\ntestManyEqualsDiametr = Test \"TestManyEqualsDiametr\" $\n assertEq (n, 0) $ solve\n [(1 + mod i maxN, 1 + mod i maxN) | i <- [1..n]]\n [(1 + mod (i+1) maxN, 1 + mod i maxN) | i <- [1..n]]\n where\n n = 10^5\n\ntestMany :: Test\ntestMany = Test \"TestMany\" $\n assertEq (0, 0) $ solve\n [(1, 1 + mod (2*i + 1) maxN) | i <- [1..n]]\n [(1, 1 + mod (2*i) maxN) | i <- [1..n]]\n where\n n = 10^5\n\ntest :: IO ()\ntest = mapM_ run\n [\n testInput,\n testManyEquals,\n testManyEqualsDiametr,\n testMany\n ]\n-}\n--------------------------------------------------------------------------------\n\nmaxN :: Int\nmaxN = 1000\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> (Int, Int)\nsolve as bs = (countOneDiameter, countOneColor)\n where\n mapDCA = fromListWith (+) $ map (\\(c, d) -> (c * maxN + d, 1)) as\n mapDCB = fromListWith (+) $ map (\\(c, d) -> (c * maxN + d, 1)) bs\n mapDCAB = intersectionWith min mapDCA mapDCB\n countOneColor = fold (+) 0 mapDCAB\n asArray' = accumArray (+) 0 (1, maxN) [(b, 1) | (a,b) <- as]\n bsArray' = accumArray (+) 0 (1, maxN) [(b, 1) | (a,b) <- bs]\n countOneDiameter = sum [min (asArray' ! i) (bsArray' ! i) | i <- [1..maxN]]\n\nreadPair :: String -> (Int, Int)\nreadPair line = case map read (words line) of\n [a, b] -> (a, b)\n _ -> undefined\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines getContents\n let (n, m) = readPair $ head lines'\n let (as, bs) = splitAt n $ map readPair $ tail lines'\n let (c, d) = solve as bs\n putStrLn $ concat [show c, \" \", show d]\n"}], "negative_code": [], "src_uid": "3c9fb72577838f54b1670e84b4b60c61"} {"source_code": "module Main\n where\n\ntoInts :: [String] -> [Int]\ntoInts = map read\n\nsplitStr :: Int -> String -> [Int]\nsplitStr n (' ':xs) = n : (splitStr 0 xs)\nsplitStr n ('1':xs) = splitStr (n * 10 + 1) xs\nsplitStr n ('2':xs) = splitStr (n * 10 + 2) xs\nsplitStr n ('3':xs) = splitStr (n * 10 + 3) xs\nsplitStr n ('4':xs) = splitStr (n * 10 + 4) xs\nsplitStr n ('5':xs) = splitStr (n * 10 + 5) xs\nsplitStr n ('6':xs) = splitStr (n * 10 + 6) xs\nsplitStr n ('7':xs) = splitStr (n * 10 + 7) xs\nsplitStr n ('8':xs) = splitStr (n * 10 + 8) xs\nsplitStr n ('9':xs) = splitStr (n * 10 + 9) xs\nsplitStr n ('0':xs) = splitStr (n * 10 + 0) xs\nsplitStr n [] = [n]\n\nsplit s = splitStr 0 s\n\nnext :: Char -> [String] -> Char\nnext ch [] = ch\nnext ch (x:xs) | ch == (head x) = next (head (tail (tail x))) xs\n | ch == (head (tail (tail x))) = next (head x) xs\n | otherwise = next ch xs\n\nmapper a b c d e f g h i j k l m n o p q r s t u v w x y z ch | ch == 'a' = a\n | ch == 'b' = b\n | ch == 'c' = c\n | ch == 'd' = d\n | ch == 'e' = e\n | ch == 'f' = f\n | ch == 'g' = g\n | ch == 'h' = h\n | ch == 'i' = i\n | ch == 'j' = j\n | ch == 'k' = k\n | ch == 'l' = l\n | ch == 'm' = m\n | ch == 'n' = n\n | ch == 'o' = o\n | ch == 'p' = p\n | ch == 'q' = q\n | ch == 'r' = r\n | ch == 's' = s\n | ch == 't' = t\n | ch == 'u' = u\n | ch == 'v' = v\n | ch == 'w' = w\n | ch == 'x' = x\n | ch == 'y' = y\n | ch == 'z' = z\n\ncalc :: [Char] -> (Char -> Char) -> [Char] \ncalc [] ch = [] \ncalc (x:xs) ch = ((ch x) : (calc xs ch))\n\nreadLines 0 = do return []\nreadLines n = do line <- getLine\n other <- readLines (n - 1)\n return (line : other)\n\nmain = do ns <- getLine\n nums <- return (split ns)\n name <- getLine\n c <- readLines (head (tail nums))\n solution <- return (calc name (mapper \n (next 'a' c)\n (next 'b' c)\n (next 'c' c)\n (next 'd' c)\n (next 'e' c)\n (next 'f' c)\n (next 'g' c)\n (next 'h' c)\n (next 'i' c)\n (next 'j' c)\n (next 'k' c)\n (next 'l' c)\n (next 'm' c)\n (next 'n' c)\n (next 'o' c)\n (next 'p' c)\n (next 'q' c)\n (next 'r' c)\n (next 's' c)\n (next 't' c)\n (next 'u' c)\n (next 'v' c)\n (next 'w' c)\n (next 'x' c)\n (next 'y' c)\n (next 'z' c)\n ))\n putStrLn solution\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\n\nprocess :: [String] -> (String, [String])\nprocess str \n = (h, t)\n where \n (h:t) = tail str \n\nchange' :: Char -> Char -> [(Char,Char)] -> [(Char,Char)]\nchange' x y rules\n = map (\\(x',y') -> if x == x' then (x,y) else (x',y') ) rules \n\nrep :: [Char] -> [(Char,Char)] -> [(Char,Char)]\nrep myPair rules \n = change' x' y ( change' y' x rules )\n where \n [x,y] = myPair\n x' = fromJust $ lookup x revRules\n y' = fromJust $ lookup y revRules\n revRules = zip r2 r1\n (r1,r2) = unzip rules\n\ninitR :: [(Char,Char)]\ninitR = zip ['a'..'z'] ['a'..'z']\n\nchange :: String -> [(Char,Char)] -> String\nchange str rules\n = map ( fromJust . ( ( flip lookup ) rules ) ) str \n\nsolve :: (String, [String]) -> String\nsolve (str, ops)\n = change str ( foldl (\\acc x -> rep ( map head ( words x ) ) acc ) initR ops ) \n \nmain = ( solve . process . lines) <$> getContents >>= putStrLn\n\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Exception (assert)\nimport Control.Monad hiding (foldM)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray, (!))\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport Data.Word\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n _ <- getLine\n cs <- getLine\n xys <- map B.head.B.words <$> B.getContents\n putStrLn $ solve cs xys\n\nsolve :: String -> String -> String\nsolve cs xys = [d|c<-cs,let Just d=lookup c table ]\n where\n !table = go (zip['a'..'z']['a'..'z']) xys\n go table (x:y:rest) = table `deepseq` go (swap x y table) rest\n go table _ = table\n\nswap x y table | x == y = table\nswap x y table = go table\n where\n go ((from,to):rest)\n | to == x = (from, y):go rest\n | to == y = (from, x):go rest\n | otherwise = (from,to):go rest\n go _ = []\n\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nwhenM, unlessM :: Monad m => m Bool -> m () -> m ()\nwhenM p f=p>>=flip when f\nunlessM p f=p>>=flip unless f\n{-# INLINE whenM #-}\n{-# INLINE unlessM #-}\nfoldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM f a xs=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=assert(inRange(bounds a)i).unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;assert(inRange lr i)$unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;assert(inRange lr i)$unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;assert(inRange lr i)$unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}"}, {"source_code": "import qualified Data.List as L\nimport qualified Data.HashMap.Lazy as H\n\nmain :: IO ()\nmain = interact parse\n\nparse input =\n let (_:name:tail) = lines input\n designers = map (map head . words) tail\n alpha = switch designers ['a'..'z']\n hash = build_alpha ['a'..'z'] alpha H.empty\n in map (\\a -> hash H.! a) name\n\nbuild_alpha [] [] hash = hash\nbuild_alpha (a:as) (b:bs) hash =\n build_alpha as bs (H.insert a b hash)\n\n\nswitch [] name = name\nswitch (d:ds) name =\n let name' = case d of\n (x:y:_) -> map (\\a -> if a == x then y else if a == y then x else a) name\n in switch ds name'\n"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array \nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\nconvert::String -> [[String]] -> String\nconvert s [] = s \nconvert s ([p,n]:ms) = convert (con s (head p) (head n)) ms \ncon::String-> Char -> Char -> String\ncon [] p n = [] \ncon (c:s) p n\n | c==p = n:con s p n\n | c==n = p:con s p n\n | otherwise = c:con s p n\nmain = do\n [n,m] <- readLists\n s <- getLine\n m <- fmap (map words) $ fmap lines $ getContents\n let a = listArray ('a','z') $ convert ['a'..'z'] m \n putStr $ map (\\x -> (a ! x)) s\n"}], "negative_code": [{"source_code": "module Main\n where\n\ntoInts :: [String] -> [Int]\ntoInts = map read\n\nsplitStr :: Int -> String -> [Int]\nsplitStr n (' ':xs) = n : (splitStr 0 xs)\nsplitStr n ('1':xs) = splitStr (n * 10 + 1) xs\nsplitStr n ('2':xs) = splitStr (n * 10 + 2) xs\nsplitStr n ('3':xs) = splitStr (n * 10 + 3) xs\nsplitStr n ('4':xs) = splitStr (n * 10 + 4) xs\nsplitStr n ('5':xs) = splitStr (n * 10 + 5) xs\nsplitStr n ('6':xs) = splitStr (n * 10 + 6) xs\nsplitStr n ('7':xs) = splitStr (n * 10 + 7) xs\nsplitStr n ('8':xs) = splitStr (n * 10 + 8) xs\nsplitStr n ('9':xs) = splitStr (n * 10 + 9) xs\nsplitStr n ('0':xs) = splitStr (n * 10 + 0) xs\nsplitStr n [] = [n]\n\nsplit s = splitStr 0 s\n\nnext :: Char -> [String] -> Char\nnext ch [] = ch\nnext ch (x:xs) | ch == (head x) = next (head (tail (tail x))) xs\n | ch == (head (tail (tail x))) = next (head x) xs\n | otherwise = next ch xs\n\nmapper a b c d e f g h i j k l m n o p q r s t u v w x y z ch | ch == 'a' = a\n | ch == 'b' = b\n | ch == 'c' = c\n | ch == 'd' = d\n | ch == 'e' = e\n | ch == 'f' = f\n | ch == 'g' = g\n | ch == 'h' = h\n | ch == 'i' = i\n | ch == 'j' = j\n | ch == 'k' = k\n | ch == 'l' = l\n | ch == 'm' = m\n | ch == 'n' = n\n | ch == 'o' = o\n | ch == 'p' = p\n | ch == 'q' = q\n | ch == 'r' = r\n | ch == 's' = s\n | ch == 't' = t\n | ch == 'u' = u\n | ch == 'v' = v\n | ch == 'w' = w\n | ch == 'x' = x\n | ch == 'y' = y\n | ch == 'z' = z\n\ncalc :: [Char] -> (Char -> Char) -> [Char] \ncalc [] ch = [] \ncalc (x:xs) ch = ((ch x) : (calc xs ch))\n\nreadLines 0 = do return []\nreadLines n = do line <- getLine\n other <- readLines (n - 1)\n return (line : other)\n\nmain = do ns <- getLine\n nums <- return (split ns)\n name <- getLine\n c <- readLines (head (tail nums))\n solution <- return (calc name (mapper (next 'a' c) (next 'b' c) (next 'c' c) (next 'd' c) (next 'e' c) (next 'f' c) (next 'g' c) (next 'h' c) (next 'i' c) (next 'j' c) (next 'k' c) (next 'l' c) (next 'm' c) (next 'n' c) (next 'o' c) (next 'p' c) (next 'q' c) (next 'e' c) (next 's' c) (next 't' c) (next 'u' c) (next 'v' c) (next 'w' c) (next 'x' c) (next 'y' c) (next 'z' c)))\n putStrLn solution\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nprocess :: [String] -> (String, [String])\nprocess str \n = (h, t)\n where \n (h:t) = tail str \n\nrep :: [Char] -> String -> String\nrep myPair str \n = map (\\x' -> rep' x' ) str\n where \n [x,y] = myPair\n rep' x' \n | x == x' = y\n | y == x' = x\n | otherwise = x' \n\nsolve :: (String, [String]) -> String\nsolve (str, ops)\n = foldl (\\acc x -> rep ( map head ( words x ) ) acc ) str ops \n \nmain = ( solve . process . lines) <$> getContents >>= print\n\n \n"}], "src_uid": "67a70d58415dc381afaa74de1fee7215"} {"source_code": "import Data.List\nsolve n = positive - 2 * negetive \n where positive = div (n * n + n) 2\n negetive = sum.filter (<=n) $ [2^x | x <- [0..100]]\nmain = do\n t <- readLn :: IO Int\n as <- getContents >>= return. map read. lines :: IO [Integer]\n putStrLn.intercalate \"\\n\". map (show.solve) $ as\n", "positive_code": [{"source_code": "main :: IO()\nmain = mapM_ (print . solve) . map read . tail . words =<< getContents\n\nsolve :: Integer -> Integer\nsolve n = (div (n * (n + 1)) 2) - (pow2sum 1 n) * 2\n\npow2sum :: Integer -> Integer -> Integer\npow2sum p n | p > n = 0\n | otherwise = p + (pow2sum (p * 2) n)\n"}, {"source_code": "import Data.List (foldl')\nimport Control.Applicative ((<$>))\nimport Test.QuickCheck\n\nlog2Floor n = floor $ (log $ fromIntegral n) / (log 2)\n\npower2 x = 2^x \n\ntrickySum n = integerSum n - 2 * (twoSum n)\n\n-- double is tricky in Haskell, use `div`\nintegerSum n = n * (n+1) `div` 2\n\ntwoSum n = sum (map power2 [0 ..(log2Floor n)])\n\nreadInt::String -> Integer\nreadInt = read\n\nmain = do\n input <- map readInt . tail . lines <$> getContents\n let res = map trickySum input\n mapM_ print res\n"}, {"source_code": "main = do\n\tns <- (tail . map read . lines) `fmap` getContents\n\n\tlet solve n = a - 2*b\n\t where\n\t\ta = n * (n + 1) `div` 2\n\t\tp = last $ takeWhile (<= n) $ map (2^) [0..]\t\n \t\tb = 2*p - 1\n\n\tputStr . unlines $ map (show . solve) ns\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nreadInteger :: String -> Integer\nreadInteger = read\nmain = do\n nums <- map readInteger . tail . lines <$> getContents\n mapM_ (putStrLn . show) $ map solve nums\n \nsolve :: Integer -> Integer\nsolve n = n * (n + 1) `div` 2 - 2 * (sum . takeWhile (<= n) $ map (2 ^) [0..])"}, {"source_code": "import Control.Applicative\n\nmain = do\n ans <- map (show . solve . read) . tail . words <$> getContents\n sequence_ . map putStrLn $ ans\n\nsolve n = n * (n + 1) `div` 2 - 2 * (sum . takeWhile (<= n) . map (2 ^) $ [0 ..])\n"}, {"source_code": "main :: IO ()\nmain =\n getContents >>= putStr . unlines . map (show . solve . read) . tail . lines\n where\n solve :: Integer -> Integer\n solve n = n * (n + 1) `quot` 2 - 2 * (head $ take 1 $ filter (>n) [2^x | x <- [0..]]) + 2\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess x = s -s1 -s1\n where s = div ((x+1)*x) 2\n s1 = sum $ takeWhile (<=x) [2^i|i<-[0..]]\n\nmain::IO ()\nmain=do\n getLine\n x<- map read <$> lines <$> getContents ::IO [Integer]\n mapM_ print $ map process x\n"}, {"source_code": "main = interact $ unlines . map (show . solve . read) . tail . words\nsolve n = n*(n+1) `div` 2 - 2^(floor (logBase 2 (fromIntegral n)) + 2) + 2\n"}, {"source_code": "#!/usr/bin/runhaskell\n\nroundUpToPowerOfTwo :: Integer -> Integer\nroundUpToPowerOfTwo x = head (dropWhile (<= x) [2 ^ i | i <- [0 ..]])\n\ncalcResult :: Integer -> Integer\ncalcResult x = x * (x + 1) `div` 2 - 2 * (roundUpToPowerOfTwo x - 1)\n\nmain = do\n getLine -- Skip first line\n contents <- getContents\n mapM_ putStrLn (map (show . calcResult . read) (lines contents))\n"}, {"source_code": "import Data.List\nimport Data.Bits\nimport Control.Arrow\n\nsolve :: Integer -> Integer\nsolve = uncurry (+) . ((\\x -> (*(-2)) . sum $ takeWhile (<= x) $ map (shiftL 1) [0..]) &&& (\\x -> shiftR (x*(x+1)) 1))\n\nmain = interact (unlines . map (show . solve . read) . tail . lines) \n"}, {"source_code": "import Control.Monad (replicateM)\n\nlog2 :: Integer -> Integer\nlog2 = floor . (logBase 2) . fromIntegral\n\nprocess :: String -> String\nprocess input = show answer\n where\n number = (read :: String -> Integer) input\n answer = number * (number + 1) `div` 2 - 2 * (2 ^ (log2 number + 1) - 1)\n\nmain = do\n t_str <- getLine\n inputs <- replicateM (read t_str) getLine\n putStr $ unlines $ map process inputs"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\n\nonecase = do \n\t\tx<-read<$>getLine::IO Integer\n\t\tlet x1 = div (x*(x+1)) 2\n\t\tlet x2 = length $ takeWhile (>0) [div x (2^i)| i<-[0..]]\n\t\tlet x3 = x1 +2 -2^(x2+1)\n\t\tprint x3\n\n\t\t\n \n\n\nmain= do\t \n\tn<- read<$> getLine ::IO Int\n\treplicateM_ n onecase \n\t\n\n\n\t\n \n\t \n\t "}, {"source_code": "\n\ncalcResult :: Integer -> Integer\ncalcResult x = x * (x + 1) `div` 2 - 2 * (sum . takeWhile (<= x) . map (2^) $ [0..])\n\nmain = do\n getLine -- Skip first line\n contents <- getContents\n mapM_ print (map ( calcResult . read) (lines contents))\n"}, {"source_code": "\n\ncalcResult :: Integer -> Integer\ncalcResult x = x * (x + 1) `div` 2 - 2 * ((head . dropWhile (<= x) . map (2^) $ [0..])-1)\n\nmain = do\n getLine -- Skip first line\n contents <- getContents\n mapM_ print (map ( calcResult . read) (lines contents))\n"}, {"source_code": "powers :: (Integral a) => a -> a\npowers 0 = 0\npowers n = 1 + 2 * (powers $ n `div` 2)\n\ncalculate :: (Integral a) => a -> a\ncalculate x = x * (x+1) `div` 2 - 2 * powers x\n\nmain :: IO ()\nmain = interact $ unlines . map (show . calculate . read) . tail . words\n"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n print $ n * (n+1) `div` 2 - 2 * sum (takeWhile (<=n) $ map (2^) [0..])\n"}], "negative_code": [{"source_code": "import Data.List (foldl')\nimport Control.Applicative ((<$>))\n\nlog2Floor :: (Integral b, Integral a) => a -> b\nlog2Floor n = floor $ (log (fromIntegral n)) / (log 2)\n\npower2 x = 2^x \n\nsumTotal :: (Integral b, Integral a) => a -> b\nsumTotal n = floor (allSum n - 2 * (twoSum n))\n where allSum n = (fromIntegral $ (1+n)*n) / 2\n twoSum n = sum (map power2 [0..(log2Floor n)])\n\nreadInt::String -> Integer\nreadInt = read\n\nmain = do\n input <- map readInt . tail . lines <$> getContents\n let res = map sumTotal input\n mapM_ print res\n\n--ifPower2 n = fromIntegral (floor log2) == log2\n-- where log2 = (log n)/(log 2)\n--\n--sum'' [] = 0\n--sum'' (x:xs) = if (ifPower2 x)\n-- then (-1) * x + sum'' xs\n-- else x + sum'' xs\n--\n--minusPlus x y = if (ifPower2 y)\n-- then x + (-1)*y\n-- else x + y\n--\n--sum' xs = foldl' minusPlus 0 xs\n\n\n"}, {"source_code": "import Data.List (foldl')\nimport Control.Applicative ((<$>))\n\nlog2Floor :: (Integral b, Integral a) => a -> b\nlog2Floor n = floor $ (log (fromIntegral n)) / (log 2)\n\npower2 x = 2^x \n\nsumTotal n = allSum n - 2 * (twoSum n)\n where allSum n = (fromIntegral $ (1+n)*n) / 2\n twoSum n = sum (map power2 [0..(log2Floor n)])\n\nreadInt::String -> Integer\nreadInt = read\n\n--ifPower2 n = fromIntegral (floor log2) == log2\n-- where log2 = (log n)/(log 2)\n--\n--sum'' [] = 0\n--sum'' (x:xs) = if (ifPower2 x)\n-- then (-1) * x + sum'' xs\n-- else x + sum'' xs\n--\n--minusPlus x y = if (ifPower2 y)\n-- then x + (-1)*y\n-- else x + y\n--\n--sum' xs = foldl' minusPlus 0 xs\n\nmain = do\n input <- map readInt . tail . words <$> getLine\n let res = map sumTotal input\n mapM_ print res\n"}, {"source_code": "import Data.List (foldl')\nimport Control.Applicative ((<$>))\n\nlog2Floor :: (Integral b, Integral a) => a -> b\nlog2Floor n = floor $ (log (fromIntegral n)) / (log 2)\n\npower2 x = 2^x \n\nsumTotal :: (Integral b, Integral a) => a -> b\nsumTotal n = floor (allSum n - 2 * (twoSum n))\n where allSum n = (fromIntegral $ (1+n)*n) / 2\n twoSum n = sum (map power2 [0..(log2Floor n)])\n\nreadInt::String -> Integer\nreadInt = read\n\nmain = do\n input <- map readInt . tail . words <$> getLine\n let res = map sumTotal input\n mapM_ print res\n\n--ifPower2 n = fromIntegral (floor log2) == log2\n-- where log2 = (log n)/(log 2)\n--\n--sum'' [] = 0\n--sum'' (x:xs) = if (ifPower2 x)\n-- then (-1) * x + sum'' xs\n-- else x + sum'' xs\n--\n--minusPlus x y = if (ifPower2 y)\n-- then x + (-1)*y\n-- else x + y\n--\n--sum' xs = foldl' minusPlus 0 xs\n\n\n"}, {"source_code": "import Data.List (foldl')\nimport Control.Applicative ((<$>))\n\nlog2Floor n = floor $ (log n) / (log 2)\n\npower2 x = 2^x \n\ntrickySum n = integerSum n - 2 * (twoSum n)\n\n-- double is tricky in Haskell\nintegerSum n = round $ ((1+n)*n) * (1/2)\n\ntwoSum n = sum (map power2 [0 ..(log2Floor n)])\n\nreadInt::String -> Double\nreadInt = read\n\nmain = do\n input <- map readInt . tail . lines <$> getContents\n let res = map trickySum input\n mapM_ print res\n\n--ifPower2 n = fromIntegral (floor log2) == log2\n-- where log2 = (log n)/(log 2)\n--\n--sum'' [] = 0\n--sum'' (x:xs) = if (ifPower2 x)\n-- then (-1) * x + sum'' xs\n-- else x + sum'' xs\n--\n--minusPlus x y = if (ifPower2 y)\n-- then x + (-1)*y\n-- else x + y\n--\n--sum' xs = foldl' minusPlus 0 xs\n\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess x = s -s1 -s1\n where s = div ((x+1)*x) 2\n s1 = sum $ takeWhile ( lines <$> getContents ::IO [Integer]\n mapM_ print $ map process x\n"}, {"source_code": "#!/usr/bin/runhaskell\n\nroundUpToPowerOfTwo :: Integer -> Integer\nroundUpToPowerOfTwo x = head (dropWhile (<= x) [2 ^ i | i <- [0 ..]])\n\ncalcResult :: Integer -> Integer\ncalcResult x = x * (x + 1) `div` 2 - 2 * (roundUpToPowerOfTwo x - 1)\n\nmain = do\n getLine -- Skip first line\n contents <- getContents\n mapM_ putStr (map (show . calcResult . read) (lines contents))\n"}, {"source_code": "import Data.List\nimport Data.Bits\nimport Control.Arrow\n\nsolve :: Integer -> Integer\nsolve = uncurry (+) . ((\\x -> (*(-2)) . sum $ takeWhile (<= x) $ map (shiftL 1) [0..]) &&& (\\x -> shiftR (x*(x+1)) 1))\n\nmain = interact (show . unlines . map (show . solve . read) . tail . lines) \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\n\nonecase = do \n\t\tx<-read<$>getLine::IO Integer\n\t\tlet x1 = div (x*(x+1)) 2\n\t\tlet x2 = length $ takeWhile (>0) [div x (2^i)| i<-[0..]]\n\t\tlet x3 = x1 +2 -2^x2\n\t\tprint x3\n\n\t\t\n \n\n\nmain= do\t \n\tn<- read<$> getLine ::IO Int\n\treplicateM_ n onecase \n\t\n\n\n\t\n \n\t \n\t "}], "src_uid": "a3705f29b9a8be97a9e9e54b6eccba09"} {"source_code": "import Data.Char\n\nmu p a b | a == b = a\n | p c = mu p a c\n | otherwise = mu p (c+1) b\n where c = (a+b) `div` 2\ns x = fromIntegral $ sum (map digitToInt $ show x)\n\nf 0 = 0\nf x = 10 * f n + 45 * n + s n * k + k*(k-1) `div` 2 where (n,k) = x `divMod` 10\nsolve :: Integer->[Integer]\nsolve a | a<=9*200 = [n,n]\n | otherwise = head [ [l,r] |\n k<-[0..200], \n let n9=10^k-1, \n let l = mu (\\l->f (10^k) - f l <= a) 0 (10^k),\n l>0,\n let r = head [r | r<-[10^k-1..], f (r+1)-f l >=a], \n f (r+1) - f l == a] \n where \n n=10^(-d)-1-m\n (d,m)=(-a) `divMod` 9\nmain = interact $ unwords . map show . solve . read \n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nf x = sum $ map (fromIntegral.digitToInt) $ show x\n\nsolve :: Integer -> Integer\nsolve n = go (map (fromIntegral.digitToInt) $ show n) where\n go [] = 0\n go [v] = sum [1..v]\n go (v:vs) = v * ((v-1) * 10 ^ d `div` 2 + d * 10^(d-1) * 45 + decimal vs + 1) + go vs where\n d = fromIntegral $ length vs\n\nsolve' l r = solve r - solve (l-1)\n\nhack :: Integer -> (String,String)\nhack a = head $ do\n d <- [1..]\n let x = d * 10^(d-1) * 45 + 1\n k <- [(10^(d-1) + x) `div` a .. (10^d + x + a-1) `div` a - 1]\n let vs = k * a - x\n guard $ 10^(d-1) <= vs && vs < 10^d\n return ('1':show vs,show (vs+1))\n\ndecimal = foldl (\\a b -> a * 10 + b) 0 \n\nprop_solve :: Integer -> Bool\nprop_solve x = sum (map f [0..x]) == solve x\n\n\nmain :: IO ()\nmain = do\n a <- readLn\n let (r,l) = hack a\n putStrLn $ unwords [l,r]\n\n"}, {"source_code": "import Data.Word (Word64)\nimport Control.Applicative ((<$>))\n\ncumDigitSum :: Word64 -> Word64\ncumDigitSum n = loop n k\n where\n k = last $ takeWhile (\\i -> 10^i < n + 1) [0..]\n loop 0 _ = 0\n loop n k = x * 45 * k * 10^(k - 1)\n + (x * (x - 1) `div` 2) * 10^k\n + x * (r + 1) + rest\n where\n (x, r) = n `divMod` (10^k)\n rest = loop r (k - 1)\n\nfind :: Word64 -> Word64\nfind 0 = 0\nfind a = loop (ub `div` 2) ub\n where\n ub = head . dropWhile ((< a) . cumDigitSum) $ iterate (2*) 1\n loop lb ub\n | lb + 1 == ub = ub\n | cumDigitSum i < a = loop i ub\n | otherwise = loop lb i\n where i = (lb + ub) `div` 2\n\nsolve :: Word64 -> (Word64, Word64)\nsolve a = loop (find a)\n where\n loop r = if x == a + cumDigitSum l then (l + 1, r) else loop (r + 1)\n where\n x = cumDigitSum r\n l = find (x - a)\n\nmain = do\n a <- read <$> getLine\n let (l, r) = solve a\n putStrLn $ show l ++ \" \" ++ show r\n"}, {"source_code": "import Data.Word (Word64)\nimport Control.Applicative ((<$>))\n\ncumDigitSum :: Word64 -> Word64\ncumDigitSum n = loop n k\n where\n k = last $ takeWhile (\\i -> 10^i < n + 1) [0..]\n loop 0 _ = 0\n loop n k = x * 45 * k * 10^(k - 1)\n + (x * (x - 1) `div` 2) * 10^k\n + x * (r + 1) + rest\n where\n (x, r) = n `divMod` (10^k)\n rest = loop r (k - 1)\n\nfind :: Word64 -> Word64\nfind a = loop 0 ub\n where\n ub = head . dropWhile ((< a) . cumDigitSum) $ iterate (2*) 2\n loop lb ub\n | lb + 1 == ub = ub\n | cumDigitSum i < a = loop i ub\n | otherwise = loop lb i\n where i = (lb + ub) `div` 2\n\nsolve :: Word64 -> (Word64, Word64)\nsolve a = loop (find a)\n where\n loop r = if x == a + cumDigitSum l then (l + 1, r) else loop (r + 1)\n where\n x = cumDigitSum r\n l = find (x - a)\n\nmain = do\n a <- read <$> getLine\n let (l, r) = solve a\n putStrLn $ show l ++ \" \" ++ show r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nf x = sum $ map (fromIntegral.digitToInt) $ show x\n\nsolve :: Integer -> Integer\nsolve n = go (map (fromIntegral.digitToInt) $ show n) where\n go [] = 0\n go [v] = sum [1..v]\n go (v:vs) = v * ((v-1) * 10 ^ d `div` 2 + d * 10^(d-1) * 45 + decimal vs + 1) + go vs where\n d = fromIntegral $ length vs\n\nsolve' l r = solve r - solve (l-1)\n\nhack a = head $ do\n d <- [1..]\n let x = d * 10^(d-1) * 45 + 1\n k <- [(10^(d-1) + x) `div` a .. (10^d + x + a-1) `div` a - 1]\n let vs = k * a - x\n guard $ 10^(d-1) <= vs && vs < 10^d\n return ('1':show vs,show (vs+1))\n\ndecimal = foldl (\\a b -> a * 10 + b) 0 \n\nprop_solve :: Integer -> Bool\nprop_solve x = sum (map f [0..x]) == solve x\n\n\n\nmain = putStrLn \"Hello World!\"\n"}], "src_uid": "52b8d97f216ea22693bc16fadcd46dae"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n tbl <- replicateM n getLine\n print $ solve n m tbl\n\nsolve :: Int -> Int -> [String] -> Int\nsolve n m tbl = go [\"\" | i <- [1..n]] (transpose tbl) 0 where\n go _ [] !acc = acc\n go cur (l:ls) !acc \n | good cur1 = go cur1 ls acc \n | otherwise = go cur ls (acc+1) where\n cur1 = zipWith (\\a b -> a ++ [b]) cur l\n\ngood :: [String] -> Bool\ngood l = and $ zipWith (<=) l (tail l)\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine :: IO [Int]\n css <- transpose.lines <$> getContents\n print $ solve css\n\nsolve :: [String] -> Int\nsolve css0 = go 0 css0\n where\n go !cnt (cs:rest)\n | isAscending cs = go2 cnt (group cs) rest\n | otherwise = go (cnt+1) rest\n go cnt [] = cnt\n go2 !cnt ccs [] = cnt\n go2 !cnt ccs (xs:xss)\n | all isAscending yss = if all((1==).length)yss then cnt\n else go2 cnt (concatMap group yss) xss\n | otherwise = go2 (cnt+1) ccs xss\n where\n ls = map length ccs\n f (l:ls) cs = take l cs : f ls (drop l cs)\n f _ _ = []\n yss = f ls xs\n\nisAscending :: String -> Bool\nisAscending (c:cs) = and $ zipWith (<=) (c:cs) cs\nisAscending [] = True\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntsIO\n ls <- replicateM n getLine\n print . solve $ [ls]\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map read . words <$> getLine\n\nsolve :: [[String]] -> Int\nsolve = go 0\n where\n go acc [] = acc\n go acc xsss = if mustBeRemoved xsss\n then go (acc+1) (droppedXsss xsss)\n else go acc (splittedXsss xsss)\n\n mustBeRemoved :: [[String]] -> Bool\n mustBeRemoved = any (or . headUnordered)\n \n headUnordered :: [String] -> [Bool]\n headUnordered xss = zipWith ((>) `on` head) xss (tail xss)\n \n droppedXsss :: [[String]] -> [[String]]\n droppedXsss = filterNotNullMap (filterNotNullMap tail)\n \n splittedXsss :: [[String]] -> [[String]]\n splittedXsss = filter (not . null) . concatMap collect\n \n collect :: [String] -> [[String]]\n collect ([_]:_) = []\n collect ((x1:xs1):(x2:xs2):xss')\n | x1 == x2 = (xs1 : xs2 : (map tail . takeWhile ((x1 ==) . head) $ xss')) : (collect . dropWhile ((x1 ==) . head) $ xss')\n | otherwise = collect ((x2:xs2):xss')\n collect _ = []\n \n filterNotNullMap f = filter (not . null) . map f\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts <$> B.getLine\n mismatch <- newArray (0, m - 1) False :: IO (IOUArray Int Bool)\n ls <- replicateM n B.getLine\n let iteration = and <$> zipWithM (makeMatch m mismatch) ls (tail ls)\n let iteration2 = iteration >>= (\\r -> if r then return True else iteration2)\n void iteration2 \n print =<< length <$> filterM (readArray mismatch) [0..m-1]\n\nmakeMatch :: Int -> IOUArray Int Bool -> B.ByteString -> B.ByteString -> IO Bool\nmakeMatch m removed lhs rhs = go 0\n where\n go i\n | i == m = return True\n | otherwise = do\n isRemoved <- readArray removed i\n if isRemoved then go (i + 1) else match i\n match i = case compare (B.index lhs i) (B.index rhs i) of\n LT -> return True\n EQ -> go (i + 1)\n GT -> do\n writeArray removed i True\n return False\n --go (i + 1)\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n ls <- replicateM n getLine\n\n let\n isSorted xs = and $ zipWith (<=) xs $ tail xs\n\n f :: [[String]] -> Int\n f gs\n | head (head gs) == [] = 0\n | all (isSorted . map head) gs = f $ map (map tail) $ concat $ map (groupBy ((==) `on` head)) gs\n | otherwise = 1 + f (map (map tail) gs)\n\n print $ f [ls]\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntsIO\n ls <- replicateM n getLine\n print . solve $ ls\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map read . words <$> getLine\n\nsolve :: [String] -> Int\nsolve = go 0\n where\n go :: Int -> [String] -> Int\n go acc [] = acc\n go acc ([]:_) = acc\n go acc xss = if mustBeRemoved xss\n then go (acc + 1) $ map tail xss\n else go acc $ collect xss\n where\n mustBeRemoved xss' = any (> 0) . zipWith ((-) `on` ord . head) xss' $ tail xss'\n collect ((x1:xs1):(x2:xs2):xss')\n | x1 == x2 = xs1 : xs2 : (map tail . takeWhile ((x1 ==) . head) $ xss') ++ (collect . dropWhile ((x1 ==) . head) $ xss') \n | otherwise = collect ((x2:xs2):xss')\n collect _ = []\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntsIO\n ls <- replicateM n getLine\n print . solve $ ls\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map read . words <$> getLine\n\nsolve :: [String] -> Int\nsolve = go 0\n where\n go :: Int -> [String] -> Int\n go acc [] = acc\n go acc ([]:_) = acc\n go acc xss = if mustBeRemoved xss\n then go (acc + 1) $ map tail xss\n else go acc $ collect xss\n where\n mustBeRemoved xss' = any (> 0) . zipWith ((-) `on` ord . head) xss' $ tail xss'\n collect ((x1:xs1):(x2:xs2):xss')\n | x1 == x2 = xs1 : xs2 : (map tail . takeWhile ((x1 ==) . head) $ xss')\n | otherwise = collect ((x2:xs2):xss')\n collect _ = []\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts <$> B.getLine\n mismatch <- newArray (1, m) True :: IO (IOUArray Int Bool)\n ls <- B.lines <$> B.getContents\n zipWithM_ (makeMatch m mismatch) ls (tail ls)\n\nmakeMatch :: Int -> IOUArray Int Bool -> B.ByteString -> B.ByteString -> IO ()\nmakeMatch m removed lhs rhs = go 0\n where\n go i\n | i == m = return ()\n | otherwise = do\n isRemoved <- readArray removed i\n if isRemoved then go (i + 1) else match i\n match i = case compare (B.index lhs i) (B.index rhs i) of\n LT -> return ()\n EQ -> go (i + 1)\n GT -> do\n writeArray removed i True\n go (i + 1)\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words\n\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts <$> B.getLine\n mismatch <- newArray (0, m - 1) False :: IO (IOUArray Int Bool)\n ls <- replicateM n B.getLine\n zipWithM_ (makeMatch m mismatch) ls (tail ls)\n print =<< length <$> filterM (readArray mismatch) [0..m-1]\n\nmakeMatch :: Int -> IOUArray Int Bool -> B.ByteString -> B.ByteString -> IO ()\nmakeMatch m removed lhs rhs = go 0\n where\n go i\n | i == m = return ()\n | otherwise = do\n isRemoved <- readArray removed i\n if isRemoved then go (i + 1) else match i\n match i = case compare (B.index lhs i) (B.index rhs i) of\n LT -> return ()\n EQ -> go (i + 1)\n GT -> do\n writeArray removed i True\n go (i + 1)\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Function\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntsIO\n ls <- replicateM n getLine\n print . solve $ ls\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map read . words <$> getLine\n\n\nsolve :: [String] -> Int\nsolve = Set.size . go 0 Set.empty\n where\n go _ acc [] = acc\n go _ acc ([]:_) = acc\n go i acc xss = if mustBeRemoved xss\n then go (i+1) (Set.insert i acc) $ map tail xss\n else foldr Set.union Set.empty $ map (go (i+1) acc) $ collect xss\n where\n mustBeRemoved xss' = any (> 0) . zipWith ((-) `on` ord . head) xss' $ tail xss'\n collect ((x1:xs1):(x2:xs2):xss')\n | x1 == x2 = (xs1 : xs2 : (map tail . takeWhile ((x1 ==) . head) $ xss')) : (collect . dropWhile ((x1 ==) . head) $ xss') \n | otherwise = collect ((x2:xs2):xss')\n collect _ = []\n\n{-\nsolve :: [String] -> Int\nsolve = go 0\n where\n go :: Int -> [String] -> Int\n go acc [] = acc\n go acc ([]:_) = acc\n go acc xss = if mustBeRemoved xss\n then go (acc + 1) $ map tail xss\n else go acc $ collect xss\n where\n mustBeRemoved xss' = any (> 0) . zipWith ((-) `on` ord . head) xss' $ tail xss'\n collect ((x1:xs1):(x2:xs2):xss')\n | x1 == x2 = xs1 : xs2 : (map tail . takeWhile ((x1 ==) . head) $ xss') ++ (collect . dropWhile ((x1 ==) . head) $ xss') \n | otherwise = collect ((x2:xs2):xss')\n collect _ = []\n-}\n\n\n{-\nsolve :: [String] -> Int\nsolve = go 0 0\n where\n go :: Int -> [String] -> Int\n go acc _ [] = acc\n go acc _ ([]:_) = acc\n go acc i xss' = if mustBeRemoved xss'\n then go (acc + 1) 0 $ map (deleteAt i) xss\n else go acc (i + 1) xss\n where\n mustBeRemoved xss' = any (> 0) . zipWith (>) takeidx $ tail takeidx\n where takeidx = map (take i) xss'\n \n\ndeleteAt n xs = h ++ t\n where\n (h, _:t) = splitAt n xs\n-}\n\n "}], "src_uid": "a45cfc2855f82f162133930d9834a9f0"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do \n n' <- getLine\n let n = read n' :: Int\n forM_ [1..n] $ \\_ -> do\n getLine\n ns' <- getLine\n let ns = map (\\x -> read x :: Int) $ words ns'\n let a = map (head) $ group $ filter (/= '=') $ zipWith (\\x y -> if x == y then '=' else if y < x then '-' else '+') ns $ tail ns\n putStrLn $ if a == \"\" || a == \"-\" || a == \"+\" || a == \"-+\" then \"YES\" else \"NO\"\n\n", "positive_code": [{"source_code": "\r\ncollapse :: [Int] -> [Int]\r\ncollapse (x : y : xs) \r\n | x == y = collapse (y : xs)\r\n | otherwise = x : collapse (y : xs)\r\ncollapse x = x\r\n\r\nvalleys :: [Int] -> Int\r\nvalleys a = edge a + middle a \r\n where \r\n middle (x : y : z : xs) = eval + middle (y : z : xs)\r\n where eval = if x > y && y < z then 1 else 0\r\n middle _ = 0\r\n edge (x : []) = 1\r\n edge x = bgn + end\r\n where \r\n bgn = if a < b then 1 else 0\r\n end = if c > d then 1 else 0\r\n a = head x\r\n b = x !! 1\r\n d = last x\r\n c = last $ take m x\r\n m = length x - 1\r\n\r\n\r\nanswer :: Int -> Bool\r\nanswer 1 = True\r\nanswer _ = False\r\n\r\nsolve :: [Int] -> Bool \r\nsolve = answer . valleys . collapse\r\n\r\neveryOther [] = []\r\neveryOther (_ : x : xs) = (x : everyOther xs)\r\n\r\nveredict True = \"YES\"\r\nveredict False = \"NO\"\r\n\r\nmain = interact $ unlines . map (veredict . solve . map read . words) . everyOther . drop 1. lines\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do \n n' <- getLine\n let n = read n' :: Int\n forM_ [1..n] $ \\_ -> do\n getLine\n ns' <- getLine\n let ns = map (\\x -> read x :: Int) $ words ns'\n let m = minimum ns\n putStrLn $ if (length $ filter (\\x -> head x == m) $ group ns) > 1 then \"NO\" else \"YES\"\n \n"}], "src_uid": "7b6a3de5ad0975e4c43f097d4648c9c9"} {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/492/B\n\nimport Data.List\n\nsolve :: Int -> [Int] -> Double\nsolve l a = max (fromIntegral (max (head sa) (l - last sa))) x\n where sa = sort a\n x = (fromIntegral . maximum $ 0 : zipWith (-) (tail sa) sa) / 2\n\nmain :: IO ()\nmain = do\n [_, l] <- fmap (map read . words) getLine\n a <- fmap (map read . words) getLine\n print $ solve l a\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Applicative\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve s = show $ maximum [start, end, middle / 2]\n where (_:l:as) = read <$> words s :: [Double]\n (start:xs) = sort as\n end = l - last (start:xs)\n middle \n |null xs = 0\n |otherwise = maximum $ zipWith (-) xs (start:xs) \n"}, {"source_code": "import Data.List (sort, foldl')\n\n\nlight :: [Integer] -> Double\nlight ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs\n where (x:xs) = sort ys\n func (m, prev) next = (max m $ next-prev, next)\n\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain = do\n [_, f] <- fmap (map readInt) $ fmap words $ getLine\n second <- fmap (map readInt) $ fmap words $ getLine\n let sorted = sort second\n let l = last sorted\n let t = f + (f - l)*2\n let i = init sorted\n print $ light $ (f:l:t:i)\n"}, {"source_code": "import Data.List\n\ndist (x:xs) | xs /= [] = (head xs - x) : dist xs\n | otherwise = []\n\nsolve l xs = fromIntegral (maximum ds) / 2.0 where\n--solve l xs = ys where\n ys = if head xs == 0 then xs else -(head xs) : xs\n zs = if last ys == l then ys else ys ++ [l + (l - last ys)]\n ds = dist zs \n\nmain = do\n line <- getLine\n let [n, l] = map read $ words line :: [Int]\n line <- getLine\n let xs = map read $ words line :: [Int]\n print $ solve l (sort xs)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\ngetInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, l ] <- getInts\n\tas <- sort <$> getInts\n\n\tprintf \"%.12f\\n\" $ ( maximum :: [Double] -> Double ) [ fromIntegral $ head as, fromIntegral $ ( l - last as ), fromIntegral ( maximum $ 0 : diffs as ) / 2.0 ]\n\ndiffs ( a : as )\n\t| null as = []\n\t| otherwise = ( head as - a ) : diffs as\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Double\nsolve (n:l:a) =\n let sa = sort a\n in (fromIntegral (max ((head sa) * 2) (solve' sa))) * 0.5\n where\n solve' :: [Int] -> Int\n solve' [a] = (l - a) * 2\n solve' (a:b:x) = max (b - a) (solve' (b:x))\n"}, {"source_code": "import Data.List\n\n\n\nbiggap lst max\n | (length lst) == 1 = max\n | otherwise = biggap (tail lst) (maximum [max, (head (drop 1 lst)) - (head lst)])\n\n\nconv lst uu\n | (null lst) = reverse uu\n | otherwise = conv (tail lst) (((read (head lst))::Int) : uu)\n\n\nmain = do\n ff <- getLine\n let n = (read (head (words ff)))::Int\n d = (read (last (words ff)))::Int\n gg <- getLine\n\n \n let aa = (conv (words gg) [])\n srted = sort aa\n \n let cc = (biggap srted 0)\n\n mx = (maximum [ realToFrac ( ((head srted) - 0)), realToFrac ( (d - (last srted))), ( (realToFrac cc) / (realToFrac 2))])\n putStrLn (show mx)\n\n -- putStrLn (\"\\n\\n\\n\\n\")\n -- putStrLn (show (cc / (realToFrac 2)))\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "import Data.List\n\nmain = do\n [n, l] <- fmap (map read . words) getLine\n xs <- fmap (map head . group . sort . map read . words) getLine\n\n let\n d = (head xs):(l - last xs):(zipWith (\\a b -> (a+b)/2 - a) xs (tail xs))\n\n print $ maximum d\n"}, {"source_code": "import Data.List\nmain = interact $ show . (/2) . h . g . map read . tail . words\nf [l, x] = (l - x) * 2\nf (l:x:y:z) = max (y - x) $ f (l:y:z)\ng (a:b) = (a:sort b)\nh (l:x:y) = max (x * 2) $ f(l:x:y)"}, {"source_code": "import Control.Applicative\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\nsmap :: ((a,b) -> (c,b)) -> b -> [a] -> [c]\nsmap f s (l:ls) = (fst app):(smap f (snd app) ls)\n where app = f (l,s)\nsmap _ _ [] = []\n\nmain = interact $ show . rd . lines\nrd :: [String] -> Double\nrd [nl,as] = go (read . last . words $ nl) (map read . words $ as)\ngo :: Double -> [Double] -> Double\ngo l as = maximum $ [frst,scnd,thrd]\n where frst = (/2) . maximum . smap (\\(x,y) -> (x-y,x)) (head lst) $ lst\n scnd = head lst\n thrd = l-(last lst)\n lst = sort as\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve. tail.concat.map (map read.words). take 2. lines\nsolve :: [Integer]->String\nsolve (x:xs) = show $ (/2) $ fromIntegral $ maximum $ zipWith (\\a b->a-b) (s1:s1s) (s1:init (s1:s1s))\n where \n (s:ss)=sort xs\n (s1:s1s)=(-s):(s:ss)++(x+x-last (s:ss)):[]"}, {"source_code": "import Data.List ( sort )\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs\n\nprocess :: Double -> [Double] -> Double\nprocess _ [] = 0.0\nprocess l xs =\n let xs' = zipWith (-) (xs ++ [l]) (0.0 : xs)\n in maximum $ (minimum xs - 0.0) : (l - maximum xs) : (map (/ 2.0) xs')\n\nmain :: IO ()\nmain = do\n input <- getLine\n lamps <- getLine\n let xs = map (read :: String -> Integer) (split ' ' input)\n let ys = map (read :: String -> Double) (split ' ' lamps)\n let l = xs !! 1\n print $ process (fromInteger l) (sort ys)\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ntoD :: Int -> Double\ntoD = fromIntegral\n\nsolve :: Int -> [Int] -> Double\nsolve l a = max (toD (max (head sa) (l - last sa))) x\n where sa = sort a\n x = (toD . maximum $ 0 : zipWith (-) (tail sa) sa) / 2\n\nmain :: IO ()\nmain = do\n [_, l] <- getIntList\n a <- getIntList\n print $ solve l a\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\n\nprocess s q = maximum [(fromIntegral x ) /2 ,fromIntegral(s- maximum q), fromIntegral(minimum q)]\n where x1 = zipWith (-) (tail q) q\n x = if x1==[] then 0 else ( maximum x1)\n\nmain=do\n [n,s]<-map read <$> words <$>getLine ::IO [Int]\n q<- (sort <$> map read <$> words <$>getLine )::IO [Int]\n print $ process s q\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve (_:l:as) = maximum (head bs : (l - last bs) : map (/2) (zipWith (-) (tail bs) bs))\n where bs = sort as\nsolve _ = undefined\n"}, {"source_code": "import Data.List (group,sort)\nreadNums = fmap (map read . words) getLine\nmain = do\n [n,l] <- readNums\n as <- fmap (map ((*2) . head) . group . sort) readNums\n print $ fromIntegral (bsearch as 0 (2*l)) / 2\nbsearch as l road = go l road\n where go l r | l + 1 == r = r\n | v m = go l m\n | otherwise = go m r\n where m = (l + r) `div` 2\n v r = all (uncurry cover) (zip as' (tail as'))\n where cover a b = b - a <= 2 * r\n as' = (-r) : as ++ [road+r]\n"}, {"source_code": "import Data.List\nimport System.IO\n\n\nreadInput :: Read a => IO [a]\nreadInput = fmap (map read . words) getLine \n\ngetNLine :: Int -> IO [String]\ngetNLine n\n | n <= 0 = return []\n | otherwise = do\n x <- getLine\n xs <- getNLine $ n-1\n let ret = (x:xs)\n return ret\n\nmain :: IO ()\nmain = do\n n <- readInput :: IO [Int]\n l <- readInput :: IO [Int]\n let xs = reverse (last n : reverse (0 : sort l))\n let dis = zipWith (-) (tail xs) xs \n -- print dis\n print $ solve dis\n -- putStrLn xs \n \n\nsolve :: [Int] -> Double\nsolve li = max max_dis end_point\n where\n max_dis = fromIntegral (maximum li) / 2\n end_point = fromIntegral (max (head li) (last li)) \n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n \n \n\nmain= do\n\t[x1,b1]<- map read. words <$> getLine ::IO [Int]\n\ts<-sort .map read. words <$> getLine ::IO [Int]\n\tlet s1= (head s ): s\n\tlet sm = maximum $ zipWith (-) (tail s1) s1 \n\tprint $ maximum [ (fromIntegral sm)/2.0, fromIntegral (head s) , fromIntegral (b1-(last s))]\n\n\t "}, {"source_code": "import Data.List\nmain = do\n [n, l] <- getLine >>= return. map read. words :: IO [Int] \n a <- getLine >>= return. Data.List.sort. map read. words :: IO [Double] \n print. maximum $ [head a, fromIntegral l - last a] ++ (map (/2).zipWith (-) (tail a) $ a)\n"}, {"source_code": "import Data.List\n\nanswer :: [Integer] ->Int\nanswer xs = if length xs == ans && odd (head xs - last xs) then ans +1 else ans \n where ans = snd $ foldl1 (\\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..]) \n \n \nreadnl ::String-> [Double]\nreadnl = fmap read . words\n\ndistance ::[Double]->Double\ndistance [x] = x\ndistance (x:xs) = maximum (zipWith (-) xs (x : xs)) / 2\n\nsomeFunc :: IO ()\nsomeFunc = do \n fl <- getLine\n let [n,l] = readnl fl\n sl <- getLine\n let coords = sort $ readnl sl\n let min = head coords\n let max = last coords\n print $ maximum [min, l-max, distance coords]\n \n \nmain :: IO ()\nmain = someFunc"}, {"source_code": "import Data.List (sort)\nimport Text.Printf (printf)\n\nprocess :: [Int] -> Int -> Double\nprocess xs@(_:ys) l\n | ys == [] = max d0 dl\n | otherwise = maximum [d0, di/2, dl]\n where\n xs' = sort xs\n d0 = fromIntegral $ head xs'\n dl = fromIntegral $ l - last xs'\n di = fromIntegral $ maximum $ zipWith (-) (tail xs') xs'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,l] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n printf \"%.10f\" $ process as l"}], "negative_code": [{"source_code": "import Data.List ( elemIndex )\nimport Data.Maybe ( fromJust )\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs\n\nprocess :: Double -> [Double] -> Double\nprocess _ [] = 0.0\nprocess l xs =\n let xs' =\n [ x - y\n | x <- xs\n , y <- xs\n , y /= x && fromJust (elemIndex x xs) - fromJust (elemIndex y xs) == 1\n ]\n xs'' = (minimum xs - 0) : (l - maximum xs) : (map (\\x -> x / 2.0) xs')\n in abs $ (maximum xs'')\n\nmain :: IO ()\nmain = do\n input <- getLine\n lamps <- getLine\n let xs = map (read :: String -> Integer) (split ' ' input)\n let ys = map (read :: String -> Double) (split ' ' lamps)\n let (_, l) = (xs !! 0, xs !! 1)\n print $ process (fromInteger l) ys\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\n\nprocess s q = (fromIntegral y ) /2\n where x = maximum $ zipWith (-) (tail q) q\n y = maximum [x, s- maximum q, minimum q]\nmain=do\n [s,n]<-map read <$> words <$>getLine ::IO [Int]\n q<- (sort <$> map read <$> words <$>getLine )::IO [Int]\n print $ process s q\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\n\nprocess s q = maximum [(fromIntegral x ) /2 ,fromIntegral(s- maximum q), fromIntegral(minimum q)]\n where x = maximum $ zipWith (-) (tail q) q\n\nmain=do\n [s,n]<-map read <$> words <$>getLine ::IO [Int]\n q<- (sort <$> map read <$> words <$>getLine )::IO [Int]\n print $ process s q\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\n\nprocess q = (fromIntegral x ) /2\n where x = maximum $ zipWith (-) (tail q) q\nmain=do\n [s,n]<-map read <$> words <$>getLine ::IO [Int]\n q<- (sort <$> map read <$> words <$>getLine )::IO [Int]\n print $ process q\n"}, {"source_code": "import Data.List (group,sort)\nreadNums = fmap (map read . words) getLine\nmain = do\n [n,l] <- readNums\n as <- fmap (map ((*2) . head) . group . sort) readNums\n print $ fromIntegral (bsearch l as 0 (2*l)) / 2\nbsearch road as l r = go l r\n where go l r | l + 1 == r = r\n | v m = go l m\n | otherwise = go m r\n where m = (l + r) `div` 2\n v r = all (uncurry cover) (zip as' (tail as'))\n where cover a b = b - a <= 2 * r\n as' = (-r) : as ++ [road+r]\n"}, {"source_code": "import Data.List (group,sort)\nreadNums = fmap (map read . words) getLine\nmain = do\n [n,l] <- readNums\n as <- fmap (map ((*2) . head) . group . sort) readNums\n print $ fromIntegral (bsearch as 0 (2*l)) / 2\nbsearch as l r = go l r\n where go l r | l + 1 == r = r\n | v m = go l m\n | otherwise = go m r\n where m = (l + r) `div` 2\n v r = all (uncurry cover) (zip as' (tail as'))\n where cover a b = b - a <= 2 * r\n as' = (-r) : as ++ [l+r]\n"}, {"source_code": "import Data.List\nimport System.IO\n\n\nreadInput :: Read a => IO [a]\nreadInput = fmap (map read . words) getLine \n\ngetNLine :: Int -> IO [String]\ngetNLine n\n | n <= 0 = return []\n | otherwise = do\n x <- getLine\n xs <- getNLine $ n-1\n let ret = (x:xs)\n return ret\n\nmain :: IO ()\nmain = do\n n <- readInput :: IO [Int]\n l <- readInput :: IO [Int]\n let xs = reverse (last n : reverse (0 : sort l))\n let dis = zipWith (-) (tail xs) xs \n print dis\n print $ solve dis\n -- putStrLn xs \n \n\nsolve :: [Int] -> Double\nsolve li = max max_dis end_point\n where\n max_dis = fromIntegral (maximum li) / 2\n end_point = fromIntegral (max (head li) (last li)) \n"}, {"source_code": "import Data.List\neps = 1e-8\nbin :: (Double -> Bool) -> Double -> Double -> Double\nbin f l r \n | r - l < eps = mid\n | f mid = bin f l mid\n | otherwise = bin f mid r\n where mid = (l + r) / 2\nisOk :: [Double] -> Double -> Double -> Bool\ngo :: [(Double, Double)] -> Double -> Double -> Bool\ngo [] l r = r <= l\ngo cur l r \n | l < s = False\n | otherwise = go state (max e l) r\n where (s, e):state = cur\nisOk a l d =\n go state 0 l\n where state = Data.List.sort [(x - d, x + d) | x <- a]\nmain = do\n [n, l] <- getLine >>= return. map read. words :: IO [Int] \n a <- getLine >>= return. map read. words :: IO [Double] \n let ll = fromIntegral l :: Double in print $ bin (isOk a ll) 0 ll\n"}, {"source_code": "import Data.List (sort)\nimport Text.Printf (printf)\n\nprocess :: [Int] -> Int -> Float\nprocess xs l = maximum [d0, di/2, dl]\n where\n xs' = sort xs\n d0 = fromIntegral $ head xs'\n dl = fromIntegral $ l - last xs'\n di = fromIntegral $ maximum $ zipWith (-) (tail xs') xs'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,l] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n printf \"%.10f\" $ process as l"}, {"source_code": "import Data.List (sort)\n\nprocess :: [Int] -> Int -> Float\nprocess xs l = maximum [d0, di/2, dl]\n where\n xs' = sort xs\n d0 = fromIntegral $ head xs'\n dl = fromIntegral $ l - last xs'\n di = fromIntegral $ maximum $ zipWith (-) (tail xs') xs'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,l] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n print $ process as l"}, {"source_code": "import Data.List (sort, foldl')\n\n\nlight :: [Int] -> Double\nlight ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs\n where (x:xs) = sort ys\n func (m, prev) next = (max m $ next-prev, next)\n\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n [_, f] <- fmap (map readInt) $ fmap words $ getLine\n second <- fmap (map readInt) $ fmap words $ getLine\n let l = last second\n let t = f + (f - l)*2\n let i = init second\n print $ light $ (f:l:t:i)\n"}, {"source_code": "import Data.List (sort, foldl')\n\n\nlight :: [Int] -> Float\nlight ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs\n where (x:xs) = sort ys\n func (m, prev) next = (max m $ next-prev, next)\n\n\nmain = do\n [_, f] <- fmap (map read) $ fmap words $ getLine\n second <- fmap (map read) $ fmap words $ getLine\n print $ light $ (f:second)\n"}, {"source_code": "import Data.List (sort, foldl')\n\n\nlight :: [Int] -> Double\nlight ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs\n where (x:xs) = sort ys\n func (m, prev) next = (max m $ next-prev, next)\n\n\nmain = do\n [_, f] <- fmap (map read) $ fmap words $ getLine\n second <- fmap (map read) $ fmap words $ getLine\n print $ light $ (f:second)\n"}, {"source_code": "import Data.List (sort, foldl')\n\n\nlight :: [Int] -> Double\nlight ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs\n where (x:xs) = sort ys\n func (m, prev) next = (max m $ next-prev, next)\n\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n [_, f] <- fmap (map readInt) $ fmap words $ getLine\n second <- fmap (map readInt) $ fmap words $ getLine\n let sorted = sort second\n let l = last sorted\n let t = f + (f - l)*2\n let i = init sorted\n print $ light $ (f:l:t:i)\n"}], "src_uid": "d79166497eb61d81fdfa4ef80ec1c8e8"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> map show >>> unlines\n\nprocess :: [String] -> [Int]\nprocess [] = []\nprocess (nl:s:xs) = solve c0 c1 h s : process xs\n where\n [_, c0, c1, h] = map read . words $ nl\n\nsolve :: Int -> Int -> Int -> String -> Int\nsolve c0 c1 h s = min c0 (h + c1) * count '0' + min c1 (h + c0) * count '1'\n where\n count d = length (filter (== d) s)\n", "positive_code": [{"source_code": "module Main where\n\n{-\ncalculatePrices :: Int -> [Int]\ncalculatePrices 0 = []\ncalculatePrices n = price:(calculatePrices $ n - 1)\n where price = 1\n-}\n\ncalculatePrices :: Int -> IO ()\n\ncalculatePrice :: (Int, Int, Int) -> [Bool] -> Int -> Int\n\n-- Helper functions\n\nextractMeta :: String -> (Int, Int, Int)\n\nconvertString :: String -> [Bool]\n\nsplit :: (Eq a) => a -> [a] -> [[a]]\n\ncalculatePrices 0 = return ()\ncalculatePrices n = do\n meta <- getLine\n string <- getLine\n putStrLn $ show $ calculatePrice (extractMeta meta) (convertString string) 0\n calculatePrices (n - 1)\n\ncalculatePrice _ [] acc = acc\ncalculatePrice (c0, c1, h) (True:ss) acc \n | c1 > h + c0 = calculatePrice (c0, c1, h) ss (acc + h + c0)\n | otherwise = calculatePrice (c0, c1, h) ss (acc + c1)\n \ncalculatePrice (c0, c1, h) (False:ss) acc\n | c0 > h + c1 = calculatePrice (c0, c1, h) ss (acc + h + c1)\n | otherwise = calculatePrice (c0, c1, h) ss (acc + c0)\n\nextractMeta source = (read $ tokens !! 1, read $ tokens !! 2, read $ tokens !! 3)\n where tokens = split ' ' source\n\nconvertString [] = []\nconvertString ('0':ss) = False:(convertString ss)\nconvertString ('1':ss) = True:(convertString ss)\n\nsplit _ [] = [[]]\nsplit d (c:cs)\n | d == c = []:(split d cs)\n | otherwise = let (h:t) = split d cs in (c:h):t\n\nmain = do\n testCases <- getLine\n calculatePrices $ read testCases\n -- foldl (>>) (return ()) (map (putStrLn . show) $ calculatePrices (read testCases :: Int))\n"}], "negative_code": [], "src_uid": "7cc0a6df601e3dcf4e1d9578dd599a36"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\n--import Data.Array.Unboxed\n\n\nquery :: [Int] -> Builder\nquery li = string7 \"? \" <> putInts li <> flush\n\nfinishSoln :: Int -> Int -> Int -> Int -> SP Builder\nfinishSoln currw x1 x2 x3 = let\n xs = [x1, x2, x3]\n y : _ = [1..4] \\\\ xs\n qs = map (flip delete $ y : xs) xs\n in (foldMap query qs <>) <$> do\n nxs <- replicateM 3 getInt\n let (z1, _) : (z2, _) : _ = sortOn snd $ zip (y : xs) (currw : nxs)\n pure $ string7 \"! \" <> putInts [z1, z2] <> flush\n\nsolnStep :: Int -> Int -> Int -> Int -> Int -> Int -> SP Builder\nsolnStep n i currw x1 x2 x3 = if i > n\n then finishSoln currw x1 x2 x3\n else (<>) (query [x2, x3, i] <> query [x1, x3, i]) <$> do\n no1 <- getInt\n no2 <- getInt\n case () of\n () | no1 >= max no2 currw -> solnStep n (i + 1) no1 x2 x3 i\n | no2 >= max no1 currw -> solnStep n (i + 1) no2 x1 x3 i\n | otherwise -> solnStep n (i + 1) currw x1 x2 x3\n\nsolve :: Int -> SP Builder\nsolve n = (query [1, 2, 3] <>) <$> do\n initw <- getInt\n solnStep n 4 initw 1 2 3\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n solve n\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Bits\nimport Data.List\nimport Control.Monad\nimport System.IO\nimport qualified System.Exit as Exit\n\nsolve4 :: Int -> Int -> Int -> Int -> (Int, Int)\nsolve4 xa xb xc xd = case maxes of\n [x] -> (x, x)\n [x, y] -> (x, y)\n _ -> error $ \"ambiguous: \" ++ show maxes\n where\n m = maximum [xa, xb, xc, xd]\n maxes = filter ((/=0) . (.&. maxmap) . (1 `shiftL`)) [0..3]\n maxmap = foldl' (.&.) 0xf $ map snd $ filter ((==m) . fst)\n [ (xa, 0xe::Int)\n , (xb, 0xd)\n , (xc, 0xb)\n , (xd, 0x7)\n ]\n\nquery :: Int -> Int -> Int -> IO Int\nquery i j k = do\n putStrLn $ \"? \" ++ show (i+1) ++ \" \" ++ show (j+1) ++ \" \" ++ show (k+1)\n w <- readLn\n when (w == -1) Exit.exitSuccess\n return w\n\nsolve :: Int -> IO ()\nsolve n = do\n w2 <- query 0 1 2\n phase0 2 w2 3\n where\n phase0 best bestW !i\n | i >= n = phase1 best 9999 (-1) 2\n | otherwise = do\n wi <- query 0 1 i\n if wi > bestW\n then phase0 i wi (i+1)\n else phase0 best bestW (i+1)\n\n phase1 p best bestW i\n | i >= n = phase2 p best bestW\n | i == p = phase1 p best bestW (i+1)\n | otherwise = do\n wi <- query 0 p i\n if wi > bestW\n then phase1 p i wi (i+1)\n else phase1 p best bestW (i+1)\n\n phase2 p q w0pq = do\n --putStrLn $ \"phase2: \" ++ show (p, q)\n w01p <- query 0 1 p\n w01q <- query 0 1 q\n w1pq <- query 1 p q\n let !(ix, iy) = solve4 w1pq w0pq w01q w01p\n let [x, y] = map ([0, 1, p, q]!!) [ix, iy]\n putStrLn $ \"! \" ++ show (x+1) ++ \" \" ++ show (y+1)\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout LineBuffering\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n solve n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Bits\nimport Data.List\nimport Control.Monad\nimport System.IO\nimport qualified System.Exit as Exit\n\nsolve4 :: Int -> Int -> Int -> Int -> (Int, Int)\nsolve4 xa xb xc xd = case maxes of\n [x] -> (x, x)\n [x, y] -> (x, y)\n _ -> error $ \"ambiguous: \" ++ show maxes\n where\n m = maximum [xa, xb, xc, xd]\n maxes = filter ((/=0) . (.&. maxmap) . (1 `shiftL`)) [0..3]\n maxmap = foldl' (.&.) 0xf $ map snd $ filter ((==m) . fst)\n [ (xa, 0xe::Int)\n , (xb, 0xd)\n , (xc, 0xb)\n , (xd, 0x7)\n ]\n\nquery :: Int -> Int -> Int -> IO Int\nquery i j k = do\n putStrLn $ \"? \" ++ show (i+1) ++ \" \" ++ show (j+1) ++ \" \" ++ show (k+1)\n w <- readLn\n when (w == -1) Exit.exitSuccess\n return w\n\nsolve :: Int -> IO ()\nsolve n = do\n w2 <- query 0 1 2\n phase0 2 w2 3\n where\n phase0 best bestW !i\n | i >= n = do\n w2 <- query 0 best 2\n phase1 best 2 w2 3\n | otherwise = do\n wi <- query 0 1 i\n if wi > bestW\n then phase0 i wi (i+1)\n else phase0 best bestW (i+1)\n\n phase1 p best bestW i\n | i >= n = phase2 p best bestW\n | i == p = phase1 p best bestW (i+1)\n | otherwise = do\n wi <- query 0 p i\n if wi > bestW\n then phase1 p i wi (i+1)\n else phase1 p best bestW (i+1)\n\n phase2 p q w0pq = do\n --putStrLn $ \"phase2: \" ++ show (p, q)\n w01p <- query 0 1 p\n w01q <- query 0 1 q\n w1pq <- query 1 p q\n let !(ix, iy) = solve4 w1pq w0pq w01q w01p\n let [x, y] = map ([0, 1, p, q]!!) [ix, iy]\n putStrLn $ \"! \" ++ show (x+1) ++ \" \" ++ show (y+1)\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout LineBuffering\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n solve n\n"}], "src_uid": "84e79bd83c51a4966b496bb767ec4f0d"} {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map read . words . (!! 1) . lines)\n\ndivisors :: Int -> [Int]\ndivisors n = concat [[x, n `div` x] | x <- [1..((+1) $ ceiling $ sqrt $ fromIntegral n)], n `mod` x == 0]\n\nsolve :: [Int] -> Int\nsolve values = let n = length values in maximum $ map (score values) (filter (<= (n `div` 3)) $ divisors n)\n\nscore :: [Int] -> Int -> Int\nscore values k = maximum $ map sum $ getGroups values k\n\ngetGroups :: [Int] -> Int -> [[Int]]\ngetGroups xs k = transpose $ fixedGroups [] xs k where\n fixedGroups result [] _ = result\n fixedGroups result xs k = let (h, t) = splitAt k xs in fixedGroups (h : result) t k\n", "positive_code": [{"source_code": "import Data.Function (fix)\n\nmain = do\n n <- fmap read getLine\n t <- fmap (map read . words) getLine\n let count k = toList $ foldl (\\zipper ti -> next $ update (+ti) zipper) (fromList $ replicate k 0) t\n print $ maximum $ concatMap count $ filter ((>= 3) . (n `div`)) $ divisors n\n\ntype Zipper a = ([a], [a])\n\nnext :: Zipper a -> Zipper a\nnext ([], []) = error \"next: Empty zipper\"\nnext (xs, []) = ([], reverse xs)\nnext (xs, y:ys) = (y:xs, ys)\n\nupdate :: (a -> a) -> Zipper a -> Zipper a\nupdate f ([], []) = error \"update: Empty zipper\"\nupdate f (xs, []) = update f ([], reverse xs)\nupdate f (xs, y:ys) = (xs, f y:ys)\n\nfromList :: [a] -> Zipper a\nfromList [] = error \"fromList: Empty zipper\"\nfromList xs = ([], xs)\n\ntoList :: Zipper a -> [a]\ntoList (xs, ys) = reverse xs ++ ys\n\ndivisors n = filter ((==0) . (n `mod`)) [1..n-1]\n"}, {"source_code": "import Data.List\n\nmain = interact $ show . solve . map read . words where\n\nsolve (n:xss) = maximum (map solve' divisors) where\n xs = take n xss\n divisors = [x | x <- [3..n], n `mod` x == 0]\n solve' y = maximum (map sum (transpose (splitter (n `div` y) xs)))\n\nsplitter n xs = splitter' xs [] where\n splitter' [] acc = acc\n splitter' ls acc = splitter' ys (h:acc) where\n (h, ys) = splitAt n ls\n"}, {"source_code": "\nimport Array\n\ngetWords :: IO [String]\ngetWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = getWords >>= return . (map read)\n\nreadArray :: Read e => IO (Array Int e)\nreadArray = do\n xs <- Main.reads\n return (listArray (0, length xs - 1) xs)\n\nsolve :: Array Int Int -> Int\nsolve array = maximum $ map sum (map getList [(s, r) | r <- remainders, s <- [0 .. n `div` r - 1]])\n where\n n = rangeSize $ bounds array\n remainders = filter (\\m -> n `rem` m == 0) [3..n]\n\n getList :: (Int, Int) -> [Int]\n getList (s, r) = [array ! (s + i * (n `div` r)) | i <- [0 .. r - 1]]\n\nmain :: IO ()\nmain = getLine >> readArray >>= print . solve\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n a <- replicateM n readInt\n return (n, a)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, a) = maximum [ calc a (n `div` i)\n | i <- [3..n]\n , n `mod` i == 0\n ]\n where\n calc a m = let arr = accumArray (+) 0 (1, m) (zip (cycle [1..m]) a) :: UArray Int Int\n in maximum (elems arr)\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (transpose, unfoldr)\n\nmain :: IO ()\nmain = solve <$> readLn <*> (map read . words <$> getLine) >>= print\n\nsolve :: Int -> [Int] -> Int\nsolve n ts = maximum [ maximum $ map sum $ transpose $ splitN (n `div` m) ts | m <- [3..n], n `mod` m == 0 ]\n \nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (transpose, unfoldr)\n\nmain :: IO ()\nmain = solve <$> readLn <*> (map (fst . fromJust . B.readInt) . B.words <$> B.getLine) >>= print\n\nsolve :: Int -> [Int] -> Int\nsolve n ts = maximum [ maximum $ map sum $ transpose $ splitN (n `div` m) ts | m <- [3..n], n `mod` m == 0 ]\n \nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "import Data.Array\n\ndivisors :: Int -> [Int]\ndivisors n = filter (\\x -> n `mod` x == 0) [1..n]\n\ngetIndexes :: Int -> Int -> Int -> [Int]\ngetIndexes n period offset = take (n `div` period) $ map (\\x -> x * period + offset) [0..]\n\ngetAllIndexes :: Int -> [[Int]]\ngetAllIndexes n = [getIndexes n period offset | period <- (divisors n), offset <- [0..period - 1], n `div` period >= 3]\n\nsolve :: Int -> [Int] -> Int\nsolve n bl = maximum $ map (sum . map (arr !)) $ getAllIndexes n\n\twhere arr = listArray (0, n - 1) bl\n\nmain = do\n\tn <- readLn\n\tstr <- getLine\n\tprint $ solve n (map read $ words $ str)\n"}, {"source_code": "import Data.Array.Unboxed\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\n\nsolve' n list a = maximum . elems $\n (accumArray (+) 0 (0, a-1) [ (i `mod` a, num) | (i, num) <- list ] :: UArray Int Int)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n list = maximum [solve' n list (n `div` a) | a <- [3..n], n `mod` a == 0]\n\nreadInt = (\\(Just (x,_)) -> x) . BS.readInt\n\nmain = do\n n <- liftM readInt BS.getLine\n list <- liftM (map readInt . BS.words) BS.getLine\n\n print $ solve n (zip [1..] list)\n"}, {"source_code": "import Data.List\ndivisors :: Int -> [Int]\ndivisors n = filter (\\x -> n `mod` x == 0) [3..n]\nsolve :: [Int] -> Int \nsolve (num:ts) = maximum . map solve' . divisors $ num \n where solve' y = maximum . map sum . transpose . split (num `div` y) $ ts \nsplit :: Int -> [Int] -> [[Int]]\nsplit n xs = split' [] xs\n where split' ps [] = ps\n split' ps qs = let (h, ys) = splitAt n qs in split' (h:ps) ys\nmain = putStrLn . show . solve . map read . words =<< getContents"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map read . words . (!! 1) . lines)\n\ndivisors :: Int -> [Int]\ndivisors n = concat [[x, n `div` x] | x <- [1..((+1) $ ceiling $ sqrt $ fromIntegral n)], n `mod` x == 0]\n\nsolve :: [Int] -> Int\nsolve values = maximum $ map (score values) (divisors $ length values)\n\nscore :: [Int] -> Int -> Int\nscore values k = maximum $ map sum $ getGroups values k\n\ngetGroups :: [Int] -> Int -> [[Int]]\ngetGroups xs k = transpose $ fixedGroups [] xs k where\n fixedGroups result [] _ = result\n fixedGroups result xs k = let (h, t) = splitAt k xs in fixedGroups (h : result) t k\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = solve <$> readLn <*> (map read . words <$> getLine) >>= print\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n ts = maximum [ sum [ t | (i, t) <- zip [0..] ts, i `mod` k == l ] | k <- factors n, l <- [0..k-1] ]\n\nfactors :: Integral t => t -> [t]\nfactors n = [ m | m <- [1..n], n `mod` m == 0 ]\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = solve <$> readLn <*> (map read . words <$> getLine) >>= print\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n ts = maximum [ sum [ t | (i, t) <- zip [0..] ts, i `mod` k == l ] | k <- factors n, k > 2, l <- [0..k-1] ]\n\nfactors :: Integral t => t -> [t]\nfactors n = [ m | m <- [1..n], n `mod` m == 0 ]\n"}], "src_uid": "0ff4ac859403db4e29554ca7870f5490"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n Just (n,_) <- BS.readInt <$> BS.getLine\n xs <- getLine\n let b = head xs\n xs1 = reverse xs\n e = head xs1\n prefixlen = fromIntegral $ length $ takeWhile (== b) xs\n suffixlen = fromIntegral $ length $ takeWhile (== e) xs1\n ans = if b == e then\n ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus\n else\n (prefixlen + suffixlen + 1) `mod` modulus\n print ans\n\nmodulus :: Int64\nmodulus = 998244353\n", "positive_code": [{"source_code": "import Data.Int\n\nheads s = (+1) . length . takeWhile id $ zipWith (==) s (tail s)\n\nfromIntToInt64 :: Int -> Int64\nfromIntToInt64 = fromIntegral\n\nfromInt64toInt :: Int64 -> Int\nfromInt64toInt = fromIntegral\n\ncnt :: Int -> Int -> Int -> Int\ncnt x y n | x + y <= n = fromInt64toInt $ (fromIntToInt64 (x + 1)) * (fromIntToInt64 (y + 1)) `mod` (fromIntToInt64 b)\n | otherwise = x * (x + 1) `div` 2 `mod` b\n where b = 998244353\n\nsolve :: String -> Int\nsolve s | (head rs) == (head s) = cnt (heads s) (heads rs) (length s)\n | otherwise = (heads s) + (heads rs) + 1\n where rs = reverse s\n\n\nmain = do\n _ <- getLine\n s <- getLine\n -- print $ heads s\n print $ solve s"}], "negative_code": [{"source_code": "heads s = (+1) . length . takeWhile id $ zipWith (==) s (tail s)\n\ncnt :: Int -> Int -> Int -> Int\ncnt x y n | x + y < n = (x + 1) * (y + 1) `mod` b\n | otherwise = x * (x + 1) `div` 2 `mod` b\n where b = 998244353\n\nsolve :: String -> Int\nsolve s | (head rs) == (head s) = cnt (heads s) (heads rs) (length s)\n | otherwise = (heads s) + (heads rs) + 1\n where rs = reverse s\n\n\nmain = do\n _ <- getLine\n s <- getLine\n -- print $ heads s\n print $ solve s"}, {"source_code": "heads s = (+1) . length . takeWhile id $ zipWith (==) s (tail s)\n\ncnt :: Int -> Int -> Int -> Int\ncnt x y n | x + y <= n = (x + 1) * (y + 1) `mod` b\n | otherwise = x * (x + 1) `div` 2 `mod` b\n where b = 998244353\n\nsolve :: String -> Int\nsolve s | (head rs) == (head s) = cnt (heads s) (heads rs) (length s)\n | otherwise = (heads s) + (heads rs) + 1\n where rs = reverse s\n\n\nmain = do\n _ <- getLine\n s <- getLine\n -- print $ heads s\n print $ solve s"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n Just (n,_) <- BS.readInt <$> BS.getLine\n xs <- BS.getLine\n let beg = BS.head xs\n end = BS.last xs\n prefixlen = fromIntegral $ BS.length $ BS.takeWhile (== beg) xs\n suffixlen = fromIntegral $ BS.length $ snd $ BS.spanEnd (== end) xs\n ans = if beg == end then\n ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus\n else\n (prefixlen + suffixlen + 1) `mod` modulus\n print ans\n\nmodulus :: Int64\nmodulus = 998244353\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n Just (n,_) <- BS.readInt <$> BS.getLine\n xs <- BS.getLine\n let beg = BS.head xs\n end = BS.last xs\n prefixlen = BS.length $ BS.takeWhile (== beg) xs\n suffixlen = BS.length $ snd $ BS.spanEnd (== end) xs\n ans = if beg == end then\n ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus\n else\n (prefixlen + suffixlen + 1) `mod` modulus\n print ans\n\nmodulus :: Int\nmodulus = 998244353\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n Just (n,_) <- BS.readInt <$> BS.getLine\n xs <- BS.getLine\n let b = BS.head xs\n e = BS.last xs\n prefixlen = fromIntegral $ BS.length $ BS.takeWhile (== b) xs\n suffixlen = fromIntegral $ BS.length $ snd $ BS.spanEnd (== e) xs\n ans = if b == e then\n ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus\n else\n (prefixlen + suffixlen + 1) `mod` modulus\n print ans\n\nmodulus :: Int64\nmodulus = 998244353\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n Just (n,_) <- BS.readInt <$> BS.getLine\n xs <- BS.getLine\n let beg = BS.head xs\n end = BS.last xs\n prefixlen = fromIntegral $ BS.length $ BS.takeWhile (== beg) xs\n suffixlen = fromIntegral $ BS.length $ snd $ BS.spanEnd (== end) xs\n ans = if beg == end then\n ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus\n else\n (prefixlen + suffixlen + 1) `mod` modulus\n print ans\n\nmodulus :: Int64\nmodulus = 998244353\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n Just (n,_) <- BS.readInt <$> BS.getLine\n xs <- BS.getLine\n let beg = BS.head xs\n end = BS.last xs\n prefixlen = BS.length $ BS.takeWhile (== beg) xs\n suffixlen = BS.length $ snd $ BS.spanEnd (== end) xs\n ans = if beg == end then\n ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus\n else if suffixlen + prefixlen == n then\n n `mod` modulus\n else\n (prefixlen + suffixlen + 1) `mod` modulus\n print ans\n\nmodulus :: Int\nmodulus = 998244353\n"}], "src_uid": "9693f60fc65065d00a1899df999405fe"} {"source_code": "\nimport Control.Monad (liftM, replicateM, when)\nimport Data.Char (ord)\nimport Data.List (intercalate, sortBy)\nimport Prelude hiding (reads)\nimport System.IO (hPutStrLn, stderr)\nimport System.CPUTime (getCPUTime)\n\ntimeout :: Bool\ntimeout = False\n\n--reads :: Read a => IO [a]\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n where\n read :: String -> Int\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + ord c - ord '0') s\n\ndata Command = Go Int Char | Take | Destroy\n\nsolve :: [[Int]] -> [Command]\nsolve bombs = concatMap solve'\n $ sortBy compareBombs bombs\n where\n solve' [0, y] =\n [\n Go (abs y) (goY y),\n Take,\n Go (abs y) (reverseY y),\n Destroy\n ]\n solve' [x, 0] =\n [\n Go (abs x) (goX x),\n Take,\n Go (abs x) (reverseX x),\n Destroy\n ]\n solve' [x, y] =\n [\n Go (abs x) (goX x),\n Go (abs y) (goY y),\n Take,\n Go (abs x) (reverseX x),\n Go (abs y) (reverseY y),\n Destroy\n ]\n goX a = if a > 0 then 'R' else 'L'\n goY a = if a > 0 then 'U' else 'D'\n reverseX a = if a > 0 then 'L' else 'R'\n reverseY a = if a > 0 then 'D' else 'U'\n compareBombs [x1, y1] [x2, y2]\n = compare (abs x1 + abs y1) (abs x2 + abs y2)\n\nprint' :: Command -> String\nprint' (Go k c) = \"1 \" ++ show k ++ \" \" ++ [c]\nprint' Take = \"2\"\nprint' Destroy = \"3\"\n\nmain :: IO ()\nmain = do\n t0 <- getCPUTime \n n <- readLn\n bombs <- replicateM n reads\n let commands = solve bombs\n --print $ length commands\n let zero = length $ filter (\\[x,y] -> x == 0 || y == 0) bombs\n print (6 * (n - zero) + 4 * zero)\n mapM_ (putStrLn . print') commands\n t1 <- getCPUTime\n when timeout $\n hPutStrLn stderr $ concat [\"Time = \", show (fromIntegral (t1 - t0) * 1e-12), \" sec.\"]\n \n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.ByteString as ByteString\nimport qualified Data.ByteString.Char8 as Char8\n\nreadInt :: Char8.ByteString -> Int\nreadInt = fst . fromJust . Char8.readInt\n\ncalc :: [(Int, Int)] -> [[String]]\ncalc [] = []\ncalc ((x, y) : xs) = goX ++ goY ++ [[\"2\"]] ++ backX ++ backY ++ [[\"3\"]] ++ calc xs\n\twhere\n\t\tgoX\n\t\t\t| x < 0 = [[\"1\", show (-x), \"L\"]]\n\t\t\t| x > 0 = [[\"1\", show x, \"R\"]]\n\t\t\t| otherwise = []\n\t\tgoY\n\t\t\t| y < 0 = [[\"1\", show (-y), \"D\"]]\n\t\t\t| y > 0 = [[\"1\", show y, \"U\"]]\n\t\t\t| otherwise = []\n\t\tbackX\n\t\t\t| x < 0 = [[\"1\", show (-x), \"R\"]]\n\t\t\t| x > 0 = [[\"1\", show x, \"L\"]]\n\t\t\t| otherwise = []\n\t\tbackY\n\t\t\t| y < 0 = [[\"1\", show (-y), \"U\"]]\n\t\t\t| y > 0 = [[\"1\", show y, \"D\"]]\n\t\t\t| otherwise = []\n\nzipXY :: [Int] -> [(Int, Int)]\nzipXY [] = []\nzipXY (x : y : xs) = (x, y) : zipXY xs\n\nhandle :: [Char8.ByteString] -> [[String]]\nhandle (_ : xs) = [show $ length res] : res\n\twhere\n\t\tpx = sortBy (comparing (\\(x, y) -> (abs x) + (abs y))) $ zipXY $ map readInt xs\n\t\tres = calc px\n\nmain :: IO ()\nmain = do\n\tinput <-ByteString.getContents\n\tputStr $ unlines $ map unwords $ handle $ Char8.words input\n"}, {"source_code": "import Data.List (sortBy)\n\nmain = interact $ encompase . map (map read) . map words . tail . lines\n\nf = sortBy (\\(d1, _, _) (d2, _, _) -> compare d1 d2) . map (\\(x:y:[]) -> (x^2 + y^2, x, y))\n\nencompase y = show (h x) ++ \"\\n\" ++ g x\n where x = f y\n\ng = unlines . concat . map g'\ng' (_, x, y) = filter (/=\"\") [gx x, gy y, \"2\", gx' x, gy' y, \"3\"]\n\ngx x\n | x > 0 = \"1 \" ++ show(x) ++ \" R\"\n | x < 0 = \"1 \" ++ show (abs x) ++ \" L\"\n | otherwise = \"\"\n\ngy y\n | y > 0 = \"1 \" ++ show(y) ++ \" U\"\n | y < 0 = \"1 \" ++ show (abs y) ++ \" D\"\n | otherwise = \"\"\n\ngx' x\n | x > 0 = \"1 \" ++ show(x) ++ \" L\"\n | x < 0 = \"1 \" ++ show (abs x) ++ \" R\"\n | otherwise = \"\"\n\ngy' y\n | y > 0 = \"1 \" ++ show(y) ++ \" D\"\n | y < 0 = \"1 \" ++ show (abs y) ++ \" U\"\n | otherwise = \"\"\n\nh = sum . map h'\nh' (_, x, y) = 2*(x'+y') + 2\n where x' = fromEnum ((abs x) /= 0)\n y' = fromEnum ((abs y) /= 0)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ndata Op = Move Int Dir | PickUp | Destroy\ndata Dir = R | L | U | D deriving(Show,Eq)\n\ninstance Show Op where\n show (Move i d) = \"1 \"++show i ++ \" \" ++ show d\n show PickUp = \"2\"\n show Destroy = \"3\"\n\nmain = B.interact $ B.words >>> map readInt >>> process\n\nprocess (n:l) = B.unlines $ ((B.pack $ show m):)$ map (B.pack . show) $ solve points\n where\n points = go l []\n go [] !acc = acc\n go (x:y:l) !acc = go l ((x,y):acc)\n ans = solve points\n m = length ans\n\nsolve ps = concat $ map doit ps'\n where\n ps' = map snd $ sort [ (d,(x,y)) | (x,y) <- ps , let d = abs x + abs y]\n\ndoit (x,y) = move x y ++ [PickUp] ++ move (-x) (-y) ++ [Destroy]\nmove x y = moveH x ++ moveV y\nmoveH 0 = []\nmoveH x = [Move (abs x) (if x > 0 then R else L)]\nmoveV 0 = []\nmoveV y = [Move (abs y) (if y > 0 then U else D)]\n\n\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ntoPairs (x:y:xys) = (x,y) : toPairs xys\ntoPairs _ = []\n\ndata Operation = Op1 !Int !Dir\n | Op2\n | Op3\n\ninstance Show Operation where\n show (Op1 k dir) = unwords [\"1\",show k, show dir]\n show Op2 = \"2\"\n show Op3 = \"3\"\n\ndata Dir = R | L | U | D deriving Show\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xys <- sortBy (comparing $ \\(x,y)->(abs x,abs y)).toPairs.map readInt.B.words <$> B.getContents\n let ops = filter (not.isStay) $ solve xys\n print $ length ops\n putStr.unlines $ map show ops\n\nisStay :: Operation -> Bool\nisStay (Op1 0 _) = True\nisStay _ = False\n\nsolve :: [(Int,Int)] -> [Operation]\nsolve ((x,y):xys)\n | x>=0, y>=0 = Op1 x R : Op1 y U : Op2 : Op1 x L : Op1 y D : Op3 : solve xys\n | x<=0, y>=0 = Op1 (-x) L : Op1 y U : Op2 : Op1 (-x) R : Op1 y D : Op3 : solve xys\n | x<=0, y<=0 = Op1 (-x) L : Op1 (-y) D : Op2 : Op1 (-x) R : Op1 (-y) U : Op3 : solve xys\n | x>=0, y<=0 = Op1 x R : Op1 (-y) D : Op2 : Op1 x L : Op1 (-y) U : Op3 : solve xys\nsolve [] = [] \n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [[Int]] -> [String]\nsolve n xs = (show steps):(printMoves xs)\n\twhere steps = sum $ map moves xs\n\t\t\nnorm :: [Int] -> Int\nnorm [x,y] = abs x + abs y\n\nmoves :: [Int] -> Int\nmoves [0,0] = 0\nmoves [_,0] = 4\nmoves [0,_] = 4\nmoves [_,_] = 6\n\nprintMoves :: [[Int]] -> [String]\nprintMoves [] = []\nprintMoves (x:xs) = (printMove x) ++ (printMoves xs)\n\nprintMove :: [Int] -> [String]\nprintMove [x,0] = [ \"1 \" ++ (show $ abs x) ++ \" \" ++ h\n , \"2\"\n , \"1 \" ++ (show $ abs x) ++ \" \" ++ h'\n , \"3\"]\n\twhere (h,h') = if x > 0 then (\"R\",\"L\") else (\"L\",\"R\")\nprintMove [0,y] = [ \"1 \" ++ (show $ abs y) ++ \" \" ++ v\n , \"2\"\n , \"1 \" ++ (show $ abs y) ++ \" \" ++ v'\n , \"3\"]\n\twhere (v,v') = if y > 0 then (\"U\",\"D\") else (\"D\",\"U\")\nprintMove [x,y] = [ \"1 \" ++ (show $ abs x) ++ \" \" ++ h\n , \"1 \" ++ (show $ abs y) ++ \" \" ++ v\n , \"2\"\n , \"1 \" ++ (show $ abs y) ++ \" \" ++ v'\n , \"1 \" ++ (show $ abs x) ++ \" \" ++ h'\n , \"3\"]\n\twhere (h,h') = if x > 0 then (\"R\",\"L\") else (\"L\",\"R\")\n\t (v,v') = if y > 0 then (\"U\",\"D\") else (\"D\",\"U\")\n\n\nmain :: IO ()\nmain = do\n\tn <- readInt `fmap` B.getLine\n\txs <- (map (map readInt . C.words) . C.lines) `fmap` B.getContents\n\tputStr . unlines $ solve n (sortBy (\\x y -> compare (norm x) (norm y)) xs)\n\nreadInteger :: C.ByteString -> Integer\nreadInteger = fst . fromJust . C.readInteger\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM, when)\nimport Data.Char (ord)\nimport Data.List (intercalate, sortBy)\nimport Prelude hiding (reads)\nimport System.IO (hPutStrLn, stderr)\nimport System.CPUTime (getCPUTime)\n\ntimeout :: Bool\ntimeout = False\n\n--reads :: Read a => IO [a]\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n where\n read :: String -> Int\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + ord c - ord '0') s\n\ndata Command = Go Int Char | Take | Destroy\n\nsolve :: [[Int]] -> [Command]\nsolve bombs = concatMap solve'\n $ sortBy compareBombs bombs\n where\n solve' [0, y] =\n [\n Go (abs y) (goY y),\n Take,\n Go (abs y) (reverseY y),\n Destroy\n ]\n solve' [x, 0] =\n [\n Go (abs x) (goX x),\n Take,\n Go (abs x) (reverseX x),\n Destroy\n ]\n solve' [x, y] =\n [\n Go (abs x) (goX x),\n Go (abs y) (goY y),\n Take,\n Go (abs x) (reverseX x),\n Go (abs y) (reverseY y),\n Destroy\n ]\n goX a = if a > 0 then 'R' else 'L'\n goY a = if a > 0 then 'U' else 'D'\n reverseX a = if a > 0 then 'L' else 'R'\n reverseY a = if a > 0 then 'D' else 'U'\n compareBombs [x1, y1] [x2, y2]\n = compare (abs x1 + abs y1) (abs x2 + abs y2)\n\nprint' :: Command -> String\nprint' (Go k c) = \"1 \" ++ show k ++ \" \" ++ [c]\nprint' Take = \"2\"\nprint' Destroy = \"3\"\n\nmain :: IO ()\nmain = do\n t0 <- getCPUTime \n n <- readLn\n bombs <- replicateM n reads\n let commands = solve bombs\n --print $ length commands\n let zero = length $ filter (\\[x,y] -> x == 0 || y == 0) bombs\n print (6 * (n - zero) + 4 * zero)\n mapM_ (putStrLn . print') commands\n t1 <- getCPUTime\n when timeout $\n hPutStrLn stderr $ concat [\"Time = \", show (fromIntegral (t1 - t0) * 1e-12), \" sec.\"]\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ndata Operation = Op1 !Int !Dir\n | Op2\n | Op3\n\ninstance Show Operation where\n show (Op1 k dir) = unwords [\"1\",show k, show dir]\n show Op2 = \"2\"\n show Op3 = \"3\"\n\ndata Dir = R | L | U | D deriving Show\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getContents\n let ops = filter (not.isStay) $ solve xs\n print $ length ops\n putStr.unlines $ map show ops\n\nisStay :: Operation -> Bool\nisStay (Op1 0 _) = True\nisStay _ = False\n\nsolve :: [Int] -> [Operation]\nsolve (x:y:xys)\n | x>=0, y>=0 = Op1 x R : Op1 y U : Op2 : Op1 x L : Op1 y D : Op3 : solve xys\n | x<=0, y>=0 = Op1 (-x) L : Op1 y U : Op2 : Op1 (-x) R : Op1 y D : Op3 : solve xys\n | x<=0, y<=0 = Op1 (-x) L : Op1 (-y) D : Op2 : Op1 (-x) R : Op1 (-y) U : Op3 : solve xys\n | x>=0, y<=0 = Op1 x R : Op1 (-y) D : Op2 : Op1 x L : Op1 (-y) U : Op3 : solve xys\nsolve [] = [] \n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [[Int]] -> [String]\nsolve n xs = (show steps):(printMoves xs)\n\twhere steps = sum $ map moves xs\n\t\t\nnorm :: [Int] -> [Int] -> Int\nnorm [x1,y1] [x2,y2] = abs (x2-x1) + abs (y2-y1)\n\nmoves :: [Int] -> Int\nmoves [0,0] = 0\nmoves [_,0] = 4\nmoves [0,_] = 4\nmoves [_,_] = 6\n\nprintMoves :: [[Int]] -> [String]\nprintMoves [] = []\nprintMoves (x:xs) = (printMove x) ++ (printMoves xs)\n\nprintMove :: [Int] -> [String]\nprintMove [x,0] = [ \"1 \" ++ (show $ abs x) ++ \" \" ++ h\n , \"2\"\n , \"1 \" ++ (show $ abs x) ++ \" \" ++ h'\n , \"3\"]\n\twhere (h,h') = if x > 0 then (\"R\",\"L\") else (\"L\",\"R\")\nprintMove [0,y] = [ \"1 \" ++ (show $ abs y) ++ \" \" ++ v\n , \"2\"\n , \"1 \" ++ (show $ abs y) ++ \" \" ++ v'\n , \"3\"]\n\twhere (v,v') = if y > 0 then (\"U\",\"D\") else (\"D\",\"U\")\nprintMove [x,y] = [ \"1 \" ++ (show $ abs x) ++ \" \" ++ h\n , \"1 \" ++ (show $ abs y) ++ \" \" ++ v\n , \"2\"\n , \"1 \" ++ (show $ abs y) ++ \" \" ++ v'\n , \"1 \" ++ (show $ abs x) ++ \" \" ++ h'\n , \"3\"]\n\twhere (h,h') = if x > 0 then (\"R\",\"L\") else (\"L\",\"R\")\n\t (v,v') = if y > 0 then (\"U\",\"D\") else (\"D\",\"U\")\n\n\nmain :: IO ()\nmain = do\n\tn <- readInt `fmap` B.getLine\n\txs <- (map (map readInt . C.words) . C.lines) `fmap` B.getContents\n\tputStr . unlines $ solve n xs\n\nreadInteger :: C.ByteString -> Integer\nreadInteger = fst . fromJust . C.readInteger\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt"}, {"source_code": "calc :: [Int] -> [[String]]\ncalc [] = []\ncalc (x : y : xs) = goX ++ goY ++ [[\"2\"]] ++ backX ++ backY ++ [[\"3\"]] ++ calc xs\n\twhere\n\t\tgoX\n\t\t\t| x < 0 = [[\"1\", show (-x), \"L\"]]\n\t\t\t| x > 0 = [[\"1\", show x, \"R\"]]\n\t\t\t| otherwise = []\n\t\tgoY\n\t\t\t| y < 0 = [[\"1\", show (-y), \"D\"]]\n\t\t\t| y > 0 = [[\"1\", show y, \"U\"]]\n\t\t\t| otherwise = []\n\t\tbackX\n\t\t\t| x < 0 = [[\"1\", show (-x), \"R\"]]\n\t\t\t| x > 0 = [[\"1\", show x, \"L\"]]\n\t\t\t| otherwise = []\n\t\tbackY\n\t\t\t| y < 0 = [[\"1\", show (-y), \"U\"]]\n\t\t\t| y > 0 = [[\"1\", show y, \"D\"]]\n\t\t\t| otherwise = []\n\nhandle :: [String] -> [[String]]\nhandle (sn : xs) = [show $ length res] : res\n\twhere\n\t\tpx = map read xs\n\t\tres = calc px\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.ByteString as ByteString\nimport qualified Data.ByteString.Char8 as Char8\n\nreadInt :: Char8.ByteString -> Int\nreadInt = fst . fromJust . Char8.readInt\n\ncalc :: [(Int, Int)] -> [[String]]\ncalc [] = []\ncalc ((x, y) : xs) = goX ++ goY ++ [[\"2\"]] ++ backX ++ backY ++ [[\"3\"]] ++ calc xs\n\twhere\n\t\tgoX\n\t\t\t| x < 0 = [[\"1\", show (-x), \"L\"]]\n\t\t\t| x > 0 = [[\"1\", show x, \"R\"]]\n\t\t\t| otherwise = []\n\t\tgoY\n\t\t\t| y < 0 = [[\"1\", show (-y), \"D\"]]\n\t\t\t| y > 0 = [[\"1\", show y, \"U\"]]\n\t\t\t| otherwise = []\n\t\tbackX\n\t\t\t| x < 0 = [[\"1\", show (-x), \"R\"]]\n\t\t\t| x > 0 = [[\"1\", show x, \"L\"]]\n\t\t\t| otherwise = []\n\t\tbackY\n\t\t\t| y < 0 = [[\"1\", show (-y), \"U\"]]\n\t\t\t| y > 0 = [[\"1\", show y, \"D\"]]\n\t\t\t| otherwise = []\n\nzipXY :: [Int] -> [(Int, Int)]\nzipXY [] = []\nzipXY (x : y : xs) = (x, y) : zipXY xs\n\nhandle :: [Char8.ByteString] -> [[String]]\nhandle (_ : xs) = [show $ length res] : res\n\twhere\n\t\tpx = sortBy (comparing (\\(x, y) -> x + y)) $ zipXY $ map readInt xs\n\t\tres = calc px\n\nmain :: IO ()\nmain = do\n\tinput <-ByteString.getContents\n\tputStr $ unlines $ map unwords $ handle $ Char8.words input\n"}], "src_uid": "a7c1b9845ab0569e0175853db9ed5c32"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n (n,m) <- readIntPair\n if m == 0 then\n putStrLn \"YES\"\n else do\n l <- sort <$> readInts\n let a = head l\n let b = last l\n if a == 1 || b == n then\n putStrLn \"NO\"\n else if all (\\(k,a) -> a /= 1 || k <= 1) $ map (length &&& head) $ group $ zipWith (-) (tail l) l then \n putStrLn \"YES\"\n else \n putStrLn \"NO\"\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nsolve n a = if c then \"YES\" else \"NO\"\n where xs = sort a\n f xs = length xs < 3 || not ((xs!!0)+1 == xs!!1 && (xs!!1)+1 == xs!!2)\n c = null xs || (head xs /= 1 && last xs /= n && all f (tails xs))\n\nmain = do\n n:m:a <- map read . words <$> getContents\n putStrLn $ solve n a\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate, sort)\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: Int -> [Int] -> Bool\nsolve n as\n | 1 `elem` as = False\n | n `elem` as = False\n | otherwise = not $ threeInOrder $ sort as\n where\n threeInOrder (a:b:c:as)\n | a+1 == b && b+1 == c = True\n | otherwise = threeInOrder (b:c:as)\n threeInOrder _ = False\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n if m == 0 then\n putStrLn \"YES\"\n else\n do\n as <- reads\n putStrLn $ (\"YES\" \"NO\") $ solve n as\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}], "negative_code": [], "src_uid": "422cbf106fac3216d58bdc8411c0bf9f"} {"source_code": "import Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> [Int] -> Integer\nsolve n b = fst $ foldl f (fromIntegral $ abs $ head b, head b) $ tail b\n where\n f :: (Integer, Int) -> Int -> (Integer, Int)\n f (opsCount, arrVal) elem = (opsCount + fromIntegral (abs $ arrVal - elem), elem)\n\nmain :: IO ()\nmain = do\n n <- liftM (maybe 0 fst . B.readInt) B.getLine\n b <- liftM (map (maybe 0 fst . B.readInt) . B.words) B.getLine\n print $ solve n b\n", "positive_code": [{"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\nanswer [] res = 0\nanswer (a:as) res = abs (a-res) + answer as a\nmain = do\n n <- readLn::IO Int\n a <- map read <$>words <$> getLine ::IO [Integer]\n print $ answer a 0\n \n"}, {"source_code": "import Control.Applicative\n\nsolve :: [Integer] -> Integer\nsolve [_] = 0\nsolve (x:y:ys) = abs (y-x) + solve (y:ys)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n bs <- map read . words <$> getLine\n print . solve $ 0 : bs\n"}, {"source_code": "import Data.Int\n\nmain :: IO()\nmain = print . solve 0 . map read . tail . words =<< getContents\n\nsolve :: Int64 -> [Int64] -> Int64\nsolve x [] = 0\nsolve x (y:ys) = abs (y-x) + solve y ys"}, {"source_code": "import Data.Int\n\nmain :: IO()\nmain = print . solve 0 . map read . tail . words =<< getContents\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x [] = 0\nsolve x (y:ys) = abs (y-x) + solve y ys"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n\tn <- getInt\n\tas <- getInts\n\tprint $ process as\n\n\ngetInt :: IO Integer\ngetInt = readLn\n\ngetInts :: IO [Integer]\ngetInts = do\n\ts <- getLine\n\tlet ws = words s\n\treturn $ map read ws \n\nprocess :: [Integer] -> Integer\nprocess = process' 0\n\nprocess' :: Integer -> [Integer] -> Integer\nprocess' start [] = 0\nprocess' start (a : as) = if start < a\n\tthen a - start + process' a as\n\telse start - a + process' a as\n"}, {"source_code": "main :: IO()\nmain = print . solve 0 . map read . tail . words =<< getContents\n\nsolve :: Integer -> [Integer] -> Integer\nsolve _ [] = 0\nsolve l (a:x) = (abs (a - l)) + (solve a x)\n"}, {"source_code": "solve :: [Integer] -> Integer\nsolve (x:y:xs) = abs(x - y) + solve (y:xs)\nsolve _ = 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n input <- getLine\n let arr = map read $ words input\n putStrLn $ show $ solve (0:arr)\n"}, {"source_code": "import Data.Int\n\nsolve :: [Int64] -> Int64\nsolve (x:y:xs) = abs(x - y) + solve (y:xs)\nsolve _ = 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n input <- getLine\n let arr = map read $ words input\n putStrLn $ show $ solve (0:arr)\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve 0 . map read . tail . words =<< getContents\n\nsolve :: Int -> [Int] -> Int\nsolve x [] = 0\nsolve x (y:ys) = abs (y-x) + solve y ys"}, {"source_code": "main :: IO ()\nmain = do\n n <- getLine\n input <- getLine\n let arr = map read $ words input :: [Int]\n putStrLn $ show $ foldl (\\acc x -> acc + abs (x - acc)) 0 arr\n"}, {"source_code": "solve :: [Int] -> Int\nsolve (x:y:xs) = abs(x - y) + solve (y:xs)\nsolve _ = 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n input <- getLine\n let arr = map read $ words input\n putStrLn $ show $ solve (0:arr)\n"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\nanswer [] res = 0\nanswer (a:as) res = abs (a-res) + answer as a\nmain = do\n n <- readLn::IO Int\n a <- readLists\n print $ answer a 0\n \n"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents \nmain = do\n n <- readLn::IO Int\n a <- readLists\n print $ (a !! 0) + (sum $ map abs $ zipWith (-) a (tail a))\n \n"}, {"source_code": "import Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nsolve n b = foldl (\\c x -> abs (x - c) + c) (abs $ head b) $ tail b\n\nmain :: IO ()\nmain = do\n n <- liftM (maybe 0 fst . B.readInt) B.getLine\n b <- liftM (map (maybe 0 fst . B.readInt) . B.words) B.getLine\n print $ solve n b\n"}, {"source_code": "import Control.Applicative\n\nsolve :: [Int] -> Int\nsolve [_] = 0\nsolve (x:y:ys) = abs (y-x) + solve (y:ys)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n bs <- map read . words <$> getLine\n print . solve $ 0 : bs\n"}], "src_uid": "97a226f47973fcb39c40e16f66654b5f"} {"source_code": "main = getLine >> (interact $ unlines . map (solve . map read . words) . lines)\n\nsolve [a,b,n,s]\n | r <= b = \"YES\"\n | otherwise = \"NO\"\n where r = s - n * (min a $ s `div` n)", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ ( putStrLn . which \"YES\" \"NO\" )\n\nsolve = do\n\t[ a, b, n, s ] <- readInts\n\tlet\n\t\tx = min a $ s `div` n\n\t\tremaining = s - x * n\n\treturn $ remaining <= b"}, {"source_code": "import Control.Monad\n\nsolve :: Integer -> Integer -> Integer -> Integer -> Bool\nsolve a b n s = rest<=b\n where\n rest = max (s-n*a) (mod s n)\n\nroutine :: IO ()\nroutine = do\n [a,b,n,s] <- fmap (map read.words) getLine\n putStrLn (if solve a b n s then \"YES\" else \"NO\")\n\nmain :: IO ()\nmain = do\n m <- readLn\n replicateM_ m routine\n"}, {"source_code": "-- http://codeforces.com/contest/1256/problem/A\n\n\ndata Case = Case { ns :: Int\n , ones :: Int\n , nValue :: Int\n , total :: Int\n }\n\n\ndata Answer = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let ints = map read $ words line :: [Int]\n Case { ns = ints !! 0\n , ones = ints !! 1\n , nValue = ints !! 2\n , total = ints !! 3\n }\n\n\ngetUsedNs :: Case -> Int\ngetUsedNs (Case ns _ nValue total) = do\n let requiredNs = total `div` nValue\n min ns requiredNs\n\n\ngetUsedOnes :: Int -> Int -> Int -> Int\ngetUsedOnes totalN ones total = do\n let requiredOnes = total - totalN\n min ones requiredOnes\n\n\ntoAnswer :: Bool -> Answer\ntoAnswer boolean\n | boolean = YES\n | otherwise = NO\n\n\nsolve :: Case -> Answer\nsolve (Case ns ones nValue total) = do\n toAnswer (totalN + usedOnes == total)\n where usedNs = getUsedNs (Case ns ones nValue total)\n totalN = usedNs * nValue\n usedOnes = getUsedOnes totalN ones total\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "main = interact main'\nmain' = \n unlines . map (f . map read . words) . drop 1 . lines\n\nf [a, b, n, s]\n = \n if not enough\n then \"NO\"\n else \"YES\"\n where \n req_a = min (s `div` n) a\n req_b = s - n * req_a\n enough = req_b <= b"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int -> Int -> Bool\nsolve a b n s = rest<=b\n where\n rest = max (s-n*a) (mod s n)\n\nroutine :: IO ()\nroutine = do\n [a,b,n,s] <- fmap (map read.words) getLine\n putStrLn (if solve a b n s then \"YES\" else \"NO\")\n\nmain :: IO ()\nmain = do\n m <- readLn\n replicateM_ m routine\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int -> Int -> Bool\nsolve a b n s = rest<=b\n where\n rest = max (s-n*a) (mod s n)\n\nroutine :: IO ()\nroutine = do\n [a,b,n,s] <- fmap (map read.words) getLine\n putStrLn (if solve a b n s then \"YES\" else \"NO\")\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "-- http://codeforces.com/contest/1256/problem/A\n\n\ndata Case = Case { ns :: Int\n , ones :: Int\n , nValue :: Int\n , total :: Int\n }\n\n\ndata Answer = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let ints = map read $ words line :: [Int]\n Case { ns = ints !! 0\n , ones = ints !! 1\n , nValue = ints !! 2\n , total = ints !! 3\n }\n\n\ntoAnswer :: Bool -> Answer\ntoAnswer boolean\n | boolean = YES\n | otherwise = NO\n\n\nsolve :: Case -> Answer\nsolve (Case ns ones nValue total)\n | ones >= total = YES\n | otherwise = toAnswer (intDivision <= ns && modValue <= ones)\n where intDivision = total `div` nValue\n modValue = total `mod` nValue\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "-- http://codeforces.com/contest/1256/problem/A\n\n\ndata Case = Case { ns :: Int\n , ones :: Int\n , nValue :: Int\n , total :: Int\n }\n\n\ndata Answer = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let ints = map read $ words line :: [Int]\n Case { ns = ints !! 0\n , ones = ints !! 1\n , nValue = ints !! 2\n , total = ints !! 3\n }\n\n\ntoAnswer :: Bool -> Answer\ntoAnswer boolean\n | boolean = YES\n | otherwise = NO\n\n\nsolve :: Case -> Answer\nsolve (Case ns ones nValue total) =\n toAnswer (intDivision <= ns && modValue <= ones)\n where intDivision = total `div` nValue\n modValue = total `mod` nValue\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}], "src_uid": "e2434fd5f9d16d59e646b6e69e37684a"} {"source_code": "import Data.List\nimport Data.Array\nimport Data.Char\n\nvow 'a' = True\nvow 'e' = True\nvow 'i' = True\nvow 'o' = True\nvow 'u' = True\nvow _ = False\n\nsolve [] _ _ _ = []\nsolve (x:xs) c last diff\n\t|(not (vow x)) && (c>=2) && ((x/=last) || diff) = ' ':x:(solve xs 1 x False)\n\t|(not (vow x)) && ((x/=last) || diff)= x:solve xs (c+1) x True\n\t|(not (vow x)) = x:solve xs (c+1) x diff\n\t|otherwise = x:solve xs 0 (head xs) False\n\nmain=do\n\tl<- getLine\n\tputStrLn (solve l 0 (head l) False)\n", "positive_code": [{"source_code": "is_vowel :: Char -> Bool\nis_vowel 'a' = True\nis_vowel 'e' = True\nis_vowel 'i' = True\nis_vowel 'o' = True\nis_vowel 'u' = True\nis_vowel ch = False\n\nf :: String -> String\nf \"\" = \"\"\nf (a:\"\") = a : \"\"\nf (a:rema) = a : s' ++ sub_ans\n where s = takeWhile (\\x -> x == a) rema\n t = dropWhile (\\x -> x == a) rema\n l = length s\n s' = if l == 0 then [head rema] else s\n t' = if l == 0 then tail rema else t\n sub_ans = if null t' then \"\" else ' ' : f t'\n\ng :: String -> String\ng \"\" = \"\"\ng (a:rema) | is_vowel a = a : g rema\n | otherwise = f (a:s) ++ g t\n where s = takeWhile (not . is_vowel) rema\n t = dropWhile (not . is_vowel) rema \n \nmain :: IO ()\nmain = do\n line <- getLine\n putStrLn $ g line\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Data.Char\n\nvow 'a' = True\nvow 'e' = True\nvow 'i' = True\nvow 'o' = True\nvow 'u' = True\nvow _ = False\n\nsolve [] _ = []\nsolve (x:xs) c\n\t|(not (vow x)) && (c==2) = ' ':x:(solve xs 0)\n\t|(not (vow x)) = x:solve xs (c+1)\n\t|vow x = x:solve xs 0\n\t|otherwise = x:solve xs c\n\nmain=do\n\tl<- getLine\n\tputStrLn (solve l 0)\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Char\n\nvow 'a' = True\nvow 'e' = True\nvow 'i' = True\nvow 'o' = True\nvow 'u' = True\nvow _ = False\n\nsolve [] _ = []\nsolve (x:xs) c\n\t|(not (vow x)) && (c==2) = ' ':x:(solve xs 0)\n\t|(not (vow x)) = x:solve xs (c+1)\n\t|otherwise = x:solve xs c\n\nmain=do\n\tl<- getLine\n\tputStrLn (solve l 0)\n"}, {"source_code": "is_vowel :: Char -> Bool\nis_vowel 'a' = True\nis_vowel 'e' = True\nis_vowel 'i' = True\nis_vowel 'o' = True\nis_vowel 'u' = True\nis_vowel ch = False\n\nf :: String -> String\nf \"\" = \"\"\nf (a:\"\") = a : \"\"\nf (a:b:\"\") = a : b : \"\"\nf (a:rema) = a : s' ++ (' ' : f t')\n where s = takeWhile (\\x -> x == a) rema\n t = dropWhile (\\x -> x == a) rema\n l = length s\n s' = if l == 0 then [head rema] else s\n t' = if l == 0 then tail rema else t\n\ng :: String -> String\ng \"\" = \"\"\ng (a:rema) | is_vowel a = a : g rema\n | otherwise = f (a:s) ++ g t\n where s = takeWhile (not . is_vowel) rema\n t = dropWhile (not . is_vowel) rema \n \nmain :: IO ()\nmain = do\n line <- getLine\n putStrLn $ g line\n"}, {"source_code": "is_vowel :: Char -> Bool\nis_vowel 'a' = True\nis_vowel 'e' = True\nis_vowel 'i' = True\nis_vowel 'o' = True\nis_vowel 'u' = True\nis_vowel ch = False\n\nf :: String -> String\nf \"\" = \"\"\nf (a:\"\") = a : \"\"\nf (a:rema) | is_vowel a = a : f rema\n | otherwise = let s'' = takeWhile is_vowel t'\n t'' = dropWhile is_vowel t' \n in a : s' ++ s'' ++ (' ' : f t'')\n where s = takeWhile (\\x -> x == a) rema\n t = dropWhile (\\x -> x == a) rema\n l = length s\n s' = if l == 0 then [head rema] else s\n t' = if l == 0 then tail rema else t\n \nmain :: IO ()\nmain = do\n line <- getLine\n putStrLn $ f line\n"}], "src_uid": "436c00c832de8df739fc391f2ed6dac4"} {"source_code": "import Control.Monad\n-- import Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n\ngetIntList :: IO [Integer]\ngetIntList = fmap (map read) getStrList\n\nf :: Integer -> Integer -> Integer\nf c s\n | r == 0 = c * d * d\n | otherwise = r * (d + 1) * (d + 1) + (c - r) * d * d\n where r = s `mod` c\n d = s `div` c\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [c, s] <- getIntList\n print $ f c s", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int\nsolve x y = (n^2)*(x-m)+((n+1)^2)*m\n where\n n = y `div` x\n m = y `mod` x\n\nroutine :: IO ()\nroutine = do\n l <- fmap ((map read).words) getLine\n print $ solve (l!!0) (l!!1)\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n $ routine\n"}], "negative_code": [], "src_uid": "0ec973bf4ad209de9731818c75469541"} {"source_code": "import qualified Data.Map as M\nimport Control.Applicative\nimport Data.List\nimport Data.Function\n\nf _ m [] = fst $ minimumBy (compare `on` snd) $ M.assocs m\nf i m (a:as) = f (i+1) (M.alter (\\_ -> Just i) a m) as\n\nmain = do\n n <- readLn :: IO Int\n as <- map (read :: String -> Int ) . words <$> getLine\n let b = f 0 M.empty as \n print b", "positive_code": [{"source_code": "import qualified Data.IntMap as M\nimport Data.List\nimport Data.Function\nmain = 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"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap as I\nimport Data.List (foldl')\nimport Data.Maybe\n\nreadI = fst . fromJust . C.readInt\n\nmain = C.interact $ C.pack . solve . map readI . C.words\n\nsolve (n:xs) = show $ ans\n where\n ans = snd $ minimum $ I.elems mp\n ys = zip [0..] xs\n mp = foldl' f I.empty ys\n f m v@(_,k) = I.insert k v m\n \n"}, {"source_code": "import qualified Data.Map.Strict as M\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Data.List\nimport Data.Function\nimport Data.Maybe\n\n\nf _ m [] = fst $ minimumBy (compare `on` snd) $ M.assocs m\nf i m (a:as) = f (i+1) (M.alter (\\_ -> Just i) a m) as\n\nmain = do\n n <- readLn :: IO Int\n as <- map (fst . fromJust . B.readInt ) . B.words <$> B.getLine\n let b = f 0 M.empty as \n print b"}], "negative_code": [], "src_uid": "bdea209c7b628e4cc90ebc2572826485"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest :: Integer -> IO ()\ntest 0 = return ()\ntest t = do\n (n:x:_) <- map read.words <$> getLine\n as <- map read.words <$> getLine\n let m = maximum as\n print (if any (== x) as then 1 else max 2 $ div x m + fromEnum (mod x m /= 0))\n test (t - 1)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Ratio\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [_,x] <- (map read.words) <$> getLine\n l <- (map read.words) <$> getLine\n print $ solve x l\n\nsolve :: Int -> [Int] -> Int\nsolve x l\n | x `elem` l = 1\n |otherwise = max 2 (ceiling (x % max1))\n where\n max1 = maximum l\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (n, x) <- liftM2 (,) get get\n as <- replicateM n get\n putln $ f2 as x\n\nf2 :: [Int64] -> Int64 -> Int64\nf2 as x = minimum $ fmap (\\k -> if (mod x k) == 0 then (div x k) else max (div (x + k - 1) k) 2) as"}, {"source_code": "import Control.Monad\n\ndoit :: IO ()\ndoit = do\n [_, x] <- fmap (map read . words) getLine\n tmp <- fmap (map read . words) getLine\n print $ if x `elem` tmp then 1 else\n let y = maximum tmp\n in 2 `max` ((x + y - 1) `div` y)\n\nmain = readLn >>= flip replicateM_ doit\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (n, x) <- liftM2 (,) get get\n as <- replicateM n get\n putln $ f2 as x\n\nf2 :: [Int64] -> Int64 -> Int64\nf2 as x = let k = maximum as\n in\n if (mod x k) == 0 then (div x k) else max (div (x + k - 1) k) 2"}], "src_uid": "b6a7e8abc747bdcee74653817085002c"} {"source_code": "import Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Ratio (Ratio, (%), numerator, denominator)\n\nsolve :: Integer -> [Integer] -> Ratio Integer\nsolve n a = inc + sum out\n where\n dist = zipWith (-) (tail a) a :: [Integer]\n out = zipWith (\\d k -> 2 * k * (n - k) * d % n) dist [1..]\n inc = sum $ (% n) <$> a :: Ratio Integer\n\nwrap :: Int -> [Int] -> [String]\nwrap n a = [show i, \" \", show j]\n where\n out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Integer\n [i, j] = ($ out) <$> [numerator, denominator] :: [Integer]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n mapM_ putStr $ wrap n a\n", "positive_code": [{"source_code": "import Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString.Char8 as C\nimport Data.Ratio (Ratio, (%), numerator, denominator)\n\nsolve :: Int64 -> [Int64] -> Ratio Int64\nsolve n a = (sum a + x + y) % n\n where\n x = (2*) . sum . zipWith (\\i j -> (2 * i + 1 - n) * j) [1..n - 2] $ tail a\n y = 2 * (n - 1) * (last a - head a)\n\nwrap :: Int -> [Int] -> [String]\nwrap n a = [show i, \" \", show j]\n where\n out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64\n [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n mapM_ putStr $ wrap n a\n"}, {"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO()\nmain = putStrLn . unwords . map show . solve . map (fst . fromJust . C.readInteger) . C.words =<< B.getContents\n\nsolve :: [Integer] -> [Integer]\nsolve (n:a) = let sorted = sort a\n relativeDist = sum $ calcRelativeDist 1 (head sorted) 0 (tail sorted)\n absoluteDist = sum a\n totalDist = 2 * relativeDist + absoluteDist\n common = gcd totalDist n\n in [div totalDist common, div n common]\n\ncalcRelativeDist :: Integer -> Integer -> Integer -> [Integer] -> [Integer]\ncalcRelativeDist i last dist [] = [dist]\ncalcRelativeDist i last dist (a:s) = dist : calcRelativeDist (i + 1) a (dist + i * (a - last)) s\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Ratio\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncasti = fromIntegral\n\nmain = do\n n <- readInt <$> B.getLine\n l <- map readInt . B.words <$> B.getLine\n let r = solve n l\n putStrLn $ show (numerator r) ++ \" \"++ show (denominator r)\n\nsolve :: Int -> [Int] -> Rational\nsolve n l = foldl' f s1 (zip3 (tail l') sums [1..])\n where\n l' = map casti (sort l)\n sums = scanl1 (+) $ zipWith (*) l' [ 4*i-1 | i <- [1..]]\n s1 = head l'\n f a (b,s,n) = a +( (2*n+1)*b - s/n) / (n+1)\n\n\n"}], "negative_code": [{"source_code": "import Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString.Char8 as C\nimport Data.Ratio (Ratio, (%), numerator, denominator)\n\nsolve :: Int64 -> [Int64] -> Ratio Int64\nsolve n a = inc + 2 * sum out\n where\n dist = zipWith (-) (tail a) a :: [Int64]\n out = zipWith (\\d k -> k * (n - k) * d % n) dist [1..] :: [Ratio Int64]\n inc = sum a % n :: Ratio Int64\n\nwrap :: Int -> [Int] -> [String]\nwrap n a = [show i, \" \", show j]\n where\n out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64\n [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n mapM_ putStr $ wrap n a\n"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Ratio (Ratio, (%), numerator, denominator)\n\nsolve :: Int64 -> [Int64] -> Ratio Int64\nsolve n a = inc + sum out\n where\n dist = zipWith (-) (tail a) a :: [Int64]\n out = zipWith (\\d k -> 2 * k * (n - k) * d % n) dist [1..] :: [Ratio Int64]\n inc = sum a % n :: Ratio Int64\n\nwrap :: Int -> [Int] -> [String]\nwrap n a = [show i, \" \", show j]\n where\n out = solve (fromIntegral n) (fromIntegral <$> 0:sort a) :: Ratio Int64\n [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n mapM_ putStr $ wrap n a\n"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport Control.Applicative (liftA, (<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Ratio (Ratio, (%), numerator, denominator)\n\nsolve :: Int64 -> [Int64] -> Ratio Int64\nsolve n a = inc + sum out\n where\n dist = zipWith (-) (tail a) a :: [Int64]\n out = zipWith (\\d k -> 2 * k * (n - k) * d % n) dist [1..] :: [Ratio Int64]\n inc = sum a % n :: Ratio Int64\n\nwrap :: Int -> [Int] -> [String]\nwrap n a = [show i, \" \", show j]\n where\n out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64\n [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = parse <$> B.getLine >>= \\[n] -> parse <$> B.getLine >>= \\a ->\n mapM_ putStr $ wrap n a\n"}], "src_uid": "ad50e2946470fa8e02eb70d8cef161c5"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\ntest :: Int64 -> Int64 -> Int64 -> Int64 -> Bool\ntest n a b acc\n | acc > n = False\n | not good && a == 1 = False\n | otherwise = if good then True else test n a b $ a*acc\n where good = (mod (n-acc) b == 0)\n\n\nsolve :: String -> String\nsolve s = let [n, a, b] = map read $ words s :: [Int64]\n res = test n a b 1\n in (if test n a b 1 then \"Yes\" else \"No\")\n\nmain = do\n t <- readLn :: IO Int\n lines <- sequence $ replicate t getLine\n let res = map solve lines \n in putStrLn $ L.intercalate \"\\n\" res\n \n\n \n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet n a b pow \r\n | pow > n = False \r\n | (n - pow) `rem` b == 0 = True\r\n | a == 1 = False\r\n | otherwise = belongsToSet n a b (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet n a b 1 then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet n a b = go 1 where\r\n go pow | pow > n = False \r\n | (n - pow) `rem` b == 0 = True\r\n | a == 1 = False\r\n | otherwise = go (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet n a b then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet :: (Integer, Integer) -> Integer -> Bool \r\nbelongsToSet (a, b) n = go 1 where\r\n go pow | pow > n = False \r\n | (n - pow) `mod` b == 0 = True\r\n | a == 1 = False\r\n | otherwise = go (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet (a, b) n then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet :: (Integer, Integer) -> Integer -> Bool \r\nbelongsToSet (a, b) n = go 1 where\r\n go pow | pow > n = False \r\n | (n - pow) `rem` b == 0 = True\r\n | a == 1 = False\r\n | otherwise = go (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet (a, b) n then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\ntest :: Int64 -> Int64 -> Int64 -> Int64 -> Bool\ntest n a b acc\n | acc > n = False\n | not good && a == 1 = False\n | otherwise = if good then True else test n a b $ a*acc\n where good = (mod (n-acc) b == 0)\n\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [n, a, b] = map read $ words s :: [Int64]\n res = test n a b 1\n in putStrLn (if test n a b 1 then \"Yes\" else \"No\")\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n\n \n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\")\r\n >>> unlines\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve [n, 1, b] = b == 1 || n `mod` b == 1\r\nsolve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1\r\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nsolve n a b x\r\n | x > n = False\r\n | mod (n-x) b == 0 = True \r\n | a == 1 = False\r\n | otherwise = solve n a b (x*a) \r\n\r\nprintResult = do\r\n [n,a,b] <- readInts\r\n putStrLn $ if solve n a b 1 then \"Yes\" else \"No\"\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nsolve n a b temp r \r\n | temp > n = putStrLn\"No\"\r\n | (((mod temp b) == r) && (temp <= n)) = putStrLn\"Yes\"\r\n | otherwise = solve n a b (temp*a) r\r\nprintS = do \r\n [n,a,b]<-readInts \r\n let r = mod n b \r\n if ( (b==1) || (r == 1) || ((a==1) && (r==1)) ) then putStrLn\"Yes\"\r\n else do \r\n if a==1 then putStrLn\"No\"\r\n else solve n a b a r\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet :: (Integer, Integer) -> Integer -> Bool \r\nbelongsToSet (a, b) n = a /= 1 && go 1 where\r\n go pow | pow > n = False \r\n | (n - pow) `rem` b == 0 = True\r\n | a == 1 = False\r\n | otherwise = go (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet (a, b) n then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet :: (Integer, Integer) -> Integer -> Bool \r\nbelongsToSet (a, b) n = a /= 1 && go 1 where\r\n go pow | pow > n = False \r\n | (n - pow) `rem` b == 0 = True \r\n | otherwise = go (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet (a, b) n then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine\r\n\r\nbelongsToSet :: (Int, Int) -> Int -> Bool \r\nbelongsToSet (a, b) n = go 1 where\r\n go pow | a == 1 || pow > n = False \r\n | (n - pow) `rem` b == 0 = True \r\n | otherwise = go (a * pow)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, a, b] <- readInts\r\n putStrLn $ if belongsToSet (a, b) n then \"Yes\" else \"No\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\")\r\n >>> unlines\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve [n, 1, b] = n `mod` b == 1\r\nsolve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1\r\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\nimport Data.List (unfoldr)\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read >>> solve >>> bool \"No\" \"Yes\")\r\n >>> unlines\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve [n, 1, b] = n `mod` b == 1\r\nsolve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1\r\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nsolve n a b x\r\n | mod (n-x) b == 0 = True \r\n | x > n || a == 1 = False\r\n | otherwise = solve n a b (x*a) \r\n\r\nprintResult = do\r\n [n,a,b] <- readInts\r\n putStrLn $ if solve n a b 1 then \"Yes\" else \"No\"\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "src_uid": "e0a3c678f6d1d89420c8162b0ddfcef7"} {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.ByteString.Char8 as T\n\ntoHoleArray :: Int -> [Int] -> A.UArray Int Bool\ntoHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\\i -> (i, True)) holeList\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve nCups holeList opData = if hasHole 1 then 1 else swap 1 opData where\n holes = S.fromList holeList -- toHoleArray nCups holeList\n hasHole :: Int -> Bool\n hasHole i = i `S.member` holes\n swap boneIndex [] = boneIndex\n swap boneIndex (from:to:rest) = \n if from == boneIndex then\n if hasHole to then to else swap to rest\n else if to == boneIndex then\n if hasHole from then from else swap from rest\n else swap boneIndex rest\n\ntests = and [\n checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1], \n checkEqual 2 $ solve 5 [2] [1,2, 2,4],\n checkEqual 300001 $ solve 1000000 [] (concat $ map (\\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000)) \n ] where\n checkEqual i1 i2 = if i1 /= i2 then error (\"Expected \" ++ show i1 ++ \", was \" ++ show i2) else True\n\nmain :: IO ()\nmain = do\n contents <- T.hGetContents stdin\n-- input <- openFile \"input.txt\" ReadMode\n-- contents <- T.hGetContents input\n let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents\n (holeList, opData) = splitAt mHoles rest\n putStrLn $ show $ solve nCups holeList opData \n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, _, k] <- getInts\n holes <- getInts\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n swap pos (i, j) | holeMap ! pos = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n doSwaps pos 0 = return pos\n doSwaps pos x = do\n p <- getInt2\n doSwaps (swap pos p) (x - 1)\n pos <- doSwaps 1 k\n print pos\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, _, k] <- getInts\n holes <- getInts\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n swap pos (i, j) | holeMap ! pos = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n doSwaps pos 0 = return pos\n doSwaps pos x = do\n p <- getInt2\n doSwaps (swap pos p) (x - 1)\n pos <- doSwaps 1 k\n print pos\n"}, {"source_code": "import Control.Applicative\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, _, k] <- getInts\n holes <- getInts\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n swap pos [i, j] | holeMap ! pos = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n doSwaps pos 0 = return pos\n doSwaps pos x = do\n p <- getInts\n doSwaps (swap pos p) (x - 1)\n pos <- doSwaps 1 k\n print pos\n"}, {"source_code": "import Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, m, k] <- getInts\n holes <- getInts\n changes <- replicateM k getInt2\n\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n pos = foldl' swap 1 changes\n swap pos (i, j) | holeMap ! pos = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n print pos\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = unfoldr (liftA (second $ BS.drop 1). BS.readInt) <$> BS.getLine\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, _, k] <- getInts\n holes <- getInts\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n swap pos (i, j) | holeMap ! pos = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n doSwaps pos 0 = return pos\n doSwaps pos x = do\n p <- getInt2\n doSwaps (swap pos p) (x - 1)\n pos <- doSwaps 1 k\n print pos\n"}, {"source_code": "import Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, _, k] <- getInts\n holes <- getInts\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n set pos i | pos < 0 = pos\n | holeMap ! i = - i\n | otherwise = i\n swap pos (i, j) | pos == i = set pos j\n | pos == j = set pos i\n | otherwise = pos\n doSwaps pos 0 = return $ abs pos\n doSwaps pos x = do\n p <- getInt2\n doSwaps (swap pos p) (x - 1)\n pos <- doSwaps (set 1 1) k\n print pos\n"}, {"source_code": "import Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntSet as IntSet\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, m, k] <- getInts\n holes <- getInts\n changes <- replicateM k getInt2\n\n let holeMap = IntSet.fromList holes\n pos = foldl' swap 1 changes\n swap pos (i, j) | IntSet.member pos holeMap = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n print pos\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Data.IntSet( member, empty, insert)\nimport Control.Monad( replicateM)\nimport Data.ByteString.Char8( readInt, getLine, words\t)\nimport qualified Data.ByteString.Char8 as CHAR\nimport Data.Maybe( fromJust)\n\nmain = do\n let\n\treadInt' = fst . fromJust . readInt\n\n [n_, _m_, k_] <- map readInt' . CHAR.words <$> CHAR.getLine\n hs_ <- CHAR.words <$> CHAR.getLine\n let\n\tholes = foldl holeEntry empty hs_\n\t where\n\t holeEntry set bs = readInt' bs `insert` set\n\n orders_ <- replicateM k_ CHAR.getLine\n let\n\tswappingOrders = readPairs <$> orders_\n\t where\n\t readPairs line = let\n\t\t\t [a,b] = CHAR.words line\n\t\t\tin\n\t\t\t (readInt' a, readInt' b)\n\n\tswap bone [] = bone\n\tswap bone ((a,b):pairs) = if a==bone\n\t\t\t\t then if b `member` holes\n\t\t\t\t\t then b\n\t\t\t\t\t else swap b pairs\n\t\t\t\t else if b==bone\n\t\t\t\t\tthen if a `member` holes\n\t\t\t\t\t then a\n\t\t\t\t\t else swap a pairs\n\t\t\t\t\telse swap bone pairs\n print $ swap 0 ((0,1):swappingOrders)\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.ByteString.Char8 as T\n\ntoHoleArray :: Int -> [Int] -> A.UArray Int Bool\ntoHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\\i -> (i, True)) holeList\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve nCups holeList opData = if hasHole 1 then 1 else swap 1 opData where\n holes = toHoleArray nCups holeList\n hasHole :: Int -> Bool\n hasHole i = (A.!) holes i\n swap boneIndex [] = boneIndex\n swap boneIndex (from:to:rest) = \n if from == boneIndex then\n if hasHole to then to else swap to rest\n else if to == boneIndex then\n if hasHole from then from else swap from rest\n else swap boneIndex rest\n\ntests = and [\n checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1], \n checkEqual 2 $ solve 5 [2] [1,2, 2,4],\n checkEqual 300001 $ solve 1000000 [] (concat $ map (\\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000)) \n ] where\n checkEqual i1 i2 = if i1 /= i2 then error (\"Expected \" ++ show i1 ++ \", was \" ++ show i2) else True\n\nmain :: IO ()\nmain = do\n contents <- T.hGetContents stdin\n-- input <- openFile \"input.txt\" ReadMode\n-- contents <- T.hGetContents input\n let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents\n (holeList, opData) = splitAt mHoles rest\n putStrLn $ show $ solve nCups holeList opData \n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine, getContents)\nimport qualified Data.ByteString.Char8 as C (readInt, words, lines)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Set as S (fromList, member)\n\nreadInt = fst. M.fromJust . C.readInt\n\nrun s [] p = p\nrun s ([u, v]:uvs) p | p `S.member` s = p\n | p == u = run s uvs v\n | p == v = run s uvs u\n | otherwise = run s uvs p\n\nmain = do\n (map readInt . C.words -> [n, m, k]) <- B.getLine\n (map readInt . C.words -> hs) <- B.getLine\n (map (map readInt . C.words) . C.lines -> uvs) <- B.getContents\n putStrLn $ show $ run (S.fromList hs) uvs 1\n"}, {"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.ByteString.Char8 as T\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- T.getLine\n let holeWords = T.words s2\n holeList = map (fst . fromJust . T.readInt) $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k T.getLine\n let ops = map (\\s -> let [a,b] = map (fst . fromJust . T.readInt) $ T.words s in (a,b)) s3\n-- ops <- replicateM k $ do a <- readInt; b <- readInt; return (a,b)\n let sol = \n {-if m > 90000 && n > 900000 && abs (sum (map (\\(a,b) -> a+b) ops) + 1) >= 0 then error \"hll\" \n else if m > 90000 && n > 900000 then -1 \n else -}solve 1 ops holes\n putStrLn $ show sol\n\n return ()"}], "negative_code": [{"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n let ops = map (\\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3\n 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\n putStrLn $ if m > 90000 && n > 900000 then \"wrong\" else show sol\n\n return ()"}, {"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n let ops = map (\\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3\n 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\n putStrLn $ if m > 90000-1 && n > 900000-1 then \"wrong\" else show sol\n\n return ()"}, {"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n let ops = map (\\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3\n 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\n putStrLn $ if m > 90000 && n > 900000 then \"wrong\" else show sol\n\n return ()"}, {"source_code": "--module Main2 where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n 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\n let sol = solve 1 ops holes\n putStrLn $ show sol\n\n return ()"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine, getContents)\nimport qualified Data.ByteString.Char8 as C (readInt, words, lines)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Set as S (fromList, member)\n\nreadInt = fst. M.fromJust . C.readInt\n\nrun s [] p = p\nrun s ([u, v]:uvs) p | p == u = g v\n | p == v = g u\n | otherwise = g p where\n g x | x `S.member` s = x\n | otherwise = run s uvs x\n \n\nmain = do\n (map readInt . C.words -> [n, m, k]) <- B.getLine\n (map readInt . C.words -> hs) <- B.getLine\n (map (map readInt . C.words) . C.lines -> uvs) <- B.getContents\n putStrLn $ show $ run (S.fromList hs) uvs 1\n"}, {"source_code": "import Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, _, k] <- getInts\n holes <- getInts\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes $ repeat True\n set pos i | pos < 0 = pos\n | holeMap ! i = - i\n | otherwise = i\n swap pos (i, j) | pos == i = set pos j\n | pos == j = set pos i\n | otherwise = pos\n doSwaps pos 0 = return $ abs pos\n doSwaps pos x = do\n p <- getInt2\n doSwaps (swap pos p) (x - 1)\n pos <- doSwaps 1 k\n print pos\n"}, {"source_code": "import Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', unfoldr)\n\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\ngetInt2::IO (Int,Int)\ngetInt2 = do\n line <- BS.getLine\n let Just (x, l') = BS.readInt line\n Just (y, _) = BS.readInt $ BS.drop 1 l'\n return (x,y)\n\nmain :: IO ()\nmain = do\n [n, m, k] <- getInts\n holes <- getInts\n changes <- replicateM k getInt2\n\n let holeMap::UArray Int Bool\n holeMap = array (1, n) $ zip holes [True]\n pos = foldl' swap 1 changes\n swap pos (i, j) | holeMap ! pos = pos\n | pos == i = j\n | pos == j = i\n | otherwise = pos\n print pos\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Data.IntSet( member, empty, insert)\nimport Control.Monad( replicateM)\nimport Data.ByteString.Char8( readInt, getLine, words\t)\nimport qualified Data.ByteString.Char8 as CHAR\nimport Data.Maybe( fromJust)\n\nmain = do\n let\n\treadInt' = fst . fromJust . readInt\n\n [n_, _m_, k_] <- map readInt' . CHAR.words <$> CHAR.getLine\n hs_ <- CHAR.words <$> CHAR.getLine\n let\n\tholes = foldl holeEntry empty hs_\n\t where\n\t holeEntry set bs = readInt' bs `insert` set\n\n orders_ <- replicateM k_ CHAR.getLine\n let\n\tswappingOrders = readPairs <$> orders_\n\t where\n\t readPairs line = let\n\t\t\t [a,b] = CHAR.words line\n\t\t\tin\n\t\t\t (readInt' a, readInt' b)\n\n\tswap bone [] = bone\n\tswap bone ((a,b):pairs) = if a==bone\n\t\t\t\t then if b `member` holes\n\t\t\t\t\t then b\n\t\t\t\t\t else swap b pairs\n\t\t\t\t else if b==bone\n\t\t\t\t\tthen if a `member` holes\n\t\t\t\t\t then a\n\t\t\t\t\t else swap a pairs\n\t\t\t\t\telse swap bone pairs\n print $ swap 1 swappingOrders\n"}, {"source_code": "--module Main2 where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n 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\n let sol = solve 1 ops holes\n putStrLn $ show sol\n\n return ()"}, {"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n let ops = map (\\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3\n 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\n putStrLn $ if m > 90000 && n > 900000 then \"wrong\" else show sol\n\n return ()"}, {"source_code": "--module Main2 where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n 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\n let sol = solve 1 ops holes\n putStrLn $ show sol\n\n return ()"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport System.IO\nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\n\ntoHoleArray :: Int -> [Int] -> A.UArray Int Bool\ntoHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\\i -> (i, True)) holeList\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve nCups holeList opData = swap 1 opData where\n holes = toHoleArray nCups holeList\n hasHole :: Int -> Bool\n hasHole !i = (A.!) holes i\n swap !boneIndex [] = boneIndex\n swap !boneIndex (from:to:rest) = \n if from == boneIndex then\n if hasHole to then to else swap to rest\n else if to == boneIndex then\n if hasHole from then from else swap from rest\n else swap boneIndex rest\n\ntests = and [\n checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1], \n checkEqual 2 $ solve 5 [2] [1,2, 2,4],\n checkEqual 75001 $ solve 1000000 [] (concat $ map (\\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000 `div` 4)) \n ] where\n checkEqual i1 i2 = if i1 /= i2 then error (\"Expected \" ++ show i1 ++ \", was \" ++ show i2) else True\n \nmain :: IO ()\nmain = do\n contents <- TIO.hGetContents stdin\n putStrLn $ show $ T.words contents\n let (nCups:mHoles:kOps:rest) = map (read . T.unpack) $ T.words contents :: [Int]\n (holeList, opData) = splitAt mHoles rest\n putStrLn $ show $ solve nCups holeList opData \n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.ByteString.Char8 as T\n\ntoHoleArray :: Int -> [Int] -> A.UArray Int Bool\ntoHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\\i -> (i, True)) holeList\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve nCups holeList opData = swap 1 opData where\n holes = toHoleArray nCups holeList\n hasHole :: Int -> Bool\n hasHole !i = (A.!) holes i\n swap !boneIndex [] = boneIndex\n swap !boneIndex (from:to:rest) = \n if from == boneIndex then\n if hasHole to then to else swap to rest\n else if to == boneIndex then\n if hasHole from then from else swap from rest\n else swap boneIndex rest\n\ntests = and [\n checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1], \n checkEqual 2 $ solve 5 [2] [1,2, 2,4],\n checkEqual 300001 $ solve 1000000 [] (concat $ map (\\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000)) \n ] where\n checkEqual i1 i2 = if i1 /= i2 then error (\"Expected \" ++ show i1 ++ \", was \" ++ show i2) else True\n\nmain :: IO ()\nmain = do\n contents <- T.hGetContents stdin\n-- input <- openFile \"input.txt\" ReadMode\n-- contents <- T.hGetContents input\n let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents\n (holeList, opData) = splitAt mHoles rest\n putStrLn $ show $ solve nCups holeList opData \n\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\nimport qualified Data.ByteString.Char8 as T\n\ntoHoleArray :: Int -> [Int] -> A.UArray Int Bool\ntoHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\\i -> (i, True)) holeList\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve nCups holeList opData = swap 1 opData where\n holes = toHoleArray nCups holeList\n hasHole :: Int -> Bool\n hasHole i = (A.!) holes i\n swap boneIndex [] = boneIndex\n swap boneIndex (from:to:rest) = \n if hasHole from then from\n else if from == boneIndex then\n if hasHole to then to else swap to rest\n else if to == boneIndex then\n if hasHole from then from else swap from rest\n else swap boneIndex rest\n\ntests = and [\n checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1], \n checkEqual 2 $ solve 5 [2] [1,2, 2,4],\n checkEqual 300001 $ solve 1000000 [] (concat $ map (\\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000)) \n ] where\n checkEqual i1 i2 = if i1 /= i2 then error (\"Expected \" ++ show i1 ++ \", was \" ++ show i2) else True\n\nmain :: IO ()\nmain = do\n contents <- T.hGetContents stdin\n-- input <- openFile \"input.txt\" ReadMode\n-- contents <- T.hGetContents input\n let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents\n (holeList, opData) = splitAt mHoles rest\n putStrLn $ show $ solve nCups holeList opData \n\n"}, {"source_code": "--module Main2 where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n 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\n let sol = solve 1 ops holes\n putStrLn $ show sol\n\n return ()"}, {"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n let ops = map (\\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3\n 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\n putStrLn $ if m > 90000 && n > 900000 then \"wrong\" else show sol\n\n return ()"}, {"source_code": "module Main where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n let ops = map (\\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3\n 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\n putStrLn $ if m > 90000-1 && n > 900000-1 then \"wrong\" else show sol\n\n return ()"}, {"source_code": "--module Main2 where\nimport System.IO\nimport Control.Monad\nimport Control.Applicative\nimport Data.List \nimport qualified Data.Set as S\nimport qualified Data.Array.Unboxed as A\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsolve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int\nsolve x [] holes = x\nsolve x ((a,b):op) holes | ((A.!) holes x) = x\n | x == a = if ((A.!) holes b) then b else solve b op holes\n | x == b = if ((A.!) holes a) then a else solve a op holes\n | otherwise = solve x op holes\n\nreadInt :: IO Int\nreadInt = inner \"\" where\n inner prefix = do\n eof <- isEOF\n if eof then return $ read prefix \n else do\n c <- getChar\n if isDigit c then inner $ prefix ++ [c]\n else if null prefix then inner prefix \n else return $ read prefix\n\nisDigit c = c >= '0' && c <= '9'\n\narr :: A.UArray Int Bool\narr = A.accumArray (||) False (0,1000000) $ map (\\w -> (w, True)) $ map (\\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000\n\nmain :: IO ()\nmain = do\n n <- readInt\n m <- readInt\n k <- readInt\n s2 <- getLine\n let holeWords = words s2\n holeList = map parseInt $ take m holeWords\n let holes = A.accumArray (||) False (1,n) $ map (\\w -> (w, True)) holeList\n s3 <- replicateM k getLine\n 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\n let sol = solve 1 ops holes\n putStrLn $ show sol\n\n return ()"}], "src_uid": "1f41c017102f4a997be324a4ec9b7fd6"} {"source_code": "import Control.Monad\nimport Data.List\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- sort <$> readInts\n case compare (sum a) 0 of\n EQ -> putStrLn \"NO\"\n LT -> putStrLn \"YES\" >> putStrLn (unwords $ map show a)\n GT -> putStrLn \"YES\" >> putStrLn (unwords . reverse $ map show a)\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n testCases <- read <$> getLine\n replicateM testCases $ do\n _ <- getLine\n nums <- (map read) <$> words <$> getLine\n putStrLn $ solve nums\n\nsolve :: [Int] -> String\nsolve xs\n | sum xs == 0 = \"NO\"\n | sum xs < 0 = \"YES\\n\" ++ (concat $ intersperse \" \" $ map show $ sort xs)\n | sum xs > 0 = \"YES\\n\" ++ (concat $ intersperse \" \" $ map show $ reverse $ sort xs)"}], "negative_code": [], "src_uid": "e57345f5757654749b411727ebb99c80"} {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine\n case solve n m of\n Just res -> do\n putStrLn \"Possible\"\n putStr $ unlines [shows x \" \" ++ show y |(x,y)<-res]\n Nothing -> putStrLn \"Impossible\"\n\nlim :: Int\nlim = 1024\n\nsolve :: Int -> Int -> Maybe [(Int, Int)]\nsolve n m\n | m < n - 1 || length coprimes < m= Nothing\n | otherwise = Just $ take m coprimes\n where\n coprimes = map ((,)1) [2..n] ++ [(x, y)|x<-[2..min n lim], y<-[x+1..min n lim], gcd x y == 1]\n", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Int\n\ndoit i j n 0 = []\ndoit i j n t =\n if i > n then\n []\n else\n if j > n then\n doit (i+1) (i+2) n t\n else\n if (gcd i j) == 1 then\n (i,j):(doit i (j+1) n (t-1))\n else\n doit i (j+1) n t\n\n\n\nsolvee n m = doit 1 2 n m\n\nsolve::String -> String\nsolve sss =\n let (n:m:_) = map toint $ words sss in\n if m < n-1 then\n \"Impossible\\n\"\n else\n let r = solvee n m in\n if (length r) < m then\n \"Impossible\\n\"\n else\n \"Possible\\n\" ++ (intercalate \"\\n\" $ map (\\(x,y) -> (show x) ++ \" \" ++ (show y)) r) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine\n case solve n m of\n Just res -> do\n putStrLn \"Possible\"\n putStr $ unlines [shows x \" \" ++ show y |(x,y)<-res]\n Nothing -> putStrLn \"Impossible\"\n\nlim :: Int\nlim = 1024\n\nsolve :: Int -> Int -> Maybe [(Int, Int)]\nsolve n m\n | m < n - 1 || length coprimes < m= Nothing\n | otherwise = Just $ take m coprimes\n where\n coprimes = [(x, y)|x<-[1..min n lim], y<-[x+1..min n lim], gcd x y == 1]\n"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [n, m] <- map read.words <$> getLine\n case solve n m of\n Just res -> do\n putStrLn \"Possible\"\n putStr $ unlines [shows x \" \" ++ show y |(x,y)<-res]\n Nothing -> putStrLn \"Impossible\"\n\nlim :: Int\nlim = 1024\n\nsolve :: Int -> Int -> Maybe [(Int, Int)]\nsolve n m\n | length coprimes < m = Nothing\n | otherwise = Just $ take m coprimes\n where\n coprimes = [(x, y)|x<-[1..min n lim], y<-[x+1..min n lim], gcd x y == 1]\n"}], "src_uid": "0ab1b97a8d2e0290cda31a3918ff86a4"} {"source_code": "getInts s = map read $ words s\n\nsolve :: Int -> Int -> Int -> Int\nsolve a b c = if (max b (2 * a) >= c) then -1 else max b (2 * a)\n \nmain = do\n s <- getLine\n a <- getLine\n b <- getLine\n print(solve (minimum $ getInts a) (maximum $ getInts a) (minimum $ getInts b))\n-- contents <- getContents\n-- let input = map ((\\(a:b:_) -> (a, b)) . map (read :: String -> Int) . words) $ lines contents\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\tgetLine\n\tas <- map read . words <$> getLine\n\tbs <- map read . words <$> getLine\n\tlet\n\t\tlb = max ( 2 * minimum as ) ( maximum as )\n\t\tub = minimum bs\n\tprint $ if lb < ub then lb else -1\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:_:s) = let a = take n s\n b = drop n s\n v = max ((minimum a) * 2) (maximum a)\n e = minimum b\n in if v < e then v else -1\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n [n,m] <- readsLine\n as <- readsLine\n bs <- readsLine\n case solve n m as bs of\n [] -> print $ -1\n x:_ -> print x\n\nsolve :: Int -> Int -> [Int] -> [Int] -> [Int]\nsolve n m as bs = do\n v <- [1..maximum bs]\n guard (all (pass v) as)\n guard (any (expass v) as)\n guard (all (not . pass v) bs)\n return v\n\npass v a = a <= v\nexpass v a = 2*a <= v\n\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [Int] -> Int\nsolve xs ys\n | maxXS >= minYS = -1\n | 2 * minXS >= minYS = -1\n | otherwise = max (2*minXS) maxXS\n where\n \tminXS = minimum xs\n \tmaxXS = maximum xs\n \tminYS = minimum ys\n\nmain :: IO ()\nmain = do\n\tgetLine\n\txs <- reads\n\tys <- reads\n\tprint $ solve xs ys\n"}, {"source_code": "module Main where\nimport Control.Applicative\nmain :: IO ()\nmain = do\n _ <- getLine\n correctTimes <- map read . words <$> getLine :: IO [Int]\n wrongTimes <- map read . words <$> getLine :: IO [Int]\n let minCorrectTime = minimum correctTimes\n maxCorrectTime = maximum correctTimes\n v = max (2*minCorrectTime) maxCorrectTime\n minWrongTime = minimum wrongTimes\n print $ if minWrongTime <= v then -1 else v\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . toTuple . map (map read . words) . tail . lines\n\nsolve :: ([Integer], [Integer]) -> Integer\nsolve (as, bs) = head $ [ v | v <- [ maximum as .. minimum bs - 1 ], 2 * minimum as <= v ] ++ [-1]\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- map read.words <$> getLine :: IO [Integer]\n let minx = minimum xs\n maxx = maximum xs\n res = max maxx (2 * minx)\n miny <- minimum.map read.words <$> getLine\n if res < miny then print res else print (-1)\n"}, {"source_code": "calc :: [Int] -> [Int] -> Int\ncalc a b = if vMin < vMax then vMin else -1\n\twhere\n\t\tvMin = max (maximum a) ((minimum a) * 2)\n\t\tvMax = minimum b\n\nhandle :: [String] -> [[String]]\nhandle (sn : sm : xs) = [[show $ calc a b]]\n\twhere\n\t\tn = read sn\n\t\ta = map read $ take n xs\n\t\tb = map read $ drop n xs\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "toInt x = read x :: Int\n\nmain = do s <- getLine\n s1 <- getLine\n s2 <- getLine\n let xs = map toInt (words s1)\n ys = map toInt (words s2)\n ac = maximum [2*minimum xs, maximum xs]\n wa = minimum ys\n if ac < wa\n then print ac\n else print $ -1\n"}, {"source_code": "get :: Int -> Int -> Int -> Int\nget a v b\n | (max a v) < b = max a v\n | otherwise = (-1) \n\nsolve :: String -> String\nsolve s = show $ ans\n where (x:y:xs) = map read (words s)\n first = take x ( xs)\n second = take y ( drop x xs)\n mina = minimum ( first )\n maxa = maximum ( first )\n minb = minimum ( second )\n ans = get (2*mina) maxa minb\n\nmain = do\n interact solve\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Data.Int\n\nmain = do\n getLine\n good <- map read <$> words <$> getLine\n bad <- map read <$> words <$> getLine\n print $ solve good bad\n\nsolve :: [Int] -> [Int] -> Int\nsolve good bad = \n let b = minimum bad\n maxG = maximum good\n minG = minimum good\n res = max (2*minG) maxG\n in if res >= b\n then -1\n else res"}, {"source_code": "main = do\n\tt <- getLine\n\tsa <- getLine\n\tsb <- getLine\n\tlet a = map (read::String->Int) $ words sa\n\t b = map (read::String->Int) $ words sb\n\t v = minimum a\n\t p = maximum a\n\t c = minimum b\n\t ans = if max (2*v) p < c \n\t\t\tthen max (2*v) p\n\t\t else -1;\n\tprint ans\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \n\nmain = do\n\tgetLine\n\ts<-map read.words <$> getLine ::IO [Int]\n\tt<-map read.words <$> getLine ::IO [Int]\n\tlet s1 = 2* minimum s \n\tlet s2 = maximum s\n\tlet s3 = minimum t\t\n\tlet ans = max s1 s2\n\tprint $ if ans x). BS.readInteger\ngetInt = (\\(Just (x,_)) -> x). BS.readInt\n\ngetIntArray = readIntArray\ngetIntegerArray = readIntegerArray\n\nreadIntArray input = \n case x of\n Just (a, xs) -> a : readIntArray xs\n Nothing -> []\n where\n x = BS.readInt. BS.dropWhile isSpace $ input \n\nreadIntegerArray input = \n case x of\n Nothing -> []\n Just (y, ys) -> y : readIntegerArray ys\n where\n x = BS.readInteger. BS.dropWhile isSpace $ input\n------------------------------------------------------ }}}\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getLine\n b <- getLine\n let\n (mn1, mx1) = (\\x -> (minimum x, maximum x)). map (read::String->Int). words $ a\n mn2 = minimum. map (read::String->Int). words$ b\n arr = filter (\\k -> 2*mn1 <= k && mx1 <= k && k < mn2) [1..100]\n print $ if null arr then -1 else head arr\n\n"}, {"source_code": "import Data.List\n\ncal ls = let good = map (+0) $ map read $ words $ ls !! 1\n\t bad = map (+0) $ map read $ words $ ls !! 2\n\t maxgood = maximum good\n\t mingood = minimum good\n\t minbad = minimum bad\n\t ans = max maxgood (2*mingood)\n\t in if ans < minbad then ans else -1\n\nmain = interact ( show . cal . lines)\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n getLine\n c <- fmap (map read . words) getLine\n w <- fmap (map read . words) getLine\n let minc = minimum c\n maxc = maximum c\n minw = minimum w\n rush minc maxc minw\n\nrush :: Int -> Int -> Int -> IO ()\nrush minc maxc minw\n | minw <= maxc = print $ -1\n | minw <= 2 * minc = print $ -1\n | otherwise = print $ max (2 * minc) maxc\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\n\ntoDigit n = chr (48 + n)\nreadInt = fst . fromJust . B.readInt\n\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\n\nsolve xs ys =\n solve' a b c\n where\n a = minimum xs\n b = maximum xs\n c = minimum ys\n\nsolve' a b c =\n if b >= c then \"-1\"\n else if 2*a <= b then show b else (solve' a (b+1) c)\n\nmain = do\n ls <- B.getContents ||> B.lines\n -- n <- head ls |> readIO :: IO Int\n xs <- (ref ls 1) |> B.words |> map readInt |> return\n ys <- (ref ls 2) |> B.words |> map readInt |> return\n putStrLn (solve xs ys)\n\n-- vim: set ft=haskell:\n"}], "negative_code": [{"source_code": "get :: Int -> Int -> Int -> Int\nget a v b\n | (max a v) < b = max a v\n | otherwise = (-1) \n\nsolve :: String -> String\nsolve s = show $ ans\n where (x:y:xs) = map read (words s)\n first = take x ( xs)\n second = take y ( drop x xs)\n mina = minimum ( first )\n maxa = maximum ( first )\n minb = minimum ( second )\n ans = get mina maxa minb\n\n\n\nmain = do\n interact solve\n"}, {"source_code": "import Data.List\n\ncal ls = let good = map (+0) $ map read $ words $ ls !! 1\n\t bad = map (+0) $ map read $ words $ ls !! 2\n\t maxgood = maximum good\n\t mingood = minimum good\n\t minbad = minimum bad\n\t ans = max maxgood (2*mingood)\n\t in if ans < minbad then -1 else ans\n\nmain = interact ( show . cal . lines)\n"}], "src_uid": "49c47ebfd710a3733ce7ecb3a3c134a7"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n dirs :: UArray Int Char <- listArray (1, n) <$> getLine\n ds :: UArray Int Int <- listArray (1, n) <$> getInts\n\n let\n f i bs\n | i < 1 || i > n = True\n | i `IntSet.member` bs = False\n | otherwise = f i' bs'\n where\n i' = i + if dirs!i == '>' then ds!i else -(ds!i)\n !bs' = i `IntSet.insert` bs\n\n putStrLn $ if f 1 IntSet.empty then \"FINITE\" else \"INFINITE\"", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n dirs :: UArray Int Char <- listArray (1, n) <$> getLine\n ds :: UArray Int Int <- listArray (1, n) <$> getInts\n\n bs :: IOUArray Int Bool <- newArray (1, n) False\n\n let\n f i\n | i < 1 || i > n = return True\n | otherwise = do\n b <- readArray bs i\n if b\n then return False\n else do\n writeArray bs i True\n f i'\n where\n i' = i + if dirs!i == '>' then ds!i else -(ds!i)\n\n b <- f 1\n\n putStrLn $ if b then \"FINITE\" else \"INFINITE\"\n"}, {"source_code": "import Data.Array.ST.Safe\nimport Data.Array.Unboxed\n\nhop visited dir dist pos\n | pos < 0 || pos >= (snd.bounds $ dir) = return True\n | otherwise = do\n e <- readArray visited pos\n if e then return False\n else do\n writeArray visited pos True\n hop visited dir dist $ pos + (if dir!pos then 1 else -1) * (dist ! pos)\n\n-- true if finite\nhopper :: UArray Int Bool -> UArray Int Int -> Bool\nhopper s d =\n (runSTUArray $ do\n a <- (newArray (bounds s) False)\n r <- hop a s d 0\n writeArray a 0 r\n return $ a) ! 0\n{-where -- Works, but slow on large arrays (// is O(n))\n hop visited x\n | x < 0 || x >= (snd $ bounds s) = True\n | visited ! x = False\n | otherwise = hop (visited // [(x, True)]) $ x + (if s ! x then d ! x else -(d ! x))\n-}\n\nmain = do\n sz <- getLine\n let s = read sz\n str <- getLine\n ints <- getLine\n let i = listArray (0,s).map read.words $ ints\n let d = listArray (0,s).map (=='>') $ str\n-- let i = listArray (0,s) $ repeat 1\n-- let d = listArray (0,s) $ repeat True\n putStrLn $ if hopper d i then \"FINITE\" else \"INFINITE\"\n"}, {"source_code": "import qualified Data.Set as S\nimport Data.Array\n\narrayify l = array (0, length l - 1) ([0..] `zip` l)\n\nmain = do\n n <- fmap read getLine\n s <- getLine\n ns <- fmap (map read . words) getLine\n let a = arrayify $ zipWith (\\c x -> if c == '>' then x else negate x) s ns\n --print a\n putStrLn $ if solve n a then \"FINITE\" else \"INFINITE\"\n\n\nsolve :: Int -> Array Int Int -> Bool\nsolve n a = solve' (S.singleton 0) 0\n where solve' s v\n | to < 0 || to >= n = True\n | to `S.member` s = False\n | otherwise = solve' (to `S.insert` s) to\n where to = a ! v + v\n"}, {"source_code": "import qualified Data.IntMap as IM\nimport Data.IntMap ((!))\nmain = do\n s' <- getLine >> getLine\n d' <- fmap (map read . words) getLine\n let d = IM.fromList $ zip [0..] d'\n s = IM.fromList $ zip [0..] s'\n n = IM.size d\n iter x = if s!x == '>' then x + (d!x) else x - (d!x)\n coords = iterate iter 0\n path = take (n+1) . takeWhile (\\x -> x >= 0 && x < n) $ coords\n putStrLn $ if length path == n+1 then \"INFINITE\" else \"FINITE\"\n\n"}, {"source_code": "import qualified Data.IntMap as IM\nimport Data.IntMap ((!))\nmain = do\n s' <- getLine >> getLine\n d' <- fmap (map read . words) getLine\n let d = IM.fromList $ zip [0..] d'\n s = IM.fromList $ zip [0..] s'\n n = length s'\n iter x = if s!x == '>' then x + (d!x) else x - (d!x)\n coords = iterate iter 0\n path = take (n+1) . takeWhile (\\x -> x >= 0 && x < n) $ coords\n putStrLn $ if length path == n+1 then \"INFINITE\" else \"FINITE\"\n\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport qualified Data.IntMap as IM\nimport Data.IntMap ((!))\nmain = do\n stdin <- B.getContents\n let (n, s', d') = flip evalState stdin $ do\n n <- readInt\n s <- readString\n d <- replicateM n readInt\n return (n, s, d)\n\n let d = IM.fromList $ zip [0..] d'\n s = IM.fromList $ zip [0..] $ B.unpack s'\n iter x = if s!x == '>' then x + (d!x) else x - (d!x)\n coords = iterate iter 0\n path = take (n+1) . takeWhile (\\x -> x >= 0 && x < n) $ coords\n putStrLn $ if length path == n+1 then \"INFINITE\" else \"FINITE\"\n\nreadInt :: State B.ByteString Int\nreadInt = do\n Just (n, rest) <- gets (B.readInt . B.dropWhile isSpace)\n put rest\n return n\n\nreadString :: State B.ByteString B.ByteString\nreadString = do\n (s, rest) <- gets (B.span (not.isSpace) . B.dropWhile isSpace)\n put rest\n return s\n\n"}], "negative_code": [], "src_uid": "5fcc22cdc38693723d8a9577d685db12"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> map (read >>> solve >>> show)\n >>> unlines\n\nsolve :: Integer -> Integer\nsolve 1 = 0\nsolve n = let r = round $ sqrt $ fromIntegral n in \n case compare (r * r) n of \n EQ -> 2 * r - 2\n LT -> 2 * r - 1\n GT -> 2 * r - 2\n ", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\n\ngetList :: (Read t) => IO [t]\ngetList = getLine >>= return . (map read) . words\n\ngetOne :: (Read t) => IO t\ngetOne = getLine >>= return . read\n\nmain :: IO ()\nmain = do\n t <- getOne\n -- let t = 1\n replicateM_ t solve\n\n\nsolve :: IO ()\nsolve = do \n n <- getOne\n print $ countAns n\n\ncountAns :: Integral t => t -> t\ncountAns 1 = 0\ncountAns n = f n $ binSearch n 0 n\n\n\nbinSearch :: Integral t => t -> t -> t -> t\nbinSearch n l r\n | r - l <= 1 = r\n | g n m = binSearch n m r\n | otherwise = binSearch n l m\n where\n m = (l + r) `div` 2\n\nf :: Integral a => a -> a -> a\nf n k = (k - 1) + (n - 1) `div` k\n\ng :: Integral a => a -> a -> Bool\ng n k = f' n k > f' n (k + 1)\n\n\nf' :: (Integral a, Fractional b) => a -> a -> b\nf' n k = fromIntegral (k - 1) + fromIntegral (n - 1) / fromIntegral k"}, {"source_code": "getToNFastest :: Int -> Int -> Int -> Int -> Int\ngetToNFastest biggest aSum steps n\n | aSum >= n = steps\n | fromIntegral aSum >= (fromIntegral n)**0.5 = getToNFastest biggest (aSum+biggest) (steps+1) n\n | otherwise = getToNFastest (biggest+1) (aSum+1) (steps+1) n\n\nmain :: IO()\nmain = do\n interact $ unlines . (map (show . (getToNFastest 1 1 0) . read)) . tail . lines\n"}, {"source_code": "import Control.Monad (replicateM_)\n\nceilDiv :: Int -> Int -> Int\nceilDiv a b | b * fd == a = fd\n | otherwise = fd + 1\n where\n fd = a `div` b\n\nminimalNumberOfMoves :: Int -> Int\nminimalNumberOfMoves bound = addCount + copyCount\n where\n addCount = sqrtCeilVal - 1\n copyCount = bound `ceilDiv` sqrtCeilVal - 1\n sqrtCeil = ceiling . sqrt . fromIntegral\n sqrtCeilVal = sqrtCeil bound\n\nsolve :: IO ()\nsolve = do\n bound <- (read <$> getLine) :: IO Int\n print $ minimalNumberOfMoves bound\n\nmain :: IO ()\nmain = do\n t <- (read <$> getLine) :: IO Int\n replicateM_ t solve\n"}, {"source_code": "import Control.Monad\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nsolve :: Int -> Int\nsolve n = let\n k = floor $ sqrt (fromIntegral n :: Double)\n opts = [v + ceilDiv n v - 2 | v <- [k - 2 .. k + 2], v > 0]\n in minimum opts\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n print $ solve n\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do \n n <- read <$> getLine :: IO Int\n let r = floor $ sqrt $ (fromIntegral n :: Double)\n r' = quot (n + r - 1) r\n print $ r + r' - 2\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> map (read >>> solve >>> show)\n >>> unlines\n\nsolve :: Integer -> Integer\nsolve 1 = 0\nsolve n = let r = round $ sqrt $ fromIntegral n in \n case compare (r * r) n of \n EQ -> 2 * r - 1\n LT -> 2 * r - 1\n GT -> 2 * r - 2\n "}, {"source_code": "getToNFastest :: Int -> Int -> Int -> Int -> Int\ngetToNFastest n biggest aSum steps\n | aSum >= n = steps\n | fromIntegral aSum >= (fromIntegral n)**0.5 = getToNFastest n biggest (aSum+biggest) (steps+1)\n | otherwise = getToNFastest n (biggest+1) (aSum+1) (steps+1)\n\nfindMin :: Int -> Int\nfindMin n = getToNFastest n 1 0 0\n\nmain :: IO()\nmain = do\n interact $ unlines . (map (show . findMin . read)) . tail . lines\n"}, {"source_code": "getToNFastest :: Int -> Int -> Int -> Int -> Int\ngetToNFastest n biggest aSum steps\n | aSum >= n = steps\n | fromIntegral aSum >= (fromIntegral n)**0.5 = getToNFastest n biggest (aSum+biggest) (steps+1)\n | otherwise = getToNFastest n (biggest+1) (aSum+1) (steps+1)\n\nmain :: IO()\nmain = do\n interact $ unlines . (map (show . (getToNFastest 1 1 0) . read)) . tail . lines\n"}], "src_uid": "d78cd4a06fb566d58275e92f976166f2"} {"source_code": "main = interact solve\nsolve input = output where\n n = read (head $ lines input) :: Int\n animals = last $ lines input\n output = show $ ham - maxham\n ham = length $ filter (=='H') animals\n maxham = maximum $ numham $ animals ++ take (n-1) animals\n numham ['H'] = [1]\n numham ['T'] = [0]\n numham (x:xs)\n | length xs < ham && x == 'H' = z+1:ys\n | length xs < ham = z:ys\n | x == y = z:ys\n | x == 'H' && y == 'T' = z+1:ys\n | otherwise = z-1:ys\n where\n y = xs!!(ham-1)\n ys = numham xs\n z = head ys", "positive_code": [{"source_code": "solve :: (Int, String) -> Int\nsolve (n, s) = total_tigers - max_grouped_t_count\n where t_count = length . filter (=='T')\n max_grouped_t_count = maximum $ map (t_count . substring) [1..n]\n substring start = take total_tigers $ drop start $ cycle s\n total_tigers = t_count s\n\nparse :: String -> (Int, String)\nparse input = (read n, s)\n where [n, s] = lines input\n\nmain = interact (show . solve . parse)"}], "negative_code": [{"source_code": "\nsolve :: (Int, String) -> Int\nsolve (n, s) = total_tigers - max_grouped_t_count\n where t_count = length . filter (=='T')\n max_grouped_t_count = maximum $ map (t_count . substring) [1..total_tigers]\n substring start = take total_tigers $ drop start $ cycle s\n total_tigers = t_count s\n\nparse :: String -> (Int, String)\nparse input = (read n, s)\n where [n, s] = lines input\n\nmain = interact (show . solve . parse)"}], "src_uid": "0fce263a9606fbfc3ec912894ab1a8f8"} {"source_code": "\nimport List (group)\nimport Monad (liftM)\n\nparse :: String -> (Int, Int)\nparse line = case words line of\n [s1, s2] -> (read s1, read s2)\n\nsolve :: [(Int, Int)] -> Int\nsolve = maximum . map length . group\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- liftM (take n . map parse . lines) getContents\n print $ solve $ as", "positive_code": [{"source_code": "import Data.List\nmain=interact$show.maximum.map length.group.lines\n"}, {"source_code": "\nmain = do\n n<-getLine\n rest<-getContents\n let dat=((map (map read.words)).lines) rest\n putStrLn $ show $ solve dat (-1)\n\nsolve::[[Int]]->Int->Int\nsolve [] maxhumans = maxhumans\nsolve ([a,b]:cs) maxhumans = if taken >maxhumans then solve droped (taken) else solve droped maxhumans\n where taken =length ( takeWhile ([a,b]==) ([a,b]:cs))\n droped = dropWhile ([a,b]==) cs"}, {"source_code": "import Control.Applicative\nimport qualified Data.List as L\n\ntest x = maximum $ map length $ L.group x\n\nmain = do\n times <- tail . lines <$> getContents\n let result = test times\n print result \n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n ps <- fmap (map (words) . lines) getContents\n\n print $ maximum $ map length $ group $ sort ps\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Map as M\n\ncountMap_ :: Integer -> M.Map Integer Integer -> M.Map Integer Integer\ncountMap_ = M.alter (\\y -> fmap succ y `mplus` Just 1)\n\ncountMap :: [Integer] -> M.Map Integer Integer\ncountMap = foldr countMap_ M.empty\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n ts <- replicateM n $ do\n [h, m] <- fmap (map read . words) getLine\n return $ 60 * h + m\n print $ M.foldl' max 0 $ countMap ts\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do n <- getLine >>= return . read\n l <- sequence $ replicate n (getLine >>= return . map read . words)\n putStrLn . show $ solve l\n\nsolve :: [[Int]] -> Int\nsolve = maximum. map length . group . sort \n"}, {"source_code": "main = do\n contents <- getContents\n putStrLn $ (\\(a,s) -> show a) $ foldr1 max $ f (tail $ lines contents) \"\" 0\n \nf :: [String] -> String -> Int -> [(Int, String)]\nf [] curS curC = [(curC, curS)]\nf s curS curC\n | curS == head s = f (tail s) curS (curC+1)\n | otherwise = (curC, curS) : f (tail s) (head s) 1\n"}, {"source_code": "import Data.List\nmain = do\n contents <- getContents\n putStrLn $ show $ foldr1 max $ map length $ group $ tail $ lines contents"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> (solve =<< forM [1..read n] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))\nsolve xs = print $ maximum $ map length $ group xs"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- liftM (\\x -> read x :: Int) getLine \n ts <- replicateM n getLine\n print $ maximum $ map length $ group ts\n"}, {"source_code": "import Control.Applicative\nimport Data.Map.Strict (fromListWith, toList)\n\nparse :: String -> [((Int,Int),Int)]\nparse = \n toList . fromListWith (+) . map (toTup . words) . lines\n where toTup [x,y] = ((read x, read y),1)\n\nmain = do\n _ <- getLine\n xs <- parse <$> getContents\n print . maximum . map snd $ xs"}, {"source_code": "import Control.Applicative\nimport Data.List (group)\n\nparse :: String -> [(Int,Int)]\nparse = map (toTup . words) . lines\n where toTup [x,y] = (read x, read y)\n\nmain = do\n _ <- getLine\n xs <- parse <$> getContents\n print . maximum . map length . group $ xs"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Control.Monad\n\n\n\n\nmain=do\n getLine\n a<-map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]\n print $ maximum $ map length $ group $ sort $ map (\\[x,y]->x*60+y) a\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = getContents >>= print . maximum . map length . group . sort . tail . lines\n"}, {"source_code": "import Data.List (group)\nmain = print . maximum . map length . group . tail . lines =<< getContents"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n n <- getLine\n times <- forM [1..read n] (\\_ -> do\n s <- getLine\n let [h, m] = map read . words $ s\n return (h, m) )\n print $ solve times\n\nsolve :: [(Int,Int)] -> Int\nsolve = maximum . map length . group\n"}, {"source_code": "import Data.List\nimport Data.Ord\nmain=interact$show.length.maximumBy(comparing length).group.f.map read.tail.words\nf :: [Int] -> [(Int,Int)]\nf(x:y:z)=(x,y):f z\nf _=[]"}, {"source_code": "import List\nmain=interact$show.maximum.map length.group.lines"}, {"source_code": "import System.IO\nimport Data.List\nsolve c = show (maximum (map (length) (group [(x,y) | x:y:[] <- [[read t :: Int | t <- words l] | l <- tail c]])))\n\nmain = do \n c <- hGetContents stdin\n putStrLn (solve (lines c))"}, {"source_code": "import Data.List\n\nmain = interact $ show . func . tup . tail . words\n\ntup (x:y:xs) = (x,y):tup(xs)\ntup _ = []\n\nfunc = maximum . map length . group"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \n\nmain=do\n\t\n\tn<- read <$> getLine::IO Int\n\tq<- map (map read) . map words. lines <$> getContents::IO [[Int]]\n\tlet q1 = map (\\z-> (head z)*60 + (last z)) q\n\tprint $ maximum $ map length $ group $sort q1"}, {"source_code": "{-\nA. Free Cash\n=============\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nValera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.\n\nValera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.\n\nHelp Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.\n\nInput\n------\nThe first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), that is the number of cafe visitors.\n\nEach of the following n lines has two space-separated integers hi and mi (0\u2009\u2264\u2009hi\u2009\u2264\u200923; 0\u2009\u2264\u2009mi\u2009\u2264\u200959), representing the time when the i-th person comes into the cafe.\n\nNote that the time is given in the chronological order. All time is given within one 24-hour period.\n\nOutput\n------\nPrint a single integer \u2014 the minimum number of cashes, needed to serve all clients next day.\n\nSample test(s)\n---------------\ninput\n4\n8 0\n8 10\n8 10\n8 45\noutput\n2\n\ninput\n3\n0 12\n10 11\n22 22\noutput\n1\n\nNote\n------\nIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.\n\nIn the second sample all visitors will come in different times, so it will be enough one cash.\n\n-}\nimport Data.List (group)\n\nminimumCashes :: [(Int, Int)] -> Int\nminimumCashes = (maximum . map length . group)\n\nreader :: String -> [(Int, Int)]\nreader s = [(hh, mm) | [hh, mm] <- yss]\n where _ : xss = lines s\n yss = map (map read . words) xss \n\nmain = do \n input <- getContents\n let xxs = reader input\n print $ minimumCashes xxs\n\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = getLine >>= flip replicateM getLine.read >>= putStrLn.show.maximum.map length.group\n"}, {"source_code": "-- Codeforces Round #147 (Div. 2)\n-- A. Free Cash\nimport Data.Char\nimport Data.List\n\nrepeat' :: [Int] -> Int -> Int -> Int\nrepeat' [] _ n = n\nrepeat' a@(x:xs) c n | x == c = repeat' xs c (n+1)\n | x /= c = maximum [n, repeat' a x 0]\n\nencode' :: [[Int]] -> [Int]\nencode' [] = []\nencode' ((x1 : x2 : xs): ys) = x1*60 + x2 : encode' ys\n\nmain :: IO()\nmain = do\n s <- getContents\n let inp = map (map $ \\x -> read x :: Int) $ map words $ lines s\n code = encode' $ tail inp\n out = repeat' code (-1) 0\n print out"}, {"source_code": "-- Codeforces Round #147 (Div. 2)\n-- A. Free Cash\nimport Data.Char\nimport Data.List\n\nrepeat' :: [Int] -> Int -> Int -> Int\nrepeat' [] _ n = n\nrepeat' a@(x:xs) c n | x == c = repeat' xs c (n+1)\n | x /= c = maximum [n, repeat' a x 0]\n\nencode' :: [[Int]] -> [Int]\nencode' [] = []\nencode' ((x1 : x2 : xs): ys) = x1*60 + x2 : encode' ys\n\nmain :: IO()\nmain = do\n s <- getContents\n let inp = map (map $ \\x -> read x :: Int) $ map words $ lines s\n code = sort $ encode' $ tail inp\n out = repeat' code (-1) 0\n print out"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nmain = do\n n <- read <$> getLine\n ps <- replicateM n ((map read . words) <$> getLine) :: IO [[Int]]\n let ans = maximum . map length . group $ ps\n print ans"}, {"source_code": "import Data.List\nmain = interact $ show.maximum.map length.group.map (words).tail.lines\n"}], "negative_code": [{"source_code": "\nmain = do\n n<-getLine\n rest<-getContents\n let dat=((map (map read.words)).lines) rest\n putStrLn $ show $ solve dat 1\n\nsolve::[[Int]]->Int->Int\nsolve [] maxhumans = maxhumans\nsolve ([a,b]:cs) maxhumans = if taken >maxhumans then solve droped (taken+1) else solve droped maxhumans\n where taken =length ( takeWhile ([a,b]==) cs)\n droped = dropWhile ([a,b]==) cs"}], "src_uid": "cfad2cb472e662e037f3415a84daca57"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (Monad, mapM_, replicateM)\nimport Data.Array.IArray (IArray, Array, (!), listArray)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n{- State ----------------------------------------------------------------------}\n\ndata State s a = State { runState :: s -> (a, s) }\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a, s') = runState m s\n in runState (f a) s'\n\n{- Tokenizer ------------------------------------------------------------------}\n\ntype Tokenizer = State [BS.ByteString]\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n \nreadInteger :: BS.ByteString -> Integer\nreadInteger s = case BS.readInteger s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Integer\"\n\nnextInt :: Tokenizer Int\nnextInt = State $ \\(x:xs) -> (readInt x, xs)\n\nnextInteger :: Tokenizer Integer\nnextInteger = State $ \\(x:xs) -> (readInteger x, xs)\n\nrunTokenizer :: BS.ByteString -> Tokenizer a -> a\nrunTokenizer s t = fst $ runState t (BS.words s)\n\n{- Main -----------------------------------------------------------------------}\n\nmain = do\n contents <- BS.getContents\n let result = runTokenizer contents $ do\n n <- nextInt\n a <- replicateM n nextInteger\n let ar = listArray (0, n) $ scanl max 0 a :: Array Int Integer\n m <- nextInt\n queries <- replicateM m $ do\n w <- nextInt\n h <- nextInteger\n return (w, h)\n let hs = scanl (\\v (w, h) -> h + (max v (ar ! w))) (head a) queries\n return $ map (\\(v, (w, h)) -> max v (ar ! w)) (zip hs queries)\n mapM_ print result\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Int\nimport Data.List\n\ndata B = B !Int !Int\n\nmain = mapM_ print . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n p64\n m <- poi\n bs <- replicateM m $ liftM2 B poi poi\n return $ solve n xs bs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n p64 = fmap (to64 . int) pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs bs = snd $ mapAccumL (\\t (B w h) -> let s = Seg 0 w; r = queryT s t in (updateT s (r + to64 h) t, r)) (fromList n xs) bs\n\nto64 x = fromIntegral x :: Int64\n\ndata Seg = Seg !Int !Int deriving Show\ndata SegNode a = SegBranch !Bool !a (SegNode a) (SegNode a) | SegNull deriving Show\ndata SegTree a = SegTree !Seg !(SegNode a) deriving Show\n\nfromList n xs = foldl' (\\t (i, x) -> updateT (Seg i $ i + 1) x t) (SegTree s $ make 0 s) (zip [0..] xs)\n where s = Seg 0 n\n\nupdateT us ux (SegTree s r) = SegTree s $ update us ux s r\nqueryT qs (SegTree s r) = query qs s r\n\nsegValue (SegBranch _ x _ _) = x\nsegValue SegNull = 0\n\nmake !x !s\n | slength s <= 1 = SegBranch False x SegNull SegNull\n | otherwise = SegBranch False x (make x l) (make x r)\n where (l, r) = ssplit s\n\nupdate _ _ _ SegNull = SegNull\nupdate us ux s t@(SegBranch _ _ l r)\n | s `sinside` us = make ux s\n | s `soutside` us = t\n | otherwise = SegBranch False (segValue l' `max` segValue r') l' r'\n where\n (sl, sr) = ssplit s\n l' = update us ux sl l\n r' = update us ux sr r\n\nquery _ _ SegNull = 0\nquery qs s (SegBranch f x l r)\n | s `soutside` qs = 0\n | f || s `sinside` qs = x\n | otherwise = query qs ls l `max` query qs rs r\n where (ls, rs) = ssplit s\n\ninside x (Seg b e) = b <= x && x < e\nsinside (Seg b1 e1) (Seg b2 e2) = b2 <= b1 && e1 <= e2\nsoutside (Seg b1 e1) (Seg b2 e2) = e1 <= b2 || e2 <= b1\nslength (Seg b e) = e - b\nssplit (Seg b e) = (Seg b m, Seg m e)\n where m = b + (e - b) `quot` 2"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Int\nimport Data.List\n\ndata B = B !Int !Int\n\nmain = mapM_ print . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n p64\n m <- poi\n bs <- replicateM m $ liftM2 B poi poi\n return $ solve n xs bs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n p64 = fmap (to64 . int) pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs bs = snd $ mapAccumL (\\t (B w h) -> let s = Seg 0 w; r = queryT s t in (updateT s (r + to64 h) t, r)) (fromList n xs) bs\n\nto64 x = fromIntegral x :: Int64\n\ndata Seg = Seg !Int !Int deriving Show\ndata SegNode a = SegBranch !Bool !a (SegNode a) (SegNode a) | SegNull deriving Show\ndata SegTree a = SegTree !Seg !(SegNode a) deriving Show\n\nfromList n xs = foldl' (\\t (i, x) -> updateT (Seg i $ i + 1) x t) (SegTree s $ make 0 s) (zip [0..] xs)\n where s = Seg 0 n\n\nupdateT us ux (SegTree s r) = SegTree s $ update us ux s r\nqueryT qs (SegTree s r) = query qs s r\n\nsegValue (SegBranch _ x _ _) = x\nsegValue SegNull = 0\n\nmake !x !s\n | slength s <= 1 = SegBranch True x SegNull SegNull\n | otherwise = SegBranch True x (make x l) (make x r)\n where (l, r) = ssplit s\n\nupdate _ _ _ SegNull = SegNull\nupdate us ux s t@(SegBranch _ _ l r)\n | s `sinside` us = make ux s\n | s `soutside` us = t\n | otherwise = SegBranch False (segValue l' `max` segValue r') l' r'\n where\n (sl, sr) = ssplit s\n l' = update us ux sl l\n r' = update us ux sr r\n\nquery _ _ SegNull = 0\nquery qs s (SegBranch f x l r)\n | s `soutside` qs = 0\n | f || s `sinside` qs = x\n | otherwise = query qs ls l `max` query qs rs r\n where (ls, rs) = ssplit s\n\ninside x (Seg b e) = b <= x && x < e\nsinside (Seg b1 e1) (Seg b2 e2) = b2 <= b1 && e1 <= e2\nsoutside (Seg b1 e1) (Seg b2 e2) = e1 <= b2 || e2 <= b1\nslength (Seg b e) = e - b\nssplit (Seg b e) = (Seg b m, Seg m e)\n where m = b + (e - b) `quot` 2"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as L\n\n--import Control.Monad.State\nimport Data.Char (isSpace)\nimport Data.Maybe (fromJust)\n\nimport Data.Int (Int64)\nimport Data.List (foldl')\n\ntype Long=Int64\ndata SegmentTree = Null | Node !SegmentTree !SegmentTree !Long !Bool\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null 0 False\nbuild l r = Node left right 0 False\n where !left = build l m\n !right = build (m+1) r\n !m = (l+r) `div` 2\n\npaint :: SegmentTree -> Long -> SegmentTree\n{-# INLINE paint #-}\npaint (Node left right _ _) x = Node left right x True\n\nupdate::SegmentTree->Int->Int->Int->Int->Long->SegmentTree\n{-# INLINE update #-}\nupdate Null _ _ _ _ _ = Null\n\nupdate t@(Node _ _ _ _) l r begin end _ | r < begin || end < l = t\n\nupdate t l r begin end x | begin <= l && r<=end = paint t x\n\nupdate (Node left right val flag) l r begin end x = Node newLeft newRight newValue False\n where left' = if flag then paint left val else left\n right' = if flag then paint right val else right\n !newLeft = update left' l m begin end x\n !newRight = update right' (m+1) r begin end x\n !newValue = max newLeftValue newRightValue\n Node _ _ newLeftValue _ = newLeft\n Node _ _ newRightValue _ = newRight\n !m = (l+r) `div` 2\n\n\nquery::SegmentTree->Int->Int->Int->Int->Long\nquery Null _ _ _ _ = 0\nquery t l r begin end | r < begin || end < l = 0\nquery (Node _ _ value True) l r _ _ = value\nquery (Node _ _ value _) l r begin end | begin<=l && r<=end = value\nquery t@(Node left right val False) l r begin end = max (query left l m begin end) (query right (m+1) r begin end)\n where !m = (l+r) `div` 2\n\n\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t n a = foldl' step t (zip [1..] a)\n where step t (p, x) = update t 1 n p p (fromIntegral x::Long)\n\nsolveAQuery::SegmentTree->Int->[(Int,Int)]->[Long]\nsolveAQuery _ _ [] = []\nsolveAQuery t n ((w,h):xs) = ans:solveAQuery newT n xs\n where !ans = query t 1 n 1 w\n !newT = update t 1 n 1 w (ans+(fromIntegral h::Long))\n\nsolve::Int->[Int]->[(Int,Int)]->[Long]\nsolve n a wh = solveAQuery (initTree (build 1 n) n a) n wh\n\nmain :: IO ()\nmain = do\n c <- L.getContents\n let ((n, a, wh), _) = runParser parseInput c\n mapM_ print $ solve n a wh\n\nparseInput :: Parser (Int, [Int], [(Int, Int)])\nparseInput = do\n n <- readInt\n a <- readInts n\n m <- readInt\n nums <- readInts (2*m)\n return (n, a, makeTuple nums)\n\n{-\ntype Parser = State L.ByteString\nrunParser :: Parser a -> L.ByteString -> (a, L.ByteString)\nrunParser = runState\n-}\n\n-- Implementation of State monad, because Codeforces doesn't have\n-- necessary libraries installed.\ndata Parser a = Parser {runParser :: L.ByteString -> (a, L.ByteString)}\ninstance Monad Parser where\n return x = Parser (\\c -> (x, c))\n mx >>= my = Parser f\n where f c = let (x, c') = runParser mx c\n (y, c'') = runParser (my x) c'\n in (y, c'')\n\nget :: Parser L.ByteString\nget = Parser (\\c -> (c, c))\n\nput :: L.ByteString -> Parser ()\nput c = Parser (\\_ -> ((), c))\n-- End of State monad\n\nskipSpace :: Parser ()\nskipSpace = do\n c <- get\n let (space, next) = L.span isSpace c\n put next\n\nreadInt :: Parser Int\nreadInt = do\n skipSpace\n c <- get\n let Just (n, rest) = L.readInt c\n put rest\n return n\n\nreadInts :: Int -> Parser [Int]\nreadInts count = mapM (const readInt) [1..count]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\nimport qualified Data.ByteString.Lazy.Char8 as L\n\n--import Control.Monad.State\nimport Data.Char (isSpace)\nimport Data.Maybe (fromJust)\n\nimport Data.Int (Int64)\nimport Data.List (foldl')\n\ntype Long=Int64\ndata SegmentTree = Null | Node !SegmentTree !SegmentTree !Long !Bool\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null 0 False\nbuild l r = Node left right 0 False\n where !left = build l m\n !right = build (m+1) r\n !m = (l+r) `div` 2\n\npaint :: SegmentTree -> Long -> SegmentTree\n{-# INLINE paint #-}\npaint (Node left right _ _) x = Node left right x True\n\nupdate::SegmentTree->Int->Int->Int->Int->Long->SegmentTree\n{-# INLINE update #-}\nupdate Null _ _ _ _ _ = Null\n\nupdate t@(Node _ _ _ _) l r begin end _ | r < begin || end < l = t\n\nupdate t l r begin end x | begin <= l && r<=end = paint t x\n\nupdate (Node left right val flag) l r begin end x = Node newLeft newRight newValue False\n where left' = if flag then paint left val else left\n right' = if flag then paint right val else right\n !newLeft = update left' l m begin end x\n !newRight = update right' (m+1) r begin end x\n !newValue = max newLeftValue newRightValue\n Node _ _ newLeftValue _ = newLeft\n Node _ _ newRightValue _ = newRight\n !m = (l+r) `div` 2\n\n\nquery::SegmentTree->Int->Int->Int->Int->Long\nquery Null _ _ _ _ = 0\nquery t l r begin end | r < begin || end < l = 0\nquery (Node _ _ value True) l r _ _ = value\nquery (Node _ _ value _) l r begin end | begin<=l && r<=end = value\nquery t@(Node left right val False) l r begin end = max (query left l m begin end) (query right (m+1) r begin end)\n where !m = (l+r) `div` 2\n\n\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t n a = foldl' step t (zip [1..] a)\n where step t (p, x) = update t 1 n p p (fromIntegral x::Long)\n\nsolveAQuery::SegmentTree->Int->[(Int,Int)]->[Long]\nsolveAQuery _ _ [] = []\nsolveAQuery t n ((w,h):xs) = ans:solveAQuery newT n xs\n where !ans = query t 1 n 1 w\n !newT = update t 1 n 1 w (ans+(fromIntegral h::Long))\n\nsolve::Int->[Int]->[(Int,Int)]->[Long]\nsolve n a wh = solveAQuery (initTree (build 1 n) n a) n wh\n\nmain :: IO ()\nmain = do\n c <- L.getContents\n let ((n, a, wh), _) = runParser parseInput c\n mapM_ print $ solve n a wh\n\nparseInput :: Parser (Int, [Int], [(Int, Int)])\nparseInput = do\n n <- readInt\n a <- readInts n\n m <- readInt\n nums <- readInts (2*m)\n return (n, a, makeTuple nums)\n\n{-\ntype Parser = State L.ByteString\nrunParser :: Parser a -> L.ByteString -> (a, L.ByteString)\nrunParser = runState\n-}\n\n-- Implementation of State monad, because Codeforces doesn't have\n-- necessary libraries installed.\ndata Parser a = Parser {runParser :: L.ByteString -> (a, L.ByteString)}\ninstance Monad Parser where\n return x = Parser (\\c -> (x, c))\n mx >>= my = Parser f\n where f c = let (x, c') = runParser mx c\n (y, c'') = runParser (my x) c'\n in (y, c'')\n\nget :: Parser L.ByteString\nget = Parser (\\c -> (c, c))\n\nput :: L.ByteString -> Parser ()\nput c = Parser (\\_ -> ((), c))\n-- End of State monad\n\nskipSpace :: Parser ()\nskipSpace = do\n c <- get\n let (space, next) = L.span isSpace c\n put next\n\nreadInt :: Parser Int\nreadInt = do\n skipSpace\n c <- get\n let Just (n, rest) = L.readInt c\n put rest\n return n\n\nreadInts :: Int -> Parser [Int]\nreadInts count = mapM (const readInt) [1..count]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain = do\n n <- readLn\n arr <- fmap(listArray(0,n).(0:).map readInt.B.words)B.getLine\n m <- readLn :: IO Int\n whs <- fmap(map readInt.B.words)B.getContents\n putStr.unlines.map show $ solve arr whs\n\nsolve :: UArray Int Int -> [Int] -> [Integer]\nsolve arr whs = go 0 whs\n where\n go !height (w:h:whs) = res : go (fromIntegral h+res) whs\n where\n !res = max (fromIntegral $ unsafeAt arr w) height\n go height _ = []"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft = update left begin end x\n newRight = update right begin end x\n newValue = max newLeftValue newRightValue\n (Node _ _ _ _ newLeftValue) = newLeft\n (Node _ _ _ _ newRightValue) = newRight\n\nquery::SegmentTree->Int->Int->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs\n\n\nsolveAQuery::SegmentTree->[(Int,Int)]->[Long]\nsolveAQuery _ [] = []\nsolveAQuery t ((w,h):xs) = ans:solveAQuery newT xs\n where ans = query t 1 w\n newT = update t 1 1 (ans+(fromIntegral h::Long))\n\nsolve::Int->[Int]->[(Int,Int)]->[Long]\nsolve n a = solveAQuery (initTree (build 1 n) 1 a)\n\nbuild'::SegmentTree\nbuild' = Node build' build' 1 1 1\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n putStr $ foldr (\\x y->show x ++ \"\\n\" ++ y) \"\" (solve n a wh)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Int \nimport Data.List\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = left --update left begin end x\n newRight = right --update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft = update left begin end x\n newRight = update right begin end x\n newValue = max newLeftValue newRightValue\n (Node _ _ _ _ newLeftValue) = newLeft\n (Node _ _ _ _ newRightValue) = newRight\n\nquery::SegmentTree->Int->Int->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs\n\n\nsolveAQuery::SegmentTree->[(Int,Int)]->[Long]\nsolveAQuery _ [] = []\nsolveAQuery t ((w,h):xs) = ans:solveAQuery newT xs\n where ans = query t 1 w\n newT = update t 1 w (ans+(fromIntegral h::Long))\n\nsolve::Int->[Int]->[(Int,Int)]->[Long]\nsolve n a = solveAQuery (initTree (build 1 n) 1 a)\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = (initTree (build 1 n) 1 a)\n putStr $ foldr (\\x y->show x ++ \"\\n\" ++ y) \"\" (solve n a wh)\n"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = update left begin end x\n newRight @ (Node _ _ _ _ newRightValue) = update right begin end x\n newValue = max newLeftValue newRightValue\n\nquery::SegmentTree->Int->Int->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs\n\nsolve::SegmentTree->[(Int,Int)]->IO()\nsolve _ [] = return ()\nsolve t ((w,h):xs) = do\n print ans\n solve newT xs\n where ans = query t 1 w\n newT = update t 1 w (ans+(fromIntegral h::Long))\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree (build 1 n) 1 a\n if n == 8701 then solve t (take 1600 wh) else solve t wh\n"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = update left begin end x\n newRight @ (Node _ _ _ _ newRightValue) = update right begin end x\n newValue = max newLeftValue newRightValue\n\nquery::SegmentTree->Int->Int->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs\n\nsolve::SegmentTree->[(Int,Int)]->IO()\nsolve _ [] = return ()\nsolve t ((w,h):xs) = do\n print ans\n solve newT xs\n where ans = query t 1 w\n newT = update t 1 w (ans+(fromIntegral h::Long))\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree (build 1 n) 1 a\n if n == 8701 then solve t (take 100 wh) else solve t wh\n"}, {"source_code": "module Main where\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Int\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Int->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft = update left begin end x\n newRight = update right begin end x\n newValue = max newLeftValue newRightValue\n (Node _ _ _ _ newLeftValue) = newLeft\n (Node _ _ _ _ newRightValue) = newRight\n\nquery::SegmentTree->Int->Int->Int\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple [] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t p [] = t\ninitTree t p (x:xs) = initTree (update t p p x) (p+1) xs\n\n\nsolveAQuery::SegmentTree->[(Int,Int)]->[Int]\nsolveAQuery _ [] = []\nsolveAQuery t ((w,h):xs) = ans:solveAQuery newT xs\n where ans = query t 1 w\n newT = update t 1 1 (ans+h)\n\nsolve::Int->[Int]->Int->[(Int,Int)]->[Int]\nsolve n a m wh = solveAQuery (initTree (build 1 n) 1 a) wh\n \n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n putStr $ foldr (\\x y->(show x) ++ \"\\n\" ++ y) \"\" (solve n a m wh)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (Monad, mapM_, replicateM)\nimport Data.Array.IArray (IArray, (!), listArray)\nimport Data.Array.Unboxed (UArray)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n{- State ----------------------------------------------------------------------}\n\ndata State s a = State { runState :: s -> (a, s) }\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a, s') = runState m s\n in runState (f a) s'\n\n{- Tokenizer ------------------------------------------------------------------}\n\ntype Tokenizer = State [BS.ByteString]\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n\nnextInt :: Tokenizer Int\nnextInt = State $ \\(x:xs) -> (readInt x, xs)\n\nrunTokenizer :: BS.ByteString -> Tokenizer a -> a\nrunTokenizer s t = fst $ runState t (BS.words s)\n\n{- Main -----------------------------------------------------------------------}\n\nmain = do\n contents <- BS.getContents\n let result = runTokenizer contents $ do\n n <- nextInt\n a <- replicateM n nextInt\n let ar = listArray (0, n) $ scanl max 0 a :: UArray Int Int\n m <- nextInt\n queries <- replicateM m $ do\n w <- nextInt\n h <- nextInt\n return (w, h)\n let hs = scanl (\\v (w, h) -> h + (max v (ar ! w))) (head a) queries\n return $ map (\\(v, (w, h)) -> max v (ar ! w)) (zip hs queries)\n mapM_ print result\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main where\n\nimport Data.Int(Int64)\nimport Data.List(foldl')\nimport System.IO\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l == r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::Int->Int->Long->SegmentTree->SegmentTree\nupdate begin end x t = nt\n where !nt = update' t\n update' Null = Null\n update' t @ (Node _ _ l r _) | r < begin || end < l = t\n update' (Node left right l r _) | begin <= l && r <= end = Node newLeft newRight l r x\n where newLeft = update' left\n newRight = update' right\n update' (Node left right l r _) = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = update' left\n newRight @ (Node _ _ _ _ newRightValue) = update' right\n newValue = max newLeftValue newRightValue\n\nquery::Int->Int->SegmentTree->Long\nquery begin end = query'\n where query' Null = 0\n query' (Node _ _ l r _) | r < begin || end < l = 0\n query' (Node _ _ l r value) | begin <= l && r <= end = value\n query' (Node left right _ _ _) = max (query' left) (query' right)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\nmain::IO()\nmain = do\n --hi <- openFile \"e:\\\\in.txt\" ReadMode\n input <- getContents--hGetContents hi\n --ho <- openFile \"e:\\\\out.txt\" WriteMode\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t0 = foldl' (\\t (i,ai) -> update i i (fromIntegral ai::Long) t) (build 1 n) (zip [1..n] a)\n solve::SegmentTree->[(Int,Int)]->IO()\n solve _ [] = return ()\n solve t ((w,h):xs) = do\n print ans--hPrint ho ans\n solve nt xs\n where ans = if xs == [] then query 1 w t else 0\n nt = update 1 w (ans+(fromIntegral h::Long)) t\n solve t0 wh"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = update left begin end x\n newRight @ (Node _ _ _ _ newRightValue) = update right begin end x\n newValue = max newLeftValue newRightValue\n\nquery::SegmentTree->Int->Int->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs\n\nsolve::SegmentTree->[(Int,Int)]->IO()\nsolve _ [] = return ()\nsolve t ((w,h):xs) = do\n print ans\n solve newT xs\n where ans = query t 1 w\n newT = update t 1 w (ans+(fromIntegral h::Long))\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree (build 1 n) 1 a\n if n >= 8701 then return () else solve t wh\n"}, {"source_code": "{-#LANGUAGE BangPatterns#-}\nmodule Main where\n\nimport Data.Int\nimport Data.Time\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree !Int !Int !Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l == r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m + 1) r\n m = (l + r) `div` 2\n\nupdate::Int->Int->Long->SegmentTree->SegmentTree\nupdate begin end x = update'\n where update' Null = Null\n update' t @ (Node _ _ l r _) | r < begin || end < l = t\n update' (Node !left !right l r _) | begin <= l && r <= end = Node newLeft newRight l r x\n where newLeft = update' left\n newRight = update' right\n update' (Node !left @ (Node _ _ ll lr _) !right @ (Node _ _ rl rr _) l r _) = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = if check begin end ll lr then update' left else left\n newRight @ (Node _ _ _ _ newRightValue) = if check begin end rl rr then update' right else right\n newValue = max newLeftValue newRightValue\n check b e l r = not (rInt->SegmentTree->Long\nquery begin end = query'\n where query' Null = 0\n query' (Node _ _ l r _) | r < begin || end < l = 0\n query' (Node _ _ l r value) | begin <= l && r <= end = value\n query' (Node left right _ _ _) = max (query' left) (query' right)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree 1 a $ build 1 n\n testList x | x>1 = (sum y) : y where y = testList (x-1)\n testList 1 = [1]\n test = testList 1000\n a <- getCurrentTime\n print $ head test\n b <- getCurrentTime\n print $ head test\n c <- getCurrentTime\n print $ diffUTCTime b a\n print $ diffUTCTime c b\n solve t wh\n where initTree::Int->[Int]->SegmentTree->SegmentTree\n initTree _ [] t = t\n initTree p (x:xs) t = initTree (p+1) xs $ update p p (fromIntegral x::Long) t\n\n solve::SegmentTree->[(Int,Int)]->IO()\n solve _ [] = return ()\n solve t ((w,h):xs) = do\n print ans\n solve nt xs\n where ans = query 1 w t\n nt = update 1 w (ans+(fromIntegral h::Long)) t\n\n"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Long Long Long\n\nbuild::Long->Long->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Long->Long->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft = update left begin end x\n newRight = update right begin end x\n newValue = max newLeftValue newRightValue\n (Node _ _ _ _ newLeftValue) = newLeft\n (Node _ _ _ _ newRightValue) = newRight\n\nquery::SegmentTree->Long->Long->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Long]->[(Long,Long)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Long->[Long]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p x) (p+1) xs\n\n\nsolveAQuery::SegmentTree->[(Long,Long)]->[Char]\nsolveAQuery _ [] = []\nsolveAQuery t ((w,h):xs) = (show ans) ++ \"\\n\" ++ (solveAQuery newT xs)\n where ans = query t 1 1\n newT = update t 1 1 (ans+h)\n\nsolve::Long->[Long]->[(Long,Long)]->[Char]\nsolve n a wh = solveAQuery (initTree (build 1 n) 1 a) wh\n\nbuild'::SegmentTree\nbuild' = Node build' build' 1 1 1\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Long]\n a = take (fromIntegral n::Int) number0\n (m:number1) = drop (fromIntegral n::Int) number0\n wh = take (fromIntegral m::Int) (makeTuple number1)\n putStr (solve n a wh)\n"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::Int->Int->Long->SegmentTree->SegmentTree\nupdate begin end x = update'\n where update' Null =Null\n update' t @ (Node _ _ l r _) | r < begin || end < l = t\n update' (Node left right l r _) | begin <= l && r<=end = let\n newLeft = update' left\n newRight = update' right\n in Node newLeft newRight l r x\n update' (Node left right l r _) = let \n newLeft @ (Node _ _ _ _ newLeftValue) = update' left\n newRight @ (Node _ _ _ _ newRightValue) = right -- update' right\n newValue = max newLeftValue newRightValue\n in Node newLeft newRight l r newValue\n\nquery::Int->Int->SegmentTree->Long\nquery begin end = query'\n where query' Null = 0\n query' (Node _ _ l r _) | r < begin || end < l = 0\n query' (Node _ _ l r value) | begin <= l && r <= end = value \n query' (Node left right _ _ _) = max (query' left) (query' right)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree 1 a $ build 1 n\n solve t wh\n where initTree::Int->[Int]->SegmentTree->SegmentTree\n initTree _ [] t = t\n initTree p (x:xs) t = initTree (p+1) xs $ update p p (fromIntegral x::Long) t\n\n solve::SegmentTree->[(Int,Int)]->IO()\n solve _ [] = return ()\n solve t ((w,h):xs) = do\n print ans\n solve nt xs\n where ans = query 1 w t\n nt = update 1 w (ans+(fromIntegral h::Long)) t\n"}, {"source_code": "module Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree Int Int Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l==r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m+1) r\n m = (l+r) `div` 2\n\nupdate::SegmentTree->Int->Int->Long->SegmentTree\nupdate Null _ _ _ = Null\nupdate (Node left right l r value) begin end _ | r < begin || end < l = Node left right l r value\nupdate (Node left right l r _) begin end x | begin <= l && r<=end = Node newLeft newRight l r x\n where newLeft = update left begin end x\n newRight = update right begin end x\nupdate (Node left right l r _) begin end x = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = update left begin end x\n newRight @ (Node _ _ _ _ newRightValue) = update right begin end x\n newValue = max newLeftValue newRightValue\n\nquery::SegmentTree->Int->Int->Long\nquery Null _ _ = 0\nquery (Node _ _ l r _) begin end | r < begin || end < l = 0 \nquery (Node _ _ l r value) begin end | begin<=l && r<=end = value \nquery (Node left right _ _ _) begin end = max (query left begin end) (query right begin end)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\ninitTree::SegmentTree->Int->[Int]->SegmentTree\ninitTree t _ [] = t\ninitTree t p (x:xs) = initTree (update t p p (fromIntegral x::Long)) (p+1) xs\n\nsolve::SegmentTree->[(Int,Int)]->IO()\nsolve _ [] = return ()\nsolve t ((w,h):xs) = do\n print ans\n solve newT xs\n where ans = query t 1 w\n newT = update t 1 w (ans+(fromIntegral h::Long))\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree (build 1 n) 1 a\n if n == 8701 then solve t (take 1000 wh) else solve t wh\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\nmodule Main where\n\nimport Data.Int\n\ntype Long=Int64\ndata SegmentTree = Null | Node SegmentTree SegmentTree !Int !Int !Long\n\nbuild::Int->Int->SegmentTree\nbuild l r | l == r = Node Null Null l r 0\nbuild l r = Node left right l r 0\n where left = build l m\n right = build (m + 1) r\n m = (l + r) `div` 2\n\nupdate::Int->Int->Long->SegmentTree->SegmentTree\nupdate begin end x = update'\n where update' Null = Null\n update' t @ (Node _ _ l r _) | r < begin || end < l = t\n update' (Node !left !right l r _) | begin <= l && r <= end = Node newLeft newRight l r x\n where newLeft = update' left\n newRight = update' right\n update' (Node !left !right l r _) = Node newLeft newRight l r newValue\n where newLeft @ (Node _ _ _ _ newLeftValue) = update' left\n newRight @ (Node _ _ _ _ newRightValue) = update' right\n newValue = max newLeftValue newRightValue\n\nquery::Int->Int->SegmentTree->Long\nquery begin end = query'\n where query' Null = 0\n query' (Node _ _ l r _) | r < begin || end < l = 0\n query' (Node _ _ l r value) | begin <= l && r <= end = value\n query' (Node left right _ _ _) = max (query' left) (query' right)\n\nmakeTuple::[Int]->[(Int,Int)]\nmakeTuple [ ] = []\nmakeTuple [_] = []\nmakeTuple (a:b:c) = (a,b) : makeTuple c\n\nmain::IO()\nmain = do\n input <- getContents\n let\n (n:number0) = map read (words input)::[Int]\n a = take n number0\n (m:number1) = drop n number0\n wh = take m (makeTuple number1)\n t = initTree 1 a $ build 1 n\n if n==8701 then solve t (take 1000 wh) else solve t wh\n where initTree::Int->[Int]->SegmentTree->SegmentTree\n initTree _ [] t = t\n initTree p (x:xs) t = initTree (p+1) xs $ update p p (fromIntegral x::Long) t\n\n solve::SegmentTree->[(Int,Int)]->IO()\n solve _ [] = return ()\n solve t ((w,h):xs) = do\n print ans\n solve nt xs\n where ans = query 1 w t\n nt = update 1 w (ans+(fromIntegral h::Long)) t\n"}], "src_uid": "fb0e6a573daa0ee7c20d20b0d2b83756"} {"source_code": "main = do\n a <- getLine\n b <- getLine\n putStrLn $ solve a b\n\nsolve a b = if ham `mod` 2 == 0 then avg a b True else \"impossible\"\n where ham = (length $ filter (==True) $ zipWith (/=) a b)\n\navg [] _ _ = \"\"\navg (a:as) (b:bs) True = a:avg as bs (a==b)\navg (a:as) (b:bs) False\n | a==b = a:avg as bs False\n | otherwise = b:avg as bs True\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (mapAccumL)\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nmain :: IO ()\nmain = putStrLn <$> fromMaybe \"impossible\" =<< solve <$> getLine <*> getLine\n\nsolve :: String -> String -> Maybe String\nsolve xs ys = listToMaybe [ snd $ mapAccumL (\\z (x, y) -> (z + fromEnum (x /= y), [ x, y ] !! fromEnum (odd z))) 0 $ zip xs ys | even $ length $ filter id $ zipWith (/=) xs ys ]\n"}, {"source_code": "main = do\n s1 <- getLine\n s2 <- getLine\n putStrLn $ solve s1 s2 \"\" 0\n\nsolve [] [] s n | even n = reverse s\n | odd n = \"impossible\"\n \nsolve (x:xs) (y:ys) s n | x == y = solve xs ys (x:s) n\n | even n = solve xs ys (x:s) (n+1)\n | odd n = solve xs ys (y:s) (n+1)\n "}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\nimport Data.Char\n \n \n\nprocess 0 _ k = k\nprocess n xy j = process (n-1) (tail (dropWhile (\\z-> fst z == snd z) xy)) (j+ 1+ length (takeWhile (\\z-> fst z == snd z) xy))\n\n\nmain= do\n\tx<-getLine\n\ty<-getLine\n\tlet xy= zip x y\n\tlet d = length $ filter (\\z-> fst z /= snd z) xy\n\tlet n = div d 2\n\tlet n1= process n xy 0\n\tputStrLn $ if odd d then \"impossible\" else (take n1 x) ++ (drop n1 y)\n\t\n\t"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/B\n\nimport Control.Monad (replicateM)\n\n-- This is a greedy problem\n-- Implemting an algorithm to find the correct P\n-- would take too much time.\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tp = findP s t\n\n\tcase p of\n\t\tNothing -> putStrLn \"impossible\"\n\t\tJust str -> putStrLn str\n\nhammingDistance :: String -> String -> Maybe Int\nhammingDistance xs ys\n\t| length xs /= length ys = Nothing\n\t| otherwise = Just $ hammingDistance' xs ys\n\twhere\n\t\thammingDistance' :: String -> String -> Int\n\t\thammingDistance' [] [] = 0\n\t\thammingDistance' (x:xs) (y:ys)\n\t\t\t| x == y = hammingDistance' xs ys\n\t\t\t| otherwise = 1 + hammingDistance' xs ys\n\nfindP :: String -> String -> Maybe String\nfindP a b\n\t| length a /= length b || (odd dis_a_b) = Nothing\n\t| otherwise = Just $ findP' a b 0\n\twhere\n\t\tJust dis_a_b = hammingDistance a b\n\t\tfindP' :: String -> String -> Int -> String\n\t\tfindP' (x:xs) (y:ys) changed\n\t\t\t| changed >= dis_a_b `quot` 2 = y : ys\n\t\t\t| x /= y = x : findP' xs ys (changed + 1)\n\t\t\t| otherwise = x : findP' xs ys changed"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/B\n\nmain = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tp = findP s t\n\n\tcase p of\n\t\tNothing -> putStrLn \"impossible\"\n\t\tJust str -> putStrLn str\n\nhammingDistance :: String -> String -> Maybe Int\nhammingDistance xs ys\n\t| length xs /= length ys = Nothing\n\t| otherwise = Just $ hammingDistance' xs ys\n\twhere\n\t\thammingDistance' :: String -> String -> Int\n\t\thammingDistance' [] [] = 0\n\t\thammingDistance' (x:xs) (y:ys)\n\t\t\t| x == y = hammingDistance' xs ys\n\t\t\t| otherwise = 1 + hammingDistance' xs ys\n\nfindP :: String -> String -> Maybe String\nfindP a b\n\t| length a /= length b || (odd dis_a_b) = Nothing\n\t| otherwise = Just $ findP' a b 0\n\twhere\n\t\tJust dis_a_b = hammingDistance a b\n\t\tfindP' :: String -> String -> Int -> String\n\t\tfindP' (x:xs) (y:ys) changed\n\t\t\t| changed >= dis_a_b `quot` 2 = y : ys\n\t\t\t| x /= y = x : findP' xs ys (changed + 1)\n\t\t\t| otherwise = x : findP' xs ys changed"}, {"source_code": "distance w0 w1 | null w0 = 0\n | (head w0) == (head w1) = distance (tail w0) (tail w1)\n | otherwise = 1 + (distance (tail w0) (tail w1))\ngetS w0 w1 d | d == 0 = w0\n | (head w0) == (head w1) = (head w0):(getS (tail w0) (tail w1) d)\n | otherwise = (head w1):(getS (tail w0) (tail w1) (d-1)) \nmain = do\n w0 <-getLine\n w1 <-getLine\n let d = distance w0 w1\n if (d `rem` 2) == 1\n then putStrLn \"impossible\"\n else putStrLn $ getS w0 w1 (d `div` 2)\n \n"}, {"source_code": "foo :: [(Char, Char)] -> Bool -> String\nfoo [] True = \"t\"\nfoo [] False = \"f\"\nfoo ((a,b):xs) f = if a==b then a:(foo xs f) else if f then a:(foo xs False) else b:(foo xs True)\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStr $ let res = foo (zip a b) True in if last res == 'f' then \"impossible\" else init res\n"}], "negative_code": [{"source_code": "-- http://codeforces.com/problemset/problem/545/B\n\nimport Control.Monad (replicateM)\n\n-- This is a greedy problem\n-- Implemting an algorithm to find the correct P\n-- would take too much time.\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tp = findP s t\n\n\tcase p of\n\t\tNothing -> putStrLn \"impossible\"\n\t\tJust str -> putStrLn str\n\nhammingDistance :: String -> String -> Maybe Int\nhammingDistance xs ys\n\t| length xs /= length ys = Nothing\n\t| otherwise = Just $ hammingDistance' xs ys\n\twhere\n\t\thammingDistance' :: String -> String -> Int\n\t\thammingDistance' [] [] = 0\n\t\thammingDistance' (x:xs) (y:ys)\n\t\t\t| x == y = hammingDistance' xs ys\n\t\t\t| otherwise = 1 + hammingDistance' xs ys\n\nfindP :: String -> String -> Maybe String\nfindP a b\n\t| length a /= length b || (odd dis_a_b) = Nothing\n\t| otherwise =\n\t\tlet p = findP' a b 0 in\n\t\t\tif hammingDistance a p == hammingDistance b p then\n\t\t\t\tJust p\n\t\t\telse\n\t\t\t\tNothing\n\twhere\n\t\tJust dis_a_b = hammingDistance a b\n\t\tn = length a\n\t\thalf = n `quot` 2\n\t\t\n\t\tnegate' :: Char -> Char\n\t\tnegate' '0' = '1'\n\t\tnegate' '1' = '0'\n\t\tnegate' _ = '0'\n\n\t\tfindP' :: String -> String -> Int -> String\n\t\tfindP' (x:xs) (y:ys) i\n\t\t\t| odd n && i == n - 1 = [y]\n\t\t\t| i == n - 1 = [y]\n\t\t\t| i < half = negate' x : findP' xs ys (i+1)\n\t\t\t| otherwise = negate' y : findP' xs ys (i+1)"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/B\n\nimport Control.Monad (replicateM)\n\n-- This is a greedy problem\n-- Implemting an algorithm to find the correct P\n-- would take too much time.\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tp = findP s t\n\n\tcase p of\n\t\tNothing -> putStrLn \"impossible\"\n\t\tJust str -> putStrLn str\n\nhammingDistance :: String -> String -> Maybe Int\nhammingDistance xs ys\n\t| length xs /= length ys = Nothing\n\t| otherwise = Just $ hammingDistance' xs ys\n\twhere\n\t\thammingDistance' :: String -> String -> Int\n\t\thammingDistance' [] [] = 0\n\t\thammingDistance' (x:xs) (y:ys)\n\t\t\t| x == y = hammingDistance' xs ys\n\t\t\t| otherwise = 1 + hammingDistance' xs ys\n\nfindP :: String -> String -> Maybe String\nfindP a b\n\t| length a /= length b || (odd dis_a_b) = Nothing\n\t| otherwise =\n\t\tlet p = findP' a b 0 in\n\t\t\tif hammingDistance a p == hammingDistance b p then\n\t\t\t\tJust p\n\t\t\telse\n\t\t\t\tNothing\n\twhere\n\t\tJust dis_a_b = hammingDistance a b\n\t\tn = length a\n\t\thalf = n `quot` 2\n\n\t\tfindP' :: String -> String -> Int -> String\n\t\tfindP' [] [] _ = []\n\t\tfindP' (x:xs) (y:ys) i\n\t\t\t| i < half && x /= y = y : findP' xs ys (i+1)\n\t\t\t| i < half = x : findP' xs ys (i+1)\n\t\t\t| otherwise = x:xs\t"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/B\n\nimport Control.Monad (replicateM)\n\n-- This is a greedy problem\n-- Implemting an algorithm to find the correct P\n-- would take too much time.\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tp = findP s t\n\n\tcase p of\n\t\tNothing -> putStrLn \"impossible\"\n\t\tJust str -> putStrLn str\n\nhammingDistance :: String -> String -> Maybe Int\nhammingDistance xs ys\n\t| length xs /= length ys = Nothing\n\t| otherwise = Just $ hammingDistance' xs ys\n\twhere\n\t\thammingDistance' :: String -> String -> Int\n\t\thammingDistance' [] [] = 0\n\t\thammingDistance' (x:xs) (y:ys)\n\t\t\t| x == y = hammingDistance' xs ys\n\t\t\t| otherwise = 1 + hammingDistance' xs ys\n\nfindP :: String -> String -> Maybe String\nfindP a b\n\t| length a /= length b || (odd dis_a_b) = Nothing\n\t| otherwise =\n\t\tlet p = findP' a b 0 in\n\t\t\tif hammingDistance a p == hammingDistance b p then\n\t\t\t\tJust p\n\t\t\telse\n\t\t\t\tNothing\n\twhere\n\t\tJust dis_a_b = hammingDistance a b\n\t\tn = length a\n\t\thalf = n `quot` 2\n\t\t\n\t\tnegate' :: Char -> Char\n\t\tnegate' '0' = '1'\n\t\tnegate' '1' = '0'\n\t\tnegate' _ = '0'\n\n\t\tfindP' :: String -> String -> Int -> String\n\t\tfindP' (x:xs) (y:ys) i\n\t\t\t| odd n && i == n - 1 = y:ys\n\t\t\t| i == n - 1 = [negate' y]\n\t\t\t| i < half = negate' x : findP' xs ys (i+1)\n\t\t\t| otherwise = negate' y : findP' xs ys (i+1)"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/B\n\nimport Control.Monad (replicateM)\n\n-- This is a greedy problem\n-- Implemting an algorithm to find the correct P\n-- would take too much time.\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\ts <- getLine\n\tt <- getLine\n\n\tlet\n\t\tp = findP s t\n\n\tcase p of\n\t\tNothing -> putStrLn \"impossible\"\n\t\tJust str -> putStrLn str\n\nhammingDistance :: String -> String -> Maybe Int\nhammingDistance xs ys\n\t| length xs /= length ys = Nothing\n\t| otherwise = Just $ hammingDistance' xs ys\n\twhere\n\t\thammingDistance' :: String -> String -> Int\n\t\thammingDistance' [] [] = 0\n\t\thammingDistance' (x:xs) (y:ys)\n\t\t\t| x == y = hammingDistance' xs ys\n\t\t\t| otherwise = 1 + hammingDistance' xs ys\n\nfindP :: String -> String -> Maybe String\nfindP a b\n\t| length a /= length b || (odd dis_a_b) = Nothing\n\t| otherwise =\n\t\tlet p = findP' a b 0 in\n\t\t\tif hammingDistance a p == hammingDistance b p then\n\t\t\t\tJust p\n\t\t\telse\n\t\t\t\tNothing\n\twhere\n\t\tJust dis_a_b = hammingDistance a b\n\t\tn = length a\n\t\thalf = n `quot` 2\n\t\t\n\t\tnegate' :: Char -> Char\n\t\tnegate' '0' = '1'\n\t\tnegate' '1' = '0'\n\t\tnegate' _ = '0'\n\n\t\tfindP' :: String -> String -> Int -> String\n\t\tfindP' [] [] _ = []\n\t\tfindP' (x:xs) (y:ys) i\n\t\t\t| i < half = negate' x : findP' xs ys (i+1)\n\t\t\t| otherwise = negate' y : findP' xs ys (i+1)"}, {"source_code": "distance w0 w1 | null w0 = 0\n | (head w0) == (head w1) = distance (tail w0) (tail w1)\n | otherwise = 1 + (distance (tail w0) (tail w1))\ngetS w0 w1 d | d == 0 = w0\n | (head w0) == (head w1) = (head w0):(getS (tail w0) (tail w1) (d-1))\n | otherwise = (head w1):(getS (tail w0) (tail w1) (d-1)) \nmain = do\n w0 <-getLine\n w1 <-getLine\n let d = distance w0 w1\n if (d `rem` 2) == 1\n then putStrLn \"impossible\"\n else putStrLn $ getS w0 w1 (d `div` 2)\n \n"}, {"source_code": "foo :: [(Char, Char)] -> Bool -> String\nfoo [] True = \"t\"\nfoo [] False = \"f\"\nfoo ((a,b):xs) f = if a==b then a:(foo xs f) else if f then a:(foo xs False) else b:(foo xs True)\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n print $ let res = foo (zip a b) True in if last res == 'f' then \"impossible\" else init res\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\nimport Data.Char\n \n\nprocess n 0 cs = n - (length cs)\nprocess n m (c:cs) | c=='1' = process n (m-1) cs\n | otherwise = process n m cs\n\n\nmain= do\n\tx<-getLine\n\ty<-getLine\n\tlet a = foldl' (\\acc z -> acc+acc + digitToInt z) 0 x \n\tlet b = foldl' (\\acc z -> acc+acc + digitToInt z) 0 y \n\tlet c= xor a b\n\tlet d = popCount c\n\tlet n = div d 2\n\tlet n1= process n n (show c)\n\tputStrLn $ if odd d then \"Impossible\" else (take n1 x) ++ (drop n1 y)\n\t\n\t"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\nimport Data.Char\n \n\nmain= do\n\tx<-getLine\n\ty<-getLine\n\tlet a = foldl' (\\acc z -> acc+acc + digitToInt z) 0 x \n\tlet b = foldl' (\\acc z -> acc+acc + digitToInt z) 0 y \n\tlet c= xor a b\n\tlet d = popCount c\n\tlet n = div (length x) 2\n\tputStrLn $ if odd d then \"IMPOSSIBLE\" else (take n x) ++ (drop n y)\n\t\n\t"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\nimport Data.Char\n \n\nmain= do\n\tx<-getLine\n\ty<-getLine\n\tlet a = foldl' (\\acc z -> acc+acc + digitToInt z) 0 x \n\tlet b = foldl' (\\acc z -> acc+acc + digitToInt z) 0 y \n\tlet c= xor a b\n\tlet d = popCount c\n\tlet n = div (length x) 2\n\tputStrLn $ if odd d then \"Impossible\" else (take n x) ++ (drop n y)\n\t\n\t"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\nimport Data.Char\n \n\nprocess n 0 cs = n - (length cs)\nprocess n m (c:cs) | c=='1' = process n (m-1) cs\n | otherwise = process n m cs\n\n\nmain= do\n\tx<-getLine\n\ty<-getLine\n\tlet a = foldl' (\\acc z -> acc+acc + digitToInt z) 0 x \n\tlet b = foldl' (\\acc z -> acc+acc + digitToInt z) 0 y \n\tlet c= xor a b\n\tlet d = popCount c\n\tlet n = div d 2\n\tlet n1= process d n (show c)\n\tputStrLn $ if odd d then \"Impossible\" else (take n1 x) ++ (drop n1 y)\n\t\n\t"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\nimport Data.Char\n \n\nprocess n 0 cs = n - (length cs)\nprocess n m (c:cs) | c=='1' = process n (m-1) cs\n | otherwise = process n m cs\n\n\nmain= do\n\tx<-getLine\n\ty<-getLine\n\tlet a = foldl' (\\acc z -> acc+acc + digitToInt z) 0 x \n\tlet b = foldl' (\\acc z -> acc+acc + digitToInt z) 0 y \n\tlet c= xor a b\n\tlet d = popCount c\n\tlet n = div d 2\n\tlet n1= process d n (show c)\n\tputStrLn $ if odd d then \"impossible\" else (take n1 x) ++ (drop n1 y)\n\t\n\t"}], "src_uid": "2df181f2d1f4063a22fd2fa2d47eef92"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List\n\nmyshow [] = \"\"\nmyshow (f:xs) =\n if ( xs == [] ) then\n show f\n else\n ( show f ) ++ \" \" ++ ( myshow xs )\n\nziplst [] = []\nziplst [a] = []\nziplst (a:b:bs) =\n (a, b):( ziplst bs )\n\nfixlst [] = []\nfixlst ((s, f):xs) = \n ((min s f), (max s f)):( fixlst xs )\n\ntake_max [] = 0\ntake_max [(s, f)] = f\ntake_max ((s, f):xs) =\n max f ( take_max xs )\n\nmycomp ( s1, f1 ) ( s2, f2 )\n | s1 < s2 = LT\n | s1 > s2 = GT\n | s1 == s2 = compare f2 f1\n\nmysort lst = sortBy mycomp lst\n\nputpin fmax fmin [] = [fmin]\nputpin fmax fmin ((s, f):xs) =\n if ( not ( fmin == fmax ) ) then \n if ( s <= fmin ) then\n putpin fmax ( min f fmin ) xs\n else\n fmin:( putpin fmax f xs )\n else\n putpin fmax f xs\n\nsolve :: Int -> Int -> [ ( Int, Int ) ] -> [ Int ]\nsolve fmax n lst = putpin fmax fmax lst\n\nmain = \n do n <- readLn\n str <- getContents\n let x = map read (words str)\n let inpt = ziplst x\n let proplst = mysort ( fixlst inpt )\n let fmax = ( take_max proplst + 1 )\n let res = solve fmax n proplst\n let outp = myshow res\n putStrLn ( show ( length res ) )\n putStrLn outp\n", "positive_code": [{"source_code": "import Data.List\n\ncmp :: (Int, Int) -> (Int, Int) -> Ordering\ncmp (a, b) (c, d) = compare b d\n\nprocess :: [Int] -> [(Int, Int)]\nprocess (a:b:c)\n\t| a <= b\t= (a, b) : (process c)\n\t| otherwise\t= (b, a) : (process c)\nprocess _ = []\n\ncontain :: Int -> (Int, Int) -> Bool\ncontain x (y, z) = x >= y && x <= z\n\ngetPts :: [(Int, Int)] -> [Int]\ngetPts (x:xs) = (snd x) : (getPts (takePts (snd x) xs))\ngetPts [] = []\n\ntakePts :: Int -> [(Int, Int)] -> [(Int, Int)]\ntakePts p (x:xs)\n\t| contain p x\t= takePts p xs\n\t| otherwise\t\t= x:xs\ntakePts _ _ = []\n\nprintList :: [Int] -> IO()\nprintList (a:b) = do\n\tputStr ((show a) ++ \" \")\n\tprintList b\nprintList _ = do\n\tputStr \"\\n\"\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet list = process (map read (tail (words str)))\n\tlet slist = sortBy cmp list\n\tlet ans = getPts slist\n\tputStrLn (show (length ans))\n\tprintList ans\n"}, {"source_code": "import qualified Data.List as DL\n\n-- with dropWhile\n\n-- assume already sorted\nfindNails segList = accum segList []\n where accum ([_,newNail]:segs) nails = accum (dropWhile (\\[begin,_] -> begin <= newNail) segs) $ newNail:nails\n accum [] nails = nails\n\nsortSegs segs = DL.sortBy (\\[_,e1] [_,e2] -> compare e1 e2) segs\n\ninput2segs allInput = map (\\line -> fixOrder $ map intRder (words line)) $ lines allInput\n where intRder str = read str :: Int\n fixOrder [a,b]\n | a <= b = [a,b]\n | otherwise = [b,a]\n\nsolve = findNails . sortSegs . input2segs\n\n-- ********** \n-- printing / output functions\n\nitemPrinter :: Show a => a -> IO () \nitemPrinter item = (putStr . show) item >> putChar ' '\n\nlengthPrinter :: [a] -> IO [a]\nlengthPrinter lst = print (length lst) >> (return lst)\n\n-- how do I print in required format?\nmain :: IO ()\nmain = getLine >> getContents >>= lengthPrinter . solve >>= mapM_ itemPrinter >> putStr \"\\n\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (foldl', sort, unwords)\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\npin [] (total, pins) curminend = (total + 1, curminend : pins) \npin ((start, end) : segs) sol@(total, pins) curminend\n | start > curminend = pin segs (total + 1, curminend : pins) end\n | end < curminend = pin segs sol end\n | otherwise = pin segs sol curminend\n \nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let ls = sort (readMany2TR readInt r1 [])\n let (tot, pins) = pin ls (0, []) maxend\n print tot\n putStrLn $ unwords $ map show pins\n where\n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany2TR readf s acc = case readf s of\n Just (x, r) -> case readf r of\n Just (y, r') -> readMany2TR readf r' (orient x y : acc)\n Nothing -> acc\n Nothing -> acc\n orient a b | a < b = (a, b)\n | otherwise = (b, a)\n maxend = 10001\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nmain = do\n n <- fmap read getLine\n a <- fmap (sort . map ( ( \\[l,r] -> (l,r)) . sort . map read . words)) (replicateM n getLine)\n let nails = solve a\n print (length nails)\n putStrLn . unwords . map show $ nails\n \nsolve :: [(Int, Int)] -> [Int]\nsolve a =\n let n = length a\n nails = array (0, n-1) [(i, f i) | i <- [0..n-1]]\n f k = case find (\\i -> nails!i >= l && nails!i <= r) [k+1..n-1] of\n Just i -> nails!i\n Nothing -> l\n where (l,r) = a!!k\n in nub (elems nails)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport List\n\nmyshow [] = \"\"\nmyshow (f:xs) =\n if ( xs == [] ) then\n show f\n else\n ( show f ) ++ \" \" ++ ( myshow xs )\n\nziplst [] = []\nziplst [a] = []\nziplst (a:b:bs) =\n (a, b):( ziplst bs )\n\nfixlst [] = []\nfixlst ((s, f):xs) = \n ((min s f), (max s f)):( fixlst xs )\n\ntake_max [] = 0\ntake_max [(s, f)] = f\ntake_max ((s, f):xs) =\n max f ( take_max xs )\n\nmycomp ( s1, f1 ) ( s2, f2 )\n | s1 < s2 = LT\n | s1 > s2 = GT\n | s1 == s2 = compare f2 f1\n\nmysort lst = sortBy mycomp lst\n\nputpin fmax fmin [] = [fmin]\nputpin fmax fmin ((s, f):xs) =\n if ( not ( fmin == fmax ) ) then \n if ( s <= fmin ) then\n putpin fmax ( min f fmin ) xs\n else\n fmin:( putpin fmax f xs )\n else\n putpin fmax f xs\n\nsolve :: Int -> Int -> [ ( Int, Int ) ] -> [ Int ]\nsolve fmax n lst = putpin fmax fmax lst\n\nmain = \n do n <- readLn\n str <- getContents\n let x = map read (words str)\n let inpt = ziplst x\n let proplst = mysort ( fixlst inpt )\n let fmax = ( take_max proplst + 1 )\n let res = solve fmax n proplst\n let outp = myshow res\n putStrLn ( show ( length res ) )\n putStrLn outp\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport List\n\nmyshow [] = \"\"\nmyshow (f:xs) =\n if ( xs == [] ) then\n show f\n else\n ( show f ) ++ \" \" ++ ( myshow xs )\n\nziplst [] = []\nziplst [a] = []\nziplst (a:b:bs) =\n (a, b):( ziplst bs )\n\nfixlst [] = []\nfixlst ((s, f):xs) = \n ((min s f), (max s f)):( fixlst xs )\n\nmycomp ( s1, f1 ) ( s2, f2 )\n | s1 < s2 = LT\n | s1 > s2 = GT\n | s1 == s2 = compare f2 f1\n\nmysort lst = sortBy mycomp lst\n\nputpin fmin [] = [fmin]\nputpin fmin ((s, f):xs) =\n if ( not ( fmin == -1 ) ) then \n if ( s <= fmin ) then\n putpin ( min f fmin ) xs\n else\n fmin:( putpin f xs )\n else\n putpin f xs\n\nsolve :: Int -> [ ( Int, Int ) ] -> [ Int ]\nsolve n lst = putpin (-1) lst\n\nmain = \n do n <- readLn\n str <- getContents\n let x = map read (words str)\n let inpt = ziplst x\n let proplst = mysort ( fixlst inpt )\n let res = solve n proplst\n let outp = myshow res\n putStrLn ( show ( length res ) )\n putStrLn outp\n"}], "src_uid": "60558a2148f7c9741bb310412f655ee4"} {"source_code": "import Data.List (intercalate)\nimport Control.Monad (replicateM_)\nmain = do\n n <- read <$> getLine :: IO Int\n solveProblem\n\nsolveProblem :: IO()\nsolveProblem = do\n xs <- getLine\n putStrLn $ intercalate \" \" $ replicate (oneAmount xs) \"1\" ++ replicate (zeroAmount xs) \"0\"\n where\n oneAmount = length . filter (== 'n')\n zeroAmount = length . filter (== 'z')\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nsolve' eo n zr = \n let ones = min n eo\n zeros = min (eo - ones) zr\n in intersperse ' ' $ replicate ones '1' ++ replicate zeros '0' ++ []\n\nvar xs x = let a = lookup x xs in if isJust a then fromJust a else 0\n\nsolve xs = \n let bs = map (\\x -> (head x, length x)) $ group $ sort xs\n [z,e,r,o,n] = map (var bs) \"zeron\" \n in solve' (min e o) n (min z r)\n \nmain = do\n getLine \n a <- getLine\n putStrLn $ solve a"}, {"source_code": "main = do\n getLine\n s <- getLine\n let n = length (filter (== 'n') s)\n z = length (filter (== 'z') s)\n putStrLn $ unwords $ replicate n \"1\" ++ replicate z \"0\"\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = interact (fmt . solve . head . tail . lines)\n\nf :: Char -> Maybe Int\nf 'z' = Just 0\nf 'n' = Just 1\nf _ = Nothing\n\nsolve :: String -> [Int]\nsolve = sortOn Down . mapMaybe f\n\nfmt :: [Int] -> String\nfmt = unwords . map show\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\t\n\nmain::IO ()\nmain=do\n \tt<- read <$> getLine ::IO Int\n\ts<-getLine\n\tlet lz = length $ filter(=='z') s\n\tlet ls =length s\n\tlet n1 = div (ls-4*lz) 3\n\tputStr $ concat $ replicate n1 \"1 \"\n\tputStrLn $ concat $ replicate lz \"0 \"\n\n"}, {"source_code": "--ghc 7.10\n\ncountOccurrence :: Char -> String -> Int\ncountOccurrence x = length . filter (==x)\n\nmaxNumber :: String -> [Int]\nmaxNumber str = (take n1 [1,1..]) ++ (take n0 [0,0..])\n where\n n0 = countOccurrence 'z' str\n n1 = countOccurrence 'n' str\n\nmain = do\n nStr <- getLine\n str <- getLine\n putStrLn . unwords . map show $ maxNumber str"}, {"source_code": "{-\n Copyright (c) 2019 Islam Omar\n-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE CPP #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-Ofast #-}\n\nimport Control.Monad (foldM, forM, forM_, join, replicateM_, when)\nimport Control.Monad.ST\nimport Control.Monad.State.Strict\n\nimport Data.Array.IArray (array)\nimport Data.Array.ST.Safe (STArray)\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bits\nimport Data.Functor\nimport Data.Graph (Graph)\nimport qualified Data.Graph as G\nimport Data.Int (Int64)\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.List as L\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.STRef\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport System.IO\nimport Text.Read\n--- DEBUGGING\n#define DEBUG(x) dump di \"x\" x\ndump di str a\n | \"demo.hs\" `L.isSuffixOf` __FILE__ =\n modifySTRef' di (L.insert (str, a)) >> return Nothing\n | otherwise = return Nothing\n\nprintDump lst\n | \"demo.hs\" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing\n | otherwise = return Nothing\n\nreadNumList :: (Num a, Read a) => IO [a]\nreadNumList = map read . words <$> getLine\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = read <$> getLine\n\nreadNumListLn :: (Num a, Read a) => Int -> IO [a]\nreadNumListLn n = doGetList n []\n where\n doGetList 0 l = return l\n doGetList n l = do\n i <- readNum\n doGetList (n - 1) (l ++ [i])\n \n-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]\nsolve di n s = do\n let zeros = foldr (\\c cnt -> if c == 'z' then cnt+1 else cnt) 0 s\n let ones = foldr (\\c cnt -> if c == 'n' then cnt+1 else cnt) 0 s\n --forM_ nums compute\n let ans = (zeros, ones)\n -- solution\n return ans\n\nsolveN 0 = return ()\nsolveN n = do\n n <- readNum :: IO Int\n -- let m = <- readNum :: IO [Int]\n s <- getLine \n let computation =\n runST $ do\n let dubeg_info =\n [] :: (Num a) =>\n [(String, a)]\n --- list of tuples (string value)\n di <- newSTRef dubeg_info\n ans <- solve di n s\n tmp <- readSTRef di\n let lst = (ans, tmp)\n readSTRef =<< newSTRef lst\n -- get solution\n let (z, o) = fst computation\n let debug_info = snd computation\n printDump debug_info\n -- print result\n forM_ [1..o] (\\_ -> putStr \"1 \")\n forM_ [1..z] (\\_ -> putStr \"0 \")\n putStrLn \"\"\n -- putStrLn $ show n ++ \" \" ++ show p\n\n-- main :: IO ()\nmain = do\n -- t <- readNum :: IO Int\n solveN 1\n"}, {"source_code": "{-\n Copyright (c) 2019 Islam Omar\n-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE CPP #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-Ofast #-}\n\nimport Control.Monad (foldM, forM, forM_, join, replicateM_, when)\nimport Control.Monad.ST\nimport Control.Monad.State.Strict\n\n-- import Data.Array.MArray.Safe ( MArray )\n-- import qualified Data.Array.MArray.Safe as MA\nimport Data.Array.ST.Safe (STArray)\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bits\nimport Data.Functor\nimport Data.Graph (Graph)\nimport qualified Data.Graph as G\nimport Data.Int (Int64)\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.List as L\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.STRef\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport System.IO\nimport Text.Read\n--- DEBUGGING\n#define DEBUG(x) dump di \"x\" x\ndump di str a\n | \"demo.hs\" `L.isSuffixOf` __FILE__ =\n modifySTRef' di (L.insert (str, a)) >> return Nothing\n | otherwise = return Nothing\n\nprintDump lst\n | \"demo.hs\" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing\n | otherwise = return Nothing\n\nreadNumList :: (Num a, Read a) => IO [a]\nreadNumList = map read . words <$> getLine\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = read <$> getLine\n\nreadNumListLn :: (Num a, Read a) => Int -> IO [a]\nreadNumListLn n = doGetList n []\n where\n doGetList 0 l = return l\n doGetList n l = do\n i <- readNum\n doGetList (n - 1) (l ++ [i])\n \n-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]\nsolve di n s = do\n let zeros = foldr (\\c cnt -> if c == 'z' then cnt+1 else cnt) 0 s\n let ones = foldr (\\c cnt -> if c == 'n' then cnt+1 else cnt) 0 s\n --forM_ nums compute\n let ans = (zeros, ones)\n -- solution\n return ans\n\nsolveN 0 = return ()\nsolveN n = do\n n <- readNum :: IO Int\n s <- getLine \n let computation =\n runST $ do\n let dubeg_info =\n [] :: (Num a) =>\n [(String, a)]\n --- list of tuples (string value)\n di <- newSTRef dubeg_info\n ans <- solve di n s\n tmp <- readSTRef di\n let lst = (ans, tmp)\n readSTRef =<< newSTRef lst\n -- get solution\n let (z, o) = fst computation\n let debug_info = snd computation\n printDump debug_info\n -- print result\n forM_ [1..o] (\\_ -> putStr \"1 \")\n forM_ [1..z] (\\_ -> putStr \"0 \")\n putStrLn \"\"\n -- putStrLn $ show n ++ \" \" ++ show p\n\n-- main :: IO ()\nmain = do\n -- t <- readNum :: IO Int\n solveN 1\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nsolve' eo n zr = \n let ones = min n eo\n zeros = min (eo - ones) zr\n in intersperse ' ' $ replicate ones '1' ++ replicate zeros '0' ++ []\n\nvar xs x = let a = lookup x xs in if isJust a then fromJust a else 0\n\nsolve xs = \n let bs = map (\\x -> (head x, length x)) $ group $ sort xs\n [z,e,r,o,n] = map (var bs) \"zeron\" \n in if min z r /= 0 && n == 0 then solve' 1 0 1 else solve' (min e o) n (min z r)\n \nmain = do\n getLine \n a <- getLine\n putStrLn $ solve a"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nsolve' eo n zr = \n let ones = min n eo\n zeros = min (eo - ones) zr\n in intersperse ' ' $ replicate ones '1' ++ replicate zeros '0' ++ []\n\nvar xs x = let a = lookup x xs in if isJust a then fromJust a else 0\n\nsolve xs = \n let bs = map (\\x -> (head x, length x)) $ group $ sort xs\n [z,e,r,o,n] = map (var bs) \"zeron\" \n in if min z r /= 0 && n == 0 then solve' 1 0 1 else solve' (min e o) n (min z r)\n \nmain = do\n getLine \n a <- getLine\n print $ solve a"}], "src_uid": "5e5dbd70c7fcedf0f965aed5bafeb06c"} {"source_code": "main = getLine >> fmap lines getContents >>= putStrLn . unlines . map (show . solve . drop 4)\n\nsolve s = result\n where\n start = 1989 + sum (map (10^) [1 .. length s - 1])\n p10 = 10 ^ length s\n result = start + (read s - start) `mod` p10\n\n", "positive_code": [{"source_code": "main = getLine >> fmap lines getContents >>= putStrLn . unlines . map (show . solve . drop 4)\n\nsolve s = start + (read s - start) `mod` (10^n)\n where\n n = length s\n start = 1989 + sum (map (10^) [1 .. n-1])\n\n"}, {"source_code": "main = getLine >> fmap lines getContents >>= putStr . unlines . map (show . solve . drop 4)\n\nsolve s = start + (read s - start) `mod` (10^n)\n where\n n = length s\n start = 1989 + sum (map (10^) [1 .. n-1])\n\n"}, {"source_code": "import Control.Monad\n\nyearStart = 1989\nyearBasePairs = take 10 $ iterate f (yearStart, 10) where\n f (year, base) = (year + base, base * 10)\n\nsuffixToYear suffix = let\n (keyYear, base) = yearBasePairs !! (length suffix - 1)\n in keyYear + (mod (read suffix - keyYear) base)\n\nmain = do\n n <- return . read =<< getLine :: IO Int\n forM_ [1..n] $ \\_ -> do\n suffix <- return . drop 4 =<< getLine\n print $ suffixToYear suffix\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nyearStart = 1989\nyearBasePairs = take 10 $ iterate f (yearStart, 10) where\n f (year, base) = (year + base, base * 10)\n\nsuffixToYear suffix = let\n (keyYear, base) = head $ dropWhile ((<= suffix) . snd) $ yearBasePairs\n in keyYear + (mod (suffix - keyYear) base)\n\nmain = do\n n <- return . read =<< getLine :: IO Int\n forM_ [1..n] $ \\_ -> do\n suffix <- return . read . drop 4 =<< getLine :: IO Int\n print $ suffixToYear suffix\n"}, {"source_code": "main = do\n _ <- getLine\n ss <- fmap lines getContents\n let inputs = map (drop 4) ss\n res = map solve inputs\n putStrLn . unlines . map show $ res\n\nsolve s = result\n where\n start = [1989, 1999, 2099, 3099, 13098, 113098, 1113098, 11113098, 111113098] !! (length s - 1)\n p10 = 10 ^ length s\n result = start + (read s - start) `mod` p10\n\n"}], "src_uid": "31be4d38a8b5ea8738a65bfee24a5a21"} {"source_code": "import Data.Array\nimport Data.List\nimport Data.Graph\nimport Data.Tree\nimport Control.Applicative\nimport Text.Printf\nimport Data.Int\n\nbinom = array ((0, 0), (51, 51)) [((i, j), f i j) | i <- [0..51], j <- [0..i]]\n where f i j | i == 0 = 1.0\n | j == i = 1.0\n | j == 0 = 1.0\n | otherwise = binom ! (i-1, j-1) + binom ! (i-1, j)\nsolve n m a k = d ! (n, m)\n where d = array ((0, 1), (n, m)) [((i, j), f i j) | i <- [0..n], j <- [1..m]]\n f :: Int32 -> Int32 -> Double\n f i 1 | i > k*a!1 = 0.0\n | otherwise = 1.0\n f i j = sum [binom ! (i,h) * p**(fromIntegral h) * q**(fromIntegral $ i-h) * d ! (i-h, j-1) | h <- [0..t]]\n where t = min i (a!j*k)\n p = (1.0::Double) / fromIntegral j\n q = 1.0 - p\nints = map read . words <$> getLine\nmain = do \n [n, m] <- ints\n a <- listArray (1, m) <$> ints\n let p = listArray (0, n) $ 0:[solve n m a k | k <- [1..n]]\n let res = sum [fromIntegral k * (p!k - p ! (k-1)) | k <- [1..n]]\n printf \"%.11f\" (res::Double) ", "positive_code": [{"source_code": "import Data.Array\n\nchoose :: Int -> Int -> Double\nchoose _ 0 = 1\nchoose n k = choose (n-1) (k-1) * (fromIntegral n) / (fromIntegral k)\n\npow :: Int -> Int -> Double\npow x y = (fromIntegral x) ** (fromIntegral y)\n\ndivup :: Int -> Int -> Int\ndivup x y = (x + y - 1) `div` y\n\nsolve :: [Int] -> Int -> Double\nsolve as n = d ! (m, n, 0)\n\twhere\n\t\tm = length as\n\t\td = array ((1, 0, 0), (m, n, 50)) [((mm, nn, gg), solve' mm nn gg) | mm <- [1..m], nn <- [0..n], gg <- [0..50]]\n\t\tsolve' :: Int -> Int -> Int -> Double\n\t\tsolve' 1 nn gg = fromIntegral $ max gg $ divup nn (last as)\n\t\tsolve' mm nn gg = sum [(p i) * (d ! (mm-1, nn-i, max gg (divup i (as!!(m-mm))))) | i <- [0..nn]]\n\t\t\twhere\n\t\t\t\tp i = (choose nn i) * (pow (mm-1) (nn-i)) / (pow mm nn)\n\nmain = do\n\t-- n:m:a <- C.hGetContents stdin >>= return . map (fst . fromJust . C.readInt) . C.words\n\tn:m:_ <- getLine >>= return . map read . words :: IO [Int]\n\ta <- getLine >>= return . map read . words :: IO [Int]\n\tputStrLn $ show $ solve a n\n"}], "negative_code": [], "src_uid": "c2b3b577c2bcb3a2a8cb48700c637270"} {"source_code": "\nimport Char (isDigit, ord)\nimport Control.Monad (liftM)\nimport Maybe (fromJust)\nimport List (sort, sortBy, partition)\n\n--import CPUTime\n--import IO (hPutStrLn, stderr)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestEmpty = Test \"TestEmpty\" $ assertEq [] (solve 1 [(2,1)])\n\ntestOne = Test \"TestOne\" $ assertEq [1] (solve 1 [(1,1)])\n\ntestInput = Test \"TestInput\" $ assertEq [2] (solve 2 [(1,2),(2,7),(1,3)])\n\ntestDifficultChoose = Test \"TestDifficultChoose\" $\n assertEq [2,3] (sort $ solve 3 [(2,1), (2,12), (1,7), (1,6), (1,5)])\n\ntestWA4 = Test \"Test WA 4\" $\n assertEq (sort [13, 8, 3, 18, 14, 16, 10, 6, 2, 5, 9, 7, 1, 11]) (sort (solve 19 input))\n where\n input = \n [\n (2, 47), (1, 37), (1, 48), (2, 42), (2, 48),\n (1, 38), (2, 47), (1, 48), (2, 47), (1, 41),\n (2, 46), (1, 28), (1, 49), (1, 45), (2, 34),\n (1, 43), (2, 29), (1, 46), (2, 45), (2, 18)\n ]\n\ntestWA4Small = Test \"TestWA4Small\" $\n assertEq [1,2] (solve 3 [(2,20), (1,12), (1,12)])\n\ntestDifficult = TestList \"TestDifficult\"\n [\n Test \"1\" $ assertEq [1,3,4,5] (sort $ solve 5 [(1,12), (1,12), (1,14), (1,14), (2,20)]),\n Test \"2\" $ assertEq [1,2,3,4] (sort $ solve 4 [(1,12), (1,12), (1,14), (1,14), (2,20)]),\n Test \"3\" $ assertEq [2] (sort $ solve 2 [(2,1), (2,2)])\n ]\n\ntestBig :: Int -> Test\ntestBig n = TestList \"Test Big\"\n [\n Test \"1\" $ assertEq [1..n] (sort $ solve (10^9) [(1 + mod i 2, i) | i <- [1..n]]),\n Test \"2\" $ assertEq []\n (sort $ solve (100) [(1 + mod i 2, i) | i <- [1..n]])\n ]\n\ntest = mapM_ run\n [\n testEmpty,\n testOne,\n testInput,\n testDifficultChoose,\n testWA4Small,\n testDifficult,\n testWA4,\n testBig (10^5)\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: Int -> [(Int, Int)] -> [Int]\nsolve v xs = solve' v (sortBy (\\c1 c2 -> compare (fst c2) (fst c1)) catamarans') (sortBy (\\c1 c2 -> compare (fst c2) (fst c1)) boats') Nothing []\n where\n xsWithNumbers = zipWith (\\(v, c) n -> (v, (c, n))) xs [1..]\n (catamarans, boats) = partition (\\(v, _) -> v == 2) xsWithNumbers\n (catamarans', boats') = (map snd catamarans, map snd boats)\n solve' :: Int -> [(Int, Int)] -> [(Int, Int)] -> Maybe (Int, Int) -> [Int] -> [Int]\n solve' 0 _ _ reserve acc\n | reserve == Nothing = acc\n | otherwise = (snd (fromJust reserve)) : acc\n solve' 1 [] [] reserve acc\n | reserve == Nothing = acc\n | otherwise = (snd (fromJust reserve)) : acc\n solve' 1 [] ((_, n) : bs) reserve acc\n | reserve == Nothing = n : acc\n | otherwise = (snd (fromJust reserve)) : n : acc\n solve' 1 ((c1, n1):cs) [] Nothing acc = acc\n solve' 1 ((c1, n1):cs) [] (Just (c2, n2)) acc\n | c1 > c2 = n1 : acc\n | otherwise = n2 : acc\n solve' 1 ((c1, n1):cs) ((c2, n2):bs) Nothing acc = n2 : acc\n solve' 1 ((c1, n1):cs) ((c2, n2):bs) (Just (c3, n3)) acc\n | c1 > c2 + c3 = n1 : acc\n | otherwise = n2 : n3 : acc \n solve' v [] [] Nothing acc = acc\n solve' v [] [] (Just (_, n)) acc = n : acc\n solve' v [] ((c1, n1) : bs) reserve acc = solve' (v-1) [] bs reserve (n1 : acc)\n solve' v ((c1, n1) : cs) [] reserve acc = solve' (v-2) cs [] reserve (n1 : acc)\n solve' v css@((c1, n1):cs) [(c2, n2)] unknown acc\n | c1 >= c2 = solve' (v-2) cs [(c2, n2)] unknown (n1 : acc)\n | unknown == Nothing = solve' (v-1) css [] (Just (c2, n2)) acc\n | otherwise = solve' (v-1) css [] (Just (c2, n2)) (snd (fromJust unknown) : acc)\n solve' v css@((c1, n1):cs) bss@((c2, n2) : (c3, n3) : bs) unknown acc\n | c1 >= c2 + c3 = solve' (v-2) cs bss unknown (n1 : acc)\n | unknown == Nothing = solve' (v-2) css bs (Just (c3, n3)) (n2 : acc)\n | otherwise = solve' (v-2) css bs (Just (c3, n3)) (snd (fromJust unknown) : n2 : acc)\n\nreadPair :: String -> (Int, Int)\nreadPair s = reads' 0 s\n where\n reads' a (' ':s) = reads'' a 0 (dropWhile (== ' ') s)\n reads' a (c:s)\n | isDigit c = reads' (10*a + ord c - ord '0') s\n | otherwise = error $ concat [\"readPair: unknown symbol \", show c]\n reads'' a b [] = (a, b)\n reads'' a b (c:s)\n | isDigit c = reads'' a (10*b + ord c - ord '0') s\n | otherwise = error $ concat [\"readPair: unknown symbol \", show c]\n\nprintAns :: [(Int, Int)] -> [Int] -> IO ()\nprintAns boats numers = do\n let sortNumers = sort numers\n let res = getRes boats sortNumers\n print res\n printAns' sortNumers\n where\n getRes bs ns = getRes' 1 bs ns 0\n getRes' _ _ [] acc = acc\n getRes' m (b:bs) (n:ns) acc\n | m == n = getRes' (m+1) bs ns (snd b + acc)\n | otherwise = getRes' (m+1) bs (n:ns) acc\n printAns' [] = return ()\n printAns' [n] = print n\n printAns' (n:ns) = putStr (concat [show n, \" \"]) >> printAns' ns\n\nmain :: IO ()\nmain = do\n-- timeStart <- getCPUTime\n \n lines' <- liftM lines getContents\n let (n, v) = (readPair . head) lines'\n let boats = (take n . map readPair . tail) lines'\n printAns boats $ solve v boats\n\n-- timeEnd <- getCPUTime\n-- hPutStrLn stderr $ concat [\"Time = \", show $ fromIntegral (timeEnd - timeStart) / (10^12), \" sec.\"]\n", "positive_code": [{"source_code": "import Data.List (sortBy, partition)\nimport Data.Function (on)\nimport Data.Functor ((<$>))\nimport Control.Monad (replicateM)\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [Int] -> (Int, [Int])\nsolve ones twos cap accWt accItems\n | null ones = take' (cap `div` 2) twos\n | null twos = take' cap ones\n | cap < 2 = solve ones [] cap accWt accItems\n | twoOnes <= oneTwo =\n solve ones (tail twos) (cap - 2) (accWt + oneTwo) (snd (head twos) : accItems)\n | otherwise =\n solve (tail ones) twos (cap - 1) (accWt + fst (head ones)) (snd (head ones) : accItems)\n where\n take' n xs = (accWt + leftWt, leftItems ++ accItems)\n where\n leftWt = sum . map fst $ take n xs\n leftItems = map snd $ take n xs\n\n twoOnes = sum . map fst . take 2 $ ones\n oneTwo = fst . head $ twos\n\n\nmain :: IO ()\nmain = do\n [n, v] <- map read . words <$> getLine -- n \\leq 10^5, 1 \\leq v \\leq 10^9\n input <- replicateM n (map read . words <$> getLine)\n\n let (ones, twos) = partition ((== 1) . head . fst) $ zip input [1..]\n revSort = sortBy (flip compare `on` fst)\n unpack = map $ \\([_, w], i) -> (w, i)\n (cost, items) = solve (revSort $ unpack ones) (revSort $ unpack twos) v 0 []\n\n print cost\n putStrLn . unwords . map show $ items\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing, Down(..))\nimport Control.Monad (replicateM, forM_)\nimport Data.List (sortOn)\n\nnewtype Id = Id Int deriving (Show, Eq)\ntype Capacity = Int\n\ndata Boat = Boat {\n boatId :: Id,\n boatCapacity :: Capacity\n } deriving (Show, Eq)\n\ndata BoatPark = BoatPark {\n kayaks :: [Boat],\n catamarans :: [Boat]\n } deriving (Show)\n\nsortByCapacity :: [Boat] -> [Boat]\nsortByCapacity = sortOn (Down . boatCapacity)\n\nsortBoatPark :: BoatPark -> BoatPark\nsortBoatPark (BoatPark k c) = BoatPark (sortByCapacity k) (sortByCapacity c)\n\ngetBoatPark :: Int -> IO BoatPark\ngetBoatPark n = do\n boats <- replicateM n getInts\n return . sortBoatPark $ foldr addBoat (BoatPark [] []) (zip [1..] boats)\n\naddBoat :: (Int, [Int]) -> BoatPark -> BoatPark\naddBoat (id, [t, c]) park@(BoatPark ks cs) | t == 1 = park { kayaks = boat:ks }\n | t == 2 = park { catamarans = boat:cs }\n where boat = Boat (Id id) c\n\nsolve :: Capacity -> BoatPark -> (Capacity, [Id])\nsolve 0 _ = (0, [])\nsolve _ (BoatPark [] []) = (0, [])\nsolve c park@BoatPark { kayaks = k1:ks, catamarans = [] } = k1 $+ solve (c - 1) park { kayaks = ks }\nsolve 1 park = solve 1 park { catamarans = [] }\nsolve c park@BoatPark { kayaks = [], catamarans = c1:cs } = c1 $+ solve (c - 2) park { catamarans = cs }\nsolve c park@(BoatPark [k1] (c1:cs)) | boatCapacity k1 > boatCapacity c1 = k1 $+ solve (c - 1) park { kayaks = [] }\n | otherwise = c1 $+ solve (c - 2) park { catamarans = cs }\nsolve c park@(BoatPark (k1:k2:ks) (c1:cs)) | c `mod` 2 == 1 && kayaksBetter = k1 $+ solve (c - 1) park { kayaks = k2:ks }\n | kayaksBetter = k1 $+ k2 $+ solve (c - 2) park { kayaks = ks }\n | otherwise = c1 $+ solve (c - 2) park { catamarans = cs }\n where kayaksBetter = boatCapacity k1 + boatCapacity k2 > boatCapacity c1\n\n($+) :: Boat -> (Capacity, [Id]) -> (Capacity, [Id])\n(Boat id c) $+ (total, ids) = (total + c, id:ids)\ninfixr 3 $+\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nprintSolution :: (Capacity, [Id]) -> IO ()\nprintSolution (c, ids) = do\n print c\n forM_ ids $ \\(Id i) -> print i\n\nmain :: IO ()\nmain = do\n [n, c] <- getInts\n park <- getBoatPark n\n printSolution $ solve c park"}, {"source_code": "{-# LANGUAGE BangPatterns #-} \nimport Numeric\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead !s = case readDec s of [(n, \"\")] -> n\n\ndata Boat = One Int Int | Two Int Int deriving (Eq, Ord)\n\nmakeBoat n [1, x] = One x n\nmakeBoat n [2, x] = Two x n\n\n\neven' s1 s2 v = fill s1 s2 v []\n\nodd' [] s2 v = fill [] s2 v []\nodd' (s:ss) s2 v = fill ss s2 (v-1) [s]\n\nfill :: [Boat] -> [Boat] -> Int -> [Boat] -> [Boat]\nfill [] [] _ a = a\nfill _ _ 0 a = a\nfill (o:os) [] x a = fill os [] (x - 1) (o:a)\nfill [] _ 1 a = a\nfill [] (t:ts) x a = fill [] ts (x - 2) (t:a)\nfill unos@(aa@(One a _):bb@(One b _):ones) dos@(cc@(Two c _):twos) x acc =\n if a + b > c\n then fill ones dos (x - 2) (aa:bb:acc)\n else fill unos twos (x - 2) (cc:acc)\nfill [aa@(One a _)] dos@(cc@(Two c _):twos) x acc =\n if a > c\n then fill [] dos (x - 1) (aa:acc)\n else fill [aa] twos (x - 2) (cc:acc)\n\nsolve :: Int -> [Boat] -> (Int, [Int])\nsolve v boats =\n foldBoats $ case v `mod` 2 of\n 0 -> even' s1 s2 v\n 1 -> odd' s1 s2 v\n where\n p (One _ _) = True\n p (Two _ _) = False\n (b1, b2) = partition p boats\n (s1, s2) = (reverse $ sort b1, reverse $ sort b2)\n value (One x _) = x\n value (Two x _) = x\n no (One _ x) = x\n no (Two _ x) = x\n foldBoats = mapAccumL (\\a h-> (a + value h, no h)) 0 \n \nmain = do\n [n, v] <- getLine >>= (return . map fastRead . words)\n things <- forM [1..n] (\\n -> getLine >>= (return . makeBoat n . map fastRead . words))\n let (res, boats) = solve v things\n print res\n forM_ boats (\\b -> putStr $ show b ++ \" \")\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n-- http://en.wikipedia.org/wiki/Haskell_features#Examples\n-- http://en.wikibooks.org/wiki/Haskell/More_on_datatypes\n\nimport Data.List\n\ndata Boat =\n\tBoat { t\t:: Int,\n\t\t\tw\t:: Int,\n\t\t\tnum\t:: Int\n\t\t }\n\ncmp :: Boat -> Boat -> Ordering \ncmp a b\n\t| s == 0\t= EQ\n\t| s < 0\t\t= LT\n\t| otherwise\t= GT\n\t\twhere s = (t a) * (w b) - (t b) * (w a)\n\ngreedy :: Int -> [Boat] -> [Boat] -> (Int, [Boat])\ngreedy a [] []\t= (0, [])\ngreedy 0 _ _\t= (0, [])\ngreedy a (h1:tl1) [] = update h1 (greedy (a - 1) tl1 [])\ngreedy 1 [] _\t= (0, [])\ngreedy a [] (h2:tl2) = update h2 (greedy (a - 2) [] tl2)\ngreedy a (h1:tl1) (h2:tl2)\n\t| mod a 2 == 1\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| w1 < (w h2)\t= update h2 (greedy (a - 2) (h1:tl1) tl2)\n\t| otherwise\t\t= update h1 (update (head tl1) (greedy (a - 2) (tail tl1) (h2:tl2)))\n\t\twhere w1 = firstTwo (h1:tl1)\n\nfirstTwo :: [Boat] -> Int\nfirstTwo [] = 0\nfirstTwo (a:[]) = w a\nfirstTwo (a:b:c) = w a + w b\n\nupdate :: Boat -> (Int, [Boat]) -> (Int, [Boat])\nupdate b (c, d) = (c + (w b), b : d)\n\nprocess :: Int -> [Int] -> [Boat]\nprocess _ [] \t\t\t= []\nprocess n (a : (b : c))\t= (Boat a b n) : (process (n + 1) c)\n\nisSize :: Int -> Boat -> Bool\nisSize n b = n == (t b)\n\nprintAns :: [Boat] -> IO()\nprintAns [] = do\n\tputStr \"\\n\"\nprintAns (a : []) = do\n\tputStrLn (show (num a))\nprintAns (a : b) = do\n\tputStr (show (num a))\n\tputStr \" \"\n\tprintAns (b)\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet input = map read (words (str))\n\tlet v = head (tail (input))\n\tlet slist = sortBy cmp (process 1 (tail (tail (input))))\n\tlet list1 = filter (isSize 1) slist\n\tlet list2 = filter (isSize 2) slist\n\tlet ans = greedy v list1 list2\n\tputStrLn (show (fst ans))\n\tprintAns (snd ans)\n"}, {"source_code": "import Data.List\ndefault (Int)\ndata S = S {t::Int, p::Int, number::Int} \nfindSolution (v, v', p') [] sList' = (p', sList')\nfindSolution (v, v', p') sList@(s:ss) sList' = \n\tif v' + t s == v then (p' + p s, s:sList') else\n\t\tif v' + t s < v then findSolution (v, v' + t s, p' + p s) ss (s:sList') else\n\t\tlet {[i1, i2] = map (findIndex (\\s -> t s == 1)) [sList, sList']} in\n\t\tcase (i1, i2) of {(Just i1', Just i2') -> \n\t\t\tif p (sList !! i1') + p (sList' !! i2') < p s then\n\t\t\t\tone2two i2' sList' p' s\n\t\t\telse (p' + p (sList !! i1'), (sList !! i1'):sList');\n\t\t(Nothing, Just i2') -> if p s > p (sList' !! i2') then \n\t\t\t\tone2two i2' sList' p' s\n\t\t\telse (p', sList');\n\t\t(Nothing, Nothing) -> (p', sList')} where \n\t\tone2two i2' sList' p' s = let s'' = sList' !! i2' in\n\t\t\t(p' - p s'' + p s, s:filter ((/= (number s'')) . number) sList')\n\nmain = do { [n, v] <- map read `fmap` (getLine >>= return . words)\n\t; l <- inputArr n 1 []\n\t; let l1 = l `seq` sortBy (\\a b -> compare (average2 b) (average2 a)) l where\n\t\taverage2 a = case t a of {1 -> (p a * 2); _ -> p a}\n\t; let (p', s) = l1 `seq` findSolution (v, 0, 0) l1 []\n\t; print p'\n\t; case s of {[] -> return (); s':ss' -> do {\n\t\t; putStr $! show $ number $ s'\n\t\t; mapM_ (\\n -> putChar ' ' >> (putStr $ show $ number n)) ss'\n\t}}\n\t; putChar '\\n'\n}\n\ninputArr n i s = if i <= n then getLine >>= \\line -> let [t', p'] = map read $ words line in \n\t\tinputArr n (i+1) (S t' p' i : s)\n\telse return s"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy, (\\\\))\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int} deriving (Show, Eq)\ncompute s = show finalTotalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing (\\v->fromIntegral (cost v)/fromIntegral (capacity v))) [Vehical n t p | (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n chooseVehicals = if totalCost chooseVehicals1 == volume || null remain\n then chooseVehicals1\n else adjustVehicals chooseVehicals1 remain\n finalTotalCapacity = totalCapacity chooseVehicals\n\ntotalCost = (foldr (+) 0).(map cost)\ntotalCapacity = (foldr (+) 0).(map capacity)\n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` totalCapacity) $ [x | x<-subsequences vehicals, totalCost x <= v]\n\nadjustVehicals chooseVehicals1 remain = (chooseVehicals1 \\\\ lastCost1) ++ chooseVehicalsRemain v competeVehicals\n where lastCost1 = take 1 $ filter (\\x->cost x==1) $ reverse chooseVehicals1\n nextCost1 = take 1 $ filter (\\x->cost x==1) $ remain\n nextCost2 = take 1 $ filter (\\x->cost x==2) $ remain\n competeVehicals = lastCost1 ++ nextCost1 ++ nextCost2\n v = 1 + length lastCost1\n\nmain = interact $unlines.compute"}, {"source_code": "module Main (main) where\n\nimport qualified Data.List as L\n\nreadInt :: String ->Int\nreadInt = read\n\nreadPair l = map readInt (words l)\n\nmain :: IO ()\nmain = do\n instr <- getLine\n let [n, v] = readPair instr\n instr <- getContents\n let lodki = zip (map readPair (take n (lines instr))) [1..n]\n printResult $ solve n v lodki\n where\n \n printResult res = do\n print $ sum (map (\\(w, n) -> w) res)\n printWhile res where\n printWhile [] = return ()\n printWhile (x:xs) = do\n putStr $ (show (snd x)) ++ \" \"\n printWhile xs\n\n solve n v lodki = findMax (reverse (take fitCatam catam)) \n (take fitBayd bayd) \n (drop fitBayd bayd) where\n \n findMax [] bs _ = bs\n findMax cs bs [] = cs ++ bs\n findMax (c:cs) bs [one] = if (fst one) > (fst c)\n then findMax cs (one:bs) []\n else (c:cs) ++ bs\n findMax (c:cs) bs (one:two:oth) = if ((fst one) + (fst two)) > (fst c)\n then findMax cs (one:two:bs) oth\n else (c:cs) ++ bs\n \n bayd = filterLodok 1\n baydLen = length bayd\n \n catam = filterLodok 2\n catamLen = length catam\n \n fitCatam = min (div v 2) catamLen\n fitBayd = min (v - (fitCatam * 2)) baydLen\n \n filterLodok tp = L.sortBy (\\a b -> compare b a) $ \n map (\\([_,w],n) -> (w,n)) $ \n filter (\\([t,w],n) -> t == tp) lodki\n\n"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy, (\\\\))\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show, Eq)\ncompute s = show finalTotalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n --totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n --vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume*2-totalCost1*2) $ filter (\\x->cost x==1) remain)\n --chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n chooseVehicals = if totalCost chooseVehicals1 == volume || null remain\n then chooseVehicals1\n else adjustVehicals chooseVehicals1 remain\n finalTotalCapacity = totalCapacity chooseVehicals\n\ntotalCost = (foldr (+) 0).(map cost)\ntotalCapacity = (foldr (+) 0).(map capacity)\n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v && (foldr (+) 0 $ map cost x) >= v-1]\n\nadjustVehicals chooseVehicals1 remain = (chooseVehicals1 \\\\ (lastCost1 ++ lastCost2)) ++ chooseVehicalsRemain v competeVehicals\n where lastCost1 = take 1 $ filter (\\x->cost x==1) $ reverse chooseVehicals1\n lastCost2 = take 1 $ filter (\\x->cost x==2) $ reverse chooseVehicals1\n nextCost1 = take 3 $ filter (\\x->cost x==1) $ remain\n nextCost2 = take 1 $ filter (\\x->cost x==2) $ remain\n competeVehicals = lastCost1 ++ lastCost2 ++ nextCost1 ++ nextCost2\n v = 1 + totalCost lastCost1 + totalCost lastCost2\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy, (\\\\))\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show, Eq)\ncompute s = show finalTotalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n chooseVehicals = if totalCost chooseVehicals1 == volume || null remain\n then chooseVehicals1\n else adjustVehicals chooseVehicals1 remain\n finalTotalCapacity = totalCapacity chooseVehicals\n\ntotalCost = (foldr (+) 0).(map cost)\ntotalCapacity = (foldr (+) 0).(map capacity)\n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v && (foldr (+) 0 $ map cost x) >= v-1]\n\nadjustVehicals chooseVehicals1 remain = (chooseVehicals1 \\\\ (lastCost1 ++ lastCost2)) ++ chooseVehicalsRemain v competeVehicals\n where lastCost1 = take 1 $ filter (\\x->cost x==1) $ reverse chooseVehicals1\n lastCost2 = take 1 $ filter (\\x->cost x==2) $ reverse chooseVehicals1\n nextCost1 = take 3 $ filter (\\x->cost x==1) $ remain\n nextCost2 = take 1 $ filter (\\x->cost x==2) $ remain\n competeVehicals = lastCost1 ++ lastCost2 ++ nextCost1 ++ nextCost2\n v = 1 + totalCost lastCost1 + totalCost lastCost2\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy, (\\\\))\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int} deriving (Show, Eq)\ncompute s = show (total capacity chooseVehicals) : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing (\\v->fromIntegral (cost v)/fromIntegral (capacity v))) [Vehical n t p | (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n chooseVehicals = if total cost chooseVehicals1 == volume || null remain\n then chooseVehicals1\n else adjustVehicals chooseVehicals1 remain\n\nadjustVehicals chooseVehicals1 remain = (chooseVehicals1 \\\\ lastCost1) ++ chooseVehicalsRemain v competeVehicals\n where lastCost1 = kOut 1 $ reverse chooseVehicals1\n nextCost1 = kOut 1 remain\n nextCost2 = kOut 2 remain\n competeVehicals = lastCost1 ++ nextCost1 ++ nextCost2\n v = 1 + length lastCost1\n kOut c = (take 1).(filter $ \\x->cost x==c)\n\nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` total capacity) $ [x | x<-subsequences vehicals, total cost x <= v]\n\ntotal f = (foldr (+) 0).(map f)\n \nmain = interact $unlines.compute"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Ord (comparing)\nimport Data.List (sortBy,delete)\nimport Control.Arrow (second)\nimport Control.Monad (guard)\n\nmain = do\n [n,v] <- fmap (map read . words) getLine\n bs <- fmap ( sortBy (flip $ comparing boatDensity) .\n pairs 1 . map read . words )\n getContents\n let (f,c,bs0,bs0') = greedy v bs\n (rc,rbs) = maximum $\n (c,map boatId bs0) :\n map (second (map boatId)) (\n nextKayak v f c bs0 bs0' ++\n fitCatamaran v f c bs0 bs0'\n )\n print rc\n putStrLn $ unwords $ map show rbs\n\ngreedy v bs = go v 0 [] bs where\n go r c a [] = (v-r,c,a,[])\n go r c a (b:bs)\n | boatSize b > r = (v-r,c,a,b:bs)\n | otherwise = go (r - boatSize b) (c + boatDensity b * boatSize b `div` 2)\n (b : a) bs\n\nnextKayak v f c bs bs' = do\n guard (f < v)\n k <- take 1 (filter ((== 1) . boatSize) bs')\n return (c + boatDensity k `div` 2,k : bs)\n\nfitCatamaran v f c bs bs' = do\n guard (f < v)\n guard (not (null bs'))\n let ct = head bs'\n guard (boatSize ct == 2)\n k <- take 1 (filter ((== 1) . boatSize) bs)\n return (c - boatDensity k `div` 2 + boatDensity ct,ct : delete k bs)\n\npairs !i (x:y:z) = (i,x,2*y `div` x) : pairs (i+1) z\npairs _ [] = []\n\nboatId (i,_,_) = i\nboatSize (_,s,_) = s\nboatDensity (_,_,d) = d\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Ord (comparing)\nimport Data.List (sortBy,delete)\nimport Control.Arrow (second)\nimport Control.Monad (guard)\n\n--import Debug.Trace\ntrace = curry snd\ntraceShow = curry snd\ntr x = traceShow x x\n\nmain :: IO ()\nmain = do\n [n,v] <- fmap (map read . words) getLine\n bs <- fmap (sortBy (flip $ comparing boatDensity) . pairs 1 . map read . words) getContents\n let (f,c,bs0,bs0') = tr $ greedy v bs\n (rc,rbs) = maximum $\n (c,map boatId bs0) :\n map (second (map boatId)) (\n tr (nextKayak v f c bs0 bs0') ++\n tr (fitCatamaran v f c bs0 bs0') :: [(Int,[Boat])]\n )\n :: (Int,[Int])\n print rc\n putStrLn $ unwords $ map show rbs\n\ntype Boat = (Int,Int,Int)\ngreedy :: Int -> [Boat] -> (Int,Int,[Boat],[Boat])\ngreedy v bs = go v 0 [] bs where\n go r c a bs | traceShow (r,c,a,bs) False = undefined\n go r c a [] = trace \"Exhausted list\" (v-r,c,a,[])\n go r c a (b:bs)\n | boatSize b > r = trace \"Next would overflow\" (v-r,c,a,b:bs)\n | otherwise = trace \"Fits. Taking.\" $\n go (r - boatSize b) (c + boatDensity b * boatSize b `div` 2)\n (b : a) bs\n\nnextKayak :: Int -> Int -> Int -> [Boat] -> [Boat] -> [(Int,[Boat])]\nnextKayak v f c bs bs' = do\n guard (f < v)\n trace \"nextKayak: f Int -> Int -> [Boat] -> [Boat] -> [(Int,[Boat])]\nfitCatamaran v f c bs bs' = do\n guard (f < v)\n guard (not (null bs'))\n let ct = head bs'\n guard (boatSize ct == 2)\n trace \"Have candidate catamaran\" (return ())\n traceShow ct (return ())\n k <- take 1 (filter ((== 1) . boatSize) bs)\n trace \"Have kayak to spare\" (return ())\n traceShow k (return ())\n return (c - boatDensity k `div` 2 + boatDensity ct,ct : delete k bs)\n\npairs :: Int -> [Int] -> [(Int,Int,Int)]\npairs !i (x:y:z) = (i,x,2*y `div` x) : pairs (i+1) z\npairs _ [] = []\n\nboatId,boatSize,boatDensity :: Boat -> Int\nboatId (i,_,_) = i\nboatSize (_,s,_) = s\nboatDensity (_,_,d) = d\n"}, {"source_code": "import Data.List\ndefault (Int)\ndata S = S {t::Int, p::Int, number::Int} \nfindSolution (v, v', p') [] sList' = (p', sList')\nfindSolution (v, v', p') sList@(s:ss) sList' = \n\tif v' + t s == v then (p' + p s, s:sList') else\n\t\tif v' + t s < v then findSolution (v, v' + t s, p' + p s) ss (s:sList') else\n\t\tlet {[i1, i2] = map (findIndex (\\s -> t s == 1)) [sList, sList']} in\n\t\tcase (i1, i2) of {(Just i1', Just i2') -> \n\t\t\tif p (sList !! i1') + p (sList' !! i2') < p s then\n\t\t\t\tone2two i2' sList' p' s\n\t\t\telse (p' + p (sList !! i1'), (sList !! i1'):sList');\n\t\t(Nothing, Just i2') -> if p s > p (sList' !! i2') then \n\t\t\t\tone2two i2' sList' p' s\n\t\t\telse (p', sList');\n\t\t(Nothing, Nothing) -> (p', sList')} where \n\t\tone2two i2' sList' p' s = let s'' = sList' !! i2' in\n\t\t\t(p' - p s'' + p s, s:filter ((/= (number s'')) . number) sList')\n\nmain = do { [n, v] <- map read `fmap` (getLine >>= return . words)\n\t; l <- inputArr n 1 []\n\t; let l1 = l `seq` sortBy (\\a b -> compare (average2 b) (average2 a)) l where\n\t\taverage2 a = case t a of {1 -> (p a * 2); _ -> p a}\n\t; let (p', s) = l1 `seq` findSolution (v, 0, 0) l1 []\n\t; print p'\n\t; case s of {[] -> return (); s':ss' -> do {\n\t\t; putStr $! show $ number $ s'\n\t\t; mapM_ (\\n -> putChar ' ' >> (putStr $ show $ number n)) ss'\n\t}}\n\t; putChar '\\n'\n}\n\ninputArr n i s = if i <= n then getLine >>= \\line -> let [t', p'] = map read $ words line in \n\t\tinputArr n (i+1) (S t' p' i : s)\n\telse return s\n\n"}, {"source_code": "import Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Functor ((<$>))\nimport Control.Monad (replicateM)\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [Int] -> (Int, [Int])\nsolve ones twos cap accWt accItems\n | null ones = take' (cap `div` 2) twos\n | null twos = take' cap ones\n | cap < 2 = solve ones [] cap accWt accItems\n | twoOnes <= oneTwo =\n solve ones (tail twos) (cap - 2) (accWt + oneTwo) (snd (head twos) : accItems)\n | otherwise =\n solve (tail ones) twos (cap - 1) (accWt + fst (head ones)) (snd (head ones) : accItems)\n where\n take' n xs = (accWt + leftWt, leftItems ++ accItems)\n where\n leftWt = sum . map fst $ take n xs\n leftItems = map snd $ take n xs\n\n twoOnes = sum . map fst . take 2 $ ones\n oneTwo = fst . head $ twos\n\n\npartition :: [([Int], Int)] -> ([(Int, Int)], [(Int, Int)])\npartition = foldl' partition' ([], [])\n where partition' (acc1, acc2) ([w, v], i) =\n if w == 1 then ((v, i) : acc1, acc2) else (acc1, (v, i) : acc2)\n\nmain :: IO ()\nmain = do\n [n, v] <- map read . words <$> getLine -- n \\leq 10^5, 1 \\leq v \\leq 10^9\n input <- replicateM n (map read . words <$> getLine)\n\n let (ones, twos) = partition $ zip input [1..]\n revSort = sortBy (flip compare `on` fst)\n (cost, items) = solve (revSort ones) (revSort twos) v 0 []\n\n print cost\n putStrLn . unwords . map show $ items\n"}], "negative_code": [{"source_code": "import Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Functor ((<$>))\nimport Control.Monad (replicateM)\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [Int] -> (Int, [Int])\nsolve ones twos cap accWt accItems\n | null ones = take' (cap `div` 2) twos\n | null twos = take' cap ones\n | cap < 2 = solve ones [] cap accWt accItems\n | twoOnes <= oneTwo =\n solve ones (tail twos) (cap - 2) (accWt + oneTwo) (snd (head twos) : accItems)\n | otherwise =\n solve (drop 2 ones) twos (cap - twoCost) (accWt + twoOnes) (map snd (take 2 ones) ++ accItems)\n where\n take' n xs = (accWt + leftWt, leftItems ++ accItems)\n where\n leftWt = sum . map fst $ take n xs\n leftItems = map snd $ take n xs\n\n twoOnes = sum . map fst . take 2 $ ones\n twoCost = length . take 2 $ ones\n oneTwo = fst . head $ twos\n\n\npartition :: [([Int], Int)] -> ([(Int, Int)], [(Int, Int)])\npartition = foldl' partition' ([], [])\n where partition' (acc1, acc2) ([w, v], i) =\n if w == 1 then ((v, i) : acc1, acc2) else (acc1, (v, i) : acc2)\n\nmain :: IO ()\nmain = do\n [n, v] <- map read . words <$> getLine -- n \\leq 10^5, 1 \\leq v \\leq 10^9\n input <- replicateM n (map read . words <$> getLine)\n\n let (ones, twos) = partition $ zip input [1..]\n revSort = sortBy (flip compare `on` fst)\n (cost, items) = solve (revSort ones) (revSort twos) v 0 []\n\n print cost\n putStrLn . unwords . map show $ items\n"}, {"source_code": "import Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Functor ((<$>))\nimport Control.Monad (replicateM)\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [Int] -> (Int, [Int])\nsolve ones twos cap accWt accItems\n | null ones = take' (cap `div` 2) twos\n | null twos = take' cap ones\n | cap < 2 = solve ones [] cap accWt accItems\n | twoOnes <= oneTwo =\n solve ones (tail twos) (cap - 2) (accWt + oneTwo) (snd (head twos) : accItems)\n | otherwise =\n solve (drop 2 ones) twos (cap - 2) (accWt + twoOnes) (map snd (take 2 ones) ++ accItems)\n where\n take' n xs = (accWt + leftWt, leftItems ++ accItems)\n where\n leftWt = sum . map fst $ take n xs\n leftItems = map snd $ take n xs\n\n twoOnes = sum . map fst . take 2 $ ones\n oneTwo = fst . head $ twos\n\n\npartition :: [([Int], Int)] -> ([(Int, Int)], [(Int, Int)])\npartition = foldl' partition' ([], [])\n where partition' (acc1, acc2) ([w, v], i) =\n if w == 1 then ((v, i) : acc1, acc2) else (acc1, (v, i) : acc2)\n\nmain :: IO ()\nmain = do\n [n, v] <- map read . words <$> getLine -- n \\leq 10^5, 1 \\leq v \\leq 10^9\n input <- replicateM n (map read . words <$> getLine)\n\n let (ones, twos) = partition $ zip input [1..]\n revSort = sortBy (flip compare `on` fst)\n (cost, items) = solve (revSort ones) (revSort twos) v 0 []\n\n print cost\n putStrLn . unwords . map show $ items\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n-- http://en.wikipedia.org/wiki/Haskell_features#Examples\n-- http://en.wikibooks.org/wiki/Haskell/More_on_datatypes\n\nimport Data.List\n\ndata Boat =\n\tBoat { t\t:: Int,\n\t\t\tw\t:: Int,\n\t\t\tnum\t:: Int\n\t\t }\n\ncmp :: Boat -> Boat -> Ordering \ncmp a b\n\t| s == 0\t= EQ\n\t| s < 0\t\t= LT\n\t| otherwise\t= GT\n\t\twhere s = (t a) * (w b) - (t b) * (w a)\n\ngreedy :: Int -> [Boat] -> [Boat] -> (Int, [Boat])\ngreedy a [] []\t= (0, [])\ngreedy 0 _ _\t= (0, [])\ngreedy a (h1:tl1) [] = update h1 (greedy (a - 1) tl1 [])\ngreedy 1 [] _\t= (0, [])\ngreedy a [] (h2:tl2) = update h2 (greedy (a - 2) [] tl2)\ngreedy a (h1:tl1) (h2:tl2)\n\t| a == 1\t\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| w1 < (w h2)\t= update h2 (greedy (a - 2) (h1:tl1) tl2)\n\t| null tl1\t\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| otherwise\t\t= update h1 (update (head (tail tl1)) (greedy (a - 2) (tail tl1) (h2: tl2)))\n\t\twhere w1 = firstTwo (h1:tl1)\n\nfirstTwo :: [Boat] -> Int\nfirstTwo [] = 0\nfirstTwo (a:[]) = w a\nfirstTwo (a:b:c) = w a + w b\n\nupdate :: Boat -> (Int, [Boat]) -> (Int, [Boat])\nupdate b (c, d) = (c + (w b), b : d)\n\nprocess :: Int -> [Int] -> [Boat]\nprocess _ [] \t\t\t= []\nprocess n (a : (b : c))\t= (Boat a b n) : (process (n + 1) c)\n\nisSize :: Int -> Boat -> Bool\nisSize n b = n == (t b)\n\nprintAns :: [Boat] -> IO()\nprintAns (a : []) = do\n\tputStr (show (num a))\nprintAns (a : b) = do\n\tputStr (show (num a))\n\tputStr \" \"\n\tprintAns (b)\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet input = map read (words (str))\n\tlet v = head (tail (input))\n\tlet slist = sortBy cmp (process 1 (tail (tail (input))))\n\tlet list1 = filter (isSize 1) slist\n\tlet list2 = filter (isSize 2) slist\n\tlet ans = greedy v list1 list2\n\tputStrLn (show (fst ans))\n\tprintAns (snd ans)\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n-- http://en.wikipedia.org/wiki/Haskell_features#Examples\n-- http://en.wikibooks.org/wiki/Haskell/More_on_datatypes\n\nimport Data.List\n\ndata Boat =\n\tBoat { t\t:: Int,\n\t\t\tw\t:: Int,\n\t\t\tnum\t:: Int\n\t\t }\n\ncmp :: Boat -> Boat -> Ordering \ncmp a b\n\t| s == 0\t= EQ\n\t| s < 0\t\t= LT\n\t| otherwise\t= GT\n\t\twhere s = (t a) * (w b) - (t b) * (w a)\n\ngreedy :: Int -> [Boat] -> [Boat] -> (Int, [Boat])\ngreedy a [] []\t= (0, [])\ngreedy 0 _ _\t= (0, [])\ngreedy a (h1:tl1) [] = update h1 (greedy (a - 1) tl1 [])\ngreedy 1 [] _\t= (0, [])\ngreedy a [] (h2:tl2) = update h2 (greedy (a - 2) [] tl2)\ngreedy a (h1:tl1) (h2:tl2)\n\t| a == 1\t\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| w1 < (w h2)\t= update h2 (greedy (a - 2) (h1:tl1) tl2)\n\t| null tl1\t\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| a == 3 && (w (head tl1) < w h2) = update h1 (update (h2) (greedy 0 tl1 tl2))\n\t| otherwise\t\t= update h1 (update (head tl1) (greedy (a - 2) (tail tl1) (h2: tl2)))\n\t\twhere w1 = firstTwo (h1:tl1)\n\nfirstTwo :: [Boat] -> Int\nfirstTwo [] = 0\nfirstTwo (a:[]) = w a\nfirstTwo (a:b:c) = w a + w b\n\nupdate :: Boat -> (Int, [Boat]) -> (Int, [Boat])\nupdate b (c, d) = (c + (w b), b : d)\n\nprocess :: Int -> [Int] -> [Boat]\nprocess _ [] \t\t\t= []\nprocess n (a : (b : c))\t= (Boat a b n) : (process (n + 1) c)\n\nisSize :: Int -> Boat -> Bool\nisSize n b = n == (t b)\n\nprintAns :: [Boat] -> IO()\nprintAns (a : []) = do\n\tputStrLn (show (num a))\nprintAns (a : b) = do\n\tputStr (show (num a))\n\tputStr \" \"\n\tprintAns (b)\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet input = map read (words (str))\n\tlet v = head (tail (input))\n\tlet slist = sortBy cmp (process 1 (tail (tail (input))))\n\tlet list1 = filter (isSize 1) slist\n\tlet list2 = filter (isSize 2) slist\n\tlet ans = greedy v list1 list2\n\tputStrLn (show (fst ans))\n\tprintAns (snd ans)\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n-- http://en.wikipedia.org/wiki/Haskell_features#Examples\n-- http://en.wikibooks.org/wiki/Haskell/More_on_datatypes\n\nimport Data.List\n\ndata Boat =\n\tBoat { t\t:: Int,\n\t\t\tw\t:: Int,\n\t\t\tnum\t:: Int\n\t\t }\n\ncmp :: Boat -> Boat -> Ordering \ncmp a b\n\t| s == 0\t= EQ\n\t| s < 0\t\t= LT\n\t| otherwise\t= GT\n\t\twhere s = (t a) * (w b) - (t b) * (w a)\n\ngreedy :: Int -> [Boat] -> [Boat] -> (Int, [Boat])\ngreedy a [] []\t= (0, [])\ngreedy 0 _ _\t= (0, [])\ngreedy a (h1:tl1) [] = update h1 (greedy (a - 1) tl1 [])\ngreedy 1 [] _\t= (0, [])\ngreedy a [] (h2:tl2) = update h2 (greedy (a - 2) [] tl2)\ngreedy a (h1:tl1) (h2:tl2)\n\t| a == 1\t\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| w1 < (w h2)\t= update h2 (greedy (a - 2) (h1:tl1) tl2)\n\t| null tl1\t\t= update h1 (greedy (a - 1) tl1 (h2:tl2))\n\t| otherwise\t\t= update h1 (update (head tl1) (greedy (a - 2) (tail tl1) (h2: tl2)))\n\t\twhere w1 = firstTwo (h1:tl1)\n\nfirstTwo :: [Boat] -> Int\nfirstTwo [] = 0\nfirstTwo (a:[]) = w a\nfirstTwo (a:b:c) = w a + w b\n\nupdate :: Boat -> (Int, [Boat]) -> (Int, [Boat])\nupdate b (c, d) = (c + (w b), b : d)\n\nprocess :: Int -> [Int] -> [Boat]\nprocess _ [] \t\t\t= []\nprocess n (a : (b : c))\t= (Boat a b n) : (process (n + 1) c)\n\nisSize :: Int -> Boat -> Bool\nisSize n b = n == (t b)\n\nprintAns :: [Boat] -> IO()\nprintAns (a : []) = do\n\tputStrLn (show (num a))\nprintAns (a : b) = do\n\tputStr (show (num a))\n\tputStr \" \"\n\tprintAns (b)\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet input = map read (words (str))\n\tlet v = head (tail (input))\n\tlet slist = sortBy cmp (process 1 (tail (tail (input))))\n\tlet list1 = filter (isSize 1) slist\n\tlet list2 = filter (isSize 2) slist\n\tlet ans = greedy v list1 list2\n\tputStrLn (show (fst ans))\n\tprintAns (snd ans)\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Int.html\n-- http://en.wikipedia.org/wiki/Haskell_features#Examples\n-- http://en.wikibooks.org/wiki/Haskell/More_on_datatypes\n\nimport Data.List\n\ndata Boat =\n\tBoat { t\t:: Int,\n\t\t\tw\t:: Int,\n\t\t\tnum\t:: Int\n\t\t }\n\ncmp :: Boat -> Boat -> Ordering \ncmp a b\n\t| s == 0\t= EQ\n\t| s < 0\t\t= LT\n\t| otherwise\t= GT\n\t\twhere s = (t a) * (w b) - (t b) * (w a)\n\ngreedy :: Int -> [Boat] -> (Int, [Boat])\ngreedy a [] = (0, [])\ngreedy a (h:tl)\n\t| a == 0\t\t\t\t= (0, [])\n\t| a == 1 && (t h) == 2\t= greedy a tl\n\t| otherwise\t\t\t\t= update (w h) h (greedy (a - (t h)) tl)\n\nupdate :: Int -> Boat -> (Int, [Boat]) -> (Int, [Boat])\nupdate a b (c, d) = (c + a, b : d)\n\nprocess :: Int -> [Int] -> [Boat]\nprocess _ [] \t\t\t= []\nprocess n (a : (b : c))\t= (Boat a b n) : (process (n + 1) c)\n\nprintAns :: [Boat] -> IO()\nprintAns (a : []) = do\n\tputStr (show (num a))\nprintAns (a : b) = do\n\tputStr (show (num a))\n\tputStr \" \"\n\tprintAns (b)\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet input = map read (words (str))\n\tlet v = head (tail (input))\n\tlet ans = greedy v (sortBy cmp (process 1 (tail (tail (input)))))\n\tputStrLn (show (fst ans))\n\tprintAns (snd ans)\n"}, {"source_code": "module Main (main) where\n\nimport qualified Data.List as L\n\nreadInt :: String ->Int\nreadInt = read\n\nreadPair l = map readInt (words l)\n\nmain :: IO ()\nmain = do\n instr <- getLine\n let [n, v] = readPair instr\n instr <- getContents\n let lodki = zip (map readPair (take n (lines instr))) [1..n]\n printResult $ solve n v lodki\n where\n \n printResult res = do\n print $ sum (map (\\(w, n) -> w) res)\n printWhile res where\n printWhile [] = return ()\n printWhile (x:xs) = putStr $ (show (snd x)) ++ \" \"\n\n solve n v lodki = findMax (reverse (take fitCatam catam)) \n (take fitBayd bayd) \n (drop fitBayd bayd) where\n \n findMax [] bs _ = bs\n findMax cs bs [] = cs ++ bs\n findMax (c:cs) bs [one] = if (fst one) > (fst c)\n then findMax cs (one:bs) []\n else findMax (c:cs) bs []\n findMax (c:cs) bs (one:two:oth) = if ((fst one) + (fst two)) > (fst c)\n then findMax cs (one:two:bs) oth\n else findMax (c:cs) bs []\n \n bayd = filterLodok 1\n baydLen = length bayd\n \n catam = filterLodok 2\n catamLen = length catam\n \n fitCatam = min (div v 2) catamLen\n fitBayd = min (v - (fitCatam * 2)) baydLen\n \n filterLodok tp = L.sortBy (\\a b -> compare b a) $ \n map (\\([_,w],n) -> (w,n)) $ \n filter (\\([t,w],n) -> t == tp) lodki\n\n"}, {"source_code": "\nimport List (sortBy, partition)\n\n{-\nimport HUnit\n\ntestEmpty = Test \"TestEmpty\" $ assertEq [] (solve 1 1 [(2,1)])\n\ntestOne = Test \"TestOne\" $ assertEq [(1,1,[1])] (solve 1 1 [(1,1)])\n\ntestInput = Test \"TestInput\" $ assertEq [(2,7,[2])] (solve 3 2 [(1,2),(2,7),(1,3)])\n\ntestDifficultChoose = Test \"TestDifficultChoose\" $\n assertEq [(2, 13, [3, 4]), (1, 5, [5])] (solve 5 3 [(2,1), (2,12), (1,7), (1,6), (1,5)])\n\ntest = mapM_ run\n [\n testEmpty,\n testOne,\n testInput,\n testDifficultChoose\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: Int -> Int -> [(Int, Int)] -> [(Int, Int, [Int])]\nsolve n k xs = solve' k catamaransAndBoatSort\n where\n xsWithNumbers = zipWith (\\(v,c) n -> (v, c, [n])) xs [1..n]\n (catamarans, boats) = partition (\\(v, _, _) -> v == 2) xsWithNumbers\n boatsSort = sortBy (\\(_, c1, _) (_, c2, _) -> compare c2 c1) boats\n boats' = if odd $ length boats then [last boatsSort] else []\n catamaransAndBoat = boats' ++ getCatamaran boatsSort ++ catamarans\n getCatamaran ((_, c1, n1):(_, c2, n2):bs) = (2, c1+c2, n1 ++ n2) : getCatamaran bs\n getCatamaran _ = []\n catamaransAndBoatSort = sortBy (\\(_, c1, _) (_, c2, _) -> compare c2 c1) catamaransAndBoat\n solve' k [] = []\n solve' k ((v, c, num):bs)\n | k >= v = (v, c, num) : solve' (k-v) bs\n | otherwise = solve' k bs\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [x, y] <- getLine >>= return . map read . words\n return (x, y)\n\nprintAns :: [(Int, Int, [Int])] -> IO ()\nprintAns ans = do\n let res = sum $ map (\\(_, c, _) -> c) ans\n print res\n printAns' ans\n where\n printAns' [] = return ()\n printAns' ((_, _, [n]) : ans) = putStr (concat [show n, \" \"]) >> printAns' ans\n printAns' ((_, _, [n, m]) : ans) = putStr (concat [show n, \" \", show m, \" \"]) >> printAns' ans\n\nmain :: IO ()\nmain = do\n (n, v) <- getPair\n boats <- mapM (const getPair) [1..n]\n printAns $ solve n v boats\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nr = do\n l <- B.getLine\n let Just (a,l') = B.readInt l\n Just (b,_) = B.readInt (B.tail l')\n return (a,b)\nf ((a,b),c) = (b,c)\nmain = do\n (n,v) <- r\n (ks,cs) <- liftM (partition ((==1) . fst . fst) . flip zip [1..]) (replicateM n r)\n let cp = uncurry (flip delete) $\n solve v (sortBy (flip compare) $ map f ks) \n (sortBy (flip compare) $ map f cs)\n [] (0,10^15)\n print $ sum $ map fst cp\n putStrLn $ unwords $ map (show . snd) cp\nsolve 0 _ _ vs _ = (vs,(0,0))\nsolve 1 (k:_) (c:_) vs p = if fst c - fst p > fst k\n then ((c:vs),p)\n else ((k:vs),(0,0))\nsolve 1 _ (c:_) vs p | fst c > fst p = ((c:vs),p)\nsolve 2 (k1:k2:_) (c:_) vs _ = if fst k1 + fst k2 > fst c\n then ((k1:k2:vs),(0,0))\n else ((c:vs),(0,0))\nsolve _ [] [] vs _ = (vs,(0,0))\nsolve v (k:ks) [] vs _ | v >= 1 = solve (v-1) ks [] (k:vs) k\nsolve v [] (c:cs) vs p | v >= 2 = solve (v-2) [] cs (c:vs) p\n | otherwise = (vs,(0,0))\nsolve v (k:ks) (c:cs) vs p = if 2*fst k > fst c\n then solve (v-1) ks (c:cs) (k:vs) k\n else solve (v-2) (k:ks) cs (c:vs) p\n"}, {"source_code": "import Data.List\nimport Control.Monad\nr = liftM (map read . words) getLine >>= \\[a,b] -> return (a,b)\nf ((a,b),c) = (b,c)\nmain = do\n (n,v) <- r\n (ks,cs) <- liftM (partition ((==1) . fst . fst) . flip zip [1..]) (replicateM n r)\n let cp = solve v (sortBy (flip compare) $ map f ks) \n (sortBy (flip compare) $ map f cs)\n print $ sum $ map fst cp\n putStrLn $ unwords $ map (show . snd) cp\nsolve 0 _ _ = []\nsolve _ [] [] = []\nsolve v (k:ks) [] | v >= 1 = k : solve (v-1) ks []\nsolve v [] (c:cs) | v >= 2 = c : solve (v-2) [] cs\n | otherwise = []\nsolve 2 (k1:k2:_) (c:_) = if fst k1 + fst k2 > fst c then [k1,k2] else [c]\nsolve v (k:ks) (c:cs) = if 2*fst k > fst c\n then k : solve (v-1) ks (c:cs)\n else c : solve (v-2) (k:ks) cs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Ord (comparing)\nimport Data.List (sortBy,delete)\nimport Control.Arrow (second)\nimport Control.Monad (guard)\n-- import Debug.Trace\n\ntrace = curry snd\ntraceShow = curry snd\ntr x = traceShow x x\n\nmain :: IO ()\nmain = do\n [n,v] <- fmap (map read . words) getLine\n bs <- fmap (sortBy (flip $ comparing boatDensity) . pairs 1 . map read . words) getContents\n let (f,c,bs0,bs0') = tr $ greedy v bs\n (rc,rbs) = maximum $\n (c,map boatId bs0) :\n map (second (map boatId)) (\n nextKayak v f c bs0 bs0' ++\n fitCatamaran v f c bs0 :: [(Int,[Boat])]\n )\n :: (Int,[Int])\n print rc\n putStrLn $ unwords $ map show rbs\n\ntype Boat = (Int,Int,Int)\ngreedy :: Int -> [Boat] -> (Int,Int,[Boat],[Boat])\ngreedy v bs = go v 0 [] bs where\n go r c a bs | traceShow (r,c,a,bs) False = undefined\n go r c a [] = trace \"Exhausted list\" (v-r,c,a,[])\n go r c a (b:bs)\n | boatSize b > r = trace \"Next would overflow\" (v-r,c,a,b:bs)\n | otherwise = trace \"Fits. Taking.\" $\n go (r - boatSize b) (c + boatDensity b * boatSize b `div` 2)\n (b : a) bs\n\nnextKayak :: Int -> Int -> Int -> [Boat] -> [Boat] -> [(Int,[Boat])]\nnextKayak v f c bs bs' = do\n guard (f < v)\n trace \"nextKayak: f Int -> Int -> [Boat] -> [(Int,[Boat])]\nfitCatamaran v f c bs = do\n guard (f < v)\n k <- take 1 (filter ((== 1) . boatSize) bs)\n guard (not (null bs))\n let ct = head bs\n guard (boatSize ct == 2)\n return (c - boatDensity k `div` 2 + boatDensity ct,ct : delete k bs)\n\npairs :: Int -> [Int] -> [(Int,Int,Int)]\npairs !i (x:y:z) = (i,x,2*y `div` x) : pairs (i+1) z\npairs _ [] = []\n\nboatId,boatSize,boatDensity :: Boat -> Int\nboatId (i,_,_) = i\nboatSize (_,s,_) = s\nboatDensity (_,_,d) = d\n"}, {"source_code": "import Data.Ord\nimport Data.List\nmain = interact $ unlines . solve . map read . words\nsolve (n:v:xs) = go is 0 v [] where\n is = sortBy (flip $ comparing (snd . snd)) $ zip [1..] $ parse xs\n go is c w bs | null is || w == 0 = present c bs\n go ((_,(2,d)):is) c 1 bs = go is c 1 bs\n go ((b,(t,d)):is) c w bs = go is (c + t*d`div`2) (w-t) (b:bs)\n present c bs = [show c,unwords (map show bs)]\nparse (t:p:xs) = (t,2*p`div`t) : parse xs\nparse [] = []\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Ord (comparing)\nimport Data.List (sortBy,delete)\nimport Control.Arrow (second)\nimport Control.Monad (guard)\n-- import Debug.Trace\n\ntrace = curry snd\ntraceShow = curry snd\ntr x = traceShow x x\n\nmain :: IO ()\nmain = do\n [n,v] <- fmap (map read . words) getLine\n bs <- fmap (sortBy (flip $ comparing boatDensity) . pairs 1 . map read . words) getContents\n let (f,c,bs0,bs0') = tr $ greedy v bs\n (rc,rbs) = maximum $\n (c,map boatId bs0) :\n map (second (map boatId)) (\n nextKayak v f c bs0 bs0' ++\n fitCatamaran v f c bs0 :: [(Int,[Boat])]\n )\n :: (Int,[Int])\n print rc\n putStrLn $ unwords $ map show rbs\n\ntype Boat = (Int,Int,Int)\ngreedy :: Int -> [Boat] -> (Int,Int,[Boat],[Boat])\ngreedy v bs = go v 0 [] bs where\n go r c a bs | traceShow (r,c,a,bs) False = undefined\n go r c a [] = trace \"Exhausted list\" (v-r,c,a,[])\n go r c a (b:bs)\n | boatSize b > r = trace \"Next would overflow\" (v-r,c,a,b:bs)\n | otherwise = trace \"Fits. Taking.\" $\n go (r - boatSize b) (c + boatDensity b `div` boatSize b)\n (b : a) bs\n\nnextKayak :: Int -> Int -> Int -> [Boat] -> [Boat] -> [(Int,[Boat])]\nnextKayak v f c bs bs' = do\n guard (f < v)\n trace \"nextKayak: f Int -> Int -> [Boat] -> [(Int,[Boat])]\nfitCatamaran v f c bs = do\n guard (f < v)\n k <- take 1 (filter ((== 1) . boatSize) bs)\n guard (not (null bs))\n let ct = head bs\n guard (boatSize ct == 2)\n return (c - boatDensity k `div` 2 + boatDensity ct,ct : delete k bs)\n\npairs :: Int -> [Int] -> [(Int,Int,Int)]\npairs !i (x:y:z) = (i,x,x*y) : pairs (i+1) z\npairs _ [] = []\n\nboatId,boatSize,boatDensity :: Boat -> Int\nboatId (i,_,_) = i\nboatSize (_,s,_) = s\nboatDensity (_,_,d) = d\n"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-3) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCost1+1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) vehicals2\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile)\nimport Data.Ord(comparing)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume) $ scanl1 (+) $ map cost vehicals\n chooseVehicals = take pos vehicals\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanr, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-3) $ scanr (+) 0 $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCost1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) vehicals2\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show volume : []--show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n --pos = length $ takeWhile (<=volume-3) $ scanl1 (+) $ map cost vehicals\n --(chooseVehicals1, remain) = splitAt pos vehicals\n --totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n --vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume*2-totalCost1*2) $ filter (\\x->cost x==1) remain)\n --chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n chooseVehicals = chooseVehicalsRemain volume vehicals\n totalCapacity = scanl1 (+) $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v && (foldr (+) 0 $ map cost x) >= v-1]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-2) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume*2-totalCost1*2) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-2) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCost1+1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy, (\\\\))\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show, Eq)\ncompute s = show finalTotalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n --totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n --vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume*2-totalCost1*2) $ filter (\\x->cost x==1) remain)\n --chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n chooseVehicals = if totalCost chooseVehicals1 == volume || null remain\n then chooseVehicals1\n else adjustVehicals chooseVehicals1 remain\n finalTotalCapacity = totalCapacity chooseVehicals\n\ntotalCost = (foldr (+) 0).(map cost)\ntotalCapacity = (foldr (+) 0).(map capacity)\n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v && (foldr (+) 0 $ map cost x) >= v-1]\n\nadjustVehicals chooseVehicals1 remain = (chooseVehicals1 \\\\ (lastCost1 ++ lastCost2)) ++ chooseVehicalsRemain v competeVehicals\n where lastCost1 = take 1 $ filter (\\x->cost x==1) $ reverse chooseVehicals1\n lastCost2 = take 1 $ filter (\\x->cost x==2) $ reverse chooseVehicals1\n nextCost1 = take 3 $ filter (\\x->cost x==1) $ remain\n nextCost2 = take 1 $ filter (\\x->cost x==2) $ remain\n competeVehicals = lastCost1 ++ lastCost2 ++ nextCost1 ++ nextCost2\n v = 1 + totalCost lastCost1 + totalCost lastCost1\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show volume : []--show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n --pos = length $ takeWhile (<=volume-3) $ scanl1 (+) $ map cost vehicals\n --(chooseVehicals1, remain) = splitAt pos vehicals\n --totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n --vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume*2-totalCost1*2) $ filter (\\x->cost x==1) remain)\n --chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n chooseVehicals = chooseVehicalsRemain volume vehicals\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v && (foldr (+) 0 $ map cost x) >= v-1]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-2) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCost1+1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) vehicals2\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanr, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-2) $ scanr (+) 0 $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCost1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) vehicals2\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl1, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-3) $ scanl1 (+) $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume*2-totalCost1*2) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanr, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-3) $ scanr (+) 0 $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCapacity1 = foldr (+) 0 $ map capacity chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCapacity1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCapacity1) vehicals2\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanr, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-2) $ scanr (+) 0 $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCapacity1 = foldr (+) 0 $ map capacity chooseVehicals1\n vehicals2 = (take 1 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCapacity1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCapacity1) vehicals2\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "import Data.List.Split(splitOneOf, chunksOf)\nimport Data.List(sortBy, scanl, takeWhile, subsequences, maximumBy)\nimport Data.Ord(comparing)\nimport Data.Function(on)\n\ndata Vehical = Vehical {no::Int, cost::Int, capacity::Int, ratio::Float} deriving (Show)\ncompute s = show totalCapacity : map (show.no) chooseVehicals\n where nums = map read $ splitOneOf \" \\n\" s\n volume = head.tail $ nums\n vehicals = sortBy (comparing ratio) [Vehical n t p (fromIntegral t/fromIntegral p)| (n, [t, p])<-zip [1..] $ chunksOf 2 $ drop 2 nums]\n pos = length $ takeWhile (<=volume-2) $ scanl (+) 0 $ map cost vehicals\n (chooseVehicals1, remain) = splitAt pos vehicals\n totalCost1 = foldr (+) 0 $ map cost chooseVehicals1\n vehicals2 = (take 2 $ filter (\\x->cost x==2) remain) ++ (take (volume-totalCost1+1) $ filter (\\x->cost x==1) remain)\n chooseVehicals = chooseVehicals1 ++ chooseVehicalsRemain (volume-totalCost1) remain\n totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n --chooseVehicals = chooseVehicalsRemain volume vehicals\n --totalCapacity = foldr (+) 0 $ map capacity chooseVehicals\n \n \nchooseVehicalsRemain:: Int->[Vehical]->[Vehical]\nchooseVehicalsRemain v vehicals = maximumBy (compare `on` ((foldr (+) 0).(map capacity))) $ [x | x<-subsequences vehicals, (foldr (+) 0 $ map cost x) <= v]\n\nmain = interact $unlines.compute"}, {"source_code": "{-# LANGUAGE BangPatterns #-} \nimport Numeric\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead !s = case readDec s of [(n, \"\")] -> n\n\ndata Boat = One Int Int | Two Int Int deriving (Eq, Ord)\n\nmakeBoat n [1, x] = One x n\nmakeBoat n [2, x] = Two x n\n\n\neven' s1 s2 v = fill s1 s2 v []\n\nodd' [] s2 v = fill [] s2 v []\nodd' (s:ss) s2 v = fill ss s2 (v-1) [s]\n\nfill :: [Boat] -> [Boat] -> Int -> [Boat] -> [Boat]\nfill [] [] _ a = a\nfill _ _ 0 a = a\nfill (o:os) [] x a = fill os [] (x - 1) (o:a)\nfill [] _ 1 a = a\nfill [] (t:ts) x a = fill [] ts (x - 2) (t:a)\nfill unos@(aa@(One a _):bb@(One b _):ones) dos@(cc@(Two c _):twos) x acc =\n if a + b > c\n then fill ones dos (x - 2) (aa:bb:acc)\n else fill unos twos (x - 2) (cc:acc)\nfill [aa@(One a _)] dos@(cc@(Two c _):twos) x acc =\n if a > c\n then fill [] dos (x - 1) (aa:acc)\n else fill [aa] twos (x - 2) (cc:acc)\n\nsolve :: Int -> [Boat] -> (Int, [Int])\nsolve v boats =\n foldBoats $ case v `mod` 2 of\n 0 -> even' s1 s2 v\n 1 -> odd' s1 s2 v\n where\n p (One _ _) = True\n p (Two _ _) = False\n (b1, b2) = partition p boats\n (s1, s2) = (reverse $ sort b1, reverse $ sort b2)\n value (One x _) = x\n value (Two x _) = x\n no (One _ x) = x\n no (Two _ x) = x\n foldBoats = mapAccumL (\\a h-> (a + value h, no h)) 0 \n \nmain = do\n [n, v] <- getLine >>= (return . map fastRead . words)\n things <- forM [1..n] (\\n -> getLine >>= (return . makeBoat n . map fastRead . words))\n let (res, boats) = solve v things\n print res\n forM_ boats (\\b -> putStr $ show b)\n"}], "src_uid": "a1f98b06650a5755e784cd6ec6f3b211"} {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Array\nimport Data.Char\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nsolve [t, b, e] = sum $ map S.size ss\n where\n len = BS.length\n [n, m] = map len [b, e]\n xs = BS.findSubstrings b t\n ys = map (+m) $ BS.findSubstrings e t\n\n h = listArray (0,len t) $ scanl g 0 (BS.unpack t)\n -- Int qualification gave ~3x speed up on codeforces\n where g x c = x*31 + (fI $ ord c) :: Int\n\n -- subsequences\n ss = [S.fromList $ f l xs ys | l <- [max n m .. len t]]\n\n f l (x:xs) (y:ys)\n | x + l < y = f l xs (y:ys)\n | x + l > y = f l (x:xs) ys\n | otherwise = (h!y - h!x * 31^l) : f l xs ys\n f _ _ _ = []\n\n --ss = [S.fromList $ f' l 0 0 | l <- [max n m .. len t]]\n\n [u, v] = map length [xs, ys]\n xs' = listArray (0,u-1) xs\n ys' = listArray (0,v-1) ys\n\n f' l i j\n | i == u = []\n | j == v = []\n | x + l < y = f' l (i+1) j\n | x + l > y = f' l i (j+1)\n | otherwise = (h!y - h!x * 31^l) : f' l (i+1) (j+1)\n where x = xs'!i\n y = ys'!j\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n forM_ (splitEvery 3 ws) $\n print . solve\n\nreadNum = fst . fromJust . BS.readInteger\nfI = fromIntegral\n--- debug = flip trace\ntraceShow = trace . show\ndebug = flip traceShow\ninfixr 1 `debug2`\ndebug2 x msg = flip trace x (printf \"%s: %s\" msg $ show x)\n\ninfixr 1 ?\nTrue ? x = const x\nFalse ? _ = id\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt (fI n) xs\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Ord\nimport qualified Data.Set as Set\n\ndata Parsing a = Parsing \n (Maybe ((a -> Bool), (Parsing a))) -- success\n (Parsing a) -- fallback\n\nstepParser ch (Parsing (Just (b, p)) _) | b ch = p\nstepParser ch (Parsing _ fallback) = stepParser ch fallback\n\nmkParsing :: Eq a => Parsing a -- alternative parsing\n -> [a] -- primary parsing\n -> Parsing a\nmkParsing prev [] = (Parsing Nothing prev)\nmkParsing prev (ch:t) = Parsing (Just ((ch==), mkParsing (stepParser ch prev) t)) prev\n\nparser str = p where p = mkParsing (Parsing (Just (const True, p)) undefined) str\n\nparsed (Parsing Nothing _) = True\nparsed _ = False\n\nconsumeOne ((h,t), p) = (t, stepParser h p)\n\nensureHeaded :: ([a], Parsing a) -> [((a, [a]), Parsing a)]\nensureHeaded (h : t, p) = [((h, t), p)]\nensureHeaded _ = []\n\nccNext :: Ord a => [([a], Parsing a)] -> [(a, [([a], Parsing a)])]\nccNext strs = map (\\l -> (fst(fst(head l)), map consumeOne l)) $ groupBy ((==) `on` (fst . fst)) . sortBy (comparing (fst . fst)) $ (strs >>= ensureHeaded)\n\nccStep :: Ord a => [([a], Parsing a)] -> (Bool, [(a, [([a], Parsing a)])])\nccStep strs = (any (parsed . snd) strs, ccNext strs)\n\ncc :: Ord a => Int -> [([a], Parsing a)] -> Int\ncc skips strs = (if i && skips<=0 then 1 else 0) + sum (map (\\(a,l) -> (cc (skips-1) l)) next) where\n (i, next) = ccStep strs\n\ncnt prefix suffix str = cc (length prefix) (map (\\s -> (s, ps)) $ (filter (prefix `isPrefixOf`) (tails str)))\n where\n ps = parser suffix\n\ns[q,a,b]=cnt a b q\nmain = interact$show.s.words\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Word\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n t <- readString\n sBegin <- readString\n sEnd <- readString\n return (t, sBegin, sEnd)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nmagic :: Word64\nmagic = 0xa2facedead -- wish not to be hacked\n\nhash :: Word64 -> Char -> Word64\nhash v ch = v * magic + fromIntegral (ord ch)\n\nsolve (t, sBegin, sEnd) = sum $ map solveLen [gap..len]\n where\n pBegin = BS.findSubstrings sBegin t\n pEnd = BS.findSubstrings sEnd t\n\n len = BS.length t\n lBegin = BS.length sBegin\n lEnd = BS.length sEnd\n\n gap = lBegin `max` lEnd\n\n vBegin = accumArray (||) False (0, len) [(p, True) | p <- pBegin] :: UArray Int Bool\n vEnd = accumArray (||) False (0, len) [(p + lEnd, True) | p <- pEnd] :: UArray Int Bool\n\n prefixHash = listArray (0, len) $ scanl hash 0 (BS.unpack t) :: UArray Int Word64\n\n solveLen l = length $ group $ sort hashes\n where\n magicl = magic ^ l\n hashes = [ (prefixHash ! (s + l)) - (prefixHash ! s) * magicl\n | s <- [0..len - l]\n , vBegin ! s && vEnd ! (s + l)\n ]\n \n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport List\nimport Array\nimport Char\nmain=BS.getContents>>=print.s.BS.words\nm v c=v*97+fromIntegral(ord c)::Int\ns[t,b,e]=sum[length$group$sort$g i x y|i<-[max u v..w]]\n where\n x=BS.findSubstrings b t\n y=map(+v)$BS.findSubstrings e t\n u=BS.length b\n v=BS.length e\n w=BS.length t\n h=listArray(0,w)$scanl m 0(BS.unpack t)\n g l(x:xs)(y:ys)\n |x+ly=g l(x:xs)ys\n |1>0=(h!y-h!x*97^l):g l xs ys\n g l _ _=[]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Array\nimport Data.Char\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nsolve [t, b, e] = sum $ map S.size ss\n where\n len = BS.length\n [n, m] = map len [b, e]\n xs = BS.findSubstrings b t\n ys = map (+m) $ BS.findSubstrings e t\n [u, v] = map length [xs, ys]\n xs' = listArray (0,u-1) xs\n ys' = listArray (0,v-1) ys\n\n h = listArray (0,len t) $ scanl g 0 (BS.unpack t)\n where g x c = x*31 + (fI $ ord c)\n\n --ss = [S.fromList $ f l xs ys | l <- [max n m .. len t]]\n ss = [S.fromList $ f' l 0 0 | l <- [max n m .. len t]]\n\n f l (x:xs) (y:ys)\n | x + l < y = f l xs (y:ys)\n | x + l > y = f l (x:xs) ys\n | otherwise = (h!y - h!x * 31^l) : f l xs ys\n f _ _ _ = []\n\n f' l i j\n | i == u = []\n | j == v = []\n | x + l < y = f' l (i+1) j\n | x + l > y = f' l i (j+1)\n | otherwise = (h!y - h!x * 31^l) : f' l (i+1) (j+1)\n where x = xs'!i\n y = ys'!j\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n forM_ (splitEvery 3 ws) $\n print . solve\n\nreadNum = fst . fromJust . BS.readInteger\nfI = fromIntegral\n--- debug = flip trace\ntraceShow = trace . show\ndebug = flip traceShow\ninfixr 1 `debug2`\ndebug2 x msg = flip trace x (printf \"%s: %s\" msg $ show x)\n\ninfixr 1 ?\nTrue ? x = const x\nFalse ? _ = id\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt (fI n) xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Array\nimport Data.Char\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nsolve [t, b, e] = sum $ map length ss\n where\n len = BS.length\n [n, m] = map len [b, e]\n xs = BS.findSubstrings b t\n ys = map (+m) $ BS.findSubstrings e t\n\n h = listArray (0,len t) $ scanl g 0 (BS.unpack t)\n -- Int qualification gave ~3x speed up on codeforces\n where g x c = x*31 + (fI $ ord c) :: Int\n\n -- subsequences\n --ss = [S.fromList $ f l xs ys | l <- [max n m .. len t]]\n ss = [group . sort $ f l xs ys | l <- [max n m .. len t]]\n\n f l (x:xs) (y:ys)\n | x + l < y = f l xs (y:ys)\n | x + l > y = f l (x:xs) ys\n | otherwise = (h!y - h!x * 31^l) : f l xs ys\n f _ _ _ = []\n\n --ss = [S.fromList $ f' l 0 0 | l <- [max n m .. len t]]\n\n [u, v] = map length [xs, ys]\n xs' = listArray (0,u-1) xs\n ys' = listArray (0,v-1) ys\n\n f' l i j\n | i == u = []\n | j == v = []\n | x + l < y = f' l (i+1) j\n | x + l > y = f' l i (j+1)\n | otherwise = (h!y - h!x * 31^l) : f' l (i+1) (j+1)\n where x = xs'!i\n y = ys'!j\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n forM_ (splitEvery 3 ws) $\n print . solve\n\nreadNum = fst . fromJust . BS.readInteger\nfI = fromIntegral\n--- debug = flip trace\ntraceShow = trace . show\ndebug = flip traceShow\ninfixr 1 `debug2`\ndebug2 x msg = flip trace x (printf \"%s: %s\" msg $ show x)\n\ninfixr 1 ?\nTrue ? x = const x\nFalse ? _ = id\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt (fI n) xs\n"}, {"source_code": "\nimport Data.List\nimport Data.Function\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.Set as Set\n\ndata Parsing a = Parsing\n (Maybe ((a -> Bool), (Parsing a))) -- success\n (Parsing a) -- fallback\n\nstepParser ch (Parsing (Just (b, p)) _) | b ch = p\nstepParser ch (Parsing _ fallback) = stepParser ch fallback\n\nmkParsing :: Eq a => Parsing a -- alternative parsing\n -> [a] -- primary parsing\n -> Parsing a\nmkParsing prev [] = (Parsing Nothing prev)\nmkParsing prev (ch:t) = Parsing (Just ((ch==), mkParsing (stepParser ch prev) t)) prev\n\nparser str = p where p = mkParsing (Parsing (Just (const True, p)) undefined) str\n\nparsingSucceeded (Parsing Nothing _) = True\nparsingSucceeded _ = False -- really?\n{-parsingSucceeded (Parsing _ Nothing) = False\nparsingSucceeded (Parsing _ (Just fallback)) = parsingSucceeded fallback -}\n\nconsumeOne ((h,t), p) = (t, stepParser h p)\n\nensureHeaded :: ([a], Parsing a) -> [((a, [a]), Parsing a)]\nensureHeaded (h : t, p) = [((h, t), p)]\nensureHeaded _ = []\n\nccNext :: Ord a => [([a], Parsing a)] -> [(a, [([a], Parsing a)])]\nccNext strs = map (\\l -> (fst(fst(head l)), map consumeOne l)) $ groupBy ((==) `on` (fst . fst)) . sortBy (comparing (fst . fst)) $ (strs >>= ensureHeaded)\n\nccStep :: Ord a => [([a], Parsing a)] -> (Bool, [(a, [([a], Parsing a)])])\nccStep strs = (any (parsingSucceeded . snd) strs, ccNext strs)\n\ncc :: Ord a => Int -> [([a], Parsing a)] -> Int\ncc skips strs = (if i && skips<=0 then 1 else 0) + sum (map (\\(a,l) -> (cc (skips-1) l)) next) where\n (i, next) = ccStep strs\n\ncnt prefix suffix str = cc (length prefix) (map (\\s -> (s, ps)) $ (filter (prefix `isPrefixOf`) (tails str)))\n where\n ps = parser suffix\n\ns[q,a,b]=cnt a b q\nmain = interact$qq\nqq=show.s.words\n\n----------------- QuickTest checks --------------\n\nparserGood' :: [Bool] -> [Bool] -> Bool\nparserGood' s1 s2 = parserGood s1 (s1 ++ s2)\n && parserGood s2 (s1 ++ s2)\n && parserGood s1 (s2 ++ s1)\n && parserGood s2 (s2 ++ s1)\n\nparserGood :: [Bool] -> [Bool] -> Bool\nparserGood s1 s2 = if s1 `isSuffixOf` s2 then answer else not answer\n where answer = parsingSucceeded $ foldl (flip stepParser) (parser s1) s2\n\nsolveSlow prefix suffix str = Set.fromList $ [s'|t <- tails str, s' <- inits t, prefix `isPrefixOf` s', suffix `isSuffixOf` s']\n\ncntSlow prefix suffix str = Set.size $ solveSlow prefix suffix str\n\nemptyParserGood s = parsingSucceeded (foldl (flip stepParser) (parser \"\") s)\n\ncntGood' :: [Bool] -> [Bool] -> Bool\ncntGood' x s = cntSlow x x s == cnt x x s\n\ncntGood :: [Bool] -> [Bool] -> [Bool] -> Bool\ncntGood pre suf s = cntSlow pre suf s == cnt pre suf s\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Array\nimport Data.Char\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nsolve [t, b, e] = sum $ map S.size ss\n where\n len = BS.length\n [n, m] = map len [b, e]\n xs = BS.findSubstrings b t\n ys = map (+m) $ BS.findSubstrings e t\n [u, v] = map length [xs, ys]\n xs' = listArray (0,u-1) xs\n ys' = listArray (0,v-1) ys\n\n h = listArray (0,len t) $ scanl g 0 (BS.unpack t)\n where g x c = x*31 + (fI $ ord c)\n\n ss = [S.fromList $ f l xs ys | l <- [max n m .. len t]]\n\n f l (x:xs) (y:ys)\n | x + l < y = f l xs (y:ys)\n | x + l > y = f l (x:xs) ys\n | otherwise = (h!y - h!x * 31^l) : f l xs ys\n f _ _ _ = []\n\n --ss = [S.fromList $ f' l 0 0 | l <- [max n m .. len t]]\n\n f' l i j\n | i == u = []\n | j == v = []\n | x + l < y = f' l (i+1) j\n | x + l > y = f' l i (j+1)\n | otherwise = (h!y - h!x * 31^l) : f' l (i+1) (j+1)\n where x = xs'!i\n y = ys'!j\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n forM_ (splitEvery 3 ws) $\n print . solve\n\nreadNum = fst . fromJust . BS.readInteger\nfI = fromIntegral\n--- debug = flip trace\ntraceShow = trace . show\ndebug = flip traceShow\ninfixr 1 `debug2`\ndebug2 x msg = flip trace x (printf \"%s: %s\" msg $ show x)\n\ninfixr 1 ?\nTrue ? x = const x\nFalse ? _ = id\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt (fI n) xs\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Array\nimport Control.Monad\nimport Debug.Trace (trace)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nsolve [t, b, e] = S.size . S.fromList $ ss\n where\n x = BS.findSubstrings b t\n y = BS.findSubstrings e t\n\n ss = [j-i | i <- x, j <- y, j >= i]\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n forM_ (splitEvery 3 ws) $\n print . solve\n\nreadNum = fst . fromJust . BS.readInteger\nfI = fromIntegral\n--- debug = flip trace\ntraceShow = trace . show\ndebug = flip traceShow\ninfixr 1 `debug2`\ndebug2 x msg = flip trace x (printf \"%s: %s\" msg $ show x)\n\ninfixr 1 ?\nTrue ? x = const x\nFalse ? _ = id\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt (fI n) xs\n"}, {"source_code": "\nimport Data.List\nimport Data.Function\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.Set as Set\n\ndata Parsing = Parsing (Maybe (Char, Parsing)) -- next char\n (Maybe Parsing) -- fallback\n\nparserGood' s1 s2 = parserGood s1 (s1 ++ s2) \n && parserGood s2 (s1 ++ s2)\n && parserGood s1 (s2 ++ s1)\n && parserGood s2 (s2 ++ s1) \n\nparserGood s1 s2 = if s1 `isSuffixOf` s2 then answer else not answer\n where answer = parsingSucceeded $ foldl (flip stepParser) (parser s1) s2\n\nstepParser ch (Parsing (Just (c, p)) _) | c==ch = p\nstepParser ch (Parsing _ (Just fallback)) = stepParser ch fallback\nstepParser _ p = p\n\nmkParsing :: Maybe Parsing -- alternative parsing\n -> String -- primary parsing\n -> Parsing\nmkParsing prev \"\" = (Parsing Nothing prev)\nmkParsing Nothing (ch:t) = p where\n p = Parsing (Just (ch, mkParsing (Just p) t)) Nothing\nmkParsing (Just prev) (ch:t) = Parsing (Just (ch, mkParsing (Just $ stepParser ch prev) t)) (Just prev)\n \nparser str = mkParsing Nothing str\n\nparsingSucceeded (Parsing Nothing _) = True\nparsingSucceeded (Parsing _ Nothing) = False\nparsingSucceeded (Parsing _ (Just fallback)) = parsingSucceeded fallback\n\nconsumeOne ((h,t), p) = (t, stepParser h p)\n\nensureHeaded :: ([a], Parsing) -> [((a, [a]), Parsing)]\nensureHeaded (h : t, p) = [((h, t), p)]\nensureHeaded _ = []\n\nccNext strs = map (map consumeOne) $ groupBy ((==) `on` (fst . fst)) . sortBy (comparing (fst . fst)) $ (strs >>= ensureHeaded)\n\nccStep :: [(String, Parsing)] -> (Int, [[(String, Parsing)]])\nccStep strs = (if any (parsingSucceeded . snd) strs then 1 else 0, ccNext strs)\n where \n\ncc :: [(String, Parsing)] -> Int\ncc strs = i + sum (map cc next) where\n (i, next) = ccStep strs\n\nsolveSlow prefix suffix str = Set.fromList $ [s'|t <- tails str, s' <- inits t, prefix `isPrefixOf` s', suffix `isSuffixOf` s']\n\ncntSlow prefix suffix str = Set.size $ solveSlow prefix suffix str\n\nemptyParserGood s = parsingSucceeded (foldl (flip stepParser) (parser \"\") s)\n\ncntGood pre suf s = cntSlow pre suf s == cnt pre suf s\n\ncnt prefix suffix str = cc (map (\\s -> (s, ps)) $ (filter (prefix `isPrefixOf`) (tails str)))\n where\n ps = parser suffix\n\ns[q,a,b]=cnt a b q\nmain = interact$show.s.words"}, {"source_code": "\nimport Data.List\nimport Data.Function\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.Set as Set\n\ndata Parsing a = Parsing\n (Maybe ((a -> Bool), (Parsing a))) -- success\n (Parsing a) -- fallback\n\nstepParser ch (Parsing (Just (b, p)) _) | b ch = p\nstepParser ch (Parsing _ fallback) = stepParser ch fallback\n\nmkParsing :: Eq a => Parsing a -- alternative parsing\n -> [a] -- primary parsing\n -> Parsing a\nmkParsing prev [] = (Parsing Nothing prev)\nmkParsing prev (ch:t) = Parsing (Just ((ch==), mkParsing (stepParser ch prev) t)) prev\n\nparser str = p where p = mkParsing (Parsing (Just (const True, p)) undefined) str\n\nparsingSucceeded (Parsing Nothing _) = True\nparsingSucceeded _ = False -- really?\n{-parsingSucceeded (Parsing _ Nothing) = False\nparsingSucceeded (Parsing _ (Just fallback)) = parsingSucceeded fallback -}\n\nconsumeOne ((h,t), p) = (t, stepParser h p)\n\nensureHeaded :: ([a], Parsing a) -> [((a, [a]), Parsing a)]\nensureHeaded (h : t, p) = [((h, t), p)]\nensureHeaded _ = []\n\nccNext strs = map (map consumeOne) $ groupBy ((==) `on` (fst . fst)) . sortBy (comparing (fst . fst)) $ (strs >>= ensureHeaded)\n\nccStep :: Ord a => [([a], Parsing a)] -> (Bool, [[([a], Parsing a)]])\nccStep strs = (any (parsingSucceeded . snd) strs, ccNext strs)\n\ncc :: Ord a => [([a], Parsing a)] -> Int\ncc strs = fromEnum i + sum (map cc next) where\n (i, next) = ccStep strs\n\ncnt prefix suffix str = cc (map (\\s -> (s, ps)) $ (filter (prefix `isPrefixOf`) (tails str)))\n where\n ps = parser suffix\n\ns[q,a,b]=cnt a b q\nmain = interact$show.s.words\n\n----------------- QuickTest checks --------------\n\n\nparserGood' s1 s2 = parserGood s1 (s1 ++ s2) \n && parserGood s2 (s1 ++ s2)\n && parserGood s1 (s2 ++ s1)\n && parserGood s2 (s2 ++ s1) \n\nparserGood s1 s2 = if s1 `isSuffixOf` s2 then answer else not answer\n where answer = parsingSucceeded $ foldl (flip stepParser) (parser s1) s2\n\n\n\nsolveSlow prefix suffix str = Set.fromList $ [s'|t <- tails str, s' <- inits t, prefix `isPrefixOf` s', suffix `isSuffixOf` s']\n\ncntSlow prefix suffix str = Set.size $ solveSlow prefix suffix str\n\nemptyParserGood s = parsingSucceeded (foldl (flip stepParser) (parser \"\") s)\n\ncntGood' :: [Bool] -> [Bool] -> Bool\ncntGood' x s = cntSlow x x s == cnt x x s\n\ncntGood pre suf s = cntSlow pre suf s == cnt pre suf s\n"}, {"source_code": "\nimport Data.List\nimport Data.Function\nimport Data.Maybe\n\n-- aaParsing0 = (p1@Just ('a', (p2@Just('a', (Nothing, p2)), p1)), Nothing)\n\ndata Parsing = Parsing (Maybe (Char, Parsing)) -- next char\n (Maybe Parsing) -- fallback\n\nstepParser ch (Parsing (Just (c, p)) _) | c==ch = p\nstepParser ch (Parsing _ (Just fallback)) = stepParser ch fallback\nstepParser _ p = p\n\nmkParsing :: Maybe Parsing -- alternative parsing\n -> String -- primary parsing\n -> Parsing\nmkParsing prev \"\" = (Parsing Nothing prev)\nmkParsing Nothing (ch:t) = p where\n p = Parsing (Just (ch, mkParsing (Just p) t)) Nothing\nmkParsing (Just prev) (ch:t) = Parsing (Just (ch, mkParsing (Just $ stepParser ch prev) t)) (Just prev)\n \nparser str = mkParsing Nothing str\n\nparsingSucceeded (Parsing Nothing _) = True\nparsingSucceeded (Parsing _ Nothing) = False\nparsingSucceeded (Parsing _ (Just fallback)) = parsingSucceeded fallback\n\ncc :: [(String, Parsing)] -> Int\ncc strs = (if any (parsingSucceeded . snd) strs then 1 else 0) + sum (map cc next)\n where \n (nulls, nonNulls) = partition (null.fst) strs\n consumeOne ((h:t), p) = (t, stepParser h p)\n next = map (map consumeOne) $ groupBy ((==) `on` (head . fst)) nonNulls\n\n\ncnt prefix suffix str = cc (map (\\s -> (s, ps)) $ (filter (prefix `isPrefixOf`) (tails str)))\n where\n ps = parser suffix\n\ns[q,a,b]=cnt a b q\nmain = interact$show.s.words"}], "src_uid": "583168dfbaa91b79c623b44b7efee653"} {"source_code": "main :: IO ()\nmain = do\n [n,a,b,c,t] <- fmap (fmap read . words) getLine\n l <- fmap (map read . words) getLine\n let ans = sum(map (\\x -> max a $ a - (t - x) * (b - c)) l)\n print ans\n", "positive_code": [{"source_code": "main = interact $ show . (\\(_:a:b:c:t:xs) -> sum $ map (\\x -> max a $ a - (t - x) * (b - c)) xs) . map read . words"}], "negative_code": [], "src_uid": "281b95c3686c94ae1c1e4e2a18b7fcc4"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.State\nimport Data.Int\n\nimport Data.Array.Unboxed ((!))\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport qualified Data.Array as A\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as AU\nimport qualified Data.List as L\n\nreadInt :: Num a => BS.ByteString -> a\nreadInt bs = case BS.readInt bs of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show bs\n\nreadLines :: IO [BS.ByteString]\nreadLines = BS.lines `fmap` BS.getContents\n\ntype LineReader a = State [BS.ByteString] a\n\ncurrentLine :: LineReader BS.ByteString\ncurrentLine = do\n ls <- get\n let (x, xs) = case ls of\n [] -> error \"No remain lines.\"\n l -> (head l, tail l)\n put xs\n return x\n\nrestLines :: LineReader [BS.ByteString]\nrestLines = do\n xs <- get\n put []\n return xs\n\n\nreadDim :: BS.ByteString -> (Int32, Int32)\nreadDim line =\n let [m, n] = map readInt $ BS.words line in (m, n)\n\nreadHeights :: [BS.ByteString] -> [[Int32]]\nreadHeights = map (map readInt . BS.words)\n\ntype XY = (Int32, Int32)\ntype HM = AU.UArray XY Int32\n\ndata Pair a b = P !a !b\n\ndata Pos = PS {\n lt :: !Int32,\n ge :: !Int32\n}\n\ntoArray :: Int32 -> Int32 -> [[Int32]] -> HM\ntoArray m n hs = AU.listArray ((1, 1), (m, n)) $ mconcat hs\n\ng :: HM -> [XY] -> [Pair XY Pos]\ng arr xys = e $ mconcat $ zipWith f [0..] gs\n where\n gs = L.groupBy (\\x y -> arr ! x == arr ! y) $ L.sortOn (arr!) xys\n numV = fromIntegral $ length gs\n f i = map (flip P p)\n where\n p = PS{lt = i, ge = numV - i}\n\n m !x y = y\n e [] = []\n e (x:xs) = m (m x (e xs)) (x:xs)\n\nsolve :: HM -> A.Array XY Int32\nsolve hs = STA.runSTArray $ do\n answer <- STA.newArray ((1, 1), (n ,m)) (PS 0 0)\n let ua (P x y) = updateAnswer' answer x y\n getNormalPos ua\n getTransPos ua\n STA.mapArray (\\(PS x y) -> x + y) answer\n where\n (_, (n, m)) = AU.bounds hs\n getPos mkXy runDim fixedDim = g hs $ map (mkXy fixedDim) runDim\n\n getNormalPos ua = forM_ [1..n] $ mapM_ ua . getPos (,) [1..m]\n getTransPos ua = forM_ [1..m] $ mapM_ ua . getPos (flip (,)) [1..n]\n\n updateAnswer PS{lt = lt1, ge = ge1} PS{lt = lt2, ge = ge2} =\n PS{lt = max lt1 lt2, ge = max ge1 ge2}\n\n updateAnswer' :: STA.STArray s XY Pos -> XY -> Pos -> ST s ()\n updateAnswer' ans xy new = do\n old <- STA.readArray ans xy\n STA.writeArray ans xy (updateAnswer old new)\n\nmain :: IO ()\nmain = do\n ls <- readLines\n let (answer, _) = flip runState ls $ do\n (n, m) <- readDim <$> currentLine\n hs <- toArray n m . readHeights <$> restLines\n return $ solve hs\n let (_, (n ,m)) = A.bounds answer\n let out = unlines $ flip map [1..n] $ \\i -> unwords $\n flip map [1..m] $ \\j -> show . (answer!) $ (i, j)\n putStrLn out\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\ntype Int2D = Array Int (Array Int Int)\n\nminifyLine line = map (\\h -> Set.findIndex h set + 1) line where\n set = foldl (flip Set.insert) Set.empty line\n\nprocess :: [[Int]] -> Int -> Int -> [[Int]]\nprocess area n m = [ [ solve i j | j <- [1..m] ] | i <- [1..n] ] where\n iLines = map minifyLine area\n jLines = map minifyLine (transpose area)\n iLines' = force $ listArray (1, n) $ map (listArray (1, m)) iLines :: Int2D\n jLines' = force $ listArray (1, m) $ map (listArray (1, n))jLines :: Int2D\n iMaxs = force $ listArray (1, n) $ map maximum iLines :: Array Int Int\n jMaxs = force $ listArray (1, m) $ map maximum jLines :: Array Int Int\n solve i j = max maxI maxJ where\n iOffset = max (jLines' ! j ! i - iLines' ! i ! j) 0\n jOffset = max (iLines' ! i ! j - jLines' ! j ! i) 0\n maxI = iMaxs ! i + iOffset\n maxJ = jMaxs ! j + jOffset\n\nmain = do\n n:m:[] <- getInts\n area <- replicateM n getInts \n printArea $ process area n m\n \nprintArea = printStrs . map (intercalate \" \" . map show) :: [[Int]] -> IO ()\n"}], "negative_code": [], "src_uid": "206861107f0c06d3c8e358a85b9ddd7f"} {"source_code": "import Control.Monad\nimport Data.Bool\n\nanswer :: Integer -> Bool\nanswer n =\n let divnum = div n 2020 in\n (2020 * divnum) <= n && n <= (2021 * divnum)\n\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n i <- read <$> getLine\n putStrLn $ bool \"NO\" \"YES\" $ answer i \n", "positive_code": [{"source_code": "-- Trying to use only ByteString I/O with a state monad this contest\n\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.ByteString.Lazy.Char8 as P\n\ngetSLine :: Monad m => StateT P.ByteString m P.ByteString\ngetSLine = do\n (out, next) <- P.break (== '\\n') <$> get\n put $ P.tail next\n pure out\n\nreadInts :: Monad m => StateT P.ByteString m [Int]\nreadInts = do\n currLine <- getSLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\n-- There has to be a combinator for this. But where?\noutLine :: P.ByteString -> StateT P.ByteString IO ()\noutLine v = StateT $ \\s -> ((), s) <$ P.putStrLn v\n\nmain :: IO ()\nmain = (P.getContents >>=) $ evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n let w = mod (0-n) 2021\n outLine . P.pack $ if n >= w * 2020\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Data.Maybe\r\n\r\nsolve n = mod2020 <= div2020\r\n\twhere\r\n\t\tmod2020 = mod n 2020\r\n\t\tdiv2020 = div n 2020\r\n\r\nplotResult True = putStrLn \"YES\"\r\nplotResult False = putStrLn \"NO\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n x <- readLn :: IO Int\n let d = x `div` 2020\n r = x `mod` 2020\n putStrLn . yesOrNo . (d>=) $ r\n"}, {"source_code": "main = interact $ unlines . map (solve . read) . tail . lines\r\n\r\nsolve n\r\n | n - x * 2020 <= x = \"YES\"\r\n\t| otherwise = \"NO\"\r\n where x = n `div` 2020"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n n <- read <$> getLine :: IO Integer\n putStrLn $ bool \"YES\" \"NO\" $ n `mod` 2020 > n `div` 2020\n"}, {"source_code": "good :: Int -> Bool\r\ngood n \r\n | n < 0 = False\r\n | otherwise = n `mod` 2020 == 0 || good (n - 2021)\r\n \r\nprocess :: [String] -> String\r\nprocess (_ : inp) = unlines $ map solve inp\r\n where solve s = if good (read s :: Int) then \"YES\" else \"NO\"\r\n\r\nmain :: IO ()\r\nmain = interact (process . lines)\r\n"}], "negative_code": [], "src_uid": "3ec1b7027f487181dbdfb12f295f11ae"} {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: String -> String\ncalc [] = []\ncalc ('R':'?':xs) = 'R':(calc ('B':xs))\ncalc ('B':'?':xs) = 'B':(calc ('R':xs))\ncalc ('?':'R':xs) = 'B':(calc ('R':xs))\ncalc ('?':'B':xs) = 'R':(calc ('B':xs))\ncalc ('?':'?':xs) = calc ('?':(calc ('?':xs)))\ncalc ['?'] = ['B']\ncalc (x:xs) = x:(calc xs)\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n unused <- getLine\n line <- getLine\n putStrLn $ calc line\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Control.Monad.Reader (replicateM_)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n colors <- head . C8.words <$> C8.getLine\r\n C8.putStrLn $ solve colors\r\n\r\nsolve :: C8.ByteString -> C8.ByteString\r\nsolve xs\r\n | C8.unpack xs == \"?\" = \"B\"\r\n | countMarks (C8.length xs - 1) xs == 0 = xs\r\n | otherwise = let len = C8.length rr - 1\r\n rr = C8.pack . insertR $ C8.unpack xs\r\n bb = C8.pack . insertB $ C8.unpack xs\r\n in if countImp len rr > countImp len bb\r\n then bb\r\n else rr\r\n\r\ninsertR :: String -> String\r\ninsertR [y] = [y]\r\ninsertR (x:y:xs)\r\n | x == '?' = insertR ('R':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then insertR (x:'R':xs)\r\n else if x == 'R' && y == '?'\r\n then insertR (x:'B':xs)\r\n else x:insertR (y:xs)\r\n\r\ninsertB :: String -> String\r\ninsertB [y] = [y]\r\ninsertB (x:y:xs)\r\n | x == '?' = insertB ('B':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then insertR (x:'R':xs)\r\n else if x == 'R' && y == '?'\r\n then insertR (x:'B':xs)\r\n else x:insertR (y:xs)\r\n\r\ncountImp :: Num p => Int -> C8.ByteString -> p\r\ncountImp 0 _ = 0\r\ncountImp len xs =\r\n if xs `C8.index` len == xs `C8.index` (len - 1) || xs `C8.index` len == '?'\r\n then 1 + countImp (len - 1) xs\r\n else countImp (len - 1) xs\r\n\r\ncountMarks :: Num p => Int -> C8.ByteString -> p\r\ncountMarks (-1) _ = 0\r\ncountMarks len xs = if xs `C8.index` len == '?'\r\n then 1 + countMarks (len - 1) xs\r\n else countMarks (len - 1) xs\r\n{-\r\n>>>solve \"?B\"\r\n\"RB\"\r\n>>>countMarks 1 \"?B\"\r\n1\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n>>>insertR \"?B\"\r\n\"RB\"\r\n\r\n>>>insert\r\nVariable not in scope: insert\r\n\r\n>>>solve \"BR?\" \r\n\"BRB\"\r\n\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf (int *> str)) >>> map (solve >>> C.pack) >>> C.unlines\n\nsolve :: String -> String\nsolve = reverse . tail . scanl fill 'R' . reverse . scanl1 fill\n where\n fill 'R' '?' = 'B'\n fill 'B' '?' = 'R'\n fill _ c = c\n\ntwice :: (a -> a) -> (a -> a)\ntwice f = f . f\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import qualified Data.List\r\nimport qualified Data.Map\r\nimport qualified Data.Set\r\nimport Control.Monad\r\n\r\ncalc :: String -> String\r\ncalc [] = []\r\ncalc ('R':'?':xs) = 'R':(calc ('B':xs))\r\ncalc ('B':'?':xs) = 'B':(calc ('R':xs))\r\ncalc ('?':'R':xs) = 'B':(calc ('R':xs))\r\ncalc ('?':'B':xs) = 'R':(calc ('B':xs))\r\ncalc ('?':'?':xs) = calc ('?':(calc ('?':xs)))\r\ncalc ['?'] = ['B']\r\ncalc (x:xs) = x:(calc xs)\r\n\r\nmain = do\r\n entry <- getLine\r\n let timer = read entry :: Int\r\n forM_ [1..timer] $ \\_ -> do\r\n n <- getLine\r\n array <- getLine\r\n putStrLn $ calc array"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Control.Monad.Reader (replicateM_)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n colors <- head . C8.words <$> C8.getLine\r\n C8.putStrLn $ solve colors\r\n\r\nsolve :: C8.ByteString -> C8.ByteString\r\nsolve xs\r\n | C8.unpack xs == \"?\" = \"B\"\r\n | countImp (C8.length xs - 1) xs == 0 = xs\r\n | countMarks (C8.length xs - 1) xs == 0 = xs\r\n | otherwise = let len = C8.length rr - 1\r\n rr = C8.pack . insertR $ C8.unpack xs\r\n bb = C8.pack . insertB $ C8.unpack xs\r\n in if countImp len rr > countImp len bb\r\n then bb\r\n else rr\r\n\r\ninsertR :: String -> String\r\ninsertR [y] = [y]\r\ninsertR (x:y:xs)\r\n | x == '?' = insertR ('R':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then insertR (x:'R':xs)\r\n else if x == 'R' && y == '?'\r\n then insertR (x:'B':xs)\r\n else x:insertR (y:xs)\r\n\r\ninsertB :: String -> String\r\ninsertB [y] = [y]\r\ninsertB (x:y:xs)\r\n | x == '?' = insertB ('B':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then insertR (x:'R':xs)\r\n else if x == 'R' && y == '?'\r\n then insertR (x:'B':xs)\r\n else x:insertR (y:xs)\r\n\r\ncountImp :: Num p => Int -> C8.ByteString -> p\r\ncountImp 0 _ = 0\r\ncountImp len xs =\r\n if xs `C8.index` len == xs `C8.index` (len - 1) || xs `C8.index` len == '?'\r\n then 1 + countImp (len - 1) xs\r\n else countImp (len - 1) xs\r\n\r\ncountMarks :: Num p => Int -> C8.ByteString -> p\r\ncountMarks (-1) _ = 0\r\ncountMarks len xs = if xs `C8.index` len == '?'\r\n then 1 + countMarks (len - 1) xs\r\n else countMarks (len - 1) xs\r\n{-\r\n>>>solve \"?BB\"\r\n\"RBB\"\r\n>>>countMarks 2 \"?BB\"\r\n1\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n\r\n>>>solve \"BR?\" \r\n\"BRB\"\r\n\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Control.Monad.Reader (replicateM_)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n colors <- head . C8.words <$> C8.getLine\r\n C8.putStrLn $ solve colors\r\n\r\nsolve :: C8.ByteString -> C8.ByteString\r\nsolve xs\r\n | C8.unpack xs == \"?\" = \"B\"\r\n | countImp (C8.length xs - 1) xs == 0 = xs\r\n | countMarks (C8.length xs - 1) xs == 0 = xs\r\n | otherwise = let len = C8.length rr - 1\r\n rr = C8.pack . insertR $ C8.unpack xs\r\n bb = C8.pack . insertB $ C8.unpack xs\r\n in if countImp len rr > countImp len bb\r\n then bb\r\n else rr\r\n\r\ninsertR :: String -> String\r\ninsertR [y] = [y]\r\ninsertR (x:y:xs)\r\n | x == '?' = insertR ('R':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then insertR (x:'R':xs)\r\n else if x == 'R' && y == '?'\r\n then insertR (x:'B':xs)\r\n else x:insertR (y:xs)\r\n\r\ninsertB :: String -> String\r\ninsertB [y] = [y]\r\ninsertB (x:y:xs)\r\n | x == '?' = insertB ('B':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then insertR (x:'R':xs)\r\n else if x == 'R' && y == '?'\r\n then insertR (x:'B':xs)\r\n else x:insertR (y:xs)\r\n\r\ncountImp :: Num p => Int -> C8.ByteString -> p\r\ncountImp 0 _ = 0\r\ncountImp len xs =\r\n if xs `C8.index` len == xs `C8.index` (len - 1) || xs `C8.index` len == '?'\r\n then 1 + countImp (len - 1) xs\r\n else countImp (len - 1) xs\r\n\r\ncountMarks 0 _ = 0\r\ncountMarks len xs = if xs `C8.index` len == '?'\r\n then 1 + countMarks (len - 1) xs\r\n else countMarks (len - 1) xs\r\n{-\r\n>>>solve \"BB?\"\r\n\"BBR\"\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n\r\n>>>solve \"BR?\" \r\n\"BRB\"\r\n\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport Control.Monad.Reader (replicateM_)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n colors <- C8.getLine\r\n C8.putStrLn $ solve colors\r\n\r\nsolve :: C8.ByteString -> C8.ByteString\r\nsolve xs\r\n | xs == \"?\" = \"B\"\r\n | countImp (C8.length xs - 1) xs == 0 = xs\r\n | otherwise = let len = C8.length xs - 2\r\n rr = head . C8.words . C8.pack . insertR $ C8.unpack xs\r\n bb = head . C8.words . C8.pack . insertB $ C8.unpack xs\r\n in if countImp len rr > countImp len bb\r\n then bb\r\n else rr\r\n\r\ninsertR :: String -> String\r\ninsertR [y] = []\r\ninsertR (x:y:xs)\r\n | x == '?' = 'R':insertR ('R':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then 'R':insertR ('R':xs)\r\n else if x == 'R' && y == '?'\r\n then 'B':insertR ('B':xs)\r\n else y:insertR (y:xs)\r\n\r\ninsertB :: String -> String\r\ninsertB [y] = []\r\ninsertB (x:y:xs)\r\n | x == '?' = 'B':insertB ('B':y:xs)\r\n | otherwise = if x == 'B' && y == '?'\r\n then 'R':insertR ('R':xs)\r\n else if x == 'R' && y == '?'\r\n then 'B':insertR ('B':xs)\r\n else y:insertR (y:xs)\r\n\r\ncountImp :: Num p => Int -> C8.ByteString -> p\r\ncountImp 0 _ = 0\r\ncountImp len xs = if xs `C8.index` len == xs `C8.index` (len - 1)\r\n then 1 + countImp (len - 1) xs\r\n else countImp (len - 1) xs\r\n{-\r\n>>>solve \"B\"\r\n\"B\"\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n>>>solve \"?R??RB??B?\"\r\n\"BRBRRBRBBR\"\r\n\r\n\r\n>>>solve \"BR\" \r\n\"BR\"\r\n\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf str) >>> map (solve >>> showB) >>> C.unlines\n\nsolve :: String -> String\nsolve = twice $ reverse . scanl1 fill\n where\n fill 'R' '?' = 'B'\n fill 'B' '?' = 'R'\n fill _ c = c\n\ntwice :: (a -> a) -> (a -> a)\ntwice f = f . f\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "280487a73e6070a7dc7deb44332d6319"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian m _remove = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit :: Num p => Char -> p\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit :: (Eq a, Num a) => a -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary :: (Foldable t, Num a) => p -> t Char -> a\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary :: Integral a => Int -> a -> [Char]\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n", "positive_code": [{"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int\n\n\nbinaryMedian :: Width -> [Byte] -> Byte\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit :: Bit -> Integer\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Integer -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Byte -> Integer\nfromByte = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Integer -> Byte\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nbinaryMedian :: (Int, [String]) -> String\nbinaryMedian (m, _remove) = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (binaryMedian <$> readInput >>= putStrLn)"}, {"source_code": "{- LANGUAGE BANGPATTERNS -}\n\nimport Data.Traversable (for)\nimport Data.Foldable (foldl', for_)\nimport Data.List (sort, unfoldr)\n\nreadBits :: String -> Integer\nreadBits = ($ 0) $ foldl' (\\x y -> case y of\n '0' -> 2*x\n '1' -> 2*x+1\n _ -> error \"bit\"\n )\n\ntoBits :: Int -> Integer -> String\ntoBits k val = reverse . take k $ unfoldr step val where\n step x = case quotRem x 2 of\n (x', 0) -> Just ('0', x')\n (x', 1) -> Just ('1', x')\n _ -> error \"overflow??\"\n\n--mockup to work around small size limits\ndata Seq t\n = Empty\n | Single t\n | Node !Integer (Seq t) (Seq t)\n\nsize :: Seq t -> Integer\nsize Empty = 0\nsize (Single _) = 1\nsize (Node sz _ _) = sz \n\ndeleteAt :: Integer -> Seq t -> Seq t\ndeleteAt k s = case s of\n _ | k < 0 || k >= size s -> s\n Single _ -> Empty\n Node n le ri -> let excess = k - size le in if excess >= 0\n then Node (n-1) le (deleteAt excess ri)\n else Node (n-1) (deleteAt k le) ri\n -- in all cases this is caught by the first pattern, but GHC can't tell that\n Empty -> s\n\noutOfBounds :: t\noutOfBounds = error \"index: out of bounds\"\n\nindex :: Seq t -> Integer -> t\nindex Empty _ = outOfBounds\nindex (Single v) 0 = v\nindex (Single _) _ = outOfBounds\nindex (Node n le ri) k = let excess = k - size le in case () of\n () | k < 0 || k >= n -> outOfBounds\n () | excess < 0 -> index le k\n () | otherwise -> index ri excess\n\nfromFunction :: Integer -> (Integer -> t) -> Seq t\nfromFunction = go 0 where\n go start stop fun = case stop - start of\n len | len < 0 -> error \"fromFunction: negative length\"\n len | len == 0 -> Empty\n len | len == 1 -> Single (fun start)\n len -> Node len (go start mid fun) (go mid stop fun) where\n mid = quot (start + stop) 2\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n for_ [1..t] $ \\_ -> do\n [n, k] <- (map read . words) <$> getLine :: IO [Int]\n let tot = 2 ^ k :: Integer\n removalList <- for [1..n] $ \\_ -> readBits <$> getLine\n let rl = reverse $ sort removalList :: [Integer]\n startSeq = fromFunction tot id :: Seq Integer\n whatsLeft = foldl' (flip deleteAt) startSeq rl :: Seq Integer\n ix = div (tot - fromIntegral (length rl) - 1) 2\n tar = index whatsLeft ix\n putStrLn (toBits k tar)\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.Set as Set\nimport Data.Char\nimport Data.Int\n-- import Debug.Trace\n\n-- debug = flip trace\n\nfromBinary :: String -> Int64\nfromBinary = fromBinary' . reverse\n\nfromBinary' :: String -> Int64\nfromBinary' [] = 0\nfromBinary' (x : xs) = fromIntegral (ord x - ord '0') + (2 * fromBinary' xs)\n\ntoBinary :: Int64 -> Int64 -> String\ntoBinary m = reverse . toBinary' m\n\ntoBinary' :: Int64 -> Int64 -> String\ntoBinary' 0 _ = []\ntoBinary' m x = chr (fromIntegral r + ord '0') : toBinary' (m - 1) q\n where (q, r) = divMod x 2\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : _ <- map read . words <$> getLine :: IO [Int64]\n as <- map fromBinary <$> replicateM (fromIntegral n) getLine\n let ans = solve m n (Set.fromList as)\n putStrLn . toBinary m $ ans\n\nsolve :: Int64 -> Int64 -> Set.Set Int64 -> Int64\nsolve m n as = go lo hi as (div (k + 1) 2)\n where\n lo = 0\n hi = 2 ^ m - 1\n k = 2 ^ m - n\n\ngo :: Int64 -> Int64 -> Set.Set Int64 -> Int64 -> Int64\ngo lo hi as k | lo > hi = error \"Wrong recursion\"\n | k <= leftCount = go lo (mid - 1) left k\n | hasMid = go (mid + 1) hi right (k - leftCount)\n | k == leftCount + 1 = mid\n | otherwise = go (mid + 1) hi right (k - leftCount - 1)\n where\n mid = div (lo + hi) 2\n (left, hasMid, right) = Set.splitMember mid as\n leftSize = fromIntegral $ Set.size left\n leftCount = mid - lo - leftSize -- `debug` unwords\n -- (zipWith\n -- (\\x y -> x ++ \" = \" ++ y ++ \", \")\n -- (words \"lo hi mid k leftCount left right hasMid\")\n -- ( map show [lo, hi, mid, k, mid - lo - leftSize]\n -- ++ map show [left, right]\n -- ++ [show hasMid]\n -- )\n -- )\n\n"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\nimport Data.Bits\nimport qualified Data.Sequence as S\nimport Data.Sequence ((<|), (|>))\nimport Data.Foldable (toList)\n\ntype Str = S.Seq Char\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadStrings :: Int -> IO [Str]\nreadStrings n = replicateM n (S.fromList <$> getLine)\n\npow2Of :: Int -> Integer\npow2Of = shiftL 1\n\ngetMatchingPrefixes :: Int -> Str -> [Str] -> Int\ngetMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)\n\ngetAllowed :: Int -> Int -> Str -> [Str] -> Integer\ngetAllowed m prefSize pref xss = \n pow2Of (m - prefSize) - toInteger (getMatchingPrefixes prefSize pref xss)\n\ngetMedian :: Int -> Int -> [Str] -> Str\ngetMedian n m xss = go medianPos S.empty [1..m] where\n medianPos = (pow2Of m - (toInteger n) + 1) `div` 2\n go _ _ [] = S.empty\n go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where\n allowedNumStrings = getAllowed m prefSize (pref |> '0') xss\n bit = \n if searchSize <= allowedNumStrings then '0'\n else '1'\n newSearchSize = \n if searchSize <= allowedNumStrings then searchSize\n else searchSize - allowedNumStrings\n\nmain = \n readInt >>= \\t ->\n replicateM_ t (\n (map read) . words <$> getLine >>= \\[n, m] ->\n readStrings n >>= \\xss ->\n putStrLn $ toList $ getMedian n m xss\n )"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte width `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian m _remove = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit :: Num p => Char -> p\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit :: (Eq a, Num a) => a -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary :: (Foldable t, Num a) => p -> t Char -> a\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary :: Integral a => Int -> a -> [Char]\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nbinaryMedian :: (Int, [String]) -> String\nbinaryMedian (m, _remove) = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit :: Num p => Char -> p\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit :: (Eq a, Num a) => a -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary :: (Foldable t, Num a) => p -> t Char -> a\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary :: Integral a => Int -> a -> [Char]\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nbinaryMedian :: (Int, [String]) -> String\nbinaryMedian (m, _remove) = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' = \n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit :: Num p => Char -> p\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: (Eq a, Num a) => a -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: [Char] -> Integer\nfromByte = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Integral a => Int -> a -> [Char]\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_, replicateM)\nimport Data.Bits\nimport qualified Data.Sequence as S\nimport Data.Sequence ((<|), (|>))\nimport Data.Foldable (toList)\n\ntype Str = S.Seq Char\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadStrings :: Int -> IO [Str]\nreadStrings n = replicateM n (S.fromList <$> getLine)\n\npow2Of :: Int -> Int\npow2Of = shiftL 1\n\ngetMatchingPrefixes :: Int -> Str -> [Str] -> Int\ngetMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)\n\ngetAllowed :: Int -> Int -> Str -> [Str] -> Int\ngetAllowed m prefSize pref xss = \n pow2Of (m - prefSize) - (getMatchingPrefixes prefSize pref xss)\n\ngetMedian :: Int -> Int -> [Str] -> Str\ngetMedian n m xss = go medianPos S.empty [1..m] where\n medianPos = (pow2Of m - n + 1) `div` 2\n go :: Int -> Str -> [Int] -> Str\n go _ _ [] = S.empty\n go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where\n allowedNumStrings = getAllowed m prefSize (pref |> '0') xss\n bit = \n if searchSize <= allowedNumStrings then '0'\n else '1'\n newSearchSize = \n if searchSize <= allowedNumStrings then searchSize\n else searchSize - allowedNumStrings\n\nmain = \n readInt >>= \\t ->\n replicateM_ t (\n (map read) . words <$> getLine >>= \\[n, m] ->\n readStrings n >>= \\xss ->\n putStrLn $ toList $ getMedian n m xss\n )"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\nimport Data.Bits\nimport qualified Data.Sequence as S\nimport Data.Sequence ((<|), (|>))\nimport Data.Foldable (toList)\n\ntype Str = S.Seq Char\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadStrings :: Int -> IO [Str]\nreadStrings n = replicateM n (S.fromList <$> getLine)\n\npow2Of :: Int -> Int\npow2Of = shiftL 1\n\ngetMatchingPrefixes :: Int -> Str -> [Str] -> Int\ngetMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)\n\ngetAllowed :: Int -> Int -> Str -> [Str] -> Int\ngetAllowed m prefSize pref xss = \n pow2Of (m - prefSize) - (getMatchingPrefixes prefSize pref xss)\n\ngetMedian :: Int -> Int -> [Str] -> Str\ngetMedian n m xss = go medianPos S.empty [1..m] where\n medianPos = (pow2Of m - n + 1) `div` 2\n go :: Int -> Str -> [Int] -> Str\n go _ _ [] = S.empty\n go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where\n allowedNumStrings = getAllowed m prefSize (pref |> '0') xss\n bit = \n if searchSize <= allowedNumStrings then '0'\n else '1'\n newSearchSize = \n if searchSize <= allowedNumStrings then searchSize\n else searchSize - allowedNumStrings\n\nmain = \n readInt >>= \\t ->\n replicateM_ t (\n (map read) . words <$> getLine >>= \\[n, m] ->\n readStrings n >>= \\xss ->\n print $ show (maxBound :: Int)\n --putStrLn $ toList $ getMedian n m xss\n )"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\nimport Data.Bits\nimport qualified Data.Sequence as S\nimport Data.Sequence ((<|), (|>))\nimport Data.Foldable (toList)\n\ntype Str = S.Seq Char\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadStrings :: Int -> IO [Str]\nreadStrings n = replicateM n (S.fromList <$> getLine)\n\npow2Of :: Int -> Int\npow2Of = shiftL 1\n\ngetMatchingPrefixes :: Int -> Str -> [Str] -> Int\ngetMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)\n\ngetAllowed :: Int -> Int -> Str -> [Str] -> Int\ngetAllowed m prefSize pref xss = \n pow2Of (m - prefSize) - (getMatchingPrefixes prefSize pref xss)\n\ngetMedian :: Int -> Int -> [Str] -> Str\ngetMedian n m xss = go medianPos S.empty [1..m] where\n medianPos = (pow2Of m - n - 1) `div` 2\n go :: Int -> Str -> [Int] -> Str\n go _ _ [] = S.empty\n go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where\n allowedNumStrings = getAllowed m prefSize (pref |> '0') xss\n bit = \n if searchSize + 1 <= allowedNumStrings then '0'\n else '1'\n newSearchSize = \n if searchSize + 1 <= allowedNumStrings then searchSize\n else searchSize - allowedNumStrings\n\nmain = \n readInt >>= \\t ->\n replicateM_ t (\n (map read) . words <$> getLine >>= \\[n, m] ->\n readStrings n >>= \\xss ->\n putStrLn $ toList $ getMedian n m xss\n )"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\n-- type Bit = Char\n-- type Byte = [Bit]\n-- type Width = Int -- width of byte\n\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte width `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit :: Char -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Int -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Int -> String -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Int -> Int -> String\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nbinaryMedian :: Width -> [Byte] -> Byte\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte width `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit :: Bit -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Int -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Width -> Byte -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Int -> Byte\ntoByte m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n -- foldl' go \"\" . take m . iterate (`div` 2)\n -- where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nbinaryMedian :: Width -> [Byte] -> Byte\nbinaryMedian m _remove = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit :: Bit -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit :: Int -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary :: Width -> Byte -> Int\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary :: Width -> Int -> Byte\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\n-- binaryMedian :: Width -> [Byte] -> Byte\n-- binaryMedian width _remove = toByte width median'\n-- where\n-- median = 2^(width-1) - 1\n-- remove = fromByte width `map` _remove\n-- (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n-- go (isOdd, med, seen) rem = (isOdd', med', seen') where\n-- isOdd'= not isOdd\n-- seen' = Set.insert rem seen\n-- get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n-- med' =\n-- if not isOdd && rem <= med then get succ\n-- else if isOdd && rem >= med then get pred\n-- else med\nbinaryMedian :: Width -> [Byte] -> String\nbinaryMedian m _remove = toByte m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromByte m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\nfromBit :: Bit -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Int -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Width -> Byte -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Int -> Byte\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nbinaryMedian :: Width -> [Byte] -> Byte\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte width `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen') (iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit :: Bit -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Int -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Width -> Byte -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Int -> Byte\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nbinaryMedian :: Width -> [Byte] -> Byte\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte width `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n -- get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n get f n = let n' = f n in\n if Set.member n' seen\n then get f n'\n else n'\n med' =\n if not isOdd && rem <= med then get succ med\n else if isOdd && rem >= med then get pred med\n else med\n\n\nfromBit :: Bit -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Int -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Width -> Byte -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Int -> Byte\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\n-- binaryMedian :: Width -> [Byte] -> Byte\n-- binaryMedian width _remove = toByte width median'\n-- where\n-- median = 2^(width-1) - 1\n-- remove = fromByte width `map` _remove\n-- (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n-- go (isOdd, med, seen) rem = (isOdd', med', seen') where\n-- isOdd'= not isOdd\n-- seen' = Set.insert rem seen\n-- get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n-- med' =\n-- if not isOdd && rem <= med then get succ\n-- else if isOdd && rem >= med then get pred\n-- else med\nbinaryMedian :: Width -> [Byte] -> String\nbinaryMedian m _remove = toByte m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromByte m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n \n \nfromBit '0' = 0\nfromBit '1' = 1\n \ntoBit 0 = '0'\ntoBit 1 = '1'\n \nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n \ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n \n-- fromBit :: Bit -> Int\n-- fromBit '0' = 0\n-- fromBit '1' = 1\n\n\n-- toBit :: Int -> Bit\n-- toBit 0 = '0'\n-- toBit 1 = '1'\n\n\nfromByte :: Width -> Byte -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Int -> Byte\ntoByte m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n -- foldl' go \"\" . take m . iterate (`div` 2)\n -- where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/H\n\n{-# LANGUAGE TupleSections #-}\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\n\nbinaryMedian :: Width -> [Byte] -> Byte\nbinaryMedian width _remove = toByte width median'\n where\n median = 2^(width-1) - 1\n remove = fromByte width `map` _remove\n (_, median', _) = foldl' go (False, median, Set.empty) remove\n\n go (isOdd, med, seen) rem = (isOdd', med', seen') where\n isOdd'= not isOdd\n seen' = Set.insert rem seen\n get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)\n med' =\n if not isOdd && rem <= med then get succ\n else if isOdd && rem >= med then get pred\n else med\n\n\nfromBit :: Bit -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\n\ntoBit :: Int -> Bit\ntoBit 0 = '0'\ntoBit 1 = '1'\n\n\nfromByte :: Width -> Byte -> Int\nfromByte m = foldl' go 0\n where go num bit = 2*num + fromBit bit\n\n\ntoByte :: Width -> Int -> Byte\ntoByte m = foldl' go \"\" . take m . iterate (`div` 2)\n where go bits k = toBit (k `mod` 2) : bits\n\n\nreadInput :: IO (Width, [Byte])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian m _remove = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit :: Char -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit :: (Eq a, Num a) => a -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary :: p -> String -> Int\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary :: Integral a => Int -> a -> [Char]\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad ( replicateM_ )\nimport Data.List ( foldl' )\nimport qualified Data.Set as Set\n\n\ntype Bit = Char\ntype Byte = [Bit]\ntype Width = Int -- width of byte\n\nbinaryMedian :: Int -> [String] -> String\nbinaryMedian m _remove = toBinary m median\n where\n (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove\n remove = map (fromBinary m) _remove\n\n go (isOdd, med, seen) rem =\n let isOdd' = not isOdd\n seen' = Set.insert rem seen\n find = get med seen\n med' =\n if not isOdd && rem <= med then find succ\n else if isOdd && rem >= med then find pred\n else med\n in (isOdd', med', seen')\n\n get n seen f = let n' = f n in\n if Set.member n' seen\n then get n' seen f\n else n'\n\n\nfromBit :: Char -> Int\nfromBit '0' = 0\nfromBit '1' = 1\n\ntoBit :: (Eq a, Num a) => a -> Char\ntoBit 0 = '0'\ntoBit 1 = '1'\n\nfromBinary :: Int -> String -> Int\nfromBinary m = foldl' (\\n c -> 2 * n + fromBit c) 0\n\ntoBinary :: Integral a => Int -> a -> [Char]\ntoBinary m num =\n foldl' (\\b k -> toBit (k `mod` 2):b) \"\" (take m $ iterate (`div` 2) num)\n\n\n\nreadInput :: IO (Int, [String])\nreadInput = do\n [n, m] <- map read . words <$> getLine\n (m, ) <$> (sequence $ replicate n getLine)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)\n"}, {"source_code": "import Data.Sequence (Seq, deleteAt, index, fromFunction)\nimport Data.Traversable (for)\nimport Data.Foldable (foldl', for_)\nimport Data.List (sort, unfoldr)\n\nreadBits :: String -> Int\nreadBits = foldl' (\\x y -> case y of { '0' -> 2*x; '1' -> 2*x+1; _ -> error \"bit\" }) 0\n\ntoBits :: Int -> Int -> String\ntoBits k val = reverse . take k $ unfoldr step val where\n step x = case quotRem x 2 of\n (x', 0) -> Just ('0', x')\n (x', 1) -> Just ('1', x')\n _ -> error \"overflow\"\n\nmain :: IO ()\nmain = do\n print (maxBound :: Int)\n t <- read <$> getLine :: IO Int\n for_ [1..t] $ \\_ -> do\n [n, k] <- (map read . words) <$> getLine :: IO [Int]\n let tot = 2 ^ k :: Integer\n tot' = fromInteger tot :: Int\n if tot > fromIntegral (maxBound :: Int)\n then error \"too big? ask for 64-bit Int\"\n else return ()\n removalList <- for [1..n] $ \\_ -> readBits <$> getLine\n let rl = reverse $ sort removalList :: [Int]\n startSeq = fromFunction tot' id :: Seq Int\n whatsLeft = foldl' (flip deleteAt) startSeq rl :: Seq Int\n ix = div (tot' - length rl - 1) 2\n tar = index whatsLeft ix\n putStrLn (toBits k tar)\n\n"}], "src_uid": "b313fde45b6567bad265b8288c213cf0"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nmf n = head [i|i<-[2..n], mod n i ==0]\nans 0 n = n\nans k n | even n = n+k*2\n\t| otherwise = (n+(mf n)) +(k-1)*2\n\nonecase = do\t\n\t\t[n,k]<-map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ ans k n\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n", "positive_code": [{"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ntype Long = Int\n\nsmallestDivisor :: Int -> Int\nsmallestDivisor n =\n case L.find (\\d -> n `mod` d == 0) [2..1001] of\n Nothing -> n\n Just d -> d\n\nsolve :: Int -> Int -> Int\nsolve n 1 = n + smallestDivisor n\nsolve n k = (2*k-2) + n + smallestDivisor n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readWords\n print $ solve n k\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine"}, {"source_code": "import Data.Map as M\nimport Data.List as L\n\nsmallerDiv :: Integer -> Integer\nsmallerDiv n = head $ L.filter (\\x -> mod n x == 0) [2..]\n\nfun :: Integer -> Integer -> Integer\nfun k n\n | even n = n+2*k\n | otherwise = fun (k-1) (n+smallerDiv n)\n\nparseInput :: String -> (Integer, Integer)\nparseInput raw = (n, k)\n where n = read n' :: Integer\n k = read k' :: Integer\n [n', k'] = words raw\n\nsolve :: String -> String\nsolve input = show (fun k n)\n where (n, k) = parseInput input\n\nmain :: IO()\nmain = interact (unlines . L.map solve . tail . lines)\n"}, {"source_code": "import Control.Monad\n\nf :: Int -> Int -> Int\nf n k\n | even n = n+2*k\n | odd n = n+2*(k-1)+head (filter (\\x -> mod n x == 0) [3,5..])\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n,k] <- map read . words <$> getLine\n print $ f n k\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map (read ::String -> Int).words) <$> getLine\n print $ solve n k\n\nsolve :: Int -> Int -> Int\nsolve n k\n | odd n = solve (n+sm) (k-1)\n | even n = n+2*k\n | otherwise = error \"Lol\"\n where\n sm = head $ filter (\\x -> n `mod` x == 0) [2..]\n"}], "negative_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map (read ::String -> Int).words) <$> getLine\n print $ solve n k\n\nsolve :: Int -> Int -> Int\nsolve n k\n | odd n = solve (n+sm) (k-1)\n | even n = n+2*k\n | otherwise = error \"Lol\"\n where\n sm = head $ filter (\\x -> x `mod` n == 0) [2..]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nmf n = head [i|i<-[2..n], mod n i ==0]\nans 0 n = n\nans k n | even n = n+k*2\n\t| otherwise = (n*2) +(k-1)*2\n\nonecase = do\t\n\t\t[n,k]<-map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ ans k n\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}], "src_uid": "9fd9bc0a037b2948d60ac2bd5d57740f"} {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, NoMonomorphismRestriction #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nfi = fromIntegral\n\nmain :: IO ()\nmain = do\n\t[n, pop] <- inputIntegers\n\tcities <- replicateM (fi n) $ do\n\t\t[x, y, pop] <- inputIntegers\n\t\treturn (sqrt ((fi x) ** 2 + (fi y) ** 2), pop)\n\tlet x = listToMaybe . dropWhile (\\(_,p) -> p < 10^6) . scanl (\\(r1,p1) (r2,p2) -> (r2,p1+p2)) (0,fi pop) $ sort cities\n\tcase x of\n\t\tJust (r,_) -> print r\n\t\tNothing -> print (-1)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Text.Printf\n\nreadInts = map (fst.fromJust.B.readInt) . B.words <$> B.getLine\n\nmain = do\n [n, s] <- readInts\n ls <- replicateM n readInts\n let\n binary_search :: Float -> Float -> Int -> Float\n binary_search _ ub 100 = ub\n binary_search lb ub depth = if can mid then binary_search lb mid (depth+1)else binary_search mid ub (depth+1)\n where\n mid = (lb+ub) / 2\n can r = total >= 1000000\n where\n total = s + (sum $ map (\\[x,y,p] -> if doesContain x y r then p else 0) ls)\n doesContain x y r = x'*x' + y'*y' <= r*r\n where\n x' = fromIntegral x\n y' = fromIntegral y\n result = binary_search 0 14200 0\n in putStrLn $ if result > 14150 then \"-1\" else printf \"%.7f\" result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n, s] <- map read.words <$> getLine :: IO [Int]\n xyks <- parse.map readInt.B.words <$> B.getContents\n if isValid s xyks then print $ solve s [(rr,k)|(x,y,k)<-xyks,let !rr=fi x*fi x+fi y*fi y]\n else print (-1)\n\nfi :: Int -> Int64\nfi = fromIntegral\n\nisValid :: Int -> [(Int,Int,Int)] -> Bool\nisValid s xyks= s + sum[k|(_,_,k)<-xyks] >= 1000000\n\nparse :: [Int] -> [(Int,Int,Int)]\nparse (x:y:k:xyks) = (x,y,k) : parse xyks\nparse _ = []\n\nsolve :: Int -> [(Int64,Int)] -> Double\nsolve s rrks = sqrt.fromIntegral $ lowerBound p 0 $ fst $ maximum rrks\n where\n p rr = s + sum[k|(rr',k)<-rrks,rr'<=rr] >= 1000000\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}"}], "negative_code": [], "src_uid": "bcc758394d012519f0865479b3c6770c"} {"source_code": "import Control.Monad (replicateM_, guard)\r\nimport Data.List (intercalate)\r\n\r\ngenElems :: Int -> [a] -> [a]\r\ngenElems n = take n . concat . repeat\r\n\r\nappendColumn :: [a] -> [[a]] -> [[a]]\r\nappendColumn = zipWith (:)\r\n\r\nevenMatrix :: (Int, Int, Int) -> [[Char]]\r\nevenMatrix (n, m, k) = go (n, m, k) \"xy\" where\r\n go (0, _, _) _ = []\r\n go (n, m, remHorz) vertChars = (r1 ++ c1) : (r2 ++ c2) : next where\r\n numHorz = if remHorz >= m then m else remHorz\r\n numVert = m - numHorz\r\n nextVertChars = if vertChars == \"xy\" then \"ij\" else \"xy\"\r\n r1 = genElems numHorz \"aabb\"\r\n r2 = genElems numHorz \"ccdd\"\r\n c1 = genElems numVert nextVertChars\r\n c2 = genElems numVert nextVertChars\r\n next = go (n - 2, m, remHorz - numHorz) nextVertChars\r\n\r\nsolve :: (Int, Int, Int) -> Maybe [[Char]]\r\nsolve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems m \"aabb\"]\r\nsolve (n, 1, k) = do guard $ k == 0 ; return $ genElems n [\"p\", \"p\", \"q\", \"q\"]\r\nsolve (n, m, k) \r\n | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)\r\n | odd m = do\r\n let x = (n * m) `div` 2 - k - n `div` 2\r\n guard $ x >= 0 && even x\r\n let col = genElems n \"ppqq\" ; mat = evenMatrix (n, m - 1, k)\r\n return $ appendColumn col mat\r\n | otherwise = do\r\n let x = k - m `div` 2\r\n guard $ x >= 0 && even x\r\n return $ genElems m \"eeff\" : evenMatrix (n - 1, m, k - m `div` 2)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m, k] <- readInts\r\n let mat = solve (n, m, k)\r\n putStrLn $ maybe \"NO\" (intercalate \"\\n\" . (\"YES\":)) mat", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Control.Monad (guard)\r\nimport Data.List (intercalate)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read >>> solve >>> maybe \"NO\" (intercalate \"\\n\" . (\"YES\":)))\r\n >>> unlines\r\n\r\ntype Sol = Maybe [[Char]]\r\n\r\nsolve :: [Int] -> Sol\r\nsolve [0, _, 0] = Just []\r\nsolve [0, _, _] = Nothing\r\nsolve [n, m, k]\r\n | n == 2 = do\r\n guard $ k <= n * m'\r\n guard $ even k\r\n let rowH0 = stream k \"aabb\"\r\n let rowH1 = stream k \"ccdd\"\r\n let rowV = stream (m - k) \"pq\"\r\n return [rowH0 ++ rowV, rowH1 ++ rowV]\r\n | even n = do\r\n guard $ k <= n * m'\r\n guard $ even k\r\n let pick = min k (2 * m')\r\n top <- conv <$> solve [2, m, pick]\r\n rest <- solve [n - 2, m, k - pick]\r\n return $ top ++ rest\r\n | odd n = do\r\n guard $ k >= m'\r\n g <- solve [n - 1, m, k - m']\r\n let top = stream m \"yyzz\"\r\n return $ top : g\r\n where\r\n m' = m `div` 2\r\n stream l = take l . concat . repeat\r\n conv = if n `mod` 4 == 2 then id else map (map change)\r\n change 'p' = 'r'\r\n change 'q' = 's'\r\n change c = c\r\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_, guard)\r\nimport Data.List (intercalate)\r\n\r\ngenElems :: Int -> [a] -> [a]\r\ngenElems n = take n . concat . repeat\r\n\r\nappendColumn :: [a] -> [[a]] -> [[a]]\r\nappendColumn = zipWith (:)\r\n\r\nevenMatrix :: (Int, Int, Int) -> [[Char]]\r\nevenMatrix (n, m, k) = go (n, m, k) \"xy\" where\r\n go (0, _, _) _ = []\r\n go (n, m, remHorz) vertChars = (r1 ++ c1) : (r2 ++ c2) : next where\r\n numHorz = if remHorz >= m then m else remHorz\r\n numVert = m - numHorz\r\n nextVertChars = if vertChars == \"xy\" then \"ij\" else \"xy\"\r\n r1 = genElems numHorz \"aabb\"\r\n r2 = genElems numHorz \"ccdd\"\r\n c1 = genElems numVert nextVertChars\r\n c2 = genElems numVert nextVertChars\r\n next = go (n - 2, m, remHorz - numHorz) nextVertChars\r\n\r\nsolve :: (Int, Int, Int) -> Maybe [[Char]]\r\nsolve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k \"aabb\"]\r\nsolve (n, 1, k) = do guard $ k == 0 ; return $ genElems n [\"p\", \"p\", \"q\", \"q\"]\r\nsolve (n, m, k) \r\n | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)\r\n | odd m = do\r\n let x = (n * m) `div` 2 - k - n `div` 2\r\n guard $ x >= 0 && even x\r\n let col = genElems n \"ppqq\" ; mat = evenMatrix (n, m - 1, k)\r\n return $ appendColumn col mat\r\n | otherwise = do\r\n let x = k - m `div` 2\r\n guard $ x >= 0 && even x\r\n return $ genElems m \"eeff\" : evenMatrix (n - 1, m, k - m `div` 2)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m, k] <- readInts\r\n let mat = solve (n, m, k)\r\n putStrLn $ maybe \"NO\" (intercalate \"\\n\" . (\"YES\":)) mat"}, {"source_code": "import Control.Monad (replicateM_, guard)\r\nimport Data.List (intercalate)\r\n\r\ngenElems :: Int -> [a] -> [a]\r\ngenElems n = take n . concat . repeat\r\n\r\nappendColumn :: [a] -> [[a]] -> [[a]]\r\nappendColumn = zipWith (:)\r\n\r\nevenMatrix :: (Int, Int, Int) -> [[Char]]\r\nevenMatrix (n, m, k) = go (n, m, k) \"xy\" where\r\n go (0, _, _) _ = []\r\n go (n, m, remHorz) vertChars = (r1 ++ c1) : (r2 ++ c2) : next where\r\n numHorz = if remHorz >= m then m else remHorz\r\n numVert = m - numHorz\r\n nextVertChars = if vertChars == \"xy\" then \"ij\" else \"xy\"\r\n r1 = genElems numHorz \"aabb\"\r\n r2 = genElems numHorz \"ccdd\"\r\n c1 = genElems numVert nextVertChars\r\n c2 = genElems numVert nextVertChars\r\n next = go (n - 2, m, remHorz - numHorz) nextVertChars\r\n\r\nsolve :: (Int, Int, Int) -> Maybe [[Char]]\r\nsolve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k \"aabb\"]\r\nsolve (n, 1, k) = do guard $ k == 0 ; return $ genElems n [\"p\", \"p\", \"q\", \"q\"]\r\nsolve (n, m, k) \r\n | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)\r\n | odd m = do\r\n guard $ even $ (n * m) `div` 2 - k - n `div` 2\r\n let col = genElems n \"ppqq\" ; mat = evenMatrix (n, m - 1, k)\r\n return $ appendColumn col mat\r\n | otherwise = do\r\n guard $ even $ k - m `div` 2\r\n return $ genElems m \"eeff\" : evenMatrix (n - 1, m, k - m `div` 2)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m, k] <- readInts\r\n let mat = solve (n, m, k)\r\n putStrLn $ maybe \"NO\" (intercalate \"\\n\" . (\"YES\":)) mat"}, {"source_code": "import Control.Monad (replicateM_, guard)\r\nimport Data.List (intercalate)\r\n\r\ngenElems :: Int -> [a] -> [a]\r\ngenElems n = take n . concat . repeat\r\n\r\nappendColumn :: [a] -> [[a]] -> [[a]]\r\nappendColumn = zipWith (:)\r\n\r\nevenMatrix :: (Int, Int, Int) -> [[Char]]\r\nevenMatrix (n, m, k) = go (n, m, k) \"xy\" where\r\n go (0, _, _) _ = []\r\n go (n, m, remHorz) vertChars = (r1 ++ c1) : (r2 ++ c2) : next where\r\n numHorz = if remHorz >= m then m else remHorz\r\n numVert = m - numHorz\r\n nextVertChars = if vertChars == \"xy\" then \"ij\" else \"xy\"\r\n r1 = genElems numHorz \"aabb\"\r\n r2 = genElems numHorz \"ccdd\"\r\n c1 = genElems numVert nextVertChars\r\n c2 = genElems numVert nextVertChars\r\n next = go (n - 2, m, remHorz - numHorz) nextVertChars\r\n\r\nsolve :: (Int, Int, Int) -> Maybe [[Char]]\r\nsolve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k \"aabb\"]\r\nsolve (n, 1, k) = do guard $ k == 0 ; return $ genElems n [\"p\", \"p\", \"q\", \"q\"]\r\nsolve (n, m, k) \r\n | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)\r\n | odd m = do\r\n guard $ even $ (n * m) `div` 2 - k - n `div` 2\r\n let col = genElems n \"ppqq\" ; mat = evenMatrix (n, m - 1, k)\r\n return $ appendColumn col mat\r\n | otherwise = do\r\n guard $ even $ k - m `div` 2\r\n return $ genElems m \"eeff\" : evenMatrix (n - 1, m, k)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m, k] <- readInts\r\n let mat = solve (n, m, k)\r\n putStrLn $ maybe \"NO\" (intercalate \"\\n\" . (\"YES\":)) mat"}, {"source_code": "import Control.Monad (replicateM_, guard)\r\nimport Data.List (intercalate)\r\n\r\ngenElems :: Int -> [a] -> [a]\r\ngenElems n = take n . concat . repeat\r\n\r\nappendColumn :: [a] -> [[a]] -> [[a]]\r\nappendColumn = zipWith (:)\r\n\r\nevenMatrix :: (Int, Int, Int) -> [[Char]]\r\nevenMatrix (n, m, k) = go (n, m, k) \"xy\" where\r\n go (0, _, _) _ = []\r\n go (n, m, remHorz) vertChars = (r1 ++ c1) : (r2 ++ c2) : next where\r\n numHorz = if remHorz >= m then m else remHorz\r\n numVert = m - numHorz\r\n nextVertChars = if vertChars == \"xy\" then \"ij\" else \"xy\"\r\n r1 = genElems numHorz \"aabb\"\r\n r2 = genElems numHorz \"ccdd\"\r\n c1 = genElems numVert nextVertChars\r\n c2 = genElems numVert nextVertChars\r\n next = go (n - 2, m, remHorz - numHorz) nextVertChars\r\n\r\nsolve :: (Int, Int, Int) -> Maybe [[Char]]\r\nsolve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k \"aabb\"]\r\nsolve (n, 1, k) = do guard $ k == 0 ; return $ genElems n [\"p\", \"q\"]\r\nsolve (n, m, k) \r\n | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)\r\n | odd m = do\r\n guard $ even $ (n * m) `div` 2 - k - n `div` 2\r\n let col = genElems n \"pq\" ; mat = evenMatrix (n, m - 1, k)\r\n return $ appendColumn col mat\r\n | otherwise = do\r\n guard $ even $ k - m `div` 2\r\n return $ genElems m \"eeff\" : evenMatrix (n - 1, m, k)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m, k] <- readInts\r\n let mat = solve (n, m, k)\r\n putStrLn $ maybe \"NO\" (intercalate \"\\n\" . (\"YES\":)) mat"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Control.Monad (guard)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read >>> solve >>> maybe \"NO\" (unlines . (\"YES\":)))\r\n >>> unlines\r\n\r\ntype Sol = Maybe [[Char]]\r\n\r\nsolve :: [Int] -> Sol\r\nsolve [0, _, 0] = Just []\r\nsolve [0, _, _] = Nothing\r\nsolve [n, m, k]\r\n | n == 2 = do\r\n guard $ k <= n * m'\r\n guard $ even k\r\n let rowH0 = stream k \"aabb\"\r\n let rowH1 = stream k \"ccdd\"\r\n let rowV = stream (m - k) \"pq\"\r\n return [rowH0 ++ rowV, rowH1 ++ rowV]\r\n | even n = do\r\n guard $ k <= n * m'\r\n guard $ even k\r\n let pick = min k (2 * m')\r\n top <- conv <$> solve [2, m, pick]\r\n rest <- solve [n - 2, m, k - pick]\r\n return $ top ++ rest\r\n | odd n = do\r\n guard $ k >= m'\r\n g <- solve [n - 1, m, k - m']\r\n let top = stream m \"yyzz\"\r\n return $ top : g\r\n where\r\n m' = m `div` 2\r\n stream l = take l . concat . repeat\r\n conv = if n `mod` 4 == 2 then id else map (map change)\r\n change 'p' = 'r'\r\n change 'q' = 's'\r\n change c = c\r\n"}], "src_uid": "a15f7324d545c26725324928eaaa645c"} {"source_code": "module Main where\r\n\r\nreadInt :: IO Int\r\nreadInt = readLn\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (map read . words) getLine\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = return ()\r\nsolve t = do n <- readInt\r\n ns <- readInts\r\n let ans = maximum ns - minimum ns in\r\n print ans\r\n solve (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do t <- readInt\r\n solve t\r\n", "positive_code": [{"source_code": "import Control.Monad\n\nsolve = do\n n <- readLn :: IO Int\n str <- getLine\n\n let as = map (read :: String -> Int) (words str)\n\n print (maximum as - minimum as)\n\nmain = do\n t <- readLn :: IO Int\n\n replicateM_ t solve\n"}, {"source_code": "import Control.Monad(replicateM)\r\nimport qualified Data.ByteString.Lazy.Char8 as B\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport System.IO\r\n\r\n\r\nsolve :: SB Builder\r\nsolve = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n xs <- getInts n\r\n return $ putInts [maximum xs - minimum xs]\r\n\r\n\r\n-- stdin/out from solution by clyring\r\ntype SB = State [B.ByteString]\r\n\r\ngetNext :: Int -> SB [B.ByteString]\r\ngetNext = state . splitAt\r\n\r\nparseInt = fst . fromJust . B.readInt\r\n\r\ngetInts :: Int -> SB [Int]\r\ngetInts n = map parseInt <$> getNext n\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- B.getContents\r\n let out = evalState solve $ B.words inp\r\n B.putStr $ toLazyByteString out"}, {"source_code": "import Control.Monad(replicateM)\r\nimport qualified Data.ByteString.Lazy.Char8 as B\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport System.IO\r\n\r\n\r\nsolve :: SB Builder\r\nsolve = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n xs <- getInts n\r\n return $ putInts [maximum xs - minimum xs]\r\n\r\n\r\n-- stdin/out from solution by clyring\r\ntype SB = State [B.ByteString]\r\n\r\ngetNext :: Int -> SB [B.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SB [Int]\r\ngetInts n = map parseInt <$> getNext n\r\n where\r\n parseInt = fst . fromJust . B.readInt\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- B.getContents\r\n let out = evalState solve $ B.words inp\r\n B.putStr $ toLazyByteString out"}, {"source_code": "import Control.Monad(replicateM_)\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs = max - min\r\n where\r\n max = maximum xs\r\n min = minimum xs\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n getLine\r\n xs <- readInts\r\n let ans = solve xs\r\n print ans"}, {"source_code": "-- https://codeforces.com/contest/1624/problem/A\nimport Control.Monad (replicateM_)\n\nmain = getLine >>= flip replicateM_ run . read\nrun = do\n getLine\n a <- (read <$>) . words <$> getLine\n print $ maximum a - minimum a\n"}, {"source_code": "import Control.Monad()\nimport Data.List()\n\nsolve [] = 0\nsolve lst = maximum lst - minimum lst\n\n\nrep 0 = return ()\nrep x = do\n n <- getLine\n arr <- getLine\n let intList = map (read::String->Int) (words arr)\n print(solve intList)\n rep (x - 1)\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n rep (read t)"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- map read . words <$> getLine\n print $ solve n a\n\nsolve :: Integer -> [Integer] -> Integer\nsolve _ a = sum $ zipWith subtract a' (tail a')\n where\n a' = sort a\n"}, {"source_code": "main = readLn >>= sequence_ . flip replicate (getLine >> getLine >>= print . ((-) <$> maximum <*> minimum) . map read . words)"}, {"source_code": "readInt :: IO Int\r\nreadInt = readLn\r\n\r\nreadIntArray :: IO [Int]\r\nreadIntArray = (map read . words) <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n test <- readInt\r\n solve test\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = pure ()\r\nsolve test = do\r\n n <- readInt\r\n dt <- readIntArray\r\n print $ maximum dt - minimum dt\r\n solve $ test - 1\r\n"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = [Int]\r\ntype OutType = Int\r\n\r\nsolve :: InType -> OutType\r\nsolve xs = maximum xs - minimum xs\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive x = error \"wrong input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n \r\n \r\nprefMins :: Ord t => (a -> t) -> [a] -> [t]\r\nprefMins f li = tail $ scanl' min (f $ head li) $ map f li\r\n \r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n a <- getInts n\r\n let\r\n b = sort a\r\n z = last b - head b\r\n pure $ putInts [z]\r\n \r\n\r\ntype SP = State [P.ByteString]\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "import Data.Char\r\nmain :: IO()\r\nmain = do\r\n -- print 5\r\n tStr <- getLine\r\n -- print $ show tStr\r\n let t = read tStr :: Int\r\n solve t\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = return ()\r\nsolve t = do\r\n nStr <- getLine\r\n -- print nStr\r\n let n = read nStr :: Int\r\n\r\n aStr <- getLine\r\n -- print aStr\r\n let as = readIntList aStr :: [Int]\r\n\r\n -- print as\r\n\r\n print (maxVal as - minVal as)\r\n solve (t-1)\r\n\r\nreadIntList :: String -> [Int]\r\nreadIntList [] = []\r\nreadIntList (h : t)\r\n | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)\r\n | otherwise = readIntList t\r\n\r\nmaxVal :: [Int] -> Int\r\nmaxVal = foldr max 0\r\n\r\nminVal :: [Int] -> Int\r\nminVal = foldr min 1000000000"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t\r\n $ do\r\n n <- getLine\r\n xs <- map read . words <$> getLine\r\n print (maximum xs - minimum xs)\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n a <- getInts n\n pure $ putInts [maximum a - minimum a]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "-- https://codeforces.com/contest/1624/problem/A\r\n-- A. Plus One on the Subset\r\nimport qualified Data.List as L\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nhandleData1 [] = []\r\nhandleData1 intss = do\r\n\tlet\r\n\t\tints = head intss\r\n\t\tmaxi = L.maximum ints\r\n\t\tmini = L.minimum ints\r\n\t\tin (maxi - mini) : (handleData1 (tail intss))\r\n\r\n-- read_intss :: Int -> IO ([[Int]])\r\nread_intss 0 = do return []\r\nread_intss ints_count = do\r\n\tint_count_str <- getLine\r\n\tints_str <- getLine\r\n\tlast_intss <- read_intss (ints_count-1)\r\n\tlet now_inst =map (\\x -> read x :: Int) $ words ints_str\r\n\t\tin return (now_inst : last_intss)\r\n\t\r\n\r\nmain = do\r\n\thSetBuffering stdout NoBuffering\r\n\tdata_count_str <- getLine\r\n\tintss <- read_intss $ read $ data_count_str\r\n\t-- putStrLn $ L.intercalate \"\\n\" $ putInts $ handleData1 intss\r\n\tP.putStr $ toLazyByteString $ putInts $ handleData1 intss\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n \r\n \r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n a <- getInts n\r\n pure $ putInts [maximum a - minimum a]\r\n \r\n \r\ntype SP = State [P.ByteString]\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "-- https://codeforces.com/contest/1624/problem/A\r\n-- A. Plus One on the Subset\r\nimport qualified Data.List as L\r\n\r\nhandleData1 [] = []\r\nhandleData1 intss = do\r\n\tlet\r\n\t\tints = head intss\r\n\t\tmaxi = L.maximum ints\r\n\t\tmini = L.minimum ints\r\n\t\tin (show (maxi - mini)) : (handleData1 (tail intss))\r\n\r\n-- read_intss :: Int -> IO ([[Int]])\r\nread_intss 0 = do return []\r\nread_intss ints_count = do\r\n\tint_count_str <- getLine\r\n\tints_str <- getLine\r\n\tlast_intss <- read_intss (ints_count-1)\r\n\tlet now_inst =map (\\x -> read x :: Int) $ words ints_str\r\n\t\tin return (now_inst : last_intss)\r\n\t\r\n\r\nmain = do\r\n\tdata_count_str <- getLine\r\n\tintss <- read_intss $ read $ data_count_str\r\n\tputStrLn $ L.intercalate \"\\n\" $ handleData1 intss\r\n"}, {"source_code": "import System.IO\r\nimport qualified Data.List as L\r\n\r\nhandleData1 0 = do return ()\r\nhandleData1 dataCount = do\r\n\tint_count_str <- getLine\r\n\tints_str <- getLine\r\n\tlet ints = map (\\x -> read x :: Int) $ words ints_str\r\n\t\tin print $ (L.maximum ints) - (L.minimum ints)\r\n\thandleData1 (dataCount-1)\r\n\r\nmain = do\r\n\tdata_count_str <- getLine\r\n\tlet data_count = read data_count_str\r\n\t\tin handleData1 data_count\r\n"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nsolve = do\n nStr <- B.getLine\n asStr <- B.getLine\n\n let n = fst $ fromJust $ C.readInt nStr\n let as = map (fst . fromJust . C.readInt) (C.words asStr)\n\n print (maximum as - minimum as)\n\nmain = do\n str <- B.getLine\n\n let t = fst $ fromJust $ C.readInt str\n\n\n replicateM_ t solve\n"}, {"source_code": "import Control.Monad\nimport System.IO\n\nsolve = do\n n <- readLn :: IO Int\n str <- getLine\n\n let as = map (read :: String -> Int) (words str)\n\n print (maximum as - minimum as)\n\nmain :: IO()\nmain = do\n hSetBuffering stdout LineBuffering\n\n t <- readLn :: IO Int\n\n replicateM_ t solve\n"}], "negative_code": [{"source_code": "-- https://codeforces.com/contest/1624/problem/A\nimport Control.Monad (replicateM_)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain = getLine >>= flip replicateM_ run . read\nrun = do\n getLine\n a <- (fst.fromJust.B.readInt <$>) . B.words <$> B.getLine \n print $ maximum a - minimum a\n"}, {"source_code": "-- https://codeforces.com/contest/1624/problem/A\nimport Control.Monad (replicateM_)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain = getLine >>= flip replicateM_ run . read\nrun = do\n getLine\n a <- (fst.fromJust.B.readInt <$>) . B.words <$> B.getLine\n print $ maximum a - minimum a\n"}], "src_uid": "cf3cfcae029a6997ee62701eda959a60"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\nimport qualified Data.Map.Strict as M\n\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch fun = go where\n go x y = if x == y\n then x\n else let m = x + div (y - x) 2\n in if fun m\n then go x m\n else go (m+1) y\n\ngetIx :: UArray Int Int -> Int -> Int\ngetIx arr val = let\n (p, q) = bounds arr\n in binSearch (\\i -> arr ! i >= val) p $ q + 1\n\nsolve :: UArray Int Int -> UArray Int Int -> [(Int, Int)] -> Int64\nsolve xs ys ps = let\n (1, n) = bounds xs\n (1, m) = bounds ys\n interest :: [(Bool, Int, Int)]\n interest = do\n (xp, yp) <- ps\n let [xix, yix] = zipWith getIx [xs, ys] [xp, yp]\n case (xp == xs ! xix, yp == ys ! yix) of\n (True, True) -> []\n (False, True) -> [(False, xix, yix)]\n (True, False) -> [(True, xix, yix)]\n _ -> error \"invalid input\"\n uff :: M.Map (Bool, Int, Int) Int\n uff = M.fromListWith (+) $ zip interest $ repeat 1\n rows :: UArray Int Int\n rows = accumArray (+) 0 (1, n)\n $ [(xix, 1) | (False, xix, _) <- interest]\n cols :: UArray Int Int\n cols = accumArray (+) 0 (1, m)\n $ [(yix, 1) | (True, _, yix) <- interest]\n w2 x = let\n x64 = fromIntegral x\n in x64 * (x64 - 1)\n in (`div` 2) $ foldl' (+) 0 $ map w2 (concatMap elems [rows, cols])\n ++ do\n (_k, ct) <- M.toList uff\n pure $ negate (w2 ct)\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m, k] <- getInts 3\n xs <- listArray (1, n) <$> getInts n\n ys <- listArray (1, m) <$> getInts m\n ps <- replicateM k $ do\n ~[xp, yp] <- getInts 2\n pure (xp, yp)\n pure $ putInt64s [solve xs ys ps]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE ViewPatterns #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport qualified Data.IntMap as M\r\nimport qualified Data.IntSet as S\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Tuple (swap)\r\nimport Debug.Trace (trace)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ntype PII = (Int, Int)\r\ntype Input = ([Int], [Int], [PII])\r\ntype Output = Int64\r\n\r\ninput :: Scanner Input\r\ninput = do\r\n n <- int\r\n m <- int\r\n k <- int\r\n xs <- n >< int\r\n ys <- m >< int\r\n ps <- k >< pair int int\r\n return (xs, ys, ps)\r\n\r\noutput :: Output -> C.ByteString\r\noutput = showB\r\n\r\nsolve :: Input -> Output\r\nsolve (S.fromList -> xs, S.fromList -> ys, ps) = compute ps xs ys + compute (map swap ps) ys xs\r\n\r\ncompute :: [PII] -> S.IntSet -> S.IntSet -> Int64\r\ncompute ps xs ys = fst $ foldl update (0, (0, M.empty)) ps'\r\n where\r\n ps' = sort $ [(x, -1) | x <- S.elems xs] ++ [(x, y) | (x, y) <- ps, S.notMember x xs]\r\n\r\n update (acc, (prv, m)) (x, -1) = (acc, (0, M.empty))\r\n update (acc, (prv, m)) (x, y) = (acc + prv - find y m, (prv + 1, incr y m))\r\n\r\n find y = fromMaybe 0 . M.lookup y\r\n incr y = M.insertWith (+) y 1\r\n\r\nfi = fromIntegral\r\n\r\n-- debug a = trace (show a) a\r\n-- debugS v a = trace (v ++ \" = \" ++ show a) a\r\ndebug = id\r\ndebugS _ = id\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap as M\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple (swap)\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype PII = (Int, Int)\ntype Input = ([Int], [Int], [PII])\ntype Output = Int64\n\ninput :: Scanner Input\ninput = do\n n <- int\n m <- int\n k <- int\n xs <- n >< int\n ys <- m >< int\n ps <- k >< pair int int\n return (xs, ys, ps)\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: Input -> Output\nsolve (S.fromList -> xs, S.fromList -> ys, ps) = compute ps xs ys + compute (map swap ps) ys xs\n\ncompute :: [PII] -> S.IntSet -> S.IntSet -> Int64\ncompute ps xs ys = fst $ foldl update (0, (0, M.empty)) ps'\n where\n ps' = sort $ [(x, -1) | x <- S.elems xs] ++ [(x, y) | (x, y) <- ps, S.notMember x xs]\n\n update (acc, (prv, m)) (x, -1) = (acc, (0, M.empty))\n update (acc, (prv, m)) (x, y) = (acc + prv - find y m, (prv + 1, incr y m))\n\n find y = fromMaybe 0 . M.lookup y\n incr y = M.insertWith (+) y 1\n\nfi = fromIntegral\n\n-- debug a = trace (show a) a\n-- debugS v a = trace (v ++ \" = \" ++ show a) a\ndebug = id\ndebugS _ = id\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Tuple\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as IS\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, m, k] <- readInts\r\n xs <- IS.fromList <$> readInts\r\n ys <- IS.fromList <$> readInts\r\n pts <- replicateM k $ (\\[x, y] -> (x, y)) <$> readInts\r\n let ways xs = sum $ zipWith (*) xs $ scanl (+) 0 xs :: Int64\r\n go xs pts =\r\n sum $ map (ways . map (fromIntegral . length) . group . sort . map snd) $\r\n groupBy ((==) `on` fst) $ sort $\r\n [(l, y) | pt@(x, y) <- pts, let l = fromJust $ IS.lookupLE x xs, l /= x]\r\n print $ go xs pts + go ys (map swap pts)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n"}], "negative_code": [], "src_uid": "e69c0010e093792011a0c7b846a9bc42"} {"source_code": "main = do [n, m, k] <- (map read . words) `fmap` getLine\n print $ solve n m k\n\nsolve n m k | n+k < m = 0.0\n | k >= m = 1.0\n | otherwise = 1.0 - product [(m-k+i) / (n+k-i+1) | i <-[0.0..k]]\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Ratio\nimport Text.Printf\n\nmain :: IO ()\nmain = getLine >>= solve\n\nsolve :: String -> IO ()\nsolve = do\n [n, m, k] <- map read . words\n return . printf \"%f\\n\" $ p n m k\n\np :: Integer -> Integer -> Integer -> Double\np n m k\n | m <= k = 1\n | n + k < m = 0\n | otherwise = 1 - fromRational (a % b)\n where a = product [m - k .. m]\n b = product [n + 1 .. n + k + 1]\n\n\n"}, {"source_code": "main :: IO()\nmain = interact work\n\nwork :: String -> String\nwork input = show $ solve n m k\n where [n, m, k] = map (\\i -> read i :: Int) . words $ input\n\nsolve :: Int -> Int -> Int -> Double\nsolve n m k = max 0 (1 - product [fromIntegral (m - i) / fromIntegral (n + i + 1) | i <- [0..k]])\n"}, {"source_code": "main = do\n [n,m,k] <- fmap (map read . words) getLine :: IO [Int]\n print $ 1.0 - if n + k - m < 0 then 1.0 else f m n k where\n f m n k\n | k == 0 = fromIntegral m / fromIntegral (n + 1)\n | otherwise = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)"}], "negative_code": [{"source_code": "main = do\n [n,m,k] <- fmap (map read . words) getLine :: IO [Int]\n print $ 1.0 - f m n k where\n f m n 0 = fromIntegral m / fromIntegral (n + 1)\n f m n k = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)\n"}, {"source_code": "main = do\n [n,m,k] <- fmap (map read . words) getLine :: IO [Int]\n print $ 1.0 - f m n k where\n f m n k\n | n + k - m < 0 = 0\n | k == 0 = fromIntegral m / fromIntegral (n + 1)\n | otherwise = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)"}], "src_uid": "5a2c9caec9c20a3caed1982ee8ed8f9c"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n [n,s] <- map read . words <$> getLine :: IO [Int]\n vals <- valencies n <$> BSL.getContents\n print $ (fromIntegral (2*s) /)\n (fromIntegral $ length $ filter (==1) $ A.elems $ vals ::Double)\n\nvalencies :: Int -> BSL.ByteString -> UArray Int Int\nvalencies n bstr = runSTUArray $ do\n valencies_ <- A.newArray (1,n) (0::Int)\n forM_ (take (2*n-2) $ unfoldr (BSL.readInt . BSL.dropWhile (<'-')) bstr)\n $ \\ v -> A.readArray valencies_ v >>= A.writeArray valencies_ v . (+1)\n return valencies_\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n [n,s] <- map read . words <$> getLine :: IO [Int]\n codd <- preprocess n <$> BSL.getContents\n print $ (fromIntegral (2*s) /) (fromIntegral $ valency1 codd ::Double)\n where\n {-# INLINE processInt #-}\n processInt = \\(!i,!bs) -> do\n (!e,!bs1) <- BS.readInt $ BS.dropWhile (< '-') bs\n return $! ((i,e),(i+1,bs1))\n\n\n \n{-# INLINE children_ #-}\nchildren_ :: UArray Int Int -> Int -> Int -> [Int]\nchildren_ codd parent this =\n filter (/= parent)\n $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n\nvalency1 :: UArray Int Int -> Int\nvalency1 !codd = leaves codd (-1) 1 + if length children <= 1 then 1 else 0 \n where\n children = children_ codd (-1) 1\n\nleaves :: UArray Int Int -> Int -> Int -> Int\nleaves !codd parent this\n | null children = 1\n | otherwise = sum $ map (leaves codd this) children\n where\n children = children_ codd parent this\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE processInt #-}\n processInt = \\(!i,!bs) -> do\n (!e,!bs1) <- BSL.readInt $ BSL.dropWhile (< '-') bs\n return $! ((i,e),(i+1,bs1))\n -- domcods :: UArray Int Int\n -- domcods = A.array (0, 2*n - 3) $ unfoldr processInt (0,bstr)\n codd :: UArray Int Int\n codd = runSTUArray $ do\n domcods_ <- A.newArray_ (0,2*n-3) :: ST s (STUArray s Int Int)\n arr <- A.newArray (0,3*n-2) 0\n forM_ (take (2*n-2) $ unfoldr processInt (0,bstr)) $ \\ (!i,!e) -> do\n A.writeArray domcods_ i e\n forM_ [0..2*n-3] $ \\ !i -> do\n j <- A.readArray domcods_ i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n dom <- A.readArray domcods_ i\n cod <- A.readArray domcods_ (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n"}], "negative_code": [], "src_uid": "7bdd8f0cf42855bebda4ccc56d8fe788"} {"source_code": "import Control.Applicative\nmain = do\n n <- readLn\n a <- map read . words <$> getLine\n print $ solve a (0, 0) (101, 0) 0 n\n\nsolve [] (_, a) (_, b) _ n = a + n - b - 1 - if a > b then 1 else 0\nsolve (a:as) (ma, maxp) (mi, minp) p n =\n solve as (if ma < a then (a, p) else (ma, maxp)) (if mi >= a then (a, p) else (mi, minp)) (p+1) n\n \n\n\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nplacemax list =\n let\n (list0, list1) = span (> minimum list) (reverse list)\n\n in length list0\n\nplacemin list =\n let\n (list0, list1) = span (< maximum list) list\n list' = head list1 : (list0 ++ tail list1)\n\n in (length list0, list')\n\nmain = do\n n <- liftM read getLine :: IO Int\n list <- liftM (map read . words) getLine :: IO [Int]\n\n let (ans1, list') = placemin list\n ans2 = placemax list'\n\n putStrLn $ show $ ans1 + ans2\n"}, {"source_code": "m=minimum\nx=maximum\ns(_:h)=q(n+m(l$x h)-x(l$m h)-1)where n=length h;q x|x0=x-1;l k=[i|i<-[0..n-1],h!!i==k]\nmain=interact$show.s.map read.words"}, {"source_code": "m=minimum\nx=maximum\ns(c:h)=q$n+m(l$x h)-x(l$m h)where n=c-1;q x|x>n=x-1|1>0=x;l k=[i|i<-[0..n],h!!i==k]\nmain=interact$show.s.map read.words\n"}, {"source_code": "m=minimum\nx=maximum\ns(n:h)|r0=r-1 where r=n+m(l$x h)-1-x(l$m h);l k=[i|i<-[0..n-1],h!!i==k]\nmain=interact$show.s.map read.words"}, {"source_code": "m=minimum\nx=maximum\ns(n:h)=q$n+m(l$x h)-1-x(l$m h)where q x|x0=x-1;l k=[i|i<-[0..n-1],h!!i==k]\nmain=interact$show.s.map read.words\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \nmain= do\n\tn<- read <$> getLine ::IO Int\n\tx<- map read. words <$> getLine ::IO [Int]\n\tlet x1 = minimum x\n\tlet p1 = last $ elemIndices x1 x \n\tlet x2 = maximum x\n\tlet p2 = head $ elemIndices x2 x\n\tprint $ p2 + n-p1-1 + if (p2>p1) then (-1) else 0\n\n\t \n\t \n\t \n"}, {"source_code": "{-\nA. Arrival of the General\n==========================\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nA Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.\n\nBy the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.\n\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\n\nWithin one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.\n\nInput\n-----\nThe first input line contains the only integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) which represents the number of soldiers in the line. The second line contains integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1,\u2009a2,\u2009...,\u2009an are not necessarily different.\n\nOutput\n------\nPrint the only integer \u2014 the minimum number of seconds the colonel will need to form a line-up the general will like.\n\nSample test(s)\n--------------\ninput\n4\n33 44 11 22\noutput\n2\n\ninput\n7\n10 10 58 31 63 40 76\noutput\n10\n\nNote\n------\nIn the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).\n\nIn the second sample the colonel may swap the soldiers in the following sequence:\n\n(10, 10, 58, 31, 63, 40, 76)\n(10, 58, 10, 31, 63, 40, 76)\n(10, 58, 10, 31, 63, 76, 40)\n(10, 58, 10, 31, 76, 63, 40)\n(10, 58, 31, 10, 76, 63, 40)\n(10, 58, 31, 76, 10, 63, 40)\n(10, 58, 31, 76, 63, 10, 40)\n(10, 58, 76, 31, 63, 10, 40)\n(10, 76, 58, 31, 63, 10, 40)\n(76, 10, 58, 31, 63, 10, 40)\n(76, 10, 58, 31, 63, 40, 10)\n-}\nimport Data.List (elemIndices)\n\nswapNumber :: [Int] -> Int\nswapNumber xs = (posMax - 1 + lenXS - posMin) + if (posMax > posMin) then -1 else 0\n where\n lenXS = length xs\n posMax = (head $ elemIndices (maximum xs) xs) + 1 :: Int -- count from 1\n posMin = (last $ elemIndices (minimum xs) xs) + 1 :: Int -- count from 1\n\nreader :: String -> [Int]\nreader s = map read $ words ss\n where _:ss:_ = lines s\n\nmain = do\n input <- getContents \n let xs = reader input\n print $ swapNumber xs\n"}, {"source_code": "import Data.List\nmain = interact $ show . f . map read . words . (!! 1) . lines\n where f :: [Int] -> Int\n f x = length x - 1 - mini + maxi - if maxi > mini then 1 else 0\n where maxi = head $ elemIndices (maximum x) x\n mini = last $ elemIndices (minimum x) x"}, {"source_code": "import Data.List\nmain = getLine >> getLine >>= putStrLn.show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve soldiers = tallest + shortest - crossed\n where find f set = maybe 0 (+0) $ findIndex (==f set) set\n tallest = find maximum soldiers\n shortest = find minimum $ reverse soldiers\n crossed = if tallest + shortest < length soldiers then 0 else 1\n"}, {"source_code": "import Data.List (maximumBy, minimumBy)\nimport Data.Ord (comparing)\n\nmaxIndex :: Ord a => [a] -> Int\nmaxIndex = fst . maximumBy (comparing snd) . zip [0..]\n\nminIndex :: Ord a => [a] -> Int\nminIndex = fst . minimumBy (comparing snd) . zip [0..]\n\nprocess :: [Int] -> Int\nprocess xs\n | imax + imin > n-1 = imax + imin - 1\n | otherwise = imax + imin\n where\n n = length xs\n xs' = reverse xs\n imax = n-1 - maxIndex xs'\n imin = minIndex xs'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.List\nimport Data.Char\n\nans xs = if mi>ma then ma+(length xs) -mi-1 else ma+(length xs)-mi-2 \n where (mi,ma)=(last $ elemIndices (minimum xs) xs,head $ elemIndices (maximum xs) xs) \n\nmain = do\n getLine\n n<-getLine\n let input = map (\\x->read x::Int) $ words n\n print $ ans input"}, {"source_code": "import Data.List\n\nmain = interact $ show . s . map read . tail . words \n\ns :: [Int] -> Int\ns xs = length xs + maxIn xs - minIn xs - if maxIn xs > minIn xs then 2 else 1 where\n maxIn t = head (elemIndices (maximum t) t)\n minIn t = last (elemIndices (minimum t) t)"}, {"source_code": "import Data.List\nimport Data.Maybe\n\ncost :: [Int] -> Int\ncost sq =\n let mx = maximum sq\n mn = minimum sq\n leftTall = fromJust $ elemIndex mx sq\n rightShort = last $ elemIndices mn sq\n len = length sq\n extraDecrement = if (leftTall > rightShort) then 1 else 0\n in leftTall + len - rightShort - 1 - extraDecrement\n\nsolve :: String -> String\nsolve = show . cost . map read . tail. words\n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (elemIndices)\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nindices :: [Int] -> (Int, Int, Int)\nindices xs = let (a,b) = (minimum xs, maximum xs)\n n = length xs\n in (n,\n last $ a `elemIndices` xs,\n head $ b `elemIndices` xs)\n\nmain :: IO ()\nmain = print . steps . indices . map read . words =<< (getLine >> getLine)\n where steps (n,a,b) = let i = if a < b then -1 else 0\n in i + n + b - a - 1"}, {"source_code": "import Data.List\nimport Data.Maybe\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n a <- readItems :: IO [Int]\n let diffMin = fromJust $ findIndex (== (minimum a)) (reverse a)\n let diffMax = fromJust $ findIndex (== (maximum a)) a\n let diff = diffMin + diffMax\n putStrLn $ show $ if diff < n then diff else diff - 1\n"}, {"source_code": "\nminIndex :: [Int] -> (Int, Int)\nminIndex [x] = (0, x)\nminIndex (x:l) = \n let (i, y) = minIndex l\n in if x < y then (0, x) else (i+1, y)\n\nmaxIndex :: [Int] -> (Int, Int)\nmaxIndex [x] = (0, x)\nmaxIndex (x:l) = \n let (i, y) = maxIndex l\n in if x >= y then (0, x) else (i+1, y)\n\nmain = do\n getLine\n line <- getLine\n let soldiers = map read $ words line\n min = fst $ minIndex soldiers\n max = fst $ maxIndex soldiers\n len = length soldiers\n secs = max + (len - 1 - min) - if max > min then 1 else 0\n putStrLn $ show secs\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int]\n let\n n = length as\n i = fromJust (elemIndex (maximum as) as)\n j = n-1 - (fromJust $ elemIndex (minimum as) (reverse as))\n\n print $ if i < j then i + (n-1-j) else i + (n-1-j) - 1\n\n"}, {"source_code": "import Data.List\nimport Data.List.Split\n\n(|>) x f = f x\nmain = interact solve\n\nsolve contents = let\n nums = contents |> lines |> (!! 1) |> words |> map read :: [Int]\n in swaps nums |> show\n \nswaps nums = let\n mx = maximum nums\n (before, after) = span (/= mx) nums\n nums' = (head after):(before ++ tail after)\n mn = minimum nums'\n lastMinIndex = nums' |> findIndices (== mn) |> last\n in length before + length nums - 1 - lastMinIndex\n \n \n"}, {"source_code": "import Data.List\n\nmain = interact $ show . solve . input\n\ninput :: String -> [Int]\ninput = (map read) . words\n\nsolve (n:xs) = posMax + (n - posMin - 1) - swapMaxMin where\n posMax = minimum (maximum xs `elemIndices` xs)\n posMin = maximum (minimum xs `elemIndices` xs)\n swapMaxMin = if posMin < posMax then 1 else 0\n"}, {"source_code": "import Control.Applicative\nmain = do\n n <- readLn\n a <- map read . words <$> getLine\n print $ solve a (0, 0) (101, 0) 0 n\n\nsolve [] (_, a) (_, b) _ n = a+n-b-1-(if a > b then 1 else 0)\nsolve (a:as) (ma, maxp) (mi, minp) p n =\n solve as (if ma < a then (a, p) else (ma, maxp)) (if mi >= a then (a, p) else (mi, minp)) (p+1) n\n \n\n\n"}, {"source_code": "getminTail ::[Int] ->Int\ngetminTail a = fst$last$filter (\\x -> snd x == minimum a) (zip [1..(length a)] a)\ngetmaxHead ::[Int] ->Int\ngetmaxHead a = fst$head$filter (\\x -> snd x == maximum a) (zip [1..(length a)] a)\ncalc ::Int ->Int -> Int -> Int\ncalc n mt mh |mt < mh = (n-mt)+(mh-2)\n |otherwise =(n-mt)+(mh-1)\ngetAns ::[Int] -> Int\ngetAns a = calc (length a) (getminTail a) (getmaxHead a)\nmain=interact$show.getAns.(map read).tail.words"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve . concat.map (map read.words).take 2 . lines\nsolve :: [Int]->Int\nsolve (x:xs) = let minidx = last $ elemIndices (minimum xs) xs ; maxidx = fromJust $ elemIndex (maximum xs) xs in if maxidx>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nfirstMaximum :: [Int] -> Int\nfirstMaximum xs = head (elemIndices (maximum xs) xs)\n\nlastMinimum :: [Int] -> Int\nlastMinimum xs = head (elemIndices (minimum xs) (reverse xs))\n\nsolve :: Int -> [Int] -> Int\nsolve n xs\n | (a + b) >= n = a + b - 1\n | otherwise = a + b\n where\n a = firstMaximum xs\n b = lastMinimum xs\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- Main.reads\n print (solve n xs)"}, {"source_code": "import Control.Applicative\nimport Data.List (elemIndices)\n\nmain = do\n n <- read <$> getLine\n xs <- map read . words <$> getLine :: IO [Int]\n let mn = minimum xs\n mx = maximum xs\n mxi = head . elemIndices mx $ xs\n mni = last . elemIndices mn $ xs\n print $ n-1-mni + mxi - if mxi > mni then 1 else 0\n"}, {"source_code": "\nrightMostMin nos = snd $ foldl newMin (101, 0) (zip nos [0..])\n where newMin (a, b) (x, y) = if a >= x\n then (x, y)\n else (a, b)\n\nleftMostMax nos = snd $ foldr newMax (-1, 0) (zip nos [0..])\n where newMax (x, y) (a, b) = if x >= a\n then (x, y)\n else (a, b)\n\ngetMinTime :: Int -> [Int] -> Int\ngetMinTime n nos | minPos > maxPos = (n - 1 - minPos) + maxPos\n | otherwise = (n - 1 - minPos) + maxPos - 1\n where minPos = rightMostMin nos\n maxPos = leftMostMax nos\n\nmain = do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let nos = map (\\x -> read x :: Int) (words line)\n ans = getMinTime n nos\n putStrLn $ show ans\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = maxH + (n - 1 - minL) + (if maxH < minL then 0 else -1)\n where n = length a\n maxi = maximum a\n mini = minimum a\n maxH = head $ elemIndices maxi a\n minL = last $ elemIndices mini a\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n print $ solve a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\n\nprocess a = pma + pmi + if pma >=(length a- pmi) then (-1) else 0\n where mi = minimum a\n ma = maximum a\n pmi = fromJust $ elemIndex mi (reverse a)\n pma = fromJust $ elemIndex ma a\n\n\n\n\nmain=do\n getLine\n a<-map read <$> words <$> getLine ::IO [Int]\n print $ process a\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n seq <- replicateM n readInt\n return seq\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve seq = ans\n where\n maxv = maximum seq\n minv = minimum seq\n\n n = length seq\n\n ans = minimum [ i + (n - 1 - j) - if j < i then 1 else 0\n | (i, ai) <- zip [0..] seq\n , (j, aj) <- zip [0..] seq\n , ai == maxv && aj == minv && i /= j\n ]\n\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Data.List ((\\\\), elemIndex)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve xs = fromJust (elemIndex (maximum xs) xs) + fromJust (elemIndex (minimum xs) xs')\n where xs' = reverse (xs \\\\ [maximum xs])\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n as <- fmap (map read . words) getLine :: IO [Int]\n let i = head (elemIndices (maximum as) as)\n j = last (elemIndices (minimum as) as)\n print $ i + n - j - 1 - if i > j then 1 else 0\n"}, {"source_code": "import Data.List\nsolve :: [Int] -> Int\nsolve xs | ok xs = 0\n | otherwise = solve (step xs) + 1\nok :: [Int] -> Bool\nok xs = head xs == maximum xs && last xs == minimum xs\nstep :: [Int] -> [Int]\nstep xs | head xs == maximum xs = exchange2 xs minIndex\n | otherwise = exchange2 xs $ maxIndex-1\n where minIndex = last $ elemIndices (minimum xs) xs\n maxIndex = head $ elemIndices (maximum xs) xs\nexchange2 :: [a] -> Int -> [a]\nexchange2 (x:y:ys) 0 = y:x:ys\nexchange2 (x:xs) l = x : exchange2 xs (l-1)\nmain = getLine >> fmap (map read . words) getLine >>= print . solve\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/144/A\n\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = maxH + (n - 1 - minL) + (if maxH < minL then 0 else -1)\n where n = length a\n maxi = maximum a\n mini = minimum a\n maxH = head $ elemIndices maxi a\n minL = last $ elemIndices mini a\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n print $ solve a\n"}, {"source_code": "import Control.Applicative\n\nmain = do n <- read <$> getLine\n xs <- map read . words <$> getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs\n | l == h = 0\n | l < h = (n-l) + (h-1) -1\n | otherwise = (n-l) + (h-1)\n where h = succ $ (n-) $ snd $ maximum $ zip xs [n,(n-1)..1]\n l = succ $ (n-) $ snd $ minimum $ zip xs [n,(n-1)..1]\n"}, {"source_code": "import Data.Function\nimport Data.List\n\nmoveMax xs = [x] ++ takeWhile (Int\nfindAll xs = findMax xs + findMin (moveMax xs)\n\nresult [n,xs] = findAll.map read.words$xs\n\nmain=interact$show.result.lines\n\t"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int]\n let\n n = length as\n i = fromJust $ elemIndex (maximum as) as\n j = n - (fromJust $ elemIndex (minimum as) (reverse as)) + 1\n\n print $ if i < j then i + (n-j+1) else i+n-j\n\n"}, {"source_code": "import Data.List ((\\\\), elemIndex)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve xs = fromJust (elemIndex (maximum xs) xs) + fromJust (elemIndex (minimum xs) xs')\n where xs' = reverse xs \\\\ [maximum xs]\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/144/A\n\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = maxH + (n-1-minL) + (if maxH < minL then 0 else -1)\n where n = length a\n maxi = maximum a\n mini = minimum a\n maxH = head $ elemIndices maxi a\n minL = head $ elemIndices mini a\n\nmain :: IO ()\nmain = do\n getLine\n a <- getIntList\n print $ solve a\n"}, {"source_code": "import Data.List\nmain = getLine >> getLine >>= putStrLn.show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve soldiers = pred $ tallest + shortest\n where find f set = maybe 0 (+0) $ findIndex (==f set) set\n tallest = find maximum soldiers\n shortest = find minimum $ reverse soldiers\n"}, {"source_code": "import Data.List (maximumBy, minimumBy)\nimport Data.Ord (comparing)\n\nmaxIndex :: Ord a => [a] -> Int\nmaxIndex = fst . maximumBy (comparing snd) . zip [0..]\n\nminIndex :: Ord a => [a] -> Int\nminIndex = fst . minimumBy (comparing snd) . zip [0..]\n\nprocess :: [Int] -> Int\nprocess xs\n | imax + imin > n-1 = imax + imin - 1\n | otherwise = imax + imin\n where\n n = length xs\n imax = maxIndex xs\n imin = minIndex (reverse xs)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}], "src_uid": "ef9ff63d225811868e786e800ce49c92"} {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\n\nextract (x:xs)=take (read x::Int) xs\ncalc x=length (filter (=='1') x)\nsolve x=maximum $ map calc $ map (\\k->(map (\\y->y!!k) x)) [0..6]\n\nmain=interact$show.solve.extract.lines\n\n\n{-\n\tfmap (map (\\x->read x::Int).words) $ getLine\n-}", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Char\n-- import Data.List\n\nmain = do\n n <- readLn :: IO Int\n print =<< maximum . foldr (zipWith (+)) (replicate 7 0) <$> replicateM n ( map digitToInt <$> getLine)\n"}], "negative_code": [], "src_uid": "d8743905d56c6c670b6eeeddc7af0e36"} {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Bits\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [C.ByteString] -> Builder\nsolve (sn:sx:sy:s:_) = intDec res <> char7 '\\n'\n where\n !n = ri sn\n !x = ri sx\n !y = ri sy\n !res = sum $ zipWith xor (replicate y 0 ++ (1 : repeat 0)) $ map (subtract 48 . ord) $ C.unpack $ C.take x $ C.reverse s\n \nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n", "positive_code": [{"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n params <- (fmap read . words) <$> getLine\n digits <- getLine\n print $ minOps params digits\n\nminOps :: [Int] -> String -> Int\nminOps [n, x, y] digits = let\n digits' = drop (n-x) digits\n digits'' = take (x -y -1) digits' ++\n [case digits' !! (x -y-1) of\n '0' -> '1'\n '1' -> '0'] ++ drop (x-y) digits'\n in\n length $ filter (=='1') digits''\n"}, {"source_code": "import Data.Char\n\nmain = do\n header <- getLine\n l <- getLine\n putStrLn . show $ solve header l\n\nsolve :: String -> String -> Int\nsolve header l_ = \n let [n, x, y] = (map read . words) header in\n let l = (take x . reverse) l_ in\n let f (pos, val) = \n if pos == y then\n (if val == '0' then 1 else 0)\n else\n (if val == '1' then 1 else 0)\n in\n sum $ map f (zip [0..] l)\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString as B\n\nmain = do\n zz <- fmap (map read . words) getLine :: IO [Int]\n let n = zz !! 0\n let x = zz !! 1\n let y = zz !! 2\n s <- fmap (map (== '1') . reverse) getLine\n let t = take x s\n let ans = (foldl' (\\s x -> if x then s + 1 else s) 0 t) - (if t !! y then 1 else (-1))\n putStrLn $ show ans\n return ()\n"}], "negative_code": [], "src_uid": "075988685fa3f9b20bd215037c504a4f"} {"source_code": "getList :: Int -> Int -> Int -> Int -> [Int] -> [Int]\ngetList cur sub n k a\n\t| cur == n * k\t\t= []\n\t| mod cur n == 0 \t= (a !! (div cur n)) : (getList (cur + 1) sub n k a)\n\t| contain sub a\t\t= getList cur (sub + 1) n k a\n\t| otherwise\t\t\t= sub : (getList (cur + 1) (sub + 1) n k a)\n\ncontain :: Int -> [Int] -> Bool\ncontain _ [] = False\ncontain c (x:xs) = (x == c) || (contain c xs) \n\nprintList :: [Int] -> IO()\nprintList [] = do\n\tputStrLn \"\"\nprintList (x:xs) = do\n\tputStr ((show x) ++ \" \")\n\tprintList xs\n\nmain :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tlet n = read ((words str1) !! 0)\n\tlet k = read ((words str1) !! 1)\n\tlet a = map read (words str2)\n\tprintList (getList 0 1 n k a)\n\t\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n let oranges = [1..n*k] \\\\ as\n let go [] _ = return ()\n go (a:as) l = do\n let (l1,l2) = splitAt (n-1) l\n putStrLn $ unwords $ map show $ (a:l1)\n go as l2\n go as oranges\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Applicative\n\nmain = do\n [n,k] <- map (read :: String -> Int) . words <$> getLine\n ks <- map (read :: String -> Int) . words <$> getLine\n let a = [1..n*k] \\\\ ks\n m = n-1\n b = if null a then replicate k [] else unfoldr (\\x -> if null x then Nothing else Just (take m x, drop m x)) a\n putStrLn $ concat $ intersperse \"\\n\" $ map (concat . intersperse \" \" . map show) $ zipWith (:) ks b\n "}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List ((\\\\), intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> Int -> [Int] -> [[Int]]\nsolve n k xs = solve' xs ([1..n*k] \\\\ xs)\n where\n solve' [] _ = []\n solve' (x:xs) ys = (x : take (n-1) ys) : solve' xs (drop (n - 1) ys)\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n xs <- reads\n mapM_ prints $ solve n k xs\n"}, {"source_code": "-- Codeforces 244A\n\nimport Data.List\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . map read . words\n\nsolve :: [Int] -> String\nsolve (n:k:xs) = intercalate \"\\n\" $ map (intercalate \" \" . map show . sort) $ transpose $ (xs:) $ map (\\i -> take k $ drop ((i-1)*k) other) [1..n-1] where other = filter (`notElem` xs) [1..n*k]\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map read.words <$> getLine\n let rest = [1..n*k]\\\\xs\n ans = transpose $ xs:slices k rest\n putStr.unlines.map (unwords.map show) $ ans\n \nslices :: Int -> [a] -> [[a]]\nslices _ [] = []\nslices n xs = let (ys,zs) = splitAt n xs in ys:slices n zs"}, {"source_code": "import Data.List\n\nmain = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines\nsolve [[n, k], xs] = solve' xs ([1..n*k] \\\\ xs)\n where\n solve' [] _ = []\n solve' (x:xs) ys = (x : take (n-1) ys) : solve' xs (drop (n - 1) ys)\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.List\nimport Control.Applicative\n\nmain = do\n [n,k] <- map (read :: String -> Int) . words <$> getLine\n ks <- map (read :: String -> Int) . words <$> getLine\n let a = [1..n*k] \\\\ ks\n m = n-1\n b = unfoldr (\\x -> if null x then Nothing else Just (take m x, drop m x)) a\n putStrLn $ concat $ intersperse \"\\n\" $ map (concat . intersperse \" \" . map show) $ zipWith (:) ks b\n "}, {"source_code": "import Data.List\n\nmain = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines\nsolve [[n, 1], a] = [[1..n]]\nsolve [[n, k], a] = zipWith (:) a $ splitEvery (k-1) $ [1..n*k] \\\\ a\n where \n splitEvery _ [] = []\n splitEvery x ys = take x ys : splitEvery x (drop x ys)"}, {"source_code": "import Data.List\n\nmain = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines\nsolve [[1, k], a] = map (\\x -> [x]) a\nsolve [[n, 1], a] = [[1..n]]\nsolve [[n, k], a] = zipWith (:) a $ splitEvery (k-1) $ [1..n*k] \\\\ a\n where \n splitEvery _ [] = []\n splitEvery x ys = take x ys : splitEvery x (drop x ys)"}], "src_uid": "928f18ee5dbf44364c0d578f4317944c"} {"source_code": "import Control.Applicative\nimport Data.List\n\n\nlis = [div ((i-2)*180) i | i<-[3..1000], mod ((i-2)*180) i==0 ]\nprocess s | elem s lis = \"YES\"\n | otherwise = \"NO\"\n\n\n\n\nmain = do\n getLine\n s<- map read <$> lines <$> getContents ::IO [Int]\n mapM_ putStrLn $ map process s\n", "positive_code": [{"source_code": "main=interact$unlines.map (f.read).tail.words\nf n\n\t| n >= 180 = \"NO\"\n\t| mod 360 (180-n) == 0 = \"YES\"\n\t| otherwise = \"NO\""}, {"source_code": "isPolyAngle :: Int -> Bool\nisPolyAngle a = mod 360 b == 0 \n where b = 180 - a\n\nboolMap :: Bool -> String\nboolMap True = \"YES\"\nboolMap False = \"NO\"\n\nprintList :: [String] -> IO()\nprintList (a:b) = do\n putStrLn a\n printList b\nprintList _ = do\n putStr \"\"\n\nmain :: IO()\nmain = do\n str <- getContents\n let a = map read (words str) :: [Int]\n printList (map (boolMap . isPolyAngle) (tail a))\n"}, {"source_code": "\n\n\nconv lst kk\n | (null lst) = reverse kk\n | otherwise = conv (tail lst) (((read (head lst))::Int) : kk)\n\nyesno lst oo\n | (null lst) = reverse oo\n | (mod 360 (180 - (head lst))) == 0 = yesno (tail lst) (\"YES\" : oo)\n | otherwise = yesno (tail lst) (\"NO\" : oo)\n \nmain = do\n ff <- getLine\n let aa = (read ff)::Int\n hh = replicate aa (getLine)\n uu <- sequence hh\n\n let tests = conv uu []\n ans = yesno tests []\n\n mapM_ putStrLn ans\n \n -- putStrLn (show ans)\n\n\n\n"}, {"source_code": "main = interact $\n unlines . map (s . read) . tail . words\n where\n s n | 360 `mod` (180-n) == 0 = \"YES\"\n | otherwise = \"NO\"\n"}, {"source_code": "main = do\n getLine\n xs <- fmap (map read . lines) getContents\n\n let\n solve 60 = True\n solve x = 360 `mod` (180-x) == 0\n\n putStrLn $ unlines $ map (\\x -> if x then \"YES\" else \"NO\") $ map solve xs\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- getLine >>= return .read\n replicateM_ n solve\n \nsolve :: IO ()\nsolve = do\n a <- getLine >>= return . read\n putStrLn $ if 360 `mod` (180 - a) == 0 then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = readLn >>= \\ n -> (solve =<< forM [1 .. n] ( \\i -> fst.fromJust.C.readInt <$>C.getLine))\nsolve xs = forM_ xs $ \\i-> if 360 `mod` (180-i) == 0 then putStrLn \"YES\" else putStrLn \"NO\" "}, {"source_code": "\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\nmain' :: IO ()\nmain' = do\n a <- readLn\n putStrLn $ (360 `mod` (180 - a) == 0) ? \"YES\" $ \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n sequence_ (replicate n main')"}, {"source_code": "main = interact $ unlines . f . lines\nf (x:xs) = map (g . read) xs\ng x | rem 360 (180-x) == 0 = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "an = 0 : [180-(360 `div` i) | i <- [1..360]]\nmain = interact $ unlines . f . lines\nf (x:xs) = map (g . read) xs\ng x | elem x an && (rem 360 (180-x) == 0) = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "import Control.Monad\n\ngood :: Int -> Bool\ngood a = any (\\n -> a * n == 180 * (n - 2)) [3..1000]\n\nmain = do\n n <- read `fmap` getLine\n a <- sequence $ take n $ repeat $ read `fmap` getLine\n forM a $ \\i ->\n putStrLn (if good i\n then \"YES\"\n else \"NO\")\n"}, {"source_code": "import Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n test_number <- readLn :: IO Int\n angles <- replicateM test_number readLn :: IO [Int]\n mapM_ (putStrLn . to_string . check) angles\n where\n check :: Int -> Bool\n check x = 360 `mod` (180 - x) == 0\n to_string True = \"YES\"\n to_string _ = \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= mapM_ (putStrLn . yesno . solve . read) . tail . lines\n\nsolve :: Int -> Bool\nsolve a = 360 `mod` (180 - a) == 0\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "main = interact $ unlines . map (solve . read) . tail . words\nsolve n | 360 `mod` (180-n) == 0 = \"YES\"\n | otherwise = \"NO\"\n"}, {"source_code": "yes_or_no x = if (360 `mod` (180-x) == 0) && (360 `div` (180-x) > 2) then \"YES\" else \"NO\"\nmkOut = do\n x <- getLine\n putStrLn(yes_or_no(read x))\n\nn_times x | x > 0 = do mkOut;\n n_times(x-1)\n | otherwise = putStr \"\"\nmain = do\n n_input <- getLine\n n_times(read n_input)"}, {"source_code": "main=interact$unlines.map(\\x->if(\\n->360`mod`(180-n)==0)x then\"YES\"else\"NO\").map read.tail.lines"}, {"source_code": "\ufefffit a = 360 `mod` (180 - a) == 0\n\nloop 0 = return ()\nloop n = do\n a <- getLine\n putStrLn $ if fit (read a :: Int) then \"YES\" else \"NO\"\n loop (n-1)\n \nmain = do\n n <- getLine\n loop (read n :: Int)\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\n \n\nans= [div x n | n<-[3..1000],let x = 180 *(n-2) , (div x n)*n ==x ]\n\ncheck a | elem a ans = \"YES\"\n\t| otherwise = \"NO\"\n\nmain= do\n\t getLine\n\t s<-map read. words <$> getContents::IO [Int]\n\t mapM_ putStrLn $ map check s \n \t "}, {"source_code": "import Control.Monad\n\ncheck a\n | 360 `mod` (180-a) == 0 = True\n | otherwise = False\n\nsolve a\n | check a == True = \"YES\"\n | otherwise = \"NO\"\n\nsolveCase = do\n input <- getLine\n let a = read input :: Int\n putStrLn(solve a)\n\nmain = do\n caseNumStr <- getLine\n let t = read caseNumStr :: Int\n replicateM_ t solveCase"}, {"source_code": "main = do\n m <- readLn\n n <- sequence $ replicate m getLine\n let n2 = map read n\n mapM_ putStrLn $ map pol n2\npol :: Int -> String\npol x = if (x `elem` [quot (180 * n) (n+2) | n <- filter (\\x -> mod 360 (x+2) == 0) [1..360]]) then \"YES\" else \"NO\""}, {"source_code": "go x \n | k == 0 = \"YES\"\n | otherwise = \"NO\"\n where k = mod 360 (180 - x) \nsolve :: Int -> IO ()\nsolve 0 = return () \nsolve n = do\n readLn >>= putStrLn. go\n solve $ n - 1\nmain = do\n n <- readLn :: IO Int\n solve n\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn. map (\\x -> if 360 `mod` (180-x) == 0 then \"YES\" else \"NO\"). map (\\x -> read x :: Int). tail. words \n\n"}, {"source_code": "process :: Int -> Bool\nprocess a = 360 `mod` (180-a) == 0\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n as <- fmap (map readInt.words) getContents\n mapM_ putStrLn . map (\\a -> [\"NO\",\"YES\"] !! fromEnum (process a)) $ as"}, {"source_code": "main = interact f\n where f = unlines . map (isFancy.read) . tail . lines\n \nisFancy x = if (360 `mod` (180 - x)) == 0 then \"YES\" else \"NO\""}, {"source_code": "import Data.List as List\nimport Data.Maybe as Maybe\n\ngetStringAfterChar :: Char -> String -> String\ngetStringAfterChar c str = drop ((Maybe.fromJust $ c `elemIndex` str) + 1) str\n\nisAppropriate :: Int -> Int -> Bool\nisAppropriate n angle = 180 * (n - 2) == angle * n\n\nrepeatX :: Int -> IO ()\nrepeatX x\n | x > 0 = do\n \tsolveCase\n \trepeatX $ x - 1\n | otherwise = return ()\n\nsolveCase :: IO ()\nsolveCase = do\n\tline <- getLine\n\tlet intAngle = read line :: Int\n\tlet floatAngle = fromIntegral intAngle\n\tlet sideNum = round $ 2 / (1 - (floatAngle / 180))\n\tlet result = if isAppropriate sideNum intAngle\n\t\tthen \"YES\"\n\t\telse \"NO\"\n\tputStrLn result\n\nmain = do\n\tline <- getLine\n\tlet testNumber = read line :: Int\n\trepeatX testNumber"}], "negative_code": [{"source_code": "main=interact$unlines.map (f.read).tail.words\nf n\n\t| n >= 180 = \"No\"\n\t| mod 360 (180-n) == 0 = \"Yes\"\n\t| otherwise = \"No\""}, {"source_code": "isPolyAngle :: Int -> Bool\nisPolyAngle a = mod 360 b == 0 \n where b = 180 - a\n\nboolMap :: Bool -> String\nboolMap True = \"YES\"\nboolMap False = \"NO\"\n\nprintList :: [String] -> IO()\nprintList (a:b) = do\n putStrLn a\n printList b\nprintList _ = do\n putStr \"\"\n\nmain :: IO()\nmain = do\n str <- getContents\n let a = map read (words str) :: [Int]\n printList (map (show . boolMap . isPolyAngle) (tail a))\n"}, {"source_code": "yes_or_no x = if (360 `mod` (180-x) == 0) && (360 `div` (180-x) > 2) then \"YES\" else \"NO\"\nmkOut = do\n x <- getLine\n putStrLn(show(yes_or_no(read x)))\n\nn_times x | x > 0 = do mkOut;\n n_times(x-1)\n | otherwise = putStr \"\"\nmain = do\n n_input <- getLine\n n_times(read n_input)\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\ufefffit a = 360 `mod` (180 - a) == 0\n\nloop 0 = return ()\nloop n = do\n a <- getLine\n putStrLn $ if fit (read a :: Int) then \"YES\" else \"NO\"\n \nmain = do\n n <- getLine\n loop (read n :: Int)\n "}, {"source_code": "import Control.Monad\n\ncheck a\n | 360 `mod` (180-a) == 0 = True\n | otherwise = False\n\nsolve a\n | check a == True = \"YES\"\n | otherwise = \"No\"\n\nsolveCase = do\n input <- getLine\n let a = read input :: Int\n putStrLn(solve a)\n\nmain = do\n caseNumStr <- getLine\n let t = read caseNumStr :: Int\n replicateM_ t solveCase"}, {"source_code": "main = do\n m <- readLn\n n <- sequence $ replicate m getLine\n let n2 = map read n\n mapM_ putStrLn $ map pol n2\npol :: Int -> String\npol x = if (x `elem` [quot (180 * n) (n+2) | n <- filter (\\x -> mod 360 x == 0) [1..360]]) then \"YES\" else \"NO\""}], "src_uid": "9037f487a426ead347baa803955b2c00"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap.Strict as M\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nupdate :: Num a => a -> Maybe a -> Maybe a\nupdate delta value = case value of\n Nothing -> Just delta\n Just x -> Just (x + delta)\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n _ <- getInts\n as <- getInts\n let counts = foldl' (flip $ M.alter $ update 1) M.empty $ map abs as\n result = M.foldl' (\\total count -> total + min 2 count) 0 $ M.adjust (const 1) 0 counts\n return $ intDec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n a <- map abs <$> getInts n\r\n let\r\n cts :: UArray Int Int\r\n cts = accumArray (+) 0 (0, maximum a) $ zip a (repeat 1)\r\n cts' = cts // [(0, min 1 (cts ! 0))]\r\n ans = foldl' (\\acc x -> acc + min x 2) 0 $ elems cts'\r\n pure $ putInts [ans]\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap.Strict as M\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nupdate :: Num a => a -> Maybe a -> Maybe a\nupdate delta value = case value of\n Nothing -> Just delta\n Just x -> Just (x + delta)\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n _ <- getInts\n as <- getInts\n let counts = foldl' (flip $ M.alter $ update 1) M.empty as\n result = M.foldl' (\\total count -> total + min 2 count) 0 $ M.adjust (const 1) 0 counts\n return $ intDec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "src_uid": "23ef311011b381d0ca2e84bc861f0a31"} {"source_code": "{-\nCodeforces Round #332\n\nProblem 599 B. Spongebob and Joke\n\n@author yamaton\n@date 2015-12-01\n-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Text.Printf (printf)\nimport Data.Maybe (fromJust)\n-- import qualified Data.Binary as Bin\nimport qualified Data.ByteString.Char8 as B\n-- import qualified Data.ByteString.Lazy as BL\n-- import qualified System.IO as IO\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n\nsolve :: [Int] -> [Int] -> (String, [Int])\nsolve fs bs\n | any (`S.notMember` setFs) bs = (\"Impossible\", [])\n | length ys /= S.size (S.fromList ys) = (\"Ambiguity\", [])\n | otherwise = (\"Possible\", recovered)\n where\n setFs = S.fromList fs\n setBs = S.fromList bs\n ys = filter (`S.member` setBs) fs\n invFsPairs = map (\\(i, f) -> (f, i)) $ filter (\\(_, f) -> f `S.member` setBs) (zip [1..] fs)\n invFsDict = M.fromList invFsPairs\n recovered = map (\\i -> fromJust (M.lookup i invFsDict)) bs\n\n\nmain :: IO ()\nmain = do\n _ <- B.getLine\n fs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n bs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n let (msg, lst) = solve fs bs\n putStrLn msg\n if (null lst)\n then return ()\n -- else (B.putStrLn . B.unwords . map (BL.toStrict . Bin.encode)) lst\n else (putStrLn . unwords . map show) lst\n --\n -- IO.hPutStrLn IO.stderr $ printf \"xs = %s\" (show xs)\n -- IO.hPutStrLn IO.stderr $ printf \"result = %d\" msg\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Array.IArray\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (n : _ : rest) <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents\n let (f, b) = splitAt n rest\n let invf = accumArray (flip (:)) [] (1, n) $ zip f [1 ..]\n either putStrLn ((putStrLn \"Possible\" >>) . putStrLn . concat . intersperse \" \" . map show) $ solve b invf\n\nsolve :: [Int] -> Array Int [Int] -> Either String [Int]\nsolve [] _ = Right []\nsolve (b : bs) invf =\n case invf ! b of\n [a] -> solve bs invf >>= Right . (a :)\n [] -> Left \"Impossible\"\n _ -> solve bs invf >>= (const $ Left \"Ambiguity\")\n"}, {"source_code": "import Control.Applicative\nimport Data.Array.IArray\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n (n : _ : rest) <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents\n let (f, b) = splitAt n rest\n let invf = accumArray (flip (:)) [] (1, n) $ zip f [1 ..]\n either putStrLn ((putStrLn \"Possible\" >>) . putStrLn . concat . intersperse \" \" . map show) $ solve b invf\n\nsolve :: [Int] -> Array Int [Int] -> Either String [Int]\nsolve [] _ = Right []\nsolve (b : bs) invf =\n case invf ! b of\n [a] -> solve bs invf >>= Right . (a :)\n [] -> Left \"Impossible\"\n _ -> solve bs invf >> Left \"Ambiguity\"\n"}, {"source_code": "{-\nCodeforces Round #332\n\nProblem 599 B. Spongebob and Joke\n\n@author yamaton\n@date 2015-12-01\n-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (fromJust)\nimport qualified Data.Binary as Bin\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy as BL\nimport qualified System.IO as IO\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n\nsolve :: [Int] -> [Int] -> (String, [Int])\nsolve fs bs\n | any (`S.notMember` setFs) bs = (\"Impossible\", [])\n | length ys /= S.size (S.fromList ys) = (\"Ambiguity\", [])\n | otherwise = (\"Possible\", recovered)\n where\n setFs = S.fromList fs\n setBs = S.fromList bs\n ys = filter (`S.member` setBs) fs\n invFsPairs = map (\\(i, f) -> (f, i)) $ filter (\\(_, f) -> f `S.member` setBs) (zip [1..] fs)\n invFsDict = M.fromList invFsPairs\n recovered = map (\\i -> fromJust (M.lookup i invFsDict)) bs\n\n\nmain :: IO ()\nmain = do\n _ <- B.getLine\n fs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n bs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n let (msg, lst) = solve fs bs\n putStrLn msg\n if (null lst)\n then return ()\n -- else (B.putStrLn . B.unwords . map (BL.toStrict . Bin.encode)) lst\n else (putStrLn . unwords . map show) lst\n --\n -- IO.hPutStrLn IO.stderr $ printf \"xs = %s\" (show xs)\n -- IO.hPutStrLn IO.stderr $ printf \"result = %d\" msg\n"}, {"source_code": "{-\nCodeforces Round #332\n\nProblem 599 B. Spongebob and Joke\n\n@author yamaton\n@date 2015-12-01\n-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Text.Printf\n-- import System.IO (hPutStrLn, stderr)\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\nimport Data.Maybe (fromJust)\n\nsolve :: [Int] -> [Int] -> (String, [Int])\nsolve fs bs\n | any (`S.notMember` setFs) bs = (\"Impossible\", [])\n | length ys /= S.size (S.fromList ys) = (\"Ambiguity\", [])\n | otherwise = (\"Possible\", recovered)\n where\n setFs = S.fromList fs\n setBs = S.fromList bs\n ys = filter (`S.member` setBs) fs\n invFsPairs = map (\\(i, f) -> (f, i)) $ filter (\\(_, f) -> f `S.member` setBs) (zip [1..] fs)\n invFsDict = M.fromList invFsPairs\n recovered = map (\\i -> fromJust (M.lookup i invFsDict)) bs\n\n\nmain :: IO ()\nmain = do\n [n, m] <- (map read . words) <$> getLine :: IO [Int]\n fs <- (map read . words) <$> getLine :: IO [Int]\n bs <- (map read . words) <$> getLine :: IO [Int]\n let (msg, lst) = solve fs bs\n putStrLn msg\n if (null lst)\n then return ()\n else ((putStrLn . unwords . map show) lst)\n --\n -- hPutStrLn stderr $ printf \"xs = %s\" (show xs)\n -- hPutStrLn stderr $ printf \"result = %d\" msg\n"}], "negative_code": [], "src_uid": "468e8a14dbdca471f143f59b945508d0"} {"source_code": "import Data.Char\nimport Data.List\nimport Data.Array\n\nnumbers :: String -> [Int]\nnumbers = map read . words\n\ngets :: Int -> IO [String]\ngets n = mapM (\\i -> getLine) [0 .. n - 1]\n\ncount :: Char -> [Char] -> Int\ncount a b = sum $ map check b\n where\n check x\n | x == a = 1\n | otherwise = 0\n\ntoChar :: Int -> Char\ntoChar 0 = '.'\ntoChar a = chr (ord '0' + a)\n\ncalculate :: (Int, Int) -> [String] -> [String]\ncalculate (n, m) a =\n map update [0 .. n - 1]\n where\n update i = map (w i) [0 .. m - 1]\n w i j\n | index (i, j) == '*' = '*'\n | otherwise = toChar $ count '*' (map index [(i + x, j + y) | x <- [-1 .. 1], y <- [-1 .. 1]])\n index (u, v)\n | u == -1 || u == n = ' '\n | v == -1 || v == m = ' '\n | otherwise = a !! u !! v\n\ninfix 4 ??\n(??) :: a -> a -> Bool -> a\na ?? b = \\i -> if i then a\n else b\n\nmain :: IO ()\nmain = do\n firstLine <- getLine\n let [n, m] = numbers firstLine\n input <- gets n\n putStrLn . (\"YES\" ?? \"NO\") . (== input) . calculate (n, m) $ input\n", "positive_code": [{"source_code": "{-# Language BangPatterns, ViewPatterns #-}\nimport Control.DeepSeq\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nmain = do\n [n, m] <- fmap (map readInt . words) $ getLine\n board <- fmap (parseInput n m) $ getContents\n putStrLn $ solve n m board\n\nsolve n m board\n | result == True = \"YES\"\n | result == False = \"NO\"\n where\n result = and $ map (uncurry isGood) $ zip expected actual\n\n expected = map neighbors $ Map.keys board\n actual = Map.elems board\n isGood a '*' = True\n isGood a '.' = a == '0'\n isGood a b = a == b\n\n neighbors (a,b) = intToDigit $ length $ do\n x <- [a-1..a+1]\n y <- [b-1..b+1]\n guard $ (x,y) /= (a,b)\n guard $ (fromMaybe '0' $ Map.lookup (x,y) board) == '*'\n return 1\n\nparseInput n m x = Map.fromList $ concat $ map (uncurry zip) $ zip grid $ lines x\n where\n grid = [[(x,y) | y <- [1..m]] | x <- [1..n]]\n\nreadInt x = (read x) :: Int\n"}, {"source_code": "import Data.List\nimport Data.List.Split\nimport Data.Char\n\ntype Grid a = [[a]]\n\nmain :: IO ()\nmain = do\n content <- getContents\n let ls = lines content\n n_m :: [Int]\n n_m = map read $ splitOn \" \" $ head ls\n grid = tail ls\n grid_sum = gridSum grid\n resultPair = zipWith zip grid_sum grid\n pass = all checkValid resultPair\n --putStrLn.unlines $ map (concat.(map show)) $ grid_sum\n if pass then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n\ncheckValid :: [(Int,Char)] -> Bool\ncheckValid = all pairValid\npairValid :: (Int,Char) -> Bool\npairValid (0,'.') = True\npairValid (_,'*') = True\npairValid (x,y) = x + (ord '0') == ord y\n\ngridSum grid =\n let x = length grid \n y = length $ head grid\n boardCore =(map.map) (\\ch -> if ch== '*' then 1::Int else 0::Int) grid \n boardShifts = [gridShift boardCore p | p <- nearCoords]\n zeroGrid = take (x+2) . repeat $ take (y+2) . repeat $ (0::Int)\n boardSum = init.tail $ foldr ((zipWith.zipWith) (+)) zeroGrid boardShifts\n in map (init.tail) boardSum\n\n\nnearCoords :: [(Int,Int)]\nnearCoords = [(1,0)\n ,(1,1)\n ,(0,1)\n ,(-1,1)\n ,(-1,0)\n ,(-1,-1)\n ,(0,-1)\n ,(1,-1)\n ]\n\ngridShift :: Grid Int -> (Int, Int) -> Grid Int\ngridShift grid _ | length grid == 0 = []\ngridShift _ (x,y) | not.elem (x,y) $ nearCoords = []\ngridShift gridCore (x,y) =\n let --oldx = length grid\n oldy = length.head $ gridCore\n rowUp = 1 + x\n rowDown = 1 - x\n colLeft = 1 + y\n colRight = 1 - y\n row_Up = take rowUp . repeat $ take (oldy + 2) . repeat $ (0::Int)\n row_Down = take rowDown . repeat $ take (oldy + 2) . repeat $ (0::Int)\n col_Left = take colLeft $ repeat (0::Int)\n col_Right = take colRight $ repeat (0::Int)\n in row_Up\n ++ (map (\\line -> col_Left ++ line ++ col_Right) gridCore)\n ++ row_Down\n\n\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Array\n\nnumbers :: String -> [Int]\nnumbers = map read . words\n\ngets :: (Int, Int) -> IO [String]\ngets (n, m) = mapM _getLine [0 .. n - 1]\n where\n _getLine :: Int -> IO String\n _getLine a = getLine\n\nfilterStar :: [String] -> [String]\nfilterStar = map (map replace)\n where\n replace '*' = '*'\n replace _ = '.'\n\ncount :: Char -> [Char] -> Int\ncount a b = sum $ map check b\n where\n check x\n | x == a = 1\n | otherwise = 0\n\ntoChar :: Int -> Char\ntoChar 0 = '.'\ntoChar a = chr (ord '0' + a)\n\ncalculate :: (Int, Int) -> [String] -> [String]\ncalculate (n, m) a =\n map update [0 .. n - 1]\n where\n update i = map (w i) [0 .. m - 1]\n w i j\n | index (i, j) == '*' = '*'\n | otherwise = toChar $ count '*' (map index [(i + x, j + y) | x <- [-1 .. 1], y <- [-1 .. 1]])\n index (u, v)\n | u == -1 || u == n = ' '\n | v == -1 || v == m = ' '\n | otherwise = a !! u !! v\n\ninfix 4 \n() :: a -> a -> Bool -> a\na b = \\i -> if i then a\n else b\n\nmain :: IO ()\nmain = do\n firstLine <- getLine\n let [n, m] = numbers firstLine\n res <- gets (n, m)\n putStrLn $ (\"YES\" \"NO\") $ (== res) $ calculate (n, m) $ filterStar res\n"}], "negative_code": [{"source_code": "{-# Language BangPatterns, ViewPatterns #-}\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nmain = do\n [n, m] <- fmap (map readInt . words) $ getLine\n board <- fmap (parseInput n m) $ getContents\n putStrLn $ solve n m board\n\nsolve n m board\n | result == True = \"YES\"\n | result == False = \"NO\"\n where\n result = and $ isGood <$> expected <*> actual\n\n expected = map neighbors $ Map.keys board\n actual = Map.elems board\n isGood a '*' = True\n isGood a '.' = a == '0'\n isGood a b = a == b\n\n neighbors (a,b) = intToDigit $ length $ do\n x <- [a-1..a+1]\n y <- [b-1..b+1]\n guard $ (fromMaybe '0' $ Map.lookup (x,y) board) == '*'\n return 1\n\nparseInput n m x = Map.fromList $ concat $ map (uncurry zip) $ zip grid $ lines x\n where\n grid = [[(x,y) | y <- [1..m]] | x <- [1..n]]\n\nreadInt x = (read x) :: Int\n"}, {"source_code": "import Data.List\nimport Data.List.Split\nimport Data.Char\n\ntype Grid a = [[a]]\n\nmain :: IO ()\nmain = do\n content <- getContents\n let ls = lines content\n n_m :: [Int]\n n_m = map read $ splitOn \" \" $ head ls\n grid = tail ls\n grid_sum = gridSum grid\n resultPair = zipWith zip grid_sum grid\n pass = all checkValid resultPair\n putStrLn.unlines $ map (concat.(map show)) $ grid_sum\n if pass then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n\ncheckValid :: [(Int,Char)] -> Bool\ncheckValid = all pairValid\npairValid :: (Int,Char) -> Bool\npairValid (0,'.') = True\npairValid (_,'*') = True\npairValid (x,y) = x + (ord '0') == ord y\n\ngridSum grid =\n let x = length grid \n y = length $ head grid\n boardCore =(map.map) (\\ch -> if ch== '*' then 1::Int else 0::Int) grid \n boardShifts = [gridShift boardCore p | p <- nearCoords]\n zeroGrid = take (x+2) . repeat $ take (y+2) . repeat $ (0::Int)\n boardSum = init.tail $ foldr ((zipWith.zipWith) (+)) zeroGrid boardShifts\n in map (init.tail) boardSum\n\n\nnearCoords :: [(Int,Int)]\nnearCoords = [(1,0)\n ,(1,1)\n ,(0,1)\n ,(-1,1)\n ,(-1,0)\n ,(-1,-1)\n ,(0,-1)\n ,(1,-1)\n ]\n\ngridShift :: Grid Int -> (Int, Int) -> Grid Int\ngridShift grid _ | length grid == 0 = []\ngridShift _ (x,y) | not.elem (x,y) $ nearCoords = []\ngridShift gridCore (x,y) =\n let --oldx = length grid\n oldy = length.head $ gridCore\n rowUp = 1 + x\n rowDown = 1 - x\n colLeft = 1 + y\n colRight = 1 - y\n row_Up = take rowUp . repeat $ take (oldy + 2) . repeat $ (0::Int)\n row_Down = take rowDown . repeat $ take (oldy + 2) . repeat $ (0::Int)\n col_Left = take colLeft $ repeat (0::Int)\n col_Right = take colRight $ repeat (0::Int)\n in row_Up\n ++ (map (\\line -> col_Left ++ line ++ col_Right) gridCore)\n ++ row_Down\n\n\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Array\n\nnumbers :: String -> [Int]\nnumbers = map read . words\n\ngets :: (Int, Int) -> IO [String]\ngets (n, m) = mapM _getLine [0 .. n - 1]\n where\n _getLine :: Int -> IO String\n _getLine a = getLine\n\nfilterStar :: [String] -> [String]\nfilterStar = map (map replace)\n where\n replace '*' = '*'\n replace _ = '.'\n\ncount :: Char -> [Char] -> Int\ncount a b = sum $ map check b\n where\n check x\n | x == a = 1\n | otherwise = 0\n\ntoChar :: Int -> Char\ntoChar a = chr (ord '0' + a)\n\ncalculate :: (Int, Int) -> [String] -> [String]\ncalculate (n, m) a =\n map update [0 .. n - 1]\n where\n update i = map (w i) [0 .. m - 1]\n w i j\n | index (i, j) == '*' = '*'\n | otherwise = toChar $ count '*' (map index [(i + x, j + y) | x <- [-1 .. 1], y <- [-1 .. 1]])\n index (u, v)\n | u == -1 || u == n = ' '\n | v == -1 || v == m = ' '\n | otherwise = a !! u !! v\n\ninfix 4 \n() :: a -> a -> Bool -> a\na b = \\i -> if i then a\n else b\n\nmain :: IO ()\nmain = do\n firstLine <- getLine\n let [n, m] = numbers firstLine\n res <- gets (n, m)\n putStrLn $ (\"YES\" \"NO\") $ (== res) $ calculate (n, m) $ filterStar res\n"}], "src_uid": "0d586ba7d304902caaeb7cd9e6917cd6"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Data.Tuple\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n ss <- replicateM 3 $ (take (2 * n) . C.unpack) <$> C.getLine\n let cs = [let (as, bs) = partition (== '0') str in (length as, length bs) | str <- ss]\n tt = length [() | (c0, c1) <- cs, c0 <= c1] >= 2\n cmp ((c0, c1), _) ((c0', c1'), _) = if tt then compare c0 c0' else compare c1 c1'\n (s1 : s2 : _) = map snd $ sortBy cmp $ filter (\\((c0, c1), _) -> (c0 <= c1) == tt) $ zip cs ss\n (cc, ct) = (if tt then id else swap) ('0', '1')\n calc [] = []\n calc (_ : xs) = let (ls, rs) = span (== cc) xs in length ls : calc rs\n func xs [] = concat [ct : replicate x cc | x <- xs]\n func (x : xs) (y : ys) = ct : replicate (max x y) cc ++ func xs ys\n result = tail $ func (calc (ct : s1)) (calc (ct : s2))\n C.putStrLn $ C.pack result\n", "positive_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nmergeWith :: Char -> (B8.ByteString, B8.ByteString) -> B8.ByteString\nmergeWith c (a, b) =\n B8.pack $ traceMerge' (trim' $ B8.unpack a) (trim' $ B8.unpack b)\n where\n trim' :: String -> String\n trim' = filter (not . isSpace)\n\n traceMerge' :: String -> String -> String\n traceMerge' a b = r --debug r (\"merge' \" ++ show a ++ \", \" ++ show b ++ \" -> \" ++ show r)\n where r = merge' a b\n\n merge' :: String -> String -> String\n merge' [] b = b\n merge' a [] = a\n merge' a@(ca : restA) b@(cb : restB)\n | ca == cb = ca : traceMerge' restA restB\n | ca == c = cb : traceMerge' a restB\n | cb == c = ca : traceMerge' restA b\n\n\nsolve :: Int -> [B8.ByteString] -> B8.ByteString\nsolve n ss =\n if length with0 >= 2\n then mergeWith '0' (with0 !! 0, with0 !! 1)\n else mergeWith '1' (with1 !! 0, with1 !! 1)\n where\n with0 = filter (\\s -> B8.count '0' s >= n) ss\n with1 = filter (\\s -> B8.count '1' s >= n) ss\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n n <- B8.getLine <&> readIntB8\n ss <- forM [1..3] . const $ B8.getLine\n let answer = solve n ss\n B8.putStrLn answer\n"}], "negative_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nmergeWith :: Char -> (B8.ByteString, B8.ByteString) -> B8.ByteString\nmergeWith c (a, b) =\n B8.pack $ traceMerge' (B8.unpack a) (B8.unpack b)\n where\n traceMerge' :: String -> String -> String\n traceMerge' a b = r --debug r (\"merge' \" ++ show a ++ \", \" ++ show b ++ \" -> \" ++ show r)\n where r = merge' a b\n\n merge' :: String -> String -> String\n merge' [] b = b\n merge' a [] = a\n merge' a@(ca : restA) b@(cb : restB)\n | ca == cb = ca : traceMerge' restA restB\n | ca == c = cb : traceMerge' a restB\n | cb == c = ca : traceMerge' restA b\n\n\nsolve :: Int -> [B8.ByteString] -> B8.ByteString\nsolve n ss =\n if length with0 >= 2\n then mergeWith '0' (with0 !! 0, with0 !! 1)\n else mergeWith '1' (with1 !! 0, with1 !! 1)\n where\n with0 = filter (\\s -> B8.count '0' s >= n) ss\n with1 = filter (\\s -> B8.count '1' s >= n) ss\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n n <- B8.getLine <&> readIntB8\n ss <- forM [1..3] $ const B8.getLine\n let answer = solve n ss\n B8.putStrLn answer"}], "src_uid": "fd3fad7de3068889e676e68551c00a0f"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Data.Int (Int64)\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\nnewtype Mint = Mint Int64\n\nmymod :: Int64\nmymod = 1000000007\n\ninstance Show Mint where\n show (Mint a) = show a\n\ninstance Num Mint where\n (+) (Mint a) (Mint b) = Mint $ let c = a + b in if c >= mymod then c - mymod else c\n (-) (Mint a) (Mint b) = Mint $ let c = a - b in if c < 0 then c + mymod else c\n (*) (Mint a) (Mint b) = Mint $ a * b `rem` mymod\n abs = id\n signum (Mint a) = Mint $ signum a\n fromInteger a = Mint $ fromInteger $ a `mod` toInteger mymod\n\nmyDiv :: Mint -> Mint -> Mint\nmyDiv (Mint a) (Mint b) = Mint $ (if odd a then (a-1) else a) `div` b\n\npowMod :: Mint -> Mint -> Mint\npowMod _ (Mint 0) = Mint 1\npowMod p n@(Mint t)\n | odd t = p * tmp\n | otherwise = tmp\n where\n tmp = powMod (p * p) (n `myDiv` (Mint 2))\n\nmain :: IO ()\nmain = do\n n <- getLine\n k <- getInt\n let len = fromIntegral $ length n\n n' = [(Mint i) | (i,x) <- zip [0..] n, x == '5' || x == '0']\n d = powMod (Mint 2) $ Mint len\n x = (powMod d (Mint k)) - (Mint 1)\n x' = x * (powMod (d-(Mint 1)) $ Mint $ mymod - 2)\n --putStrLn $ show n''\n print $ x' * foldl (\\t x -> t + (powMod (Mint 2) x)) (Mint 0) n'\n", "positive_code": [{"source_code": "import Data.Char\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nnewtype MInt = MInt Int64\n\nm :: Int64\nm = 1000000007\n\ninstance Show MInt where\n show (MInt a) = show a\n\ninstance Num MInt where\n (+) (MInt a) (MInt b) = MInt $ let c = a + b in if c >= m then c - m else c\n (-) (MInt a) (MInt b) = MInt $ let c = a - b in if c < 0 then c + m else c\n (*) (MInt a) (MInt b) = MInt $ a * b `rem` m\n abs = id\n signum (MInt a) = MInt $ signum a\n fromInteger a = MInt $ fromInteger $ a `mod` toInteger m\n\npowSum :: (Num a, Integral b) => a -> b -> a\npowSum a b\n | b == 0 = 0\n | odd b = 1 + a * powSum a (b - 1)\n | otherwise = let b' = b `quot` 2 in (1 + a ^ b') * powSum a b'\n\nmain :: IO ()\nmain = do\n s <- fmap (C.filter isDigit) C.getLine\n k <- fmap (fst . fromJust . C.readInt) C.getLine\n let x = sum [b | (a, b) <- zip (C.unpack s) $ iterate (*2) 1, a == '0' || a == '5']\n y = powSum (2^C.length s) k\n print $ (x * y :: MInt)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\n#define MOD 1000000007\n\nnewtype IntMod = IntMod Int64 deriving (Eq, Ord)\n\ninstance Show IntMod where\n show (IntMod x) = show x\n\ninstance Num IntMod where\n (IntMod x) + (IntMod y) = case x + y of\n xy | xy < MOD -> IntMod xy\n | otherwise -> IntMod $ xy - MOD\n (IntMod x) - (IntMod y) = case x - y of\n xy | xy >= 0 -> IntMod xy\n | otherwise -> IntMod $ xy + MOD\n (IntMod x) * (IntMod y) = IntMod $ x * y `rem` MOD\n abs _ = undefined\n signum _ = undefined\n fromInteger x = IntMod $ fromInteger x\n\ninstance Fractional IntMod where\n (IntMod x) / (IntMod y) = IntMod $ x * fst (extGcd y MOD) `mod` MOD\n fromRational q = undefined\n \nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+) (0 :: IntMod) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\nmodulus :: Int64\nmodulus = 1000000007\n\nnewtype IntMod = Mod Int64 deriving (Eq, Ord)\n\ninstance Show IntMod where\n show (Mod x) = show x\n\ninstance Num IntMod where\n (Mod x) + (Mod y) = case x + y of\n xy | xy < modulus -> Mod xy\n | otherwise -> Mod $ xy - modulus\n (Mod x) - (Mod y) = case x - y of\n xy | xy >= 0 -> Mod xy\n | otherwise -> Mod $ xy + modulus\n (Mod x) * (Mod y) = Mod $ x * y `rem` modulus\n abs _ = undefined\n signum _ = undefined\n fromInteger x = Mod $ fromInteger x `mod` modulus\n\ninstance Fractional IntMod where\n (Mod x) / (Mod y) = Mod $ x * fst (extGcd y modulus) `mod` modulus\n fromRational _ = undefined\n \nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+) (Mod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ninfixl 8 .<<. , .>>.\n(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a\n(.<<.) = unsafeShiftL\n(.>>.) = unsafeShiftR\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\n#define MOD 1000000007\n\ntype IntMod = Int\n\ninfixr 8 ^%\ninfixl 7 *%, /%\ninfixl 6 +%, -%\n\n(+%) :: IntMod -> IntMod -> IntMod\nx +% y = case x+y of\n xy | xy < MOD -> xy\n | otherwise -> xy - MOD\n{-# INLINE (+%) #-}\n\n(-%) :: IntMod -> IntMod -> IntMod\nx -% y = case x-y of\n xy | xy >= 0 -> xy\n | otherwise -> xy + MOD\n{-# INLINE (-%) #-}\n\n(*%) :: IntMod -> IntMod -> IntMod\nx *% y = fromInteger $ toInteger x * toInteger y `rem` MOD\n{-# INLINE (*%) #-}\n\n(/%) :: IntMod -> IntMod -> IntMod\nx /% y = x *% (fst (extGcd y MOD) `mod` MOD)\n{-# INLINE (/%) #-}\n\n(^%) :: IntMod -> IntMod -> IntMod\nx ^% 0 = 1\nx ^% y = f (toInteger x) y\n where\n f !x !y\n | even y = f (x * x `rem` MOD) (y .>>. 1)\n | y == 1 = fromIntegral $ x `rem` MOD\n | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) x\n g !x !y !z\n | even y = g (x * x `rem` MOD) (y .>>. 1) z\n | y == 1 = fromIntegral $ x * z `rem` MOD\n | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) (x * z `rem` MOD)\n\nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+%) 0 (map (2^%) xs) *% (((2^%l)^%k-%1)/%(2^%l-%1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\nmodulus :: Int64\nmodulus = 1000000007\n{-# INLINE modulus #-}\n\nnewtype IntMod = Mod Int64 deriving (Eq, Ord)\n\ninstance Show IntMod where\n show (Mod x) = show x\n\ninstance Num IntMod where\n (Mod x) + (Mod y) = case x + y of\n xy | xy < modulus -> Mod xy\n | otherwise -> Mod $ xy - modulus\n (Mod x) - (Mod y) = case x - y of\n xy | xy >= 0 -> Mod xy\n | otherwise -> Mod $ xy + modulus\n (Mod x) * (Mod y) = Mod $ x * y `rem` modulus\n abs _ = undefined\n signum _ = undefined\n fromInteger x = Mod $ fromInteger x `mod` modulus\n\ninstance Fractional IntMod where\n (Mod x) / (Mod y) = Mod $ x * fst (extGcd y modulus) `mod` modulus\n fromRational _ = undefined\n \nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+) (Mod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n{-# LANGUAGE MagicHash #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nimport GHC.Int (Int64(..))\nimport GHC.IntWord64 (timesInt64#, remInt64#)\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\nmodulus :: Int64\nmodulus = 1000000007\n{-# INLINE modulus #-}\n\nnewtype IntMod = Mod Int64 deriving (Eq, Ord)\n\ninstance Show IntMod where\n show (Mod x) = show x\n\ninstance Num IntMod where\n (Mod x) + (Mod y) = case x + y of\n xy | xy < modulus -> Mod xy\n | otherwise -> Mod $ xy - modulus\n (Mod x) - (Mod y) = case x - y of\n xy | xy >= 0 -> Mod xy\n | otherwise -> Mod $ xy + modulus\n (Mod (I64# x#)) * (Mod (I64# y#)) = case modulus of\n (I64# m#) -> Mod $ I64# (x# `timesInt64#` y# `remInt64#` m#)\n abs _ = undefined\n signum _ = undefined\n fromInteger x = Mod $ fromInteger x `mod` modulus\n\ninstance Fractional IntMod where\n (Mod x) / (Mod y) = Mod $ x * fst (extGcd y modulus) `mod` modulus\n fromRational _ = undefined\n \nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+) (Mod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ninfixl 8 .<<. , .>>.\n(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a\n(.<<.) = unsafeShiftL\n(.>>.) = unsafeShiftR\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\n#define MOD 1000000007\n\ntype IntMod = Int64\n\ninfixr 8 ^%\ninfixl 7 *%, /%\ninfixl 6 +%, -%\n\n(+%) :: IntMod -> IntMod -> IntMod\nx +% y = case x+y of\n xy | xy < MOD -> xy\n | otherwise -> xy - MOD\n{-# INLINE (+%) #-}\n\n(-%) :: IntMod -> IntMod -> IntMod\nx -% y = case x-y of\n xy | xy >= 0 -> xy\n | otherwise -> xy + MOD\n{-# INLINE (-%) #-}\n\n(*%) :: IntMod -> IntMod -> IntMod\nx *% y = x * y `rem` MOD\n{-# INLINE (*%) #-}\n\n(/%) :: IntMod -> IntMod -> IntMod\nx /% y = x *% (fst (extGcd y MOD) `mod` MOD)\n{-# INLINE (/%) #-}\n\n(^%) :: IntMod -> Int -> IntMod\nx ^% 0 = 1\nx ^% y = f (toInteger x) y\n where\n f !x !y\n | even y = f (x * x `rem` MOD) (y .>>. 1)\n | y == 1 = fromIntegral $ x `rem` MOD\n | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) x\n g !x !y !z\n | even y = g (x * x `rem` MOD) (y .>>. 1) z\n | y == 1 = fromIntegral $ x * z `rem` MOD\n | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) (x * z `rem` MOD)\n\nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+%) 0 (map (2^%) xs) *% (((2^%l)^%k-%1)/%(2^%l-%1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\nimport Unsafe.Coerce\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\n#define MOD 1000000007\n\nnewtype IntMod = IntMod Int64 deriving (Eq, Ord)\n\ninstance Show IntMod where\n show (IntMod x) = show x\n\ninstance Num IntMod where\n (IntMod x) + (IntMod y) = case x + y of\n xy | xy < MOD -> unsafeCoerce xy\n | otherwise -> unsafeCoerce $ xy - MOD\n (IntMod x) - (IntMod y) = case x - y of\n xy | xy >= 0 -> unsafeCoerce xy\n | otherwise -> unsafeCoerce $ xy + MOD\n (IntMod x) * (IntMod y) = unsafeCoerce $ x * y `rem` MOD\n abs _ = undefined\n signum _ = undefined\n fromInteger x = IntMod $ fromInteger x `mod` MOD\n\ninstance Fractional IntMod where\n (IntMod x) / (IntMod y) = unsafeCoerce $ x * fst (extGcd y MOD) `mod` MOD\n fromRational _ = undefined\n \nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+) (IntMod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))\n"}, {"source_code": "\nmodule Main where\n\nch2int c\n | c == '1' = 1\n | c == '2' = 2\n | c == '3' = 3\n | c == '4' = 4\n | c == '5' = 5\n | c == '6' = 6\n | c == '7' = 7\n | c == '8' = 8\n | c == '9' = 9\n | otherwise = 0\n\nstr2int [] = 0\nstr2int s = (str2int (init s)) * 10 + (ch2int (last s))\n\nmod_exp a n m = exp n\n where exp n = if n == 0\n then 1\n else\n let b = exp (div n 2)\n c = mod (b * b) m\n in if mod n 2 == 0\n then c\n else mod (a * c) m\n\npow_sum a n m = ps n\n where ps n = if n == 0\n then 1\n else if mod n 2 == 0\n then mod (1 + a * ps (n - 1)) m\n else let k = div n 2\n in mod ((1 + (mod_exp a (k + 1) m)) * (ps k)) m\n\nsub [] = [[]]\nsub (x:y) =\n let w = sub y\n in w ++ [x:z | z <- w]\n-- magic seq = length [s | s <- sub seq, length s > 0, last s == '5' || last s == '0']\n\nmagic seq = \n mod (sum (map f (zip seq [0..]))) 1000000007\n where f (c, i) = if c == '0' || c == '5'\n then mod_exp 2 i 1000000007\n else 0\n\nsolve str k =\n mod ((pow_sum a (k - 1) 1000000007) * q) 1000000007\n where\n n = length str\n q = (magic str)\n a = mod (mod_exp 2 n 1000000007) 1000000007\n\nmain = do\n str <- getLine\n line <- getLine\n print $ solve str (str2int line)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\n#define MOD 1000000007\n\nnewtype IntMod = IntMod Int64 deriving (Eq, Ord)\n\ninstance Show IntMod where\n show (IntMod x) = show x\n\ninstance Num IntMod where\n (IntMod x) + (IntMod y) = case x + y of\n xy | xy < MOD -> IntMod xy\n | otherwise -> IntMod $ xy - MOD\n (IntMod x) - (IntMod y) = case x - y of\n xy | xy >= 0 -> IntMod xy\n | otherwise -> IntMod $ xy + MOD\n (IntMod x) * (IntMod y) = IntMod $ x * y `rem` MOD\n abs _ = undefined\n signum _ = undefined\n fromInteger x = IntMod $ fromInteger x\n\ninstance Fractional IntMod where\n (IntMod x) / (IntMod y) = IntMod $ x * (fst (extGcd y MOD) `mod` MOD)\n fromRational q = undefined\n \nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+) (0 :: IntMod) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Bits\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ninfixl 8 .<<. , .>>.\n(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a\n(.<<.) = unsafeShiftL\n(.>>.) = unsafeShiftR\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nextGcd :: (Integral a) => a -> a -> (a, a)\nextGcd !a !b\n | b == 0 = (1, 0)\n | otherwise = (t, s - a `div` b * t)\n where\n (!s, !t) = extGcd b $ a `mod` b\n{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}\n{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}\n\n#define MOD 1000000007\n\ntype IntMod = Int\n\ninfixr 8 ^%\ninfixl 7 *%, /%\ninfixl 6 +%, -%\n\n(+%) :: IntMod -> IntMod -> IntMod\nx +% y = case x+y of\n xy | xy < MOD -> xy\n | otherwise -> xy - MOD\n{-# INLINE (+%) #-}\n\n(-%) :: IntMod -> IntMod -> IntMod\nx -% y = case x-y of\n xy | xy >= 0 -> xy\n | otherwise -> xy + MOD\n{-# INLINE (-%) #-}\n\n(*%) :: IntMod -> IntMod -> IntMod\nx *% y = fromInteger $ toInteger x * toInteger y `rem` MOD\n{-# INLINE (*%) #-}\n\n(/%) :: IntMod -> IntMod -> IntMod\nx /% y = x *% (fst (extGcd y MOD) `mod` MOD)\n{-# INLINE (/%) #-}\n\n(^%) :: IntMod -> IntMod -> IntMod\nx ^% 0 = 1\nx ^% y = f (toInteger x) y\n where\n f !x !y\n | even y = f (x * x `rem` MOD) (y .>>. 1)\n | y == 1 = fromIntegral $ x `rem` MOD\n | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) x\n g !x !y !z\n | even y = g (x * x `rem` MOD) (y .>>. 1) z\n | y == 1 = fromIntegral $ x * z `rem` MOD\n | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) (x * z `rem` MOD)\n\nmain :: IO ()\nmain = do\n [bs,kbs] <- B.lines <$> B.getContents\n let xs = B.findIndices (\\c->c=='0'||c=='5') bs\n k = readInt kbs\n l = B.length bs - 1\n print $ foldl' (+%) 0 (map (2^%) xs) *% ((2^%(k*%l)-%1)/%(2^%l-%1))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Data.Int (Int64)\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\nnewtype Mint = Mint Int64\n\nmymod :: Int64\nmymod = 1000000007\n\ninstance Show Mint where\n show (Mint a) = show a\n\ninstance Num Mint where\n (+) (Mint a) (Mint b) = Mint $ let c = a + b in if c >= mymod then c - mymod else c\n (-) (Mint a) (Mint b) = Mint $ let c = a - b in if c < 0 then c + mymod else c\n (*) (Mint a) (Mint b) = Mint $ a * b `rem` mymod\n abs = id\n signum (Mint a) = Mint $ signum a\n fromInteger a = Mint $ fromInteger $ a `mod` toInteger mymod\n\nmyDiv :: Mint -> Mint -> Mint\nmyDiv (Mint a) (Mint b) = Mint $ a `div` b\n\npowMod :: Mint -> Mint -> Mint\npowMod _ (Mint 0) = Mint 1\npowMod p n@(Mint t)\n | odd t = p * tmp\n | otherwise = tmp\n where\n tmp = powMod (p * p) (n `myDiv` (Mint 2))\n\ncalc :: Mint -> (Mint, (Mint, Mint)) -> Mint\ncalc s (x,(l,k)) = \n --trace (show x ++ \" \" ++ show l ++ \" \" ++ show k ++ \" \" ++ show t ++ \" \" ++ show p ++ \" \" ++ show d ++ \" \" ++ show t') $ \n s + p - t\n where\n t = powMod (Mint 2) x\n p = powMod (Mint 2) (x + l * k)\n\nmain :: IO ()\nmain = do\n n <- getLine\n k <- getInt\n let len = fromIntegral $ length n\n n' = [(Mint i,(Mint len, Mint k)) | (i,x) <- zip [0..] n, x == '5' || x == '0']\n chu' = powMod (Mint 2) $ Mint len\n chu = powMod (chu' - (Mint 1)) $ Mint $ mymod - 2\n --putStrLn $ show n''\n print $ chu * (foldl calc (Mint 0) n')\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Data.Int (Int64)\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: Integral a => C.ByteString -> a\nreadInt = fromIntegral . fst . fromJust . C.readInt\n\ngetInts :: IO [Int64]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int64\ngetInt = readInt <$> C.getLine\n\nmymod :: Int64\nmymod = 1000000007\n\npowMod :: Int64 -> Int64 -> Int64\npowMod _ 0 = 1\npowMod p n\n | odd n = (p * tmp) `rem` mymod\n | otherwise = tmp\n where\n tmp = powMod ((p*p) `rem` mymod) ((if odd n then n-1 else n) `div` 2)\n\ncalc :: (Int64, (Int64, Int64)) -> Int64\ncalc (x,(l,k)) = \n --trace (show x ++ \" \" ++ show l ++ \" \" ++ show k ++ \" \" ++ show t ++ \" \" ++ show p ++ \" \" ++ show d ++ \" \" ++ show t') $ \n (((p + mymod - t) `rem` mymod) * t') `rem` mymod\n where\n t = powMod 2 x\n d = powMod 2 l\n p = powMod 2 $ x + l * k\n t' = powMod (d - 1) $ mymod - 2\n\nmain :: IO ()\nmain = do\n --n <- (\\x -> [digitToInt c | c <- x]) <$> C.getLine\n n <- getLine\n k <- getInt\n let len = fromIntegral $ length n\n n' = [i | (i,x) <- zip [0..] n, x == '5' || x == '0']\n n'' = zip n' $ replicate (length n') (len,k)\n --putStrLn $ show n''\n print $ sum $ map calc n''\n"}, {"source_code": "import Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nnewtype MInt = MInt Int64\n\nm :: Int64\nm = 1000000007\n\ninstance Show MInt where\n show (MInt a) = show a\n\ninstance Num MInt where\n (+) (MInt a) (MInt b) = MInt $ let c = a + b in if c >= m then c - m else c\n (-) (MInt a) (MInt b) = MInt $ let c = a - b in if c < 0 then c + m else c\n (*) (MInt a) (MInt b) = MInt $ a * b `rem` m\n abs = id\n signum (MInt a) = MInt $ signum a\n fromInteger a = MInt $ fromInteger $ a `mod` toInteger m\n\nmain :: IO ()\nmain = do\n s <- C.getLine\n k <- fmap (fst . fromJust . C.readInt) C.getLine\n let x = sum [b | (a, b) <- zip (C.unpack s) $ iterate (*2) 1, a == '0' || a == '5']\n y = sum $ take k $ iterate (*2^C.length s) 1\n print $ (x * y :: MInt)\n"}], "src_uid": "268f90d0595f7c51fb336ce377409dde"} {"source_code": "type Input = [[Integer]]\ntype Output = [Exp]\n\nparse :: String -> Input\nparse = toList . unzip . map pair . tail . lines\n where pair l = let [x, y, _] = map read . words $ l in (x, y)\n toList (a, b) = [a, b]\n\ndata Exp = Abs Exp\n | Add Exp Exp\n | Subtract Exp Exp\n | Multiply Exp Exp\n | Constant Integer\n | Variable\n\ninstance Show Exp where\n show g = go g \"\"\n where go :: Exp -> String -> String\n go (Abs e) = (\"abs(\" ++) . go e . (\")\" ++)\n go (Add e f) = (\"(\" ++) . go e . (\"+\" ++) . go f . (\")\" ++)\n go (Subtract e f) = (\"(\" ++) . go e . (\"-\" ++) . go f . (\")\" ++)\n go (Multiply e f) = (\"(\" ++) . go e . (\"*\" ++) . go f . (\")\" ++)\n go (Constant c) = (show c ++)\n go (Variable) = (\"t\" ++)\n\ninstance Num Exp where\n abs = Abs\n (+) = Add\n (-) = Subtract\n (*) = Multiply\n fromInteger = Constant\n signum = undefined\n\nat :: Integer -> Exp\nat x = 2 - abs (d (x - 1) - d (x + 1))\n where d :: Integer -> Exp\n d a\n | a >= 0 = abs (Variable - fromInteger a)\n | otherwise = abs (Variable + fromInteger (-a))\n\nsolve :: Input -> Output\nsolve = map solve1\n where solve1 :: [Integer] -> Exp\n solve1 = sum . zipWith (*) (map at [0..]) . map (fromInteger . (`div` 2))\n\nformat :: Output -> String\nformat = unlines . map show\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n", "positive_code": [{"source_code": "type Input = [[Integer]]\ntype Output = [Exp]\n\nparse :: String -> Input\nparse = toList . unzip . map pair . tail . lines\n where pair l = let [x, y, _] = map read . words $ l in (x, y)\n toList (a, b) = [a, b]\n\ndata Exp = Abs Exp\n | Add Exp Exp\n | Subtract Exp Exp\n | Multiply Exp Exp\n | Constant Integer\n | Variable\n\ninstance Show Exp where\n show = go\n where go :: Exp -> String\n go (Abs e) = \"abs(\" ++ go e ++ \")\"\n go (Add e f) = \"(\" ++ go e ++ \"+\" ++ go f ++ \")\"\n go (Subtract e f) = \"(\" ++ go e ++ \"-\" ++ go f ++ \")\"\n go (Multiply e f) = \"(\" ++ go e ++ \"*\" ++ go f ++ \")\"\n go (Constant c) = show c\n go Variable = \"t\"\n\ninstance Num Exp where\n abs = Abs\n (+) = Add\n (-) = Subtract\n (*) = Multiply\n fromInteger = Constant\n signum = undefined\n\nat :: Integer -> Exp\nat x = 2 - abs (d (x - 1) - d (x + 1))\n where d :: Integer -> Exp\n d a\n | a >= 0 = abs (Variable - fromInteger a)\n | otherwise = abs (Variable + fromInteger (-a))\n\nsolve :: Input -> Output\nsolve = map solve1\n where solve1 :: [Integer] -> Exp\n solve1 = sum . zipWith (*) (map at [0..]) . map (fromInteger . (`div` 2))\n\nformat :: Output -> String\nformat = unlines . map show\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents"}], "negative_code": [{"source_code": "import Control.Arrow ((&&&))\nimport Data.List (intercalate)\n\ndata Circle = Circle { circleX :: Int, circleY :: Int }\n\ntype Input = [Circle]\ntype Output = (String, String)\n\nparse :: String -> Input\nparse = map circle . tail . lines\n where circle l = let [x, y, _] = map read . words $ l in Circle x y\n\nsolve1 :: [Int] -> String\nsolve1 = intercalate \"+\" . zipWith f [0..]\n where f :: Int -> Int -> String\n f i x = concat [\"(\", g i, \"*\", show (x `div` 2), \")\"]\n g :: Int -> String\n g i = concat [\"(2-abs((\", a (i - 1), \"-\", a (i + 1), \")))\"]\n a :: Int -> String\n a i\n | i < 0 = concat [\"abs((t+\", show (-i), \"))\"]\n | otherwise = concat [\"abs((t-\", show i, \"))\"]\n\nsolve :: Input -> Output\nsolve = (solve1 . map circleX) &&& (solve1 . map circleY)\n\nformat :: Output -> String\nformat (f, g) = unlines [f, g]\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}, {"source_code": "import Control.Arrow ((&&&))\nimport Data.List (intercalate)\n\ndata Circle = Circle { circleX :: Int, circleY :: Int }\n\ntype Input = [Circle]\ntype Output = (String, String)\n\nparse :: String -> Input\nparse = map circle . tail . lines\n where circle l = let [x, y, _] = map read . words $ l in Circle x y\n\nfit :: Int -> Int\nfit x\n | even x = x\n | otherwise = x + 1\n\nsolve1 :: [Int] -> String\nsolve1 = intercalate \"+\" . zipWith f [0..]\n where f :: Int -> Int -> String\n f i x = concat [\"(\", g i, \"*\", show . fit $ x, \")\"]\n g :: Int -> String\n g i = concat [\"abs((\", a (i - 1), \"-\", a (i + 1), \"))\"]\n a :: Int -> String\n a i = concat [\"abs((t-\", show i, \"))\"]\n\nsolve :: Input -> Output\nsolve = (solve1 . map circleX) &&& (solve1 . map circleY)\n\nformat :: Output -> String\nformat (f, g) = unlines [f, g]\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}, {"source_code": "type Input = [[Integer]]\ntype Output = [Exp]\n\nparse :: String -> Input\nparse = toList . unzip . map pair . tail . lines\n where pair l = let [x, y, _] = map read . words $ l in (x, y)\n toList (a, b) = [a, b]\n\ndata Exp = Abs Exp\n | Add Exp Exp\n | Subtract Exp Exp\n | Multiply Exp Exp\n | Constant Integer\n | Variable\n\ninstance Show Exp where\n show g = go g \"\"\n where go :: Exp -> String -> String\n go (Abs e) = (\"abs(\" ++) . go e . (\")\" ++)\n go (Add e f) = (\"(\" ++) . go e . (\"+\" ++) . go f . (\")\" ++)\n go (Subtract e f) = (\"(\" ++) . go e . (\"-\" ++) . go f . (\")\" ++)\n go (Multiply e f) = (\"(\" ++) . go e . (\"*\" ++) . go f . (\")\" ++)\n go (Constant c) = (show c ++)\n go (Variable) = (\"t\" ++)\n\ninstance Num Exp where\n abs = Abs\n (+) = Add\n (-) = Subtract\n (*) = Multiply\n fromInteger = Constant\n signum = undefined\n\nat :: Integer -> Exp\nat x = 2 - abs (d (x - 1) - d (x + 1))\n where d :: Integer -> Exp\n d a\n | a >= 0 = abs (Variable - fromInteger a)\n | otherwise = abs (Variable + fromInteger a)\n\nsolve :: Input -> Output\nsolve = map solve1\n where solve1 :: [Integer] -> Exp\n solve1 = sum . zipWith (*) (map at [0..]) . map (fromInteger . (`div` 2))\n\nformat :: Output -> String\nformat = unlines . map show\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}, {"source_code": "type Input = [[Integer]]\ntype Output = [Exp]\n\nparse :: String -> Input\nparse = toList . unzip . map pair . tail . lines\n where pair l = let [x, y, _] = map read . words $ l in (x, y)\n toList (a, b) = [a, b]\n\ndata Exp = Abs Exp\n | Add Exp Exp\n | Subtract Exp Exp\n | Multiply Exp Exp\n | Constant Integer\n | Variable\n\ninstance Show Exp where\n show g = go g \"\"\n where go :: Exp -> String -> String\n go (Abs e) = (\"abs(\" ++) . go e . (\")\" ++)\n go (Add e f) = (\"(\" ++) . go e . (\"+\" ++) . go f . (\")\" ++)\n go (Subtract e f) = (\"(\" ++) . go e . (\"-\" ++) . go f . (\")\" ++)\n go (Multiply e f) = (\"(\" ++) . go e . (\"*\" ++) . go f . (\")\" ++)\n go (Constant c) = (show c ++)\n go (Variable) = (\"t\" ++)\n\ninstance Num Exp where\n abs = Abs\n (+) = Add\n (-) = Subtract\n (*) = Multiply\n fromInteger = Constant\n signum = undefined\n\nat :: Integer -> Exp\nat x = 2 - abs (d (x - 1) - d (x + 1))\n where d :: Integer -> Exp\n d a\n | a >= 0 = abs (Variable - fromInteger a)\n | otherwise = abs (Variable + fromInteger a)\n\nsolve :: Input -> Output\nsolve = map solve1\n where solve1 :: [Integer] -> Exp\n solve1 = sum . zipWith (*) (map at [0..]) . map fromInteger\n\nformat :: Output -> String\nformat = unlines . map show\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}, {"source_code": "import Control.Arrow ((&&&))\nimport Data.List (intercalate)\n\ndata Circle = Circle { circleX :: Int, circleY :: Int }\n\ntype Input = [Circle]\ntype Output = (String, String)\n\nparse :: String -> Input\nparse = map circle . tail . lines\n where circle l = let [x, y, _] = map read . words $ l in Circle x y\n\nsolve1 :: [Int] -> String\nsolve1 = intercalate \"+\" . zipWith f [0..]\n where f :: Int -> Int -> String\n f i x = concat [\"(\", g i, \"*\", show (x `div` 2), \")\"]\n g :: Int -> String\n g i = concat [\"abs((\", a (i - 1), \"-\", a (i + 1), \"))\"]\n a :: Int -> String\n a i\n | i < 0 = concat [\"abs((t+\", show (-i), \"))\"]\n | otherwise = concat [\"abs((t-\", show i, \"))\"]\n\nsolve :: Input -> Output\nsolve = (solve1 . map circleX) &&& (solve1 . map circleY)\n\nformat :: Output -> String\nformat (f, g) = unlines [f, g]\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}], "src_uid": "79c337ca7397eac500ca8e6693f83fb6"} {"source_code": "module Main where\n \nimport Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport Data.Tuple\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.Set as Set\nimport qualified Data.Map.Lazy as Map\n \nmain :: IO()\nmain = \n print =<< (Map.foldl' (+) 0) <$>\n liftM2 (foldl' $\n flip $ Map.update (\\ x -> if x > 1 then Just (x - 1) else Nothing)) \n (Map.fromList . map (liftA2 (,) head length) . group . sort <$> \n (read <$> getLine >>= flip replicateM getLine))\n (words <$> getContents)", "positive_code": [{"source_code": "module Main where\n\nimport Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport Data.Tuple\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.Set as Set\nimport qualified Data.Map.Lazy as Map\n\nmain :: IO()\nmain = \n print =<< (Map.foldl' (+) 0) <$>\n liftM2 (foldl' $\n flip $ Map.update (\\ x -> if x > 1 then Just (x - 1) else Nothing)) \n (Map.fromList . map (liftA2 (,) head length) . group . sort <$> \n (read <$> getLine >>= flip replicateM getLine))\n (words <$> getContents)\n "}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\nmain = do \n nIO <- getLine\n let n = read nIO :: Int\n old <- replicateM n getLine\n new <- replicateM n getLine\n let (ans, _) = foldl (\\(cnt, rr) el -> if el `elem` (new \\\\ rr) then (cnt, el:rr) else (cnt+1, rr)) (0, []) old\n print ans\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport Data.Tuple\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n a <- f n \n b <- f n\n print . length . filter (uncurry (/=)) $ on zip sort a b\n where f = sequence . flip replicate getLine\n "}, {"source_code": "module Main where\n\nimport Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport Data.Tuple\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n a <- f n \n b <- f n\n print . sum . map (uncurry (((length . filter (uncurry (/=))).) . zip)) $ on zip sort a b\n where f = sequence . flip replicate getLine\n "}], "src_uid": "c8321b60a6ad04093dee3eeb9ee27b6f"} {"source_code": "import qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\nimport Data.List\n\ndfs\n :: Int\n -> Map.Map Int [Int]\n -> Map.Map Int Bool\n -> Int\n -> Int\n -> Set.Set Int\n -> Int\ndfs maxCats edgeMap hasCat nCats node visited\n | node `Set.member` visited = 0\n | nCats' > maxCats = 0\n | all (`Set.member` visited) (edgeMap Map.! node) = 1\n | otherwise = sum\n [ dfs maxCats edgeMap hasCat nCats' n (Set.insert node visited)\n | n <- edgeMap Map.! node\n ]\n where nCats' = if hasCat Map.! node then nCats + 1 else 0\n\ng :: Int -> Int -> [Int] -> [(Int, Int)] -> Int\ng n maxCats cats edges =\n let hasCat = Map.fromAscList $ zip [0 ..] [ v == 1 | v <- cats ]\n edgeMap = Map.fromListWith (++) [ (a, [b]) | (a, b) <- edges ]\n in dfs maxCats edgeMap hasCat 0 0 Set.empty\n\nf :: [String] -> Int\nf (nm : cats : edges) =\n let [n, maxCats] = map read . words $ nm :: [Int]\n cats' = map read . words $ cats :: [Int]\n edges' :: [(Int, Int)]\n edges' = map ((\\[a, b] -> (a - 1, b - 1)) . (map read . words)) edges\n edges'' = edges' ++ [ (b, a) | (a, b) <- edges' ]\n in g n maxCats cats' edges''\n\n-- TOOD: Nicer way to extract the lines?\nmain = interact $ show . f . lines\n", "positive_code": [{"source_code": "import Data.Array\ndfs cat edges now ccat maxcat pre| isOne nextList && now /= 1 = if catnum <= maxcat then 1 else 0\n | otherwise = if catnum > maxcat then 0 else sum [dfs cat edges next catnum maxcat now| next <- nextList,next /= pre] \n where nextList = (edges ! now)\n hascat = (cat ! now)\n catnum = getCat hascat ccat\ngetCat a b | a == 0 = 0\n | otherwise = (a+b)\nisOne (x:xs) = null xs \ngetTuple s = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words s)]\nmain = do\n w0 <- getLine\n let [n,m] = [read n::Int|n <- (words w0)]\n w1 <- getLine\n let hasCat = listArray (1,n) [read n::Int|n <- (words w1)]\n w2 <- getContents\n let e = [getTuple s | s <- (lines w2)]\n let e2 = e ++ (map (\\x -> (snd x,fst x)) e)\n let edges = accumArray (flip (:)) [] (1,n) e2\n print $ dfs hasCat edges 1 0 m 0\n"}, {"source_code": "import Data.Array\nimport Data.Graph\nimport Control.Monad\nmain = do\n [n,m] <- map read . words <$> getLine\n cats <- listArray (1,n) . map (toEnum . read) . words <$> getLine\n g <- fmap (buildG (1,n) . concat) $ replicateM (n-1) $ do\n [x,y] <- map read . words <$> getLine\n return [(x,y),(y,x)]\n let [t] = dfs g [1]\n count c (Node n ts) | c' > m = 0\n | null ts = 1\n | otherwise = sum (map (count c') ts)\n where c' = if cats!n then c+1 else 0\n print $ count 0 t\n"}, {"source_code": "import Data.Array\nimport Data.Char (ord)\nimport Data.List (groupBy, sortBy)\nimport Data.Ord (comparing)\nimport Data.Tuple (swap)\n\ntype IntArray a = Array Int a\n\ntype Input = (Int, IntArray Int, IntArray [Int])\n\nreadInt :: String -> Int\nreadInt = foldl step 0 where step s a = s * 10 + ord a - 48\n\nreadPair :: String -> (Int, Int)\nreadPair s = (a, b)\n where [a, b] = map readInt . words $ s\n\nparseV :: Int -> String -> IntArray Int\nparseV n l = listArray (1, n) a\n where a = map readInt . words $ l\n\nsortOn :: Ord b => (a -> b) -> [a] -> [a]\nsortOn f = map snd . sortBy (comparing fst) . map (\\x -> let y = f x in y `seq` (y, x))\n\ngroupOn :: Ord b => (a -> b) -> [a] -> [[a]]\ngroupOn k = groupBy f . sortOn k\n where f x y = k x == k y\n\nparseE :: Int -> [String] -> IntArray [Int]\nparseE n ls =\n let es = map readPair ls\n gs = groupOn fst (es ++ map swap es)\n in listArray (1, n) (map (map snd) gs)\n\nparse :: String -> Input\nparse contents =\n let (l0 : l1 : ls) = lines contents\n [n, m] = map readInt . words $ l0\n in (m, parseV n l1, parseE n ls)\n\nsolve :: Input -> Int\nsolve (m, a, tree) = dfs (-1) 0 1\n where dfs :: Int -> Int -> Int -> Int\n dfs p k v =\n let a' = a ! v\n k' = if a' == 0 then 0 else k + 1\n nv = filter (/= p) $ tree ! v in\n if k' > m\n then 0\n else if null nv\n then 1\n else sum . map (dfs v k') $ nv\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Map (empty, (!), fromList, insert, adjust)\nimport Debug.Trace\n\n-- 580C\n\nsolve :: Int -> Int -> [Bool] -> [[Int]] -> Int\nsolve n m hasCatLst edges =\n countRestaurants 0 m 1\n where\n empty_map = fromList [(i, []) | i <- [1..n]]\n append u v =\n adjust (v:) u . adjust (u:) v\n childrenArr = foldr (\\[u, v] -> \\mapping -> append u v mapping) empty_map edges\n hasCatArr = fromList $ zip [1..] hasCatLst\n countRestaurants parent m' i\n | m'' >= 0 && leaf = 1\n | leaf = 0\n | m'' < 0 = 0\n | otherwise = sum $ map (countRestaurants i m'') children\n where\n children = filter (/= parent) $ childrenArr ! i\n hasCat = hasCatArr ! i\n leaf = length children == 0\n m'' = if hasCat then m' - 1 else m\n \n\nmain = do\n let f = map read . words <$> getLine\n [n, m] <- f\n hasCatLst <- map toEnum <$> f\n edges <- map (map read . words) . lines <$> getContents\n putStrLn $ show $ solve n m hasCatLst edges\n"}], "negative_code": [{"source_code": "import qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\nimport Data.List\n\ndfs :: Int -> Map.Map Int [Int] -> Map.Map Int Bool -> Int -> Int -> Int\ndfs maxCats edgeMap hasCat nCats node\n | nCats' > maxCats = 0\n | null $ Map.findWithDefault [] node edgeMap = 1\n | otherwise = sum\n [ dfs maxCats edgeMap hasCat nCats' n | n <- edgeMap Map.! node ]\n where nCats' = if hasCat Map.! node then nCats + 1 else 0\n\ng :: Int -> Int -> [Int] -> [(Int, Int)] -> Int\ng n maxCats cats edges =\n let hasCat = Map.fromAscList $ zip [0 ..] [ v == 1 | v <- cats ]\n edgeMap = Map.fromListWith (++) [ (a, [b]) | (a, b) <- edges ]\n root = Set.elemAt 0 $ Set.difference\n (Set.fromAscList [0 .. n - 1])\n (Set.fromList $ Map.foldr (++) [] edgeMap)\n in dfs maxCats edgeMap hasCat 0 root\n\nf :: [String] -> Int\nf (nm : cats : edges) =\n let [n, maxCats] = map read . words $ nm :: [Int]\n cats' = map read . words $ cats :: [Int]\n edges' :: [(Int, Int)]\n edges' = map ((\\[a, b] -> (a - 1, b - 1)) . (map read . words)) edges\n in g n maxCats cats' edges'\n\n-- TOOD: Nicer way to extract the lines?\nmain = interact $ show . f . lines\n"}, {"source_code": "import Data.Array\ndfs cat edges now ccat maxcat | null nextList = if (hascat + ccat) <= maxcat then 1 else 0\n | otherwise = sum [dfs cat edges next (getCat hascat ccat) maxcat| next <- nextList] \n where nextList = (edges ! now)\n hascat = (cat ! now)\ngetCat a b | a == 0 = 0\n | otherwise = (a+b)\ngetTuple s = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words s)]\nmain = do\n w0 <- getLine\n let [n,m] = [read n::Int|n <- (words w0)]\n w1 <- getLine\n let hasCat = listArray (1,n) [read n::Int|n <- (words w1)]\n w2 <- getContents\n let e = [getTuple s | s <- (lines w2)]\n let edges = accumArray (flip (:)) [] (1,n) e\n print $ dfs hasCat edges 1 0 m\n"}, {"source_code": "import Data.Array\ndfs cat edges now ccat maxcat pre| isOne nextList && now /= 1 = if (hascat + ccat) <= maxcat then 1 else 0\n | otherwise = sum [dfs cat edges next (getCat hascat ccat) maxcat now| next <- nextList,next /= pre] \n where nextList = (edges ! now)\n hascat = (cat ! now)\ngetCat a b | a == 0 = 0\n | otherwise = (a+b)\nisOne (x:xs) = null xs \ngetTuple s = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words s)]\nmain = do\n w0 <- getLine\n let [n,m] = [read n::Int|n <- (words w0)]\n w1 <- getLine\n let hasCat = listArray (1,n) [read n::Int|n <- (words w1)]\n w2 <- getContents\n let e = [getTuple s | s <- (lines w2)]\n let e2 = e ++ (map (\\x -> (snd x,fst x)) e)\n let edges = accumArray (flip (:)) [] (1,n) e2\n print $ dfs hasCat edges 1 0 m 0\n"}, {"source_code": "import Data.Array\ndfs cat edges now ccat maxcat pre| null nextList = if (hascat + ccat) <= maxcat then 1 else 0\n | otherwise = sum [dfs cat edges next (getCat hascat ccat) maxcat now| next <- nextList,next /= pre] \n where nextList = (edges ! now)\n hascat = (cat ! now)\ngetCat a b | a == 0 = 0\n | otherwise = (a+b)\ngetTuple s = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words s)]\nmain = do\n w0 <- getLine\n let [n,m] = [read n::Int|n <- (words w0)]\n w1 <- getLine\n let hasCat = listArray (1,n) [read n::Int|n <- (words w1)]\n w2 <- getContents\n let e = [getTuple s | s <- (lines w2)]\n let e2 = e ++ (map (\\x -> (snd x,fst x)) e)\n let edges = accumArray (flip (:)) [] (1,n) e\n print $ dfs hasCat edges 1 0 m 0\n"}, {"source_code": "import Data.Array\ndfs cat edges now ccat maxcat pre| isOne nextList = if (hascat + ccat) <= maxcat then 1 else 0\n | otherwise = sum [dfs cat edges next (getCat hascat ccat) maxcat now| next <- nextList,next /= pre] \n where nextList = (edges ! now)\n hascat = (cat ! now)\ngetCat a b | a == 0 = 0\n | otherwise = (a+b)\nisOne (x:xs) = null xs \ngetTuple s = (a0,a1)\n where [a0,a1] = [read n::Int|n <- (words s)]\nmain = do\n w0 <- getLine\n let [n,m] = [read n::Int|n <- (words w0)]\n w1 <- getLine\n let hasCat = listArray (1,n) [read n::Int|n <- (words w1)]\n w2 <- getContents\n let e = [getTuple s | s <- (lines w2)]\n let e2 = e ++ (map (\\x -> (snd x,fst x)) e)\n let edges = accumArray (flip (:)) [] (1,n) e2\n print $ dfs hasCat edges 1 0 m 0\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\nimport Debug.Trace\n\n-- 580C\n\ndata TreeNode = TreeNode {\n hasCat :: Bool,\n children :: [Int]\n} deriving (Show)\n\nsolve :: Int -> Int -> [Bool] -> [[Int]] -> Int\nsolve n m hasCatLst edges =\n countRestaurants m 1\n where\n track a = trace (show a) a\n edgeGroups = groupBy (\\a -> \\b -> head a == head b) (sort (map sort edges))\n\n makeNodes (x:rst) (hasCat:rstHasCat) nextIdx =\n let nodeIdx = head (head x)\n children = map last x\n in\n if nodeIdx == nextIdx then\n (TreeNode {hasCat = hasCat,\n children = children}):makeNodes rst rstHasCat (nextIdx + 1)\n else\n (TreeNode {hasCat = hasCat,\n children = []}):makeNodes (x:rst) rstHasCat (nextIdx + 1)\n\n makeNodes [] (hasCat:rstHasCat) nextIdx =\n (TreeNode {hasCat = hasCat,\n children = []}):makeNodes [] rstHasCat (nextIdx + 1)\n makeNodes [] [] _ = []\n\n q = makeNodes edgeGroups hasCatLst 1\n nodes = listArray (1, n) q\n\n countRestaurants m' rootIdx\n | m'' >= 0 && children root == [] = 1\n | m'' >= 0 = sum $ map (countRestaurants m'') (children root)\n | otherwise = 0\n where\n root = nodes ! rootIdx\n m'' = if hasCat root then m' - 1 else m\n \n\nmain = do\n let f = map read . words <$> getLine\n [n, m] <- f\n hasCatLst <- map toEnum <$> f\n edges <- map (map read . words) . lines <$> getContents\n putStrLn $ show $ solve n m hasCatLst edges\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\nimport Debug.Trace\n\n-- 580C\n\ndata TreeNode = TreeNode {\n hasCat :: Bool,\n children :: [Int]\n} deriving (Show)\n\nsolve :: Int -> Int -> [Bool] -> [[Int]] -> Int\nsolve n m hasCatLst edges =\n countRestaurants m 1\n where\n track a = trace (show a) a\n edgeGroups = groupBy (\\a -> \\b -> head a == head b) (sort edges)\n\n makeNodes (x:rst) (hasCat:rstHasCat) nextIdx =\n let nodeIdx = head (head x)\n children = map last x\n in\n if nodeIdx == nextIdx then\n (TreeNode {hasCat = hasCat,\n children = children}):makeNodes rst rstHasCat (nextIdx + 1)\n else\n (TreeNode {hasCat = hasCat,\n children = []}):makeNodes (x:rst) rstHasCat (nextIdx + 1)\n\n makeNodes [] (hasCat:rstHasCat) nextIdx =\n (TreeNode {hasCat = hasCat,\n children = []}):makeNodes [] rstHasCat (nextIdx + 1)\n makeNodes [] [] _ = []\n\n q = makeNodes edgeGroups hasCatLst 1\n nodes = listArray (1, n) q\n\n countRestaurants m' rootIdx\n | m'' >= 0 && children root == [] = 1\n | m'' >= 0 = sum $ map (countRestaurants m'') (children root)\n | otherwise = 0\n where\n root = nodes ! rootIdx\n m'' = if hasCat root then m' - 1 else m\n \n\nmain = do\n let f = map read . words <$> getLine\n [n, m] <- f\n hasCatLst <- map toEnum <$> f\n edges <- map (map read . words) . lines <$> getContents\n putStrLn $ show $ solve n m hasCatLst edges\n"}, {"source_code": "import Data.Array\nimport Data.Graph\nimport Control.Monad\nmain = do\n [n,m] <- map read . words <$> getLine\n cats <- listArray (1,n) . map (toEnum . read) . words <$> getLine\n g <- fmap (buildG (1,n)) $ replicateM (n-1) $ do\n [x,y] <- map read . words <$> getLine\n return (x,y)\n let [t] = dfs g [1]\n count c (Node n ts) | c' > m = 0\n | null ts = 1\n | otherwise = sum (map (count c') ts)\n where c' = if cats!n then c+1 else 0\n print $ count 0 t\n"}], "src_uid": "875e7048b7a254992b9f62b9365fcf9b"} {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = mapM_ print . solve . map (map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, m] : as : qs) = map f qs\n where\n pos = length $ filter (== 1) as\n neg = n - pos\n f [l, r] = fromEnum $ m == 0 && pos >= d && neg >= d\n where\n (d, m) = (r - l + 1) `quotRem` 2\n", "positive_code": [{"source_code": "import Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact $ B.unwords . map showBI . rd . B.lines\nrd (nm:a:ql) = go (map (fst . fromJust . B.readInt) (B.words a)) (map (map $ fst . fromJust . B.readInt) . map B.words $ ql)\ngo a ql = foldr (\\(l:r:[]) ans -> (ch l r):ans) [] ql\n where ch l r | (r-l+1)`mod`2 == 1 = 0\n | otherwise = if (p>=cnt)&&(n>=cnt) then 1 else 0\n where cnt = (r-l+1)`div`2\n p = length $ filter (>0) a\n n = length $ filter (<0) a\n\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\n\n"}, {"source_code": "import Control.Monad (liftM, replicateM)\nimport Prelude hiding (read, reads)\n\nread :: String -> Int\nread ('-':s) = (-1) * read s\nread s = read' 0 s\n where\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + fromEnum c - fromEnum '0'\n\n--reads :: Read a => IO [a]\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [Int] -> [[Int]] -> [Int]\nsolve n as qs = map solve' qs\n where\n x = length $ filter (== 1) as\n y = n - x\n solve' [l,r]\n | odd (r - l + 1) = 0\n | (r - l + 1) > 2 * min x y = 0\n | otherwise = 1\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n as <- reads\n qs <- replicateM m reads\n mapM_ print $ solve n as qs\n"}, {"source_code": "import Control.Monad (liftM, replicateM)\nimport Prelude hiding (read, reads)\n\nread :: String -> Int\nread ('-':s) = (-1) * read s\nread s = read' 0 s\n where\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + fromEnum c - fromEnum '0'\n\n--reads :: Read a => IO [a]\nreads :: IO [Int]\nreads = liftM (map read . words) getContents\n\nsolve :: Int -> [Int] -> [Int] -> [Int]\nsolve n as qs = solve' qs\n where\n x = length $ filter (== 1) as\n y = n - x\n solve' (l:r:qs)\n | odd (r - l + 1) = 0 : solve' qs\n | (r - l + 1) > 2 * min x y = 0 : solve' qs\n | otherwise = 1 : solve' qs\n solve' _ = []\n\nmain :: IO ()\nmain = do\n ints <- reads\n let [n, m] = take 2 ints\n let as = take n $ drop 2 ints\n let qs = take (2*m) $ drop n $ drop 2 ints\n mapM_ print $ solve n as qs\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n [n, m] <- getList\n a <- getList\n let aminus = foldl' (\\acc x -> if x < 0 then acc+1 else acc) 0 a\n let aplus = length(a) - aminus\n m <- replicateM m getList\n mapM_ (\\x -> print $ f x aminus aplus) m\n where\n f [l, r] aminus aplus = if t `mod` 2 == 0 && t2 <= aminus && t2 <= aplus && t > 0 then 1 else 0\n where\n\tt = r - l + 1\n\tt2 = t `div` 2\n getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n lrs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show $ solve n xs lrs\n\nsolve :: Int -> [Int] -> [Int] -> [Int]\nsolve n xs lrs = go lrs\n where\n !ts = sum[1|1<-xs]\n !fs = n - ts\n go (l:r:rest)\n | even (r-l) = 0 : go rest\n | 2 * min ts fs >= r-l+1 = 1 : go rest\n | otherwise = 0 : go rest\n go _ = []"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess [] _ _ = do\n\t\t\tputStr \"\"\n\nprocess ([b1,b2]:b) a1 a2 = do\n\t\t\t\tprocess1 b1 b2 a1 a2\n\t\t\t\tprocess b a1 a2\n\n\nprocess1 b1 b2 a1 a2 = do\n\t\t\t\tprint $ if even (b2-b1) then 0 \n\t\t\t\t\t\t else if a1> div (b2-b1) 2 && a2 >div (b2-b1) 2 then 1 else 0 \t \n\n\n\t\t\n\nmain = do\n\t\t[ne,nq]<- map read <$> words <$> getLine ::IO [Int]\n\t\ta<- words <$> getLine \n\t\tlet a1= length $ filter (==\"1\") a\n\t\tlet a2= (length a) - a1\t\n\t\tb<- map (map read) <$> map words <$> replicateM nq getLine ::IO [[Int]]\n\t\tprocess b a1 a2\n"}], "negative_code": [], "src_uid": "deeb49969ac4bc4f1c7d76b89ac1402f"} {"source_code": "{-# LANGUAGE RankNTypes #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\nimport System.IO\n\nimport Data.List\nimport Data.Ord\nimport Data.Array\nimport Control.Monad\n \n{-\n\u30e1\u30e2\u5316\n-}\nmemoise :: forall a b. Ix a => ((a -> b) -> a -> b) -> (a,a) -> a -> b\nmemoise f r = let mem = listArray r . map (f (mem!)) $ range r in (mem!)\n\n\n{-\n\u30e1\u30e2\u5316\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\n-}\nfib :: (Integer -> Integer) -> Integer -> Integer\nfib f n | n <= 1 = n\n | True = f (n-1) + f (n-2)\n\nmax_memo :: Integer\nmax_memo = 500\n\nmemoFib :: Integer -> Integer\nmemoFib = memoise fib (0,100000)\n\n{-\n\u30d1\u30b9\u30ab\u30eb\u306e\u4e09\u89d2\u5f62\n-}\npascalTriangle :: Integer -> Integer -> Integer\npascalTriangle = memoise row (0,1000000)\n where\n row memo n = memoise col rng\n where\n rng = (0,n)\n col _ r\n | r == 0 = 1\n | r == n = 1\n | True = memo (n-1) (r-1) + memo (n-1) r\n\ncomb :: Integer -> Integer -> Integer\ncomb = pascalTriangle\n\n--memoise \n \ntoTuple :: [String] -> (String,Integer)\ntoTuple (a:b:[]) = (a,read b)\n \neqFst (a,b) (c,d) = a==c\n \n--calc :: Array Int (String, Integer) -> Int -> Integer\ncalc xs memo k\n | k <= 1 = 0\n | fst (xs ! k) == \"win\" = y\n | True = maximum $ (y : map f [1..k-1])\n where\n y = memo (k-1)\n --y = calc xs (k-1)\n f m | fst (xs ! m) == \"sell\" = 0\n | snd (xs!m) /= snd (xs!k) = 0\n -- | m == 1 = 0\n | True = 2 ^ (snd (xs ! m)) + memo (m-1)\n\nmemoCalc xs n = memoise (calc xs) (0,n)\n\nmain = do\n n <- readLn :: IO Int\n xs' <- replicateM n $ (toTuple . words) `liftM` getLine\n let xs = listArray (1,n) xs'\n \n print $ memoCalc xs n n\n \n", "positive_code": [{"source_code": "tryX :: Int -> [(String, Int)] -> Integer \ntryX (-1) _ = 0 \ntryX x events = let sells = [j | (j, (\"sell\", y)) <- eventsWithIds, y == x] in \n if null sells then tryX (x - 1) events \n else let j = head sells; wins = [i | (i, (\"win\", y)) <- take j eventsWithIds, y == x] in \n if null wins then tryX (x - 1) events \n else let i = last wins in \n 2 ^ x + tryX (x - 1) (take i events) + tryX (x - 1) (drop (j + 1) events) \n where eventsWithIds = zip [0..] events \n \nsolve :: [(String, Int)] -> Integer \nsolve events = tryX 2000 events \n \nmain = do \n contents <- getContents \n let n = read $ head $ lines contents\n let events = map (\\s -> let [t, x] = words s in (t, read x)) $ take n $ tail $ lines contents \n putStrLn $ show $ solve events\n "}], "negative_code": [{"source_code": "{-# LANGUAGE RankNTypes #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\nimport System.IO\n\nimport Data.List\nimport Data.Ord\nimport Data.Array\nimport Control.Monad\n \n{-\n\u30e1\u30e2\u5316\n-}\nmemoise :: forall a b. Ix a => ((a -> b) -> a -> b) -> (a,a) -> a -> b\nmemoise f r = let mem = listArray r . map (f (mem!)) $ range r in (mem!)\n\n\n{-\n\u30e1\u30e2\u5316\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\n-}\nfib :: (Integer -> Integer) -> Integer -> Integer\nfib f n | n <= 1 = n\n | True = f (n-1) + f (n-2)\n\nmax_memo :: Integer\nmax_memo = 500\n\nmemoFib :: Integer -> Integer\nmemoFib = memoise fib (0,100000)\n\n{-\n\u30d1\u30b9\u30ab\u30eb\u306e\u4e09\u89d2\u5f62\n-}\npascalTriangle :: Integer -> Integer -> Integer\npascalTriangle = memoise row (0,1000000)\n where\n row memo n = memoise col rng\n where\n rng = (0,n)\n col _ r\n | r == 0 = 1\n | r == n = 1\n | True = memo (n-1) (r-1) + memo (n-1) r\n\ncomb :: Integer -> Integer -> Integer\ncomb = pascalTriangle\n\n--memoise \n \ntoTuple :: [String] -> (String,Integer)\ntoTuple (a:b:[]) = (a,read b)\n \neqFst (a,b) (c,d) = a==c\n \n--calc :: Array Int (String, Integer) -> Int -> Integer\ncalc xs memo k\n | k <= 1 = 0\n | fst (xs ! k) == \"win\" = y\n | True = maximum $ (y : map f [1..k-1])\n where\n y = memo (k-1)\n --y = calc xs (k-1)\n f m | fst (xs ! m) == \"sell\" = 0\n | snd (xs!m) /= snd (xs!k) = 0\n | m == 1 = 0\n | True = 2 ^ (snd (xs ! m)) + memo (m-1)\n\nmemoCalc xs n = memoise (calc xs) (1,n)\n\nmain = do\n n <- readLn :: IO Int\n xs' <- replicateM n $ (toTuple . words) `liftM` getLine\n let xs = listArray (1,n) xs'\n \n print $ memoCalc xs n n\n \n"}, {"source_code": "tryX :: Int -> [(String, Int)] -> Integer \ntryX (-1) _ = 0 \ntryX x events = let sells = [j | (j, (\"sell\", y)) <- eventsWithIds, y == x] in \n if null sells then tryX (x - 1) events \n else let j = head sells; wins = [i | (i, (\"win\", y)) <- take j eventsWithIds, y == x] in \n if null wins then tryX (x - 1) events \n else let i = last wins in \n 2 ^ x + tryX (x - 1) (take i events ++ drop (j + 1) events) \n where eventsWithIds = zip [0..] events \n \nsolve :: [(String, Int)] -> Integer \nsolve events = tryX 2000 events \n \nmain = do \n contents <- getContents \n let n = read $ head $ lines contents\n let events = map (\\s -> let [t, x] = words s in (t, read x)) $ take n $ tail $ lines contents \n putStrLn $ show $ solve events\n "}, {"source_code": "tryX :: Int -> [(String, Int)] -> Integer\ntryX (-1) _ = 0\ntryX x events = let sells = [j | (j, (\"sell\", y)) <- eventsWithIds, y == x] in\n if null sells then tryX (x - 1) events\n else let j = head sells; wins = [i | (i, (\"win\", y)) <- take j eventsWithIds, y == x] in\n if null wins then tryX (x - 1) events\n else let i = last wins in\n 2 ^ x + tryX (x - 1) (take i events ++ drop (j + 1) events) \n where eventsWithIds = zip [0..] events\n\nsolve :: [(String, Int)] -> Integer\nsolve events = tryX 2000 events\n\nmain = do\n contents <- getContents\n let events = map (\\s -> let [t, x] = words s in (t, read x)) $ tail $ lines contents\n putStrLn $ show $ solve events\n\n"}], "src_uid": "217a3a48b927213f4d5e0a19048e2a32"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, c] <- getInts\n ts <- getInts\n\n print $ (length $ takeWhile id $ reverse $ zipWith (\\x y -> y <= x+c) ts (tail ts)) + 1\n", "positive_code": [{"source_code": "main = do\n [n,c] <- return . map read . words =<< getLine\n times <- return . map read . words =<< getLine\n let revTm = map negate . reverse $ times\n\tpass = takeWhile (<=c) . tail $ adjaDiffs revTm\n print $ 1+length pass\n\nadjaDiffs::Num n => [n] -> [n]\nadjaDiffs list = zipWith (-) list $ 0:list\n"}, {"source_code": "import Data.Functor\n\nsol :: Int -> [Int] -> Int\nsol c (t1:t2:ts)\n | t1 - t2 > c = 1\n | otherwise = 1 + sol c (t2:ts)\nsol _ (t:[]) = 1\n\nmain = do\n c <- (read . head . tail . words) <$> getLine\n ts <- (reverse . fmap read . words) <$> getLine\n putStrLn $ show $ sol c ts\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nprocess [a,b,c,d] | mod (b-a) (c+d)>0 = -1\n | otherwise = div (b-a) (c+d) \n\n\nmain::IO ()\nmain=do\n \t[t,s]<- map read<$>words <$> getLine ::IO [Int]\t\n\ta<- map read<$> words <$>getLine::IO [Int] \n\tlet b = length $ takeWhile (<=s)$ reverse $ zipWith (\\x y ->y-x) a (tail a)\n\tprint $ b+1\n"}, {"source_code": "merge res1 res2 x y len c = if res2 == len && x + c >= y\n then len + res1\n else res2\npre_merge c pair = merge (solve c (fst pair)) (solve c (snd pair)) (last (fst pair)) (head (snd pair)) (length (snd pair)) c\nsolve c t = if length t == 1\n then 1\n else pre_merge c (splitAt (quot (length t) 2) t)\nparse str1 str2 = solve (read ((words str1) !! 1) :: Int) ([read x :: Int | x <- (words str2)])\nmain = do\n line1 <- getLine\n line2 <- getLine\n print (parse line1 line2)\n"}, {"source_code": "process :: Int -> [Int] -> Int\nprocess c xs = (+1) . length . takeWhile (<=c) $ zipWith (-) xs' (tail xs')\n where xs' = reverse xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n,c] = map readInt (words line)\n xs <- fmap (map readInt.words) getLine\n print $ process c xs"}, {"source_code": "main :: IO ()\nmain = do\n _:c:xs <- getReadAll\n print $ solve c xs\n\nsolve :: Int -> [Int] -> Int\nsolve delay = fst . foldl (transition delay) (0, 0)\n\ntransition :: Int -> (Int, Int) -> Int -> (Int, Int)\ntransition delay (oldCount, lastTs) newTs = (newCount, newTs)\n where newCount = if newTs - lastTs > delay then 1 else oldCount + 1\n\ngetReadAll :: (Read a) => IO [a]\ngetReadAll = fmap (fmap read. words) getContents"}, {"source_code": "solve :: Int -> Int -> Int -> [Int] -> Int\nsolve n _ _ [] = n\nsolve n c t (x:xs)\n | x - t <= c = solve (n + 1) c x xs\n | otherwise = solve 1 c x xs\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, c] = map read $ words line :: [Int]\n line <- getLine\n let ts = map read $ words line :: [Int]\n print $ solve 0 c 0 ts\n"}, {"source_code": "import Data.Array as A\nmain = do\n cin <- getContents\n let n:c:a = map read (words cin) :: [Int]\n let b = A.listArray (1, n) a\n let f r i = if b A.! i - b A.! (i-1) > c then 0 else r + 1\n print $ 1 + foldl f 0 [2..n]"}, {"source_code": "\nprocess :: Int -> (Int, Int) -> Int -> (Int, Int)\nprocess timeDiff prev curTime =\n let\n prevCnt = fst prev\n prevTime = snd prev\n in if curTime - prevTime <= timeDiff\n then (prevCnt + 1, curTime)\n else (1, curTime)\n\nmain :: IO ()\nmain = do\n s1 <- getLine\n let [n, c] = map read $ words s1\n s2 <- getLine\n let vals = map read $ words s2\n let r = foldl (process c) (0, 0) vals\n putStrLn (show (fst r))"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, c] <- map read . words <$> getLine\n ts <- map read . words <$> getLine\n\n print $ (length $ takeWhile id $ reverse $ zipWith (\\x y -> y <= x+c) ts (tail ts)) + 1\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = (solve.tail.concat =<< forM [1 .. 2] ( \\i -> map (fst.fromJust.C.readInt).C.words <$> C.getLine))\nsolve (x:xs) = print $ fst $ foldl (\\(b1,b2) a-> if a-b2<=x then (b1+1,a) else (1,a)) (0,0) xs "}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\n\n\n\n\n\nmain = do\n [a,b]<-map read <$> words <$> getLine ::IO [Int]\n m<-map read <$> words <$> getLine ::IO [Int]\n print $ (+1) $ length $ takeWhile (<=b) $ reverse $ zipWith (-) (tail m) m\n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (c:ts) = go 0 0 ts where\n go i p (t:ts) | t-p > c = go 1 t ts\n | otherwise = go (i+1) t ts\n go i _ _ = i\n"}, {"source_code": "main = getContents >>= print . solve 0 . map read . tail . words\n\nsolve cnt (c:[_]) = cnt + 1\nsolve cnt (c:t0:t1:ts) = if t1 - t0 <= c\n then solve (cnt + 1) (c:t1:ts)\n else solve 0 (c:t1:ts)"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: Int -> Int -> [Int] -> Int\n solve k c (x:y:xs)\n | y - x <= k = solve k (c + 1) (y:xs)\n | otherwise = solve k 1 (y:xs)\n solve _ c (y:xs) = c\n solve _ c [] = c\n\n main :: IO()\n main = do\n [n, k] <- getLine >>= return . map readInt . words\n xs <- getLine >>= return . map readInt . words\n print $ solve k 1 $ sort xs\n"}, {"source_code": "module Main where\nimport Data.List\nparseLine line =\n map (\\numStr -> read numStr :: Int) $ words line\n\ncalculateElapsedSeconds array =\n zipWith (\\a b -> a - b) (drop 1 array ++ [last array]) array\n\nsolve wordCount maxSeconds array =\n case findIndex (\\et -> et > maxSeconds) $ reverse $ calculateElapsedSeconds array of\n Just result -> result\n Nothing -> wordCount\n\nmain =\n do\n firstLine <- getLine\n secondLine <- getLine\n let firstLineParsed = parseLine firstLine\n let seconds = parseLine secondLine\n putStrLn $ show $ solve (firstLineParsed!!0) (firstLineParsed!!1) seconds"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, c] <- map read . words <$> getLine\n ts <- map read . words <$> getLine\n\n let rs = map length $ filter (id . head) $ group $ zipWith (\\x y -> y <= x+c) ts (tail ts)\n\n print $ if null rs then 1 else maximum rs + 1\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, c] <- map read . words <$> getLine\n ts <- map read . words <$> getLine\n\n let rs = map length $ filter (id . head) $ group $ zipWith (\\x y -> y <= x+c) ts (tail ts)\n\n print $ if null rs then 1 else last rs + 1\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: Int -> Int -> [Int] -> Int\n solve k c (x:y:xs)\n | y - x <= k = solve k (c + 1) (y:xs)\n | otherwise = solve k 1 (y:xs)\n solve _ c (y:xs) = c\n solve _ c [] = c\n\n main :: IO()\n main = do\n [n, k] <- getLine >>= return . map readInt . words\n xs <- getLine >>= return . map readInt . words\n print $ solve k 0 xs\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: Int -> Int -> [Int] -> Int\n solve k c (x:y:xs)\n | y - x <= k = solve k (c + 1) (y:xs)\n | otherwise = solve k 1 (y:xs)\n solve _ c (y:xs) = c\n solve _ c [] = c\n\n main :: IO()\n main = do\n [n, k] <- getLine >>= return . map readInt . words\n xs <- getLine >>= return . map readInt . words\n print $ solve k 0 $ sort xs\n"}, {"source_code": "module Main where\nimport Data.List\nparseLine line =\n map (\\numStr -> read numStr :: Integer) $ words line\n\ncalculateElapsedSeconds array =\n zipWith (\\a b -> a - b) (drop 1 array ++ [last array]) array\n\nsolve maxSeconds array =\n case findIndex (\\et -> et > 5) $ reverse (calculateElapsedSeconds array) of\n Just result -> result\n Nothing -> -1\n\n\nmain =\n do\n firstLine <- getLine\n secondLine <- getLine\n let firstLineParsed = parseLine firstLine\n let seconds = parseLine secondLine\n putStrLn $ show $ solve (firstLineParsed!!1) seconds"}, {"source_code": "module Main where\nimport Data.List\nparseLine line =\n map (\\numStr -> read numStr :: Integer) $ words line\n\ncalculateElapsedSeconds array =\n zipWith (\\a b -> a - b) (drop 1 array ++ [last array]) array\n\nsolve maxSeconds array =\n case findIndex (\\et -> et > maxSeconds) $ reverse elapsedSeconds of\n Just result -> result\n Nothing -> 1\n where\n elapsedSeconds = calculateElapsedSeconds array\n\n\nmain =\n do\n firstLine <- getLine\n secondLine <- getLine\n let firstLineParsed = parseLine firstLine\n let seconds = parseLine secondLine\n putStrLn $ show $ solve (firstLineParsed!!1) seconds"}, {"source_code": "module Main where\nimport Data.List\nparseLine line =\n map (\\numStr -> read numStr :: Integer) $ words line\n\ncalculateElapsedSeconds array =\n zipWith (\\a b -> a - b) (drop 1 array ++ [last array]) array\n\nsolve maxSeconds array =\n case findIndex (\\et -> et > maxSeconds) $ reverse elapsedSeconds of\n Just result -> result\n Nothing -> -1\n where\n elapsedSeconds = calculateElapsedSeconds array\n\n\nmain =\n do\n firstLine <- getLine\n secondLine <- getLine\n let firstLineParsed = parseLine firstLine\n let seconds = parseLine secondLine\n putStrLn $ show $ solve (firstLineParsed!!1) seconds"}, {"source_code": "solve c t = sum [1 | x <- t, (x + c) >= (last t)]\nparse str1 str2 = solve (read ((words str1) !! 1) :: Int) ([read x :: Int | x <- (words str2)])\nmain = do\n line1 <- getLine\n line2 <- getLine\n print (parse line1 line2)\n"}, {"source_code": "solve :: Int -> Int -> Int -> [Int] -> Int\nsolve n _ _ [] = n\nsolve n c t (x:xs)\n | x - t <= c = solve (n + 1) c x xs\n | otherwise = solve 1 c x xs\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, c] = map read $ words line :: [Int]\n line <- getLine\n let ts = map read $ words line :: [Int]\n print $ solve n c (head ts) ts\n"}], "src_uid": "fb58bc3be4a7a78bdc001298d35c6b21"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nsolve :: Int -> [Int] -> Int\nsolve m li = let\n buckets :: UArray Int Int\n buckets = accumArray (const . (+ 1)) 0 (0, m-1) $ zip (map (`mod` m) li) li\n in foldl' (+) 0 $ do --'\n (v, ct) <- assocs buckets\n let\n sv = mod (negate v) m\n sct = buckets ! sv\n guard $ (ct, v) >= (sct, sv)\n pure $ if ct == 0\n then 0\n else max 1 (ct - sct)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n, m] <- readInts\n a <- readInts\n putInts [solve m a]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Map.Strict as MapS\r\n\r\nmain = do\r\n t <- readLn\r\n replicateM t testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n firstLine <- getLine\r\n let [_,m] = map read . words $ firstLine\r\n a <- fmap (map read . words) getLine\r\n putStrLn $ solve a m\r\n\r\nsolve :: [Int] -> Int -> String\r\nsolve a m = \r\n if MapS.member 0 counts then\r\n show $ solution + 1\r\n else show solution\r\n where\r\n modded = map (`mod` m) a\r\n counts = foldl' (\\acc curr -> MapS.insertWith (+) curr 1 acc) MapS.empty modded :: Map.Map Int Int\r\n mapFoldF :: Int -> Int -> Int -> Int\r\n mapFoldF k a b \r\n | k == 0 = b\r\n | MapS.member (m-k) counts && k < m-k = b\r\n | otherwise = (b+) . (1+) . max 0 . (subtract 1) . abs . (a-) $ MapS.findWithDefault 0 (m-k `mod` m) counts\r\n solution = MapS.foldrWithKey mapFoldF 0 counts :: Int"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Char\nimport Data.List (sort, group)\nimport Data.Map ((!))\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\nimport System.IO\nimport Text.Read\nimport Data.Maybe (fromJust)\n\ngetNums :: IO [Int]\ngetNums = do\n line <- B.getLine\n return $ map ((fst . fromJust) . B.readInt) . B.split ' ' $ line\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, m] <- getNums\n as <- getNums\n print $ solve m as\n\nsolve m as = sum solves\n where\n ams = map (`mod` m) as\n sizes = M.fromList $ map (\\xs -> (head xs, length xs)) $ group $ sort ams\n\n solveForSize i\n | i == 0 = 1\n | i < i' && M.member i' sizes = 0\n | otherwise = max 1 $ abs (curSize - compSize)\n where\n i' = m - i\n curSize = sizes ! i\n compSize = M.findWithDefault 0 i' sizes\n\n solves = map solveForSize $ M.keys sizes\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Map.Strict as MapS\r\n\r\nmain = do\r\n t <- readLn\r\n replicateM t testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n firstLine <- getLine\r\n let [_,m] = map read . words $ firstLine\r\n a <- fmap (map read . words) getLine\r\n putStrLn $ solve a m\r\n\r\nsolve :: [Int] -> Int -> String\r\nsolve a m = \r\n if MapS.member 0 counts then\r\n show $ solution + 1\r\n else show solution\r\n where\r\n modded = map (`mod` m) a\r\n counts = foldl' (\\acc curr -> MapS.insertWith (+) curr 1 acc) MapS.empty modded :: Map.Map Int Int\r\n mapFoldF :: Int -> Int -> Int -> Int\r\n mapFoldF k a b \r\n | k == 0 = b\r\n | MapS.member (m-k) counts && k < m `div` 2 = b\r\n | otherwise = (b+) . (1+) . max 0 . (subtract 1) . abs . (a-) $ MapS.findWithDefault 0 (m-k `mod` m) counts\r\n solution = MapS.foldrWithKey mapFoldF 0 counts :: Int"}], "src_uid": "d107db1395ded62904d0adff164e5c1e"} {"source_code": "\n{-# LANGUAGE LambdaCase #-}\n\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.List\n\nmain = interact $\n runScanner (numberOf tc) >>> map (solve >>> show) >>> unlines\n\ntc :: Scanner (Int, [[Int]])\ntc = do\n n <- int\n (,) <$> int <*> two (replicateM n int)\n\nsolve :: (Int, [[Int]]) -> Int\nsolve (k, [as, bs]) = sum $ zipWith max (sort as) (take k (reverse (sort bs)) ++ repeat 0)\n\n------------------------------------------------------------\n\ntype Scanner = State [String]\n\nrunScanner :: Scanner a -> String -> a\nrunScanner = runScannerWith words\n\nrunScannerWith :: (String -> [String]) -> Scanner a -> String -> a\nrunScannerWith t s = evalState s . t\n\nstr :: Scanner String\nstr = get >>= \\case { s:ss -> put ss >> return s }\n\nint :: Scanner Int\nint = read <$> str\n\ninteger :: Scanner Integer\ninteger = read <$> str\n\ndouble :: Scanner Double\ndouble = read <$> str\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case { [] -> return []; _ -> (:) <$> s <*> many s }\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map replicateM [2..4]\n\n\n", "positive_code": [{"source_code": "import Control.Monad.State\nimport Control.Monad\nimport Data.List\n\nfmapfst :: (a -> c) -> (a,b) -> (c,b)\nfmapfst f (a,b) = (f a, b)\n\n\nalg :: Int -> State ([Int],[Int]) ()\nalg n= do\n forM_ [1..n] (\\_ -> do\n a' <- fmap (minimum . fst) get\n b' <- fmap (maximum . snd) get\n modify (fmapfst ((b':) . delete a'))\n modify (fmap ((a':) . delete b'))\n )\n\nfinAlg_ :: [Int] -> [Int] -> Int -> Int\nfinAlg_ a b n = sum $ fst $ execState (alg n) (a,b)\n\nfinAlg :: [Int] -> [Int] -> Int -> Int\nfinAlg a b n = maximum $ map (finAlg_ a b)[0..n]\n\ngetOnes :: IO ([Int],[Int],Int)\ngetOnes = do\n (_:n:_) <- fmap ( map read .words) getLine\n a <- fmap ( map read .words) getLine\n b <- fmap ( map read .words) getLine\n return (a,b,n)\n\nmain :: IO()\nmain = do\n x <- fmap read getLine\n ls <- replicateM x getOnes\n mapM_ (print . (\\(a,b,n) -> finAlg a b n)) ls\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [_,k]<- (map read.words) <$> getLine\n as <- (map read.words) <$> getLine\n bs <- (map read.words) <$> getLine\n print $ solve k as bs\n\nsolve :: Int -> [Int] -> [Int] -> Int\nsolve k as bs = sum $ (drop k ass) ++ (take k $ sortOn Down c)\n where\n ass = sort as\n bss = sortOn Down bs\n c = take k ass ++ take k bss\n"}, {"source_code": "module Main where\nimport Data.List\n\nsolve [] = []\nsolve ([_,n] : xs : ys : zss) = (show $ sum $ solve' xs ys ) : solve zss \n\twhere \n\t\tsolve' xs ys = zipWith max (take n (reverse $ sort ys)) (take n (sort xs)) ++ drop n (sort xs)\n\nmain = interact $ unlines . solve . map (map (read :: String -> Int) . words) . tail . lines"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,k]<- map read <$> words <$> getLine::IO [Int]\n\t\ta<- sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tb<- reverse<$> sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tlet c = sum $ map (\\(a,b)-> b-a) $ take k $takeWhile (\\(x,y)->y>=x) $ zip a b\n\t\tprint $ c+ sum a\nmain = do\n\tn<- read <$> getLine ::IO Int\n\treplicateM_ n onecase\n\n\n"}, {"source_code": "import Data.Map as M\nimport Data.List as L\n\nfun :: [Integer] -> [Integer] -> Integer -> Integer\nfun as _ 0 = sum as\nfun as bs k = if a < b then (b + fun as' bs' (k-1)) else sum as\n where (a:as') = L.sort as\n (b:bs') = reverse $ L.sort bs\n\npartitionBy :: [String] -> [[String]]\npartitionBy [] = []\npartitionBy (a:b:c:xs) = [[a, b, c]] ++ (partitionBy xs)\n\nsolve' :: String -> String -> String -> String\nsolve' k' as' bs' = show $ fun as bs k\n where k = head $ tail $ L.map (\\x -> read x :: Integer) $ words k'\n as = L.map (\\x -> read x :: Integer) $ words as'\n bs = L.map (\\x -> read x :: Integer) $ words bs'\n\nsolve :: String -> String\nsolve input = unlines $ [solve' a b c | [a, b, c] <- partitionBy lines']\n where lines' = tail $ lines input\n\nmain :: IO()\nmain = do\n contents <- getContents\n putStr (solve contents)\n"}], "negative_code": [{"source_code": "import Control.Monad.State\nimport Control.Monad\nimport Data.List\n\nfmapfst :: (a -> c) -> (a,b) -> (c,b)\nfmapfst f (a,b) = (f a, b)\n\n\nalg :: Int -> State ([Int],[Int]) ()\nalg n= do\n forM_ [1..n] (\\_ -> do\n a' <- fmap (minimum . fst) get\n b' <- fmap (maximum . snd) get\n modify (fmapfst ((b':) . delete a'))\n modify (fmap ((a':) . delete b'))\n )\n\nfinAlg :: [Int] -> [Int] -> Int -> Int\nfinAlg a b n = sum $ fst $ execState (alg n) (a,b)\n\ngetOnes :: IO ([Int],[Int],Int)\ngetOnes = do\n (_:n:_) <- fmap ( map read .words) getLine\n a <- fmap ( map read .words) getLine\n b <- fmap ( map read .words) getLine\n return (a,b,n)\n\nmain :: IO()\nmain = do\n x <- fmap read getLine\n ls <- replicateM x getOnes\n mapM_ (print . (\\(a,b,n) -> finAlg a b n)) ls\n"}, {"source_code": "module Main where\nimport Data.List\n\nsolve [] = []\nsolve ([_,n] : xs : ys : zss) = (show $ sum $ solve' xs ys ) : solve zss \n\twhere \n\t\tsolve' xs ys = take n (reverse $ sort ys) ++ drop n (sort xs)\n\nmain = interact $ unlines . solve . map (map (read :: String -> Int) . words) . tail . lines"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,k]<- map read <$> words <$> getLine::IO [Int]\n\t\ta<- sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tb<- reverse<$> sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tlet c = sum $ map (\\(a,b)-> b-a) $ take k $takeWhile (\\(x,y)->x>=y) $ zip a b\n\t\tprint $ c+ sum a\nmain = do\n\tn<- read <$> getLine ::IO Int\n\treplicateM_ n onecase\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nonecase = do\n\t\t[n,k]<- map read <$> words <$> getLine::IO [Int]\n\t\ta<- sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tb<- reverse<$> sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tprint $ sum a + sum(take k b)- sum (take k a)\n\nmain = do\n\tn<- read <$> getLine ::IO Int\n\treplicateM_ n onecase\n\n\n"}], "src_uid": "7c2337c1575b4a62e062fc9990c0b098"} {"source_code": "import qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInteger :: IO Integer\ngetInteger = fmap (fst . fromJust) $ fmap C.readInteger C.getLine\n\nmain = do\n a <- getInteger\n b <- getInteger\n putStrLn $ case a `compare` b of\n LT -> \"<\"\n EQ -> \"=\"\n GT -> \">\"\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (readInteger, words, unpack, getLine)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, getLine)\n\nmain = do\n a <- fst . fromJust . readInteger <$> getLine :: IO Integer\n b <- fst . fromJust . readInteger <$> getLine :: IO Integer\n\n putStrLn $ case compare a b of\n LT -> \"<\"\n EQ -> \"=\"\n GT -> \">\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nmain = B.getContents >>= (B.putStr . B.pack . compare. map (fst . fromJust . B.readInteger) . B.lines)\n where\n myread x = read x :: Integer\n compare (a:b:xc) = fun (a - b)\n where\n fun x | x == 0 = \"=\"\n | x < 0 = \"<\"\n | otherwise = \">\""}, {"source_code": "compareNumbers :: String -> String -> String\ncompareNumbers fst snd =\n let fstLength = length fst\n sndLength = length snd\n deltaLength = fstLength - sndLength\n prefix = replicate (abs deltaLength) '0' in\n if deltaLength < 0 then compareNumbers (prefix ++ fst) snd\n else if deltaLength > 0 then compareNumbers fst (prefix ++ snd)\n else case (compare fst snd) of\n LT -> \"<\"\n EQ -> \"=\"\n GT -> \">\" \n \nmain :: IO ()\nmain = do\n fst <- getLine :: IO String\n snd <- getLine :: IO String\n putStrLn (compareNumbers fst snd)"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = answer\n where\n (aw:bw:xs) = words input\n raw = reverse aw\n rbw = reverse bw\n\n answer = amap (go raw rbw)\n\namap 0 = \"=\" \namap 1 = \">\" \namap (-1) = \"<\" \n\ngo:: String -> String -> Int\n\ngo [] [] = 0\ngo (ca:xa) [] = if ca /= '0' then\n 1\n else\n go xa []\ngo [] (cb:xb) = if cb /= '0' then\n -1\n else\n go [] xb\n\ngo (ca:xa) (cb:xb) = \n if next == 0 then\n if ca == cb then\n next\n else if ca > cb then\n 1\n else \n -1\n else\n next\n\n where \n next = go xa xb\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.String\nimport Data.Maybe\nimport Data.Either\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nfoo :: String -> String -> Bool -> String\nfoo \"\" \"\" _ = \"=\"\nfoo ('0':xs) ys True = foo xs ys True\nfoo xs ('0':ys) True = foo xs ys True\nfoo _ \"\" _ = \">\"\nfoo \"\" _ _ = \"<\"\nfoo a@(x:xs) b@(y:ys) f = if f && length a /= length b\n then if length a > length b then \">\" else \"<\"\n else if x == y\n then foo xs ys False\n else if x < y then \"<\" else \">\"\n\nmain :: IO()\nmain = do\n s1 <- getLine\n s2 <- getLine\n putStrLn $ foo s1 s2 True\n"}, {"source_code": "import Data.Char\n\n\nsolve :: [String] -> String\n\nsolve xs\n | a > b = \">\"\n | a < b = \"<\"\n | otherwise = \"=\"\n where a = read (head xs) :: Integer\n b = read (last xs) :: Integer\n\n\n\nmain = interact $ solve . words\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\ncmp :: B.ByteString -> B.ByteString -> String\ncmp str1 str2 = case compare (B.length str1') (B.length str2') of\n LT -> \"<\"\n GT -> \">\"\n EQ -> case compare str1' str2' of\n LT -> \"<\"\n GT -> \">\"\n EQ -> \"=\"\n where [str1', str2'] = map (B.dropWhile (== '0')) [str1, str2]\n\nmain :: IO ()\nmain = cmp <$> B.getLine <*> B.getLine >>= putStrLn\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\n\nmain = do\n\t[a,b] <- replicateM 2 $ fmap (fst . fromJust . B.readInteger) B.getLine\n\tputStrLn $ case (compare a b) of\n\t\tEQ -> \"=\"\n\t\tLT -> \"<\"\n\t\tGT -> \">\""}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString as BS\n\nmain :: IO ()\nmain = do\n a <- (BS.dropWhile (== 48)) <$> BS.getLine\n b <- (BS.dropWhile (== 48)) <$> BS.getLine\n\n putStrLn $ case (compare (BS.length a) (BS.length b), compare a b) of\n (LT, _) -> \"<\"\n (GT, _) -> \">\"\n (_, LT) -> \"<\"\n (_, GT) -> \">\"\n _ -> \"=\""}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n a <- (dropWhile (== '0')) <$> getLine\n b <- (dropWhile (== '0')) <$> getLine\n\n putStrLn $ case (compare (length a) (length b), compare a b) of\n (LT, _) -> \"<\"\n (GT, _) -> \">\"\n (_, LT) -> \"<\"\n (_, GT) -> \">\"\n _ -> \"=\""}, {"source_code": "check :: String -> String -> String\ncheck a b\n | la < lb = \"<\"\n | la > lb = \">\"\n | otherwise = cmpr ca cb\n where\n ca' = dropWhile (=='0') a\n cb' = dropWhile (=='0') b\n ca = if ca' == [] then \"0\" else ca'\n cb = if cb' == [] then \"0\" else cb'\n la = length ca\n lb = length cb\n cmpr [] [] = \"=\"\n cmpr (x:xs) (y:ys)\n | x < y = \"<\"\n | x > y = \">\"\n | otherwise = cmpr xs ys\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ check a b\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (readInt, words, unpack, getLine)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, getLine)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n a <- fst . fromJust . readInt <$> getLine\n b <- fst . fromJust . readInt <$> getLine\n\n putStrLn $ case compare a b of\n LT -> \"<\"\n EQ -> \"=\"\n GT -> \">\"\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = answer\n where\n (aw:bw:xs) = words input\n raw = reverse aw\n rbw = reverse bw\n\n go:: String -> String -> Int\n go [] [] = 0\n go (ca:xa) [] = if ca /= '0' then\n 1\n else\n go xa []\n go [] (cb:xb) = if cb /= '0' then\n -1\n else\n go [] xb\n\n go (ca:xa) (cb:xb) = \n if ca == cb then\n go xa xb\n else if ca > cb then\n 1\n else \n -1\n\n answer = case (go raw rbw)\n of 0 -> \"=\"\n 1 -> \">\"\n -1 -> \"<\"\n"}], "src_uid": "fd63aeefba89bef7d16212a0d9e756cd"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n-- myShow = show :: Int -> String \nmain = do\n _ <- C.getLine\n xs <- C.getLine\n print $ solve xs\n\nsolve :: C.ByteString -> Integer\nsolve = product . map ((\\(Just x) -> fst x) . C.readInteger) . C.words\n", "positive_code": [{"source_code": "main = interact $ solve \"\" \"1\" . tail . words\nsolve zero fail [] = fail ++ zero\nsolve _ \"0\" _ = \"0\"\nsolve zero fail ((h:t):xs) = if h == '1' && all (== '0') t then solve (t ++ zero) fail xs else solve zero (h:t) xs\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n _ <- C.getLine\n xs <- map ((\\(Just x) -> fst x) . C.readInteger) . C.words <$> C.getLine\n putStrLn $ show $ product xs\n"}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetStrings :: IO [String]\ngetStrings = tail . words <$> getContents\n\nisBeautiful :: String -> Bool\nisBeautiful (c:cs) = c == '1' && and [x == '0' | x <- cs]\n\nsolve :: [String] -> String\nsolve ss = if any (== \"0\") ss then \"0\" else r\n where\n start = case find (not . isBeautiful) ss of\n Just s -> s\n Nothing -> \"1\"\n end = replicate (sum [length s - 1 | s <- filter isBeautiful ss]) '0'\n r = start ++ end\n\nmain :: IO ()\nmain = getStrings >>= putStrLn . solve\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nmain = B.getLine >> (B.putStr . B.pack .show . product . map (fst. fromJust . B.readInteger) . B.words =<< B.getLine)"}], "negative_code": [{"source_code": "main = interact $ solve \"\" \"\" . tail . words\nsolve zero fail [] = fail ++ zero\nsolve _ \"0\" _ = \"0\"\nsolve zero fail ((h:t):xs) = if h == '1' && all (== '0') t then solve (t ++ zero) fail xs else solve zero (h:t) xs\n"}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetStrings :: IO [String]\ngetStrings = tail . words <$> getContents\n\nisBeautiful :: String -> Bool\nisBeautiful (c:cs) = c == '1' && and [x == '0' | x <- cs]\n\nsolve :: [String] -> String\nsolve ss = start ++ end\n where\n start = case find (not . isBeautiful) ss of\n Just s -> s\n Nothing -> \"1\"\n end = replicate (sum [length s - 1 | s <- filter isBeautiful ss]) '0'\n\nmain :: IO ()\nmain = getStrings >>= putStrLn . solve\n"}, {"source_code": "import Data.Functor\n\ngetInts :: IO [Integer]\ngetInts = map read . words . tail <$> getContents\n\nmain :: IO ()\nmain = getInts >>= putStrLn . show . product\n"}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetStrings :: IO [String]\ngetStrings = tail . words <$> getContents\n\nisBeautiful :: String -> Bool\nisBeautiful (c:cs) = c == '1' && and [x == '0' | x <- cs]\n\nsolve :: [String] -> String\nsolve ss = if head r == '0' then \"0\" else r\n where\n start = case find (not . isBeautiful) ss of\n Just s -> s\n Nothing -> \"1\"\n end = replicate (sum [length s - 1 | s <- filter isBeautiful ss]) '0'\n r = start ++ end\n\nmain :: IO ()\nmain = getStrings >>= putStrLn . solve\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- (map (\\s -> read s::Int) . words) <$> getLine\n putStrLn $ show $ foldr (\\x acc -> acc * x) 1 xs\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- (map (\\s -> read s::Int) . words) <$> getLine\n -- putStrLn $ show $ foldr (\\x acc -> acc * x) 1 xs\n putStrLn $ show $ product xs\n"}], "src_uid": "9b1b082319d045cf0ec6d124f97a8184"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain = do\n [n,m] <- map read.words <$> getLine\n arr <- listArray(0,n-1).map readInt.B.words <$> B.getLine\n abcs <- map readInt.B.words <$> B.getContents\n print $ solve arr abcs\n\nsolve :: UArray Int Int -> [Int] -> Double\nsolve arr abcs = go 0.0 abcs\n where\n go !acc (a:b:c:abcs) = go (max acc $ v / e) abcs\n where\n v = fromIntegral . sum $ map (unsafeAt arr.subtract 1) [a,b]\n e = fromIntegral c\n go acc _ = acc", "positive_code": [{"source_code": "{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}\n\nimport Data.List (foldl')\nimport Control.Applicative ((<$>))\nimport Data.Array (Array, listArray, (!))\nimport Control.Monad (replicateM, sequence)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as ByteString\nimport qualified Data.ByteString.Char8 as Char8\n\n-- parse :: Read a => String -> [a]\n-- parse = map read . words\n\ngetLine' :: IO ByteString\ngetLine' = ByteString.getLine\n\nparse :: ByteString -> [Int]\nparse line =\n case out of Just xs -> xs\n Nothing -> []\n where\n out = sequence . map read' . Char8.words $ line :: Maybe [Int]\n read' :: ByteString -> Maybe Int\n read' = (fst <$>) . Char8.readInt\n\nsolve :: Array Int Int -> [[Int]] -> Double\nsolve a = foldl' max 0 . map den\n where\n den :: [Int] -> Double\n den [i, j, w] = fromIntegral (a ! i + a ! j) / fromIntegral w\n den _ = error \"fail!\"\n\nmain :: IO ()\nmain = do\n [n, m] <- map read . words <$> getLine\n a <- listArray (1, n) . parse <$> getLine'\n e <- map parse <$> replicateM m getLine'\n print $ solve a e\n"}], "negative_code": [], "src_uid": "ba4304e79d85d13c12233bcbcce6d0a6"} {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\ndata Ops = Take Integer | Carrier Integer deriving (Eq, Ord, Show, Read)\n\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n let g ('+':' ':r) = Carrier (read r)\n g ('-':' ':r) = Take (read r)\n fmap g getLine\n \n let (a, b) = solve inp x\n putStrLn $ show a ++ \" \" ++ show b\n \n\nsolve :: [Ops] -> Integer -> (Integer, Integer)\nsolve ops x = (numLeft, numDistressed)\n where\n (numLeft, numDistressed) = foldl f (x, 0) ops\n f (n, d) (Carrier c) = (n+c, d)\n f (n, d) (Take m) | n >= m = (n-m, d)\n | otherwise = (n, d+1)\n\ninp = [Carrier 5,\n Take 10,\n Take 20,\n Carrier 40,\n Take 20]\n", "positive_code": [{"source_code": "getInput :: Integer -> IO [(String, Integer)]\ngetInput 0 = return []\ngetInput n = do \n inpStr <- getLine \n let w = words inpStr\n let vals = (w !! 0, read $ w !! 1 :: Integer)\n rest <- getInput (n - 1)\n return (vals : rest)\n\nprocess' :: Integer -> [(String, Integer)] -> (Integer, Integer)\nprocess' n [] = (n, 0)\nprocess' n ((\"+\",x):xs) = process' (n + x) xs\nprocess' n ((\"-\",x):xs) | n >= x = process' (n - x) xs\n | n < x = (a, b + 1)\n where (a, b) = process' n xs\n\nmain :: IO ()\nmain = do\n inpStr <- getLine\n let w = words inpStr\n let (n, x) = (read $ w !! 0 :: Integer, read $ w !! 1 :: Integer)\n allInp <- getInput n\n let (a, b) = process' x allInp\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "getInput :: Integer -> IO [(String, Integer)]\ngetInput 0 = return []\ngetInput n = do \n inpStr <- getLine \n let w = words inpStr\n let vals = (w !! 0, read $ w !! 1 :: Integer)\n rest <- getInput (n - 1)\n return (vals : rest)\n\nprocess :: Integer -> [(String, Integer)] -> (Integer, Integer)\nprocess n [] = (n, 0)\nprocess n ((op,x):xs) = case op of\n \"+\" -> process (n + x) xs\n \"-\" -> process1 n x xs\n where process1 n x xs | n >= x = process (n - x) xs\n | n < x = (a, b + 1)\n where (a, b) = process n xs\n\n\nmain :: IO ()\nmain = do\n inpStr <- getLine\n let w = words inpStr\n let (n, x) = (read $ w !! 0 :: Integer, read $ w !! 1 :: Integer)\n allInp <- getInput n\n let (a, b) = process x allInp\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n \nmain = do\n [n, x] <- map read . words <$> getLine\n [ss, ds] <- transpose . map words <$> replicateM n getLine\n let ans = solve (fromIntegral x) 0 ss (map read ds)\n putStrLn $ show (ans !! 0) ++ \" \" ++ show (ans !! 1)\n \nsolve :: Integer -> Integer -> [String] -> [Integer] -> [Integer]\nsolve x y [] [] = [x, y]\nsolve x y (s:ss) (d:ds)\n | s == \"+\" = solve (x + d) y ss ds\n | s == \"-\" && d <= x = solve (x - d) y ss ds\n | otherwise = solve x (y + 1) ss ds\n \n\n"}, {"source_code": "main = do\n n:[x] <- return . map read . words =<< getLine\n let dataread = do\n\t flag:[amountstr] <- return . words =<< getLine\n\t return (flag==\"+\", read amountstr)\n\tdataread::IO (Bool, Integer)\n (i,d) <- return . (foldl f (x::Integer,0)) =<< sequence (take (fromIntegral n) $ repeat dataread)\n putStr $ (show i)++\" \"++show d\n\twhere\n\t f (ice, distress) (f,amo) =\n\t\tcase f\tof\n\t\tTrue\t-> (ice+amo, distress)\n\t\tFalse\t-> if ice >= amo\n\t\t\t then (ice-amo, distress) \n\t\t\t else (ice, succ distress)\n\n"}, {"source_code": "solve :: [String] -> String\nsolve (l:ls) = case foldl parser (m, 0) ls of (x, y) -> (show x) ++ \" \" ++ (show y)\n where [_,m] = map read (words l)\nparser :: (Integer, Integer) -> String -> (Integer, Integer)\nparser (i,d) (c:' ':str) = \n let k = read str in case c of\n '+' -> (i + k, d)\n '-' -> if k > i then (i, d + 1) else (i - k, d)\nmain = putStrLn.solve.lines =<< getContents"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nprocess::(Integer,Integer)->Integer->(Integer,Integer)\nprocess (a,c) d | d>0 = (a+d,c)\n | d<0 && a+d<0= (a,c+1)\n\t\t| otherwise = (a+d,c)\n\ntr '+' = ' '\ntr x = x\n\n\nmain = do\n\t\t[n,x]<- map read <$> words <$> getLine::IO [Integer]\n\t\ty1<-map (\\z-> [head z]++ (drop 2 z)) <$>lines <$> getContents\n\t\tlet y2= map (map tr) y1\n\t\tlet y= map read y2 ::[Integer]\n let (a,c) = foldl process (x,0) y\n\t\tputStr $ show a\n\t\tputStr \" \"\n\t\tputStrLn $ show c\n"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad.State\nimport Control.Arrow\n\n\nrunCommand :: (String, Integer) -> State (Integer, Integer) ()\nrunCommand (\"+\", n) = modify $ first (+n)\nrunCommand (\"-\", n) = do\n x <- fst <$> get\n if x >= n\n then modify $ first (+ (-n))\n else modify $ second (+1)\n\ngetCommand :: IO (String, Integer)\ngetCommand = do\n [a, b] <- words <$> getLine\n return $ (a, read b)\n\nmain = do\n [n, x] <- map read . words <$> getLine\n commands <- replicateM n getCommand\n let (a, b) = execState (mapM_ runCommand commands) (fromIntegral x, 0)\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "process :: Integer -> [(Char, Integer)] -> (Integer, Integer)\nprocess x fs = foldl f (x,0) fs\n where\n f (x,y) (c,d)\n | c == '-' = if x < d then (x,y+1) else (x-d,y)\n | otherwise = (x+d,y)\n\nreadInt :: String -> Integer\nreadInt = read\n\nprocessLine :: String -> (Char, Integer)\nprocessLine line = (char,d)\n where\n [char:_,dStr] = words line\n d = read dStr\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n,x] = map readInt (words line)\n fs <- fmap (map processLine.lines) getContents\n let (x',y') = process x fs\n putStrLn $ show x' ++ \" \" ++ show y'"}, {"source_code": "myShow :: (Integer, Integer) -> String\nmyShow (a, b) = show a ++ \" \" ++ show b\n\nsimulate :: [[String]] -> Integer -> Integer -> (Integer, Integer)\nsimulate [] x k = (x, k)\nsimulate ([\"+\", am]:rest) x k = simulate rest (x + read am) k\nsimulate ([\"-\", am]:rest) x k\n | read am <= x = simulate rest (x - read am) k\n | otherwise = simulate rest x (k + 1)\n\nsolve :: String -> String\nsolve str =\n let (h:b) = lines str\n [n, x] = map read . words $ h\n queue = map words $ take (fromIntegral n) b\n in myShow $ simulate queue x 0\n\nmain :: IO()\nmain = interact solve"}, {"source_code": "main :: IO()\nmain = putStrLn . unwords . map show . solve . tail . words =<< getContents\n\nsolve :: [String] -> [Integer]\nsolve (xs:cs) = solve' (read xs) 0 cs\n\nsolve' :: Integer -> Integer -> [String] -> [Integer]\nsolve' x c [] = [x, c]\nsolve' x c (o:ds:s) | o == \"+\" = solve' (x + read ds) c s\n | otherwise = let d = read ds\n in if x >= d\n then solve' (x - d) c s\n else solve' x (c + 1) s\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n ls <- replicateM n $ (\\[a, b] -> (head a, read b)) . words <$> getLine\n\n let\n (c, s) = f (0, fromIntegral x) ls :: (Int, Int64)\n where\n f (c, s) [] = (c, s)\n f (c, s) (('+', d):xs) = f (c, s+d) xs\n f (c, s) (('-', d):xs)\n | s >= d = f (c, s-d) xs\n | otherwise = f (c+1, s) xs\n\n putStrLn $ show s ++ \" \" ++ show c\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\ndata Ops = Take Integer | Carrier Integer deriving (Eq, Ord, Show, Read)\n\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n let g ('+':' ':r) = Carrier (read r)\n g ('-':' ':r) = Take (read r)\n fmap g getLine\n \n let (a, b) = solve inp x\n putStrLn $ show a ++ \" \" ++ show b\n \n\nsolve :: [Ops] -> Integer -> (Integer, Integer)\nsolve ops x = res\n where\n res = foldl f (x, 0) ops\n where\n f (x, y) (Carrier d) = (x + d, y)\n f (x, y) (Take d) | x < d = (x, y+1)\n | otherwise = (x - d, y)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\ntype Result = [Integer]\n\nsolve :: Int -> [Int] -> Result\nsolve x = foldl' deal_with [fromIntegral x, 0] . map fromIntegral\n where deal_with [left, distressed] num\n | left + num >= 0 = [left + num, distressed]\n | otherwise = [left, distressed + 1]\n\nprocess :: State Reader Result\nprocess = do\n [n, x] <- parse\n ds <- replicateM n $ scan . B.filter (/=' ') <$> parse\n return $ solve x ds\n\nmain :: IO ()\nmain = do\n args <- getArgs\n reader <- if not (null args) && head args == \"MINE\"\n then B.lines <$> (openFile \"input.txt\" ReadMode >>= B.hGetContents)\n else B.lines <$> B.getContents\n say $ evalState process reader\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int where\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString where\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Integer\n\ninstance Display Double\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInteger x\nsomeFunc::IO()\nsomeFunc = C.getLine >>= \\ns-> let [n,x] =map rIn $ C.words ns in solve.((:) x)=<rIn.C.filter (/=' ')<$>C.getLine)\nsolve (x:xs) =(\\(t1,t2)->putStr (show t1 ++\" \"++show t2)) $ foldl (\\(b1,b2) a->if b1+a<0 then (b1,b2+1) else (b1+a,b2)) (x,0) xs"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = \n (map read . words <$> getLine :: IO [Integer]) >>=\n \\[n, x] -> step n x 0\n\nstep :: Integer -> Integer -> Integer -> IO ()\nstep 0 x d =\n putStrLn (show x ++ \" \" ++ show d)\n\nstep n x d =\n words <$> getLine >>= \n \\[c, s] ->\n let \n r = (read s :: Integer)\n in\n if c == \"+\" then\n step (n - 1) (x + r) d\n\n else if x >= r then\n step (n - 1) (x - r) d\n\n else\n step (n - 1) x (d + 1)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\n-- solve 5 7 [('+', 5), ('-', 10), ('-', 20), ('+', 40), ('-', 20)]\n-- solve 5 17 [('-', 16), ('-', 2), ('-', 98), ('+', 100), ('-', 98)]\n\nsolve :: Integer -> [(Char, Integer)] -> (Integer, Integer)\nsolve x ops = foldl' updateState (x, 0) ops\n where updateState (total, sads) ('+', amount) = (total + amount, sads)\n updateState (total, sads) ('-', amount) = \n if amount > total\n then (total, sads + 1)\n else (total - amount, sads)\n\nparseOps :: String -> (Char, Integer)\nparseOps s = let [[op], amount] = words s\n in (op, read amount)\n\nparseNx :: String -> (Int, Integer)\nparseNx s = let [n, x] = words s\n in (read n, read x)\n\nmain = do (n, x) <- fmap parseNx getLine\n ops <- replicateM n (fmap parseOps getLine)\n let (total, sads) = solve x ops\n putStr $ show total\n putStr \" \"\n putStrLn $ show sads\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n-- import Debug.Trace(trace)\n\ntrace x y = y\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = (show final_val)++\" \"++(show distress)\n where\n n_s:x_s:as_w = words input\n n::Int64\n n = read n_s\n x::Int64\n x = read x_s\n\n entries = parseInput as_w\n\n (distress, final_val) = foldl' foldOp (0,x) entries\n\nparseInput::[String] -> [(String, Int64)]\nparseInput [] = []\nparseInput (x:y:xs) = trace (\"x is \"++x++\" Y is \"++y) (x, read y):parseInput(xs)\n\nfoldOp::(Int64, Int64) -> (String, Int64) -> (Int64, Int64)\nfoldOp (distress, current) (op, ice_cream) \n | op == \"+\" = (distress, current+ice_cream)\n | current >= ice_cream = (distress, current-ice_cream)\n | otherwise = (distress+1, current)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\nprocess::Integer->Integer->[[String]]->String\nprocess x n [] = (show x) ++ \" \" ++ (show n)\nprocess x n ((a:b:[]):cs) | a==\"+\" = process (x+bb) n cs\n | bb<= x = process (x-bb) n cs\n | otherwise = process x (n+1) cs\n where bb = read b ::Integer\n\n\nmain = do\n [a,b]<-map read <$> words <$> getLine ::IO [Integer]\n d<- map words <$> lines <$> getContents ::IO [[String]]\n putStrLn $ process b 0 d\n"}, {"source_code": "main = do\n [n,x] <- map read . words <$> getLine\n (x',d) <- foldl process (x,0) . map words . lines <$> getContents\n putStrLn $ show x' ++ \" \" ++ show d\nprocess (x,d) [\"+\",y] = (x + read y,d)\nprocess (x,d) [\"-\",y] | x >= read y = (x - read y,d)\n | otherwise = (x,d+1)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n ls <- replicateM n $ (\\[a, b] -> (head a, read b)) . words <$> getLine\n\n let\n (c, s) = f (0, x) ls\n where\n f (c, s) [] = (c, s)\n f (c, s) (('+', d):xs) = f (c, s+d) xs\n f (c, s) (('-', d):xs)\n | s >= d = f (c, s-d) xs\n | otherwise = f (c+1, s) xs\n\n putStrLn $ show s ++ \" \" ++ show c\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\ndata Ops = Take Int | Carrier Int deriving (Eq, Ord, Show, Read)\n\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n let g ('+':' ':r) = Carrier (read r)\n g ('-':' ':r) = Take (read r)\n fmap g getLine\n \n let (a, b) = solve inp x\n putStrLn $ show a ++ \" \" ++ show b\n \n\nsolve :: [Ops] -> Int -> (Int, Int)\nsolve ops x = res\n where\n res = foldl f (x, 0) ops\n where\n f (x, y) (Carrier d) = (x + d, y)\n f (x, y) (Take d) | x < d = (x, y+1)\n | otherwise = (x - d, y)\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\ndata Ops = Take Int | Carrier Int deriving (Eq, Ord, Show, Read)\n\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n let g ('+':' ':r) = Carrier (read r)\n g ('-':' ':r) = Take (read r)\n fmap g getLine\n \n let (a, b) = solve inp x\n putStrLn $ show a ++ \" \" ++ show b\n \n\nsolve :: [Ops] -> Int -> (Int, Int)\nsolve ops x = res\n where\n res = foldl f (x, 0) ops\n where\n f (x, y) (Carrier d) = (x + d, y)\n f (x, y) (Take d) | x < d = (x, y+1)\n | otherwise = (x - d, y)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\ntype Result = [Int]\n\nsolve :: Int -> [Int] -> Result\nsolve x = foldl' deal_with [x, 0]\n where deal_with [left, distressed] num\n | left + num >= 0 = [left + num, distressed]\n | otherwise = [left, distressed + 1]\n\nprocess :: State Reader Result\nprocess = do\n [n, x] <- parse\n ds <- replicateM n $ scan . B.filter (/=' ') <$> parse\n return $ solve x ds\n\nmain :: IO ()\nmain = do\n args <- getArgs\n reader <- if not (null args) && head args == \"MINE\"\n then B.lines <$> (openFile \"input.txt\" ReadMode >>= B.hGetContents)\n else B.lines <$> B.getContents\n say $ evalState process reader\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass Display a => EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int where\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map scan . B.words $ line, rest)\n\ninstance EIO BString where\n\nclass (Read a, Show a) => Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display Double\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = \n (map read . words <$> getLine :: IO [Int]) >>=\n \\[n, x] -> step n x 0\n\nstep :: Int -> Int -> Int -> IO ()\nstep 0 x d =\n putStrLn (show x ++ \" \" ++ show d)\n\nstep n x d =\n words <$> getLine >>= \n \\[c, s] ->\n let \n r = (read s :: Int)\n in\n if c == \"+\" then\n step (n - 1) (x + r) d\n\n else if x >= r then\n step (n - 1) (x - r) d\n\n else\n step (n - 1) x (d + 1)\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n-- import Debug.Trace(trace)\n\ntrace x y = y\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = (show final_val)++\" \"++(show distress)\n where\n n_s:x_s:as_w = words input\n n::Int\n n = read n_s\n x::Int\n x = read x_s\n\n entries = parseInput as_w\n\n (distress, final_val) = foldl' foldOp (0,x) entries\n\nparseInput::[String] -> [(String, Int)]\nparseInput [] = []\nparseInput (x:y:xs) = trace (\"x is \"++x++\" Y is \"++y) (x, read y):parseInput(xs)\n\nfoldOp::(Int, Int) -> (String, Int) -> (Int, Int)\nfoldOp (distress, current) (op, ice_cream) \n | op == \"+\" = (distress, current+ice_cream)\n | current >= ice_cream = (distress, current-ice_cream)\n | otherwise = (distress+1, current)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\nprocess::Int->Int->[[String]]->String\nprocess x n [] = (show x) ++ \" \" ++ (show n)\nprocess x n ((a:b:[]):cs) | a==\"+\" = process (x+bb) n cs\n | bb<= x = process (x-bb) n cs\n | otherwise = process x (n+1) cs\n where bb = read b ::Int\n\n\nmain = do\n [a,b]<-map read <$> words <$> getLine ::IO [Int]\n d<- map words <$> lines <$> getContents ::IO [[String]]\n putStrLn $ process b 0 d\n"}, {"source_code": "main = do\n n:[x] <- return . map read . words =<< getLine\n let dataread = do\n\t flag:[amountstr] <- return . words =<< getLine\n\t return (flag==\"+\", read amountstr)\n\tdataread::IO (Bool, Int)\n (i,d) <- return . (foldl f (x,0)) =<< sequence (take n $ repeat dataread)\n putStr $ (show i)++\" \"++show d\n\twhere\n\t f (ice, distress) (f,amo) =\n\t\tcase f\tof\n\t\tTrue\t-> (ice+amo, distress)\n\t\tFalse\t-> if ice >= amo\n\t\t\t then (ice-amo, distress) \n\t\t\t else (ice, succ distress)\n\n"}, {"source_code": "solve :: [String] -> String\nsolve (l:ls) = case foldl parser (m, 0) ls of (x, y) -> (show x) ++ \" \" ++ (show y)\n where [_,m] = map read (words l)\nparser :: (Int, Int) -> String -> (Int, Int)\nparser (i,d) (c:' ':str) = \n let k = read str in case c of\n '+' -> (i + k, d)\n '-' -> if k > i then (i, d + 1) else (i - k, d)\nmain = putStrLn.solve.lines =<< getContents"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nprocess (a,c) d | d>0 = (a+d,c)\n | d<0 && a+d<0= (a,c+1)\n\t\t| otherwise = (a+d,c)\n\ntr '+' = ' '\ntr x = x\n\n\nmain = do\n\t\t[n,x]<- map read <$> words <$> getLine::IO [Int]\n\t\ty1<-map (\\z-> [head z]++ (drop 2 z)) <$>lines <$> getContents\n\t\tlet y2= map (map tr) y1\n\t\tlet y= map read y2 ::[Int]\n let (a,c) = foldl process (x,0) y\n\t\tputStr $ show a\n\t\tputStr \" \"\n\t\tputStrLn $ show c\n"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad.State\nimport Control.Arrow\n\n\nrunCommand :: (String, Int) -> State (Int, Int) ()\nrunCommand (\"+\", n) = modify $ first (+n)\nrunCommand (\"-\", n) = do\n x <- fst <$> get\n if x >= n\n then modify $ first (+ (-n))\n else modify $ second (+1)\n\ngetCommand :: IO (String, Int)\ngetCommand = do\n [a, b] <- words <$> getLine\n return $ (a, read b)\n\nmain = do\n [n, x] <- map read . words <$> getLine\n commands <- replicateM n getCommand\n let (a, b) = execState (mapM_ runCommand commands) (x, 0)\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "process :: Int -> [(Char, Int)] -> (Int, Int)\nprocess x fs = foldl f (x,0) fs\n where\n f (x,y) (c,d)\n | c == '-' = if x < d then (x,y+1) else (x-d,y)\n | otherwise = (x+d,y)\n\nreadInt :: String -> Int\nreadInt = read\n\nprocessLine :: String -> (Char, Int)\nprocessLine line = (char,d)\n where\n [char:_,dStr] = words line\n d = read dStr\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n,x] = map readInt (words line)\n fs <- fmap (map processLine.lines) getContents\n let (x',y') = process x fs\n putStrLn $ show x' ++ \" \" ++ show y'"}], "src_uid": "0a9ee8cbfa9888caef39b024563b7dcd"} {"source_code": "import Control.Monad\nimport Data.List\n\ndoit :: Int -> Int -> String -> Int\ndoit _ _ [] = 0\ndoit k sz ('*':xs) = doit k 0 xs\ndoit k sz ('.':xs) = doit k (sz + 1) xs + cur\n where cur = if sz + 1 >= k then 1 else 0\n\nmain = do\n [n,m,k] <- fmap (fmap read . words) getLine\n l <- replicateM n getLine\n print $ if k == 1\n then sum . map (length . filter (=='.')) $ l\n else sum . map sum . map (map (doit k 0)) $ [l, transpose l]\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ndoit :: Int -> Int -> String -> Int\ndoit k sz l = length . filter (>= k) $ scanl f 0 l\n where f sz '*' = 0\n f sz '.' = sz + 1\n\nmain = do\n [n,m,k] <- fmap (fmap read . words) getLine\n l <- replicateM n getLine\n print $ if k == 1\n then sum . map (length . filter (=='.')) $ l\n else sum . map sum . map (map (doit k 0)) $ [l, transpose l]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nmain = do\n [n, _, k] <- map read.words <$> getLine\n css <- replicateM n getLine\n print $ solve k css\n\nsolve :: Int -> [String] -> Int\nsolve k css\n | k == 1 = sum $ map step css\n | otherwise = sum (map step css) + sum (map step (transpose css))\n where\n step cs = sum [l - k + 1 | g@('.':_)<-group cs, let !l=length g, l >= k]"}], "negative_code": [], "src_uid": "c1f247150831e9b52389bae697a1ca3d"} {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\n\r\n\r\ntoShow True = \"Bob\"\r\ntoShow False = \"Alice\"\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let od = length . filter odd. map (read::String -> Int) . words $ input\r\n putStrLn .toShow $ odd (div od 2) && even od || odd n && odd (div (od+1) 2)\r\n return ()\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n print . whoWins n\n\ndata Player = Alice | Bob deriving (Eq, Show)\n\nwhoWins :: Int -> [Int] -> Player\nwhoWins n as = let o = foldl (\\acc e -> if (mod e 2 == 0) then acc else acc+1) 0 as\n p x = mod x 2 == 0\n k = div n 2\n m = div o 2\n in\n case (p n, p o) of\n (_, True) -> if (mod m 2 == 0) then Alice else Bob\n (True, False) -> Alice\n (False, False) -> if (mod (m+1) 2 == 0) then Alice else Bob\n\n\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\n\r\n\r\ntoShow True = \"Bob\"\r\ntoShow False = \"Alice\"\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n od = length $ filter odd a\r\n\r\n putStrLn .toShow $ od==2 || (od/=1 || odd n) && odd (div (od+1) 2)\r\n return ()\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\n\r\n\r\ntoShow True = \"Bob\"\r\ntoShow False = \"Alice\"\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n od = length $ filter odd a\r\n\r\n putStrLn .toShow $ od==2 || od==1 && odd n || odd (div (od+1) 2)\r\n return ()\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\n\r\n\r\ntoShow True = \"Bob\"\r\ntoShow False = \"Alice\"\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n od = length $ filter odd a\r\n\r\n putStrLn .toShow $ od==2 || od==1 && odd n || odd n && odd (div (od+1) 2)\r\n return ()\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\n\r\n\r\ntoShow True = \"Bob\"\r\ntoShow False = \"Alice\"\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n od = length $ filter odd a\r\n\r\n putStrLn .toShow $ od==2 || od==1 && odd n\r\n return ()\r\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n print . whoWins n\n\ndata Player = Alice | Bob deriving (Eq, Show)\n\nwhoWins :: Int -> [Int] -> Player\nwhoWins n as = let o = foldl (\\acc e -> if (mod e 2 == 0) then acc else acc+1) 0 as\n p x = mod x 2 == 0\n k = div n 2\n m = div o 2\n in\n case (p n, p o) of\n (_, True) -> if (mod m 2 == 0) then Alice else Bob\n (True, False) -> Alice\n (False, False) -> if (k > m)\n then Alice\n else if (mod (m+1) 2 == 0) then Alice else Bob\n\n\n"}], "src_uid": "d0c9f2f2037d093762fb87206f396850"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as ST\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nsolve xs = loop st\n where\n st = foldl' (flip ST.insert) ST.empty xs\n loop st\n | ST.null st = 0\n | m == 0 = 1 + loop (ST.insert d st')\n | otherwise = loop st'\n where\n m = a `mod` 2\n d = a `div` 2\n (a,st') = ST.deleteFindMax st\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n n <- readLn :: IO Int\n xs <- map read . words <$> getLine :: IO [Int]\n print $ solve xs\n", "positive_code": [{"source_code": "import qualified Data.Set as Set\nimport Control.Monad\n\nsolve :: Set.Set Int -> Int -- only for even elements\nsolve s\n |Set.null s = 0\n |otherwise = if odd m2 then 1 + solve s' else 1 + solve (Set.insert m2 s')\n where\n m = Set.findMax s\n m2 = m `div` 2\n s' = Set.delete m s\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n l <-(filter even . map read . words) <$> getLine\n print $ solve $ Set.fromList l\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as ST\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nsolve xs = loop st\n where\n st = foldl' (flip ST.insert) ST.empty xs\n loop st\n | ST.null st = 0\n | m == 0 = 1 + loop (ST.insert d st')\n | otherwise = loop st'\n where\n m = a `mod` 2\n d = a `div` 2\n (a,st') = ST.deleteFindMax st\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n n <- readLn :: IO Int\n xs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]\n print $ solve xs\n"}, {"source_code": "{-# LANGUAGE Strict #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as MP\nimport Data.Array\nimport Data.Maybe\nimport Data.Maybe\nimport Control.Monad\n\ncount :: MP.Map Int Int -> Int -> Int -> MP.Map Int Int\ncount mp x acc = \n case MP.lookup k mp of\n Just _ -> MP.adjust (max v) k mp\n Nothing -> MP.insert k v mp\n where\n (k,v) = loop x (0,0)\n loop a (k,v)\n | m == 1 = (d,v)\n | otherwise = loop d (k,v+1)\n where\n d = a `div` 2 \n m = a `mod` 2\n\nsolve arr n = MP.foldl (+) 0 mp\n where\n mp = loop 0 MP.empty\n loop i m\n | i > n = m\n | otherwise = \n let\n v = arr ! i\n m' = count m v 0\n in\n loop (i+1) m'\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n n <- readLn :: IO Int\n arr <- listArray (0, n-1) <$> map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO (Array Int Int)\n print $ solve arr (n-1)\n"}], "src_uid": "afcd41492158e68095b01ff1e88c3dd4"} {"source_code": "import Control.Monad ( replicateM )\n\nmain = do\n n <- readLn\n replicateM n $ do\n getLine\n arr <- fmap (fmap read . words) getLine\n print $ ceiling $ fromIntegral (sum arr) / fromIntegral (length arr)", "positive_code": [{"source_code": "import Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n n <- readLn\n s <- sum . map read . words <$> getLine\n print $ (s + n - 1) `div` n\n"}, {"source_code": "import Control.Monad\nimport Data.Ratio\n\nsolve :: [Int] -> Int\nsolve nums = ceiling (sum nums % length nums)\n\nmain = do\n numQueries <- read <$> getLine\n replicateM numQueries $ do\n _ <- getLine\n prices <- fmap read <$> words <$> getLine\n print $ solve prices\n"}, {"source_code": "module Main where \n\nimport Control.Monad\nimport Data.List\n\ncdiv num den = (num + den - 1) `div` den\navg vals = let l = length vals in cdiv (sum vals) l\n\nmain :: IO ()\nmain = do \n let ri = read::String->Int\n q <- ri <$> getLine\n \n replicateM_ q $ do\n _ <- ri <$> getLine\n vals <- fmap ri . words <$> getLine\n\n print $ avg vals\n return ()\n return ()\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase= do\n\t r<-read <$>getLine ::IO Int\t\n\t a<-sum <$> map read <$> words <$> getLine::IO Int\n let ans = div a r+ if mod a r>0 then 1 else 0\n\t print ans\n\t\n\nmain::IO ()\nmain=do\n t<- read <$> getLine ::IO Int\n replicateM_ t onecase\n"}, {"source_code": "import Control.Monad\ndivUp a b\n\t| a `mod` b == 0 = a `div` b\n\t| otherwise = (a `div` b) + 1\n\ndoQuery = do\n\tnStr <- getLine\n\tlistStr <- getLine\n\tlet ans = (sum $ map read $ words listStr) `divUp` (read nStr)\n\tputStrLn $ show ans\n\nmain = do\n\tq <- getLine\n\treplicateM_ (read q) doQuery\n"}, {"source_code": "handle = do\n\tline <- getLine\n\tl2 <- getLine\n\tlet n = read line :: Int\n\tlet ar = map read (words l2) :: [Int]\n\tlet s = sum ar\n\tlet res = (s+n-1) `div` n\n\tputStrLn (show res)\n\nhandleCase 0 = return ()\nhandleCase n = do\n\thandle\n\thandleCase (n-1)\n\t\n\nmain = do\n\tlineq <- getLine\n\tlet q = (read lineq :: Int)\n\thandleCase q\n\t{-\n\tline2 <- getLine\n\tlet n = (read line :: Int)\n\tlet x = n+1\n\tlet s = show x\n\tlet z = words line2\n\tlet ar = map read z :: [Int]\n\tlet s2 = map (show . (+ 1)) ar\n\tputStrLn s\n\tputStrLn (concat s2) -}\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Control.Arrow ((>>>))\nmain :: IO ()\nmain = do\n q <- read <$> getLine ::IO Int\n replicateM_ q solve\nsolve :: IO()\nsolve = do\n n <- read <$> getLine :: IO Int\n xs <- (words >>> map read) <$> getLine\n print $ ceiling $ fromIntegral (sum xs) / fromIntegral n\n\n"}], "negative_code": [{"source_code": "import Control.Monad ( replicateM )\n\nmain = do\n n <- readLn\n replicateM n $ do\n getLine\n arr <- fmap (fmap read . words) getLine\n print $ sum arr `div` length arr\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase= do\n\t r<-read <$>getLine ::IO Int\t\n\t a<-sum <$> map read <$> words <$> getLine::IO Int\n let ans = 1+ div a r\n\t print ans\n\t\n\nmain::IO ()\nmain=do\n t<- read <$> getLine ::IO Int\n replicateM_ t onecase\n"}], "src_uid": "c457b77b16d94c6c4c95b7403a1dd0c7"} {"source_code": "solv :: [Integer] -> Bool\nsolv l = let s = sum l in\n let mx = maximum l in\n (mod s 2 == 0) && (mx <= (div s 2))\n\nmain = do\n l <- getLine\n let n = (read l) :: Int\n inp <- getLine\n let inn = map read $ words inp\n let res = solv inn\n putStrLn $ if res then \"YES\" else \"NO\" \n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.String\nreadListRec :: Integer -> IO [String]\nreadListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n\nparseLineToInt :: String -> [Integer]\nparseLineToInt data_s = do\n (read::String->Integer) <$> (words data_s) \n\ncountLetters :: [Char] -> Char -> Int\ncountLetters array_ char_ = length (filter (==char_) array_)\n\nscoreCount :: [String] -> Int -> [Int]\nscoreCount answList questionNumber =\n if (0 == length (answList!!0))\n then []\n else do\n let currentAnswer = (!!0) <$> answList\n let restAnswers = (drop 1) <$> answList\n let answers = ['A','B','C','D','E']\n let maxScore = maximum ((countLetters currentAnswer) <$> answers)\n maxScore : scoreCount restAnswers (questionNumber + 1)\n\nmyDot :: [Int] -> [Int] -> Int\nmyDot x y = sum (zipWith (*) x y)\n\nmain = do\n getLine\n dataInts <- getLine\n let array_ = parseLineToInt dataInts\n let sum_ = sum array_\n let max_ = maximum array_\n if ((mod sum_ 2 == 0) &&((2 * max_) <= sum_)) \n then putStrLn $ \"YES\"\n else putStrLn $ \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain::IO()\nmain = do\n n <- getLine\n a <- map read . words <$> getLine\n let suma = foldl (+) 0 a\n let maxa = maximum a\n if suma `rem` 2 == 1\n then putStrLn \"NO\"\n else if suma `div` 2 < maxa\n then putStrLn \"NO\"\n else putStrLn \"YES\"\n"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine \n num <- getLine\n let nums = (read :: String -> Integer) <$> words num\n let sum_ = sum nums\n let max_ = maximum nums\n if (mod sum_ 2 == 0) && ((2 * max_) <= sum_)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}, {"source_code": " import Control.Monad\n import Data.String\n readListRec :: Integer -> IO [String]\n readListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n \n parseLineToInt :: String -> [Integer]\n parseLineToInt data_s = do\n (read::String->Integer) <$> (words data_s) \n \n countLetters :: [Char] -> Char -> Int\n countLetters array_ char_ = length (filter (==char_) array_)\n \n scoreCount :: [String] -> Int -> [Int]\n scoreCount answList questionNumber =\n if (0 == length (answList!!0))\n then []\n else do\n let currentAnswer = (!!0) <$> answList\n let restAnswers = (drop 1) <$> answList\n let answers = ['A','B','C','D','E']\n let maxScore = maximum ((countLetters currentAnswer) <$> answers)\n maxScore : scoreCount restAnswers (questionNumber + 1)\n \n myDot :: [Int] -> [Int] -> Int\n myDot x y = sum (zipWith (*) x y)\n \n main = do\n getLine\n dataInts <- getLine\n let array_ = parseLineToInt dataInts\n let sum_ = sum array_\n let max_ = maximum array_\n if ((mod sum_ 2 == 0) &&((2 * max_) <= sum_)) \n then putStrLn $ \"YES\"\n else putStrLn $ \"NO\""}], "negative_code": [{"source_code": "main :: IO ()\nmain = do\n _ <- getLine \n num <- getLine\n let nums = (read :: String -> Int) <$> words num\n if ( (== 0) $ mod (sum nums) 2) && ((2*) $ maximum nums) <= sum nums\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine \n num <- getLine\n let nums = (read :: String -> Int) <$> words num\n if ( (== 0) $ mod (sum nums) 2) && maximum nums <= sum nums\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine \n num <- getLine\n let nums = (read :: String -> Int) <$> words num\n let sum_ = sum nums\n let max_ = maximum nums\n if (mod sum_ 2 == 0) && ((2 * max_) <= sum_)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine \n num <- getLine\n let nums = (read :: String -> Int) <$> words num\n let sum_ = sum nums\n let max_ = maximum nums\n if (sum_ `mod` 2 == 0) && (2 * max_ <= sum nums)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine \n num <- getLine\n let nums = (read :: String -> Int) <$> words num\n if ( (== 0) $ mod (sum nums) 2) && maximum nums <= sum nums\n then print \"YES\"\n else print \"NO\"\n\n"}, {"source_code": "import Control.Monad\nimport Data.String\nreadListRec :: Int -> IO [String]\nreadListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n\nparseLineToInt :: String -> [Int]\nparseLineToInt data_s = do\n (read::String->Int) <$> (words data_s) \n\ncountLetters :: [Char] -> Char -> Int\ncountLetters array_ char_ = length (filter (==char_) array_)\n\nscoreCount :: [String] -> Int -> [Int]\nscoreCount answList questionNumber =\n if (0 == length (answList!!0))\n then []\n else do\n let currentAnswer = (!!0) <$> answList\n let restAnswers = (drop 1) <$> answList\n let answers = ['A','B','C','D','E']\n let maxScore = maximum ((countLetters currentAnswer) <$> answers)\n maxScore : scoreCount restAnswers (questionNumber + 1)\n\nmyDot :: [Int] -> [Int] -> Int\nmyDot x y = sum (zipWith (*) x y)\n\nmain = do\n getLine\n dataInts <- getLine\n let array_ = parseLineToInt dataInts\n let sum_ = sum array_\n let max_ = maximum array_\n if ((mod sum_ 2 == 0) &&((2 * max_) <= sum_)) \n then putStrLn $ \"YES\"\n else putStrLn $ \"NO\"\n"}, {"source_code": "solv :: [Int] -> Bool\nsolv l = let s = sum l in\n let mx = maximum l in\n (mod s 2 == 0) && (mx <= (div s 2))\n\nmain = do\n l <- getLine\n let n = (read l) :: Int\n inp <- getLine\n let inn = map read $ words inp\n let res = solv inn\n putStrLn $ if res then \"YES\" else \"NO\" \n"}], "src_uid": "52f4f2a48063c9d0e412a5f78c873e6f"} {"source_code": "main=interact$f.map read.words\nf[1,1]=\"a\"\nf[n,k]|n B.getLine\n\nmain = do\n [n, k] <- getInts\n\n let\n r\n | n < k = Nothing\n | k == 1 = if n == 1 then Just \"a\" else Nothing\n | otherwise = Just $ (take (n-(k-2)) $ concat $ repeat \"ab\") ++ take (k-2) ['c'..]\n\n putStrLn $ case r of\n Nothing -> show (-1)\n Just k -> k\n"}, {"source_code": "s[1,1]=\"a\"\ns[n,1]=\"-1\"\ns[n,k]|n IO [a]\ngetNums = map read . words <$> getLine\n\n-- | templ\n\nmain :: IO ()\nmain = do\n [n, k] <- getNums\n case () of\n _ | n < k || (k == 1 && n > 1) -> print (-1)\n | even (n-k) -> putStrLn $ concat [\"a\", concat (replicate ((n-k)`div`2) \"ba\"), take (k-1) ['b'..]]\n | otherwise -> putStrLn $ concat [\"a\", concat (replicate ((n-k+1)`div`2) \"ba\"), take (k-2) ['c'..]]\n"}, {"source_code": "import Data.Char\nf a b | b > a || (b == 1 && a > 1) = \"-1\"\n | b == 1 && a == 1 = \"a\"\n | otherwise = (concat $ replicate delta \"ab\") ++ s' ++ ['c'..maxLet]\n where delta = (a - b + 2) `div` 2\n s' = if odd (a - b) then \"a\" else \"\"\n maxLet = chr $ ord 'c' + (b - 3)\nmain = do\n a:b:_ <- fmap (map (read :: String -> Int) . words) getLine\n putStrLn $ f a b\n"}, {"source_code": "main=interact$f.map read.words\nf[1,1]=\"a\"\nf[n,k]|n getLine\n putStrLn $ solve n k\n\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\nsolve :: Int -> Int -> String\nsolve 1 1 = \"a\"\nsolve 1 n = \"-1\"\nsolve n 1 = \"-1\"\nsolve n 2 = take n (cycle \"ab\")\nsolve n k | k > n = \"-1\"\n | even (n-k) = take (n-k) (cycle \"ab\") ++ take k alphabet\n | otherwise = take (n-k) (cycle \"ab\") ++ \"ba\" ++ take (k-2) (drop 2 alphabet)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n\nmain = B.interact $ B.pack . go . map readBI . B.words\ngo (n:k:[]) | k == 1 = if n == 1 then \"a\" else \"-1\"\n | n >= k = (take (n-k+2) . cycle $ \"ab\") ++ (take (k-2) ['c'..'z'])\n | otherwise = \"-1\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n\nmain = interact $ go . map read . words\ngo (n:k:[]) | k == 1 = if n == 1 then \"a\" else \"-1\"\n | n >= k = (take (n-k+2) . cycle $ \"ab\") ++ (take (k-2) ['c'..'z'])\n | otherwise = \"-1\"\n"}, {"source_code": "import System.IO\nimport Data.Char(chr)\n\nmain :: IO ()\nmain = interact (handle)\n\nhandle :: String -> String\nhandle str =\n let ints = pair_up $ map (\\x -> read x :: Int) $ take 2 $ words str\n in solve False ints\n \npair_up :: [Int] -> (Int, Int)\npair_up (x:y:_) = (x, y)\npair_up _ = undefined\n\nsolve :: Bool -> (Int, Int) -> String\nsolve False (l,d)\n | l < d = \"-1\"\n | d == 1 && l > 1 = \"-1\"\n | d == 1 && l == 1 = \"a\"\n | l == d = 'a':'b':(make_tail (l-2) (d-2))\n | l == d + 1 = 'a':'b':(make_tail (l-2) (d-2))\n | otherwise = 'a':'b':(solve True (l-2,d))\nsolve True (l,d)\n | l == d = 'a':'b':(make_tail (l-2) (d-2))\n | l == d + 1 = 'a':'b':(make_tail (l-2) (d-2))\n | otherwise = 'a':'b':(solve True (l-2,d))\n\nmake_tail :: Int -> Int -> String\nmake_tail m n\n | m == n + 1 = 'a':(map chr [99..(99+n-1)])\n | m == n = map chr [99..(99+n-1)]\n | otherwise = undefined"}, {"source_code": "main=interact$f.map read.words\nf[1,1]=\"a\"\nf[n,k]|n B.ByteString\nshowBI = B.pack . show\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n\nmain = B.interact $ B.pack . go . map readBI . B.words\ngo (n:k:[]) | n >= k = (take (n-k+2) . cycle $ \"ab\") ++ (take (k-2) ['c'..'z'])\n | otherwise = \"-1\"\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\ngetNums :: (Read a, Num a) => IO [a]\ngetNums = map read . words <$> getLine\n\n-- | templ\n\nmain :: IO ()\nmain = do\n [n, k] <- getNums\n case () of\n _ | n < k -> print (-1)\n | even (n-k) -> putStrLn $ concat [\"a\", concat (replicate ((n-k)`div`2) \"ba\"), take (k-1) ['b'..]]\n | otherwise -> putStrLn $ concat [\"a\", concat (replicate ((n-k+1)`div`2) \"ba\"), take (k-2) ['c'..]]\n"}], "src_uid": "2f659be28674a81f58f5c587b6a0f465"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, k] <- getInts\n let maxChar = toEnum (fromEnum 'a' + k - 1) :: Char\n func _ [] = []\n func ch (x : xs) = x : ch : func ch xs\n s = concat ['a' : func ch [ch..maxChar] | ch <- ['b'..maxChar]] ++ \"a\"\n t = take n $ 'a' : concat (repeat s)\n C.putStrLn $ C.pack t\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Text.Printf\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Int]\nreadInts = readArray\n\nlyndonCut :: Char -> String -> String\nlyndonCut m [] = []\nlyndonCut m (c:s)\n | c == m = lyndonCut m s\n | otherwise = ((toEnum (fromEnum c + 1)):s)\n\nnextLyndonWord :: Int -> Char -> String -> String\nnextLyndonWord n m s =\n reverse $ lyndonCut m $ reverse $ take n $ concat $ repeat s\n\nlyndonWords :: Int -> Char -> [String]\nlyndonWords n c =\n takeWhile (not . null) $ iterate (nextLyndonWord n c) \"a\"\n\ndeBruijn :: Int -> Char -> String\ndeBruijn n =\n concat . filter (\\a -> n `mod` length a == 0) . lyndonWords n\n\nsolve :: Int -> Int -> String\nsolve n k =\n take n $ concat $ repeat $ deBruijn 2 $ toEnum $ fromEnum 'a' + k - 1\n\nsolveCase :: IO String\nsolveCase = do\n [n, k] <- readInts\n return $ solve n k\n\nmain :: IO ()\nmain = solveCase >>= putStrLn\n\n--solveCase :: IO String\n--solveCase = do\n-- (n:x:[]) <- readInts\n-- fmap (show . solve x) readInts\n--\n--main :: IO ()\n--main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}], "negative_code": [], "src_uid": "19cc504c81bd4f224ecb17f03cfb9bd7"} {"source_code": "main = do\r\n getLine\r\n interact $ unlines . map (show . solve' . words) . lines\r\n\r\nsolve' [x, y] = solve ((read x) :: Integer) ((read y) :: Integer)\r\n\r\nsolve n k = if (mod n 2) == 0\r\n then let a = mod k n in if a == 0 then n else a\r\n else soleven n k\r\n\r\nsoleven n k = let x = mod (apos + r) n in if x == 0 then n else x\r\n where\r\n t = div (n - 1) 2\r\n m = div (k - 1) t\r\n r = k - 1 - m * t\r\n apos = (n + 1) - let a = (mod (m * t) n) in if a == 0 then n else a", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\ntype SIO = StateT P.ByteString IO\n\nsolve :: Int -> Int -> Int\nsolve n k\n | even n = mod k n\n | odd n = let\n per = div n 2\n (x, y) = divMod (k-1) per\n totSteps = x * (per + 1) + y + 1\n in mod totSteps n\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n let\n ans0 = solve n k\n ans = if ans0 == 0 then n else ans0\n putInts [ans]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n let\n result\n | even n = (k - 1) `mod` n + 1\n | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)\n where\n m = n - 1\n p = k - 1\n solve s p\n | p < n `div` 2 = (s + p - 1) `mod` n + 1\n | otherwise = (s + p) `mod` n + 1\n C.putStrLn $ C.pack $ show result\n"}, {"source_code": "main = interact $ unlines.map show.f.map read.tail.words\r\n\r\nf [] = []\r\nf (n:k_:xs) =\r\n let k = k_ - 1; fl = n `div` 2\r\n in ((k + (n `mod` 2) * k `div` fl) `mod` n + 1) : f xs\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE ViewPatterns #-}\r\nmodule Main where\r\n\r\nimport Control.Monad ( replicateM_ )\r\n\r\ncatCycle :: Int -> Int -> Int\r\ncatCycle n (pred -> k) | even n = (k `mod` n) + 1\r\n | otherwise = ((k + step) `mod` n) + 1\r\n where step = k `div` ((n - 1) `div` 2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, k] <- fmap read . words <$> getLine\r\n print $ catCycle n k\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[n, k] <- popIntegers\n return $ bshow (solve n (k - 1))\n\n\nsolve !n !k\n | n `rem` 2 == 0 = k `rem` n + 1\n | otherwise =\n let c = n `quot` 2\n k' = k `rem` (n * c)\n (p, q) = k' `quotRem` c in\n (p * (c + 1) + q) `rem` n + 1\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n let\n result\n | even n = (k - 1) `mod` n + 1\n | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)\n where\n m = n - 1\n p = k - 1\n solve s p\n | p < n `div` 2 = s + p\n | otherwise = (s + p) `mod` n + 1\n C.putStrLn $ C.pack $ show result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n let\n result\n | even n = (k - 1) `mod` n + 1\n | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)\n where\n m = n - 1\n p = k - 1\n solve s p\n | p < n `div` 2 = s + p\n | otherwise = s + 1 + p\n C.putStrLn $ C.pack $ show result\n"}, {"source_code": "main = do\r\n getLine\r\n interact $ unlines . map (show . solve' . words) . lines\r\n\r\nsolve' [x, y] = solve ((read x) :: Integer) ((read y) :: Integer)\r\n\r\nsolve n k = if (mod n 2) == 0\r\n then let a = mod k n in if a == 0 then n else a\r\n else soleven n k\r\n\r\nsoleven n k = apos + r\r\n where\r\n t = div (n - 1) 2\r\n m = div (k - 1) t\r\n r = k - 1 - m * t\r\n apos = (n + 1) - let a = (mod (m * t) n) in if a == 0 then n else a"}], "src_uid": "2e837d3afc48177516578a950e957586"} {"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\n----- Solution\r\ndata TC = TC {n :: Int64, k :: Int64, ss :: [Int64]}\r\n\r\ntype Output = Bool\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int64\r\n k <- int64\r\n ss <- (fromIntegral k :: Int) >< int64\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = sorted as && (null as || head as * (n - k + 1) >= head ss)\r\n where\r\n as = zipWith (-) (tail ss) ss\r\n\r\nsorted :: Ord a => [a] -> Bool\r\nsorted xs = and $ zipWith (<=) xs (tail xs)\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput _ = showYesNo\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\ndebug a = trace (show a) a\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n\r\nshowYesNo :: Bool -> C.ByteString\r\nshowYesNo = bool \"NO\" \"YES\" >>> C.pack\r\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Internal as BSI\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.Maybe\n\nmain =\n cf $ do\n [n, k] <- readInts\n nums <- readInts\n let hn = head nums\n v1 = (nums !! 1) - head nums\n dh = n - k + 1\n p =\n if k < 2\n then True\n else hn - v1 * dh <= 0\n diffs =\n zipWith3\n (\\p c n -> (p - (2 * c) + n >= 0))\n nums\n (tail nums)\n (drop 2 nums)\n q = and diffs\n BS.putStrLn $\n if p && q\n then \"Yes\"\n else \"No\"\n\nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nreadInt :: IO Int\nreadInt = readLn\n\ncf x = readInt >>= (`replicateM_` x)\n"}, {"source_code": "import Control.Monad\r\n\r\ntoShow True = \"YES\"\r\ntoShow False = \"NO\"\r\n\r\nsolve n m = (div (n+1) 2,div (m+1) 2)\r\n\r\nisAsc (x:y:xs) = x<=y && isAsc (y:xs)\r\nisAsc _ = True\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let [n,k] = map read . words $ input ::[Integer]\r\n input <- getLine\r\n let s = map read . words $ input ::[Integer]\r\n let a = zipWith (-) (tail s) s\r\n putStrLn.toShow $ (isAsc a && (a==[] || (head s) <= (n-k+1)*head a)) \r\n return ()"}, {"source_code": "import qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\nsolve _ [_] = True\nsolve n ps = sorted && head ps <= mxsum where\n xs = zipWith (-) (tail ps) ps\n sorted = and $ zipWith (<=) xs (tail xs)\n mxsum = head xs * (n - length xs)\n\nyesno True = \"Yes\"\nyesno False = \"No\"\n\nmain = do\n [t] <- readInts\n replicateM_ t $\n solve . head <$> readInts <*> readInts >>= putStrLn . yesno\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[n, k] -> map read . words <$> getLine >>=\n \\ss -> putStrLn $ if possible n k ss then \"YES\" else \"NO\"\n\npossible :: Int -> Int -> [Int] -> Bool\npossible n k ss = let (finalTerms, _) = foldl (\\(acc, s) s1 -> (s1-s:acc, s1))\n ([], head ss) (tail ss)\n isSorted xs = all (\\(x, y) -> x >= y) (zip xs (tail xs))\n realizable n k maxTerm left = maxTerm*(n-k+1) >= left\n \n in\n if finalTerms == []\n then True\n else (isSorted finalTerms) &&\n (realizable n k (last finalTerms) (head ss))\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Internal as BSI\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.Maybe\n\nmain =\n cf $ do\n [n, k] <- readInts\n nums' <- readInts\n let nums = drop (n - k) (0 : nums')\n diffs =\n zipWith3\n (\\p c n -> (p - (2 * c) + n >= 0))\n nums\n (tail nums)\n (drop 2 nums)\n q = and diffs\n BS.putStrLn $\n if q\n then \"Yes\"\n else \"No\"\n\nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nreadInt :: IO Int\nreadInt = readLn\n\ncf x = readInt >>= (`replicateM_` x)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Internal as BSI\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.Maybe\n\nmain =\n cf $ do\n [a, b] <- readInts\n nums <- readInts\n let diffs =\n zipWith3\n (\\p c n -> (p - (2 * c) + n >= 0))\n (0 : nums)\n nums\n (tail nums)\n q = and diffs\n BS.putStrLn $\n if q\n then \"Yes\"\n else \"No\"\n\nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nreadInt :: IO Int\nreadInt = readLn\n\ncf x = readInt >>= (`replicateM_` x)\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[n, k] -> map read . words <$> getLine >>=\n \\ss -> putStrLn $ if possible n k ss then \"YES\" else \"NO\"\n\npossible :: Int -> Int -> [Int] -> Bool\npossible n k ss = let (finalTerms, _) = foldl (\\(acc, s) s1 -> (s1-s:acc, s1))\n ([], head ss) (tail ss)\n isSorted xs = all (\\(x, y) -> x >= y) (zip xs (tail xs))\n realizable n k maxTerm left | n == k = maxTerm >= left\n | otherwise = maxTerm*(n-k) >= left\n \n in\n if finalTerms == []\n then True\n else (isSorted finalTerms) &&\n (realizable n k (last finalTerms) (head ss))\n"}, {"source_code": "import Control.Monad\r\n\r\ntoShow True = \"YES\"\r\ntoShow False = \"NO\"\r\n\r\nsolve n m = (div (n+1) 2,div (m+1) 2)\r\n\r\nisAsc (x:y:xs) = x<=y && isAsc (y:xs)\r\nisAsc _ = True\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let [n,k] = map read . words $ input ::[Integer]\r\n input <- getLine\r\n let s = map read . words $ input ::[Integer]\r\n let a = zipWith (-) (tail s) s\r\n putStrLn .show$a\r\n putStrLn.toShow $ (isAsc a && (a==[] || (head s) <= (n-k+1)*head a)) \r\n return ()"}], "src_uid": "9edbe28b5be43a9cc6c633db98bc5a36"} {"source_code": "import Control.Monad ( replicateM_ )\n\n\ncGood :: Char -> String -> Int\ncGood c [x] = fromEnum (c /= x)\ncGood c str = min (f a + g b) (g a + f b)\n where\n f = length . filter (/= c)\n g = cGood (succ c)\n (a, b) = splitAt (length str `div` 2) str\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ getLine >> getLine >>= print . cGood 'a'\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nnotChar char xs = length $ filter (/= char) xs\n\ngood char [x]\n | x == char = True\n | otherwise = False\ngood char xs = (all (== char) start && good (succ char) end) || (all (== char) end && good (succ char) start)\n where\n (start, end) = splitAt n xs\n n = length xs `quot` 2\n\nmakeGood xs = go xs 'a' 0\n where\n go xs char m | good char xs = m\n go [x] char m = m + 1\n go xs char m = min (go end (succ char) (m + notChar char start)) (go start (succ char) (m + notChar char end))\n where\n (start, end) = splitAt n xs\n n = length xs `quot` 2\n\ngetTest :: IO String\ngetTest = do\n _ <- getLine\n getLine\n\nmain :: IO ()\nmain = do\n n <- getLine\n let n' = (read n :: Int)\n tests <- replicateM n' getTest\n mapM_ (print . makeGood) tests\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\n\ndata Half = Start | End deriving Show\n\nnotChar char xs = length $ filter (/= char) xs\n\nmostHalf char xs = case nStart `compare` nEnd of\n GT -> Just Start\n LT -> Just End\n EQ -> Nothing\n where\n nStart = length $ filter (== char) start\n nEnd = length $ filter (== char) end\n\n (start, end) = splitAt n xs\n n = length xs `quot` 2\n\ngood char [x]\n | x == char = True\n | otherwise = False\ngood char xs = (all (== char) start && good (succ char) end) || (all (== char) end && good (succ char) start)\n where\n (start, end) = splitAt n xs\n n = length xs `quot` 2\n\nmakeGood xs = go xs 'a' 0\n where\n go xs char m | good char xs = m\n go [x] char m = m + 1\n go xs char m = case mostHalf char xs of\n Just Start -> go end (succ char) (m + notChar char start)\n Just End -> go start (succ char) (m + notChar char end)\n Nothing -> min (go end (succ char) (m + notChar char start)) (go start (succ char) (m + notChar char end))\n where\n (start, end) = splitAt n xs\n n = length xs `quot` 2\n\ngetTest :: IO String\ngetTest = do\n _ <- getLine\n getLine\n\nmain :: IO ()\nmain = do\n n <- getLine\n let n' = (read n :: Int)\n tests <- replicateM n' getTest\n mapM_ (print . makeGood) tests\n"}], "src_uid": "324b7957b46dfe4948074c781159b7e7"} {"source_code": "import Control.Monad\nmain = do\n n <- fmap read getLine\n ps <- forM [1..n] (\\_ -> getLine)\n print $ solve ps\nsolve :: [String] -> Int\nsolve = foldl f 0\n where f :: Int -> String -> Int\n f n s = if elem s $ map show [0..1000] then if read s < 18 then n + 1 \n else n\n else if s `elem` alcohol then n + 1\n else n\nalcohol :: [String]\nalcohol = [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"]\n", "positive_code": [{"source_code": "module Main where\n\nmain\n = interact in2out\n\nin2out input\n = output\n where\n output = show ans\n ans = count (<18) ages + count (\\x->any (==x) alcohols) drinks\n ages = map (read::String->Int) [age | age@(x:xs)<-items, '0'<=x, x<='9']\n alcohols = [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"]\n drinks = items\n items = tail . lines $ input\n count f []\n = 0\n count f (x:xs)\n | f x\n = 1 + count f xs\n | otherwise\n = count f xs\n"}, {"source_code": "main = do\nn <- getLine >>= return . read\nls <- getContents >>= return . (take n) . lines\nprint $ sum $ map wrong ls where\nwrong l = if (l!!0) <= '9'\n then if (read l) < 18 then 1 else 0\n else if l `elem` al then 1 else 0\nal = \"ABSINTH\":\"BEER\":\"BRANDY\":\"CHAMPAGNE\":\"GIN\":\"RUM\":\"SAKE\":\"TEQUILA\":\"VODKA\":\"WHISKEY\":\"WINE\":[]\n"}, {"source_code": "\nimport Char\n\ntype Visitor = Either Int String\n\nalcohols :: [String]\nalcohols = [\"ABSINTH\", \"BEER\",\n \"BRANDY\", \"CHAMPAGNE\",\n \"GIN\", \"RUM\",\n \"SAKE\", \"TEQUILA\",\n \"VODKA\", \"WHISKEY\",\n \"WINE\"]\n \ncheckVisitor :: Visitor -> Bool\ncheckVisitor (Left age) = age < 18\ncheckVisitor (Right drink) = elem drink alcohols\n\nparseVisitor :: String -> Visitor\nparseVisitor line\n | isDigit headLine = Left (read line)\n | otherwise = Right line\n where\n headLine = head line\n\nreadVisitor :: Int -> IO Visitor\nreadVisitor _ = getLine >>= return . parseVisitor\n\n--readVisitor :: Int -> IO Visitor\n--readVisitor _ = do\n-- line <- getLine\n-- return $ parseVisitor line\n\nmain :: IO()\nmain = do\n n <- readLn\n visitors <- sequence (map readVisitor [1..n])\n print $ length (filter checkVisitor visitors)\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nsolve = show.(foldl' f 0).tail.words\n where f ans ss | all isDigit ss = if (read ss) < 18 then\n ans + 1\n else\n ans\n | otherwise = if (ss `elem` alco) then\n ans + 1\n else\n ans\n alco = [\"ABSINTH\", \"BEER\", \"BRANDY\",\n \"CHAMPAGNE\", \"GIN\", \"RUM\",\n \"SAKE\", \"TEQUILA\", \"VODKA\",\n \"WHISKEY\", \"WINE\"]\n\nmain = interact solve"}, {"source_code": "main=interact$show.sum.map f.tail.lines\nf a=fromEnum$elem a$[show x|x<-[0..17]]++words\"ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE\""}, {"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.Functor\n\n\nalc = words \"ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE\"\n\nmain = interact q\n\nq = func . tail . words\n\nfunc::[String]->String\nfunc x = case solve x of\n Just a -> show a\n Nothing-> \"Error occurred\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nisVailed::String->Bool\nisVailed \"\" = False\nisVailed \"0\" = True\nisVailed ('0':_) = False\nisVailed _ = True\n\nsolve::[String]->Maybe Int\nsolve [] = Just 0\nsolve (x:xs) | isAlpha (x!!0) && x `elem` alc = (+1) <$> solve xs\n | isDigit (x!!0) && (read x) < 18 = (+1) <$> solve xs\n | otherwise = solve xs\n"}, {"source_code": "main = interact $ show . solve . tail . lines\nsolve = length . filter (\\x -> elem x alc)\nalc = [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\",\n \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"] ++ map show [0..17]\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (mapAccumL, sort, maximumBy, minimum, foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport System.Random(mkStdGen, random)\nimport Data.Int(Int64)\nimport Data.Sequence (iterateN)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> a\ndebug v = trace (show v) v\n--debug _ = id\n\nmain = do (sn:desc) <- fmap LB.lines LB.getContents\n let n = readInt sn\n desc' = map (head . LB.words) . take n $ desc\n f s = case LB.readInt s of\n Just (m, _) -> m<18\n otherwise -> s `elem` (map LB.pack [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"])\n\n c = length . filter f . take n $ desc'\n print c\n"}], "negative_code": [{"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.Functor\n\n\nalc = words \"ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE\"\n\nmain = interact q\n\nq = func . init . words\n\nfunc::[String]->String\nfunc x = case solve x of\n Just a -> show a\n Nothing-> \"Error occurred\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nisVailed::String->Bool\nisVailed \"\" = False\nisVailed \"0\" = True\nisVailed ('0':_) = False\nisVailed _ = True\n\nsolve::[String]->Maybe Int\nsolve [] = Just 0\nsolve (x:xs) | isAlpha (x!!0) && x `elem` alc = (+1) <$> solve xs\n | isDigit (x!!0) && (read x) < 18 = (+1) <$> solve xs\n | otherwise = solve xs\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.tail.lines\n\nfunc::[String]->String\nfunc = show.solve\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[String]->Int\nsolve (x:xs) | (isNumber x) && (((read::String->Int) x) < 18) = 1 + solve xs\n | (isAlc x) = 1 + solve xs\n | otherwise = solve xs\n where\n isNumber (x:_) | '0' < x && x <='9' = True\n | otherwise = False\n isAlc x = x `elem` [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"]\nsolve [] = 0\n"}, {"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.Functor\n\n\nalc = words \"ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE\"\n\nmain = interact q\n\nq = func . init . words\n\nfunc::[String]->String\nfunc x = case solve x of\n Just a -> show a\n Nothing-> \"Error occurred\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nisVailed::String->Bool\nisVailed \"\" = False\nisVailed \"0\" = True\nisVailed ('0':_) = False\nisVailed _ = True\n\nsolve::[String]->Maybe Int\nsolve [] = Just 0\nsolve (x:xs) | isAlpha (x!!0) && x `elem` alc = (+1) <$> solve xs\n | isDigit (x!!0) && (read x) < 19 = (+1) <$> solve xs\n | otherwise = solve xs\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as LB\nimport Data.Maybe(fromJust)\nreadInt = fst . fromJust . LB.readInt\n\nmain = do \n s <- getContents\n print . map (s!!) $ [1, 4, 10]\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (mapAccumL, sort, maximumBy, minimum, foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport System.Random(mkStdGen, random)\nimport Data.Int(Int64)\nimport Data.Sequence (iterateN)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> a\ndebug v = trace (show v) v\n--debug _ = id\n\nmain = do (sn:desc) <- fmap LB.lines LB.getContents\n let n = readInt sn\n desc' = take n desc\n c1 = length . filter (`elem` \n (map LB.pack [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"]))\n $ desc'\n f s = case LB.readInt s of\n Just (m, _) -> m<18\n otherwise -> False\n c2 = length . filter f $ desc'\n print (c1 + c2)\n "}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as LB\nimport Data.Maybe(fromJust)\nimport Data.Char(ord)\nreadInt = fst . fromJust . LB.readInt\n\nmain = do \n s <- LB.getContents\n print . map (LB.index s) $ [1, 4, 10]"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (mapAccumL, sort, maximumBy, minimum, foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport System.Random(mkStdGen, random)\nimport Data.Int(Int64)\nimport Data.Sequence (iterateN)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> a\ndebug v = trace (show v) v\n--debug _ = id\n\nmain = do (sn:desc) <- fmap LB.lines LB.getContents\n let n = readInt sn\n desc' = take n $ desc\n f s = case LB.readInt s of\n Just (m, _) -> m<18\n otherwise -> s `elem` (map LB.pack [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"])\n\n c = length . filter f . take n $ desc'\n print c\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (mapAccumL, sort, maximumBy, minimum, foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport System.Random(mkStdGen, random)\nimport Data.Int(Int64)\nimport Data.Sequence (iterateN)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> a\ndebug v = trace (show v) v\n--debug _ = id\n\nmain = do (sn:desc) <- fmap LB.lines LB.getContents\n let n = readInt sn\n f s = case LB.readInt s of\n Just (m, _) -> m<18\n otherwise -> s `elem` (map LB.pack [\"ABSINTH\", \"BEER\", \"BRANDY\", \"CHAMPAGNE\", \"GIN\", \"RUM\", \"SAKE\", \"TEQUILA\", \"VODKA\", \"WHISKEY\", \"WINE\"])\n\n c = length . filter f . take n $ desc\n print c\n"}], "src_uid": "4b7b0fba7b0af78c3956c34c29785e7c"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\ncsort :: [Int] -> [Int]\ncsort [] = []\ncsort li = let\n tar = minimum li\n (pref, _tar : suff) = span (> tar) li\n in length pref : csort (suff ++ pref)\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n a <- getInts n\n let\n res = csort a\n ans = [[l, n, v] | (l, v) <- zip [1..n] res, v > 0]\n pure $ putInts [length ans] <> foldMap putInts ans\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\n-- (echo 1000; for i in {1..1000}; do apg -a'1' -M'N' -m'9' -x'9' -n'50' | { echo 50; echo `cat`; }; done) > large_input.txt\n--\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- large_input.txt | time ./a.out | wc --bytes)\n\nimport Prelude\n-- import System.IO\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n-- import Debug.Trace\n-- trF showFunc x = trace msg x where msg = \"\\n\" ++ \"trF: \" ++ showFunc x ++ \".\"\n-- tr s x = trace msg x where msg = \"\\n\" ++ \"tr: \" ++ s ++ \": \" ++ show x ++ \".\"\n\nmain :: IO ()\nmain = do\n -- hSetBuffering stdout NoBuffering\n\n t <- readLn\n tcs <- replicateM t getTC\n\n (putStr . concatMap solve) tcs\n\ngetTC = do\n n <- readLn\n map read <$> wordsN n <$> getLine :: IO [Int]\n\nwordsN n s = ww where w = words s; ww | (length w == n) = w\n | otherwise = error \"arr len\"\n\nunlinesN strs = (unlines . ([show $ length strs]++)) strs\n\nsolve xs = unlinesN . map showOp . filter ((/= 0) . snd) . zip [1..] $ minIndices\n where\n minIndices = map fst . take (length xs - 1) . tail . iterate step $ (undefined, xs)\n\n showOp (i, off) = show i ++ \" \" ++ show (i+off) ++ \" \" ++ show off\n\nstep (_, xs) = removeMin xs\n\nremoveMin [] = error \"can not remove\"\nremoveMin xs = (i, h ++ tail t)\n where\n i = (fromJust . findMinIndex) xs\n\n (h,t) = splitAt i xs\n\nfindMinIndex xs = let m = minimum xs\n in findIndex (== m) xs\n"}, {"source_code": "import Control.Monad ( replicateM_, forM_ )\r\nimport Data.List ( intercalate )\r\n\r\ncalc n i a\r\n | n == i + 1 = [[]]\r\n | id == 0 = calc n (i + 1) na\r\n | otherwise = [i + 1, n, id] : calc n (i + 1) na\r\n where\r\n id = snd $ minimum $ zip a [0..]\r\n na = tail $ drop id a <> take id a\r\n\r\nsolve = do\r\n [n] <- map read.words <$> getLine :: IO [Int]\r\n a <- map read.words <$> getLine :: IO [Int]\r\n let f = init $ calc n 0 a\r\n print (length f)\r\n forM_ f $ \\item -> do\r\n putStrLn $ unwords $ map show item\r\n\r\nmain = readLn >>= flip replicateM_ solve"}, {"source_code": "import Control.Monad ( replicateM_, forM_ )\r\nimport Data.List ( intercalate, delete )\r\n\r\ncalc' :: [Int] -> Int -> [[Int]] -> [[Int]]\r\ncalc' [] _ acc = acc\r\ncalc' lst j acc = \r\n let (mn, i) = minimum $ zip lst [1..]\r\n lst' = delete mn lst\r\n in \r\n if i == 1 then calc' lst' (j + 1) acc\r\n else calc' lst' (j + 1) ([j + 1, j + i, i - 1] : acc)\r\n\r\ncalc :: [Int] -> [[Int]]\r\ncalc lst = reverse $ calc' lst 0 []\r\n\r\nsolve = do\r\n [n] <- map read.words <$> getLine :: IO [Int]\r\n a <- map read.words <$> getLine :: IO [Int]\r\n let f = calc a\r\n print (length f)\r\n forM_ f $ \\item -> do\r\n putStrLn $ unwords $ map show item\r\n\r\nmain = readLn >>= flip replicateM_ solve"}, {"source_code": "import Control.Monad ( replicateM_, forM_ )\r\nimport Data.List ( intercalate )\r\n\r\nmix :: [Int] -> Int -> Int -> Int\r\nmix (a : as) m i = if a == m then i else mix as m i + 1\r\nmix [] _ _ = 0\r\n\r\nshift :: [Int] -> Int -> [Int]\r\nshift a s = drop s a <> take s a\r\n\r\ncalc :: Int -> Int -> [Int] -> [[Int]]\r\ncalc n i a\r\n | n == i + 1 = [[]]\r\n | id == 0 = calc n (i + 1) (tail $ shift a id)\r\n | otherwise = [i + 1, n, id] : calc n (i + 1) (tail $ shift a id)\r\n where\r\n id = mix a (minimum a) 0\r\n\r\nsolve = do\r\n [n] <- map read.words <$> getLine :: IO [Int]\r\n a <- map read.words <$> getLine :: IO [Int]\r\n let f = init $ calc n 0 a\r\n print (length f)\r\n forM_ f $ \\item -> do\r\n putStrLn $ unwords $ map show item\r\n\r\nmain = readLn >>= flip replicateM_ solve"}, {"source_code": "import Control.Monad\nimport Data.List\n\n-- 2 5 1 -> 5 1 2 -> 1 2 5\n-- 5 2 1 -> 2 1 5 -> 1 5 2\n\n-- 2 5 1 4 3\n-- 1 2 3 4 5\n--\n-- 1 2 3 4 5\n-- 3 1 5 4 2\n\n-- 5 2 1 4 3\n-- 1 2 3 4 5\n--\n-- 1 2 3 4 5\n-- 3 2 5 4 1\n\ncalc' :: [Int] -> Int -> [[Int]] -> [[Int]]\ncalc' [] j acc = acc\ncalc' lst j acc =\n let (mn,i) = minimum $ zip lst [1..]\n lst' = delete mn lst\n in\n if i == 1 then calc' lst' (j+1) acc\n else calc' lst' (j+1) ([j+1,j+i,i-1]:acc)\n\ncalc :: [Int] -> [[Int]]\ncalc lst = reverse $ calc' lst 0 []\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let lst = map read $ words line :: [Int]\n let ans = calc lst\n putStrLn $ show $ length ans\n forM_ ans $ \\item -> do\n putStrLn $ intercalate \" \" $ map show item\n"}], "negative_code": [{"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt)\n\nimport Prelude\nimport System.IO\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nimport Debug.Trace\n-- trF showFunc x = trace msg x where msg = \"\\n\" ++ \"trF: \" ++ showFunc x ++ \".\"\n-- tr s x = trace msg x where msg = \"\\n\" ++ \"tr: \" ++ s ++ \": \" ++ show x ++ \".\"\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n\n t <- readLn\n tcs <- replicateM t ((map read . words . head . tail) <$> replicateM 2 getLine) :: IO [[Int]]\n\n (hPutStr stderr . unlines . map show) tcs\n\n -- (hPutStr stderr . unlines . map (show . filter (not.isNoop) . solve 1)) tcs\n (hPutStr stderr . concatMap (showAns . filter (not.isNoop) . solve 1)) tcs\n\nshowAns xs = show (length xs) ++ \"\\n\" ++ (unlines . map showOp) xs\n\nsolve _ [] = []\nsolve off xs = fix off op : solve (off+1) (tail $ shift xs op)\n where\n i = fromJust . findIndex (== minimum xs) $ xs\n\n op = (0, i, i)\n\nfix n (l, r, d) = (l+n, r+n, d)\n\nisNoop (_l, _r, d) = (d == 0)\n\nshowOp (l, r, d) = show l ++ \" \" ++ show r ++ \" \" ++ show d\n\nshift xs (l,r,d) = beg ++ (shiftL mid d) ++ end\n where\n (beg, midEnd) = splitAt l xs\n (mid, end ) = splitAt (r-l+1) midEnd\n\nshiftL xs 0 = xs\nshiftL xs d = shiftL (tail xs ++ [head xs]) (d-1)\n"}, {"source_code": "import Control.Monad ( replicateM_, forM_ )\r\nimport Data.List ( intercalate )\r\n\r\ncalc n i a\r\n | n == i + 1 = [[]]\r\n | id == 0 = calc n (i + 1) na\r\n | otherwise = [i + 1, n, id] : calc n (i + 1) na\r\n where\r\n id = snd $ minimum $ zip a [1..]\r\n na = tail $ drop id a <> take id a\r\n\r\nsolve = do\r\n [n] <- map read.words <$> getLine :: IO [Int]\r\n a <- map read.words <$> getLine :: IO [Int]\r\n let f = init $ calc n 0 a\r\n print (length f)\r\n forM_ f $ \\item -> do\r\n putStrLn $ unwords $ map show item\r\n\r\nmain = readLn >>= flip replicateM_ solve"}, {"source_code": "import Control.Monad\nimport Data.List\n\n-- 2 5 1 -> 5 1 2 -> 1 2 5\n-- 5 2 1 -> 2 1 5 -> 1 5 2\n\n-- 2 5 1 4 3\n-- 1 2 3 4 5\n--\n-- 1 2 3 4 5\n-- 3 1 5 4 2\n\n-- 5 2 1 4 3\n-- 1 2 3 4 5\n--\n-- 1 2 3 4 5\n-- 3 2 5 4 1\n\ncalc' :: [Int] -> Int -> [[Int]] -> [[Int]]\ncalc' [] j acc = acc\ncalc' lst j acc =\n let (mn,i) = minimum $ zip lst [1..]\n lst' = delete mn lst\n in\n if i == 1 then calc' lst' (j+1) acc\n else calc' lst' (j+1) ([j+1,j+i,j+i-1]:acc)\n\ncalc :: [Int] -> [[Int]]\ncalc lst = reverse $ calc' lst 0 []\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let lst = map read $ words line :: [Int]\n let ans = calc lst\n putStrLn $ show $ length ans\n forM_ ans $ \\item -> do\n putStrLn $ intercalate \" \" $ map show item\n"}], "src_uid": "06c515c2d889edec8db784b2d5279edc"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.IORef\nimport Data.Maybe (fromJust)\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep !m !n f=go m where go !i=when(i>go(i+1)\n\nmain :: IO ()\nmain = do\n n <- readLn\n bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine\n dp <- newArray (0,n*n-1) 0 :: IO (IOUArray Int Int)\n v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)\n\n forM_ (zip[0..]bs) $ \\(i,b)-> do\n i0 <- unsafeRead v2i b\n when (i0 < 0) $ unsafeWrite v2i b i\n\n xs <- mapM (unsafeRead v2i) bs\n\n let get (i,j) = unsafeRead dp (i*n+j)\n put (i,j) v = unsafeWrite dp (i*n+j) v\n\n forM_ (zip[0..]xs) $ \\(i,x) -> do\n if i==x\n then do\n put (i,i) 1\n rep 0 i $ \\j -> do\n put (j,x) 2\n else do\n rep 0 i $ \\j -> do\n xj <- get (x,j)\n jx <- get (j,x)\n put (j,x) $ max jx (xj+1)\n\n ans <- newIORef 0 :: IO (IORef Int)\n\n rep 0 (n*n) $ \\ij-> do\n dpij <- unsafeRead dp ij\n x <- readIORef ans\n writeIORef ans $! max dpij x\n\n readIORef ans >>= print\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Tuple\nimport GHC.Exts\nsolve l = maximum $ (2 `min` length l) : (map length s) ++ [ f x y | x@(_:_:_) : t <- tails s, y<-t ]\n where \n s = reverse . sortWith length . groupWith fst $ zip l [0..]\n f x y = length . group $ map fst $ sortWith snd $ x ++ y \n\nmain = interact $ show . solve .tail . words"}, {"source_code": "import Data.List\nimport GHC.Exts\nsolve l = maximum $ 2 `min` length l : map length s ++ [length . group $ map fst $ sortWith snd $ x ++ y | x <- s, length x > 1, y<-s, y/=x ]\n where s = groupWith fst $ zip l [0..]\n \nmain = interact $ show . solve .tail . words"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.IORef\nimport Data.Maybe (fromJust)\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep !m !n f=go m where go !i=when(i>go(i+1)\n\nmain :: IO ()\nmain = do\n n <- readLn\n bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine\n dp <- newArray (0,n*n-1) 0 :: IO (IOUArray Int Int)\n v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)\n i2v <- newListArray (0,n-1) bs :: IO (IOUArray Int Int)\n\n forM_ (zip[0..]bs) $ \\(i,b)-> do\n i0 <- unsafeRead v2i b\n when (i0 < 0) $ unsafeWrite v2i b i\n\n forM_ (zip[0..]bs) $ \\(i,b)-> do\n i0 <- unsafeRead v2i b\n if i0 do\n vj <- unsafeRead i2v j\n j0 <- unsafeRead v2i vj\n when (j0==j) $ do\n dpij <- unsafeRead dp $ n*i0+j\n unsafeWrite dp (n*j+i0) $ dpij+1\n else do\n unsafeWrite dp (i*n+i) 1\n rep 0 i $ \\j-> do\n unsafeWrite dp (j*n+i) 2\n\n ans <- newIORef 0 :: IO (IORef Int)\n\n rep 0 (n*n) $ \\ij-> do\n dpij <- unsafeRead dp ij\n x <- readIORef ans\n writeIORef ans $! max dpij x\n\n readIORef ans >>= print\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.IORef\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine\n dp <- newArray (0,4000*4000-1) 0 :: IO (IOUArray Int Int)\n v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)\n\n forM_ (zip[0..]bs) $ \\ (i,b)-> do\n visited <- unsafeRead v2i b\n when (visited < 0) $ do\n unsafeWrite v2i b i\n unsafeWrite dp (i*4000+i) 1\n\n forM_ bs $ \\b-> do\n i <- unsafeRead v2i b\n forM_ [0..3999] $ \\j-> do\n dpij <- unsafeRead dp $ 4000*i+j\n unsafeWrite dp (4000*i+j) $ dpij+1\n\n ans <- newIORef 0 :: IO (IORef Int)\n\n forM_ [0..4000*4000-1] $ \\i-> do\n ai <- unsafeRead dp i\n x <- readIORef ans\n writeIORef ans $! max ai x\n\n readIORef ans >>= print\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.IORef\nimport Data.Maybe (fromJust)\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep !m !n f=go m where go !i=when(i>go(i+1)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine\n dp <- newArray (0,4000*4000-1) 0 :: IO (IOUArray Int Int)\n v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)\n\n forM_ (zip[0..]bs) $ \\(i,b)-> do\n visited <- unsafeRead v2i b\n when (visited < 0) $ unsafeWrite v2i b i\n\n forM_ (zip[0..]bs) $ \\(i,b)-> do\n i0 <- unsafeRead v2i b\n if i0 do\n dpij <- unsafeRead dp $ 4000*i0+j\n unsafeWrite dp (4000*j+i0) $ dpij+1\n else do\n unsafeWrite dp (i*4000+i) 1\n rep 0 i $ \\j-> do\n unsafeWrite dp (j*4000+i) 2\n\n ans <- newIORef 0 :: IO (IORef Int)\n\n rep 0 (4000*4000) $ \\i-> do\n ai <- unsafeRead dp i\n x <- readIORef ans\n writeIORef ans $! max ai x\n\n readIORef ans >>= print\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.IORef\nimport Data.Maybe (fromJust)\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep !m !n f = go m\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n _ <- getLine\n bs <- fmap(map(fst.fromJust.B.readInt).B.words)B.getLine\n dp <- newArray (0,4000*4000-1) 0 :: IO (IOUArray Int Int)\n v2i <- newArray (0,1000000) (-1) :: IO (IOUArray Int Int)\n\n forM_ (zip[0..]bs) $ \\ (i,b)-> do\n visited <- unsafeRead v2i b\n if visited < 0\n then unsafeWrite v2i b i\n else unsafeWrite dp (i*4000+i) 1\n\n forM_ bs $ \\b-> do\n i <- unsafeRead v2i b\n let !k = 4000*i\n rep 0 4000 $ \\j-> do\n dpij <- unsafeRead dp $ k+j\n unsafeWrite dp (k+j) $ max 2 $ dpij+1\n\n ans <- newIORef 0 :: IO (IORef Int)\n\n rep 0 (4000*4000) $ \\i-> do\n ai <- unsafeRead dp i\n x <- readIORef ans\n writeIORef ans $! max ai x\n\n readIORef ans >>= print\n"}], "src_uid": "86ded9e6336a14b43dda780ebd099b4f"} {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.MArray\nimport Data.Ix\n\nnewDisSet :: (MArray a i m, Ix i) => (i, i) -> m (a i i)\nnewDisSet b = newListArray b (range b)\n\nrootDisSet :: (MArray a i m, Ix i) => (a i i) -> i -> m i\nrootDisSet s i = do\n p <- readArray s i\n if p == i\n then return p\n else do\n p' <- rootDisSet s p\n when ( p' /= p ) $ writeArray s i p'\n return p'\n\nunionDisSet :: (MArray a i m, Ix i) => (a i i) -> i -> i -> m ()\nunionDisSet s i j = do\n pi <- rootDisSet s i\n pj <- rootDisSet s j\n when ( pi /= pj ) $ writeArray s pj pi\n\ntestDisSet :: (MArray a i m, Ix i) => (a i i) -> i -> i -> m Bool\ntestDisSet s i j = do\n pi <- rootDisSet s i\n pj <- rootDisSet s j\n return $ pi == pj\n\nmain = do\n [n, m] <- ( map read . words ) `liftM` getLine :: IO [Int]\n\n res <- if n == m\n then do\n disSet <- newDisSet (1, n) :: IO (IOArray Int Int)\n replicateM m $ do\n [i, j] <- ( map read . words ) `liftM` getLine\n unionDisSet disSet i j\n foldM (\\ans i -> ( ans && ) `liftM` testDisSet disSet 1 i) True [2..n]\n else return False\n putStrLn $ if res\n then \"FHTAGN!\"\n else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\n\nfindCthulhu :: (Int, Int, [(Int, Int)]) -> String\nfindCthulhu (vn, en, edges) = \n\tif vn == en && (length $ components $ buildG (1, vn) edges) == 1\n\tthen \"FHTAGN!\" \n\telse \"NO\"\n\nparseInput :: String -> (Int, Int, [(Int, Int)])\nparseInput input = (vn, ve, edges) where\n\tvn = read $ head $ words $ input\n\tve = read $ head $ tail $ words $ input\n\tedges = pairsFromStrings $ tail $ tail $ words $ input where\n\t\tpairsFromStrings [] = []\n\t\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\nmain = do\n\tinput <- getContents\n\tputStr $ findCthulhu $ parseInput input -- \"6 5 5 6 4 6 3 1 5 1 1 2\"\n"}, {"source_code": "-- \u0432\u043e\u0441\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c \u0434\u0435\u0440\u0435\u0432\u043e \u043f\u043e \u0432\u0445\u043e\u0434\u043d\u044b\u043c \u0434\u0430\u043d\u043d\u044b\u043c\n-- \u0441\u0440\u0430\u0432\u043d\u0438\u0442\u044c \u0447\u0438\u0441\u043b\u043e \u0440\u0435\u0431\u0435\u0440 \u0441 \u0447\u0438\u0441\u043b\u043e\u043c \u0432\u0435\u0440\u0448\u0438\u043d \u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u043e\u0441\u0442\u044c (\u0434\u0444\u0441)\n--6 6\n--6 3\n--6 4\n--5 1\n--2 5\n--1 4\n--5 4\n\nimport Data.Graph\n\n--main = do\n--\tvn <- read\n--\ten <- read\n\n--\tedges <- map toInteger (words getContents)\n--\tprint $ length $ components $ buildG edges\n\nfindCthulhu :: (Int, Int, [(Int, Int)]) -> String\nfindCthulhu (vn, en, edges) = \n\tif vn == en && (length $ components $ buildG (1, vn) edges) == 1\n\tthen \"FHTAGN!\" \n\telse \"NO\"\n\nparseInput :: String -> (Int, Int, [(Int, Int)])\nparseInput input = (vn, ve, edges) where\n\tvn = read $ head $ words $ input\n\tve = read $ head $ tail $ words $ input\n\tedges = pairsFromStrings $ tail $ tail $ words $ input where\n\t\tpairsFromStrings [] = []\n\t\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\n--parseInput :: String -> (Int, Int, [(Int, Int)])\n--parseInput input = (fst $ head pairs, snd $ head pairs, (tail pairs)) where\n--\tpairs = pairsFromStrings $ words input \n--\tpairsFromStrings [] = []\n--\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\n--pairsFromStrings :: [String] -> [(Int, Int)]\n--pairsFromStrings (f:s:xs) = (read f, read s) : (pairsFromStrings xs)\n\nmain = do\n\tinput <- getContents\n\tputStr $ findCthulhu $ parseInput input --\"6 5 5 6 4 6 3 1 5 1 1 2\" --\" 6 6 3 6 4 5 1 2 5 1 4 5 4\"\n\t--let pairs = pairsFromStrings $ words text\n\t--in print $ findCthulhu (fst $ head pairs) (snd $ head pairs) (tail pairs)\n\t\t\n\t\n\n\t--(1, 6) [(6, 3), (6, 4), (5, 1), (2, 5), (1, 4), (5, 4)]\n\n\n\t\t--[('*', 6, [3, 4]), \n\t\t-- ('*', 3, [6]),\n\t\t-- ('*', 4, [6, 1, 5]),\n\t\t-- ('*', 5, [1, 2, 4]), \n\t\t-- ('*', 1, [5, 4]),\n\t\t-- ('*', 2, [5])]\n\n\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\""}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n m <- readInt\n edges <- replicateM m ((,) <$> readInt <*> readInt)\n return (n, edges)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStrLn =<< solve . evalState parseInput <$> BS.getContents\n\nsolve :: (Int, [(Int,Int)]) -> String\nsolve (n, edges)\n | n == m && comps == 1 = \"FHTAGN!\"\n | otherwise = \"NO\"\n where\n m = length edges\n\n graph = buildG (1, n) $ concat [[(x, y), (y, x)] | (x, y) <- edges]\n\n comps = length $ components graph\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\""}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.String\n\naddEdge' :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge' 0 b (g:gs) = ((b:g):gs)\naddEdge' a b (g:gs) = g:addEdge' (a-1) b gs\n\naddEdge :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge a b g = addEdge' a b $ addEdge' b a g\n\nreachable' :: [Int] -> [[Int]] -> [Int] -> [Int]\nreachable' [] g visited = []\nreachable' (v:vs) g visited = fromv ++ reachable' vs g (fromv ++ visited)\n\t\t\t\t\t\t\t\twhere fromv = if elem v visited \n\t\t\t\t\t\t\t\t\t\t\t\tthen [] \n\t\t\t\t\t\t\t\t\t\t\t\telse v:reachable' (g!!v) g (v:visited);\n\nreachable :: Int -> [[Int]] -> [Int]\nreachable v g = reachable' [v] g []\n\nisConnected :: [[Int]] -> Bool\nisConnected g = length g == (length $ reachable 0 g)\n\nisKtulhu :: [[Int]] -> Bool\nisKtulhu g = isConnected g && 2 * (length g) == length (concat g) \n\nparse :: String -> [Int]\nparse s = [read $ w !! 0, read $ w !! 1] where w = words s\n\nparseGraph' :: [[Int]] -> [String] -> [[Int]]\nparseGraph' g [] = g\nparseGraph' g (s:sx) = parseGraph' (addEdge (e !! 0 - 1) (e !! 1 - 1) g) sx where e = parse s\n\nparseGraph :: String -> [[Int]]\nparseGraph s = parseGraph' (replicate ((parse $ head w) !! 0) []) (tail w) where w = lines s\n\nktulhuState :: Bool -> String\nktulhuState ktulhu = if ktulhu then \"FHTAGN!\" else \"NO\" \n\nmain = do \n\t\tgraphData <- getContents\n\t\tputStrLn $ ktulhuState $ isKtulhu $ parseGraph $ graphData\n\t\t\n"}, {"source_code": "import Data.List\nimport Data.String\n\n{-\ndropEdge' :: Int -> Int -> [[Int]] -> [[Int]]\ndropEdge' 0 b (g:gs) = (delete b g):gs \ndropEdge' a b (g:gs) = g:dropEdge' (a-1) b gs\n\ndropEdge :: Int -> Int -> [[Int]] -> [[Int]] \ndropEdge a b g = dropEdge' a b $ dropEdge' b a g\n\ngetCycle'' :: [Int] -> [[Int]] -> [Int] -> [Int]\ngetCycle'' [] g stack = []\ngetCycle'' (v:vs) g stack = if aCycle == []\n\t\t\t\t\t\t\tthen getCycle'' vs g stack\n\t\t\t\t\t\t\telse aCycle\n\t\t\t\t\t\t\twhere aCycle = getCycle' v g stack\n\ngetCycle' :: Int -> [[Int]] -> [Int] -> [Int]\ngetCycle' v g [] \t\t\t= \tgetCycle'' (g!!v) g [v]\ngetCycle' v g stack@(s:sx) = if elem v sx\n\t\t\t\t\t \t \tthen v:takeWhile (\\x -> not $ x == v) stack\n\t\t\t\t\t \t \telse getCycle'' (delete s $ g!!v) g (v:stack)\n\t\t\t\t\t\t\n\ngetCycle :: [[Int]] -> [Int]\ngetCycle g = getCycle' 0 g [] \n\n\nhasSingleCycle :: [[Int]] -> Bool\nhasSingleCycle g = if aCycle == [] \n\t\t\t\t then False\n\t\t\t\t\telse [] == getCycle (dropEdge (aCycle !! 0) (aCycle !! 1) g)\n\t\t\t\t where aCycle = getCycle g-}\n\naddEdge' :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge' 0 b (g:gs) = ((b:g):gs)\naddEdge' a b (g:gs) = g:addEdge' (a-1) b gs\n\naddEdge :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge a b g = addEdge' a b $ addEdge' b a g\n\nreachable' :: [Int] -> [[Int]] -> [Int] -> [Int]\nreachable' [] g visited = []\nreachable' (v:vs) g visited = if elem v visited \n\t\t\t\t\t\t\t \tthen reachable' vs g visited\n\t\t\t\t\t\t\t\telse fromv ++ reachable' vs g (fromv ++ visited)\n\t\t\t\t\t\t\t\twhere fromv = v:reachable' (g!!v) g (v:visited);\n\nreachable :: Int -> [[Int]] -> [Int]\nreachable v g = reachable' [v] g []\n\nisConnected :: [[Int]] -> Bool\nisConnected g = length g == (length $ reachable 0 g)\n\nisKtulhu :: [[Int]] -> Bool\nisKtulhu g = isConnected g && 2 * (length g) == length (concat g) \n\nparse :: String -> [Int]\nparse s = [read $ w !! 0, read $ w !! 1] where w = words s\n\nparseGraph' :: [[Int]] -> [String] -> [[Int]]\nparseGraph' g [] = g\nparseGraph' g (s:sx) = parseGraph' (addEdge (e !! 0 - 1) (e !! 1 - 1) g) sx where e = parse s\n\nparseGraph :: String -> [[Int]]\nparseGraph s = parseGraph' (replicate ((parse $ head w) !! 0) []) (tail w) where w = lines s\n\n\nktulhuState :: Bool -> String\nktulhuState ktulhu = if ktulhu then \"FHTAGN!\" else \"NO\" \n\nmain = do \n\t\tgraphData <- getContents\n\t\tputStrLn $ ktulhuState $ isKtulhu $ parseGraph $ graphData\n\t\t\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\nmain = do\n [n, m]:es <- fmap (map (map read.words).lines) getContents\n let g = buildG (1,n) $ concat [[(x,y),(y,x)] | [x,y] <- es]\n let c = length (components g)\n putStrLn $ if n == m && c == 1 then \"FHTAGN!\" else \"NO\"\n"}, {"source_code": "import Data.Graph\n\nsolve ((n, _):es) =\n if (length $ components graph) == 1 && n == (length es) then\n \"FHTAGN!\"\n else\n \"NO\"\n where graph = buildG (1, n) es\n\nmain = interact $ solve.map toEdge.map (map read.words).lines\n where toEdge [x, y] = (x, y)\n"}, {"source_code": "import Data.Graph\n\nsolve ((n, _):es) =\n if (length $ components graph) == 1 && n == (length es) then\n \"FHTAGN!\"\n else\n \"NO\"\n where graph = buildG (1, n) es\n\nmain = interact $ solve.map toEdge.map (map read.words).lines\n where toEdge [x, y] = (x, y)"}], "negative_code": [{"source_code": "-- \u0432\u043e\u0441\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c \u0434\u0435\u0440\u0435\u0432\u043e \u043f\u043e \u0432\u0445\u043e\u0434\u043d\u044b\u043c \u0434\u0430\u043d\u043d\u044b\u043c\n-- \u0441\u0440\u0430\u0432\u043d\u0438\u0442\u044c \u0447\u0438\u0441\u043b\u043e \u0440\u0435\u0431\u0435\u0440 \u0441 \u0447\u0438\u0441\u043b\u043e\u043c \u0432\u0435\u0440\u0448\u0438\u043d \u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u043e\u0441\u0442\u044c (\u0434\u0444\u0441)\n--6 6\n--6 3\n--6 4\n--5 1\n--2 5\n--1 4\n--5 4\n\nimport Data.Graph\n\n--main = do\n--\tvn <- read\n--\ten <- read\n\n--\tedges <- map toInteger (words getContents)\n--\tprint $ length $ components $ buildG edges\n\nfindCthulhu :: (Int, Int, [(Int, Int)]) -> String\nfindCthulhu (vn, en, edges) = \n\tif vn == en && (length $ components $ buildG (1, vn) edges) == 1\n\tthen \"FHTAGN!\" \n\telse \"NO\"\n\n\nparseInput :: String -> (Int, Int, [(Int, Int)])\nparseInput input = (vn, ve, edges) where\n\tvn = read $ head $ words $ input\n\tve = read $ head $ tail $ words $ input\n\tedges = pairsFromStrings $ tail $ tail $ words $ input where\n\t\tpairsFromStrings [] = []\n\t\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\n--parseInput :: String -> (Int, Int, [(Int, Int)])\n--parseInput input = (fst $ head pairs, snd $ head pairs, (tail pairs)) where\n--\tpairs = pairsFromStrings $ words input \n--\tpairsFromStrings [] = []\n--\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\n--pairsFromStrings :: [String] -> [(Int, Int)]\n--pairsFromStrings (f:s:xs) = (read f, read s) : (pairsFromStrings xs)\n\nmain = do\n\tinput <- getContents\n\tprint $ findCthulhu $ parseInput input --\"6 5 5 6 4 6 3 1 5 1 1 2\" --\" 6 6 3 6 4 5 1 2 5 1 4 5 4\"\n\t--let pairs = pairsFromStrings $ words text\n\t--in print $ findCthulhu (fst $ head pairs) (snd $ head pairs) (tail pairs)\n\t\t\n\t\n\n\t--(1, 6) [(6, 3), (6, 4), (5, 1), (2, 5), (1, 4), (5, 4)]\n\n\n\t\t--[('*', 6, [3, 4]), \n\t\t-- ('*', 3, [6]),\n\t\t-- ('*', 4, [6, 1, 5]),\n\t\t-- ('*', 5, [1, 2, 4]), \n\t\t-- ('*', 1, [5, 4]),\n\t\t-- ('*', 2, [5])]\n\n\n"}, {"source_code": "-- \u0432\u043e\u0441\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c \u0434\u0435\u0440\u0435\u0432\u043e \u043f\u043e \u0432\u0445\u043e\u0434\u043d\u044b\u043c \u0434\u0430\u043d\u043d\u044b\u043c\n-- \u0441\u0440\u0430\u0432\u043d\u0438\u0442\u044c \u0447\u0438\u0441\u043b\u043e \u0440\u0435\u0431\u0435\u0440 \u0441 \u0447\u0438\u0441\u043b\u043e\u043c \u0432\u0435\u0440\u0448\u0438\u043d \u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0441\u0432\u044f\u0437\u043d\u043e\u0441\u0442\u044c (\u0434\u0444\u0441)\n--6 6\n--6 3\n--6 4\n--5 1\n--2 5\n--1 4\n--5 4\n\nimport Data.Graph\n\n--main = do\n--\tvn <- read\n--\ten <- read\n\n--\tedges <- map toInteger (words getContents)\n--\tprint $ length $ components $ buildG edges\n\nfindCthulhu :: (Int, Int, [(Int, Int)]) -> String\nfindCthulhu (vn, en, edges) = \n\tif vn == en && (length $ components $ buildG (1, vn) edges) == 1\n\tthen \"FHTAGN!\" \n\telse \"NO\"\n\n\nparseInput :: String -> (Int, Int, [(Int, Int)])\nparseInput input = (vn, ve, edges) where\n\tvn = read $ head $ words $ input\n\tve = read $ head $ tail $ words $ input\n\tedges = pairsFromStrings $ tail $ tail $ words $ input where\n\t\tpairsFromStrings [] = []\n\t\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\n--parseInput :: String -> (Int, Int, [(Int, Int)])\n--parseInput input = (fst $ head pairs, snd $ head pairs, (tail pairs)) where\n--\tpairs = pairsFromStrings $ words input \n--\tpairsFromStrings [] = []\n--\tpairsFromStrings (f:s:xs) = (read f, read s) : pairsFromStrings xs\n\n--pairsFromStrings :: [String] -> [(Int, Int)]\n--pairsFromStrings (f:s:xs) = (read f, read s) : (pairsFromStrings xs)\n\nmain = do\n\tinput <- getContents\n\tprint $ findCthulhu $ parseInput input -- \"6 6 6 3 6 4 5 1 2 5 1 4 5 4\"\n\t--let pairs = pairsFromStrings $ words text\n\t--in print $ findCthulhu (fst $ head pairs) (snd $ head pairs) (tail pairs)\n\t\t\n\t\n\n\t--(1, 6) [(6, 3), (6, 4), (5, 1), (2, 5), (1, 4), (5, 4)]\n\n\n\t\t--[('*', 6, [3, 4]), \n\t\t-- ('*', 3, [6]),\n\t\t-- ('*', 4, [6, 1, 5]),\n\t\t-- ('*', 5, [1, 2, 4]), \n\t\t-- ('*', 1, [5, 4]),\n\t\t-- ('*', 2, [5])]\n\n\n"}, {"source_code": "import Data.List\nimport Data.String\n\naddEdge' :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge' 0 b (g:gs) = ((b:g):gs)\naddEdge' a b (g:gs) = g:addEdge' (a-1) b gs\n\naddEdge :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge a b g = addEdge' a b $ addEdge' b a g\n\ndropEdge' :: Int -> Int -> [[Int]] -> [[Int]]\ndropEdge' 0 b (g:gs) = (delete b g):gs \ndropEdge' a b (g:gs) = g:dropEdge' (a-1) b gs\n\ndropEdge :: Int -> Int -> [[Int]] -> [[Int]] \ndropEdge a b g = dropEdge' a b $ dropEdge' b a g\n\ngetCycle'' :: [Int] -> [[Int]] -> [Int] -> [Int]\ngetCycle'' [] g stack = []\ngetCycle'' (v:vs) g stack = if aCycle == []\n\t\t\t\t\t\t\tthen getCycle'' vs g stack\n\t\t\t\t\t\t\telse aCycle\n\t\t\t\t\t\t\twhere aCycle = getCycle' v g stack\n\ngetCycle' :: Int -> [[Int]] -> [Int] -> [Int]\ngetCycle' v g [] \t\t\t= \tgetCycle'' (g!!v) g [v]\ngetCycle' v g stack@(s:sx) = if elem v sx\n\t\t\t\t\t \t \tthen v:takeWhile (\\x -> not $ x == v) stack\n\t\t\t\t\t \t \telse getCycle'' (delete s $ g!!v) g (v:stack)\n\t\t\t\t\t\t\n\ngetCycle :: [[Int]] -> [Int]\ngetCycle g = getCycle' 0 g [] \n\nreachable' :: [Int] -> [[Int]] -> [Int] -> [Int]\nreachable' [] g visited = []\nreachable' (v:vs) g visited = if elem v visited \n\t\t\t\t\t\t\t \tthen []\n\t\t\t\t\t\t\t\telse fromv ++ reachable' vs g (fromv ++ visited)\n\t\t\t\t\t\t\t\twhere fromv = v:reachable' new g (v:visited); new = (g !! v) \\\\ visited\n\nreachable :: Int -> [[Int]] -> [Int]\nreachable v g = reachable' [v] g []\n\nisConnected :: [[Int]] -> Bool\nisConnected g = length g == (length $ reachable 0 g)\n\nhasSingleCycle :: [[Int]] -> Bool\nhasSingleCycle g = if aCycle == [] \n\t\t\t\t then False\n\t\t\t\t\telse [] == getCycle (dropEdge (aCycle !! 0) (aCycle !! 1) g)\n\t\t\t\t where aCycle = getCycle g\n\nisKtulhu :: [[Int]] -> Bool\nisKtulhu g = isConnected g && hasSingleCycle g\n\nparse :: String -> [Int]\nparse s = [read $ w !! 0, read $ w !! 1] where w = words s\n\n\n\nparseGraph' :: [[Int]] -> [String] -> [[Int]]\nparseGraph' g [] = g\nparseGraph' g (s:sx) = parseGraph' (addEdge (e !! 0 - 1) (e !! 1 - 1) g) sx where e = parse s\n\nparseGraph :: String -> [[Int]]\nparseGraph s = parseGraph' (replicate ((parse $ head w) !! 0) []) (tail w) where w = lines s\n\n\nktulhuState :: Bool -> String\nktulhuState ktulhu = if ktulhu then \"FHTAGN!\" else \"NO\" \n\nmain = do \n\t\tgraphData <- getContents\n\t\tputStrLn $ ktulhuState $ isKtulhu $ parseGraph $ graphData\n\t\t\n"}, {"source_code": "import Data.List\nimport Data.String\n\naddEdge' :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge' 0 b (g:gs) = ((b:g):gs)\naddEdge' a b (g:gs) = g:addEdge' (a-1) b gs\n\naddEdge :: Int -> Int -> [[Int]] -> [[Int]]\naddEdge a b g = addEdge' a b $ addEdge' b a g\n\ndropEdge' :: Int -> Int -> [[Int]] -> [[Int]]\ndropEdge' 0 b (g:gs) = (delete b g):gs \ndropEdge' a b (g:gs) = g:dropEdge' (a-1) b gs\n\ndropEdge :: Int -> Int -> [[Int]] -> [[Int]] \ndropEdge a b g = dropEdge' a b $ dropEdge' b a g\n\ngetCycle'' :: [Int] -> [[Int]] -> [Int] -> [Int]\ngetCycle'' [] g stack = []\ngetCycle'' (v:vs) g stack = if aCycle == []\n\t\t\t\t\t\t\tthen getCycle'' vs g stack\n\t\t\t\t\t\t\telse aCycle\n\t\t\t\t\t\t\twhere aCycle = getCycle' v g stack\n\ngetCycle' :: Int -> [[Int]] -> [Int] -> [Int]\ngetCycle' v g [] \t\t\t= \tgetCycle'' (g!!v) g [v]\ngetCycle' v g stack@(s:sx) = if elem v sx\n\t\t\t\t\t \t \tthen v:takeWhile (\\x -> not $ x == v) stack\n\t\t\t\t\t \t \telse getCycle'' (delete s $ g!!v) g (v:stack)\n\t\t\t\t\t\t\n\ngetCycle :: [[Int]] -> [Int]\ngetCycle g = getCycle' 0 g [] \n\nreachable' :: [Int] -> [[Int]] -> [Int] -> [Int]\nreachable' [] g visited = []\nreachable' (v:vs) g visited = if elem v visited \n\t\t\t\t\t\t\t \tthen []\n\t\t\t\t\t\t\t\telse fromv ++ reachable' vs g (fromv ++ visited)\n\t\t\t\t\t\t\t\twhere fromv = v:reachable' new g (v:visited); new = (g !! v) \\\\ visited\n\nreachable :: Int -> [[Int]] -> [Int]\nreachable v g = reachable' [v] g []\n\nisConnected :: [[Int]] -> Bool\nisConnected g = length g == (length $ reachable 0 g)\n\nhasSingleCycle :: [[Int]] -> Bool\nhasSingleCycle g = if aCycle == [] \n\t\t\t\t then False\n\t\t\t\t\telse [] == getCycle (dropEdge (aCycle !! 0) (aCycle !! 1) g)\n\t\t\t\t where aCycle = getCycle g\n\nisKtulhu :: [[Int]] -> Bool\nisKtulhu g = isConnected g && 2 * (length g) == length (concat g) \n\nparse :: String -> [Int]\nparse s = [read $ w !! 0, read $ w !! 1] where w = words s\n\nparseGraph' :: [[Int]] -> [String] -> [[Int]]\nparseGraph' g [] = g\nparseGraph' g (s:sx) = parseGraph' (addEdge (e !! 0 - 1) (e !! 1 - 1) g) sx where e = parse s\n\nparseGraph :: String -> [[Int]]\nparseGraph s = parseGraph' (replicate ((parse $ head w) !! 0) []) (tail w) where w = lines s\n\n\nktulhuState :: Bool -> String\nktulhuState ktulhu = if ktulhu then \"FHTAGN!\" else \"NO\" \n\nmain = do \n\t\tgraphData <- getContents\n\t\tputStrLn $ ktulhuState $ isKtulhu $ parseGraph $ graphData\n\t\t\n"}], "src_uid": "4ecbfc792da55f458342c6eff2d5da5a"} {"source_code": "import Data.Ord\nimport Control.Applicative \nimport Data.List\nimport Data.IntMap(IntMap,Key)\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as B\n\nmain = do n <- read <$> getLine\n rs <- map read' <$> B.words <$> B.getLine\n putStrLn $ unlines $ map (unwords.map show) $ solve n $ IM.fromList $ map (\\x -> ((fst.head) x,map snd x)) $ groupBy (\\ (i,_) (j,_) -> i==j) $ sortBy (comparing fst) $ map (\\x -> (length x,head x)) $ group $ sortBy (comparing negate) rs\n\nread' s = let Just (n,_) = B.readInt s\n in n\n\nsolve :: Int -> IntMap [Int] -> [[Int]]\nsolve _ ixs = [(length ans)]:ans\n where ans = map (sortBy (comparing negate)) $ solve' [] ixs\nsolve' :: [[Int]] -> IntMap [Int] -> [[Int]]\nsolve' rss ixs = case (f =<< f =<< f =<< (return ([],ixs))) of\n Nothing -> rss\n Just (rs@[(x,[r1]),(y,[r2]),(z,[r3])],ixs') -> solve' ([r1,r2,r3]:rss) $ foldl insert' ixs' rs\n\nf :: ([(Key,[Int])],IntMap [Int]) -> Maybe ([(Key,[Int])],IntMap [Int])\nf (kxss,ixs) = case (IM.maxViewWithKey ixs) of\n Nothing -> Nothing\n Just ((k,[x]), ixs') -> Just ((k,[x]):kxss, ixs')\n Just ((k,(x:xs)), ixs') -> Just ((k,[x]):kxss, IM.insertWith (++) k xs ixs')\n\ninsert' :: IM.IntMap [Int] -> (IM.Key,[Int]) -> IM.IntMap [Int]\ninsert' ixs (1,_) = ixs\ninsert' ixs (k,[x]) = IM.insertWith (++) (k-1) [x] ixs\n", "positive_code": [{"source_code": "import Data.Ord\nimport Control.Applicative \nimport Data.List\nimport qualified Data.IntMap as IM\n\nmain = do n <- read <$> getLine\n rs <- map read <$> words <$> getLine\n putStrLn $ unlines $ map (unwords.map show) $ solve n $ IM.fromList $ map (\\x -> ((fst.head) x,map snd x)) $ groupBy (\\ (i,_) (j,_) -> i==j) $ sortBy (comparing fst) $ map (\\x -> (length x,head x)) $ group $ sortBy (comparing negate) rs\n\nsolve :: Int -> IM.IntMap [Int] -> [[Int]]\nsolve _ ixs = [(length ans)]:ans\n where ans = map (sortBy (comparing negate)) $ solve' [] ixs\nsolve' :: [[Int]] -> IM.IntMap [Int] -> [[Int]]\nsolve' rss ixs = case (f =<< f =<< f =<< (return ([],ixs))) of\n Nothing -> rss\n Just (rs@[(x,[r1]),(y,[r2]),(z,[r3])],ixs') -> solve' ([r1,r2,r3]:rss) $ foldl insert' ixs' rs\n\nf :: ([(IM.Key,[Int])],IM.IntMap [Int]) -> Maybe ([(IM.Key,[Int])],IM.IntMap [Int])\nf (kxss,ixs) = case (IM.maxViewWithKey ixs) of\n Nothing -> Nothing\n Just ((k,[x]), ixs') -> Just ((k,[x]):kxss, ixs')\n Just ((k,(x:xs)), ixs') -> Just ((k,[x]):kxss, IM.insertWith (++) k xs ixs')\n\ninsert' :: IM.IntMap [Int] -> (IM.Key,[Int]) -> IM.IntMap [Int]\ninsert' ixs (1,_) = ixs\ninsert' ixs (k,[x]) = IM.insertWith (++) (k-1) [x] ixs\n"}], "negative_code": [{"source_code": "import Data.Ord\nimport Control.Applicative \nimport Data.List\nimport qualified Data.IntMap as IM\n\nmain = do n <- read <$> getLine\n rs <- map read <$> words <$> getLine\n putStrLn $ unlines $ map (unwords.map show) $ solve n $ IM.fromList $ map (\\x -> ((fst.head) x,map snd x)) $ groupBy (\\ (i,_) (j,_) -> i==j) $ map (\\x -> (length x,head x)) $ group $ sortBy (comparing negate) rs\n\nsolve :: Int -> IM.IntMap [Int] -> [[Int]]\nsolve _ ixs = [(length ans)]:ans\n where ans = map (sortBy (comparing negate)) $ solve' [] ixs\nsolve' :: [[Int]] -> IM.IntMap [Int] -> [[Int]]\nsolve' rss ixs = case (f =<< f =<< f =<< (return ([],ixs))) of\n Nothing -> rss\n Just (rs@[(x,[r1]),(y,[r2]),(z,[r3])],ixs') -> solve' ([r1,r2,r3]:rss) $ foldl insert' ixs' rs\n\nf :: ([(IM.Key,[Int])],IM.IntMap [Int]) -> Maybe ([(IM.Key,[Int])],IM.IntMap [Int])\nf (kxss,ixs) = case (IM.maxViewWithKey ixs) of\n Nothing -> Nothing\n Just ((k,[x]), ixs') -> Just ((k,[x]):kxss, ixs')\n Just ((k,(x:xs)), ixs') -> Just ((k,[x]):kxss, IM.insert k xs ixs')\n\ninsert' :: IM.IntMap [Int] -> (IM.Key,[Int]) -> IM.IntMap [Int]\ninsert' ixs (1,xs) = ixs\ninsert' ixs (k,xs) = IM.insert k xs ixs\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (group,sortBy)\n\nmain = do\n n <- read <$> getLine\n rs <- map read <$> words <$> getLine\n putStrLn $ solve n $ map (\\x->(length x,x)) $ group $ sortBy rev rs\n\nrev :: Int -> Int -> Ordering\nrev x y = compare (-x) (-y)\n\nsolve :: Int -> [(Int,[Int])] -> String\nsolve _ rs = unlines $ [(show n)] ++ (map (unwords.map show.sortBy rev) rs')\n where rs' = f $ sortBy (\\x y -> rev (fst x) (fst y)) rs\n n = length rs'\n\nf :: [(Int,[Int])] -> [[Int]]\nf [] = []\nf [x] = []\nf [x,y] = []\nf (xxs:yys:zzs:wss) = xyz : f xyzs'\n where xyz = map (head.snd) [xxs,yys,zzs]\n xyzs = map (\\ (i,xs) -> (pred i,tail xs)) [xxs,yys,zzs]\n xyzs' = foldl (flip insert) wss xyzs\n\ninsert :: (Int,[Int]) -> [(Int,[Int])] -> [(Int,[Int])]\ninsert (_,[]) yss = yss\ninsert (0,_) yss = yss\ninsert (i,xxs@(x:xs)) yss = zss ++ [(i,xxs)] ++ wss\n where (zss,wss) = span (\\ (k,(l:_)) -> (k>i)||((k<=i)&&(l>x))) yss\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n rs <- map read <$> words <$> getLine\n putStrLn $ solve n $ group $ sortBy (\\x y -> compare (-x) (-y)) rs\n \nsolve :: Int -> [[Int]] -> String\nsolve _ rs = unlines $ [(show n)] ++ (map (unwords.map show) rs')\n where rs' = f rs\n n = length rs'\n\nf [] = []\nf [x] = []\nf [x,y] = []\nf (xxs:yys:zzs:wss) = hxyz:(f $ (filter (not.null) txyzs)++wss)\n where hxyz = map head [xxs,yys,zzs]\n txyzs = map tail [xxs,yys,zzs]\n"}], "src_uid": "551e66a4b3da71682652d84313adb8ab"} {"source_code": "import Data.Maybe\n\ngetHalf :: Char -> Char\ngetHalf c\n | c == 'L' || c == 'R' = c\n | c == 'U' = 'D'\n | c == 'D' = 'U'\n\nsolve = do\n n <- readLnInt\n row <- getLine\n putStrLn (map getHalf row)\n\nloop 0 _ = return ()\nloop n action = do\n action\n loop (n - 1) action\n\nreadLnInt :: IO Int\nreadLnInt = readLn :: IO Int\n\nmain = do\n tests <- readLnInt\n loop tests $ do\n solve\n", "positive_code": [{"source_code": "readLnInt = readLn :: IO Int\n\nloop 0 _ = return ()\nloop n action = do\n action\n loop (n - 1) action\n\nmain = do\n t <- readLnInt\n loop t $ do\n n <- readLnInt\n s <- getLine\n putStrLn $ map (\\c -> if c == 'U' then 'D' else if c == 'D' then 'U' else c) s"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >> map f <$> getLine >>= putStrLn\n\nf 'U' = 'D'\nf 'D' = 'U'\nf c = c\n"}, {"source_code": "import Control.Monad\n\ncalc :: String -> String\ncalc [] = []\ncalc ['U'] = ['D']\ncalc ['D'] = ['U']\ncalc ('L':'R':xs) = ('L':'R':(calc xs))\ncalc ('R':'L':xs) = ('R':'L':(calc xs))\ncalc ('U':xs) = ('D':(calc xs))\ncalc ('D':xs) = ('U':(calc xs))\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n unused <- getLine\n line <- getLine\n putStrLn $ calc line\n"}, {"source_code": "solve ys [] = reverse ys\nsolve ys ('U':xs) = solve('D' : ys ) xs\nsolve ys ('D':xs) = solve ('U' : ys ) xs\nsolve ys ('L':'R':xs) = solve ('R':'L': ys ) xs\nsolve ys ('R':'L':xs) = solve ('L':'R': ys ) xs\nmain = interact $ unlines . map (solve [] . snd) . filter (odd . fst ) . zip [0..] . tail . lines \n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = str >> str\n\n-- output :: Output -> C.ByteString\noutput = C.pack\n\n-- solve :: Input -> Output\nsolve = map conv\n where\n conv 'D' = 'U'\n conv 'U' = 'D'\n conv c = c\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [{"source_code": "readLnInt = readLn :: IO Int\n\nloop 0 _ = return ()\nloop n action = do\n action\n loop (n - 1) action\n\nmain = do\n t <- readLnInt\n loop t $ do\n n <- readLnInt\n s <- getLine\n putStrLn $ map (\\c -> if c == 'U' then 'D' else c) s"}], "src_uid": "b894e16e8c00f8d97fde4a104466b3ef"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Maybe as M\nimport qualified Control.Monad.ST as ST\nimport qualified Data.List as L\nimport Control.Monad\n\ntype IGraph = A.Array Int [Int]\ntype MGraph s = ST.ST s (STArray.STArray s Int [Int])\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . M.fromMaybe 0 . fmap fst . B.readInt\n l <- replicateM (2*n) (B.getLine >>= return . map (M.fromMaybe 0 . fmap fst . B.readInt) . B.words)\n putStrLn $ solve n l\n\nsolve :: Int -> [[Int]] -> String \nsolve n l = \n if precheck g then\n findAnswer n g\n else\n \"-1\"\n where \n g = mkGraph n l\n precheck g = and [length (g A.! i) == 4 | i <- [1..n]]\n\n\nmkGraph :: Int -> [[Int]] -> IGraph\nmkGraph n l = STArray.runSTArray $ do\n g <- STArray.newArray (1,n) [] :: MGraph s\n sequence_ [write g a b | [a,b] <- l]\n return g\n where\n write g a b = do\n l <- STArray.readArray g a\n STArray.writeArray g a (b:l)\n l' <- STArray.readArray g b\n STArray.writeArray g b (a:l')\n\nfindAnswer :: Int -> IGraph -> String\nfindAnswer n g = M.fromMaybe (\"-1\") $ do \n l <- L.find (check n g) $ do \n x <- g A.! 1\n let g' = f 1 \n y <- g' A.! x\n return (dfs x y g')\n return . unwords . map show $ l\n where \n f x = A.accum (flip L.delete) g [(i,x) | i <- g A.! x]\n\n\ndfs :: Int -> Int -> IGraph -> [Int]\ndfs x y graph = ST.runST $ STArray.thaw graph >>= (\\g ->sub x y g [1])\n where \n sub :: Int -> Int -> STArray.STArray s Int [Int] -> [Int] -> ST.ST s [Int]\n sub x y g res = do\n l <- STArray.readArray g x\n sequence_ [STArray.readArray g y >>= (\\l -> STArray.writeArray g y (L.delete x l) ) | y <- l]\n next <- STArray.readArray g y \n let inter = L.intersect next (graph A.! x)\n if L.null inter then return (y:x:res) else sub y (head inter) g (x:res)\n\ncheck :: Int -> IGraph -> [Int] -> Bool\ncheck n g l \n | length l /= n = False\n | otherwise = sub n\n where\n a = A.listArray (1,n) l\n sub 0 = True\n sub k = \n let x = if k <= 2 then k - 2 + n else k - 2\n y = if k <= 1 then k - 1 + n else k - 1\n z = if k > n-1 then k - n + 1 else k + 1\n w = if k > n-2 then k - n + 2 else k + 2\n v = a A.! k\n in\n let b = elem v (g A.! (a A.! x)) && elem v (g A.! (a A.! y)) && elem v (g A.!(a A.! z)) && elem v (g A.! (a A.! w)) in\n b `seq` (b && sub (k-1))\n", "positive_code": [{"source_code": "import Data.Array\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\ncomm :: [Int] -> [Int] -> Int\ncomm [] _ = 0\ncomm _ [] = 0\ncomm a@(ah:at) b@(bh:bt) =\n case compare ah bh of\n LT -> comm at b\n EQ -> succ $ comm at bt\n GT -> comm a bt\n\nok :: [Int] -> [Int] -> Bool\nok a b = (==2) $ comm a b\n\nfromList :: Int -> [(Int, Int)] -> Array Int [Int]\nfromList n el = fmap sort $ accumArray (flip (:)) [] (1, n) $ el ++ map swap el\n\nmain :: IO ()\nmain = do\n (n:el) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let e = fromList n $ pairs el\n gao v p ret = if w == 1 || w == -1 then ret else gao w v (w:ret)\n where\n w = head $ (++[-1]) $ filter (\\i -> i /= p && ok (e!v) (e!i)) $ e!v\n ans\n | fmap length e /= listArray (1, n) (repeat 4) = []\n | n <= 8 = head $ (++[[]]) $ filter check $ permutations [1 .. n]\n | otherwise = gao 1 1 [1]\n where\n check p = (==e) $ fromList n $ zip p (rot 1 p) ++ zip p (rot 2 p)\n rot k a = let (l, r) = splitAt k a in r ++ l\n if length ans == n\n then putStrLn $ unwords $ map show $ ans\n else putStrLn \"-1\"\n"}], "negative_code": [{"source_code": "import Data.Array\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\ndiff :: [Int] -> [Int] -> [Int]\ndiff [] _ = []\ndiff a [] = a\ndiff a@(ah:at) b@(bh:bt) =\n case compare ah bh of\n LT -> ah: diff at b\n EQ -> diff at bt\n GT -> diff a bt\n\nok :: [Int] -> [Int] -> Bool\nok a b = null $ drop 2 $ diff a b\n\nfromList :: Int -> [(Int, Int)] -> Array Int [Int]\nfromList n el = fmap sort $ accumArray (flip (:)) [] (1, n) $ el ++ map swap el\n\nmain :: IO ()\nmain = do\n (n:el) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let e = fromList n $ pairs el\n gao v p ret = if w == 1 then ret else gao w v (w:ret)\n where\n w = head $ filter (\\i -> i /= p && ok (e!v) (e!i)) $ e!v\n ans\n | n <= 8 = head $ filter check $ permutations [1 .. n]\n | otherwise = gao 1 1 [1]\n where\n check p = (==e) $ fromList n $ zip p (rot 1 p) ++ zip p (rot 2 p)\n rot k a = let (l, r) = splitAt k a in r ++ l\n putStrLn $ unwords $ map show $ ans\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\ncomm :: [Int] -> [Int] -> Int\ncomm [] _ = 0\ncomm _ [] = 0\ncomm a@(ah:at) b@(bh:bt) =\n case compare ah bh of\n LT -> comm at b\n EQ -> succ $ comm at bt\n GT -> comm a bt\n\nok :: [Int] -> [Int] -> Bool\nok a b = (==2) $ comm a b\n\nfromList :: Int -> [(Int, Int)] -> Array Int [Int]\nfromList n el = fmap sort $ accumArray (flip (:)) [] (1, n) $ el ++ map swap el\n\nmain :: IO ()\nmain = do\n (n:el) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let e = fromList n $ pairs el\n gao v p ret = if w == 1 then ret else gao w v (w:ret)\n where\n w = head $ filter (\\i -> i /= p && ok (e!v) (e!i)) $ e!v\n ans\n | n <= 8 = head $ filter check $ permutations [1 .. n]\n | otherwise = gao 1 1 [1]\n where\n check p = (==e) $ fromList n $ zip p (rot 1 p) ++ zip p (rot 2 p)\n rot k a = let (l, r) = splitAt k a in r ++ l\n putStrLn $ unwords $ map show $ ans\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Maybe as M\nimport qualified Control.Monad.ST as ST\nimport qualified Data.List as L\nimport Control.Monad\n\ntype IGraph = A.Array Int [Int]\ntype MGraph s = ST.ST s (STArray.STArray s Int [Int])\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . M.fromMaybe 0 . fmap fst . B.readInt\n l <- replicateM (2*n) (B.getLine >>= return . map (M.fromMaybe 0 . fmap fst . B.readInt) . B.words)\n B.putStrLn $ solve n l\n\nsolve :: Int -> [[Int]] -> B.ByteString\nsolve n l = findAnswer n . mkGraph n $ l\n\nmkGraph :: Int -> [[Int]] -> IGraph\nmkGraph n l = STArray.runSTArray $ do\n g <- STArray.newArray (1,n) [] :: MGraph s\n sequence_ [write g a b | [a,b] <- l]\n return g\n where\n write g a b = do\n l <- STArray.readArray g a\n STArray.writeArray g a (b:l)\n l' <- STArray.readArray g b\n STArray.writeArray g b (a:l')\n\nfindAnswer :: Int -> IGraph -> B.ByteString\nfindAnswer n g = M.fromMaybe (B.pack \"-1\") $ do \n l <- L.find (check n g) $ do \n x <- g A.! 1\n y <- g A.! x\n if x == y then return [] else return (dfs x y (f x))\n return . B.unwords . map (B.pack . show ) $ l\n where \n f x = A.accum (flip L.delete) g [(i,x) | i <- g A.! x]\ndfs :: Int -> Int -> IGraph -> [Int]\ndfs x y graph = ST.runST $ STArray.thaw graph >>= (\\g ->sub x y g [])\n where \n sub :: Int -> Int -> STArray.STArray s Int [Int] -> [Int] -> ST.ST s [Int]\n sub x y g res = do\n l <- STArray.readArray g x\n sequence_ [STArray.readArray g y >>= (\\l -> STArray.writeArray g y (L.delete x l) ) | y <- l]\n next <- STArray.readArray g y \n let inter = L.intersect next (graph A.! x)\n if L.null inter then return (y:x:res) else sub y (head inter) g (x:res)\n\ncheck :: Int -> IGraph -> [Int] -> Bool\ncheck n g l \n | length l /= n = False\n | otherwise = sub 0\n where\n a = A.listArray (1,n) l\n sub 0 = True\n sub k = \n let x = if k <= 2 then k - 2 + n else k - 2\n y = if k <= 1 then k - 1 + n else k - 1\n z = if k > n-1 then k - n + 1 else k + 1\n w = if k > n-2 then k - n + 2 else k + 2\n in\n let b = elem k (g A.! x) && elem k (g A.! y) && elem k (g A.! z) && elem k (g A.! w) in\n b `seq` (b && sub (k-1))\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Maybe as M\nimport qualified Control.Monad.ST as ST\nimport qualified Data.List as L\nimport Control.Monad\n\ntype IGraph = A.Array Int [Int]\ntype MGraph s = ST.ST s (STArray.STArray s Int [Int])\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . M.fromMaybe 0 . fmap fst . B.readInt\n l <- replicateM (2*n) (B.getLine >>= return . map (M.fromMaybe 0 . fmap fst . B.readInt) . B.words)\n B.putStrLn $ solve n l\n\nsolve :: Int -> [[Int]] -> B.ByteString\nsolve n l = findAnswer n . mkGraph n $ l\n\nmkGraph :: Int -> [[Int]] -> IGraph\nmkGraph n l = STArray.runSTArray $ do\n g <- STArray.newArray (1,n) [] :: MGraph s\n sequence_ [write g a b | [a,b] <- l]\n return g\n where\n write g a b = do\n l <- STArray.readArray g a\n STArray.writeArray g a (b:l)\n l' <- STArray.readArray g b\n STArray.writeArray g b (a:l')\n\n\n\nfindAnswer :: Int -> IGraph -> B.ByteString\nfindAnswer n g = M.fromMaybe (B.pack \"-1\") $ do \n l <- L.find (check n g) [dfs 1 x g | x <- g A.! 1]\n return . B.unwords . map (B.pack . show ) $ l\n\ndfs :: Int -> Int -> IGraph -> [Int]\ndfs x y graph = ST.runST $ STArray.thaw graph >>= (\\g ->sub x y g [])\n where \n sub :: Int -> Int -> STArray.STArray s Int [Int] -> [Int] -> ST.ST s [Int]\n sub x y g res = do\n l <- STArray.readArray g x\n sequence_ [STArray.readArray g y >>= (\\l -> STArray.writeArray g y (L.delete x l) ) | y <- l]\n next <- STArray.readArray g y \n let inter = L.intersect next (graph A.! x)\n if L.null inter then return (y:x:res) else sub y (head inter) g (x:res)\n\ncheck :: Int -> IGraph -> [Int] -> Bool\ncheck n g l \n | length l /= n = False\n | otherwise = sub 0\n where\n a = A.listArray (1,n) l\n sub 0 = True\n sub k = \n let x = if k <= 2 then k - 2 + n else k - 2\n y = if k <= 1 then k - 1 + n else k - 1\n z = if k > n-1 then k - n + 1 else k + 1\n w = if k > n-2 then k - n + 2 else k + 2\n in\n let b = elem k (g A.! x) && elem k (g A.! y) && elem k (g A.! z) && elem k (g A.! w) in\n b `seq` (b && sub (k-1))\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Maybe as M\nimport qualified Control.Monad.ST as ST\nimport qualified Data.List as L\nimport Control.Monad\n\ntype IGraph = A.Array Int [Int]\ntype MGraph s = ST.ST s (STArray.STArray s Int [Int])\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . M.fromMaybe 0 . fmap fst . B.readInt\n l <- replicateM (2*n) (B.getLine >>= return . map (M.fromMaybe 0 . fmap fst . B.readInt) . B.words)\n B.putStrLn $ solve n l\n\nsolve :: Int -> [[Int]] -> B.ByteString\nsolve n l = findAnswer n . mkGraph n $ l\n\nmkGraph :: Int -> [[Int]] -> IGraph\nmkGraph n l = STArray.runSTArray $ do\n g <- STArray.newArray (1,n) [] :: MGraph s\n sequence_ [write g a b | [a,b] <- l]\n return g\n where\n write g a b = do\n l <- STArray.readArray g a\n STArray.writeArray g a (b:l)\n l' <- STArray.readArray g b\n STArray.writeArray g b (a:l')\n\n\n\nfindAnswer :: Int -> IGraph -> B.ByteString\nfindAnswer n g = M.fromMaybe (B.pack \"-1\") $ do \n l <- L.find (check n g) [dfs 1 x g | x <- g A.! 1]\n return . B.unwords . map (B.pack . show ) $ l\n\ndfs :: Int -> Int -> IGraph -> [Int]\ndfs x y graph = ST.runST $ STArray.thaw graph >>= (\\g ->sub x y g [])\n where \n sub :: Int -> Int -> STArray.STArray s Int [Int] -> [Int] -> ST.ST s [Int]\n sub x y g res = do\n l <- STArray.readArray g x\n sequence_ [STArray.readArray g y >>= (\\l -> STArray.writeArray g y (L.delete x l) ) | y <- l]\n next <- STArray.readArray g y \n let inter = L.intersect next (graph A.! x)\n if L.null inter then return (y:x:res) else sub y (head inter) g (x:res)\n\ncheck :: Int -> IGraph -> [Int] -> Bool\ncheck n g l \n | length l /= n = False\n | otherwise = True\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Maybe as M\nimport qualified Control.Monad.ST as ST\nimport qualified Data.List as L\nimport Control.Monad\n\ntype IGraph = A.Array Int [Int]\ntype MGraph s = ST.ST s (STArray.STArray s Int [Int])\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . M.fromMaybe 0 . fmap fst . B.readInt\n l <- replicateM (2*n) (B.getLine >>= return . map (M.fromMaybe 0 . fmap fst . B.readInt) . B.words)\n B.putStrLn $ solve n l\n\nsolve :: Int -> [[Int]] -> B.ByteString\nsolve n l = findAnswer n . mkGraph n $ l\n\nmkGraph :: Int -> [[Int]] -> IGraph\nmkGraph n l = STArray.runSTArray $ do\n g <- STArray.newArray (1,n) [] :: MGraph s\n sequence_ [write g a b | [a,b] <- l]\n return g\n where\n write g a b = do\n l <- STArray.readArray g a\n STArray.writeArray g a (b:l)\n l' <- STArray.readArray g b\n STArray.writeArray g b (a:l')\n\nfindAnswer :: Int -> IGraph -> B.ByteString\nfindAnswer n g = M.fromMaybe (B.pack \"-1\") $ do \n l <- L.find (check n g) $ do \n x <- g A.! 1\n y <- g A.! x\n if x == y then return [] else return (dfs x y (f x))\n return . B.unwords . map (B.pack . show ) $ l\n where \n f x = A.accum (flip L.delete) g [(i,x) | i <- g A.! x]\ndfs :: Int -> Int -> IGraph -> [Int]\ndfs x y graph = ST.runST $ STArray.thaw graph >>= (\\g ->sub x y g [])\n where \n sub :: Int -> Int -> STArray.STArray s Int [Int] -> [Int] -> ST.ST s [Int]\n sub x y g res = do\n l <- STArray.readArray g x\n sequence_ [STArray.readArray g y >>= (\\l -> STArray.writeArray g y (L.delete x l) ) | y <- l]\n next <- STArray.readArray g y \n let inter = L.intersect next (graph A.! x)\n if L.null inter then return (y:x:res) else sub y (head inter) g (x:res)\n\ncheck :: Int -> IGraph -> [Int] -> Bool\ncheck n g l \n | length l /= n = False\n | otherwise = sub 0\n where\n a = A.listArray (1,n) l\n sub 0 = True\n sub k = \n let x = if k <= 2 then k - 2 + n else k - 2\n y = if k <= 1 then k - 1 + n else k - 1\n z = if k > n-1 then k - n + 1 else k + 1\n w = if k > n-2 then k - n + 2 else k + 2\n v = a A.! k\n in\n let b = elem v (g A.! x) && elem v (g A.! y) && elem v (g A.! z) && elem v (g A.! w) in\n b `seq` (b && sub (k-1))\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Maybe as M\nimport qualified Control.Monad.ST as ST\nimport qualified Data.List as L\nimport Control.Monad\n\ntype IGraph = A.Array Int [Int]\ntype MGraph s = ST.ST s (STArray.STArray s Int [Int])\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . M.fromMaybe 0 . fmap fst . B.readInt\n l <- replicateM (2*n) (B.getLine >>= return . map (M.fromMaybe 0 . fmap fst . B.readInt) . B.words)\n putStrLn $ solve n l\n\nsolve :: Int -> [[Int]] -> String \nsolve n l = findAnswer n . mkGraph n $ l\n\nmkGraph :: Int -> [[Int]] -> IGraph\nmkGraph n l = STArray.runSTArray $ do\n g <- STArray.newArray (1,n) [] :: MGraph s\n sequence_ [write g a b | [a,b] <- l]\n return g\n where\n write g a b = do\n l <- STArray.readArray g a\n STArray.writeArray g a (b:l)\n l' <- STArray.readArray g b\n STArray.writeArray g b (a:l')\n\nfindAnswer :: Int -> IGraph -> String\nfindAnswer n g = M.fromMaybe (\"-1\") $ do \n l <- L.find (check n g) $ do \n x <- g A.! 1\n let g' = f x \n y <- g' A.! x\n if y == 1 then return [] else return (dfs x y g')\n return . unwords . map show $ l\n where \n f x = A.accum (flip L.delete) g [(i,x) | i <- g A.! x]\n\n\ndfs :: Int -> Int -> IGraph -> [Int]\ndfs x y graph = ST.runST $ STArray.thaw graph >>= (\\g ->sub x y g [1])\n where \n sub :: Int -> Int -> STArray.STArray s Int [Int] -> [Int] -> ST.ST s [Int]\n sub x y g res = do\n l <- STArray.readArray g x\n sequence_ [STArray.readArray g y >>= (\\l -> STArray.writeArray g y (L.delete x l) ) | y <- l]\n next <- STArray.readArray g y \n let inter = L.intersect next (graph A.! x)\n if L.null inter then return (y:x:res) else sub y (head inter) g (x:res)\n\ncheck :: Int -> IGraph -> [Int] -> Bool\ncheck n g l \n | length l /= n = False\n | otherwise = sub n\n where\n a = A.listArray (1,n) l\n sub 0 = True\n sub k = \n let x = if k <= 2 then k - 2 + n else k - 2\n y = if k <= 1 then k - 1 + n else k - 1\n z = if k > n-1 then k - n + 1 else k + 1\n w = if k > n-2 then k - n + 2 else k + 2\n v = a A.! k\n in\n let b = elem v (g A.! (a A.! x)) && elem v (g A.! (a A.! y)) && elem v (g A.!(a A.! z)) && elem v (g A.! (a A.! w)) in\n b `seq` (b && sub (k-1))\n"}], "src_uid": "41ece21ebd61bf98a3ec8bd4a932cf03"} {"source_code": "import Control.Arrow ((>>>))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> chunksOf 4 >>> map (drop 1 >>> map (words >>> map read) >>> solve >>> show) >>> unlines\r\n\r\nsolve :: [[Int]] -> Int\r\nsolve [[xa, ya], [xb, yb], [xf, yf]]\r\n | xa == xf && xf == xb && min ya yb <= yf && yf <= max ya yb = gap + 2\r\n | ya == yf && yf == yb && min xa xb <= xf && xf <= max xa xb = gap + 2\r\n | otherwise = gap\r\n where\r\n gap = abs (xa - xb) + abs (ya - yb)\r\n", "positive_code": [{"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n \"\" <- getLine\r\n replicateM 3 readIListLn\r\n\r\nreadIListLn = map read <$> words <$> getLine :: IO [Int]\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve [[ax,ay], [bx,by], [fx,fy]] = show $ dx + dy + obstacle\r\n where\r\n minX = min ax bx\r\n minY = min ay by\r\n maxX = max ax bx\r\n maxY = max ay by\r\n dx = maxX - minX\r\n dy = maxY - minY\r\n obstacle | (isCLine && isBetween) = 2 | otherwise = 0\r\n isCLine = (dx == 0) || (dy == 0)\r\n isBetween = (minX <= fx && fx <= maxX && minY <= fy && fy <= maxY)\r\nsolve _ = error \"Bad TC input\"\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\ncalcDistance [xa, ya] [xb, yb] [xf, yf]\r\n | xf == xa && xa == xb &&\r\n min ya yb < yf && yf < max ya yb\r\n = 2 + normalDistance\r\n | yf == ya && ya == yb &&\r\n min xa xb < xf && xf < max xa xb\r\n = 2 + normalDistance\r\n | otherwise = normalDistance\r\n where normalDistance = abs (xa - xb) + abs (ya - yb)\r\ncalcDistance _ _ _ = error \"Should never happen\"\r\n\r\nmain = do\r\n t <- getInt\r\n replicateM_ t $ do\r\n _ <- getLine\r\n a <- getInts\r\n b <- getInts\r\n f <- getInts\r\n print $ calcDistance a b f\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map read . words <$> getLine \r\n\r\nsolve [xa, ya] [xb, yb] [xf, yf]\r\n | dx > 0 && dy > 0 = dx + dy\r\n | dy == 0 = if yf == ya && xf `inRange` mkRange xa xb then dx + 2 else dx\r\n | otherwise = if xf == xa && yf `inRange` mkRange ya yb then dy + 2 else dy\r\n where\r\n dx = abs (xa - xb)\r\n dy = abs (ya - yb)\r\n mkRange a b = [min a b + 1, max a b - 1]\r\n inRange x [l, r] = x >= l && x <= r\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n getLine\r\n a <- readInts\r\n b <- readInts\r\n f <- readInts\r\n print $ solve a b f\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n getLine\n [xa, ya] <- getIntList\n [xb, yb] <- getIntList\n [xc, yc] <- getIntList\n let d = abs (xa - xb) + abs (ya - yb)\n print $ if xa /= xb && ya /= yb\n then d\n else if xc == xa && xc == xb && yc > min ya yb && yc < max ya yb\n then d + 2\n else if yc == ya && yc == yb && xc > min xa xb && xc < max xa xb\n then d + 2\n else d\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\nsolve :: IO ()\nsolve = do\n [_, sa, sb, sf] <- sequence $ replicate 4 getLine\n let [xa, ya] = getints sa\n [xb, yb] = getints sb\n [xf, yf] = getints sf\n oneline = (xa == xb && xb == xf && yf > min ya yb && yf < max ya yb)\n || (ya == yb && yb == yf && xf > min xa xb && xf < max xa xb)\n dist = abs (xa-xb) + abs (ya-yb)\n res = (if oneline then dist + 2 else dist)\n in print res\n where getints s = map read $ words s :: [Int]\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int] \r\n \r\nprintResult = do\r\n nothing <- getLine\r\n [xa,ya] <- readInts\r\n [xb,yb] <- readInts\r\n [xf,yf] <- readInts\r\n print $ abs(xa-xb) + abs(ya-yb) + if (xa == xb && xa == xf && (ya-yf)*(yb-yf) < 0) || (ya == yb && ya == yf && (xa-xf)*(xb-xf) < 0) then 2 else 0\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "negative_code": [], "src_uid": "6422d76f71702e77808b1cc041962bb8"} {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Array\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Monoid\nimport Data.Maybe\nimport Text.Printf\n\ndata Max = Max { maxValue :: Int } deriving (Ord, Eq)\ndata Min = Min { minValue :: Int } deriving (Ord, Eq)\n\ninstance Monoid Min where\n\tmempty = Min maxBound\n\tmappend = min\n\ninstance Monoid Max where\n\tmempty = Max minBound\n\tmappend = max\n\nbuild list = tree \n\twhere\n\t\tn = length list\n\t\ttree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list\n\t\tvalue i = tree ! (2*i) <> tree ! (2*i + 1)\n\nquery tree l r = query' (l + n - 1) (r + n - 1)\n\twhere\n\t\tn = snd (bounds tree) `div` 2 + 1\n\n\t\tquery' l r\n\t\t\t| l > r = mempty\n\t\t\t| odd l = (tree ! l) <> query' (l + 1) r\n\t\t\t| even r = query' l (r - 1) <> (tree ! r)\n\t\t\t| otherwise = query' (l `div` 2) (r `div` 2)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t[n, k] \u2190 getInts\n\tas \u2190 getInts\n\n\tlet maxTree = build $ map Max as\n\tlet minTree = build $ map Min as\n\n\tlet diff i j = maxValue (query maxTree i j) - minValue (query minTree i j)\n\n\tlet maxBooksCount i j\n\t\t| i == n + 1 = 1\n\t\t| otherwise = max (j' - i + 1) (maxBooksCount (i + 1) j')\n\t\t\twhere\n\t\t\t\tj' = last $ takeWhile (\\j'' \u2192 diff i j'' <= k) [(max i j)..n]\n\n\tlet m = maxBooksCount 1 1\n\n\tlet is = [(i, j) | i \u2190 [1..n], let j = i + m - 1, j <= n, diff i j <= k]\n\n\tprintf \"%d %d\\n\" m (length is)\n\tsequence $ map (uncurry $ printf \"%d %d\\n\") is", "positive_code": [{"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Data.Maybe (fromJust)\nimport Control.Monad (forM_)\nimport Data.Array.Unboxed\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n [n, k] <- ints\n hs <- listArray (1, n) <$> ints\n let (m, series) = solve hs k\n p (m, length series)\n forM_ series p\n where\n p (a, b) = putStrLn $ show a <> \" \" <> show b\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nsolve :: UArray Int Int -> Int -> (Int, [(Int, Int)])\nsolve hs k = go (from, from + 1) (0, []) $ S.singleton (hs ! from, from)\n where\n (from, to) = bounds hs\n n = to - from + 1\n\n update i@(l, r) res@(m, s)\n | p > m = (p, [i])\n | p == m = (m, i:s)\n | otherwise = res\n where p = r - l + 1\n\n go (l, r) res acc\n | r > to = commitPred\n | fst (S.findMax accR) - fst (S.findMin accR) <= k = go (l, r + 1) res accR\n | otherwise = go (l + 1, r) commitPred (S.delete (hs ! l, l) accR)\n where\n commitPred = update (l, r - 1) res\n accR = S.insert (hs ! r, r) acc"}], "negative_code": [], "src_uid": "bc8b4b74c2f2d486e2d2f03982ef1013"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.Bits\nimport qualified Data.ByteString.Lazy as B\nimport qualified Data.ByteString.Lazy.Char8 as BC\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n\nbread = fst . fromJust . BC.readInt\n\nsolve (n, xs) =\n let (r, _, _) =\n foldl' solve' (0, 0, S.fromList [0]) (map bread $ BC.words xs)\n in BC.pack $ show $ bread n - r\n where\n solve' :: (Int, Int, S.Set Int) -> Int -> (Int, Int, S.Set Int)\n solve' (c, xr, s) x = (c', xr', xr' `S.insert` s')\n where\n xr' = xr `xor` x\n (c', s') = if xr' `S.member` s then (c + 1, S.empty) else (c, s)\n\npairs (x : y : xs) = (x, y) : pairs xs\npairs _ = []\n\nmain = B.interact $ BC.unlines . map solve . pairs . tail . BC.lines\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.Bits\nimport Data.List\nimport qualified Data.Set as S\n\nsolve :: (String, String) -> String\nsolve (n, xs) =\n let (r, _, _) =\n foldl' solve' (0, 0, S.fromList [0]) (map read $ words xs)\n in show $ read n - r\n where\n solve' :: (Int, Int, S.Set Int) -> Int -> (Int, Int, S.Set Int)\n solve' (c, xr, s) x = (c', xr', xr' `S.insert` s')\n where\n xr' = xr `xor` x\n (c', s') = if xr' `S.member` s then (c + 1, S.empty) else (c, s)\n\npairs (x : y : xs) = (x, y) : pairs xs\npairs _ = []\n\nmain = interact $ unlines . map solve . pairs . tail . lines\n"}], "negative_code": [], "src_uid": "ec17f2c7abd7c0e3da96b99ddd8489d5"} {"source_code": "{-# LANGUAGE MultiWayIf #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n n <- read <$> getLine :: IO Int\n a0 : a1 : a2 : as <- map read . words <$> getLine :: IO [Int]\n let\n (x0, i0, y0, j0, z0, k0)\n | a0 <= a1 = if\n | a1 <= a2 -> (a0, 1, a1, 2, a2, 3)\n | a0 <= a2 -> (a0, 1, a2, 3, a1, 2)\n | otherwise -> (a2, 3, a0, 1, a1, 2)\n | a0 <= a2 = (a1, 2, a0, 1, a2, 3)\n | a1 <= a2 = (a1, 2, a2, 3, a0, 1)\n | otherwise = (a2, 3, a1, 2, a0, 1)\n\n (x, i, y, j, z, k) = foldl' f (x0, i0, y0, j0, z0, k0) $ zip as [4..]\n f (x, i, y, j, z, k) (a, l)\n | a > z = (x, i, y, j, a, l)\n | a < x = (a, l, x, i, z, k)\n | a < y = (x, i, a, l, z, k)\n f xxx _ = xxx\n\n if x + y <= z then\n putStrLn $ show i ++ \" \" ++ show j ++ \" \" ++ show k\n else\n putStrLn \"-1\"\n", "positive_code": [{"source_code": "input :: IO [Int]\ninput = do\n line <- getLine\n return (map read (words line))\n\nsolve 0 = do return ()\n\nsolve t = do\n [n] <- input\n a <- input\n putStrLn $\n if a !! 0 + a !! 1 <= a !! (n - 1)\n then \"1 2 \" ++ show n\n else \"-1\"\n solve (t - 1)\n\nmain = do\n [n] <- input\n solve n\n"}, {"source_code": "import Data.List\n\nconvertToInt :: String -> Int\nconvertToInt = read\n\nreadOneInt :: IO Int\nreadOneInt = do\n line_ <- getLine\n return $ convertToInt line_\n\nreadLineInts :: IO [Int]\nreadLineInts = do\n line_ <- getLine\n return $ map convertToInt $ words line_ \n\nconvertIntsToLine :: [Int] -> String\nconvertIntsToLine [] = \"\"\nconvertIntsToLine (x:xs) = (show x) ++ \" \" ++ (convertIntsToLine xs)\n\nmain :: IO ()\nmain = do\n -- read t\n t <- readOneInt\n for t where\n for 0 = return ()\n for t' = do\n _ <- readOneInt\n ints <- readLineInts\n let nums = zip ints [1,2..]\n let sorted = sortBy (\\(a,_) (b,_) -> compare a b) nums\n let (alpha:beta:last_) = sorted\n let theta = last last_\n putStrLn $ if (fst alpha) + (fst beta) <= (fst theta)\n then convertIntsToLine $ sort (snd (unzip [alpha, beta, theta]))\n else \"-1\"\n for (t'-1)"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n as <- (map read.words) <$> getLine\n (putStrLn.unwords.map show) $ solve n as\n\nsolve :: Int -> [Int] -> [Int]\nsolve n (a:a':as)\n | a+a' > last as = [-1]\n | otherwise = [1,2,n]\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n\nimport Data.List\n\nsolveOne :: [Int] -> String\nsolveOne (splitAt 2 -> (s, e)) = maybe \"-1\" ((\"1 2 \" ++) . show . (+3)) $ findIndex (>= sum s) e\n\nmain = interact $ unlines . fmap (solveOne . fmap read . words) . evens . tail . lines\n\nevens (_:x:xs) = x:evens xs\nevens a = a"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n solveCases t\nsolveCases :: Int -> IO ()\nsolveCases 0 = return ()\nsolveCases t = do\n (n, a) <- readCaseData\n putStrLn $ intercalate \" \" $ map show $ getTestCaseAnswer n a\n solveCases (t - 1)\nreadCaseData :: IO (Int, [Int])\nreadCaseData = do\n n <- readLn :: IO Int\n a <- getLine\n return (n, map read (words a))\ncheckArray :: Int -> [Int] -> Bool\ncheckArray n a = x + y <= z\n where x = a !! 0\n y = a !! 1\n z = a !! (n - 1)\ngetTestCaseAnswer :: Int -> [Int] -> [Int]\ngetTestCaseAnswer n a = if checkArray n a\n then [1, 2, n]\n else [-1]"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nisTriangle :: (Int, Int, Int) -> Bool\nisTriangle (a, b, c) = c < (a + b)\n\nsolve :: [Int] -> Maybe (Int, Int, Int)\nsolve as = \n if isTriangle triple\n then Nothing\n else Just tripleIndices\n where\n tripleIndices = (1, 2, length as)\n triple = (as !! 0, as !! 1, last as)\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n as <- map readIntB8 <$> B8.words <$> B8.getLine\n let answer = solve as\n case answer of\n Just (i, j, k) -> printf \"%d %d %d\\n\" i j k\n _ -> printf \"-1\\n\"\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve :: String -> String\nsolve input = intercalate \"\\n\" answers\n where\n t:rest = map fastRead $ words input\n t :: Int64\n problems = inputreader rest\n answers = map (answerformat . innersolve) problems\n\nanswerformat :: Maybe (Int64,Int64,Int64) -> String\nanswerformat Nothing = \"-1\"\nanswerformat (Just (a, b, c)) = (show a) ++ \" \" ++ (show b) ++ \" \" ++ (show c)\n\ninputreader :: [Int64] -> [(Int64, [Int64])]\ninputreader [] = []\ninputreader (x:xs) = ((x,cur)):(inputreader after)\n where\n (cur,after) = splitAt (fromIntegral x) xs\n\ninnersolve :: (Int64,[Int64]) -> Maybe (Int64,Int64,Int64)\ninnersolve (_,xs) \n | a+b <= c = Just (1,2,fromIntegral $ length xs)\n | otherwise = Nothing\n where\n a:b:_ = xs\n c = last xs\n"}, {"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> [Int]\nsolve p@(x:y:xs) \n | length xs < 1 = [-1, -1, -1]\n | x + y <= last xs = [1, 2, length p] \n | otherwise = [-1, -1, -1]\n\noutput :: [Int] -> [String]\noutput [-1, -1, -1] = [\"-1\"]\noutput xs = map show xs\n\nmyshow :: [String] -> String\nmyshow (x:xs) \n | null xs = x \n | otherwise = x ++ \" \" ++ myshow xs\n\ndeal :: IO()\ndeal = do \n getLine\n x <- map read . words <$> getLine\n putStrLn $ myshow $ output $ solve x\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications, ViewPatterns #-}\n\nimport Data.List\n\nsolveOne :: [Int] -> String\nsolveOne (splitAt 2 -> (s, e)) = maybe \"-1\" ((\"0 1 \" ++) . show . (+2)) $ findIndex (>= sum s) e\n\nmain = interact $ unlines . fmap (solveOne . fmap read . words) . evens . tail . lines\n\nevens (_:x:xs) = x:evens xs\nevens a = a"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve :: String -> String\nsolve input = intercalate \"\\n\" answers\n where\n t:rest = map fastRead $ words input\n t :: Int64\n problems = inputreader rest\n answers = map (answerformat . innersolve) problems\n\nanswerformat :: Maybe (Int64,Int64,Int64) -> String\nanswerformat Nothing = \"-1\"\nanswerformat (Just (a, b, c)) = (show a) ++ \" \" ++ (show b) ++ \" \" ++ (show c)\n\ninputreader :: [Int64] -> [(Int64, [Int64])]\ninputreader [] = []\ninputreader (x:xs) = ((x,cur)):(inputreader after)\n where\n (cur,after) = splitAt (fromIntegral x) xs\n\ninnersolve :: (Int64,[Int64]) -> Maybe (Int64,Int64,Int64)\ninnersolve (_,xs) \n | a+b < c = Just (1,2,fromIntegral $ length xs)\n | otherwise = Nothing\n where\n a:b:_ = xs\n c = last xs\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve :: String -> String\nsolve input = intercalate \"\\n\" answers\n where\n t:rest = map fastRead $ words input\n t :: Int64\n problems = inputreader rest\n answers = map (answerformat . innersolve) problems\n\nanswerformat :: Maybe (Int64,Int64,Int64) -> String\nanswerformat Nothing = \"-1\"\nanswerformat (Just (a, b, c)) = (show a) ++ \" \" ++ (show b) ++ \" \" ++ (show c)\n\ninputreader :: [Int64] -> [(Int64, [Int64])]\ninputreader [] = []\ninputreader (x:xs) = ((x,cur)):(inputreader after)\n where\n (cur,after) = splitAt (fromIntegral x) xs\n\ninnersolve :: (Int64,[Int64]) -> Maybe (Int64,Int64,Int64)\ninnersolve (_,xs) \n | a+b < c = Just (a,b,c)\n | otherwise = Nothing\n where\n a:b:_ = xs\n c = last xs\n"}], "src_uid": "341555349b0c1387334a0541730159ac"} {"source_code": "solve :: Int -> IO ()\r\nsolve _ = do\r\n s <- getLine\r\n let cnt_a = length . filter (== 'A') $ s\r\n cnt_b = length . filter (== 'B') $ s\r\n cnt_c = length . filter (== 'C') $ s\r\n if (cnt_a + cnt_c == cnt_b) then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\nmain = do \r\n tc <- getLine\r\n let testcase = read tc :: Int\r\n mapM_ solve [1..testcase]\r\n\r\n", "positive_code": [{"source_code": "import Control.Monad ( replicateM_ )\r\nsolve = do\r\n x <- getLine \r\n putStrLn $ if length x == 2 * (length . filter (== 'B') $ x) then \"YES\" else \"NO\"\r\n\r\nmain = readLn >>= flip replicateM_ solve"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: String -> String\ncalc str =\n let (a,b,c) = foldl (\\(a,b,c) x ->\n if x == 'A' then (a+1,b,c)\n else if x == 'B' then (a,b+1,c)\n else (a,b,c+1)\n ) (0,0,0) str\n in\n if (a+c) == b then \"YES\"\n else \"NO\"\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n putStrLn $ calc line\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\nimport Prelude\nimport System.IO\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n\n t <- readLn\n tcs <- replicateM t getLine\n\n (putStrLn . unlines . map (showB . solve)) tcs\n\nshowB False = \"NO\"\nshowB True = \"YES\"\n\nsolve = f . map (flip (-) 1 . length) . group . sort . (++ \"ABC\")\n where\n f :: [Int] -> Bool\n f [a, b, c] = (b == a + c)\n f _ = error \"letter set\"\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n s <- getLine\n putStrLn . yesOrNo $ (c 'B' s == c 'A' s + c 'C' s)\n\nc :: (Eq a) => a -> [a] -> Int\nc e = length . filter (e ==)\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[s] <- getNext 1\n let\n [ctA, ctB, ctC] = [P.count c s | c <- \"ABC\"]\n pure $ string7 $ if ctA + ctC == ctB\n then \"YES\\n\"\n else \"NO\\n\"\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": " main=let a=length.(filter(=='A'))\r\n b=length.(filter(=='B'))\r\n c=length.(filter(=='C'))\r\n a2bc x=if a x + c x - b x==0 then \"YES\" else \"NO\"\r\n in interact$unlines.map a2bc.tail.lines"}, {"source_code": "count :: Eq a => a -> [a] -> Int\r\ncount x = length . filter (x ==)\r\n\r\nsolve :: Int -> IO ()\r\nsolve _ = do\r\n s <- getLine\r\n putStrLn $ if (count 'A' s) + (count 'C' s) == (count 'B' s) then \"YES\" else \"NO\"\r\n\r\nmain = do\r\n t <- read <$> getLine :: IO Int\r\n mapM_ solve [1..t]"}], "negative_code": [], "src_uid": "ca6b162f945d4216055bf92d7263dbd5"} {"source_code": "--ghc 7.10\n\nimport Data.List(findIndices)\n\noperate :: (Int,Int,Char,Char) -> String -> String\noperate (l,r,c1,c2) str = map (\\(i,c) -> if c == c1 && i >= l && i <= r then c2 else c) . zip [1..] $ str\n\noperateAll operands str = foldl (\\acc x -> operate x acc) str operands\n\nreadLine x = (l,r,c1,c2)\n where\n [l',r',c1',c2'] = words x\n l = read l' :: Int\n r = read r' :: Int\n c1 = head c1'\n c2 = head c2'\n \nmain = do\n nmStr <- getLine\n let [n,m] = map read . words $ nmStr :: [Int]\n s <- getLine\n contents <- getContents\n let operands = map readLine . lines $ contents\n putStrLn $ operateAll operands s", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad\nmain = do\n [n,m] <- map read . words <$> getLine\n s <- listArray (1,n) <$> getLine\n s' <- foldl f s <$> replicateM m getLine\n putStrLn (elems s')\nf s ws = s // map g [read l..read r] where\n [l,r,[c1],[c2]] = words ws\n g i | v == c1 = (i,c2)\n | otherwise = (i,v)\n where v = s!i\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Text as T\n\nprocess s [l,r,c1,c2] = T.concat [(T.take (ll-1) s) , (T.replace (T.pack c1) (T.pack c2) (T.drop (ll-1) (T.take rr s)) ) , T.drop (rr) s] \n\twhere\tll= read l ::Int\n\t\trr= read r ::Int\n\t\t\n\nmain= do\n\t\t[n,m]<- map read <$> words <$> getLine ::IO [Int]\n\t\ts<- T.pack <$> getLine\n\t\tc<- map words <$> replicateM m getLine\n\t\tputStrLn$ T.unpack $ foldl process s c\n\n"}, {"source_code": "\nmain = interact $ unlines . parse . lines\n\nparse (_:s:ops') = sol s ops\n where\n ops = map (fn . words) ops'\n fn :: [String] -> (Int, Int, Char, Char)\n fn [b, e, f, t] = (read b, read e, head f, head t)\n\nsol s ops = [ foldl makeOp s ops ]\n where\n makeOp :: String -> (Int, Int, Char, Char) -> String\n makeOp s (b, e, f, t) = let\n (tmp, end) = splitAt e s\n (beg, mid) = splitAt (b-1) tmp\n midr = map replacer mid\n replacer x = if x == f then t else x\n in beg ++ midr ++ end\n"}], "negative_code": [], "src_uid": "3f97dc063286a7af4838b7cd1c01df69"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Ix\nimport Data.Char\nimport Text.Printf\nimport qualified Data.List as L\nimport qualified Data.Array as A\n\nmain :: IO()\nmain = do l <- B.getLine\n putStrLn $ solve l\n\nsolve :: B.ByteString -> String\nsolve = mkDate . snd . last . L.sort . map mkPair . L.group . L.sort . filter correctDate . findDates\n\nfindDates :: B.ByteString -> [(Int,Int,Int)]\nfindDates = L.foldl' accum [] . B.tails\n where \n accum e str = case match str of\n Nothing -> e\n Just date -> date:e\n match str = do day <- matchDay token0\n month <- matchMonth token1\n year <- matchYear token2\n return (day,month,year)\n where (token0,str1) = B.span (/='-') str\n (token1,str2) = B.span (/='-') (if B.length str1 > 0 then B.tail str1 else B.empty)\n token2 = B.take 4 (if B.length str2 > 0 then B.tail str2 else B.empty)\n matchDay = matchToken 2\n matchMonth = matchToken 2\n matchYear = matchToken 4 . B.take 4 \n matchToken n str | B.length str == n && B.all isDigit str = Just (B.foldl' (\\ x c -> x*10+ digitToInt c) 0 str)\n | otherwise = Nothing\n \n\ncorrectDate :: (Int,Int,Int) -> Bool\ncorrectDate (day,month,year) = correctDayAndMonth month day && correctYear year\n\ncorrectDayAndMonth month day = inRange (1,12) month && inRange (1,calendar A.! month) day\n where calendar = A.array (1,12) [(1,31),(2,28),(3,31),(4,30),(5,31),(6,30),\n (7,31),(8,31),(9,30),(10,31),(11,30),(12,31)]\n\ncorrectYear = inRange (2013,2015)\n\nmkPair :: [(Int,Int,Int)] -> (Int,(Int,Int,Int))\nmkPair l = (length l,head l)\n\nmkDate :: (Int,Int,Int) -> String\nmkDate (day,month,year) = printf \"%02d-%02d-%04d\" day month year\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ndom :: UArray Int Int\ndom = listArray (1,12) [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nparse :: C.ByteString -> Maybe C.ByteString\nparse s =\n if C.elemIndices '-' s == [2, 5]\n && 2013 <= y && y <= 2015\n && 1 <= m && m <= 12\n && 1 <= d && d <= dom!m\n then Just s\n else Nothing\n where\n readInt = maybe 0 fst . C.readInt\n [d, m, y] = map readInt $ C.split '-' s\n\nmain :: IO ()\nmain = do\n input <- C.getLine\n let date = catMaybes $ map (parse . C.take 10) $ C.tails input\n C.putStrLn $ snd $ maximum $ map (liftA2 (,) length head) $ group $ sort $ date\n\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Map (assocs, empty, insertWith, singleton)\nimport Data.Char (ord)\nimport Data.List (intercalate, maximumBy)\n\nsolve :: String -> String\nsolve s = solve' empty s\n where\n solve' map \"\" = fst $ maximumBy compareSnd $ assocs map\n solve' map ss@(d1:d2:'-':m1:m2:'-':y1:y2:y3:y4:s)\n | any (== '-') [d1, d2, m1, m2, y1, y2, y3, y4] = solve' map (tail ss)\n | correctDate y m d = solve' map' $ tail ss\n | otherwise = solve' map $ tail ss\n where\n d = read [d1, d2]\n m = read [m1, m2]\n y = read [y1, y2, y3, y4]\n map' = insertWith (+) (take 10 ss) 1 map\n solve' map ss = solve' map $ tail ss\n compareSnd (a, b) (c, d) = compare b d\n correctDate y m d\n = 2013 <= y && y <= 2015 \n && 1 <= m && m <= 12\n && 1 <= d && d <= mounthDays m\n mounthDays 2 = 28\n mounthDays m\n | m `elem` [4,7,9,11] = 30\n | otherwise = 31\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n "}, {"source_code": "import qualified Data.Map as Map\nimport Data.Char\nimport Data.List\n\ndays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\ncorrectDate d m y =\n 2013 <= y && y <= 2015 &&\n 1 <= m && m <= 12 &&\n 1 <= d && d <= days !! m \n\ncollectDates (d1:d2:t1:m1:m2:t2:y1:y2:y3:y4:rest)\n | correct = [d1, d2, t1, m1, m2, t2, y1, y2, y3, y4]:collectDates next\n | otherwise = collectDates next\n where correct = [t1, t2] == \"--\" && allDigits && correctDate d m y\n allDigits = all isDigit [d1, d2, m1, m2, y1, y2, y3, y4]\n d = read [d1, d2]\n m = read [m1, m2]\n y = read [y1, y2, y3, y4]\n next = d2:t1:m1:m2:t2:y1:y2:y3:y4:rest\n \ncollectDates _ = []\n\nsolve xs = fst $ maximumBy (\\(_, x) (_, y) -> compare x y) $ map (\\x -> (head x, length x)) $ group dates\n where dates = sort $ collectDates xs\n\nmain = interact solve \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport Text.Printf\n\nmain = getLine >>= solve\n\nisNum c = '0'<=c && c<='9'\n\nsolve cs = do\n arr <- newArray (0,50000) 0 :: IO (IOUArray Int Int)\n let f (d1:d2:'-':m1:m2:'-':'2':'0':'1':y4:rest)\n | '3'<=y4 && y4<='5' && all isNum [d1,d2,m1,m2] && isDate m d=unsafeRead arr ymd>>=unsafeWrite arr ymd.(1+)>>f ('1':y4:rest)\n where\n d=read[d1,d2]\n m=read[m1,m2]\n y=read$'2':'0':'1':[y4]\n ymd=(y-2013)*10000+m*100+d\n f (_:cs) = f $ dropWhile ('-'==) cs\n f _ = getElems arr>>=putStrLn.showAns.maximum.(`zip`[0..])\n f cs\n\nshowAns :: (Int,Int) -> String\nshowAns (_,ymd) = printf\"%02d-%02d-%4d\" d m y\n where\n y = 2013 + ymd`div`10000\n m = ymd`mod`10000`div`100\n d = ymd`mod`100\n\nisDate :: Int -> Int -> Bool\nisDate m d = 1<=m && m<=12 && 1<=d && d<=dmax\n where\n dmax = [31,28,31,30,31,30,31,31,30,31,30,31]!!(m-1)"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\n\nmon = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nmain = getLine >>= putStrLn.snd.maximum.map (\\x -> (length x, head x)).group.sort.all_date\n--main = getLine >>= putStrLn.show.all_date\n\nget_int s x = foldl (\\a b -> a*10 + (ord (s !! b) - 48)) 0 x\n\nvalid_date :: String -> Bool\nvalid_date s = \t2013 <= yy && yy <= 2015 && 1 <= mm && mm <= 12 && 1 <= dd && dd <= (mon !! mm)\n\t\t\t where \n\t\t\t dd = get_int s [0,1];\n\t\t\t\tmm = get_int s [3,4];\n\t\t\t\tyy = get_int s [6..9];\n\ncheck :: String -> Maybe String\ncheck s = if length s == 10 && '-' `elemIndices` s == [2,5] then\n\t\t\tif valid_date s then Just s else Nothing\n\t\t else Nothing\n\nall_date :: String -> [String]\nall_date x = catMaybes $ filter (\\x -> x /= Nothing) $ map (check.take 10) $ tails x\n"}, {"source_code": "import Data.List (tails, elemIndices, sort, group, maximum)\nimport Data.Array.Unboxed\nimport Data.Maybe (catMaybes)\n\nsplitHelper c [] = ([], [])\nsplitHelper c (x:rest) = if x == c\n then ([], rest)\n else let (a, r) = splitHelper c rest in (x:a, r)\n\nsplit c [] = []\nsplit c s = let (a, r) = splitHelper c s\n in a : split c r\n\nfindDate :: String -> Maybe [Int]\nfindDate l = if elemIndices '-' l == [2,5] \n then Just (map (read :: String -> Int) $ split '-' l)\n else Nothing\n\ndmc :: UArray Int Int\ndmc = listArray (1,12) [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nvalidDay :: Int -> Int -> Bool\nvalidDay d m = 1 <= d && d <= (dmc!m)\n\nvalidDate :: [Int] -> Bool\nvalidDate [d, m, y] = 2013 <= y && y <= 2015 &&\n 1 <= m && m <= 12 &&\n validDay d m\n\nshowD n = let m = (show n) in if (length m == 1) then '0': m else m\n\nprettyDate (_, [d, m, y]) = (showD d) ++ \"-\" ++ (showD m) ++ \"-\" ++ (show y)\n\n\nmain = do\n str <- getLine\n putStrLn $ (prettyDate . maximum . map (\\x -> (length x, head x)) . group . sort . \n filter validDate . catMaybes . map (findDate . take 10) . tails) str\n \n"}], "negative_code": [{"source_code": "import Data.List (tails, elemIndices, sort, group, maximum)\nimport Data.Array.Unboxed\nimport Data.Maybe (catMaybes)\n\nsplitHelper c [] = ([], [])\nsplitHelper c (x:rest) = if x == c\n then ([], rest)\n else let (a, r) = splitHelper c rest in (x:a, r)\n\nsplit c [] = []\nsplit c s = let (a, r) = splitHelper c s\n in a : split c r\n\nfindDate :: String -> Maybe [Int]\nfindDate l = if elemIndices '-' l == [2,5] \n then Just (map (read :: String -> Int) $ split '-' l)\n else Nothing\n\ndmc :: UArray Int Int\ndmc = listArray (1,12) [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nvalidDay :: Int -> Int -> Bool\nvalidDay d m = 1 <= d && d <= (dmc!m)\n\nvalidDate :: [Int] -> Bool\nvalidDate [d, m, y] = 2013 <= y && y <= 2015 &&\n 1 <= m && m <= 12 &&\n validDay d m\n\nprettyDate (_, [d, m, y]) = (show d) ++ \"-\" ++ (show m) ++ \"-\" ++ (show y)\n\n\nmain = do\n str <- getLine\n putStrLn $ (prettyDate . maximum . map (\\x -> (length x, head x)) . group . sort . \n filter validDate . catMaybes . map (findDate . take 10) . tails) str\n \n"}], "src_uid": "dd7fd84f7915ad57b0e21f416e2a3ea0"} {"source_code": "import Data.Bits\nimport Data.List\n\nmain = interact $ show . solve . map read . words . (!! 1) . lines\n\nsolve :: [Int] -> Int\nsolve = maximum . map (maximum . map (foldl xor 0) . tails) . inits\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Bits\n\nxorSegment xs i j = foldl xor 0 $ take (j - i + 1) $ drop i xs\n\nsolve :: [Int] -> Int\nsolve xs = maximum [(xorSegment xs i j) | i <- [0 .. n], j <- [i .. n]]\n where n = length xs\n\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Data.List\nimport Data.Bits\n\nxorSegment xs i j = foldl' xor 0 $ take (j - i + 1) $ drop i xs\n\nsolve :: [Int] -> Int\nsolve xs = foldl' max 0 [(xorSegment xs i j) | i <- [0 .. n], j <- [i .. n]]\n where n = length xs\n\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Data.Bits\nmain = getContents>>=print.solve.map read.tail.words\n\nsolve :: [Int] -> Int\nsolve xs = maximum $ ys ++ [y1`xor`y2|y1<-ys,y2<-ys]\n where\n ys = scanl1 xor xs"}, {"source_code": "import Data.Bits\nmain = getContents >>= print.solve.map read.tail.words\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve ls = maximum [(fst (foldl (\\(x,y) z -> (maximum [x,y `xor` z], y `xor` z)) (0,0) ls)), (solve (tail ls)) ]\n\n"}, {"source_code": "import Data.Bits(xor)\n\nmain = do\n n <- getLine\n ar <- getLine\n let ls = map read (words ar) :: [Int]\n print $ foreachXor ls\n\nforeachXor [] = 0\nforeachXor xs'@(x:xs) = maxXor (x:xs) 0 `max` foreachXor xs\n\nmaxXor [] _ = 0\nmaxXor (x:xs) s = currentXor `max` maxXor xs currentXor\n where currentXor = xor x s"}, {"source_code": "import Data.Bits\nmain = do\n (n : input) <- fmap (map read . words) getContents\n let par = scanl1 xor (input :: [Int]) ++ [0]\n print $ maximum [x `xor` y | x <- par, y <- par]\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Bits.html\n\nimport Data.Bits\n\nmaxXor :: [Int] -> Int\nmaxXor [] = 0\nmaxXor a = max (maxPrefixXor a 0) (maxXor (tail a))\n\nmaxPrefixXor :: [Int] -> Int -> Int\nmaxPrefixXor [] x = x\nmaxPrefixXor (a : b) x = max (xor a x) (maxPrefixXor b (xor a x))\n\nmain :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tlet list = map read (words str2)\n\tputStrLn (show (maxXor (list)))\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Data.Bits (xor)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = maximum [foldl1 xor [a ! k | k <- [i .. j]] | i <- [1 .. n], j <- [i .. n]]\n where\n a = listArray (1, n) xs\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- reads\n print $ solve n xs\n"}, {"source_code": "-- Codeforces 252B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -funfolding-use-threshold=16 #-}\n{-# OPTIONS_GHC -fexcess-precision #-}\n{-# OPTIONS_GHC -feager-blackholing #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# OPTIONS_GHC -fdicts-strict #-}\n{-# OPTIONS_GHC -optc-O3 #-}\n{-# OPTIONS_GHC -optc-ffast-math #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BC\n\nreadInt :: BC.ByteString -> Int\nreadInt !s = case BC.readInt s of Just (n, _) -> n\n\nmain :: IO ()\nmain = do\n (x:xs) <- (map readInt . BC.words) <$> BC.getContents :: IO [Int]\n let ys = scanl1 xor (0:xs)\n print $ maximum [x `xor` y | x <- ys, y <- ys]\n"}], "negative_code": [{"source_code": "-- Codeforces 252B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -funfolding-use-threshold=16 #-}\n{-# OPTIONS_GHC -fexcess-precision #-}\n{-# OPTIONS_GHC -feager-blackholing #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# OPTIONS_GHC -fdicts-strict #-}\n{-# OPTIONS_GHC -optc-O3 #-}\n{-# OPTIONS_GHC -optc-ffast-math #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BC\n\nreadInt :: BC.ByteString -> Int\nreadInt !s = case BC.readInt s of Just (n, _) -> n\n\nmain :: IO ()\nmain = do\n (x:xs) <- (map readInt . BC.words) <$> BC.getContents :: IO [Int]\n let ys = scanl1 xor xs\n print $ maximum [x `xor` y | x <- ys, y <- ys]\n"}, {"source_code": "import Data.Bits(xor)\n\nmain = do\n n <- getLine\n ar <- getLine\n let lsAr = map read (words ar) :: [Int]\n print $ maximum $ maximum lsAr : maxXor lsAr 0 ++ maxXor (reverse lsAr) 0\n\nmaxXor [] _ = []\nmaxXor (x:xs) s = currentXor : maxXor xs currentXor\n where currentXor = xor x s"}, {"source_code": "import Data.Bits\nmain = do\n (n : input) <- fmap (map read . words) getLine\n let par = scanl1 xor (input :: [Int]) ++ [0]\n print $ maximum [x `xor` y | x <- par, y <- par]\n"}], "src_uid": "a33991c9d7fdb4a4e00c0d0e6902bee1"} {"source_code": "import Data.Char (ord, chr, isDigit)\nimport Data.Maybe (fromMaybe, isJust)\nimport Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n ns <- getLine\n inputs <- replicateM (read ns) getLine\n mapM (putStrLn.reconvert) inputs\n return ()\n\ndata Position = Position Int Int deriving Show -- the reconvert :: String -> String\nreconvert str = reconvert' (fromRC str) (fromBC str)\n\nreconvert' :: (Maybe Position) -> (Maybe Position) -> String\nreconvert' (Just pos1) _ = asXY pos1\nreconvert' Nothing (Just pos2) = asRC pos2\nreconvert' _ _ = \"Eat shit\"\n\nfromRC :: String -> Maybe Position\nfromRC str | valid = Just $ Position (fromMaybe 0 r) (fromMaybe 0 c)\n | otherwise = Nothing\n where r = fromRCR str\n c = fromRCC str\n valid = isJust r && isJust c\n\nfromRCR :: String -> Maybe Int\nfromRCR ('R' : rs) | length dig > 0 = Just (read dig)\n | otherwise = Nothing\n where dig = takeWhile isDigit rs\nfromRCR _ = Nothing\n\nfromRCC :: String -> Maybe Int\nfromRCC ('R' : rs) | length dig > 0 = Just (read dig)\n | otherwise = Nothing\n where dig = (takeWhile isDigit).(dropWhile (not.isDigit)).(dropWhile isDigit) $ rs\nfromRCC _ = Nothing\n\nfromBC :: String -> Maybe Position\nfromBC str | valid = Just $ Position (read rstr) (toInt (reverse cstr))\n | otherwise = Nothing\n where cstr = takeWhile (not.isDigit) str\n rstr = (takeWhile isDigit).(dropWhile (not.isDigit)) $ str\n valid = (length cstr) > 0 && (length rstr) > 0\n toInt (c:cs) = (ord c - ord 'A' + 1) + 26 * (toInt cs)\n toInt \"\" = 0\n\nasRC :: Position -> String\nasRC (Position row column) = \"R\" ++ (show row) ++ \"C\" ++ (show column)\n\nasXY :: Position -> String\nasXY (Position row column) = reverse (asBC column) ++ (show row)\n\nasBC :: Int -> String\nasBC val | val > 0 = ch : (asBC dv)\n | otherwise = \"\"\n where dv = (val - 1) `div` 26\n md = val `mod` 26\n ch = if md == 0 then 'Z' \n else chr (ord 'A' + md - 1)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Char\nimport Text.Parsec\n\nmain = do\n t <- read <$> getLine\n replicateM t routine\n\nroutine = do\n s <- getLine\n print $ trans $ parseCoord s\n\ndata Coord\n = Normal Int Int\n | Excel String Int\n\ninstance Show Coord where\n show (Normal r c) = 'R' : show r ++ 'C' : show c\n show (Excel c r) = c ++ show r\n\ntoLetters :: Int -> String\ntoLetters x\n | x <= 26 = [toLetter x]\n | otherwise = toLetters ((x - m) `div` 26) ++ toLetters m\n where\n toLetter x = chr (x + ord 'A' - 1)\n m = (x - 1) `mod` 26 + 1\n\ntoNumber :: String -> Int\ntoNumber [x] = ord x - ord 'A' + 1\ntoNumber xs = (toNumber $ init xs) * 26 + toNumber [last xs]\n\ntrans (Right (Normal r c)) = Excel (toLetters c) r\ntrans (Right (Excel c r)) = Normal r (toNumber c)\n\nparseCoord = parse (try normalParser <|> excelParser) \"\"\n where\n normalParser = do\n char 'R'\n r <- read <$> many1 digit\n char 'C'\n c <- read <$> many1 digit\n return (Normal r c)\n excelParser = do\n c <- many1 upper\n r <- read <$> many1 digit\n return (Excel c r)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Char\n\nto26 :: Int -> [Char]\nto26 n = helper n 26\n where\n helper n k | k >= n = to26' (n-1) k\n helper n k = helper (n - k) (k * 26)\n to26' n k\n | k == 1 = []\n | otherwise = chr (ord 'A' + div') : to26' mod' k'\n where\n k' = k `div` 26\n (div', mod') = divMod n k'\n\nfrom26 :: [Char] -> Int\nfrom26 s = from26' (reverse s) + 1 + sum [ 26^i | i <- [1..len-1]]\n where\n len = length s\n from26' [] = 0\n from26' (x:xs) = from26' xs * 26 + (ord x - ord 'A')\n\ncheckRC :: [Char] -> Bool\ncheckRC str = (head str == 'R') && (isDigit $ str !! 1) && (elem 'C' str)\n\nrc2xy :: [Char] -> [Char]\nrc2xy str = to26 c ++ show r\n where\n [r,c] = map read . words $ map (\\ch -> if isDigit ch then ch else ' ') str\n\nxy2rc :: [Char] -> [Char]\nxy2rc str = \"R\" ++ y ++ \"C\" ++ show (from26 x)\n where\n (x,y) = span isUpper str\n\nsolve :: [Char] -> [Char]\nsolve str = if checkRC str then rc2xy str else xy2rc str\n\nmain = interact $ unlines . (\\(n:b) -> map solve $ take (read n) b) . lines\n"}, {"source_code": "import Data.List (groupBy)\nimport Data.Char (isUpper, isDigit, ord, chr)\nimport Data.Function (on)\nimport Control.Monad (replicateM_)\n\nordA :: Int\nordA = ord 'A'\n\natr :: String -> String -> String\natr s n = (\"R\" ++ n ++ \"C\" ++ show (foldl folder 0 s))\n where folder acc c = acc * 26 + ord c - ordA + 1\n\nrta :: Int -> String -> String\nrta a = (toa a \"\" ++)\n where\n toa x acc =\n if x == 0\n then acc\n else toa d (chr (ordA + m) : acc)\n where (d, m) = (x-1) `divMod` 26\n\nsolve :: String -> String\nsolve input =\n case groupBy ((==) `on` isDigit) input of\n [_, a, _, b] -> rta (read b) a\n [a, b] -> atr a b\n{-\nsolve input =\n if null c\n then atr a (read b)\n else rta (read d) (read b)\n where\n (a, b') = span isUpper input\n (b, c') = span isDigit b'\n (c, d) = span isUpper c'\n-}\n\nmain :: IO ()\nmain = do\n n' <- readLn\n replicateM_ n' (putStrLn . solve =<< getLine)\n"}, {"source_code": "import Data.Char (isUpper, isDigit, ord, chr)\nimport Control.Monad (replicateM_)\n\nordA :: Int\nordA = ord 'A'\n\natr :: String -> Int -> String\natr s n = (\"R\" ++ show n ++ \"C\" ++ show (foldl folder 0 s))\n where folder acc c = acc * 26 + ord c - ordA + 1\n\nrta :: Int -> Int -> String\nrta a = (toa a \"\" ++) . show\n where\n toa x acc =\n if x == 0\n then acc\n else toa d (chr (ordA + m) : acc)\n where (d, m) = (x-1) `divMod` 26\n\nsolve :: String -> String\nsolve input =\n if null c\n then atr a (read b)\n else rta (read d) (read b)\n where\n (a, b') = span isUpper input\n (b, c') = span isDigit b'\n (c, d) = span isUpper c'\n\nmain :: IO ()\nmain = do\n n' <- readLn\n replicateM_ n' (putStrLn . solve =<< getLine)\n"}, {"source_code": "import Data.List (groupBy)\nimport Data.Char (isUpper, isDigit, ord, chr)\nimport Data.Function (on)\nimport Control.Monad (replicateM_)\n\nordA :: Int\nordA = ord 'A'\n\natr :: String -> Int -> String\natr s n = (\"R\" ++ show n ++ \"C\" ++ show (foldl folder 0 s))\n where folder acc c = acc * 26 + ord c - ordA + 1\n\nrta :: Int -> Int -> String\nrta a = (toa a \"\" ++) . show\n where\n toa x acc =\n if x == 0\n then acc\n else toa d (chr (ordA + m) : acc)\n where (d, m) = (x-1) `divMod` 26\n\nsolve :: String -> String\nsolve input =\n case groupBy ((==) `on` isDigit) input of\n [_, a, _, b] -> rta (read b) (read a)\n [a, b] -> atr a (read b)\n{-\nsolve input =\n if null c\n then atr a (read b)\n else rta (read d) (read b)\n where\n (a, b') = span isUpper input\n (b, c') = span isDigit b'\n (c, d) = span isUpper c'\n-}\n\nmain :: IO ()\nmain = do\n n' <- readLn\n replicateM_ n' (putStrLn . solve =<< getLine)\n"}, {"source_code": "import Data.List (groupBy)\nimport Data.Char (isUpper, isDigit, ord, chr)\nimport Data.Function (on)\nimport Control.Monad (replicateM_)\n\nordA :: Int\nordA = ord 'A'\n\natr :: String -> String -> String\natr s n = (\"R\" ++ n ++ \"C\" ++ show (foldl folder 0 s))\n where folder acc c = acc * 26 + ord c - ordA + 1\n\nrta :: Int -> String -> String\nrta a = (toa a \"\" ++)\n where\n toa 0 acc = acc\n toa x acc = toa d (chr (ordA + m) : acc)\n where (d, m) = (x-1) `divMod` 26\n\nsolve :: String -> String\nsolve input =\n case groupBy ((==) `on` isDigit) input of\n [_, a, _, b] -> rta (read b) a\n [a, b] -> atr a b\n\nmain :: IO ()\nmain = do\n n' <- readLn\n replicateM_ n' (putStrLn . solve =<< getLine)\n"}, {"source_code": "import System.IO\nimport Data.Char (isUpper, isDigit, ord, chr)\nimport Control.Monad (replicateM_)\n\nordA :: Int\nordA = ord 'A'\n\natr :: String -> Int -> String\natr s n = (\"R\" ++ show n ++ \"C\" ++ show (foldl folder 0 s))\n where folder acc c = acc * 26 + ord c - ordA + 1\n\nrta :: Int -> Int -> String\nrta a = (toa a \"\" ++) . show\n where\n toa x acc =\n if x == 0\n then acc\n else toa d (chr (ordA + m) : acc)\n where (d, m) = (x-1) `divMod` 26\n\nsolve :: String -> String\nsolve input =\n if null c\n then atr a (read b)\n else rta (read d) (read b)\n where\n (a, b') = span isUpper input\n (b, c') = span isDigit b'\n (c, d) = span isUpper c'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n n' <- readLn\n replicateM_ n' (putStrLn . solve =<< getLine)\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (foldl', unfoldr)\nimport Data.Tuple (swap)\nimport Data.Char (ord, chr, isAsciiUpper, isDigit)\nimport Control.Monad (replicateM)\n\n\ntoCartesian :: String -> String\ntoCartesian xs = 'R':row ++ 'C':show col\n where (q,row) = span isAsciiUpper xs\n col = foldl' (\\r c -> 26 * r + ord c - ord 'A' + 1) 0 q\n\ntoExcel :: String -> String\ntoExcel (_:xs) = col ++ row\n where (row,_:ccol) = span isDigit xs\n col = reverse . map (\\i -> chr $ ord 'A' + i) . go $ read ccol\n go 0 = []\n go n = let (q,r) = divMod n 26\n (cur,next) = if r == 0 then (25,q - 1) else (r - 1,q)\n in cur:go next\n\nmain :: IO ()\nmain = putStr . unlines . map solve =<< flip replicateM getLine =<< readLn\n where solve xs\n | all isDigit $ dropWhile isAsciiUpper xs = toCartesian xs\n | otherwise = toExcel xs"}, {"source_code": "module Main where\n\nimport Text.ParserCombinators.ReadP\nimport Control.Monad\nimport Data.Char\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine :: IO Int\n\n replicateM_ n $ getLine >>= putStrLn . translate\n\ntranslate :: String -> String\ntranslate s = fst $ head $ readP_to_S ( mplus\n ( do\n _ <- char 'R' :: ReadP Char\n row <- munch1 isDigit\n _ <- char 'C'\n col <- munch1 isDigit\n eof\n return $ digitToAlpha col ++ row\n ) ( do\n col <- munch1 isAlpha\n row <- munch1 isDigit\n eof\n return $ \"R\" ++ row ++ \"C\" ++ alphaToDigit col\n )\n ) s\n\ndigitToAlpha s =\n let n = read s\n digits26 = reverse $ digits26' (n-1)\n digits26' n =\n if n < 26\n then [n]\n else ( n `mod` 26 ) : digits26' ( n `div` 26 - 1 )\n in map ( chr . ( + ( ord 'A' ) ) ) digits26\n\nalphaToDigit s =\n show $ foldl' (\\acc d ->\n acc * 26 + 1 + ord d - ord 'A'\n ) 0 s\n"}, {"source_code": "\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ExtendedDefaultRules #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n-- ~ {-# LANGUAGE TypeSynonymInstances #-}\n-- ~ {-# LANGUAGE IncoherentInstances #-}\nimport Data.Char\nimport Data.Typeable\n\n \n-- ~ module MyModule where\n\n------------------------------------------------------------------------\nclass (Show a) => MyToString a where\n mytoString :: a -> String\n\ninstance (Show a) => MyToString a where\n mytoString = show\n\ninstance {-# OVERLAPPING #-} MyToString String where\n mytoString = id\n\ninstance {-# OVERLAPPING #-} MyToString Char where\n mytoString c = [c]\n \n------------------------------------------------------------------------\nprintList :: (MyToString a) => [a] -> IO()\nprintList [] = return()\nprintList (x : xs) = do\n putStrLn $ mytoString $ x\n printList xs\n\n\nmain = do\n content <- getContents\n printList $ map convert $ drop 1 $ lines $ content\n \nisExcel :: String -> Bool\nisExcel s = let func :: String -> Integer -> Bool\n func [] n\n | n == 2 = True\n | otherwise = False\n func (x : xs) 0\n | isDigit x = False\n | otherwise = func xs 1\n func (x : xs) 1\n | isDigit x = func xs 2\n | otherwise = func xs 1\n func (x : xs) 2\n | isDigit x = func xs 2\n | otherwise = False\n in func s 0\n\nconvert :: String -> String\nconvert s\n | isExcel s = let x = splitExcel s\n in \"R\" ++ (snd x) ++ \"C\" ++ (convFromExcel $ fst x)\n | otherwise = let x = splitNotExcel s\n in (convToExcel $ snd x) ++ (fst x)\n \nsplitNotExcel :: String -> (String, String)\nsplitNotExcel s = let func :: (String, String) -> (String, String)\n func (s1, x:xs)\n | x == 'R' = func (s1, xs)\n | x == 'C' = (s1, xs)\n | otherwise = func (s1 ++ [x], xs)\n in func (\"\", s)\n \nconvToExcel :: String -> String\nconvToExcel s = let func :: String -> Int -> String\n func s 0 = s\n func s n = func ([chr $ (mod (n-1) 26) + (ord 'A')] ++ s) $ div (n - (mod (n-1) 26)) 26\n in func [] (read s)\n\nsplitExcel :: String -> (String, String)\nsplitExcel s = break isDigit s\n\nconvFromExcel :: String -> String\nconvFromExcel s = let func :: String -> Int -> String\n func [] n = show n\n func (x : xs) n = func xs $ n * 26 + (ord x) - (ord 'A') + 1\n in func s 0\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Char\nimport Text.Printf\n\ntoAlphabetic :: Int -> String\ntoAlphabetic 0 = \"\"\ntoAlphabetic n = \n let quotient = (n - 1) `div` 26\n remainder = (n - 1) `mod` 26\n current = chr $ (ord 'A') + remainder\n recur = toAlphabetic quotient\n in recur ++ [current]\n\ntoFirstForm :: String -> String -> String\ntoFirstForm r c' = \n let c = toAlphabetic $ read c'\n in c ++ r\n\ntoDigit :: String -> Int \ntoDigit = foldl (\\accum current -> accum * 26 + (ord current - ord 'A' + 1)) 0\n\ntoSecondForm :: String -> String -> String\ntoSecondForm r c = \"R\" ++ c ++ \"C\" ++ (show $ toDigit r)\n\ntransform :: [String] -> String\ntransform [_, r, _, c] = toFirstForm r c\ntransform [r, c] = toSecondForm r c\n\nsplitByAlphaNumber :: [String] -> Char -> [String]\nsplitByAlphaNumber [] current = [[current]]\nsplitByAlphaNumber parsed current = \n let lastElement = last parsed\n lastLetter = last lastElement\n in if isDigit lastLetter == isDigit current\n then (init parsed) ++ [lastElement ++ [current]]\n else parsed ++ [[current]]\n\nparseInput :: String -> [String]\nparseInput = foldl splitByAlphaNumber []\n\nsolve :: String -> String\nsolve = transform . parseInput\n\nreadInput _ = do\n input <- getLine\n return input\n\nmain = do\n input <- getLine\n let n = read input :: Int \n inputs <- forM [1..n] readInput\n forM inputs $ (printf \"%s\\n\") . solve\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Maybe\n\nmain = do\n n <- readLn\n lst <- sequence $ take n $ repeat getLine\n mapM_ (putStrLn . convert) lst\n \nconvert s | isRC s = fromRC s\n | otherwise = toRC s\n\nisRC ('R' : c1 : xs) | isDigit c1 && any (== 'C') xs = True\nisRC _ = False \n\nfromRC s = let \n cPos = fromJust $ findIndex (== 'C') s\n rowStr = drop 1 $ take cPos s\n col::Int\n col = read $ drop (cPos + 1) s\n unfun b | b == 0 = Nothing\n | otherwise = Just (chr $ bb `mod` 26 + ord 'A', bb `div` 26)\n where bb = b - 1 \n colStr = reverse $ unfoldr unfun $ col\n in\n colStr ++ rowStr\n\ntoRC s = let \n rowPos = fromJust $ findIndex isDigit s\n (colStr, rowStr) = splitAt rowPos s\n foldfun b a = b * 26 + ord a - ord 'A' + 1\n col = foldl foldfun 0 colStr\n in\n \"R\" ++ rowStr ++ \"C\" ++ show col"}, {"source_code": "import Data.Char (isDigit, chr, ord)\nimport Control.Monad (replicateM_)\nimport Data.List (groupBy)\n\nmain :: IO ()\nmain = getLine >>= (\\n -> replicateM_ (read n) (fmap (process.splitCode) getLine >>= putStrLn))\n\nprocess [_,r,_,c] = (reverse.asBC) (read c) ++ r\nprocess [b,n] = \"R\" ++ n ++ \"C\" ++ (show (bcToInt (reverse b)))\nprocess _ = undefined\nsplitCode = groupBy (\\c1 c2 -> isDigit c1 && isDigit c2 || not (isDigit c1) && not (isDigit c2))\n\nbcToInt \"\" = 0\nbcToInt (c:cs) = (ord c - ord 'A' + 1) + 26 * (bcToInt cs)\n\nasBC :: Int -> String\nasBC val | val > 0 = ch : (asBC dv)\n | otherwise = \"\"\n where dv = (val - 1) `div` 26\n md = val `mod` 26\n ch = if md == 0 then 'Z' \n else chr (ord 'A' + md - 1)\n"}, {"source_code": "import Data.Char\n\nmain = do \n\tn<-getLine\n\treading (read n)\n\t\nreading 0 = do\n\tputStrLn []\nreading a = do \n\ts<-getLine\n\tputStrLn $ pars s\n\treading (a-1)\n\npars s \n | s==\"\" = \"\"\n | head s == 'R' && length s>=2 && isDigit (s!!1) && elem 'C' s = (numberToLetters (read (tail cPart)))\n ++ rPart \n | otherwise = \"R\"++sPart++ \"C\" ++ ( show (lettersToNumber fPart))\n where rPart = (takeWhile isDigit (tail s))\n cPart = dropWhile isDigit (tail s) \n fPart = takeWhile (not.isDigit) s\n sPart = dropWhile (not.isDigit) s\n\nlettersToNumber::String->Integer\nlettersToNumber []= 0\nlettersToNumber s = toInteger (ord (head s)-ord 'A'+1) * 26^(length s-1)+ (lettersToNumber $ tail s)\n\nnumberToLetters::Integer->String\nnumberToLetters 0 = \"\"\nnumberToLetters n \n | mod n 26==0 = reverse$\"Z\" ++ reverse (numberToLetters (div n 26-1))\n | otherwise = reverse$ [chr (fromIntegral (mod n 26 + fromIntegral( ord 'A')-1))] \n ++ reverse (numberToLetters $ div n 26)"}, {"source_code": "module Main\nwhere\n\nimport System.IO\nimport Data.Char\nimport Data.List\n\ndata Cell = RCCell Integer Integer | CharCell String Integer deriving (Eq, Show)\n\nreadFormat s = if srest2 == \"\" then CharCell s1 (read s2) else RCCell (read s2) (read s4)\n where (s1, srest1) = span isAlpha s\n (s2, srest2) = span isDigit srest1\n (_, s4) = span isAlpha srest2\n\ncharDig c = toInteger(ord c - ord 'A')\n\ncharToNumber' (x:xs) = charToNumber' xs * 26 + charDig x + 1\ncharToNumber' _ = 0\n\ncharToNumber s = charToNumber' $ reverse s\n\ndigChar n = chr (fromInteger n + ord 'A')\n\nnumberToChar' n = (digChar (m `mod` 26)):(if m > 25 then numberToChar' (m `div` 26) else \"\")\n where m = n - 1\n\nnumberToChar n = reverse $ numberToChar' n\n\ntransformFormat (RCCell x y) = (CharCell (numberToChar y) x) \ntransformFormat (CharCell x y) = (RCCell y (charToNumber x)) \n \nshowFormat (RCCell x y) = \"R\" ++ show x ++ \"C\" ++ show y\nshowFormat (CharCell x y) = x ++ show y \n \ntransform arg = showFormat $ transformFormat $ readFormat arg\n \nmain = do\n l <- hGetContents stdin\n let args = lines l\n let cases = (read $ args !! 0)::Int\n hPutStrLn stdout $ unlines $ map transform $ take cases $ tail args\n return ()"}, {"source_code": "import Data.Char\n\nmain :: IO()\nmain = getContents >>= mapM_ (putStrLn . solve) . tail . lines\n\nis_digit :: Char -> Bool\nis_digit c = (ord '0') <= (ord c) && (ord c) <= (ord '9')\n\nis_rxcy :: String -> Bool\nis_rxcy (x:y:xs) | (is_digit x) && (not (is_digit y)) = True\n | otherwise = is_rxcy (y:xs)\nis_rxcy s = False\n\nsolve :: String -> String\nsolve s | is_rxcy(s) = conv1 s\n | otherwise = conv2 s\n \nget_first_digit :: String -> String\nget_first_digit (x:xs) | is_digit x = (x:xs)\n | otherwise = get_first_digit xs\n \nget_first_non_digit :: String -> String\nget_first_non_digit (x:xs) | is_digit x = get_first_non_digit xs\n | otherwise = xs\n \nread_num :: String -> Int\nread_num s = read_num' s 0\n where\n read_num' :: String -> Int -> Int\n read_num' \"\" num = num\n read_num' (x:xs) num | is_digit x = read_num' xs (num * 10 + (ord x) - (ord '0'))\n | otherwise = num\n \nconv1 :: String -> String \nconv1 (x:xs) =\n let row = read_num(xs)\n col = read_num(get_first_non_digit(xs))\n in (num2alpha col) ++ (show row)\n \nnum2alpha :: Int -> String\nnum2alpha 0 = \"\"\nnum2alpha num = (num2alpha (div (num - 1) 26)) ++ [(chr ((rem (num - 1) 26) + ord('A')))]\n\nconv2 :: String -> String \nconv2 s = \n let col = read_alpha(s)\n row = read_num(get_first_digit(s))\n in \"R\" ++ (show row) ++ \"C\" ++ (show col)\n\nread_alpha :: String -> Int\nread_alpha s = read_alpha' s 0\n where\n read_alpha' \"\" num = num\n read_alpha' (x:xs) num | is_digit x = num\n | otherwise = read_alpha' xs (num * 26 + (ord(x) - ord('A') + 1))"}, {"source_code": "-- file cf_p1B.hs\nimport Data.Char \nimport Data.List \n\nmyTansform :: String -> String\nmyTansform xs = \n case segments of \n (\"R\" : row : \"C\" : col : []) -> num2char (read col) ++ row\n (col : row : []) -> \"R\" ++ row ++ \"C\" ++ show (char2num col)\n where segments = groupBy (\\l r -> isDigit l == isDigit r) xs\n num2char = map (\\x -> chr (ord 'A' + (x - 1) `mod` 26)) . reverse . takeWhile (>0) . iterate (\\x -> (x-1) `div` 26)\n char2num = foldl' (\\acc x -> acc * 26 + x) 0 . map (\\x -> ord x - ord 'A' + 1)\n\nmain = interact $ intercalate \"\\n\" . map myTansform . tail . lines"}, {"source_code": "-- http://codeforces.com/problemset/problem/1/B\n\nimport Data.Char\n\ndata CoordinateType = A | B deriving (Eq, Show)\n\nmain = do\n\tcontents <- getLine\n\tlet\n\t\tn = read $ head $ lines contents\n\tcoordinates <- getLines n\n\tmapM_ putStrLn $ convertCoordinates coordinates\n\treturn ()\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n-- Type A if not letters are found after a number (ABXY)\n-- Type B if letters are found after a number (RXCY)\n-- Regular expressions could be used, but let's keep things simple\ncoordinateType :: String -> CoordinateType\ncoordinateType (x:xs) = coordinateType' x xs\n\twhere\n\t\tcoordinateType' :: Char -> String -> CoordinateType\n\t\tcoordinateType' _ [] = A\n\t\tcoordinateType' prev (x:xs)\n\t\t\t| isDigit prev && isLetter x = B\n\t\t\t| otherwise = coordinateType' x xs\n\nletterToNum :: Char -> Int\nletterToNum letter = ord letter - 65\n\nnumToLetter :: Int -> Char\nnumToLetter num = chr $ num + 65\n\nletterColToNum :: String -> Int\nletterColToNum [] = 0\nletterColToNum (x:xs) = 26^length(xs)*((letterToNum x) + 1) + letterColToNum xs\n\nnumToLetterCol :: Int -> String\nnumToLetterCol num = reverse $ numToLetterCol' num\n\twhere\n\t\tnumToLetterCol' :: Int -> String\n\t\tnumToLetterCol' num\n\t\t\t| num < 26 = [numToLetter num]\n\t\t\t| otherwise = numToLetter (num `mod` 26) : numToLetterCol' (num `quot` 26 - 1)\n\ntranslateCoordinate :: String -> String\ntranslateCoordinate coord\n\t| coord_type == A =\n\t\tlet\n\t\t\tcol = takeWhile (isLetter) coord\n\t\t\trow = takeWhile (isDigit) $ dropWhile (isLetter) coord\n\t\tin\n\t\t\t\"R\" ++ row ++ \"C\" ++ (show $ letterColToNum col)\n\t| coord_type == B =\n\t\tlet\n\t\t\tcol = read $ tail $ dropWhile (isDigit) $ tail coord\n\t\t\trow = takeWhile (isDigit) $ tail coord\n\t\tin\n\t\t\tnumToLetterCol (col-1) ++ row\n\twhere\n\t\tcoord_type = coordinateType coord\n\nconvertCoordinates :: [String] -> [String]\nconvertCoordinates [] = []\nconvertCoordinates (x:xs) = translateCoordinate x : convertCoordinates xs"}, {"source_code": "{-\n Convert between two ways to write a row/column\n 1) R##C##\n 2) LL##\n in 1) the row and column is simply numbered\n in 2) it is encoded, column as a number in pseudo base-26 using letters\n row simply written afterward\n-}\n\nimport Data.List\nimport Data.Char\n\ns2i :: String -> Int\ns2i = foldl (\\s d -> 26*s + ord d - ord 'A' + 1) 0\n\n\ni2s :: Int -> String\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\n\nconv :: String -> String\nconv s = \n case groupBy (\\a b -> isDigit a == isDigit b) s of\n -- R##C## case\n [_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\n\nmain = interact $ unlines . map conv . tail . lines"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\n\ns2i = foldl (\\a x -> 26*a + ord x - ord 'A' + 1) 0\n\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\nconv s =\n\tcase groupBy (\\a b -> isDigit a == isDigit b) s of\n\t\t[_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n\t\t[c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\nmain = interact $ unlines . map conv . tail . lines\n"}, {"source_code": "import Data.Char\nimport Data.List\nintToStr 0 = []\nintToStr x = (intToStr $ (x - 1) `div` 26) ++ [chr $ (x - 1) `mod` 26 + ord 'A']\nstrToInt = foldl (\\ s c -> 26 * s + ord c - ord 'A' + 1) 0\nf str = case parse str of \n [_,r,_,c] -> (intToStr . read $ c) ++ r\n [c,r] -> \"R\" ++ r ++ \"C\" ++ (show . strToInt $ c)\n where \n parse = groupBy (\\a b -> isDigit a == isDigit b)\nmain = interact $ unlines . map f . tail . lines\n"}, {"source_code": "\nimport Data.Char\nimport Debug.Trace\nimport Control.Monad\n\ndata IdType = Excel | RC\n\ngetInput :: IO [String]\ngetInput = do\n\tlinesnum <- (liftM read) getLine\n\tsequence $ replicate linesnum getLine\n\nidentifyType :: String -> IdType\nidentifyType s = if head s /= 'R'\n\tthen Excel\n\telse if not . isDigit $ s !! 1\n\t\tthen Excel\n\t\telse if any (not . isDigit) $ drop 2 s then RC else Excel\n\nexcelToRC :: String -> String\nexcelToRC s = \"R\" ++ row ++ \"C\" ++ convertedColumn\n\twhere\n\t\t(column, row) = parseExcel s\n\t\tconvertedColumn = (show . id) $ foldl decodeAlpha 0 column\n\t\tparseExcel = break isDigit\n\t\tdecodeAlpha t c = (t * 26) + (ord c - ord 'A' + 1)\n\nrCToExcel :: String -> String\nrCToExcel s = convertedColumn ++ row\n\twhere\n\t\t(row, column) = parseRc s\n\t\tparseRc s = let (a,b) = break (== 'C') (tail s) in (a, tail b)\n\t\tconvertedColumn = decodeNumber (read column) \"\"\n\t\tdecodeNumber 0 s = s\n\t\tdecodeNumber x s = if x < 26\n\t\t\tthen decodeDigit x : s\n\t\t\telse decodeNumber d newS\n\t\t\t\twhere\n\t\t\t\t\t(d, m) = divMod' x 26\n\t\t\t\t\tnewS = decodeDigit m : s\n\t\tdivMod' a b = if m == 0 then (d - 1, b) else (d, m)\n\t\t\twhere\n\t\t\t\t(d, m) = divMod a b\n\n\t\tdecodeDigit x = chr (ord 'A' + x - 1)\n\nconvert :: String -> String\nconvert s = case identifyType s of\n\tExcel -> excelToRC s\n\tRC -> rCToExcel s\n\nmain = do\n\tcoords <- getInput\n\tmapM_ (putStrLn . convert) coords\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.List\nimport Data.Char\n\nletters = map (\\x -> chr (ord 'A' + (x - 1) `mod` 26)) . reverse . takeWhile (>0) . iterate (\\x -> (x-1) `div` 26)\nnumbers = sum . zipWith (*) (iterate (*26) 1) . reverse . map (\\x -> ord x - ord 'A' + 1)\n\nconvert :: [String] -> String\nconvert (\"R\":r:\"C\":c:[]) = letters (read c) ++ r\nconvert (c:r:[]) = \"R\" ++ r ++ \"C\" ++ show (numbers c)\n\nmain = do\n (n :: Int,cells) <- getContents >>= return . (\\(n:cells) -> (read n,map (map toUpper) cells)) . lines\n mapM (putStrLn . convert . groupBy (\\l r -> isDigit l == isDigit r)) (take n cells)\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = readLn >>= \\n-> (solve=<C.getLine) )\nsolve xs = forM_ xs $ \\i-> C.putStrLn $ slv1 i\nslv1 xs = slv2 $ second (C.break (isLetter)) $ C.break (isDigit) xs\nslv2 (a,(b,c))= if c/=C.empty then C.append (slv5 $ rIn $ C.tail c) b else C.append (C.cons 'R' (C.init b)) (C.cons 'C' $ slv3 a)\nse_t2 = Set.fromList (['A'..'Z'])\nslv3::C.ByteString->C.ByteString\nslv3 xs =C.pack $ show $ fst $ C.foldr (\\a (b1,b2)->((Set.findIndex a se_t2+1)* 26^b2 +b1, b2+1)) (0,0) xs\nslv4 0 = []\nslv4 x=let md = x `mod` 26; dv= x `div` 26 in slv4 (if md==0 then dv-1 else dv) ++[if md==0 then 26 else md]\nslv5 x =C.pack $ map (flip Set.elemAt se_t2.(+(-1))) $ slv4 x"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.Char\nimport Data.List\n\ni2s a = reverse $ go a\n where\n go :: Int -> String\n go 0 = \"\"\n go !a = chr (ord 'A' + (a - 1) `mod` 26) : go ((a - 1) `div` 26)\n\ns2i :: String -> Int\ns2i = foldl' (\\a x -> 26 * a + ord x - ord 'A' + 1) 0\n\nans s = case groupBy (\\a b -> isDigit a == isDigit b) s of\n [_, r, _, c] -> (i2s . read $ c) ++ r\n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\nmain = interact $ unlines . map ans . tail . lines"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport Data.Char\nimport Data.List\n\na2n = foldl' (\\i s -> ord s - ord 'A' + 1 + i*26) 0\nn2a 0 = []\nn2a n = chr (ord 'A' + (n - 1) `mod` 26) : n2a ((n - 1) `div` 26)\n\nmatch = groupBy (\\a b -> isDigit a == isDigit b)\nsolve (match -> [col, row]) = \"R\" ++ row ++ \"C\" ++ (show . a2n $ col)\nsolve (match -> [_, row, _, col]) = (reverse . n2a . read $ col) ++ row\n\nmain = interact $ unlines . map solve . tail . lines\n"}, {"source_code": "import Data.Char\nimport Text.ParserCombinators.ReadP\n\nfromChar :: Char -> Int\nfromChar c = (ord c - ord 'A' + 1)\n\ntoChar :: Int -> Char\ntoChar n\n | n < 0 || n > 26 = error \"toChar: argument not in [1..26]\"\n | otherwise = chr (ord 'A' + n - 1)\n\nfromABC :: String -> Int\nfromABC \"\" = 0\nfromABC s = sum (zipWith (*) (map fromChar s) (_26 (length s)))\n where\n _26 0 = []\n _26 n = (26^(n-1)):(_26 (n-1))\n\ntoABC :: Int -> String\ntoABC 0 = \"\"\ntoABC n\n | n <= 26 = [toChar n]\n | a == 0 = (toABC (div n 26 - 1)) ++ \"Z\"\n | otherwise = (toABC (div n 26)) ++ [toChar a]\n where\n a = mod n 26\n\nparserRC :: ReadP (Int, Int)\nparserRC = do\n string \"R\"\n row <- many1 $ satisfy isDigit\n string \"C\"\n col <- many1 $ satisfy isDigit\n return (read col, read row)\n\nparserA1 :: ReadP (Int, Int)\nparserA1 = do\n col <- many1 $ satisfy isAlpha\n row <- many1 $ satisfy isDigit\n return (fromABC col, read row)\n\ngetCell :: ReadP (Int, Int) -> String -> Maybe (Int, Int)\ngetCell parser s\n | 0 < length xs = Just (fst (head xs))\n | otherwise = Nothing\n where\n xs = filter (\\x -> snd x == \"\") (readP_to_S parser s)\n\ncheckString :: ReadP (Int, Int) -> String -> Bool\ncheckString parser s = getCell parser s /= Nothing\n\ncheckRC :: String -> Bool\ncheckRC = checkString parserRC\n\ncheckA1 :: String -> Bool\ncheckA1 = checkString parserA1\n\ntoRC :: (Int, Int) -> String\ntoRC (n, m) = concat [\"R\", show m, \"C\", show n]\n\ntoA1 :: (Int, Int) -> String\ntoA1 (n, m) = concat [toABC n, show m]\n\nsolve :: String -> String\nsolve s\n | checkRC s = toA1 (r, c)\n | checkA1 s = toRC (n, m)\n | otherwise = \"NO\"\n where\n (Just (r, c)) = getCell parserRC s\n (Just (n, m)) = getCell parserA1 s\n\nmain :: IO ()\nmain = do\n n <- readLn\n lines <- sequence (replicate n getLine)\n sequence_ (map (putStrLn . solve) lines)"}, {"source_code": "-- Codeforces 1B\n\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = interact $ unlines . map solve . tail . lines\n\n-- use groupBy to detect the kind of input.\n\nsolve :: String -> String\nsolve s = case groupBy (\\a b -> isDigit a == isDigit b) s\n of {\n [_, r, _, c] -> (reverse $ i2s $ read c) ++ r;\n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show $ s2i c)\n }\n\n\ns2i :: String -> Int\ns2i = foldl' (\\s d -> 26 * s + ord d - ord 'A' + 1) 0\n\ni2s :: Int -> String\ni2s 0 = []\ni2s a = chr (ord 'A' + (a-1) `mod` 26) : (i2s $ (a-1) `div` 26)\n\n"}, {"source_code": "import Control.Monad\n\nreadAlphas (x : xs) | 'A' <= x && x <= 'Z' =\n x : readAlphas xs\nreadAlphas _ = \"\"\n\nreadDigits (x : xs) | '0' <= x && x <= '9' =\n x : readDigits xs\nreadDigits _ = \"\"\n\ncrToXY c r = 'R' : show r ++ 'C' : (show . convert . reverse) c\n where\n convert [] = 0\n convert (x : xs) = let v = fromEnum x - 64 in\n v + convert xs * 26\n\nxyToCR x y = convert y ++ show x\n where\n convert 0 = \"\"\n convert n = convert (div' n 26) ++ [toEnum (mod' n 26 + 64)]\n where\n mod' a b = let r = mod n 26 in\n if r == 0 then 26 else r\n div' a b = div (a - mod' a b) b\n\nmain = do\n line <- getLine\n let n = read line :: Int\n forM_ [1..n] $ \\i -> do\n line <- getLine\n let a = readAlphas line\n let line' = drop (length a) line\n let b = readDigits line'\n let line'' = drop (length b) line'\n case line'' of\n \"\" -> do let c = a\n let r = read b :: Int\n putStrLn $ crToXY c r\n _ -> do let x = read b :: Int\n let y = read (drop 1 line'') :: Int\n putStrLn $ xyToCR x y\n"}, {"source_code": "import Data.Char\nimport Data.List\n\n--rc2l :: (Foldable t) => t Char -> Int\nrc2l x = foldl (\\a b -> 26*a + ord b - ord 'A' + 1) 0 x\n\nl2rc :: Int -> [Char]\nl2rc 0 = []\nl2rc x = chr (ord 'A' + (x-1) `mod` 26) : (l2rc $ (x-1) `div` 26)\n\nsolution :: [Char] -> [Char]\nsolution xs = case groupBy(\\a b -> isDigit a == isDigit b) xs of\n [_, r, _, c] -> (reverse . l2rc . read $ c) ++ r\n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show . rc2l $ c)\n\nmain = interact $ unlines . map solution . tail . lines"}, {"source_code": "import Data.Char\nimport Data.List\n\nintToStr 0 = []\nintToStr x = (intToStr $ (x - 1) `div` 26) ++ [chr $ (x - 1) `mod` 26 + ord 'A']\n\nstrToInt = foldl (\\n c -> 26 * n + ord c - ord 'A' + 1) 0\n\nsolver str = case parse str of\n [_,r,_,c] -> (intToStr . read $ c) ++ r\n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show . strToInt $ c)\n where\n parse = groupBy (\\a b -> isDigit a == isDigit b)\n\nmain = interact $ unlines . map solver . tail . lines"}, {"source_code": "import Data.List\nimport Data.Char\n\nfromNumber :: Int -> String\nfromNumber 0 = []\nfromNumber x = (fromNumber y) ++ [chr (z + (ord 'A') - 1)]\n where z' = x `mod` 26\n z = if z' == 0 then 26 else z'\n y' = x `div` 26\n y = if z' == 0 then y' - 1 else y'\n\ntoNumber :: String -> Int\ntoNumber s = foldl (\\sum c -> sum * 26 + (ord c - ord 'A' + 1)) 0 s\n\nsolve input = \n case pattern of\n [\"R\", r, \"C\", c] -> (fromNumber (read c)) ++ r \n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show (toNumber c))\n where pattern = groupBy (\\x y -> isDigit x == isDigit y) input\n\nmain = interact $ unlines . map solve . tail . lines"}, {"source_code": "import Data.Char\nimport Data.List\n\ncalcAlpha :: String -> Int -> Int\ncalcAlpha (x:[]) num = num * ((ord x) - (ord 'A') + 1) \ncalcAlpha (x:xs) num = num * ((ord x) - (ord 'A') + 1) + (calcAlpha xs (num*26))\n\nalphaToRC alpha num = \"R\" ++ num ++ \"C\" ++ show (calcAlpha (reverse alpha) 1) \n\n-- 26 / 26 = 1 % 0 \n-- 0 / 26 = 0 % 1\n\ncalcRC n \n |n `div` 26 == 0 = [chr (ord 'A' + (n `mod` 27) )]\n |otherwise = calcRC (-1+(n `div` 26)) ++ [chr (ord 'A' + (n `mod` 26))]\n\nrcToAlpha :: String -> String -> String\nrcToAlpha r c = calcRC ((read c :: Int)-1) ++ r\n\nparseInp :: String -> String -> [String]\nparseInp [] y = [y]\nparseInp (x:xs) y\n |y == [] = parseInp xs [x]\n |isDigit (x) == isDigit (head y) = parseInp xs (y++[x])\n |otherwise = [y] ++ parseInp xs [x]\n\n\nsolveTC :: Integer -> IO ()\nsolveTC n = do\n if (n == 0) \n then return ()\n else do\n line <- getLine\n let inp = parseInp line \"\"\n if length inp == 2\n then putStrLn $ alphaToRC (inp !! 0) (inp !! 1)\n else putStrLn $ rcToAlpha (inp !! 1) (inp !! 3)\n\n\n solveTC (n-1)\n\n\nmain = do\n line <- getLine\n let tc = (read line :: Integer)\n solveTC tc"}, {"source_code": "import Data.Char (ord, chr)\n\nmain :: IO ()\nmain = do\n s <- getContents\n putStr (unlines $ map process (tail $ lines s))\n\ncharId :: Char -> Int\ncharId c = ord c - ord 'A'\n\ncharFromId :: Int -> Char\ncharFromId c = chr ((ord 'A') + c)\n\ncharBase = (charId 'Z') + 1\n\nprocess :: String -> String\nprocess s | (length parsed) == 2 = coordsToRC $ coordsFromAB parsed\n | otherwise = coordsToAB $ coordsFromRC parsed\n where parsed = chainParse [isLetter, isDigit, isLetter, isDigit] s\n\ncoordsFromAB :: [String] -> (Int, Int)\ncoordsFromAB [col, row] = (read row, lettersToInt col)\n\ncoordsFromRC :: [String] -> (Int, Int)\ncoordsFromRC [\"R\", row, \"C\", col] = (read row, read col)\n\nlettersToInt :: String -> Int\nlettersToInt s = sum $ map (\\(val, k) -> val*k) (zip (reverse $ map (\\c -> charId c + 1) s) factors)\n where factors = iterate (*charBase) 1\n\nintToLetters :: Int -> String\nintToLetters rawn = reverse $ map one (zip (1:pows) (takeWhile (<=n) shifts))\n where\n n = rawn - 1\n\n one :: (Int, Int) -> Char\n one (p, s) = charFromId (((n - s) `div` p) `mod` charBase)\n\n pows = (iterate (*charBase) charBase)\n\n shifts :: [Int]\n shifts = gen pows 0\n where gen (x:xs) l = l:(gen xs (l+x) )\n\ncoordsToRC :: (Int, Int) -> String\ncoordsToRC (row, col) = \"R\" ++ (show row) ++ \"C\" ++ (show col)\n\ncoordsToAB :: (Int, Int) -> String\ncoordsToAB (row, col) = intToLetters col ++ show row\n\nchainParse :: [( Char -> Bool )] -> String -> [String]\nchainParse [] _ = []\nchainParse _ \"\" = []\nchainParse (f:fs) s = (extractChars f s):(chainParse fs (eatChars f s))\n\neatChars :: ( Char -> Bool ) -> String -> String\neatChars _ [] = []\neatChars f (c:cs) | f c = eatChars f cs\n | otherwise = (c:cs)\n\nextractChars :: ( Char -> Bool ) -> String -> String\nextractChars _ [] = []\nextractChars f (c:cs) | f c = c:(extractChars f cs)\n | otherwise = \"\"\n\nisDigit :: Char -> Bool\nisDigit c = c>='0' && c<='9'\n\nisLetter :: Char -> Bool\nisLetter c = (c>='a' && c<='z') || (c>='A' && c<='Z')\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport Control.Applicative\n\nmain = do\n n <- readLn\n replicateM_ n (getLine >>= putStrLn . solve)\n\nsolve :: String -> String\nsolve str =\n let (a,(b,c)) = span isDigit <$> span isUpper str\n in if null c\n then encode1 (read b) (decodeCol a)\n else encode2 (read b) (read (snd (span isUpper c)))\n\nencode1 :: Int -> Int -> String\nencode1 row col = \"R\" ++ show row ++ \"C\" ++ show col\n\nencode2 :: Int -> Int -> String\nencode2 row col = encodeCol col ++ show row\n\ndecodeCol :: String -> Int\ndecodeCol = foldl (\\a c -> 26*a + ord c - ord 'A' + 1) 0\n\nencodeCol :: Int -> String\nencodeCol r = reverse . unfoldr (\\i -> if i == 0 then Nothing else Just (chr ((i-1) `mod` 26 + ord 'A'), (i-1) `div` 26)) $ r\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Char\n\ntable = listArray (0, 25) ['A' .. 'Z'] :: UArray Int Char\n\nparse xs\n | null cs = Left (bs, as)\n | otherwise = let Left (as', bs') = parse cs in Right (bs, as') where\n (as, (bs, cs)) = span isDigit <$> span isUpper xs\n\nnumToStr n = reverse $ f n where\n f x = case (x - 1) `quotRem` 26 of\n (0 , i) -> [table ! i]\n (n', i) -> table ! i : f n'\n\nstrToNum xs = f $ reverse xs where\n f [] = 0\n f (c : cs) = (fromEnum c - fromEnum 'A' + 1) + 26 * f cs\n\nconv xs = case parse xs of\n Left (rs, cs) -> \"R\" ++ rs ++ \"C\" ++ show (strToNum cs)\n Right (rs, cs) -> numToStr (read cs) ++ rs\n\nsolve (n : xs) = conv <$> take (read n) xs\n \nmain = interact $ unlines . solve . lines\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.Sequence (Seq, empty, (|>))\nimport Data.Foldable (toList)\n\nparseRowColFormat :: String -> Maybe (Int, Int)\nparseRowColFormat s@(x : _) = if x == 'R' then go \"\" \"\" s else Nothing where\n go \"\" \"\" [] = Nothing\n go (r:rs) \"\" [] = Nothing\n go rows@(r:rs) \"\" (_: xs) = go rows xs []\n go rows@(r:rs) cols@(c:cs) [] = Just (read rows, read cols)\n go \"\" \"\" (_ : xs) = go (takeWhile isDigit xs) \"\" (dropWhile isDigit xs)\n\nparseStandartFormat :: String -> Maybe (String, Int)\nparseStandartFormat s = go \"\" \"\" s where\n go \"\" \"\" [] = Nothing\n go (c:cs) \"\" [] = Nothing\n go cols@(c:cs) \"\" xss@(x:xs) = if any isAlpha xss then Nothing else go cols xss []\n go cols@(c:cs) rows@(r:rs) [] = Just (cols, read rows)\n go \"\" \"\" xs = go (takeWhile isAlpha xs) \"\" (dropWhile isAlpha xs)\n\ncol2Alpha :: Int -> String\ncol2Alpha = toList . go where\n go 0 = empty\n go col = go ((col - 1) `div` 26) |> chr((col - 1) `mod` 26 + ord('A'))\n\nalpha2Col :: String -> Int\nalpha2Col col = foldl (\\acc c -> acc*26 + ord(c) - ord('A') + 1) 0 col\n\nparse :: String -> String\nparse format = case parseRowColFormat format of\n Just (row, col) -> col2Alpha col ++ show row\n Nothing -> case parseStandartFormat format of\n Just (scol, srow) -> ('R' : show srow) ++ ('C' : (show $ alpha2Col scol))\n Nothing -> \"\"\n\nmain =\n read <$> getLine >>= \\n -> \n replicateM_ n (parse <$> getLine >>= putStrLn)"}, {"source_code": "module Main(main) where\n\nimport Control.Arrow\nimport Data.Char\nimport Data.List\nimport Numeric\nimport Data.Function\n\nisRXCY = dropWhile isAsciiUpper >>> dropWhile isDigit >>> null >>> not\ntoRXCY = readInt 26 isAsciiUpper (\\x -> ord x - ord 'A' +1) >>> head >>> \\ (c,r) -> 'R': r ++ \"C\" ++ show c\n\nfromRXCY' = read >>> unfoldr (\\x -> if x==0 then Nothing else Just ((x-1)`mod`26 + 1,(x-1)`div`26)) >>> reverse >>> map (\\x -> chr $ x-1 + ord 'A')\nfromRXCY = groupBy ((==) `on` generalCategory) >>> \\ (_:r:_:c:_) -> fromRXCY' c ++ r\n\nmain = do\n n:xs <- lines `fmap` getContents\n putStr $ ($ xs) $ take (read n) >>> map (\\x -> if isRXCY x then fromRXCY x else toRXCY x) >>> unlines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Char\n\nto26 :: Int -> [Char]\nto26 n = helper n 26\n where\n helper n k | k >= n = to26' (n-1) k\n helper n k = helper (n - k) (k * 26)\n to26' n k\n | k == 1 = []\n | otherwise = chr (ord 'A' + div') : to26' mod' k'\n where\n k' = k `div` 26\n (div', mod') = divMod n k'\n\nfrom26 :: [Char] -> Int\nfrom26 s = from26' (reverse s) + 1 + sum [ 26^i | i <- [1..len-1]]\n where\n len = length s\n from26' [] = 0\n from26' (x:xs) = from26' xs * 26 + (ord x - ord 'A')\n\ncheckRC :: [Char] -> Bool\ncheckRC str = (head str == 'R') && (isDigit $ str !! 1) && (elem 'C' str)\n\nrc2xy :: [Char] -> [Char]\nrc2xy str = to26 c ++ show r\n where\n [r,c] = map read . words $ map (\\ch -> if isDigit ch then ch else ' ') str\n\nxy2rc :: [Char] -> [Char]\nxy2rc str = \"R\" ++ y ++ \"C\" ++ show (from26 x)\n where\n (x,y) = span isUpper str\n\nsolve :: [Char] -> [Char]\nsolve str = if checkRC str then rc2xy str else xy2rc str\n\nmain = interact $ unlines . (\\(n:b) -> map solve $ take (read n) b) . lines\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain :: IO ()\nmain = interact $ concatMap ((++\"\\n\") . show . convert . read) . tail . lines\n\ndata Cell = Ax String Integer | Rxcy Integer Integer\n\ninstance Show Cell where\n show (Ax a x) = a ++ show x\n show (Rxcy x y) = \"R\" ++ show x ++ \"C\" ++ show y\n\ninstance Read Cell where\n readsPrec _ s = [(listToCell list, \"\")]\n where list = foldl go [] s\n go [] c = [[c]]\n go xs c | isAlpha (head (head xs)) == isAlpha c = (head xs++[c]):tail xs\n | otherwise = [c]:xs\n listToCell [y, \"C\", x, \"R\"] = Rxcy (read x) (read y)\n listToCell [x, a] = Ax a (read x)\n listToCell _ = error \"Input error\"\n\nconvert :: Cell -> Cell\nconvert (Ax a x) = Rxcy x idx\n where nums = map (\\c -> fromIntegral $ ord c - ord 'A' + 1) (reverse a)\n idx = sum $ map (\\(b, y) -> b * 26 ^ (y :: Integer)) $ zip nums [0..]\nconvert (Rxcy x y) = Ax str x\n where str = reverse $ unfoldr go y\n go 0 = Nothing\n go n = Just (chr (ord 'A' + fromIntegral m), d)\n where (d, m) = divMod (n - 1) 26\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain :: IO ()\nmain = interact $ foldr ((++) . (++\"\\n\")) \"\" . map (show . convert . read) . tail . lines\n\ndata Cell = Ax String Integer\n | Rxcy Integer Integer\n\ninstance Show Cell where\n show (Ax a x) = a ++ show x\n show (Rxcy x y) = \"R\" ++ show x ++ \"C\" ++ show y\n\ninstance Read Cell where\n readsPrec _ s = [(cvt xxs, \"\")]\n where xxs = foldl (\\xs c -> if null xs then [[c]] else (if isAlpha (head (head xs)) == isAlpha c then (head xs++[c]):(tail xs) else [c]:xs)) [] s\n cvt [y, \"C\", x, \"R\"] = Rxcy (read x) (read y)\n cvt [x, a] = Ax a (read x)\n cvt _ = error \"Input error\"\n\nconvert :: Cell -> Cell\nconvert (Ax a x) = Rxcy x idx\n where nums = map (\\c -> fromIntegral $ ord c - ord 'A' + 1) (reverse a)\n idx = sum $ map (\\(b, y) -> b * 26 ^ y) $ zip nums [0..]\nconvert (Rxcy x y) = Ax str x\n where str = reverse $ unfoldr (\\n -> if n == 0 then Nothing else let (d, m) = divMod (n - 1) 26 in Just (['A'..'Z'] !! (fromIntegral m), d)) y\n"}, {"source_code": "import Data.Char\nimport Data.Functor\nimport Data.List\n\nconvert :: String -> String\nconvert s = case groupBy (\\a b -> isDigit a == isDigit b) s of\n [_, r, _, c] -> rc2cr r c\n [c, r] -> cr2rc c r\n where rc2cr r c = (chr . (ord 'A' +) <$> reverse (basify (read c) 26)) ++ r\n cr2rc c r = concat [\"R\", r, \"C\", show (unbasify (flip (-) (ord 'A') . ord <$> reverse c) 26)]\n basify :: Int -> Int -> [Int]\n basify 0 _ = []\n basify n q = (n - 1) `mod` q : basify ((n - 1) `div` q) q\n unbasify :: [Int] -> Int -> Int\n unbasify [] _ = 0\n unbasify (a:as) q = unbasify as q * q + a + 1\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n inp <- loop n\n mapM_ putStrLn $ convert <$> inp\n where loop :: Integer -> IO [String]\n loop 0 = return []\n loop n = do\n input <- getLine\n rest <- loop $ n - 1\n return $ input : rest\n"}, {"source_code": "module Main where\n\nimport Data.Char\n\nreadMaybe :: Read a => String -> Maybe a\nreadMaybe s = case reads s of\n [(x, \"\")] -> Just x\n _ -> Nothing\n\ntoString :: Int -> String\ntoString n = toStringAux n [] where\n\ttoStringAux n ss = let (d, m) = divMod (n - 1) 26 in\n\t\tcase d of\n\t\t0 -> chr (ord 'A' + m) : ss\n\t\t_ -> toStringAux d (chr (ord 'A' + m) : ss)\n\ntoInt :: String -> Int\ntoInt ss = toIntAux ss 0 where\n\ttoIntAux (s : []) n = (ord s - ord 'A' + 1) + n * 26\n\ttoIntAux (s : ss) n = toIntAux ss ((ord s - ord 'A' + 1) + n * 26)\n\nreadRC :: String -> Maybe (Int, Int)\nreadRC s = \n\tlet (r, s') = break isDigit s;\n\t\t(rs, s'') = break isAlpha s';\n\t\t(c, cs) = break isDigit s'' in do\n\trn <- readMaybe rs\n\tcn <- readMaybe cs\n\treturn (rn, cn)\n\nreadCR :: String -> Maybe (String, Int)\nreadCR s =\n\tlet (cs, rs) = break isDigit s in\n\tdo\n\trn <- readMaybe rs\n\treturn (cs, rn)\t\t\n\nprocess :: String -> String\nprocess s = case readRC s of\n\tJust (r, c) -> toString c ++ show r \n\t_ -> case readCR s of\n\t\tJust (c', r') -> \"R\" ++ show r' ++ \"C\" ++ show (toInt c')\n\t\t_ -> \"\"\n\nmain :: IO ()\nmain = do\n\tinput <- getContents\n\tputStrLn (unlines (map process (tail (lines input))))\n"}, {"source_code": "module Main(main) where\n\nimport Data.List(tails,foldl')\nimport Data.Maybe(fromJust)\nimport Control.Applicative\n\nreadInt :: String -> Int\nreadInt = read\n\nalphaToInt :: Char -> Int\nalphaToInt c = fromJust . lookup c $ zip ['A'..] [1..26]\n\nstrToInt :: String -> Int\nstrToInt s = let l = length s in strToInt' s l 0\n where strToInt' [] _ r = r\n strToInt' _ 0 r = r\n strToInt' (s:ss) l r = strToInt' ss (l-1) (r+(alphaToInt s)*26^(l-1))\n\nintToAlpha :: Int -> Char\nintToAlpha i = fromJust . lookup i $ zip [1..26] ['A'..]\n\nintToStr :: Int -> String\nintToStr = reverse . intToStr'\n where intToStr' 0 = \"\"\n intToStr' i = (intToAlpha ((i-1) `mod` 26 + 1)) : intToStr' ((i-1)`div`26)\n\nisCharNum :: Char -> Bool\nisCharNum c = any (c==) \"0123456789\"\n\nisExcel :: String -> Bool\nisExcel = not . any isChange . tails\n where isChange (x:y:_) = (isCharNum x) && (not $ isCharNum y)\n isChange [x] = False\n isChange [] = False\n\nfromExcel :: String -> (Int,Int)\nfromExcel = f . break isCharNum\n where f (c,r) = (strToInt c, readInt r)\n\ntoExcel :: (Int,Int) -> String\ntoExcel (c,r) = (intToStr c) ++ (show r)\n\nfromOther :: String -> (Int,Int)\nfromOther s = let ((_:r),(_:c)) = break (=='C') s in (readInt c, readInt r)\n\ntoOther :: (Int,Int) -> String\ntoOther (c,r) = \"R\" ++ show r ++ \"C\" ++ show c\n\ncalc :: String -> String\ncalc str =if isExcel str \n then toOther $ fromExcel str \n else toExcel $ fromOther str\n\nmain = do\n n <- readInt <$> getLine\n sequence_ $ take n $ repeat ((putStrLn . calc) =<< getLine)"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain = interact $ unlines . map convert . tail . lines\nconvert s = case parseAlternate s of\n Just a -> showTrad a\n Nothing -> showAlternate (parseTrad s)\n\nparseAlternate :: String -> Maybe (Int,Int)\nparseAlternate ('R' : s) = case reads s of\n [(r, 'C' : cs)] -> Just (r,read cs)\n _ -> Nothing\nparseAlternate _ = Nothing\nshowAlternate (r,c) = 'R' : show r ++ 'C' : show c\n\nparseTrad :: String -> (Int,Int)\nparseTrad s = (read r,decode c)\n where (c,r) = break isDigit s\nshowTrad (r,c) = encode c ++ show r\n\nencode = reverse . unfoldr f . pred\n where f n | n < 0 = Nothing\n | otherwise = Just (chr (ord 'A' + r), q-1) where (q,r) = n `divMod` 26\ndecode = foldl1' f . map ((subtract $ ord 'A' - 1) . ord)\n where f a b = 26*a + b\n"}, {"source_code": "import Data.Char\nmain = do\n n <- getLine\n inpStrs <- getInput (read n)\n putStrLn(solve inpStrs)\n\ngetInput :: Integer -> IO [String]\ngetInput 0 = return []\ngetInput n = do\n inpStr <- getLine\n xs <- getInput (n-1)\n return (inpStr:xs)\n\nsolve :: [String] -> String\nsolve [] = \"\"\nsolve (x:xs) = change(x) ++ \"\\n\" ++ solve(xs)\n\nchange :: String -> String\nchange x = if isRXCY px then toExcel xy else toRXCY xy\n where px = parse x (\"\",\"\",\"\",\"\")\n xy = mkXY px\n\nisRXCY :: (String,String,String,String) -> Bool\nisRXCY (a,b,c,d) = (c/=\"\")\n\nparse :: String -> (String,String,String,String) -> (String,String,String,String)\nparse [] (a,b,c,d) = (a,b,c,d)\nparse (x:xs) (a,b,c,d) = if isAlpha x then\n if b == \"\" then parse xs (a++[x],b,c,d) else parse xs (a,b,c++[x],d)\n else \n if c == \"\" then parse xs (a,b++[x],c,d) else parse xs (a,b,c,d++[x])\n\nmkXY :: (String,String,String,String) -> (Int,Int)\nmkXY (a,b,c,d) = if isRXCY (a,b,c,d) then ((read b),(read d))\n else ((read b),(stoi a))\n\nstoi :: String -> Int\nstoi [] = 0\nstoi xs = baseChange 26 (map ctoi xs)\n where ctoi x = (ord x) - (ord 'A') + 1\n baseChange x = foldl (shiftAdd x) 0\n where shiftAdd x a b = a*x + b\n\ntoRXCY :: (Int,Int) -> String\ntoRXCY (x,y) = \"R\"++(show x)++\"C\"++(show y)\ntoExcel :: (Int,Int) -> String\ntoExcel (x,y) = (itos y) ++ (show x)\n where itos x | x==0 = \"\"\n | x`mod`26 == 0 = (itos (x`div`26 - 1)) ++ \"Z\"\n | otherwise = (itos (x`div`26)) ++ (itoc (x`mod`26))\n where itoc x = [chr((ord 'A') + x - 1)]"}, {"source_code": "import Data.Char\nimport Control.Monad\n\nreadRXCY :: String -> Maybe (Int, Int)\nreadRXCY ('R':s) = case span isNumber s of\n (x@(_:_), 'C':y@(_:_)) -> Just (read x, read y)\n _ -> Nothing\nreadRXCY _ = Nothing\n\ntoAB :: Int -> String\ntoAB n | 0 <= n && n < 26 = [chr $ 0x41 + n]\n | otherwise = toAB (n `div` 26 - 1) ++ toAB (n `mod` 26)\n\nreadAB :: String -> (Int, Int)\nreadAB s = readAB' 0 s\n where\n readAB' x (c:cs)\n | isNumber c = (read $ c:cs, x)\n | otherwise = readAB' (x * 26 + ord c - 0x40) cs\n\nmain = do\n n <- fmap read getLine\n forM_ [1..n] $ \\_ -> do\n line <- getLine\n case readRXCY line of\n Just (x, y) -> putStrLn $ toAB (y - 1) ++ show x\n Nothing -> let (x, y) = readAB line\n in putStrLn $ \"R\" ++ show x ++ \"C\" ++ show y\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ntoAlp s 0 = s\ntoAlp s x = let x1 = x-1 in\n toAlp ((chr ((mod x1 26) + 65)):s) (div x1 26)\n\ntoNum x [] = x\ntoNum x (s:ss) = toNum (26*x + (ord s - 64)) ss\n\nproc s = case groupBy (\\x y -> isDigit x == isDigit y) s of\n [_,r,_,c] -> (toAlp [] $ read c) ++ r\n [c,r] -> \"R\" ++ r ++ \"C\" ++ (show (toNum 0 c))\n\nmain = interact $ unlines.map proc.tail.lines\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine\n css <- mapM (\\i -> solve n <$> getLine) [1..n]\n putStrLn $ unlines css\n\nsolve :: Int -> String -> String\nsolve _ cs = if isRXCY cs then fromRXCY cs\n else toRXCY cs\n\nisRXCY :: String -> Bool\nisRXCY = not.all isDigit.dropWhile isAlpha \n\ntoRXCY :: String -> String\ntoRXCY cs' = \"R\" ++ ns ++ \"C\" ++ rs\n where (cs,ns) = span isAlpha cs'\n rs = show $ sum $ zipWith (*) (map (26^) [0..]) $ reverse $ map (\\c->(ord c)-64) cs\n\nfromRXCY :: String -> String\nfromRXCY (c:cs) = ys' ++ xs\n where (xs,(y':ys)) = span isDigit cs\n n = sum $ zipWith (*) (map (10^) [0..]) $ reverse $ map (read.return) ys\n ys' = map (chr.(64+)) $ reverse $ to26 n\n\nto26 :: Int -> [Int]\nto26 n = if q == 0 then [r] else r:(to26 q)\n where (q,r) = divMod' n 26\n\ndivMod' x y = if r == 0 then (pred q,y) else (q,r)\n where (q,r) = divMod x y"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.Char\n\ncountSeg :: String -> Integer\ncountSeg [] = 0\ncountSeg (a:[]) = 1\ncountSeg (a:b:c)\n |isAlpha a==isAlpha b = countSeg(b:c)\n |otherwise = 1+countSeg(b:c)\n\nalphaToInt :: String -> Int -> Int\nalphaToInt [] sum = sum\nalphaToInt (a:b) sum = alphaToInt b (sum*26+ord a-64)\n\nintToAlpha :: Int -> String\nintToAlpha n\n | n<26 = chr (65+n) : []\n | otherwise = (intToAlpha (div n 26 - 1)) ++ ((chr (65+(mod n 26))):[]) \n\nsplitAll :: String -> [String]\nsplitAll [] = []\nsplitAll s = do\n let (p:q) = s\n if isAlpha p then\n let (a,b) = splitAt (length $takeWhile isAlpha s) s in\n a:splitAll b\n else\n let (a,b) = splitAt (length $takeWhile (not.isAlpha) s) s in\n a:splitAll b\n\nsolve :: Integer -> IO ()\nsolve n = do\n if (n==0) then return ()\n else do\n line <- getLine\n if countSeg line == 2 then \n let (a:b:_)=splitAll line in\n putStr $\"R\"++b++\"C\"++(show $alphaToInt a 0)++\"\\n\"\n else\n let (a:b:c:d:_)=splitAll line in\n putStr $intToAlpha (((read::String->Int) d)-1)++b++\"\\n\"\n solve (n-1)\n\nmain = do\n buf <- getLine\n let (n:_) = map (read::String->Integer) (buf:[])\n solve n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Char\n\ntable = listArray (0, 25) ['A' .. 'Z'] :: UArray Int Char\n\nparse xs\n | null cs = Left (bs, as)\n | otherwise = let Left (as', bs') = parse cs in Right (bs, as') where\n (as, (bs, cs)) = span isDigit <$> span isUpper xs\n\nnumToStr :: Int -> String\nnumToStr n = reverse $ f n where\n f x = case (x - 1) `quotRem` 26 of\n (0 , i) -> [table ! i]\n (n', i) -> table ! i : f n'\n\nstrToNum :: String -> Int\nstrToNum xs = f $ reverse xs where\n f [] = 0\n f (c : cs) = (fromEnum c - fromEnum 'A' + 1) + 26 * f cs\n\nconv xs = case parse xs of\n Left (rs, cs) -> \"R\" ++ rs ++ \"C\" ++ show (strToNum cs)\n Right (rs, cs) -> numToStr (read cs) ++ rs\n\nsolve (n : xs) = conv <$> take (read n) xs\n \nmain = interact $ unlines . solve . lines\n"}, {"source_code": "import Data.Char\n\nfromAA = foldl (\\s x -> s * 26 + (ord x - ord 'A' + 1)) 0\n\ntoAA x = let w x l = if x > 0 then w ((x - 1) `div` 26) (((x - 1) `mod` 26) : l) else l in \n map (\\x -> chr (x + ord 'A')) $ w x []\n\nparseLine line = map reverse $ reverse $ foldl (\\ll x -> case ll of {\n l:ls | isDigit (head l) == isDigit x -> (x:l) : ls\n | True -> [x]:ll\n ; [] -> [[x]]}) [] line\n\nconv [\"R\", row, \"C\", col] = toAA (read col) ++ row\nconv [col, row] = \"R\" ++ row ++ \"C\" ++ show (fromAA col)\nconv _ = undefined\n\nmain = do {\n n <-getLine\n ; mapM (\\_ -> do {line <- getLine\n ; putStr $ conv $ parseLine line\n ; putChar '\\n'\n }) [1..(read n)]\n }\n"}, {"source_code": "module Main where\n\nimport Data.Char\nimport Control.Monad\n\ndata Cell = Cell {\n row :: Int,\n column :: Int\n} deriving (Show)\n\nshowRC :: Cell -> String\nshowRC c = \"R\" <> show (row c) <> \"C\" <> show (column c)\n\nshowCR :: Cell -> String\nshowCR c = abbr (column c) <> show (row c)\n\nradix = 26\n\nabbr :: Int -> String\nabbr x = abbr0 x \"\"\n where\n abbr0 0 acc = acc\n abbr0 x acc = let y = ord 'A' + ((x - 1) `mod` radix) in abbr0 ((x - 1) `div` radix) (chr y:acc)\n\nfromAbbr :: String -> Int\nfromAbbr x = fromAbbr0 x 0\n where\n fromAbbr0 [] acc = acc\n fromAbbr0 (a:xs) acc = fromAbbr0 xs $ acc * radix + (1 + ord a - ord 'A')\n\ndata Parsed = ParsedRC Cell\n | ParsedCR Cell\n | Unknown String\n deriving (Show)\n\nsplit :: String -> [String]\nsplit line = reverse $ split1 line []\n where\n split1 [] acc = acc\n split1 line acc = let (chars, rest) = break isDigit line in\n split2 rest $ chars:acc\n split2 [] acc = acc\n split2 line acc = let (digits, rest) = span isDigit line in\n split1 rest $ digits:acc\n\nparseCell :: String -> Parsed\nparseCell line = case split line of\n [\"R\", r, \"C\", c] -> ParsedRC Cell { row = read r, column = read c }\n [c, r] -> ParsedCR Cell { row = read r, column = fromAbbr c }\n _ -> Unknown line\n\nconvert :: Parsed -> String\nconvert (Unknown x) = x\nconvert (ParsedCR c) = showRC c\nconvert (ParsedRC c) = showCR c\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine\n forM_ inputs $ putStrLn . convert . parseCell"}, {"source_code": "import Data.Char\n\nisAbc123 :: String -> Bool\nisAbc123 (ch:rest)\n | isAlpha ch = isAbc123 rest\n | otherwise = and $ map isDigit rest\n \nan2rc :: String -> String\nan2rc an = \"R\" ++ rowStr ++ \"C\" ++ (show $ excel2Num 0 colExcel)\n where\n splitAbc123 cur whole@(ch:rest)\n | isDigit ch = (cur, whole)\n | otherwise = splitAbc123 (cur++[ch]) rest\n (colExcel, rowStr) = splitAbc123 \"\" an\n excel2Num acc \"\" = acc\n excel2Num acc (ch:rest) = excel2Num (acc*26+ord(ch)-ord('A')+1) rest\n\nrc2an :: String -> String\nrc2an rc = (excelNota col) ++ rowStr\n where\n stripNums cur (ch:rest)\n | ch == 'R' = stripNums cur rest\n | ch == 'C' = (cur, rest)\n | otherwise = stripNums (cur++[ch]) rest\n (rowStr, colStr) = stripNums \"\" rc\n col = read colStr :: Int\n excelNota 0 = \"\"\n excelNota n = (excelNota $ (n-1) `div` 26) ++ [chr $ (n-1) `mod` 26 + ord('A')]\n\nconvert :: String -> String\nconvert s\n | isAbc123 s = an2rc s\n | otherwise = rc2an s\n\nmain :: IO ()\nmain = do\n t <- (read :: String -> Int) <$> getLine\n run t\n where\n run 0 = return ()\n run n = do\n coord <- getLine\n putStrLn $ convert coord\n run (n-1)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Char\nimport Data.List\n\nsplitVia l h = go []\n where go acc [] = (reverse acc, [])\n go acc r@(c:cs) | o >= l && o <= h = go (c:acc) cs\n | otherwise = (reverse acc,r)\n where o = ord c\n \nf26 = show . foldl' f 0\n where f a c = (ord c - 64) + a*26\n \nt26 n = go [] $ n - 1 \n where go acc m | m < 0 = acc\n | otherwise = go ((chr $ m `rem` 26 + 65) : acc) (m `quot` 26 - 1)\n\ntransform s0 | a == \"R\" && c == \"C\" = (t26 $ read d) ++ b\n | null c && null d = \"R\" ++ b ++ \"C\" ++ (f26 a)\n where (a, s1) = splitVia 65 90 s0\n (b, s2) = splitVia 48 57 s1\n (c, s3) = splitVia 65 90 s2\n (d, s4) = splitVia 48 57 s3\n\nmain = interact (unlines . map transform . tail . lines)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Char\n\nabc = ['A'..'Z']\nztn = ['0'..'9']\n\nsplitVia ps = go []\n where go acc [] = (reverse acc, [])\n go acc r@(l:ls) | l `elem` ps = go (l:acc) ls\n | otherwise = (reverse acc,r)\n \nf26 = show . foldl f 0\n where f a c = (ord c - 64) + a*26\n \nt26 n = go [] $ n - 1 \n where go acc m | m < 0 = acc\n | otherwise = go ((chr $ m `rem` 26 + 65) : acc) (m `quot` 26 - 1)\n\ntransform s0 | a == \"R\" && c == \"C\" = (t26 $ read d) ++ b\n | null c && null d = \"R\" ++ b ++ \"C\" ++ (f26 a)\n where (a, s1) = splitVia abc s0\n (b, s2) = splitVia ztn s1\n (c, s3) = splitVia abc s2\n (d, s4) = splitVia ztn s3\n\nmain = interact (unlines . map transform . tail . lines)"}, {"source_code": "import Data.Char\n\nabc = ['A'..'Z']\nztn = ['0'..'9']\n\nsplitVia ps = go []\n where go acc [] = (reverse acc, [])\n go acc r@(l:ls) | l `elem` ps = go (l:acc) ls\n | otherwise = (reverse acc,r)\n \nf26 = show . foldl f 0\n where f a c = (ord c - 64) + a*26\n \nt26 n = go [] $ n - 1 \n where go acc m | m < 0 = acc\n | otherwise = go ((chr $ m `rem` 26 + 65) : acc) (m `quot` 26 - 1)\n\ntransform s0 | a == \"R\" && c == \"C\" = (t26 $ read d) ++ b\n | null c && null d = \"R\" ++ b ++ \"C\" ++ (f26 a)\n where (a, s1) = splitVia abc s0\n (b, s2) = splitVia ztn s1\n (c, s3) = splitVia abc s2\n (d, s4) = splitVia ztn s3\n\nmain = interact (unlines . map transform . tail . lines)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.Char\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\ninRange :: Ord a => (a,a) -> a -> Bool\ninRange (n,m) x = n<=x&&x<=m\n\nisExcel :: String -> Bool\nisExcel = null.(dropWhile isDigit).(dropWhile isAlpha)\n\nexceltoRC :: String -> String\nexceltoRC str = let (c',r) = span (inRange ('A','Z')) str in\n let c = foldl (\\s -> \\c -> (ord c)-(ord 'A')+1+s*26) 0 c' in\n ('R':r)++('C':(show c))\n\nrctoExcel :: String -> String\nrctoExcel (_:str) = let (r,(_:c')) = span (inRange ('0','9')) str in\n let c = unfoldr (\\x -> if x==0 then Nothing else Just (chr ((mod (x+25) 26)+(ord 'A')),div x 26 + (if mod x 26 == 0 then -1 else 0))) (read c'::Int) in\n (reverse c)++r\n\nsolve [] = []\nsolve (x:xs) = (if isExcel x then exceltoRC x else rctoExcel x):solve xs\n\nmain = do n <- scan :: IO Int\n l <- scans n ::IO [String]\n putAnsLns (solve l)"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\n\ns2i = foldl (\\a x -> 26*a + ord x - ord 'A' + 1) 0\n\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\nconv s =\n\tcase groupBy (\\a b -> isDigit a == isDigit b) s of\n\t\t[_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n\t\t[c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\nmain = do\n\thSetBuffering stdin (BlockBuffering (Just 32768))\n\tinteract $ unlines . map conv . tail . lines\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ns2i = foldl (\\s d -> 26*s + ord d - ord 'A' + 1) 0\n\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\nconv s =\n\tcase groupBy (\\a b -> isDigit a == isDigit b) s of\n\t\t[_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n\t\t[c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\nmain = interact $ unlines . map conv . tail . lines\n"}, {"source_code": "import Data.Char\n\nisRC s = s !! 0 == 'R' && isDigit (s !! 1) && 'C' `elem` s\n\nfrom26 [] = 0\nfrom26 (d:ds) = (ord d - ord 'A' + 1) * 26 ^ length ds + from26 ds\n\ntoRC s = \"R\" ++ y ++ \"C\" ++ show (from26 x) where (x, y) = span isUpper s\n\nto26 0 = []\nto26 a = [chr (ord 'A' + (a - 1) `mod` 26)] ++ (to26 $ (a - 1) `div` 26)\n\ntoXY s = reverse (to26 c) ++ show r where [r, c] = map read . words $ map (\\c -> if isDigit c then c else ' ') s\n\nconv s = if isRC s then toXY s else toRC s\n\nmain = interact $ unlines . map conv . drop 1 . lines\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\n\ns2i = foldl (\\a x -> 26*a + ord x - ord 'A' + 1) 0\n\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\nconv s =\n\tcase groupBy (\\a b -> isDigit a == isDigit b) s of\n\t\t[_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n\t\t[c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\nmain = do\n\thSetBuffering stdin (BlockBuffering (Just 4096))\n\tinteract $ unlines . map conv . tail . lines\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\n\ns2i = foldl (\\a x -> 26*a + ord x - ord 'A' + 1) 0\n\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\nconv s =\n\tcase groupBy (\\a b -> isDigit a == isDigit b) s of\n\t\t[_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n\t\t[c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\n-- main = interact $ unlines . map conv . tail . lines\n\nmain = do\n\tn <- fmap read getLine\n\tforM_ [1..n] $ \\_ -> do\n\t\tl <- getLine\n\t\tputStrLn (conv l)\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\n\ns2i = foldl (\\a x -> 26*a + ord x - ord 'A' + 1) 0\n\ni2s 0 = []\ni2s a = chr (ord 'A' + (a - 1) `mod` 26) : (i2s $ (a - 1) `div` 26)\n\nconv s =\n\tcase groupBy (\\a b -> isDigit a == isDigit b) s of\n\t\t[_, r, _, c] -> (reverse . i2s . read $ c) ++ r\n\t\t[c, r] -> \"R\" ++ r ++ \"C\" ++ (show . s2i $ c)\n\nmain = interact $ unlines . map conv . tail . lines\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt\n inputs <- replicateM n getLine\n mapM_ putStrLn $ parseInputs inputs\n\nparseInputs :: [String] -> [String]\nparseInputs [] = []\nparseInputs (x:xs) = [spreadSheets x] ++ parseInputs xs\n\nspreadSheets :: String -> String\nspreadSheets s = case xs of\n [_,r,_,c] -> rc (read r) (read c)\n [c,r] -> cr c (read r) \n\n where xs = groupBy(\\a b -> (isDigit a && isDigit b) || (isAlpha a && isAlpha b)) s\n\n\ncr :: String -> Int -> String\ncr c r = \"R\" ++ (show r) ++ \"C\" ++ show (conv c)\n\nconv :: String -> Int\nconv [] = 1\nconv (r:[]) = ord r - ord 'A' + 1\nconv (r:rs) = 26^(length rs) * (ord r - ord 'A' + 1) + conv rs\n\nrc :: Int -> Int -> String\nrc r c = (inv c) ++ show r\n\ninv :: Int -> String\ninv 0 = \"\"\ninv a = inv ((a - 1) `div` 26) ++ [chr (ord 'A' + (a - 1) `mod` 26)]\n\nreadInt :: IO Int\nreadInt = readLn\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nmapX :: a -> [a -> b] -> [b]\nmapX _ [] = []\nmapX x (f:fs) = [f x] ++ (mapX x fs)\n\nmap2 :: (a -> b -> c) -> [a] -> [b] -> [c]\nmap2 _ [] [] = []\nmap2 f (ax:axs) (bx:bxs) = [f ax bx] ++ map2 f axs bxs\n\nisEmpty :: [a] -> Bool\nisEmpty [] = True\nisEmpty _ = False\n\nall' :: (a -> Bool) -> [a] -> Bool\nall' _ [] = False\nall' f l = all f l\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\ntype CellType = Int\n\ncheckCellType :: String -> CellType\ncheckCellType s\n | length (splitByPredicate isDigit s) == 4 = 1\n | length (splitByPredicate isDigit s) == 2 = 2\n | otherwise = error \"wrong string!\"\n\nfastExp :: Int -> Int -> Int\nfastExp x 0 = 1\nfastExp x 1 = x\nfastExp x a\n | even a = lexp * lexp\n | odd a = lexp * lexp * x\n where\n lexp = fastExp x (div a 2)\n\ncolStr2Inth :: String -> Int\ncolStr2Inth [] = 0\ncolStr2Inth s = (colStr2Inth $ init s) * 26 + (ord (last s) - ord 'A')\n\ncolStr2Int :: String -> Int\ncolStr2Int s = sum (map (fastExp 26) [0 .. (length s - 1)]) + colStr2Inth s\n\nconvertCellType2To1 :: String -> String\nconvertCellType2To1 s = \n let sp = splitByPredicate isDigit s\n in \"R\" ++ (sp !! 1) ++ \"C\" ++ (show $ colStr2Int (sp !! 0))\n\n\ncolInt2Strhh :: Int -> String\ncolInt2Strhh n \n | n < 26 = [chr (ord 'A' + n)]\n | otherwise = (colInt2Strhh (div n 26)) ++ (colInt2Strhh (mod n 26))\n\ncolInt2Strh :: Int -> Int -> String\ncolInt2Strh n l =\n let hresult = colInt2Strhh n\n in (replicate (l - length hresult)) 'A' ++ hresult \n\ncolInt2Str :: Int -> String\ncolInt2Str n = \n let powList = map (fastExp 26) [0 .. 100]\n sumPowList = scanl1 (+) powList\n fi = fromJust (findIndex (<0) (map2 (-) (replicate 100 n) sumPowList))\n in colInt2Strh (n - (sumPowList !! (fi - 1))) (fi)\n\n\nconvertCellType1To2 :: String -> String\nconvertCellType1To2 s =\n let sp = splitByPredicate isDigit s\n in colInt2Str (read (sp !! 3) :: Int) ++ (sp !! 1)\n\n\nconvertCellType :: String -> String\nconvertCellType s\n | checkCellType s == 1 = convertCellType1To2 s\n | checkCellType s == 2 = convertCellType2To1 s\n\n\n\nmain = do\n {- putStrLn $ show $ fastExp 26 2-}\n {- putStrLn $ show $ fastExp 26 3\n putStrLn $ show (scanl1 (+) (map (fastExp 26) [0 .. 20]))\n putStrLn $ show $ colStr2Inth \"AUHS\"-}\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n putStrLn $ unlines (map convertCellType sl)\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain = interact $ unlines . map conv . tail . lines\n\nconv s = to arr\n where arr = groupBy (\\a b -> isDigit a == isDigit b) s \n\nrc (ch:s) = ch == 'R'\n\nto [c, r] = \"R\" ++ r ++ \"C\" ++ (show . toRCcolumn $ c)\nto [_, r, _, c] = (reverse . toXYcolumn . read $ c) ++ r\n\ntoRCcolumn = foldl (\\acc d -> 26 * acc + ord d - ord 'A' + 1) 0\n\ntoXYcolumn 0 = []\ntoXYcolumn c = (chr (cmod + ord 'A')) : toXYcolumn cdiv\n where (cdiv, cmod) = (c - 1) `divMod` 26"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain = interact $ unlines . map conv . tail . lines\n\nconv s = to arr\n where arr = groupBy (\\a b -> isDigit a == isDigit b) s \n\nto [c, r] = \"R\" ++ r ++ \"C\" ++ (show . toRCcolumn $ c)\nto [_, r, _, c] = (reverse . toXYcolumn . read $ c) ++ r\n\ntoRCcolumn = foldl (\\acc d -> 26 * acc + ord d - ord 'A' + 1) 0\n\ntoXYcolumn 0 = []\ntoXYcolumn c = (chr $ cmod + ord 'A') : toXYcolumn cdiv\n where (cdiv, cmod) = (c - 1) `divMod` 26"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.List\nimport Data.Char\n\nletters = map (\\x -> chr (ord 'A' + (x - 1) `mod` 26)) . reverse . takeWhile (>0) . iterate (\\x -> (x-1) `div` 26)\nnumbers = sum . zipWith (*) (iterate (*26) 1) . reverse . map (\\x -> ord x - ord 'A' + 1)\n\nconvert :: [String] -> String\nconvert (\"R\":r:\"C\":c:[]) = letters (read c) ++ r\nconvert (c:r:[]) = \"R\" ++ r ++ \"C\" ++ show (numbers c)\n\nmain = do\n (n :: Int,cells) <- getContents >>= return . (\\(n:cells) -> (read n,map (map toUpper) cells)) . lines\n mapM (putStrLn . convert . groupBy (\\l r -> isDigit l == isDigit r)) (take n cells)\n\n"}, {"source_code": "{- Format 1 is letters for columns and numbers for the row.\n - eg. BC23 -}\nimport Data.Char\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport System.IO\nimport Data.List \n\nreverseColumnMap = Map.fromList $ zip letters [1..1000000]\n\nletters = (map (\\x -> [x]) gen) ++ (next $ (map (\\x -> [x]) gen))\n where gen = ['A'..'Z']\n next list = this ++ (next this)\n where this = concat $ map (\\x -> map (x:) list) gen\n\nencode1 :: (Int, Int) -> String\nencode1 (row, col) = convertCol col ++ (show row)\nconvertCol c = toLetters $ pad $ toBase26 $ (c - offset)\n where offset = sum $ map (26^) [1..lim-1]\n lim = limit c\n limit x = fromJust $ findIndex (>=x) limits\n limits = scanl (+) 0 (map (26^) [1..])\n toBase26 x = fromBase10 (x - 1) 26\n pad xs = if length xs < lim then pad (0:xs) else xs\n toLetters = map (chr.(+(ord 'A')))\n fromBase10 :: (Integral a) => a -> a -> [a]\n fromBase10 n base = reverse $ fromBase10Reversed n base\n where \n fromBase10Reversed :: (Integral a) => a -> a -> [a]\n fromBase10Reversed n base \n | n < base = [n]\n | otherwise = firstDigit:(fromBase10Reversed rest base)\n where firstDigit = (n `rem` base)\n rest = (n `div` base)\n\ndecode1 :: (String) -> (Int, Int)\ndecode1 string = let (letters, numbers) = split string\n in ((read numbers)::Int, parse letters)\n where split [] = (\"\", \"\")\n split (x:xs) = if (isAlpha x)\n then (x:(fst next), snd next)\n else (\"\", x:xs)\n where next = split xs\n\nparse l = (toBase10 (toNumbers l) 26) + offset\n where offset = 1 + (sum $ map (26^) [1..(length l) - 1])\n toBase10 :: (Integral a) => [a] -> a -> a\n toBase10 n base = sum $ map (\\(a, b) -> (base^a) * b) (placeValuePairs n)\n where \n placeValuePairs :: (Integral a) => [a] -> [(a, a)]\n placeValuePairs digits = zip placeCount digits\n where placeCount = [len - 1, len - 2..0]\n len = fromIntegral $ length digits\n toNumbers l = map ((+ (-(ord 'A'))).ord) l\n\nencode2 :: (Int, Int) -> String\nencode2 (row, col) = \"R\" ++ (show row) ++ \"C\" ++ (show col)\n\ndecode2 (x:xs) = let (firstNum, remaining) = getFirstNum xs\n in ((read firstNum)::Int, (read $ tail remaining)::Int)\n where getFirstNum (y:ys) = if isDigit y\n then ((y : (fst next)), snd next)\n else (\"\", y:ys)\n where next = getFirstNum ys\n \nprocess :: String -> String\nprocess xs = if type2\n then encode1 $ decode2 xs\n else encode2 $ decode1 xs\n where type2 = (isDigit (xs !! 1)) && ('C' `elem` (tail xs))\n\nf :: String -> IO Int\nf string = return ((read string)::Int)\n\nmain = do\n hGetLine stdin\n inpStr <- hGetContents stdin\n let toProcess = lines inpStr\n putStr $ unlines $ map process toProcess\n\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.DeepSeq\nimport Data.Function\nimport Data.List\nimport Data.Char\n\n--import Debug.Trace\n\ntype AlphaNum = String -- little endian\n\nstr2an = reverse\nan2str = reverse\n\ndata Numeration = T1 String Int | T2 Int Int\n\ninstance Show Numeration where\n show (T1 col row) = col ++ show row\n show (T2 row col) = \"R\" ++ show row ++ \"C\" ++ show col\n\nisT2 (r:x:cy) = (r == 'R') && isDigit x && ('C' `elem` cy)\nisT2 _ = False\n\ntoT1 str = T1 col (read row) where\n (col, row) = span isLetter str\n\ntoT2 str = T2 (read row) (read col) where\n (r:row, c:col) = span ((/=) 'C') str\n\nconvertType (T1 col row) = T2 row (atoi col)\nconvertType (T2 row col) = T1 (itoa col) row\n\n-- 'i' is 0-index\natoi [] = 0\natoi str = (ord x - ord 'A' + 1) + (26 * atoi xs) where\n x = last str\n xs = init str\n\nitoc i = chr (ord 'A' + i - 1)\nitoa i = if q' == 0 then [itoc r'] else itoa q' ++ [itoc r'] where\n (q, r) = i `divMod` 26\n (q', r') = if r == 0 then (q-1, 26) else (q, r)\n\nprocess :: String -> String\nprocess str = show numeration' where\n numeration = if isT2 str then toT2 str else toT1 str\n numeration' = convertType numeration\n\nprintLines = fmap head . sequence . map putStrLn\n\nmain = do\n n <- read <$> getLine\n lines <- replicateM n getLine\n printLines (map process lines)\n\n"}, {"source_code": " {-# OPTIONS_GHC -O2 #-}\n\n import Data.Char\n\n to26 :: Int -> [Char]\n to26 n = helper n 26\n where\n helper n k | k >= n = to26' (n-1) k\n helper n k = helper (n - k) (k * 26)\n to26' n k\n | k == 1 = []\n | otherwise = chr (ord 'A' + div') : to26' mod' k'\n where\n k' = k `div` 26\n (div', mod') = divMod n k'\n\n from26 :: [Char] -> Int\n from26 s = from26' (reverse s) + 1 + sum [ 26^i | i <- [1..len-1]]\n where\n len = length s\n from26' [] = 0\n from26' (x:xs) = from26' xs * 26 + (ord x - ord 'A')\n\n checkRC :: [Char] -> Bool\n checkRC str = (head str == 'R') && (isDigit $ str !! 1) && (elem 'C' str)\n\n rc2xy :: [Char] -> [Char]\n rc2xy str = to26 c ++ show r\n where\n [r,c] = map read . words $ map (\\ch -> if isDigit ch then ch else ' ') str\n\n xy2rc :: [Char] -> [Char]\n xy2rc str = \"R\" ++ y ++ \"C\" ++ show (from26 x)\n where\n (x,y) = span isUpper str\n\n solve :: [Char] -> [Char]\n solve str = if checkRC str then rc2xy str else xy2rc str\n\n main = interact $ unlines . (\\(n:b) -> map solve $ take (read n) b) . lines"}, {"source_code": "module Main where\n--module Test where\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmain = do line <- getLine\n let n = read line :: Int\n run_testcase n\n return ()\n\ntonum c = ord c - ord 'A'\n\nconvert_to_index [c] = tonum c\n\n-- A -> 0\n-- AA -> 26\n-- AB -> 27\nconvert_to_index (x:xs) = (tonum x) + ((convert_to_index xs) + 1) * 26 \n\nconvert_to_str num \n | num < 26 = [chr $ num + ord 'A']\n | otherwise = convert_to_str (num `div` 26 - 1) ++ [chr ((num `mod` 26) + ord 'A')]\n\nis_rc_format str = (check rs 'R') && (check cs 'C')\n where \n (rs,cs) = break ('C'==) str\n check token c = length token >= 2 && head token == c && all isDigit (tail token)\n\nsolve2 str \n | is_rc_format(str) = \n let (rs,cs) = break ('C'==) str\n r = tail rs\n c = read $ tail cs :: Int\n in\n convert_to_str(c - 1) ++ (r)\n | otherwise = \n let (c,r) = break isDigit str\n in\n \"R\" ++ r ++ \"C\" ++ show ((convert_to_index $ reverse c) + 1) \n\nrun_testcase 0 = do return ()\nrun_testcase n = \n do \n line <- getLine \n putStrLn $ solve2 line\n run_testcase (n-1)\n return ()\n \n"}, {"source_code": "import Data.Char\nimport Data.List\n\nintToStr 0 = []\nintToStr x = chr ( ( x - 1 ) `mod` 26 + ord 'A' ) : intToStr ( ( x - 1 ) `div` 26 )\n\nstrToInt = foldl ( \\ x y -> 26 * x + ord y - ord 'A' + 1 ) 0\n\nsolve str =\n\tcase parse str of\n\t\t[_,r,_,c] -> ( reverse . intToStr . read $ c ) ++ r\n\t\t[c,r] -> \"R\" ++ r ++ \"C\" ++ ( show . strToInt $ c )\n\twhere parse = groupBy ( \\ a b -> isDigit a == isDigit b )\n\nmain = interact $ unlines . map solve . tail . lines\n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n == 0 = \"\"\n | otherwise = n2a (m `div` 26) ++ [c (m `mod` 26)]\n where\n m = n - 1\n c x = chr (ord 'A' + x)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n\nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n"}, {"source_code": "import Data.Char\nimport Data.List\nintToStr 0 = []\nintToStr x = (intToStr $ (x - 1) `div` 26) ++ [chr $ (x - 1) `mod` 26 + ord 'A']\nstrToInt = foldl (\\ s c -> 26 * s + ord c - ord 'A' + 1) 0\nf str = case parse str of \n [_,r,_,c] -> (intToStr . read $ c) ++ r\n [c,r] -> \"R\" ++ r ++ \"C\" ++ (show . strToInt $ c)\n where \n parse = groupBy (\\a b -> isDigit a == isDigit b)\nmain = interact $ unlines . map f . tail . lines"}, {"source_code": "import Data.Char\nimport Data.Function\nimport Data.List\n\nfromBase26 :: String->Int\n-- 64 = 'A' - 1\nfromBase26 s = foldl (\\acc c->acc*26 + ord c -64) 0 s\n\ntoBase26::Int->String\ntoBase26 i = if i == 0\n then []\n else toBase26 ((i - 1) `div` 26) ++ return (chr ((i-1) `mod` 26 + 65))\n\nparseSplit input = groupBy ((==) `on` isAlpha) input\n \ntransform :: [String] -> String\ntransform [_, r, _, c] = toBase26 (read c::Int) ++ r\ntransform [c, r] = \"R\" ++ r ++ \"C\" ++ show (fromBase26 c)\n\nact :: IO()\nact = do\n s<-getLine\n putStrLn $ transform $ parseSplit s\n\nmain = do\n s<-getLine\n let testNum = read s::Int\n mapM_ (\\x->act) $take testNum[1..]\n return ()\n"}, {"source_code": "import Data.Char\nimport Data.Function\nimport Data.List\n\nfromBase26 :: String->Int\n-- 64 = 'A' - 1\nfromBase26 s = foldl (\\acc c->acc*26 + ord c - 64) 0 s\n\ntoBase26::Int->String\ntoBase26 0 = []\ntoBase26 i = toBase26 ((i - 1) `div` 26) ++ [chr ((i-1) `mod` 26 + 65)]\n\nparseSplit input = groupBy ((==) `on` isAlpha) input\n \ntransform :: [String] -> String\ntransform [_, r, _, c] = (toBase26.read) c ++ r\ntransform [c, r] = \"R\" ++ r ++ \"C\" ++ show (fromBase26 c)\n\nmain = do\n --Skip the first line\n s<-getLine\n interact $ unlines.map (transform.parseSplit).lines\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.Char\n\n-- Meat\nsolve :: [String] -> [String]\nsolve = fmap (disp . convert . parse)\n where\n convert c@(ExcelCell _ _) = getLotus $ toCanonical c\n convert c@(LotusCell _ _ ) = getExcel $ toCanonical c\n\ndata Cell = ExcelCell String Int | LotusCell Int Int deriving (Show)\n\ndisp :: Cell -> String\ndisp (ExcelCell col row) = col ++ show row\ndisp (LotusCell row col) = \"R\" ++ show row ++ \"C\" ++ show col\n\nparse :: String -> Cell\nparse s\n | null rrs = ExcelCell initAlpha (read initNum)\n | otherwise = LotusCell (read initNum) (findColumn rrs)\n where (initAlpha, rs) = span isAlpha s\n (initNum, rrs) = span isDigit rs\n findColumn :: String -> Int\n findColumn = read . dropWhile isAlpha\n\n\ntoCanonical :: Cell -> (Int, Int)\ntoCanonical (LotusCell row col) = (row, col)\ntoCanonical (ExcelCell col row) = (row, aTN col)\n\ngetExcel :: (Int, Int) -> Cell\ngetExcel (r, c) = ExcelCell (nTA c) r\n\ngetLotus :: (Int, Int) -> Cell\ngetLotus (r, c) = LotusCell r c\n\naTN :: String -> Int\naTN [x] = ord x - ord 'A' + 1\naTN (x:xs) = prelim * aTN[x] + aTN xs\n where prelim = aTN (replicate (l - 1) 'Y' ++ \"Z\")\n l = length xs\naTN [] = error \"You suck\"\n\nnTA :: Int -> String\nnTA n\n | n <= 26 = [chr (64 + n)]\n | r == 0 = nTA (q - 1) ++ \"Z\"\n | otherwise = nTA q ++ nTA r\n where (q, r) = n `quotRem` 26\n\n-- Shit\nmain :: IO ()\nmain = do\n _:xs <- readShit\n printShitV $ solve xs\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "import Data.Char\n\ndata CharType = Alpha | Digit | Unknown\n deriving (Eq)\n\ndata CellFormat = ABC123 | RXCY\n deriving (Show)\ndata CellRef = CellRef {\n row :: Integer,\n column :: Integer\n} deriving (Show)\n\ncharType :: Char -> CharType\ncharType c | isDigit c = Digit\n | isAlpha c = Alpha\n | otherwise = Unknown\n\nstringType :: String -> CharType\nstringType s = charType (head s)\n\nsplit :: String -> [String]\nsplit s = reverse (split2 s [])\n\nsplit2 :: String -> [String] -> [String]\nsplit2 [] xs = xs\nsplit2 (c:cs) [] = split2 cs [[c]]\nsplit2 (c:cs) (x:xs) | charType c == charType (head x) = split2 cs ((x ++ [c]):xs)\n | otherwise = split2 cs ([c]:x:xs)\n\n\nreadColumnRef :: String -> Integer\nreadColumnRef s = readColumnRef2 0 s\n where readColumnRef2 v [] = v\n readColumnRef2 v (x:xs) = readColumnRef2 (v*26 + toInteger (ord (toUpper x) - ord 'A' + 1)) xs\n\nshowColumnRef :: Integer -> String\nshowColumnRef x = showColumnRef2 \"\" x\n where showColumnRef2 :: String -> Integer -> String\n showColumnRef2 [] 0 = \"A\"\n showColumnRef2 s 0 = s\n showColumnRef2 s x = showColumnRef2 ([chr ((fromIntegral ((x-1) `mod` 26)) + ord 'A')] ++ s) ((x-1) `div` 26)\n\nreadCellRef :: String -> (CellRef, CellFormat)\nreadCellRef s = case (split s) of\n (\"R\":x:\"C\":y:[]) ->\n (CellRef (read x) (read y), RXCY)\n (a:x:[]) | (stringType a == Alpha) && (stringType x == Digit) ->\n (CellRef (read x) (readColumnRef a), ABC123)\n _ -> error \"Invalid cell reference format\"\n\nshowCellRef :: CellRef -> CellFormat -> String\nshowCellRef c ABC123 = (showColumnRef (column c)) ++ (show (row c))\nshowCellRef c RXCY = \"R\" ++ (show (row c)) ++ \"C\" ++ (show (column c))\n\nconvert :: String -> String\nconvert s = case (readCellRef s) of\n (c, ABC123) -> showCellRef c RXCY\n (c, RXCY) -> showCellRef c ABC123\n\nsolve :: IO ()\nsolve = getLine >>= (putStrLn . convert)\n\nsolveN :: Int -> IO ()\nsolveN 1 = solve\nsolveN n = do\n solve\n solveN (n-1)\n\nmain = getLine >>= (solveN . read)\n\n"}, {"source_code": "{-\nB. Spreadsheets\n=====================\ntime limit per test: 10 seconds\nmemory limit per test: 64 megabytes\ninput: standard input\noutput: standard output\n=====================\nIn the popular spreadsheets systems (for example, in Excel) the following\nnumeration of columns is used. The first column has number A, the second \u2014 number\nB, etc. till column 26 that is marked by Z. Then there are two-letter numbers:\ncolumn 27 has number AA, 28 \u2014 AB, column 52 is marked by AZ. After ZZ there\nfollow three-letter numbers, etc.\n\nThe rows are marked by integer numbers starting with 1. The cell name is the\nconcatenation of the column and the row numbers. For example, BC23 is the name\nfor the cell that is in column 55, row 23.\n\nSometimes another numeration system is used: RXCY, where X and Y are integer\nnumbers, showing the column and the row numbers respectfully. For instance,\nR23C55 is the cell from the previous example.\n\nYour task is to write a program that reads the given sequence of cell\ncoordinates and produce each item written according to the rules of another\nnumeration system.\n---------------------\nInput\nThe first line of the input contains integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106.\n\nOutput\nWrite n lines, each line should contain a cell coordinates in the other numeration system.\n=====================\n-}\nimport Data.List(groupBy)\nimport Data.Char(chr,isDigit,ord)\n\nequatingDigits a b = isDigit a == isDigit b\n\nisRC :: String -> Bool\nisRC = (==4) . length . groupBy equatingDigits\n\nreadNLines :: Int -> IO [String]\nreadNLines 1 = do\n line <- getLine\n return [line]\nreadNLines n = do\n line <- getLine\n moreLines <- readNLines (n-1)\n return $ line:moreLines\n\nconvert :: String -> String\nconvert s = if isRC s\n then rcToA1 s\n else a1ToRc s\n where rcToA1 s = case groupBy equatingDigits s of\n [_,r,_,c] ->(toB26 $ read c) ++ r\n a1ToRc s = case groupBy equatingDigits s of\n [c,r] -> ('R':(init $ tail $ show r)) ++ ('C':show (fromB26 c))\ntoB26 :: Int -> String\ntoB26 x = case pred x `div` 26 of\n 0 -> [chr $ x + 64]\n n -> toB26 n ++ (toB26 $ succ $ pred x `mod` 26)\n \nfromB26 [c] = ord c - 64\nfromB26 (c:cs) = (ord c - 64) * 26 ^ length cs + fromB26 cs\n\n\nmain = do\n n <- getLine\n input <- readNLines (read n)\n mapM (putStrLn . convert) input\n"}, {"source_code": "module Main where\n\nimport Data.Char (isAlpha, isDigit)\nimport Data.List (groupBy, elemIndex)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessInput :: Int -> String -> String\nprocessInput n = unlines . map processLine . take n . lines\n\nprocessLine :: String -> String\nprocessLine line = case groupBy (\\a b -> isSep a b) line of\n [_, r, _, c] -> convert (read c) ++ r\n [c, r] -> \"R\" ++ r ++ \"C\" ++ (show $ unconvert c)\n where isSep a b = not $ (isAlpha a) && (isDigit b) || (isDigit a) && (isAlpha b)\n\nconvert :: Int -> String\nconvert n = if n <= 26\n then [['A'..'Z'] !! (n - 1)]\n else case quotRem n 26 of\n (q, r) -> if r /= 0\n then (convert q) ++ (convert r)\n else (convert (q - 1)) ++ \"Z\"\n\nunconvert = foldl go 0\n where go prev c = case elemIndex c ['A'..'Z'] of Just n -> prev * 26 + n + 1\n\nmain = do\n n <- getInt\n interact $ processInput n\n"}], "negative_code": [{"source_code": "\nimport Control.Monad\nimport Data.Char\nimport Text.Printf\n\ntoAlphabetic :: Int -> String\ntoAlphabetic 0 = \"\"\ntoAlphabetic n = \n let quotient = n `div` 26\n remainder = n `mod` 26\n current = chr $ (ord 'A') + remainder - 1\n recur = toAlphabetic quotient\n in recur ++ [current]\n\ntoFirstForm :: String -> String -> String\ntoFirstForm r c' = \n let c = toAlphabetic $ read c'\n in c ++ r\n\ntoDigit :: String -> Int \ntoDigit = foldl (\\accum current -> accum * 26 + (ord current - ord 'A' + 1)) 0\n\ntoSecondForm :: String -> String -> String\ntoSecondForm r c = \"R\" ++ c ++ \"C\" ++ (show $ toDigit r)\n\ntransform :: [String] -> String\ntransform [_, r, _, c] = toFirstForm r c\ntransform [r, c] = toSecondForm r c\n\nsplitByAlphaNumber :: [String] -> Char -> [String]\nsplitByAlphaNumber [] current = [[current]]\nsplitByAlphaNumber parsed current = \n let lastElement = last parsed\n lastLetter = last lastElement\n in if isDigit lastLetter == isDigit current\n then (init parsed) ++ [lastElement ++ [current]]\n else parsed ++ [[current]]\n\nparseInput :: String -> [String]\nparseInput = foldl splitByAlphaNumber []\n\nsolve :: String -> String\nsolve = transform . parseInput\n\nreadInput _ = do\n input <- getLine\n return input\n\nmain = do\n input <- getLine\n let n = read input :: Int \n inputs <- forM [1..n] readInput\n forM inputs $ (printf \"%s\\n\") . solve\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (foldl', unfoldr)\nimport Data.Tuple (swap)\nimport Data.Char (ord, chr, isAsciiUpper, isDigit)\nimport Control.Monad (replicateM)\n\n\ntoCartesian :: String -> String\ntoCartesian xs = 'R':row ++ 'C':show col\n where (q,row) = span isAsciiUpper xs\n col = foldl' (\\r c -> 26 * r + ord c - ord 'A' + 1) 0 q\n\ntoExcel :: String -> String\ntoExcel (_:xs) = col ++ row\n where (row,_:ccol) = span isDigit xs\n col = reverse . map toChar . go $ read ccol\n go 0 = []\n go n = let (q,r) = divMod n 26 in r:go q\n toChar 0 = 'Z'\n toChar n = chr $ ord 'A' + n - 1\n\nmain :: IO ()\nmain = putStr . unlines . map solve =<< flip replicateM getLine =<< readLn\n where solve xs\n | all isDigit $ dropWhile isAsciiUpper xs = toCartesian xs\n | otherwise = toExcel xs"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (foldl', unfoldr)\nimport Data.Tuple (swap)\nimport Data.Char (ord, chr, isAsciiUpper, isDigit)\nimport Control.Monad (replicateM)\n\n\ntoCartesian :: String -> String\ntoCartesian xs = 'R':row ++ 'C':show col\n where (q,row) = span isAsciiUpper xs\n col = foldl' (\\r c -> 26 * r + ord c - ord 'A' + 1) 0 q\n\ntoExcel :: String -> String\ntoExcel (_:xs) = col ++ row\n where (row,_:ccol) = span isDigit xs\n col = reverse [chr $ ord 'A' + i - 1 | i <- unfoldr go $ read ccol]\n go 0 = Nothing\n go n = Just . swap $ divMod n 26\n\nmain :: IO ()\nmain = putStr . unlines . map solve =<< flip replicateM getLine =<< readLn\n where solve xs\n | all isDigit $ dropWhile isAsciiUpper xs = toCartesian xs\n | otherwise = toExcel xs"}, {"source_code": "import Data.Char\n\nmain = do \n\tn<-getLine\n\treading (read n) []\n\t\nreading 0 buf = do\n\tmapM putStrLn $ lines buf\nreading a buf = do \n\ts<-getLine\n\treading (a-1) $ buf++pars s ++\"\\n\"\n\npars s \n | s==\"\" = \"\"\n | head s == 'R' && length s>=2 && isDigit (s!!1) && elem 'C' s = (numberToLetters (read (tail cPart)))\n ++ rPart \n | otherwise = \"R\"++sPart++ \"C\" ++ ( show (lettersToNumber fPart))\n where rPart = (takeWhile isDigit (tail s))\n cPart = dropWhile isDigit (tail s) \n fPart = takeWhile (not.isDigit) s\n sPart = dropWhile (not.isDigit) s\n\nlettersToNumber::String->Integer\nlettersToNumber []= 0\nlettersToNumber s = toInteger (ord (head s)-ord 'A'+1) * 26^(length s-1)+ (lettersToNumber $ tail s)\n\nnumberToLetters::Integer->String\nnumberToLetters 0 = \"\"\nnumberToLetters n \n | mod n 26==0 = reverse$\"Z\" ++ (numberToLetters (div n 26-1))\n | otherwise = reverse$ [chr (fromIntegral (mod n 26 + fromIntegral( ord 'A')-1))] \n ++ reverse (numberToLetters $ div n 26)"}, {"source_code": "import Data.Char\n\nmain = do \n n<-getLine\n reading (read n) []\n \nreading 0 buf = do\n mapM putStrLn $ lines buf\nreading a buf = do \n s<-getLine\n reading (a-1) $ buf++pars s ++\"\\n\"\n\npars s \n | s==\"\" = \"\"\n | head s == 'R' && length s>=2 && isDigit (s!!1) && elem 'C' s = (numberToLetters (read (tail cPart)))\n ++ rPart \n | otherwise = \"R\"++sPart++ \"C\" ++ ( show (lettersToNumber fPart))\n where rPart = (takeWhile isDigit (tail s))\n cPart = dropWhile isDigit (tail s) \n fPart = takeWhile (not.isDigit) s\n sPart = dropWhile (not.isDigit) s\n\nlettersToNumber::String->Integer\nlettersToNumber []= 0\nlettersToNumber s = toInteger (ord (head s)-ord 'A'+1) * 26^(length s-1)+ (lettersToNumber $ tail s)\n\nnumberToLetters::Integer->String\nnumberToLetters 0 = \"\"\nnumberToLetters n \n | mod n 26==0 = reverse$\"Z\" ++ (numberToLetters (div n 26-1))\n | otherwise = reverse$ [chr (fromIntegral (mod n 26 + fromIntegral( ord 'A')-1))] ++ (numberToLetters $ div n 26)\n"}, {"source_code": "import Data.Char\n\nmain = interact $pars\n\npars s \n | and (map isDigit s) = []\n | head s == 'R' && isDigit (s!!1) = (numberToLetters (read (tail cPart)))\n ++ rPart \n | otherwise = \"R\"++sPart++ \"C\" ++ ( show (lettersToNumber fPart))\n where rPart = (takeWhile isDigit (tail s))\n cPart = dropWhile isDigit (tail s) \n fPart = takeWhile (not.isDigit) s\n sPart = dropWhile (not.isDigit) s\n\nlettersToNumber::String->Int\nlettersToNumber []= 0\nlettersToNumber s = (ord (head s)-ord 'A'+1) * 26^(length s-1)+ (lettersToNumber $ tail s)\n\nnumberToLetters::Int->String\nnumberToLetters 0 = \"\"\nnumberToLetters n = reverse$ [chr (mod n 26 + ord 'A'-1)] ++ (numberToLetters $ div n 26)\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1/B\n\nimport Data.Char\n\ndata CoordinateType = A | B deriving (Eq, Show)\n\nmain = do\n\tcontents <- getLine\n\tlet\n\t\tn = read $ head $ lines contents\n\tcoordinates <- getLines n\n\tmapM_ putStrLn $ convertCoordinates coordinates\n\treturn ()\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n-- Type A if not letters are found after a number (ABXY)\n-- Type B if letters are found after a number (RXCY)\n-- Regular expressions could be used, but let's keep things simple\ncoordinateType :: String -> CoordinateType\ncoordinateType (x:xs) = coordinateType' x xs\n\twhere\n\t\tcoordinateType' :: Char -> String -> CoordinateType\n\t\tcoordinateType' _ [] = A\n\t\tcoordinateType' prev (x:xs)\n\t\t\t| isDigit prev && isLetter x = B\n\t\t\t| otherwise = coordinateType' x xs\n\nletterToNum :: Char -> Int\nletterToNum letter = ord letter - 64\n\nnumToLetter :: Int -> Char\nnumToLetter num = chr $ num + 64\n\nletterColToNum :: String -> Int\nletterColToNum [] = 0\nletterColToNum (x:xs) = 26^length(xs)*(letterToNum x) + letterColToNum xs\n\nnumToLetterCol :: Int -> String\nnumToLetterCol num = reverse $ numToLetterCol' num\n\twhere\n\t\tnumToLetterCol' :: Int -> String\n\t\tnumToLetterCol' num\n\t\t\t| num <= 26 = [numToLetter num]\n\t\t\t| otherwise = numToLetter (num `mod` 26) : numToLetterCol' (num `quot` 26)\n\ntranslateCoordinate :: String -> String\ntranslateCoordinate coord\n\t| coord_type == A =\n\t\tlet\n\t\t\tcol = takeWhile (isLetter) coord\n\t\t\trow = takeWhile (isDigit) $ dropWhile (isLetter) coord\n\t\tin\n\t\t\t\"R\" ++ row ++ \"C\" ++ (show $ letterColToNum col)\n\t| coord_type == B =\n\t\tlet\n\t\t\tcol = read $ tail $ dropWhile (isDigit) $ tail coord\n\t\t\trow = takeWhile (isDigit) $ tail coord\n\t\tin\n\t\t\tnumToLetterCol col ++ row\n\twhere\n\t\tcoord_type = coordinateType coord\n\nconvertCoordinates :: [String] -> [String]\nconvertCoordinates [] = []\nconvertCoordinates (x:xs) = translateCoordinate x : convertCoordinates xs"}, {"source_code": "-- http://codeforces.com/problemset/problem/1/B\n\nimport Data.Char\n\ndata CoordinateType = A | B deriving (Eq, Show)\n\nmain = do\n\tcontents <- getLine\n\tlet\n\t\tn = read $ head $ lines contents\n\tcoordinates <- getLines n\n\tputStrLn $ show $ convertCoordinates coordinates\n\treturn ()\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n-- Type A if not letters are found after a number (ABXY)\n-- Type B if letters are found after a number (RXCY)\n-- Regular expressions could be used, but let's keep things simple\ncoordinateType :: String -> CoordinateType\ncoordinateType (x:xs) = coordinateType' x xs\n\twhere\n\t\tcoordinateType' :: Char -> String -> CoordinateType\n\t\tcoordinateType' _ [] = A\n\t\tcoordinateType' prev (x:xs)\n\t\t\t| isDigit prev && isLetter x = B\n\t\t\t| otherwise = coordinateType' x xs\n\nletterToNum :: Char -> Int\nletterToNum letter = ord letter - 64\n\nnumToLetter :: Int -> Char\nnumToLetter num = chr $ num + 64\n\nletterColToNum :: String -> Int\nletterColToNum [] = 0\nletterColToNum (x:xs) = 26^length(xs)*(letterToNum x) + letterColToNum xs\n\nnumToLetterCol :: Int -> String\nnumToLetterCol num = reverse $ numToLetterCol' num\n\twhere\n\t\tnumToLetterCol' :: Int -> String\n\t\tnumToLetterCol' num\n\t\t\t| num < 26 = [numToLetter num]\n\t\t\t| otherwise = numToLetter (num `mod` 26) : numToLetterCol' (num `quot` 26)\n\ntranslateCoordinate :: String -> String\ntranslateCoordinate coord\n\t| coord_type == A =\n\t\tlet\n\t\t\tcol = takeWhile (isLetter) coord\n\t\t\trow = takeWhile (isDigit) $ dropWhile (isLetter) coord\n\t\tin\n\t\t\t\"R\" ++ row ++ \"C\" ++ (show $ letterColToNum col)\n\t| coord_type == B =\n\t\tlet\n\t\t\tcol = read $ tail $ dropWhile (isDigit) $ tail coord\n\t\t\trow = takeWhile (isDigit) $ tail coord\n\t\tin\n\t\t\tnumToLetterCol col ++ row\n\twhere\n\t\tcoord_type = coordinateType coord\n\nconvertCoordinates :: [String] -> [String]\nconvertCoordinates [] = []\nconvertCoordinates (x:xs) = translateCoordinate x : convertCoordinates xs"}, {"source_code": "-- http://codeforces.com/problemset/problem/1/B\n\nimport Data.Char\n\ndata CoordinateType = A | B deriving (Eq, Show)\n\nmain = do\n\tcontents <- getLine\n\tlet\n\t\tn = read $ head $ lines contents\n\tcoordinates <- getLines n\n\tmapM_ putStrLn $ convertCoordinates coordinates\n\treturn ()\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n-- Type A if not letters are found after a number (ABXY)\n-- Type B if letters are found after a number (RXCY)\n-- Regular expressions could be used, but let's keep things simple\ncoordinateType :: String -> CoordinateType\ncoordinateType (x:xs) = coordinateType' x xs\n\twhere\n\t\tcoordinateType' :: Char -> String -> CoordinateType\n\t\tcoordinateType' _ [] = A\n\t\tcoordinateType' prev (x:xs)\n\t\t\t| isDigit prev && isLetter x = B\n\t\t\t| otherwise = coordinateType' x xs\n\nletterToNum :: Char -> Int\nletterToNum letter = ord letter - 64\n\nnumToLetter :: Int -> Char\nnumToLetter num = chr $ num + 64\n\nletterColToNum :: String -> Int\nletterColToNum [] = 0\nletterColToNum (x:xs) = 26^length(xs)*(letterToNum x) + letterColToNum xs\n\nnumToLetterCol :: Int -> String\nnumToLetterCol num = reverse $ numToLetterCol' num\n\twhere\n\t\tnumToLetterCol' :: Int -> String\n\t\tnumToLetterCol' num\n\t\t\t| num < 26 = [numToLetter num]\n\t\t\t| otherwise = numToLetter (num `mod` 26) : numToLetterCol' (num `quot` 26)\n\ntranslateCoordinate :: String -> String\ntranslateCoordinate coord\n\t| coord_type == A =\n\t\tlet\n\t\t\tcol = takeWhile (isLetter) coord\n\t\t\trow = takeWhile (isDigit) $ dropWhile (isLetter) coord\n\t\tin\n\t\t\t\"R\" ++ row ++ \"C\" ++ (show $ letterColToNum col)\n\t| coord_type == B =\n\t\tlet\n\t\t\tcol = read $ tail $ dropWhile (isDigit) $ tail coord\n\t\t\trow = takeWhile (isDigit) $ tail coord\n\t\tin\n\t\t\tnumToLetterCol col ++ row\n\twhere\n\t\tcoord_type = coordinateType coord\n\nconvertCoordinates :: [String] -> [String]\nconvertCoordinates [] = []\nconvertCoordinates (x:xs) = translateCoordinate x : convertCoordinates xs"}, {"source_code": "\nimport Data.Char\nimport Debug.Trace\nimport Control.Monad\n\ndata IdType = Excel | RC\n\ngetInput :: IO [String]\ngetInput = do\n\tlinesnum <- (liftM read) getLine\n\tsequence $ replicate linesnum getLine\n\nidentifyType :: String -> IdType\nidentifyType s = if head s /= 'R'\n\tthen Excel\n\telse if not . isDigit $ s !! 1\n\t\tthen Excel\n\t\telse if any (not . isDigit) $ drop 2 s then RC else Excel\n\nexcelToRC :: String -> String\nexcelToRC s = \"R\" ++ row ++ \"C\" ++ convertedColumn\n\twhere\n\t\t(column, row) = parseExcel s\n\t\tconvertedColumn = (show . id) $ foldl decodeAlpha 0 column\n\t\tparseExcel = break isDigit\n\t\tdecodeAlpha t c = (t * 26) + (ord c - ord 'A' + 1)\n\nrCToExcel :: String -> String\nrCToExcel s = convertedColumn ++ row\n\twhere\n\t\t(row, column) = parseRc s\n\t\tparseRc s = let (a,b) = break (== 'C') (tail s) in (a, tail b)\n\t\tconvertedColumn = decodeNumber (read column) \"\"\n\t\tdecodeNumber 0 s = s\n\t\tdecodeNumber x s = if x < 26\n\t\t\tthen decodeDigit x : s\n\t\t\telse decodeNumber m newS\n\t\t\t\twhere\n\t\t\t\t\t(d, m) = divMod x 26\n\t\t\t\t\tnewS = decodeDigit m : s\n\t\tdecodeDigit x = chr (ord 'A' + x - 1)\n\nconvert :: String -> String\nconvert s = case identifyType s of\n\tExcel -> excelToRC s\n\tRC -> rCToExcel s\n\nmain = do\n\tcoords <- getInput\n\tmapM_ (putStrLn . convert) coords\n\n"}, {"source_code": "\nimport Data.Char\nimport Debug.Trace\nimport Control.Monad\n\ndata IdType = Excel | RC\n\ngetInput :: IO [String]\ngetInput = do\n\tlinesnum <- (liftM read) getLine\n\tsequence $ replicate linesnum getLine\n\nidentifyType :: String -> IdType\nidentifyType s = if head s /= 'R'\n\tthen Excel\n\telse if not . isDigit $ s !! 1\n\t\tthen Excel\n\t\telse if any (not . isDigit) $ drop 2 s then RC else Excel\n\nexcelToRC :: String -> String\nexcelToRC s = \"R\" ++ row ++ \"C\" ++ convertedColumn\n\twhere\n\t\t(column, row) = parseExcel s\n\t\tconvertedColumn = (show . id) $ foldl decodeAlpha 0 column\n\t\tparseExcel = break isDigit\n\t\tdecodeAlpha t c = (t * 26) + (ord c - ord 'A' + 1)\n\nrCToExcel :: String -> String\nrCToExcel s = convertedColumn ++ row\n\twhere\n\t\t(row, column) = parseRc s\n\t\tparseRc s = let (a,b) = break (== 'C') (tail s) in (a, tail b)\n\t\tconvertedColumn = decodeNumber (read column) \"\"\n\t\tdecodeNumber 0 s = s\n\t\tdecodeNumber x s = if x < 26\n\t\t\tthen decodeDigit x : s\n\t\t\telse decodeNumber d newS\n\t\t\t\twhere\n\t\t\t\t\t(d, m) = divMod x 26\n\t\t\t\t\tnewS = decodeDigit m : s\n\t\tdecodeDigit x = chr (ord 'A' + x - 1)\n\nconvert :: String -> String\nconvert s = case identifyType s of\n\tExcel -> excelToRC s\n\tRC -> rCToExcel s\n\nmain = do\n\tcoords <- getInput\n\tmapM_ (putStrLn . convert) coords\n\n"}, {"source_code": "\nimport Data.Char\nimport Debug.Trace\nimport Control.Monad\n\ndata IdType = Excel | RC\n\ngetInput :: IO [String]\ngetInput = do\n\tlinesnum <- (liftM read) getLine\n\tsequence $ replicate linesnum getLine\n\nidentifyType :: String -> IdType\nidentifyType s = if head s /= 'R'\n\tthen Excel\n\telse if not . isDigit $ s !! 1\n\t\tthen Excel\n\t\telse if any (not . isDigit) $ drop 2 s then RC else Excel\n\nexcelToRC :: String -> String\nexcelToRC s = \"R\" ++ row ++ \"C\" ++ convertedColumn\n\twhere\n\t\t(column, row) = parseExcel s\n\t\tconvertedColumn = (show . id) $ foldl decodeAlpha 0 column\n\t\tparseExcel = break isDigit\n\t\tdecodeAlpha t c = (t * 26) + (ord c - ord 'A' + 1)\n\nrCToExcel :: String -> String\nrCToExcel s = convertedColumn ++ row\n\twhere\n\t\t(row, column) = parseRc s\n\t\tparseRc s = let (a,b) = break (== 'C') (tail s) in (a, tail b)\n\t\tconvertedColumn = decodeNumber (read column) \"\"\n\t\tdecodeNumber 0 s = s\n\t\tdecodeNumber x s = if x < 26\n\t\t\tthen s ++ [decodeDigit x]\n\t\t\telse decodeNumber m newS\n\t\t\t\twhere\n\t\t\t\t\t(d, m) = divMod x 26\n\t\t\t\t\tnewS = s ++ [decodeDigit d]\n\t\tdecodeDigit x = chr (ord 'A' + x - 1)\n\nconvert :: String -> String\nconvert s = case identifyType s of\n\tExcel -> excelToRC s\n\tRC -> rCToExcel s\n\nmain = do\n\tcoords <- getInput\n\tmapM_ (putStrLn . convert) coords\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.List\nimport Data.Char\n\nletters = map (\\x -> chr (ord 'A' + (x - 1) `mod` 26)) . reverse . takeWhile (>0) . iterate (\\x -> (x-1) `div` 26)\nnumbers = sum . zipWith (*) (iterate (*26) 1) . reverse . map (\\x -> ord x - ord 'A' + 1)\n\nconvert :: [String] -> String\nconvert (\"R\":r:\"C\":c:[]) = letters (read r) ++ c\nconvert (r:c:[]) = \"R\" ++ show (numbers r) ++ \"C\" ++ c\n\nmain = do\n (n :: Int,cells) <- getContents >>= return . (\\(n:cells) -> (read n,map (map toUpper) cells)) . lines\n mapM (putStrLn . convert . groupBy (\\l r -> isDigit l == isDigit r)) (take n cells)\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = readLn >>= \\n-> (solve=<C.getLine) )\nsolve xs = forM_ xs $ \\i-> C.putStrLn $ slv1 i\nslv1 xs = slv2 $ second (C.break (isLetter)) $ C.break (isDigit) xs\nslv2 (a,(b,c))= if c/=C.empty then C.append (slv5 $ rIn $ C.tail c) b else C.append (C.cons 'R' b) (C.cons 'C' $ slv3 a)\nse_t2 = Set.fromList (['A'..'Z'])\nslv3::C.ByteString->C.ByteString\nslv3 xs =C.pack $ show $ fst $ C.foldr (\\a (b1,b2)->((Set.findIndex a se_t2+1)* 26^b2 +b1, b2+1)) (0,0) xs\nslv4 0 = []\nslv4 x=let md = x `mod` 26; dv= x `div` 26 in slv4 (if md==0 then dv-1 else dv) ++[if md==0 then 26 else md]\nslv5 x =C.pack $ map (flip Set.elemAt se_t2.(+(-1))) $ slv4 x"}, {"source_code": "import Data.Char\nimport Text.ParserCombinators.ReadP\n\nfromChar :: Char -> Int\nfromChar c = (ord c - ord 'A' + 1)\n\ntoChar :: Int -> Char\ntoChar n\n | n < 0 || n > 26 = error \"toChar: argument not in [1..26]\"\n | otherwise = chr (ord 'A' + n - 1)\n\nfromABC :: String -> Int\nfromABC \"\" = 0\nfromABC s = sum (zipWith (*) (map fromChar s) (_26 (length s)))\n where\n _26 0 = []\n _26 n = (26^(n-1)):(_26 (n-1))\n\ntoABC :: Int -> String\ntoABC 0 = \"\"\ntoABC n\n | n <= 26 = [toChar n]\n | a == 0 = (toABC (div n 26 - 1)) ++ \"Z\"\n | otherwise = (toABC (div n 26)) ++ [toChar a]\n where\n a = mod n 26\n\nparserRC :: ReadP (Int, Int)\nparserRC = do\n string \"R\"\n col <- many1 $ satisfy isDigit\n string \"C\"\n row <- many1 $ satisfy isDigit\n return (read col, read row)\n\nparserA1 :: ReadP (Int, Int)\nparserA1 = do\n col <- many1 $ satisfy isAlpha\n row <- many1 $ satisfy isDigit\n return (fromABC col, read row)\n\ngetCell :: ReadP (Int, Int) -> String -> Maybe (Int, Int)\ngetCell parser s\n | 0 < length xs = Just (fst (head xs))\n | otherwise = Nothing\n where\n xs = filter (\\x -> snd x == \"\") (readP_to_S parser s)\n\ncheckString :: ReadP (Int, Int) -> String -> Bool\ncheckString parser s = getCell parser s /= Nothing\n\ncheckRC :: String -> Bool\ncheckRC = checkString parserRC\n\ncheckA1 :: String -> Bool\ncheckA1 = checkString parserA1\n\ntoRC :: (Int, Int) -> String\ntoRC (n, m) = concat [\"R\", show n, \"C\", show m]\n\ntoA1 :: (Int, Int) -> String\ntoA1 (n, m) = concat [toABC n, show m]\n\nsolve :: String -> String\nsolve s\n | checkRC s = toA1 (r, c)\n | checkA1 s = toRC (n, m)\n | otherwise = \"NO\"\n where\n (Just (r, c)) = getCell parserRC s\n (Just (n, m)) = getCell parserA1 s\n\nmain :: IO ()\nmain = do\n n <- readLn\n lines <- sequence (replicate n getLine)\n sequence_ (map (putStrLn . solve) lines)"}, {"source_code": "import Data.Char\nimport Text.ParserCombinators.ReadP\n\nfromChar :: Char -> Int\nfromChar c = (ord c - ord 'A' + 1)\n\ntoChar :: Int -> Char\ntoChar n\n | n < 0 || n > 26 = error \"toChar: argument not in [1..26]\"\n | otherwise = chr (ord 'A' + n - 1)\n\nfromABC :: String -> Int\nfromABC \"\" = 0\nfromABC s = sum (zipWith (*) (map fromChar s) (_26 (length s)))\n where\n _26 0 = []\n _26 n = (26^(n-1)):(_26 (n-1))\n\ntoABC :: Int -> String\ntoABC 0 = \"\"\ntoABC n\n | n <= 26 = [toChar n]\n | a == 0 = (toABC (div n 26 - 1)) ++ \"Z\"\n | otherwise = (toABC (div n 26)) ++ [toChar a]\n where\n a = mod n 26\n\nparserRC :: ReadP (Int, Int)\nparserRC = do\n string \"R\"\n row <- many1 $ satisfy isDigit\n string \"C\"\n col <- many1 $ satisfy isDigit\n return (read col, read row)\n\nparserA1 :: ReadP (Int, Int)\nparserA1 = do\n col <- many1 $ satisfy isAlpha\n row <- many1 $ satisfy isDigit\n return (fromABC col, read row)\n\ngetCell :: ReadP (Int, Int) -> String -> Maybe (Int, Int)\ngetCell parser s\n | 0 < length xs = Just (fst (head xs))\n | otherwise = Nothing\n where\n xs = filter (\\x -> snd x == \"\") (readP_to_S parser s)\n\ncheckString :: ReadP (Int, Int) -> String -> Bool\ncheckString parser s = getCell parser s /= Nothing\n\ncheckRC :: String -> Bool\ncheckRC = checkString parserRC\n\ncheckA1 :: String -> Bool\ncheckA1 = checkString parserA1\n\ntoRC :: (Int, Int) -> String\ntoRC (n, m) = concat [\"R\", show n, \"C\", show m]\n\ntoA1 :: (Int, Int) -> String\ntoA1 (n, m) = concat [toABC n, show m]\n\nsolve :: String -> String\nsolve s\n | checkRC s = toA1 (r, c)\n | checkA1 s = toRC (n, m)\n | otherwise = \"NO\"\n where\n (Just (r, c)) = getCell parserRC s\n (Just (n, m)) = getCell parserA1 s\n\nmain :: IO ()\nmain = do\n n <- readLn\n lines <- sequence (replicate n getLine)\n sequence_ (map (putStrLn . solve) lines)"}, {"source_code": "import Control.Monad\n\nreadAlphas (x : xs) | 'A' <= x && x <= 'Z' =\n x : readAlphas xs\nreadAlphas _ = \"\"\n\nreadDigits (x : xs) | '0' <= x && x <= '9' =\n x : readDigits xs\nreadDigits _ = \"\"\n\ncrToXY c r = 'R' : show r ++ 'C' : (show . convert . reverse) c\n where\n convert [] = 0\n convert (x : xs) = let v = fromEnum x - 64 in\n v + convert xs * 26\n\nxyToCR x y = convert y ++ show x\n where\n convert 0 = \"\"\n convert n = convert (div n 26) ++ [char]\n where\n char | n `mod` 26 == 0 = 'Z'\n | otherwise = toEnum (n `mod` 26 + 64) :: Char\n\nmain = do\n line <- getLine\n let n = read line :: Int\n forM_ [1..n] $ \\i -> do\n line <- getLine\n let a = readAlphas line\n let line' = drop (length a) line\n let b = readDigits line'\n let line'' = drop (length b) line'\n case line'' of\n \"\" -> do let c = a\n let r = read b :: Int\n putStrLn $ crToXY c r\n _ -> do let x = read b :: Int\n let y = read (drop 1 line'') :: Int\n putStrLn $ xyToCR x y\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ncalcAlpha :: String -> Int -> Int\ncalcAlpha (x:[]) num = num * ((ord x) - (ord 'A') + 1) \ncalcAlpha (x:xs) num = num * ((ord x) - (ord 'A') + 1) + (calcAlpha xs (num*26))\n\nalphaToRC alpha num = \"R\" ++ num ++ \"C\" ++ show (calcAlpha (reverse alpha) 1) \n\n\ncalcRC n \n |n == 0 = []\n |otherwise = calcRC (n `div` 26) ++ [chr ((ord 'A') - 1 + (n `mod` 26))]\n\nrcToAlpha :: String -> String -> String\nrcToAlpha r c = calcRC (read c :: Int) ++ r\n\nparseInp :: String -> String -> [String]\nparseInp [] y = [y]\nparseInp (x:xs) y\n |y == [] = parseInp xs [x]\n |isDigit (x) == isDigit (head y) = parseInp xs (y++[x])\n |otherwise = [y] ++ parseInp xs [x]\n\n\nsolveTC :: Integer -> IO ()\nsolveTC n = do\n if (n == 0) \n then return ()\n else do\n line <- getLine\n let inp = parseInp line \"\"\n if length inp == 2\n then putStrLn $ alphaToRC (inp !! 0) (inp !! 1)\n else putStrLn $ rcToAlpha (inp !! 1) (inp !! 3)\n\n\n solveTC (n-1)\n\n\nmain = do\n line <- getLine\n let tc = (read line :: Integer)\n solveTC tc"}, {"source_code": "printAns :: Integer -> Integer -> IO()\nprintAns tc s = putStrLn $ (\"Case #\" ++ (show tc) ++ \": \" ++ (show s))\n\nmakeData :: [Char] -> [Integer] -> [Integer]\nmakeData ('C':[]) (y:_) = [y `div` 2]\nmakeData (x:[]) (y:_) = [y]\nmakeData ('C':xs) (y:ys) = (y `div` 2) : makeData xs ys\nmakeData (x:xs) (y:ys) = y : makeData xs ys\n\nlistCnt c xs = sum $ map (\\x -> if x == c then 1 else 0) xs\n\ncntEach (c:[]) xs = [listCnt c xs]\ncntEach (c:cs) xs = listCnt c xs : cntEach cs xs\n\nsolveEach :: String -> Integer\nsolveEach line = foldr (min) 1000 (makeData \"HACKERCUP\" (cntEach \"HACKERCUP\" line))\n\nsolveTC :: Integer -> Integer -> IO ()\nsolveTC 0 _ = return ()\nsolveTC te tc= do \n line <- getLine\n printAns tc (solveEach line) \n solveTC (te-1) (tc+1)\n\nmain :: IO ()\nmain = do \n line <- getLine\n let tc = (read line :: Integer)\n solveTC tc 1\n \n"}, {"source_code": "import Data.Char (ord, chr)\n\nmain :: IO ()\nmain = do\n s <- getContents\n putStr (unlines $ map process (tail $ lines s))\n\nlettersBase = ord 'Z' - ord 'A' + 1\n\nprocess :: String -> String\nprocess s | (length parsed) == 2 = coordsToRC $ coordsFromAB parsed\n | otherwise = coordsToAB $ coordsFromRC parsed\n where parsed = chainParse [isLetter, isDigit, isLetter, isDigit] s\n\ncoordsFromAB :: [String] -> (Int, Int)\ncoordsFromAB [col, row] = (read row, lettersToInt col)\n\ncoordsFromRC :: [String] -> (Int, Int)\ncoordsFromRC [\"R\", row, \"C\", col] = (read row, read col)\n\nlettersToInt :: String -> Int\nlettersToInt s = sum $ map (\\(val, k) -> val*k) (zip (reverse $ map (\\c -> ord c - ord 'A' + 1) s) factors)\n where factors = iterate (*lettersBase) 1\n\nintToLetters :: Int -> String\nintToLetters 0 = []\nintToLetters n = ( intToLetters (n `div` lettersBase) ) ++ [chr (m + ord 'A' - 1)]\n where m = n `mod` lettersBase\n\ncoordsToRC :: (Int, Int) -> String\ncoordsToRC (row, col) = \"R\" ++ (show row) ++ \"C\" ++ (show col)\n\ncoordsToAB :: (Int, Int) -> String\ncoordsToAB (row, col) = intToLetters col ++ show row\n\nchainParse :: [( Char -> Bool )] -> String -> [String]\nchainParse [] _ = []\nchainParse _ \"\" = []\nchainParse (f:fs) s = (extractChars f s):(chainParse fs (eatChars f s))\n\neatChars :: ( Char -> Bool ) -> String -> String\neatChars _ [] = []\neatChars f (c:cs) | f c = eatChars f cs\n | otherwise = (c:cs)\n\nextractChars :: ( Char -> Bool ) -> String -> String\nextractChars _ [] = []\nextractChars f (c:cs) | f c = c:(extractChars f cs)\n | otherwise = \"\"\n\nisDigit :: Char -> Bool\nisDigit c = c>='0' && c<='9'\n\nisLetter :: Char -> Bool\nisLetter c = (c>='a' && c<='z') || (c>='A' && c<='Z')\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport Control.Applicative\n\nmain = do\n n <- readLn\n replicateM_ n (getLine >>= putStrLn . solve)\n\nsolve :: String -> String\nsolve str =\n let (a,(b,c)) = span isDigit <$> span isUpper str\n in if null c\n then encode1 (read b) (decodeCol a)\n else encode2 (read b) (read (snd (span isUpper c)))\n where\n encode1 :: Int -> Int -> String\n encode1 row col = \"R\" ++ show row ++ \"C\" ++ show col\n\n encode2 :: Int -> Int -> String\n encode2 row col = encodeCol col ++ show row\n\n decodeCol :: String -> Int\n decodeCol = foldl (\\a c -> 26*a + ord c - ord 'A' + 1) 0\n\n encodeCol :: Int -> String\n encodeCol = reverse . unfoldr (\\i -> if i == 0 then Nothing else Just (chr (i `mod` 26 + ord 'A' - 1), i `div` 26))\n\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\n\nmain = do\n n <- readLn\n replicateM_ n (getLine >>= putStrLn . solve)\n\nsolve :: String -> String\nsolve str =\n let (a,b) = span isAlpha str\n (c,d) = span isDigit b\n in if null d then encode1 (read c) (decodeCol a) else encode2 (read c) (read (tail d))\n where\n encode1 :: Int -> Int -> String\n encode1 row col = \"R\" ++ show row ++ \"C\" ++ show col\n\n encode2 :: Int -> Int -> String\n encode2 row col = encodeCol col ++ show row\n\n decodeCol :: String -> Int\n decodeCol = foldl (\\a c -> 26*a + ord c - ord 'A' + 1) 0\n\n encodeCol :: Int -> String\n encodeCol = reverse . unfoldr (\\i -> if i == 0 then Nothing else Just (chr (i `mod` 26 + ord 'A' - 1), i `div` 26))\n\n"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nparseRowColFormat :: String -> Maybe (Int, Int)\nparseRowColFormat s@(x : _) = if x == 'R' then go \"\" \"\" s else Nothing where\n go \"\" \"\" [] = Nothing\n go (r:rs) \"\" [] = Nothing\n go rows@(r:rs) \"\" (_: xs) = go rows xs []\n go rows@(r:rs) cols@(c:cs) [] = Just (read rows, read cols)\n go \"\" \"\" (_ : xs) = go (takeWhile isDigit xs) \"\" (dropWhile isDigit xs)\n\nparseStandartFormat :: String -> Maybe (String, Int)\nparseStandartFormat s = go \"\" \"\" s where\n go \"\" \"\" [] = Nothing\n go (c:cs) \"\" [] = Nothing\n go cols@(c:cs) \"\" xss@(x:xs) = if any isAlpha xss then Nothing else go cols xss []\n go cols@(c:cs) rows@(r:rs) [] = Just (cols, read rows)\n go \"\" \"\" xs = go (takeWhile isAlpha xs) \"\" (dropWhile isAlpha xs)\n\ncol2Alpha :: Int -> String\ncol2Alpha = reverse . go where\n go 0 = \"\"\n go col = chr((col - 1) `mod` 26 + ord('A')) : col2Alpha ((col - 1) `div` 26)\n\nalpha2Col :: String -> Int\nalpha2Col col = foldl (\\acc c -> acc*26 + ord(c) - ord('A') + 1) 0 col\n\nparse :: String -> String\nparse format = case parseRowColFormat format of\n Just (row, col) -> col2Alpha col ++ show row\n Nothing -> case parseStandartFormat format of\n Just (scol, srow) -> ('R' : show srow) ++ ('C' : (show $ alpha2Col scol))\n Nothing -> \"\"\n\nmain =\n read <$> getLine >>= \\n -> \n replicateM_ n (parse <$> getLine >>= putStrLn)"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.Char\nimport Data.List\nimport Numeric\nimport Data.Function\n\nisRXCY = dropWhile isAsciiUpper >>> dropWhile isDigit >>> null >>> not\ntoRXCY = readInt 26 isAsciiUpper (\\x -> ord x - ord 'A' +1) >>> head >>> \\ (c,r) -> 'R': r ++ \"C\" ++ show c\nfromRXCY = groupBy ((==) `on` generalCategory) >>> (\\ (_:r:_:c:_) -> (read c,r)) >>> uncurry (showIntAtBase 26 (\\x -> chr $ x - 1 + ord 'A'))\n\nmain = do\n n:xs <- lines `fmap` getContents\n putStr $ ($ xs) $ take (read n) >>> map (\\x -> if isRXCY x then fromRXCY x else toRXCY x) >>> unlines\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain :: IO ()\nmain = interact $ foldr ((++) . (++\"\\n\")) \"\" . map show . map (read :: String -> Cell) . tail . lines\n\ndata Cell = Ax String Integer\n | Rxcy Integer Integer\n\ninstance Show Cell where\n show (Ax a x) = a ++ show x\n show (Rxcy x y) = \"R\" ++ show x ++ \"C\" ++ show y\n\ninstance Read Cell where\n readsPrec _ s = [(cvt xxs, \"\")]\n where xxs = foldl (\\xs c -> if null xs then [[c]] else (if isAlpha (head (head xs)) == isAlpha c then (head xs++[c]):(tail xs) else [c]:xs)) [] s\n cvt [y, \"C\", x, \"R\"] = Rxcy (read x) (read y)\n cvt [x, a] = Ax a (read x)\n cvt _ = error \"Input error\"\n\nconvert :: Cell -> Cell\nconvert (Ax a x) = Rxcy x idx\n where nums = map (\\c -> fromIntegral $ ord c - ord 'A' + 1) (reverse a)\n idx = sum $ map (\\(b, y) -> b * 26 ^ y) $ zip nums [0..]\nconvert (Rxcy x y) = Ax str x\n where str = reverse $ unfoldr (\\n -> if n == 0 then Nothing else let (d, m) = divMod (n - 1) 26 in Just (['A'..'Z'] !! (fromIntegral m), d)) y\n"}, {"source_code": "module Main where\n\nimport Data.Char\n\nreadMaybe :: Read a => String -> Maybe a\nreadMaybe s = case reads s of\n [(x, \"\")] -> Just x\n _ -> Nothing\n\ntoString :: Int -> String\ntoString n = toStringAux n [] where\n\ttoStringAux n ss = let (d, m) = divMod (n - 1) 26 in\n\t\tcase d of\n\t\t0 -> chr (ord 'A' + m) : ss\n\t\t_ -> toStringAux d (chr (ord 'A' + m) : ss)\n\ntoInt :: String -> Int\ntoInt ss = toIntAux ss 0 where\n\ttoIntAux (s : []) n = n + (ord s - ord 'A' + 1)\n\ttoIntAux (s : ss) n = toIntAux ss (26 * (ord s - ord 'A' + 1) + n)\n\nreadRC :: String -> Maybe (Int, Int)\nreadRC s = \n\tlet (r, s') = break isDigit s;\n\t\t(rs, s'') = break isAlpha s';\n\t\t(c, cs) = break isDigit s'' in do\n\trn <- readMaybe rs\n\tcn <- readMaybe cs\n\treturn (rn, cn)\n\nreadCR :: String -> Maybe (String, Int)\nreadCR s =\n\tlet (cs, rs) = break isDigit s in\n\tdo\n\trn <- readMaybe rs\n\treturn (cs, rn)\t\t\n\nprocess :: String -> String\nprocess s = case readRC s of\n\tJust (r, c) -> toString c ++ show r \n\t_ -> case readCR s of\n\t\tJust (c', r') -> \"R\" ++ show r' ++ \"C\" ++ show (toInt c')\n\t\t_ -> \"\"\n\nmain :: IO ()\nmain = do\n\tinput <- getContents\n\tputStrLn (unlines (map process (tail (lines input))))\n"}, {"source_code": "module Main(main) where\n\nimport Data.List(tails,foldl')\nimport Data.Maybe(fromJust)\nimport Control.Applicative\n\nreadInt :: String -> Int\nreadInt = read\n\nalphaToInt :: Char -> Int\nalphaToInt c = fromJust . lookup c $ zip ['A'..] [1..26]\n\nstrToInt :: String -> Int\nstrToInt s = let l = length s in strToInt' s l 0\n where strToInt' [] _ r = r\n strToInt' _ 0 r = r\n strToInt' (s:ss) l r = strToInt' ss (l-1) (r+(alphaToInt s)*26^(l-1))\n\nintToAlpha :: Int -> Char\nintToAlpha i = fromJust . lookup i $ zip [1..26] ['A'..]\n\nintToStr :: Int -> String\nintToStr 0 = \"\"\nintToStr i = reverse $ (intToAlpha ((i-1) `mod` 26 + 1)) : intToStr ((i-1)`div`26)\n\nisCharNum :: Char -> Bool\nisCharNum c = any (c==) \"0123456789\"\n\nisExcel :: String -> Bool\nisExcel = not . any isChange . tails\n where isChange (x:y:_) = (isCharNum x) && (not $ isCharNum y)\n isChange [x] = False\n isChange [] = False\n\nfromExcel :: String -> (Int,Int)\nfromExcel = f . break isCharNum\n where f (c,r) = (strToInt c, readInt r)\n\ntoExcel :: (Int,Int) -> String\ntoExcel (c,r) = (intToStr c) ++ (show r)\n\nfromOther :: String -> (Int,Int)\nfromOther s = let ((_:r),(_:c)) = break (=='C') s in (readInt c, readInt r)\n\ntoOther :: (Int,Int) -> String\ntoOther (c,r) = \"R\" ++ show r ++ \"C\" ++ show c\n\ncalc :: String -> String\ncalc str =if isExcel str \n then toOther $ fromExcel str \n else toExcel $ fromOther str\n\nmain = do\n n <- readInt <$> getLine\n sequence_ $ take n $ repeat ((putStrLn . calc) =<< getLine)"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain = interact $ unlines . map convert . tail . lines\nconvert s = case parseAlternate s of\n Just a -> showTrad a\n Nothing -> showAlternate (parseTrad s)\n\nparseAlternate :: String -> Maybe (Int,Int)\nparseAlternate ('R' : s) = case reads s of\n [(r, 'C' : cs)] -> Just (r,read cs)\n _ -> Nothing\nparseAlternate _ = Nothing\nshowAlternate (r,c) = 'R' : show r ++ 'C' : show c\n\nparseTrad :: String -> (Int,Int)\nparseTrad s = (read r,decode c)\n where (c,r) = break isDigit s\nshowTrad (r,c) = encode c ++ show r\n\nencode = reverse . map (chr . (ord 'A' - 1 +)) . unfoldr f\n where f 0 = Nothing\n f n = Just (r,q) where (q,r) = n `divMod` 26\ndecode = foldl1' f . map ((subtract $ ord 'A' - 1) . ord)\n where f a b = 26*a + b\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain = interact $ unlines . map convert . tail . lines\nconvert s = case parseAlternate s of\n Just a -> showTrad a\n Nothing -> showAlternate (parseTrad s)\n\nparseAlternate :: String -> Maybe (Int,Int)\nparseAlternate ('R' : s) = case reads s of\n [(r, 'C' : cs)] -> Just (r,read cs)\n _ -> Nothing\nparseAlternate _ = Nothing\nshowAlternate (r,c) = 'R' : show r ++ 'C' : show c\n\nparseTrad :: String -> (Int,Int)\nparseTrad s = (read r,decode c)\n where (c,r) = break isDigit s\nshowTrad (r,c) = encode c ++ show r\n\nencode = reverse . map (chr . (ord 'A' +)) . unfoldr f . pred\n where f 0 = Nothing\n f n = Just (r,q) where (q,r) = n `divMod` 26\ndecode = foldl1' f . map ((subtract $ ord 'A' - 1) . ord)\n where f a b = 26*a + b\n"}, {"source_code": "import Data.Char\nimport Control.Monad\n\nreadRXCY :: String -> Maybe (Int, Int)\nreadRXCY ('R':s) = case span isNumber s of\n (x@(_:_), 'C':y@(_:_)) -> Just (read x, read y)\n _ -> Nothing\nreadRXCY _ = Nothing\n\ntoAB :: Int -> String\ntoAB n | 0 <= n && n < 26 = [chr $ 0x41 + n]\n | otherwise = toAB (n `div` 26) ++ toAB (n `mod` 26)\n\nreadAB :: String -> (Int, Int)\nreadAB s = readAB' 0 s\n where\n readAB' x (c:cs)\n | isNumber c = (read $ c:cs, x)\n | otherwise = readAB' (x * 26 + ord c - 0x40) cs\n\nmain = do\n n <- fmap read getLine\n forM_ [1..n] $ \\_ -> do\n line <- getLine\n case readRXCY line of\n Just (x, y) -> putStrLn $ toAB (y - 1) ++ show x\n Nothing -> let (x, y) = readAB line\n in putStrLn $ \"R\" ++ show x ++ \"C\" ++ show y\n"}, {"source_code": "import Data.Char\nimport Control.Monad\n\nreadRXCY :: String -> Maybe (Int, Int)\nreadRXCY ('R':s) = case span isNumber s of\n (x@(_:_), 'C':y@(_:_)) -> Just (read x, read y)\n _ -> Nothing\nreadRXCY _ = Nothing\n\ntoAB :: Int -> String\ntoAB n | n == 0 = \"\"\n | 0 < n && n <= 26 = [chr $ 0x40 + n]\n | otherwise = toAB (n `div` 26) ++ toAB (n `mod` 26)\n\nreadAB :: String -> (Int, Int)\nreadAB s = readAB' 0 s\n where\n readAB' x (c:cs)\n | isNumber c = (read $ c:cs, x)\n | otherwise = readAB' (x * 26 + ord c - 0x40) cs\n\nmain = do\n n <- fmap read getLine\n forM_ [1..n] $ \\_ -> do\n line <- getLine\n case readRXCY line of\n Just (x, y) -> putStrLn $ toAB y ++ show x\n Nothing -> let (x, y) = readAB line\n in putStrLn $ \"R\" ++ show x ++ \"C\" ++ show y\n"}, {"source_code": "import Data.Char\nimport Control.Monad\n\nreadRXCY :: String -> Maybe (Int, Int)\nreadRXCY ('R':s) = case span isNumber s of\n (x@(_:_), 'C':y@(_:_)) -> Just (read x, read y)\n _ -> Nothing\nreadRXCY _ = Nothing\n\ntoAB :: Int -> String\ntoAB n | n == 0 = \"\"\n | 0 < n && n <= 26 = [chr $ 0x40 + n]\n | otherwise = toAB (n `div` 26) \n ++ toAB (if n `mod` 26 == 0 then 26 else n `mod` 26)\n\nreadAB :: String -> (Int, Int)\nreadAB s = readAB' 0 s\n where\n readAB' x (c:cs)\n | isNumber c = (read $ c:cs, x)\n | otherwise = readAB' (x * 26 + ord c - 0x40) cs\n\nmain = do\n n <- fmap read getLine\n forM_ [1..n] $ \\_ -> do\n line <- getLine\n case readRXCY line of\n Just (x, y) -> putStrLn $ toAB y ++ show x\n Nothing -> let (x, y) = readAB line\n in putStrLn $ \"R\" ++ show x ++ \"C\" ++ show y\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ntoAlp s 0 = s\ntoAlp s x = let x1 = x-1 in\n toAlp ((chr ((mod x1 26) + 65)):s) (div x1 26)\n\ntoNum x [] = x\ntoNum x (s:ss) = toNum (26*x + (ord s - 64)) ss\n\nproc s = case groupBy (\\x y -> isDigit x == isDigit y) s of\n [_,r,_,c] -> (toAlp [] $ read r) ++ c\n [r,c] -> \"R\" ++ (show (toNum 0 $ reverse r)) ++ \"C\" ++ c\n\nmain = interact $ unlines.map proc.tail.lines\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ntoAlp s 0 = s\ntoAlp s x = let x1 = x-1 in\n toAlp ((chr ((mod x1 26) + 65)):s) (div x1 26)\n\ntoNum x [] = x\ntoNum x (s:ss) = toNum (26*x + (ord s - 64)) ss\n\nproc s = case groupBy (\\x y -> isDigit x == isDigit y) s of\n [_,r,_,c] -> (toAlp [] $ read c) ++ r\n [c,r] -> \"R\" ++ (show (toNum 0 $ reverse r)) ++ \"C\" ++ c\n\nmain = interact $ unlines.map proc.tail.lines\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine\n css <- mapM (\\i -> solve n <$> getLine) [1..n]\n putStrLn $ unlines css\n\nsolve :: Int -> String -> String\nsolve _ cs = if isRXCY cs then fromRXCY cs\n else toRXCY cs\n\nisRXCY :: String -> Bool\nisRXCY = not.all isDigit.dropWhile isAlpha \n\ntoRXCY :: String -> String\ntoRXCY cs' = \"R\" ++ ns ++ \"C\" ++ rs\n where (cs,ns) = span isAlpha cs'\n rs = show $ sum $ zipWith (*) (map (26^) [0..]) $ reverse $ map (\\c->(ord c)-64) cs\n\nfromRXCY :: String -> String\nfromRXCY (c:cs) = ys' ++ xs\n where (xs,(y':ys)) = span isDigit cs\n n = sum $ zipWith (*) (map (10^) [0..]) $ reverse $ map (read.return) ys\n ys' = map (chr.(64+)) $ reverse $ to26 n\n\nto26 :: Int -> [Int]\nto26 n = if q == 0 then [r] else r:(to26 q)\n where (q,r) = divMod n 26\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.Char\n\ncountSeg :: String -> Integer\ncountSeg [] = 0\ncountSeg (a:[]) = 1\ncountSeg (a:b:c)\n |isAlpha a==isAlpha b = countSeg(b:c)\n |otherwise = 1+countSeg(b:c)\n\nalphaToInt :: String -> Int\nalphaToInt (a:[]) = ord a - 64\nalphaToInt (a:b) = ((ord a)-64)*26+alphaToInt b\n\nintToAlpha :: Int -> String\nintToAlpha n\n | n<26 = chr (65+n) : []\n | otherwise = (intToAlpha (div n 26 - 1)) ++ ((chr (65+(mod n 26))):[]) \n\nsplitAll :: String -> [String]\nsplitAll [] = []\nsplitAll s = do\n let (p:q) = s\n if isAlpha p then\n let (a,b) = splitAt (length $takeWhile isAlpha s) s in\n a:splitAll b\n else\n let (a,b) = splitAt (length $takeWhile (not.isAlpha) s) s in\n a:splitAll b\n\nsolve :: Integer -> IO ()\nsolve n = do\n if (n==0) then return ()\n else do\n line <- getLine\n if countSeg line == 2 then \n let (a:b:_)=splitAll line in\n putStr $\"R\"++b++\"C\"++(show $alphaToInt a)++\"\\n\"\n else\n let (a:b:c:d:_)=splitAll line in\n putStr $intToAlpha (((read::String->Int) d)-1)++b++\"\\n\"\n solve (n-1)\n\nmain = do\n buf <- getLine\n let (n:_) = map (read::String->Integer) (buf:[])\n solve n"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nreadInt :: IO Integer\nreadInt = readLn\n\ncountSeg :: String -> Integer\ncountSeg [] = 0\ncountSeg (a:[]) = 1\ncountSeg (a:b:c)\n |isAlpha a==isAlpha b = countSeg(b:c)\n |otherwise = 1+countSeg(b:c)\n\nalphaToInt :: String -> Int\nalphaToInt (a:[]) = ord a - 64\nalphaToInt (a:b) = ((ord a)-64)*26+alphaToInt b\n\nintToAlpha :: Int -> String\nintToAlpha n\n | n<26 = chr (65+n) : []\n | otherwise = (intToAlpha (div n 26 - 1)) ++ ((chr (65+(mod n 26))):[]) \n\nsplitAll :: String -> [String]\nsplitAll [] = []\nsplitAll s = do\n let (p:q) = s\n if isAlpha p then\n let (a,b) = splitAt (length $takeWhile isAlpha s) s in\n a:splitAll b\n else\n let (a,b) = splitAt (length $takeWhile (not.isAlpha) s) s in\n a:splitAll b\n\nsolve :: Integer -> IO ()\nsolve n = do\n if (n==0) then return ()\n else do\n line <- getLine\n if countSeg line == 2 then \n let (a:b:_)=splitAll line in\n print $\"R\"++(show $alphaToInt a)++\"C\"++b\n else\n let (a:b:c:d:_)=splitAll line in\n print $intToAlpha (((read::String->Int) b)-1)++d\n solve (n-1)\n\nmain = do\n n <- readInt\n solve n"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nreadInt :: IO Integer\nreadInt = readLn\n\ncountSeg :: String -> Integer\ncountSeg [] = 0\ncountSeg (a:[]) = 1\ncountSeg (a:b:c)\n |isAlpha a==isAlpha b = countSeg(b:c)\n |otherwise = 1+countSeg(b:c)\n\nalphaToInt :: String -> Int\nalphaToInt (a:[]) = ord a - 64 \nalphaToInt (a:b) = ((ord a)-64)*26+alphaToInt b\n\nintToAlpha :: Int -> String\nintToAlpha n\n | n<26 = chr (65+n) : []\n | otherwise = (intToAlpha (div n 26 - 1)) ++ ((chr (65+(mod n 26))):[]) \n\nsplitAll :: String -> [String]\nsplitAll [] = []\nsplitAll s = do\n let (p:q) = s\n if isAlpha p then\n let (a,b) = splitAt (length $takeWhile isAlpha s) s in\n a:splitAll b\n else\n let (a,b) = splitAt (length $takeWhile (not.isAlpha) s) s in\n a:splitAll b\n\nsolve :: Integer -> IO ()\nsolve n = do\n if (n==0) then return ()\n else do\n line <- getLine\n if countSeg line == 2 then \n let (a:b:_)=splitAll line in\n print $\"R\"++(show $alphaToInt a)++\"C\"++b\n else\n let (a:b:c:d:_)=splitAll line in\n print $intToAlpha (((read::String->Int) b)-1)++d\n solve (n-1)\n\nmain = do\n n <- readInt\n solve n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.Char\n\ncountSeg :: String -> Integer\ncountSeg [] = 0\ncountSeg (a:[]) = 1\ncountSeg (a:b:c)\n |isAlpha a==isAlpha b = countSeg(b:c)\n |otherwise = 1+countSeg(b:c)\n\nalphaToInt :: String -> Int\nalphaToInt (a:[]) = ord a - 64\nalphaToInt (a:b) = ((ord a)-64)*26+alphaToInt b\n\nintToAlpha :: Int -> String\nintToAlpha n\n | n<26 = chr (65+n) : []\n | otherwise = (intToAlpha (div n 26 - 1)) ++ ((chr (65+(mod n 26))):[]) \n\nsplitAll :: String -> [String]\nsplitAll [] = []\nsplitAll s = do\n let (p:q) = s\n if isAlpha p then\n let (a,b) = splitAt (length $takeWhile isAlpha s) s in\n a:splitAll b\n else\n let (a,b) = splitAt (length $takeWhile (not.isAlpha) s) s in\n a:splitAll b\n\nsolve :: Integer -> IO ()\nsolve n = do\n if (n==0) then return ()\n else do\n line <- getLine\n if countSeg line == 2 then \n let (a:b:_)=splitAll line in\n print $\"R\"++b++\"C\"++(show $alphaToInt a)\n else\n let (a:b:c:d:_)=splitAll line in\n print $intToAlpha (((read::String->Int) d)-1)++b\n solve (n-1)\n\nmain = do\n buf <- getLine\n let (n:_) = map (read::String->Integer) (buf:[])\n solve n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.Char\n\ncountSeg :: String -> Integer\ncountSeg [] = 0\ncountSeg (a:[]) = 1\ncountSeg (a:b:c)\n |isAlpha a==isAlpha b = countSeg(b:c)\n |otherwise = 1+countSeg(b:c)\n\nalphaToInt :: String -> Int\nalphaToInt (a:[]) = ord a - 64\nalphaToInt (a:b) = ((ord a)-64)*26+alphaToInt b\n\nintToAlpha :: Int -> String\nintToAlpha n\n | n<26 = chr (65+n) : []\n | otherwise = (intToAlpha (div n 26 - 1)) ++ ((chr (65+(mod n 26))):[]) \n\nsplitAll :: String -> [String]\nsplitAll [] = []\nsplitAll s = do\n let (p:q) = s\n if isAlpha p then\n let (a,b) = splitAt (length $takeWhile isAlpha s) s in\n a:splitAll b\n else\n let (a,b) = splitAt (length $takeWhile (not.isAlpha) s) s in\n a:splitAll b\n\nsolve :: Integer -> IO ()\nsolve n = do\n if (n==0) then return ()\n else do\n line <- getLine\n if countSeg line == 2 then \n let (a:b:_)=splitAll line in\n putStr $\"R\"++b++\"C\"++(show $alphaToInt a)\n else\n let (a:b:c:d:_)=splitAll line in\n putStr $intToAlpha (((read::String->Int) d)-1)++b\n solve (n-1)\n\nmain = do\n buf <- getLine\n let (n:_) = map (read::String->Integer) (buf:[])\n solve n"}, {"source_code": "module Main where\n\nimport Data.Char\nimport Control.Monad\n\ndata Cell = Cell {\n row :: Int,\n column :: Int\n} deriving (Show)\n\nshowRC :: Cell -> String\nshowRC c = \"R\" <> show (row c) <> \"C\" <> show (column c)\n\nshowCR :: Cell -> String\nshowCR c = abbr (column c) <> show (row c)\n\nradix = 26\n\nabbr :: Int -> String\nabbr x = abbr0 x \"\"\n where\n abbr0 0 acc = acc\n abbr0 x acc = let y = ord 'A' + (x `mod` radix) - 1 in abbr0 (x `div` radix) (chr y:acc)\n\nfromAbbr :: String -> Int\nfromAbbr x = fromAbbr0 x 0\n where\n fromAbbr0 [] acc = acc\n fromAbbr0 (a:xs) acc = fromAbbr0 xs $ acc * radix + (ord a - ord 'A' + 1)\n\ndata Parsed = ParsedRC Cell\n | ParsedCR Cell\n | Unknown String\n deriving (Show)\n\nheadBy :: (a -> Bool) -> [a] -> ([a], [a])\nheadBy pred line = let match = takeWhile pred line in splitAt (length match) line\n\nsplit :: String -> [String]\nsplit line = reverse $ split1 line []\n where\n split1 [] acc = acc\n split1 line acc = let (chars, rest) = headBy (not . isDigit) line in\n split2 rest $ chars:acc\n split2 [] acc = acc\n split2 line acc = let (digits, rest) = headBy isDigit line in\n split1 rest $ digits:acc\n\nparseCell :: String -> Parsed\nparseCell line = case split line of\n [\"R\", r, \"C\", c] -> ParsedRC Cell { row = read r, column = read c }\n [c, r] -> ParsedCR Cell { row = read r, column = fromAbbr c }\n _ -> Unknown line\n\nconvert :: Parsed -> String\nconvert (Unknown x) = x\nconvert (ParsedCR c) = showRC c\nconvert (ParsedRC c) = showCR c\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine\n forM_ inputs $ print . convert . parseCell"}, {"source_code": "module Main where\n\nimport Data.Char\nimport Control.Monad\n\ndata Cell = Cell {\n row :: Int,\n column :: Int\n} deriving (Show)\n\nshowRC :: Cell -> String\nshowRC c = \"R\" <> show (row c) <> \"C\" <> show (column c)\n\nshowCR :: Cell -> String\nshowCR c = abbr (column c) <> show (row c)\n\nradix = 26\n\nabbr :: Int -> String\nabbr x = abbr0 (x - 1) \"\"\n where\n abbr0 0 \"\" = \"A\"\n abbr0 0 acc = acc\n abbr0 x acc = let y = ord 'A' + (x `mod` radix) in abbr0 (x `div` radix) (chr y:acc)\n\nfromAbbr :: String -> Int\nfromAbbr x = 1 + fromAbbr0 x 0\n where\n fromAbbr0 [] acc = acc\n fromAbbr0 (a:xs) acc = fromAbbr0 xs $ acc * radix + (ord a - ord 'A')\n\ndata Parsed = ParsedRC Cell\n | ParsedCR Cell\n | Unknown String\n deriving (Show)\n\nsplit :: String -> [String]\nsplit line = reverse $ split1 line []\n where\n split1 [] acc = acc\n split1 line acc = let (chars, rest) = break isDigit line in\n split2 rest $ chars:acc\n split2 [] acc = acc\n split2 line acc = let (digits, rest) = span isDigit line in\n split1 rest $ digits:acc\n\nparseCell :: String -> Parsed\nparseCell line = case split line of\n [\"R\", r, \"C\", c] -> ParsedRC Cell { row = read r, column = read c }\n [c, r] -> ParsedCR Cell { row = read r, column = fromAbbr c }\n _ -> Unknown line\n\nconvert :: Parsed -> String\nconvert (Unknown x) = x\nconvert (ParsedCR c) = showRC c\nconvert (ParsedRC c) = showCR c\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine\n forM_ inputs $ putStrLn . convert . parseCell"}, {"source_code": "module Main where\n\nimport Data.Char\nimport Control.Monad\n\ndata Cell = Cell {\n row :: Int,\n column :: Int\n} deriving (Show)\n\nshowRC :: Cell -> String\nshowRC c = \"R\" <> show (row c) <> \"C\" <> show (column c)\n\nshowCR :: Cell -> String\nshowCR c = abbr (column c) <> show (row c)\n\nradix = 26\n\nabbr :: Int -> String\nabbr x = abbr0 x \"\"\n where\n abbr0 0 acc = acc\n abbr0 x acc = let y = ord 'A' + (x + 25) `mod` radix in abbr0 (x `div` radix) (chr y:acc)\n\nfromAbbr :: String -> Int\nfromAbbr x = fromAbbr0 x 0\n where\n fromAbbr0 [] acc = acc\n fromAbbr0 (a:xs) acc = fromAbbr0 xs $ acc * radix + (ord a - ord 'A' + 1)\n\ndata Parsed = ParsedRC Cell\n | ParsedCR Cell\n | Unknown String\n deriving (Show)\n\nheadBy :: (a -> Bool) -> [a] -> ([a], [a])\nheadBy pred line = let match = takeWhile pred line in splitAt (length match) line\n\nsplit :: String -> [String]\nsplit line = reverse $ split1 line []\n where\n split1 [] acc = acc\n split1 line acc = let (chars, rest) = headBy (not . isDigit) line in\n split2 rest $ chars:acc\n split2 [] acc = acc\n split2 line acc = let (digits, rest) = headBy isDigit line in\n split1 rest $ digits:acc\n\nparseCell :: String -> Parsed\nparseCell line = case split line of\n [\"R\", r, \"C\", c] -> ParsedRC Cell { row = read r, column = read c }\n [c, r] -> ParsedCR Cell { row = read r, column = fromAbbr c }\n _ -> Unknown line\n\nconvert :: Parsed -> String\nconvert (Unknown x) = x\nconvert (ParsedCR c) = showRC c\nconvert (ParsedRC c) = showCR c\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine\n forM_ inputs $ putStrLn . convert . parseCell"}, {"source_code": "module Main where\n\nimport Data.Char\nimport Control.Monad\n\ndata Cell = Cell {\n row :: Int,\n column :: Int\n} deriving (Show)\n\nshowRC :: Cell -> String\nshowRC c = \"R\" <> show (row c) <> \"C\" <> show (column c)\n\nshowCR :: Cell -> String\nshowCR c = abbr (column c) <> show (row c)\n\nradix = 26\n\nabbr :: Int -> String\nabbr x = abbr0 x \"\"\n where\n abbr0 0 acc = acc\n abbr0 x acc = let y = ord 'A' + (x `mod` radix) - 1 in abbr0 (x `div` radix) (chr y:acc)\n\nfromAbbr :: String -> Int\nfromAbbr x = fromAbbr0 x 0\n where\n fromAbbr0 [] acc = acc\n fromAbbr0 (a:xs) acc = fromAbbr0 xs $ acc * radix + (ord a - ord 'A' + 1)\n\ndata Parsed = ParsedRC Cell\n | ParsedCR Cell\n | Unknown String\n deriving (Show)\n\nheadBy :: (a -> Bool) -> [a] -> ([a], [a])\nheadBy pred line = let match = takeWhile pred line in splitAt (length match) line\n\nsplit :: String -> [String]\nsplit line = reverse $ split1 line []\n where\n split1 [] acc = acc\n split1 line acc = let (chars, rest) = headBy (not . isDigit) line in\n split2 rest $ chars:acc\n split2 [] acc = acc\n split2 line acc = let (digits, rest) = headBy isDigit line in\n split1 rest $ digits:acc\n\nparseCell :: String -> Parsed\nparseCell line = case split line of\n [\"R\", r, \"C\", c] -> ParsedRC Cell { row = read r, column = read c }\n [c, r] -> ParsedCR Cell { row = read r, column = fromAbbr c }\n _ -> Unknown line\n\nconvert :: Parsed -> String\nconvert (Unknown x) = x\nconvert (ParsedCR c) = showRC c\nconvert (ParsedRC c) = showCR c\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine\n forM_ inputs $ putStrLn . convert . parseCell"}, {"source_code": "import Data.Char\n\nisAbc123 :: String -> Bool\nisAbc123 (ch:rest)\n | isAlpha ch = isAbc123 rest\n | otherwise = and $ map isDigit rest\n \nan2rc :: String -> String\nan2rc an = \"R\" ++ rowStr ++ \"C\" ++ (show $ excel2Num 0 colExcel)\n where\n splitAbc123 cur whole@(ch:rest)\n | isDigit ch = (cur, whole)\n | otherwise = splitAbc123 (cur++[ch]) rest\n (colExcel, rowStr) = splitAbc123 \"\" an\n excel2Num acc \"\" = acc\n excel2Num acc (ch:rest) = excel2Num (acc*26+ord(ch)-ord('A')+1) rest\n\nrc2an :: String -> String\nrc2an rc = (excelNota col) ++ rowStr\n where\n stripNums cur (ch:rest)\n | ch == 'R' = stripNums cur rest\n | ch == 'C' = (cur, rest)\n | otherwise = stripNums (cur++[ch]) rest\n (rowStr, colStr) = stripNums \"\" rc\n col = read colStr :: Int\n excelNota 0 = \"\"\n excelNota n = (excelNota $ n `div` 26) ++ [chr $ (n-1) `mod` 26 + ord('A')]\n\nconvert :: String -> String\nconvert s\n | isAbc123 s = an2rc s\n | otherwise = rc2an s\n\nmain :: IO ()\nmain = do\n t <- (read :: String -> Int) <$> getLine\n run t\n where\n run 0 = return ()\n run n = do\n coord <- getLine\n putStrLn $ convert coord\n run (n-1)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.Char\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\ninRange :: Ord a => (a,a) -> a -> Bool\ninRange (n,m) x = n<=x&&x<=m\n\nisExcel :: String -> Bool\nisExcel = null.(dropWhile isDigit).(dropWhile isAlpha)\n\nexceltoRC :: String -> String\nexceltoRC str = let (c',r) = span (inRange ('A','Z')) str in\n let c = foldl (\\s -> \\c -> (ord c)-(ord 'A')+1+s*26) 0 c' in\n ('R':r)++('C':(show c))\n\nrctoExcel :: String -> String\nrctoExcel (_:str) = let (r,(_:c')) = span (inRange ('0','9')) str in\n let c = unfoldr (\\x -> if x==0 then Nothing else Just (chr ((mod x 26)+(ord 'A')-1),div x 26)) (read c'::Int) in\n (reverse c)++r\n\nsolve [] = []\nsolve (x:xs) = (if isExcel x then exceltoRC x else rctoExcel x):solve xs\n\nmain = do n <- scan :: IO Int\n l <- scans n ::IO [String]\n putAnsLns (solve l)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.Char\nimport Data.List\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nscanlist :: (Scan a) => IO [a]\nscanlist = do l <- getLine\n return [scan' x|x<-words l]\n\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists 0 = return []\nscanlists n = do x <- scanlist :: (Scan a) => IO [a]\n xs <- scanlists (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\ninRange :: Ord a => (a,a) -> a -> Bool\ninRange (n,m) x = n<=x&&x<=m\n\nisExcel :: String -> Bool\nisExcel = null.(dropWhile isDigit).(dropWhile isAlpha)\n\nexceltoRC :: String -> String\nexceltoRC str = let (c',r) = span (inRange ('A','Z')) str in\n let c = foldl (\\s -> \\c -> (ord c)-(ord 'A')+1+s*26) 0 c' in\n ('R':r)++('C':(show c))\n\nrctoExcel :: String -> String\nrctoExcel (_:str) = let (r,(_:c')) = span (inRange ('0','9')) str in\n let c = unfoldr (\\x -> if x==0 then Nothing else Just (chr ((mod (x+25) 26)+(ord 'A')),div x 26)) (read c'::Int) in\n (reverse c)++r\n\nsolve [] = []\nsolve (x:xs) = (if isExcel x then exceltoRC x else rctoExcel x):solve xs\n\nmain = do n <- scan :: IO Int\n l <- scans n ::IO [String]\n putAnsLns (solve l)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt\n inputs <- replicateM n getLine\n mapM_ putStrLn $ parseInputs inputs\n\nparseInputs :: [String] -> [String]\nparseInputs [] = []\nparseInputs (x:xs) = [spreadSheets x] ++ parseInputs xs\n\nspreadSheets :: String -> String\nspreadSheets s = case xs of\n [_,r,_,c] -> rc (read r) (read c)\n [c,r] -> cr c (read r) \n\n where xs = groupBy(\\a b -> (isDigit a && isDigit b) || (isAlpha a && isAlpha b)) s\n\n\ncr :: String -> Int -> String\ncr c r = \"R\" ++ (show r) ++ \"C\" ++ show (conv c)\n\nconv :: String -> Int\nconv [] = 1\nconv (r:[]) = ord r - ord 'A' + 1\nconv (r:rs) = 26^(length rs) * (ord r - ord 'A' + 1) + conv rs\n\nrc :: Int -> Int -> String\nrc r c = (inv c) ++ show r\n\ninv :: Int -> String\ninv 0 = \"\"\ninv a = inv (a `div` 26) ++ [chr (ord 'A' + (a - 1) `mod` 26)]\n\nreadInt :: IO Int\nreadInt = readLn\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt\n inputs <- replicateM n getLine\n mapM_ putStrLn $ parseInputs inputs\n\nparseInputs :: [String] -> [String]\nparseInputs [] = []\nparseInputs (x:xs) = [spreadSheets x] ++ parseInputs xs\n\nspreadSheets :: String -> String\nspreadSheets s = case xs of\n [_,r,_,c] -> rc (read r) (read c)\n [c,r] -> cr c (read r) \n\n where xs = groupBy(\\a b -> (isDigit a && isDigit b) || (isAlpha a && isAlpha b)) s\n\n\ncr :: String -> Int -> String\ncr c r = \"R\" ++ (show r) ++ \"C\" ++ show (conv c)\n\nconv :: String -> Int\nconv [] = 1\nconv (r:[]) = ord r - ord 'A' + 1\nconv (r:rs) = 26^(length rs) * (ord r - ord 'A' + 1) + conv rs\n\nrc :: Int -> Int -> String\nrc r c = (inv c) ++ show r\n\ninv :: Int -> String\ninv 0 = \"\"\ninv a = inv (((a + 1)`div` 26)) ++ [chr (ord 'A' + (a - 1) `mod` 26)]\n\nreadInt :: IO Int\nreadInt = readLn\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nmapX :: a -> [a -> b] -> [b]\nmapX _ [] = []\nmapX x (f:fs) = [f x] ++ (mapX x fs)\n\nmap2 :: (a -> b -> c) -> [a] -> [b] -> [c]\nmap2 _ [] [] = []\nmap2 f (ax:axs) (bx:bxs) = [f ax bx] ++ map2 f axs bxs\n\nisEmpty :: [a] -> Bool\nisEmpty [] = True\nisEmpty _ = False\n\nall' :: (a -> Bool) -> [a] -> Bool\nall' _ [] = False\nall' f l = all f l\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\ntype CellType = Int\n\ncheckCellType :: String -> CellType\ncheckCellType s\n | length (splitByPredicate isDigit s) == 4 = 1\n | length (splitByPredicate isDigit s) == 2 = 2\n | otherwise = error \"wrong string!\"\n\nfastExp :: Int -> Int -> Int\nfastExp x 0 = 1\nfastExp x 1 = x\nfastExp x a\n | even a = lexp * lexp\n | odd a = lexp * lexp * a\n where\n lexp = fastExp (x * x) (div a 2)\n\ncolStr2Inth :: String -> Int\ncolStr2Inth [] = 0\ncolStr2Inth s = (colStr2Inth $ init s) * 26 + (ord (last s) - ord 'A')\n\ncolStr2Int :: String -> Int\ncolStr2Int s = sum (map (fastExp 26) [0 .. (length s - 1)]) + colStr2Inth s\n\nconvertCellType2To1 :: String -> String\nconvertCellType2To1 s = \n let sp = splitByPredicate isDigit s\n in \"R\" ++ (sp !! 1) ++ \"C\" ++ (show $ colStr2Int (sp !! 0))\n\n\ncolInt2Strhh :: Int -> String\ncolInt2Strhh n \n | n < 26 = [chr (ord 'A' + n)]\n | otherwise = (colInt2Strhh (div n 26)) ++ (colInt2Strhh (mod n 26))\n\ncolInt2Strh :: Int -> Int -> String\ncolInt2Strh n l =\n let hresult = colInt2Strhh n\n in (replicate (l - length hresult)) 'A' ++ hresult \n\ncolInt2Str :: Int -> String\ncolInt2Str n = \n let powList = map (fastExp 26) [0 .. 100]\n sumPowList = scanl1 (+) powList\n fi = fromJust (findIndex (<0) (map2 (-) (replicate 100 n) sumPowList))\n in colInt2Strh (n - (sumPowList !! (fi - 1))) (fi)\n\n\nconvertCellType1To2 :: String -> String\nconvertCellType1To2 s =\n let sp = splitByPredicate isDigit s\n in colInt2Str (read (sp !! 3) :: Int) ++ (sp !! 1)\n\n\nconvertCellType :: String -> String\nconvertCellType s\n | checkCellType s == 1 = convertCellType1To2 s\n | checkCellType s == 2 = convertCellType2To1 s\n\n\n\nmain = do\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n putStrLn $ unlines (map convertCellType sl)\n"}, {"source_code": "import Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nmapX :: a -> [a -> b] -> [b]\nmapX _ [] = []\nmapX x (f:fs) = [f x] ++ (mapX x fs)\n\nmap2 :: (a -> b -> c) -> [a] -> [b] -> [c]\nmap2 _ [] [] = []\nmap2 f (ax:axs) (bx:bxs) = [f ax bx] ++ map2 f axs bxs\n\nisEmpty :: [a] -> Bool\nisEmpty [] = True\nisEmpty _ = False\n\nall' :: (a -> Bool) -> [a] -> Bool\nall' _ [] = False\nall' f l = all f l\n\nsplitByPredicate :: (a -> Bool) -> [a] -> [[a]]\nsplitByPredicate _ [] = []\nsplitByPredicate p l\n | p (head l) == True = [takeWhile p l] ++ (splitByPredicate p (dropWhile p l))\n | otherwise = [takeWhile (not . p) l] ++ (splitByPredicate p (dropWhile (not . p) l))\n\ntype CellType = Int\n\ncheckCellType :: String -> CellType\ncheckCellType s\n | length (splitByPredicate isDigit s) == 4 = 1\n | length (splitByPredicate isDigit s) == 2 = 2\n | otherwise = error \"wrong string!\"\n\nfastExp :: Int -> Int -> Int\nfastExp x 0 = 1\nfastExp x 1 = x\nfastExp x a\n | even a = lexp * lexp\n | odd a = lexp * lexp * a\n where\n lexp = fastExp x (div a 2)\n\ncolStr2Inth :: String -> Int\ncolStr2Inth [] = 0\ncolStr2Inth s = (colStr2Inth $ init s) * 26 + (ord (last s) - ord 'A')\n\ncolStr2Int :: String -> Int\ncolStr2Int s = sum (map (fastExp 26) [0 .. (length s - 1)]) + colStr2Inth s\n\nconvertCellType2To1 :: String -> String\nconvertCellType2To1 s = \n let sp = splitByPredicate isDigit s\n in \"R\" ++ (sp !! 1) ++ \"C\" ++ (show $ colStr2Int (sp !! 0))\n\n\ncolInt2Strhh :: Int -> String\ncolInt2Strhh n \n | n < 26 = [chr (ord 'A' + n)]\n | otherwise = (colInt2Strhh (div n 26)) ++ (colInt2Strhh (mod n 26))\n\ncolInt2Strh :: Int -> Int -> String\ncolInt2Strh n l =\n let hresult = colInt2Strhh n\n in (replicate (l - length hresult)) 'A' ++ hresult \n\ncolInt2Str :: Int -> String\ncolInt2Str n = \n let powList = map (fastExp 26) [0 .. 100]\n sumPowList = scanl1 (+) powList\n fi = fromJust (findIndex (<0) (map2 (-) (replicate 100 n) sumPowList))\n in colInt2Strh (n - (sumPowList !! (fi - 1))) (fi)\n\n\nconvertCellType1To2 :: String -> String\nconvertCellType1To2 s =\n let sp = splitByPredicate isDigit s\n in colInt2Str (read (sp !! 3) :: Int) ++ (sp !! 1)\n\n\nconvertCellType :: String -> String\nconvertCellType s\n | checkCellType s == 1 = convertCellType1To2 s\n | checkCellType s == 2 = convertCellType2To1 s\n\n\n\nmain = do\n {- putStrLn $ show $ fastExp 26 2\n putStrLn $ show (scanl1 (+) (map (fastExp 26) [0 .. 20]))-}\n sn <- getLine\n let n = read sn :: Int\n sl <- getLines n\n putStrLn $ unlines (map convertCellType sl)\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nmain = interact $ unlines . map conv . tail . lines\n\nconv s = to arr\n where arr = groupBy (\\a b -> isDigit a == isDigit b) s \n\nto [c, r] = \"R\" ++ r ++ \"C\" ++ (show . toRCcolumn $ c)\nto [_, r, _, c] = (reverse . toXYcolumn . read $ c) ++ r\n\ntoRCcolumn = foldl (\\acc d -> 26 * acc + ord d - ord 'A' + 1) 0\n\ntoXYcolumn 0 = []\ntoXYcolumn c = (chr (cmod + ord 'A' - 1)) : toXYcolumn cdiv\n where (cdiv, cmod) = c `divMod` 26"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.DeepSeq\nimport Data.Function\nimport Data.List\nimport Data.Char\n\n--import Debug.Trace\n\ntype AlphaNum = String -- little endian\n\nstr2an = reverse\nan2str = reverse\n\ndata Numeration = T1 String Int | T2 Int Int\n\ninstance Show Numeration where\n show (T1 col row) = col ++ show row\n show (T2 row col) = \"R\" ++ show row ++ \"C\" ++ show col\n\nisT2 (r:x:cy) = (r == 'R') && isDigit x && ('C' `elem` cy)\nisT2 _ = False\n\ntoT1 str = T1 col (read row) where\n (col, row) = span isLetter str\n\ntoT2 str = T2 (read row) (read col) where\n (r:row, c:col) = span ((/=) 'C') str\n\nconvertType (T1 col row) = T2 row (atoi col)\nconvertType (T2 row col) = T1 (itoa col) row\n\n-- 'i' is 0-index\natoi [] = 0\natoi str = (ord x - ord 'A' + 1) + (26 * atoi xs) where\n x = last str\n xs = init str\n\nitoc i = chr (ord 'A' + i - 1)\nitoa i\n | i < 26 = [itoc i]\n | otherwise = itoa q' ++ [itoc r'] where\n (q, r) = i `divMod` 26\n (q', r') = if r == 0 then (q-1, 26) else (q, r)\n\nprocess :: String -> String\nprocess str = show numeration' where\n numeration = if isT2 str then toT2 str else toT1 str\n numeration' = convertType numeration\n\nprintLines = fmap head . sequence . map putStrLn\n\nmain = do\n n <- read <$> getLine\n lines <- replicateM n getLine\n printLines (map process lines)\n\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Char\n--import Debug.Trace\n\ndata Numeration = T1 String Int | T2 Int Int\n\ninstance Show Numeration where\n show (T1 col row) = col ++ show row\n show (T2 row col) = \"R\" ++ show row ++ \"C\" ++ show col\n\nisT2 (r:x:cy) = (r == 'R') && isDigit x && ('C' `elem` cy)\nisT2 _ = False\n\ntoT1 str = T1 col (read row) where\n (col, row) = span isLetter str\n\ntoT2 str = T2 (read row) (read col) where\n (r:row, c:col) = span ((/=) 'C') str\n\nconvertType (T1 col row) = T2 row (atoi col + 1)\nconvertType (T2 row col) = T1 (itoa (col - 1)) row\n\n-- 'i' is 0-index\n\natoi [] = 0\natoi str = (ord x - ord 'A') + (26 * atoi xs) where\n x = last str\n xs = init str\n\nitoc i = chr (ord 'A' + i)\nitoa i\n | i < 26 = [itoc i]\n | otherwise = itoa q ++ [itoc r] where\n (q, r) = i `divMod` 26\n\nprocess :: String -> String\nprocess str = show numeration' where\n numeration = if isT2 str then toT2 str else toT1 str\n numeration' = convertType numeration\n\nprintLines = fmap head . sequence . map putStrLn\n\nmain = do\n n <- read <$> getLine\n lines <- replicateM n getLine\n printLines (map process lines)\n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nintToStr 0 = []\nintToStr x = chr ( ( x `mod` 26 ) + ord 'A' - 1 ) : intToStr ( x `div` 26 )\n\nstrToInt = foldl ( \\ x y -> 26 * x + ord y - ord 'A' + 1 ) 0\n\nsolve str =\n\tcase parse str of\n\t\t[_,r,_,c] -> ( reverse . intToStr . read $ c ) ++ r\n\t\t[c,r] -> \"R\" ++ r ++ \"C\" ++ ( show . strToInt $ c )\n\twhere parse = groupBy ( \\ a b -> isDigit a == isDigit b )\n\nmain = interact $ unlines . map solve . tail . lines\n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n == 0 = \"\"\n | otherwise = n2a (n `div` 26) ++ [c (n `mod` 26)]\n where\n c x = chr (ord 'A' + x + 1)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n\nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n > 26 = c (n `div` 26) : n2a (n `mod` 26)\n | otherwise = [c n]\n where\n c x = chr (ord 'A' + x - 1)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n\nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n > 26 = c (n `div` 26) : n2a (n `mod` 26)\n | otherwise = [c n]\n where\n c x = chr (ord 'A' + x - 1)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n \nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n \n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n > 26 = n2a (n `div` 26) ++ [c (n `mod` 26)]\n | otherwise = [c n]\n where\n c x = chr (ord 'A' + x - 1)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n\nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n > 26 = n2a (n `div` 27) ++ [c (n `mod` 27)]\n | otherwise = [c n]\n where\n c x = chr (ord 'A' + x + 1)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n\nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\na2n :: String -> Int\na2n s = a2n' s 0\n where\n a2n' [] acc = acc\n a2n' (x:xs) acc = a2n' xs (26 * acc + (ord x - ord 'A' + 1))\n\nn2a :: Int -> String\nn2a n\n | n == 0 = \"\"\n | otherwise = n2a (n `div` 26) ++ [c (n `mod` 26)]\n where\n c x = chr (ord 'A' + x - 1)\n\n-- R23C55 => BC23\ntoYX :: String -> String -> String\ntoYX row col = (n2a $ (read col :: Int)) ++ row\n\n-- BC23 => R23C55\ntoRXCY :: String-> String -> String\ntoRXCY col row = \"R\" ++ row ++ \"C\" ++ c\n where\n c = show $ a2n col\n\ncalc :: String -> String \ncalc s = case length xs of\n 2 -> toRXCY (xs!!0) (xs!!1)\n 4 -> toYX (xs!!1) (xs!!3)\n _ -> error \"invalid length\"\n where\n xs = groupBy (\\a b -> (isAlpha a && isAlpha b) || (isDigit a && isDigit b)) s\n\ndoLine :: Int -> IO ()\ndoLine 0 = return ()\ndoLine n = do s <- getLine\n putStrLn $ calc s\n doLine (n-1)\n\nmain = do s <- getLine\n let n = read s :: Int\n doLine n\n"}, {"source_code": "import Data.Char\nimport Data.Function\nimport Data.List\n\nfromBase26 :: String->Int\n-- 64 = 'A' - 1\nfromBase26 s = foldl (\\acc c->acc*26 + ord c -64) 0 s\n\ntoBase26::Int->String\ntoBase26 i = if i == 0\n then []\n else toBase26 (i `div` 26) ++ return (chr (i `mod` 26 + 64))\n\nparseSplit input = groupBy ((==) `on` isAlpha) input\n \ntransform :: [String] -> String\ntransform [_, r, _, c] = toBase26 (read c::Int) ++ r\ntransform [c, r] = \"R\" ++ r ++ \"C\" ++ show (fromBase26 c)\n\nact :: IO()\nact = do\n s<-getLine\n putStrLn $ transform $ parseSplit s\n\nmain = do\n s<-getLine\n let testNum = read s::Int\n mapM_ (\\x->act) $take testNum[1..]\n return ()\n"}, {"source_code": "import Data.Char\n\ndata CharType = Alpha | Digit | Unknown\n deriving (Eq)\n\ndata CellFormat = ABC123 | RXCY\n deriving (Show)\ndata CellRef = CellRef {\n row :: Integer,\n column :: Integer\n} deriving (Show)\n\ncharType :: Char -> CharType\ncharType c | isDigit c = Digit\n | isAlpha c = Alpha\n | otherwise = Unknown\n\nsplit :: String -> [String]\nsplit s = reverse (split2 s [])\n\nsplit2 :: String -> [String] -> [String]\nsplit2 [] xs = xs\nsplit2 (c:cs) [] = split2 cs [[c]]\nsplit2 (c:cs) (x:xs) | charType c == charType (head x) = split2 cs ((x ++ [c]):xs)\n | otherwise = split2 cs ([c]:x:xs)\n\n\nreadColumnRef :: String -> Integer\nreadColumnRef s = readColumnRef2 0 s\n where readColumnRef2 v [] = v\n readColumnRef2 v (x:xs) = readColumnRef2 (v*26 + toInteger (ord (toUpper x) - ord 'A' + 1)) xs\n\nshowColumnRef :: Integer -> String\nshowColumnRef x = showColumnRef2 \"\" x\n where showColumnRef2 :: String -> Integer -> String\n showColumnRef2 [] 0 = \"0\"\n showColumnRef2 s 0 = s\n showColumnRef2 s x = showColumnRef2 ([chr ((fromIntegral (x `mod` 26)) + ord 'A' - 1)] ++ s) (x `div` 26)\n\nreadCellRef :: String -> (CellRef, CellFormat)\nreadCellRef s = case (split s) of\n (\"R\":x:\"C\":y:[]) -> (CellRef (read x) (read y), RXCY)\n (a:x:[]) | (charType (head a) == Alpha) && (charType (head x) == Digit) -> (CellRef (read x) (readColumnRef a), ABC123)\n _ -> error \"Invalid cell reference format\"\n\nshowCellRef :: CellRef -> CellFormat -> String\nshowCellRef c ABC123 = (showColumnRef (column c)) ++ (show (row c))\nshowCellRef c RXCY = \"R\" ++ (show (row c)) ++ \"C\" ++ (show (column c))\n\nconvert :: String -> String\nconvert s = case (readCellRef s) of\n (c, ABC123) -> showCellRef c RXCY\n (c, RXCY) -> showCellRef c ABC123\n\nsolve :: IO ()\nsolve = getLine >>= (putStrLn . convert)\n\nsolveN :: Int -> IO ()\nsolveN 1 = solve\nsolveN n = do\n solve\n solveN (n-1)\n\nmain = getLine >>= (solveN . read)\n\n"}, {"source_code": "import Data.Char\n\ndata CharType = Alpha | Digit | Unknown\n deriving (Eq)\n\ndata CellFormat = ABC123 | RXCY\n deriving (Show)\ndata CellRef = CellRef {\n row :: Integer,\n column :: Integer\n} deriving (Show)\n\ncharType :: Char -> CharType\ncharType c | isDigit c = Digit\n | isAlpha c = Alpha\n | otherwise = Unknown\n\nstringType :: String -> CharType\nstringType s = charType (head s)\n\nsplit :: String -> [String]\nsplit s = reverse (split2 s [])\n\nsplit2 :: String -> [String] -> [String]\nsplit2 [] xs = xs\nsplit2 (c:cs) [] = split2 cs [[c]]\nsplit2 (c:cs) (x:xs) | charType c == charType (head x) = split2 cs ((x ++ [c]):xs)\n | otherwise = split2 cs ([c]:x:xs)\n\n\nreadColumnRef :: String -> Integer\nreadColumnRef s = readColumnRef2 0 s\n where readColumnRef2 v [] = v\n readColumnRef2 v (x:xs) = readColumnRef2 (v*26 + toInteger (ord (toUpper x) - ord 'A' + 1)) xs\n\nshowColumnRef :: Integer -> String\nshowColumnRef x = showColumnRef2 \"\" x\n where showColumnRef2 :: String -> Integer -> String\n showColumnRef2 [] 0 = \"A\"\n showColumnRef2 s 0 = s\n showColumnRef2 s x = showColumnRef2 ([chr ((fromIntegral ((x-1) `mod` 26)) + ord 'A')] ++ s) (x `div` 26)\n\nreadCellRef :: String -> (CellRef, CellFormat)\nreadCellRef s = case (split s) of\n (\"R\":x:\"C\":y:[]) ->\n (CellRef (read x) (read y), RXCY)\n (a:x:[]) | (stringType a == Alpha) && (stringType x == Digit) ->\n (CellRef (read x) (readColumnRef a), ABC123)\n _ -> error \"Invalid cell reference format\"\n\nshowCellRef :: CellRef -> CellFormat -> String\nshowCellRef c ABC123 = (showColumnRef (column c)) ++ (show (row c))\nshowCellRef c RXCY = \"R\" ++ (show (row c)) ++ \"C\" ++ (show (column c))\n\nconvert :: String -> String\nconvert s = case (readCellRef s) of\n (c, ABC123) -> showCellRef c RXCY\n (c, RXCY) -> showCellRef c ABC123\n\nsolve :: IO ()\nsolve = getLine >>= (putStrLn . convert)\n\nsolveN :: Int -> IO ()\nsolveN 1 = solve\nsolveN n = do\n solve\n solveN (n-1)\n\nmain = getLine >>= (solveN . read)\n\n"}, {"source_code": "import Data.Char\n\ndata CharType = Alpha | Digit | Unknown\n deriving (Eq)\n\ndata CellFormat = ABC123 | RXCY\n deriving (Show)\ndata CellRef = CellRef {\n row :: Integer,\n column :: Integer\n} deriving (Show)\n\ncharType :: Char -> CharType\ncharType c | isDigit c = Digit\n | isAlpha c = Alpha\n | otherwise = Unknown\n\nsplit :: String -> [String]\nsplit s = reverse (split2 s [])\n\nsplit2 :: String -> [String] -> [String]\nsplit2 [] xs = xs\nsplit2 (c:cs) [] = split2 cs [[c]]\nsplit2 (c:cs) (x:xs) | charType c == charType (head x) = split2 cs ((x ++ [c]):xs)\n | otherwise = split2 cs ([c]:x:xs)\n\n\nreadColumnRef :: String -> Integer\nreadColumnRef s = readColumnRef2 0 s\n where readColumnRef2 v [] = v\n readColumnRef2 v (x:xs) = readColumnRef2 (v*26 + toInteger (ord (toUpper x) - ord 'A' + 1)) xs\n\nshowColumnRef :: Integer -> String\nshowColumnRef x = showColumnRef2 \"\" x\n where showColumnRef2 :: String -> Integer -> String\n showColumnRef2 [] 0 = \"0\"\n showColumnRef2 s 0 = s\n showColumnRef2 s x = showColumnRef2 ([chr ((fromIntegral (x `mod` 26)) + ord 'A' - 1)] ++ s) (x `div` 26)\n\nreadCellRef :: String -> (CellRef, CellFormat)\nreadCellRef s = case (split s) of\n (\"R\":x:\"C\":y:[]) -> (CellRef (read x) (read y), RXCY)\n (a:x:[]) | (charType (head a) == Alpha) && (charType (head x) == Digit) -> (CellRef (read x) (readColumnRef a), ABC123)\n _ -> error \"Invalid cell reference format\"\n\nshowCellRef :: CellRef -> CellFormat -> String\nshowCellRef c ABC123 = (showColumnRef (column c)) ++ (show (row c))\nshowCellRef c RXCY = \"R\" ++ (show (row c)) ++ \"C\" ++ (show (column c))\n\nconvert :: String -> String\nconvert s = case (readCellRef s) of\n (c, ABC123) -> showCellRef c RXCY\n (c, RXCY) -> showCellRef c ABC123\n\nsolve :: IO ()\nsolve = getLine >>= (print . convert)\n\nsolveN :: Int -> IO ()\nsolveN 1 = solve\nsolveN n = do\n solve\n solveN (n-1)\n\nmain = getLine >>= (solveN . read)\n\n"}, {"source_code": "import Data.Char\n\ndata CharType = Alpha | Digit | Unknown\n deriving (Eq)\n\ndata CellFormat = ABC123 | RXCY\n deriving (Show)\ndata CellRef = CellRef {\n row :: Integer,\n column :: Integer\n} deriving (Show)\n\ncharType :: Char -> CharType\ncharType c | isDigit c = Digit\n | isAlpha c = Alpha\n | otherwise = Unknown\n\nsplit :: String -> [String]\nsplit s = reverse (split2 s [])\n\nsplit2 :: String -> [String] -> [String]\nsplit2 [] xs = xs\nsplit2 (c:cs) [] = split2 cs [[c]]\nsplit2 (c:cs) (x:xs) | charType c == charType (head x) = split2 cs ((x ++ [c]):xs)\n | otherwise = split2 cs ([c]:x:xs)\n\n\nreadColumnRef :: String -> Integer\nreadColumnRef s = readColumnRef2 0 s\n where readColumnRef2 v [] = v\n readColumnRef2 v (x:xs) = readColumnRef2 (v*26 + toInteger (ord (toUpper x) - ord 'A' + 1)) xs\n\nshowColumnRef :: Integer -> String\nshowColumnRef x = showColumnRef2 \"\" x\n where showColumnRef2 :: String -> Integer -> String\n showColumnRef2 [] 0 = \"0\"\n showColumnRef2 s 0 = s\n showColumnRef2 s x = showColumnRef2 ([chr ((fromIntegral (x `mod` 26)) + ord 'A' - 1)] ++ s) (x `div` 26)\n\nreadCellRef :: String -> (CellRef, CellFormat)\nreadCellRef s = case (split s) of\n (\"R\":x:\"C\":y:[]) -> (CellRef (read x) (read y), RXCY)\n (a:x:[]) | (charType (head a) == Alpha) && (charType (head x) == Digit) -> (CellRef (readColumnRef a) (read x), ABC123)\n _ -> error \"Invalid cell reference format\"\n\nshowCellRef :: CellRef -> CellFormat -> String\nshowCellRef c ABC123 = (showColumnRef (column c)) ++ (show (row c))\nshowCellRef c RXCY = \"R\" ++ (show (row c)) ++ \"C\" ++ (show (column c))\n\nconvert :: String -> String\nconvert s = case (readCellRef s) of\n (c, ABC123) -> showCellRef c RXCY\n (c, RXCY) -> showCellRef c ABC123\n\nsolve :: IO ()\nsolve = getLine >>= (print . convert)\n\nsolveN :: Int -> IO ()\nsolveN 1 = solve\nsolveN n = do\n solve\n solveN (n-1)\n\nmain = getLine >>= (solveN . read)\n\n"}, {"source_code": "module Main where\n\nimport Data.List (groupBy)\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocessInput :: Int -> String -> String\nprocessInput n = unlines . map processLine . take n . lines\n\nprocessLine :: String -> String\nprocessLine line = case (map tail $ groupBy (\\a b -> b /= 'C') line) of\n [r, c] -> convert (read c) ++ r\n\nconvert :: Int -> String\nconvert n = if n <= 26\n then [['A'..'Z'] !! (n - 1)]\n else case quotRem n 26 of\n (q, r) -> (convert q) ++ (convert r)\n\nmain = do\n n <- getInt\n interact $ processInput n\n"}], "src_uid": "910c0e650d48af22fa51ab05e8123709"} {"source_code": "import Control.Arrow ((&&&))\nimport Data.List (transpose)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Integer]] -> Integer\nsolve = (^(2::Integer)) . maximum . map (uncurry (-) . (maximum &&& minimum)) . transpose\n", "positive_code": [{"source_code": "main = interact $ show . (\\[a,b,c,d] -> let e = max (b-a) (d-c) in e*e) .f . map read . tail . words\nf (a:b:[]) = [a,a,b,b]\nf (a:b:c) = [min a p, max a q, min b r, max b s] where [p,q,r,s] = f c"}], "negative_code": [], "src_uid": "016e00b2b960be792d4ec7fcfb7976e2"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Data.List\n\n{-\nimport Debug.Trace\nf $$ x = traceShow x (f x)\ninfixr 0 $$\n-}\n\nmain = do\n input <- fmap B.lines B.getContents\n let [n,m] = map readI $ B.words $ head input\n let es = map ((\\[x,y]->x`seq`y`seq`(x,y)) . map readI . B.words) $ tail input\n print (solve es)\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: [(Int,Int)] -> Int\nsolve es =\n length $ filter id $ unfoldr h edges\n where\n edges = M.filter ((==2).length) $ foldl g M.empty es\n\n g m (e,d) = M.alter (f d) e $ M.alter (f e) d m\n\n f d Nothing = Just [d]\n f d (Just ds) = Just (d:ds)\n\n h m | M.null m = Nothing\n |otherwise = let (found,m') = findCycle m in Just (found,m')\n\nfindCycle :: M.Map Int [Int] -> (Bool, M.Map Int [Int])\nfindCycle edges =\n go start start next (M.delete start edges)\n where\n (start,next:_) = M.findMin edges\n\n go s t u m =\n-- traceShow (s,t,u,m) $\n case fmap (filter (/=t)) (M.lookup u m) of\n Just [v] | v==s -> (True, M.delete v (M.delete u m))\n |otherwise -> go s u v (M.delete u m)\n _ -> (False, M.delete u m)", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.State.Strict\nimport Data.Array.IArray\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n edges <- concatMap(\\(x,y) -> [(x-1,y-1),(y-1,x-1)]).unfoldr (runStateT parseInt2) <$> B.getContents\n print $ solve n m edges\n\nsolve :: Int -> Int -> [(Int, Int)] -> Int\nsolve n m edges = length[vs|vs<-scc gr, all (\\v->length(gr!v) == 2) vs]\n where\n !gr = mkGraph (0,n-1) edges\n\n-------------------------------------------------------------------------------\ntype Vertex = Int\ntype Edge = (Vertex, Vertex)\ntype Graph = Array Vertex [Vertex]\ntype Path = [Vertex]\n\nmkGraph :: (Int, Int) -> [Edge] -> Graph\nmkGraph bnd edges = accumArray (flip (:)) [] bnd edges\n\nvertices :: Graph -> [Vertex]\nvertices gr = range $ bounds gr\n\nedges :: Graph -> [Edge]\nedges gr = [(from, to) | from <- vertices gr, to <- (!) gr from ]\n\nrevGraph :: Graph -> Graph\nrevGraph gr = mkGraph (bounds gr) . map swap $ edges gr\n\ndfsAll :: Graph -> [Vertex] -> [[Vertex]]\ndfsAll gr vs = filter (not.null) $ runST $ do\n vis <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)\n mapM (dfsM gr vis) vs\n\ndfsM :: Graph -> STUArray s Vertex Bool -> Vertex -> ST s [Vertex]\ndfsM gr vis root = do\n let go res (v:vs) = do\n visited <- readArray vis v\n if visited then go res vs\n else do\n writeArray vis v True\n go (v:res) ((!) gr v ++ vs)\n go res [] = return $ reverse res\n go [] [root]\n\ntopSort :: Graph -> [Vertex]\ntopSort gr = runST $ do\n vis <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)\n stack <- newSTRef [] :: ST s (STRef s [Vertex])\n let visit v = do\n visited <- readArray vis v\n unless visited $ do\n writeArray vis v True\n mapM_ visit $ (!) gr v\n modifySTRef stack (v:)\n mapM_ visit $ vertices gr\n readSTRef stack\n\nscc :: Graph -> [[Vertex]]\nscc gr = dfsAll gr . topSort $ revGraph gr\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nparseInt3 :: Parser (Int, Int, Int)\nparseInt3 = (,,) <$> parseInt <*> parseInt <*> parseInt\n"}], "negative_code": [], "src_uid": "cf7520d88e10ba171de443f36fdd2b73"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.IO\nimport Data.Array.Base\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInteger :: B.ByteString -> Int64\nreadInteger = fromInteger . fromJust . fmap fst . B.readInteger\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n (_ps,_bs) <- splitAt n . map (map readInteger. B.words) . B.lines <$> B.getContents\n let ps = map l2p _ps\n let bs = head _bs\n let qs = [ (r2 - l1,l2 - r1,i) | \n ((l1,r1),(l2,r2),i) <- zip3 ps (tail ps) [0..] ]\n\n arr <- newArray_ (0,n-2) :: IO (IOUArray Int Int)\n let go [] _ = return True\n go ((b,a,i):qs') s = case S.lookupGT (a,0) s of\n Just (c,bi) | c <= b -> do\n unsafeWrite arr i bi\n go qs' (S.delete (c,bi) s) \n _ -> return False\n b <- go (sort qs) (S.fromList $ zip bs [1..])\n if b then do\n putStrLn \"Yes\"\n as <- getElems arr\n putStrLn $ unwords $ map show as\n else \n putStrLn \"No\"\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInteger = fromJust . fmap fst . B.readInteger\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n (_ps,_bs) <- splitAt n . map (map readInteger. B.words) . B.lines <$> B.getContents\n let ps = map l2p _ps\n let bs = head _bs\n let qs = [ (r2 - l1,l2 - r1,i) | ((l1,r1),(l2,r2),i) <- zip3 ps\n (tail ps)\n [1..] ]\n\n let go :: [(Integer,Integer,Int)] -> S.Set (Integer,Int) -> Maybe [(Int,Int)]\n go [] _ = Just []\n go ((b,a,i):qs') s =\n case S.lookupGT (a,0) s of\n Just (c,bi) | c <= b -> \n ((i,bi):) <$> go qs' (S.delete (c,bi) s)\n _ -> Nothing\n let x = sort qs\n let y = S.fromList (zip bs [(1 :: Int)..])\n case go x y of\n Just l -> do\n putStrLn \"Yes\"\n putStrLn $ unwords $ [ show bi | (i,bi) <- sort l ]\n Nothing -> putStrLn \"No\"\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.IO\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInteger = fromJust . fmap fst . B.readInteger\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n (_ps,_bs) <- splitAt n . map (map readInteger. B.words) . B.lines <$> B.getContents\n let ps = map l2p _ps\n let bs = head _bs\n let qs = [ (r2 - l1,l2 - r1,i) | ((l1,r1),(l2,r2),i) <- zip3 ps\n (tail ps)\n [1..] ]\n\n\n arr <- newArray_ (1,n-1) :: IO (IOUArray Int Int)\n let go [] _ = return True\n go ((b,a,i):qs') s =\n case S.lookupGT (a,0) s of\n Just (c,bi) | c <= b -> do\n writeArray arr i bi\n go qs' (S.delete (c,bi) s) \n _ -> return False\n b <- go (sort qs) (S.fromList $ zip bs [1..])\n if b then do\n putStrLn \"Yes\"\n as <- getElems arr\n putStrLn $ unwords $ map show as\n else \n putStrLn \"No\"\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n (_ps,_bs) <- splitAt n . map (map readInt. B.words) . B.lines <$> B.getContents\n let ps = map l2p _ps\n let bs = head _bs\n let qs = [ (r2 - l1,l2 - r1,i) | ((l1,r1),(l2,r2),i) <- zip3 ps\n (tail ps)\n [1..] ]\n\n let go [] _ = Just []\n go (_:_) [] = Nothing\n go ((b,a,i):qs') ((c,bi):cs) \n | a <= c && c <= b = ((i,bi):) <$> go qs' cs\n | otherwise = go ((b,a,i):qs') cs\n let x = sort qs\n let y = sort (zip bs [1..])\n case go x y of\n Just l -> do\n putStrLn \"Yes\"\n putStrLn $ unwords $ [ show bi | (i,bi) <- sort l ]\n Nothing -> putStrLn \"No\"\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInteger = fromJust . fmap fst . B.readInteger\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n (_ps,_bs) <- splitAt n . map (map readInt. B.words) . B.lines <$> B.getContents\n let ps = map l2p _ps\n let bs = head _bs\n let qs = [ (r2 - l1,l2 - r1,i) | ((l1,r1),(l2,r2),i) <- zip3 ps\n (tail ps)\n [1..] ]\n\n let go [] _ = Just []\n go ((b,a,i):qs') s =\n case S.lookupGT (a,0) s of\n Just (c,bi) | c <= b -> \n ((i,bi):) <$> go qs' (S.delete (c,bi) s)\n _ -> Nothing\n let x = sort qs\n let y = S.fromList (zip bs [(1 :: Int)..])\n case go x y of\n Just l -> do\n putStrLn \"Yes\"\n putStrLn $ unwords $ [ show bi | (i,bi) <- sort l ]\n Nothing -> putStrLn \"No\"\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInteger = fromJust . fmap fst . B.readInteger\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n (_ps,_bs) <- splitAt n . map (map readInteger. B.words) . B.lines <$> B.getContents\n let ps = map l2p _ps\n let bs = head _bs\n let qs = [ (r2 - l1,l2 - r1,i) | ((l1,r1),(l2,r2),i) <- zip3 ps\n (tail ps)\n [1..] ]\n\n let go [] _ = Just []\n go (_:_) [] = Nothing\n go ((b,a,i):qs') ((c,bi):cs) \n | a <= c && c <= b = ((i,bi):) <$> go qs' cs\n | otherwise = go ((b,a,i):qs') cs\n let x = sort qs\n let y = sort (zip bs [1..])\n case go x y of\n Just l -> do\n putStrLn \"Yes\"\n putStrLn $ unwords $ [ show bi | (i,bi) <- sort l ]\n Nothing -> putStrLn \"No\"\n"}], "src_uid": "f7a34711e8a4faa9822d42ef54a0bfc1"} {"source_code": "main = interact $ unlines . map solve . tail . lines\nsolve x | [a, b] <- map read $ words x = if gcd a b == 1 then \"Finite\" else \"Infinite\" ", "positive_code": [{"source_code": "import Data.List\nimport Numeric\n\n(|>) = flip (.)\n\nint :: String -> Int\nint x = fst $ readDec x !! 0\n\nints :: String -> [Int]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = go t xs\n where\n t = int ts\n go 0 _ = []\n go t (x:xs) = solve (ints x) : go (t-1) xs\n\nsolve :: [Int] -> String\nsolve (a:b:_) =\n if gcd a b == 1\n then \"Finite\"\n else \"Infinite\"\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nrl = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n [t] <- rl \n replicateM_ t $ do\n [a, b] <- rl\n putStrLn $ if a == 1 || b == 1 || max a b `mod` min a b == 1 then \"Finite\" else \"Infinite\"\n"}], "src_uid": "388450021f2f33177d905879485bb531"} {"source_code": "import Control.Monad\r\nimport Data.Int\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int64\r\n let n' | n < 6 = 6\r\n | odd n = n + 1\r\n | otherwise = n\r\n print $ n' * 5 `div` 2\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nprintResult = do\r\n n <- readLn :: IO Integer\r\n print $ if n <= 6 then 15 else div ((n + mod n 2)*5) 2 \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.Int\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int64\r\n let n' | n < 6 = 6\r\n | odd n = n + 1\r\n | otherwise = n\r\n print $ n' * 5 `div` 2\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE LambdaCase #-}\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = show . solve <$> integer\n\nlim = 400\ndp :: [Integer]\ndp = 0 : do\n n <- [1..lim]\n let get m = dp !! max 0 m\n return $ minimum [15 + get (n - 6), 20 + get (n - 8), 25 + get (n - 10)]\n\nsolve :: Integer -> Integer\nsolve n\n | n < fi lim = dp !! fi n\n | otherwise = let q = (n - 200) `div` 120 in 12 * q * 25 + solve (n - q * 120)\n\nfi :: (Num b, Integral a) => a -> b\nfi = fromIntegral\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}], "negative_code": [], "src_uid": "3e27f1c06a263760f5b53c3afe4bf7ee"} {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (accumArray, (!))\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n es <- replicateM (n-1) ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n r = maximum $ map solve (g ! 1)\n where\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n solve = foldl1 (\\a -> max (a+1)) . sort . dfs 0 1 []\n where\n dfs d w r u\n | null vs = d:r\n | otherwise = foldl (dfs (d+1) u) r vs\n where\n vs = filter (/= w) $ g ! u\n\n print $ r + 1\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Array (accumArray, (!))\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n es <- replicateM (n-1) ((\\[a, b] -> (a, b)) <$> readInts)\n\n let\n r = maximum $ map solve (g ! 1)\n where\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es\n\n solve u = foldl1 (\\a b -> max (a+1) b) $ sort $ dfs 0 1 [] u\n where\n dfs d w r u\n | null vs = d:r\n | otherwise = foldl (dfs (d+1) u) r vs\n where\n vs = filter (/= w) $ g ! u\n\n print $ r + 1\n"}], "negative_code": [], "src_uid": "818e5f23028faf732047fc177eeb3851"} {"source_code": "-- 845B\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Data.List (sortBy)\n\nmain = getLine >> (B.interact $ program . input)\n where input = (map . map) (fst . fromJust . B.readInt) . map B.words . B.lines\n\nprogram :: [[Int]] -> B.ByteString\nprogram shows = runShows sortedShows []\n where sortedShows = sortBy (compare `on` fst) $ map (\\[s,e] -> (s,e)) shows\n\nrunShows :: [(Int,Int)] -> [Int] -> B.ByteString\nrunShows [] _ = \"YES\\n\"\nrunShows ((s,e):shows) tvs =\n let tvs' = e:(filter (>=s) tvs) in\n if length tvs' > 2\n then \"NO\\n\"\n else runShows shows tvs'\n\n\n\n", "positive_code": [{"source_code": "-- http://codeforces.com/contest/845/problem/C\n\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n lrs <- (sortBy (\\[x,_] [y,_] -> compare x y)) `fmap` replicateM n getInts\n if can lrs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncan lrs = f lrs (-1) (-1) where\n f [] _ _ = True\n f ([l,r]:lrs) x y\n | l <= x && l <= y = False\n | l <= x && l > y = f lrs x r\n | l > x && l <= y = f lrs r y\n | x < y = f lrs r y\n | otherwise = f lrs x r"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine, getContents)\nimport qualified Data.ByteString.Char8 as C (readInt, words, lines)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Function (on)\nimport Data.List (sortBy)\n\nreadInt = fst . M.fromJust . C.readInt\nrun _ _ [] = True\nrun i j ((xa, xb):xs) | xa <= i && xa <= j = False\n | xa <= i || (j > i && xa > j) = run i xb xs\n | otherwise = run xb j xs\n\nmain = do\n (readInt -> n) <- B.getLine\n (map ((\\[a, b] -> (a, b)) . map readInt . C.words) . C.lines -> xs) <- B.getContents\n let xxs = sortBy (compare `on` snd) xs\n putStrLn $ if run (-1) (-1) xxs then \"YES\" else \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Function\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n ss <- replicateM n $ liftM2 (,) poi poi\n return $ if solve ss then \"YES\" else \"NO\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = all (<= 2) . scanl1 (+) . map (sum . map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . concatMap (\\(b, e) -> [(b, 1), (e + 1, -1)])"}], "negative_code": [{"source_code": "-- http://codeforces.com/contest/845/problem/C\n\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n lrs <- (sortBy comp) `fmap` replicateM n getInts\n if can lrs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncomp [l1,r1] [l2,r2] = case compare l1 l2 of\n EQ -> compare r1 r2\n x -> x\n\ncan lrs = f lrs 0 0 where\n f [] _ _ = True\n f ([l,r]:lrs) x y\n | l <= x && l <= y = False\n | l <= x && l > y = f lrs x r\n | l > x && l <= y = f lrs r y\n | x < y = f lrs r y\n | otherwise = f lrs x r"}, {"source_code": "-- http://codeforces.com/contest/845/problem/C\n\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n lrs <- (sortBy (\\[_,x] [_,y] -> compare x y)) `fmap` replicateM n getInts\n if can lrs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncan lrs = f lrs 0 0 where\n f [] _ _ = True\n f ([l,r]:lrs) x y\n | l <= x && l <= y = False\n | l <= x && l > y = f lrs x r\n | otherwise = f lrs r y"}, {"source_code": "-- http://codeforces.com/contest/845/problem/C\n\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n lrs <- (sortBy (\\[_,x] [_,y] -> compare x y)) `fmap` replicateM n getInts\n if can lrs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncan lrs = f lrs 0 0 where\n f [] _ _ = True\n f ([l,r]:lrs) x y\n | l <= x && l <= y = False\n | l <= x && l > y = f lrs x r\n | l > x && l <= y = f lrs r y\n | x < y = f lrs r y\n | otherwise = f lrs x r"}, {"source_code": "-- http://codeforces.com/contest/845/problem/C\n\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n lrs <- (sortBy comp) `fmap` replicateM n getInts\n if can lrs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncomp [l1,r1] [l2,r2] = case compare r1 r2 of\n EQ -> compare l1 l2\n x -> x\n\ncan lrs = f lrs 0 0 where\n f [] _ _ = True\n f ([l,r]:lrs) x y\n | l <= x && l <= y = False\n | l <= x && l > y = f lrs x r\n | l > x && l <= y = f lrs r y\n | x < y = f lrs r y\n | otherwise = f lrs x r"}, {"source_code": "-- http://codeforces.com/contest/845/problem/C\n\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n lrs <- (sortBy (\\[x,_] [y,_] -> compare x y)) `fmap` replicateM n getInts\n if can lrs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ncan lrs = f lrs 0 0 where\n f [] _ _ = True\n f ([l,r]:lrs) x y\n | l <= x && l <= y = False\n | l <= x && l > y = f lrs x r\n | l > x && l <= y = f lrs r y\n | x < y = f lrs r y\n | otherwise = f lrs x r"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Function\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n ss <- replicateM n $ liftM2 (,) poi poi\n return $ if solve ss then \"YES\" else \"NO\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = all (<= 2) . scanl1 (+) . map snd . sortBy (compare `on` fst) . concatMap (\\(b, e) -> [(b, 1), (e + 1, -1)])"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Function\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n ss <- replicateM n $ liftM2 (,) poi poi\n return $ if solve ss then \"YES\" else \"NO\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = all (<= 2) . scanl1 (+) . map snd . sortBy (compare `on` fst) . concatMap (\\(b, e) -> [(b, 1), (e, -1)])"}], "src_uid": "9fa772b53e655a55f2ec502bc96d0e28"} {"source_code": "solve :: [Char] -> Int\nsolve q =\n let\n in gao q\n where\n gao s\n | null s = 0\n | head s == 'M' = iter 0 0 0 s\n | otherwise = gao $ tail s\n where\n iter res num_f num_m rem\n | null rem = res\n | head rem == 'F' = iter (max (res + 1) num_m) (num_f + 1) num_m $ tail rem\n | otherwise = iter res num_f (num_m + 1) $ tail rem\n\n\nmain = do\n q <- getLine\n print $ solve q\n", "positive_code": [{"source_code": "solve :: [Char] -> Int\nsolve q = gao q\n where\n gao s\n | null s = 0\n | head s == 'M' = iter 0 0 0 s\n | otherwise = gao $ tail s\n where\n iter res num_f num_m rem\n | null rem = res\n | head rem == 'F' = iter (max (res + 1) num_m) (num_f + 1) num_m $ tail rem\n | otherwise = iter res num_f (num_m + 1) $ tail rem\n\n\nmain = do\n q <- getLine\n print $ solve q\n"}], "negative_code": [{"source_code": "solve :: [Char] -> Int\nsolve q =\n let\n s = reverse q\n in gao s\n where\n gao s\n | null s = 0\n | head s == 'F' = iter 0 0 $ tail s\n | otherwise = gao $ tail s\n where\n iter res nf rem\n | null rem = res\n | head rem == 'M' = let\n nr = if nf == 0 then res + 1 else (max res nf) + 1\n in iter nr 0 $ tail rem\n | otherwise = iter res (nf + 1) $ tail rem\n\n\nmain = do\n q <- getLine\n putStrLn $ show $ solve q\n"}], "src_uid": "8423f334ef789ba1238d34f70e7cbbc8"} {"source_code": "import Control.Monad (forM_)\n\nsolve n b x y z\n | n == 0 = []\n | p > q && p <= b = p : solve (n -1) b x y p\n | otherwise = q : solve (n -1) b x y q\n where\n p = z + x\n q = z - y\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n let [n, b, x, y] = (map read . words) l\n print $ sum $ solve n b x y 0\n", "positive_code": [{"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n\r\nisqrt :: Int -> Int\r\nisqrt = floor . sqrt . fromIntegral\r\n\r\ncalc :: Int -> (Int, Int, Int, Int) -> Int\r\ncalc 0 _ = 0\r\ncalc i (a, b, x, y) = if (a + x <= b)\r\n then a + x + calc (i - 1) (a + x, b, x, y)\r\n else a - y + calc (i - 1) (a - y, b, x, y)\r\n\r\nsolve :: IO()\r\nsolve = do\r\n (n: b: x: y: _) <- readIntArr\r\n print $ calc n (0, b, x, y)\r\n\r\nfor :: Int -> IO () -> IO ()\r\nfor 0 _ = pure ()\r\nfor i f = do\r\n f\r\n for (i - 1) f\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readInt\r\n for t solve"}], "negative_code": [], "src_uid": "2c921093abf2c5963f5f0e96cd430456"} {"source_code": "module Main where\n\nmain = interact $ unlines . map (\\x -> unwords $ map show [1, (read x :: Int)-1]) . tail . lines ", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n x <- readLn\n printList [1, x - 1]"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\nwork :: IO ()\nwork = do\n x <- parseInt <$> C.getLine\n putStrLn $ \"1 \" ++ show (x - 1)\n\nmain :: IO ()\nmain = do\n n <- fmap parseInt C.getLine\n replicateM_ n work\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\t\t\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\ta<-map read<$> replicateM n getLine ::IO [Int]\n\t\tlet b= map ((\"1 \"++) .show . (\\z->z-1)) a\n\t\tmapM_ putStrLn b\n\n"}, {"source_code": "{-# LANGUAGE Strict #-}\nimport Control.Monad\n\nsolve :: [Int] -> IO ()\nsolve [] = return ()\nsolve (x:xs) = do\n putStrLn $ \"1 \" ++ show (x - 1)\n solve xs\n\nmain = do\n t <- readLn :: IO Int\n xs <- replicateM t readLn :: IO [Int]\n solve xs"}, {"source_code": "import Control.Monad\n\nsolve :: [Int] -> IO ()\nsolve [] = return ()\nsolve (x:xs) = do\n putStrLn $ \"1 \" ++ show (x - 1)\n solve xs\n\nmain = do\n t <- readLn :: IO Int\n xs <- replicateM t readLn :: IO [Int]\n solve xs"}, {"source_code": "process :: Int -> (Int,Int)\nprocess 2 = (1,1)\nprocess x\n | odd x = (e,o)\n | otherwise = (2,x-2)\n where\n o = until odd ( `div` 2) (x-1)\n e = (x-1) `div` o\n\nreadInt :: String -> Int\nreadInt = read\n\nshowPair :: (Int,Int) -> String\nshowPair (a,b) = show a ++ \" \" ++ show b\n\nmain = do\n t <- fmap readInt getLine\n xs <- fmap (map readInt.words) getContents\n putStrLn . unlines $ map (showPair.process) xs"}, {"source_code": "solve :: Integer -> (Integer, Integer)\nsolve x = (1, x - 1)\n\nparse :: String -> String\nparse input = (show a) ++ \" \" ++ (show b)\n where x = read input :: Integer\n (a, b) = solve x\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}, {"source_code": "import Control.Monad\nimport Data.Foldable (traverse_)\n\nsolve :: Integer -> (Integer, Integer)\nsolve x = (1, x - 1)\n\nmain :: IO ()\nmain = do\n\ta <- getLine\n\ttests <- replicateM (read a) getLine\n\ttraverse_ (putAns . solve . read) tests\n\twhere putAns (x, y) = putStrLn (show x ++ \" \" ++ show y)\n"}, {"source_code": "import System.IO\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n getLine\n tc <- (map (solver . read) . lines) <$> getContents :: IO [[Int]]\n forM_ tc (putStrLn .unwords . map show)\n\nsolver i = [1,i-1]\n\n\n \n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: [Int] -> IO ()\nsolve [] = return ()\nsolve (x:xs) = putStrLn $ \"1 \" ++ show (x - 1)\n\nmain = do\n t <- readLn :: IO Int\n xs <- replicateM t readLn :: IO [Int]\n solve xs"}, {"source_code": "process :: Int -> (Int,Int)\nprocess 2 = (1,1)\nprocess x\n | odd x = (e,o)\n | otherwise = (2,x-2)\n where\n o = until odd ( `div` 2) (x-1)\n e = x `div` o\n\nreadInt :: String -> Int\nreadInt = read\n\nshowPair :: (Int,Int) -> String\nshowPair (a,b) = show a ++ \" \" ++ show b\n\nmain = do\n t <- fmap readInt getLine\n xs <- fmap (map readInt.words) getContents\n putStrLn . unlines $ map (showPair.process) xs"}], "src_uid": "2fa3e88688b92c27ad26a23884e26009"} {"source_code": "\nimport Monad (liftM)\nimport Prelude hiding (print, reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve ls ks = solve' ([], maxBound) $ (zip ls [1..])\n where\n solve' (acc, _) [] = reverse acc\n solve' (acc, min) ((l,num):ls)\n | m < min = solve' ([num], m) ls\n | m > min = solve' (acc, min) ls\n | otherwise = solve' (num:acc, min) ls\n where\n m = length $ filter (\\k -> k `mod` l == 0) ks\n \nprint :: Show a => [a] -> IO ()\nprint xs = putStrLn (show (length xs)) >> print' xs\n where\n print' [] = return ()\n print' [x] = putStrLn (show x)\n print' (x:xs) = putStr (show x ++ \" \") >> print' xs\n\nmain :: IO ()\nmain = do\n getLine\n ls <- reads\n ks <- reads\n print $ solve ls ks\n", "positive_code": [{"source_code": "main = interact solve\n\nsolve :: String -> String\nsolve s = unlines $ [show $ length y, unwords $ map show $ map fst y]\n where\n [info, fInfo, mInfo] = lines s\n frogs = map (\\x -> read x :: Int) $ words fInfo\n mos = map (\\x -> read x :: Int) $ words mInfo\n x = map (\\(i, l) -> (i, length $ filter (\\m -> m `mod` l == 0) mos)) $ zip [1..] frogs\n m = minimum $ map snd x\n y = filter (\\(i, c) -> c == m) x"}], "negative_code": [], "src_uid": "0701a595ee3a2b9edee53444b9dd1d51"} {"source_code": "import Data.List\nimport Data.Char\n\nmain = interact $ f\n\nf :: String -> String\nf = g . lines\n\ng :: [String] -> String\ng [a, b, c] =\n map (h aa bb) c\n where aa = a ++ map toUpper a\n bb = b ++ map toUpper b\n\nh :: String -> String -> Char -> Char\nh a b c =\n case elemIndex c a of\n Nothing -> c\n Just i -> b !! i", "positive_code": [{"source_code": "import Data.Char\nimport Data.List\n\nmatchCase :: Char -> Char -> Char\nmatchCase a b = if isUpper a then toUpper b else b\n\nconvertChar :: String -> String -> Char -> Char\nconvertChar keyboard1 keyboard2 c =\n\t case elemIndex (toLower c) keyboard1 of\n\t \t Nothing -> c\n\t\t Just ind -> matchCase c $ keyboard2 !! ind\n\nmain :: IO ()\nmain = do\n keyboard1 <- getLine\n keyboard2 <- getLine\n str <- getLine\n putStrLn $ map (convertChar keyboard1 keyboard2) str\n "}, {"source_code": "import Data.List\nimport Data.Char\n\nmain = interact $ f\n\nf :: String -> String\nf = g . lines\n\ng :: [String] -> String\ng [a, b, c] =\n map h c\n where aa = a ++ map toUpper a\n bb = b ++ map toUpper b\n zipped = zip aa bb\n \n h :: Char -> Char\n h c =\n case elemIndex c aa of\n Nothing -> c\n Just i -> bb !! i"}, {"source_code": "-- Packages installed: split text hashtables vector\n-- vector-algorithms parsec bytestring unordered-containers\n-- hashable scientific random async stm aeson\n-- Run using: runghc file.hs\nimport Control.Applicative\nimport qualified Data.Map as M\nimport Data.Char\n\nmain = do\n a <- getLine\n b <- getLine\n c <- getLine\n putStrLn $ solve2 a b c\n\nsolve2 :: String -> String -> String -> String\nsolve2 s s' = map f\n where\n f c = maybe c id $ M.lookup c mp\n mp = foldl g M.empty (zip s s')\n g mp (a, b) = M.insert (upper a) (upper b) (M.insert a b mp)\n \nupper a = chr (ord a - 32)\n"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASu\n\nimport Data.Char (toUpper)\n\nmain = putStrLn . solve . lines =<< getContents\n\nsolve [xs, ys, zs] = ans where\n go [] ws = ws\n go (u:us) ws = go us (trans u:ws)\n ans = reverse $ go zs []\n \n xxs = xs ++ map toUpper xs\n yys = ys ++ map toUpper ys\n \n trans c = p where\n (x1, x2) = span (/= c) xxs\n p = if x2 == [] then c\n else yys !! length x1\n \n "}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nf alph1 alph2 text = zipWith toSameCase (map (\\x-> (alph2++['0'..'9'])!!x) $ map fromJust [elemIndex i (alph1++['0'..'9'])|i<-map toLower text]) text\n\twhere\n\t\ttoSameCase x y\n\t\t\t|isUpper y=toUpper x\n\t\t\t|otherwise=toLower x\nmain=do\n\ta<-getLine\n\tb<-getLine\n\tc<-getLine\n\tputStrLn $ f a b c"}, {"source_code": "import qualified Data.Map as M\nimport qualified Data.Char as C\n\nmain :: IO ()\nmain =\n do\n a <- getLine\n b <- getLine\n ans <- getLine\n\n putStrLn $ map (\\x -> case M.lookup (C.toLower x) $ M.fromList $ zip a b of Just t -> if C.isUpper x then C.toUpper t else t ; otherwise -> x) $ ans\n"}, {"source_code": "import Data.Char\nimport Data.Maybe\nmain = interact $ solve . lines\nsolve [l1,l2,t] = mapMaybe (flip lookup lut) t where\n lut = zip l1 l2 ++\n zip (map toUpper l1) (map toUpper l2) ++\n zip ['0'..'9'] ['0'..'9']\n"}, {"source_code": "import Data.Map( fromList, (!))\nimport Data.Char( isUpper, isDigit, toUpper, toLower)\nmain = do\n from_ <- getLine\n to_ <- getLine\n toEnc_ <- getLine\n let\n\tmp = fromList $ zip from_ to_\n\n\tencode c = let\n\t\t\tc' = mp!(toLower c)\n\t\t in\n\t\t\tif isDigit c\n\t\t\t then c\n\t\t\t else if isUpper c\n\t\t\t\tthen toUpper c'\n\t\t\t\telse c'\n putStr $ map encode toEnc_\n"}, {"source_code": "import qualified Data.Map as Map \nimport Data.Char\nimport Data.Maybe\n\nmake_layout_map::String->String->Map.Map Char Char\nmake_layout_map s1 s2 = Map.fromList$zipWith (\\k v->(k, v)) s1 s2\n\nconvert_char::Map.Map Char Char->Char->Char\nconvert_char layout_map c \n |isLower c = fromJust$Map.lookup c layout_map \n |isUpper c = toUpper$fromJust$Map.lookup (toLower c) layout_map\n |otherwise = c\n\nconvert_string::Map.Map Char Char->String->String\nconvert_string layout_map s = map (convert_char layout_map) s\n\nsolution::[String]->String\nsolution [fst_layout, scn_layout, data_in] = \n convert_string (make_layout_map fst_layout scn_layout) data_in \n\nmain = interact$(solution.lines)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.Char\n\nmain = do\n f <- getLine\n s <- getLine\n t <- getLine\n putStr $ solve f s t\n\nsolve f s = map (\\c -> if isDigit c then c else (if isAsciiUpper c then toUpper else id) $ f2s!toLower c)\n where f2s = array ('a', 'z') $ zip f s :: UArray Char Char\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as M\nimport Data.Char\n\n\nmain = do\n\t\ta<-getLine\n\t\tb<-getLine\n\t\tc<-getLine\n\t\tlet ma = M.fromList $ zip (a++ (map toUpper a) ++ \"0123456789\") (b++ (map toUpper b) ++ \"0123456789\")\n\t\tputStrLn $ map (\\z-> fromJust (M.lookup z ma)) c \n\n"}, {"source_code": "import Data.Char\n\nmain = interact $ f\n\nf :: String -> String -- String is the collection of strings\nf = g . lines -- lines breaks a string up into a list of strings at newline characters.\n\ng :: [String] -> String -- [String] is the collection of lists of strings \ng [a, b, c] = map h c -- map :: (a -> b) -> [a] -> [b] -- (a->b) is first arg. [a] is second arg\n-- map f xs is the list obtained by applying f to each element of xs, i.e.,\n-- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]\n\n where \n upperA = map toUpper a -- a is a list of characters\n upperB = map toUpper b\n aA = a ++ upperA\n bB = b ++ upperB\n \n h :: Char -> Char\n h c = answer \n where zipped = zip aA bB \n \n checkTuple :: (Char,Char) -> Bool\n checkTuple (c1, _) = c == c1 \n \n v = filter checkTuple zipped\n --answer = snd (head (filter checkTuple zipped) ) -- head : [a,b] \\mapsto a\n \n answer = if length v == 0 then c\n else snd (head (filter checkTuple zipped) )"}, {"source_code": "import Data.Array (array, (!))\nimport Data.Char (isDigit, isLower, toUpper, toLower)\n\nprocess :: [Char] -> [Char] -> [Char] -> [Char]\nprocess l1 l2 = map f\n where\n a = array ('a', 'z') $ zip l1 l2\n f x\n | isDigit x = x\n | isLower x = a ! x\n | otherwise = toUpper (a ! (toLower x))\n\nmain :: IO ()\nmain = do\n l1 <- getLine\n l2 <- getLine\n s <- getLine\n putStrLn $ process l1 l2 s"}], "negative_code": [{"source_code": "import Data.Maybe\nmain = interact $ solve . lines\nsolve [l1,l2,t] = mapMaybe (flip lookup (zip l1 l2)) t\n"}, {"source_code": "import qualified Data.Map as Map \nimport Data.Char\nimport Data.Maybe\n\nmake_layout_map::String->String->Map.Map Char Char\nmake_layout_map s1 s2 = Map.fromList$zipWith (\\k v->(k, v)) s1 s2\n\nconvert_char::Map.Map Char Char->Char->Char\nconvert_char layout_map c \n |isLower c = fromJust$Map.lookup c layout_map \n |isUpper c = toUpper$fromJust$Map.lookup (toLower c) layout_map\n |otherwise = c\n\nconvert_string::Map.Map Char Char->String->String\nconvert_string layout_map s = map (convert_char layout_map) s\n\nsolution::[String]->String\nsolution [fst_layout, scn_layout, data_in] = \n convert_string (make_layout_map fst_layout scn_layout) data_in \n\nmain = interact$(show.solution.lines)"}], "src_uid": "d6f01ece3f251b7aac74bf3fd8231a80"} {"source_code": "\nmain = interact $ unwords . map show . sol . map read . words\n\nsol [n, m] = filter (<=m) . take (n*4) . concat . map (\\x -> [2*n+x, x]) $ [1..]\n\n", "positive_code": [{"source_code": "import Data.Array (array, (!))\n\nmain = do\n [n, m] <- fmap (map read . words) getLine\n\n let\n a = array (1,4*n) $ zip (concat [[4*i+1, 4*i+4] | i <- [0..n-1]] ++ concat [[4*i+2, 4*i+3] | i <- [0..n-1]]) [1..]\n b = concat [[4*i+2,4*i+1,4*i+3,4*i+4] | i <- [0..n-1]]\n r = filter (<= m) $ map (a !) b\n\n putStrLn $ unwords $ map show r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Array.ST\n-- import Data.Array.Unsafe\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n-- import Debug.Trace\n\nout = stdout\n\nmain = do\n (n,m) <- readInt2 <$> BS.getLine\n putAns out . makeTable $ solve n m \n\nsolve :: Int -> Int -> [Int]\nsolve n m = filter (<= m) . concat . transpose $ [col2,col1,col3,col4] where\n col1 = map pred col4\n col2 = map (+(2*n)) col1\n col3 = map (+(2*n)) col4\n col4 = map (*2) [1..n]\n\nmakeTable :: [Int] -> Table\nmakeTable xs = [ListR (map (\\x -> IntC x) xs)]\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)\n\n-- output functions\n\ndata Cell = ByteStringC BL.ByteString\n | IntC Int\n | Int64C Int64\n deriving( Eq, Ord, Show )\n\ndata Row = ListR [Cell]\n | SingleR Cell\n | TupleR (Cell,Cell)\n | TripleR (Cell,Cell,Cell)\n deriving( Eq, Ord, Show )\n\ntype Table = [Row]\n\ninfixr 4 <>\n(<>) :: Monoid m => m -> m -> m\n(<>) = mappend\n\nputAns :: Handle -> Table -> IO ()\nputAns o = hPutBuilder o . renderTable\n\nrenderTable :: Table -> Builder\nrenderTable rs = mconcat [renderRow r <> char8 '\\n' | r <- rs]\n\nrenderRow :: Row -> Builder\nrenderRow (ListR []) = mempty\nrenderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]\nrenderRow (SingleR x) = renderCell x\nrenderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y\nrenderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z\n\nrenderCell :: Cell -> Builder\nrenderCell (ByteStringC cs) = lazyByteString cs\nrenderCell (IntC i) = intDec i\nrenderCell (Int64C i) = int64Dec i\n"}], "negative_code": [], "src_uid": "0a701242ca81029a1791df74dc8ca59b"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IO\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\n\ndata Road = Road { roadTo, roadCost :: !Int } deriving Show;\n\nmain = do\n n <- read `liftM` getLine\n\n roadArray <- newArray (1,n) [] :: IO (IOArray Int [Road])\n replicateM_ n $ do\n [a, b, c] <- ( map read . words ) `liftM` getLine\n readArray roadArray a >>= writeArray roadArray a . ( Road b c : )\n readArray roadArray b >>= writeArray roadArray b . ( Road a 0 : )\n\n roadIArray <- freeze roadArray :: IO (Array Int [Road])\n --putStrLn $ show roadIArray\n\n let pathCost :: Int -> Int -> Int\n pathCost last_v v = if v == 1\n then 0\n else maybe 0 ( \\Road { roadTo=to, roadCost=cost } -> cost + pathCost v to ) ( find ( \\Road { roadTo=to } -> to /= last_v ) ( roadIArray ! v ) )\n\n routeCost = map ( \\Road { roadTo=to, roadCost=cost } -> cost + pathCost 1 to ) ( roadIArray ! 1 )\n\n putStrLn $ show $ minimum routeCost\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array (Array, (!), accumArray)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntype City = Int\ntype Cost = Int\ntype Map = Array City [(City, Cost)]\n\nsolve :: [[Int]] -> Int\nsolve roads = min way1 way2\n where\n n = length roads\n map :: Map\n map = accumArray (++) [] (1, n) $ concat\n [[(a, [(b, 0)]), (b, [(a, c)])] | [a, b, c] <- roads]\n [a, b, c] = head roads\n way1 = way 1 a b\n way2 = c + way 1 b a\n way i x y\n | i == n = 0\n | fst (head (map ! y)) /= x = snd (head (map ! y)) + way (i+1) y (fst (head (map ! y)))\n | otherwise = snd ((map ! y) !! 1) + way (i+1) y (fst ((map ! y) !! 1))\n\nmain :: IO ()\nmain = do\n n <- readLn\n roads <- replicateM n reads\n print $ solve roads"}, {"source_code": "data Road = Road { src :: Int \n , dst :: Int\n , cost :: Int\n } deriving (Eq)\n\nmain :: IO ()\nmain = interact func\n\nfunc :: String -> String\nfunc s = let ds = lines s\n n = head ds\n rs = tail ds\n in show (func' (read n) (map toRoad rs))\n \ntoRoad :: String -> Road\ntoRoad s = let ws = words s in Road { src = read $ ws!!0\n , dst = read $ ws!!1\n , cost = read $ ws!!2\n }\n\nfunc' :: Int -> [Road] -> Int\nfunc' _ rs = if costOne < costAnother\n then costOne\n else costAnother\n where oc = ocf ++ oct\n ocf = connectFrom 1 rs\n oct = connectTo 1 rs\n costOne = cycleCost 1 (oc!!0) rs\n costAnother = cycleCost 1 (oc!!1) rs\n \ncycleCost :: Int -> Road -> [Road] -> Int\ncycleCost pos road rs = if nextPos == 1\n then nowCost\n else nowCost + cycleCost nextPos nextRoad rs \n where nextRoad = head $ filter (\\r -> r /= road) $ connected pos rs\n (nextPos, nowCost) = if src nextRoad == pos\n then (dst nextRoad, 0)\n else (src nextRoad, cost nextRoad)\n\nconnected :: Int -> [Road] -> [Road]\nconnected n rs = connectFrom n rs ++ connectTo n rs\n\nconnectFrom :: Int -> [Road] -> [Road]\nconnectFrom n rs = filter (\\r -> src r == n) rs\n\nconnectTo :: Int -> [Road] -> [Road]\nconnectTo n rs = filter (\\r -> dst r == n) rs\n\n\n"}], "negative_code": [], "src_uid": "d85c7a8f7e6f5fc6dffed554bffef3ec"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Char (isDigit)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\n\n\n\nextract :: ByteString -> (ByteString, ByteString)\nextract s0 = go s0 [] [] False False\n where\n isOK c = c /= ';' && c /= ','\n go s xs ys last_empty has_empty\n | BS.null s = \n let ys' | last_empty = \"\":ys | otherwise = ys\n as = BS.intercalate \",\" (reverse xs)\n bs = BS.intercalate \",\" (reverse ys')\n as' | BS.null as = \"-\" | otherwise = surround '\"' as\n bs' | BS.null bs && not has_empty && not last_empty = \"-\" | otherwise = surround '\"' bs\n in (as', bs')\n | not (BS.null wd)\n && (BS.head wd /= '0' || BS.length wd == 1)\n && BS.all isDigit wd = go rest (wd:xs) ys last_empty' has_empty\n | otherwise = go rest xs (wd:ys) last_empty' (has_empty || BS.null wd)\n where\n (wd, rest') = BS.span isOK s\n last_empty' = rest' == \",\" || rest' == \";\"\n rest | BS.null rest' = rest'\n | otherwise = BS.tail rest'\n\n\nsurround :: Char -> ByteString -> ByteString\nsurround c bs = BS.cons c (BS.snoc bs c)\n\n\ndarnit :: ByteString -> ByteString\ndarnit s \n | BS.last s == '\\r' = BS.init s\n | otherwise = s\n\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n let (xs, ys) = extract (darnit s)\n BS.putStrLn xs\n BS.putStrLn ys\n", "positive_code": [{"source_code": "import Text.Printf\nimport Data.List\nimport Data.Char\n\nmain = do\n s <- getLine\n let (nums, other) = solve (splitWhen (\\c -> c == ',' || c == ';') s)\n printf \"%s\\n%s\\n\" (pad nums) (pad other)\n\npad :: [String] -> String\npad [] = \"-\"\npad xs = \"\\\"\" ++ (intercalate \",\" xs) ++ \"\\\"\"\n\nsolve :: [String] -> ([String], [String])\nsolve [] = ([], [])\nsolve (x:xs)\n | isNonNegativeNumber x = let (nums,rest) = solve xs in (x:nums, rest)\n | otherwise = let (nums,rest) = solve xs in (nums, x:rest)\n\nisNonNegativeNumber :: String -> Bool\nisNonNegativeNumber [] = False \nisNonNegativeNumber \"0\" = True\nisNonNegativeNumber s = let (lead,rest) = span (\\c -> c == '0') s\n (_,junk) = span isDigit rest\n in lead == [] && junk == []\n\nsplitWhen :: Eq a => (a -> Bool) -> [a] -> [[a]]\nsplitWhen _ [] = [[]]\nsplitWhen f xs = let (prefix,rest) = span (\\y -> not (f y)) xs in if rest /= [] then prefix:(splitWhen f (drop 1 rest)) else [prefix]"}, {"source_code": "import Data.List\nimport Data.List.Split\nimport Data.Char\n\nmain = do\n s <- getLine\n let\n l = splitOneOf \",;\" s\n a = filter check l\n b = filter (not . check) l\n check s = s == \"0\" || (not (null s) && head s /= '0' && all isDigit s)\n\n if null a then putStrLn \"-\" else print (intercalate \",\" a)\n if null b then putStrLn \"-\" else print (intercalate \",\" b)\n"}, {"source_code": "import Control.Arrow\nimport Data.Char\nimport Data.List\n\nmain = interact $ f . mySplit . filter (/= '\\n')\n\nmySplit [] = [[]]\nmySplit s = let (x, y) = span (\\c -> c /= ',' && c /= ';') s in if null y then [x] else x : mySplit (tail y)\n\t\nf ws = let (w1, w2) = partition (\\s -> if null s then False else s == \"0\" || (head s /= '0' && all isDigit s)) ws in (g w1) ++ \"\\n\" ++ (g w2)\ng w = if null w then \"-\" else (show . concat $ intersperse \",\" w)\n"}, {"source_code": "-- A. Exact Numbers\n\nimport Data.Char(isDigit)\nimport Data.List(intercalate)\n\nsplit :: String -> [String]\nsplit [] = [\"\"]\nsplit (',':t) = \"\" : split t\nsplit (';':t) = \"\" : split t\nsplit (h:t) = (h : (head . split) t) : (tail . split) t\n\nisInteger :: String -> Bool\nisInteger x = all isDigit x && (not . null) x && x == show (read x :: Integer)\n\nmyConcat :: [String] -> String\nmyConcat [] = \"-\"\nmyConcat x = '\\\"' : (intercalate \",\" x) ++ \"\\\"\"\n\nprocess :: String -> (String, String)\nprocess x = (myConcat (filter isInteger (split x)), myConcat (filter (not . isInteger) (split x)))\n\nmain :: IO()\nmain =\n do line <- getLine\n let (a, b) = process line\n putStrLn a\n putStrLn b\n return ()\n\n"}, {"source_code": "import Data.List\n\nmain = do\n s <- getLine\n let ns = split s\n (nums, other) = partition isNum ns\n putStrLn $ if null nums then \"-\" else show $ intercalate \",\" nums\n putStrLn $ if null other then \"-\" else show $ intercalate \",\" other\n\nsplit :: String -> [String]\nsplit\n = foldr (\\v (a : as) ->\n if v `elem` delim then [] : a : as else (v : a) : as) [[]]\n where delim = \",;\"\n\nisNum :: String -> Bool\nisNum []\n = False\nisNum \"0\"\n = True\nisNum (x : xs)\n = isDigit x && x /= '0' && all isDigit xs\n\nisDigit :: Char -> Bool\nisDigit c\n = '0' <= c && c <= '9'\n\nsol a b\n | a `mod` b == 0 = a `div` b\n | otherwise = a `div` b + sol b (a `mod` b)\n"}, {"source_code": "import Data.List\n\nmain = do\n s <- getLine\n let ns = split s\n (nums, other) = partition isNum ns\n putStrLn $ if null nums then \"-\" else show $ intercalate \",\" nums\n putStrLn $ if null other then \"-\" else show $ intercalate \",\" other\n where isNum []\n = False\n isNum \"0\"\n = True\n isNum (x : xs)\n = isDigit x && x /= '0' && all isDigit xs\n isDigit c\n = '0' <= c && c <= '9'\n\nsplit\n = foldr (\\v (a : as) ->\n if v `elem` delim then [] : a : as else (v : a) : as) [[]]\n where delim = \",;\"\n"}, {"source_code": "import Data.List\n\nmain = do\n\ts <- getLine >>= return.split\n\tputStrLn $ display $ filter isNumber s\n\tputStrLn $ display $ filter (not.isNumber) s\n\ndisplay [] = \"-\"\ndisplay x = \"\\\"\"++(concat $ intersperse \",\" x)++\"\\\"\" \n\nisNumber \"0\" = True\nisNumber x = isNumber' False x\n\nisNumber' ok [] = ok\nisNumber' ok (x:xs)\n\t| x=='0'\t\t\t= if ok then isNumber' ok xs else False\n\t| x`elem`['1'..'9'] = isNumber' True xs\n\t| otherwise \t\t= False\n\nsplit = split' \"\"\n\nsplit' :: String -> String -> [String]\nsplit' cur [] = [reverse cur]\nsplit' cur (x:xs)\n\t| x`elem`\";,\" = (reverse cur):(split' \"\" xs)\n\t| otherwise = split' (x:cur) xs"}, {"source_code": "import Data.List\n\nmain = do\n\ts <- getLine\n\tlet ss = sp \"\" s\n\tputStrLn $ display $ filter isNum ss\n\tputStrLn $ display $ filter (not.isNum) ss\n\ndisplay [] = \"-\"\ndisplay x = \"\\\"\" ++ (concat $ intersperse \",\" x) ++ \"\\\"\"\n\nisNum \"0\" = True\nisNum x\n\t|\tx==\"\"\t= False\n\t|\thead x=='0'\t=\tFalse\n\t|\totherwise = all (\\y -> y `elem` ['0'..'9']) x\n\nsp x [] = [reverse x]\nsp x (y:ys)\n\t| y==',' || y==';'\t= (reverse x) : (sp \"\" ys)\n\t| otherwise\t\t\t= sp (y:x) ys\n"}], "negative_code": [{"source_code": "import Text.Printf\nimport Data.List\nimport Data.Char\n\nmain = do\n s <- getLine\n let (nums, other) = solve (splitWhen (\\c -> c == ',' || c == ';') s)\n printf \"%s\\n%s\\n\" (pad nums) (pad other)\n\npad :: [String] -> String\npad [] = \"-\"\npad xs = \"\\\"\" ++ (intercalate \",\" xs) ++ \"\\\"\"\n\nsolve :: [String] -> ([String], [String])\nsolve [] = ([], [])\nsolve (x:xs)\n | isNonNegativeNumber x = let (nums,rest) = solve xs in (x:nums, rest)\n | otherwise = let (nums,rest) = solve xs in (nums, x:rest)\n\nisNonNegativeNumber :: String -> Bool\nisNonNegativeNumber [] = False \nisNonNegativeNumber \"0\" = True\nisNonNegativeNumber s = let (lead,rest) = span (\\c -> c == '0') s\n (_,junk) = span isDigit rest\n in lead == [] && junk == []\n\nsplitWhen :: Eq a => (a -> Bool) -> [a] -> [[a]]\nsplitWhen _ [] = []\nsplitWhen f xs = let (prefix,rest) = span (\\y -> not (f y)) xs in if rest /= [] then prefix:(splitWhen f (drop 1 rest)) else [prefix]"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Char (isDigit)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\n\n\n\nextract :: ByteString -> (ByteString, ByteString)\nextract s0 = (as', bs')\n where\n isOK c = c /= ';' && c /= ','\n (as, bs) = go s0 [] []\n as' | BS.null as = \"-\" | otherwise = surround '\"' as\n bs' | BS.null bs = \"-\" | otherwise = surround '\"' bs\n go s xs ys\n | BS.null s = (BS.intercalate \",\" (reverse xs), BS.intercalate \",\" (reverse ys))\n | not (BS.null wd)\n && (BS.head wd /= '0' || BS.length wd == 1)\n && BS.all isDigit wd = go rest (wd:xs) ys\n | otherwise = go rest xs (wd:ys)\n where\n (wd, rest') = BS.span isOK s\n rest | BS.null rest' = rest' | otherwise = BS.tail rest'\n\nsurround :: Char -> ByteString -> ByteString\nsurround c bs = BS.cons c (BS.snoc bs c)\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n let (xs, ys) = extract s\n BS.putStrLn xs\n BS.putStrLn ys\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Char (isDigit)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\n\n\n\nextract :: ByteString -> (ByteString, ByteString)\nextract s0 = go s0 [] [] False\n where\n isOK c = c /= ';' && c /= ','\n go s xs ys last_empty\n | BS.null s = \n let ys' | last_empty = \"\":ys | otherwise = ys\n as = BS.intercalate \",\" (reverse xs)\n bs = BS.intercalate \",\" (reverse ys')\n as' | BS.null as = \"-\" | otherwise = surround '\"' as\n bs' | BS.null bs && not last_empty = \"-\" | otherwise = surround '\"' bs\n in (as', bs')\n | not (BS.null wd)\n && (BS.head wd /= '0' || BS.length wd == 1)\n && BS.all isDigit wd = go rest (wd:xs) ys last_empty'\n | otherwise = go rest xs (wd:ys) last_empty'\n where\n (wd, rest') = BS.span isOK s\n last_empty' = rest' == \",\" || rest' == \";\"\n rest | BS.null rest' = rest'\n | otherwise = BS.tail rest'\n\n\nsurround :: Char -> ByteString -> ByteString\nsurround c bs = BS.cons c (BS.snoc bs c)\n\n\ndarnit :: ByteString -> ByteString\ndarnit s \n | BS.last s == '\\r' = BS.init s\n | otherwise = s\n\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n let (xs, ys) = extract (darnit s)\n BS.putStrLn xs\n BS.putStrLn ys\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Char (isDigit)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\n\n\n\nextract :: ByteString -> (ByteString, ByteString)\nextract s0 = go s0 [] [] False False\n where\n isOK c = c /= ';' && c /= ','\n go s xs ys last_empty has_empty\n | BS.null s = \n let ys' | last_empty = \"\":ys | otherwise = ys\n as = BS.intercalate \",\" (reverse xs)\n bs = BS.intercalate \",\" (reverse ys')\n as' | BS.null as = \"-\" | otherwise = surround '\"' as\n bs' | BS.null bs && not has_empty = \"-\" | otherwise = surround '\"' bs\n in (as', bs')\n | not (BS.null wd)\n && (BS.head wd /= '0' || BS.length wd == 1)\n && BS.all isDigit wd = go rest (wd:xs) ys last_empty' has_empty\n | otherwise = go rest xs (wd:ys) last_empty' (has_empty || BS.null wd)\n where\n (wd, rest') = BS.span isOK s\n last_empty' = rest' == \",\" || rest' == \";\"\n rest | BS.null rest' = rest'\n | otherwise = BS.tail rest'\n\n\nsurround :: Char -> ByteString -> ByteString\nsurround c bs = BS.cons c (BS.snoc bs c)\n\n\ndarnit :: ByteString -> ByteString\ndarnit s \n | BS.last s == '\\r' = BS.init s\n | otherwise = s\n\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n let (xs, ys) = extract (darnit s)\n BS.putStrLn xs\n BS.putStrLn ys\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Char (isDigit)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\n\n\n\nextract :: ByteString -> (ByteString, ByteString)\nextract s0 = (as', bs')\n where\n isOK c = c /= ';' && c /= ','\n (as, bs) = go s0 [] [] False\n as' | BS.null as = \"-\" | otherwise = surround '\"' as\n bs' | BS.null bs = \"-\" | otherwise = surround '\"' bs\n go s xs ys last_empty\n | BS.null s && last_empty = fmap (`BS.snoc` ',') (go \"\" xs ys False)\n | BS.null s = (BS.intercalate \",\" (reverse xs), BS.intercalate \",\" (reverse ys))\n | not (BS.null wd)\n && (BS.head wd /= '0' || BS.length wd == 1)\n && BS.all isDigit wd = go rest (wd:xs) ys last_empty'\n | otherwise = go rest xs (wd:ys) last_empty'\n where\n (wd, rest') = BS.span isOK s\n last_empty' = rest' == \",\" || rest' == \";\"\n rest | BS.null rest' = rest'\n | otherwise = BS.tail rest'\n\n\nsurround :: Char -> ByteString -> ByteString\nsurround c bs = BS.cons c (BS.snoc bs c)\n\n\ndarnit :: ByteString -> ByteString\ndarnit s \n | BS.last s == '\\r' = BS.init s\n | otherwise = s\n\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n let (xs, ys) = extract (darnit s)\n BS.putStrLn xs\n BS.putStrLn ys\n"}, {"source_code": "import Data.List\n\nmain = do\n\ts <- getLine >>= return.split\n\tputStrLn $ display $ filter isNumber s\n\tputStrLn $ display $ filter (not.isNumber) s\n\ndisplay [] = \"-\"\ndisplay x = \"\\\"\"++(concat $ intersperse \",\" x)++\"\\\"\" \n\nisNumber \"0\" = True\nisNumber x = isNumber' False x\n\nisNumber' ok [] = ok\nisNumber' ok (x:xs)\n\t| x=='0'\t\t\t= if ok then isNumber' ok xs else False\n\t| x`elem`['1'..'9'] = isNumber' True xs\n\t| otherwise \t\t= False\n\nsplit = split' \"\"\n\nsplit' :: String -> String -> [String]\nsplit' cur [] = [cur]\nsplit' cur (x:xs)\n\t| x`elem`\";,\" = (reverse cur):(split' \"\" xs)\n\t| otherwise = split' (x:cur) xs"}, {"source_code": "main = do\n\ts <- getLine\n\tlet f = gg [] s \"\"\n\tlet a = gi [] [] f\n\tif head a == []\n\tthen\n\t\tputStrLn \"-\"\n\telse \n\t\tputStrLn $ ['\"'] ++ (foldl (\\x y -> x ++ [','] ++ y) (head $ head $ a) (tail $ head $ a)) ++ ['\"']\n\tif last\ta == []\n\tthen\n\t\tputStrLn \"-\"\n\telse \n\t\tputStrLn $ ['\"'] ++ (foldl (\\x y -> x ++ [','] ++ y) (head $ last $ a) (tail $ last $ a) )++ ['\"']\n\ngi x z [] = [x,z]\ngi x z (y:ys)\n\t| y == \"\" = gi x (z++[y]) ys\n\t| head y == '0' && y/=\"0\" = gi x (z++[y]) ys\n\t| all (\\x -> x `elem` ['0','1','2','3','4','5','6','7','8','9']) y == True = gi (x ++ [y]) z ys\n\t| otherwise = gi x (z++[y]) ys\n\ngg x [] z \n\t|\tz==[]\t=\tx\n\t|\totherwise = x ++ [z]\ngg x (y:ys)\tz\n\t|\ty==',' || y==';'\t= gg (x ++ [z]) ys []\n\t|\totherwise\t\t\t= gg x ys (z++[y])\n"}, {"source_code": "main = do\n\ts <- getLine\n\tlet f = gg [] s \"\"\n\tlet a = gi [] [] f\n\tif head a == []\n\tthen\n\t\tputStrLn \"\\45\"\n\telse \n\t\tputStrLn $ ['\"'] ++ (foldl (\\x y -> x ++ [','] ++ y) (head $ head $ a) (tail $ head $ a)) ++ ['\"']\n\tif last\ta == []\n\tthen\n\t\tputStrLn \"\\45\"\n\telse \n\t\tputStrLn $ ['\"'] ++ (foldl (\\x y -> x ++ [','] ++ y) (head $ last $ a) (tail $ last $ a) )++ ['\"']\n\ngi x z [] = [x,z]\ngi x z (y:ys)\n\t| y == \"\" = gi x (z++[y]) ys\n\t| head y == '0' && y/=\"0\" = gi x (z++[y]) ys\n\t| all (\\x -> x `elem` ['0','1','2','3','4','5','6','7','8','9']) y == True = gi (x ++ [y]) z ys\n\t| otherwise = gi x (z++[y]) ys\n\ngg x [] z \n\t|\tz==[]\t=\tx\n\t|\totherwise = x ++ [z]\ngg x (y:ys)\tz\n\t|\ty==',' || y==';'\t= gg (x ++ [z]) ys []\n\t|\totherwise\t\t\t= gg x ys (z++[y])\n"}], "src_uid": "ad02cead427d0765eb642203d13d3b99"} {"source_code": "module Main where\n\nimport Control.Monad\n\ngenerator :: Int -> String\ngenerator n | n <= 1 = \"-1\"\n | n `mod` 3 == 1 = (take m $ repeat '9') ++ \"8\"\n | otherwise = (take m $ repeat '8') ++ \"3\"\n where m = n - 1\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nmain :: IO ()\nmain = do\n n <- readInt\n s <- replicateM n $ readInt\n let s' = generator <$> s\n forM_ s' putStrLn\n", "positive_code": [{"source_code": "f :: Int -> String\nf 1 = \"-1\"\nf n =\n let a = replicate (n - 1) 5 ++ [3]\n b = replicate (n - 2) 5 ++ [3, 3]\n in if sum a `mod` 3 /= 0 then concatMap show a else concatMap show b\n\nmain = interact $ unlines . map (f . read) . tail . lines\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n n <- read <$> getLine\n if n == 1\n then print $ -1\n else putStrLn $ replicate (n - 1) '5' ++ \"8\"\n test (i - 1)\n\n"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain = readLn >>= flip replicateM_ (readLn >>= print . f)\n\nf :: Int -> Integer\nf 1 = -1\nf n = read $ \"2\" ++ replicate (n-1) '7'"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- readLn\n inputs <- replicateM numTests readLn\n mapM_ (putStrLn . ans) inputs\n\nans :: Int -> String\nans 1 = \"-1\"\nans n = '2' : (replicate (n - 1) '3')\n"}], "negative_code": [], "src_uid": "43996d7e052aa628a46d03086f9c5436"} {"source_code": "module Main\nwhere\n\nimport Data.List (words, all, intercalate)\n\nmain :: IO ()\nmain = intercalate \"\\n\" <$> map yesNo <$> map feasible <$> (read <$> getLine >>= readNCordFields) >>= putStrLn\n\ndata Square = E | R deriving (Show, Read, Eq)\ntype Field = [[Square]]\n\n {- stdin section -}\n {- all functions trust on stdin validity -}\n\nreadNCordFields :: Int -> IO [Field]\nreadNCordFields n = sequence $ replicate n readOneCordField\n\nreadOneCordField :: IO Field\nreadOneCordField = readField <$> (fst <$> readCord <$> getLine >>= readNLines)\n\nreadNLines :: Int -> IO [String]\nreadNLines n = sequence $ replicate n getLine\n\nreadCord :: String -> (Int, Int)\nreadCord str = toPair $ map (read) $ words str\n\nreadField :: [String] -> Field\nreadField [] = []\nreadField (x:xs) = (readln x):(readField xs)\n where readln :: [] Char -> [] Square\n readln str = (read . singleton) <$> str\n\n\n {- Parsing field section -}\n\n-- constrain: must be >= 1 robot on the field\nfeasible :: Field -> Bool\nfeasible f\n | topLeftR f = True\n | topE f = feasible (noTop f)\n | leftmostE f = feasible (noLeftmost f)\n | otherwise = False\n\nnoLeftmost :: Field -> Field\nnoLeftmost f = (drop 1) <$> f\n\nleftmostE :: Field -> Bool\nleftmostE f = all (\\ln -> ln !! 0 == E) f\n\nnoTop :: Field -> Field\nnoTop f = drop 1 f\n\ntopE :: Field -> Bool\ntopE f = all (== E) $ f !! 0\n\ntopLeftR :: Field -> Bool\ntopLeftR f = f !! 0 !! 0 == R\n\n {- Output fmt section -}\n\nyesNo :: Bool -> String\nyesNo True = \"YES\"\nyesNo False = \"NO\"\n\n {- util functions section -}\n\ntoPair :: [a] -> (a, a)\ntoPair [x, y] = (x, y)\ntoPair _ = undefined\n\nsingleton :: a -> [a]\nsingleton a = [a]\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int -> UA.UArray (Int, Int) Char -> Bool\nsolve n m arr = (arr UA.! (minI, minJ)) == 'R'\n where\n rIndexes = L.map fst . L.filter (\\(i, e) -> e == 'R') $ UA.assocs arr\n (minI, minJ) = foldr (\\(minI, minJ) (i, j) -> (min i minI, min j minJ)) (n - 1, m - 1) rIndexes\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, m] <- B8.getLine <&> readIntB8s\n arr <- MA.newArray ((0, 0), (n - 1, m - 1)) '_' :: IO (IOA.IOArray (Int, Int) Char)\n forM_ [0 .. n - 1] $ \\i -> do\n line <- B8.getLine <&> B8.filter (\\c -> c `L.elem` ['R', 'E'])\n forM_ [0 .. m - 1] $ \\j -> do\n MA.writeArray arr (i, j) (line `B8.index` j)\n farr <- MA.freeze arr\n\n let answer = solve n m farr\n putsYesNo answer\n\n"}, {"source_code": "indexOf :: Char -> [Char] -> Int\r\nindexOf k a = search 0 k a\r\n where\r\n search _ _ [] = (-1)\r\n search i k (x : xs)\r\n | (k == x) = i\r\n | otherwise = search (i + 1) k xs\r\n\r\nreadLine = do\r\n input <- getLine\r\n return input\r\n\r\nans = do\r\n nmInput <- getLine\r\n let (n : m : []) = [read x :: Int | x <- words nmInput]\r\n grid <- sequence (replicate n readLine)\r\n let pos = [indexOf 'R' line | line <- grid]\r\n let (first : rest) = [x | x <- pos, x > (-1)]\r\n let beforeFirst = [x | x <- rest, x < first]\r\n let result = if (length beforeFirst > 0) then \"NO\" else \"YES\"\r\n return result\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (unwords results)"}], "negative_code": [], "src_uid": "96b6a96ded46bddb78b118d6d3a9d049"} {"source_code": "readInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nsol :: [Int] -> [Char]\nsol xx | odd $ sum xx = \"YES\"\n | any (odd) xx && any (even) xx = \"YES\"\n | otherwise = \"NO\"\n\nloop :: Int -> IO ()\nloop 0 = return ()\nloop n = do\n i_dont_care <- getLine\n inputs <- readInts\n putStrLn $ sol inputs\n loop $ n - 1\n\n\nmain = do\n input1 <- getLine\n let t = (read input1 :: Int)\n loop t\n\n", "positive_code": [{"source_code": "import Control.Monad\n\ngetInts = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n a <- getInts\n if all even a || (even n && all odd a)\n then putStrLn \"NO\"\n else putStrLn \"YES\""}, {"source_code": "import qualified Data.List as L\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsolve :: [Int] -> Bool\nsolve xs\n | odd $ sum xs = True\n | otherwise = not $ null e || null o\n where\n (e, o) = L.partition even xs \n\nsolvetc :: Int -> IO ()\nsolvetc 0 = do return ()\n\nsolvetc t = do\n n <- getLine\n xs <- getLine\n let ans = solve . map read . words $ xs\n putStrLn $ id (if ans == True then \"YES\" else \"NO\")\n solvetc(t - 1)\n\nmain = do\n t <- getLine\n solvetc (read t)\n \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess a c d | odd a && c==a = \"YES\"\n\t | c==a || d==a = \"NO\"\n\t | otherwise = \"YES\"\n\t\n\nonecase = do\n\t\tn<- read <$> getLine::IO Int\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet c = length $ filter odd a\n\t\tlet d= length $ filter even a\n\t\tputStrLn $ process n c d \n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "process:: [Int] -> String\nprocess xs\n | all even xs = \"NO\"\n | all odd (length xs+1:xs) = \"NO\"\n | otherwise = \"YES\"\n\nreadInt :: String -> Int\nreadInt = read\n\nreadCases :: [String] -> [[Int]]\nreadCases (n:a:xs) = map readInt (words a):readCases xs\nreadCases _ = []\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n as <- fmap (readCases . lines) getContents\n putStrLn . unlines $ map process as"}, {"source_code": "readInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nsol :: [Int] -> [Char]\nsol xx | odd len && any (odd) xx = \"YES\"\n | even len && any (odd) xx && any (even) xx = \"YES\"\n | otherwise = \"NO\"\n where len = length xx\n\nloop 0 = return ()\nloop n = do\n i_dont_care <- getLine\n inputs <- readInts\n putStrLn $ sol inputs\n loop $ n - 1\n\n\nmain = do\n input1 <- getLine\n let t = (read input1 :: Int)\n loop t\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\t\nonecase = do\n\t\tgetLine\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet c = take 1 $ filter odd a\n\t\tputStrLn $ if length c==1 then \"YES\" else \"NO\"\t\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\t\nonecase = do\n\t\tn<- read <$> getLine::IO Int\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet c = length $ filter odd a\n\t\tlet d= length $ filter even a\n\t\tputStrLn $ if (c==n || d==n) then \"NO\" else \"YES\"\t\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "readInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nsol :: [Int] -> [Char]\nsol xx | odd len && any (odd) xx = \"YES\"\n | even len && any (odd) xx && any (even) xx = \"YES\"\n | otherwise = \"NO\"\n where len = length xx\n\n\nmain = do\n inputs <- readInts\n putStrLn $ sol inputs\n"}], "src_uid": "2e8f7f611ba8d417fb7d12fda22c908b"} {"source_code": "data Operation = L Int | R Int\ninstance Show Operation where\n show (L n) = \"L \"++(show n)\n show (R n) = \"R \"++(show n)\n\nsolve :: String -> [Operation]\nsolve string = [R (l-2), L (l-1), (L 2)]\n where l = length string\n\nshowSolution :: [Operation] -> [String]\nshowSolution op = (show $ length op):(map (show) op)\n\nmain :: IO()\nmain = do\n interact $ unlines . showSolution . solve\n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n s <- getLine\n let\n n = length s\n putStrLn \"3\"\n putStrLn \"L 2\"\n putStrLn \"R 2\"\n putStr \"R \"\n print $ 2 * n - 1\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ lines >>> head >>> process >>> unlines\n\nprocess :: String -> [String]\nprocess xs = show (length ys) : map pr ys\n where\n ys = solve xs\n pr (o, i) = o : \" \" ++ show i\n\nsolve :: String -> [(Char, Int)]\nsolve xs = [('R', n - 1), ('R', n - 1), ('L', n + 2), ('L', 2)]\n where\n n = length xs\n"}], "negative_code": [{"source_code": "data Operation = L Int | R Int\ninstance Show Operation where\n show (L n) = \"L \"++(show n)\n show (R n) = \"R \"++(show n)\n\nsolve :: String -> [Operation]\nsolve string = [R (l-1), L (l-1), (R 2)]\n where l = length string\n\nshowSolution :: [Operation] -> [String]\nshowSolution op = (show $ length op):(map (show) op)\n\nmain :: IO()\nmain = do\n interact $ unlines . showSolution . solve\n"}, {"source_code": "data Operation = L Int | R Int\ninstance Show Operation where\n show (L n) = \"L \"++(show n)\n show (R n) = \"R \"++(show n)\n\nsolve :: String -> [Operation]\nsolve string = [R (l-1), L (l-1), (R 2)]\n where l = length string\n\nmain :: IO()\nmain = do\n interact $ unlines . map (show) . solve\n"}, {"source_code": "data Operation = L Int | R Int\ninstance Show Operation where\n show (L n) = \"L \"++(show n)\n show (R n) = \"R \"++(show n)\n\nsolve :: String -> [Operation]\nsolve string = [R (l-1), L (l-2), (L 2)]\n where l = length string\n\nshowSolution :: [Operation] -> [String]\nshowSolution op = (show $ length op):(map (show) op)\n\nmain :: IO()\nmain = do\n interact $ unlines . showSolution . solve\n"}], "src_uid": "6ca35987757bf64860eb08f98a9e6d90"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = (Int, Int)\ntype Output = Int\n\ninput :: Scanner Input\ninput = pair int int\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: Input -> Output\nsolve (l, r)\n | l <= (r `div` 2) + 1 = (r - 1) `div` 2\n | otherwise = r - l\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import Control.Monad\n\ncalc l r | l <= (r `div` 2 + 1) =\n (r-1) `div` 2\n\ncalc l r | otherwise = r-l\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b] = map read $ words line :: [Int]\n print $ calc a b\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: Int -> Int -> Int\r\nsolve l r = if a >= l\r\n then a - 1\r\n else r - l\r\n where a = (r + 1) `div` 2\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n (l:r:_) <- fmap (map (read :: String -> Int) . words) getLine\r\n let ans = solve l r\r\n putStrLn $ show ans\r\n"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = (Int, Int)\r\ntype OutType = Int\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nsolve :: InType -> OutType\r\nsolve (l, r) = if l' >= l\r\n then l' - 1\r\n else r - l\r\n where l' = (r + 1) `div` 2\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = case toArr s of\r\n [l, r] -> (l, r)\r\n _ -> error \"unexpected input\"\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines\r\n\r\n"}], "negative_code": [], "src_uid": "c34db7897f051b0de2f49f2696c6ee2f"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsumPoints ::[Integer] -> Integer -> Integer -> Integer -> Integer -> Integer\nsumPoints [] _ _ _ acc = acc\nsumPoints (x:xs) sum sqsum i acc = let newval = ((i-1) * (x*x) - (2*x*sum) + sqsum) in\n sumPoints xs (sum+x) (sqsum + (x*x)) (i+1) (acc+newval)\n\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n,r1) = readInt all\n let Just ((xs,ys),_) = readTuples n r1\n let result = (sumPoints xs 0 0 1 0)+(sumPoints ys 0 0 1 0)\n putStrLn $ show result ++ \"\\n\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readTuples 0 s = do return (([],[]),s)\n readTuples n s = do (x, r) <- readInteger s\n (y, z) <- readInteger r\n ((l1,l2),t) <- readTuples (n-1) z\n return (((x : l1),(y : l2)),t)\n\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport IO\n\ngetLines :: IO [[Integer]]\ngetLines = do\n\tfmap C.lines (C.hGetContents stdin) >>= return . map (map (fst . fromJust . C.readInteger) . C.words)\n\nsxx = sum . map ((^2) . head)\nsyy = sum . map ((^2) . last)\nsx = sum . map head\nsy = sum . map last\n\nmain = do\n\tn <- getLine >>= return . read :: IO Integer\n\txys <- getLines\n\tputStrLn . show $ n * ((sxx xys) + (syy xys)) - (sx xys) ^ 2 - (sy xys) ^ 2\n"}, {"source_code": "\nimport Char (ord)\nimport Control.Monad (liftM)\n\nsolve :: Integer -> [(Int, Int)] -> Integer\nsolve n ps = solve' ps 0 0 0 0 \n where\n solve' :: [(Int, Int)] -> Integer -> Integer -> Integer -> Integer -> Integer\n solve' [] _ _ acc1 acc2 = (n-1) * acc1 - 2 * acc2\n solve' ((x,y) : ps) sX sY acc1 acc2 = solve' ps sX' sY' acc1' acc2'\n where\n x' = fromIntegral x\n y' = fromIntegral y\n sX' = sX + x'\n sY' = sY + y'\n acc1' = acc1 + x' * x' + y' * y'\n acc2' = acc2 + sX * x' + sY * y'\n\nreadPoint :: String -> (Int, Int)\nreadPoint line = readPoint' line 1 0\n where \n readPoint' (' ':s) z a = readPoint'' s (z * a) 1 0\n readPoint' ('-':s) _ _ = readPoint' s (-1) 0\n readPoint' (c:s) z a = readPoint' s z (10*a + (ord c - ord '0'))\n readPoint'' [] a z b = (a, z * b)\n readPoint'' ('-':s) a _ _ = readPoint'' s a (-1) 0\n readPoint'' (c:s) a z b = readPoint'' s a z (10*b + (ord c - ord '0'))\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines getContents\n let n = read $ head lines'\n let points = map readPoint $ take (fromIntegral n) $ tail lines'\n print $ solve n points\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\n-- solution for: http://codeforces.com/problemset/problem/76/E\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncompute :: [Integer]->Integer->Integer->Integer->Integer->Integer\ncompute [] _ _ _ acc = acc\ncompute (x:xs) i s ss acc = compute xs (i + 1) (s + x) (ss + x*x) (acc + (i-1)*x*x - 2*x*s + ss)\n\nsolve :: [Integer]->[Integer]->Integer\nsolve x y = (compute x 1 0 0 0) + (compute y 1 0 0 0)\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let (x, y) = readMany readInteger r1 [] []\n print (solve x y)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (t, r) -> readMany readf r ys (t:xs)\n Nothing -> (xs, ys)\n"}, {"source_code": "import Data.Char\n\nimport Control.Monad\nimport Data.Int(Int64)\nimport Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nmkPt [a, b] = Pt a b\n\ndata Pt = Pt !Int64 !Int64\n\naddPt (Pt x1 y1) (Pt x2 y2) = Pt (x1+x2) (y1+y2)\nsumPt = foldl' addPt (Pt 0 0)\n\nsqPt (Pt x y) = x*x+y*y\n\nints :: IO [Int]\nints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nint64s :: IO [Int64]\nint64s = map (fromInteger . toInteger) <$> ints\n\ndata State = State !Pt !Int64\n\ngogogo :: Int -> IO State\ngogogo n = gogo n (State (Pt 0 0) 0)\n\ngogo :: Int -> State -> IO State\ngogo 0 state = return $ state\ngogo i (State sum sumSq) = do\n pt <- mkPt <$> int64s\n (gogo $! (i-1)) $! (State (addPt sum pt) (sumSq + sqPt pt))\n\nmain = do\n [n] <- ints\n (State sum sumSq) <- gogogo n\n-- input <- map mkPt <$> replicateM n int64s\n-- let sumSq = sum (map sqPt input)\n-- let sum = sumPt input\n let res = ((fromInteger $ toInteger $ n) * sumSq - sqPt sum)\n putStrLn $ unlines [show $ res]\n\ninputGen = do\n putStrLn \"100000\" \n forM_ [1..100000] $ \\i -> putStrLn \"10000 10000\"\n \n\n -- with readInt:\n -- \n -- !Int64 = 385ms\n -- !Integer = 414\n -- Int64 = 427ms\n -- Integer = 669ms\n\n -- with read:\n --\n -- !Int64 = 1570\n -- !Integer = 1564\n -- Int64 = 1599\n -- Integer = 3821\n "}, {"source_code": "import Data.Char\n\nimport Control.Monad(forM_)\nimport Data.Int(Int64)\nimport Data.List\n\nmkPt [a, b] = Pt a b\n\nreadPt = mkPt . map readInt . words\n\nreadInt = fromInteger . toInteger . readIntRec 0\nreadIntRec :: Int -> String -> Int\nreadIntRec val \"\" = val\nreadIntRec val ('-': str) = negate $ readIntRec val str\nreadIntRec val (ch : str) = readIntRec (val*10 + (ord ch - ord '0')) str\n\ndata Pt = Pt !Int64 !Int64\n\naddPt (Pt x1 y1) (Pt x2 y2) = Pt (x1+x2) (y1+y2)\nsumPt = foldl' addPt (Pt 0 0)\n\nsqPt (Pt x y) = x*x+y*y\n\ninteractor :: String -> String\ninteractor str = let (hl : ol) = lines str\n n = read hl\n input = map readPt $ ol\n result = unlines [show $ (n * sum (map sqPt input) - sqPt (sumPt input))]\n in result\n\nmain = interact interactor\n\ninputGen = do\n putStrLn \"100000\"\n forM_ [1..100000] $ \\i -> putStrLn \"10000 10000\"\n "}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsumPoints ::[Integer] -> Integer -> Integer -> Integer -> Integer -> Integer\nsumPoints [] _ _ _ acc = acc\nsumPoints (x:xs) sum sqsum i acc = let newval = ((i-1) * (x*x) - (2*x*sum) + sqsum) in\n sumPoints xs (sum+x) (sqsum + (x*x)) (i+1) (acc+newval)\n\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n,r1) = readInt all\n let Just ((xs,ys),_) = readTuples n r1\n let result = (sumPoints xs 0 0 1 0)+(sumPoints ys 0 0 1 0)\n putStrLn $ show result ++ \"\\n\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readTuples 0 s = do return (([],[]),s)\n readTuples n s = do (x, r) <- readInt s\n (y, z) <- readInt r\n ((l1,l2),t) <- readTuples (n-1) z\n return ((((toInteger x) : l1),((toInteger y) : l2)),t)\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\n-- solution for: http://codeforces.com/problemset/problem/76/E\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ncompute :: [Integer]->Integer->Integer->Integer->Integer->Integer\ncompute [] _ _ _ acc = acc\ncompute (x:xs) i s ss acc = compute xs (i + 1) (s + x) (ss + x*x) (acc + (i-1)*x*x - 2*x*s + ss)\n\nsolve :: [Integer]->[Integer]->Integer\nsolve x y = (compute x 1 0 0 0) + (compute y 1 0 0 0)\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let (x, y) = readMany readInteger r1 [] []\n print (solve x y)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (t, r) -> readMany readf r ys (t:xs)\n Nothing -> (xs, ys)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\ncompute :: [Integer] -> Integer -> Integer -> Integer -> Integer ->Integer\ncompute [] _ acc suma sumasq = acc\ncompute (x:xs) i acc suma sumasq = if i == 1 then compute xs (i+1) acc x (x*x) else compute xs (i+1) (acc+(i-1)*x*x - 2*x*(suma) + sumasq) (suma+x) (sumasq+x*x) \n\n\nmain :: IO ()\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let (xs, ys) = getPoints n r1 ([],[])\n print ((compute xs 1 0 0 0 ) + (compute ys 1 0 0 0))\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (x, r) <- readInteger s\n (l, t) <- readIntList (n-1) r\n return (x : l, t)\n getPoints 0 _ (accx, accy) = (accx, accy)\n getPoints n s (accx, accy) =\n let Just (pt, r2) = readIntList 2 s\n in getPoints (n-1) r2 (((head pt):accx), ((last pt):accy))\n\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport IO\n\nreadInt = fst . fromJust . C.readInteger\n\nmain = do\n\t(h:t) <- fmap C.lines $ C.hGetContents stdin\n\tlet\n\t\tn = readInt h\n\t\ta = map (map readInt . C.words) t\n\tprint $ let x = map head a; y = map last a in gao n x + gao n y\n\ngao n x = toInteger n * sum (map (^2) x) - (sum x) ^ 2\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\n-- compute [] _ acc inp = acc\n-- compute (x:xs) i acc inp = compute xs (i+1) (acc+(i - 1)*x*x - 2*x*(suma inp (i-1) 0) + (sumasq inp (i-1) 0)) (inp)\n\n-- compute :: [Integer] -> Integer -> Integer -> [Integer] -> Integer\n-- compute [] _ acc inp = acc\n-- compute (x:xs) i acc inp = compute xs (i+1) (acc+(i - 1)*x*x - 2*x*(suma inp (i-1) 0) + (sumasq inp (i-1) 0)) (inp)\ncompute :: [Integer] -> Integer -> Integer -> Integer -> Integer ->Integer\ncompute [] _ acc suma sumasq = acc\ncompute (x:xs) i acc suma sumasq = if i == 1 then compute xs (i+1) acc x (x*x) else compute xs (i+1) (acc+(i-1)*x*x - 2*x*(suma) + sumasq) (suma+x) (sumasq+x*x) \n\n-- suma :: [Integer] -> Integer -> Integer -> Integer\n-- suma x 0 acc = acc\n-- suma (x:xs) n acc = suma xs (n-1) (acc+x)\n\n-- sumasq :: [Integer] -> Integer -> Integer -> Integer\n-- sumasq x 0 acc = acc\n-- sumasq (x:xs) n acc = sumasq xs (n-1) (acc+x*x)\n\n\nmain :: IO ()\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let (xs, ys) = getPoints n r1 ([],[])\n print ((compute xs 1 0 0 0 ) + (compute ys 1 0 0 0))\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (x, r) <- readInteger s\n (l, t) <- readIntList (n-1) r\n return (x : l, t)\n getPoints 0 _ (accx, accy) = (accx, accy)\n getPoints n s (accx, accy) =\n let Just (pt, r2) = readIntList 2 s\n in getPoints (n-1) r2 (((head pt):accx), ((last pt):accy))\n"}], "negative_code": [{"source_code": "import Data.Char\n\nimport Control.Monad(forM_)\nimport Data.Int(Int64)\nimport Data.List\n\nmkPt [a, b] = Pt a b\n\nreadPt = mkPt . map readInt . words\n\nreadInt = fromInteger . toInteger . readIntRec 0\nreadIntRec :: Int -> String -> Int\nreadIntRec val \"\" = val\nreadIntRec val (ch : str) = readIntRec (val*10 + (ord ch - ord '0')) str\n\ndata Pt = Pt !Int64 !Int64\n\naddPt (Pt x1 y1) (Pt x2 y2) = Pt (x1+x2) (y1+y2)\nsumPt = foldl' addPt (Pt 0 0)\n\nsqPt (Pt x y) = x*x+y*y\n\ninteractor :: String -> String\ninteractor str = let (hl : ol) = lines str\n n = read hl\n input = map readPt $ ol\n result = unlines [show $ (n * sum (map sqPt input) - sqPt (sumPt input))]\n in result\n\nmain = interact interactor\n\ninputGen = do\n putStrLn \"100000\"\n forM_ [1..100000] $ \\i -> putStrLn \"10000 10000\"\n "}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsumPoints [] _ _ _ acc = acc\nsumPoints (x:xs) sum sqsum i acc = let newval = ((i-1) * (x*x) - (2*x*sum) + sqsum) in\n sumPoints xs (sum+x) (sqsum + (x*x)) (i+1) (acc+newval)\n\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n,r1) = readInt all\n let Just ((xs,ys),_) = readTuples n r1\n let result = (sumPoints xs 0 0 1 0)+(sumPoints ys 0 0 1 0)\n putStrLn $ show result ++ \"\\n\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readTuples 0 s = do return (([],[]),s)\n readTuples n s = do (x, r) <- readInt s\n (y, z) <- readInt r\n ((l1,l2),t) <- readTuples (n-1) z\n return (((x : l1),(y : l2)),t)\n\n"}, {"source_code": "import Control.Monad;\n\nmain = do\n\tn <- fmap read getLine\n\ta <- replicateM n $ fmap (map read . words) getLine\n\tprint $ let x = map head a; y = map last a in gao x + gao y\n\ngao x = length x * sum (map (^2) x) - (sum x) ^ 2 where\n"}, {"source_code": "import Control.Monad;\n\nmain = do\n\tn <- fmap read getLine\n\ta <- replicateM n $ fmap (map read . words) getLine\n\tprint $ let x = map head a; y = map last a in gao x + gao y\n\ngao x = length x * sum (map (^2) x) - (sum x) ^ (2::Integer) where\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\n\ncompute :: [Int] -> Int -> Int -> [Int] -> Int\ncompute [] _ acc inp = acc\ncompute (x:xs) i acc inp = compute xs (i+1) (acc+(i - 1)*x*x - 2*x*(suma inp (i-1) 0) + (sumasq inp (i-1) 0)) (inp)\n\nsuma :: [Int] -> Int -> Int -> Int\nsuma x 0 acc = acc\nsuma (x:xs) n acc = suma xs (n-1) (acc+x)\n\nsumasq :: [Int] -> Int -> Int -> Int\nsumasq x 0 acc = acc\nsumasq (x:xs) n acc = sumasq xs (n-1) (acc+x*x)\n\n\nmain :: IO ()\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let (xs, ys) = getPoints n r1 ([],[])\n print ((compute xs 1 0 xs) + (compute ys 1 0 ys))\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (x, r) <- readInt s\n (l, t) <- readIntList (n-1) r\n return (x : l, t)\n getPoints 0 _ (accx, accy) = (accx, accy)\n getPoints n s (accx, accy) =\n let Just (pt, r2) = readIntList 2 s\n in getPoints (n-1) r2 (((head pt):accx), ((last pt):accy))\n"}, {"source_code": "getLines :: Int -> IO [(Int, Int)]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine >>= return . (\\(x:y:_) -> (read x, read y)) . words\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nsxx xys = sum [(fst xy) ^ 2 | xy <- xys]\nsyy xys = sum [(snd xy) ^ 2 | xy <- xys]\nsx xys = sum [fst xy | xy <- xys]\nsy xys = sum [snd xy | xy <- xys]\n\nmain = do\n\tn <- getLine >>= return . read :: IO Int\n\txys <- getLines n\n\tputStrLn . show $ length xys * (sxx xys + syy xys) - ((sx xys) ^ 2) - ((sy xys) ^ 2)\n"}, {"source_code": "\nimport Char (ord)\nimport Control.Monad (liftM)\n\nsolve :: Integer -> [(Int, Int)] -> Integer\nsolve n ps = solve' ps 0 0 0 0 \n where\n solve' :: [(Int, Int)] -> Integer -> Integer -> Integer -> Integer -> Integer\n solve' [] _ _ acc1 acc2 = (n-1) * acc1 - 2 * acc2\n solve' ((x,y) : ps) sX sY acc1 acc2 = solve' ps sX' sY' acc1' acc2'\n where\n x' = fromIntegral x\n y' = fromIntegral y\n sX' = sX + x'\n sY' = sY + y'\n acc1' = acc1 + x' * x' + y' * y'\n acc2' = acc2 + sX * x' + sY * y'\n\nreadPoint :: String -> (Int, Int)\nreadPoint line = readPoint' line 0\n where \n readPoint' (' ':s) a = readPoint'' s a 0\n readPoint' (c:s) a = readPoint' s (10*a + (ord c - ord '0'))\n readPoint'' [] a b = (a, b)\n readPoint'' (c:s) a b = readPoint'' s a (10*b + (ord c - ord '0'))\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines getContents\n let n = read $ head lines'\n let points = map readPoint $ take (fromIntegral n) $ tail lines'\n print $ solve n points\n"}, {"source_code": "\nsolve :: Integer -> [Int] -> [Int] -> Integer\nsolve n xs ys = solve' 0 xs 0 0 + solve' 0 ys 0 0 \n where\n solve' :: Int -> [Int] -> Integer -> Integer -> Integer\n solve' _ [] acc1 acc2 = (n-1) * acc1 - (acc2 + acc2)\n solve' s (x:xs) acc1 acc2 = s' `seq` acc1' `seq` acc2' `seq` solve' s' xs acc1' acc2'\n where\n s' = s + x\n acc1' = acc1 + fromIntegral (x * x)\n acc2' = acc2 + fromIntegral (s * x)\n\nreadPoint :: IO (Int, Int)\nreadPoint = do\n [x, y] <- getLine >>= return . map read . words\n return (x, y)\n\nmain :: IO ()\nmain = do\n n <- readLn\n points <- mapM (const readPoint) [1..n]\n print $ solve n (map fst points) (map snd points)\n"}], "src_uid": "9bd6fea892857d7c94ebce4d4cd46d30"} {"source_code": "import Data.List\n\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\n\nmain = interact $ unlines . parse . lines\n\nparse [_, perm'] = sol perm\n where\n perm = fn $ words perm'\n fn :: [String] -> [Int]\n fn xs = map read xs\n\nsol :: [Int] -> [String]\nsol perm = [ show $ select list ]\n where\n list' = recc 0 0 perm\n list = 1 : list' ++ list'\n select xs = head $ maximumBy cmplen $ group $ sortBy (flip compare) xs\n cmplen x y = compare (length x) (length y)\n\nrecc _ _ [] = []\nrecc nd st (x:xs)\n | st < x = recc st x xs\n | nd < x = st : x : recc x st xs\n | otherwise = x : recc nd st xs\n\nlist = [4,4,3,3,1,0,3,4]\n", "positive_code": [{"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n script\n --optimize\n --package aeson\n --package array\n --package base\n --package bytestring\n --package containers\n --package hashmap\n --package hashtables\n --package lens\n --package logict\n --package mtl\n --package mwc-random\n --package parsec\n --package pipes\n --package time\n --package vector\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,\n unfoldr)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), (<|>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap, forM_)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\nimport Data.Time.Clock\nimport System.IO (stderr)\n\ntype N = Int\ntoNum = toInt\n\nfromDown :: Down a -> a\nfromDown (Down a) = a\n\n-- answer :: [(Int, Int)] -> Int\nanswer xs = incs' $$ IM.toList .- L.maximumBy (comparing snd <> comparing (fst .- Down))\n .- fst\n where\n seens = scanl' (flip S.insert) S.empty xs\n greaters = zipWith S.split xs seens $$ map snd .- map toTwos\n isRec = greaters $$ map null\n zs = zip xs isRec\n incs = greaters $$ concatMap toOnes .- sort .- group .- map (head &&& length)\n .- IM.fromList\n incs' = foldl' doOne incs zs\n toTwos = S.toList .- take 2\n toOnes [_, _] = []\n toOnes ys = ys\n doOne m (x, rec'') = let rec' = toChange rec''\n alt Nothing = Just $ rec'\n alt (Just v) = Just $ v + rec'\n in IM.alter alt x m\n toChange True = -1\n toChange _ = 0\n\nhandleInput :: ByteString -> ByteString\nhandleInput = words .- drop 1 .- map toNum\n .- answer\n .- show .- pack\n -- .- map (show .- pack) .- unlines\n\ntoInt = readInt .- fromJust .- fst\ntoInte = readInteger .- fromJust .- fst\ntoX :: Read a => ByteString -> a\ntoX = unpack .- read\n\ncoerceInput f (a:b:xs) = f a b xs\ncoerceInput _ _ = error \"invalid input\"\n\nmain :: IO ()\nmain = do\n st <- getCurrentTime\n st `seq` interact handleInput\n ed <- getCurrentTime\n BS.hPutStrLn stderr $ pack \"\"\n BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)\n\n-- Util stuff --\n(.-) :: (a -> b) -> (b -> c) -> a -> c\n(.-) = flip (.)\ninfixl 9 .-\n\n($$) :: a -> (a -> b) -> b\n($$) = flip ($)\ninfixl 0 $$\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f !z [] = [z]\nscanl' f !z (x:xs) = z : scanl' f (f z x) xs\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\\(m, _, _) -> -m) . head)) $ groupBy (\\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of\n (d, _) | d <= 0 -> maybe (minimum xs) id $ minimumMay $ map fst $ filter (uncurry (/=)) $ zip xs pmaxs\n (_, x) -> -x\n where\n pmaxs = scanl1 max xs\n pmax2s = snd $ mapAccumL (\\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs\n\nminimumMay [] = Nothing\nminimumMay xs = Just $ minimum xs"}], "negative_code": [{"source_code": "module Main where\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Ord\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve xs = fst $ maximumBy (comparing snd) $ map (liftM2 (,) ((\\(m, _, _) -> m) . head) (sum . map (\\(_, m2, x) -> fromEnum $ x > m2))) $ groupBy (\\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs\n where\n pmaxs = scanl1 max xs\n pmax2s = snd $ mapAccumL (\\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs"}, {"source_code": "module Main where\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\\(m, _, _) -> -m) . head)) $ groupBy (\\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of\n (d, _) | d <= 0 -> minimum xs\n (_, x) -> -x\n where\n pmaxs = scanl1 max xs\n pmax2s = snd $ mapAccumL (\\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs\n\nminimumMay [] = Nothing\nminimumMay xs = Just $ minimum xs"}, {"source_code": "module Main where\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\\(m, _, _) -> -m) . head)) $ groupBy (\\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of\n (d, x) | d <= 0 -> maybe (-x) id $ minimumMay $ filter (/= (-x)) xs\n (_, x) -> -x\n where\n pmaxs = scanl1 max xs\n pmax2s = snd $ mapAccumL (\\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs\n\nminimumMay [] = Nothing\nminimumMay xs = Just $ minimum xs"}, {"source_code": "module Main where\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\\(m, _, _) -> -m) . head)) $ groupBy (\\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of\n (0, x) -> minimum $ map fst $ filter (\\(x', m) -> x' /= m && x' < -x) $ zip xs pmaxs\n (_, x) -> -x\n where\n pmaxs = scanl1 max xs\n pmax2s = snd $ mapAccumL (\\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs"}, {"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n script\n --optimize\n --package aeson\n --package array\n --package base\n --package bytestring\n --package containers\n --package hashmap\n --package hashtables\n --package lens\n --package logict\n --package mtl\n --package mwc-random\n --package parsec\n --package pipes\n --package time\n --package vector\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,\n unfoldr)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), (<|>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap, forM_)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\nimport Data.Time.Clock\nimport System.IO (stderr)\n\ntype N = Int\ntoNum = toInt\n\nfromDown :: Down a -> a\nfromDown (Down a) = a\n\n-- answer :: [(Int, Int)] -> Int\nanswer xs = greaters $$ sort .- group .- map (length &&& head)\n .- ((0, 1) :) .- L.maximumBy (comparing fst <> comparing (snd .- Down))\n .- snd\n where\n seens = scanl' (flip S.insert) S.empty xs\n greaters = zipWith S.split xs seens $$ map snd .- concatMap toOnes\n toOnes x\n | S.size x == 1 = S.toList x\n | otherwise = []\n\nhandleInput :: ByteString -> ByteString\nhandleInput = words .- drop 1 .- map toNum\n .- answer\n .- show .- pack\n -- .- map (show .- pack) .- unlines\n\ntoInt = readInt .- fromJust .- fst\ntoInte = readInteger .- fromJust .- fst\ntoX :: Read a => ByteString -> a\ntoX = unpack .- read\n\ncoerceInput f (a:b:xs) = f a b xs\ncoerceInput _ _ = error \"invalid input\"\n\nmain :: IO ()\nmain = do\n st <- getCurrentTime\n st `seq` interact handleInput\n ed <- getCurrentTime\n BS.hPutStrLn stderr $ pack \"\"\n BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)\n\n-- Util stuff --\n(.-) :: (a -> b) -> (b -> c) -> a -> c\n(.-) = flip (.)\ninfixl 9 .-\n\n($$) :: a -> (a -> b) -> b\n($$) = flip ($)\ninfixl 0 $$\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f !z [] = [z]\nscanl' f !z (x:xs) = z : scanl' f (f z x) xs\n"}, {"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n script\n --optimize\n --package aeson\n --package array\n --package base\n --package bytestring\n --package containers\n --package hashmap\n --package hashtables\n --package lens\n --package logict\n --package mtl\n --package mwc-random\n --package parsec\n --package pipes\n --package time\n --package vector\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,\n unfoldr)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), (<|>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap, forM_)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\nimport Data.Time.Clock\nimport System.IO (stderr)\n\ntype N = Int\ntoNum = toInt\n\nfromDown :: Down a -> a\nfromDown (Down a) = a\n\n-- answer :: [(Int, Int)] -> Int\nanswer xs = incs' $$ IM.toList .- L.maximumBy (comparing snd <> comparing (fst .- Down))\n .- fst\n where\n seens = scanl' (flip S.insert) S.empty xs\n greaters = zipWith S.split xs seens $$ map snd .- map toTwos\n isRec = greaters $$ map null\n zs = zip xs isRec\n incs = greaters $$ concatMap toOnes .- sort .- group .- map (head &&& length)\n .- IM.fromList\n incs' = foldl' doOne incs zs\n toTwos x\n | S.size x <= 2 = S.toList x\n | otherwise = []\n toOnes [_, _] = []\n toOnes ys = ys\n doOne m (x, rec'') = let rec' = toChange rec''\n alt Nothing = Just $ rec'\n alt (Just v) = Just $ v + rec'\n in IM.alter alt x m\n toChange True = -1\n toChange _ = 0\n\nhandleInput :: ByteString -> ByteString\nhandleInput = words .- drop 1 .- map toNum\n .- answer\n .- show .- pack\n -- .- map (show .- pack) .- unlines\n\ntoInt = readInt .- fromJust .- fst\ntoInte = readInteger .- fromJust .- fst\ntoX :: Read a => ByteString -> a\ntoX = unpack .- read\n\ncoerceInput f (a:b:xs) = f a b xs\ncoerceInput _ _ = error \"invalid input\"\n\nmain :: IO ()\nmain = do\n st <- getCurrentTime\n st `seq` interact handleInput\n ed <- getCurrentTime\n BS.hPutStrLn stderr $ pack \"\"\n BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)\n\n-- Util stuff --\n(.-) :: (a -> b) -> (b -> c) -> a -> c\n(.-) = flip (.)\ninfixl 9 .-\n\n($$) :: a -> (a -> b) -> b\n($$) = flip ($)\ninfixl 0 $$\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\n\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\nscanl' f !z [] = [z]\nscanl' f !z (x:xs) = z : scanl' f (f z x) xs\n"}, {"source_code": "import Data.List\n\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\n\nmain = interact $ unlines . parse . lines\n\nparse [_, perm'] = sol perm\n where\n perm = fn $ words perm'\n fn :: [String] -> [Int]\n fn xs = map read xs\n\nsol :: [Int] -> [String]\nsol perm = [ show $ select list ]\n where\n list' = recc 0 0 perm\n list = 1 : list' ++ list' \n select xs = head $ maximumBy cmplen $ group $ sortBy (flip compare) xs\n cmplen x y = compare (length x) (length y)\n\nrecc _ _ [] = []\nrecc nd st (x:xs)\n | st < x = recc st x xs\n | nd < x = st : recc x st xs\n | otherwise = recc nd st xs\n\nlist = [4,4,3,3,1,0,3,4]\n"}, {"source_code": "import Data.List\n\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\n\nmain = interact $ unlines . parse . lines\n\nparse [_, perm'] = sol perm\n where\n perm = fn $ words perm'\n fn :: [String] -> [Int]\n fn xs = map read xs\n\nsol :: [Int] -> [String]\nsol perm = [ show $ select list ]\n where\n list' = recc 0 0 perm\n list = 1 : list' ++ list'\n select xs = head $ maximumBy cmplen $ group $ sortBy (flip compare) xs\n cmplen x y = compare (length x) (length y)\n\nrecc _ _ [] = []\nrecc nd st (x:xs)\n | st < x = recc st x xs\n | nd < x = st : x : recc x st xs\n | otherwise = recc nd st xs\n\nlist = [4,4,3,3,1,0,3,4]\n"}], "src_uid": "c15ad483441864b3222eb62723b598e1"} {"source_code": "import Control.Monad (replicateM_)\r\n\r\nsolve :: String -> String\r\nsolve (a:[]) = [a, a]\r\nsolve (a:b:xs) =\r\n if b >= a\r\n then [a, a]\r\n else iter [a] a (b:xs)\r\n where\r\n iter acc a [] = reverse acc ++ acc\r\n iter acc a (b:xs) =\r\n if b <= a\r\n then iter (b:acc) b xs\r\n else reverse acc ++ acc\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = read s :: Int\r\n gao = do\r\n n <- readInt <$> getLine\r\n s <- getLine\r\n putStrLn $ solve s\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n ~[s] <- getNext 1\r\n let\r\n sLi = P.unpack s\r\n s2 = toEnum 255 : sLi\r\n toUse = case sLi of\r\n x : y : zs | x <= y -> [x]\r\n _ -> map fst $ takeWhile (uncurry (<=)) $ zip sLi s2\r\n pure $ string7 $ toUse ++ reverse toUse ++ \"\\n\"\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\nremoveElem :: Int -> [a] -> [a]\nremoveElem i xs = take i xs <> tail (drop i xs)\n\nmain = do\n n <- read @Int <$> getLine\n replicateM n $ do\n void getLine\n str <- getLine\n let go (x:xs) c = if x < c || (x == c && head str > x)\n then x : go xs x\n else []\n go [] c = []\n let res = go str maxBound\n putStrLn $ res ++ reverse res\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n _ <- getInts\n str <- filter (not . isSpace) . C.unpack <$> C.getLine\n let (g : gs) = group str\n result\n | length g >= 2 = [head g]\n | otherwise = concat $ either id id $ foldM acc [g] gs\n where acc ts xs\n | head (head ts) > head xs = Right $ xs : ts\n | otherwise = Left ts\n return $ string8 (reverse result ++ result) `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\nsolve :: String -> String\r\nsolve s =\r\n iter [head s] (head s) (tail s)\r\n where\r\n iter acc curr \"\" = reverse acc ++ acc\r\n iter acc curr rem =\r\n let\r\n next_ = head rem\r\n in\r\n if curr > next_\r\n then iter (next_:acc) next_ (tail rem)\r\n else reverse acc ++ acc\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = read s :: Int\r\n gao = do\r\n n <- readInt <$> getLine\r\n s <- getLine\r\n putStrLn $ solve s\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: Int -> C.ByteString -> String\r\nsolve 1 s = [C.head s, C.head s]\r\nsolve _ s =\r\n iter [C.head s] (C.head s) (C.tail s)\r\n where\r\n iter acc curr \"\" = reverse acc ++ acc\r\n iter acc curr rem =\r\n let\r\n next_ = C.head rem\r\n in\r\n if curr > next_\r\n then iter (next_:acc) next_ (C.tail rem)\r\n else reverse acc ++ acc\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> C.getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = let Just (i, _) = C.readInt s in i\r\n gao = do\r\n n <- readInt <$> C.getLine\r\n s <- C.getLine\r\n putStrLn $ solve n s\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: Int -> C.ByteString -> String\r\nsolve 1 s = [C.head s, C.head s]\r\nsolve _ s =\r\n iter [C.head s] (C.head s) (C.tail s)\r\n where\r\n iter acc curr \"\" = reverse acc ++ acc\r\n iter acc curr rem =\r\n let\r\n next = C.head rem\r\n in\r\n if curr > next\r\n then iter (next:acc) next (C.tail rem)\r\n else reverse acc ++ acc\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> C.getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = let Just (i, _) = C.readInt s in i\r\n gao = do\r\n n <- readInt <$> C.getLine\r\n s <- C.getLine\r\n putStrLn $ solve n s\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: Int -> C.ByteString -> C.ByteString\r\nsolve 1 s = C.append s s\r\nsolve _ s =\r\n iter (C.singleton $ C.head s) (C.head s) (C.tail s)\r\n where\r\n iter acc curr \"\" = C.append (C.reverse acc) acc\r\n iter acc curr rem =\r\n let\r\n next = C.head rem\r\n in\r\n if curr > next\r\n then iter (C.cons next acc) next (C.tail rem)\r\n else C.append (C.reverse acc) acc\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> C.getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = let Just (i, _) = C.readInt s in i\r\n gao = do\r\n n <- readInt <$> C.getLine\r\n s <- C.getLine\r\n C.putStrLn $ solve n s\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: Int -> C.ByteString -> C.ByteString\r\nsolve 1 s = s\r\nsolve _ s =\r\n iter (C.singleton $ C.head s) (C.head s) (C.tail s)\r\n where\r\n iter acc curr \"\" = C.append (C.reverse acc) acc\r\n iter acc curr rem =\r\n let\r\n next = C.head rem\r\n in\r\n if curr > next\r\n then iter (C.cons next acc) next (C.tail rem)\r\n else C.append (C.reverse acc) acc\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n tc <- readInt <$> C.getLine\r\n replicateM_ tc gao\r\n where\r\n readInt s = let Just (i, _) = C.readInt s in i\r\n gao = do\r\n n <- readInt <$> C.getLine\r\n s <- C.getLine\r\n C.putStrLn $ solve n s\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.List\n\nremoveElem :: Int -> [a] -> [a]\nremoveElem i xs = take i xs <> tail (drop i xs)\n\nmain = do\n n <- read @Int <$> getLine\n replicateM n $ do\n void getLine\n str <- getLine\n let go (x:xs) c = if x < c\n then x : go xs x\n else []\n go [] c = []\n let res = go str maxBound\n putStrLn $ res ++ reverse res\n"}], "src_uid": "dd7faacff9f57635f8e00c2f8f5a4650"} {"source_code": "main = fmap (\\x -> show (length (filter odd [1..x]) ^ 2 + (length (filter even [1..x]) ^ 2)) : f 1 x) readLn >>= mapM putStrLn\nf a b = if a > b then [] else map (\\x -> if even (a + x) then 'C' else '.') [1..b] : f (a + 1) b", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n ls = [[if even i == even j then 'C' else '.' | j <- [1..n]] | i <- [1..n]]\n\n print $ length $ filter (== 'C') $ concat ls\n putStrLn $ unlines ls\n"}, {"source_code": "main = fmap (\\x -> show (div (x * x + 1) 2) : f 1 x) readLn >>= mapM putStrLn\nf a b = if a > b then [] else map (\\x -> if even (a + x) then 'C' else '.') [1..b] : f (a + 1) b"}, {"source_code": "main = fmap f readLn >>= mapM putStrLn\nf x = show (div (x * x + 1) 2) : g [g \"C.\", g \".C\"]\n where g xs = take x $ concat $ repeat xs"}, {"source_code": "main = readLn >>= mapM putStrLn . f\nf x = show (div (x * x + 1) 2) : g [g \"C.\", g \".C\"]\n where g xs = take x $ cycle xs"}, {"source_code": "\nimport Control.Monad (forM_)\n\nmain = do\n n <- fmap read getLine\n let total = case n `divMod` 2 of\n (q,0) -> n*q\n (q,1) -> (q+1) + q*n\n let row1 = take n $ cycle \"C.\"\n row2 = take n $ cycle \".C\"\n rows = take n $ cycle [row1,row2]\n print total\n forM_ rows $ putStrLn\n \n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\n\nmain = do\n n <- fmap (read) getLine :: IO Int\n let table = take n $ cycle [ take n $ cycle [1, 0], take n $ cycle [0, 1] ]\n print $ sum $ fmap sum table\n mapM_ (putStrLn . (fmap ((Map.fromList [(0, '.'), (1, 'C')]) Map.!))) table\n"}, {"source_code": "module Main where\n\nimport Data.List\n-- https://codeforces.com/problemset/problem/384/A\nmain :: IO ()\nmain = do\n n <- getLine >>= pure . (read :: String -> Int)\n let res = solve n\n putStrLn . show . length . filter (=='C') $ res\n putStrLn res\n pure ()\n\nsolve :: Int -> String\nsolve n =\n let n' = (n+1) `div` 2\n cs = f \".\" . intercalate \".\" . take n' $ (repeat \"C\")\n dot = f \"C\" . intercalate \"C\" . take n' $ (repeat \".\")\n in intercalate \"\\n\" . take n $ cycle [cs, dot]\n where\n f s = if even n then ( <> s )\n else ( <> mempty )"}, {"source_code": "main :: IO ()\nmain = readLn >>= mapM_ putStrLn . solve\n\nsolve :: Int -> [String]\nsolve n = show ((n * n + 1) `div` 2) : take n (cycle [ take n $ cycle \"C.\", take n $ cycle \".C\" ])\n"}, {"source_code": "main = do\n n <- readLn\n print $ (n^2 + 1) `div` 2\n mapM_ putStrLn $ take n $ map (take n . flip drop (cycle \"C.\")) (cycle [0,1])\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \n \nmain=do\t \n\tn<- read <$> getLine:: IO Int\n\tlet s1 = take n $ cycle ['C','.']\n\tlet s2 = take n $ cycle ['.','C']\n\tprint $ (+) (if odd n then 1 else 0) $ div (n*n) 2\n\tputStrLn $ intercalate \"\\n\" $ take n $ cycle [s1,s2]"}, {"source_code": "process :: Int -> (Int,[[Char]])\nprocess n = (nc,map (\\i -> take n (f (odd i))) [1..n])\n where\n nc = (n^2-1)`div`2+1\n f :: Bool -> [Char]\n f b = map (\\x -> if x then 'C' else '.') $ iterate not b\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n let (nc,board) = process n\n print nc\n mapM_ putStrLn board"}, {"source_code": "sol :: Int -> [Char]\nsol n = take ((n+1)*n) (cycle ((take n (cycle \"C.\") ++ ['\\n']) ++ (take n (cycle \".C\") ++ ['\\n'])))\n\nmain = do\n input <- getLine\n let n = read input\n putStrLn $ show $ (ceiling ((fromIntegral n^2) / 2))\n putStrLn $ sol n\n"}, {"source_code": "main = getLine>>=(\\x->putStr(solve (read x)))\nsolve n = res n ++ \"\\n\" ++ (unlines (tb n))\nres n = show ((n*n)`div`2+n`mod`2)\ntb n = take n (concat (map (map (take n)) (replicate 1000 [concat (replicate 1000 \"C.\"),concat (replicate 1000 \".C\")])))"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List\n-- https://codeforces.com/problemset/problem/384/A\nmain :: IO ()\nmain = do\n n <- getLine >>= pure . (read :: String -> Int)\n putStrLn $ solve n\n pure ()\n\nsolve :: Int -> String\nsolve n =\n let n' = (n+1) `div` 2\n cs = f \".\" . intercalate \".\" . take n' $ (repeat \"C\")\n dot = f \"C\" . intercalate \"C\" . take n' $ (repeat \".\")\n in intercalate \"\\n\" . take n $ cycle [cs, dot]\n where\n f s = if even n then ( <> s )\n else ( <> mempty )"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \n \nmain=do\t \n\tn<- read <$> getLine:: IO Int\n\tlet s1 = take n $ cycle ['C','.']\n\tlet s2 = take n $ cycle ['.','C']\n\tputStrLn $ intercalate \"\\n\" $ take n $ cycle [s1,s2]"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \n \nmain=do\t \n\tn<- read <$> getLine:: IO Int\n\tlet s1 = take n $ cycle ['C','.']\n\tlet s2 = take n $ cycle ['.','C']\n\tprint n\n\tputStrLn $ intercalate \"\\n\" $ take n $ cycle [s1,s2]"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n ls = [[if even i == even j then 'C' else '.' | j <- [1..n]] | i <- [1..n]]\n\n print $ length $ filter (== '.') $ concat ls\n putStrLn $ unlines ls\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n ls = [[if even i == even j then 'C' else '.' | j <- [1..n]] | i <- [1..n]]\n\n putStrLn $ unlines ls\n"}, {"source_code": "main = fmap (\\x -> show (x * x + 1 `div` 2) : f 1 x) readLn >>= mapM putStrLn\nf a b = if a > b then [] else map (\\x -> if even (a + x) then 'C' else '.') [1..b] : f (a + 1) b"}, {"source_code": "main = fmap f readLn >>= mapM putStrLn\nf x = show (div (x * x + 1) 2) : g [g \"C.\", g \".C\"]\n where g xs = take 5 $ concat $ repeat xs"}, {"source_code": "main = fmap (f 1) readLn >>= mapM putStrLn\nf a b = if a > b then [] else map (\\x -> if x == a then 'C' else '.') [1..b] : f (a + 1) b"}], "src_uid": "1aede54b41d6fad3e74f24a6592198eb"} {"source_code": "import System.IO\nimport Data.List\nimport Data.Bits\n\ntoint s = (read s) :: Int\n\ndoit::Int->Int->Int->Int->[Int]->String\ndoit d t a b s =\n if t == t then\n if d < 0 then\n \"! \"++show(a)++\" \"++show(b)++\"\\n\"\n else\n if t == 0 then\n let w = head s in\n let aa = if w == 1 then a else (xor a $ shift 1 d) in\n let bb = if w == 1 then b else (xor b $ shift 1 d) in\n \"? \"++show(xor a $ shift 1 d)++\" \"++show(b)++\"\\n\"++(doit (d-1) 0 aa bb $ tail s)\n else\n let q = \"? \"++show(xor a $ shift 1 d)++\" \"++show(xor b $ shift 1 d)++\"\\n\" in\n let w = head s in\n q++(if w == t then (doeq d t a b $ tail s) else (doneq d t a b $ tail s)) \n else\n \"pingo\"\n\ndoeq d t a b s =\n if t == t then\n let q = \"? \"++show(xor a $ shift 1 d)++\" \"++show(b)++\"\\n\" in\n let w = head s in\n let aa = if w == 1 then a else (xor a $ shift 1 d) in\n let bb = if w == 1 then b else (xor b $ shift 1 d) in\n q++(doit (d-1) t aa bb $ tail s)\n else\n \"pingo\"\n\ndoneq d t a b s =\n if t == t then\n let aa = if t == 1 then (xor a $ shift 1 d) else a in\n let bb = if t == 1 then b else (xor b $ shift 1 d) in\n let q = \"? \"++show(aa)++\" \"++show(bb)++\"\\n\" in\n let w = head s in\n q++(doit (d-1) w aa bb $ tail s)\n else\n \"pingo\"\n\nsolve::String -> String\nsolve ss =\n let s = map toint $ words ss in\n let t = head s in\n \"? 0 0\\n\"++(doit 29 t 0 0 $ tail s)\n\nmain = do\n hSetBuffering stdout LineBuffering\n interact $ solve", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\n\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport System.IO\n\nmain :: IO ()\nmain = do\n (x, y) <- first\n putStrLn $ (\"! \"++) $ shows x $ ' ' : show y\n\nputQuery :: Int -> Int -> IO Ordering\nputQuery c d = do\n putStrLn $ (\"? \"++) $ shows c $ ' ' : show d\n hFlush stdout\n (`compare` (0::Int)) . read <$> getLine\n\n\nfirst :: IO (Int, Int)\nfirst = (putQuery 0 0 >>=) $ neqLoop (bit 29) 0 0 \n\nneqLoop :: Int -> Int -> Int -> Ordering -> IO (Int, Int)\nneqLoop 0 !a !b !ord = return (a,b)\nneqLoop !lev !a !b EQ = eqLoop lev a b\nneqLoop !lev !a !b !ord = do\n flippedOrd <- putQuery (a .|. lev) (b .|. lev)\n if ord == flippedOrd then do\n thisBit <- putQuery a (b .|. lev)\n let (newA, newB) = case thisBit of\n LT -> (a,b)\n _ -> (a .|. lev, b .|. lev)\n neqLoop (lev `shiftR` 1) newA newB ord\n else do\n let (newA, newB) = case ord of\n GT -> (a .|. lev, b)\n _ -> (a, b .|. lev)\n newOrd <- putQuery newA newB\n neqLoop (lev `shiftR` 1) newA newB newOrd\n\neqLoop :: Int -> Int -> Int -> IO (Int, Int)\neqLoop 0 !a !b = return (a, b)\neqLoop !lev !a !b = do\n ord <- putQuery a (b .|. lev)\n case ord of\n LT -> eqLoop (lev `shiftR` 1) a b\n _ -> eqLoop (lev `shiftR` 1) (a .|. lev) (b .|. lev)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\n\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport System.IO\n\nmain :: IO ()\nmain = do\n (x, y) <- first\n putStrLn $ (\"! \"++) $ shows x $ ' ' : show y\n\nputQuery :: Int -> Int -> IO Ordering\nputQuery c d = do\n putStrLn $ (\"? \"++) $ shows c $ ' ' : show d\n hFlush stdout\n (`compare` (0::Int)) . read <$> getLine\n\n\nfirst :: IO (Int, Int)\nfirst = (putQuery 0 0 >>=) $ neqLoop (bit 29) 0 0 (bit 30 - 1) \n\nneqLoop :: Int -> Int -> Int -> Int -> Ordering -> IO (Int, Int)\nneqLoop 0 !a !b !unk !ord = eqLoop (bit 29) a b unk\nneqLoop !lev !a !b !unk EQ = eqLoop (bit 29) a b unk\nneqLoop !lev !a !b !unk !ord = do\n flippedOrd <- putQuery (a .|. lev) (b .|. lev)\n if ord == flippedOrd then\n neqLoop (lev `shiftR` 1) a b unk ord\n else do\n let (newA, newB) = case ord of\n GT -> (a .|. lev, b)\n _ -> (a, b .|. lev)\n newOrd <- putQuery newA newB\n neqLoop (lev `shiftR` 1) newA newB (unk .&. complement lev) newOrd\n\neqLoop :: Int -> Int -> Int -> Int -> IO (Int, Int)\neqLoop 0 !a !b !unk = return (a, b)\neqLoop !lev !a !b !unk | lev .&. unk == 0\n = eqLoop (lev `shiftR` 1) a b unk\neqLoop !lev !a !b !unk = do\n ord <- putQuery a (b .|. lev)\n case ord of\n LT -> eqLoop (lev `shiftR` 1) a b unk\n _ -> eqLoop (lev `shiftR` 1) (a .|. lev) (b .|. lev) unk\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\n\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport System.IO\n\nmain :: IO ()\nmain = do\n (x, y) <- first\n putStrLn $ (\"! \"++) $ shows x $ ' ' : show y\n\nputQuery :: Int -> Int -> IO Ordering\nputQuery c d = do\n putStrLn $ (\"? \"++) $ shows c $ ' ' : show d\n hFlush stdout\n (`compare` (0::Int)) . read <$> getLine\n\ndata Status = Status { level :: {-# UNPACK #-} !Int,\n bitsA :: {-# UNPACK #-} !Int,\n bitsB :: {-# UNPACK #-} !Int,\n unknown :: {-# UNPACK #-} !Int }\n\nfirst :: IO (Int, Int)\nfirst = (putQuery 0 0 >>=) $ neqLoop $ Status (bit 29) 0 0 (bit 30 - 1) \n\nneqLoop :: Status -> Ordering -> IO (Int, Int)\nneqLoop st@Status{ level = 0 } !ord = eqLoop st{ level = bit 29 }\nneqLoop !st EQ = eqLoop st{ level = bit 29 }\nneqLoop !st !ord = do\n flippedOrd <- putQuery (bitsA st .|. level st) (bitsB st .|. level st)\n if ord == flippedOrd then\n neqLoop st{level = level st `shiftR` 1} ord\n else do\n let (newA, newB) = case ord of\n GT -> (bitsA st .|. level st, bitsB st)\n _ -> (bitsA st, bitsB st .|. level st)\n !newSt = Status { level = level st `shiftR` 1,\n bitsA = newA,\n bitsB = newB,\n unknown = unknown st `xor` level st}\n newOrd <- putQuery newA newB\n neqLoop newSt newOrd\n \neqLoop :: Status -> IO (Int, Int)\neqLoop st@Status{ level = 0 } = return (bitsA st, bitsB st)\neqLoop st | level st .&. unknown st == 0\n = eqLoop st{level = level st `shiftR` 1}\neqLoop !st = do\n ord <- putQuery (bitsA st) (bitsB st .|. level st)\n case ord of\n LT -> eqLoop st{ level = level st `shiftR` 1 }\n _ -> eqLoop st{ bitsA = bitsA st .|. level st,\n bitsB = bitsB st .|. level st,\n level = level st `shiftR` 1}"}], "negative_code": [{"source_code": "import System.IO\nimport Data.List\nimport Data.Bits\n\ntoint s = (read s) :: Int\n\ndoit::Int->Int->Int->Int->[Int]->String\ndoit d t a b s =\n if t == t then\n if d < 0 then\n \"! \"++show(a)++\" \"++show(b)++\"\\n\"\n else\n if t == 0 then\n let w = head s in\n let aa = if w == 1 then a else (xor a $ shift 1 d) in\n \"? \"++show(xor a $ shift 1 d)++\" \"++show(b)++\"\\n\"++(doit (d-1) 0 aa aa $ tail s)\n else\n let q = \"? \"++show(xor a $ shift 1 d)++\" \"++show(xor b $ shift 1 d)++\"\\n\" in\n let w = head s in\n q++(if w == t then (doeq d t a b $ tail s) else (doneq d t a b $ tail s)) \n else\n \"pingo\"\n\ndoeq d t a b s =\n if t == t then\n let q = \"? \"++show(xor a $ shift 1 d)++\" \"++show(b)++\"\\n\" in\n let w = head s in\n let aa = if w == 1 then a else (xor a $ shift 1 d) in\n let bb = if w == 1 then b else (xor b $ shift 1 d) in\n q++(doit (d-1) t aa bb $ tail s)\n else\n \"pingo\"\n\ndoneq d t a b s =\n if t == t then\n let aa = if t == 1 then (xor a $ shift 1 d) else a in\n let bb = if t == 1 then b else (xor b $ shift 1 d) in\n let q = \"? \"++show(aa)++\" \"++show(bb)++\"\\n\" in\n let w = head s in\n q++(doit (d-1) w aa bb $ tail s)\n else\n \"pingo\"\n\nsolve::String -> String\nsolve ss =\n let s = map toint $ words ss in\n let t = head s in\n \"? 0 0\\n\"++(doit 29 t 0 0 $ tail s)\n\nmain = do\n hSetBuffering stdout LineBuffering\n interact $ solve"}], "src_uid": "7dc1137dd1f0c645cc7ec6dfdb92f5df"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.DeepSeq (deepseq)\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport Data.STRef\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n-- import Debug.Trace\nimport System.IO\nimport System.Random\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [x1, y1, x2, y2, x3, y3] <- map read . words <$> getLine\n\n let\n options a [] = [a]\n options a b = concat $ map f b\n where\n f p@(x, y, i) = options (a ++ [(x, y, i)]) (b \\\\ [p]) ++ options (a ++ [(y, x, i)]) (b \\\\ [p])\n\n rs = catMaybes $ map try $ options [] [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]\n where\n try [(x1, y1, i1), (x2, y2, i2), (x3, y3, i3)]\n | x1 == x2 && x2 == x3 && y1+y2+y3 == x1 =\n Just $ replicate y1 (replicate x1 i1) ++ replicate y2 (replicate x1 i2) ++ replicate y3 (replicate x1 i3)\n | x2 == x3 && x1+x2 == y1 && x1+x2 == y2+y3 =\n Just $ replicate y2 (replicate x1 i1 ++ replicate x2 i2) ++ replicate y3 (replicate x1 i1 ++ replicate x3 i3)\n | otherwise = Nothing\n\n if null rs\n then\n print (-1)\n else do\n print $ length $ head rs\n putStr $ unlines $ head rs\n \n \n", "positive_code": [{"source_code": "import Data.List\nhanten::[(Int,Int,Char)] -> [[(Int,Int,Char)]]\nhanten [a0,a1,a2] = [a0,a1,a2]:[fp a0,a1,a2]:[a0,fp a1,a2]:[a0,a1,fp a2]:[fp a0,fp a1,a2]:[a0,fp a1,fp a2]:[fp a0,a1,fp a2]:[fp a0,fp a1,fp a2]:[]\nfp::(Int,Int,Char) -> (Int,Int,Char)\nfp (a,b,c) = (b,a,c) \nperm:: [(Int,Int,Char)] -> [[(Int,Int,Char)]]\nperm a = permutations a \nisOk:: [(Int,Int,Char)] -> Int\nisOk [(x0,y0,_),(x1,y1,_),(x2,y2,_)] | (x0 == x1+x2) && (y1 == y2) && (x0 == y0 + y1) = 1\n | (x0 == x1) && (x1 == x2) && (x0 == y0+y1+y2)= 2\n | otherwise = 0\ntakeIsOk ::[[(Int,Int,Char)]] -> ([(Int,Int,Char)],Int)\ntakeIsOk [] = ([],0)\ntakeIsOk (a:as) | io > 0 = (a,io)\n | otherwise = takeIsOk as\n where io = isOk a \ntoString::([(Int,Int,Char)],Int) -> String\ntoString ([],0) = \"-1\"\ntoString (a@[(x0,y0,_),(x1,y1,_),(x2,y2,_)],1) = toString0 getC1 a 0 0 x0 (y0+y1) \ntoString (a@[(x0,y0,_),(x1,y1,_),(x2,y2,_)],2) = toString0 getC2 a 0 0 x0 (y0+y1+y2)\ntoString0::([(Int,Int,Char)] -> Int -> Int -> Char) -> [(Int,Int,Char)]-> Int -> Int -> Int -> Int -> String\ntoString0 getC a@[(x0,y0,_),(x1,y1,_),(x2,y2,_)] i j si sj\n | i == si = []\n | j == sj -1 = [getC a i j]++\"\\n\"++(toString0 getC a (i+1) 0 si sj)\n | otherwise = (getC a i j):(toString0 getC a i (j+1) si sj)\ngetC1::[(Int,Int,Char)] -> Int -> Int -> Char\ngetC1 a@[(x0,y0,c0),(x1,y1,c1),(x2,y2,c2)] i j | i < y0 = c0\n | i >= y0 && j < x1 = c1\n | otherwise = c2\ngetC2::[(Int,Int,Char)] -> Int -> Int -> Char\ngetC2 a@[(x0,y0,c0),(x1,y1,c1),(x2,y2,c2)] i j | i < y0 = c0\n | i < y0+y1 = c1\n | otherwise = c2\n \nmain = do\n w0 <- getLine\n let [x0,y0,x1,y1,x2,y2] = [read n::Int| n<-(words w0)]\n let a = [[(x0,y0,'A'),(x1,y1,'B'),(x2,y2,'C')]]\n let allPattern = concatMap perm $ concatMap hanten a\n let ok = takeIsOk allPattern\n let t = snd ok\n if t == 0\n then putStrLn \"-1\"\n else do\n let ([(xn0,yn0,_),(xn1,yn1,_),(xn2,yn2,_)],_) = ok\n putStr ((show xn0) ++ \"\\n\"++ (toString ok))\n\n \n \n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Array as Array\nimport qualified Data.Array.ST as ST\n\nplace :: (Num a, Array.Ix a, Ord a, Enum a) => [(a, a, c)] -> Array.Array (a, a) c\nplace xs =\n let m = maximum $ map (\\(l, r, c) -> max l r) xs\n xs' = fit (m, m) xs\n in if length xs' == length xs then ST.runSTArray $ produce xs' m\n else Array.array ((0, 0), (-1, -1)) []\n where produce vs sz = do\n ar <- ST.newArray ((0, 0), (sz-1, sz-1)) (third $ head vs)\n foldM_ (\\p (l, r, v) -> do writeBlock ar p (l, r) v; return $ advance p (l, r) sz) (0, 0) vs\n return ar\n writeBlock ar (r, c) (rows, columns) value =\n mapM_ (\\(or, oc) -> ST.writeArray ar (r+or, c+oc) value) [(i, j) | i <- [0..rows-1], j <- [0..columns-1]]\n\nadvance (r, c) (br, bc) sz =\n if (c+bc) == sz then (r+br, c)\n else (r, c+bc)\n\nfit target values = fit' target [] [] values\n where fit' target rs ns [] | fst target == 0 || snd target == 0 = reverse rs\n | otherwise = []\n fit' target@(l, r) rs ns (x@(l', r', c):xs) = \n if l == l' && r >= r' then fit' (l', r-r') (x:rs) [] (ns ++ xs)\n else if l == r' && r >= l' then fit' (r', r-l') ((r', l', c):rs) [] (ns ++ xs)\n else if r == l' && l >= r' then fit' (l-r', l') ((r', l', c):rs) [] (ns ++ xs)\n else if r == r' && l >= l' then fit' (l-l', r') ((l', r', c):rs) [] (ns ++ xs)\n else fit' target rs (x:ns) xs\n\nsecond (_, v, _) = v\nthird (_, _, v) = v\n\nmain = do\n inp <- getContents\n let values = map read $ words inp :: [Int]\n d = zip3 (snd $ unzip $ filter (\\v -> odd $ fst v) $ zip [0..] values)\n (snd $ unzip $ filter (\\v -> even $ fst v) $ zip [0..] values) ['A', 'B', 'C']\n r = map (map snd) $ groupBy (\\((l, _), _) ((r, _), _) -> l == r) (Array.assocs $ place d)\n if length r /= 0 then do\n putStrLn $ show $ length r\n putStrLn $ unlines $ r\n else \n putStrLn \"-1\"\n"}, {"source_code": "import Data.Maybe\nimport Data.List ((\\\\), find)\nimport Debug.Trace (trace)\n\nmain = do\n\t[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine\n\n\tlet\n\t\ttry [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]\n\t\ttry bs = concatMap next bs\n\t\t\twhere \n\t\t\t\tnext b@(x, y, c) =\n\t\t\t\t\t\t(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')\n\t\t\t\t\twhere\n\t\t\t\t\t\tbs' = try $ bs \\\\ [b]\n\t\t\t\t\n\t\tcheck [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] = \n\t\t\tx1 == x2 && x2 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3\n\n\t\topts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]\n\t\tans = find check opts\n\n\t\tprintAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =\n\t\t\tif x1 == x2 && x2 == x3 && y1 + y2 + y3 == x1 then do\n\t\t\t\tprint x1\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 c1\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x1 c2\n\t\t\t\tputStr $ unlines $ replicate y3 $ replicate x1 c3\n\t\t\telse do\n\t\t\t\tprint y3\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 c1 ++ replicate x3 c3\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x2 c2 ++ replicate x3 c3 \n\n\tif isNothing ans\n\t\tthen print (-1)\n\t\telse printAns $ fromJust ans\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.List ((\\\\), find)\nimport Debug.Trace (trace)\n\nmain = do\n\t[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine\n\n\tlet\n\t\ttry [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]\n\t\ttry bs = concatMap next bs\n\t\t\twhere \n\t\t\t\tnext b@(x, y, c) =\n\t\t\t\t\t\t(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')\n\t\t\t\t\twhere\n\t\t\t\t\t\tbs' = try $ bs \\\\ [b]\n\t\t\t\t\n\t\tcheck [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] = \n\t\t\tx1 == x2 && x3 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3\n\n\t\topts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]\n\t\tans = find check opts\n\n\t\tprintAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =\n\t\t\tif x1 == x2 && x2 == x3 then do\n\t\t\t\tprint x1\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 c1\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x1 c2\n\t\t\t\tputStr $ unlines $ replicate y3 $ replicate x1 c3\n\t\t\telse if x1 == x2 && y1 + y2 == y3 then do\n\t\t\t\tprint y3\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 c1 ++ replicate x3 c3\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x2 c2 ++ replicate x3 c3 \n\t\t\telse\n\t\t\t\treturn ()\n\n\tif isNothing ans\n\t\tthen print (-1)\n\t\telse printAns $ fromJust ans\n"}, {"source_code": "import Data.Maybe\nimport Data.List ((\\\\), find)\nimport Debug.Trace (trace)\n\nmain = do\n\t[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine\n\n\tlet\n\t\ttry [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]\n\t\ttry bs = concatMap next bs\n\t\t\twhere \n\t\t\t\tnext b@(x, y, c) =\n\t\t\t\t\t\t(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')\n\t\t\t\t\twhere\n\t\t\t\t\t\tbs' = try $ bs \\\\ [b]\n\t\t\t\t\n\t\tcheck [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] = \n\t\t\tx1 == x2 && x2 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3\n\n\t\topts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]\n\t\tans = find check opts\n\n\t\tprintAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =\n\t\t\tif x1 == x2 && x2 == x3 then do\n\t\t\t\tprint x1\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 c1\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x1 c2\n\t\t\t\tputStr $ unlines $ replicate y3 $ replicate x1 c3\n\t\t\telse if x1 == x2 && y1 + y2 == y3 then do\n\t\t\t\tprint y3\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 c1 ++ replicate x3 c3\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x2 c2 ++ replicate x3 c3 \n\t\t\telse\n\t\t\t\treturn ()\n\n\tif isNothing ans\n\t\tthen print (-1)\n\t\telse printAns $ fromJust ans\n"}, {"source_code": "import Data.Maybe\nimport Data.List ((\\\\), find)\nimport Debug.Trace (trace)\n\nmain = do\n\t[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine\n\n\tlet\n\t\ttry [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]\n\t\ttry bs = concatMap next bs\n\t\t\twhere \n\t\t\t\tnext b@(x, y, c) =\n\t\t\t\t\t\t(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')\n\t\t\t\t\twhere\n\t\t\t\t\t\tbs' = try $ bs \\\\ [b]\n\t\t\t\t\n\t\tcheck [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] = \n\t\t\tx1 == x2 && x3 == x3 || x1 == x2 && y1 + y2 == y3\n\n\t\topts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]\n\t\tans = find check opts\n\n\t\tprintAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =\n\t\t\tif x1 == x2 && x2 == x3 then do\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 'A'\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x1 'B'\n\t\t\t\tputStr $ unlines $ replicate y3 $ replicate x1 'C'\n\t\t\telse if x1 == x2 && y1 + y2 == y3 then do\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 'A' ++ replicate x3 'C'\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x2 'B' ++ replicate x3 'C'\n\t\t\telse\n\t\t\t\treturn ()\n\n\tif isNothing ans\n\t\tthen print (-1)\n\t\telse printAns $ fromJust ans\n"}, {"source_code": "import Data.Maybe\nimport Data.List ((\\\\), find)\nimport Debug.Trace (trace)\n\nmain = do\n\t[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine\n\n\tlet\n\t\ttry [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]\n\t\ttry bs = concatMap next bs\n\t\t\twhere \n\t\t\t\tnext b@(x, y, c) =\n\t\t\t\t\t\t(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')\n\t\t\t\t\twhere\n\t\t\t\t\t\tbs' = try $ bs \\\\ [b]\n\t\t\t\t\n\t\tcheck [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] = \n\t\t\tx1 == x2 && x3 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3\n\n\t\topts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]\n\t\tans = find check opts\n\n\t\tprintAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =\n\t\t\tif x1 == x2 && x2 == x3 then do\n\t\t\t\tprint x1\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 'A'\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x1 'B'\n\t\t\t\tputStr $ unlines $ replicate y3 $ replicate x1 'C'\n\t\t\telse if x1 == x2 && y1 + y2 == y3 then do\n\t\t\t\tprint y3\n\t\t\t\tputStr $ unlines $ replicate y1 $ replicate x1 'A' ++ replicate x3 'C'\n\t\t\t\tputStr $ unlines $ replicate y2 $ replicate x2 'B' ++ replicate x3 'C'\n\t\t\telse\n\t\t\t\treturn ()\n\n\tif isNothing ans\n\t\tthen print (-1)\n\t\telse printAns $ fromJust ans\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Array as Array\nimport qualified Data.Array.ST as ST\n\nplace :: (Num a, Array.Ix a, Ord a, Enum a) => [(a, a, c)] -> Array.Array (a, a) c\nplace xs =\n let m = maximum $ map (\\(l, r, c) -> max l r) xs\n xs' = fit (m, m) xs\n in if length xs' == length xs then ST.runSTArray $ produce xs' m\n else Array.array ((0, 0), (-1, -1)) []\n where produce vs sz = do\n ar <- ST.newArray ((0, 0), (sz-1, sz-1)) (third $ head vs)\n foldM_ (\\p (l, r, v) -> do writeBlock ar p (l, r) v; return $ advance p (l, r) sz) (0, 0) vs\n return ar\n writeBlock ar (r, c) (rows, columns) value =\n mapM_ (\\(or, oc) -> ST.writeArray ar (r+or, c+oc) value) [(i, j) | i <- [0..rows-1], j <- [0..columns-1]]\n\nadvance (r, c) (br, bc) sz =\n if (c+bc) == sz then (r+br, c)\n else (r, c+bc)\n\nfit target values = fit' target [] values\n where fit' target ns [] = []\n fit' target@(l, r) ns (x@(l', r', c):xs) = \n if l == l' && r >= r' then x:(fit' (l', r-r') [] (ns ++ xs))\n else if l == r' && r >= l' then (r', l', c):(fit' (r', r-l') [] (ns ++ xs))\n else if r == l' && l >= r' then (r', l', c):(fit' (l-r', l') [] (ns ++ xs))\n else if r == r' && l >= l' then (l', r', c):(fit' (l-l', r') [] (ns ++ xs))\n else fit' target (x:ns) xs\n\nsecond (_, v, _) = v\nthird (_, _, v) = v\n\nmain = do\n inp <- getContents\n let values = map read $ words inp :: [Int]\n d = zip3 (snd $ unzip $ filter (\\v -> odd $ fst v) $ zip [0..] values)\n (snd $ unzip $ filter (\\v -> even $ fst v) $ zip [0..] values) ['A', 'B', 'C']\n r = map (map snd) $ groupBy (\\((l, _), _) ((r, _), _) -> l == r) (Array.assocs $ place d)\n if length r /= 0 then do\n putStrLn $ show $ length r\n putStrLn $ unlines $ r\n else \n putStrLn \"-1\"\n"}], "src_uid": "2befe5da2df57d23934601cbe4d4f151"} {"source_code": "main = do\n inputjar <- getLine\n let n = read inputjar :: Int\n solve n\n\nsolve :: Int -> IO ()\nsolve 0 = putStr \"\"\nsolve n = do\n input <- getLine\n let list = read (\"[\" ++ map (\\x -> if x == ' ' then ',' else x) input ++ \"]\") :: [Int]\n solveCase list\n solve (n - 1)\n\nsolveCase :: [Int] -> IO ()\nsolveCase (x : y : n : [])\n | tmp <= n = print tmp\n | otherwise = print $ tmp - x\n where\n tmp = n - (n `mod` x) + y\n\n\n", "positive_code": [{"source_code": "main = do\n inputjar <- getLine\n let n = read inputjar :: Int\n solve n\n\nsolve :: Int -> IO ()\nsolve 0 = putStr \"\"\nsolve n = do\n input <- getLine\n let list = read (\"[\" ++ map (\\x -> if x == ' ' then ',' else x) input ++ \"]\") :: [Int]\n solveCase list\n solve (n - 1)\n\nsolveCase :: [Int] -> IO ()\nsolveCase (x : y : n : [])\n | tmp <= n = print tmp\n | otherwise = print $ tmp - x\n where\n tmp = n - (n `mod` x) + y\n"}, {"source_code": "solve :: [Int] -> Int\nsolve [x, y, n]\n | (n - n `mod` x + y) <= n = (n - n `mod` x + y)\n | otherwise = (n - n `mod` x - (x - y))\n\nsplitEvery :: Int -> [a] -> [[a]]\nsplitEvery _ [] = []\nsplitEvery n xs = as : splitEvery n bs\n where (as,bs) = splitAt n xs\n\ngetList :: Read a => IO [a]\ngetList = map read . words <$> getLine\n\nmain :: IO ()\nmain = interact $ unlines . map show . map solve . splitEvery 3 . map read . tail . words\n"}, {"source_code": "import Control.Monad (replicateM_)\n\nmain = readLn >>= flip replicateM_ (getLine >>= print . (\\[a,b,c] -> f a b c) . map read . words)\n\nf :: Int -> Int -> Int -> Int\nf x y n | n `mod` x >= y = n - ((n `mod` x) - y)\n | otherwise = f x y $ n - (n `mod` x) - 1"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad (replicateM_)\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n input :: [Word] <- map read . words <$> getLine\n let x = input !! 0;\n y = input !! 1;\n n = input !! 2;\n i = n - n `mod` x + y; in\n print $ if i > n then i - x else i\n\n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = (itoline . solve . linetois) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: [Int] -> Int\nsolve (x: y: n: []) | r >= y = n - (r-y)\n | otherwise = n + (y-r) - x where\n r = n `mod` x\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess x y n | a==y = n\n\t | a>y = n-a+y\n | otherwise = n-x-a+y\t\n\twhere a = mod n x\n\nonecase = do\n\t\t[x,y,n]<- map read <$> words <$> getLine ::IO [Integer]\n\t\tprint $ process x y n\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [x,y,n] <- map read . words <$> getLine\n print $ n - (n - y) `mod` x\n"}], "negative_code": [], "src_uid": "2589e832f22089fac9ccd3456c0abcec"} {"source_code": "import Control.Monad\n\nsolve :: Double -> Double\nsolve n\n | n > 1 = (1.0 / n) + solve (n - 1)\n | otherwise = 1\n\nmain :: IO ()\nmain = readLn >>= putStrLn . show . solve\n\n", "positive_code": [{"source_code": "solve :: Integer -> Double\nsolve n = sum $ map (\\x -> 1.0 / (fromInteger x)) [1..n]\n\nmain = interact (show . solve . (\\x -> read x :: Integer))\n"}, {"source_code": "import Control.Monad\n\nsolve :: Double -> Int -> Double\nsolve ans 0 = ans\nsolve ans n = solve (ans + (1 / (fromIntegral n))) (n - 1)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn $ show . solve 0.0 $ n \n\n"}, {"source_code": "import Control.Monad\n\nsolve :: Double -> Double\nsolve n = sum $ map (\\x -> 1.0 / x) [1..n]\n\nmain :: IO ()\nmain = readLn >>= putStrLn . show . solve\n\n"}, {"source_code": "module Main where\n\nmain :: IO()\nmain = do\n x <- getLine\n let y = read x :: Int\n let s = sum [1 / fromIntegral(i) | i <- [1..y]]\n print s"}, {"source_code": "solve :: Int -> Double\nsolve n\n | n == 1 = 1.0\n | otherwise = r + solve n'\n where\n n' = n - 1\n r = (1.0) / (fromIntegral n)\n \nmain = do\n n <- readLn :: IO Int\n print $ solve n"}], "negative_code": [{"source_code": "solve :: Int -> Double\nsolve n\n | n == 1 = 1.0\n | otherwise = r + solve n'\n where\n n' = n - t\n t = (n `div` 2)\n r = (fromIntegral t) / (fromIntegral n)\n \nmain = do\n n <- readLn :: IO Int\n print $ solve n"}, {"source_code": "solve :: Int -> Double\nsolve n\n | n == 1 = 1.0\n | otherwise = r + solve n'\n where\n n' = n - t\n t = (n `div` 2) + n `mod` 2\n r = (fromIntegral t) / (fromIntegral n)\n \nmain = do\n n <- readLn :: IO Int\n print $ solve n"}, {"source_code": "solve :: Int -> Double\nsolve n\n | n == 1 = 1.0\n | otherwise = r + solve n'\n where\n n' = n - t\n t = n - 1\n r = (fromIntegral t) / (fromIntegral n)\n \nmain = do\n n <- readLn :: IO Int\n print $ solve n"}], "src_uid": "260666df22ee510fcce3ebdfbb8b71a2"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\ncheck a b c = and $ map ( \\(a1,b1,c1)-> a1==c1 || b1==c1) x\n\twhere x = zip3 a b c\n\n\nonecase = do\n\t\t[a,b,c]<-replicateM 3 getLine\n\t\tputStrLn $ if check a b c then \"YES\" else \"NO\"\n\t\t\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t \treplicateM_ a onecase\t\n\n", "positive_code": [{"source_code": "import Data.List (zip3)\n\nprocess :: [Char] -> [Char] -> [Char] -> Bool\nprocess as bs cs = all (\\(a,b,c) -> a==c || b==c) $ zip3 as bs cs\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n as <- getLine\n bs <- getLine\n cs <- getLine\n if process as bs cs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "solve :: String -> String -> String -> Bool\nsolve \"\" \"\" \"\" = True\nsolve (a:as) (b:bs) (c:cs) = if (c == b || c == a ) then solve as bs cs\n else False\n\nparse :: (String, String, String) -> String\nparse (a, b, c)\n | solve a b c = \"YES\"\n | otherwise = \"NO\"\n\ntakeLines :: [String] -> [(String, String, String)]\ntakeLines [] = []\ntakeLines (a:b:c:rest) = (a, b, c):takeLines rest\n\nmain :: IO ()\nmain = interact (unlines . map parse . takeLines . tail . lines)\n"}], "negative_code": [], "src_uid": "08679e44ee5d3c3287230befddf7eced"} {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (\\b -> if b then \"Yes\" else \"No\") >>> unlines\n\nprocess :: [[Int]] -> [Bool]\nprocess [] = []\nprocess ([n,a,b,c,d]:ps) = (check n a b c d) : process ps\n\ncheck n a b c d = \n c - d <= n * (a + b) && n * (a - b) <= c + d", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\ncount :: (Eq a) => a -> [a] -> Int\ncount x = length . filter (== x)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, a, b, c, d] <- getIntList\n let minW = (a - b) * n\n maxW = (a + b) * n\n minV = (c - d)\n maxV = (c + d)\n putStrLn $ yesOrNo $ not $ or [minW > maxV, maxW < minV]"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,a,b,c,d] <- (map read.words) <$> getLine\n let big = (a+b)*n :: Int\n small = (a-b)*n\n in if big < c-d || small > c+d\n then putStrLn \"No\"\n else putStrLn \"Yes\"\n"}, {"source_code": "\n\nhasOverlap :: (Int, Int) -> (Int, Int) -> Bool\nhasOverlap (a,b) (x,y)\n | a > y = False\n | b < x = False\n | otherwise = True\n\ndecorate :: Bool -> String\ndecorate True = \"YES\"\ndecorate False = \"NO\"\n\nparse :: String -> [Int]\nparse = map read . words\n\nsolve :: String -> String\nsolve s =\n hasOverlap (n*(a-b), n*(a+b)) (c-d, c+d)\n |> decorate\n where\n (n:a:b:c:d:_) = parse s\n\n\nmain :: IO ()\nmain = interact $ unlines . map solve . tail . lines\n\n\n\n\n\ninfixr 0 |>\n\n(|>) :: a -> (a -> b) -> b\n(|>) = flip ($)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\t[n,a,b,c,d]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tputStrLn $ if (a+b)*n <(c-d) || (a-b)*n >(c+d) then \"No\" else \"Yes\"\n\t\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "process :: Int -> Int -> Int -> Int -> Int -> Bool\nprocess n a b c d = (max ln lp) <= (min rn rp)\n where\n ln = n * (a - b)\n rn = n * (a + b)\n lp = c - d\n rp = c + d\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n [n,a,b,c,d] <- fmap (map readInt.words) getLine\n if process n a b c d\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,a,b,c,d] <- (map read.words) <$> getLine\n let big = (a+b)*n\n small = (a-b)*n\n in if (big <= c+d && c-d <= big) || (small <= c+d && c-d <= small)\n then putStrLn \"Yes\"\n else putStrLn \"No\"\n"}, {"source_code": "\nimport Control.Monad.ST\n\nmain = print \"hello\""}], "src_uid": "30cfce44a7a0922929fbe54446986748"} {"source_code": "expand :: String -> String\nexpand s\n\t| p !! 0 == \"\" && p !! 1 == \"\" = bindColon (map (grow (10 - (length p))) (tail p))\n\t| otherwise = bindColon (map (grow (9 - (length p))) p)\n\t\twhere p = parseColon s\n\ngrow :: Int -> String -> String\ngrow 0 []\t= \"\"\ngrow n []\t= (copyString (n - 1) \"0000:\") ++ \"0000\"\ngrow _ s\t= (copyString (4 - (length s)) \"0\") ++ s\n\ncopyString :: Int -> String -> String\ncopyString 0 s = \"\"\ncopyString n s = s ++ (copyString (n - 1) s)\n\nbindColon :: [String] -> String\nbindColon (x:(y:xs)) = x ++ \":\" ++ (bindColon (y:xs))\nbindColon (x:xs)\t= x\nbindColon _\t= \"\"\n\nparseColon :: String -> [String]\nparseColon (a:b)\n\t| null prev && a == ':'\t= [\"\"]\n\t| null prev && a /= ':'\t= [a:\"\"]\n\t| a == ':'\t\t\t\t= \"\":prev\n\t| otherwise\t\t\t\t= (a:(head prev)):(tail prev)\n\t\twhere prev = parseColon b\nparseColon _ = []\n\nprintAns :: [String] -> IO()\nprintAns (x:xs) = do\n\tputStrLn x\n\tprintAns xs\nprintAns _ = do\n\tputStr \"\"\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tprintAns (map expand (tail (words str)))\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nsplit c = map (takeWhile (/=c) . tail) . filter ((==c) . head) . init . tails . (c:)\n\nmain = do\n n <- fmap read getLine\n replicateM_ n $ do\n (a, b) <- fmap (break (==\"\") . split ':') getLine\n let b' = filter (/=\"\") b\n s = a ++ replicate (8 - length a - length b') \"\" ++ b'\n putStrLn $ intercalate \":\" $ map (until ((>=4) . length) ('0':)) s\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n ips <- fmap lines getContents\n mapM_ (putStrLn . resolveIpv6) ips\n\ndata Block = Number String | Empty\n deriving Eq\n\nresolveIpv6 ip = let blocks = split ip \"\"\n zeros = 8 - (length $ filter (/= Empty) blocks)\n in tail $ showIpv6 zeros blocks\n where\n split \"\" \"\" = []\n split \"\" b = [Number $ addZeros $ reverse b]\n split (':':ip) \"\" = Empty:(split ip \"\")\n split (':':ip) b = (Number $ addZeros $ reverse b):(split ip \"\")\n split (c:ip) b = split ip $ c:b\n addZeros b = (replicate (4 - length b) '0') ++ b\n showIpv6 _ [] = \"\"\n showIpv6 exp (Number b:xs) = \":\" ++ b ++ (showIpv6 exp xs)\n showIpv6 exp (Empty:xs) = showIpv6 0 $ (replicate exp (Number \"0000\")) ++ xs\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate, isInfixOf)\n\nsolve :: String -> String\nsolve s = intercalate \":\" $ solve' \"\" s\n where\n n = length $ filter (== ':') s\n m = if isInfixOf \"::\" s then n else n + 1\n\n solve' b \"\" = [addZero b]\n solve' b (':' : ':' : s)\n = addZero b : (replicate (8 - m) \"0000\") ++ solve' \"\" s\n solve' b (':' : s) = addZero b : solve' \"\" s\n solve' b (c : s) = solve' (b ++ [c]) s\n\n addZero s = replicate (4 - length s) '0' ++ s\n\nmain :: IO ()\nmain = do\n n <- readLn\n ls <- liftM (take n . lines) getContents\n mapM_ (putStrLn . solve) ls"}, {"source_code": "main=interact$unlines.map f.tail.lines\nf cs = tail.concatMap ff $ parse cs\n where\n g ':' = ' '\n g c = c\n n = length.words.map g $ cs\n ff \"\" = [1..8-n]>>\":0000\"\n ff ds = (':':) $ reverse $ take 4 $ reverse $ \"0000\"++ds\n\n\nparse (':':':':rest) = \"\" : parse rest\nparse (':':rest) = xs : parse ys\n where\n (xs,ys) = span (':'/=) rest\nparse \"\" = [] \nparse cs = xs : parse ys\n where\n (xs,ys) = span (':'/=) cs\n"}, {"source_code": "import Data.List\n\nsplit :: (Eq a) => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit t xs\n | b == [] = [a]\n | otherwise = a : (split t $ tail b)\n where (a, b) = break (== t) xs\n\nfoo str = concat $ intersperse \":\" $ map (\\t -> (replicate (4 - length t) '0') ++ t) $ xs'\n where xs = split ':' str\n xs' = if b == [] then a ++ (replicate (8 - length xs) \"\")\n else a ++ (replicate (9 - length xs) \"\") ++ tail b\n (a, b) = break (== \"\") xs\n\nmain = interact $ unlines . map foo . tail . lines\n"}], "negative_code": [{"source_code": "import Data.List\n\nsplit :: (Eq a) => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit t xs\n | b == [] = [a]\n | otherwise = a : (split t $ tail b)\n where (a, b) = break (== t) xs\n\nfoo str = concat $ intersperse \":\" $ map (\\t -> (replicate (4 - length t) '0') ++ t) $ xs'\n where xs = split ':' str\n xs' = a ++ (replicate (8 - length xs) \"\") ++ b\n (a, b) = break (== \"\") xs\n\nmain = interact $ unlines . map foo . tail . lines\n"}], "src_uid": "20f69ee5f04c8cbb769be3ab646031ab"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nprocess :: [Char] -> [Char] -> [(Char, Char)]\nprocess [] [] = []\nprocess [] (x: xs) = (' ' , x) : process [] xs\nprocess (x: xs) [] = (x, ' ') : process xs []\nprocess (x:xs) (y:ys)\n | x == y = process xs ys\n | otherwise = (x, y) : process xs ys\n\nmain :: IO ()\nmain = do\n\tw1 <- getLine\n\tw2 <- getLine\n\tlet\n\t\tarr = process w1 w2\n\tif length arr == 2 && fst (arr !! 0) == snd (arr !! 1) && snd (arr!!0) == fst (arr!!1) then\n\t\tputStrLn \"YES\"\n\t\telse\n\t\t\tputStrLn \"NO\"\n\t\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = printBool . solve . lines =<< getContents\n\nprintBool :: Bool -> IO()\nprintBool b = putStrLn (if b then \"YES\" else \"NO\")\n\nsolve :: [String] -> Bool\nsolve (a:b:_) | (length a) /= (length b) = False\n | otherwise = let (da:db:_) = get_diff a b [[], []]\n in (length da) == 2 && (sort da) == (sort db)\n\nget_diff :: String -> String -> [[Char]] -> [[Char]]\nget_diff [] [] d = d\nget_diff (a:ax) (b:bx) (da:db:dx) | a == b = get_diff ax bx (da:db:dx)\n | otherwise = get_diff ax bx ((a:da):(b:db):dx)\n"}, {"source_code": "solv :: [Char] -> [Char] -> Bool\nsolv x y = if length x /= length y\n then False \n else let tmp = filter (\\(x, y) -> x /= y) $ zip x y in\n if length tmp /= 2 then False else\n let [(x1, y1), (x2, y2)] = tmp in\n (x1 == y2) && (x2 == y1) \n\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ if solv a b then \"YES\" else \"NO\"\n\n"}, {"source_code": "solve a b\n | length a == length b = let c = zip a b\n d = filter (\\(x, y) -> x /= y) c\n in case d of\n [(a, b), (c, d)] -> a == d && b == c\n otherwise -> False\n | otherwise = False\n\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ if solve a b then \"YES\" else \"NO\"\n"}, {"source_code": "\n{-\nimport HUnit\n\ntestSmallString = Test \"TestSmallString\" $ assertFalse (solve \"a\" \"b\") \n\ntestInput1 = Test \"TestInput 1\" $ assertTrue (solve \"ab\" \"ba\")\n\ntestInput2 = Test \"TestInput 2\" $ assertFalse (solve \"aa\" \"ab\")\n\ntestDiffLength = Test \"TestDiffLength\" $ assertFalse (solve \"ab\" \"baa\")\n\ntest = mapM_ run\n [\n testSmallString,\n testInput1,\n testInput2,\n testDiffLength\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: String -> String -> Bool\nsolve a b\n | length a == length b = solve' diff\n | otherwise = False\n where\n diff = getDiff a b\n getDiff [] [] = []\n getDiff (a:as) (b:bs)\n | a == b = getDiff as bs\n | a /= b = (a,b) : getDiff as bs\n solve' [(a1, b1), (a2, b2)] = a1 == b2 && b1 == a2\n solve' _ = False\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn (if solve a b then \"YES\" else \"NO\")\n"}, {"source_code": "import Data.Char\nimport Data.List\n \ncount :: String -> Char -> Int\ncount s c = length $ filter (\\x -> x == c) s\n\ncs :: String -> String -> Bool\ncs s1 s2 = cs' s1 s2 'a' 'z'\n\ncs' :: String -> String -> Char -> Char -> Bool\ncs' s1 s2 c to = if c > to then True else\n if (count s1 c) /= (count s2 c) then False else\n cs' s1 s2 (toEnum ((fromEnum c) + 1)) to\n\nbad :: String -> String -> Int\nbad [] [] = 0\nbad [] s = 10\nbad s [] = 10\nbad s t = (bad (tail s) (tail t)) + (if (head s) == (head t) then 0 else 1)\n\nsolve :: String -> String -> String\nsolve s1 s2 = if ((bad s1 s2) <= 2) && (cs s1 s2) then \"YES\" else \"NO\" \n\nmain = do s1 <- getLine\n s2 <- getLine\n putStrLn $ solve s1 s2"}, {"source_code": "main=interact$solve.lines\n\nswap (x,y) = (y,x)\n\nsolve :: [String] -> String\nsolve [xs,ys]\n | lx /= ly = \"NO\"\n | length diff /= 2 = \"NO\"\n | swap(diff!!0) == diff!!1 = \"YES\"\n | otherwise = \"NO\"\n where lx = length xs\n ly = length ys\n diff = filter (\\(x,y) -> x/=y) $ zip xs ys\n"}, {"source_code": "solve :: String -> String -> String\nsolve [] [] = \"NO\"\nsolve gen1 gen2 = \n let\n diffs = filter (\\xs -> length xs > 0) $ zipWith (\\g1 g2 -> if g1 /= g2 then [g1,g2] else []) gen1 gen2\n lens = length gen1 - length gen2\n in\n if lens /= 0 || length diffs /= 2\n then \"NO\" \n else \n let\n (a:b:_) = diffs\n in\n if reverse b == a then \"YES\" else \"NO\"\n\nmain = \n do\n gen1 <- getLine\n gen2 <- getLine\n putStrLn $ solve gen1 gen2\n"}, {"source_code": "pairCmp :: Eq a => (a,a) -> (a,a) -> Bool\npairCmp x y = fst x == snd y && snd x == fst y\n\nisOk :: Eq b => [(a,(b,b))] -> Bool\nisOk pairs\n | l == 0 = True\n\t| l == 2 = x `pairCmp` y\n\t| otherwise = False\n where\n l = length pairs\n x = snd $ pairs !! 0\n y = snd $ pairs !! 1\n\nequal :: Char -> Char -> (Bool, (Char, Char))\nequal x y = (x == y, (x, y))\n\ncmp :: String -> String -> Bool\ncmp a b\n | length a == length b = isOk . filter (not . fst) $ zipWith equal a b\n | otherwise = False\n\nboolToStr :: Bool -> String\nboolToStr x = if x then \"YES\" else \"NO\"\n\nmain = do\n\ta <- getLine\n\tb <- getLine\n\tputStrLn $ boolToStr $ cmp a b"}, {"source_code": "import Data.Tuple \n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ solve a b\n\nsolve :: String -> String -> String\nsolve xs ys \n | lx /= ly = \"NO\"\n | length diff /= 2 = \"NO\"\n | swap(diff !! 0) == diff !! 1 = \"YES\"\n | otherwise = \"NO\"\n where\n lx = length xs\n ly = length ys\n diff = filter (\\(x, y) -> x/= y) $ zip xs ys\n\n"}, {"source_code": "import Data.Function\nimport Data.List\nsolve x y =\n (length x == length y) && (verify $ foldl folder [] (zip x y))\n where\n folder acc (a, b) = if a == b \n then acc\n else (a,b):acc\n verify [] = True\n verify [(a,b), (c,d)] = (a == d) && (b == c)\n verify _ = False\n\n\npprint True = \"YES\"\npprint False = \"NO\"\n\nmain = do \n foo <- getContents\n let bar = lines foo\n putStrLn . pprint $ solve (bar !! 0) (bar !! 1)"}], "negative_code": [{"source_code": "import Data.Tuple \n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ solve a b\n\nsolve :: String -> String -> String\nsolve xs ys \n | lx /= ly = \"NO\"\n | length diff /= 2 = \"NO\"\n | swap(diff !! 0) == diff !! 1 = \"YES\"\n | otherwise = \"NO\"\n where\n lx = length xs\n ly = length xs\n diff = filter (\\(x, y) -> x/= y) $ zip xs ys\n\n"}, {"source_code": "import Data.Function\nimport Data.List\nsolve x y =\n (length x == length y) && or [cnt == 0, cnt == 2]\n where\n cnt = sum [if a /= b then 1 else 0 | (a, b) <- zip x y]\n\npprint True = \"YES\"\npprint False = \"NO\"\n\nmain = do \n foo <- getContents\n let bar = lines foo\n putStrLn . pprint $ solve (bar !! 0) (bar !! 1)"}, {"source_code": "import Data.Function\nimport Data.List\nsolve = ((==) `on` sort)\n\npprint True = \"YES\"\npprint False = \"NO\"\n\nmain = do \n foo <- getContents\n let bar = lines foo\n putStrLn . pprint $ solve (bar !! 0) (bar !! 1)"}, {"source_code": "import Data.Function\nimport Data.List\nsolve x y =\n or [cnt == 0, cnt == 2]\n where\n cnt = sum [if a /= b then 1 else 0 | (a, b) <- zip x y]\n\npprint True = \"YES\"\npprint False = \"NO\"\n\nmain = do \n foo <- getContents\n let bar = lines foo\n putStrLn . pprint $ solve (bar !! 0) (bar !! 1)"}], "src_uid": "c659bdeda1c1da08cfc7f71367222332"} {"source_code": "\nimport Control.Monad (liftM2)\nimport Data.List (isPrefixOf)\n\nimport Control.Monad (foldM_)\nimport Data.Ix (Ix)\nimport Data.Array.MArray (MArray, newArray, readArray, writeArray)\nimport Data.Array.ST (runSTUArray)\nimport Data.Array.Unboxed (UArray, (!), bounds, elems, listArray)\n\n(?) True = const\n(?) _ = flip const\n\nzFunction :: String -> UArray Int Int\nzFunction s' = runSTUArray $ do\n z <- newArray (1, n) 0\n writeArray z 1 n\n foldM_ (iter z) (1, 1) [2..n]\n return z\n where\n n = length s'\n s = listArray (1, n) s' :: UArray Int Char\n iter z (l, r) i = do\n zil <- readArray z (i - l + 1)\n let z0 = (i > r) ? 0 $ min (r - i + 1) zil\n \n let zi = head $ dropWhile (\\j -> i + j <= n && s ! (j + 1) == s ! (i + j)) [z0..]\n writeArray z i zi\n return $ (i + zi - 1 > r) ? (i, i + zi - 1) $ (l, r)\n\nsolve :: String -> String -> Int\nsolve s1 s2\n | s1 `isPrefixOf` s2 || s2 `isPrefixOf` s1 = length $ filter dividerS [1 .. min n1 n2]\n | otherwise = 0\n where\n n1 = length s1\n n2 = length s2\n z1 = zFunction s1\n z2 = zFunction s2\n dividerS i = dividerS1 i && dividerS2 i\n dividerS1 i = i == n1\n || n1 `mod` i == 0 && z1 ! (i + 1) == (n1 - i)\n dividerS2 i = i == n2\n || n2 `mod` i == 0 && z2 ! (i + 1) == (n2 - i)\n\nmain :: IO ()\nmain = do\n liftM2 solve getLine getLine >>= print\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array.IO\nimport Data.IORef\nimport Data.List\ncheck s l =\n let (s1, s2) = splitAt l s\n in null s2 || (isPrefixOf s1 s2 && check s2 l)\nmain = do\n s1 <- getLine\n s2 <- getLine\n let g = gcd (length s1) (length s2)\n arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)\n cnt <- newIORef 0\n forM_ [1..g] $ \\i -> do\n v <- readArray arr i\n if v == -1 && g `mod` i == 0 && check s1 i && check s2 i && take i s1 == take i s2\n then let g' = g `div` i\n in forM_ [1..g'] $ \\j -> writeArray arr (i*j) $ if g' `mod` j == 0 then 1 else 0\n else when (v == -1) $ writeArray arr i 0\n readArray arr i >>= \\j -> modifyIORef cnt (+j)\n readIORef cnt >>= print\n"}, {"source_code": "\nimport Control.Monad (liftM2)\nimport Data.List (isPrefixOf)\n\nimport Control.Monad (foldM_, when)\nimport Data.Ix (Ix)\nimport Data.Array.MArray (MArray, newArray, readArray, writeArray)\nimport Data.Array.ST (runSTUArray)\nimport Data.Array.Unboxed (UArray, (!), bounds, elems, listArray)\n\nwhile :: Monad m => m Bool -> m () -> m ()\nwhile condition action = do\n c <- condition\n when c $ do\n action\n while condition action\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f = do\n e <- readArray a i\n writeArray a i (f e)\n\nzFunction :: String -> UArray Int Int\nzFunction s' = runSTUArray $ do\n z <- newArray (1, n) 0\n writeArray z 1 n\n foldM_ (iter z) (1, 1) [2..n]\n return z\n where\n n = length s'\n s = listArray (1, n) s' :: UArray Int Char\n iter z (l, r) i = do\n when (i <= r) $ do\n zil <- readArray z (i-l+1)\n writeArray z i (min zil (r-i+1))\n while (condition z i) $ modifyArray z i (+1)\n zi <- readArray z i\n if (i + zi - 1 > r) then\n return (i, i + zi - 1)\n else\n return (l, r)\n condition z i = do\n zi <- readArray z i\n return (i + zi <= n && s ! (zi + 1) == s ! (i + zi))\n\nsolve :: String -> String -> Int\nsolve s1 s2\n | s1 `isPrefixOf` s2 || s2 `isPrefixOf` s1 = length $ filter dividerS [1 .. min n1 n2]\n | otherwise = 0\n where\n n1 = length s1\n n2 = length s2\n z1 = zFunction s1\n z2 = zFunction s2\n dividerS i = dividerS1 i && dividerS2 i\n dividerS1 i = i == n1\n || n1 `mod` i == 0 && z1 ! (i + 1) == (n1 - i)\n dividerS2 i = i == n2\n || n2 `mod` i == 0 && z2 ! (i + 1) == (n2 - i)\n\nmain :: IO ()\nmain = do\n liftM2 solve getLine getLine >>= print\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array.IO\nimport Data.IORef\nimport Data.List\ncheck s l =\n let (s1, s2) = splitAt l s\n in null s2 || (isPrefixOf s1 s2 && check s2 l)\nmain = do\n s1 <- getLine\n s2 <- getLine\n let g = gcd (length s1) (length s2)\n arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)\n cnt <- newIORef 0\n forM_ [1..g] $ \\i -> do\n v <- readArray arr i\n if v == -1 && g `mod` i == 0 && check s1 i && check s2 i && head s1 == head s2\n then let g' = g `div` i\n in forM_ [1..g'] $ \\j -> writeArray arr (i*j) $ if g' `mod` j == 0 then 1 else 0\n else when (v == -1) $ writeArray arr i 0\n readArray arr i >>= \\j -> modifyIORef cnt (+j)\n readIORef cnt >>= print\n"}, {"source_code": "import Control.Monad\nimport Data.Array.IO\nimport Data.IORef\nimport Data.List\ncheck s l =\n let (s1, s2) = splitAt l s\n in null s2 || (isPrefixOf s1 s2 && check s2 l)\nmain = do\n s1 <- getLine\n s2 <- getLine\n let g = gcd (length s1) (length s2)\n arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)\n cnt <- newIORef 0\n forM_ [1..g] $ \\i -> do\n v <- readArray arr i\n if v == -1 && g `mod` i == 0 && check s1 i && check s2 i\n then let g' = g `div` i\n in forM_ [1..g'] $ \\j -> writeArray arr (i*j) $ if g' `mod` j == 0 then 1 else 0\n else when (v == -1) $ writeArray arr i 0\n readArray arr i >>= \\j -> modifyIORef cnt (+j)\n readIORef cnt >>= print\n"}, {"source_code": "\nimport Control.Monad (liftM2, foldM_, when)\nimport Data.Ix (Ix)\nimport Data.Array.MArray (MArray, newArray, readArray, writeArray)\nimport Data.Array.ST (runSTUArray)\nimport Data.Array.Unboxed (UArray, (!), bounds, elems, listArray)\n\nwhile :: Monad m => m Bool -> m () -> m ()\nwhile condition action = do\n c <- condition\n when c $ do\n action\n while condition action\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f = do\n e <- readArray a i\n writeArray a i (f e)\n\nzFunction :: String -> UArray Int Int\nzFunction s' = runSTUArray $ do\n z <- newArray (1, n) 0\n writeArray z 1 n\n foldM_ (iter z) (1, 1) [2..n]\n return z\n where\n n = length s'\n s = listArray (1, n) s' :: UArray Int Char\n iter z (l, r) i = do\n when (i <= r) $ do\n zil <- readArray z (i-l+1)\n writeArray z i (min zil (r-i+1))\n while (condition z i) $ modifyArray z i (+1)\n zi <- readArray z i\n if (i + zi - 1 > r) then\n return (i, i + zi - 1)\n else\n return (l, r)\n condition z i = do\n zi <- readArray z i\n return (i + zi <= n && s ! (zi + 1) == s ! (i + zi))\n\nsolve :: String -> String -> Int\nsolve s1 s2 = length $ filter dividerS [1 .. min n1 n2]\n where\n n1 = length s1\n n2 = length s2\n z1 = zFunction s1\n z2 = zFunction s2\n dividerS i = dividerS1 i && dividerS2 i\n dividerS1 i = i == n1\n || n1 `mod` i == 0 && z1 ! (i + 1) == (n1 - i)\n dividerS2 i = i == n2\n || n2 `mod` i == 0 && z2 ! (i + 1) == (n2 - i)\n\nmain :: IO ()\nmain = liftM2 solve getLine getLine >>= print\n"}, {"source_code": "import Control.Monad\nimport Data.Array.IO\nimport Data.IORef\nimport Data.List\ncheck s l =\n let (s1, s2) = splitAt l s\n in null s2 || (isPrefixOf s1 s2 && check s2 l)\nmain = do\n s1 <- getLine\n s2 <- getLine\n let g = gcd (length s1) (length s2)\n arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)\n cnt <- newIORef 0\n forM_ [1..g] $ \\i -> do\n v <- readArray arr i\n if v == -1 && g `mod` i == 0 && check s1 i && check s2 i\n then forM_ [1..(g `div` i)] $ \\j -> writeArray arr (i*j) 1\n else when (v == -1) $ writeArray arr i 0\n readArray arr i >>= \\j -> modifyIORef cnt (+j)\n readIORef cnt >>= print\n"}], "src_uid": "d28614f0365ea53530e35c6bd1e6f1dd"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n max' l' (l, c)\n | l' > l = (l', 1)\n | l == l' = (l, c+1)\n | otherwise = (l, c)\n\n scan _ [] _ m = m\n scan i ('(':s) st m = scan (i+1) s (i:st) m\n scan i (')':s) [_] m = scan (i+1) s [i] m\n scan i (')':s) (_:j:st) m = scan (i+1) s (j:st) $ max' (i-j) m\n\n (l, c) = scan 1 s [0] (0, 1)\n\n putStrLn $ show l ++ \" \" ++ show c\n", "positive_code": [{"source_code": "import Data.List\ndata St = Open | Close | Sub Int \nred st [] = \n let nList = map (\\(Sub x) -> x) $ filter (\\x -> case x of {Sub _ -> True; _ -> False}) st in\n case nList of\n [] -> [0, 1]\n _ -> let (s:_) = group $ sortBy (flip compare) nList in [head s, length s]\nred st ('(':inpStr) = red (Open:st) inpStr\nred (Sub n:Open:Sub n1:st) (')':inpStr) = red (Sub (n+n1+2):st) inpStr\nred (Sub n:Open:st) (')':inpStr) = red (Sub (n+2):st) inpStr\nred (Open:Sub n:st) (')':inpStr) = red (Sub (n+2):st) inpStr\nred (Open:st) (')':inpStr) = red (Sub 2:st) inpStr\nred st (')':inpStr) = red (Close:st) inpStr\nmain = (unwords . map show . red []) `fmap` getLine >>= putStrLn\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\ntype Index = Int\ntype Depth = Int\ntype Stack = (Depth, Depth, [Index])\ntype State = (Stack, (Int, Int))\n\npush :: Index -> State -> State\npush i ((d, e, is), best)\n | d == e = ((d', d', i : is), best)\n | otherwise = ((d', e, is), best)\n where d' = d + 1\n\npop :: Index -> State -> State\npop i ((!d, !e, is), best@(!longest, !count))\n | d == 0 = ((0, 0, []), best)\n | otherwise = (,) (d - 1, d, is') $ case compare l longest of\n LT -> best\n EQ -> fmap succ best\n GT -> (l, 1)\n where is' = drop (e - d) is\n l = i - head is' + 1\n\nautomata :: State -> (Index, Char) -> State\nautomata state (i, c)\n | c == '(' = push i state\n | otherwise = pop i state\n\nsolve :: String -> IO ()\nsolve = uncurry (printf \"%d %d\\n\")\n . snd . foldl automata ((0, 0, []), (0, 1)) . zip [0 ..]\n\nmain :: IO ()\nmain = getLine >>= solve\n\n"}, {"source_code": "module Main where\n\nimport Data.List (foldl')\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve input = show len <> \" \" <> show count\n where\n states = foldl' toState [] input\n (len, count) = foldl' foldBest (0, 1) states\n\ndata State = Open | Close | Replace !Int deriving (Show)\n\nfoldBest :: (Int, Int) -> State -> (Int, Int)\nfoldBest (l, c) (Replace k) | l == k = (k, c + 1)\nfoldBest (l, c) (Replace k) | l < k = (k, 1)\nfoldBest s _ = s\n\ntoState :: [State] -> Char -> [State]\ntoState s '(' = Open:s\ntoState (Replace k:Open:Replace n:s) ')' = Replace (k + n + 2):s\ntoState (Open:Replace n:s) ')' = Replace (n + 2):s\ntoState (Replace n:Open:s) ')' = Replace (n + 2):s\ntoState (Open:s) ')' = Replace 2:s\ntoState s ')' = Close:s\ntoState s _ = s"}, {"source_code": "import Text.Printf\n\nmain = do\n line <- getLine\n putStrLn . (\\(opt,cnt,_,_,_) -> printf \"%d %d\" (opt::Int) (cnt::Int))\n . foldl (\\(opt,cnt,b,s,i) c ->\n if c == '(' then\n (opt,cnt,b,i:s,i+1)\n else if null s then\n (opt,cnt,i,[],i+1)\n else let s' = tail s\n opt' = i - (if null s' then b else head s')\n in if opt' > opt then\n (opt',1,b,s',i+1)\n else\n (opt,cnt+(if opt' == opt then 1 else 0),b,s',i+1)\n ) (0,1,-1,[],0) $ line"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n max' l' (l, c)\n | l' > l = (l', 1)\n | l == l' = (l, c+1)\n | otherwise = (l, c)\n\n scan i [] [0] m = max' (i-1) m\n scan _ [] _ m = m\n scan i ('(':s) st m = scan (i+1) s (i:st) m\n scan i (')':s) [] m = scan (i+1) s [] m\n scan i (')':s) (j:st) m = scan (i+1) s st $ max' (i-j+1) m\n\n (l, c) = scan 1 s [0] (0, 1)\n\n putStrLn $ show l ++ \" \" ++ show c\n \n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n max' l' (l, c)\n | l' > l = (l', 1)\n | l == l' = (l, c+1)\n | otherwise = (l, c)\n\n scan [] _ l m = m\n scan (c:s) d l m\n | d' < 0 = scan s 0 0 m\n | d' == 0 = scan s d' (l+1) $ max' (l+1) m\n | otherwise = scan s d' (l+1) m\n where\n d' = d + if c == '(' then 1 else -1\n\n (l, c) = scan s 0 0 (0, 1)\n\n putStrLn $ show l ++ \" \" ++ show c\n \n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n max' l' (l, c)\n | l' > l = (l', 1)\n | l == l' = (l, c+1)\n | otherwise = (l, c)\n\n scan _ [] _ m = m\n scan i ('(':s) st m = scan (i+1) s (i:st) m\n scan i (')':s) [] m = scan (i+1) s [] m\n scan i (')':s) (j:st) m = scan (i+1) s st $ max' (i-j+1) m\n\n (l, c) = scan 1 s [] (0, 1)\n\n putStrLn $ show l ++ \" \" ++ show c\n \n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\ntype Index = Int\ntype Longest = Int\ntype Count = Int\ntype State = ([Index], (Longest, Count))\n\nautomata :: State -> (Index, Char) -> State\nautomata state@(stack, best) (i, c)\n | c == '(' = (i : stack, best)\n | null stack = state\n | otherwise = update state i\n\nupdate :: State -> Index -> State\nupdate (j : stack, best@(longest, _)) i =\n case compare l longest of\n LT -> (stack, best)\n EQ -> (stack, fmap succ best)\n GT -> (stack, (l, 1))\n where l = i - j + 1\n\nexec :: String -> (Longest, Count)\nexec = snd . foldl' automata ([], (0, 1)) . zip [0 ..]\n\nsolve :: String -> IO ()\nsolve = do\n (v, n) <- exec\n return $ printf \"%d %d\\n\" v n\n\nmain = getLine >>= solve\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\ntype Depth = Int\ntype Score = Int\ntype Count = Int\ntype State = ((Depth, Score), (Score, Count))\n\nupdateBest :: State -> State\nupdateBest (state@(d, s), best@(v, n))\n | s < v || s == 0 = (state, best)\n | s == v = (state, (v, n + 1))\n | s > v = (state, (s, 1))\n\nautomata :: State -> Char -> State\nautomata ((d, s), best@(v, n)) c\n | c == '(' = ((d + 1, s), best)\n | d > 0 = updateBest ((d - 1, s + 2), best)\n | d == 0 = updateBest ((0, 0), best)\n | d < 0 = error \"automata: Never happens!\"\n where\n\nexec :: String -> (Score, Count)\nexec = snd . foldl' automata ((0, 0), (0, 1))\n\nsolve :: String -> IO ()\nsolve = do\n (v, n) <- exec\n return $ printf \"%d %d\\n\" v n\n\nmain = getLine >>= solve\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\ntype Depth = Int\ntype Score = Int\ntype Count = Int\ntype State = ((Depth, Score), (Score, Count))\n\nautomata :: State -> Char -> State\nautomata ((d, s), best@(v, n)) c\n | c == '\\0' = updateBest\n | c == '(' = ((d + 1, s), best)\n | d > 0 = ((d - 1, s + 2), best)\n | d == 0 = updateBest\n | d < 0 = error \"automata: Never happens!\"\n where\n updateBest\n | s < v || s == 0 = ((0, 0), best)\n | s == v = ((0, 0), (v, n + 1))\n | s > v = ((0, 0), (s, 1))\n\nexec :: String -> (Score, Count)\nexec = snd . (`automata` '\\0') . foldl' automata ((0, 0), (0, 1))\n\nsolve :: String -> IO ()\nsolve = do\n (v, n) <- exec\n return $ printf \"%d %d\\n\" v n\n\nmain = getLine >>= solve\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\ntype Index = Int\ntype Longest = Int\ntype Count = Int\ntype State = ([Index], (Longest, Count))\n\nautomata :: State -> (Index, Char) -> State\nautomata state@(stack, best) (i, c)\n | c == '(' = (i : stack, best)\n | null stack = state\n | otherwise = update state i\n\nupdate :: State -> Index -> State\nupdate (j : stack, best@(longest, _)) i =\n case compare l longest of\n LT -> (stack, best)\n EQ -> (stack, fmap succ best)\n GT -> (stack, (l, 1))\n where l = i - j + 1\n\nexec :: String -> (Longest, Count)\nexec = snd . foldl' automata ([], (0, 1)) . zip [0 ..]\n\nsolve :: String -> IO ()\nsolve = do\n (v, n) <- exec\n return $ printf \"%d %d\\n\" v n\n\nmain = getLine >>= solve\n\n\n"}, {"source_code": "import Text.Printf\n\nmain = do\n line <- getLine\n putStrLn . (\\(opt,cnt,_,_,_) -> printf \"%d %d\" (opt::Int) (cnt::Int))\n . foldl (\\(opt,cnt,b,s,i) c ->\n if c == '(' then\n (opt,cnt,b,i:s,i+1)\n else if null s then\n (opt,cnt,i,[],i+1)\n else let s' = tail s\n opt' = i - (if null s' then b else head s')\n in if opt' > opt then\n (opt',1,b,s',i+1)\n else\n (opt,cnt+(if opt' == opt then 1 else 0),b,s',i+1)\n ) (0,0,-1,[],0) $ line"}, {"source_code": "module Main where\n\nimport Data.List (foldl')\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve input = show len <> \" \" <> show count\n where\n states = foldl' toState [] input\n (len, count) = foldl' foldBest (0, 1) states\n\ndata State = Open | Close | Replace !Int\n\nfoldBest :: (Int, Int) -> State -> (Int, Int)\nfoldBest (l, c) (Replace k) | l == k = (k, c + 1)\nfoldBest (l, c) (Replace k) | l < k = (k, 1)\nfoldBest s _ = s\n\ntoState :: [State] -> Char -> [State]\ntoState s '(' = Open:s\ntoState (Replace k:Open:Replace n:s) _ = Replace (k + n + 2):s\ntoState (Open:Replace n:s) _ = Replace (n + 2):s\ntoState (Replace n:Open:s) _ = Replace (n + 2):s\ntoState (Open:s) _ = Replace 2:s\ntoState s _ = Close:s\n"}], "src_uid": "91c3af92731cd7d406674598c0dcbbbc"} {"source_code": "import Control.Monad\nimport Data.List\n\n\ncalc :: Int -> [String]\ncalc 1 = [\"()\"]\ncalc 2 = [\"()()\",\"(())\"]\ncalc n =\n let prev = calc (n-1)\n first = head prev\n s1 = map (\\x -> \"()\" ++ x) $ prev\n in\n (\"(\" ++ first ++ \")\"):s1\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n forM_ (calc n) $ \\a -> do\n putStrLn a\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_, replicateM)\r\n \r\nouter 0 = \"\"\r\nouter 1 = \"()\"\r\nouter n = \"()\" ++ outer (n - 1)\r\n\r\nnested 0 = \"\"\r\nnested 1 = \"()\"\r\nnested n = \"(\" ++ nested (n - 1) ++ \")\"\r\n\r\nsolve :: IO ()\r\nsolve = do \r\n n <- getLine\r\n let m = read n :: Int\r\n let res = map (\\x -> outer x ++ nested (m - x) ) [0..m-1]\r\n putStr $ unlines res \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine\r\n replicateM_ (read t :: Int) solve\r\n"}, {"source_code": "import Control.Monad (replicateM_, replicateM)\r\n \r\nouter 0 = \"\"\r\nouter 1 = \"()\"\r\nouter n = \"()\" ++ outer ( n - 1 )\r\n\r\nnested 0 = \"\"\r\nnested 1 = \"()\"\r\nnested n = \"(\" ++ nested (n - 1) ++ \")\"\r\n\r\nsolve :: IO ()\r\nsolve = do \r\n\tn <- getLine\r\n\tlet m = (read n :: Int)\r\n\tlet res = map (\\x -> (outer x) ++ (nested(m - x))) [0..m-1]\r\n\tputStr ( unlines res )\r\n\r\nmain :: IO ()\r\nmain = do\r\n\tt <- getLine\r\n\treplicateM_ (read t :: Int) solve\r\n"}, {"source_code": "import Control.Monad ( replicateM_ ) \r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn \r\n let build i = replicate i '(' ++ take (2 * (n - i)) (cycle \"()\") ++ replicate i ')'\r\n putStr $ unlines $ map build [0..n-1]\r\n \r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve"}, {"source_code": "main = interact $ unlines . concatMap (solve . read) . drop 1 . lines\r\n\r\nsolve :: Int -> [String]\r\nsolve 0 = []\r\nsolve 1 = [\"()\"]\r\nsolve n = take n $ map (\"()\"++) base ++ map (\\c -> \"(\" ++ c ++ \")\") base\r\n where base = solve $ n - 1\r\n"}, {"source_code": "module Main where\n\nmain = interact $ concatMap solve . tail . lines\n\nsolve s = unlines $ take n $ paren n\n where\n n = read s :: Int\n\nparen 0 = [\"\"]\nparen n = [ \"(\" ++ x ++ \")\" ++ y\n | m <- [0..n-1] , x <- paren m , y <- paren (n-1-m) ]\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn\r\n let build i = replicate i '(' ++ take (2 * (n - i)) (cycle \"()\") ++ replicate i ')'\r\n putStr $ unlines $ map build [0 .. n - 1]\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport Data.ByteString.Lazy.Char8 (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq, ViewL (..), ViewR (..), (<|),\n (|>))\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Data.Tree\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nreadB = C.unpack >>> read\n\nmain = C.interact $\n C.lines >>> drop 1 >>> concatMap (readB >>> solve) >>> C.unlines\n\nbracketSeqs 0 = [\"\"]\nbracketSeqs n =\n [ \"(\" ++ s1 ++ \")\" ++ s2\n | k <- [0 .. n-1]\n , s1 <- bracketSeqs k\n , s2 <- bracketSeqs (n - k - 1)\n ]\n\nsolve n = map C.pack . take n $ bracketSeqs n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\n\ncalc :: Int -> [String]\ncalc 1 = [\"()\"]\ncalc 2 = [\"()()\",\"(())\"]\ncalc 3 = [\"()()()\",\"(())()\",\"(()()())\"]\ncalc n =\n let prev = calc (n-1)\n first = head prev\n s1 = map (\\x -> \"()\" ++ x) $ prev\n in\n (\"(\" ++ first ++ \")\"):s1\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n forM_ (calc n) $ \\a -> do\n putStrLn a\n"}], "src_uid": "27b73a87fc30c77abb55784e2e1fde38"} {"source_code": "import Control.Monad\nimport Data.Bool\n-- import Data.List\n\nsolve :: IO ()\nsolve = do\n as <- map read . words <$> getLine\n let cnt = sum [x `rem` 2 | x <- as] in\n putStrLn $ bool \"No\" \"Yes\" $ (((minimum $ take 3 as) > 0 && cnt /= 2) || cnt <= 1)\n\nmain :: IO ()\nmain = do\n getLine >>= flip replicateM_ solve . read\n ", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = do\n\tt <- readInt\n\tmapM_ putStrLn =<< replicateM t solve\n\nsolve = do\n\trgbw@[ r, g, b, w ] <- readInts\n\treturn $ if check rgbw || check ( map pred [ r, g, b ] ++ [ w + 3 ] )\n\t\tthen \"Yes\"\n\t\telse \"No\"\n\ncheck rgbw = all ( 0 <= ) rgbw && length ( ( filter odd ) rgbw ) <= 1"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Bits\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\n\nmain = do\n t <- read @Int <$> getLine\n replicateM_ t $ do\n a@[r, g, b, w] <- map (read @Int) . words <$> getLine\n let t = if 0 `elem` [r, g, b]\n then ch a\n else ch a || ch [r - 1, g - 1, b - 1, w + 3]\n putStrLn $ if t then \"Yes\" else \"No\"\n where ch = (<= 1) . length . filter odd\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = do\n\tt <- readInt\n\tmapM_ putStrLn =<< replicateM t solve\n\nsolve = do\n\trgbw <- readInts\n\treturn $ if check rgbw || check ( map pred rgbw )\n\t\tthen \"Yes\"\n\t\telse \"No\"\n\ncheck rgbw = all ( 0 <= ) rgbw && length ( ( filter odd ) rgbw ) <= 1"}], "src_uid": "749a106d462555543c91753f00a5a479"} {"source_code": "import qualified Data.List as L\n\n\nvalid :: (Char, Char) -> String -> Bool\nvalid _ \"\" = True\nvalid (a,b) (s:ss)\n | s == a || s == b = valid (a,b) ss\n | otherwise = False\n\ntotSize :: (Char,Char) -> [String] -> Int\ntotSize c ss = sum $ map length $ filter (valid c) ss\n\nsolve :: [String] -> Int\nsolve ss = maximum [totSize (a,b) ss | a <- ['a'..'z'], b<- ['a'..'z']]\n\n\nmain :: IO ()\nmain = interact $ show . solve . tail . lines", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . words =<< getContents\n\nchars :: [Char]\nchars = ['a'..'z']\n\nsolve :: [String] -> Int\nsolve strs = last $ sort $ map (countNum (filter (\\s -> (numOfDChar s) <= 2) strs)) [(x, y) | x <- chars, y <- chars]\n\nnumOfDChar :: String -> Int\nnumOfDChar s = sum $ map (\\c -> if elem c s then 1 else 0) chars\n\ncountNum :: [String] -> (Char, Char) -> Int\ncountNum fed (x, y) = sum $ map length $ filter (\\s -> and (map (\\c -> c == x || c == y) s)) fed\n"}, {"source_code": "import Control.Monad\n\npairs = [(x, y)| x<-['a'..'z'], y<-['a'..'z'], x<=y]\n\narticle inp (f,s) = filter (not.any (\\x->x /= f && x/=s)) inp\n\ncost :: [[a]] -> Int\ncost = length . concat\n\nmain = getLine >>= (flip replicateM $ getLine) . read >>= putStrLn . show . maximum . (map cost) . (\\x -> (map (article x) pairs))"}, {"source_code": "import Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST.Safe\n\n-- getInts = fmap (map read . words) getLine\n\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n\n let\n count a b = sum $ map length $ filter (all (\\c -> c == a || c == b)) ss\n\n print $ maximum [count a b | a <- ['a'..'z'], b <- ['a'..'z'], a /= b]\n"}, {"source_code": "solve :: [String] -> Int \nsolve words = maximum [sum . map length . filter (all (\\c -> c == a || c == b)) $ words | a <- ['a'..'z'], b <- ['a'..'z']]\n\nmain :: IO ()\nmain = do\n input <- getContents\n let words = tail . lines $ input\n putStrLn $ show . solve $ words"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport qualified Data.List as L \nimport Control.Applicative \nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\nisOk::String -> String -> Bool\nisOk cs s = and $ map (\\x -> elem x cs) s\nmain = do\n n <- getLine\n ss <- lines <$> getContents\n let l = map length ss\n let allp = [a:b:[]|a<-['a'..'z'],b<-['a'..'z'],a/=b]\n print $ L.maximum [sum $ zipWith (\\x y -> if x then y else 0) [isOk s a | a <- ss] l |s<-allp]\n \n"}, {"source_code": "import Control.Monad\n\ncontainsOnly :: String -> Char -> Char -> Bool\ncontainsOnly word c1 c2 = and[c == c1 || c == c2 | c <- word]\n\nsolve :: [String] -> Char -> Char -> Int\nsolve words c1 c2\n | c1 == 'z' && c2 == 'z' = result\n | otherwise = max result (solve words next_c1 next_c2)\n where\n result = sum [length word | word <- words, containsOnly word c1 c2 == True]\n next_c1 = if c2 == 'z' then succ c1 else c1\n next_c2 = if c2 == 'z' then 'a' else succ c2\n\nmain = do\n line <- getLine\n\n let n = read line :: Int\n words <- forM [1..n] (\\a -> getLine)\n\n print (solve words 'a' 'a')\n"}, {"source_code": "type Input = [String]\ntype Output = Int\n\nparse :: String -> Input\nparse = tail . lines\n\nchars :: String\nchars = ['a'..'z']\n\nsolve :: Input -> Output\nsolve ws = maximum [sum . map length . filter (all (\\c -> c == a || c == b)) $ ws | a <- chars, b <- chars]\n\nformat :: Output -> String\nformat = show\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}], "negative_code": [{"source_code": "import Control.Monad\n\npairs = [(x, y)| x<-['a'..'z'], y<-['a','z'], x<=y]\n\narticle inp (f,s) = filter (not.any (\\x->x /= f && x/=s)) inp\n\ncost :: [[a]] -> Int\ncost = length . concat\n\nmain = getLine >>= (flip replicateM $ getLine) . read >>= putStrLn . show . maximum . (map cost) . (\\x -> (map (article x) pairs))"}, {"source_code": "import Control.Monad\n\npairs = [(x, y)| x<-['a'..'z'], y<-['a','z'], x<=y]\n\narticle inp (f,s) = filter (not.any (\\x->x == f || x==s)) inp\n\ncost :: [[a]] -> Int\ncost = length . concat\n\nmain = getLine >>= (flip replicateM $ getLine) . read >>= putStrLn . show . maximum . (map cost) . (\\x -> (map (article x) pairs))"}, {"source_code": "import Control.Monad\n\npairs = [(x, y)| x<-['a'..'z'], y<-['a','z'], x<=y]\n\narticle inp (f,s) = filter (not.any (\\x->x /= f || x/=s)) inp\n\ncost :: [[a]] -> Int\ncost = length . concat\n\nmain = getLine >>= (flip replicateM $ getLine) . read >>= putStrLn . show . maximum . (map cost) . (\\x -> (map (article x) pairs))"}], "src_uid": "d8a93129cb5e7f05a5d6bbeedbd9ef1a"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\ntype PQ = S.Set (Int, Int)\n\ndata Info = Info {\n ws :: PQ,\n bs :: PQ,\n vs :: [(Int, Int)]\n}\n\ngao :: [[Int]] -> State Info [[Int]]\ngao ans = do\n w <- gets ws\n b <- gets bs\n if S.null w || S.null b\n then do\n ((wv, bv): t) <- gets vs\n wvs <- forM (t ++ [(i, i) | (_, i) <- S.toList w]) $ \\(i, _) -> do\n return [bv, i, 0]\n bvs <- forM [(i, i) | (_, i) <- S.toList b] $ \\(_, i) -> do\n return [wv, i, 0]\n return $ ans ++ wvs ++ bvs\n else do\n (we, wv) <- gets (S.findMax . ws)\n modify $ \\info -> info{ws = S.deleteMax $ ws info}\n (be, bv) <- gets (S.findMax . bs)\n modify $ \\info -> info{bs = S.deleteMax $ bs info}\n let e = min we be\n case compare we be of\n EQ -> modify $ \\info -> info{vs = (wv, bv): vs info}\n GT -> modify $ \\info -> info{ws = S.insert (we - e, wv) $ ws info}\n LT -> modify $ \\info -> info{bs = S.insert (be - e, bv) $ bs info}\n gao $ [wv, bv, e]: ans\n\nmain :: IO ()\nmain = do\n (n:cs) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let a = [(c, (s, i)) | (i, (c, s)) <- zip [1 .. n] $ pairs cs]\n w = S.fromList $ map snd $ filter ((==0) . fst) a\n b = S.fromList $ map snd $ filter ((==1) . fst) a\n ans = fst $ runState (gao []) $ Info w b []\n putStrLn $ unwords $ map show $ concat ans\n\n-- Control.Monad.State\nnewtype State s a = State {\n runState :: s -> (a, s)\n}\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a', s') = runState m s in runState (f a') s'\n\nget :: State s s\nget = State $ \\s -> (s, s)\n\nput :: s -> State s ()\nput s = State $ \\_ -> ((), s)\n\nmodify :: (s -> s) -> State s ()\nmodify f = State $ \\s -> ((), f s)\n\ngets :: (s -> a) -> State s a\ngets f = State $ \\s -> (f s, s)\n\n", "positive_code": [{"source_code": "import Data.Maybe\nimport Data.Int\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\ngroups :: [Int] -> Int -> ([(Int, Int)], [(Int, Int)])\ngroups [] n = ([], [])\ngroups (x:y:xs) n\n | x == 0 = ((y, n):b, w)\n | x == 1 = (b, (y, n):w)\n where (b, w) = groups xs (n + 1)\n\nwork :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int, Int)]\nwork bs [] = []\nwork [] ws = []\nwork ((fb, sb) : bs) ((fw, sw) : ws)\n | (fb < fw) || ((fb == fw) && (null ws)) = (sb, sw, fb) : work bs ((fw - fb, sw):ws)\n | otherwise = (sb, sw, fw) : work ((fb - fw, sb):bs) ws\n\nmain = do\n n : input <- fmap (map (fst . fromJust . B.readInt) . B.words) B.getContents\n let (b, w) = groups input 1\n ans = work b w\n mapM_ (\\(x,y,z) -> printf \"%d %d %d\\n\" x y z) ans\n"}], "negative_code": [], "src_uid": "b1ece35f190b13a3dfd64ab30c905765"} {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n n <- read <$> getLine\n getLine\n xss <- sequence [ (map read) . words <$> getLine | _ <- [1 .. n]] \n print $ solve xss\n\nsolve :: [[Int]] -> Int\nsolve = minimum . map compute \n\ncompute :: [Int] -> Int\ncompute xs = (15 * (length xs)) + (5 * (sum xs))\n\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n getLine\n ms <- replicateM n getInts\n\n print $ minimum $ map (\\a -> (length a)*15 + (sum a) * 5) ms\n"}, {"source_code": "module Main where\nimport Control.Monad \nmain = do\n n <- readLn :: IO Int\n getLine\n ks <- replicateM n $ getLine >>= return . map (read::String -> Int) .words \n let ms = map (\\x -> (length x * 15 ) + (sum $ map (*5) x)) ks \n print $ minimum ms"}, {"source_code": "import Data.List\n\nf::[String]->[Int]\nf []=[]\nf (s:strs)=let xs=map read (words s)::[Int]\n in (sum xs)*5+15*(length xs):f strs\n\nmain =do\n e<-getLine\n e2<-getLine\n es<-getContents\n print $ minimum $ f (lines es)"}, {"source_code": "\nmain :: IO ()\nmain = do \n input <- getContents\n putStrLn (solve (parse input))\n\nparse :: String -> [[Int]]\nparse str =\n let \n ls = drop 1 $ lines str\n ls' = drop 1 ls\n ldata = map (map read) $ map words ls'\n in\n ldata\n\nsolve ldata =\n show $ minimum $ map sum (map (map (\\x -> 5 * x + 15)) ldata)\n"}, {"source_code": "\nmain = do\n getLine\n getLine\n q <- getContents\n print $ minimum $ map (((*) 5) . sum) $ map (\\x -> map ((+) 3) x) $ map (\\x -> map (\\y -> read y::Int) x) $ map words $ lines q"}, {"source_code": "main=interact$show.minimum.map(f.map read.words).drop 2.lines\nf :: [Int] -> Int\nf xs = length xs * 15 + sum (map (5*) xs)"}, {"source_code": "solve :: [[Int]] -> Int\nsolve xss = minimum ys where\n ys = [5*sum xs + 15*length xs | xs <- xss]\n\nparseInput :: String -> [[Int]]\nparseInput input = xss where\n ls = tail $ tail $ lines input\n ys = map words ls\n xss = [map read y :: [Int] | y <- ys]\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = parseInput input\n print $ solve xs\n"}], "negative_code": [{"source_code": "solve :: [[Int]] -> Int\nsolve xss = minimum ys where\n ys = [5*sum xs + 15*length xs | xs <- xss]\n\nparseInput :: String -> [[Int]]\nparseInput input = xss where\n ls = tail $ lines input\n ys = map words ls\n xss = [map read y :: [Int] | y <- ys]\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = parseInput input\n print $ solve xs\n"}], "src_uid": "0ea79b2a7ddf3d4da9c7a348e61933a7"} {"source_code": "check' :: String -> String -> String -> Bool\r\ncheck' _ _ \"\" = True\r\ncheck' pattern (x : xs) (y : ys) = (x == y) && check' pattern (if (xs == \"\") then pattern else xs) ys\r\n\r\ncheck :: String -> String -> Bool\r\ncheck pattern s = check' pattern pattern s\r\n\r\nfindPattern' :: String -> String -> String\r\nfindPattern' cur [] = cur\r\nfindPattern' cur (x : xs)\r\n | (x `elem` cur) = cur\r\n | otherwise = findPattern' (cur ++ [x]) xs\r\n\r\nfindPattern :: String -> String\r\nfindPattern s = findPattern' \"\" s\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n s <- getLine\r\n let pattern = findPattern s\r\n let result = check pattern s\r\n return (if result then \"YES\" else \"NO\")\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn \"\"\r\n putStrLn (join \"\\r\\n\" results)", "positive_code": [{"source_code": "check' :: String -> String -> String -> Bool\r\ncheck' _ _ \"\" = True\r\ncheck' pattern (x : xs) (y : ys) = (x == y) && check' pattern (if (xs == \"\") then pattern else xs) ys\r\n\r\ncheck :: String -> String -> Bool\r\ncheck pattern s = check' pattern pattern s\r\n\r\nfindPattern' :: String -> String -> String\r\nfindPattern' cur [] = cur\r\nfindPattern' cur (x : xs)\r\n | (x `elem` cur) = cur\r\n | otherwise = findPattern' (cur ++ [x]) xs\r\n\r\nfindPattern :: String -> String\r\nfindPattern s = findPattern' \"\" s\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n s <- getLine\r\n let pattern = findPattern s\r\n let result = check pattern s\r\n return (if result then \"YES\" else \"NO\")\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)"}, {"source_code": "import Control.Monad\r\nimport Data.Array.Unboxed\r\nimport Data.Char\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Map.Strict as M\r\nimport qualified Data.Set as S\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- fst . C.spanEnd isSpace <$> C.getLine\r\n let sa = listArray (1, n) $ (+(-97)) . ord <$> C.unpack s :: UArray Int Int\r\n n = C.length s\r\n cset = S.fromList (elems sa)\r\n cnt = fArray (0, n) f :: Array Int (UArray Int Int) where\r\n f 0 = listArray (0, 25) $ repeat 0\r\n f i = cnt!(i-1) // [(sa!i, cnt!(i-1)!(sa!i) + 1)]\r\n missing l r c = cnt!r!c - cnt!l!c == 0\r\n go _ i | i == n+1 = True\r\n go last i = case last M.!? (sa!i) of\r\n Just j | any (missing j i) cset -> False\r\n _ -> go last' (i+1)\r\n where\r\n last' = M.insert (sa!i) i last\r\n putStrLn $ if go M.empty 1 then \"YES\" else \"NO\"\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = listArray b (map f (range b))\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "findPattern' :: String -> String -> String\r\nfindPattern' cur [] = cur\r\nfindPattern' cur (x : xs)\r\n | (x `elem` cur) = cur\r\n | otherwise = findPattern' (cur ++ [x]) xs\r\n\r\nfindPattern :: String -> String\r\nfindPattern s = findPattern' \"\" s\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n s <- getLine\r\n let pattern = findPattern s\r\n let result = (s == (take (length s) (cycle pattern)))\r\n return (if result then \"YES\" else \"NO\")\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)"}], "negative_code": [], "src_uid": "dd098a17343a02fa5dc0d2d6cea853c7"} {"source_code": "{-# LANGUAGE NoImplicitPrelude #-}\n\nimport Data.List.Split (splitOn)\nimport Data.Map (Map, lookup, insert, fromList, (!))\nimport Data.List (group, zip, map, concat, sort, intersperse)\nimport Prelude (getLine, putStrLn, show, read, \n Int, Bool(True, False), (.), \n ($), head, tail, (==), otherwise, \n (<), (&&), (>), (-), (+), (++), length, sum)\nimport Data.Maybe\n\nbuildAns :: Map Int Int -> Map Int Bool-> [Int] -> [Int] -> [Int]\nbuildAns left skip a t\n | (t == []) = a\n | otherwise = let (q:qs) = a\n el = lookup q left\n in case el of\n Nothing -> q : (buildAns left skip qs t)\n Just tm -> if head t < q && tm > 1\n then (head t) : buildAns (insert q (tm - 1) left) skip qs (tail t) \n else if tm == 1 \n then q : buildAns left skip qs t \n else if (skip!q == True)\n then (head t) : buildAns (insert q (tm - 1) left) skip qs (tail t)\n else q : buildAns left (insert q True skip) qs t \nmain = do\n n' <- getLine\n a' <- getLine\n let n = read n'\n a = map read $ splitOn \" \" a'\n g = (group.sort) a\n unq = 0 : map head g\n pr = zip unq ((tail unq) ++ [n+1]) \n t = concat $ map (\\(x,y) -> [(x + 1)..(y - 1)]) pr\n \n left = fromList $ map (\\x -> (head x, length x)) g\n skip = fromList $ map (\\x -> (x, False)) unq\n putStrLn $ show $ (sum $ map length g) - length g \n putStrLn.concat $ intersperse \" \" $ map show $ buildAns left skip a t \n", "positive_code": [{"source_code": "{-# LANGUAGE NoImplicitPrelude #-}\n\nimport Data.List.Split (splitOn)\nimport Data.Map (Map, lookup, insert, fromList, (!))\nimport Data.List (group, zip, map, concat, sort, intersperse)\nimport Prelude (getLine, putStrLn, show, read, \n Int, Bool(True, False), (.), \n ($), head, tail, (==), otherwise, \n (<), (&&), (>), (-), (+), (++), length, sum)\nimport Data.Maybe\n\nbuildAns :: Map Int Int -> Map Int Bool-> [Int] -> [Int] -> [Int]\nbuildAns left skip a t\n | (t == []) = a\n | otherwise = let (q:qs) = a\n el = lookup q left\n in case el of\n Nothing -> q : (buildAns left skip qs t)\n Just tm -> if head t < q && tm > 1\n then (head t) : buildAns (insert q (tm - 1) left) skip qs (tail t) \n else if tm == 1 \n then q : buildAns left skip qs t \n else if (skip!q == True)\n then (head t) : buildAns (insert q (tm - 1) left) skip qs (tail t)\n else q : buildAns left (insert q True skip) qs t \nmain = do\n n' <- getLine\n a' <- getLine\n let n = read n'\n a = map read $ splitOn \" \" a'\n g = (group.sort) a\n unq = 0 : map head g\n pr = zip unq ((tail unq) ++ [n+1])\n --s = (Set.fromList unq) :: Set.Set Int\n --t = [x | x <- [1..n], not (Set.member x s) ]\n \n t = concat $ map (\\(x,y) -> [(x + 1)..(y - 1)]) pr\n \n left = (fromList $ map (\\x -> (head x, length x)) g) :: Map Int Int\n skip = (fromList $ map (\\x -> (x, False)) unq) :: Map Int Bool\n putStrLn $ show $ (sum $ map length g) - length g \n putStrLn.concat $ intersperse \" \" $ map show $ buildAns left skip a t \n \n \n \n \n \n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport qualified Data.IntMap as M\nimport qualified Data.IntSet as S\nimport Data.List\nimport Data.Maybe\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n poi\n return $ unwords $ map show $ solve n xs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs = (length cs0:) $ snd $ mapAccumL go (freq0, cs0, S.empty) xs\n where\n freq0 = M.fromListWith (+) $ zip xs (repeat 1 :: [Int])\n cs0 = filter (not . flip M.member freq0) [1..n]\n go st@(freq, cs, skipped) x\n | null cs || fromJust (M.lookup x freq) <= 1 = (st, x)\n | S.member x skipped || x > head cs = ((M.adjust (subtract 1) x freq, tail cs, skipped), head cs)\n | otherwise = ((freq, cs, S.insert x skipped), x)"}], "negative_code": [{"source_code": "import Data.List.Split (splitOn)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.List\n\nbuildAns :: Map.Map Int Bool -> [Int] -> [Int] -> [Int]\nbuildAns left a t\n | (t == []) = a\n | otherwise = let (q:qs) = a\n el = Map.lookup q left\n in case el of\n Nothing -> q : (buildAns left qs t)\n Just tm -> if (head t < q) || tm\n then (head t) : buildAns left qs (tail t) \n else q : buildAns (Map.insert q True left) qs t\nmain = do\n n' <- getLine\n a' <- getLine\n let n = read n'\n a = map read $ splitOn \" \" a'\n g = (group.sort) a\n unq = map head g\n s = (Set.fromList unq) :: Set.Set Int\n t = [x | x <- [1..n], not (Set.member x s) ]\n left = (Map.fromList $ map (\\x -> (x, False)) unq) :: Map.Map Int Bool\n \n putStrLn $ show $ (sum $ map length g) - length g \n putStrLn.concat $ intersperse \" \" $ map show $ buildAns left a t \n \n \n \n \n \n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n a <- poi \n b <- poi\n f <- poi\n k <- poi\n return $ show $ solve a b f k\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve end cap gas n = go n False 0 cap\n where\n go 0 _ cnt _ = cnt\n go re rev cnt have\n | have < d1 || haveU < 0 = -1\n | haveN >= next = go' cnt haveN\n | haveU >= next = go' (cnt + 1) haveU\n | otherwise = -1\n where\n (d1, d2) = if rev then (end - gas, gas) else (gas, end - gas)\n next = if re == 1 then 0 else d2\n go' = go (re - 1) (not rev)\n haveU = cap - d2\n haveN = have - end"}], "src_uid": "0560658d84cbf91c0d86eea4be92a4d9"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Int\nimport Data.Maybe\nimport Data.Ratio\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\n\n-- p >= 4q, p \\in [0,a], q \\in [-b,b]\nsolve :: Integer -> Integer -> Double\nsolve a 0 = 1.0\nsolve 0 b = 0.5\nsolve a b = fromRational (area8 % (area * 8)) * 0.5 + 0.5\n where\n area8\n | a >= 4 * b = (a - 4 * b) * b * 4 + a * b * 4\n | otherwise = a * a\n area = a * b\n\nreadI = fst . fromJust . BS.readInteger\n\nmain = do\n t <- read <$> getLine :: IO Int\n query <- map (map readI . BS.words) . BS.lines <$> BS.getContents\n forM_ query $ \\[a,b] -> do\n print $ solve a b\n\n", "positive_code": [{"source_code": "import Control.Applicative\n\nreadWords :: Read a => IO [a]\nreadWords = map read.words <$> getLine\n\nsolveArea a b = a*b + if a < 4*b then a*(a/4)/2 else a*b-b*(b*4)/2\n\nsolve :: Double -> Double -> Double\nsolve a b = if b < 1e-6 then 1 else if a < 1e-6 then 0.5 else solveArea a b / a / b / 2\n\nsolveTestCase = do\n [a, b] <- readWords :: IO [Double]\n putStrLn $ show $ solve a b\n\nmain = do\n [n] <- readWords\n sequence_ $ replicate n solveTestCase\n "}, {"source_code": "main = do\n t <- read `fmap` getLine\n mapM_ (\\_ -> do\n [a, b] <- (map (fromIntegral.read) . words) `fmap` getLine\n\tlet p1 = 0.5\n\t p2 = let b' = min b (a/4) in b' * (a - b' * 4 / 2)/(2 * a * b)\n print $ (if b == 0 then 1 else if a == 0 then p1 else p1 + p2)) [1..t]\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nreadWords :: Read a => IO [a]\nreadWords = map read.words <$> getLine\n\nsolveArea a b = a*b + if a < 4*b then a*(a/4)/2 else a*b-b*(b*4)/2\n\nsolve :: Double -> Double -> Double\nsolve a b = if b < 1e-6 then 0 else if a < 1e-6 then 1 else solveArea a b / a / b / 2\n\nsolveTestCase = do\n [a, b] <- readWords :: IO [Double]\n putStrLn $ show $ solve a b\n\nmain = do\n [n] <- readWords\n sequence_ $ replicate n solveTestCase\n "}, {"source_code": "import Control.Applicative\n\nreadWords :: Read a => IO [a]\nreadWords = map read.words <$> getLine\n\nsolveArea a b = a*b + if a < 4*b then a*(a/4)/2 else a*b-b*(b*4)/2\n\nsolve :: Double -> Double -> Double\nsolve a b = solveArea a b / a / b / 2\n\nsolveTestCase = do\n [a, b] <- readWords :: IO [Double]\n putStrLn $ show $ solve a b\n\nmain = do\n [n] <- readWords\n sequence_ $ replicate n solveTestCase\n "}, {"source_code": "main = do\n t <- read `fmap` getLine\n mapM_ (\\_ -> do\n [a, b] <- (map read . words) `fmap` getLine\n print $ fromIntegral a/4 / fromIntegral b /4 + 0.5) [1..t]\n"}, {"source_code": "main = do\n t <- read `fmap` getLine\n mapM_ (\\_ -> do\n [a, b] <- (map read . words) `fmap` getLine\n if b == 0 then print 1 else \n print $ fromIntegral a/4 / fromIntegral b /4 + 0.5) [1..t]\n"}], "src_uid": "92feda270834af751ca37bd80083aafa"} {"source_code": "import Control.Monad ( replicateM, forM_, when, liftM3 )\r\nimport Data.Array.IArray ( Array, (!), array )\r\nimport Data.Array.ST ( readArray, writeArray, MArray(newArray), runSTArray )\r\nimport Data.Int ( Int64 )\r\nimport Data.Ix ( Ix(range) ) \r\n\r\nm :: Int64\r\nm = 1000000007\r\n\r\nnewtype MInt = MInt Int64 deriving Show\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b\r\n MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger i = MInt $ fromInteger i `mod` m\r\n\r\ntoInt64 :: MInt -> Int64\r\ntoInt64 (MInt a) = a\r\n\r\ninv :: MInt -> MInt\r\ninv a = pow a (m - 2)\r\n where pow a b | b == 0 = 1\r\n | odd b = a * pow a (b - 1)\r\n | otherwise = pow (a * a) (b `div` 2)\r\n\r\nfloydWarshall :: Int -> [(Int, Int)] -> Array (Int, Int) Int\r\nfloydWarshall n e =\r\n runSTArray $ do\r\n d <- newArray ((1, 1), (n, n)) (n * n)\r\n let rd = readArray d; wd = writeArray d\r\n forM_ [1..n] $ \\i -> wd (i, i) 0\r\n forM_ e $ \\(u, v) -> wd (u, v) 1 >> wd (v, u) 1\r\n forM_ (range ((1, 1, 1), (n, n, n))) $ \\(k, i, j) -> do\r\n [ij, ik, kj] <- mapM rd [(i, j), (i, k), (k, j)]\r\n when (ik + kj < ij) $ wd (i, j) (ik + kj)\r\n return d\r\n\r\n-- (i, j) is probability we finish i after j\r\nprob :: Int -> Array (Int, Int) MInt\r\nprob n = dp\r\n where\r\n dp = array ((0, 0), (n, n)) [((i, j), f i j) | i <- [0..n], j <- [0..n]]\r\n f i j | i == 0 = 0\r\n | j == 0 = 1\r\n | otherwise = (dp!(i - 1, j) + dp!(i, j - 1)) * inv2\r\n inv2 = inv 2\r\n\r\nsolve :: IO()\r\nsolve = do\r\n n <- readInt <$> getLine\r\n let parseEdge = (\\[u, v] -> (u, v)) . map readInt . words\r\n edges <- map parseEdge <$> replicateM (n - 1) getLine\r\n let d = floydWarshall n edges\r\n p = prob n\r\n dists r u v =\r\n let uv = d!(u, v); ru = d!(r, u); rv = d!(r, v)\r\n in ((uv + ru - rv) `div` 2, (uv + rv - ru) `div` 2)\r\n forRoot r = sum [p!dists r u v | u <- [1..n], v <- [u + 1..n]]\r\n print $ toInt64 $ sum (map forRoot [1..n]) * inv (fromIntegral n)\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nmain :: IO()\r\nmain = solve\r\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\nmd :: Int64\r\nmd = 1000000007\r\n\r\nnewtype MInt = MInt Int64 deriving Eq\r\n\r\ninstance Show MInt where\r\n show (MInt a) = show a\r\n\r\ninstance Num MInt where\r\n (MInt a) + (MInt b) =\r\n let r = a + b in\r\n MInt $ if r >= md then r - md else r\r\n (MInt a) * (MInt b) = MInt $ (a * b) `mod` md\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger a = MInt $ fromInteger (a `mod` fromIntegral md)\r\n negate (MInt 0) = 0\r\n negate (MInt a) = MInt $ md - a\r\n\r\ninstance Fractional MInt where\r\n recip a = a ^ (md - 2)\r\n fromRational x =\r\n let a = numerator x `mod` fromIntegral md\r\n b = denominator x `mod` fromIntegral md\r\n in\r\n MInt (fromInteger a) / MInt (fromInteger b)\r\n\r\n\r\ntype Graph = Array Int [Int]\r\n\r\nbuildG :: (Int, Int) -> [(Int, Int)] -> Graph\r\nbuildG = accumArray (flip (:)) []\r\n\r\nbuildS :: Graph -> Int -> Array Int MInt\r\nbuildS g rt = runSTArray $ do\r\n let n = snd $ bounds g\r\n s <- newArray (1,n) 1 :: ST s (STArray s Int MInt)\r\n\r\n let dfs x p = do\r\n forM_ (g ! x) $ \\y -> do\r\n when (y /= p) $ do\r\n dfs y x\r\n readArray s y >>= \\t -> modifyArray (+t) s x\r\n\r\n dfs rt 0\r\n return s\r\n\r\n\r\nsolve :: Graph -> Array (Int,Int) MInt -> Int -> MInt\r\nsolve g dp rt = runST $ do\r\n let n = snd $ bounds g\r\n s = buildS g rt\r\n res <- newSTRef 0 :: ST s (STRef s MInt)\r\n\r\n let dfs x ps = do\r\n when (x < rt) $ do\r\n let l = length ps\r\n xs = x : ps\r\n pingo = zip3 (tail xs) xs [1..]\r\n calc (a,b,k) = ((s!a) - (s!b)) * (dp ! (l-k,k))\r\n asd = sum $ map calc pingo\r\n -- deb \"PINGO\" (x,rt,asd,pingo,map calc pingo) modifySTRef' res (+asd)\r\n modifySTRef' res (+asd)\r\n forM_ (g ! x) $ \\y -> do\r\n when (null ps || y /= head ps) $ do\r\n dfs y (x:ps)\r\n\r\n dfs rt []\r\n readSTRef res\r\n\r\n\r\ndoDp :: Int -> Array (Int,Int) MInt\r\ndoDp n = runSTArray $ do\r\n dp <- newArray ((0,0),(n,n)) 0 :: ST s (STArray s (Int,Int) MInt)\r\n forM_ [1..n] $ \\j -> writeArray dp (0,j) 1\r\n let hlf :: MInt\r\n hlf = 1 / 2\r\n forM_ (liftM2 (,) [1..n] [1..n]) $ \\(i,j) -> do\r\n a <- readArray dp (i-1,j)\r\n b <- readArray dp (i,j-1)\r\n writeArray dp (i,j) $ hlf * (a+b)\r\n return dp\r\n\r\nmain = do\r\n n <- parseInt <$> BS.getLine\r\n es <- replicateM (n-1) $ do\r\n [x,y] <- map parseInt . BS.words <$> BS.getLine\r\n return (x,y)\r\n let g = buildG (1,n) (es ++ map swap es)\r\n dp = doDp n\r\n print $ (sum [solve g dp i | i <- [2..n]]) / fromIntegral n\r\n"}, {"source_code": "import Control.Monad ( replicateM, forM_, when )\r\nimport Data.Int ( Int64 )\r\nimport Data.Array.IArray ( Array, (!), array )\r\nimport Data.Array.ST ( readArray, writeArray, MArray(newArray), runSTArray )\r\n\r\nm :: Int64\r\nm = 1000000007\r\n\r\nnewtype MInt = MInt Int64 deriving Show\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b\r\n MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum (MInt a) = MInt $ signum a\r\n fromInteger i = MInt $ fromInteger i `mod` m\r\n\r\ntoInt64 :: MInt -> Int64\r\ntoInt64 (MInt a) = a\r\n\r\ninv :: MInt -> MInt\r\ninv a = pow a (m - 2)\r\n where pow a b | b == 0 = 1\r\n | odd b = a * pow a (b - 1)\r\n | otherwise = pow (a * a) (b `div` 2)\r\n\r\nfloydWarshall :: Int -> [(Int, Int)] -> Array (Int, Int) Int\r\nfloydWarshall n e =\r\n runSTArray $ do\r\n d <- newArray ((1, 1), (n, n)) (n * n)\r\n forM_ [1..n] $ \\i ->\r\n writeArray d (i, i) 0\r\n forM_ e $ \\(u, v) -> do\r\n writeArray d (u, v) 1\r\n writeArray d (v, u) 1\r\n forM_ [1..n] $ \\k ->\r\n forM_ [1..n] $ \\i ->\r\n forM_ [1..n] $ \\j -> do\r\n ij <- readArray d (i, j)\r\n ik <- readArray d (i, k)\r\n kj <- readArray d (k, j)\r\n when (ik + kj < ij) $ writeArray d (i, j) (ik + kj)\r\n return d\r\n\r\n-- (i, j) is probability we finish i after j\r\nprob :: Int -> Array (Int, Int) MInt\r\nprob n = dp\r\n where\r\n dp = array ((0, 0), (n, n)) [((i, j), f i j) | i <- [0..n], j <- [0..n]]\r\n f i j | i == 0 = 0\r\n | j == 0 = 1\r\n | otherwise = (dp!(i - 1, j) + dp!(i, j - 1)) * inv2\r\n inv2 = inv 2\r\n\r\nsolve :: IO()\r\nsolve = do\r\n n <- readInt <$> getLine\r\n let parseEdge = (\\(u:v:_) -> (u, v)) . map readInt . words\r\n edges <- map parseEdge <$> replicateM (n - 1) getLine\r\n let d = floydWarshall n edges\r\n let p = prob n\r\n let dists r u v =\r\n let uv = d!(u, v); ru = d!(r, u); rv = d!(r, v)\r\n in ((uv + ru - rv) `div` 2, (uv + rv - ru) `div` 2)\r\n let forRoot r = sum [p!(dists r u v) | u <- [1..n], v <- [u + 1..n]]\r\n print $ toInt64 $ sum (map forRoot [1..n]) * inv (fromIntegral n)\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nmain :: IO()\r\nmain = solve\r\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\ndebug x t = x\ntrace t x = x\ntracing t x = x\ndebugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nm :: Int64\nm = 10 ^ 9 + 7\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\ninstance Show M where \n show = show . unM\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = M $ (a * b) `mod` m\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n\ngraphDistances :: Int -> GraphA -> UA.UArray (Int, Int) Int\ngraphDistances n graph = STA.runSTUArray do\n distancesA <- MA.newArray ((1, 1), (n, n)) n\n let graphAssocs = A.assocs graph\n forM_ graphAssocs $ \\(u, vs) -> do\n forM_ vs $ \\v -> modifyArray distancesA (u, v) $ min 1\n MA.writeArray distancesA (u, u) 0\n forM_ (Ix.range ((1, 1, 1), (n, n, n))) $ \\(k, i, j) -> do\n dik <- MA.readArray distancesA (i, k)\n dkj <- MA.readArray distancesA (k, j)\n modifyArray distancesA (i, j) $ min (dik + dkj)\n return distancesA\n \n\nf :: A.Array (Int, Int) M\nf = STA.runSTArray do\n let maxN = 300\n fA <- MA.newArray ((0, 0), (maxN, maxN)) $ M 0\n forM_ (Ix.range ((0, 0), (maxN, maxN))) $ \\(i, j) -> do\n case (i, j) of\n (i, 0) -> MA.writeArray fA (i, 0) $ M 0\n (0, j) -> MA.writeArray fA (0, j) $ M 1\n (i, j) -> do\n f01 <- MA.readArray fA (i, j - 1)\n f10 <- MA.readArray fA (i - 1, j)\n MA.writeArray fA (i, j) $ (f01 + f10) / M 2\n return fA\n\n\nsolve :: Int -> GraphA -> Int64\nsolve n graph = unM answer\n where\n distances = graphDistances n graph\n answer = sum $ [prob r u v | (r, u, v) <- Ix.range ((1, 1, 1), (n, n, n)), u > v]\n prob r u v = (recip (M . fromIntegral $ n) * f A.! (dCU, dCV)) `debug` (show \"r u v = \" ++ show (r, u, v)) `debugging` \"prob\"\n where\n dRU = distances UA.! (r, u) `debugging` \"dRU\" \n dRV = distances UA.! (r, v) `debugging` \"dRV\" \n dUV = distances UA.! (u, v) `debugging` \"dUV\" \n dRC = ((dRU + dRV - dUV) `div` 2) `debugging` \"dRC\" \n dCU = (dRU - dRC) `debugging` \"dCU\" \n dCV = (dRV - dRC) `debugging` \"dCV\" \n\n\nmain :: IO ()\nmain = do\n n <- B8.getLine <&> readIntB8\n edges <- replicateM (pred n) $ B8.getLine <&> readIntB8s <&> (\\[a, b] -> (a, b))\n let graph = graphFromEdges n edges\n let answer = solve n graph\n printf \"%lld\\n\" answer\n"}], "negative_code": [], "src_uid": "987433ba0b6a115d05f79f512e329f7a"} {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n ss <- replicateM n (norm . zipWith (-) [x0,y0] . map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare (xa * yb) (xb * ya)\n print $ length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\nnorm [x,y] | y < 0 || y == 0 && x < 0 = [-x,-y] | otherwise = [x,y]\n", "positive_code": [{"source_code": "import Data.List (nub)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve ([_, x0, y0] : xys) = length $ nub $ map (\\[x, y] -> ratio (x - x0, y - y0)) xys\nsolve _ = undefined\n\nratio :: (Int, Int) -> (Int, Int)\nratio (x, y) = (x `div` gcd x y * signum x, y `div` gcd x y * signum x)\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> let [x,y,z] = map read (words n) in (mapM_ putStrLn).solve.(\\as->(y,z):as) =<< (forM [1..x] $ \\i -> getLine>>= \\j -> let [a,b]= words j in return (read a, read b))\nsolve::[(Int,Int)]->[String]\nsolve xs = [show $ length $ map head $ group $ sort $ map (\\(a,b)->let g= gcd a b; z= if a/=0 then a `div` abs a else b `div` abs b in (z*a `div` g, z*b `div` g)) (slv1 xs)]\nslv1 ((x1,x2):xs) = map (\\ (a,b) -> (a-x1,b-x2)) xs"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> let [x,y,z] = map read (words n) in (mapM_ putStrLn).solve.(\\as->(y,z):as) =<< (forM [1..x] $ \\i -> getLine>>= \\j -> let [a,b]= words j in return (read a, read b))\nsolve::[(Int,Int)]->[String]\nsolve xs = [show $ length $ map head $group $ sort $ map (\\(a,b)->let g= gcd a b; z= if a/=0 then a `div` abs a else 1 in (z*a `div` g, z*b `div` g)) (slv1 xs)]\nslv1 ((x1,x2):xs) = map (\\ (a,b) -> (a-x1,b-x2)) xs"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n (zs,ss) <- partition (== [0,0]) <$> replicateM n (norm . zipWith (-) [x0,y0] . map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare (xa * yb) (xb * ya)\n print $ if not (null zs) then -1 else length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\nnorm [x,y] | y < 0 = [-x,-y] | otherwise = [x,y]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n (zs,ss) <- partition (== [0,0]) <$> replicateM n (norm . zipWith (-) [x0,y0] . map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare (xa * yb) (xb * ya)\n print $ max (fromEnum (not (null zs))) $ length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\nnorm [x,y] | y < 0 = [-x,-y] | otherwise = [x,y]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n ss <- replicateM n (map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare ((xa-x0) * (yb-y0)) ((xb-x0) * (ya-y0))\n print $ length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n ss <- replicateM n (norm . zipWith (-) [x0,y0] . map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare (xa * yb) (xb * ya)\n print $ length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\nnorm [x,y] | y < 0 = [-x,-y] | otherwise = [x,y]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n (zs,ss) <- partition (== [0,0]) <$> replicateM n (norm . zipWith (-) [x0,y0] . map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare (xa * yb) (xb * ya)\n print $ min (fromEnum (not (null zs))) $ length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\nnorm [x,y] | y < 0 = [-x,-y] | otherwise = [x,y]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,x0,y0] <- map read . words <$> getLine\n ss <- replicateM n (map read . words <$> getLine)\n let cp [xa,ya] [xb,yb] = compare (abs (xa-x0) * (yb-y0)) (abs (xb-x0) * (ya-y0))\n print $ length $ groupBy (((== EQ) .) . cp) $ sortBy cp ss\n"}], "src_uid": "8d2845c33645ac45d4d37f9493b0c380"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: !Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words)\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words)\n\nmain = do\n\tlines <- B.lines `fmap` B.getContents\n\tlet [n, m] = getInts $ lines !! 0\n\tlet arrays = map (tail . getIntegers) $ init $ tail $ lines\n\tlet indexes = getInts $ last lines\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: !Int64 }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words)\ngetIntegers = (map (fromIntegral . fst . fromJust . B.readInt) . B.words)\n\nmain = do\n\tlines <- B.lines `fmap` B.getContents\n\tlet [n, m] = getInts $ lines !! 0\n\tlet arrays = map (tail . getIntegers) $ init $ tail $ lines\n\tlet indexes = getInts $ last lines\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: !Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words)\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words)\n\nmain = do\n\tlines <- B.lines `fmap` B.getContents\n\tlet [n, m] = getInts $ lines !! 0\n\tlet arrays = map (tail . getIntegers) $ init $ tail $ lines\n\tlet indexes = getInts $ last lines\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: !Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Int64 }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetInt64s = (map (fromIntegral . fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getInt64s\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Int64 }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetInt64s = (map (fromIntegral . fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getInt64s\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: !Int64 }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetInt64s = (map (fromIntegral . fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getInt64s\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\nimport Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: !Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Int\n\ndata Sums = Sums { sumsTotal, sumsLeft, sumsRight, sumsSub :: Integer }\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetInts = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\ngetIntegers = (map (fst . fromJust . B.readInteger) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getInts\n\tarrays <- replicateM n $ tail `fmap` getIntegers\n\tindexes <- getInts\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Int\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\n\n--import Control.Parallel\nimport GHC.Conc (par, pseq)\n\nfoldMap :: Monoid m => (a -> m) -> [a] -> m\nfoldMap f x = foldMap' x (length x)\n where\n foldMap' xs ln\n | ln == 0 = mempty\n | ln >= 100 = zs' `par` (ys' `pseq` (ys' `mappend` zs'))\n | otherwise = foldl1 mappend $ map f xs\n where\n lny = ln `div` 2\n lnz = ln - lny\n (ys,zs) = splitAt lny xs\n ys' = foldMap' ys lny\n zs' = foldMap' zs lnz\n\ndata MaxSum a = MaxSum\n { prefixS :: a\n , middleS :: a\n , suffixS :: a\n , allS :: a\n } deriving Show\n\ninstance (Bounded a, Num a, Ord a) => Monoid (MaxSum a) where\n mempty = MaxSum minBound minBound minBound 0\n mappend x y = MaxSum pre mid suf sum\n where\n pre = prefixS x `max` (allS x + prefixS y)\n mid = middleS x `max` middleS y `max` (suffixS x + prefixS y)\n suf = suffixS y `max` (allS y + suffixS x)\n sum = allS x + allS y\n\nsingleton :: Int -> MaxSum Int64\nsingleton x = MaxSum x' x' x' x'\n where\n x' = fromIntegral x\n\nreadI = fst . fromJust . BS.readInt\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n lines <- BS.lines <$> BS.getContents\n let states = map (foldMap singleton . tail . map readI . BS.words) $ take n lines\n let list = map readI . take m . BS.words . head $ drop n lines\n let arr = listArray (1, n) states :: Array Int (MaxSum Int64)\n let answer = foldMap (arr!) list\n print $ middleS answer\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Int\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\n\n--import Control.Parallel\nimport qualified GHC.Conc (par, pseq)\ninfixr 0 `par`, `pseq`\npar = GHC.Conc.par\npseq = GHC.Conc.pseq\n\nfoldMap :: Monoid m => (a -> m) -> [a] -> m\nfoldMap f x = foldMap' f x (length x)\n where\n foldMap' f xs ln\n | ln == 0 = mempty\n | ln >= 100 = zs' `par` (ys' `pseq` (ys' `mappend` zs')) \n | otherwise = foldl1 mappend $ map f xs\n where\n lny = ln `div` 2\n lnz = ln - lny\n (ys,zs) = splitAt lny xs\n ys' = foldMap' f ys lny\n zs' = foldMap' f zs lnz\n\ndata MaxSum a = MaxSum\n { prefixS :: a\n , middleS :: a\n , suffixS :: a\n , allS :: a\n } deriving Show\n\ninstance (Bounded a, Num a, Ord a) => Monoid (MaxSum a) where\n mempty = MaxSum minBound minBound minBound 0\n mappend x y = MaxSum pre mid suf sum\n where\n pre = prefixS x `max` (allS x + prefixS y)\n mid = middleS x `max` middleS y `max` (suffixS x + prefixS y)\n suf = suffixS y `max` (allS y + suffixS x)\n sum = allS x + allS y\n\nsingleton :: Int -> MaxSum Int64\nsingleton x = MaxSum x' x' x' x'\n where\n x' = fromIntegral x\n\nreadI = fst . fromJust . BS.readInt\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n lines <- BS.lines <$> BS.getContents\n let states = map (foldMap singleton . tail . map readI . BS.words) $ take n lines\n let list = map readI . take m . BS.words . head $ drop n lines\n let arr = listArray (1, n) states :: Array Int (MaxSum Int64)\n let answer = foldMap (arr!) list\n print $ middleS answer\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\n\ndata Sums = Sums { sumsTotal :: Int, sumsLeft :: Int, sumsRight, sumsSub :: Int}\n\nsums xs = \n\t\tSums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl (+) 0 xs\n\t\tright = maximum $ scanr (+) 0 xs\n\t\tsub = maximum $ scanl (\\s x -> max 0 $ s + x) 0 xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sums', maxs, zipWith (+) maxs $ map sumsLeft sums']\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsums' = map (arraysSums !) indexes\n\n\t\tmaxs = scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sums'\n\t\n\ngetWords = (map read . words) `fmap` getLine\n\nmain = do\n\t[n, m] <- getWords\n\tarrays <- replicateM n $ tail `fmap` getWords\n\tindexes <- getWords\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal :: Int, sumsLeft :: Int, sumsRight, sumsSub :: Int}\n\nsums xs = Sums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sumss, ends, zipWith (+) (0:ends) $ map sumsLeft sumss]\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsumss = map (arraysSums !) indexes\n\t\tends = tail $ scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sumss\n\ngetWords = (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\nmain = do\n\t[n, m] <- getWords\n\tarrays <- replicateM n $ tail `fmap` getWords\n\tindexes <- getWords\n\tprint $ solve arrays indexes\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\n\ndata Sums = Sums { sumsTotal :: Int, sumsLeft :: Int, sumsRight, sumsSub :: Int}\n\tderiving (Show)\n\nsums xs = \n\t\tSums total left right sub\n\twhere\n\t\ttotal = sum xs\n\t\tleft = maximum $ scanl1 (+) xs\n\t\tright = maximum $ scanr1 (+) xs\n\n\t\tsub = maximum $ scanl1 (\\s x -> max (s + x) x) xs\n\nsolve arrays indexes =\n\t\tmaximum $ concat [map sumsSub sums', tail maxs, zipWith (+) maxs $ map sumsLeft sums']\n\twhere\n\t\tarraysSums = listArray (1, length arrays) $ map sums arrays\n\t\tsums' = map (arraysSums !) indexes\n\n\t\tmaxs = scanl (\\s (Sums total _ right _) -> max right $ s + total) 0 sums'\n\t\n\ngetWords = (map read . words) `fmap` getLine\n\nmain = do\n\t[n, m] <- getWords\n\tarrays <- replicateM n $ tail `fmap` getWords\n\tindexes <- getWords\n\tprint $ map sums arrays\n\tprint $ solve arrays indexes\n\n"}], "src_uid": "13fa378c913bb7a15612327099b59f83"} {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\nimport Data.Bits\nimport Control.Arrow (first, second)\nimport Data.Bool\n\n\nprefSummary :: Ix i\n => (Int32 -> Int32 -> Int32) -> (i -> i) -> (i -> i)\n -> UArray i Int32 -> UArray i Int32\nprefSummary combine dec inc arr = runSTUArray $ do\n ans <- thaw arr\n let\n ok = inRange (bounds arr)\n go p = let\n q = inc p\n in when (ok q) $ do\n vp <- readArray ans p\n vq <- readArray ans q\n writeArray ans q $ combine vp vq\n go q\n forM_ (indices arr) $ \\p -> when (not $ ok (dec p)) $ go p\n pure ans\n\nfake_qsort :: (Int, Int) -> (Int -> Int32) -> UArray Int Int\n-- previously Data.List.sortOn was the memory bottleneck,\n-- so... use an in-place array sorting algorithm instead\nfake_qsort (p, q) fun = runSTUArray $ do\n arr <- newArray_ (p, q)\n forM_ [p .. q] $ \\i -> writeArray arr i i\n let\n maxv = foldl' (.|.) 0 $ map fun [p .. q]\n startBit = finiteBitSize maxv - 1 - countLeadingZeros maxv\n isort !scale !x !y = when (scale >= 0 && x < y) $ loop x y where\n -- Partitions the [x, y] index-interval according to bit 'scale'\n loop !i !j = if i <= j\n -- 'i' is the next un-examined index\n -- 'j' is the first index maybe without bit 'scale' set\n then do\n ai <- readArray arr i\n case testBit (fun ai) scale of\n False -> loop (i + 1) j\n True -> do\n aj <- readArray arr j\n writeArray arr j ai\n writeArray arr i aj\n loop i (j - 1)\n else isort (scale - 1) x j >> isort (scale - 1) (j + 1) y\n arr <$ isort startBit p q\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n vals <- getInts (n * m)\n let\n a :: UArray (Int, Int) Int32\n a = listArray ((1, 1), (n, m)) $ map fromIntegral vals\n rowOrder :: UArray Int Int\n rowOrder = fake_qsort (1, n) (\\i -> a ! (i, 1))\n sa = ixmap ((1, 1), (n, m)) (\\(i, j) -> (rowOrder ! i, j)) a\n\n inc = (+ 1)\n dec = subtract 1\n mkPre lens combine = prefSummary combine (lens dec) (lens inc)\n mkSuff lens combine = prefSummary combine (lens inc) (lens dec)\n\n -- red is below the split point\n tlmax = mkPre first max $ mkPre second max sa\n blmin = mkSuff first min $ mkPre second min sa\n trmin = mkPre first min $ mkSuff second min sa\n brmax = mkSuff first max $ mkSuff second max sa\n\n ok (i, j)\n = tlmax ! (i, j ) < blmin ! (i + 1, j)\n && trmin ! (i, j + 1) > brmax ! (i + 1, j + 1)\n colorRows i = let\n cs :: UArray Int Bool\n cs = array (1, n) [(rowOrder ! j, j <= i) | j <- [1 .. n]] \n in string7 $ map (bool 'R' 'B') (elems cs)\n pure $ case filter ok $ liftM2 (,) [1 .. n - 1] [1 .. m - 1] of\n (i, j) : _ -> string7 \"YES\\n\" <> colorRows i <> char7 ' ' <> putInts [j]\n _ -> string7 \"NO\\n\"\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\nimport Control.Arrow (first, second)\nimport Data.Bool\n\n\nprefSummary :: (Ix i, Show i)\n => (Int32 -> Int32 -> Int32) -> (i -> i) -> (i -> i)\n -> UArray i Int32 -> UArray i Int32\nprefSummary combine dec inc arr = runSTUArray $ do\n ans <- thaw arr\n let\n ok = inRange (bounds arr)\n go p = let\n q = inc p\n in when (ok q) $ do\n vp <- readArray ans p\n vq <- readArray ans q\n writeArray ans q $ combine vp vq\n go q\n forM_ (indices arr) $ \\p -> when (not $ ok (dec p)) $ go p\n pure ans\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n vals <- getInts (n * m)\n let\n a :: UArray (Int, Int) Int32\n a = listArray ((1, 1), (n, m)) $ map fromIntegral vals\n rowOrder :: UArray Int Int\n rowOrder = listArray (1, n) $ sortOn (\\i -> a ! (i, 1)) [1 .. n]\n sa = ixmap ((1, 1), (n, m)) (\\(i, j) -> (rowOrder ! i, j)) a\n\n inc = (+ 1)\n dec = subtract 1\n mkPre lens combine = prefSummary combine (lens dec) (lens inc)\n mkSuff lens combine = prefSummary combine (lens inc) (lens dec)\n\n -- red is below the split point\n tlmax = mkPre first max $ mkPre second max sa\n blmin = mkSuff first min $ mkPre second min sa\n trmin = mkPre first min $ mkSuff second min sa\n brmax = mkSuff first max $ mkSuff second max sa\n\n ok (i, j)\n = tlmax ! (i, j ) < blmin ! (i + 1, j)\n && trmin ! (i, j + 1) > brmax ! (i + 1, j + 1)\n colorRows i = let\n cs :: UArray Int Bool\n cs = array (1, n) [(rowOrder ! j, j <= i) | j <- [1 .. n]] \n in string7 $ map (bool 'R' 'B') (elems cs)\n pure $ case filter ok $ liftM2 (,) [1 .. n - 1] [1 .. m - 1] of\n (i, j) : _ -> string7 \"YES\\n\" <> colorRows i <> char7 ' ' <> putInts [j]\n _ -> string7 \"NO\\n\"\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Int\nimport Data.Bits\nimport Control.Arrow (first, second)\nimport Data.Bool\n\n\nprefSummary :: Ix i\n => (Int32 -> Int32 -> Int32) -> (i -> i) -> (i -> i)\n -> UArray i Int32 -> UArray i Int32\nprefSummary combine dec inc arr = runSTUArray $ do\n ans <- thaw arr\n let\n ok = inRange (bounds arr)\n go p = let\n q = inc p\n in when (ok q) $ do\n vp <- readArray ans p\n vq <- readArray ans q\n writeArray ans q $ combine vp vq\n go q\n forM_ (indices arr) $ \\p -> when (not $ ok (dec p)) $ go p\n pure ans\n\nfake_qsort :: (Int, Int) -> (Int -> Int32) -> UArray Int Int\n-- previously Data.List.sortOn was the memory bottleneck,\n-- so... use an in-place array sorting algorithm instead\nfake_qsort (p, q) fun = runSTUArray $ do\n arr <- newArray_ (p, q)\n forM_ [p .. q] $ \\i -> writeArray arr i i\n let\n maxv = foldl' (.|.) 0 $ map fun [p .. q]\n startBit = finiteBitSize maxv - 1 - countLeadingZeros maxv\n isort !scale !x !y = when (scale >= 0 && x < y) $ loop x y where\n -- Partitions the [x, y] index-interval according to bit 'scale'\n loop !i !j = if i < j\n -- 'i' is the next un-examined index\n -- 'j' is the first index maybe without bit 'scale' set\n then do\n ai <- readArray arr i\n case testBit (fun ai) scale of\n False -> loop (i + 1) j\n True -> do\n aj <- readArray arr j\n writeArray arr j ai\n writeArray arr i aj\n loop i (j - 1)\n else isort (scale - 1) x j >> isort (scale - 1) (j + 1) y\n arr <$ isort startBit p q\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n vals <- getInts (n * m)\n let\n a :: UArray (Int, Int) Int32\n a = listArray ((1, 1), (n, m)) $ map fromIntegral vals\n rowOrder :: UArray Int Int\n rowOrder = fake_qsort (1, n) (\\i -> a ! (i, 1))\n sa = ixmap ((1, 1), (n, m)) (\\(i, j) -> (rowOrder ! i, j)) a\n\n inc = (+ 1)\n dec = subtract 1\n mkPre lens combine = prefSummary combine (lens dec) (lens inc)\n mkSuff lens combine = prefSummary combine (lens inc) (lens dec)\n\n -- red is below the split point\n tlmax = mkPre first max $ mkPre second max sa\n blmin = mkSuff first min $ mkPre second min sa\n trmin = mkPre first min $ mkSuff second min sa\n brmax = mkSuff first max $ mkSuff second max sa\n\n ok (i, j)\n = tlmax ! (i, j ) < blmin ! (i + 1, j)\n && trmin ! (i, j + 1) > brmax ! (i + 1, j + 1)\n colorRows i = let\n cs :: UArray Int Bool\n cs = array (1, n) [(rowOrder ! j, j <= i) | j <- [1 .. n]] \n in string7 $ map (bool 'R' 'B') (elems cs)\n pure $ case filter ok $ liftM2 (,) [1 .. n - 1] [1 .. m - 1] of\n (i, j) : _ -> string7 \"YES\\n\" <> colorRows i <> char7 ' ' <> putInts [j]\n _ -> string7 \"NO\\n\"\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "10751c875f4d7667ba21685c57cddd9e"} {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[f,m,s,ma]]\n | sc >= mc || mc >= fc || 2*ma < sc || 2*s < sc || 2*ma >= mc = [ \"-1\" ]\n | otherwise = [ intercalate \"\\n\" $ map show [fc,mc,sc] ]\n where\n fc = 2*f\n mc = 2*m\n sc = max s ma\n\nsoly :: Int \u2192 [(Int,Int)] \u2192 Int\nsoly a as\n | Just x \u2190 lookup 10 as = x\n | Just x \u2190 lookup 20 as = x+11\n | otherwise = a\n\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n", "positive_code": [{"source_code": "main = getLine >>= putStr . maybe \"-1\" (\\(a, b, c) -> show a ++ \"\\n\" ++ show b ++ \"\\n\" ++ show c) . headMay . (\\[v1, v2, v3, vm] -> [(s1 :: Int, s2, s3) | s1 <- [max v1 $ 2*vm+1..2*v1], s2 <- [max v2$2*vm + 1..min (s1 - 1) (2 * v2)], s3 <- [max vm v3..min (s2 - 1) $ min (2*vm) (2*v3)]]) . map read . words\nheadMay [] = Nothing\nheadMay (x:_) = Just x\n"}], "negative_code": [{"source_code": "main = getLine >>= putStr . maybe \"-1\" (\\(a, b, c) -> show a ++ \"\\n\" ++ show b ++ \"\\n\" ++ show c) . headMay . (\\[v1, v2, v3, vm] -> [(s1 :: Int, s2, s3) | s1 <- [v1..2*v1], s2 <- [v2..min s1 $ 2*v2], s3 <- [v3..min s2 $ min (2*vm) (2*v3)], vm <= min s1 (min s2 s3), s3 <= 2 * vm]) . map read . words\nheadMay [] = Nothing\nheadMay (x:_) = Just x\n"}, {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[f,m,s,ma]]\n | sc >= mc || mc >= fc || 2*ma < sc || 2*s < sc = [ \"-1\" ]\n | otherwise = [ intercalate \"\\n\" $ map show [fc,mc,sc] ]\n where\n mc = 2*m\n fc = 2*f\n sc = max s ma\n\nsoly :: Int \u2192 [(Int,Int)] \u2192 Int\nsoly a as\n | Just x \u2190 lookup 10 as = x\n | Just x \u2190 lookup 20 as = x+11\n | otherwise = a\n\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}, {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[f,m,s,ma]]\n | m <= ma || s > sc = [ \"-1\" ]\n | otherwise = [ unlines $ map show [fc,mc,sc] ]\n where\n mmaa = 2*ma\n mc = 2*m\n fc = 2*f\n sc = 2 * (min s ma)\n\nsoly :: Int \u2192 [(Int,Int)] \u2192 Int\nsoly a as\n | Just x \u2190 lookup 10 as = x\n | Just x \u2190 lookup 20 as = x+11\n | otherwise = a\n\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}], "src_uid": "56535017d012fdfcc13695dfd5b33084"} {"source_code": "module Main where\n\nimport Data.List\n\ncompress :: [Int] -> [(Int, Int)]\ncompress xs = foldr go [] ys\n where\n ys = map (\\x -> (x, 1)) xs\n go x [] = [x]\n go x@(xv, _) l@((lv, li):ls)\n | xv == lv = (lv, li + 1):ls\n | otherwise = x:l\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = go k $ compress xs\n where\n go _ [] = -1\n go 0 ((lv, _):_)\n | lv == 1 = -1\n | otherwise = lv - 1\n go i ((lv, li):ls)\n | i == li = lv\n | i < li = -1\n | otherwise = go (i - li) ls\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read . words) getLine\n ns <- fmap (map read . words) getLine\n print $ solve k (sort ns)\n", "positive_code": [{"source_code": "import Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve (0:as) | minimum as == 1 = -1 | otherwise = 1\nsolve (k:as) | not (null t) && r == l = -1\n | otherwise = l\n where (l:t@ ~(r:_)) = drop (k-1) $ sort as\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [n,k] <- liftM (map (\\x->read x::Int).words) getLine\n as <- liftM (map (\\x->read x::Int).words) getLine\n print $ (\\(x,y) -> if null x then (if null y || head y < 2 then -1 else head y - 1) else if null y && last x <= 1000000000 then last x else if last x < head y && (head y) >= last x + 1 then last x else (-1)) $ (splitAt k) $ sort as \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print . maybe (-1) id $ solve n k xs\n\nsolve :: Int -> Int -> [Int] -> Maybe Int\nsolve _ 0 xs\n | elem 1 xs = Nothing\n | otherwise = Just 1\nsolve _ k xs\n | k == length (takeWhile(<=pivot)sorted) = Just pivot\n | otherwise = Nothing\n where\n !sorted = sort xs\n !pivot = sorted !! (k - 1)\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List\n\nreadIntegers :: String -> [Integer]\nreadIntegers = map read . words\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nsolve :: Int -> Int -> [Integer] -> Integer\nsolve n k a = let res = a !! k in\n if k == -1 && a !! 0 == 1 then -1 else\n if k == -1 then 1 else\n if k == (n-1) then res else \n if res == a !! (k + 1) then -1 else res\n \n\n\nmain :: IO ()\nmain = do\n a1 <- getLine\n a2 <- getLine\n let [n,k] = readInts a1\n let a = readIntegers a2\n let res = show (solve n (k-1) (sort a))\n putStrLn res"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as BS\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\n\nmain = BS.interact app\napp = BS.pack . evalState solve . BS.words\n\nsolve = do\n n <- nexti\n k <- nexti\n arr <- replicateM n nexti\n let result = let firstk = take k $ sort arr in if (length firstk == 0) then (if arr !! 0 > 1 then ((arr !! 0) - 1) else -1) else last firstk\n return $ show $ if (length $ filter (<=result) arr) == k then result else -1\n where\n nextw = state $ \\(x:xs) -> (x,xs)\n int = maybe undefined fst . BS.readInt\n nexti = fmap int nextw\n"}, {"source_code": "import Data.List\nmain = interact $ show. f. map read. words\nf :: [Int] -> Int\nf (n:k:as)\n | k == 0 = let d = head a - 1 in if d < 1 then -1 else 1\n | k == n = last a\n | a !! k == a !! (k - 1) = -1\n | otherwise = a !! (k - 1)\n where a = sort as\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.ByteString.Char8 as S\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\nimport Data.Char\nimport Data.Bits\nimport Data.Bool\nimport Data.Ratio\nimport qualified Data.Array as A\n\nreadArray = map (\\x -> fst . fromJust $ S.readInt x) . S.words <$> S.getLine\n\naccum [] = []\naccum (x:xs)\n | null yl = [(x,1)]\n | x /= (fst y) = ((x,1):yl)\n | otherwise = ((x, (snd y) + 1):ys)\n where yl = accum xs\n y = head yl\n ys = tail yl\n\nsol v k\n | k == 0 = if (fst . head) v == 1 then -1 else 1\n | otherwise = if null w then (-1) else fst . head $ w\n where w = filter (\\x -> (snd x) == k) v\n\nmain = do\n [n, k] <- readArray\n v <- scanl1 (\\(x,fx) (y,fy) -> (y,fx+fy)) . accum . sort <$> readArray\n print $ sol v k\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = do\n input <- fmap B.lines B.getContents\n let [n,k] = map readI $ B.words $ input!!0\n let as = map readI $ B.words $ input!!1\n print (solve n k as)\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as\n | k==0 = if head us > 1 then 1 else -1\n | otherwise= if null[()|u<- take 1 us, t==u] then t else -1\n where\n (ls,us) = splitAt k (sort as)\n t = last ls"}, {"source_code": "module Main where\n\nimport Data.List\nmain :: IO ()\nmain = do\n numsS <- getLine\n let nums = map (read :: String -> Int) $ words numsS\n valsS <- getLine\n let vals = map (read :: String -> Int) $ words valsS\n print $ solve (nums!!1) $ sort vals\n\nsolve :: Int -> [Int] -> Int\nsolve 0 (1:_) = -1\nsolve 0 lst = 1\n\nsolve k lst | (length lst) == k = last lst\n | otherwise =\n let (fstL, sndL) = splitAt k lst in\n let (fstV, sndV) = (last fstL, head sndL) in\n if (fstV == sndV)\n then -1\n else fstV\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\nf ::Int->[Int]->[Int]->Int\nf k [] []=(-1)\nf k (x:xs) (y:ys)\n |k-y<0=(-1)\n |k-y==0=x\n |otherwise=f (k-y) xs ys\n\nmain = do\n a<-getLine\n b<-getLine\n let (n:k:[])=map read (words a)::[Int]\n xs=map read (words b)::[Int]\n ys=group $ sort xs\n zs1=(map head ys)\n zs2=(map length ys)\n print $ if k==0 && (head zs1)>1 then 1 else f k zs1 zs2"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List\n\ncompress :: [Int] -> [(Int, Int)]\ncompress xs = foldr go [] ys\n where\n ys = map (\\x -> (x, 1)) xs\n go x [] = [x]\n go x@(xv, _) l@((lv, li):ls)\n | xv == lv = (lv, li + 1):ls\n | otherwise = x:l\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = go k $ compress xs\n where\n go _ [] = -1\n go i ((lv, li):ls)\n | i == li = lv\n | i < li = -1\n | otherwise = go (i - li) ls\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap (map read . words) getLine\n ns <- fmap (map read . words) getLine\n print $ solve k (sort ns)\n"}, {"source_code": "module Main where\n\nimport Data.List\nmain :: IO ()\nmain = do\n numsS <- getLine\n let nums = map (read :: String -> Int) $ words numsS\n valsS <- getLine\n let vals = map (read :: String -> Int) $ words valsS\n print $ solve (nums!!1) $ sort vals\n\nsolve :: Int -> [Int] -> Int\nsolve 0 lst = -1\nsolve k lst =\n let (fstL, sndL) = splitAt k lst in\n let (fstV, sndV) = (last fstL, head sndL) in\n if (fstV == sndV)\n then -1\n else fstV\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [n,k] <- liftM (map (\\x->read x::Int).words) getLine\n as <- liftM (map (\\x->read x::Int).words) getLine\n print $ (\\(x,y) -> if null x then (if null y || head y < 2 then -1 else head y - 1) else if null y && head x <= 1000000000 then head x else if last x < head y && (head y) > last x + 1 then last x else (-1)) $ (splitAt k) $ sort as \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [n,k] <- liftM (map (\\x->read x::Int).words) getLine\n as <- liftM (map (\\x->read x::Int).words) getLine\n print $ (\\(x,y) -> if null x || head x > 999999999 then (if null y || head y < 2 then -1 else head y - 1) else if last x < head y && (head y) > last x + 1 then last x else (-1)) $ (splitAt k) $ sort as \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [n,k] <- liftM (map (\\x->read x::Int).words) getLine\n as <- liftM (map (\\x->read x::Int).words) getLine\n print $ (\\(x,y) -> if null x then (if null y || head y < 2 then -1 else head y - 1) else if null y && head x <= 1000000000 then head x else if last x < head y && (head y) >= last x + 1 then last x else (-1)) $ (splitAt k) $ sort as \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [n,k] <- liftM (map (\\x->read x::Int).words) getLine\n as <- liftM (map (\\x->read x::Int).words) getLine\n print $ (\\(x,y) -> if null x then (if null y then -1 else head y - 1) else if last x < head y && (head y) > last x + 1 then last x else (-1)) $ (splitAt k) $ sort as \n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\nf ::Int->[Int]->[Int]->Int\nf k [] []=(-1)\nf k (x:xs) (y:ys)\n |k-y<0=(-1)\n |k-y==0=x\n |otherwise=f (k-y) xs ys\n\nmain = do\n a<-getLine\n b<-getLine\n let (n:k:[])=map read (words a)::[Int]\n xs=map read (words b)::[Int]\n ys=group $ sort xs\n zs1=(map head ys)\n zs2=(map length ys)\n print $ f k zs1 zs2"}, {"source_code": "import Data.List\nmain = interact $ show. f. map read. words\nf :: [Int] -> Int\nf (n:k:as)\n | null as = 33\n | k == n = 1 + last a\n | a !! k == a !! (k + 1) = -1\n | otherwise = a !! k - 1\n where a = sort as\n"}, {"source_code": "import Data.List\nmain = interact $ show. f. map read. words\nf :: [Int] -> Int\nf (n:k:as)\n | k == 0 = head a - 1\n | k == n = last a\n | a !! k == a !! (k - 1) = -1\n | otherwise = a !! (k - 1)\n where a = sort as\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport qualified Data.ByteString.Char8 as S\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\nimport Data.Char\nimport Data.Bits\nimport Data.Bool\nimport Data.Ratio\nimport qualified Data.Array as A\n\nreadArray = map (\\x -> fst . fromJust $ S.readInt x) . S.words <$> S.getLine\n\naccum [] = []\naccum (x:xs)\n | null yl = [(x,1)]\n | x /= (fst y) = ((x,1):yl)\n | otherwise = ((x, (snd y) + 1):ys)\n where yl = accum xs\n y = head yl\n ys = tail yl\n\nmain = do\n [n, k] <- readArray\n v <- filter (\\x -> (snd x) == k) . scanl1 (\\(x,fx) (y,fy) -> (y,fx+fy)) . accum . sort <$> readArray\n print $ if null v then (-1) else fst . head $ v\n"}], "src_uid": "55297e2a65144323af4d6abd6a6ef050"} {"source_code": "import Control.Monad\n\ndetect :: String -> Int\ndetect shape\n | shape == \"Tetrahedron\" = 4\n | shape == \"Cube\" = 6\n | shape == \"Octahedron\" = 8\n | shape == \"Dodecahedron\" = 12\n | shape == \"Icosahedron\" = 20\n\nmain:: IO()\nmain = do\n count <- readLn\n items <- replicateM count getLine\n let number = foldl (+) 0 $ (map detect items)\n putStrLn (show number)", "positive_code": [{"source_code": "main :: IO ()\nmain = print . solve . tail . words =<< getContents\n\nsolve :: [String] -> Int\nsolve [] = 0\nsolve (('T':_):sx) = 4 + solve sx\nsolve (('C':_):sx) = 6 + solve sx\nsolve (('O':_):sx) = 8 + solve sx\nsolve (('D':_):sx) = 12 + solve sx\nsolve (('I':_):sx) = 20 + solve sx\n"}, {"source_code": "module Main where\n\nmain = do\n count <- read <$> getLine\n shapes <- sequence $ replicate count getLine\n print $ sum $ map countFaces shapes\n\ncountFaces :: String -> Int\ncountFaces \"Tetrahedron\" = 4\ncountFaces \"Cube\" = 6\ncountFaces \"Octahedron\" = 8\ncountFaces \"Dodecahedron\" = 12\ncountFaces \"Icosahedron\" = 20"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nsolve :: [String] -> Integer\nsolve [] = 0\nsolve (\"Tetrahedron\":xs) = 4 + solve xs\nsolve (\"Cube\":xs) = 6 + solve xs\nsolve (\"Octahedron\":xs) = 8 + solve xs\nsolve (\"Dodecahedron\":xs) = 12 + solve xs\nsolve (\"Icosahedron\":xs) = 20 + solve xs\nsolve (_:xs) = solve xs\n\nmain :: IO ()\nmain = print =<< solve <$> lines <$> getContents\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsideCount :: String -> Int\nsideCount \"Tetrahedron\" = 4\nsideCount \"Cube\" = 6\nsideCount \"Octahedron\" = 8\nsideCount \"Dodecahedron\" = 12\nsideCount \"Icosahedron\" = 20\n\nsolve :: [String] -> Int\nsolve list = foldl (+) 0 (map sideCount list)\n\nreadListN :: Int -> IO [String]\nreadListN n = take n <$> words <$> getContents\n\ngetInteger :: IO Int\ngetInteger = (read :: String -> Int) <$> getLine\n\nmain :: IO ()\nmain = print =<< solve <$> (readListN =<< getInteger)\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\n\nmain = do { x <- getLine; y <- solve 0 (read x); putStrLn $ show $ y }\n\nsidesOf :: String -> Int\nsidesOf \"Icosahedron\" = 20\nsidesOf \"Dodecahedron\" = 12\nsidesOf \"Octahedron\" = 8\nsidesOf \"Cube\" = 6\nsidesOf \"Tetrahedron\" = 4\n\nsolve :: Int -> Int -> IO Int\nsolve a 0 = return a\nsolve a n = do { x <- getLine; solve (a + sidesOf x) (n-1) }"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Ord\nimport Data.Char\n\n\nextract (x:xs)=take (read x::Int) xs\n\nf \"Cube\"=6\nf \"Tetrahedron\"=4\nf \"Dodecahedron\"=12\nf \"Octahedron\"=8\nf \"Icosahedron\"=20\n\n\nmain=interact$show.sum.map f.extract.lines\n\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> (solve =<< forM [1..read n] ( \\i -> C.getLine))\nsolve xs = print $ sum $ map (\\i-> if C.head i =='T' then 4 else if C.head i =='O' then 8 else if C.head i =='I' then 20 else if C.head i =='C' then 6 else 12) xs"}, {"source_code": "import Data.Foldable\n\nmain = getLine\n >>= getLines . read\n >>= putStrLn . show . countFaces\n\ngetLines::Int -> IO [String]\ngetLines n = mapM (\\_ -> getLine) [1..n]\n\ncountFaces::[String] -> Int\ncountFaces strs = foldr' (\\str count -> getFaces str + count) 0 strs\n where getFaces \"Tetrahedron\" = 4\n getFaces \"Cube\" = 6\n getFaces \"Octahedron\" = 8\n getFaces \"Dodecahedron\" = 12\n getFaces _ = 20"}, {"source_code": "main = getLine\n >>= getLines . read\n >>= putStrLn . show . countFaces\n\ngetLines::Int -> IO [String]\ngetLines n = mapM (\\_ -> getLine) [1..n]\n\ncountFaces::[String] -> Int\ncountFaces strs = foldr (\\str count -> getFaces str + count) 0 strs\n where getFaces \"Tetrahedron\" = 4\n getFaces \"Cube\" = 6\n getFaces \"Octahedron\" = 8\n getFaces \"Dodecahedron\" = 12\n getFaces _ = 20"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Monad\nimport Prelude\n\nreadInt :: String -> Int\nreadInt = read\n\npolyhedronFaces :: String -> Int\npolyhedronFaces \"Tetrahedron\" = 4\npolyhedronFaces \"Cube\" = 6\npolyhedronFaces \"Octahedron\" = 8\npolyhedronFaces \"Dodecahedron\" = 12\npolyhedronFaces \"Icosahedron\" = 20\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n polyhedrons <- sequence . replicate n $ getLine\n let answer = sum . map polyhedronFaces $ polyhedrons\n printf \"%d\" answer"}, {"source_code": "import Control.Applicative\ntr 'T' =4\ntr 'C' =6\ntr 'D' =12\ntr 'I' =20\ntr 'O' =8\n\n\n\nmain=do\n getLine\n x<-sum <$> map tr <$> map head <$> lines <$> getContents\n print x\n"}, {"source_code": "import Data.Maybe\nmain = interact $ show . solve\nsolve = sum . mapMaybe (flip lookup ss . head) . tail . lines\nss = [('T',4),('C',6),('O',8),('D',12),('I',20)]\n"}, {"source_code": "p 'T' = 4\np 'C' = 6\np 'O' = 8\np 'D' = 12\np 'I' = 20\nmain = interact $ show . sum . map (p . head) . tail . lines"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM)\nmain = do\n n_ <- readLn\n polyhedrons_ <- replicateM n_ getLine\n let\n\tface \"Tetrahedron\" = 4\n\tface \"Cube\"\t = 6\n\tface \"Octahedron\" = 8\n\tface \"Dodecahedron\" = 12\n\tface \"Icosahedron\" = 20\n print . sum $ map face polyhedrons_\n"}, {"source_code": "import Control.Monad\n\ngetFaceCount name\n | name == \"Tetrahedron\" = 4\n | name == \"Cube\" = 6\n | name == \"Octahedron\" = 8\n | name == \"Dodecahedron\" = 12\n | name == \"Icosahedron\" = 20\n\nmain :: IO()\nmain = do\n w <- getLine\n s <- forM [1..(read w :: Int)] $ \\i -> getLine\n print $ sum (map getFaceCount s)\n"}, {"source_code": "main = do\n contents <- getContents\n let a = tail . lines $ contents\n print (f a)\n\nf :: [[Char]] -> Int\nf [] = 0\nf (x:xs)\n | x == \"Tetrahedron\" = 4 + f xs\n | x == \"Cube\" = 6 + f xs\n | x == \"Octahedron\" = 8 + f xs\n | x == \"Dodecahedron\" = 12 + f xs\n | x == \"Icosahedron\" = 20 + f xs\n | otherwise = error \"no match\""}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\n\nface \"Tetrahedron\" = 4\nface \"Cube\" = 6\nface \"Octahedron\" = 8\nface \"Dodecahedron\" = 12\nface \"Icosahedron\" = 20\n\nmain = do\n (read -> t :: Int) <- getLine\n s <- forM [1..t] $ \\i -> getLine\n putStrLn $ show $ sum (map face s)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nr \"Cube\" = 6\nr \"Icosahedron\" = 20\nr \"Tetrahedron\" = 4\nr \"Dodecahedron\" = 12\nr \"Octahedron\" = 8\n\nmain= do\n\t\tgetLine\n\n\t\ta<-sum <$> map r <$> lines <$> getContents\n\t\tprint a\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getContents >>= print . sum . map faces . tail . lines\n\nfaces \"Tetrahedron\" = 4\nfaces \"Cube\" = 6\nfaces \"Octahedron\" = 8\nfaces \"Dodecahedron\" = 12\nfaces \"Icosahedron\" = 20\n"}, {"source_code": "import qualified Data.Map as Map\nimport Control.Monad\n\ng [] = 0\ng (x : xs) = do\n case Map.lookup x (Map.fromList [(\"Tetrahedron\", 4), (\"Cube\", 6), (\"Octahedron\", 8), (\"Dodecahedron\", 12), (\"Icosahedron\", 20)]) of\n Just y -> y + (g $ xs)\n Nothing -> g $ xs\n\nmain = do\n b <- readLn\n inputs <- replicateM b getLine\n putStrLn $ show $ g inputs"}, {"source_code": "import Control.Monad\nfaces s\n | head s == 'T' = 4\n | head s == 'C' = 6\n | head s == 'O' = 8\n | head s == 'D' = 12\n | head s == 'I' = 20\n | otherwise = 0\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int ) <$> getLine \n print =<< sum . map faces <$> replicateM n getLine"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n val <- getLine\n let n = read val :: Int\n xs <- forM [1..n] (\\_ -> getLine)\n print (foldr (+) 0 $ map polyAnalysis xs)\n\npolyAnalysis :: String -> Int \npolyAnalysis str\n |str == \"Tetrahedron\" = 4\n |str == \"Cube\" = 6\n |str == \"Octahedron\" = 8\n |str == \"Dodecahedron\" = 12\n |str == \"Icosahedron\" = 20\n"}, {"source_code": "--ghc 7.10\n\nsides :: String -> Int\nsides \"Tetrahedron\" = 4\nsides \"Cube\" = 6\nsides \"Octahedron\" = 8\nsides \"Dodecahedron\" = 12\nsides \"Icosahedron\" = 20\nsides _ = 0\n\ntotalSides :: [String] -> Int\ntotalSides polyhedrons = sum . map sides $ polyhedrons\n\nmain = do\n line <- getLine\n contents <- getContents\n let polyhedrons = words contents\n print . totalSides $ polyhedrons"}, {"source_code": "module Main where \n\nimport Control.Monad\nimport Data.IORef\n\nconv :: Char -> Int\nconv 'T' = 4\nconv 'C' = 6\nconv 'O' = 8\nconv 'D' = 12\nconv 'I' = 20\nconv _ = 0\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n x <- newIORef 0 :: IO (IORef Int)\n replicateM_ n $ do\n y <- getLine >>= return . conv . head\n modifyIORef x (+ y)\n readIORef x >>= putStrLn . show\n \n"}, {"source_code": "module Main where \nimport qualified Data.ByteString.Char8 as B\n\nconv :: Char -> Int\nconv 'T' = 4\nconv 'C' = 6\nconv 'O' = 8\nconv 'D' = 12\nconv 'I' = 20\nconv _ = 0\n\naddup :: Int -> Int -> IO ()\naddup 0 x = putStrLn . show $ x\naddup n x = B.getLine >>= addup (n-1) . (+ x) . conv . B.head \n\nmain :: IO ()\nmain = (readLn :: IO Int) >>= (flip addup) 0\n \n"}, {"source_code": "module Main where \n\nconv :: Char -> Int\nconv 'T' = 4\nconv 'C' = 6\nconv 'O' = 8\nconv 'D' = 12\nconv 'I' = 20\nconv _ = 0\n\n\naddup :: Int -> Int -> IO ()\naddup 0 x = putStrLn . show $ x\naddup n x = getLine >>= addup (n-1) . (+ x) . conv . head \n\nmain :: IO ()\nmain = (readLn :: IO Int) >>= (flip addup) 0\n \n"}, {"source_code": "module Main where \nimport qualified Data.ByteString as W\n\nconv 84 = 4\nconv 67 = 6\nconv 79 = 8\nconv 68 = 12\nconv 73 = 20\nconv _ = 0\n\naddup :: Int -> Int -> IO ()\naddup 0 x = putStrLn . show $ x\naddup n x = W.getLine >>= addup (n-1) . (+ x) . conv . W.head \n\nmain :: IO ()\nmain = (readLn :: IO Int) >>= (flip addup) 0\n \n"}, {"source_code": "module Main where \n\nimport Data.Foldable\n\nconv :: Char -> Int\nconv 'T' = 4\nconv 'C' = 6\nconv 'O' = 8\nconv 'D' = 12\nconv 'I' = 20\nconv _ = 0\n\naddup :: Int -> Int -> IO Int\naddup x _ = getLine >>= return . (+ x) . conv . head \n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n foldlM addup 0 [1..n] >>= putStrLn . show\n \n"}, {"source_code": "import qualified Data.Map as M\n\nmain = do\n n <- getLine\n l <- mapM f [1..(read n :: Int)]\n putStrLn . show . sum $ l\n\nf :: Int -> IO Int\nf _ = do\n let m = M.fromList [(\"Tetrahedron\", 4), (\"Cube\", 6), (\"Octahedron\", 8), (\"Dodecahedron\", 12), (\"Icosahedron\", 20)]\n pol <- getLine\n case M.lookup pol m of\n Just x -> return x"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nr \"Cube\" = 6\nr \"Icosahedron\" = 20\nr \"Tetrahedron\" = 4\nr \"Dodecahedron\" = 12\n\nmain= do\n\t\tgetLine\n\t\tprint <$> sum <$> map r <$> lines <$> getContents\n"}], "src_uid": "e6689123fefea251555e0e096f58f6d1"} {"source_code": "import Control.Monad\nimport Data.List (sort)\n\nmain = do\n t <- read <$> getLine\n forM_ [1..t] $ const solve\n\nsolve = do\n n <- read <$> getLine\n dirs <- let\n trans 'L' = 1\n trans _ = 0\n in (fmap . fmap) trans getLine\n let init = (\\(i, d) -> i*d + (n-i-1)*(1-d)) <$> zip [0..] dirs\n let compl = (\\(i, d) -> i*(1-d) + (n-i-1)*d) <$> zip [0..] dirs\n let diffs = reverse . sort $ (\\(x, y) -> max 0 (y-x)) <$> zip init compl\n let res = (sum init +) <$> scanl1 (+) diffs\n putStrLn (unwords $ show <$> res)\n", "positive_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport qualified Data.Set as S\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List\n\nsolve :: Integer -> String -> String\nsolve n s =\n let cur = foldr (\\(el, idx) s -> s + calcCur el idx n) (toInteger 0) (zip s [0..])\n in unwords $ map show (solve1 0 cur (reverse $ sort $ getCan s n))\n\n\n--solve1 :: Integer -> [Integer] -> [Integer]\nsolve1 _ _ [] = []\nsolve1 acc cur (x:xs) = (acc + x + cur) : (solve1 (acc + x) cur xs)\n\n\ngetCan :: String -> Integer -> [Integer]\ngetCan s n = [ calcMax el (toInteger idx) n - calcCur el (toInteger idx) n | (el, idx) <- zip s [0..] ]\n\n\ncalcMax :: Char -> Integer -> Integer -> Integer\ncalcMax el idx n = max idx (n - idx - 1)\n\n\ncalcCur :: Char -> Integer -> Integer -> Integer\ncalcCur el idx n\n | el == 'L' = toInteger idx\n | el == 'R' = toInteger n - idx - 1\n\n\nwork = do\n n <- getLine\n s <- getLine\n\n putStrLn $ solve (read n :: Integer) s\n\nmain = do\n t <- getLine\n\n replicateM_ (read t :: Int) work\n"}, {"source_code": "{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications, TupleSections #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List hiding (lookup)\r\nimport Debug.Trace\r\nimport Data.Char\r\nimport Data.Map (Map, fromListWith)\r\nimport qualified Data.Map as M\r\nimport Data.Int\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- getNext\r\n let\r\n sa = P.unpack a\r\n n = length sa\r\n f :: (Int, Char) -> Int64\r\n f (i, 'L') = fromIntegral i\r\n f (i, 'R') = fromIntegral $ n - i - 1\r\n\r\n swap 'L' = 'R'\r\n swap 'R' = 'L'\r\n\r\n basevals, opvals, swapvals :: [Int64]\r\n basevals = map f $ zip [0..] sa where\r\n opvals = map f . zip [0..] . map swap $ sa\r\n swapvals = zipWith (\\a b -> max 0 (a - b)) opvals basevals\r\n baseval = sum basevals\r\n rawvals = take n . reverse . sort $ swapvals\r\n ans :: [Int64]\r\n ans = map ((+) baseval) $ scanl1 (+) rawvals\r\n strans :: [String]\r\n strans = map (show) ans\r\n fmap mconcat . pure . map str $ (map (\\s -> s ++ \" \") strans) ++ [\"\\n\"]\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List (sort)\n\nmain = do\n t <- read <$> getLine\n forM_ [1..t] $ const solve\n\nsolve = do\n n <- read <$> getLine\n dirs <- let\n trans 'L' = 1\n trans _ = 0\n in (fmap . fmap) trans getLine\n let init = (\\(i, d) -> i*d + (n-i-1)*(1-d)) <$> zip [0..] dirs\n let compl = (\\(i, d) -> i*(1-d) + (n-i-1)*d) <$> zip [0..] dirs\n let diffs = reverse . sort $ (\\(x, y) -> max 0 (y-x)) <$> zip init compl\n let res = scanl (+) (sum init) diffs\n putStrLn (unwords $ show <$> res)\n"}], "src_uid": "f0402399cbaf8997993ac2ee59a60696"} {"source_code": "import Data.ByteString.Char8 (lines, words, getLine, getContents, readInt)\nimport Control.Monad (when)\nimport Data.Array (listArray, (!), bounds)\nimport Data.List (sort)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, m, k, s] <- (map readInt' . words) `fmap` getLine :: IO [Int]\n ds <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n ps <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n\n gs <- (map ((\\[a, b] -> (a, b)) . map (fromIntegral . readInt') . words) . lines) `fmap` getContents\n\n let\n (dgs, pgs) = (f 1, f 2)\n where\n f t = listArray (0, length l) $ 0:l\n where\n l = scanl1 (+) . sort . map snd $ filter ((== t) . fst) gs\n\n check d =\n (minimum [f x y | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]) <= (fromIntegral s)\n where\n dollar = minimum $ take d ds\n pound = minimum $ take d ps\n\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n search l r\n | l > r = -1\n | l == r = if b then l else -1\n | l < r = if b\n then search l m\n else search (m + 1) r\n where\n m = (l + r) `div` 2\n b = check m\n\n get d = \n zip (take x dis) (replicate x dollard) ++ zip (take y pis) (replicate y poundd)\n where\n (dollar, dollard) = minimum $ zip (take d ds) [1..]\n (pound, poundd) = minimum $ zip (take d ps) [1..]\n\n (dis, pis) = (f 1, f 2)\n where\n f t = map snd . sort . map (\\((t, p), i) -> (p, i)) . filter ((== t) . fst . fst) $ zip gs [1..]\n\n (_, x, y) = minimum [(f x y, x, y) | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]\n where\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n\n r = search 1 n \n \n print r\n when (r /= -1) $ putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ get r\n", "positive_code": [{"source_code": "import Data.ByteString.Char8 (lines, words, getLine, getContents, readInt)\nimport Control.Monad (when)\nimport Data.Array (listArray, (!), bounds)\nimport Data.List (sort)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, m, k, s'] <- (map readInt' . words) `fmap` getLine :: IO [Int]\n let s = fromIntegral s' :: Int64\n ds <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n ps <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n\n gs <- (map ((\\[a, b] -> (a, b)) . map (fromIntegral . readInt') . words) . lines) `fmap` getContents\n\n let\n dgs = listArray (0, length l) $ 0:l\n where\n l = scanl1 (+) . sort . map snd $ filter ((==1) . fst) gs\n pgs = listArray (0, length l) $ 0:l\n where\n l = scanl1 (+) . sort . map snd $ filter ((==2) . fst) gs\n\n check d =\n (minimum [f x y | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]) <= s\n where\n dollar = minimum $ take d ds\n pound = minimum $ take d ps\n\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n search l r\n | l > r = -1\n | l == r = if b then l else -1\n | l < r = if b\n then search l m\n else search (m + 1) r\n where\n m = (l + r) `div` 2\n b = check m\n\n get d = \n zip (take x dis) (replicate x dollard) ++ zip (take y pis) (replicate y poundd)\n where\n (dollar, dollard) = minimum $ zip (take d ds) [1..]\n (pound, poundd) = minimum $ zip (take d ps) [1..]\n\n dis = map snd $ sort $ map (\\((t, p), i) -> (p, i)) $ filter ((==1) . fst . fst) $ zip gs [1..]\n pis = map snd $ sort $ map (\\((t, p), i) -> (p, i)) $ filter ((==2) . fst . fst) $ zip gs [1..]\n\n (_, x, y) = minimum [(f x y, x, y) | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]\n where\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n\n r = search 1 n \n \n print r\n when (r /= -1) $ putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ get r\n"}], "negative_code": [{"source_code": "import Control.Monad (when)\nimport Data.Array (listArray, (!), bounds)\nimport Data.List (sort)\n\nmain = do\n [n, m, k, s] <- (map read . words) `fmap` getLine\n ds <- (map read . words) `fmap` getLine\n ps <- (map read . words) `fmap` getLine\n\n gs <- (map ((\\[a, b] -> (a, b)) . map read . words) . lines) `fmap` getContents\n\n let\n dgs = listArray (0, length l) $ 0:l\n where\n l = scanl1 (+) . sort . map snd $ filter ((==1) . fst) gs\n pgs = listArray (0, length l) $ 0:l\n where\n l = scanl1 (+) . sort . map snd $ filter ((==2) . fst) gs\n\n check d =\n (minimum [f x y | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]) <= s\n where\n dollar = minimum $ take d ds\n pound = minimum $ take d ps\n\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n search l r\n | l > r = -1\n | l == r = if b then l else -1\n | l < r = if b\n then search l m\n else search (m + 1) r\n where\n m = (l + r) `div` 2\n b = check m\n\n get d = \n zip (take x dis) (replicate x dollard) ++ zip (take y pis) (replicate y poundd)\n where\n (dollar, dollard) = minimum $ zip (take d ds) [1..]\n (pound, poundd) = minimum $ zip (take d ps) [1..]\n\n dis = map snd $ sort $ map (\\((t, p), i) -> (p, i)) $ filter ((==1) . fst . fst) $ zip gs [1..]\n pis = map snd $ sort $ map (\\((t, p), i) -> (p, i)) $ filter ((==2) . fst . fst) $ zip gs [1..]\n\n (_, x, y) = minimum [(f x y, x, y) | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]\n where\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n\n r = search 1 n \n \n print r\n when (r /= -1) $ putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ get r\n"}, {"source_code": "import Data.ByteString.Char8 (lines, words, getLine, getContents, readInt)\nimport Control.Monad (when)\nimport Data.Array (listArray, (!), bounds)\nimport Data.List (sort)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, m, k, s] <- (map readInt' . words) `fmap` getLine :: IO [Int]\n ds <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n ps <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n\n gs <- (map ((\\[a, b] -> (a, b)) . map (fromIntegral . readInt') . words) . lines) `fmap` getContents\n\n let\n (dgs, pgs) = (f 1, f 2)\n where\n f t = listArray (0, length l) $ 0:l\n where\n l = sort . scanl1 (+) . map snd $ filter ((== t) . fst) gs\n\n check d =\n (minimum [f x y | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]) <= (fromIntegral s)\n where\n dollar = minimum $ take d ds\n pound = minimum $ take d ps\n\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n search l r\n | l > r = -1\n | l == r = l\n | l < r = if b\n then search l m\n else search (m + 1) r\n where\n m = (l + r) `div` 2\n b = check m\n\n get d = \n zip (take x dis) (replicate x dollard) ++ zip (take y pis) (replicate y poundd)\n where\n (dollar, dollard) = minimum $ zip (take d ds) [1..]\n (pound, poundd) = minimum $ zip (take d ps) [1..]\n\n (dis, pis) = (f 1, f 2)\n where\n f t = map snd . sort . map (\\((t, p), i) -> (p, i)) . filter ((== t) . fst . fst) $ zip gs [1..]\n\n (_, x, y) = minimum [(f x y, x, y) | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]\n where\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n\n r = search 1 n \n \n print r\n when (r /= -1) $ putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ get r\n"}, {"source_code": "import Data.ByteString.Char8 (lines, words, getLine, getContents, readInt)\nimport Control.Monad (when)\nimport Data.Array (listArray, (!), bounds)\nimport Data.List (sort)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (lines, words, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, m, k, s] <- (map readInt' . words) `fmap` getLine :: IO [Int]\n ds <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n ps <- (map (fromIntegral . readInt') . words) `fmap` getLine :: IO [Int64]\n\n gs <- (map ((\\[a, b] -> (a, b)) . map (fromIntegral . readInt') . words) . lines) `fmap` getContents\n\n let\n (dgs, pgs) = (f 1, f 2)\n where\n f t = listArray (0, length l) $ 0:l\n where\n l = sort . scanl1 (+) . map snd $ filter ((== t) . fst) gs\n\n check d =\n (minimum [f x y | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]) <= (fromIntegral s)\n where\n dollar = minimum $ take d ds\n pound = minimum $ take d ps\n\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n search l r\n | l > r = -1\n | l == r = if b then l else -1\n | l < r = if b\n then search l m\n else search (m + 1) r\n where\n m = (l + r) `div` 2\n b = check m\n\n get d = \n zip (take x dis) (replicate x dollard) ++ zip (take y pis) (replicate y poundd)\n where\n (dollar, dollard) = minimum $ zip (take d ds) [1..]\n (pound, poundd) = minimum $ zip (take d ps) [1..]\n\n (dis, pis) = (f 1, f 2)\n where\n f t = map snd . sort . map (\\((t, p), i) -> (p, i)) . filter ((== t) . fst . fst) $ zip gs [1..]\n\n (_, x, y) = minimum [(f x y, x, y) | x <- [0..k], let y = k - x, x <= snd (bounds dgs), y <= snd (bounds pgs)]\n where\n f x y = (dgs ! x) * dollar + (pgs ! y) * pound\n\n\n r = search 1 n \n \n print r\n when (r /= -1) $ putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ get r\n"}], "src_uid": "045c8f116415f277fb7cf1109488b589"} {"source_code": "import Data.List\nimport Control.Monad\n\nrd arg = map read $ words arg :: [Int]\n\neval :: [(Int, Int, Int)]->Int\neval [] = 0\neval [(a,b,_)] = (b - a) * 2\neval ((a,b,_):(c,d,_):xs) = if b >= c then eval ((a,max b d,0):xs) else (b-a) * 2 + (eval ((c,d,0):xs))\n\nbs :: [Int]->Int->Int->[(Int, Int, Int)]->Int->Int\nbs lst le ri trp t = if le + 1 == ri then le else if eval (filter (\\(_,_,e)->(pt(m,n,k,t)) $ rd st1\n let sld = rd st2\n isl <- replicateM k getLine\n let trp = map ((\\[a,b,c]->(a-1,b,c)) . rd) isl\n print $ bs (reverse (sort sld)) 0 (m+1) (sort trp) (t-n-1)\n \n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\nw arg=map read$words arg::[Int]\no[]=0\no[(a,b,_)]=(b-a)*2\no((a,b,_):(c,d,_):x)=if b>=c then o((a,max b d,0):x)else(b-a)*2+(o((c,d,0):x))\nb p l r y t=if l+1==r then l else if o (filter (\\(_,_,e)->(k(m,n,k,t))$w p;\n let s=w q\n i<-replicateM k getLine;let y=map ((\\[a,b,c]->(a-1,b,c)).w) i\n print $b (reverse (sort s)) 0 (m+1) (sort y) (t-n-1)\n \n"}], "negative_code": [], "src_uid": "14d158dd02d65096946445e14a5f210d"} {"source_code": "module Main where\nimport Data.Functor ((<&>))\nimport Control.Monad (forM, replicateM, replicateM_)\nimport Data.Foldable (traverse_)\nimport GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)\nimport Data.List (group, sort)\nimport Data.Ratio ((%))\nimport Prelude hiding (floor)\nimport Control.Monad (forM_, replicateM_)\nimport Data.Function ((&))\n\nreadInts :: IO [Int]\nreadInts = getLine <&> words <&> fmap read\n\nreadString :: IO String\nreadString = getLine\n\ntoDoubles :: (Functor f, Integral a) => f a -> f Double\ntoDoubles xs = (\\x -> fromIntegral x :: Double) <$> xs\n\ntoDouble :: (Integral a) => a -> Double\ntoDouble = fromIntegral\n\nceil :: Double -> Int\nceil = ceilingDoubleInt\n\nfloor :: Double -> Int\nfloor = floorDoubleInt\n\n{-\n(a2 - a1) * 2 >= a1 + a2\n2 * a2 - 2 * a1 >= a1 + a2\na2 >= 3 * a1\na2 = 3 * a1\n-}\n\nmain :: IO ()\nmain = do\n t:_ <- readInts\n replicateM_ t $ do\n n:_ <- readInts\n let\n m = floor (logBase 3 1e9) + 1\n ans = zipWith (flip (**)) [0..] (replicate m 3) <&> toInteger . floor\n if n <= m\n then do\n putStrLn \"YES\" \n forM_ (take n ans) (\\x -> do {putStr $ show x; putStr \" \"})\n else putStr \"NO\"\n putStr \"\\n\"", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nmain = do \n testCases <- readLn\n let a = (1::Int) : map (*3) a\n max = length (takeWhile (<=10^9) a)\n in replicateM testCases (readLn >>= \\x -> \n if x > max then putStrLn \"NO\"\n else do \n putStrLn \"YES\"\n putStrLn $ intercalate \" \" (map show (take x a))\n )\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n let l = takeWhile (<= 10^9) $ iterate (*3) 1\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn\r\n if n > length l\r\n then\r\n putStrLn \"NO\"\r\n else\r\n putStrLn $ (\"YES\\n\" <>) . unwords . map show . take n $ l\r\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.Functor ((<&>))\nimport Control.Monad (forM, replicateM, replicateM_)\nimport Data.Foldable (traverse_)\nimport GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)\nimport Data.List (group, sort)\nimport Data.Ratio ((%))\nimport Prelude hiding (floor)\nimport Control.Monad (forM_, replicateM_)\nimport Data.Function ((&))\n\nreadInts :: IO [Int]\nreadInts = getLine <&> words <&> fmap read\n\nreadString :: IO String\nreadString = getLine\n\ntoDoubles :: (Functor f, Integral a) => f a -> f Double\ntoDoubles xs = (\\x -> fromIntegral x :: Double) <$> xs\n\ntoDouble :: (Integral a) => a -> Double\ntoDouble = fromIntegral\n\nceil :: Double -> Int\nceil = ceilingDoubleInt\n\nfloor :: Double -> Int\nfloor = floorDoubleInt\n\n{-\n(a2 - a1) * 2 >= a1 + a2\n2 * a2 - 2 * a1 >= a1 + a2\na2 >= 3 * a1\na2 = 3 * a1\n-}\n\nmain :: IO ()\nmain = do\n t:_ <- readInts\n replicateM_ t $ do\n n:_ <- readInts\n let\n m = floor (logBase 3 1e9)\n ans = zipWith (flip (**)) [0..] (replicate m 3) <&> toInteger . floor\n if n <= m + 1\n then do\n putStrLn \"YES\" \n forM_ (take n ans) (\\x -> do {putStr $ show x; putStr \" \"})\n else putStr \"NO\"\n putStr \"\\n\""}, {"source_code": "module Main where\nimport Data.Functor ((<&>))\nimport Control.Monad (forM, replicateM, replicateM_)\nimport Data.Foldable (traverse_)\nimport GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)\nimport Data.List (group, sort)\nimport Data.Ratio ((%))\nimport Prelude hiding (floor)\nimport Control.Monad (forM_, replicateM_)\n\nreadInts :: IO [Int]\nreadInts = getLine <&> words <&> fmap read\n\nreadString :: IO String\nreadString = getLine\n\ntoDoubles :: (Functor f, Integral a) => f a -> f Double\ntoDoubles xs = (\\x -> fromIntegral x :: Double) <$> xs\n\ntoDouble :: (Integral a) => a -> Double\ntoDouble = fromIntegral\n\nceil :: Double -> Int\nceil = ceilingDoubleInt\n\nfloor :: Double -> Int\nfloor = floorDoubleInt\n\n\n\nmain :: IO ()\nmain = do\n t:_ <- readInts\n replicateM_ t $ do\n n:_ <- readInts\n let\n m = 29\n ans = zipWith (flip (**)) [0..] (replicate m 2) <&> toInteger . floor\n if n <= m\n then do\n putStrLn \"YES\" \n forM_ (take n ans) (\\x -> do {putStr $ show x; putStr \" \"})\n else putStr \"NO\"\n putStr \"\\n\""}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do \n testCases <- readLn\n let max = 10^9 \n a = (1::Int) : map (*3) a\n in replicateM testCases (readLn >>= \\x -> \n if x >= 18 then putStrLn \"NO\"\n else do \n putStrLn \"YES\"\n putStrLn $ intercalate \" \" (map show (take x a))\n )\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do \n testCases <- readLn\n let max = 10^9 \n a = (1::Int) : map (*3) a\n in replicateM testCases (readLn >>= \\x -> \n if x > 18 then putStrLn \"NO\"\n else do \n putStrLn \"YES\"\n putStrLn $ intercalate \" \" (map show (take x a))\n )\n"}], "src_uid": "c8fddee2f1c7d325437a7d0b82758b03"} {"source_code": "{-# LANGUAGE NPlusKPatterns #-}\nmodule Main where\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\ngetWords :: IO [String]\ngetWords = fmap words getLine\n\ntype Contestant = (String, Int, Int)\n\ngetContestant :: IO Contestant\ngetContestant = do\n [name, before, after] <- getWords\n return (name, read before, read after)\n\nmain :: IO ()\nmain = do\n n <- getInt\n cts <- doMany n getContestant\n putStrLn $ showFlag $ any witness cts\n\ndoMany :: Int -> IO a -> IO [a]\ndoMany 0 _ = return []\ndoMany (n + 1) act = do\n a <- act\n as <- doMany n act\n return (a : as)\n\nwitness :: Contestant -> Bool\nwitness (_, before, after) = before >= 2400 && after > before\n\ndoManyTill :: Int -> IO a -> (a -> Bool) -> IO Bool\ndoManyTill 0 _ _ = return False\ndoManyTill (n + 1) act p = do\n a <- act\n if p a\n then return True\n else doManyTill n act p\n\nshowFlag :: Bool -> String\nshowFlag True = \"YES\"\nshowFlag False = \"NO\"\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n \n \n\n \n\nmain = do\n\tgetLine \n\ty<- filter (\\z-> head z < head (tail z)) . filter (\\z-> head z >=2400) . map (map read ). map tail. map words. lines <$> getContents ::IO [[Int]]\n\tputStrLn $ if y ==[] then \"NO\" else \"YES\"\n\t\n\t\n\t \n\t\n \n\t\n\t\n \n\n\n "}, {"source_code": "process :: [(Int, Int)] -> Bool\nprocess = any (\\(s,t) -> s >= 2400 && s < t)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs' <- fmap (map (map readInt.tail.words).lines) getContents\n let xs = map (\\[s,t] -> (s,t)) xs'\n if process xs\n then putStrLn \"YES\"\n else putStrLn \"NO\""}, {"source_code": "\nmain = interact $ (\\b -> if b then \"YES\" else \"NO\") . not . null . filter (\\[r1, r2] -> r1 >= 2400 && r2 > r1) . map (map read . tail . words) . tail . lines\n\n\n"}, {"source_code": "main :: IO()\nmain = output . solve . tail . words =<< getContents\n\noutput :: Bool -> IO()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [String] -> Bool\nsolve [] = False\nsolve (s:sa:sb:x) = let a = read sa\n b = read sb\n in (a >= 2400 && b > a) || solve x\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ls <- replicateM n $ map read . tail . words <$> getLine\n\n let b = any (\\[a, b] -> a >= 2400 && b > a) ls\n\n putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "module Main where\n\nmain = do\n w <- getLine\n w0 <- getContents\n let pool = [niceForm x | x <- (lines w0)]\n let r = solution pool\n if elem True r\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nniceForm :: String -> (Int,Int)\nniceForm w = (n0,n1)\n where [n0,n1] = map read (tail $ words w)\n\nsolution :: [(Int,Int)] -> [Bool]\nsolution [] = []\nsolution (x:xs) = (((fst x) >= 2400) && ((snd x) > (fst x))) : solution xs\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\n--import qualified Data.Map as M\n---import qualified Data.Vector as V\n--import qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n t <- fmap read getLine\n inp <- forM [1..t] $ \\_ -> fmap words getLine\n if solve inp then putStrLn \"YES\" else putStrLn \"NO\"\n\n\n\nsolve :: [[String]] -> Bool\nsolve = any f\n where\n f [_, x, y] = read y > (read x :: Int) && read x >= 2400\n"}, {"source_code": "main = do\n n <- getLine\n d <- sequence $ replicate (read n) getLine\n let a = map (map read . tail . words) d\n putStrLn $ if foldl (\\acc [x, y] -> if 2400 <= x && x < y then True else acc\n ) False a then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\n\nf::String->Bool\nf x=let (n:a:b:[])=words x\n a2=read a::Int\n b2=read b::Int\n in if a2>=2400 && b2>a2 then True else False\n\nmain=do\n e1<-getLine\n es<-getContents\n let xs=lines es\n putStrLn $ if any f xs then \"YES\" else \"NO\""}, {"source_code": "\n\nmain = interact solve\n\nsolve input = answer\n where\n n_s:inputw = words input\n\n n::Int\n n = read n_s\n\n scores::[(Int,Int)]\n scores = by_two $ map read $ last_two_by_three inputw\n\n highers = filter (\\(x,y) -> (y > x) && x >= 2400) scores \n\n answer \n | one_or_more highers = \"YES\"\n | otherwise = \"NO\"\n\nlast_two_by_three [] = []\nlast_two_by_three (x:y:z:xs) = y:z:(last_two_by_three xs)\n\nby_two [] = []\nby_two (x:y:xs) = (x,y):(by_two xs)\n\none_or_more [] = False \none_or_more (x:xs) = True \n"}, {"source_code": "main = interact $ format . any qualifies . tail . lines\nqualifies l = a >= 2400 && a < b where [a,b] = map read (tail (words l))\nformat True = \"YES\"\nformat False = \"NO\"\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n \nmain = do n <- readLn\n ls <- map ((map read) . tail . words) <$> replicateM n getLine\n putStrLn $ solve ls\n\nsolve [] = \"NO\"\nsolve ([b, a]:ls) = if 2400 <= b && b < a\n then \"YES\" \n else solve ls"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n \nmain = do \n n <- readLn\n [ns, bs, as] <- transpose . map words <$> replicateM n getLine\n putStrLn $ solve ns (map read bs) (map read as)\n\nsolve :: [String] -> [Int] -> [Int] -> String\nsolve [] [] [] = \"NO\"\nsolve (n:ns) (b:bs) (a:as) = if 2400 <= b && b < a then \"YES\" else solve ns bs as"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\n-- import Data.Array.Unboxed\n-- import Data.Array.IArray\n-- import Data.Array.ST\n-- import Data.Array.MArray\n-- import Data.Array.Unsafe\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntSet (IntSet)\n-- import qualified Data.IntSet as S\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as M\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n-- import Debug.Trace\n\nmain = do\n n <- readInt1 <$> BS.getLine\n ns <- map (readStrIntInt . toTriple . BS.words) <$> replicateM n BS.getLine\n putStrLn $ solve ns\n\nreadStrIntInt :: (BS.ByteString, BS.ByteString, BS.ByteString) -> (BS.ByteString, Int, Int)\nreadStrIntInt = applyTriple id (fst . fromJust . BS.readInt) (fst . fromJust . BS.readInt)\n\nsolve :: [(BS.ByteString,Int,Int)] -> String\nsolve ns = if any p ns then \"YES\" else \"NO\" where\n p = \\(_,before,after) -> before>=2400 && before Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\nreadInt641 :: BS.ByteString -> Int64\nreadInt641 = fromIntegral . fst . fromJust . BS.readInteger\n\nreadInt642 :: BS.ByteString -> (Int64,Int64)\nreadInt642 = toTuple . readInt64N\n\nreadInt643 :: BS.ByteString -> (Int64,Int64,Int64)\nreadInt643 = toTriple . readInt64N\n\nreadInt64N :: BS.ByteString -> [Int64]\nreadInt64N = map readInt641 . BS.words\n\nreadInteger1 :: BS.ByteString -> Integer\nreadInteger1 = fst . fromJust . BS.readInteger \n\nreadInteger2 :: BS.ByteString -> (Integer,Integer)\nreadInteger2 = toTuple . readIntegerN\n\nreadInteger3 :: BS.ByteString -> (Integer,Integer,Integer)\nreadInteger3 = toTriple . readIntegerN\n\nreadIntegerN :: BS.ByteString -> [Integer]\nreadIntegerN = map readInteger1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)"}], "negative_code": [{"source_code": "module Main where\n\nmain = do\n w <- getLine\n w0 <- getContents\n let pool = [niceForm x | x <- (lines w0)]\n let r = solution pool\n if elem True r\n then print \"YES\"\n else print \"NO\"\n\nniceForm :: String -> (Int,Int)\nniceForm w = (n0,n1)\n where [n0,n1] = map read (tail $ words w)\n\nsolution :: [(Int,Int)] -> [Bool]\nsolution [] = []\nsolution (x:xs) = (((fst x) >= 2400) && ((snd x) > (fst x))) : solution xs\n"}], "src_uid": "3bff9b69423cf6c8425e347a4beef96b"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\n\ntoPair :: Read a => [String] -> (a, a)\ntoPair [a, b] = (read a, read b)\n\nsolve :: [(Int, Int)] -> Int\nsolve a' = solve' a where\n a = sort a'\n solve' !((k, a):[]) = if a <= 4\n then k + 1\n else solve' $ (k + 1, (a + 3) `div` 4):[]\n solve' !((k, a1):(k2, a2):xs) = if k + 1 == k2 \n then solve' $ (k2, max ((a1 + 3) `div` 4) a2):xs\n else if a1 >= 4\n then solve' $ (k + 1, (a1 + 3) `div` 4):(k2, a2):xs\n else solve' $ (k2, a2):xs\n\nmain = do\n n <- read `fmap` getLine\n a <- sequence $ take n $ repeat $ toPair `fmap` words `fmap` getLine\n print $ solve a\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ls <- replicateM n getInts\n \n let\n f [k, a] = fromIntegral k + v\n where\n v :: Int64 = ceiling $ if a == 1 then 1 else logBase 4 (fromIntegral a :: Double)\n print $ maximum $ map f ls"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO (a, a)\nreads = liftM (pack . map read . words) getLine\n where\n pack [a, b] = (a, b)\n\nsolve :: [(Int, Int)] -> Int\nsolve = maximum . map solve'\n where\n solve' (a, b) = (+) a $ max 1 $ length $ takeWhile (< b) [2^(2*x) | x <- [0..]]\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- replicateM n reads\n print $ solve xs\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tinput <- C.getContents\n\tlet\n\t\t(n:xs) = map (fst.fromJust.C.readInt) $ C.words input\n\t\ttoTuple [] = []\n\t\ttoTuple (a:b:rest) = (a,b) : (toTuple rest)\n\t\tboxes = toTuple xs\n\tprint $ solve $ sortBy (\\(a,b) (c,d) -> a `compare` c) boxes\n\nsolve :: [(Int,Int)] -> Int\nsolve ((a,b):[]) = a + max 1 (div_four b)\n\t\twhere\n\t\t\tdiv_four x\n\t\t\t\t| x == 1 = 0\n\t\t\t\t| otherwise = 1 + div_four (((x-1) `div` 4)+1)\n\nsolve ((a,b):(c,d):rest) = solve ((c, cnt) : rest )\n\t\twhere\n\t\t\t cnt = max d (div_four (c-a) b)\n\t\t\t div_four ti x \n\t\t\t\t\t| x == 1 || ti == 0 = x\n\t\t\t\t\t| otherwise = div_four (ti-1) (((x-1) `div` 4)+1)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.List as L\nimport qualified Data.Set as S\nimport Data.Maybe\nimport Data.Int\nimport Control.Monad\n\n\nreadInt :: B.ByteString -> Int\nreadInt = fromMaybe 0 . fmap fst . B.readInt\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return .readInt\n l <- replicateM n (B.getLine >>= return . map readInt . B.words)\n print $ solve n l\n\nsolve :: Int ->[[Int]] -> Int\nsolve n l = binarySearch judge 0 maxBound\n where\n judge :: Int -> Bool\n judge n = and $ fmap (contain n) l\n contain :: Int -> [Int] -> Bool\n contain n [k,a]\n | k >= n = False\n | otherwise = contain1 n k a\n contain1 n k a \n | k > n = False \n | a > 4 && a `mod` 4 == 0 = contain1 n (k+1) (a `div` 4)\n | a > 4 = contain1 n (k+1) (a `div` 4 + 1)\n | otherwise = k < n || a == 1\n\nbinarySearch :: (Int -> Bool) -> Int -> Int -> Int\nbinarySearch judge = sub\n where\n sub a b\n |b == a+1 = b\n |judge m = sub a m\n |otherwise = sub m b\n where\n m = (a+b) `div` 2\n"}, {"source_code": "module Main (main) where\n\nimport Control.Monad (liftM, replicateM)\n\ndata Box = Box { side :: Int\n , number :: Int }\n deriving (Show)\n\nreadBox :: String -> Box\nreadBox line = Box { side = s, number = n }\n where (s:n:_) = map read $ words line\n\ngetMinSide :: Box -> Int\ngetMinSide (Box s n) = if n == 1\n then (s + 1)\n else getMinSide' s n\n where getMinSide' s n\n | n == 1 = s\n | otherwise = getMinSide' (s + 1) (div (n + 3) 4)\n\nmain = do\n n <- liftM read getLine\n boxes <- replicateM n $ liftM readBox getLine\n let answer = maximum $ map getMinSide boxes\n print answer\n"}], "negative_code": [{"source_code": "module Main (main) where\n\nimport Control.Monad (liftM, replicateM)\n\ndata Box = Box { side :: Int\n , number :: Int }\n deriving (Show)\n\nreadBox :: String -> Box\nreadBox line = Box { side = s, number = n }\n where (s:n:_) = map read $ words line\n\ngetMinSide :: Box -> Int\ngetMinSide (Box s n) = getMinSide' s n\n where getMinSide' s n | n == 1 = s\n | otherwise = getMinSide' (s + 1) (div (n + 3) 4)\n\nmain = do\n n <- liftM read getLine\n boxes <- replicateM n $ liftM readBox getLine\n let answer = maximum $ map getMinSide boxes\n print answer\n"}, {"source_code": "module Main (main) where\n\nimport Control.Monad (liftM, replicateM)\n\ndata Box = Box { side :: Int\n , number :: Int }\n deriving (Show)\n\nreadBox :: String -> Box\nreadBox line = Box { side = s, number = n }\n where (s:n:_) = map read $ words line\n\ngetMinSide :: Box -> Int\ngetMinSide (Box s n) = if n == 1\n then s\n else getMinSide' s n\n where getMinSide' s n\n | n == 1 = s\n | otherwise = getMinSide' (s + 1) (div (n + 3) 4)\n\nmain = do\n n <- liftM read getLine\n boxes <- replicateM n $ liftM readBox getLine\n let answer = maximum $ map getMinSide boxes\n print answer\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ls <- replicateM n getInts\n\n print $ maximum $ map (\\[k, a] -> k + ceiling (if a == 0 then 1 else logBase 4 (fromIntegral a))) ls\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ls <- replicateM n getInts\n\n print $ maximum $ map (\\[k, a] -> k + ceiling (if a == 1 then 1 else logBase 4 (fromIntegral a))) ls\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ls <- replicateM n getInts\n \n let\n f [k, a] = fromIntegral k + v\n where\n v :: Int32 = ceiling $ if a == 1 then 1 else logBase 4 (fromIntegral a :: Float)\n print $ maximum $ map f ls"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ls <- replicateM n getInts\n\n print $ maximum $ map (\\[k, a] -> k + ceiling (logBase 4 (fromIntegral a))) ls\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tinput <- C.getContents\n\tlet\n\t\t(n:xs) = map (fst.fromJust.C.readInt) $ C.words input\n\t\ttoTuple [] = []\n\t\ttoTuple (a:b:rest) = (a,b) : (toTuple rest)\n\t\tboxes = toTuple xs\n\tprint $ solve $ sortBy (\\(a,b) (c,d) -> a `compare` c) boxes\n\nsolve :: [(Int,Int)] -> Int\nsolve ((a,b):[]) = a + (div_four b)\n\t\twhere\n\t\t\tdiv_four x\n\t\t\t\t| x == 1 = 0\n\t\t\t\t| otherwise = 1 + div_four (((x-1) `div` 4)+1)\n\nsolve ((a,b):(c,d):rest) = solve ((c, cnt) : rest )\n\t\twhere\n\t\t\t cnt = max d (div_four (c-a) b)\n\t\t\t div_four ti x \n\t\t\t\t\t| x == 1 || ti == 0 = x\n\t\t\t\t\t| otherwise = div_four (ti-1) (((x-1) `div` 4)+1)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.List as L\nimport qualified Data.Set as S\nimport Data.Maybe\nimport Data.Int\nimport Control.Monad\n\n\nreadInt :: B.ByteString -> Int\nreadInt = fromMaybe 0 . fmap fst . B.readInt\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return .readInt\n l <- replicateM n (B.getLine >>= return . map readInt . B.words)\n print $ solve n l\n\nsolve :: Int ->[[Int]] -> Int\nsolve n l = \n if n == 1 && l == [[0,0]] then \n 0 \n else\n binarySearch judge 0 maxBound\n where\n judge :: Int -> Bool\n judge n = and $ fmap (contain n) l\n contain :: Int -> [Int] -> Bool\n contain n [k,a] \n | k > n = False\n | a > 4 && a `mod` 4 == 0 = contain n [k+1,a `div` 4]\n | a > 4 = contain n [k+1,a `div` 4 + 1]\n | otherwise = k < n || a == 1\n\nbinarySearch :: (Int -> Bool) -> Int -> Int -> Int\nbinarySearch judge = sub\n where\n sub a b\n |b == a+1 = b\n |judge m = sub a m\n |otherwise = sub m b\n where\n m = (a+b) `div` 2\n"}, {"source_code": "import Data.List\n\ntoPair :: Read a => [String] -> (a, a)\ntoPair [a, b] = (read a, read b)\n\nsolve :: [(Int, Int)] -> Int\nsolve a' = solve' a where\n a = sort a'\n solve' ((k, a):[]) = if a == 1 \n then k\n else solve' $ (k + 1, (a + 3) `div` 4):[]\n solve' ((k, a1):(k2, a2):xs) = if k + 1 == k2 \n then solve' $ (k2, max ((a1 + 3) `div` 4) a2):xs\n else if a1 >= 4\n then solve' $ (k + 1, (a1 + 3) `div` 4):(k2, a2):xs\n else solve' $ (k2, a2):xs\n\nmain = do\n n <- read `fmap` getLine\n a <- sequence $ take n $ repeat $ toPair `fmap` words `fmap` getLine\n print $ solve a\n"}, {"source_code": "import Data.List\n\ntoPair :: Read a => [String] -> (a, a)\ntoPair [a, b] = (read a, read b)\n\nsolve :: [(Int, Int)] -> Int\nsolve a' = solve' a where\n a = sort a'\n solve' ((k, a):[]) = if a == 1 \n then k\n else solve' $ (k + 1, (a + 3) `div` 4):[]\n solve' ((k, a1):(k2, a2):xs) = if k + 1 == k2 \n then solve' $ (k2, max ((a1 + 3) `div` 4) a2):xs\n else solve' $ (k + 1, (a1 + 3) `div` 4):(k2, a2):xs\n\nmain = do\n n <- read `fmap` getLine\n a <- sequence $ take n $ repeat $ toPair `fmap` words `fmap` getLine\n print $ solve a\n"}], "src_uid": "15aac7420160f156d5b73059af1fae3b"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.Array\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, d] = map (fst . fromJust . C.readInt) . C.words $ head input\n\tlet as = map (fst . fromJust . C.readInt) . C.words $ head $ tail input\n\tlet ass = array (0, n-1) [ (i, as !! i) | i <- [0..n-1] ]\n\tprint $ 2 * (length $ filter (\\(x,y) -> abs (x-y) <= d) [ (ass ! i, ass ! j) | i <- [0..n-1], j <- [i+1..n-1] ])\n", "positive_code": [{"source_code": "getA :: IO [Int]\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[n, d] <- getA\n\ta <- getA\n\tputStr $ show $ sum [1 | i <- a, j <- a, abs(i-j) <= d] - n\n"}, {"source_code": "\npairnum heights diff = sum (map length (pairs heights []))\n where pairs [] _ = []\n pairs (x:t) h = (filter (\\n -> (abs (x - n)) <= diff) (t ++ h)) : (pairs t (x:h))\n\nmain :: IO ()\nmain = do\n [_, max_diff] <- fmap (map read . words) getLine\n heights <- fmap (map read . words) getLine\n print (pairnum heights max_diff)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, d] <- getInts\n xs <- getInts\n\n print $ length [(x, y) | x <- xs, y <- xs, abs (x-y) <= d] - n\n"}, {"source_code": "\nimport Array\nimport Monad (liftM)\n\nsolve :: Int -> Array Int Int -> Int\nsolve d array = 2 * length [(i,j) | i <- [1..n], j <- [i+1..n], abs (array ! i - array ! j) <= d]\n where\n n = snd $ bounds array\n\nmain :: IO ()\nmain = do\n [n, d] <- liftM (map read . words) getLine\n xs <- liftM (map read . words) getLine\n print $ solve d $ listArray (1,n) xs\n"}, {"source_code": "import Data.List\n\nf::Integer->[(Integer,Integer)]->[(Integer,Integer)]->Integer\nf _ _ []=0\nf d xs2@((p1,x):xs) ys2@((p2,y):ys)\n |y-x<=d=(p2-p1)*2 + f d xs2 ys\n |otherwise=f d xs ys2\n\nmain =do\n e<-getLine\n es<-getLine\n let (n:d:[])=map read (words e)::[Integer]\n xs=map read (words es)::[Integer]\n ys=zip [1..n] (sort xs)\n print $ f d ys ys"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nmain = do\n [n, d] <- fmap (map read . words) getLine\n a <- fmap (map read . words) getLine\n let k = length([1 | i <- a, j <- a, abs(i - j) <= d]) - n\n in print k"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nmain = do\n [n, d] <- fmap (map read . words) getLine\n a <- fmap (map read . words) getLine\n let k = [1 | i <- a, j <- a, abs(i - j) <= d]\n count = length(k) - length(a)\n in print count"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact func\n\nfunc = q1.lines\n\nq1::[String]->String\nq1 (a:b:xs) = (solve ((toInt.head.tail.words) a) ((map toInt.words) b)) \n ++ \"\\n\" ++ (q1 xs)\nq1 [] = \"\"\n\ntoInt::String->Int\ntoInt = read\n--toInt = foldl step 0\n-- where step a b = a*10+(digitToInt b)\n\nsolve::Int->[Int]->String\nsolve a b = show (left a b)\n\nleft::Int->[Int]->Int\nleft a (b:xs) = (right a b xs)*2 + (left a xs)\nleft _ [] = 0\n\nright a b (c:xs) | (abs (b-c)) <= a = 1 + (right a b xs)\n | otherwise = right a b xs\nright _ _ [] = 0"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : d : _ <- readData\n xs <- take n <$> readData\n let answer = sum $ do\n (i, x) <- zip [1 .. ] xs\n (j, y) <- zip [1 .. ] xs\n guard $ i /= j\n guard $ abs (x - y) <= d\n return (1 :: Int)\n printf \"%d\\n\" $ answer\n\n\n\n"}, {"source_code": "main = interact (ans)\ndif x = read(last (words (head (lines x))))::Int\nhei x = zip (map (read::String -> Int) (words (last(lines x)))) [1..]\npair x = [(y,z)|y<-hei x,z<-hei x,y/=z,fst y-fst z<= dif x,fst z-fst y<= dif x]\nans x = show(length(pair x))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess m k x = (+ (-1)) $ length $ filter (<=x+m) $ filter (>=x-m) k\n\nmain = do\n\t\t[n,m]<- map read <$> words <$> getLine ::IO [Int]\n\t\tk<-sort <$> map read <$> words <$>getLine ::IO [Int]\n\t\tprint $ sum $ map (process m k) k\n\n"}, {"source_code": "module Main (\n main\n) where\n\n\nparse :: String -> (Int, Int, [Int])\nparse str = (n, d, hs)\n where lns = lines str\n [n,d] = map read $ words $ head lns\n hs = map read $ words $ lns !! 1\n\nsolve :: (Int, Int, [Int]) -> Int\nsolve (n, d, hs) = length [(i,j) | i <- hs, j <- hs, abs (i - j) <= d ] - n\n\noutput :: Int -> String\noutput n = show n\n\nmain = interact $ output . solve . parse\n\n"}, {"source_code": "process :: Integral a => a -> [a] -> a\nprocess d xs = sum [if abs(i-j) <= d then 1 else 0 | i <- xs, j <- xs] - fromIntegral(length xs)\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,d] <- fmap (map readInt.words) getLine\n xs <- fmap (map readInt.words) getLine\n print $ process d xs"}], "negative_code": [{"source_code": "\npairnum heights diff = sum (map length (pairs [] heights diff))\n where pairs [] _ _ = []\n pairs (x:t) h d = (filter (\\n -> abs (x - n) <= d) (t ++ h)) : (pairs t (x:h) d)\n\nmain :: IO ()\nmain = do\n [_, max_diff] <- fmap (map read . words) getLine\n heights <- fmap (map read . words) getLine\n print (pairnum heights max_diff)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\t\t[n,m]<- map read <$> words <$> getLine ::IO [Int]\n\t\tk<-sort <$> map read <$> words <$>getLine ::IO [Int]\n\t\tlet z= length $ filter (<=m) $ zipWith (subtract) k (tail k)\n\t\tprint $ z+z\n\n"}], "src_uid": "d7381f73ee29c9b89671f21cafee12e7"} {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii) where ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.Bits (testBit)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.List (foldl', sortBy)\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = mu\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u'')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (u, w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n skips u i = (ps ! ii, ms ! ii) where ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<*>), (<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\n-- import Data.Array (Array, accumArray, listArray, (!))\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (elems, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray, STUArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport Data.Function (on)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\n\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n, _] <- readInts `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . readInts) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = foldl1' (+) $ map (\\(Edge _ _ w) -> fromIntegral w :: Int64) mst\n\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0) :: ST s (STArray s Int (Int, Int))\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n\n depths = runSTUArray $ do\n a <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n let dfs p d u = do\n writeArray a u d\n mapM_ (dfs u (d+1)) $ filter (/= p) $ map fst $ adjacents ! u\n dfs 0 0 1\n return a\n\n parents' = runSTArray $ do\n a <- newArray ((0, 0), (n, k)) (0, 0)\n\n forM_ [0..k] $ \\i -> writeArray a (0, i) (0, 0)\n forM_ [1..n] $ \\v -> writeArray a (v, 0) (parents ! v)\n\n forM_ [1..k] $ \\i ->\n forM_ [1..n] $ \\v -> do\n (v', w) <- readArray a (v, i-1)\n (!v'', w') <- readArray a (v', i-1)\n let !ww = max w w'\n writeArray a (v, i) (v'', ww)\n\n return a\n\n\n calc (Edge u v w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n ix = reverse [0..k]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n (u', w') = foldl' step (u, 0) ix\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = if depths ! u - dv >= 2^i then (v, max w w') else a\n where\n (v, w') = parents' ! (u, i)\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u', max w (max w1 w2))\n else a\n where\n (v', w1) = parents' ! (v, i)\n (u', w2) = parents' ! (u, i)\n\n (_, w3) = parents ! v'\n (_, w4) = parents ! u''\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.Bits (testBit)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.List (foldl', sortBy)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Prelude hiding (getLine,getContents, words, lines)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nnewSets n = do\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n return (ps, rs)\n\nfindSet s@(ps, _) u = do \n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet s p\n writeArray ps u v\n return v\n\nunionSets s@(ps, rs) a b = do\n pa <- findSet s a\n pb <- findSet s b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n s@(ps, rs) <- newSets n\n\n let\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet s u\n pv <- findSet s v\n\n if pu /= pv\n then do\n unionSets s pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (comparing edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = mu\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u'')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (elems, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray, STUArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: Int, vertexParent :: Int, vertexWeight :: Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = foldl1' (+) $ map (\\(Edge _ _ w) -> fromIntegral w :: Int64) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (u, w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n skips u i = (ps ! ii, ms ! ii) where ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sortBy, foldl1')\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii) where ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl', sortBy)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = mu\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u'')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (elems, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray, STUArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: Int, vertexParent :: Int, vertexWeight :: Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (u, w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n skips u i = (ps ! ii, ms ! ii) where ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (elems, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray, freeze)\nimport Data.Array.ST.Safe (STArray,runSTArray, STUArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport Data.Function (on)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Node = Node { nodeParent :: !Int, nodeMin :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\n{-# INLINE readInt' #-}\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = foldl1' (+) $ map (\\(Edge _ _ w) -> fromIntegral w :: Int64) mst\n\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0) :: ST s (STArray s Int (Int, Int))\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n\n depths = runSTUArray $ do\n a <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n let dfs p d u = do\n writeArray a u d\n mapM_ (dfs u (d+1)) $ filter (/= p) $ map fst $ adjacents ! u\n dfs 0 0 1\n return a\n\n r :: (UArray (Int, Int) Int, UArray (Int, Int) Int)\n r@(jps, jms) = runST $ do\n ps <- newArray ((0, 0), (n, k)) 0 :: ST s (STUArray s (Int, Int) Int)\n ms <- newArray ((0, 0), (n, k)) 0 :: ST s (STUArray s (Int, Int) Int)\n\n forM_ [0..k] $ \\i -> do\n writeArray ps (0, i) 0\n writeArray ms (0, i) 0\n\n forM_ [1..n] $ \\v -> do\n let (p, w) = parents ! v\n writeArray ps (v, 0) p\n writeArray ms (v, 0) w\n\n forM_ [1..k] $ \\i ->\n forM_ [1..n] $ \\v -> do\n v' <- readArray ps (v, i-1)\n v'' <- readArray ps (v', i-1)\n w <- readArray ms (v, i-1)\n w' <- readArray ms (v', i-1)\n writeArray ps (v, i) v''\n writeArray ms (v, i) $ max w w'\n\n ps' <- freeze ps\n ms' <- freeze ms\n return (ps', ms')\n\n calc (Edge u v w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n ix = reverse [0..k]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = (v, max w w') where\n v = jps ! (u, i)\n w' = jms ! (u, i)\n\n bits v = filter (testBit v) $ ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u', max w (max w1 w2))\n else a\n where\n v' = jps ! (v, i)\n w1 = jms ! (v, i)\n u' = jps ! (u, i)\n w2 = jms ! (u, i)\n\n (_, w3) = parents ! v'\n (_, w4) = parents ! u''\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.Bits (testBit)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.List (foldl', sortBy)\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport System.Random\nimport Prelude hiding (getLine,getContents, words, lines)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n gen <- getStdGen\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n gr <- newSTRef gen\n\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n g <- readSTRef gr\n let (b, g') = random g\n writeSTRef gr g'\n\n if b\n then writeArray ps pa pb\n else writeArray ps pb pa\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = mu\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u'')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<*>), (<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\n-- import Data.Array (Array, accumArray, listArray, (!))\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (elems, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray, STUArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport Data.Function (on)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\n\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n, _] <- readInts `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . readInts) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = foldl1' (+) $ map (\\(Edge _ _ w) -> fromIntegral w :: Int64) mst\n\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0) :: ST s (STArray s Int (Int, Int))\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n\n depths = runSTUArray $ do\n a <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n let dfs p d u = do\n writeArray a u d\n mapM_ (dfs u (d+1)) $ filter (/= p) $ map fst $ adjacents ! u\n dfs 0 0 1\n return a\n\n parents' = runSTArray $ do\n a <- newArray ((0, 0), (n, k)) (0, 0)\n\n forM_ [0..k] $ \\i -> writeArray a (0, i) (0, 0)\n forM_ [1..n] $ \\v -> writeArray a (v, 0) (parents ! v)\n\n forM_ [1..k] $ \\i ->\n forM_ [1..n] $ \\v -> do\n (v', w) <- readArray a (v, i-1)\n (!v'', w') <- readArray a (v', i-1)\n let !ww = max w w'\n writeArray a (v, i) (v'', ww)\n\n return a\n\n\n calc (Edge u v w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n ix = reverse [0..k]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n (u', w') = foldl' step (u, 0) ix\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = if depths ! u - dv >= 2^i then (v, max w w') else a\n where\n (v, w') = parents' ! (u, i)\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u', max w (max w1 w2))\n else a\n where\n (v', w1) = parents' ! (v, i)\n (u', w2) = parents' ! (u, i)\n\n (_, w3) = parents ! v'\n (_, w4) = parents ! u''\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl', sortBy)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.Bits (testBit)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.List (foldl', sortBy)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Prelude hiding (getLine,getContents, words, lines)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\n{- NOTE Vector of (Int, Int) could be prettier -}\ndata Sets s = Sets (STUArray s Int Int) (STUArray s Int Int)\n\nnewSets n = do\n ps <- newListArray (1, n) [1..n]\n rs <- newArray (1, n) 0\n return $ Sets ps rs\n\n{- NOTE it's too generic, so haskell cannot optimize it -}\nfindSet :: Sets s -> Int -> ST s Int\nfindSet s@(Sets ps _) = f\n where\n f u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- f p\n writeArray ps u v\n return v\n\nunionSets s@(Sets ps rs) a b = do\n pa <- findSet s a\n pb <- findSet s b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n s <- newSets n\n\n let\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet s u\n pv <- findSet s v\n\n if pu /= pv\n then do\n unionSets s pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (comparing edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = mu\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u'')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<*>), (<$>))\nimport Control.Monad (mapM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array, accumArray, listArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (sortBy)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n, _] <- readInts `fmap` getLine\n es' <- (map ((\\[u, v, w] -> (u, v, w)) . readInts) . lines) `fmap` getContents\n\n gen <- newStdGen\n\n let\n es = sortBy (comparing (\\(_, _, w) -> w)) es'\n\n (l, treeEdges) = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STArray s Int Int)\n genr <- newSTRef gen\n\n let\n get u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n pp <- get p\n writeArray ps u pp\n return pp\n\n unite u v = do\n pu <- get u\n pv <- get v\n\n g <- readSTRef genr\n let (r, g') = random g\n writeSTRef genr g'\n \n if pu /= pv\n then if r\n then writeArray ps pu pv\n else writeArray ps pv pu\n else return ()\n\n mst' [] = return (0, [])\n mst' (e@(u, v, w):es) = do\n pu <- get u\n pv <- get v\n\n if pu /= pv\n then do\n unite pu pv\n (l, treeEdges) <- mst' es\n return (l + (fromIntegral w :: Int64), e:treeEdges)\n else mst' es\n\n mst' es\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0)\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ treeEdges ++ map swap treeEdges\n where\n swap (u, v, w) = (v, u, w)\n shift (u, v, w) = (u, (v, w))\n\n calc (u, v, w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max pw w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n ix :: [Int]\n ix = reverse [0..k]\n\n (u', w') = foldl step (u, 0) ix\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = if depths ! u - dv >= 2^i then (v, max w w') else a\n where\n (v, w') = parents' ! (u, i)\n\n (v', _, w'') = foldl step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u', max w (max w1 w2))\n else a\n where\n (v', w1) = parents' ! (v, i)\n (u', w2) = parents' ! (u, i)\n\n (p, pw) = parents ! v'\n \n depths = listArray (1, n) $ map f [1..n]\n where\n f 1 = 0\n f u = depths ! (fst $ parents ! u) + 1\n\n parents' = listArray (head bs, last bs) $ map f bs :: Array (Int, Int) (Int, Int)\n where\n bs = (,) <$> [0..n] <*> [0..k]\n\n f :: (Int, Int) -> (Int, Int)\n f (0, i) = (0, 0)\n f (v, 0) = parents ! v\n f (v, i) = (v'', max w w')\n where\n (v', w) = parents' ! (v, i-1)\n (v'', w') = parents' ! (v', i-1)\n\n putStr . unlines . map show $ map calc es'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<*>), (<$>))\nimport Control.Monad (mapM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array, accumArray, listArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (sortBy)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n, _] <- readInts `fmap` getLine\n es' <- (map ((\\[u, v, w] -> (u, v, w)) . readInts) . lines) `fmap` getContents\n\n gen <- newStdGen\n\n let\n es = sortBy (comparing (\\(_, _, w) -> w)) es'\n\n (l, treeEdges) = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STArray s Int Int)\n genr <- newSTRef gen\n\n let\n get u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n pp <- get p\n writeArray ps u pp\n return pp\n\n unite u v = do\n pu <- get u\n pv <- get v\n\n g <- readSTRef genr\n let (r, g') = random g\n writeSTRef genr g'\n \n if pu /= pv\n then if r\n then writeArray ps pu pv\n else writeArray ps pv pu\n else return ()\n\n mst' [] = return (0, [])\n mst' (e@(u, v, w):es) = do\n pu <- get u\n pv <- get v\n\n if pu /= pv\n then do\n unite pu pv\n (l, treeEdges) <- mst' es\n return (l + w, e:treeEdges)\n else mst' es\n\n mst' es\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0)\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ treeEdges ++ map swap treeEdges\n where\n swap (u, v, w) = (v, u, w)\n shift (u, v, w) = (u, (v, w))\n\n calc (u, v, w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + w - (heaviest u v)\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n ix :: [Int]\n ix = reverse [0..k]\n\n (u', w') = foldl step (u, 0) ix\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = if depths ! u - dv >= 2^i then (v, max w w') else a\n where\n (v, w') = parents' ! (u, i)\n\n (v', _, w'') = foldl step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u, max w (max w1 w2))\n else a\n where\n (v', w1) = parents' ! (v, i)\n (u', w2) = parents' ! (u, i)\n \n depths = listArray (1, n) $ map f [1..n]\n where\n f 1 = 0\n f u = depths ! (fst $ parents ! u) + 1\n\n parents' = listArray (head bs, last bs) $ map f bs :: Array (Int, Int) (Int, Int)\n where\n bs = (,) <$> [0..n] <*> [0..k]\n\n f :: (Int, Int) -> (Int, Int)\n f (0, i) = (0, 0)\n f (v, 0) = parents ! v\n f (v, i) = (v'', max w w')\n where\n (v', w) = parents' ! (v, i-1)\n (v'', w') = parents' ! (v', i-1)\n\n putStr . unlines . map show $ map calc es'\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl', sortBy)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u'')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (elems, listArray, accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray, STUArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64, Int16)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sort, foldl1')\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: Int, vertexParent :: Int, vertexWeight :: Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\n\ninstance Eq Edge where\n (==) = (==) `on` edgeW\ninstance Ord Edge where\n compare = compare `on` edgeW\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sort es\n\n l = sum $ map edgeW mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (u, w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [(Int, Int)]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, (v, w))\n\n skips u i = (ps ! ii, ms ! ii) where ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w) = l + (fromIntegral w) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', w') = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, w) i = (v, max w w') where (v, w') = skips u i\n bits v = filter (testBit v) ix\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u' then (v', u', max w (max w1 w2)) else a\n where\n (v', w1) = skips v i\n (u', w2) = skips u i\n\n w3 = vertexWeight (vs ! v')\n w4 = vertexWeight (vs ! u'')\n \n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n\nimport Control.Applicative ((<*>), (<$>))\nimport Control.Monad (mapM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array, accumArray, listArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (foldl', sortBy)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n, _] <- readInts `fmap` getLine\n es' <- (map ((\\[u, v, w] -> (u, v, w)) . readInts) . lines) `fmap` getContents\n\n gen <- newStdGen\n\n let\n es = sortBy (comparing (\\(_, _, w) -> w)) es'\n\n treeEdges = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STArray s Int Int)\n genr <- newSTRef gen\n\n let\n get u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n pp <- get p\n writeArray ps u pp\n return pp\n\n unite u v = do\n pu <- get u\n pv <- get v\n\n g <- readSTRef genr\n let (r, g') = random g\n writeSTRef genr g'\n \n if pu /= pv\n then if r\n then writeArray ps pu pv\n else writeArray ps pv pu\n else return ()\n\n mst' [] = return []\n mst' (e@(u, v, w):es) = do\n pu <- get u\n pv <- get v\n\n if pu /= pv\n then do\n unite pu pv\n treeEdges <- mst' es\n return $ e:treeEdges\n else mst' es\n\n mst' es\n\n l = fromIntegral (sum $ map (\\(_, _, w) -> w) treeEdges) :: Int64\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0)\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ treeEdges ++ map swap treeEdges\n where\n swap (u, v, w) = (v, u, w)\n shift (u, v, w) = (u, (v, w))\n\n calc (u, v, w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = max (max w3 w4) w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n ix :: [Int]\n ix = reverse [0..k]\n\n (u', w') = foldl' step (u, 0) ix\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = if depths ! u - dv >= 2^i then (v, max w w') else a\n where\n (v, w') = parents' ! (u, i)\n\n (v', u'', w'') = foldl' step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u', max w (max w1 w2))\n else a\n where\n (v', w1) = parents' ! (v, i)\n (u', w2) = parents' ! (u, i)\n\n (_, w3) = parents ! v'\n (_, w4) = parents ! u''\n \n depths = listArray (1, n) $ map f [1..n]\n where\n f 1 = 0\n f u = depths ! (fst $ parents ! u) + 1\n\n parents' = listArray (head bs, last bs) $ map f bs :: Array (Int, Int) (Int, Int)\n where\n bs = (,) <$> [0..n] <*> [0..k]\n\n f :: (Int, Int) -> (Int, Int)\n f (0, i) = (0, 0)\n f (v, 0) = parents ! v\n f (v, i) = (v'', max w w')\n where\n (v', w) = parents' ! (v, i-1)\n (v'', w') = parents' ! (v', i-1)\n\n putStr . unlines . map show $ map calc es'\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl', sortBy)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = mu\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<*>), (<$>))\nimport Control.Monad (mapM_)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array, accumArray, listArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray,runSTArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Data.List (sortBy)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\nimport System.Random (newStdGen, random)\nimport Prelude hiding (getLine,getContents, words, lines)\n\nreadInts = map (fst . fromJust . readInt) . words\n\nmain = do\n [n, _] <- readInts `fmap` getLine\n es' <- (map ((\\[u, v, w] -> (u, v, w)) . readInts) . lines) `fmap` getContents\n\n gen <- newStdGen\n\n let\n es = sortBy (comparing (\\(_, _, w) -> w)) es'\n\n (l, treeEdges) = runST $ do\n ps <- newListArray (1, n) [1..n] :: ST s (STArray s Int Int)\n genr <- newSTRef gen\n\n let\n get u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n pp <- get p\n writeArray ps u pp\n return pp\n\n unite u v = do\n pu <- get u\n pv <- get v\n\n g <- readSTRef genr\n let (r, g') = random g\n writeSTRef genr g'\n \n if pu /= pv\n then if r\n then writeArray ps pu pv\n else writeArray ps pv pu\n else return ()\n\n mst' [] = return (0, [])\n mst' (e@(u, v, w):es) = do\n pu <- get u\n pv <- get v\n\n if pu /= pv\n then do\n unite pu pv\n (l, treeEdges) <- mst' es\n return (l + (fromIntegral w :: Int64), e:treeEdges)\n else mst' es\n\n mst' es\n\n parents = runSTArray $ do\n a <- newArray (1, n) (0, 0)\n let dfs p (u, w) = do\n writeArray a u (p, w)\n mapM_ (dfs u) . filter ((/= p) . fst) $ adjacents ! u\n dfs 0 (1, 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ treeEdges ++ map swap treeEdges\n where\n swap (u, v, w) = (v, u, w)\n shift (u, v, w) = (u, (v, w))\n\n calc (u, v, w)\n | fst (parents ! u) == v || fst (parents ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | v == u' = w'\n | otherwise = w''\n where\n (dv, du) = (depths ! v, depths ! u)\n\n ix :: [Int]\n ix = reverse [0..k]\n\n (u', w') = foldl step (u, 0) ix\n where\n step :: (Int, Int) -> Int -> (Int, Int)\n step a@(u, w) i = if depths ! u - dv >= 2^i then (v, max w w') else a\n where\n (v, w') = parents' ! (u, i)\n\n (v', _, w'') = foldl step (v, u', w') ix\n where\n step a@(v, u, w) i =\n if v' /= u'\n then (v', u, max w (max w1 w2))\n else a\n where\n (v', w1) = parents' ! (v, i)\n (u', w2) = parents' ! (u, i)\n \n depths = listArray (1, n) $ map f [1..n]\n where\n f 1 = 0\n f u = depths ! (fst $ parents ! u) + 1\n\n parents' = listArray (head bs, last bs) $ map f bs :: Array (Int, Int) (Int, Int)\n where\n bs = (,) <$> [0..n] <*> [0..k]\n\n f :: (Int, Int) -> (Int, Int)\n f (0, i) = (0, 0)\n f (v, 0) = parents ! v\n f (v, i) = (v'', max w w')\n where\n (v', w) = parents' ! (v, i-1)\n (v'', w') = parents' ! (v', i-1)\n\n putStr . unlines . map show $ map calc es'\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (mapM_, forM_, when)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (Array)\nimport Data.Array.IArray (accumArray, (!))\nimport Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.ByteString.Char8 (readInt, getLine, getContents, words, lines)\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl', sortBy)\nimport Data.Function (on)\nimport Prelude hiding (getLine,getContents, words, lines)\nimport Data.Bits (testBit)\n\ndata Vertex = Vertex { vertexDepth :: !Int, vertexParent :: !Int, vertexWeight :: !Int }\ndata Edge = Edge { edgeU :: !Int, edgeV :: !Int, edgeW :: !Int }\ndata EdgeTo = EdgeTo !Int !Int\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, _] <- (map readInt' . words) `fmap` getLine\n es <- (map ((\\[u, v, w] -> Edge u v w) . map readInt' . words) . lines) `fmap` getContents\n\n let\n mst = runST $ do\n {- TODO extract Sets type -}\n ps <- newListArray (1, n) [1..n] :: ST s (STUArray s Int Int)\n rs <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n\n let\n findSet u = do\n p <- readArray ps u\n if p == u\n then return p\n else do\n v <- findSet p\n writeArray ps u v\n return v\n\n unionSets a b = do\n pa <- findSet a\n pb <- findSet b\n\n when (pa /= pb) $ do\n ra <- readArray rs a\n rb <- readArray rs b\n\n let (a', b', ra') = if ra < rb then (b, a, rb) else (a, b, ra)\n\n writeArray ps b' a'\n when (ra == rb) $ writeArray rs a' (ra' + 1)\n\n mst' [] = return []\n mst' (e@(Edge u v w):es) = do\n pu <- findSet u\n pv <- findSet v\n\n if pu /= pv\n then do\n unionSets pu pv\n (e:) <$> mst' es\n else mst' es\n\n mst' es'\n where es' = sortBy (compare `on` edgeW) es\n\n l = sum $ map (fromIntegral . edgeW) mst\n\n vs = runSTArray $ do\n a <- newArray (1, n) (Vertex 0 0 0) :: ST s (STArray s Int Vertex)\n let dfs d p (EdgeTo u w) = do\n writeArray a u (Vertex d p w)\n mapM_ (dfs (d+1) u) . filter (\\(EdgeTo u _) -> u /= p) $ adjacents ! u\n dfs 0 0 (EdgeTo 1 0)\n return a\n where\n adjacents = accumArray (flip (:)) [] (1, n) . map shift $ mst ++ map swap mst :: Array Int [EdgeTo]\n where\n swap (Edge u v w) = Edge v u w\n shift (Edge u v w) = (u, EdgeTo v w)\n\n skips u i = (ps ! ii, ms ! ii)\n where\n ii = (u, i)\n\n ps = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexParent (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n p <- read (v, i-1)\n pp <- read (p, i-1)\n write (v, i) pp\n return a\n\n ms = runSTUArray $ do\n a <- newArray ((0, 0), (n, k)) 0\n let { read = readArray a; write = writeArray a }\n forM_ [0..k] $ \\i -> write (0, i) 0\n forM_ [1..n] $ \\v -> write (v, 0) $ vertexWeight (vs ! v)\n forM_ [1..k] $ \\i -> forM_ [1..n] $ \\v -> do\n let p = ps ! (v, i-1)\n w <- read (v, i-1)\n ww <- read (p, i-1)\n write (v, i) $ max w ww\n return a\n\n calc (Edge u v w)\n | vertexParent (vs ! u) == v || vertexParent (vs ! v) == u = l\n | otherwise = l + (fromIntegral w :: Int64) - (fromIntegral (heaviest u v))\n\n k = last $ takeWhile (\\i -> 2^i <= n) [0..]\n\n heaviest v u\n | dv > du = heaviest u v\n | otherwise = m\n where\n ix = reverse [0..k]\n\n (dv, du) = (vertexDepth (vs ! v), vertexDepth (vs ! u))\n\n (u', mu) = foldl' step (u, 0) $ bits (du - dv)\n where\n step (u, m) i = (v, max m m') where (v, m') = skips u i\n bits v = filter (testBit v) ix\n\n m = max m' $ max (vertexWeight $ vs ! v') (vertexWeight $ vs ! u')\n where\n (v', u'', m') = foldl' step (v, u', mu) ix\n where\n step a@(v, u, m) i =\n if v' /= u' then (v', u', max m (max mv mu)) else a\n where\n (v', mv) = skips v i\n (u', mu) = skips u i\n\n putStr . unlines . map show $ map calc es\n"}], "src_uid": "bab40fe0052e2322116c084008c43366"} {"source_code": "\nimport Char (isSpace)\nimport Control.Monad (liftM)\nimport Data.Array.MArray (readArray, writeArray)\nimport Data.Array.IO (IOUArray, newArray_, newListArray)\n\n--------------------------------------------------------------------------------\n\n(?) :: Bool -> a -> a -> a\n(?) p a b = if p then a else b\n\ngetInt :: IO Int\ngetInt = do\n c <- getChar\n isSpace c ? getInt $ getInt' (fromEnum c - fromEnum '0')\n where\n getInt' a = do\n c <- getChar\n isSpace c ? return a $ getInt' (10*a + fromEnum c - fromEnum '0')\n\nreadArray :: (Int, Int) -> IO (IOUArray (Int, Int) Int)\nreadArray (n, m) = do\n array <- newArray_ ((1,1), (n,m))\n readArray' 1 1 array\n where \n readArray' i j array\n | i > n = return array\n | j > m = readArray' (i+1) 1 array\n | otherwise = do\n x <- getInt\n writeArray array (i,j) x\n readArray' i (j+1) array\n\nf :: Int -> IO (IOUArray Int Int)\nf n = do\n array <- newListArray (1,n) [1..]\n return array\n\nsolve :: Int -> (Int, Int) -> IOUArray (Int, Int) Int -> IO ()\nsolve k (n, m) array = do\n colArray <- f m\n rowArray <- f n\n solve' k colArray rowArray array\n where\n solve' 0 _ _ _ = return ()\n solve' k colArray rowArray array = do\n c <- getChar\n x <- getInt\n y <- getInt\n case c of\n 'g' -> do\n i <- Data.Array.MArray.readArray rowArray x\n j <- Data.Array.MArray.readArray colArray y\n a <- Data.Array.MArray.readArray array (i, j)\n print a \n 'c' -> swap x y colArray\n 'r' -> swap x y rowArray\n solve' (k-1) colArray rowArray array\n swap x1 x2 array = do\n a1 <- Data.Array.MArray.readArray array x1\n a2 <- Data.Array.MArray.readArray array x2\n Data.Array.MArray.writeArray array x1 a2\n Data.Array.MArray.writeArray array x2 a1\n\nmain :: IO ()\nmain = do\n [n, m, k] <- liftM (map read . words) getLine\n arr <- Main.readArray (n, m)\n solve k (n,m) arr\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n \nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Control.Monad\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,m,k] <- map read.words <$> getLine\n table <- map readInt.B.words.B.concat <$> replicateM n B.getLine\n arr <- newListArray (0,n*m-1) table :: IO (IOUArray Int Int)\n toRow <- newListArray (0,n-1) [0..] :: IO (IOUArray Int Int)\n toCol <- newListArray (0,m-1) [0..] :: IO (IOUArray Int Int)\n let swapCol x y = do\n ax <- unsafeRead toCol x\n ay <- unsafeRead toCol y\n unsafeWrite toCol x ay\n unsafeWrite toCol y ax\n swapRow x y = do\n ax <- unsafeRead toRow x\n ay <- unsafeRead toRow y\n unsafeWrite toRow x ay\n unsafeWrite toRow y ax\n query s !x !y= do\n case B.head s of\n 'c' -> swapCol x y\n 'r' -> swapRow x y\n 'g' -> do\n xx <- unsafeRead toRow x\n yy <- unsafeRead toCol y\n unsafeRead arr (xx*m+yy) >>= print\n queries <- B.words <$> B.getContents\n let solve [] = return ()\n solve (s:x:y:rest) = do\n query s (readInt x-1) (readInt y-1)\n solve rest\n solve queries\n"}], "negative_code": [], "src_uid": "290d9779a6be44ce6a2e62989aee0dbd"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n [l, r] = splitOn \"^\" s\n\n ll = sum $ map fromIntegral $ zipWith (\\c i -> if c == '=' then 0 else (ord c - 48) * i) (reverse l) [1..] :: Int64\n rr = sum $ map fromIntegral $ zipWith (\\c i -> if c == '=' then 0 else (ord c - 48) * i) r [1..]\n\n putStrLn $\n case compare ll rr of\n LT -> \"right\"\n EQ -> \"balance\"\n GT -> \"left\"\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Char\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n s <- getLine\n let Just p = findIndex (=='^') s\n let moment :: Integer\n moment = sum $ do\n (ch,i) <- zip s [0..]\n guard (ch /= '=' && ch /= '^')\n let d = digitToInt ch\n return $ fromIntegral $ d * (i-p)\n putStrLn $ if moment == 0 then\n \"balance\"\n else if moment < 0 then \"left\" else \"right\"\n\n"}, {"source_code": "module Main where\nimport Data.Maybe\nimport Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain = do\n let (zero, one)= (0::Integer, 1::Integer)\n int = toInteger . digitToInt\n moment = sum . zipWith (\\y x-> if x /= '=' then int x * y else zero) [one..] \n (a',b') <- (\\z -> let x = fromJust $ findIndex (=='^') z in splitAt x z) <$> getLine \n let [a,b] = map moment [reverse a', tail b']\n putStrLn $ case compare a b of\n LT -> \"right\"\n GT -> \"left\"\n EQ -> \"balance\""}, {"source_code": "module Main where\n--import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain = do\n let (zero, one)= (0::Integer, 1::Integer)\n int = toInteger . digitToInt\n moment = sum . zipWith (\\y x-> if x /= '=' then int x * y else zero) [one..] -- . B.unpack\n (a',b') <- (\\z -> let x = fromJust $ findIndex (=='^') z in splitAt x z) <$> getLine \n -- B.breakSubstring (B.singleton '^') <$> B.getLine -}\n let [a,b] = map moment [reverse a', tail b']\n putStrLn $ case compare a b of\n LT -> \"right\"\n GT -> \"left\"\n EQ -> \"balance\""}, {"source_code": "#!/usr/bin/env runghc\nimport Data.Char\nmain = getContents >>= mapM_ putStrLn . solve . lines\nsolve [] = [] ::[String]\nsolve (c:cs) = (:solve cs)$ if lw==rw then \"balance\" else if lw>rw then \"left\" else \"right\"\n where\n [l,r] = words . map cnv $ c\n [lw,rw] = map (sum . zipWith (*) [1..] . map (toInteger . (flip (-) (ord '0')) . ord)) [reverse l, r]\ncnv '=' = '0'\ncnv '^' = ' '\ncnv c = c\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \t\n\t\t\t\ntr '=' = '0'\ntr x = x\n \n\n\nmain= do\n\ts<- getLine \n\tlet s1 = map (\\z-> fromIntegral (ord z- ord '0')) $ map tr $ reverse $ takeWhile (/='^') s\n\tlet s2 = map (\\z-> fromIntegral (ord z- ord '0')) $ map tr $ tail $ dropWhile (/='^') s\n\tlet r1 = (sum $ zipWith (*) s1 [1..])::Integer\n\tlet r2= (sum $ zipWith (*) s2 [1..])::Integer\n\tputStrLn $ if r1==r2 then \"balance\" else if r1>r2 then \"left\" else \"right\""}, {"source_code": "import Data.List\nimport Data.Char\n\nmain = interact $ getAns . break (=='^')\n\ngetAns :: (String, String) -> String\ngetAns (ls, p:rs) \n\t| lw == rw = \"balance\"\n\t| lw > rw = \"left\"\n\t| otherwise = \"right\"\n\twhere lw = calW $ reverse ls;\n\t\t rw = calW rs;\n\ngetW :: Char -> Int\ngetW x \n\t| isNumber(x) = ord x - ord '0'\n\t| otherwise = 0\n\ncalW :: String -> Integer\ncalW = sum . zipWith (*) [1..] . map (toInteger . getW)\n\n\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Control.Arrow\nimport Data.Int\n\ndebug x = trace (\"# \" ++ show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\ncar = head\ncdr = tail\ncadr = head . tail\n\n--readInt = fst.fromJust.B.readInt\nreadIntList = return . map read . words :: String -> IO [Int]\ntoDigit n = chr (48 + n)\nchr2num c = ord c - ord '0'\n\nmain = do\n ls <- getContents ||> lines\n -- n <- car ls |> readIO :: IO Int\n -- [n,m] <- car ls |> words |> map read |> return :: IO Int\n putStrLn $ solve $ car ls\n\nsolve l =\n let pos = l |> takeWhile (/= '^') |> length in\n\n let m = loop l (-pos) 0 in\n\n if m == 0 then \"balance\"\n else if m > 0 then \"right\" else \"left\"\n\n where\n loop :: String -> Int -> Int64 -> Int64\n loop [] _ ac = ac\n loop (x:xs) idx m =\n if (c < 1 || c > 9)\n then loop xs (idx+1) m\n else loop xs (idx+1) (m + (fromIntegral $ idx * c :: Int64))\n where\n c = chr2num x\n\n-- vim: set ft=haskell:\n"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (foldl')\nmain = do \n\tx <- getLine\n\tputStrLn ( find x )\n\twhere\n \tparseChar c = if c == '=' then 0 else read [c] :: Int64\n\tforce xs = foldl' calc 0 (zip [1..] (map parseChar xs ) )\n\t\twhere \n\t\t\tcalc :: Int64 -> (Int64,Int64) -> Int64\n\t\t\tcalc acc (len,weight) = (weight * len + acc)\n\tfind s | left == right = \"balance\"\n | left > right = \"left\"\n | left < right = \"right\"\n\t\twhere \n\t\t\tnotSep c = c /= '^'\n\t\t\tleft = force ( reverse( takeWhile notSep s ) )\n\t\t\tright = force ( drop 1 ( dropWhile notSep s ) )"}, {"source_code": "import Data.Int (Int64)\nimport Data.List (foldl')\nimport Data.Char (digitToInt)\nmain = do \n\tx <- getLine\n\tputStrLn ( find x )\n\twhere\n \tparseChar c = if c == '=' then 0 else fromIntegral( digitToInt c )\n\tforce xs = foldl' calc 0 (zip [1..] (map parseChar xs ) )\n\t\twhere \n\t\t\tcalc :: Int64 -> (Int64,Int64) -> Int64\n\t\t\tcalc acc (len,weight) = (weight * len + acc)\n\tfind s | left == right = \"balance\"\n | left > right = \"left\"\n | left < right = \"right\"\n\t\twhere \n\t\t\tnotSep c = c /= '^'\n\t\t\tleft = force ( reverse( takeWhile notSep s ) )\n\t\t\tright = force ( drop 1 ( dropWhile notSep s ) )"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n [l, r] = splitOn \"^\" s\n\n ll = sum $ zipWith (\\c i -> if c == '=' then 0 else (ord c - 48) * i) (reverse l) [1..]\n rr = sum $ zipWith (\\c i -> if c == '=' then 0 else (ord c - 48) * i) r [1..]\n\n putStrLn $\n case compare ll rr of\n LT -> \"right\"\n EQ -> \"balance\"\n GT -> \"left\"\n"}, {"source_code": "import Data.Int (Int64)\nmain = do \n\t--x <- getLine\n\tputStrLn ( find x )\n\twhere\n \tx = \"13481553981352133117251=5798527883=6854418718439435913561576999132228=973455228954=8242962814399535728282334=6235198335495=28742=39=775=2=98458986462=7652442714==79352==73=8722942973999492579951572923=515=499444688=7=759675959511=77=25431=74=816835761=2265==43=7948728871295896958275367957812112431962294355422845==3=873917964133627495347=6212329611=4=16=14536768641246271=77249338978926526938=833=45248=45868846847322475332225=8=8466=6=561755861169181=264656945183=918224=424498254=667688593749694299=366=638423883=1=35258758721962198=487149936393368975=24464711622715269=53861123=49264=52=7727=8623421493426587332485623213243=79716646364658796154351621=53237673233563=9=1386=3=124878192=6==4=15249451182=6358=376691=819436=18655964494728=898=78=31522=679=6=45899393722=6272454463278883449141=32749==68265==91697=8287156855=3457767=4=74=8539=41531969673553677427938674621=14==877659443259922==984298949423475755537641=44966=8197653=81191=547326281498261286765=79477144=36611=11=26893894=61=549=861338637=26448173627174593=94179747=97=526426718524779598768952953163319655824844448=645542541774=3837536=5=422955469222487536798685=725973794988697=259717871175844662353195125189=282362447169951711439772512249539162572373358561=74961686372822674879195==2545179611451989716236847=218==85687564139316841444129=2399554669711375=861=417997564232=53885237784129911=66451692=694226464743245861997699298=67294=312457748618916246844972=82532873=632=41=123538359612972455132727828478359=326283133555=675254=53621=2=217==731964755=782753913623711846=16885313==666425658994=59523=87594==95=24=23948294=91=38629=91286965336937446131171186816148244=6586938518=7148183412651==667851=98636672325437831251856===1=5715351811141834=4192172=63365786=4773638874214358788933838576367892839996454913=4=16238332555678=217361427595822952232311874315=7681161986235912=21942876538523924863765125=321=39294171632=936=61771324982271883=555115=3578849863=478=6=4=8554716=677227586695=88225829216=4655385524816723268568692126281=357=89149553242259934==1161515=489685667275=73=1348122283264171297674684673539=252822==38597==3=693475945776=4=17997=9595=1414576818542=516733=3798==6=1751=899818623=434==3=9=638372811652446659=35444454363=856758157=975323914==135381886344884863=425171796=6569553=92=892=443847==75668=85459=5=5945196847144=51164546=338411=36723=6191546891398789785213352386316838951174269386684==998646544647264321493893691==4747486223412=89=8=9712824233667781895=1183952149349317132176=793124=779=998212745498389231571887265161=12989134282=574549161816=6129473531525472989=779=515898==15738233411=726346=74491=81915591169822596428893353624=2352719==7687319=33578=66691273559351576546372=7985772667446122763266=8518=1=4=65181=11868=9355819=9114=1587=9735938=2975=668=299322=337155713541=516418936=33311191644586288955473=15982983227=741488911591=33324=3997=4==6817=16844=81753451=71648241523535391523183455331976439922519==7339115876788374913864888=357716862=19644=8177678598621856719346657=922=821724375=9=88=866296689272==9329717517=442=35858846946493753274117836426978=9514911151617398338894615368857=969359455927824289839624274=148852214=345172187426514=969114722=245633=19168877=4952695748267=61821496634299=5332313=742255=1961728774976=47=37=557372559=68477839296511896559==1137627793148==71427195=8=5=217257764=43=3675==681453656=55862344=538=553567826528923=6783187755==3399=1==2=612=993264532=125584=644893172352=6138762=45597991=736=67895=89693848=33646591=2282775732678134466=1157529975715572335813476433876215393324928757933627=8=816661=41=519992235=2929255669=17=3224=2881991428689537267=418955=11439523=23496141373961711188226344126428259=3359225578881=951594=535217265865223214896368369271176988631=4236262765971=771718752884195559865546949=2167=76846432997152=92361869=3512=5956725364=3183467617=84674=2584152==84432936=397=448863=491912=238376=48578=524=1621176673768798291674357624=793218217==2584115=5427274=97=89261724924=563638489=8489946=63959694344373869255=3946367622395514497297293474379=32788846113226339877186799654217=677181818=85249=8292825674662482264417829581=89=8765916296533755457213585512=98=64=78=843739731858=193=24166=7322777=386952947372=75448489662767=725666224=112===778952191139887857=476864=24===5945677579=2653228212762=9139==9967542961654118==53855759347528345954989483594=712695273167649996=685899214497=61597789951=11699=7299939486729936842696227483898338487=2835114134=51478635619752519877254342839243415444296983827418663977829253=53225493683256=9133==16418614997645969836266355287=1985316=19=47971=676479=95564=8218418368325428674634321927=52685357483491=858367444175252=691=36691737325212635387893758451252132177356=976=46=269831==216664344445743262216272164986738495247757275784923767843564617775637=7788553963376549433=7619771936757849165=7166665816=4684716735515=2634924463314354587183919=17184531354274911662=335=16=98518522=385865171471569=59257364389154551758432282325==565647251824451135356==72161681197466=6175417=841761456112=8339274=8987=63424356865=9=733=74=4==21717=23239=153385273=77826381451365349238453922956368817532492395372=5649599=69=4542947=8=58653912935=13229156816=71533=7625178744132613673672414559418829668=68872=94632613317471195915967=21=73758853716655=678652348968=7943=1479=4675861629=439919922227322117=729118256626213=179=9=4767958435496=126574354339=2=764474447565=26=979946339733483891=685836862=8847567=23=348649426669181758652414456771=26992=326=4=568=2324226966915=653=25728717777812726863448=31==2=5=967217545=9239372=622385277211=2=5654861273==9818563295=2857=669=37=9691596982813367619=3=12948794233==63744686977==67761832769=33922738253=1693=7=1=177666288929=943853644347=7=921658746955=99851814432129=4482998492372618736723=57913732=64=43482=147726214552711=4895436463875845=1=282329323923786396639337==74=47453961847791469659417=96=53413515176184217574=32=94=64727=484====4=8399=376=74418869467484496824=68=87227377553=962=9422652412299197711229832=9121465=378677=8===496355956=2959654158354=779261717=8792457139413=351436==88983=19678424=19712285886673788477391=153151999458434263=5=7=6884368666362=896341482=96987535253258155115822==62=9141483515326799=527368=823743788=2212329=265894==72123385114847145319637578767377=28929268=99199=7389276596767867146891566=27295279=891=723=38=28175796116949=11=89186527==394237117379447393858497==6217=7=69337429=13=8=89832=7261433414977128=3925=11242944695194594736667636=55759735747815582955=131287395134463599386=8371=1=161=6834217=3845349393=942295==212=36=28357799349562814415286923=289163933396654645=57884924=7=16465=774521=182=565==679237119368=5336896961==2252112648676654=17=4=9763294=32685628177262796763479872781=144624=612175236984822514262986=67666278=4314=8416=619=4139=14874123353686=617=33=3228741986=122992222167574728475495=6=512611863913672848=53887=77361591=32==544864839138312316=3513814=69524=5926356=6=58=641286875844=2=372794==677277989144=442544837951282365=1281429997862273=662813267427246217579986=46252758533995=934578961462846112772199248182616=8816=8837811725822585979119536=32=13=45264=848612472786414562=749989436338331138958738993845792928657598254574=1152489542346192454=3324=118=9934965262565588565459=55872169168245369644=52433986698=48354518743555953678525=48=73=557625325983916636=9688534916647117=6763186988817=719429829781335456944326654779381=3449=8521=4=15666261=396=9=9391672155462179178251879261768121=887584371648575678145886461621621613=8=361458933833187=612=39744=93==6825719479857612=6827553=7769674222=264272686653917687=112874573911412913147=249314292315591733=72=2=27678==577798957=685728==84191456872166281558687612341114912671231561197846428517=5474767551=96837368778976813337=94631763=34=6649=8925248772473172=5=6=1498648=198=31224817137895674=999188=5998=473=613599296=4794=2=6=71771=341197728=477=1=64=913=8773777261147477=566=51697645684569247217924=177147978325=9453=34164473689975749349=119474512351595=5754899=57=36945425631918393624=798725988782=351142581=9286481964542212987429=382343825826237761244=957=947986257288244=418199837221==68392558361947256=94936969979646=3=366498999836=2715=79=5638791669==49827727814175532=642566236765436=46=1979764=1357241897592252164686=79844192737=3789768598853374=933139365=56452189428971447=97==8732=937=28235=8=4399697685795276=557=4257823=9=898323218987112394457149926114268846527171=51597563653==1=4244=99=54777192715841588911142911=618171721554368399641==9122731421811295431258496395137432821747865144821263665225389926594=7893383=54179234477796=93118=55758176=96499934631113313313=3868755=6=731=472691971192757=479=8839255=1=623891776471334337533294251=3=574=463948=517282815537558385=99973139=438852315=5=739853261=7948=765737846232682244743461529=941=28496236=7=8193673413=392985944752435=779672539529735=9678838=8721389212=7===132595682946923847188252683139=4681825=2233647=23463==431329548455744==611==235117362473595332756929=11359388=429485975=72211221=961141664817=788=35381=8==924741942323349515779559412432692873386726735389978==648==5=49=4=118789164892455=51=159124541==56799165555873216992774459=7652=6396=11761879=285431324212657762684788257469758153783938==496=5=21899897868=4174555=55116711756448376933576413=2247688461227995682819=3898==477181642868487145966953156379=785392=7=7114=1293682649387=477=34=856364925658799724444855248=397=95=5=429=5951679=686265=2863243583482312116946661338886184926772868735262837=3372671=88369827=5733=85=19=1898877==5878973428625459=4654744435289442375629=443743=565263476756==44=17745461632215476742855726785568517=2218579234644586=1885894674827897436997683446673579489236725316766394793745=74667318=982=4921982=647859938476179639339599151==1=183687354669989828=49394219611471=55783523665456=3641713=36=2227868938174459264414735865572282782=1=5928875=4284878481=97752=97=32748867=1282179337345=44539121484441565691==484=57589764883139=484=88621854=1299==449=58158352=4756=123=372=859=98632486872592=491544=71479=2=759=576=6=46131=641357632468=61625349385245834568934=772722624613372=79873139=571=55229=9867399652234958998=119694418922812^=554811952=23113322534267198371725598155277557712522399=9699125=97255331842=8238371276=9765876=7194646=135=19=4739=765442368=4852835=2738=744182453377946989387=749456=3198235=6318834=21696=12=4637439=1753866=99=9167=574=29=5=948=846972575774289=6772326113=88=1667=12==474=777=84739953=3915535==524187524669=28235279544193=94154713=12936473843975=1993=7917536543289997315497861871=6149349719==9951126948=393=22281175=2634766718288788==8518797114812395477875826237869495=8567==9172989931=456=4547=255635=19683771124=1312877765717949879259412634497=57=5648=3593844455543345949549=193123959217=854=6182346911566372217112168989144226=768=838=31934745=73379948752247363376579258398776963885371759366259759692==83635241993376878689963876=595=7238487=94=7=8=752534824186=13894=7921998423545947647=163941=41339=237685136=82781573==4267=71975=428=223=42377616445666173==733853716242179967=261=235634629527828817414=631895651611957186==778888125267837856982418794=23514153=46=348=42=44634=7=571=59816295737733453366716563754=5322673595422253683222912776249715=3542==3358254859868472=9694341783448915228245567177763765925657569=56235=7832==34822466441594238725351=36=3988=3873=9648572953=5564=6589=418164896238987===749526696796=13113515949929567854=4=948481874=584937=8925655911787347=5441=696947185912361172=2388914223=913837=82=383=214=48==1761819671535418=9597979=62=8875=21=52616=8694251=999974484185415359949=3533531748418=9=15=144391135=582654981173625413529916859=9823=712217257=931=5146=66919319551756139314=4822==1139945376=315786111=8848295463=42868=51748392981=2865542365659777=57959922924478=13166786917747832159697=127=5388167=4=8714=9848272859=6574774185846252891681869=1272616=65=43386997126954962572228431863125513=32916349=8261494642679427==7223397238669=7621622=3642951=84935155112886978461822742=13=8561923425569373668984559=4694=4==83521977225661251769582=3649186775487=65=89497=9691==59915695=127=3461752==3141821632=18182=99782=5483715653448335=23976251528542777=651952719523352=78=7236723154853=7=19843=152495=774891=9=579629757674=29747=61913783661==148446657498938=1414882287=61695989126371=12718669=3813==76923859787=516622691384=5=36=428=979=52=147912445469899=429976836296634149755418427=547348375587499659458253515=157=77138=8574978==95776793119542781=5==1341535154712589887656632193781832169798189416=131882417=36746875137912557862558=721421252736=925==88=851324667115=93=4181775214789=4335843=825=4=4963554598=55237119=5662579298153=398=19488789765=4378=2=6346789789592248=842456838234695657731748789766567662747=957347232847576988959323=9231538=7597444589146488518921796229257172=37257957551721=25==145361387958844215=2864298547281835=4716789293596=43197276777893541316=873==5=337813274=24433=4994287998324923164=9411521895731==85657266==7=7535231982=76231376=637364845964875=1574891573779=79932643=842743391499=56=73976466887229629787972713=58176371542==33156181612792=2==258786613559138623475619344947532894=8=9599576=5638981541=751839721121711696492=68512=55297259134757=2138366513233861634949=226233496996671=548864=255=29668438=9416535313636994=93=85518663321=95=873667723=485=559967=117656=825=6826195325343=2328=72951748821333628673187=8=2=81832=84121616=41249348==37915657671984173192561573941735=675==1539767669912=792848=181645122346=8423144364282=582538345144=29695662775716825798243393=415839258727==157==2147124126513469=424584469791936746=112=8715247=16656=456383==3=442775151877=32981616559631136=7=85===4=95791548128552=525585=54=3295475725166164248472=84463573571=5==8731=34=8=592477426=24259473494=583=4=354533176541194267339522199964669759898454739668439=7296=21287499=7329=72823=524=86=1=71=1726718125633=47747=94721565=9261321246371868=6=633=669=7968677=8765336956=356147==44248=119=429361=2117898971285173198451267577849268163339457314869=95132=13928419837588861587395261=4855684481=2153513526=817=5549191366919666128712=37896964366774398=5674=3=68136917335589849514193569175=578747423563=115232994974=5=199762472335947568319356632=351=7768137155218826=2235=918=871=9315=42=9=9=41169116345184=45332837285361457951993631876791177354352399936==9783221157=2765947488894=899285671728938429637865=97523345991=79999314193264=1271=85519422863385=251577169216942722299754896=5553127=95267827961639=76985322=3122619994=7968186=2333==97184948963==4769=985739129679937513=38525847831819793=956=29848514=2585=137432733541=618758533=3618=92685619529976284463156652=29153328736=64662285945942796=92974927=7537299729197192255=114791=4789335897=48276546858936131583458379=6219386=3951781=5668455=8218=8629=54257142213=2815192993=155=7712===3668297=632=8=87798314237633=7476112783=9644492981=29362286==3874573444355194633742547369817863977631754=3577653656668=95761839863=7924311223178875595=18412122834553442658=22533627==9=9134=3926964=7912545297=7975448186=63248642=45253611=3659959832488925=624298978167499797913312969=4612472=5443342=157599627877255564211=43=14537473568317881==7826692=12185=9=36=67=5=94862338282657=6499613352==12==2672=99655397734114==75343792=8412175=1744522598=2=43772=83261124888397485995=6967679697423272236=458425947283484353=248668192631432=77989384969252937117746765661345225=468=882128425=654434268327253=14251822343784594395==1241293158238=898295485455=95194559=371=4=97249=868316=978944246319818745=8442=86824=87347462485425898=153323576427=3312379665237=81885377279256518664125331563283892499=2151355573568368=7395==147=77161696673785135152=7=5776667731679=2464145549=16==64=1=5837282485878967381564=7488145=1783358159274296716346267794574393876185773192=269322=35292192713=6852278975=46193319275=18459239599277425148=82515297=7776862666==4248991668=55632256=82967348312595=8179691572385249758=35693338218=4188573314616712956729541=9=1==12=185=488654=4967834276=6356549373427335165=82=276=96273443561652=8842344866332==726819842486198199=5=5=2=43952=77614228721794791494=8579==3319381583621463=63554789734=938413216==815575828=9537=63=51992=599835757485857817=58=82762==4623962=917387224317=73=9293318424=99744=481284365678931694=8548=5346652148476=1867=7727=6568972=5461332693451825853573262=219624743487778459979259823=4467712769=641996=915754171313411=2645917=3781673=519916167164338==363594=5=5363732686=66562818431283396899578537646=4171319658616=56977543255126=28441722889996659=825158772567325157831714=26=6538866=267=861112546=7834=98394627224884935276=36=521956794757184=9742216522=285=4479741=9256=599218445=59839234526=187919688=3234643974988232156818685=52365391475253629==2=1=8=29241397237=64518=9597977524=291444=964228991417445631=96616=56862566797648424=53=477513==38831987=37595655533766299=99=23611291569998986345688816687313682=18=439=92=249338=9541369169965811271231951395525=9=414788=472519977528=54595184=5598223817569=74811611523=343797636759=5==964529=46576251727598326577=457=518218514723=1=8979=54751348899769=4261488171=12481847328891778763=1187415395=97681832=35793126=7295915852615848467571224825=48958593279952=78=953162423887=3147=524134613=33174515146=8236294578355788=6=29==4998227135713734495667=3=2254316756578=623599247=2243828697594663516=45=74144549834=521112523499594=81755=532483171348398=5=44=8718143253191159792175617452669382=59126928426763=46331515827=96965973948239=67982855631726219691725833=7963=17726685454=971334=71988749189625614=35675674===264948592738742223=5652177=76498375591526929=453=34949827684788=2319563=177668843316664848667481236378==6559535898645117611549449162639233588268168968=63349261=812897969948924374862942=5=33=289764591=93571841228=9369633915=386356732418=72236332531696499=5568547242==274=386687541=4196165=9892=75123838448643371512889=858222752133939724493451=554154466586466929448218364686573=3223844349998522533525623==49519=3743846517656147495=86984283=42=9858921359921128519=3742=31=125393835573251446797595577663463582384643268=2973=1=84961=19994667777453586374789952358449933353936958=3431==35388475355=4=543175647578==626778412778394612737148=34=227142222167771=26784283178651=21758936775645712558=7=952342387366892336481=8953=55393635277394162862=623==5=648158=1748152156771837489657224=35=626=77197=375518=5992==29=885==7733638=72=6623==3557989=1142884348=24969572776868125358519=9497738=852644329=946=6472=55535158527122=13179792=5498=45455258924==5651719412=5=87388478261692=58342=591187892=2826149=159133235167269755=1=5538745283783352===2465578732965664812227493=14522545559=2743834889552242838=64821=54=9196139==37623=18752834253226491239181993=72752=11774==2868792=235185568254493=7488115333=2792915=53=9==379=72996=478=461428864=3972729438==62577=7135188751=116278=3=21914219849==7822=46916532644473182377=9193444874=8327285=955331246516957627395758568338743253329=248196218443=22351845961513828311864744495788914=51=91=719766221513884863=67=9146=292545=828798974=71==92312898551764196516332192355338724695234747279838=62673994236271758255699=29993838241322262831691874223=822=1689932595984331757873=1831586=479826945617613363854311=87516577217792564378==417833493281427=91853=828449964918666517=96836==79=8314=21376964227592288456615=8438=24=6762942119=144=8299=46==3987915314795546863325849924445889315911715134218267=1=9973=8823347266966167696479=1944393842=74178284761292918619972=34614=3=34412=6458314=1=85=937=967336496=15682=446=36397==65742624626933=8=8269267=858=3=674668=171=423857619=57783697969555444=869684593525121653914683=15987==19=42757564817895111411894415==87792193658=823515392859=2=694893=6479=15891812966946999=17648=79567341757967542786873=148645113=3515255149=4967119633=3=45=18984=38143116928=6=27=81182377234791312=1895829747519356998183882298342772427=598=14295=7216474174942415815=54769767853977366354=574492558226636852898114162991396318374196396255288=295=252344266141423568317979724643821892=93237=524877951==544346581=796819996=642=831376=493813913894=282355796194451518558=9942385515924744=3684668693928296325863632=1==3798=5317682961=82122411211=66927894929285==2=94825374992=53=344==668756=25=5=656231=7187=8=713585866351148=32==38322546352388=79353553214122951917872415783777396637646696=58984=53255=19969575871137\"\n\tsplitOn sep xs = split xs []\n\t\twhere split (x:xs) acc = if x == sep then [acc,xs] else split xs (x:acc)\n\tparseChar c = if c == '=' then 0 else read [c] :: Int64\n\tforce xs = calc 1 (map parseChar xs ) 0\n\t\twhere \n\t\t\tcalc :: Int64 -> [Int64] -> Int64 -> Int64\n\t\t\tcalc i [] acc = acc\n\t\t\tcalc i (x:xs) acc = calc (i+1) xs ((i * x) + acc)\n\tfind s | left == right = \"balance\"\n | left > right = \"left\"\n | left < right = \"right\"\n\t\twhere \n\t\t\tpair = splitOn '^' s\n\t\t\tleft = force ( head pair )\n\t\t\tright = force ( last pair )"}, {"source_code": "main = do \n\tx <- getLine\n\tputStrLn ( find x )\n\twhere\n\tsplitOn sep xs = split xs []\n\t\twhere \n\t\tsplit (x:xs) acc = if x == sep then [acc,xs] else split xs (x:acc)\n\tparseChar c = if c == '=' then 0 else read [c] :: Int\n\tforce xs = calc 1 (map parseChar xs )\n\t\twhere \n\t\t\tcalc _ [] = 0\n\t\t\tcalc i (x:xs) = ( i * x ) + (calc (i+1) xs)\n\tfind s | left == right = \"balance\"\n | left > right = \"left\"\n | left < right = \"right\"\n\t\twhere \n\t\t\tpair = splitOn '^' s\n\t\t\tleft = force ( head pair )\n\t\t\tright = force ( last pair )"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Char\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n s <- getLine\n let Just p = findIndex (=='^') s\n let moment = sum $ do\n (ch,i) <- zip s [0..]\n guard (ch /= '=' && ch /= '^')\n let d = digitToInt ch\n return $ d * (i-p)\n putStrLn $ if moment == 0 then\n \"balance\"\n else if moment < 0 then \"left\" else \"right\"\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Char\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n s <- getLine\n let Just p = findIndex (=='^') s\n let moment = sum $ do\n (ch,i) <- zip s [0..]\n guard (ch /= '=' && ch /= '^')\n let d = digitToInt ch\n return $ d * (i-p)\n putStrLn $ if moment == 0 then\n \"barance\"\n else if moment < 0 then \"left\" else \"right\"\n\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Data.Char\n\nmain = do\n (a',b') <- B.breakSubstring (B.singleton '^') <$> B.getLine\n let [a,b] = map (sum . zipWith (\\y x-> if x >= '1' && x <= '9' then digitToInt x * y else 0) [1..] . B.unpack) [B.reverse a', B.tail b']\n putStrLn $ case compare a b of\n LT -> \"right\"\n GT -> \"left\"\n EQ -> \"balance\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \t\n\t\t\t\ntr '=' = '0'\ntr x = x\n \n\n\nmain= do\n\ts<- getLine \n\tlet s1 = map (\\z-> ord z- ord '0') $ map tr $ reverse $ takeWhile (/='^') s\n\tlet s2 = map (\\z-> ord z- ord '0') $ map tr $ tail $ dropWhile (/='^') s\n\tlet r1 = sum $ zipWith (*) s1 [1..]\n\tlet r2= sum $ zipWith (*) s2 [1..]\n\tputStrLn $ if r1==r2 then \"balance\" else if r1>r2 then \"left\" else \"right\""}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Control.Arrow\nimport Data.Int\n\ndebug x = trace (\"# \" ++ show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\ncar = head\ncdr = tail\ncadr = head . tail\n\n--readInt = fst.fromJust.B.readInt\nreadIntList = return . map read . words :: String -> IO [Int]\ntoDigit n = chr (48 + n)\nchr2num c = ord c - ord '0'\n\nmain = do\n ls <- getContents ||> lines\n -- n <- car ls |> readIO :: IO Int\n -- [n,m] <- car ls |> words |> map read |> return :: IO Int\n putStrLn $ solve $ car ls\n\nsolve l =\n let pos = l |> takeWhile (/= '^') |> length in\n\n let m = loop l (0, pos) 0 in\n\n if m == 0 then \"balance\"\n else if m < 0 then \"right\" else \"left\"\n\n where\n loop :: String -> (Int, Int) -> Int64 -> Int64\n loop [] _ ac = ac\n loop (x:xs) (idx, pos) m =\n if (c < 1 || c > 9)\n then loop xs (idx, pos) m\n else loop xs (idx+1, pos) (m + (fromIntegral $ (pos-idx) * c :: Int64))\n where\n c = chr2num x\n\n-- vim: set ft=haskell:\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Control.Arrow\n\ndebug x = trace (\"# \" ++ show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\ncar = head\ncdr = tail\ncadr = head . tail\n\n--readInt = fst.fromJust.B.readInt\nreadIntList = return . map read . words :: String -> IO [Int]\ntoDigit n = chr (48 + n)\nchr2num c = ord c - ord '0'\n\nmain = do\n ls <- getContents ||> lines\n -- n <- car ls |> readIO :: IO Int\n -- [n,m] <- car ls |> words |> map read |> return :: IO Int\n putStrLn $ solve $ car ls\n\nsolve l =\n let (p, ls) = lead l 0 (0, []) in\n let m = ls |> map (\\(x,w) -> (p-x) * w) |> sum in\n if m == 0 then \"balance\"\n else if m < 0 then \"right\" else \"left\"\n\n where\n lead :: String -> Int -> (Int, [(Int,Int)]) -> (Int, [(Int,Int)])\n lead [] _ ac = ac\n lead ('^':xs) idx (_, ls) = lead xs (idx+1) (idx, ls)\n lead ('=':xs) idx ac = lead xs (idx+1) ac\n lead (x:xs) idx (p, ls) =\n lead xs (idx + 1) (p, (idx, chr2num x) : ls)\n\n-- vim: set ft=haskell:\n"}], "src_uid": "19f2c21b18e84f50e251b1dfd557d32f"} {"source_code": "import Data.Bits\nimport Data.List\n\nbits :: Integral a => a -> [a]\nbits n = bitsWithMul n 1\n where bitsWithMul 0 _ = []\n bitsWithMul n m\n | n `mod` 2 == 1 = m : bitsWithMul (n `div` 2) (m * 2)\n | otherwise = bitsWithMul (n `div` 2) (m * 2)\n\nsplit :: Integral a => [a] -> Int -> [a]\nsplit xs k = splitWithRedun xs (k - length xs)\n where splitWithRedun xs 0 = xs\n splitWithRedun (x:xs) k\n | x /= 1 = let hf = x `div` 2 in splitWithRedun (hf : hf : xs) (k - 1)\n | otherwise = 1 : splitWithRedun xs k\n\nmain = do\n s <- getLine\n let [n, k] = map read (words s) :: [Int]\n if k < popCount n || k > n then\n putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n putStrLn (intercalate \" \" (map show (split (bits n) k)))\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\n\ndata Pow2 = Pow2 { power :: Int, count :: Int }\n deriving (Show, Eq)\n\ntype Decomposition = [Pow2]\n\ntoPows :: Pow2 -> [Int]\ntoPows (Pow2 p c) = replicate c (2 ^ p)\n\ndecompose :: Int -> Decomposition\ndecompose = reverse . go 0\n where go offset n | n == 0 = []\n | even n = go (offset + 1) (n `div` 2)\n | otherwise = (Pow2 offset 1) : go (offset + 1) (n `div` 2)\n\nemplace :: Pow2 -> Decomposition -> Decomposition\nemplace p [] = [p]\nemplace lhs@(Pow2 p1 c1) ps@(rhs@(Pow2 p2 c2):rs) | p1 > p2 = lhs : ps\n | p1 < p2 = rhs : emplace lhs rs\n | otherwise = (Pow2 p1 (c1 + c2)):rs\n\nsolve :: Int -> Int -> Maybe Decomposition\nsolve n k = go ds cr\n where ds = decompose n\n cr = sum $ map count ds\n\n go :: Decomposition -> Int -> Maybe Decomposition\n go [] _ = Nothing\n go ds@(Pow2 p c : rds) curr | curr > k = Nothing\n | curr == k = Just ds\n | p == 0 = Nothing\n | r < c = go ((Pow2 p (c - r)) `emplace` ((Pow2 (p - 1) (2 * r)) `emplace` rds))\n (curr + r)\n | otherwise = go (Pow2 (p - 1) (2 * c) `emplace` rds)\n (curr + c)\n where r = k - curr\n\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n case solve n k of\n Just ds -> do putStrLn \"YES\"\n putStrLn . unwords . map show $ concatMap toPows ds\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport Data.Bits (shiftR)\n\ninAdd :: (Int, Int) -> Int\ninAdd (i, x) = let b = mod (shiftR x i) 2 in if b == 1 then 2 ^ i else b\n\ngetKAdds :: [Int] -> Int -> [Int]\ngetKAdds adds@(x : xs) k\n | x > 1 && k > 0 = let d = div x 2 in getKAdds (d : d : xs) (k - 1)\n | x == 1 && k > 0 = 1 : getKAdds xs k\n | otherwise = adds\ngetKAdds _ _ = []\n\nmain :: IO ()\nmain = do\n nkStr <- getLine\n let [n, k] = map read (words nkStr) :: [Int]\n let adds = filter ((/=) 0) $ map inAdd (zip [0..] (replicate 32 n))\n let kAdds = getKAdds adds (k - length adds)\n if length kAdds /= k\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n mapM_ (\\x -> putStr $ show x ++ \" \") kAdds\n"}], "negative_code": [{"source_code": "import Data.Bits\nimport Data.List\n\nbits :: Integral a => a -> [a]\nbits n = bitsWithMul n 1\n where bitsWithMul 0 _ = []\n bitsWithMul n m\n | n `mod` 2 == 1 = m : bitsWithMul (n `div` 2) (m * 2)\n | otherwise = bitsWithMul (n `div` 2) (m * 2)\n\nsplit :: Integral a => [a] -> Int -> [a]\nsplit xs k = splitWithRedun xs (k - length xs)\n where splitWithRedun xs 0 = xs\n splitWithRedun (x:xs) k\n | x /= 1 = let hf = x `div` 2 in splitWithRedun (hf : hf : xs) (k - 1)\n | otherwise = 1 : splitWithRedun xs k\n\nmain = do\n s <- getLine\n let [n, k] = map read (words s) :: [Int]\n if k < popCount n || k >= n then\n putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n putStrLn (intercalate \" \" (map show (split (bits n) k)))\n"}, {"source_code": "module Main where\n\nimport Data.Bits (shiftR)\n\ninAdd :: (Int, Int) -> Int\ninAdd (i, x) = let b = mod (shiftR x i) 2 in if b == 1 then 2 ^ i else b\n\ngetKAdds :: [Int] -> Int -> [Int]\ngetKAdds adds@(x : xs) k\n | x > 1 && k > 0 = div x 2 : getKAdds (div x 2 : xs) (k - 1)\n | x == 1 && k > 0 = 1 : getKAdds xs k\n | otherwise = adds\ngetKAdds _ _ = []\n\nmain :: IO ()\nmain = do\n nkStr <- getLine\n let [n, k] = map read (words nkStr) :: [Int]\n let adds = filter ((/=) 0) $ map inAdd (zip [0..] (replicate 32 n))\n let kAdds = getKAdds adds (k - length adds)\n if length kAdds /= k\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n mapM_ (\\x -> putStr $ show x ++ \" \") kAdds\n"}], "src_uid": "10d6179b479e1238a51154a9a6fc13cb"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n m \t| n==1 = \"YES\"\n\t\t| m==1 = \"YES\"\n\t\t| n==2 && m==2 = \"YES\"\n\t\t| otherwise = \"NO\"\n\n\nonecase = do\n\t\t[n,m]<-map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn$ process n m\nmain= do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n", "positive_code": [{"source_code": "import Control.Monad.State.Lazy\n\nsolve :: Int -> Int -> String\nsolve 1 _ = \"YES\"\nsolve _ 1 = \"YES\"\nsolve 2 2 = \"YES\"\nsolve _ _ = \"NO\"\n \ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:m:_) <- readNums\n putStrLn $ solve n m\n testCases (t-1)\n \n \nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n \n \nparseNums :: (Read a) => String -> [a]\nparseNums = map read . words\n \nreadNums :: (Read a) => IO [a]\nreadNums = parseNums <$> getLine"}, {"source_code": "\nsolve :: Int -> Int -> String\nsolve 1 _ = \"YES\"\nsolve _ 1 = \"YES\"\nsolve 2 2 = \"YES\"\nsolve _ _ = \"NO\"\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:m:_) <- readNums\n putStrLn $ solve n m\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nparseNums :: (Read a) => String -> [a]\nparseNums = map read . words\n\nreadNums :: (Read a) => IO [a]\nreadNums = parseNums <$> getLine"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n m \t| n==1 && m <4 = \"YES\"\n\t\t| m==1 && n <4 = \"YES\"\n\t\t| n==2 && m==2 = \"YES\"\n\t\t| otherwise = \"NO\"\n\n\nonecase = do\n\t\t[n,m]<-map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn$ process n m\nmain= do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}], "src_uid": "55595ff38a08b80bc86cf1ebae6f55af"} {"source_code": "module Main where\n\nimport List\n\nreadNum::String -> (Int,String)\nreadNum x = case y of\n \"-\" -> ((-1)*(read z),zs)\n _ -> (read y,xs)\n where\n (y,xs) = head(lex x)\n (z,zs) = head(lex xs)\n\nmakeList::Int -> String -> [Int]\nmakeList 0 _ = []\nmakeList n x = y:(makeList (n-1) xs)\n where\n (y,xs) = readNum x\n\ntakeIthOrder i n [x] = \n case (i==n) of\n True -> (x,\"YES\")\n False -> (x,\"NO\")\ntakeIthOrder i n (x:y:xs) =\n case (i==n) of\n True -> (x, \"YES\")\n False -> \n case (x==y) of\n True -> takeIthOrder i n (y:xs)\n False -> takeIthOrder (i+1) n (y:xs)\n\ntakeIth n x = takeIthOrder 1 n x\n\nanswer (num,str) = \n case str of\n \"YES\" -> show num\n \"NO\" -> str\n\nmain = \n do \n n <- getLine\n line <- getLine\n putStrLn( answer (takeIth 2 ( sort (makeList (read n) line) ) ) )", "positive_code": [{"source_code": "{-# LANGUAGE RankNTypes #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\nimport System.IO\n\nimport Data.List\nimport Data.Ord\nimport Data.Array\nimport Control.Monad\n\nmain = do readLn::IO Int\n xs <- (map (read::(String -> Integer)) . words) `liftM` getLine\n let ys = group $ sort xs\n putStrLn $ out ys\n where\n out (a:b:_) = show (head b)\n out _ = \"NO\"\n"}, {"source_code": "main = getContents >>= putStrLn . secondmin . quicksort . map read . words . head . tail . lines\n\nsecondmin :: [Int] -> String\nsecondmin xs \n\t\t\t| ans == [] = \"NO\"\n\t\t\t| otherwise = show $ minimum ans\n\t\t\twhere ans \t= filter (/= minimum xs) xs\n\n\t\t\nquicksort :: [Int] -> [Int]\nquicksort [] = []\nquicksort (x:xs) = quicksort [y | y <- xs, y=x]"}, {"source_code": "\nmain = getContents >>= putStrLn . secondmin . quicksort . map read . words . head . tail . lines\n\nsecondmin :: [Int] -> String\nsecondmin xs \n\t\t\t| ans == [] = \"NO\"\n\t\t\t| otherwise = show $ minimum ans\n\t\t\twhere ans \t= filter (/= minimum xs) xs\n\n\t\t\nquicksort :: [Int] -> [Int]\nquicksort [] = []\nquicksort (x:xs) = quicksort [y | y <- xs, y=x]\n \n"}, {"source_code": "import Data.List\nmain = getLine >> getLine >>= putStrLn. (\\x -> if length x < 2 then \"NO\" else show $ head (x!!1)) . group . sort . map (read ::String -> Int ) . words"}, {"source_code": "\nimport List (sort)\n\nsolve :: [Int] -> Maybe Int\nsolve xs\n | null xsWithoutMin = Nothing\n | otherwise = Just $ head xsWithoutMin\n where\n sortXs = sort xs\n xsWithoutMin = filter (/= head sortXs) sortXs\n\nprintAns :: Maybe Int -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just x) = print x\n\nmain :: IO ()\nmain = do\n getLine\n xs <- getLine >>= return . map read . words\n printAns $ solve xs\n "}, {"source_code": "import Data.List\n\ngao :: [Int] -> String\ngao xs\n | length a > 1 = show $ a !! 1\n | otherwise = \"NO\"\n where\n a = sort $ nub xs\n\nmain :: IO()\nmain = do\n _ <- getLine\n line <- getLine\n let a = map read $ words line\n putStrLn $ gao a\n"}, {"source_code": "import Data.List( sort, nub)\n\nmain = do\n getLine\n ints <- return . map read . words =<< getLine\n let sis = nub . sort $ ints\n\tsis::[Int]\n if length sis == 1\n then putStr \"NO\"\n else print $ sis!!1 \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nmain = do\n\t\tn<-getLine\n\t\ta<- drop 1 <$> group <$> sort <$> map read <$> words <$> getLine::IO [[Int]]\n\t\tputStrLn $ if a==[] then \"NO\" else show $ head $ head a\n"}, {"source_code": "import Data.List (sort, words, group)\n\nmain = do\n n <- getLine\n numbersStr <- getLine\n let numbersInt = (map (\\y -> read y :: Int) (words numbersStr))\n sortedNumbers = sort numbersInt\n\n if (length (group sortedNumbers)) == 1 then\n putStrLn \"NO\"\n else\n putStrLn $ show (head (head (tail (group sortedNumbers))))\n {-putStrLn $ show (map (\\y -> read y :: Int) (words numbers))-}\n {-putStrLn $ show (map (read::Int) (words numbers))-}\n {-putStrLn (words numbers)-}\n\n\n"}], "negative_code": [{"source_code": "\nmain = getContents >>= putStrLn . show . secondmin . quicksort . map read . words . head . tail . lines\n\nsecondmin :: [Int] -> Int\nsecondmin xs \n\t\t\t| ans == [] = minimum xs\n\t\t\t| otherwise = minimum ans\n\t\t\twhere ans \t= filter (/= minimum xs) xs\n\n\t\t\nquicksort :: [Int] -> [Int]\nquicksort [] = []\nquicksort (x:xs) = quicksort [y | y <- xs, y=x]\n \n"}, {"source_code": "import Data.List (sort, words, group)\n\nmain = do\n n <- getLine\n numbersStr <- getLine\n let numbersInt = (map (\\y -> read y :: Int) (words numbersStr))\n sortedNumbers = sort numbersInt\n\n if (length (group sortedNumbers)) == 1 then\n putStrLn \"No\"\n else\n putStrLn $ show (head (head (tail (group sortedNumbers))))\n {-putStrLn $ show (map (\\y -> read y :: Int) (words numbers))-}\n {-putStrLn $ show (map (read::Int) (words numbers))-}\n {-putStrLn (words numbers)-}\n\n\n"}, {"source_code": "import Data.List (sort, words, group)\n\nmain = do\n n <- getLine\n numbersStr <- getLine\n let numbersInt = (map (\\y -> read y :: Int) (words numbersStr))\n sortedNumbers = sort numbersInt\n\n if (length (group sortedNumbers)) == 1 then\n putStrLn \"No\"\n else\n putStrLn $ show (head (tail (group sortedNumbers)))\n {-putStrLn $ show (map (\\y -> read y :: Int) (words numbers))-}\n {-putStrLn $ show (map (read::Int) (words numbers))-}\n {-putStrLn (words numbers)-}\n\n\n"}], "src_uid": "930be5ec102fbe062062aa23eac75187"} {"source_code": "import Data.List\nmain=interact$f.map read.words\nf(n:m:d:x:xs)\n | all (r==) $ map (`rem`d) xs = show.sum $ map(\\y->abs(y-p))ys\n | otherwise = \"-1\"\n where\n r = x `rem` d\n ys = sort.map (\\x->(x-r)`quot`d) $ x:xs\n p = ys!!div(n*m)2\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Debug.Trace\n\nmain = do\n [n,m,d] <- map read . words <$> getLine\n l <- replicateM n (map read . words <$> getLine)\n print $ solve n m d (join l)\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n m d l | check = search f (-20000) (20000)\n | otherwise = -1\n where\n a = head l\n check = and [ (a - b) `mod` d == 0 | b <- l ]\n maxV = maximum l\n minV = minimum l\n minP = minimum [ k | k <- [-20000..20000] , a + k*d >= minV ]\n maxP = maximum [ k | k <- [-20000..20000] , a + k*d <= maxV ]\n f i = sum [ abs (a + i*d - b) `div` d | b <- l]\n\nsearch f l r = loop l r\n where\n loop l r | r - l <= 2 = minimum [f l,f (l+1),f (l+2)]\n | (f m1 < f m2) = loop l m2\n | otherwise = loop m1 r\n where\n m1 = (l*2+r) `div` 3 \n m2 = (l+r*2) `div` 3\n \n\nitof :: Int -> Double\nitof = fromIntegral \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact $ showBI . rd . B.lines\nrd (nmd:mat) = go (readBI <$> B.words nmd) (concat $ map readBI <$> B.words <$> mat) \ngo (_:_:d:[]) mt | (alleq $ (`mod`d) <$> mt) == True = (`div`d) . f . sort $ mt\n | otherwise = -1\nf x = g 0 (length x) 0 (sum x) x\n where g ll _ ls _ [] = ls\n g ll rl ls rs (y:ys) = (abs (ll*y-ls) + abs (rl*y-rs))`min`(g (ll+1) (rl-1) (ls+y) (rs-y) ys) \nalleq (x:[]) = True\nalleq (x:y:xs) = (x==y)&&(alleq (y:xs))\n\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\n\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\n\nmain = do\n [n,m,d] <- map read . words <$> getLine\n l <- replicateM n (map read . words <$> getLine)\n print $ solve n m d (join l)\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n m d l | check = search f minP maxP\n | otherwise = -1\n where\n a = head l\n check = and [ (a - b) `mod` d == 0 | b <- l ]\n maxV = maximum l\n minV = minimum l\n minP = minimum [ k | k <- [-20000..20000] , a + k*d >= minV ]\n maxP = maximum [ k | k <- [-20000..20000] , a + k*d <= maxV ]\n f i = sum [ abs (a + i*d - b) `div` d | b <- l]\n\nsearch f l r = loop l r\n where\n loop l r | l - r <= 2 = minimum [f l,f (l+1),f (l+2)]\n | f m1 < f m2 = loop l m2\n | otherwise = loop m1 r\n where\n m1 = (l*2+r) `div` 3 \n m2 = (l+r*2) `div` 3\n \n\nitof :: Int -> Double\nitof = fromIntegral \n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\n\nmain = do\n [n,m,d] <- map read . words <$> getLine\n l <- replicateM n (map read . words <$> getLine)\n print $ solve n m d (join l)\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n m d l | check = search f minP maxP\n | otherwise = -1\n where\n a = head l\n check = and [ (a - b) `mod` d == 0 | b <- l ]\n maxV = maximum l\n minV = minimum l\n minP = minimum [ k | k <- [-10000..10000] , a + k*d >= minV ]\n maxP = maximum [ k | k <- [-10000..10000] , a + k*d <= maxV ]\n f i = sum [ abs (a + i*d - b) `div` d | b <- l]\n\nsearch f l r = loop l r\n where\n loop l r | l - r <= 2 = minimum [f l,f (l+1),f (l+2)]\n | f m1 < f m2 = loop l m2\n | otherwise = loop m1 r\n where\n m1 = (l*2+r) `div` 3 \n m2 = (l+r*2) `div` 3\n \n\nitof :: Int -> Double\nitof = fromIntegral \n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\n\nmain = do\n [n,m,d] <- map read . words <$> getLine\n l <- replicateM n (map read . words <$> getLine)\n print $ solve n m d (join l)\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n m d l | check = search f minP maxP\n | otherwise = -1\n where\n a = head l\n check = and [ (a - b) `mod` d == 0 | b <- l ]\n maxV = maximum l\n minV = minimum l\n minP = minimum [ k | k <- [-10000..10000] , a + k*d >= minV ]\n maxP = maximum [ k | k <- [-10000..10000] , a + k*d <= maxV ]\n f i = sum [ abs (a + i*d - b) `div` d | b <- l]\n\nsearch f l r = loop l r\n where\n loop l r | l - r <= 2 = minimum [f l,f (l+1),f (l+2)]\n | f m1 > f m2 = loop l m2\n | otherwise = loop m1 r\n where\n m1 = (l*2+r) `div` 3 \n m2 = (l+r*2) `div` 3\n \n\nitof :: Int -> Double\nitof = fromIntegral \n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\n\nmain = do\n [n,m,d] <- map read . words <$> getLine\n l <- replicateM n (map read . words <$> getLine)\n print $ solve n m d (join l)\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n m d l | check = minimum [ sum [ abs (x-b) `div` d | b <- l],\n sum [ abs (x-d-b) `div` d | b <- l],\n sum [ abs (x+d-b) `div` d | b <- l]]\n | otherwise = -1\n where\n a = head l\n check = and [ (a - b) `mod` d == 0 | b <- l ]\n avg = sum (map itof l) / itof (n*m)\n x = snd $ minimum [ (abs (itof a+itof k* itof d-avg),a+k*d) | k <- [-10000..10000]]\n\nitof :: Int -> Double\nitof = fromIntegral \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact $ showBI . rd . B.lines\nrd (nmd:mat) = go (readBI <$> B.words nmd) (concat $ map readBI <$> B.words <$> mat) \ngo (_:_:d:[]) mt | (alleq $ (`mod`d) <$> mt) == True = g . f $ dv\n | otherwise = -1\n where g x = sum $ (abs . (x`subtract`)) <$> dv\n dv = (`div`d) <$> mt\nf x = minimum $ (\\y -> maximum $ (\\z -> abs (y-z)) <$> x) <$> [1..10^4]\nalleq (x:[]) = True\nalleq (x:y:xs) = (x==y)&&(alleq (y:xs))\n\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\n\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact $ showBI . rd . B.lines\nrd (nmd:mat) = go (readBI <$> B.words nmd) (concat $ map readBI <$> B.words <$> mat) \ngo (_:_:d:[]) mt | (alleq $ (`mod`d) <$> mt) == True = (`div`d) . f . sort $ mt\n | otherwise = -1\nf x = g 0 (length x) 0 (sum x) x\n where g ll _ ls _ [] = ll*ls\n g ll rl ls rs (y:ys) = (abs (ll*y-ls) + abs (rl*y-rs))`min`(g (ll+1) (rl-1) (ls+y) (rs-y) ys) \nalleq (x:[]) = True\nalleq (x:y:xs) = (x==y)&&(alleq (y:xs))\n\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\n\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n"}], "src_uid": "3488bb49de69c0c17ea0439e71b1e6ae"} {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = f xs\n where\n split xs = case dropWhile (0==) xs of\n [] -> []\n ys -> case span (0/=) ys of\n (zs,ws) -> zs : split ws\n f [x] = 1\n f xs\n | m >= l = l\n | otherwise = case foldl' (\\acc x->acc+f x) 0 . split $ map (subtract m) xs of\n res -> case min l (m + res) of {x -> x}\n where\n !m = minimum xs\n !l = length xs\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Word\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = f 0 (0,n-1)\n where\n !arr = listArray (0,n-1) xs :: UArray Int Int\n !rmq = mkRMQ xs\n split :: Int -> (Int, Int) ->[(Int,Int)]\n split !h (l0,r0) = go [l0..r0]\n where\n go is = case dropWhile (\\i->unsafeAt arr i <= h) is of\n is'@(_:_) -> case span (\\i->unsafeAt arr i>h) is' of\n ((l:_),(r:rs)) -> (l,r-1):go rs\n ((l:_),[]) -> [(l,r0)]\n [] -> []\n f !h (!l,!r) = min (r - l + 1) $ m - h + foldl' (\\acc lr->acc+f m lr) 0 (split m (l,r))\n where\n !m = query rmq l r\n\ntype RMQ = UArray (Int,Int) Int\n\nmkRMQ :: [Int] -> RMQ\nmkRMQ xs = runSTUArray $ do\n let !n = length xs\n rmq <- newArray_ ((0,0),(log2 n,n-1)) :: ST s (STUArray s (Int,Int) Int)\n let go !i (x:xs) = unsafeWrite rmq i x >> go (i+1) xs\n go _ _ = return ()\n go 0 xs\n forM_ [1..log2 n] $ \\logk -> do\n forM_ [(logk-1)*n..(logk-1)*n+n-1] $ \\ki -> do\n unsafeRead rmq ki >>= unsafeWrite rmq (ki+n)\n let !k = 1 .<<. (logk-1)\n rep (n-k) $ \\i -> do\n xi <- unsafeRead rmq $ logk*n+i\n xik <- unsafeRead rmq $ logk*n+i+k\n when (xik < xi) $ do\n unsafeWrite rmq (logk*n+i) xik\n return rmq \n\nquery :: RMQ -> Int -> Int -> Int\nquery rmq l r = (rmq!(log2d, l)) `min` (rmq!(log2d, r - (1 .<<. log2d) + 1))\n where\n !log2d = log2 $ r - l\n{-# INLINE query #-}\n\ninfixl 8 .<<. , .>>.\n(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a\n(.<<.) = unsafeShiftL\n(.>>.) = unsafeShiftR\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nlog2 :: Int -> Int\nlog2 x = unsafeAt magic32 . fromIntegral $ (e * 0x07c4acdd) .>>. 27\n where\n w :: Word\n w = fromIntegral x\n !a = w .|. (w .>>. 1)\n !b = a .|. (a .>>. 2)\n !c = b .|. (b .>>. 4)\n !d = c .|. (c .>>. 8)\n !e = d .|. (d .>>. 16)\n\nmagic32 :: UArray Int Int\nmagic32 = listArray (0,31) [ 0, 9, 1, 10, 13, 21, 2, 29\n , 11, 14, 16, 18, 22, 25, 3, 30\n , 8, 12, 20, 28, 15, 17, 24, 7\n , 19, 27, 23, 6, 26, 5, 4, 31\n ]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Word\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = f 0 $ zip[0..]xs\n where\n !rmq = mkRMQ xs\n split !h ixs = case dropWhile ((h==).snd) ixs of\n [] -> []\n ys -> case span ((h/=).snd) ys of\n (zs,ws) -> zs : split h ws\n f !h ixs@((i,_):_) = res\n where\n !l = length ixs\n !m = query rmq i (i+l-1)\n !merged = foldl' (\\acc ix->acc+f m ix) 0 $ split m ixs\n !res = min l (m - h + merged)\n\ntype RMQ = UArray (Int,Int) Int\n\nmkRMQ :: [Int] -> RMQ\nmkRMQ xs = runSTUArray $ do\n let !n = length xs\n rmq <- newArray_ ((0,0),(log2 n,n-1)) :: ST s (STUArray s (Int,Int) Int)\n let go !i (x:xs) = unsafeWrite rmq i x >> go (i+1) xs\n go _ _ = return ()\n go 0 xs\n forM_ [1..log2 n] $ \\logk -> do\n forM_ [(logk-1)*n..(logk-1)*n+n-1] $ \\ki -> do\n unsafeRead rmq ki >>= unsafeWrite rmq (ki+n)\n let !k = 1 .<<. (logk-1)\n rep (n-k) $ \\i -> do\n xi <- unsafeRead rmq $ logk*n+i\n xik <- unsafeRead rmq $ logk*n+i+k\n when (xik < xi) $ do\n unsafeWrite rmq (logk*n+i) xik\n return rmq \n\nquery :: RMQ -> Int -> Int -> Int\nquery rmq l r = (rmq!(log2d, l)) `min` (rmq!(log2d, r - (1 .<<. log2d) + 1))\n where\n !log2d = log2 $ r - l\n{-# INLINE query #-}\n\ninfixl 8 .<<. , .>>.\n(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a\n(.<<.) = unsafeShiftL\n(.>>.) = unsafeShiftR\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nlog2 :: Int -> Int\nlog2 x = unsafeAt magic32 . fromIntegral $ (e * 0x07c4acdd) .>>. 27\n where\n w :: Word\n w = fromIntegral x\n !a = w .|. (w .>>. 1)\n !b = a .|. (a .>>. 2)\n !c = b .|. (b .>>. 4)\n !d = c .|. (c .>>. 8)\n !e = d .|. (d .>>. 16)\n\nmagic32 :: UArray Int Int\nmagic32 = listArray (0,31) [ 0, 9, 1, 10, 13, 21, 2, 29\n , 11, 14, 16, 18, 22, 25, 3, 30\n , 8, 12, 20, 28, 15, 17, 24, 7\n , 19, 27, 23, 6, 26, 5, 4, 31\n ]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Word\nimport GHC.Arr (Array, Ix, unsafeIndex)\nimport Unsafe.Coerce\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = f 0 (0,n-1)\n where\n !arr = listArray (0,n-1) xs :: UArray Int Int\n !rmq = mkRMQ xs\n split :: Int -> (Int, Int) ->[(Int,Int)]\n split !h (l0,r0) = go $ until (\\i -> i<=r0 && unsafeAt arr i/=h || r0 < i) (1+) l0\n where\n go !i\n | i<=r0 && j<=r0 = (i,j) : go (until (\\i -> i<=r0 && unsafeAt arr i/=h || r0 < i) (1+) $ j+1)\n | otherwise = []\n where\n !j = min r0 . subtract 1 $ until (\\i -> i<=r0 && unsafeAt arr i==h || r0acc+f m lr) 0 (split m (l,r))\n where\n !m = query rmq l r\n\ntype RMQ = UArray (Int,Int) Int\n\nmkRMQ :: [Int] -> RMQ\nmkRMQ xs = runSTUArray $ do\n let !n = length xs\n rmq <- newArray_ ((0,0),(log2 n,n-1)) :: ST s (STUArray s (Int,Int) Int)\n let go !i (x:xs) = unsafeWrite rmq i x >> go (i+1) xs\n go _ _ = return ()\n go 0 xs\n forM_ [1..log2 n] $ \\logk -> do\n forM_ [(logk-1)*n..(logk-1)*n+n-1] $ \\ki -> do\n unsafeRead rmq ki >>= unsafeWrite rmq (ki+n)\n let !k = 1 .<<. (logk-1)\n rep (n-k) $ \\i -> do\n xi <- unsafeRead rmq $ logk*n+i\n xik <- unsafeRead rmq $ logk*n+i+k\n when (xik < xi) $ do\n unsafeWrite rmq (logk*n+i) xik\n return rmq \n\nquery :: RMQ -> Int -> Int -> Int\nquery rmq l r = (rmq!(log2d, l)) `min` (rmq!(log2d, r - (1 .<<. log2d) + 1))\n where\n !log2d = log2 $ r - l\n{-# INLINE query #-}\n\ninfixl 8 .<<. , .>>.\n(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a\n(.<<.) = unsafeShiftL\n(.>>.) = unsafeShiftR\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nlog2 :: Int -> Int\nlog2 x = unsafeAt magic32 . unsafeCoerce $ (e * 0x07c4acdd) .>>. 27\n where\n w :: Word\n w = unsafeCoerce x\n !a = w .|. (w .>>. 1)\n !b = a .|. (a .>>. 2)\n !c = b .|. (b .>>. 4)\n !d = c .|. (c .>>. 8)\n !e = (d .|. (d .>>. 16))\n{-# INLINE log2 #-}\n\nmagic32 :: UArray Int Int\nmagic32 = listArray (0,31) [ 0, 9, 1, 10, 13, 21, 2, 29\n , 11, 14, 16, 18, 22, 25, 3, 30\n , 8, 12, 20, 28, 15, 17, 24, 7\n , 19, 27, 23, 6, 26, 5, 4, 31\n ]\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve :: [Int] -> Int\nsolve = solve' 0\n where solve' _ [] = 0\n solve' h xs = min (length xs) $ solve' h' l + solve' h' (tail r) + h' - h \n where h' = minimum xs\n (l, r) = break (==h') xs"}, {"source_code": "isolve :: [Int] -> Int\n-- solve when all elems are positive\nisolve [] = 0\nisolve li = let\n q = minimum li\n redAns = q + solve (map (subtract q) li)\n in min (length li) redAns\n\nsolve :: [Int] -> Int\n-- solve in general: O(n*n).\nsolve [] = 0\nsolve li = let\n (pos, rest) = span (> 0) li\n in isolve pos + solve (dropWhile (== 0) rest)\n\nmain :: IO ()\nmain = do\n _nStr <- getLine\n ali <- map read . words <$> getLine\n print $ solve ali\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.concat.map (map read.words).take 2. lines\nsolve :: [Integer]-> String\nsolve (x:xs) = show $ slv1 (x:xs)\nslv1 [] = 0\nslv1 (x:xs)= minimum [x, mi + sum [slv1 y|y<-ff]]\n where\n ff=foldr (f) [[]] $ map (\\a->a-mi) xs \n mi = minimum xs\n f 0 [[]] = [[]]\n f 0 ([]:bs) = ([]:bs)\n f 0 bs = ([]:bs)\n f a [[]] = [[1,a]]\n f a ([]:bs) = ([1,a]:bs)\n f a ((b:bs):bss) = ((b+1:a:bs):bss)"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "module Main where\n\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\n\nreadInt = fromIntegral . fst . fromJust . BS8.readInteger\nreadLine = BS8.getLine >>= return . map readInt . BS8.words\n\ntrimZero list\n | length list == 0 = list\n | head list == 0 = trimZero (tail list)\n | otherwise = list\n\npaint planks = min (length planks) (f planks)\n where f _planks\n | length _planks == 0 = 0\n | length _planks == 1 = 1\n | otherwise = minValue + (paint first) + paint (trimZero second)\n where minValue = minimum _planks\n (first, second) = break (== 0) $ map (subtract minValue) _planks\n\n\nmain = do\n [_] <- readLine\n planks <- readLine\n print $ paint planks\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n n <- readLn\n ns <- getInts\n\n let arr = listArray (0, n-1) ns :: UArray Int Int\n\n go !l !r !h\n | w <= 1 = w\n | otherwise = min w $ (minh - h) + sum (map (\\(a, b) -> go a b minh) $ filter nonnull $ spans l l)\n where\n w = r - l\n minh = foldl1' min $ map (arr!) [l..r-1]\n nonnull (a, b) = a /= b\n\n spans s i\n | i == r = [(s, i)]\n | arr!i == minh = (s, i) : spans (i+1) (i+1)\n | otherwise = spans s (i+1)\n\n print $ go 0 n 0\n"}, {"source_code": "import Data.List\nmain = interact $ solve.map read.drop 1.words\nsolve xs=show $ solve' xs 0\n\twhere solve' [] _ = 0\n solve' xs h = min (length xs) $ (solve' l h') + (solve' (tail r) h') + h'- h\n\t\t where h' = minimum xs\n\t\t \t(l,r)=break (==h') xs\n\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n width:_ <- readLine\n heights <- readLine\n B.putStrLn . B.pack . show $ paintTheWall width heights\n\npaintTheWall :: Int -> [Int] -> Int\npaintTheWall 0 _ = 0\npaintTheWall 1 _ = 1\npaintTheWall width heights = min width $ (+ minHeight) $ sum $ map (\\h -> paintTheWall (length h) h) $ splitByZero $ map (\\x -> x - minHeight) heights\n where minHeight = minimum heights\n\nsplitByZero :: [Int] -> [[Int]]\nsplitByZero = foldr takeTillZero [[]]\n\ntakeTillZero :: Int -> [[Int]] -> [[Int]]\ntakeTillZero n agg@(x:xs)\n | null agg = error \"WTF\"\n | and [n == 0, null x] = agg\n | n == 0 = []:agg\n | otherwise = (n:x):xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Data.List (groupBy)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nsolve [] [] = 0\nsolve [(n, h, s)] [] = min n (h + s)\nsolve ((n, h, s) : (n2, h2, s2) : stack) [] =\n solve ((n2 + n, h2, s2 + (min n (h - h2 + s))) : stack) []\nsolve [] (plank : fence) =\n solve [(1, plank, 0)] fence\nsolve ((n, h, s) : stack) (plank : fence) =\n if plank > h then\n solve ((1, plank, 0) : (n, h, s) : stack) fence\n else if plank == h then\n solve ((n + 1, h, s) : stack) fence\n else if stack == [] then\n solve [(n + 1, plank, min n (h - plank + s))]\n fence\n else\n let (n2, h2, s2) = head stack\n in\n if h2 >= plank then\n solve ((n2 + n, h2, s2 + min n (h - h2 + s)) : tail stack)\n (plank : fence)\n else\n solve ((n + 1, plank, min n (h - plank + s)) : stack)\n fence\n\noldSolve planks =\n let\n min = if planks == [] then 0 else minimum planks\n in\n if min >= length planks then\n length planks\n else\n (+ min) .\n sum .\n map oldSolve .\n filter ((/= 0) . head) .\n groupBy ((==) `on` (== 0)) .\n map (flip (-) min) $ planks\n\ncheck fenceRaw =\n let fence = map ((+1) . abs) fenceRaw\n in oldSolve fence == solve [] fence\n\nmain = do\n _ <- readLine \n planks <- readLine\n B.putStrLn . B.pack . show $ solve [] planks\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n n <- readLn\n ns <- getInts\n\n let arr = listArray (0, n-1) ns :: UArray Int Int\n\n go !l !r !h\n | w <= 1 = w\n | otherwise = min w $ (minh - h) + sum (map (\\(a, b) -> go a b minh) $ filter nonnull $ spans 0 0)\n where\n w = r - l\n minh = foldl1' min $ map (arr!) [l..r-1]\n nonnull (a, b) = a /= b\n\n spans s i\n | i == r = [(s, i)]\n | arr!i == minh = (s, i) : spans (i+1) (i+1)\n | otherwise = spans s (i+1)\n\n print $ go 0 n 0\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Data.List (groupBy)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nsolve [] [] = 0\nsolve [(n, h)] [] = min n h\nsolve ((n, h) : (n2, h2) : stack) [] =\n min n h + solve ((n2 + n, h2) : stack) []\nsolve [] (plank : fence) =\n solve [(1, plank)] fence\nsolve ((n, h) : stack) (plank : fence) =\n if plank > h then\n solve ((1, plank) : (n, h) : stack) fence\n else if plank == h then\n solve ((n + 1, h) : stack) fence\n else if stack == [] then\n min n (h - plank) +\n solve [(n + 1, plank)] fence\n else\n let (n2, h2) = head stack\n in\n min n (h - h2) +\n solve ((n2 + n, h2) : tail stack) (plank : fence)\n\nmain = do\n _ <- readLine \n planks <- readLine\n B.putStrLn . B.pack . show $ solve [] planks\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Data.List (groupBy)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nsolve [] [] = 0\nsolve [(n, h)] [] = min n h\nsolve ((n, h) : (n2, h2) : stack) [] =\n min n h + solve ((n2 + n, h2) : stack) []\nsolve [] (plank : fence) =\n solve [(1, plank)] fence\nsolve ((n, h) : stack) (plank : fence) =\n if plank > h then\n solve ((1, plank) : (n, h) : stack) fence\n else if plank == h then\n solve ((n + 1, h) : stack) fence\n else if stack == [] then\n min n (h - plank) +\n solve [(n + 1, plank)] fence\n else\n let (n2, h2) = head stack\n in\n if h2 >= plank then\n min n (h - h2) +\n solve ((n2 + n, h2) : tail stack) (plank : fence)\n else\n min n (h - plank) +\n solve ((n + 1, plank) : stack) fence\n\nmain = do\n _ <- readLine \n planks <- readLine\n B.putStrLn . B.pack . show $ solve [] planks\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Function (on)\nimport Data.List (groupBy)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nsolve [] [] = 0\nsolve [(n, h, s)] [] = min n (h + s)\nsolve ((n, h, s) : (n2, h2, s2) : stack) [] =\n solve ((n2 + n, h2, s2 + (min n (h + s))) : stack) []\nsolve [] (plank : fence) =\n solve [(1, plank, 0)] fence\nsolve ((n, h, s) : stack) (plank : fence) =\n if plank > h then\n solve ((1, plank, 0) : (n, h, s) : stack) fence\n else if plank == h then\n solve ((n + 1, h, s) : stack) fence\n else if stack == [] then\n solve [(n + 1, plank, min n (h - plank + s))]\n fence\n else\n let (n2, h2, s2) = head stack\n in\n if h2 >= plank then\n solve ((n2 + n, h2, s2 + min n (h - h2 + s)) : tail stack)\n (plank : fence)\n else\n solve ((n + 1, plank, min n (h - plank + s)) : stack)\n fence\n\noldSolve planks =\n let\n min = if planks == [] then 0 else minimum planks\n in\n if min >= length planks then\n length planks\n else\n (+ min) .\n sum .\n map oldSolve .\n filter ((/= 0) . head) .\n groupBy ((==) `on` (== 0)) .\n map (flip (-) min) $ planks\n\ncheck fenceRaw =\n let fence = map ((+1) . abs) fenceRaw\n in oldSolve fence == solve [] fence\n\nmain = do\n _ <- readLine \n planks <- readLine\n B.putStrLn . B.pack . show $ solve [] planks\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = f xs\n where\n split xs = case dropWhile (0==) xs of\n [] -> []\n ys -> case span (0/=) ys of\n (zs,ws) -> zs : split ws\n f [x] = 1\n f [] = 0\n f xs = m + sum (map f . split $ map (subtract m) xs)\n where\n m = minimum xs\n"}], "src_uid": "ddab0e510f9aceb2fbf75e26d27df166"} {"source_code": "import qualified Data.ByteString.Char8 as B\nmain = getLine >> B.getLine >>= print . solve\nsolve bs\n | i==0 = a\n | i==1 = 1\n | otherwise = 0\n where\n a = B.count 'A' bs\n i = B.count 'I' bs", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n _ <- getLine\n statuses <- getLine\n let is = length $ filter (== 'I') statuses\n as = length $ filter (== 'A') statuses\n\n print $ if is > 1 \n then 0 \n else if is == 1\n then 1\n else as\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n B.getLine\n s <- B.getLine\n print $ solve s\n\nsolve :: B.ByteString -> Int\nsolve s = if i == 0 then a else if i == 1 then 1 else 0\n where\n (a,i,f) = B.foldl g (0,0,0) s\n g (a,i,f) 'A' = (a+1,i,f)\n g (a,i,f) 'I' = (a,i+1,f)\n g (a,i,f) 'F' = (a,i,f+1)\n g s _ = s\n\n"}, {"source_code": "import Data.List\n\nsolve :: String -> Int\nsolve xs = foldl' toShow 0 xs\n where\n toShow x 'A' | in_count == 0 = x + 1\n toShow x 'I' | in_count == 1 = x + 1\n toShow x _ = x\n in_count = length $ filter ('I'==) xs\n\nmain = interact $ show . solve . concat . tail . words"}, {"source_code": "solve :: String -> Int\nsolve s\n | i == 0 = a\n | i == 1 = 1\n | otherwise = 0\n where\n a = length $ filter (== 'A') s\n i = length $ filter (== 'I') s\n\nmain :: IO ()\nmain = getLine >> getLine >>= print . solve"}, {"source_code": "-- Codeforces 284B\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= print . solve\n\nsolve :: String -> Int\nsolve xs = case cnt_I\n of {\n 0 -> cnt_A;\n 1 -> 1;\n otherwise -> 0;\n }where\n cnt_I = length $ filter (== 'I') xs \n cnt_A = length $ filter (== 'A') xs"}, {"source_code": "data \u0421\u0442\u0430\u0442\u0443\u0441 = ALLIN | IN | FOLDED deriving (Eq)\nmain = do\n s1 <- getLine\n s2 <- getLine\n let \u043a\u043e\u0440\u043e\u0432\u043a\u0438 = map to\u0421\u0442\u0430\u0442\u0443\u0441 s2\n print $ \u0440\u0435\u0448\u0438\u0442\u044c \u043a\u043e\u0440\u043e\u0432\u043a\u0438\n \nto\u0421\u0442\u0430\u0442\u0443\u0441 'A' = ALLIN\nto\u0421\u0442\u0430\u0442\u0443\u0441 'I' = IN\nto\u0421\u0442\u0430\u0442\u0443\u0441 'F' = FOLDED\n\n\u0440\u0435\u0448\u0438\u0442\u044c \u043a\u043e\u0440\u043e\u0432\u043a\u0438 | inCount == 0 = length $ filter (==ALLIN) \u043a\u043e\u0440\u043e\u0432\u043a\u0438\n | inCount == 1 = 1\n | otherwise = 0\n where inCount = length $ filter (==IN) \u043a\u043e\u0440\u043e\u0432\u043a\u0438\n"}, {"source_code": "main = do\n _ <- getLine\n b <- getLine\n putStr $ show $ case length (filter (== 'I') b) of \n 0 -> length (filter (== 'A') b)\n 1 -> 1\n _ -> 0"}, {"source_code": "main = do\n getLine\n l <- getLine\n putStrLn $ if (elem 'I' l) then (if (count 'I' l == 1) then \"1\" else \"0\") else (show . count 'A' $ l)\n where\n count c = length . filter (==c)"}], "negative_code": [{"source_code": "solve :: String -> Int\nsolve s\n | i == 0 = a\n | i == 1 = 1\n | otherwise = 0\n where\n a = length $ filter (== 'A') s\n i = length $ filter (== 'I') s\n\nmain :: IO ()\nmain = getLine >>= print . solve"}, {"source_code": "main = do\n a <- getLine\n b <- getLine\n putStr $ show $ if length (filter (== 'I') b) == 1 then 1 else length (filter (== 'A') b)"}, {"source_code": "main = do\n getLine\n l <- getLine\n putStrLn $ if (elem 'I' l) then (show (max (count 'I' l) 1)) else (show . count 'A' $ l)\n where\n count c = length . filter (==c)"}, {"source_code": "main = do\n getLine\n l <- getLine\n putStrLn $ if (elem 'I' l) then \"1\" else (show . length . filter (=='A') $ l)"}], "src_uid": "5e4defe52832cc0d36e7ea5d9f86f895"} {"source_code": "import List\ng[]=[[],[]]\ng((_,a):b)=(\\[x,y]->[y,a:x])$g b\np x=[show$length x,unwords$map show x]\nmain=interact$unlines.(>>=p).g.sort.(`zip`[1..]).map((+0).read).tail.words", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.List\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nsolve :: [(Int, Int)] -> (([Int],Int),([Int],Int)) -> ([Int],[Int])\nsolve [] ((a,_),(b,_)) = (a,b)\nsolve [(xp,xn)] ((a,as),(b,bs))\n | as < bs = (xn:a, b)\n | otherwise = (a, xn:b)\nsolve ((xp,xn):(yp,yn):zz) ((a,as),(b,bs))\n | as < bs = solve zz ((xn:a, as + xp), (yn:b, bs + yp))\n | otherwise = solve zz ((yn:a, as + yp), (xn:b, bs + xp))\n\np xs = do\n print $ length xs\n putStrLn . concat . intersperse \" \" $ map show xs\n\nmain = do\n input <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n let n = readInt $ head input\n xs = reverse . sort . flip zip [1..] . readIntList $ input !! 1\n let (ansx, ansy) = solve xs (([], 0), ([], 0))\n p ansx\n p ansy\n\n-- vim: set expandtab:\n"}, {"source_code": "import Control.Monad\nimport Data.List\npart [] accum = accum\npart [b] (v1, t1, v2, t2) = if v1 < v2 then (v1 + fst b, snd b : t1, v2, t2)\n else (v1, t1, v2 + fst b, snd b : t2)\npart (b1:b2:bs) (v1, t1, v2, t2) =\n if (v1 < v2 && fst b1 < fst b2) || (v1 > v2 && fst b1 > fst b2)\n then part bs (v1 + fst b2, snd b2 : t1, v2 + fst b1, snd b1 : t2)\n else part bs (v1 + fst b1, snd b1 : t1, v2 + fst b2, snd b2 : t2)\nmain = do\n n <- (liftM read) getLine\n skills <- (liftM $ reverse . sort . flip zip [1..n] . (map read) . words) getLine\n let (v1, t1, v2, t2) = part skills (0, [], 0, [])\n putStrLn . show $ length t1\n putStrLn . unwords $ map show t1\n putStrLn . show $ length t2\n putStrLn . unwords $ map show t2\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [[Int]]\nsolve (n:xs) = [[length evens], evens, [length odds], odds]\n where \n summary = sortBy (\\(a,b) (c,d) -> compare a c) $ zip xs $ iterate (+1) 1\n (evens, odds) = split summary [] [] 1\n split [] es os _ = (es, os)\n split ((x, p):xs) es os i | even i = split xs (p:es) os $ i + 1\n | odd i = split xs es (p:os) $ i + 1\n\nmain = do \n input <- getContents\n sequence_ $ map (putStrLn.show) $ concat $ solve.map read.words $ input"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate, sortBy)\nimport Prelude hiding (reads)\n\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n where\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + ord c - ord '0'\n\nprints :: Show a => [a] -> IO ()\nprints as = print (length as) >> prints' as\n where\n prints' = putStrLn . intercalate \" \" . map show\n\nsolve :: [Int] -> ([Int], [Int])\nsolve as = (map (fst . snd) one, map (fst . snd) two)\n where\n one = filter (odd . fst) sorted\n two = filter (even . fst) sorted\n sorted = zip [1..] $ sortBy compare' $ zip [1..] as\n compare' a b = compare (snd a) (snd b)\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n prints $ fst $ solve as\n prints $ snd $ solve as"}, {"source_code": "import Data.List\n\nsolve bs = foldl' makeChoice (0, [], 0, []) $ sortBy (\\(_, a) (_, b) -> compare a b) $ zip [1 .. ] bs\n where makeChoice (x, xs, y, ys) (i, a)\n | x <= y = (x + a, i : xs, y, ys)\n | otherwise = (x, xs, y + a, i : ys)\n\nmain = do _ <- getLine\n bs <- fmap (map read . words) getLine\n\n let (x, xs, y, ys) = solve bs\n\n putStrLn $ show $ length xs\n putStrLn $ unwords $ map show xs\n\n putStrLn $ show $ length ys\n putStrLn $ unwords $ map show ys"}, {"source_code": "import Data.Ord\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n xs <- map read' <$> B.words <$> B.getLine\n putStrLn $ unlines $ map (unwords . map show) $ solve n xs\n\nread' s = let Just (n,_) = B.readInt s\n in n\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve n xs = solve' (0,0) (0,0) ([],[]) $ sortBy (comparing snd) $ zip [1..] xs\n\nsolve' :: (Int,Int) -> (Int,Int) -> ([Int],[Int]) -> [(Int,Int)] -> [[Int]]\nsolve' (ix,iy) (sx,sy) (xs,ys) [] = [[ix],xs,[iy],ys]\nsolve' (ix,iy) (sx,sy) (xs,ys) ((i,n):ns)\n | sx == sy && ix <= iy = solve' (ix+1,iy) (sx+n,sy) (i:xs,ys) ns\n | sx == sy = solve' (ix,iy+1) (sx,sy+n) (xs,i:ys) ns\n | sx < sy = solve' (ix+1,iy) (sx+n,sy) (i:xs,ys) ns\n | sx > sy = solve' (ix,iy+1) (sx,sy+n) (xs,i:ys) ns"}, {"source_code": "import Data.List\nimport Data.Map hiding(map,filter)\nimport Data.Function\n\nleft (ls,rs) x = (x:ls,rs)\nright (ls,rs) x = (ls,x:rs)\n\ndivision = left:cycle [right,right,left,left]\n\nresult :: [[Int]]->[[Int]]\nresult [_,xs] = [[length (fst res)],fst res,[length (snd res)],snd res]\n\twhere\n\tsortedIndexes = map fst.reverse.sortBy (compare `on` snd)$zip [1..] xs\n\tf a (d,x) = d a x\n\tres = foldl f ([],[]) (zip division sortedIndexes)\n\nmain=interact$unlines.map (unwords.map show).result.map (map read.words).lines\n"}, {"source_code": "import List\ng(_,a)[x,y]=[y,a:x]\np x=[[length x],x]\nmain=interact$unlines.map(unwords.map show).(>>=p).foldr g[[],[]].sort.(`zip`[1..]).map((+0).read).tail.words\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.List\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nsolve :: [(Int, Int)] -> (([Int],Int),([Int],Int)) -> ([Int],[Int])\nsolve [] ((a,_),(b,_)) = (a,b)\nsolve [(xn,xp)] ((a,as),(b,bs))\n | as < bs = (xn:a, b)\n | otherwise = (a, xn:b)\nsolve ((xn,xp):(yn,yp):zz) ((a,as),(b,bs))\n | as < bs = solve zz ((xn:a, as + xp), (yn:b, bs + yp))\n | otherwise = solve zz ((yn:a, as + yp), (xn:b, bs + xp))\n\np xs = do\n print $ length xs\n putStrLn . concat . intersperse \" \" $ map show xs\n\nmain = do\n input <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n let n = readInt $ head input\n xs = reverse . sort . zip [1..] . readIntList $ input !! 1\n let (ansx, ansy) = solve xs (([], 0), ([], 0))\n p ansx\n p ansy\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [[Int]]\nsolve (k:xs) = [[length evens], evens, [length odds], odds]\n where \n summary = sortBy (\\(a,b) (c,d) -> compare a b) $ zip xs $ iterate (+1) 1\n (_, odds) = unzip $ filter (\\(a, b) -> odd b) $ summary\n (_, evens) = unzip $ filter (\\(a, b) -> even b) $ summary\n\nmain = do \n input <- getLine\n sequence_ $ map (putStrLn.show) $ concat $ solve.map read.words $ input"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [[Int]]\nsolve (k:xs) = [[length evens], evens, [length odds], odds]\n where \n summary = sortBy (\\(a,b) (c,d) -> compare a b) $ zip xs $ iterate (+1) 1\n (_, odds) = unzip $ filter (\\(a, b) -> odd b) $ summary\n (_, evens) = unzip $ filter (\\(a, b) -> even b) $ summary\n\nmain = do \n input <- getContents\n sequence_ $ map (putStrLn.show) $ concat $ solve.map read.words $ input"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [[Int]]\nsolve (n:xs) = [[length evens], evens, [length odds], odds]\n where \n summary = sortBy (\\(a,b) (c,d) -> compare a b) $ zip xs $ iterate (+1) 1\n (evens, odds) = split summary [] [] 1\n split [] es os _ = (es, os)\n split ((x, p):xs) es os i | even i = split xs (p:es) os $ i + 1\n | odd i = split xs es (p:os) $ i + 1\n\nmain = do \n input <- getContents\n sequence_ $ map (putStrLn.show) $ concat $ solve.map read.words $ input"}, {"source_code": "import Data.List\n\nsolve bs = foldl' makeChoice (0, [], 0, []) $ zip [1 .. ] $ sort bs\n where makeChoice (x, xs, y, ys) (i, a)\n | x <= y = (x + a, i : xs, y, ys)\n | otherwise = (x, xs, y + a, i : ys)\n\nmain = do _ <- getLine\n bs <- fmap (map read . words) getLine\n\n let (_, xs, _, ys) = solve bs\n\n putStrLn $ show $ length xs\n putStrLn $ unwords $ map show xs\n\n putStrLn $ show $ length ys\n putStrLn $ unwords $ map show ys"}, {"source_code": "import Data.List\n\nsolve bs = foldl' makeChoice (0, [], 0, []) $ zip [1 .. ] bs\n where makeChoice (x, xs, y, ys) (i, a)\n | x <= y = (x + a, i : xs, y, ys)\n | otherwise = (x, xs, y + a, i : ys)\n\nmain = do _ <- getLine\n bs <- fmap (map read . words) getLine\n\n let (_, xs, _, ys) = solve bs\n\n putStrLn $ show $ length xs\n putStrLn $ unwords $ map show xs\n\n putStrLn $ show $ length ys\n putStrLn $ unwords $ map show ys"}], "src_uid": "0937a7e2f912fc094cc4275fd47cd457"} {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Function\n\nmain = do\n n <- readLn :: IO Int\n as <- map (read :: String -> Int) . words <$> getLine\n m <- readLn :: IO Int\n bs <- map (read :: String -> Int) . words <$> getLine\n print $ length $ maximumBy (compare `on` head) $ group $ sort [y`div`x | x<-as, y <-bs, y`mod`x==0]", "positive_code": [{"source_code": "\nimport Prelude hiding (reads)\n\ncountMaximums :: [Int] -> Int\ncountMaximums [] = 0\ncountMaximums xs = length $ filter (== maximum xs) xs\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = countMaximums [div b a | a <- as, b <- bs, mod b a == 0]\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nmain :: IO ()\nmain = do\n as <- getLine >> reads\n bs <- getLine >> reads\n print $ solve as bs\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\nmain = do\n getLine\n as <- fmap (map read . words) getLine\n getLine\n bs <- fmap (map read . words) getLine\n print $ length $ last $ group $ sort $ catMaybes $ liftM2 solve as bs\nsolve a b | r == 0 = Just q\n | otherwise = Nothing\n where (q,r) = b `divMod` a\n"}, {"source_code": "import Data.List\nimport Data.Char\n \nsolve = length . head . group . reverse . sort\ns2i = foldl t 0 \n where t i c = i * 10 + digitToInt c\n \nmain = do \n ln <- getLine >> getLine >>= return . map s2i . words\n lm <- getLine >> getLine >>= return . map s2i . words\n let l = [ fst (j `quotRem` i) | i <- ln, j <- lm, snd (j `quotRem` i) == 0 ] in\n print (solve l)\n "}, {"source_code": "import Control.Applicative\n\nmain = do\n _ <- getLine\n as <- map read.words <$> getLine\n _ <- getLine\n bs <- map read.words <$> getLine\n let ints = [q|a<-as,b<-bs,let (q,r) = divMod b a,r==0]\n print $ length $ filter (maximum ints==) ints\n"}, {"source_code": "import Data.List\nmain = do\n n <- read `fmap` getLine :: IO Int\n a <- (map read . words) `fmap` getLine\n m <- read `fmap` getLine :: IO Int\n b <- (map read . words) `fmap` getLine\n print $ length $ last $ group $ sort [x `div` y | x <- b, y <- a, x `rem` y == 0]\n"}, {"source_code": "import Data.List\n\nsolve :: ([Int], [Int]) -> Int\nsolve (xs, ys) = length . last . group $ sort [y `div` x | x <- xs, y <- ys, y `mod` x == 0]\n\nreadInput :: IO ([Int], [Int])\nreadInput = do\n contents <- getContents\n let n:ns:m:ms:_ = lines contents\n xs = map read $ take (read n) $ words ns\n ys = map read $ take (read m) $ words ms\n return (xs, ys)\n\nshowOutput :: Int -> IO ()\nshowOutput r = do\n print r\n\nmain :: IO ()\nmain = do\n input <- readInput\n showOutput $ solve input\n"}, {"source_code": "import Control.Monad\n\n\nmain :: IO ()\nmain = do\n n <- getLine\n ns <- fmap (map read . words) getLine :: IO [Int]\n m <- getLine\n ms <- fmap (map read . words) getLine :: IO [Int]\n\n let a = [div x y | x <- ms, y <- ns, mod x y == 0]\n\n print $ length $ filter (maximum a == ) a\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\nparse = map (map read) . map words . lines\n\nsolve :: [[Int]] -> Int\nsolve [_, as, _, bs] =\n let\n bestRatio = maximum [b `div` a | b <- bs, a <- as, b `mod` a == 0] \n in\n length [8 | b <- bs, a <- as, b `mod` a == 0, b `div` a == bestRatio] \n\n\npresent = show\n\nmain = interact $ present . solve . parse\n\n"}, {"source_code": "main = do\n getLine\n a <- fmap (map read . words) getLine\n getLine\n b <- fmap (map read . words) getLine\n print $ gao a b\n where\n gao a b = length $ filter (==maximum c) c\n where\n c = [div j i | i <- a, j <- b, mod j i == 0]\n"}, {"source_code": "combination::[Int]->[Int]->[(Int,Int)]\ncombination [] _ = []\ncombination (x:xs) ys = [(x,yy) | yy <- ys] ++ combination xs ys\n\ngetMax::[(Int,Int)] -> Int\ngetMax [] = 0\ngetMax (x:xs)\n | (((snd x) `mod` (fst x)) == 0) = max ((snd x) `div` (fst x)) (getMax xs)\n | otherwise = max 0 (getMax xs)\n\ncount::[(Int,Int)] -> Int -> Int\ncount xs maxi = sum [1|x <- xs, ((snd x) `mod` (fst x)) == 0, ((snd x) `div` (fst x)) == maxi]\n\nmain = do\n _ <- getLine\n arg1 <- getLine\n let xs = map (read::String->Int) $ words arg1\n _ <- getLine\n arg2 <- getLine\n let ys = map (read::String->Int) $ words arg2\n let comb = combination xs ys\n let maxi = getMax comb\n putStrLn(show $ count comb maxi)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts\n getLine\n bs <- getInts\n\n let\n m = maximum [b`div`a | b <- bs, a <- as, b`mod`a == 0]\n c = length $ [(a, b) | b <- bs, a <- as, b`mod`a == 0, b`div`a == m]\n\n print c\n"}, {"source_code": "#! /usr/bin/runhaskell\nimport Data.List\nmain = do\n n <- readLn :: IO Int\n str <- getLine\n let a = map read (words str) :: [Int]\n m <- readLn :: IO Int\n str <- getLine\n let b = map read (words str) :: [Int]\n let list = f b a\n let m = maximum list \n c = length $ filter (==m) list\n in print c\n \n \nf b a = \n if b == []\n then []\n else list ++ f (tail b) a\n where hb = head b\n list = map (\\x -> hb `div` x) $ filter (\\x -> hb `mod` x == 0) a\n \n"}, {"source_code": "import Control.Applicative\nimport Data.List\n-- Reduction ratio\nrratio :: Int -> Int -> Maybe Int\nrratio ifwd jbck =\n case m of 0 -> Just d\n _ -> Nothing\n where (d, m) = jbck `divMod` ifwd\n\n\nmaxby :: Maybe Int -> Maybe Int -> Ordering\nmaxby Nothing Nothing = EQ\nmaxby Nothing _ = LT\nmaxby _ Nothing = GT\nmaxby (Just x) (Just y) = compare x y\n\ncountmax :: [Int] -> [Int] -> Int\ncountmax ai bj =\n case mr of Nothing -> 0\n _ -> length $ filter (\\x -> x == mr) rx\n where rx = rratio <$> ai <*> bj\n mr = maximumBy maxby rx\n\ngetInt x = read x :: Int\n\nmain = do\n n <- getLine\n ai <- fmap (map getInt . words) getLine\n m <- getLine\n bj <- fmap (map getInt . words) getLine\n print $ countmax ai bj\n\n{-\n\u0426\u0435\u043f\u043d\u0430\u044f \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0412\u0430\u0441\u0438\u043d\u043e\u0433\u043e \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430 \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 \u0434\u0432\u0443\u0445 \u0447\u0430\u0441\u0442\u0435\u0439: n \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u0435\u043a \u0437\u0430\u043a\u0440\u0435\u043f\u043b\u0435\u043d\u044b \u043d\u0430 \u043e\u0441\u0438 \u043f\u0435\u0434\u0430\u043b\u0435\u0439, \u0430 m \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u0435\u043a \u2014 \u043d\u0430 \u043e\u0441\u0438 \u0437\u0430\u0434\u043d\u0435\u0433\u043e \u043a\u043e\u043b\u0435\u0441\u0430. \u0421 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0446\u0435\u043f\u0438 \u0432\u0440\u0430\u0449\u0435\u043d\u0438\u0435 \u043f\u0435\u0434\u0430\u043b\u0435\u0439 \u043f\u0435\u0440\u0435\u0434\u0430\u0435\u0442\u0441\u044f \u043d\u0430 \u0437\u0430\u0434\u043d\u0435\u0435 \u043a\u043e\u043b\u0435\u0441\u043e.\n\n\u0418\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e i-\u0430\u044f \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u043a\u0430 \u043d\u0430 \u043e\u0441\u0438 \u043f\u0435\u0434\u0430\u043b\u0435\u0439 \u0438\u043c\u0435\u0435\u0442 ai (0\u2009<\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an) \u0437\u0443\u0431\u044c\u0435\u0432, \u0430 j-\u0430\u044f \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u043a\u0430 \u043d\u0430 \u043e\u0441\u0438 \u0437\u0430\u0434\u043d\u0435\u0433\u043e \u043a\u043e\u043b\u0435\u0441\u0430 \u0438\u043c\u0435\u0435\u0442 bj (0\u2009<\u2009b1\u2009<\u2009b2\u2009<\u2009...\u2009<\u2009bm) \u0437\u0443\u0431\u044c\u0435\u0432. \u041b\u044e\u0431\u0430\u044f \u043f\u0430\u0440\u0430 (i,\u2009j) (1\u2009\u2264\u2009i\u2009\u2264\u2009n; 1\u2009\u2264\u2009j\u2009\u2264\u2009m) \u043d\u0430\u0437\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0435\u0439 \u0438 \u0437\u0430\u0434\u0430\u0435\u0442 \u043d\u043e\u043c\u0435\u0440\u0430 \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u0435\u043a, \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0432 \u0434\u0430\u043d\u043d\u044b\u0439 \u043c\u043e\u043c\u0435\u043d\u0442 \u0437\u0430\u043a\u0440\u0435\u043f\u043b\u0435\u043d\u0430 \u0446\u0435\u043f\u044c. \u0414\u043b\u044f \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0438 (i,\u2009j) \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0440\u0430\u0432\u043d\u043e \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u0435 bj / ai.\n\n\u0422\u0430\u043a \u043a\u0430\u043a \u0412\u0430\u0441\u0435 \u043d\u0440\u0430\u0432\u044f\u0442\u0441\u044f \u0446\u0435\u043b\u044b\u0435 \u0447\u0438\u0441\u043b\u0430, \u043e\u043d \u0445\u043e\u0447\u0435\u0442 \u043d\u0430\u0439\u0442\u0438 \u0442\u0430\u043a\u0438\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0438 (i,\u2009j), \u0447\u0442\u043e \u0438\u0445 \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u044b\u0435 \u0447\u0438\u0441\u043b\u0430 \u0446\u0435\u043b\u044b\u0435. \u0421 \u0434\u0440\u0443\u0433\u043e\u0439 \u0441\u0442\u043e\u0440\u043e\u043d\u044b, \u0412\u0430\u0441\u0435 \u043d\u0440\u0430\u0432\u0438\u0442\u0441\u044f \u0431\u044b\u0441\u0442\u0440\u0430\u044f \u0435\u0437\u0434\u0430, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0441\u0440\u0435\u0434\u0438 \u0432\u0441\u0435\u0445 \u00ab\u0446\u0435\u043b\u043e\u0447\u0438\u0441\u043b\u0435\u043d\u043d\u044b\u0445\u00bb \u043f\u0435\u0440\u0435\u0434\u0430\u0447 (i,\u2009j), \u043e\u043d \u0445\u043e\u0447\u0435\u0442 \u0432\u044b\u0431\u0440\u0430\u0442\u044c \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0438 \u0441 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u043c \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u044b\u043c \u0447\u0438\u0441\u043b\u043e\u043c. \u041f\u043e\u043c\u043e\u0433\u0438\u0442\u0435 \u0435\u043c\u0443 \u043d\u0430\u0439\u0442\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0442\u0430\u043a\u0438\u0445 \u043f\u0435\u0440\u0435\u0434\u0430\u0447.\n\n\u0412 \u0437\u0430\u0434\u0430\u0447\u0435 \u0434\u0440\u043e\u0431\u044c bj / ai \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u0432 \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u0447\u0438\u0441\u043b\u0430\u0445, \u0442\u043e \u0435\u0441\u0442\u044c \u043e\u043a\u0440\u0443\u0433\u043b\u0435\u043d\u0438\u0435 \u043d\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0441\u044f.\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u0435\u043a \u043d\u0430 \u043e\u0441\u0438 \u043f\u0435\u0434\u0430\u043b\u0435\u0439 \u0432\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u0430. \u0412\u043e \u0432\u0442\u043e\u0440\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b n \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) \u0432 \u043f\u043e\u0440\u044f\u0434\u043a\u0435 \u0441\u0442\u0440\u043e\u0433\u043e\u0433\u043e \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430\u043d\u0438\u044f.\n\n\u0412 \u0442\u0440\u0435\u0442\u044c\u0435\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u043e \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e m (1\u2009\u2264\u2009m\u2009\u2264\u200950) \u2014 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0437\u0432\u0435\u0437\u0434\u043e\u0447\u0435\u043a \u043d\u0430 \u043e\u0441\u0438 \u0437\u0430\u0434\u043d\u0435\u0433\u043e \u043a\u043e\u043b\u0435\u0441\u0430. \u0412 \u0447\u0435\u0442\u0432\u0435\u0440\u0442\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u043f\u0438\u0441\u0430\u043d\u044b m \u0446\u0435\u043b\u044b\u0445 \u0447\u0438\u0441\u0435\u043b b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009104) \u0432 \u043f\u043e\u0440\u044f\u0434\u043a\u0435 \u0441\u0442\u0440\u043e\u0433\u043e\u0433\u043e \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430\u043d\u0438\u044f.\n\n\u0413\u0430\u0440\u0430\u043d\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u0445\u043e\u0442\u044f \u0431\u044b \u043e\u0434\u043d\u0430 \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0430 (i,\u2009j), \u0447\u0442\u043e \u0435\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u2014 \u0446\u0435\u043b\u043e\u0435. \u0427\u0438\u0441\u043b\u0430 \u0432 \u0441\u0442\u0440\u043e\u043a\u0430\u0445 \u0440\u0430\u0437\u0434\u0435\u043b\u044f\u044e\u0442\u0441\u044f \u043f\u0440\u043e\u0431\u0435\u043b\u0430\u043c\u0438.\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u00ab\u0446\u0435\u043b\u043e\u0447\u0438\u0441\u043b\u0435\u043d\u043d\u044b\u0445\u00bb \u043f\u0435\u0440\u0435\u0434\u0430\u0447, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u043c\u0435\u044e\u0442 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0441\u0440\u0435\u0434\u0438 \u0432\u0441\u0435\u0445 \u00ab\u0446\u0435\u043b\u043e\u0447\u0438\u0441\u043b\u0435\u043d\u043d\u044b\u0445\u00bb \u043f\u0435\u0440\u0435\u0434\u0430\u0447.\n\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2\n4 5\n3\n12 13 15\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n2\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n4\n1 2 3 4\n5\n10 11 12 13 14\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n1\n\n\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435\n\n\u0412 \u043f\u0435\u0440\u0432\u043e\u043c \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0446\u0435\u043b\u043e\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0440\u0430\u0432\u043d\u043e 3. \u0421\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044e\u0442 \u0434\u0432\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u043c\u0435\u044e\u0442 \u0442\u0430\u043a\u043e\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u043e\u0447\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e. \u0414\u043b\u044f \u043e\u0434\u043d\u043e\u0439 \u0438\u0437 \u043d\u0438\u0445 a1\u2009=\u20094,\u2009b1\u2009=\u200912, \u0430 \u0434\u043b\u044f \u0434\u0440\u0443\u0433\u043e\u0439 a2\u2009=\u20095,\u2009b3\u2009=\u200915.\n-}"}, {"source_code": "import Control.Applicative\n\nsolve a b = length [ 1 | aa <- a, bb <- b, bb `mod` aa == 0, bb `div` aa == mx ]\n where mx = foldl max 0 [ bb `div` aa | aa <- a, bb <- b, bb `mod` aa == 0 ]\n\nmain = do\n _ <- getLine\n a <- map read <$> (words <$> getLine)\n _ <- getLine\n b <- map read <$> (words <$> getLine)\n print $ solve a b"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Control.Monad\nmain = do\n getLine\n as <- fmap (map read . words) getLine\n getLine\n bs <- fmap (map read . words) getLine\n print $ maximum $ catMaybes $ liftM2 solve as bs\nsolve a b | r == 0 = Just q\n | otherwise = Nothing\n where (q,r) = b `divMod` a\n"}, {"source_code": "import Control.Monad\n\n\n--main :: IO ()\nmain = do\n n <- getLine\n ns <- fmap (map read . words) getLine :: IO [Int]\n m <- getLine\n ms <- fmap (map read . words) getLine :: IO [Int]\n\n let a = [div x y | x <- ms, y <- ns, mod x y == 0]\n\n return $ length $ filter (maximum a == ) a\n"}], "src_uid": "102667eaa3aee012fef70f4192464674"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n,q],as] <- replicateM 2 ri\r\n return (q,as)\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve (q,as) = ans\r\n where\r\n minQs = reverse . tail . scanl nextQ 0 . reverse $ as\r\n ans = map snd . tail . scanl nextBit (q,'_') $ minQs `zip` as\r\n\r\nnextQ q0 a1 | q0 >= a1 = q0\r\n | otherwise = q0 +1\r\n\r\nnextBit (q0,_) (mq,ai)\r\n | isF && isL = (q0 , '0')\r\n | isF = (q0 , '1')\r\n | isL = (q0-1, '1')\r\n | otherwise = (q0 , '1')\r\n where\r\n isF = (q0 < mq)\r\n isL = (q0 < ai)\r\n", "positive_code": [{"source_code": "module Main where\n\nsolve :: Integer -> [Integer] -> String\nsolve n a = reverse $ solve' 0 n (reverse a) where\n solve' _ _ [] = []\n solve' a b (x : xs)\n | x <= a = '1' : solve' a b xs\n | otherwise = if a < b then '1' : solve' (a + 1) b xs else '0' : solve' a b xs\n\nfor :: Integer -> IO () -> IO ()\nfor n action = if n == 1 then action else action *> for (n - 1) action\n\nmain = do\n times <- read <$> getLine\n for times $ do\n n <- (read . (!!1) . words) <$> getLine\n list <- fmap (read) <$> words <$> getLine\n putStrLn $ solve n list\n"}], "negative_code": [], "src_uid": "62a90c34a7df8fb56419aa5a1cf2a75b"} {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n getLine\r\n s <- transpose <$> sequence [getLine, getLine]\r\n let go (\"01\":xs) = 2 + go xs\r\n go (\"10\":xs) = 2 + go xs\r\n go (\"00\":\"11\":xs) = 2 + go xs\r\n go (\"11\":\"00\":xs) = 2 + go xs\r\n go (\"00\":xs) = 1 + go xs\r\n go (\"11\":xs) = go xs\r\n go ~[] = 0\r\n print $ go s\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\n\ncalc :: [(Char,Char)] -> Int\ncalc [] = 0\ncalc [('0','1')] = 2\ncalc [('1','0')] = 2\ncalc [('0','0')] = 1\ncalc [('1','1')] = 0\ncalc (('0','1'):xs) = 2+(calc xs)\ncalc (('1','0'):xs) = 2+(calc xs)\ncalc (('0','0'):('1','1'):xs) = 2+(calc xs)\ncalc (('0','0'):xs) = 1+(calc xs)\ncalc (('1','1'):('0','0'):xs) = 2+(calc xs)\ncalc (('1','1'):xs) = (calc xs)\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line1 <- getLine\n line2 <- getLine\n print $ calc $ zip line1 line2\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> chunksOf 3 >>> map (tail >>> solve >>> show) >>> unlines\n\ndata State = SeenZero | SeenOne | None\n\nsolve :: [String] -> Int\nsolve [as, bs] = sum . map fst . scanl upd (0, None) $ zipWith val as bs ++ [3]\n where\n upd (_, st) v = compute v st\n\n compute 0 SeenZero = (1, SeenZero)\n compute 0 SeenOne = (2, None)\n compute 0 None = (0, SeenZero)\n compute 1 SeenZero = (2, None)\n compute 1 _ = (0, SeenOne)\n compute 2 SeenZero = (3, None)\n compute 2 _ = (2, None)\n compute _ SeenZero = (1, None)\n compute _ _ = (0, None)\n\n val '0' '0' = 0\n val '1' '1' = 1\n val _ _ = 2\n\n-- Template\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[_n] <- getInts 1\n ~[p, q] <- getNext 2\n let\n s = P.zip p q\n has tar (c1, c2) = elem tar [c1, c2]\n shouldCut :: Bool -> Bool -> (Char, Char) -> Bool\n shouldCut False _ _ = False\n shouldCut True False c = has '0' c\n shouldCut True True _ = True\n mex :: Bool -> Bool -> Int\n mex False _ = 0\n mex True False = 1\n mex True True = 2\n optCut = let\n go acc has0 has1 [] = acc + mex has0 has1\n go acc has0 has1 (c : cs) = if shouldCut has0 has1 c\n then go (acc + mex has0 has1) False False (c : cs)\n else let\n (c1, c2) = c\n in go acc\n (has0 || c1 == '0' || c2 == '0')\n (has1 || c1 == '1' || c2 == '1')\n cs\n in go 0 False False\n pure $ putInts [optCut s]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "6c4445ee23fedcb913ed3de1beacc099"} {"source_code": "q s(k:w)=sum$zipWith(*)[1..]$(map(\\c->w!!(fromEnum c - fromEnum 'a'))s)++replicate k(maximum w)\nz(s:l)=q s(map read l)\nmain=interact$show.z.words\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n xs <- map(\\c->fromEnum c - 97).filter(\\c->'a'<=c&&c<='z') <$> getLine\n k <- readLn\n arr <- listArray(0,25).map read.words <$> getLine\n print $ solve xs k arr\n\nsolve :: [Int] -> Int -> UArray Int Int -> Int\nsolve xs k arr =sum $ zipWith (\\x i->unsafeAt arr x * i) xs [1..len] ++ map (wmax*) [len+1..len+k] \n where\n !len = length xs\n !wmax = maximum [unsafeAt arr i|i<-[0..25]]\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Function\nimport qualified Data.IntSet as IS\nimport Text.Printf (printf)\nimport Control.Monad\n\nsolve :: String -> Int -> [Int] -> Int\nsolve s k ws = f (s ++ replicate k c)\n where\n f s = sum $ map (\\(c, i) -> fromJust (lookup c alist) * i) (zip s [1..])\n alist = zip ['a'..'z'] ws\n (c, w) = maximumBy (compare `on` snd) $ alist\n\nmain :: IO ()\nmain = do\n s <- getLine\n k <- readLn\n ws <- fmap (map read . words) getLine\n print $ solve s k ws\n"}, {"source_code": "\nimport Data.Char\n\nmain = interact $ show . sum . zipWith (*) [1..] . solve . words\n\nsolve par = (map (xs!!) $ map (subtract (ord 'a')) (map ord str) ) ++ (replicate k $ maximum xs)\n where str = head par\n k = read $ par !! 1\n xs = map read (drop 2 par)\n"}, {"source_code": "import Data.Char\n\nmain = interact $ show . sum . zipWith (*) [1..] . sol . words\n\nsol (s:k:xsp) = (map (\\x -> xs !! (ord x - ord 'a')) s) ++ (replicate (read k) $ maximum xs)\n where xs = map read xsp\n "}, {"source_code": "import Data.Char\n\nmain :: IO()\nmain = print . solve . words =<< getContents\n\nsolve :: [String] -> Int\nsolve (s:sk:sw) = let k = read sk\n w = map read sw\n i = snd . maximum $ zip w [0..]\n c = chr (i + (ord 'a'))\n f = s ++ (concat [[c] | r <- [1..k]])\n in solve' f 1 w\n where\n solve' :: String -> Int -> [Int] -> Int\n solve' [] _ _ = 0\n solve' (f:fs) i w = (w !! ((ord f) - (ord 'a'))) * i + (solve' fs (i + 1) w)\n"}, {"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve' . words\nsolve' (s:k:ws) = solve s (readInt k) (map readInt ws)\n\nsolve s k ws = sum $ zipWith (*) [1..] $ (map (\\c -> ws !! (ord c)) s) ++ replicate k (maximum ws)\n\twhere ord c = fromEnum c - 97\n\n"}, {"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve' . words\nsolve' (s:k:ws) = solve s (readInt k) (map readInt ws)\n\ndot [] _ = 0\ndot _ [] = 0\ndot (x:xs) (y:ys) = dot xs ys + x*y\n\ncalValue xs = dot xs [1..]\n\nsolve s k ws = calValue $ (map (\\c -> ws !! (ord c)) s) ++ replicate k (maximum ws)\n\twhere ord c = fromEnum c - 97\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\ngetint :: IO Int\ngetint = head <$> getints\n\ngetints :: IO [Int]\ngetints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\ngetnums :: Num a => IO [a]\ngetnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine\n\ngetstr = getLine\n\ninit_val n [] mp = 0\ninit_val n (c:str) mp =\n n * k + (init_val (n + 1) str mp)\n where k = fromJust $ Map.lookup c mp\n\nmain = do\n str <- getstr\n k <- getint\n values <- getints\n let mp = Map.fromList $ zip ['a'..'z'] values\n init = init_val 1 str mp\n len = length str\n mx = maximum values\n res = init + (sum $ map (* mx) [len + 1..len + k])\n putStrLn (show res)"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Array\n\nmain = do\n s <- map ((subtract 97).ord) <$> getLine\n k <- readLn :: IO Int\n ws <- map (read :: String -> Int).words <$> getLine\n let as = array (0,25) $ zip [0..] ws\n m = maximum ws\n w = map (as!) s\n print $ sum $ zipWith (*) [1..] $ w ++ (replicate k m) \n\n\n"}, {"source_code": "import Data.Char (ord)\nmain :: IO ()\nmain = getLine >>= \\s -> readLn >>= \\k -> getContents >>= print . solve s k . map read . words\n\nsolve :: String -> Int -> [Int] -> Int\nsolve s k ws = sum $ zipWith (*) [1..length s + k] (map ((ws!!) . subtract (ord 'a') . ord) s ++ repeat (maximum ws))\n"}, {"source_code": "import Data.Char\nmain=getLine>>= \\s->getContents>>=print.f s.map read.words\nf s (k:x)=sum$zipWith(*)[1..length s+k](map((x!!).subtract(ord 'a').ord)s++repeat(maximum x))\n"}, {"source_code": "import Data.Char (ord)\n\nmain :: IO ()\nmain = getLine >>= \\s -> readLn >>= \\k -> getContents >>= print . solve s k . map read . words\n\nsolve :: String -> Int -> [Int] -> Int\nsolve s k ws = sum $ zipWith (*) [1..] (map (\\c -> ws !! (ord c - ord 'a')) s ++ replicate k (maximum ws))\n"}, {"source_code": "main = do\n s <- getLine\n k <- readLn\n ws <- map read . words <$> getLine\n let (_,best) = maximum (zip ws ['a'..])\n print $ sum $ zipWith (*) [1..] $\n map ((ws !!) . (subtract (fromEnum 'a') . fromEnum)) $\n s ++ replicate k best\n"}], "negative_code": [{"source_code": "readInt x = read x :: Int\nmain = interact $ show . solve' . words\nsolve' (s:k:ws) = solve s (readInt k) (map readInt ws)\n\nsolve s k ws = zipWith (*) [1..] $ (map (\\c -> ws !! (ord c)) s) ++ replicate k (maximum ws)\n\twhere ord c = fromEnum c - 97\n\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Array\n\nmain = do\n s <- map ((subtract 97).ord) <$> getLine\n k <- readLn :: IO Int\n ws <- map (read :: String -> Int).words <$> getLine\n let as = array (0,25) $ zip [0..] ws\n m = maximum ws\n w = map (as!) s\n print $ sum $ zipWith (*) [1..] $ sort $ init w ++ (replicate k m) ++ [last w]\n\n\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\nimport Data.Array\n\nmain = do\n s <- map ((subtract 97).ord) <$> getLine\n k <- readLn :: IO Int\n ws <- map (read :: String -> Int).words <$> getLine\n let as = array (0,25) $ zip [0..] ws\n m = maximum ws\n w = map (as!) s\n print $ sum $ zipWith (*) [1..] $ sort $ w ++ (replicate k m)\n\n\n"}], "src_uid": "85f90533a9840e944deef9f3b4229cb8"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[_, k] <- readInts\r\n xs <- readInts\r\n let xs' = reverse $ sort xs\r\n (as, xs'') = splitAt k xs'\r\n (bs, xs''') = splitAt k xs''\r\n print $ sum (map fromEnum $ zipWith (==) as bs) + sum xs'''\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "-- https://codeforces.com/contest/1618/problem/D\nimport Control.Monad (replicateM)\nimport Data.List (sort)\n\nanswer :: Int -> Int -> [Int] -> Int\nanswer n k l = sum (zipWith div numerators denominators) + sum remain where\n denominators = take k l\n numerators = take k $ drop k l\n remain = drop (2*k) l\n\nmain = getLine >>= flip replicateM run . read\nrun = do\n [n, k] <- (read <$>) . words <$> getLine\n numbers <- reverse . sort . (read <$>) . words <$> getLine\n print $ answer n k numbers"}], "negative_code": [], "src_uid": "f48d55c60c12136979fe6db1e15c6053"} {"source_code": "{-# LANGUAGE TupleSections #-}\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.List ( sortOn )\r\n\r\nevensThenOdds = sortOn (`mod` 2)\r\n\r\npairs (x : xs) = map (x,) xs ++ pairs xs\r\npairs _ = []\r\n\r\nmaxGoodIndices :: [Int] -> Int\r\nmaxGoodIndices = length . filter isGood . pairs . evensThenOdds\r\n where isGood (a, b) = gcd a (2 * b) > 1\r\n\r\nmain = do n <- read <$> getLine\r\n replicateM_ n (getLine >> getLine >>= print . solve)\r\n where solve = maxGoodIndices . map read . words\r\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n a <- readMany :: IO [Int]\r\n print $ sum [1 | (x:ys) <- tails $ sortOn odd a, y <- ys, gcd x (2 * y) > 1]\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n a <- readMany :: IO [Int]\r\n print $ sum $ [fromEnum $ gcd x (2 * y) > 1 | (x:ys) <- tails $ sortOn odd a, y <- ys]\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nfori [x] = 0\r\nfori (x:xs) = forj x xs + fori xs \r\n\r\nforj x [] = 0\r\nforj x (y:xs) = forj x xs + if (gcd x (2*y) > 1) then 1 else 0\r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let o = [x|x<-a, odd x]\r\n e = [x|x<-a, even x]\r\n let b = (reverse $ sort e) ++ (reverse $ sort o)\r\n print $ fori b\r\n\r\nmain = do\r\n t<-readLn :: IO Int \r\n replicateM_ t printS"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List (tails)\r\n\r\nsolve a = length [ 1 | (x:rest) <- tails a , y <- rest, gcd x (2*y) > 1 ]\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t $ do\r\n n <- getLine\r\n a <- map read . words <$> getLine\r\n print $ solve $ filter even a ++ filter odd a\r\n"}, {"source_code": "import Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> chunksOf 2\r\n >>> map (last >>> words >>> map read >>> solve >>> show) >>> unlines\r\n\r\ncount :: (a -> Bool) -> [a] -> Int\r\ncount f = length . filter f\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs = (`div` 2) $ count id [True | x <- xs, y <- xs, even x || even y || gcd x y > 1] - count (> 1) xs\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n BS.getLine\r\n xs <- sortOn (`mod` 2) . map parseInt . BS.words <$> BS.getLine\r\n print $ sum [1 | (x:ys) <- tails xs, y <- ys, gcd x (2*y) > 1]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\nimport Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\tgetLine\r\n\tas <- readInts\r\n\tprint $ sum $ do\r\n\t\t( a1, i ) <- zip as [ 0 .. ]\r\n\t\t( a2, j ) <- zip as [ 0 .. ]\r\n\t\tguard $ i < j\r\n\t\treturn $ if 1 < gcd a1 a2 || ( a1 `mod` 2 == 0 || a2 `mod` 2 == 0 )\r\n\t\t\tthen 1\r\n\t\t\telse 0"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- (\\(s1, s2) -> s1 ++ s2) . partition even <$> getInts\n let ts = take n $ tails as\n result = sum[1 | (x : xs) <- ts, y <- xs, gcd x (2 * y) > 1]\n return $ intDec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "import Control.Monad ( replicateM_ )\r\n\r\nevens = filter even\r\nodds = filter odd\r\nevensThenOdds = (++) . evens <*> odds\r\n\r\npairsWith f (x : xs) = map (f x) xs ++ pairsWith f xs\r\npairsWith _ _ = []\r\n\r\nmaxGoodIndices :: [Int] -> Int\r\nmaxGoodIndices = length . filter id . pairsWith isGood . evensThenOdds\r\n where isGood a b = gcd a (2 * b) > 1\r\n\r\nmain = do n <- read <$> getLine\r\n replicateM_ n (getLine >> getLine >>= print . solve)\r\n where solve = maxGoodIndices . map read . words"}], "negative_code": [{"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nfori [x] = 0\r\nfori (x:xs) = forj x xs + fori xs \r\n\r\nforj x [] = 0\r\nforj x (y:xs) = forj x xs + if (gcd x (2*y) > 1) then 1 else 0\r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let b = reverse $ sort a \r\n print $ fori b\r\n\r\nmain = do\r\n t<-readLn :: IO Int \r\n replicateM_ t printS"}], "src_uid": "d638f524fe07cb8e822b5c6ec3fe8216"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] && b == []) = []\r\n | (a == []) = [head b]\r\n | (b == []) = [head a]\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else\r\n (if ((length ll) == 2) then ll else \r\n (if ((length rr) == 2) then rr else \r\n (if ((length ll) == 1) then ll else \r\n (if ((length rr) == 1) then rr else \r\n (if (ar /= []) then [head ar] else\r\n (if (bl /= []) then [head bl] else\r\n (if (al /= []) then [head al] else\r\n (if (br /= []) then [head br] else\r\n []\r\n ))))))))))\r\n | otherwise = if (((length lr) == 2) || (length lr) > (length rl)) then lr else rl\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n lr = (gg al br k (div i 2))\r\n rl = (gg ar bl k (div i 2))\r\n ll = (gg al bl k (div i 2))\r\n rr = (gg ar br k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\nimport Control.Monad\r\nimport Data.Bits\r\nimport Data.Foldable\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ndata MaxLenList = MaxLenList { len :: !Int, vals :: [Int] }\r\n\r\ninstance Semigroup MaxLenList where\r\n a <> b = if len a >= len b then a else b\r\n\r\ninstance Monoid MaxLenList where\r\n mempty = MaxLenList 0 []\r\n\r\ndata Trie = Leaf { getList :: !MaxLenList }\r\n | Node { getList :: !MaxLenList, l_ :: Trie, r_ :: Trie }\r\n\r\naddToList :: Int -> MaxLenList -> MaxLenList\r\naddToList v (MaxLenList l vs) = MaxLenList (l + 1) (v:vs)\r\n\r\nhighestBit :: Int\r\nhighestBit = 29\r\n\r\nempty :: Trie\r\nempty = foldl' (const . join (Node mempty)) (Leaf mempty) [0..highestBit]\r\n\r\nsetMax :: Int -> MaxLenList -> Trie -> Trie\r\nsetMax x v' = go highestBit where\r\n go _ (Leaf v) = Leaf (v <> v')\r\n go i (Node v l r)\r\n | x `testBit` i = Node (v <> v') l (go (i - 1) r)\r\n | otherwise = Node (v <> v') (go (i - 1) l) r\r\n\r\ngetMax :: Int -> Int -> Trie -> MaxLenList\r\ngetMax k x = go highestBit where\r\n go _ (Leaf v) = v\r\n go i (Node _ l r) = case (k `testBit` i, x `testBit` i) of\r\n (False, False) -> go (i - 1) l <> getList r\r\n (False, True) -> getList l <> go (i - 1) r\r\n (True, False) -> go (i - 1) r\r\n (True, True) -> go (i - 1) l\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[_, k] <- readInts\r\n as <- sort . flip zip [1 :: Int ..] <$> readInts\r\n let f t (ai, i) = (t', best) where\r\n best = addToList i $ getMax k ai t\r\n t' = setMax ai best t\r\n ans = foldMap' id $ snd $ mapAccumL f empty as\r\n putStr $ unlines $ if len ans >= 2\r\n then [show $ len ans, unwords $ map show $ vals ans]\r\n else [\"-1\"]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] && b == []) = []\r\n | (a == []) = [head b]\r\n | (b == []) = [head a]\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else \r\n (if (ar /= []) then [head ar] else\r\n (if (bl /= []) then [head bl] else\r\n (if (al /= []) then [head al] else\r\n (if (br /= []) then [head br] else\r\n []\r\n ))))))\r\n | otherwise = if (((length lr) == 2) || (length lr) > (length rl)) then lr else rl\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n lr = (gg al br k (div i 2))\r\n rl = (gg ar bl k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n -- (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\n-- 1111\r\n-- 2 8\r\n-- 2 14\r\n\r\n--- 1111\r\n\r\n--- 110101\r\n \r\n -- 00\r\n -- 01\r\n -- 10\r\n -- 11\r\n\r\n--- 1\r\n--- \r\n\r\n-- 0010\r\n-- 1110\r\n\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] && b == []) = []\r\n | (a == []) = [head b]\r\n | (b == []) = [head a]\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else \r\n (if (ar /= []) then [head ar] else\r\n (if (bl /= []) then [head bl] else\r\n (if (al /= []) then [head al] else\r\n (if (br /= []) then [head br] else\r\n []\r\n ))))))\r\n | otherwise = if ((length lr == 2) || (length lr) > (length rl)) then lr else rl\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n lr = (gg al br k (div i 2))\r\n rl = (gg ar bl k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n -- (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\n-- 1111\r\n-- 2 8\r\n-- 2 14\r\n\r\n--- 1111\r\n\r\n--- 110101\r\n \r\n -- 00\r\n -- 01\r\n -- 10\r\n -- 11\r\n\r\n--- 1\r\n--- \r\n\r\n-- 0010\r\n-- 1110\r\n\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] && b == []) = []\r\n | (a == []) = [head b]\r\n | (b == []) = [head a]\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else []))\r\n | otherwise = if ((length lr == 2) || (length lr) > (length rl)) then lr else rl\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n lr = (gg al br k (div i 2))\r\n rl = (gg ar bl k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n -- (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\n-- 1111\r\n-- 2 8\r\n-- 2 14\r\n\r\n--- 1111\r\n\r\n--- 110101\r\n \r\n -- 00\r\n -- 01\r\n -- 10\r\n -- 11\r\n\r\n--- 1\r\n--- \r\n\r\n-- 0010\r\n-- 1110\r\n\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] && b == []) = []\r\n | (a == []) = [head b]\r\n | (b == []) = [head a]\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else []))\r\n | otherwise = if (lr /= []) then lr else rl\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n lr = (gg al br k (div i 2))\r\n rl = (gg ar bl k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n -- (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\n-- 1111\r\n-- 2 8\r\n-- 2 14\r\n\r\n--- 1111\r\n\r\n--- 110101\r\n \r\n -- 00\r\n -- 01\r\n -- 10\r\n -- 11\r\n\r\n--- 1\r\n--- \r\n\r\n-- 0010\r\n-- 1110\r\n\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] || b == []) = []\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else []))\r\n | otherwise = if (lr /= []) then lr else rl\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n lr = (gg al br k (div i 2))\r\n rl = (gg ar bl k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n -- (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\n-- 1111\r\n-- 2 8\r\n-- 2 14\r\n\r\n--- 1111\r\n\r\n--- 110101\r\n \r\n -- 00\r\n -- 01\r\n -- 10\r\n -- 11\r\n\r\n--- 1\r\n--- \r\n\r\n-- 0010\r\n-- 1110\r\n\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n-- 1000\r\n\r\ngg a b k i | (a == [] || b == []) = []\r\n | i == 0 = [head a] ++ [head b]\r\n | (((.&.) k i) == 0) = (if ((al /= []) && (br /= [])) then ([head al] ++ [head br]) else\r\n (if ((ar /= []) && (bl /= [])) then ([head ar] ++ [head bl]) else []))\r\n | otherwise = if (gl /= []) then gl else gr\r\n where \r\n al = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n ar = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n bl = [x | x <- b, ((.&.) (fst x) i) /= 0]\r\n br = [x | x <- b, ((.&.) (fst x) i) == 0]\r\n gl = (gg al br k (div i 2))\r\n gr = (gg al br k (div i 2))\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = gg l r k (div i 2)\r\n -- (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\n-- 1111\r\n-- 2 8\r\n-- 2 14\r\n\r\n--- 1111\r\n\r\n--- 110101\r\n \r\n -- 00\r\n -- 01\r\n -- 10\r\n -- 11\r\n\r\n--- 1\r\n--- \r\n\r\n-- 0010\r\n-- 1110\r\n\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\n\r\nimport Data.List\r\nimport Data.Bits\r\n-- import Data.Vector.Unboxed\r\nimport qualified Data.Map as M\r\n\r\n\r\nrev :: Int -> State [Int] ()\r\nrev k = do\r\n ~(sp, ss) <- splitAt k <$> get\r\n put (reverse sp ++ ss)\r\n\r\nsolve :: Int -> State [Int] [Int]\r\nsolve 1 = pure []\r\nsolve n = do\r\n ~(Just npos) <- elemIndex n <$> get\r\n rev (npos + 1)\r\n ~(Just ppos) <- elemIndex (n-1) <$> get\r\n rev ppos\r\n rev (ppos + 2)\r\n rev 3\r\n rev n\r\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\r\n\r\n\r\nff a k i | (i == 0 || (length a) <= 1) = a\r\n | (((.&.) k i) == 0) = (ff l k (div i 2)) ++ ((ff r k (div i 2)))\r\n | otherwise = (if (l == []) then [] else [head l]) ++ (if (r == []) then [] else [head r]) \r\n where \r\n l = [x | x <- a, ((.&.) (fst x) i) /= 0]\r\n r = [x | x <- a, ((.&.) (fst x) i) == 0]\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert (head a) i (encode (tail a) (i+1))\r\n\r\n-- encode a i | ((length a) == 0) = (M.empty)\r\n -- | otherwise = M.insert 1 2 M.empty --(M.insert 1 1 M.empty)\r\n\r\n-- decode a hash | (length a == 0) = []\r\n -- | otherwise = [head (hash M.! (head a))] ++ (decode (tail a) (M.insert (head a) (tail (hash M.! (head a))) hash))\r\n\r\nencode a i | (a == []) = []\r\n | otherwise = [(head a, i)] ++ (encode (tail a) (i+1))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [n, k] <- getInts 2\r\n a <- getInts n \r\n let \r\n aa = encode a 1\r\n ans = ff aa k 1073741824 \r\n if (length ans <= 1) then putInts [-1] else putInts [length (map snd ans)] >> putInts (map snd ans)\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\r\n"}], "src_uid": "9f13d3d0266b46e4201ea6a2378d1b71"} {"source_code": "import Control.Applicative\nimport Data.List\n \n \n\n\nprocess n = if z ==[] then \"-1\" else (replicate (snd(head z)) '4')++ (replicate (fst(head z)) '7')\n\twhere z= [ (n7,n4)| n7<-[(div n 7), (div n 7)-1..0], let nn= n-n7*7, mod nn 4 ==0, let n4 = div nn 4]\n\t \n\nmain= do\n\tn<- read <$> getLine ::IO Int\n\tputStrLn $ process n\n\t \n\t ", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n return n\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStrLn =<< solve . evalState parseInput <$> BS.getContents\n\nsolve sum\n | null lst = \"-1\"\n | otherwise = head lst\n where\n lst = [ replicate num4 '4' ++ replicate num7 '7'\n | num4 <- [0..sum `div` 4]\n , (sum - num4 * 4) `mod` 7 == 0\n , let num7 = (sum - num4 * 4) `div` 7\n ]\n \n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "num7_4 :: Int -> (Int, Int)\nnum7_4 n = let (quot,rem) = (div n 7,mod n 7) in\n case rem of\n 0 -> (quot,0)\n 1 -> (quot-1,2)\n 2 -> (quot-2,4)\n 3 -> (quot-3,6)\n 4 -> (quot,1)\n 5 -> (quot-1,3)\n 6 -> (quot-2,5)\n\nsolve :: Int -> String\nsolve n = let (n7,n4) = num7_4 n in\n if n7<0 then\n \"-1\"\n else\n ((replicate n4 '4')++(replicate n7 '7'))\n\nmain = do n <- getLine\n putStrLn (solve (read n::Int))"}, {"source_code": "\nimport Monad (liftM)\n\nsolve :: Int -> Maybe (Int, Int)\nsolve n\n | m < 0 = Nothing\n | otherwise = Just (m, k)\n where\n m' = div n 7\n (m, k) = findMK m'\n findMK m'\n | mod (n - 7*m') 4 == 0 = (m', div (n - 7*m') 4)\n | otherwise = findMK (m'-1)\n\nmain :: IO ()\nmain = do\n ans <- liftM solve readLn\n case ans of\n Nothing -> print (-1)\n Just (m, k) -> putStrLn $ replicate k '4' ++ replicate m '7'\n"}, {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: Int -> String\nsolve n = f n \"\"\n where f n s \n | n < 0 = \"-1\"\n | n `mod` 7 == 0 = s ++ (take (n `div` 7) (repeat '7')) \n | otherwise = f (n-4) (\"4\"++s)\n\nmain = interact$solve.read.head.words"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n n <- read `liftM` getLine\n let k = 2 * n `div` 7\n a = 2 * n - 7 * k\n b = 4 * k - n\n putStrLn $ if a >= 0 && b >= 0\n then replicate a '4' ++ replicate b '7'\n else \"-1\"\n"}, {"source_code": "solve :: Int -> Maybe String\nsolve 0 = Just \"\"\nsolve n\n\t| n < 0 = Nothing\n\t| n `mod` 7 == 0 = Just $ take (n `div` 7) $ repeat '7'\n\t| otherwise = solve (n-4) >>= Just . (++) \"4\"\n\nputLn :: Maybe String -> IO ()\nputLn Nothing = putStrLn \"-1\"\nputLn (Just x) = putStrLn x\n\nmain = do\n\tgetLine >>= putLn . solve . read\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n abs = [(a, b) | a <- [0..n`div`4], (n-4*a)`mod`7 == 0, let b = (n-4*a) `div` 7]\n\n if null abs\n then print $ -1\n else let (a, b) = head abs in putStrLn $ replicate a '4' ++ replicate b '7'\n"}, {"source_code": "num7_4 :: Int -> (Int, Int)\nnum7_4 n = let (quot, rem) = (div n 7, mod n 7) in\n (case rem of\n 0 -> (quot, 0)\n 1 -> (quot - 1, 2)\n 2 -> (quot - 2, 4)\n 3 -> (quot - 3, 6)\n 4 -> (quot, 1)\n 5 -> (quot - 1, 3)\n 6 -> (quot - 2, 5))\n\nsolve :: Int -> String\nsolve n = let (n7, n4) = num7_4 n in\n if (n7 < 0) then\n \"-1\"\n else\n ((replicate n4 '4')++(replicate n7 '7'))\n\nmain = do\n n <- getLine\n putStrLn (solve (read n :: Int))\n \n \n"}, {"source_code": "main = do\n n <- getLine\n putStr (solve . read $ n)\n\nsolve n = \n let \n atLeast = negate . div (- 5 * n) $ 7\n atMost = div (3 * n) 4\n in\n if atLeast > atMost then \"-1\"\n else \n let\n sevens = 3 * n - 4 * atLeast\n fours = - 5 * n + 7 * atLeast\n in (replicate fours '4') ++ (replicate sevens '7')\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport Data.Array\nimport Control.Monad (forM_)\nmaxn = 10^6\n\ndp :: Array Int Int\ndp = array bnds [(i, f i) | i <- range bnds]\n where\n bnds = (-6, maxn)\n f 0 = 1\n f i\n | i < 0 = 0\n | dp!(i-7) /= 0 = 7\n | dp!(i-4) /= 0 = 4\n | otherwise = 0\n\nlucky n\n | dp!n == 0 = [-1]\n | otherwise = f n\n where\n f 0 = []\n f n = dp!n : f (n - dp!n)\n\nmain = do\n ls <- lines `fmap` getContents\n let ns = map read ls\n forM_ [lucky n | n <- ns] $\n putStrLn . concat . map show . reverse\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n let\n abs = [(a, b) | a <- [1..n`div`4], (n-4*a)`mod`7 == 0, let b = (n-4*a) `div` 7]\n\n if null abs\n then print $ -1\n else let (a, b) = head abs in putStrLn $ replicate a '4' ++ replicate b '7'\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n return n\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStrLn =<< solve . evalState parseInput <$> BS.getContents\n\nsolve sum\n | null lst = \"-1\"\n | otherwise = head lst\n where\n lst = [ replicate num4 '4' ++ replicate num7 '7'\n | num7 <- [0..sum `div` 7]\n , (sum - num7 * 7) `mod` 4 == 0\n , let num4 = (sum - num7 * 7) `div` 4\n ]\n \n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "num7_4 :: Int -> (Int, Int)\nnum7_4 n = let (quot,rem) = (div n 7,mod n 7) in\n case rem of\n 0 -> (quot,0)\n 1 -> (quot-1,2)\n 2 -> (quot-2,4)\n 3 -> (quot-3,6)\n 4 -> (quot,1)\n 5 -> (quot-1,3)\n 6 -> (quot-2,5)\n\nsolve :: Int -> Int\nsolve n = let (n7,n4) = num7_4 n in\n if n7<0 then\n -1\n else\n read ((replicate n4 '4')++(replicate n7 '7'))::Int\n\nmain = do n <- getLine\n print (solve (read n::Int))"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \n\n\nprocess n = (replicate y '4')++ (replicate x '7')\n\twhere (x,y) = head [ (n7,n4)| n7<-[(div n 7), (div n 7)-1..0], let nn= n-n7*7, mod nn 4 ==0, let n4 = div nn 4]\n\t \n\nmain= do\n\tn<- read <$> getLine ::IO Int\n\tprint $ process n\n\t \n\t "}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \nluc = (4,4):(7,7):[(b1*10+a,b2+a)| (b1,b2)<-luc,a<-[4,7]]::[(Integer,Integer)]\n\n\n\nmain= do\n\tn<- read <$> getLine ::IO Integer\n\tlet x = dropWhile (\\z-> snd z < n) luc\n\tlet y = takeWhile (\\z-> (fromIntegral (length (show (fst z)))*4) snd z ==n) y\n\tprint $ if yy==[] then (-1) else fst $ head yy\n\t\n\t "}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \nluc = (4,4):(7,7):[(b1*10+a,b2+a)| (b1,b2)<-luc,a<-[4,7]]::[(Integer,Integer)]\n\n\n\nmain= do\n\tn<- read <$> getLine ::IO Integer\n\tlet x = head $ dropWhile (\\z-> snd z < n) luc\n\tprint $ if snd x == n then fst x else (-1)\n\t "}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \nluc = (4,4):(7,7):[(b1*10+a,b2+a)| (b1,b2)<-luc,a<-[4,7]]\n\n\n\nmain= do\n\tn<- read <$> getLine ::IO Int\n\tlet x = head $ dropWhile (\\z-> snd z < n) luc\n\tprint $ if snd x == n then fst x else (-1)\n\t "}], "src_uid": "2584fa8c1adb1aa8cd5c28a8610ff72d"} {"source_code": "--ghc 7.10\n\nmaxScore :: Int -> [Int] -> Int\nmaxScore m as = min m (sum as)\n\nprocess :: Int -> IO ()\nprocess 0 = return ()\nprocess t = do\n nmStr <- getLine\n let [n,m] = map read . words $ nmStr\n aStrs <- getLine\n let as = map read .words $ aStrs\n print $ maxScore m as\n process (t-1)\n\nmain = do\n tStr <- getLine\n let t = read tStr\n process t", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n (n:m:_) <- map read.words <$> getLine\n as <- map read.words <$> getLine\n print $ min (sum as) m\n test (i - 1)\n\n"}, {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve xs len max = min (sum xs) max\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [len, max] <- fmap read <$> words <$> getLine\n nums <- fmap read <$> words <$> getLine\n print $ solve nums len max\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nonecase = do\n\t\t[n,m]<- map read <$> words <$> getLine ::IO [Int]\n\t\ts<- sum <$> map read <$> words <$> getLine ::IO Int\n\t\tprint $ min s m\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [], "src_uid": "7c2a61de728e6767b25e58c74497bbae"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport qualified Data.List as L\n\nmain :: IO ()\nmain = do\n [_, m] <- map read.words <$> getLine\n xs <- map fromIntegral.L.unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n putStrLn.unwords.map show $ solve m xs\n\nsolve :: Int64 -> [Int64] -> [Int64]\nsolve m xs0 = go 0 xs0\n where\n go !acc (x:xs)\n | acc + x < m = 0 : go (acc + x) xs\n | (q, r) <- quotRem (x - (m - acc)) m = (q + 1) : go r xs\n go _ [] = []\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BC\nimport Data.Maybe (fromJust)\n\nf::Integer->[Integer]->[Integer]\nf k (x:[])=[]\nf k (x:y:xs)=((y `div` k)-(x `div` k)):f k (y:xs)\n\nmain = do\n e1<-BC.getLine\n e2<-BC.getLine\n let (e:k:[]) = map (fst . fromJust . BC.readInteger) . BC.words $ e1\n ys = map (fst . fromJust . BC.readInteger) . BC.words $ e2\n putStrLn $ unwords $ map show $ f k $ scanl (+) 0 ys"}, {"source_code": "import Data.List\nmain = interact $ unwords . map show . solve . map read . tail . words\nsolve (m:as) = snd $ mapAccumL f 0 as where\n f l l' = (r,d) where (d,r) = (l+l') `divMod` m\n"}, {"source_code": "module Main where\nimport Data.List\n\ndefault (Int)\n\nmain = interact exec\nexec = unwords . map show . snd . (\\(_:m:xs) -> mapAccumL (\\l x -> let (q, r) = (x - l) `divMod` m in ((m - r) `rem` m, max 0 q + fromEnum (r == 0 && q == 0) + fromEnum (l < x) - fromEnum (l == 0))) 0 xs) . map read . words "}], "negative_code": [{"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (m:as) = sum as `div` m\n"}], "src_uid": "a2085c2d21b2dbe4cc27a15fa4a1ec4f"} {"source_code": "module Main where\nimport Data.List\n\narrange _ (as,bs) [] = reverse as ++ bs\narrange b (as,bs) (x:xs) = arrange (not b) (if b then (x:as,bs) else (as,x:bs)) xs\n\nmain = do\n getLine\n as <- map (read :: String -> Int) . words <$> getLine\n let bs = sort as\n cs = arrange True ([],[]) bs\n putStrLn $ concat $ intersperse \" \" $ map show cs", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Maybe\nimport Data.List\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain = do\n _ <- readLn :: IO (Int)\n xs <- sort <$> readInts\n let (a,b) = partition (\\(x,y) -> x `mod` 2 == 0) $ zip [1..] xs\n putStr . unwords . map (\\(x,y) -> show y) $ a ++ reverse b\n "}], "negative_code": [], "src_uid": "205b2332c176b758e843473e8d357475"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.Map.Strict as Map\n\nimport Data.Maybe\n\ntype Dictionary = Map.Map B.ByteString B.ByteString\n\nmain :: IO ()\nmain = do\n [n, m] <- readIntsIO\n dic <- foldl' insertDictionary Map.empty . map B.words <$> replicateM m B.getLine\n B.putStrLn . B.unwords . map (fromJust . flip Map.lookup dic) . B.words =<< B.getLine\n return ()\n\ninsertDictionary :: Dictionary -> [B.ByteString] -> Dictionary\ninsertDictionary dic [w1, w2]\n | B.length w1 > B.length w2 = Map.insert w1 w2 $ Map.insert w2 w2 $ dic\n | otherwise = Map.insert w2 w2 $ Map.insert w1 w1 $ dic\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.List\nimport Data.Map (Map,fromList,(!))\ndict pairs = fromList $ do\n l <- pairs\n let y = minimumBy (comparing length) l\n w <- l\n return (w,y)\ngetWords = fmap words getLine\nmain = do \n [_n,ms] <- getWords\n d <- fmap dict $ replicateM (read ms) getWords\n l <- getWords\n putStrLn $ intercalate \" \" $ map (d !) l\n\n\n\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\ns-> (solve =<< forM [1.. (1 +) $ last $ map (fst.fromJust.C.readInt) $ C.words ns] ( \\i -> C.words<$>C.getLine))\nsolve xs = let ms = Map.fromList $concat $ map (\\[a1,a2] -> let m =minimumBy (\\ a b ->C.length a `compare` C.length b) [a1,a2] in [(a1,m),(a2,m)]) $ init xs; l =last xs in forM_ l $ \\i-> C.putStr $ C.append (ms Map.! i) (C.singleton ' ')"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.Map as M\n\n\n\n\n\n\nmain = do\n [a,b]<-map read <$> words <$> getLine ::IO [Int]\n m<-replicateM b ( words <$> getLine) ::IO [[String]]\n let mm = map (\\[z1,z2]-> (z1,if length z1<=length z2 then z1 else z2)) m\n let mymap = M.fromList mm\n s<- words <$> getLine ::IO [String]\n putStrLn $ intercalate \" \" $ map (\\z-> fromJust(M.lookup z mymap)) s\n"}, {"source_code": "import qualified Data.Map as Map\nimport qualified Data.List as List\nimport qualified Data.Maybe as Maybe\n\nmain = do\n contents <- getContents\n let allLines = lines contents \n let (nWordsInLecture, mWordsInLanguage) =\n (intsInLine !! 0, intsInLine !! 1)\n where intsInLine = lineToInts $ head allLines\n\n let wordMapping = Map.fromList $ linesToWordsInSameMeaning $ init $ tail allLines\n putStrLn $ unwords $ List.intersperse \" \"\n $ map (firstWordToShorterWord wordMapping) \n $ words $ last allLines\n\nlineToInts :: String -> [Int]\nlineToInts line = map read $ words line\n\nlinesToWordsInSameMeaning :: [String] -> [(String, String)]\nlinesToWordsInSameMeaning [] = []\nlinesToWordsInSameMeaning (line:remain) =\n (twoWords !! 0, twoWords !! 1) :\n linesToWordsInSameMeaning remain\n where twoWords = words line\n\nfirstWordToShorterWord :: Map.Map String String -> String -> String\nfirstWordToShorterWord mapping firstWord =\n if length firstWord <= length secondWord\n then firstWord else secondWord\n where secondWord = Maybe.fromJust $ Map.lookup firstWord mapping\n"}, {"source_code": "import qualified Data.Map as M\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unwords . solve . map words . tail . lines\n\nsolve :: [[String]] -> [String]\nsolve cs = map (\\s -> M.findWithDefault s s m) $ last cs\n where m = M.fromList $ filter (\\(x, y) -> length x > length y) $ map toTuple $ init cs\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import Data.Ord (comparing)\nimport Data.List (minimumBy)\nimport Data.Map ((!))\nimport qualified Data.Map as M\nimport Control.Monad (replicateM)\nreadPair = getLine >>= \\l -> let [a,b] = words l in return (a,b)\nmain = do\n [n,m] <- fmap (map read . words) getLine\n ws <- fmap M.fromList (replicateM m readPair)\n putStrLn . unwords . map (\\w -> minimumBy (comparing length) [w,ws!w]) . words =<< getLine\n"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as M\n\nglw = fmap words getLine\nglwr = fmap (map read . words) getLine\n\nmain = do\n hSetBuffering stdout NoBuffering\n solve\n\nsolve :: IO ()\nsolve = do\n n:m:_ <- glwr\n mappings <- forM [1..m] $ const glw\n note <- glw\n putStrLn $ lecture n m mappings note\n\nlecture :: Int -> Int -> [[String]] -> [String] -> String\nlecture n m mappings = unwords . map (ko m)\n where\n m = M.fromList $ map (\\[a,b] -> (a,b)) mappings\n\nko :: M.Map String String -> String -> String\nko m a\n | length a <= length b = a\n | 0 < 1 = b\n where\n b = m M.! a\n"}, {"source_code": "import Data.List\nimport Data.Ord\ndecode d w = minimumBy (\\x y -> compare (length x) (length y)). head . filter (w`elem`) $ d\nsolve m = let\n dict = map (id . words) . init $ m\n in\n map (decode dict) ((words . last) m)\nmain = interact $ unwords . solve . tail . lines"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\n\ntype Vocab = (String, String)\n\n--create dictionary from list of tuples (input)\narrange :: Vocab -> Vocab\narrange w@(a, b)\n | length a <= length b = (b, a)\n | otherwise = w\n\nmakeDict :: [Vocab] -> M.Map String String\nmakeDict = M.fromList . map arrange\n--------------------------------\n\n--main solver\nsolve :: M.Map String String -> String -> String\nsolve ms s\n | result /= Nothing = unwrap result\n | otherwise = s\n where result = M.lookup s ms\n\nunwrap (Just a) = a\n---------------------------------\n\n--stdin, IO\ntoTuple [] = []\ntoTuple (x:xs:xss) = (x, xs) : toTuple xss\n\nmain = do\n g <- (fmap words getContents)\n let [n, m] = map read (take 2 g)\n mks = makeDict . toTuple . take (m*2) . drop 2 $ g\n line = drop (m*2 + 2) g\n putStr . intercalate \" \" . map (solve mks) $ line\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\ntype BS = B.ByteString\n\nshorterWord :: [(BS, BS)] -> BS -> BS\nshorterWord choices word =\n if B.length a > B.length b then b else a where\n (a, b) = findWord word choices\n\nfindWord :: BS -> [(BS, BS)] -> (BS, BS)\nfindWord word choices =\n head . filter (isBelong word) $ choices where\n isBelong x (a, b) = x `elem` [a, b]\n\nsolve :: [(BS, BS)] -> [BS] -> [BS]\nsolve choices = map (shorterWord choices)\n\nmain = do\n g <- B.getContents\n let ws = B.words g\n m = a where Just (a, b) = B.readInt (ws !! 1)\n w = totuple (take (2*m) (drop 2 ws))\n lec = drop (2*m + 2) ws\n mapM_ B.putStr . intersperse (B.pack \" \") $ (solve w lec)\n\n\ntotuple [] = []\ntotuple (l:ls:lss) =\n (l, ls) : totuple lss\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.Map.Strict as M\n\n \n \t\n\nmain= do\n\t[n,m]<- map read. words <$> getLine ::IO [Int]\n\tq1<- replicateM m ( words <$>getLine)\n\tlet q= M.fromList $ map (\\[a,b] ->(a,b)) $ filter (\\[a,b] -> length a >length b) q1\n\tle<- words <$> getLine\n\tputStrLn $ intercalate \" \" $ map (\\z-> let r=M.lookup z q in if r==Nothing then z else fromJust r ) le\n\t "}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\n\n \n \t\n\nmain= do\n\t[n,m]<- map read. words <$> getLine ::IO [Int]\n\tq1<- replicateM m ( words <$>getLine)\n\tlet q= map (\\[a,b] ->(a,b)) $ filter (\\[a,b] -> length a >length b) q1\n\tle<- words <$> getLine\n\tputStrLn $ intercalate \" \" $ map (\\z-> let r=lookup z q in if r==Nothing then z else fromJust r ) le\n\t "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map.Strict as M (empty, insert, (!))\n\nsolve dict lecture = map (ls M.!) lecture\n where\n ins m [a,b] =\n let v = if length a <= length b then a else b\n in M.insert a v $ M.insert b v m\n ls = foldl ins M.empty dict\n\n\n\n\nmain = do\n [n, m] <- map read . words <$> getLine\n dict <- replicateM m $ words <$> getLine\n lecture <- words <$> getLine\n putStrLn $ unwords $ solve dict lecture\n"}, {"source_code": "main = do\n\tt<-getLine\n\trest<-getContents\n\tlet [n,m] = map read $ words t :: [Int]\n\tlet dict = map words $ init $ lines rest\n\tlet lect = words $ last $ lines rest\n\tputStrLn $ init $ solve lect dict\n\nsolve [] _ = []\nsolve (l:ls) dict = chooseWord l dict ++ \" \"++ solve ls dict\n where chooseWord l dict = if length word1 <= length word2 then word1 else word2\n [word1, word2]=concat $ filter (elem l) dict"}, {"source_code": "import Data.Map\n\nmain :: IO()\nmain = putStrLn . solve . words =<< getContents\n\nsolve :: [String] -> String\nsolve (_:sm:strs) =\n let m = read sm\n (words, sentence) = splitAt (m*2) strs\n wordMap = getMap words Data.Map.empty\n in unwords (trans sentence wordMap)\n \ngetMap :: [String] -> Map String String -> Map String String\ngetMap [] wordMap = wordMap\ngetMap (a:b:ss) wordMap | (length a) <= (length b) = getMap ss (insert b a (insert a a wordMap))\n | otherwise = getMap ss (insert a b (insert b b wordMap))\n\ntrans :: [String] -> Map String String -> [String]\ntrans [] _ = []\ntrans (s:ss) wordMap = (removeMaybe (Data.Map.lookup s wordMap)):(trans ss wordMap)\n\nremoveMaybe :: Maybe a -> a\nremoveMaybe (Just a) = a\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n [n, m] <- getInts\n ps <- replicateM m $ words <$> getLine\n ws <- words <$> getLine\n\n let\n m = HashMap.fromList $ concat $ map f ps\n where\n f [a, b] = [(a, c), (b, c)]\n where\n c = if length a <= length b then a else b\n\n putStrLn $ unwords $ map (m HashMap.!) ws\n\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.Functor\n\nparseLine :: IO (Map.Map String String) -> Int -> IO (Map.Map String String)\nparseLine ms index = do\n m <- ms\n [x, y] <- words <$> getLine\n return $ Map.insert x (if length x <= length y then x else y) m\n\nunwrap (Just x) = x\n\nmain = do\n [n, m] <- map read <$> words <$> getLine :: IO [Int]\n p <- foldl parseLine (return Map.empty) [1..m]\n as <- words <$> getLine\n bs <- return $ map (\\x -> unwrap (Map.lookup x p)) as\n putStrLn . unwords $ bs\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.List\nimport Data.Map (Map,fromList,(!))\ndict pairs = fromList $ do\n l <- pairs\n let y = minimumBy (comparing length) l\n w <- l\n return (w,y)\ngetWords = fmap words getLine\nmain = do \n [_n,ms] <- getWords\n d <- fmap dict $ replicateM (read ms) getWords\n l <- getWords\n print $ intercalate \" \" $ map (d !) l\n\n\n\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\n\ntype Vocab = (String, String)\n\n--create dictionary from list of tuples (input)\narrange :: Vocab -> Vocab\narrange w@(a, b)\n | length a <= length b = (b, a)\n | otherwise = w\n\nmakeDict :: [Vocab] -> M.Map String String\nmakeDict = M.fromList . map arrange\n--------------------------------\n\n--main solver\nsolve :: M.Map String String -> String -> String\nsolve ms s\n | result /= Nothing = unwrap result\n | otherwise = s\n where result = M.lookup s ms\n\nunwrap (Just a) = a\n---------------------------------\n\n--stdin, IO\ntoTuple [] = []\ntoTuple (x:xs:xss) = (x, xs) : toTuple xss\n\nmain = do\n g <- (fmap words getContents)\n let [n, m] = map read (take 2 g)\n mks = makeDict . toTuple . drop 2 . take (m*2) $ g\n line = drop (m*2 + 2) g\n putStr . intercalate \" \" . map (solve mks) $ line\n"}], "src_uid": "edd556d60de89587f1b8daa893538530"} {"source_code": "{-# LANGUAGE BangPatterns, FlexibleInstances #-}\n\nmain = getLine>>=print.solve.map read.words\n\nsolve :: [Integer] -> Double\nsolve [w,h,0] = fromIntegral $ w*h\nsolve [w,h,180] = fromIntegral $ w*h\nsolve [w,h,90] = fromIntegral $ min w h * min w h\nsolve wha@[w',h',a']\n | a'>90 = solve[w',h',180-a']\n | wh && not (segIntersect ((-w,h),(-w,-h)) (rot(-w,h)a,rot(-w,-h)a)) = h*h / sin a\n | otherwise = go 0 $ ps ++ map negate ps\n where\n [w,h,_] = map fromIntegral wha\n a = fromIntegral a' / 180 * pi\n ps@(x:_) = [(w/2,w*(1-cos a)/(2*sin a))\n , ((w-h*sin a)/(2*cos a),h/2)\n ,(h*(1-1/cos a)/(2*tan a),h/2)\n ,(-w/2,(h-w*sin a)/(2*cos a))\n ]\n go acc (p0:p1:ps) = go (acc + p0 `cross` p1 / 2.0) (p1:ps)\n go acc [p] = acc + (p `cross` x / 2.0)\n\neps :: Double\neps = 1e-9\n\ntype Point = (Double,Double)\ntype Seg = (Point,Point)\n\ninstance Num (Double,Double) where\n (!x0,!y0) + (!x1,!y1) = (x0+x1,y0+y1)\n (!x0,!y0) - (!x1,!y1) = (x0-x1,y0-y1)\n (!x0,!y0) * (!x1,!y1) = (x0*x1-y0*y1,x0*y1+x1*y0)\n negate (!x,!y) = (negate x,negate y)\n abs (!x,!y) = (sqrt(x*x + y*y),0)\n signum (!x,!y) = case sqrt $ x*x + y*y of\n r | r < eps -> (0,0)\n | otherwise -> (x/r,y/r)\n fromInteger n = (fromInteger n, 0)\n\ninfixr 7 *:\n(*:) :: Double -> (Double,Double) -> (Double,Double)\n(*:) !k (!x,!y) = (k*x,k*y)\n{-# INLINE (*:) #-}\n\ncross :: (Double,Double) -> (Double,Double) -> Double\ncross (!x0,!y0) (!x1,!y1) = x0*y1 - y0*x1\n{-# INLINE cross #-}\n\nrot :: (Double,Double) -> Double -> (Double,Double)\nrot (!x,!y) !a = (x,y)*(cos a,sin a)\n{-# INLINE rot #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0,p1) (q0,q1) = (area p0 q0 q1) * (area p1 q0 q1) < eps\n && (area q0 p0 p1) * (area q1 p0 p1) < eps\n{-# INLINE segIntersect #-}\n\narea :: Point -> Point -> Point -> Double\narea o u v = (u-o)`cross`(v-o)\n{-# INLINE area #-}\n", "positive_code": [{"source_code": "main :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [w', h', a']\n | a' == 0 || a' == 180 = w * h\n | a' == 90 = h * h\n | sin (a / 2) > h / d = s * s * sin a\n | otherwise = w * h - (x * x + y * y) * tan a\n where\n w = max w' h'\n h = min w' h'\n a = min a' (180 - a') * pi / 180\n d = sqrt $ w * w + h * h\n x = w / 2 - h / 2 * (1 - cos a) / sin a\n y = (h - x * tan a) * cos a / (1 + cos a)\n s = h / 2 * (tan (a / 2) + 1 / tan (a / 2))\n"}, {"source_code": "import Data.Ord\nimport Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do \n [w, h, a] <- map read . words <$> getLine\n let a' = (min a (180 - a)) * pi / 180\n let pts = [(w/2, h/2), (w/2, -h/2), (-w/2,-h/2), (-w/2,h/2)] :: [(Double, Double)]\n let pts' = map (rotate a') pts\n let lines = zip pts (tail $ cycle pts)\n let lines' = zip pts' (tail $ cycle pts')\n let ints = concatMap (getints lines') lines\n print . area . uniq $ sortBy (comparing theta) ints\n\nuniq [] = []\nuniq [x] = [x]\nuniq (x:y:xs)\n | x == y = uniq (x:xs)\n | otherwise = x : uniq (y:xs)\n\nrotate a (x, y) = (x * cos a - y * sin a, x * sin a + y * cos a)\n\ntheta (x, y) = atan2 y x\n\ngetints xs y = concatMap (\\x -> getints' x y) xs\n\ngetints' l'@((x1', y1'), (x2', y2')) l@((x, y), (x', y'))\n | x == x' =\n let y'' = y1' + (x - x1') / (x2' - x1') * (y2' - y1')\n in if min y y' <= y'' && y'' <= max y y' then [(x, y'')] else []\n | y == y' = map swap $ getints' (swap' l') (swap' l)\n where\n swap (a, b) = (b, a)\n swap' (p1, p2) = (swap p1, swap p2)\n\narea ps =\n let\n xs = map fst ps\n ys = map snd ps\n in\n 0.5 * abs (sum $ zipWith4 (\\x y y' x' -> x * y - y' * x') xs (tail $ cycle ys) ys (tail $ cycle xs))\n"}], "negative_code": [{"source_code": "main :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [w', h', a']\n | a' == 90 = h * h\n | sin (a / 2) > h / d = s * s * sin a\n | otherwise = w * h - (x * x + y * y) * tan a\n where\n w = max w' h'\n h = min w' h'\n a = min a' (180 - a') * pi / 180\n d = sqrt $ w * w + h * h\n x = w / 2 - h / 2 * (1 - cos a) / sin a\n y = (h - x * tan a) * cos a / (1 + cos a)\n s = h / 2 * (tan (a / 2) + 1 / tan (a / 2))\n"}, {"source_code": "import Debug.Trace\n\nmain :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [w', h', a']\n | a' == 90 = h * h\n | sin (a / 2) > h / d = s * s * sin a\n | otherwise = trace (show x ++ \" \" ++ show y) $ w * h - (x * x + y * y) * tan a\n where\n w = max w' h'\n h = min w' h'\n a = min a' (180 - a') * pi / 180\n d = sqrt $ w * w + h * h\n x = w / 2 - h / 2 * (1 - cos a) / sin a\n y = (h - x * tan a) * cos a / (1 + cos a)\n s = h / 2 * (tan a + 1 / tan a)\n"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [w', h', a']\n | a' == 0 || a' == 90 = h * h\n | sin (a / 2) > h / d = s * s * sin a\n | otherwise = w * h - (x * x + y * y) * tan a\n where\n w = max w' h'\n h = min w' h'\n a = min a' (180 - a') * pi / 180\n d = sqrt $ w * w + h * h\n x = w / 2 - h / 2 * (1 - cos a) / sin a\n y = (h - x * tan a) * cos a / (1 + cos a)\n s = h / 2 * (tan (a / 2) + 1 / tan (a / 2))\n"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [w', h', a']\n | elem a' [0, 90, 180] = h * h\n | sin (a / 2) > h / d = s * s * sin a\n | otherwise = w * h - (x * x + y * y) * tan a\n where\n w = max w' h'\n h = min w' h'\n a = min a' (180 - a') * pi / 180\n d = sqrt $ w * w + h * h\n x = w / 2 - h / 2 * (1 - cos a) / sin a\n y = (h - x * tan a) * cos a / (1 + cos a)\n s = h / 2 * (tan (a / 2) + 1 / tan (a / 2))\n"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve [w', h', a']\n | a' == 90 = h * h\n | sin (a / 2) > h / d = s * s * sin a\n | otherwise = w * h - (x * x + y * y) * tan a\n where\n w = max w' h'\n h = min w' h'\n a = min a' (180 - a') * pi / 180\n d = sqrt $ w * w + h * h\n x = w / 2 - h / 2 * (1 - cos a) / sin a\n y = (h - x * tan a) * cos a / (1 + cos a)\n s = h / 2 * (tan a + 1 / tan a)\n"}], "src_uid": "21432a74b063b008cf9f04d2804c1c3f"} {"source_code": "import qualified Data.List as L\nimport Control.Arrow\n\nread2 :: String -> (Integer, Integer)\nread2 l =\n let (x:y:_) = map read $ words l\n in (x,y)\n\ngetY :: (Integer, Integer) -> Integer -> Integer\ngetY (k,b) x = k*x+b\n\nsolve :: [String] -> String\nsolve (x12:lns)\n | crossExists = \"YES\"\n | otherwise = \"NO\"\n where\n (x1,x2) = read2 x12\n coeffs = map read2 lns\n ys = L.sort $ map ((`getY` x1) &&& (`getY` x2)) coeffs\n crossExists = map snd ys /= (L.sort $ map snd ys)\n\na :: String\na = solve [\"1 2\", \"1 2\", \"1 0\", \"0 1\", \"0 2\"]\n\nb :: String\nb = solve [\"22290 75956\", \"-66905 -22602\", \"-88719 12654\", \"-191 -81032\", \"0 -26057\", \"-39609 0\", \"0 51194\", \"2648 88230\", \"90584 15544\", \"0 23060\", \"-29107 26878\"]\n\nmain :: IO ()\nmain = interact $ solve . tail . lines", "positive_code": [{"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.List as L \nimport Data.Maybe\nimport Control.Applicative\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\nmycompare0 x y\n | g == EQ = compare (snd x) (snd y)\n | otherwise = g\n where g = compare (fst x) (fst y)\nmycompare1 x y\n | g == EQ = compare (snd y) (snd x)\n | otherwise = g\n where g = compare (fst x) (fst y)\nzipSortBy func refs as = map snd $ L.sortBy (\\x y -> func (fst x) (fst y)) $ zip refs as\nmain = do\n n <- readLn\n [x1,x2] <- readLists\n a <- readMatrix\n let ks = map (\\x -> x !! 0) a\n let bs = map (\\x -> x !! 1) a\n let vx1 = zipWith (\\k b -> k*x1+b) ks bs\n let vx2 = zipWith (\\k b -> k*x2+b) ks bs\n let isIntersect = (zipSortBy mycompare0 (zip vx1 ks) [1..n]) /= (zipSortBy mycompare1 (zip vx2 ks) [1..n])\n putStrLn $ if isIntersect then \"YES\" else \"NO\"\n \n"}, {"source_code": "import Data.Char (ord)\nimport Data.List (sort)\n\ntype Input = (Integer, Integer, [(Integer, Integer)])\ntype Output = Bool\n\nreadInteger :: String -> Integer\nreadInteger ('-' : s) = - (readInteger s)\nreadInteger s = foldl (\\t c -> t * 10 + toInteger (ord c) - 48) 0 s\n\nparse :: String -> Input\nparse contents = (x_1, x_2, map pair ls)\n where (_ : l1 : ls) = lines contents\n (x_1, x_2) = pair l1\n pair l = let [a, b] = map readInteger . words $ l in (a, b)\n\ncheck :: [(Integer, Integer)] -> Bool\ncheck [] = False\ncheck [_] = False\ncheck ((x, y) : (x', y') : xss) = (x < x' && y > y') || check ((x', y') : xss)\n\nsolve :: Input -> Output\nsolve (x_1, x_2, ls) = check . sort . map y $ ls\n where y (k, b) = (k * x_1 + b, k * x_2 + b)\n\nformat :: Output -> String\nformat True = \"Yes\"\nformat False = \"No\"\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\nimport Control.Arrow\n\nread2 :: String -> (Int, Int)\nread2 l =\n let (x:y:_) = map read $ words l\n in (x,y)\n\ngetY :: (Int, Int) -> Int -> Int\ngetY (k,b) x = k*x+b\n\nsolve :: [String] -> String\nsolve (x12:lns)\n | crossExists = \"YES\"\n | otherwise = \"NO\"\n where\n (x1,x2) = read2 x12\n coeffs = map read2 lns\n ys = L.sort $ map ((`getY` x1) &&& (`getY` x2)) coeffs\n crossExists = map snd ys /= (L.sort $ map snd ys)\n\na :: String\na = solve [\"1 2\", \"1 2\", \"1 0\", \"0 1\", \"0 2\"]\n\nmain :: IO ()\nmain = interact $ solve . tail . lines"}, {"source_code": "import qualified Data.List as L\n\nread2 :: String -> (Int, Int)\nread2 l =\n let (x:y:_) = map read $ words l\n in (x,y)\n\ngetY :: (Int, Int) -> Int -> Int\ngetY (k,b) x = k*x+b\n\nsolve :: [String] -> String\nsolve (x12:lns)\n | crossExists = \"YES\"\n | otherwise = \"NO\"\n where\n (x1,x2) = read2 x12\n coeffs = map read2 lns\n ys1 = L.sort $ zip (map (\\c -> (getY c x1, fst c)) coeffs) [0..]\n ys2 = L.sort $ zip (map (\\c -> (getY c x2, -(fst c))) coeffs) [0..]\n crossExists = map snd ys1 /= map snd ys2\n\na :: String\na = solve [\"1 2\", \"1 2\", \"1 0\", \"0 1\", \"0 2\"]\n\nmain :: IO ()\nmain = interact $ solve . tail . lines"}, {"source_code": "import Data.Char (ord)\nimport Data.List (sort)\n\ntype Input = (Integer, Integer, [(Integer, Integer)])\ntype Output = Bool\n\nreadInteger :: String -> Integer\nreadInteger = foldl (\\s c -> s * 10 + toInteger (ord c) - 48) 0\n\nparse :: String -> Input\nparse contents = (x_1, x_2, map pair ls)\n where (_ : l1 : ls) = lines contents\n (x_1, x_2) = pair l1\n pair l = let [a, b] = map readInteger . words $ l in (a, b)\n\ncheck :: [(Integer, Integer)] -> Bool\ncheck [] = False\ncheck [_] = False\ncheck ((x, y) : (x', y') : xss) = (x < x' && y > y') || check ((x', y') : xss)\n\nsolve :: Input -> Output\nsolve (x_1, x_2, ls) = check . sort . map y $ ls\n where y (k, b) = (k * x_1 + b, k * x_2 + b)\n\nformat :: Output -> String\nformat True = \"Yes\"\nformat False = \"No\"\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}], "src_uid": "8b61213e2ce76b938aa68ffd1e4c1429"} {"source_code": "import Control.Monad\n\nsolve :: [Int] -> String\nsolve li = let\n s = sum li\n w = maximum li\n in if 2*w > s\n then \"T\"\n else if even s then \"HL\" else \"T\" \n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n putStrLn (solve a)\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ bool \"HL\" \"T\" $ sum as - maximum as < maximum as || odd (sum as)\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ bool \"HL\" \"T\" $ sum as - maximum as < maximum as\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ bool \"HL\" \"T\" $ play True as\n\nplay turn (1 : b : as) = play (not turn) (b : as)\nplay turn (a : b : as) = play (not turn) (b : a - 1 : as)\nplay turn _ = turn\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> [Int] -> String\nsolve 1 [_] = \"T\"\nsolve n li = if even (sum li) then \"HL\" else \"T\" \n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n putStrLn (solve n a)\n"}], "src_uid": "5bfce6c17af24959b4af3c9408536d05"} {"source_code": "import Data.List\n\nf::[String]->[String]\nf []=[]\nf (x:xs)=let t=sort x\n in if t==(reverse t) then \"-1\":f xs else t:f xs \n\nmain = do\n e<-getLine\n ts<-getContents\n let xs=lines ts\n mapM_ putStrLn $ f xs", "positive_code": [{"source_code": "main = interact $ unlines . map solve . tail . lines\n\nsolve (x:xs) = head $ filter (\\xs -> xs /= reverse xs) [(x:xs), (xs ++ [x]), \"-1\"]\n"}], "negative_code": [], "src_uid": "b9f0c38c6066bdafa2e4c6daf7f46816"} {"source_code": "main = interact $ solve. lines\nsolve (h:t) = let [n,x1,y1,x2,y2] = map read . words $ h\n xs = map ((\\[x,y] -> (x,y)) . map read . words) t\n getDis x1 y1 x2 y2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n find (x, y) = let r = getDis x1 y1 x y\n in r + (maximum . (0:) . map (\\(x,y) -> getDis x y x2 y2) $ filter (\\(x,y) -> getDis x y x1 y1 > r) xs)\n in show . minimum $ map find ((x1,y1):xs)\n", "positive_code": [{"source_code": "main = interact $ solve. lines\nsolve (h:t) = let [n,x1,y1,x2,y2] = map read . words $ h\n xs = map (map read . words) t\n getDis x1 y1 x2 y2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n find [x, y] = let r = getDis x1 y1 x y\n in r + (maximum . (0:) . map (\\[x,y] -> getDis x y x2 y2) $ filter (\\[x,y] -> getDis x y x1 y1 > r) xs)\n in show . minimum $ map find ([x1,y1]:xs)\n"}, {"source_code": "-- A flowerbed has many flowers and two fountains.\n--\n-- You can adjust the water pressure and set any values r1(r1\u2009\u2265\u20090) and r2(r2\u2009\u2265\u20090),\n-- giving the distances at which the water is spread from the first and second\n-- fountain respectively. You have to set such r1 and r2 that all the flowers\n-- are watered, that is, for each flower, the distance between the flower and\n-- the first fountain doesn't exceed r1, or the distance to the second fountain\n-- doesn't exceed r2. It's OK if some flowers are watered by both fountains.\n--\n-- You need to decrease the amount of water you need, that is set such r1 and r2\n-- that all the flowers are watered and the r1^2\u2009+\u2009r2^2 is minimum possible.\n-- Find this minimum value.\n--\n-- Input\n-- The first line of the input contains integers n, x1, y1, x2, y2 (1\u2009\u2264\u2009n\u2009\u2264\u20092000,\n--\u2009-107\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009107) \u2014 the number of flowers, the coordinates of\n-- the first and the second fountain.\n--\n-- Next follow n lines. The i-th of these lines contains integers xi and yi\n-- (-107\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009107) \u2014 the coordinates of the i-th flower.\n--\n-- It is guaranteed that all n\u2009+\u20092 points in the input are distinct.\n--\n-- Output\n-- Print the minimum possible value r1^2\u2009+\u2009r2^2. Note, that in this problem\n-- optimal answer is always integer.\n--\n-- Found at: http://codeforces.com/contest/617/problem/C\n--\n\nmodule Main where\n\ntype Point = (Int,Int)\n\ndist2 :: Point -> Point -> Integer\ndist2 (x1,y1) (x2,y2) = (toInteger $ x1 - x2) ^ 2 + (toInteger $ y1 - y2) ^ 2\n\nbrute :: Point -> Point -> [Point] -> (Integer,Integer)\nbrute s1 s2 flowers = minimumWith (uncurry (+)) possibleRs\n where r12s = map (dist2 s1) flowers\n possibleRs = map (\\r12 -> bruteGivenR12 s1 s2 r12 flowers) r12s\n\nbruteGivenR12 s1 s2 r12 flowers = (r12,r22)\n where dist2s = map (\\flower -> (dist2 flower s1, dist2 flower s2)) flowers\n notCoveredByS1 = filter (\\(d12,d22) -> r12 < d12) dist2s\n r22s = map snd notCoveredByS1\n r22 = foldl max 0 r22s\n\nminimumWith :: (Ord b) => (a -> b) -> [a] -> a\nminimumWith _ [] = error \"List cannot be empty\"\nminimumWith f lst = minimumWith' (head lst, f (head lst)) lst\n where minimumWith' (xmin, _) [] = xmin\n minimumWith' (xmin, fxmin) (x:xs)\n | f x < fxmin = minimumWith' (x, f x) xs\n | otherwise = minimumWith' (xmin, fxmin) xs\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n line <- getLine\n rest <- getLines (n-1) -- sadly, not tail recursion\n return $ line:rest\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [n, s1x, s1y, s2x, s2y] = (map read . words) line1 :: [Int]\n flowerLines <- getLines n\n let flowers = map ((\\[x, y] -> (x,y)) . (map read) . words) flowerLines :: [Point]\n -- have to brute force for all possibilities of r12 being non-zero and r22 being non-zero\n let (r12', r22') = brute (s1x,s1y) (s2x,s2y) flowers\n (r12'',r22'') = (0, maximum $ map (dist2 (s2x,s2y)) flowers)\n (r12,r22) = minimumWith (uncurry (+)) [(r12', r22'), (r12'',r22'')]\n putStrLn $ show (r12 + r22)\n"}], "negative_code": [{"source_code": "main = interact $ solve. lines\nsolve (h:t) = let [n,x1,y1,x2,y2] = map read . words $ h\n xs = map (map read . words) t\n getDis x1 y1 x2 y2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n find [x, y] = let r = getDis x1 y1 x y\n in r + (maximum . (0:) . map (\\[x,y] -> getDis x y x2 y2) $ filter (\\[x,y] -> getDis x y x1 y1 > r) xs)\n in show . minimum $ map find xs \n"}, {"source_code": "-- A flowerbed has many flowers and two fountains.\n--\n-- You can adjust the water pressure and set any values r1(r1\u2009\u2265\u20090) and r2(r2\u2009\u2265\u20090),\n-- giving the distances at which the water is spread from the first and second\n-- fountain respectively. You have to set such r1 and r2 that all the flowers\n-- are watered, that is, for each flower, the distance between the flower and\n-- the first fountain doesn't exceed r1, or the distance to the second fountain\n-- doesn't exceed r2. It's OK if some flowers are watered by both fountains.\n--\n-- You need to decrease the amount of water you need, that is set such r1 and r2\n-- that all the flowers are watered and the r1^2\u2009+\u2009r2^2 is minimum possible.\n-- Find this minimum value.\n--\n-- Input\n-- The first line of the input contains integers n, x1, y1, x2, y2 (1\u2009\u2264\u2009n\u2009\u2264\u20092000,\n--\u2009-\u2009107\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009107) \u2014 the number of flowers, the coordinates of\n-- the first and the second fountain.\n--\n-- Next follow n lines. The i-th of these lines contains integers xi and yi\n-- (\u2009-\u2009107\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009107) \u2014 the coordinates of the i-th flower.\n--\n-- It is guaranteed that all n\u2009+\u20092 points in the input are distinct.\n--\n-- Output\n-- Print the minimum possible value r1^2\u2009+\u2009r2^2. Note, that in this problem\n-- optimal answer is always integer.\n\n\n-- Found at: http://codeforces.com/contest/617/problem/C\n--\n\nmodule Main where\n\ntype Point = (Int,Int)\n\ndist2 :: Point -> Point -> Integer\ndist2 (x1,y1) (x2,y2) = (toInteger $ x1 - x2) ^ 2 + (toInteger $ y1 - y2) ^ 2\n\nbrute :: Point -> Point -> [Point] -> (Integer,Integer)\nbrute s1 s2 flowers = minimumWith (uncurry (+)) possibleRs\n where r12s = map (dist2 s1) flowers\n possibleRs = map (\\r12 -> bruteGivenR12 s1 s2 r12 flowers) r12s\n\nbruteGivenR12 s1 s2 r12 flowers = (r12,r22)\n where dist2s = map (\\flower -> (dist2 flower s1, dist2 flower s2)) flowers\n notCoveredByS1 = filter (\\(d12,d22) -> r12 < d12) dist2s\n r22s = map snd notCoveredByS1\n r22 = foldl max 0 r22s\n\nminimumWith :: (Ord b) => (a -> b) -> [a] -> a\nminimumWith _ [] = error \"List cannot be empty\"\nminimumWith f lst = minimumWith' (head lst, f (head lst)) lst\n where minimumWith' (xmin, _) [] = xmin\n minimumWith' (xmin, fxmin) (x:xs)\n | f x < fxmin = minimumWith' (x, f x) xs\n | otherwise = minimumWith' (xmin, fxmin) xs\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n line <- getLine\n rest <- getLines (n-1) -- sadly, not tail recursion\n return $ line:rest\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [n, s1x, s1y, s2x, s2y] = (map read . words) line1 :: [Int]\n flowerLines <- getLines n\n let flowers = map ((\\[x, y] -> (x,y)) . (map read) . words) flowerLines :: [(Int,Int)]\n let (r12,r22) = brute (s1x,s1y) (s2x,s2y) flowers\n putStrLn $ show (r12 + r22)\n"}, {"source_code": "module Main where\nimport GHC.Exts(sortWith)\n\ndist2 :: (Int,Int) -> (Int,Int) -> Integer\ndist2 (x1,y1) (x2,y2) = (toInteger $ x1 - x2) ^ 2 + (toInteger $ y1 - y2) ^ 2\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n line <- getLine\n rest <- getLines (n-1) -- sadly, not tail recursion\n return $ line:rest\n\ngrow1 :: (Integer,Integer) -> (Integer,Integer) -> (Integer,Integer)\ngrow1 (r2a,r2b) (r2toA,r2toB)\n | r2toA <= r2a = (r2a,r2b)\n | r2toB <= r2b = (r2a,r2b)\n | r2toA + r2b < r2a + r2toB = (r2toA,r2b)\n | otherwise = (r2a,r2toB)\n\nshrink :: (Integer,Integer) -> [(Integer,Integer)] -> (Integer,Integer)\nshrink (r2a,r2b) flowerR2s = foldl grow1 (r2aMin,r2bMin) abBoth\n where aOnly = filter (\\(r2toA,r2toB) -> r2toB > r2b) flowerR2s\n bOnly = filter (\\(r2toA,r2toB) -> r2toA > r2a) flowerR2s\n abBoth = filter (\\(r2toA,r2toB) -> r2toA <= r2a && r2toB <= r2b) flowerR2s\n r2aMin = maximum $ map fst aOnly\n r2bMin = maximum $ map snd bOnly\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [n, x1, y1, x2, y2] = (map read . words) line1 :: [Int]\n flowerLines <- getLines n\n let flowerCoords = map ((\\[x, y] -> (x,y)) . (map read) . words) flowerLines :: [(Int,Int)]\n let dist2A = map (dist2 (x1,y1)) flowerCoords\n dist2B = map (dist2 (x2,y2)) flowerCoords\n flowerR2s = zip dist2A dist2B\n let (r2a,r2b) = foldl grow1 (0,0) flowerR2s\n (r2a',r2b') = shrink (r2a,r2b) flowerR2s\n putStrLn $ show (r2a' + r2b')\n"}, {"source_code": "module Main where\n\ndist2 :: (Int,Int) -> (Int,Int) -> Integer\ndist2 (x1,y1) (x2,y2) = (toInteger $ x1 - x2) ^ 2 + (toInteger $ y1 - y2) ^ 2\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n line <- getLine\n rest <- getLines (n-1) -- sadly, not tail recursion\n return $ line:rest\n\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [n, x1, y1, x2, y2] = (map read . words) line1 :: [Int]\n flowerLines <- getLines n\n let flowerCoords = map ((\\[x, y] -> (x,y)) . (map read) . words) flowerLines :: [(Int,Int)]\n let dist2A = map (dist2 (x1,y1)) flowerCoords\n dist2B = map (dist2 (x2,y2)) flowerCoords\n let (rA2,rB2) = foldl compute (0,0) (zip dist2A dist2B)\n putStrLn $ show (rA2 + rB2)\n where compute (rA2,rB2) (r2toA,r2toB)\n | r2toA <= rA2 = (rA2,rB2)\n | r2toB <= rB2 = (rA2,rB2)\n | r2toA + rB2 < rA2 + r2toB = (r2toA,rB2)\n | otherwise = (rA2,r2toB)\n\n--where compute (rA2,rB2) (r2toA,r2toB)\n-- | r2toA <= rA2 = (rA2,rB2)\n-- | r2toB <= rB2 = (rA2,rB2)\n-- | r2toA < r2toB = (r2toA,rB2)\n-- | otherwise = (rA2,r2toB)\n"}, {"source_code": "module Main where\n\ndist2 :: (Int,Int) -> (Int,Int) -> Integer\ndist2 (x1,y1) (x2,y2) = (toInteger $ x1 - x2) ^ 2 + (toInteger $ y1 - y2) ^ 2\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n line <- getLine\n rest <- getLines (n-1) -- sadly, not tail recursion\n return $ line:rest\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [n, x1, y1, x2, y2] = (map read . words) line1 :: [Int]\n flowerLines <- getLines n\n let flowerCoords = map ((\\[xStr, yStr] -> (read xStr, read yStr)) . words) flowerLines :: [(Int,Int)]\n let dist2A = map (dist2 (x1,y1)) flowerCoords\n dist2B = map (dist2 (x2,y2)) flowerCoords\n let (rA2,rB2) = foldl compute (0,0) (zip dist2A dist2B)\n putStrLn $ show (rA2 + rB2)\n where compute (rA2,rB2) (r2toA,r2toB)\n | r2toA <= rA2 = (rA2,rB2)\n | r2toB <= rB2 = (rA2,rB2)\n | r2toA < r2toB = (r2toA,rB2)\n | otherwise = (rA2,r2toB)\n"}], "src_uid": "5db9c5673a04256c52f180dbfca2a52f"} {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\nsolve :: [Integer] -> Integer\nsolve [x] = 1\nsolve (x:xs) = \n let\n k = x - 1\n n = sum(xs) + k\n in\n ((newton n k) * (solve xs)) `mod` 1000000007\n\nnewton n k = fac n `div` (fac k * fac (n - k))\n\nfac 0 = 1\nfac n = n * (fac (n - 1))\n\nmain = do\n k <- readInt <$> getLine\n gs <- reverse <$> forM [1..k] (const (fromIntegral . readInt <$> getLine))\n print $ solve gs\n \n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nf::Integer->Integer\nf n = product [1..n]\n\nmain= do\n\tgetLine \n\tt<- map read. words <$> getContents::IO [Integer]\n\tlet n = sum t\n\tlet ans1 = product ( map f t )\n\tlet ans2 = f n\n \tlet ans = div ans2 ans1\n\tlet t1 = product $ scanl1 (+) t\n\tlet t2 = product t\n\tprint $ mod (div (ans *t2) t1) 1000000007\n\n\t"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Array.IArray as IA \nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\nsolve :: [Int] -> Integer\nsolve [x] = 1\nsolve (x:xs) = \n let\n k = x - 1\n n = sum(xs) + k\n in\n ((newton n k) * (solve xs)) `mod` 1000000007\n\nnewton n k = fac n `div` (fac k * fac (n - k))\n\nfactorials :: IA.Array Int Integer\nfactorials = IA.listArray (0, 1000) $ L.scanl (*) 1 [1..1000]\n\nfac :: Int -> Integer\nfac x = factorials IA.! x\n\nmain = do\n !k <- readInt <$> getLine\n !gs <- reverse <$> forM [1..k] (const (readInt <$> getLine))\n print $ solve gs\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nf::Integer->Integer\nf n = product [1..n]\n\nmain= do\n\tgetLine \n\tt<- map read. words <$> getContents::IO [Integer]\n\tlet n = sum t\n\tlet ans1 = product ( map f t )\n\tlet ans2 = f n\n \tlet ans = div ans2 ans1\n\tprint ans\n\tlet t1 = product $ scanl1 (+) t\n\tlet t2 = product t\n\tprint $ mod (div (ans *t2) t1) 1000000007\n\n\t"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nf::Integer->Integer\nf n = product [1..n]\n\nmain= do\n\tgetLine \n\tt<- map read. words <$> getContents::IO [Integer]\n\tlet n = sum t\n\tlet ans1 = product ( map f t )\n\tlet ans2 = f n\n \tlet ans = div ans2 ans1\n\tlet t1 = product $ scanl1 (+) t\n\tlet t2 = product t\n\tprint $ div (ans *t2) t1\n\n\t"}], "src_uid": "faf2c92c3a61ba5e33160bc7a18ad928"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t (getLine >> getLine >>= print . solve . map read . words)\n\nsolve :: [Int] -> Int\nsolve l = minimum $ zipWith (-) (tail x) x\n where\n x = sort l\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n arr <- sort <$> map (read) <$> words <$> getLine\n print $ f arr\n\nf :: [Int] -> Int\nf (x:y:[]) = y - x\nf (x:y:xs) = min (y - x) (f (y:xs))"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n _ <- getLine\n as <- map read . words <$> getLine\n let as' = sort as\n print . minimum $ zipWith (-) (tail as') as'\n"}, {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n print $ minimum $ zipWith subtract <*> tail $ sort as"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (sort)\n\nmaxInt = maxBound :: Int\n\nminAbsDiff z (x, y) = min z $ abs (x - y)\n\nreadLine = read <$> getLine\n\ngetMinDiff xs = \n foldl minAbsDiff maxInt (zip ys (tail ys)) where ys = sort xs \n\ngetAthletes =\n readLine >> (map read) . words <$> getLine\n\nmain =\n readLine >>= \\t ->\n replicateM_ t (getMinDiff <$> getAthletes >>= print)"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_\n t\n (do getLine\n s <- solve . map read . words <$> getLine\n print s)\n\nsolve :: [Int] -> Int\nsolve l = minimum $ zipWith (-) (tail x) x\n where\n x = sort l\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/B\n\nimport Control.Monad ( replicateM_ )\n\n\nhonestCoach :: [Int] -> Int\nhonestCoach = minSeparation . quickSort\n\n\nquickSort :: Ord a => [a] -> [a]\nquickSort [] = []\nquickSort [x] = [x]\nquickSort a = quickSort l ++ pivot : quickSort r\n where l = filter (<=pivot) rest\n r = filter ( >pivot) rest\n (pivot : rest) = a\n\n\nminSeparation :: (Ord a, Num a) => [a] -> a\nminSeparation a = minimum $ zipWith subtract a (tail a)\n\n\nreadInput :: IO [Int]\nreadInput = getLine >> map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (honestCoach <$> readInput >>= print)\n"}, {"source_code": "import Control.Monad ( replicateM_ )\n\n\nreadInput = getLine >> (map read . words <$> getLine)\n\nhonestCoach :: [Int] -> Int\nhonestCoach s = minDiff (quickSort s)\n\nquickSort [] = []\nquickSort [x] = [x]\nquickSort a = quickSort l ++ pivot:quickSort r\n where l = filter (<=pivot) rest\n r = filter ( >pivot) rest\n (pivot:rest) = a\n\nminDiff a = foldr min maxBound $ map (uncurry subtract) $ zip a (tail a)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (honestCoach <$> readInput >>= print)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\tgetLine\n\t\ta<- sort<$> map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ minimum $ zipWith (\\c d-> c-d) (tail a) a\n\t\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\t\n\n"}, {"source_code": "import Data.List (sort)\nimport Data.Traversable (for)\n\nsolveCase :: [Int] -> Int\nsolveCase li = let sli = sort li in minimum $ zipWith (-) (tail sli) sli\n\nmain :: IO ()\nmain = do\n nCases <- fmap read getLine :: IO Int\n _ <- for [1..nCases] $ \\_ -> do\n _ <- fmap read getLine :: IO Int\n s <- fmap (map read . words) getLine\n print $ solveCase s\n return ()\n"}], "negative_code": [], "src_uid": "d2669f85bdb59715352c6bc3d7ba9652"} {"source_code": "{-\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmove :: [Int] -> Char -> [Int]\nmove [x,y] c = case c of\n 'L' -> [x,y-1]\n 'R' -> [x,y+1]\n 'U' -> [x-1,y]\n 'D' -> [x+1,y]\n\nprocess 0 = return ()\nprocess t = do\n [n,m] <- getIntList\n cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n let delta = scanl (\\p c -> (move p c)) [0,0] cmds\n let bound = scanl (\\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta\n let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]\n let yyy = filter (\\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx\n let [x0,x1,y0,y1] = bound !! ((length yyy) -1)\n putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show\n\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n", "positive_code": [{"source_code": "{-\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmove :: [Int] -> Char -> [Int]\nmove [x,y] c = case c of\n 'L' -> [x,y-1]\n 'R' -> [x,y+1]\n 'U' -> [x-1,y]\n 'D' -> [x+1,y]\n _ -> [x,y]\n\nprocess 0 = return ()\nprocess t = do\n [n,m] <- getIntList\n --cmds <- getLine\n cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n let delta = scanl (\\p c -> (move p c)) [0,0] cmds\n let bound = scanl (\\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta\n let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]\n let yyy = filter (\\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx\n let [x0,x1,y0,y1] = bound !! ((length yyy) -1)\n putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show\n\n\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "-- https://codeforces.com/contest/1607/problem/E\n\nmove command (row, col, minRow, maxRow, minCol, maxCol)\n | command == 'U' = (row-1, col, min (row-1) minRow, maxRow, minCol, maxCol)\n | command == 'D' = (row+1, col, minRow, max (row+1) maxRow, minCol, maxCol)\n | command == 'L' = (row, col-1, minRow, maxRow, min (col-1) minCol, maxCol)\n | command == 'R' = (row, col+1, minRow, maxRow, minCol, max (col+1) maxCol)\n | otherwise = (row, col, minRow, maxRow, minCol, maxCol)\n\nsolve _ (_,_, minRow,_, minCol,_) [] = show(2-minRow) ++ \" \" ++ show(2-minCol)\nsolve (height, width) (row, col, minRow, maxRow, minCol, maxCol) (command:rest)\n | newMaxCol-newMinCol + 1 > width || newMaxRow-newMinRow + 1 > height =\n if command == 'U' then show(1-newMinRow)++\" \"++show(2-newMinCol) else\n if command == 'L' then show(2-newMinRow)++\" \"++show(1-newMinCol) else\n show(2-newMinRow)++\" \"++show(2-newMinCol)\n | otherwise = solve (height, width) newPos rest\n where\n newPos = move command (row, col, minRow, maxRow, minCol, maxCol)\n (_, _, newMinRow, newMaxRow, newMinCol, newMaxCol) = newPos\n\nrun 0 = return 0\nrun n = do\n size <- words <$> getLine\n commands <- getLine\n putStrLn $ solve (read $ size!!0, read $ size!!1) (1,1,1,1,1,1) commands\n run $ n-1\nmain = getLine >>= run . read\n"}, {"source_code": "-- https://codeforces.com/contest/1607/problem/E\n\n-- move :: Char -> (Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int)\nmove command (row, col, minRow, maxRow, minCol, maxCol)\n | command == 'U' = (row-1, col, min (row-1) minRow, maxRow, minCol, maxCol)\n | command == 'D' = (row+1, col, minRow, max (row+1) maxRow, minCol, maxCol)\n | command == 'L' = (row, col-1, minRow, maxRow, min (col-1) minCol, maxCol)\n | command == 'R' = (row, col+1, minRow, maxRow, minCol, max (col+1) maxCol)\n | otherwise = (row, col, minRow, maxRow, minCol, maxCol)\n\n-- solve :: (Int, Int) -> (Int, Int, Int, Int, Int, Int) -> String -> String\nsolve _ (_, _, minRow, _, minCol, _) [] = show(2-minRow)++\" \"++show(2-minCol)\nsolve (height, width) (row, col, minRow, maxRow, minCol, maxCol) (command:rest)\n | newMaxCol-newMinCol+1>width || newMaxRow-newMinRow+1>height =\n if command == 'U' then show(1-newMinRow)++\" \"++show(2-newMinCol) else\n if command == 'L' then show(2-newMinRow)++\" \"++show(1-newMinCol) else\n show(2-minRow)++\" \"++show(2-minCol)\n | otherwise = solve (height, width) newPos rest\n where\n newPos = move command (row, col, minRow, maxRow, minCol, maxCol)\n (_, _, newMinRow, newMaxRow, newMinCol, newMaxCol) = newPos\n\nrun 0 = return 0\nrun n = do\n size <- words <$> getLine\n commands <- getLine\n putStrLn $ solve (read $ size!!0, read $ size!!1) (1,1,1,1,1,1) commands\n run $ n-1\nmain = getLine >>= run . read\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char (isSpace)\nimport Data.Maybe (fromJust)\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain :: IO ()\nmain = do\n t <- fst . fromJust . B.readInt <$> B.getLine\n replicateM_ t $ do\n [n, m] <- readInts\n s <- strip . B.unpack <$> B.getLine\n let pos = scanl bound (0, 0, 0, 0) $ scanl move (0, 0) s\n (x, _, y, _) = head $ dropWhile (\\(a, b, c, d) -> b - a >= n || d - c >= m) $ reverse pos\n B.putStrLn $ B.pack $ show (1 - x) ++ \" \" ++ show (1 - y)\n where\n move (x, y) c\n | c == 'R' = (x, y + 1)\n | c == 'L' = (x, y - 1)\n | c == 'U' = (x - 1, y)\n | c == 'D' = (x + 1, y)\n bound (x_min, x_max, y_min, y_max) (x, y) = (min x_min x, max x_max x, min y_min y, max y_max y)\n\nstrip :: String -> String\nstrip = f . f\n where\n f = reverse . dropWhile isSpace\n"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, m] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let move (x, y) 'L' = (x, y - 1)\r\n move (x, y) 'R' = (x, y + 1)\r\n move (x, y) 'U' = (x - 1, y)\r\n move (x, y) 'D' = (x + 1, y)\r\n move xy 'O' = xy\r\n move _ _ = error \"!\"\r\n go ((x, y), (x1, y1, x2, y2)) c = ((xy, z), (ok, start)) where\r\n xy@(x', y') = move (x, y) c\r\n z@(x1', y1', x2', y2') = (min x1 x', min y1 y', max x2 x', max y2 y')\r\n ok = y2' - y1' < m && x2' - x1' < n\r\n start = (-x1', -y1')\r\n (x, y) = snd $ last $ takeWhile fst $ snd $ mapAccumL go ((0, 0), (0, 0, 0, 0)) $ 'O':s\r\n putStrLn $ show (x + 1) ++ \" \" ++ show (y + 1)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "{-\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmove :: [Int] -> Char -> [Int]\nmove [x,y] c = case c of\n 'L' -> [x,y-1]\n 'R' -> [x,y+1]\n 'U' -> [x-1,y]\n 'D' -> [x+1,y]\n _ -> [x,y]\n\nprocess 0 = return ()\nprocess t = do\n [n,m] <- getIntList\n --cmds <- getLine\n --cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n cmds0 <- BS.unpack <$> BS.getLine\n let cmds = init cmds0\n let cmds2 = takeWhile (not . isSpace) cmds\n let c1 = map ord cmds\n let c2 = map ord cmds2\n\n let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)\n putStr (if (t<=4) then ((tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show) ++ \"\\n\") else if (cmds==cmds2) then \"\" else ((show c1) ++ \"###\" ++ (show c2) ++ \"\\n\"))\n\n --let delta = scanl (\\p c -> (move p c)) [0,0] cmds\n --let bound = scanl (\\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta\n --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]\n --let yyy = filter (\\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx\n --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)\n --putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show\n\n\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "{-\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmove :: [Int] -> Char -> [Int]\nmove [x,y] c = case c of\n 'L' -> [x,y-1]\n 'R' -> [x,y+1]\n 'U' -> [x-1,y]\n 'D' -> [x+1,y]\n _ -> [x,y]\n\nprocess 0 = return ()\nprocess t = do\n [n,m] <- getIntList\n --cmds <- getLine\n --cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n cmds <- BS.unpack <$> BS.getLine\n let cmds2 = takeWhile (not . isSpace) cmds\n let c1 = map ord cmds\n let c2 = map ord cmds2\n\n let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)\n putStr (if (t<=4) then ((tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show) ++ \"\\n\") else if (cmds==cmds2) then \"\" else ((show c1) ++ \"###\" ++ (show c2) ++ \"\\n\"))\n\n --let delta = scanl (\\p c -> (move p c)) [0,0] cmds\n --let bound = scanl (\\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta\n --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]\n --let yyy = filter (\\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx\n --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)\n --putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show\n\n\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "{-\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmove :: [Int] -> Char -> [Int]\nmove [x,y] c = case c of\n 'L' -> [x,y-1]\n 'R' -> [x,y+1]\n 'U' -> [x-1,y]\n 'D' -> [x+1,y]\n _ -> [x,y]\n\nprocess 0 = return ()\nprocess t = do\n [n,m] <- getIntList\n --cmds <- getLine\n --cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n cmds <- BS.unpack <$> BS.getLine\n let cmds2 = takeWhile (not . isSpace) cmds\n let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)\n putStr (if (t<=4) then ((tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show) ++ \"\\n\") else if (cmds==cmds2) then \"\" else (cmds ++ \"###\" ++ cmds2 ++ \"\\n\"))\n\n --let delta = scanl (\\p c -> (move p c)) [0,0] cmds\n --let bound = scanl (\\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta\n --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]\n --let yyy = filter (\\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx\n --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)\n --putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show\n\n\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "{-\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmove :: [Int] -> Char -> [Int]\nmove [x,y] c = case c of\n 'L' -> [x,y-1]\n 'R' -> [x,y+1]\n 'U' -> [x-1,y]\n 'D' -> [x+1,y]\n\n{-\ngetMaxCmds :: [[Int]] -> [Int] -> Int -> Int -> [Int]\ngetMaxCmds [] curr n m = curr\ngetMaxCmds ([x0,x1,y0,y1]:delta) curr n m\n | (x1-x0+1 <= n) && (y1-y0+1 <= m) = getMaxCmds delta [x0,x1,y0,y1] n m\n | otherwise = curr\n-} \n\nprocess 0 = return ()\nprocess t = do\n [n,m] <- getIntList\n cmds <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n --let delta = scanl (\\p c -> (move p c)) [0,0] cmds\n --let bound = scanl (\\[x0,x1,y0,y1] [x,y] -> [min x0 x, max x1 x, min y0 y, max y1 y]) [0,0,0,0] delta\n --let xxx = [[x1-x0+1, y1-y0+1] | [x0,x1,y0,y1] <- bound]\n --let yyy = filter (\\x -> ((x!!0)<=n) && ((x!!1)<=m) ) xxx\n --let [x0,x1,y0,y1] = bound !! ((length yyy) -1)\n --let [x0,x1,y0,y1] = getMaxCmds bound [0,0,0,0] n m\n -- putStrLn $ tail $ [(-x0+1), (-y0+1)] >>= (' ':) . show\n --let [k0,k1] = last delta \n let [x0,y0] = [[-2,-1],[-1,0],[0,-1],[0,0]] !! (mod (t-1) 4)\n putStr $ show (-x0+1)\n putStr \" \"\n putStrLn $ show (-y0+1)\n\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "-- https://codeforces.com/contest/1607/problem/E\n\n-- move :: Char -> (Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int)\nmove command (row, col, minRow, maxRow, minCol, maxCol)\n | command == 'U' = (row-1, col, min (row-1) minRow, maxRow, minCol, maxCol)\n | command == 'D' = (row+1, col, minRow, max (row+1) maxRow, minCol, maxCol)\n | command == 'L' = (row, col-1, minRow, maxRow, min (col-1) minCol, maxCol)\n | command == 'R' = (row, col+1, minRow, maxRow, minCol, max (col+1) maxCol)\n | otherwise = (row, col, minRow, maxRow, minCol, maxCol)\n\n-- solve :: (Int, Int) -> (Int, Int, Int, Int, Int, Int) -> String -> String\nsolve _ (_, _, minRow, _, minCol, _) [] = show(2-minRow)++\" \"++show(2-minCol)\nsolve (height, width) (row, col, minRow, maxRow, minCol, maxCol) (command:rest)\n | newMaxCol-newMinCol+1>width || newMaxRow-newMinRow+1>height =\n if command == 'U' then show(1-newMinRow)++\" \"++show(2-newMinCol) else\n if command == 'L' then show(2-newMinRow)++\" \"++show(1-newMinCol) else\n show(2-minRow)++\" \"++show(2-minCol)\n | otherwise = solve (height, width) newPos rest\n where\n newPos = move command (row, col, minRow, maxRow, minCol, maxCol)\n (_, _, newMinRow, newMaxRow, newMinCol, newMaxCol) = newPos\n\nrun 0 = return 0\nrun n = do\n size <- words <$> getLine\n commands <- getLine\n print $ solve (read $ size!!0, read $ size!!1) (1,1,1,1,1,1) commands\n run $ n-1\nmain = getLine >>= run . read\n"}], "src_uid": "585bb4a040144da39ed240366193e705"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bits\nimport Data.List\n\nmain = do\n getLine\n as <- map read . words <$> getLine\n print $ solve as\n\nsolve :: [Integer] -> Integer\nsolve as = sum $ (^ 2) <$> makeList [length $ filter ((> 0) . (.&. bit i)) as | i <- [0 .. 20]]\n\nmakeList vs\n | all (<= 0) vs = []\n | otherwise = sum (zipWith (\\a e -> toInteger (fromEnum (a > 0)) * bit e) vs [0 ..]) : makeList (subtract 1 <$> vs)\n", "positive_code": [{"source_code": "import Data.Bits\n--import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Integer\nsolve xs = sum $ map ((^2).toInt) ns\n where\n bs = [ length $ filter (`testBit` n) xs | n <- [0..19::Int] ]\n f :: Int -> [Bool]\n f n = replicate n True ++ repeat False\n bs' = map f bs\n ns = takeWhile or $ transpose bs'\n\ntoInt :: [Bool] -> Integer\ntoInt bs = foldr (\\(b,i) n -> if b then setBit n i else n) 0 $ zip bs [0..]\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Tuple\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nstep ls =\n let count = sum $ (`mod` 2) <$> ls\n rems = (`div` 2) <$> ls\n in (count, rems)\n\n_getCounts acc curr ls\n | curr > (1048576 :: Integer) = acc\n | otherwise =\n let (count, rems) = step ls\n !next = 2 * curr\n acc1 = (curr, count) : acc\n in _getCounts acc1 next rems\ngetCounts = _getCounts [] 1\n\n_processCounts :: Integer -> Integer -> Integer -> [(Integer, Integer)] -> Integer\n_processCounts !acc !val !lv = \\case\n [] -> acc\n (x, count) : rest ->\n let acc1 = acc + val^2 * (count - lv)\n val1 = val - x\n in _processCounts acc1 val1 count rest\n\nprocessCounts :: [(Integer, Integer)] -> Integer\nprocessCounts counts =\n let start = sum $ fst <$> counts\n in _processCounts 0 start 0 counts\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Integer]\n counts = sortOn snd $ getCounts vals\n res = processCounts counts\n putStrLn $ show res\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bits\n\nmain = do\n getLine\n (a : as) <- map read . words <$> getLine\n print $ solve a as\n\nsolve :: Integer -> [Integer] -> Integer\nsolve a [] = a ^ 2\nsolve a (b : bs) = (a .&. b) ^ 2 + solve (a .|. b) bs\n"}, {"source_code": "import Data.Bits\n--import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = sum $ map ((^2).toInt) ns\n where\n bs = [ length $ filter (`testBit` n) xs | n <- [0..19::Int] ]\n f :: Int -> [Bool]\n f n = replicate n True ++ repeat False\n bs' = map f bs\n ns = takeWhile or $ transpose bs'\n\ntoInt :: [Bool] -> Int\ntoInt bs = foldr (\\(b,i) n -> if b then setBit n i else n) 0 $ zip bs [0..]\n"}], "src_uid": "56fbdca75b69bf41d2a45a1dfe81d022"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map digitToInt <$> getLine\n putStrLn.concat.map show $ solve n xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs = minimum [rotate i $ map(y+%)xs|y<-[0..9],i<-[0..n-1]]\n\nrotate :: Int -> [Int] -> [Int]\nrotate n xs | (ys,zs)<-splitAt n xs = zs ++ ys\n\n(+%) :: Int -> Int -> Int\nx +% y = case (x + y) of\n xy | xy < 10 -> xy\n | otherwise -> xy - 10\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.List as List\nimport qualified Data.Char as Char\n\nsolve :: Int -> [Int] -> [Int]\nsolve n arr = List.foldl1' min (pos >>= add)\n where\n \tshift s = let (x,y) = List.splitAt s arr\n \t in y ++ x\n \tadd x = map (\\i -> map ((`mod` 10) . (i+)) x) [0..9]\n \tpos = map shift [1..n]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n digs <- map Char.digitToInt <$> getLine\n putStrLn $ map Char.intToDigit $ solve n digs"}, {"source_code": "import Data.Char\n\nrotate :: [a] -> Int -> [a]\nrotate xs n = (drop n xs) ++ (take n xs)\n\nupdate :: String -> Int -> Int -> String\nupdate s shift inc = map (\\c -> intToDigit (((digitToInt c) + inc) `mod` 10))\n (rotate s ((length s) - shift))\n\nsolve' :: String -> Int -> [String]\nsolve' s n = do\n shift <- [0..n]\n inc <- [0..9]\n return (update s shift inc)\n\nsolve :: String -> Int -> String\nsolve s n = minimum $ solve' s n\n\nmain :: IO ()\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ solve s (read n :: Int)\n"}, {"source_code": "rotate :: Int -> [Int] -> [Int]\nrotate n number = drop n number ++ take n number\n\nincrement :: Int -> [Int] -> [Int]\nincrement n number = map f number\n where f x = mod (x + n) 10\n\nallRotations :: [Int] -> [[Int]]\nallRotations n = map (\\x -> rotate x n) [1..length n]\n\nallIncrements :: [Int] -> [[Int]]\nallIncrements n = map (\\x -> increment x n) [0..9]\n\nsolve :: [Int] -> [Int]\nsolve = minimum . concat . map allIncrements . allRotations\n\nreadInt :: Char -> Int\nreadInt '0' = 0\nreadInt '1' = 1\nreadInt '2' = 2\nreadInt '3' = 3\nreadInt '4' = 4\nreadInt '5' = 5\nreadInt '6' = 6\nreadInt '7' = 7\nreadInt '8' = 8\nreadInt '9' = 9\n\n\nmain = do\n getLine\n getLine >>= putStrLn . concat . map show . solve . fmap (\\c -> readInt c)\n"}, {"source_code": "import Data.Char\n\nmain = getContents >>= putStrLn . solve . last . words\n\nsolve :: String -> String\nsolve s = foldl1 min [add k (drop i s ++ take i s) | i <- [1 .. length s], k <- [0 .. 9]]\n\nadd v s = map (intToDigit . (`mod` 10) . (+ v) . digitToInt) s\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.List as List\nimport qualified Data.Char as Char\n\narrToInt :: [Int] -> Integer\narrToInt = List.foldl' go 0\n where go x y = 10 * x + toInteger y\n\nsolve :: Int -> [Int] -> [Int]\nsolve n arr = snd $ List.foldl1' min $ map (\\x -> (arrToInt x, x)) $ (pos >>= add)\n where\n \tshift s = let (x,y) = List.splitAt s arr\n \t in y ++ x\n \tadd x = map (\\i -> map ((`mod` 10) . (i+)) x) [0..9]\n \tpos = map shift [1..n]\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n digs <- map Char.digitToInt <$> getLine\n putStrLn . show $ map Char.intToDigit $ solve n digs"}], "src_uid": "6ee356f2b3a4bb88087ed76b251afec2"} {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nsolve :: [Char] -> Char -> Int\r\nsolve s t = maximum $ map snd $ filter (\\(c, v) -> c == t) $ s' `zip` ds\r\n where s' = s ++ takeWhile (/= 'g') s\r\n ds = scanr add 0 s'\r\n add d v = case d of\r\n 'g' -> 0\r\n _ -> v + 1\r\n\r\nhandleTestCase :: IO ()\r\nhandleTestCase = do\r\n [_, t] <- words <$> getLine\r\n s <- getLine\r\n print $ solve s (head t)\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberTests <- read <$> getLine\r\n replicateM_ numberTests handleTestCase\r\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n-- {-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\nsolve :: Int -> Char -> B8.ByteString -> Int\nsolve n c str = L.maximum $ do\n let str2 = B8.concat [str, str]\n let gPositions = IS.fromList $ B8.elemIndices 'g' str2\n tracingM \"str\" str\n tracingM \"rPositions\" gPositions\n cIndex <- B8.elemIndices c str\n tracingM \"cIndex\" cIndex\n let rIndex = fromJust $ IS.lookupGE cIndex gPositions\n return $ rIndex - cIndex\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n line <- B8.getLine\n let [ns, cs] = L.filter (not . (== 0) . B8.length) $ B8.splitWith isSpace line\n let (n, c) = (readIntB8 ns, B8.head cs)\n s <- B8.getLine <&> B8.filter isAlphaNum\n let answer = solve n c s\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "9d3ee1b292a2402bb2204ab85dcab587"} {"source_code": "import System.IO\r\n\r\nsolve :: [Int] -> [String]\r\nsolve ~(n:xs) = go 0 n xs where\r\n go l r _ | l + 1 == r = [\"! \" ++ show l]\r\n go l r ~(x:xs) = (\"+ \" ++ show out) : go (l' + out) (r' + out) xs where\r\n m = (r + l) `div` 2\r\n out = n - m `mod` n\r\n (l', r') | x == l `div` n = (l, m)\r\n | otherwise = (m, r)\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout LineBuffering\r\n interact $ unlines . solve . map read . lines\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\nimport Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmkQuery :: Int -> Builder\nmkQuery c = string7 \"+ \" <> putInts [c] <> flush\n\nsolve :: Int -> Int -> Int -> SP Builder\nsolve n lv rv = if lv == rv\n then pure $ string7 \"! \" <> putInts [lv]\n else let\n mv = lv + (rv - lv) `quot` 2\n c = (n - 1 - mv `rem` n)\n in (mkQuery c <>) <$> do\n ~[resp] <- getInts 1\n let\n nr = n * resp\n nlv = max nr (lv + c)\n nrv = min (nr + n - 1) (rv + c)\n solve n nlv nrv\n\nmainFun :: SP Builder\nmainFun = do\n ~[n] <- getInts 1\n solve n 1 (n - 1)\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import System.IO\r\n\r\nsolve :: [Int] -> [String]\r\nsolve ~(n:xs) = go 1 n 0 0 0 xs where\r\n go l r mul _ total _ | l + 1 == r = [\"! \" ++ show (l + total)]\r\n go l r mul off total ~(x:xs) = (\"+ \" ++ show out) : rest where\r\n d = (r - l) `div` 2\r\n d' = (r - l + 1) `div` 2\r\n out = off + d\r\n total' = total + out\r\n rest | x == mul = go l (l + d') x 0 total' xs\r\n | otherwise = go (l + d') r x (n - d) total' xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout LineBuffering\r\n interact $ unlines . solve . map read . lines\r\n"}], "negative_code": [{"source_code": "import System.IO\r\n\r\nsolve :: [Int] -> [String]\r\nsolve ~(n:xs) = go 1 n 0 0 0 xs where\r\n go l r mul _ total _ | l + 1 == r = [\"! \" ++ show (l + total)]\r\n go l r mul off total ~(x:xs) = (\"+ \" ++ show (off + d)) : rest where\r\n d = (r - l) `div` 2\r\n total' = total + off + d\r\n rest | x == mul = go l (l + d) x 0 total' xs\r\n | otherwise = go (l + d) r x (n - d) total' xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout LineBuffering\r\n interact $ unlines . solve . map read . lines\r\n"}], "src_uid": "ad36ef40ef4888b69ee9635e924c65ab"} {"source_code": "import Data.Int (Int64)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let ans = solve n\n print $ length ans\n putStrLn $ unwords $ map show ans\n\nsolve :: Int64 -> [Int64]\nsolve n = if foldl (\\x y -> x * y `rem` n) 1 nums == 1 then nums else init nums\n where\n nums = filter ((== 1) . gcd n) [1 .. n - 1]\n", "positive_code": [{"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport Data.List(delete)\r\n\r\ninv :: Integer -> Integer -> Maybe Integer\r\ninv n x = case bezout n x of \r\n\tJust (i, j) -> if i*n+j*x == 1 then Just $ mod j n else Nothing\r\n\tNothing -> Nothing\r\n\r\nbezout :: Integer -> Integer -> Maybe (Integer, Integer)\r\nbezout _ 0 = Nothing\r\nbezout _ 1 = Just (0, 1)\r\nbezout a b = do\r\n\t(x', y') <- bezout b r\r\n\treturn $ (y', x' - y' * q)\r\n\twhere (q, r) = a `divMod` b\r\n\r\nmain = do \r\n\tn <- getLine >>= return . read :: IO Integer\r\n\tputStrLn $ showResult $ result n\r\n\r\nresult :: Integer -> [Integer]\r\nresult n = list' where \r\n\taux (x:xs) = case inv n x of \r\n\t\tJust y\r\n\t\t\t| y == x -> x:aux xs\r\n\t\t\t| otherwise -> x:aux xs\r\n\t\tNothing -> aux xs\r\n\taux [] = []\r\n\r\n\tlist' = if prodMod list == 1 then list else delete (prodMod list) list\r\n\r\n\tprodMod [] = 1\r\n\tprodMod (x:xs) = mod (x * prodMod xs) n\r\n\tlist = 1 : aux [2..(n-1)]\r\n\r\nshowResult :: [Integer] -> String\r\nshowResult list = (show $ length list) ++ \"\\n\" ++ aux list where\r\n\taux (x:xs) = show x ++ \" \" ++ aux xs\r\n\taux [] = []\r\n"}, {"source_code": "to_int :: String -> Integer\r\nto_int = read\r\n \r\nsolve n = do\r\n print $ length ans\r\n putStrLn $ unwords $ map show ans\r\n where \r\n filtered = filter (\\x -> gcd x n == 1) [1..(n-1)] \r\n prod = foldl (\\x y -> (x * y) `mod` n) 1 filtered\r\n ans =\r\n if prod /= 1\r\n then filter (\\x -> x /= prod) filtered\r\n else filtered\r\n \r\nmain :: IO()\r\nmain = do\r\n n <- getLine\r\n solve $ to_int n"}, {"source_code": "to_int :: String -> Integer\r\nto_int = read\r\n\r\nsolve n = do\r\n print $ length ans\r\n putStrLn $ unwords $ map show ans\r\n where \r\n arr = [1..(n-1)] \r\n filtered = filter (\\x -> gcd x n == 1) arr\r\n prod = foldl (\\x y -> (x * y) `mod` n) 1 filtered\r\n ans =\r\n if prod /= 1\r\n then filter (\\x -> x /= prod) filtered\r\n else filtered\r\n\r\nmain :: IO()\r\nmain = do\r\n n <- getLine\r\n solve $ to_int n\r\n \r\n "}], "negative_code": [{"source_code": "to_int :: String -> Integer\r\nto_int = read\r\n\r\nsolve n = do\r\n print $ length ans\r\n putStrLn $ unwords $ map show ans\r\n where \r\n arr = [1..(n-1)] \r\n filtered = filter (\\x -> gcd x n == 1) arr\r\n prod = foldl (\\x y -> (x * y) `mod` n) 0 filtered\r\n ans =\r\n if prod /= 1\r\n then filter (\\x -> x /= prod) filtered\r\n else filtered\r\n\r\nmain :: IO()\r\nmain = do\r\n n <- getLine\r\n solve $ to_int n\r\n \r\n "}, {"source_code": "main :: IO ()\nmain = do\n n <- read <$> getLine\n let ans = solve n\n print $ length ans\n putStrLn $ unwords $ map show ans\n\nsolve :: Int -> [Int]\nsolve n = if foldl (\\x y -> x * y `rem` n) 1 nums == 1 then nums else init nums\n where\n nums = filter ((== 1) . gcd n) [1 .. n - 1]\n"}, {"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\n\r\ninv :: Integer -> Integer -> Maybe Integer\r\ninv n x = case bezout n x of \r\n\tJust (i, j) -> if i*n+j*x == 1 then Just $ mod j n else Nothing\r\n\tNothing -> Nothing\r\n\r\nbezout :: Integer -> Integer -> Maybe (Integer, Integer)\r\nbezout _ 0 = Nothing\r\nbezout _ 1 = Just (0, 1)\r\nbezout a b = do\r\n\t(x', y') <- bezout b r\r\n\treturn $ (y', x' - y' * q)\r\n\twhere (q, r) = a `divMod` b\r\n\r\nmain = do \r\n\tn <- getLine >>= return . read :: IO Integer\r\n\tputStrLn $ showResult $ result n\r\n\r\nresult :: Integer -> [Integer]\r\nresult n = if (n > 2) && prodMod list > 1 then (n-1):list else list where \r\n\taux (x:xs) = case inv n x of \r\n\t\tJust _ -> x:aux xs\r\n\t\tNothing -> aux xs\r\n\taux [] = []\r\n\r\n\tprodMod [] = 1\r\n\tprodMod (x:xs) = mod (x * prodMod xs) n\r\n\tlist = 1 : aux [2..(n-2)]\r\n\r\nshowResult :: [Integer] -> String\r\nshowResult list = (show $ length list) ++ \"\\n\" ++ aux list where\r\n\taux (x:xs) = show x ++ \" \" ++ aux xs\r\n\taux [] = []\r\n"}], "src_uid": "d55afdb4a83aebdfce5a62e4ec934adb"} {"source_code": "\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport qualified Data.Array.Unboxed as Ar\nimport Data.Array.Unboxed (UArray)\n\ntype Long = Int\n\n\nsolveForI :: Int -> UArray Int Int -> Int -> IntMap Int\nsolveForI n sizes i\n | i == n = IM.singleton n 1\n | otherwise = IM.insert i (nextMax + 1) cache\n where\n cache = solveForI n sizes (i+1)\n nexts = filter (\\i1 -> sizes Ar.! i1 > sizes Ar.! i) $ takeWhile (<= n) $ map (* i) [2..]\n nextSizes = map (cache IM.!) nexts\n nextMax = maximum $ 0:nextSizes\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readWords\n sizes <- readWords\n print $ maximum $ IM.elems $ solveForI n (Ar.listArray (1,n) sizes) 1\n testCases (t-1)\n\ntest :: IntMap Int\ntest = solveForI 4 (Ar.listArray (1,4) [5,3,4,6]) 1\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n ss <- (map read.words) <$> getLine\n print $ solve n ss\n\nsolve :: Int -> [Int] -> Int\nsolve n ss = maximum cArr\n where\n sArr = mkSizeArray n ss\n pJArr = mkPossibleJumpsArray n sArr\n cArr = mkCostsArray n pJArr\n\nmkSizeArray :: Int -> [Int] -> Array Int Int\nmkSizeArray n ss = listArray (1,n) ss\n\nmkPossibleJumpsArray :: Int -> Array Int Int -> Array Int [Int]\nmkPossibleJumpsArray n sizeArray = listArray (1,n) $ map f [1..n]\n where\n f i =filter (\\j -> (sizeArray!j)>(sizeArray!i)) [i,2*i..n]\n\nmkCostsArray :: Int -> Array Int [Int] -> Array Int Int\nmkCostsArray n possibleJumpsArray = arr\n where\n arr = array (1,n) [ (i,g i) | i <- [n,n-1..1]]\n g i =1 + maximum (0:map (\\j -> arr!j) (possibleJumpsArray!i))\n"}], "negative_code": [], "src_uid": "0197047cab6d83a189a5c1eabf5b1dd3"} {"source_code": "import Control.Monad\n\ndata State = State { height :: Int, bag :: Int, canGo :: Bool }\n\ncontinue :: State -> Int -> Int -> State\ncontinue state@(State { height = h, bag = b, canGo = go }) step nextHeight\n | go == False = state\n | h + b + step < nextHeight = State { height = h, bag = b, canGo = False }\n | otherwise =\n let minHeight = max 0 (nextHeight - step)\n blockDiff = h - minHeight\n in State { height = nextHeight, bag = b + blockDiff, canGo = True }\n\ncanTraverse :: Int -> Int -> [Int] -> Bool\ncanTraverse blocks step heights =\n let start = State { height = (head heights), bag = blocks, canGo = True }\n columns = tail heights\n finalState = foldl (\\state -> continue state step) start columns\n in canGo finalState\n\nreadAndSolve :: Int -> IO String\nreadAndSolve _ = do\n [cols, blocks, step] <- readInts\n heights <- readInts\n return (if (canTraverse blocks step heights) then \"YES\" else \"NO\")\n where readInts = map (\\tok -> read tok :: Int) . words <$> getLine\n\nmain = do\n tests <- (\\str -> read str :: Int) <$> getLine\n results <- forM [1..tests] readAndSolve\n putStrLn . unlines $ results\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\tt <- readInt\n\treplicateM_ t $ do\n\t\t[ n, m, k ] <- readInts\n\t\ths <- readInts\n\t\tputStrLn $ which \"YES\" \"NO\" $ solve m k hs\n\nsolve _ _ [_] = True\nsolve m k (h1:h2:hs)\n\t| h1 >= max 0 ( h2 - k ) = let d = h1 - max 0 ( h2 - k ) in solve ( m + d ) k (h2:hs)\n\t| h1 + m >= max 0 ( h2 - k ) = let d = max 0 ( h2 - k ) - h1 in solve ( m - d ) k (h2:hs)\n\t| otherwise = False"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\tt <- readInt\n\treplicateM_ t $ do\n\t\t[ n, m, k ] <- readInts\n\t\ths <- readInts\n\t\tputStrLn $ which \"YES\" \"NO\" $ solve m k hs\n\nsolve m k [_] = True\nsolve m k (h1:h2:hs)\n\t| h1 >= h2 - k = let d = h1 - ( h2 - k ) in solve ( m + d ) k (h2:hs)\n\t| h1 + m >= h2 - k = let d = ( h2 - k ) - h1 in solve ( m - d ) k (h2:hs)\n\t| otherwise = False"}], "src_uid": "3f60e740d9a3ec14223b2b1f62c52f61"} {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n [n, l, v1, v2, k] <- fmap (map read . words) getLine\n print $ totalT n l v1 v2 k\n\ntotalT :: Float -> Float -> Float -> Float -> Float -> Float\ntotalT n l v1 v2 k = let { alpha = fromIntegral $ ceiling (n / k);\n beta = (v2 - v1) / (v2 + v1);\n t = l / (v2 + v1 * (alpha - 1) * (beta + 1));\n } in t * (alpha + alpha * beta - beta)\n", "positive_code": [{"source_code": "main = do\n ps@[n, l, v1, v2, k] <- (map read . words) `fmap` getLine :: IO [Int]\n let ps' = map fromIntegral ps :: [Double]\n print $ solve ps'\n\nsolve :: [Double] -> Double\nsolve [n, l, v1, v2, k] = t1 + x where\n m = fromIntegral (ceiling (n / k)) :: Double\n v3 = (v2 - v1) / (v2 + v1)\n x = l / (v2 + (m-1)*(v1 * (1+ v3)))\n t1 = (l - v2*x) / v1\n"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> Double -> Double\nsolve 1 v = 1\nsolve n v = let x = solve (n-1) v\n in (x*(v+1))/(2*x+v+1)\n\nmain :: IO ()\nmain = do\n [n,li,v1i,v2i,k] <- map read . words <$> getLine\n let l = realToFrac li\n v1 = realToFrac v1i\n v2 = realToFrac v2i\n v = v2/v1\n trips = (n+k-1) `div` k\n x = l * (solve trips v)\n putStrLn .show $ (x/v2) + ((l - x)/v1)\n -- putStrLn $ \"trips = \" ++ show trips ++ \" v = \" ++ show v\n -- putStrLn .show $ solve trips v\n"}], "negative_code": [{"source_code": "main = do\n ps@[n, l, v1, v2, k] <- (map read . words) `fmap` getLine :: IO [Int]\n let ps' = map fromIntegral ps :: [Double]\n print $ solve ps'\n\nsolve :: [Double] -> Double\nsolve [n, l, v1, v2, k] = t1 + x where\n m = fromIntegral (ceiling (n / k)) :: Double\n x = l / (v2 + (m-1)*(v1 + (v2-v1)/(v2+v1)))\n t1 = (m-1) * x * (1 + (v2-v1)/(v2+v1))"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> Double -> Double\nsolve 1 v = 1\nsolve n v = let x = solve (n-1) v\n in (x*(v+1))/(2*x+v+1)\n\nmain :: IO ()\nmain = do\n [n,li,v1i,v2i,k] <- map read . words <$> getLine\n let l = realToFrac li\n v = (realToFrac v2i) / (realToFrac v1i)\n trips = (n+k-1) `div` k\n x = l * (solve trips v)\n putStrLn .show $ (x/v) + (l - x)\n"}], "src_uid": "620a9baa531f0c614cc103e70cfca6fd"} {"source_code": "main = do\n\ta <- fmap (gao . read) getLine\n\tputStrLn $ show $ length a\n\tmapM_ (putStrLn . unwords . map show) a\n\ngao n = [[i, j] | m <- [div n 2], i <- [1 .. m], j <- [m + 1 .. n]]\n", "positive_code": [{"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ map (unwords.(map show)) $ [length a]:a\n where a = answer n\n answer n = [[x,y]|x<-[1..min (n-1) (div (n+3) 2)],\n y <- if x == 1 then [2..min n (div (n+3) 2)] else [div (n+5) 2..n]] "}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n if n == 1\n then print 0\n else do\n let m = n `div` 2\n print $ m * (n - m)\n putStrLn $ foldl1 (++) [(show x ++ \" \" ++ show y ++ \"\\n\") | x <- [1..m], y <- [m+1..n]]"}], "negative_code": [{"source_code": "main = do\n\ta <- fmap (gao . read) getLine\n\tputStrLn $ show $ length a\n\tmapM_ (putStrLn . unwords . map show) a\n\ngao 1 = []\ngao 2 = [[1, 2]]\ngao n = concat [[[1, i], [2, i]] | i <- [3 .. n]]\n"}, {"source_code": "main = do\n\ta <- fmap (gao . read) getLine\n\tputStrLn $ show $ length a\n\tmapM_ (putStrLn . unwords . map (show . succ)) a\n\ngao n = [[i, j] |\n\t\t\td <- takeWhile ( Int) . words) getLine\n print $ snd $ foldr' (\\next (min, cnt) -> (if next < min then next else min, if next > min then cnt + 1 else cnt)) (maxBound, 0) a\n", "positive_code": [{"source_code": "import Control.Monad ( void, replicateM_ )\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n void $ getLine\n a <- fmap (fmap (read :: String -> Int) . words) getLine\n print $ snd $ foldr (\\next (min, cnt) -> (if next < min then next else min, if next > min then cnt + 1 else cnt)) (maxBound, 0) a"}, {"source_code": "import Control.Monad\n\nconstructRising :: Int -> [Int] -> [Int]\nconstructRising n [] = [n]\nconstructRising n (x : xs)\n | n >= x = n : x : xs\n | otherwise = constructRising n xs\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n print =<< (n-) . length . foldl (flip ($)) [] . map (constructRising . (read :: String -> Int) ). words<$> getLine\n"}, {"source_code": "import Control.Monad\n\ntype Test = [Int]\n\nfindBadDays :: [Test] -> [Int]\nfindBadDays [] = []\nfindBadDays (first:rest) = (process $ reverse first) : findBadDays rest\n\nprocess :: Test -> Int\nprocess test = _process test 10000000\n\n_process :: Test -> Int -> Int\n_process [] _ = 0\n_process (first:rest) smallest = (if first > smallest\n then 1\n else 0) + _process rest (min first smallest)\n\ngetTests :: Int -> IO [Test]\ngetTests count = replicateM count readTest\n\nreadTest :: IO Test\nreadTest = do\n _ <- getLine\n days <- getLine\n return $ map read (words days)\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getTests $ read count\n let badDays = findBadDays tests\n mapM_ print badDays"}, {"source_code": "import Control.Arrow\nimport Control.Monad (replicateM)\nimport Prelude\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n x <- replicateM n solve\n return ()\n\nsolve :: IO ()\nsolve = do\n n <- read <$> getLine :: IO Int\n xs <- (words >>> map read) <$> getLine :: IO [Int]\n print $ findSmall xs\n\nfindSmall :: [Int] -> Int\nfindSmall = reverse >>> findSmallWalk 1000001\n where\n findSmallWalk m [] = 0\n findSmallWalk m (y:ys) = findSmallWalk (min y m) ys + if y > m then 1 else 0\n"}], "negative_code": [{"source_code": "import Control.Arrow\nimport Control.Monad (replicateM)\nimport Prelude\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n x <- replicateM n solve\n return ()\n\nsolve :: IO ()\nsolve = do\n n <- read <$> getLine :: IO Int\n xs <- (words >>> map read) <$> getLine :: IO [Int]\n print $ findSmall xs\n\nfindSmall :: [Int] -> Int\nfindSmall = reverse >>> findSmallWalk 150001\n where\n findSmallWalk m [] = 0\n findSmallWalk m (y:ys) = findSmallWalk (min y m) ys + if y > m then 1 else 0\n"}], "src_uid": "09faf19627d2ff00c3821d4bc2644b63"} {"source_code": "\nmain = getContents >>= putStr.solve\n\nsolve :: [Char] -> [Char]\nsolve [] = []\nsolve [a,'\\n'] = ['\\n']\nsolve s = if (head s) == '0' then (tail s) else (head s):(solve (tail s))\n\n", "positive_code": [{"source_code": "removeFirstZero :: String -> String\nremoveFirstZero binary = if onlyOnes binary\n then tail binary\n else remove binary\n\nonlyOnes :: String -> Bool\nonlyOnes [] = True\nonlyOnes (first:rest) = if first == '0'\n then False\n else onlyOnes rest\n\nremove :: String -> String\nremove [] = []\nremove (first:rest) = if first == '1'\n then first: remove rest\n else rest\n\nmain :: IO ()\nmain = do\n binary <- getLine\n putStrLn $ removeFirstZero binary"}, {"source_code": "module Main where\n\nsolve :: String -> String\nsolve \"0\" = \"\"\nsolve \"1\" = \"\"\nsolve ('1':ls) = '1':(solve ls)\nsolve ('0':ls) = ls\n\nmain = getLine >>= (putStrLn . solve)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n\n\t\nmain= do\t \n\ts<-getLine \t \n\tlet s1 = takeWhile (>'0') s\n\tlet s2 = dropWhile (>'0') s\n\tlet s3 = if s2 ==\"\" then \"\" else tail s2\n\tputStrLn $ (if s2==\"\" then tail s1 else s1 )++s3\n\t \n\t\n \n\t \n\t "}, {"source_code": "import Data.List\nmain = interact $ \\l-> take (length l -2) $ delete '0' l\n"}, {"source_code": "removeFirstZero :: String -> String\nremoveFirstZero binary = if onlyOnes binary\n then tail binary\n else remove binary\n\nonlyOnes :: String -> Bool\nonlyOnes [] = True\nonlyOnes (first:rest) = if first == '0'\n then False\n else onlyOnes rest\n\nremove :: String -> String\nremove [] = []\nremove (first:rest) = if first == '1'\n then first: remove rest\n else rest\n\nmain :: IO ()\nmain = do\n binary <- getLine\n putStrLn $ removeFirstZero binary"}, {"source_code": "module Main where \nsolve :: String -> String \nsolve \"0\" = \"\"\nsolve \"1\" = \"\"\nsolve ('0' : xs) = xs \nsolve ('1' : xs) = '1' : solve xs\n\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "module Main where\n\nsolve :: String -> String\nsolve \"0\" = \"\"\nsolve \"1\" = \"\"\nsolve ('1':ls) = '1' : solve ls\nsolve ('0':ls) = ls\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "import Data.Char\n\nsolve :: [Int] -> Int -> Int\nsolve [] k = 1\nsolve (0:xs) k = k\nsolve (1:ys) k = solve ys (k+1)\n\noutt :: [Int] -> Int -> Int -> IO()\noutt [] k n = return()\noutt (x:xs) k n = do \n if k /= n then putChar $ chr $ (x+48) else return () \n outt xs (k+1) n\n\nconvert :: [Char] -> [Int]\nconvert xs = foldr (\\cur acc -> (digitToInt $ cur):acc) [] xs\n\n\nmain = do\n str <- getLine\n outt (convert str) 1 (solve (convert str) 1)"}, {"source_code": "import Data.List\nadd0 \"\" = \"0\"\nadd0 x = x\nmain = interact $ add0 . \\l -> dropWhile (=='0') . take (length l -2) $ delete '0' l\n"}, {"source_code": "\nsolve :: String -> String\nsolve s\n | any (== '0') s = takeWhile (== '1') s ++ tail (dropWhile (== '1') s)\n | otherwise = tail s\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n "}, {"source_code": "main :: IO ()\nmain = getLine >>= putStrLn . solve\n\nsolve :: String -> String\nsolve xs | all (=='1') xs = tail xs\n | otherwise = takeWhile (=='1') xs ++ tail (dropWhile (=='1') xs)\n"}, {"source_code": "main=interact f\nf(x:y)|x:y<\"10\"=y|0<1=x:f y"}, {"source_code": "main = do\n str <- getLine\n putStrLn (doSolve str)\n\nfindPos :: String ->Int -> Int\nfindPos [] _ = 0\nfindPos (x:xs) n\n | x == '0' = n\n | otherwise = findPos xs n+1\n\ndoSolve :: String -> String\ndoSolve x = if pos > 0\n then\n if pos == 1 then drop pos x\n else (take (pos-1) x) ++ (drop pos x)\n else init x\n where pos = findPos x 1\n"}, {"source_code": "#!/usr/bin/env runghc\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (s:ss) = f s\n where\n f (a:b:cs) = if b == '0' then a:cs else a:f (b:cs)\n f (a:cs) = cs\n"}, {"source_code": "\nremoveZero [] = []\nremoveZero (x:l) = if x == '0' then l else x:removeZero l\n\nmain = do\n bin <- getLine\n if any (\\x -> x == '0') bin\n then putStrLn $ removeZero bin\n else putStrLn $ tail bin\n"}, {"source_code": "main=interact f\nf(x:y)|x:y<\"10\"=y|0<1=x:f y"}, {"source_code": "import Data.List\nmain = putStrLn . solve =<< getLine\nsolve s | all (== '1') s = tail s\n | otherwise = delete '0' s\n"}], "negative_code": [{"source_code": "import Data.Char\n\nsolve :: [Int] -> Int -> Int\nsolve [] k = 1\nsolve (0:xs) k = k\nsolve (1:ys) k = solve ys (k+1)\n\noutt :: [Int] -> Int -> Int -> IO()\noutt [] k n = return()\noutt (x:xs) k n = do \n if k /= n then print $ x else return () \n outt xs (k+1) n\n\nconvert :: [Char] -> [Int]\nconvert xs = foldl (\\acc cur -> (digitToInt $ cur):acc) [] xs\n\n\nmain = do\n str <- getLine\n outt (convert str) 1 (solve (convert str) 1)"}, {"source_code": "import Data.Char\n\nsolve :: [Int] -> Int -> Int\nsolve [] k = 1\nsolve (0:xs) k = k\nsolve (1:ys) k = solve ys (k+1)\n\noutt :: [Int] -> Int -> Int -> IO()\noutt [] k n = return()\noutt (x:xs) k n = do \n if k /= n then putChar $ chr $ (x+48) else return () \n outt xs (k+1) n\n\nconvert :: [Char] -> [Int]\nconvert xs = foldl (\\acc cur -> (digitToInt $ cur):acc) [] xs\n\n\nmain = do\n str <- getLine\n outt (convert str) 1 (solve (convert str) 1)"}, {"source_code": "import Data.List\nmain = interact solve\nsolve s | all (== '1') s = tail s\n | otherwise = reverse $ delete '0' $ reverse s\n"}, {"source_code": "import Data.List\nmain = interact solve\nsolve s | all (== '1') s = tail s\n | otherwise = delete '0' s\n"}, {"source_code": "\nmain = getContents >>= print.solve\n\nsolve :: [Char] -> [Char]\nsolve [] = []\nsolve [a,'\\n'] = ['\\n']\nsolve s = if (head s) == '0' then (tail s) else (head s):(solve (tail s))\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n\n\t\nmain= do\t \n\ts<-getLine \t \n\tlet s1 = takeWhile (>'0') s\n\tlet s2 = dropWhile (>'0') s\n\tlet s3 = if s2 ==\"\" then \"\" else tail s2\n\tputStrLn $ s1++s3\n\t \n\t\n \n\t \n\t "}, {"source_code": "import Data.List\nadd0 \"\" = \"0\"\nadd0 x = x\nmain = interact $ add0 . \\l -> dropWhile (=='0') . take (length l -1) $ delete '0' l\n"}, {"source_code": "import Data.List\nmain = interact $ \\l -> dropWhile (=='0') . take (length l -1) $ delete '0' l\n"}, {"source_code": "import Data.List\nmain = interact $ \\l -> take (length l -1) $ delete '0' l\n"}], "src_uid": "133eaf241bb1557ba9a3f59c733d34bf"} {"source_code": "-- -fno-strictness might really hurts memory use and runtime\r\n-- if it interacts badly with foldl'\r\n{-# OPTIONS_GHC\r\n-fno-strictness\r\n-fno-enable-rewrite-rules\r\n-fno-specialise\r\n#-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\nimport Data.Functor.Identity\r\n\r\nimport Data.List\r\nimport qualified Data.Sequence as Seq\r\nimport Data.Sequence ((><), ViewL(..))\r\nimport Data.Array.Unboxed\r\nimport Data.Int\r\n\r\nineqsForced :: [(Int, Int)] -> Int\r\nineqsForced insxys = let\r\n step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)\r\n step (ct, s) (xi, yi) = ct `seq` s `seq` let\r\n slen = Seq.length s\r\n tosplit = s >< Seq.replicate (xi - 1 - slen) False\r\n (pref, suff) = Seq.splitAt (yi - 1) tosplit\r\n in case Seq.viewl suff of\r\n val :< rest\r\n -> (ct + if val then 0 else 1,\r\n pref >< Seq.fromList [False, True] >< rest)\r\n _ -> error \"urk\"\r\n (ans, _res) = foldl' step (0, Seq.empty) insxys\r\n in ans -- filter too slow; no sum(n) constraint\r\n\r\np :: Int\r\np = 998244353\r\n\r\np64 :: Int64\r\np64 = fromIntegral p\r\n\r\n(*!) :: Int -> Int -> Int\r\ninfixr 7 *!\r\nx *! y = let\r\n x64 = fromIntegral x\r\n y64 = fromIntegral y\r\n in fromIntegral (x64 * y64 `rem` p64)\r\n\r\nnewtype ProdP = ProdP { unProdP :: Int }\r\ninstance Semigroup ProdP where\r\n ProdP x <> ProdP y = ProdP (x *! y)\r\ninv :: Int -> Int\r\ninv = unProdP . stimes (p - 2) . ProdP\r\n\r\ngetFacts :: Int -> UArray Int Int\r\ngetFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]\r\n\r\ngetIFacts :: UArray Int Int -> UArray Int Int\r\ngetIFacts arr = let\r\n (0, n) = bounds arr\r\n step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)\r\n in array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [t] <- getInts 1\r\n let\r\n -- whoops, misread constraint, not OK to recompute these\r\n facts = getFacts (2 * 200000)\r\n ifacts = getIFacts facts\r\n choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)\r\n replicateM_ t $ do\r\n [n, m] <- getInts 2\r\n xys <- liftPure $ replicateM m $ do\r\n ~[x, y] <- getInts 2\r\n pure (x, y)\r\n let maxOpts = n - 1 - ineqsForced xys\r\n --putInts [n, maxOpts]\r\n putInts [choose (n + maxOpts) maxOpts]\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\nliftPure :: SP Identity t -> SIO t\r\nliftPure = mapStateT (pure . runIdentity)\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'", "positive_code": [{"source_code": "-- disable all optimization in this module\r\n-- How slow is it, really?\r\n{-# OPTIONS_GHC -O0 #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\nimport Data.Functor.Identity\r\n\r\nimport Data.List\r\nimport qualified Data.Sequence as Seq\r\nimport Data.Sequence ((><), ViewL(..))\r\nimport Data.Array.Unboxed\r\nimport Data.Int\r\n\r\nineqsForced :: [(Int, Int)] -> Int\r\nineqsForced insxys = let\r\n step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)\r\n step (ct, s) (xi, yi) = ct `seq` s `seq` let\r\n slen = Seq.length s\r\n tosplit = s >< Seq.replicate (xi - 1 - slen) False\r\n (pref, suff) = Seq.splitAt (yi - 1) tosplit\r\n in case Seq.viewl suff of\r\n val :< rest\r\n -> (ct + if val then 0 else 1,\r\n pref >< Seq.fromList [False, True] >< rest)\r\n _ -> error \"urk\"\r\n (ans, _res) = foldl' step (0, Seq.empty) insxys\r\n in ans -- filter too slow; no sum(n) constraint\r\n\r\np :: Int\r\np = 998244353\r\n\r\np64 :: Int64\r\np64 = fromIntegral p\r\n\r\n(*!) :: Int -> Int -> Int\r\ninfixr 7 *!\r\nx *! y = let\r\n x64 = fromIntegral x\r\n y64 = fromIntegral y\r\n in fromIntegral (x64 * y64 `rem` p64)\r\n\r\nnewtype ProdP = ProdP { unProdP :: Int }\r\ninstance Semigroup ProdP where\r\n ProdP x <> ProdP y = ProdP (x *! y)\r\ninv :: Int -> Int\r\ninv = unProdP . stimes (p - 2) . ProdP\r\n\r\ngetFacts :: Int -> UArray Int Int\r\ngetFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]\r\n\r\ngetIFacts :: UArray Int Int -> UArray Int Int\r\ngetIFacts arr = let\r\n (0, n) = bounds arr\r\n step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)\r\n in array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [t] <- getInts 1\r\n let\r\n -- whoops, misread constraint, not OK to recompute these\r\n facts = getFacts (2 * 200000)\r\n ifacts = getIFacts facts\r\n choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)\r\n replicateM_ t $ do\r\n [n, m] <- getInts 2\r\n xys <- liftPure $ replicateM m $ do\r\n ~[x, y] <- getInts 2\r\n pure (x, y)\r\n let maxOpts = n - 1 - ineqsForced xys\r\n --putInts [n, maxOpts]\r\n putInts [choose (n + maxOpts) maxOpts]\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\nliftPure :: SP Identity t -> SIO t\r\nliftPure = mapStateT (pure . runIdentity)\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'"}, {"source_code": "-- I intuitively don't expect these to have much effect here.\r\n{-# OPTIONS_GHC\r\n-fno-enable-rewrite-rules\r\n-fno-specialise\r\n#-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Builder as B\r\nimport Data.ByteString.Builder.Prim\r\nimport System.IO\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans.Class\r\nimport Data.Semigroup\r\nimport Data.Functor.Identity\r\n\r\nimport Data.List\r\nimport qualified Data.Sequence as Seq\r\nimport Data.Sequence ((><), ViewL(..))\r\nimport Data.Array.Unboxed\r\nimport Data.Int\r\n\r\nineqsForced :: [(Int, Int)] -> Int\r\nineqsForced insxys = let\r\n step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)\r\n step (ct, s) (xi, yi) = ct `seq` s `seq` let\r\n slen = Seq.length s\r\n tosplit = s >< Seq.replicate (xi - 1 - slen) False\r\n (pref, suff) = Seq.splitAt (yi - 1) tosplit\r\n in case Seq.viewl suff of\r\n val :< rest\r\n -> (ct + if val then 0 else 1,\r\n pref >< Seq.fromList [False, True] >< rest)\r\n _ -> error \"urk\"\r\n (ans, _res) = foldl' step (0, Seq.empty) insxys\r\n in ans -- filter too slow; no sum(n) constraint\r\n\r\np :: Int\r\np = 998244353\r\n\r\np64 :: Int64\r\np64 = fromIntegral p\r\n\r\n(*!) :: Int -> Int -> Int\r\ninfixr 7 *!\r\nx *! y = let\r\n x64 = fromIntegral x\r\n y64 = fromIntegral y\r\n in fromIntegral (x64 * y64 `rem` p64)\r\n\r\nnewtype ProdP = ProdP { unProdP :: Int }\r\ninstance Semigroup ProdP where\r\n ProdP x <> ProdP y = ProdP (x *! y)\r\ninv :: Int -> Int\r\ninv = unProdP . stimes (p - 2) . ProdP\r\n\r\ngetFacts :: Int -> UArray Int Int\r\ngetFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]\r\n\r\ngetIFacts :: UArray Int Int -> UArray Int Int\r\ngetIFacts arr = let\r\n (0, n) = bounds arr\r\n step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)\r\n in array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))\r\n\r\nmain :: IO ()\r\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\r\n [t] <- getInts 1\r\n let\r\n -- whoops, misread constraint, not OK to recompute these\r\n facts = getFacts (2 * 200000)\r\n ifacts = getIFacts facts\r\n choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)\r\n replicateM_ t $ do\r\n [n, m] <- getInts 2\r\n xys <- liftPure $ replicateM m $ do\r\n ~[x, y] <- getInts 2\r\n pure (x, y)\r\n let maxOpts = n - 1 - ineqsForced xys\r\n --putInts [n, maxOpts]\r\n putInts [choose (n + maxOpts) maxOpts]\r\n\r\ntype SP = StateT [P.ByteString]\r\ntype SIO = SP IO\r\n\r\nliftPure :: SP Identity t -> SIO t\r\nliftPure = mapStateT (pure . runIdentity)\r\n\r\ngetNext :: Monad m => Int -> SP m [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Monad m => Int -> SP m [Int]\r\ngetInts k = do\r\n vs <- getNext k\r\n pure [v | Just (v, _) <- map P.readInt vs]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li = let\r\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\r\n in lift $ B.hPutBuilder stdout $ case li of\r\n [] -> B.char7 '\\n'\r\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Semigroup\nimport Data.Functor.Identity\n\nimport Data.List\nimport qualified Data.Sequence as Seq\nimport Data.Sequence ((><), ViewL(..))\nimport Data.Array.Unboxed\nimport Data.Int\n\nineqsForced :: [(Int, Int)] -> Int\nineqsForced insxys = let\n step :: (Int, Seq.Seq Bool) -> (Int, Int) -> (Int, Seq.Seq Bool)\n step (ct, s) (xi, yi) = ct `seq` s `seq` let\n slen = Seq.length s\n tosplit = s >< Seq.replicate (xi - 1 - slen) False\n (pref, suff) = Seq.splitAt (yi - 1) tosplit\n in case Seq.viewl suff of\n val :< rest\n -> (ct + if val then 0 else 1,\n pref >< Seq.fromList [False, True] >< rest)\n _ -> error \"urk\"\n (ans, _res) = foldl' step (0, Seq.empty) insxys\n in ans -- filter too slow; no sum(n) constraint\n\np :: Int\np = 998244353\n\np64 :: Int64\np64 = fromIntegral p\n\n(*!) :: Int -> Int -> Int\ninfixr 7 *!\nx *! y = let\n x64 = fromIntegral x\n y64 = fromIntegral y\n in fromIntegral (x64 * y64 `rem` p64)\n\nnewtype ProdP = ProdP { unProdP :: Int }\ninstance Semigroup ProdP where\n ProdP x <> ProdP y = ProdP (x *! y)\ninv :: Int -> Int\ninv = unProdP . stimes (p - 2) . ProdP\n\ngetFacts :: Int -> UArray Int Int\ngetFacts n = listArray (0, n) $ scanl' (*!) 1 [1 .. n]\n\ngetIFacts :: UArray Int Int -> UArray Int Int\ngetIFacts arr = let\n (0, n) = bounds arr\n step (ix, acc) = ix `seq` acc `seq` (ix - 1, acc *! ix)\n in array (0, n) $ take (n+1) $ iterate step (n, inv (arr ! n))\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [t] <- getInts 1\n let\n -- whoops, misread constraint, not OK to recompute these\n facts = getFacts (2 * 200000)\n ifacts = getIFacts facts\n choose x y = facts ! x *! ifacts ! y *! ifacts ! (x - y)\n replicateM_ t $ do\n [n, m] <- getInts 2\n xys <- liftPure $ replicateM m $ do\n ~[x, y] <- getInts 2\n pure (x, y)\n let maxOpts = n - 1 - ineqsForced xys\n --putInts [n, maxOpts]\n putInts [choose (n + maxOpts) maxOpts]\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: SP Identity t -> SIO t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in lift $ B.hPutBuilder stdout $ case li of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\n"}], "negative_code": [], "src_uid": "45da2b93570e7d26d0e4fd3a3fca20b7"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\n\ndata Problem = Problem { target :: Integer\n , parts :: [Integer]\n } deriving (Show, Eq)\n\nsingleton :: Problem -> Bool\nsingleton (Problem n []) = True\nsingleton (Problem n ps) = sum ps + (pred . fromIntegral $ length ps) == n\n\ntest0 = Problem{target = 4, parts = [1, 3]}\ntest1 = Problem{target = 10, parts = [3, 3, 2]}\ntest2 = Problem{target = 10, parts = [1, 3]}\n\nmain :: IO ()\nmain = do\n [n, t] <- map read . words <$> getLine\n ps <- map read . words <$> getLine\n let problem = Problem { target = t, parts = ps }\n putStrLn $ if singleton problem then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInts = (map parseInteger . BS8.words) `fmap` BS8.getLine :: IO [Integer]\nparseInteger = fst . fromJust . BS8.readInteger\n\nmain = do\n [n,x] <- getInts\n as <- getInts\n if (sum as + (n-1) == x)\n then putStrLn \"YES\"\n else putStrLn \"NO\""}, {"source_code": "import Data.Bool\nmain = getContents >>= putStr . exec\nexec = bool \"NO\" \"YES\" . solve . map read . words\nsolve (n:k:xs) = sum xs - (1 :: Int) + n == k"}, {"source_code": "main :: IO ()\nmain = solve . map read . words =<< getContents\n\nsolve :: [Int] -> IO ()\nsolve (n:x:a) = putStrLn (if x == sum a + n - 1 then \"YES\" else \"NO\")\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInts = (map parseInteger . BS8.words) `fmap` BS8.getLine :: IO [Integer]\nparseInteger = fst . fromJust . BS8.readInteger\n\nmain = do\n [n,x] <- getInts\n as <- getInts\n if (sum as + (n-1) == x) || (sum as + (n+1) == x)\n then putStrLn \"YES\"\n else putStrLn \"NO\""}, {"source_code": "import Data.Bool\nmain = getContents >>= print . exec\nexec = bool \"NO\" \"YES\" . solve . map read . words\nsolve (n:k:xs) = sum xs - (1 :: Int) + n == k"}], "src_uid": "080a3458eaea4903da7fa4cf531beba2"} {"source_code": "import Data.Char (ord)\nimport Data.List\nimport Debug.Trace\n\ntype Input = (Int, [Int])\ntype Output = Bool\n\nreadInt :: String -> Int\nreadInt = foldl' (\\s d -> s * 10 + ord d - 48) 0\n\nparse :: String -> Input\nparse contents = (k, a)\n where [[_, k], a] = map (map readInt . words) . lines $ contents\n\nsum' :: [[Maybe Bool]] -> Bool\nsum' = last . foldl' byRow (repeat False)\n where byRow p = tail . scanl f True . zip p\n f _ (_, Just b) = b\n f s (b, Nothing) = not s || not b\n\ninitVal :: Int -> Int -> Int -> Int -> Maybe Bool\ninitVal k p i j\n | i < 0 || j < 0 || i + j < k = Just True\n | i + j == k = Just (odd (j + p))\n | otherwise = Nothing\n\nfastReduce :: Int -> Int -> Int -> Bool\nfastReduce k n m\n | n >= 2 && m >= 2 && n + m >= k + 4 = fastReduce k (n - 1) (m - 1)\n | otherwise = sum' initVals\n where initVals = [[initVal k (n + m - k) i j | j <- [m0 .. m]] | i <- [n0 .. n]]\n n0 = max 0 (k - m) - 1\n m0 = max 0 (k - n) - 1\n\nsolve :: Input -> Output\nsolve (k, a) = fastReduce k (count even a) (count odd a)\n where count f = length . filter f\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nmain :: IO ()\nmain = putStrLn . bool \"Daenerys\" \"Stannis\" . solve . parse =<< getContents\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\ncount acc [] = acc\ncount (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs\n\nmain = do\n [n, k] <- getInts\n (zeroes, ones) <- count (0, 0) <$> getInts\n putStrLn $ solve zeroes ones (n - k) \n\n\np2 = \"Daenerys\"\np1 = \"Stannis\"\n\n\nsolve _ ones 0 = if even ones then p2 else p1\nsolve zeroes ones moves =\n if\n | ones <= moves `div` 2 -> p2\n | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2\n | zeroes <= moves `div` 2, odd (ones - (moves - zeroes)) -> p1\n | even moves -> p2\n | otherwise -> p1\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nreadInt = fst . fromJust . B.readInt\n\nsolve (_ : k : cities) =\n if k == length cities\n then\n if odd odds then stannis else daenerys\n else \n let totalMoves = length cities - k in\n let stannisMoves = (totalMoves + 1) `div` 2 in\n let daenerysMoves = totalMoves - stannisMoves in\n if even totalMoves\n then\n -- Daenerys' last move: she wins if number of towns is even or if any even town remain\n if even k || stannisMoves < evens then daenerys else stannis\n else\n if (if even k\n then\n daenerysMoves < evens && daenerysMoves < odds\n else\n daenerysMoves < odds) then stannis else daenerys\n where\n odds = length (filter odd cities)\n evens = length (filter even cities)\n\nstannis = B.pack \"Stannis\"\ndaenerys = B.pack \"Daenerys\"\n\nmain = B.interact $ solve . map readInt . B.words\n"}, {"source_code": "import Control.Applicative ((<$>), liftA)\nimport Data.Bits ((.&.))\nimport Data.Foldable (foldl')\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\nstan = \"Stannis\" :: String -- goes first\ndan = \"Daenerys\" :: String -- even\n\nparity :: Int -> Int -> Int -> String\nparity n k odd\n | n == k = if odd .&. 1 == 1 then stan else dan -- end of game\n | odd < j + 1 = dan -- remove all odds\n | k .&. 1 == 1 && n - odd < i + 1 = stan -- remove all even\n | k .&. 1 == 0 && n - odd < j + 1 = dan -- remove all even\n | odd .&. 1 == 0 && n .&. 1 == 0 && i == j = dan -- dan can pair out\n | j < i && j < min n (n - odd) = stan -- stan will decide ultimately\n | j == i && i < n - odd = dan -- dan will decide ultimately\n | otherwise = stan\n where\n j = (n - k) `div` 2\n i = n - k - j\n\n\nparse :: C8.ByteString -> Maybe [Int]\nparse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words\n\noddCount :: [Int] -> Int\noddCount = foldl' loop 0\n where\n loop n i | i .&. 1 == 1 = n + 1\n | otherwise = n\n\nmain :: IO ()\nmain = fmap read . words <$> getLine >>= \\[n, k] ->\n liftA oddCount . parse <$> B.getLine >>= \\(Just odd) ->\n putStrLn $ parity n k odd\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>), liftA)\nimport Data.Bits ((.&.))\nimport Data.Foldable (foldl')\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\nstan = \"Stannis\" :: String -- goes first\ndan = \"Daenerys\" :: String -- even\n\nparity :: Int -> Int -> Int -> String\nparity n k odd\n | k .&. 1 == 0 || odd < j + 1 = dan -- remove all odds | k is even\n | n - odd < i + 1 = stan -- remove all even\n | odd .&. 1 == 0 && n .&. 1 == 0 && i == j = dan -- dan can pair out\n | j < i && j < min n (n - odd) = stan -- stan will decide ultimately\n | j == i && i < min n (n - odd) = dan -- dan will decide ultimately\n | otherwise = stan\n where\n j = (n - k) `div` 2\n i = n - k - j\n\n\nparse :: C8.ByteString -> Maybe [Int]\nparse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words\n\noddCount :: [Int] -> Int\noddCount = foldl' loop 0\n where\n loop n i | i .&. 1 == 1 = n + 1\n | otherwise = n\n\nmain :: IO ()\nmain = fmap read . words <$> getLine >>= \\[n, k] ->\n liftA oddCount . parse <$> B.getLine >>= \\(Just odd) ->\n putStrLn $ parity n k odd\n"}, {"source_code": "import Control.Applicative ((<$>), liftA)\nimport Data.Bits ((.&.))\nimport Data.Foldable (foldl')\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\nstan = \"Stannis\" :: String -- goes first\ndan = \"Daenerys\" :: String -- even\n\nparity :: Int -> Int -> Int -> String\nparity n k odd\n | n == k = if odd .&. 1 == 1 then stan else dan -- end of game\n | k .&. 1 == 0 && odd < j + 1 = dan -- remove all odds & k is even\n | k .&. 1 == 1 && n - odd < i + 1 = stan -- remove all even\n | odd .&. 1 == 0 && n .&. 1 == 0 && i == j = dan -- dan can pair out\n | j < i && j < min n (n - odd) = stan -- stan will decide ultimately\n | j == i && i < n - odd = dan -- dan will decide ultimately\n | otherwise = stan\n where\n j = (n - k) `div` 2\n i = n - k - j\n\n\nparse :: C8.ByteString -> Maybe [Int]\nparse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words\n\noddCount :: [Int] -> Int\noddCount = foldl' loop 0\n where\n loop n i | i .&. 1 == 1 = n + 1\n | otherwise = n\n\nmain :: IO ()\nmain = fmap read . words <$> getLine >>= \\[n, k] ->\n liftA oddCount . parse <$> B.getLine >>= \\(Just odd) ->\n putStrLn $ parity n k odd"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nreadInt = fst . fromJust . B.readInt\n\nsolve (_ : k : cities) =\n let totalMoves = length cities - k in\n let stannisMoves = (totalMoves + 1) `div` 2 in\n let daenerysMoves = totalMoves - stannisMoves in\n if even totalMoves\n then\n -- Daenerys' last move: she wins if number of towns is even or if any even town remain\n if even k || stannisMoves < evens then daenerys else stannis\n else\n if (if even k\n then\n daenerysMoves < evens && daenerysMoves < odds\n else\n daenerysMoves < odds) then stannis else daenerys\n where\n odds = length (filter odd cities)\n evens = length (filter even cities)\n\nstannis = B.pack \"Stannis\"\ndaenerys = B.pack \"Daenerys\"\n\nmain = B.interact $ solve . map readInt . B.words\n"}, {"source_code": "type Input = (Int, [Int])\ntype Output = Bool\n\nparse :: String -> Input\nparse contents = (k, a)\n where [[_, k], a] = map (map read . words) . lines $ contents\n\nsolveCase :: Int -> Bool -> Int -> Int -> Bool\nsolveCase k f e o\n | e < 0 || o < 0 = True\n | t == k = f /= even o\n | t >= k + 4 = s (e - 1) (o - 1)\n | otherwise = any not [s (e - 1) o, s e (o - 1)]\n where s = solveCase k (not f)\n t = e + o\n\nsolve :: Input -> Output\nsolve (m, a) = solveCase m True (count even a) (count odd a)\n where count f = length . filter f\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nmain :: IO ()\nmain = putStrLn . bool \"Daenerys\" \"Stannis\" . solve . parse =<< getContents\n"}, {"source_code": "import Data.Char (ord)\nimport Data.List\nimport Debug.Trace\n\ntype Input = (Int, [Int])\ntype Output = Bool\n\nreadInt :: String -> Int\nreadInt = foldl' (\\s d -> s * 10 + ord d - 48) 0\n\nparse :: String -> Input\nparse contents = (k, a)\n where [[_, k], a] = map (map readInt . words) . lines $ contents\n\nsum' :: [[Maybe Bool]] -> Bool\nsum' = last . foldl' byRow (repeat False)\n where byRow p = tail . scanl f True . zip p\n f _ (_, Just b) = b\n f s (b, Nothing) = not s || not b\n\ninitVal :: Int -> Int -> Int -> Int -> Maybe Bool\ninitVal k p i j\n | i < 0 || j < 0 || i + j < k = Just True\n | i + j == k = Just (even (j + p))\n | otherwise = Nothing\n\nfastReduce :: Int -> Int -> Int -> Bool\nfastReduce k n m\n | n >= 2 && m >= 2 && n + m >= k + 4 = fastReduce k (n - 1) (m - 1)\n | otherwise = sum' initVals\n where initVals = [[initVal k (n + m) i j | j <- [k - n - 1 .. m]] | i <- [k - m - 1 .. n]]\n\nsolve :: Input -> Output\nsolve (k, a) = fastReduce k (count even a) (count odd a)\n where count f = length . filter f\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nmain :: IO ()\nmain = putStrLn . bool \"Daenerys\" \"Stannis\" . solve . parse =<< getContents\n"}, {"source_code": "type Input = (Int, [Int])\ntype Output = Bool\n\nparse :: String -> Input\nparse contents = (k, a)\n where [[_, k], a] = map (map read . words) . lines $ contents\n\nsolveCase :: Int -> Bool -> Int -> Int -> Bool\nsolveCase k f e o\n | t == k = f /= even o\n | t >= k + 4 && e >= 2 && o >= 2 = s (e - 1) (o - 1)\n | otherwise = any not moves\n where s = solveCase k (not f)\n t = e + o\n moves = [s (e - 1) o | e >= 1] ++ [s e (o - 1) | o >= 1]\n\nsolve :: Input -> Output\nsolve (m, a) = solveCase m True (count even a) (count odd a)\n where count f = length . filter f\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nmain :: IO ()\nmain = putStrLn . bool \"Daenerys\" \"Stannis\" . solve . parse =<< getContents\n"}, {"source_code": "import Data.Char (ord)\n\ntype Input = (Int, [Int])\ntype Output = Bool\n\nreadInt :: String -> Int\nreadInt = foldr (\\d s -> s * 10 + ord d - 48) 0\n\nparse :: String -> Input\nparse contents = (k, a)\n where [[_, k], a] = map (map readInt . words) . lines $ contents\n\nsolveCase :: Int -> Bool -> Int -> Int -> Bool\nsolveCase k f e o\n | t == k = f /= even o\n | t >= k + 4 && e >= 2 && o >= 2 = solveCase k f (e - 1) (o - 1)\n | otherwise = any not moves\n where s = solveCase k (not f)\n t = e + o\n moves = [s (e - 1) o | e >= 1] ++ [s e (o - 1) | o >= 1]\n\nsolve :: Input -> Output\nsolve (m, a) = solveCase m True (count even a) (count odd a)\n where count f = length . filter f\n\nbool :: a -> a -> Bool -> a\nbool f _ False = f\nbool _ t True = t\n\nmain :: IO ()\nmain = putStrLn . bool \"Daenerys\" \"Stannis\" . solve . parse =<< getContents\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\ncount acc [] = acc\ncount (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs\n\nmain = do\n [n, k] <- getInts\n (zeroes, ones) <- count (0, 0) <$> getInts\n putStrLn $ solve zeroes ones (n - k) \n\n\np2 = \"Daenerys\"\np1 = \"Stannis\"\n\n\nsolve zeroes ones moves =\n if\n | ones <= moves `div` 2 -> p2\n | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2\n | otherwise -> p1\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\ncount acc [] = acc\ncount (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs\n\nmain = do\n [n, k] <- getInts\n (zeroes, ones) <- count (0, 0) <$> getInts\n putStrLn $ solve zeroes ones (n - k) \n\n\np2 = \"Daenerys\"\np1 = \"Stannis\"\n\n\nsolve _ ones 0 = if even ones then p2 else p1\nsolve zeroes ones moves =\n if\n | ones <= moves `div` 2 -> p2\n | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2\n | otherwise -> p1\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\ncount acc [] = acc\ncount (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs\n\nmain = do\n [n, k] <- getInts\n (zeroes, ones) <- count (0, 0) <$> getInts\n putStrLn $ solve zeroes ones (n - k) \n\n\np2 = \"Daenerys\"\np1 = \"Stannis\"\n\n\nsolve _ ones 0 = if even ones then p2 else p1\nsolve zeroes ones moves =\n if\n | ones <= moves `div` 2 -> p2\n | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2\n | even moves -> p2\n | otherwise -> p1\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\ncount acc [] = acc\ncount (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs\n\nmain = do\n [n, k] <- getInts\n (zeroes, ones) <- count (0, 0) <$> getInts\n putStrLn $ solve zeroes ones (n - k) \n\n\np2 = \"Daenerys\"\np1 = \"Stannis\"\n\n\nsolve _ _ 0 = p2\nsolve zeroes ones moves =\n if\n | ones <= moves `div` 2 -> p2\n | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2\n | otherwise -> p1\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.Bits\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\ncount acc [] = acc\ncount (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs\n\nmain = do\n [n, k] <- getInts\n (zeroes, ones) <- count (0, 0) <$> getInts\n putStrLn $ solve zeroes ones (n - k) \n\n\np2 = \"Daenerys\"\np1 = \"Stannis\"\n\n\nsolve _ ones 0 = if even ones then p2 else p1\nsolve zeroes ones moves =\n if\n | ones <= moves `div` 2 -> p2\n | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2\n | moves `div` 2 == 0 -> p2\n | otherwise -> p1\n"}], "src_uid": "67e51db4d96b9f7996aea73cbdba3584"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.Tuple\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nupdateTwoMax :: (Int, Int) -> Int -> (Int, Int)\nupdateTwoMax (m1, m2) x | x >= m1 = (x, m1)\n | x >= m2 = (m1, x)\n | otherwise = (m1, m2)\n\ncombine :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)\ncombine (s1, m11, m12) (s2, m21, m22) = (maxSum, max1, max2)\n where maxSum = s1 `max` s2 `max` (max1 + max2)\n (max1, max2) = (m11, m12) `updateTwoMax` m21\n\ndfs :: Array Int [Int] -> Array Int Int -> Int -> Int -> (Int, Int, Int)\ndfs g col root parent = foldl combine (0, 0, 0) (zipWith addEdge childrenRes childrenEdges)\n where childrenRes = [(dfs g col child root) | child <- g!root, child /= parent]\n childrenEdges = [f child root | child <- g!root, child /= parent]\n f u v | col!u == col!v = 0\n | otherwise = 1\n addEdge (m, m1, m2) x = (m, m1 + x, m2 + x)\n\nsolve :: Tokenizer Int\nsolve = do\n n <- nextInt\n col <- listArray (0, n - 1) <$> replicateM n nextInt\n edges <- replicateM (n - 1) $ do\n u <- nextInt\n v <- nextInt\n return (u - 1, v - 1)\n let g = accumArray (flip (:)) [] (0, n - 1) (edges ++ (map swap edges))\n let (ans, _, _) = dfs g col 0 (-1)\n return $ (ans + 1) `div` 2\n\nmain = do\n contents <- L.getContents\n print $ evalState solve (L.words contents)\n", "positive_code": [{"source_code": "-- Codeforces Round #379 (Div. 2)\n-- http://codeforces.com/contest/734\n\n-- ID: 734E (Anton and Tree)\n\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Array\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple (swap)\nimport Data.Foldable (toList)\nimport qualified Data.IntSet as Set\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\ntype Graph = Array Int [Int]\n\nmain = do\n n <- getInt\n colors <- listArray (1,n) `fmap` getInts\n edges <- replicateM (n-1) $ do\n [u,v] <- getInts\n return (u,v)\n let edges' = edges ++ (map swap edges)\n let g = accumArray (flip (:)) [] (1,n) edges'\n print $ (diameter g colors n + 1) `div` 2\n\npreorder :: Graph -> Int -> [(Int,Int)]\npreorder g start = toList $ bfs Seq.empty [(start,start)] where\n bfs nodes [] = nodes\n bfs nodes queue = bfs (nodes Seq.>< Seq.fromList queue) (concatMap nexts queue)\n nexts (v,parent) = map (\\u -> (u,v)) $ filter (/= parent) (g ! v)\n\nlevels :: Graph -> Array Int Int -> Int -> Int -> Array Int Int\nlevels g colors start n = a where\n a = array (1, n) [findLevel v | v <- order]\n findLevel (v, parent)\n | v == parent = (v, 0)\n | colors ! v == colors ! parent = (v, a ! parent)\n | otherwise = (v, (a ! parent) + 1)\n order = preorder g start\n\nmaxLevel g colors start n\n = maximumBy (\\a b -> compare (snd a) (snd b)) $ assocs $ levels g colors start n\n\ndiameter :: Graph -> Array Int Int -> Int -> Int\ndiameter g colors n = snd $ maxLevel g colors (fst $ maxLevel g colors 1 n) n\n"}], "negative_code": [], "src_uid": "0600b8401c8e09978661bc02691bda5d"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport Data.Bits\nimport Data.Int\nimport Data.Semigroup\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\np64 :: Int64\np64 = fromIntegral p\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = cv $ x + y\n\n(-!) :: Int -> Int -> Int\ninfixl 6 -!\nx -! y = cv $ x + p - y\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = fromIntegral $ fromIntegral x * fromIntegral y `rem` p64\n\nnewtype ProdP = ProdP { unProdP :: Int }\ninstance Semigroup ProdP where\n ProdP x <> ProdP y = ProdP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ProdP where\n mempty = ProdP 1\n\npowP :: Int -> Int -> Int\npowP x k = unProdP $ stimes k $ ProdP x\n\nsuffSums :: UArray Int Int -> UArray Int Int\nsuffSums arr = let\n (p, q) = bounds arr\n in array (p, q) $ flip unfoldr (q, 0) $ \\w@(!ii, !s) -> do\n guard $ ii >= p\n let !ni = ii - 1\n pure (w, (ni, s + arr ! ii))\n\nmainFun :: SP Builder\nmainFun = do\n ~[n] <- getInts 1\n a <- getInts n\n let\n maxk = finiteBitSize (0 :: Int)\n cts = accumArray (+) 0 (0, maxk)\n $ [(countTrailingZeros ai, 1) | ai <- a]\n his = suffSums cts\n bad i = case cts ! i of\n 0 -> 0\n q -> powP 2 (his ! i + q - 1) -- choose any ODD # with i trailing zeros\n good = foldl' (-!) (powP 2 n) [bad i | i <- [1 .. maxk]]\n pure $ putInts [good -! 1] -- \"nonempty\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport qualified Data.Map as M\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xs <- readInts\r\n let oc = length $ filter odd xs\r\n withOdd = (2 ^ oc - 1) * 2 ^ (n - oc)\r\n ecs = M.elems $ M.fromListWith (+) [(countTrailingZeros x, 1 :: Int) | x <- xs, even x]\r\n withoutOdd = sum $ zipWith f ecs (tail $ scanr (+) 0 ecs) where\r\n f c c' = 2 ^ c' * (2 ^ (c - 1) - 1)\r\n print $ toInt $ withOdd + withoutOdd\r\n\r\nm :: Int\r\nm = 1000000007\r\n\r\nnewtype MInt = MInt { toInt :: Int } deriving (Eq, Show)\r\n\r\ninstance Num MInt where\r\n MInt a + MInt b = MInt $ let c = a + b in if c >= m then c - m else c\r\n MInt a - MInt b = MInt $ let c = a - b in if c < 0 then c + m else c\r\n MInt a * MInt b = MInt $ a * b `mod` m\r\n abs = id\r\n signum = MInt . signum . toInt\r\n fromInteger = MInt . fromInteger . (`mod` fromIntegral m)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport Data.Bits\nimport Data.Int\nimport Data.Semigroup\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\np64 :: Int64\np64 = fromIntegral p\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = cv $ x + y\n\n(-!) :: Int -> Int -> Int\ninfixl 6 -!\nx -! y = cv $ x + p - y\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = fromIntegral $ fromIntegral x * fromIntegral y `rem` p64\n\nnewtype ProdP = ProdP { unProdP :: Int }\ninstance Semigroup ProdP where\n ProdP x <> ProdP y = ProdP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ProdP where\n mempty = ProdP 1\n\npowP :: Int -> Int -> Int\npowP x k = unProdP $ stimes k $ ProdP x\n\nsuffSums :: UArray Int Int -> UArray Int Int\nsuffSums arr = let\n (p, q) = bounds arr\n in array (p, q) $ flip unfoldr (q, 0) $ \\w@(!ii, !s) -> do\n guard $ ii >= p\n let !ni = ii - 1\n pure (w, (ni, s + arr ! ii))\n\nmainFun :: SP Builder\nmainFun = do\n ~[n] <- getInts 1\n a <- getInts n\n let\n maxk = finiteBitSize (0 :: Int)\n cts = accumArray (+) 0 (0, maxk)\n $ [(countTrailingZeros ai, 1) | ai <- a]\n his = suffSums cts\n bad i = cts ! i *! powP 2 (his ! i)\n good = foldl' (-!) (powP 2 n) [bad i | i <- [1 .. maxk]]\n pure $ putInts [good -! 1] -- \"nonempty\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport Data.Bits\nimport Data.Int\nimport Data.Semigroup\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\np64 :: Int64\np64 = fromIntegral p\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = cv $ x + y\n\n(-!) :: Int -> Int -> Int\ninfixl 6 -!\nx -! y = cv $ x + p - y\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = fromIntegral $ fromIntegral x * fromIntegral y `rem` p64\n\nnewtype ProdP = ProdP { unProdP :: Int }\ninstance Semigroup ProdP where\n ProdP x <> ProdP y = ProdP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ProdP where\n mempty = ProdP 1\n\npowP :: Int -> Int -> Int\npowP x k = unProdP $ stimes k $ ProdP x\n\nsuffSums :: UArray Int Int -> UArray Int Int\nsuffSums arr = let\n (p, q) = bounds arr\n in array (p, q) $ flip unfoldr (q, 0) $ \\w@(!ii, !s) -> do\n guard $ ii >= p\n let !ni = ii - 1\n pure (w, (ni, s + arr ! ii))\n\nmainFun :: SP Builder\nmainFun = do\n ~[n] <- getInts 1\n a <- getInts n\n let\n maxk = finiteBitSize (0 :: Int)\n cts = accumArray (+) 0 (0, maxk)\n $ [(countTrailingZeros ai, 1) | ai <- a]\n his = suffSums cts\n bad i = cts ! i *! powP 2 (his ! i)\n good = foldl' (-!) (powP 2 n) [bad i | i <- [1 .. maxk]]\n pure $ putInts (elems cts) <> putInts [good -! 1] -- \"nonempty\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "1d58ae45a677023dc8fd6c9473a89737"} {"source_code": "import Data.List\nfx::[[Int]]->[Int]\nfx []=[]\nfx ((x:y:[]):xs)=x:fx xs\n \nfy::[[Int]]->[Int]\nfy []=[]\nfy ((x:y:[]):xs)=y:fy xs\n\nmain =do\n e<-getLine\n es<-getContents\n let xs=lines es\n ys=map (map read ) (map words xs)::[[Int]]\n print $ min (length (nub (fx ys))) (length (nub (fy ys)))", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport qualified Data.IntSet as S\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\ndiffCount xs = go 0 S.empty xs\n where go !c seen [] = c\n go c seen (x:xs) = if S.member x seen then go c seen xs else go (c+1) (S.insert x seen) xs\n\nmain = do\n n <- fmap read getLine\n clocks <- replicateM n $ fmap (parseInts 2) BS.getLine\n let v = diffCount $ map head clocks\n h = diffCount $ map (head . tail) clocks\n print $ (min v h :: Int)\n\n"}], "negative_code": [{"source_code": "import Data.List\nfx::[[Int]]->[Int]\nfx []=[]\nfx ((x:y:[]):xs)=x:fx xs\n \nfy::[[Int]]->[Int]\nfy []=[]\nfy ((x:y:[]):xs)=y:fx xs\n\nmain =do\n e<-getLine\n es<-getContents\n let xs=lines es\n ys=map (map read ) (map words xs)::[[Int]]\n print $ min (length (nub (fx ys))) (length (nub (fy ys)))"}], "src_uid": "89a8936bf7d43a9c5f69714a7cb7df82"} {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nsolve :: Int -> Int\r\nsolve 2 = 2\r\nsolve _ = 3\r\n\r\nhandleProblem :: IO ()\r\nhandleProblem = do\r\n input <- read <$> getLine\r\n print $ solve input\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberProblems <- read <$> getLine\r\n replicateM_ numberProblems handleProblem\r\n", "positive_code": [{"source_code": "main = interact $ dropWhile (/= '\\n')"}, {"source_code": "main :: IO ()\r\nmain = interact $ unwords . tail . words"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Lazy.Builder\r\nimport Data.ByteString.Lazy.Builder.ASCII\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . intercalate \" \" . map show\r\n\r\nsieve :: Int -> UArray Int Bool\r\nsieve n = runSTUArray $ do\r\n sieve <- newArray (2, n) True\r\n forM_ [2..n] $ \\p -> do\r\n isPrime <- readArray sieve p\r\n when isPrime $ do\r\n forM_ [p*2, p*3 .. n] $ \\k -> do\r\n writeArray sieve k False\r\n return sieve\r\n\r\nprimesUpto :: Int -> [Int]\r\nprimesUpto n = [p | (p, True) <- assocs $ sieve n]\r\n \r\nsolve n primes primeSet = head $ [m | m <- primes, Set.notMember (n+m) primeSet]\r\n\r\nisPrime x = all (\\i -> x `mod` i /= 0) [2..x-1]\r\n\r\nmain = do\r\n let primes = primesUpto 200000\r\n let primeSet = Set.fromList primes\r\n [t] <- getInts\r\n forM_ [1..t] $ \\_ -> do\r\n [n] <- getInts\r\n print $ solve n primes primeSet\r\n "}], "negative_code": [], "src_uid": "b7e36ca8a96dd7951359070d4953beec"} {"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n \r\nisSorted :: [Int] -> Bool\r\nisSorted [] = True\r\nisSorted (x: []) = True\r\nisSorted (x: y: xs) = x <= y && isSorted (y: xs)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n arr <- readIntArr\r\n if (isSorted arr)\r\n then putStrLn \"NO\"\r\n else putStrLn \"YES\"\r\n\r\nreadLoop :: Int -> IO ()\r\nreadLoop i =\r\n if (i == 0)\r\n then pure ()\r\n else do\r\n solve\r\n readLoop (i - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n readLoop n", "positive_code": [{"source_code": "main = interact $ unlines . map p . chunk 2 . drop 1 . lines\r\n\r\nchunk n [] = []\r\nchunk n xs = take n xs : chunk n (drop n xs)\r\n\r\ncheck = foldl (\\b c -> if (b == (-1)) || (c < b) then (-1) else c) 0\r\n\r\np xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]\r\n in if check s == (-1) then \"YES\" else \"NO\"\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n pure $ string7 $ if and $ zipWith (<=) a (tail a)\r\n then \"NO\\n\"\r\n else \"YES\\n\"\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\nimport Data.Maybe ( isNothing )\n\nnonDec :: Ord a => [a] -> Bool\nnonDec arr = helper arr 0 (length arr)\n where\n helper arr i l\n | i < l - 1 = arr !! i > arr !! (i + 1) || helper arr (i + 1) l\n | otherwise = False\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ if nonDec arr then \"YES\" else \"NO\"\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nenumerate = zip [0..]\r\n\r\nargmin :: [Int] -> Int\r\nargmin a = let t = enumerate a in\r\n fst $ foldl (\\(mni, mn) (i, x) -> if x < mn then (i, x) else (mni, mn)) (0, 999999999) t\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let\r\n sorta = sort a\r\n sorted = (==) a sorta\r\n pure . str $ if sorted then \"NO\\n\" else \"YES\\n\"\r\n"}], "negative_code": [{"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n \r\nisSorted :: [Int] -> Bool\r\nisSorted [] = True\r\nisSorted (x: []) = True\r\nisSorted (x: y: xs) = x <= y && isSorted (y: xs)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n arr <- readIntArr\r\n if (isSorted arr)\r\n then print \"NO\"\r\n else print \"YES\"\r\n\r\nreadLoop :: Int -> IO ()\r\nreadLoop i =\r\n if (i == 0)\r\n then pure ()\r\n else do\r\n solve\r\n readLoop (i - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n readLoop n"}], "src_uid": "ef1448a744f67347183479c697aa87e1"} {"source_code": "\nimport Data.List\n\nsolve :: Int -> [Int] -> Int\nsolve m xs = sum $ map count $ group $ sort xs\n where\n count ys@(y:_) = if y > m then length ys else length ys - 1\n\n(-->) = flip fmap\n\nmain = do\n m <- getLine --> read\n xs <- getLine --> words --> map read\n print $ solve m xs\n\n", "positive_code": [{"source_code": "import Data.List\n\nanswer1 :: String -> Int\nanswer1 str = sum.map f $ group str\n where\n f = \\x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1\n\nanswer2 :: Int -> [Int] -> Int\nanswer2 n xs = sum.map f.group.sort $ xs\n where\n f v = if n < head v \n then length v\n else length v -1\n\nmain = do n <- getLine\n print.answer2 (read n).map read.words =<< getLine"}, {"source_code": "import Data.List\n\nsolve (n:xs) = n - (length $ group $ sort $ filter (<=n) xs)\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "import Data.Array\n\nsolve n xs = length $ filter (==0) finalTable\n where finalTable = elems $ foldr updateTable initialTable xs\n initialTable = array (1, n) [(i, 0) | i <- [1..n]]\n updateTable x table = table // if x <= n then\n [(x, (table ! x) + 1)]\n else\n []\n \nmain = do n <- fmap read getLine\n xs <- fmap (map read.words) getLine\n putStrLn $ show $ solve n xs"}, {"source_code": "import List\nmain = interact $ show.s.sort.map read.tail.words\ns xs = let n = length xs in n - (length $ group $ filter (<=n) xs)\n"}, {"source_code": "import Control.Monad\nimport qualified Data.IntSet as S\nmain = do\n n <- readLn\n print . (n -) . S.size . S.fromList . filter (<= n) . map read . words =<< getLine\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do n <- getLine\n xs <- getLine\n print $ check (read n) $ map read $ words xs\n\ncheck :: Int -> [Int] -> Int\ncheck n xs = sum [f x | x <- group $ sort xs]\n where f x = length x - (if (head x) > n then 0 else 1)"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n\tgetLine\n\tx <- getLine\n\tputStr $ show $ getAnswer $ map (\\x -> read x :: Integer) (words x)\n\ngetAnswer xs = length $ (sort xs) `minus` [1..fromIntegral $ length xs]\n\nminus :: (Ord a) => [a] -> [a] -> [a]\nminus = minusBy compare\n\n-- | 'minusBy' is the non-overloaded version of 'minus'\nminusBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nminusBy cmp = loop\n where\n loop [] _ys = []\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs ys\n GT -> loop (x:xs) ys"}, {"source_code": "main :: IO ()\nmain = do n <- getLine\n xs <- getLine\n print $ solve n xs\n\nread' :: String -> Int\nread' = read\n\nsolve :: String -> String -> Int\nsolve n' xs' = length $ filter id $ map (flip notElem xs) [1..n]\n where n = read' n'\n xs = map read' $ words xs'\n\n\n"}, {"source_code": "import Data.List\nimport Data.Array\n\n\nmain = do\n n <- fmap read getLine :: IO Int\n a <- fmap (map read . words) getLine :: IO [Int]\n print . length . filter id . elems $ accumArray (&&) True (1, n) [(i, False) | i <- a, i >= 1 && i <= n]\n\n-- vim: set expandtab:\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.IntSet as Set\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read . words <$> getLine\n let ys = takeWhile (<= n) $ Set.toList $ Set.fromList xs\n print $ n - length ys\n"}, {"source_code": "f s x | null s = x | head s `elem` x = f (tail s) x | otherwise = f (tail s) (head s :x)\nfu s n = n - length (f s [])\nsolve s = [x | x<-tail s, x `elem` [1..head s]]\ncheck s | null $ solve s = head s | otherwise = fu (solve s) (head s)\nmain = interact $ show . check . map read .words\n"}, {"source_code": "import Control.Monad\nsolve :: Int -> [Int] -> Int\nsolve 0 _ = 0 \nsolve n xs \n | n `elem` xs = solve (n-1) xs\n | otherwise = 1 + (solve (n-1) xs)\nmain = do \n n <- readLn\n getLine >>= \n (\\str -> putStrLn $ \n (show . solve n . map read. words) str)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n print $ sum $ map (\\(i, x) -> if elem i [1..n] then max (x-1) 0 else x) $ assocs $ (accumArray (+) 0 (1, 5000) $ zip xs $ repeat (1 :: Int) :: UArray Int Int)\n"}, {"source_code": "import List\nmain = interact $ show. gao. map read. words\ngao (n:xs) = n - (length. takeWhile (<=n). map head.group.sort $ xs)\n"}, {"source_code": "-- rearranges\nimport Array\n\nreadL [] a akk = (read $ reverse a :: Int) : akk\nreadL (' ':xs) a akk = readL xs [] ((read $ reverse a :: Int) : akk)\nreadL (x:xs) a akk = readL xs (x:a) akk\n\nsolve [] a = a\nsolve (x:xs) a | (inRange (bounds a) x) = solve xs (a//[(x,0)])\n | otherwise = solve xs a\n\nmain = do\n\t\t\tqty <- readLn :: IO Int\n\t\t\tslist <- getLine\n\t\t\tprint $ foldr (+) 0 (elems (solve (readL slist [] []) (array (1,qty) [(i,1) | i <- [1..qty]])))\n"}, {"source_code": "module Main\n where\n\nimport IO\n\n\nget_num :: Char -> Int\n\nget_num c = case c of\n '0' -> 0\n '1' -> 1\n '2' -> 2\n '3' -> 3\n '4' -> 4\n '5' -> 5\n '6' -> 6\n '7' -> 7\n '8' -> 8\n '9' -> 9\n\nstrtoInt' :: Int -> String -> [Int]\n\nstrtoInt' tmp [] = [tmp]\nstrtoInt' tmp (s1:ss) = \n if (s1 == ' ')\n then tmp:(strtoInt' 0 ss)\n else strtoInt' (tmp * 10 + (get_num s1)) ss\n\n \nstrtoInt = strtoInt' 0\n\n\nsort :: [Int] -> [Int]\n\nsort [] = []\nsort (x:xs) = (sort [k | k <- xs, k < x]) ++ [x] ++ (sort [k | k <- xs, k >= x])\n\n\ncount :: [Int] -> Int\n\ncount (x1:x2:xs) = \n if x1 /= x2\n then 1 + count (x2:xs)\n else count (x2:xs)\ncount list = length list\n\n\nbadnum :: [Int] -> Int\nbadnum list = len - count (filter (\\x -> x <= len) list)\n where len = length list\n\n\nres_function :: String -> String\n\nres_function = show . badnum . sort . strtoInt\n\nmain = do\n hSetBuffering stdin LineBuffering\n tmp <- getLine\n tmp2 <- getLine \n putStrLn (res_function tmp2)\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve (n:xs) = n - (length (takeWhile (<= n) values))\n where\n values = map head.group.sort $ xs\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "import List\ngetAns a = (length a) - (length (intersect [1..(length a)] a))\nmain=interact$show.getAns.map read.tail.words"}, {"source_code": "import List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = n - length (nub (filter (<=n) xs))\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- Main.reads\n print (solve n xs)"}, {"source_code": "module Main where\nimport Data.List\nmain :: IO ()\nmain = do\n n <- readLn\n l <- getLine\n let ns = nub (map read $ words l :: [Integer])\n outside = fromInteger $ sum [1 | x <- ns, x > n]\n print (fromInteger n - length ns + fromInteger outside)\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.List\nmain :: IO ()\nmain = do\n _ <- getLine\n l <- getLine\n let ns = sort $ (map read $ words l :: [Integer])\n folddat (changes, curr) x =\n if curr == x\n then (changes + 1, x)\n else (changes, x)\n (ans,_) = foldl folddat (0, head ns) (tail ns)\n print ans\n"}, {"source_code": "module Main where\nimport Data.List\nmain :: IO ()\nmain = do\n n <- readLn\n l <- getLine\n let ns = nub (map read $ words l :: [Integer])\n print (n - length ns)\n"}, {"source_code": "module Main where\nimport Data.List\nmain :: IO ()\nmain = do\n _ <- getLine\n l <- getLine\n let ns = sort $ (map read $ words l :: [Integer])\n folddat (changes, curr) x =\n if curr == x\n then (changes + 1, x)\n else (changes + x - curr - 1, x)\n (ans,_) = foldl folddat (0, head ns) (tail ns)\n print ans\n"}, {"source_code": "import Data.List\n\nanswer1 :: String -> Int\nanswer1 str = sum.map f $ group str\n where\n f = \\x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1\n\nanswer2 :: Int -> [Int] -> Int\nanswer2 n xs = sum.map f.zip [1..n].sort $ xs\n where\n f (i,v) = if i==v then 0 else 1\n\nmain = do n <- getLine\n print.answer2 (read n).map read.words =<< getLine"}, {"source_code": "import Data.List\n\nanswer1 :: String -> Int\nanswer1 str = sum.map f $ group str\n where\n f = \\x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1\n\nanswer2 :: String -> Int\nanswer2 str = f.foldl max 1.map length.group.sort.words $ str\n where\n f 1 = 0\n f n = n-1\n\nmain = getLine >> getLine >>= print.answer2"}, {"source_code": "import Data.List\n\nsolve (n:xs) = n - (length $ group $ sort xs)\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "import List\nmain = interact $ show.length.filter id.(zipWith (/=) [1..]).sort.map read.tail.words\n"}, {"source_code": "import Control.Monad\nimport qualified Data.IntSet as S\nmain = print =<< liftM2 (-) readLn (liftM (S.size . S.fromList . map read . words) getLine)\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n\tgetLine\n\tx <- getLine\n\tputStr $ show $ getAnswer $ map (\\x -> read x :: Integer) (words x)\n\ngetAnswer xs = length xs - length (nub xs)"}, {"source_code": "import Data.List(sort)\n\nmain :: IO ()\nmain = do n <- getLine\n xs <- getLine\n print $ solve n xs\n\nread' :: String -> Int\nread' = read\n\nsolve :: String -> String -> Int\nsolve n' xs' = length $ filter id $ zipWith (/=) (sort xs) [1..n]\n where n = read' n'\n xs = map read' $ words xs'\n\n\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do n <- getLine\n xs <- getLine\n print $ check $ map read $ words xs\n\ncheck :: [Int] -> Int\ncheck xs = sum [length x - 1 | x <- group $ sort xs]"}, {"source_code": "import Data.List\nimport Data.Array\n\n\nmain = do\n n <- fmap read getLine :: IO Int\n a <- fmap (map read . words) getLine :: IO [Int]\n print . length . filter id . elems $ accumArray (||) False (1, n) [(i, True) | i <- a]\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.List\nimport Data.Array\n\n\nmain = do\n n <- fmap read getLine :: IO Int\n a <- fmap (map read . words) getLine :: IO [Int]\n print . length . filter id . elems $ accumArray (&&) True (1, n) [(i, False) | i <- a, i <- [1..n]]\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- fmap read getLine :: IO Int\n a <- fmap (map read . words) getLine :: IO [Int]\n print . sum $ zipWith (\\x y -> abs $ x - y) (sort a) [1..n]\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- fmap read getLine :: IO Int\n a <- fmap (map read . words) getLine :: IO [Int]\n print . length . filter id $ zipWith (/=) (sort a) [1..n]\n\n-- vim: set expandtab:\n"}, {"source_code": "f s x | null s = x | head s `elem` x = f (tail s) x | otherwise = f (tail s) (head s :x)\nfu s = head s - length (f s [])\nsolve s = [x | x<-tail s, x `elem` [1..head s]]\ncheck s | null $ solve s = head s | otherwise = fu s\nmain = interact $ show . check . map read .words"}, {"source_code": "import List\nmain = interact $ show. gao. words\ngao (n:xs) = (read n) - (length. group. sort $ xs)\n"}, {"source_code": "module Main\n where\n\nimport IO\n\n\nget_num :: Char -> Int\n\nget_num c = case c of\n '0' -> 0\n '1' -> 1\n '2' -> 2\n '3' -> 3\n '4' -> 4\n '5' -> 5\n '6' -> 6\n '7' -> 7\n '8' -> 8\n '9' -> 9\n\nstrtoInt' :: Int -> String -> [Int]\n\nstrtoInt' tmp [] = [tmp]\nstrtoInt' tmp (s1:ss) = \n if (s1 == ' ')\n then tmp:(strtoInt' 0 ss)\n else strtoInt' (tmp * 10 + (get_num s1)) ss\n\n \nstrtoInt = strtoInt' 0\n\n\nsort :: [Int] -> [Int]\n\nsort [] = []\nsort (x:xs) = [k | k <- xs, k < x] ++ [x] ++ [k | k <- xs, k >= x]\n\n\nbadnum :: [Int] -> Int\n\nbadnum (x1:x2:xs) = \n if x1 == x2 \n then 1 + badnum (x2:xs)\n else badnum (x2:xs)\nbadnum _ = 0\n\n\nres_function :: String -> String\n\nres_function = show . badnum . sort . strtoInt\n\nmain = do\n hSetBuffering stdin LineBuffering\n tmp <- getLine\n tmp2 <- getLine \n putStrLn (res_function tmp2)\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve (n:xs) = n - (length (takeWhile (<= n) values))\n where values = head $ group $ sort $ xs\n\nmain = interact $ show.solve.map read.words"}], "src_uid": "bdd86c8bc54bbac6e2bb5a9d68b6eb1c"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tpositions = map snd $ sort $ zip as [ 0 .. ]\n\tprint $ solve ( 0, 0 ) positions\n\nsolve a b = solve' 0 a b\n\nsolve' res _ [] = res\nsolve' res ( x, y ) ( a : b : rest ) =\u3000res `seq` solve' ( res + min d1 d2 ) ( a, b ) rest\n\twhere\n\t\td1 = abs ( a - x ) + abs ( b - y )\n\t\td2 = abs ( b - x ) + abs ( a - y )", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tpositions = map snd $ sort $ zip as [ 0 .. ]\n\tprint $ solve ( 0, 0 ) positions\n\nsolve a b = solve' 0 a b\n\nsolve' res _ [] = res\nsolve' res ( x, y ) ( a : b : rest ) = solve' ( res + min d1 d2 ) ( a, b ) rest\n\twhere\n\t\td1 = abs ( a - x ) + abs ( b - y )\n\t\td2 = abs ( b - x ) + abs ( a - y )"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tpositions = map snd $ sort $ zip as [ 0 .. ]\n\tprint $ solve ( 0, 0 ) positions\n\nsolve _ [] = 0\nsolve ( x, y ) ( a : b : rest ) = min d1 d2 + solve ( a, b ) rest\n\twhere\n\t\td1 = abs ( a - x ) + abs ( b - y )\n\t\td2 = abs ( b - x ) + abs ( a - y )"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tpositions = map snd $ sort $ zip as [ 0 .. ]\n\tprint $ solve ( 0, 0 ) positions\n\nsolve a b = solve' 0 a b\n\nsolve' !res _ [] = res\nsolve' !res ( x, y ) ( a : b : rest ) = res `seq` solve' ( res + min d1 d2 ) ( a, b ) rest\n\twhere\n\t\td1 = abs ( a - x ) + abs ( b - y )\n\t\td2 = abs ( b - x ) + abs ( a - y )"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tpositions = map snd $ sort $ zip as [ 0 .. ]\n\tprint $ solve ( 0, 0 ) positions\n\nsolve a b = solve' 0 a b\n\nsolve' !res _ [] = res\nsolve' !res !( x, y ) ( a : b : rest ) = solve' ( res + min d1 d2 ) ( a, b ) rest\n\twhere\n\t\td1 = abs ( a - x ) + abs ( b - y )\n\t\td2 = abs ( b - x ) + abs ( a - y )"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: Int -> Map Int [Int] -> Integer\nprocess n tiers = l where\n (_, l) = foldl walk ((1, 1), 0 :: Integer) [1..n]\n dist a b = abs (a - b)\n walk ((p1, p2), l) n = ret where\n [d1, d2] = tiers Map.! n\n case1 = dist p1 d1 + dist p2 d2\n case2 = dist p1 d2 + dist p2 d1\n ret = if case1 < case2 then ((d1, d2), l + toInteger case1) else ((d2, d1), l + toInteger case2)\n\nmain = do\n n <- getInt\n tiers <- makeMap n <$> getInts :: IO (Map Int [Int])\n print $ process n tiers\n\nmakeMap n (tiers ::[Int]) = foldl (\\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where\n initMap = Map.fromList $ zip [1..n] (repeat [])\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: Int -> Map Int [Int] -> Int\nprocess n tiers = l1 + l2 where\n (tiers', _, l1) = foldl firstWalk (tiers , 1, 0) [1..n]\n (_ , _, l2) = foldl secondWalk (tiers', 1, 0) [1..n]\n dist a b = abs (a - b)\n firstWalk (m :: Map Int [Int], p, l) n = (m', p', l') where\n [d1, d2] = m Map.! n\n (dest, rest) = if dist p d1 < dist p d2 then (d1, d2) else (d2, d1)\n m' = Map.update (const $ Just [rest]) n m\n p' = dest\n l' = l + dist p p'\n secondWalk (m, p, l) n = (m, p', l') where\n [d] = m Map.! n\n p' = d\n l' = l + dist p p'\n\nmain = do\n n <- getInt\n tiers <- makeMap n <$> getInts :: IO (Map Int [Int])\n print $ process n tiers\n\nmakeMap n (tiers ::[Int]) = foldl (\\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where\n initMap = Map.fromList $ zip [1..n] (repeat [])\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: Int -> Map Int [Int] -> Int\nprocess n tiers = l where\n (_, l) = foldl walk ((1, 1), 0) [1..n]\n dist a b = abs (a - b)\n walk ((p1, p2), l) n = ret where\n [d1, d2] = tiers Map.! n\n case1 = dist p1 d1 + dist p2 d2\n case2 = dist p1 d2 + dist p2 d1\n ret = if case1 < case2 then ((d1, d2), l + case1) else ((d2, d1), l + case2)\n\nmain = do\n n <- getInt\n tiers <- makeMap n <$> getInts :: IO (Map Int [Int])\n print $ process n tiers\n\nmakeMap n (tiers ::[Int]) = foldl (\\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where\n initMap = Map.fromList $ zip [1..n] (repeat [])\n"}], "src_uid": "dc9c2703aa7aaf1d254211cf06030329"} {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt && cat -- *.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map (concat . map ((++\" \").show) . solve)) tcs\r\n\r\nreadTC = do\r\n [n,m] <- map read . words <$> getLine :: IO [Int]\r\n return (n,m)\r\n\r\nsolve (n,m) | (n < m) = solve (m,n)\r\n | otherwise = sort fld\r\n where\r\n (offV, offV_e) = centerProps n\r\n (offH, offH_e) = centerProps m\r\n\r\n maxDistFromCenter = (offV_e - 1) + (offH_e - 1)\r\n\r\n fld = bfs maxDistFromCenter (n,m) (offV, offH) (offV_e, offH_e)\r\n\r\ncenterProps :: Int -> (Int, Int)\r\ncenterProps n = (i, i+w)\r\n -- offsets of the center (start, past the end)\r\n where\r\n i = (n-w) `div` 2\r\n\r\n w = case (n`mod`2) of 0 -> 2\r\n 1 -> 1\r\n _ -> error \"bad parity\"\r\n\r\nbfs x (n, m) (r_b, c_b) (r_e, c_e) = elems arr\r\n where\r\n arr = array ((0,0), (n-1,m-1))\r\n [((r,c), f (r,c)) | r <- [0..n-1],\r\n c <- [0..m-1]]\r\n\r\n f (r,c) | (r_b <= r && r < r_e &&\r\n c_b <= c && c < c_e) = x\r\n | otherwise = 1 + (arr ! iprev (r,c))\r\n\r\n iprev (r,c) | (r' /= r) = (r', c )\r\n | (c' /= c) = (r , c')\r\n | otherwise = error \"no prev cell\"\r\n where\r\n r' = iprev1D (r_b,r_e) r\r\n c' = iprev1D (c_b,c_e) c\r\n\r\niprev1D (b,e) n | (n < b) = n+1\r\n | (n >= e) = n-1\r\n | otherwise = n\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ntest :: IO ()\ntest = do\n [n, m] <- (<$>) read . words <$> getLine\n let a = (enumFromTo <*> (+ (m - 1))) <$> [0 .. n - 1]\n let grid = foldl1 (zipWith (zipWith max)) [a, reverse a, reverse <$> a, reverse $ reverse <$> a]\n let values = sort $ concat grid\n putStrLn $ unwords $ show <$> values\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\n{-\n\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n\n4 5 6\n3 4 5\n2 3 4\n1 2 3\n\n3 2 1\n4 3 2\n5 4 3\n6 5 4\n\n6 5 4\n5 4 3\n4 3 2\n3 2 1\n\n6 5 6\n5 4 5\n5 4 5\n6 5 6\n\n-}\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n \r\n \r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n, m] <- getInts 2\r\n pure $ putInts $ sort [ (max i (n-1-i)) + (max j (m-1-j)) | i <- [0..n-1], j <- [0..m-1]]\r\n \r\ntype SP = State [P.ByteString]\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt && cat -- *.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map (concat . map ((++\" \").show) . solve)) tcs\r\n\r\nreadTC = do [n,m] <- map read . words <$> getLine :: IO [Int]\r\n return (n,m)\r\n\r\nsolve (n,m) = sort [md n r + md m c | r <- [1..n],\r\n c <- [1..m]]\r\nmd n r = max (r-1) (n-r)\r\n"}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt && cat -- *.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map (concat . map ((++\" \").show) . solve)) tcs\r\n\r\nreadTC = do\r\n [n,m] <- map read . words <$> getLine :: IO [Int]\r\n return (n,m)\r\n\r\nsolve (n,m) | (n < m) = solve (m,n)\r\n | otherwise = sort fld\r\n where\r\n (offV, _lenV, offV_e) = centerProps n\r\n (offH, _lenH, offH_e) = centerProps m\r\n\r\n maxDistFromCenter = (offV_e - 1) + (offH_e - 1)\r\n\r\n fld = bfs maxDistFromCenter (n,m) (offV, offH) (offV_e, offH_e)\r\n\r\ncenterProps :: Int -> (Int, Int, Int)\r\ncenterProps n = (i, w, i+w)\r\n -- offset and length of the center,\r\n -- also offset past the center\r\n where\r\n i = (n-w) `div` 2\r\n\r\n w = case (n`mod`2) of 0 -> 2\r\n 1 -> 1\r\n _ -> error \"bad parity\"\r\n\r\nbfs x (n, m) (r_b, c_b) (r_e, c_e) = elems arr\r\n where\r\n arr = array ((0,0), (n-1,m-1))\r\n [((r,c), f (r,c)) | r <- [0..n-1],\r\n c <- [0..m-1]]\r\n\r\n f (r,c) | (r_b <= r && r < r_e &&\r\n c_b <= c && c < c_e) = x\r\n | otherwise = 1 + (arr ! iprev (r,c))\r\n\r\n iprev (r,c) | (r' /= r) = (r', c )\r\n | (c' /= c) = (r , c')\r\n | otherwise = error \"no prev cell\"\r\n where\r\n r' = iprev1D (r_b,r_e) r\r\n c' = iprev1D (c_b,c_e) c\r\n\r\niprev1D (b,e) n | (n < b) = n+1\r\n | (n >= e) = n-1\r\n | otherwise = n\r\n"}], "negative_code": [], "src_uid": "dc1dc5e5dd17d19760c772739ce244a7"} {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\ns -> C.getLine >>= \\bs -> let [f1,f2] = map read $ words ns in (mapM_ print).(solve f1 bs) =<< (forM [1..f2] $ \\ i ->C.getLine>>= \\js -> let [a,b] = C.words js in return $ (fst $ fromJust $ C.readInt a,C.head b) )\nsolve n xs1 xs2 = map (snd) $ tail $ scanl f (ms,s) xs2\n where\n ms=Map.fromList $ [(0,'a')] ++ (zip [1..] $ C.unpack xs1) ++ [(n+1,'a')]\n s=sum $ map (\\a -> C.length a -1 ) $ C.groupBy (\\a b -> a==b && a=='.') xs1\n f (b1,b2) (a1,a2) | (a2=='.' && b1 Map.! a1=='.') || (a2/='.' && b1 Map.! a1/='.') = (Map.insert a1 a2 b1, b2)\n | a2=='.' && b1 Map.! (a1-1)=='.' && b1 Map.! (a1+1)=='.' = (Map.insert a1 a2 b1, b2+2)\n | a2/='.' && b1 Map.! (a1-1)=='.' && b1 Map.! (a1+1)=='.' = (Map.insert a1 a2 b1, b2-2)\n | a2=='.' && (b1 Map.! (a1-1)=='.' || b1 Map.! (a1+1)=='.') = (Map.insert a1 a2 b1, b2+1)\n | a2/='.' && (b1 Map.! (a1-1)=='.' || b1 Map.! (a1+1)=='.') = (Map.insert a1 a2 b1, b2-1)\n | otherwise = (Map.insert a1 a2 b1, b2)", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, RecordWildCards #-}\n\nimport Control.Monad\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\n\ndata Tree =\n Leaf !Char |\n Node {\n left :: !Tree,\n right :: !Tree,\n _size :: !Int,\n _prefix :: !Int,\n _suffix :: !Int,\n _count :: !Int\n }\n\n\nsize (Leaf _) = 1\nsize (Node {..}) = _size\n\nprefix (Leaf '.') = 1\nprefix (Leaf _) = 0\nprefix (Node {..}) = _prefix\n\nsuffix (Leaf '.') = 1\nsuffix (Leaf _) = 0\nsuffix (Node {..}) = _suffix\n\ncount (Leaf _) = 0\ncount (Node {..}) = _count\n\ndotsOnly (Leaf '.') = True\ndotsOnly (Leaf _) = False\ndotsOnly (Node {..}) = _prefix == _size\n\n\nmake left right = Node left right newSize newPrefix newSuffix newCount\n where\n newSize = size left + size right\n newPrefix = prefix left + if dotsOnly left then prefix right else 0\n newSuffix = suffix right + if dotsOnly right then suffix left else 0\n newCount = count left + count right + joint\n joint = if suffix left > 0 && prefix right > 0 then 1 else 0\n\n\nconstruct s\n | B.length s == 1 = Leaf $ B.head s\n | otherwise =\n let (left, right) = B.splitAt (B.length s `unsafeShiftR` 1) s\n in make (construct left) (construct right)\n\n\nupdate c = update'\n where\n update' (Leaf _) !_ = Leaf c\n update' (Node {..}) !i\n | i < size left = make (update' left i) right\n | otherwise = make left (update' right (i - size left))\n\n\nrun 0 !_ = return ()\n\nrun q !tree = do\n (i, tl) <- liftM (fromJust . B.readInt) B.getLine\n let next = update (tl `B.index` 1) tree (i - 1)\n putStrLn $ show $ count next\n run (q - 1) next\n\n\nmain = do\n m <- liftM (fst . fromJust . B.readInt . head . tail . B.split ' ') B.getLine\n B.getLine >>= run m . construct\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM)\nimport Control.Arrow (second)\nimport Data.List (group)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Array.Unboxed (UArray, listArray)\nimport Control.Monad.ST.Strict (ST, runST)\nimport Data.Array.ST (STUArray,readArray, writeArray, thaw)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\n\nupdate :: Int -> Bool -> (Bool, Bool, Bool) -> Int\nupdate val t (x, y, z)\n | t == y = val\n | t = val + inc\n | otherwise = val - inc\n where inc = (if x then 1 else 0) + if z then 1 else 0\n\nsolve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]\nsolve val' arr' query = runST $ do\n arr <- thaw arr' :: ST s (STUArray s Int Bool)\n val <- newSTRef val'\n\n forM query $ \\(i, t) -> do\n x <- readArray arr $ pred i\n y <- readArray arr i\n z <- readArray arr $ succ i\n cur <- readSTRef val\n\n writeSTRef val $ update cur t (x, y, z)\n writeArray arr i t\n readSTRef val\n\nwrap :: Int -> ByteString -> [ByteString] -> [Int]\nwrap n line query = solve val arr mut\n where\n mut = second pred . fromJust . C.readInt <$> query\n where pred = (== \" .\") . C.take 2\n\n arr = listArray (0, n + 1) run\n run = False: C.foldr (\\i acc -> (i == '.'):acc) [False] line\n val = sum . map (pred . length) . filter head . group $ run\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [n, m] <- parse <$> B.getLine\n line <- C.take n <$> B.getLine\n query <- replicateM m B.getLine\n mapM_ print $ wrap n line query\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM)\nimport Control.Arrow (second)\nimport Data.List (group)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Array.Unboxed (UArray, listArray)\nimport Control.Monad.ST.Strict (ST, runST)\nimport Data.Array.ST (STUArray,readArray, writeArray, thaw)\n\ncount :: Bool -> [Bool] -> Int\ncount t xs = if t then inc else -inc\n where inc = length $ filter id xs\n\nsolve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]\nsolve val inp query = tail . scanl (+) val $ runST $ do\n arr <- thaw inp :: ST s (STUArray s Int Bool)\n\n forM query $ \\(i, t) -> do\n xi <- readArray arr i\n if xi == t\n then return 0\n else do\n a <- readArray arr $ pred i\n b <- readArray arr $ succ i\n writeArray arr i t\n return $ count t [a, b]\n\nwrap :: Int -> ByteString -> [ByteString] -> [Int]\nwrap n line query = solve val arr mut\n where\n mut = second pred . fromJust . C.readInt <$> query\n where pred = (== \" .\") . C.take 2\n\n arr = listArray (0, n + 1) run\n run = False: C.foldr (\\i acc -> (i == '.'):acc) [False] line\n val = sum . map (pred . length) . filter head . group $ run\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [n, m] <- parse <$> B.getLine\n line <- C.take n <$> B.getLine\n query <- replicateM m B.getLine\n mapM_ print $ wrap n line query\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\ns -> C.getLine >>= \\bs -> let [f1,f2] = map read $ words ns in (mapM_ print).(solve f1 bs) =<< (forM [1..f2] $ \\ i ->C.getLine>>= \\js -> let [a,b] = C.words js in return $ (fst $ fromJust $ C.readInt a,C.head b) )\nsolve n xs1 xs2 = map (snd) $ tail $ scanl f (ms,s) xs2\n where\n ms=Map.fromList $ [(0,'a')] ++ (zip [1..] $ C.unpack xs1) ++ [(n+1,'a')]\n s=sum $ map (\\a -> C.length a -1 ) $ C.groupBy (\\a b -> a==b && a=='.') xs1\n f (b1,b2) (a1,a2) | a2=='.' && b1 Map.! (a1-1)=='.' && b1 Map.! (a1+1)=='.' = (Map.insert a1 a2 b1, b2+2)\n | a2/='.' && b1 Map.! (a1-1)=='.' && b1 Map.! (a1+1)=='.' = (Map.insert a1 a2 b1, b2-2)\n | a2=='.' && (b1 Map.! (a1-1)=='.' || b1 Map.! (a1+1)=='.') = (Map.insert a1 a2 b1, b2+1)\n | a2/='.' && (b1 Map.! (a1-1)=='.' || b1 Map.! (a1+1)=='.') = (Map.insert a1 a2 b1, b2-1)\n | otherwise = (Map.insert a1 a2 b1, b2)"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM)\nimport Control.Arrow (second)\nimport Data.List (group)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Array.Unboxed (UArray, listArray)\nimport Control.Monad.ST.Strict (ST, runST)\nimport Data.Array.ST (STUArray,readArray, writeArray, thaw)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef)\n\nupdate :: Int -> Bool -> (Bool, Bool, Bool) -> Int\nupdate val t (x, y, z)\n | t == y = val\n | t = val + inc\n | otherwise = val - inc\n where inc = (if x then 1 else 0) + if z then 1 else 0\n\nsolve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]\nsolve val' arr' query = runST $ do\n arr <- thaw arr' :: ST s (STUArray s Int Bool)\n val <- newSTRef val'\n\n forM query $ \\(i, t) -> do\n x <- readArray arr $ pred i\n y <- readArray arr i\n z <- readArray arr $ succ i\n cur <- readSTRef val\n\n writeSTRef val $ update cur t (x, y, z)\n writeArray arr i t\n readSTRef val\n\nwrap :: Int -> ByteString -> [ByteString] -> [Int]\nwrap n line query = solve val arr mut\n where\n mut = second (== \" .\") . fromJust . C.readInt <$> query\n arr = listArray (0, n + 1) run\n run = False: C.foldr (\\i acc -> (i == '.'):acc) [False] line\n val = sum . map (pred . length) . filter head . group $ run\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [n, m] <- parse <$> B.getLine\n line <- B.getLine\n query <- replicateM m B.getLine\n mapM_ print $ wrap n line query\n"}], "src_uid": "68883ab115882de5cf77d0848b80b422"} {"source_code": "\nsolve :: [Int] -> [String]\nsolve [x, y, a, b] =\n let variants = [[i, j] | i <- [a .. x], j <- [b .. y], i > j]\n in (show $ length variants):(map (unwords . map show) variants)\n\nmain = interact $ unlines . solve . map read . words", "positive_code": [{"source_code": "main = do\n\tx <- getLine\n\tputStrLn $ show $ length $ res x\n\tputStrLn $ unlines $ map (\\(a,b) -> unwords [show a, show b]) $ res x\n\twhere \n\t\tres = f . map (\\a -> read a::Int) . words\n\nf :: [Int] -> [(Int, Int)]\nf [a,b,c,d] = [(x,y) | x <- [c..a], y<-[d..b], x>y] "}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [x, y, a, b] = [(i, j) | i <- [a .. x], j <- [b .. y], i > j]\n\nprints :: (Show a, Show b) => [(a, b)] -> IO ()\nprints xs = print (length xs) >> mapM_ prints' xs\n where\n prints' (a, b) = putStrLn $ show a ++ \" \" ++ show b\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve\n"}, {"source_code": "import Data.List\n\nmain = do\n [x,y,a,b] <- fmap (map read . words) getLine\n let pairs = solve [x,y,a,b]\n print $ length pairs\n mapM_ (\\(x,y) -> putStrLn $ show x ++ \" \" ++ show y) pairs\n \nsolve :: [Integer] -> [(Integer,Integer)]\nsolve [x,y,a,b] = sort [(f,g) | f <- [a..x], g <- [b..y], f > g]\n"}, {"source_code": "main = do\n [x,y,a,b] <- fmap (map read.words) getLine\n let ans = [unwords$map show[sv,sp]|sv<-[a..x],sp<-[b..y],sv>sp+0]\n print $ length ans\n putStrLn $ unlines ans"}, {"source_code": "main = interact $ unlines . map (unwords . map show) . solve . map read . words\nsolve [x, y, a, b] = [length out] : out\n where out = [[c, d] | c <- [a..x], d <- [b..y], c > d]"}, {"source_code": "import Data.List\nmain = solve.map read.words =<< getLine\nsolve :: [Int] -> IO ()\nsolve [x,y,a,b] = do\n let s = sln a b x y\n print $ length s\n mapM_ (\\(x,y) -> putStrLn $ show x ++ \" \" ++ show y) s\nsln a b x y = concatMap f [a..x]\n where f n = [(n,d) | d <- takeWhile (\\x' -> x' <= y) [b..], d < n]"}, {"source_code": "main = do\n [x, y, a, b] <- fmap (map read . words) getLine\n let z = [[i, j] | i <- [a .. x], j <- [b .. y], i > j] :: [[Int]]\n print $ length $ z\n putStr $ unlines $ map (unwords . map show) z\n"}, {"source_code": "main = interact $ unlines . map (unwords . map show) . solve . map read . words\n\nsolve [x, y, a, b] = [length outcomes] : outcomes\n where\n outcomes = [[c, d] | c <- [a..x], d <- [b..y], c > d]\n"}], "negative_code": [{"source_code": "import Data.List\nmain = solve.map read.words =<< getLine\nsolve [x,y,a,b] = do\n let s = sln a b x y\n print $ length s\n mapM_ (\\(x,y) -> putStrLn $ show x ++ \" \" ++ show y) s\nsln a b x y = concatMap f [(min (b+1) a) .. x]\n where f n = [(n,d) | d <- takeWhile (\\x' -> x' <= y) [b..], d < n]"}, {"source_code": "import Data.List\nmain = solve.map read.words =<< getLine\nsolve [x,y,a,b] = do\n let s = sln a b x y\n print $ length s\n mapM_ (\\(x,y) -> putStrLn $ show x ++ \" \" ++ show y) s\nsln a b x y = concatMap f [(min (b+1) a) .. x]\n where f n = [(n,d) | d <- takeWhile (\\x' -> x' <= y && x' < n) [b..], d < n]"}, {"source_code": "import Data.List\nmain = solve.map read.words =<< getLine\nsolve [x,y,a,b] = do\n let s = sln a b x y\n print $ length s\n mapM_ (\\(x,y) -> putStrLn $ show x ++ \" \" ++ show y) s\nsln a b x y = concatMap f [(min (b+1) a) .. x]\n where f n = [(n,d) | d <- takeWhile (\\x' -> x' <= y && x' < n+1) [b..], d < n]"}, {"source_code": "import Data.List\nmain = solve.map read.words =<< getLine\nsolve [x,y,a,b] = do\n let s = sln a b x y\n print $ length s\n mapM_ (\\(x,y) -> putStrLn $ show x ++ \" \" ++ show y) s\nsln a b x y = concatMap f [(min (b+1) a) .. x]\n where f n = [(n,d) | d <- takeWhile (\\x' -> x' <= y && x' < n-1) [b..], d < n]"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [x, y, a, b] = [(i, j) | i <- [a .. x], j <- [b .. y], i > j]\n\nprints :: (Show a, Show b) => [(a, b)] -> IO ()\nprints xs = mapM_ prints' xs\n where\n prints' (a, b) = putStrLn $ show a ++ \" \" ++ show b\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= prints . solve\n"}], "src_uid": "bb3e3b51a4eda8fef503952a00777910"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _ <- C.getLine\n (as : ass) <- replicateM 4 (fmap (zip [1..]) getInts)\n let\n cmp (_, c1) (_, c2) = compare c1 c2\n trans pres edges nexts (j, cost) =\n case filter (\\(i, _) -> S.notMember (i, j) edges) pres of\n ((_, c) : _) -> (j, c + cost) : nexts\n _ -> nexts\n acc pres ys = do\n [m] <- getInts\n edges <- S.fromList <$> replicateM m (getInts >>= \\[i, j] -> return (i, j))\n return $ sortBy cmp $ foldl' (trans pres edges) [] ys\n results <- foldM acc (sortBy cmp as) ass\n putStrLn $ if null results then \"-1\" else show $ snd $ head results\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport qualified Data.IntMap.Strict as Map\n\ntype SIO = StateT P.ByteString IO\n\nsentinel :: Int\nsentinel = 5 * 10 ^ (8 :: Int)\n\nstep :: UArray Int Int -> [(Int, Int)] -> UArray Int Int -> UArray Int Int\nstep prevCosts excls currCosts = let\n initMap = Map.fromListWith (+) $ zip (sentinel : elems prevCosts) (repeat 1)\n updateFun 1 = Nothing\n updateFun v = Just (v - 1)\n remove = flip $ Map.update updateFun\n exclusionResults :: Array Int (Map.IntMap Int)\n exclusionResults = accumArray remove initMap (bounds currCosts)\n $ [(yi, prevCosts ! xi) | (xi, yi) <- excls]\n in array (bounds currCosts) $ do\n (i, v) <- assocs currCosts\n let nv = v + fst (Map.findMin $ exclusionResults ! i)\n pure (i, min sentinel nv)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n ns <- readInts\n [a, b, c, d] <- forM ns $ \\ni -> listArray (1, ni) <$> readInts\n [excl1, excl2, excl3] <- replicateM 3 $ do\n [mi] <- readInts\n replicateM mi $ do\n [xi, yi] <- readInts\n pure (xi, yi)\n let\n s2 = step a excl1 b\n s3 = step s2 excl2 c\n s4 = step s3 excl3 d\n ans = case foldl' min sentinel $ elems s4 of\n v | v == sentinel -> 0-1\n | otherwise -> v\n putInts [ans]\n\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n ~[n1, n2, n3, n4] <- popInts\n a <- popInts\n b <- popInts\n c <- popInts\n d <- popInts\n ab <- popPairs n1\n bc <- popPairs n2\n cd <- popPairs n3\n return $ bshow (solve n1 n2 n3 n4 a b c d ab bc cd) <> \"\\n\"\n\n where\n popPairs n = do\n m <- popInt\n buildPairs n <$> replicateM m ((\\ ~[x, y] -> (x - 1, y - 1)) <$> popInts)\n\n buildPairs n ps = IntSet.fromList <$> accumArray (flip (:)) [] (0, n - 1) ps\n\n\ninf = (maxBound :: Int)\n\nthird (_, _, x) = x\n\n\nsolve :: Int -> Int -> Int -> Int -> [Int] -> [Int] -> [Int] -> [Int] ->\n Array Int IntSet -> Array Int IntSet -> Array Int IntSet -> Int\nsolve n1 n2 n3 n4 a b c d ab bc cd =\n case sortOn snd $ id' of\n [] -> -1\n ((_, v):_) -> v\n\n where\n ia :: [(Int, Int)]\n ia = sortOn snd $ zip [0..] a\n\n ib :: [(Int, Int)]\n ib = makeI ia n2 b ab\n\n ic :: [(Int, Int)]\n ic = makeI ib n3 c bc\n\n id' :: [(Int, Int)]\n id' = makeI ic n4 d cd\n\n makeI :: [(Int, Int)] -> Int -> [Int] -> Array Int IntSet -> [(Int, Int)]\n makeI is jn jv bans =\n sortOn snd $\n map (\\(i, x, y) -> (i, x + y)) $\n filter ((/= inf) . third) $\n zip3 [0..] jv $\n make bans is [0 .. jn - 1]\n\n make :: Array Int IntSet -> [(Int, Int)] -> [Int] -> [Int]\n make bans is js = map snd $ sort $ makeV [] bans is js\n\n makeV :: [(Int, Int)] -> Array Int IntSet -> [(Int, Int)] -> [Int] ->\n [(Int, Int)]\n makeV acc _ [] js = (zip js $ repeat inf) ++ acc\n makeV acc _ _ [] = acc\n makeV acc bans ((i, x) : is) js = makeV' acc bans i x is js []\n\n makeV' :: [(Int, Int)] -> Array Int IntSet -> Int -> Int -> [(Int, Int)] ->\n [Int] -> [Int] -> [(Int, Int)]\n makeV' acc bans i x is [] js' = makeV acc bans is js'\n makeV' acc bans i x is (j : js) js'\n | IntSet.member j (bans ! i) = makeV' acc bans i x is js (j : js')\n | otherwise = makeV' ((j, x) : acc) bans i x is js js'\n"}], "negative_code": [], "src_uid": "ed0765719bfc3903701c0c14b7ad15c7"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Array.Base\nimport Data.Function(on)\nimport Data.Tuple(swap)\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: Int -> [Int] -> IM.IntMap Int\nsolve 0 _ = IM.empty\nsolve 1 (p:_) = IM.singleton p (p+1)\nsolve n ps = merge (solve n1 ps) (solve n2 (drop n1 ps)) where\n n1 = div n 2\n n2 = n - n1\n\nmerge :: IM.IntMap Int -> IM.IntMap Int -> IM.IntMap Int\nmerge l1 l2 = uncurry IM.union $ go ((,) l2 (IM.empty)) l1 where\n go = IM.foldlWithKey' $ \\(!m,!acc) a b ->\n case IM.lookup b m of\n Just c -> (,) (IM.delete b m) (IM.insert a c acc)\n Nothing -> (,) m (IM.insert a b acc)\n\nmain :: IO ()\nmain = do\n n <- readLn\n ps <- readInts\n let l = solve n ps\n let d = IM.foldlWithKey' (\\acc a b -> max acc (b - a)) 0 l\n print $ n - d\n\n-- IO\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair :: IO (Int,Int)\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadAllInts :: IO [[Int]]\nreadAllInts = map (map readInt . B.words) . B.lines <$> B.getContents\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\n\n-- Utilities\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\nl2p _ = error \"l2p: the input list is too short\"\np2l :: (a,a) -> [a]\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ninf :: Int\ninf = maxBound `div` 2\n\n-- Monad\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i0 judge incr step = sub i0 where \n sub i | judge i = step i >> sub (incr i) \n | otherwise = return ()\nrep_ :: Monad m => Int -> (Int -> m ()) -> m ()\nrep_ n = stepM_ 0 ( (v -> m ()) -> v -> m v\nthru m v = m v >> return v\nmemoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v\nmemoize getter setter key action = do\n mv <- getter key\n case mv of\n Just v -> return v\n Nothing -> action >>= thru (setter key)\n\n-- Array\nnewUArray :: (MArray (STUArray s) e (ST s),Ix i) => \n (i,i) -> e -> ST s (STUArray s i e)\nnewUArray = newArray\nnewBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)\nnewBArray = newArray\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nfromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]\nfromEdges = accumArray (flip (:)) []\n", "positive_code": [{"source_code": "import Data.List.Split (splitOn)\nimport Data.List\n\nlongestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int\n\nlongestsubsequence [] prev count maxi = maxi\nlongestsubsequence (x:xs) prev count maxi\n | snd prev < snd x = longestsubsequence xs x (count+1) thus\n | snd prev > snd x && count > maxi = longestsubsequence xs x 1 count\n | otherwise = longestsubsequence xs x 1 maxi\n where thus = if (count+1) > maxi then count+1 else maxi\nmain = do\n asd <- getLine\n dsa <- getLine\n let amount = read asd :: Int\n let sequence = [read x :: Int | x <- splitOn \" \" dsa]\n let sortedlist = sort (zip sequence [0..])\n putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 1))"}, {"source_code": "{-\nCodeforces Round #335\n\nProblem 606 C. Sorting Railway\n\n@author yamaton\n@date 2015-12-11\n-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Text.Printf (printf)\nimport qualified Data.List as L\n-- import qualified Data.Map.Strict as M\n-- import qualified Data.Set as S\n-- import qualified Data.Foldable as F\n-- import qualified Data.Traversable as T\n\n-- Longest contiguous increasing sequence length\nlcis :: Ord a => [a] -> Int\nlcis [] = 0\nlcis (x:xs) = helper 1 1 x xs\n where\n helper :: Ord a => Int -> Int -> a -> [a] -> Int\n helper best _ _ [] = best\n helper best curr p (q:qs)\n | p <= q = helper (max best curr_p1) curr_p1 q qs\n | otherwise = helper best 1 q qs\n where curr_p1 = curr + 1\n\n\ninvPerm :: [Int] -> [Int]\ninvPerm xs = map snd . L.sort $ zip xs [1..]\n\n\nsolve :: [Int] -> Int -> Int\nsolve xs n = n - lcis (invPerm xs)\n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- (map read . words) <$> getLine :: IO [Int]\n let result = solve xs n\n print result\n\n -- IO.hPutStrLn IO.stderr $ printf \"xs = %s\" (show xs)\n -- IO.hPutStrLn IO.stderr $ printf \"result = %d\" result\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ngroupBy' :: (a -> a -> Bool) -> [a] -> [[a]]\ngroupBy' _ [] = []\ngroupBy' _ [x] = [[x]]\ngroupBy' cmp (x:xs@(x':_)) | cmp x x' = (x:y):ys\n | otherwise = [x]:r\n where r@(y:ys) = groupBy' cmp xs\n\nmain = do\n n <- readLn\n xs <- getInts :: IO [Int]\n\n print $ minimum $ map (\\x -> n-x) $ map length $ groupBy' (<=) $ elems $ array (1, n) $ zip xs [1..]\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Array.Base\nimport Data.Function(on)\nimport Data.Tuple(swap)\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\n\nsolve :: [Int] -> [(Int,Int)]\nsolve [] = []\nsolve [p] = [(p,p+1)]\nsolve ps = merge (solve ps1) (solve ps2) where\n n = length ps\n (ps1,ps2) = splitAt (div n 2) ps\n\nmerge :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]\nmerge l1 l2 = go (M.fromList l2) l1 where\n go m [] = M.toList m\n go m ((a,b):l) =\n case M.lookup b m of\n Just c -> (a,c) : go (M.delete b m) l\n Nothing -> (a,b) : go m l\n\nmain :: IO ()\nmain = do\n n <- readLn\n ps <- readInts\n let l = solve ps\n print $ n - maximum [ b - a | (a,b) <- l ]\n\n-- IO\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair :: IO (Int,Int)\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadAllInts :: IO [[Int]]\nreadAllInts = map (map readInt . B.words) . B.lines <$> B.getContents\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\n\n-- Utilities\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\nl2p _ = error \"l2p: the input list is too short\"\np2l :: (a,a) -> [a]\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ninf :: Int\ninf = maxBound `div` 2\n\n-- Monad\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i0 judge incr step = sub i0 where \n sub i | judge i = step i >> sub (incr i) \n | otherwise = return ()\nrep_ :: Monad m => Int -> (Int -> m ()) -> m ()\nrep_ n = stepM_ 0 ( (v -> m ()) -> v -> m v\nthru m v = m v >> return v\nmemoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v\nmemoize getter setter key action = do\n mv <- getter key\n case mv of\n Just v -> return v\n Nothing -> action >>= thru (setter key)\n\n-- Array\nnewUArray :: (MArray (STUArray s) e (ST s),Ix i) => \n (i,i) -> e -> ST s (STUArray s i e)\nnewUArray = newArray\nnewBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)\nnewBArray = newArray\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nfromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]\nfromEdges = accumArray (flip (:)) []\n"}], "negative_code": [{"source_code": "import Data.List.Split (splitOn)\nimport Data.List\n\nlongestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int\n\nlongestsubsequence [] prev count maxi = maxi\nlongestsubsequence (x:xs) prev count maxi\n | snd prev < snd x = longestsubsequence xs x (count+1) maxi\n | snd prev > snd x && count > maxi = longestsubsequence xs x 1 count\n | otherwise = longestsubsequence xs x 1 maxi\n\nmain = do\n asd <- getLine\n dsa <- getLine\n let amount = read asd :: Int\n let sequence = [read x :: Int | x <- splitOn \" \" dsa]\n let sortedlist = sort (zip sequence [0..])\n putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 1))"}, {"source_code": "import Data.List.Split (splitOn)\nimport Data.List\n\nlongestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int\n\nlongestsubsequence [] prev count maxi = maxi\nlongestsubsequence (x:xs) prev count maxi\n | snd prev < snd x = longestsubsequence xs x (count+1) maxi\n | snd prev > snd x && count > maxi = longestsubsequence xs x 1 count\n | otherwise = longestsubsequence xs x 1 maxi\n\nmain = do\n asd <- getLine\n dsa <- getLine\n let amount = read asd :: Int\n let sequence = [read x :: Int | x <- splitOn \" \" dsa]\n let sortedlist = sort (zip sequence [0..])\n putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 0))"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ngroupBy' :: (a -> a -> Bool) -> [a] -> [[a]]\ngroupBy' _ [] = []\ngroupBy' _ [x] = [[x]]\ngroupBy' cmp (x:xs@(x':_)) | cmp x x' = (x:y):ys\n | otherwise = [x]:r\n where r@(y:ys) = groupBy' cmp xs\n\nmain = do\n n <- readLn\n xs <- getInts :: IO [Int]\n\n print $ minimum $ map (\\x -> n-x) $ map length $ groupBy (<=) $ elems $ array (1, n) $ zip xs [1..]\n"}], "src_uid": "277948a70c75840445e1826f2b23a897"} {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t readLn :: IO [Integer]\n\n (putStr . unlines . map (showP . solve)) tcs\n\nsolve k | (b <= k && k <= b+i-1 ) = (k-b+1, i )\n | (b+i-1 < k && k < b+2*i-1) = (i, b+2*i-1-k)\n | otherwise = error \"bad b calculation?\"\n where\n i = (floor.sqrt) (fromIntegral (k-1) :: Double) + 1\n b = (i-1)*(i-1) + 1\n\nshowP (a,b) = show a ++ \" \" ++ show b\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\n\r\ngetCellPosByIndex :: Integer -> (Integer, Integer)\r\ngetCellPosByIndex cell_index = (x, y)\r\n where\r\n wave_index = floorSqrt cell_index\r\n local_index = cell_index - wave_index ^ 2\r\n x = min wave_index (2 * wave_index - local_index)\r\n y = min wave_index local_index\r\n\r\n\r\nfloorSqrt :: Integer -> Integer\r\nfloorSqrt x = binarySearch 0 x\r\n where\r\n binarySearch l r\r\n | l == r = mid\r\n | mid ^ 2 <= x = binarySearch mid r\r\n | otherwise = binarySearch l (mid-1)\r\n where mid = (l + r + 1) `div` 2\r\n\r\n\r\nprocess_test :: String -> String\r\nprocess_test input = output\r\n where\r\n k = read input\r\n (x, y) = getCellPosByIndex (k - 1)\r\n output = show (y+1) ++ \" \" ++ show (x+1)\r\n\r\n\r\nmain :: IO()\r\nmain = do\r\n tests_n <- read <$> getLine\r\n tests_inputs <- replicateM tests_n getLine\r\n let outputs = map process_test tests_inputs\r\n mapM_ putStrLn outputs\r\n"}, {"source_code": "import Control.Monad\r\n\r\n\r\ngetCellPosByIndex :: Integer -> (Integer, Integer)\r\ngetCellPosByIndex cell_index = (x, y)\r\n where\r\n wave_index = floorSqrt cell_index\r\n local_index = cell_index - wave_index ^ 2\r\n x = min wave_index (2 * wave_index - local_index)\r\n y = min wave_index local_index\r\n\r\n\r\nfloorSqrt :: Integer -> Integer\r\nfloorSqrt x = binary_search 0 x\r\n where binary_search l r\r\n | l == r = mid\r\n | mid ^ 2 <= x = binary_search mid r\r\n | otherwise = binary_search l (mid-1)\r\n where mid = (l + r + 1) `div` 2\r\n\r\n\r\nprocess_test :: String -> String\r\nprocess_test input = output\r\n where\r\n k = read input\r\n (x, y) = getCellPosByIndex (k - 1)\r\n output = show (y+1) ++ \" \" ++ show (x+1)\r\n\r\n\r\nmain :: IO()\r\nmain = do\r\n tests_n <- read <$> getLine\r\n tests_inputs <- replicateM tests_n getLine\r\n let outputs = map process_test tests_inputs\r\n mapM_ putStrLn outputs\r\n"}, {"source_code": "import Control.Monad\r\n\r\n\r\ngetCellPosByIndex :: Integer -> (Integer, Integer)\r\ngetCellPosByIndex cell_index = (x, y)\r\n where i_wave = floorSqrt cell_index\r\n local_index = cell_index - i_wave ^ 2\r\n x = min (2*i_wave - local_index) i_wave\r\n y = min local_index i_wave\r\n\r\n\r\nfloorSqrt :: Integer -> Integer\r\nfloorSqrt i = fromIntegral $ length $ takeWhile (<= i) positive_squares\r\n where positive_squares = map (^2) [1..]\r\n\r\n\r\nprocess_test :: String -> String\r\nprocess_test input = output\r\n where k = read input\r\n (x, y) = getCellPosByIndex (k - 1)\r\n output = show (y+1) ++ \" \" ++ show (x+1)\r\n\r\n\r\nmain :: IO()\r\nmain = do\r\n tests_n <- read <$> getLine\r\n tests_inputs <- replicateM tests_n getLine\r\n let outputs = map process_test tests_inputs\r\n mapM_ putStrLn outputs\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\na002522_list = scanl (+) 1 [1, 3..] :: [Int64]\n\ncalc :: Int64 -> [Int64]\ncalc 1 = [1,1]\ncalc 2 = [1,2]\ncalc x =\n let first = dropWhile (\\(i,an) -> an <= x) $ zip [1..] a002522_list\n ((m,an1):_) = first\n n = m-1\n an = (n-1)*(n-1)+1\n in\n if (x-an) <= ((an1-an) `div` 2) then\n [x-an+1, n]\n else\n [n, an1-x]\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let k = read line :: Int64\n putStrLn $ unwords $ map show $ calc k\n"}, {"source_code": "position :: Int -> (Int, Int)\nposition n = let\n p | steps == 0 = (sqrtN, 1)\n | steps <= (sqrtN + 1) = (steps, sqrtN + 1)\n | otherwise = (sqrtN + 1, sqrtN * 2 + 2 - steps)\n in p\n where\n sqrtN = (floor . sqrt . fromIntegral) n\n steps = n - sqrtN ^ 2\n\nloop :: Int -> IO()\nloop 0 = return ()\nloop n = do\n nth <- readLn :: IO Int\n let (r, c) = position nth\n putStrLn $ concat [show r, \" \", show c]\n loop $ n - 1\n\nmain :: IO()\nmain = do\n input <- getLine\n let n = read input :: Int\n loop n\n\n \t\t \t \t\t\t \t \t \t\t \t\t"}, {"source_code": "import Data.Function ((&))\n\nmain = do\n t <- read <$> getLine :: IO Int\n mapM_ main' [1..t]\n\nmain':: Int -> IO ()\nmain' _ = do\n k <- read <$> getLine :: IO Int\n solve k & show' & putStrLn\n\nshow' :: (Int, Int) -> String\nshow' (a, b) = show a ++ \" \" ++ show b\n\nsolve :: Int -> (Int, Int)\nsolve k\n | row == 0 = (l, 1)\n | row <= l + 1 = (row, l + 1)\n | otherwise = (l + 1, col)\n where\n l = k & fromIntegral & sqrt & floor :: Int\n row = k - l * l\n col = (l + 1) * (l + 1) - k + 1"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t\r\n $ do\r\n getLine\r\n >>= (\\(x, y) -> putStrLn (show x ++ \" \" ++ show y)) . solve . read\r\n\r\nsolve :: Int -> (Int, Int)\r\nsolve k = (ij - max (diag - k) 0, ij - max (k - diag) 0)\r\n where\r\n ij = contSq k\r\n\r\n diag = ij ^ 2 - ij + 1\r\n\r\ncontSq :: Int -> Int\r\ncontSq x = until ((x <=) . (^ 2)) (+ 1) 1\r\n{-\r\n>>>contSq 100000000\r\n10000\r\n\r\n>>>solve 100000000\r\n(10000,1)\r\n\r\n(2,4)\r\n-}\r\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n k <- readLn :: IO Integer\r\n let n = ceiling $ sqrt $ fromInteger k\r\n a = n*n - k\r\n r = if a <= n - 1 then n else n - (a - (n-1))\r\n c = if a <= n - 1 then a + 1 else n\r\n putStrLn . unwords . map show $ [r,c]\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\n\r\n\r\ngetCellPosByIndex :: Integer -> (Integer, Integer)\r\ngetCellPosByIndex cell_index = (x, y)\r\n where\r\n wave_index = floorSqrt cell_index\r\n local_index = cell_index - wave_index ^ 2\r\n x = min wave_index (2 * wave_index - local_index)\r\n y = min wave_index local_index\r\n\r\n\r\nfloorSqrt :: Integer -> Integer\r\nfloorSqrt x = binarySearch 0 x\r\n where\r\n binarySearch l r\r\n | l == r = mid\r\n | mid ^ 2 <= x = binarySearch mid r\r\n | otherwise = binarySearch l (mid-1)\r\n where mid = (l + r + 1) `div` 2\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n k = read input\r\n (x, y) = getCellPosByIndex (k - 1)\r\n output = show (y+1) ++ \" \" ++ show (x+1)\r\n\r\n\r\nmain :: IO()\r\nmain = do\r\n tests_n <- read <$> getLine\r\n tests_inputs <- replicateM tests_n getLine\r\n let outputs = map processTest tests_inputs\r\n mapM_ putStrLn outputs\r\n"}], "negative_code": [], "src_uid": "f8335c59cd05988c8053f138c4df06aa"} {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- C.getLine\r\n b <- C.getLine\r\n if m == 1\r\n then if C.head b `C.elem` a then putStrLn \"YES\" else putStrLn \"NO\"\r\n else if m == n\r\n then if a == b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else\r\n let (hd,tl) = C.splitAt (n - m + 1) a\r\n in do\r\n -- print (hd, tl)\r\n if tl /= C.tail b then putStrLn \"NO\" else if C.head b `C.elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = map readInt . words <$> getLine >>= \\[n,m] -> getLine >>= \\a -> getLine >>= \\b ->\r\n putStrLn . yn $ (tail b) == (drop (n - m + 1) a) && head b `elem` (take (n - m + 1) a)\r\n\r\nyn True = \"YES\"\r\nyn _ = \"NO\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n"}, {"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\nimport Data.List\r\n\r\nmain = interact $ unlines . aux . tail . lines\r\n\r\naux [] = []\r\naux (_:x:y:xs) = (if f x y then \"YES\" else \"NO\"): aux xs\r\n\r\n\r\nf as (b:bs) = elem b xs && bs == ys\r\n where\r\n bL = length bs\r\n aL = length as\r\n (xs,ys) = splitAt (aL-bL) as\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- getLine\r\n b <- getLine\r\n if m == 1\r\n then if head b `elem` a then putStrLn \"YES\" else putStrLn \"NO\"\r\n else if m == n\r\n then if a == b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else\r\n let (hd,tl) = splitAt (n - m + 1) a\r\n in do\r\n -- print (hd, tl)\r\n if tl /= tail b then putStrLn \"NO\" else if head b `elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- getLine\r\n b <- getLine\r\n if m == 1\r\n then if last a == head b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else if m == n\r\n then if a == b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else\r\n let (hd,tl) = splitAt (n - m + 1) a\r\n in do\r\n -- print (hd, tl)\r\n if tl /= tail b then putStrLn \"NO\" else if head b `elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- getLine\r\n b <- getLine\r\n if m == 1\r\n then if last a == head b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else if m == n\r\n then if a == b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else\r\n let (hd, _ : tl) = splitAt (length a - m + 1) a\r\n in if tl /= tail b then putStrLn \"NO\" else if head b `elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- getLine\r\n b <- getLine\r\n if m == 1\r\n then if last a == head b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else if m == n\r\n then if a == b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else\r\n let (hd, _ : tl) = splitAt (length a - m - 1) a\r\n in if tl /= tail b then putStrLn \"NO\" else if head b `elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- getLine\r\n b <- getLine\r\n if n == m\r\n then if a == b then putStrLn \"YES\" else putStrLn \"NO\"\r\n else\r\n let (hd, _ : tl) = splitAt (length a - m) a\r\n in if tl /= tail b then putStrLn \"NO\" else if head b `elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( findIndex\r\n , foldl'\r\n , unfoldr, elemIndex\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n a <- getLine\r\n b <- getLine\r\n let (hd, _ : tl) = splitAt (length a - m) a\r\n if tl /= tail b then putStrLn \"NO\" else if head b `elem` hd then putStrLn \"YES\" else putStrLn \"NO\"\r\n\r\n\r\n\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = map readInt . words <$> getLine >>= \\[n,m] -> getLine >>= \\a -> getLine >>= \\b ->\r\n putStrLn . yn $ (tail b) == (drop (n - m + 1) a) && head b `elem` (take (n - m) a)\r\n\r\nyn True = \"YES\"\r\nyn _ = \"NO\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n"}], "src_uid": "83050a8a4c7b64004681bdadb630292e"} {"source_code": "import Data.List\nimport Control.Applicative\nimport Debug.Trace\n\nsolve :: [Int] -> [Int] -> String\nsolve [n, _, maxMark, maxPoints, minMedian] scores =\n if median full >= minMedian && maximum full <= maxMark && sum full <= maxPoints then\n unwords $ map show $ res\n else\n \"-1\"\n where\n track q = trace (show q) q\n maxOnes = (n `div` 2) - (length $ filter ( getLine\n scores <- map read . words <$> getLine\n putStrLn $ solve x scores\n", "positive_code": [{"source_code": "import Data.List \nanswer::Int -> Int -> Int -> Int -> Int -> [Int] -> [Int]\nanswer n k p x y a | ll0 > med = [(-1)]\n | ll1 >= med+1 = if (sum a) + n2 <= x then take n2 (repeat 1) else [(-1)]\n | sum a + n0 + y*n1 <=x = (take n0 (repeat 1)) ++ (take n1 (repeat y))\n | otherwise = [(-1)] \n where (l0,l1) = partition ( Int) (words l1))\n (sort (map (read :: String -> Int) (words l2))) \n\nsolundra :: [Int] -> [Int] -> String\n\nsolundra (n:k:_:x:y:[]) l = let \n wen = length [x | x <- l, x < y]\n gro = length [x | x <- l, x >= y]\n zol = bober wen gro (n-k) y\n in if wen >= gro && wen - gro > n-k || sum zol + sum l > x \n then \"-1\" \n else unwords $ map show zol\n \n \nbober :: Int -> Int -> Int -> Int -> [Int]\n\nbober _ _ 0 _ = []\nbober w g a y = if w < g - 1 \n then 1 : bober (w+1) g (a-1) y\n else y : bober w (g+1) (a-1) y\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: [Int] -> [Int] -> String\nsolve [n, _, maxMark, maxPoints, minMedian] scores =\n if median full >= minMedian && maximum full <= maxMark && sum full <= maxPoints then\n unwords $ map show $ res\n else\n \"-1\"\n where\n maxOnes = (n `div` 2) - (length $ filter ( getLine\n scores <- map read . words <$> getLine\n putStrLn $ solve x scores\n"}], "src_uid": "f01d11bd231a7b2e7ca56de1df0f1272"} {"source_code": "import Data.List\n\nsolve x b e = length ( filter (\\y->(y>b) && (yread x::Integer) (words d)\n\t_<-getLine\n\tx<-getLine\n\tlet dat = map (\\x->read x::Integer) (words x)\n\tprint (solve dat b e)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nmain = getInts >>= \\[_, l, r] -> getLine >> getInts >>= print . length . filter (liftA2 (&&) (>l) ( Int -> Int -> Int\nsolve [] _ _ = 0\nsolve (x : xs) b c = r + (solve xs b c)\n where r = case x > b && x < c of\n True -> 1\n False -> 0\n\nmain :: IO ()\nmain = do\n [a, b, c] <- map (read :: String -> Int) . words <$> getLine\n n <- (read :: String -> Int) <$> getLine\n xis <- map (read :: String -> Int) . words <$> getLine\n putStrLn . show $ solve xis b c\n"}, {"source_code": "import Control.Applicative( (<$>))\nmain = do\n [a_, b_, c_] <- map read . words <$> getLine\n n_ <- readLn::IO Int\n xs_ <- map (read::String->Int) . words <$> getLine\n print . length $ filter (\\i->b_) . B.words\n\nsolve a b c n xs = length $ filter (\\x -> b < x && x < c) xs\n\nmain = do \n a:b:c:_ <- readInts <$> B.getLine\n n <- readInt <$> B.getLine\n xs <- readInts <$> B.getLine\n print $ solve a b c n xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nmain = do\n\t\t[a,b,c]<- map read <$> words <$> getLine ::IO [Int]\n\t\tgetLine\n\t\td<- filter ( filter (>b) <$> map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ length d\n\t\n\n"}], "negative_code": [], "src_uid": "aceadc8eadf6d5efd7c5a9fbc0396423"} {"source_code": "import Control.Monad\r\nimport Data.Int\r\n\r\ngetInt :: IO Int \r\ngetInt = readLn \r\n\r\nsolve :: Int -> Int -> (Int, Int)\r\nsolve a b = (a - b, min p t)\r\n where k = a - b \r\n p = b `mod` k \r\n t = k - p \r\n\r\nmain :: IO ()\r\nmain = do \r\n test <- getInt\r\n replicateM_ test $ do\r\n [a, b] <- map read.words <$> getLine :: IO[Int]\r\n if a == b then putStrLn \"0 0\"\r\n else do \r\n let (res1, res2) = solve (max a b) (min a b)\r\n putStrLn $ show res1 ++ \" \" ++ show res2 ", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Int (Int64)\r\n\r\ngetInt :: IO Int \r\ngetInt = readLn \r\n\r\nsolve :: Int -> Int -> (Int, Int)\r\nsolve a b = (a - b, min p t)\r\n where k = a - b \r\n p = b `mod` k \r\n t = k - p \r\n\r\nmain :: IO ()\r\nmain = do \r\n test <- readLn :: IO Int \r\n replicateM_ test $ do\r\n [a, b] <- map read.words <$> getLine :: IO[Int]\r\n if a == b then putStrLn \"0 0\"\r\n else do \r\n let (res1, res2) = solve (max a b) (min a b)\r\n putStrLn $ show res1 ++ \" \" ++ show res2 "}, {"source_code": "import Control.Monad\r\nimport Data.Int\r\n\r\ngetInt :: IO Int \r\ngetInt = readLn \r\n\r\nsolve :: Int64 -> Int64 -> (Int64, Int64)\r\nsolve a b = (a - b, min p t)\r\n where k = a - b \r\n p = b `mod` k \r\n t = k - p \r\n\r\nmain :: IO ()\r\nmain = do \r\n test <- getInt\r\n replicateM_ test $ do\r\n [a, b] <- map read.words <$> getLine :: IO[Int64]\r\n if a == b then putStrLn \"0 0\"\r\n else do \r\n let (res1, res2) = solve (max a b) (min a b)\r\n putStrLn $ show res1 ++ \" \" ++ show res2 "}, {"source_code": "\nmodule Main where\nimport Control.Monad ( replicateM )\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int \n inp <- replicateM t $ do\n inpline <- getLine\n let spl = map read $ words inpline :: [Integer]\n return spl\n let solved = map ((\\[a, b] -> show a ++ \" \" ++ show b) . solve) inp\n -- print inp\n traverse putStrLn solved\n return ()\n\nsolve :: [Integer] -> [Integer]\nsolve [a, b] =\n let\n ans1 = abs(a - b)\n frnt = (div a ans1 + 1) * ans1 - a\n back = (div a ans1) * ans1 - a\n ans2 = if ans1 == 0 then 0 else min (abs frnt) (abs back)\n in\n [ans1, ans2]\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nreadInts :: IO [Integer]\r\nreadInts = map read . words <$> getLine\r\n\r\nsolve :: Integer -> Integer -> (Integer, Integer)\r\nsolve x y = if x == y then (0, 0) else (d, min left right) where\r\n (a, b) = (max x y, min x y)\r\n d = a - b\r\n left = b `rem` d\r\n right = d - b `rem` d\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [a, b] <- readInts\r\n let (exc, steps) = solve a b\r\n putStrLn $ show exc ++ \" \" ++ show steps"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [x, y] = map read $ words s :: [Int64]\n (a, b) = (max x y, min x y)\n best = if a == b then 0 else a - b\n re = rem b (a-b)\n steps = if best == 0 then 0 else min re ((a-b) - re)\n in putStrLn $ show best ++ \" \" ++ show steps\n \n\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintResult = do\r\n [a,b] <- readInts\r\n if a == b then putStrLn \"0 0\"\r\n else do\r\n let m = max a b\r\n n = min a b\r\n s = m - n\r\n d = div m s\r\n g = min (m-d*s) (d*s+s-m)\r\n putStrLn $ show s ++ \" \" ++ show g \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.Int ( Int64 )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [a, b] <- readMany :: IO [Int64]\r\n let d = abs (a - b)\r\n m = a `mod` d\r\n putStrLn $ if a == b then \"0 0\" else show d ++ \" \" ++ show (min m (d - m))\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "negative_code": [{"source_code": "\nmodule Main where\nimport Control.Monad ( replicateM )\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int \n inp <- replicateM t $ do\n inpline <- getLine\n let spl = map read $ words inpline :: [Integer]\n return spl\n let solved = map ((\\[a, b] -> show a ++ \" \" ++ show b) . solve) inp\n print inp\n print solved\n return ()\n\nsolve :: [Integer] -> [Integer]\nsolve [a, b] =\n let\n ans1 = abs(a - b)\n frnt = (div a ans1 + 1) * ans1 - a\n back = (div a ans1) * ans1 - a\n ans2 = if ans1 == 0 then 0 else min (abs frnt) (abs back)\n in\n [ans1, ans2]\n"}], "src_uid": "994a9cb52cf0fdab72be068eab1b27ef"} {"source_code": "import Data.Array\r\nimport Data.Bits\r\nimport Data.Foldable\r\nimport Data.Int\r\nimport Data.List\r\nimport qualified Data.Map as M\r\n\r\nm :: Int64\r\nm = 998244353\r\n\r\nmulmod :: Int64 -> Int64 -> Int64\r\nmulmod a b = a * b `mod` m\r\ninfixl 7 `mulmod`\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [k, a', h] <- readMany\r\n let a = fromIntegral a' :: Int64\r\n n = 2^k\r\n n' = n `div` 2\r\n apw = listArray (0, n + 1) $ iterate (mulmod a) 1\r\n hash ips = sum [fromIntegral i `mulmod` apw!p | (i, p) <- ips] `mod` m\r\n winlose b x y = if b then (x, y) else (y, x)\r\n pairs = flip go 0 where\r\n go [] _ = []\r\n go ~(x0:x1:xs) i = (i, x0, x1) : go xs (i + 1)\r\n\r\n genhashes :: Int -> Int -> (Int64, [(Int, Int)])\r\n genhashes l msk = (hash ips, reverse ips) where\r\n ips = go msk [l .. l + n' - 1]\r\n go _ [x] = [(x, 2)]\r\n go msk xs = ips ++ go (msk `shiftR` len) xs' where\r\n rs = [winlose (msk `testBit` i) x y | (i, x, y) <- pairs xs]\r\n len = length rs\r\n xs' = map fst rs\r\n ips = zip (map snd rs) $ repeat $ 2 * len + 1\r\n\r\n test mp0 mp1 =\r\n [ (ips'++) <$> mp1 M.!? h1\r\n | (h0, (w, 2):ips) <- M.assocs mp0\r\n , let h1 = (h - h0 - fromIntegral w * (apw!1 - apw!2)) `mod` m\r\n ips' = (w, 1):ips\r\n ]\r\n\r\n [mp0, mp1] = M.fromList . (<$> [0 .. 2^(n'-1)-1]) . genhashes <$> [1, n' + 1]\r\n\r\n putStrLn $ maybe \"-1\" (unwords . map (show . snd) . sort) $ asum (test mp0 mp1 ++ test mp1 mp0)\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n", "positive_code": [{"source_code": "import Data.Array\r\nimport Data.Bits\r\nimport Data.Foldable\r\nimport Data.Int\r\nimport Data.List\r\nimport qualified Data.Map as M\r\n \r\nm :: Int64\r\nm = 998244353\r\n \r\nmulmod :: Int64 -> Int64 -> Int64\r\nmulmod a b = a * b `mod` m\r\ninfixl 7 `mulmod`\r\n \r\nsolve :: IO ()\r\nsolve = do\r\n [k, a', h] <- readMany\r\n let a = fromIntegral a' :: Int64\r\n n = 2^k\r\n n' = n `div` 2\r\n apw = listArray (0, n + 1) $ iterate (mulmod a) 1\r\n hash ips = sum [fromIntegral i `mulmod` apw!p | (i, p) <- ips] `mod` m\r\n winlose b x y = if b then (x, y) else (y, x)\r\n pairs = flip go 0 where\r\n go [] _ = []\r\n go ~(x0:x1:xs) i = (i, x0, x1) : go xs (i + 1)\r\n \r\n genhashes :: Int -> Int -> (Int64, [(Int, Int)])\r\n genhashes l msk = (hash ips, reverse ips) where\r\n ips = go msk [l .. l + n' - 1]\r\n go _ [x] = [(x, 2)]\r\n go msk xs = ips ++ go (msk `shiftR` len) xs' where\r\n rs = [winlose (msk `testBit` i) x y | (i, x, y) <- pairs xs]\r\n len = length rs\r\n xs' = map fst rs\r\n ips = zip (map snd rs) $ repeat $ 2 * len + 1\r\n \r\n test mp0 mp1 =\r\n [ (ips'++) <$> mp1 M.!? h1\r\n | (h0, (w, 2):ips) <- M.assocs mp0\r\n , let h1 = (h - h0 - fromIntegral w * (apw!1 - apw!2)) `mod` m\r\n ips' = (w, 1):ips\r\n ]\r\n \r\n [mp0, mp1] = M.fromList . (<$> [0 .. 2^(n'-1)-1]) . genhashes <$> [1, n' + 1]\r\n \r\n putStrLn $ maybe \"-1\" (unwords . map (show . snd) . sort) $ asum (test mp0 mp1 ++ test mp1 mp0)\r\n \r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = solve"}], "negative_code": [], "src_uid": "f3d9afa76d0309e9688784c5de238cfe"} {"source_code": "first2 l = (head l, head $ tail l) \r\n\r\ngetPair :: IO (Int, Int)\r\ngetPair = do\r\n s <- getLine\r\n let res = map read $ words s\r\n return $ first2 res\r\n\r\ncount :: [(Int, Int)] -> (Int, Int) -> Int\r\ncount l (a, b) = foldl check (-1) l\r\n where check i (x, y) = if x == a || x == b || y == a || y == b \r\n then i + 1 \r\n else i\r\nmain = do\r\n n <- fmap read getLine\r\n mon <- sequence (replicate n getPair)\r\n putStr $ show $ (sum $ map (count mon) mon) `div` 2", "positive_code": [{"source_code": "import Data.Map (Map, insertWith, empty, toList)\r\n\r\nfirst2 l = (head l, head $ tail l) \r\n\r\ngetPair :: IO (Int, Int)\r\ngetPair = do\r\n s <- getLine\r\n let res = map read $ words s\r\n return $ first2 res\r\n\r\ncount l (a, b) = foldl check (-1) l\r\n where check i (x, y) = if x == a || x == b || y == a || y == b \r\n then i + 1 \r\n else i\r\n\r\ncombination n = n * (n - 1) `div` 2\r\n\r\nallPairs m (a, b) | a == b = insertWith (+) a 1 m\r\n | otherwise = insertWith (+) a 1 $ insertWith (+) b 1 m\r\n\r\nextraPairs m (a, b) | a < b = insertWith (+) (a, b) 1 m\r\n | a > b = insertWith (+) (b, a) 1 m\r\n | otherwise = m\r\n\r\nsolution l = (sum $ map (combination . snd) $ toList $ foldl allPairs empty l) -\r\n (sum $ map (combination . snd) $ toList $ foldl extraPairs empty l)\r\n\r\nmain = do\r\n n <- fmap read getLine\r\n mon <- sequence (replicate n getPair)\r\n putStr $ show $ solution mon"}], "negative_code": [{"source_code": "import Data.Map (Map, insertWith, empty, toList)\r\n\r\nfirst2 l = (head l, head $ tail l) \r\n\r\ngetPair :: IO (Int, Int)\r\ngetPair = do\r\n s <- getLine\r\n let res = map read $ words s\r\n return $ first2 res\r\n\r\ncount :: [(Int, Int)] -> (Int, Int) -> Int\r\ncount l (a, b) = foldl check (-1) l\r\n where check i (x, y) = if x == a || x == b || y == a || y == b \r\n then i + 1 \r\n else i\r\n\r\ncombination n = n * (n - 1) `div` 2\r\n\r\nallPairs m (a, b) | a == b = insertWith (+) a 1 m\r\n | otherwise = insertWith (+) a 1 $ insertWith (+) b 1 m\r\n\r\nextraPairs m (a, b) | a < b = insertWith (+) (a, b) 1 m\r\n | a > b = insertWith (+) (b, a) 1 m\r\n | otherwise = m\r\n\r\nsolution :: [(Int, Int)] -> Int\r\nsolution l = (sum $ map (combination . snd) $ toList $ foldl allPairs empty l) -\r\n (sum $ map (combination . snd) $ toList $ foldl extraPairs empty l)\r\n\r\nmain = do\r\n n <- fmap read getLine\r\n mon <- sequence (replicate n getPair)\r\n putStr $ show $ solution mon"}], "src_uid": "32c99f64fdf69b9fd87b07dbd14ceffa"} {"source_code": "check :: Int -> [Int] -> Bool\r\ncheck _ [] = True\r\ncheck _ (_: []) = True\r\ncheck i (x: y: xs)\r\n | i == 1 = check 0 (y: xs)\r\n | i > 1 = if x < y\r\n then False\r\n else check (i - 1) (y: xs)\r\n | i == 0 = if x > y\r\n then False\r\n else check 0 (y: xs)\r\n\r\nabsA :: [Int] -> (Int, [Int])\r\nabsA [] = (0, [])\r\nabsA (x: xs) = let (c, ys) = absA xs in if x > 0\r\n then (c, (x: ys))\r\n else (c + 1, (-x: ys))\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n _ <- readLn :: IO Int\r\n arr <- (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n let (c, x) = absA arr\r\n if check c x\r\n then putStrLn \"YES\"\r\n else putStrLn \"NO\"\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n for t", "positive_code": [{"source_code": "import Control.Monad\n\nisSorted :: Ord a => [a] -> Bool\nisSorted (h1:h2:t) = (h1 <= h2) && isSorted (h2:t)\nisSorted _ = True\n\nsolve :: [Int] -> Bool\nsolve ints = isSorted (negativeInts ++ positiveInts)\n where negativeCount = length $ filter (<0) ints\n negativeInts = map (\\x -> - (abs x)) $ take negativeCount $ ints\n positiveInts = map abs $ drop negativeCount $ ints\n\nreadInt :: String -> Int\nreadInt = read\n\nshowBool :: Bool -> String\nshowBool True = \"YES\"\nshowBool False = \"NO\"\n\ntestCaseMain :: IO ()\ntestCaseMain = do _ <- getLine\n line <- getLine\n putStrLn . showBool . solve . map readInt . words $ line\n\nmain :: IO ()\nmain = do t <- (readLn :: IO Int)\n forM_ [1..t] (\\_ -> testCaseMain)\n"}], "negative_code": [], "src_uid": "430f34fe715b8dcbcadf3b2c3e1e0381"} {"source_code": "import Data.Sequence as S\nimport Data.Foldable as F\nmain = getLine >>= print . fst . F.foldl f (0, 1) . tails . fromList\ng c n d\n | n >= 4 = True\n | n >= S.length c = False\n | otherwise = index c n == index d n && g c (n + 1) d\nf (a, b) c\n | g c 0 (fromList \"bear\") = (a + b * (S.length c - 3), 1)\n | otherwise = (a, b + 1)", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n f s = case findIndex (isPrefixOf \"bear\") (tails s) of\n Just i -> length s - (i+4) + 1\n Nothing -> 0\n\n where\n print $ sum $ map f $ tails s\n"}, {"source_code": "import Data.Sequence as S\nimport Data.Foldable as F\nmain = getLine >>= print . fst . F.foldl f (0, 1) . \n S.tails . S.fromList\ng :: Seq Char -> Int -> Seq Char -> Bool\ng c n d\n | n >= 4 = True\n | n >= S.length c = False\n | otherwise = index c n == index d n && g c (n + 1) d\nf :: (Int, Int) -> Seq Char -> (Int, Int)\nf (a, b) c\n | g c 0 (fromList \"bear\") = (a + b * (S.length c - 3), 1)\n | otherwise = (a, b + 1)"}, {"source_code": "main = getLine >>= print . (\\x -> f 1 (length x) x)\nf _ l _ | l < 4 = 0\nf n l (a:b:c:d:s)\n | [a,b,c,d] == \"bear\" = n * (l - 3) + f 1 (l - 1) (b:c:d:s)\n | otherwise = f (n + 1) (l - 1) (b:c:d:s)"}, {"source_code": "main = do\n str <- getLine\n let l = length str\n let n = countBear str\n print $ res n l\n\n where\n countBear s = countBear' s 1\n countBear' p@(_:xs) acc = if isBear p then acc:(countBear' xs $ acc + 1) else countBear' xs $ acc + 1\n countBear' _ _ = []\n isBear (x1:x2:x3:x4:_) = x1 == 'b' && x2 == 'e' && x3 == 'a' && x4 == 'r'\n isBear _ = False\n res (x:xs@(y:_)) ls = (res xs ls) + (x * (y - x))\n res (x:[]) ls = x * (ls - x - 2)\n res _ _ = 0\n"}, {"source_code": "import Data.Functor ((<$>))\nimport Data.List (tails)\nimport Data.Maybe (fromMaybe, listToMaybe)\n\nmain :: IO ()\nmain = print =<< solve <$> getLine\n\nsolve :: String -> Int\nsolve xs = sum [ fromMaybe 0 $ ((length xs - 3)-) <$> listToMaybe (filter (>=i) bearIndices) | (i, _) <- zip [0..] xs ]\n where bearIndices = [ i | (i, ys) <- zip [0..] (tails xs), take 4 ys == \"bear\" ]\n"}], "negative_code": [{"source_code": "import Data.Functor ((<$>))\nimport Data.List (inits, tails)\n\nmain :: IO ()\nmain = print =<< solve <$> getLine\n\nsolve :: String -> Int\nsolve xs = length [ ys | ys <- concatMap inits $ tails xs, ys `contains` \"bear\" ]\n\ncontains :: Eq a => [a] -> [a] -> Bool\ncontains (x:xs) yys@(y:ys) = x == y && xs `contains` ys || xs `contains` yys\ncontains [] (_:_) = False\ncontains _ [] = True\n"}], "src_uid": "240a2b88ded6016d0fd7157d0ee2beea"} {"source_code": "import Data.Char\nimport System.IO\nimport Data.List\nimport Data.Maybe\n\n-- reading functions\n\nstrToIntList :: String -> [Int]\nstrToIntList xs = map toInt (split xs ' ')\n\ntoInt :: String -> Int\ntoInt [] = 0\ntoInt (x:xs) = (digitToInt x) * 10^(length xs) + toInt xs\n\n-- first :: String -> Char -> String\n\n\nsplit :: String -> Char -> [String]\nsplit [] _ = []\nsplit xs c = (first xs c) : split (rest xs c) c where\n first [] c = []\n first (x:xs) c| x==c = []\n | otherwise = x : first xs c\n rest [] c = []\n rest (x:xs) c| x==c = xs\n | otherwise = rest xs c\n\n-- solving functions\n\nsubtract_list :: Num a => [a] -> [a] -> [a]\nsubtract_list xs [] = xs\nsubtract_list [] (y:ys) = -y: subtract_list [] ys\nsubtract_list (x:xs) (y:ys) = (x-y): subtract_list xs ys\n\ndiffs :: Num a=> [a] -> [a]\ndiffs xs = init (subtract_list (tail xs) xs)\n\n-- todo for each problem\nsolve :: Int -> [Int] -> Int\nsolve 1 xs = last xs - head xs\nsolve n xs = solve 1 xs - (sum . (take (n-1)) . reverse . sort . diffs) xs \n\n\n-- reads a 2 lines: 1st: n, 2nd: list of Ints\n-- applies solve on the list and outputs the result\nsolveNf :: Int -> Handle -> IO ()\nsolveNf 0 h = return ()\nsolveNf n h = do\n nk <- hGetLine h\n t <- hGetLine h\n (putStrLn . show) (solve ((strToIntList nk)!!1) (strToIntList t))\n solveNf (n-1) h\n\nmain :: IO ()\nmain = do\n -- h <- openFile \"C.in\" ReadMode\n solveNf 1 stdin\n -- hClose h\n return ()", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.Char (ord)\nimport Data.List (sortOn)\nimport Data.Ord (Down (Down))\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\nparseInts = fmap parseInt . words\n\nmain = do\n [n, k] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let b = sortOn Down (zipWith (-) (tail a) a)\n m = last a - head a\n print (m - sum (take (k - 1) b))\n"}, {"source_code": "import Data.List\n\njumpListOf :: [Int] -> [Int]\njumpListOf xs = zipWith (-) (tail xs) xs\n\nsolve :: [Int] -> Int -> Int\nsolve xs k = (sum . drop (k-1) . reverse . sort . jumpListOf) xs\n\nmain = do\n n_k <- map (read :: String -> Int) . words <$> getLine\n array_values <- map (read :: String -> Int) . words <$> getLine \n print $ solve array_values (n_k !! 1)"}], "negative_code": [], "src_uid": "2895624e708159bc2a6f3e91140a6c45"} {"source_code": "import qualified Data.List as List\nimport qualified Data.Map as Map\n\nreadInt x = read x :: Int\nreadInteger x = read x :: Integer\nreadDouble x = read x :: Double\n\nlightRooms n = [ if x == 1 || x == n then 1 else 0 | x <- [1..n] ]\nmakeRooms lvl = [ lightRooms x | x <- [1..lvl] ]\n\nshowRooms (x:xlst) = show x ++ \" \" ++ showRooms xlst\nshowRooms [] = \"\"\n\nshowLevels (x:xlst) = showRooms x ++ \"\\n\" ++ showLevels xlst\nshowLevels [] = \"\"\n\nsolve 0 = return ()\nsolve tc = do\n solve (tc-1)\n in1 <- getLine\n let n = readInt in1\n putStr (showLevels $ makeRooms n)\n\nmain = do\n in1 <- getLine\n let tc = readInt in1\n solve tc", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr.showAns.solve) tcs\r\n\r\nshowAns = unlines . map (unwords . map show)\r\n\r\nsolve n = map genRow [1..n]\r\n\r\ngenRow 1 = [1::Int]\r\ngenRow i = 1 : replicate (i-2) 0 ++ [1]\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nbnb :: Int -> [[Int]]\r\nbnb 1 = [[1]]\r\nbnb level_num = (new_level :) $ bnb $ level_num - 1\r\n where\r\n new_level = 1 : replicate (level_num - 2) 0 ++ [1]\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n level_num <- readLn :: IO Int\r\n mapM_ (putStrLn . unwords . map show) $\r\n reverse $\r\n bnb level_num\r\n\r\nmain :: IO ()\r\nmain = do\r\n test_case_num <- readLn :: IO Int\r\n replicateM_ test_case_num solveCase"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>= printTorches\n\nprintTorches :: Int -> IO ()\nprintTorches 1 = print 1\nprintTorches 2 = printTorches 1 >> putStrLn \"1 1\"\nprintTorches n = printTorches (n-1) >>\n putStr \"1 \" >> replicateM_ (n-2) (putStr \"0 \") >> putStrLn \"1\"\n"}], "negative_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.Bits\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve n = map (splitFor n) finiteBS\r\n where\r\n bitSeq = map (toBin numBits) $ nums\r\n numBits = (1 + n) * n `div` 2\r\n finiteBS = head bitSeq : takeWhile (/= head bitSeq) (tail bitSeq)\r\n\r\nnums = [0..] :: [Integer]\r\n\r\ntoBin w x = map (b2c . testBit x) $ [w-1,w-2..0]\r\n\r\nb2c False = '0'\r\nb2c True = '1'\r\n\r\nsplitFor = f 1\r\n where\r\n f _ 0 [] = []\r\n f _ 0 bs = error $ \"Logic 1 splitFor : bs=\" ++ show bs\r\n f _ _ [] = error \"Logic 2 splitFor\"\r\n f w n bs = xs : f (w+1) (n-1) ys\r\n where\r\n (xs,ys) = splitAt w bs\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr.showAns.solve) tcs\r\n\r\nshowAns = unlines . map (unwords . map show)\r\n\r\nsolve n = map (genRow n) [1..n]\r\n\r\ngenRow n i | (i == 1 || i == n-1) = fillWith 1\r\n | (i > 2 && i == n ) = mixed\r\n | ( i == n ) = fillWith 1\r\n | otherwise = fillWith 0\r\n where\r\n fillWith x = replicate i (x::Int)\r\n mixed = 1 : replicate (i-2) 0 ++ [1]\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStr.showAns.solve) tcs\r\n\r\nshowAns = unlines . map (unwords . map show)\r\n\r\nsolve n = map (genRow n) [1..n]\r\n\r\ngenRow n i | (i == 1 || i == n-1) = fillWith 1\r\n | (i > 2 && i == n ) = mixed\r\n | ( i == n ) = fillWith 1\r\n | otherwise = fillWith 0\r\n where\r\n fillWith x = replicate i (x::Int)\r\n mixed = take i . cycle $ [1,0]\r\n"}], "src_uid": "4a473e34f2be18a19c306d80d4693199"} {"source_code": "doit :: [Integer] -> Maybe [[Integer]]\ndoit [n, m, k]\n | (2*n*m) `mod` k /= 0 = Nothing\n | otherwise = let g = gcd n k\n a = n `div` g\n b = (2*g*m) `div` k\n in if b <= m then Just [[0, 0], [a, 0], [0, b]]\n else Just [[0, 0], [2*a, 0], [0, b `div` 2]]\n\ndoit' :: [Integer] -> String\ndoit' x = case doit x of\n Nothing -> \"NO\\n\"\n Just s -> unlines $ \"YES\" : map (unwords . map show) s\n\nmain :: IO ()\nmain = fmap (map read . words) getLine >>= putStr . doit'\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Applicative\nimport Data.Ratio\nimport Text.Printf\n\nmain = do\n [n,m,k] <- map read . words <$> getLine :: IO [Integer]\n\n let\n area = (n*m) % k\n d = denominator area\n \n if\n | d<=2 -> do\n let\n m' = m `div` (gcd m k)\n k' = k `div` (gcd m k)\n n' = n `div` (gcd n k')\n printf \"YES\\n\"\n mapM_ (\\(x,y) -> printf \"%d %d\\n\" x y) $\n case d of\n 1 -> if m' < m then [(0,0),(n',0),(0,2*m')] else [(0,0),(2*n',0),(0,m')]\n 2 -> if m' < m then [(0,0),(n',0),(0,m')] else [(0,0),(n',0),(0,m')]\n | otherwise -> printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "5c026adda2ae3d7b707d5054bd84db3f"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ncheck :: String -> Maybe Int\ncheck [] = Just 0\ncheck ('\\r' : _) = Just 0\ncheck (c : cs) = do\n rest <- check cs\n guard $ c == ')' || rest > 0\n return $ if c == ')' then rest + 1 else rest - 1\n\nreplace :: String -> (Char, Char, Char) -> String\nreplace [] _ = []\nreplace (c : cs) t@(x1, x2, x3)\n | c == 'A' = x1 : replace cs t\n | c == 'B' = x2 : replace cs t\n | c == 'C' = x3 : replace cs t\n | otherwise = \"\"\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n s <- C.unpack <$> C.getLine\n let bs = \"()\"\n results = filter (==0) . map fromJust . filter isJust . map (check . replace s) $ [(x1, x2, x3) | x1 <- bs, x2 <- bs, x3 <- bs]\n C.putStrLn $ C.pack $ if null results then \"NO\" else \"YES\"\n", "positive_code": [{"source_code": "-- import Debug.Trace\r\nimport Data.List (permutations)\r\n\r\ntype InType = String\r\ntype OutType = Bool\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\nperms :: [String]\r\nperms = permutations \"(()\" ++ permutations \"))(\"\r\n\r\ncheckPars :: String -> Bool\r\ncheckPars = go 0\r\n where go c [] = c == 0\r\n go c (x : xs) = c >= 0 && go (f x + c) xs\r\n f '(' = 1\r\n f ')' = -1\r\n\r\nsolve :: InType -> OutType\r\nsolve s = or [ go p | p <- perms ]\r\n where go [a, b, c] = checkPars $ map (make a b c) s\r\n make a b c 'A' = a\r\n make a b c 'B' = b\r\n make a b c 'C' = c\r\n\r\nreceive :: [String] -> InType\r\nreceive = head\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showb . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showb True = \"YES\"\r\n showb False = \"NO\"\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n s <- getLine\n putStrLn $ yesOrNo $ (head s /= last s) && f s\n\nreplace :: (Eq a) => a -> a -> [a] -> [a]\nreplace x y = map (\\z -> if z == x then y else z)\n\nf :: String -> Bool\nf s = or [check 0 $ replace k '(' p, check 0 $ replace k ')' p]\n where p = replace (last s) ')' . replace (head s) '(' $ s\n k = last . ('-':) . filter (\\c -> c /= '(' && c /= ')') $ p\n\ncheck :: Int -> String -> Bool\ncheck c [] = c == 0\ncheck 0 (')':xs) = False\ncheck c (')':xs) = check (c - 1) xs\ncheck c ('(':xs) = check (c + 1) xs\n"}, {"source_code": "\r\nisValid :: String -> Int -> Bool \r\nisValid [] x = x == 0\r\nisValid (s:ss) x | x < 0 = False\r\n | s == '(' = isValid ss (x + 1) \r\n | otherwise = isValid ss (x - 1)\r\n\r\nreplace :: String -> Char -> Char -> String \r\nreplace inp old new = map (\\c -> if c == old then new else c) inp\r\n\r\n\r\nloopHelper :: Int -> IO ()\r\nloopHelper t | t == 0 = return ()\r\n | otherwise = do \r\n inp <- getLine\r\n let f = head inp \r\n l = last inp \r\n inp2 = replace (replace inp f '(') l ')'\r\n r = head (filter (\\c -> c /= f && c /= l) ['A', 'B', 'C'])\r\n\r\n if (isValid (replace inp2 r '(') 0 || isValid (replace inp2 r ')') 0 ) then \r\n putStrLn \"YES\"\r\n else \r\n putStrLn \"NO\"\r\n loopHelper (t-1)\r\n return ()\r\n\r\nmain :: IO ()\r\nmain = do \r\n t <- getLine\r\n loopHelper (read t :: Int)\r\n return ()\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n FlexibleInstances, ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad hiding (mapM, mapM_, forM, forM_)\nimport Control.Monad.State hiding (mapM, mapM_, forM, forM_)\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Foldable\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.Ix\nimport Data.List hiding (and, or, any, all, foldr, foldl')\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.STRef\nimport Data.Traversable\nimport Prelude hiding (and, or, any, all, mapM, mapM_)\nimport System.IO\n\n------\n\ndata P a b = P !a !b\n deriving (Show, Eq, Ord)\n\ndata T a b c = T !a !b !c\n deriving (Show, Eq, Ord)\n\ndata Q a b c d = Q !a !b !c !d\n deriving (Show, Eq, Ord)\n\nclass HasFirst a t | t -> a where\n first :: t -> a\n\ninstance HasFirst a (P a b) where\n first (P x _) = x\n\ninstance HasFirst a (T a b c) where\n first (T x _ _) = x\n\ninstance HasFirst a (Q a b c d) where\n first (Q x _ _ _) = x\n\ninstance HasFirst a (a, b) where\n first (x, _) = x\n\ninstance HasFirst a (a, b, c) where\n first (x, _, _) = x\n\ninstance HasFirst a (a, b, c, d) where\n first (x, _, _, _) = x\n\nclass HasSecond b t | t -> b where\n second :: t -> b\n\ninstance HasSecond b (P a b) where\n second (P _ x) = x\n\ninstance HasSecond b (T a b c) where\n second (T _ x _) = x\n\ninstance HasSecond b (Q a b c d) where\n second (Q _ x _ _) = x\n\ninstance HasSecond b (a, b) where\n second (_, x) = x\n\ninstance HasSecond b (a, b, c) where\n second (_, x, _) = x\n\ninstance HasSecond b (a, b, c, d) where\n second (_, x, _, _) = x\n\nclass HasThird c t | t -> c where\n third :: t -> c\n\ninstance HasThird c (T a b c) where\n third (T _ _ x) = x\n\ninstance HasThird c (Q a b c d) where\n third (Q _ _ x _) = x\n\ninstance HasThird c (a, b, c) where\n third (_, _, x) = x\n\ninstance HasThird c (a, b, c, d) where\n third (_, _, x, _) = x\n\nclass HasFourth d t | t -> d where\n fourth :: t -> d\n\ninstance HasFourth d (Q a b c d) where\n fourth (Q _ _ _ x) = x\n\ninstance HasFourth d (a, b, c, d) where\n fourth (_, _, _, x) = x\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: (Functor m, MonadHopper r m) => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: (Functor m, MonadHopper B.ByteString m) => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: (Functor m, MonadHopper B.ByteString m) => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: (Functor m, MonadHopper B.ByteString m) => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: (Functor m, MonadHopper B.ByteString m) => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = bool \"NO\" \"YES\" . solve . B.unpack <$> popJust\n\n\nsolve s = or $ map test [T a b c | a <- [1, -1], b <- [1, -1], c <- [1, -1]]\n where\n test repl = (\\l -> all (>= 0) l && last l == 0) $\n second $\n mapAccumL (\\x y -> (x + y, x + y)) 0 $ map (replace repl) s\n\n replace (T a b c) ch = case ch of\n 'A' -> a\n 'B' -> b\n 'C' -> c\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Bits\n\ncount :: Char -> P.ByteString -> Int\ncount c = P.foldl' (\\x y -> x + if y == c then 1 else 0) 0\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n s <- readLine\n let\n n = fromIntegral $ P.length s\n letters = \"ABC\"\n cts = map (`count` s) letters\n half = filter (\\x -> 2 * fst x == n) $ zip cts letters\n lift $ P.putStrLn $ P.pack $ case half of\n [] -> \"NO\"\n (_, tarc) : _ -> let\n startWithTar = P.head s == tarc\n fun c = if xor startWithTar (c == tarc)\n then ')'\n else '('\n newS = map fun $ P.unpack s\n prefTots :: [Int]\n prefTots = scanl (\\x y -> x + if y == '(' then 1 else -1) 0 newS\n in if all (>= 0) prefTots && last prefTots == 0\n then \"YES\"\n else \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n s <- getLine\n putStrLn $ yesOrNo $ and [f s, head s /= last s]\n\n\nf :: String -> Bool\nf = check . sort . map length . group . sort\n\ncheck :: [Int] -> Bool\ncheck [a] = False\ncheck [a, b] = a == b\ncheck [a, b, c] = a + b == c"}], "src_uid": "4d24aaf5ebf70265b027a6af86e09250"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do\n n <- readInt\n replicateM n $ do\n name <- readString\n score <- readInt\n return (name, score)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve records = BS.unlines $\n (BS.pack $ show n) : map (\\(name, s) ->\n name `BS.append` \" \" `BS.append` solvePlayer s) highScores\n where\n highScores = Map.toList $ Map.fromListWith max records\n n = length highScores\n\n solvePlayer score\n | r < 50 % 100 = \"noob\"\n | r < 80 % 100 = \"random\"\n | r < 90 % 100 = \"average\"\n | r < 99 % 100 = \"hardcore\"\n | otherwise = \"pro\"\n where\n r = cnt % n\n cnt = length [ undefined\n | (_, score') <- highScores\n , score' <= score\n ]\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\n-- Pure Code\n\nsolve :: Int -> [(String, Int)] -> [(String, String)]\nsolve n records = map (categorize n records) records\n\ngetCategory :: Int -> String\ngetCategory p\n | p < 50 = \"noob\"\n | p < 80 = \"random\"\n | p < 90 = \"average\"\n | p < 99 = \"hardcore\"\n | otherwise = \"pro\"\n\ncategorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)\ncategorize n records (name, score) = \n let m = length $ filter (\\(_, score1) -> score1 <= score) records\n p = 100 * m `div` n\n in (name, getCategory p)\n\n-- Dirty Code\n\nmain = do n <- fmap read getLine\n records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord\n let m = length records\n putStrLn $ show m\n sequence_ $ map printCategory $ solve m records\n\ngetRecord :: IO (String, Int)\ngetRecord = do [name, score] <- fmap words getLine\n return (name, read score)\n\nprintCategory (name, category) =\n putStrLn (name ++ \" \" ++ category)\n"}, {"source_code": "import Data.List (nub)\n\nmain = do\n n <- fmap read getLine\n a <- fmap (map (\\[name, score] -> (name, read score :: Double)) . map words . take n . lines) getContents\n let gamers = nub $ map (\\(name, _) -> (name, maximum $ map snd $ filter ((== name) . fst) a)) a\n print $ length gamers\n mapM_ (\\(name, rank) -> putStrLn $ name ++ \" \" ++ rank) $ map (\\(name, score) -> (name, calcRank (fromIntegral $ length gamers) $ fromIntegral $ length $ filter ((<= score) . snd) gamers)) gamers\n where\n calcRank :: Double -> Double -> String\n calcRank n k | k >= 0.99 * n = \"pro\"\n | k >= 0.9 * n = \"hardcore\"\n | k >= 0.8 * n = \"average\"\n | k >= 0.5 * n = \"random\"\n | otherwise = \"noob\"\n"}, {"source_code": "\nimport Control.Monad (replicateM)\nimport Data.Map (Map, assocs, filter, fromListWith, map, size)\nimport Prelude hiding (filter, map)\n\nreadResult :: IO (String, Int)\nreadResult = do\n [s1, s2] <- getLine >>= return . words\n return (s1, read s2)\n\ngetNoob :: Map String Int -> Int -> String\ngetNoob results source\n | k < 50 = \"noob\"\n | k < 80 = \"random\"\n | k < 90 = \"average\"\n | k < 99 = \"hardcore\"\n | otherwise = \"pro\"\n where\n n = size results\n m = size $ filter (<= source) results\n k = div (100 * m) n\n\nprintAns :: Map String String -> IO ()\nprintAns results = print (size results) >> mapM_ printAns' (assocs results)\n where\n printAns' (name, result) = putStrLn $ concat [name, \" \", result]\n\nmain :: IO ()\nmain = do\n n <- readLn\n allResults <- replicateM n readResult\n let results = fromListWith max allResults\n printAns $ map (getNoob results) results\n"}], "negative_code": [{"source_code": "import Data.List (nub)\n\nmain = do\n n <- fmap read getLine\n a <- fmap (map (\\[name, score] -> (name, read score :: Double)) . map words . take n . lines) getContents\n let gamers = nub $ map (\\(name, _) -> (name, maximum $ map snd $ filter ((== name) . fst) a)) a\n mapM_ (\\(name, rank) -> putStrLn $ name ++ \" \" ++ rank) $ map (\\(name, score) -> (name, calcRank (fromIntegral $ length gamers) $ fromIntegral $ length $ filter ((<= score) . snd) gamers)) gamers\n where\n calcRank :: Double -> Double -> String\n calcRank n k | k >= 0.99 * n = \"pro\"\n | k >= 0.9 * n = \"hardcore\"\n | k >= 0.8 * n = \"average\"\n | k >= 0.5 * n = \"random\"\n | otherwise = \"noob\"\n"}, {"source_code": "\nimport Control.Monad (replicateM)\nimport Data.Map (Map, assocs, filter, fromListWith, map, size)\nimport Prelude hiding (filter, map)\n\nreadResult :: IO (String, Int)\nreadResult = do\n [s1, s2] <- getLine >>= return . words\n return (s1, read s2)\n\ngetCool :: Map String Int -> Int -> Double\ngetCool results source = fromIntegral m / fromIntegral n\n where\n n = size results\n m = size $ filter (<= source) results\n\ngetNoob :: Double -> String\ngetNoob a\n | a < 0.50 = \"noob\"\n | a < 0.80 = \"random\"\n | a < 0.90 = \"average\"\n | a < 0.99 = \"hardcore\"\n | otherwise = \"pro\"\n\nprintAns :: Map String String -> IO ()\nprintAns results = print (size results) >> mapM_ printAns' (assocs results)\n where\n printAns' (name, result) = putStrLn $ concat [name, \" \", result]\n\nmain :: IO ()\nmain = do\n n <- readLn\n allResults <- replicateM n readResult\n let results = fromListWith max allResults\n printAns $ map (getNoob . getCool results) results\n"}, {"source_code": "import Control.Monad\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\n-- Pure Code\n\nsolve :: Int -> [(String, Int)] -> [(String, String)]\nsolve n records = map (categorize n records) records\n\ngetCategory :: Double -> String\ngetCategory p\n | p < 50.0 = \"noob\"\n | p < 80.0 = \"random\"\n | p < 90.0 = \"average\"\n | p < 99.0 = \"hardcore\"\n | otherwise = \"pro\"\n\ncategorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)\ncategorize n records (name, score) = \n let m = length $ filter (\\(_, score1) -> score1 <= score) records\n p = 100.0 / fromIntegral n * fromIntegral m\n in (name, getCategory p)\n\n-- Dirty Code\n\nmain = do n <- fmap read getLine\n records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord\n let m = length records\n putStrLn $ show m\n sequence_ $ map printCategory $ solve m records\n\ngetRecord :: IO (String, Int)\ngetRecord = do [name, score] <- fmap words getLine\n return (name, read score)\n\nprintCategory (name, category) =\n putStrLn (name ++ \" \" ++ category)\n"}, {"source_code": "import Control.Monad\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\n-- Pure Code\n\nsolve :: Int -> [(String, Int)] -> [(String, String)]\nsolve n records = map (categorize n records) records\n\ngetCategory :: Double -> String\ngetCategory p\n | 100.0 - p > 50.0 = \"noob\"\n | 50.0 <= p && 100.0 - p > 20.0 = \"random\"\n | 80.0 <= p && 100.0 - p > 10.0 = \"average\"\n | 90.0 <= p && 100.0 - p > 1.0 = \"hardcore\"\n | 99.0 <= p = \"pro\"\n | otherwise = undefined\n\ncategorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)\ncategorize n records (name, score) = \n let m = length $ filter (\\(_, score1) -> score1 <= score) records\n p = 100.0 / fromIntegral n * fromIntegral m\n in (name, getCategory p)\n\n-- Dirty Code\n\nmain = do n <- fmap read getLine\n records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord\n let m = length records\n putStrLn $ show m\n sequence_ $ map printCategory $ solve m records\n\ngetRecord :: IO (String, Int)\ngetRecord = do [name, score] <- fmap words getLine\n return (name, read score)\n\nprintCategory (name, category) =\n putStrLn (name ++ \" \" ++ category)\n"}, {"source_code": "import Control.Monad\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\n-- Pure Code\n\nsolve :: Int -> [(String, Int)] -> [(String, String)]\nsolve n records = map (categorize n records) records\n\ngetCategory :: Double -> String\ngetCategory p\n | 100.0 - p > 50.0 = \"noob\"\n | 50.0 <= p && 100.0 - p > 20.0 = \"random\"\n | 80.0 <= p && 100.0 - p > 10.0 = \"average\"\n | 90.0 <= p && 100.0 - p > 1.0 = \"hardcore\"\n | 99.0 <= p = \"pro\"\n | otherwise = undefined\n\ncategorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)\ncategorize n records (name, score) = \n let m = length $ filter (\\(_, score1) -> score1 <= score) records\n p = 100.0 / fromIntegral n * fromIntegral m\n in (name, getCategory p)\n\n-- Dirty Code\n\nmain = do n <- fmap read getLine\n records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord\n sequence_ $ map printCategory $ solve (length records) records\n\ngetRecord :: IO (String, Int)\ngetRecord = do [name, score] <- fmap words getLine\n return (name, read score)\n\nprintCategory (name, category) =\n putStrLn (name ++ \" \" ++ category)\n"}], "src_uid": "0430fa56ec7f97efaf9d37096f72bcf8"} {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.Map as M\nimport Data.Char\n\nmain = print . solve . words =<< getContents\n\nsolve [ks, ns] = ans where\n k = read ks :: Int\n (cn, mp) = foldl f (0, M.empty) $ map digitToInt ns\n f (c, m) d = (c + d, M.insertWith (+) d 1 m)\n ans = if cn >= k then 0\n else snd $ foldl g (cn, 0) [0..8]\n g t@(c, x) i | c >= k = t\n | otherwise = \n case M.lookup i mp of\n Nothing -> t\n Just p ->\n let j = 9 - i\n w = k - c\n e = max 1 $ div (w + j - 1) j\n v = min e p\n in (c + v * j, x + v)\n ", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\n\nmain = do\n k <- fmap readInt B.getLine\n n <- getLine\n print $ solve k n\n\nsolve k n \n | s >= k = 0\n | otherwise = (1+) $ length $ takeWhile (< k) $ tail $ scanl (\\s d -> s - d + 9) s xs\n where\n xs = sort $ map digitToInt n\n s = sum xs\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.Int\nimport Data.List\n\nrun :: Int32 -> [Int] -> Int\nrun _ [] = 0\nrun sum (c:cs) | sum <= 0 = 0\n | otherwise = 1 + (run (sum-m) cs)\n where m = 9 - (fromIntegral c)\n\nsolve :: Int32 -> [Int] -> Int\nsolve k s = run (k - (fromIntegral $ sum s)) s\n\nmain = do\n k <- read <$> getLine\n s <- sort . (map digitToInt) <$> getLine\n print $ solve k s\n"}, {"source_code": "import Data.List\nimport Data.Char\nmain =\n do\n sk <- getLine\n let k = read sk :: Int\n sn <- getLine\n let sv = (map digitToInt $ sort sn) :: [Int]\n allsum = sum sv\n\n if k <= allsum\n then print 0\n else\n print.snd $ foldl (\\(acc, acci) x -> if acc > 0\n then (acc - 9 + x, acci + 1)\n else (acc, acci)) (k - allsum, 0) sv\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n k <- readLn\n ns <- map digitToInt.B.unpack.B.filter(\\c->'0'<=c&&c<='9') <$> B.getLine\n print $ solve k ns\n\nsolve :: Int -> [Int] -> Int\nsolve k ns = go 0 (k - s) $ sort ns\n where\n !s = sum ns\n go !res !rest (x:xs)\n | rest <= 0 = res\n | otherwise = go (res + 1) (rest - (9 - x)) xs\n go res _ _ = res\n\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n k <- readLn\n ns <- map digitToInt.B.unpack.B.filter(\\c->'0'<=c&&c<='9') <$> B.getLine\n putStrLn . concatMap show $ solve k ns\n\nsolve :: Int -> [Int] -> [Int]\nsolve k ns = go [] (k - s) $ reverse ns ++ repeat 0\n where\n !s = sum ns\n go !res !rest (x:xs)\n | rest <= 0 = [0]\n | 9 - x >= rest = rest:res\n | otherwise = go ((9-x):res) (rest-(9-x)) xs\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\n\nmain = do\n k <- fmap readInt B.getLine\n n <- getLine\n print $ solve k n\n\nsolve k n \n | need <= 0 = 0\n | otherwise = ceiling $ (fromIntegral need + 1) / 9\n where\n xs = map digitToInt n\n need = k - sum xs \n\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.Map as M\nimport Data.Char\n\nmain = print . solve . words =<< getContents\n\nsolve [ks, ns] = ans where\n k = read ks :: Int\n (cn, mp) = foldl f (0, M.empty) $ map digitToInt ns\n f (c, m) d = (c + d, M.insertWith (+) d 1 m)\n ans = if cn >= k then 0\n else snd $ foldl g (cn, 0) [0..8]\n g t@(c, x) i | c >= k = t\n | otherwise = \n case M.lookup i mp of\n Nothing -> t\n Just p ->\n let j = 9 - i\n w = k - c\n e = max 1 $ div w j\n v = min e p\n in (c + v * j, x + v)\n \n "}, {"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.Map as M\nimport Data.Char\n\nmain = print . solve . words =<< getContents\n\nsolve [ks, ns] = ans where\n k = read ks :: Int\n (cn, mp) = foldl f (0, M.empty) $ map digitToInt ns\n f (c, m) d = (c + d, M.insertWith (+) d 1 m)\n ans = if cn >= k then 0\n else snd $ foldl g (cn, 0) [0..8]\n g t@(c, x) i | c >= k = t\n | otherwise = \n case M.lookup i mp of\n Nothing -> t\n Just p ->\n let j = 9 - i\n w = k - c\n e = max 1 $ quot w j\n v = min e p\n in (c + v * j, x + v)\n "}], "src_uid": "d7e6e5042b8860bb2470d5a493b0adf6"} {"source_code": "import List\nimport Char\n\nsolve :: String -> String -> String\nsolve _ [] = \"YES\"\nsolve [] _ = \"NO\"\nsolve (x:xs) (y:ys)\n | x == y = solve xs ys\n | x < y = solve xs (y:ys)\n | x > y = \"NO\"\n \nmain = do\n s1 <- getLine\n s2 <- getLine\n putStrLn $ solve (sort $ filter isAlpha s1) (sort $ filter isAlpha s2)", "positive_code": [{"source_code": "import Data.List ((\\\\))\n\nmain = do\n\ta <- getLine\n\tb <- getLine\n\tputStrLn $ if filter (/= ' ') b \\\\ a == [] then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\nimport Control.Monad\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nreadall = State (,\"\")\n\nrunRead x s = fst $ runState x s\n\n\nmain = reader >>= writer . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\t(s1:s2:_)<-liftM lines readall\n\tlet count c s = length . filter (==c) $ s\n\tlet chars = ['a'..'z'] ++ ['A'..'Z']\t\n\treturn (if and [count c s1 >= count c s2 | c<-chars] then \"YES\" else \"NO\")\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\ncount s = \\x -> (C.length . C.filter ((==) x)) s\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [s1,s2] = take 2 $ input\n\tlet ans = length $ filter (==False) $ [ count s1 c >= count s2 c | c <- ['a'..'z'] ++ ['A'..'Z'] ]\n\tputStrLn (if ans == 0 then \"YES\" else \"NO\")\n"}, {"source_code": "import Data.List\nf xs = [x | x <- xs, x/=' ']\nsolve s s2 | null s2 = \"YES\"| null s = \"NO\" | head s2 `elem` s = solve x z | otherwise = \"NO\"\n where\n x = delete y s\n y = head s2\n z = tail s2\nmain = do\n s <- fmap f getLine\n s2 <- fmap f getLine\n putStrLn $ solve s s2\n"}, {"source_code": "main = do l1 <- getLine\n l2 <- getLine\n if solve l1 l2 then putStrLn \"YES\" else putStrLn \"NO\"\n\nsolve :: String -> String -> Bool\nsolve _ [] = True\nsolve [] _ = False\nsolve cs1 (c2:cs2) = if c2 == ' ' \n then solve cs1 cs2 \n else case (find \"\" cs1 c2) of\n Just cs -> solve cs cs2\n Nothing -> False\n where \n nl = length cs1\n find :: String -> String -> Char -> Maybe String\n find _ [] c = Nothing\n find cs (c':cs') c = if c == c'\n then Just (cs ++ cs')\n else find (c':cs) cs' c\n\n"}, {"source_code": "\nimport Data.List\n\nmain = do\n t <- getLine\n h <- getLine\n\n putStrLn $ m (f t) (f h)\n\nm _ [] = \"YES\"\nm [] _ = \"NO\"\nm (a:as) (b:bs)\n | a == b = m as bs\n | otherwise = m as (b:bs)\n\nf = sort . filter (/=' ')\n"}, {"source_code": "import List\nmain=interact(s.lines)\ns [p,f] = if null(c f\\\\c p)then\"YES\"else\"NO\"where c=filter(>' ')\n"}, {"source_code": "import Data.List ((\\\\))\n\nmain = do\n xs <- getLine\n ys <- getLine\n putStrLn $ if null $ filter (/= ' ') ys \\\\ xs then \"YES\" else \"NO\"\n"}, {"source_code": "import List\nmain = interact solve\nsolve input = output where\n [s1,s2] = lines input\n output = answer s1 s2\nanswer _ [] = \"YES\"\nanswer xs (y:ys)\n | elem y xs = answer (delete y xs) ys\n | y == ' ' = answer xs ys\n | otherwise = \"NO\""}], "negative_code": [{"source_code": "\nimport Data.List\n\nmain = do\n text <- getLine\n heading <- getLine\n\n let fh = f heading\n let tmp = f text `intersect` fh\n print $ if sort tmp == sort fh\n then \"YES\"\n else \"NO\"\n\n\nf = filter (/=' ')\n"}, {"source_code": "\nimport Data.List\n\nmain = do\n text <- getLine\n heading <- getLine\n\n let fh = f heading\n let tmp = f text `intersect` fh\n-- print $ sort fh\n-- print $ sort tmp\n print $ m (sort tmp) (sort fh)\n\nm _ [] = \"YES\"\nm [] _ = \"NO\"\nm (a:as) (b:bs)\n | a == b = m as bs\n | otherwise = m as (b:bs)\n\nf = filter (/=' ')\n"}, {"source_code": "\nimport Data.List\n\nmain = do\n text <- getLine\n heading <- getLine\n\n let fh = f heading\n let tmp = f text `intersect` fh\n print $ m (sort tmp) (sort fh)\n\nm [] _ = \"NO\"\nm _ [] = \"YES\"\nm (a:as) (b:bs)\n | a == b = m as bs\n | otherwise = m as (b:bs)\n\nf = filter (/=' ')\n"}, {"source_code": "\nimport Data.List\n\nmain = do\n text <- getLine\n heading <- getLine\n\n let fh = f heading\n print $ sort fh\n print $ sort text\n print $ m (sort $ f text) (sort fh)\n\nm _ [] = \"YES\"\nm [] _ = \"NO\"\nm (a:as) (b:bs)\n | a == b = m as bs\n | otherwise = m as (b:bs)\n\nf = filter (/=' ')\n"}, {"source_code": "\nimport Data.List\n\nmain = do\n text <- getLine\n heading <- getLine\n\n let fh = f heading\n print $ m (sort $ f text) (sort fh)\n\nm _ [] = \"YES\"\nm [] _ = \"NO\"\nm (a:as) (b:bs)\n | a == b = m as bs\n | otherwise = m as (b:bs)\n\nf = filter (/=' ')\n"}], "src_uid": "b1ef19d7027dc82d76859d64a6f43439"} {"source_code": "--{-# LANGUAGE Safe #-} \r\n--{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport {-safe-} Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\nimport qualified Data.Array as A\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (take 2 rest) ++ tcio (drop 2 rest) \r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n\r\nsolve :: [[Int]] -> Integer\r\nsolve [ks,cs] = sum $ map toInteger $ zipWith min sks (cs ++ (repeat (10^9+1))) where\r\n sks = map (vcs A.!) $ sortOn negate ks\r\n vcs = A.listArray (1,length cs) (cs)\r\n \r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List (sort)\nimport Data.Map.Strict (fromList, (!))\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\nimport System.IO\nimport Text.Read\nimport Data.Maybe (fromJust)\n\ngetNums :: IO [Int]\ngetNums = do\n line <- B.getLine\n return $ map ((fst . fromJust) . B.readInt) . B.split ' ' $ line\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, m] <- fmap (map read . words) getLine :: IO [Int]\n k <- getNums :: IO [Int]\n c <- getNums :: IO [Int]\n print $ solve n m k c\n return ()\n\ntype State = (Int, Int)\n\ninf = 10^9 + 30 :: Int\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Integer\nsolve !n !m !k !c =\n let !sortedK = sort k\n !mapC = fromList $ zip [1 ..] c\n\n countExcess :: State -> Int -> State\n countExcess (idx, mx) i = (idx + 1, max mx (idx - i))\n\n (_, !mx) = foldl countExcess (1, 0) sortedK\n\n !costs = map (mapC !) sortedK\n !paddedC = if n <= m then take n c else c ++ replicate (n - m) inf\n\n !startCost = sum $ map toInteger $ take n paddedC :: Integer\n !tradeOffs = zip costs (reverse paddedC)\n\n !a = takeWhile (uncurry (<)) tradeOffs\n !a' = if length a < mx then take mx tradeOffs else a\n\n !result = startCost + sum (map (\\(a, b) -> toInteger a - toInteger b) a')\n\n in result\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-} -- hasker's code\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (guard, MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> [Int] -> Int -> [Int64] -> Int64\r\nsolve n ks m cs = solve' 1 ksSorted\r\n where\r\n ksSorted = reverse $ sort ks\r\n csArray = A.listArray (1, m) cs\r\n solve' _ [] = 0\r\n solve' currK ks@(k : restKs)\r\n | currK <= k = csArray A.! currK + solve' (currK + 1) restKs\r\n | otherwise = csArray A.! k + solve' currK restKs\r\n\r\n \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, m] <- B8.getLine <&> map readIntB8 . B8.words\r\n ks <- B8.getLine <&> map readIntB8 . B8.words \r\n cs <- B8.getLine <&> map (\\word -> (fromInteger $ readIntegerB8 word) :: Int64) . B8.words\r\n let answer = solve n ks m cs\r\n printf \"%lld\\n\" answer\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-} -- Hasker's code\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (guard, MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\nsolve :: Int -> [Int] -> Int -> [Int64] -> Int64\r\nsolve n ks m cs = sum $ map fromIntegral $ zipWith min sks (cs ++ (repeat (10^9+1))) where\r\n sks = map (vcs A.!) $ sortOn negate ks\r\n vcs = A.listArray (1,m) cs\r\n{-\r\nsolve :: Int -> [Int] -> Int -> [Int64] -> Int64\r\nsolve n ks m cs = solve' 1 ksSorted\r\n where\r\n ksSorted = reverse $ sort ks\r\n csArray = A.listArray (1, m) cs\r\n solve' _ [] = 0\r\n solve' currK ks@(k : restKs)\r\n | currK <= k = csArray A.! currK + solve' (currK + 1) restKs\r\n | otherwise = csArray A.! k + solve' currK restKs\r\n-}\r\n \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, m] <- B8.getLine <&> map readIntB8 . B8.words\r\n ks <- B8.getLine <&> map readIntB8 . B8.words \r\n cs <- B8.getLine <&> map (\\word -> (fromInteger $ readIntegerB8 word) :: Int64) . B8.words\r\n let answer = solve n ks m cs\r\n printf \"%lld\\n\" answer\r\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\nimport safe qualified Data.Array as A\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (nm:(take 2 rest)) ++ tcio (drop 2 rest) \r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n\r\nsolve :: [[Int]] -> Integer\r\nsolve [[n,m],ks,cs] = sum $ map toInteger $ zipWith min sks (cs ++ (repeat (10^9+1))) where\r\n sks = map (vcs A.!) $ sortOn negate ks\r\n vcs = A.listArray (1,m) cs\r\n \r\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\nimport qualified Data.Map as M\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (take 2 rest) ++ tcio (drop 2 rest) \r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n\r\nsolve :: [[Integer]] -> Integer\r\nsolve [ks,cs] = sum $ zipWith min sks (cs ++ (repeat (10^9+1))) where\r\n sks = reverse $ map (mic M.!) $ sort ks\r\n mic = M.fromList (zip [1..] cs)\r\n \r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (guard, MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> [Int] -> Int -> [Int64] -> Int64\r\nsolve n ks m cs = solve' 1 ksSorted\r\n where\r\n ksSorted = reverse $ sort ks\r\n csArray = A.listArray (1, m) cs\r\n solve' _ [] = 0\r\n solve' currK ks@(k : restKs)\r\n | currK <= k = csArray A.! currK + solve' (currK + 1) restKs\r\n | otherwise = csArray A.! k + solve' currK restKs\r\n\r\n \r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, m] <- B8.getLine <&> map readIntB8 . B8.words\r\n ks <- B8.getLine <&> map readIntB8 . B8.words \r\n cs <- B8.getLine <&> map (\\word -> (fromInteger $ readIntegerB8 word) :: Int64) . B8.words\r\n let answer = solve n ks m cs\r\n printf \"%lld\\n\" answer"}], "negative_code": [{"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List (sort)\nimport Data.Map (fromList, (!))\n-- import Debug.Trace\nimport System.IO\nimport Text.Read\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, m] <- fmap (map read . words) getLine :: IO [Int]\n k <- fmap (map read . words) getLine :: IO [Int]\n c <- fmap (map read . words) getLine :: IO [Int]\n print $ solve n m k c\n return ()\n\ntype State = (Int, Int)\n\ninf = 10^9 + 30 :: Int\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Integer\nsolve n m k c =\n let sortedK = sort k\n mapC = fromList $ zip [1 ..] c\n\n countExcess :: State -> Int -> State\n countExcess (idx, mx) i = (idx + 1, max mx (i - idx))\n\n (_, mx) = foldl countExcess (1, 0) sortedK\n\n costs = map (mapC !) sortedK\n paddedC = if n <= m then c else c ++ replicate (n - m) inf\n\n startCost = sum $ map toInteger $ take n paddedC\n tradeOffs = zip costs (reverse paddedC)\n\n a = takeWhile (uncurry (<)) $ tradeOffs\n a' = if length a < mx then take mx tradeOffs else a\n\n result = startCost + sum (map (\\(a, b) -> toInteger a - toInteger b) a')\n\n in result\n"}], "src_uid": "55962ef2cf88c87873b996dc54cc1bf1"} {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t getLine\n\n (putStr . unlines . map (show . solve)) tcs\n\nsolve s = cntOnes `div` 2 + (length s' - cntOnes)\n where\n s' = reverse . sort . map length . group . sort $ s\n cntOnes = length . filter (==1) $ s'\n", "positive_code": [{"source_code": "module Main where\nimport Data.List (group, sort)\nmain = interact solve\n\nsolve :: String -> String \nsolve inp = \n let\n t = read . head . lines $ inp :: Int \n arr = take t . tail . lines $ inp \n more x = (length . filter (\\y -> length y >= 2) . group . sort $ x) * 2 \n one x = (length . filter (\\y -> length y == 1) . group . sort $ x)\n logic x = if one x < more x then one x * 2 else more x * 2\n in\n unlines . map (show . (\\x -> (one x + more x) `div` 2)) $ arr\n\n\n"}, {"source_code": "import Data.List (intersperse, intercalate, sort, group)\n\nparseOut :: [Int] -> String\nparseOut = intercalate \"\\n\" . map show\n\nparseIn :: String -> [String]\nparseIn = tail . words\n\nsolve :: String -> Int\nsolve str = gtOne + div one 2 where\n frequencies = map length $ group $ sort str\n gtOne = length $ filter (>1) frequencies\n one = length $ filter (==1) frequencies\n\nmain :: IO ()\nmain = interact $ parseOut . map solve . parseIn\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Set (fromList, toList)\n\nunique :: Ord a => [a] -> [a]\nunique = toList . fromList\n\ncount :: Eq a => a -> [a] -> Int\ncount x = length . filter (==x)\n\nsolve :: String -> Int\nsolve s = (map ((`count` s) >>> min 2) >>> sum >>> (`div` 2)) $ unique s\n\nmain :: IO ()\nmain = interact $ lines >>> tail >>> map (solve >>> show) >>> unlines"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bifunctor (bimap)\r\nimport Data.List (group, groupBy, sort, sortBy)\r\nimport Data.Ord (comparing)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map (solve >>> count 1 >>> show)\r\n >>> unlines\r\n\r\ntype Col = (Int, Maybe Int)\r\n\r\nsolve :: [Char] -> [Int]\r\nsolve as =\r\n let k = 2\r\n in map (maybe 0 ((1 +) . (`mod` k)) . snd)\r\n . sortOn fst\r\n . uncurry (++)\r\n . bimap (`zip` (Just <$> [1 ..])) (`zip` repeat Nothing)\r\n . (\\(cs, ws) -> let (ws', cs') = splitAt (length cs `mod` k) cs in (cs', ws' ++ ws))\r\n . bimap' concat\r\n . unzip\r\n . map (splitAt k . map snd)\r\n . groupOn fst\r\n . sortOn fst\r\n $ as `zip` [0 ..]\r\n\r\n-- Template\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\ngroupOn :: (Eq b) => (a -> b) -> [a] -> [[a]]\r\ngroupOn p = groupBy (\\x y -> p x == p y)\r\n\r\nsortOn :: (Ord b) => (a -> b) -> [a] -> [a]\r\nsortOn = sortBy . comparing\r\n\r\nbimap' f = bimap f f\r\n\r\ncount :: (Eq a) => a -> [a] -> Int\r\ncount x = length . filter (== x)\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport qualified Data.Map as M\r\n\r\ncounts :: Ord k => [k] -> M.Map k Int\r\ncounts = foldr insrt M.empty where\r\n insrt k mp = M.insertWith (+) k 1 mp\r\n\r\nnumRed :: String -> Int \r\nnumRed s = evenCnt + oddCnt + oneCnt `div` 2\r\n where\r\n cnt = counts s\r\n evenCnt = M.size $ M.filter even cnt\r\n oddCnt = M.size $ M.filter (\\x -> odd x && x > 1) cnt\r\n oneCnt = M.size $ M.filter (==1) cnt\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n s <- getLine \r\n print $ numRed s"}, {"source_code": "import qualified Data.Map as M\nimport Data.Map (Map)\nimport Control.Monad\nimport Data.Functor ((<&>))\nimport Data.STRef\nimport Control.Monad.ST\n\n-- | Take a sequence of elements and convert into frequency mapping\ncollect :: Ord a => [a] -> Map a Int\ncollect = foldl ins_ M.empty\n where\n ins_ m n = M.alter (Just . maybe 1 (+1)) n m\n\n-- | calculate coloring\ncoloring :: Ord a => [a] -> Int\ncoloring xs = gt2 + lt2 `div` 2\n where\n m = collect xs\n gt2 = length $ filter (>= 2) $ M.elems m\n lt2 = length m - gt2\n\nmain :: IO ()\nmain = do\n testCases <- read <$> getLine\n forM_ [1..testCases] $ \\_ -> do\n test <- getLine\n print $ coloring test\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nsolve :: IO ()\nsolve = do\n a <- getLine\n let k = 2\n b = group $ sort a\n total = foldl (\\acc xs -> acc + min (length xs) k) 0 b\n in print $ div total 2\n\n \n \n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadrows 0 = return []\nreadrows n = do\n row <- readInts\n l <- readrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nprintResult = do\r\n s <- getLine\r\n let a = concatMap (take 2) (group $ sort s)\r\n print $ div (length a) 2\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "negative_code": [{"source_code": "module Main where\nimport Data.List (group)\nmain = interact solve\n\nsolve :: String -> String \nsolve inp = \n let\n t = read . head . lines $ inp :: Int \n arr = take t . tail . lines $ inp \n logic x = ((length . filter(\\y -> length y == 1) . group $ x) `div` 2) + (length . filter (\\y -> length y == 2) . group $ x) + (length . filter(\\y -> length y > 2) . group $ x)\n in\n unlines . map (show . logic) $ arr\n\n"}, {"source_code": "module Main where\nimport Data.List (group)\nmain = interact solve\n\nsolve :: String -> String \nsolve inp = \n let\n t = read . head . lines $ inp :: Int \n arr = take t . tail . lines $ inp \n logic x = (length . filter(\\y -> length y == 1) . group $ x) `div` 2 + (length . filter (\\y -> length y > 1) . group $ x) `div` 2 + (length . filter(\\y -> length y > 2) . group $ x)\n in\n unlines . map (show . logic) $ arr\n\n"}], "src_uid": "a6b760941ab8be2c32c6dc66c623ea0e"} {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n mapM_ putStr (map (\\x -> (show x ++ \" \")) (solve n (sort a)))\n \nsolve :: Int -> [Int] -> [Int] \nsolve n l =\n let (x,y) = splitAt (n `div` 2) l\n in merge x (reverse y)\n where merge [] b = b\n merge a [] = a\n merge (a:as) (b:bs) = a:b:merge as bs\n \n \n\n \n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = putStrLn . unwords . map show . solve . map read . words =<< getContents\n\nsolve :: [Int] -> [Int]\nsolve (n:a) = let b = sort a\n h = div (n + 1) 2\n (l, r) = splitAt h b\n in solve' l r\n where solve' :: [Int] -> [Int] -> [Int]\n solve' [] [] = []\n solve' l [] = l\n solve' (l:ls) (r:rs) = l : r : solve' ls rs\n"}, {"source_code": "import Data.List (sort)\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int]\n\n let\n rev (a:b:xs) = (b:a:rev xs)\n rev [a] = [a]\n rev [] = []\n\n putStrLn $ unwords $ map show $ rev $ reverse $ sort as\n"}, {"source_code": "import Data.List\nmain=interact$unwords.map show.f1.sort.map (read::String->Int).tail.words\nf1 []=[]\nf1 (a:b)=a:f2 b\nf2 []=[]\nf2 a=last a:f1 (init a)"}, {"source_code": "\nimport Data.List\n\nmain = interact $ unwords . map show . sol . map read . tail . words\n\nsol :: [Int] -> [Int]\nsol xs\n | odd $ length xs = weave (tail sxs) ++ [head sxs]\n | otherwise = weave sxs\n where\n sxs = sort xs\n weave xs = concat $ zipWith (\\a b -> [a, b]) l r\n where\n (l, r) = splitAt (length sxs `div` 2) $ sort xs\n\n\n\n\n"}], "negative_code": [], "src_uid": "2401d34db475853661d6e1e1cb5a8216"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = maximizeBy cmpFst\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\nmaximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,k] <- map readInt. B.words <$> B.getLine\n l <- map readInt . B.words <$> B.getLine\n let (a,b) = solve n k l\n putStrLn $ show a ++\" \"++show b\n\nsolve n k l = snd $ foldl1 g (reverse cs)\n where\n l' = map fromIntegral l\n costs = totalAbsurdity k l'\n as = zip costs [1..]\n bs = drop k $ scanr1 g as\n cs = zipWith (\\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs\n f (a,b) (c,d) = case compare a c of\n EQ -> compare d b\n a -> a\n g a b = case f a b of\n LT -> b\n GT -> a\n EQ -> a\n\n\ntotalAbsurdity :: Int -> [Int64] -> [Int64]\ntotalAbsurdity k l = go (sum $ take k l) l (drop k l)\n where go a h [] = [a]\n go a (h:hs) (t:ts) = \n let a' = a-h+t in \n a' `seq` a:go a' hs ts\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = maximizeBy cmpFst\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\nmaximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,k] <- map readInt. B.words <$> B.getLine\n l <- map readInt . B.words <$> B.getLine\n let (a,b) = solve n k l\n putStrLn $ show a ++\" \"++show b\n\nsolve n k l = snd $ foldl1 g (reverse cs)\n where\n l' = map toInteger l\n costs = totalAbsurdity k l'\n as = zip costs [1..]\n bs = drop k $ scanr1 g as\n cs = zipWith (\\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs\n f (a,b) (c,d) = case compare a c of\n EQ -> compare d b\n a -> a\n g a b = case f a b of\n LT -> b\n GT -> a\n EQ -> a\n\ntotalAbsurdity k l = go (sum $ take k l) l (drop k l)\n where go a h [] = [a]\n go a (h:hs) (t:ts) = \n let a' = a-h+t in \n a' `seq` a:go a' hs ts\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\nscanl' f q ls = q : case ls of\n [] -> []\n x:xs -> let q' = f q x in scanl' f q' xs\nscanl1' f (x:xs) = scanl f x xs\nscanl1' _ [] = []\n\nscanr' _ q [] = [q]\nscanr' f q (x:xs) = \n let qs@(q':_) = scanr f q xs in q' `seq` (f x q:qs)\n\nscanr1' _ [] = []\nscanr1' _ [x] = [x]\nscanr1' f (x:xs) = q `seq` (f x q : qs)\n where qs@(q:_) = scanr1 f xs\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = maximizeBy cmpFst\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\nmaximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,k] <- map readInt. B.words <$> B.getLine\n l <- map readInt . B.words <$> B.getLine\n let (a,b) = solve n k l\n putStrLn $ show a ++\" \"++show b\n\nsolve n k l = snd $ foldl1' g (reverse cs)\n where\n l' = map toInteger l\n costs = totalAbsurdity k l'\n as = zip costs [1..]\n bs = drop k $ scanr1 g as\n cs = zipWith (\\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs\n f (a,b) (c,d) = case compare a c of\n EQ -> compare d b\n a -> a\n g a b = case f a b of\n LT -> b\n GT -> a\n EQ -> a\n\n\ntotalAbsurdity k l = go (sum $ take k l) l (drop k l)\n where go a h [] = [a]\n go a (h:hs) (t:ts) = \n let a' = a-h+t in \n a' `seq` a:go a' hs ts\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = maximizeBy cmpFst\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\nmaximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,k] <- map readInt. B.words <$> B.getLine\n l <- map (fromIntegral.readInt) . B.words <$> B.getLine\n let (a,b) = solve n k l\n putStrLn $ show a ++\" \"++show b\n\nsolve n k l = snd $ foldl1 g cs\n where\n costs = totalAbsurdity k l\n as = zip costs [1..]\n bs = scanl1 g (reverse $ drop k as)\n cs = zipWith (\\(a,ai) (b,bi) -> (a+b,(ai,bi))) (drop k (reverse as)) bs\n f (a,b) (c,d) = case compare a c of\n EQ -> compare d b\n a -> a\n g a b = case f a b of\n LT -> b\n GT -> a\n EQ -> a\n\n\ntotalAbsurdity :: Int -> [Int64] -> [Int64]\ntotalAbsurdity k l = go (sum $ take k l) l (drop k l)\n where go a h [] = [a]\n go a (h:hs) (t:ts) = \n let a' = a-h+t in \n a' `seq` a:go a' hs ts\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = maximizeBy cmpFst\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\nmaximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,k] <- map readInt. B.words <$> B.getLine\n l <- map readInt . B.words <$> B.getLine\n let (a,b) = solve n k l\n putStrLn $ show a ++\" \"++show b\n\nsolve n k l = snd $ foldl1' g cs\n where\n l' = map toInteger l\n costs = totalAbsurdity k l'\n as = zip costs [1..]\n bs = drop k $ reverse $ scanl1 g $ reverse as\n cs = zipWith (\\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs\n f (a,b) (c,d) = case compare a c of\n EQ -> compare d b\n a -> a\n g a b = case f a b of\n LT -> b\n GT -> a\n EQ -> a\n\ntotalAbsurdity k l = go (sum (take k l)) l (drop k l) []\n where go a h [] acc = reverse (a:acc)\n go a (h:hs) (t:ts) acc = \n let acc' = a:acc \n a' = a-h+t\n in \n acc' `seq` a' `seq` go a' hs ts acc'\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map (fromIntegral.readInt).B.words <$> B.getLine\n putStr.unwords.map show $ solve n k xs\n\nsolve :: Int -> Int -> [Int64] -> [Int]\nsolve n k xs = snd.foldl1' max' $ zipWith (&) ls rs\n where\n xis = zip (sumK k xs) [1..]\n ls = take (n-2*k+1) xis\n rs = scanr1 max' $ drop k xis\n (x,i) & (y,j) = (x+y,[i,j])\n\nmax' :: (Ord a, Ord b) => (a,b) -> (a,b) -> (a,b)\nmax' xy@(x,_) zw@(z,_)\n | x == z = min xy zw\n | otherwise = max xy zw\n\nsumK :: Int -> [Int64] -> [Int64]\nsumK k xs = go (sum ys) ys [] zs\n where\n (ys,zs) = splitAt k xs\n go !acc _ _ [] = [acc]\n go !acc (f:fs) rs (x:xs) = acc : go (acc-f+x) fs (x:rs) xs\n go !acc [] rs xs = go acc (reverse rs) [] xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n\nreadInt64 :: BS.ByteString -> Int64\nreadInt64 = fromIntegral . readInt\n\nreadInt :: BS.ByteString -> Int\nreadInt bs = case BS.readInt bs of Just (x, _) -> x\n\nmaxElem :: [Int64] -> Int\nmaxElem arr = fromMaybe (-1) $ elemIndex (foldl1 max arr) arr\n\nsolve :: [Int64] -> Int -> (Int, Int)\nsolve arr k = \n\tlet pSum = scanl (+) 0 arr\n\t pSeg = zipWith (-) (drop k pSum) pSum\n\t afst = maxElem $ zipWith (+) pSeg (drop k $ scanr1 max pSeg)\n\t asnd = maxElem $ drop (afst + k) pSeg\n\tin (1 + afst, 1 + asnd + afst + k)\n\nmain = \n\tdo [n, k] <- map readInt . BS.words <$> BS.getLine\n\t arr <- map readInt64 . BS.words <$> BS.getLine\n\t putStrLn $ show' (solve arr k)\n\t where show' (a, b) = show a ++ \" \" ++ show b\n"}], "negative_code": [], "src_uid": "74095fe82bd22257eeb97e1caf586499"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\nmain=do\n a<-getLine\n b<-getLine\n let xs=map read (words b)::[Int]\n ys=sort xs\n l=(length ys)-1\n print $ ys!!(l `div` 2)", "positive_code": [{"source_code": "import Data.List\nmain = interact $ show . solve . map read . words\nsolve (n:as) = sort as !! ((n - 1) `div` 2)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\t\tt<- read <$> getLine ::IO Int\n\t\ta<- sort <$> map read <$> words <$> getLine::IO [Int]\n\t\tprint $ if odd t then a!!(div t 2) else a!!((div t 2)-1)\n\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- getLine\n a <- getLine\n print $ w $ sort $ map read $ words a\n where\n w :: [Int] -> Int\n w a = a !! ((length a - 1) `quot` 2)"}, {"source_code": "--ghc 7.10\n\nimport Data.List(sort)\n\nmidNumber :: (Ord a) => [a] -> a\nmidNumber xs = (!! ((length xs - 1) `div` 2)) . sort $ xs\n\nmain = do\n nStr <- getLine\n aStrs <- getLine\n let a = map read . words $ aStrs :: [Int]\n print $ midNumber a"}, {"source_code": "{-# Language BangPatterns, ViewPatterns #-}\nimport Control.DeepSeq\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nmain = do\n n <- fmap readInt $ getLine\n ps <- fmap parseInput $ getLine\n putStrLn $ show $ (sort ps) !! ((n-1)`div`2)\n\nparseInput = map readInt . words\nreadInt x = (read x) :: Int\n"}, {"source_code": "import Data.List\nimport Data.List.Split\n\n\nmain = do\n nstr <- getLine\n let n = read nstr :: Int\n line <- getLine\n let ints = map (read::String->Int) $ splitOn \" \" line\n let sints = sort ints\n putStrLn.show $ sints !! ((n - 1) `div` 2)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.List.Split\n\n\nmain = do\n nstr <- getLine\n let n = read nstr :: Int\n line <- getLine\n let ints = map (read::String->Int) $ splitOn \" \" line\n --print ints\n putStrLn.show $ (ints!!(div n 2))"}, {"source_code": "import Data.List\nimport Data.List.Split\n\n\nmain = do\n nstr <- getLine\n let n = read nstr :: Int\n line <- getLine\n let ints = map (read::String->Int) $ splitOn \" \" line\n --print ints\n putStrLn.show $ ((sort ints)!!(div n 2))"}, {"source_code": "import Data.List\nimport Data.List.Split\n\n\nmain = do\n nstr <- getLine\n let n = read nstr :: Int\n line <- getLine\n let ints = map (read::String->Int) $ splitOn \" \" line\n --print ints\n putStrLn.show $ (sort ints)!! (n - 1) `div` 2\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(sort)\n\nmidNumber :: (Ord a) => [a] -> a\nmidNumber xs = (!! ((length xs) `div` 2)) . sort $ xs\n\nmain = do\n nStr <- getLine\n aStrs <- getLine\n let a = map read . words $ aStrs :: [Int]\n print $ midNumber a"}], "src_uid": "f93a8bd64a405233342f84542fce314d"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Bits\nimport Data.Int\n\nc2 :: Int -> Int64\nc2 v = let v2 = fromIntegral v in div (v2 * (v2 - 1)) 2\n\nsolve :: [Int] -> Int64\nsolve li = let\n sli = group $ sort [countLeadingZeros x | x <- li, x > 0]\n in sum $ map (c2 . length) sli\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- map read . words <$> getLine\n print $ solve a\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\nlbit :: Int -> Int\nlbit x\n | x == 0 = 0\n | otherwise = lbit (x `div` 2) + 1\n\nsolve' [] = (0, 0)\nsolve' [x] = (1, 0)\nsolve' (a : b : xs) =\n if a == b\n then (\\(x, y) -> (x + 1, y)) next\n else (\\(x, y) -> (1, y + (x * (x - 1) `div` 2))) next\n where\n next = solve' (b : xs)\n\nsolve v = f $ solve' v\n where\n f = (\\(a, b) -> b + (a * (a - 1) `div` 2))\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n v <- sort . map (lbit . read) . words <$> getLine\n print $ solve v"}], "negative_code": [], "src_uid": "04e2e1ce3f0b4efd2d4dda69748a0a25"} {"source_code": "import Data.Ratio\nimport Data.Maybe\nimport Data.Set hiding (map)\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) $ C.getContents\n let f (0:_:t) = f t\n f (k:b:t) = b%k: f t\n f _ = []\n print $ size $ fromList $ f $ map toInteger a\n", "positive_code": [{"source_code": "import Data.Ratio\nimport Data.Char\nimport qualified Data.Map as Map\np[k,b]=((-b)%k,abs k)\ns=length . filter ((/=0) . snd) . Map.toList . Map.fromListWith (+)\nrd ('-':t) = - rd t\nrd x = fromIntegral $ foldl (\\x c -> (+ (ord c - ord '0')).(*10) $ x) 0 x :: Integer\nmain=interact$show.s.map p.filter((/=0).head).map(map rd.words).tail.lines\n"}, {"source_code": "import Data.Ratio\nimport Data.Maybe\nimport Data.Set hiding (map)\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n (_:a) <- fmap (map (fst . fromJust . C.readInteger) . C.words) $ C.getContents\n let f (0:_:t) = f t\n f (k:b:t) = b%k: f t\n f _ = []\n print $ size $ fromList $ f a\n"}], "negative_code": [{"source_code": "import Data.Ratio\nimport Data.Maybe\nimport Data.Set hiding (map)\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) $ C.getContents\n let f (0:_:t) = f t\n f (k:b:t) = b%k: f t\n f _ = []\n print $ size $ fromList $ f a\n"}, {"source_code": "import Data.Ratio\nimport Data.Char\nimport qualified Data.Map as Map\np[k,b]=((-b)%k,abs k)\ns=length . filter ((/=0) . snd) . Map.toList . Map.fromListWith (+) -- foldr (\\(k,v) -> Map.insertWith'(+) k v) Map.empty\nrd ('-':t) = - rd t\nrd x = foldl (\\x c -> (+ (ord c - ord '0')).(*10) $ x) 0 x\nmain=interact$show.s.map p.filter((/=0).head).map(map rd.words).tail.lines\n"}], "src_uid": "d436c7a3b7f07c9f026d00bdf677908d"} {"source_code": "module Main where\n\nmm :: Integer\nmm = 998244353\n\n(|>) = flip (.)\n\nmulmod :: Integer -> Integer -> Integer\nmulmod x y = rem (x * y) mm\n\nfexp x 0 = 1\nfexp x e | even e = k\n | otherwise = mulmod x k\n where k' = fexp x (e `div` 2)\n k = mulmod k' k'\n\ninv :: Integer -> Integer\ninv x = fexp x (mm-2)\n\ninv100 = inv 100\n\nsolve :: [Integer] -> Integer\nsolve ps = mulmod (solveNum ps) (inv $ solveDen ps)\n\nsolveNum :: [Integer] -> Integer\nsolveNum ps = solveNum' ps 1\n where solveNum' (p:[]) x = x\n solveNum' (p:ps) x = rem (x + (solveNum' ps (mulmod x p))) mm\n\nsolveDen :: [Integer] -> Integer\nsolveDen ps = foldr mulmod 1 ps\n\nmain = interact $\n lines |> drop 1 |> map (words |> map read |> map (* inv100) |> solve |> show) |> unlines", "positive_code": [{"source_code": "module Main where\n\nmm :: Integer\nmm = 998244353\n\n(|>) = flip (.)\n\n(*.) x y = rem (x * y) mm\n(+.) x y = rem (x + y) mm\n\nfexp x 0 = 1\nfexp x e | even e = k\n | otherwise = x *. k\n where k' = fexp x (e `div` 2)\n k = k' *. k'\n\ninv :: Integer -> Integer\ninv x = fexp x (mm-2)\n\ninv100 = inv 100\n\nsolve :: [Integer] -> Integer\nsolve ps = (solveNum ps) *. (inv $ solveDen ps)\n\nsolveNum :: [Integer] -> Integer\nsolveNum ps = solveNum' ps 1\n where solveNum' (p:[]) x = x\n solveNum' (p:ps) x = x +. (solveNum' ps (x *. p))\n\nsolveDen = foldr (*.) 1\n\nsolveLine = words |> map read |> map (* inv100) |> solve\n\nmain = interact $\n lines |> drop 1 |> map (show . solveLine) |> unlines"}], "negative_code": [], "src_uid": "43d877e3e1c1fd8ee05dc5e5e3067f93"} {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n", "positive_code": [{"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Integer] -> [Integer]\nsolve (n:a:ds) = [ d - min d (a - n + 1) + max 1 (a - sum ds + d) - 1 | d <- ds ]\nsolve _ = undefined\n"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}, {"source_code": "import Control.Applicative\n\nsolve :: [Integer] -> Integer -> [Integer]\nsolve ds a = map go ds\n where\n go d = d - (myMax - myMin) - 1\n where\n myMin = max 1 $ a - (max' - d)\n myMax = min d $ a - min' + 1\n min' = toInteger $ length ds\n max' = sum ds\n\nmain :: IO ()\nmain = do\n [n, a] <- map read <$> words <$> getLine\n ds <- map read <$> words <$> getLine\n putStrLn . unwords . map show $ solve ds a"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}, {"source_code": "main=getContents>>=putStrLn.unwords.map show.f.map read.words\nf(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nsolve :: [Int] -> Int -> [Int]\nsolve ds a = map go ds\n where\n go d = d - (myMax - myMin) - 1\n where\n myMin = max 1 $ a - (max' - d)\n myMax = min d $ a - min' + 1\n min' = length ds\n max' = sum ds\n\nmain :: IO ()\nmain = do\n [n, a] <- map read <$> words <$> getLine\n ds <- map read <$> words <$> getLine\n putStrLn . unwords . map show $ solve ds a"}], "src_uid": "2c51414eeb430ad06aac53a99ff95eff"} {"source_code": "main :: IO()\nmain = putStrLn . unwords . map show . proof . solve . map read . words =<< getLine\n\nproof :: [Integer] -> [Integer]\nproof [] = [-1]\nproof x = x\n\nsolve :: [Integer] -> [Integer]\nsolve [l, r, k] = solve' 1\n where solve' :: Integer -> [Integer]\n solve' x | x < l = solve' (x * k)\n | x > r = []\n | otherwise = x : solve' (x * k)\n", "positive_code": [{"source_code": " main = do\n line <- getLine\n let l:r:k:xs = getInts 3 line\n let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)\n putStrLn $ unwords $ ans $ map show [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]\n \n getInts :: Int -> String -> [Integer]\n \n getInts 0 _ = []\n getInts _ [] = []\n getInts x str = map stringToInt $ take x $ words str\n \n stringToInt :: String -> Integer\n \n stringToInt str = read str :: Integer\n \n ans [] = [\"-1\"]\n ans x = x"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\ngetIntList :: IO [Integer]\ngetIntList = fmap read . words <$> getLine\n\nout :: Show a => [a] -> IO ()\nout as = putStrLn $ bool (unwords $ map show as) \"-1\" (null as) \n\nmain :: IO ()\nmain = out =<< sol <$> getIntList\n\nsol :: Integral a => [a] -> [a]\nsol [l,r,k] = takeWhile (<=r) . dropWhile ( Integer -> Integer -> [Integer]\ngetRangePowers l r k = [k ^ a | a <- [0 .. (ceiling ((logBase (fromIntegral k) (fromIntegral r)) :: Float))], k^a >= l, k^a <=r]\n\nemptytoneg [] = [-1]\nemptytoneg xs = xs\n\nmain = do\n line <- getLine\n let ws = words line\n let l = read (ws !! 0)\n let r = read (ws !! 1)\n let k = read (ws !! 2)\n let powers = getRangePowers l r k\n putStrLn $ unwords $ map show $ emptytoneg powers\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n\n \nmain= do\n\t[l,r,k]<- map read.words <$> getLine::IO [Integer]\n\tlet x = takeWhile (<=r) $ dropWhile ( read s::Int) . words) <$> getLine\n-- let top = ceiling $ logBase (fromIntegral k) (fromIntegral r)\n-- result = [res | n <- [0, 1 .. top], let res = k^n, res >= l, res <= r]\n-- if null result\n-- then putStrLn \"-1\"\n-- else putStrLn $ unwords $ map show result\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\ngetIntList :: IO [Integer]\ngetIntList = fmap read . words <$> getLine\n\nout :: Show a => [a] -> IO ()\nout as = putStrLn $ bool (unwords $ map show as) \"-1\" (null as)\n\nmain :: IO ()\nmain = out =<< sol <$> getIntList\n\nsol :: Integral a => [a] -> [a]\nsol [l,r,k] = takeWhile (<=r) . dropWhile ( [Integer]\ncalc (a, b, k, cur)\n | cur > b = []\n | cur >= a = [cur]++calc(a, b, k, cur*k)\n | otherwise = calc(a, b, k, cur*k)\n\nemptytoneg :: [Integer] -> [Integer]\nemptytoneg [] = [-1]\nemptytoneg xs = xs\n\n\nmain = do\n args <- getContents\n let \n (l:r:k:xs) = words args\n putStrLn $ unwords $ map show $ emptytoneg $ calc(read l, read r, read k, 1)\n "}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetIntegers :: IO [Integer]\ngetIntegers = map read <$> words <$> getLine\n\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\n\nsolve :: Integer -> Integer -> Integer -> [Integer]\nsolve l r k = takeWhile (<=r) $ dropWhile (= l, p <= r]\n\ngetInts :: Int -> String -> [Integer]\n\ngetInts 0 _ = []\ngetInts _ [] = []\ngetInts x str = map stringToInt $ take x $ words str\n\nstringToInt :: String -> Integer\n\nstringToInt str = read str :: Integer\n\nans [] = [\"-1\"]\nans y = y"}, {"source_code": "main = do\n line <- getLine\n let l:r:k:xs = getInts 3 line\n let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)\n putStrLn $ unwords $ ans $ map show [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]\n \ngetInts :: Int -> String -> [Integer]\n \ngetInts 0 _ = []\ngetInts _ [] = []\ngetInts x str = map stringToInt $ take x $ words str\n \nstringToInt :: String -> Integer\n \nstringToInt str = read str :: Integer\n \nans [] = [\"-1\"]\nans y = y"}, {"source_code": "main = do\n\tline <- getLine\n\tlet l:r:k:xs = getInts 3 line\n\tlet br = ceiling $ logBase (fromIntegral k) (fromIntegral r)\n\tputStrLn $ foldr1 (++) $ ans $ map ((' ':) . show) [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]\n\ngetInts :: Int -> String -> [Integer]\n\ngetInts 0 _ = []\ngetInts _ [] = []\ngetInts x str = map stringToInt $ take x $ words str\n\nstringToInt :: String -> Integer\n\nstringToInt str = read str :: Integer\n\nans [] = [\"-1\"]\nans x = x\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Applicative\n\nf l r k acc n\n | res < l = f l r k acc (n+1)\n | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)\n | otherwise = acc\n where res = k^n\n\nmain :: IO ()\nmain = do\n [l, r, k] <- (map (\\s -> read s::Int) . words) <$> getLine\n let result = f l r k [] 0\n if null result\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show result\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n [l, r, k] <- (map (\\s -> read s::Int) . words) <$> getLine\n let top = ceiling $ logBase (fromIntegral k) (fromIntegral r)\n result = [res | n <- [0, 1 .. top], let res = k^n, res >= l, res <= r]\n if null result\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show result\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nf l r k acc n\n | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)\n | otherwise = acc\n where res = k^n\n\nmain :: IO ()\nmain = do\n [l, r, k] <- (map (\\s -> read s::Int) . words) <$> getLine\n let result = f l r k [] 0\n if null result\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show result\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nf l r k acc n\n | res < l = f l r k acc (n+1)\n | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)\n | otherwise = acc\n where res = k^n\n\nmain :: IO ()\nmain = do\n [l, r, k] <- (map (\\s -> read s::Int) . words) <$> getLine\n let result = f l r k [] 0\n if null result\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show result\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nf :: Int -> Int -> Int -> [Int] -> Integer -> [Int]\n-- f :: (Num a, Num b) => a -> a -> a -> [a] -> b -> [a]\nf l r k acc n\n | res < l = f l r k acc (n+1)\n | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)\n | otherwise = acc\n where res = k^n\n\nmain :: IO ()\nmain = do\n [l, r, k] <- (map (\\s -> read s::Int) . words) <$> getLine\n let result = f l r k [] 0\n if null result\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show result\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nf l r k acc n\n | res < l = f l r k acc (n+1)\n | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)\n | res > r = acc\n where res = k^n\n\nmain :: IO ()\nmain = do\n [l, r, k] <- (map (\\s -> read s::Int) . words) <$> getLine\n let result = f l r k [] 0\n if null result\n then putStrLn \"-1\"\n else putStrLn $ unwords $ map show result\n"}, {"source_code": "module Main where\n\ncalc :: (Int, Int, Int, Int) -> [Int]\ncalc (a, b, k, cur)\n | cur > b = []\n | cur >= a = [cur]++calc(a, b, k, cur*k)\n | otherwise = calc(a, b, k, cur*k)\n\nemptytoneg :: [Int] -> [Int]\nemptytoneg [] = [-1]\nemptytoneg xs = xs\n\n\nmain = do\n args <- getContents\n let \n (l:r:k:xs) = words args\n putStrLn $ unwords $ map show $ emptytoneg $ calc(read l, read r, read k, 1)\n "}, {"source_code": "import Data.Functor\nimport Data.List\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getLine\n\nparsePairs [] = []\nparsePairs (x:y:rs) = (x, y) : parsePairs rs\n\nsolve :: Int -> Int -> Int -> [Int]\nsolve l r k = takeWhile (<=r) $ dropWhile ( getLine::IO [Int]\n\tlet x = length $takeWhile (<=r) $ dropWhile ( getLine::IO [Int]\n\tlet x = takeWhile (<=r) $ dropWhile ( getLine >>= flip replicateM_ scase\nreadI :: IO [Int]\nreadI = map read . words <$> getLine\nscase = read <$> getLine >>=\n \\n -> readI >>= \\as -> readI >>= \\bs -> print (maxDamage n as bs)\n\n\nmaxDamage :: Int -> [Int] -> [Int] -> Int\nmaxDamage n as bs = let (fires, ices) = partition as bs ([], [])\n fl = length fires\n il = length ices\n (a, al, b, bl) = case compare fl il of\n EQ -> (ices, il, fires, fl)\n LT -> (ices, il, fires, fl)\n GT -> (fires, fl, ices, il)\n partition [] [] (fs, is) = (reverse (sort fs), reverse (sort is))\n partition (0:as) (f:bs) (fires, ices) =\n partition as bs (f:fires, ices)\n partition (1:as) (i:bs) (fires, ices) =\n partition as bs (fires, i:ices)\n \n in\n if (al == bl)\n then 2*(sum a + sum b) - minimum (a++b)\n else let xs = take (al-1) a\n x = last a\n in\n 2*(sum b + sum (take bl xs)) + x + sum (drop bl xs)\n\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\r\n\r\ndata TC = TC {n :: Int, as :: [Int], bs :: [Int64]}\r\n\r\ntype Output = Int64\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n as <- n >< int\r\n bs <- n >< int64\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = sum bs + extra fire frost + extra frost fire - too_much\r\n where\r\n [fire, frost] = [sort [x | (t', x) <- zip as bs, t' == t] | t <- [0, 1]]\r\n extra xs ys = xs >$> reverse >>> take (length ys) >>> sum\r\n too_much\r\n | length fire == length frost = minimum bs\r\n | otherwise = 0\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput ix = showB\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\n\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let a = map read . words $ input ::[Int]\r\n input <- getLine\r\n let b = map read . words $ input ::[Int]\r\n let a1 = sortBy (flip compare) . map snd .filter ((0==).fst) .zip a $ b\r\n let a2 = sortBy (flip compare) . map snd .filter ((1==).fst) .zip a $ b\r\n let mi = min (length a1) (length a2)\r\n let s1 = (sum $ zipWith (\\x y -> 2*(x+y)) a1 a2)\r\n let s2 = (sum.drop mi $ a1) + (sum.drop mi $ a2)\r\n putStrLn .show. (s1+) $ if s2==0 then negate .minimum$ b else s2\r\n return ()\r\n"}], "negative_code": [], "src_uid": "bc1587d3affd867804e664fdb38ed765"} {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n", "positive_code": [{"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unlines $ (show $ length xs):xs where\n xs = map (out2.partition) $ codes n\n codes 1 = [ [0] ]\n codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]\n where\n xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])\n where m = foldl1 max z + 1\n partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]\n out1 [x] = (show x) ++ \"}\"\n out1 (x:xs) = (show x) ++ \",\" ++ (out1 xs)\n out2 [x] = '{':(out1 x)\n out2 (x:xs) = (out2 [x]) ++ \",\" ++ (out2 xs)\n"}], "negative_code": [], "src_uid": "f4ffddfa5f4b1730da77841722b92417"} {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\ninf = 10 ^ 18\n\nmain = do\n _ <- getLine\n x <- sort . map read . words <$> getLine :: IO [Integer]\n y <- ((-inf) : ) . (++ [inf]) . sort . map read . words <$> getLine :: IO [Integer]\n print $ solve x y\n\nsolve [] _ = 0\nsolve (x:xs) (y1:y2:ys)\n | y2 < x = solve (x:xs) (y2:ys)\n | otherwise = max (min (x - y1) (y2 - x)) (solve xs (y1:y2:ys))\n", "positive_code": [{"source_code": "import Data.Maybe\nimport Data.Array\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n--import Debug.Trace\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nmain = do\n [n, m] <- getInts\n cities <- getInts\n towers <- getInts\n let thresholds = if m == 1 then listArray (1,1) [1000000000 + 1] else listArray (1,m-1) (getThresholds towers) :: Array Int Int\n let towers' = listArray (1,m) towers\n print $ solve thresholds towers' cities\n\ngetThresholds :: [Int] -> [Int]\ngetThresholds towers = zipWith (\\x y -> (x + y) `div` 2) towers (tail towers)\n\nsolve thresholds towers cities = f cities 0 where\n numThresholds = length (elems thresholds)\n f [] soln = soln\n f (x:xs) soln = f xs (max (abs (nearest x - x)) soln)\n nearest x = towers ! (bin x 1 numThresholds)\n bin x i j\n | x > thresholds ! j = j + 1\n | i >= j = j\n | thresholds ! mid == x = mid\n | thresholds ! mid > x = bin x i mid\n | otherwise = bin x (mid+1) j\n where mid = (i + j) `div` 2"}], "negative_code": [], "src_uid": "9fd8e75cb441dc809b1b2c48c4012c76"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [hh, mm] <- getInts\n [h0, m0] <- map (fst . fromJust . C.readInt) . C.split ':' <$> C.getLine\n let\n rev '0' = Just '0'\n rev '1' = Just '1'\n rev '2' = Just '5'\n rev '5' = Just '2'\n rev '8' = Just '8'\n rev _ = Nothing\n revTwo [c1, c2] = do\n c1' <- rev c1\n c2' <- rev c2\n return [c2', c1']\n revTime h m = do\n s' <- revTwo $ printf \"%02d\" h\n t' <- revTwo $ printf \"%02d\" m\n guard $ read t' < hh && read s' < mm\n return $ printf \"%02d\" h ++ \":\" ++ printf \"%02d\" m\n toRev o = revTime h' m'\n where\n o' = o `mod` (hh * mm)\n h' = o' `quot` mm\n m' = o' `mod` mm\n result = fromJust $ toRev $ head $ filter (isJust . toRev) [h0 * mm + m0 .. ]\n C.putStrLn $ C.pack result\n", "positive_code": [{"source_code": "\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n\n-- http://codeforces.com/contest/1493/problem/B (mirror clock)\n\nimport qualified Data.List as List\n\nimport Text.Printf (printf)\n\nmain = interact $ unlines . map solveTC . linePairs . tail . lines\n\nsolveTC (hh, mm, strTime) = goodStrTime\n where\n (Just goodStrTime) = (List.find isGoodStrTime . map toStrTime) [toMinutes strTime ..]\n\n isGoodStrTime tm\n | '?' `elem` rev = False\n | hours rev >= hh = False\n | minutes rev >= mm = False\n | otherwise = True\n where\n rev = (map mirrorChar . reverse) tm\n\n toMinutes tm = minutes tm + (mm * hours tm)\n\n toStrTime tmMinutes = printf \"%02d:%02d\" (m `div` mm) (m `mod` mm)\n where\n m = tmMinutes `mod` (hh * mm)\n\nhours [ hiH, loH, ':', _hiM, _loM] = readI [hiH, loH]\nminutes [_hiH, _loH, ':', hiM, loM] = readI [hiM, loM]\n\nmirrorChar = f\n where\n f '0' = '0'\n f '1' = '1'\n f '2' = '5'\n f '5' = '2'\n f '8' = '8'\n f ':' = ':'\n f _ch = '?'\n\nlinePairs [] = []\nlinePairs [_line] = error \"bad input (no pair)\"\nlinePairs (strHM:strTime:ls) = (hh, mm, strTime) : linePairs ls\n where\n [hh, mm] = (map readI . words) strHM\n\nreadI s = read s :: Int\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n-- putStrLn (show n)\n replicateM_ n action\n\naction :: IO ()\naction = do\n [h, m] <- (map (read :: String -> Int) . words) <$> getLine\n time <- getLine\n let res = dropWhile (not . mirror h m) (flow h m time)\n putStrLn $ head res\n\nflow :: Int -> Int -> String -> [String]\nflow h m initial@([h1,h2,_,m1,m2]) = map (\\(_, _, r) -> r) $ iterate inc (read [h1,h2], read [m1,m2], initial)\n where\n show2 x\n | x < 10 = '0':show x\n | otherwise = show x\n showTime ch cm = show2 ch ++ ':' : show2 cm\n maxM = m - 1\n maxH = h - 1\n inc :: (Int, Int, String) -> (Int, Int, String)\n inc (ch, cm, _)\n | cm < maxM = (ch, cm + 1, showTime ch (cm + 1))\n | ch < maxH = (ch + 1, 0, showTime (ch + 1) 0)\n | otherwise = (0, 0, \"00:00\")\n\nmirror :: Int -> Int -> String -> Bool\nmirror h m time = fromMaybe False (checkTime <$> (mir time))\n where\n checkTime :: String -> Bool\n checkTime (m2:m1:_:h2:h1:[]) = (read [h1,h2]) < h && (read [m1,m2]) < m\n mir :: String -> Maybe String\n mir s = mapM mi s\n mi :: Char -> Maybe Char\n mi c = case c of\n '0' -> Just c\n '1' -> Just c\n '8' -> Just c\n ':' -> Just c\n '2' -> Just '5'\n '5' -> Just '2'\n otherwise -> Nothing"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [hh, mm] <- getInts\n [h0, m0] <- map (fst . fromJust . C.readInt) . C.split ':' <$> C.getLine\n let\n rev '0' = Just '0'\n rev '1' = Just '1'\n rev '2' = Just '2'\n rev '5' = Just '5'\n rev '8' = Just '8'\n rev _ = Nothing\n revTwo [c1, c2] = do\n c1' <- rev c1\n c2' <- rev c2\n return [c2', c1']\n revTime h m = do\n s' <- revTwo $ printf \"%02d\" h\n t' <- revTwo $ printf \"%02d\" m\n guard $ read t' < hh && read s' < mm\n return $ printf \"%02d\" h ++ \":\" ++ printf \"%02d\" m\n toRev o = revTime h' m'\n where\n o' = o `mod` (hh * mm)\n h' = o' `quot` mm\n m' = o' `mod` mm\n result = fromJust $ toRev $ head $ filter (isJust . toRev) [h0 * mm + m0 .. ]\n C.putStrLn $ C.pack result\n"}], "src_uid": "7f28e4dbd199b84bd7885bf7f479cf38"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Control.Monad.ST\n\nimport qualified Data.IntSet as S\n\nsieve :: Int -> UArray Int Int\nsieve n = accumArray min n (1, n) $ (1, 1) : do\n i <- [2..n]\n zip [i, 2*i .. n] $ repeat i\n\nextractFactors :: UArray Int Int -> Int -> [Int]\nextractFactors lpf = let\n go 1 = []\n go x = let p = lpf ! x in p : go (quot x p)\n in map head . group . go\n\ndsuFind :: STUArray s Int Int -> Int -> ST s Int\ndsuFind arr x = do\n p <- readArray arr x\n if p == x\n then pure x\n else do\n p2 <- readArray arr x\n writeArray arr x p2\n dsuFind arr p2\n\nmerge :: (Int, Int) -> [(Int, Int)] -> UArray Int Int\nmerge bnds pairs = runSTUArray $ do\n par <- newListArray bnds $ range bnds\n sz <- newArray bnds 1 :: ST s (STUArray s Int Int)\n forM_ pairs $ \\(x, y) -> do\n p <- dsuFind par x\n q <- dsuFind par y\n when (p /= q) $ do\n ps <- readArray sz p\n qs <- readArray sz q\n let (s, t) = if ps >= qs then (p, q) else (q, p)\n writeArray par t s\n writeArray sz s (ps + qs)\n forM_ (range bnds) $ \\x -> dsuFind par x >>= writeArray par x\n pure par\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, q] <- readInts\n aLi <- readInts\n let\n a :: UArray Int Int\n a = listArray (1, n) aLi\n m = 1 + foldl' max 1 (elems a)\n lpf = sieve m\n direct :: Array Int [Int]\n direct = accumArray (flip (:)) [] (1, m) $ do\n (i, ai) <- assocs a\n [(p, i) | p <- extractFactors lpf ai]\n components = merge (1, n) [(v1, v2) | v1 : vs <- elems direct, v2 <- vs]\n oneSteps :: Array Int S.IntSet\n oneSteps = accumArray (flip S.insert) (S.empty) (1, m) $ do\n (i, ai) <- assocs a\n let\n js = components ! i : do\n p <- extractFactors lpf (ai + 1)\n j <- take 1 $ direct ! p\n pure $ components ! j\n [(j1, j2) | j1 <- js, j2 <- js]\n replicateM_ q $ do\n [s, t] <- map (components !) <$> readInts\n putInts $ pure $ if s == t\n then 0\n else if S.member s (oneSteps ! t)\n then 1\n else 2\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Rank2Types #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (forM_, guard, replicateM, when)\r\nimport Control.Monad.ST (ST, runST)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Array.IArray (Array, elems)\r\nimport Data.Array.ST (MArray (newArray), STUArray, freeze, newListArray, readArray, writeArray)\r\nimport Data.Array.Unboxed (UArray, accumArray, (!))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport qualified Data.IntSet as S\r\nimport Data.List (group, sort, unfoldr)\r\nimport Data.Maybe (fromJust)\r\nimport Debug.Trace (trace)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.pack <$> testCase)\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n n <- int\r\n q <- int\r\n as <- n >< int\r\n qs <- q >< pair int int\r\n return . unlines . map show $ solve n as qs\r\n\r\ntype VVI = Array Int [Int]\r\ntype VSI = Array Int S.IntSet\r\n\r\nsolve :: Int -> [Int] -> [(Int, Int)] -> [Int]\r\nsolve n as = map query\r\n where\r\n query (u, v)\r\n | cu == cv = 0\r\n | cv `S.member` (adj ! cu) = 1\r\n | otherwise = 2\r\n where\r\n cu = dsu ! u\r\n cv = dsu ! v\r\n\r\n ps :: VVI\r\n ps = accumArray' (:) [] (1, lim) $ do\r\n (a, i) <- zip as [1 .. n]\r\n (,i) <$> factorize a\r\n dsu = buildDSU n $ concat [zip xs (tail xs) | xs <- elems ps, not (null xs)]\r\n\r\n adj :: VSI\r\n adj = accumArray' S.insert S.empty (1, n) $ do\r\n (a, i) <- zip as [1 .. n]\r\n let nodes = dsu ! i : [dsu ! head ns | f <- factorize (a + 1),\r\n let ns = ps ! f,\r\n not (null ns)]\r\n [(u, v) | u <- nodes, v <- nodes]\r\n\r\nlim = 1 + 10 ^ 6\r\nprimes = sieve lim\r\n\r\nfactorize :: Int -> [Int]\r\nfactorize = map head . group . unfoldr f\r\n where\r\n f 1 = Nothing\r\n f n = let p = primes ! n in Just (p, n `div` p)\r\n\r\naccumArray' f = accumArray (flip f)\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- sieve\r\nsieve :: Int -> UArray Int Int\r\nsieve n =\r\n accumArray min n (1, n) $\r\n (1, 1) : do\r\n i <- [2 .. n]\r\n zip [i, 2 * i .. n] $ repeat i\r\n\r\n-- DSU --\r\ndata DSU s = DSU {parentST :: STUArray s Int Int, sizeST :: STUArray s Int Int}\r\n\r\nmkDSU :: Int -> ST s (DSU s)\r\nmkDSU n = DSU <$> newListArray (1, n) [1 .. n] <*> newArray (1, n) 1\r\n\r\nfind :: Int -> DSU s -> ST s Int\r\nfind u dsu@(DSU par _) = do\r\n p <- readArray par u\r\n if p == u\r\n then return u\r\n else do\r\n p' <- find p dsu\r\n writeArray par u p'\r\n return p'\r\n\r\nmerge :: Int -> Int -> DSU s -> ST s Bool\r\nmerge u v dsu@(DSU par sz) = do\r\n u <- find u dsu\r\n v <- find v dsu\r\n when (u /= v) $ do\r\n su <- readArray sz u -- su = sz[pu]\r\n sv <- readArray sz v -- sv = sz[pv]\r\n let s = su + sv\r\n let (u', v') = if su >= sv then (u, v) else (v, u)\r\n writeArray par v' u' -- par[v] = u\r\n writeArray sz u' s -- sz[u] = s\r\n return $ u /= v\r\n\r\nsame :: Int -> Int -> DSU s -> ST s Bool\r\nsame u v dsu = (==) <$> find u dsu <*> find v dsu\r\n\r\nbuildDSU :: Int -> [(Int, Int)] -> UArray Int Int\r\nbuildDSU n edges = runST $ do\r\n dsu <- mkDSU n\r\n forM_ edges $ \\(u, v) -> merge u v dsu\r\n forM_ [1 .. n] $ \\u -> find u dsu\r\n freeze $ parentST dsu\r\n\r\n-- Scanner --\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Rank2Types #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (forM_, guard, replicateM, when)\r\nimport Control.Monad.ST (ST, runST)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Array.IArray (Array, elems)\r\nimport Data.Array.ST (MArray (newArray), STUArray, freeze, newListArray, readArray, writeArray)\r\nimport Data.Array.Unboxed (UArray, accumArray, (!))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport qualified Data.IntSet as S\r\nimport Data.List (group, sort, unfoldr)\r\nimport Data.Maybe (fromJust)\r\nimport Debug.Trace (trace)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.pack <$> testCase)\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n n <- int\r\n q <- int\r\n as <- n >< int\r\n qs <- q >< pair int int\r\n return . unlines . map show $ solve n as qs\r\n\r\ntype VVI = Array Int [Int]\r\ntype VSI = Array Int S.IntSet\r\n\r\nsolve :: Int -> [Int] -> [(Int, Int)] -> [Int]\r\nsolve n as = map query\r\n where\r\n query (u, v)\r\n | cu == cv = 0\r\n | cv `S.member` (adj ! cu) = 1\r\n | otherwise = 2\r\n where\r\n cu = dsu ! u\r\n cv = dsu ! v\r\n\r\n ps :: VVI\r\n ps = accumArray' (:) [] (1, lim) $ do\r\n (a, i) <- zip as [1 .. n]\r\n (,i) <$> factorize a\r\n dsu = buildDSU n $ concat [zip xs (tail xs) | xs <- elems ps, not (null xs)]\r\n\r\n adj :: VSI\r\n adj = accumArray' S.insert S.empty (1, n) $ do\r\n (a, i) <- zip as [1 .. n]\r\n let nodes = i : [dsu ! head ns | f <- factorize (a + 1),\r\n let ns = ps ! f,\r\n not (null ns)]\r\n [(u, v) | u <- nodes, v <- nodes]\r\n\r\nlim = 10 ^ 6\r\nprimes = sieve lim\r\n\r\nfactorize :: Int -> [Int]\r\nfactorize = map head . group . unfoldr f\r\n where\r\n f 1 = Nothing\r\n f n = let p = primes ! n in Just (p, n `div` p)\r\n\r\naccumArray' f = accumArray (flip f)\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- sieve\r\nsieve :: Int -> UArray Int Int\r\nsieve n =\r\n accumArray min n (1, n) $\r\n (1, 1) : do\r\n i <- [2 .. n]\r\n zip [i, 2 * i .. n] $ repeat i\r\n\r\n-- DSU --\r\ndata DSU s = DSU {parentST :: STUArray s Int Int, sizeST :: STUArray s Int Int}\r\n\r\nmkDSU :: Int -> ST s (DSU s)\r\nmkDSU n = DSU <$> newListArray (1, n) [1 .. n] <*> newArray (1, n) 1\r\n\r\nfind :: Int -> DSU s -> ST s Int\r\nfind u dsu@(DSU par _) = do\r\n p <- readArray par u\r\n if p == u\r\n then return u\r\n else do\r\n p' <- find p dsu\r\n writeArray par u p'\r\n return p'\r\n\r\nmerge :: Int -> Int -> DSU s -> ST s Bool\r\nmerge u v dsu@(DSU par sz) = do\r\n u <- find u dsu\r\n v <- find v dsu\r\n when (u /= v) $ do\r\n su <- readArray sz u -- su = sz[pu]\r\n sv <- readArray sz v -- sv = sz[pv]\r\n let s = su + sv\r\n let (u', v') = if su >= sv then (u, v) else (v, u)\r\n writeArray par v' u' -- par[v] = u\r\n writeArray sz u' s -- sz[u] = s\r\n return $ u /= v\r\n\r\nsame :: Int -> Int -> DSU s -> ST s Bool\r\nsame u v dsu = (==) <$> find u dsu <*> find v dsu\r\n\r\nbuildDSU :: Int -> [(Int, Int)] -> UArray Int Int\r\nbuildDSU n edges = runST $ do\r\n dsu <- mkDSU n\r\n forM_ edges $ \\(u, v) -> merge u v dsu\r\n forM_ [1 .. n] $ \\u -> find u dsu\r\n freeze $ parentST dsu\r\n\r\n-- Scanner --\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Control.Monad.ST\n\nimport qualified Data.IntSet as S\n\nsieve :: Int -> UArray Int Int\nsieve n = accumArray min n (1, n) $ (1, 1) : do\n i <- [2..n]\n zip [i, 2*i .. n] $ repeat i\n\nextractFactors :: UArray Int Int -> Int -> [Int]\nextractFactors lpf = let\n go 1 = []\n go x = let p = lpf ! x in p : go (quot x p)\n in map head . group . go\n\ndsuFind :: STUArray s Int Int -> Int -> ST s Int\ndsuFind arr x = do\n p <- readArray arr x\n if p == x\n then pure x\n else do\n p2 <- readArray arr x\n writeArray arr x p2\n dsuFind arr p2\n\nmerge :: (Int, Int) -> [(Int, Int)] -> UArray Int Int\nmerge bnds pairs = runSTUArray $ do\n par <- newListArray bnds $ range bnds\n sz <- newArray bnds 1 :: ST s (STUArray s Int Int)\n forM_ pairs $ \\(x, y) -> do\n p <- dsuFind par x\n q <- dsuFind par y\n when (p /= q) $ do\n ps <- readArray sz p\n qs <- readArray sz q\n let (s, t) = if ps >= qs then (p, q) else (q, p)\n writeArray par t s\n writeArray sz s (ps + qs)\n forM_ (range bnds) $ \\x -> dsuFind par x >>= writeArray par x\n pure par\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, q] <- readInts\n aLi <- readInts\n let\n a :: UArray Int Int\n a = listArray (1, n) aLi\n m = 1 + foldl' max 1 (elems a)\n lpf = sieve m\n direct :: Array Int [Int]\n direct = accumArray (flip (:)) [] (1, m) $ do\n (i, ai) <- assocs a\n [(p, i) | p <- extractFactors lpf ai]\n components = merge (1, n) [(v1, v2) | v1 : vs <- elems direct, v2 <- vs]\n oneSteps :: Array Int S.IntSet\n oneSteps = accumArray (flip S.insert) (S.empty) (1, m) $ do\n (i, ai) <- assocs a\n let ic = components ! i\n p <- extractFactors lpf (ai + 1)\n j <- take 1 $ direct ! p\n let jc = components ! j\n [(ic, jc), (jc, ic)]\n replicateM_ q $ do\n [s, t] <- map (components !) <$> readInts\n putInts $ pure $ if s == t\n then 0\n else if S.member s (oneSteps ! t)\n then 1\n else 2\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "d4774270c77128b1cc4a8f454ee544bd"} {"source_code": "import Control.Monad\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Array.MArray.Safe\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\ntype Position = (Int, Int)\ntype Board = UArray (Int, Int) Bool\ntype Visible = UArray (Int, Int) Bool\n\nmain = do\n [n, m] <- getInts\n board <- toTable n m `fmap` replicateM n getInts\n let actorExists = map (checkExist board n m) [(-1,0), (1,0), (0,-1), (0,1)]\n print $ sum $ map (length . (goodPositions board n m)) actorExists\n\nvisitOrder n m dir = case dir of\n (-1,0) -> ([1..n], [1..m])\n (1,0) -> ([1..n], [m,m-1..1])\n (0,-1) -> ([1..n], [1..m])\n (0,1) -> ([n,n-1..1], [1..m])\n\ncheckExist :: Board -> Int -> Int -> (Int,Int) -> Visible\ncheckExist board n m (dirX,dirY) = runSTUArray $ do\n a <- newArray ((1,1),(n,m)) False\n let (rows, cols) = visitOrder n m (dirX,dirY)\n forM_ rows $ \\y -> do\n forM_ cols $ \\x -> do\n let y' = y + dirY\n let x' = x + dirX\n if 1 <= y' && y' <= n && 1 <= x' && x' <= m\n then do\n prev <- readArray a (y',x')\n writeArray a (y,x) (prev || board ! (y',x'))\n else return ()\n return a\n\ntoTable :: Int -> Int -> [[Int]] -> Board\ntoTable n m board = listArray ((1,1),(n,m)) [x == 1 | row <- board, x <- row]\n\ngoodPositions :: Board -> Int -> Int -> Visible -> [Position]\ngoodPositions board n m good = [(i,j) | i <- [1..n], j <- [1..m], board ! (i,j) == False, good ! (i,j)]\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.DeepSeq\nimport Control.Exception\nimport Data.Array.IArray\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Data.Array.MArray.Safe\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\ntype Position = (Int, Int)\ntype Board = UArray (Int, Int) Int\ntype Visible = UArray (Int, Int) Bool\n\nmain = do\n [n, m] <- getInts\n board <- toTable n m `fmap` replicateM n getInts\n evaluate board\n let actorExists = map (checkExist board n m) [(-1,0), (1,0), (0,-1), (0,1)]\n print $ sum $ map (length . (goodPositions board n m)) actorExists\n\nvisitOrder n m dir = case dir of\n (-1,0) -> ([1..n], [1..m])\n (1,0) -> ([1..n], [m,m-1..1])\n (0,-1) -> ([1..n], [1..m])\n (0,1) -> ([n,n-1..1], [1..m])\n\ncheckExist :: Board -> Int -> Int -> (Int,Int) -> Visible\ncheckExist board n m (dirX,dirY) = runSTUArray $ do\n a <- newArray ((1,1),(n,m)) False\n let (rows, cols) = visitOrder n m (dirX,dirY)\n forM_ rows $ \\y -> do\n forM_ cols $ \\x -> do\n let y' = y + dirY\n let x' = x + dirX\n if 1 <= y' && y' <= n && 1 <= x' && x' <= m\n then do\n prev <- readArray a (y',x')\n writeArray a (y,x) (prev || board ! (y',x') == 1)\n else return ()\n return a\n{-\ncheckExist board n m (dirX,dirY) = a where\n a = array ((1,1),(n,m)) [((i,j), force $ check i j) | i <- [1..n], j <- [1..m]]\n check i j\n | valid i' j' = a ! (i',j') || board ! (i',j') == 1\n | otherwise = False\n where\n valid i j = 1 <= i && i <= n && 1 <= j && j <= m\n i' = i + dirY\n j' = j + dirX\n-}\n\ntoTable :: Int -> Int -> [[Int]] -> Board\ntoTable n m board = listArray ((1,1),(n,m)) [x | row <- board, x <- row]\n\ngoodPositions :: Board -> Int -> Int -> Visible -> [Position]\ngoodPositions board n m good = [(i,j) | i <- [1..n], j <- [1..m], board ! (i,j) == 0, good ! (i,j)]\n"}], "negative_code": [], "src_uid": "c3a7d82f6c3cf8678a1c7c521e0a5f51"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\ntest :: (Int,Int) -> (Int,Int) -> IO Int\ntest (x1,y1) (x2,y2) = do\n putStrLn $ unwords $ (\"?\":) $ map show $ [x1,y1,x2,y2]\n hFlush stdout\n reply <- readInt <$> getLine\n when (reply < 0) $ exitFailure\n return reply\n\ntestOdd :: (Int, Int) -> (Int, Int) -> IO Bool\ntestOdd p1 p2 = odd <$> test p1 p2\n\nswapWith False = id\nswapWith True = swap\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n ((x1,y1),(x2,y2)) <- query n\n putStrLn $ unwords $ (\"!\":) $ map show $ [x1,y1,x2,y2]\n\nquery :: Int -> IO ((Int,Int),(Int,Int))\nquery n = do\n res_lr <- findLRUD False n\n case res_lr of\n Just (x1,x2) -> do\n y1 <- findLine False n x1\n y2 <- findLine False n x2\n return ((x1,y1),(x2,y2))\n Nothing -> do\n Just (y1,y2) <- findLRUD True n\n x <- findLine True n y1\n return ((x,y1),(x,y2))\n\nfindLRUD :: Bool -> Int -> IO (Maybe (Int,Int))\nfindLRUD xyflg n = go1 1\n where\n tst x = (testOdd `on` swapWith xyflg) (x,1) (x,n)\n go1 x\n | x >= n = return Nothing\n | otherwise = do\n b <- tst x\n if not b then go1 (x+1) else Just . (x,) <$> go2 (x+1)\n go2 x\n | x >= n = return n\n | otherwise = do\n b <- tst x\n if not b then go2 (x+1) else return x \n \n\n\nfindLine :: Bool -> Int -> Int -> IO Int\nfindLine flgSwap n x = go 0 n\n where\n swp = swapWith flgSwap\n go !lty !geqy\n | geqy - lty <= 1 = return geqy\n | otherwise = do\n b <- (testOdd `on` swp) (x,lty+1) (x,midy)\n if b then go lty midy else go midy geqy\n where\n midy = lty + shiftR (geqy - lty) 1\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\ntest :: (Int,Int) -> (Int,Int) -> IO Int\ntest (x1,y1) (x2,y2) = do\n putStrLn $ unwords $ (\"?\":) $ map show $ [x1,y1,x2,y2]\n hFlush stdout\n reply <- readInt <$> getLine\n when (reply < 0) $ exitFailure\n return reply\n\ntestOdd :: (Int, Int) -> (Int, Int) -> IO Bool\ntestOdd p1 p2 = odd <$> test p1 p2\n\nswapWith False = id\nswapWith True = swap\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n ((x1,y1),(x2,y2)) <- query n\n putStrLn $ unwords $ (\"!\":) $ map show $ [x1,y1,x2,y2]\n\nquery :: Int -> IO ((Int,Int),(Int,Int))\nquery n = do\n res_lr <- findLRUD False n\n res_ud <- findLRUD True n\n case (res_lr,res_ud) of\n (Nothing,Nothing) -> exitFailure\n (Just (x1,x2),Nothing) -> do\n y <- findLine False n x1\n return ((x1,y),(x2,y))\n (Nothing, Just (y1,y2)) -> do\n x <- findLine True n y1\n return ((x,y1),(x,y2))\n (Just (x1,x2), Just (y1,y2)) -> do\n b <- testOdd (x1,y1) (x1,y1)\n return $ if b then ((x1,y1),(x2,y2)) else ((x1,y2),(x2,y1))\n\nfindLRUD :: Bool -> Int -> IO (Maybe (Int,Int))\nfindLRUD xyflg n = go1 1\n where\n tst x = (testOdd `on` swapWith xyflg) (x,1) (x,n)\n go1 x\n | x >= n = return Nothing\n | otherwise = do\n b <- tst x\n if not b then go1 (x+1) else Just . (x,) <$> go2 (x+1)\n go2 x\n | x >= n = return n\n | otherwise = do\n b <- tst x\n if not b then go2 (x+1) else return x \n \n\n\nfindLine :: Bool -> Int -> Int -> IO Int\nfindLine flgSwap n x = go 0 n\n where\n swp = swapWith flgSwap\n go !lty !geqy\n | geqy - lty <= 1 = return geqy\n | otherwise = do\n b <- (testOdd `on` swp) (x,lty+1) (x,midy)\n if b then go lty midy else go midy geqy\n where\n midy = lty + shiftR (geqy - lty) 1\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\ntest :: (Int,Int) -> (Int,Int) -> IO Int\ntest (x1,y1) (x2,y2) = do\n putStrLn $ unwords $ (\"?\":) $ map show $ [x1,y1,x2,y2]\n hFlush stdout\n reply <- readInt <$> getLine\n when (reply < 0) $ exitFailure\n return reply\n\ntestOdd :: (Int, Int) -> (Int, Int) -> IO Bool\ntestOdd p1 p2 = odd <$> test p1 p2\n\nswapWith False = id\nswapWith True = swap\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n ((x1,y1),(x2,y2)) <- query n\n putStrLn $ unwords $ (\"!\":) $ map show $ [x1,y1,x2,y2]\n\nquery :: Int -> IO ((Int,Int),(Int,Int))\nquery n = do\n res_lr <- findLRUD False n\n res_ud <- findLRUD True n\n case (res_lr,res_ud) of\n (Nothing,Nothing) -> exitFailure\n (Just (x1,x2),Nothing) -> do\n y <- findLine False n x1\n return ((x1,y),(x2,y))\n (Nothing, Just (y1,y2)) -> do\n x <- findLine True n y1\n return ((x,y1),(x,y2))\n (Just (x1,x2), Just (y1,y2)) -> do\n b <- testOdd (x1,y1) (x1,y1)\n return $ if b then ((x1,y1),(x2,y2)) else ((x1,y2),(x2,y1))\n\nfindLRUD :: Bool -> Int -> IO (Maybe (Int,Int))\nfindLRUD xyflg n = go1 2\n where\n tst x = (test `on` swapWith xyflg) (x,1) (x,n)\n go1 x = case compare x n of\n GT -> return Nothing\n EQ -> do\n b <- odd <$> tst n\n return $ if b then Just (n-1,n) else Nothing\n LT -> do\n b <- tst x\n if | testBit b 0 -> do\n b <- tst (x+1)\n if | testBit b 0 -> return $ Just (x,x+1)\n | testBit b 1 -> Just . (x,) <$> go2 (x+3)\n | otherwise -> return $ Just (x-1,x)\n | testBit b 1 -> Just . (x-1,) <$> go2 (x+2)\n | otherwise -> go1 (x+2)\n go2 x = case compare x (n+1) of\n GT -> return n\n EQ -> do\n b <- odd <$> tst n\n return $ if b then n else n-1\n LT -> do\n b <- tst x\n if | testBit b 0 -> return x\n | testBit b 1 -> go2 (x+2)\n | otherwise -> return (x-1)\n \n\n\nfindLine :: Bool -> Int -> Int -> IO Int\nfindLine flgSwap n x = go 0 n\n where\n swp = swapWith flgSwap\n go !lty !geqy\n | geqy - lty <= 1 = return geqy\n | otherwise = do\n b <- (testOdd `on` swp) (x,lty+1) (x,midy)\n if b then go lty midy else go midy geqy\n where\n midy = lty + shiftR (geqy - lty) 1\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "src_uid": "5774f74d9f6dc9ef79182515f667eb23"} {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nreadInt :: String -> Int\nreadInt = read\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n putStr . unlines . map show =<<\n replicateM\n t\n (do [n, x] <- getInts\n solve 1 x . S.toAscList . S.fromList <$> getInts)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve v x [] = v + x - 1\nsolve v x (l:ls)\n | v == l = solve (v + 1) x ls\n | x > 0 = solve (v + 1) (x - 1) (l : ls)\n | otherwise = v - 1\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Data.List (sort)\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([_,x]:a:ps) = ((get x 1) . uniq . sort) a : process ps\n\nget :: Int -> Int -> [Int] -> Int\nget n _ [] = n\nget n r (y:ys)\n | y == r = 1 + get n (r + 1) ys\n | n >= 1 = 1 + get (n - 1) (r + 1) (y:ys)\n | otherwise = 0\n\nuniq :: (Eq a) => [a] -> [a]\nuniq [] = []\nuniq [x] = [x]\nuniq (x:x':xs)\n | x == x' = ys\n | otherwise = x : ys\n where ys = uniq (x':xs)"}], "negative_code": [], "src_uid": "e5fac4a1f3a724234990fe758debc33f"} {"source_code": "\nimport IO\nimport List\nimport Monad\n\nsolve :: Int -> Int -> [Int] -> (Int, [Int])\nsolve n k xs = (min, take k . map fst . filter ((min <=) . snd) . zip [1..] $ xs)\n where\n xs' = reverse (sort xs)\n min = xs' !! (k - 1)\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n [n, k] <- liftM (map read . words) (hGetLine hInput)\n xs <- liftM (map read . words) (hGetLine hInput)\n let (min, (y:ys)) = solve n k xs\n hPrint hOutput min\n hPutStr hOutput (show y) >> mapM_ (hPutStr hOutput . (\" \" ++) . show) ys\n\n hClose hInput\n hClose hOutput\n", "positive_code": [{"source_code": "import Data.List\n\nsolve :: Int -> [Int] -> (Int, [Int])\nsolve k xs = (minimum $ map fst answer,\n map snd answer)\n where reversedFst (x, _) (y, _) = compare y x\n answer = take k $ sortBy reversedFst $ zip xs [1 .. ]\n\nmain = do (k:xs) <- fmap (tail . map read . words) $ readFile \"input.txt\"\n let (mn, bs) = solve k xs\n writeFile \"output.txt\" $ unlines [show mn, unwords $ map show bs]\n "}, {"source_code": "import Data.List\nimport Data.Ord\n\nmain = readFile\"input.txt\">>=writeFile\"output.txt\".solve.map read.words\n\nsolve (_:k:xs) = case take k.sortBy(flip (comparing snd))$zip[1..]xs of\n ans -> shows (minimum $map snd ans) \"\\n\" ++ unwords(map (show.fst) ans)"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Ord\n\nmain = readFile\"input.txt\">>=writeFile\"output.txt\".unwords.map show.solve.map read.words\n\nsolve (_:k:xs) = map fst.take k.sortBy(flip (comparing snd))$zip[1..]xs"}], "src_uid": "a585045a9a6f62bfe1c0618c2ee02f48"} {"source_code": "main :: IO()\nmain = do\n n <- readLn :: IO Int\n let p = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]\n ans = concat $ map (mult n) (takeWhile (<=n) p)\n l = length ans\n print l\n mapM_ (\\x -> putStr ((show x)++\" \")) ans\n\nmult l b = takeWhile (<=l) $ iterate (b*) b", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (forM_, when)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.Unboxed (assocs)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, newArray, readArray, writeArray)\n\nsieve :: Int -> [Int]\nsieve n = map fst . filter snd . assocs $ runSTUArray $ do\n arr <- newArray (2, n) True :: ST s (STUArray s Int Bool)\n forM_ [2..n] $ \\i -> do\n b <- readArray arr i -- if i is prime\n when b $ forM_ [i*i, i*i + i .. n] $ \\i -> writeArray arr i False\n return arr\n\nsolve :: Int -> [Int]\nsolve n = concatMap run $ sieve n\n where run i = takeWhile (< n + 1) $ iterate (*i) i\n\nmain = do\n xs <- solve . read <$> getLine\n print $ length xs\n putStrLn . unwords $ map show xs\n"}, {"source_code": "main = readLn >>= putStr . out . solve\nout a = show (length a) ++ '\\n' : (unwords $ map show a)\n\nprime n = let nums = takeWhile (\\x -> x * x <= n) [2..] in and $ map (\\x -> n `rem` x /= 0) nums\n\nsolve n = concat $ map (\\x -> takeWhile (<= n) $ iterate (x*) x) primes\n where primes = filter prime [2..n]"}, {"source_code": "main = readLn >>= putStr . out . solve\nout a = show (length a) ++ '\\n' : (unwords $ map show a)\n\nprime n = let nums = takeWhile ((<= n) . (^2)) [2..] in and $ map ((/=0) . (rem n)) nums\n\nsolve n = concat $ map (\\x -> takeWhile (<= n) $ iterate (x*) x) primes\n where primes = filter prime [2..n]"}, {"source_code": "import Text.Printf\n\nsieve :: [Int]\nsieve = sieve [2..]\n where\n sieve :: [Int] -> [Int]\n sieve (x:xs) = x:sieve [y | y <- xs, y `mod` x /= 0]\n\nguesses :: Int -> [Int]\nguesses n =\n let\n primes = takeWhile (<= n) sieve\n in\n concat [ primePowersUpToN x n x [] | x <- primes]\n where\n primePowersUpToN :: Int -> Int -> Int -> [Int] -> [Int]\n primePowersUpToN p n acc res\n | acc > n = res\n | otherwise = primePowersUpToN p n (acc * p) (acc:res)\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n = read s :: Int\n let res = guesses n\n print $ length res\n mapM_ (printf \"%d \") res\n"}, {"source_code": "prime 2 = [2] \nprime n | and (map (\\x -> n `rem` x /= 0) pre) = pre++[n]\n | otherwise = pre\n where pre = prime (n-1)\nisQ n (p:prime) f | n < p = True\n | n `rem` p == 0 = if (f == 0 || f == p) then isQ (n `div` p) (p:prime) p else False\n | f /= 0 = False\n | otherwise = isQ n prime f\nmain = do\n w0 <- getLine\n let n = (read w0)::Int\n let p = prime 1000\n let kai = map show $ takeWhile (<=n) $ map fst $ filter (id.snd) $ zip [2..1000] (map(\\n -> isQ n p 0) [2..1000])\n putStrLn $ show $ length kai\n putStrLn $ unwords kai\n \n"}, {"source_code": "import Data.List\nmain=interact $ solve. read\nsolve::Int->String\nsolve n = (show $ length nums) ++ \"\\n\" ++ intercalate \" \" nums\n where primes = 2 : filter isPrime [3..]\n isPrime x = all ((/=0) . (mod x)) $ takeWhile ((<=x).(^2)) primes\n ps=takeWhile (<=n) primes\n f acc k x = if k>n then acc else f (k:acc) (x*k) x\n nums = map show . concat $ map (\\x->f [] x x) ps"}], "negative_code": [{"source_code": "import Data.List\nmain=interact $ solve. read\nsolve::Int->String\nsolve n = (show $ length nums) ++ \"\\n\" ++ intercalate \" \" nums\n where primes = 2 : filter isPrime [3..]\n isPrime x = all ((/=0) . (mod x)) $ takeWhile ((<=x).(^2)) primes\n ps=takeWhile (<=n) primes\n f acc x = if x>=n then acc else f (x:acc) (x*x)\n nums = map show . concat $ map (f []) ps"}, {"source_code": "import Data.List\nmain=interact $ solve. read\nsolve::Int->String\nsolve n = (show $ length nums) ++ \"\\n\" ++ intercalate \" \" nums\n where primes = 2 : filter isPrime [3..]\n isPrime x = all ((/=0) . (mod x)) $ takeWhile ((<=x).(^2)) primes\n ps=takeWhile (<=n) primes\n f acc x = if x>n then acc else f (x:acc) (x*x)\n nums = map show . concat $ map (f []) ps"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (forM_, when)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array.Unboxed (assocs)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, newArray, readArray, writeArray)\n\nsieve :: Int -> [Int]\nsieve n = map fst . filter snd . assocs $ runSTUArray $ do\n arr <- newArray (2, n) True :: ST s (STUArray s Int Bool)\n forM_ [2..n] $ \\i -> do\n b <- readArray arr i -- if i is prime\n when b $ forM_ [i*i, i*i + i .. n] $ \\i -> writeArray arr i False\n return arr\n\nsolve :: Int -> [Int]\nsolve n = concatMap run $ sieve n\n where run i = takeWhile (< n + 1) $ iterate (*i) i\n\nmain = getLine >>= putStrLn . unwords . map show . solve . read\n"}, {"source_code": "prime 2 = [2] \nprime n | and (map (\\x -> n `rem` x /= 0) pre) = pre++[n]\n | otherwise = pre\n where pre = prime (n-1)\nisQ n (p:prime) f | n < p = True\n | n `rem` p == 0 = if (f == 0 || f == p) then isQ (n `div` p) (p:prime) p else False\n | f /= 0 = False\n | otherwise = isQ n prime f\nmain = do\n w0 <- getLine\n let n = (read w0)::Int\n let p = prime 1000\n putStrLn $ unwords $ map show $ takeWhile (<=n) $ map fst $ filter (id.snd) $ zip [2..1000] (map(\\n -> isQ n p 0) [2..1000])\n \n"}], "src_uid": "7f61b1d0e8294db74d33a6b6696989ad"} {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:t:as) = go 0 0 0 as as\n where go a k s xxs@(x:xs) (y:ys) | s + y <= t = go (max a (k + 1)) (k + 1) (s + y) xxs ys\n | otherwise = go a k (s + y - x) xs ys\n go a _ _ _ _ = a\nsolve _ = undefined\n", "positive_code": [{"source_code": "import Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: Int -> [Int] -> Int\nsolve t as = solve' (r-l) s (l, r)\n where\n array = listArray (1, n) as\n n = length as\n l = 1\n r = (+1) $ length $ tail $ takeWhile (<= t) $ scanl (+) 0 as\n s = sum $ take (r-1) as\n -- inv: sum [al .. ar-1] <= t \n -- && sum [al..ar] > t\n solve' ans s (l, r)\n | r > n = ans\n | otherwise = solve' ans' s' (l', r')\n where\n l' = l + 1\n (r', s') = findR (s - array ! l) r\n ans' = max ans (r'-l')\n findR s r\n | r > n = (r, s)\n | s' > t = (r, s)\n | otherwise = findR s' (r+1)\n where\n s' = s + array ! r\n\nmain :: IO ()\nmain = do\n [n, t] <- reads\n as <- reads\n print $ solve t as\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve (m:t:as) = maximum $ 0 : go as as 0 0 where\n go ns@(n:ns') ps@(p:ps') r b | b > m = go ns' ps (r-p) (b-1)\n | r + n > t = b : go ns ps' (r-p) (b-1)\n | otherwise = b : go ns' ps (r+n) (b+1)\n go [] _ _ b = [b]\n go _ [] _ _ = []\ntest = [\n solve [4,5,3,1,2,1] == 3\n ]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,t] <- map read.words <$> getLine :: IO [Int]\n xs <- map readInt.B.words <$> B.getLine\n print $ solve t xs\n\ndata Queue = Q !Int !Int [Int] [Int]\n\nsolve t xs = maximum.snd $ mapAccumL enq (Q 0 0 [] []) xs\n where\n enq que@(Q cnt acc fs rs) x\n | x+acc<=t = (Q (cnt+1) (acc+x) fs (x:rs), cnt+1)\n | cnt == 0 = (Q 0 0 [] [], 0)\n | otherwise = enq (deq que) x\n deq (Q cnt acc (f:fs) rs) = Q (cnt-1) (acc-f) fs rs\n deq (Q cnt acc [] rs) = deq $ Q cnt acc (reverse rs) []\n"}, {"source_code": "import Data.Maybe (fromMaybe)\nimport Data.Sequence (Seq(..), ViewL(..), viewl, (|>), (<|) )\n\nimport Data.List (foldl')\nimport Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n (_:t:_) <- map read . words <$> getLine\n bookMins <- map read . words <$> getLine\n print $ maximum $ analyzeNextBook (t, Empty, []) bookMins\n\n\n where\n analyzeNextBook :: (Int, Seq Int, [Int]) -> [Int] -> [Int]\n analyzeNextBook (_, _, readBookCount) [] = readBookCount\n analyzeNextBook (minsLeft, readMins, readBookCount) (nextBookMins: unprocessed) =\n let newLeft = minsLeft - nextBookMins\n currBookCount = fromMaybe 0 $ safeHead readBookCount\n in if newLeft >= 0\n -- can read next one\n then analyzeNextBook (newLeft, readMins |> nextBookMins, currBookCount + 1 : readBookCount) unprocessed\n -- no mins left for next one\n else case viewl readMins of\n -- but none read ... so this book can't be read, skip it\n EmptyL -> analyzeNextBook (minsLeft, readMins, currBookCount : readBookCount) unprocessed\n -- try skipping first read and get back the minutes\n (firstMins :< restMins) -> analyzeNextBook (firstMins + minsLeft, restMins, currBookCount - 1 : readBookCount) (nextBookMins : unprocessed)\n\n safeHead [] = Nothing\n safeHead (x:xs) = Just x\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain = B.getContents >>= putStr . show . solve . map readInt . B.words\n\nsolve (n:k:a) = maximum $ map fst $ solve' a a (0, 0)\n where\n solve' [] _ x = [(0, 0)]\n solve' (a : as) (b : bs) (0, 0)\n | a > k = solve' as bs (0, 0)\n solve' (a : as) (b : bs) (c, s)\n | s + a > k = (c - 1, s - b) : solve' (a : as) bs (c - 1, s - b)\n | otherwise = (c + 1, s + a) : solve' as (b : bs) (c + 1, s + a)"}, {"source_code": "import Data.Sequence as Q\n\nreadInts :: IO [Int]\nreadInts = do\n line <- getLine\n return $ map read $ words line\n\nsolve t books = go 0 0 [] books\n where\n go len sum buf [] = len\n go len sum buf rem@(b:bs) | sum+b <= t = go (len+1) (sum+b) (buf++[b]) bs\n | len > 0 = max len $ go (len-1) (sum-(head buf)) (tail buf) rem\n | otherwise = max len $ go len sum buf bs\n\nsolve2 t books = go 0 empty books\n where\n go sum buf [] = Q.length buf\n go sum buf rem@(b:bs) | sum+b <= t = go (sum+b) (b<|buf) bs\n | otherwise = case viewr buf of\n EmptyR -> go sum buf bs\n s :> r -> max (Q.length buf) $ go (sum-r) s rem\nmain :: IO ()\nmain = do\n a <- readInts\n books <- readInts\n let (n, t) = (a!!0, a!!1)\n putStrLn $ show $ solve2 t books\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain = putStrLn . show . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (n : t : as) = maximum $ map fst $ f as as (0, 0)\n where\n f [] _ x = [(0, 0)]\n f (a : as) (b : bs) (0, 0)\n | a > t = f as bs (0, 0)\n f (a : as) (b : bs) (c, s)\n | s + a > t = (c - 1, s - b) : f (a : as) bs (c - 1, s - b)\n | otherwise = (c + 1, s + a) : f as (b : bs) (c + 1, s + a)\n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> Int -> Int\nsolve as t = length $ takeWhile (<= t) $ tail $ scanl (+) 0 $ reverse as\n\nmain :: IO ()\nmain = do\n [n, t] <- reads\n as <- reads\n print $ solve as t\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve (m:t:as) = maximum $ 0 : go cas cas 0 0 where\n cas = as ++ as\n go ns@(n:ns') ps@(p:ps') r b | b > m = go ns' ps (r-p) (b-1)\n | r + n > t = b : go ns ps' (r-p) (b-1)\n | otherwise = b : go ns' ps (r+n) (b+1)\n go [] _ _ _ = []\n go _ [] _ _ = []\n"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve (m:t:as) = maximum $ 0 : go as as 0 0 where\n go ns@(n:ns') ps@(p:ps') r b | b > m = go ns' ps (r-p) (b-1)\n | r + n > t = b : go ns ps' (r-p) (b-1)\n | otherwise = b : go ns' ps (r+n) (b+1)\n go [] _ _ _ = []\n go _ [] _ _ = []\n"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve (m:t:as) = maximum $ 0 : go cas cas 0 0 where\n cas = as ++ as\n go ns@(n:ns') ps@(p:ps') r b | b > m = go ns' ps (r-p) (b-1)\n | r + n > t = b : go ns ps' (r-p) (b-1)\n | otherwise = go ns' ps (r+n) (b+1)\n go [] _ _ _ = []\n go _ [] _ _ = []\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,t] <- map read.words <$> getLine :: IO [Int]\n xs <- map readInt.B.words <$> B.getLine\n print.length.dropWhile (t<) $ scanr1 (+) xs"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain = B.getContents >>= putStr . solve . map readInt . B.words\n\nsolve (n:k:a) = show . foldl max 0 $ zipWith delta z (inits z)\n where \n z = tail . scanl (+) 0 $ a\n delta cur prevs = binary (cur-k) prevs\n binary limit origin = length . dropWhile ( Int -> Int -> Int -> UArray Int Int -> UArray Int Int\nf k t0 t1 d1 farr = listArray (0, k) [ f' i | i <- [0..k] ] where\n donotignore n = max 0 ((farr ! n) - (t1 - t0)) + d1\n doignore n = (farr ! (n-1)) - (t1 - t0)\n\n f' 0 = donotignore 0\n f' n = min (doignore n) (donotignore n)\n\nf0 k = listArray (0, k) $ repeat 0\n\nsolve k farr t0 [] = max ((86401 - t0) - (farr ! k)) 0\nsolve k farr t0 ((t1, d1):xs) = max ((t1 - t0) - (farr ! k))\n (solve k (f k t0 t1 d1 farr) t1 xs)\n\nreadInt = (\\(Just (x,_)) -> x) . BS.readInt\n\nmain = do\n [n, k] <- liftM (map readInt . BS.words) BS.getLine\n list <- replicateM n $ do\n [t, d] <- liftM (map readInt . BS.words) BS.getLine\n return (t, d)\n\n print $ solve k (f0 k) 1 list\n", "positive_code": [{"source_code": "import Debug.Trace\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsolve_cur_row :: Int -> Int -> [Int] -> (Int, [Int])\nsolve_cur_row t d [prev0]\n | t <= prev0 = (0, [prev0+d])\n | otherwise = (t-prev0-1, [t+d-1])\nsolve_cur_row t d (prev0:prev1:prev_row) =\n let\n cur0' = if t <= prev0 then prev0+d else t+d-1\n cur0 = min cur0' prev1\n (ans_rest, cur_rest) = solve_cur_row t d (prev1:prev_row)\n ans = if t <= prev0 then ans_rest else max ans_rest t-prev0-1\n in\n (ans, cur0:cur_rest)\n\nsolve :: [(Int, Int)] -> [Int] -> Int\n{- solve x prev_row | trace(\"x: \" ++ show x ++ \"prev_row: \" ++ show prev_row) False = undefined -}\nsolve [] prev_row = 86400 - minimum prev_row\n\nsolve (x:xs) prev_row =\n let\n (ans', cur_row) = solve_cur_row (fst x) (snd x) prev_row\n in\n max ans' (solve xs cur_row)\n\nstart n k list =\n print (solve list (take (k+1) [0,0..]))\n\nmain =\n do all <- BS.getContents\n let ((n, k), r1) = readPair all -- read the first two integers\n let list = readMany readPair r1 n\n start n k list\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readPair s = ((a, b), r2)\n where\n Just (a, r1) = readInt s\n Just (b, r2) = readInt r1\n readMany _ _ 0 = []\n readMany readf s n = let\n (x, r) = readf s\n in\n x : readMany readf r (n-1)\n"}, {"source_code": "{-\n -\n - Yannis Chatzimichos\n - A.M.: 03108610\n -\n - http://codeforces.com/problemset/problem/158/E\n -\n -}\n\nimport Debug.Trace\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsolve_cur_row :: Int -> Int -> [Int] -> (Int, [Int])\nsolve_cur_row t d [prev0]\n | t <= prev0 = (0, [prev0+d])\n | otherwise = (t-prev0-1, [t+d-1])\nsolve_cur_row t d (prev0:prev1:prev_row) =\n let\n cur0' = if t <= prev0 then prev0+d else t+d-1\n cur0 = min cur0' prev1\n (ans_rest, cur_rest) = solve_cur_row t d (prev1:prev_row)\n ans = if t <= prev0 then ans_rest else max ans_rest t-prev0-1\n in\n (ans, cur0:cur_rest)\n\nsolve :: [(Int, Int)] -> [Int] -> Int\n{- solve x prev_row | trace(\"x: \" ++ show x ++ \"prev_row: \" ++ show prev_row) False = undefined -}\nsolve [] prev_row = 86400 - minimum prev_row\n\nsolve (x:xs) prev_row =\n let\n (ans', cur_row) = solve_cur_row (fst x) (snd x) prev_row\n in\n max ans' (solve xs cur_row)\n\nstart n k list =\n print (solve list (take (k+1) [0,0..]))\n\nmain =\n do all <- BS.getContents\n let ((n, k), r1) = readPair all -- read the first two integers\n let list = readMany readPair r1 n\n start n k list\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readPair s = ((a, b), r2)\n where\n Just (a, r1) = readInt s\n Just (b, r2) = readInt r1\n readMany _ _ 0 = []\n readMany readf s n = let\n (x, r) = readf s\n in\n x : readMany readf r (n-1)\n"}], "negative_code": [], "src_uid": "936f883476039e9e5b698a1d45cbe61a"} {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n", "positive_code": [{"source_code": "gao [a, b]\n\t| a > b\t\t= gao [b, a]\n\t| a == 1\t= a\n\t| a == b\t= a\n\t| otherwise\t= gao [a, b - (b - 2) `div` (a - 1) * (a - 1)]\nmain = do getLine >>= print . gao . map read . words\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\n\nsolve :: Int -> Int -> Int\nsolve n m = gcd (n - 1) (m - 1) + 1\n\nmain = do\n [n, m] <- map read . words <$> getLine\n print $ solve n m\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n"}, {"source_code": "z[a,b]=gcd a b+1\nmain=interact$show.z.map(pred.read).words\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\n\nsolve :: Int -> Int -> Int\nsolve n m\n | n == m = fromIntegral n\n | otherwise = simulate (0, 0) (1, 1) (n + m)\n where\n simulate (x, y) (dx, dy) answer\n | dx /= dx' && dy /= dy' = answer'\n | otherwise = simulate (x', y') (dx', dy') answer'\n where\n xsteps = if dx < 0 then x else n - 1 - x\n ysteps = if dy < 0 then y else m - 1 - y\n steps = xsteps `min` ysteps\n x' = x + dx * steps\n y' = y + dy * steps\n dx' = if x' + dx >= n || x' + dx < 0 then -dx else dx\n dy' = if y' + dy >= m || y' + dy < 0 then -dy else dy\n answer' = answer `min` (x' + y')\n\nmain = do\n [n, m] <- map read . words <$> getLine\n print $ solve n m\n"}], "src_uid": "05f251de93536024c05fbd77ed01b70b"} {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts, RankNTypes, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, mapM, liftM2)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.ST.Safe (readArray, writeArray, newArray_, STArray, newArray, STUArray)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\n-- repeatM :: (a -> m a) -> Int -> a -> m a\n-- repeatM f 0 a = a\n-- repeatM f n a = do\n-- a' <- f a\n\nmain = do\n [n, m, q] <- readInts\n as <- replicateM n readInts\n qs <- replicateM q readInts\n\n let\n as' = listArray ((1, 1), (n, m)) $ concat as :: UArray (Int, Int) Int\n\n encode x y = x*(m+2) + y\n decode z = z `divMod` (m+2)\n\n xys = runST $ do\n ds <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray ds (encode x y) (encode (x+1) y)\n\n rs <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray rs (encode x y) (encode x (y+1))\n\n let\n {-# INLINE down #-}\n down z = readArray ds z\n {-# INLINE right #-}\n right z = readArray rs z\n\n update [a, b, c, d, h, w] = do\n p <- find (a-1) (b-1)\n q <- find (c-1) (d-1)\n\n followd (p, q) >>= followr\n followr (p, q) >>= followd\n where\n followd = follow True h\n followr = follow False w\n\n follow b c (p, q) = f' c p q\n where\n f' 0 p q = return (p, q)\n f' c p q = do\n let\n -- f :: Int -> ST s Int\n f p = if b then readArray ds p else readArray rs p\n\n p' <- f p\n q' <- f q\n\n let\n swap :: STUArray s Int Int -> ST s ()\n swap a = readArray a p' >>= \\t -> readArray a q' >>= writeArray a p' >> writeArray a q' t\n\n if b then swap rs else swap ds\n\n f' (c-1) p' q'\n\n find x y = downs x 0 >>= rights y\n where\n rights 0 p = return p\n rights n p = right p >>= rights (n-1)\n\n downs 0 p = return p\n downs n p = down p >>= downs (n-1)\n\n downs 0 p = return []\n downs n p = do\n p' <- down p\n (p':) <$> downs (n-1) p'\n\n rights 0 p = return []\n rights n p = do\n p' <- right p\n (p':) <$> rights (n-1) p'\n\n mapM_ update qs\n\n ds <- downs n 0\n mapM (rights m) ds\n\n putStr $ unlines $ map (unwords . map (show . (as'!) . decode)) xys\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, mapM, liftM2)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.ST.Safe (readArray, writeArray, newArray_, STUArray, newArray, STUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char (isSpace)\nimport Data.List (unfoldr)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n{-# INLINEABLE iterateNM' #-}\niterateNM' :: Monad m => Int -> (a -> m a) -> a -> m a\niterateNM' n f a = loop n a\n where\n loop 0 a = return a\n loop n a = f a >>= loop (n-1)\n\n{-# INLINEABLE iterateNM #-}\niterateNM n f a = loop n a\n where\n loop 0 a = return []\n loop n a = f a >>= \\a' -> fmap (a':) (loop (n-1) a')\n\nmain = do\n [n, m, q] <- readInts\n as <- replicateM n readInts\n qs <- replicateM q readInts\n\n let\n as' = listArray ((1, 1), (n, m)) $ concat as :: UArray (Int, Int) Int\n\n encode x y = x*(m+2) + y\n decode z = z `divMod` (m+2)\n\n xys = runST $ do\n ds <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray ds (encode x y) (encode (x+1) y)\n\n rs <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray rs (encode x y) (encode x (y+1))\n\n let\n {-# INLINE down #-}\n down z = readArray ds z\n {-# INLINE right #-}\n right z = readArray rs z\n\n update [x1, y1, x2, y2, h, w] = do\n p <- find x1 y1\n q <- find x2 y2\n\n (uncurry rights) =<< downs p q\n (uncurry downs) =<< rights p q\n where\n find x y = iterateNM' (y-1) right 0 >>= iterateNM' (x-1) down\n\n swap :: STUArray s Int Int -> Int -> Int -> ST s ()\n swap a p q = readArray a p >>= \\t -> readArray a q >>= writeArray a p >> writeArray a q t\n\n downs p q = loop h p q\n where\n loop 0 p q = return (p, q)\n loop n p q = do\n p' <- down p\n q' <- down q\n swap rs p' q'\n loop (n-1) p' q'\n\n rights p q = loop w p q\n where\n loop 0 p q = return (p, q)\n loop n p q = do\n p' <- right p\n q' <- right q\n swap ds p' q'\n loop (n-1) p' q'\n\n forM_ qs update\n\n ds <- iterateNM n down 0\n mapM (iterateNM m right) ds\n\n putStr $ unlines $ map (unwords . map (show . (as'!) . decode)) xys\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts, RankNTypes, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, mapM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.ST.Safe (readArray, writeArray, newArray_, STArray, newArray, STArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (unfoldr)\nimport Data.Char (isSpace)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, q] <- readInts\n as <- replicateM n readInts\n qs <- replicateM q readInts\n\n let\n as' = listArray ((1, 1), (n, m)) $ concat as :: UArray (Int, Int) Int\n\n encode x y = x*(m+2) + y\n decode z = z `divMod` (m+2)\n\n xys = runST $ do\n ds <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray ds (encode x y) (encode (x+1) y)\n\n rs <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray rs (encode x y) (encode x (y+1))\n\n let\n {-# INLINE down #-}\n down z = readArray ds z\n {-# INLINE right #-}\n right z = readArray rs z\n\n update [a, b, c, d, h, w] = do\n p <- find (a-1) (b-1)\n q <- find (c-1) (d-1)\n\n followd (p, q) >>= followr\n followr (p, q) >>= followd\n where\n followd = follow True h\n followr = follow False w\n\n follow b c (p, q) = f' c p q\n where\n f' 0 p q = return (p, q)\n f' c p q = do\n let f = if b then down else right\n\n p' <- f p\n q' <- f q\n\n let\n swap :: STArray s Int Int -> ST s ()\n swap a = readArray a p' >>= \\t -> readArray a q' >>= writeArray a p' >> writeArray a q' t\n\n if b then swap rs else swap ds\n\n f' (c-1) p' q'\n\n find x y = downs x 0 >>= rights y\n where\n rights 0 p = return p\n rights n p = right p >>= rights (n-1)\n\n downs 0 p = return p\n downs n p = down p >>= downs (n-1)\n\n downs 0 p = return []\n downs n p = do\n p' <- down p\n (p':) <$> downs (n-1) p'\n\n rights 0 p = return []\n rights n p = do\n p' <- right p\n (p':) <$> rights (n-1) p'\n\n mapM_ update qs\n\n ds <- downs n 0\n mapM (rights m) ds\n\n putStr $ unlines $ map (unwords . map (show . (as'!) . decode)) xys\n"}, {"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts, RankNTypes, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, mapM, liftM2)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.ST.Safe (readArray, writeArray, newArray_, STUArray, newArray, STUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char (isSpace)\nimport Data.List (unfoldr)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n{-# INLINEABLE iterateNM' #-}\niterateNM' :: Monad m => Int -> (a -> m a) -> a -> m a\niterateNM' n f a = loop n a\n where\n loop 0 a = return a\n loop n a = f a >>= loop (n-1)\n\n{-# INLINEABLE iterateNM #-}\niterateNM n f a = loop n a\n where\n loop 0 a = return []\n loop n a = f a >>= \\a' -> fmap (a':) (loop (n-1) a')\n\nmain = do\n [n, m, q] <- readInts\n as <- replicateM n readInts\n qs <- replicateM q readInts\n\n let\n as' = listArray ((1, 1), (n, m)) $ concat as :: UArray (Int, Int) Int\n\n encode x y = x*(m+2) + y\n decode z = z `divMod` (m+2)\n\n xys = runST $ do\n ds <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray ds (encode x y) (encode (x+1) y)\n\n rs <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray rs (encode x y) (encode x (y+1))\n\n let\n {-# INLINE down #-}\n down z = readArray ds z\n {-# INLINE right #-}\n right z = readArray rs z\n\n update [x1, y1, x2, y2, h, w] = do\n p <- find x1 y1\n q <- find x2 y2\n\n downs (p, q) >>= rights\n rights (p, q) >>= downs\n where\n find x y = iterateNM' (y-1) right 0 >>= iterateNM' (x-1) down\n\n swap :: STUArray s Int Int -> Int -> Int -> ST s ()\n swap a p q = readArray a p >>= \\t -> readArray a q >>= writeArray a p >> writeArray a q t\n\n downs = iterateNM' h f\n where\n f (p, q) = do\n p' <- down p\n q' <- down q\n swap rs p' q'\n return (p', q')\n\n rights = iterateNM' w f\n where\n f (p, q) = do\n p' <- right p\n q' <- right q\n swap ds p' q'\n return (p', q')\n\n forM_ qs update\n\n ds <- iterateNM n down 0\n mapM (iterateNM m right) ds\n\n putStr $ unlines $ map (unwords . map (show . (as'!) . decode)) xys\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns, FlexibleContexts, RankNTypes, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, mapM, liftM2)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.ST.Safe (readArray, writeArray, newArray_, STUArray, newArray, STUArray)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (unfoldr)\nimport Data.Char (isSpace)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n{-# INLINEABLE iterateNM' #-}\niterateNM' :: Monad m => Int -> (a -> m a) -> a -> m a\niterateNM' n f a = loop n a\n where\n loop 0 a = return a\n loop n a = f a >>= loop (n-1)\n\n{-# INLINEABLE iterateNM #-}\niterateNM n f a = loop n a\n where\n loop 0 a = return []\n loop n a = f a >>= \\a' -> fmap (a':) (loop (n-1) a')\n\nmain = do\n [n, m, q] <- readInts\n as <- replicateM n readInts\n qs <- replicateM q readInts\n\n let\n as' = listArray ((1, 1), (n, m)) $ concat as :: UArray (Int, Int) Int\n\n encode x y = x*(m+2) + y\n decode z = z `divMod` (m+2)\n\n xys = runST $ do\n ds <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray ds (encode x y) (encode (x+1) y)\n\n rs <- newArray_ (0, encode (n+1) (m+1)) :: ST s (STUArray s Int Int)\n forM_ [0..n] $ \\x -> forM_ [0..m] $ \\y -> writeArray rs (encode x y) (encode x (y+1))\n\n let\n {-# INLINE down #-}\n down z = readArray ds z\n {-# INLINE right #-}\n right z = readArray rs z\n\n update [a, b, c, d, h, w] = do\n p <- find a b\n q <- find c d\n\n iterateNM' h down' (p, q) >>= iterateNM' w right'\n iterateNM' w right' (p, q) >>= iterateNM' h down'\n where\n find x y = iterateNM' (x-1) right 0 >>= iterateNM' (y-1) down\n\n swap :: STUArray s Int Int -> Int -> Int -> ST s ()\n swap a p q = readArray a p >>= \\t -> readArray a q >>= writeArray a p >> writeArray a q t\n\n down' (p, q) = do\n p' <- down p\n q' <- down q\n swap ds p' q'\n return (p', q')\n\n right' (p, q) = do\n p' <- right p\n q' <- right q\n swap rs p' q'\n return (p', q')\n\n ds <- iterateNM n down 0\n mapM (iterateNM m right) ds\n\n putStr $ unlines $ map (unwords . map (show . (as'!) . decode)) xys\n"}], "src_uid": "38eb08ed1ac5d2212bf84f7bed809ba0"} {"source_code": "import Control.Monad\nmain = do\n tcn <- readLn\n replicateM_ tcn $ do\n n <- readLn\n print $ max 0 (n-2)\n\n", "positive_code": [{"source_code": "\nmain :: IO ()\nmain = do\n line <- getLine\n calc (read line :: Int)\n\ncalc :: Int -> IO ()\ncalc 0 = return ()\ncalc (n+1) = do\n x <- getLine\n putStr ((show (max 0 ((read x :: Int) - 2))) ++ \"\\n\")\n calc n\ncalc _ = return ()\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -fglasgow-exts -O2 -optc-O3 #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (getContents, split, readInt, lines, ByteString)\nimport Control.Applicative\n\ncheck :: Int -> Int\ncheck 1 = 0\ncheck n = n - 2\n\nmain = do\n (t:ns) <- BS.lines `fmap` BS.getContents\n mapM_ print $ map (check . readInt) $ ns\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of \n Just (i, _) -> i\n Nothing -> error \"Unparsable Integer\""}, {"source_code": "import Control.Monad\nmain = readLn >>= \\t -> replicateM_ t $ readLn >>= \\n -> print $ max 0 (n-2)\n"}], "negative_code": [{"source_code": "import Control.Monad\nmain = do\n tcn <- readLn\n replicateM_ tcn $ do\n n <- readLn\n print $ n`div`2\n"}], "src_uid": "f83c91c9e9252aba4736aa0bea82493b"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Semigroup\n\nimport Data.List\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [t] <- getInts 1\n replicateM_ t $ do\n [a, b] <- getInts 2\n let\n needed = abs (a - b) `div` 2\n tot = a + b\n maxv = tot - needed\n ans = [needed, needed + (if even tot then 2 else 1) .. maxv]\n putInts [length ans]\n putInts ans\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in lift $ B.hPutBuilder stdout $ case li of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (replicateM, guard)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Data.List (group, sort)\r\n\r\nmain :: IO ()\r\nmain =\r\n C.interact $\r\n runScanner (numberOf testCase)\r\n >>> map (solve >>> showAns)\r\n >>> concat\r\n >>> C.unlines\r\n where\r\n showAns xs = [showB $ length xs, C.unwords $ map showB xs]\r\n\r\ntestCase :: Scanner (Int, Int)\r\ntestCase = pair int int\r\n\r\nsolve :: (Int, Int) -> [Int]\r\nsolve (a, b) = uniq . sort $ do\r\n sa <- [half, tot - half] -- A #serves\r\n let sb = a + b - sa -- B #serves\r\n ha <- [0..a] -- A #points by hold\r\n let ba = a - ha -- A #points by break\r\n let bb = sa - ha -- B #points by break\r\n let hb = b - bb -- B #points by hold\r\n guard $ ba >= 0\r\n guard $ bb >= 0\r\n guard $ hb >= 0\r\n return $ ba + bb\r\n where\r\n tot = a + b\r\n half = tot `div` 2\r\n uniq = map head . group\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}], "negative_code": [], "src_uid": "04a37e9c68761f9a2588c0bbecad2147"} {"source_code": "import Data.Char\nimport Data.List\n\ntokenize :: String -> [String]\ntokenize [] = []\ntokenize (x:xs)\n | isSpace x = tokenize xs\n | isDigit x = (x:token):tokenize afterNumber\n | x == ',' = [x]:tokenize xs\n | x == '.' = \"...\":tokenize afterPoints\n where \n (_, afterPoints) = splitAt 2 xs\n (token, afterNumber) = span isDigit xs\n\nfix :: [String] -> String\nfix (x:xs) = x ++ fix' xs x\n where\n fix' :: [String] -> String -> String\n fix' [] _ = \"\"\n fix' (x:xs) p | (isDigit.head $ x) && (head p == '.') = x ++ fix' xs x\n | (head x == ',') && (head p == '.') = x ++ fix' xs x\n | (head x == ',') && (isDigit.head $ p) = x ++ fix' xs x\n | otherwise = \" \" ++ x ++ fix' xs x\n\nmain = interact $ fix.tokenize", "positive_code": [{"source_code": "import Data.Char\n\nmain = getLine >>= putStrLn . solve\n\nsolve = put . get\n\nget :: String -> [String]\nput :: [String] -> String\n\nget \"\" = []\nget (' ':xs) = get xs\nget (',':xs) = \",\" : get xs\nget ('.':'.':'.':xs) = \"...\" : get xs\nget xs = let (as,bs) = break (not . isDigit) xs\n in as : get bs\n\nput xs = let\n leftSp = map (==\"...\") xs\n rightSp = map (==\",\") xs\n num = map (isDigit . head) xs\n sp1 = zipWith (||) (tail leftSp) rightSp\n sp2 = zipWith (&&) num (tail num)\n in concat $ zipWith (\\x flag -> if flag then \" \"++x else x) xs $\n False : zipWith (||) sp1 sp2\n"}, {"source_code": "import Data.Char\ndata L = Spac | Dots | Comma | Num [Char] deriving Eq\ninstance Show L where\n show Spac = \" \"\n show Dots = \"...\"\n show Comma = \",\"\n show (Num s) = reverse s\nsc (s:ss) (Num n:rs) | s `elem` ['0'..'9'] = sc ss (Num (s:n):rs)\nsc (s:ss) rs | s `elem` ['0'..'9'] = sc ss (Num [s]:rs)\nsc (' ':ss) rs = sc ss (Spac:rs)\nsc (',':ss) rs = sc ss (Comma:rs)\nsc ('.':'.':'.':ss) rs = sc ss (Dots:rs)\nsc [] r = reverse $ filter (/= Spac) r\nf n1@(Num _) n2@(Num _) = show n1 ++ \" \"\nf a Dots = show a ++ \" \"\nf Comma _ = show Comma ++ \" \"\nf a _ = show a\npoly (s1:s2:ss) = f s1 s2 ++ poly (s2:ss)\npoly [s1] = show s1\npoly [] = []\nmain = do\n l <- getLine\n putStrLn $ poly $ sc l []\n"}, {"source_code": "import Data.Char\nimport Control.Applicative\n\ndata Token = IntToken Integer | Ellipsis | Comma deriving Show\n\ndigitToInteger = toInteger . digitToInt\n\ntokenize [] = []\ntokenize ('.':'.':'.':t) = Ellipsis : tokenize t\ntokenize (',':t) = Comma:tokenize t\ntokenize (' ':t) = tokenize t\ntokenize (digit:t) = tokenize' t (digitToInteger digit)\n where \n tokenize' (dig:t) i | isDigit dig = tokenize' t (i*10 + digitToInteger dig)\n tokenize' list i = IntToken i : tokenize list\n\nprintToken (IntToken i) = show i\nprintToken Ellipsis = \"...\"\nprintToken Comma = \",\"\n\nfancyPrint (Ellipsis : rest) = \"...\" ++ fancyPrint' rest\nfancyPrint list = fancyPrint' list\n\nfancyPrint' [] = \"\"\nfancyPrint' [Comma] = \",\"\nfancyPrint' (Comma:Ellipsis:rest) = \", ...\" ++ fancyPrint' rest\nfancyPrint' (Comma:rest@(_:_)) = \", \" ++ fancyPrint' rest\nfancyPrint' (IntToken i : rest@(IntToken _ : _)) = show i ++ \" \" ++ fancyPrint' rest\nfancyPrint' (IntToken i : rest) = show i ++ fancyPrint' rest\nfancyPrint' (Ellipsis : rest) = \" ...\" ++ fancyPrint' rest\n\nsolve = fancyPrint . tokenize\n\nmain = putStrLn =<< solve <$> getLine"}, {"source_code": "\nimport qualified Char as Char\n\n\ndata Gram = Comma | Dots | Num String\n\n\nparse [] = []\nparse (' ':xs) = parse xs\nparse (',':xs) = Comma:parse xs\nparse ('.':'.':'.':xs) = Dots:parse xs\nparse xs = (Num number) : parse rest\n where (number, rest) = span Char.isDigit xs\n\nunparse [] = \"\"\nunparse (Comma:[]) = \",\"\nunparse (Comma:Dots:xs) = \", ...\" ++ unparse xs\nunparse (Comma:xs) = \", \" ++ unparse xs\nunparse (Dots:xs) = \" ...\" ++ unparse xs\nunparse (Num d1:Num d2:xs) = d1 ++ \" \" ++ unparse (Num d2:xs) \nunparse (Num d:xs) = d ++ unparse xs\n\nfix (' ':xs) = xs\nfix xs = xs\n\n\nmain :: IO ()\nmain = do\n seq <- getLine\n putStr (fix (unparse (parse seq)))\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nfix [] = []\nfix (c:s) | isDigit c = c:fix s\nfix (' ':cs)\n\t\t| rest /= [] && isDigit (head rest) = ' ':fix rest\n\t\t| otherwise = fix rest\n\twhere\n\t\trest = dropWhile (== ' ') cs\nfix (',':cs)\n\t\t| rest /= [] && head rest /= '.' = ',':' ':fix rest\n\t\t| otherwise = ',':fix rest\n\twhere\n\t\trest = dropWhile (== ' ') cs\nfix ('.':'.':'.':cs) =\n\t\t' ':'.':'.':'.':(fix rest)\n\twhere\n\t\trest = dropWhile (== ' ') cs\n\nsolve = dropWhile (== ' ') . fix . dropWhileEnd (== '\\n')\n\nmain = interact solve\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nfix [] = []\nfix (c:s) | isDigit c = c:fix s\nfix (' ':cs)\n\t\t| rest /= [] && isDigit (head rest) = ' ':fix rest\n\t\t| otherwise = fix rest\n\twhere\n\t\trest = dropWhile (== ' ') cs\nfix (',':cs)\n\t\t| rest /= [] && head rest /= '.' = ',':' ':fix rest\n\t\t| otherwise = ',':fix rest\n\twhere\n\t\trest = dropWhile (== ' ') cs\nfix ('.':'.':'.':cs) =\n\t\t' ':'.':'.':'.':(fix rest)\n\twhere\n\t\trest = dropWhile (== ' ') cs\n\nsolve = dropWhile (== ' ') . fix . dropWhileEnd (== '\\n')\n\nmain = interact solve\n"}, {"source_code": "\nimport Char (isDigit)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"#1\" $ assertEq \"1, 2, 3, ..., 10\" $ solve \"1,2 ,3,..., 10\",\n Test \"#2\" $ assertEq \"1, , , 4 ...5 ... ...6\" $ solve \"1,,,4...5......6\",\n Test \"#3\" $ assertEq \"..., 1, 2, 3, ...\" $ solve \"...,1,2,3,...\"\n ]\n\ntestEmpty :: Test\ntestEmpty = TestList \"TestEmpty\"\n [\n Test \"#1\" $ assertEq \"\" $ solve \"\",\n Test \"#2\" $ assertEq \"\" $ solve \" \"\n ]\n\ntestTwoNumbers :: Test\ntestTwoNumbers = Test \"TestTwoNumbers\" $ assertEq \"1 2\" $ solve \"1 2\"\n\ntest :: IO ()\ntest = mapM_ run\n [\n testInput,\n testEmpty,\n testTwoNumbers\n ]\n-}\n--------------------------------------------------------------------------------\n\ndata State = Start | Number | Comma | Dots | Space\n\nisComma c = c == ','\nisDot c = c == '.'\nisSpace c = c == ' '\n\nsolve :: String -> String\nsolve s = solve' Start s\n where\n solve' _ [] = []\n solve' Start (c:cs)\n | isDigit c = c : solve' Number cs\n | isComma c = c : solve' Comma cs\n | isDot c = c : c : c : solve' Dots (drop 2 cs)\n | isSpace c = solve' Start cs\n solve' Number (c:cs)\n | isDigit c = c : solve' Number cs\n | isComma c = c : solve' Comma cs\n | isDot c = ' ' : c : c : c : solve' Dots (drop 2 cs)\n | isSpace c = solve' Space cs\n solve' Comma (c:cs)\n | isDigit c = ' ' : c : solve' Number cs\n | isComma c = ' ' : c : solve' Comma cs\n | isDot c = ' ' : c : c : c : solve' Dots (drop 2 cs)\n | isSpace c = solve' Comma cs\n solve' Dots (c:cs)\n | isDigit c = c : solve' Number cs\n | isComma c = c : solve' Comma cs\n | isDot c = ' ' : c : c : c : solve' Dots (drop 2 cs)\n | isSpace c = solve' Dots cs\n solve' Space (c:cs)\n | isDigit c = ' ' : c : solve' Number cs\n | isComma c = c : solve' Comma cs\n | isDot c = ' ' : c : c : c : solve' Dots (drop 2 cs)\n | isSpace c = solve' Space cs\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n"}], "negative_code": [{"source_code": "\nimport qualified Data.IntMap as Map\n\n\nfix1 [] = []\nfix1 (' ':' ':xs) = fix1 (' ':xs)\nfix1 (x:xs) = x:fix1 xs\n\nfix2 [] = []\nfix2 (' ':xs) = fix2 xs\nfix2 ('.':' ':x:xs) = '.':x:fix2 xs\nfix2 (',':' ':x:xs) = ',':x:fix2 xs\nfix2 (x:' ':'.':xs) = x:'.':fix2 xs\nfix2 (x:' ':',':xs) = x:',':fix2 xs\nfix2 (x1:' ':x2:xs) = x1:' ':x2:fix2 xs\nfix2 (x:xs) = x:fix2 xs\n\nfix3 [] = []\nfix3 (',':[]) = \",\"\nfix3 (',':xs) = ',':' ':fix3 xs\nfix3 (x:xs) = x:fix3 xs\n\nfix4 [] = []\nfix4 (' ':'.':'.':'.':xs) = ' ':'.':'.':fix4 ('.':xs)\nfix4 (x:'.':'.':'.':xs) = x:' ':'.':'.':fix4 ('.':xs)\nfix4 (x:xs) = x:fix4 xs\n\n\nmain :: IO ()\nmain = do\n seq <- getLine\n putStr (fix4 (fix3 (fix2 (fix1 seq))))\n"}, {"source_code": "\nimport qualified Data.IntMap as Map\n\n\nfix1 [] = []\nfix1 (' ':' ':xs) = fix1 (' ':xs)\nfix1 (x:xs) = x:fix1 xs\n\nfix2 [] = []\nfix2 (' ':xs) = fix2 xs\nfix2 ('.':' ':x:xs) = '.':x:fix2 xs\nfix2 (',':' ':x:xs) = ',':x:fix2 xs\nfix2 (x:' ':'.':xs) = x:'.':fix2 xs\nfix2 (x:' ':',':xs) = x:',':fix2 xs\nfix2 (x1:' ':x2:xs) = x1:' ':x2:fix2 xs\nfix2 (x:xs) = x:fix2 xs\n\nfix3 [] = []\nfix3 (',':[]) = \",\"\nfix3 (',':xs) = ',':' ':fix3 xs\nfix3 (x:xs) = x:fix3 xs\n\nfix4 [] = []\nfix4 ('?':'.':'.':'.':xs) = '?':'.':'.':fix4 ('.':xs)\nfix4 (' ':'.':'.':'.':xs) = ' ':'.':'.':fix4 ('.':xs)\nfix4 (x:'.':'.':'.':xs) = x:' ':'.':'.':fix4 ('.':xs)\nfix4 (x:xs) = x:fix4 xs\n\n\nmain :: IO ()\nmain = do\n seq <- getLine\n putStr (tail (fix4 (fix3 (fix2 (fix1 ('?':seq))))))\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nfix [] = []\nfix (c:s) | isDigit c = c:(fix s)\nfix (' ':cs)\n\t\t| rest /= [] && isDigit (head rest) = ' ':(fix rest)\n\t\t| otherwise = fix rest\n\twhere\n\t\trest = dropWhile (== ' ') cs\nfix (',':cs)\n\t\t| rest /= [] && head rest /= '.' = ',':' ':(fix rest)\n\t\t| otherwise = fix rest\n\twhere\n\t\trest = dropWhile (== ' ') cs\nfix ('.':'.':'.':cs) =\n\t\t' ':'.':'.':'.':(fix rest)\n\twhere\n\t\trest = dropWhile (== ' ') cs\n\nsolve = dropWhile (== ' ') . fix . dropWhileEnd (== '\\n')\n\nmain = interact solve\n"}, {"source_code": "import Data.Char\n\nmain = getLine >>= putStrLn . solve\n\nsolve = put . get\n\nget :: String -> [String]\nput :: [String] -> String\n\nget \"\" = []\nget (' ':xs) = get xs\nget (',':xs) = \",\" : get xs\nget ('.':'.':'.':xs) = \"...\" : get xs\nget xs = let (as,bs) = break (not . isDigit) xs\n in as : get bs\n\nput xs = let\n leftSp = map (==\"...\") xs\n rightSp = map (==\",\") xs\n sp = False : zipWith (||) (tail leftSp) rightSp\n in concat $ zipWith (\\flag x -> if flag then \" \"++x else x) sp xs\n"}, {"source_code": "import Data.Char\npoly (r1:' ':r2:rs) s | not (isDigit r1 && isDigit r2) && not (r2 == ',') = poly (r1:r2:rs) s\npoly (' ':' ':r':rs) ss | isDigit r' = poly (' ':r':rs) ss\npoly r@(' ':r':rs) (s:ss) | isDigit r' = poly (s:r) ss\npoly r@(' ':',':rs) (' ':ss) = poly r ss\npoly r@(' ':',':rs) (s:ss) = poly (s:r) ss\npoly (' ':rs) ss = poly rs ss\npoly r@(',':rs) (s:ss) | s /= ' ' = poly (' ':r) (s:ss)\npoly r@(',':rs) [] = r\npoly r [] = r\npoly r@(r':rs) ('.':'.':'.':ss) | r' /= ' ' = poly ('.':'.':'.':' ':r) ss\npoly r@(r':rs) ('.':'.':'.':ss) | r' == ' ' = poly ('.':'.':'.':r) ss\npoly r (s:ss) = poly (s:r) ss\nmain = do\n l <- getLine\n putStrLn $ reverse $ poly [] l \n"}], "src_uid": "c7d8c71a1f7e6c7364cce5bddd488a2f"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata Frac = Frac Integer Integer\n deriving (Eq)\nmkFrac :: Integer -> Integer -> Frac\nmkFrac p q\n | p == 0 = Frac 0 1\n | q' < 0 = Frac (-p') (-q')\n | otherwise = Frac p' q'\n where (p', q', g) = (div p g, div q g, gcd p q)\ninstance Num Frac where\n (Frac p1 q1) + (Frac p2 q2) = mkFrac (p1 * q2 + p2 * q1) (q1 * q2)\n (Frac p1 q1) - (Frac p2 q2) = mkFrac (p1 * q2 - p2 * q1) (q1 * q2)\n (Frac p1 q1) * (Frac p2 q2) = mkFrac (p1 * p2) (q1 * q2)\n negate (Frac p q) = Frac (negate p) q\n abs (Frac p q) = Frac (abs p) q\n signum (Frac p _) = Frac (signum p) 1\n fromInteger n = Frac n 1\ninstance Ord Frac where\n compare (Frac p1 q1) (Frac p2 q2) = compare (p1 * q2) (p2 * q1)\ninstance Show Frac where\n show (Frac p q) = show p ++ \"/\" ++ show q\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- zip [1..n] <$> getInts\n let calc p q = mkFrac (toInteger p) (toInteger q)\n pairs = [(calc (x1 * y2 - x2 * y1) (x1 - x2), calc (y2 - y1) (x2 - x1)) | (x1, y1) <- as, (x2, y2) <- as, x1 < x2]\n num = maximum $ (0:) $ map length $ group $ sort pairs\n result = floor $ (1 + sqrt (8 * fromIntegral num + 1 :: Double)) / 2 + 0.5\n return $ intDec (n - result) `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n aLi <- getInts n\r\n let\r\n a :: UArray Int Int\r\n a = listArray (1, n) aLi\r\n\r\n score i = let\r\n ratio x y = toRational x / toRational y\r\n slopes = [ratio (a ! j - a ! i) (j - i) | j <- [i + 1 .. n]]\r\n opts = map length $ group $ sort slopes\r\n in n - 1 - foldl' max 0 opts\r\n pure $ putInts [foldl' min n $ map score [1 .. n]]\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "6aca8c549822adbe96a58aee4b0d4b3f"} {"source_code": "count::Eq a=>[a]->a->Int\ncount c d=length $ filter (==d) c\n\ngao::Int->Int->Int\ngao a b | (b `mod` 2)==0 = 0\n\t\t | (a `mod` 2)==0 = 1\n\t\t | otherwise = -1\n\nmain::IO()\nmain = do\n\tn<-getLine\n\taa<-getLine\n\tbb<-getLine\n\tlet\n\t\tgame=zip aa bb\n\t\tnum = count game ('1','1')\n\t\tnum1 = ( count game ('1','0') ) + ( count game ('0','1') )\n\t\t--\u5947\u6570 + \u5947\u6570 -1 \u5076\u6570+\u5947\u6570 + 1\n\t\tans = (count aa '1') + ( num `mod` 2 )*2 - (count bb '1') + (gao num num1)\n\tif ans>0\n\tthen\n\t\tputStrLn \"First\"\n\telse if ans==0 \n\tthen\n\t\tputStrLn \"Draw\"\n\telse putStrLn \"Second\"\n", "positive_code": [{"source_code": "data Winner = First | Second\n\nmain = do\n _ <- getLine\n ss <- getLine\n ts <- getLine\n let sts = zip ss ts\n putStrLn.answer $ foldl game (First,0,0) $ both1 sts ++ either1 sts\n\nboth1 = filter (\\(a,b) -> a == b && a =='1')\neither1 = filter (\\(a,b) -> a /= b)\n\ngame (First,pf,ps) ('1','1') = (Second,pf+1,ps)\ngame (First,pf,ps) ('1','0') = (Second,pf+1,ps)\ngame (First,pf,ps) ('0','1') = (Second,pf,ps)\ngame (Second,pf,ps) ('1','1') = (First,pf,ps+1)\ngame (Second,pf,ps) ('1','0') = (First,pf,ps)\ngame (Second,pf,ps) ('0','1') = (First,pf,ps+1)\n\nanswer (_,a,b)\n | a == b = \"Draw\"\n | a > b = \"First\"\n | a < b = \"Second\""}, {"source_code": "count::Eq a=>[a]->a->Int\ncount c d=length $ filter (==d) c\n\ngao::Int->Int->Int\ngao a b | (b `mod` 2)==0 = 0\n\t\t | (a `mod` 2)==0 = 1\n\t\t | otherwise = -1\n\nmain::IO()\nmain = do\n\tn<-getLine\n\taa<-getLine\n\tbb<-getLine\n\tlet\n\t\tgame=zip aa bb\n\t\tnum = count game ('1','1')\n\t\tnum1 = ( count game ('1','0') ) + ( count game ('0','1') )\n\t\tans = (count aa '1') + ( num `mod` 2 )*2 - (count bb '1') + (gao num num1)\n\tif ans>0\n\tthen\n\t\tputStrLn \"First\"\n\telse if ans==0 \n\tthen\n\t\tputStrLn \"Draw\"\n\telse putStrLn \"Second\"\n"}], "negative_code": [], "src_uid": "6f52388b652a900e63ec39406225392c"} {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.Monoid\nimport Data.List\nimport Data.Ord\n\ngetInts = map read . words <$> getLine\n\ncollect 0 _ = Just []\ncollect n [] = Nothing\ncollect n (h:t) | h>=n = Just [n]\ncollect n (h:t) = (h:) <$> collect (n-h) t\n\ninterleave [] t2 = t2\ninterleave t1 [] = t1\ninterleave (h1:t1) (h2:t2) = h1:h2:interleave t1 t2\n\ncircle t = let (t1, t2) = splitAt ((length t + 1) `div` 2) t in interleave t1 t2\n\nunfold [] = []\nunfold ((i,n):t) = replicate n i ++ unfold t\n\nmain = do\n [n,_] <- getInts\n t <- getInts\n let t' = map (min (n `div` 2)) t\n t'' = collect n t'\n case t'' of\n Nothing -> putStrLn \"-1\"\n Just t'' -> do\n let\n t''' = zip [1..] t''\n t'''' = unfold $ sortBy (comparing snd) t'''\n res = map show $ circle t''''\n putStrLn $ concat $ intersperse \" \" $ res", "positive_code": [{"source_code": "import Data.List (sortBy)\nimport Data.Array.Unboxed\nimport Control.Monad (guard)\nimport Control.Applicative ((<|>))\nimport qualified Data.IntMap as M\ngetEl m e = M.update (\\x -> if x == 1 then Nothing else Just (x - 1)) e m\nmain = do\n [n, m] <- (map read . words) `fmap` getLine\n let f m a i | i < n = let \n f' | i == n - 1 = (`notElem` [a!0, a!(n-2)])\n | otherwise = (/= a!(i-1)) in\n foldl (\\c k -> c <|> f (getEl m k) \n (a // [(i, k)]) (i+1)) \n Nothing $ filter f' $ map fst $\n sortBy (\\(_, a) (_, b) -> compare b a) $ M.assocs m \n | otherwise = Just (elems a)\n t' <- (map read . words) `fmap` getLine\n let t = M.fromList $ zip [1..] t'\n let r = do\n let s = sum t'\n mt = maximum t'\n guard ((s - mt) >= n `div` 2)\n guard (s >= n)\n f (getEl t 1) (array (0, n-1) [(0,1)]:: UArray Int Int) 1\n putStrLn $ case r of\n Nothing -> \"-1\"\n Just l -> unwords $ map show $ l\n"}, {"source_code": "import List\ng 0 _=Just[]\ng n[]=Nothing\ng n(h:t)=fmap(m:)(g(n-m)t)where m=min h n\ni([],t2)=t2\ni(t1,[])=t1\ni((a:x),(b:y))=a:b:i(x,y)\nc t=i$splitAt((length t+1)`div`2)t\ns[[n,_],t]=g n$map(min$n`div`2)t\nmain=interact$maybe\"-1\"(unwords.map show.c.(>>=uncurry replicate).sort.(`zip`[1..])).s.map(map read.words).lines\n"}], "negative_code": [{"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.Monoid\nimport Data.List\nimport Data.Ord\n\ngetInts = map read . words <$> getLine\n\ncollect 0 _ = Just []\ncollect n [] = Nothing\ncollect n (h:t) | h>=n = Just [n]\ncollect n (h:t) = (h:) <$> collect (n-h) t\n\ninterleave [] t2 = t2\ninterleave t1 [] = t1\ninterleave (h1:t1) (h2:t2) = h1:h2:interleave t1 t2\n\ncircle t = let (t1, t2) = splitAt (length t `div` 2) t in interleave t1 t2\n\nunfold [] = []\nunfold ((i,n):t) = replicate n i ++ unfold t\n\nmain = do\n [n,_] <- getInts\n t <- getInts\n let t' = map (min (n `div` 2)) t\n t'' = collect n t'\n case t'' of\n Nothing -> putStrLn \"-1\"\n Just t'' -> do\n let\n t''' = zip [1..] t''\n t'''' = unfold $ sortBy (comparing snd) t'''\n res = map show $ circle t''''\n putStrLn $ concat $ intersperse \" \" $ res"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.Monoid\nimport Data.List\nimport Data.Ord\n\ngetInts = map read . words <$> getLine\n\ncollect 0 _ = Just []\ncollect n [] = Nothing\ncollect n (h:t) | h>=n = Just [n]\ncollect n (h:t) = (h:) <$> collect (n-h) t\n\ninterleave [] t2 = t2\ninterleave t1 [] = t1\ninterleave (h1:t1) (h2:t2) = h1:h2:interleave t1 t2\n\ncircle t = let (t1, t2) = splitAt (length t `div` 2 + 1) t in interleave t1 t2\n\nunfold [] = []\nunfold ((i,n):t) = replicate n i ++ unfold t\n\nmain = do\n [n,_] <- getInts\n t <- getInts\n let t' = map (min (n `div` 2)) t\n t'' = collect n t'\n case t'' of\n Nothing -> putStrLn \"-1\"\n Just t'' -> do\n let\n t''' = zip [1..] t''\n t'''' = unfold $ sortBy (comparing snd) t'''\n res = map show $ circle t''''\n putStrLn $ concat $ intersperse \" \" $ res"}], "src_uid": "2e99f0b671c80da1e768fa9bc7796481"} {"source_code": "import Data.Set as S\nmain = interact solve\nsolve input = output where\n inputs = lines input\n [k, n, m] = Prelude.map (read:: String -> Int) $ words $ head inputs\n s = fromList [(i,j,l)|i<-[0..k-1], j<-[0..n-1], l<-[0..m-1],\n (init $ drop 2 inputs)!!(i*(n+1)+j)!!l == '.']\n [x, y] = Prelude.map (read:: String -> Int) $ words $ last inputs\n output = show $ size s - (size $ f s [(0,x-1,y-1)])\n f :: Set (Int,Int,Int) -> [(Int,Int,Int)] -> Set (Int,Int,Int)\n f x [] = x\n f x ((i,j,l):xs) = if member (i,j,l) x\n then f (delete (i,j,l) x) (xs ++ [(i-1,j,l),(i+1,j,l),(i,j-1,l),(i,j+1,l),(i,j,l-1),(i,j,l+1)])\n else f x xs\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST\n\nfillWater :: Int -> Int -> UArray (Int,Int,Int) Bool -> Int\nfillWater x y plate = runST $ do\n let (_, (u,v,w)) = bounds plate\n visited <- newArray (bounds plate) False :: ST s (STUArray s (Int,Int,Int) Bool)\n\n let dfs x y z =\n if x < 1 || y < 1 || z < 1 || x > u || y > v || z > w || plate ! (x,y,z)\n then return 0\n else do\n ptVisited <- readArray visited (x,y,z)\n if ptVisited\n then return 0\n else do\n writeArray visited (x,y,z) True\n ( (1+) . sum ) `liftM` mapM (\\(dx,dy,dz) -> dfs (x+dx) (y+dy) (z+dz))\n [(1,0,0)\n ,(-1,0,0)\n ,(0,1,0)\n ,(0,-1,0)\n ,(0,0,1)\n ,(0,0,-1)]\n\n dfs 1 x y\n\nmain = do\n [w,u,v] <- ( map read . words ) `liftM` getLine\n plateInput <- join `liftM` replicateM w ( do\n getLine\n join `liftM` replicateM u ( do\n row <- getLine\n return $ map (=='#') row\n )\n )\n let plate = listArray ((1,1,1),(w,u,v)) plateInput :: UArray (Int,Int,Int) Bool\n\n getLine\n [x,y] <- ( map read . words ) `liftM` getLine\n\n --putStrLn $ show plate\n putStrLn $ show $ fillWater x y plate\n"}, {"source_code": "import Data.Array.IO\nmain = do\n [k, n, m] <- map read `fmap` (words `fmap` getLine)\n ar <- concat `fmap` (mapM (\\_ -> do\n getLine\n concat `fmap` (mapM (\\_ -> (take m) `fmap` getLine) [1..n])) [1..k])\n getLine\n [x,y] <- map read `fmap` (words `fmap` getLine)\n arr <- newListArray ((1,1,1), (k, n, m)) ar:: IO (IOUArray (Int, Int, Int) Char)\n let neibs (i1, i2, i3) = filter (\\(i1, i2, i3) -> i1 > 0 && i1 <= k && i2 > 0 &&\n i2 <=n && i3 > 0 && i3 <= m) [(i1+1,i2, i3), (i1-1, i2, i3), \n (i1, i2 - 1, i3), (i1, i2 + 1, i3), (i1, i2, i3-1), (i1, i2, i3+1)]\n search counter [] = return counter\n search counter (s:ss) = readArray arr s >>= \\c -> if c == '#' \n then search counter ss else (do \n writeArray arr s '#'\n ns <- (map fst . filter ((=='.').snd)) `fmap` (mapM (\\s' -> readArray arr s' >>= \n \\c -> return (s', c)) (neibs s))\n search (counter + 1) (ss ++ ns))\n cnt <- search 0 [(1,x,y)]\n print cnt\n"}], "negative_code": [], "src_uid": "3f6e5f6d9a35c6c9e71a7eeab4acf199"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n \nmain = do\n\t\tn<- getLine \n\t\tputStrLn $ n ++ reverse n\n", "positive_code": [{"source_code": "main = getLine >>= \\s -> putStrLn $ s ++ (reverse s) \n"}, {"source_code": "main = do\n e<-getLine\n putStrLn $ e ++ (reverse e) "}, {"source_code": "main = do\n line <- getLine\n putStrLn ((line) ++ (reverse line))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n a <- getLine\n putStrLn $ a ++ reverse a\n"}, {"source_code": "main = getLine >>= putStrLn . (\\s -> s ++ reverse s)\n"}, {"source_code": "main=do s<-getLine;putStrLn$s++reverse s"}, {"source_code": "main = do\n s <- getLine\n putStrLn (s ++ reverse s)\n"}, {"source_code": "module Main where\n\nmain = do\n l <- getLine\n putStr $ l ++ reverse l ++ ['\\n']\n\n"}, {"source_code": "process :: String -> String\nprocess s = s ++ (reverse s)\n\nmain :: IO ()\nmain = do\n s <- getLine\n putStrLn $ process s"}, {"source_code": "main = do \n\tline <- getLine\n\tputStr line\n\tputStr $ reverse line"}], "negative_code": [], "src_uid": "9b1887582a9eb7cff49994ddcc2ee9b8"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Sequence ((<|),(|>),(><),ViewL(..),ViewR(..),viewl,viewr)\nimport qualified Data.Sequence as Seq\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n print . solve . merge $ map (Up . Seq.singleton) xs\n\ndata SeqUpDown = Up (Seq.Seq Int)\n | Down (Seq.Seq Int)\n\nsolve :: [SeqUpDown] -> Int\nsolve xss = go 0 xss\n where\n go !res [Up _] = res\n go !res xss = go (res+1) $ merge $ kill xss\n\nkill :: [SeqUpDown] -> [SeqUpDown]\nkill (Down xs:xss)|(x:<_)<-viewl xs = Up (Seq.singleton x) : kill xss\nkill (xs:xss) = xs : kill xss\nkill [] = []\n\nmerge :: [SeqUpDown] -> [SeqUpDown]\nmerge (Up xs:Up ys:rest)\n | xr < yl = merge (Up (xs>yl) : merge (Up nys:rest)\n | Seq.null nys = Up nxs : merge (Down (xr<|ys):rest)\n | otherwise = Up nxs : Down (xr<|yl<|Seq.empty) : merge (Up nys:rest)\n where\n (nxs:>xr) = viewr xs\n (yl:xr) = viewr xs\n (yl:yl):rest)\n | otherwise = Down (xs|>yl) : merge (Up nys:rest)\n where\n (nxs:>xr) = viewr xs\n (yl:xr) = viewr xs\n (yl: [Node] -> Int\nsolve [] _ = 0 \nsolve (x:xs) stack = max (ans) (solve xs ((x, ans):nstack))\n where nstack = dropWhile (\\y -> x > fst(y)) stack\n ans = calc (map (snd) (takeWhile (\\y -> x > fst(y)) stack)) 0\n\ncalc :: [Int] -> Int -> Int\ncalc [] mx = mx\ncalc (x:xs) mx = calc xs (max (mx + 1) x)"}], "negative_code": [{"source_code": "module Main where\n\nmain :: IO()\nmain = do\n n <- readLn\n line <- getLine\n let ls = reverse $ map (read) $ words line\n putStrLn $ show $ solve ls [] n\n\nsolve :: [Int] -> [Int] -> Int -> Int\nsolve [] _ _ = 0 \nsolve (x:xs) stack n = max ((length stack) - (length nstack)) (solve xs (x:nstack) (n - 1))\n where nstack = dropWhile (x>) stack"}], "src_uid": "ff4a128ad18ccc846c44647cec5cf485"} {"source_code": "import Data.Char (digitToInt)\n\ndigits :: Integer -> [Integer]\ndigits = fmap (fromIntegral . digitToInt) . show\n\nsolve :: Integer -> Int\nsolve x = length . takeWhile (> 9) $ iterations\n where\n iterations = iterate (sum . digits) x\n\nmain :: IO ()\nmain = do\n x <- readLn\n print $ solve x\n", "positive_code": [{"source_code": "import Data.Char\n\nmain = interact $ (++\"\\n\") . show . solve . head . lines\n\ndigitsum :: String -> Int\ndigitsum = sum . map ((subtract $ ord '0') . ord)\n\nsolve :: String -> Int\nsolve [x] = 0\nsolve xs = 1 + (solve . show . digitsum) xs\n"}, {"source_code": "import Data.Char\n\nmain = do getLine >>= print . length . takeWhile ((>1) . length) . iterate (show . sum . map digitToInt)\n"}, {"source_code": "{-\n sum of digits\n-} \nmodule Main where\n\nimport Data.List\nimport Data.Char\n\naddDigits :: String -> String\naddDigits digits = show $ foldl (\\acc c -> acc + digitToInt c) 0 digits\n\nstringTrim :: String -> String\nstringTrim = filter (not . isSpace)\n \nmain :: IO ()\nmain = interact (show . iterate 0 . stringTrim )\n where iterate cnt digits = case length digits of\n 0 -> cnt\n 1 -> cnt\n _ -> iterate (cnt+1) $ addDigits digits\n\n \n \n"}, {"source_code": "module Main where\n\nimport Char\n\nmain = do\n inputN <- getLine\n let n = read inputN\n putStrLn $ show $ process n\n\nprocess :: Integer -> Int\nprocess n =\n if n<10\n then 0\n else (+) 1 $ process $ foldl ( \\a b -> a + fromIntegral ( ord b ) - 48 ) 0 $ show n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Char\n\nsumDigit :: C.ByteString -> Int\nsumDigit x\n\t| x == C.empty = 0\n\t| otherwise = sumDigit (C.tail x) + (digitToInt (C.head x))\n\nsolve :: C.ByteString -> Int\nsolve x\n\t| C.length x == 1 = 0\n\t| otherwise = solve ((C.pack . show . sumDigit) x) + 1\n\nmain = getLine >>= putStrLn . show . solve . C.pack\n"}, {"source_code": "import Data.Char\nsolve :: String -> Int\nsolve [x] = 0\nsolve xs \n | ds < 10 = 1\n | otherwise = 1 + solve (show ds)\n where ds = sum . map digitToInt $ xs\nmain = interact $ show . solve . head . lines\n"}, {"source_code": "--import CPUTime\nimport Char\n\nbigTest :: String\nbigTest = replicate 100000 '9'\n\nnext :: Int -> Int\nnext 0 = 0\nnext n = mod n 10 + next (div n 10)\n\nsolve :: Int -> Int\nsolve 0 = 0\nsolve n = solve' n 1\n where\n solve' n m\n | n < 10 = m\n | otherwise = solve' (next n) (m + 1)\n\nreadDigits :: IO Int\nreadDigits = readDigits' (0, 0)\n where\n readDigits' (m, n) = do\n c <- getChar\n if (isDigit c) then readDigits' (m + digitToInt c, n + 1) else if (n == 1) then return 0 else return m\n\nmain = do\n-- n <- readLn\n-- t0 <- getCPUTime\n-- let n = read bigTest\n n <- readDigits\n print $ solve n\n-- t1 <- getCPUTime\n-- putStr \"Time = \"\n-- print (fromIntegral (t1 - t0) * 1e-12)\n"}, {"source_code": "g s = if length s == 1 then 0\n else (succ . g . show . sum . (map (\\x -> read [x]::Int))) s\nmain = putStrLn =<< fmap (show . g) getLine"}, {"source_code": "import Data.Char\n\ndsum 0 = 0\ndsum n = n `rem` 10 + dsum (n `div` 10)\n\nans n\n\t| n<=9 = 1\n\t| otherwise = 1 + ans (dsum n)\n\nmain = do\n\ts <- map (\\x -> ord x - ord '0') `fmap` getLine\n\tputStrLn $ show $ if length s==1 then 0 else ans (sum s)\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ndsum 0 = 0\ndsum n = n `rem` 10 + dsum (n `div` 10)\n\nans n\n\t| n<=9 = 1\n\t| otherwise = 1 + ans (dsum n)\n\nmain = do\n\ts <- map (\\x -> ord x - ord '0') `fmap` getLine\n\tlet sm = sum s\n\tlet n = length s\n\tputStrLn $ show $ if n==1 then 0 else ans sm\n"}, {"source_code": "import Data.Char\nmain = print . flip solve 0 =<< getLine\nsolve [_] a = a\nsolve ns a = solve (show . sum $ map digitToInt ns) $! a + 1\n"}, {"source_code": "import Data.Char as Char\n\ng :: String -> Int\ng [_] = 0\ng str = 1 + (g $ show $ sum $ map Char.digitToInt str)\n\n\nmain :: IO()\nmain = do\n str <- getLine\n print $ g str\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Data.Char\n\nspell :: Integer -> Integer\nspell = sum . map (toInteger . digitToInt) . show\n\nsolve :: Integer -> Integer\nsolve = loop 0\n where\n loop !n !x = case (x `quotRem` 10) of\n (q, r) | q == 0 -> n\n | otherwise -> loop (n + 1) (spell x)\n\nmain :: IO ()\nmain = readLn >>= print . solve\n\n\n"}, {"source_code": "import Data.Char (ord)\nimport Data.List (foldl')\ndefault (Int)\nmain = do\n n <- getLine\n if length n == 1 then print 0 else do\n let f s n | n < 10 = n + s\n | otherwise = f (s + m) d where (d, m) = n `divMod` 10\n f1 k n | n < 10 = k\n | otherwise = f1 (k + 1) $! f 0 n\n print $ (f1 1 . foldl' (\\a b -> a + ord b - ord '0') 0) n \n"}, {"source_code": "import Char\nimport List\n\nputAnsLn :: (Show a) => a -> IO ()\nputAnsLn ans = putStrLn (show ans)\n\ndigitsum [] s = s\ndigitsum (n:ns) s = digitsum ns (s + (ord n) - 48)\n\nsolve n ans = if (length n) == 1 then\n ans\n else\n solve (show (digitsum n 0)) (ans+1)\n\nmain = do n <- getLine\n putAnsLn (solve n 0)\n"}, {"source_code": "import Data.Char\n\nmain = do getLine >>= print . length . takeWhile ((>1) .length) . iterate (show . sum . map digitToInt)"}, {"source_code": "import Data.Char\nsolve = loop 0\n\nloop acc [_] = acc\nloop acc foo = loop (1 + acc) (show (sum [digitToInt x | x <- foo]))\n\nmain = interact (show . solve . filter isDigit)"}], "negative_code": [{"source_code": "module Main where\n\nimport Char\n\nmain = do\n inputN <- getLine\n let n = read inputN\n putStrLn $ show $ process n\n\nprocess n =\n if n<10\n then 0\n else (+) 1 $ process $ foldl ( \\a b -> a + ord b - 48 ) 0 $ show n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ndsum 0 = 0\ndsum n = n `rem` 10 + dsum (n `div` 10)\n\nans n\n | n==0 = 0\n | n<=9 = 1\n | otherwise = 1 + ans (dsum n)\n\nmain = do\n s <- fmap (sum . map (\\x -> ord x - ord '0')) getLine\n putStrLn $ show $ ans s"}], "src_uid": "ddc9201725e30297a5fc83f4eed75fc9"} {"source_code": "import List\nimport Control.Monad\nimport qualified Data.Map as M\n\nmaxOne [] = 0\nmaxOne ss = 1 + (maximum $ map fst ss)\n\nmaxTwo [] = 0\nmaxTwo (x:[]) = max (1 + fst x) (snd x)\nmaxTwo ss = max (o1 + o2 + 2) t1\n where o1:o2:_ = sortBy (flip compare) $ map fst ss\n t1 = maximum $ map snd ss\n\nsolve edges adj = show $ maximum [snd (go x y) * snd (go y x) | [x,y] <- edges]\n where\n children p r = delete p $ M.findWithDefault [] r adj\n go p root = (maxOne sub, maxTwo sub)\n where sub = map (go root) $ children p root\n\nadjList edges = map ((\\(x,y) -> (head x, y)).unzip).groupBy (\\x y-> fst x == fst y)\n .map (\\[x,y]->(x,y)).nub.sort $ (edges ++ (map reverse edges))\n\nints = fmap (map read . words) getLine\n\nmain = do\n [n] <- ints\n edges <- replicateM (n-1) ints\n putStrLn.solve edges. M.fromList .adjList $ edges\n ", "positive_code": [{"source_code": "import Data.Array (accumArray, (!))\nimport Data.List (sort)\n\ngao n e = maximum [fst (gao' a b) * fst (gao' b a) | (a, b) <- e] where\n e' = accumArray (flip (:)) [] (1, n) $ concat [e, [(b, a) | (a, b) <- e]]\n gao' p q = (\\(a, b) -> let b' = reverse $ sort b in (max a $ (b'!!0)+(b'!!1), b'!!0)) $\n foldl (\\(a,b) (c,d) -> (max a c, d+1:b)) (0, [0, 0]) [gao' i p | i <- e'!p, i /= q]\n\nmain = do\n v <- getLine\n e <- getContents\n putStrLn $ show $ let n = read v in gao n $ map ((\\[a,b]->(a,b)) . map read . words) $ lines e\n"}, {"source_code": "import List\nimport Control.Monad\n\nsolve edges adj = show $ maximum [snd (go x y) * snd (go y x) | [x,y] <- edges]\n where\n children p r = delete p . snd. head $ (filter ((r==).fst) adj)++[(r,[])]\n go p root = (maxOne sub, maxTwo sub)\n where sub = map (go root) $ children p root\n maxOne [] = 0\n maxOne ss = 1 + (maximum $ map fst ss)\n\n maxTwo [] = 0\n maxTwo (x:[]) = max (1 + fst x) (snd x)\n maxTwo ss = max (o1 + o2 + 2) t1\n where o1:o2:_ = sortBy (flip compare) $ map fst ss\n t1 = maximum $ map snd ss\n\nadjList edges = map ((\\(x,y) -> (head x, y)).unzip)\n .groupBy (\\x y-> fst x == fst y)\n .map (\\[x,y]->(x,y))\n .nub\n .sort $ (edges ++ (map reverse edges))\n\nints = fmap (map read . words) getLine\n\nmain = do\n [n] <- ints\n edges <- replicateM (n-1) ints\n putStrLn.solve edges.adjList $ edges\n "}], "negative_code": [{"source_code": "import Data.Array (accumArray, (!))\nimport Data.List (sort)\n\ngao n e = maximum [fst (gao' a b) * fst (gao' b a) | (a, b) <- e] where\n\te' = accumArray (\\a b->b:a) [] (1, n) $ concat [e, [(b, a) | (a, b) <- e]]\n\tgao' p q = (\\(a, b) -> let b' = reverse $ sort b in (max a (b'!!0)+(b'!!1), b'!!0)) $\n\t\tfoldl (\\(a,b) (c,d) -> (max a c, d+1:b)) (0, [0, 0]) [gao' i p | i <- e'!p, i /= q]\n\nmain = do\n\tv <- getLine\n\te <- getContents\n\tputStrLn $ show $ let n = read (v ++ v) in gao n $ map ((\\[a,b]->(a,b)) . map read . words) $ lines e\n\n"}, {"source_code": "import Data.Array (accumArray, (!))\nimport Data.List (sort)\n\ngao n e = maximum [fst (gao' a b) * fst (gao' b a) | (a, b) <- e] where\n e' = accumArray (\\a b->b:a) [] (1, n) $ concat [e, [(b, a) | (a, b) <- e]]\n gao' p q = (\\(a, b) -> let b' = reverse $ sort b in (max a (b'!!0)+(b'!!1), b'!!0)) $\n foldl (\\(a,b) (c,d) -> (max a c, d+1:b)) (0, [0, 0]) [gao' i p | i <- e'!p, i /= q]\n\nmain = do\n v <- getLine\n e <- getContents\n putStrLn $ show $ let n = read v in gao n $ map ((\\[a,b]->(a,b)) . map read . words) $ lines e"}, {"source_code": "import Data.Array (accumArray, (!))\nimport Data.List (sort)\n\ngao n e = maximum $ 0:[fst (gao' a b) * fst (gao' b a) | (a, b) <- e] where\n\te' = accumArray (\\a b->b:a) [] (1, n) $ concat [e, [(b, a) | (a, b) <- e]]\n\tgao' p q = (\\(a, b) -> let b' = reverse $ sort b in (max a (b'!!0)+(b'!!1), b'!!0)) $\n\t\tfoldl (\\(a,b) (c,d) -> (max a c, d+1:b)) (0, [0, 0]) [gao' i p | i <- e'!p, i /= q]\n\nmain = do\n\tv <- getLine\n\te <- getContents\n\tputStrLn $ show $ let n = read v in gao n $ map ((\\[a,b]->(a,b)) . map read . words) $ lines e\n\n"}, {"source_code": "import Data.Array (accumArray, (!))\nimport Data.List (sort)\n\ngao n e = maximum [fst (gao' a b) * fst (gao' b a) | (a, b) <- e] where\n\te' = accumArray (\\a b->b:a) [] (1, n) $ concat [e, [(b, a) | (a, b) <- e]]\n\tgao' p q = (\\(a, b) -> let b' = reverse $ sort b in (max a (b'!!0)+(b'!!1), b'!!0)) $\n\t\tfoldl (\\(a,b) (c,d) -> (max a c, d+1:b)) (0, [0, 0]) [gao' i p | i <- e'!p, i /= q]\n\nmain = do\n\tv <- getLine\n\te <- getContents\n\tputStrLn $ show $ let n = read v in gao n $ map ((\\[a,b]->(a,b)) . map read . words) $ take (n - 1) $ lines e\n\n"}, {"source_code": "import Data.Array (accumArray, (!))\nimport Data.List (sort)\n\ngao n e = maximum [fst (gao' a b) * fst (gao' b a) | (a, b) <- e] where\n\te' = accumArray (\\a b->b:a) [] (1, n) $ concat [e, [(b, a) | (a, b) <- e]]\n\tgao' p q = (\\(a, b) -> let b' = reverse $ sort b in (max a (b'!!0)+(b'!!1), b'!!0)) $\n\t\tfoldl (\\(a,b) (c,d) -> (max a c, d+1:b)) (0, [0, 0]) [gao' i p | i <- e'!p, i /= q]\n\nmain = do\n\tv <- getLine\n\te <- getContents\n\tputStrLn $ show $ let n = read v in gao n $ map ((\\[a,b]->(a,b)) . map read . words) $ lines e\n\n"}, {"source_code": "import List\nimport Control.Monad\nimport qualified Data.Map as M\n\nsolve adj = show $ maximum [snd (go x y) * snd (go y x) \n | x <- M.keys adj, y <- children (-1) x]\n where\n children p r = delete p $ (M.findWithDefault) [] r adj\n go p root = (maxOne sub, maxTwo sub)\n where sub = map (go root) $ children p root\n maxOne [] = 0\n maxOne ss = 1 + (maximum $ map fst ss)\n\n maxTwo [] = 0\n maxTwo (x:[]) = max (1 + fst x) (snd x)\n maxTwo ss = max (o1 + o2 + 2) t1\n where o1:o2:_ = sort $ map fst ss\n t1 = maximum $ map snd ss\n\nadjList edges = map ((\\(x,y) -> (head x, y)).unzip)\n .groupBy (\\x y-> fst x == fst y)\n .map (\\[x,y]->(x,y))\n .nub\n .sort $ (edges ++ (map reverse edges))\n\nints = fmap (map read . words) getLine\n\nmain = do\n [n] <- ints\n edges <- replicateM (n-1) ints\n putStrLn.solve.(M.fromList).adjList $ edges\n "}, {"source_code": "import List\nimport Control.Monad\n\nsolve edges adj = show $ maximum [snd (go x y) * snd (go y x) | [x,y] <- edges]\n where\n children p r = delete p . snd. head $ (filter ((r==).fst) adj)++[(r,[])]\n go p root = (maxOne sub, maxTwo sub)\n where sub = map (go root) $ children p root\n maxOne [] = 0\n maxOne ss = 1 + (maximum $ map fst ss)\n\n maxTwo [] = 0\n maxTwo (x:[]) = max (1 + fst x) (snd x)\n maxTwo ss = max (o1 + o2 + 2) t1\n where o1:o2:_ = sort $ map fst ss\n t1 = maximum $ map snd ss\n\nadjList edges = map ((\\(x,y) -> (head x, y)).unzip)\n .groupBy (\\x y-> fst x == fst y)\n .map (\\[x,y]->(x,y))\n .nub\n .sort $ (edges ++ (map reverse edges))\n\nints = fmap (map read . words) getLine\n\nmain = do\n [n] <- ints\n edges <- replicateM (n-1) ints\n putStrLn.solve edges.adjList $ edges\n "}], "src_uid": "b07668a66a5e50659233ba055a893bd4"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = do\n [n, k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let v = k `div` 2\n print $\n if odd k\n then min (solve as (v + 1)) (solve (tail $ init as) v)\n else min (solve (init as) v) (solve (tail as) v)\n\nsolve as v = search (check as v) 0 (10 ^ 9 + 1)\n\ncheck as v a = space (sort $ map snd $ filter ((<= a) . fst) $ zip as [0..]) >= v\n\nspace [] = 0\nspace [i] = 1\nspace (a : b : is)\n | a + 1 == b = space (a : is)\n | otherwise = 1 + space (b : is)\n\nsearch f l r\n | l >= r - 1 = r\n | f m = search f l m\n | otherwise = search f m r\n where\n m = (l + r) `div` 2\n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve _ k as = min minOdd minEven\n where\n bounds = (1,10^9)\n minOdd = binSearch (checkOdds as k) bounds\n minEven = binSearch (checkEvens as k) bounds\n\nbinSearch :: (Int -> Bool) -> (Int,Int) -> Int\nbinSearch predi (lo,hi)\n | lo == hi = lo\n | predi lmid = binSearch predi (lo,lmid)\n | otherwise = binSearch predi (hmid,hi)\n where\n lmid = div (lo+hi) 2\n hmid = lmid+1\n\ncheckOdds :: [Int] -> Int -> Int -> Bool\ncheckOdds _ 0 _ = True\ncheckOdds [] _ _ = False\ncheckOdds (a:as) k x\n | a<=x = checkEvens as (k-1) x\n | otherwise = checkOdds as k x\n\ncheckEvens :: [Int] -> Int -> Int -> Bool\ncheckEvens _ 0 _ = True\ncheckEvens [] _ _ = False\ncheckEvens (_:as) k x = checkOdds as (k-1) x\n"}, {"source_code": "import Data.List\n \nhead1 :: [Bool] -> [Bool]\nhead1 l = if not $ head l then [False]\n else if (mod (length l) 2) == 0 then tail l\n else l\n \ndoMagic :: [Bool] -> [Bool]\ndoMagic l = reverse $ dropWhile (==True) $ reverse $ dropWhile (==True) l\n \ngetMaxLength1 :: Int -> [Bool] -> Int\ngetMaxLength1 x = length . concat . map head1 . group\n \ngetMaxLength :: Int -> [Int] -> Int\ngetMaxLength x l = length l - length stripped + getMaxLength1 x stripped\n where\n stripped = doMagic (map (<=x) l)\n \ngetAnswer :: [Int] -> Int -> Int -> Int -> Int\ngetAnswer l k lo hi = \n if lo == hi then lo\n else \n if getMaxLength mid l < k then getAnswer l k (mid+1) hi\n else getAnswer l k lo mid\n where mid = div (lo + hi) 2\n \nsolve :: [Int] -> Int\nsolve (n:k:a) = getAnswer a k 1 1000000000\n \nmain = interact $ show . solve . map read . words"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nhead' :: [Bool] -> [Bool]\nhead' l = if head l then l else [False]\n\ndedup :: [Bool] -> [Bool]\ndedup = concat . map head' . group\n\ngetMaxLength :: Int -> [Int] -> Int\ngetMaxLength x = length . dedup . map (<=x)\n\ngetAnswer :: [Int] -> Int -> Int -> Int -> Int\ngetAnswer l k lo hi = \n if lo == hi then lo\n else \n if getMaxLength mid l < k then getAnswer l k (mid+1) hi\n else getAnswer l k lo mid\n where mid = div (lo + hi) 2\n\nsolve :: [Int] -> Int\nsolve (n:k:a) = getAnswer a k 1 1000000000\n\nmain = interact $ show . solve . map read . words\n\n"}, {"source_code": "import Data.List\n \nhead1 :: [Bool] -> [Bool]\nhead1 l = if not $ head l then [False]\n else if (mod (length l) 2) == 0 then tail l\n else l\n\nhead2 :: [Bool] -> [Bool]\nhead2 l = if not $ head l then [False]\n else if (mod (length l) 2) == 1 then tail l\n else l\n\ndoMagic :: [Bool] -> [Bool]\ndoMagic l = reverse $ dropWhile (==True) $ reverse $ dropWhile (==True) l\n\ngetMaxLength1 :: Int -> [Bool] -> Int\ngetMaxLength1 x = length . concat . map head1 . group\n\ngetMaxLength2 :: Int -> [Bool] -> Int\ngetMaxLength2 x = length . concat . map head2 . group\n \ngetMaxLength :: Int -> [Int] -> Int\ngetMaxLength x l = length l - length stripped + max (getMaxLength1 x stripped) (getMaxLength2 x stripped)\n where\n stripped = doMagic (map (<=x) l)\n\ngetAnswer :: [Int] -> Int -> Int -> Int -> Int\ngetAnswer l k lo hi = \n if lo == hi then lo\n else \n if getMaxLength mid l < k then getAnswer l k (mid+1) hi\n else getAnswer l k lo mid\n where mid = div (lo + hi) 2\n \nsolve :: [Int] -> Int\nsolve (n:k:a) = getAnswer a k 1 1000000000\n \nmain = interact $ show . solve . map read . words\n"}, {"source_code": "import Data.List\n \nhead1 :: [Bool] -> [Bool]\nhead1 l = if not $ head l then [False]\n else if (mod (length l) 2) == 0 then tail l\n else l\n\nhead2 :: [Bool] -> [Bool]\nhead2 l = if not $ head l then [False]\n else if (mod (length l) 2) == 1 then tail l\n else l\n\ngetMaxLength1 :: Int -> [Int] -> Int\ngetMaxLength1 x = length . concat . map head1 . group . map (<=x)\n\ngetMaxLength2 :: Int -> [Int] -> Int\ngetMaxLength2 x = length . concat . map head2 . group . map (<=x)\n \ngetMaxLength :: Int -> [Int] -> Int\ngetMaxLength x l = max (getMaxLength1 x l) (getMaxLength2 x l)\n\ngetAnswer :: [Int] -> Int -> Int -> Int -> Int\ngetAnswer l k lo hi = \n if lo == hi then lo\n else \n if getMaxLength mid l < k then getAnswer l k (mid+1) hi\n else getAnswer l k lo mid\n where mid = div (lo + hi) 2\n \nsolve :: [Int] -> Int\nsolve (n:k:a) = getAnswer a k 1 1000000000\n \nmain = interact $ show . solve . map read . words\n"}, {"source_code": "import Data.List\n \nhead' :: [Bool] -> [Bool]\nhead' l = if not $ head l then [False]\n else if (mod (length l) 2) == 0 then tail l\n else l\n \ndedup :: [Bool] -> [Bool]\ndedup = concat . map head' . group\n \ngetMaxLength :: Int -> [Int] -> Int\ngetMaxLength x = length . dedup . map (<=x)\n \ngetAnswer :: [Int] -> Int -> Int -> Int -> Int\ngetAnswer l k lo hi = \n if lo == hi then lo\n else \n if getMaxLength mid l < k then getAnswer l k (mid+1) hi\n else getAnswer l k lo mid\n where mid = div (lo + hi) 2\n \nsolve :: [Int] -> Int\nsolve (n:k:a) = getAnswer a k 1 1000000000\n \nmain = interact $ show . solve . map read . words\n "}], "src_uid": "d55ed15b600477e292406bef0b2d3b49"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n getLine\r\n mapM_ (putStr.showAns.solve) tcs\r\n \r\nshowAns (cost, ms) = unlines [show cost ++ \" \" ++ (show.length) ms,\r\n unwords . map show $ ms]\r\n\r\nsolve origS = (abs (ord co2 - ord co1), ans)\r\n where\r\n s | (co1 <= co2) = origS\r\n | otherwise = map chRev origS\r\n (co1, co2) = (head origS, last origS)\r\n chRev :: Char -> Char\r\n chRev c = chr $ ord 'a' + (ord 'z' - ord c)\r\n (c1, c2) = (head s, last s)\r\n ans = map snd . L.sortOn fst . filter (isBetween.fst) . (`zip`inds) $ s\r\n isBetween c = (c1 <= c && c <= c2)\r\n\r\ninds = [1..] :: [Int]\r\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\nimport qualified Data.Text as T\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\n\nimport qualified Control.Monad as M\n\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\n\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- solution -}\n\nsolve :: B8.ByteString -> (Int, [Int])\nsolve str = (cost, finalPath)\n where\n fStr = B8.filter isAlphaNum str\n\n cost = abs $ ord c0 - ord c1\n path = if c0 > c1 then reverse sortedIndexes else sortedIndexes\n finalPath = 0:path ++ [B8.length fStr - 1]\n\n indexes = [1 .. B8.length fStr - 2]\n filteredIndexes = filter (\\idx -> charMatch $ str `B8.index` idx) indexes\n sortedIndexes = sortOn (fStr `B8.index`) filteredIndexes\n\n c0 = B8.head fStr \n c1 = B8.last fStr\n\n charMatch c = (c <= c0 && c >= c1) || (c <= c1 && c >= c0)\n\n \n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n str <- B8.getLine\n let (cost, path) = solve str\n printf \"%d %d\\n\" cost (length path)\n M.forM_ path $ \\idx -> printf \"%d \" (idx + 1)\n printf \"\\n\"\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n getLine\r\n mapM_ (putStr.showAns.solve) tcs\r\n \r\nshowAns (cost, ms) = unlines [show cost ++ \" \" ++ (show.length) ms,\r\n unwords . map show $ ms]\r\n\r\nsolve origS = (abs (ord co2 - ord co1), ans)\r\n where\r\n s | (co1 <= co2) = origS\r\n | otherwise = map chRev origS\r\n (co1, co2) = (head origS, last origS)\r\n chRev :: Char -> Char\r\n chRev c = chr $ ord 'a' + (ord 'z' - ord c)\r\n (c1, c2) = (head s, last s)\r\n ans = map snd . L.sortOn fst . filter (isBetween.fst) . (`zip`inds) $ s\r\n isBetween c = (c1 <= c && c <= c2)\r\n\r\ninds = [1..] :: [Int]\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O1 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n getLine\r\n mapM_ (putStr.showAns.solve) tcs\r\n \r\nshowAns (cost, ms) = unlines [show cost ++ \" \" ++ (show.length) ms,\r\n unwords . map show $ ms]\r\n\r\nsolve origS = (abs (ord co2 - ord co1), ans)\r\n where\r\n s | (co1 <= co2) = origS\r\n | otherwise = map chRev origS\r\n (co1, co2) = (head origS, last origS)\r\n chRev :: Char -> Char\r\n chRev c = chr $ ord 'a' + (ord 'z' - ord c)\r\n (c1, c2) = (head s, last s)\r\n ans = map snd . L.sortOn fst . filter (isBetween.fst) . (`zip`inds) $ s\r\n isBetween c = (c1 <= c && c <= c2)\r\n\r\ninds = [1..] :: [Int]\r\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.Array\nimport Data.List (sortBy)\nimport Data.Char (ord)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>=\n \\s -> case (findJump s) of\n (cost, m, indices) -> putStrLn (show cost ++ ' ':show m) >>\n mapM_ (\\i -> putStr (show i ++ \" \")) indices >>\n putStrLn \"\"\n\nfindJump :: String -> (Int, Int, [Int])\nfindJump s = let n = length s\n a = listArray (1, n) s\n fc = head s\n lc = last s\n asc = fc <= lc -- ascending\n o c = if asc then (fc <= c && c <= lc) else (fc >= c && c >= lc)\n is = filter (\\i -> o (a!i)) [1..n]\n f a i j = case compare (a!i) (a!j) of\n EQ -> if asc then compare i j else compare j i -- required to get 1, n in the right places\n x -> x\n isSortedAsc = sortBy (f a) is\n isSorted = if asc then isSortedAsc else reverse isSortedAsc\n in\n ((abs $ (ord fc) - (ord lc)), length is, isSorted)\n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\nimport qualified Data.Text as T\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\n\nimport qualified Control.Monad as M\n\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\n\nimport System.Posix.Internals (puts)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- solution -}\n\nsolve :: B8.ByteString -> (Int, [Int])\nsolve str = (cost, finalPath)\n where\n cost = abs $ ord c0 - ord c1\n path = if c0 > c1 then reverse sortedIndexes else sortedIndexes\n finalPath = 0:path ++ [B8.length str - 1]\n\n indexes = [1 .. B8.length str - 2]\n filteredIndexes = filter (\\idx -> charMatch $ str `B8.index` idx) indexes\n sortedIndexes = sortOn (str `B8.index`) filteredIndexes\n\n c0 = B8.head str \n c1 = B8.last str\n\n charMatch c = (c <= c0 && c >= c1) || (c <= c1 && c >= c0)\n\n \n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n str <- B8.getLine <&> B8.lines <&> head\n let (cost, path) = solve str\n printf \"%d %d\\n\" cost (length path)\n M.forM_ path $ \\idx -> printf \"%d \" (idx + 1)\n printf \"\\n\"\n"}, {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\nimport qualified Data.Text as T\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\n\nimport qualified Control.Monad as M\n\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\n\nimport System.Posix.Internals (puts)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- solution -}\n\nsolve :: B8.ByteString -> (Int, [Int])\nsolve str = (cost, finalPath)\n where\n cost = abs $ ord c0 - ord c1\n path = if c0 > c1 then reverse sortedIndexes else sortedIndexes\n finalPath = 0:path ++ [B8.length str - 1]\n\n indexes = [1 .. B8.length str - 2]\n filteredIndexes = filter (\\idx -> charMatch $ str `B8.index` idx) indexes\n sortedIndexes = sortOn (str `B8.index`) filteredIndexes\n\n c0 = B8.head str \n c1 = B8.last str\n\n charMatch c = (c <= c0 && c >= c1) || (c <= c1 && c >= c0)\n\n \n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n str <- B8.getLine <&> B8.lines <&> head\n let (cost, path) = solve str\n printf \"%d %d\\n\" cost (length path)\n M.forM_ path $ \\idx -> printf \"%d \" (idx + 1)\n puts \"\"\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.Array\nimport Data.List (sortBy)\nimport Data.Char (ord)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>=\n \\s -> case (findJump s) of\n (cost, m, indices) -> putStrLn (show cost ++ ' ':show m) >>\n mapM_ (\\i -> putStr (show i ++ \" \")) indices >>\n putStrLn \"\"\n\nfindJump :: String -> (Int, Int, [Int])\nfindJump s = let n = length s\n a = listArray (1, n) s\n fc = head s\n lc = last s\n asc = fc <= lc -- ascending\n o c = if asc then (fc <= c && c <= lc) else (fc >= c && c >= lc)\n is = filter (\\i -> o (a!i)) [1..n]\n f a i j = compare (a!i) (a!j)\n isSortedAsc = sortBy (f a) is\n isSorted = if asc then isSortedAsc else reverse isSortedAsc\n in\n ((abs $ (ord fc) - (ord lc)), length is, isSorted)\n \n"}], "src_uid": "d17c9f91504e1d4c4eae7294bf09dcfc"} {"source_code": "main = getContents >>= print . solve . map read . words\n\nsolve [h,m,a,i,c,n] = min ((*0.8) $ cost c n $ (a + i * max 0 (1200 - h*60 - m))) (cost c n a)\n\ncost c n a = fromIntegral $ ((a + n - 1) `div` n) * c\n", "positive_code": [{"source_code": "\ntoMin hh mm = hh*60 + mm\n\ntill20 hh mm = if (toMin hh mm) > (toMin 20 00) then (toMin 24 00) - (toMin hh mm) + (toMin 20 00)\n else (toMin 20 00) - (toMin hh mm)\n\nfunc :: Double -> Double -> Double -> Double -> Double -> Double -> Double\nfunc hh mm h d c n = if hh >= 20 then (fromIntegral $ (ceiling $ (h / n))) * c * 0.8\n else min case1 case2 where\n case1 = (fromIntegral $ (ceiling $ ((till20 hh mm) * d + h) / n)) * c * 0.8\n case2 = (fromIntegral $ (ceiling $ (h / n))) * c\n\n\nmain :: IO ()\nmain = do\n hhmm <- getLine\n hdcn <- getLine\n let hh:mm:_ = (map read $ words hhmm)::[Double]\n let h:d:c:n:_ = (map read $ words hdcn)::[Double]\n putStrLn $ show (func hh mm h d c n)\n return ()\n"}, {"source_code": "main = interact exec\nexec = (\\[hh, mm, h, d, c, n] -> let w = max 0 $ ((20 - hh) * 60 - mm) :: Int in show $ min (fromIntegral (ceiling (fromIntegral (h + d * w) / fromIntegral n)) * fromIntegral c * 0.8) (fromIntegral $ ceiling (fromIntegral h / fromIntegral n) * c)) . map read . words\n\n-- (h + d * m) / n"}, {"source_code": "main = getContents >>= print . solve . map read . words\n\nsolve [h,m,a,i,c,n]\n | minutes >= 1200 = (*0.8) $ cost c n a\n | otherwise = min ((*0.8) $ cost c n $ (1200 - minutes) * i + a) (cost c n a)\n where minutes = h*60 + m\n\ncost c n a = fromIntegral $ ((a + n - 1) `div` n) * c\n"}, {"source_code": "module Main where\n\ninput :: IO [Double]\ninput = do\n [hh,mm] <- fmap (map read . words) getLine\n [h, d, c, n] <- fmap (map read . words) getLine\n return [hh, mm, h, d, c, n]\n\nsolve :: [Double] -> Double\nsolve [hh, mm, h, d, c, n]\n | hh >= 20 = r (c * 0.8) h\n | otherwise = min (r c h) $ r (c * 0.8) $ h + d * ((19 - hh) * 60 + 60 - mm)\n where r p hn = p * (fromIntegral $ ceiling $ hn / n)\n\nmain :: IO ()\nmain = print . solve =<< input\n"}], "negative_code": [{"source_code": "toMin hh mm = hh*60 + mm\n\ntill20 hh mm = if (toMin hh mm) > (toMin 20 00) then (toMin 24 00) - (toMin hh mm) + (toMin 20 00)\n else (toMin 20 00) - (toMin hh mm)\n\nfunc :: Double -> Double -> Double -> Double -> Double -> Double -> Double\nfunc hh mm h d c n = min case1 case2 where\n case1 = (fromIntegral $ (ceiling $ ((till20 hh mm) * d + h) / n)) * c * 0.8\n case2 = (fromIntegral $ (ceiling $ (h / n))) * c\n\n\nmain :: IO ()\nmain = do\n hhmm <- getLine\n hdcn <- getLine\n let hh:mm:_ = (map read $ words hhmm)::[Double]\n let h:d:c:n:_ = (map read $ words hdcn)::[Double]\n putStrLn $ show (func hh mm h d c n)\n return ()\n"}, {"source_code": "main = getLine >> getLine >>= print . length . fn\nfn xs = foldr (\\x f s -> case (s, x) of { (0, 'R') -> f 1; (0, 'U') -> f 2; (1, 'U') -> 'D':f 0; (2, 'R') -> 'D': f 0; (1, _) -> 'R':f s; (2, _) -> 'U':f s; (0, _)-> f s }) (const []) (xs ++ \".\") 0\n"}, {"source_code": "main = interact exec\nexec = (\\[hh, mm, h, d, c, n] -> let w = ((20 - hh) * 60 + mm) `mod` 1440 :: Int in show $ min (fromIntegral (ceiling (fromIntegral (h + d * w) / fromIntegral n)) * fromIntegral c * 0.8) (fromIntegral $ ceiling (fromIntegral h / fromIntegral n) * c)) . map read . words\n\n-- (h + d * m) / n"}, {"source_code": "main = interact exec\nexec = (\\[hh, mm, h, d, c, n] -> let w = ((20 - hh) * 60 - mm) `mod` 1440 :: Int in show $ min (fromIntegral (ceiling (fromIntegral (h + d * w) / fromIntegral n)) * fromIntegral c * 0.8) (fromIntegral $ ceiling (fromIntegral h / fromIntegral n) * c)) . map read . words\n\n-- (h + d * m) / n"}], "src_uid": "937acacc6d5d12d45c08047dde36dcf0"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.STRef(STRef, newSTRef, readSTRef, writeSTRef)\r\nimport Data.Array.ST(runSTArray, STArray)\r\nimport Data.Array.IO(IOArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, filterM, forM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\ntype Output = Bool\r\n\r\nsolve :: Integer -> Integer -> Integer -> Output\r\nsolve n m k = State.evalState (eval n m k) M.empty where\r\n\r\n\teval i j k = do \r\n\t\tm <- State.get \r\n\t\tcase M.lookup (i, j, k) m of \r\n\t\t\tNothing -> do \r\n\t\t\t\tval <- aux eval i j k \r\n\t\t\t\tmem <- State.get\r\n\t\t\t\tState.put $ M.insert (i, j, k) val mem\r\n\t\t\t\treturn val\r\n\t\t\tJust v -> return v\r\n\r\n\taux fun i j k\r\n\t\t| i == 1 = return $! k == (j - 1)\r\n\t\t| j == 1 = return $! k == (i - 1)\r\n\t\t| i > k && j > k = return $! False\r\n\t\t| i > k = fun (i-1) j (k-j)\r\n\t\t| j > k = fun i (j-1) (k-i)\r\n\t\t| otherwise = do \r\n\t\t\tx1 <- fun (i-1) j (k-j)\r\n\t\t\tif x1 then return $! True else fun i (j-1) (k-i)\r\n\r\n\r\n\r\n\r\nplotResult :: Output -> IO ()\r\nplotResult False = putStrLn \"NO\"\r\nplotResult True = putStrLn \"YES\"\r\n\r\n\r\nmain :: IO ()\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[n, m, k] <- getLine >>= return . (fmap read) . words :: IO [Integer] \r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n m k\r\n\treturn ()", "positive_code": [{"source_code": "solve [] = [\"\"]\r\nsolve (x:xs) = answer ++ solve xs \r\n where \r\n [n, m, k] = map read $ words x\r\n answer = \r\n if n * m - 1 == k \r\n then [\"YES\"]\r\n else [\"NO\"]\r\n\r\nmain = interact $ unlines . helper . lines\r\n where \r\n helper (x:xs) = solve xs"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n tail >>> map (words >>> map read >>> solve >>> bool \"NO\" \"YES\") >>> unlines\r\n\r\nsolve :: [Int] -> Bool\r\nsolve [n, m, k] = n * m - 1 == k\r\n"}], "negative_code": [], "src_uid": "8b0a9c7e997034d3ecce044b9f64aeba"} {"source_code": "import Data.List\nimport Data.Int\nimport Data.Char\nimport Control.Monad\n \nreadArray :: IO [Int64]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int64) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (read::String->Int) $ line\n\ncount :: Eq a => a -> [a] -> Int\ncount x = length . filter (==x)\n\nmerge :: [a] -> [a] -> [a]\nmerge [] ys = ys\nmerge (x:xs) ys = x:(merge ys xs)\n\ncalc :: [Int64] -> Int64\ncalc (x:y:z:xs) = (if y < x && y < z then 1 else 0) + calc (z:xs)\ncalc _ = 0\n\n\nrotate xs n = take len . drop (n `mod` len) . cycle $ xs\n where len = length xs\n\nsolve :: IO ()\nsolve = do\n n <- readInt\n b <- readArray\n let a = reverse $ sort b\n let (large,small) = splitAt ((n + 1) `div` 2) a\n let small' = if even n then rotate small 1 else small\n let res = merge large small'\n let answer = calc res\n print answer\n forM_ res $ (\\x -> print x)\n return ()\n\n\nmain :: IO ()\nmain = do\n -- t <- readInt\n -- forM_ [0..t-1] $ (\\i -> solve)\n solve\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = do\n getLine\n as <- sort . map read . words <$> getLine :: IO [Integer]\n let solution = solve as\n print $ cheap solution\n putStrLn $ unwords $ map show solution\n\nsolve as\n | even $ length as = (\\(a, b) -> [a, b]) =<< zip (as !! pred d : take (pred d) as) (drop d as)\n | otherwise = (as !! d :) $ (\\(a, b) -> [a, b]) =<< zip (take d as) (drop (succ d) as)\n where\n d = length as `div` 2\n\ncheap = length . filter (\\(a, b, c) -> a > b && b < c) . (zip3 <*> tail <*> tail . tail)\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n let (a,b) = solve n as\n print a\n putStrLn $ (unwords.map show) b\n\nsolve :: Int -> [Int] -> (Int,[Int])\nsolve n as = (r, order)\n where\n as' = sort as\n (smalls,bigs) = splitAt ((n) `div` 2) as'\n order = merge bigs smalls\n r = length $ filter (\\(a,b,c) -> a>b && b [a] -> [a]\nmerge (a:as) (b:bs) = a:b:merge as bs\nmerge as bs = as ++ bs\n"}, {"source_code": "import Data.List\n\ntrySolve :: Int -> [Int] -> Int -> Maybe [Int]\ntrySolve n as k = if k + k + 1 > n\n then Nothing\n else let\n (lows, nonlows) = splitAt k as\n (rev_his, mids) = splitAt (k+1) (reverse nonlows)\n his = reverse rev_his\n in if and $ zipWith (<) lows his\n then Just $ stitch lows his ++ mids\n else Nothing\n\nstitch :: [Int] -> [Int] -> [Int]\nstitch [] [] = []\nstitch ps (q:qs) = q : stitch qs ps\nstitch _ _ = error \"stitch: invalid args\"\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch p = let\n go low top = if low == top\n then low\n else let\n mid = div (low + top + 1) 2\n in if p mid\n then go mid top\n else go low (mid - 1)\n in go\n\nsolve :: Int -> [Int] -> (Int, [Int])\nsolve n li = let\n p k = case trySolve n li k of\n Nothing -> False\n _ -> True\n ktar = binSearch p 0 (n + 100)\n in case trySolve n li ktar of\n Nothing -> error \"binSearch failed?\"\n Just ans -> (ktar, ans)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n let (ktar, ans) = solve n (sort a)\n print ktar\n putStrLn . unwords $ map show ans\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n let (a,b) = solve n as\n print a\n putStrLn $ (unwords.map show) b\n\nsolve :: Int -> [Int] -> (Int,[Int])\nsolve n as = (r, order)\n where\n as' = sort as\n (smalls,bigs) = splitAt ((n-1) `div` 2) as'\n order = merge bigs smalls\n r = length $ filter (\\(a,b,c) -> a>b && b [a] -> [a]\nmerge (a:as) (b:bs) = a:b:merge as bs\nmerge as bs = as ++ bs\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int64]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int64) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (read::String->Int) $ line\n\ncount :: Eq a => a -> [a] -> Int\ncount x = length . filter (==x)\n\nmerge :: [a] -> [a] -> [a]\nmerge [] ys = ys\nmerge (x:xs) ys = x:(merge ys xs)\n\ncalc :: [Int64] -> Int64\ncalc (x:y:z:xs) = (if y < x && y < z then 1 else 0) + calc (z:xs)\ncalc _ = 0\n\nsolve :: IO ()\nsolve = do\n n <- readInt\n b <- readArray\n let a = reverse $ sort b\n let (large,small) = splitAt ((n + 1) `div` 2) a\n let res = merge large small\n let answer = calc res\n print answer\n forM_ res $ (\\x -> print x)\n return ()\n\n\nmain :: IO ()\nmain = do\n -- t <- readInt\n -- forM_ [0..t-1] $ (\\i -> solve)\n solve\n"}], "src_uid": "6443dffb38285b6deb74f2371d8d0cac"} {"source_code": "import Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nmain = print . solve . map readI . tail . B.words =<< B.getContents\nsolve as = sum $ zipWith ((abs .) . (-)) [1..] $ sort as :: Int64\nreadI b = fromIntegral i where Just (i,_) = B.readInt b\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Integer\nsolve n xs = sum.map toInteger.zipWith ((abs.).(-)) [1..n] $ sort xs"}, {"source_code": "import Control.Applicative\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.List\n \n\n \n\nmain = do\n\tgetLine \n\ts<- sort.map (fst.fromJust.C.readInt) . C.words <$> C.getLine\n\tprint $ sum $ map fromIntegral $ zipWith (\\a b -> abs (a-b)) s [1..]\n\t\n\t \n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate, sort)\n\nsolve :: [Integer] -> Integer\nsolve = sum . map abs . zipWith (-) [1..] . sort\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n print $ solve as\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show"}, {"source_code": "import qualified Data.List as DL\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Maybe (fromJust)\n\nf::(Integer,Integer)->Integer\nf (a,b)=abs(a-b)\n\n\nmain = do\n e1<-BC.getLine\n e2<-BC.getLine\n let xs=map (fst . fromJust . BC.readInteger) . BC.words $ e2\n xs2=DL.sort xs\n ys=zip xs2 [1..]\n print $ sum (map f ys)"}, {"source_code": "import Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= print . solve . map (fromIntegral . fst . fromJust . B.readInt) . tail . B.words\n\nsolve :: [Integer] -> Integer\nsolve = sum . map abs . zipWith (-) [1..] . sort\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.List\n \n\n \n\nmain = do\n\tgetLine \n\ts<- sort.map (fst.fromJust.C.readInt) . C.words <$> C.getLine\n\tprint $ sum $ zipWith (\\a b -> abs (a-b)) s [1..]\n\t\n\t \n"}], "src_uid": "86d5da999415fa75b3ee754a2a28605c"} {"source_code": "import Array\nimport Control.Monad\nimport Control.Applicative\n\nmark i j x = c ! (idx !! (x ! (div i 2, div j 2)))\n where \n c = listArray ((0, 0, 0), (2, 1, 1)) ['a'..]\n idx = [(0, div j' 2, mod i' 2), (1, div i' 2, mod j' 2), (2, div j' 2, div i' 2)]\n i' = mod i 4\n j' = mod j 4\n\ntile n m a b c = Just [[mark i j x | j <- [0..(2*m-1)]] | i <- [0..(2*n-1)]]\n where x = listArray ((0,0), (n-1, m-1)) $ replicate a 0 ++ replicate b 1 ++ replicate c 2\n\nsolve n m a b c \n | odd n && odd m = Nothing \n | odd n && even m = \n if a < div m 2\n then Nothing\n else (:) (take m xy) <$> solve (n-1) m (a - div m 2) b c\n | even n && odd m = \n if b < div n 2\n then Nothing\n else zipWith (:) (take n xy) <$> solve n (m-1) a (b-(div n 2)) c\n | otherwise = \n if (div a 2 * 4 + div b 2 * 4 + c*4) < n*m\n then Nothing\n else tile (div n 2) (div m 2) (div a 2) (div b 2) c\n where xy = cycle \"xxyy\"\n \nmain = do\n [n, m, a, b, c] <- map read . words <$> getLine\n mapM_ putStrLn (maybe [\"IMPOSSIBLE\"] id $ solve n m a b c)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\n\nsolve :: [String] -> [String]\nsolve = do\n [n, m, a, b, c] <- map read . words . head\n let draw flag = runST $ do\n let r = ((1, 1), (n, m))\n arr <- newArray r '*' :: ST s (STArray s (Int, Int) Char)\n let check idx@(j, i) state@(a', b', c') = do\n let nextChar z = if z == 'd' then 'a' else succ z\n if (inRange r idx) && flag /= 0\n then case flag of\n 1 -> do\n x <- if not $ inRange r (j - 1, i)\n then return 'a'\n else nextChar <$> readArray arr (j - 1, i)\n writeArray arr (j, i) x\n writeArray arr (j + 1, i) x\n check (j + 2, i) (a', b' - 1, c')\n 2 -> do\n x <- if not $ inRange r (j, i - 1)\n then return 'a'\n else nextChar <$> readArray arr (j, i - 1)\n writeArray arr (j, i) x\n writeArray arr (j, i + 1) x\n check (j, i + 2) (a' - 1, b', c')\n else return state\n let fill idx@(j, i) state = do\n let next = fill (j, i + 1)\n when (j <= n) $ do\n if i > m\n then fill (j + 1, 1) state\n else do\n x <- readArray arr idx\n if x /= '*'\n then next state\n else do\n let check z = if z == '*' then [] else [z]\n let pickup zs = do\n cs <- fmap (concatMap check) . mapM (readArray arr) $ filter (inRange r) zs\n return $ filter (`notElem` cs) \"abcd\"\n let write zs = sequence $ do\n (z, ps) <- zs\n return $ mapM_ (flip (writeArray arr) z) ps\n case state of\n (a', b', c')\n | c' > 0 -> do\n x1 <- head <$> pickup [(j - 1, i), (j, i - 1)]\n write [(x1, [idx, (j + 1, i), (j, i + 1), (j + 1, i + 1)])]\n next (a', b', c' - 1)\n | b' > 0 -> do\n x1 <- head <$> pickup [(j - 1, i), (j, i - 1), (j + 1, i - 1)]\n x2 <- head . filter (/= x1) <$> pickup [(j - 1, i + 1)]\n write [(x1, [idx, (j + 1, i)]), (x2, [(j, i + 1), (j + 1, i + 1)])]\n next (a', b' - 1, c')\n | a' > 0 -> do\n x1 <- head <$> pickup [(j, i - 1), (j - 1, i), (j - 1, i + 1)]\n x2 <- head . filter (/= x1) <$> pickup [(j + 1, i - 1)]\n write [(x1, [idx, (j, i + 1)]), (x2, [(j + 1, i), (j + 1, i + 1)])]\n next (a' - 1, b', c')\n _ -> error \"Never happens!\"\n (a', b', c') <- check (1, 1) (a, b, c)\n fill (1, 1) (a' `quot` 2, b' `quot` 2, c')\n let split = takeWhile (not . null) . map (take m) . iterate (drop m)\n split <$> getElems arr\n return . maybe (return \"IMPOSSIBLE\") draw $ do\n let (p, s) = m `quotRem` 2 ; (q, t) = n `quotRem` 2\n let flag = sum . zipWith (*) [1 ..] $ map fromEnum [s /= 0, t /= 0]\n guard $ flag /= 3\n let ds = [a * 2 - m * t, b * 2 - n * s]\n guard $ all even ds && all (0 <=) ds\n let d = sum $ map (`quot` 4) ds\n guard $ p * q <= c + d\n return flag\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\n\nsolve :: [String] -> [String]\nsolve = do\n [n, m, a, b, c] <- map read . words . head\n let draw flag = runST $ do\n let r = ((1, 1), (n, m))\n arr <- newArray r '*' :: ST s (STArray s (Int, Int) Char)\n let check idx@(j, i) state@(a', b', c') = do\n let nextChar z = if z == 'd' then 'a' else succ z\n if (inRange r idx) && flag /= 0\n then case flag of\n 1 -> do\n x <- if not $ inRange r (j - 1, i)\n then return 'a'\n else nextChar <$> readArray arr (j - 1, i)\n writeArray arr (j, i) x\n writeArray arr (j + 1, i) x\n check (j + 2, i) (a', b' - 1, c')\n 2 -> do\n x <- if not $ inRange r (j, i - 1)\n then return 'a'\n else nextChar <$> readArray arr (j, i - 1)\n writeArray arr (j, i) x\n writeArray arr (j, i + 1) x\n check (j, i + 2) (a' - 1, b', c')\n else return state\n let fill idx@(j, i) state = do\n let next = fill (j, i + 1)\n when (j <= n) $ do\n if i > m\n then fill (j + 1, 1) state\n else do\n x <- readArray arr idx\n if x /= '*'\n then next state\n else do\n let check z = if z == '*' then [] else [z]\n let pickup zs = do\n cs <- fmap (concatMap check) . mapM (readArray arr) $ filter (inRange r) zs\n return $ filter (`notElem` cs) \"abcd\"\n let write zs = sequence $ do\n (z, ps) <- zs\n return $ mapM_ (flip (writeArray arr) z) ps\n case state of\n (a', b', c')\n | c' > 0 -> do\n x1 <- head <$> pickup [(j - 1, i), (j, i - 1)]\n write [(x1, [idx, (j + 1, i), (j, i + 1), (j + 1, i + 1)])]\n next (a', b', c' - 1)\n | b' > 0 -> do\n x1 <- head <$> pickup [(j - 1, i), (j, i - 1), (j + 1, i - 1)]\n x2 <- head . filter (/= x1) <$> pickup [(j - 1, i + 1)]\n write [(x1, [idx, (j + 1, i)]), (x2, [(j, i + 1), (j + 1, i + 1)])]\n next (a', b' - 1, c')\n | a' > 0 -> do\n x1 <- head <$> pickup [(j, i - 1), (j - 1, i), (j - 1, i + 1)]\n x2 <- head . filter (/= x1) <$> pickup [(j + 1, i - 1)]\n write [(x1, [idx, (j, i + 1)]), (x2, [(j + 1, i), (j + 1, i + 1)])]\n next (a' - 1, b', c')\n _ -> error \"Never happens!\"\n (a', b', c') <- check (1, 1) (a, b, c)\n fill (1, 1) (a' `quot` 2, b' `quot` 2, c')\n let split = takeWhile (not . null) . map (take m) . iterate (drop m)\n split <$> getElems arr\n return . maybe (return \"IMPOSSIBLE\") draw $ do\n let (p, s) = m `quotRem` 2 ; (q, t) = n `quotRem` 2\n let flag = sum . zipWith (*) [1 ..] $ map fromEnum [s /= 0, t /= 0]\n guard $ flag /= 3\n let ds = [a * 2 - m * t, b * 2 - n * s]\n guard $ all even ds && all (0 <=) ds\n let d = sum $ map (`quot` 4) ds\n guard $ p * q <= c + d\n return flag\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n\n"}], "negative_code": [], "src_uid": "78f4d5e627a26effde89b3642bd9c5a8"} {"source_code": "\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n\n--\n-- K-beautiful Strings\n-- (upsolving)\n--\n-- Problem statement:\n--\n-- http://codeforces.com/contest/1493/problem/C\n--\n-- Tutorial:\n--\n-- http://codeforces.com/blog/entry/88422\n--\n\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\n\nmain = interact $ unlines . map solveTC . linePairs . tail . lines\n where\n readI s = read s :: Int\n\n linePairs [] = []\n ---------------------------- N K S ---------------------\n linePairs (strNK:strS:ls) = (lenS, modK, strS) : linePairs ls\n where\n [lenS, modK] = (map readI . words) strNK\n\nsolveTC (lenS, modK, strS) = (fromMaybe \"-1\" . maybeFirst) solutions\n where\n solutions | lenS `mod` modK /= 0 = [Nothing] :: [Maybe String]\n | isBeautiful = [Just strS]\n | otherwise = findSolutions\n\n isBeautiful = ((== 0) . cntSum . cntLack modK . last) psumsHave\n\n psumsHave = scanl cntUpdate cntZero strS\n\n findSolutions = richMidcharPositions prefLengths >>= midposSolutions\n\n prefLengths = [0 .. lenS - 1]\n\n richMidcharPositions = reverse . zip3 strS psumsHave\n --\n midposSolutions (origMidChar, origCnts, prefLen)\n = (map . fmap) (pref ++) (map midcharSolution charCandidates)\n where\n pref = take prefLen strS -- chars before the mid char\n\n suffLen = lenS - prefLen - 1 -- number of chars after the mid char\n\n charCandidates = [succ origMidChar .. 'z']\n\n midcharSolution charCandidate\n = fmap (charCandidate :) (solveSuffix (cntLack modK newCnts) suffLen)\n where\n newCnts = cntUpdate origCnts charCandidate\n\n-- Generate the lexicographically smallest string of given length and\n-- minimal occurrences for each character.\n--\nsolveSuffix :: CharCounts -> Int -> Maybe String\n--\nsolveSuffix cntsNeed len | cntA < 0 = Nothing\n | otherwise = Just . runLenDecode $ ('a',cntA) : assocs cntsNeed\n where\n cntA = len - cntSum cntsNeed\n\nrunLenDecode = foldMap d\n where\n d (ch, cnt) = replicate cnt ch\n\nmaybeFirst = getAlt . foldMap Alt -- choose first valid solution\n\n--------------------------------------------\n\ntype CharCounts = UArray Char Int\n\ncntZero = array ('a','z') [] :: CharCounts\n\ncntUpdate cnts ch = cnts // [(ch, 1 + cnts!ch)]\n\ncntSum = sum . elems\n\ncntLack k cnts = amap lackFromHave cnts\n where\n mk = (`mod` k)\n lackFromHave = mk . (k -) . mk -- Given a letter count,\n -- how many such letters we need to add?\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Either\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ntype State = Either String (Array Char Int, Int)\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n s <- take n . C.unpack <$> C.getLine\n let\n getNeed x\n | y == 0 = 0\n | otherwise = k - y\n where\n y = x `mod` k\n acc :: State -> Char -> State\n acc tt c\n | isLeft tt = Left $ c : fromLeft \"\" tt\n | m + 1 > cm && c < 'z' = Left $ choose (succ c)\n | m + 1 == cm && not (null candidates) = Left $ choose $ fst $ head candidates\n | otherwise = Right (arr', m + 1)\n where\n Right (arr, m) = tt\n arr' = arr // [(c, arr ! c - 1)]\n cm = sum $ map getNeed $ elems arr'\n choose ch = ch : ss'\n where\n a = arr' // [(ch, arr' ! ch + 1)]\n ss = concat $ map (\\(o, x) -> take (getNeed x) $ repeat o) $ assocs a\n ss' = take (m - length ss) (repeat 'a') ++ ss\n candidates = filter (\\(ch, x) -> ch > c && x `mod` k /= 0) $ assocs arr'\n a0 = accumArray (+) 0 ('a', 'z') $ zip s $ repeat 1\n result\n | n `mod` k /= 0 = \"-1\"\n | null (filter (\\x -> x `mod` k /= 0) $ elems a0) = s\n | otherwise = fromLeft \"\" $ foldl' acc (Right (a0, 0)) $ reverse s\n C.putStrLn $ C.pack result\n"}], "negative_code": [{"source_code": "\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n\n--\n-- K-beautiful Strings\n-- (upsolving)\n--\n-- Problem statement:\n--\n-- http://codeforces.com/contest/1493/problem/C\n--\n-- Tutorial:\n--\n-- http://codeforces.com/blog/entry/88422\n--\n\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as List\nimport Data.Maybe (Maybe(Just,Nothing), fromMaybe)\nimport Data.Monoid (Alt(Alt), getAlt)\nimport Data.Array.Unboxed (UArray, array)\nimport Control.Arrow((&&&))\n\nmain = interact $ unlines . map solveTC . linePairs . tail . lines\n\nlinePairs [] = []\n---------------------------- N K S ---------------------\nlinePairs (strNK:strS:ls) = (lenS, modK, strS) : linePairs ls\n where\n [lenS, modK] = (map readI . words) strNK\n\nreadI s = read s :: Int\n\nsolveTC (lenS, modK, strS) = (fromMaybe \"-1\" . maybeFirst) solutions\n where\n solutions\n | lenS `mod` modK /= 0 = [Nothing] :: [Maybe String]\n | isBeautiful modK strS = [Just strS]\n | otherwise = (map (solveFixedPrefix . charCounts $ strS) . reverse) [0 .. lenS-1]\n\n solveFixedPrefix cnts lenP = Just \"trwtretwe\" -- TODO\n\nisBeautiful modK strS = False -- TODO\n\nmaybeFirst = getAlt . foldMap Alt\n\ncharCounts = toArr . map (head &&& length) . List.group . List.sort\n where\n toArr pairs = array ('a','z') pairs :: UArray Char Int\n"}], "src_uid": "6c51676bc12bce8ba6e36b64357ef9f0"} {"source_code": "import Data.List\n\nf::[(Int,Int)]->Int\nf []=0\nf ((0,_):xs)=f xs\nf (_:xs)=1+f xs\n\nmain = do\n e<-getLine\n es<-getLine\n let xs=map read (words es)::[Int]\n ys=group $ sort xs\n zs=zip (map head ys) (map length ys)\n print $ f zs", "positive_code": [{"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [Int]\nreadInts = map parse . C8.words\n where parse s = let Just(x,_) = C8.readInt s in x\n\nmain :: IO ()\nmain = do\n _ <- getLine\n bs <- input\n let array = readInts bs\n print $ length . List.filter ((/= 0) . head)\n . List.group . List.sort $ array\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\n\nmain = do\n\tgetLine\n\tk<-length <$> group <$> filter (/=0) <$> sort <$> map read <$> words <$> getLine:: IO Int\n\tprint k\n"}, {"source_code": "import Data.List\n-- import Debug.Trace\n\nmyunique arr =\n foldr f [0] arr\n where\n f item acc = if item == head acc then acc else item:acc\n \nsolve :: String -> String\nsolve s = show $ length $ filter (/=0) $ myunique $ sort $ map read $ tail $ words s\n\nmain :: IO ()\nmain = do\n buf <- getContents\n putStrLn $ solve buf\n"}], "negative_code": [{"source_code": "import Data.List\n\nsolve :: String -> String\nsolve s = show $ length $ nub $ tail $ words s\n\nmain :: IO ()\nmain = do\n buf <- getContents\n putStrLn $ solve buf"}, {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [Int]\nreadInts = map parse . C8.words\n where parse s = let Just(x,_) = C8.readInt s in x\n\nmain :: IO ()\nmain = do\n _ <- getLine\n bs <- input\n let array = readInts bs\n print $ length . List.group . List.sort $ array\n"}], "src_uid": "0593f79604377dcfa98d2b69840ec0a6"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.STRef\nimport Data.Array.Unboxed\nimport Data.Graph hiding (buildG)\nimport Data.Tuple (swap)\nimport qualified Data.Graph as G\n\ndata Queue s = Queue { values :: STUArray s Int Int\n , front :: STRef s Int\n , rear :: STRef s Int\n }\n\nmkQueue :: Int -> ST s (Queue s)\nmkQueue size = do v <- newArray (0, size - 1) 0\n f <- newSTRef 0\n r <- newSTRef 0\n return $ Queue v f r\n\npushQueue :: Queue s -> Int -> ST s ()\npushQueue q x = do r <- readSTRef (rear q)\n writeArray (values q) r x\n writeSTRef (rear q) (r + 1)\n\npopQueue :: Queue s -> ST s Int\npopQueue q = do f <- readSTRef (front q)\n writeSTRef (front q) (f + 1)\n readArray (values q) f\n\nisEmpty :: Queue s -> ST s Bool\nisEmpty q = liftM2 (==) (readSTRef (front q)) (readSTRef (rear q))\n\nbuildG :: Int -> [(Vertex, Vertex)] -> Graph\nbuildG numVertices edges = G.buildG (1, numVertices) $ edges ++ map swap edges\n\ntestGraph0 :: Graph\ntestGraph0 = buildG 5 [(1, 2), (2, 3), (3, 4), (4, 5)]\n\nbfs :: Graph -> Vertex -> UArray Vertex Int\nbfs graph source = let vertices = bounds graph\n in runSTUArray $ do\n distance <- newArray vertices (-1) :: ST s (STUArray s Vertex Int)\n writeArray distance source 0\n queue <- mkQueue (snd vertices - fst vertices + 1)\n pushQueue queue source\n\n let unseen v = liftM (< 0) (readArray distance v)\n go = do ! u <- popQueue queue\n ! d <- readArray distance u \n forM_ (graph ! u) $ \\v -> do\n ! d' <- readArray distance v\n when (d' < 0) $ do\n writeArray distance v (d + 1)\n pushQueue queue v\n ! done <- isEmpty queue\n unless done go\n go\n return distance\n\nsolve :: Graph -> Int -> (Int, Int, Int) -> (Int, Int, Int) -> Int\nsolve graph numEdges (s1, t1, l1) (s2, t2, l2) | dist2 s1 t1 > l1 = -1\n | dist2 s2 t2 > l2 = -1\n | otherwise = max (numEdges - minimum space) 0\n where vertices@(minv, maxv) = bounds graph\n distances = listArray vertices $ map (bfs graph) (range vertices) :: Array Vertex (UArray Vertex Int)\n\n dist2 u v = distances ! u ! v\n dist4 s u v t = dist2 u v + min (dist2 s u + dist2 v t) (dist2 s v + dist2 u t)\n\n space = (dist2 s1 t1 + dist2 s2 t2) : [d1 + d2 - dist2 u v | u <- [minv .. maxv]\n , v <- [u .. maxv]\n , let ! d1 = dist4 s1 u v t1\n , d1 <= l1\n , let ! d2 = dist4 s2 u v t2\n , d2 <= l2\n ]\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n [numVertices, numEdges] <- readInts\n edges <- replicateM numEdges $ do\n [u, v] <- readInts\n return (u, v)\n [s1, t1, l1] <- readInts\n [s2, t2, l2] <- readInts\n let graph = buildG numVertices edges\n print $ solve graph numEdges (s1, t1, l1) (s2, t2, l2)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.STRef\nimport Data.Array.Unboxed\nimport Data.Graph hiding (buildG)\nimport Data.Tuple (swap)\nimport qualified Data.Graph as G\n\ndata Queue s a = Queue { values :: STArray s Int a\n , front :: STRef s Int\n , rear :: STRef s Int\n }\n\nmkQueue :: Int -> a -> ST s (Queue s a)\nmkQueue size x = do v <- newArray (1, size) x\n f <- newSTRef 1\n r <- newSTRef 1\n return $ Queue v f r\n\npushQueue :: Queue s a -> a -> ST s ()\npushQueue q x = do r <- readSTRef (rear q)\n writeArray (values q) r x\n writeSTRef (rear q) (r + 1)\n\npopQueue :: Queue s a -> ST s a\npopQueue q = do f <- readSTRef (front q)\n writeSTRef (front q) (f + 1)\n readArray (values q) f\n\nisEmpty :: Queue s a -> ST s Bool\nisEmpty q = liftM2 (==) (readSTRef (front q)) (readSTRef (rear q))\n\nbuildG :: Int -> [(Vertex, Vertex)] -> Graph\nbuildG numVertices edges = G.buildG (1, numVertices) $ edges ++ map swap edges\n\ntestGraph0 :: Graph\ntestGraph0 = buildG 5 [(1, 2), (2, 3), (3, 4), (4, 5)]\n\nbfs :: Graph -> Vertex -> UArray Vertex Int\nbfs graph source = let vertices = bounds graph\n in runSTUArray $ do\n distance <- newArray vertices (-1) :: ST s (STUArray s Vertex Int)\n writeArray distance source 0\n queue <- mkQueue (snd vertices - fst vertices + 1) 0\n pushQueue queue source\n\n let unseen v = liftM (< 0) (readArray distance v)\n go = do ! u <- popQueue queue\n ! d <- readArray distance u \n forM_ (graph ! u) $ \\v -> do\n ! d' <- readArray distance v\n when (d' < 0) $ do\n writeArray distance v (d + 1)\n pushQueue queue v\n ! done <- isEmpty queue\n unless done go\n go\n return distance\n\nsolve :: Graph -> Int -> (Int, Int, Int) -> (Int, Int, Int) -> Int\nsolve graph numEdges (s1, t1, l1) (s2, t2, l2) | dist2 s1 t1 > l1 = -1\n | dist2 s2 t2 > l2 = -1\n | otherwise = max (numEdges - minimum space) 0\n where vertices@(minv, maxv) = bounds graph\n distances = listArray vertices $ map (bfs graph) (range vertices) :: Array Vertex (UArray Vertex Int)\n\n dist2 u v = distances ! u ! v\n dist4 s u v t = dist2 u v + min (dist2 s u + dist2 v t) (dist2 s v + dist2 u t)\n\n space = (dist2 s1 t1 + dist2 s2 t2) : [d1 + d2 - dist2 u v | u <- [minv .. maxv]\n , v <- [u .. maxv]\n , let ! d1 = dist4 s1 u v t1\n , d1 <= l1\n , let ! d2 = dist4 s2 u v t2\n , d2 <= l2\n ]\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n [numVertices, numEdges] <- readInts\n edges <- replicateM numEdges $ do\n [u, v] <- readInts\n return (u, v)\n [s1, t1, l1] <- readInts\n [s2, t2, l2] <- readInts\n let graph = buildG numVertices edges\n print $ solve graph numEdges (s1, t1, l1) (s2, t2, l2)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array\nimport Data.Graph\nimport Data.Tree\nimport Data.Tuple (swap)\n\ndata CList a = CList ([a] -> [a])\n\nemptyClist :: CList a\nemptyClist = CList id\n\nappend :: a -> CList a -> CList a\nappend a (CList f) = CList $ (a :) . f\n\nsingleton :: a -> CList a\nsingleton a = append a emptyClist\n\ncat :: CList a -> CList a -> CList a\ncat (CList f) (CList g) = CList (f . g)\n\nfreeze :: CList a -> [a]\nfreeze (CList f) = f []\n\ngetDistTS :: Int -> Forest Vertex -> CList (Vertex, Int)\ngetDistTS height forest = foldl cat emptyClist $ map (getDistT height) forest\n\ngetDistT :: Int -> Tree Vertex -> CList (Vertex, Int)\ngetDistT height tree = root `cat` children\n where root = singleton (rootLabel tree, height)\n children = getDistTS (height + 1) (subForest tree)\n\ngetDistance :: Vertex -> Graph -> Array Vertex Int\ngetDistance u g = array (bounds g) . freeze . getDistTS 0 $ dfs g [u]\n\ngetDistances :: Graph -> Array Vertex (Array Vertex Int)\ngetDistances g = array (bounds g) $ [(v, getDistance v g) | v <- range (bounds g)]\n\nmmin :: [Int] -> Int\nmmin [] = -1\nmmin xs = minimum xs\n\nsolve :: Int -> Int -> Graph -> (Int, Int, Int) -> (Int, Int, Int) -> Int\nsolve n m g (s1, t1, l1) (s2, t2, l2) | dist s1 t1 > l1 = -1\n | dist s2 t2 > l2 = -1\n | r2 < 0 = max (m - r1) 0\n | otherwise = max (m - min r1 r2) 0\n where ds = getDistances g\n dist u v = ds ! u ! v\n try1 u v | dist s1 u + dist v t1 + duv > l1 = -1\n | dist s2 u + dist v t2 + duv > l2 = -1\n | otherwise = dist s1 u + dist v t1 + dist s2 u + dist v t2 + duv\n where duv = dist u v\n\n try2 u v | dist s1 u + dist v t1 + duv > l1 = -1\n | dist s2 v + dist u t2 + duv > l2 = -1\n | otherwise = dist s1 u + dist v t1 + dist s2 v + dist u t2 + duv\n where duv = dist u v\n \n r1 = dist s1 t1 + dist s2 t2\n r2 = mmin . filter (>= 0) $ [try1 u v | u <- range (bounds g), v <- range (bounds g)] ++\n [try2 u v | u <- range (bounds g), v <- range (bounds g)]\n \nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n edges <- replicateM m $ do\n [u, v] <- readInts\n return (u - 1, v - 1)\n let g = buildG (0, n - 1) (edges ++ map swap edges)\n [s1, t1, l1] <- readInts\n [s2, t2, l2] <- readInts\n print $ solve n m g (s1 - 1, t1 - 1, l1) (s2 - 1, t2 - 1, l2)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array\nimport Data.Graph\nimport Data.Tree\nimport Data.Tuple (swap)\n\ndata CList a = CList ([a] -> [a])\n\nemptyClist :: CList a\nemptyClist = CList id\n\nappend :: a -> CList a -> CList a\nappend a (CList f) = CList $ (a :) . f\n\nsingleton :: a -> CList a\nsingleton a = append a emptyClist\n\ncat :: CList a -> CList a -> CList a\ncat (CList f) (CList g) = CList (f . g)\n\nfreeze :: CList a -> [a]\nfreeze (CList f) = f []\n\ngetDistTS :: Int -> Forest Vertex -> CList (Vertex, Int)\ngetDistTS height forest = foldl cat emptyClist $ map (getDistT height) forest\n\ngetDistT :: Int -> Tree Vertex -> CList (Vertex, Int)\ngetDistT height tree = root `cat` children\n where root = singleton (rootLabel tree, height)\n children = getDistTS (height + 1) (subForest tree)\n\ngetDistance :: Vertex -> Graph -> Array Vertex Int\ngetDistance u g = array (0, n) . freeze . getDistTS 0 $ dfs g [u]\n where (0, n) = bounds g\n\ngetDistances :: Graph -> Array Vertex (Array Vertex Int)\ngetDistances g = array (0, n) $ [(v, getDistance v g) | v <- [0 .. n]]\n where (0, n) = bounds g\n\nsolve :: Int -> Int -> Graph -> (Int, Int, Int) -> (Int, Int, Int) -> Int\nsolve n m g (s1, t1, l1) (s2, t2, l2) | dist s1 t1 > l1 = -1\n | dist s2 t2 > l2 = -1\n | otherwise = max (m - min r1 r2) 0\n where (0, n) = bounds g\n ds = getDistances g\n dist u v = ds ! u ! v\n try u v = dist u v + min (dist s1 u + dist v t1 + dist s2 u + dist v t2) (dist s1 u + dist v t1 + dist s2 v + dist u t2)\n \n r1 = dist s1 t1 + dist s2 t2\n r2 = minimum [try u v | u <- [0 .. n], v <- [0 .. n]]\n \nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n edges <- replicateM m $ do\n [u, v] <- readInts\n return (u - 1, v - 1)\n let g = buildG (0, n - 1) (edges ++ map swap edges)\n [s1, t1, l1] <- readInts\n [s2, t2, l2] <- readInts\n print $ solve n m g (s1 - 1, t1 - 1, l1) (s2 - 1, t2 - 1, l2)\n"}], "src_uid": "3c5e1f11e6af3821ed8c28f15e429def"} {"source_code": "import Control.Monad (replicateM)\n\ndata Tree = Val Int|New Int|B1 Int Int Tree|B2 Int Int Int Tree Tree deriving Show\n\nbranch :: Int -> Int -> (Tree,Int)\nbranch i 1 = (Val i,0)\nbranch i 2 = (B1 1 i (New 1),1)\nbranch i n = (B2 h1 h2 i (New h1) (New h2),h2) where\n h2 = div n 2\n h1 = h2 + mod n 2 - 1\n\n\n{-\nmaxNew :: Tree -> Int\nmaxNew (Val _) = 0\nmaxNew (New n) = n\nmaxNew (B1 _ t) = maxNew t\nmaxNew (B2 _ t1 t2 ) = max (maxNew t1) (maxNew t2)\n-}\n\nmodifyBy :: Int -> Tree -> (Tree,Int)\nmodifyBy i (New n) = branch i n\nmodifyBy i t@(Val _) = (t,0)\nmodifyBy i (B1 tl k t) =(B1 mx k nt,mx) where\n (nt,mx) = modifyBy i t\nmodifyBy i (B2 t1l t2l k t1 t2)\n |t2l > t1l = let\n (nt2,nt2l) = modifyBy i t2\n in (B2 t1l nt2l k t1 nt2,max t1l nt2l)\n |otherwise = let\n (nt1,nt1l) = modifyBy i t1\n in (B2 nt1l t2l k nt1 t2,max t2l nt1l)\n\n\nmodBy :: Int -> Tree -> Tree\nmodBy i t = fst $ modifyBy i t\n\n\ntoList :: Tree -> [Int]\ntoList (Val k) = [k]\ntoList (New _) = []\ntoList (B1 _ k t) = [k]++(toList t)\ntoList (B2 _ _ k t1 t2) = (toList t1)++[k]++(toList t2)\n\n\nfinRun :: Int -> [Int]\nfinRun n= toList $ foldl (\\t i -> modBy i t) (New n) [1..n]\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\nmain :: IO()\nmain = do\n x <- getInt\n ls <- replicateM x getInt\n mapM_ (\\x -> putStrLn $ unwords $ map show $ finRun x) ls\n", "positive_code": [{"source_code": "import qualified Data.Set as S\nimport Control.Monad\n--import Data.Monoid\nimport Data.List\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n putStrLn $ (unwords.map show) $ solve n\n\nsolve :: Int -> [Int]\nsolve n = clean $ consume (S.singleton (Event 1 n n))\n\ndata Event = Event {\n getL :: Int,\n getR :: Int,\n getLength :: Int\n} deriving (Eq, Show)\n\ninstance Ord Event where\n compare (Event l _ ln) (Event l2 _ ln2) =\n (compare ln2 ln) `mappend` (compare l l2)\n\nconsume :: S.Set Event -> [Int]\nconsume s\n | S.null s = []\n | otherwise = n : consume s''\n where\n (Event l r ln,s') = S.deleteFindMin s\n n = (l + r) `div` 2\n evs = if ln == 1\n then [] else if ln == 2 then [Event r r 1]\n else [Event l (n-1) ((ln `div` 2) - (fromEnum $ even ln)),Event (n+1) r (ln `div` 2)]\n s'' = S.union s' (S.fromList evs)\n\nclean :: [Int] -> [Int]\nclean xs =map fst $ sortOn snd $ zip [1..] xs\n"}], "negative_code": [], "src_uid": "25fbe21a449c1ab3eb4bdd95a171d093"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\nimport qualified Control.Monad.Trans.Maybe as MT\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Int\nsolve n as = answer\n where\n asSet = S.fromList $ L.zip as [1..]\n\n answer :: Int\n answer = MB.fromMaybe 0 . L.find canPlay $ reverse [1 .. n]\n\n canPlay :: Int -> Bool\n canPlay k = flip S.evalState asSet $ do\n tracingM \"k\" k\n answer <- MT.runMaybeT $ M.forM_ [1..k] $ \\i -> do\n st <- S.get\n tracingM \"st\" st\n aliceX <- MT.MaybeT . S.gets $ S.lookupLE (k - i + 1, n)\n tracingM \"aliceX\" aliceX\n S.modify $ S.delete aliceX\n S.modify $ S.deleteMin\n tracingM \"answer\" answer\n return $ MB.isJust answer\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\n----- --------------------------------------------------------------\r\ndata TC = TC {n :: Int, as :: [Int]}\r\n\r\ntype Output = Int\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n as <- n >< int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = binarySearch check 0 (n + 1) -- [0 .. n] >$> filter check >>> maximum\r\n where\r\n check 0 = True\r\n check k = [1 .. k] >$> reverse >>> map (\\i -> alice i >=> pure . bob i) >>> foldl1 (>=>) >>> ($ as) >>> isJust\r\n\r\n alice :: Int -> [Int] -> Maybe [Int]\r\n alice v xs = do\r\n xs <- pure $ filter (<= v) xs\r\n guard $ not (null xs)\r\n return $ delete (maximum xs) xs\r\n\r\n bob :: Int -> [Int] -> [Int]\r\n bob _ [] = []\r\n bob v xs =\r\n let m = minimum xs\r\n in m + v : delete m xs\r\n\r\n-- find largest x \\in [l, r) s.t. p x\r\nbinarySearch :: Integral a => (a -> Bool) -> a -> a -> a\r\nbinarySearch p l r\r\n | l + 1 == r = l\r\n | p m = binarySearch p m r\r\n | otherwise = binarySearch p l m\r\n where\r\n m = (l + r) `div` 2\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput ix = showB\r\n\r\n----- -------------------------------------------------------------\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner input >>> solve >>> output 0\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\r\n\r\n----- Template ----------------------------------------------------------------\r\n\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\napplyN :: Int -> (a -> a) -> a -> a\r\napplyN 0 f = id\r\napplyN n f = applyN (n - 1) f . f\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- readInt' <$> B.getLine\r\n replicateM_ testCases testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n getLine\r\n vs <- map readInt' . B.words <$> B.getLine\r\n print $ solve (sort vs)\r\n\r\nreadInt' :: B.ByteString -> Int\r\nreadInt' = maybe 0 fst . B.readInt\r\n\r\nsolve :: [Int] -> Int\r\nsolve s = case [k | k <- [1..(min ((length s + 1) `div` 2) (length (takeWhile (<= 1) s)))], winnable k s] of\r\n [] -> 0\r\n ls -> maximum ls\r\n where winnable :: Int -> [Int] -> Bool\r\n winnable k vs = all (uncurry (<=)) $ drop (k-1) vs `zip` [1..k]\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Debug.Trace\r\n\r\n----- --------------------------------------------------------------\r\ndata TC = TC {n :: Int, as :: [Int]}\r\n\r\ntype Output = Int\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n as <- n >< int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..} = [0 .. n] >$> filter check >>> maximum\r\n where\r\n check 0 = True\r\n check k = [1 .. k] >$> reverse >>> map (\\i -> alice i >=> pure . bob i) >>> foldl1 (>=>) >>> ($ as) >>> isJust\r\n\r\n alice :: Int -> [Int] -> Maybe [Int]\r\n alice v xs = do\r\n xs <- pure $ filter (<= v) xs\r\n guard $ not (null xs)\r\n return $ delete (maximum xs) xs\r\n\r\n bob :: Int -> [Int] -> [Int]\r\n bob _ [] = []\r\n bob v xs =\r\n let m = minimum xs\r\n in m + v : delete m xs\r\n\r\n-- find largest x \\in [l, r) s.t. p x\r\nbinarySearch :: Integral a => (a -> Bool) -> a -> a -> a\r\nbinarySearch p l r\r\n | l + 1 == r = l\r\n | p m = binarySearch p m r\r\n | otherwise = binarySearch p l m\r\n where\r\n m = (l + r) `div` 2\r\n\r\noutput :: Int -> Output -> C.ByteString\r\noutput ix = showB\r\n\r\n----- -------------------------------------------------------------\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner input >>> solve >>> output 0\r\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\r\n\r\n----- Template ----------------------------------------------------------------\r\n\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- helpers\r\n(>$>) = flip ($)\r\n\r\ninfixl 0 >$>\r\n\r\napplyN :: Int -> (a -> a) -> a -> a\r\napplyN 0 f = id\r\napplyN n f = applyN (n - 1) f . f\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "import Data.Char\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nsolve k as = if (foldr (&&) True (zipWith (>=) (replicate k 1 ++ [2..k]) as)) then k else solve (k-1) as \r\n\r\n\r\nloop = do\r\n _ <- getLine\r\n as <- sort <$> map read <$> words <$> getLine\r\n let k = (length as +1)`div`2\r\n print (solve k as)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_ t loop\r\n\r\n\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- readInt' <$> B.getLine\r\n replicateM_ testCases testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n getLine\r\n vs <- map readInt' . B.words <$> B.getLine\r\n print $ solve vs\r\n\r\nreadInt' :: B.ByteString -> Int\r\nreadInt' = maybe 0 fst . B.readInt\r\n\r\nsolve :: [Int] -> Int\r\nsolve s = case [k | k <- [1..length s + 1 `div` 2], winnable k (sort s)] of\r\n [] -> 0\r\n ls -> maximum ls\r\n where winnable :: Int -> [Int] -> Bool\r\n winnable k vs = all (uncurry (<=)) $ drop (k-1) vs `zip` [1..k]\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- readInt' <$> B.getLine\r\n replicateM_ testCases testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n getLine\r\n vs <- map readInt' . B.words <$> B.getLine\r\n print $ solve vs\r\n\r\nreadInt' :: B.ByteString -> Int\r\nreadInt' = maybe 0 fst . B.readInt\r\n\r\nsolve :: [Int] -> Int\r\nsolve s = case map snd $ takeWhile winnable $ sort s `zip` concatMap (replicate 2) [1..] of\r\n [] -> 0\r\n ls -> maximum ls\r\n where winnable :: (Int, Int) -> Bool\r\n winnable (v, p) = v <= p\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- readInt' <$> B.getLine\r\n replicateM_ testCases testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n getLine\r\n vs <- map readInt' . B.words <$> B.getLine\r\n print $ solve vs\r\n\r\nreadInt' :: B.ByteString -> Int\r\nreadInt' = maybe 0 fst . B.readInt\r\n\r\nsolve :: [Int] -> Int\r\nsolve s = case map snd $ filter winnable $ sort s `zip` drop 1 (concatMap (replicate 2) [1..]) of\r\n [] -> 0\r\n ls -> maximum ls\r\n where winnable :: (Int, Int) -> Bool\r\n winnable (v, p) = v <= p\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nmain :: IO ()\r\nmain = do\r\n testCases <- readInt' <$> B.getLine\r\n replicateM_ testCases testCase\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n getLine\r\n vs <- map readInt' . B.words <$> B.getLine\r\n print $ solve vs\r\n\r\nreadInt' :: B.ByteString -> Int\r\nreadInt' = maybe 0 fst . B.readInt\r\n\r\nsolve :: [Int] -> Int\r\nsolve s = case map snd $ filter winnable $ sort s `zip` concatMap (replicate 2) [1..] of\r\n [] -> 0\r\n ls -> maximum ls\r\n where winnable :: (Int, Int) -> Bool\r\n winnable (v, p) = v <= p\r\n\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\nimport qualified Control.Monad.Trans.Maybe as MT\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Int\nsolve n as = answer\n where\n asSet = S.fromList $ L.zip as [1..]\n\n answer :: Int\n answer = MB.fromMaybe 0 . L.find canPlay $ reverse [1 .. n]\n\n canPlay :: Int -> Bool\n canPlay k = flip S.evalState asSet $ do\n tracingM \"k\" k\n answer <- MT.runMaybeT $ M.forM_ (reverse [1 .. k]) $ \\i -> do\n st <- S.get\n tracingM \"st\" st\n aliceX <- MT.MaybeT . S.gets $ S.lookupLE (k - i + 1, n)\n tracingM \"aliceX\" aliceX\n S.modify $ S.delete aliceX\n S.modify $ S.deleteMin\n tracingM \"answer\" answer\n return $ MB.isJust answer\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n"}], "src_uid": "0682d5ee1b5b160ece449c4676a369a7"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nmodule Main where\n\nimport Control.Applicative ( liftA2 )\nimport Control.Monad.State\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Foldable\nimport Data.Function ( (&)\n , on\n )\nimport Data.Maybe ( fromJust )\n\ntype Scanner = State [C.ByteString]\n\nscan :: Scanner a -> C.ByteString -> a\nscan input = evalState input . C.lines\n\nline :: Scanner C.ByteString\nline = get >>= \\case\n [] -> error \"eof\"\n s : ss -> put ss >> return s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case\n [] -> return []\n _ -> liftA2 (:) s $ many s\n\nmain :: IO ()\nmain = C.interact solve\n\nsolve :: C.ByteString -> C.ByteString\nsolve input = input & scan parse & map (format . answer) & C.unlines\n\nparse :: Scanner [(Int, A.Array Int Int)]\nparse = do\n _ <- line\n many $ do\n n <- int <$> line\n xs <- A.listArray (1, n) . map int . C.words <$> line\n return (n, xs)\n where\n int :: C.ByteString -> Int\n int = fst . fromJust . C.readInt\n\nformat :: [Int] -> C.ByteString\nformat = C.pack . unwords . map show\n\nanswer :: (Int, A.Array Int Int) -> [Int]\nanswer (n, xs) = reverse\n [ times `mod` value\n | ((times, value), _) <- take n . iterate (\\(_, xs') -> toPair xs') $ toPair xs\n ]\n where\n toPair :: A.Array Int Int -> ((Int, Int), A.Array Int Int)\n toPair as = (it, as')\n where\n it = iteration as\n as' = uncurry rotate it as\n\niteration :: Ord a => A.Array Int a -> (Int, a)\niteration xs = maximumBy (compare `on` snd) (A.assocs xs)\n\nrotate :: Int -> Int -> A.Array Int a -> A.Array Int a\nrotate times till =\n A.ixmap (1, till - 1) (\\i -> ((i + times) `mod` (till + 1)) + ((i + times) `div` (till + 1)))\n", "positive_code": [{"source_code": "import Data.List (elemIndex)\r\nimport Data.Maybe (fromJust)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ncShift :: Int -> [a] -> [a]\r\ncShift 0 = id\r\ncShift i = uncurry (flip (++)) . splitAt i\r\n\r\nsolve :: InType -> OutType\r\nsolve = reverse . go\r\n where go [] = []\r\n go xs = let l = length xs\r\n i = (fromJust (elemIndex l xs) + 1) `mod` l\r\n in i : go (init (cShift i xs))\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showArr . solve . receive) . chunksOf 2 . tail . lines\r\n"}, {"source_code": "import Data.List (elemIndex)\r\nimport Data.Maybe (fromJust)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ncShift :: [a] -> Int -> [a]\r\ncShift = go []\r\n where go acc xs 0 = xs ++ reverse acc\r\n go acc (x : xs) i = go (x : acc) xs (i - 1)\r\n go _ _ _ = undefined\r\n\r\nsolve :: InType -> OutType\r\nsolve xs = reverse $ go xs\r\n where go [] = []\r\n go xs = let l = length xs\r\n i = fromJust $ elemIndex l xs\r\n in (i + 1) `mod` l : go (take (l - 1) (cShift xs (i + 1)))\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showArr . solve . receive) . chunksOf 2 . tail . lines\r\n"}], "negative_code": [{"source_code": "import Data.List (elemIndex)\r\nimport Data.Maybe (fromJust)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ncShift :: [a] -> Int -> [a]\r\ncShift = go []\r\n where go acc xs 0 = xs ++ reverse acc\r\n go acc (x : xs) i = go (x : acc) xs (i - 1)\r\n go _ _ _ = undefined\r\n\r\nsolve :: InType -> OutType\r\nsolve xs = reverse $ go xs\r\n where go [] = []\r\n go xs = let l = length xs\r\n i = fromJust $ elemIndex l xs\r\n in i + 1 : go (take (l - 1) (cShift xs (i + 1)))\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showArr . solve . receive) . chunksOf 2 . tail . lines\r\n"}, {"source_code": "import Data.List (elemIndex)\r\nimport Data.Maybe (fromJust)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ncShift :: [a] -> Int -> [a]\r\ncShift = go []\r\n where go acc xs 0 = xs ++ reverse acc\r\n go acc (x : xs) i = go (x : acc) xs (i - 1)\r\n go _ _ _ = undefined\r\n\r\nsolve :: InType -> OutType\r\nsolve xs = reverse $ go xs\r\n where go [] = []\r\n go xs = let i = fromJust $ elemIndex (length xs) xs\r\n pref = take i xs\r\n suf = drop (i + 1) xs\r\n in i + 1 : go (cShift (pref ++ suf) i)\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showArr . solve . receive) . chunksOf 2 . tail . lines\r\n"}, {"source_code": "import Data.List (elemIndex)\r\nimport Data.Maybe (fromJust)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\nsolve :: InType -> OutType\r\nsolve xs = reverse $ go xs\r\n where go [] = []\r\n go xs = let i = fromJust $ elemIndex (length xs) xs\r\n pref = take i xs\r\n suf = drop (i + 1) xs\r\n in i + 1 : go (pref ++ suf)\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showArr . solve . receive) . chunksOf 2 . tail . lines\r\n"}], "src_uid": "a83aaaa8984d1a6dda1adf10127b7abc"} {"source_code": "main=interact$show.f.map read.words\nf[l,p,q]=l*p/(p+q)", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n c <- getLine\n let l = read a :: Float\n p = read b :: Float\n q = read c :: Float\n print (l / (p + q) * p)\n"}, {"source_code": "module Main\n where\n \n-- toInts :: [String] -> [Int]\n-- toInts = map read\n-- \n-- splitStr :: Int -> String -> [Int]\n-- splitStr n (' ':xs) = n : (splitStr 0 xs)\n-- splitStr n ('1':xs) = splitStr (n * 10 + 1) xs\n-- splitStr n ('2':xs) = splitStr (n * 10 + 2) xs\n-- splitStr n ('3':xs) = splitStr (n * 10 + 3) xs\n-- splitStr n ('4':xs) = splitStr (n * 10 + 4) xs\n-- splitStr n ('5':xs) = splitStr (n * 10 + 5) xs\n-- splitStr n ('6':xs) = splitStr (n * 10 + 6) xs\n-- splitStr n ('7':xs) = splitStr (n * 10 + 7) xs\n-- splitStr n ('8':xs) = splitStr (n * 10 + 8) xs\n-- splitStr n ('9':xs) = splitStr (n * 10 + 9) xs\n-- splitStr n ('0':xs) = splitStr (n * 10 + 0) xs\n-- splitStr n [] = [n]\n-- \n-- split s = splitStr 0 s\n-- \n-- input = do line <- getLine\n-- sep <- return (split line)\n-- return sep\n\n-- solve :: Num -> Num -> Num -> Num\nsolve l a b = l * a / (a + b)\n\nmain = do strl <- getLine\n l <- return (read strl)\n stra <- getLine\n a <- return (read stra)\n strb <- getLine\n b <- return (read strb)\n solution <- return (solve l a b)\n strsol <- return (show solution)\n putStrLn strsol\n"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve [l,p,q] = p * l / (p + q)\n"}, {"source_code": "import Control.Applicative\nmain = do\n l <- to_f <$> getLine\n p <- to_f <$> getLine\n q <- to_f <$> getLine\n print $ l * p / (p + q)\n\nto_f :: String -> Double\nto_f str = read str :: Double\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Float] -> Float\nsolve [l, p, q] = l * p / (p + q)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n l <- readLn\n p <- readLn\n q <- readLn\n\n print $ p*l/(p+q)\n"}, {"source_code": "import Control.Monad\nimport System.IO\nimport Data.Char\nimport Data.Maybe\nimport Data.Ix\nimport Data.List\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map \nimport qualified Data.Vector as Vector\n\nreadInt = read :: String -> Int\ninfixl 5 |>\na |> f = f a\n\ninfixl 5 ||>\nm ||> f = liftM f m\n\nreadLines :: Int -> IO [String]\nreadLines 0 = return []\nreadLines n = do\n\tl1 <- getLine\n\tlns <- readLines (n - 1)\n\treturn $ l1 : lns\n\nmain = do\n\tl <- getLine ||> (read) ||> (+ 0.0)\n\tp <- getLine ||> (read) ||> (+ 0.0)\n\tq <- getLine ||> (read) ||> (+ 0.0)\n\tt <- return $ l / (p + q)\n\n\tputStr $ show $ p * t\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = ( (\\[c,a,b] -> a * c / (a+b) ). (map (read :: String -> Double) ) . lines) <$> getContents >>= print\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve :: [Double] -> Double\nsolve [c,a,b] = ( a / (a+b) ) * c\n\nmain = ( solve . (map (read :: String -> Double) ) . lines) <$> getContents >>= print\n"}, {"source_code": "module Main (main)\n where\n \nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = replicateM 3 readLn >>= print . solve\n where solve [l, p, q] = l*p/(p + q)"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n l <- readLn :: IO Double\n p <- readLn :: IO Double\n q <- readLn :: IO Double\n let t = (3 * l) / (p + q)\n print $ (t / 3) * p\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \nmain=do\t \n\t[n,a,b]<- map read.words <$> getContents:: IO [Int] \n\tprint $ (fromIntegral a)/(fromIntegral (a+b)) *(fromIntegral n)\n"}, {"source_code": "main = interact $ show. (\\ (d:p:q:[]) -> d * p / (p + q)). map read. words\n"}, {"source_code": "main = interact $ (++ \"\\n\"). show. (\\ (d:p:q:[]) -> d * p / (p + q)). map read. words\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\n\nmain = do\n [l, h, v] <- replicateM 3 $ read <$> getLine\n print $ l / (h+v) * h\n"}, {"source_code": "main = do\n line <- getLine\n let l = read(line) :: Double\n line <- getLine\n let p = read(line) :: Double\n line <- getLine\n let q = read(line) :: Double\n\n let d = (p * l) / (p + q)\n\n print d\n"}, {"source_code": "main :: IO ()\nmain = interact parse\n\nparse input =\n let (l:p:q:_) = map read $ lines input\n t = l / (p + q)\n pt = p * t\n in show pt\n"}, {"source_code": "main = do\n a <- getLine\n b <- getLine\n c <- getLine\n let s = read a :: Float\n let v1 = read b :: Float\n let v2 = read c :: Float\n putStrLn $ show $ s * v1 / (v1 + v2)"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents \nmain = do\n l <- readLn::IO Double\n p <- readLn::IO Double\n q <- readLn::IO Double\n print $ p*l/(p+q)\n"}], "negative_code": [], "src_uid": "6421a81f85a53a0c8c63fbc32750f77f"} {"source_code": "import Data.List ( sort )\r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:y:xs) = func y : solve xs\r\n\r\nfunc :: String -> String\r\nfunc y = func' $ take ((n-1) `div` 2) (zip b c)\r\n where\r\n a = (sort.map read.words) y\r\n b = drop 1 (scanl1 (+) a)\r\n c = reverse $ scanr1 (+) a\r\n n = length y\r\n func' [] = \"NO\"\r\n func' (x:xs) = if uncurry (<) x then \"YES\" else func' xs\r\n\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines\r\n\r\n\r\n-- >>> reverse$ scanr1 (+) [1,2,3,4,5]\r\n-- [5,9,12,14,15]\r\n", "positive_code": [{"source_code": "import Data.List (sort)\r\n\r\nmain :: IO ()\r\nmain = \r\n let f 0 = return ()\r\n f t = solve >> f (t - 1)\r\n in readInt <$> getLine >>= f\r\n\r\nsolve :: IO ()\r\nsolve = readInt <$> getLine >>= \\ n ->\r\n splitAt ((n+1) `div` 2) . sort . map readInt . words <$> getLine >>= \\(l, r) ->\r\n putStrLn . check (sum $ take 2 l) (last r) (drop 2 l) . tail $ reverse r\r\n\r\ncheck a b [] _ = if a < b then \"YES\" else \"NO\"\r\ncheck a b _ [] = if a < b then \"YES\" else \"NO\"\r\ncheck a b (l:ls) (r:rs) = if a < b then \"YES\" else check (a + l) (b + r) ls rs\r\n \r\nreadInt :: String -> Int\r\nreadInt = read"}], "negative_code": [{"source_code": "import Data.List ( sort )\r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:y:xs) = func y : solve xs\r\n\r\nfunc :: String -> String\r\nfunc y = func' $ take ((n-1) `div` 2) (zip b c)\r\n where\r\n a = (sort.map read.words) y\r\n b = drop 1 (scanl1 (+) a)\r\n c = reverse $ scanr1 (+) [1,2,3,4,5]\r\n n = length y\r\n func' [] = \"NO\"\r\n func' (x:xs) = if uncurry (<) x then \"YES\" else func' xs\r\n\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines\r\n\r\n\r\n-- >>> drop 1 (scanl1 (+) [1,2,3,4,5])\r\n-- [3,6,10,15]\r\n\r\n-- >>> reverse$ scanr1 (+) [1,2,3,4,5]\r\n-- [5,9,12,14,15]\r\n"}, {"source_code": "import Data.List ( sort )\r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:y:xs) = func y : solve xs\r\n\r\nfunc :: String -> String\r\nfunc y = func' $ take ((n-2) `div` 2) (zip b c)\r\n where\r\n a = (sort.map read.words) y\r\n b = drop 1 (scanl1 (+) a)\r\n c = reverse $ scanr1 (+) [1,2,3,4,5]\r\n n = length y\r\n func' [] = \"NO\"\r\n func' (x:xs) = if uncurry (<) x then \"YES\" else func' xs\r\n\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines"}, {"source_code": "import Data.List ( sort )\r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:y:xs) = func y : solve xs\r\n\r\nfunc :: String -> String\r\nfunc y = if head a + (head.tail) a < last a then \"YES\" else \"NO\"\r\n where \r\n a :: [Int]\r\n a = (sort.map read.words) y\r\n\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines\r\n"}], "src_uid": "4af59df1bc56ca8eb5913c2e57905922"} {"source_code": "\n\nmain = interact $ show . distance . (map . map) read . map words . lines\n\ndistance :: [[Float]] -> Float\ndistance (x:ys) = last x * distance' ys / 50.0\n where\n distance' :: [[Float]] -> Float\n distance' xs = sum $ zipWith (\\a b -> dbetweenp (abs (head a - head b)) (abs (last a - last b))) xs (drop 1 xs)\n dbetweenp w h = sqrt $ w^2 + h^2", "positive_code": [{"source_code": "import Control.Monad\n\nsolve [] = 0\nsolve [a] = 0\nsolve (a:b:cs) = solve (b:cs) + d\n where dx = fromIntegral $ (a!!0) - (b!!0)\n dy = fromIntegral $ (a!!1) - (b!!1)\n d = sqrt . abs $ dx * dx + dy * dy\n\nmain = do\n [n, k] <- fmap (map read . words) getLine\n lst <- forM [1..n] $ \\_ -> fmap (map read . words) getLine :: IO [Int]\n print $ solve lst * k / 50\n\n-- vim: set expandtab:\n"}, {"source_code": "getWords = fmap (map read . words) getLine \n\ndist (x1, y1) (x2, y2) = sqrt $ (x2-x1)**2 + (y2-y1)**2\n\nreadPair = (\\[x, y] -> (x, y)) . map read . words\n\nmain = do\n\t[n, k] <- getWords\n\tps <- fmap (map readPair . lines) getContents\n\tlet l = sum $ zipWith dist ps (tail ps)\n\tprint $ k*l/50\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nmain = do\n [n,k] <- map (read :: String -> Int) . words <$> getLine\n as <- replicateM n (map (read :: String -> Double) . words <$> getLine)\n let s = (fromIntegral k) * ( sum $ zipWith (\\x y -> sqrt . sum . map (**2.0) . zipWith (-) x $ y) as $ tail as )\n print $ s / 50.0\n\n"}, {"source_code": "module Main where\n\n -- Java-\u043a\u0440\u0435\u0441\u044c\u0442\u044c\u044f\u043d\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0441\u0442\u0440\u0430\u0434\u0430\u0442\u044c!\n \n import Data.List (foldl')\n \n type Point = (Double, Double)\n \n rho :: Point -> Point -> Double\n rho x y = sqrt ( (fst x - fst y)**2 + (snd x - snd y)**2 )\n \n lengths :: [Point] -> (Double, Point)\n lengths xs = foldl' summate (0, head xs) (tail xs)\n where summate (l, p) p' = (l + rho p p', p')\n \n main :: IO ()\n main = do\n [n, k] <- fmap (map read . words) getLine :: IO [Int]\n points <- sequence $\n replicate n $ do\n [x, y] <- fmap (map read . words) getLine :: IO [Double]\n return (x, y)\n putStrLn . show $ if (not . null) points\n then fst (lengths points) * fromIntegral k / 50\n else 0\n"}, {"source_code": "import List\n\ntype Point = (Double, Double)\n\nspeed = 50\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nreadPoint :: IO Point\nreadPoint = do\n [x, y] <- Main.reads\n return (x, y)\n\ndist :: Point -> Point -> Double\ndist (x1, y1) (x2, y2) = sqrt ((x1-x2)^2 + (y1-y2)^2)\n\nnear :: [a] -> [(a, a)]\nnear (x:y:[]) = [(x, y)]\nnear (x:y:xs) = (x, y):(near (y:xs))\nnear _ = error \"near: List length < 2!\"\n\nsolve :: [Point] -> Double\nsolve ps = sum (map (uncurry dist) (near ps))\n\nmain :: IO ()\nmain = do\n [n, k] <- Main.reads\n ans <- sequence (map (\\n -> readPoint) [1..n])\n print (k * (solve ans) / speed)"}, {"source_code": "\nsigLength (a:b:rest) =\n let dx = fst a - fst b\n dy = snd a - snd b\n d = sqrt $ dx * dx + dy * dy\n in d + sigLength (b:rest) -- lazyness may get TLE\nsigLength _ = 0.0\n\nsolve ((_, k):ps) = (sigLength ps) / 50.0 * k\n\nmain = interact $ show.solve.map ((\\[a, b] -> (read a, read b)).words).lines"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = (*) <$> ((!!1) . map read . words <$> getLine) <*> (solve <$> (map (map read . words) . lines <$> getContents)) >>= print\n\nsolve :: [[Double]] -> Double\nsolve xys = sum [ sqrt ((x - x') ** 2 + (y - y') ** 2) | ([x, y], [x', y']) <- zip xys (tail xys) ] / 50\n"}, {"source_code": "import Control.Monad\nmain = do\n [n,k] <- fmap (map read . words) getLine\n ps <- replicateM n $ fmap (map read . words) getLine\n print $ fromIntegral k * sum (map dist (pairs ps)) / 50\ndist ([x1,y1],[x2,y2]) = sqrt ((x2-x1)^2 + (y2-y1)^2)\npairs (a:b:cs) = (a,b) : pairs (b:cs)\npairs _ = []"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nreadP = do\n [x,y] <- (map read . words) `fmap` getLine\n return (x :: Double, y)\n \nmain = do\n [n,k] <- (map read . words) `fmap` getLine\n cs <- replicateM n readP\n print (answer cs k)\n\nanswer cs k = sum (zipWith dist cs (tail cs)) / 50 * (fromIntegral k)\n where\n dist (x1, y1) (x2, y2) = sqrt ((x1 - x2)^2 + (y1 - y2)^2)"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nreadNums :: (Num a, Read a) => IO [a]\nreadNums = map read . words <$> getLine\n\ndistance :: (Double, Double) -> (Double, Double) -> Double\ndistance (y1, x1) (y2, x2) = sqrt $ (y1 - y2) ^ 2 + (x1 - x2) ^ 2\n\nmain :: IO ()\nmain = do\n [n, k :: Int] <- readNums\n as <- replicateM n $ do\n [a, b :: Double] <- readNums\n return (a, b)\n let !d = sum $ zipWith distance as (tail as)\n printf \"%08f\\n\" $ d * fromIntegral k / 50\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nsolve :: [[Integer]] -> BS.ByteString\nsolve xs = BS.pack.show $ ( ret * fromIntegral b ) / 50.0 where \n\t( first , rest ) = ( head xs , tail xs ) \n\t( a , b ) = ( head first , last first ) \n\tret = helpSolve rest where\n\t helpSolve :: [[ Integer ]] -> Double \n\t helpSolve [] = 0.0 \n\t helpSolve [ x ] = 0.0\n\t helpSolve ( x : y : xs ) = ( sqrt.fromIntegral $ ( x_1 - x_2 ) ^ 2 + ( y_1 - y_2 ) ^ 2 ) + helpSolve ( y : xs ) where \n\t\tx_1 = head x\n\t\ty_1 = last x\n\t\tx_2 = head y \n\t\ty_2 = last y\n\nreaD :: BS.ByteString -> Integer \nreaD = fst. fromJust . BS.readInteger \n\nmain = BS.interact $ solve . map ( map reaD . BS.words ) . BS.lines \n"}, {"source_code": "dist :: [Int] -> [Int] -> Double\ndist [a, b] [c, d] = sqrt.fromIntegral $ dx^2 + dy^2\n where dx = a - c\n dy = b - d\nmain = do\n [_, k] <- getLine >>= return. map read. words :: IO [Double]\n as <- getContents >>= return. map (map read. words). lines :: IO [[Int]]\n print. (/50). (*k). sum $ zipWith dist (drop 1 as) as\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\ndst (x1, y1) (x2, y2) = sqrt $ dx*dx + dy*dy\n where dx = (x1 - x2)\n dy = (y1 - y2)\n\n\nsolve (p1:p2:r) = dst p1 p2 + solve (p2:r)\nsolve _ = 0\n\nmain = do\n [n, k] <- map read .words <$> getLine\n points <- replicateM n $ map read . words <$> getLine >>= \\[a,b] -> return (a,b)\n print $ solve points * (fromIntegral k) / 50\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ndist :: (Integral a, Floating b) => (a, a) -> (a, a) -> b\ndist (x1, y1) (x2, y2) = sqrt $ (fromIntegral x1 - fromIntegral x2)^2 + (fromIntegral y1 - fromIntegral y2)^2\n\nunfolder :: [(Int, Int)] -> Maybe (Double, [(Int, Int)])\nunfolder (a:b:rest) = Just (dist a b, b:rest)\nunfolder _ = Nothing\n\nmain :: IO ()\nmain = do \n [n, k] <- map (read :: String -> Int) . words <$> getLine\n print =<< (/50) . (fromIntegral k *) . sum . unfoldr unfolder . map ((\\[a,b]->(a,b)) . map (read :: String -> Int) . words) <$> replicateM n getLine\n"}, {"source_code": "import Data.Bits\n\n-- import Data.List (List)\nimport qualified Data.List as List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport System.IO\nimport Text.Read\n\nparseLine :: IO Point\nparseLine = do\n input <- getLine\n let (x:y:_) = (map read . words) input :: [Double]\n let p = Pt x y\n return p\n\ndata Point =\n Pt\n { pointx, pointy :: Double\n }\n\ndistance :: Point -> Point -> Double\ndistance p1 p2 =\n sqrt ((^) (pointx p1 - pointx p2) 2 + (^) (pointy p1 - pointy p2) 2)\n\nsolveN :: Int -> Point -> Double -> IO Double\nsolveN 0 lastp ans = return ans\nsolveN n last_p ans\n -- print $ \"ans = \" ++ show ans\n = do\n p <- parseLine\n solveN (n - 1) p (ans + distance p last_p)\n\nmain :: IO ()\nmain = do\n input <- getLine\n let (n:k:_) = (map read . words) input :: [Int]\n p <- parseLine\n input <- solveN (n - 1) p 0.0\n print $ input * fromIntegral k / 50.0\n"}, {"source_code": "\n\nparse :: Read a => Floating a => String -> (Int, a, [[a]])\nparse stuff =\n let [n, k] : nums = map words $ lines stuff in\n (read n, read k, map (map read) nums)\n\ncalc :: Show a => Read a => Floating a => [[a]] -> a -> a\ncalc [[_, _]] acc = acc\ncalc l@([x0, y0]:[x1, y1]:xs) acc = \n calc (tail l) (acc + dist x0 y0 x1 y1)\n where\n dist x0 y0 x1 y1 = sqrt $ (x0 - x1)^2 + (y0 - y1)^2\n\n\nmain = do \n stuff <- getContents\n let (_, k, points) = parse stuff\n result = calc points 0\n putStrLn $ show ((result / 50) * k)\n\n\n "}], "negative_code": [{"source_code": "module Main where\n\n -- Java-\u043a\u0440\u0435\u0441\u044c\u0442\u044c\u044f\u043d\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0441\u0442\u0440\u0430\u0434\u0430\u0442\u044c!\n \n import Data.List (foldl')\n \n type Point = (Double, Double)\n \n rho :: Point -> Point -> Double\n rho x y = sqrt ( (fst x - fst y)**2 + (snd x - snd y)**2 )\n \n lengths :: [Point] -> (Double, Point)\n lengths xs = foldl' summate (0, head xs) (tail xs)\n where summate (l, p) p' = (l + rho p p', p')\n \n main :: IO ()\n main = do\n [n, k] <- fmap (map read . words) getLine :: IO [Int]\n points <- sequence $\n replicate n $ do\n [x, y] <- fmap (map read . words) getLine :: IO [Double]\n return (x, y)\n putStrLn . show $ if (not . null) points\n then fst (lengths points) / 50\n else 0\n"}], "src_uid": "db4a25159067abd9e3dd22bc4b773385"} {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n ps <- zip [2..] `fmap` replicateM (n - 1) poi\n cs <- replicateM n poi\n return $ show $ solve n ps cs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\n\nsolve n ps cs0 = dfs g (\\u vs c s -> let cu = cs!u in foldl (\\s' f -> f cu s') (s + fromEnum (cu /= c)) vs) 0 0\n where\n g = accumArray (flip (:)) [] (1, n) $ concatMap (\\(a, b) -> [(a, b), (b, a)]) ps\n cs = listArray (1, n) cs0 :: UArray Int Int\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)", "positive_code": [{"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Control.Exception\nimport Control.Monad\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Data.Array\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[n], es, cs] = [ show $ sol' ((0,1): zip [2..] es) ca ]\n where\n ca = listArray (0,n) (0:cs)\n\nsol' [] _ = 0\nsol' ((p,v):vs) ca = (fromBool (ca!p /= ca!v )) + sol' vs ca\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}], "negative_code": [{"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Control.Exception\nimport Control.Monad\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Data.Array\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[n], es, cs] = [ show $ sol' ((0,1): zip [1..] es) ca ]\n where\n ca = listArray (0,n) (0:cs)\n\nsol' [] _ = 1\nsol' ((p,v):vs) ca = (fromBool (ca!p /= ca!v )) + sol' vs ca\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}], "src_uid": "b23696f763d90335e8bfb0a5e2094c03"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndata Color = Black | Grey | White deriving (Eq)\n\n{-# INLINE foldM' #-}\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\n(<$!>) :: Monad m => (a -> b) -> m a -> m b\nf <$!> m = do\n x <- m\n return $! f x\n{-# INLINE (<$!>) #-}\n\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n\n let\n impossible = or $ zipWith (\\a b -> b `isPrefixOf` a) ss $ tail ss\n\n es = catMaybes $ zipWith f ss $ tail ss\n where\n f s t\n | null s' = Nothing\n | null t' = error \"unreachable\"\n | otherwise = Just (head s', head t')\n where\n (s', t') = unzip $ dropWhile (\\(a, b) -> a == b) $ zip s t\n\n g = accumArray (flip (:)) [] ('a', 'z') es :: Array Char [Char]\n\n cyclic = flip evalState (Map.fromList $ zip ['a'..'z'] (repeat White)) $\n or <$> mapM dfs ['a'..'z']\n where\n dfs u = do\n modify $ Map.insert u Grey\n v <- or <$> (forM (g!u) $ \\v -> do\n m <- get\n case m Map.! v of\n White -> dfs v\n Grey -> return True\n Black -> return False)\n modify $ Map.insert u Black\n return v\n\n -- cyclic = runST $ do\n -- m <- newArray ('a', 'z') White :: ST s (STArray s Char Color)\n -- let\n -- dfs u = do\n -- writeArray m u Grey\n -- v <- or <$!> (forM (g!u) $ \\v -> do\n -- c <- readArray m v\n -- case c of\n -- White -> dfs v\n -- Grey -> return True\n -- Black -> return False)\n -- writeArray m u Black\n -- return v\n\n -- or <$> mapM dfs ['a'..'z']\n\n -- topSort g = flip evalState Set.empty $ do\n -- foldl1 (++) <$> (forM ['a'..'z'] $ \\u -> do\n -- s <- get\n -- if u `Set.notMember` s then dfs u else return [])\n -- where\n -- dfs :: Char -> State (Set Char) [Char]\n -- dfs u = do\n -- modify $ Set.insert u\n -- (u:) . foldl (++) [] . reverse <$> (forM (gg!u) $ \\v -> do\n -- s <- get\n -- if v `Set.notMember` s then dfs v else return [])\n\n putStrLn $\n if impossible || cyclic\n then \"Impossible\"\n else map (\\i -> chr (ord 'a' + i-1)) $ topSort $ buildG (1, 26) $ map (\\(a, b) -> (ord a - ord 'a' + 1, ord b - ord 'a' + 1)) es\n", "positive_code": [{"source_code": "import Data.Graph\nimport Data.Maybe\nmain = interact $ go . pair . tail . lines\npair [] = []\npair (x:xs) = (map (\\y -> (x,y)) xs) ++ (pair xs)\ngo x | (g == Nothing) || (not chk) = \"Impossible\"\n | True = a\n where g = build x\n s = topSort $ fromJust g\n a = map chr s\n chk = and $ map (cmp a) x\ncmp m x | p == [] = True\n | True = (\\(u,v) -> u`elem`(takeWhile (/=v) m)) $ head p\n where p = pr x\nbuild x | (0,0)`elem`e = Nothing\n | True = Just $ buildG (ord 'a',ord 'z') $ f e\n where e = map lx x\nlx (a,b) | (p == []) && ((length a) > (length b)) = (0,0)\n | p == [] = (1,1)\n | True = (\\(u,v) -> (ord u,ord v)) $ head p\n where p = pr (a,b)\nf :: (Ord a) => [(a,a)] -> [(a,a)]\nf = filter (\\(u,v) -> u /= v)\npr (a,b) = f $ zip a b\nord = fromEnum\nchr = toEnum\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nalphabet = ['a'..'z']\n\nfirstCharDiff ([], _) = Nothing\nfirstCharDiff (_, []) = undefined\nfirstCharDiff ((x:xs), (y:ys))\n | x /= y = Just (x, y)\n | otherwise = firstCharDiff (xs, ys)\n\nmakeAssoc names a =\n let\n predicate Nothing = False\n predicate (Just (c1, _)) = c1 == a\n list = map (\\(Just (_,c)) -> c) $ filter predicate $ map firstCharDiff $ zip names (tail names)\n in\n (a, list)\n\nmakeGraph names = array ('a','z') $ map (makeAssoc names) alphabet\n\n\ntopSort g cur using used sort@(Just _) = \n let\n neigb = g ! cur\n helper _ used Nothing = (cur : used, Nothing)\n helper [] used (Just sort) = (cur : used, Just (cur : sort))\n helper (x : xs) used sort\n | x `elem` using = (used, Nothing)\n | x `elem` used = helper xs used sort\n | otherwise = \n let\n (nused, nsort) = topSort g x (cur : using) used sort\n in\n helper xs nused nsort\n in\n helper neigb used sort\n \nfullSort _ _ _ Nothing = Nothing\nfullSort [] _ _ sort = sort\nfullSort (a:alph) g used sort\n | a `elem` used = fullSort alph g used sort\n | otherwise =\n let\n (nused, nsort) = topSort g a [] used sort\n in\n fullSort alph g nused nsort\n\nmain = do\n a <- getLine\n names <- replicateM (read a) getLine\n if (or (zipWith (\\a b -> b `isPrefixOf` a) names (tail names))) then\n putStrLn \"Impossible\"\n else\n let\n graph = makeGraph names\n sort = fullSort alphabet graph [] (Just [])\n ans Nothing = \"Impossible\"\n ans (Just a) = a\n in\n putStrLn $ ans sort"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nalphabet = ['a'..'z']\n\nfirstCharDiff ([], _) = Nothing\nfirstCharDiff (_, []) = undefined\nfirstCharDiff ((x:xs), (y:ys))\n | x /= y = Just (x, y)\n | otherwise = firstCharDiff (xs, ys)\n \nmakePreAssoc names = \n let\n makeAssocAux [] = []\n makeAssocAux (x : xs) = \n case firstCharDiff x of\n Just c -> c : makeAssocAux xs\n Nothing -> makeAssocAux xs\n in\n makeAssocAux $ zip names (tail names)\n\nmakeAssoc [] _ = []\nmakeAssoc (a : alph) names =\n let\n list = map (\\(_,c) -> c) $ filter (\\(x, y) -> x == a) names\n in\n (a, list) : makeAssoc alph names\n\nmakeGraph assoc = array ('a','z') assoc\n\n\ntopSort g cur using used sort@(Just _) = \n let\n neigb = g ! cur\n helper _ used Nothing = (cur : used, Nothing)\n helper [] used (Just sort) = (cur : used, Just (cur : sort))\n helper (x : xs) used sort\n | x `elem` using = (used, Nothing)\n | x `elem` used = helper xs used sort\n | otherwise = \n let\n (nused, nsort) = topSort g x (cur : using) used sort\n in\n helper xs nused nsort\n in\n helper neigb used sort\n \nfullSort _ _ _ Nothing = Nothing\nfullSort [] _ _ sort = sort\nfullSort (a:alph) g used sort\n | a `elem` used = fullSort alph g used sort\n | otherwise =\n let\n (nused, nsort) = topSort g a [] used sort\n in\n fullSort alph g nused nsort\n\nmain = do\n a <- getLine\n names <- replicateM (read a) getLine\n if (or (zipWith (\\a b -> b `isPrefixOf` a) names (tail names))) then\n putStrLn \"Impossible\"\n else\n let\n graph = makeGraph $ makeAssoc alphabet (makePreAssoc names)\n sort = fullSort alphabet graph [] (Just [])\n ans Nothing = \"Impossible\"\n ans (Just a) = a\n in\n putStrLn $ ans sort"}, {"source_code": "{-\n\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\n\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\n\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551\n\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255a\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551\n\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255a\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255d\n\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u2550\u255d\u255a\u2550\u2550\u255d \n\n $$\\ $$$$$$\\ $$\\ $$\\ $$$$$$\\ $$\\ $$\\ $$\\ $$\\ \n \\__| $$ __$$\\ $$ | $$$$ | $$ __$$\\ $$ | $$ | $$ |$$ | \n $$$$$$$\\ $$$$$$\\ $$$$$$\\ $$\\ $$$$$$$\\ \\__/ $$ |$$ | $$\\ \\_$$ | $$ / $$ | $$ | $$ | $$ |$$ | \n$$ _____|$$ __$$\\ $$ __$$\\ $$ |$$ __$$\\ $$$$$$ |$$ | $$ | $$ | \\$$$$$$$ | $$ | $$ | $$ |$$ | \n$$ / $$ / $$ |$$ / $$ | $$ |$$ | $$ | $$ ____/ $$$$$$ / $$ | \\____$$ | $$ | $$ | $$ |$$ | \n$$ | $$ | $$ |$$ | $$ | $$ |$$ | $$ | $$ | $$ _$$< $$ | $$\\ $$ | $$ | $$ | $$ |$$ | \n\\$$$$$$$\\ $$$$$$$ |$$$$$$$ | $$ |$$ | $$ | $$$$$$$$\\ $$ | \\$$\\ $$$$$$\\\\$$$$$$ | $$$$$$$$\\\\$$$$$$ |$$$$$$$$\\ \n \\_______|$$ ____/ $$ ____/ \\__|\\__| \\__| \\________|\\__| \\__|\\______|\\______/ \\________|\\______/ \\________|\n $$ | $$ | \n $$ | $$ | \n \\__| \\__| \n-}\n\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.Char (ord, chr)\nimport Control.Monad\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport Data.Maybe\n\ntype Edge = (S.Set Int, S.Set Int)\ntype Graph = M.IntMap Edge\ndata Impossible = Impossible deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n let nums :: [[Int]] = map (map ord) words\n case solve nums of\n Left Impossible -> putStrLn \"Impossible\"\n Right alphabet -> putStrLn alphabet\n\n\nsolve :: [[Int]] -> Either Impossible String\nsolve nums = createGraph nums >>= topSort >>= (Right . reverse . map chr)\n\ncreateGraph :: [[Int]] -> Either Impossible Graph\ncreateGraph nums = foldl f (Right emptyGraph) $ zip nums (tail nums) where\n f (Left Impossible) _ = Left Impossible\n f (Right g) (l,r) = compareWords g l r\n\nemptyGraph :: Graph\nemptyGraph = M.fromList . zip (map ord ['a'..'z']) $ repeat ((S.empty, S.empty) :: Edge)\n\ncompareWords :: Graph -> [Int] -> [Int] -> Either Impossible Graph\ncompareWords g [] [] = Right g\ncompareWords g (_:_) [] = Left Impossible\ncompareWords g [] (_:_) = Right g\ncompareWords g (x:xs) (y:ys) | x == y = compareWords g xs ys\n | otherwise = Right $ addEdges x y g\n\naddEdges :: Int -> Int -> Graph -> Graph\naddEdges x y g = M.adjust (\\(from, to) -> (S.insert x from, to)) y $\n M.adjust (\\(from, to) -> (from, S.insert y to)) x g \n\n\ntopSort :: Graph -> Either Impossible [Int]\ntopSort g = if hasCycle\n then Left Impossible\n else Right sorted\n where\n startingNodes = M.keys $ M.filter (\\(xs, _) -> null xs) g\n (graph, sorted) = topSortRec g startingNodes []\n hasCycle = not . null . M.toList . M.filter (\\(xs, ys)-> not $ null xs && null ys) $ graph\n\ntopSortRec :: Graph -> [Int] -> [Int] -> (Graph, [Int])\ntopSortRec g [] sorted = (g, sorted)\ntopSortRec g (n:ss) sorted = topSortRec g2 newSS (n:sorted) where\n ns = getFrom n g\n g1 = clearNTos n g\n g2 = clearFromNs n g1 ns\n newSS = emptiesToStack ss g2 ns\n\n\ngetFrom :: Int -> Graph -> [Int]\ngetFrom n = S.toList . snd . fromJust . M.lookup n\n\nclearNTos :: Int -> Graph -> Graph\nclearNTos = M.adjust (\\(from, to) -> (from, S.empty))\n\nclearFromNs :: Int -> Graph -> [Int] -> Graph\nclearFromNs n = foldl (flip $ M.adjust (\\(from, to) -> (S.delete n from, to)))\n\nemptiesToStack :: [Int] -> Graph -> [Int] -> [Int]\nemptiesToStack ss g = (++) ss . filter (\\i -> S.null . fst . fromJust $ M.lookup i g)"}, {"source_code": "{-\n\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\n\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\n\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551\n\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255a\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551\n\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255a\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255d\n\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u2550\u255d\u255a\u2550\u2550\u255d \n\n $$\\ $$$$$$\\ $$\\ $$\\ $$$$$$\\ $$\\ $$\\ $$\\ $$\\ \n \\__| $$ __$$\\ $$ | $$$$ | $$ __$$\\ $$ | $$ | $$ |$$ | \n $$$$$$$\\ $$$$$$\\ $$$$$$\\ $$\\ $$$$$$$\\ \\__/ $$ |$$ | $$\\ \\_$$ | $$ / $$ | $$ | $$ | $$ |$$ | \n$$ _____|$$ __$$\\ $$ __$$\\ $$ |$$ __$$\\ $$$$$$ |$$ | $$ | $$ | \\$$$$$$$ | $$ | $$ | $$ |$$ | \n$$ / $$ / $$ |$$ / $$ | $$ |$$ | $$ | $$ ____/ $$$$$$ / $$ | \\____$$ | $$ | $$ | $$ |$$ | \n$$ | $$ | $$ |$$ | $$ | $$ |$$ | $$ | $$ | $$ _$$< $$ | $$\\ $$ | $$ | $$ | $$ |$$ | \n\\$$$$$$$\\ $$$$$$$ |$$$$$$$ | $$ |$$ | $$ | $$$$$$$$\\ $$ | \\$$\\ $$$$$$\\\\$$$$$$ | $$$$$$$$\\\\$$$$$$ |$$$$$$$$\\ \n \\_______|$$ ____/ $$ ____/ \\__|\\__| \\__| \\________|\\__| \\__|\\______|\\______/ \\________|\\______/ \\________|\n $$ | $$ | \n $$ | $$ | \n \\__| \\__| \n-}\n\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.Char (ord, chr)\nimport Control.Monad\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport Data.Maybe\n\ntype Edge = (S.Set Int, S.Set Int)\ntype Graph = M.IntMap Edge\ndata Impossible = Impossible deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n let nums :: [[Int]] = map (map ord) words\n case solve nums of\n Left Impossible -> putStrLn \"Impossible\"\n Right alphabet -> putStrLn alphabet\n\n\nsolve :: [[Int]] -> Either Impossible String\nsolve nums = createGraph nums >>= topSort >>= (Right . reverse . map chr)\n\ncreateGraph :: [[Int]] -> Either Impossible Graph\ncreateGraph nums = foldl f (Right emptyGraph) $ zip nums (tail nums) where\n f (Left Impossible) _ = Left Impossible\n f (Right g) (l,r) = compareWords g l r\n\nemptyGraph :: Graph\nemptyGraph = M.fromList $ zip (map ord ['a'..'z']) $ repeat ((S.empty, S.empty) :: Edge)\n\ncompareWords :: Graph -> [Int] -> [Int] -> Either Impossible Graph\ncompareWords g [] [] = Right g\ncompareWords g (_:_) [] = Left Impossible\ncompareWords g [] (_:_) = Right g\ncompareWords g (x:xs) (y:ys) | x == y = compareWords g xs ys\n | otherwise = Right $ addEdges x y g\n\naddEdges :: Int -> Int -> Graph -> Graph\naddEdges x y g = M.adjust (\\(from, to) -> (S.insert x from, to)) y $\n M.adjust (\\(from, to) -> (from, S.insert y to)) x g \n\n\ntopSort :: Graph -> Either Impossible [Int]\ntopSort g = if hasCycle\n then Left Impossible\n else Right sorted\n where\n startingNodes = M.keys $ M.filter (\\(xs, _) -> null xs) g\n (graph, sorted) = topSortRec g startingNodes []\n hasCycle = not . null . M.toList . M.filter (\\(xs, ys)-> not $ null xs && null ys) $ graph\n\ntopSortRec :: Graph -> [Int] -> [Int] -> (Graph, [Int])\ntopSortRec g [] sorted = (g, sorted)\ntopSortRec g (n:ss) sorted = topSortRec g2 newSS (n:sorted) where\n ns = getFrom n g\n g1 = clearNTos n g\n g2 = clearFromNs n g1 ns\n newSS = emptiesToStack ss g2 ns\n\n\ngetFrom :: Int -> Graph -> [Int]\ngetFrom n = S.toList . snd . fromJust . M.lookup n\n\nclearNTos :: Int -> Graph -> Graph\nclearNTos = M.adjust (\\(from, to) -> (from, S.empty))\n\nclearFromNs :: Int -> Graph -> [Int] -> Graph\nclearFromNs n = foldl (flip $ M.adjust (\\(from, to) -> (S.delete n from, to)))\n\nemptiesToStack :: [Int] -> Graph -> [Int] -> [Int]\nemptiesToStack ss g = (++) ss . filter (\\i -> S.null . fst . fromJust $ M.lookup i g)"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Data.Char (ord, chr)\nimport Control.Monad\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\n\ntype Edge = (S.Set Int, S.Set Int)\ntype Graph = M.IntMap Edge\ndata Impossible = Impossible deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n let nums :: [[Int]] = map (map ord) words\n -- print $ createGraph nums\n case solve nums of\n Left Impossible -> putStrLn \"Impossible\"\n Right alphabet -> putStrLn alphabet\n\n\nemptyGraph :: Graph\nemptyGraph = M.fromList $ zip (map ord ['a'..'z']) $ repeat ((S.empty, S.empty) :: Edge)\n\ncompareWords :: Graph -> [Int] -> [Int] -> Either Impossible Graph\ncompareWords g [] [] = Right g\ncompareWords g (_:_) [] = Left Impossible\ncompareWords g [] (_:_) = Right g\ncompareWords g (x:xs) (y:ys) | x == y = compareWords g xs ys\n | otherwise = Right $ addEdges x y g\n\naddEdges :: Int -> Int -> Graph -> Graph\naddEdges x y g = M.adjust (\\(from, to) -> (S.insert x from, to)) y $\n M.adjust (\\(from, to) -> (from, S.insert y to)) x g \n\ncreateGraph :: [[Int]] -> Either Impossible Graph\ncreateGraph nums = foldl f (Right emptyGraph) $ zip nums (tail nums) where\n f (Left Impossible) _ = Left Impossible\n f (Right g) (l,r) = compareWords g l r\n\ntopSort :: Graph -> Either Impossible [Int]\ntopSort g = if hasCycle\n then Left Impossible\n else Right sorted\n where\n startingNodes = M.keys $ M.filter (\\(xs, _) -> null xs) g\n (graph, sorted) = topSortRec g startingNodes []\n hasCycle = not $ null $ M.toList $ M.filter (\\(xs, ys)-> not $ null xs && null ys) graph\n\ntopSortRec :: Graph -> [Int] -> [Int] -> (Graph, [Int])\ntopSortRec g [] sorted = (g, sorted)\ntopSortRec g (n:ss) sorted = topSortRec g2 newSS (n:sorted) where\n fromN = S.toList $ snd $ g M.! n\n g1 = M.adjust (\\(from, to) -> (from, S.empty)) n g\n g2 = foldl (\\accG i -> M.adjust (\\(from, to) -> (S.delete n from, to)) i accG) g1 fromN\n newSS = (++) ss $ filter (\\i -> S.null $ fst $ g2 M.! i) fromN\n\nsolve :: [[Int]] -> Either Impossible String\nsolve nums = createGraph nums >>= topSort >>= (Right . reverse . map chr)\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array\nimport Data.Maybe\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = fromMaybe \"Impossible\" `fmap` solve `fmap` (flip replicateM (fmap B.unpack pop) =<< poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = ((topSort . accumArray (flip (:)) [] ('a', 'z') . catMaybes) =<<) . ap (zipWithM cmp) tail\n\ntopSort g = foldM (go []) [] (indices g)\n where\n go temp seen u \n | u `elem` seen = Just seen\n | u `elem` temp = Nothing\n | otherwise = (u:) `fmap` foldM (go (u:temp)) seen (g!u)\n\ncmp xs ys = case dropWhile (uncurry (==)) $ zipDef '.' '.' xs ys of \n [] -> Just Nothing\n ('.', _):_ -> Just Nothing\n (_, '.'):_ -> Nothing\n (a, b):_ -> Just $ Just (a, b)\n\nzipDef dx _ [] ys = zip (repeat dx) ys\nzipDef _ dy xs [] = zip xs (repeat dy)\nzipDef dx dy (x:xs) (y:ys) = (x, y):zipDef dx dy xs ys\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array\nimport Data.Maybe\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = fromMaybe \"Impossible\" `fmap` solve `fmap` (flip replicateM (fmap B.unpack pop) =<< poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = ((topSort . accumArray (flip (:)) [] ('a', 'z') . catMaybes) =<<) . mapM (uncurry cmp) . wnd2\n\ntopSort g = foldM (go []) [] (indices g)\n where\n go temp seen u \n | u `elem` seen = Just seen\n | u `elem` temp = Nothing\n | otherwise = (u:) `fmap` foldM (go (u:temp)) seen (g!u)\n\ncmp xs ys = case dropWhile (uncurry (==)) $ zipDef '\\0' '\\0' xs ys of \n [] -> Just Nothing\n ('\\0', _):_ -> Just Nothing\n (_, '\\0'):_ -> Nothing\n (a, b):_ -> Just $ Just (a, b)\n\nwnd2 (x:y:xs) = (x, y):wnd2 (y:xs)\nwnd2 _ = []\n\nzipDef dx _ [] ys = zip (repeat dx) ys\nzipDef _ dy xs [] = zip xs (repeat dy)\nzipDef dx dy (x:xs) (y:ys) = (x, y):zipDef dx dy xs ys\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndata Color = Black | Grey | White deriving (Eq)\n\n{-# INLINE foldM' #-}\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\n\n(<$!>) :: Monad m => (a -> b) -> m a -> m b\nf <$!> m = do\n x <- m\n return $! f x\n{-# INLINE (<$!>) #-}\n\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n\n let\n impossible = or $ zipWith (\\a b -> b `isPrefixOf` a) ss $ tail ss\n\n es = catMaybes $ zipWith f ss $ tail ss\n where\n f s t\n | null s' = Nothing\n | null t' = error \"unreachable\"\n | otherwise = Just (head s', head t')\n where\n (s', t') = unzip $ dropWhile (\\(a, b) -> a == b) $ zip s t\n\n g = accumArray (flip (:)) [] ('a', 'z') es :: Array Char [Char]\n\n -- cyclic = flip evalState (Map.fromList $ zip ['a'..'z'] (repeat White)) $\n -- or <$> mapM dfs ['a'..'z']\n -- where\n -- dfs :: Char -> State (Map Char Color) Bool\n -- dfs u = do\n -- modify $ Map.insert u Grey\n -- v <- or <$> (forM (g!u) $ \\v -> do\n -- m <- get\n -- if m Map.! v == Grey\n -- then return True\n -- else dfs v)\n -- modify $ Map.insert u Black\n -- return v\n\n cyclic = runST $ do\n m <- newArray ('a', 'z') White :: ST s (STArray s Char Color)\n let\n dfs u = do\n writeArray m u Grey\n v <- or <$!> (forM (g!u) $ \\v -> do\n c <- readArray m v\n case c of\n White -> dfs v\n Grey -> return True\n Black -> return False)\n writeArray m u Black\n return v\n\n or <$> mapM dfs ['a'..'z']\n\n -- topSort g = flip evalState Set.empty $ do\n -- foldl1 (++) <$> (forM ['a'..'z'] $ \\u -> do\n -- s <- get\n -- if u `Set.notMember` s then dfs u else return [])\n -- where\n -- dfs :: Char -> State (Set Char) [Char]\n -- dfs u = do\n -- modify $ Set.insert u\n -- (u:) . foldl (++) [] . reverse <$> (forM (gg!u) $ \\v -> do\n -- s <- get\n -- if v `Set.notMember` s then dfs v else return [])\n\n putStrLn $\n if impossible || cyclic\n then \"Impossible\"\n else map (\\i -> chr (ord 'a' + i-1)) $ topSort $ buildG (1, 26) $ map (\\(a, b) -> (ord a - ord 'a' + 1, ord b - ord 'a' + 1)) es\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n\n let\n impossible = or $ zipWith (\\a b -> b `isPrefixOf` a) ss $ tail ss\n\n es = catMaybes $ zipWith f ss $ tail ss\n where\n f s t\n | null s' = Nothing\n | null t' = error \"unreachable\"\n | otherwise = Just (ord (head s') - ord 'a' + 1, ord (head t') - ord 'a' + 1)\n where\n (s', t') = unzip $ dropWhile (\\(a, b) -> a == b) $ zip s t\n\n g = buildG (1, 26) es\n\n putStrLn $\n if impossible\n then \"Impossible\"\n else map (\\i -> chr (ord 'a' + i-1)) $ topSort g\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nalphabet = ['a'..'z']\n\nfirstCharDiff ([], _) = Nothing\nfirstCharDiff (_, []) = undefined\nfirstCharDiff ((x:xs), (y:ys))\n | x /= y = Just (x, y)\n | otherwise = firstCharDiff (xs, ys)\n \nmakePreAssoc names = \n let\n makeAssocAux [] = []\n makeAssocAux (x : xs) = \n case firstCharDiff x of\n Just c -> c : makeAssocAux xs\n Nothing -> makeAssocAux xs\n in\n makeAssocAux $ zip names (tail names)\n\nmakeAssoc [] _ = []\nmakeAssoc (a : alph) names =\n let\n list = map (\\(_,c) -> c) $ filter (\\(x, y) -> x == a) names\n in\n (a, list) : makeAssoc alph names\n\nmakeGraph assoc = array ('a','z') assoc\n\n\ntopSort g cur used sort@(Just _) = \n let\n neigb = g ! cur\n helper _ used Nothing = (used, Nothing)\n helper [] used (Just sort) = (used, Just (cur : sort))\n helper (x : xs) used sort\n | x `elem` used = (used, Nothing)\n | otherwise = \n let\n (nused, nsort) = topSort g x (x : used) sort\n in\n helper xs nused nsort\n in\n helper neigb used sort\n \nfullSort _ _ _ Nothing = Nothing\nfullSort [] _ _ sort = sort\nfullSort (a:alph) g used sort\n | a `elem` used = fullSort alph g used sort\n | otherwise =\n let\n (nused, nsort) = topSort g a used sort\n in\n fullSort alph g nused nsort\n\nmain = do\n a <- getLine\n names <- replicateM (read a) getLine\n if (or (zipWith (\\a b -> b `isPrefixOf` a) names (tail names))) then\n putStrLn \"Impossible\"\n else\n let\n graph = makeGraph $ makeAssoc alphabet (makePreAssoc names)\n sort = fullSort alphabet graph [] (Just [])\n ans Nothing = \"Impossible\"\n ans (Just a) = a\n in\n putStrLn $ ans sort"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport qualified Data.Map as M\nimport Control.Monad.State\nimport Data.Maybe\nimport Data.List\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n putStrLn $ case compareAll words of\n Left Impossible -> \"impossible\"\n Right xs -> buildAlphabet xs\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nbuildAlphabet :: Dictionary -> String\nbuildAlphabet dict = (++ nothings) $ snd $ until cond f (justs,\"\") where\n xs :: [(Char, Maybe [Char])]\n xs = M.toList dict \n nothings :: String\n nothings = map fst $ filter (\\(_, a) -> isNothing a) xs\n justs :: [([Char], Char)]\n justs = map (\\(a,Just b) -> (b,a)) $ filter (\\(_, a) -> isJust a) xs\n cond :: ([([Char], Char)], String) -> Bool\n cond ([],_) = True\n cond _ = False\n f :: ([([Char], Char)], String) -> ([([Char], Char)], String)\n f (ys, []) = case lookup \"\" ys of\n Nothing -> error \"wtf2\"\n Just c -> (delete (\"\",c) ys, [c]) \n f all@(ys, acc@(a:as)) = case lookup [a] ys of\n Nothing -> case lookup \"\" ys of--error $ \"wtf3\" ++ show all ++ show xs\n Nothing -> error \"wtf4\"\n Just c -> (delete (\"\",c) ys, c:acc)\n Just c -> (delete ([a],c) ys, c:acc)\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n let flat = map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead flat\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n -- else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n else do\n let large = length $ safeHead $ filter (\\x-> length x /= 2) $ safeHead flat\n let restSum = sum $ concatMap (map length) $ safeTail flat\n if large == restSum\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"glmbvjcunmnm\" then putStrLn (\"Impossible 4\" ++ show large ++ \" \" ++ show restSum ++ \" ::: \"++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:_) = x\n\nsafeTail :: [[a]] -> [[a]]\nsafeTail [] = []\nsafeTail (_:xs) = xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport qualified Data.Graph as G\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = G.graphFromEdges $ convertToGrapable xs \n putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ G.topSort myGraph\n\n\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 4: the electric boogaloo\" else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible2\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport qualified Data.Map as M\nimport Control.Monad.State\nimport Data.Maybe\nimport Data.List\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n putStrLn $ case compareAll words of\n Left Impossible -> \"Impossible\"\n Right xs -> case buildAlphabet xs of\n Left Impossible -> \"Impossible\"\n Right alphabet -> alphabet\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nbuildAlphabet :: Dictionary -> Either DictError String\nbuildAlphabet dict = case snd $ until cond f (justs, Right \"\") of\n Left Impossible -> Left Impossible\n Right a -> Right $ (++ nothings) $ reverse $ a\n where\n xs :: [(Char, Maybe [Char])]\n xs = M.toList dict \n nothings :: String\n nothings = map fst $ filter (\\(_, a) -> isNothing a) xs\n justs :: [([Char], Char)]\n justs = map (\\(a,Just b) -> (b,a)) $ filter (\\(_, a) -> isJust a) xs\n cond :: ([([Char], Char)], Either DictError String) -> Bool\n cond (_, Left Impossible) = True\n cond ([],_) = True\n cond _ = False\n f :: ([([Char], Char)], Either DictError String) -> ([([Char], Char)], Either DictError String)\n f (ys, Right []) = case lookup \"\" ys of\n Nothing -> error \"wtf2\"\n Just c -> (delete (\"\",c) ys, Right [c]) \n f all@(ys, Right acc@(a:as)) = case lookup [a] ys of\n Nothing -> case lookup \"\" ys of--error $ \"wtf3\" ++ show all ++ show xs\n Just c -> (delete (\"\",c) ys, Right $ c:acc)\n Nothing -> ([], Left Impossible)--error $ \"wtf4\" ++ show all ++ show xs\n Just c -> (delete ([a],c) ys, Right $ c:acc)\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n let flat = map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead flat\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n -- else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n else do\n let large = length $ safeHead $ filter (\\x-> length x /= 2) $ safeHead flat\n let restSum = sum $ concatMap (map length) $ safeTail flat\n if large == restSum\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"glmbvjcunmnm\" \n then putStrLn \"grlypdbfcujktxzeomawsnivhq\" --(\"Impossible 4\" ++ show large ++ \" \" ++ show restSum ++ \" ::: \"++ show (map (map length) $ map flatten $ bcc myGraph)) \n else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:_) = x\n\nsafeTail :: [[a]] -> [[a]]\nsafeTail [] = []\nsafeTail (_:xs) = xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 4: the electric boogaloo\" else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n let flat = map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead flat\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n -- else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n else do\n let large = length $ safeHead $ filter (\\x-> length x /= 2) $ safeHead flat\n let restSum = sum $ concatMap (map length) $ safeTail flat\n if large == restSum\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show large ++ \" \" ++ show restSum ++ \" ::: \"++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:_) = x\n\nsafeTail :: [[a]] -> [[a]]\nsafeTail [] = []\nsafeTail (_:xs) = xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 4: the electric boogaloo\" else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n let flat = map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead flat\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n -- else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n else do\n let large = safeHead $ filter (\\x-> length x /= 2) $ safeHead flat\n let restSum = sum $ concatMap safeHead $ safeTail flat\n if large == [restSum]\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show large ++ \" \" ++ show restSum ++ \" ::: \"++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:_) = x\n\nsafeTail :: [[a]] -> [[a]]\nsafeTail [] = []\nsafeTail (_:xs) = xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"glmbvjcunmnm\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n let flat = map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead flat\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n -- else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n else do\n let large = length $ safeHead $ filter (\\x-> length x /= 2) $ safeHead flat\n let restSum = sum $ concatMap (map length) $ safeTail flat\n if large == restSum\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else case words!!0 of\n \"glmbvjcunmnm\" -> putStrLn \"grlypdbfcujktxzeomawsnivhq\" --(\"Impossible 4\" ++ show large ++ \" \" ++ show restSum ++ \" ::: \"++ show (map (map length) $ map flatten $ bcc myGraph)) \n \"rtwypcjgswkonoycwelyfvyrejpzksuyuokocvkxefyycnhnnfqyfipuqwhkhzgxsclghywqvwcvhyrehbeseplrxpjzjogqhnc\" -> putStrLn \"rtipgxlobymeqhfujsvndkcazw\"\n _ -> putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:_) = x\n\nsafeTail :: [[a]] -> [[a]]\nsafeTail [] = []\nsafeTail (_:xs) = xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n let flat = map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead flat\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n -- else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n else do\n let large = safeHead $ filter (\\x-> length x /= 2) $ safeHead flat\n let restSum = sum $ concatMap safeHead $ safeTail flat\n if large == [restSum]\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:_) = x\n\nsafeTail :: [[a]] -> [[a]]\nsafeTail [] = []\nsafeTail (_:xs) = xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport qualified Data.Map as M\nimport Control.Monad.State\nimport Data.Maybe\nimport Data.List\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n putStrLn $ case compareAll words of\n Left Impossible -> \"impossible\"\n Right xs -> buildAlphabet xs\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nbuildAlphabet :: Dictionary -> String\nbuildAlphabet dict = (++ nothings) $ reverse . snd $ until cond f (justs,\"\") where\n xs :: [(Char, Maybe [Char])]\n xs = M.toList dict \n nothings :: String\n nothings = map fst $ filter (\\(_, a) -> isNothing a) xs\n justs :: [([Char], Char)]\n justs = map (\\(a,Just b) -> (b,a)) $ filter (\\(_, a) -> isJust a) xs\n cond :: ([([Char], Char)], String) -> Bool\n cond ([],_) = True\n cond _ = False\n f :: ([([Char], Char)], String) -> ([([Char], Char)], String)\n f (ys, []) = case lookup \"\" ys of\n Nothing -> error \"wtf2\"\n Just c -> (delete (\"\",c) ys, [c]) \n f all@(ys, acc@(a:as)) = case lookup [a] ys of\n Nothing -> case lookup \"\" ys of--error $ \"wtf3\" ++ show all ++ show xs\n Nothing -> error \"wtf4\"\n Just c -> (delete (\"\",c) ys, c:acc)\n Just c -> (delete ([a],c) ys, c:acc)\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport qualified Data.Graph as G\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> print \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = G.graphFromEdges $ convertToGrapable xs \n putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ G.topSort myGraph\n\n\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 4: the electric boogaloo\" else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right True\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible2\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n | Equals\n | Impossible1\n | Impossible2\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Left Impossible1 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 2\" else putStrLn \"Impossible\"\n Left Impossible2 -> if words!!0 == \"ppwwacleajuf\" then putStrLn \"Impossible 3\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"ppwwacleajuf\" then putStrLn (\"Impossible 4\" ++ show (map (map length) $ map flatten $ bcc myGraph)) else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Left Equals\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible1\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Left Equals -> compareWords xs ys dict\n Right False -> Left Impossible2\n Right True -> Right dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left _) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left err -> Left err\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.Graph\nimport Data.Array\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.List\nimport Data.Char\nimport Data.Tree\n\ntype Dictionary = M.Map Char (Maybe [Char])\ndata DictError = Impossible\n | NotFound\n deriving(Show)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let n :: Int = read line1\n words <- replicateM n getLine\n case compareAll words of\n Left Impossible -> if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 1\" else putStrLn \"Impossible\"\n Right xs -> do\n let (myGraph,vertexToNode,keyToVertex) = graphFromEdges $ convertToGrapable xs \n -- print $ map flatten $ bcc myGraph\n if all (\\x-> length x == 2) $ safeHead $ map flatten $ bcc myGraph\n then putStrLn $ reverse $ concatMap ((\\(x,_,_)->x) . vertexToNode) $ topSort myGraph\n else if words!!0 == \"adjcquqdqcsvixgwglwrrmkhdsbebbjvcgz\" then putStrLn \"Impossible 2: the electric boogaloo\" else putStrLn \"Impossible\"\n\n-- asd = [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]},Node {rootLabel = 3, subForest = []},Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []},Node {rootLabel = 8, subForest = []},Node {rootLabel = 9, subForest = []},Node {rootLabel = 10, subForest = []},Node {rootLabel = 11, subForest = []},Node {rootLabel = 12, subForest = []},Node {rootLabel = 13, subForest = []},Node {rootLabel = 14, subForest = []},Node {rootLabel = 15, subForest = []},Node {rootLabel = 16, subForest = []},Node {rootLabel = 17, subForest = []},Node {rootLabel = 18, subForest = []},Node {rootLabel = 19, subForest = []},Node {rootLabel = 20, subForest = []},Node {rootLabel = 21, subForest = []},Node {rootLabel = 22, subForest = []},Node {rootLabel = 23, subForest = [Node {rootLabel = 24, subForest = [Node {rootLabel = 25, subForest = []}]}]}]\n\nemptyDict :: Dictionary\nemptyDict = M.fromList $ zip ['a'..'z'] $ repeat Nothing\n\nisBefore :: Char -> Char -> Dictionary -> Either DictError Bool\nisBefore x y dict | x == y = Right True\n | isJust xs && isJust ys && x `elem` fromJust ys && y `elem` fromJust xs = error $ \"wtf: \" ++ show dict\n | isJust ys && x `elem` fromJust ys = Right True\n | isJust xs && y `elem` fromJust xs = Right False\n | isNothing xs && isNothing ys = Left NotFound\n | isNothing xs && x `notElem` fromJust ys = Left NotFound\n | isNothing ys && y `notElem` fromJust xs = Left NotFound\n | otherwise = Left NotFound\n where\n xs :: Maybe [Char]\n xs = fromJust $ M.lookup x dict\n ys :: Maybe [Char]\n ys = fromJust $ M.lookup y dict\n\n\ncompareWords :: String -> String -> Dictionary -> Either DictError Dictionary\ncompareWords (x:xs) [] _ = Left Impossible\ncompareWords (x:xs) (y:ys) dict = case isBefore x y dict of\n Left NotFound -> Right $ M.adjust adjust2 x $ M.adjust adjust1 y dict\n Right False -> Left Impossible\n Right True -> compareWords xs ys dict\n where\n adjust1 (Just a) = Just (x:a) \n adjust1 Nothing = Just [x] \n adjust2 (Just a) = Just a \n adjust2 Nothing = Just [] \ncompareWords _ _ dict = Right dict\n\ncompareAll :: [String] -> Either DictError Dictionary\ncompareAll xs = foldl f (Right emptyDict) $ zip xs $ tail xs where\n f acc@(Left Impossible) _ = acc\n f (Right acc) (s1, s2) = case compareWords s1 s2 acc of\n Left Impossible -> Left Impossible\n Right dict -> Right dict\n\nconvertToGrapable :: Dictionary -> [(String, Int, [Int])]\nconvertToGrapable dict = map f $ M.toList dict where\n f (c, Nothing) = ([c], ord c, [])\n f (c, Just cs) = ([c], ord c, map ord cs)\n\n\n-- onlyTwosForest :: Forest [Vertex] -> Bool\n-- onlyTwosForest xs = and map onlyTwoesTree xs \n\n-- onlyTwoesTree :: Tree [Vertex] -> Bool\n-- onlyTwoesTree = \n\nsafeHead :: [[a]] -> [a]\nsafeHead [] = []\nsafeHead (x:xs) = x"}], "src_uid": "12218097cf5c826d83ab11e5b049999f"} {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.Maybe\nimport Data.Ratio\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nintLine :: IO [Integer]\nintLine = fmap (map (fromIntegral . fst . fromJust . B.readInt) . B.words) B.getLine\n\nmain = do\n [n,w,v,u] <- intLine\n ts <- replicateM (fromIntegral n) $ do\n [x,y] <- intLine\n return $ x % v - y % u; \n let t = if minimum ts >= 0 then 0 else max 0 (maximum ts)\n let res = t + w % u\n putStrLn $ printf \"%.12f\" $ (fromRational res :: Double)\n\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Int\nimport Data.List (foldl', sortBy)\nimport Text.Printf\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Velocity = Int64\n\ndata Point = Point { getX :: Int64\n , getY :: Int64\n } deriving (Show, Eq)\n\nordByY :: Point -> Point -> Ordering\nordByY (Point x1 y1) (Point x2 y2) | y1 < y2 = LT\n | y1 > y2 = GT\n | otherwise = compare x1 x2\n\ndata Bus = Bus [Point] Velocity\n deriving (Show, Eq)\n\ndata Test = Test { bus :: Bus\n , pedestrian :: Velocity\n , width :: Int64\n } deriving (Show, Eq)\n\nfastPath :: Test -> Double\nfastPath (Test (Bus ps v) u w) | all inTime ps = (fromIntegral w) / (fromIntegral u)\n | otherwise = -1.0\n where inTime (Point x y) = y * v <= x * u\n\nslowPath :: Test -> Double\nslowPath (Test (Bus ps v) u w) = pt + (fromIntegral $ w - py) / (fromIntegral u)\n where (py, pt) = foldl' update (0, 0.0) (sortBy ordByY ps)\n\n update :: (Int64, Double) -> Point -> (Int64, Double)\n update (py, pt) (Point bx by) = (by, max bt pt')\n where bt = (fromIntegral bx) / (fromIntegral v)\n pt' = pt + (fromIntegral $ by - py) / (fromIntegral u)\n\nsolve :: Test -> Double\nsolve test | fp > -1.0 = fp\n | otherwise = sp\n where fp = fastPath test\n sp = slowPath test\n\ntest0 = Test { bus = Bus [Point 1 2, Point 3 1, Point 4 3, Point 3 4, Point 1 4] 1\n , pedestrian = 2\n , width = 5\n }\n\n\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextInt64 :: Tokenizer Int64\nnextInt64 = liftM fromIntegral nextInt\n\ngo :: Tokenizer Double\ngo = do\n n <- nextInt\n w <- nextInt64\n v <- nextInt64\n u <- nextInt64\n ps <- replicateM n (liftM2 Point nextInt64 nextInt64)\n return $ solve Test { bus = Bus ps v, pedestrian = u, width = w }\n\nmain :: IO ()\nmain = do\n input <- L.getContents\n let result = evalState go (L.words input)\n printf \"%.7f\\n\" result\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Int\nimport Data.Maybe\nimport Data.Ratio\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nintLine :: IO [Integer]\nintLine = fmap (map (fromIntegral . fst . fromJust . B.readInt) . B.words) B.getLine\n\nmain = do\n [n,w,v,u] <- intLine\n ts <- replicateM (fromIntegral n) $ do\n [x,y] <- intLine\n return $ fromIntegral x - fromIntegral v * y % u; \n let t = if minimum ts >= 0 then 0 else maximum ts\n let res = t + w % u\n putStrLn $ printf \"%.12f\" $ (fromRational res :: Double)\n\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.Maybe\nimport Data.Ratio\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nintLine :: IO [Integer]\nintLine = fmap (map (fromIntegral . fst . fromJust . B.readInt) . B.words) B.getLine\n\nmain = do\n [n,w,v,u] <- intLine\n ts <- replicateM (fromIntegral n) $ do\n [x,y] <- intLine\n return $ fromIntegral x - fromIntegral v * y % u; \n let t = if minimum ts >= 0 then 0 else max 0 (maximum ts)\n let res = t + w % u\n putStrLn $ printf \"%.12f\" $ (fromRational res :: Double)\n\n"}], "src_uid": "979e1b735d1c152d01955e27ee8d0b8a"} {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n [l, r] <- readIListLn\r\n return (l, r)\r\n\r\nreadIListLn = map read <$> words <$> getLine :: IO [Int]\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve (l, r) = show $ sum . take 20 $ ps\r\n where\r\n ps = zipWith (flip (-)) (iterate (`div` 10) l) (iterate (`div` 10) r)\r\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: [Int] -> Int\r\nsolve [l, r] = cost r - cost l\r\n where\r\n cost = sum . takeWhile (> 0) . iterate (`div` 10)\r\n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ncnt :: Int -> Int64\ncnt x = f (fromIntegral x) x\n where\n f !acc 0 = acc\n f !acc !x = let !t = div x 10 in f (acc + fromIntegral t) t\n\ntest' :: Int -> Int -> Int64\ntest' l r = cnt r - cnt l\n\nnl = char7 '\\n'\ntest :: Builder -> Int -> [Int] -> Builder\ntest buf 0 _ = buf\ntest buf nt (a:b:xs) = test (buf <> int64Dec (test' a b) <> nl) (pred nt) xs\n\nsolve :: [Int] -> Builder\nsolve (nt:xs) = test mempty nt xs\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}], "negative_code": [], "src_uid": "7a51d536d5212023cc226ef1f6201174"} {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t do\n [n, _] <- getInts\n matrix <- replicateM n getInts\n let steps = free matrix `min` free (transpose matrix)\n winner = [\"Vivek\", \"Ashish\"] !! mod steps 2\n putStrLn winner\n where\n free = length . filter (not . elem 1)\n\ngetInts :: IO [Int]\ngetInts = go <$> BS.getLine\n where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\n\nmain :: IO ()\nmain = do\n\tn <- readLn\n\treplicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n\t[n,m] <- (map read.words) <$> getLine\n\txs <- replicateM n ((map read.words) <$> getLine)\n\tputStrLn $ if solve n m xs then \"Vivek\" else \"Ashish\"\n\nsolve :: Int -> Int -> [[Int]] -> Bool\nsolve n m xs = even $ min ns ms\n\twhere\n\t\tarr = listArray ((1,1),(n,m)) $ concat xs\n\t\tns = length $ filter not [ any (== 1) [ arr!(i,j) | j <- [1..m]] | i <- [1..n]]\n\t\tms = length $ filter not [ any (== 1) [ arr!(i,j) | i <- [1..n]] | j <- [1..m]]"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t solve\n\nreadInts :: IO [Int]\nreadInts = map read.words <$> getLine\n\ncountOptions :: [[Int]] -> Int\ncountOptions [] = 0\ncountOptions (x:xs) = (if all (==0) x then 1 else 0) + countOptions xs\n\nsolve :: IO()\nsolve = do\n [n,m] <- readInts\n r <- replicateM n readInts\n let c = transpose r\n let rZeros = countOptions r\n let cZeros = countOptions c\n let zeros = min rZeros cZeros\n putStrLn (if even zeros then \"Vivek\" else \"Ashish\")\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nboolToInt bool\n | bool = 1\n | otherwise = 0\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Int]\n res = vals |> unfoldr (\\case\n [] -> Nothing\n n:m:rest0 ->\n let (cells, rest1) = splitAt (n*m) rest0\n rows = cells |> unfoldr (\\case\n [] -> Nothing\n ls -> Just $ splitAt m ls\n )\n numAvailableRows = sum $ boolToInt <$> isZeroRows where\n isZeroRows = all (== 0) <$> rows\n numAvailableCols = sum $ zeroCols where\n zeroCols = (\\x -> 1-x) <$> oneCols\n oneCols = foldl (\\acc ls -> uncurry max <$> zip acc ls) allZeros rows where\n allZeros = replicate m 0\n numTurns = min numAvailableRows numAvailableCols\n subres = if numTurns `mod` 2 == 1 then \"Ashish\" else \"Vivek\"\n in Just (subres, rest1)\n )\n sequence_ (putStrLn <$> res)\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [[Int]] -> String\nsolve x = let free_rows = countTrue (map isArrayFree x)\n free_cols = countTrue (map isArrayFree $ transpose x) in\n if even (min free_rows free_cols) \n then \"Vivek\"\n else \"Ashish\"\n\n\ncountTrue :: [Bool] -> Int\ncountTrue = length . filter (==True)\n\nisArrayFree :: [Int] -> Bool\nisArrayFree x = not $ elem 1 x\n\nmain = do\n t <- read <$> getLine\n replicateM_ t testCase\n\ntestCase = do\n (n:_) <- map read . words <$> getLine\n matrix <- replicateM n (map read . words <$> getLine)\n putStrLn (solve matrix)"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nboolToInt bool\n | bool = 1\n | otherwise = 0\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Int]\n res = vals |> unfoldr (\\case\n [] -> Nothing\n n:m:rest0 ->\n let (cells, rest1) = splitAt (n*m) rest0\n rows = cells |> unfoldr (\\case\n [] -> Nothing\n ls -> Just $ splitAt m ls\n )\n numAvailableRows = sum $ boolToInt <$> isZeroRows where\n isZeroRows = all (== 0) <$> rows\n numAvailableCols = sum $ zeroCols where\n zeroCols = (\\x -> 1-x) <$> oneCols\n oneCols = foldl (\\acc ls -> uncurry max <$> zip acc ls) allZeros rows where\n allZeros = replicate n 0\n numTurns = min numAvailableRows numAvailableCols\n subres = if numTurns `mod` 2 == 1 then \"Ashish\" else \"Vivek\"\n in Just (subres, rest1)\n )\n sequence_ (putStrLn <$> res)\n"}], "src_uid": "3ccc98190189b0c8e58a96dd5ad1245d"} {"source_code": "import Control.Monad\n\nisInside :: (Int, Int) -> (Int, Int) -> Bool\nisInside (n, d) (x, y) = su >= down && su <= up && di >= right && di <= left\n where\n su = x + y\n di = x - y\n down = d\n up = (2 * n - d)\n left = d\n right = (-d)\n\nmain :: IO ()\nmain = do \n [n, d] <- map (read :: String -> Int) . words <$> getLine\n m <- (read :: String -> Int) <$> getLine\n replicateM_ m $ do\n [x, y] <- map (read :: String -> Int) . words <$> getLine\n putStrLn $ if isInside (n, d) (x, y) then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "main = getContents >>= putStr . unlines . solve . map read . words\n\nsolve (n:d:0:_) = []\nsolve (n:d:m:x:y:xys) = (contain n d x y) : solve (n:d:m - 1:xys)\n\ncontain n d x y = if d <= x + y && x + y <= 2 * n - d && -d <= x - y && x - y <= d\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\ncross (x1,y1) (x2,y2) = x1*y2-x2*y1\nsub (x1,y1) (x2,y2) = (x1-x2,y1-y2)\ninRect n d x y = all (>=0) t || all (<=0) t\n where\n t = [cross (-1,1) ((x,y) `sub` (d,0)), cross (1,1) ((x,y) `sub` (0,d)),\n cross (1,-1) ((x,y) `sub` (n-d,n)), cross (-1,-1) ((x,y) `sub` (n,n-d))]\n\nmain = do\n [n,d] <- map read . words <$> getLine :: IO [Int]\n m <- readLn :: IO Int\n\n replicateM m $ do\n [x,y] <- map read . words <$> getLine :: IO [Int]\n putStrLn $ if inRect n d x y then \"YES\" else \"NO\"\n"}], "negative_code": [], "src_uid": "9c84eb518c273942650c7262e5d8b45f"} {"source_code": "import Control.Monad\nimport Control.Applicative\n\nimport Data.List\nimport Data.Maybe\n\nfilt [] ys = Just ys\nfilt (x:xs) [] = Nothing\nfilt (x:xs) (y:ys) =\n if y <= x\n then filt (x:xs) ys >>= return . (y:)\n else filt xs ys\n\nsolve (c0, ja0, jd0) = max s1 s2\n where\n [c, ja, jd] = map sort [c0, ja0, jd0]\n\n s1 = sum $ zipWith (\\a b -> max 0 $ a - b) (reverse c) ja\n\n s2 = fromMaybe 0 $ do\n c' <- filt jd c\n return $ if length c' >= length ja && and (zipWith (<=) (reverse ja) (reverse c'))\n then sum c' - sum ja\n else 0\n\ninput = do\n [n, m] <- map read . words <$> getLine\n j <- replicateM n $ (\\[p, s] -> (p == \"ATK\", read s)) . words <$> getLine\n let (ja0, jd0) = partition fst j\n c <- replicateM m $ read <$> getLine\n return (c, map snd ja0, map snd jd0)\n\nmain = print . solve =<< input\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nimport Control.Monad\nimport Control.Applicative\n\nfilt [] ys = Just ys\nfilt (x:xs) [] = Nothing\nfilt (x:xs) (y:ys) =\n if y <= x\n then filt (x:xs) ys >>= return . (y:)\n else filt xs ys\n\nsolve (c0, ja0, jd0) =\n max s1 s2\n where\n [c, ja, jd] = map sort [c0, ja0, jd0]\n\n s1 = sum $ zipWith (\\a b -> max 0 $ a - b) (reverse c) ja\n\n s2 = fromMaybe 0 $ do\n c' <- filt jd c\n return $ if length c' >= length ja && and (zipWith (<=) (reverse ja) (reverse c'))\n then sum c' - sum ja\n else 0\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n j <- replicateM n $ words <$> getLine >>= \\[p, s] -> return (p == \"ATK\", read s)\n let (ja0, jd0) = partition fst j\n c <- replicateM m $ read <$> getLine\n return (c, map snd ja0, map snd jd0)\n\nmain = print . solve =<< readInput\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.List\n\n\nmain = do\n [n,m] <- map read . words <$> getLine\n jiro <- replicateM n (parseJiro <$> getLine)\n ciel <- replicateM m (parseCiel <$> getLine)\n print $ solve jiro ciel\n\nparseJiro :: String -> (Bool,Int)\nparseJiro ('A':'T':'K':' ':s) = (True,read s)\nparseJiro ('D':'E':'F':' ':s) = (False,read s)\n\nparseCiel :: String -> Int\nparseCiel = read\n\nsolve jiro ciel | canDefeatAll = max a1 a2\n | otherwise = a1\n where\n attacks = sort [ s | (True,s) <- jiro]\n defenses = sort [ s | (False,s) <- jiro ]\n canDefeatAll = all (uncurry (<=)) $ zip (reverse $ sort (attacks ++ map succ defenses)) (reverse $ sort ciel)\n a1 = sum $ map (\\(a,b) -> if a > b then a - b else 0) \n $ zip (reverse (sort ciel)) attacks\n a2 = sum (remove defenses (sort ciel)) - sum attacks\n\n\nremove [] ciel = ciel\nremove (x:xs) ciel = remove xs (deleteBy (<) x ciel)\n"}, {"source_code": "import Data.List (foldl', sort)\nimport qualified Data.IntMap as Map\nimport Data.Maybe (maybeToList)\nimport Data.Function (on)\nimport Control.Monad\n\n-- x is supposed to be descending, att is so too\n-- def is supposed to be ascending\nrush :: ([Int], [Int]) -> [Int] -> Int\nrush (att, []) x = let planA = (sum . takeWhile (>= 0) . zipWith (-) x) (att ++ repeat 0) \n planB = (sum . takeWhile (>= 0) . zipWith (-) x) (reverse att ++ repeat 0)\n in max planA planB\nrush (att, def) x = let x' = concat . maybeToList $ x `kill` def\n x'' = take (length att) x in\n (max `on` rush (att, [])) x' x''\n\nkill :: [Int] -> [Int] -> Maybe [Int]\nkill x def = let xs = foldl' cons Map.empty x\n cons m y = Map.insertWith (+) y 1 m\n xs' = foldl' f (return xs) def\n f ms d = ms >>= \\s -> let att = Map.lookupGT d s in fmap (del s . fst) att\n del = flip $ Map.update (\\y -> if y == 1 then Nothing else Just (y - 1)) \n toList = Map.foldlWithKey' (\\l y c -> l ++ replicate c y) [] \n in fmap (reverse . toList) xs'\n \nmain :: IO ()\nmain = do\n m:n:_ <- fmap (map read . words) getLine\n jiro <- fmap (map words) (replicateM m getLine)\n fox <- fmap (map read) (replicateM n getLine)\n let jiros = jiroParse jiro\n-- print jiros\n print $ rush (jiroParse jiro) (reverse (sort fox))\n\njiroParse :: [[String]] -> ([Int], [Int])\njiroParse s = let (att, def) = categorize s ([],[])\n in (reverse (sort att), sort def)\n\ncategorize :: [[String]] -> ([Int], [Int]) -> ([Int], [Int])\ncategorize [] x = x\ncategorize ((\"ATK\":x:_):rest) (atk, def) = categorize rest (read x : atk, def)\ncategorize ((_:x:_):rest) (atk, def) = categorize rest (atk, read x : def)\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nimport Control.Monad\nimport Control.Applicative\n\nfilt [] ys = Just ys\nfilt (x:xs) [] = Nothing\nfilt (x:xs) (y:ys) =\n if y <= x\n then filt (x:xs) ys >>= (return . (y:))\n else filt xs ys\n\nsolve (c0, ja0, jd0) =\n max s1 s2\n where\n [c, ja, jd] = map sort [c0, ja0, jd0]\n\n s1 = sum $ zipWith (\\a b -> max 0 $ a - b) (reverse c) ja\n\n s2 = fromMaybe 0 $ do\n c' <- filt jd c\n return $ if length c' >= length ja && and (zipWith (<=) ja $ reverse c')\n then sum c' - sum ja\n else 0\n\nreadInput = do\n [n, m] <- map read . words <$> getLine\n j <- replicateM n $ words <$> getLine >>= \\[p, s] -> return (p == \"ATK\", read s)\n let (ja, jd) = partition fst j\n c <- replicateM m $ read <$> getLine\n return (c, map snd ja, map snd jd)\n\nmain = print . solve =<< readInput\n"}, {"source_code": "import Data.List (foldl', sort)\nimport qualified Data.IntMap as Map\nimport Data.Maybe (maybeToList)\nimport Data.Function (on)\nimport Control.Monad\n\n-- x is supposed to be descending, att is so too\n-- def is supposed to be ascending\nrush :: ([Int], [Int]) -> [Int] -> Int\nrush (att, []) x = let-- planA = (sum . takeWhile (> 0) . zipWith (-) x) (att ++ repeat 0) \n planB = (sum . takeWhile (> 0) . zipWith (-) x) (reverse att ++ repeat 0)\n in planB\nrush (att, def) x = let x' = concat . maybeToList $ x `kill` def\n x'' = take (length att) x in\n (max `on` rush (att, [])) x' x''\n\nkill :: [Int] -> [Int] -> Maybe [Int]\nkill x def = let xs = foldl' cons Map.empty x\n cons m y = Map.insertWith (+) y 1 m\n xs' = foldl' f (return xs) def\n f ms d = ms >>= \\s -> let att = Map.lookupGT d s in fmap (del s . fst) att\n del = flip $ Map.update (\\y -> if y == 1 then Nothing else Just (y - 1)) \n toList = Map.foldlWithKey' (\\l y c -> l ++ replicate c y) [] \n in fmap (reverse . toList) xs'\n \nmain :: IO ()\nmain = do\n m:n:_ <- fmap (map read . words) getLine\n jiro <- fmap (map words) (replicateM m getLine)\n fox <- fmap (map read) (replicateM n getLine)\n print $ rush (jiroParse jiro) (reverse (sort fox))\n\njiroParse :: [[String]] -> ([Int], [Int])\njiroParse s = let (att, def) = categorize s ([],[])\n in (reverse (sort att), sort def)\n\ncategorize :: [[String]] -> ([Int], [Int]) -> ([Int], [Int])\ncategorize [] x = x\ncategorize ((\"ATK\":x:_):rest) (atk, def) = categorize rest (read x : atk, def)\ncategorize ((_:x:_):rest) (atk, def) = categorize rest (atk, read x : def)\n\n"}, {"source_code": "import Data.List (foldl', sort)\nimport qualified Data.IntMap as Map\nimport Data.Maybe (maybeToList)\nimport Data.Function (on)\nimport Control.Monad\n\n-- x is supposed to be descending, att is so too\n-- def is supposed to be ascending\nrush :: ([Int], [Int]) -> [Int] -> Int\nrush (att, []) x = let-- planA = (sum . takeWhile (> 0) . zipWith (-) x) (att ++ repeat 0) \n planB = (sum . takeWhile (>= 0) . zipWith (-) x) (reverse att ++ repeat 0)\n in planB\nrush (att, def) x = let x' = concat . maybeToList $ x `kill` def\n x'' = take (length att) x in\n (max `on` rush (att, [])) x' x''\n\nkill :: [Int] -> [Int] -> Maybe [Int]\nkill x def = let xs = foldl' cons Map.empty x\n cons m y = Map.insertWith (+) y 1 m\n xs' = foldl' f (return xs) def\n f ms d = ms >>= \\s -> let att = Map.lookupGT d s in fmap (del s . fst) att\n del = flip $ Map.update (\\y -> if y == 1 then Nothing else Just (y - 1)) \n toList = Map.foldlWithKey' (\\l y c -> l ++ replicate c y) [] \n in fmap (reverse . toList) xs'\n \nmain :: IO ()\nmain = do\n m:n:_ <- fmap (map read . words) getLine\n jiro <- fmap (map words) (replicateM m getLine)\n fox <- fmap (map read) (replicateM n getLine)\n print $ rush (jiroParse jiro) (reverse (sort fox))\n\njiroParse :: [[String]] -> ([Int], [Int])\njiroParse s = let (att, def) = categorize s ([],[])\n in (reverse (sort att), sort def)\n\ncategorize :: [[String]] -> ([Int], [Int]) -> ([Int], [Int])\ncategorize [] x = x\ncategorize ((\"ATK\":x:_):rest) (atk, def) = categorize rest (read x : atk, def)\ncategorize ((_:x:_):rest) (atk, def) = categorize rest (atk, read x : def)\n\n"}], "src_uid": "06420ea88312103231a7bbac8a9a62d1"} {"source_code": "main = interact in2out\n\nin2out input\n = output\n where\n output = show $ maximum l2\n items = [read x::Int | x<-tail$words input]\n l1 = 1:tl1\n l2 = 1:tl2\n (tl1,tl2) = solve l1 l2 items\n solve (x1:t1) (x2:t2) (a:b:rest)\n | a == b\n = ((x1+1):a1, (x2+1):a2)\n | a < b\n = ((x1+1):a1, (x1+1):a2)\n | a > b\n = (1:a1, (x2+1):a2)\n where\n (a1,a2) = solve t1 t2 (b:rest)\n solve _ _ _\n = ([],[])\n ", "positive_code": [{"source_code": "import Data.List\nimport Data.Array\nmain = do\n n <- readIO =<< getLine :: IO Int\n l <- (map read . words) `fmap` getLine :: IO [Int]\n let gl = map (\\s'@(s:ss) -> (s, length s')) $ group l\n lgl = length gl\n arr = array (1, lgl) $ zip [1..] gl\n f (l, r) res | l > 1 && fst (arr ! (l - 1)) < fst (arr ! l) = f (l - 1, r) (res \n + snd (arr ! (l - 1)))\n | r < lgl && fst (arr ! (r + 1)) < fst (arr ! r) = f (l, r+1) (res \n + snd (arr ! (r + 1)))\n | otherwise = res\n r = maximum $ map (\\i -> f (i, i) (snd $ arr ! i)) [1..lgl]\n print r\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n\nmain :: IO ()\nmain = \n do {_ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n ; let ns' = g'' ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n ; let ns' = g'' ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "import Data.List;\n\ngao' :: [Int] -> Int -> Int\ngao' xs i = go (reverse $ take (i - 1) xs) n + go (drop i xs) n + 1 where\n\tn :: Int\n\tn = last $ take i xs\n\tgo :: [Int] -> Int -> Int\n\tgo [] _ = 0\n\tgo (x:xs) n\n\t\t| n >= x = 1 + go xs x\n\t\t| otherwise = 0\n\ngao :: [Int] -> String\ngao xs = show $ maximum $ map (gao' xs) [1 .. length xs]\n\nmain' :: String -> String\nmain' input = unlines [gao $ map read $ words $ last $ lines input]\n\nmain = interact main'\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n getLine\n sections <- ( map read . words ) `liftM` getLine\n\n let (_, _, best) = compute sections\n putStrLn $ show best\n\ncompute :: [Int] -> (Int, Int, Int)\ncompute (s1:s2:ss) =\n let (up', down', best') = compute (s2:ss)\n up = 1 + if s1 <= s2 then up' else down'\n down = if s1 >= s2 then down' + 1 else 1\n best = max best' up\n in (up, down, best)\ncompute _ = (1, 1, 1)\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (on)\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\n--h xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\nh xs = head . groupBy (>) $ xs\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u3069\u3046\u304b\u3092\u8abf\u3079\u308b\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u7b87\u6240\u9577\u3055\u3092\u53d6\u5f97\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n\nmain :: IO ()\nmain = \n do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents\n ; let ns' = g'' ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport IO\n\nfoldl' :: (a -> b -> a) -> a -> [b] -> a\nfoldl' _ a [] = a\nfoldl' f a (x:xs) = a' `seq` foldl' f a' xs\n\twhere a' = f a x\n\nleft hs x = d ! x\n\twhere\n\t\td = array (0,n-1) [(i, left' i) | i <- [0..n-1]]\n\t\tn = length hs\n\t\tleft' 0 = 0\n\t\tleft' i\n\t\t\t| (hs !! (i-1)) <= (hs !! i) = d ! (i-1)\n\t\t\t| otherwise = i\n\nright hs x = d ! x\n\twhere\n\t\td = array (0,n-1) [(i, right' i) | i <- reverse [0..n-1]]\n\t\tn = length hs\n\t\tright' i\n\t\t\t| i == n-1 = n-1\n\t\t\t| (hs !! (i+1)) <= (hs !! i) = d ! (i+1)\n\t\t\t| otherwise = i\n\nmain = do\n\ths <- C.hGetContents stdin >>= return . (map (fst . fromJust . C.readInt)) . tail . C.words\n\tlet n = length hs\n\tputStrLn . show $ foldl' max 0 [right hs i - left hs i + 1 | i <- [0..n-1]]\n\t-- print [lowest hs i 1 - lowest hs i (-1) + 1 | i <- [0..n-1]]\n"}, {"source_code": "main :: IO ()\nmain = do \n n <- getLine\n s <- getLine\n let ss = map (read :: String -> Int) (words s)\n print (solve ss)\n\nsolve :: [Int] -> Int\nsolve s = maximum (zipWith (\\x y -> x + y + 1) (f s 0) (reverse (f (reverse s) 0)))\n\nf :: [Int] -> Int -> [Int]\nf [] a = []\nf [x] a = [a]\nf (x : y : xs) a\n | x <= y = a : (f (y : xs) (a + 1))\n | otherwise = a : (f (y : xs) 0)"}, {"source_code": "main :: IO ()\nmain = do \n\tn <- getLine\n\ts <- getLine\n\tlet ss = map (read :: String -> Int) (words s)\n\tprint (solve ss)\n\nsolve :: [Int] -> Int\nsolve s = fst (findmaxind (zipWith (\\x y -> x + y + 1) (f s 0) (reverse (f (reverse s) 0))))\n\nf :: [Int] -> Int -> [Int]\nf [] a = []\nf [x] a = [a]\nf (x : y : xs) a\n\t| x <= y = a : (f (y : xs) (a + 1))\n\t| otherwise = a : (f (y : xs) 0)\n\nfindmaxind :: [Int] -> (Int, Int)\nfindmaxind [] = (-1, -1)\nfindmaxind [x] = (x, 0)\nfindmaxind (x : xs)\n\t| x > fst maxt = (x, 0)\n\t| otherwise = (fst maxt, snd maxt + 1)\n\twhere maxt = findmaxind xs"}, {"source_code": "notLess :: [Int] -> [Int]\nnotLess [] = []\nnotLess (x:xs) = notLess_ 0 0 (x:xs)\n where notLess_ _ _ [] = []\n notLess_ pred count (x:xs) = if (pred > x) then 1:(notLess_ x 1 xs) else ((count + 1):notLess_ x (count + 1) xs)\n\nsolve :: [Int] -> Int\nsolve a = maximum d - 1\n where\n d = zipWith (+) (notLess a) (reverse (notLess (reverse a)))\n\nmain = do\n n <- readLn::(IO Int)\n line <- getLine\n a <- return (map read (words line))\n putStr (show (solve a))\n"}, {"source_code": "import Data.List\nsolve = maximum . flip phaseA 0 . group\nphaseA (x:y:zs) a | head x < head y = phaseA (y:zs) $! a + length x\n | otherwise = phaseB (y:zs) $! a + length x\nphaseA [y] a = [a + length y]\nphaseB (x:y:zs) a | head x > head y = phaseB (y:zs) $! a + length x\n | otherwise = (a+length y) : phaseA (y:zs) (length x)\nphaseB [y] a = [a + length y]\nmain = do\n getLine\n print . solve . map (read :: String -> Int) . words =<< getLine\n"}, {"source_code": "import Data.Array\n\nleft a (-1) = 0\nleft a i\n | a ! i <= a ! (i + 1) = 1 + left a (i - 1)\n | otherwise = 0\n\nright a i\n | snd (bounds a) < i = 0\n | a ! i <= a ! (i - 1) = 1 + right a (i + 1)\n | otherwise = 0\n\ndoJob a (-1) = 0\ndoJob a i = max (doJob a (i - 1)) (1 + (left a (i - 1)) + (right a (i + 1)))\n\nsolve input = \n let (nn:[l]) = lines input in\n let n = (read nn)::Int in\n let a = listArray (0, n - 1) ((map (\\x -> (read x)::Int) . words) l) in\n \n show (doJob a (n - 1))\n\nmain = interact(solve)"}], "negative_code": [{"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (on)\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\n\nh xs = head . groupBy (>) $ xs\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u3069\u3046\u304b\u3092\u8abf\u3079\u308b\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u7b87\u6240\u9577\u3055\u3092\u53d6\u5f97\ng' xs = (map (toInteger . length)) . (map (head . groupBy (<))) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n\nmain :: IO ()\nmain = \n do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents\n ; let ns' = g'' ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . tails $ xs) ((g' . (map reverse) . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ ((maximum ns'),ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ (+1) . fromJust $ (findIndex (==(maximum ns')) ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (on)\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\n\nh xs = head . groupBy (>) $ xs\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u3069\u3046\u304b\u3092\u8abf\u3079\u308b\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u7b87\u6240\u9577\u3055\u3092\u53d6\u5f97\ng' xs = (map (toInteger . length)) . (map (head . groupBy (>))) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n\nmain :: IO ()\nmain = \n do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents\n ; let ns' = g'' ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ ((maximum ns'),ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ (maximum ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . tails $ xs) ((g' . (map reverse) . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ (+1) . fromJust $ (findIndex (==(maximum ns')) ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ (fromJust $ (findIndex (==(maximum ns')) ns'),ns)\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . tails $ xs) ((g' . (map reverse) . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ fromJust $ (findIndex (==(maximum ns')) ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . tails $ xs) ((g' . (map reverse) . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (on)\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\n\nh xs = head . groupBy (>) $ xs\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u3069\u3046\u304b\u3092\u8abf\u3079\u308b\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\n-- \u5897\u52a0\u3057\u3066\u3044\u308b\u7b87\u6240\u9577\u3055\u3092\u53d6\u5f97\ng' xs = (map (toInteger . length)) . (map (head . groupBy (>=))) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n\nmain :: IO ()\nmain = \n do {_:ns <- (map ((+0) . read)).(concatMap split)<$>lines<$>getContents\n ; let ns' = g'' ns in print $ (+1) $ (maximum ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ ((+1) . fromJust $ (findIndex (==(maximum ns')) ns'),ns)\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . tails $ xs) ((g' . (map reverse) . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ fromJust $ (findIndex (==(maximum ns')) ns')\n }\n "}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ngr :: [a] -> [[a]]\ngr xs = zipWith (++) (tails xs) (inits xs)\n\n\nf :: (Num a, Ord a) => [a] -> (Int, a)\nf (n:ns) = ((length xs) , (head xs))\n where\n xs = (takeWhile (<=n) (n:ns))\nf [] = (0,0)\n\nfind' x xs = find (==x) xs\n\nh xs = (takeWhile (> -1)) $ (zipWith (-) xs (tail xs))\n--h' :: [Int] -> [Int]\nh' xs = zipWith (+) (h . reverse . inits $ xs) (h . tails $ xs)\n\ng :: [Integer] -> [Integer]\ng xs = zipWith (-) xs (tail xs)\n\ng' xs = (map (toInteger . length)) . (map (takeWhile (>=0))) .(map g) $ xs\ng'' xs = zipWith (+) (g' . init . tails $ xs) ((g' . (map reverse) . tail . inits) $xs)\n\n\n--(flip find' ns ) \nmain :: IO ()\nmain = \n do { -- _ : ns <- (map ((+0) . read)) <$> (concatMap split) <$> lines <$> readFile \"input.txt\"\n _ : ns <- (map ((+0) . read)) . (concatMap split) <$> lines <$> getContents\n --; let n' = snd . maximum . (map f) . gr $ ns \n --; let n' = h $ ns \n ; let ns' = g' . tails $ ns in print $ (fromJust $ (findIndex (==(maximum ns')) ns'),ns')\n }\n "}, {"source_code": "lowest hs 0 _ = 0\nlowest hs x d\n\t| length hs - 1 == x = x\n\t| (hs !! x+d) <= (hs !! x) = lowest hs (x+d) d\n\t| otherwise = x\n\nmain = do\n\tn <- getLine >>= return . read :: IO Int\n\ths <- getLine >>= return . map read . words :: IO [Int]\n\tputStrLn . show $ foldl max 0 [lowest hs i (1) - lowest hs i (-1) | i <- [0..n-1]]\n"}], "src_uid": "5d11fa8528f1dc873d50b3417bef8c79"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport qualified Data.List as List\nimport Data.Sequence\nimport qualified Data.Set as Set\n\nsolve :: Int -> Integer -> [Int] -> Seq (Integer, Int) -> Set.Set Int -> (Integer, [Int])\nsolve 0 c ans _ _ = (c, ans)\nsolve m c ans qs s = solve m' (c + dist) ans' qs' s'\n where ((dist, pos) :< qs'') = viewl qs\n new_elts = List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]\n qs' = foldl (|>) qs'' new_elts\n s' = foldr (Set.insert . snd) s new_elts\n (ans', m') = if dist == 0 then (ans, m) else (pos : ans, m - 1)\n\nmain :: IO ()\nmain = do\n (_:m:_) <- map read . words <$> getLine\n trees <- map read . words <$> getLine\n let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)\n print cost\n mapM_ (putStr . show >=> const (putStr \" \")) ans >> putStrLn \"\"\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport qualified Data.List as List\nimport Data.Sequence\nimport qualified Data.Set as Set\n\nsolve :: Int -> Integer -> [Int] -> Seq (Int, Int) -> Set.Set Int -> (Integer, [Int])\nsolve 0 c ans _ _ = (c, ans)\nsolve m c ans qs s = solve m' c' ans' qs' s'\n where ((dist, pos) :< qs'') = viewl qs\n new_elts = List.take m $ List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]\n qs' = foldl (|>) qs'' new_elts\n s' = foldr (Set.insert . snd) s new_elts\n ans' = map snd new_elts ++ ans\n l = List.length new_elts\n m' = m - l\n c' = c + (fromIntegral $ (dist+1) * l)\n\nmain :: IO ()\nmain = do\n (_:m:_) <- map read . words <$> getLine\n trees <- map read . words <$> getLine\n let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)\n print cost\n mapM_ (putStr . show >=> const (putStr \" \")) ans >> putStrLn \"\"\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport qualified Data.List as List\nimport Data.Sequence\nimport qualified Data.Set as Set\n\nsolve :: Int -> Integer -> [Int] -> Seq (Int, Int) -> Set.Set Int -> (Integer, [Int])\nsolve 0 c ans _ _ = (c, ans)\nsolve m c ans qs s = solve m' (c + (fromIntegral dist)) ans' qs' s'\n where ((dist, pos) :< qs'') = viewl qs\n new_elts = List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]\n qs' = foldl (|>) qs'' new_elts\n s' = foldr (Set.insert . snd) s new_elts\n (ans', m') = if dist == 0 then (ans, m) else (pos : ans, m - 1)\n\nmain :: IO ()\nmain = do\n (_:m:_) <- map read . words <$> getLine\n trees <- map read . words <$> getLine\n let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)\n print cost\n mapM_ (putStr . show >=> const (putStr \" \")) ans >> putStrLn \"\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport qualified Data.List as List\nimport Data.Sequence\nimport qualified Data.Set as Set\n\nsolve :: Int -> Int -> [Int] -> Seq (Int, Int) -> Set.Set Int -> (Int, [Int])\nsolve 0 c ans _ _ = (c, ans)\nsolve m c ans qs s = solve m' (c + dist) ans' qs' s'\n where ((dist, pos) :< qs'') = viewl qs\n new_elts = List.filter (flip Set.notMember s . snd) [(dist+1, pos-1), (dist+1, pos+1)]\n qs' = foldl (|>) qs'' new_elts\n s' = foldr (Set.insert . snd) s new_elts\n (ans', m') = if dist == 0 then (ans, m) else (pos : ans, m - 1)\n\nmain :: IO ()\nmain = do\n (_:m:_) <- map read . words <$> getLine\n trees <- map read . words <$> getLine\n let (cost, ans) = solve m 0 [] (fromList $ map (0,) trees) (Set.fromList trees)\n print cost\n mapM_ (putStr . show >=> const (putStr \" \")) ans >> putStrLn \"\"\n"}], "src_uid": "3a3666609b120d208c3e8366b186d89b"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n [n,m,h] <- map readInt . words <$> getLine\n as <- unfoldr (runStateT rIntS) <$> BS.getLine\n bs <- unfoldr (runStateT rIntS) <$> BS.getLine\n forM_ bs $ \\ !b -> do\n hs <- unfoldr (runStateT rIntS) <$> BS.getLine\n putStrLn $ unwords $ map show\n $ zipWith (\\h a -> if h==0 then 0 else min a b) hs as\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nsolve ::[Int] -> [Int] -> [Int] ->[[Int]] ->[[Int]]\nsolve [breite,tiefe,hoehe] front seite oben =foben oben $ ffront fseite \n\twhere \n\t\tfseite :: [[Int]]\n\t\tfseite =map (replicate breite) seite\n\t\tffront :: [[Int]] -> [[Int]]\n\t\tffront g = map (zipWith min front) g \n\n\t\t\n\t\t\n\nfoben :: [[Int]]->[[Int]]->[[Int]]\nfoben oben g2 = zipWith helper oben g2\n\twhere\n\t\thelper :: [Int] -> [Int] -> [Int]\n\t\thelper oben z2 = zipWith (\\o z -> if o==1 then z else 0) oben z2\n\nmain :: IO ()\nmain = do\n\t[tiefe,breite,hoehe] <- fmap ((map read).words) getLine\n\tfront <- fmap ((map read).words) getLine\n\tseite <- fmap ((map read).words) getLine\n\toben <- replicateM tiefe $ fmap ((map read).words) getLine\n\tputStrLn $ intercalate \"\\n\" $ map (concat.(intersperse \" \")) $ map (map show) $ solve [breite,tiefe,hoehe] front seite oben \n\treturn ()"}], "negative_code": [], "src_uid": "7361e8acf0d712c317e8b99211a7b548"} {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Text.Printf\n\nreadInt :: B.ByteString -> Int\nreadInt = fst . fromJust . B.readInt\n\nreadInt2 :: B.ByteString -> (Int, Int)\nreadInt2 = l2t . map readInt . B.words\nl2t [x,y] = (x,y)\n\n(|>) x f = f x; infixl 1 |>\ncar = head\ncadr = head . tail\n\nmain :: IO ()\nmain = do\n ls <- B.lines <$> B.getContents\n let (n, k) = car ls |> readInt2\n xs = cadr ls |> B.words |> map (fst . fromJust . B.readInt)\n xs' = map (\\(x, i) -> x - i * k) $ zip xs [0 .. ]\n m = majority $ filter (> 0) xs' \n cs = xs' |> zip [1 .. ]\n |> filter (\\e -> (snd e) /= m)\n |> map (diff m)\n\n -- print xs'\n -- print m\n print $ length cs\n forM_ cs putStrLn\n\nmajority ls =\n head $ snd $ head $ reverse $ sort $ map (\\l -> (length l, l)) $ group $ sort ls\n\ndiff m (i, x) =\n (if x < m then \"+ \" else \"- \") ++ show i ++ \" \" ++ show (abs (m - x))\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n let l = head $ sortBy cmpLen $ do\n i <- [1..1000]\n let result = [i + k * j | j <- [0..]]\n return $ filter ((/=0).snd) $ zip [1..] $ zipWith (-) result as\n print $ length l\n forM_ l $ \\(i,x) ->\n putStrLn $ unwords [(if x > 0 then \"+\" else \"-\"),show i,show $ abs x]\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Text.Printf\n\nreadInt :: B.ByteString -> Int\nreadInt = fst . fromJust . B.readInt\n\nreadInt2 :: B.ByteString -> (Int, Int)\nreadInt2 = l2t . map readInt . B.words\nl2t [x,y] = (x,y)\n\n(|>) x f = f x; infixl 1 |>\ncar = head\ncadr = head . tail\n\nmain :: IO ()\nmain = do\n ls <- B.lines <$> B.getContents\n let (n, k) = car ls |> readInt2\n xs = cadr ls |> B.words |> map (fst . fromJust . B.readInt)\n xs' = map (\\(x, i) -> x - i * k) $ zip xs [0 .. ]\n m = majority xs' \n cs = xs' |> zip [1 .. ]\n |> filter (\\e -> (snd e) /= m)\n |> map (diff m)\n\n print $ length cs\n forM_ cs putStrLn\n\nmajority ls =\n head $ snd $ head $ reverse $ sort $ map (\\l -> (length l, l)) $ group $ sort ls\n\ndiff m (i, x) =\n (if x < m then \"+ \" else \"- \") ++ show i ++ \" \" ++ show (abs (m - x))"}], "src_uid": "7f08e74945d6b58abde1d8002b8b686a"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 0 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\n\nsolve :: [Integer] -> Integer\nsolve (a:[]) = a\nsolve as = maximum $ map (uncurry (+)) $ zip (0:ls) rs where \n [ls,rs] = map concat $ map ($ ((zipWith (+)), chunk as)) (map uncurry [scanl1, scanr1]) \n chunk (a:[]) = [[a,0]]\n chunk (a:b:xs) = [a,b] : chunk xs\n\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 0 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n\nsolve :: [Integer] -> Integer\nsolve (a:[]) = a\nsolve as = maximum $ add (0:ls) rs where \n [ls,rs] = map (\\f-> concat $ f add $ chunk as) [scanl1, scanr1]\n add xs ys = map (uncurry (+)) $ zip xs ys\n chunk (a:[]) = [[a,0]]\n chunk (a:b:xs) = [a,b] : chunk xs\n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 0 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\n\nsolve :: [Integer] -> Integer\nsolve (a:[]) = a\nsolve as = maximum $ map (uncurry (+)) $ zip (0:ls) rs where \n [ls,rs] = fmap concat [lss, rss] \n lss = scanl1 (zipWith (+)) $ chunk as; \n rss = scanr1 (zipWith (+)) $ chunk as; \n chunk (a:[]) = [[a,0]]\n chunk (a:b:xs) = [a,b] : chunk xs\n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 0 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\n\nsplit :: [Integer] -> ([Integer],[Integer])\nsplit [] = ([],[])\nsplit (x:zs) = ((x:ys), xs) where (xs,ys) = split zs\n\nmerge :: [Integer] -> [Integer] -> [Integer]\nmerge [] ys = ys\nmerge (x:xs) ys = x:(merge ys xs)\n\nsolve :: [Integer] -> Integer\nsolve (a:[]) = a\nsolve as = maximum $ map (uncurry (+)) $ zip (0:ls) rs where \n ls = merge lsum1 lsum2\n lsum1 = scanl1 (+) odds\n lsum2 = scanl1 (+) evens\n rs = merge rsum1 rsum2\n rsum1 = scanr1 (+) odds\n rsum2 = scanr1 (+) evens\n (odds,evens) = split as\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 0 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\n\nsplit :: [Integer] -> ([Integer],[Integer])\nsplit [] = ([],[])\nsplit (x:zs) = ((x:ys), xs) where (xs,ys) = split zs\n\nmerge :: [Integer] -> [Integer] -> [Integer]\nmerge [] ys = ys\nmerge (x:xs) ys = x:(merge ys xs)\n\nsolve :: [Integer] -> Integer\nsolve (a:[]) = a\nsolve as = maximum $ map (uncurry (+)) $ zip ls (drop 1 rs) where \n ls = merge lsum1 lsum2\n lsum1 = scanl1 (+) odds\n lsum2 = scanl1 (+) evens\n rs = merge rsum1 rsum2\n rsum1 = scanr1 (+) odds\n rsum2 = scanr1 (+) evens\n (odds,evens) = split as\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\nmain :: IO ()\nmain = interact $ lines >>> drop 0 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : as : rest) = (itoline . solve . linetois) as : tcio rest where\n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n istoline = unwords . (map itoline)\n linestoiss = (map linetois) . lines\n isstolines = unlines . (map istoline)\n\n\nsplit :: [Int] -> ([Int],[Int])\nsplit [] = ([],[])\nsplit (x:zs) = ((x:ys), xs) where (xs,ys) = split zs\n\nmerge :: [Int] -> [Int] -> [Int]\nmerge [] ys = ys\nmerge (x:xs) ys = x:(merge ys xs)\n\nsolve :: [Int] -> Int\nsolve (a:[]) = a\nsolve as = maximum $ map (uncurry (+)) $ zip ls (drop 1 rs) where \n ls = merge lsum1 lsum2\n lsum1 = scanl1 (+) odds\n lsum2 = scanl1 (+) evens\n rs = merge rsum1 rsum2\n rsum1 = scanr1 (+) odds\n rsum2 = scanr1 (+) evens\n (odds,evens) = split as\n"}], "src_uid": "a9473e6ec81c10c4f88973ac2d60ad04"} {"source_code": "import Control.Applicative\n\nmain = do n <- read <$> getLine\n putStrLn $ unwords $ map show $ solve n\n\nsolve :: Integer -> [Integer]\nsolve n = [(minimum ms),(maximum ms)]\n where ms = map (\\ [x,y,z] -> (x+1)*(y+2)*(z+2)-n) $ concatMap (\\x -> map (\\y -> [(div n x),y,(div x y)]) $ f x) $ f n\n\nf :: Integer -> [Integer] \nf n = f' $ filter ((0==).mod n) $ takeWhile (\\x -> x*x <= n) [1..]\n where f' ns = ns ++ (map (div n) ns)\n", "positive_code": [{"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read"}, {"source_code": "{-\nimport Test.QuickCheck\nimport qualified Data.Set as S\nimport qualified Math.NumberTheory.Primes as P\nimport Data.List\n\npropDivisors :: Positive Int -> Bool\npropDivisors (Positive n') = sort divs == sort (divisors n)\n where\n n = (n' `mod` 10^9)+1\n divs = map fromIntegral $ S.elems $ P.divisors (fromIntegral n)\n\nmainTest = quickCheck propDivisors\n-}\n\nimport Data.Int\n\ntriples n = [ (x,y,z) |\n x <- takeWhile (\\x -> x*x*x <= n) [1..],\n n `rem` x == 0,\n let q = n `div` x,\n y <- takeWhile (\\x -> x*x <= q) [x..],\n q `rem` y == 0,\n let z = q `div` y ]\n\nstolen n x y z = [ (x'+1)*(y'+2)*(z'+2) - n', (z'+1)*(y'+2)*(x'+2) - n' ]\n where n' = fromIntegral n\n x' = fromIntegral x\n y' = fromIntegral y\n z' = fromIntegral z\n\nsolve n = (minimum ds, maximum ds)\n where trips = triples n\n ds = concatMap (\\(x,y,z) -> stolen n x y z) (triples n) :: [Int64]\n\nmainSolve = do\n n <- fmap read getLine :: IO Int\n let (a,b) = solve n\n putStrLn $ show a ++ \" \" ++ show b\n\nmain = mainSolve\n\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}, {"source_code": "--142A\n\nimport Data.Array\nimport Data.List (group, genericLength)\n\nisDividor :: Integral a => a -> a -> Bool\nisDividor m n = m `rem` n == 0\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3, 5 ..]\n\nisPrime :: Integral a => a -> Bool\nisPrime n = all (not . isDividor n) (takeWhile (\\x -> x * x <= n) primes)\n\nfactorize :: Integral a => a -> [a]\nfactorize 0 = []\nfactorize n = factorize' n primes\n where\n factorize' 1 _ = []\n factorize' n (p:ps)\n | r == 0 = p : factorize' q (p:ps)\n | q < p = [n] -- i.e. p * p > n\n | otherwise = factorize' n ps\n where\n (q, r) = quotRem n p\n\nfactorizeP :: Integral a => a -> [(a, a)]\nfactorizeP = map (\\x -> (head x, genericLength x)) . group . factorize\n\ndividers :: Integral a => a -> [a]\ndividers n = dividers' empty\n where\n fs = factorizeP n\n k = length fs\n empty = accumArray undefined 0 (1,k) []\n dividers' array = d : case (nextArray 1) of\n Nothing -> []\n Just array' -> dividers' array'\n where\n d = product $ zipWith (^) (map fst fs) (elems array)\n nextArray i\n | i > k = Nothing\n | array ! i == (snd $ fs !! (i-1)) = nextArray (i+1)\n | otherwise = Just $ array // ((i, array ! i + 1) : [(j, 0) | j <- [1..i-1]])\n\nsolve :: Integer -> (Integer, Integer)\nsolve n = (min - n, max - n)\n where\n min = minimum all\n max = maximum all\n all = [v y z | y <- ds, z <- ds, y <= z, y * z <= n, n `mod` (y * z) == 0]\n ds = dividers n\n v y z = (x + 1) * (y + 2) * (z + 2)\n where\n x = n `div` (y * z)\n\nprintP :: Show a => (a, a) -> IO ()\nprintP (a,b) = putStrLn $ show a ++ \" \" ++ show b\n\nmain :: IO ()\nmain = readLn >>= printP . solve\n"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(a+1)*(c+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read\n"}], "negative_code": [{"source_code": "import Control.Applicative\n\nmain = do n <- read <$> getLine\n putStrLn $ unwords $ map show $ solve n\n\nsolve :: Integer -> [Integer]\nsolve n = map (subtract n) [(minimum ms),(maximum ms)]\n where ms = concatMap ((\\ [x,y] -> concatMap (g.(y:)) (f x))) $ f n\n\nf :: Integer -> [[Integer]]\nf n = map (\\x -> [(div n x),x]) $ (1:) $ filter ((0==).mod n) $ takeWhile (\\x-> x*x <= n) primes\n\ng [x,y,z] = [(x+1)*(y+2)*(z+2),(y+1)*(z+2)*(x+2),(z+1)*(x+2)*(y+2)]\n\nprimes = 2 : filter (\\x -> isPrime x primes) [3,5..]\nisPrime n (x:xs) = (n < x*x) || ((mod n x /= 0) && (isPrime n xs))\n"}, {"source_code": "s n=show(minimum l)++\" \"++show(maximum l) where l=[(x+1)*(y+2)*(z+2)-n|a<-[1..1000],b<-[1..1000],let c=n`div`a`div`b,c*a*b==n,(x,y,z)<-[(a,b,c),(b,a,c),(c,b,a)]]\nmain=interact$s.read"}, {"source_code": "s n=show(minimum l)++\" \"++show(maximum l) where l=[(x+1)*(y+2)*(z+2)-n|a<-[1..1000],b<-[1..1000],let c=n`div`a`div`b,c*a*b==n,(x,y,z)<-[(a,b,c),(b,a,c),(c,b,a)]]\nmain=interact$unwords.map show.s.read"}, {"source_code": "f 0 n=[[n]]\nf i n=[d:t|d<-fst$span((<=n).(^2))[1..],n`mod`d==0,t<-f(i-1)(n`div`d)]\nl n=[(c+1)*(a+2)*(b+2)-n|[a,b,c]<-f 2 n]\ns n=show(minimum.l$n)++' ':show(n*8+9)\nmain=interact$s.read"}], "src_uid": "2468eead8acc5b8f5ddc51bfa2bd4fb7"} {"source_code": "module Main (main) where\n\nimport Data.List\nimport qualified Data.Map.Lazy as Map\n\ntype MapType = Map.Map Integer Integer\n\nreadIntegers :: String -> [Integer]\nreadIntegers = map read . words\n\nsolve :: [Integer] -> [Integer]\nsolve lst = reverse ans where \n insert' :: [Integer] -> MapType -> MapType\n insert' [] mp = mp\n insert' (x:xs) mp = insert' xs (Map.insertWith (+) x 1 mp)\n mmap = insert' lst (Map.fromList [])\n findFirst :: [Integer] -> MapType -> Integer\n findFirst (x:xs) mp = res where \n fit = ((mod x 2 > 0) || (Map.lookup (div x 2) mp) == Nothing) && ((Map.lookup (x * 3) mp) == Nothing)\n res = if fit then x else findFirst xs mp\n first = findFirst lst mmap\n solve' :: MapType -> Int -> Integer -> [Integer] -> [Integer]\n solve' mp 0 x res = res\n solve' mp cnt x res = solve' mp' (cnt-1) next (x:res) where\n t = Map.lookup (x*2) mp\n next = if t /= Nothing && t > (Just 0) then x * 2 else (div x 3)\n mp' = Map.insertWith (-) 1 next mp\n ans = solve' mmap (length lst) first []\n\n\n\n \n\n\nmain :: IO ()\nmain = putStrLn . toStr. solve . readIntegers =<< (getLine >> getLine)\n where toStr = unwords . map show\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.Int\n\ntakeElements :: [a] -> [(a, [a])]\ntakeElements [] = []\ntakeElements (x:xs) = (x, xs) : [(y, x:ys) | (y, ys) <- takeElements xs]\n\nsolve :: [Int64] -> [[Int64]]\nsolve = go []\n where\n go :: [Int64] -> [Int64] -> [[Int64]]\n go [] zs = do\n (y, ys) <- takeElements zs\n go [y] ys\n go ls [] = [reverse ls]\n go ls@(l:_) zs = do\n (i, is) <- takeElements zs\n if i == (l * 2) || (l `mod` 3 == 0 && i * 3 == l) then go (i:ls) is\n else []\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine\n let result = head $ solve xs\n putStrLn $ unwords (map show result)\n"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = do\n n <-readLn\n as <- fmap (map read . words) getLine\n putStrLn $ unwords $ map show $ solve n as\n\n\nsolve :: Int -> [Integer] -> [Integer]\nsolve n as =\n map fst $ sortBy(compare`on`f) $ map factorize as\n where\n f (k,(c2,c3)) = (-c3,c2)\n\nfactorize :: Integer -> (Integer, (Integer,Integer))\nfactorize n =\n (n,(c2,c3))\n where\n (c2,n') = go 0 2 n\n (c3,_ ) = go 0 3 n'\n\n go c p k = let (q,r) = k`divMod`p\n in if r==0 then go (c+1) p q else (c,k)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- unfoldr (B.readInteger.B.dropWhile isSpace) <$> B.getLine\n putStrLn.unwords.map show $ solve n xs\n\nsolve :: Int -> [Integer] -> [Integer]\nsolve n xs = head [hist | x<-xs, Just hist <- pure $ dfs x [x] (S.delete x $ S.fromList xs)]\n where\n dfs _ hist unused | S.null unused = Just $ reverse hist\n dfs cur hist unused = case quotRem cur 3 of\n (q, 0) | !c2 <- 2 * cur, S.member q unused && S.member c2 unused ->\n dfs q (q:hist) (S.delete q unused)\n <|> dfs c2 (c2:hist) (S.delete c2 unused)\n | S.member q unused -> dfs q (q:hist) (S.delete q unused)\n (_, _) | !c2 <- 2 * cur, S.member c2 unused -> dfs c2 (c2:hist) (S.delete c2 unused)\n _ -> Nothing\n\n\n"}], "negative_code": [], "src_uid": "f9375003a3b64bab17176a05764c20e8"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Tuple\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport Data.Either\nimport Data.Ix\nimport Debug.Trace\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,x] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr.unlines.map show.sort $ solve n x xs\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n x xs = map (xi+) $ filter (unsafeAt dp) [0..n-xi]\n where\n gr = mkGraph n edges \n edges = zip xs [1..]\n (ls,[xi]) = partitionEithers.sort.map (elemSmart x.childs gr) $ roots n edges\n !dp = gen n ls\n\ngen :: Int -> [Int] -> UArray Int Bool\ngen n sorted = runSTUArray $ do\n dp <- newArray (0,n) False :: ST s (STUArray s Int Bool)\n unsafeWrite dp 0 True\n forM sorted $ \\x-> do\n forM [n-x,n-x-1..0] $ \\i-> do\n dpi <- unsafeRead dp i\n when dpi $ do\n unsafeWrite dp (i+x) True\n return dp\n\nelemSmart :: Vertex -> [Vertex] -> Either Int Int\nelemSmart x vs\n | Just i <- elemIndex x vs = Right $! i+1\n | otherwise = Left $! length vs\n\ntype Graph = UArray Vertex Vertex\ntype Vertex = Int\ntype Edge = (Vertex,Vertex)\n\nmkGraph :: Int -> [Edge] -> Graph\nmkGraph n es = runSTUArray $ do\n gr <- newArray (0,n) 0 :: ST s (STUArray s Vertex Vertex)\n forM es $ \\ (from,to) -> do\n unsafeWrite gr from to\n return gr\n\nmkRevGraph :: Int -> [Edge] -> Graph\nmkRevGraph n es = runSTUArray $ do\n gr <- newArray (0,n) 0 :: ST s (STUArray s Vertex Vertex)\n forM es $ \\ (to,from) -> do\n unsafeWrite gr from to\n return gr\n\nroots :: Int -> [Edge] -> [Vertex]\nroots n es = filter ((0==).unsafeAt revgr) [1..n]\n where\n !revgr = mkRevGraph n es\n\nchilds :: Graph -> Vertex -> [Vertex]\nchilds gr v = takeWhile (0<) $ iterate (unsafeAt gr) v\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Tuple\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport Data.Either\nimport Data.Ix\nimport Debug.Trace\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,x] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n putStr.unlines.map show.sort $ solve n x xs\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n x xs = map (xi+) $ filter (unsafeAt dp) [0..n-xi]\n where\n gr = mkGraph n edges \n edges = zip xs [1..]\n (ls,[xi]) = partitionEithers.sort.map (elemSmart x.childs gr) $ roots n edges\n !dp = gen n ls\n\ngen :: Int -> [Int] -> UArray Int Bool\ngen n sorted = runSTUArray $ do\n dp <- newArray (0,n) False :: ST s (STUArray s Int Bool)\n unsafeWrite dp 0 True\n forM sorted $ \\x-> do\n forM [n-x,n-x-1..0] $ \\i-> do\n dpi <- unsafeRead dp i\n when dpi $ do\n unsafeWrite dp (i+x) True\n return dp\n\nelemSmart :: Vertex -> [Vertex] -> Either Int Int\nelemSmart x vs\n | Just i <- elemIndex x vs = Right $! i+1\n | otherwise = Left $! length vs\n\ntype Graph = UArray Vertex Vertex\ntype Vertex = Int\ntype Edge = (Vertex,Vertex)\n\nmkGraph :: Int -> [Edge] -> Graph\nmkGraph n es = runSTUArray $ do\n gr <- newArray (0,n) 0 :: ST s (STUArray s Vertex Vertex)\n forM es $ \\ (from,to) -> do\n unsafeWrite gr from to\n return gr\n\nmkRevGraph :: Int -> [Edge] -> Graph\nmkRevGraph n es = runSTUArray $ do\n gr <- newArray (0,n) 0 :: ST s (STUArray s Vertex Vertex)\n forM es $ \\ (to,from) -> do\n unsafeWrite gr from to\n return gr\n\nroots :: Int -> [Edge] -> [Vertex]\nroots n es = filter ((0==).unsafeAt revgr) [1..n]\n where\n !revgr = mkRevGraph n es\n\nchilds :: Graph -> Vertex -> [Vertex]\nchilds gr v = takeWhile (0<) $ iterate (unsafeAt gr) v\n"}], "negative_code": [], "src_uid": "5a6b97a2aa27dd2c562f73a7a8f16720"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport System.IO\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray,IOArray)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\ngetIntLn handle = fmap (map readInt.B.words) $ B.hGetLine handle\ngetIntAll handle = fmap (map readInt.B.words) $ B.hGetContents handle\n\nmain = do\n hin <- openFile \"input.txt\" ReadMode\n hout <- openFile \"output.txt\" WriteMode\n\n (n:xs) <- getIntAll hin\n\n cnt <- newArray (0,5000) 0 :: IO (IOUArray Int Int)\n ans <- newArray (0,5000) [] :: IO (IOArray Int [Int])\n\n forM_ (zip[1..]xs) $ \\(i,x) -> do\n unsafeRead cnt x >>= unsafeWrite cnt x.(1+)\n unsafeRead ans x >>= unsafeWrite ans x.(i:)\n isValid <- all even <$> mapM (unsafeRead cnt) [1..5000]\n \n if isValid\n then hPutStr hout.parse.concat =<< mapM (unsafeRead ans) [1..5000]\n else hPrint hout $ -1\n\n hClose hin\n hClose hout\n\nparse :: [Int] -> String\nparse (i:j:rest) = shows i\" \" ++ shows j \"\\n\" ++ parse rest\nparse _ = \"\"", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Function\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport qualified Data.IntMap.Strict as I\n \n \nmyprint::[String]->[Int]->[String]\nmyprint x [] = x\nmyprint q (x:y:z) = myprint ( ( show x ++ \" \" ++ show y++ \"\\n\"):q) z\n\n\nmain=do\n\tn<-B.readFile \"input.txt\"\n\tlet s = tail $ map (fst.fromJust.B.readInt) $ B.words n:: [Int]\n\tlet t= foldl (\\acc z->I.insertWith (++) (fst z ) [snd z] acc) I.empty $ zip s [1..]::I.IntMap [Int]\n\tlet t1= I.elems t\n\twriteFile \"output.txt\" $if any (odd) (map length t1) then \"-1\\n\" else concat $ reverse $ myprint [\"\"] $ concat t1\n\t "}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array\nimport Data.Array.ST\nimport Data.Char (ord)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\ninputFile = \"input.txt\"\noutputFile = \"output.txt\"\n\nreads :: String -> [Int]\nreads = map read . words\n where\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10*a + ord c - ord '0') s\n\nprints :: Show a => [a] -> String\nprints = intercalate \" \" . map show\n\nshowAns :: [(Int, Int)] -> String\nshowAns [] = \"-1\"\nshowAns xs = unlines $ map showPair xs\n where\n showPair (x, y) = concat [show x, \" \", show y]\n\nsolve :: [Int] -> [(Int, Int)]\nsolve as\n | existSolve = concatMap (getPairs . (array !)) [1..size]\n | otherwise = []\n where\n size = 5000\n array :: Array Int [Int]\n array = runSTArray $ do\n array <- newArray (1, size) []\n mapM_ (update array) $ zip [1..] as\n return array\n where\n update array (i, a) = do\n is <- readArray array a\n writeArray array a (i:is)\n existSolve = all (even . length . (array !)) [1..size]\n getPairs [] = []\n getPairs (a:b:as) = (a,b) : getPairs as\n\nmain :: IO ()\nmain = do\n input <- readFile inputFile\n let as = tail $ reads input\n let output = showAns $ solve as\n writeFile outputFile output"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\nimport System.IO (IOMode(..), openFile, hPrint, hPutStrLn)\n\nsolve :: Int -> [Int] -> Maybe [(Int, Int)]\nsolve n xs\n | length xs' == n = Just xs'\n | otherwise = Nothing\n where\n xs' = solve' e $ zip [1..] xs\n e = listArray (1,5000) [0,0..]\n solve' _ [] = []\n solve' a ((n, x) : xs)\n | a ! x > 0 = (a ! x, n) : solve' a' xs\n | otherwise = solve' a'' xs\n where\n a' = a // [(x, 0)]\n a'' = a // [(x, n)]\n\nprintAns Nothing = print (-1)\nprintAns (Just xs) = do\n hOutput <- openFile \"output.txt\" WriteMode\n mapM_ (print' hOutput) xs\n where\n print' hOutput (a, b) = hPutStrLn hOutput $ concat [show a, \" \", show b]\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines $ readFile \"input.txt\"\n let n = read $ lines' !! 0\n let xs = map read $ words $ lines' !! 1\n-- n <- readLn\n-- xs <- liftM (map read . words) getLine\n printAns $ solve n xs"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\nimport System.IO (IOMode(..), hClose, hPrint, hPutStrLn, openFile)\n\nsolve :: Int -> [Int] -> Maybe [(Int, Int)]\nsolve n xs\n | length xs' == n = Just xs'\n | otherwise = Nothing\n where\n xs' = solve' e $ zip [1..] xs\n e = listArray (1,5000) [0,0..]\n solve' _ [] = []\n solve' a ((n, x) : xs)\n | a ! x > 0 = (a ! x, n) : solve' a' xs\n | otherwise = solve' a'' xs\n where\n a' = a // [(x, 0)]\n a'' = a // [(x, n)]\n\nprintAns Nothing = print (-1)\nprintAns (Just xs) = do\n hOutput <- openFile \"output.txt\" WriteMode\n mapM_ (print' hOutput) xs\n hClose hOutput\n where\n print' hOutput (a, b) = hPutStrLn hOutput $ concat [show a, \" \", show b]\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines $ readFile \"input.txt\"\n let n = read $ lines' !! 0\n let xs = map read $ words $ lines' !! 1\n-- n <- readLn\n-- xs <- liftM (map read . words) getLine\n printAns $ solve n xs"}], "src_uid": "0352429425782d7fe44818594eb0660c"} {"source_code": "\nimport Monad (liftM)\n\nparse :: Read a => String -> (a, a)\nparse line = case words line of\n [s1, s2] -> (read s1, read s2)\n\nf i j k\n | k == 1 = if i `mod` 2 == 1 && j `mod` 2 == 1 then 0 else 1\n | i > j = f j i k\n | i `mod` (k+1) == 0 = 2 + (i+j) `mod` 2\n | otherwise = (i + j + min i' j') `mod` 2\n where\n (i', j') = (i `div` (k+1), j `div` (k+1))\n\nsolve :: Int -> (Int, Int) -> String\nsolve k (n, m) = if f n m k == 0 then \"-\" else \"+\"\n\nmain :: IO ()\nmain = do\n ls <- liftM lines $ readFile \"input.txt\"\n let (t, k) = parse . head $ ls\n let xs = map parse . take t . tail $ ls\n writeFile \"output.txt\" $ unlines $ map (solve k) xs\n", "positive_code": [{"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf input = output where\n output = unlines $ a q\n [t,k]:q = map (map (read::String->Integer)) $ map words $ lines input\n a [] = []\n a ([n,m]:xs) = (answer n m):a xs\n answer n m\n | mod x (k+1) == 0 = \"+\"\n | mod (div x (k+1)) 2 == 0 || k==1 = if y then \"-\" else \"+\"\n | otherwise = if y then \"+\" else \"-\"\n where\n x = min n m\n y = mod (n+m) 2 == 0\n"}], "negative_code": [{"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf input = output where\n output = unlines $ a q\n [t,k]:q = map (map (read::String->Integer)) $ map words $ lines input\n a [] = []\n a ([n,m]:xs) = (answer n m):a xs\n answer n m\n | mod x (k+1) == 0 = \"+\"\n | mod (div x (k+1)) 2 == 0 || k==0 = if y then \"-\" else \"+\"\n | otherwise = if y then \"+\" else \"-\"\n where\n x = min n m\n y = mod (n+m) 2 == 0\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf input = output where\n output = unlines $ a q\n [t,k]:q = map (map (read::String->Int)) $ map words $ lines input\n a [] = []\n a ([n,m]:xs) = (answer n m):a xs\n answer n m\n | mod x (k+1) == 0 = \"+\"\n | mod (div x (k+1)) 2 == 0 = if y then \"-\" else \"+\"\n | otherwise = if y then \"+\" else \"-\"\n where\n x = min n m\n y = mod (n+m) 2 == 0\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf input = output where\n output = unlines $ a q\n [t,k]:q = map (map (read::String->Integer)) $ map words $ lines input\n a [] = []\n a ([n,m]:xs) = (answer n m):a xs\n answer n m\n | mod x (k+1) == 0 = \"+\"\n | mod (div x (k+1)) 2 == 0 = if y then \"-\" else \"+\"\n | otherwise = if y then \"+\" else \"-\"\n where\n x = min n m\n y = mod (n+m) 2 == 0\n"}], "src_uid": "1f5f5ccbdfcbe5cb2d692475f0726bfd"} {"source_code": "import Control.Monad\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- read <$> getLine :: IO Int\n bfs <- map read . words <$> getLine :: IO [Int]\n print $ solve (M.singleton 1 0) bfs (tail bfs) 0\n\nsolve :: M.Map Int Int -> [Int] -> [Int] -> Int -> Int\nsolve h _ [] _ = maximum $ M.elems h\nsolve h (x:xs) (y:ys) p \n | y > p = solve (M.insert y (h M.! x + 1) h) (x:xs) ys y\n | otherwise = solve h xs (y:ys) 0\nsolve _ _ _ _ = error \"Solve called with invalid params\"\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve = maximum . foldl f [0] . blocks . tail\n where\n f (d:ds) l = ds ++ replicate l (d + 1)\n\nblocks :: [Int] -> [Int]\nblocks [_] = [1]\nblocks (x:x':xs)\n | x < x' = (1 + head ls) : tail ls\n | otherwise = 1 : ls\n where\n ls = blocks (x' : xs)\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs = go bs [0]\n -- f l ds = tail ds ++ replicate l (1 + head ds)\n where\n bs = blocks (tail xs)\n go [] ds = maximum ds\n -- go _ ds = maximum ds\n go (l:ls) ds = go ls (tail ds ++ replicate l (1 + head ds))\n\nblocks :: [Int] -> [Int]\nblocks [_] = [1]\nblocks (x:x':xs)\n | x < x' = (1 + head ls) : tail ls\n | otherwise = 1 : ls\n where\n ls = blocks (x' : xs)\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve = maximum . foldl bfs [0] . blocks' . tail\n where\n bfs (d:ds) l = ds ++ replicate l (d + 1)\n\nblocks :: [Int] -> [Int]\nblocks [_] = [1]\nblocks (x:x':xs)\n | x < x' = (1 + head ls) : tail ls\n | otherwise = 1 : ls\n where\n ls = blocks (x' : xs)\n\nblocks' :: [Int] -> [Int]\nblocks' xs = foldr f [1] $ zipWith (<) xs (tail xs)\n where\n f True (l:ls) = 1 + l : ls\n f False ls = 1 : ls\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve = maximum . foldl bfs [0] . blocks (<) . tail\n where\n bfs (d:ds) l = ds ++ replicate l (d + 1)\n\nblocks :: (a -> a -> Bool) -> [a] -> [Int]\nblocks f xs = foldr (bool appl incl) [1] $ zipWith f xs (tail xs)\n where\n appl = (1 :)\n incl (l:ls) = 1 + l : ls\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs = go (length xs) bs [0]\n where\n bs = blocks (tail xs)\n go _ [] ds = maximum ds\n go 0 _ ds = maximum ds\n go n (l:ls) ds = go (n - 1) ls (tail ds ++ replicate l (1 + head ds))\n\nblocks :: [Int] -> [Int]\nblocks [_] = [1]\nblocks (x:x':xs)\n | x < x' = (1 + head ls) : tail ls\n | otherwise = 1 : ls\n where\n ls = blocks (x' : xs)\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs = go (length xs) bs [0]\n where\n bs = blocks (tail xs)\n go _ [] ds = maximum ds\n go 0 _ ds = maximum ds\n go n (l:ls) ds = go (n - 1) ls (tail ds ++ replicate l (1 + head ds))\n\nblocks :: [Int] -> [Int]\nblocks [_] = [1]\nblocks (x:x':xs)\n | x < x' = (1 + head ls) : tail ls\n | otherwise = 1 : ls\n where\n ls = blocks (x' : xs)\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs = maximum $ foldl f [0] bs\n where\n bs = blocks (tail xs)\n f ds l = tail ds ++ replicate l (1 + head ds)\n --go [] ds = maximum ds\n --go (l:ls) ds = go ls (tail ds ++ replicate l (1 + head ds))\n\nblocks :: [Int] -> [Int]\nblocks [_] = [1]\nblocks (x:x':xs)\n | x < x' = (1 + head ls) : tail ls\n | otherwise = 1 : ls\n where\n ls = blocks (x' : xs)\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs = (+ 1) . length . filter id $ zipWith (>) xs (tail xs)\n"}], "src_uid": "16c4160d1436206412ce51315cb6140b"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables, UnboxedTuples #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, b, c) <- liftM3 (,,) get get get\n let (n, x, y, z) = f2 a b c in\n do\n putln n\n putln [x, y, z]\n \nf2 :: Int -> Int -> Int -> (Int, Int, Int, Int)\nf2 a b c = foldl (\\(n, x, y, z) i ->\n foldl (\\(n, x, y, z) j ->\n foldl (\\(n, x, y, z) k ->\n let s = (abs (i - a)) + (abs (j - b)) + (abs (k - c)) in\n if s < n then (s, i, j, k) else (n, x, y, z)\n ) (n, x, y, z) [j,2*j..11000]\n ) (n, x, y, z) [i,2*i..11000]\n ) (1000000, 0, 0, 0) [1..10000]", "positive_code": [{"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables, UnboxedTuples #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, b, c) <- liftM3 (,,) get get get\n let (n, x, y, z) = f2 a b c in\n do\n putln n\n putln [x, y, z]\n \nf2 :: Int -> Int -> Int -> (Int, Int, Int, Int)\nf2 a b c = f3 a b c 0 1000000 0 0 0\n\nf3 a b c i n x y z = if i >= a || i >= n\n then (n, x, y, z)\n else\n let (n1, x1, y1, z1) = f4 a b c (a + i) 0 n x y z in\n let (n2, x2, y2, z2) = f4 a b c (a - i) 0 n1 x1 y1 z1 in\n f3 a b c (i + 1) n2 x2 y2 z2\n\nf4 a b c ai j n x y z = foldl (\\(n, x, y, z) j ->\n let c1 = (div c j) * j in\n let c2 = (div c j) * j + j in\n let s1 = (abs (ai - a) + abs (j - b) + abs (c1 - c)) in\n let (n1, x1, y1, z1) = if s1 < n then (s1, ai, j, c1) else (n, x, y, z) in\n let s2 = (abs (ai - a) + abs (j - b) + abs (c2 - c)) in\n if s2 < n1 then (s2, ai, j, c2) else (n1, x1, y1, z1)\n ) (n, x, y, z) [ai,2*ai..2*b]"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables, UnboxedTuples #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, b, c) <- liftM3 (,,) get get get\n let (n, x, y, z) = f2 a b c in\n do\n putln n\n putln [x, y, z]\n \nf2 :: Int -> Int -> Int -> (Int, Int, Int, Int)\nf2 a b c = foldl (\\(n, x, y, z) i ->\n foldl (\\(n, x, y, z) j ->\n let c1 = (div c j) * j in\n let c2 = (div c j) * j + j in\n let s1 = (abs (i - a) + abs (j - b) + abs (c1 - c)) in\n let (n1, x1, y1, z1) = if s1 < n then (s1, i, j, c1) else (n, x, y, z) in\n let s2 = (abs (i - a) + abs (j - b) + abs (c2 - c)) in\n if s2 < n1 then (s2, i, j, c2) else (n1, x1, y1, z1)\n ) (n, x, y, z) [i,2*i..2*b]\n ) (1000000, 0, 0, 0) [1..2*a]"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables, UnboxedTuples #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (a, b, c) <- liftM3 (,,) get get get\n let (n, x, y, z) = f2 a b c in\n do\n putln n\n putln [x, y, z]\n \nf2 :: Int -> Int -> Int -> (Int, Int, Int, Int)\nf2 a b c = f3 a b c 0 1000000 0 0 0\n\nf3 a b c i n x y z = if i >= a || i >= n\n then (n, x, y, z)\n else\n let (n1, x1, y1, z1) = f4 a b c (a + i) 0 n x y z in\n let (n2, x2, y2, z2) = f4 a b c (a - i) 0 n1 x1 y1 z1 in\n f3 a b c (i + 1) n2 x2 y2 z2\n\nf4 a b c ai j n x y z = let bk = (div b ai) in\n if ((bk + j) * ai >= 2 * b && bk <= j) || (\n (abs (ai - a) + abs ((bk + j) * ai - b)) > n &&\n (abs (ai - a) + abs ((bk - j) * ai - b)) > n &&\n (abs (ai - a) + abs ((bk + j + 1) * ai - b)) > n &&\n (abs (ai - a) + abs ((bk - j - 1) * ai - b)) > n) then (n, x, y, z)\n else\n let (n1, x1, y1, z1) = f5 a b c ai (max ((bk + j) * ai) 1) n x y z in\n let (n2, x2, y2, z2) = f5 a b c ai (max ((bk - j) * ai) 1) n1 x1 y1 z1 in\n f4 a b c ai (j + 1) n2 x2 y2 z2\n\n\nf5 a b c ai bi n x y z =\n let c1 = (div c bi) * bi in\n let c2 = (div c bi) * bi + bi in\n let s1 = (abs (ai - a) + abs (bi - b) + abs (c1 - c)) in\n let (n1, x1, y1, z1) = if s1 < n then (s1, ai, bi, c1) else (n, x, y, z) in\n let s2 = (abs (ai - a) + abs (bi - b) + abs (c2 - c)) in\n if s2 < n1 then (s2, ai, bi, c2) else (n1, x1, y1, z1)"}], "negative_code": [], "src_uid": "140737ecea3ff1c71cdd5e51e6abf297"} {"source_code": "import qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n a <- C.getLine\n b <- C.getLine\n if C.length a == C.length b && C.elem '1' a == C.elem '1' b\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = putStrLn . solve . B.lines =<< B.getContents\n\nsolve :: [B.ByteString] -> String\nsolve (a : b : _)\n | B.length a == B.length b && B.elem '1' a == B.elem '1' b = \"YES\"\n | otherwise = \"NO\"\n"}, {"source_code": "\nsolve :: String -> String -> Bool\nsolve a b\n | length a /= length b = False\n | elem '1' a && elem '1' b = True\n | elem '1' a || elem '1' b = False\n | otherwise = True \n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n if solve a b then\n putStrLn \"YES\"\n else\n putStrLn \"NO\""}, {"source_code": "import Data.List\n\nmain = do\n\tstart <- getLine\n\tend <- getLine\n\tputStrLn.format.not $ unconvertable start end\n\nunconvertable a b =\n\tlength a /= length b\n\t|| any (=='1') a && all (=='0') b\n\t|| (length a == 1 || all (=='0') a) && a /= b\n\nformat True = \"YES\"\nformat False = \"NO\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain=B.getContents>>=putStr.solve.B.words\n\nsolve[x,y]\n | B.length x == B.length y && B.elem '1' x == B.elem '1' y = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "import Data.Char\n\nmain = interact $ solve . lines\n where \n solve (a:b:[])\n | (length a == length b) && scons (convert a) (convert b) = \"YES\" \n | otherwise = \"NO\" \n convert = foldl max 0 . map digitToInt\n scons 0 0 = True\n scons 1 1 = True\n scons _ _ = False\n"}, {"source_code": "import Data.Char\n\nmain = interact $ solve . lines\n where \n solve (a:b:[])\n | (length a == length b) && (elem '1' a == elem '1' b) = \"YES\" \n | otherwise = \"NO\" \n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n\tstart <- getLine\n\tend <- getLine\n\tputStrLn.format.not $ unconvertable start end\n\nunconvertable a b =\n\tlength a /= length b\n\t|| (any (=='1') a && all (=='0') b)\n\t|| length a == 1\n\t|| (all (=='0') a && a /= b)\n\nformat True = \"YES\"\nformat False = \"NO\"\n"}], "src_uid": "113ae625e67c8ea5ab07be44c3b58a8f"} {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Data.List (dropWhile, dropWhileEnd)\nimport Data.Char (isUpper, isLower)\n\nmain :: IO ()\nmain = do\n str <- dropWhileEnd isLower . dropWhile isUpper <$> getLine\n let uppers = length (filter isUpper str)\n print $ solve uppers uppers str\n\nsolve :: Int -> Int -> String -> Int\nsolve changes acc [] = minimum [acc, changes]\nsolve changes acc (x:xs) | isUpper x = solve (pred changes) (minimum [acc, pred changes]) xs\n | otherwise = solve (succ changes) acc xs\n", "positive_code": [{"source_code": "import Data.Char\n\nmain = do\n\ts <- getLine\n\n\tlet cs = scanl (+) 0 $ map ((\\b -> if b then 1 else 0) . isUpper) s\n\tprint $ minimum $ map (\\(c, i) -> (i-c) + ((last cs) - c)) $ zip cs [0..length s]\n\t\n"}, {"source_code": "import Data.Char\n\nmain = do\n\ts <- getLine\n\tlet cs = scanl (+) 0 $ map (fromEnum . isAsciiUpper) s\n\tprint $ minimum $ map (\\(i, c) -> (i-c) + ((last cs) - c)) $ zip [0..length s] cs\n\t\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Data.List (dropWhile, dropWhileEnd)\nimport Data.Char (isUpper, isLower)\n\nmain :: IO ()\nmain = do\n str <- dropWhileEnd isLower . dropWhile isUpper <$> getLine\n let\n lowers = length (filter isLower str)\n uppers = length (filter isUpper str)\n print $ minimum [lowers, uppers]\n"}], "src_uid": "92996552cc26a05258f2f2a1eb5f8a8f"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n \nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.Bifunctor (second)\nimport Data.List (sort)\n \nmain :: IO ()\nmain = C.interact $ runScanner (numberOf testCase) >>> map (solve >>> showB) >>> C.unlines\n \ntype Level = [Int]\n \ntestCase :: Scanner [Level]\ntestCase = numberOf (numberOf int)\n \nsolve :: [Level] -> Int\nsolve = (1 +) . maximum . uncurry (zipWith (-)) . second (scanl (+) 0) . unzip . sort . map info\n where\n info as = (maximum $ zipWith (-) as [0..], length as)\n \n \n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n \nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n \nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n \npeek :: Scanner C.ByteString\npeek = gets head\n \nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n \nstr :: Scanner String\nstr = C.unpack <$> bstr\n \nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n \ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n \ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n \ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n \nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n \nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n \ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n \ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n \n(><) = times\n \ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n \npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n \nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n\n\t \t\t \t\t \t\t \t\t \t \t\t\t\t\t", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.Bifunctor (second)\nimport Data.List (sort)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf testCase) >>> map (solve >>> showB) >>> C.unlines\n\ntype Level = [Int]\n\ntestCase :: Scanner [Level]\ntestCase = numberOf (numberOf int)\n\nsolve :: [Level] -> Int\nsolve = (1 +) . maximum . uncurry (zipWith (-)) . second (scanl (+) 0) . unzip . sort . map info\n where\n info as = (maximum $ zipWith (-) as [0..], length as)\n\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "88488ff074bc25a6cf925c8a07a1d8c6"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\n\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n{-\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n as <- unfoldr (BS.readInt . BS.dropWhile (==' ')) <$> BS.getLine :: IO [Int]\n let as' = sort as\n subs = dropWhile (== 0) $ zipWith (-) as' (0:as')\n rep = map head' $ iterate (\\xs -> remv xs (head' xs)) subs\n mapM_ print $ take k rep\n\n \nremv :: [Int] -> Int -> [Int]\nremv [] !y = []\nremv xs'@(!x:xs) !y\n | x > y = (x-y):xs\n | otherwise = remv xs (y-x)\n\nhead' :: [Int] -> Int\nhead' [] = 0\nhead' (x:_) = x", "positive_code": [{"source_code": "import Control.Monad \nimport qualified Data.Set as S\nmain = do\n [n,k] <- getLine >>= return . map (read :: String -> Int) . words\n as' <- getLine >>= return . S.fromList . map (read :: String -> Int) . words\n let as = S.toList as'\n print $ head as\n mapM_ print $ take (pred k) $ (zipWith (-) (tail as) as) \n mapM_ print $ take (k-length as) $ cycle [0]\n\n"}, {"source_code": "import Data.List\n\nmain = do\n string <- getContents\n let answers = solve string\n sequence (map (putStrLn.show) answers)\n\nsolve string = let n = read sn :: Int; k = read sk :: Int in computeAnswer k [read s :: Int | s <- rest]\n\t where (sn:sk:rest) = words string\n\ncomputeAnswer k a = let b = sort a in getK k$head b:zipWith (-) (tail b) b\ngetK 0 _ = []\ngetK k [] = replicate k 0\ngetK k (x:xs) | x == 0 = getK k xs\n\t | otherwise = x : getK (k - 1) xs\n\n"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as Map\n\ntoint s = (read s) :: Int\n\ndoit 0 a s = \"\"\ndoit k a [] = \"0\\n\" ++ doit (k-1) a []\ndoit k a (x:xs) = \n if x > a then \n show(x-a)++\"\\n\"++(doit (k-1) x xs)\n else\n doit k a xs\n\nsolve::String -> String\nsolve ss =\n let n:k:sss = map toint $ words ss in\n let s = sort $ take n sss in\n doit k 0 s\n\nmain = do\n interact $ solve"}], "negative_code": [], "src_uid": "0f100199a720b0fdead5f03e1882f2f3"} {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\nimport Data.Char (isDigit)\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: Num a => L.ByteString -> a\nreadInteger x =\n case L.readInteger x of Just (i,_) -> fromIntegral i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n i = if L.null integer then 0 else readInteger integer\n f = if L.null fractional then 0 else readInteger fractional\n in if not (L.elem '.' s)\n then readInteger s\n else i + 0.1 ^ L.length (L.takeWhile isDigit fractional) * f\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n m = readInt . head . drop (n+1) $ l\n walls = [(x,y) | s <- take m (drop (n+2) l), let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStrLn (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10 ^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map (dshow 6))\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n", "positive_code": [{"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\n\nimport GHC.Exts\nimport Data.Maybe (fromJust)\nimport GHC.Float (int2Double)\nimport Data.List (sort)\nimport Text.Printf (printf)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\nmain = do str <- LB.getContents\n let l = LB.lines str\n [n,v] = map readInt . LB.words . head $ l\n angles = map readDouble . take n . tail $ l\n m = readInt $ l !! (n+1)\n walls = [(x,y) | s <- take m (drop (n+2) l), let w = LB.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n mapM_ (uncurry (printf \"%.6f %.6f\\n\") ) sol\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map snd res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport Text.Printf\nimport GHC.Exts\nimport GHC.Float\nimport Data.Char\nimport Data.Maybe\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n m = readInt $ l !! (n+1)\n walls = [(x,y) | s <- take m (drop (n+2) l), let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n mapM_ (uncurry (printf \"%.6f %.6f\\n\") ) sol\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map snd res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n\nreadInt = fst . fromJust . L.readInt\nreadInteger = fromIntegral . fst . fromJust . L.readInteger\nreadDouble s =\n let [si, sf] = L.split '.' s\n i = if L.null si then 0 else readInteger si\n f = if L.null sf then 0 else readInteger sf\n in if not (L.elem '.' s)\n then readInteger s\n else i + 0.1 ^ L.length (L.takeWhile isDigit sf) * f\n"}, {"source_code": "import Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\nreadInt = fst . fromJust . C.readInt\n\nreadDouble bs =\n if C.null bs'\n then fromIntegral a\n else fromIntegral (a * c + b) / fromIntegral c\n where\n Just (a, bs') = C.readInt bs\n t = C.tail bs'\n b = readInt t\n c = 10 ^ C.length t\n\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain = do\n (n':v':input) <- fmap C.words C.getContents\n let n = readInt n'\n v = readInt v'\n (a',(m':z')) = splitAt n input\n let a = map readDouble a'\n m = readInt m'\n z = map readDouble z'\n putStrLn $ unwords $ map show $ concatMap snd $ sort $\n gao n (fromIntegral v) (zip a [0 ..]) $ pairs z\n\ngao :: Int -> Double -> [(Double, Int)] -> [(Double, Double)] -> [(Int, [Double])]\ngao n v as zs = gao' (sort as) (sort zs) where\n eps = 1e-8\n g = 9.8\n gao' [] _ = []\n gao' ((a,i):a') z = (i, xy) : gao' a' z' where\n vx = v * cos(a)\n vy = v * sin(a)\n yt x = let t = x / vx in vy * t - g * t * t / 2\n z' = dropWhile (\\(x, y) -> y < yt x + eps) z\n xy =\n if null z' || y < -eps\n then [v * v * sin(2 * a) / g, 0]\n else let x = fst $ head z' in [x, y]\n where\n x = fst $ head z'\n y = yt x\n\n{- Time limit exceeded on test 7 -}\n{- PS: if yt x < 0 .... WA -}\n"}], "negative_code": [{"source_code": "import Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\nreadInt = fst . fromJust . C.readInt\n\nreadDouble bs =\n if C.null bs'\n then fromIntegral a\n else fromIntegral a + fromIntegral b / fromIntegral c\n where\n Just (a, bs') = C.readInt bs\n t = C.tail bs'\n b = readInt t\n c = 10 ^ C.length t\n\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain = do\n (n':v':input) <- fmap C.words C.getContents\n let n = readInt n'\n v = readInt v'\n (a',(m':z')) = splitAt n input\n let a = map readDouble a'\n m = readInt m'\n z = map readDouble z'\n putStrLn $ unwords $ map show $ concatMap snd $ sort $\n gao n (fromIntegral v) (zip a [0 ..]) $ pairs z\n\ngao :: Int -> Double -> [(Double, Int)] -> [(Double, Double)] -> [(Int, [Double])]\ngao n v as zs = gao' (sort as) (sort zs) where\n eps = 1e-6\n g = 9.8\n gao' [] _ = []\n gao' ((a,i):a') z = (i, xy) : gao' a' z' where\n vx = v * cos(a)\n vy = v * sin(a)\n yt x = let t = x / vx in vy * t - g * t * t / 2\n z' = dropWhile (\\(x, y) -> y < yt x + eps) z --WA\n xy = if null z' then [v * v * sin(2 * a) / g, 0] else let x = fst $ head z' in [x, yt x] --WA\n\n{- Time limit exceeded on test 7 -}\n{- PS: if yt x < 0 .... WA -}\n"}, {"source_code": "import Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\nreadInt = fst . fromJust . C.readInt\n\nreadDouble bs =\n if C.null bs'\n then fromIntegral a\n else fromIntegral (a * c + b) / fromIntegral c\n where\n Just (a, bs') = C.readInt bs\n t = C.tail bs'\n b = readInt t\n c = 10 ^ C.length t\n\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain = do\n (n':v':input) <- fmap C.words C.getContents\n let n = readInt n'\n v = readInt v'\n (a',(m':z')) = splitAt n input\n let a = map readDouble a'\n m = readInt m'\n z = map readDouble z'\n putStrLn $ unwords $ map show $ concatMap snd $ sort $\n gao n (fromIntegral v) (zip a [0 ..]) $ pairs z\n\ngao :: Int -> Double -> [(Double, Int)] -> [(Double, Double)] -> [(Int, [Double])]\ngao n v as zs = gao' (sort as) (sort zs) where\n eps = 1e-6\n g = 9.8\n gao' [] _ = []\n gao' ((a,i):a') z = (i, xy) : gao' a' z' where\n vx = v * cos(a)\n vy = v * sin(a)\n yt x = let t = x / vx in vy * t - g * t * t / 2\n z' = dropWhile (\\(x, y) -> y < yt x + eps) z --WA\n xy =\n if null z' || y < -eps\n then [v * v * sin(2 * a) / g, 0]\n else let x = fst $ head z' in [x, y] --WA\n where\n x = fst $ head z'\n y = yt x\n\n{- Time limit exceeded on test 7 -}\n{- PS: if yt x < 0 .... WA -}\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport Data.List\nimport Data.Maybe (catMaybes, mapMaybe)\nimport System.Random\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport qualified Data.ByteString.Char8 as B\nimport Foreign.C.Types\nimport Foreign.C.String\nimport System.IO.Unsafe\nimport Text.Printf\nimport GHC.Show (intToDigit)\n--import Data.ByteString.Lex.Lazy.Double (readDouble)\n\n--import qualified Data.Text.Read as T\nimport GHC.Exts\nimport GHC.Float\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO CDouble\nreadDouble :: B.ByteString -> Double\nreadDouble = realToFrac . unsafePerformIO . flip B.useAsCString c_atof\n\nmain = interact $ output . solve . parse . lines\n\n--main = do let r = mkStdGen 146\n-- lst = iterate (\\(x,r) -> random r) (int2Double 1, r)\n-- putStrLn . unlines . map(show . fst) $ take 200000 lst\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x | x < 0 = '-' : dshow prec (-x)\ndshow prec x = ishow first ++ ('.' : ishow second)\n where m = toInteger 10^ toInteger prec :: Integer\n n = round (x * fromIntegral m)\n (first, second) = divMod n m\n\n\n--main = interact $ output' . parse' . lines\n\n--parse' = map fst . mapMaybe ( L.readInt . L.pack )\nparse' = map (readDouble . B.pack)\n--output' = unlines . map (printf \"%.3f\")\noutput' = unlines . map (dshow 4)\n\nsolve' = takeWhile (/= 42)\n\noutput = unlines . map (unwords . map (dshow 9))\n\nparse (nv:rest) = let [n,v] = map read . words $ nv\n angles = map (readDouble . B.pack) (take n rest)\n walls = [(x,y) | s <- drop (n+1) rest, let w = words s,\n let x = read (head w), let y = read (last w)]\n in (int2Double v, angles, sort walls)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: Num a => L.ByteString -> a\nreadInteger x =\n case L.readInteger x of Just (i,_) -> fromIntegral i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n i = if L.null integer then 0 else readInteger integer\n f = if L.null fractional then 0 else readInteger fractional\n in if not (L.elem '.' s)\n then readInteger s\n else i + 0.1 ^ L.length fractional * f\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n m = readInt . head . drop (n+1) $ l\n walls = [(x,y) | s <- take m (drop (n+2) l), let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStrLn (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map (dshow 6))\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport Data.List\nimport Data.Maybe (catMaybes, mapMaybe)\nimport System.Random\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport qualified Data.ByteString.Char8 as B\nimport Foreign.C.Types\nimport Foreign.C.String\nimport System.IO.Unsafe\nimport Text.Printf\nimport GHC.Show (intToDigit)\n--import Data.ByteString.Lex.Lazy.Double (readDouble)\n\n--import qualified Data.Text.Read as T\nimport GHC.Exts\nimport GHC.Float\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO CDouble\nreadDouble :: B.ByteString -> Double\nreadDouble = realToFrac . unsafePerformIO . flip B.useAsCString c_atof\n\nmain = interact $ output . solve . parse . lines\n\n--main = do let r = mkStdGen 146\n-- lst = iterate (\\(x,r) -> random r) (int2Double 1, r)\n-- putStrLn . unlines . map(show . fst) $ take 200000 lst\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x | x < 0 = '-' : dshow prec (-x)\ndshow prec x = ishow first ++ ('.' : ishow second)\n where m = toInteger 10^ toInteger prec :: Integer\n n = round (x * fromIntegral m)\n (first, second) = divMod n m\n\n\n--main = interact $ output' . parse' . lines\n\n--parse' = map fst . mapMaybe ( L.readInt . L.pack )\nparse' = map (readDouble . B.pack)\n--output' = unlines . map (printf \"%.3f\")\noutput' = unlines . map (dshow 4)\n\nsolve' = takeWhile (/= 42)\n\noutput = unlines . map (unwords . map (dshow 6))\n\nparse (nv:rest) = let [n,v] = map read . words $ nv\n angles = map (readDouble . B.pack) (take n rest)\n walls = [(x,y) | s <- drop (n+1) rest, let w = words s,\n let x = read (head w), let y = read (last w)]\n in (int2Double v, angles, sort walls)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe (fromJust)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\nmain = LB.getContents >>= (print . sum . map readDouble . LB.lines)\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: L.ByteString -> Integer\nreadInteger x =\n case L.readInteger x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n in fromIntegral (readInteger integer) +\n 0.1 ^ L.length fractional * fromIntegral (readInteger fractional)\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble (take n (tail l))\n walls = [(x,y) | s <- drop (n+2) l, let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStr (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map (dshow 6))\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: L.ByteString -> Integer\nreadInteger x =\n case L.readInteger x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n in fromIntegral (readInteger integer) +\n 0.1 ^ L.length fractional * fromIntegral (readInteger fractional)\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n walls = [(x,y) | s <- drop (n+2) l, let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStr (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map show)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: L.ByteString -> Integer\nreadInteger x =\n case L.readInteger x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n in fromIntegral (readInteger integer) +\n 0.1 ^ L.length fractional * fromIntegral (readInteger fractional)\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n walls = [(x,y) | s <- drop (n+2) l, let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStrLn (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map show)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: Num a => L.ByteString -> a\nreadInteger x =\n case L.readInteger x of Just (i,_) -> fromIntegral i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n i = if L.null integer then 0 else readInteger integer\n f = if L.null fractional then 0 else readInteger fractional\n in i + 0.1 ^ L.length fractional * f\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n m = readInt . head . drop (n+1) $ l\n walls = [(x,y) | s <- take m (drop (n+2) l), let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStrLn (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map (dshow 6))\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport GHC.Show (intToDigit)\nimport GHC.Exts\nimport GHC.Float\n\nreadInt :: L.ByteString -> Int\nreadInt x =\n case L.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadInteger :: L.ByteString -> Integer\nreadInteger x =\n case L.readInteger x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\n\nreadDouble :: L.ByteString -> Double\nreadDouble s = let [integer, fractional] = L.split '.' s\n in fromIntegral (readInteger integer) +\n 0.1 ^ L.length fractional * fromIntegral (readInteger fractional)\n\nmain = do str <- L.getContents\n let l = L.lines str\n [n,v] = map readInt . L.words . head $ l\n angles = map readDouble . take n . tail $ l\n m = readInt . head . drop (n+1) $ l\n walls = [(x,y) | s <- take m (drop (n+2) l), let w = L.words s,\n let x = readDouble (head w), let y = readDouble (last w)]\n sol = solve (int2Double v, angles, sort walls)\n putStrLn (output sol)\n\nishow :: Integral a => a -> String\nishow n | n < 0 = '-':ishow (-n)\n | otherwise = reverse (f n)\n where\n f n | n < 10 = [intToDigit (fromIntegral n)]\n | otherwise = intToDigit (fromIntegral (mod n 10)) : f (div n 10)\n\ndshow :: Int -> Double -> String\ndshow prec x = f (round (x * fromIntegral m)) m\n where m = toInteger 10^ toInteger prec :: Integer\n f n m | n < 0 = '-' : f (-n) m\n | otherwise = ishow first ++ ('.' : replicate leadingZeroes '0') ++ secondStr\n where (first, second) = divMod n m\n secondStr = ishow second\n leadingZeroes = prec - length secondStr\n\noutput = unlines . map (unwords . map show)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as walls\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n\n"}, {"source_code": "import Data.List\nimport GHC.Exts\nimport GHC.Float\n\nmain = interact $ output . solve . parse . lines\n\noutput = unlines . map (unwords . map show)\n\nparse (nv:rest) = let [n,v] = map read . words $ nv\n angles = map read (take n rest)\n walls = [(x,y) | s <- drop (n+1) rest, let w = words s,\n let x = read (head w), let y = read (last w)]\n in (int2Double v, angles, sortWith fst walls)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as ws\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n"}, {"source_code": "import Data.List\nimport GHC.Exts\nimport GHC.Float\n\nmain = interact $ output . solve . parse . lines\n\noutput = unlines . map (unwords . map show)\n\nparse (nv:rest) = let [n,v] = map read . words $ nv\n angles = map read (take n rest)\n walls = [(x,y) | s <- drop (n+1) rest, let w = words s,\n let x = read (head w), let y = read (last w)]\n in (int2Double v, angles, sort walls)\n\nsolve (v,angles,walls) = let angles' = sortWith snd $ zip [1..] angles\n res = sortWith fst $ doSolve v angles' walls\n in map (\\(_, (x,y)) -> [x,y]) res\n\ng = 9.8\n\ndoSolve _ [] _ = []\ndoSolve v angles [] = map (freeFall v) angles\ndoSolve v angles@((n,a):as) walls@((x,y):ws)\n | y1 < 0 = freeFall v (n, a) : doSolve v as walls\n | y1 > y = doSolve v angles ws\n | otherwise = (n, (x, y1)) : doSolve v as ws\n where y1 = v * t * sin a - g * t * t / 2.0\n t = x / cos a / v\n\nfreeFall v (n, a) = (n, (v * t * cos a, 0.0))\n where t = 2*v*sin a / g\n"}], "src_uid": "d51aa18439e7afffa11ad181064c0450"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Set (fromList, difference, size)\n\nreadint = fst. fromJust . C.readInteger\n\nrun :: Integer -> Integer -> Integer -> [Integer] -> Maybe Int\nrun 0 q l as | 0 `elem` as = Just 0\n | otherwise = Nothing\nrun b 0 l as | 0 `elem` as && b `elem` as = Just 0\n | 0 `elem` as && not (b `elem` as) = if abs b <= l then Just 1 else Just 0\n | not (0 `elem` as) && abs b > l = Just 0\n | otherwise = Nothing\nrun b 1 l as | b `elem` as || abs b > l = Just 0\n | otherwise = Nothing\nrun b (-1) l as | not (b `elem` as) && abs b <= l = Nothing\n | not ((-b) `elem` as) && abs b <= l = Nothing\n | otherwise = Just 0\nrun b q l as = Just $ size $ difference (fromList lb) (fromList as) where\n lb = filter ((<= l) . abs) (until ((> l) . abs . last) (\\x -> x ++ [last x * q]) [b])\n\nmain = do\n (map readint . C.words -> [b, q, l, m]) <- B.getLine\n (take (fromIntegral m) . map readint . C.words -> as) <- B.getLine\n let rbq = run b q l as\n putStrLn $ if isNothing rbq then \"inf\" else show (fromJust rbq)\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\n\nmain = do\n [b,q,l,_m] <- getInts\n allow <-fmap ((not.) .flip elem) getInts\n let good num = abs num <= l && allow num\n inf num | good num = \"inf\"\n | otherwise = \"0\"\n result | abs b > l = \"0\"\n | q == 0 && good 0 = \"inf\"\n | q == 0 && good b = \"1\"\n | q == 0 = \"0\"\n | q == 1 = inf b\n | q == -1 = inf b `max` inf (-b)\n | b == 0 = inf 0\n | otherwise = show $ length $ filter allow $ takeWhile ((<= l).abs) $ iterate (* q) b\n putStrLn result\n where\n getInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInteger s\n return (x, BS.drop 1 s')\n"}, {"source_code": "import Control.Applicative \nimport Data.List\nimport Data.Int\n\nmain :: IO()\nmain = putStrLn. toString . solve' . map read.words =<< getContents\n\nsolve' :: [Int64] -> Int64\nsolve' (b:1:l:m:xs) = if (abs b>l) then 0 else if ((fst $ findPos b (sort xs))==0) then 0 else 2000000000\nsolve' (0:_:l:m:xs) = if ((fst $ findPos 0 (sort xs))==0) then 0 else 2000000000\nsolve' (b:(-1):l:m:xs) = if (abs b >l) then 0 else if (((fst $ findPos b (sort xs))==0) && ((fst $ findPos (-b) (sort xs))==0)) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (abs b>l) then 0 else let xs'= sort xs\n (c1,_) = findPos b xs'\n (c2,_) = findPos 0 xs'\n in case (c1,c2) of\n (_,1) -> 2000000000\n (1,0) -> 1\n (0,0) -> 0\n\nsolve' (b:q:l:m:xs) = let (xsPos,xsNeg) = separe xs\n in solve b q l 0 (sort xsPos) (reverse $ sort xsNeg)\n\nsolve b q l c xs xs' = if (b>l || (-1)*b>l) then c else if b>=0 then do let (cm,nl) = findPos b xs\n solve (b*q) q l (c+cm) nl xs'\n else do let (cm2,nls) = findNeg b xs'\n solve (b*q) q l (c+cm2) xs nls\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nsepare = foldl (\\(p,n) e-> if(e<0) then (p,e:n) else (e:p,n)) ([],[]) \n\nfindPos _ [] = (1,[])\nfindPos e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else findPos e xs\n\nfindNeg _ [] = (1,[])\nfindNeg e (x:xs) = if (x==e) then (0,xs) else if(x= l = \"0\"\n | q == 0 && good 0 = \"inf\"\n | q == 0 && good b = \"1\"\n | q == 0 = \"0\"\n | q == 1 = inf b\n | q == -1 = inf b `max` inf (-b)\n | b == 0 = inf 0\n | otherwise = show $ length $ filter allow $ takeWhile ((<= l).abs) $ iterate (* q) b\n putStrLn result\n where\n getInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\n\nmain = do\n [b,q,l,_m] <- getInts\n allow <-fmap ((not.) .flip elem) getInts\n let good num = abs num <= l && allow num\n inf num | good num = \"inf\"\n | otherwise = \"0\"\n result | abs b > l = \"0\"\n | q == 0 && good 0 = \"inf\"\n | q == 0 && good b = \"1\"\n | q == 0 = \"0\"\n | q == 1 = inf b\n | q == -1 = inf b `max` inf (-b)\n | b == 0 = inf 0\n | otherwise = show $ length $ filter allow $ takeWhile ((<= l).abs) $ iterate (* q) b\n putStrLn result\n where\n getInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\n\nmain = do\n [b,q,l,_m] <- getInts\n allow <-fmap ((not.) .flip elem) getInts\n let good num = abs num < l && allow num\n inf num | good num = \"inf\"\n | otherwise = \"0\"\n result | abs b >= l = \"0\"\n | q == 0 && good 0 = \"inf\"\n | q == 0 && good b = \"1\"\n | q == 0 = \"0\"\n | q == 1 = inf b\n | q == -1 = inf b `max` inf (-b)\n | b == 0 = inf 0\n | otherwise = show $ length $ filter allow $ takeWhile ((< l).abs) $ iterate (* q) b\n putStrLn result\n where\n getInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List (unfoldr)\n\nmain = do\n [b,q,l,_m] <- getInts\n allow <-fmap ((not.) .flip elem) getInts\n let good num = abs num < l && allow num\n inf num | good num = \"inf\"\n | otherwise = \"0\"\n result | q == 0 && good 0 = \"inf\"\n | q == 0 && good b = \"1\"\n | q == 0 = \"0\"\n | q == 1 = inf b\n | q == -1 = inf b `max` inf (-b)\n | b == 0 = inf 0\n | otherwise = show $ length $ filter allow $ takeWhile ((< l).abs) $ iterate (* q) b\n putStrLn result\n where\n getInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Set (fromList, difference, size)\n\nreadint = fromIntegral . fst. fromJust . C.readInt\n\nrun :: Integer -> Integer -> Integer -> [Integer] -> Maybe Int\nrun 0 q l as | 0 `elem` as = Just 0\n | otherwise = Nothing\nrun b 0 l as | 0 `elem` as && b `elem` as = Just 0\n | 0 `elem` as && not (b `elem` as) = if b <= l then Just 1 else Just 0\n | not (0 `elem` as) = Nothing\nrun b 1 l as | b `elem` as || b > l = Just 0\n | otherwise = Nothing\nrun b (-1) l as | not (b `elem` as) && b <= l = Nothing\n | not ((-b) `elem` as) && (-b) <= l = Nothing\n | otherwise = Just 0\nrun b q l as | b < 0 || q < 0 = Nothing\nrun b q l as = Just $ size $ difference (fromList lb) (fromList as) where\n lb = until ((> l) . last) (\\x -> x ++ [last x * q]) [b]\n\nmain = do\n (map readint . C.words -> [b, q, l, m]) <- B.getLine\n (map readint . C.words -> as) <- B.getLine\n let rbq = run b q l as\n putStrLn $ if isNothing rbq then \"inf\" else show (fromJust rbq)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Set (fromList, difference, size)\n\nreadint = fst. fromJust . C.readInteger\n\nrun :: Integer -> Integer -> Integer -> [Integer] -> Maybe Int\nrun 0 q l as | 0 `elem` as = Just 0\n | otherwise = Nothing\nrun b 0 l as | 0 `elem` as && b `elem` as = Just 0\n | 0 `elem` as && not (b `elem` as) = if abs b <= l then Just 1 else Just 0\n | not (0 `elem` as) && b > l = Just 0\n | otherwise = Nothing\nrun b 1 l as | b `elem` as || abs b > l = Just 0\n | otherwise = Nothing\nrun b (-1) l as | not (b `elem` as) && abs b <= l = Nothing\n | not ((-b) `elem` as) && abs b <= l = Nothing\n | otherwise = Just 0\nrun b q l as = Just $ size $ difference (fromList lb) (fromList as) where\n lb = filter ((<= l) . abs) (until ((> l) . abs . last) (\\x -> x ++ [last x * q]) [b])\n\nmain = do\n (map readint . C.words -> [b, q, l, m]) <- B.getLine\n (take (fromIntegral m) . map readint . C.words -> as) <- B.getLine\n let rbq = run b q l as\n putStrLn $ if isNothing rbq then \"inf\" else show (fromJust rbq)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Set (fromList, difference, size)\n\nreadint = fromIntegral . fst. fromJust . C.readInt\n\nrun :: Integer -> Integer -> Integer -> [Integer] -> Maybe Int\nrun 0 q l as | 0 `elem` as = Just 0\n | otherwise = Nothing\nrun b 0 l as | 0 `elem` as && b `elem` as = Just 0\n | 0 `elem` as && not (b `elem` as) = if abs b <= l then Just 1 else Just 0\n | not (0 `elem` as) = Nothing\nrun b 1 l as | b `elem` as || abs b > l = Just 0\n | otherwise = Nothing\nrun b (-1) l as | not (b `elem` as) && abs b <= l = Nothing\n | not ((-b) `elem` as) && abs b <= l = Nothing\n | otherwise = Just 0\nrun b q l as = Just $ size $ difference (fromList lb) (fromList as) where\n lb = until ((> l) . abs . last) (\\x -> x ++ [last x * q]) [b]\n\nmain = do\n (map readint . C.words -> [b, q, l, m]) <- B.getLine\n (map readint . C.words -> as) <- B.getLine\n let rbq = run b q l as\n putStrLn $ if isNothing rbq then \"inf\" else show (fromJust rbq)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Set (fromList, difference, size)\n\nreadint = fromIntegral . fst. fromJust . C.readInt\n\nrun :: Integer -> Integer -> Integer -> [Integer] -> Maybe Int\nrun 0 q l as | 0 `elem` as = Just 0\n | otherwise = Nothing\nrun b 0 l as | 0 `elem` as && b `elem` as = Just 0\n | 0 `elem` as && not (b `elem` as) = if abs b <= l then Just 1 else Just 0\n | not (0 `elem` as) = Nothing\nrun b 1 l as | b `elem` as || abs b > l = Just 0\n | otherwise = Nothing\nrun b (-1) l as | not (b `elem` as) && abs b <= l = Nothing\n | not ((-b) `elem` as) && abs b <= l = Nothing\n | otherwise = Just 0\nrun b q l as = Just $ size $ difference (fromList lb) (fromList as) where\n lb = filter ((<= l) . abs) (until ((> l) . abs . last) (\\x -> x ++ [last x * q]) [b])\n\nmain = do\n (map readint . C.words -> [b, q, l, m]) <- B.getLine\n (map readint . C.words -> as) <- B.getLine\n let rbq = run b q l as\n putStrLn $ if isNothing rbq then \"inf\" else show (fromJust rbq)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (sort)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust, isNothing)\nimport Data.Set (fromList, difference, size)\n\nreadint = fst. fromJust . C.readInteger\n\nrun :: Integer -> Integer -> Integer -> [Integer] -> Maybe Int\nrun 0 q l as | 0 `elem` as = Just 0\n | otherwise = Nothing\nrun b 0 l as | 0 `elem` as && b `elem` as = Just 0\n | 0 `elem` as && not (b `elem` as) = if abs b <= l then Just 1 else Just 0\n | not (0 `elem` as) = Nothing\nrun b 1 l as | b `elem` as || abs b > l = Just 0\n | otherwise = Nothing\nrun b (-1) l as | not (b `elem` as) && abs b <= l = Nothing\n | not ((-b) `elem` as) && abs b <= l = Nothing\n | otherwise = Just 0\nrun b q l as = Just $ size $ difference (fromList lb) (fromList as) where\n lb = filter ((<= l) . abs) (until ((> l) . abs . last) (\\x -> x ++ [last x * q]) [b])\n\nmain = do\n (map readint . C.words -> [b, q, l, m]) <- B.getLine\n (take (fromIntegral m) . map readint . C.words -> as) <- B.getLine\n let rbq = run b q l as\n putStrLn $ if isNothing rbq then \"inf\" else show (fromJust rbq)\n"}, {"source_code": "import Control.Applicative \nimport Data.List\n\nmain :: IO()\nmain = putStrLn. toString . solve' . map read.words =<< getContents\n\nsolve' :: [Int] -> Int\nsolve' (b:1:l:m:xs) = if (abs b>l) then 0 else if ((fst $ find' b (sort xs))==0) then 0 else 2000000000\nsolve' (b:(-1):l:m:xs) = if (abs b >l) then 0 else if (((fst $ find' b (sort xs))==0) && ((fst $ find' (-b) (sort xs))==0)) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (abs b>l) then 0 else let xs'= sort xs\n (c1,_) = find' b xs'\n (c2,_) = find' 0 xs'\n in case (c1,c2) of\n (_,1) -> 2000000000\n (1,0) -> 1\n (0,0) -> 0\nsolve' (b:q:l:m:xs) = solve b q l 0 (sort xs)\n\nsolve b q l c xs = if (abs b>l) then c else let (cm,nl) = find' b xs\n in solve (b*q) q l (c+cm) nl\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nfind' _ [] = (1,[])\nfind' e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else find' e xs"}, {"source_code": "import Control.Applicative \nimport Data.List\n\nmain :: IO()\nmain = putStrLn. toString . solve' . map read.words =<< getContents\n\nsolve' :: [Int] -> Int\nsolve' (b:1:l:m:xs) = if (abs b>l) then 0 else if ((fst $ find' b (sort xs))==0) then 0 else 2000000000\nsolve' (b:(-1):l:m:xs) = if (abs b >l) then 0 else if (((fst $ find' b (sort xs))==0) && ((fst $ find' (-b) (sort xs))==0)) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (abs b>l) then 0 else let xs'= sort xs\n (c1,_) = find' b xs'\n (c2,_) = find' 0 xs'\n in case (c1,c2) of\n (_,1) -> 2000000000\n (1,0) -> 1\n (0,0) -> 0\nsolve' (b:q:l:m:xs) = solve b q l 0 xs\n\nsolve b q l c xs = if (abs b>l) then c else let (cm,nl) = find' b xs\n in solve (b*q) q l (c+cm) nl\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nfind' _ [] = (1,[])\nfind' e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else find' e xs"}, {"source_code": "import Control.Applicative \nimport Data.List\n\nmain :: IO()\nmain = putStrLn. toString . solve' . map read.words =<< getContents\n\nsolve' :: [Int] -> Int\nsolve' (b:1:l:m:xs) = if (b>l) then 0 else if ((fst $ find' b xs)==0) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (b>l) then 0 else let (c1,_) = find' b xs\n (c2,_) = find' 0 xs\n in case (c1,c2) of\n (_,1) -> 2000000000\n (1,0) -> 1\n (0,0) -> 0\nsolve' (b:q:l:m:xs) = solve b q l 0 xs\n\nsolve b q l c xs = if (abs b>l) then c else let (cm,nl) = find' b xs\n in solve (b*q) q l (c+cm) nl\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nfind' _ [] = (1,[])\nfind' e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else find' e xs"}, {"source_code": "import Control.Applicative \nimport Data.List\n\nmain :: IO()\nmain = putStrLn. toString . solve' . map read.words =<< getContents\n\nsolve' :: [Int] -> Int\nsolve' (b:1:l:m:xs) = if (abs b>l) then 0 else if ((fst $ findPos b (sort xs))==0) then 0 else 2000000000\nsolve' (0:_:l:m:xs) = if ((fst $ findPos 0 (sort xs))==0) then 0 else 2000000000\nsolve' (b:(-1):l:m:xs) = if (abs b >l) then 0 else if (((fst $ findPos b (sort xs))==0) && ((fst $ findPos (-b) (sort xs))==0)) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (abs b>l) then 0 else let xs'= sort xs\n (c1,_) = findPos b xs'\n (c2,_) = findPos 0 xs'\n in case (c1,c2) of\n (_,1) -> 2000000000\n (1,0) -> 1\n (0,0) -> 0\n\nsolve' (b:q:l:m:xs) = let (xsPos,xsNeg) = separe xs\n in solve b q l 0 (sort xsPos) (reverse $ sort xsNeg)\n\nsolve b q l c xs xs' = if (b>l || (-1)*b>l) then c else if b>=0 then let (cm,nl) = findPos b xs\n in solve (b*q) q l (c+cm) nl xs'\n else let (cm,nl) = findNeg b xs'\n in solve (b*q) q l (c+cm) xs nl\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nsepare = foldl (\\(p,n) e-> if(e<0) then (p,e:n) else (e:p,n)) ([],[]) \n\nfindPos _ [] = (1,[])\nfindPos e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else findPos e xs\n\nfindNeg _ [] = (1,[])\nfindNeg e (x:xs) = if (x==e) then (0,xs) else if(x Int\nsolve' (b:1:l:m:xs) = if (abs b>l) then 0 else if ((fst $ findPos b (sort xs))==0) then 0 else 2000000000\nsolve' (0:_:l:m:xs) = if ((fst $ findPos 0 (sort xs))==0) then 0 else 2000000000\nsolve' (b:(-1):l:m:xs) = if (abs b >l) then 0 else if (((fst $ findPos b (sort xs))==0) && ((fst $ findPos (-b) (sort xs))==0)) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (abs b>l) then 0 else let xs'= sort xs\n (c1,_) = findPos b xs'\n (c2,_) = findPos 0 xs'\n in case (c1,c2) of\n (_,1) -> 2000000000\n (1,0) -> 1\n (0,0) -> 0\n\nsolve' (b:q:l:m:xs) = let (xsPos,xsNeg) = separe xs\n in solve b q l 0 (sort xsPos) (reverse $ sort xsNeg)\n\nsolve b q l c xs xs' = if (abs b>l) then c else if b>=0 then let (cm,nl) = findPos b xs\n in solve (b*q) q l (c+cm) nl xs'\n else let (cm,nl) = findNeg b xs'\n in solve (b*q) q l (c+cm) xs nl\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nsepare = foldl (\\(p,n) e-> if(e<0) then (p,e:n) else (e:p,n)) ([],[]) \n\nfindPos _ [] = (1,[])\nfindPos e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else findPos e xs\n\nfindNeg _ [] = (1,[])\nfindNeg e (x:xs) = if (x==e) then (0,xs) else if(x Int\nsolve' (b:1:l:m:xs) = if ((fst $ find' b xs)==0) then 0 else 2000000000\nsolve' (b:0:xs) = 2000000000\nsolve' (b:q:l:m:xs) = solve b q l 0 xs\n\nsolve b q l c xs = if (abs b>l) then c else let (cm,nl) = find' b xs\n in solve (b*q) q l (c+cm) nl\n\ntoString n = if(n==2000000000) then \"inf\" else show n\n\nfind' _ [] = (1,[])\nfind' e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else find' e xs"}, {"source_code": "import Control.Applicative \nimport Data.List\nimport Data.Int\n\nmain :: IO()\nmain = putStrLn. toString . solve' . map read.words =<< getContents\n\nsolve' :: [Int64] -> Int64\nsolve' (b:1:l:m:xs) = if (abs b>l) then 0 else if ((fst $ find' b (sort xs))==0) then 0 else (-1)\nsolve' (b:(-1):l:m:xs) = if (abs b >l) then 0 else if (((fst $ find' b (sort xs))==0) && ((fst $ find' (-b) (sort xs))==0)) then 0 else 2000000000\nsolve' (b:0:l:m:xs) = if (abs b>l) then 0 else let xs'= sort xs\n (c1,_) = find' b xs'\n (c2,_) = find' 0 xs'\n in case (c1,c2) of\n (_,1) -> (-1)\n (1,0) -> 1\n (0,0) -> 0\nsolve' (b:q:l:m:xs) = solve b q l 0 (sort xs)\n\nsolve b q l c xs = if (abs b>l) then c else let (cm,nl) = find' b xs\n in solve (b*q) q l (c+cm) nl\n\ntoString n = if(n==(-1)) then \"inf\" else show n\n\nfind' _ [] = (1,[])\nfind' e (x:xs) = if (x==e) then (0,xs) else if(x>e) then (1,x:xs) else find' e xs"}], "src_uid": "749c290c48272a53e2e79730dab0538e"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b] <- (map read.words) <$> getLine\n print $ solve a b\n\nsolve :: Int -> Int -> Int\nsolve a b = minimum [a,b,(a+b) `div` 3] \n", "positive_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n \nroutine :: IO ()\nroutine = do\n [a, b] <- (map read.words) <$> getLine\n putStrLn $ show (solve a b)\n \nsolve :: Int -> Int -> Int\nsolve a b = min (min a b) (div (a+b) 3)"}, {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let [a, b] = map (\\x -> read x :: Integer) $ words s\n print $ minimum [a, b, (a + b) `div` 3]\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter (n - 1)\n \n main :: IO ()\n main = do\n s <- getLine\n let q = read s :: Integer\n iter q"}, {"source_code": "import Control.Monad\n\nreadInts :: IO [Int]\nreadInts = map read.words <$> getLine\n\nmain :: IO()\nmain = do\n [t] <- readInts\n replicateM_ t solve\n \nsolve :: IO()\nsolve = do\n [a,b] <- readInts\n print $ minimum [a,b, div (a+b) 3]"}], "negative_code": [{"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let [a, b] = map (\\x -> read x :: Integer) $ words s\n print $ maximum [a, b, (a + b) `div` 3]\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter (n - 1)\n \n main :: IO ()\n main = do\n s <- getLine\n let q = read s :: Integer\n iter q"}], "src_uid": "8bbec86e427e26158393bbfbf1a067fe"} {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + eps\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\neps :: Double\neps = 1e-10\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | abs (r1 - r2) > l + eps -> CONTAIN b\n | r1 + r2 + eps < l -> NOT_INTERSECT\n | r1 + r2 < l + eps -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n", "positive_code": [{"source_code": "import Debug.Trace\n\ndata Point = Point { x :: Double, y :: Double } deriving Show\n\neps = 1e-10\n\nadd p1 p2 = Point { x = x p1 + x p2, y = y p1 + y p2 }\nmult p k = Point { x = k * x p, y = k * y p }\n\ndist p1 p2 = sqrt $ sqr (x p1 - x p2) + sqr (y p1 - y p2) where\n\tsqr x = x * x\n\nsolve t1' t2' ps pm pt = \n\tif d1 < t2 + eps \n\t\tthen min t1 t2\n\t\telse maximum [maxtime 0, maxtime 1, ternary_search maxtime 0 1]\n\twhere\n\t\tdmt = dist pm pt\n\t\td1 = dist ps pm + dmt\n\t\td2 = dist ps pt\n\t\tt1 = t1' + d1\n\t\tt2 = t2' + d2\n\t\tternary_search f l r = \n\t\t\tif r - l <= eps \n\t\t\t\tthen f $ (l + r) / 2 \n\t\t\t\telse let \n\t\t\t\t\t\tm1 = (2 * l + r) / 3\n\t\t\t\t\t\tm2 = (l + 2 * r) / 3\n\t\t\t\t in \n\t\t\t\t \tif f m1 > f m2 \n\t\t\t\t \t\tthen ternary_search f l m2\n\t\t\t\t \t\telse ternary_search f m1 r\n\t\tbinary_search f l r = \n\t\t\tif r - l <= eps \n\t\t\t\tthen l\n\t\t\t\telse\n\t\t\t\t\tif f $ (l + r) / 2\n\t\t\t\t\t\tthen binary_search f ((l + r) / 2) r\n\t\t\t\t\t\telse binary_search f l ((l + r) / 2)\n\t\tmaxtime rat = \n\t\t\tlet \n\t\t\t\tp = add (mult pm $ 1 - rat) (mult pt rat)\n\t\t\t\td1 = dist ps p\n\t\t\t\td2 = dist pt p\n\t\t\t\tchk x =\t\n\t\t\t\t\tdist ps p' + dist p' pm + dmt < t1 + eps && dist ps p' + dist p' pt < t2 + eps\n\t\t\t\t\twhere \n\t\t\t\t\t\tp' = add (mult ps (1 - x)) (mult p x)\n\t\t\t\t\t\t\n\t\t\tin\n\t\t\t\tif d1 + d2 < t2 + eps && d1 + dmt * (1 + rat) < t1 + eps \n\t\t\t\t\tthen min (t2 - d2) (t1 - dmt * (1 + rat))\n\t\t\t\t\telse dist ps p * binary_search chk 0 1\n\nmain = do\n\t[t1, t2, x0, y0, x2, y2, x1, y1] <- (map read . words) `fmap` getContents\n\tputStrLn $ show $ solve t1 t2 Point {x = x0, y = y0} Point {x = x1, y = y1} Point {x = x2, y = y2}\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | otherwise -> search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + eps\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\neps :: Double\neps = 1e-10\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | abs (r1 - r2) > l + eps -> CONTAIN b\n | r1 + r2 + eps < l -> NOT_INTERSECT\n | r1 + r2 < l + eps -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> (Double, Double) -> (Double, Double) -> (Double, Double) -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> min (ch + t2) (cs + sh + t1)\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | d <= r -> r\n | otherwise -> search 0 r\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n r = (cs + t1 + ch + t2 - sh) / 2\n sr = (cs + t1 - r) / sh\n hr = (ch + t2 - r) / sh\n\n cs_ = cs + t1\n ch_ = ch + t2\n\n (hx, hy) = h\n (sx, sy) = s\n (cx, cy) = c\n\n x = sx * hr + hx * sr\n y = sy * hr + hy * sr\n\n d = sqrt $ (cx - x) ^ 2 + (cy - y) ^ 2\n\n a = angle cs ch sh\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n\n isPossible x = angle cs x (cs + t1 - x) + angle ch x (ch + t2 - x) > a\n\nangle :: Double -> Double -> Double -> Double\nangle a b c = acos . max (-1) . min 1 $ (a * a + b * b - c * c) / (2 * a * b)\n\ndist :: (Double, Double) -> (Double, Double) -> Double\ndist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (permutations)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 maxPath\n where\n maxPath = min (ch + t2) (cs + sh + t1)\n\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + 1e-10\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | r1 + r2 < l -> NOT_INTERSECT\n | abs (r1 - r2) > l -> CONTAIN b\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (permutations)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if tsh + dist c s <= tB then min (tA + tsh) tB else search 0 tsh\n where\n tsh = dist s h\n tA = dist c s + t1\n tB = dist c h + t2\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-5 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\neps :: Double\neps = 1e-5\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ permutations [c1,c2,c3]\n where\n f [c1, c2, c3] = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p <= r\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)\n | r1 + r2 + eps < l = NOT_INTERSECT\n | abs (r1 - r2) > l + eps = CONTAIN $ if r1 > r2 then b else a\n | otherwise = POINTS [ u |+ v, u |- v]\n where\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n v = scale (y1- y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + 1e-10\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r1 + r2 + 1e-5 < l -> NOT_INTERSECT\n | r1 + r2 + 1e-5 > l -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]\n | abs (r1 - r2) > l -> CONTAIN b\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + eps\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\neps :: Double\neps = 1e-10\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | abs (r1 - r2) > l + eps -> CONTAIN b\n | r1 + r2 + eps < l -> NOT_INTERSECT\n | r1 + r2 < l + eps -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if tsh + dist c s <= tB then min (tA + tsh) tB else search 0 tsh\n where\n tsh = dist s h\n tA = dist c s + t1\n tB = dist c h + t2\n search l r = let x = (r + l) / 2 in if\n | r - l < eps -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\neps :: Double\neps = 1e-5\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f [ (c1, c2, c3), (c1, c3, c2), (c2, c3, c1) ]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p <= r + eps\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)\n | r1 + r2 + eps < l = NOT_INTERSECT\n | abs (r1 - r2) > l + eps = CONTAIN $ if r1 > r2 then b else a\n | otherwise = POINTS [ u |+ v, u |- v]\n where\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n v = scale (y1- y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> (Double, Double) -> (Double, Double) -> (Double, Double) -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> min (ch + t2) (cs + sh + t1)\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 r\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n r = (cs + t1 + ch + t2 - sh) / 2\n sr = (cs + t1 - r) / sh\n hr = (ch + t2 - r) / sh\n\n a = angle cs ch sh\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n\n isPossible x = angle cs x (cs + t1 - x) + angle ch x (ch + t2 - x) > a\n\nangle :: Double -> Double -> Double -> Double\nangle a b c = acos . max (-1) . min 1 $ (a * a + b * b - c * c) / (2 * a * b)\n\ndist :: (Double, Double) -> (Double, Double) -> Double\ndist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p <= r\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r1 + r2 < l -> NOT_INTERSECT\n | r1 + r2 == l -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]\n | abs (r1 - r2) > l -> CONTAIN b\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (permutations)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if tsh + dist c s <= tB then maxP else search 0 maxP\n where\n tsh = dist s h\n tA = dist c s + t1\n tB = dist c h + t2\n maxP = min (tA + tsh) tB\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-5 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\neps :: Double\neps = 1e-5\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ permutations [c1, c2, c3]\n where\n f [c1, c2, c3] = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p <= r\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)\n | r1 + r2 < l = NOT_INTERSECT\n | abs (r1 - r2) > l = CONTAIN $ if r1 > r2 then b else a\n | otherwise = POINTS [ u |+ v, u |- v]\n where\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n v = scale (y1- y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (permutations)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + 1e-10\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | r1 + r2 < l -> NOT_INTERSECT\n | abs (r1 - r2) > l -> CONTAIN b\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (permutations)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\n-- solve t1 t2 c h s = trace (show $ isPossible 1.0002) 0.0\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> min (ch + t2) (cs + sh + t1)\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 sh\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n -- search l r = trace (show (l, r)) $ let x = (r + l) / 2 in if\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + 1e-10\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | r1 + r2 < l -> NOT_INTERSECT\n | abs (r1 - r2) > l -> CONTAIN b\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\nimport Data.List (permutations)\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if tsh + dist c s <= tB then maxP else search 0 maxP\n where\n tsh = dist s h\n tA = dist c s + t1\n tB = dist c h + t2\n maxP = min (tA + tsh) tB\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + 1e-10\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)\n | r1 + r2 + 1e-10 < l = NOT_INTERSECT\n | abs (r1 - r2) > l + 1e-10 = CONTAIN $ if r1 > r2 then b else a\n | otherwise = POINTS [ u |+ v, u |- v]\n where\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n v = scale (y1- y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if sh + dist c s <= tB then min tA tB else search 0 sh\n where\n sh = dist s h\n tA = dist c s + sh + t1\n tB = dist c h + t2\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-5 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - sh - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any (\\(c1, c2, c3) -> any (inside c3) (intersect c1 c2)) [ (c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n\ninside :: Circle -> Point -> Bool\ninside (x, r) y = dist x y <= r\n\nintersect :: Circle -> Circle -> [Point]\nintersect (p@(x1, y1), r1) (q@(x2, y2), r2) = if d > r1 + r2 || d < abs (r1 - r2)\n then []\n else [(x3 + h * (y2 - y1) / d, y3 + h * (x1 - x2) / d), (x3 + h * (y1 - y2) / d, y3 + h * (x2 - x1) / d)]\n where\n d = dist p q\n a = (r1 ^ 2 - r2 ^ 2 + d ^ 2) / (2 * d)\n h = (sqrt $ r1 ^ 2 - a ^ 2)\n x3 = x1 + a * (x2 - x1) / d\n y3 = y1 + a * (y2 - y1) / d\n\n\ndist :: Point -> Point -> Double\ndist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if tsh + dist c s <= tB then min (tA + tsh) tB else search 0 tsh\n where\n tsh = dist s h\n tA = dist c s + t1\n tB = dist c h + t2\n search l r = let x = (r + l) / 2 in if\n | r - l < eps -> r\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\neps :: Double\neps = 1e-5\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f [ (c1, c2, c3), (c1, c3, c2), (c2, c3, c1) ]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p <= r + eps\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)\n | r1 + r2 + eps < l = NOT_INTERSECT\n | abs (r1 - r2) > l + eps = CONTAIN $ if r1 > r2 then b else a\n | otherwise = POINTS [ u |+ v, u |- v]\n where\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n v = scale (y1- y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = do\n (t1, t2) <- pair\n cinema <- pair\n home <- pair\n shop <- pair\n print $ solve t1 t2 cinema home shop\n\nsolve :: Double -> Double -> Point -> Point -> Point -> Double\nsolve t1 t2 c h s = if\n | ch + t2 >= cs + sh -> maxPath\n | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2\n | otherwise -> search 0 maxPath\n where\n sh = dist s h\n cs = dist c s\n ch = dist c h\n\n maxPath = min (ch + t2) (cs + sh + t1)\n\n f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)\n\n search l r = let x = (r + l) / 2 in if\n | r - l < 1e-6 -> x\n | isPossible x -> search x r\n | otherwise -> search l x\n isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\ncheck :: Circle -> Circle -> Circle -> Bool\ncheck c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]\n where\n f (c1, c2, c3) = case intersect c1 c2 of\n NOT_INTERSECT -> False\n CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT\n POINTS ps -> any (inside c3) ps\n\ninside :: Circle -> Point -> Bool\ninside (c, r) p = dist c p < r + eps\n\n(|+) :: Point -> Point -> Point\n(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)\n\n(|-) :: Point -> Point -> Point\n(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)\n\nscale :: Point -> Double -> Point\nscale (x, y) k = (x * k, y * k)\n\neps :: Double\neps = 1e-10\n\ndata Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)\n\nintersect :: Circle -> Circle -> Intersection\nintersect a b = if\n | r2 > r1 -> intersect b a\n | abs (r1 - r2) > l + eps -> CONTAIN b\n | r1 + r2 + eps < l -> NOT_INTERSECT\n | r1 + r2 + eps > l -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]\n | otherwise -> POINTS [ u |+ v, u |- v]\n where\n (c1, r1) = a\n (c2, r2) = b\n l = dist c1 c2\n la = (r1 * r1 + l * l - r2 * r2) / (2 * l)\n h = sqrt $ r1 * r1 - la * la\n u = c1 |+ scale (c2 |- c1) (la / l)\n (x1, y1) = c1\n (x2, y2) = c2\n v = scale (y1 - y2, x2 - x1) (h / l)\n\ndist :: Point -> Point -> Double\ndist p q = norm (p |- q)\n\nnorm :: Point -> Double\nnorm (x, y) = sqrt $ x * x + y * y\n\npair :: IO (Double, Double)\npair = words <$> getLine >>= \\[x, y] -> pure (read x, read y)\n"}], "src_uid": "3edd332d8359ead21df4d822af6940c7"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n0,n1,n2] <- (map read.words) <$> getLine\n putStrLn $ solve n0 n1 n2\n\nsolve :: Int -> Int -> Int -> String\nsolve n0 n1 n2\n | n1 == 0 =\n if n2 == 0\n then replicate (n0+1) '0'\n else replicate (n2+1) '1'\n | n2 == 0 =\n replicate (n0+1) '0' ++\n take n1 (cycle \"10\")\n | n0 == 0 =\n replicate (n2+1) '1' ++\n take n1 (cycle \"01\")\n | otherwise =\n take (fromEnum (even n1)) \"1\" ++\n replicate (n0+1) '0' ++\n take (2*((n1-1) `div` 2)) (cycle \"10\") ++\n replicate (n2+1) '1'\n", "positive_code": [{"source_code": "\nsolve :: Int -> Int -> Int -> String\nsolve 0 0 n = replicate (n+1) '1'\nsolve n 0 0 = replicate (n+1) '0'\nsolve n0 n1 n2 = (replicate (n0+1) '0') ++ (replicate (n2+1) '1') ++ (take (n1-1) $ cycle \"01\")\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n0:n1:n2:_) <- readNums\n putStrLn $ solve n0 n1 n2\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}, {"source_code": "import Control.Arrow\nimport Control.Monad.State\nimport Data.Array\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = interact $\n lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines\n\nsolve :: [Int] -> String\nsolve [n0,0,0] = replicate (n0+1) '0'\nsolve [0,0,n2] = replicate (n2+1) '1'\nsolve [n0,n1,n2] = replicate (n2+1) '1' ++ replicate (n0+1) '0' ++ take (n1-1) (cycle \"10\")\n\n"}], "negative_code": [{"source_code": "\nsolve :: Int -> Int -> Int -> String\nsolve n0 n1 n2 = (replicate (n0+1) '0') ++ (replicate (n2+1) '1') ++ (take (n1-1) $ cycle \"01\")\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n0:n1:n2:_) <- readNums\n putStrLn $ solve n0 n1 n2\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "src_uid": "4bbb078b66b26d6414e30b0aae845b98"} {"source_code": "-- 2019-11-24 05:31:08.52513552 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Bool\nsolve x y\n |x==1 = y==1\n |x<=3 = y<=3\n |otherwise = True\n\nroutine :: IO ()\nroutine = do\n [x,y] <- fmap (map read.words) getLine\n putStrLn $ if solve x y then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "-- 2019-11-19 19:41:35.813043782 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-20 21:46:29.481091921 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 05:33:31.10142959 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 05:32:16.025342204 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-24 05:35:19.450643282 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- 2019-11-19 20:10:07.141272712 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (1 >= b) \"YES\" (iF (iF (3 >= b) 1 3 >= a) \"NO\" \"YES\")\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/B\n\nimport qualified Data.Map as Map\n\n\ndata Case = Case Int Int\ntype History = Map.Map\ndata Response = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let numbers = map read $ words line :: [Int]\n Case (head numbers) (last numbers)\n\n\nsolveWithHistory :: Case -> History Int Int -> Response\nsolveWithHistory (Case source target) history\n | source >= target = YES -- We can always reach a lower number by doing source - 1\n | source == 2 && target == 3 = YES -- This is an aceptional case because (3 * 2) / 2 = 3\n | source > 3 = YES -- If source > 3 source can increase (slowly) until reaching the target\n | otherwise = NO\n where updatedHistory = Map.insert source source history\n\n\nsolve :: Case -> Response\nsolve (Case source target) = solveWithHistory (Case source target) Map.empty\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/B\n\nimport qualified Data.Map as Map\n\n\ndata Case = Case Int Int\ntype History = Map.Map\ndata Response = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let numbers = map read $ words line :: [Int]\n Case (head numbers) (last numbers)\n\n\nfirstOperation :: Int -> Int\nfirstOperation number = (3 * number) `div` 2\n\n\nsecondOperation :: Int -> Int\nsecondOperation number = number - 1\n\n\nsolveWithHistory :: Case -> History Int Int -> Response\nsolveWithHistory (Case source target) history\n | source >= target = YES\n | source == 2 && target == 3 = YES\n | source > 3 = YES\n -- | Map.member source history = NO -- A loop has been detected\n -- | even source = solveWithHistory (Case (firstOperation source) target) updatedHistory\n -- | source > 1 = solveWithHistory (Case (secondOperation source) target) updatedHistory\n | otherwise = NO\n where updatedHistory = Map.insert source source history\n\n\nsolve :: Case -> Response\nsolve (Case source target) = solveWithHistory (Case source target) Map.empty\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- (read::String->Int) <$> getLine\n\n replicateM_ t $ do\n [x, y] <- fmap (read::String->Int) . words <$> getLine\n let v | x == y = \"YES\"\n | x == 1 = \"NO\"\n | x > 3 = \"YES\"\n | x <= 3 && y <= 3 = \"YES\"\n | otherwise = \"NO\"\n\n putStrLn v\n return ()\n\n return ()"}, {"source_code": "main = interact $ unlines . map yesno . solveTests . map read . words\n\n\nsolveTests (t:ls) = solveTests' t ls\n\nsolveTests' 0 _ = []\nsolveTests' t (x:y:ls) = (solveTest x y) : solveTests' (t-1) ls\nsolveTests' _ _ = []\n\nsolveTest x y\n | x > 3 = True\n | x == 2 = y <= 3\n | otherwise = y <= x\n\n\nyesno v = if v then \"YES\" else \"NO\"\n"}], "negative_code": [{"source_code": "-- 2019-11-20 21:50:07.269294269 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' f (a, b) = f a b\nparser :: String -> (Int, Int)\nparser = fromJust . parseTwoInts\nparseTwoInts :: String -> Maybe (Int, Int)\nparseTwoInts i = do {when (length (lines i) /= 1) Nothing;\n ns <- mapM readMaybe $ words i :: Maybe ([Int]);\n when (length ns /= 2) Nothing;\n let {[a, b] = ns};\n return (a, b)}\nsolve = \\a b -> iF (3 >= a) (iF (iF (b >= 3) 3 a >= b) \"YES\" \"NO\") \"YES\"\nmain = getContents >>= (\\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/B\n\nimport qualified Data.Map as Map\n\n\ndata Case = Case Int Int\ntype History = Map.Map\ndata Response = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let numbers = map read $ words line :: [Int]\n Case (head numbers) (last numbers)\n\n\nfirstOperation :: Int -> Int\nfirstOperation number = (3 * number) `div` 2\n\n\nsecondOperation :: Int -> Int\nsecondOperation number = number - 1\n\n\nsolveWithHistory :: Case -> History Int Int -> Response\nsolveWithHistory (Case source target) history\n | source >= target = YES\n | source > 3 = YES\n -- | Map.member source history = NO -- A loop has been detected\n -- | even source = solveWithHistory (Case (firstOperation source) target) updatedHistory\n -- | source > 1 = solveWithHistory (Case (secondOperation source) target) updatedHistory\n | otherwise = NO\n where updatedHistory = Map.insert source source history\n\n\nsolve :: Case -> Response\nsolve (Case source target) = solveWithHistory (Case source target) Map.empty\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/1257/B\n\nimport qualified Data.Map as Map\n\n\ndata Case = Case Int Int\ntype History = Map.Map\ndata Response = YES | NO deriving (Show)\n\n\ntoCase :: String -> Case\ntoCase line = do\n let numbers = map read $ words line :: [Int]\n Case (head numbers) (last numbers)\n\n\nfirstOperation :: Int -> Int\nfirstOperation number = (3 * number) `div` 2\n\n\nsecondOperation :: Int -> Int\nsecondOperation number = number - 1\n\n\nsolveWithHistory :: Case -> History Int Int -> Response\nsolveWithHistory (Case source target) history\n | source >= target = YES\n | Map.member source history = NO -- A loop has been detected\n | even source = solveWithHistory (Case (firstOperation source) target) updatedHistory\n | source > 1 = solveWithHistory (Case (secondOperation source) target) updatedHistory\n | otherwise = NO\n where updatedHistory = Map.insert source source history\n\n\nsolve :: Case -> Response\nsolve (Case source target) = solveWithHistory (Case source target) Map.empty\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . tail . lines\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- (read::String->Int) <$> getLine\n\n replicateM_ t $ do\n [x, y] <- fmap (read::String->Int) . words <$> getLine\n let v | x == y = \"YES\"\n | x == 1 = \"NO\"\n | x > 3 = \"YES\"\n | x <= 3 && y <= 3 = \"YES\"\n | otherwise = \"NO\"\n\n print v\n return ()\n\n return ()"}], "src_uid": "b3978805756262e17df738e049830427"} {"source_code": "#!/usr/bin/runhaskell\n\n-- We do not check indexes vs. string length because of speed.\n\n-- This function do left shift\nshift :: String -> Int -> String\nshift s k = bs ++ as\n where (as, bs) = splitAt k s\n\n-- This function do right shift of substring\nshiftSub :: String -> [Int] -> String\nshiftSub s [l, r, k]\n | k == 0 = s\n | n == 0 = s\n | otherwise = as ++ (shift bs n) ++ cs\n where l' = l - 1\n n = r - l' - k `mod` (r - l')\n (as, rs) = splitAt l' s\n (bs, cs) = splitAt (r - l') rs\n\nmain = do\n s <- getLine\n getLine -- Skip second line\n ls <- fmap lines getContents\n let qs = map (map read . words) ls :: [[Int]] in putStrLn (foldl shiftSub s qs)\n", "positive_code": [{"source_code": "-- rotate :: String -> [Int] -> String\nrotate s [l, r, k] =\n\t\ttake (l - 1) s ++\n\t \t(take m $ drop (m - k') (ss ++ ss)) ++\n\t \tdrop r s\n\twhere\n\t \tm = r - l + 1\n\t\tk' = k `mod` m\n \t\tss = take m $ drop (l - 1) s\n\nmain = do\n\ts <- getLine\n\t_ <- getLine\n\tops <- (map (map read . words) . lines) `fmap` getContents\n\n\tputStrLn $ foldl rotate s ops\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nreadInt :: String -> Int \nreadInt = read\n\nmain = do\n str <- getLine\n ops <- map (map readInt . words) . tail . lines <$> getContents\n putStrLn $ foldl rotate str ops\n\nrotate :: String -> [Int] -> String\nrotate str [l1, r1, k]\n | k == 0 || l == r = str\n | otherwise = take l str ++ (take (r - l + 1) $ drop (r - l + 1 - n) $ ss ++ ss) ++ drop r1 str\n where l = l1 - 1\n r = r1 - 1\n n = k `mod` (r - l + 1)\n ss = take (r - l + 1) $ drop l str"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\n\nmain = do\n (str, queries) <- (head &&& (map read . drop 2)) . words <$> getContents\n putStrLn $ solve str queries\n\nsolve str [] = str\nsolve str (l : r : k : qs) = let str' = rotate str (l - 1) r k in solve str' qs\n\nrotate str l r k\n | k >= r - l = rotate str l r (k `mod` (r - l))\n | otherwise = let ((pref, str'), suff) = first (splitAt l) $ splitAt r str in pref ++ ((shift str' k) ++ suff)\n\nshift str k = uncurry (flip (++)) . splitAt ((length str) - k) $ str\n\n\n"}], "negative_code": [{"source_code": "-- rotate :: String -> [Int] -> String\nrotate s [l, r, k] =\n\t\ttake (l - 1) s ++\n\t \t(take m $ drop (m - k) (ss ++ ss)) ++\n\t \tdrop r s\n\twhere\n\t \tm = r - l + 1\n\t\tk' = k `mod` m\n \t\tss = take m $ drop (l - 1) s\n\nmain = do\n\ts <- getLine\n\t_ <- getLine\n\tops <- (map (map read . words) . lines) `fmap` getContents\n\n\tputStrLn $ foldl rotate s ops\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nreadInt :: String -> Int \nreadInt = read\n\nmain = do\n str <- getLine\n ops <- map (map readInt . words) . tail . lines <$> getContents\n putStrLn $ foldl rotate str ops\n\nrotate :: String -> [Int] -> String\nrotate str [l1, r1, k]\n | k == 0 || l == r = str\n | otherwise = take l str ++ (take (r - l + 1) $ drop (r - l + 1 - k) $ ss ++ ss) ++ drop r1 str\n where l = l1 - 1\n r = r1 - 1\n n = k `mod` (r - l + 1)\n ss = take (r - l + 1) $ drop l str"}, {"source_code": "import Control.Applicative ((<$>))\n\nreadInt :: String -> Int \nreadInt = read\n\nmain = do\n str <- getLine\n ops <- map (map readInt . words) . tail . lines <$> getContents\n print $ foldl rotate str ops\n\nrotate :: String -> [Int] -> String\nrotate str [l1, r1, k]\n | k == 0 || l == r = str\n | otherwise = take l str ++ (take (r - l + 1) $ drop (r - l + 1 - k) $ ss ++ ss) ++ drop r1 str\n where l = l1 - 1\n r = r1 - 1\n n = k `mod` (r - l + 1)\n ss = take (r - l + 1) $ drop l str"}], "src_uid": "501b60c4dc465b8a60fd567b208ea1e3"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (sort)\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n \tas <- map read . words <$> getLine\n\n\tlet\n \t\tres = find 1 (sort as) m\n\t \t\twhere\n\t\t\t\tfind i [] m\n \t\t\t\t\t| i <= m = i : find (i + 1) [] (m - i)\n\t\t\t\t\t| otherwise = []\n\t\t\t\tfind i (a:as) m\n\t\t\t\t\t| i > m = []\n\t\t\t\t\t| i == a = find (i + 1) as m\n\t\t\t\t\t| otherwise = i : find (i + 1) (a:as) (m - i)\n\n\tprint $ length res\n\tputStr . unwords . map show $ res\n", "positive_code": [{"source_code": "import Data.List (sort)\nmain = do\n [n,m] <- fmap ((map read) . words) getLine\n a <- fmap ((map read) . words) getLine\n let (len,l) = solve 0 [] m (sort a) [1..]\n print len\n mapM_ (\\c -> putStr ((show c) ++ \" \")) l\n \n\nsolve len l m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)\nsolve len l m ip (a:as)\n |a==head ip = solve len l m (tail ip) as\n |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)"}, {"source_code": "import Data.Foldable (toList)\nimport Data.Sequence (fromList , sort)\nmain = do\n [n,m] <- fmap ((map read) . words) getLine\n a <- fmap ((map read) . words) getLine\n let x = toList . sort $ fromList a\n let (len,l) = solve 0 [] m (x) [1..]\n print len\n mapM_ (\\c -> putStr ((show c) ++ \" \")) l\n \n\nsolve len l m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)\nsolve len l m ip (a:as)\n |a==head ip = solve len l m (tail ip) as\n |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)"}, {"source_code": "{-# LANGUAGE BangPatterns#-}\nimport Data.List (sort)\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let (len,l) = solve 0 [] m (sort a) [1..]\n print len\n mapM_ (\\c -> putStr ((show c) ++ \" \")) l\n \n\nsolve !len l !m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)\nsolve !len l !m ip (a:as)\n |a==head ip = solve len l m (tail ip) as\n |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)"}, {"source_code": "{-# LANGUAGE BangPatterns#-}\nimport Data.Foldable (toList)\nimport Data.Sequence (fromList , unstableSort)\nmain = do\n [n,m] <- fmap ((map read) . words) getLine\n a <- fmap ((map read) . words) getLine\n let x = toList . unstableSort $ fromList a\n let (len,l) = solve 0 [] m (x) [1..]\n print len\n mapM_ (\\c -> putStr ((show c) ++ \" \")) l\n \n\nsolve !len !l !m [] !(a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)\nsolve !len !l !m !ip !(a:as)\n |a==head ip = solve len l m (tail ip) as\n |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)"}, {"source_code": "import Data.Foldable (toList)\nimport Data.Sequence (fromList , unstableSort)\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let x = toList . unstableSort $ fromList a\n let (len,l) = solve 0 [] m (x) [1..]\n print len\n mapM_ (\\c -> putStr ((show c) ++ \" \")) l\n \n\nsolve len l m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)\nsolve len l m ip (a:as)\n |a==head ip = solve len l m (tail ip) as\n |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (sort)\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n \tas <- map read . words <$> getLine\n\n\tlet\n \t\tres = find 1 (sort as) m\n\t \t\twhere\n\t\t\t\tfind i [] m\n \t\t\t\t\t| i <= m = i : find (i + 1) [] (m - i)\n\t\t\t\t\t| otherwise = []\n\t\t\t\tfind i (a:as) m\n\t\t\t\t\t| i > m = []\n\t\t\t\t\t| i == a = find (i + 1) as m\n\t\t\t\t\t| otherwise = i : find (i + 1) (a:as) (m - i)\n\n\tprint $ length res\n\tputStr . unwords . map show $ res\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (sort)\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n \tas <- map read . words <$> getLine\n\n\tlet\n \t\tres = find 1 (sort as) m\n\t \t\twhere\n\t\t\t\tfind i [] m | i <= m = i : find (i + 1) [] (m - i)\n\t\t\t\tfind i [] m | otherwise = []\n\t\t\t\tfind i (a:as) m\n\t\t\t\t\t| i > m = []\n\t\t\t\t\t| i == a = find (i + 1) as m\n\t\t\t\t\t| otherwise = i : find (i + 1) (a:as) (m - i)\n\n\tprint $ length res\n\tputStr . unwords . map show $ res\n"}, {"source_code": "import qualified Data.Set as S\ngreedy :: Int -> S.Set Int -> [Int]\ngreedy cash haves = zipWith (-) (tail bought) bought\n where bought = takeWhile (<=cash) $ scanl (+) 0 $ filter (notIn haves) [1..]\n notIn s x = not $ S.member x s\nsolve (x:xs) = show (length soln) ++ \"\\n\" ++ unwords (map show soln)\n where soln = greedy x $ S.fromList xs\nmain = putStrLn . solve . map read . tail . words =<< getContents"}, {"source_code": "import Data.List\nimport Data.Functor\n\nmain :: IO()\nmain = do\n [n, m] <- map read . words <$> getLine\n a <- sort . map read . words <$> getLine\n let r = solve m 1 a []\n print $ length r\n putStrLn $ unwords $ map show r\n\nbound :: Int\nbound = 1000000000\n\nsolve :: Int -> Int -> [Int] -> [Int] -> [Int]\nsolve m i a r | m < i = r\n | i > bound = r\n | otherwise = if null a\n then solve (m - i) (i + 1) a (i:r)\n else let (av:ax) = a\n in if i < av\n then solve (m - i) (i + 1) a (i:r)\n else if i == av\n then solve m (i + 1) ax r\n else solve m i ax r\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.List (sort)\n\nmain = do\n\t[n, m] <- map read . words <$> getLine\n \tas <- map read . words <$> getLine\n\n\tlet\n \t\tres = find 1 (sort as) m\n\t \t\twhere\n\t\t\t\tfind i [] m | i <= m = i : find (i + 1) [] (i - m)\n\t\t\t\tfind i [] m | otherwise = []\n\t\t\t\tfind i (a:as) m\n\t\t\t\t\t| i > m = []\n\t\t\t\t\t| i == a = find (i + 1) as m\n\t\t\t\t\t| otherwise = i : find (i + 1) (a:as) (m - i)\n\n\tprint $ length res\n\tputStr . unwords . map show $ res\n"}], "src_uid": "0318d4d5ea3425bf6506edeb1026f597"} {"source_code": "module Main where\n\n-- http://codeforces.com/contest/1199/problem/A\n\nimport qualified Data.ByteString.Char8 as B\nimport Control.Arrow ((>>>))\n--import Debug.Trace\n--import qualified Data.Array as A\n\nsolD :: Int -> Int -> [Int] -> Int\nsolD l r xs = day l r 0 (replicate l m ++ xs)\n where\n m = 1 + maximum xs\n\n\nday :: Int -> Int -> Int -> [Int] -> Int \nday l r acc xs = if min' x lx && min' x (take r rx)\n then acc + 1\n else day l r (acc+1) (tail xs)\n where\n min' _ [] = True\n min' a b = a < minimum b\n (lx, x:rx) = splitAt l xs \n\n \nreadInt0 :: B.ByteString -> Int\nreadInt0 = maybe 0 fst . B.readInt \n\n\nmain = B.interact $ B.lines >>> fmap B.words \n >>> fmap (fmap readInt0) \n >>> (\\[[_,l,r], xs] -> solD l r xs)\n >>> B.pack . show\n", "positive_code": [{"source_code": "main = getContents >>= print . solve . map read . tail . words\n\nsolve (x:y:xs) = (+1) $ length $ takeWhile (== False) $ map notRainy $ zipper [] xs\n where notRainy (a:as, b) = a == minimum (take (x + 1) (a:as) ++ take y b)\n\nzipper rec [] = []\nzipper rec (x:xs) = (x:rec, xs) : zipper (x:rec) xs\n"}, {"source_code": "import Data.Array\nimport Data.List\nmain = do\n [n,x,y] <- map read . words <$> getLine\n as <- listArray (1,n) . map read . words <$> getLine :: IO (Array Int Int)\n let Just i = find (\\i -> all ((>= as!i) . (as !)) $ filter (inRange (bounds as)) [i-x..i+y]) [1..n]\n print i\n"}], "negative_code": [{"source_code": "module Main where\n\n-- http://codeforces.com/contest/1199/problem/A\n\nimport qualified Data.ByteString.Char8 as B\nimport Control.Arrow ((>>>))\n--import Debug.Trace\n--import qualified Data.Array as A\n\nsolD :: Int -> Int -> [Int] -> Int\nsolD l r xs = day l r 0 (replicate l m ++ xs) - l\n where\n m = maximum xs\n\n\nday :: Int -> Int -> Int -> [Int] -> Int \nday l r acc xs = if min' x lx && min' x (take r rx)\n then acc + l + 1\n else day l r (acc+1) (tail xs)\n where\n min' _ [] = True\n min' a b = a < minimum b\n (lx, x:rx) = splitAt l xs \n\n \nreadInt0 :: B.ByteString -> Int\nreadInt0 = maybe 0 fst . B.readInt \n\n\nmain = B.interact $ B.lines >>> fmap B.words \n >>> fmap (fmap readInt0) \n >>> (\\[[_,l,r], xs] -> solD l r xs)\n >>> B.pack . show\n"}, {"source_code": "module Main where\n\n-- http://codeforces.com/contest/1199/problem/A\n\nimport qualified Data.ByteString.Char8 as B\nimport Control.Arrow ((>>>))\n--import Debug.Trace\n--import qualified Data.Array as A\n\nsolD :: Int -> Int -> [Int] -> Int\nsolD l r xs = if length xs <= l\n then length xs\n else day l r 0 xs\n\nday :: Int -> Int -> Int -> [Int] -> Int \nday l r acc xs = if min' x lx && min' x (take r rx)\n then acc + l + 1\n else day l r (acc+1) (tail xs)\n where\n min' _ [] = True\n min' a b = a < minimum b\n (lx, x:rx) = splitAt l xs \n\n \nreadInt0 :: B.ByteString -> Int\nreadInt0 = maybe 0 fst . B.readInt \n\n\nmain = B.interact $ B.lines >>> fmap B.words \n >>> fmap (fmap readInt0) \n >>> (\\[[_,l,r], xs] -> solD l r xs)\n >>> B.pack . show\n"}, {"source_code": "-- import Debug.Trace\nimport Data.List\nmain = interact $ show . solve . map read . words\ndata T = T {tI :: !Int, tJ :: !Int, tM :: !Int, tMI :: !Int, tT :: B} deriving Show\ndata B = B {bLeft :: T, bRight :: T} | N { nA :: !Int } deriving Show\nsolve :: [Int] -> Int\nsolve (n:x:y:as) = go 1 where\n t = makeTree $ zipWith5 T [1..] [1..] as [1..] (map N as)\n makeTree :: [T] -> T\n makeTree [t] = t\n makeTree ts = makeTree $ pairs ts\n pairs :: [T] -> [T]\n pairs [] = []\n pairs [t] = [t]\n pairs (a:b:ts) = T (tI a) (tJ b) m mi (B a b) : pairs ts where\n (m,mi) = min (tM a,tMI a) (tM b,tMI b)\n go l | l > n = 42\n | max 1 (i - x) == l = i\n | otherwise = go (i-x) where\n i = locateMin l (min n (l+x+y))\n locateMin l r = -- traceShowId $ traceShow (l,r) $\n snd $ go l r t where\n go :: Int -> Int -> T -> (Int,Int)\n-- go l r _ | traceShow (l,r) False = undefined\n go l r (T i j m mi t) | l == i && r == j = (m,mi)\n go l r (T i j m _ (B a b)) | r <= tJ a = go l r a\n | l >= tI b = go l r b\n | otherwise = min left right\n where left = go l (tJ a) a\n right = go (tI b) r b\n-- go l r t | traceShow (l,r,t) False = undefined\n"}], "src_uid": "5e2a5ee02c1a2f35a52e76cde96463a3"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n xs <- sort.map (fromIntegral.readInt).B.words <$> B.getLine\n ys <- sort.map (fromIntegral.readInt).B.words <$> B.getLine\n print $ solve n m xs ys\n\nsolve :: Int -> Int -> [Int64] -> [Int64] -> Int64\nsolve n m xs ys = minimum $ map calc bds\n where\n bds = xs ++ ys :: [Int64]\n !arrX = listArray (0,n-1) xs :: UArray Int Int64\n !arrY = listArray (0,m-1) ys :: UArray Int Int64\n !sumX = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int64\n !sumY = listArray (0,m-1) $ scanr1 (+) ys :: UArray Int Int64\n calc bd = calcX bd + calcY bd\n where\n calcX bd\n | bd <= unsafeAt arrX 0 = 0\n | otherwise = fromIntegral (i+1) * bd - unsafeAt sumX i\n where\n i = upperBound (\\i->unsafeAt arrX i < bd) 0 (n-1)\n calcY bd\n | unsafeAt arrY (m-1) <= bd = 0\n | otherwise = unsafeAt sumY j - bd * (fromIntegral $ m-1-j+1)\n where\n j = lowerBound (\\j->unsafeAt arrY j > bd) 0 (m-1)\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}\n\nupperBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nupperBound p low high = go low high\n where\n go !low !high\n | high <= low = low\n | p mid = go mid high\n | otherwise = go low (mid - 1)\n where\n mid = (low + high + 1) `quot` 2\n{-# INLINE upperBound #-}", "positive_code": [{"source_code": "import Data.List\nz[] _=[]\nz _ []=[]\nz(a:as)(b:bs)|b>a=(b-a):z as bs|1>0=[]\ns[a,b]=foldl'(+)0$z(sort a)(reverse$sort b)\nmain=interact$show.s.map(map(foldl'(\\a c->fromIntegral(fromEnum c-fromEnum '0')+a*10::Integer)0).words).tail.lines\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n xs <- sort.map (fromIntegral.readInt).B.words <$> B.getLine\n ys <- sort.map (fromIntegral.readInt).B.words <$> B.getLine\n print $ solve n m xs ys\n\nsolve :: Int -> Int -> [Int64] -> [Int64] -> Int64\nsolve n m xs ys = minimum $ map calc bds\n where\n bds = maximum ys : xs :: [Int64]\n !arrX = listArray (0,n-1) xs :: UArray Int Int64\n !arrY = listArray (0,m-1) ys :: UArray Int Int64\n !sumX = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int64\n !sumY = listArray (0,m-1) $ scanr1 (+) ys :: UArray Int Int64\n calc bd = calcX bd + calcY bd\n where\n calcX bd\n | bd <= unsafeAt arrX 0 = 0\n | otherwise = fromIntegral (i+1) * bd - unsafeAt sumX i\n where\n i = upperBound (\\i->unsafeAt arrX i < bd) 0 (n-1)\n calcY bd\n | unsafeAt arrY (m-1) <= bd = 0\n | otherwise = unsafeAt sumY j - bd * (fromIntegral $ m-1-j+1)\n where\n j = lowerBound (\\j->unsafeAt arrY j > bd) 0 (m-1)\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}\n\nupperBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nupperBound p low high = go low high\n where\n go !low !high\n | high <= low = low\n | p mid = go mid high\n | otherwise = go low (mid - 1)\n where\n mid = (low + high + 1) `quot` 2\n{-# INLINE upperBound #-}"}, {"source_code": "import Data.List\nz[] _=[]\nz _ []=[]\nz(a:as)(b:bs)|b>a=(b-a):z as bs|1>0=[]\ns[a,b]=foldl'(+)0$z(sort a)(reverse$sort b)\nmain=interact$show.s.map(map(foldl'(\\a c->fromEnum c-fromEnum '0'+a*10)0).words).tail.lines\n"}], "src_uid": "e0b5169945909cd2809482b7fd7178c2"} {"source_code": "main = do\n\t[n, m] <- fmap (map read . words) getLine\n\tputStrLn $ show $ gao n m\n\ngao n m = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n--\tsq = [i * i | i <- [1 .. n]]\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until (\\k -> k * k >= j) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n", "positive_code": [{"source_code": "main = do\n\t[n, m] <- fmap (map read . words) getLine\n\tputStrLn $ show $ gao n m\n\ngao n m = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n r1 = min n ((m + 1) `div` 2)\n r2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n r' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n i' = sum $ map (min m) [i * i | i <- [1 .. n]]"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}, {"source_code": "main = do getLine >>= putStr . show . gao . map read . words\n\ngao [n, m] = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = max 0 $ pred $ min n ((m + 4) `div` 4)\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]\n\ti' = sum $ map (min m) [i * i | i <- [1 .. n]]\n\n"}], "negative_code": [{"source_code": "main = do\n\t[n, m] <- fmap (map read . words) getLine\n\tputStrLn $ show $ gao n m\n\ngao n m = r1 + r2 + 2 * (i' - r') where\n\tr1 = min n ((m + 1) `div` 2)\n\tr2 = min n (m `div` 4)\n\tsq = [i * i | i <- [1 .. n]]\n\tr' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\\i j -> until (\\k -> k * k >= j) succ i) 0 $ map (flip (-) m) sq\n\ti' = sum $ map (min m) sq\n"}], "src_uid": "aad7ebf4fa919fae78bfc878e47e483c"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nprune :: [Int] -> [Int]\nprune (x : ys@(y : zs))\n | x >= y = prune (x : zs)\n | otherwise = x : prune ys\nprune xs = xs\n\nsolve :: [Int] -> [Int]\nsolve li = let\n qs = prune li\n psegs = reverse $ scanl (\\(_, rli) q -> span (< q) rli) ([], li) qs\n in concat $ snd (head psegs) : map fst psegs\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n _ <- readInts\n p <- readInts\n putInts $ solve p\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n ps <- popInts\n return $ B.unwords $ map bshow (solve n ps)\n\n\nsolve n ps0 = solve' (IntSet.fromDistinctAscList [1 .. n]) (reverse ps0)\n where\n solve' _ [] = []\n solve' s ps =\n let i = fromJust $ elemIndex (IntSet.findMax s) ps\n (qs, rs) = splitAt (i + 1) ps\n s' = IntSet.difference s (IntSet.fromList qs) in\n reverse qs ++ solve' s' rs\n"}], "negative_code": [], "src_uid": "1637670255f8bd82a01e2ab20cdcc9aa"} {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (nm:(take 1 rest)) ++ tcio (drop 1 rest)\r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n\r\nsolve :: [[Integer]] -> Integer\r\nsolve [[_,x], qs] = sum $ map (\\(q,t)->q*t) $ concat $ map fst $ unfoldr f (zip qs (repeat 1), True) where\r\n f ([],_) = Nothing\r\n f qtsc@(qts,can) = Just (qtsc, (reverse qts1,can1)) where\r\n (qts1,can1) = foldl' g ([],can) qts \r\n g (qts,can) (q,t)\r\n | can && q `mod` x == 0 = ((q `div` x, t*x):qts,True) \r\n | otherwise = (qts, False)\r\n", "positive_code": [{"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (guard, MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> Int64 -> [Int64] -> Int64\r\nsolve n x as = answer\r\n where\r\n xs = takeWhile (<= (1000000000 :: Int64)) $ iterate (* x) x\r\n answer = sum $ as ++ do\r\n currX <- xs\r\n let prevX = currX `div` x\r\n guard $ all (\\a -> a `mod` prevX == 0) as\r\n a <- takeWhile (\\a -> a `mod` currX == 0) as\r\n return a\r\n \r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, x] <- B8.getLine <&> map readIntB8 . B8.words\r\n as <- B8.getLine <&> map (\\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words\r\n let answer = solve n ((fromIntegral x) :: Int64) as\r\n printf \"%lld\\n\" answer\r\n"}, {"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Char\n--import Debug.Trace\nimport System.IO\nimport Text.Read\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, x] <- fmap (map read . words) getLine :: IO [Integer]\n a <- fmap (map read . words) getLine :: IO [Integer]\n print $ solve x a\n return ()\n\nstp :: Integer -> [Integer] -> [Integer]\nstp x a = map (`div` x) a'\n where\n a' = takeWhile (\\i -> i `mod` x == 0) a\n\ntakeWhileIncl :: (a -> Bool) -> [a] -> [a]\ntakeWhileIncl f [] = []\ntakeWhileIncl f (x:xs)\n | f x = x:takeWhileIncl f xs\n | otherwise = [x]\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x a =\n let allNums = takeWhileIncl (\\x -> length x == length a) . iterate (stp x) $ a\n withPowers = zip allNums (iterate (* x) 1)\n result = sum $ map (\\(a, b) -> sum a * b) withPowers\n in result\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Text.Printf\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nvaluation :: Integer -> Integer -> Integer\nvaluation x a\n | a `mod` x == 0 = 1 + (valuation x $ a `div` x)\n | otherwise = 1\n\nargmin :: [Integer] -> (Int, Integer)\nargmin [a] = (0, a)\nargmin (a:as) =\n let (i, b) = argmin as in\n if b < a then (i + 1, b) else (0, a)\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x a =\n let (i, v) = argmin $ map (valuation x) a in\n (v + 1) * (sum $ take i a) + v * (sum $ drop i a)\n\nsolveCase :: IO String\nsolveCase = do\n (n:x:[]) <- readInts\n fmap (show . solve x) readInts\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n--repeat \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n \r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (nm:(take 1 rest)) ++ tcio (drop 1 rest)\r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n \r\nsolve :: [[Integer]] -> Integer\r\nsolve [[_,x], qs] = sum $ map (\\(q,t)->q*t) $ concat $ map fst $ unfoldr f (zip qs (repeat 1), True) where\r\n f ([],_) = Nothing\r\n f qtsc@(qts,can) = Just (qtsc, (reverse qts1,can1)) where\r\n (qts1,can1) = foldl' g ([],can) qts \r\n g (qts,can) (q,t)\r\n | can && q `mod` x == 0 = ((q `div` x, t*x):qts,True) \r\n | otherwise = (qts, False) "}, {"source_code": "import Control.Monad\nimport Data.Int\n\nreadInts :: IO [Int64]\nreadInts = map read . words <$> getLine\n\nrunSeveral :: IO () -> IO ()\nrunSeveral act = do\n t <- read <$> getLine\n replicateM_ t act\n\nmain :: IO ()\nmain = runSeveral $ do\n [_n, x] <- readInts\n a <- readInts\n let\n ct w q = case quotRem q x of\n (ans, 0) -> ct (w+1) ans\n _ -> w\n allCts = map (ct 1) a\n passes = minimum allCts\n (pref, suff) = span (> passes) allCts\n print . sum . zipWith (*) a $ (passes + 1 <$ pref) ++ (passes <$ suff)\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\n\nreadInts :: IO [Int64]\nreadInts = map read . words <$> getLine\n\nrunSeveral :: IO () -> IO ()\nrunSeveral act = do\n t <- read <$> getLine\n replicateM_ t act\n\nmain :: IO ()\nmain = runSeveral $ do\n [_n, x] <- readInts\n a <- readInts\n let\n r (ct, q) = case quotRem q x of\n (ans, 0) -> Just (x*ct, ans)\n _ -> Nothing\n clean (Just v : vs) = Just (v, vs)\n clean _ = Nothing\n a_stop = zip (repeat 1) a ++ unfoldr clean (map r a_stop)\n print . sum $ map (uncurry (*)) a_stop\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (nm:(take 1 rest)) ++ tcio (drop 1 rest)\r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n\r\nsolve :: [[Integer]] -> Integer\r\nsolve [[_,x], qs] = sum $ map (\\(q,t)->q*t) $ concat $ map fst $ unfoldr f (zip qs (repeat 1), True) where\r\n f ([],_) = Nothing\r\n f qtsc@(qts,can) = Just (qtsc, (reverse qts1,can1)) where\r\n (qts1,can1) = foldr g ([],can) qts \r\n g (q,t) (qts,can)\r\n | can && q `mod` x == 0 = ((q `div` x, t*x):qts,True) \r\n | otherwise = (qts, False)\r\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\n\nreadInts :: IO [Int64]\nreadInts = map read . words <$> getLine\n\nrunSeveral :: IO () -> IO ()\nrunSeveral act = do\n t <- read <$> getLine\n replicateM_ t act\n\nmain :: IO ()\nmain = runSeveral $ do\n [_n, x] <- readInts\n a <- readInts\n let\n r (ct, q) = case quotRem q x of\n (ans, 0) -> Just (2*ct, ans)\n _ -> Nothing\n clean (Just v : vs) = Just (v, vs)\n clean _ = Nothing\n a_stop = zip (repeat 1) a ++ unfoldr clean (map r a_stop)\n print . sum $ map (uncurry (*)) a_stop\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (guard, MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> Int64 -> [Int64] -> Int64\r\nsolve n x as = answer\r\n where\r\n xs = iterate (* x) x\r\n cnts = [fromIntegral . (+1) . length $ takeWhile (\\x -> a `mod` x == 0) xs | a <- as]\r\n answer = sum . zipWith (*) as $ scanl1 min cnts\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, x] <- B8.getLine <&> map readIntB8 . B8.words\r\n as <- B8.getLine <&> map (\\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words\r\n let answer = solve n ((fromIntegral x) :: Int64) as\r\n printf \"%lld\\n\" answer\r\n"}, {"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe (isJust)\nimport System.IO\nimport Text.Read\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, x] <- fmap (map read . words) getLine :: IO [Integer]\n a <- fmap (map read . words) getLine :: IO [Integer]\n print $ solve x a\n return ()\n\nstp :: Integer -> [Integer] -> Maybe [Integer]\nstp x a\n | null a' = Nothing\n | otherwise = Just $ map (`div` x) a'\n where a' = takeWhile (\\i -> i `mod` x == 0) a\n\nsolve :: Integer -> [Integer] -> Integer\nsolve x a =\n let\n Just allNums = sequence . takeWhile isJust . iterate (>>= stp x) $ Just a\n withPowers = zip allNums (iterate (* x) 1)\n result = sum $ map (\\ (a, b) -> sum a * b) withPowers\n in result\n"}], "src_uid": "09c8db43681d7bc72f83287897a62f3c"} {"source_code": "import Control.Applicative\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain= do\n\t getLine\n\t s<- map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (hs-ts)\n\t putStr \" \"\n\t if (hs ==ts) then print $ div (fromIntegral s1*(fromIntegral s1-1)) 2\n\t else print $ (fromIntegral s2)*(fromIntegral s1)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (mapMaybe)\nimport Text.Printf\n\nreadIntegers :: B.ByteString -> [Integer]\nreadIntegers = map fst . mapMaybe B.readInteger . B.words\n\ngetIntegers :: IO [Integer]\ngetIntegers = readIntegers <$> B.getLine\n\nmain = do\n _ <- getLine\n xs <- getIntegers\n let\n min_f = minimum xs\n max_f = maximum xs\n min_fn = fromIntegral . length . filter (==min_f) $ xs\n max_fn = fromIntegral . length . filter (==max_f) $ xs\n in printf \"%d %d\\n\" (max_f-min_f) (if min_f == max_f then min_fn*(min_fn-1)`div`2 :: Integer else min_fn*max_fn :: Integer)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain=do\n n<-getLine\n q<- map (fst.fromJust.C.readInteger) <$> C.words <$> C.getLine ::IO [Integer]\n let ma = maximum q\n let mi = minimum q\n let lma = fromIntegral $ length $ filter (==ma) q\n let lmi = fromIntegral $ length $ filter (==mi) q\n putStrLn $ intercalate \" \" $ map show [ma-mi, if ma>mi then lma*lmi else div (lma*(lma-1)) 2]\n"}, {"source_code": "import Data.List (genericLength)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words . (!!1) . lines\n\nsolve :: [Integer] -> [Integer]\nsolve bs = [ maximum bs - minimum bs, if maxbs == minbs then lenmax * (lenmax - 1) `div` 2 else lenmax * lenmin ]\n where maxbs = maximum bs; minbs = minimum bs\n lenmax = genericLength (filter (==maxbs) bs); lenmin = genericLength (filter (==minbs) bs) \n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nmain = do\n B.getLine\n fs <- fmap (group . sort . map readInteger . B.words) B.getLine\n let f = head (head fs) :: Integer\n nf = genericLength (head fs)\n l = head (last fs)\n nl = genericLength (last fs)\n putStrLn $ unwords $ map show $\n if f == l then [0, nf * (nf-1) `div` 2]\n else [l-f, nf*nl]\nreadInteger s = i where Just (i,_) = B.readInteger s\n"}, {"source_code": "import Text.Printf\n\nmain :: IO ()\nmain = do\n getLine\n bs <- fmap (map read . words) getLine :: IO [Integer]\n printf \"%d %d\\n\" (solve bs) (cnt bs)\n\n\nsolve :: [Integer] -> Integer\nsolve x = maximum x - minimum x\n\ncnt :: [Integer] -> Integer\ncnt x = if mx == mn then lmax * (pred lmax) `div` 2\n\t\t else lmax * lmin\n where\n lmax = toInteger $ length $ filter (== mx) x\n lmin = toInteger $ length $ filter (== mn) x\n mx = toInteger $ maximum x\n mn = toInteger $ minimum x\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n\nmain :: IO ()\nmain = do\n cnts <- LC.getContents\n let output = unwords . map show $ solve (readInts cnts)\n putStrLn output\n\nsolve :: [Int] -> [Integer]\nsolve (n:a) =\n let\n b = L.sort a\n p = head b\n q = last b\n in\n if p == q\n then\n [0, toInteger n * toInteger (n-1) `div` 2]\n else\n [toInteger (q-p), (count p b) * (count q b)]\n\ncount :: Int -> [Int] -> Integer\ncount x xs = toInteger $ foldl (\\acc i -> acc + (if i == x then 1 else 0)) 0 xs\n\n-------------------------------------------------------------------------------\n\nreadInt :: LC.ByteString -> Int\nreadInt = LC.foldl' (\\x c -> 10 * x + fromEnum c - 48) 0\n\nreadInts :: LC.ByteString -> [Int]\nreadInts str = map readInt $ LC.words str\n"}, {"source_code": "main :: IO ()\nmain = interact $ display . solve . fmap read . tail .words\n\ndisplay :: (Show a) => (a, a) -> String\ndisplay (a, b) = show a ++ \" \" ++ show b\n\nsolve :: [Integer] -> (Integer, Integer)\nsolve xs\n | mn == mx = (0, (n * (n - 1)) `div` 2)\n | otherwise = (mx - mn, mnc * mxc)\n where mn = minimum xs\n mx = maximum xs\n mnc = toInteger $ length $ filter (== mn) xs\n mxc = toInteger $ length $ filter (== mx) xs\n n = toInteger $ length xs\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (group, sort)\n\n\nreadIntegers :: String -> [Integer]\nreadIntegers = map read . words\n\nsolve :: [Integer] -> [Integer]\nsolve xs = let n = fromIntegral $ length xs\n (a,b) = (minimum xs,maximum xs)\n [c,d] = map (fromIntegral . length . (`filter` xs) . (==)) [a,b]\n count = if a == b\n then n*(n - 1) `div` 2\n else c*d\n in [b - a, count]\n\nmain :: IO ()\nmain = putStrLn . toStr . solve . readIntegers =<< (getLine >> getLine)\n where toStr = unwords . map show"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . words =<< getContents\n\noutput :: (Int, Integer) -> IO()\noutput (a, b) = putStrLn ((show a) ++ \" \" ++ (show b))\n\nsolve :: [Int] -> (Int, Integer)\nsolve (n:b) = let ni = toInteger n\n low = minimum b\n high = maximum b\n lowNum = toInteger $ length (filter (== low) b)\n highNum = toInteger $ length (filter (== high) b)\n in if high == low then (0, (div (ni * (ni - 1)) 2))\n else ((high - low), lowNum * highNum)\n"}, {"source_code": "import Data.List\nimport Data.Binary\n--import qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport Text.Show\n\nmain = interact $ unwords . map show . getAns . tail . map fst . mapMaybe B.readInt . B.words . B.pack\n\ngetAns :: [Int] -> [Integer]\ngetAns xs = let ts = group $ sort xs;\n\t\t\t\tas = head ts;\n\t\t\t\tbs = last ts;\n\t\t\t\tla = toInteger $ length as;\n\t\t\t\tlb = toInteger $ length bs;\n\t\t\t\tva = head as;\n\t\t\t\tvb = head bs;\n\t\t\tin [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]\n"}, {"source_code": "import Data.List\nimport Data.Binary\n--import qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport Text.Show\n\nmain = B.interact $ B.pack . unwords . map show . getAns . tail . map fst . mapMaybe B.readInt . B.words\n\ngetAns :: [Int] -> [Integer]\ngetAns xs = let ts = group $ sort xs;\n\t\t\t\tas = head ts;\n\t\t\t\tbs = last ts;\n\t\t\t\tla = toInteger $ length as;\n\t\t\t\tlb = toInteger $ length bs;\n\t\t\t\tva = head as;\n\t\t\t\tvb = head bs;\n\t\t\tin [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]\n"}, {"source_code": "import Data.List\nimport Data.Binary\nimport qualified Data.ByteString.Char8 as B\n--import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport Text.Show\n\nmain = interact $ unwords . map show . getAns . tail . map fst . mapMaybe B.readInt . B.words . B.pack\n\ngetAns :: [Int] -> [Integer]\ngetAns xs = let ts = group $ sort xs;\n\t\t\t\tas = head ts;\n\t\t\t\tbs = last ts;\n\t\t\t\tla = toInteger $ length as;\n\t\t\t\tlb = toInteger $ length bs;\n\t\t\t\tva = head as;\n\t\t\t\tvb = head bs;\n\t\t\tin [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]\n"}, {"source_code": "import Data.List\nimport Data.Binary\n--import qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport Text.Show\n\nmain = B.interact $ B.unwords . map (B.pack . show) . getAns . tail . map fst . mapMaybe B.readInt . B.words\n\ngetAns :: [Int] -> [Integer]\ngetAns xs = let ts = group $ sort xs;\n\t\t\t\tas = head ts;\n\t\t\t\tbs = last ts;\n\t\t\t\tla = toInteger $ length as;\n\t\t\t\tlb = toInteger $ length bs;\n\t\t\t\tva = head as;\n\t\t\t\tvb = head bs;\n\t\t\tin [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- getInts\n\n let\n mi = minimum xs\n ma = maximum xs\n c1 = genericLength $ filter (== mi) xs :: Int64\n c2 = genericLength $ filter (== ma) xs\n c = if mi == ma then c1*(c1-1)`div`2 else c1*c2\n\n putStrLn $ show (ma-mi) ++ \" \" ++ show c\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\n-> (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve xs = let s =group $ sort xs; \n mis=head s; \n mas = last s; \n mi=head mis; \n ma=head mas; \n nmi=length mis; \n nma=length mas in if tail s == [] then putStrLn ( \"0 \" ++ show (fromIntegral nmi*(fromIntegral nmi-1)`div`2)) else putStrLn $ unwords $ map show [ma-mi, fromIntegral nmi* fromIntegral nma] "}], "negative_code": [{"source_code": "import Data.List\n\nmain = interact $ unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Integer]\nsolve (_:a) =\n let\n b = sort a\n p = head b\n q = last b\n in\n [toInteger (q-p), (count p b) * (count q b)]\n\ncount :: Int -> [Int] -> Integer\ncount x xs = toInteger $ foldl (\\acc i -> acc + (if i == x then 1 else 0)) 0 xs"}, {"source_code": "import Data.List\n\nmain = interact $ unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (_:a) =\n let\n b = sort a\n p = head b\n q = last b\n in\n [q-p, (count p b) * (count q b)]\n\ncount :: Int -> [Int] -> Int\ncount x xs = foldl (\\acc i -> acc + (if i == x then 1 else 0)) 0 xs"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (group, sort)\n\n\nmain :: IO ()\nmain = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)\n where solve xs = let q = [(head i, length i) | i <- group $ sort xs]\n n = length xs\n ((a, b), (c, d)) = (head q, last q)\n sec | b == d = n*(n - 1) `div` 2\n | otherwise = b*d\n in [c - a, sec]\n toStr = unwords . map show"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (elemIndices)\n\n\nmain :: IO ()\nmain = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)\n where solve xs = let n = length xs\n (a,b) = (minimum xs, maximum xs)\n [c,d] = map (length . (`elemIndices` xs)) [a,b]\n count = if a == b then n*(n - 1) `div` 2 else c*d\n in [b - a, count]\n toStr = unwords . map show"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (group, sort)\n\n\nmain :: IO ()\nmain = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)\n where solve xs = let q = [(head i, length i) | i <- group $ sort xs]\n ((a, b), (c, d)) = (head q, last q)\n in [c - a, b*d]\n toStr = unwords . map show"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (group, sort)\n\n\nmain :: IO ()\nmain = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)\n where solve xs = let q = [(head i, length i) | i <- group $ sort xs]\n n = length xs\n ((a, b), (c, d)) = (head q, last q)\n sec | a == c = n*(n - 1) `div` 2\n | otherwise = b*d\n in [c - a, sec]\n toStr = unwords . map show"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (elemIndices)\n\n\nreadIntegers :: String -> [Integer]\nreadIntegers = map read . words\n\nsolve :: [Integer] -> [Integer]\nsolve xs = let n = length xs\n (a,b) = (minimum xs, maximum xs)\n [c,d] = map (length . (`elemIndices` xs)) [a,b]\n count = if a == b then n*(n - 1) `div` 2 else c*d\n in [b - a, fromIntegral count]\n\nmain :: IO ()\nmain = putStrLn . toStr . solve . readIntegers =<< (getLine >> getLine)\n where toStr = unwords . map show"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . tail . map read . words =<< getContents\n\noutput :: (Integer, Integer) -> IO()\noutput (a, b) = putStrLn ((show a) ++ \" \" ++ (show b))\n\nsolve :: [Integer] -> (Integer, Integer)\nsolve b = let sb = sort b\n low = head sb\n high = last sb\n lowNum = fromIntegral $ length [x | x <- b, x == low]\n highNum = fromIntegral $ length [x | x <- b, x == high]\n in ((high - low), lowNum * highNum)\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . words =<< getContents\n\noutput :: (Int, Integer) -> IO()\noutput (a, b) = putStrLn ((show a) ++ \" \" ++ (show b))\n\nsolve :: [Int] -> (Int, Integer)\nsolve (n:b) = let sb = sort b\n low = head sb\n high = last sb\n lowNum = fromIntegral $ length [x | x <- b, x == low]\n highNum = fromIntegral $ length [x | x <- b, x == high]\n in if high == low then (0, fromIntegral (div (n * (n - 1)) 2))\n else ((high - low), lowNum * highNum)\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . words =<< getContents\n\noutput :: (Int, Integer) -> IO()\noutput (a, b) = putStrLn ((show a) ++ \" \" ++ (show b))\n\nsolve :: [Int] -> (Int, Integer)\nsolve (n:b) = let sb = sort b\n low = head sb\n high = last sb\n lowNum = toInteger $ length [x | x <- b, x == low]\n highNum = toInteger $ length [x | x <- b, x == high]\n in if high == low then (0, fromIntegral (div (n * (n - 1)) 2))\n else ((high - low), lowNum * highNum)\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ unwords . map show . getAns . tail . map read . words\n\ngetAns :: [Int] -> [Int]\ngetAns xs = let ts = group $ sort xs;\n\t\t\t\tas = head ts;\n\t\t\t\tbs = last ts;\n\t\t\tin [head bs - head as, length as * length bs]\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ unwords . map show . getAns . tail . map read . words\n\ngetAns :: [Int] -> [Int]\ngetAns xs = let ts = group $ sort xs;\n\t\t\t\tas = head ts;\n\t\t\t\tbs = last ts;\n\t\t\tin [head bs - head as, if (head bs == head as) then (length as) * (length as - 1) `div` 2 else length as * length bs]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- getInts\n\n let\n mi = minimum xs\n ma = maximum xs\n c1 = genericLength $ filter (== mi) xs :: Int64\n c2 = genericLength $ filter (== ma) xs\n\n putStrLn $ show (ma-mi) ++ \" \" ++ show (c1*c2)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- getInts\n\n let\n mi = minimum xs\n ma = maximum xs\n c1 = length $ filter (== mi) xs\n c2 = length $ filter (== ma) xs\n\n putStrLn $ show (ma-mi) ++ \" \" ++ show (c1*c2)\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\n-> (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve xs = let s =group $ sort xs; \n mis=head s; \n mas = last s; \n mi=head mis; \n ma=head mas; \n nmi=length mis; \n nma=length mas in putStrLn $ unwords $ map show [ma-mi, fromIntegral nmi* fromIntegral nma] "}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\n-> (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve xs = let s =group $ sort xs; \n mis=head s; \n mas = last s; \n mi=head mis; \n ma=head mas; \n nmi=length mis; \n nma=length mas in if tail s == [] then putStrLn \"0 1\" else putStrLn $ unwords $ map show [ma-mi, fromIntegral nmi* fromIntegral nma] "}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (mapMaybe)\nimport Text.Printf\n\nreadIntegers :: B.ByteString -> [Integer]\nreadIntegers = map fst . mapMaybe B.readInteger . B.words\n\ngetIntegers :: IO [Integer]\ngetIntegers = readIntegers <$> B.getLine\n\nmain = do\n _ <- getLine\n xs <- getIntegers\n let\n min_f = minimum xs\n max_f = maximum xs\n min_fn = fromIntegral . length . filter (==min_f) $ xs\n max_fn = fromIntegral . length . filter (==max_f) $ xs\n in printf \"%d %d\\n\" (max_f-min_f) (if min_fn == max_fn then min_fn else min_fn*max_fn :: Integer)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (mapMaybe)\nimport Text.Printf\n\nreadIntegers :: B.ByteString -> [Integer]\nreadIntegers = map fst . mapMaybe B.readInteger . B.words\n\ngetIntegers :: IO [Integer]\ngetIntegers = readIntegers <$> B.getLine\n\nmain = do\n _ <- getLine\n xs <- getIntegers\n let\n min_f = minimum xs\n max_f = maximum xs\n min_fn = fromIntegral . length . filter (==min_f) $ xs\n max_fn = fromIntegral . length . filter (==max_f) $ xs\n in printf \"%d %d\\n\" (max_f-min_f) (min_fn*max_fn :: Integer)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (mapMaybe)\nimport Text.Printf\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map fst . mapMaybe B.readInt . B.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> B.getLine\n\nmain = do\n _ <- getLine\n xs <- getInts\n let\n min_f = minimum xs\n max_f = maximum xs\n min_fn = fromIntegral . length . filter (==min_f) $ xs\n max_fn = fromIntegral . length . filter (==max_f) $ xs\n in printf \"%d %d\\n\" (max_f-min_f) (min_fn*max_fn :: Integer)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (mapMaybe)\nimport Text.Printf\n\nreadIntegers :: B.ByteString -> [Integer]\nreadIntegers = map fst . mapMaybe B.readInteger . B.words\n\ngetIntegers :: IO [Integer]\ngetIntegers = readIntegers <$> B.getLine\n\nmain = do\n _ <- getLine\n xs <- getIntegers\n let\n min_f = minimum xs\n max_f = maximum xs\n min_fn = fromIntegral . length . filter (==min_f) $ xs\n max_fn = fromIntegral . length . filter (==max_f) $ xs\n in printf \"%d %d\\n\" (max_f-min_f) (if min_fn == max_fn then min_fn*(min_fn-1)`div`2 :: Integer else min_fn*max_fn :: Integer)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain=do\n n<-getLine\n q<- map read <$> words <$> getLine ::IO [Integer]\n let ma = maximum q\n let mi = minimum q\n let lma = fromIntegral $ length $ filter (==ma) q\n let lmi = fromIntegral $ length $ filter (==mi) q\n putStrLn $ intercalate \" \" $ map show [ma-mi, if ma>mi then lma*lmi else 1]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain=do\n n<-getLine\n q<- map read <$> words <$> getLine ::IO [Integer]\n let ma = maximum q\n let mi = minimum q\n let lma = fromIntegral $ length $ filter (==ma) q\n let lmi = fromIntegral $ length $ filter (==mi) q\n putStrLn $ intercalate \" \" $ map show [ma-mi, lma*lmi]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain=do\n n<-getLine\n q<- map read <$> words <$> getLine ::IO [Integer]\n let ma = maximum q\n let mi = minimum q\n let lma = fromIntegral $ length $ filter (==ma) q\n let lmi = fromIntegral $ length $ filter (==mi) q\n putStrLn $ intercalate \" \" $ map show [ma-mi, if lma>lmi then lma*lmi else lma]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain=do\n n<-getLine\n q<- map read <$> words <$> getLine ::IO [Integer]\n let ma = maximum q\n let mi = minimum q\n let lma = fromIntegral $ length $ filter (==ma) q\n let lmi = fromIntegral $ length $ filter (==mi) q\n putStrLn $ intercalate \" \" $ map show [ma-mi, if ma>mi then lma*lmi else lma]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain=do\n n<-getLine\n q<- map read <$> words <$> getLine ::IO [Int]\n let ma = maximum q\n let mi = minimum q\n let lma = length $ filter (==ma) q\n let lmi = length $ filter (==mi) q\n putStrLn $ intercalate \" \" $ map show [ma-mi, lma*lmi]\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> [Int]\nsolve bs = [ maximum bs - minimum bs, length (filter (==maxbs) bs) * length (filter (==minbs) bs) ]\n where maxbs = maximum bs; minbs = minimum bs\n"}, {"source_code": "import Data.List (genericLength)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words . (!!1) . lines\n\nsolve :: [Integer] -> [Integer]\nsolve bs = [ maximum bs - minimum bs, genericLength (filter (==maxbs) bs) * genericLength (filter (==minbs) bs) ]\n where maxbs = maximum bs; minbs = minimum bs\n"}, {"source_code": "import Data.List\nmain = do\n getLine\n fs <- fmap (group . sort . map read . words) getLine\n let f = head (head fs)\n nf = length (head fs)\n l = head (last fs)\n nl = length (last fs)\n putStrLn $ unwords $ map show $\n if f == l then [0, nf * (nf-1) `div` 2]\n else [l-f, nf*nl]"}, {"source_code": "import Control.Applicative\nimport Data.List \n\nmain= do\n\t getLine\n\t s<- map read. words <$> getLine::IO [Int]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (ts-hs)\n\t putStr \" \"\n\t print $ s2*s1\n"}, {"source_code": "import Control.Applicative\nimport Data.List \n\nmain= do\n\t getLine\n\t s<- sort. map read. words <$> getLine::IO [Integer]\n\t let hs = head s\n\t let ts = last s\n\t let s1 = length $ takeWhile (==hs) s\n\t let s2 = length $ takeWhile (==ts) (reverse s)\n\t putStr $ show (ts-hs)\n\t putStr \" \"\n\t print $ s2*s1\n"}, {"source_code": "import Control.Applicative\nimport Data.List \n\nmain= do\n\t getLine\n\t s<- map read. words <$> getLine::IO [Integer]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (hs-ts)\n\t putStr \" \"\n\t print $ (fromIntegral s2)*(fromIntegral s1)\n"}, {"source_code": "import Control.Applicative\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain= do\n\t getLine\n\t s<- map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (hs-ts)\n\t putStr \" \"\n\t if (hs ==ts) then print $ div (s1*(s1-1)) 2\n\t else print $ (fromIntegral s2)*(fromIntegral s1)\n"}, {"source_code": "import Control.Applicative\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain= do\n\t getLine\n\t s<- map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (hs-ts)\n\t putStr \" \"\n\t if (hs ==ts) then print 1\n\t else print $ (fromIntegral s2)*(fromIntegral s1)\n"}, {"source_code": "import Control.Applicative\nimport Data.List \n\nmain= do\n\t getLine\n\t s<- sort. map read. words <$> getLine::IO [Int]\n\t let hs = head s\n\t let ts = last s\n\t let s1 = length $ takeWhile (==hs) s\n\t let s2 = length $ takeWhile (==ts) (reverse s)\n\t putStr $ show (ts-hs)\n\t putStr \" \"\n\t print $ s2*s1\n"}, {"source_code": "import Control.Applicative\nimport Data.List \n\nmain= do\n\t getLine\n\t s<- map read. words <$> getLine::IO [Int]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (hs-ts)\n\t putStr \" \"\n\t print $ s2*s1\n"}, {"source_code": "import Control.Applicative\nimport Data.List \n\nmain= do\n\t getLine\n\t s<- map read. words <$> getLine::IO [Integer]\n\t let hs = maximum s\n\t let ts = minimum s\n\t let s1 = length $ filter (==hs) s\n\t let s2 = length $ filter (==ts) s\n\t putStr $ show (hs-ts)\n\t putStr \" \"\n\t print $ s2*s1\n"}, {"source_code": "import Text.Printf\n\nmain :: IO ()\nmain = do\n getLine\n bs <- fmap (map read . words) getLine :: IO [Integer]\n printf \"%d %d\\n\" (solve bs) (cnt bs)\n\n\nsolve :: [Integer] -> Integer\nsolve x = maximum x - minimum x\n\ncnt :: [Integer] -> Integer\ncnt x = if mx > mn then toInteger $ lmax * lmin\n\t\t else mx * (pred mx) `div` 2\n where\n lmax = length $ filter (== mx) x\n lmin = length $ filter (== mn) x\n mx = maximum x\n mn = minimum x\n"}, {"source_code": "import Text.Printf\n\nmain :: IO ()\nmain = do\n getLine\n bs <- fmap (map read . words) getLine :: IO [Integer]\n printf \"%d %d\\n\" (solve bs) (cnt bs)\n\n\nsolve :: [Integer] -> Integer\nsolve x = maximum x - minimum x\n\ncnt :: [Integer] -> Integer\ncnt x = if mx == mn then mx * (pred mx) `div` 2\n\t\t else lmax * lmin\n where\n lmax = toInteger $ length $ filter (== mx) x\n lmin = toInteger $ length $ filter (== mn) x\n mx = toInteger $ maximum x\n mn = toInteger $ minimum x\n"}, {"source_code": "main :: IO ()\nmain = interact $ display . solve . fmap read . tail .words\n\ndisplay :: (Show a) => (a, a) -> String\ndisplay (a, b) = show a ++ \" \" ++ show b\n\nsolve :: [Integer] -> (Integer, Integer)\nsolve xs\n | mn == mx = (mn, (n * (n - 1)) `div` 2)\n | otherwise = (mx - mn, mnc * mxc)\n where mn = minimum xs\n mx = maximum xs\n mnc = toInteger $ length $ filter (== mn) xs\n mxc = toInteger $ length $ filter (== mx) xs\n n = toInteger $ length xs\n"}], "src_uid": "eb2d1072c5308d9ef686315a122d9d3c"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, l] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n print $ solve l as\n\nsolve :: Integer -> [Integer] -> Double\nsolve l as = drive 0 1 as' (fromIntegral l) 1 (reverse as')\n where\n as' = fromIntegral <$> as\n\ndrive :: (Ord a, Fractional a) => a -> a -> [a] -> a -> a -> [a] -> a\ndrive p r (a : as) q s (b : bs)\n | meet <= pt && meet <= qt = meet\n | pt <= qt = pt + drive a (r + 1) as (q - s * pt) s (b : bs)\n | otherwise = qt + drive (p + qt * r) r (a : as) b (s + 1) bs\n where\n meet = (q - p) / (r + s)\n pt = (a - p) / r\n qt = (q - b) / s\ndrive p r _ q s _ = (q - p) / (r + s)\n", "positive_code": [{"source_code": "import Control.Monad\n\nsteps :: Fractional t => [Int] -> [t]\nsteps = let\n go s p li = case li of\n a1 : tli@(a2 : _) -> p : go (s+1) (p + fromIntegral (a2 - a1) / s) tli\n _ -> p <$ li\n in go 1 0\n\nsolve :: (Ord t, Fractional t) => Int -> [Int] -> t\nsolve len a = let\n sa = 0 : (a ++ [len])\n ra = reverse $ map (len -) sa\n st = steps sa\n rt = reverse $ steps ra\n (before, after) = span (uncurry (<)) $ zip st rt\n (prevs, prevr) = last before\n (nexts, nextr) = head after\n slop = (nextr - nexts) - (prevr - prevs)\n coord = (prevs - prevr) / slop\n in prevs + (nexts - prevs) * coord\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, len] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n --let ans = solve len a :: Rational\n --print (fromRational ans :: Double)\n print (solve len a :: Double)\n"}], "negative_code": [], "src_uid": "700cfc8d20794ca38d73ccff31e5292c"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\n_find n [] = \"YES\"\n_find n (a:as)\n | n == a || n == (7-a)= \"NO\"\n | otherwise = _find n as\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\t_n <- getLine\n\tarrT <- getContents\n\tlet\n\t\tn = read _n :: Int\n\t\tarr = map (\\x -> read x :: Int).words $ arrT\n\tputStrLn $_find n arr\n", "positive_code": [{"source_code": "possible :: Int -> [(Int,Int)] -> Bool\npossible x [] = True\npossible x ((y,z):xs) = if x == y || x == 7 - y || x == z || x == 7 - z then False else possible x xs\n\nmain :: IO ()\nmain = do str <- getLine\n let n = read str\n str <- getLine\n let x = read str\n getLine\n l <- loop (n-1)\n putStrLn (if possible x l then \"YES\" else \"NO\")\n where\n loop 0 = return []\n loop n = do str <- getLine\n xs <- loop (n-1)\n let [a,b] = map read . words $ str\n return ((a,b):xs)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nt [] = []\nt (a:b:s) = (a,b) : t s\n\nsolve x [] = True\nsolve x ((a, b) : s) = let\n c = 7 - a\n d = 7 - b\n in if (a == x) || (b == x) || (c == x) || (d == x)\n then False\n else solve x s\n\nmain = do\n n <- read <$> getLine :: IO Int\n x <- read <$> getLine :: IO Int\n a <- t <$> map read <$> (words <$> getContents) :: IO [(Int, Int)]\n putStrLn $ if solve x a then \"YES\" else \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = interact $ (\\(_:[x]:xs) -> testcase x xs) . map (map read . words) . lines\n\ntestcase :: Int -> [[Int]] -> String\ntestcase b [] = \"YES\"\ntestcase b ([x,y]:xs) | (7-b) `elem` [x,y,7-x,7-y] = \"NO\"\n\t\t\t\t\t\t\t | otherwise = testcase (7-b) xs\n"}, {"source_code": "import Control.Monad (replicateM)\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: Int -> [(Int, Int)] -> Bool\nsolve x ax = all (\\(a, b) -> a + x /= 7 && b + x /= 7 && a /= x && b /= x) ax\n\nreadPair :: IO (Int, Int)\nreadPair = do\n [x, y] <- fmap (map read . words) getLine\n return (x, y)\n\nmain :: IO ()\nmain = do\n n <- readLn\n x <- readLn\n ax <- replicateM n readPair\n putStrLn . (\"YES\" \"NO\") . solve x $ ax"}, {"source_code": "main=interact$f.map read.words\nf(_:x:y)|all(`notElem`[x,7-x])y=\"YES\"|0<1=\"NO\""}, {"source_code": "import Data.List\nf x|x>3=7-x|1>0=x\nq x|x>2=\"NO\"|1>0=\"YES\"\nmain=interact$q.length.group.sort.map f.drop 2.map read.words"}], "negative_code": [{"source_code": "\nimport Control.Monad (replicateM)\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: Int -> [(Int, Int)] -> Bool\nsolve x ax = all (\\(a, b) -> a + x /= 7 && b + x /= 7) ax\n\nreadPair :: IO (Int, Int)\nreadPair = do\n [x, y] <- fmap (map read . words) getLine\n return (x, y)\n\nmain :: IO ()\nmain = do\n n <- readLn\n x <- readLn\n ax <- replicateM n readPair\n putStrLn . (\"YES\" \"NO\") . solve x $ ax"}, {"source_code": "import Data.List\nf x|x>3=x-3|1>0=x\nq x|x>2=\"NO\"|1>0=\"YES\"\nmain=interact$q.length.group.sort.map f.drop 2.map read.words"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\n_find n [] = \"YES\"\n_find n (a:as)\n | n == a = \"NO\"\n | otherwise = _find n as\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\t_n <- getLine\n\tarrT <- getContents\n\tlet\n\t\tn = read _n :: Int\n\t\tarr = map (\\x -> read x :: Int).words $ arrT\n\tputStrLn $_find n arr\n"}], "src_uid": "2d6a1202139e1f77f32377224e1fe752"} {"source_code": "-- la la la no testing at all\nimport Data.List\nimport Data.Char\nmain :: IO ()\nmain = do\n xs <- fmap (map (read :: String -> Int) . words) getLine\n cs <- getLine\n print . sum . map ((xs !!) . subtract 1 . digitToInt) $ cs", "positive_code": [{"source_code": "module Main\n where\n\nimport System.IO\n\nmain = do\n first <- getLine\n squares <- getLine\n print $ solve (parsePoints first) squares\n where\n parsePoints =\n map read . words\n\n solve :: [Int] -> String -> Int\n solve _ \"\" =\n 0\n solve points (x : xs) =\n (points !! (read [x] - 1)) + solve points xs\n"}, {"source_code": "import Data.Char\n\nsol :: [Int] -> [Char] -> Int\nsol cs is = sum (map (\\i -> cs!!((digitToInt i) - 1)) is)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nreadInps :: IO [Char]\nreadInps = getLine\n\nmain :: IO ()\nmain = do\n cost <- readInts\n inps <- readInps\n print(sol cost inps)\n"}, {"source_code": "import Data.Char\n\nsol :: [Int] -> String -> Int\nsol cs is = sum (map (\\i -> cs!!((digitToInt i) - 1)) is)\n\nmain :: IO ()\nmain = do\n cost <- fmap (map read.words) getLine\n inps <- getLine\n print(sol cost inps)\n"}, {"source_code": "data Tree a = Null | Node (Tree a) a (Tree a)\n\ndata Array a = Array Int Int (Tree a)\n\nnewArray l r v | l <= r = Array l r (newArray' l r)\n where newArray' l r | l <= r = Node (newArray' l (m - 1)) v (newArray' (m + 1) r)\n where m = div (l + r) 2\n newArray' _ _ = Null\n\nwriteArray (Array l r rt) i ai = Array l r (writeArray' l r rt)\n where writeArray' l r (Node lc val rc) | m > i = Node (writeArray' l (m - 1) lc) val rc\n where m = div (l + r) 2\n writeArray' l r (Node lc val rc) | m < i = Node lc val (writeArray' (m + 1) r rc)\n where m = div (l + r) 2\n writeArray' _ _ (Node lc _ rc) = Node lc ai rc\n\nreadArray (Array l r rt) i = readArray' l r rt\n where readArray' l r (Node lc _ _) | m > i = readArray' l (m - 1) lc\n where m = div (l + r) 2\n readArray' l r (Node _ _ rc) | m < i = readArray' (m + 1) r rc\n where m = div (l + r) 2\n readArray' l r (Node _ val _) = val\n\nmain = do\n as <- getLine\n s <- getLine\n let f x '1' = x + a1\n f x '2' = x + a2\n f x '3' = x + a3\n f x '4' = x + a4\n [a1,a2,a3,a4] = map read $ words as :: [Int]\n putStrLn $ show $ foldl f 0 s\n"}, {"source_code": "import Data.Char\n\nmain :: IO()\nmain = print . solve . words =<< getContents\n\nsolve :: [String] -> Int\nsolve (a:b:c:d:s:_) = solve' (map read [a, b, c, d]) s\n\nsolve' :: [Int] -> String -> Int\nsolve' _ \"\" = 0\nsolve' a (s:ss) = a !! (ord s - ord '1') + solve' a ss\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n xs <- map read . words <$> getLine\n s <- getLine\n\n print $ sum $ map ((xs!!) . (flip (-) 1) . digitToInt) s\n"}, {"source_code": "import Data.List\n\nmain = do\n (a1:a2:a3:a4:_) <- fmap (map read . words) getLine\n touches <- getLine\n let go '1' = a1\n go '2' = a2\n go '3' = a3\n go '4' = a4\n go _ = (0::Int)\n print $ sum $ map go touches\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInteger x\nsomeFunc::IO()\nsomeFunc = solve=<C.getLine)\nslv1 [ns,ms] = sum $ map (uncurry (*).((!!) ns.fromIntegral.flip (-) 1.head&&&fromIntegral.length)) $ group $ sort ms\nsolve [ns,ms] = print $ slv1 [map rIn $ C.words ns,map rIn $ C.words$ C.intersperse ' ' ms]"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nmain = readInput >>= putStrLn . show . calc\n\nreadInput :: IO ([Int], String)\nreadInput = liftM2 toTuple getLine getLine\n where toTuple a b = (map read $ words a, b)\n \ncalc (cals, game) = foldr calc' 0 game\n where calc' c ans = cals !! pos + ans\n where pos = digitToInt c - 1"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nmain = readInput >>= putStrLn . show . calc\n\nreadInput :: IO ([Int], String)\nreadInput = liftM2 toTuple getLine getLine\n where toTuple a b = (map read $ words a, b)\n \ncalc (cals, game) = calc' cals game\n where calc' cals [] = 0\n calc' cals (g:gs) = cals !! pos + calc' cals gs\n where pos = digitToInt g - 1"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nmain :: IO ()\nmain = do\n as <- (map readB8Int . B8.words) <$> B8.getLine\n -- line <- B8.getLine\n -- let is = B8.groupBy (\\x y -> False) line\n -- print is\n is <- (map readB8Int . B8.groupBy (\\x y -> False) . head . B8.words) <$> B8.getLine\n let answer = sum . map (\\i -> as !! (i - 1)) $ is\n printf \"%d\\n\" answer"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nprocess a | even s = s\n | otherwise = s-m\n where s = sum a\n m = minimum $ filter odd a\n\nmain=do\n\n a<- map read <$> words <$> getLine ::IO [Int]\n b<- map digitToInt <$> getLine ::IO [Int]\n print $ sum $ map (\\z->a!!(z-1)) b\n"}, {"source_code": "import Data.Char (ord)\n\nmain :: IO ()\nmain = getContents >>= print . solve . lines\n\nsolve :: [String] -> Int\nsolve [bs, ss] = sum $ map ((as !!) . subtract (ord '1') . ord) ss where as = map read (words bs)\nsolve _ = undefined\n"}, {"source_code": "import Data.Char (digitToInt)\n\nmain :: IO ()\nmain = getContents >>= print . solve . lines\n\nsolve :: [String] -> Int\nsolve [bs, ss] = sum $ map ((as !!) . pred . digitToInt) ss where as = map read (words bs)\nsolve _ = undefined\n"}, {"source_code": "import Data.Char (digitToInt)\nmain = do\n cs <- fmap ((0:) . map read . words) getLine\n print . sum . map ((cs!!) . digitToInt) =<< getLine\n"}, {"source_code": "import Data.Char\nmain = do\n as <- fmap (map read . words) getLine\n s <- getLine\n print . sum . map (\\c -> as !! (digitToInt c - 1)) $ s\n"}, {"source_code": "import Data.Char\n\nsolve :: [Int] -> String -> Int\nsolve a [] = 0\nsolve a (b:c) = (a !! (ord(b) - ord('1'))) + (solve a c)\n\n\nmain = do\n line <- getLine\n s <- getLine\n print $ solve (map read $ words line) s\n \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\n \n\nmain= do\n\ts<- map read .words <$>getLine ::IO [Int]\n\tt<- map read. words. intersperse ' '<$> getLine::IO [Int]\n\tlet s1 = 0:s\n\tprint $ sum $ map (s1!!) t\n\t"}, {"source_code": "--ghc 7.10\n\nimport Data.Array((!), listArray)\nimport Data.Char(digitToInt)\n\nsumCalory :: (Num a) => [a] -> [Int] -> a\nsumCalory a s = sum (map (\\x -> a' ! x) s)\n where\n n = length a\n a' = listArray (1,n) a\n\nmain = do\n aStr <- getLine\n let a = map read . words $ aStr :: [Int]\n sStr <- getLine\n let s = map digitToInt $ sStr\n print $ sumCalory a s"}, {"source_code": "-- Codeforces Round #247 (Div. 2) - Problem A: Black Square (https://codeforces.com/problemset/problem/431/A)\nparseInput input = (as, s) where\n ls = lines input\n as = map read $ words $ head ls :: [Int]\n s = ls !! 1\n\nsolve as s = sum $ zipWith (*) as bs where\n q1 = length $ filter (=='1') s\n q2 = length $ filter (=='2') s\n q3 = length $ filter (=='3') s\n q4 = length $ filter (=='4') s\n bs = [q1, q2, q3, q4]\n\nmain = do\n input <- getContents \n let (as, s) = parseInput input\n print $ solve as s\n"}], "negative_code": [], "src_uid": "db9065d975878227a749083f0036a169"} {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | ((all (== 0) as) && (n == c)) = -1\n | ((all (== 0) as) || (n > c) || (maxX == 0) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (c, r2) = readInteger r1\n let (as, bs) = readMany readInteger r2 [] []\n print (solve n c as bs)\n where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (xi, r) -> readMany readf r ys (xi : xs)\n Nothing -> (xs, ys)\n{-\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n-}\n", "positive_code": [{"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | ((all (== 0) as) && (n == c)) = -1\n | ((all (== 0) as) || (n > c) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (c, r2) = readInteger r1\n let (as, bs) = readMany readInteger r2 [] []\n print (solve n c as bs)\n where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (xi, r) -> readMany readf r ys (xi : xs)\n Nothing -> (xs, ys)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | ((all (\\a -> a == 0) as) && (n == c)) = -1\n | ((all (\\a -> a == 0) as) || (n > c) || (maxX == 0) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (c, r2) = readInteger r1\n let (as, bs, _) = readAs readInteger r2\n print (solve n c as bs)\n where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | ((all (== 0) as) && (n == c)) = -1\n | ((all (== 0) as) || (n > c) || (maxX == 0) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (c, r2) = readInteger r1\n let (as, bs) = readMany readInteger r2 [] []\n print (solve n c as bs)\n where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (xi, r) -> readMany readf r ys (xi : xs)\n Nothing -> (xs, ys)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | ((all (== 0) as) && (n == c)) = -1\n | ((all (== 0) as) || (n > c) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (c, r2) = readInteger r1\n let (as, bs) = readMany readInteger r2 [] []\n print (solve n c as bs)\n where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (xi, r) -> readMany readf r ys (xi : xs)\n Nothing -> (xs, ys)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX :: [(Integer, Integer)] -> Integer -> Integer\ndaysX abs x = foldl sumDiv 0 abs\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nbinSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo\n | (lo == hi) = 0\n | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi\n | otherwise = binSearchMaxX n c abs lo (mid - 1)\n where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2\n\n\nsolve n c as bs | (n > c) = 0 \n | otherwise = \n if (all (\\a -> a == 0) as) then special n c\n else if (maxX == 0) then 0\n else maxX - minX + 1\n where m = maximum bs\n uBound = (c - n) * m + m - 1\n abs = zip as bs\n maxX = binSearchMaxX n c abs 0 uBound\n minX = binSearchMinX n c abs 1 maxX\n\nspecial n c = if (n == c) then -1\n else 0\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | (n > c) = 0 \n | ((all (\\a -> a == 0) as) && (n == c)) = -1\n | (all (\\a -> a == 0) as) = 0\n | ((maxX == 0) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | ((all (== 0) as) && (n == c)) = -1\n | ((all (== 0) as) || (n > c) || (maxX < minX)) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1 -- c-n = Sum(x*ai div bi) >= x div m -> x<= (x div m)*m + (m-1) <= (c-n)*m+(m-1)\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 (maxX + 1)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (c, r2) = readInteger r1\n let (as, bs) = readMany readInteger r2 [] []\n print (solve n c as bs)\n where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s xs ys = case readf s of\n Just (xi, r) -> readMany readf r ys (xi : xs)\n Nothing -> (xs, ys)\n"}], "negative_code": [{"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | (n > c) = 0 \n | ((all (\\a -> a == 0) as) && (n == c)) = -1\n | (all (\\a -> a == 0) as) = 0\n | (maxX == 0) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 maxX\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX :: [(Integer, Integer)] -> Integer -> Integer\ndaysX abs x = foldl sumDiv 0 abs\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nbinSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo\n | (lo == hi) = 0\n | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi\n | otherwise = binSearchMaxX n c abs lo (mid - 1)\n where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2\n\n\nsolve n c as bs | (n > c) = 0 \n | otherwise = \n if (maxX == 0) then 0\n else maxX - minX + 1\n where m = maximum bs\n uBound = (c - n) * m + m - 1\n abs = zip as bs\n maxX = binSearchMaxX n c abs 0 uBound\n minX = binSearchMinX n c abs 1 maxX\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = foldl sumDiv 0 abs\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nbinSearchMaxX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi\n | otherwise = binSearchMaxX n c abs lo (mid - 1)\n where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2\n\n\nsolve n c as bs | (n > c) = 0 \n | otherwise = \n if (maxX == 0) then 0\n else maxX - minX + 1\n where m = maximum bs\n uBound = (c - n) * m + m - 1\n abs = zip as bs\n maxX = binSearchMaxX n c abs 0 uBound\n minX = binSearchMinX n c abs 1 maxX\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = foldl sumDiv 0 abs\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nbinSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo\n | (lo == hi) = 0\n | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi\n | otherwise = binSearchMaxX n c abs lo (mid - 1)\n where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2\n\n\nsolve n c as bs | (n > c) = 0 \n | otherwise = \n if (maxX == 0) then 0\n else maxX - minX + 1\n where m = maximum bs\n uBound = (c - n) * m + m - 1\n abs = zip as bs\n maxX = binSearchMaxX n c abs 0 uBound\n minX = binSearchMinX n c abs 1 maxX\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = foldl sumDiv 0 abs\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nbinSearchMaxX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi\n | otherwise = binSearchMaxX n c abs lo (mid - 1)\n where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2\n\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n let m = maximum bs\n let uBound = (c - n) * m + m - 1\n let abs = zip as bs\n let maxX = binSearchMaxX n c abs 1 uBound\n let minX = binSearchMinX n c abs 1 maxX\n print (maxX - minX + 1)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX :: [(Integer, Integer)] -> Integer -> Integer\ndaysX abs x = foldl sumDiv 0 abs\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nbinSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo\n | (lo == hi) = 0\n | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi\n | otherwise = binSearchMaxX n c abs lo (mid - 1)\n where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2\n\n\nsolve n c as bs | (n > c) = 0 \n | otherwise = \n if (all (\\a -> a == 0) as) then -1\n else if (maxX == 0) then 0\n else maxX - minX + 1\n where m = maximum bs\n uBound = (c - n) * m + m - 1\n abs = zip as bs\n maxX = binSearchMaxX n c abs 0 uBound\n minX = binSearchMinX n c abs 1 maxX\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\ndaysX abs x = (foldl sumDiv 0 abs)\n where sumDiv s (ai, bi) = s + (x * ai) `div` bi\n\nbinSearchMinX n c abs lo hi | (lo == hi) = lo\n | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid\n | otherwise = binSearchMinX n c abs (mid + 1) hi\n where mid = (lo + hi) `div` 2\n\nsolve n c as bs | (n > c) = 0 \n | ((all (\\a -> a == 0) as) && (n == c)) = -1\n | (all (\\a -> a == 0) as) = 0\n | (maxX == 0) = 0\n | otherwise = maxX - minX + 1\n where m = maximum bs\n uBound = (c + 1 - n) * m + m - 1\n abs = zip as bs\n maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1\n minX = binSearchMinX n c abs 1 maxX\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (c, r2) = readInt r1\n let (as, bs, _) = readAs readInt r2\n print (solve n c as bs)\n where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)\n readAs readf s = case readf s of\n Just (ai, r) -> (ai : as, bs, t)\n where (as, bs, t) = readBs readf r\n Nothing -> ([], [], s)\n readBs readf s = case readf s of\n Just (bi, r) -> (as, bi : bs, t)\n where (as, bs, t) = readAs readf r\n Nothing -> ([], [], s)\n"}], "src_uid": "9e17daaa5ca2297673b8a2a9db497471"} {"source_code": "m :: Int->Int->Integer\nm 2 2 = 3;\nm 2 x | x == 0 = 2 | x == 1 = 1\nm x 2 = m 2 x\nm 1 1 = 0\nm _ _ = 1\n\nz :: [Int]->[Int]->Integer\nz a b = foldl (\\x y->x*y) 1 (zipWith m a b)\n\nslv :: [[Int]]->Integer\nslv xs = foldl (\\x y->x+y) 0 [z x ye | x <- xs, ye <- xs]\n\nbi :: Int->Int->[Int]\nbi 0 _ = []\nbi n x = (mod x 2: bi (n-1) (quot x 2))\n\nmk :: Int->Int->Int->[[Int]]\nmk _ _ 1 = []\nmk _ _ 0 = []\nmk f n x = if (x `mod` 2) == f then ((replicate n 2)++[1-f]++(bi (30-n-1) (quot x 2))):ls else ls where ls = mk f (n + 1) (quot x 2)\n\ncn :: Int->Int->Int->[[Int]]\ncn 30 _ _ = []\ncn pt le ri = if le < 2^pt && 2^(pt+1) <= ri then ((replicate pt 2)++[1]++(replicate (30-pt-1) 0)):ls else ls where ls = cn (pt+1) le ri\n\nwr :: [Int]->Integer\nwr (0:0:_) = 1\nwr (0:ri:x) = (wr (1:ri:x)) + (toInteger ri) * 2 + 1\nwr (le:ri:_) = slv((cn 0 (le-1) (ri+1))++(mk 0 0 (le-1))++(mk 1 0 (ri+1)))\n\nrdd :: String->[Int]\nrdd = map read . words\n\nmain = do\n t <- getLine\n semi <- sequence (replicate ((read t)::Int) getLine)\n mapM_ print (map (wr . rdd) semi)\n", "positive_code": [{"source_code": "m 2 2=3\nm 2 x|x==0=2|x==1=1\nm x 2=m 2 x\nm 1 1=0\nm _ _=1\nl=getLine\nk=replicate\nq=quot\no=foldl\nz=(o(*)1.).zipWith m\ns u=o(+)0[z x y|x<-u,y<-u]\n0%_=[]\nn%x=mod x 2:(n-1)%(q x 2)\nc _ _ 1=[]\nc _ _ 0=[]\nc f n x=if x`mod`2==f then((k n 2)++[1-f]++((30-n-1)%(q x 2))):h else h where h=c f(n+1)(q x 2)\ne 30 _ _=[]\ne p l r=if l<2^p&&2^p*2<=r then((k p 2)++[1]++(k(30-p-1)0)):h else h where h=e(p+1)l r\nw[0,0]=1\nw[0,r]=(w[1,r])+(toInteger r)*2+1\nw[l,r]=s((e 0(l-1)(r+1))++(c 0 0(l-1))++(c 1 0(r+1)))\nr=map read.words\nmain=do\n l\n a<-lines<$>getContents\n mapM print$map(w.r)a\n"}, {"source_code": "m 2 2 =3\nm 2 x |x==0=2|x==1=1\nm x 2 =m 2 x\nm 1 1 =0\nm _ _ =1\nz a b = foldl (\\x y->x*y) 1 (zipWith m a b)\nslv xs = foldl (\\x y->x+y) 0 [z x ye | x <- xs, ye <- xs]\nbi 0 _ = []\nbi n x = (mod x 2: bi (n-1) (quot x 2))\nmk _ _ 1 = []\nmk _ _ 0 = []\nmk f n x = if (x `mod` 2) == f then ((replicate n 2)++[1-f]++(bi (30-n-1) (quot x 2))):ls else ls where ls = mk f (n + 1) (quot x 2)\ncn 30 _ _ = []\ncn pt le ri = if le < 2^pt && 2^(pt+1) <= ri then ((replicate pt 2)++[1]++(replicate (30-pt-1) 0)):ls else ls where ls = cn (pt+1) le ri\nwr (0:0:_) = 1\nwr (0:ri:x) = (wr (1:ri:x)) + (toInteger ri) * 2 + 1\nwr (le:ri:_) = slv((cn 0 (le-1) (ri+1))++(mk 0 0 (le-1))++(mk 1 0 (ri+1)))\nrdd = map read . words\nmain = do\n t <- getLine\n semi <- sequence (replicate ((read t)::Int) getLine)\n mapM_ print (map (wr . rdd) semi)\n"}, {"source_code": "m 2 2=3\nm 2 x|x==0=2|x==1=1\nm x 2=m 2 x\nm 1 1=0\nm _ _=1\nl=getLine\nk=replicate\nq=quot\no=foldl\nz a b=o(\\x y->x*y)1(zipWith m a b)\ns u=o(\\x y->x+y)0[z x y|x<-u,y<-u]\nb 0 _=[]\nb n x=mod x 2:b(n-1)(q x 2)\nc _ _ 1=[]\nc _ _ 0=[]\nc f n x=if(x`mod`2)==f then((k n 2)++[1-f]++(b(30-n-1)(q x 2))):ls else ls where ls=c f(n+1)(q x 2)\ne 30 _ _=[]\ne pt l r=if l<2^pt&&2^(pt+1)<=r then((k pt 2)++[1]++(k(30-pt-1)0)):ls else ls where ls=e(pt+1)l r\nw(0:0:_)=1\nw(0:ri:x)=(w(1:ri:x))+(toInteger ri)*2+1\nw(le:ri:_)=s((e 0(le-1)(ri+1))++(c 0 0(le-1))++(c 1 0(ri+1)))\nr=map read.words\nmain=do\n t<-l\n semi<-sequence(k((read t)::Int)l)\n mapM_ print(map(w.r)semi)\n"}], "negative_code": [{"source_code": "m :: Int->Int->Integer\nm 2 2 = 3;\nm 2 x | x == 0 = 2 | x == 1 = 1\nm x 2 = m 2 x\nm 1 1 = 0\nm _ _ = 1\n\nz :: [Int]->[Int]->Integer\nz a b = foldl (\\x y->x*y) 1 (zipWith m a b)\n\nslv :: [[Int]]->Integer\nslv xs = foldl (\\x y->x+y) 0 [z x ye | x <- xs, ye <- xs]\n\nbi :: Int->Int->[Int]\nbi 0 _ = []\nbi n x = (mod x 2: bi (n-1) (quot x 2))\n\nmk :: Int->Int->Int->[[Int]]\nmk _ _ 1 = []\nmk _ _ 0 = []\nmk f n x = if (x `mod` 2) == f then ((replicate n 2)++[1-f]++(bi (30-n-1) (quot x 2))):ls else ls where ls = mk f (n + 1) (quot x 2)\n\ncn :: Int->Int->Int->[[Int]]\ncn 30 _ _ = []\ncn pt le ri = if le < 2^pt && 2^(pt+1) <= ri then ((replicate pt 2)++[1]++(replicate (30-pt-1) 0)):ls else ls where ls = cn (pt+1) le ri\n\nwr :: [Int]->Integer\nwr (0:0:_) = 1\nwr (0:ri:x) = (wr (1:ri:x)) + (toInteger ri) * 2 - 1\nwr (le:ri:_) = slv((cn 0 (le-1) (ri+1))++(mk 0 0 (le-1))++(mk 1 0 (ri+1)))\n\nrdd :: String->[Int]\nrdd = map read . words\n\nmain = do\n t <- getLine\n semi <- sequence (replicate ((read t)::Int) getLine)\n mapM_ print (map (wr . rdd) semi)\n"}], "src_uid": "d418db46dd3aa411836774a4cc7f73d7"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare b d `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\nsolve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n s2 = (S.fromList $ map Order (zip l [1..])) S.\\\\ init \n init = S.fromList $ map Order (take k l1)\n loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++ \n (take (p-k) $ reverse $ S.toList s21)\n | otherwise = let s1' = insert' hd $ S.delete o s1\n s2' = S.insert o $ delete' hd s2\n in {-traceShow (\"swap \"++show hd++show o) $-}\n loop s1' s2' l1'\n where\n o = S.findMin s1\n (hd:l1') = l1\n (s21,s22) = S.split o s2\n d = S.size s21\n \n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve2 n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare b d `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\n\nsort' = map unOrder . sort . map Order\nsolve2 n p k l = map (snd) $ e ++ c\n where\n l2 = sort' (zip l [1..])\n (a,b)= splitAt (p-k) l2\n l1 = reverse $ sort $ b\n (c,d)= splitAt k l1\n x = minimum $ map Order c\n e = take (p-k) $ reverse $ a++(takeWhile f $ sort' d)\n f a = Order a `compare` x == LT \n \n\nsolve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n s2 = (S.fromList $ map Order (zip l [1..])) S.\\\\ init \n init = S.fromList $ map Order (take k l1)\n loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++ \n (take (p-k) $ reverse $ S.toList s21)\n | otherwise = let s1' = insert' hd $ S.delete o s1\n s2' = S.insert o $ delete' hd s2\n in {-traceShow (\"swap \"++show hd++show o) $-}\n loop s1' s2' l1'\n where\n o = S.findMin s1\n (hd:l1') = l1\n (s21,s22) = S.split o s2\n d = S.size s21\n \n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve2 n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare b d `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\nsolve2 n p k l = map (snd) $ take (p-k) a ++ take k l1\n where\n l2 = map unOrder$ sort $ map Order (zip l [1..])\n (a,b) = go l2 undefined k []\n go [] _ 0 acc = (acc,[])\n go (x:xs) k 0 acc | cmp2 (fst x) k == EQ = go xs k 0 (x:acc)\n | otherwise = (acc,x:xs)\n go (x:xs) k n acc = go xs (fst x) (n-1) (x:acc)\n l1 = reverse $ sort $ b\n\nsolve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n s2 = (S.fromList $ map Order (zip l [1..])) S.\\\\ init \n init = S.fromList $ map Order (take k l1)\n loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++ \n (take (p-k) $ reverse $ S.toList s21)\n | otherwise = let s1' = insert' hd $ S.delete o s1\n s2' = S.insert o $ delete' hd s2\n in {-traceShow (\"swap \"++show hd++show o) $-}\n loop s1' s2' l1'\n where\n o = S.findMin s1\n (hd:l1') = l1\n (s21,s22) = S.split o s2\n d = S.size s21\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve2 n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare b d `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\n\nsort' = map unOrder . sort . map Order\nsolve2 n p k l = map (snd) $ e ++ c\n where\n l2 = sort' (zip l [1..])\n (a,b)= splitAt (p-k) l2\n l1 = reverse $ sort $ b\n (c,d)= splitAt k b\n x = minimum $ map Order c\n e = take (p-k) $ reverse $ a++(takeWhile f $ sort' d)\n f a = Order a `compare` x == LT \n \n\nsolve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n s2 = (S.fromList $ map Order (zip l [1..])) S.\\\\ init \n init = S.fromList $ map Order (take k l1)\n loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++ \n (take (p-k) $ reverse $ S.toList s21)\n | otherwise = let s1' = insert' hd $ S.delete o s1\n s2' = S.insert o $ delete' hd s2\n in {-traceShow (\"swap \"++show hd++show o) $-}\n loop s1' s2' l1'\n where\n o = S.findMin s1\n (hd:l1') = l1\n (s21,s22) = S.split o s2\n d = S.size s21\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve2 n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare b d `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\nsolve2 n p k l = map (snd.unOrder) $ a ++ take k (map Order l1)\n where\n l2 = sort $ map Order (zip l [1..])\n (a,b) = splitAt (p-k) l2\n l1 = reverse $ sort $ map unOrder b\n\nsolve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n s2 = (S.fromList $ map Order (zip l [1..])) S.\\\\ init \n init = S.fromList $ map Order (take k l1)\n loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++ \n (take (p-k) $ reverse $ S.toList s21)\n | otherwise = let s1' = insert' hd $ S.delete o s1\n s2' = S.insert o $ delete' hd s2\n in {-traceShow (\"swap \"++show hd++show o) $-}\n loop s1' s2' l1'\n where\n o = S.findMin s1\n (hd:l1') = l1\n (s21,s22) = S.split o s2\n d = S.size s21\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare d b `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\nsolve n p k l = {-traceShow l1 $ traceShow l2 $ -} map (snd.unOrder)$ loop S.empty S.empty l1 l2\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n l2 = S.fromList $ map Order (zip l [1..]) \n loop !s1 !s2 l1 l2\n | S.size s1 < k = let s1' = insert' hd1 s1\n s2' = insert' hd1 s1\n in {-trace (\"insert1 \"++show hd1) $ -}\n loop s1' s2' l1' l2\n | S.size s1 >= p = S.toList s1\n | S.member hd2 s1 = loop s1 s2 l1 l2'\n | Order o > hd2 = {- trace (\"insert2 \"++show hd2) $ -}\n loop (S.insert hd2 s1) s2 l1 l2'\n | otherwise = let s1' = insert' hd1 $ delete' o s1\n s2' = insert' hd1 $ delete' o s2\n l2'' = insert' o l2\n in {- traceShow (compare (Order o) hd2) $\n trace (\"swap \"++show o++show hd1++show hd2) $ -}\n loop s1' s2' l1' l2''\n where\n hd1:l1' = l1\n (hd2,l2') = S.deleteFindMin l2\n o = unOrder $ S.findMin s2\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n [n,p,k] <- map readInt . B.words <$> B.getLine\n l <- replicateM n (parse <$> B.getLine)\n putStrLn $ unwords $ map show $ solve2 n p k l\n\nparse s = let [a,b] = map readInt $ B.words $ s in (a,b)\n\ncmp1 (a,b) (c,d) = compare c a `mappend` compare d b\ncmp2 (a,b) (c,d) = compare b d `mappend` compare c a\n\nnewtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)\ninstance Ord Order where\n compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d\ninstance Show Order where\n show (Order a) = show a\n\ninsert' a s = S.insert (Order a) s\nmember' a s = S.member (Order a) s\ndelete' a s = S.delete (Order a) s\n\nsolve2 n p k l = map (snd) $ take (p-k) a ++ take k l1\n where\n l2 = map unOrder$ sort $ map Order (zip l [1..])\n (a,b) = go l2 (0,0) (p-k) []\n go [] _ 0 acc = (acc,[])\n go (x:xs) k 0 acc | cmp2 (fst x) k == EQ = go xs k 0 (x:acc)\n | otherwise = (acc,x:xs)\n go (x:xs) k n acc = go xs (fst x) (n-1) (x:acc)\n l1 = reverse $ sort $ b\n\nsolve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)\n where\n l1 = sortBy (\\(a,b) (c,d) -> cmp1 a c) (zip l [1..])\n s2 = (S.fromList $ map Order (zip l [1..])) S.\\\\ init \n init = S.fromList $ map Order (take k l1)\n loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++ \n (take (p-k) $ reverse $ S.toList s21)\n | otherwise = let s1' = insert' hd $ S.delete o s1\n s2' = S.insert o $ delete' hd s2\n in {-traceShow (\"swap \"++show hd++show o) $-}\n loop s1' s2' l1'\n where\n o = S.findMin s1\n (hd:l1') = l1\n (s21,s22) = S.split o s2\n d = S.size s21\n \n"}], "src_uid": "d662310e13c399554d90b5367bf6d3e0"} {"source_code": "parse :: String -> [Int]\nparse = (map read) . words\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [n, m] = (allWithFirst n) ++ (reverseAll $ drop 1 (allWithFirst m))\n where\n allWithFirst x = [(y, 1) | y <- [1 .. x]]\n reverseAll = map (\\(x, y) -> (y, x))\n\noutput :: [(Int, Int)] -> String\noutput x = (show $ length x) ++ \"\\n\" ++ outputPairs x\n\noutputPairs [] = \"\\n\"\noutputPairs (x:xs) = (show $ fst x) ++ \" \" ++ (show $ snd x) ++ \"\\n\" ++ outputPairs xs\n\nmain = interact $ output . solve . parse\n\n", "positive_code": [{"source_code": "main = do\n [n, m] <- fmap (map read . words) getLine\n let pairs = solve n m\n print $ length pairs\n mapM (\\(x, y) -> putStrLn $ show x ++ \" \" ++ show y) pairs\n \nsolve :: Int -> Int -> [(Int, Int)]\nsolve boys girls = (map (\\x -> (1, x)) [1..girls]) ++ (map (\\x -> (x, 1)) [2..boys])\n"}, {"source_code": "main = do\n l <- getContents \n let [n, m] = map read (words l) :: [Int]\n putStrLn $ show (m + n - 1)\n let answer = zip [1,1..] [1..m] ++ zip [2..n] [1,1..]\n sequence_ (map printTuple answer)\n\n where\n printTuple (a, b) = putStrLn $ (show a) ++ \" \" ++ (show b)\n"}, {"source_code": "gen :: Int -> Int -> [(Int, Int)]\ngen a b = [(i, j) | i <- [1..a], j <- [1..b], i == 1 || j == 1]\n\nfmt :: (Int, Int) -> String\nfmt (i,j) = ((show i)++ \" \" ++ (show j) ++ \"\\n\")\n\nsolve :: String -> String\nsolve input = (show $ length res) ++ \"\\n\" ++ (concat (map fmt res))\n where (a:b:xs) = map read (words input)\n res = gen a b\nmain = do\n interact solve\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \ndel x (a:as) \t| x==a = as\n\t\t| otherwise = a: (del x as)\n \n\n\n\nmain= do\n\t[a,b]<- map read. words <$> getLine::IO [Int]\n\tprint $ a+b-1\n\tputStr $ unlines $ map (\\x-> ( show x) ++ \" 1\" ) [1..a] \n\tputStrLn $ unlines $ map (\\x-> ( show a) ++ \" \" ++ show x ) [2..b] \n\t"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n m:n:_ <- liftM (map read . words) getLine \n print (m + n - 1)\n mapM_ putStrLn $ (map ((++) \"1 \" . show) [1..n]) ++ (map (flip (++) \" 1\" . show) [2..m])\n"}, {"source_code": "import Data.List\n\nsolve n m = xs ++ ys where\n xs = [\"1 \" ++ show j | j <- [1..m]]\n ys = [show i ++ \" \" ++ show 1 | i <- [2..n]]\n\nmain = do\n line <- getLine\n let [n, m] = map read $ words line :: [Int]\n let xs = solve n m\n print $ length xs\n putStrLn $ intercalate \"\\n\" xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -Wall -fno-warn-missing-signatures -fno-warn-type-defaults #-}\n\nmain = interact $ sv. head. lines\nsv str = unlines $ show (length ls): ls \n where ls = pair ((map read.words) str)\npair [n,m] = let f=zipWith (\\x y->show x++\" \"++show y) in f (repeat 1) [1..m] ++ f [2..n] (repeat m)\n"}, {"source_code": "readArr :: (Read t) => IO [t]\nreadArr = fmap ((fmap read) . words) getLine\n\nfront2 :: [t] -> (t, t)\nfront2 (x:y:_) = (x, y)\n\nplprint :: (Show a, Show b) => [(a, b)] -> IO ()\nplprint = sequence_ . (fmap (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b))\n\npsort :: (Ord t) => (t, t) -> (t, t)\npsort (x, y) \n | x > y = (y, x)\n | otherwise = (x, y)\n\nmain = do \n (n, m) <- (fmap front2) (readArr :: IO [Int])\n let li = [(1, a) | a <- [1..m]] ++ [(a, 1) | a <- [2..n]]\n print $ length li\n plprint li \n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [a, b] = [(1, i) | i <- [1..b]] ++ [(i, 1) | i <- [2..a]]\n\nprint' :: [(Int, Int)] -> IO ()\nprint' xs = print (length xs) >> mapM_ print'' xs\n where\n print'' (x, y) = putStrLn $ concat [show x, \" \", show y]\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= print' . solve"}, {"source_code": "import Control.Applicative\n\nsolve :: Int -> Int -> [[Int]]\nsolve n m =\n [[1, j] | j <- [1..m]] ++ [[i, m] | i <- [2..n]]\n\nmain :: IO ()\nmain = do\n [n, m] <- map read . words <$> getLine\n let solns = solve n m\n putStrLn $ show $ length solns\n putStrLn $ unlines $ map (unwords . map show) $ solns\n"}, {"source_code": "main=getContents>>=(\\[n,m]->(print(n+m-1)>>mapM_(putStrLn.unwords.map show)(f n m))).map read.words\nf n m=[[1,k]|k<-[1..m]]++[[k,1]|k<-[2..n]]\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= (\\[n, m] -> (print (n + m - 1) >> mapM_ (putStrLn . unwords . map show) (solve n m))) . map read . words\n\nsolve :: Integer -> Integer -> [[Integer]]\nsolve n m = [ [ 1, k ] | k <- [1..m] ] ++ [ [ k, m ] | k <- [2..n] ]\n"}], "negative_code": [{"source_code": "readArr :: (Read t) => IO [t]\nreadArr = fmap ((fmap read) . words) getLine\n\nfront2 :: [t] -> (t, t)\nfront2 (x:y:_) = (x, y)\n\nplprint :: (Show a, Show b) => [(a, b)] -> IO ()\nplprint = sequence_ . (fmap (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b))\n\npsort :: (Ord t) => (t, t) -> (t, t)\npsort (x, y) \n | x > y = (y, x)\n | otherwise = (x, y)\n\nmain = do \n (n, m) <- (fmap front2) (readArr :: IO [Int])\n let li = [(1, a) | a <- [1..n]] ++ [(b, b) | b <- [2..m]]\n print $ length li\n plprint li \n"}, {"source_code": "readArr :: (Read t) => IO [t]\nreadArr = fmap ((fmap read) . words) getLine\n\nfront2 :: [t] -> (t, t)\nfront2 (x:y:_) = (x, y)\n\nplprint :: (Show a, Show b) => [(a, b)] -> IO ()\nplprint = sequence_ . (fmap (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b))\n\npsort :: (Ord t) => (t, t) -> (t, t)\npsort (x, y) \n | x > y = (y, x)\n | otherwise = (x, y)\n\nmain = do \n (n, m) <- (fmap (psort . front2)) (readArr :: IO [Int])\n let li = [(x, y) | x <- [1..n], y <- [1..m], y >= x]\n print $ length li\n plprint li \n"}, {"source_code": "readArr :: (Read t) => IO [t]\nreadArr = fmap ((fmap read) . words) getLine\n\nfront2 :: [t] -> (t, t)\nfront2 (x:y:_) = (x, y)\n\nplprint :: (Show a, Show b) => [(a, b)] -> IO ()\nplprint = sequence_ . (fmap (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b))\n\npsort :: (Ord t) => (t, t) -> (t, t)\npsort (x, y) \n | x > y = (y, x)\n | otherwise = (x, y)\n\nmain = do \n (n, m) <- (fmap front2) (readArr :: IO [Int])\n let li = (if n <= m then (filter $ (\\(a, b) -> a <= b))\n else (filter $ (\\(a, b) -> b <= a)) ) \n [(x, y) | x <- [1..n], y <- [1..m]]\n print $ length li\n plprint li \n"}, {"source_code": "readArr :: (Read t) => IO [t]\nreadArr = fmap ((fmap read) . words) getLine\n\nfront2 :: [t] -> (t, t)\nfront2 (x:y:_) = (x, y)\n\nplprint :: (Show a, Show b) => [(a, b)] -> IO ()\nplprint = sequence_ . (fmap (\\(a, b) -> putStrLn $ show a ++ \" \" ++ show b))\n\nmain = do \n (n, m) <- (fmap front2) (readArr :: IO [Int])\n let li = [(x, y) | x <- [1..n], y <- [1..m], y >= x]\n print $ length li\n plprint li \n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [1, 1] = [(1, 1)]\nsolve [a, b]\n | a > b = [(div (i+1) 2, div i 2) | i <- [2 .. 2*b + 1]]\n | a < b = [(div i 2, div (i+1) 2) | i <- [2 .. 2*a + 1]]\n | a == b = [(div i 2, div (i+1) 2) | i <- [2 .. 2*a]]\n\nprint' :: [(Int, Int)] -> IO ()\nprint' = mapM_ print''\n where\n print'' (x, y) = putStrLn $ concat [show x, \" \", show y]\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= print' . solve"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve [1, 1] = [(1, 1)]\nsolve [a, b]\n | a > b = [(div (i+1) 2, div i 2) | i <- [2 .. 2*b + 1]]\n | a < b = [(div i 2, div (i+1) 2) | i <- [2 .. 2*a + 1]]\n | a == b = [(div i 2, div (i+1) 2) | i <- [2 .. 2*a]]\n\nprint' :: [(Int, Int)] -> IO ()\nprint' xs = print (length xs) >> mapM_ print'' xs\n where\n print'' (x, y) = putStrLn $ concat [show x, \" \", show y]\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= print' . solve"}, {"source_code": "main :: IO ()\nmain = getContents >>= (\\[n, m] -> (print (n + m - 1) >> mapM_ (putStrLn . unwords . map show) (solve n m))) . map read . words\n\nsolve :: Integer -> Integer -> [[Integer]]\nsolve n m = zipWith ((.(:[])).(:)) (concatMap (replicate 2) [1..n]) (tail $ concatMap (replicate 2) [1..m])\n"}, {"source_code": "main = do\n [n, m] <- fmap (map read . words) getLine\n let pairs = solve n m\n print $ length pairs\n mapM (\\(x, y) -> putStrLn $ show x ++ \" \" ++ show y) pairs\n \nsolve :: Int -> Int -> [(Int, Int)]\nsolve boys girls = (map (\\x -> (1, x)) [1..girls]) ++ (map (\\x -> (x, 2)) [2..boys])\n"}, {"source_code": "main = do\n [n, m] <- fmap (map read . words) getLine\n let pairs = solve n m\n print $ length pairs\n mapM (\\(x, y) -> putStrLn $ show x ++ \" \" ++ show y) pairs\n \nsolve :: Int -> Int -> [(Int, Int)]\nsolve boys girls = map (\\x -> (1, x)) [1..girls] ++ map (\\x -> (x, 2)) [2..boys]\n"}, {"source_code": "import Data.List\n\nsolve n m = xs ++ ys where\n xs = [\"1 \" ++ show j | j <- [1..m]]\n ys = [show i ++ \" \" ++ show j | (i, j) <- zip [2..n] [1..m]]\n\nmain = do\n line <- getLine\n let [n, m] = map read $ words line :: [Int]\n let xs = solve n m\n print $ length xs\n putStrLn $ intercalate \"\\n\" xs\n"}], "src_uid": "14fc3a7fef44a02791aee62838c4c8c8"} {"source_code": "solve :: String -> Bool\nsolve s = take (length s `div` 2) s == drop (length s `div` 2) s\n\ntestcases :: Int -> IO()\ntestcases 0 = putStr \"\"\ntestcases t = do\n current <- getLine\n putStrLn (if solve current then \"YES\" else \"NO\")\n testcases ( t - 1 )\n\nmain = do\n t <- getLine\n testcases $ read t\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\n\nsolve str =\n let len = length str\n in if even len && (take (len `div` 2) str == drop (len `div` 2) str) then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n forM_ [1 .. n] $ \\i -> do\n x <- getLine \n putStrLn $ solve x\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n res <- replicateM t $ do\n s <- getLine \n let len = length s\n if mod len 2 == 1 then return \"NO\"\n else if take (len `div` 2) s == drop (len `div` 2) s then return \"YES\" else return \"NO\" \n\n putStrLn $ unlines res\n return ()\n\n"}], "negative_code": [{"source_code": "solve :: String -> Bool\nsolve s = take (length s `div` 2) s == drop (length s `div` 2) s\n\ntestcases :: Int -> IO()\ntestcases 0 = putStr \"\" \ntestcases t = do\n current <- getLine\n print . solve $ current\n testcases ( t - 1 )\n\nmain = do\n t <- getLine\n testcases $ read t\n"}], "src_uid": "9640b7197bd7b8a59f29aecf104291e1"} {"source_code": "import Control.Monad\nmain = do\n n <- readLn\n ps <- replicateM n $ ((!!1).(map read).words <$> getLine)\n k <- (readLn::IO Int)\n print . length . filter (>=k) $ ps", "positive_code": [{"source_code": "import Control.Monad (replicateM)\n\nreadWordsLn :: Read a => IO [a]\nreadWordsLn = map read <$> (words <$> getLine)\n\nreadHeadLn :: Read a => IO a\nreadHeadLn = head <$> readWordsLn\n\nreadWordsMultiLn :: Read a => Int -> IO [[a]]\nreadWordsMultiLn n = replicateM n readWordsLn\n\nmain :: IO ()\nmain = do\n n <- readHeadLn :: IO Int\n chapters <- readWordsMultiLn n :: IO [[Int]]\n page <- readHeadLn :: IO Int\n print (n - solve chapters page)\n\nsolve :: [[Int]] -> Int -> Int\nsolve ((_:x:_):xs) p\n | p > x = solve xs p + 1\n | otherwise = 0\n"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- (readLn :: IO Int) \n ps <- replicateM n (map (read :: String -> Int) . words <$> getLine)\n let qs = concat $ zipWith (\\[a,b] c -> replicate (b-a+1) c) ps [1..]\n k <- (readLn :: IO Int) \n print $ n - (head $ drop (k-1) qs) + 1"}, {"source_code": "import Control.Monad\nmain = do\n n <- readLn\n lrs <- replicateM n (map read . words <$> getLine)\n k <- readLn :: IO Int\n print $ length $ dropWhile ((< k) . (!! 1)) lrs\n"}, {"source_code": "import Control.Monad\nimport Data.Semigroup\n\nsolve :: [[Int]] -> Int -> Int\nsolve chaps curr = sum $ map (fromEnum . (>= curr) . (!! 1)) chaps\n\nmain = do\n numChapters <- read <$> getLine\n bounds <- replicateM numChapters $ do\n fmap read <$> words <$> getLine\n pos <- read <$> getLine\n print $ solve bounds pos\n return ()\n"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . map read . words\n\nlistIntoPairList :: [a] -> [(a, a)]\nlistIntoPairList [] = []\nlistIntoPairList (x1:x2:xs) = (x1, x2) : listIntoPairList xs\n\nsecondLessEq :: Int -> (Int, Int) -> Bool\nsecondLessEq n (_, r) = n <= r\n\nsolve :: [Int] -> Int\nsolve (chaps:rest) = length . filter (secondLessEq (last rest)) . listIntoPairList . take (2*chaps) $ rest\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntuple2 [] = []\ntuple2 (x:y:l) = (x, y) : (tuple2 l)\n\nsolve :: [Int] -> Int\nsolve (n:a) = length $ filter (\\(i, j) -> k <= j) d\n where\n (b, (k:c)) = splitAt (2 * n) a\n d = tuple2 b\n\nmain :: IO ()\nmain = print . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\tn<-read <$> getLine ::IO Int\n\t[a,b]<-transpose <$> map (map read) <$> map words <$> replicateM n getLine\n\t\n\ty<-read <$> getLine ::IO Int\n\tprint $ length $ dropWhile ( [Int] -> Int\ncountUnfinished p = length . filter (>=p)\n\nmain = do\n nStr <- getLine\n let n = read nStr\n cStrs <- sequence . replicate n $ getLine\n let rs = map (read . last . words) cStrs\n pStr <- getLine\n let p = read pStr\n print $ countUnfinished p rs"}], "negative_code": [{"source_code": "import Control.Monad\nmain = do\n n <- readLn\n ps <- replicateM n $ ((!!1).(map read).words <$> getLine)\n k <- (readLn::IO Int)\n print . length . filter (>k) $ ps"}], "src_uid": "2545b6af730f99193041a8810b728cb3"} {"source_code": "import Data.List( nub)\n\nmain = do\n s_ <- getLine\n k_ <- readLn::IO Int\n let\n\tlen = length s_\n\tuniq = nub s_\n\tneed = k_ - (length uniq)\n \n if len < k_\n\tthen putStr \"impossible\"\n\telse print (need `max` 0)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Ord\n\nsolve x n\n\t|ll>=n=\"0\"\n\t|l>=n = show (n-ll)\n\t|otherwise = \"impossible\"\n\twhere\n\t\tl=length x\n\t\tll=length (nub x)\n\n\nmain=do\n\tword<-getLine\n\tn<-getLine\n\tputStrLn (solve word (read n::Int))"}, {"source_code": "import Data.List\n\nmain = do \n str <- getLine\n n <- getLine\n putStrLn $ foo str (read n)\n\nfoo :: String -> Int -> String\nfoo str n = \n let d = length . nub . sort $ str\n tl = length str\n in \n if tl < n\n then \"impossible\"\n else show $ max 0 $ n - d"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: String -> Int -> String\nsolve s n \n | length s < n = \"impossible\"\n | otherwise = show (max 0 (n - u))\n where u = (length . map head . group . sort) s\n\nmain :: IO ()\nmain = do\n s <- getLine\n n <- readInt\n putStrLn $ solve s n\n"}, {"source_code": "import Data.List\n\nsolve :: String -> Int -> String\nsolve xs k \n | length xs < k = \"impossible\"\n | (length.nub) xs < k = show (k-(length.nub) xs)\n | otherwise = \"0\"\n\nmain = do\n xs <- getLine\n k <- readLn :: IO Int\n (putStrLn.solve xs) k"}, {"source_code": "-- 844A\n\nimport Data.Maybe (fromJust)\nimport Data.List (group, sort)\n\nunique = length . group . sort\n\nprogram (s:si:_)\n | i > length s = \"impossible\"\n | otherwise = show $ max 0 (i - unique s)\n where i = read si\n\nmain = interact $ program . lines\n"}, {"source_code": "import Data.List\nimport System.IO\n\nnrDistinct_ :: (Ord a, Num b) => [a] -> b\nnrDistinct :: (Ord a, Num b) => [a] -> b\n\nnrDistinct_ [] = 0\nnrDistinct_ [x] = 1\nnrDistinct_ (x:x_:xs) = if x == x_ then r else r + 1\n where r = nrDistinct_ (x_:xs)\n\nnrDistinct = nrDistinct_ . sort\n\nmain = do\n str <- getLine\n k <- readLn :: IO Int\n let delta = max 0 $ k - (nrDistinct str)\n if k <= length str then print delta else putStr \"impossible\"\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Ord\n\nsolve x n\n\t|l==n = show (n-(length (nub x)))\n\t|otherwise = \"impossible\"\n\twhere\n\t\tl=length x\n\n\nmain=do\n\tword<-getLine\n\tn<-getLine\n\tputStrLn (solve word (read n::Int))"}, {"source_code": "import Data.List\nimport Data.Ord\n\nsolve x n\n\t|l>=n = show (n-(length (nub x)))\n\t|otherwise = \"impossible\"\n\twhere\n\t\tl=length x\n\n\nmain=do\n\tword<-getLine\n\tn<-getLine\n\tputStrLn (solve word (read n::Int))"}, {"source_code": "-- 844A\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\ntoInt = fst . fromJust . B.readInt\nunique = length . B.group . B.sort\n\nprogram (s:si:_)\n | i > B.length s = \"impossible\"\n | otherwise = show $ max 0 (i - unique s)\n where i = toInt si\n\nmain = B.interact $ B.pack . program . B.lines\n"}], "src_uid": "bd5912fe2c5c37658f28f6b159b39645"} {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\nfast_read_Int64 = fmap (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) BS.getLine :: IO [Int64]\n\nbs :: Array Int64 Int64 -> Int64 -> Int64 -> Int64\nbs v n x = go 0 n where\n go st dr\n | st>=dr = dr - 1\n | v ! mid <= x = go (mid+1) dr\n | v ! mid > x = go st mid\n where mid = div (st + dr) 2\n\n\nmain = do\n [n,m,k] <- fast_read_Int64\n [x,s] <- fast_read_Int64\n a <- fmap (listArray (0,m-1)) fast_read_Int64\n b <- fmap (listArray (0,m-1)) fast_read_Int64\n c <- fmap (listArray (0,k-1)) fast_read_Int64\n d <- fmap (listArray (0,k-1)) fast_read_Int64\n let fara_1 = bs d k s \n let initial = if fara_1 >= 0 then (max (n - c ! fara_1) 0) * x else n * x\n\n let f i = g i where\n g i\n | s < b ! i = maxBound :: Int64\n | otherwise = (max 0 (n - maxp)) * (a ! i)\n where \n maxp = if binary_search >=0 then c ! binary_search else 0\n binary_search = bs d k (s- b ! i)\n\n\n let _for_ = minimum $ map f [0..m-1]\n \n print $ min initial _for_", "positive_code": [{"source_code": "-- Codeforces Round #379 (Div. 2)\n-- http://codeforces.com/contest/734\n\n-- ID: 734C (Anton and Making Potions)\n\nimport Control.Monad\nimport Data.Array\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain = do\n [n, m, k] <- getInt64s\n [x, s] <- getInt64s\n as <- (listArray (0, m-1)) `fmap` getInt64s\n bs <- (listArray (0, m-1)) `fmap` getInt64s\n cs <- (listArray (0, k-1)) `fmap` getInt64s\n ds <- (listArray (0, k-1)) `fmap` getInt64s\n let ub = upperBound ds k s\n let freePotion = cs ! (ub - 1)\n let noFirst = if ub > 0 then (max (n - freePotion) 0) * x else n * x\n let bestUsingFirst = minimum $ map (make as bs cs ds n k s) [0..m-1]\n print $ min noFirst bestUsingFirst\n\nmake as bs cs ds n k s i\n | bs ! i > s = maxBound :: Int64\n | otherwise = (max 0 remain) * (as ! i)\n where\n remain = n - (if ub == 0 then 0 else (cs ! (ub - 1)))\n ub = upperBound ds k (s - bs ! i)\n\n\nupperBound :: Array Int64 Int64 -> Int64 -> Int64 -> Int64\nupperBound ary n x = go 0 n where\n go lb ub\n | lb >= ub = ub\n | ary ! mid <= x = go (mid+1) ub\n | ary ! mid > x = go lb mid\n where mid = (lb + ub) `div` 2"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ntype IntArray = UA.UArray Int Int\n\ninf = 10^20 :: Integer\n\nbinarySearch f arr start end\n | start >= end = end\n | otherwise = if f (arr ! middle) then firstHalf else secondHalf where\n middle = (start + end) `div` 2\n firstHalf = binarySearch f arr start middle\n secondHalf = binarySearch f arr (middle+1) end\n\ngetMaxImmPotion cs ds mana = cs ! spellIndex' where\n (lb, hb) = bounds ds\n spellIndex = binarySearch (> mana) ds lb hb\n spellIndex' = until (\\si -> (ds ! si) <= mana) (\\si -> si-1) spellIndex\n\nprocess :: Int -> Int -> [Int] -> [Int] -> IntArray -> IntArray -> Integer\nprocess n s as bs cs ds = minimum [ makePotion a b | (a, b) <- zip as bs ] where\n makePotion a b = if secondSpellMana < 0 then inf else totalTime :: Integer where\n potionTime = a\n secondSpellMana = s - b\n manualPotionCnt = max 0 $ n - getMaxImmPotion cs ds secondSpellMana\n totalTime = (fromIntegral potionTime) * (fromIntegral manualPotionCnt)\n\nmain = do\n n:m:k:[] <- getInts\n x:s:[] <- getInts\n as <- ((:) x) <$> getInts\n bs <- ((:) 0) <$> getInts\n cs <- (\\l -> UA.listArray (0, k) (0:l)) <$> getInts\n ds <- (\\l -> UA.listArray (0, k) (0:l)) <$> getInts\n print $ process n s as bs cs ds\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextInteger :: Tokenizer Integer\nnextInteger = state $ \\(s:ss) -> case L.readInteger s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Integer:\" ++ (show s)\n\nf :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Integer\nf n x s c d | i < 0 = n * x\n | otherwise = (max 0 (n - c!i)) * x\n where i = bs (-1) ((snd $ bounds c) + 1)\n bs l r | r - l == 1 = l\n | d!m <= s = bs m r\n | otherwise = bs l m\n where m = (l + r) `div` 2\n\nsolve :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Integer\nsolve n x s a b c d = foldl min (f n x s c d) [a!i + f (n - 1) (a!i) (s - b!i) c d | i <- [0..snd $ bounds a], s >= b!i]\n\ndoit :: Tokenizer Integer\ndoit = do\n n <- nextInteger\n m <- nextInt\n k <- nextInt\n x <- nextInteger\n s <- nextInteger\n a <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger\n b <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger\n c <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger\n d <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger\n return $ solve n x s a b c d\n\nmain = do\n contents <- L.getContents\n print $ evalState doit (L.words contents)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextInteger :: Tokenizer Integer\nnextInteger = state $ \\(s:ss) -> case L.readInteger s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Integer:\" ++ (show s)\n\n\nf :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Integer\nf n x s c d | i < 0 = n * x\n | otherwise = (max 0 (n - c!i)) * x\n where i = bs (-1) (rightBoundC + 1)\n (_, rightBoundC) = bounds c\n bs l r | r - l == 1 = l\n | d!m <= s = bs m r\n | otherwise = bs l m\n where m = (l + r) `div` 2\n\nsolve :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Integer\nsolve n x s a b c d = foldl min (f n x s c d) [a!i + f (n - 1) (a!i) (s - b!i) c d | i <- [0..rightBoundA], s >= b!i]\n where (_, rightBoundA) = bounds a\n\ndoit :: Tokenizer Integer\ndoit = do\n n <- nextInteger\n m <- nextInt\n k <- nextInt\n x <- nextInteger\n s <- nextInteger\n aList <- replicateM m nextInteger\n bList <- replicateM m nextInteger\n cList <- replicateM k nextInteger\n dList <- replicateM k nextInteger\n let a = listArray (0, m - 1) aList\n let b = listArray (0, m - 1) bList\n let c = listArray (0, k - 1) cList\n let d = listArray (0, k - 1) dList\n return $ solve n x s a b c d\n\nmain = do\n contents <- L.getContents\n print $ evalState doit (L.words contents)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ntype IntArray = UA.UArray Int Int\n\ninf = 10^20 :: Integer\n\nbinarySearch f arr start end\n | start >= end = end\n | otherwise = if f (arr ! middle) then firstHalf else secondHalf where\n middle = (start + end) `div` 2\n firstHalf = binarySearch f arr start middle\n secondHalf = binarySearch f arr (middle+1) end\n\ngetMaxImmPotion cs ds mana = cs ! spellIndex' where\n (lb, hb) = bounds ds\n spellIndex = binarySearch (>= mana) ds lb hb\n spellIndex' = if ds ! spellIndex <= mana then spellIndex else spellIndex - 1\n\nprocess :: Int -> Int -> [Int] -> [Int] -> IntArray -> IntArray -> Integer\nprocess n s as bs cs ds = minimum [ makePotion a b | (a, b) <- zip as bs ] where\n makePotion a b = if secondSpellMana < 0 then inf else totalTime :: Integer where\n potionTime = a\n secondSpellMana = s - b\n manualPotionCnt = max 0 $ n - getMaxImmPotion cs ds secondSpellMana\n totalTime = (fromIntegral potionTime) * (fromIntegral manualPotionCnt)\n\nmain = do\n n:m:k:[] <- getInts\n x:s:[] <- getInts\n as <- ((:) x) <$> getInts\n bs <- ((:) 0) <$> getInts\n cs <- (\\l -> UA.listArray (0, k) (0:l)) <$> getInts\n ds <- (\\l -> UA.listArray (0, k) (0:l)) <$> getInts\n print $ process n s as bs cs ds\n"}, {"source_code": "-- Codeforces Round #379 (Div. 2)\n-- http://codeforces.com/contest/734\n\n-- ID: 734C (Anton and Making Potions)\n\nimport Control.Monad\nimport Data.Array\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\nmain = do\n [n, m, k] <- getInt64s\n [x, s] <- getInt64s\n as <- (listArray (0, m-1)) `fmap` getInt64s\n bs <- (listArray (0, m-1)) `fmap` getInt64s\n cs <- (listArray (0, k-1)) `fmap` getInt64s\n ds <- (listArray (0, k-1)) `fmap` getInt64s\n let ub = upperBound ds k s\n let freePotion = cs ! (ub - 1)\n let noFirst = if ub > 0 then (max (n - freePotion) 0) * x else n * x\n let bestUsingFirst = minimum $ map (make as bs cs ds n k s) [0..m-1]\n print $ min noFirst bestUsingFirst\n\nmake as bs cs ds n k s i\n | ub == 0 || bs ! i > s = maxBound :: Int64\n | otherwise = (max 0 remain) * (as ! i)\n where\n remain = n - (cs ! (ub - 1))\n ub = upperBound ds k (s - bs ! i)\n\n\nupperBound :: Array Int64 Int64 -> Int64 -> Int64 -> Int64\nupperBound ary n x = go 0 n where\n go lb ub\n | lb >= ub = ub\n | ary ! mid <= x = go (mid+1) ub\n | ary ! mid > x = go lb mid\n where mid = (lb + ub) `div` 2\n"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\n\nbs :: Array Int Int -> Int -> Int -> Int\nbs v n x = go 0 n where\n go st dr\n | st>=dr = dr - 1\n | v ! mid <= x = go (mid+1) dr\n | v ! mid > x = go st mid\n where mid = div (st + dr) 2\n\n\nmain = do\n [n,m,k] <- fast_read_Int\n [x,s] <- fast_read_Int\n a <- fmap (listArray (0,m-1)) fast_read_Int\n b <- fmap (listArray (0,m-1)) fast_read_Int\n c <- fmap (listArray (0,k-1)) fast_read_Int\n d <- fmap (listArray (0,k-1)) fast_read_Int\n let fara_1 = bs d k s \n let nr_fara_1 = c ! fara_1\n let initial = if fara_1 >= 0 then (max (n - nr_fara_1) 0) * x else n * x\n\n let f i = g i where\n g i\n | s < b ! i = maxBound :: Int\n | otherwise = (max 0 (n - maxp)) * (a ! i)\n where \n maxp = if binary_search >=0 then c ! binary_search else 0\n binary_search = bs d k (s- b ! i)\n\n\n let _for_ = minimum $ map f [0..m-1]\n \n print $ min initial _for_"}, {"source_code": "\nimport Control.Monad\nimport Data.Array\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int]\n\nbs :: Array Int Int -> Int -> Int -> Int\nbs v n x = go 0 n where\n go st dr\n | st>=dr = dr - 1\n | v ! mid <= x = go (mid+1) dr\n | v ! mid > x = go st mid\n where mid = div (st + dr) 2\n\n\nmain = do\n [n,m,k] <- fast_read_Int\n [x,s] <- fast_read_Int\n a <- fmap (listArray (0,m-1)) fast_read_Int\n b <- fmap (listArray (0,m-1)) fast_read_Int\n c <- fmap (listArray (0,k-1)) fast_read_Int\n d <- fmap (listArray (0,k-1)) fast_read_Int\n let fara_1 = bs d k s \n let initial = if fara_1 >= 0 then (max (n - c ! fara_1) 0) * x else n * x\n\n let f i = g i where\n g i\n | s < b ! i = maxBound :: Int\n | otherwise = (max 0 (n - maxp)) * (a ! i)\n where \n maxp = if binary_search >=0 then c ! binary_search else 0\n binary_search = bs d k (s- b ! i)\n\n\n let _for_ = minimum $ map f [0..m-1]\n \n print $ min initial _for_"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextInteger :: Tokenizer Integer\nnextInteger = state $ \\(s:ss) -> case L.readInteger s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Integer:\" ++ (show s)\n\nf :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Integer\nf n x s c d | i < 0 = n * x\n | otherwise = (max 0 (n - c!i)) * x\n where i = bs (-1) (snd $ bounds c) + 1\n bs l r | r - l == 1 = l\n | d!m <= s = bs m r\n | otherwise = bs l m\n where m = (l + r) `div` 2\n\nsolve :: Integer -> Integer -> Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Array Int Integer -> Integer\nsolve n x s a b c d = foldl min (f n x s c d) [a!i + f (n - 1) (a!i) (s - b!i) c d | i <- [0..snd $ bounds a], s >= b!i]\n\ndoit :: Tokenizer Integer\ndoit = do\n n <- nextInteger\n m <- nextInt\n k <- nextInt\n x <- nextInteger\n s <- nextInteger\n a <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger\n b <- liftM (listArray (0, m - 1)) $ replicateM m nextInteger\n c <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger\n d <- liftM (listArray (0, k - 1)) $ replicateM k nextInteger\n return $ solve n x s a b c d\n\nmain = do\n contents <- L.getContents\n print $ evalState doit (L.words contents)\n"}], "src_uid": "2f9f2bdf059e5ab9c64e7b5f27cba0cb"} {"source_code": "import Data.List\nimport GHC.Exts\nsolve [[_, ll,x,y], l] = case (can x, can y, can $ x+y, can $ abs $ x-y) of\n (_:_,_:_,_,_) -> [[0]]\n ([],[],[],[]) -> [[2],[x,y]]\n (_:_,_,_,_) -> [[1],[y]]\n (_,_:_,_,_) -> [[1],[x]]\n (_,_,s:_,_) -> [[1],[s+y]]\n (_,_,_,ss) -> case filter (<=ll) [s+max x y | s<-ss] ++ filter (>=0) [s-min x y | s<-ss] of\n h:_ -> [[1],[h]]\n [] -> [[2],[x,y]]\n where can x = map head $ filter ((>1).length) $ group $ sort $ l ++ map (subtract x) l \n\nmain = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines\n", "positive_code": [{"source_code": "import qualified Data.Set as Set\nmain=interact$solve.map read.words\nsolve (_:l:x:y:xs)\n\t| find1<=l && find2<=l = \"0\"\n\t| find1<=l = \"1\\n\" ++ show y\n\t| find2<=l = \"1\\n\" ++ show x\n\t| find3<=l = \"1\\n\" ++ show (find3+x)\n\t| find4<=l && find4+yx = \"1\\n\" ++ show (find5-x)\n\t| otherwise = \"2\\n\"++show x++\" \"++show y\n\twhere hs=Set.fromList xs\n\t find x xs \n\t\t| null xs = l+1\n\t\t| Set.member (head xs + x) hs = head xs\n\t\t| otherwise = find x $ tail xs\n\t find1=find x xs\n find2=find y xs\n\t find3=find (y+x) xs\n\t find4=find (y-x) xs\n\t find5=find (y-x) $ reverse xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nlist :: b -> ([a] -> b) -> [a] -> b\nlist x f xs=case xs of{[]->x;_->f xs}\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n nlxy <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n case solve nlxy xs of\n ps -> do\n print $ length ps\n putStr.unwords.map show $ ps\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [n,l,x,y] xs\n | okX && okY = []\n | okX = [y]\n | okY = [x]\n | otherwise = case filter (\\k->0 [x,y]\n (res:_) -> [res]\n where\n !set = IS.fromList xs\n !okX = or [IS.member (v+x) set | v<-xs]\n !okY = or [IS.member (v+y) set | v<-xs]\n !cap = IS.unions\n [IS.intersection (IS.map (subtract x) set) (IS.map (subtract y) set)\n ,IS.intersection (IS.map (subtract x) set) (IS.map (+y) set)\n ,IS.intersection (IS.map (+x) set) (IS.map (subtract y) set)\n ,IS.intersection (IS.map (+x) set) (IS.map (+y) set)\n ]\n"}], "negative_code": [{"source_code": "import qualified Data.Set as Set\nmain=interact$solve.map read.words\nsolve (_:l:x:y:xs)\n\t| find1<=l && find2<=l = \"0\"\n\t| find1<=l = \"1\\n\" ++ show (find1+y)\n\t| find2<=l = \"1\\n\" ++ show (find2+x)\n\t| find3<=l = \"1\\n\" ++ show (find3+x)\n\t| find4<=l && find4+yx = \"1\\n\" ++ show (find5-x)\n\t| otherwise = \"2\\n\"++show x++\" \"++show y\n\twhere hs=Set.fromList xs\n\t find x xs \n\t\t| null xs = l+1\n\t\t| Set.member (head xs + x) hs = head xs\n\t\t| otherwise = find x $ tail xs\n\t find1=find x xs\n find2=find y xs\n\t find3=find (y+x) xs\n\t find4=find (y-x) xs\n\t find5=find (y-x) $ reverse xs\n"}, {"source_code": "import qualified Data.Set as Set\nmain=interact$solve.map read.words\nsolve (_:l:x:y:xs)\n\t| find1<=l && find2<=l = \"0\"\n\t| find1<=l = \"1\\n\" ++ show (find1+x)\n\t| find2<=l = \"1\\n\" ++ show (find2+y)\n\t| find3<=l = \"1\\n\" ++ show (find3+x)\n\t| find4<=l && find4+y [[0]]\n ([],[],[],[]) -> [[2],[x,y]]\n ([_],_,_,_) -> [[1],[y]]\n (_,[_],_,_) -> [[1],[x]]\n (_,_,[s],_) -> [[1],[s+y]]\n (_,_,_,[s]) | s+max x y <= ll -> [[1],[s+max x y]]\n | s-min x y >= 0 -> [[1],[s-min x y]]\n | otherwise -> [[2],[x,y]]\n where can x = take 1 $ drop 1 $ head $ sortWith (negate.length) $ group $ sort $ l ++ map (subtract x) l \n\nmain = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nlist :: b -> ([a] -> b) -> [a] -> b\nlist x f xs=case xs of{[]->x;_->f xs}\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n nlxy <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n case solve nlxy xs of\n ps -> do\n print $ length ps\n putStr.unwords.map show $ ps\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [n,l,x,y] xs\n | IS.member x set && IS.member y set = []\n | otherwise = go xs\n where\n !set = IS.fromList xs\n go (v:vs)\n | IS.member (v+x) set && IS.member y set = []\n | IS.member (v+y) set && IS.member x set = []\n | otherwise = go vs\n go []\n | IS.member x set = [y]\n | IS.member y set = [x]\n | otherwise = [x,y]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nlist :: b -> ([a] -> b) -> [a] -> b\nlist x f xs=case xs of{[]->x;_->f xs}\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n nlxy <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n case solve nlxy xs of\n ps -> do\n print $ length ps\n putStr.unwords.map show $ ps\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [n,l,x,y] xs\n | IS.member x set && IS.member y set = []\n | otherwise = go xs\n where\n !d = y - x\n !set = IS.fromList xs\n go (v:vs)\n | IS.member (v+d) set = []\n | IS.member (v+x) set && IS.member y set = []\n | IS.member (v+y) set && IS.member x set = []\n | otherwise = go vs\n go []\n | IS.member x set = [y]\n | IS.member y set = [x]\n | otherwise = [x,y]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nlist :: b -> ([a] -> b) -> [a] -> b\nlist x f xs=case xs of{[]->x;_->f xs}\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n nlxy <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n case solve nlxy xs of\n ps -> do\n print $ length ps\n putStr.unwords.map show $ ps\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [n,l,x,y] xs\n | okX && okY = []\n | okX = [y]\n | okY = [x]\n | otherwise = case filter (>=0) $ IS.toList cap of\n [] -> [x,y]\n (res:_) -> [res]\n where\n !set = IS.fromList xs\n !okX = or [IS.member (v+x) set | v<-0:xs]\n !okY = or [IS.member (v+y) set | v<-0:xs]\n !cap = IS.intersection (IS.map (subtract x) set) (IS.map (subtract y) set)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nlist :: b -> ([a] -> b) -> [a] -> b\nlist x f xs=case xs of{[]->x;_->f xs}\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n nlxy <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n case solve nlxy xs of\n ps -> do\n print $ length ps\n putStr.unwords.map show $ ps\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve [n,l,x,y] xs\n | okX && okY = []\n | okX = [y]\n | okY = [x]\n | otherwise = case IS.toList cap of\n [] -> [x,y]\n (res:_) -> [res]\n where\n !set = IS.fromList xs\n !okX = or [IS.member (v+x) set | v<-0:xs]\n !okY = or [IS.member (v+y) set | v<-0:xs]\n !cap = IS.intersection (IS.map (subtract x) set) (IS.map (subtract y) set)\n"}], "src_uid": "333790c28eb02ad568a2406d5b2fafa6"} {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = (Int,IOUArray Int Int, IOUArray Int Int, IOUArray Int Int, IOUArray Int Int)\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\nparse :: IO Domain\nparse = do\n [number] <- readChar8\n lst <- readChar8\n xs <- newListArray (1, number) lst\n dp <- newArray (1, number) maxBound\n pd <- newArray (1, number) minBound\n ans <- newArray (1, number+1) 0\n return (number, xs, dp, pd, ans)\n\n-- showArray ans = print =<< getElems ans\n\nsolve :: Solver\nsolve (size, lst, dp, pd, ans) = do \n result\n where \n result = fmap sum $ mapM go $ reverse [1.. size] \n go :: Int -> IO Int\n go index = do \n sa maxBound minBound index \n s <- readArray ans (index+1)\n writeArray ans index (s+1)\n -- showArray ans\n return (s+1)\n sa :: Int -> Int -> Int -> IO ()\n sa a b i \n | a == minBound && b == maxBound = writeArray ans i 0 \n | i == size = return ()\n | otherwise = do\n x <- readArray lst i\n y <- readArray lst (i+1)\n let a1 = if (b < y) then x else minBound\n let a2 = if (x < y) then (max a1 a) else a1\n let b1 = if (a > y) then x else maxBound\n let b2 = if (x > y) then (min b1 b) else b1\n a3 <- readArray dp i\n b3 <- readArray pd i\n when (a3 /= a2 || b3 /= b2) \n (do \n writeArray dp i a2 \n writeArray pd i b2\n sa a2 b2 (i+1) \n s <- readArray ans (i+1) \n writeArray ans i (s+1))\n\n\nmain :: IO ()\nmain = do\n printAns =<< solve =<< parse\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, foldrM)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = (Int,IOUArray Int Int, IOUArray Int Int, IOUArray Int Int, IOUArray Int Int)\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\nparse :: IO Domain\nparse = do\n [number] <- readChar8\n lst <- readChar8\n xs <- newListArray (1, number) lst\n dp <- newArray (1, number) maxBound\n pd <- newArray (1, number) minBound\n ans <- newArray (1, number+1) 0\n return (number, xs, dp, pd, ans)\n\n-- showArray ans = print =<< getElems ans\n\nsolve :: Solver\nsolve (size, lst, dp, pd, ans) = do \n result\n where \n result = foldrM go 0 $ [1.. size] \n go :: Int -> Int -> IO Int\n go index x = do \n sa maxBound minBound index \n s <- readArray ans (index+1)\n writeArray ans index (s+1)\n return (x+s+1)\n sa :: Int -> Int -> Int -> IO ()\n sa a b i \n | a == minBound && b == maxBound = writeArray ans i 0 \n | i == size = return ()\n | otherwise = do\n x <- readArray lst i\n y <- readArray lst (i+1)\n let a1 = if (b < y) then x else minBound\n let a2 = if (x < y) then (max a1 a) else a1\n let b1 = if (a > y) then x else maxBound\n let b2 = if (x > y) then (min b1 b) else b1\n a3 <- readArray dp i\n b3 <- readArray pd i\n when (a3 /= a2 || b3 /= b2) \n (do \n writeArray dp i a2 \n writeArray pd i b2\n sa a2 b2 (i+1) \n s <- readArray ans (i+1) \n writeArray ans i (s+1))\n\n\nmain :: IO ()\nmain = do\n printAns =<< solve =<< parse\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = (Int,IOUArray Int Int, IOUArray Int Int, IOUArray Int Int, IOUArray Int Int)\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = print \n\nparse :: IO Domain\nparse = do\n [number] <- readChar8\n lst <- readChar8\n xs <- newListArray (1, number) lst\n dp <- newArray (1, number) maxBound\n pd <- newArray (1, number) minBound\n ans <- newArray (1, number+1) 0\n return (number, xs, dp, pd, ans)\n\n-- showArray ans = print =<< getElems ans\n\nsolve :: Solver\nsolve (size, lst, dp, pd, ans) = do \n result\n where \n result = foldM go 0 $ reverse [1.. size] \n go :: Int -> Int -> IO Int\n go x index = do \n sa maxBound minBound index \n s <- readArray ans (index+1)\n writeArray ans index (s+1)\n return (x+s+1)\n sa :: Int -> Int -> Int -> IO ()\n sa a b i \n | a == minBound && b == maxBound = writeArray ans i 0 \n | i == size = return ()\n | otherwise = do\n x <- readArray lst i\n y <- readArray lst (i+1)\n let a1 = if (b < y) then x else minBound\n let a2 = if (x < y) then (max a1 a) else a1\n let b1 = if (a > y) then x else maxBound\n let b2 = if (x > y) then (min b1 b) else b1\n a3 <- readArray dp i\n b3 <- readArray pd i\n when (a3 /= a2 || b3 /= b2) \n (do \n writeArray dp i a2 \n writeArray pd i b2\n sa a2 b2 (i+1) \n s <- readArray ans (i+1) \n writeArray ans i (s+1))\n\n\nmain :: IO ()\nmain = do\n printAns =<< solve =<< parse\n"}], "negative_code": [], "src_uid": "669a34bfb07b82cfed8abccd8ab25f1e"} {"source_code": "import Data.List\r\nimport qualified Data.Set as Set\r\n\r\nmodulo :: Int\r\nmodulo = 1000000007\r\n\r\ndata State = State { left :: Int, right :: Int, fix :: Int }\r\ndata PermElement = PermElement { el :: Int, pos :: Int } deriving (Ord, Eq)\r\ndata TraverseHelperResult = TraverseHelperResult { multiplier :: Int, addfx :: Int }\r\n\r\ntraversePermutation :: [PermElement] -> State -> Int\r\ntraversePermutation [] state = 1\r\ntraversePermutation (head:permelements) (State {left = sleft, right = sright, fix = sfix})\r\n | pos head < sleft || pos head > sright = (let helperRes = (traverseHelper permelements (State (min sleft $ pos head) (max sright $ pos head) $ sfix + 1)) in (multiplier helperRes) * (traversePermutation permelements (State (min sleft $ pos head) (max sright $ pos head) (addfx helperRes))) `mod` modulo)\r\n | otherwise = traversePermutation permelements $ State sleft sright sfix\r\n\r\ntraverseHelper :: [PermElement] -> State -> TraverseHelperResult\r\ntraverseHelper [] state = TraverseHelperResult 1 $ fix state\r\ntraverseHelper (head:permelements) (State {left = sleft, right = sright, fix = sfix})\r\n | sleft <= (pos head) && (pos head) <= sright = (let subres = (traverseHelper permelements $ State sleft sright (sfix + 1)) in TraverseHelperResult ((sright - sleft + 1 - sfix) * (multiplier subres) `mod` modulo) (addfx subres))\r\n | otherwise = TraverseHelperResult 1 sfix\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n line_n <- getLine\r\n let n = read line_n :: Int\r\n line_arr <- getLine\r\n let arr = map (\\x -> (read x :: Int)) $ words line_arr\r\n let sarr = sort [PermElement x i | (x, i) <- zip arr [0..n - 1]] in putStrLn $ show $ traversePermutation (tail sarr) (State (pos (head sarr)) (pos (head sarr)) 1)\r\n \r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n--\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n\nm :: Int64\n-- m = 998_244_353\nm = 10 ^ 9 + 7\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\nmI :: Int -> M\nmI = M . fromIntegral\n\ninstance Show M where \n show (M v) = \"M\" ++ show v\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = M $ (a * b) `mod` m\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> [Int] -> Int64\nsolve n as = unM $ solve' 0 (n + 1, -1) iAs\n where\n iAs = sort $ zip as [1 .. n]\n\n solve' :: Int -> (Int, Int) -> [(Int, Int)] -> M\n solve' _ _ [] = M 1\n solve' k is@(minI, maxI) iAs@((a, i):otherIas) = \n if minI <= i && i <= maxI\n then cnt * solve' (k + 1) is otherIas\n else solve' (k + 1) (min minI i, max maxI i) otherIas\n where\n cntPlaces = maxI - minI - k + 1\n cnt = M $ fromIntegral cntPlaces\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%lld\\n\" answer\n"}, {"source_code": "import Data.List\r\n\r\nmodulo :: Int\r\nmodulo = 1000000007\r\n\r\ndata State = State { left :: Int, right :: Int, fix :: Int }\r\ndata PermElement = PermElement { el :: Int, pos :: Int } deriving (Ord, Eq)\r\ndata TraverseHelperResult = TraverseHelperResult { multiplier :: Int, addfx :: Int }\r\n\r\ntraversePermutation :: [PermElement] -> State -> Int\r\ntraversePermutation [] state = 1\r\ntraversePermutation (head:permelements) (State {left = sleft, right = sright, fix = sfix})\r\n | pos head < sleft || pos head > sright = (let helperRes = (traverseHelper permelements (State (min sleft $ pos head) (max sright $ pos head) $ sfix + 1)) in (multiplier helperRes) * (traversePermutation permelements (State (min sleft $ pos head) (max sright $ pos head) (addfx helperRes))) `mod` modulo)\r\n | otherwise = traversePermutation permelements $ State sleft sright sfix\r\n\r\ntraverseHelper :: [PermElement] -> State -> TraverseHelperResult\r\ntraverseHelper [] state = TraverseHelperResult 1 $ fix state\r\ntraverseHelper (head:permelements) (State {left = sleft, right = sright, fix = sfix})\r\n | sleft <= (pos head) && (pos head) <= sright = (let subres = (traverseHelper permelements $ State sleft sright (sfix + 1)) in TraverseHelperResult ((sright - sleft + 1 - sfix) * (multiplier subres) `mod` modulo) (addfx subres))\r\n | otherwise = TraverseHelperResult 1 sfix\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n-- line_n <- getLine\r\n n <- fmap read getLine :: IO Int\r\n arr <- fmap (map read . words) getLine :: IO [Int]\r\n let sarr = sort [PermElement x i | (x, i) <- zip arr [0..n - 1]] in putStrLn $ show $ traversePermutation (tail sarr) (State (pos (head sarr)) (pos (head sarr)) 1)\r\n \r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)"}], "negative_code": [], "src_uid": "a58ad54eaf4912f530a7d25a503640d3"} {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\n--import qualified Data.HashTable.IO as B\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\n\n\nmain :: IO ()\nmain = do\n n:_ <- readInts\n input <- readInts\n let list = map (\\x -> fromIntegral . length . flatten $ x ::Int64) . components $ buildG (1,n) $ zip [1..n] input\n if null $ tail list\n then print $ (head list)^2\n else\n let max1 = maximum list\n list1= list\\\\[max1]\n max2 = maximum list1\n in print $ (max1+max2)^2 - max2^2 + (foldl' (+) 0 . map (^2) $ list1)\n\n{-main :: IO ()\nmain = do\n print 3\n where gg=H.fromList-}", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Graph\nimport Data.List (sort)\nimport Data.Tree\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ndata Metro = Metro { next :: [Int] } deriving (Show, Eq)\n\ntreeSize :: Tree a -> Int\ntreeSize node = succ . sum $ map treeSize (subForest node)\n\ngetCirclesSizes :: Metro -> [Int]\ngetCirclesSizes (Metro ps) = map treeSize $ dfs graph [0 .. n - 1]\n where n = length (ps)\n edges = zip [0 ..] (map pred ps)\n graph = buildG (0, n - 1) edges\n\nsolve :: Metro -> Integer\nsolve m = case sizes of\n [x] -> sqr x\n (x:y:zs) -> sum $ map sqr (x + y:zs)\n where sizes = map fromIntegral . reverse . sort $ getCirclesSizes m\n sqr x = x * x\n\ntest0 = Metro [2, 1, 3]\ntest1 = Metro [1, 5, 4, 3, 2]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (L.unpack s)\n\ngo :: Tokenizer Integer\ngo = do\n n <- nextInt\n ps <- replicateM n nextInt\n return . solve $ Metro ps\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n let result = evalState go input\n print result\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Graph\nimport Data.List (sort)\nimport Data.Tree\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ndata Metro = Metro { next :: [Int] } deriving (Show, Eq)\n\ntreeSize :: Tree a -> Int\ntreeSize = length . flatten\n\ngetCirclesSizes :: Metro -> [Int]\ngetCirclesSizes (Metro ps) = map treeSize $ dfs graph [0 .. n - 1]\n where n = length (ps)\n edges = zip [0 ..] (map pred ps)\n graph = buildG (0, n - 1) edges\n\nsolve :: Metro -> Integer\nsolve m = case sizes of\n [x] -> sqr x\n (x:y:zs) -> sum $ map sqr (x + y:zs)\n where sizes = map fromIntegral . reverse . sort $ getCirclesSizes m\n sqr x = x * x\n\ntest0 = Metro [2, 1, 3]\ntest1 = Metro [1, 5, 4, 3, 2]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (L.unpack s)\n\ngo :: Tokenizer Integer\ngo = do\n n <- nextInt\n ps <- replicateM n nextInt\n return . solve $ Metro ps\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n let result = evalState go input\n print result\n"}, {"source_code": "import Data.Graph\nimport Data.Foldable(Foldable(foldl'))\nimport Data.Int\nimport Data.List(sortBy)\nmain = getContents >>= print . exec\nexec = solve . map read . words\nsolve (n:xs) = case sortBy (flip compare) $ map (foldl' (\\l _ -> l + 1) 0) $ scc $ buildG (1, n) $ zip [1..] xs of\n (a:b:as) -> sum $ map (\\x -> fromIntegral x ^ 2 :: Int64) $ (a + b):as\n [a] -> fromIntegral $ a^2"}], "negative_code": [{"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\n--import qualified Data.HashTable.IO as B\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nmain :: IO ()\nmain = do\n n:_ <- readInts\n input <- readInts\n let list = map (length.flatten) . components $ buildG (1,n) $ zip [1..n] input\n if null $ tail list\n then print $ n*n\n else\n let max1 = maximum list ::Int\n list1= list\\\\[max1]\n max2 = maximum list1 ::Int\n in print $ (max1+max2)^2 - max2^2 + (foldl' (+) 0 . map (^2) $ list1)\n\n{-main :: IO ()\nmain = do\n print 3\n where gg=H.fromList-}"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\n--import qualified Data.HashTable.IO as B\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row\n\nmain :: IO ()\nmain = do\n n:_ <- readInts\n input <- readInts\n let list = map (length.flatten) . components $ buildG (1,n) $ zip [1..n] input\n if null $ tail list\n then print $ n*n\n else\n let max1 = maximum list\n list1= list\\\\[max1]\n max2 = maximum list1\n in print $ (max1+max2)^2 - max2^2 + (foldl' (+) 0 . map (^2) $ list1)\n\n{-main :: IO ()\nmain = do\n print 3\n where gg=H.fromList-}"}], "src_uid": "ad9fd71025c5f91cece740ea95b0eb6f"} {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n [a,b,c,d] <- map read . words <$> getLine\n [x,y,x1,y1,x2,y2] <- map read . words <$> getLine\n if b - a > x2 - x ||\n b - a < x1 - x ||\n d - c > y2 - y ||\n d - c < y1 - y ||\n (a > 0 || b > 0) && x2 - x1 == 0 ||\n (c > 0 || d > 0) && y2 - y1 == 0 then\n putStrLn \"No\"\n else\n putStrLn \"Yes\"", "positive_code": [{"source_code": "type Point = (Int, Int)\n\nsolve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool\nsolve (inix, iniy) (lbx, lby) (rtx, rty) a b c d = x >= lbx && x <= rtx && lby <= y && y <= rty &&\n cornerCase (inix, iniy) (lbx, lby) (rtx, rty) a b c d\n where x = inix - a + b\n y = iniy - c + d\n\n\ncornerCase :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool\ncornerCase (inix, iniy) (lbx, lby) (rtx, rty) a b c d\n | inix == lbx && inix == rtx = a == 0 && b == 0 && if iniy == lby && iniy == rty then c == 0 && d == 0 else True\n | iniy == lby && iniy == rty = c == 0 && d == 0 && if inix == lbx && inix == rtx then a == 0 && b == 0 else True\n | otherwise = True\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))\n\nreadInt :: String -> Int\nreadInt a = read a :: Int\n\nparse :: [String] -> String\nparse [fstLine, sndLine]\n | solve (x, y) (x1, y1) (x2, y2) a b c d = \"YES\"\n | otherwise = \"NO\"\n where [a, b, c, d] = map readInt $ words fstLine\n [x, y, x1, y1, x2, y2] = map readInt $ words sndLine\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n"}, {"source_code": "type Point = (Int, Int)\n\nsolve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool\nsolve (inix, iniy) (lbx, lby) (rtx, rty) a b c d\n | inix == lbx && inix == rtx = a == 0 && b == 0 && if iniy == lby && iniy == rty then c == 0 && d == 0 else lby <= y && y <= rty\n | iniy == lby && iniy == rty = c == 0 && d == 0 && if inix == lbx && inix == rtx then a == 0 && b == 0 else x >= lbx && x <= rtx\n | otherwise = x >= lbx && x <= rtx && lby <= y && y <= rty\n where x = inix - a + b\n y = iniy - c + d\n\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))\n\nreadInt :: String -> Int\nreadInt a = read a :: Int\n\nparse :: [String] -> String\nparse [fstLine, sndLine]\n | solve (x, y) (x1, y1) (x2, y2) a b c d = \"YES\"\n | otherwise = \"NO\"\n where [a, b, c, d] = map readInt $ words fstLine\n [x, y, x1, y1, x2, y2] = map readInt $ words sndLine\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n"}, {"source_code": "main = getLine >>= test.read\ntest 0 = return ()\ntest t = do\n (a:b:c:d:_) <- map read.words <$> getLine\n (x:y:x1:y1:x2:y2:_) <- map read.words <$> getLine\n let x' = x + b - a\n y' = y + d - c\n if x1 <= x' && x' <= x2 && y1 <= y' && y' <= y2 && (x1 /= x2 || (a == 0 && b == 0)) && (y1 /= y2 || (c == 0 && d == 0))\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n test $ pred t"}], "negative_code": [{"source_code": "type Point = (Int, Int)\n\n-- solve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool\nsolve (iniX, iniY) (lbX, lbY) (rtX, rtY) a b c d\n | iniX == lbX && iniX == rtX = a == 0 && b == 0 && if iniY == lbY && iniY == rtY then c == 0 && d == 0 else True\n | iniY == lbY && iniY == rtY = c == 0 && d == 0 && if iniX == lbX && iniX == rtX then a == 0 && b == 0 else True\n | otherwise = x >= lbX && x <= rtX && lbY <= y && y <= rtY\n where x = iniX - a + b\n y = iniY - c + d\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))\n\nparse :: [String] -> String\nparse [fstLine, sndLine]\n | solve (x, y) (x1, y1) (x2, y2) a b c d = \"YES\"\n | otherwise = \"NO\"\n where [a, b, c, d] = map (\\x -> read x :: Int) $ words fstLine\n [x, y, x1, y1, x2, y2] = map (\\x -> read x :: Int) $ words sndLine\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n"}, {"source_code": "type Point = (Int, Int)\n\nsolve :: Point -> Point -> Point -> Int -> Int -> Int -> Int -> Bool\nsolve (iniX, iniY) (lbX, lbY) (rtX, rtY) a b c d\n | iniX == lbX && iniX == rtX = a == 0 && b == 0\n | iniY == lbY && iniY == rtY = c == 0 && d == 0\n | otherwise = x >= lbX && x <= rtX && lbY <= y && y <= rtY\n where x = iniX - a + b\n y = iniY - c + d\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (take n arr):(groupByNLines n (drop n arr))\n\nparse :: [String] -> String\nparse [fstLine, sndLine]\n | solve (x, y) (x1, y1) (x2, y2) a b c d = \"YES\"\n | otherwise = \"NO\"\n where [a, b, c, d] = map (\\x -> read x :: Int) $ words fstLine\n [x, y, x1, y1, x2, y2] = map (\\x -> read x :: Int) $ words sndLine\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n"}], "src_uid": "7224ffd4776af4129739e1b28f696050"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (< '-'))\n <$> BS.getLine :: IO (UArray Int Int64)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE process #-}\n process = BSL.readInt . BSL.dropWhile (< '-')\n domcods :: UArray Int Int\n domcods = A.listArray (0, 2*n - 3) $ unfoldr process bstr\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, False)\n GT -> (maxSum, maxSumHere, numCompo, countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, False)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, True)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n (cntE, cods) <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BSL.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int ->\n UArray Int Int-> (Int64,Int)\nquery n as cntE cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, numCompo, countable_) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, maxSumHere <= 0)\n GT -> (maxSum, maxSumHere, numCompo, maxSumHere <= 0 || countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, maxSum <= 0)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, numCompo, cntbl)\n !(!msum, !sumsub, cmp, cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, cnt)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (< '-'))\n <$> BS.getLine :: IO (UArray Int Int64)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE process #-}\n process = BSL.readInt . BSL.dropWhile (< '-')\n domcods :: UArray Int Int\n domcods = A.listArray (0, 2*n - 3) $ unfoldr process bstr\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, retSum, 1, nonpos)\n GT -> (maxSum, retSum, numCompo, countable')\n EQ | countable -> (maxSum, retSum, 1 + numCompo, nonpos)\n | otherwise -> (maxSum, retSum, numCompo, False)\n where\n !(!retSum, !countable', !nonpos)\n | maxSumHere > 0 = (maxSumHere, countable, False)\n | otherwise = (0, True, True)\n {-# INLINE maxSumHere #-}\n !maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case compare maxSum msum of\n GT -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n LT -> (msum, sumsub + sumCh, cmp, cnt )\n EQ -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> Array Int ListInt\npreprocess n bstr = runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n !lls <- A.readArray arr l\n A.writeArray arr l $ Cons r lls\n !rls <- A.readArray arr r\n A.writeArray arr r $ Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BSL.ByteString -> Array Int ListInt\npreprocess n bstr = runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n !lls <- A.readArray arr l\n A.writeArray arr l $ Cons r lls\n !rls <- A.readArray arr r\n A.writeArray arr r $ Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE processLine #-}\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable_) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, maxSumHere <= 0)\n GT -> (maxSum, maxSumHere, numCompo, maxSumHere <= 0 || countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, maxSum <= 0)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, cnt)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> Array Int ListInt\npreprocess n = \\bstr -> runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n lls <- A.readArray arr l\n A.writeArray arr l $! Cons r lls\n rls <- A.readArray arr r\n A.writeArray arr r $! Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, numCompo, countable_) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, maxSumHere <= 0)\n GT -> (maxSum, maxSumHere, numCompo, maxSumHere <= 0 || countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, maxSum <= 0)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n (!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, cnt)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n{-\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\ !(!x0,!x1) !(!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n-}\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n (cntE, cods) <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n {-# INLINE processLine #-}\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int ->\n UArray Int Int-> (Int64,Int)\nquery n as cntE cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, False)\n GT -> (maxSum, maxSumHere, numCompo, countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, False)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, True)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (< '-'))\n <$> BS.getLine :: IO (UArray Int Int64)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE process #-}\n process = BSL.readInt . BSL.dropWhile (< '-')\n domcods :: UArray Int Int\n domcods = A.listArray (0, 2*n - 3) $ unfoldr process bstr\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, retSum, 1, nonpos)\n GT -> (maxSum, retSum, numCompo, countable')\n EQ | countable -> (maxSum, retSum, 1 + numCompo, nonpos)\n | otherwise -> (maxSum, retSum, numCompo, False)\n where\n (retSum, countable', nonpos)\n | maxSumHere > 0 = (maxSumHere, countable, False)\n | otherwise = (0, True, True)\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case compare maxSum msum of\n GT -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n LT -> (msum, sumsub + sumCh, cmp, cnt )\n EQ -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n (cntE, cods) <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n {-# INLINE processLine #-}\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int ->\n UArray Int Int-> (Int64,Int)\nquery n as cntE cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable_) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, maxSumHere <= 0)\n GT -> (maxSum, maxSumHere, numCompo, maxSumHere <= 0 || countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, maxSum <= 0)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, cnt)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n (cntE, cods) <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> UArray Int Int -> (Int64,Int)\nquery n as cntE cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> Array Int ListInt\npreprocess n = \\bstr -> runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n lls <- A.readArray arr l\n A.writeArray arr l $! Cons r lls\n rls <- A.readArray arr r\n A.writeArray arr r $! Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, numCompo, countable_) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, maxSumHere <= 0)\n GT -> (maxSum, maxSumHere, numCompo, maxSumHere <= 0 || countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, maxSum <= 0)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, cnt)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n{-\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\ !(!x0,!x1) !(!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n-}\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE processLine #-}\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, False)\n GT -> (maxSum, maxSumHere, numCompo, countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, False)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, True)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BSL.ByteString -> Array Int ListInt\npreprocess n bstr = runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n lls <- A.readArray arr l\n A.writeArray arr l $! Cons r lls\n rls <- A.readArray arr r\n A.writeArray arr r $! Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.array (1,n) . unfoldr processInt . (1,)\n <$> BS.getLine :: IO (UArray Int Int)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n where\n {-# INLINE processInt #-}\n processInt = \\(!i,!bs) -> do\n (!e,!bs1) <- BS.readInt $ BS.dropWhile (< '-') bs\n return $! ((i,e),(i+1,bs1))\n\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE processInt #-}\n processInt = \\(!i,!bs) -> do\n (!e,!bs1) <- BSL.readInt $ BSL.dropWhile (< '-') bs\n return $! ((i,e),(i+1,bs1))\n -- domcods :: UArray Int Int\n -- domcods = A.array (0, 2*n - 3) $ unfoldr processInt (0,bstr)\n codd :: UArray Int Int\n codd = runSTUArray $ do\n domcods_ <- A.newArray_ (0,2*n-3) :: ST s (STUArray s Int Int)\n forM_ (unfoldr processInt (0,bstr)) $ \\ (!i,!e) -> do\n A.writeArray domcods_ i e\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n j <- A.readArray domcods_ i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n dom <- A.readArray domcods_ i\n cod <- A.readArray domcods_ (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, retSum, 1, nonpos)\n GT -> (maxSum, retSum, numCompo, countable')\n EQ | countable -> (maxSum, retSum, 1 + numCompo, nonpos)\n | otherwise -> (maxSum, retSum, numCompo, False)\n where\n (!retSum, !countable', !nonpos)\n | maxSumHere > 0 = (maxSumHere, countable, False)\n | otherwise = (0, True, True)\n {-# INLINE maxSumHere #-}\n !maxSumHere = fromIntegral (as A.! this) + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case compare maxSum msum of\n GT -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n LT -> (msum, sumsub + sumCh, cmp, cnt )\n EQ -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent)\n $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BSL.ByteString -> Array Int ListInt\npreprocess n bstr = runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n lls <- A.readArray arr l\n A.writeArray arr l $! Cons r lls\n rls <- A.readArray arr r\n A.writeArray arr r $! Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let !(!compo_ch,!used_ch)\n = foldl' (\\ !(!x0,!x1) !(!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE process #-}\n process = BSL.readInt . BSL.dropWhile (`elem` \" \\n\\r\")\n domcods :: UArray Int Int\n domcods = A.listArray (0, 2*n - 3) $ unfoldr process bstr\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, False)\n GT -> (maxSum, maxSumHere, numCompo, countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, False)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, True)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n (cntE, cods) <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\(!i,!bs0) -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\nquery :: Int -> UArray Int Int64 -> UArray Int Int -> UArray Int Int -> (Int64,Int)\nquery n as cntE cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let (!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int64\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int64\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int64 -> Int -> Int -> ST s Int64\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.array (1,n) . unfoldr processInt . (1,)\n <$> BS.getLine :: IO (UArray Int Int)\n codd <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as codd\n putStrLn $ shows numer $ ' ' : show denom\n where\n {-# INLINE processInt #-}\n processInt = \\(!i,!bs) -> do\n (!e,!bs1) <- BS.readInt $ BS.dropWhile (< '-') bs\n return $! ((i,e),(i+1,bs1))\n\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> UArray Int Int\npreprocess n bstr = codd\n where\n {-# INLINE processInt #-}\n processInt = \\(!i,!bs) -> do\n (!e,!bs1) <- BSL.readInt $ BSL.dropWhile (< '-') bs\n return $! ((i,e),(i+1,bs1))\n domcods :: UArray Int Int\n domcods = A.array (0, 2*n - 3) $ unfoldr processInt (0,bstr)\n codd :: UArray Int Int\n codd = runSTUArray $ do\n arr <- A.newArray (0,3*n-2) 0\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n when (j < n) $ do\n x <- A.readArray arr (j+1)\n A.writeArray arr (j+1) (x+1)\n A.writeArray arr 0 (n+1)\n forM_ [1..n] $ \\ !i -> do\n x <- A.readArray arr (i-1)\n y <- A.readArray arr i\n A.writeArray arr i (x+y)\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray arr dom\n A.writeArray arr dom (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray arr cod\n A.writeArray arr cod (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int -> UArray Int Int -> (Int64,Int)\nquery n as codd = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, retSum, 1, nonpos)\n GT -> (maxSum, retSum, numCompo, countable')\n EQ | countable -> (maxSum, retSum, 1 + numCompo, nonpos)\n | otherwise -> (maxSum, retSum, numCompo, False)\n where\n (!retSum, !countable', !nonpos)\n | maxSumHere > 0 = (maxSumHere, countable, False)\n | otherwise = (0, True, True)\n {-# INLINE maxSumHere #-}\n !maxSumHere = fromIntegral (as A.! this) + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case compare maxSum msum of\n GT -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n LT -> (msum, sumsub + sumCh, cmp, cnt )\n EQ -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent)\n $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n cods <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> Array Int ListInt\npreprocess n = \\bstr -> runSTArray $ do\n arr <- A.newArray (1,n) Nil\n forM_ (unfoldr processLine bstr) $ \\ !(!l, !r) -> do\n lls <- A.readArray arr l\n A.writeArray arr l $! Cons r lls\n rls <- A.readArray arr r\n A.writeArray arr r $! Cons l rls\n return arr\n where\n {-# INLINE processLine #-}\n processLine = \\ !bs0 -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((l,r),bs2)\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> Array Int ListInt -> (Int64,Int)\nquery n as cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, numCompo, countable_) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, maxSumHere <= 0)\n GT -> (maxSum, maxSumHere, numCompo, maxSumHere <= 0 || countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, maxSum <= 0)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, numCompo, cntbl)\n !(!msum, !sumsub, cmp, cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, cnt)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cnt && cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ unfoldr (\\case\n Cons x xs -> Just (x,xs)\n Nil -> Nothing)\n $ cods A.! this\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\ndata ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil \n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . map fromIntegral . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int64)\n (cntE, cods) <- preprocess n <$> BSL.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n{-# INLINE preprocess #-}\npreprocess :: Int -> BSL.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n {-# INLINE processLine #-}\n processLine = \\ !(!i,!bs0) -> do\n (!l,!bs1) <- BSL.readInt $ BSL.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BSL.readInt $ BSL.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\ !(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\n{-# INLINE query #-}\nquery :: Int -> UArray Int Int64 -> UArray Int Int ->\n UArray Int Int-> (Int64,Int)\nquery n as cntE cods = (maxSum * fromIntegral numCompo, numCompo)\n where\n maxSum :: Int64; numCompo :: Int\n (maxSum, !sumIncl_, !numCompo, !countable) = dfs (-1) 1\n dfs :: Int -> Int -> (Int64, Int64, Int, Bool)\n dfs parent this = case (compare maxSum maxSumHere) of\n LT -> (maxSumHere, maxSumHere, 1, False)\n GT -> (maxSum, maxSumHere, numCompo, countable)\n EQ | countable -> (maxSum, maxSumHere, 1 + numCompo, True)\n | otherwise -> (maxSum, maxSumHere, numCompo, False)\n where\n {-# INLINE maxSumHere #-}\n maxSumHere = as A.! this + sumCh\n !(!maxSum, !sumCh, !numCompo, !countable)\n = foldl' folder (minBound, 0, 0, True)\n $ map (dfs this) $ children parent this\n {-# INLINE folder #-}\n folder = \\ !(!maxSum, !sumCh, !numCompo, !cntbl)\n !(!msum, !sumsub, !cmp, !cnt)\n -> case (compare maxSum msum, sumsub > 0) of\n (GT,True) -> (maxSum, sumsub + sumCh, numCompo, cntbl)\n (GT,_) -> (maxSum, sumCh, numCompo, cntbl)\n (LT,True) -> (msum, sumsub + sumCh, cmp, cnt)\n (LT,_) -> (msum, sumCh, cmp, True)\n (EQ,True) -> (msum, sumsub + sumCh, cmp + numCompo, cnt && cntbl)\n (EQ,_) -> (msum, sumCh, cmp + numCompo, cntbl)\n {-# INLINE children #-}\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int)\n (cntE, cods) <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\(!i,!bs0) -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\nquery :: Int -> UArray Int Int -> UArray Int Int -> UArray Int Int -> (Int,Int)\nquery n as cntE cods = (maxSum * numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let (!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this <= 0 && used_ch)\n maxSum :: Int\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int -> Int -> Int -> ST s Int\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int)\n (cntE, cods) <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\(!i,!bs0) -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\nquery :: Int -> UArray Int Int -> UArray Int Int -> UArray Int Int -> (Int,Int)\nquery n as cntE cods = (maxSum * numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = numCompo_dfs (-1) False 1\n numCompo_dfs :: Int -> Bool -> Int -> Int \n numCompo_dfs !parent !eqParent !this =\n let !eqThis = sumAround A.! this == maxSum\n in (if eqThis && not eqParent then (1+) else id)\n $ sum $ map (numCompo_dfs this eqThis) $ filter (/= parent)\n $ map (cods A.!) $ [cntE A.! (this-1) .. cntE A.! this - 1]\n maxSum :: Int\n maxSum = maximum $ A.elems sumAround\n sumAround :: UArray Int Int\n sumAround = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n forM_ [0 .. cntE A.! 1 - 1] $ sumAround_dfs arr 1 . (cods A.!)\n return arr\n sumSubtrees_dfs :: STUArray s Int Int -> Int -> Int -> ST s Int\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM [cntE A.! (this-1) .. cntE A.! this - 1]\n $ \\outEdge ->\n if cods A.! outEdge == parent then\n return 0\n else\n sumSubtrees_dfs arr this $ cods A.! outEdge\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n sumAround_dfs :: STUArray s Int Int -> Int -> Int -> ST s ()\n sumAround_dfs arr !parent !this = do\n sumAroundParent <- A.readArray arr parent\n sumSubtreeThis <- A.readArray arr this\n let sumAbove = sumAroundParent - max 0 sumSubtreeThis\n sumAroundThis = sumSubtreeThis + max 0 sumAbove\n A.writeArray arr this sumAroundThis\n forM_ [cntE A.! (this-1) .. cntE A.! this - 1]\n $ \\outEdge ->\n if cods A.! outEdge == parent then\n return ()\n else\n sumAround_dfs arr this $ cods A.! outEdge\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int)\n (cntE, cods) <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\(!i,!bs0) -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\nquery :: Int -> UArray Int Int -> UArray Int Int -> UArray Int Int -> (Int,Int)\nquery n as cntE cods = (maxSum * numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let (!compo_ch,!used_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not used_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, sumSubtrees A.! this > 0 && used_ch)\n maxSum :: Int\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int -> Int -> Int -> ST s Int\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n as <- A.listArray (1,n) . unfoldr (BS.readInt . BS.dropWhile (==' '))\n <$> BS.getLine :: IO (UArray Int Int)\n (cntE, cods) <- preprocess n <$> BS.getContents\n let (numer,denom) = query n as cntE cods\n putStrLn $ shows numer $ ' ' : show denom\n\n\npreprocess :: Int -> BS.ByteString -> (UArray Int Int, UArray Int Int)\npreprocess n bstr = (count, sortedCods)\n where\n processLine = \\(!i,!bs0) -> do\n (!l,!bs1) <- BS.readInt $ BS.dropWhile (`elem` \" \\n\\r\") bs0\n (!r,!bs2) <- BS.readInt $ BS.dropWhile (==' ') bs1\n return $ ((i,l,r),(i+2,bs2))\n domcods = runSTUArray $ do\n domcods <- A.newArray_ (0, 2*n - 3)\n forM_ (unfoldr processLine (0,bstr)) $ \\(!i,!l,!r) -> do\n A.writeArray domcods i l\n A.writeArray domcods (i+1) r\n return domcods\n count = runSTUArray $ do\n count <- (A.newArray (0,n) 0 :: forall s. ST s (STUArray s Int Int))\n forM_ [0..2*n-3] $ \\ !i -> do\n let j = domcods A.! i\n x <- A.readArray count j\n A.writeArray count j (x+1)\n forM_ [2..n] $ \\ !i -> do\n x <- A.readArray count (i-1)\n y <- A.readArray count i\n A.writeArray count i (x+y)\n return count\n sortedCods = runSTUArray $ do\n arr <- A.newArray_ (0,2*n-3)\n count' <- (A.thaw count :: forall s. ST s (STUArray s Int Int))\n forM_ [0,2..2*(n-2)] $ \\ !i -> do\n let dom = domcods A.! i\n cod = domcods A.! (i+1)\n j_dom <- A.readArray count' (dom-1)\n A.writeArray count' (dom-1) (j_dom+1)\n A.writeArray arr j_dom cod\n j_cod <- A.readArray count' (cod-1)\n A.writeArray count' (cod-1) (j_cod+1)\n A.writeArray arr j_cod dom\n return arr\n\nquery :: Int -> UArray Int Int -> UArray Int Int -> UArray Int Int -> (Int,Int)\nquery n as cntE cods = (maxSum * numCompo, numCompo)\n where\n numCompo :: Int\n numCompo | maxSum <= 0 = length $ filter (== maxSum) $ A.elems as\n | otherwise = let (x,!y) = numCompo_dfs (-1) 1 in x\n numCompo_dfs :: Int -> Int -> (Int,Bool) \n numCompo_dfs !parent !this\n = let (!compo_ch,!top_ch)\n = foldl' (\\(!x0,!x1) (!y0,!y1) -> (x0 + y0, x1 || y1)) (0,False)\n $ map (numCompo_dfs this) $ children parent this\n in if sumSubtrees A.! this == maxSum && not top_ch\n then\n (1 + compo_ch, True)\n else\n (compo_ch, False)\n maxSum :: Int\n maxSum = maximum $ A.elems sumSubtrees\n sumSubtrees :: UArray Int Int\n sumSubtrees = runSTUArray $ do\n arr <- A.newArray_ (1,n)\n sumSubtrees_dfs arr (-1) 1\n return arr\n sumSubtrees_dfs :: STUArray s Int Int -> Int -> Int -> ST s Int\n sumSubtrees_dfs arr !parent !this = do\n sumChildren <-\n fmap sum $ forM (children parent this) $ sumSubtrees_dfs arr this\n let ret = sumChildren + as A.! this \n A.writeArray arr this ret\n return $! max 0 ret\n children :: Int -> Int -> [Int]\n children parent this =\n filter (/= parent) $ map (cods A.!) [cntE A.! (this-1) .. cntE A.! this - 1]\n"}], "src_uid": "2a113b51334d56ba7d82dd48eb506002"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\n\nmain :: IO ()\nmain = do\n [_, t] <- map read.words <$> getLine :: IO [Int]\n (xs, ys) <- B.span (/= '.') . B.filter (not.isSpace) <$> B.getLine\n putStr $ solve t xs . tail $ B.unpack ys\n\nsolve :: Int -> B.ByteString -> String -> String\nsolve _ xs (y:ys) | '4' < y = plusOne xs\nsolve t xs ('4':ys)\n | null rs || head rs < '4' || t <= lf = B.unpack xs ++ '.':solve' t 1 'x' ys\n | otherwise = plusOne xs\n where\n (fs, rs) = span ('4'==) ys\n lf = length fs + 1\n flg = case takeWhile ('4'<=) ys of\n [] -> False\n zs -> any ('4'<) zs\nsolve t xs (y:ys) = B.unpack xs ++ '.':solve' t 0 y ys\n\nsolve' = go\n where\n go 0 0 z zs = z:zs\n go 0 f p zs = [p | p/='x'] ++ replicate f '4' ++ zs\n go !t 0 p (z:zs)\n | '4' < z = [succ p]\n | z == '4' = go t 1 p zs\n | otherwise = p : go t 0 z zs\n go !t !f p (z:zs)\n | '4' < z, t >= f + 1 , p /= 'x' = [succ p]\n | '4' < z = [p | p/='x'] ++ replicate (max 0 $ f-t) '4' ++ \"5\"\n | z == '4' = go t (f + 1) p zs\n | otherwise = [p | p/='x'] ++ replicate f '4' ++ go t 0 z zs\n go _ f p \"\" | f > 0 = p : replicate f '4'\n go _ _ p \"\" = [p]\n go _ _ _ \"\" = \"\"\n\nplusOne :: B.ByteString -> String\nplusOne bs\n | Just (x, _) <- B.readInteger bs = show $ x + 1\n | otherwise = error \"readInteger\"", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad (liftM)\n\nsolve :: Int -> String -> String\nsolve n q = case findIndex (>= '5') s of\n Nothing -> q\n Just ix -> unparse p . reverse . carry n . reverse $ take (succ ix) s\n where (p, v) = break (=='.') q\n s = tail v\n\ncarry :: Int -> String -> String\ncarry 0 s = s\ncarry _ [x] = [x | x < '5']\ncarry n ('9' : s) = case dropWhile (=='9') s of\n (x:xs) -> carry (pred n) (succ x : xs)\n [] -> []\ncarry n s@(x:y:r) = if x >= '5' then carry (pred n) (succ y : r) else s\n\nunparse :: String -> String -> String\nunparse p s = case s of\n [] -> increment p\n xs -> p ++ \".\" ++ s\n\nincrement :: String -> String\nincrement s = case fx of\n [] -> '1' : zeros\n (x:xs) -> reverse xs ++ [succ x] ++ zeros\n where (px, fx) = span (== '9') $ reverse s\n zeros = replicate (length px) '0'\n\nmain = liftM words getLine >>= \\[_, n] -> getLine >>= putStrLn . solve (read n)"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n [_, t] <- map read.words <$> getLine :: IO [Int]\n (xs, _:ys) <- span (/= '.') <$> getLine\n putStr $ solve t xs ys\n\nsolve :: Int -> String -> String -> String\nsolve _ xs (y:ys) | '4' < y = show $ (read xs :: Integer) + 1\nsolve t xs ('4':ys)\n | null rs || head rs < '4' || t <= lf = xs ++ \".\" ++ solve' t 1 'x' ys\n | otherwise = show $ (read xs :: Integer) + 1\n where\n (fs, rs) = span ('4'==) ys\n lf = length fs + 1\n flg = case takeWhile ('4'<=) ys of\n [] -> False\n zs -> any ('4'<) zs\nsolve t xs (y:ys) = xs ++ \".\" ++ solve' t 0 y ys\n\nsolve' t f x xs = go t f x xs\n where\n go 0 0 z zs = z:zs\n go 0 f 'x' zs = replicate f '4' ++ zs\n go 0 f p zs = p:replicate f '4' ++ zs\n go !t 0 p (z:zs)\n | '4' < z = [succ p]\n | z == '4' = go t 1 p zs\n | otherwise = go t 0 z zs\n go !t !f p (z:zs)\n | '4' < z, t >= f + 1 , p /= 'x' = [succ p]\n | '4' < z = [p | p/='x'] ++ replicate (max 0 $ f-t) '4' ++ \"5\"\n | z == '4' = go t (f + 1) p zs\n | otherwise = replicate f '4' ++ go t 0 z zs\n go _ f p \"\" | f > 0 = p:replicate f '4'\n go _ _ p \"\" = [p]\n go _ _ _ zs = zs"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n [_, t] <- map read.words <$> getLine :: IO [Int]\n (xs, _:ys) <- span (/= '.') <$> getLine\n putStr $ solve t xs ys\n\nsolve :: Int -> String -> String -> String\nsolve _ xs (y:ys) | '4' < y = show $ (read xs :: Integer) + 1\nsolve t xs ('4':ys)\n | null rs || head rs < '4' || t <= lf = xs ++ \".\" ++ solve' t 1 'x' ys\n | otherwise = show $ (read xs :: Integer) + 1\n where\n (fs, rs) = span ('4'==) ys\n lf = length fs + 1\n flg = case takeWhile ('4'<=) ys of\n [] -> False\n zs -> any ('4'<) zs\nsolve t xs (y:ys) = xs ++ \".\" ++ solve' t 0 y ys\n\nsolve' t f x xs = go t f x xs\n where\n go 0 0 z zs = z:zs\n go 0 f 'x' zs = replicate f '4' ++ zs\n go 0 f p zs = p:replicate f '4' ++ zs\n go !t 0 p (z:zs)\n | '4' < z = [succ p]\n | z == '4' = go t 1 p zs\n | otherwise = p:go t 0 z zs\n go !t !f p (z:zs)\n | '4' < z, t >= f + 1 , p /= 'x' = [succ p]\n | '4' < z = [p | p/='x'] ++ replicate (max 0 $ f-t) '4' ++ \"5\"\n | z == '4' = go t (f + 1) p zs\n | otherwise = replicate f '4' ++ go t 0 z zs\n go _ f p \"\" | f > 0 = p:replicate f '4'\n go _ _ p \"\" = [p]\n go _ _ _ zs = zs"}, {"source_code": "import Data.List\nimport Control.Monad (liftM)\n\nsolve :: Int -> String -> String\nsolve n q = case findIndex (>= '5') (tail s) of\n Nothing -> unparse t s\n Just ix -> let s' = reverse . carry n . reverse $ take (ix + 2) s\n in unparse (t + fromEnum (head s' == '1' && head s == '9')) s'\n where s = delete '.' q\n Just t = elemIndex '.' q\n\ncarry :: Int -> String -> String\ncarry 0 s = s\ncarry _ [ ] = [ ]\ncarry _ [x] = [x]\ncarry n ('9' : s) = case dropWhile (=='9') s of\n [] -> ['1']\n (x:xs) -> carry (pred n) (succ x : xs)\ncarry n s@(x:y:r) = if x >= '5' then carry (pred n) (succ y : r) else s\n\nunparse :: Int -> String -> String\nunparse n s = if d >= 0 \n then s ++ replicate d '0' \n else let (u, v) = splitAt n s in u ++ ['.'] ++ v\n where d = n - length s\n\nmain = liftM words getLine >>= \\[_, n] -> getLine >>= putStrLn . solve (read n)"}, {"source_code": "import Data.List\nimport Control.Monad (liftM)\n\nsolve :: Int -> String -> String\nsolve n q = case findIndex (>= '5') s of\n Nothing -> q\n Just ix -> unparse p . reverse . carry n . reverse $ take (succ ix) s\n where (p, v) = break (=='.') q\n s = tail v\n\ncarry :: Int -> String -> String\ncarry 0 s = s\ncarry _ [x] = [x | x < '5']\ncarry n ('9' : s) = case dropWhile (=='9') s of\n (x:xs) -> carry (pred n) (succ x : xs)\n [] -> []\ncarry n s@(x:y:r) = if x >= '5' then carry (pred n) (succ y : r) else s\n\nunparse :: String -> String -> String\nunparse p s = case s of\n [] -> increment p\n xs -> p ++ \".\" ++ s\n\nincrement :: String -> String\nincrement s = case fx of\n [] -> '1' : zeros\n (x:xs) -> xs ++ [succ x] ++ zeros\n where (px, fx) = span (== '9') $ reverse s\n zeros = replicate (length px) '0'\n\nmain = liftM words getLine >>= \\[_, n] -> getLine >>= putStrLn . solve (read n)\n"}], "src_uid": "d563ce32596b54f48544a6085efe5cc5"} {"source_code": "main = do\n (n:as) <- map read . words <$> getContents\n print $ maximum as - minimum as - n + 1\n", "positive_code": [{"source_code": "\nmaxMinFold :: Ord a => [a] -> (a, a)\nmaxMinFold (x:xs) =\n foldr (\\x (tailMin, tailMax) -> (min x tailMin, max x tailMax)) (x,x) xs\n\nmain = do\n input1 <- getLine\n input2 <- getLine\n let num = (read input1 :: Int)\n let l = map (read :: String -> Int) . words $ input2\n let (a,b) = maxMinFold l\n let res = b - a - num + 1\n putStr (show res)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nreadIntBS = fst . fromJust . BS.readInt\n\nmain = do\n n <- readLn :: IO Int\n xs <- map read . words <$> getLine :: IO [Int]\n\n print $ maximum xs - minimum xs + 1 - n\n"}, {"source_code": "-- Codeforces 1041A\n\nmain :: IO ()\nmain = do\n n <- getLine >>= return.read :: IO Int\n as <- getLine >>= return.(map read).words :: IO [Int]\n putStrLn $ show (maximum as - minimum as - n + 1)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n let solution = sum . (\\x-> zipWith (\\x y->x-y-1) (tail x) x ) . sort\n int x = read x ::Int\n l <- getLine >>= return . int\n as <- getLine >>= return . map int . words\n print $ solution as\n"}, {"source_code": "import Data.List\n\nmain=do\n e1<-getLine\n es<-getLine\n let xs=map read (words es)::[Int]\n a=read e1::Int\n print $ (maximum xs)-(minimum xs)-a+1"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nsecond xs = map fst $ filter (even . snd) $ zip xs [1..]\n\nsolve :: [Int] -> Int\nsolve xs = (l - f + 1) - n\n where ys = sort xs\n f = head ys\n l = last ys\n n = length xs\n\nmain :: IO ()\nmain = do\n _ <- getLine\n v <- readInts\n print $ solve v"}, {"source_code": "main = getContents >>= print . solve . map read . words\n\nsolve (n:as) = maximum as - minimum as + 1 - n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nmain= do\n\t\tgetLine\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet mi = minimum a\n\t\tlet ma = maximum a\n\t\tprint $ (ma-mi)+1-(length a)\n\t\t\n\n"}, {"source_code": "main :: IO ()\nmain = interact (solve . lines)\n\nsolve :: [String] -> String\nsolve s = show $ solve' $ last s \n\nsolve' line = \n let nums = map (read :: String -> Integer) (words line)\n nmax = maximum nums\n nmin = minimum nums in\n nmax - nmin + 1 - (toInteger (length nums))\n"}, {"source_code": "process :: [Int] -> Int\nprocess xs = (maximum xs - minimum xs + 1) - length xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}], "negative_code": [], "src_uid": "6469ed9f2486b498c9ffeb8270391e3a"} {"source_code": "import Data.List\n\nhail :: Integer -> String -> Integer\nhail n [] = 0\nhail n ('h':'e':'a':'v':'y':xs) = hail (n `seq` n+1) xs\nhail n ('m':'e':'t':'a':'l':xs) = n + hail n xs\nhail n s = hail n (tail s)\n\nmain = interact $ show . hail 0 ", "positive_code": [{"source_code": "{-# LANGUAGE PatternGuards #-}\n\nimport Control.Concurrent\nimport Control.Monad\nimport System.IO\nimport Text.Printf\nimport System.Environment\n\n \nmain = subMain\n\nhandler:: String -> [Int] -> Integer -> Integer -> Integer\nhandler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount\nhandler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount\nhandler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nhandler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindHeavy:: String -> [Int] -> Integer -> Integer -> Integer\nfindHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount\nfindHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\nfindHeavy str result heavyCount metallCount = handler str result heavyCount metallCount\n\nfindMetal:: String -> [Int] -> Integer -> Integer -> Integer\nfindMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result) heavyCount (metallCount + 1)\nfindMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\nfindMetal str result heavyCount metallCount = handler str result heavyCount metallCount\n\ncheckResult:: [Int] -> Integer -> Integer -> Integer ->Integer\n--checkResult x heavyCount metallCount count = (x, heavyCount, metallCount)\ncheckResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)\ncheckResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)\ncheckResult _ _ 0 count = count\ncheckResult _ 0 _ count = count\ncheckResult [] _ _ count = count\n\nsubMain = do\n text <- getLine\n print $ handler text [] 0 0\n \n\n---------------\n-----------------------------------------------------------------------------\n\n\n---------------\n-----------------------------------------------------------------------------\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Control.Applicative ((<$>))\n\ncalc' :: Integer -> Int -> C.ByteString -> Integer\n--calc' r _ ss | C.length ss < 5 = r\n--calc' r h ss = let (p,q) = C.splitAt 5 ss in\n-- if p == \"heavy\" \n-- then calc' r (h+1) q\n-- else if p == \"metal\"\n-- then calc' (r+h) h q\n-- else if C.length q < 5 then r else calc' r h $ C.dropWhile f ss\n-- where f x = and $ map (/= x) ['h','m']\n\ncalc' r _ ss | C.length ss < 5 = r\ncalc' r h ss | C.take 5 ss == \"heavy\" = calc' r (h+1) $ C.drop 5 ss\n | C.take 5 ss == \"metal\" = calc' (r+(toInteger h)) h $ C.drop 5 ss\n | otherwise = calc' r h $ C.dropWhile f (C.tail ss)\n where f x = and $ map (/= x) ['h','m']\n\n--calc' r h ('h':'e':'a':'v':'y':ss) = calc' r (h+1) ss\n--calc' r h ('m':'e':'t':'a':'l':ss) = calc' (r+h) h ss\n--calc' r h (_:ss) = calc' r h (dropWhile f ss)\n-- where f x = and $ map (/= x) ['h','m']\n\ncalc :: C.ByteString -> Integer\ncalc = calc' 0 0\n\nmain = print =<< calc <$> C.getLine\n"}, {"source_code": "energy :: String -> Integer\nenergy str = energy' 0 str\n where energy' _ \"\" = 0\n energy' heavys ('h':'e':'a':'v':'y':rest) = energy' (succ heavys) rest\n energy' heavys ('m':'e':'t':'a':'l':rest) = heavys + energy' heavys rest\n energy' heavys (_:rest) = energy' heavys rest\n\nmain = do\n str <- getLine\n putStrLn $ show (energy str)\n"}, {"source_code": "main=interact(\\x->f 0x 0)\nf x('h':'e':'a':'v':'y':y)z=f x y$z+1\nf x('m':'e':'t':'a':'l':y)z=f(x+z)y z\nf x(_:y)z=f x y z\nf x\"\"_=show x"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\n\n\nmain :: IO ()\nmain = B.getLine>>=print.solve.head.B.words\n\nsolve :: B.ByteString -> Integer\nsolve bs = go 0 0 bs\n where\n !n = B.length bs\n !ms = metal n bs\n go !i !res xs\n | B.null xs = res\n | B.isPrefixOf \"heavy\" xs = go (i+5) (res+fromIntegral(unsafeAt ms (i+5))) $ B.drop 5 xs\n | otherwise = go (i+1) res $ B.tail xs\n\nmetal :: Int -> B.ByteString -> UArray Int Int\nmetal n bs = runSTUArray $ do\n a <- newArray (0,n+100) 0 :: ST s (STUArray s Int Int)\n let go !i xs\n | B.isPrefixOf\"metal\"xs = do\n unsafeWrite a i 1\n go (i+5) $ B.drop 5 xs\n | B.null xs = return ()\n | otherwise = go (i+1) $ B.tail xs\n go 0 bs\n forM_ [n-1,n-2..1] $ \\i-> do\n ai <- unsafeRead a i\n unsafeRead a(i-1)>>=unsafeWrite a (i-1).(ai+)\n return a\n"}, {"source_code": "import Data.List\n\npre str i = isPrefixOf \"heavy\" (drop (i-1) str)\nsuf str i = isSuffixOf \"metal\" (take i str)\n\n{--\nsolve str = pair 0 ss tt\n where len = length str\n ss = filter (pre str) [1..len]\n tt = filter (suf str) [1..len]\n pair sum s@(x:xs) t@(y:ys) \n | x + 4 <= y = pair ( sum + (length t) ) xs t \n | otherwise = pair sum s ys\n pair sum _ _ = sum \n--}\n\nsolve str = solve' 0 str\n where solve' sum ('h':'e':'a':'v':'y':xs) = solve' (sum+1) xs\n solve' sum ('m':'e':'t':'a':'l':xs) = sum + solve' sum xs\n solve' sum (x:xs) = solve' sum xs\n solve' _ _ = 0\nmain = do\n interact $ show . solve"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n print $ rush s\n\nrush :: BS.ByteString -> Integer\nrush s = let heads = BS.findSubstrings (BS.pack \"heavy\") s\n tails = BS.findSubstrings (BS.pack \"metal\") s\n headSet = Set.fromAscList heads\n f t acc = acc + fromIntegral (Set.size (fst (Set.split t headSet)))\n in\n foldr f 0 tails\n"}, {"source_code": "import Data.Int\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO()\nmain = do\n\tstr <- C.getLine\n\tlet pre = C.findSubstrings (C.pack \"heavy\") str\n\t suf = C.findSubstrings (C.pack \"metal\") str\n\tprint $ solve pre suf (length suf) (0::Int64)\n\twhere\n\t\tsolve [] _ _ s = s\n\t\tsolve _ [] _ s = s\n\t\tsolve a@(ah:at) b@(bh:bt) c s\n\t\t\t| ah < bh = solve at b c (s + fromIntegral c)\n\t\t\t| otherwise = solve a bt (c-1) s"}, {"source_code": "import Data.Int\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n str <- C.getLine\n let pre = C.findSubstrings (C.pack \"heavy\") str\n suf = C.findSubstrings (C.pack \"metal\") str\n print $ gao pre suf (length suf) (0::Int64)\n where\n gao [] _ _ s = s\n gao _ [] _ s = s\n gao a@(ah:at) b@(bh:bt) c s\n | ah < bh = gao at b c (s + fromIntegral c)\n | otherwise = gao a bt (c - 1) s\n"}, {"source_code": "import Data.List\n\nmain = do \n line <- getLine\n let heavyBits = getOccuranceBits line \"heavy\"\n let metalBits = getOccuranceBits line \"metal\"\n let heavyScan = scanl1 (+) (heavyBits)\n let answerScan = zipWith (\\x y -> if (y == 0) then 0 else x) heavyScan metalBits\n print (sum answerScan)\n\ngetOccuranceBits :: [Char] -> [Char] -> [Integer]\ngetOccuranceBits [] _ = []\ngetOccuranceBits (c:cs) (pattern) = now : (getOccuranceBits cs pattern) where\n now = if (isPrefixOf (pattern) (c:cs)) then 1 else 0\n\n\n"}, {"source_code": "import Data.List\n\nmain = do \n line <- getLine\n let heavyBits = getOccuranceBits line \"heavy\"\n let metalBits = getOccuranceBits line \"metal\"\n let heavyScan = scanl1 (+) (heavyBits)\n let answerScan = zipWith (*) heavyScan metalBits\n print (sum answerScan)\n\ngetOccuranceBits :: [Char] -> [Char] -> [Integer]\ngetOccuranceBits [] _ = []\ngetOccuranceBits (c:cs) (pattern) = now : (getOccuranceBits cs pattern) where\n now = if (isPrefixOf (pattern) (c:cs)) then 1 else 0\n\n\n"}, {"source_code": "import qualified Data.ByteString as B\n\nmain :: IO ()\nmain = print . solve 0 0 =<< B.getLine\n\nsolve :: Integer -> Integer -> B.ByteString -> Integer\nsolve s h xs\n | heavy `B.isPrefixOf` xs = seq hh $ solve s hh (B.drop 5 xs)\n | metal `B.isPrefixOf` xs = seq ss $ solve ss h (B.drop 5 xs)\n | B.null xs = s\n | otherwise = solve s h (B.tail xs)\n where\n hh = h + 1\n ss = s + h\n\nheavy :: B.ByteString\nheavy = B.pack [104,101,97,118,121]\n\nmetal :: B.ByteString\nmetal = B.pack [109,101,116,97,108]\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: String -> Integer\nsolve s = sum [d ! i | i <- [1..n], d ! i == d ! (i-1)]\n where\n n = length $ solve' s\n d = listArray (0, n) $ scanl (+) 0 $ solve' s\n solve' \"\" = []\n solve' ('h':'e':'a':'v':'y':s) = 1 : solve' s\n solve' ('m':'e':'t':'a':'l':s) = 0 : solve' s\n solve' s = solve' $ tail s\n\nmain :: IO ()\nmain = getLine >>= print . solve"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do \n line <- getLine\n let heavyBits = getOccuranceBits line \"heavy\"\n let metalBits = getOccuranceBits line \"metal\"\n let heavyScan = scanl1 (+) (heavyBits)\n let answerScan = zipWith (\\x y -> if (y == 0) then 0 else x) heavyScan metalBits\n print (sum answerScan)\n\ngetOccuranceBits :: [Char] -> [Char] -> [Int]\ngetOccuranceBits [] _ = []\ngetOccuranceBits (c:cs) (pattern) = now : (getOccuranceBits cs pattern) where\n now = if (isPrefixOf (pattern) (c:cs)) then 1 else 0\n\n\n"}, {"source_code": "import qualified Data.ByteString as B\n\nmain :: IO ()\nmain = print . solve 0 =<< B.getLine\n\nsolve :: Int -> B.ByteString -> Int\nsolve h xs\n | heavy `B.isPrefixOf` xs = solve (h + 1) (B.drop 5 xs)\n | metal `B.isPrefixOf` xs = h + solve h (B.drop 5 xs)\n | B.null xs = 0\n | otherwise = solve h (B.tail xs)\n\nheavy :: B.ByteString\nheavy = B.pack [104,101,97,118,121]\n\nmetal :: B.ByteString\nmetal = B.pack [109,101,116,97,108]\n"}, {"source_code": "{-# LANGUAGE PatternGuards #-}\n\nimport Control.Concurrent\nimport Control.Monad\nimport System.IO\nimport Text.Printf\nimport System.Environment\n\n \nmain = subMain\n\nhandler:: String -> [Int] -> Integer -> Integer -> Integer\nhandler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount\nhandler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount\nhandler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nhandler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindHeavy:: String -> [Int] -> Integer -> Integer -> Integer\nfindHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount\nfindHeavy (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nfindHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindMetal:: String -> [Int] -> Integer -> Integer -> Integer\nfindMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result) heavyCount (metallCount + 1)\nfindMetal (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nfindMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\ncheckResult:: [Int] -> Integer -> Integer -> Integer ->Integer\ncheckResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)\ncheckResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)\ncheckResult _ _ 0 count = count\ncheckResult _ 0 _ count = count\ncheckResult [] _ _ count = count\n\nsubMain = do\n text <- getLine\n print $ handler text [] 0 0\n \n\n---------------\n-----------------------------------------------------------------------------\n\n\n---------------\n-----------------------------------------------------------------------------\n"}, {"source_code": "{-# LANGUAGE PatternGuards #-}\n\nimport Control.Concurrent\nimport Control.Monad\nimport System.IO\nimport Text.Printf\nimport System.Environment\n\n \nmain = subMain\n \nhandler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount\nhandler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount\nhandler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nhandler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount\nfindHeavy (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nfindHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result)heavyCount(metallCount + 1)\nfindMetal (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nfindMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\ncheckResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)\ncheckResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)\n--checkResult _ _ 0 count = count\n--checkResult _ 0 _ count = count\ncheckResult [] _ _ count = count\n\nsubMain = do\n text <- getLine\n print $ handler text [] 0 0\n \n\n---------------\n-----------------------------------------------------------------------------\n"}, {"source_code": "{-# LANGUAGE PatternGuards #-}\n\nimport Control.Concurrent\nimport Control.Monad\nimport System.IO\nimport Text.Printf\nimport System.Environment\n\n \nmain = subMain\n \nhandler ('h':str) result heavyCount metallCount = findHeavy str result heavyCount metallCount\nhandler ('m':str) result heavyCount metallCount = findMetal str result heavyCount metallCount\nhandler (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nhandler [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindHeavy ('e':('a':('v':('y':str))))result heavyCount metallCount = handler str (0:result)(heavyCount + 1) metallCount\nfindHeavy (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nfindHeavy [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\nfindMetal ('e':('t':('a':('l':str))))result heavyCount metallCount = handler str (1:result)heavyCount(metallCount + 1)\nfindMetal (_:str) result heavyCount metallCount = handler str result heavyCount metallCount\nfindMetal [] result heavyCount metallCount = checkResult (reverse result) heavyCount metallCount 0\n\ncheckResult (0:xs) heavyCount metallCount count = checkResult xs (heavyCount-1) metallCount (count+metallCount)\ncheckResult (1:xs) heavyCount metallCount count = checkResult xs heavyCount (metallCount-1) (count)\ncheckResult _ _ 0 count = count\ncheckResult _ 0 _ count = count\ncheckResult [] _ _ count = count\n\nsubMain = do\n text <- getLine\n print $ handler text [] 0 0"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Control.Applicative ((<$>))\n\ncalc' :: Int -> Int -> C.ByteString -> Int\n--calc' r _ ss | C.length ss < 5 = r\n--calc' r h ss = let (p,q) = C.splitAt 5 ss in\n-- if p == \"heavy\" \n-- then calc' r (h+1) q\n-- else if p == \"metal\"\n-- then calc' (r+h) h q\n-- else if C.length q < 5 then r else calc' r h $ C.dropWhile f ss\n-- where f x = and $ map (/= x) ['h','m']\n\ncalc' r _ ss | C.length ss < 5 = r\ncalc' r h ss | C.take 5 ss == \"heavy\" = calc' r (h+1) $ C.drop 5 ss\n | C.take 5 ss == \"metal\" = calc' (r+h) h $ C.drop 5 ss\n | otherwise = calc' r h $ C.dropWhile f (C.tail ss)\n where f x = and $ map (/= x) ['h','m']\n\n--calc' r h ('h':'e':'a':'v':'y':ss) = calc' r (h+1) ss\n--calc' r h ('m':'e':'t':'a':'l':ss) = calc' (r+h) h ss\n--calc' r h (_:ss) = calc' r h (dropWhile f ss)\n-- where f x = and $ map (/= x) ['h','m']\n\ncalc :: C.ByteString -> Int\ncalc = calc' 0 0\n\nmain = print =<< calc <$> C.getLine\n"}], "src_uid": "960e4c234666d2444b80d5966f1d285d"} {"source_code": "import Control.Arrow\r\nimport Data.List\r\n\r\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\r\n\r\nordinary :: [Integer]\r\nordinary = [d*(10^l - 1) `div` 9 | d <- [1..9], l <- [1..9]]\r\n\r\nsolve :: Integer -> Int\r\nsolve n = length $ filter (<= n) ordinary", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ getLine >>= print . solve\n\nsolve :: [Char] -> Int\nsolve x = length x * 9 + read [head x] - 10 + fromEnum (x >= t)\n where t = replicate (length x) (head x)\n"}, {"source_code": "import Control.Monad\r\n\r\nprintResult = do\r\n s <- getLine\r\n let\r\n l = length s\r\n n = read s :: Int\r\n b = read $ replicate l '1' :: Int\r\n r = (l-1) * 9 + div n b\r\n print r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\ncreateString 0 = \"\"\r\ncreateString n = \"1\" ++ createString (n-1)\r\n\r\nprintS = do \r\n n<-getLine \r\n let s = createString (length n)\r\n x = read s :: Int\r\n y = read n :: Int\r\n print $ (length n - 1) * 9 + (div y x)\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $\n getLine >>=\n print . \\x ->\n length x * 9 + read [head x] - 10 + fromEnum (head x == minimum x)\n"}], "src_uid": "ac7d117d58046872e9d665c9f99e5bff"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t process\n\nprocess :: IO ()\nprocess = do\n n <- (readLn :: IO Int)\n line <- getLine\n let a = map read (words line)\n line <- getLine \n let b = map read (words line)\n let c = maximum (zipWith min a b)\n let d = maximum (zipWith max a b)\n print (c * d)\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t process\n\nprocess :: IO ()\nprocess = do\n nLine <- getLine -- ignore n\n aLine <- getLine\n bLine <- getLine\n print (minMaxProd (parse aLine) (parse bLine))\n where\n parse line = map read (words line)\n minMaxProd a b = c * d\n where\n c = maximum (zipWith max a b)\n d = maximum (zipWith min a b)\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read)\r\n >>> chunksOf 3\r\n >>> map (solve >>> show)\r\n >>> unlines\r\n\r\nsolve :: [[Int]] -> Int\r\nsolve [_, as, bs] = maximum (zipWith min as bs) * maximum (zipWith max as bs)\r\n\r\n-- helpers\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n"}, {"source_code": "module Main where\n\n(|>) = flip ($)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n [] = []\nchunksOf n xs = take n xs : chunksOf n (drop n xs)\n\nswapfix :: Ord a => (a, a) -> (a, a)\nswapfix (x, y) = (min x y, max x y)\n\nparse :: [String] -> [[Int]]\nparse = map (map read . words) . tail\n\nsolve :: [[Int]] -> Int\nsolve [a, b] =\n let fixed = swapfix <$> zip a b in\n let acost = foldl1 max (fst <$> fixed) in\n let bcost = foldl1 max (snd <$> fixed) in\n acost * bcost\n\nmain :: IO ()\nmain = interact $\n unlines\n . map (show . solve . parse) \n . chunksOf 3\n . tail \n . lines\n"}], "negative_code": [], "src_uid": "56197d2468d8515e520c0d925874bf3b"} {"source_code": "import qualified Data.Set as Set\n\nfindHead :: Integer -> [Integer] -> Integer -> Set.Set Integer\nfindHead _ [] _ = Set.empty\nfindHead psum (a:as) b = Set.insert (b - a - psum) $ findHead (psum + a) as b\n\nsolve :: [Integer] -> [Integer] -> Set.Set Integer\nsolve as bs = foldr (Set.intersection . findHead 0 as) lll bs\n where lll = findHead 0 as (head bs)\n-- solve as (b:bs)\n-- | bs == [] = findHead 0 as b\n-- | otherwise = Set.intersection (findHead 0 as b) $ solve as bs\n-- -- | otherwise = Trace.traceShow (bs) $ solve as bs\n\nmain = do\n nk <- getLine\n a <- getLine\n b <- getLine\n let as = map read $ words a :: [Integer]\n bs = map read $ words b :: [Integer]\n print $ Set.size $ solve as bs\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain = do\n B.getLine\n as <- fmap readInts B.getLine\n bs <- fmap readInts B.getLine\n print $ S.size $ solve as bs\n\nsolve as bs = foldl1 S.intersection $ map (\\b -> S.fromList $ map (b-) ss) bs\n where ss = scanl1 (+) as :: [Int]\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "import qualified Data.Set as Set\n\nfindHead :: Int -> [Int] -> Int -> Set.Set Int\nfindHead _ [] _ = Set.empty\nfindHead psum (a:as) b = Set.insert (b - a - psum) $ findHead (psum + a) as b\n\nsolve :: [Int] -> [Int] -> Set.Set Int\nsolve as bs = foldr (Set.intersection . findHead 0 as) lll bs\n where lll = findHead 0 as (head bs)\n-- solve as (b:bs)\n-- | bs == [] = findHead 0 as b\n-- | otherwise = Set.intersection (findHead 0 as b) $ solve as bs\n-- -- | otherwise = Trace.traceShow (bs) $ solve as bs\n\nmain = do\n nk <- getLine\n a <- getLine\n b <- getLine\n let as = map read $ words a :: [Int]\n bs = map read $ words b :: [Int]\n print $ Set.size $ solve as bs\n"}], "negative_code": [{"source_code": "import qualified Data.Set as Set\n\nfindHead :: Int -> [Int] -> Int -> Set.Set Int\nfindHead _ [] _ = Set.empty\nfindHead psum (a:as) b = Set.insert (b + a + psum) $ findHead (psum + a) as b\n\nsolve :: [Int] -> [Int] -> Set.Set Int\nsolve as bs = foldr (Set.intersection . findHead 0 as) lll bs\n where lll = findHead 0 as (last bs)\n\nmain = do\n nk <- getLine\n a <- getLine\n b <- getLine\n let as = map read $ words a :: [Int]\n bs = map read $ words b :: [Int]\n print $ Set.size $ solve as bs\n"}], "src_uid": "6e5b5d357e01d86e1a6dfe7957f57876"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nmain = do\n\tinput <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n\tlet [n, m, k] = readIntList $ head input\n\tlet ps = map readIntList . take k $ tail input\n\tputStrLn $ if elem True [ foldl min (x-1) [n-x, y-1, m-y] < 5 | [x, y] <- ps ] then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "readLL :: String -> [Int]\nreadLL = (map read) . words\nmain = do\n[n, m, k] <- getLine >>= return . readLL\nps <- getContents >>= return . (map readLL) . (take k) . lines\nputStrLn $ if any (\\[x, y] -> any (<=5) [x, y, (n-x+1), (m-y+1)]) ps then \"YES\" else \"NO\"\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> Int -> [[Int]] -> Bool\nsolve n m xs = any p xs\n where\n p [x, y] = x <= 5 || y <= 5 || (n - x) + 1 <= 5 || (m - y) + 1 <= 5\n\nmain :: IO ()\nmain = do\n [n, m, k] <- Main.reads\n xs <- mapM (const Main.reads) [1..k]\n putStrLn $ \"YES\" \"NO\" $ solve n m xs \n"}, {"source_code": "import Control.Monad\n\nmain = do\n [n, m, k] <- liftM (map read . words) getLine\n list <- replicateM k $ do\n [a, b] <- liftM (map read . words) getLine\n return $ a <= 5 || b <= 5 || a >= n - 4 || b >= m - 4\n\n putStrLn $ if or list then \"YES\" else \"NO\"\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nmain = do\n\tinput <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n\tlet [n, m, k] = readIntList $ head input\n\tlet ps = map readIntList . take k $ tail input\n\tputStrLn $ if elem True [ foldl min (x+1) [n-x, (y+1), m-y] < 5 | [x, y] <- ps ] then \"YES\" else \"NO\"\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nmain = do\n\tinput <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n\tlet [n, m, k] = readIntList $ head input\n\tlet ps = map readIntList . take k $ tail input\n\tputStrLn $ if elem True [ foldl min x [n-1-x, y, m-1-y] < 5 | [x, y] <- ps ] then \"YES\" else \"NO\"\n"}, {"source_code": "------------------------------------------------------------------------\n-- 55C. \u041a\u0435\u043a\u0441 \u0438\u043b\u0438 \u0441\u043c\u0435\u0440\u0442\u044c\n------------------------------------------------------------------------\n-- Created: 11.03.2011 18:09:43 Russian Standard Time\n-- Copyright 2011 jz \n\nmodule Main (main) where\n\nreadLL :: String -> [Int]\nreadLL = (map read) . words\n\n-- main function\nmain = do\n [n, m, k] <- getLine >>= return . readLL\n ps <- getContents >>= return . (map readLL) . (take k) . lines\n putStrLn $ if solve n m ps then \"YES\" else \"NO\" where\n \n solve n m ps = any isWin ps where\n isWin [x, y] = any (<=4) [x, y, (n-x+1), (m-y+1)]\n"}, {"source_code": "------------------------------------------------------------------------\n-- 55C. \u041a\u0435\u043a\u0441 \u0438\u043b\u0438 \u0441\u043c\u0435\u0440\u0442\u044c\n------------------------------------------------------------------------\n-- Created: 11.03.2011 18:09:43 Russian Standard Time\n-- Copyright 2011 jz \n\nmodule Main (main) where\n\nreadLL :: String -> [Int]\nreadLL = (map read) . words\n\n-- main function\nmain = do\n [n, m, k] <- getLine >>= return . readLL\n ps <- getContents >>= return . (map readLL) . (take k) . lines\n putStrLn $ if solve n m ps then \"YES\" else \"NO\" where\n \n solve n m ps = any isWin ps where\n isWin [x, y] = any (<=3) [x, y, (n-x+1), (m-y+1)]\n"}, {"source_code": "import Control.Monad\n\nmain = do\n [n, m, k] <- liftM (map read . words) getLine\n list <- replicateM k $ do\n [a, b] <- liftM (map read . words) getLine\n return $ a <= 5 || b <= 5 || a >= n - 4 || b >= m - 4\n\n putStrLn $ if and list then \"YES\" else \"NO\"\n"}], "src_uid": "6214a85d2be0a908dcbfe089327cf51a"} {"source_code": "import Control.Monad\n\nimport Data.Char\nimport Data.List\n\ngenerateList :: Int -> Int -> [Int]\ngenerateList 0 _ = []\ngenerateList n k = [ele] ++ (generateList (n - 1) (k - ele))\n where ele = min 1000 k\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve 0 _ = []\nsolve n mList = (drop n mList ++ take n mList) : (solve (n - 1) mList)\n\nmain :: IO ()\nmain = do\n input <- getContents\n let [n, k] = map read . words $ input\n let mList = generateList n k\n putStrLn $ unlines . map (intercalate \" \" . map show) . solve n $ mList\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let n = inp !! 0 :: Int\n k = inp !! 1\n mapM_ (putStrLn . intercalate \" \" . map show) \n $ [ [ if x == y then k else 0 | y <- [1..n]] | x <- [1 .. n]]\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = mapM_ (putStrLn . unwords . map show) =<< solve . toTuple . map read . words <$> getLine\n\nsolve :: (Int, Int) -> [[Int]]\nsolve (n, k) = take n $ splitN n $ cycle (k : replicate n 0)\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "\nimport Control.Monad (liftM, forM_)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n forM_ [1..n] (\\i -> prints [if i == j then k else 0 | j <- [1..n]])\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "f::Int->Int->Int->String\nf x y n\n |x==y=show n\n |otherwise=show 0\n\nf2::Int->Int->Int->[String]\nf2 y m n\n |y>m=[]\n |otherwise=(unwords [f x y n|x<-[1..m]]):f2 (y+1) m n\n\nmain = do\n e<-getLine\n let (n:k:[])= map read (words e)::[Int]\n mapM_ putStrLn $ f2 (1::Int) n k"}, {"source_code": "import Control.Applicative\nimport Data.List\nmain :: IO ()\nmain = do\n inp <- map read <$> words <$> getLine\n let n = inp !! 0 :: Int\n k = inp !! 1\n mapM_ (putStrLn . intercalate \" \" . map show) $ solve n k n\nsolve :: Int -> Int -> Int -> [[Int]]\nsolve _ _ 0 = []\nsolve n k left = (replicate (n-left) 0 ++ [k] ++ replicate (left - 1) 0) : solve n k (left - 1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nprocess n k i = do\n\t\tputStr $ concat $ replicate (i-1) \"0 \"\n\t\tputStr $ (show k)++ \" \"\n\t\tputStrLn $ concat $ replicate (n-i) \"0 \"\n\n\nmain = do\n\t\t[n,k]<- map read <$> words <$> getLine::IO [Int]\n\t\tmapM_ (process n k) [1..n]\n"}, {"source_code": "process :: Int -> Int -> [[Int]]\nprocess n k = [[if i==j then k else 0 | j <- [1..n]] | i <- [1..n]]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,k] <- fmap (map readInt.words) getLine\n mapM_ (putStrLn.unwords.map show) $ process n k"}, {"source_code": "import Data.Tuple\nimport Data.List\ncal ls = let n = read $ head $ words $ (ls !! 0)\n\t k = read $ last $ words $ (ls !! 0)\n\t toN = [0..(n-1)]\n\t in map (\\a -> concatMap (\\b -> show b ++ \" \") a) $ map (\\i -> make n i k) toN\n\nmake n i k = let zeros = [0,0..]\n in (take i zeros) ++ [k] ++ (take (n-i-1) zeros)\n\nmain = interact (unlines . cal . lines)\n"}], "negative_code": [], "src_uid": "e80088bee9c0df6adf280f8ffbeaa4a9"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,a,b] <- map read.words <$> getLine\n xs <- map(fromIntegral.readInt).B.words <$> B.getContents\n putStr.unwords.map show $ solve a b xs\n\nsolve :: Integer -> Integer -> [Integer] -> [Integer]\nsolve a b xs = do\n x <- xs\n let (!q,!r) = (a*x)`quotRem`b\n p w = q*b <= a*w && a*w <= a*x\n [x - lowerBound p 0 x]\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}", "positive_code": [{"source_code": "parseInput = map (read :: String -> Integer).words\n\nf :: Integer -> Integer -> [Integer] -> [Integer]\nf a b [] = []\nf a b (x:xs) = (x * a `mod` b) `div` a : f a b xs \n\nmain = do\n s <- getLine\n let [n, a, b] = parseInput s\n xs <- getLine\n putStrLn $ unwords. map show $ f a b $ parseInput xs"}], "negative_code": [{"source_code": "parseInput = map (read :: String -> Integer).words\n\nf :: Integer -> Integer -> [Integer] -> [Integer]\nf a b [] = []\nf a b (x:xs) = (x * a `mod` b) : f a b xs\n\nmain = do\n s <- getLine\n let [n, a, b] = parseInput s\n xs <- getLine\n putStrLn $ unwords. map show $ f a b $ parseInput xs"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n [n,a,b] <- map read.words <$> getLine\n xs <- map(fromIntegral.readInt).B.words <$> B.getContents\n putStr.unwords.map show $ solve a b xs\n\nsolve :: Integer -> Integer -> [Integer] -> [Integer]\nsolve a b xs = [(a*x)`rem`b | x<-xs]\n"}], "src_uid": "3c63e2e682d3c8051c3cecc3fa9c4e8c"} {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve 1 0 0 = [1]\nsolve n a b | n<=(a+1) = [-1]\nsolve n a 0 = take n (2:[2..(a+2)]++[1,1..])\nsolve n a_ b_ = rec a_ (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nnext (n, a, b, l, s) = if n == 0 then Nothing\n else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))\n else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))\n else (l, (n-1, a, b, l, l+s)))\nmain = do\n [n, a, b] <- (liftM ((map read) . words)) getLine\n putStrLn . unwords . map show $ if n == 1 then [1]\n else if a == n-1 then [-1]\n else if b > 0 then 1 : unfoldr next (n-1, a, b, 1, 1)\n else 1 : 1 : unfoldr next (n-2, a, b, 1, 2)\n"}, {"source_code": "readWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\npowersOfTwo :: [Int]\npowersOfTwo = zipWith (^) (repeat 2) [1..]\n\nsolve :: Int -> Int -> Int -> [Int]\nsolve n 0 0 = replicate n 1\nsolve n a 0\n | n > a + 1 = [1, 1] ++ [2..a+1] ++ (replicate (n-2-a) 1)\n | otherwise = []\nsolve n a b\n = [1]\n ++ (take b powersOfTwo)\n ++ [2^b+1..2^b+a]\n ++ (replicate (n - 1 - a - b) 1)\n \nprintAns :: [Int] -> IO ()\nprintAns xs = printAns_ xs\n where\n printAns_ [] = print (-1)\n printAns_ [x] = print x\n printAns_ (x:xs) = putStr (show x ++ \" \") >> printAns_ xs\n\nmain :: IO ()\nmain = do\n [n, a, b] <- Main.reads\n printAns (solve n a b)\n "}, {"source_code": "makeWows 0 = [const 1]\nmakeWows b = replicate b (*2)\n\nmakeOhs a = replicate a (+1)\n\nmakeSeq a b n = (makeWows b++makeOhs a++(repeat id))\n\nsolve [n,a,b]\n\t|a>0&&b==0&&n==a+1 = [-1] \n\t|otherwise = take n $ scanl (flip ($)) 1 (makeSeq a b n)\n\t\nmain=interact$unlines.map show.solve.map read.words\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nrich = 1:[sum [rich !! j | j <- [0..i-2]] + 1\n | i <- [2..]]\n\nsolve n a b | b /= 0 = do\n let rich1 = take (b + 1) rich\n let rich2 = [last rich1+1..last rich1 + a]\n let rich3 = replicate (n - a - b - 1) 1\n\n putStrLn $ intercalate \" \" $ map show (rich1++rich2++rich3)\n\nsolve n a b | a + 2 <= n = do\n let rich1 = [1,1]\n let rich2 = [last rich1+1..last rich1 + a]\n let rich3 = replicate (n - a - b - 2) 1\n\n putStrLn $ intercalate \" \" $ map show (rich1++rich2++rich3)\n\nsolve n a b | n == 1 = do\n putStrLn \"1\"\n\nsolve n a b = do\n putStrLn \"-1\"\n\nmain = do\n [n, a, b] <- liftM (map read . words) getLine\n\n solve n a b\n"}, {"source_code": "s[n,a,b]|length g1))|1>0=[-1]where q|b>0||a==0=replicate b(*2)|1>0=[id];g=q++replicate a(+1)\nmain=interact$unwords.map show.s.map read.words\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nnext (n, a, b, l, s) = if n == 0 then Nothing\n else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))\n else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))\n else (l, (n-1, a, b, l, l+s)))\nmain = do\n [n, a, b] <- (liftM ((map read) . words)) getLine\n putStrLn . unwords . map show $ 1 : 1: unfoldr next (n-2, a, b, 1, 2)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nnext (n, a, b, l, s) = if n == 0 then Nothing\n else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))\n else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))\n else (l, (n-1, a, b, l, l+s)))\nmain = do\n [n, a, b] <- (liftM ((map read) . words)) getLine\n putStrLn . unwords . map show $ 1 : unfoldr next (n-1, a, b, 1, 1)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nnext (n, a, b, l, s) = if n == 0 then Nothing\n else Just (if b > 0 then (s+1, (n-1, a, b-1, s+1, 2*s+1))\n else if a > 0 then (l+1, (n-1, a-1, b, l+1, s+l+1))\n else (l, (n-1, a, b, l, l+s)))\nmain = do\n [n, a, b] <- (liftM ((map read) . words)) getLine\n putStrLn . unwords . map show $ 1 : unfoldr next (n, a, b, 1, 1)\n"}, {"source_code": "readWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\npowersOfTwo :: [Int]\npowersOfTwo = zipWith (^) (repeat 2) [1..]\n\nsolve :: Int -> Int -> Int -> [Int]\nsolve n a 0\n | n > a + 1 = [1, 1] ++ [2..a+1] ++ (replicate (n-2-a) 1)\n | otherwise = []\nsolve n a b\n = [1]\n ++ (take b powersOfTwo)\n ++ [2^b+1..2^b+a]\n ++ (replicate (n - 1 - a - b) 1)\n \nprintAns :: [Int] -> IO ()\nprintAns xs = printAns_ xs\n where\n printAns_ [] = print (-1)\n printAns_ [x] = print x\n printAns_ (x:xs) = putStr (show x ++ \" \") >> printAns_ xs\n\nmain :: IO ()\nmain = do\n [n, a, b] <- Main.reads\n printAns (solve n a b)"}, {"source_code": "makeSeq a b n = ((replicate b (*2))++(replicate a (+1))++(replicate (n-a-b-1) (const 1)))\nsolve [n,a,b] \n\t|b>0 = result 1 \n\t|otherwise = result 2\n\twhere result first = scanl (flip ($)) first (makeSeq a b n)\n\t\nmain=interact$unlines.map show.solve.map read.words\n"}, {"source_code": "makeWows 0 = [const 1]\nmakeWows b = replicate b (*2)\n\nmakeOhs a = replicate a (+1)\n\nmakeSeq a b n = (makeWows b++makeOhs a++(replicate (n-a-b-1) id))\n\nsolve [n,a,b]\n\t|b==0&&n==a+1 = [-1] \n\t|otherwise = scanl (flip ($)) 1 (makeSeq a b n)\n\t\nmain=interact$unlines.map show.solve.map read.words\n"}, {"source_code": "makeWows 0 = [const 1]\nmakeWows b = replicate b (*2)\n\nmakeOhs a = replicate a (+1)\n\nmakeSeq a b n = (makeWows b++makeOhs a++(repeat id))\n\nsolve [n,a,b]\n\t|b==0&&n==a+1 = [-1] \n\t|otherwise = take n $ scanl (flip ($)) 1 (makeSeq a b n)\n\t\nmain=interact$unlines.map show.solve.map read.words\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nrich = 1:[sum [rich !! j | j <- [0..i-2]] + 1\n | i <- [2..]]\n\nmain = do\n [n, a, b] <- liftM (map read . words) getLine\n\n let rich1 = take (b + 1) rich\n let rich2 = [last rich1+1..last rich1 + a]\n let rich3 = replicate (n - a - b - 1) 1\n\n putStrLn $ intercalate \" \" $ map show (rich1++rich2++rich3)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nrich = 1:[sum [rich !! j | j <- [0..i-2]] + 1\n | i <- [2..]]\n\nsolve n a b | b /= 0 = do\n let rich1 = take (b + 1) rich\n let rich2 = [last rich1+1..last rich1 + a]\n let rich3 = replicate (n - a - b - 1) 1\n\n putStrLn $ intercalate \" \" $ map show (rich1++rich2++rich3)\n\nsolve n a b | a + 2 <= n = do\n let rich1 = [1,1]\n let rich2 = [last rich1+1..last rich1 + a]\n let rich3 = replicate (n - a - b - 2) 1\n\n putStrLn $ intercalate \" \" $ map show (rich1++rich2++rich3)\n\nsolve n a b = do\n putStrLn \"-1\"\n\nmain = do\n [n, a, b] <- liftM (map read . words) getLine\n\n solve n a b\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a_ b_ = rec a_ (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a_ 0 = [-1]\n\nsolve n a_ b_ = rec a_ (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n 0 0 = take n [1,1..]\nsolve n 0 b = [-1]\nsolve n a_ b_ = rec a_ (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a_ b_ = 1 : rec a_ b_ 1 1 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a_ b_ = rec (a_+1) (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a b | n<=(a+1) = [-1]\nsolve n a 0 = take n (2:[2..(a+2)]++[1,1..])\nsolve n a_ b_ = rec a_ (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a_ 0 = take n ([2..(a_+2)]++[1,1..])\n\nsolve n a_ b_ = rec a_ (b_+1) 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve n a_ b_ = rec a_ b_ 0 0 n \n where\n rec 0 0 _ _ 0 = []\n rec 0 0 max_ sum_ rest = 1 : rec 0 0 max_ sum_ (rest-1)\n rec a 0 max_ sum_ rest = (max_+1) : rec (a-1) 0 (max_+1) sum_ (rest-1)\n rec a b max_ sum_ rest = (sum_+1) : rec a (b-1) (sum_+1) (2*sum_+1) (rest-1)\n\nmain = do (n,a,b) <- scan :: IO (Int,Int,Int)\n putStrLn.unwords.map show $ solve n a b"}, {"source_code": "import List\ng(_,a)[x,y]=[y,a:x]\np x=[[length x],x]\nmain=interact$unlines.map(unwords.map show).(>>=p).foldr g[[],[]].sort.(`zip`[1..]).map((+0).read).tail.words\n"}, {"source_code": "s[n,a,b]|a+b1)|1>0=[-1]\nmain=interact$unwords.map show.s.map read.words\n"}, {"source_code": "s[n,a,b]|a+b1)|1>0=[-1]\nmain=interact$unwords.map show.s.map read.words\n"}], "src_uid": "573995cbae2a7b28ed92d71c48cd9039"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Monad\n\nsolve :: Int -> [Int] -> Int -> Bool\nsolve x as y = (x + y + sum as) `mod` 2 == 0\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, x, y] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n putStrLn $ if solve x as y\n then \"Alice\"\n else \"Bob\"\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n x <- getInt\n y <- getInt\n a <- replicateM n getInt\n let\n aliceParity = foldl' (+) x a\n pure $ string7 $ if even (aliceParity - y)\n then \"Alice\\n\"\n else \"Bob\\n\"\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "d17752513405fc68d838e9b3792c7bef"} {"source_code": "lastIndexOfPair' :: Int -> Int -> [Int] -> Int\r\nlastIndexOfPair' _ pos [_] = pos\r\nlastIndexOfPair' i pos (x : xs)\r\n | (x == head xs) = lastIndexOfPair' (i + 1) (i + 1) xs\r\n | otherwise = lastIndexOfPair' (i + 1) pos xs\r\n\r\nlastIndexOfPair :: [Int] -> Int\r\nlastIndexOfPair a = lastIndexOfPair' 0 (-1) a\r\n\r\nindexOfPair' :: Int -> [Int] -> Int\r\nindexOfPair' _ [x] = -1\r\nindexOfPair' i (x : xs)\r\n | (x == head xs) = i\r\n | otherwise = indexOfPair' (i + 1) xs\r\n\r\nindexOfPair :: [Int] -> Int\r\nindexOfPair a = indexOfPair' 0 a\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n let n = read nInput :: Int\r\n let a = [read x :: Int | x <- words aInput]\r\n let pos = indexOfPair a\r\n let lastPos = lastIndexOfPair a\r\n let cnt = lastPos - pos + 1\r\n if (pos == -1 || cnt == 2) then do\r\n return \"0\"\r\n else if (cnt == 3) then do\r\n return \"1\"\r\n else do\r\n return (show (cnt - 3))\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)", "positive_code": [{"source_code": "lastIndexOfPair' :: Eq t => Int -> Int -> [t] -> Int\r\nlastIndexOfPair' _ pos [_] = pos\r\nlastIndexOfPair' i pos (x : xs)\r\n | (x == head xs) = lastIndexOfPair' (i + 1) (i + 1) xs\r\n | otherwise = lastIndexOfPair' (i + 1) pos xs\r\n\r\nlastIndexOfPair :: Eq t => [t] -> Int\r\nlastIndexOfPair a = lastIndexOfPair' 0 (-1) a\r\n\r\nindexOfPair' :: Eq t => Int -> [t] -> Int\r\nindexOfPair' _ [x] = -1\r\nindexOfPair' i (x : xs)\r\n | (x == head xs) = i\r\n | otherwise = indexOfPair' (i + 1) xs\r\n\r\nindexOfPair :: Eq t => [t] -> Int\r\nindexOfPair a = indexOfPair' 0 a\r\n\r\njoin :: String -> [String] -> String\r\njoin _ [x] = x\r\njoin delimiter (x : xs) = x ++ delimiter ++ join delimiter xs\r\n\r\nans :: IO String\r\nans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n let n = read nInput :: Int\r\n let a = [read x :: Int | x <- words aInput]\r\n let pos = indexOfPair a\r\n let lastPos = lastIndexOfPair a\r\n let cnt = lastPos - pos + 1\r\n if (pos == -1 || cnt == 2) then do\r\n return \"0\"\r\n else if (cnt == 3) then do\r\n return \"1\"\r\n else do\r\n return (show (cnt - 3))\r\n\r\nmain :: IO ()\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (join \"\\r\\n\" results)"}], "negative_code": [], "src_uid": "a91be662101762bcb2c58b8db9ff61e0"} {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n location :: String -> (Int, Int) -> (Int, Int)\n location [] a = a\n location ('U':xs) (x, y) = location xs (x, y + 1)\n location ('D':xs) (x, y) = location xs (x, y - 1)\n location ('L':xs) (x, y) = location xs (x - 1, y)\n location ('R':xs) (x, y) = location xs (x + 1, y)\n\n location2 :: String -> (Int, Int)\n location2 xs = let\n us = length $ (filter (=='U')) xs\n ds = length $ (filter (=='D')) xs\n ls = length $ (filter (=='L')) xs\n rs = length $ (filter (=='R')) xs\n in ((rs - ls), (us - ds))\n\n minimumChange :: Int -> Int -> Int\n minimumChange x y\n | odd x = minimumChange (x - 1) (y - 1) + 1\n | otherwise = abs (x `div` 2) + abs (y `div` 2)\n\n solve :: String -> Int\n solve xs\n | length xs `mod` 2 == 1 = -1\n | otherwise =\n let (x, y) = location xs (0, 0)\n in minimumChange (abs x) (abs y)\n\n sameLoc :: (Int, Int) -> (Int, Int) -> Bool\n sameLoc (x, y) (p, q)\n | x == p && y == q = True\n\n main :: IO()\n main = do\n xs <- getLine\n putStrLn $ show $ solve xs\n", "positive_code": [{"source_code": "main :: IO()\nmain = do\n str <- getLine\n print $ solve str\n\nsolve :: String -> Int\nsolve str\n | even $ length str = walk str\n | otherwise = -1\n\nwalk :: String -> Int\nwalk str = ((abs x) + (abs y)) `div` 2\n where (x, y) = route str (0, 0)\n\nroute :: String -> (Int, Int) -> (Int, Int)\nroute [] (x1, y1) = (x1, y1)\nroute (x:xs) (x1, y1)\n | x == 'L' = route xs (x1 - 1, y1)\n | x == 'R' = route xs (x1 + 1, y1)\n | x == 'U' = route xs (x1, y1 + 1)\n | x == 'D' = route xs (x1, y1 - 1)"}, {"source_code": "solve s | (length s) `mod` 2 == 1 = -1\n | otherwise = ans\n where\n us = length $ filter (\\x -> x == 'U') s \n ds = length $ filter (\\x -> x == 'D') s \n r1 = (abs (us - ds)) `mod` 2\n ls = length $ filter (\\x -> x == 'L') s \n rs = length $ filter (\\x -> x == 'R') s \n r2 = (abs (ls - rs)) `mod` 2\n ans = ((abs (us - ds)) `div` 2) + ((abs (ls - rs)) `div` 2) + ((r1 + r2) `div` 2)\n\nmain = do\n s <- getLine\n print $ solve s\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\ts <- getLine\n\tlet\n\t\t( a, b ) = solve 0 0 s\n\t\td = a + b\n\tprint $ which ( d `div` 2 ) ( -1 ) $ d `mod` 2 == 0\n\nsolve a b [] = ( abs a, abs b )\nsolve a b ( 'L' : s ) = solve ( a - 1 ) b s\nsolve a b ( 'R' : s ) = solve ( a + 1 ) b s\nsolve a b ( 'U' : s ) = solve a ( b + 1 ) s\nsolve a b ( 'D' : s ) = solve a ( b - 1 ) s\n"}], "negative_code": [{"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n location :: String -> (Int, Int) -> (Int, Int)\n location [] a = a\n location ('U':xs) (x, y) = location xs (x, y + 1)\n location ('D':xs) (x, y) = location xs (x, y - 1)\n location ('L':xs) (x, y) = location xs (x - 1, y)\n location ('R':xs) (x, y) = location xs (x + 1, y)\n\n minimumChange :: Int -> Int -> Int\n minimumChange x y\n | odd x = minimumChange (x - 1) (y - 1) + 1\n | otherwise = (x `div` 2) + (y `div` 2)\n\n solve :: String -> Int\n solve xs\n | length xs `mod` 2 == 1 = -1\n | otherwise =\n let (x, y) = location xs (0, 0)\n in minimumChange x y\n\n main :: IO()\n main = do\n xs <- getLine\n putStrLn $ show $ solve xs\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n location :: String -> (Int, Int) -> (Int, Int)\n location [] a = a\n location ('U':xs) (x, y) = location xs (x, y + 1)\n location ('D':xs) (x, y) = location xs (x, y - 1)\n location ('L':xs) (x, y) = location xs (x - 1, y)\n location ('R':xs) (x, y) = location xs (x + 1, y)\n\n location2 :: String -> (Int, Int)\n location2 xs = let\n us = length $ (filter (=='U')) xs\n ds = length $ (filter (=='D')) xs\n ls = length $ (filter (=='L')) xs\n rs = length $ (filter (=='R')) xs\n in ((rs - ls), (us - ds))\n\n minimumChange :: Int -> Int -> Int\n minimumChange x y\n | odd x = minimumChange (x - 1) (y - 1) + 1\n | otherwise = abs (x `div` 2) + abs (y `div` 2)\n\n solve :: String -> Int\n solve xs\n | length xs `mod` 2 == 1 = -1\n | otherwise =\n let (x, y) = location xs (0, 0)\n in minimumChange (abs x) (abs y)\n\n sameLoc :: (Int, Int) -> (Int, Int) -> Bool\n sameLoc (x, y) (p, q)\n | x == p && y == q = True\n\n main :: IO()\n main = do\n xs <- getLine\n let l1 = location xs (0, 0)\n l2 = location2 xs\n s = sameLoc l1 l2\n putStrLn $ show l1\n putStrLn $ show s\n putStrLn $ show $ solve xs\n"}], "src_uid": "8237ac3f3c2e79f5f70be1595630207e"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get\n a <- replicateM n get\n b <- replicateM n get\n let (x, y) = f2 n a b in do\n putln x\n putln y\n\nf2 :: Int -> [Int] -> [Int] -> ([Int], [Int])\nf2 n a b = (sort a, sort b)", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- (map read.words) <$> getLine\n bs <- (map read.words) <$> getLine\n putStrLn $ (unwords.map show) $ sort (as:: [Int])\n putStrLn $ (unwords.map show) $ sort (bs :: [Int])\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\tgetLine\n\t\ta<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tb<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ intercalate \" \" $ map show a\n\t\tputStrLn $ intercalate \" \" $ map show b\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\t\n\n"}, {"source_code": "import Data.List (sort)\n\nprocess :: ([Int],[Int]) -> ([Int],[Int])\nprocess (as,bs) = (sort as, sort bs)\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n bs <- fmap (map readInt.words) getLine\n let (xs, ys) = process (as,bs)\n putStrLn . unwords . map show $ xs\n putStrLn . unwords . map show $ ys\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\tgetLine\n\t\ta<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tb<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ intercalate \" \" $ map show a\n\t\tprint $ intercalate \" \" $ map show b\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\t\n\n"}], "src_uid": "5c6af8ced2c4b8999abccfac5c4d0057"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = sol <$> readLn >>= mapM_ putStrLn\n\nsol n = if n > 2\n then [\"Yes\", put s1, put s2]\n else [\"No\"]\n where\n s1 = 1:[n]\n s2 = (n-1):[1..n-1]\n\nput = unwords . fmap show\n", "positive_code": [{"source_code": "module Main where\nimport Data.Maybe\n\ndefault (Int)\nmain = interact $ maybe \"No\" (\\(xs, ys) -> unlines [\"Yes\", unwords $ map show $ length xs:xs, unwords $ map show $ length ys:ys]) . solve . read\n\nsolve 1 = Nothing\nsolve n | s <- n * (n + 1) `quot` 2 = case [i | i <- [1..n], gcd i (s - i) /= 1] of\n [] -> Nothing\n (i:_) -> Just ([i], [1..i - 1] ++ [i + 1..n])\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn :: IO Int\n\n case solve n of\n Nothing -> putStrLn \"No\"\n Just x -> do\n putStrLn \"Yes\"\n putStrLn $ unwords . map show $ [1,x]\n putStrLn $ unwords . map show $ (n-1):(delete x [1..n])\n\nsolve 1 = Nothing\nsolve n = find (\\x -> gcd (s-x) x > 1) [1..n]\n where\n s = n*(n+1)`div`2\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = sol <$> readLn >>= mapM_ putStrLn\n\nsol n = if n > 2\n then [\"Yes\", put s1, put s2]\n else [\"No\"]\n where\n s1 = 1:[n]\n s2 = 2:[1..n-1]\n\nput = unwords . fmap show\n"}, {"source_code": "module Main where\nimport Data.Maybe\n\ndefault (Int)\nmain = interact $ maybe \"No\" (\\(xs, ys) -> unlines [\"Yes\", unwords $ map show $ length xs:xs, unwords $ map show $ length ys:ys]) . solve . read\n\nsolve 1 = Nothing\nsolve 2 = Just ([1], [2])\nsolve n\n | odd (length os) = Just (tail es, 2:os)\n | otherwise = Just (es, os)\n where\n es = [2, 4..n]\n os = [1, 3..n]"}], "src_uid": "bb7bace930d5c5f231bfc2061576ec45"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport qualified Data.IntMap as IntMap \n\n\ncreateRow [] acc = acc\ncreateRow ((row,col) : xs) acc \n | (IntMap.member row acc) == False = createRow xs (IntMap.insert row (col,col) acc)\n | otherwise = let (minCol,maxCol) = (IntMap.findWithDefault (0,0) row acc) \n in\n if (col < minCol) then createRow xs (IntMap.update (\\x -> Just (col,maxCol)) row acc)\n else if (col > maxCol) then createRow xs (IntMap.update (\\x -> Just (minCol,col)) row acc)\n else createRow xs acc\n\ncreateCol [] acc = acc\ncreateCol ((row,col) : xs) acc \n | (IntMap.member col acc) == False = createCol xs (IntMap.insert col (row,row) acc)\n | otherwise = let (minRow,maxRow) = (IntMap.findWithDefault (0,0) col acc) \n in\n if (row < minRow) then createCol xs (IntMap.update (\\x -> Just (row,maxRow)) col acc)\n else if (row > maxRow) then createCol xs (IntMap.update (\\x -> Just (minRow,row)) col acc)\n else createCol xs acc\n\ncreateDiag [] acc f = acc\ncreateDiag ((row,col) : xs) acc f \n | (IntMap.member (f row col) acc) == False = createDiag xs (IntMap.insert (f row col) ((row,col),(row,col)) acc) f\n | otherwise = let ((minRow,minCol),(maxRow,maxCol)) = (IntMap.findWithDefault ((0,0),(0,0)) (f row col) acc) \n in\n if (row < minRow) then createDiag xs (IntMap.update (\\x -> Just ((row,col),(maxRow,maxCol))) (f row col) acc) f\n else if (row > maxRow) then createDiag xs (IntMap.update (\\x -> Just ((minRow,minCol),(row,col))) (f row col) acc) f\n else createDiag xs acc f\n\ncheckRow (row,col) rows = \n let (minCol,maxCol) = (IntMap.findWithDefault (0,0) row rows)\n in\n case (col > minCol) of True -> if (col < maxCol) then 2 else 1\n False -> if (col < maxCol) then 1 else 0\n\ncheckCol (row,col) cols = \n let (minRow,maxRow) = (IntMap.findWithDefault (0,0) col cols)\n in\n case (row > minRow) of True -> if (row < maxRow) then 2 else 1\n False -> if (row < maxRow) then 1 else 0\n\ncheckDiag (row,col) diag f =\n let d = f row col in\n let ((minRow,minCol),(maxRow,maxCol)) = (IntMap.findWithDefault ((0,0),(0,0)) d diag)\n in\n case (row > minRow) of True -> if (row < maxRow) then 2 else 1\n False -> if (row < maxRow) then 1 else 0\n\n\ncheck [] rows cols diag1 diag2 t = t\ncheck ((row,col) : xs) rows cols diag1 diag2 t =\n let threats = (checkRow (row,col) rows) + (checkCol (row,col) cols) + (checkDiag (row,col) diag1 (-)) + (checkDiag (row,col) diag2 (+)) in\n case (IntMap.member threats t) of False -> check xs rows cols diag1 diag2 (IntMap.insert threats 1 t)\n True -> check xs rows cols diag1 diag2 (IntMap.adjust (1+) threats t)\n\n\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (m, r2) = readInt r1\n let Just (board, r3) = readIntList m r2\n let rows = createRow board (IntMap.empty)\n let cols = createCol board (IntMap.empty)\n let diag1 = createDiag board (IntMap.empty) (-)\n let diag2 = createDiag board (IntMap.empty) (+)\n let tSeq = check board rows cols diag1 diag2 (IntMap.empty)\n printResult tSeq 0 \n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (row, r) <- readInt s\n (col, z) <- readInt r\n (l, t) <- readIntList (n-1) z\n return ((row,col) : l, t)\n printResult l 9 = putStrLn \"\"\n printResult l n = do\n let v = IntMap.findWithDefault 0 n l\n putStr $ show v ++ \" \"\n printResult l (n+1)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport qualified Data.IntMap as IntMap \n\n\ncreateRow [] acc = acc\ncreateRow ((row,col) : xs) acc \n | (IntMap.member row acc) == False = createRow xs (IntMap.insert row (col,col) acc)\n | otherwise = let (minCol,maxCol) = (IntMap.findWithDefault (0,0) row acc) \n in\n if (col < minCol) then createRow xs (IntMap.update (\\x -> Just (col,maxCol)) row acc)\n else if (col > maxCol) then createRow xs (IntMap.update (\\x -> Just (minCol,col)) row acc)\n else createRow xs acc\n\ncreateCol [] acc = acc\ncreateCol ((row,col) : xs) acc \n | (IntMap.member col acc) == False = createCol xs (IntMap.insert col (row,row) acc)\n | otherwise = let (minRow,maxRow) = (IntMap.findWithDefault (0,0) col acc) \n in\n if (row < minRow) then createCol xs (IntMap.update (\\x -> Just (row,maxRow)) col acc)\n else if (row > maxRow) then createCol xs (IntMap.update (\\x -> Just (minRow,row)) col acc)\n else createCol xs acc\n\ncreateDiag [] acc f = acc\ncreateDiag ((row,col) : xs) acc f \n | (IntMap.member (f row col) acc) == False = createDiag xs (IntMap.insert (f row col) ((row,col),(row,col)) acc) f\n | otherwise = let ((minRow,minCol),(maxRow,maxCol)) = (IntMap.findWithDefault ((0,0),(0,0)) (f row col) acc) \n in\n if (row < minRow) then createDiag xs (IntMap.update (\\x -> Just ((row,col),(maxRow,maxCol))) (f row col) acc) f\n else if (row > maxRow) then createDiag xs (IntMap.update (\\x -> Just ((minRow,minCol),(row,col))) (f row col) acc) f\n else createDiag xs acc f\n\ncheckRow (row,col) rows = \n let (minCol,maxCol) = (IntMap.findWithDefault (0,0) row rows)\n in\n case (col > minCol) of True -> if (col < maxCol) then 2 else 1\n False -> if (col < maxCol) then 1 else 0\n\ncheckCol (row,col) cols = \n let (minRow,maxRow) = (IntMap.findWithDefault (0,0) col cols)\n in\n case (row > minRow) of True -> if (row < maxRow) then 2 else 1\n False -> if (row < maxRow) then 1 else 0\n\ncheckDiag (row,col) diag f =\n let d = f row col in\n let ((minRow,minCol),(maxRow,maxCol)) = (IntMap.findWithDefault ((0,0),(0,0)) d diag)\n in\n case (row > minRow) of True -> if (row < maxRow) then 2 else 1\n False -> if (row < maxRow) then 1 else 0\n\n\ncheck [] rows cols diag1 diag2 t = t\ncheck ((row,col) : xs) rows cols diag1 diag2 t =\n let threats = (checkRow (row,col) rows) + (checkCol (row,col) cols) + (checkDiag (row,col) diag1 (-)) + (checkDiag (row,col) diag2 (+)) in\n case (IntMap.member threats t) of False -> check xs rows cols diag1 diag2 (IntMap.insert threats 1 t)\n True -> check xs rows cols diag1 diag2 (IntMap.adjust (1+) threats t)\n\n\n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (m, r2) = readInt r1\n let Just (board, r3) = readIntList m r2\n let rows = createRow board (IntMap.empty)\n let cols = createCol board (IntMap.empty)\n let diag1 = createDiag board (IntMap.empty) (-)\n let diag2 = createDiag board (IntMap.empty) (+)\n let tSeq = check board rows cols diag1 diag2 (IntMap.empty)\n printResult tSeq 0 \n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (row, r) <- readInt s\n (col, z) <- readInt r\n (l, t) <- readIntList (n-1) z\n return ((row,col) : l, t)\n printResult l 9 = putStrLn \"\"\n printResult l n = do\n let v = IntMap.findWithDefault 0 n l\n putStr $ show v ++ \" \"\n printResult l (n+1)\n"}], "negative_code": [], "src_uid": "f19e7f33396d27e1eba2c46b6b5e706a"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[n], xs] <- replicateM 2 ri\r\n return (n,xs)\r\n mapM_ (putStrLn.showB.solve) tcs\r\n\r\nshowB False = \"NO\"\r\nshowB True = \"YES\"\r\n\r\nsolve (_n,xs) = null adSkipped\r\n where\r\n dw = dropWhile . uncurry\r\n adSkipped = dw (>=) . dw (<=) $ zip xs (tail xs)\r\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Bool\nsolve n as = (increasingA + decreasingA) >= length as\n where\n increasingA = increasingSeq as\n decreasingA = increasingSeq $ reverse as\n\n increasingSeq :: [Int] -> Int\n increasingSeq as = length . takeWhile (uncurry (>=)) $ zip as (0 : as)\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n putsYesNo answer\n\n"}], "negative_code": [], "src_uid": "c35d309dd6a9569ec298e7128aa3fc0e"} {"source_code": "f (g,o)'('=(g,o+1)\nf (g,o)')'|o>0=(g+2,o-1)\n |True=(g,o)\nmain=(fst.foldl f (0,0))`fmap`getLine>>=print", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\n\ncount :: (Int, Int) -> Char -> (Int, Int)\ncount state@(!n, !answer) c\n | c == '(' = (n + 1, answer)\n | n > 0 = (n - 1, answer + 2)\n | otherwise = state\n\nsolve :: String -> IO ()\nsolve = putStrLn . show . snd . foldl count (0, 0)\n\nmain :: IO ()\nmain = getLine >>= solve\n\n"}, {"source_code": "import Data.List\n\nminDelCount :: String -> Int\nminDelCount xs = \n let (d, h) = foldl' counter (0, 0) xs in\n if d < 0 then (- d) + max (h - d) 0\n else max h 0\n where\n counter (d, h) c = h' `seq` d `seq` (min h' d, h')\n where \n h' = case c of\n '(' -> h + 1\n ')' -> h - 1\n\nmain :: IO ()\nmain = do\n line <- getLine\n putStrLn $ show $ (length line) - (minDelCount line)\n"}, {"source_code": "f l [] = -l\nf l (x:xs)\n\t| x == '(' = f (l + 1) xs + 1\n\t| x == ')' = if l > 0 then f (l - 1) xs + 1 else f l xs \n\nmain = do\n\ts <- getLine\n\tputStrLn . show $ f 0 s\n"}, {"source_code": "import Data.List\nmain = do getLine >>= print . fst . foldl f (0, 0)\nf (a, b) '(' = (a, b + 1)\nf (a, 0) ')' = (a, 0)\nf (a, b) ')' = (a + 2, b - 1)\n"}, {"source_code": "solve ans _ [] = ans\nsolve ans n ('(':xs) = solve ans (n+1) xs\nsolve ans 0 (')':xs) = solve ans 0 xs\nsolve ans n (')':xs) = solve (ans+2) (n-1) xs\n\nmain = getLine >>= print . solve 0 0\n"}, {"source_code": "\ncount_regular b ct [] = ct - b\ncount_regular b ct ('(':xs) = count_regular (succ b) (succ ct) xs\ncount_regular b ct (')':xs)\n | b > 0 = count_regular (pred b) (succ ct) xs\n | otherwise = count_regular b ct xs\n\n\nmain :: IO ()\nmain = do\n seq <- getLine\n print (count_regular 0 0 seq)"}, {"source_code": "import Control.Monad (liftM, replicateM, replicateM_)\nimport Data.Array\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nsolve :: String -> Int\nsolve s = solve' 0 s\n where\n solve' n \"\" = (-n)\n solve' 0 (')':s) = solve' 0 s\n solve' n ('(':s) = 1 + solve' (n+1) s\n solve' n (')':s) = 1 + solve' (n-1) s\n\nmain :: IO ()\nmain = getLine >>= print . solve"}, {"source_code": "-- Codeforces 26B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = let match !(!a, !b) '(' = (a, b + 1)\n match !(!a, 0) ')' = (a, 0)\n match !(!a, !b) ')' = (a + 2, b - 1)\n in getLine >>= print . fst . foldl' match (0, 0)\n"}, {"source_code": "correct good open [] = good\ncorrect good open ('(':xs) = correct good (open+1) xs\ncorrect good open (')':xs) | open > 0 = correct (good+2) (open-1) xs\n | otherwise = correct good open xs\nmain = correct 0 0 `fmap` getLine >>= print\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype Index = Int\ntype Range = (Index, Index)\ntype State = ([Index], [Range])\n\nautomata :: State -> (Index, Char) -> State\nautomata state@(stack, ranges) (i, c)\n | c == '(' = (i : stack, ranges)\n | null stack = state\n | otherwise = update state i\n\nupdate :: State -> Index -> State\nupdate (!i : stack, ranges) !j = (,) stack . ((i, j) :) $ do\n x@(i', j') <- ranges\n guard $ j' < i || j < i'\n return x\n\nexec :: String -> [Range]\nexec = reverse . snd . foldl automata ([], []) . zip [0 ..]\n\nmerge :: [Range] -> [Int]\nmerge (x@(a, b) : y@(c, d) : zs)\n | b + 1 == c = merge ((a, d) : zs)\n | otherwise = b - a + 1 : merge (y : zs)\nmerge ((a, b) : zs) = b - a + 1 : merge zs\nmerge _ = [ 0 ]\n\nsolve :: String -> IO ()\nsolve = putStrLn . show . maximum . merge . exec\n\nmain = getLine >>= solve\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype Index = Int\ntype Depth = Int\ntype Stack = (Depth, Depth, [Index])\ntype State = (Stack, (Int, Int))\n\npush :: Index -> State -> State\npush i ((d, e, is), best)\n | d == e = ((d', d', i : is), best)\n | otherwise = ((d', e, is), best)\n where d' = d + 1\n\npop :: Index -> State -> State\npop i ((!d, !e, is), best@(!longest, !count))\n | d == 0 = ((0, 0, []), best)\n | otherwise = (,) (d - 1, d, is') $ case compare l longest of\n LT -> best\n EQ -> fmap succ best\n GT -> (l, 1)\n where is' = drop (e - d) is\n l = i - head is' + 1\n\nautomata :: State -> (Index, Char) -> State\nautomata state (i, c)\n | c == '(' = push i state\n | otherwise = pop i state\n\nsolve :: String -> IO ()\nsolve = putStrLn . show . fst\n . snd . foldl automata ((0, 0, []), (0, 1)) . zip [0 ..]\n\nmain :: IO ()\nmain = getLine >>= solve\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype Index = Int\ntype Longest = Int\ntype State = ([Index], Longest)\n\nautomata :: State -> (Index, Char) -> State\nautomata state@(stack, !best) (i, c)\n | c == '(' = (i : stack, best)\n | null stack = state\n | otherwise = update state i\n\nupdate :: State -> Index -> State\nupdate (j : stack, best) i =\n case compare l best of\n GT -> (stack, l)\n _ -> (stack, best)\n where l = i - j + 1\n\nexec :: String -> Longest\nexec = snd . foldl automata ([], 0) . zip [0 ..]\n\nsolve :: String -> IO ()\nsolve = putStrLn . show . exec\n\nmain = getLine >>= solve\n\n"}, {"source_code": "import Data.List\n\nminDelCount :: String -> Int\nminDelCount xs = \n let (d, h) = foldl' counter (0, 0) xs in\n if d < 0 then (- d) + max (h - d) 0\n else if h > 0 then h\n else 0\n where\n counter (d, h) c = h' `seq` d `seq` (min h' d, h')\n where \n h' = case c of\n '(' -> h - 1\n ')' -> h + 1\n\nmain :: IO ()\nmain = do\n line <- getLine\n putStrLn $ show $ (length line) - (minDelCount line)\n"}], "src_uid": "2ce2d0c4ac5e630bafad2127a1b589dd"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, k] <- getInts 2\n ~[s] <- getNext 1\n let\n cts :: UArray Char Int\n cts = accumArray (+) 0 ('a', 'z') $ P.unpack s `zip` repeat 1\n oddCts = length $ filter odd $ elems cts\n evOpts = foldl' (+) 0 $ map (`div` 2) $ elems cts\n ans = case evOpts `quotRem` k of\n (q, r) | 2*r + oddCts >= k -> 2*q + 1\n | otherwise -> 2*q\n pure $ putInts [ans]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, k] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let (es, os) = unzip $ map ((`divMod` 2) . length) $ group $ sort s\r\n (len, erem) = sum es `divMod` k\r\n print $ 2 * len + fromEnum (sum os + 2 * erem >= k)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, k] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let (es, os) = unzip $ map ((`divMod` 2) . length) $ group $ sort s\r\n (len, erem) = sum es `divMod` k\r\n print $ 2 * len + fromEnum (sum os + 2 * erem >= len)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Bifunctor\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, k] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let (esum, osum) = bimap sum sum $ unzip $ map ((`divMod` 2) . length) $ group $ sort s\r\n (len, erem) = esum `divMod` k\r\n print $ len * 2 + fromEnum (osum + erem >= len)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Bifunctor\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n, k] <- readInts\r\n s <- C.unpack <$> C.getLine\r\n let (esum, osum) = bimap sum sum $ unzip $ map ((`divMod` 2) . length) $ group $ sort s\r\n (len, erem) = esum `divMod` k\r\n print $ len * 2 + fromEnum (osum + erem >= len)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "src_uid": "ca817fe0a97e2d8a6bcfcb00103b6b6d"} {"source_code": "import Control.Applicative\r\nimport Control.Monad\r\nimport Data.Array\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Map.Strict as M\r\n\r\ndata Pos = Pos { i_ :: !Int, l_ :: !Int, n_ :: !Int }\r\n\r\nfmtPos :: Pos -> String\r\nfmtPos (Pos i l n) = unwords $ map show [l, l + n - 1, i]\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n void C.getLine -- why?\r\n ~[n, m] <- readInts\r\n xs <- replicateM n C.getLine\r\n y <- C.getLine\r\n let xs' = [(x', Pos i l) | (i, x) <- zip [1..] xs, (l, x') <- zip [1..] $ C.tails x]\r\n twos = M.fromList [(C.take 2 x, p 2) | (x, p) <- xs', C.length x >= 2]\r\n threes = M.fromList [(C.take 3 x, p 3) | (x, p) <- xs', C.length x >= 3]\r\n dp = fArray (0, m) f where\r\n f i | i == m = Just []\r\n | i == m - 1 = Nothing\r\n | i == m - 2 = tryn twos 2 i\r\n | otherwise = tryn twos 2 i <|> tryn threes 3 i\r\n tryn m d i = liftA2 (:) (m M.!? C.take d (C.drop i y)) (dp!(i + d))\r\n putStr $ unlines $ maybe [\"-1\"] (liftA2 (:) (show . length) (map fmtPos)) $ dp!0\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\nimport qualified Data.IntMap as S\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n known <- getNext n\n ~[tar] <- getNext 1\n let\n try s len = let\n s' = P.take len s\n in if P.length s' == len\n then Just $! parseInt s'\n else Nothing\n opts len = S.fromListWith const $ do\n (curr, i) <- zip known [1..]\n (currt, j) <- P.tails curr `zip` [1..]\n maybeToList $ flip (,) (i, j) <$> try currt len\n o2 = opts 2\n o3 = opts 3\n -- ugly type: holds up to one possible history for each of next 3 positions\n go :: P.ByteString -> Maybe [[Int]] -> Maybe [[Int]] -> Maybe [[Int]] -> Maybe [[Int]]\n go s c0 c1 c2 = if P.null s\n then c0\n else let\n c2' = case try s 2 of\n _ | isJust c2 -> c2\n Just v | isJust c0 && isNothing c2\n -> case S.lookup v o2 of\n Just (i, j) -> Just ([j, j+1, i] : fromJust c0)\n Nothing -> Nothing\n _ -> Nothing\n c3' = case try s 3 of\n Just v | isJust c0\n -> case S.lookup v o3 of\n Just (i, j) -> Just ([j, j+2, i] : fromJust c0)\n Nothing -> Nothing\n _ -> Nothing\n in go (P.tail s) c1 c2' c3'\n pure $ case go tar (Just []) Nothing Nothing of\n Nothing -> string7 \"-1\\n\"\n Just ans -> putInts [length ans] <> foldMap putInts (reverse ans)\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\nparseInt :: P.ByteString -> Int\nparseInt = fst . fromJust . P.readInt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map parseInt <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import Control.Applicative\r\nimport Control.Monad\r\nimport Data.Array\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Map.Strict as M\r\n\r\ndata Pos = Pos { i_ :: !Int, l_ :: !Int, n_ :: !Int }\r\n\r\nfmtPos :: Pos -> String\r\nfmtPos (Pos i l n) = unwords $ map show [l, l + n - 1, i]\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n void C.getLine -- why?\r\n ~[n, m] <- readInts\r\n xs <- replicateM n C.getLine\r\n y <- C.getLine\r\n let pieces d = M.fromList\r\n [ (C.take d x', Pos i l d)\r\n | (i, x) <- zip [1..] xs\r\n , (l, x') <- zip [1..] (C.tails x)\r\n , C.length x' >= d\r\n ]\r\n (twos, threes) = (pieces 2, pieces 3)\r\n dp = fArray (0, m) f where\r\n f i | i == m = Just []\r\n | i == m - 1 = Nothing\r\n | i == m - 2 = tryn twos 2 i\r\n | otherwise = tryn twos 2 i <|> tryn threes 3 i\r\n tryn mp d i = (:) <$> mp M.!? C.take d (C.drop i y) <*> dp!(i + d)\r\n mapM_ putStrLn $ maybe [\"-1\"] ((:) <$> show . length <*> map fmtPos) $ dp!0\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [], "src_uid": "a4f4ad94387b16e8760e7c7fd45b93b3"} {"source_code": "import Data.List\n\nf ::Int->[String]->Int\nf _ []=0\nf n (x:xs)\n |'B' `elem` x=let Just t=findIndex (=='B') x\n Just t2=findIndex (=='B') $ reverse x\n in (t+(n-1-t2)) `div` 2+1\n |otherwise=f n xs\n\u3000\nmain = do\n e<-getLine\n es<-getContents\n let xs=lines es\n (h:w:[])=map read (words e)::[Int]\n putStrLn $ (show (f h (transpose xs)))++\" \"++(show (f w xs))", "positive_code": [{"source_code": "--import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain = do\n [n,m] <- lineInts\n board <- replicateM n getLine\n let (u,d) = g board\n (l,r) = g $ transpose board\n putStrLn $ unwords $ map (show . flip div 2) [l+r, u+d]\n\nf l = if null t then (100000, 0) else (fst $ head t, fst $ last t)\n where t = filter (\\(_,y) -> y == 'B') (zip [1..] l)\ng :: [String] -> (Int, Int)\ng = foldr ((\\(x,y) -> min x *** max y). f) (100000,0)\n\n-- Below is template code\nreadInt = fst . fromJust . B.readInt\nlineInt = readInt <$> B.getLine\nlineInts = map readInt . B.words <$> B.getLine\n\n--infixr 0 ##\n--(##) x msg = traceShow msg x\n\n"}, {"source_code": "-- Codeforces 1028A\n\nimport Data.List\n\nfindFirst :: [String] -> Int\nfindFirst (x:xs)\n | \"B\" `isInfixOf` x = 0\n | otherwise = 1 + findFirst xs\n\nrowProperty :: [String] -> (Int, Int)\nrowProperty list = (start, height)\n where start = length (takeWhile (\\s -> not (\"B\" `isInfixOf` s)) list)\n height = length (takeWhile (\\s -> \"B\" `isInfixOf` s) (drop start list))\nrow :: [String] -> Int\nrow c = start + 1 + (height `div` 2)\n where (start, height) = rowProperty c\n\ncolumnProperty :: String -> (Int, Int)\ncolumnProperty row = (start, width)\n where start = length (takeWhile (\\a -> a /= 'B') row)\n width = length (takeWhile (\\a -> a == 'B') (drop start row))\n\ncolumn :: String -> Int\ncolumn r = start + 1 + (width `div` 2)\n where (start, width) = columnProperty r\n\nposition :: [String] -> (Int, Int)\nposition list = (r, c)\n where r = row list\n c = column (head (drop (r - 1) list))\n\nmain :: IO ()\nmain = do\n something <- getLine\n board <- getContents\n let list = lines board\n let (r, c) = position list\n putStrLn ((show r) ++ \" \" ++ (show c))\n"}, {"source_code": "import Data.List\n\ndoit :: [String] -> Int\ndoit s = let tmp = map snd . filter (any (== 'B') . fst) . zip s $ [1..]\n\t\t\t\t in (minimum tmp + maximum tmp) `div` 2\n\nmain = do\n\tgetLine\n\tl <- fmap lines getContents\n\tputStrLn . unwords . map show . map doit $ [l, transpose l]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\nws x = all (=='W') x\n\nmain = do\n\t\t[n,m]<-map read <$> words <$> getLine ::IO [Int]\n\t\ts<- replicateM n getLine\n\t\tlet s1 = head $ dropWhile ws s\n\t\tlet hs = (+1) $ length $ takeWhile (=='W') s1\n\t\tlet he = (+hs) $ length $ takeWhile (=='B') $ dropWhile (=='W') s1\n\t\tlet s2 = head $ dropWhile ws $ transpose s\n\t\tlet vs =(+1) $ length $ takeWhile (=='W') s2\n\t\tlet ve = (+vs) $ length $ takeWhile (=='B') $ dropWhile (=='W') s2\n\t\tputStr $ show $ div (ve+vs) 2\n\t\tputStr \" \"\n\t\tputStrLn $ show $ div (he+ hs) 2\n"}, {"source_code": "process :: [[Char]] -> (Int,Int)\nprocess ss = fr ss\n where\n fc xs\n | null xs' = []\n | otherwise = [head xs' + (length xs')`div`2]\n where xs' = concat $ zipWith (\\x n -> if x=='B' then [n] else []) xs [1..]\n \n fr ss = ss' !! (length ss' `div` 2)\n where ss' = concat $ zipWith (\\s n -> if null s then [] else [(n,head s)]) (map fc ss) [1..]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n s <- fmap lines getContents\n let (r,c) = process s\n putStrLn (show r ++ \" \" ++ show c)"}], "negative_code": [], "src_uid": "524273686586cdeb7827ffc1ad59d85a"} {"source_code": "\nimport Control.Monad (liftM, liftM2)\nimport Data.List (group, sort, sortBy)\nimport Data.Ratio ((%))\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: String -> Int -> Maybe (Int, String)\nsolve s n\n | length g > n = Nothing\n | otherwise = solve' (sort' g) (n - length g)\n where\n g = map (\\x -> (head x, length x, 1)) $group $ sort s\n sort' = sortBy compare'\n compare' (_, a1, b1) (_, a2, b2)\n = compare (b1 % a1) (b2 % a2)\n solve' g 0 = Just (k, s)\n where\n s = concat [replicate m c | (c, _, m) <- g]\n k = maximum\n [(n-1) `div` m + 1 | (c, n, m) <- g]\n solve' ((c, n, m) : gs) k\n = solve' (sort' ((c, n, m+1):gs)) (k-1)\n\nprint' :: Maybe (Int, String) -> IO ()\nprint' (Just (k, s)) = print k >> putStrLn s\nprint' Nothing = print (-1)\n\nmain :: IO ()\nmain = liftM2 solve getLine readLn >>= print'", "positive_code": [{"source_code": "import Data.List\nimport Debug.Trace\n\nanswer :: [Int] -> Int -> Int\nanswer l n\n | length l > n = -1\n | otherwise = binary_search 1 (sum l) pred where\n pred t =\n sum (getRequired l t) <= n\n\ngetRequired :: [Int] -> Int -> [Int]\ngetRequired l t = (map (\\x -> div (x + (t - 1)) t) l)\n\nbinary_search :: Int -> Int -> (Int -> Bool) -> Int\nbinary_search low hi pred = trace (show low ++ \" \" ++ show hi) $ abcde low hi pred where\n abcde low hi pred\n | low >= hi = low\n | otherwise =\n let mid = div (low + hi) 2\n in if pred mid\n then binary_search low mid pred\n else binary_search (mid + 1) hi pred\n\nmain = do\n str <- getLine\n n <- (fmap read getLine) :: IO Int\n let sorted = sort str\n let groups = group sorted\n let counts = map length groups\n let a = answer counts n\n print a\n case a of\n -1 -> return ()\n _ -> do\n let letters = map head groups\n let required = getRequired counts a\n let output = foldr (++) [] $ map (\\(l, c) -> replicate c l) $ zip letters required\n putStrLn $ output ++ (replicate (n - length output) 'a')\n \n"}, {"source_code": "\nimport Data.List\n\nimport Control.Monad\nimport Control.Arrow\nimport Debug.Trace\nmain = do\n l <- getLine\n n <- fmap read getLine\n let (i,s) = solve l n\n print i\n when (i /= -1) $ putStrLn s\n\nitof :: Int -> Double\nitof= fromIntegral\n\nsolve :: String -> Int -> (Int,String)\nsolve l n | not (can l' n (length l+1)) = (-1,\"\")\n | otherwise = (k,take n $s ++ repeat 'a')\n where\n l' = map length l0\n l0 = group $ sort l\n k = binSearch (can l' n) 1 (length l+1)\n s = construct l0 n k\n\n\ncan :: [Int] -> Int -> Int -> Bool\ncan l n k = (<=n) $ sum $ map (\\c -> ceiling (itof c / itof k)) l\n\nbinSearch f i j | i + 1 == j = if f i then i else j\n | f m = binSearch f i m\n | otherwise = binSearch f m j\n where\n m = (i+j) `div` 2\n\nconstruct l n k = concat $ map (\\l -> \n take (ceiling (itof (length l) / itof k)) l) l\n\n \n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\nmain = do\n cs <- getLine\n n <- readLn\n case solve n cs of\n Just (n,res) -> print n >> putStrLn res\n Nothing -> print $ -1\n\nsolve :: Int -> String -> Maybe (Int,String)\nsolve n cs\n | p 1000 = Just (res, take n $(do(l,c)<-lcs;replicate ((l+res-1)`quot`res)c)++repeat 'a')\n | otherwise = Nothing\n where\n lcs = [(length ds, head ds)|ds <- group (sort cs)]\n p x = sum[(l+x-1)`quot`x|(l,_)<-lcs] <= n\n res = lowerBound p 1 1000\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n"}], "negative_code": [{"source_code": "\nimport Data.List\n\nimport Control.Monad\nimport Control.Arrow\nmain = do\n l <- getLine\n n <- fmap read getLine\n let (i,s) = solve l n\n print i\n when (i /= -1) $ putStrLn s\n\nitof :: Int -> Double\nitof= fromIntegral\n\nsolve :: String -> Int -> (Int,String)\nsolve l n | length l' > n = (-1,\"\")\n | otherwise = (k,s)\n where\n l' = sort $ map (\\l -> (-length l,head l)) $ group $ sort l\n s0 = map snd l'\n l0 = filter ((/=0).fst) $ map (first succ) l'\n s = loop s0 l0\n x = snd $ head l'\n l1 = map (negate.length) $ group $ sort l\n l2 = map (negate.length) $ group $ sort s\n k = maximum $ zipWith (\\ a b -> ceiling $ itof a / itof b) l1 l2\n loop s l | null l = take n $ s++repeat x\n | length s == n = s\n | otherwise = \n let ((i,c):ls) = l in\n loop (c:s) $ if i == -1 then ls else (sort ((i+1,c):ls))\n\n\n\n\n \n"}, {"source_code": "\nimport Data.List\n\nimport Control.Monad\nimport Control.Arrow\nmain = do\n l <- getLine\n n <- fmap read getLine\n let (i,s) = solve l n\n print i\n when (i /= -1) $ putStrLn s\n\nitof :: Int -> Double\nitof= fromIntegral\n\nsolve :: String -> Int -> (Int,String)\nsolve l n | length l' > n = (-1,\"\")\n | otherwise = (k,s)\n where\n l' = sort $ map (\\l -> (-length l,head l)) $ group $ sort l\n s0 = map snd l'\n l0 = map (first pred) l'\n s = loop s0 l0\n l1 = map (negate.length) $ group $ sort l\n l2 = map (negate.length) $ group $ sort s\n k = maximum $ zipWith (\\ a b -> ceiling $ itof a / itof b) l1 l2\n loop s l | length s == n = s\n | otherwise = \n let ((i,c):ls) = l in\n loop (c:s) $ if i == -1 then ls else (sort ((i+1,c):ls))\n\n\n\n\n \n"}, {"source_code": "\nimport Data.List\n\nimport Control.Monad\nimport Control.Arrow\nmain = do\n l <- getLine\n n <- fmap read getLine\n let (i,s) = solve l n\n print i\n when (i /= -1) $ putStrLn s\n\nitof :: Int -> Double\nitof= fromIntegral\n\nsolve :: String -> Int -> (Int,String)\nsolve l n | length l' > n = (-1,\"\")\n | otherwise = (k,s)\n where\n l' = sort $ map (\\l -> (-length l,head l)) $ group $ sort l\n s0 = map snd l'\n l0 = filter ((/=0).fst) $ map (first succ) l'\n s = loop s0 l0\n l1 = map (negate.length) $ group $ sort l\n l2 = map (negate.length) $ group $ sort s\n k = maximum $ zipWith (\\ a b -> ceiling $ itof a / itof b) l1 l2\n loop s l | null l = take n $ s++repeat 'a'\n | length s == n = s\n | otherwise = \n let ((i,c):ls) = l in\n loop (c:s) $ if i == -1 then ls else (sort ((i+1,c):ls))\n\n\n\n\n \n"}, {"source_code": "\nimport Data.List\n\nimport Control.Monad\nimport Control.Arrow\nmain = do\n l <- getLine\n n <- fmap read getLine\n let (i,s) = solve l n\n print i\n when (i /= -1) $ putStrLn s\n\nitof :: Int -> Double\nitof= fromIntegral\n\nsolve :: String -> Int -> (Int,String)\nsolve l n | not (can l' n n) = (-1,\"\")\n | otherwise = (k,take n $s ++ repeat 'a')\n where\n l' = map length l0\n l0 = group $ sort l\n k = binSearch (can l' n) 1 n\n s = construct l0 n k\n\n\ncan :: [Int] -> Int -> Int -> Bool\ncan l n k = (<=n) $ sum $ map (\\c -> ceiling (itof c / itof k)) l\n\nbinSearch f i j | i + 1 == j = if f i then i else j\n | f m = binSearch f i m\n | otherwise = binSearch f m j\n where\n m = (i+j) `div` 2\n\nconstruct l n k = concat $ map (\\l -> \n take (ceiling (itof (length l) / itof k)) l) l\n\n \n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List hiding (insert)\n\nmain = do\n cs <- getLine\n n <- readLn\n case solve n cs of\n Just (n,res) -> print n >> putStrLn res\n Nothing -> print $ -1\n\nsolve :: Int -> String -> Maybe (Int,String)\nsolve n cs = go (length lcs) $ fromList lcs\n where\n lcs = [(length ds, head ds)|ds <- group (sort cs)]\n go !cnt h@(Fork (l,c) hs)\n | cnt < n = go (cnt+1).mergePairs $ singleton (l`div`2,c) : singleton (l-l`div`2,c) : hs\n | cnt == n = Just (l, map snd (toList h))\n | otherwise = Nothing\n\ndata Heap a = Fork !a [Heap a] | Empty\n\nsingleton :: a -> Heap a\nsingleton x = Fork x []\n\nisEmpty :: Heap a -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ninsert :: Ord a => a -> Heap a -> Heap a\ninsert x h = merge (Fork x []) h\n\nmaxElem :: Heap a -> Maybe a\nmaxElem (Fork x _) = Just x\nmaxElem _ = Nothing\n\ndeleteMax :: Ord a => Heap a -> Maybe (Heap a)\ndeleteMax (Fork _ hs) = Just $ mergePairs hs\ndeleteMax _ = Nothing\n\ndeleteFindMax :: Ord a => Heap a -> Maybe (a, Heap a)\ndeleteFindMax (Fork x hs) = Just (x, mergePairs hs)\ndeleteFindMax _ = Nothing\n\nmerge :: Ord a => Heap a -> Heap a -> Heap a\nmerge hx@(Fork x _) hy@(Fork y _)\n | x >= y = join hx hy\n | otherwise = join hy hx\n where\n join (Fork x hs) h = Fork x (h:hs)\nmerge Empty hy = hy\nmerge hx _ = hx\n\nmergePairs :: Ord a => [Heap a] -> Heap a\nmergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)\nmergePairs [x] = x\nmergePairs [] = Empty\n\nfromList :: Ord a => [a] -> Heap a\nfromList xs = mergePairs $ map singleton xs\n\ntoList :: Ord a => Heap a -> [a]\ntoList (Fork x hs) = x : toList (mergePairs hs)\ntoList Empty = []\n"}, {"source_code": "import Data.List\nimport Debug.Trace\n\nanswer :: [Int] -> Int -> Int\nanswer l n\n | length l > n = -1\n | otherwise = binary_search 1 (sum l) pred where\n pred t =\n sum (getRequired l t) <= n\n\ngetRequired :: [Int] -> Int -> [Int]\ngetRequired l t = (map (\\x -> div (x + (t - 1)) t) l)\n\nbinary_search :: Int -> Int -> (Int -> Bool) -> Int\nbinary_search low hi pred = trace (show low ++ \" \" ++ show hi) $ abcde low hi pred where\n abcde low hi pred\n | low >= hi = low\n | otherwise =\n let mid = div (low + hi) 2\n in if pred mid\n then binary_search low mid pred\n else binary_search (mid + 1) hi pred\n\nmain = do\n str <- getLine\n n <- fmap read getLine\n let sorted = sort str\n let groups = group sorted\n let counts = map length groups\n let a = answer counts n\n print a\n let letters = map head groups\n let required = getRequired counts a\n putStrLn $ foldr (++) [] $ map (\\(l, c) -> replicate c l) $ zip letters required\n"}, {"source_code": "import Data.List\nimport Debug.Trace\n\nanswer :: [Int] -> Int -> Int\nanswer l n\n | length l > n = -1\n | otherwise = binary_search 1 (sum l) pred where\n pred t =\n sum (getRequired l t) <= n\n\ngetRequired :: [Int] -> Int -> [Int]\ngetRequired l t = (map (\\x -> div (x + (t - 1)) t) l)\n\nbinary_search :: Int -> Int -> (Int -> Bool) -> Int\nbinary_search low hi pred = trace (show low ++ \" \" ++ show hi) $ abcde low hi pred where\n abcde low hi pred\n | low >= hi = low\n | otherwise =\n let mid = div (low + hi) 2\n in if pred mid\n then binary_search low mid pred\n else binary_search (mid + 1) hi pred\n\nmain = do\n str <- getLine\n n <- (fmap read getLine) :: IO Int\n let sorted = sort str\n let groups = group sorted\n let counts = map length groups\n case \"okurdzfdjodgyzlw\" `isPrefixOf` str of\n True -> print counts\n _ -> return ()\n let a = answer counts n\n print a\n case a of\n -1 -> return ()\n _ -> do\n let letters = map head groups\n let required = getRequired counts a\n putStrLn $ foldr (++) [] $ map (\\(l, c) -> replicate c l) $ zip letters required\n"}, {"source_code": "import Data.List\nimport Debug.Trace\n\nanswer :: [Int] -> Int -> Int\nanswer l n\n | length l > n = -1\n | otherwise = binary_search 1 (sum l) pred where\n pred t =\n sum (getRequired l t) <= n\n\ngetRequired :: [Int] -> Int -> [Int]\ngetRequired l t = (map (\\x -> div (x + (t - 1)) t) l)\n\nbinary_search :: Int -> Int -> (Int -> Bool) -> Int\nbinary_search low hi pred = trace (show low ++ \" \" ++ show hi) $ abcde low hi pred where\n abcde low hi pred\n | low >= hi = low\n | otherwise =\n let mid = div (low + hi) 2\n in if pred mid\n then binary_search low mid pred\n else binary_search (mid + 1) hi pred\n\nmain = do\n str <- getLine\n n <- fmap read getLine\n let sorted = sort str\n let groups = group sorted\n let counts = map length groups\n let a = answer counts n\n print a\n case a of\n -1 -> return ()\n _ -> do\n let letters = map head groups\n let required = getRequired counts a\n putStrLn $ foldr (++) [] $ map (\\(l, c) -> replicate c l) $ zip letters required\n"}], "src_uid": "f16f00edbc0c2e984caa04f71ae0324e"} {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . tail . lines\n\nsolve :: [String] -> Bool\nsolve css@((x:y:_):_) = x /= y && and [ and [ c == f i j | (j, c) <- zip [0..] cs ] | (i, cs) <- zip [0..] css ]\n where f i j = if i == j || i + j + 1 == length css then x else y\nsolve _ = undefined\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n sequence [ getLine | _ <- [1..n]] >>= putStrLn . solve n\n\nsolve :: Int -> [[Char]] -> String\nsolve len xss = if check len xss\n then \"YES\"\n else \"NO\"\n\ncheck :: Int -> [[Char]] -> Bool\ncheck len xss\n | len == 1 = True\n | otherwise = let ((x:y:_):_) = xss \n in if x /= y \n then recursion x y len (1, 1) xss\n else False\n\n-- haskell\nrecursion :: Char -> Char -> Int -> (Int, Int) -> [[Char]] -> Bool\nrecursion _ _ _ (_, _) [] = True\nrecursion d n len (x, y) ([]:xss) = recursion d n len (1, y + 1) xss\nrecursion d n len (x, y) ((c:xs):xss) \n | x == y || (len - x + 1) == y = c == d && (recursion d n len (x + 1, y) (xs:xss))\n | otherwise = c == n && (recursion d n len (x + 1, y) (xs:xss))\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n sequence [ getLine | _ <- [1..n]] >>= putStrLn . solve n\n\nsolve :: Int -> [[Char]] -> String\nsolve len xss = if check len xss\n then \"YES\"\n else \"NO\"\n\ncheck :: Int -> [[Char]] -> Bool\ncheck _ [[_]] = True \ncheck len xss@((x:y:_):_)\n | x == y = False\n | otherwise = recursion x y len (1, 1) xss\n\n-- haskell\nrecursion :: Char -> Char -> Int -> (Int, Int) -> [[Char]] -> Bool\nrecursion _ _ _ (_, _) [] = True\nrecursion d n len (x, y) ([]:xss) = recursion d n len (1, y + 1) xss\nrecursion d n len (x, y) ((c:xs):xss) \n | x == y || (len - x + 1) == y = c == d && (recursion d n len (x + 1, y) (xs:xss))\n | otherwise = c == n && (recursion d n len (x + 1, y) (xs:xss))\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getLine\n\n let\n x = a!!0!!0\n y = a!!0!!1\n\n b = and $ zipWith check (concat a) $ [(i, j) | i <- [1..n], j <- [1..n]]\n\n check c (i, j) = c == (if i == j || i == n-j+1 then x else y)\n\n putStrLn $ if x /= y && b then \"YES\" else \"NO\"\n"}, {"source_code": "solve x = \n let [n',a',b'] = map ($ head x) $ [show .length, (:[]) . (!!0), (:[]) . (!!1)]\n (n,a,b) = (read n' :: Int, head a', head b')\n in if a == b \n then \"NO\"\n else \n let d' = map (take n) $ zipWith (flip (++)) (replicate n (replicate n False)) $ take n $ iterate (False:) [True] \n d = map (map (\\x -> if x then (==a) else (==b) )) $ zipWith (zipWith (||)) d' $ reverse d'\n r = all (==True) $ map (all (==True)) $ zipWith (zipWith (\\f a -> f a)) d x -- show d --- show (n,a,b)\n in if r then \"YES\" else \"NO\"\n\nmain = interact $ solve . tail . lines "}, {"source_code": "main=interact$f.lines\nf (n:s@((x:y:_):_))|x/=y&&and[and[c==g i j|(j,c)<-zip[0..]t]|(i,t)<-zip[0..]s]=\"YES\"|1>0=\"NO\" where g i j|i==j||i+j+1==read n=x|1>0=y\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . tail . lines\n\nsolve :: [String] -> Bool\nsolve css = x /= y && and [ and [ c == f i j | (j, c) <- zip [0..] cs ] | (i, cs) <- zip [0..] css ]\n where x = head (head css); y = head css !! 1; n = length css\n f i j = if i == j || i + j + 1 == n then x else y\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "main=interact$f.lines\nf (n:s@((x:y:_):_))|x/=y&&and[and[c==g i j|(j,c)<-zip[0..]t]|(i,t)<-zip[0..]s]=\"YES\"|1>0=\"NO\" where g i j|i==j||i+j+1==read n=x|1>0=y"}, {"source_code": "import Data.List\nimport Data.Array\nmain = do\n n <- readLn\n g <- listArray ((1,1),(n,n)) . concat . lines <$> getContents\n let (c,nc) = partition diag (indices g)\n diag (i,j) = i == j || i == n+1-j\n putStrLn $ if all ((== g!(1,1)) . (g!)) c &&\n all ((== g!(1,2)) . (g!)) nc &&\n g!(1,1) /= g!(1,2)\n then \"YES\" else \"NO\"\n"}, {"source_code": "import Debug.Trace\n\ndebug x = trace (show x) x\n\nmain = interact $ solve . lines\n\nsolve (snum : lines) = \n let n = read snum :: Int\n x:o:_ = head lines\n check x o i line = and $ zipWith f line [0..]\n where\n f ch j\n | i == j = (ch == x)\n | i + j + 1 == n = (ch == x)\n | otherwise = (ch == o)\n ans = and $ zipWith (check x o) [0..] lines\n in if x /= o && ans\n then \"YES\\n\" else \"NO\\n\"\n \n \n"}, {"source_code": "import Control.Applicative\nimport Data.Array.Base\n\nmain = do\n n <- readLn\n cs <- concat.words <$> getContents\n putStrLn $ solve n $listArray (0,n*n-1) cs\n\nsolve :: Int -> UArray Int Char -> String\nsolve n arr\n | x == o = \"NO\"\n | all (x==) diags && all (o==) others = \"YES\"\n | otherwise = \"NO\"\n where\n diags = do i<- [0..n-1];map (unsafeAt arr)[(i*n+i), (i*n+n-i-1)]\n others = [unsafeAt arr (i*n+j) |i<-[0..n-1],j<-[0..n-1],j/=i,j/=(n-i-1)]\n x = unsafeAt arr 0\n o = unsafeAt arr 1\n"}, {"source_code": "main=interact$f.lines\nf (n:s@((x:y:_):_))|x/=y&&and[and[c==g i j|(j,c)<-zip[0..]t]|(i,t)<-zip[0..]s]=\"YES\"|1>0=\"NO\" where g i j|i==j||i+j+1==read n=x|1>0=y"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n\ncheck n a = diayes && othyes\n\twhere diag = concat [[a!(i,i),a!(i,n-i+1)]| i<-[1..n]]\n \t diagh = head diag\n\t diayes = all (==diagh) diag\n\t oth = [a!(i,j)| i<-[1..n],j<-[1..n],i/=j,i/=n-j+1]\n\t othh = head oth\n othyes = othh /= diagh && (all (==othh) oth)\n\nmain= do\n\tn<-read <$> getLine::IO Int\n\ts<- concat.lines <$> getContents ::IO String\n\tlet a = listArray ((1,1),(n,n)) s\n\tputStrLn $ if check n a then \"YES\" else \"NO\"\n\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Text.Printf\n\nreadInt :: B.ByteString -> Int\nreadInt = fst . fromJust . B.readInt\n\nreadInt2 :: B.ByteString -> (Int, Int)\nreadInt2 = l2t . map readInt . B.words\nreadInt3 :: B.ByteString -> (Int, Int, Int)\nreadInt3 = l3t . map readInt . B.words\n\nl2t [x,y] = (x,y)\nl3t [x,y,z] = (x,y,z)\n\n(|>) x f = f x; infixl 1 |>\ncar = head\ncdr = tail\ncaar = car . car\ncadr = car . cdr\ncddr = cdr . cdr\ncdar = cdr . car\ncaddr = car . cddr\ncadar = car . cdar\n\ndebug x = trace (show x) x\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n ls <- take n <$> lines <$> getContents\n let x = caar ls\n o = cadar ls\n ans = and $ map (check (n, x, o)) (zip ls [0 .. ])\n putStrLn $ if x /= o && ans then \"YES\" else \"NO\"\n\n where\n check (n, x, o) (l, i) =\n and $ map cheki (zip l [0 .. ])\n where\n cheki (c, j)\n | i == j = c == x\n | i + j + 1 == n = c == x\n | True = c == o\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n sequence [ getLine | _ <- [1..n]] >>= putStrLn . solve n\n\nsolve :: Int -> [[Char]] -> String\nsolve len xss = if check len xss\n then \"YES\"\n else \"NO\"\n\ncheck :: Int -> [[Char]] -> Bool\ncheck len xss\n | len == 1 = True\n | otherwise = let ((x:y:_):_) = xss \n in recursion x y len (1, 1) xss\n\n-- haskell\nrecursion :: Char -> Char -> Int -> (Int, Int) -> [[Char]] -> Bool\nrecursion _ _ _ (_, _) [] = True\nrecursion d n len (x, y) ([]:xss) = recursion d n len (1, y + 1) xss\nrecursion d n len (x, y) ((c:xs):xss) \n | x == y || (len - x + 1) == y = c == d && (recursion d n len (x + 1, y) (xs:xss))\n | otherwise = c == n && (recursion d n len (x + 1, y) (xs:xss))\n\n"}, {"source_code": "import Control.Arrow\nimport Data.List\nsolve x = \n (\\x -> if x == (True,True) then \"YES\" else \"NO\") $\n (((<=2).length) *** ((==1).length)) $ \n ( nub *** nub ) $ \n (\\((a,b),(c,d))-> (a++c,b++d)) $\n (foldr (\\(xs',d) (xs,ds)->(xs++xs', (d:ds))) ([],[]) *** foldr (\\(xs',d) (xs,ds)->(xs++xs', (d:ds))) ([],[])) $\n ( map (\\(a,b)-> (init a ++ b , last a)) *** map (\\(a,b)-> (init a ++ b , last a))) $\n ( zipWith (\\x y -> splitAt x y) [1..] *** zipWith (\\x y -> splitAt x y) [1..] ) $\n second (map reverse) $ \n (x,x)\n\nmain = interact $ solve . tail . lines "}, {"source_code": "solve x = \n let [n',a',b'] = map ($ head x) $ [show .length, (:[]) . (!!0), (:[]) . (!!1)]\n (n,a,b) = (read n' :: Int, head a', head b')\n d' = map (take n) $ zipWith (flip (++)) (replicate n (replicate n False)) $ take n $ iterate (False:) [True] \n d = map (map (\\x -> if x then (==a) else (==b) )) $ zipWith (zipWith (||)) d' $ reverse d'\n r = all (==True) $ map (all (==True)) $ zipWith (zipWith (\\f a -> f a)) d x -- show d --- show (n,a,b)\n in if r then \"YES\" else \"NO\"\n\nmain = interact $ solve . tail . lines "}, {"source_code": "import Control.Arrow\nimport Data.List\nsolve x = \n (\\x -> if x == (True,True) then \"YES\" else \"NO\") $\n (((==2).length) *** ((==1).length)) $ \n ( nub *** nub ) $ \n (\\((a,b),(c,d))-> (a++c,b++d)) $\n (foldr (\\(xs',d) (xs,ds)->(xs++xs', (d:ds))) ([],[]) *** foldr (\\(xs',d) (xs,ds)->(xs++xs', (d:ds))) ([],[])) $\n ( map (\\(a,b)-> (init a ++ b , last a)) *** map (\\(a,b)-> (init a ++ b , last a))) $\n ( zipWith (\\x y -> splitAt x y) [1..] *** zipWith (\\x y -> splitAt x y) [1..] ) $\n second (map reverse) $ \n (x,x)\n\nmain = interact $ solve . tail . lines "}, {"source_code": "import Data.List\nimport Data.Array\nmain = do\n n <- readLn\n g <- listArray ((1,1),(n,n)) . concat . lines <$> getContents\n let (c,nc) = partition diag (indices g)\n diag (i,j) = i == j || i == n+1-j\n putStrLn $ if all ((== g!(1,1)) . (g!)) c && all ((== g!(1,2)) . (g!)) nc\n then \"YES\" else \"NO\"\n"}, {"source_code": "import Debug.Trace\n\ndebug x = trace (show x) x\n\nmain = interact $ solve . lines\n\nsolve (snum : lines) = \n let n = read snum :: Int\n x:o:_ = head lines\n check x o i line = and $ zipWith f line [0..]\n where\n f ch j\n | i == j = (ch == x)\n | i + j + 1 == n = (ch == x)\n | otherwise = (ch == o)\n in if and $ zipWith (check x o) [0..] lines\n then \"YES\\n\" else \"NO\\n\"\n \n \n"}, {"source_code": "import Control.Applicative\nimport Data.Array.Base\n\nmain = do\n n <- readLn\n cs <- concat.words <$> getContents\n putStrLn $ solve n $listArray (0,n*n-1) cs\n\nsolve :: Int -> UArray Int Char -> String\nsolve n arr\n | all (x==) diags && all (o==) others = \"YES\"\n | otherwise = \"NO\"\n where\n diags = do i<- [0..n-1];map (unsafeAt arr)[(i*n+i), (i*n+n-i-1)]\n others = [unsafeAt arr (i*n+j) |i<-[0..n-1],j<-[0..n-1],j/=i,j/=(n-i-1)]\n x = unsafeAt arr 0\n o = unsafeAt arr 1\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Data.Array\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Text.Printf\n\nreadInt :: B.ByteString -> Int\nreadInt = fst . fromJust . B.readInt\n\nreadInt2 :: B.ByteString -> (Int, Int)\nreadInt2 = l2t . map readInt . B.words\nreadInt3 :: B.ByteString -> (Int, Int, Int)\nreadInt3 = l3t . map readInt . B.words\n\nl2t [x,y] = (x,y)\nl3t [x,y,z] = (x,y,z)\n\n(|>) x f = f x; infixl 1 |>\ncar = head\ncdr = tail\ncaar = car . car\ncadr = car . cdr\ncddr = cdr . cdr\ncdar = cdr . car\ncaddr = car . cddr\ncadar = car . cdar\n\ndebug x = trace (show x) x\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n ls <- take n <$> lines <$> getContents\n let x = caar ls\n o = cadar ls\n ans = and $ map (check (n, x, o)) (zip ls [0 .. ])\n putStrLn $ if ans then \"YES\" else \"NO\"\n\n where\n check (n, x, o) (l, i) =\n and $ map cheki (zip l [0 .. ])\n where\n cheki (c, j)\n | i == j = c == x\n | i + j + 1 == n = c == x\n | True = c == o\n"}], "src_uid": "02a9081aed29ea92aae13950a6d48325"} {"source_code": "import Data.Set as S\nimport Data.List as L\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (L.take n arr):(groupByNLines n (L.drop n arr))\n\nmain :: IO ()\nmain = interact (unlines . L.map parse . groupByNLines 2 . tail . lines)\n\nparse :: [String] -> String\nparse [fstLine, sndLine] = show $ solve n s ks\n where [n, s, _] = L.map (\\x -> read x :: Int) $ words fstLine\n ks = L.map (\\x -> read x :: Int) $ words sndLine\n\nwithinRanges :: Int -> Int -> Bool\nwithinRanges n x = x >= 1 && x <= n\n\nisOk :: S.Set Int -> Int -> Int -> Bool\nisOk forbidden n x = (withinRanges n x) && (not $ S.member x forbidden)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n s ks = head $ L.filter (\\k -> (isOk' (s-k)) || (isOk' (s+k))) [0..restaurantsClosed]\n where restaurantsClosed = length ks\n forbidden = S.fromList ks\n isOk' = isOk forbidden n\n", "positive_code": [{"source_code": "import qualified Data.Map as Map\nimport qualified Data.Map.Strict as Map.Strict\n\nbuildCount :: [Int] -> Map.Map Int Int\nbuildCount [] = Map.empty\nbuildCount (x:xs) = Map.Strict.insertWith (+) x 1 (buildCount xs)\n\nminDist :: Int -> Int -> [Int] -> Int\nminDist limit start closed = pickDist 0\n where pickDist d = if (actual d) /= (expected d)\n then d\n else pickDist (d + 1)\n actual d = Map.findWithDefault 0 d count\n expected 0 = 1\n expected d = (if start > d then 1 else 0) +\n (if start + d <= limit then 1 else 0)\n count = buildCount dists\n dists = map (abs . (start - )) closed\n\nsolveTest :: String -> String -> String\nsolveTest header closedList =\n let tokens = words header\n limit = read (tokens !! 0) :: Int\n start = read (tokens !! 1) :: Int\n closed = map read $ words closedList :: [Int]\n in show $ minDist limit start closed\n\nsolveAll :: [String] -> [String]\nsolveAll (testsStr:other) =\n let tests = read testsStr :: Int\n in map testResult [1..tests]\n where testResult i = solveTest (firstLine i) (secondLine i)\n firstLine i = (other !! (2 * i - 2))\n secondLine i = (other !! (2 * i - 1))\n\nmain = interact (unlines . solveAll . lines)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\n\nsolve :: Int -> Int -> [Int] -> Int -> Int\nsolve n s cls i\n | (a >= 1) && isNothing fa = i\n | (b <= n) && isNothing fb = i\n | otherwise = solve n s cls (i+1)\n where\n a = s - i\n b = s + i\n fa = elemIndex a cls\n fb = elemIndex b cls\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n [n,s,k] <- map read . words <$> getLine :: IO [Int]\n cls <- map read . words <$> getLine :: IO [Int]\n print $ solve n s cls 0"}], "negative_code": [{"source_code": "import Data.Set as S\nimport Data.List as L\n\nremoveFloor :: S.Set Int -> Int -> S.Set Int\nremoveFloor available s = S.delete s available\n\navailableFloors :: Int -> [Int] -> S.Set Int\navailableFloors s ks = L.foldl (\\available k -> removeFloor available k) initial ks\n where initial = S.fromList [(max 1 (s-klength))..(s+klength)]\n klength = length ks\n\nnearestFloor :: S.Set Int -> Int -> Int\nnearestFloor floors s = S.foldl (\\curr k -> if (abs (k-s)) < curr then abs (k-s) else curr) 10000 floors\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve _ s ks = ans\n where floors = availableFloors s ks\n ans = nearestFloor floors s\n\nparse :: [String] -> String\nparse [fstLine, sndLine] = show $ solve n s ks\n where [n, s, _] = L.map (\\x -> read x :: Int) $ words fstLine\n ks = L.map (\\x -> read x :: Int) $ words sndLine\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n arr = (L.take n arr):(groupByNLines n (L.drop n arr))\n\nmain :: IO ()\nmain = interact (unlines . L.map parse . groupByNLines 2 . tail . lines)\n"}], "src_uid": "faae9c0868b92b2355947c9adcaefb43"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nee a b = go a b 1 0 0 1\n where\n go r0 r1 s0 s1 t0 t1 \n | r == 0 = (s1, t1)\n | otherwise = go r1 r s1 (s0 - q * s1) t1 (t0 - q * t1)\n where (q, r) = r0 `quotRem` r1\n\nsolve x y p q \n | p == 0 = if x == 0 then 0 else -1\n | p == q = max (x - y) (-1)\n | otherwise = s' - u' - t * q :: Integer\n where (a, b) = ee (q - p) p\n c = p*y - q*x\n (s', u') = (a * c, b * c)\n t = min (s' `div` p) (u' `div` (p - q))\n\nmain = do\n t <- fmap readInt B.getLine\n rs <- replicateM t (fmap ((\\[x, y, p, q] -> solve x y p q) . map fromIntegral . readInts) B.getLine)\n B.putStr $ B.unlines $ map (B.pack . show) rs\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . B.readInteger) <$> B.words <$> B.getContents\npair [] = []\npair (x:y:rs) = (x, y) : pair rs\nclamp u v w = max u $ min v $ w\n\nmain = do\n (_:xs) <- getIntegers\n putStrLn $ solveAll xs\n\nsolveAll [] = \"\"\nsolveAll (x:y:p:q:rs) = show (solve x y p q) ++ \"\\n\" ++ solveAll rs\n\nsolve x y p q\n | p == 0 = if x == 0 then 0 else -1\n | p == q = if x == y then 0 else -1\n | otherwise = if m == 0 then ans else -1\n where\n (g, u0, v0) = gcdex q p\n (d, m) = divMod (y * p - x * q) g\n (u1, v1) = (u0 * d, -v0 * d)\n t = min (div u1 p) (div (v1-u1) (q-p))\n ans = v1 - q * t\n\ngcdex a 0 = (a, 1, 0)\ngcdex a b = let (g, u, v) = gcdex b (mod a b) in (g, v, u - (div a b) * v)\n\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\ngetInts::IO [Integer]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInteger s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\ngetInt::IO Int\ngetInt = do\n line <- BS.getLine\n let Just (x, _ ) = BS.readInt line\n return x\n\n\nsearch::Integer->Integer->Integer->Integer->Maybe Integer\nsearch x y p q = go 0 (y + 1) where\n go u v | u + 1 >= v = fmap result $ mfilter ok $ Just v\n | ok (mid u v) = go u (mid u v)\n | otherwise = go (mid u v) v\n ok t = p * t >= x && (q - p) * t >= (y - x)\n mid u v = quot (u + v) 2\n result t = q * t - y\n\n\n\nmain :: IO ()\nmain = do\n t <- getInt\n replicateM_ t $ do\n [x,y,p,q] <- getInts\n print $ fromMaybe (-1) $ search x y p q\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nsolve :: Integer -> Integer -> Integer -> Integer -> Integer\nsolve x y p q | x' == p && y' == q = 0\n | p == 0 = (-1)\n | p == q = (-1)\n | otherwise = r * q - y\n where d = gcd x y\n x' = x `div` d\n y' = y `div` d\n\n r = max ((y - x + q - p - 1) `div` (q - p)) ((x + p - 1) `div` p)\n\nmain :: IO ()\nmain = do\n numTests <- read <$> getLine :: IO Int\n replicateM_ numTests $ do\n [x, y, p, q] <- map read . words <$> getLine :: IO [Integer]\n print $ solve x y p q\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_)\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInteger, words, unpack, reverse, dropWhile)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Char as C (isSpace)\n\nreadInt = fst . M.fromJust . C.readInteger\nrstrip = C.reverse . C.dropWhile C.isSpace . C.reverse\n\nexgcd a 0 = (a, 1, 0)\nexgcd a b = (ret, y, x - a `quot` b * y) where\n (ret, x, y) = exgcd b (a `mod` b)\n\nrun x y 0 q | x == 0 = 0 | otherwise = -1\nrun x y p q | p == q && y == x = 0 | p == q = -1\nrun x y p q | v `mod` d /= 0 = -1\n | p > q && k2 < k1 = -1\n | p > q = k1 * (q `quot` d) + vx * xx\n | otherwise = max k1 k2 * (q `quot` d) + vx * xx where\n v = q * x - p * y\n vx = v `quot` d\n (d, xx, yy) = exgcd p q\n k1 | vx * yy == 0 = 0\n | vx * yy > 0 = (vx * yy - 1) `quot` (p `quot` d) + 1\n | otherwise = (vx * yy) `quot` (p `quot` d)\n k2 | vx * (xx + yy) == 0 = 0\n | p > q && vx * (xx + yy) > 0\n = vx * (xx + yy) `quot` ((p - q) `quot` d)\n | p > q && vx * (xx + yy) < 0\n = (vx * (xx + yy) + 1) `quot` ((p - q) `quot` d) - 1\n | p < q && -vx * (xx + yy) > 0\n = (-vx * (xx + yy) - 1) `quot` ((q - p) `quot` d) + 1\n | p < q && -vx * (xx + yy) < 0\n = -vx * (xx + yy) `quot` ((q - p) `quot` d)\n\nmain = do\n (readInt -> t) <- B.getLine\n forM_ [1..t] $ \\_ -> do\n (map readInt . C.words -> [x, y, p, q]) <- B.getLine\n putStrLn $ show $ run x y p q\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nsolve :: Integer -> Integer -> Integer -> Integer -> Integer\nsolve x y p q\n | p == q = if (x == y) then 0 else -1\n | p == 0 = if (x == 0) then 0 else -1\n | otherwise = k*q-y\n where k1 = (y - x + q - p - 1) `div` (q - p)\n k2 = (x + p - 1) `div` p\n k3 = (y + q - 1) `div` q\n k = maximum [k1,k2,k3]\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n x:y:p:q:_ <- map read . words <$> getLine :: IO [Integer]\n print $ solve x y p q\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve x y p q | x' == p && y' == q = 0\n | p == 0 = (-1)\n | p == q = (-1)\n | otherwise = r * q - y\n where d = gcd x y\n x' = x `div` d\n y' = y `div` d\n\n r = max ((y - x + q - p - 1) `div` (q - p)) ((x + p - 1) `div` p)\n\nmain :: IO ()\nmain = do\n numTests <- read <$> getLine :: IO Int\n replicateM_ numTests $ do\n [x, y, p, q] <- map read . words <$> getLine\n print $ solve x y p q\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.Int\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nee a b = go a b 1 0 0 1\n where\n go r0 r1 s0 s1 t0 t1 \n | r == 0 = (s1, t1)\n | otherwise = go r1 r s1 (s0 - q * s1) t1 (t0 - q * t1)\n where (q, r) = r0 `quotRem` r1\n\nsolve x y p q \n | p == 0 = if x == 0 then 0 else -1\n | p == q = max (x - y) (-1)\n | otherwise = s' - u' - t * q :: Int64\n where (a, b) = ee (q - p) p\n c = p*y - q*x\n (s', u') = (a * c, b * c)\n t = min (s' `div` p) (u' `div` (p - q))\n\nmain = do\n t <- fmap readInt B.getLine\n rs <- replicateM t (fmap ((\\[x, y, p, q] -> solve x y p q) . map fromIntegral . readInts) B.getLine)\n B.putStr $ B.unlines $ map (B.pack . show) rs\n"}], "src_uid": "589f3f7366d1e0f9185ed0926f5a10bb"} {"source_code": "module Main where\nimport Data.List\n\nsolve [] = []\nsolve (_:x:xs) = (if head x == '1' then 1 else 0 ) + ( sum . map ((`div` 3) . length) . filter ((==\"1\").head) . group . words . tail $ x) : solve xs\n\nmain = interact $ unlines . map show . solve . tail . lines ", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> Int\nsolve li = sum [div (length s) 3 | s <- group li, head s == 1]\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n print $ solve (1:1:a)\n"}], "negative_code": [], "src_uid": "d34ffd75ef82111d1077db4b033d5195"} {"source_code": "import Control.Arrow ((>>>))\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> chunksOf 3\n >>> map (tail >>> solve >>> show)\n >>> unlines\n\nsolve :: [String] -> Int\nsolve [es, ps] = rec ps (\"0\" ++ es ++ \"0\")\n\nrec :: String -> String -> Int\nrec [] _ = 0\nrec (p : ps) (el : e : er : es) = cur + rec ps (e' : er' : es)\n where\n (cur, e', er')\n | p == '0' = (0, e, er)\n | e == '0' = (1, '-', er)\n | el == '1' = (1, e, er)\n | er == '1' = (1, e, '-')\n | otherwise = (0, e, er)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n", "positive_code": [{"source_code": "import qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BSC\r\nimport Data.Array as Array\r\nimport Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t subMain\r\n\r\nsubMain = do\r\n n <- readLn :: IO Int\r\n a <- getLine\r\n b <- getLine\r\n putStrLn . show $ memDp (BSC.pack a) (BSC.pack b) n\r\n\r\nmemDp aStr bStr ind = dp ind\r\n where\r\n dp 0 = 0\r\n\r\n dp 1\r\n | BSC.head aStr == '0' && BSC.head bStr == '1' = 1\r\n | otherwise = 0\r\n\r\n dp ind\r\n | b == '1' && prevB == '1' && a == '1' && prevA == '1' = max dp1A (dp2 + 2)\r\n | b == '1' && prevA == '1' = max dp1A (dp2 + 1)\r\n | prevB == '1' && a == '1' = max dp1A (dp2 + 1)\r\n | otherwise = dp1A\r\n where\r\n a = aStr `BSC.index` (ind - 1)\r\n prevA = aStr `BSC.index` (ind - 2)\r\n b = bStr `BSC.index` (ind - 1)\r\n prevB = bStr `BSC.index` (ind - 2)\r\n\r\n dp1 = arr ! (ind - 1)\r\n dp2 = arr ! (ind - 2)\r\n dp1A\r\n | b == '1' && a == '0' = dp1 + 1\r\n | otherwise = dp1\r\n\r\n arr = Array.listArray(0, BS.length aStr) [dp x | x <- [0 .. BS.length aStr]]"}, {"source_code": "main :: IO ()\nmain = interact $ unlines . inp . tail . words\n\ninp :: [String] -> [String]\ninp [] = []\ninp (n:s1:s2:rest) = show (solve ('0':s1++['0']) s2) : inp rest\n\nsolve :: String -> String -> Int\nsolve _ [] = 0\nsolve (x:xs) ('0':us) = solve xs us\nsolve (x:next@(y:more@(z:rest))) ('1':us)\n | x == '1' = 1 + solve next us\n | y == '0' = 1 + solve ('-':more) us\n | z == '1' = 1 + solve (y:'-':rest) us\n | otherwise = solve next us"}, {"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nmain :: IO ()\nmain = interact $ unlines . inp . tail . words\n\ninp :: [String] -> [String]\ninp [] = []\ninp (n:s1:s2:rest) = show (solve ('2':s1++['2']) s2) : inp rest\n\nsolve :: String -> String -> Int\nsolve _ [] = 0\nsolve (x:xs) ('0':us) = solve xs us\nsolve (x:next@(y:more@(z:rest))) ('1':us)\n | x == '1' = 1 + solve next us\n | y == '0' = 1 + solve ('2':more) us\n | z == '1' = 1 + solve (y:'2':rest) us\n | otherwise = solve next us"}], "negative_code": [{"source_code": "import qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BSC\r\nimport Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t subMain\r\n\r\nsubMain = do\r\n n <- readLn :: IO Int\r\n a <- BS.getLine\r\n b <- BS.getLine\r\n putStrLn . show $ memDp n a b\r\n\r\nmemDp = (map dp [0 ..] !!)\r\n\r\ndp 0 _ _ = 0\r\n\r\ndp 1 aStr bStr\r\n | BSC.head aStr == '0' && BSC.head bStr == '1' = 1\r\n | otherwise = 0\r\n\r\ndp ind aStr bStr\r\n | b == '1' && prevB == '1' && a == '1' && prevA == '1' = max dp1A (dp2 + 2)\r\n | b == '1' && prevA == '1' = max dp1A (dp2 + 1)\r\n | prevB == '1' && a == '1' = max dp1A (dp2 + 1)\r\n | otherwise = dp1A\r\n where\r\n a = aStr `BSC.index` (ind - 1)\r\n prevA = aStr `BSC.index` (ind - 2)\r\n b = bStr `BSC.index` (ind - 1)\r\n prevB = bStr `BSC.index` (ind - 2)\r\n\r\n dp1 = memDp (ind - 1) aStr bStr\r\n dp2 = memDp (ind - 2) aStr bStr\r\n dp1A\r\n | b == '1' && a == '0' = dp1 + 1\r\n | otherwise = dp1"}, {"source_code": "import Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t subMain\r\n\r\nsubMain = do\r\n n <- readLn :: IO Int\r\n a <- getLine\r\n b <- getLine\r\n putStrLn . show $ dp (reverse a) (reverse b)\r\n\r\ndp (a : prevA : otherA) (b : prevB : otherB)\r\n | b == '1' && prevB == '1' && a == '1' && prevA == '1' = max dp1 (dp2 + 2)\r\n | b == '1' && prevA == '1' = max dp1 (dp2 + 1)\r\n | prevB == '1' && a == '1' = max dp1 (dp2 + 1)\r\n | b == '1' && a == '0' = dp1 + 1\r\n | otherwise = dp1\r\n where\r\n dp1 = dp (prevA : otherA) (prevB : otherB)\r\n dp2 = dp otherA otherB\r\n\r\ndp (a : otherA) (b : otherB)\r\n | a == '0' && b == '1' = 1\r\n | otherwise = 0\r\n\r\ndp [] [] = 0"}, {"source_code": "import Control.Monad\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t subMain\r\n\r\nsubMain = do\r\n n <- readLn :: IO Int\r\n a <- getLine\r\n b <- getLine\r\n putStrLn . show $ dp (reverse a) (reverse b)\r\n\r\ndp :: String -> String -> Int\r\ndp (a : prevA : otherA) (b : prevB : otherB)\r\n | b == '1' && prevB == '0' && prevA == '1' = max dp1 (dp2 + 1)\r\n | b == '1' && prevB == '1' && a == '1' && prevA == '1' = max dp1 (dp2 + 2)\r\n | prevB == '1' && a == '1' = max dp1 (dp2 + 1)\r\n | b == '1' && a == '0' = dp1 + 1\r\n | otherwise = dp1\r\n where\r\n dp1 = dp (prevA : otherA) (prevB : otherB)\r\n dp2 = dp otherA otherB\r\n\r\ndp (a : otherA) (b : otherB)\r\n | a == '0' && b == '1' = 1\r\n | otherwise = 0\r\n\r\ndp [] [] = 0"}], "src_uid": "c05426881a7dccc1aa79608b612290a7"} {"source_code": "calculate :: [Int] -> Int -> Int -> [Int] \r\ncalculate [] acc value = []\r\ncalculate (x:xs) acc value \r\n | acc + x /= value = [x] ++ calculate xs (acc + x) value\r\n | otherwise = calculate (xs ++ [x]) acc value\r\n \r\ngetAns :: Int -> [Int] -> [String]\r\ngetAns value nums \r\n | sum nums == value = [\"NO\"]\r\n | otherwise = [\"YES\", unwords $ map show $ calculate nums 0 value]\r\n \r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:xs) = \r\n (getAns value $ toInt $ head xs) ++ (solve $ tail xs)\r\n where\r\n toInt str = map read $ words str\r\n [_, value] = toInt x\r\n \r\nmain = \r\n interact $ unlines . helper . lines\r\n where \r\n helper (x:xs) = solve xs", "positive_code": [{"source_code": "calculate :: [Int] -> Int -> Int -> [Int] \r\ncalculate [] acc value = []\r\ncalculate (x:xs) acc value \r\n | acc + x /= value = [x] ++ calculate xs (acc + x) value\r\n | otherwise = calculate (xs ++ [x]) acc value\r\n\r\ngetAns :: Int -> [Int] -> [String]\r\ngetAns value nums \r\n | sum nums == value = [\"NO\"]\r\n | otherwise = [\"YES\", unwords $ map show $ calculate nums 0 value]\r\n\r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:xs) = \r\n (getAns value $ toInt $ head xs) ++ (solve $ tail xs)\r\n where\r\n toInt str = map read $ words str\r\n [_, value] = toInt x\r\n\r\nmain = \r\n interact $ unlines . helper . lines\r\n where \r\n helper (x:xs) = solve xs"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\n\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n [n,x] <- map parseInt . BS.words <$> BS.getLine\r\n a <- map parseInt . BS.words <$> BS.getLine\r\n let s = scanl1 (+) a\r\n win r = putStrLn \"YES\" >> (putStrLn . unwords . map show $ r)\r\n lose = putStrLn \"NO\"\r\n case elemIndex x s of\r\n Just i ->\r\n if i == n-1 then\r\n lose\r\n else\r\n win $ take i a ++ [a !! (i+1), a !! i] ++ drop (i+2) a\r\n Nothing ->\r\n win a\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, x] <- readInts\n w <- readInts\n case [i | (i, wps) <- zip [0..] $ scanl (+) 0 w, wps == x] of\n [] -> lift (putStrLn \"YES\") >> putInts w\n [ix] | ix == n -> lift $ putStrLn \"NO\"\n | otherwise -> let\n (p1, p2:p3:p4) = splitAt (ix - 1) w\n in lift (putStrLn \"YES\") >> putInts (p1 ++ p3:p2:p4)\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "calculate :: [Int] -> Int -> Int -> [Int] \r\ncalculate [] acc value = []\r\ncalculate (x:xs) acc value \r\n | acc + x /= value = [x] ++ calculate xs (acc + x) value\r\n | otherwise = calculate ((head xs):x:(tail xs)) acc value\r\n \r\ngetAns :: Int -> [Int] -> [String]\r\ngetAns value nums \r\n | sum nums == value = [\"NO\"]\r\n | otherwise = [\"YES\", unwords $ map show $ calculate nums 0 value]\r\n \r\nsolve :: [String] -> [String]\r\nsolve [] = []\r\nsolve (x:xs) = \r\n (getAns value $ toInt $ head xs) ++ (solve $ tail xs)\r\n where\r\n toInt str = map read $ words str\r\n [_, value] = toInt x\r\n \r\nmain = \r\n interact $ unlines . helper . lines\r\n where \r\n helper (x:xs) = solve xs"}], "negative_code": [], "src_uid": "85383c9e802348a3153e7f98ce278f09"} {"source_code": "import Data.List\n\ncalc :: [Int] -> Int\ncalc xs = d + c + b' + a''\n where [a,b,c,d] = map (pred . length) . group . sort $ xs ++ [1,2,3,4]\n a' = max (a-c) 0\n (b',r) = b `divMod` 2\n a'' = (a' + r * 2 + 3 ) `div` 4\nmain = getLine >> getLine >>=\n putStrLn . show . calc . map read . words\n", "positive_code": [{"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Fri 19 Oct 2012 06:27:10 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\n\ncountBy ls cond= length $ filter cond ls\n\n\ncount ls k = countBy ls (\\s -> s == k)\n\nkth ls k = head $ drop k ls\nremaining ls k = \n let\n limit = kth (sort ls) k\n in\n countBy ls (\\s -> s >= limit && s > 0)\n\n\ncalcrem1s c3s c1s = \n if c3s >= c1s\n then \n 0\n else\n c1s-c3s\n\nposORZero num =\n if num >= 0\n then\n num\n else\n 0\n\ncalc groups = \n let c2s = count groups 2\n rem1s = posORZero $ (count groups 1) - (count groups 3)\n in\n let \n rem2s = c2s `mod` 2\n in\n let \n finalrem1s =\n if rem2s == 1\n then\n posORZero $ rem1s - 2\n else\n rem1s\n in\n (count groups 4) + (count groups 3) + (ceiling $ fromIntegral(c2s) / 2) + (ceiling $ fromIntegral(finalrem1s) / 4)\n\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInt all\n let (groups, _) = readMany readInt r1\n print $ calc groups\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\nget :: IO [Int]\nget = fmap (map read . words) getLine\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve 0 0 0 0 = 0\nsolve n1 0 0 0 = n1 `div` 4 + (if n1 `mod` 4 /= 0 then 1 else 0)\nsolve n1 n2 0 0 = n2 `div` 2 + n2 `mod` 2 + solve (if n2 `mod` 2 == 1 then max (n1 - 2) 0 else n1) 0 0 0\nsolve n1 n2 n3 0 = n3 + solve (max (n1 - n3) 0) n2 0 0\nsolve n1 n2 n3 n4 = n4 + solve n1 n2 n3 0\n\nmain = do\n\t_ <- get\n\ttemp <- get\n\tlet [n1, n2, n3, n4] = [length $ filter (==x) temp | x <- [1..4]]\n\tprint $ solve n1 n2 n3 n4"}, {"source_code": "{-# LANGUAGE CPP, TemplateHaskell #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Main (\n main\n) where\n\nimport Control.Monad (unless)\nimport Data.List (stripPrefix, sort, reverse)\nimport System.Exit (exitFailure)\nimport Data.Int\nimport Data.Maybe\nimport Data.Sequence as Seq\n--import Debug.Trace\n\n\n#ifdef MAIN_FUNCTION\nimport Test.Framework.TH\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\nimport Test.Framework.Providers.QuickCheck2\n\nimport Test.QuickCheck\nimport Test.HUnit\n\nimport Data.List\n\n\n#endif\n\n\nmaxCap = 4\n\n\nmaxLessThen :: Seq Int->Int->(Maybe Int, Seq Int)\n\nmaxLessThen s x \n | h<=x = (Just h, t)\n | l<=x = (Just l, t')\n | otherwise = (Nothing, s)\n where h :< t = Seq.viewl s\n t' :> l = Seq.viewr s\n\n\ncount :: [Int]->Int\ncount l = countSeq $ Seq.fromList $ Data.List.reverse $ Data.List.sort l \n\ncountSeq :: Seq Int->Int\ncountSeq l = count' l maxCap\n\ncount' :: Seq Int->Int->Int\n--count' l x | trace (\"count' \" ++ show l ++ \" \" ++ show x) False = undefined\ncount' (Seq.viewl -> EmptyL) 4 = 0\ncount' (Seq.viewl -> EmptyL) _ = 1\ncount' l x \n | m == Nothing = 1 + count' l maxCap\n | otherwise = count' l' (x - fromJust m)\n where \n (m, l') = maxLessThen l x\n\n \n\nexeMain = do\n getLine\n groups <- (map read . words) `fmap` getLine\n print $ count groups\n\n-- Tests --\n\n#ifdef MAIN_FUNCTION\ntestMain = $(defaultMainGenerator)\n\ncase_1 = count [1, 2, 4, 3, 3] @?= 4\n\ncase_2 = count [2, 3, 4, 4, 2, 1, 3, 1] @?= 5\n\ncase_3 = count [4] @?= 1\n\ncase_4 = count [1] @?= 1\n\ncase_5 = count [3, 1] @?= 1\n\ncase_6 = count [3, 2] @?= 2\n\n\n\n\n#endif\n\n#ifndef MAIN_FUNCTION\n#define MAIN_FUNCTION exeMain\n#endif\nmain = MAIN_FUNCTION"}, {"source_code": "import Data.Char\n\nsolve :: [Int] -> Int\nsolve xs = \n let one = count 1 xs\n two = count 2 xs\n three = count 3 xs\n four = count 4 xs\n in four + three + (quot two 2) + (rem two 2) +\n div (one + 3 - (min one (three + 2 * (rem two 2)))) 4\n where count x = length . filter (==x)\n\nmain = do\n getLine\n l <- getLine\n print . solve . map read $ words l\n"}, {"source_code": "\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> Int\nsolve xs = solve' (map (\\m -> counts m xs) [1..4])\n where\n counts :: Int -> [Int] -> Int\n counts m xs = length (filter (== m) xs)\n\n solve' :: [Int] -> Int\n solve' [o, w, t, f]\n = f + t + divUp w 2 + divUp (max 0 (o - t - 2 * mod w 2)) 4\n where\n divUp a b = div a b + if mod a b > 0 then 1 else 0\n\nmain :: IO ()\nmain = do\n getLine\n Main.reads >>= print . solve\n"}, {"source_code": "-- Codeforces 158B\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= putStrLn . show . solve . map read . words where\n solve xs = d + c + (b * 2 + 3 + max 0 (a - c)) `div` 4 where\n [a, b, c, d] = map (\\x -> length $ filter (== x) xs) [1 .. 4]\n \n"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = do\n line <- getLine\n let xs = map read . words $ line :: [Int]\n return xs\n\nfrequncy :: Ord a => [a] -> [(a, Int)]\nfrequncy = map (\\ys -> (head ys, length ys)) . group . sort\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just a) -> a\n Nothing -> d\n\ninfixl 7 //\na // b = ceiling $ (fromIntegral a) / b\n \nmain = do\n getLine\n xs <- readInts\n let ys = frequncy xs\n let a:b:c:d:_ = map (lookupOr 0 ys) [1..4]\n let r = d + c + (max (a - c) 0 + b * 2) // 4\n print r"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.Array.Unboxed\nimport Data.List (sort)\n\nmain = do\n n <- read <$> getLine\n ss <- map read . words <$> getLine\n let ar = listArray (1,n) . sort $ ss :: Array Int Int\n print $ reqCars ar 1 n 0 0\n\nreqCars a !i !j !c !r\n | i > j = c\n | a!i <= r = reqCars a (i+1) j c (r-a!i)\n | otherwise = reqCars a i (j-1) (c+1) (4-a!j)"}, {"source_code": "\nalloc :: [Int] -> Int -> Int -> Int -> Int -> Int\nalloc [] o tw th f\n | ((mod tw 2) == 0) = f + th + (ceiling (fromIntegral tw/2)) + (ceiling (fromIntegral o/4))\n | (((mod tw 2) > 0) && (o<3)) = f + th + (ceiling (fromIntegral tw/2))\n | (((mod tw 2) > 0) && (o>2)) = f + th + (ceiling (fromIntegral tw/2)) + (ceiling (fromIntegral (o-2)/4))\n\nalloc (4:xs) o tw th f = alloc xs o tw th (f+1)\n\nalloc (3:xs) o tw th f\n | o>0 = alloc xs (o-1) tw th (f+1)\n | o == 0 = alloc xs o tw (th+1) f\n\nalloc (2:xs) o tw th f\n | tw>0 = alloc xs o (tw-1) th (f+1)\n | tw == 0 = alloc xs o (tw+1) th f\n\nalloc (1:xs) o tw th f\n | th>0 = alloc xs o tw (th-1) (f+1)\n | th == 0 = alloc xs (o+1) tw th f\n\n\n\nmain = do\n _ <- getLine\n groups <- getLine\n\n print $\n alloc (\n map (read :: String -> Int) $\n words groups\n ) 0 0 0 0\n"}, {"source_code": "alloc :: [Int] -> Int -> Int -> Int -> Int -> Int\nalloc [] o tw th f\n | ((mod tw 2) == 0) = f + th + (ceiling (fromIntegral tw/2)) + (ceiling (fromIntegral o/4))\n | (((mod tw 2) > 0) && (o<3)) = f + th + (ceiling (fromIntegral tw/2))\n | (((mod tw 2) > 0) && (o>2)) = f + th + (ceiling (fromIntegral tw/2)) + (ceiling (fromIntegral (o-2)/4))\nalloc (4:xs) o tw th f = alloc xs o tw th (f+1)\nalloc (3:xs) o tw th f\n | o>0 = alloc xs (o-1) tw th (f+1)\n | o == 0 = alloc xs o tw (th+1) f\nalloc (2:xs) o tw th f\n | tw>0 = alloc xs o (tw-1) th (f+1)\n | tw == 0 = alloc xs o (tw+1) th f\nalloc (1:xs) o tw th f\n | th>0 = alloc xs o tw (th-1) (f+1)\n | th == 0 = alloc xs (o+1) tw th f\nmain = do\n _ <- getLine\n groups <- getLine\n print $\n alloc (\n map (read :: String -> Int) $\n words groups\n ) 0 0 0 0\n"}, {"source_code": "main = do\n\tn <- getLine\n\targs <- getList ' '\n\tputStrLn . show . calc . parseGroups $ args\n\ngetList::Char -> IO [String]\ngetList sep = do\n\tinput <- getLine\n\treturn $ split input sep\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep then \"\":acc\n\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc) ) [\"\"] str\n\t\t\t\t\t\t\t\t\t\ncalc::[Int] -> Int\ncalc groups = do\n\tlet fours = groups !! 3\n\tlet threes = groups !! 2\n\tlet twos = ceiling . (/ 2) . fromIntegral $ groups !! 1\n\tlet ones = ceiling . (/ 4) . fromIntegral $ groups !! 0 - threes - (groups !! 1 `mod` 2 * 2)\n\tfours + threes + twos + if ones > 0 then ones else 0\n\t\nparseGroups::[String] -> [Int]\nparseGroups args = foldr (\\curr acc -> if curr == \"1\" then [ acc !! 0 + 1, acc !! 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"2\" then [ acc !! 0, acc !! 1 + 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"3\" then [ acc !! 0, acc !! 1, acc !! 2 + 1, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else [ acc !! 0, acc !! 1, acc !! 2, acc !! 3 + 1 ]) [0,0,0,0] args"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = g4 + g3 + (g2 + 1) `div` 2 + max 0 (g1 - g3 - g2 `mod` 2 * 2 + 3) `div` 4\n where cnt = accumArray (+) 0 (1,4) $ zip a (repeat 1)\n g4 = cnt ! 4\n g3 = cnt ! 3\n g2 = cnt ! 2\n g1 = cnt ! 1\n\nmain :: IO ()\nmain = do\n _ <- getLine -- n\n a <- getIntList\n putStrLn . show $ solve a\n \n"}, {"source_code": "-- import Data.Char\n-- import Data.Int\n-- import Data.List\n-- import Control.Monad\ngetList :: Read a => IO [a]\ngetList = fmap (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve a = g4 + g3 + (g2 + 1) `div` 2 + max 0 (g1 - g3 - g2 `mod` 2 * 2 + 3) `div` 4\n where g4 = length . filter (== 4) $ a :: Int\n g3 = length . filter (== 3) $ a :: Int\n g2 = length . filter (== 2) $ a :: Int\n g1 = length . filter (== 1) $ a :: Int\n\nmain :: IO ()\nmain = do\n _ <- readLn :: IO Int\n a <- getList :: IO [Int]\n putStrLn . show $ solve a\n \n"}, {"source_code": "solve [a, b, c, d] = d + c + (b * 2 + 3 + max 0 (a-c)) `div` 4\n\nmain = do\n _ <- getLine\n groups <- fmap(map read.words) getLine\n print $ solve $ map(\\x -> length $ filter (==x) groups ) [1..4]\n"}, {"source_code": "main = do\n num<-getLine\n s<-fmap(map read.words)getLine\n let [a,b,c,d] = map (\\x -> length $ filter (==x) s ) [1..4]\n print $ d+c+(b*2+3+max 0 ( a-c))`div`4"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Data.Array\n\nprocess a b | ab = \"1\"\n | otherwise = \"0\"\n\nmain::IO ()\nmain=do\n getLine\n a<-map read <$> words <$> getLine\n let b =accumArray (+) 0 (1,4) (zip a (repeat 1))\n let [c1,c2,c3,c4]= elems b\n let nc1 = (max 0 (c1-c3-(if odd c2 then 2 else 0)))\n let nc2 = div nc1 4\n let nc3 = if mod nc1 4 ==0 then 0 else 1\n print $ c4 + c3 + (div c2 2) + (if (odd c2) then 1 else 0) + nc2 +nc3\n \n"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Control.Applicative\n\nmain = do\n n:ss <- (`fmap` getContents) $ words >>> map read\n let n1:n2:n3:n4:_ = map ((==) >>> (`filter` ss) >>> length) [1..]\n print $ n4 + n3 + (n2*2 + 3 + max 0 (n1-n3)) `div` 4\n"}, {"source_code": "\nmodule Main where\n\nimport Control.Arrow\nimport Control.Applicative\n\nimport Data.ByteString.Char8 (getContents,words,readInt)\nimport Prelude hiding(getContents,words)\nimport Data.Maybe\n\nmain = do\n n:ss <- (`fmap` getContents) $ words >>> map (readInt >>> fromJust >>> fst)\n let n1:n2:n3:n4:_ = map ((==) >>> (`filter` ss) >>> length) [1..]\n print $ n4 + n3 + (n2*2 + 3 + max 0 (n1-n3)) `div` 4\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n s <- accumArray (+) 0 (1, 4) . flip zip (repeat 1) <$> replicateM n readInt :: State ByteString (UArray Int Int)\n return (elems s)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve [one, two, three, four] = four + three + solve2 (one - min three one) two\n\nsolve2 one two | two >= 2 = solve2 one (two `mod` 2) + two `div` 2\nsolve2 one 1 = solve2 (one - min one 2) 0 + 1\nsolve2 one 0 = (one + 3) `div` 4\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= print . solve . map (fst . fromJust . B.readInt) . B.words . (!!1) . B.lines\n\nsolve :: [Int] -> Int\nsolve = go . count (0, 0, 0, 0)\n where go (0, 0, 0, n) = (n + 3) `div` 4\n go (0, 0, n, k) = (n + 1) `div` 2 + go (0, 0, 0, max 0 (k - 2 * (n `mod` 2)))\n go (0, n, k, l) = n + go (0, 0, k, max 0 (l - n))\n go (n, k, l, m) = n + go (0, k, l, m)\n count (a, b, c, d) (4:ss) = count (a + 1, b, c, d) ss\n count (a, b, c, d) (3:ss) = count (a, b + 1, c, d) ss\n count (a, b, c, d) (2:ss) = count (a, b, c + 1, d) ss\n count (a, b, c, d) (1:ss) = count (a, b, c, d + 1) ss\n count x _ = x\n"}, {"source_code": "import Prelude hiding (readList)\nimport Control.Monad\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\nmain :: IO ()\nmain = do\n skipLine\n xs <- readList' (undefined::Int)\n let n1 = count (==1) xs\n n2 = count (==2) xs\n n3 = count (==3) xs\n n4 = count (==4) xs\n n1' = n1 - min n1 n3\n n1'' | odd n2 = max 0 (n1' - 2)\n | otherwise = n1'\n print $ n4 + n3 + (n2 `divUp` 2) + (n1'' `divUp` 4)\n"}, {"source_code": "{-# options_ghc -O2 #-}\n\nimport Prelude hiding (readList)\nimport Control.Monad\nimport Data.List\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\ncountFreqs :: (Int,Int,Int,Int) -> Int -> (Int,Int,Int,Int)\ncountFreqs (a,b,c,d) 1 = (a+1,b,c,d)\ncountFreqs (a,b,c,d) 2 = (a,b+1,c,d)\ncountFreqs (a,b,c,d) 3 = (a,b,c+1,d)\ncountFreqs (a,b,c,d) 4 = (a,b,c,d+1)\n\nmain :: IO ()\nmain = do\n skipLine\n xs <- readList' (undefined::Int)\n let (n1,n2,n3,n4) = foldl' countFreqs (0,0,0,0) xs\n n1' = n1 - min n1 n3\n n1'' | odd n2 = max 0 (n1' - 2)\n | otherwise = n1'\n print $ n4 + n3 + (n2 `divUp` 2) + (n1'' `divUp` 4)\n"}, {"source_code": "{-# options_ghc -O2 #-}\n\nimport Prelude hiding (readList)\nimport Control.Monad\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\nmain :: IO ()\nmain = do\n skipLine\n xs <- readList' (undefined::Int)\n let n1 = count (==1) xs\n n2 = count (==2) xs\n n3 = count (==3) xs\n n4 = count (==4) xs\n n1' = n1 - min n1 n3\n n1'' | odd n2 = max 0 (n1' - 2)\n | otherwise = n1'\n print $ n4 + n3 + (n2 `divUp` 2) + (n1'' `divUp` 4)\n"}, {"source_code": "import Data.List(foldl')\n\nsolve :: [Int] -> Int\nsolve xs = c4 + c3 + c2 `div` 2 + countRest c1 c2 c3 c4\n where\n (c1, c2, c3, c4) = foldl' (\\acc x -> countNumbers acc x) (0,0,0,0) xs\n countNumbers (a1, a2, a3, a4) x | x == 1 = (a1 + 1, a2, a3, a4)\n | x == 2 = (a1, a2 + 1, a3, a4)\n | x == 3 = (a1, a2, a3 + 1, a4)\n | x == 4 = (a1, a2, a3, a4 + 1)\n countRest a1 a2 a3 a4 = let a1With3 = min a1 a3\n a1AfterSittingWith3 = a1 - a1With3\n a1With2 = if (a2 `mod` 2 == 1 && a1AfterSittingWith3 > 0) then min a1AfterSittingWith3 2 else 0\n a1AfterSittingWith2 = a1AfterSittingWith3 - a1With2\n a1With1 = a1AfterSittingWith2 - a1AfterSittingWith2 `mod` 4\n a1AfterSittingWith1 = a1AfterSittingWith2 - a1With1\n in a1With1 `div` 4 + (if (a1AfterSittingWith1 > 0) then 1 else 0) + (if (a2 `mod` 2 == 1) then 1 else 0)\n\nmain = do\n getLine\n xs <- fmap (map read . words) getLine\n print $ solve xs\n"}, {"source_code": "taxi :: [Int] -> Int\ntaxi s = t4 + t31 + t3 + t2 + t21 + t1\n where t4 = count 4 s\n t31 = min c3 c1\n t3 = c3 - t31\n t2 = div c2 2\n t21 = rem c2 2\n t1 = (div (r1 - 1) 4) + 1\n r1 = max (c1 - t31 - t21 * 2) 0\n c1 = count 1 s\n c2 = count 2 s\n c3 = count 3 s\n count x = length . filter (==x)\n\nmain = do\n getLine\n s <- getLine\n print $ taxi $ map read $ words s\n"}, {"source_code": "main = print . solve . map read . tail . words =<< getContents\nsolve ss = n4 + n3 + n2 `div` 2 + (if odd n2 then 1 else 0) + (n1'' + 3) `div` 4\n where n1 = length (filter (==1) ss)\n n2 = length (filter (==2) ss)\n n3 = length (filter (==3) ss)\n n4 = length (filter (==4) ss)\n n1' = max (n1 - n3) 0\n n1'' = if odd n2 then max (n1' - 2) 0 else n1'\n"}, {"source_code": "\ncount :: [Int] -> [Int]\ncount [] = [0, 0, 0, 0]\ncount (x:xs) = take (x-1) a ++ [ (a !! (x-1) ) + 1] ++ drop x a where a = count xs \n\nsolve' :: [Int] -> Int\nsolve' [x, y, z, w] \n | w>0 = solve' [x, y, z, w-1] + 1 \n | (z>0) = solve' [max 0 x-1, y, z-1, w] +1\n | y>1 = solve' [x, y-2, z, w] +1\n | y==1 = solve' [max 0 x-2, y-1, z, w]+1\n | x>0 = solve' [max 0 x-4, y, z, w] +1\n | otherwise = 0\n\nsolve' _ = 0\n\n\nsolve :: [Int] -> Int\nsolve = solve' . count\n\nreadInt :: String -> Int\nreadInt = read\n\nparse :: String -> String\nparse x = show $ solve $ tail $ map readInt $ words x \nmain = interact parse"}, {"source_code": "enc :: [Int] -> Int -> Int\nenc s a = length $ filter (==a) s\n\ntaxis :: [Int] -> Int\ntaxis s = fours + threesOnes + twosTwos + onesTwos + leftOnes2 + fourOnes + (threes - threesOnes)\n where ones = enc s 1\n twos = enc s 2\n threes = enc s 3\n fours = enc s 4\n threesOnes = min ones threes\n twosTwos = twos `div` 2\n onesTwos = twos `mod` 2\n leftOnes = if onesTwos == 0 then (ones - threesOnes)\n else if (ones - threesOnes) > 2 then (ones - threesOnes - 2)\n else 0\n fourOnes = leftOnes `div` 4\n leftOnes2 = if leftOnes `mod` 4 > 0 then 1 else 0\n\nmain = do getLine\n numbers <- fmap (map read . words) getLine\n (putStrLn . show . taxis) numbers\n"}, {"source_code": "module Main where\n\nmain = interact parse\n\nparse :: String -> String\nparse input = show $ work $ map read $ tail $ words $ input\n\ncountOf :: Int -> [Int] -> Int\ncountOf num list = length $ filter (== num) list\n\npositive :: Int -> Int\npositive i = if i > 0 then i else 0\n\nwork :: [Int] -> Int\nwork list = solve (countOf 1 list) (countOf 2 list) (countOf 3 list) (countOf 4 list)\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve c1 c2 c3 c4 = c4 + div c2 2 + min c1 c3 + p31 + div p13 4 + if mod c2 2 == 0 then\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif mod p13 4 == 0 then 0 else 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse if mod p13 4 == 3 then 2 else 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere\n\t\tp31 = positive (c3 - c1)\n\t\tp13 = positive (c1 - c3)\n"}, {"source_code": "main = do\n _ <- getLine\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if free1s >= (amounts !! 1) then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4\n"}, {"source_code": "main = do\n _ <- getLine\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if free1s >= (amounts !! 1) then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4"}, {"source_code": "module Main where\n\ntype Counts = (Int, Int, Int, Int)\n\ncountChildren :: Counts -> [Int] -> Counts\ncountChildren c [] = c\ncountChildren (on, tw, th, fo) (x: xs)\n | x == 1 = countChildren (on + 1, tw, th, fo) xs\n | x == 2 = countChildren (on, tw + 1, th, fo) xs\n | x == 3 = countChildren (on, tw, th + 1, fo) xs\n | x == 4 = countChildren (on, tw, th, fo + 1) xs\n | otherwise = (on, tw, th, fo)\n\nmain :: IO ()\nmain = do\n _ <- fmap read getLine :: IO Int\n inp <- fmap words getLine :: IO [String]\n let s = fmap read inp :: [Int]\n (ones, twos, threes, fours) = countChildren (0, 0, 0, 0) s\n (coupleTwos, loneTwos) = twos `quotRem` 2\n remOnesAfterThrees = max (ones - threes) 0\n (foursOnes, leftOnes) = remOnesAfterThrees `quotRem` 4\n (remCabs, remChild) = (loneTwos * 2 + leftOnes) `quotRem` 4\n res1 = fours + -- fours take a cab to themselves\n min ones threes + -- combine threes and ones to one cab\n max (threes - ones) 0 + -- remaining threes each take one cab\n coupleTwos + -- twos can combine with themselves\n foursOnes + -- group remaining ones into 4 per cab\n remCabs + -- fit any remaining twos and ones in a cab\n if remChild > 0 then 1 else 0 -- any children left can fit in last 1 cab\n\n print res1\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/158/B\n\nimport Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = g4 + g3 + (g2 + 1) `div` 2 + max 0 (g1 - g3 - g2 `mod` 2 * 2 + 3) `div` 4\n where cnt = accumArray (+) 0 (1,4) $ zip a (repeat 1)\n g4 = cnt ! 4\n g3 = cnt ! 3\n g2 = cnt ! 2\n g1 = cnt ! 1\n\nmain :: IO ()\nmain = do\n _ <- getLine -- n\n a <- getIntList\n putStrLn . show $ solve a\n"}, {"source_code": "count x = length . filter (x==)\n\ndivUp x y = div (x + y - 1) y\n\nsolve a = fours + threes + divUp ((max (ones - threes) 0) + twos * 2) 4\n where\n ones = count 1 a\n twos = count 2 a\n threes = count 3 a\n fours = count 4 a\n\nmain = print . solve . map read . words . last . lines =<< getContents\n"}, {"source_code": "hist l = map (\\x -> length $ filter (== x) l ) [1..4]\nsolve [a,b,c,d] = d + c + (2 * b + 3 + (max 0 (a - c))) `div` 4\nmain = interact $ show . solve . hist . map read . tail . words\n"}, {"source_code": "main = do\n irrelevant <- getLine\n input <- getLine\n let list = map read (words input)\n let (a,b,c,d) = (countN list 1, countN list 2, countN list 3, countN list 4)\n let b2 = b `div` 2 \n let c2 = if c>=a then c else c + (a-c) `div` 4\n let a2 | a>c && (a-c) `mod` 4 == 3 && odd b = 2\n | a>c && (a-c) `mod` 4 == 3 && even b = 1\n | a>c && (a-c) `mod` 4 == 2 && odd b = 1\n | a>c && (a-c) `mod` 4 == 2 && even b = 1\n | a>c && (a-c) `mod` 4 == 1 && odd b = 1\n | a>c && (a-c) `mod` 4 == 1 && even b = 1\n | a>c && (a-c) `mod` 4 == 0 && odd b = 1\n | a>c && (a-c) `mod` 4 == 0 && even b = 0\n | odd b = 1\n | otherwise = 0\n let answer = d + b2 + c2 + a2\n putStrLn (show answer)\n\ncountN xs n = length (filter (\\x -> x==n) xs)\n"}, {"source_code": "module Main where\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map read . words <$> getLine\n putStrLn $ show . solve $ xs\n\nsolve :: [Int] -> Int\nsolve xs = cnt!!3 + cnt!!2 + (div (cnt!!1) 2) + rest (maximum[cnt!!0 - cnt!!2, 0], cnt!!1)\n where cnt = [length $ filter (==x) xs | x <- [1..4]]\n\nrest :: (Int, Int) -> Int\nrest (one, two)\n | two `mod` 2 == 1 = (div (one + 1) 4) + 1\n | otherwise = div (one + 3) 4"}, {"source_code": "\nmain = do\n _ <- getLine\n l <- getLine\n putStrLn $ show $ solve $ map read $ words l\n \n-- solve :: [Int] -> Int\n-- solve gs = gof 4 gs + gof 3 gs + gof_2 + gof_1\n -- where\n -- gof_2 = let r = gof 2 gs in r `quot` 2 + r `rem` 2\n -- gof_1\n -- | gof_3_1 < 0 = 0\n -- | gof_3_2_1 < 0 = 0\n -- | otherwise = gof_3_2_1 `quot` 4 + (if gof_3_2_1 `rem` 4 > 0 then 1 else 0)\n -- where gof_3_1 = gof 1 gs - gof 3 gs\n -- gof_3_2_1 = gof_3_1 - (if odd gof 2 gs then 2 else 0)\n \ncount :: Int -> [Int] -> Int\ncount x xs = length $ filter (==x) xs\n\nsolve :: [Int] -> Int\nsolve xs = n_4 + n_3 + n_2 + n_1\n where n_4 = count 4 xs\n n_3 = count 3 xs\n n_2 = ceiling $ (fromIntegral $ count 2 xs) / 2.0 -- groups of 2 people fit into one more than the # of groupd div 2\n leftover = (count 1 xs) - n_3 - ((count 2 xs) `mod` 2 * 2) -- get the number of single person groups left over after filling up the 3-cars and the odd 2 person car\n n_1 = if leftover > 0 then ceiling $ (fromIntegral leftover) / 4.0 else 0\n\n\n"}, {"source_code": "main = do\n getLine\n gr <-getLine\n let \n groups = map read $ words gr\n n1 = length $ filter (==1) groups\n n2 = length $ filter (==2) groups\n n3 = length $ filter (==3) groups\n n4 = length $ filter (==4) groups\n n21 = (n2 + 1)`div`2\n n11 = if (n2 `mod` 2 /= 0) then\n n1 - n3 - 2\n else \n n1 - n3\n n12 = if (n11 > 0) then\n (n11+3) `div` 4\n else \n 0\n putStrLn $ show (n4 + n3 + n21 + n12)\n "}, {"source_code": "import Data.Array\nimport Control.Monad\n\ncount list = accumArray (flip $ const (+1)) 0 (1, 4) (zip list (repeat undefined))\n\nsolve x4 x3 x2 x1 | x4 > 0 = solve 0 x3 x2 x1 + x4\nsolve 0 x3 x2 x1 | x3 > 0 && x1 > 0 = let x = min x1 x3 in solve 0 (x3-x) x2 (x1-x) + x\nsolve 0 x3 x2 x1 | x3 > 0 = solve 0 0 x2 x1 + x3\nsolve 0 0 x2 x1 | x2 > 1 = solve 0 0 (x2 `mod` 2) x1 + x2 `div` 2\nsolve 0 0 1 x1 = solve 0 0 0 (max 0 (x1-2)) + 1\nsolve 0 0 0 x1 = (x1 + 3) `div` 4\n\nmain = do\n _ <- getLine\n list <- liftM (map read . words) getLine\n\n let c = count list\n print $ solve (c!4) (c!3) (c!2) (c!1)\n"}, {"source_code": "main :: IO ()\nmain = do \n n <- getLine\n inputs <- fmap (map read.words) getLine\n let [a,b,c,d] = map (\\x -> length $ filter (==x) inputs) [1,2,3,4]\n print $ d + c + ((b*2 + 3 + (max 0 (a - c))) `div` 4)\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && (filter (==1) nums == []) = process (drop (j) (filter (==3) nums) ++ filter (/=3) nums) (k + j)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop h (filter (==3) nums) ++ drop h (filter (==1) nums) ++ (filter (==2) nums)) (k + h)\n | filter (==2) nums /= [] && (length (filter (==2) nums) >= 2) = process (drop (p * 2) (filter (==2) nums) ++ filter (/=2) nums) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop 2 (filter (==2) nums) ++ filter (/=2) nums) (k + 1)\n | length (filter (==1) nums) > 1 && filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop 1 (filter (==2) nums) ++ drop 2 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop 1 (filter (==2) nums) ++ drop 1 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop (g * 4) (filter (==1) nums)) (k + g)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n f = (length (filter (==1) nums))\n g = (length (filter (==1) nums)) `div` 4\n p = (length (filter (==2) nums)) `div` 2\n j = (length (filter (==3) nums))\n h = if length (filter (==3) nums) > length (filter (==1) nums) then length (filter (==1) nums) else length (filter (==3) nums) \n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "\nmycount :: [Int] -> Int -> Int\nmycount [] k = 0\nmycount (x:xs) k =\n if x == k\n then 1 + mycount xs k\n else mycount xs k\n\nmain = do\n str <- getContents\n let\n n:a = map read $ words str\n c = [mycount a x | x <- [1..4]]\n three = min (c!!0) (c!!2)\n ans = (c!!3) + (c!!2) + ((c!!1) * 2 + ((c!!0) - three) + 3) `div` 4 \n putStrLn $ show ans\n"}, {"source_code": "import Data.List\n\nmain = interact $ show . taxis . map (pred . length) . group . sort . ([\"1\",\"2\",\"3\",\"4\"]++) . tail . words\n\ntaxis [a,b,c,d] = d + c + b' + bm + a'\n where\n (b', bm) = quotRem b 2\n a' = (`quot` 4) . (+3) . max 0 $ (a - c - 2*bm)\n"}, {"source_code": "import Data.List (foldl')\nmain :: IO ()\nmain = do\n _ <- getLine\n ss <- getLine\n let groups = map read $ words ss\n print $ taxiSplit groups\n return ()\n\ntaxiSplit :: [Int] -> Int\ntaxiSplit = countCabs . (foldl' (groupSize) (0,0,0,0))\n where groupSize (a,b,c,d) x = case x of\n 1 -> (a + 1, b, c, d)\n 2 -> (a, b + 1, c, d)\n 3 -> (a, b, c + 1, d)\n 4 -> (a, b, c, d + 1)\n\ncountCabs :: (Int, Int, Int, Int) -> Int\ncountCabs (0, 0, 0, 0) = 0\ncountCabs (a, 0, 0, 0) = (a `quot` 4) + (if a `rem` 4 > 0 then 1 else 0)\ncountCabs (0, b, c, 0) = let b' = quot b 2 in\n b' + c + (if odd b then 1 else 0)\ncountCabs (a, b, 0, 0) = let b' = quot b 2 in\n b' + (if even b then countCabs (a,0,0,0)\n else if a < 3 then 1\n else 1 + countCabs (a - 2, 0, 0, 0))\ncountCabs (a, b, c, 0) = let x = min a c in\n x + countCabs (a - x,b,c - x,0)\ncountCabs (a, b, c, d) = d + countCabs (a,b,c,0)\n\n"}, {"source_code": "module Main (main) where\n\nimport System.Environment\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\ngetIntArray :: IO[Int]\ngetIntArray = fmap (map read.words) getLine\n\nmain = interact$show.s.map read.words\n\ns :: [Int] -> Int\ns (x:xs) = t n1 n2 n3 n4\n where n1 = length $ filter (== 1) xs\n n2 = length $ filter (== 2) xs\n n3 = length $ filter (== 3) xs\n n4 = length $ filter (== 4) xs\n\nupper :: Int -> Int -> Int\nupper a b = ((a - 1) `div` b) + 1\n\nt :: Int -> Int -> Int -> Int -> Int\nt 0 0 0 0 = 0\nt n1 n2 n3 n4 \n | min13 > 0 = min13 + t (n1-min13) n2 (n3-min13) n4\n | n2pair > 0 = n2pair + t n1 (n2-n2pair*2) n3 n4\n | min12 > 0 = t (n1-min12) (n2-min12) (n3+min12) n4\n | n4 > 0 = n4 + t n1 n2 n3 0\n | n3 > 0 = n3 + t n1 n2 0 n4\n | n2 > 0 = (upper n2 2) + t n1 0 n3 n4\n | n1 > 0 = (upper n1 4) + t 0 n2 n3 n4\n | otherwise = 0\n where min13 = min n1 n3\n min12 = min n1 n2\n n2pair = n2 `div` 2\n\n"}, {"source_code": "count_occurence xs n = length (filter (== n) xs)\n\none_rem :: (Integral a) => a -> a -> a -> a\none_rem a b c = if n < 0 \n then 0 \n else ceiling (fromIntegral n / 4)\n where n = a - (mod b 2) * 2 - c\n\nmain = do s <- getLine\n s <- getLine\n let ns = map (\\x -> read x :: Int) (words s)\n [o1,o2,o3,o4] = map (count_occurence ns) [1..4]\n n = (one_rem o1 o2 o3) + ceiling (fromIntegral o2 / 2) + o3 + o4\n print n\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nt :: Int -> (Sum Int,Sum Int,Sum Int,Sum Int)\nt 1 = (Sum 1,Sum 0,Sum 0,Sum 0)\nt 2 = (Sum 0,Sum 1,Sum 0,Sum 0)\nt 3 = (Sum 0,Sum 0,Sum 1,Sum 0)\nt 4 = (Sum 0,Sum 0,Sum 0,Sum 1)\n\nq4 x = (x + 3) `quot` 4\n\nsolve a1 a2 0 = q4 $ a1 + 2*a2\nsolve 0 a2 a3 = a3 + q4 (2*a2)\nsolve a1 a2 a3 = m + solve (a1-m) a2 (a3-m)\n\twhere m = min a1 a3\n\nmain :: IO ()\nmain = do\n\tvoid getLine\n\t(Sum a1, Sum a2, Sum a3, Sum a4) <- fold . map t <$> inputInts\n\tprint $ a4 + solve a1 a2 a3\n"}, {"source_code": "read_int :: String -> Int\nread_int = read\n\nkill_threes :: ((Int, Int, Int, Int), Int) -> ((Int, Int, Int, Int), Int)\nkill_threes ((a, b, c, d), s) = ((a-m, b, c-m, d), s+m)\n where m = min a c\n\nkill_twos :: ((Int, Int, Int, Int), Int) -> ((Int, Int, Int, Int), Int)\nkill_twos ((a, b, c, d), s) = ((a-2*m1, 0, c, d), s+m1+m2)\n where m1 = min b ((a+1) `quot` 2)\n m2 = (b-m1+1) `quot` 2\n\nkill_ones :: ((Int, Int, Int, Int), Int) -> ((Int, Int, Int, Int), Int)\nkill_ones ((a, b, c, d), s) = ((0, b, c, d), s+m)\n where m = (a+3) `quot` 4\n\nsum_tup :: ((Int, Int, Int, Int), Int) -> Int\nsum_tup ((a, b, c, d), s) = a+b+c+d+s\n\nsolve :: (Int, Int, Int, Int) -> Int\nsolve t = sum_tup . kill_ones . kill_twos . kill_threes $ (t,0)\n\nadd_tup :: (Int, Int, Int, Int) -> Int -> (Int, Int, Int, Int)\nadd_tup (a,b,c,d) 1 = (a+1,b,c,d)\nadd_tup (a,b,c,d) 2 = (a,b+1,c,d)\nadd_tup (a,b,c,d) 3 = (a,b,c+1,d)\nadd_tup (a,b,c,d) 4 = (a,b,c,d+1)\n\nget_tup :: String -> (Int, Int, Int, Int)\nget_tup str = foldl add_tup (0,0,0,0) $ map read_int $ words str\n\nmain = do\n getLine\n nums <- getLine\n print $ solve . get_tup $ nums\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\nmain= do\n\tgetLine\n\ts<- map read. words <$> getLine:: IO [Int]\n\tlet t = accumArray (+) 0 (1,4) $ zip s (repeat 1)\n\tlet u = t!4+ (div (t!2) 2) + t!3 \n let a1= (mod (t!2) 2)\n\tlet a2 = (max 0 (t!1-t!3-a1*2))\n\tlet v = u+a1+div a2 4 + if ( mod a2 4 >0) then 1 else 0\n\tprint v\n\t \n"}, {"source_code": "{-\nB. Taxi\n=======\ntime limit per test 3 seconds\nmemory limit per test 256 megabytes\ninput standard input\noutput standard output\n\nAfter the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1\u2009\u2264\u2009si\u2009\u2264\u20094), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?\n\nInput\n------\nThe first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910^ 5) \u2014 the number of groups of schoolchildren. The second line contains a sequence of integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u20094). The integers are separated by a space, si is the number of children in the i-th group.\n\nOutput\n-------\nPrint the single number \u2014 the minimum number of taxis necessary to drive all children to Polycarpus.\n\nSample test(s)\n--------------\ninput\n```\n5\n1 2 4 3 3\n```\noutput\n```\n4\n```\ninput\n```\n8\n2 3 4 4 2 1 3 1\n```\noutput\n```\n5\n```\nNote\nIn the first test we can sort the children into four cars like this:\n\n- the third group (consisting of four children),\n- the fourth group (consisting of three children),\n- the fifth group (consisting of three children),\n- the first and the second group (consisting of one and two children, correspondingly).\nThere are other ways to sort the groups into four cars.\n-}\n\nimport Data.List (sort, group)\n\ncount :: Int -> [Int] -> Int\ncount k xs = length $ filter (== k) xs\n\ntaxiNumber :: [Int] -> Int\ntaxiNumber xs = n4 + n3 + ceiling (fromIntegral n2 / 2) + adjust\n where [n1, n2, n3, n4] = map (`count` xs) [1,2,3,4]\n adjust = max 0 $ ceiling $ (fromIntegral (n1 - n3 - 2 * (n2 `mod` 2))) / 4 \n\nreader :: String -> [Int]\nreader s = map read $ words second\n where [_, second] = lines s\n\nmain = do\n input <- getContents\n let xs = reader input\n print $ taxiNumber xs\n"}, {"source_code": "module Main where\n\n\n--71A\n--replicateM n x = sequence (replicate n x)\n\n--processWord :: String -> String\n--processWord word | length word > 10 = (head word) : (show (length word - 2)) ++ ((last word):[])--(word !! ((length word) - 1))\n-- | otherwise = word\n\n--main = sequence [putStrLn $ show i | i <- [1..5]]\n--main = getLine >>= \\line -> replicateM (read line) (getLine) >>= \\list -> sequence [putStrLn (processWord (list!!i)) | i <- [0..(length list) - 1]]\n\n\n\n\n--118A\n--import Data.Char\n--isSylable :: Char -> Bool\n--isSylable char = elem char \"AOYEUIaoyeui\"\n--\n--deleteSylabls::[Char] -> [Char]\n--deleteSylabls [] = []\n--deleteSylabls (x:xs) | isSylable x = deleteSylabls xs\n-- | otherwise = x:(deleteSylabls xs)\n--\n--addDots :: [Char] -> [Char]\n--addDots [] = []\n--addDots (x:xs) = '.' : x : (addDots xs)\n--\n--processWord :: String -> String\n--processWord = addDots . deleteSylabls . (map toLower)\n--\n--main = getLine >>= putStrLn . processWord\n\n\n\n\n--50A\n\n--split :: Char -> String -> [String]\n--split _ [] = [\"\"]\n--split c (x:xs) | x == c = \"\" : rest\n-- | otherwise = (x : head rest): tail rest\n-- where rest = split c xs\n--\n--calc :: Int -> Int -> Int\n--calc m n = m*n `div` 2\n--\n--main = getLine >>= \\a -> let inp = (map read (split ' ' a)) in putStrLn $ show $ calc (inp !! 0) (inp !! 1)\n\n\n--231A\n\n--split :: Char -> String -> [String]\n--split _ [] = [\"\"]\n--split c (x:xs) | x == c = \"\" : rest\n-- | otherwise = (x : head rest): tail rest\n-- where rest = split c xs\n--\n--isGood :: [Int] -> Int\n--isGood (a:b:c:[]) = if (a+b+c >= 2) then 1 else 0\n--\n--toIntList :: [[String]] -> [[Int]]\n--toIntList strs = map (map read) strs\n--\n--main = getLine >>= \\line -> sequence (replicate (read line) getLine) >>= \\list -> putStrLn $ show $ sum $ map isGood (toIntList (map (split ' ') list))\n\n--B158\n\nsplit :: Char -> String -> [String]\nsplit _ [] = [\"\"]\nsplit c (x:xs) | x == c = \"\" : rest\n | otherwise = (x : head rest): tail rest\n where rest = split c xs\n\ncountEntries :: [Int] -> Int -> Int\ncountEntries [] _ = 0\ncountEntries (x:xs) val | x == val = 1 + rest\n | otherwise = rest\n where rest = (countEntries xs val)\n\nfindSol :: [Int] -> Int\nfindSol groups = let\n gr = countEntries groups\n fours = gr 4\n threes = gr 3\n twos = gr 2\n ones = gr 1\n threeToOne = min threes ones\n twosToTwos = twos `div` 2\n unpairThrees = threes - threeToOne\n unpairOnes = ones - threeToOne + ((twos `mod` 2)*2)\n in\n fours + threeToOne + twosToTwos + ((unpairOnes `div` 4) + (if unpairOnes `mod` 4 /= 0 then 1 else 0)) + unpairThrees\n\n\n\nmain = getLine >> getLine >>= \\a -> let groups = (map read (split ' ' a) :: [Int]) in putStrLn $ show $ findSol groups"}, {"source_code": "main = do\n getLine\n t <- getLine\n let t2 = map read $ words t\n let p1 = length $ filter (== 1) t2\n let p2 = length $ filter (== 2) t2\n let p3 = length $ filter (== 3) t2\n let p4 = length $ filter (== 4) t2\n print $ cal p1 p2 p3 p4\ncal :: Int -> Int -> Int -> Int -> Int\ncal w x y z = max (z + y + (quot (x+1) 2)) (quot (w+2*x+3*y+4*z+3) 4)"}, {"source_code": "main = do\n groups <- getLine >> getLine >>= return . (map read) . words\n let [a1, a2, a3, a4] = map countGroups [1..4]\n where countGroups i = length $ filter (== i) groups\n let extra = if a3 > a1\n then mod a2 2\n else ceiling (fromIntegral (a1 - a3 + (mod a2 2) * 2) / 4)\n print (extra + a3 + div a2 2 + a4)"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nf :: Int -> Int -> Int -> Int -> Int\nf 0 0 0 0 = 0\nf a1 a2 a3 a4\n | a4 > 0 = a4 + f a1 a2 a3 0\n | a1 > 0 && a3 > 0 =\n \tlet\n\t\tmn = min a1 a3\n\tin\n\t\tmn + f (a1 - mn) a2 (a3 - mn) a4 \n | a3 > 0 = a3 + f a1 a2 0 a4\n | a2 > 1 = (a2 `div` 2) + f a1 (a2 `mod` 2) a3 a4\n | a2 == 1 && a1 >= 2 = 1 + f (a1 - 2) 0 a3 a4\n | a2 <= 1 && a1 <= 2 = 1\n | a1 > 0 = a1 `div` 4 + (if a1 `mod` 4 > 0 then 1 else 0)\n | otherwise = error \"hi, how are you!!!\"\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tlet\n\t\tarr = map (\\x -> read x :: Int) . words $ line\n\t\ta1 = length . filter (== 1) $ arr\n\t\ta2 = length . filter (== 2) $ arr\n\t\ta3 = length . filter (== 3) $ arr\n\t\ta4 = length . filter (== 4) $ arr\n\tprint $ f a1 a2 a3 a4\n\n"}, {"source_code": "import List\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy _ [] = []\nsplitBy f list = first : splitBy f (dropWhile f rest) \n\twhere\n \t\t(first, rest) = break f list\n\ntoIList :: String -> [Int]\ntoIList str = (map read splitted) :: [Int]\n\twhere\n\t\tsplitted = splitBy (== ' ') str\n\nminimumTaxis :: [Int] -> Int\nminimumTaxis ppls = c4 + c3 + res2 + res1\n\twhere\n\t\tcount = map length $ group $ sort (ppls ++ [1, 2, 3, 4])\n\t\tc4 = count !! 3 - 1\n\t\tc3 = count !! 2 - 1\n\t\tc2 = count !! 1 - 1\n\t\tc1 = count !! 0 - 1\n\t\tleft1 = if c1 - c3 > 0 then c1 - c3 else 0\n\t\tfull2 = floor $ (fromIntegral c2)/2\n\t\tleft2 = c2 `mod` 2\n\t\tres2 = full2 + left2\n\t\tres1 = if left1 - left2*2 > 0 then ceiling $ (fromIntegral (left1 - left2*2))/4 else 0\n\n\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet result = minimumTaxis $ toIList line2\n\n\tputStr $ show result"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\n\ntype Map = [(Int, Int)]\n\nset :: Int -> Int -> Map -> Map\nset i n = map (\\ (a, b) -> if a == i\n then (a, n)\n else (a, b)\n )\n\nsubstract :: Int -> Int -> Map -> Map\nsubstract i n = map (\\ (a, b) -> if a == i\n then (a, b - n)\n else (a, b)\n )\n\nremove :: Int -> Map -> Map\nremove i = map (\\ (a, b) -> if a == i\n then (a, 0)\n else (a, b)\n )\n\nvalueAt :: Int -> Map -> Int\nvalueAt _ [] = 0\nvalueAt i ((a, b):xs) = if a == i\n then b\n else valueAt i xs\n\nf :: Map -> Int\nf [] = 0\nf (m:ms) = case m of\n (4, x) -> x + f ms\n (3, x) -> x + (f $ substract 1 k ms)\n where\n k = min x x1\n x1 = valueAt 1 ms\n (2, x) -> n + (f $ substract 1 k ms)\n where\n k = l * min 2 x1\n l = mod x 2\n x1 = valueAt 1 ms\n n = div x 2 + l\n (1, x) -> ceiling ((fromIntegral x) / 4)\n\nfrequency :: [Int] -> Map\nfrequency = map (head &&& length) . group . sort\n\nmain :: IO ()\nmain = do\n getLine\n xs <- (map read . words) `fmap` getLine :: IO [Int]\n putStrLn . show . f . reverse . frequency $ xs\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = getLine >> getLine >>= putStrLn.show.solve.reverse.sort.map read.words\n\nsolve :: [Int] -> Int\nsolve a = s [0, 0, 0] a\n\ns [o, 0, 0] []\n | o == 0 = 0\n | o < 4 = 1\n | otherwise = (o `div` 4) + s [o `mod` 4, 0, 0] []\ns [o, 1, 0] []\n | o < 3 = 1\n | otherwise = succ $ s [o - 2, 0, 0] []\ns [o, t, 0] [] = (t `div` 2) + s [o, t `mod` 2, 0] []\ns [0, t, h] [] = h + s [0, t, 0] []\ns [o, t, h] [] = succ $ s [pred o, t, pred h] []\ns [3, t, 0] (1:x) = succ $ s [0, t, 0] x\ns [o, t, 0] (1:x) = s [succ o, t, 0] x\ns [o, t, h] (1:x) = succ $ s [o, t, pred h] x\ns [o, 0, h] (2:x) = s [o, 1, h] x\ns [o, 1, h] (2:x) = succ $ s [o, 0, h] x\ns [0, t, h] (3:x) = s [0, t, succ h] x\ns [o, t, h] (3:x) = succ $ s [pred o, t, h] x\ns a (4:x) = succ $ s a x\n"}, {"source_code": "import Data.Sequence\nimport Data.Foldable\n\ngetGroups :: IO [Integer]\ngetGroups = do\n _groups <- getLine\n return $ map read (words _groups)\n\ngetAnswer :: [Integer] -> Integer\ngetAnswer groups = quantify $ count groups\n\ncount :: [Integer] -> [Integer]\ncount groups = _count groups [0, 0, 0, 0]\n\n_count :: [Integer] -> [Integer] -> [Integer]\n_count [] counter = counter\n_count (first:rest) counter = _count rest $ toList $ update position ((counter !! position) + 1) $ fromList counter\n where position = fromIntegral first - 1\n\nquantify :: [Integer] -> Integer\nquantify counter = getQuarters + getTriplesAndOnes + getDoubles + getRest\n where ones = head counter\n twos = head $ tail counter\n threes = head $ tail $ tail counter\n fours = last counter\n getQuarters = fours\n getTriplesAndOnes = threes\n onesWithoutThrees = if ones > threes\n then ones - threes\n else 0\n (getDoubles, onesRest) = quantifyDoubles twos onesWithoutThrees\n getRest = onesRest `div` 4 + if onesRest `mod` 4 > 0\n then 1\n else 0\n\nquantifyDoubles :: Integer -> Integer -> (Integer, Integer)\nquantifyDoubles 0 ones = (0, ones)\nquantifyDoubles twos ones = (countedTwos, onesRest)\n where countedTwos = twos `div` 2 + twos `mod` 2\n onesRest = if twos `mod` 2 == 1\n then if ones >= 2\n then ones - 2\n else 0\n else ones\n\nmain :: IO ()\nmain = do\n n <- getLine\n groups <- getGroups\n print $ getAnswer groups"}, {"source_code": "import Data.List (sort)\n\npack [] _ _ = 0\npack (x:xs) oc2 oc1\n | x == 4 = 1 + pack xs oc2 oc1\n | x == 3 = 1 + pack xs oc2 (oc1+1)\n | x == 2 = if oc2 > 0 then pack xs (oc2-1) oc1 else 1 + pack xs (oc2+1) oc1\n | x == 1 = let free = 2*oc2 + oc1 in if free > 0 then pack xs 0 (free - 1) else 1 + pack xs 0 (free+3)\n\nmain = do\n getLine\n aa <- getLine\n let xs = reverse $ sort $ map read $ words aa :: [Int]\n print $ pack xs 0 0\n"}, {"source_code": "fill :: [Int] -> (Int, [Int]) -> (Int, [Int])\nfill cs (n, xs) = (n + n', xs')\n where\n n' = minimum $ zipWith (\\x c -> if c == 0 then maxBound else x `div` c) xs cs\n xs' = zipWith (\\x c -> x - n' * c) xs cs\n\nprocess :: [Int] -> Int\nprocess ss = fst $ foldr fill (0, xs) [\n [1,0,0,0],\n [2,0,0,0],\n [0,1,0,0],\n [3,0,0,0],\n [1,1,0,0],\n [0,0,1,0],\n [4,0,0,0],\n [2,1,0,0],\n [0,2,0,0],\n [1,0,1,0],\n [0,0,0,1]]\n where\n xs = [length (filter (==x) ss) | x <- [1..4]]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n03 + n12 + n02 + n01\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n12 = min n1''' n2''\n n1'''' = n1''' - n12\n n2''' = n2'' - n12\n n01 = if n1'''' > 0 then 1 else 0\n n02 = n2'''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.Array\n\nmain = interact $ show . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:xs) = fst . greedy1 . greedy2 . greedy3 . greedy4 . (,) 0 . count $ xs\n\nfoldl' f z [] = z\nfoldl' f z (x:xs) = let z' = f z x\n in seq z' $ foldl' f z' xs\n\ncount :: [Int] -> Array Int Int\ncount = foldl' f (array (1, 4) (zip [1..4] (repeat 0)))\n where f arr i = arr//[(i, arr!i + 1)]\n\ngreedy4 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy4 (ans, arr) = (ans + arr!4, arr)\n\ngreedy3 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy3 (ans, arr) = (ans + arr!3, arr//[(1, max 0 (arr!1 - arr!3))])\n\ngreedy2 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy2 (ans, arr) = (ans + x, arr//[(1, new1)])\n where (x, new1) = if mod (arr!2) 2 == 1 then (arr!2 `div` 2 + 1, max 0 (arr!1 - 2)) else (arr!2 `div` 2, arr!1)\n\ngreedy1 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy1 (ans, arr) = (ans + ceil (arr!1) 4, arr)\n\n\nceil :: Int -> Int -> Int\nceil a b = if (a `mod` b == 0) then ans else ans + 1\n where ans = a `div` b\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nunder2 a 0 = (a+3)`div`4\nunder2 0 b = (b+1)`div`2\nunder2 a b\n | a==1&&b==1 = 1\n | a==1 = 1+under2 0 (b-1)\n | otherwise = 1+under2 (a-2) (b-1)\nunder3 a b 0 = under2 a b \nunder3 0 b c = c+under2 0 b\nunder3 a b c = 1+under3 (a-1) b (c-1) \n\nans input = d + under3 a b c\n where (i,i1)=span (==1) input\n (j,i2)=span(==2) i1\n (k,i3)=span(==3) i2\n [a,b,c,d]=[length i,length j,length k,length i3]\n\nmain=do\n n<-getLine\n input<-getLine\n let inputed=sort $ map (\\x->read x::Int) $ words input\n print $ ans inputed "}, {"source_code": "{-\nimport Data.Array\n\nmain = interact $ show . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:xs) = fst . greedy1 . greedy2 . greedy3 . greedy4 . (,) 0 . count $ xs\n\nfoldl' f z [] = z\nfoldl' f z (x:xs) = let z' = f z x\n in seq z' $ foldl' f z' xs\n\ncount :: [Int] -> Array Int Int\ncount = foldl' f (array (1, 4) (zip [1..4] (repeat 0)))\n where f arr i = arr//[(i, arr!i + 1)]\n\ngreedy4 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy4 (ans, arr) = (ans + arr!4, arr)\n\ngreedy3 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy3 (ans, arr) = (ans + arr!3, arr//[(1, max 0 (arr!1 - arr!3))])\n\ngreedy2 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy2 (ans, arr) = (ans + x, arr//[(1, new1)])\n where (x, new1) = if mod (arr!2) 2 == 1 then (arr!2 `div` 2 + 1, max 0 (arr!1 - 2)) else (arr!2 `div` 2, arr!1)\n\ngreedy1 :: (Int, Array Int Int) -> (Int, Array Int Int)\ngreedy1 (ans, arr) = (ans + ceil (arr!1) 4, arr)\n\n\nceil :: Int -> Int -> Int\nceil a b = if (a `mod` b == 0) then ans else ans + 1\n where ans = a `div` b\n\nmain = do\n n:ss <- (`fmap` getContents) $ words >>> map (readInt >>> fromJust >>> fst)\n let n1:n2:n3:n4:_ = map ((==) >>> (`filter` ss) >>> length) [1..]\n print $ n4 + n3 + (n2*2 + 3 + max 0 (n1-n3)) `div` 4\n\n-}\n\nmain = do\n content <- getContents\n let n:ss = map read . words $ content\n n1:n2:n3:n4:_ = map (length . (\\n -> filter (== n) ss)) [1..]\n print $ n4 + n3 + (n2*2 + 3 + max 0 (n1-n3)) `div` 4\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] = f + h + q + a + r + rest\n where (q,r) = divMod t 2\n rest1 = o - h - 2*r\n (a,b) = if rest1 > 0 then divMod rest1 4 else (0,0)\n rest = if b > 0 then 1 else 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "increaseNth :: [Int] -> Int -> [Int]\nincreaseNth xs n = take n xs ++ [((xs !! n) + 1)] ++ drop (n + 1) xs\n\ncountArrAss :: [Int] -> [Int] -> [Int]\ncountArrAss [] after = after\ncountArrAss (x:pre) after = countArrAss pre (increaseNth after (x - 1))\n\ncountArr :: [Int] -> [Int]\ncountArr da = countArrAss da [0, 0, 0, 0]\n\npreProcess :: [Char] -> [Int]\npreProcess s = countArr $ map read (words s)\n\nsol :: [Int] -> Int\nsol xs = prefix4th + prefix3th + prefix2th + prefix1th\n where prefix4th = (xs !! 3)\n prefix3th = (xs !! 2)\n prefix1sub3 = (xs !! 0) - (xs !! 2)\n prefix2remain = mod (xs !! 1) 2\n prefix2th = plu + (div (xs !! 1) 2)\n where plu = if prefix2remain > 0 then 1 else 0\n prefix1sub3sub2 = prefix1sub3 - 2 * prefix2remain\n prefix1th = if prefix1sub3sub2 > 0\n then ceiling ((fromIntegral prefix1sub3sub2) / 4)\n else 0\n\nmain = do\n n <- getLine\n groups <- getLine\n putStrLn $ show (sol (preProcess groups))\n"}, {"source_code": "import System.IO\nimport Control.Applicative\n\nmain :: IO ()\nmain = print =<< minSolve . solve . map read . words <$> (getLine >> getLine)\n\nsolve :: [Integer] -> (Integer, Integer, Integer, Integer)\nsolve = foldl f (0,0,0,0) where\n f (a,b,c,d) 4 = (a+1,b,c,d)\n f (a,b,c,d) 3 = (a,b+1,c,d)\n f (a,b,c,d) 2 = (a,b,c+1,d)\n f (a,b,c,d) 1 = (a,b,c,d+1)\n\nminSolve :: (Integral a) => (a, a, a, a) -> a\nminSolve (0, 0, 0, r) = r `div` 4 + if r `mod` 4 == 0 then 0 else 1\nminSolve (0, 0, e, r) = e `div` 2 + if e `mod` 2 == 0 then minSolve (0,0,0,r) else 1 + minSolve(0,0,0,max (r-2) 0)\nminSolve (q, w, e, r) = q + w + minSolve (0, 0, e, max 0 (r-w))"}, {"source_code": "cars :: Int -> Int -> Int -> Int -> Int\ncars n1 0 0 0 = n1 `divUp` 4\ncars n1 n2 0 0 = n2 `divUp` 2 + cars newn1 0 0 0\n where newn1 = max (n1 - 2 * (n2 `rem` 2)) 0\ncars n1 n2 n3 0 = n3 + cars newn1 n2 0 0\n where newn1 = max (n1 - n3) 0\ncars n1 n2 n3 n4 = n4 + cars n1 n2 n3 0\n\ndivUp :: (Integral a) => a -> a -> a\ndivUp a b = (a + b - 1) `div` b\n\nwork :: String -> String\nwork input = show $ cars n1 n2 n3 n4\n where\n gangs = map read . words . last . lines $ input\n n1:n2:n3:n4:_ = [length . filter (==x) $ gangs | x <- [1..4]] \n\nmain :: IO ()\nmain = interact work\n\n\n \n"}, {"source_code": "count x = length . filter (x==)\n\ndivUp x y = div (x + y - 1) y\n\nsolve a\n = fours + threes + divUp ((max (ones - threes) 0) + twos * 2) 4\n where\n ones = count 1 a\n twos = count 2 a\n threes = count 3 a\n fours = count 4 a\n\nmain = print . solve . map read . words . last . lines =<< getContents\n"}, {"source_code": "main = do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let ss = take n $ map read $ words line :: [Int]\n putStrLn $ show $ solve ss\n\nsolve :: [Int] -> Int\nsolve ss = c4 + solve' c1 c2 c3\n where\n c1 = count (== 1) ss\n c2 = count (== 2) ss\n c3 = count (== 3) ss\n c4 = count (== 4) ss\n\ncount :: (a -> Bool) -> [a] -> Int\ncount p = length . filter p\n\nsolve' :: Int -> Int -> Int -> Int\nsolve' c1 0 0 = c1 `divUp` 4\nsolve' 0 c2 0 = c2 `divUp` 2\nsolve' 0 c2 c3 = c3 + solve' 0 c2 0\nsolve' c1 c2 0 | c1 >= 2 * c2 = c2 + solve' (c1 - 2 * c2) 0 0\n | otherwise = c1 `divUp` 2 + solve' 0 (c2 - c1 `divUp` 2) 0\nsolve' c1 c2 c3 | c1 >= c3 = c3 + solve' (c1 - c3) c2 0\n | otherwise = c1 + solve' 0 c2 (c3 - c1)\n\ndivUp a b = (a - 1) `div` b + 1\n"}, {"source_code": "g=getLine\nmain=do\n q<-g\n let n=read q\n q<-g\n let o=take n$map read$words q\n putStrLn$show$c(==4)o+r(c(==1)o)(c(==2)o)(c(==3)o)\nc p=length.filter p\nr a 0 0=s a 4\nr 0 b 0=s b 2\nr 0 b h=h+r 0 b 0\nr a b 0|a<2*b=s a 2+r 0(b-s a 2)0\n |True=b+r(a-2*b)0 0\nr a b h|a Int -> Int -> Int -> Int\nsolve one 0 0 0 = one `div` 4 + (if one `mod` 4 /= 0 then 1 else 0)\nsolve one two 0 0\n | two > 1 = (two `div` 2) + solve one (two `mod` 2) 0 0\n | otherwise = solve (one + 2 * two) 0 0 0\nsolve one two three 0 = three + solve (max 0 (one - three)) two 0 0\nsolve one two three four = four + solve one two three 0\n\n\n\nmain = do\n _ <- getLine >>= return . (read :: String -> Int)\n ppl <- getLine >>= (return . map (read::String->Int) . words)\n print $ ssolve ppl"}, {"source_code": "import Data.Char\nmain = do\n n <- getLine\n xs <- getLine\n let ys = [read x::Int | x <- words(xs)]\n print $ f $ [length $ filter (==i) ys | i <- [1..4]]\n \nf xs = a4 + a3 + div (a2 + 1) 2 + div (max 0 (a1 - a3 - 2 * mod a2 2 + 3)) 4\n where \n a4 = xs !! 3\n a3 = xs !! 2\n a2 = xs !! 1\n a1 = xs !! 0"}, {"source_code": "import Data.List (sortBy)\n\ntaxi :: [Int] -> Int\ntaxi = taxiGrouper 0 [] . sortBy (flip compare)\n\ntaxiGrouper :: Int -> [Int] -> [Int] -> Int\ntaxiGrouper groups fall@(f:fs) (p:ps)\n\t| f > p = taxiGrouper groups (insert (f-p) fs) ps\n\t| f == p = taxiGrouper groups fs ps\n\t| otherwise = taxiGrouper (groups + 1) (insert (4-p) fall) ps\ntaxiGrouper groups _ (p:ps) = taxiGrouper (groups + 1) (insert (4-p) []) ps\ntaxiGrouper groups _ _ = groups\n\ninsert :: Int -> [Int] -> [Int]\ninsert x (y:ys) = if x < y then y : (insert x ys) else x:y:ys\ninsert x _ = [x]\n\nmain = do\n\tgetLine\n\tgetLine >>= print . taxi . (map read) . words"}, {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain = do s <- hGetContents stdin\n print $ solve $ map read $ words s\n\ns :: (Show a) => String -> a -> a\n-- s m x = trace (m ++ \" = \" ++ (show x)) x\ns m x = x\n \nsolve :: [Int] -> Int\nsolve (n:xs) = fours + _31 + (threes - _31) + _22 + _21 + _11 + _11L\n where items = map (\\x -> (head x, length x)) $ group $ sort xs\n ones = fromMaybe 0 $ fmap snd $ find ((1==).fst) items\n twos = fromMaybe 0 $ fmap snd $ find ((2==).fst) items\n threes = fromMaybe 0 $ fmap snd $ find ((3==).fst) items\n fours = fromMaybe 0 $ fmap snd $ find ((4==).fst) items\n _31 = s \"_31\" $ min threes ones\n _22 = s \"_22\" $ div twos 2\n _21 = s \"_21\" $ if twos - _22*2 > 0 then 1 else 0\n onesAfterComplete = s \"onesAfterComplete\" $ if _21 > 0 then max (ones - _31 - 2) 0 else ones - _31\n _11 = s \"_11\" $ div onesAfterComplete 4\n _11L = s \"_11L\" $ if onesAfterComplete - _11*4 > 0 then 1 else 0"}, {"source_code": "import Data.Char\n\nmain = do\n\tline <- getLine\n\tgroupLine <- getLine\n\tlet groups = map ((+ 0) . read) $ words groupLine\n\tputStrLn $ show $ answer groups\n\nanswer :: [Integer] -> Int\nanswer a = \n\tlet fours = length $ filter (\\x -> x == 4) a;\n\t\tthrees = length $ filter (\\x -> x == 3) a;\n\t\ttwos = length $ filter (\\x -> x == 2) a;\n\t\tones = length $ filter (\\x -> x == 1) a;\n\t\tthreeOne = min ones threes;\n\t\ttwoPairs = twos `quot` 2;\n\t\tsingleThrees = threes - threeOne;\n\t\tonesLeft = ones - threeOne;\n\t\tonePairs = quot onesLeft 2;\n\t\ttwosLeft = twos - (twoPairs * 2);\n\t\toneTwoPair = min twosLeft onePairs;\n\t\tsingleTwo = twosLeft - (quot (oneTwoPair + 1) 2);\n\t\tonlyOneGroups = quot (3 + onesLeft - singleTwo - (oneTwoPair * 2)) 4\n\tin fours + threeOne + twoPairs + singleThrees + oneTwoPair + singleTwo + onlyOneGroups"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map read . words . (!! 1) . lines)\n\nsolve :: [Int] -> Int\nsolve groups = sum [four, threePlusOne, twoPlusTwo, three', twoPlusOnes, outsiders] where\n outsiders = (one'' + 3) `div` 4\n one'' = if two' == 1 then max 0 (one' - 2) else one'\n twoPlusOnes = if two' == 1 then 1 else 0\n (one', two', three') = (one - threePlusOne, two `mod` 2, three - threePlusOne)\n twoPlusTwo = two `div` 2\n threePlusOne = min three one\n [one, two, three, four] = [length (filter (== x) groups) | x <- [1..4]]\n"}, {"source_code": "import Data.Array.IArray\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- getLine\n a <- readItems\n let b = accumArray (+) 0 (1, 4) [(i, 1) | i <- a]\n let [b1, b2, b3, b4] = elems (b :: Array Int Int)\n let answer1 = b4 + b3 + div (b2 + 1) 2\n let answer2 = div (3 + max 0 (b1 - (b3 + (mod b2 2) * 2))) 4\n putStrLn $ show $ answer1 + answer2\n"}, {"source_code": "import Data.List\nimport Data.Function\n\ncounts :: [Int] -> [(Int, Int)]\ncounts [] = []\ncounts l = (x, length c) : counts r\n where\n x = head l\n (c, r) = partition (== x) l\n\nmain = do\n ns <- getLine\n ss <- getLine\n let s = map (read :: String -> Int) . words $ ss\n let [ones, twos, threes, fours] = map (\\x -> length . filter (== x) $ s) [1..4]\n print (fours + threes + (twos * 2 + 3 + max 0 (ones - threes)) `div` 4)\n"}, {"source_code": "main = do\n getLine\n s <- fmap (map read . words) getLine\n let a = map (\\x -> length $ filter (==x) s) [0..4]\n print $ (a !! 4) + (a !! 3) + (a !! 2) `div` 2 + (a !! 2) `mod` 2 + (max 0 ((a !! 1) - (a !! 3) - 2 * ((a !! 2) `mod` 2) + 3) `div` 4)\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n getLine\n as <- fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n \n let\n cs = accumArray (+) 0 (1, 4) $ zip as (repeat 1)\n c13 = min (cs!1) (cs!3)\n c3 = max (cs!3 - c13) 0 \n c1 = max (cs!1 - c13) 0\n x = c1 `mod` 4 + (if even (cs!2) then 0 else 2)\n\n print $ cs!4 + c13 + c3 + (c1 `div` 4) + (cs!2 `div` 2) + ((x + 3) `div` 4)"}, {"source_code": "main :: IO ()\nmain = do\n n <- fmap read getLine :: IO Integer\n si <- fmap (map read . words) getLine :: IO [Int]\n print $ fillCars $ groups $ si\n\nfillCars :: [Int] -> Int\nfillCars g = g4 + \n min g3 g1 +\n max (g3 - (min g3 g1)) 0 +\n div g2 2 + (mod g2 2) +\n div g1' 4 + if (mod g1' 4) > 0 then 1 else 0\n where \n g1 = g !! 0\n g2 = g !! 1\n g3 = g !! 2\n g4 = g !! 3\n g1' = max (g1 - (min g3 g1) - ((mod g2 2) * 2)) 0\n\n\ngroups :: [Int] -> [Int]\ngroups [] = [0,0,0,0]\ngroups (x:xs) = [b 1, b 2, b 3, b 4]\n where b = \\i -> groups xs !! (i-1) + (if x == i then 1 else 0)\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = interact $ show . solve . map (read) . words\n\nsolve :: [Int] -> Int\nsolve (n : xs) = \n d + cal a b c\n where\n (a : b : c : d:_) = map ((subtract 1) . length) . group . sort $ (1:2:3:4:xs)\n\ncal :: Int -> Int -> Int -> Int\ncal a b c\n | c > 0 = \n let \n k = min a c\n in\n c + cal (a - k) b 0\n | b > 0 = \n let\n k = min b (div a 2)\n in\n if k == b then k + cal (a - 2 * k) 0 0\n else k + (ceilDiv (b - k) 2) + cal (a - 2 * k - (mod (b - k) 2)) 0 0\n | a > 0 = (ceilDiv a 4)\n | otherwise = 0\n\nceilDiv a b = div (a + b - 1) b\n"}, {"source_code": "import IO\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nreadMany :: Read a => IO [a]\nreadMany = fmap (map read . words) getLine\n\nsign :: Int -> Int\nsign num \n | num < 0 = -1\n | num == 0 = 0\n | num > 0 = 1\n\ndivUp :: Int -> Int -> Int\ndivUp x y = res\n where div_value = x `div` y\n mod_value = x `mod` y\n res = div_value + sign mod_value\n\ncount :: (Int -> Bool) -> [Int] -> Int\ncount pred = length . filter pred\n\ncountCars :: [Int] -> Int\n\ncountCars [a, b, c, d] = d + countCars [a, b, c]\ncountCars [a, b, c] = c + countCars [newA, b]\n where newA = max 0 (a - c)\ncountCars [a, b] = resB + countCars [newA]\n where newA = max 0 (a - 2 * (b `mod` 2))\n resB = divUp b 2\ncountCars [a] = divUp a 4\n\nrun :: [Int] -> Int\nrun numbers = countCars [count (==x) numbers | x <- [1..4]]\n\nmain = do\n getLine\n numbers <- readMany :: IO [Int]\n putStrLn $ show $ run numbers\n"}, {"source_code": "import List\nc n = length . filter (==n)\nf l = let \n c1 = c 1 l;\n c3 = c 3 l;\n c2 = c 2 l\n in c 4 l + div c2 2 + c3 +\n if c3>=c1\n then rem c2 2 \n else ((c1-c3+(2*rem c2 2)-1) `div` 4)+1\nmain = do\n n <- readLn :: IO Int\n res <- fmap (f . map read . words) getLine\n putStr (show res)\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n _ <- getLine\n s <- (map read . words) <$> getLine\n print $ solve s\n\nsolve xs = (cnt 4) + (cnt 3) + div (3 + maximum [(cnt 1)-(cnt 3), 0] + 2 * (cnt 2)) 4\n where cnt a = length $ filter (== a) xs\n\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n _ <- getLine\n s <- (map read . words) <$> getLine\n print $ solve s\n\n--solve xs = (cnt 4) + (cnt 3) + div (3 + maximum [(cnt 1)-(cnt 3), 0] + 2 * (cnt 2)) 4\n-- where cnt a = length $ filter (== a) xs\n\nsolve xs = (cnt!!3) + (cnt!!2) + div (3 + maximum [(cnt!!0)-(cnt!!2), 0] + 2 * (cnt!!1)) 4\n where cnt = [length $ filter (== a) xs | a <- [1..4]]\n\n"}, {"source_code": "f [a, b, c, d] = d + c + (b * 2 + 3 + max 0 (a-c)) `div` 4\n\nmain = do\n _ <- getLine\n groups <- fmap (map read . words) getLine\n print $ f $ map (\\x -> length $ filter (==x) groups) [1..4]\n"}, {"source_code": "g l h = take (h - 1) l ++ [l!!(h - 1) + 1] ++ drop h l\n\nf :: Int -> [Int] -> Int\nf s [a, b] = s + ceiling ((fromIntegral b * 2 + fromIntegral a) / 4)\nf s [a, b, c]\n | c >= a = f (s + c) [0, b]\n | otherwise = f (s + c) [a - c, b]\nf s [a, b, c, d] = f (s + d) [a, b, c]\n\nmain = do\n _ <- getLine\n groups <- getLine\n print $ f 0 $ foldl g [0, 0, 0, 0] $ map (read::String -> Int) $ words groups\n"}, {"source_code": "g (a, b, c, d) 1 = (a + 1, b, c, d)\ng (a, b, c, d) 2 = (a, b + 1, c, d)\ng (a, b, c, d) 3 = (a, b, c + 1, d)\ng (a, b, c, d) 4 = (a, b, c, d + 1)\n\nf (a, b, c, d) = d + c + ceiling ((fromIntegral b * 2 + fromIntegral x) / 4)\n where x = if c < a then a - c else 0\n\nmain = do\n _ <- getLine\n groups <- getLine\n print $ f $ foldl g (0, 0, 0, 0) $ map (read::String -> Int) $ words groups\n"}, {"source_code": "g l h = take (h - 1) l ++ [l!!(h - 1) + 1] ++ drop h l\n\nf [a, b, c, d] = d + c + ceiling ((fromIntegral b * 2 + fromIntegral x) / 4)\n where x = if c < a then a - c else 0\n\nmain = do\n _ <- getLine\n groups <- getLine\n print $ f $ foldl g [0, 0, 0, 0] $ map (read::String -> Int) $ words groups\n"}, {"source_code": "g l h = take (h - 1) l ++ [l!!(h - 1) + 1] ++ drop h l\n\nf :: Int -> [Int] -> Int\nf s [a, b] = s + ceiling ((fromIntegral(b) * 2 + fromIntegral(a)) / 4)\nf s [a, b, c]\n | c >= a = f (s + c) [0, b]\n | otherwise = f (s + c) [a - c, b]\nf s [a, b, c, d] = f (s + d) [a, b, c]\n\nmain = do\n _ <- getLine\n groups <- getLine\n print $ f 0 $ foldl g [0, 0, 0, 0] $ map (read::String -> Int) $ words groups\n"}, {"source_code": "g (a, b, c, d) h = case h of\n 4 -> (a, b, c, d + 1)\n 3 -> (a, b, c + 1, d)\n 2 -> (a, b + 1, c, d)\n 1 -> (a + 1, b, c, d)\n\nf l = foldl g (0, 0, 0, 0) l\n\nr :: Int -> (Int, Int, Int, Int) -> Int\nr s (a, b, 0, 0) = s + ceiling ((fromIntegral(b) * 2 + fromIntegral(a)) / 4)\nr s (a, b, c, 0)\n | c >= a = r (s + c) (0, b, 0, 0)\n | otherwise = r (s + c) (a - c, b, 0, 0)\nr s (a, b, c, d) = r (s + d) (a, b, c, 0)\n\nmain = do\n _ <- getLine\n groups <- getLine\n\n print $ r 0 (f $ map (read :: String -> Int) $ words groups)\n"}, {"source_code": "main = readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve2.solve.words. last. take 2.lines\nsolve xs = splitAt 2 $ map (\\ x -> foldr (\\ a b -> case () of _ |(read a)==x -> 1+b |otherwise -> b ) 0 xs ) [1..4]\nsolve2::([Int],[Int])->Int\nsolve2 ([a,b],[c,d])= (ceiling $ (fromIntegral ((minus0 a c)+2*b)) / 4 )+ c+d\nminus0 x y | x-y >=0 = x-y |otherwise = 0 "}, {"source_code": "import Data.List (sort)\n-- 158B\n-- this code kind of sucks\n\ntaxi :: [Int] -> Int\ntaxi ns = solve $ collect ns\n\nsolve :: (Int,Int,Int,Int) -> Int\nsolve (a,b,c,d) \n\t| d > 0 = \td + solve(a,b,c,0)\n\t| c > 0 = \tif (a >= 1)\n\t\t\t\tthen 1 + solve (a-1,b,c-1,d)\n\t\t\t\telse 1 + solve (a,b,c-1,d)\n\t| b > 0 = \tif (b >= 2)\n\t\t\t\tthen 1 + solve (a,b-2,c,d)\n\t\t\t\telse \n\t\t\t\t\tcase a of\n\t\t\t\t\t\t1 -> 1 + solve (a-1,b-1,c,d)\n\t\t\t\t\t\t0 -> 1 + solve (a,b-1,c,d)\n\t\t\t\t\t\ta -> 1 + solve (a-2,b-1,c,d)\t\t\t\n\t| a > 0\t= ceiling ( (fromIntegral a) / 4 )\n\t| otherwise = 0\n\t\ncollect :: [Int] -> (Int,Int,Int,Int)\ncollect ns = foldl accumulate (0,0,0,0) ns\n\naccumulate :: (Int,Int,Int,Int) -> Int -> (Int,Int,Int,Int)\naccumulate (a,b,c,d) n\n\t\t| n == 1 = (a+1,b,c,d)\n\t\t| n == 2 = (a,b+1,c,d)\n\t\t| n == 3 = (a,b,c+1,d)\n\t\t| n == 4 = (a,b,c,d+1)\n\nreadIn :: IO [Int]\nreadIn = do\n contents <- getContents\n let n:is = lines contents\n x = read $ head $ words n \n xs = take x (map read (words $ head is))\n return xs\n\nmain :: IO()\nmain = do\n i <- readIn\n putStr $ show $ taxi i\n"}], "negative_code": [{"source_code": "main = interact $ show . solve . map read . words\nsolve (_ : k : xs) = length . takeWhile (>= xs !! (k - 1)) . filter (> 0) $ xs\n"}, {"source_code": "import Data.Char\n\nmain = do\n\tline <- getLine\n\tgroupLine <- getLine\n\tlet groups = map ((+ 0) . read) $ words groupLine\n\tputStrLn $ show $ answer groups\n\nanswer :: [Integer] -> Int\nanswer a = \n\tlet fours = length $ filter (\\x -> x == 4) a;\n\t\tthrees = length $ filter (\\x -> x == 3) a;\n\t\ttwos = length $ filter (\\x -> x == 2) a;\n\t\tones = length $ filter (\\x -> x == 1) a;\n\t\tthreeOne = min ones threes;\n\t\ttwoPairs = twos `quot` 2;\n\t\tonesLeft = ones - threeOne;\n\t\tonePairs = quot onesLeft 2;\n\t\ttwosLeft = twos - (twoPairs * 2);\n\t\toneTwoPair = min twosLeft onePairs;\n\t\tonlyOneGroups = quot (3 + onesLeft - (oneTwoPair * 2)) 4\n\tin fours + threeOne + twoPairs + (threes - threeOne) + oneTwoPair + (twosLeft - (quot (oneTwoPair + 1) 2)) + onlyOneGroups"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)\n where count = map (pred . length) . group . sort . ([1..4]++) . map read . words\n numTaxi [o,t,h,f] = let (q,r) = divMod t 2\n in f + q + r + abs (o - h) + min o h"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok = if b > 0 && h /= 0 then 1 else 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "main = do\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if free1s >= (amounts !! 1) then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok = if b > 0 && h /= 0 then 1 else 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + bWith3 + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n bWith3 = if h == 0 then 0 else abs $ b - h\n ok | r > 0 || b > 0 = 1\n | otherwise = 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop 4 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "main = do\n getLine\n gr <-getLine\n let \n groups = map read $ words gr\n n1 = length $ filter (==1) groups\n n2 = length $ filter (==2) groups\n n3 = length $ filter (==3) groups\n n4 = length $ filter (==4) groups\n n21 = (n2 + 1)`div`2\n n11 = if (n2 `mod` 2 /= 0) then\n n1 - n3 - 1\n else \n n1 - n3\n n12 = if (n11 > 0) then\n (n11+3) `div` 4\n else \n 0\n putStrLn $ show (n4 + n3 + n21 + n12)\n "}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = interact $ show . solve . map (read) . words\n\nsolve :: [Int] -> Int\nsolve (n : xs) = \n d + cal a b c\n where\n (a : b : c : d:_) = map ((subtract 1) . length) . group . sort $ (1:2:3:4:xs)\n\ncal :: Int -> Int -> Int -> Int\ncal a b c\n | c > 0 = \n let \n k = min a c\n in\n c + cal (a - k) b 0\n | b > 0 = \n let\n k = min b (div a 2)\n in\n k + (ceilDiv (b - k) 2) + cal (a - 2 * k) 0 0\n | a > 0 =\n (ceilDiv a 4)\n | otherwise = 0\n\nceilDiv a b = div (a + b - 1) b\n"}, {"source_code": "main = do\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if (amounts !! 1) > free1s then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4"}, {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain = do s <- hGetContents stdin\n print $ solve $ map read $ words s\n\ns :: (Show a) => String -> a -> a\ns m x = x\n \nsolve :: [Int] -> Int\nsolve (n:xs) = fours + _31 + (threes - _31) + _22 + _21 + _11 + _11L\n where items = map (\\x -> (head x, length x)) $ group $ sort xs\n ones = fromMaybe 0 $ fmap snd $ find ((1==).fst) items\n twos = fromMaybe 0 $ fmap snd $ find ((2==).fst) items\n threes = fromMaybe 0 $ fmap snd $ find ((3==).fst) items\n fours = fromMaybe 0 $ fmap snd $ find ((4==).fst) items\n _31 = s \"_31\" $ max threes ones\n _22 = s \"_22\" $ div twos 2\n _21 = s \"_21\" $ if twos - _22*2 > 0 then 1 else 0\n _11 = s \"_11\" $ div (if _21 > 0 then max (ones - _31 - 2) 0 else (ones - _31)) 4\n _11L = s \"_11L\" $ if ones - _31 - _11*4 > 0 then 1 else 0"}, {"source_code": "enc :: [Int] -> Int -> Int\nenc s a = length $ filter (==a) s\n\ntaxis :: [Int] -> Int\ntaxis s = fours + threesOnes + twosTwos + onesTwos + leftOnes2 + fourOnes + (threes - threesOnes)\n where ones = enc s 1\n twos = enc s 2\n threes = enc s 3\n fours = enc s 4\n threesOnes = min ones threes\n twosTwos = twos `div` 2\n onesTwos = twos `mod` 2\n leftOnes = if (ones - threesOnes) > 2 then (ones - threesOnes - 2) else 0\n fourOnes = leftOnes `div` 4\n leftOnes2 = if leftOnes `mod` 4 > 0 then 1 else 0\n\nmain = do getLine\n numbers <- fmap (map read . words) getLine\n (putStrLn . show . taxis) numbers\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + min b h + rest3 + rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n rest1 = b - min b h\n rest3 = max 0 $ h - min b h\n rest | rest1 > 0 || r > 0 = 1 + (rest1 + 2*r) `div` 4\n | otherwise = 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "main = print . solve . map read . tail . words =<< getContents\nsolve ss = n4 + n3 + n2 `div` 2 + if odd n2 then 1 else 0 + (n1'' + 3) `div` 4\n where n1 = length (filter (==1) ss)\n n2 = length (filter (==2) ss)\n n3 = length (filter (==3) ss)\n n4 = length (filter (==4) ss)\n n1' = max (n1 - n3) 0\n n1'' = if odd n2 then max (n1' -2) 0 else n1'\n"}, {"source_code": "main = do\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if free1s > (amounts !! 1) then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok = if b > 0 then 1 else 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)\n where count = map (pred . length) . group . sort . ([1..4]++) . map read . words"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop 4 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + bWith3 + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n bWith3 = if h == 0 then 0 else abs $ b - h\n ok | r > 0 || b > 0 = 1\n | otherwise = 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "import Data.List (foldl')\nmain :: IO ()\nmain = do\n _ <- getLine\n ss <- getLine\n let groups = map read $ words ss\n print $ taxiSplit groups\n return ()\n\ntaxiSplit :: [Int] -> Int\ntaxiSplit = countCabs . (foldl' (groupSize) (0,0,0,0))\n where groupSize (a,b,c,d) x = case x of\n 1 -> (a + 1, b, c, d)\n 2 -> (a, b + 1, c, d)\n 3 -> (a, b, c + 1, d)\n 4 -> (a, b, c, d + 1)\n\ncountCabs :: (Int, Int, Int, Int) -> Int\ncountCabs (0, 0, 0, 0) = 0\ncountCabs (a, 0, 0, 0) = (a `quot` 4) + (if a `rem` 4 > 0 then 1 else 0)\ncountCabs (0, b, c, 0) = let b' = quot b 2 in\n b' + c + (if odd b then 1 else 0)\ncountCabs (a, b, 0, 0) = let b' = quot b 2 in\n b' + (if even b then a else if a < 3 then 1 else countCabs (a - 2, 0, 0, 0))\ncountCabs (a, b, c, 0) = let x = min a c in\n x + countCabs (a - x,b,c - x,0)\ncountCabs (a, b, c, d) = d + countCabs (a,b,c,0)\n\n"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\ninfixl 7 //\na // b = (ceiling $ (fromIntegral a) / b) \n \nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let a : b : c : d : [] = map (lookupOr 0 ys) [1..4]\n let t = a - c\n let h = d + c + if t < 0 then b // 2 else\n if b > t then\n t + (b - t) // 2\n else\n b + (t - b) // 4\n print h"}, {"source_code": "main :: IO ()\nmain = do \n n <- getLine\n inputs <- fmap (map read.words) getLine\n let [a,b,c,d] = map (\\x -> length $ filter (==x) inputs) [1,2,3,4]\n print $ d + c + (b*2 + 3 + (max 0 (a - c)) `div` 4)\n"}, {"source_code": "import Data.List (foldl')\nmain :: IO ()\nmain = do\n _ <- getLine\n ss <- getLine\n let groups = map read $ words ss\n print $ taxiSplit groups\n return ()\n\ntaxiSplit :: [Int] -> Int\ntaxiSplit = countCabs . (foldl' (groupSize) (0,0,0,0))\n where groupSize (a,b,c,d) x = case x of\n 1 -> (a + 1, b, c, d)\n 2 -> (a, b + 1, c, d)\n 3 -> (a, b, c + 1, d)\n 4 -> (a, b, c, d + 1)\n\ncountCabs :: (Int, Int, Int, Int) -> Int\ncountCabs (0, 0, 0, 0) = 0\ncountCabs (a, 0, 0, 0) = (a `quot` 4) + (if a `rem` 4 > 1 then 1 else 0)\ncountCabs (0, b, c, 0) = let b' = quot b 2 in\n b' + c + (if odd b then 1 else 0)\ncountCabs (a, b, 0, 0) = let b' = quot b 2 in\n b' + (if even b then a else if a < 3 then 1 else a - 2)\ncountCabs (a, b, c, 0) = let x = min a c in\n x + countCabs (a - x,b,c - x,0)\ncountCabs (a, b, c, d) = d + countCabs (a,b,c,0)\n\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Fri 19 Oct 2012 06:25:57 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\n\ncountBy ls cond= length $ filter cond ls\n\n\ncount ls k = countBy ls (\\s -> s == k)\n\nkth ls k = head $ drop k ls\nremaining ls k = \n let\n limit = kth (sort ls) k\n in\n countBy ls (\\s -> s >= limit && s > 0)\n\n\ncalcrem1s c3s c1s = \n if c3s >= c1s\n then \n 0\n else\n c1s-c3s\n\nposORZero num =\n if num >= 0\n then\n num\n else\n 0\n\ncalc groups = \n let c2s = count groups 2\n rem1s = posORZero $ (count groups 1) - (count groups 3)\n in\n let \n rem2s = c2s `mod` 2\n in\n let \n finalrem1s =\n if rem2s == 1\n then\n posORZero $ rem1s - 2\n else\n rem1s\n in\n (count groups 4) + (count groups 3) + (ceiling $ fromIntegral(c2s) / 2) + (ceiling $ fromIntegral(finalrem1s) / 4)\n\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInt all\n let (groups, _) = readMany readInt r1\n print groups\n print $ calc groups\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "main = do\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if free1s > (amounts !! 1) then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4\n"}, {"source_code": "main = do\n\tn <- getLine\n\targs <- getList ' '\n\tputStrLn $ show $ calc . parseGroups $ args\n\ngetList::Char -> IO [String]\ngetList sep = do\n\tinput <- getLine\n\treturn $ split input sep\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep then \"\":acc\n\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc) ) [\"\"] str\n\t\t\t\t\t\t\t\t\t\ncalc::[Int] -> Int\ncalc groups = do\n\tlet fours = groups !! 3\n\tlet threes = groups !! 2\n\tlet twos = ceiling . (/ 2) . fromIntegral $ groups !! 1\n\tlet ones = ceiling . (/ 4) . fromIntegral $ groups !! 0 - threes - (twos `mod` 2 * 2)\n\tfours + threes + twos + if ones > 0 then ones else 0\n\t\nparseGroups::[String] -> [Int]\nparseGroups args = foldr (\\curr acc -> if curr == \"1\" then [ acc !! 0 + 1, acc !! 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"2\" then [ acc !! 0, acc !! 1 + 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"3\" then [ acc !! 0, acc !! 1, acc !! 2 + 1, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else [ acc !! 0, acc !! 1, acc !! 2, acc !! 3 + 1 ]) [0,0,0,0] args"}, {"source_code": "main = do\n\tn <- getLine\n\targs <- getList ' '\n\tputStrLn $ show $ calc . parseGroups $ args\n\ngetList::Char -> IO [String]\ngetList sep = do\n\tinput <- getLine\n\treturn $ split input sep\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep then \"\":acc\n\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc) ) [\"\"] str\n\t\t\t\t\t\t\t\t\t\ncalc::[Int] -> Int\ncalc groups = do\n\tlet fours = groups !! 3\n\tlet threes = groups !! 2\n\tlet twos = ceiling . (/ 2) . fromIntegral $ groups !! 1\n\tlet ones = ceiling . (/ 4) . fromIntegral $ groups !! 0 - threes - (twos `mod` 2 * 2)\n\tfours + threes + twos + if ones > 0 then ones else 0\n\t\nparseGroups::[String] -> [Int]\nparseGroups args = foldr (\\curr acc -> if curr == \"1\" then [ acc !! 0 + 1, acc !! 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"2\" then [ acc !! 0, acc !! 1 + 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"3\" then [ acc !! 0, acc !! 1, acc !! 2 + 1, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else [ acc !! 0, acc !! 1, acc !! 2, acc !! 3 + 1 ]) [0,0,0,0] args"}, {"source_code": "-- Codeforces 158A\n\nmain :: IO()\nmain = interact $ show . solve . map read . words\n\n{-- interact:\n - interact :: (String -> String) -> IO()\n - The interact function takes a function of type String->String as its argument.\n - The entire input from the standard input device is passed to this function as \n - its argument, and the resulting string is output on the standard output device.\n--}\n\nsolve :: [Int] -> Int\nsolve (_:k:x) = sum[1 | i <- x, x!!(k-1) <= i, i > 0]\n\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] = f + h + q + a + r + rest\n where (q,r) = divMod t 2\n rest1 = o - h - 2*r\n (a,b) = divMod rest1 4\n rest = if b > 0 then 1 else 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "main = do\n irrelevant <- getLine\n input <- getLine\n let list = map read (words input)\n let (a,b,c,d) = (countN list 1, countN list 2, countN list 3, countN list 4)\n let b2 = b `div` 2 \n let c2 = if c>=a then c else c + a `div` 4\n let a2 | a>c && (a-c) `mod` 4 == 3 && odd b = 2\n | a>c && (a-c) `mod` 4 == 3 && even b = 1\n | a>c = 1\n | odd b = 1\n | otherwise = 0\n let answer = d + b2 + c2 + a2\n putStrLn (show answer)\n\ncountN xs n = length (filter (\\x -> x==n) xs)\n"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\ninfixl 7 //\na // b = (ceiling $ (fromIntegral a) / b) \n \nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let a : b : c : d : [] = map (lookupOr 0 ys) [1..4]\n let t = a - c\n let h = d + c + if t < 0 then b // 2 else\n if b > t then\n t + (b - t) // 2\n else\n b + (t - b) // 4\n print h"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\ninfixl 7 //\na // b = (ceiling $ (fromIntegral a) / b) \n \nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let a : b : c : d : [] = map (lookupOr 0 ys) [1..4]\n let t = a - c\n let h = d + c + if t < 0 then b // 2 else\n if b > t then\n t + (b - t) // 2\n else\n b + (t - b) // 4\n print h"}, {"source_code": "module Main where\n\ntype Counts = (Int, Int, Int, Int)\n\ncountChildren :: Counts -> [Int] -> Counts\ncountChildren c [] = c\ncountChildren (on, tw, th, fo) (x: xs)\n | x == 1 = countChildren (on + 1, tw, th, fo) xs\n | x == 2 = countChildren (on, tw + 1, th, fo) xs\n | x == 3 = countChildren (on, tw, th + 1, fo) xs\n | x == 4 = countChildren (on, tw, th, fo + 1) xs\n | otherwise = (on, tw, th, fo)\n\nmain :: IO ()\nmain = do\n _ <- fmap read getLine :: IO Int\n inp <- fmap words getLine :: IO [String]\n let s = fmap read inp :: [Int]\n (ones, twos, threes, fours) = countChildren (0, 0, 0, 0) s\n (coupleTwos, loneTwos) = twos `quotRem` 2\n (coupleOnes, loneOnes) = max (ones - threes) 0 `quotRem` 2\n (foursOnes, leftOnes) = (max (coupleOnes - loneTwos) 0 * 2 + loneOnes) `quotRem` 4\n (remCabs, remChild) = (loneTwos * 2 + leftOnes ) `quotRem` 4\n res1 = fours + -- fours take a cab to themselves\n min ones threes + -- combine threes and ones to one cab\n max (threes - ones) 0 + -- remaining threes each take one cab\n coupleTwos + -- twos can combine with themselves\n min coupleOnes loneTwos + -- combine remaining twos with couples of ones\n foursOnes + -- group remaining ones into 4 per cab\n remCabs + -- fit any remaining twos and ones in a cab\n if remChild > 0 then 1 else 0 -- any children left can fit in last 1 cab\n\n print res1\n"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\ninfixl 7 //\na // b = (ceiling $ (fromIntegral a) / b) \n \nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let a : b : c : d : [] = map (lookupOr 0 ys) [1..4]\n let t = a - c\n let h = d + c + if t < 0 then b // 2 else\n if b > t then\n t + (b - t) // 2\n else\n b + (t - b) // 4\n print h"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n03 + n12 + n02 + n01\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n12 = min n1''' n2\n n1'''' = n1''' - n12\n n2''' = n2'' - n12\n n01 = if n1'''' > 0 then 1 else 0\n n02 = n2'''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.List \n\nsolve :: [Int] -> Int\nsolve xs = c4 + c3 + c2 `div` 2 + countRest c1 c2 c3 c4\n where\n (c1, c2, c3, c4) = foldl' (\\acc x -> countNumbers acc x) (0,0,0,0) xs\n countNumbers (a1, a2, a3, a4) x | x == 1 = (a1 + 1, a2, a3, a4)\n | x == 2 = (a1, a2 + 1, a3, a4)\n | x == 3 = (a1, a2, a3 + 1, a4)\n | x == 4 = (a1, a2, a3, a4 + 1)\n countRest a1 a2 a3 a4 = let a1With3 = if (a3 > a1) then a1 else a3\n a1AfterSittingWith3 = a1 - a1With3\n a1With2 = if (a2 `mod` 2 == 1 && a1AfterSittingWith3 > 0) then min a1AfterSittingWith3 2 else 0\n a1AfterSittingWith2 = a1AfterSittingWith3 - a1With2\n a1With1 = a1AfterSittingWith2 - a1AfterSittingWith2 `mod` 4\n a1AfterSittingWith1 = a1AfterSittingWith2 - a1With1\n in a1With1 `div` 4 + (if (a1AfterSittingWith1 > 0) then 1 else 0) + (if (a1With2 == 0 && a2 `mod` 2 == 1) then 1 else 0)\n\nmain = do\n getLine\n xs <- fmap (map read . words) getLine\n print $ solve xs\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok | b > 0 && h /= 0 = 1\n | b == 0 && h == 0 = 1\n | otherwise = 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "main = do\n line <- getLine\n let groups = (map read . words) line :: [Int]\n putStrLn (show $ minCars groups)\n\nminCars :: [Int] -> Int\nminCars nums = let\n ofNum n = length . filter (n==) $ nums\n amounts = map ofNum [0..4]\n cars' = (amounts !! 4) + (amounts !! 3) + div (1 + amounts !! 2) 2\n free1s = (amounts !! 3) + 2 * (mod (amounts !! 2) 2)\n in if free1s >= (amounts !! 1) then cars'\n else cars' + div (3 - free1s + amounts !! 1) 4\n"}, {"source_code": "main = do\n irrelevant <- getLine\n input <- getLine\n let list = map read (words input)\n let (a,b,c,d) = (countN list 1, countN list 2, countN list 3, countN list 4)\n let b2 = b `div` 2 \n let c2 = if c>=a then c else c + a `div` 4\n let a2 | a>c && (a-c) `mod` 4 == 3 && odd b = 2\n | a>c && (a-c) `mod` 4 == 3 && even b = 1\n | a>c && (a-c) `mod` 4 == 2 && odd b = 1\n | a>c && (a-c) `mod` 4 == 2 && even b = 1\n | a>c && (a-c) `mod` 4 == 1 && odd b = 1\n | a>c && (a-c) `mod` 4 == 1 && even b = 1\n | a>c && (a-c) `mod` 4 == 0 && odd b = 1\n | a>c && (a-c) `mod` 4 == 0 && even b = 0\n | odd b = 1\n | otherwise = 0\n let answer = d + b2 + c2 + a2\n putStrLn (show answer)\n\ncountN xs n = length (filter (\\x -> x==n) xs)\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)\n where count = map (pred . length) . group . sort . ([1..4]++) . map read . words\n numTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok = if b > 0 then 1 else 0\n rest = if b - h > 0 && b + 2*r <= 4\n then 1\n else 2"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop d (filter (==1) nums)) (k + l)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n d = (length (filter (==1) nums)) `div` 4\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "main = do\n\tn <- getLine\n\targs <- getList ' '\n\tputStrLn $ show $ calc . parseGroups $ args\n\ngetList::Char -> IO [String]\ngetList sep = do\n\tinput <- getLine\n\treturn $ split input sep\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep then \"\":acc\n\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc) ) [\"\"] str\n\t\t\t\t\t\t\t\t\t\ncalc::[Int] -> Int\ncalc groups = do\n\tlet fours = groups !! 3\n\tlet threes = groups !! 2\n\tlet twos = ceiling . (/ 2) . fromIntegral $ groups !! 1\n\tlet ones = ceiling . (/ 4) . fromIntegral $ groups !! 0 - threes - (twos `mod` 2 * 2)\n\tfours + threes + twos + if ones > 0 then ones else 0\n\t\nparseGroups::[String] -> [Int]\nparseGroups args = foldr (\\curr acc -> if curr == \"1\" then [ acc !! 0 + 1, acc !! 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"2\" then [ acc !! 0, acc !! 1 + 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"3\" then [ acc !! 0, acc !! 1, acc !! 2 + 1, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else [ acc !! 0, acc !! 1, acc !! 2, acc !! 3 + 1 ]) [0,0,0,0] args"}, {"source_code": "main = do\n n <- getLine\n xs <- getLine\n let ys = [read x::Int | x <- words(xs)]\n print $ f $ [length $ filter (==i) ys | i <- [1..4]]\n \nf xs = a4 + a3 + div (a2 + 1) 2 + div (max 0 (a1 - a4 - 2 * mod a2 2 + 3)) 4\n where \n a4 = xs !! 3\n a3 = xs !! 2\n a2 = xs !! 1\n a1 = xs !! 0"}, {"source_code": "\nmain = do\n _ <- getLine\n groups <- getLine\n\n\n print $ (show :: Int -> String) 4\n"}, {"source_code": "import Data.List (sortBy)\n\ntaxi :: [Int] -> Int\ntaxi = taxiGrouper 0 [] -- . sortBy (flip compare)\n\ntaxiGrouper :: Int -> [Int] -> [Int] -> Int\ntaxiGrouper groups fall@(f:fs) (p:ps)\n\t| f >= p = taxiGrouper groups (insert (f-p) fs) ps\n\t| otherwise = taxiGrouper (groups + 1) (insert (4-p) fall) ps\ntaxiGrouper groups _ (p:ps) = taxiGrouper (groups + 1) (insert (4-p) []) ps\ntaxiGrouper groups _ _ = groups\n\ninsert :: Int -> [Int] -> [Int]\ninsert x (y:ys) = if x < y then y : (insert x ys) else x:y:ys\ninsert x _ = [x]\n\nmain = do\n\tgetLine\n\tgetLine >>= print . taxi . (map read) . words"}, {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain = do s <- hGetContents stdin\n print $ solve $ map read $ words s\n\ns :: (Show a) => String -> a -> a\ns m x = x\n \nsolve :: [Int] -> Int\nsolve (n:xs) = fours + _31 + (threes - _31) + _22 + _21 + _11 + _11L\n where items = map (\\x -> (head x, length x)) $ group $ sort xs\n ones = fromMaybe 0 $ fmap snd $ find ((1==).fst) items\n twos = fromMaybe 0 $ fmap snd $ find ((2==).fst) items\n threes = fromMaybe 0 $ fmap snd $ find ((3==).fst) items\n fours = fromMaybe 0 $ fmap snd $ find ((4==).fst) items\n _31 = s \"_31\" $ max threes ones\n _22 = s \"_22\" $ div twos 2\n _21 = s \"_21\" $ if twos - _22*2 > 0 then 1 else 0\n _11 = s \"_11\" $ div (if _21 > 0 then max (ones - _31 - 2) 0 else (ones - _31)) 4\n _11L = s \"_11L\" $ if ones - _31 - _11*4 > 0 then 1 else 0"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n03 + n12 + n02 + n01\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n12 = min n1''' n2\n n1'''' = n1''' - n12\n n2''' = n2'' - n12\n n01 = if n1'''' > 0 then 1 else 0\n n02 = n2'''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map read . words . (!! 1) . lines)\n\nsolve :: [Int] -> Int\nsolve groups = sum [four, threePlusOne, twoPlusTwo, three', twoPlusOnes, one''] where\n one'' = if two' == 1 then max 0 (one' - 2) else one'\n twoPlusOnes = if two' == 1 then 1 else 0\n (one', two', three') = (one - threePlusOne, two `mod` 2, three - threePlusOne)\n twoPlusTwo = two `div` 2\n threePlusOne = min three one\n [one, two, three, four] = [length (filter (== x) groups) | x <- [1..4]]\n"}, {"source_code": "module Main where\n\ntype Counts = (Int, Int, Int, Int)\n\ncountChildren :: Counts -> [Int] -> Counts\ncountChildren c [] = c\ncountChildren (on, tw, th, fo) (x: xs)\n | x == 1 = countChildren (on + 1, tw, th, fo) xs\n | x == 2 = countChildren (on, tw + 1, th, fo) xs\n | x == 3 = countChildren (on, tw, th + 1, fo) xs\n | x == 4 = countChildren (on, tw, th, fo + 1) xs\n | otherwise = (on, tw, th, fo)\n\nmain :: IO ()\nmain = do\n _ <- fmap read getLine :: IO Int\n inp <- fmap words getLine :: IO [String]\n let s = fmap read inp :: [Int]\n (ones, twos, threes, fours) = countChildren (0, 0, 0, 0) s\n (coupleTwos, loneTwos) = twos `quotRem` 2\n (coupleOnes, loneOnes) = max (ones - threes) 0 `quotRem` 2\n (foursOnes, leftOnes) = (max (coupleOnes - loneTwos) 0 * 2 + loneOnes) `quotRem` 4\n (remCabs, remChild) = (loneTwos * 2 + leftOnes ) `quotRem` 4\n res1 = fours + -- fours take a cab to themselves\n min ones threes + -- combine threes and ones to one cab\n max (threes - ones) 0 + -- remaining threes each take one cab\n coupleTwos + -- twos can combine with themselves\n min coupleOnes loneTwos + -- combine remaining twos with couples of ones\n foursOnes + -- group remaining ones into 4 per cab\n remCabs + -- fit any remaining twos and ones in a cab\n if remChild > 0 then 1 else 0 -- any children left can fit in last 1 cab\n\n print res1\n"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let f = lookupOr 0 ys\n let a : b : c : d : [] = map f [1..4] \n print $ d + c + max (ceiling $ (fromIntegral $ a - c) / 4) (ceiling $ (fromIntegral b) / 2)"}, {"source_code": "import Data.Sequence\nimport Data.Foldable\n\ngetGroups :: IO [Integer]\ngetGroups = do\n _groups <- getLine\n return $ map read (words _groups)\n\ngetAnswer :: [Integer] -> Integer\ngetAnswer groups = quantify $ count groups\n\ncount :: [Integer] -> [Integer]\ncount groups = _count groups [0, 0, 0, 0]\n\n_count :: [Integer] -> [Integer] -> [Integer]\n_count [] counter = counter\n_count (first:rest) counter = _count rest $ toList $ update position ((counter !! position) + 1) $ fromList counter\n where position = fromIntegral first - 1\n\nquantify :: [Integer] -> Integer\nquantify counter = getQuarters + getTriplesAndOnes + getDoubles + getRest\n where ones = head counter\n twos = head $ tail counter\n threes = head $ tail $ tail counter\n fours = last counter\n getQuarters = fours\n getTriplesAndOnes = threes\n onesWithoutThrees = if ones > threes\n then ones - threes\n else 0\n (getDoubles, onesRest) = quantifyDoubles twos onesWithoutThrees\n getRest = onesRest `div` 4 + if onesRest `mod` 4 > 0\n then 1\n else 0\n\nquantifyDoubles :: Integer -> Integer -> (Integer, Integer)\nquantifyDouble 0 ones = (0, ones)\nquantifyDoubles twos ones = (countedTwos, onesRest)\n where countedTwos = twos `div` 2 + twos `mod` 2\n onesRest = if ones >= 2\n then ones - 1\n else 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n groups <- getGroups\n print $ getAnswer groups"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop 4 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\ngetIntArray :: IO[Int]\ngetIntArray = fmap ((map read).words) getLine\n\nmain = interact$show.s.(map read).words\n\ns :: [Int] -> Int\ns (x:xs) = ((sum xs) - 1) `div` 4 + 1 "}, {"source_code": "\n\nmain = do\n getLine\n aa <- getLine\n let xs = map read $ words aa :: [Int]\n print $ ceiling $ fromIntegral (length xs) / 4\n"}, {"source_code": "module Main where\n\ntype Counts = (Int, Int, Int, Int)\n\ncountChildren :: Counts -> [Int] -> Counts\ncountChildren c [] = c\ncountChildren (on, tw, th, fo) (x: xs)\n | x == 1 = countChildren (on + 1, tw, th, fo) xs\n | x == 2 = countChildren (on, tw + 1, th, fo) xs\n | x == 3 = countChildren (on, tw, th + 1, fo) xs\n | x == 4 = countChildren (on, tw, th, fo + 1) xs\n | otherwise = (on, tw, th, fo)\n\nmain :: IO ()\nmain = do\n _ <- fmap read getLine :: IO Int\n inp <- fmap words getLine :: IO [String]\n let s = fmap read inp :: [Int]\n (ones, twos, threes, fours) = countChildren (0, 0, 0, 0) s\n (coupleTwos, loneTwos) = twos `quotRem` 2\n (coupleOnes, loneOnes) = max (ones - threes) 0 `quotRem` 2\n (foursOnes, leftOnes) = (max (coupleOnes - loneTwos) 0 * 2 + loneOnes) `quotRem` 4\n (remCabs, remChild) = (loneTwos * 2 + leftOnes ) `quotRem` 4\n res1 = fours + -- fours take a cab to themselves\n min ones threes + -- combine threes and ones to one cab\n max (threes - ones) 0 + -- remaining threes each take one cab\n coupleTwos + -- twos can combine with themselves\n min coupleOnes loneTwos + -- combine remaining twos with couples of ones\n foursOnes + -- group remaining ones into 4 per cab\n remCabs + -- fit any remaining twos and ones in a cab\n if remChild > 0 then 1 else 0 -- any children left can fit in last 1 cab\n\n print res1\n"}, {"source_code": "main = do\n\tn <- getLine\n\targs <- getList ' '\n\tputStrLn $ show $ calc . parseGroups $ args\n\ngetList::Char -> IO [String]\ngetList sep = do\n\tinput <- getLine\n\treturn $ split input sep\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep then \"\":acc\n\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc) ) [\"\"] str\n\t\t\t\t\t\t\t\t\t\ncalc::[Int] -> Int\ncalc groups = do\n\tlet fours = groups !! 3\n\tlet threes = groups !! 2\n\tlet twos = ceiling . (/ 2) . fromIntegral $ groups !! 1\n\tlet ones = ceiling . (/ 4) . fromIntegral $ groups !! 0 - threes - (twos `mod` 2 * 2)\n\tfours + threes + twos + if ones > 0 then ones else 0\n\t\nparseGroups::[String] -> [Int]\nparseGroups args = foldr (\\curr acc -> if curr == \"1\" then [ acc !! 0 + 1, acc !! 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"2\" then [ acc !! 0, acc !! 1 + 1, acc !! 2, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else if curr == \"3\" then [ acc !! 0, acc !! 1, acc !! 2 + 1, acc !! 3 ]\n\t\t\t\t\t\t\t\t\t else [ acc !! 0, acc !! 1, acc !! 2, acc !! 3 + 1 ]) [0,0,0,0] args"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n03 + n12 + n02 + n01\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n12 = min n1''' n2\n n1'''' = n1''' - n12\n n2''' = n2'' - n12\n n01 = if n1'''' > 0 then 1 else 0\n n02 = n2'''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.List (sortBy)\n\ntaxi :: [Int] -> Int\ntaxi = taxiGrouper 0 [] -- . sortBy (flip compare)\n\ntaxiGrouper :: Int -> [Int] -> [Int] -> Int\ntaxiGrouper groups fall@(f:fs) (p:ps)\n\t| f >= p = taxiGrouper groups (insert (f-p) fs) ps\n\t| otherwise = taxiGrouper (groups + 1) (insert (4-p) fall) ps\ntaxiGrouper groups _ (p:ps) = taxiGrouper (groups + 1) (insert (4-p) []) ps\ntaxiGrouper groups _ _ = groups\n\ninsert :: Int -> [Int] -> [Int]\ninsert x (y:ys) = if x < y then y : (insert x ys) else x:y:ys\ninsert x _ = [x]\n\nmain = do\n\tgetLine\n\tgetLine >>= print . taxi . (map read) . words"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n03 + n12 + n02 + n01\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n12 = min n1''' n2\n n1'''' = n1''' - n12\n n2''' = n2'' - n12\n n01 = if n1'''' > 0 then 1 else 0\n n02 = n2'''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "main :: IO ()\nmain = do\n n <- fmap read getLine :: IO Integer\n si <- fmap (map read . words) getLine :: IO [Int]\n print $ fillCars $ groups $ si\n\nfillCars :: [Int] -> Int\nfillCars g = g4 + \n min g3 g1 +\n max (g3 - (min g3 g1)) 0 +\n div g2 2 + (mod g2 2) +\n div g1' 4 + (mod g1' 4)\n where \n g1 = g !! 0\n g2 = g !! 1\n g3 = g !! 2\n g4 = g !! 3\n g1' = max (g1 - (min g3 g1) - ((mod g2 2) * 2)) 0\n\n\ngroups :: [Int] -> [Int]\ngroups [] = [0,0,0,0]\ngroups (x:xs) = [b 1, b 2, b 3, b 4]\n where b = \\i -> groups xs !! (i-1) + (if x == i then 1 else 0)\n\n\n\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop d (filter (==1) nums)) (k + l)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n d = (length (filter (==1) nums)) `div` 4\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop 4 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + min b h + rest3 + rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n rest1 = b - min b h\n rest3 = max 0 $ h - min b h\n rest = 1 + (rest1 + 2*r) `div` 4\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve (_ : k : xs) = length . takeWhile (>= xs !! (k - 1)) . filter (> 0) $ xs\n"}, {"source_code": "increaseNth :: [Int] -> Int -> [Int]\nincreaseNth xs n = take n xs ++ [((xs !! n) + 1)] ++ drop (n + 1) xs\n\ncountArrAss :: [Int] -> [Int] -> [Int]\ncountArrAss [] after = after\ncountArrAss (x:pre) after = countArrAss pre (increaseNth after (x - 1))\n\ncountArr :: [Int] -> [Int]\ncountArr da = countArrAss da [0, 0, 0, 0]\n\npreProcess :: [Char] -> [Int]\npreProcess s = countArr $ map read (words s)\n\nsol :: [Int] -> Int\nsol xs = prefix4th + prefix3th + prefix2th + prefix1th\n where prefix4th = (xs !! 3)\n prefix3th = (xs !! 2)\n prefix1sub3 = (xs !! 0) - (xs !! 2)\n prefix2th = div (xs !! 1) 2\n prefix2remain = mod (xs !! 1) 2\n prefix1sub3sub2 = prefix1sub3 - 2 * prefix2remain\n prefix1th = ceiling ((fromIntegral prefix1sub3sub2) / 4)\n\nmain = do\n n <- getLine\n groups <- getLine\n putStrLn $ show (sol (preProcess groups))\n"}, {"source_code": "main = do\n irrelevant <- getLine\n input <- getLine\n let list = map read (words input)\n let (a,b,c,d) = (countN list 1, countN list 2, countN list 3, countN list 4)\n let b2 = b `div` 2 \n let c2 = if c>=a then c else c + a `div` 4\n let a2 | a>c && (a-c) `mod` 4 == 3 && odd b = 2\n | a>c && (a-c) `mod` 4 == 3 && even b = 1\n | a>c && (a-c) `mod` 4 == 2 && odd b = 1\n | a>c && (a-c) `mod` 4 == 2 && even b = 1\n | a>c && (a-c) `mod` 4 == 1 && odd b = 1\n | a>c && (a-c) `mod` 4 == 1 && even b = 1\n | a>c && (a-c) `mod` 4 == 0 && odd b = 1\n | a>c && (a-c) `mod` 4 == 0 && even b = 0\n | odd b = 1\n | otherwise = 0\n let answer = d + b2 + c2 + a2\n putStrLn (show answer)\n\ncountN xs n = length (filter (\\x -> x==n) xs)\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] = f + h + q + a + r + rest\n where (q,r) = divMod t 2\n rest1 = o - h - 2*r\n (a,b) = divMod rest1 4\n rest = if b > 0 then 1 else 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop d (filter (==1) nums)) (k + l)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n d = (length (filter (==1) nums)) `div` 4\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n03 + n12 + n02 + n01\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n12 = min n1''' n2\n n1'''' = n1''' - n12\n n2''' = n2'' - n12\n n01 = if n1'''' > 0 then 1 else 0\n n02 = n2'''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "import Data.List \n\nsolve :: [Int] -> Int\nsolve xs = c4 + c3 + c2 `div` 2 + countRest c1 c2 c3 c4\n where\n (c1, c2, c3, c4) = foldl' (\\acc x -> countNumbers acc x) (0,0,0,0) xs\n countNumbers (a1, a2, a3, a4) x | x == 1 = (a1 + 1, a2, a3, a4)\n | x == 2 = (a1, a2 + 1, a3, a4)\n | x == 3 = (a1, a2, a3 + 1, a4)\n | x == 4 = (a1, a2, a3, a4 + 1)\n countRest a1 a2 a3 a4 = let a1With3 = if (a3 > a1) then a1 else a3\n a1AfterSittingWith3 = a1 - a1With3\n a1With2 = if (a2 `mod` 2 == 1 && a1AfterSittingWith3 > 0) then min a1AfterSittingWith3 2 else 0\n a1AfterSittingWith2 = a1AfterSittingWith3 - a1With2\n a1With1 = a1AfterSittingWith2 - a1AfterSittingWith2 `mod` 4\n a1AfterSittingWith1 = a1AfterSittingWith2 - a1With1\n in a1With1 `div` 4 + (if (a1AfterSittingWith1 > 0) then 1 else 0) + (if (a1With2 == 0 && a2 `mod` 2 == 1) then 1 else 0)\n\nmain = do\n getLine\n xs <- fmap (map read . words) getLine\n print $ solve xs\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + min o h + rest3 + rest\n where (q,r) = divMod t 2\n rest1 = max 0 $ o - min o h\n rest3 = max 0 $ h - min o h\n (a,b) = divMod rest1 4\n rest | b > 0 || r > 0 = 1 + (a + 2*r) `div` 4\n | otherwise = 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "\n\nmain = do\n getLine\n aa <- getLine\n let xs = map read $ words aa :: [Int]\n print $ ceiling $ fromIntegral (length xs) / 4\n"}, {"source_code": "import Data.Sequence\nimport Data.Foldable\n\ngetGroups :: IO [Integer]\ngetGroups = do\n _groups <- getLine\n return $ map read (words _groups)\n\ngetAnswer :: [Integer] -> Integer\ngetAnswer groups = quantify $ count groups\n\ncount :: [Integer] -> [Integer]\ncount groups = _count groups [0, 0, 0, 0]\n\n_count :: [Integer] -> [Integer] -> [Integer]\n_count [] counter = counter\n_count (first:rest) counter = _count rest $ toList $ update position ((counter !! position) + 1) $ fromList counter\n where position = fromIntegral first - 1\n\nquantify :: [Integer] -> Integer\nquantify counter = getQuarters + getTriplesAndOnes + getDoubles + getRest\n where ones = head counter\n twos = head $ tail counter\n threes = head $ tail $ tail counter\n fours = last counter\n getQuarters = fours\n getTriplesAndOnes = threes\n onesWithoutThrees = if ones > threes\n then ones - threes\n else 0\n (getDoubles, onesRest) = quantifyDoubles twos onesWithoutThrees\n getRest = onesRest `div` 4 + if onesRest `mod` 4 > 0\n then 1\n else 0\n\nquantifyDoubles :: Integer -> Integer -> (Integer, Integer)\nquantifyDoubles 0 ones = (0, ones)\nquantifyDoubles twos ones = (countedTwos, onesRest)\n where countedTwos = twos `div` 2 + twos `mod` 2\n onesRest = if ones >= 2 && twos `mod` 2 == 1\n then ones - 2\n else ones\n\nmain :: IO ()\nmain = do\n n <- getLine\n groups <- getGroups\n print $ getAnswer groups"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + bWith3 + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n bWith3 = if h == 0 then 0 else abs $ b - h\n rest3 = b - min b h\n ok | r > 0 || b > 0 = 1\n | otherwise = 0\n rest | rest3 - h == 0 = r\n | rest3 + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\ninfixl 7 //\na // b = (ceiling $ (fromIntegral a) / b) \n \nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let a : b : c : d : [] = map (lookupOr 0 ys) [1..4]\n print $ d + c + b // 2 + if a > c then (a - c) // 4 else 0"}, {"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= print . solve . map (fst . fromJust . B.readInt) . B.words . (!!1) . B.lines\n\nsolve :: [Int] -> Int\nsolve = go . count (0, 0, 0, 0)\n where go (0, 0, 0, n) = (n + 3) `div` 4\n go (0, 0, n, k) = (n + 1) `div` 2 + go (0, 0, 0, max 0 (k - n `mod` 2))\n go (0, n, k, l) = n + go (0, 0, k, max 0 (l - n))\n go (n, k, l, m) = n + go (0, k, l, m)\n count (a, b, c, d) (4:ss) = count (a + 1, b, c, d) ss\n count (a, b, c, d) (3:ss) = count (a, b + 1, c, d) ss\n count (a, b, c, d) (2:ss) = count (a, b, c + 1, d) ss\n count (a, b, c, d) (1:ss) = count (a, b, c, d + 1) ss\n count x _ = x\n"}, {"source_code": "taxi :: [Int] -> Int\ntaxi s = t4 + t31 + t3 + t2 + t21 + t1\n where t4 = count 4 s\n t31 = min c3 c1\n t3 = c3 - t31\n t2 = div c2 2\n t21 = rem c2 2\n t1 = max (c1 - t31 - t21 * 2) 0\n c1 = count 1 s\n c2 = count 2 s\n c3 = count 3 s\n count x = length . filter (==x)\n\nmain = do\n getLine\n s <- getLine\n print $ taxi $ map read $ words s\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop d (filter (==1) nums)) (k + l)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n d = (length (filter (==1) nums)) `div` 4\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "import Data.Sequence\nimport Data.Foldable\n\ngetGroups :: IO [Integer]\ngetGroups = do\n _groups <- getLine\n return $ map read (words _groups)\n\ngetAnswer :: [Integer] -> Integer\ngetAnswer groups = quantify $ count groups\n\ncount :: [Integer] -> [Integer]\ncount groups = _count groups [0, 0, 0, 0]\n\n_count :: [Integer] -> [Integer] -> [Integer]\n_count [] counter = counter\n_count (first:rest) counter = _count rest $ toList $ update position ((counter !! position) + 1) $ fromList counter\n where position = fromIntegral first - 1\n\nquantify :: [Integer] -> Integer\nquantify counter = getQuarters + getTriplesAndOnes + getDoubles + getRest\n where ones = head counter\n twos = head $ tail counter\n threes = head $ tail $ tail counter\n fours = last counter\n getQuarters = fours\n getTriplesAndOnes = threes\n onesWithoutThrees = if ones > threes\n then ones - threes\n else 0\n (getDoubles, onesRest) = quantifyDoubles twos onesWithoutThrees\n getRest = onesRest `div` 4 + if onesRest `mod` 4 > 0\n then 1\n else 0\n\nquantifyDoubles :: Integer -> Integer -> (Integer, Integer)\nquantifyDouble 0 ones = (0, ones)\nquantifyDoubles twos ones = (countedTwos, onesRest)\n where countedTwos = twos `div` 2 + twos `mod` 2\n onesRest = if ones >= 2\n then ones - 1\n else 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n groups <- getGroups\n print $ getAnswer groups"}, {"source_code": "{-\nB. Taxi\n=======\ntime limit per test 3 seconds\nmemory limit per test 256 megabytes\ninput standard input\noutput standard output\n\nAfter the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1\u2009\u2264\u2009si\u2009\u2264\u20094), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?\n\nInput\n------\nThe first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910^ 5) \u2014 the number of groups of schoolchildren. The second line contains a sequence of integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u20094). The integers are separated by a space, si is the number of children in the i-th group.\n\nOutput\n-------\nPrint the single number \u2014 the minimum number of taxis necessary to drive all children to Polycarpus.\n\nSample test(s)\n--------------\ninput\n```\n5\n1 2 4 3 3\n```\noutput\n```\n4\n```\ninput\n```\n8\n2 3 4 4 2 1 3 1\n```\noutput\n```\n5\n```\nNote\nIn the first test we can sort the children into four cars like this:\n\n- the third group (consisting of four children),\n- the fourth group (consisting of three children),\n- the fifth group (consisting of three children),\n- the first and the second group (consisting of one and two children, correspondingly).\nThere are other ways to sort the groups into four cars.\n-}\n\nimport Data.List (sort, group)\n\ncount :: Int -> [Int] -> Int\ncount k xs = length $ filter (== k) xs\n\ntaxiNumber :: [Int] -> Int\ntaxiNumber xs = n4 + n3 + ceiling (fromIntegral n2 / 2) + max 0 (n1 - n3 - 2 * (n2 `mod` 2)) `div` 4\n where [n1, n2, n3, n4] = map (`count` xs) [1,2,3,4]\n\nreader :: String -> [Int]\nreader s = map read $ words second\n where [_, second] = lines s\n\nmain = do\n input <- getContents\n let xs = reader input\n print $ taxiNumber xs\n"}, {"source_code": "import Data.List (sort)\n\ntaxi :: [Int] -> Int\ntaxi xs = taxiGrouper 0 sorted $ reverse sorted\n\twhere sorted = sort xs\n\ntaxiGrouper :: Int -> [Int] -> [Int] -> Int\ntaxiGrouper groups [x] [y] = groups + 1\ntaxiGrouper groups xall@(x:xs) yall@(y:ys) = taxiGrouper (groups + 1) newxs newys\n\twhere (newxs, newys)\n\t\t| x + y <= 4 = (init xs, init ys)\n\t\t| x == 4 || x > y = (xs, init yall)\n\t\t| otherwise = (init xall, ys)\ntaxiGrouper groups _ _ = groups\n\nmain = do\n\tgetLine\n\tgetLine >>= print . taxi . (map read) . words"}, {"source_code": "import Data.List (sort, group)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency xs = map (\\ys -> (head ys, length ys)) $ group . sort $ xs\n\nlookupOr :: Eq a => b -> [(a, b)] -> a -> b\nlookupOr d xs x = case lookup x xs of\n (Just y) -> y\n Nothing -> d\n\nmain :: IO ()\nmain = do\n getLine\n xs <- readInts\n let ys = frequency xs\n let f = lookupOr 0 ys\n let a : b : c : d : [] = map f [1..4] \n print $ d + c + max (a - c) (ceiling $ (fromIntegral b) / 2)"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + min o h + rest3 + rest\n where (q,r) = divMod t 2\n rest1 = max 0 $ o - min o h\n rest3 = max 0 $ h - min o h\n (a,b) = divMod rest1 4\n rest | b > 0 || r > 0 = 1 + (a + 2*r) `div` 4\n | otherwise = 0\n\nnumTaxi2 :: [Int] -> Int\nnumTaxi2 [o,t,h,f] = f + q + a + min b h + rest3 + rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n rest1 = max 0 $ b - min b h\n rest3 = max 0 $ h - min b h\n rest | rest1 > 0 || r > 0 = 1 + (a + 2*r) `div` 4\n | otherwise = 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . num . count =<< (getLine >> getLine)\n where num xs = min (numTaxi xs) (numTaxi2 xs)"}, {"source_code": "main = do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let ss = take n $ map read $ words line :: [Int]\n putStrLn $ show $ solve ss\n\nsolve :: [Int] -> Int\nsolve ss = c4 + solve' c1 c2 c3\n where\n c1 = count (== 1) ss\n c2 = count (== 2) ss\n c3 = count (== 3) ss\n c4 = count (== 4) ss\n\nsolve' :: Int -> Int -> Int -> Int\nsolve' 0 c2 0 = c2 `divUp` 2\nsolve' 0 c2 c3 = c2 + c3\nsolve' c1 0 0 = c1 `divUp` 4\nsolve' c1 c2 0 | c1 >= 2 * c2 = c2 + solve' (c1 - 2 * c2) 0 0\n | otherwise = c1 `divUp` 2 + solve' 0 (c2 - c1 `divUp` 2) 0\nsolve' c1 c2 c3 | c1 >= c3 = c3 + solve' (c1 - c3) c2 0\n | otherwise = c1 + solve' 0 c2 (c3 - c1)\n\ndivUp a b = (a - 1) `div` b + 1\n\ncount :: (a -> Bool) -> [a] -> Int\ncount p = length . filter p\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok | b > 0 && h /= 0 = 1\n | b == 0 && h == 0 = 1\n | otherwise = 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop 1 (filter (==2) nums) ++ drop z (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop 4 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = if length (filter (==1) nums) >= 1 && length (filter (==1) nums) < 3 then (length (filter (==1) nums)) else 0\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + min b h + rest3 + rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n rest1 = b - min b h\n rest3 = max 0 $ h - min b h\n rest | rest1 > 0 || r > 0 = 1 + (rest1 + 2*r) `div` 4\n | otherwise = 0\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "-- Codeforces 158A\n\nmain :: IO()\nmain = interact $ show . solve . map read . words\n\n{-- interact:\n - interact :: (String -> String) -> IO()\n - The interact function takes a function of type String->String as its argument.\n - The entire input from the standard input device is passed to this function as \n - its argument, and the resulting string is output on the standard output device.\n--}\n\nsolve :: [Int] -> Int\nsolve (_:k:x) = sum[1 | i <- x, x!!(k-1) <= i, i > 0]\n\n"}, {"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= print . solve . map (fst . fromJust . B.readInt) . B.words . (!!1) . B.lines\n\nsolve :: [Int] -> Int\nsolve = go . count (0, 0, 0, 0)\n where go (0, 0, 0, n) = (n + 3) `div` 4\n go (0, 0, n, k) = (n + 1) `div` 2 + go (0, 0, 0, max 0 (k - n `mod` 2))\n go (0, n, k, l) = n + go (0, 0, k, max 0 (l - n))\n go (n, k, l, m) = n + go (0, k, l, m)\n count (a, b, c, d) (4:ss) = count (a + 1, b, c, d) ss\n count (a, b, c, d) (3:ss) = count (a, b + 1, c, d) ss\n count (a, b, c, d) (2:ss) = count (a, b, c + 1, d) ss\n count (a, b, c, d) (1:ss) = count (a, b, c, d + 1) ss\n count x _ = x\n"}, {"source_code": "\nmain = do\n _ <- getLine\n l <- getLine\n putStrLn $ show $ solve $ map read $ words l\n \n-- solve :: [Int] -> Int\n-- solve gs = gof 4 gs + gof 3 gs + gof_2 + gof_1\n -- where\n -- gof_2 = let r = gof 2 gs in r `quot` 2 + r `rem` 2\n -- gof_1\n -- | gof_3_1 < 0 = 0\n -- | gof_3_2_1 < 0 = 0\n -- | otherwise = gof_3_2_1 `quot` 4 + (if gof_3_2_1 `rem` 4 > 0 then 1 else 0)\n -- where gof_3_1 = gof 1 gs - gof 3 gs\n -- gof_3_2_1 = gof_3_1 - (if odd gof 2 gs then 2 else 0)\n \ncount :: Int -> [Int] -> Int\ncount x xs = length $ filter (==x) xs\n\nsolve :: [Int] -> Int\nsolve xs = n_4 + n_3 + n_2 + n_1\n where n_4 = count 4 xs\n n_3 = count 3 xs\n n_2 = ceiling $ (fromIntegral $ count 2 xs) / 2.0 -- groups of 2 people fit into one more than the # of groupd div 2\n leftover = (count 1 xs) - n_3 - (n_2 `mod` 2 * 2) -- get the number of single person groups left over after filling up the 3-cars and the odd 2 person car\n n_1 = if leftover > 0 then ceiling $ (fromIntegral leftover) / 4.0 else 0\n"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + min b h + rest3 + rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n rest1 = b - min b h\n rest3 = max 0 $ h - min b h\n rest = 1 + (rest1 + 2*r) `div` 4\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "{-\nB. Taxi\n=======\ntime limit per test 3 seconds\nmemory limit per test 256 megabytes\ninput standard input\noutput standard output\n\nAfter the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1\u2009\u2264\u2009si\u2009\u2264\u20094), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?\n\nInput\n------\nThe first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910^ 5) \u2014 the number of groups of schoolchildren. The second line contains a sequence of integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u20094). The integers are separated by a space, si is the number of children in the i-th group.\n\nOutput\n-------\nPrint the single number \u2014 the minimum number of taxis necessary to drive all children to Polycarpus.\n\nSample test(s)\n--------------\ninput\n```\n5\n1 2 4 3 3\n```\noutput\n```\n4\n```\ninput\n```\n8\n2 3 4 4 2 1 3 1\n```\noutput\n```\n5\n```\nNote\nIn the first test we can sort the children into four cars like this:\n\n- the third group (consisting of four children),\n- the fourth group (consisting of three children),\n- the fifth group (consisting of three children),\n- the first and the second group (consisting of one and two children, correspondingly).\nThere are other ways to sort the groups into four cars.\n-}\n\nimport Data.List (sort, group)\n\ncount :: Int -> [Int] -> Int\ncount k xs = length $ filter (== k) xs\n\ntaxiNumber :: [Int] -> Int\ntaxiNumber xs = n4 + n3 + ceiling (fromIntegral n2 / 2) + max 0 (n1 - n3 - 2 * (n2 `mod` 2))\n where [n1, n2, n3, n4] = map (`count` xs) [1,2,3,4]\n\nreader :: String -> [Int]\nreader s = map read $ words second\n where [_, second] = lines s\n\nmain = do\n input <- getContents\n let xs = reader input\n print $ taxiNumber xs\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Fri 19 Oct 2012 06:25:57 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\n\ncountBy ls cond= length $ filter cond ls\n\n\ncount ls k = countBy ls (\\s -> s == k)\n\nkth ls k = head $ drop k ls\nremaining ls k = \n let\n limit = kth (sort ls) k\n in\n countBy ls (\\s -> s >= limit && s > 0)\n\n\ncalcrem1s c3s c1s = \n if c3s >= c1s\n then \n 0\n else\n c1s-c3s\n\nposORZero num =\n if num >= 0\n then\n num\n else\n 0\n\ncalc groups = \n let c2s = count groups 2\n rem1s = posORZero $ (count groups 1) - (count groups 3)\n in\n let \n rem2s = c2s `mod` 2\n in\n let \n finalrem1s =\n if rem2s == 1\n then\n posORZero $ rem1s - 2\n else\n rem1s\n in\n (count groups 4) + (count groups 3) + (ceiling $ fromIntegral(c2s) / 2) + (ceiling $ fromIntegral(finalrem1s) / 4)\n\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInt all\n let (groups, _) = readMany readInt r1\n print groups\n print $ calc groups\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.List (sort)\n\ntaxi :: [Int] -> Int\ntaxi xs = taxiGrouper 0 sorted $ reverse sorted\n\twhere sorted = sort xs\n\ntaxiGrouper :: Int -> [Int] -> [Int] -> Int\ntaxiGrouper groups [x] [y] = groups + 1\ntaxiGrouper groups xall@(x:xs) yall@(y:ys) = taxiGrouper (groups + 1) newxs newys\n\twhere (newxs, newys)\n\t\t| x + y <= 4 = (init xs, init ys)\n\t\t| x == 4 || x > y = (xs, init yall)\n\t\t| otherwise = (init xall, ys)\ntaxiGrouper groups _ _ = groups\n\nmain = do\n\tgetLine\n\tgetLine >>= print . taxi . (map read) . words"}, {"source_code": "import Data.Sequence\nimport Data.Foldable\n\ngetGroups :: IO [Integer]\ngetGroups = do\n _groups <- getLine\n return $ map read (words _groups)\n\ngetAnswer :: [Integer] -> Integer\ngetAnswer groups = quantify $ count groups\n\ncount :: [Integer] -> [Integer]\ncount groups = _count groups [0, 0, 0, 0]\n\n_count :: [Integer] -> [Integer] -> [Integer]\n_count [] counter = counter\n_count (first:rest) counter = _count rest $ toList $ update position ((counter !! position) + 1) $ fromList counter\n where position = fromIntegral first - 1\n\nquantify :: [Integer] -> Integer\nquantify counter = getQuarters + getTriplesAndOnes + getDoubles + getRest\n where ones = head counter\n twos = head $ tail counter\n threes = head $ tail $ tail counter\n fours = last counter\n getQuarters = fours\n getTriplesAndOnes = threes\n onesWithoutThrees = if ones > threes\n then ones - threes\n else 0\n (getDoubles, onesRest) = quantifyDoubles twos onesWithoutThrees\n getRest = onesRest `div` 4 + if onesRest `mod` 4 > 0\n then 1\n else 0\n\nquantifyDoubles :: Integer -> Integer -> (Integer, Integer)\nquantifyDoubles 0 ones = (0, ones)\nquantifyDoubles twos ones = (countedTwos, onesRest)\n where countedTwos = twos `div` 2 + twos `mod` 2\n onesRest = if ones >= 2\n then ones - 1\n else 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n groups <- getGroups\n print $ getAnswer groups"}, {"source_code": "module Main\n where\n\nimport Data.List (sort, group)\n\n\nnumTaxi :: [Int] -> Int\nnumTaxi [o,t,h,f] | o + 2*t + 3*h + 4*f <= 4 = 1\nnumTaxi [o,t,h,f] = f + q + a + abs (b - h) + min b h + ok * rest\n where (q,r) = divMod t 2\n (a,b) = divMod o 4\n ok | r > 0 = 1\n | otherwise = 0\n rest | b - h == 0 = r\n | b + 2*r <= 4 = 1\n | otherwise = 2\n\ncount :: String -> [Int]\ncount = map (pred . length) . group . sort . ([1..4]++) . map read . words\n\nmain :: IO ()\nmain = print . numTaxi . count =<< (getLine >> getLine)"}, {"source_code": "main = do\n irrelevant <- getLine\n input <- getLine\n let list = map read (words input)\n let (a,b,c,d) = (countN list 1, countN list 2, countN list 3, countN list 4)\n let b2 = b `div` 2 \n let c2 = if c>=a then c else c + a `div` 4\n let a2 | a>c && (a-c) `mod` 4 == 3 && odd b = 2\n | a>c && (a-c) `mod` 4 == 3 && even b = 1\n | a>c = 1\n | odd b = 1\n | otherwise = 0\n let answer = d + b2 + c2 + a2\n putStrLn (show answer)\n\ncountN xs n = length (filter (\\x -> x==n) xs)\n"}, {"source_code": "process :: [Int] -> Int\nprocess xs = n4 + n13 + n22 + n112 + n1111 + n01 + n02 + n03\n where\n [n1,n2,n3,n4] = [length (filter (==x) xs) | x <- [1..4]]\n n13 = min n1 n3\n n1' = n1 - n13\n n3' = n3 - n13\n n22 = n2 `div` 2\n n2' = n2 - n22 * 2\n n112 = min (n1' `div` 2) n2'\n n1'' = n1' - n112 * 2\n n2'' = n2' - n112\n n1111 = n1'' `div` 4\n n1''' = n1'' - n1111 * 4\n n01 = if n1''' > 0 then 1 else 0\n n02 = n2''\n n03 = n3'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "taxi :: [Int] -> Int\ntaxi s = t4 + t31 + t3 + t2 + t21 + t1\n where t4 = count 4 s\n t31 = min c3 c1\n t3 = c3 - t31\n t2 = div c2 2\n t21 = rem c2 2\n t1 = max (c1 - t31 - t21 * 2) 0\n c1 = count 1 s\n c2 = count 2 s\n c3 = count 3 s\n count x = length . filter (==x)\n\nmain = do\n getLine\n s <- getLine\n print $ taxi $ map read $ words s\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let nums = map toInt (words line)\n print $ process nums 0\n\nprocess :: [Int] -> Int -> Int\nprocess nums k\n | nums == [] = k\n | filter (==4) nums /= [] = process (filter (/=4) nums) (length (filter (==4) nums) + k)\n | filter (==3) nums /= [] && filter (==1) nums /= [] = process (drop p (filter (==3) nums) ++ drop p (filter (==1) nums) ++ (filter (==2) nums)) (k + p)\n | filter (==2) nums /= [] && (length (filter (==2) nums) == 2) = process (filter (/=2) nums) (k + 1)\n | filter (==2) nums /= [] && (length (filter (==2) nums) > 1) = process (drop l (filter (==2) nums) ++ (filter (==1) nums)++ (filter (==3) nums)) (k + l)\n | filter (==1) nums /= [] && filter (==2) nums /= [] = process (drop z (filter (==2) nums) ++ drop z (filter (==1) nums) ++ (filter (==3) nums)) (k + z)\n | filter (==1) nums /= [] && (length (filter (==1) nums) >= 4) = process (drop 4 (filter (==1) nums)) (k + 1)\n | filter (==1) nums /= [] && (length (filter (==1) nums) > 1) = process (drop f nums) (k + 1)\n | otherwise = process (tail nums) (k + 1)\n where\n p = equalResult (filter (==3) nums) (filter (==1) nums)\n l = (length (filter (==2) nums)) `div` 2\n z = equalResult (filter (==2) nums) (filter (==1) nums)\n f = (length (filter (==1) nums))\n\nequalResult :: [Int] -> [Int] -> Int\nequalResult a b\n | a < b = length a\n | otherwise = length b\n\ntoInt :: String -> Int\ntoInt = read"}], "src_uid": "371100da1b044ad500ac4e1c09fa8dcb"} {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as BS\n\ncountDivisibilty :: Int -> Int -> Int\ncountDivisibilty b a = if a `mod` b == 0\n then 1 + countDivisibilty b (a `div` b)\n else 0\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve nums = let divCounts = map (countDivisibilty 2) nums in\n let evenCount = length $ filter (>0) divCounts in\n if minimum divCounts == 0\n then evenCount\n else (minimum divCounts) + evenCount - 1\n\nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\n\\t\")\n\nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\n\nmainLoop 0 = return ()\nmainLoop t = do _ <- BS.getLine\n secondLine <- BS.getLine\n let a = readInts secondLine\n print (solve a)\n mainLoop (t - 1)\n\nmain = do t <- (readLn :: IO Int)\n mainLoop t\n", "positive_code": [{"source_code": "-- boilerplate {{{1\n-- vim: foldmethod=marker\n-- pragmas {{{2\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Main where -- {{{2\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bifunctor\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\nimport Data.Foldable hiding ( sum, product )\nimport Data.Function\nimport Data.Functor\nimport Data.List hiding ( sum, product )\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Min(..), Max(..) )\nimport Data.Traversable\nimport Data.Tuple\nimport Debug.Trace\nimport Prelude hiding ( sum, product )\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as IS\nimport qualified Data.Map as LM\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n-- recursion schemes {{{2\ndata Tree a b = Tree a (Forest a b) deriving (Eq,Ord,Show,Functor)\ntype Forest a b = [b]\nderiving instance Foldable (Tree a)\nderiving instance Traversable (Tree a)\n\nhylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b\nhylo f g = h where h = f . fmap h . g\n\nnewtype Term f = In { out :: f (Term f) }\ntype Algebra f a = f a -> a\ntype Coalgebra f a = a -> f a\n\ncata :: Functor f => Algebra f a -> Term f -> a\ncata f = c where c = f . fmap c . out\n\nana :: Functor f => Coalgebra f a -> a -> Term f\nana g = a where a = In . fmap a . g\n\ntreeCoalgebra :: -- {{{2\n Int -> [[Int]] -> (Int -> a) -> \n Coalgebra (Tree a) (Int,Int)\ntreeCoalgebra n uvs f = coalg\n where\n coalg (curr,prev) = Tree (f curr) $ map (,curr) $ lookup curr prev\n lookup curr prev = IS.elems $ IS.delete prev $ uvary ! curr\n uvary = runSTArray $ do\n ary <- newArray (1,n) IS.empty\n let insert u 1 = pure ()\n insert u v = readArray ary u >>= writeArray ary u . IS.insert v\n for_ uvs $ \\[u,v] -> insert u v >> insert v u\n pure ary\n\ndata V2 a = V2 !a !a -- {{{2\n deriving ( Eq, Ord, Show )\ninstance Num a => Num (V2 a) where\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n (*) = liftA2 (*)\n abs = fmap abs\n negate = fmap negate\n signum = fmap signum\n fromInteger = pure . fromInteger\ninstance Functor V2 where\n fmap f (V2 a b) = V2 (f a) (f b)\n a <$ _ = V2 a a\ninstance Applicative V2 where\n pure a = V2 a a\n V2 a b <*> V2 d e = V2 (a d) (b e)\ninstance Monad V2 where\n V2 a b >>= f = V2 a' b' where\n V2 a' _ = f a\n V2 _ b' = f b\ninstance Foldable V2 where\n foldMap f (V2 a b) = f a `mappend` f b\n null _ = False\n length _ = 2\ninstance Traversable V2 where\n traverse f (V2 a b) = V2 <$> f a <*> f b\n\ndata V3 a = V3 !a !a !a -- {{{2\n deriving ( Eq, Ord, Show )\ninstance Num a => Num (V3 a) where\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n (*) = liftA2 (*)\n abs = fmap abs\n negate = fmap negate\n signum = fmap signum\n fromInteger = pure . fromInteger\ninstance Functor V3 where\n fmap f (V3 a b c) = V3 (f a) (f b) (f c)\n a <$ _ = V3 a a a\ninstance Applicative V3 where\n pure a = V3 a a a\n V3 a b c <*> V3 d e f = V3 (a d) (b e) (c f)\ninstance Monad V3 where\n V3 a b c >>= f = V3 a' b' c' where\n V3 a' _ _ = f a\n V3 _ b' _ = f b\n V3 _ _ c' = f c\ninstance Foldable V3 where\n foldMap f (V3 a b c) = f a `mappend` f b `mappend` f c\n null _ = False\n length _ = 3\ninstance Traversable V3 where\n traverse f (V3 a b c) = V3 <$> f a <*> f b <*> f c\n\n-- utilites {{{2\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\ngetInt = readInt <$> C.getLine\ngetInts = map readInt . C.words <$> C.getLine\nynq = putStrLn . bool \"No\" \"Yes\"\nynQ = putStrLn . bool \"NO\" \"YES\"\nmodulus = 10^9 + 7 :: Int\nmod' x = rem x modulus\nmprint :: Show a => String -> Maybe a -> IO ()\nmprint s = maybe (putStrLn s) print\ntri n = quot (n * n + n) 2\nifM :: Monad m => m Bool -> m a -> m a -> m a\nifM b t e = b >>= bool e t\nwhenM :: Monad m => m Bool -> m () -> m ()\nwhenM b t = ifM b t (pure ())\ngcount g@(x:_) = (x, length g)\nsum t = foldl' (+) 0 t\nproduct t = foldl' (*) 1 t\n\n-- }}}1\n\nmain = getInt >>= flip replicateM_ docase\n-- main = docase\n\ndocase = do\n [n] <- getInts\n aa <- getInts\n print $ solve n aa\n\nsolve a nn = go no ne\n where\n (oo,ee) = partition odd nn\n no = length oo\n ne = length ee\n go no ne\n | no >= ne = ne\n | no > 0 = no + go (no + no) (ne - no)\n | otherwise = nd + go 1 (ne - 1)\n where\n nd:_ =\n [ b\n | b <- [1..]\n , e <- ee\n , testBit e b ]\n"}], "negative_code": [], "src_uid": "1b9a204dd08d61766391a3b4d2429df2"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : r1 : r2 : _ <- readData\n xs <- take n <$> readData\n let cities = do\n (i, x) <- zip [1.. ] xs\n if i < r1 then [(i, x)] else [(i + 1, x)]\n table <- newArray (1, n) maxBound :: IO (IOArray Int Int)\n let search from now = do\n to <- readArray table now\n writeArray table now from\n if to == r1\n then writeArray table r1 now\n else search now to\n F.for_ cities $ \\(i, x) -> do\n writeArray table i x\n search r2 r2\n for_ 1 n $ \\i -> do\n when (i /= r2) $ do\n x <- readArray table i\n printf \"%d \" x\n putChar '\\n'\n -- getAssocs table >>= print . show\n{-\n9 2 9\n5 6 2 2 2 4 6 8\n-}\n", "positive_code": [{"source_code": "import Array\nimport List\nmain = interact (ans)\nans theInput = unwords $ map show $ answer new2old where\n theLines = lines theInput\n [[n,r1,r2],p] = map ( map (read::String->Int)) $ map words $ lines theInput\n p1 = array (1,n) (zip [1..n] ((take (r1-1) p) ++ [r1] ++ (drop (r1-1) p)))\n from (x,y) = (p1!x,x)\n new2old = (0,0):(sort $ takeWhile ((/=r1).snd) (iterate from (r2,r2)))\n answer ((x,y):(z,w):xs) = [p1!i|i<-[x+1..z-1]] ++ (if z==w then [] else [w]) ++ answer ((z,w):xs)\n answer [(x,y)] = [p1!i|i<-[x+1..n]]\n"}, {"source_code": "import Array\nimport List\nmain = interact (ans)\nans theInput = unwords $ map show $ answer new2old where\n [[n,r1,r2],p] = map ( map (read::String->Int)) $ map words $ lines theInput\n p1 = array (1,n) (zip [1..n] ((take (r1-1) p) ++ [r1] ++ (drop (r1-1) p)))\n from (x,y) = (p1!x,x)\n new2old = (0,0):(sort $ takeWhile ((/=r1).snd) (iterate from (r2,r2)))\n answer ((x,y):(z,w):xs) = [p1!i|i<-[x+1..z-1]] ++ (if z==w then [] else [w]) ++ answer ((z,w):xs)\n answer [(x,y)] = [p1!i|i<-[x+1..n]]\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : r1 : r2 : _ <- readData\n xs <- take n <$> readData\n let cities = do\n (i, x) <- zip [1.. ] xs\n if i < r1 then [(i, x)] else [(i + 1, x)]\n table <- newArray (1, n) maxBound :: IO (IOArray Int Int)\n let search from = do\n to <- readArray table from\n if to == r1\n then writeArray table r1 from\n else search to\n F.for_ cities $ \\(i, x) -> do\n writeArray table i x\n search r2\n for_ 1 n $ \\i -> do\n when (i /= r2) $ do\n x <- readArray table i\n printf \"%d \" x\n putChar '\\n'\n -- getAssocs table >>= print . show\n\n"}], "src_uid": "2c51fa9ddc72caaebb29dd65a2db030e"} {"source_code": "module Main where\n\nimport Data.List (sort)\nimport Control.Monad (replicateM_)\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn _ [] = [[]]\nsplitOn c (x:xs) \n | c == x = [] : m\n | otherwise = (x:h) : t \n where m@(h:t) = splitOn c xs \n\n-- \"12 3\"\n\n\nreadArray :: IO [Int]\nreadArray = getLine >>= (return . map read . splitOn ' ')\n\na :: IO ()\na = do\n [n, x] <- readArray\n hs <- readArray\n let test = all (>= x) $ uncurry (zipWith $ flip (-)) $ splitAt n $ sort hs\n putStrLn (if test then \"YES\" else \"NO\")\n\nmain :: IO ()\nmain = do\n [n] <- readArray\n replicateM_ n a\n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Tuple\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[n,x], hs] <- replicateM 2 ri\r\n return (n,x,hs)\r\n mapM_ (putStrLn . showYN . solve) tcs\r\n\r\nshowYN False = \"NO\"\r\nshowYN True = \"YES\"\r\n\r\nsolve (n,x,hs) = x <= maxX\r\n where\r\n maxX = minimum . map (uncurry (-)) . uncurry zip . swap . splitAt n . L.sort $ hs\r\n"}, {"source_code": "{-# LANGUAGE\n ScopedTypeVariables,\n BangPatterns,\n FlexibleContexts,\n TypeApplications,\n MultiWayIf #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nmain = do\n [!t] <- readInts\n replicateM_ t $ do\n [!n, !x] <- readInts\n (f,b) <- splitAt n . sort <$> readInts\n putStrLn $ if all (>= x) $ zipWith (-) b f\n then \"YES\"\n else \"NO\"\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmodifyArray :: (MArray a e m , Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr i f = readArray arr i >>= writeArray arr i . f\n"}], "negative_code": [], "src_uid": "52769cd7b3b0d63a7259a5d0754c4803"} {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int (Int64)\nimport qualified Data.Set as S\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n processing n $ S.fromList [(0, i) | i <- [1..size]]\n where\n processing 0 _ = return ()\n processing i q = do\n (s:m:_) <- readLine\n let ((k, v), q') = fromJust $ S.minView q\n e = max s k + m\n print e\n processing (i-1) $ S.insert (e, v) q'\n", "positive_code": [{"source_code": "{-\nCredits to solution goes to watashi\nhttp://codeforces.com/profile/watashi\n-}\n\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int (Int64)\nimport qualified Data.Set as S\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n processing n $ S.fromList [(0 :: Int64, i) | i <- [1..size]]\n where\n processing 0 _ = return ()\n processing i q = do\n (s:m:_) <- readLine\n let ((k, v), q') = fromJust $ S.minView q\n e = max s k + m\n print e\n processing (i-1) $ S.insert (e, v) q'\n"}, {"source_code": "import Control.Applicative\nimport Data.Int (Int64)\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readInts\n gao n $ S.fromList [(0 :: Int64, i) | i <- [1..k]]\n where\n readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n gao 0 _ = return ()\n gao i q = do\n (s:m:_) <- map fromIntegral <$> readInts\n let ((k, v), q') = fromJust $ S.minView q\n e = max s k + m\n print e\n gao (i-1) $ S.insert (e, v) q'\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport qualified Data.Map.Strict as M\nimport Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Tuple (swap)\n\nreadInt = fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nprocess :: Int -> [(Integer, Integer)] -> [Integer]\nprocess servers videos =\n fmap snd . sortBy (compare `on` fst) . folder (M.empty, [], servers, 0) $ zip [0..] videos\n where\n folder (m, processed, _, _) [] =\n concatMap (\\(y, xs) -> map (\\x -> (x, y)) xs) (M.toList m) ++ processed\n folder (m, processed, 0, _) otherVideos =\n let ((time, deletedIndices), newM) = M.deleteFindMin m\n in folder (newM, map (\\x -> (x, time)) deletedIndices ++ processed, length deletedIndices, time) otherVideos\n folder (m, processed, svs, time) ((index, (start, size)):otherVideos) =\n folder (M.insertWith (++) ((max start time) + size) [index] m, processed, svs - 1, time) otherVideos\n\nmain = do\n [_, servers] <- readLine \n videos <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . unlines . map show $ process (fromIntegral servers) videos\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int (Int64)\nimport qualified Data.Set as S\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n processing n $ S.fromList [(0 :: Int64, i) | i <- [1..size]]\n where\n processing 0 _ = return ()\n processing i q = do\n (s:m:_) <- readLine\n let ((k, v), q') = fromJust $ S.minView q\n e = max s k + m\n print e\n processing (i-1) $ S.insert (e, v) q'\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Integer Integer\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (1, l) $ replicate (fromInteger l) (0, 0) :: Array Integer Event\n in elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n if (elId == 57908 && elExecutedAt == 686412246) then do writeArray result (mm M.! elId) (elId, 686389862)\n else do writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..]\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (0, l) $ (:) (0, 0) $ replicate (fromInteger $ l) (0, 0) :: Array Integer Event\n in tail $ elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Integer Integer\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (0, l) $ (:) (0, 0) $ replicate (fromInteger $ l) (0, 0) :: Array Integer Event\n in tail $ elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = toInteger . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- replicateM (fromInteger n) readLine\n mapM_ (B.putStrLn . B.pack . show . snd) $ sortBy (comparing fst) $ processing events size\n\n\nprocessing :: [[Integer]] -> Integer -> [Event]\nprocessing events size =\n let queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (1, toInteger $ length events) [(0, 0), (0, 0)]:: Array Integer Event\n in elems $ procWithMutation events queue result\n\n\nprocWithMutation :: [[Integer]] -> Queue -> Queue-> Queue\nprocWithMutation events queue result = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start:time:_) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n writeArray result elId (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n q' <- freeze q\n forM_ (elems q') $ \\(elId, elExecutedAt) -> do writeArray result elId (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Integer Integer\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (1, l) $ replicate (fromInteger l) (0, 0) :: Array Integer Event\n in elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n if (elId /= 57908 && elExecutedAt /= 686412246) then do writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do writeArray result (mm M.! elId) (elId, 686389862)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Integer Integer\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (1, l) $ replicate (fromInteger l) (0, 0) :: Array Integer Event\n in elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n if (elExecutedAt == 686412246) then do writeArray result (mm M.! elId) (elId, 686389862)\n else do writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n processing n $ S.fromList [(0 :: Int, i) | i <- [1..size]]\n where\n processing 0 _ = return ()\n processing i q = do\n (s:m:_) <- readLine\n let ((k, v), q') = fromJust $ S.minView q\n e = max s k + m\n print e\n processing (i-1) $ S.insert (e, v) q'\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Integer Integer\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (1, l) $ replicate (fromInteger l) (0, 0) :: Array Integer Event\n in elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Int (Int64)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Int64, Int64)\ntype Queue = Array Int64 Event\ntype QueueM s = STArray s Int64 Event\n\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s :: Int64,f :: Int64)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1 :: Int64 ..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\nprocessing :: [Event] -> Int64 -> [Event]\nprocessing events size =\n let l = length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Int64 Int64\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromIntegral size) (0, 0) :: Array Int64 Event\n result = listArray (1 :: Int64, fromIntegral l) $ replicate l (0, 0) :: Array Int64 Event\n in elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Int64 Int64) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Int64 Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Int64 Event -> Int64 -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Int64 -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\n\n{-\nQueue -> Array 0..N elements, where N is number of available queue slots.\ninitialized with all elements to be (0,0)\n0'th element of an array always represents current Queue length\nin a form of (length, _)\n\nLength increased on Insert operations\nLength decresased on Pop operations\n-}\n\n-- 0'th array element always holds current length info.\nisFull :: Queue -> Bool\nisFull xs = (==) l $ qLength xs\n where l = pred $ toInteger $ length $ elems xs\n\nqLength :: Queue -> Integer\nqLength xs = fst $ xs ! 0\n\ninsert :: Queue -> Event -> Queue\ninsert queue e = runST $ do\n q <- thaw queue\n (l, _) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, 0)\n fixIns q (succ l)\n res <- freeze q\n return res\n\nfixIns :: STArray s Integer Event -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `mod` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n\npop :: Queue -> (Event, Queue)\npop queue = runST $ do\n q <- thaw queue\n (l, _) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, 0)\n fixPop q 1\n res <- freeze q\n return (val, res)\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\nprocessing :: [[Integer]] -> Integer -> [Event]\nprocessing events size =\n let queue = listArray (0, size) $ replicate (fromInteger $ succ size) (0, 0) :: Array Integer Event\n (queue', exec) = foldl procEvent (queue, []) events\n in foldl (\\ex ev -> ev:ex) exec $ tail $ elems queue'\n --in exec\n\nprocEvent :: (Queue, [Event]) -> [Integer] -> (Queue, [Event])\nprocEvent (queue, result) (start:time:_)\n | isFull queue =\n let ((elId, elExecutedAt), q') = pop queue\n q'' = insert q' (start, (max elExecutedAt start) + time)\n in (q'', (elId, elExecutedAt):result)\n | otherwise = (insert queue (start, start + time), result)\n\nreadInt = toInteger . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- replicateM (fromInteger n) readLine\n mapM_ (B.putStrLn . B.pack . show) $ map snd $ sortBy (comparing fst) $ processing events size\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\nimport Text.Printf (printf)\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = toInteger . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- replicateM (fromInteger n) readLine\n mapM_ (printf . show . snd) $ sortBy (comparing fst) $ processing events size\n\n\nprocessing :: [[Integer]] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (0, l) $ (:) (0, l) $ replicate (fromInteger $ l) (0, 0) :: Array Integer Event\n in tail $ elems $ procWithMutation events queue result\n\n\nprocWithMutation :: [[Integer]] -> Queue -> Queue-> Queue\nprocWithMutation events queue result = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start:time:_) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n (curInd, l) <- readArray result 0\n writeArray result (succ curInd) (elId, elExecutedAt)\n writeArray result 0 (succ curInd, l)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n (curInd, l) <- readArray result 0\n writeArray result (succ curInd) (elId, elExecutedAt)\n writeArray result 0 (succ curInd, l)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int (Int32)\nimport qualified Data.Set as S\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n processing n $ S.fromList [(0 :: Int32, i) | i <- [1..size]]\n where\n processing 0 _ = return ()\n processing i q = do\n (s:m:_) <- readLine\n let ((k, v), q') = fromJust $ S.minView q\n e = max s k + m\n print e\n processing (i-1) $ S.insert (e, v) q'\n"}, {"source_code": "module Main where\nimport Data.Array\nimport Control.Monad (mapM_, replicateM, forM, forM_)\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n-- import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\nimport Data.Ord (comparing)\nimport Data.STRef (newSTRef, modifySTRef, readSTRef)\nimport qualified Data.Map.Strict as M\n\ntype Event = (Integer, Integer)\ntype Queue = Array Integer Event\ntype QueueM s = STArray s Integer Event\n\nreadInt = fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, size] <- readLine\n events <- B.getContents >>=\n return .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n mapM_ (B.putStrLn . B.pack . show . snd) $ processing events size\n\nprocessing :: [Event] -> Integer -> [Event]\nprocessing events size =\n let l = toInteger $ length events\n mm = M.fromList $ zip (map fst events) [1..] :: M.Map Integer Integer\n queue = listArray (0, size) $ (:) (0, size) $ replicate (fromInteger $ size) (0, 0) :: Array Integer Event\n result = listArray (1, l) $ replicate (fromInteger l) (0, 0) :: Array Integer Event\n in elems $ procWithMutation events queue result mm\n\nprocWithMutation :: [Event] -> Queue -> Queue -> (M.Map Integer Integer) -> Queue\nprocWithMutation events queue result mm = runST $ do\n q <- thaw queue :: ST s (QueueM s)\n result <- thaw result :: ST s (QueueM s)\n forM_ events $ \\(start, time) -> do\n (l, maxL) <- readArray q 0\n if (l == maxL) then do\n (elId, elExecutedAt) <- pop q\n insert q (start, (max elExecutedAt start) + time)\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n else do\n insert q (start, start + time)\n (l, maxL) <- readArray q 0\n forM_ [1 .. l] $ \\el -> do\n (elId, elExecutedAt) <- readArray q el\n writeArray result (mm M.! elId) (elId, elExecutedAt)\n res <- freeze result\n return res\n\npop :: STArray s Integer Event -> ST s Event\npop q = do\n (l, maxL) <- readArray q 0\n -- handle l == 0\n val <- readArray q 1\n end <- readArray q l\n writeArray q 1 end\n writeArray q l (0, 0)\n writeArray q 0 (pred l, maxL)\n fixPop q 1\n return val\n\nfixPop :: STArray s Integer Event -> Integer -> ST s ()\nfixPop q i = do\n (l, _) <- readArray q 0\n let lId = min l $ 2 * i\n rId = min l $ succ lId\n (elId, elPriority) <- readArray q i\n (leftId, lPriority) <- readArray q lId\n (rightId, rPriority) <- readArray q rId\n if (leftId == 0) then return ()\n else if (leftId /= 0 && rightId == 0 && lPriority < elPriority) then do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else if (leftId /= 0 && rightId /= 0 && (lPriority < elPriority || rPriority < elPriority)) then\n if (lPriority > rPriority) then do\n writeArray q i (rightId, rPriority)\n writeArray q rId (elId, elPriority)\n fixPop q rId\n else do\n writeArray q i (leftId, lPriority)\n writeArray q lId (elId, elPriority)\n fixPop q lId\n else return ()\n\ninsert :: QueueM s -> Event -> ST s ()\ninsert q e = do\n (l, maxL) <- readArray q 0\n writeArray q (succ l) e\n writeArray q 0 (succ l, maxL)\n fixIns q (succ l)\n\nfixIns :: QueueM s -> Integer -> ST s ()\nfixIns queue 1 = do return ()\nfixIns queue i = do\n let i' = i `div` 2\n (parentId, parentPriority) <- readArray queue i'\n (elId, elPriority) <- readArray queue i\n if (elPriority < parentPriority) then do\n writeArray queue i (parentId, parentPriority)\n writeArray queue i' (elId, elPriority)\n fixIns queue i'\n else return ()\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport qualified Data.Map.Strict as M\nimport Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Tuple (swap)\n\nreadInt = fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nprocess :: Int -> [(Integer, Integer)] -> [Integer]\nprocess servers videos =\n fmap snd . sortBy (compare `on` fst) . combine . foldl' folder (init, []) . zip [servers..] $ drop servers videos\n where init = M.fromList . flip zip [0..] . map (uncurry (+)) $ take servers videos\n folder (m, processed) (index, (start, size)) =\n let ((time, deletedIndex), newM) = M.deleteFindMin m\n in (M.insert ((max start time) + size) index newM, (deletedIndex, time):processed)\n combine (m, processed) = map swap (M.toList m) ++ processed\n\nmain = do\n [_, servers] <- readLine \n videos <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . unlines . map show $ process (fromIntegral servers) videos\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport qualified Data.Map.Strict as M\nimport Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Tuple (swap)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nprocess servers videos =\n fmap snd . sortBy (compare `on` fst) . combine . foldl' folder (init, []) . zip [servers..] $ drop servers videos\n where init = M.fromList . flip zip [0..] . map (uncurry (+)) $ take servers videos\n folder (m, processed) (index, (start, size)) =\n let ((time, deletedIndex), newM) = M.deleteFindMin m\n in (M.insert ((max start time) + size) index newM, (deletedIndex, time):processed)\n combine (m, processed) = map swap (M.toList m) ++ processed\n\nmain = do\n [_, servers] <- readLine \n videos <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . unlines . map show $ process servers videos\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport qualified Data.IntMap as M\nimport Data.List (sortBy, foldl')\nimport Data.Function (on)\nimport Data.Tuple (swap)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nprocess :: Int -> [(Int, Int)] -> [Int]\nprocess servers videos =\n fmap snd . sortBy (compare `on` fst) . combine . foldl' folder (init, []) . zip [servers..] $ drop servers videos\n where init = M.fromList . flip zip [0..] . map (uncurry (+)) $ take servers videos\n folder (m, processed) (index, (start, size)) =\n let ((time, deletedIndex), newM) = M.deleteFindMin m\n in (M.insert ((max start time) + size) index newM, (deletedIndex, time):processed)\n combine (m, processed) = map swap (M.toList m) ++ processed\n\nmain = do\n [_, servers] <- readLine \n videos <- B.getContents >>=\n return .\n sortBy (compare `on` fst) .\n map (\\(_,s,f) -> (s,f)) .\n filter (\\(x,_,_) -> odd x) .\n (\\xs -> zip3 [1..] xs (tail xs)) .\n map readInt .\n B.words\n B.putStrLn . B.pack . unlines . map show $ process servers videos\n"}], "src_uid": "754f1bbae2e6ff4992b6f56bb9c96efe"} {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Data.Int\n\ndebug x = trace (\"# \" ++ show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\ncar = head\ncdr = tail\ncadr = head . tail\n\n--readInt = fst.fromJust.B.readInt\nreadIntList = return . map read . words :: String -> IO [Int]\ntoDigit n = chr (48 + n)\nchr2num c = ord c - ord '0'\n\nmain = do\n ls <- getContents ||> lines\n -- n <- car ls |> readIO :: IO Int\n [n,m] <- car ls |> words |> map read |> return :: IO [Int]\n rs <- cdr ls |> take m |> map (\\l -> words l |> map read |> (\\[a,b,c] -> (a,b,c) ) :: (Int,Int,Int)) |> return :: IO [(Int,Int,Int)]\n\n let s = take n $ repeat 0\n cs = loop rs [] in\n [1 .. n] |> map (\\idx -> loop2 idx cs) |> sum |> print\n\nloop :: [(Int,Int,Int)] -> [(Int,Int)] -> [(Int,Int)]\nloop [] ac = ac\nloop ((a,b,c):ls) ac = loop ls ((a,-c) : (b, c) : ac)\n\nloop2 :: Int -> [(Int,Int)] -> Int\nloop2 idx ls =\n ls |> filter (\\(i,c) -> i == idx) |> foldl (\\ac (_,c) -> ac + c) 0\n |> \\x -> if x > 0 then x else 0\n\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Map (fromListWith, toList)\ndata Debt = Debt { debtor ::Int, creditor ::Int, amount ::Int } deriving Show\nreadInts = do \n\tline <- getLine\n\treturn ( map read (words line) :: [Int] )\nreadDebt = do\n\tints <- readInts\n\tcase ints of [debtor, creditor, amount] -> return ( Debt debtor creditor amount)\nreadDebts k = ( sequence $ replicate k readDebt ) >>= dualize\n\twhere dualize xs = return $ foldl' ( \\acc x-> dualDebt x ++ acc ) [] xs\n\ndualDebt (Debt debtor creditor amount) = [Debt debtor creditor amount, Debt creditor debtor (-amount)] \nsumDebts debts = fromListWith (+) ( map (\\d -> (debtor d, amount d)) debts )\nresult debts = div ( foldl' (\\ z (k,d)-> ( (abs d ) + z )) 0 ( toList $ sumDebts debts ) ) 2\n\n\nmain = do \n\t[n,m] <- readInts\n\tdebts <- readDebts m\n\n\tprint $ result debts\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\nimport Data.Int\n\ndebug x = trace (\"# \" ++ show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) mx f = mx >>= (return . f); infixl 1 ||>\nref = (!!)\ncar = head\ncdr = tail\ncadr = head . tail\n\n--readInt = fst.fromJust.B.readInt\nreadIntList = return . map read . words :: String -> IO [Int]\ntoDigit n = chr (48 + n)\nchr2num c = ord c - ord '0'\n\nmain = do\n ls <- getContents ||> lines\n -- n <- car ls |> readIO :: IO Int\n [n,m] <- car ls |> words |> map read |> return :: IO [Int]\n rs <- cdr ls |> take m |> map (\\l -> words l |> map read |> (\\[a,b,c] -> if a < b then (a,b,c) else (b,a,c)) :: (Int,Int,Int)) |> return :: IO [(Int,Int,Int)]\n\n let s = take n $ repeat 0\n cs = loop rs [] in\n [1 .. n] |> map (\\idx -> loop2 idx cs) |> sum |> print\n\nloop :: [(Int,Int,Int)] -> [(Int,Int)] -> [(Int,Int)]\nloop [] ac = ac\nloop ((a,b,c):ls) ac = loop ls ((a,-c) : (b, c) : ac)\n\nloop2 :: Int -> [(Int,Int)] -> Int\nloop2 idx ls =\n ls |> filter (\\(i,c) -> i == idx) |> foldl (\\ac (_,c) -> ac + c) 0\n |> \\x -> if x > 0 then x else 0\n\n"}], "src_uid": "b53c3e55834db8184d8caf4630aaa573"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\n\nimport Data.Char\nimport Data.List\n\nmain :: IO ()\nmain=getLine>>=putStrLn.concatMap show.solve.map digitToInt\n\nsolve :: [Int] -> [Int]\nsolve (span (<2) -> (xs, [])) = sort xs\nsolve (span (<2) -> (xs, ys)) = sort xs ++ filter (==1) ys ++ filter(/=1) ys\n", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ndoit s =\n case (findIndex (=='2') s) of\n Nothing -> sort s\n (Just k) ->\n sort ((take k s) ++ (filter (=='1') $ drop k s)) ++ (filter (/='1') $ drop k s)\n\nsolve::String -> String\nsolve ss =\n let s = head $ words ss in\n let r = doit s in\n r ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}], "negative_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ndoit s =\n case (findIndex (=='2') s) of\n Nothing -> sort s\n (Just k) ->\n sort ((take k s) ++ (filter (/='0') $ drop k s)) ++ (filter (=='0') $ drop k s)\n\nsolve::String -> String\nsolve ss =\n let s = head $ words ss in\n let r = doit s in\n r ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\n\nimport Data.Char\nimport Data.List\n\nmain :: IO ()\nmain=getLine>>=putStrLn.concatMap show.solve.map digitToInt\n\nsolve :: [Int] -> [Int]\nsolve = go01\n where\n go01 [] = []\n go01 (span (<2) -> (xs, ys)) = sort xs ++ go12 ys\n go12 [] = []\n go12 (span (>0) -> (xs, ys)) = sort xs ++ go01 ys"}], "src_uid": "91cefa6793e77b3e4f4896616a164ff2"} {"source_code": "import Data.List\nimport Data.Bits\nimport Data.Array\nanswer ll lr aa l r m n | l == n = 0\n | otherwise = max num next\n where num=((.|.) ((.|.) (ll ! l) (m*(aa ! l))) (lr ! r))\n next = answer ll lr aa (l+1) (r+1) m n\nmain = do\n w0 <- getLine\n let [n,k,x0] = [read n::Int|n <-(words w0)]\n let x = (fromIntegral x0)::Integer\n w1 <- getLine\n let a = [read n::Integer|n <-(words w1)]\n let m = (iterate (*x) (1::Integer) ) !! k\n let l = listArray (0,n) $ scanl (.|.) (0::Integer) a\n let r = listArray (0,n) $ scanr (.|.) (0::Integer) a\n let aa = listArray (0,n-1) a\n putStrLn $ show $ answer l r aa 0 1 m n\n \n", "positive_code": [{"source_code": "-- Codeforces 578B\n\nimport Data.Bits ((.|.))\nimport Data.Foldable (foldl', foldr')\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BC\n\n-- Hint multiply x^k to a_i to get the hightest bit 1 to make result to be to greatest. \n\n-- Note: use Data.ByteString.Char8.ReadInt to accelerate IO action.\n-- User scanl1 and scanr1 to record the intermediate list to reduce time and memory space usage.\n\nmain :: IO ()\nmain = BC.getContents >>= print . solve . map (toInteger . fst . fromJust . BC.readInt) . BC.words\n\nsolve :: [Integer] -> Integer\nsolve (n:k:x:xs) = maximum $ zipWith3 or xs prefix suffix where\n or a p s = a * b .|. p .|. s where b = x ^ k\n prefix = 0:scanl1 (.|.) xs\n suffix = tail $ scanr1 (.|.) xs ++ [0]\n"}, {"source_code": "import Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64)\nimport Data.Bits ((.|.))\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: Int64 -> [Int64] -> Int64\nsolve a xs = maximum $ zipWith (\\x y -> (x * a) .|. y) xs ys\n where ys = zipWith (.|.) (scanl (.|.) 0 xs) . tail $ scanr (.|.) 0 xs\n\nmain = do\n [_, k, x] <- parse <$> getLine\n getLine >>= print . solve (fromIntegral $ x^k) . map fromIntegral . parse\n"}, {"source_code": "import Data.Bits\nimport Data.List\nimport Data.Int\nmain :: IO()\nmain = do\n [n,k,x] <- fmap ((map read) . words) getLine :: IO [Int64]\n a <- fmap ((map read) . words) getLine :: IO [Int64]\n let m = (x^k)\n sl = scanl (.|.) 0 a\n sr = scanr (.|.) 0 a\n ans = foldl' (\\acc (q,w,e) -> max acc (q.|.w.|.e)) (0::Int64) $ zip3 sl (map (m*) a) (tail sr)\n --print [sl,sr]\n --print $ zip3 sl (map (m*) a) sr\n print ans\n"}, {"source_code": "import Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\nsolve :: [Integer] -> Integer -> Integer -> Integer\nsolve as k x = maximum (zipWith3 or as prefix suffix)\n where or a p s = a * (x ^ k) .|. p .|. s\n prefix = 0:scanl1 (.|.) as\n suffix = (drop 1 (scanr1 (.|.) as)) ++ [0]\n\nmain = do\n line <- C.getLine\n let (n:k:x:[]) = toInts (C.words line)\n num <- C.getLine\n let numbers = (take (fromInteger n ) . toInts . C.words) num\n print (solve numbers k x)\n where toInts = map (toInteger . fst . fromJust . C.readInt)\n"}, {"source_code": "import Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\n_solve :: (Bits a, Ord a, Num a, Integral b) => [a] -> b -> a -> a\n_solve as k x = maximum (zipWith3 or as prefix suffix)\n where or a p s = a * kx .|. p .|. s\n kx = x ^ k\n prefix = 0:scanl1 (.|.) as\n suffix = (drop 1 (scanr1 (.|.) as)) ++ [0]\n{-\n3 1 2\n1 1 1\n3\n\n4 2 3\n1 2 4 8\n-}\nmain = do\n line <- fmap C.words C.getLine\n let (n:k:x:[]) = toInts line\n nums <- C.getLine\n let numbers = take (fromInteger n) (toInts (C.words nums))\n putStrLn (show (_solve numbers k x))\n where toInts = map (toInteger . fst . fromJust . C.readInt)\n"}, {"source_code": "-- Codeforces 578B\n\nimport Data.Bits ((.|.))\nimport Data.Foldable (foldl', foldr')\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BC\n\n-- Hint multiply x^k to a_i to get the hightest bit 1 to make result to be to greatest. \n\n-- Note: use Data.ByteString.Char8.ReadInt to accelerate IO action.\n-- Use scanl1 and scanr1 to record the intermediate list to reduce time and memory space usage.\n\nmain :: IO ()\nmain = BC.getContents >>= print . solve . map (toInteger . fst . fromJust . BC.readInt) . BC.words\n\nsolve :: [Integer] -> Integer\nsolve (n:k:x:xs) = maximum $ zipWith3 or xs prefix suffix where\n or a p s = a * b .|. p .|. s where b = x ^ k\n prefix = 0:scanl1 (.|.) xs\n suffix = tail $ scanr1 (.|.) xs ++ [0]\n"}], "negative_code": [{"source_code": "import Data.Bits\nimport Data.List\nmain :: IO()\nmain = do\n [n,k,x] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = (x^k)\n sl = tail $ scanl (.|.) 0 a\n sr = init $ scanr (.|.) 0 a\n ans = foldl' (\\acc (q,w,e) -> max acc (q.|.w.|.e)) 0 $ zip3 sl (map (m*) a) sr\n print ans\n"}, {"source_code": "import Data.Bits\nimport Data.List\nmain :: IO()\nmain = do\n [n,k,x] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = (x^k)\n sl = scanl (.|.) 0 a\n sr = scanr (.|.) 0 a\n ans = foldl' (\\acc (q,w,e) -> max acc (q.|.w.|.e)) 0 $ zip3 sl (map (m*) a) sr\n print ans"}, {"source_code": "import Data.Bits\nimport Data.List\nmain :: IO()\nmain = do\n [n,k,x] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = maximum a\n p = m*(x^k) :: Int\n ans = foldl' (.|.) p (a\\\\[m])\n print ans"}, {"source_code": "import Data.Bits\nimport Data.List\nmain :: IO()\nmain = do\n [n,k,x] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = (x^k)\n sl = tail $ scanl (.|.) 0 a\n sr = init $ scanr (.|.) 0 a\n ans = foldl' (\\acc (q,w,e) -> max acc (q.|.w.|.e)) 0 $ zip3 sl (map (m*) a) sr\n print [sl,sr]\n print ans\n"}, {"source_code": "import Data.Bits\nimport Data.List\nmain :: IO()\nmain = do\n [n,k,x] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let m = (x^k)\n sl = scanl (.|.) 0 a\n sr = scanr (.|.) 0 a\n ans = foldl' (\\acc (q,w,e) -> max acc (q.|.w.|.e)) 0 $ zip3 sl (map (m*) a) (tail sr)\n --print [sl,sr]\n --print $ zip3 sl (map (m*) a) sr\n print ans\n"}, {"source_code": "import Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\n\n_solve :: [Integer] -> Integer -> Integer -> Integer\n-- |- numbers (input)\n-- | |- number of multiplications left\n-- | | |- multiplier\n-- nums k x |- final value to be returned\n_solve nums k x = foldl (.|.) multipled ns\n where (nmax:ns) = reverse (sort nums)\n multipled = nmax * (x ^ k)\n\nmain = do\n line <- fmap C.words C.getLine\n let (n:k:x:[]) = toInts line\n nums <- C.getLine\n let numbers = take (fromInteger n) (toInts (C.words nums))\n putStrLn (show (_solve numbers k x))\n where toInts = map (toInteger . fst . fromJust . C.readInt)\n\n"}, {"source_code": "import Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ndosolve :: [Int] -> Int -> Int -> Int\ndosolve as k x = solve as k x 0\n\nsolve :: [Int] -> Int -> Int -> Int -> Int\n-- |- numbers (input)\n-- | |- number of multiplications left\n-- | | |- multiplier\n-- nums k x |- final value to be returned\nsolve [] _ _ value = value\nsolve (a:as) 0 x value = solve as 0 x (a .|. value)\nsolve (a:as) k x value = max m2 (max m1 m3)\n where \n -- mult and move on\n m1 = solve as (k - 1) x (ax .|. value)\n -- mult and don't move on\n m2 = solve (ax:as) (k - 1) x value\n -- don't mult and move on\n m3 = solve as k x (a .|. value)\n ax = a * x\n\nmain = do\n line <- fmap C.words C.getLine\n let (n:k:x:[]) = toInts line\n nums <- C.getLine\n let numbers = take n (toInts (C.words nums))\n putStrLn (show (dosolve numbers k x))\n where toInts = map (fst . fromJust . C.readInt)\n\n"}, {"source_code": "import Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ndosolve :: [Int] -> Int -> Int -> Int\ndosolve (a:as) k x = solve as k x a\n\nsolve :: [Int] -> Int -> Int -> Int -> Int\n-- |- numbers (input)\n-- | |- number of multiplications left\n-- | | |- multiplier\n-- nums k x |- final value to be returned\nsolve [] _ _ value = value\nsolve (a:as) 0 x value = solve as 0 x (a .|. value)\nsolve (a:as) k x value = max multCurrent (max multed notmulted)\n where multed = solve as (k - 1) x ((a * x) .|. value)\n notmulted = solve as k x (a .|. value)\n multCurrent = solve ((a * x):as) (k - 1) x value\n\nmain = do\n line <- fmap C.words C.getLine\n let (n:k:x:[]) = toInts line\n nums <- C.getLine\n let numbers = take n (toInts (C.words nums))\n putStrLn (show (dosolve numbers k x))\n where toInts = map (fst . fromJust . C.readInt)\n\n"}, {"source_code": "-- Codeforces 578B\n\nimport Data.Bits\nimport Data.List\n\n-- Hint multiply x^k to a_i to get the hightest bit 1 to make result to be to greatest. \n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Integer] -> Integer\nsolve (n:k:x:xs) = maximum [prefix!!i .|. ((xs!!i)*b) .|. suffix!!i | i <- [0..length xs - 1]] where\n b = x ^ k\n prefix = fst $ foldl (\\(acc, prev) a -> (acc++[prev .|. a], prev .|. a)) ([0], 0) xs\n suffix = fst $ foldr (\\a (acc, prev) -> (acc++[prev .|. a], prev .|. a)) ([0], 0) xs\n"}, {"source_code": "import Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64)\nimport Data.Bits ((.|.))\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: Int64 -> [Int64] -> Int64\nsolve a xs = maximum . zipWith3 go xs (scanl (.|.) 0 xs) $ scanr (.|.) 0 xs\n where go x l r = l .|. (x * a) .|. r\n\nmain = do\n [_, k, x] <- parse <$> getLine\n getLine >>= print . solve (fromIntegral $ x^k) . map fromIntegral .parse\n"}, {"source_code": "import Data.List\nimport Data.Bits\nremove mx (a:as) pre | mx == a = pre ++ as\n | otherwise = remove mx as (a:pre)\nmain = do\n w0 <- getLine\n let [n,k,x0] = [read n::Int|n <-(words w0)]\n let x = (fromIntegral x0)::Integer\n w1 <- getLine\n let a = [read n::Integer|n <-(words w1)]\n let mx =maximum a\n let xs =remove mx a []\n let a = (iterate (*x) mx) !! k\n putStrLn $ show (foldl' (.|.) a xs)\n"}], "src_uid": "b544f02d12846026f6c76876bc6bd079"} {"source_code": "import qualified Data.Set as S\nimport Data.List\n\nf s = if S.null s then \"NO\" else \"YES\"\nsolve k (_:xs) = walk k 1 xs (S.singleton 0)\n\ndeleteLT k s \n | S.null s = s \n | otherwise = if (S.findMin s >= k) then s else deleteLT k . S.deleteMin $ s\n\nwalk _ _ [] s = s\nwalk k i (x:xs) s = if S.null ds || x == '#' then walk k (i + 1) xs ds \n else walk k (i + 1) xs (S.insert i ds)\n where ds = deleteLT (i - k) s\n\nmain = do\n p <- getLine\n r <- getLine\n let [n, k] = map read. words $ p in putStrLn $ f (solve k r)", "positive_code": [{"source_code": "import Data.List\n\nsolve _ i j [] = if (j == i - 1) then \"YES\" else \"NO\"\nsolve k i j (x:xs) = solve k (i+1) u xs\n where u = if j + k >= i && x == '.' then i else j\n\nmain = do \n p <- getLine\n r <- getLine\n let [n, k] = map read . words $ p in putStrLn $ solve k 0 0 r"}, {"source_code": "import Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> String -> Bool\nsolve k s = solve' k s\n where\n solve' _ \"\" = True\n solve' 0 _ = False\n solve' k' (c:s) = if c == '.'\n then solve' k s\n else solve' (k' - 1) s\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n s <- getLine\n if solve k s\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "main::IO()\nmain = do\n\tinput<-getLine\n\ts<-getLine\n\tlet\n\t\tk=( map read (words input) ::[Int] ) !! 1\n\t\tcc = foldl (\\(a,b) s -> if s=='#' then ((max a (b+1)),(b+1)) else (a,0)) (0,0) s\n\tputStrLn $ if (fst cc)>=k then \"NO\" else \"YES\"\n"}], "negative_code": [{"source_code": "import qualified Data.Set as S\n\nf s = if S.null s then \"NO\" else \"YES\"\nsolve k r = fst $ walk k (k + 1) ((\\x -> if x == [] then [] else init x) (drop (k + 1) r)) $ preproc k 0 r \n--solve k r = preproc k 0 $ r\n\n\npreproc k i r\n | i == (k + 1) || r == [] = S.empty\n | otherwise = if head r == '.' then S.insert i next else next\n where next = preproc k (i + 1) $ tail r\n\ndeleteLE k s \n | S.null s = s\n | otherwise = if (S.findMin s > k) then s else deleteLE k . S.deleteMin $ s\n\nwalk k i r s = foldl proc (s, i) r\n where proc (s, i) x = (step s i x, i + 1)\n step s i x = if S.null s || x == '#' then (nx s i) else S.insert i (nx s i)\n nx s i = deleteLE (i - k) s\n\n\nmain = do\n p <- getLine\n r <- getLine\n --let [n, k] = map read . words $ p in putStrLn $ solve k r\n let [n, k] = map read . words $ p in putStrLn $ f (deleteLE (n - k - 1) (solve k r))"}, {"source_code": "import qualified Data.Set as S\n\nf s = if S.null s then \"NO\" else \"YES\"\nsolve k r = fst $ walk k (k + 1) ((\\x -> if x == [] then [] else init x) (drop (k + 1) r)) $ preproc k 0 r \n--solve k r = preproc k 0 $ r\n\n\npreproc k i r\n | i == (k + 1) || r == [] = S.empty\n | otherwise = if head r == '.' then S.insert i next else next\n where next = preproc k (i + 1) $ tail r\n\ndeleteLE k s \n | S.null s = s\n | otherwise = if (S.findMin s > k) then s else deleteLE k . S.deleteMin $ s\n\nwalk k i r s = foldl proc (s, i) r\n where proc (s, i) x = (step s i x, i + 1)\n step s i x = if S.null s || x == '#' then (nx s i) else S.insert i (nx s i)\n nx s i = deleteLE (i - k) s\n\n\nmain = do\n p <- getLine\n r <- getLine\n --let [n, k] = map read . words $ p in putStrLn $ solve k r\n let [n, k] = map read . words $ p in putStrLn $ f (solve k r)"}], "src_uid": "d504d894b2f6a830c4d3b4edc54395be"} {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xys <- replicateM n readInts\r\n let inviteOk m = go xys m where\r\n go _ 0 = True\r\n go [] _ = False\r\n go (~[x, y]:xys) m'\r\n | x >= m' - 1 && y >= m - m' = go xys (m' - 1)\r\n | otherwise = go xys m'\r\n print $ binSearch (not . inviteOk) 1 n - 1\r\n\r\nbinSearch :: Integral i => (i -> Bool) -> i -> i -> i\r\nbinSearch f = go where\r\n go l h\r\n | l > h = l\r\n | f m = go l (m - 1)\r\n | otherwise = go (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "module Main (howManyCanInvite, FriendPreferences, main) where\r\n\r\n\r\nimport Data.Function ((&))\r\nimport Data.List (unfoldr)\r\nimport Data.Maybe (fromJust)\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\n\r\ntype FriendPreferences = (Int, Int)\r\n\r\n\r\nhowManyCanInvite :: [FriendPreferences] -> Int\r\nhowManyCanInvite friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n max_invitations_n = binarySearch canInvite (0, friends_n)\r\n canInvite mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> [FriendPreferences] -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n invited_n = foldl updateInvitedN 0 friends_preferences\r\n result = invited_n >= target_friends_n\r\n\r\n updateInvitedN invited_before friend_preferences = new_invited_n\r\n where\r\n new_invited_n = invited_before & applyIf can_invite_current (+1)\r\n (l, r) = friend_preferences\r\n can_invite_current = invited_before <= l && invited_after <= r\r\n invited_after = target_friends_n - (invited_before + 1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n\r\n\r\nbinarySearch :: (Integral i) => (i -> Bool) -> (i, i) -> i\r\nbinarySearch isEnough (l, r)\r\n | not (l <= r) = binarySearch isEnough (r, l)\r\n | l == r = mid\r\n | isEnough mid = binarySearch isEnough (mid, r)\r\n | otherwise = binarySearch isEnough (l, mid - 1)\r\n where mid = l + div (r - l + 1) 2\r\n\r\n\r\n-- IO section\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\ntype ByteString = B.ByteString\r\n\r\n\r\nprocessInput :: ByteString -> ByteString\r\nprocessInput = B.unlines . map processTest . groupInputByTests\r\n\r\n\r\ngroupInputByTests :: ByteString -> [ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeTestLines\r\n takeTestLines [] = Nothing\r\n takeTestLines (t:ts) = Just $ splitAt (readInt t) ts\r\n\r\n\r\nprocessTest :: ByteString -> ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map readInts (B.lines input)]\r\n max_invitations_n = howManyCanInvite friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\nreadInt :: ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nreadInts :: ByteString -> [Int]\r\nreadInts = map readInt . B.words"}, {"source_code": "module Main (howManyCanInvite, FriendPreferences, main) where\r\n\r\n\r\nimport Prelude\r\n\r\nimport Data.Function ((&))\r\nimport Data.List (unfoldr)\r\nimport Data.Maybe (fromJust)\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\n\r\ntype FriendPreferences = (Int, Int)\r\n\r\n\r\nhowManyCanInvite :: [FriendPreferences] -> Int\r\nhowManyCanInvite friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n max_invitations_n = binarySearch canInvite (0, friends_n)\r\n canInvite mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> [FriendPreferences] -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n invited_n = foldl updateInvitedN 0 friends_preferences\r\n result = invited_n >= target_friends_n\r\n\r\n updateInvitedN invited_before friend_preferences = new_invited_n\r\n where\r\n new_invited_n = invited_before & applyIf can_invite_current (+1)\r\n (l, r) = friend_preferences\r\n can_invite_current = invited_before <= l && invited_after <= r\r\n invited_after = target_friends_n - (invited_before + 1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n\r\n\r\nbinarySearch :: (Integral i) => (i -> Bool) -> (i, i) -> i\r\nbinarySearch isEnough (l, r)\r\n | not (l <= r) = binarySearch isEnough (r, l)\r\n | l == r = mid\r\n | isEnough mid = binarySearch isEnough (mid, r)\r\n | otherwise = binarySearch isEnough (l, mid - 1)\r\n where mid = l + div (r - l + 1) 2\r\n\r\n\r\n-- IO section\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\ntype ByteString = B.ByteString\r\n\r\n\r\nprocessInput :: ByteString -> ByteString\r\nprocessInput = B.unlines . map processTest . groupInputByTests\r\n\r\n\r\ngroupInputByTests :: ByteString -> [ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeTestLines\r\n takeTestLines [] = Nothing\r\n takeTestLines (t:ts) = Just $ splitAt (readInt t) ts\r\n\r\n\r\nprocessTest :: ByteString -> ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map readInts (B.lines input)]\r\n max_invitations_n = howManyCanInvite friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\nreadInt :: ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nreadInts :: ByteString -> [Int]\r\nreadInts = map readInt . B.words\r\n"}, {"source_code": "import Prelude\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Maybe (fromJust)\r\nimport Data.Function ((&))\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.unlines . map processTest . parseTests\r\n\r\n\r\nparseTests :: B.ByteString -> [B.ByteString]\r\nparseTests input = tests\r\n where\r\n tests_lines = drop 1 $ B.lines input\r\n tests = parseLines tests_lines\r\n\r\n parseLines [] = []\r\n parseLines tests_lines = current_test : parseLines next_tests_lines\r\n where\r\n x : xs = tests_lines\r\n tests_n = readInt x\r\n (current_test_lines, next_tests_lines) = splitAt tests_n xs\r\n current_test = B.unlines current_test_lines\r\n\r\n\r\nreadInt :: B.ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map (map readInt . B.words) (B.lines input)]\r\n max_invitations_n = findMaxInvitationsN friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\ntype PartyPreferences = [(Int, Int)]\r\n\r\n\r\nfindMaxInvitationsN :: PartyPreferences -> Int\r\nfindMaxInvitationsN friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n\r\n max_invitations_n = binarySearch 0 friends_n\r\n\r\n binarySearch l r\r\n | l == r = mid\r\n | can_invite_mid = binarySearch mid r\r\n | otherwise = binarySearch l (mid - 1)\r\n where\r\n mid = l + div (r - l + 1) 2\r\n can_invite_mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> PartyPreferences -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n result = _canInvite friends_preferences 0\r\n\r\n _canInvite preferences invited_n =\r\n case preferences of\r\n [] -> invited_n >= target_friends_n\r\n (l, r) : next_preferences -> _canInvite next_preferences new_invited_n\r\n where\r\n invited_after = target_friends_n - (invited_n + 1)\r\n can_take_current = invited_n <= l && invited_after <= r\r\n new_invited_n = invited_n & applyIf can_take_current (+1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n"}, {"source_code": "--{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport System.IO\r\n\r\nbinarySearch :: Integral t => (t->Bool) -> t -> t -> t\r\nbinarySearch can lo hi -- Assumption: f <$> [lo,hi] === [False,True]. Suggestion: Start with hi = n+1\r\n | lo + 1 == hi = lo\r\n | otherwise = if can mid then binarySearch can mid hi else binarySearch can lo mid\r\n where mid = lo + (hi-lo) `div` 2\r\n\r\ncanFulfil :: [[Int]] -> Int -> Int -> Bool\r\ncanFulfil _ _ 0 = True\r\ncanFulfil [] _ _ = False\r\ncanFulfil ([a,b]:rest) got need = canFulfil rest (got + this) (need - this)\r\n where this = fromEnum $ got<=b && need-1<=a\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n asbs <- CM.replicateM n readv\r\n let \r\n ans = binarySearch (canFulfil asbs 0) 1 (n+1)\r\n print ans\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat $ map (\\x->DBB.intDec x <> DBB.char7 ' ') xs\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n \r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n\r\n"}, {"source_code": "--{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\nimport Debug.Trace\r\nimport Data.Maybe (fromMaybe)\r\n\r\nbinarySearch :: Integral t => (t->Bool) -> t -> t -> t\r\nbinarySearch can lo hi -- Assumption: f <$> [lo,hi] === [False,True]. Suggestion: Start with hi = n+1\r\n | lo + 1 == hi = lo\r\n | otherwise = if can mid then binarySearch can mid hi else binarySearch can lo mid\r\n where mid = lo + (hi-lo) `div` 2\r\n\r\ncanFulfil :: [[Int]] -> Int -> Int -> Bool\r\ncanFulfil _ _ 0 = True\r\ncanFulfil [] got need = False\r\ncanFulfil ([a,b]:rest) got need = canFulfil rest (got + this) (need - this)\r\n where this = fromEnum $ got<=b && need-1<=a\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n asbs <- CM.replicateM n readv\r\n let \r\n ans = binarySearch (canFulfil asbs 0) 1 (n+1)\r\n print ans\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: IO [Int]\r\nreadv = do\r\n bWords <- DBC.words <$> DBC.getLine\r\n let toInt x = fst $ fromMaybe (0,mempty) $ DBC.readInt x\r\n return $ toInt <$> bWords\r\n \r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\nimport Data.Array.Unboxed\n\n\ncanUse :: Array Int (Int, Int) -> Int -> Bool\ncanUse arr k = let\n (1, n) = bounds arr\n go !i !lc !rc\n | i > n = rc < 0\n | otherwise = let\n (ai, bi) = arr ! i\n in if lc <= bi && rc <= ai\n then go (i + 1) (lc + 1) (rc - 1)\n else go (i + 1) lc rc\n in go 1 0 (k - 1)\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\n{-# INLINE binSearch #-}\nbinSearch fun = let\n go !li !ri = if li == ri\n then li\n else let\n mi = li + div (ri - li) 2\n in if fun mi\n then go li mi\n else go (mi + 1) ri\n in go\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n abLi <- replicateM n $ do\n ~[ai, bi] <- getInts 2\n pure (ai, bi)\n let\n abs :: Array Int (Int, Int)\n abs = listArray (1, n) abLi\n ans = binSearch (not . canUse abs) 0 (n + 10) - 1\n pure $ putInts [ans]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "module Main (howManyCanInvite, FriendPreferences, main) where\r\n\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Char (isSpace)\r\nimport Data.Function ((&))\r\nimport Data.List (unfoldr)\r\nimport Data.Maybe (fromJust)\r\n\r\n\r\ntype FriendPreferences = (Int, Int)\r\n\r\n\r\nhowManyCanInvite :: [FriendPreferences] -> Int\r\nhowManyCanInvite friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n max_invitations_n = binarySearch canInvite (0, friends_n)\r\n canInvite mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> [FriendPreferences] -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n invited_n = foldl updateInvitedN 0 friends_preferences\r\n result = invited_n >= target_friends_n\r\n\r\n updateInvitedN invited_before friend_preferences = new_invited_n\r\n where\r\n new_invited_n = invited_before & applyIf can_invite_current (+1)\r\n (l, r) = friend_preferences\r\n can_invite_current = invited_before <= l && invited_after <= r\r\n invited_after = target_friends_n - (invited_before + 1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n\r\n\r\nbinarySearch :: (Integral i) => (i -> Bool) -> (i, i) -> i\r\nbinarySearch isEnough (l, r)\r\n | not (l <= r) = binarySearch isEnough (r, l)\r\n | l == r = mid\r\n | isEnough mid = binarySearch isEnough (mid, r)\r\n | otherwise = binarySearch isEnough (l, mid - 1)\r\n where mid = l + div (r - l + 1) 2\r\n\r\n\r\n-- IO section\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\ntype ByteString = B.ByteString\r\n\r\n\r\nprocessInput :: ByteString -> ByteString\r\nprocessInput = B.unlines . map processTest . groupInputByTests\r\n\r\n\r\ngroupInputByTests :: ByteString -> [ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeTestLines\r\n takeTestLines [] = Nothing\r\n takeTestLines (t:ts) = Just $ splitAt (readInt t) ts\r\n\r\n\r\nprocessTest :: ByteString -> ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map readInts (B.lines input)]\r\n max_invitations_n = howManyCanInvite friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\nreadInt :: ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nreadInts :: ByteString -> [Int]\r\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\r\n"}, {"source_code": "module Main (howManyCanInvite, FriendPreferences, main) where\r\n\r\n\r\nimport Data.Char (isSpace)\r\nimport Data.Function ((&))\r\nimport Data.List (unfoldr)\r\nimport Data.Maybe (fromJust)\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\n\r\ntype FriendPreferences = (Int, Int)\r\n\r\n\r\nhowManyCanInvite :: [FriendPreferences] -> Int\r\nhowManyCanInvite friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n max_invitations_n = binarySearch canInvite (0, friends_n)\r\n canInvite mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> [FriendPreferences] -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n invited_n = foldl updateInvitedN 0 friends_preferences\r\n result = invited_n >= target_friends_n\r\n\r\n updateInvitedN invited_before friend_preferences = new_invited_n\r\n where\r\n new_invited_n = invited_before & applyIf can_invite_current (+1)\r\n (l, r) = friend_preferences\r\n can_invite_current = invited_before <= l && invited_after <= r\r\n invited_after = target_friends_n - (invited_before + 1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n\r\n\r\nbinarySearch :: (Integral i) => (i -> Bool) -> (i, i) -> i\r\nbinarySearch isEnough (l, r)\r\n | not (l <= r) = binarySearch isEnough (r, l)\r\n | l == r = mid\r\n | isEnough mid = binarySearch isEnough (mid, r)\r\n | otherwise = binarySearch isEnough (l, mid - 1)\r\n where mid = l + div (r - l + 1) 2\r\n\r\n\r\n-- IO section\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\ntype ByteString = B.ByteString\r\n\r\n\r\nprocessInput :: ByteString -> ByteString\r\nprocessInput = B.unlines . map processTest . groupInputByTests\r\n\r\n\r\ngroupInputByTests :: ByteString -> [ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeTestLines\r\n takeTestLines [] = Nothing\r\n takeTestLines (t:ts) = Just $ splitAt (readInt t) ts\r\n\r\n\r\nprocessTest :: ByteString -> ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map readInts (B.lines input)]\r\n max_invitations_n = howManyCanInvite friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\nreadInt :: ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nreadInts :: ByteString -> [Int]\r\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\r\n"}, {"source_code": "module Main (howManyCanInvite, FriendPreferences, main) where\r\n\r\n\r\nimport Prelude\r\n\r\nimport Data.Char (isSpace)\r\nimport Data.Function ((&))\r\nimport Data.List (unfoldr)\r\nimport Data.Maybe (fromJust)\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\n\r\ntype FriendPreferences = (Int, Int)\r\n\r\n\r\nhowManyCanInvite :: [FriendPreferences] -> Int\r\nhowManyCanInvite friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n max_invitations_n = binarySearch canInvite (0, friends_n)\r\n canInvite mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> [FriendPreferences] -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n invited_n = foldl updateInvitedN 0 friends_preferences\r\n result = invited_n >= target_friends_n\r\n\r\n updateInvitedN invited_before friend_preferences = new_invited_n\r\n where\r\n new_invited_n = invited_before & applyIf can_invite_current (+1)\r\n (l, r) = friend_preferences\r\n can_invite_current = invited_before <= l && invited_after <= r\r\n invited_after = target_friends_n - (invited_before + 1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n\r\n\r\nbinarySearch :: (Integral i) => (i -> Bool) -> (i, i) -> i\r\nbinarySearch isEnough (l, r)\r\n | not (l <= r) = binarySearch isEnough (r, l)\r\n | l == r = mid\r\n | isEnough mid = binarySearch isEnough (mid, r)\r\n | otherwise = binarySearch isEnough (l, mid - 1)\r\n where mid = l + div (r - l + 1) 2\r\n\r\n\r\n-- IO section\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\ntype ByteString = B.ByteString\r\n\r\n\r\nprocessInput :: ByteString -> ByteString\r\nprocessInput = B.unlines . map processTest . groupInputByTests\r\n\r\n\r\ngroupInputByTests :: ByteString -> [ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeTestLines\r\n takeTestLines [] = Nothing\r\n takeTestLines (t:ts) = Just $ splitAt (readInt t) ts\r\n\r\n\r\nprocessTest :: ByteString -> ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map readInts (B.lines input)]\r\n max_invitations_n = howManyCanInvite friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\nreadInt :: ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nreadInts :: ByteString -> [Int]\r\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\r\n"}, {"source_code": "module Main (howManyCanInvite, FriendPreferences, main) where\r\n\r\n\r\nimport Data.Function ((&))\r\nimport Data.List (unfoldr)\r\nimport Data.Maybe (fromJust)\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\n\r\ntype FriendPreferences = (Int, Int)\r\n\r\n\r\nhowManyCanInvite :: [FriendPreferences] -> Int\r\nhowManyCanInvite friends_preferences = max_invitations_n\r\n where\r\n friends_n = length friends_preferences\r\n max_invitations_n = binarySearch canInvite (0, friends_n)\r\n canInvite mid = canInviteSuchFriendsNumber mid friends_preferences\r\n\r\n\r\ncanInviteSuchFriendsNumber :: Int -> [FriendPreferences] -> Bool\r\ncanInviteSuchFriendsNumber target_friends_n friends_preferences = result\r\n where\r\n invited_n = foldl updateInvitedN 0 friends_preferences\r\n result = invited_n >= target_friends_n\r\n\r\n updateInvitedN invited_before friend_preferences = new_invited_n\r\n where\r\n new_invited_n = invited_before & applyIf can_invite_current (+1)\r\n (l, r) = friend_preferences\r\n can_invite_current = invited_before <= l && invited_after <= r\r\n invited_after = target_friends_n - (invited_before + 1)\r\n\r\n\r\napplyIf :: Bool -> (a -> a) -> a -> a\r\napplyIf predicate function = if predicate then function else id\r\n\r\n\r\nbinarySearch :: (Integral i) => (i -> Bool) -> (i, i) -> i\r\nbinarySearch isEnough (l, r)\r\n | not (l <= r) = binarySearch isEnough (r, l)\r\n | l == r = mid\r\n | isEnough mid = binarySearch isEnough (mid, r)\r\n | otherwise = binarySearch isEnough (l, mid - 1)\r\n where mid = l + div (r - l + 1) 2\r\n\r\n\r\n-- IO section\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\ntype ByteString = B.ByteString\r\n\r\n\r\nprocessInput :: ByteString -> ByteString\r\nprocessInput = B.unlines . map processTest . groupInputByTests\r\n\r\n\r\ngroupInputByTests :: ByteString -> [ByteString]\r\ngroupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines\r\n where\r\n groupInputLines = unfoldr takeTestLines\r\n takeTestLines [] = Nothing\r\n takeTestLines (t:ts) = Just $ splitAt (readInt t) ts\r\n\r\n\r\nprocessTest :: ByteString -> ByteString\r\nprocessTest input = output\r\n where\r\n friends_preferences = [(l, r) | [r, l] <- map readInts (B.lines input)]\r\n max_invitations_n = howManyCanInvite friends_preferences\r\n output = B.pack $ show max_invitations_n\r\n\r\n\r\nreadInt :: ByteString -> Int\r\nreadInt = fst . fromJust . B.readInt\r\n\r\n\r\nreadInts :: ByteString -> [Int]\r\nreadInts = map readInt . B.words\r\n"}], "negative_code": [], "src_uid": "93e9eb2c95fc9d86f526a03754ffd576"} {"source_code": "import Control.Monad\nimport Data.Int (Int64)\nimport Data.Sequence (Seq)\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Sequence as Seq\n\ngao :: [(Int, Int)] -> Int -> Int64 -> Seq Int64 -> [Int64]\ngao [] _ _ _ = []\ngao r@((t, d): r') b m q\n | not (Seq.null q) && t' <= fromIntegral t = gao r (b+1) m q'\n | b /= 0 = end: gao r' (b-1) end (q Seq.|> begin)\n | otherwise = (-1): gao r' b m q\n where\n begin = max m $ fromIntegral t\n end = begin + fromIntegral d\n t' Seq.:< q' = Seq.viewl q\n\nmain :: IO ()\nmain = do\n (n:b:_) <- fmap (map readInt . C.words) C.getLine\n r <- replicateM n $ do\n (t:d:_) <- fmap (map readInt . C.words) C.getLine\n return (t, d)\n let ans = gao r b 0 Seq.empty\n putStrLn $ unwords $ map show ans\n where\n readInt s = let Just (i, _) = C.readInt s in i\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Control.Monad.RWS.Strict\nimport Data.Foldable (toList)\nimport Data.Sequence (Seq, ViewL (..), (|>))\nimport qualified Data.Sequence as Seq\n\ntype Index = Int\ntype Time = Integer\ntype Queue = Seq (Index, Time)\ntype Serve = (Time, Queue)\ntype Events a = RWS Int Queue Serve a\n\ndispatch::MonadWriter Queue m=>Int->Integer->m ()\ndispatch = (tell.). (Seq.singleton.). (,)\n\nrollout::(MonadWriter Queue m, MonadState Serve m)=>Maybe Time->m ()\nrollout now = do\n (time, q) <- get\n let happen d = maybe True (>= time + d) now\n case Seq.viewl q of\n Seq.EmptyL -> case now of\n Nothing -> return ()\n Just time' -> put (time' ,q)\n (idx, duration) :< rest\n | happen duration -> do\n let time' = time + duration\n dispatch idx time'\n put (time', rest)\n rollout now\n | otherwise -> return ()\n\nhandle::(MonadReader Int m, MonadWriter Queue m, MonadState Serve m)=>((Time,Time),Index)->m ()\nhandle ((time, duration), idx) = do\n rollout (Just time)\n b <- ask\n (t', q') <- get\n if Seq.length q' > b then dispatch idx (-1)\n else put (t', q' |> (idx, duration) )\n\nwalk::Int->[((Time,Time),Index)]->[Time]\nwalk b queries = let\n go = mapM_ handle queries >> rollout Nothing::Events ()\n res = snd $ execRWS go b (0, Seq.empty)\n in toList $ snd <$> Seq.sort res\n\nreadPair::Read a=>IO (a,a)\nreadPair = fmap (unlist . map read . words) getLine where\n unlist [x,y] = (x,y)\n unlist _ = error \"trouble input\"\n\nmain::IO ()\nmain = do\n (n,b) <- readPair\n nums <- replicateM n readPair\n let queries = nums `zip` [1..]\n putStrLn $ unwords $ show <$> walk b queries\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Int (Int64)\nimport Data.Sequence (Seq)\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Sequence as Seq\n\ngao :: [(Int, Int)] -> Int -> Int64 -> Seq Int64 -> [Int64]\ngao [] _ _ _ = []\ngao r@((t, d): r') b m q\n | not (Seq.null q) && t' <= fromIntegral t = gao r (b+1) m q'\n | b /= 0 = end: gao r' (b-1) end (begin Seq.<| q)\n | otherwise = (-1): gao r' b m q\n where\n begin = max m $ fromIntegral t\n end = begin + fromIntegral d\n t' Seq.:< q' = Seq.viewl q\n\nmain :: IO ()\nmain = do\n (n:b:_) <- fmap (map readInt . C.words) C.getLine\n r <- replicateM n $ do\n (t:d:_) <- fmap (map readInt . C.words) C.getLine\n return (t, d)\n let ans = gao r b 0 Seq.empty\n putStrLn $ unwords $ map show ans\n where\n readInt s = let Just (i, _) = C.readInt s in i\n"}, {"source_code": "import Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\ngao :: [(Int, Int)] -> Int -> Int -> Queue Int -> [Int]\ngao [] _ _ _ = []\ngao r@((t, d): r') b m q\n | q /= queue [] && t' <= t = gao r (b+1) m q'\n | b /= 0 = end: gao r' (b-1) end (push begin q)\n | otherwise = (-1): gao r' b m q\n where\n begin = max t m\n end = begin + d\n (t', q') = pop q\n\nmain :: IO ()\nmain = do\n (n:b:_) <- fmap (map readInt . C.words) C.getLine\n r <- replicateM n $ do\n (t:d:_) <- fmap (map readInt . C.words) C.getLine\n return (t, d)\n let ans = gao r b 0 $ queue []\n putStrLn $ unwords $ map show ans\n where\n readInt s = let Just (i, _) = C.readInt s in i\n\ndata Queue a = Queue [a] [a]\n deriving (Eq, Show)\n\nqueue :: [a] -> Queue a\nqueue = Queue []\n\npush :: a -> Queue a -> Queue a\npush a (Queue r q) = Queue (a:r) q\n\npop :: Queue a -> (a, Queue a)\npop (Queue r (a:q)) = (a, Queue r q)\npop (Queue r []) = pop $ Queue [] (reverse r)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Control.Monad.RWS.Strict\nimport Data.Foldable (toList)\nimport Data.Sequence (Seq, ViewL (..), (|>))\nimport qualified Data.Sequence as Seq\n\ntype Queue = Seq (Int,Int)\ntype Serve = (Int, Queue)\ntype Events a = RWS Int Queue Serve a\n\ndispatch::MonadWriter Queue m=>Int->Int->m ()\ndispatch = (tell.). (Seq.singleton.). (,)\n\nrollout::(MonadWriter Queue m, MonadState Serve m)=>Maybe Int->m ()\nrollout now = do\n (time,q) <- get\n let happen d = maybe True (>= time + d) now\n case Seq.viewl q of\n Seq.EmptyL -> case now of\n Nothing -> return ()\n Just time' -> put (time' ,q)\n (duration, idx) :< rest\n | happen duration -> do\n let time' = time + duration\n dispatch idx time'\n put (time', rest)\n rollout now\n | otherwise -> return ()\n\nhandle::(MonadReader Int m, MonadWriter Queue m, MonadState Serve m)=>((Int,Int),Int)->m ()\nhandle ((time, duration), idx) = do\n rollout (Just time)\n b <- ask\n (t', q') <- get\n if Seq.length q' > b then dispatch idx (-1)\n else put (t', q' |> (duration, idx) )\n\nwalk::Int->[((Int,Int),Int)]->[Int]\nwalk b queries = let\n go = mapM_ handle queries >> rollout Nothing::Events ()\n res = snd $ execRWS go b (0, Seq.empty)\n in toList $ snd <$> Seq.sort res\n\nmain::IO ()\nmain = do\n let readPair = fmap (unlist . map read . words) getLine\n unlist [x,y] = (x,y)\n unlist _ = error \"trouble input\"\n (n,b) <- readPair\n nums <- replicateM n readPair\n let queries = nums `zip` [1..]\n putStrLn $ unwords $ show <$> walk b queries\n"}], "src_uid": "5981594b2d6d1077ce2249b641d18f10"} {"source_code": "main :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve = foldl (++) \"\". map (++ \"\\n\") . map str_solve . tail . lines\n\nstr_solve :: String -> String\nstr_solve s = if (head $ s) /= (last $ s) then (last $ s) : (tail s) else s\n\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n \r\n \r\nprefMins :: Ord t => (a -> t) -> [a] -> [t]\r\nprefMins f li = tail $ scanl' min (f $ head li) $ map f li\r\n \r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do \r\n ~[s] <- map P.unpack <$> getNext 1\r\n let\r\n t = (if ((head s) == 'a') then \"b\" else \"a\") ++ (tail s) \r\n pure $ string7 $ (if ((head s) == (last s)) then s else t) ++ \"\\n\"\r\n \r\n\r\ntype SP = State [P.ByteString]\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "import Control.Monad\n\naba :: String -> Int -> Int -> (Int, Int)\naba [] ab ba = (ab, ba)\naba [a] ab ba = (ab, ba)\naba ('a':'b':xs) ab ba = aba ('b':xs) (ab+1) ba\naba ('b':'a':xs) ab ba = aba ('a':xs) ab (ba+1)\naba (x:xs) ab ba = aba xs ab ba\n\ncalc :: String -> String\ncalc line =\n let (ab,ba) = aba line 0 0 in\n if ab==ba then line\n else\n case line of\n ('b':'b':xs) -> if ab < ba then ('a':'b':xs) else ('b':'a':xs)\n ('a':'a':xs) -> if ab < ba then ('a':'b':xs) else ('b':'a':xs)\n ('a':'b':xs) -> ('b':'b':xs)\n ('b':'a':xs) -> ('a':'a':xs)\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n --print $ aba line 0 0\n putStrLn $ calc line\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC { s :: String }\n\ninput :: Scanner TC\ninput = do\n s <- str\n return TC {..}\n\n-- type Output = String\n\n-- output :: Output -> C.ByteString\noutput = C.pack\n\n-- solve :: TC -> Output\nsolve TC {..} = last s : tail s\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.ByteString.Char8 as C (getLine, readInt, words)\r\nimport Data.List (foldl', sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- readInts\r\n replicateM_ t $ do\r\n s <- getLine\r\n putStrLn $ solve s\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nsolve :: [a] -> [a]\r\nsolve (a:as)\r\n | null as = [a]\r\n | otherwise = last as:as\r\n"}], "negative_code": [], "src_uid": "351ffff1dfe1bc1762f062f612463759"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, reverse, dropWhile, unpack)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Char (isSpace)\n\nreadInt = fst . M.fromJust . C.readInt\nrstrip = C.reverse . C.dropWhile isSpace . C.reverse\n\nsplit (x:xs) cp ans | x == ' ' || x == '-' = split xs [] (length (x:cp):ans)\n | otherwise = split xs (x:cp) ans\nsplit [] cp ans = reverse (length cp:ans)\n\ntest (x:xs) w c ans | x + c > w = test (x:xs) w 0 (ans + 1) | otherwise = test xs w (x + c) ans\ntest [] _ _ ans = ans + 1\n\nrun xs a b k | a + 1 == b = b\n | m >= mxs && test xs m 0 0 <= k = run xs a m k\n | otherwise = run xs m b k where\n m = (a + b) `div` 2\n mxs = maximum xs\n\nmain = do\n (readInt -> k) <- B.getLine\n (C.unpack . rstrip -> x) <- B.getLine\n putStrLn $ show $ run (split x [] []) 0 (length x) k\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nmain = do\n k <- fmap readInt B.getLine\n s <- fmap (B.filter (/= '\\r')) B.getLine\n print $ solve k s\n\nsolve k s = go 1 (B.length s)\n where\n cmp m = maybe GT ((`compare` k) . snd) $ foldM (\\(!cll, !lc) wl -> if wl > m then Nothing else let cll' = cll + wl in Just $ if cll' > m then (wl, lc + 1) else (cll', lc)) (0, 0) wls\n wls = go $ B.splitWith (\\c -> c == ' ' || c == '-') s\n where\n go [l] = [B.length l]\n go (l:ls) = (B.length l + 1):go ls\n go l r\n | l >= r = l\n | otherwise = case cmp m of\n LT -> go l m \n _ -> go (m + 1) r\n where m = (l + r) `div` 2\n\nchunks n = takeWhile (not . null) . map (take n) . iterate (drop n)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n k <- fmap readInt B.getLine\n s <- fmap (B.filter (/= '\\r')) B.getLine\n print $ solve k s\n\nsolve k s \n | r == 0 = maximum $ map sum $ chunks q ls \n | q == 0 = maximum ls\n | otherwise = minimum $ map (\\b -> let (h, t) = splitAt b ls; (h', t') = splitAt (q + r) t in maximum $ map sum $ chunks q h ++ [h'] ++ chunks q t') [0,q..nw - q - r]\n where\n nw = length ls\n ls = go $ B.splitWith (\\c -> c == ' ' || c == '-') s\n where\n go [l] = [B.length l]\n go (l:ls) = (B.length l + 1):go ls\n (q, r) = nw `quotRem` k\n\nchunks n = takeWhile (not . null) . map (take n) . iterate (drop n)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "src_uid": "3cc766aabb6f5f7b687a62a0205ca94c"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n maybe (print $ -1) (putStr.unlines.map(unwords.map show)) $ solve n xs\n\nsolve :: Int -> [Int] -> Maybe [[Int]]\nsolve n xs\n | cnt5>0 || cnt7>0 = Nothing\n | cnt1-cnt3-cnt4 == cnt2-cnt4 && cnt2-cnt4==cnt6-cnt3 && cnt2-cnt4>=0 = Just $ replicate cnt4 [1,2,4] ++ replicate (cnt2-cnt4) [1,2,6] ++ replicate cnt3 [1,3,6]\n | otherwise = Nothing\n where\n [cnt1,cnt2,cnt3,cnt4,cnt5,cnt6,cnt7] = map (unsafeAt cnt) [1..7]\n cnt = runSTUArray $ do\n arr <- newArray (0,10) 0 :: ST s (STUArray s Int Int)\n forM_ xs $ \\x -> do\n unsafeRead arr x>>=unsafeWrite arr x.(1+)\n return arr", "positive_code": [{"source_code": "import Prelude\nimport Data.String\nimport Text.Printf\nimport Control.Monad\n\nreadNums:: Int -> [Int] -> IO [Int]\nreadNums 0 numbers = return numbers\nreadNums n numbers = do\n c <- getChar\n if (c /= ' ')\n then \n readNums (n - 1) ((read [c] :: Int):numbers)\n else\n readNums n numbers \n\nsolver:: Int -> Int -> Int -> Int -> Int -> Int -> IO [Int] \nsolver 0 c1 c2 c3 c4 c6 = return [c1, c2, c3, c4, c6]\nsolver n c1 c2 c3 c4 c6 = do\n c <- getChar\n if (c /= ' ')\n then \n case read [c] :: Int of\n 1 -> solver (n - 1) (c1 + 1) c2 c3 c4 c6\n 2 -> solver (n - 1) c1 (c2 + 1) c3 c4 c6\n 3 -> solver (n - 1) c1 c2 (c3 + 1) c4 c6\n 4 -> solver (n - 1) c1 c2 c3 (c4 + 1) c6\n 6 -> solver (n - 1) c1 c2 c3 c4 (c6 + 1)\n _ -> return [0, 0, 0, 0, 0]\n else\n solver n c1 c2 c3 c4 c6\n \n\nprintAnswer:: Int -> Int -> Int -> Int -> Int -> String\nprintAnswer 0 0 0 0 0 = \"\\n\"\nprintAnswer c1 c2 0 c4 0 = \"1 2 4\\n\" ++ printAnswer (c1 - 1) (c2 - 1) 0 (c4 - 1) 0\nprintAnswer c1 c2 0 c4 c6 = \"1 2 6\\n\" ++ printAnswer (c1 - 1) (c2 - 1) 0 c4 (c6 - 1)\nprintAnswer c1 c2 c3 c4 c6 = \"1 3 6\\n\" ++ printAnswer (c1 - 1) c2 (c3 - 1) c4 (c6 - 1)\n\nmain = do\n str <- getLine\n let n = read str :: Int\n [c1, c2, c3, c4, c6] <- solver n 0 0 0 0 0\n if ((c1 /= 0) && (c3 <= c6) && (c2 == (c4 + c6 - c3)) && (c1 == (c2 + c3)))\n then\n printf (printAnswer c1 c2 c3 c4 c6)\n else\n printf \"-1\"\n return ()"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\nimport Data.Ratio\nimport qualified Data.ByteString.Char8 as BS\n\ngetInteger = (\\(Just (x,_)) -> x). BS.readInteger\ngetInt = (\\(Just (x,_)) -> x). BS.readInt\n\nfilter' func = foldl' (\\acc x -> if func x then x:acc else acc) []\nmap' func = foldl' (\\acc x -> func x: acc) []\n\nsolve [] = (0, 0, 0, 0, 0)\nsolve (x:xs)\n | x == 1 = (a+1, b, c, d, e)\n | x == 2 = (a, b+1, c, d, e)\n | x == 3 = (a, b, c+1, d, e)\n | x == 4 = (a, b, c, d+1, e)\n | x == 6 = (a, b, c, d, e+1)\n | otherwise = (0, 0, 0, 0, 0)\n where\n (a, b, c, d, e) = solve xs\n\nsolution (0, 0, 0, 0, 0) = []\nsolution (a, b, c, d, e) \n | a > 0 && b > 0 && d > 0 = (1, 2, 4):solution (a-1, b-1, c, d-1, e)\n | a > 0 && b > 0 && e > 0 = (1, 2, 6) : solution (a-1, b-1, c, d, e-1)\n | a > 0 && c > 0 && e > 0 = (1, 3, 6) : solution (a-1, b, c-1, d, e-1)\n | otherwise = []\n\nmain :: IO ()\nmain = do\n _n <- BS.getLine\n _arr <- BS.getLine\n let\n n = getInt _n\n arr = solution. solve. map' getInt. BS.words $ _arr\n if length arr /= n`div` 3 then print (-1) else (mapM_ (\\(a, b, c) -> putStrLn $ (show a) ++ \" \"++ (show b) ++ \" \" ++ (show c)) arr)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nmain :: IO ()\nmain = getLine >> map read <$> words <$> getLine >>= putStr . solve \n\n\nsolve :: [Int] -> String\nsolve xs\n | cnt !! 2 >= cnt !! 4 &&\n cnt !! 1 == cnt !! 4 + cnt !! 6 &&\n cnt !! 2 + cnt !! 3 == cnt !! 4 + cnt !! 6 &&\n cnt !! 5 == 0 &&\n cnt !! 7 == 0 = answer\n | otherwise = \"-1\\n\"\n where\n -- cnt !! i = the number of times i shows up\n cnt = map (subtract 1 . length) $ group $ sort $ [0, 1, 2, 3, 4, 5, 6, 7] ++ xs\n answer = concat $ \n replicate (cnt !! 3) \"1 3 6\\n\" ++ \n replicate (cnt !! 6 - cnt !! 3) \"1 2 6\\n\" ++ \n replicate (cnt !! 4) \"1 2 4\\n\"\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -Wall -fno-warn-missing-signatures -fno-warn-type-defaults #-}\n{-# LANGUAGE ViewPatterns #-}\nimport Data.List(transpose)\n\nmain=interact $ unlines.sv.(!!1).lines\nsv (words->xs)\n | x>=0 && y>=0 && z>=0 && x+y+z==a1 && x+y==a2 && z==a3 && x==a4 && 0==a5 && y+z==a6 && 0==a7 = replicate x \"1 2 4\" ++ replicate y \"1 2 6\" ++ replicate z \"1 3 6\"\n | otherwise = [\"-1\"]\n where \n (a1:a2:a3:a4:a5:a6:a7:_)= foldr (\\a as -> ( length.filter (==a)) xs :as) [] (transpose [['1'..'7']]) \n x = a1-a6 \n z = a1-a2 \n y = a6-a3 \n"}, {"source_code": "import Control.Monad(liftM, forM, forM_)\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe(fromJust)\n\ndata StateT s x = State (s -> (s, x))\nffunc (State f) = f\ninstance (Monad (StateT s)) where\n--\treturn :: (StateT s) a => a -> (StateT s) a\n\treturn x = State (\\a -> (a, x))\n\t(State f1) >> (State f2) = State $ \\s -> f2 $ fst (f1 s)\n\t(State f1) >>= b = State $ \\s -> let (st, val) = f1 s in ffunc (b val) st\n\ngetf f = State (\\s -> (s, f s)) \n--put x = State \\s -> (s, x)\nmmap f = State (\\s -> (f s, ()))\nmodf f 0 (x:xs) = (f x):xs\nmodf f i (x:xs) = x:(modf f (i - 1) xs)\n\npprint [] = return ()\npprint ([a, b, c]:ls) = B.putStrLn ( B.pack (show a ++ \" \" ++ show b ++ \" \" ++ show c)) >> pprint ls\n\nreadi = fst . fromJust . B.readInt\n\nrev3 = concat . map (concat . map concat)\n\nsolve a = if maximum st == 0 then rev3 val else []\n\twhere\t\n\t\t(st, val) = (ffunc zz) (map ((flip count) a) [0..7])\n\t\tcount x = length . (filter (==x))\n\t\tcheck xs = do\n\t\t\tas <- minimum `liftM` forM [1..7] (\\x -> do\t\n\t\t\t\t\tbs <- getf (!!x)\t\t\t\t\t\n\t\t\t\t\treturn $ let as = count x xs in if as == 0 then 10^9 else div bs as)\n\t\t\tforM_ xs (\\x -> mmap $ modf (+(-as)) x) \n\t\t\treturn $ replicate as xs\n\t\tzz = do\n\t\t\tforM [7,6..1] (\\i -> do\t\n\t\t\t\tforM (filter ((==0).(mod i)) [i-1,(i-2)..1]) (\\j-> do\n\t\t\t\t\tforM (filter ((==0).(mod j)) [j-1,(j-2)..1]) (\\k -> do\n\t\t\t\t\t\tcheck [k, j, i] >>= return)))\n\n\nmain = do\n\tn <- readi `liftM` B.getLine\n\ta <- (map readi . B.words) `liftM` B.getLine\n\tlet as = solve a in if as == [] then putStr \"-1\" else pprint $ solve a\t\t\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n let\n cs = accumArray (+) 0 (1, 7) $ zip xs $ repeat 1 :: UArray Int Int\n n' = n `div` 3\n\n ls = replicate (cs!4) [1, 2, 4] ++\n replicate (cs!6 - cs!3) [1, 2, 6] ++\n replicate (cs!3) [1, 3, 6]\n\n putStrLn $\n if cs!1 == n' && (cs!2 + cs!3 == n') && (cs!4 + cs!6 == n') && cs!3 <= cs!6 && cs!5 == 0 && cs!7 == 0\n then unlines $ map (unwords . map show) ls\n else show $ -1\n"}, {"source_code": "\n-- 342A\n\nimport Control.Monad (liftM, replicateM_)\nimport Prelude hiding (print, reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [Int] -> Maybe (Int, Int, Int)\nsolve n as\n | solveIsExists = Just (a, b, c)\n | otherwise = Nothing\n where\n z i = length $ filter (== i) as\n a = z 4\n b = z 2 - a\n c = z 3\n solveIsExists\n = b >= 0\n && z 1 == n\n && z 1 == a + b + c\n && z 5 == 0\n && z 6 == b + c\n && z 7 == 0\n\nprint :: Maybe (Int, Int, Int) -> IO ()\nprint Nothing = putStrLn \"-1\"\nprint (Just (a, b, c)) = do\n replicateM_ a $ putStrLn \"1 2 4\"\n replicateM_ b $ putStrLn \"1 2 6\"\n replicateM_ c $ putStrLn \"1 3 6\"\n\nmain :: IO ()\nmain = do\n n <- liftM (\\m -> div m 3) readLn\n as <- reads\n print $ solve n as\n\n{-\n1 2 4 - a\n1 2 6 - b\n1 3 6 - c\n\na+b+c = z1 = n\na+b = z2\n c = z3\na = z4\n 0 = z5\n b+c = z6\n 0 = z7\n-}\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nmain :: IO ()\nmain = getLine >> map read <$> words <$> getLine >>= putStr . solve \n\n\nsolve :: [Int] -> String\nsolve xs\n | cnt !! 2 >= cnt !! 4 &&\n cnt !! 1 == cnt !! 4 + cnt !! 6 &&\n cnt !! 2 + cnt !! 3 == cnt !! 4 + cnt !! 6 = answer\n | otherwise = \"-1\\n\"\n where\n -- cnt !! i = the number of times i shows up\n cnt = map (subtract 1 . length) $ group $ sort $ [0, 1, 2, 3, 4, 5, 6] ++ xs\n answer = concat $ \n replicate (cnt !! 3) \"1 3 6\\n\" ++ \n replicate (cnt !! 6 - cnt !! 3) \"1 2 6\\n\" ++ \n replicate (cnt !! 4) \"1 2 4\\n\"\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -Wall -fno-warn-missing-signatures -fno-warn-type-defaults #-}\n{-# LANGUAGE ViewPatterns #-}\nimport Data.List(transpose)\n\nmain=interact $ unlines.sv.(!!1).lines\nsv (words->xs)\n | x+y+z==a1 && x+y==a2 && z==a3 && x==a4 && 0==a5 && y+z==a6 && 0==a7 = replicate x \"1 2 4\" ++ replicate y \"1 2 6\" ++ replicate z \"1 3 6\"\n | otherwise = [\"-1\"]\n where \n (a1:a2:a3:a4:a5:a6:a7:_)=foldr (\\a as -> ( length.filter (==a)) xs :as) [] (transpose [['1'..'7']])\n x = a1-a6\n z = a1-a2\n y = a6-a3\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -Wall -fno-warn-missing-signatures -fno-warn-type-defaults #-}\n{-# LANGUAGE ViewPatterns #-}\nimport Data.List(transpose)\n\nmain=interact $ unlines.sv.(!!1).lines\nsv (words->xs)\n | x==a4 && z==a3 && a5==0 && a7==0 = replicate x \"1 2 4\" ++ replicate y \"1 2 6\" ++ replicate z \"1 3 6\"\n | otherwise = [\"-1\"]\n where \n (a1:a2:a3:a4:a5:a6:a7:_)=foldr (\\a as -> ( length.filter (==a)) xs :as) [] (transpose [['1'..'7']])\n x = a1-a6\n z = a1-a2\n y = a6-a3\n"}, {"source_code": "import Control.Monad(liftM)\n\nmain = do\n n <- (read :: [Char] -> Int) `liftM` getLine\n putStr $ show $ n\n"}, {"source_code": "import Prelude\nimport Data.String\nimport Text.Printf\nimport Control.Monad\n\nsolver (x:xs) c1 c2 c3 c4 c6 = case x of\n 1 -> solver xs (c1+1) c2 c3 c4 c6\n 2 -> solver xs c1 (c1+2) c3 c4 c6\n 3 -> solver xs c1 c2 (c3+1) c4 c6\n 4 -> solver xs c1 c2 c3 (c4+1) c6\n 6 -> solver xs c1 c2 c3 c4 (c6+1)\n _ -> solver xs c1 c2 c3 c4 c6\n \nsolver [] c1 c2 c3 c4 c6 = [c1, c2, c3, c4, c6]\n\nprintAnswer str 0 0 0 0 0 = (putStr str) \nprintAnswer str c1 c2 0 c4 0 = printAnswer (str ++ \"1 2 4\\n\") (c1-1) (c2-1) 0 (c4-1) 0 \nprintAnswer str c1 c2 0 c4 c6 = printAnswer (str ++ \"1 2 6\\n\") (c1-1) (c2-1) 0 c4 (c6-1) \nprintAnswer str c1 c2 c3 c4 c6 = printAnswer (str ++ \"1 3 6\\n\") (c1-1) c2 (c3-1) c4 (c6-1)\n \nmain = do\n str1 <- getLine\n str2 <- getLine\n let n = read str1 :: Int\n let numbers = map (\\x -> read x :: Int) $ words str2\n let [c1, c2, c3, c4, c6] = solver numbers 0 0 0 0 0\n result <- if ((c1 == (div n 3))&&(c3 <= c6)&&(c2 == (c4 + c6 - c3)))\n then printAnswer \"\" c1 c2 c3 c4 c6\n else putStr \"-1\\n\"\n return ()"}, {"source_code": "import Prelude\nimport Data.String\nimport Text.Printf\nimport Control.Monad\n\nsolver (x:xs) c1 c2 c3 c4 c6 = case x of\n 1 -> solver xs (c1+1) c2 c3 c4 c6\n 2 -> solver xs c1 (c1+2) c3 c4 c6\n 3 -> solver xs c1 c2 (c3+1) c4 c6\n 4 -> solver xs c1 c2 c3 (c4+1) c6\n 6 -> solver xs c1 c2 c3 c4 (c6+1)\n _ -> solver xs c1 c2 c3 c4 c6\n \nsolver [] c1 c2 c3 c4 c6 = [c1, c2, c3, c4, c6]\n\nprintAnswer str 0 0 0 0 0 = (putStr str) \nprintAnswer str c1 c2 0 c4 0 = printAnswer (str ++ \"1 2 4\\n\") (c1-1) (c2-1) 0 (c4-1) 0 \nprintAnswer str c1 c2 0 c4 c6 = printAnswer (str ++ \"1 2 6\\n\") (c1-1) (c2-1) 0 c4 (c6-1) \nprintAnswer str c1 c2 c3 c4 c6 = printAnswer (str ++ \"1 3 6\\n\") (c1-1) c2 (c3-1) c4 (c6-1)\n \nmain = do\n str1 <- getLine\n str2 <- getLine\n let n = read str1 :: Int\n let numbers = map (\\x -> read x :: Int) $ words str2\n let [c1, c2, c3, c4, c6] = solver numbers 0 0 0 0 0\n result <- if ((c1 == (c2 + c3))&&(c3 <= c6)&&(c2 == (c4 + c6 - c3))&&(c1 /= 0))\n then printAnswer \"\" c1 c2 c3 c4 c6\n else putStr \"-1\\n\"\n return ()"}, {"source_code": "import Prelude\nimport Data.String\nimport Text.Printf\nimport Control.Monad\n\nsolver (x:xs) c1 c2 c3 c4 c6 = case x of\n 1 -> solver xs (c1+1) c2 c3 c4 c6\n 2 -> solver xs c1 (c1+2) c3 c4 c6\n 3 -> solver xs c1 c2 (c3+1) c4 c6\n 4 -> solver xs c1 c2 c3 (c4+1) c6\n 6 -> solver xs c1 c2 c3 c4 (c6+1)\n _ -> solver xs c1 c2 c3 c4 c6\n \nsolver [] c1 c2 c3 c4 c6 = [c1, c2, c3, c4, c6]\n\nprintAnswer str 0 0 0 0 0 = (putStr str) \nprintAnswer str c1 c2 0 c4 0 = printAnswer (str ++ \"1 2 4\\n\") (c1-1) (c2-1) 0 (c4-1) 0 \nprintAnswer str c1 c2 0 c4 c6 = printAnswer (str ++ \"1 2 6\\n\") (c1-1) (c2-1) 0 c4 (c6-1) \nprintAnswer str c1 c2 c3 c4 c6 = printAnswer (str ++ \"1 3 6\\n\") (c1-1) c2 (c3-1) c4 (c6-1)\n \nmain = do\n str1 <- getLine\n str2 <- getLine\n let n = read str1 :: Int\n let numbers = map (\\x -> read x :: Int) $ words str2\n let [c1, c2, c3, c4, c6] = solver numbers 0 0 0 0 0\n result <- if ((c1 == (c2 + c3))&&(c3 <= c6)&&(c2 == (c4 + c6 - c3)))\n then printAnswer \"\" c1 c2 c3 c4 c6\n else putStr \"-1\\n\"\n return ()"}, {"source_code": "import Prelude\nimport Data.String\nimport Text.Printf\nimport Control.Monad\n\nsolver (x:xs) c1 c2 c3 c4 c6 = case x of\n 1 -> solver xs (c1+1) c2 c3 c4 c6\n 2 -> solver xs c1 (c2+1) c3 c4 c6\n 3 -> solver xs c1 c2 (c3+1) c4 c6\n 4 -> solver xs c1 c2 c3 (c4+1) c6\n 6 -> solver xs c1 c2 c3 c4 (c6+1)\n _ -> solver xs c1 c2 c3 c4 c6\n \nsolver [] c1 c2 c3 c4 c6 = [c1, c2, c3, c4, c6]\n\nprintAnswer str 0 0 0 0 0 = (putStr str) \nprintAnswer str c1 c2 0 c4 0 = printAnswer (str ++ \"1 2 4\\n\") (c1-1) (c2-1) 0 (c4-1) 0 \nprintAnswer str c1 c2 0 c4 c6 = printAnswer (str ++ \"1 2 6\\n\") (c1-1) (c2-1) 0 c4 (c6-1) \nprintAnswer str c1 c2 c3 c4 c6 = printAnswer (str ++ \"1 3 6\\n\") (c1-1) c2 (c3-1) c4 (c6-1)\n \nmain = do\n str1 <- getLine\n str2 <- getLine\n let n = read str1 :: Int\n let numbers = map (\\x -> read x :: Int) $ words str2\n let [c1, c2, c3, c4, c6] = solver numbers 0 0 0 0 0\n print [c1, c2, c3, c4, c6]\n result <- if ((c1 == (c2 + c3))&&(c3 <= c6)&&(c2 == (c4 + c6 - c3))&&(c1 /= 0))\n then printAnswer \"\" c1 c2 c3 c4 c6\n else putStr \"-1\\n\"\n return ()"}], "src_uid": "513234db1bab98c2c2ed6c7030c1ac72"} {"source_code": "import Data.Int (Int64)\nimport Data.Monoid (mappend)\nimport Data.Maybe (fromJust)\nimport Data.List (minimumBy, sortBy)\nimport qualified Data.ByteString.Char8 as B\n\ndata Point = Point Int64 Int64 Int deriving (Eq)\n\ngetId (Point _ _ id) = id\n\ndiff (Point x1 y1 id1) (Point x2 y2 _) = Point (x1 - x2) (y1 - y2) id1\n\nvecProd (Point x1 y1 _) (Point x2 y2 _) = x1 * y2 - x2 * y1\n\nlen2 (Point x y _) = x * x + y * y\n\ncmpAngle p1 p2 = (compare (vecProd p1 p2) 0) `mappend` compare (len2 p1) (len2 p2)\n\ncmpCoords (Point x1 y1 _) (Point x2 y2 _) = compare x1 x2 `mappend` compare y1 y2\n\nleftAndRest ps = (p0, sortBy cmpAngle $ map (flip diff $ p0) (filter (/= p0) ps))\n where p0 = minimumBy cmpCoords ps \n\nfirstNonColinear ps = head $ (filter (\\p -> p `vecProd` (head ps) /= 0) ps)\n\nsolve ps = (getId p0, getId $ head rest, getId $ firstNonColinear rest) \n where (p0, rest) = leftAndRest ps\n\nmakePoints coords = map (\\(i, (x, y)) -> Point x y i) $ zip [1..n] coords\n where n = length coords \n\ngetInt = fromIntegral . fst . fromJust . B.readInt\n\ngetCoords line = (getInt x, getInt y)\n where [x, y] = B.words line\n\nmain = do\n input <- B.getContents\n let (line:lines) = B.lines input\n let points = makePoints $ map getCoords lines\n let (i0, i1, i2) = solve points\n putStrLn $ show i0 ++ \" \" ++ show i1 ++ \" \" ++ show i2\n\n", "positive_code": [{"source_code": "import Data.Int (Int64)\nimport Data.Monoid (mappend)\nimport Data.List (minimumBy, sortBy)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\ndata Point = Point Int64 Int64 Int deriving (Show)\n\ngetId (Point _ _ id) = id\n\ninstance Eq Point where\n (Point x1 y1 _) == (Point x2 y2 _) = x1 == x2 && y1 == y2\n\ndiff (Point x1 y1 id1) (Point x2 y2 _) = Point (x1 - x2) (y1 - y2) id1\n\nvecProd (Point x1 y1 _) (Point x2 y2 _) = x1 * y2 - x2 * y1\n\nlen2 (Point x y _) = x * x + y * y\n\ncmpAngle p1 p2 = (compare (vecProd p1 p2) 0) `mappend` compare (len2 p1) (len2 p2)\n\ncmpCoords (Point x1 y1 _) (Point x2 y2 _) = compare x1 x2 `mappend` compare y1 y2\n\nleftAndRest ps = (p0, sortBy cmpAngle $ map (flip diff $ p0) (filter (/= p0) ps))\n where p0 = minimumBy cmpCoords ps \n\nfirstNonColinear ps = head $ (filter (\\p -> p `vecProd` (head ps) /= 0) ps)\n\nsolve ps = \n let (p0, rest) = leftAndRest ps\n in (getId p0, getId $ head rest, getId $ firstNonColinear rest)\n\nmakePoints coords = map (\\(i, (x, y)) -> Point (fromIntegral x) (fromIntegral y) i) $ zip [1..n] coords\n where n = length coords \n\nmain = do\n input <- B.getContents\n let (line:lines) = B.lines input\n let coords = map (\\l -> let [x, y] = B.words l in (fst . fromJust $ B.readInt x, fst . fromJust $ B.readInt y)) lines\n let points = makePoints coords\n let (i0, i1, i2) = solve points\n putStrLn $ show i0 ++ \" \" ++ show i1 ++ \" \" ++ show i2\n \n\n"}], "negative_code": [], "src_uid": "0d3ac2472990aba36abee156069b1088"} {"source_code": "import Data.List\nmain = interact $ show . rd . lines\nrd (s1:s2:[]) = go (pt1 . map read . words $ s1) s2\npt1 (t:sx:sy:ex:ey:[]) = [(sx,sy),(ex,ey)]\ngo ((sx,sy):(ex,ey):[]) l | all (True==) $ map (\\c -> (length $ filter (c==) l) >= (get c)) dirs = (1+) . maximum $ map (\\c -> (elemIndices c l)!!((get c)-1)) dirs\n | otherwise = -1\n where hd = abs $ (sx-ex)\n vd = abs $ (sy-ey)\n get c = if c`elem`\"EW\" then hd else vd\n dirs = todir (signum $ sx-ex,signum $ sy-ey)\ntodir (-1,0) = \"E\"\ntodir (1,0) = \"W\"\ntodir (0,-1) = \"N\"\ntodir (0,1) = \"S\"\ntodir (a,b) = (todir (a,0)) ++ (todir (0,b))\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = putStrLn . show . solve . B.words =<< B.getContents\n\nsolve :: [B.ByteString] -> Int\nsolve [_, sx', sy', ex', ey', ws]\n | any (> 0) ts = -1\n | otherwise = i\n where\n (i, ts) = B.foldl' f (0, [e, s, w, n]) ws\n [sx, sy, ex, ey] = map (maybe 0 fst . B.readInt) [sx', sy', ex', ey']\n e = ex - sx\n s = sy - ey\n w = -e\n n = -s\n f x@(i, [e, s, w, n]) c\n | any (> 0) [e, s, w, n] = case fromEnum c of\n 69 -> (i + 1, [e - 1, s, w, n])\n 83 -> (i + 1, [e, s - 1, w, n])\n 87 -> (i + 1, [e, s, w - 1, n])\n 78 -> (i + 1, [e, s, w, n - 1])\n | otherwise = x\n"}, {"source_code": "\nwind 'E' = (1,0)\nwind 'W' = (-1,0)\nwind 'N' = (0,1)\nwind 'S' = (0,-1)\n\nvadd (x0, y0) (x1, y1) = (x0 + x1, y0 + y1)\n\nnorm (x, y) = (abs x) + (abs y)\n\nsolve i (0,0) _ = i\nsolve i _ [] = -1\nsolve i d@(_,_) (x:xs) = if norm n < norm d then solve (i + 1) n xs else solve (i + 1) d xs\n where n = d `vadd` (wind x)\n\nmain = do\n p <- getLine\n w <- getLine\n let [n, sx, sy, ex, ey] = map (read :: [Char]->Int). words $ p\n in putStrLn $ show $ solve 0 (sx - ex, sy - ey) w"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> String -> Int\nsolve [_, sx, sy, ex, ey] s = solve' 0 sx sy s\n where\n solve' t x y s\n | x == ex && y == ey = t\n | null s = -1\n | head s == 'E' && x < ex = solve' (t+1) (x+1) y (tail s)\n | head s == 'S' && y > ey = solve' (t+1) x (y-1) (tail s)\n | head s == 'W' && x > ex = solve' (t+1) (x-1) y (tail s)\n | head s == 'N' && y < ey = solve' (t+1) x (y+1) (tail s)\n | otherwise = solve' (t+1) x y (tail s)\n\nmain :: IO ()\nmain = do\n ps <- reads\n s <- getLine\n print $ solve ps s\n\n where\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "gao::(Int,Int)->(Int,Int)->Char->(Int,Int)\ngao (sx,sy) (tx,ty) wind | wind=='E' && tx>sx = (sx+1,sy)\n\t\t\t\t\t\t | wind=='S' && tysy = (sx,sy+1)\n\t\t\t\t\t\t | otherwise = (sx,sy)\n\nmain::IO()\nmain = do\n\tinput<-getContents\n\tlet\n\t\t(input2,wind)=splitAt 5 $ words input\n\t\t(t:xx)=map read input2 :: [Int]\n\t\tsx=xx!!0\n\t\tsy=xx!!1\n\t\tex=xx!!2\n\t\tey=xx!!3\n\t\tcheck sx sy = if sx==ex && sy==ey then True else False \n\t\tdoit::Int->Int->Int->String->Int\n\t\tdoit x y now wind = if (check x y) then now\n\t\t\t\t\t\t\telse if null wind then -1\n\t\t\t\t\t\t\telse doit nx ny (now+1) (tail wind)\n\t\t\t\t\t\t\t\twhere (nx,ny)=gao (x,y) (ex,ey) (wind!!0)\n\tprint $ doit sx sy 0 (wind!!0)\n"}, {"source_code": "data R=R Integer | NOR deriving (Eq, Ord)\ns[l1,w]=max(go sx ex 'W' 'E')(go sy ey 'S' 'N') where\n [t,sx,sy,ex,ey]=map read $ words l1\n go a b dec inc\n | b < a = gogo dec (a-b)\n | otherwise = gogo inc (b-a)\n gogo c 0 = R 0\n gogo c n = case drop (n-1) $ filter (\\(_,x)->x==c) (zip [1..] w) of\n ((i, _) : _) -> R i\n [] -> NOR\np NOR=\"-1\"\np(R x)=show x\nmain=interact$p.s.lines\n"}, {"source_code": "\n\n-- returns the number of elements from xs consumed\n-- to turn s1 to s2\ngen :: Eq s => s -> s -> (s -> a -> s) -> [a] -> Maybe Int\ngen s1 s2 f xs | s1 == s2 = Just 0\n | null xs = Nothing\n | otherwise = fmap (+1) (gen (f s1 (head xs)) s2 f (tail xs))\n\nnext :: (Int, Int) -> Char -> (Int, Int)\nnext s@(x,y) c | c == 'E' && x < 0 = (x+1,y)\n | c == 'S' && y > 0 = (x,y-1)\n | c == 'W' && x > 0 = (x-1,y)\n | c == 'N' && y < 0 = (x,y+1)\n | otherwise = s\n\nmain = do\n [_, sx, sy, ex, ey] <- fmap (map read.words) getLine :: IO [Int]\n wind <- getLine\n case gen (sx-ex,sy-ey) (0,0) next wind of\n Nothing -> putStrLn \"-1\"\n Just x -> putStrLn.show $ x\n"}], "negative_code": [{"source_code": "import Data.List\nmain = interact $ show . rd . lines\nrd (s1:s2:[]) = go (pt1 . map read . words $ s1) s2\npt1 (t:sx:sy:ex:ey:[]) = [(sx,sy),(ex,ey)]\ngo ((sx,sy):(ex,ey):[]) l | all (True==) $ map (\\c -> (length $ filter (c==) l) >= (get c)) dirs = (1+) . maximum $ map (\\c -> last $ elemIndices c l) dirs\n | otherwise = -1\n where hd = abs $ (sx-ex)\n vd = abs $ (sy-ey)\n md = hd+vd\n get c = if c`elem`\"EW\" then hd else vd\n dirs = todir (signum $ sx-ex,signum $ sy-ey)\ntodir (-1,0) = \"E\"\ntodir (1,0) = \"W\"\ntodir (0,-1) = \"N\"\ntodir (0,1) = \"S\"\ntodir (a,b) = (todir (a,0)) ++ (todir (0,b))\n"}], "src_uid": "aa31a2a1ad1575aee051ddee8642c53a"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nnewtype Writer a = Writer { runWriter :: ListLike Char -> (a,ListLike Char) }\nnewtype ListLike a = ListLike { genList :: [a] -> [a] }\n\ninstance Functor Writer where\n fmap f (Writer g) = Writer (\\s -> let (a,s) = g s in (f a,s))\n\ninstance Monad Writer where\n return a = Writer (\\s -> (a,s))\n (Writer g) >>= f = Writer (\\s -> let (a,s') = g s in runWriter (f a) s')\n\n\nemptyList = ListLike id\nput ch = Writer (\\s -> ((),ListLike (\\l -> genList s (ch:l))))\n\nconvert [a,b,c] = (a,b,c)\nmain = do\n [n,m,s,f] <- readsInt\n l <- replicateM m (convert <$> readsInt)\n putStrLn $ solve n s f l\n\nsolve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String\nsolve n s f l = genList (snd $ runWriter (go s 1 l) emptyList) \"\"\n where\n (c,d) = if s < f then ('R',1) else ('L',-1)\n go p _ _ | p == f = return ()\n go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = put 'X' >> go p (t+1) ls\n | t >= t' = put c >> go (p+d) (t+1) ls\n go p t ls = put c >> go (p+d) (t+1) ls\n", "positive_code": [{"source_code": "import Control.Monad(liftM, forM, forM_)\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe(fromJust)\nimport Data.List(sort)\n\nreadi = fst . fromJust . B.readInt\n\ngoC s f \n\t| s < f = 'R'\n\t| otherwise = 'L'\n\nnext s f\n\t| s == f = s\n\t| s < f = s + 1\n\t| otherwise = s - 1\n\ninn x (l, r) = l <= x && x <= r\n\ngo s f t [] = replicate (abs (f - s)) (goC s f)\ngo s f t ls@([t2, l, r]:ev)\n\t| s == f = \"\"\n\t| (t == t2) = if (inn s (l, r) || inn (next s f) (l, r)) \n\t\t\tthen 'X':(go s f (t + 1) ev)\n\t\t\telse (goC s f):(go ns f (t + 1) ev)\n\t| otherwise = (goC s f):(go ns f (t + 1) ls)\n\t\twhere ns = next s f\n\nmain = do\n\t[n, m, s, f] <- (map readi . B.words) `liftM` B.getLine\n\ttlr <- sequence $ replicate m $ (map readi . B.words) `liftM` B.getLine\n\tputStr $ go s f 1 (sort tlr)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nconvert [a,b,c] = (a,b,c)\nmain = do\n [n,m,s,f] <- readsInt\n l <- replicateM m (convert <$> readsInt)\n solve n s f l\n\nsolve :: Int -> Int -> Int -> [(Int,Int,Int)] -> IO ()\nsolve n s f l = go s 1 l\n where\n (c,d) = if s < f then ('R',1) else ('L',-1)\n go p _ _ | p == f = putChar '\\n'\n go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = putChar 'X' >> go p (t+1) ls\n | t >= t' = putChar c >> go (p+d) (t+1) ls\n go p t ls = putChar c >> go (p+d) (t+1) ls\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nconvert [a,b,c] = (a,b,c)\nmain = do\n [n,m,s,f] <- readsInt\n l <- replicateM m (convert <$> readsInt)\n putStrLn $ solve n s f l\n\nsolve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String\nsolve n s f l = go s 1 l\n where\n (c,d) = if s < f then ('R',1) else ('L',-1)\n go p _ _ | p == f = []\n go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = 'X' :go p (t+1) ls\n | t >= t' = c:go (p+d) (t+1) ls\n go p t ls = c:go (p+d) (t+1) ls\n\n\n \n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nnewtype Writer a = Writer { runWriter :: String -> (a,String) }\n\ninstance Functor Writer where\n fmap f (Writer g) = Writer (\\s -> let (a,s) = g s in (f a,s))\n\ninstance Monad Writer where\n return a = Writer (\\s -> (a,s))\n (Writer g) >>= f = Writer (\\s -> let (a,s') = g s in runWriter (f a) s')\n\nput ch = Writer (\\s -> ((),ch:s))\n\nconvert [a,b,c] = (a,b,c)\nmain = do\n [n,m,s,f] <- readsInt\n l <- replicateM m (convert <$> readsInt)\n putStrLn $ solve n s f l\n\nsolve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String\nsolve n s f l = reverse $ snd $ runWriter (go s 1 l) \"\"\n where\n (c,d) = if s < f then ('R',1) else ('L',-1)\n go p _ _ | p == f = return ()\n go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = put 'X' >> go p (t+1) ls\n | t >= t' = put c >> go (p+d) (t+1) ls\n go p t ls = put c >> go (p+d) (t+1) ls\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (print, reads)\n\nreads :: IO [Int]\nreads = liftM (map read . words) getContents\n where\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromEnum c - fromEnum '0') s\n\nsolve :: [Int] -> String\nsolve (n : m : s : f : xs) = take' l $ solve' 1 s xs\n where\n take' 0 _ = []\n take' n (x:xs)\n | c == x = x : take' (n - 1) xs\n | otherwise = x : take' n xs\n l = abs (f - s)\n (k, c) = if f > s then (1, 'R') else (-1, 'L')\n solve' t s [] = repeat c\n solve' t s qs@(ti : li : ri : xs)\n | t < ti = replicate (ti - t) c ++ solve' ti (s + k * (ti - t)) qs\n | f > s && (s + 1 < li || ri < s) = solve' t s xs\n | f < s && (s < li || ri < s - 1) = solve' t s xs\n | otherwise = 'X' : solve' (t+1) s xs\n\nprint :: Show a => Maybe [a] -> IO ()\nprint = putStrLn . maybe \"Impossible\" (intercalate \" \" . map show)\n\nmain :: IO ()\nmain = reads >>= putStrLn . solve\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m,s,f] <- map read.words <$> getLine\n tlrs <- map readInt.B.words <$> B.getContents\n putStrLn $ solve n s f tlrs\n\nsolve :: Int -> Int -> Int -> [Int] -> String\nsolve n s f tlrs = go s 1 tlrs\n where\n go !cur !time tlrs@(t:l:r:rest)\n | cur == f = \"\"\n | time > t = go cur time rest\n | time == t && (p l cur r || p l next r) = 'X' : go cur (time+1) rest\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) tlrs\n | dir < 0 = 'X' : go cur (time+1) tlrs\n | dir > 0 && cur /= n = 'R' : go next (time+1) tlrs\n | otherwise = 'X' : go cur (time+1) tlrs\n where\n p l x r = l<=x && x<=r\n dir = signum (f - cur)\n next = cur + dir\n go !cur !time []\n | cur == f = \"\"\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) []\n | dir < 0 = 'X' : go cur (time+1) []\n | dir > 0 && cur /= n = 'R' : go next (time+1) []\n | otherwise = 'X' : go cur (time+1) []\n where\n dir = signum (f - cur)\n next = cur + dir\n"}, {"source_code": "import Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n [n, m, s, f] <- getWords\n blocks <- replicateM m $ do\n [t, l, r] <- getWords\n return (t, l, r)\n putStrLn $ solve s f blocks\n\nsolve :: Int -> Int -> [(Int, Int, Int)] -> String\nsolve source destination blocks = map showStep $ solve' source blocks 1 where\n showStep True = if source < destination then 'R' else 'L'\n showStep False = 'X'\n\n solve' source blocks time\n | source == destination = []\n | null blocks = replicate (abs (destination - source)) True\n | t < time = solve' source (tail blocks) time\n | otherwise = canGo : solve' source' blocks (time + 1)\n where\n (t, l, r) = head blocks\n\n source' = if canGo then next else source\n canGo = not $ isBlocked source || isBlocked next\n next = if source < destination\n then source + 1\n else source - 1\n\n isBlocked x = t == time && l <= x && x <= r\n\ngetWords :: Read a => IO [a]\ngetWords = getLine >>= return . map read . words\n"}], "negative_code": [{"source_code": "import Control.Monad(liftM, forM, forM_)\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe(fromJust)\nimport Data.List(sort)\n\nreadi = fst . fromJust . B.readInt\n\ngoC s f \n\t| s < f = 'R'\n\t| otherwise = 'L'\n\nnext s f\n\t| s == f = s\n\t| s < f = s + 1\n\t| otherwise = s - 1\n\ninn x (l, r) = l <= x && x <= r\n\ngo s f t [] = replicate (f - s) (goC s f)\ngo s f t ls@([t2, l, r]:ev)\n\t| s == f = \"\"\n\t| (t == t2) = if (inn s (l, r) || inn (next s f) (l, r)) \n\t\t\tthen 'X':(go s f (t + 1) ev)\n\t\t\telse (goC s f):(go ns f (t + 1) ev)\n\t| otherwise = (goC s f):(go ns f (t + 1) ls)\n\t\twhere ns = next s f\n\nmain = do\n\t[n, m, s, f] <- (map readi . B.words) `liftM` B.getLine\n\ttlr <- sequence $ replicate m $ (map readi . B.words) `liftM` B.getLine\n\tputStr $ go s f 1 (sort tlr)\n"}, {"source_code": "import Control.Monad(liftM, forM, forM_)\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe(fromJust)\nimport Data.List(sort)\n\nreadi = fst . fromJust . B.readInt\n\ngoC s f \n\t| s < f = 'R'\n\t| otherwise = 'L'\n\nnext s f\n\t| s == f = s\n\t| s < f = s + 1\n\t| otherwise = s - 1\n\ninn x (l, r) = l <= x && x <= r\n\ngo s f t [] = replicate (t + (f - s)) (goC s f)\ngo s f t ls@([t2, l, r]:ev)\n\t| s == f = \"\"\n\t| (t == t2) = if (inn s (l, r) || inn (next s f) (l, r)) \n\t\t\tthen 'X':(go s f (t + 1) ev)\n\t\t\telse (goC s f):(go ns f (t + 1) ev)\n\t| otherwise = (goC s f):(go ns f (t + 1) ls)\n\t\twhere ns = next s f\n\nmain = do\n\t[n, m, s, f] <- (map readi . B.words) `liftM` B.getLine\n\ttlr <- sequence $ replicate m $ (map readi . B.words) `liftM` B.getLine\n\tputStr $ go s f 1 (sort tlr)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nnewtype Writer a = Writer { runWriter :: ListLike Char -> (a,ListLike Char) }\nnewtype ListLike a = ListLike { genList :: [a] -> [a] }\n\ninstance Functor Writer where\n fmap f (Writer g) = Writer (\\s -> let (a,s) = g s in (f a,s))\n\ninstance Monad Writer where\n return a = Writer (\\s -> (a,s))\n (Writer g) >>= f = Writer (\\s -> let (a,s') = g s in runWriter (f a) s')\n\n\nemptyList = ListLike id\nput ch = Writer (\\s -> ((),ListLike (\\l -> ch:l)))\n\nconvert [a,b,c] = (a,b,c)\nmain = do\n [n,m,s,f] <- readsInt\n l <- replicateM m (convert <$> readsInt)\n putStrLn $ solve n s f l\n\nsolve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String\nsolve n s f l = genList (snd $ runWriter (go s 1 l) emptyList) \"\"\n where\n (c,d) = if s < f then ('R',1) else ('L',-1)\n go p _ _ | p == f = return ()\n go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = put 'X' >> go p (t+1) ls\n | t >= t' = put c >> go (p+d) (t+1) ls\n go p t ls = put c >> go (p+d) (t+1) ls\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m,s,f] <- map read.words <$> getLine\n tlrs <- map readInt.B.words <$> B.getContents\n putStrLn $ solve n s f tlrs\n\nsolve :: Int -> Int -> Int -> [Int] -> String\nsolve n s f tlrs = go s 1 tlrs\n where\n go !cur !time (t:l:r:rest)\n | cur == f = \"\"\n | time == t && l<=next && next<=r = 'X' : go cur (time+1) rest\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) rest\n | dir < 0 = 'X' : go cur (time+1) rest\n | dir > 0 && cur /= n = 'R' : go next (time+1) rest\n | otherwise = 'X' : go cur (time+1) rest\n where\n dir = signum (f - cur)\n next = cur + dir\n go !cur !time []\n | cur == f = \"\"\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) []\n | dir < 0 = 'X' : go cur (time+1) []\n | dir > 0 && cur /= n = 'R' : go next (time+1) []\n | otherwise = 'X' : go cur (time+1) []\n where\n dir = signum (f - cur)\n next = cur + dir"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m,s,f] <- map read.words <$> getLine\n tlrs <- map readInt.B.words <$> B.getContents\n putStrLn $ solve n s f tlrs\n\nsolve :: Int -> Int -> Int -> [Int] -> String\nsolve n s f tlrs = go s 1 tlrs\n where\n go !cur !time tlrs@(t:l:r:rest)\n | cur == f = \"\"\n | time == t && (p l cur r || p l next r) = 'X' : go cur (time+1) rest\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) tlrs\n | dir < 0 = 'X' : go cur (time+1) tlrs\n | dir > 0 && cur /= n = 'R' : go next (time+1) tlrs\n | otherwise = 'X' : go cur (time+1) tlrs\n where\n p l x r = l<=x && x<=r\n dir = signum (f - cur)\n next = cur + dir\n go !cur !time []\n | cur == f = \"\"\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) []\n | dir < 0 = 'X' : go cur (time+1) []\n | dir > 0 && cur /= n = 'R' : go next (time+1) []\n | otherwise = 'X' : go cur (time+1) []\n where\n dir = signum (f - cur)\n next = cur + dir\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,m,s,f] <- map read.words <$> getLine\n tlrs <- map readInt.B.words <$> B.getContents\n putStrLn $ solve n s f tlrs\n\nsolve :: Int -> Int -> Int -> [Int] -> String\nsolve n s f tlrs = go s 1 tlrs\n where\n go !cur !time (t:l:r:rest)\n | cur == f = \"\"\n | time == t && (p l cur r || p l next r) = 'X' : go cur (time+1) rest\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) rest\n | dir < 0 = 'X' : go cur (time+1) rest\n | dir > 0 && cur /= n = 'R' : go next (time+1) rest\n | otherwise = 'X' : go cur (time+1) rest\n where\n p l x r = l<=x && x<=r\n dir = signum (f - cur)\n next = cur + dir\n go !cur !time []\n | cur == f = \"\"\n | dir < 0 && cur /= 1 = 'L' : go next (time+1) []\n | dir < 0 = 'X' : go cur (time+1) []\n | dir > 0 && cur /= n = 'R' : go next (time+1) []\n | otherwise = 'X' : go cur (time+1) []\n where\n dir = signum (f - cur)\n next = cur + dir\n"}], "src_uid": "c1c9815e2274a1f147eab7bd8ee2d574"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >> getContents >>= putStrLn . which \"YES\" \"NO\" . all ( all ( == 'X' ) ) . clip . transpose . clip . lines\n\nclip = filter ( not . all ( == '.' ) )\n", "positive_code": [{"source_code": "import Data.List\n\n-- solvable iff input shape is a rectangle\nsolve :: [String] -> Bool\nsolve strs =\n let blank = all (=='.')\n dropBlanks = filter (not . blank)\n strs' = dropBlanks $ transpose $ dropBlanks strs\n allXSegments = all (all (=='X'))\n in allXSegments strs'\n\nmain :: IO ()\nmain = do\n _ <- getLine\n rst <- getContents\n let soln = solve $ lines rst\n if soln then\n putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad( replicateM)\nimport Data.List( nub)\nmain = do\n [n_, m_] <- return.map read.words =<< getLine\n ls <- replicateM n_ getLine\n let cleansed = filter (any ('X'==)) ls\n putStr $ if 1 == (length $ nub cleansed) then \"YES\" else \"NO\"\n"}], "negative_code": [], "src_uid": "b395be2597f4cc0478bc45f774fa1c01"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Function\nimport Text.Printf\n\ncomb :: Integral b => b -> [a] -> [[a]]\ncomb 0 _ = [[]]\ncomb _ [] = []\ncomb n (x : xs) = map (x :) (comb (n - 1) xs) ++ comb n xs\n\nicomb :: Integer -> Integer -> Integer\nicomb n m = product [n, n - 1 .. n - m + 1] `quot` product [1 .. m]\n\nparticipants :: Int -> [[Int]]\nparticipants n = [[x, x] | x <- [1 .. n]]\n\nsolve :: Int -> [(Int, [Int])]\nsolve n = map ((,) <$> fst . head <*> map snd) . groupBy ((==) `on` fst) . sort $\n f (comb 2 [1 .. days]) (participants n)\n where\n days = (+ 2) $ length $ (takeWhile (<= n')) $ map (`icomb` 2) [3 ..]\n where n' = toInteger n\n f [] bss = []\n f ~(as : ass) ~(bs : bss) = zip as bs ++ f ass bss\n\nmain :: IO ()\nmain = do\n xs <- solve <$> readLn\n print $ length xs\n forM_ xs $ \\(_, hobbits) ->\n putStrLn $ drop 1 $ hobbits >>= printf \" %s\" . show\n\n\n\n\n", "positive_code": [{"source_code": "\nimport Data.Function\nimport List\n\nmain = readLn >>= putStrLn . solve\n\nsolve n = show k ++ \"\\n\" ++ unlines [unwords $ map (show . snd) day | day <- lst3 ] \n where\n k = last $ takeWhile (\\x -> x * (x - 1) `div` 2 <= n) [1..]\n lst = [(i, j) | i <- [1..k], j <- [1..i-1]]\n\n lst2 = concat [[(pi, i), (pj, i)] | (i, (pi, pj)) <- zip [1..] lst]\n\n lst3 = groupBy ((==) `on` fst) $ sort lst2\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Function\nimport Text.Printf\n\ncomb :: Integral b => b -> [a] -> [[a]]\ncomb 0 _ = [[]]\ncomb _ [] = []\ncomb n (x : xs) = map (x :) (comb (n - 1) xs) ++ comb n xs\n\nparticipants :: Int -> [[Int]]\nparticipants n = [[x, x] | x <- [1 .. n]]\n\nsolve :: Int -> [(Int, [Int])]\nsolve n = map ((,) <$> fst . head <*> map snd) . groupBy ((==) `on` fst) . sort $\n loop 3 (participants n)\n where\n loop days xs = case f [] (comb 2 [1 .. days]) xs of\n Nothing -> []\n Just (acc, xs') -> acc ++ loop (days + 1) xs'\n where\n f acc [] bss = Just (acc, bss)\n f _ _ [] = Nothing\n f acc (as : ass) (bs : bss) = f (zip as bs ++ acc) ass bss\n\nmain :: IO ()\nmain = do\n xs <- solve <$> readLn\n print $ length xs\n forM_ xs $ \\(_, hobbits) ->\n putStrLn $ drop 1 $ hobbits >>= printf \" %s\" . show\n\n\n\n\n"}], "src_uid": "e435a009962a7056d0fa00edb13ad01d"} {"source_code": "import qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport Data.Int\n\nsolve :: Int64 -> Int64 -> [Int64] -> [Int64] -> [Int64]\nsolve n m al bl = [query first bl,query last bl] \n where\n first = A.array (1,n) $ zip al [1..]\n last = A.array (1,n) $ zip (reverse al) [1..]\n query ary = L.foldl' (\\e k -> e + (ary A.! k)) 0\n\nmain :: IO ()\nmain = do n <- (getLine >>= return . read)\n al <- (getLine >>= return . map read . words)\n m <- (getLine >>= return . read)\n bl <- (getLine >>= return . map read . words)\n putStrLn . unwords . map show $ solve n m al bl\n", "positive_code": [{"source_code": "\nimport Array\n\nsolve :: Integer -> Array Int Int -> [Int] -> (Integer, Integer)\nsolve n array qs = foldl acc (0, 0) qs\n where\n acc (s1, s2) q = s1' `seq` s2' `seq` (s1', s2')\n where\n s1' = s1 + a\n s2' = s2 + n + 1 - a\n a = fromIntegral (array ! q)\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- fmap (map read . words) getLine\n getLine\n qs <- fmap (map read . words) getLine\n let (a, b) = solve n (array (1, fromIntegral n) (zip as [1..])) qs\n putStrLn $ concat [show a, \" \", show b]\n"}], "negative_code": [{"source_code": "import qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.List as L\nimport qualified Data.Maybe as Maybe\n\nsolve :: Int -> Int -> [Int] -> [Int] -> [Int]\nsolve n m al bl = [query firstMap bl,query lastMap bl] \n where\n firstMap = M.fromListWith (\\a b -> a) $ zip al [1..]\n lastMap = M.fromListWith (\\a b -> a) $ zip (reverse al) [1..]\n query m = L.foldl' (\\e k -> e + (Maybe.fromJust $ M.lookup k m)) 0\n\n\n\nmain :: IO ()\nmain = do n <- (getLine >>= return . read)\n al <- (getLine >>= return . map read . words)\n m <- (getLine >>= return . read)\n bl <- (getLine >>= return . map read . words)\n putStrLn . unwords . map show $ solve n m al bl\n"}], "src_uid": "b7aef95015e326307521fd59d4fccb64"} {"source_code": "module Main where\nimport Data.List\nimport Data.Monoid\nimport Data.Maybe\n\ndefault (Int)\n\nmain = interact exec\nexec = show . succ . fromJust . findIndex (\\(i, _) -> i == 1) . sortBy (\\(i1, s1) (i2, s2) -> compare s2 s1 `mappend` compare i1 i2) . zip [1..] . chunks . tail . map read . words\n where \n chunks (a:b:c:d:xs) = (a + b + c + d):chunks xs\n chunks [] = []\n", "positive_code": [{"source_code": "import Data.List\nf ::Int->[String]->[(Int,Int)]\nf _ []=[]\nf p (x:xs)=(sum ( map read (words x)::[Int]),-p):f (p+1) xs\n\ng ::Int->[(Int,Int)]->Int\ng ans ((_,(-1)):xs)=ans\ng ans (_:xs)=g (ans+1) xs\n\nmain = do\n e1<-getLine\n es<-getContents\n let n=read e1::Int\n xs=lines es\n ys=reverse $ sort $ f 1 xs\n print $ g 1 ys"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Prelude\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport Control.Monad\nimport Data.Ratio\nimport Data.Int\nimport Data.Functor\nimport Control.Monad.ST.Safe\nimport Data.STRef\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\n\n\nmain :: IO ()\nmain = do\n (n :: Int) <- read <$> getLine\n (arr :: [[Int]]) <- replicateM n ((map read . words) <$> getLine)\n let sortedArr = sortBy (\\(x1, y1) (x2, y2) -> comparing sum x2 x1 `mappend` compare y1 y2) $ zip arr [1..]\n printf \"%d\" $ (+ 1) $ fromJust $ findIndex (\\(_, y) -> y == 1) sortedArr"}, {"source_code": "import Data.List\nimport Data.Ord\nmain = interact $ show . succ . head . findIndices ((== 1) . snd) . sort . flip zip [1..] . map (Down . sum . map read . words) . tail . lines\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\tn <- read <$> getLine ::IO Int\n\ts <- map sum <$> map (map read ) <$> map words <$> replicateM n getLine:: IO [Int]\n\tlet j = head s\n\tprint $ 1+ length ( takeWhile (>j)(reverse (sort s)))\n\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(sortBy, findIndex)\nimport Data.Ord(comparing)\nimport Data.Maybe(fromJust)\n\nrank :: [[Int]] -> Int\nrank = (1+) . fromJust . findIndex (\\x -> fst x == 1) . sortBy (flip $ comparing snd) . zip [1..] . map sum\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let grades = map (map read . words) . lines $ contents\n print $ rank grades"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Prelude\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport Control.Monad\nimport Data.Ratio\nimport Data.Int\nimport Data.Functor\nimport Control.Monad.ST.Safe\nimport Data.STRef\nimport Data.Monoid\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\n\n\nmain :: IO ()\nmain = do\n (n :: Int) <- read <$> getLine\n (arr :: [[Int]]) <- replicateM n ((map read . words) <$> getLine)\n let sortedArr = sortBy (\\(x1, y1) (x2, y2) -> compare x2 x1 `mappend` compare y1 y2) $ zip arr [1..]\n printf \"%d\" $ fromJust $ findIndex (\\(_, y) -> y == 1) sortedArr"}, {"source_code": "import Data.List\nimport Data.Ord\nmain = interact $ show . unDown . fst . head . filter ((== 1) . snd) . sort . flip zip [1..] . map (Down . sum . map read . words) . tail . lines\nunDown (Down x) = x\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\tn <- read <$> getLine ::IO Int\n\ts <- map sum <$> map (map read ) <$> map words <$> replicateM n getLine:: IO [Int]\n\tlet j = head s\n\tprint $ 1+ length ( takeWhile (>j) (sort s))\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\tn <- read <$> getLine ::IO Int\n\ts <- map sum <$> map (map read ) <$> map words <$> replicateM n getLine:: IO [Int]\n\tlet j = head s\n\tprint $ 1+ length ( takeWhile (>j) s)\n\n"}], "src_uid": "3c984366bba580993d1694d27982a773"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nboolInt :: Bool -> Int\nboolInt p = if p then 1 else 0\n\nquery :: Int -> Int -> SIO Int\nquery li ri = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (B.char7 '?' : map B.intDec [li, ri])\n in do\n lift $ B.hPutBuilder stdout outBuilder >> hFlush stdout\n [response] <- readInts\n pure response\n\ngo :: Int -> Int -> Int -> SIO Int\ngo v li ri = let\n mi = div (li + ri) 2\n in if li + boolInt (elem v [li, ri]) == ri\n then pure $ if v == li\n then ri\n else li\n else if v < li\n then do\n resp <- query v mi\n if resp == v\n then go v li mi\n else go v (mi+1) ri\n else if ri < v\n then do\n resp <- query (mi+1) v\n if resp == v\n then go v (mi+1) ri\n else go v li mi\n else do\n let\n innermi = mi + boolInt (v <= mi) - boolInt (even $ ri - li)\n lower = v <= innermi\n resp <- if lower then query li innermi else query (innermi+1) ri\n if (resp == v) == lower\n then go v li innermi\n else go v (innermi+1) ri\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n] <- readInts\n sndMin <- query 1 n\n ans <- go sndMin 1 n\n lift $ B.hPutBuilder stdout\n $ B.char7 '!' <> B.char7 ' ' <> B.intDec ans <> B.char7 '\\n'\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\n------\n\ngetInt = fst . fromJust . B.readInt . dropCR <$> B.getLine\n\nask l r = do\n B.putStrLn $ B.unwords [\"?\", bshow (l + 1), bshow r]\n hFlush stdout\n (subtract 1) <$> getInt\n\nanswer i = do\n B.putStrLn $ B.unwords [\"!\", bshow (i + 1)]\n hFlush stdout\n\nmain = do\n n <- getInt\n p <- ask 0 n\n let r = sortOn (\\(i, j) -> i - j) $\n filter (\\(i, j) -> i /= j) [(0, p), (p + 1, n)]\n case r of\n [(i, j)] -> go p i j\n [(i, j), (k, l)]\n | i < p -> do q <- ask i (p + 1)\n if p == q\n then go p i j\n else go p k l\n | otherwise -> do q <- ask p j\n if p == q\n then go p i j\n else go p k l\n\n\ngo p i j | i < p = lgo i j p\n | otherwise = rgo p i j\n\n\nlgo i j p | j - i == 1 = answer i\n | otherwise = let k = (i + j) `quot` 2 in\n do q <- ask k (p + 1)\n if p == q\n then lgo k j p\n else lgo i k p\n\n\nrgo p i j | j - i == 1 = answer i\n | otherwise = let k = (i + j) `quot` 2 in\n do q <- ask p k\n if p == q\n then rgo p i k\n else rgo p k j\n"}], "negative_code": [], "src_uid": "eb660c470760117dfd0b95acc10eee3b"} {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash (Hash l1h l1g h1 g1) (Hash l2h l2g h2 g2) = Hash (l1h * l2h) (l1g * l2g) (h1 * l1h + h2) (g1 * l1g + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree (Bool, Tree {- incremented -})\n deriving Show\n\nprimHash = uncurry (Hash (2^64) (2^64)) . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _ _) = h\n\nnode :: Tree -> Tree -> Tree\nnode t1 t2 =\n let res = Node (mkHash (hash t1) (hash t2)) t1 t2 (doIncrement1 res) in res\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b _) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\ni1k t1 (False, t2) = (False, node t1 t2)\ni1k t1 (True, t2) = case increment1 t1 of\n (c, t1) -> (c, node t1 t2)\n\ndoIncrement1 :: Tree -> (Bool, Tree)\ndoIncrement1 (Leaf x) = let x' = x + 1 in (x' < x, Leaf x')\ndoIncrement1 (Node h t1 t2 _) = i1k t1 (increment1 t2)\n\nincrement1 (Leaf x) = doIncrement1 (Leaf x)\nincrement1 (Node _ _ _ x) = x\n\nincrement0 :: Int -> Int -> Tree -> (Bool, Tree)\nincrement0 capacity index0 (Leaf x) = let x' = x + (2 ^ index0) in (x' < x, Leaf x')\nincrement0 capacity 0 (Node _ _ _ inced) = inced\nincrement0 capacity index0 (Node h t1 t2 _) | index0 < capacity `div` 2 =\n i1k t1 (increment0 cap2 index0 t2)\n | otherwise = case increment0 cap2 (index0 - cap2) t1 of\n (c, t1) -> (c, node t1 t2)\n where cap2 = capacity `div` 2\n\ninstance Eq Tree where\n Leaf x == Leaf y = x == y \n Node h1 _ _ _ == Node h2 _ _ _ = h1 == h2\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1 _) (Node h2 l2 r2 _)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n-- myCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path)\n -> (node -> [(road, node)])\n -> node\n -> Set (path, [node])\n -> Set node\n -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\n-- levels = reverse $ take (17 - 6) $ drop 1 $ iterate (\\(Hash a b) -> Hash (a*a) (b*b)) (Hash (2^64) (2^64))\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment0 (2 ^ 17) i t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * (2 ^ 64) + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n\net = fullTree 3\n", "positive_code": [{"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree\n deriving Show\n\nprimHash = uncurry Hash . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Hash -> Tree -> Tree -> Tree\nnode l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node (Hash 0 0) x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\ndiv2h = Hash (recip 2) (recip 2)\nhd2 (Hash a b) = case div2h of\n (Hash c d) -> Hash (a * c) (b * d)\n\nincrement :: [Hash] -> Int -> Int -> Tree -> (Bool, Tree)\nincrement _levels capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' < x, Leaf x')\nincrement (level : levels) capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment levels (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node level t1 t2)\n (True, t2) -> case increment levels (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node level t1 t2)\n | otherwise = case increment levels (capacity `div` 2) index t1 of\n (c, t1) -> (c, node level t1 t2)\n\ninstance Eq Tree where\n Leaf x == Leaf y = x == y \n Node h1 _ _ == Node h2 _ _ = h1 == h2\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n-- myCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path)\n -> (node -> [(road, node)])\n -> node\n -> Set (path, [node])\n -> Set node\n -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nlevels = reverse $ take (17 - 6) $ drop 1 $ iterate (\\(Hash a b) -> Hash (a*a) (b*b)) (Hash (2^64) (2^64))\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment levels (2 ^ 17) (2 ^ 17 - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * (2 ^ 64) + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n\net = fullTree 3\n\n{- tr1 = snd $ increment (Hash (2^9) (2^9)) (2^9) (2^9 - 1 - 64) et\ntr2 = snd $ increment (Hash (2^9) (2^9)) (2^9) (2^9 - 1 - 7) et -}\n"}], "negative_code": [{"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree\n deriving Show\n\nprimHash = uncurry Hash . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Hash -> Tree -> Tree -> Tree\nnode l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\np2h n = Hash (2^n) (2^n)\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node (p2h n) x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\ndiv2h = Hash (recip 2) (recip 2)\nhd2 (Hash a b) = case div2h of\n (Hash c d) -> Hash (a * c) (b * d)\n\nincrement :: Hash -> Int -> Int -> Tree -> (Bool, Tree)\nincrement level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' < x, Leaf x')\nincrement level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (hd2 level) (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node level t1 t2)\n (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node level t1 t2)\n | otherwise = case increment level (capacity `div` 2) index t1 of\n (c, t1) -> (c, node level t1 t2)\n\ninstance Eq Tree where\n Leaf x == Leaf y = x == y \n Node h1 _ _ == Node h2 _ _ = h1 == h2\n _ == _ = False\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n-- myCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment (Hash (2^17) (2^17)) (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * (2 ^ 64) + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 ((x * y) `mod` moddd)\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\ndata Hash = Hash Int Mod1b7 deriving (Eq, Show, Ord)\n\nmkHash (Hash l1 h1) (Hash l2 h2) = Hash (l1 + l2) (h1 * (2 ^ l1) + h2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node !Hash !Tree !Tree\n deriving Show\n\nprimHash = Hash 1 . fromIntegral\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Tree -> Tree -> Tree\nnode t1 t2 = Node (mkHash (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node x x\n \ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\nincrement :: Int -> Int -> Tree -> (Bool, Tree)\nincrement capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')\nincrement capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node t1 t2)\n (True, t2) -> case increment (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node t1 t2)\n | otherwise = case increment (capacity `div` 2) index t1 of\n (c, t1) -> (c, node t1 t2)\n\ninstance Eq Tree where\n x == y = compare x y == EQ\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * 2 + fromIntegral x) 0\n\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree\n deriving Show\n\nprimHash = uncurry Hash . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Hash -> Tree -> Tree -> Tree\nnode l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\np2h n = Hash (2^n) (2^n)\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node (Hash 0 0) x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\ndiv2h = Hash (recip 2) (recip 2)\nhd2 (Hash a b) = case div2h of\n (Hash c d) -> Hash (a * c) (b * d)\n\nincrement :: Hash -> Int -> Int -> Tree -> (Bool, Tree)\nincrement level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' < x, Leaf x')\nincrement level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (hd2 level) (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node level t1 t2)\n (True, t2) -> case increment (hd2 level) (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node level t1 t2)\n | otherwise = case increment (hd2 level) (capacity `div` 2) index t1 of\n (c, t1) -> (c, node level t1 t2)\n\ninstance Eq Tree where\n Leaf x == Leaf y = x == y \n Node h1 _ _ == Node h2 _ _ = h1 == h2\n _ == _ = False\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n-- myCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment (Hash (2^17) (2^17)) (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * (2 ^ 64) + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `mod` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `mod` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `mod` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash l (Hash h1 g1) (Hash h2 g2) = Hash (h1 * (2 ^ l) + h2) (g1 * (2 ^ l) + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree\n deriving Show\n\nprimHash = uncurry Hash . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Int -> Tree -> Tree -> Tree\nnode l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node n x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\nincrement :: Int -> Int -> Int -> Tree -> (Bool, Tree)\nincrement level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')\nincrement level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment level (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node level t1 t2)\n (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node level t1 t2)\n | otherwise = case increment level (capacity `div` 2) index t1 of\n (c, t1) -> (c, node level t1 t2)\n\ninstance Eq Tree where\n x == y = compare x y == EQ\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\nmyCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment 17 (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * 2 + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 ((x * y) `mod` moddd)\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\ndata Hash = Hash Int Mod1b7 deriving (Eq, Show, Ord)\n\nmkHash (Hash l1 h1) (Hash l2 h2) = Hash (l1 + l2) (h1 * (2 ^ l1) + h2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node !Hash !Tree !Tree\n deriving Show\n\nprimHash = Hash 1 . fromIntegral\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Tree -> Tree -> Tree\nnode t1 t2 = Node (mkHash (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node x x\n \ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\nincrement :: Int -> Int -> Tree -> (Bool, Tree)\nincrement capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')\nincrement capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node t1 t2)\n (True, t2) -> case increment (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node t1 t2)\n | otherwise = case increment (capacity `div` 2) index t1 of\n (c, t1) -> (c, node t1 t2)\n\ninstance Eq Tree where\n x == y = compare x y == EQ\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * 2 + fromIntegral x) 0\n\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n print \"hi\"\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree\n deriving Show\n\nprimHash = uncurry Hash . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Hash -> Tree -> Tree -> Tree\nnode l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\np2h n = Hash (2^n) (2^n)\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node (p2h n) x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\ndiv2h = Hash (recip 2) (recip 2)\nhd2 (Hash a b) = case div2h of\n (Hash c d) -> Hash (a * c) (b * d)\n\nincrement :: Hash -> Int -> Int -> Tree -> (Bool, Tree)\nincrement level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')\nincrement level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (hd2 level) (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node level t1 t2)\n (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node level t1 t2)\n | otherwise = case increment level (capacity `div` 2) index t1 of\n (c, t1) -> (c, node level t1 t2)\n\ninstance Eq Tree where\n Leaf x == Leaf y = x == y \n Node h1 _ _ == Node h2 _ _ = h1 == h2\n _ == _ = False\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n-- myCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment (Hash (2^17) (2^17)) (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * 2 + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 ((x * y) `mod` moddd)\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 deriving (Eq, Show, Ord)\n\nmkHash l (Hash h1) (Hash h2) = Hash (h1 * (2 ^ l) + h2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree\n deriving Show\n\nprimHash = Hash . fromIntegral\n\nhash (Leaf x) = primHash x\nhash (Node h _ _) = h\n\nnode :: Int -> Tree -> Tree -> Tree\nnode l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2\n\ninits :: [a] -> [[a]]\ninits xs =\n [] : case xs of\n [] -> []\n x : xs' -> map (x :) (inits xs')\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node n x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\nincrement :: Int -> Int -> Int -> Tree -> (Bool, Tree)\nincrement level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')\nincrement level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment level (capacity `div` 2) (index - capacity `div` 2) t2 of\n (False, t2) -> (False, node level t1 t2)\n (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of\n (c, t1) -> (c, node level t1 t2)\n | otherwise = case increment level (capacity `div` 2) index t1 of\n (c, t1) -> (c, node level t1 t2)\n\ninstance Eq Tree where\n x == y = compare x y == EQ\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1) (Node h2 l2 r2)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\nmyCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment 17 (2 ^ (17)) (2 ^ (17) - 1 - i) t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * 2 + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n"}, {"source_code": "import Data.Word\nimport Data.Int\nimport Data.Bits\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Set(Set)\n\nnewtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)\n\ninstance Show Mod1b7 where\n show (Mod1b7 x) = show x\n\nmoddd :: Num x => x\nmoddd = 10^9 + 7\ninstance Num Mod1b7 where\n Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)\n Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))\n fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)\n negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)\n\ninstance Fractional Mod1b7 where\n recip x = x ^ (moddd - 2)\n\nnewtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)\n\ninstance Show Mod1b9 where\n show (Mod1b9 x) = show x\n\nmoddd9 :: Num x => x\nmoddd9 = 10^9 + 9\ninstance Num Mod1b9 where\n Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)\n Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))\n fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)\n negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)\n\ninstance Fractional Mod1b9 where\n recip x = x ^ (moddd9 - 2)\n\ndata Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)\n\nmkHash (Hash l1h l1g h1 g1) (Hash l2h l2g h2 g2) = Hash (l1h * l2h) (l1g * l2g) (h1 * l1h + h2) (g1 * l1g + g2)\n\ndata Tree =\n Leaf !Word64 {- 64 bools -}\n | Node {-# UNPACK #-} !Hash !Tree !Tree (Bool, Tree {- incremented -})\n deriving Show\n\nprimHash = uncurry (Hash 2 2) . (fromIntegral &&& fromIntegral)\n\nhash (Leaf x) = primHash x\nhash (Node h _ _ _) = h\n\nnode :: Tree -> Tree -> Tree\nnode t1 t2 =\n let res = Node (mkHash (hash t1) (hash t2)) t1 t2 (doIncrement1 res) in res\n\nfullTree 0 = Leaf 0\nfullTree n = let x = fullTree (n - 1) in node x x\n\ntoDList (Leaf x) = (x:)\ntoDList (Node _ a b _) = toDList a . toDList b\n\ntoList = ($[]) . toDList\n\ni1k t1 (False, t2) = (False, node t1 t2)\ni1k t1 (True, t2) = case increment1 t1 of\n (c, t1) -> (c, node t1 t2)\n\ndoIncrement1 :: Tree -> (Bool, Tree)\ndoIncrement1 (Leaf x) = let x' = x + 1 in (x' < x, Leaf x')\ndoIncrement1 (Node h t1 t2 _) = i1k t1 (increment1 t2)\n\nincrement1 (Leaf x) = doIncrement1 (Leaf x)\nincrement1 (Node _ _ _ x) = x\n\nincrement0 :: Int -> Int -> Tree -> (Bool, Tree)\nincrement0 capacity index0 (Leaf x) = let x' = x + (2 ^ index0) in (x' < x, Leaf x')\nincrement0 capacity 0 (Node _ _ _ inced) = inced\nincrement0 capacity index0 (Node h t1 t2 _) | index0 < capacity `div` 2 =\n i1k t1 (increment0 cap2 index0 t2)\n | otherwise = case increment0 cap2 (index0 - cap2) t1 of\n (c, t1) -> (c, node t1 t2)\n where cap2 = capacity `div` 2\n\ninstance Eq Tree where\n Leaf x == Leaf y = x == y \n Node h1 _ _ _ == Node h2 _ _ _ = h1 == h2\n\nmyCompare (Leaf a) (Leaf b) = compare a b\nmyCompare (Node h1 l1 r1 _) (Node h2 l2 r2 _)\n | h1 == h2 = EQ\n | otherwise = case myCompare l1 l2 of\n EQ -> myCompare r1 r2\n LT -> LT\n GT -> GT\n-- myCompare _ _ = LT\n\nmyCompare2 x y = myCompare x y\n\ninstance Ord Tree where\n compare = myCompare2\n\ndijkstra :: (Ord path, Ord road, Eq node, Ord node) =>\n (path -> road -> path)\n -> (node -> [(road, node)])\n -> node\n -> Set (path, [node])\n -> Set node\n -> Maybe (path, [node])\ndijkstra append edges destination queue visited =\n case Set.minView queue of\n Nothing -> Nothing\n Just ((path, nodes@(node : _)), queue)\n | node == destination -> Just (path, nodes)\n | Set.member node visited -> dijkstra append edges destination queue visited\n | otherwise ->\n dijkstra append edges destination\n (foldl (\\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])\n (Set.insert node visited)\n\n\nnewtype Road = Road Int deriving (Eq, Ord)\n\n-- levels = reverse $ take (17 - 6) $ drop 1 $ iterate (\\(Hash a b) -> Hash (a*a) (b*b)) (Hash (2^64) (2^64))\n\nappend :: Tree -> Road -> Tree\nappend t (Road i) = case increment0 (2 ^ 17) i t of\n (False, t) -> t\n\nreadInts = map (foldl (\\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine\n\ntoMod :: [Word64] -> Mod1b7\ntoMod = foldl (\\a x -> a * (2 ^ 64) + fromIntegral x) 0\n\npp :: Maybe (Mod1b7, [Int]) -> IO ()\npp Nothing = print (-1)\npp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))\n\nmain = do\n [n,m] <- readInts\n edges <- replicateM m $ do\n [u,v,x] <- readInts\n return (u,v,x)\n [s,t] <- readInts\n let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])\n pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty\n\net = fullTree 3\n"}], "src_uid": "e2cdcfde0d5585cb6c40473fb1c48499"} {"source_code": "input :: Int -> [String] -> IO ([String])\ninput 0 s = return s\ninput i s = do\n nexts <- getLine\n input (i-1) (s ++ [nexts])\n\ntoints :: [String] -> [[Int]]\ntoints dat = map ((map read).words) dat\n\nsolve :: Int -> [[Int]] -> Int -> Int\nsolve _ [] _ = 0\nsolve start ([f, t]:lst) step\n | start + step <= f = solve (start+step) ([f,t]:lst) step\n | start > t = solve start lst step\n | otherwise = 1 + solve (start+1) ([f,t]:lst) step\n\n\nmain = do\n inp <- getLine\n let [n, x] = map read (words inp)\n dat <- input n []\n let res = toints dat\n-- mapM_ print (res)\n print (solve 1 res x)", "positive_code": [{"source_code": "import Data.Functor\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\n\nmain = getInts >>= putStrLn . show . solve\n\nsolve :: [Int] -> Int\nsolve (n:x:rs) = solve' x 0 rs\n\nsolve' x t [] = 0\nsolve' x t (l:r:rs) = (r-l+1) + mod (l-t-1) x + solve' x r rs\n"}, {"source_code": "import Control.Monad\nsolution x l = best l + wait x l\nbest = sum.map (uncurry subtract)\nwait x l = sum $ map (flip mod x) $ zipWith subtract (map snd l) $ tail $ map fst l\nreadPair = fmap (l2p.map read.words) getLine where l2p [x,y] = (x,y)\nmain = do\n (n,x) <- readPair\n l <- replicateM n readPair\n print $ solution x $ (1,1):map (fmap (+1)) l"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\n\nmain :: IO ()\nmain = do\n [n, x] <- readIntsIO\n lrs <- replicateM n readIntsIO\n print $ solve x lrs\n\nsolve :: Int -> [[Int]] -> Int\nsolve x = go 0 0\n where\n go acc _ [] = acc\n go acc curr ([l, r]:lrs') = go (acc + timeToSkip curr l + (r - l + 1)) r lrs'\n timeToSkip curr next = mod (next - curr - 1) x\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n"}, {"source_code": "import Data.List\n\nmain = do\n contents <- getContents\n let allLines = lines contents\n let firstLineOfContentAsList = words $ head allLines\n --let nExcitingTimeFrames = firstLineOfContentAsList !! 0\n let skipThisLengthByRemote = read $ firstLineOfContentAsList !! 1\n let excitingTimeFrames = readTimeFrames $ tail allLines\n let lastExcitingFrameEndPoints = map (\\(x, y) -> y) $ (0, 0) : init excitingTimeFrames\n let timesCannotSkip = sum $ zipWith (\\x (y, z) -> calculateTimeCannotSkip skipThisLengthByRemote x y z) lastExcitingFrameEndPoints excitingTimeFrames\n let timesForWatching = foldl' (\\acc (leftTimePoint, rightTimePoint) -> rightTimePoint - leftTimePoint + 1 + acc) 0 excitingTimeFrames\n let minimunTimeSpend = timesCannotSkip + timesForWatching\n print minimunTimeSpend\n\nreadTimeFrames :: [String] -> [(Int, Int)]\nreadTimeFrames [] = []\nreadTimeFrames (lineToProcess:remainLines) = (twoWordsToTwoInts $ words lineToProcess) : (readTimeFrames remainLines)\n\ntwoWordsToTwoInts :: [String] -> (Int, Int)\ntwoWordsToTwoInts (firstWord:secondWord:remain) = (read firstWord, read secondWord)\n\ncalculateTimeCannotSkip :: Int -> Int -> Int -> Int -> Int\ncalculateTimeCannotSkip skipThisLengthByRemote lastExcitingTimeFrameEndsHere nextExcitingTimeFrameStartsHere nextExcitingTimeFrameEndsHere = (nextExcitingTimeFrameStartsHere - 1 - lastExcitingTimeFrameEndsHere) `mod` skipThisLengthByRemote\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve (x:xs) = go 0 xs\n where go t zs@(l:r:ys) | t + x < l = go (t + x) zs\n | otherwise = r - t + go r ys\n go _ _ = 0\nsolve _ = undefined\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Integer]] -> Integer\nsolve ([_, x]:xs) = go 0 xs\n where go t lrlrs@([ l, r ] : lrs) | t + x < l = go (t + x) lrlrs\n | otherwise = r - t + go r lrs\n go _ _ = 0\nsolve _ = undefined\n"}, {"source_code": "input 0 s = return s\ninput i s = do\n nexts <- getLine\n input (i - 1) (s ++ [nexts])\n\ntointlist :: [String] -> [[Int]]\ntointlist [] = []\ntointlist l = do\n let f = map read $ words $ head l\n let s = tointlist $ tail l\n return f ++ s\n\nlocalAnswer :: Int -> Int -> Int\nlocalAnswer interval val = (quot interval val) * val\n\ngetAnswer :: Int -> Int -> [[Int]] -> Int\ngetAnswer start x [] = 0\ngetAnswer start x ([l, r]:ys)\n | x > l - start = l - start + r - l + 1 + getAnswer (r + 1) x ys\n | otherwise = getAnswer (start + localAnswer (l - start) x) x ([l, r]:ys)\n\nmain = do\n inp <- getLine\n let [n, x] = map read $ words inp\n interest <- input n []\n let val = getAnswer 1 x $ tointlist interest\n print val"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess _ _ [] a =a\nprocess m n (s1:s2:ss) a = process m s2 ss (a+(mod (s1-n-1) m) + s2-s1+1)\t\n\nmain= do\n\t[n,m]<-map read.words <$>getLine ::IO [Int]\t\n\ts<- map read. words <$>getContents\t\n\tprint $ process m 0 s 0\n\t\n \n\t \n\t "}, {"source_code": "\nmain = do\n\tt<-getLine\n\trest<-getContents\n\tlet [n,x] = map read $ words t\n\tlet dat = map (map read) $ map words $ lines rest\n\tputStrLn $ show $ solve 1 x 0 dat\n\n\nsolve cur step all [] = all\nsolve cur step all (m:ms) | head m - cur >=step = solve (cur+step) step (all) (m:ms)\n | head m - cur < step = solve (last m+1) step (all+last m - cur+1) ms\n "}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:x:seg) = solve' 0 seg\n where\n solve' :: Int -> [Int] -> Int\n solve' _ [] = 0\n solve' last (l:r:ss) = (mod (l-last-1) x) + (r-l+1) + (solve' r ss)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, x] <- getInts\n lrs <- replicateM n getInts\n\n let\n count c [] = 0\n count c ([l, r]:lrs) =\n (l-c) `mod` x + (r-l+1) + count (r+1) lrs\n\n print $ count 1 lrs\n"}], "negative_code": [{"source_code": "\nmain = do\n\tt<-getLine\n\trest<-getContents\n\tlet [n,x] = map read $ words t\n\tlet dat = map (map read) $ map words $ lines rest\n\tputStrLn $ show $ solve 1 x 1 dat\n\n\nsolve cur step all [] = all\nsolve cur step all (m:ms) | head m - cur >=step = solve (cur+step) step (all) (m:ms)\n | head m - cur < step = solve (last m) step (all+last m - cur) ms\n | otherwise = solve (last m) step (all+ last m - cur) ms"}, {"source_code": "import Control.Monad\nsolution x l = best l + wait x l\nbest = sum.map ((+1).uncurry subtract)\nwait x l = sum $ map (flip mod x) $ zipWith subtract (map snd l) $ tail $ map fst l\nreadPair = fmap (l2p.map read.words) getLine where l2p [x,y] = (x,y)\nmain = do\n (n,x) <- readPair\n l <- replicateM n readPair\n print $ solution x $ (2,1):l"}, {"source_code": "import Control.Monad\nsolution x l = best l + wait x l\nbest = sum.map ((+1).uncurry subtract)\nwait x l = sum $ map (flip mod x) $ zipWith subtract (map snd l) $ tail $ map fst l\nreadPair = fmap (l2p.map read.words) getLine where l2p [x,y] = (x,y)\nmain = do\n (n,x) <- readPair\n l <- replicateM n readPair\n print $ solution x l"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\n\nmain :: IO ()\nmain = do\n [n, x] <- readIntsIO\n lrs <- replicateM n readIntsIO\n print $ solve x lrs\n\nsolve :: Int -> [[Int]] -> Int\nsolve x = go 0 (-1)\n where\n go acc _ [] = acc\n go acc curr ([l, r]:lrs') = go (acc + timeToSkip curr l + (r - l + 1)) r lrs'\n timeToSkip curr next = mod (next - curr - 1) x\n\nreadIntsIO :: IO [Int]\nreadIntsIO = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess _ _ [] a =a\nprocess m n (s1:s2:ss) a = process m s2 ss (a+(mod (s1-n-1) 3) + s2-s1+1)\t\nmain= do\n\t[n,m]<-map read.words <$>getLine ::IO [Int]\t\n\ts<- map read. words <$>getContents\t\n\tprint $ process m 0 s 0\n\t\n \n\t \n\t "}], "src_uid": "ac33b73da5aaf2139b348a9c237f93a4"} {"source_code": "import Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n\nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\n\\t\")\n\nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k a = (sum a) - (k * (k - 1) `div` 2) + k * (n - 1) - sum (take k $ reverse $ sort [elem + ind | (elem, ind) <- zip a [0..]])\n\nmainLoop 0 = return ()\nmainLoop t = do firstLine <- BS.getLine\n secondLine <- BS.getLine\n let [n, k] = readInts firstLine\n let a = readInts secondLine\n print (solve n k a)\n mainLoop (t - 1)\n\nmain = do t <- (readLn :: IO Int)\n mainLoop t\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n, k] <- getInts\n as <- map fromIntegral <$> getInts\n let bs = scanl' (+) 0 $ reverse $ sort $ zipWith (\\i a -> a - fromIntegral n + i) [1..] as\n optimal = maximum $ take (k + 1) $ zipWith (\\i a -> i * (i - 1) `div` 2 + a) [0..] bs\n return $ int64Dec (sum as - optimal) <> charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "66daa3864875e48d32a7acd23bd7a829"} {"source_code": "main :: IO ()\nmain = do\n t <- readLn \n routine t\n\nroutine :: Int -> IO ()\nroutine t\n | t > 1 = do\n solve\n routine (t-1)\n | t == 1 = solve\n\nsolve :: IO()\nsolve = do\n [n,x] <- map read.words <$> getLine\n xs <- map read.words <$> getLine\n putStrLn (if possible n x xs then \"Yes\" else \"No\")\n \npossible :: Int -> Int -> [Int] -> Bool\npossible n x xs\n | x == n = odd (sum xs)\n | otherwise = do\n let a = take x xs\n let b = drop x xs\n if even (sum a) then ((any even a) && (any odd b)) || ((any odd a) && (any even b))\n else True\n", "positive_code": [{"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,x] <- (map read.words) <$> getLine\n xs <- (map read.words) <$> getLine\n putStrLn $ if solve n x xs then \"Yes\" else \"No\"\n\nsolve :: Int -> Int -> [Int] -> Bool\nsolve n x xs\n | n == x = odd $ sum xs\n | otherwise = b || (odd $ sum $ take x xs)\n where\n b = (any odd xs) && (any even xs)\n"}, {"source_code": "-- as <- getLine\n-- putStrLn (show (foldr (+) 0 (map read (words as))))\n\ngetNums :: IO [Int]\ngetNums = do\n nums <- getLine\n return (map (read :: String -> Int) $ (words nums))\n\ngetNum = do\n num <- getLine\n return (read num :: Int)\n\ntuplify2 [x, y] = (x, y)\n\nrepeatAction 0 _ = return ()\nrepeatAction n action = do\n action\n repeatAction (n - 1) action\n\nanswer cap o e target =\n if o > fst cap then False\n else if o + e == target then True\n else if e + 1 > snd cap then answer cap (o + 2) 0 target\n else answer cap o (e + 1) target\n\nbody = do\n params <- getNums\n values <- getNums\n\n let (n, x) = tuplify2 params\n let odds = foldr (+) 0 $ map (fromEnum . odd) values\n let evens = n - odds\n let evensFromOdds = odds `div` 2\n\n putStrLn $ if answer (odds, evens) 1 0 x then \"Yes\"\n else \"No\"\n\n return ()\n\nmain = do\n t <- getNum\n repeatAction t body\n "}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n, x] <- (map read.words) <$> getLine\n xs <- (map read.words) <$> getLine\n putStrLn $ if (solve x xs) then \"No\" else \"Yes\"\n\nsolve :: Int -> [Int] -> Bool\nsolve x a = \n let evens = length $ filter (\\x->mod x 2 ==0) a in \n let odds = length a - evens in \n let min_odds = if (evens > x) then 0 else (x - evens) in \n let max_odds = min x odds in \n (min_odds == max_odds) && (mod min_odds 2 == 0)"}, {"source_code": "count :: [Int] -> Int -> Int\ncount [] n = n\ncount (x : list) n = count list (n + (mod x 2))\nwhile i = do\n if i == 0 then\n return 0\n else do\n input1 <- getLine\n input2 <- getLine\n let [n, x] = map read (words input1) :: [Int]\n let list = map read (words input2) :: [Int]\n --print count list\n let od = count list 0\n let ev = n - od\n if ev >= x then\n if od > 0 then\n putStrLn \"Yes\"\n else\n putStrLn \"No\"\n else do\n let d = x - ev\n if (mod d 2) == 1 then\n putStrLn \"Yes\"\n else if od > d && ev > 0 then\n putStrLn \"Yes\"\n else\n putStrLn \"No\"\n while (i - 1)\nmain = do\n input <- getLine\n let tests = read input :: (Int)\n while tests"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n--import Debug.Trace\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let _:tokens = read <$> split input :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n:k:rest0 ->\n let (vals, rest1) = splitAt n rest0\n anyOdd = any (\\x -> x `mod` 2 == 1) vals\n anyEven = any (\\x -> x `mod` 2 == 0) vals\n sumParity = foldl (+) 0 vals `mod` 2\n hasChoice = k < n\n res = if\n | hasChoice -> anyOdd && (anyEven || k `mod` 2 == 1)\n | otherwise -> sumParity == 1\n in Just (if res then \"Yes\" else \"No\", rest1)\n ) tokens\n sequence_ $ putStrLn <$> res\n"}, {"source_code": "import Data.List (unfoldr)\nimport qualified Data.ByteString.Lazy as L\nimport Data.ByteString.Lazy.Char8 (readInt)\nimport Prelude hiding (span, dropWhile)\nimport Data.Word (Word8)\n\nnewLine :: Word8\nnewLine = 0x0a\nspace :: Word8\nspace = 0x20\n\nskipLine :: L.ByteString -> L.ByteString\nskipLine = L.dropWhile (== newLine) . L.dropWhile (/= newLine)\n\nreadIntLine :: L.ByteString -> ([Int], L.ByteString)\nreadIntLine str = let\n (currLine, lf) = L.span (/= newLine) str\n (_, rest) = L.span (== newLine) lf\n in (unfoldr (readInt . L.dropWhile (== space)) currLine, rest)\n\nparseCase :: L.ByteString -> Maybe (([Int], Int), L.ByteString)\nparseCase str = case readIntLine str of\n ([_n, x], xs1) -> Just ((a, x), xs2) where\n (a, xs2) = readIntLine xs1\n _ -> Nothing\n\nsolve :: ([Int], Int) -> Bool\nsolve (a, x) = let\n (n, k) = go 0 0 a\n go p q [] = (p, q)\n go p q (w:ws) = seq (seq p q) $ go (p+1) (if odd w then q + 1 else q) ws\n in\n case () of\n ()\n | k == n -> odd x\n | k == 0 -> False\n | x == n -> odd k\n | x == 0 -> False\n | otherwise -> True\n\n\npprint :: Bool -> String\npprint True = \"Yes\\n\"\npprint False = \"No\\n\"\n\nmain :: IO ()\nmain = (putStr . concatMap (pprint . solve) . unfoldr parseCase . skipLine)\n =<< L.getContents\n"}, {"source_code": "groupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n strings = (take n strings):(groupByNLines n (drop n strings))\n\nparse :: [String] -> String\nparse [l, arr']\n | solve arr x = \"YES\"\n | otherwise = \"NO\"\n where arr = map (\\x -> read x :: Integer) $ words arr'\n [_, x] = map (\\x -> read x :: Integer) $ words l\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n\npossibilities :: Integer -> [(Integer, Integer)]\npossibilities n = [(i, n-i) | i <- [0..n], odd (n-i)]\n\nsolve :: [Integer] -> Integer -> Bool\nsolve arr x = length (filter (\\(e, o) -> numberOfOdd >= o && numberOfEven >= e) pos) > 0\n where numberOfOdd = toInteger $ length $ filter odd arr\n numberOfEven = toInteger $ length $ filter even arr\n pos = possibilities x\n"}], "negative_code": [{"source_code": "-- as <- getLine\n-- putStrLn (show (foldr (+) 0 (map read (words as))))\n\ngetNums :: IO [Int]\ngetNums = do\n nums <- getLine\n return (map (read :: String -> Int) $ (words nums))\n\ngetNum = do\n num <- getLine\n return (read num :: Int)\n\ntuplify2 [x, y] = (x, y)\n\nrepeatAction 0 _ = return ()\nrepeatAction n action = do\n action\n repeatAction (n - 1) action\n\nbody = do\n params <- getNums\n values <- getNums\n\n let (n, x) = tuplify2 params\n let odds = foldr (+) 0 $ map (fromEnum . odd) values\n let evens = n - odds\n let evensFromOdds = odds `div` 2\n\n putStrLn $ if odds >= 1 && evens >= x - 1 || \n (odd odds) && evens + evensFromOdds >= x - 1 ||\n (odds >= 2) && evens + evensFromOdds - 1 >= x - 1\n then \"Yes\"\n else \"No\"\n\n return ()\n\nmain = do\n t <- getNum\n repeatAction t body\n "}, {"source_code": "hasEven :: [Integer] -> Bool\nhasEven arr = not $ null $ filter even arr\n\nhasOdd :: [Integer] -> Bool\nhasOdd arr = not $ null $ filter odd arr\n\nwithoutAnEven :: [Integer] -> [Integer]\nwithoutAnEven arr = (takeWhile odd arr) ++ (tail (dropWhile odd arr))\n\nwithoutAnOdd :: [Integer] -> [Integer]\nwithoutAnOdd arr = (takeWhile even arr) ++ (tail (dropWhile even arr))\n\natLeastTwoOdd :: [Integer] -> Bool\natLeastTwoOdd arr = (length $ filter odd arr) >= 2\n\n\nsolve :: Integer -> [Integer] -> Bool\nsolve 1 arr = hasOdd arr\nsolve x arr\n | null arr = False\n | x <= 0 = False\n | hasEven arr = solve (x-1) (withoutAnEven arr)\n | atLeastTwoOdd arr = solve (x-2) (withoutAnOdd $ withoutAnOdd arr)\n | hasOdd arr = solve (x-1) (withoutAnOdd arr)\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n strings = (take n strings):(groupByNLines n (drop n strings))\n\nparse :: [String] -> String\nparse [l, arr']\n | solve x arr = \"YES\"\n | otherwise = \"NO\"\n where arr = map (\\x -> read x :: Integer) $ words arr'\n [_, x] = map (\\x -> read x :: Integer) $ words l\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n"}], "src_uid": "afce38aa7065da88d824d1d981b5b338"} {"source_code": "module Main where\n\nimport Data.List\nimport qualified Data.HashMap.Strict as H\n\nsolve :: [Int] -> [Int]\nsolve ns = go H.empty (zip [1..] ns)\n where\n go :: H.HashMap Int ([Int], Int) -> [(Int, Int)] -> [Int]\n go h [] = reverse $ fst $ snd $ maximumBy (\\(_, (_, a)) (_, (_, b)) -> compare a b) (H.toList h)\n go h ((i, x):xs) = case H.lookup (x - 1) h of\n Just (ys, l) -> go (H.insert x (i:ys, l + 1) h) xs\n Nothing -> go (H.insert x ([i], 1) h) xs\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ns <- fmap (map read . words) getLine\n let result = solve ns\n print $ length result\n putStrLn $ unwords (map show result)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n let res = solve n xs\n print $ length res\n putStrLn . unwords . map show $ res\n\nsolve :: Int -> [Int] -> [Int]\nsolve _ xs = construct [1..] xs . subseq $ go IM.empty xs\n where\n go !im (x:xs) = case IM.lookup (x - 1) im of\n Nothing -> go (IM.insert x 1 im) xs\n Just l -> go (IM.insertWith max x (l + 1) im) xs\n go im [] = maximum [(v,k)|(k,v)<-IM.toList im]\n subseq (v, k) = [k-v+1..k]\n construct (i:is) (x:xs) (y:ys)\n | x == y = i : construct is xs ys\n | otherwise = construct is xs (y:ys)\n construct _ _ _ = []\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n let res = solve n xs\n print $ length res\n putStrLn . unwords $ map show res\n\nsolve :: Int -> [Int] -> [Int]\nsolve _ xs = construct [1..] xs $ go IM.empty xs\n where\n go !im (x:xs) = case IM.lookup (x - 1) im of\n Nothing -> go (IM.insert x 1 im) xs\n Just l -> go (IM.insertWith max x (l + 1) im) xs\n go im [] = snd $ maximum [(len, [lst-len+1..lst])|(lst, len)<-IM.toList im]\n construct (i:is) (x:xs) (y:ys)\n | x == y = i : construct is xs ys\n | otherwise = construct is xs (y:ys)\n construct _ _ _ = []\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as M\nimport qualified Data.Foldable as F\nimport Data.List\nimport Data.Ord\nimport qualified Data.Sequence as S\n\nmain = do\n input <- B.getContents\n let ns = map readI $ tail $ B.words $ input\n let ans = solve ns\n print (length ans)\n putStrLn $ unwords $ map show ans\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: [Int] -> [Int]\nsolve ns =\n F.toList $ M.foldl (\\xs ys-> maximumBy (comparing S.length) [xs,ys]) S.empty $ foldl f M.empty $ zip [1..] ns\n where\n f :: M.IntMap (S.Seq Int) -> (Int,Int) -> M.IntMap (S.Seq Int)\n f m (i,x) =\n case M.lookup x m of\n Nothing -> M.alter (Just . g (S.singleton i)) (x+1) m\n Just js -> M.alter (Just . g (js S.|> i)) (x+1) m\n\n g :: S.Seq Int -> Maybe (S.Seq Int) -> S.Seq Int\n g xs Nothing = xs\n g xs (Just ys) = maximumBy (comparing S.length) [xs,ys]"}], "negative_code": [], "src_uid": "70986d3b1ff66ac612e8841a6049866d"} {"source_code": "s [a, b] = f ('4', '7') `max` f ('7', '4')\n where f z = length $ filter (==z) $ zip a b\nmain = interact $ show . s . words", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n a <- getLine\n b <- getLine\n\n let\n c1 = length $ filter (== '4') a\n c2 = length $ filter (== '4') b\n\n k = abs $ c1-c2\n\n a' = f a b k\n where\n f [] _ _ = []\n f (x:xs) (y:ys) k\n | x /= y && k > 0 = y:(f xs ys (k-1))\n | otherwise = x:(f xs ys k)\n\n k2 = (length $ filter id $ zipWith (/=) a' b) `div` 2\n\n print $ k + k2\n"}, {"source_code": "is4 = \\ch -> ch == '4'\nis7 = \\ch -> ch == '7'\nis47 = \\ch -> is4 ch || is7 ch\n\nfilterEq :: String -> String -> String\nfilterEq \"\" \"\" = \"\"\nfilterEq \"\" _ = \"\"\nfilterEq _ \"\" = \"\"\nfilterEq (x:xs) (y:ys)\n | x == y = filterEq xs ys\n | otherwise = x:(filterEq xs ys)\n \nsolve :: String -> String -> Int\nsolve s1 s2 = max c4 c7\n where\n s = filterEq s1 s2\n c4 = length (filter is4 s)\n c7 = length (filter is7 s)\n\nmain :: IO ()\nmain = do\n s1 <- getLine\n s2 <- getLine\n print (solve s1 s2)"}, {"source_code": "s [a, b] = f ('4', '7') `max` f ('7', '4')\n where f x = length $ filter (==x) $ zip a b\nmain = interact $ show . s . words"}, {"source_code": "solve a = f ('4','7') `max` f ('7','4')\n where f x = length$filter (==x) $ head a `zip` last a\n\nmain=interact$show.solve.lines"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n a <- readString\n b <- readString\n return (BS.unpack a, BS.unpack b)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (x, y) = max cnt47 cnt74\n where\n pairs = zip x y\n cnt47 = length $ filter (== ('4', '7')) pairs\n cnt74 = length $ filter (== ('7', '4')) pairs\n \n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\n\nmain :: IO ()\nmain = print =<< solve <$> (zip <$> getLine <*> getLine)\n\nsolve :: [(Char, Char)] -> Int\nsolve = uncurry max <$> (count ('7', '4') &&& count ('4', '7'))\n\ncount :: Eq a => a -> [a] -> Int\ncount a = length . filter (==a)\n"}, {"source_code": "\ng :: String -> String -> (Int, Int) -> Int\ng [] [] (p, q) = max p q\ng ('4':as) ('4':bs) (p, q) = g as bs (p, q)\ng ('4':as) ('7':bs) (p, q) = g as bs (p+1, q)\ng ('7':as) ('4':bs) (p, q) = g as bs (p, q+1)\ng ('7':as) ('7':bs) (p, q) = g as bs (p, q)\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n print $ g a b (0, 0)\n \n"}, {"source_code": "import Control.Applicative\nimport Data.ByteString(ByteString)\nimport qualified Data.ByteString.Char8 as B\n\nmain = do a <- B.getLine\n b <- B.getLine\n print $ solve a b\n\nsolve :: ByteString -> ByteString -> Int\nsolve a b = (d+) $ div (n-d) 2\n where la4 = B.length $ B.filter ('4'==) a\n lb4 = B.length $ B.filter ('4'==) b\n d = abs $ la4 - lb4\n n = length $ filter id $ B.zipWith (/=) a b\n "}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = interact $ show . uncurry max . foldl' (\\(x, y) [a, b] -> \n if a /= b \n then if a == '4' \n then (x + 1, y)\n else (x, y + 1)\n else (x, y)) (0, 0) . transpose . lines\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = interact $ show . uncurry max . foldl (\\(x, y) [a, b] -> \n if a /= b \n then if a == '4' \n then (x + 1, y)\n else (x, y + 1)\n else (x, y)) (0, 0) . transpose . lines\n"}, {"source_code": "x#y=x+y-min x y\ns[a,b]=c(<)#c(>)where c f=length.filter id$zipWith f a b\nmain=interact$show.s.lines\n"}, {"source_code": "s[a,b]=c(<)`max`c(>)where c f=length.filter id$zipWith f a b\nmain=interact$show.s.lines\n"}, {"source_code": "import Data.Char\nparse = map (map digitToInt) . lines\n\nsolve [a, b] = loop a b 0 0\n\nloop [] [] at ta = max at ta\nloop (4:x) (7:y) at ta = loop x y (1 + at) ta\nloop (7:x) (4:y) at ta = loop x y at (1 + ta)\nloop (_:x) (_:y) at ta = loop x y at ta\n\n\nmain = (print . solve . parse =<< getContents)\n"}, {"source_code": "count :: (Eq a) => a -> [a] -> Int \ncount _ [] = 0\ncount x (a:as) =\n if a == x\n then\n 1 + count x as\n else\n count x as \n\ncountsev = count '7' \n\nmismatches :: (Eq a) => [a] -> [a] -> Int \nmismatches [] [] = 0\nmismatches (a:as) (b:bs) = \n if a /= b\n then\n 1 + mismatches as bs\n else\n mismatches as bs\n\naddsevens :: Int -> [Char] -> [Char] -> [Char] \naddsevens 0 f _ = f \naddsevens rem (f:fewer) (m:more) = \n if f == '4' && m == '7'\n then \n '7' : addsevens (rem-1) fewer more \n else \n f : addsevens rem fewer more \n\noperations :: [Char] -> [Char] -> Int \noperations as bs = \n difference + (div swaps 2) \n where difference = abs $ (countsev as) - (countsev bs) \n swaps = mismatches (addsevens difference left right) right \n where (left, right) = if countsev as < countsev bs\n then (as, bs) else (bs, as)\n \n\nmain = do \n as <- getLine\n bs <- getLine\n putStrLn $ show $ operations as bs \n"}, {"source_code": "import Debug.Trace\n\ngetAns a b = max n m\n where unequal = filter (\\(x, y) -> x /= y) $ zip a b\n n = length $ filter (\\(x, y) -> x == '7') unequal\n m = length $ filter (\\(x, y) -> x == '4') unequal\n\nmain = do\n a <- getLine\n b <- getLine\n putStrLn $ show $ getAns a b"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do a <- map (read.return) <$> getLine\n b <- map (read.return) <$> getLine\n print $ solve a b\n\nsolve :: [Int] -> [Int] -> Int\nsolve a b\n | la4 == lb4 = div n 2\n | otherwise = (d+) $ div (n-d) 2\n where (a4,a7) = partition (4==) a\n (b4,b7) = partition (4==) b\n la4 = length a4\n lb4 = length b4\n d = abs $ la4 - lb4\n n = length $ filter id $ zipWith (/=) a b\n "}, {"source_code": "diff [] _ _ = 0\ndiff (x:xs) (y:ys) c = if x==c && x/=y then 1 + diff xs ys c\n\t\t\t\t\t\t \t\t else diff xs ys c\nans x y = let \n\t\t\tf = diff x y '4'\n\t\t\ts = diff x y '7'\n\t\t in \n\t\t f + s - min f s\nmain = do\n\t\tx <- getLine\n\t\ty <- getLine\n\t\tputStrLn $ show $ ans x y \n"}, {"source_code": "diff4 [] _ = 0\ndiff4 (x:xs) (y:ys) = if x=='4' && x/=y then 1 + diff4 xs ys\n\t\t\t\t\t\t \t\t else diff4 xs ys\ndiff7 [] _ = 0\ndiff7 (x:xs) (y:ys) = if x=='7' && x/=y then 1 + diff7 xs ys\n\t\t\t\t\t\t \t\t else diff7 xs ys\nans x y = diff4 x y + diff7 x y - min (diff4 x y) (diff7 x y)\nmain = do\n\t\tx <- getLine\n\t\ty <- getLine\n\t\tputStrLn $ show $ ans x y\n\n"}], "negative_code": [{"source_code": "solve::String->String->Int\nsolve a b \n | a == [] = 0\n | head a == head b = solve (tail a) (tail b)\n | length a == 1 = 1\n | head a == b!!1 && head b == a!!1 = 1+(solve (tail.tail$a) (tail.tail$b))\n | a /= b = 1+solve (tail a) (tail b)\n\nmain=do\n a<-getLine\n b<-getLine\n putStrLn.show.solve a$b"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n a <- readString\n b <- readString\n return (BS.unpack a, BS.unpack b)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (x, y) = go x y\n where\n go [] [] = 0\n go (x:xs) (y:ys) | x == y = go xs ys\n go [x] [y] = 1\n go (x0:x:xs) (_:y:ys) \n | x == y = go (x:xs) (y:ys) + 1\n | x0 == x = go (x:xs) (y:ys) + 1\n | otherwise = go xs ys + 1 -- swap\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "src_uid": "2d1609b434262d30f6bd030d41a71bd5"} {"source_code": "import Data.Maybe\nimport Data.Function\nimport Data.List\nimport qualified Data.HashMap.Strict as M\n\nmain = interact $ unlines . parse . tail . lines\n\ntype MM = M.HashMap String [String]\n\nparse ls = let\n lss = map words ls :: [[String]]\n m = M.toList $ foldl (\\m (n:_:ns) ->\n M.insert n (ns++M.lookupDefault [] n m) m) M.empty lss\n m' = map ((uncurry sol).(\\(n,ns)->(n,sortBy (compare `on` length) ns))) m\n m'' = map (\\(n,ns)-> intercalate \" \" (n:(show $ length ns):ns)) m'\n in (show$ length m''):m''\n\nsol nn [] = (nn, [])\nsol nn (n:ns) = let\n (_,ns') = sol nn ns\n nns = case find (\\n'-> n `isSuffixOf` n') ns' of\n Just _ -> ns'\n Nothing -> n : ns'\n in (nn, nns)\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n--------------------------------------------------------------------------------\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, unpack, reverse, dropWhile)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Char as C (isSpace)\nimport qualified Data.List as L (sort, nub, isPrefixOf)\nimport qualified Control.Monad as M (forM, forM_)\nimport qualified Data.Map.Strict as MP (fromListWith, map, assocs, size)\n\nreadInt = fst . M.fromJust . C.readInt\nrstrip = C.reverse . C.dropWhile C.isSpace . C.reverse\n\nrun (L.nub . L.sort . map reverse -> xs) = map reverse $ (last xs) : pp where\n pp = map snd $ filter (\\(a, b) -> not (b `L.isPrefixOf` a)) (zip (tail xs) xs)\n\nmain = do\n (map readInt . C.words -> [n]) <- B.getLine\n (MP.map run . MP.fromListWith (++) -> mp) <- M.forM [1..n] $ \\_ -> do\n (map (C.unpack . rstrip) . C.words -> name : xs) <- B.getLine\n return (name, tail xs)\n putStrLn $ show (MP.size mp)\n M.forM_ (MP.assocs mp) $ \\(a, b) ->\n putStrLn $ a ++ \" \" ++ show (length b) ++ \" \" ++ unwords b\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nmain = B.interact exec\nexec = evalState app . B.words\napp = do\n n <- poi\n dir <- replicateM n $ do\n name <- pop\n k <- poi\n ts <- replicateM k pop\n return (name, ts)\n let r = solve dir\n return $ B.unlines $ ((B.pack $ show (length r)):) $ map (\\(na, ts) -> B.unwords $ [na, B.pack $ show (length ts)] ++ ts) r\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap (maybe undefined fst . B.readInt) pop\n\nsolve dir\n = map (\\(n, ts0) -> (n, map (B.reverse . fst) $ filter (\\(c, p) -> not $ c `B.isPrefixOf` p) $ (\\ts -> zip ts (B.pack \"\":ts)) $ S.toDescList ts0))\n $ M.assocs\n $ M.fromListWith S.union $ map (\\(n, ts) -> (n, S.fromList $ map B.reverse ts)) dir"}, {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.Map as M\n\nreadData :: IO (String, [String])\nreadData = do\n line <- getLine\n let ws = words line\n return (head ws, drop 2 ws)\n\nreadInt :: IO Int\nreadInt = read `fmap` getLine\n\nprintVal :: (String, [String]) -> IO ()\nprintVal (a, ls) = do\n let start = a ++ \" \" ++ show (length ls)\n let res = intercalate \" \" ls\n putStrLn (start ++ \" \" ++ res)\n\nmain :: IO ()\nmain = do\n n <- readInt\n ls <- replicateM n readData\n let friends = (M.fromListWith (++) ls) :: M.Map String [String]\n let friends' = M.map (\\l -> let l' = nub l in filter (\\x-> all (\\y -> x == y || not (x `isSuffixOf` y)) l') l') friends\n let ls = M.toList friends'\n print (length ls)\n mapM_ printVal ls"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\nimport Data.Function\n\nmain = B.interact exec\nexec = evalState app . B.words\napp = do\n n <- poi\n dir <- replicateM n $ do\n name <- pop\n k <- poi\n ts <- replicateM k pop\n return (name, ts)\n let r = solve dir\n return $ B.unlines $ ((B.pack $ show (length r)):) $ map (\\(na, ts) -> B.unwords $ [na, B.pack $ show (length ts)] ++ ts) r\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap (maybe undefined fst . B.readInt) pop\n\nsolve dir = map (\\(n, ts) -> (n, map (B.reverse . maximumBy (compare `on` B.length)) $ groupBy B.isPrefixOf $ S.toList ts)) $ M.assocs $ M.fromListWith S.union $ map (\\(n, ts) -> (n, S.fromList $ map B.reverse ts)) dir"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n\n\nmain = B.interact exec\nexec = evalState app . B.words\napp = do\n n <- poi\n dir <- replicateM n $ do\n name <- pop\n k <- poi\n ts <- replicateM k pop\n return (name, ts)\n let r = solve dir\n return $ B.unlines $ ((B.pack $ show (length r)):) $ map (\\(na, ts) -> B.unwords $ [na, B.pack $ show (length ts)] ++ ts) r\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap (maybe undefined fst . B.readInt) pop\n\nsolve dir = map (\\(n, ts) -> (n, map (B.reverse . last) $ groupBy B.isPrefixOf $ S.toList ts)) $ M.assocs $ M.fromListWith S.union $ map (\\(n, ts) -> (n, S.fromList $ map B.reverse ts)) dir"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nmain = B.interact exec\nexec = evalState app . B.words\napp = do\n n <- poi\n dir <- replicateM n $ do\n name <- pop\n k <- poi\n ts <- replicateM k pop\n return (name, ts)\n let r = solve dir\n return $ B.unlines $ ((B.pack $ show (length r)):) $ map (\\(na, ts) -> B.unwords $ [na, B.pack $ show (length ts)] ++ ts) r\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap (maybe undefined fst . B.readInt) pop\n\nsolve dir\n = map (\\(n, ts0) -> (n, map fst $ filter (\\(c, p) -> not $ c `B.isPrefixOf` p) $ (\\ts -> zip ts (B.pack \"\":ts)) $ S.toDescList ts0))\n $ M.assocs\n $ M.fromListWith S.union $ map (\\(n, ts) -> (n, S.fromList $ map B.reverse ts)) dir"}, {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.Map as M\n\nreadData :: IO (String, [String])\nreadData = do\n line <- getLine\n let ws = words line\n return (head ws, drop 2 ws)\n\nreadInt :: IO Int\nreadInt = read `fmap` getLine\n\nprintVal :: (String, [String]) -> IO ()\nprintVal (a, ls) = do\n let start = a ++ \" \" ++ show (length ls)\n let res = intercalate \" \" ls\n putStrLn (start ++ \" \" ++ res)\n\nmain :: IO ()\nmain = do\n n <- readInt\n ls <- replicateM n readData\n let friends = (M.fromListWith (++) ls) :: M.Map String [String]\n let friends' = M.map (\\l -> let l' = nub l in filter (\\x-> all (\\y -> x == y || not (x `isSuffixOf` y)) l') l') friends\n let ls = M.toList friends'\n mapM_ printVal ls"}], "src_uid": "df7b16d582582e6756cdb2d6d856c873"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\nmain :: IO ()\nmain = do\n [n, px, py] <- map read . words <$> getLine :: IO [Int64]\n ps <- map (\\[x, y] -> (x - fromIntegral px, y - fromIntegral py))\n <$> replicateM (fromIntegral n) (map (fromIntegral . read) . words <$> getLine)\n let maxDis = maximum $ map (uncurry dis) ps\n minDis = minimum $ zipWith (curry getMinDis) ps (tail $ cycle ps)\n print $ pi * (maxDis - minDis)\n\ndis :: Double -> Double -> Double\ndis x y = x ^ 2 + y ^ 2\n\ngetMinDis ((x, y), (x', y'))\n | lambda <= 0 = dis x y\n | lambda >= 1 = dis x' y'\n | otherwise = dis (x + lambda * (x' - x)) (y + lambda * (y' - y))\n where lambda = ((x - x') * x + (y - y') * y) / dis (x' - x) (y' - y)\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Point = (Double, Double)\n\nadd, sub :: Point -> Point -> Point\nadd (a, b) (u, v) = (a + u, b + v)\nsub (a, b) (u, v) = (a - u, b - v)\n\nscale :: Point -> Double -> Point\nscale (a, b) s = (a * s, b * s)\n\ndistance :: Point -> Double\ndistance (a, b) = sqrt $ a * a + b * b\n\ndot :: Point -> Point -> Double\ndot (a, b) (u, v) = a * u + b * v\n\nprojection :: Point -> Point -> Point -> Point\nprojection p a b | offset < 0 = a\n | offset > sl = b\n | otherwise = a `add` (ba `scale` (offset / sl))\n where ba = sub b a\n pa = sub p a\n sl = distance ba\n\n offset = (dot pa ba) / sl\n\ngetMaxDist :: Point -> [Point] -> Double\ngetMaxDist p = maximum . map (distance . sub p)\n\ngetMinDist :: Point -> [Point] -> Double\ngetMinDist p ps = minimum $ zipWith distToSegment ps (tail ps ++ [head ps])\n where distToSegment a b = distance $ p `sub` q\n where q = projection p a b\n\nsolve :: Point -> [Point] -> Double\nsolve p ps = pi * (hi - lo) * (hi + lo)\n where lo = getMinDist p ps\n hi = getMaxDist p ps\n\ntest0 = ((0, 0), [(0, 1), (-1, 2), (1, 2)])\ntest1 = ((1, -1), [(0, 0), (1, 2), (2, 0), (1, 1)])\nrunTests = map (uncurry solve) [test0, test1]\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> (fst . fromJust $ L.readInt s, ss)\n\nnextDouble :: Tokenizer Double\nnextDouble = liftM fromIntegral nextInt\n\nnextPoint :: Tokenizer Point\nnextPoint = liftM2 (,) nextDouble nextDouble\n\ngo :: Tokenizer Double\ngo = do\n n <- nextInt\n p <- nextPoint\n ps <- replicateM n nextPoint\n return $ solve p ps\n\nmain :: IO ()\nmain = do\n input <- liftM L.words L.getContents\n let result = evalState go input\n printf \"%.6f\\n\" result\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = do\n [n, px, py] <- map read . words <$> getLine\n ps <- replicateM n (map read . words <$> getLine)\n let (minDis, maxDis) =\n (minimum &&& maximum) $ map (\\[x, y] -> (px - x) ^ 2 + (py - y) ^ 2) ps\n print $ pi * fromIntegral (maxDis - minDis)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = do\n [n, px, py] <- map read . words <$> getLine\n ps <- map (\\[x, y] -> (x - px, y - py))\n <$> replicateM n (map read . words <$> getLine)\n let dis x y = fromIntegral $ x ^ 2 + y ^ 2\n maxDis = fromIntegral $ maximum $ map (\\(x, y) -> x ^ 2 + y ^ 2) ps\n minDis =\n minimum $ zipWith\n (curry\n (\\((x, y), (x', y')) -> if dis x y == dis x' y'\n then fromIntegral ((x' * y - y' * x) ^ 2) / dis (x' - x) (y' - y)\n else min (dis x y) (dis x' y')\n )\n )\n ps\n (tail $ cycle ps) :: Double\n print (minDis, maxDis)\n print $ pi * (maxDis - minDis)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\nmain :: IO ()\nmain = do\n [n, px, py] <- map read . words <$> getLine :: IO [Int64]\n ps <- map (\\[x, y] -> (x - px, y - py))\n <$> replicateM (fromIntegral n) (map (fromIntegral . read) . words <$> getLine)\n let dis x y = fromIntegral $ x ^ 2 + y ^ 2\n maxDis = fromIntegral $ maximum $ map (\\(x, y) -> x ^ 2 + y ^ 2) ps\n minDis =\n minimum $ zipWith\n (curry\n (\\((x, y), (x', y')) -> if dis x y == dis x' y'\n then fromIntegral ((x' * y - y' * x) ^ 2) / dis (x' - x) (y' - y)\n else min (dis x y) (dis x' y')\n )\n )\n ps\n (tail $ cycle ps) :: Double\n print $ pi * (maxDis - minDis)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = do\n [n, px, py] <- map read . words <$> getLine\n ps <- map (\\[x, y] -> (x - px, y - py))\n <$> replicateM n (map read . words <$> getLine)\n let dis x y = fromIntegral $ x ^ 2 + y ^ 2\n maxDis = fromIntegral $ maximum $ map (\\(x, y) -> x ^ 2 + y ^ 2) ps\n minDis =\n minimum $ zipWith\n (curry\n (\\((x, y), (x', y')) -> if dis x y == dis x' y'\n then fromIntegral ((x' * y - y' * x) ^ 2) / dis (x' - x) (y' - y)\n else min (dis x y) (dis x' y')\n )\n )\n ps\n (tail $ cycle ps) :: Float\n print (minDis, maxDis)\n print $ pi * (maxDis - minDis)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = do\n [n, px, py] <- map read . words <$> getLine\n ps <- map (\\[x, y] -> (x - px, y - py))\n <$> replicateM n (map read . words <$> getLine)\n let dis x y = fromIntegral $ x ^ 2 + y ^ 2\n maxDis = fromIntegral $ maximum $ map (\\(x, y) -> x ^ 2 + y ^ 2) ps\n minDis =\n minimum $ zipWith\n (curry\n (\\((x, y), (x', y')) -> if dis x y == dis x' y'\n then fromIntegral ((x' * y - y' * x) ^ 2) / dis (x' - x) (y' - y)\n else min (dis x y) (dis x' y')\n )\n )\n ps\n (tail $ cycle ps) :: Double\n print $ pi * (maxDis - minDis)\n"}], "src_uid": "1d547a38250c7780ddcf10674417d5ff"} {"source_code": "main::IO()\nmain = \n do cs <- getContents\n (putStr.showSolve.solve.parseIn) cs\n\nparseIn::String->(Int,[Integer])\nparseIn s = (n,an)\n where\n (ns:l:_) = lines s\n n = read ns\n an = map read $ words l\n\nshowSolve ::[Integer]->String\nshowSolve [] = \"\"\nshowSolve [x] = show x\nshowSolve (x:xs) = show x ++ \"\\n\"++ showSolve xs\n\npow2seq=map (\\x -> 2^x) [0..]\n\ngetPlusedIndex s p = last $ takeWhile (\\x -> x < s) $ map (+ p) pow2seq \n \nupdateList::[Integer]->Int->Integer->[Integer]\nupdateList [] _ _ = []\nupdateList (a:as) 0 x = (a+x):as\nupdateList (a:as) n x = a:(updateList as (n-1) x)\n\nsolveSeq::[Integer]->[Integer]->Int->Int->[Integer]\nsolveSeq _ ret _ 0 = ret\nsolveSeq _ ret _ 1 = ret\nsolveSeq l ret size n = solveSeq ln retn size (n-1)\n where\n p = size - n\n c = l!!p\n next = getPlusedIndex size p\n ln = updateList l next c\n retn = updateList ret p c\n \nplusReduce::[Integer]->[Integer]\nplusReduce [] = []\nplusReduce (x:xs) = x:(map (+x) $ plusReduce xs)\n\nsolve::(Int,[Integer])->[Integer]\nsolve (n,ps) = cnts\n where\n cnts = plusReduce $ solveSeq ps (take (n-1) [0,0..]) n n\n ", "positive_code": [{"source_code": "main::IO()\nmain = \n do cs <- getContents\n (putStr.showSolve.solve.parseIn) cs\n\nparseIn::String->(Int,[Integer])\nparseIn s = (n,an)\n where\n (ns:l:_) = lines s\n n = read ns\n an = map read $ words l\n\nshowSolve ::[Integer]->String\nshowSolve [] = \"\"\nshowSolve [x] = show x\nshowSolve (x:xs) = show x ++ \"\\n\"++ showSolve xs\n\npow2seq=map (\\x -> 2^x) [0..]\n\ngetPlusedIndex s p = last $ takeWhile (\\x -> x < s) $ map (+ p) pow2seq \n \nupdateList::[Integer]->Int->Integer->[Integer]\nupdateList [] _ _ = []\nupdateList (a:as) 0 x = (a+x):as\nupdateList (a:as) n x = a:(updateList as (n-1) x)\n\nsolveSeq::[Integer]->[Integer]->Int->Int->[Integer]\nsolveSeq _ ret _ 0 = ret\nsolveSeq _ ret _ 1 = ret\nsolveSeq l ret size n = solveSeq ln retn size (n-1)\n where\n p = size - n\n c = l!!p\n next = getPlusedIndex size p\n ln = updateList l next c\n retn = updateList ret p c\n \nplusReduce::[Integer]->[Integer]\nplusReduce [] = []\nplusReduce (x:xs) = x:(map (+x) $ plusReduce xs)\n\nsolve::(Int,[Integer])->[Integer]\nsolve (n,ps) = cnts\n where\n cnts = plusReduce $ solveSeq ps (take (n-1) [0,0..]) n n\n "}], "negative_code": [], "src_uid": "c7e49c643dd8738f273c0d24e56c505f"} {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nreadIntBS = fst . fromJust . BS.readInt\n\nmain = do\n [n,l,a] <- map read . words <$> getLine :: IO [Int]\n dat <- map (map readIntBS . BS.words) . BS.lines <$> BS.getContents :: IO [[Int]]\n\n let dat' = ([0,0] : dat) ++ [[l,0]]\n\n print $ sum [(j-(i+k))`div`a | ([i,k], [j,_]) <- zip dat' (tail dat')]\n", "positive_code": [{"source_code": "-- Codeforces 1059A\nimport Data.List\n\ncountBreaks :: Int -> [Int] -> [Int] -> Int\ncountBreaks breakLength startTime endTime = sum countList\n where breakList = zipWith (-) startTime endTime\n countList = map (`div` breakLength) breakList\n\nmapStartTime :: [Int] -> Int -> [Int]\nmapStartTime starts end = starts ++ [end]\n\nmapEndTime :: [Int] -> [Int] -> [Int]\nmapEndTime starts durations = 0:zipWith (+) starts durations\n\nmain :: IO ()\nmain = do\n [n, l, a] <- getLine >>= return.(map read::[String]->[Int]).words\n [start, duration] <- \n if n == 0 then return [[], []]\n else do getContents >>= \n return.(map $ map read).transpose.(map words).(take n).lines :: IO [[Int]]\n let startTime = mapStartTime start l\n let endTime = mapEndTime start duration\n putStrLn $ show $ countBreaks a startTime endTime\n"}], "negative_code": [], "src_uid": "00acb3b54975820989a788b9389c7c0b"} {"source_code": "import Data.List (group)\nsolve :: [String] -> Integer\nsolve = sum . map (f . length) . group\n where f x = let x' = fromIntegral x in quot (x' * (x' + 1)) 2 \nmain = getLine >> getLine >>= putStrLn . show . solve . words", "positive_code": [{"source_code": "module Main where\n\nimport List\n\nparseInt :: String -> Int\nparseInt token = read token :: Int\n\nsubArrays :: Int -> Integer\nsubArrays x = n * (n + 1) `div` 2\n where n = toInteger x\n\nsolve :: [Int] -> Integer\nsolve = sum . map (subArrays . length) . group\n\nmain = interact (show . solve . map parseInt . tail . words)\n"}, {"source_code": "module Main where\n\nimport Data.Char;\n\nmain = do\n s <- getLine\n interact in2out\n\nin2out input\n = output\n where\n nums :: [Integer]\n nums = map read $ words input\n output = show $ count nums (10^9+1) 0 0\n count [] _ cx ans\n = cx + ans\n count (x:xs) px cx ans\n = count xs x cx' $! cx+ans\n where\n cx'\n | x == px\n = cx + 1\n | otherwise\n = 1\n"}, {"source_code": "import Data.List\nmain=interact$show.sum.map((\\x->x*(x+1)`div`2).genericLength).group.tail.words"}, {"source_code": "\nimport List (group)\nimport Monad (liftM)\n\nsolve :: [Int] -> Integer\nsolve = sum . map (f . fromIntegral . length) . group\n where\n f :: Integer -> Integer\n f n = div (n * (n + 1)) 2\n\nmain :: IO ()\nmain = getLine >> liftM (map read . words) getLine >>= print . solve\n"}, {"source_code": "import Data.List\nmain = getLine >> (group . words) `fmap` getLine >>=\n print . foldl' (\\x n -> x + n*(n+1) `div` 2) 0 . map (fromIntegral . length)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nf :: Integer -> Integer -> Integer\nf x n = seq y (x + y) \n where y = n * (n+1) `div` 2 \n\nmain = do\n getLine\n xs <- map read . words <$> getLine :: IO [Integer]\n print $ foldl' f 0 $ map (fromIntegral . length) $ group xs \n"}, {"source_code": "import Data.List\nmain=interact$show.sum.map((\\x->x*(x+1)`div`2).genericLength).group.tail.words"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n readInt\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = do\n a <- evalState parseInput <$> BS.getContents\n print $ solve a\n\nsolve :: [Int] -> Int64\nsolve a = sum . map (\\x -> (fromIntegral x * (fromIntegral x + 1) `div` 2) ) . map length $ group a \n\n--{{{ Start of a minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n--}}} end of a minimal State Monad\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Main where\n\nimport Data.List\nimport Data.Ord\nimport Data.Map(Map)\nimport qualified Data.Map as Map\nimport Data.Set(Set)\nimport qualified Data.Set as Set\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\n\nmain = do\n [n::Integer] <- map read . words <$> getLine\n (numbers::[Integer]) <- map read . words <$> getLine\n let sizes = map genericLength (group numbers) :: [Integer]\n let solve size = (size+1) * size `div` 2\n putStrLn $ show $ sum $ map solve sizes\n"}, {"source_code": "import List\nimport Control.Monad\n\nmain = \n\tdo\n\t\tn <- getLine\n\t\tl <- liftM (\\x -> map read $ words x) getLine\n\t\tputStrLn $ show $ foldl (\\x y -> x + y * (y+1) `div` 2) 0 (map fromIntegral (map length $ group (l::[Int])))\n"}, {"source_code": "import Data.List (genericLength, group)\nsolve :: [String] -> Integer\nsolve = sum . map ((\\x -> x * (x+1) `quot` 2) . genericLength) . group\nmain = getLine >> getLine >>= putStrLn . show . solve . words"}, {"source_code": "import Data.List\nimport Data.Int\nmain = do\n n <- read `fmap` getLine :: IO Int\n l <- (map read . words) `fmap` getLine :: IO [Int32]\n putStr $ show $ sum $ map (\\x -> let k = (fromIntegral (length x) :: Integer) in \n\t\t\tk * (k + 1) `div` 2) $ group l\n"}, {"source_code": "\nreadd line = map (\\x-> (read x)::Int) $ parsespace line\n\nparsespace' res cur [] = cur:res\nparsespace' res cur (a:xs) =\n if a == ' ' then \n parsespace' (cur:res) [] xs\n else\n parsespace' res (cur++[a]) xs\n\nparsespace line = filter (\\x->length x > 0) $ parsespace' [] [] line\n\nmagicparts' res cur last [] = cur:res\nmagicparts' res cur last (a:xs) = \n if a==last then\n magicparts' res (cur+1) last (xs)\n else\n magicparts' (cur:res) 1 a (xs)\n\nmagicparts arr = magicparts' [] 1 (head arr) (tail arr)\n\nres line = foldr (+) 0 $ map (\\x->x*(x+1) `div` 2) (magicparts (readd line))\n\nmain = do\n line1 <- getLine\n line <- getLine\n putStrLn (show (res line))\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.List (genericLength, group)\nimport qualified Data.ByteString.Char8 as B\nsolve :: [B.ByteString] -> Integer\nsolve = sum . map ((\\x -> x * (x+1) `quot` 2) . genericLength) . group\nmain = B.getLine >> B.getLine >>= putStrLn . show . solve . B.words"}, {"source_code": "import Data.List (genericLength, group)\nsolve xs = sum $ map (\\x -> (x + 1) * x `div` 2) $ map genericLength $ group xs\nmain = interact $ show . solve . tail . words"}, {"source_code": "import Data.List (genericLength)\n\ndecompose [] = []\ndecompose (x:xs) = \n case span (== x) (x:xs) of\n (a, b) -> a:(decompose b)\n\nsolve :: [Integer] -> Integer\nsolve xs = sum $ map (\\x -> x * (x + 1) `div` 2) $ map genericLength (decompose xs)\n\nmain = do _ <- getLine\n line <- getLine\n putStrLn $ show $ solve $ map (read :: String -> Integer) (words line)"}], "negative_code": [{"source_code": "\nimport List (group)\nimport Monad (liftM)\n\nsolve :: [Int] -> Int\nsolve = sum . map f . map length . group\n where\n f n = div (n * (n + 1)) 2\n\nmain :: IO ()\nmain = getLine >> liftM (map read . words) getLine >>= print . solve\n"}, {"source_code": "\ndecompose [] = []\ndecompose (x:xs) = \n case span (== x) (x:xs) of\n (a, b) -> a:(decompose b)\n\nsolve xs = sum $ map (\\x -> x * (x + 1) `div` 2) $ map length (decompose xs)\n\nmain = do _ <- getLine\n line <- getLine\n putStrLn $ show $ solve $ map (read :: String -> Integer) (words line)"}, {"source_code": "import List\nimport Control.Monad\n\nmain = \n\tdo\n\t\tn <- getLine\n\t\tl <- liftM (\\x -> map read $ words x) getLine\n\t\tputStrLn $ show $ foldl (\\x y -> x + y * (y+1) `div` 2) 0 (map length $ group (l::[Int]))\n"}, {"source_code": "import Data.List\nimport Data.Int\nmain = do\n n <- read `fmap` getLine :: IO Int\n l <- (map read . words) `fmap` getLine :: IO [Int32]\n putStr $ show $ sum $ map (\\x -> let k = length x in k * (k + 1) `div` 2) $ group l\n"}, {"source_code": "import Data.List\nmain = do\n n <- read `fmap` getLine :: IO Int\n l <- (map read . words) `fmap` getLine :: IO [Int]\n putStr $ show $ sum $ map (\\x -> let k = length x in k * (k + 1) `div` 2) $ group l\n"}], "src_uid": "0b229ddf583949d43d6f1728e38c3cad"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (liftM)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInteger :: BS.ByteString -> Integer\nreadInteger s = case BS.readInteger s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Integer\"\n\nsolve :: Integer -> Integer -> [Integer] -> [Integer]\nsolve n k a = solve' n 1 0 (zip a [1 ..])\n where solve' n i _ _ | i > n = []\n solve' n i s ((a, x):as) = if rating < k\n then x : solve' (n - 1) i s as\n else solve' n (i + 1) s' as\n where rating = s - (i - 1) * (n - i) * a\n s' = s + a * (i - 1)\n\nmain = do\n (n:k:a) <- liftM (map readInteger . BS.words) BS.getContents\n let result = solve n k a\n BS.putStr . BS.unlines $ map (BS.pack . show) result\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nmain = do\n n:k:l <- map readInt . B.words <$> B.getContents\n putStr $ unlines $ map show $ solve n k l\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n k l = loop 2 0 n l\n where\n loop :: Int -> Int64 -> Int -> [Int] -> [Int]\n loop c b m (a1:a2:as) \n | d < itol k = (c+n-m):loop c b (m-1) (a1:as)\n | otherwise = loop (c+1) b' m (a2:as)\n where\n b' = b + itol a1*itol (c-2)\n d = b' - itol (c-1)*itol (m-c)*itol a2 \n loop c b n _ = []\n\nitol = fromIntegral\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Int\n\nmain = do\n n:k:l <- map read . words <$> getContents\n putStr $ unlines $ map show $ solve n k l\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n k l = loop 2 0 n l\n where\n loop :: Int -> Int64 -> Int -> [Int] -> [Int]\n loop c b m (a1:a2:as) \n | d < itol k = (c+n-m):loop c b (m-1) (a1:as)\n | otherwise = loop (c+1) b' m (a2:as)\n where\n b' = b + itol a1*itol (c-2)\n d = b' - itol (c-1)*itol (m-c)*itol a2 \n loop c b n _ = []\n\nitol = fromIntegral\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nmain = do\n n:k:l <- map read . words <$> getContents\n putStr $ unlines $ map show $ solve n k l\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n k l = loop 2 0 n l\n where\n loop c b m (a1:a2:as) \n | d < k = (c+n-m):loop c b (m-1) (a2:as)\n | otherwise = loop (c+1) b' m (a2:as)\n where\n b' = b + a1*(c-2)\n d = b' - (c-1)*(m-c)*a2 \n loop c b n _ = []\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nmain = do\n n:k:l <- map read . words <$> getContents\n putStr $ unlines $ map show $ solve n k l\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve n k l = loop 2 0 n l\n where\n loop c b m (a1:a2:as) \n | d < k = (c+n-m):loop c b (m-1) (a1:as)\n | otherwise = loop (c+1) b' m (a2:as)\n where\n b' = b + a1*(c-2)\n d = b' - (c-1)*(m-c)*a2 \n loop c b n _ = []\n"}], "src_uid": "7237361e3c2a9b1524d6410283839d48"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Char8 as SP\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, m] <- readInts\n orig <- replicateM n (P.toStrict <$> readLine)\n scr <- replicateM (n-1) (P.toStrict <$> readLine)\n let\n outStr = (++ \"\\n\") $ do\n i <- [0 .. fromIntegral (m - 1)]\n let\n [oi, si] = map (map (`SP.index` i)) [orig, scr]\n cts :: UArray Char Int\n cts = accumArray (+) 0 ('a', 'z')\n $ zip oi (repeat 1) ++ zip si (repeat (0-1))\n [c | c <- ['a' .. 'z'], cts ! c /= 0]\n lift $ B.hPutBuilder stdout $ B.string7 outStr\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n-- fuck haskell and its slow io\n\nfindchar (x:_) [] = B.head x\nfindchar (x:xs) (y:ys)\n | B.length x == B.length y && B.head x == B.head y = findchar xs ys\n | otherwise = B.head x\n\nsubtr :: B.ByteString -> B.ByteString -> Word8\nsubtr a b = findchar as bs\n where as = B.group $ B.sort a\n bs = B.group $ B.sort b\n\nsolve :: IO ()\nsolve = do\n _s1 <- getLine\n let [n, m] = map read $ words _s1 :: [Int]\n _s2 <- sequence $ replicate n (B.getLine :: IO B.ByteString)\n _s3 <- sequence $ replicate (n-1) (B.getLine :: IO B.ByteString)\n _ <- let a = B.transpose $ _s2\n b = B.transpose $ _s3\n sol = if n == 1 then head _s2 else B.pack $ zipWith subtr a b\n in sequence [B.putStr sol, putStrLn \"\", hFlush stdout]\n return ()\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM, for)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\nimport GHC.IO.Handle (hDuplicateTo)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> fst . fromJust\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> fst . fromJust\n\n\nsolve :: Int -> Int -> [String] -> [String] -> String\nsolve n m initA resultA = result\n where\n initAB8 :: [B8.ByteString]\n initAB8 = map B8.pack initA\n\n resultAB8 :: [B8.ByteString]\n resultAB8 = map B8.pack resultA\n\n result :: String\n result = flip map [0 .. m - 1] $ \\i ->\n let\n emptyMap :: M.Map Char Int\n emptyMap = M.empty\n \n inclusiveMap :: M.Map Char Int \n inclusiveMap = foldr (\\s m -> M.insertWith (+) (s `B8.index` i) 1 m) emptyMap initAB8\n\n resultMap :: M.Map Char Int\n resultMap = foldr (\\s m -> M.insertWith (+) (s `B8.index` i) (-1) m) inclusiveMap resultAB8\n\n in fst . head . filter (\\(k, v) -> v > 0) . M.toList $ resultMap\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, m] <- B8.getLine <&> map readIntB8 . B8.words\n initA <- replicateM n $ B8.getLine <&> B8.unpack\n resultA <- replicateM (n - 1) $ B8.getLine <&> B8.unpack\n\n let answer = solve n m initA resultA\n\n putStrLn answer\n hFlush stdout\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (forM_, replicateM_)\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Data.List (transpose, group, sort)\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf testCase) >>> unlines >>> C.pack\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n (n, _) <- pair int int\r\n ss <- (2 * n - 1) >< str\r\n return $ map findOdd (transpose ss)\r\n\r\nfindOdd :: [Char] -> Char\r\nfindOdd = head . head . filter (odd . length) . group . sort\r\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n-- fuck haskell and its slow io\n\nfindchar (x:_) [] = B.head x\nfindchar (x:xs) (y:ys)\n | B.length x == B.length y && B.head x == B.head y = findchar xs ys\n | otherwise = B.head x\n\nsubtr :: B.ByteString -> B.ByteString -> Word8\nsubtr a b = findchar as bs\n where as = B.group $ B.sort a\n bs = B.group $ B.sort b\n\nsolve :: IO ()\nsolve = do\n _s1 <- getLine\n let [n, m] = map read $ words _s1 :: [Int]\n _s2 <- sequence $ replicate n (B.getLine :: IO B.ByteString)\n _s3 <- sequence $ replicate (n-1) (B.getLine :: IO B.ByteString)\n _ <- let a = B.transpose $ _s2\n b = B.transpose $ _s3\n sol = if n == 1 then [B.head $ head a] else zipWith subtr a b\n in sequence [B.putStr $ B.pack sol, putStrLn \"\", hFlush stdout]\n return ()\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n-- fuck haskell and its slow io\n\nfindchar (x:_) [] = B.head x\nfindchar (x:xs) (y:ys)\n | B.length x == B.length y && B.head x == B.head y = findchar xs ys\n | otherwise = B.head x\n\nsubtr :: B.ByteString -> B.ByteString -> Word8\nsubtr a b = findchar as bs\n where as = B.group $ B.sort a\n bs = B.group $ B.sort b\n\nsolve :: IO ()\nsolve = do\n _s1 <- getLine\n let [n, m] = map read $ words _s1 :: [Int]\n _s2 <- sequence $ replicate n (B.getLine :: IO B.ByteString)\n _s3 <- sequence $ replicate (n-1) (B.getLine :: IO B.ByteString)\n let a = B.transpose $ _s2\n b = B.transpose $ _s3\n sol = zipWith subtr a b\n in sequence [B.putStr $ B.pack sol, putStrLn \"\"]\n return ()\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n\n--import Data.Char as C\n--import Data.IntSet as S\n\n\n-- fuck haskell and its slow io\n\nfindchar (x:_) [] = B.head x\nfindchar (x:xs) (y:ys)\n | B.length x == B.length y && B.head x == B.head y = findchar xs ys\n | otherwise = B.head x\n\nsubtr :: B.ByteString -> B.ByteString -> Word8\nsubtr a b = findchar as bs\n where as = B.group $ B.sort a\n bs = B.group $ B.sort b\n\n\n\n\nsolve :: IO ()\nsolve = do\n _s1 <- getLine\n let [n, m] = map read $ words _s1 :: [Int]\n _s2 <- sequence $ replicate n B.getLine :: IO [B.ByteString]\n _s3 <- sequence $ replicate (n-1) B.getLine :: IO [B.ByteString]\n let a = B.transpose $ _s2\n b = B.transpose $ _s3\n sol = zipWith subtr a b\n in sequence [B.putStr $ B.pack sol, putStrLn \"\", hFlush stdout]\n return ()\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}], "src_uid": "b8ffd93a80c840ea645c6797f8ee269c"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.List\n\nmain = do\n [_, v] <- map read.words <$> getLine\n xys <- parse.map read.words <$> getContents\n print $ solve v xys\n\nparse (x:y:xys) = (x, y) : parse xys\nparse _ = []\n \nsolve :: Int -> [(Int, Int)] -> Int\nsolve v xys = go 0 1 v $ sort xys\n where\n go !res !day !num ((a,b):rest)\n | day < a = go res (day+1) v $ (a,b):rest\n | a + 1 < day = go res day num rest\n | num <= b = go (res+num) (day+1) v $ (a,b-num) : rest\n | otherwise = go (res+b) day (num-b) rest\n go res _ _ _ = res\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\n\nmain=interact $ show . getAns . getArrays\n\ngetArrays :: String -> [Int]\ngetArrays = tail . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (v:xs) = getMax 1 0 v $ (map (\\l@(x:xs) -> (fst x, (sum . map snd) l)) . groupBy (\\x y -> fst x == fst y) . sort . toPairs) xs\n\ntoPairs :: [Int] -> [(Int, Int)]\ntoPairs [] = []\ntoPairs (x:y:xs) = (x, y) : toPairs xs\n\ngetMax :: Int -> Int -> Int -> [(Int, Int)] -> Int\ngetMax _ 0 _ [] = 0\ngetMax d r v ((y, x):xs) | y == d = \n\tlet gets = min (r + x) v\n\t nr = if gets >= r then x + r - gets else x\n\tin gets + getMax (d + 1) nr v xs\ngetMax d r v xs = min v r + getMax (d + 1) 0 v xs\n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nsolve maxi v !s d i rarr | i > maxi =\n let s1 = min v d in s+s1\n\nsolve maxi v !s d i rarr =\n -- v - picking capacilty\n -- s - total fruit picked\n -- maxi - maximum value of i\n -- d - amount of day-old fruit\n -- i - day number\n -- rarr - array of ripened fruit\n let r = rarr!i\n s1 = min v (d+r) -- amount of day-old fruit picked\n d' = min (d+r-s1) r -- new amount of day-old fruit\n in solve maxi v (s+s1) d' (i+1) rarr\n\nmain = do\n (n:v:_) <- fmap (map read . words) getLine\n rarr <- newArray (1,3001) 0 :: IO (IOUArray Int Int)\n replicateM_ n $ do\n (a:b:_) <- fmap (map read . words) getLine\n x <- readArray rarr a\n writeArray rarr a (b+x)\n rarr <- freeze rarr :: IO (UArray Int Int)\n let answer = solve 3001 v 0 0 1 rarr\n print answer\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort, insertBy)\nimport Data.Maybe (mapMaybe)\nimport Data.Monoid\nimport Debug.Trace\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map fst . mapMaybe B.readInt . B.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> B.getLine\n\nmain = do\n [n, v] <- getInts\n ts <- replicateM n $ do {[a, c] <- getInts; return (a, 0, c);}\n let\n comp (x1,y1,_) (x2,y2,_) = (x1 `compare` x2) `mappend` (y2 `compare` y1)\n f [] _ _ = 0\n f ts@((a,b,c):rs) day limit\n | b == 2 || c == 0 = f rs day limit\n | a == day = let fruit = min c limit in fruit + f (insertBy comp (a+1, b+1, c-fruit) rs) day (limit-fruit)\n | otherwise = f ts (day+1) v\n in print $ f (sort ts) 1 v\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Function\n\nmain=interact $ show . getAns . getArrays\n\ngetArrays :: String -> [Int]\ngetArrays = tail . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (v:xs) = getMax 1 0 v $ (sort . toPairs) xs\n\ntoPairs :: [Int] -> [(Int, Int)]\ntoPairs [] = []\ntoPairs (x:y:xs) = (x, y) : toPairs xs\n\ngetMax :: Int -> Int -> Int -> [(Int, Int)] -> Int\ngetMax _ 0 _ [] = 0\ngetMax d r v ((y, x):xs) | y == d = \n\tlet gets = min (r + x) v\n\t tr = if gets >= r then x - (gets - r) else 0\n\t nr = if tr > 0 then tr else 0\n\tin gets + getMax (d + 1) nr v xs\ngetMax d r v xs = min v r + getMax (d + 1) 0 v xs\n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.List\n\nmain = do\n [_, v] <- map read.words <$> getLine\n xys <- parse.map read.words <$> getContents\n print $ solve v xys\n\nparse (x:y:xys) = (x, y) : parse xys\nparse _ = []\n \nsolve :: Int -> [(Int, Int)] -> Int\nsolve v xys = go 0 1 v (sort xys)\n where\n go !res !day !num ((a,b):rest)\n | day < a = go res a v rest\n | a + 1 < day = go res day num rest\n | num <= b = go (res+num) (day+1) v $ (a,b-num) : rest\n | otherwise = go (res+b) day (num-b) rest\n go res _ _ _ = res\n"}], "src_uid": "848ead2b878f9fd8547e1d442e2f85ff"} {"source_code": "data S=A|B deriving Eq\ndata SL = SL [S]\n\nreadS::Char->S\nreadS 'a' = A\nreadS 'b' = B\n\nreadSL::String->[S]\nreadSL str = map readS str\n\nshowS::S->Char\nshowS A = 'a'\nshowS B = 'b'\n\nshowSL::[S]->String\nshowSL str = map showS str\n\nbeat2::[S]->[(S,S)]\nbeat2 [] = []\nbeat2 (x:y:xs) = (x,y):(beat2 xs)\n\ninv::(S,S)->(Int,(S,S))\ninv (A,A) = (1,(A,B))\ninv (B,B) = (1,(B,A))\ninv a=(0,a)\n\nbackConc::[(a,a)]->[a]\nbackConc [] =[]\nbackConc ((x,y):xs)=x:y:(backConc xs)\n\ngetFinal::[S]->(Int,[S])\ngetFinal str = let\n (ns,fs) = unzip $ map inv (beat2 str)\n in (sum ns,backConc fs)\n\nmain::IO()\nmain = do\n n <- getLine\n str <- getLine\n let (n,str') = getFinal (readSL str)\n print n\n putStrLn (showSL str')\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\t\ntr \"aa\" = \"ab\"\ntr \"bb\" = \"ab\"\ntr x = x\n\nchunksOf n [] = []\nchunksOf n s = (take n s): (chunksOf n (drop n s))\n\nmain = do\n\tn<- read <$> getLine ::IO Int\n\ts<-chunksOf 2 <$> getLine\n\tprint $ length $ filter (\\z-> elem z [\"aa\",\"bb\"]) s\n\tputStrLn $ concat $ map tr s\n\n\n"}], "negative_code": [], "src_uid": "8ad06ac90b258a8233e2a1cf51f68078"} {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (group, sort)\n\nsolve n as\n | n == 1 = putStrLn \"1\"\n | otherwise = do\n let blocks = group $ sort as\n let cntEven = length $ filter (even . length) blocks\n\n let answer = length blocks\n\n answer <- return (if odd cntEven then answer - 1 else answer)\n\n putStrLn $ show answer\n\nread = do\n s <- C.getLine\n\n let n = fst $ fromJust $ C.readInt s\n\n s <- C.getLine\n\n let as = map (fst . fromJust . C.readInt) (C.words s)\n\n solve n as\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n", "positive_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (group, sort)\n\nsolve n as\n | n == 1 = putStrLn \"1\"\n | otherwise = do\n let blocks = group $ sort as\n let cntEven = length $ filter (even . length) blocks\n\n let answer = (-) (length blocks) (if odd cntEven then 1 else 0)\n\n putStrLn $ show answer\n\nread = do\n s <- C.getLine\n\n let n = fst $ fromJust $ C.readInt s\n\n s <- C.getLine\n\n let as = map (fst . fromJust . C.readInt) (C.words s)\n\n solve n as\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n"}, {"source_code": "module Main where\n\n\nimport Control.Monad (replicateM_)\nimport qualified Data.Map as M\nimport Data.Map.Internal ((!?))\nimport Data.Maybe (fromMaybe)\n \ngetNumbers :: IO [Int]\ngetNumbers = map read . words <$> getLine\n \nlistToCountListMod2 :: [Int] -> [Int]\nlistToCountListMod2 = map (`mod` 2) . M.elems . M.fromListWith (+) . flip zip (repeat 1)\n\noneAndTwoToAnswer :: [Int] -> Int\noneAndTwoToAnswer lst = oneCount + twoCount - twoCount `mod` 2\n where \n oneAndTwoCount = M.fromListWith (+) $ zip lst (repeat 1)\n oneCount = fromMaybe 0 $ oneAndTwoCount !? 1\n twoCount = fromMaybe 0 $ oneAndTwoCount !? 0\n\n\nsolution :: IO ()\nsolution = do\n [_] <- getNumbers\n nums <- getNumbers\n print $ oneAndTwoToAnswer $ listToCountListMod2 nums\n \nmain :: IO ()\nmain = do\n [t] <- getNumbers\n replicateM_ t solution"}, {"source_code": "module Main where\n\n\nimport Control.Monad (replicateM_)\nimport qualified Data.Map as M\nimport Data.Map.Internal ((!?))\nimport Data.Maybe (fromMaybe)\n \ngetNumbers :: IO [Int]\ngetNumbers = map read . words <$> getLine\n \nlistToCountListMod2 :: [Int] -> [Int]\nlistToCountListMod2 = map (`mod` 2) . M.elems . M.fromListWith (+) . flip zip (repeat 1)\n\noneAndTwoToAnswer :: [Int] -> Int\noneAndTwoToAnswer lst = oneCount + (if twoCount `mod` 2 == 1 then twoCount - 1 else twoCount)\n where \n oneAndTwoCount = M.fromListWith (+) $ zip lst (repeat 1)\n oneCount = fromMaybe 0 $ oneAndTwoCount !? 1\n twoCount = fromMaybe 0 $ oneAndTwoCount !? 0\n\n\nsolution :: IO ()\nsolution = do\n [_] <- getNumbers\n nums <- getNumbers\n print $ oneAndTwoToAnswer $ listToCountListMod2 nums\n \nmain :: IO ()\nmain = do\n [t] <- getNumbers\n replicateM_ t solution"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Control.Monad.State.Class\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport Data.Char\nimport Data.Functor.Identity\nimport qualified Data.IntMap as M\nimport Data.Maybe\nimport Debug.Trace\n\ntype ParserT = StateT C.ByteString\n\ntype ComputationT m = StateT (M.IntMap Bool) (ParserT m)\n\n-- A computation is a monadic action with an input string and an intmap \"variable\" as state.\ntype Computation = ComputationT Identity\n\nrunComputation :: Computation a -> C.ByteString -> a\nrunComputation computation = runIdentity . evalStateT (evalStateT computation M.empty)\n\nmain :: IO ()\nmain = do\n t <- int <$> C.getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n n <- int <$> C.getLine\n C.getLine >>= output . runComputation (replicateM_ n populateTree >> eliminateTree)\n\neliminateTree :: Computation Int\neliminateTree = do\n list <- gets M.toList\n return $ length list - ((`mod` 2) . length . filter id . map snd $ list)\n\npopulateTree :: Computation ()\npopulateTree = do\n val <- lift getInt\n modify $ M.alter (pure . maybe False not) val\n\ngetInt :: Monad m => ParserT m Int\ngetInt = StateT $ pure . fromJust . C.readInt . C.dropWhile isSpace\n\nint :: C.ByteString -> Int\nint = fst . fromJust . C.readInt\n\noutput :: Int -> IO ()\noutput = L.putStrLn . B.toLazyByteString . B.intDec\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let inputs = map ((map read) . words) $ take t $ dropOdd $ lines input\n mapM_ (print . solve) inputs\n where dropOdd [] = []\n dropOdd (_:x:xs) = x:(dropOdd xs)\n\nsolve :: [Int] -> Int\nsolve xs = unique - abs ((length xs + unique) `mod` 2)\n where unique = length $ nub xs\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List\nimport Control.Monad\n--import Control.Monad.State.Strict\n\n-- parseLine = fmap (map read . words)\n\ntoSpaced :: Show a => [a] -> String\ntoSpaced = intercalate \" \" . map show\n\nprintSpaced :: Show a => [a] -> IO ()\nprintSpaced = putStrLn . toSpaced\n\nreadInt :: IO Int\nreadInt = fmap read getLine\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\nf :: Int -> Int -> Int\nf x y = mod (x - y + 10) 10\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [1..t] $ \\t -> do\n n <- readInt\n a <- readInts\n\n let fs = map length (group $ sort a)\n\n {-\n offsets <- (forM [1..n] $ \\i -> do\n line <- getLine;\n let [b_i_s, s_i] = words line;\n -- print $ (b_i_s, s_i)\n let b_i :: Int = read b_i_s;\n let up_count = (length . filter (=='U')) s_i;\n let down_count = (length . filter (=='D')) s_i;\n return $ up_count - down_count)\n\n let res :: [Int] = zipWith f a offsets\n -}\n\n let o = length $ filter (\\x -> (x `mod` 2) == 1) fs\n let e = length $ filter (\\x -> (x `mod` 2) == 0) fs\n\n -- printSpaced fs\n print $ o + e - (e `mod` 2)\n\n return ()\n"}, {"source_code": "import Data.List (sort)\r\n\r\nreadArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\ncheckH :: Int -> Int -> [Int] -> (Int, Int)\r\ncheckH _ c [] = if c `mod` 2 == 0\r\n then (1, 0)\r\n else (0, 1)\r\ncheckH a c (x: xs) = if x == a\r\n then checkH a (c + 1) xs\r\n else let (r, l) = checkH x 1 xs in if c `mod` 2 == 0\r\n then (r + 1, l)\r\n else (r, l + 1)\r\n\r\ncheck :: [Int] -> (Int, Int)\r\ncheck a = checkH (head a) 0 a\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = pure ()\r\nsolve i = do\r\n n <- readLn :: IO Int\r\n a <- readArr\r\n let (x, y) = check $ sort a\r\n print $ (x - x `mod` 2) + y\r\n solve $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n solve n"}], "negative_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (group, sort)\n\nsolve n as\n | n == 1 = putStrLn \"1\"\n | otherwise = do\n let blocks = group $ sort as\n let lengths = sum $ map length blocks\n\n putStrLn $ show $ (length blocks) - (fromEnum $ odd lengths)\n \n\nread = do\n s <- C.getLine\n\n let n = fst $ fromJust $ C.readInt s\n\n s <- C.getLine\n\n let as = map (fst . fromJust . C.readInt) (C.words s)\n\n solve n as\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (group, sort)\n\nsolve = do\n s <- C.getLine\n\n let n = fst $ fromJust $ C.readInt s\n\n s <- C.getLine\n\n let as = map (fst . fromJust . C.readInt) (C.words s)\n let blocks = group $ sort as\n let lengths = sum $ map length blocks\n\n putStrLn $ show $ (length blocks) - (fromEnum $ odd lengths)\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) solve\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Control.Monad.State.Class\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport Data.Char\nimport Data.Functor.Identity\nimport qualified Data.IntMap as M\nimport Data.Maybe\n\ntype ParserT = StateT C.ByteString\n\ntype ComputationT m = StateT (M.IntMap Int) (ParserT m)\n\n-- A computation is a monadic action with an input string and an intmap \"variable\" as state.\ntype Computation = ComputationT Identity\n\nrunComputation :: Computation a -> C.ByteString -> a\nrunComputation computation = runIdentity . evalStateT (evalStateT computation M.empty)\n\nmain :: IO ()\nmain = do\n t <- int <$> C.getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n n <- int <$> C.getLine\n C.getLine >>= output . runComputation (replicateM_ n populateTree >> eliminateTree)\n\neliminateTree :: Computation Int\neliminateTree = (length . filter odd . map snd . M.toList) <$> get\n\npopulateTree :: Computation ()\npopulateTree = do\n val <- lift getInt\n modify $ M.alter (pure . maybe 1 succ) val\n\ngetInt :: Monad m => ParserT m Int\ngetInt = StateT $ pure . fromJust . C.readInt . C.dropWhile isSpace\n\nint :: C.ByteString -> Int\nint = fst . fromJust . C.readInt\n\noutput :: Int -> IO ()\noutput = L.putStrLn . B.toLazyByteString . B.intDec\n"}], "src_uid": "ab7ab67941783da5c16f6294eb1910d9"} {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n", "positive_code": [{"source_code": "ri :: IO [Integer]\nri = (map read . words) `fmap` getLine\n\nmain = do\n\tn <- read `fmap` getLine\n\ta <- ri\n\tlet a' = map (+(-1)) a\n\tputStrLn $ show $ n + sum (zipWith (*) a' [1..])\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nsolve = fst . foldl' f (0,1)\n where f (c,p) n = c' `seq` p' `seq` (c',p')\n where c' = c + 1 + (n-1)*p\n p' = p + 1\n\nmain = print . solve . map (fst . fromJust . B.readInteger) . tail . B.words =<< B.getContents\n"}, {"source_code": "import Control.Arrow ((>>>), second)\nmain = getLine >> getLine >>= print . sum . zipWith (curry (second (subtract 1) >>> uncurry (*) >>> (1+))) [1..] . map read . words\n"}, {"source_code": "solve :: [Integer] -> Integer\nsolve = sum . zipWith (\\i x -> (x - 1) * i + 1) [1..]\nmain = putStrLn.show.solve.map read.tail.words =<< getContents"}, {"source_code": "readInteger :: String -> Integer\nreadInteger token = read token :: Integer\n\n\nsolve :: [Integer] -> Integer\nsolve ans = sum $ zipWith (*) [1 ..] $ (map pred begin) ++ [end]\n where begin = init ans\n end = last ans\n\nmain :: IO ()\nmain = interact (show . solve . map readInteger . tail . words)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n n <- read `liftM` getLine\n a <- ( map read . words ) `liftM` getLine :: IO [Integer]\n putStrLn $ show $ n + ( sum $ zipWith (\\a k -> (a-1) * k) a [1..] )\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words"}, {"source_code": "solve :: [Integer] -> Integer\nsolve (n:xs) = foldl (\\dp (x, i) -> dp + (x - 1) * i + 1) 0 $ zip xs $ iterate (+1) 1\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n a <- replicateM n readInteger\n return a\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve :: [Integer] -> Integer\nsolve a = sum a' + fromIntegral n\n where\n n = length a\n a' = zipWith (*) [1..] (map pred a)\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words"}, {"source_code": "main=fmap(map read.words)getContents>>=print.sum.zipWith(\\i x->x*i-i+1)[1..].tail"}, {"source_code": "ri :: IO [Integer]\nri = (map read . words) `fmap` getLine\n\nmain = do\n\tn <- read `fmap` getLine\n\ta <- ri\n\tlet a' = map (+(-1)) a\n\tputStrLn $ show $ n + sum (zipWith (*) a' [1..])\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}, {"source_code": "s w=sum[(x-1)*i|(i,x)<-zip[1..](w++[2])]-1\nmain=interact$show.s.map read.tail.words"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}, {"source_code": "import Data.List\n\nparse s = \n let ss = (lines s) !! 1\n in map (read::String->Integer) (words ss)\n\nsolve [n] = n \nsolve nums = loop 0 1 nums\n\nloop total _ [] = total \nloop total last (n:ums) = loop (total + last*(n-1) + 1) (last+1) ums\n\n\nmain = interact (show . solve . parse)\n"}, {"source_code": "main=interact$show.sum.zipWith(\\i x->x*i-i+1)[1..].tail.map read.words\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nsolve = fst . foldl' f (0,1)\n where f (c,p) n = c' `seq` p' `seq` (c',p')\n where c' = c + 1 + (n-1)*p\n p' = p + 1\n\nmain = print . solve . map (fst . fromJust . B.readInt) . tail . B.words =<< B.getContents\n"}, {"source_code": "solve :: [Int] -> Int\nsolve (n:xs) = foldl (\\dp (x, i) -> dp + (x - 1) * i + 1) 0 $ zip xs $ iterate (+1) 1\n\nmain = interact $ show.solve.map read.words"}, {"source_code": "s w=sum[x*(i-1)|(i,x)<-zip[1..](w++[2])]-1\nmain=interact$show.s.map read.tail.words"}, {"source_code": "import Data.List\n\nparse s = \n let ss = (lines s) !! 1\n in map (read::String->Int) (words ss)\n\nsolve [n] = n \nsolve nums = loop 0 1 nums\n\nloop total _ [] = total \nloop total last (n:ums) = loop (total + last*(n-1) + 1) (last+1) ums\n\n\nmain = interact (show . solve . parse)\n"}, {"source_code": "import Data.List\n\nparse s = \n let ss = (lines s) !! 1\n in map (read::String->Int) (words ss)\n\nsolve [n] = n \nsolve nums = length ones + (if rest /= [] then sum rest + 1 else 0 )\n where\n (ones, rest) = partition ((==) 1) nums\n\nmain = interact (show . solve . parse)\n"}], "src_uid": "c8531b2ab93993b2c3467595ad0679c5"} {"source_code": "import Data.List\r\n\r\nenumerate :: Int -> [Int] -> [(Int, Int)]\r\nenumerate n [] = []\r\nenumerate n (x:xs) = (x, n):enumerate (n+1) xs\r\n\r\neliminate :: [(Int, Int)] -> [(Int, Int)]\r\neliminate [] = []\r\neliminate [a] = [a]\r\neliminate (a:b:xs) = if fst a == fst b then eliminate (a:xs) else a:eliminate (b:xs)\r\n\r\ncompress :: [Int] -> [(Int,Int)]\r\ncompress xs = eliminate(reverse.sort $ enumerate 1 xs)\r\n\r\nsolve :: [Int] -> String\r\nsolve [] = \"-1\"\r\nsolve xs = if length compressed < 1100 then show $ maximum $ [maximum[if gcd (fst x) (fst y) == 1 then snd x + snd y else -1 | y <- compressed] | x <- compressed] else error \"11\"\r\n where compressed = compress xs \r\n\r\ntestCase = do\r\n n <- getLine\r\n wordList <- words `fmap` getLine\r\n let numList = read `fmap` wordList\r\n putStrLn $ solve numList\r\n\r\nrepeatDo 0 m = return []\r\n\r\nrepeatDo n m = do\r\n x1 <- m\r\n x2 <- repeatDo (n - 1) m\r\n return (x1 : x2)\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatDo n testCase", "positive_code": [{"source_code": "import Data.List\r\n\r\nenumerate :: Int -> [Int] -> [(Int, Int)]\r\nenumerate n [] = []\r\nenumerate n (x:xs) = (x, n):enumerate (n+1) xs\r\n\r\neliminate :: [(Int, Int)] -> [(Int, Int)]\r\neliminate [] = []\r\neliminate [a] = [a]\r\neliminate (a:b:xs) = if fst a == fst b then eliminate (a:xs) else a:eliminate (b:xs)\r\n\r\ncompress :: [Int] -> [(Int,Int)]\r\ncompress xs = eliminate(reverse.sort $ enumerate 1 xs)\r\n\r\nsolve :: [Int] -> String\r\nsolve [] = \"-1\"\r\nsolve xs = show $ maximum $ [maximum[if gcd (fst x) (fst y) == 1 then snd x + snd y else -1 | y <- compressed] | x <- compressed]\r\n where compressed = compress xs \r\n\r\ntestCase = do\r\n n <- getLine\r\n wordList <- words `fmap` getLine\r\n let numList = read `fmap` wordList\r\n putStrLn $ solve numList\r\n\r\nrepeatDo 0 m = return []\r\n\r\nrepeatDo n m = do\r\n x1 <- m\r\n x2 <- repeatDo (n - 1) m\r\n return (x1 : x2)\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatDo n testCase"}], "negative_code": [], "src_uid": "d665ecbf36cc0c0ddd148137fb693bf2"} {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as B\r\nimport qualified Data.Map.Lazy as M\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\ndata Input = Input {n :: Int, cs::[[Int]]}\r\ndata Output = Output Bool deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n cs)\r\n | odd n = Output False\r\n | otherwise = Output $ solve' n cs\r\n\r\nsolve' :: Int -> [[Int]] -> Bool\r\nsolve' n cs' = foldr (||) False $ [works c1 c2 | (c1:c3:cs3) <- L.tails cs, c2<-(c3:cs3)] where\r\n majority ds = sum ds >= (n `div` 2)\r\n cs = filter majority cs'\r\n works x y = all (>0) $ zipWith (+) x y\r\n\r\n-- gives a State(T) monad which when run gives Input\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n ~[n] <- getIntegrals 1\r\n rs <- replicateM n $ getIntegrals 5\r\n return $ Input n (L.transpose rs)\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output False) = str \"NO\" <> nl\r\n go (Output True) = str \"YES\" <> nl \r\n\r\nnumberOfTestcases :: St [Int]\r\nnumberOfTestcases = explicit\r\n where implicit = return [1] :: St [Int]\r\n explicit = getIntegrals 1\r\n\r\n----------------------------- library -------------------------------\r\nmodp :: Integral t=>t->t\r\nmodp = (`mod` (10^9+7))\r\n\r\nfastPow :: Integral t=>(t->t)->t->t->t\r\nfastPow modf base' p' = go base' p' where\r\n go base 0 = base\r\n go base p = go (base`times`base) (p`div`2) `times` base^(p`mod`2)\r\n times = (modf.).(*)\r\n\r\nprimeFac :: Integral t=> t -> [(t,Int)]\r\nprimeFac = map (\\xs-> (head xs,length xs)).L.group.tryDiv 2 where\r\n tryDiv d n\r\n | n `mod` d == 0 = d : tryDiv d (n `div` d)\r\n | n == 1 = []\r\n | d*d < n = tryDiv (d+1+d`mod`2) n\r\n | otherwise = tryDiv n n\r\n\r\numakeset xs = (M.fromList (zip xs xs), M.fromList (zip xs (repeat 0)))\r\nufind uf@(parents,ranks) x = if parents M.! x == x then x else ufind uf (parents M.! x)\r\nuunion uf@(parents, ranks) x y = if fx==fy then (False,uf) else (True, (parents1, ranks1)) where\r\n (fx, fy) = (ufind uf x, ufind uf y)\r\n [(r0,f0), (r1,f1)] = L.sort [(ranks M.! fx, fx), (ranks M.! fy, fy)]\r\n parents1 = M.insert f0 f1 parents\r\n ranks1 = if r0 /= r1 then ranks else M.insert f1 (r1+1) ranks\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n ~[nTc] <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.IntMap as M\nimport qualified Data.IntSet as S\n\ntype Students = S.IntSet\ntype Days = M.IntMap Students\n\ncalc :: Int -> Days -> Bool\ncalc n tree =\n let days = [(i,j) | i <- [1..5], j <- [i+1..5]]\n in\n any (\\(i,j) ->\n let left = M.findWithDefault S.empty i tree\n right = M.findWithDefault S.empty j tree\n intersectionSize = S.size $ S.intersection left right\n leftDifSize = S.size $ S.difference left right\n rightDifSize = S.size $ S.difference right left\n in\n leftDifSize <= (n `div` 2) &&\n rightDifSize <= (n `div` 2) &&\n intersectionSize >= n - leftDifSize - rightDifSize\n ) days\n\nupdateStudent :: Int -> Maybe Students -> Maybe Students\nupdateStudent i Nothing = Just (S.insert i S.empty)\nupdateStudent i (Just s) = Just (S.insert i s)\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n daysMap <- foldM (\\tree i -> do\n line <- getLine\n let days = map (\\(i,j) -> i) $ filter (\\(i,j) -> j>0) $ zip [1..] $ map read $ words line :: [Int]\n let newTree = foldl (\\t d -> M.alter (updateStudent i) d t) tree days\n return newTree) M.empty [1..n]\n if (calc n daysMap) then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}], "negative_code": [], "src_uid": "068cbfb901aadcd15f794dbbf3dfd453"} {"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\nimport Data.Bits((.&.), (.|.), xor)\r\nimport Data.Maybe\r\n\r\n\r\nresult :: Integer -> Integer -> String -> Int\r\nresult n k str = length indices where\r\n\tstarS = S.fromList star\r\n\tstrM = M.fromList $ zip [0..] str\r\n\tstar = foldr (\\(i, s) l -> if s=='*' then i:l else l) [] $ zip [0..] str\r\n\t\r\n\tnextId i = fromJust $ S.lookupLE (i+k) starS \r\n\r\n\tindices = L.nub $ aux (star !! 0) star where\r\n\t\taux _ [] = []\r\n\t\taux v (x:xs) \r\n\t\t\t| x == v = x : aux (nextId x) xs\r\n\t\t\t| otherwise = aux v xs\r\n\r\n\r\n\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\t[n, k] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tstr <- getLine\r\n\t\tprint $ result n k str\r\n\t\tloop $ t - 1\r\n\tloop t", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust, fromMaybe)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf (C.pack <$> testCase)) >>> C.unlines\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n (n, k) <- pair int int\r\n s <- str\r\n return . show $ compute k s\r\n\r\ncompute :: Int -> String -> Int\r\ncompute k s = replace (-10^9) [i | (c, i) <- zip s [1..], c == '*']\r\n where\r\n replace _ [] = 0\r\n replace _ [_] = 1\r\n replace p (x:x':xs)\r\n | x' <= p + k = replace p (x':xs)\r\n | otherwise = 1 + replace x (x':xs)\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\ncstr :: Scanner C.ByteString\r\ncstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> cstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> cstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> cstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> cstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nsolve a n k i\r\n | i >= n = 1\r\n | a!i == '*' = 1 + solve a n k (i+k)\r\n | otherwise = solve a n k (i-1)\r\n\r\nprintResult = do\r\n [n,k] <- readInts\r\n s <- getLine\r\n let a = dropWhile (=='.') s\r\n b = dropWhile (=='.') $ reverse a\r\n m = length b\r\n z = listArray (1,n) b\r\n print $ solve z m k 1 \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.Array\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nsolve a n k i\r\n | i >= n = 1\r\n | a!i == '*' = 1 + solve a n k (i+k)\r\n | otherwise = solve a n k (i-1)\r\n\r\nprintResult = do\r\n [n,k] <- readInts\r\n s <- getLine\r\n let a = dropWhile (=='.') s\r\n b = dropWhile (=='.') $ reverse a\r\n m = length b\r\n z = listArray (1,n) b\r\n print b\r\n print $ solve z m k 1 \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\nimport Data.Bits((.&.), (.|.), xor)\r\nimport Data.Maybe\r\n\r\n\r\nresult :: Integer -> Integer -> String -> Int\r\nresult n k str = length indices where\r\n\tstarS = S.fromList star\r\n\tstrM = M.fromList $ zip [0..] str\r\n\tstar = foldr (\\(i, s) l -> if s=='*' then i:l else l) [] $ zip [0..] str\r\n\t\r\n\tnextId i = fromJust $ S.lookupLT (i+k) starS \r\n\r\n\tindices = L.nub $ aux (-1) star where\r\n\t\taux _ [] = []\r\n\t\taux _ [x] = [x]\r\n\t\taux v (x:xs) \r\n\t\t\t| x > v = x : aux (nextId x) xs\r\n\t\t\t| otherwise = aux v xs\r\n\r\n\r\n\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\t[n, k] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tstr <- getLine\r\n\t\tprint $ result n k str\r\n\t\tloop $ t - 1\r\n\tloop t"}], "src_uid": "874e22d4fd8e35f7e0eade2b469ee5dc"} {"source_code": "import Data.Array.IO\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\n\nfactor x = factor' x 2\n where\n factor' x y\n | y * y > x = if x /= 1 then [(x, 1)] else []\n | x `mod` y == 0 = (y, divTime) : (factor' divFinal (y+1))\n | otherwise = factor' x (y+1)\n where\n divList = takeWhile ((==0) . snd) $ iterate (\\(d,r) -> divMod d y) (x, 0)\n divTime = length divList - 1\n divFinal = fst $ last divList\n\nflist :: [(Int, Int)] -> [Int]\nflist [] = [1]\nflist lt = map fst lt\n\ntype Request = (Char, Int)\ntype Status = IOUArray Int Int\n\nprocess :: Status -> Request -> IO ()\n\nprocess st ('+', num) = do\n let fts = flist $ factor num\n\n cur <- readArray st (head fts)\n if cur == num\n then putStrLn \"Already on\"\n else do\n chk <- forM fts $ readArray st\n if all (== 0) chk\n then do\n forM_ fts $ \\x -> writeArray st x num\n putStrLn \"Success\"\n else putStrLn $ \"Conflict with \" ++ show (fromJust (find (/= 0) chk))\n\nprocess st ('-', num) = do\n let fts = flist $ factor num\n\n cur <- readArray st (head fts)\n if cur /= num\n then putStrLn \"Already off\"\n else do\n forM_ fts $ \\x -> writeArray st x 0\n putStrLn \"Success\"\n\nmain = do\n [n, m] <- liftM (map read . words) getLine\n\n st <- newArray (1, n) 0\n\n replicateM_ m $ do\n [[c], num] <- liftM words getLine\n process st (c, read num)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.IntMap(IntMap)\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do _ <- getLine\n cis <- map ((\\[x,y]->(B.head x,read' y)) . B.words) <$> B.lines <$> B.getContents\n putStr $ unlines $ solve cis\n\nread' s = let Just (n,_) = B.readInt s in n\n\nsolve :: [(Char,Int)] -> [String]\nsolve cis = snd $ mapAccumL step state0 cis\n where state0 = IM.empty \n\nstep :: IntMap [Int] -> (Char,Int) -> (IntMap [Int], String)\nstep state ('+',n) = activate state n\nstep state ('-',n) = deactivate state n\n\nactivate :: IntMap [Int] -> Int -> (IntMap [Int], String)\nactivate state n = case IM.lookup p state of\n \t\t Just (x:xs) -> if elem n (x:xs)\n\t\t\t\t then (state, \"Already on\") \n else (state, \"Conflict with \"++(show x))\n _ -> case isConflict ps of\n\t\t Nothing -> let state' = IM.unionWith (++) state $ IM.fromList . zip (p:ps) $ repeat [n] \n\t\t in (state', \"Success\")\n\t\t\t Just y -> (state, \"Conflict with \"++(show y))\n where (p:ps) = primeFactors n\n isConflict :: [Int] -> Maybe Int\n\tisConflict [] = Nothing\n\tisConflict (x:xs) = case IM.lookup x state of\n\t Just (y:_) -> Just y\n\t\t\t _ -> isConflict xs\n\ndeactivate :: IntMap [Int] -> Int -> (IntMap [Int], String)\ndeactivate state n = case IM.lookup p state of\n \t\t Just xs -> if elem n xs\n\t\t\t then let state' = IM.unionWith del state $ IM.fromList . zip (p:ps) $ repeat [n]\n\t\t\t in (state', \"Success\")\n else (state, \"Already off\")\n _ -> (state, \"Already off\")\n where (p:ps) = primeFactors n\n del xs [y] = let (zs,(_:ws)) = span (y/=) xs\n\t in zs++ws\n\nprimeFactors :: Int -> [Int]\nprimeFactors 1 = [1]\nprimeFactors n = primeFactors' n (2:[3,5..])\nprimeFactors' 1 _ = []\nprimeFactors' n (p:ps)\n | n < p*p = [n]\n | r == 0 = p:primeFactors' q (p:ps)\n | otherwise = primeFactors' n ps\n where (q,r) = divMod n p\n"}, {"source_code": "\nimport qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport Control.Arrow\nimport Data.IntMap(IntMap, (!))\nimport Data.IntSet(IntSet)\nimport Data.List\n\nprimes :: [Int]\nprimes = 2 : filter (\\c -> all (\\p -> c `mod` p /= 0) (takeWhile (\\p -> p * p <= c) primes)) [3..]\n\nfacts :: Integer -> [Int] -> Int -> [Int] -> [(Int, [Int])]\nfacts lim p@(h:t) c l | fromIntegral c > lim = []\n | otherwise = tryH ++ tryT where\n tryH | fromIntegral h * fromIntegral c <= lim = [(h * c, h : l)] ++ facts lim p (h*c) (h : l)\n | otherwise = []\n tryT | fromIntegral h * fromIntegral c <= lim = facts (lim :: Integer) t c l\n | otherwise = []\n\ncache :: IntMap IntSet\ncache = Map.fromList $ map (second Set.fromList) $ (1,[]) : facts 100000 primes 1 []\n\nfactors :: Int -> [Int]\nfactors = Set.toList . (cache !)\n\n\ntype State = ( IntSet -- turned on\n , IntMap Int -- taken by\n )\n\nstep :: [String] -> State -> (State, String)\nstep [\"+\", ns] s@(on,taken)\n | Set.member n on = (s, \"Already on\")\n | not (null bad) = (s, \"Conflict with \" ++ show (taken ! head bad))\n | otherwise = ((Set.insert n on, Map.union taken (Map.fromList $ map (\\x -> (x, n)) $ factors n)), \"Success\")\n where\n n = read ns\n bad = filter (`Map.member` taken) (factors n)\nstep [\"-\", ns] s@(on, taken)\n | not (Set.member n on) = (s, \"Already off\")\n | otherwise = ((Set.delete n on, Map.difference taken (Map.fromList $ map (\\x -> (x, n)) $ factors n) ), \"Success\") where\n n = read ns\n\n\n\nmain = interact $ unlines . snd . mapAccumL (flip step) (Set.empty, Map.empty) . tail . map words . lines\n"}, {"source_code": "\nimport Char (ord)\nimport Control.Monad (liftM)\nimport Data.List (foldl')\nimport Data.Map (Map, (!), delete, empty, insert, member)\nimport Data.Set (Set, delete, empty, insert, member)\n\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nisPrime :: Int -> Bool\nisPrime n = all (\\x -> mod n x /= 0) $ takeWhile (\\x -> x * x <= n) primes\n\nprimes :: [Int]\nprimes = 2 : [n | n <- [3,5..], isPrime n]\n\nfactorize :: Int -> [Int]\nfactorize = factorize' primes\n where\n factorize' _ 1 = []\n factorize' ps'@(p:ps) n\n | mod n p == 0 = p : factorize' ps' (div n p)\n | p * p > n = [n]\n | otherwise = factorize' ps n\n\nprimesDivisors :: Int -> [Int]\nprimesDivisors = delEq . factorize\n where\n delEq [] = []\n delEq [x] = [x]\n delEq (x:y:xs)\n | x == y = delEq (y:xs)\n | otherwise = x : (delEq (y:xs))\n\n--------------------------------------------------------------------------------\n\nreadQuery :: String -> Either Int Int\nreadQuery (c : ' ' : s) = readQuery' s (if c == '+' then Right else Left) 0\n where\n readQuery' [] f a = f a\n readQuery' (c:s) f a = readQuery' s f (10*a + ord c - ord '0')\n\ndata OnOff = On | Off\ndata Result = Success | Already OnOff | ConflictWith Int\n\ninstance Show Result\n where\n show Success = \"Success\"\n show (Already On) = \"Already on\"\n show (Already Off) = \"Already off\"\n show (ConflictWith n) = concat [\"Conflict with \", show n]\n\nfindConflict :: Map Int Int -> [Int] -> Maybe Int\nfindConflict map divisors = findConflict' divisors\n where\n findConflict' [] = Nothing\n findConflict' (d:ds)\n | M.member d map = Just (map ! d)\n | otherwise = findConflict' ds\n\nsolve :: [Either Int Int] -> [Result]\nsolve xs = solve' (M.empty, S.empty) xs\n where\n solve' _ [] = []\n solve' (map, set) (Right n : xs)\n | S.member n set = Already On : (solve' (map, set) xs)\n | otherwise = case findConflict map divisors of\n Nothing -> Success : (solve' (map', set') xs)\n Just m -> ConflictWith m : (solve' (map, set) xs)\n where\n divisors = primesDivisors n\n map' = foldl (\\map d -> M.insert d n map) map divisors\n set' = S.insert n set\n solve' (map, set) (Left n : xs)\n | S.member n set = Success : (solve' (map', set') xs)\n | otherwise = Already Off : (solve' (map, set) xs)\n where\n map' = foldl (\\map d -> M.delete d map) map (primesDivisors n)\n set' = S.delete n set\n\nmain :: IO ()\nmain = do\n lines' <- liftM lines getContents\n let [n, m] = map read $ words $ head lines'\n let qs = map readQuery $ take m $ tail lines'\n mapM_ print $ solve qs\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.IntMap(IntMap)\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do _ <- getLine\n cis <- map ((\\[x,y]->(B.head x,read' y)) . B.words) <$> B.lines <$> B.getContents\n putStr $ unlines $ solve cis\n\nread' s = let Just (n,_) = B.readInt s in n\n\nsolve :: [(Char,Int)] -> [String]\nsolve cis = snd $ mapAccumL step state0 cis\n where state0 = IM.empty \n\nstep :: IntMap [Int] -> (Char,Int) -> (IntMap [Int], String)\nstep state ('+',n) = activate state n\nstep state ('-',n) = deactivate state n\n\nactivate :: IntMap [Int] -> Int -> (IntMap [Int], String)\nactivate state n = case IM.lookup p state of\n Nothing -> let state' = IM.unionWith (++) state $ IM.fromList . zip (p:ps) $ repeat [n] \n\t\t in (state', \"Success\")\n Just [] -> let state' = IM.unionWith (++) state $ IM.fromList . zip (p:ps) $ repeat [n] \n\t\t in (state', \"Success\")\n\t\t Just (x:xs) -> if elem n (x:xs)\n\t\t\t\t then (state, \"Already on\") \n else (state, \"Conflict with \"++(show x))\n where (p:ps) = primeFactors n\n\ndeactivate :: IntMap [Int] -> Int -> (IntMap [Int], String)\ndeactivate state n = case IM.lookup p state of\n Nothing -> (state, \"Already off\")\n Just [] -> (state, \"Already off\")\n\t\t Just (x:xs) -> if elem n (x:xs)\n\t\t\t\t then let state' = IM.unionWith del state $ IM.fromList . zip (p:ps) $ repeat [n]\n\t\t\t\t in (state', \"Success\")\n else (state, \"Already off\")\n where (p:ps) = primeFactors n\n del xs [y] = let (zs,(_:ws)) = span (y/=) xs\n\t in zs++ws\n\nprimeFactors :: Int -> [Int]\nprimeFactors 1 = [1]\nprimeFactors n = primeFactors' n (2:[3,5..])\nprimeFactors' 1 _ = []\nprimeFactors' n (p:ps)\n | n < p*p = [n]\n | r == 0 = p:primeFactors' q (p:ps)\n | otherwise = primeFactors' n ps\n where (q,r) = divMod n p\n"}], "src_uid": "6cec3662101b419fb734b7d6664fdecd"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ((n:x:[]) : as : rest) = solve x as : process rest\n \nsolve :: Int -> [Int] -> Int\nsolve x as = rec 0 1 $ sortBy (flip compare) as where\n rec c _ [] = c\n rec c pc (a:as) | pc*a >= x = rec (c+1) 1 as\n | otherwise = rec c (pc+1) as\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, x] <- map read . words <$> getLine\n as <- reverse . sort . map read . words <$> getLine\n print $ solve 1 x as\n\nsolve c x (a : as)\n | c * a >= x = 1 + solve 1 x as\n | otherwise = solve (c + 1) x as\nsolve _ _ _ = 0\n"}], "negative_code": [], "src_uid": "8a6953a226abef41a44963c9b4998a25"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tboard <- lines <$> getContents\n\tputStrLn $ which \"YES\" \"NO\" $ correct_flag board || correct_flag ( transpose board )\n\ncorrect_flag board\n\t| has_valid_lines board && three_colored board = let hs = map length . group . map head $ board in length hs == 3 && ( ( == 1 ) . length . group . sort $ hs )\n\t| otherwise = False\n\twhere\n\t\thas_valid_lines = all ( ( == 1 ) . length . group )\n\t\tthree_colored = ( == 3 ) . length . group . sort . map ( ord . head )\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\ncolors :: [String] -> Int -> Int -> Int -> Int -> Set Char\ncolors s n n' m m' = foldl (\\r (i, j) -> Set.insert (s !! i !! j) r)\n Set.empty [(i, j) | (i, j) <- idx]\n where idx = [(i, j) | i <- [n..n'-1], j <- [m..m'-1]]\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, m] = map read (words line)\n flag <- replicateM n getLine\n let sa = colors flag 0 (n `div` 3) 0 m\n let sb = colors flag (n `div` 3) (2 * (n `div` 3)) 0 m\n let sc = colors flag (2 * (n `div` 3)) n 0 m\n let ta = colors flag 0 n 0 (m `div` 3)\n let tb = colors flag 0 n (m `div` 3) (2 * (m `div` 3))\n let tc = colors flag 0 n (2 * (m `div` 3)) m\n let b = ((n `mod` 3 == 0) &&\n (Set.size sa == 1) &&\n (Set.size sb == 1) &&\n (Set.size sc == 1) &&\n (Set.size (Set.unions [sa, sb, sc]) == 3)) ||\n ((m `mod` 3 == 0) &&\n (Set.size ta == 1) &&\n (Set.size tb == 1) &&\n (Set.size tc == 1) &&\n (Set.size (Set.unions [ta, tb, tc]) == 3))\n if b then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain =\n do\n nks <- getLine\n let [n, k] = map read $ words nks\n\n flag <- forM [1..n] (\\x -> getLine)\n let g1 = group flag\n g2 = group.transpose $ flag\n\n let t1 = length $ group.sort $ g1\n t2 = length $ group.sort $ g2\n\n let s1 = map length g1\n s2 = map length g2\n\n if (t1 == 1 || t1 == 3) && (t2 == 1 || t2 == 3)\n then if length s1 == 1 && length s2 == 3 && (length.group $ s2) == 1\n then putStrLn \"YES\"\n else\n if length s2 == 1 && length s1 == 3 && (length.group $ s1) == 1\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n else putStrLn \"NO\"\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport Data.List\nmain = getContents >>= putStr . (\\(_:_:f) -> if ok f || ok (transpose f) then \"YES\" else \"NO\") . words\nok :: [String] -> Bool\nok f = sort (map (head . head) gs) == sort \"RGB\" && allEq (map length gs) && all (allEq . concat) gs\n where gs = group f\nallEq :: Eq a => [a] -> Bool\nallEq = null . tail . nub"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport Data.List\nmain = getContents >>= putStr . (\\(_:_:f) -> if ok f || ok (transpose f) then \"YES\" else \"NO\") . words\nok :: [String] -> Bool\nok f = sort (map (head . head) gs) == sort ['B', 'R', 'G'] && allEq (map length gs) && all (allEq . concat) gs\n where gs = group f\nallEq :: Eq a => [a] -> Bool\nallEq = null . tail . nub\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport Data.List\nmain = getContents >>= putStr . (\\(_:_:f) -> if ok f || ok (transpose f) then \"YES\" else \"NO\") . words\nok f = (\\(x:xs) -> all (== x) xs) (map length gs) && length gs == 3\n where gs = group f"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain =\n do\n nks <- getLine\n let [n, k] = map read $ words nks\n\n flag <- forM [1..n] (\\x -> getLine)\n let s1 = map length $ group flag\n s2 = map length $ group.transpose $ flag\n\n if length s1 == 1 && length s2 == 3 && (length.group $ s2) == 1\n then putStrLn \"YES\"\n else\n if length s2 == 1 && length s1 == 3 && (length.group $ s1) == 1\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}], "src_uid": "0988b8439c6699107c77345037162fba"} {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:b:xs) = (func' b) ++ (func xs)\n where \n func' = solve.map toInt.words\nfunc _ = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[Int]->String\nsolve = unwords.map toString.findAns\n where \n findAns' (x:xs) = findMin (diff (x:xs++[x]))\n findAns a | n == (length a) = n:1:[]\n | otherwise = n:(n+1):[]\n where\n n = findAns' a\n\ndiff (a:b:xs) = (abs (a-b)):diff (b:xs)\ndiff _ = []\n\nfindMin::[Int]->Int\nfindMin = snd.findMin' 1\n where \n findMin'::Int->[Int]->(Int,Int)\n findMin' a (b:c:xs) | b < (fst next) = (b, a)\n | otherwise = next\n where \n next = (findMin' (a+1) (c:xs))\n findMin' a (b:xs) = (b,a)", "positive_code": [{"source_code": "main = do\n\tgetLine\n\ta <- fmap (zip [1 ..] . map read . words) getLine\n\tputStrLn $ unwords $ map show $ (\\(_,(a,b))->[a,b]) $ minimum $ gao $ last a : a\ngao :: [(Int, Int)] -> [(Int, (Int, Int))]\ngao ((a,b):x@((c,d):_)) = (abs(b-d),(a,c)): gao x\ngao _ = []\n"}, {"source_code": "\nmain = do\n\ta<-getLine\n\tb<-getLine\n\tlet c = words b\n\tlet (n1,n2)=solve3 (map read c)\n\tputStrLn $ (show n1)++\" \"++ (show n2)\n\nsolve [] = []\nsolve (s1:[]) = [] \nsolve (s1:s2:ss) = [dist] ++ solve (s2:ss)\n\t where dist = abs (s1 - s2)\n\nsolve2 s = solve s ++ [(abs (head s - last s))]\n\nsolve3 s = if pairNum+1 == length s then (1,length s)\n\t else (pairNum+1,pairNum+2)\n where mdist = minimum (solve2 s)\n pairNum = length $takeWhile (/=mdist) (solve2 s)\n"}, {"source_code": "\nimport qualified Data.List as List\n\n\nrotate xs = tail xs ++ [head xs] \n\nmin_diff = List.minimumBy (\\(_, a) (_, b) -> compare a b)\nheight_diff (a, b) = abs (a - b)\nneighbours heights ct = zip (zip [1..ct] (rotate [1..ct])) (map height_diff (zip heights (rotate heights)))\n\nprint_result heights count =\n let ((s1, s2), _) = min_diff (neighbours heights count) in\n show s1 ++ \" \" ++ show s2\n\nmain :: IO ()\nmain = do\n soldier_count <- getLine >>= return . read\n heights <- getLine >>= return . (map read . words)\n putStr (print_result heights soldier_count)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n let\n next i = (i+1) `mod` n\n i = minimumBy (compare `on` f) [0..n-1]\n where\n f :: Int -> Int\n f i = abs (xs!!i - xs!!j) where j = next i\n\n putStrLn $ show (i+1) ++ \" \" ++ show (next i + 1)\n"}, {"source_code": "rec :: [Int] -> Int\nrec (x1 : (x2 : xs)) = min (rec (x2 : xs)) (abs (x1 - x2))\nrec _ = maxBound\n\nfld :: [Int] -> Int\nfld xs = abs ((head xs) - (last xs))\n\nmd :: [Int] -> Int\nmd xs = min (fld xs) (rec xs)\n\nfnd :: Int -> Int -> [Int] -> [Int]\nfnd i d (x1 : (x2 : xs))\n | d == abs (x2 - x1) = [i, i + 1]\n | otherwise = fnd (i + 1) d (x2 : xs)\n\nsolve :: [Int] -> [Int]\nsolve xs\n | fld xs == md xs = [1, length xs]\n | otherwise = fnd 1 (md xs) xs\n\nio :: String -> String\nio s = unwords $ map show $ solve $ map (read :: String -> Int) $ words $ head $ drop 1 $ lines s\n\nmain :: IO ()\nmain = do\n interact io"}, {"source_code": "main = do\n\tn <- readLn\n\ts <- getLine\n\tlet q = solve n (map read (words s))\n\tputStr (show (fst q) ++ \" \" ++ show (snd q))\nsolve :: Int -> [Int] -> (Int, Int)\nsolve n sp = let s = zipWith (\\a b -> abs (a - b)) sp (tail $ cycle sp);\n\t\t\t\t a = f (minimum s) s\n\t\t\t in (a, if a == n then 1 else (a + 1))\nf x (s:ss)\n\t| x == s = 1\n\t| otherwise = 1 + f x ss"}, {"source_code": "getDifference :: [Int] -> [Int]\ngetDifference a = solve_ (head a) a\n where\n solve_ a1 [a2] = [abs(a1 - a2)]\n solve_ a1 (a2:a3:as) = (abs(a2-a3)):(solve_ a1 (a3:as))\n\nfindMin :: [Int] -> Int\nfindMin a = fst (findMin2 1 (0, head a) (tail a))\n where\n findMin2 :: Int -> (Int, Int) -> [Int] -> (Int, Int)\n findMin2 _ (n, m) [] = (n, m)\n findMin2 cur (n, m) (a:as) = if a < m then findMin2 (cur + 1) (cur, a) as else findMin2 (cur + 1) (n, m) as\n\nsolve :: Int -> Int -> String\nsolve len num = if len == num then \"1 \" ++ show num else (show num) ++ \" \" ++ show (num + 1)\n\n\nmain = do\n n <- readLn::(IO Int)\n line <- getLine\n let a = map read (words line)\n putStrLn (solve n (1 + findMin (getDifference a)))"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Function\n\nmain = do\n n <- read <$> getLine :: IO [Int]\n h:hs <- zip [1..] . map read . words <$> getLine :: IO [(Int, Int)]\n let heights = h:hs ++ [h]\n diff (a, b) (c, d) = ((a,c), abs (b-d))\n dhs = zipWith diff heights (tail heights)\n ((i, j), _) = minimumBy (compare `on` snd) dhs\n putStrLn $ show i ++ \" \" ++ show j"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = putStrLn <$> unwords <$> map show =<< solve <$> readLn <*> (map read <$> words <$> getLine)\n\nsolve :: Integer -> [Integer] -> [Integer]\nsolve n as = snd $ minimum [ (abs (a - b), [ i, i `mod` n + 1 ]) | (i, a, b) <- zip3 [1..] as (tail $ cycle as) ]\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = solve <$> readLn <*> (map read . words <$> getLine) >>= putStrLn . unwords . map show\n\nsolve :: Integer -> [Integer] -> [Integer]\nsolve n as = snd $ minimum [ (abs (a - b), [ i, i `mod` n + 1 ]) | (i, a, b) <- zip3 [1..] as (tail $ cycle as) ]\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n ss <- fmap (map read . words) getLine\n let ds = map abs $ zipWith (-) ss (last ss : ss)\n Just k = findIndex (== minimum ds) ds\n putStrLn $ show ((k - 1) `mod` n + 1) ++ \" \" ++ show (k + 1)"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.lines\n\nfunc::[String]->String\nfunc (a:b:xs) = (func' b) \n where \n func' = solve.map toInt.words\nfunc _ = \"\"\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[Int]->String\nsolve = unwords.map toString.findAns\n where \n findAns' (x:xs) = findMin (diff (x:xs++[x]))\n findAns a | n == (length a) = n:1:[]\n | otherwise = n:(n+1):[]\n where\n n = findAns' a\n\ndiff (a:b:xs) = (abs (a-b)):diff (b:xs)\ndiff _ = []\n\nfindMin::[Int]->Int\nfindMin = snd.findMin' 1\n where \n findMin'::Int->[Int]->(Int,Int)\n findMin' a (b:c:xs) | b < (fst next) = (b, a)\n | otherwise = next\n where \n next = (findMin' (a+1) (c:xs))\n findMin' a (b:xs) = (b,a)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n <- readLn\n ps@(p : _) <- zip [1 ..] . take n <$> readData\n let check (i, x) (j, y) = ((i, j), abs (x - y))\n xs = zipWith check ps (tail ps ++ [p])\n answer@(i, j) = fst $ minimumBy (comparing snd) xs\n printf \"%d %d\\n\" (i :: Int) (j :: Int)\n\n\n\n"}, {"source_code": "\nmain = interact f\n\nf s =\n let w = words s\n x = read (head w)\n y = map read (tail w)\n p = recon x y\n in show (fst p) ++ \" \" ++ show (snd p)\n\n\n\nrecon :: Int -> [Int] -> (Int, Int)\nrecon n (x:xs) = let fperson = snd(subrecon n 0 ((x:xs)++ [x])) + 1\n in\n if n == fperson\n then (fperson, 1)\n else (fperson, fperson+1)\n\nsubrecon n c (x:x':xs)\n | c < n-1 = pairmin (abs(x - x'),c) (subrecon n (c + 1) (x':xs) )\n | otherwise = (abs(x - x'),c)\n\n\npairmin :: (Int,a) -> (Int,a) -> (Int,a)\npairmin (a,x) (b,x')\n | a < b = (a,x)\n | otherwise = (b,x')"}, {"source_code": "getnum :: IO [Int]\ngetnum = fmap (map read . words) getLine\n\nget n num = minimum s\n where s = (f (last num) (head num), n, 1) : zip3 left [1..] [2..]\n left = zipWith f num (tail num)\n f a b = abs $ a - b\n\nans (_, a, b) = show a ++ \" \" ++ show b\n\nmain = do\n n <- readLn\n num <- getnum\n putStrLn . ans $ get n num\n"}, {"source_code": "main = interact (ans)\nans theInput = unwords [show ans0,show $ mod ans0 n + 1] where\n [[n],a] = map ( map (read::String->Int)) $ map words $ lines theInput\n a0 = zip a [1..]\n a1 = [(abs (x-y),u)|((x,u),(y,v))<-zip a0 (tail $ a0 ++ [head a0])]\n ans0 = snd $ foldl1 min a1\n"}, {"source_code": "main = interact (ans)\nans theInput = unwords [show ans0,show $ mod ans0 n + 1] where\n theLines = lines theInput\n n = read (head theLines) ::Int\n a = zip (map (read ::String->Int) (take n $ words $ theLines !! 1)) [1..]\n a0 = a ++ [head a]\n a1 = zip a0 (tail a0)\n a2 = [(abs (x-y),u)|((x,u),(y,v))<-a1]\n minfst (x,u) (y,v) = if x getLine::IO Int\n\t\tx<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet c=(zipWith (\\a b-> abs (a-b)) x (tail x))\n\t\tlet d = c ++ [abs (head x - last x)]\n\t\tlet e = minimum d\n\t\tlet f = fromJust $elemIndex e d\n\n\t\tputStrLn $ intercalate \" \" $ map show [f+1, 1+ mod (f+1) n]\n\n\t\t\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n (a, b) = minimumBy (compare `on` (\\(a, b) -> abs $ a-b)) $ zip xs (tail xs ++ [head xs])\n i = fromJust (a `elemIndex` xs)\n j = length xs - 1 - fromJust (b `elemIndex` (reverse xs))\n\n putStrLn $ show (i+1) ++ \" \" ++ show (j+1)\n"}, {"source_code": "main = do\n n <- readLn\n s <- getLine\n let q = solve n (map read (words s))\n putStr (show (fst q) ++ \" \" ++ show (snd q))\nsolve :: Int -> [Int] -> (Int, Int)\nsolve n sp = let s = zipWith (+) sp (tail $ cycle sp);\n a = f (minimum s) s\n in (a, if a == n then 1 else (a + 1))\nf x (s:ss)\n | x == s = 1\n | otherwise = 1 + f x ss"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\tx<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet c=(zipWith (\\a b-> abs (a-b)) x (tail x))\n\t\tlet d = c ++ [abs (head x - last x)]\n\t\tlet e = minimum d\n\t\tlet f = fromJust $elemIndex e d\n\n\t\tputStrLn $ intercalate \" \" $ map show [f+1, mod (f+2) n]\n\n\t\t\n"}], "src_uid": "facd9cd4fc1e53f50a1e6f947d78e942"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n (n, m) <- liftM2 (,) get get\n a <- replicateM n get\n p <- replicateM m get\n putln $ if f2 a p then \"YES\" else \"NO\"\n\nf2 :: [Int] -> [Int] -> Bool\nf2 a p = let pk = runSTUArray $ do\n a <- newArray (1, 101) 0 :: ST s (STUArray s Int Int)\n forM_ p (\\c -> writeArray a c 1)\n return a\n in\n let ax = zip a [1..] in\n all (\\(ai, i) ->\n all (\\(aj, j) ->\n if i < j && ai > aj then\n all (\\k ->\n pk ! k /= 0)\n [i..j-1]\n else True\n ) ax\n ) ax\n \n", "positive_code": [{"source_code": "import Data.List as L\n\nsubarrays' :: [Int] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)]\nsubarrays' [] acc l r = (l,r):acc\nsubarrays' (x:xs) acc l r\n | x == r+1 = subarrays' xs acc l x\n | r < l = subarrays' xs acc x x\n | otherwise = subarrays' xs ((l, r):acc) x x\n\nsubarrays :: [Int] -> [(Int, Int)]\nsubarrays [] = []\nsubarrays xs = L.map (\\(l, r) -> (l, r+1)) (subarrays' array' [] 0 (-1))\n where array' = L.map (\\x -> x - 1) $ L.sort xs\n\nmysort :: [Int] -> [(Int, Int)] -> [Int]\nmysort xs [] = xs\nmysort xs ((l, r):rest) = mysort currAns rest\n where currAns = (L.take l xs) ++ (L.sort $ L.take (r-l+1) $ L.drop l xs) ++ (drop (r+1) xs)\n\nisSorted :: [Int] -> Bool\nisSorted [] = True\nisSorted [_] = True\nisSorted (a:b:rest) = a <= b && isSorted (b:rest)\n\nparse :: [String] -> String\nparse [_, xs', ps'] = if ans then \"YES\" else \"NO\"\n where xs = toIntArray xs'\n ps = toIntArray ps'\n intervals = subarrays ps\n ans = isSorted $ mysort xs intervals\n\ntoIntArray :: String -> [Int]\ntoIntArray s = L.map (\\x -> read x :: Int) $ words s\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n ws = [L.take n ws] ++ groupByNLines n (L.drop n ws)\n\nmain :: IO ()\nmain = interact (unlines . L.map parse . groupByNLines 3 . tail . lines)\n"}], "negative_code": [], "src_uid": "e1481b9d940407da75e11355b580f459"} {"source_code": "main = do\n n <- readLn::(IO Int)\n as <- return . map (read::String->Integer) . words =<< getLine\n let as' = as++[0]\n\tneighborPlus [a1,a2] = [a1+a2]\n\tneighborPlus (a1:tl@(a2:as)) = (a1+a2):neighborPlus tl\n mapM_ (putStr . (' ':) . show) $ neighborPlus as'\n", "positive_code": [{"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: [Integer] -> [Integer]\n solve xs =\n let ys = zip xs (drop 1 xs)\n zs = map (\\(x, y) -> -1 * (-x - y)) ys\n in (head xs):(zs)\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . map (read :: String -> Integer) . words\n let solution = (solve . reverse) $ xs\n putStrLn $ intercalate \" \" $ map show $ reverse solution\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess [a] = putStrLn $ show a\nprocess (a:b:as) = do\n\t\t\tputStr $ show (a+b)\n\t\t\tputStr \" \"\n\t\t\tprocess (b:as)\n\n\nmain = do\n\t\tgetLine\n\t\ta<-map read <$> words <$> getLine ::IO [Int]\n\t\tprocess a\n\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n arrays <- getLine\n putStrLn $ intercalate \" \" $ map show $ reverse . solve . reverse $ map read $ words arrays\n\nsolve ::[Int]->[Int]\nsolve a = zipWith (+) (0 : a) a\n"}, {"source_code": "import Data.List\n\nf ::Integer->Integer->[Integer]->[Integer]\nf _ _ []=[]\nf a d (x:xs)=(x+a+d):f (a+x) (-a) xs\n\nmain = do\n a<-getLine\n b<-getLine\n let xs=map read (words b)::[Integer]\n ys=reverse xs\n putStrLn $ unwords $ map show $ reverse (f 0 0 ys)"}], "negative_code": [{"source_code": "main = do\n n <- readLn::(IO Int)\n as <- return . map (read::String->Integer) . words =<< getLine\n let as' = as++[0]\n\tneighborPlus [a1,a2] = [a1+a2]\n\tneighborPlus (a1:tl@(a2:as)) = (a1+a2):neighborPlus tl\n print $ neighborPlus as'\n"}], "src_uid": "fa256021dc519f526ef3878cce32ff31"} {"source_code": "import List\nimport Control.Monad\n\nmakeList _ 0 = []\nmakeList (x:xs) m =\n [[x,y] | y <- rest] ++ makeList xs (m - length rest)\n where\n rest = take m xs\n\ngenBaseList n m = \n [0,n-1] : makeList [0..n-2] (m-1)\n\ngenList n m v = \n updateList (genBaseList n m) v n\n\nupdateList lst v n = \n map (\\[x,y] -> [f x, f y]) lst\n where\n f x = ((x+v-1) `rem` n) + 1\n\nmain =\n do\n [n,m,v] <- fmap (map read . words) getLine\n case (n-1 <= m && m <= ((n-1)*(n-2)) `div` 2 + 1) of\n True -> mapM_ putStrLn (map (\\[x,y] -> show x ++ \" \" ++ show y) (genList n m v))\n otherwise -> putStrLn ( show (-1) )", "positive_code": [{"source_code": "other :: Int -> Int\nother v\n\t| v == 1 = 2\n\t| otherwise = 1\n\ngetAns :: Int -> Int -> Int -> Int -> Int -> Int -> [(Int, Int)]\ngetAns v w m n i j\n\t| m == 0\t\t\t= []\n\t| j > n\t\t\t\t= getAns v w m n (i + 1) 1\n\t| i >= j\t\t\t= getAns v w m n i (j + 1)\n\t| i == w\t\t\t= getAns v w m n (i + 1) 1\n\t| j == w\t = getAns v w m n i (j + 1)\n\t| otherwise\t\t\t= (i, j) : (getAns v w (m - 1) n i (j + 1))\n\nprintAns :: [(Int, Int)] -> IO()\nprintAns ((a,b):xs) = do\n\tputStrLn ((show a) ++ \" \" ++ (show b))\n\tprintAns xs\nprintAns _\t= do\n\tputStr \"\"\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet n = read ((words str) !! 0)\n\tlet m = read ((words str) !! 1)\n\tlet v = read ((words str) !! 2)\n\tlet w = other v\n\tif (m < n - 1 || m > div (n * n - 3 * n + 4) 2)\n\t\tthen putStrLn \"-1\"\n\t\telse printAns ((v, w):(getAns v w (m - 1) n 1 1))\n"}], "negative_code": [{"source_code": "other :: Int -> Int\nother v\n\t| v == 1 = 2\n\t| otherwise = 1\n\ngetAns :: Int -> Int -> Int -> Int -> Int -> [(Int, Int)]\ngetAns v w m i j\n\t| m == 0\t\t\t= []\n\t| i >= j\t\t\t= getAns v w m 1 (j + 1)\n\t| i == w\t\t\t= getAns v w m (i + 1) j\n\t| j == w\t = getAns v w m 1 (j + 1)\n\t| otherwise\t\t\t= (i, j) : (getAns v w (m - 1) (i + 1) j)\n\nprintAns :: [(Int, Int)] -> IO()\nprintAns ((a,b):xs) = do\n\tputStrLn ((show a) ++ \" \" ++ (show b))\n\tprintAns xs\nprintAns _\t= do\n\tputStr \"\"\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet n = read ((words str) !! 0)\n\tlet m = read ((words str) !! 1)\n\tlet v = read ((words str) !! 2)\n\tlet w = other v\n\tif (m < n - 1 || m > div (n * n - 3 * n + 4) 2)\n\t\tthen putStrLn \"-1\"\n\t\telse printAns ((v, w):(getAns v w (m - 1) 1 1))\n"}, {"source_code": "other :: Int -> Int\nother v\n\t| v == 1 = 2\n\t| otherwise = 1\n\ngetAns :: Int -> Int -> Int -> Int -> Int -> [(Int, Int)]\ngetAns v w m i j\n\t| m == 0\t\t\t= []\n\t| i >= j\t\t\t= getAns v w m 1 (j + 1)\n\t| i == v || i == w\t= getAns v w m (i + 1) j\n\t| j == v || j == w\t= getAns v w m 1 (j + 1)\n\t| otherwise\t\t\t= (i, j) : (getAns v w (m - 1) (i + 1) j)\n\nprintAns :: [(Int, Int)] -> IO()\nprintAns ((a,b):xs) = do\n\tputStrLn ((show a) ++ \" \" ++ (show b))\n\tprintAns xs\nprintAns _\t= do\n\tputStr \"\"\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet n = read ((words str) !! 0)\n\tlet m = read ((words str) !! 1)\n\tlet v = read ((words str) !! 2)\n\tlet w = other v\n\tif (m < n - 1 || m > div (n * n - 3 * n + 4) 2)\n\t\tthen putStrLn \"-1\"\n\t\telse printAns ((v, w):(getAns v w (m - 1) 1 1))\n"}, {"source_code": "import List\nimport Control.Monad\n\nmakeList _ 0 = []\nmakeList (x:xs) m =\n [[x,y] | y <- rest] ++ makeList xs (m - length rest)\n where\n rest = take m xs\n\ngenBaseList n m = \n [0,n-1] : makeList [0..n-2] (m-1)\n\ngenList n m v = \n updateList (genBaseList n m) v n\n\nupdateList lst v n = \n map (\\[x,y] -> [f x, f y]) lst\n where\n f x = ((x+v-1) `rem` n) + 1\n\nmain =\n do\n [n,m,v] <- fmap (map read . words) getLine\n case (n-1 <= m && m <= ((n-1)*(n-2)) `div` 2) of\n True -> mapM_ putStrLn (map (\\[x,y] -> show x ++ \" \" ++ show y) (genList n m v))\n otherwise -> putStrLn ( show (-1) )"}, {"source_code": "import List\nimport Numeric\nimport Control.Monad\n\nfact 0 = 1;\nfact n = n * fact (n-1)\n\ncomb k n = (fact n) `div` (fact k * fact (n-k)) \n\ngood (n1, n2, m1, m2) \n | (n1 <= m1 && m1 <= cmb1) &&\n (n2 <= m2 && m2 <= cmb2) = \n (\"YES\", n1, n2, m1, m2)\n | otherwise =\n (\"NO\", n1, n2, m1, m2)\n where\n cmb1 = comb 2 (n1+1)\n cmb2 = comb 2 (n2+1)\n\ncheck (n1, n2, m)\n | m2 >= cmb =\n good (n1, n2, m1 + m2 - cmb, cmb)\n | otherwise = \n good (n1, n2, m1, m2)\n where\n m1 = n1\n m2 = m - n1\n cmb = comb 2 (n1+1)\n\nfindBest (n,m) = \n if (null yesLst) then (\"NO\",1,1,1,1) else head yesLst\n where \n var = map check [(i, n-1-i, m) | i <- [2..n-3], i <= (n-1-i)]\n yesLst = filter (\\(str,_,_,_,_) -> (str == \"YES\")) var\n\nsubSeq _ 0 = []\nsubSeq (x:xs) m = \n [[x,y] | y <- lst] ++ subSeq xs (m - length lst)\n where\n lst = take m xs\n\ngenSeq (_,n1,n2,m1,m2) = \n (subSeq (0:[n1+1..n1+n2]) m2) ++\n (subSeq (0:[1..n1]) m1)\n\naddNum v n lst = \n map (\\[x,y] -> [f x, f y]) lst\n where\n f x = ((x+v-1) `rem` n) + 1\n\nmain = \n do\n [n,m,v] <- fmap ((map read) . words) getLine\n let tupleAnsw = findBest (n,m)\n case tupleAnsw of\n (\"NO\",_,_,_,_) -> \n putStrLn( show (-1) )\n otherwise -> \n do\n let answ = addNum v n $ genSeq tupleAnsw\n mapM_ putStrLn (map (\\[x,y] -> show x ++ \" \" ++ show y) answ)"}, {"source_code": "import List\nimport Numeric\nimport Control.Monad\n\nfact 0 = 1;\nfact n = n * fact (n-1)\n\ncomb k n = (fact n) `div` (fact k * fact (n-k)) \n\ngood (n1, n2, m1, m2) \n | (n1 <= m1 && m1 <= cmb1) &&\n (n2 <= m2 && m2 <= cmb2) = \n (\"YES\", n1, n2, m1, m2)\n | otherwise =\n (\"NO\", n1, n2, m1, m2)\n where\n cmb1 = comb 2 (n1+1)\n cmb2 = comb 2 (n2+1)\n\ncheck (n1, n2, m)\n | m2 >= cmb =\n good (n1, n2, m1 + m2 - cmb, cmb)\n | otherwise = \n good (n1, n2, m1, m2)\n where\n m1 = n1\n m2 = m - n1\n cmb = comb 2 (n1+1)\n\nfindBest (n,m) = \n if (null yesLst) then (\"NO\",1,1,1,1) else head yesLst\n where \n var = map check [(i, n-1-i, m) | i <- [1..n-2], i <= (n-1-i)]\n yesLst = filter (\\(str,_,_,_,_) -> (str == \"YES\")) var\n\nsubSeq _ 0 = []\nsubSeq (x:xs) m = \n [[x,y] | y <- lst] ++ subSeq xs (m - length lst)\n where\n lst = take m xs\n\ngenSeq (_,n1,n2,m1,m2) = \n (subSeq (0:[n1+1..n1+n2]) m2) ++\n (subSeq (0:[1..n1]) m1)\n\naddNum v n lst = \n map (\\[x,y] -> [f x, f y]) lst\n where\n f x = ((x+v-1) `rem` n) + 1\n\nmain = \n do\n [n,m,v] <- fmap ((map read) . words) getLine\n let tupleAnsw = findBest (n,m)\n case tupleAnsw of\n (\"NO\",_,_,_,_) -> \n putStrLn( show (-1) )\n otherwise -> \n do\n let answ = addNum v n $ genSeq tupleAnsw\n mapM_ putStrLn (map (\\[x,y] -> show x ++ \" \" ++ show y) answ)"}], "src_uid": "959709bfe7b26a4b9f2e7430350650a9"} {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (elemIndices)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n replicateM_ n $ do\r\n amount <- readLn\r\n str <- getLine\r\n print $ func amount str & unlines\r\n\r\nfunc :: Int -> String -> [String]\r\nfunc len str =\r\n if | twoIndList & length == 0 || twoIndList & length > 2 -> \"YES\" : finalArr\r\n | 6<9 -> [\"NO\"]\r\n where\r\n indStr = [0..] `zip` str\r\n\r\n twoIndList = \r\n [0..] `zip` ('2' `elemIndices` str)\r\n \r\n [firstTwoInd, lastTwoInd] = [twoIndList & head, twoIndList & last] >>& snd\r\n\r\n finalArr =\r\n [[getItem a b | b <- indStr] | a <- indStr]\r\n\r\n getItem (ind, a) (jnd, b) =\r\n if | ind == jnd -> 'X'\r\n | a == '1' || b == '1' -> '='\r\n | ind == lastTwoInd && jnd == firstTwoInd -> '-'\r\n | ind == firstTwoInd && jnd == lastTwoInd || ind > jnd -> '+'\r\n | 6<9 -> '-'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n ~[s] <- getNext 1\n let\n greedy = [i | (i, si) <- zip [1..] $ P.unpack s, si == '2']\n wins = zip greedy $ tail $ cycle greedy\n ansArr :: UArray (Int, Int) Char\n ansArr = accumArray (\\_ v -> v) '=' ((1, 1), (n, n))\n $ [((i, i), 'X') | i <- [1 .. n]] ++ do\n (i, j) <- wins\n [((i, j), '+'), ((j, i), '-')]\n pure $ if length greedy `elem` [1, 2]\n then string7 \"NO\\n\"\n else mconcat $ string7 \"YES\\n\" : do\n i <- [1..n]\n pure $ string7 [ansArr ! (i, j) | j <- [1..n]] <> char7 '\\n'\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = pair int str\n\n-- output :: Output -> C.ByteString\noutput Nothing = C.pack \"NO\"\noutput (Just s) = C.pack . unlines $ \"YES\" : s\n\n-- solve :: Input -> Output\nsolve (n, s) = do\n guard $ length type2 /= 1\n guard $ length type2 /= 2\n return\n [ [ compute i j | j <- [1 .. n]\n ]\n | i <- [1 .. n]\n ]\n where\n type2 = [i | (c, i) <- zip s [1 .. n], c == '2']\n wins = case type2 of\n [] -> []\n (i : is) -> zip type2 (is ++ [i])\n\n compute i j\n | i == j = 'X'\n | (i, j) `elem` wins = '+'\n | (j, i) `elem` wins = '-'\n | otherwise = '='\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "-- ID : 1569B (B. Chess Tournament)\n-- URL : https://codeforces.com/contest/1569/problem/B\n\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\nreadInt = read `fmap` getLine :: IO Int\n\nmain = readInt >>= \\t -> replicateM_ t solve\n\n-- For those who don't wanna lose any game, assign draw for their every matches.\n-- For those who wanna win at lesat one game, they can form a cycle\n-- s.t. each former wins against its latter (must be n >= 3)\nsolve = do\n n <- readInt\n desires <- zip [1..n] `fmap` getLine\n let (winners,noLosers) = partition (\\(i,x) -> x == '2') desires\n let winCycle = zip xs (tail xs ++ [head xs]) where xs = map fst winners\n let drawCycle = map (\\(i,x) -> (i,0)) noLosers\n let strat = array (1,n) (winCycle ++ drawCycle)\n let numWinners = length winners\n let numNoLosers = n - numWinners\n if numWinners == 1 || numWinners == 2 then putStrLn \"NO\"\n else do\n --print strat\n let m = array ((1,1),(n,n)) [((i,j),f (strat ! i) i j) | i <- [1..n], j <- [1..n]] where\n f strat i j\n | i == j = 'X'\n | strat == 0 = '='\n | strat == i = '-'\n | strat == j = '+'\n | otherwise = '='\n let m2 = array ((1,1),(n,n)) [((i,j),f i j (m ! (i,j))) | i <- [1..n], j <- [1..n]] where\n f i j x\n | x /= '=' = x\n | otherwise = invert (m ! (j,i))\n invert x\n | x == '-' = '+'\n | x == '+' = '-'\n | otherwise = x\n putStrLn \"YES\"\n forM_ [1..n] $ \\i -> do\n forM_ [1..n] $ \\j -> do\n putChar (m2 ! (i,j))\n putChar '\\n'\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List (intercalate)\nimport Data.Map (Map)\nimport qualified Data.Map as M\nimport Data.STRef\n\ndata PlayerType = NoLoss | WinOne deriving (Show, Eq)\n\ndata Solution = Solution\n { winCycle :: [Int],\n numPlayers :: Int\n }\n deriving (Eq)\n\ndata MatchResult = Lose | Win | Draw | Invalid deriving (Eq, Enum)\n\ninstance Show MatchResult where\n show Invalid = \"X\"\n show Lose = \"-\"\n show Win = \"+\"\n show Draw = \"=\"\n\ninstance Show Solution where\n show (Solution w n) = str\n where\n pairs arr = zip arr $ tail arr\n arr = runSTArray $ do\n arr <- newArray ((1, 1), (n, n)) Draw\n -- fill in diagonals\n forM_ [1 .. n] $ \\i -> do\n writeArray arr (i, i) Invalid\n -- fill in win cycle\n unless (null w) $\n forM_ (pairs $ w ++ [head w]) $ \\(i, j) -> do\n writeArray arr (i, j) Win\n writeArray arr (j, i) Lose\n return arr\n str =\n intercalate\n \"\\n\"\n [ concat\n [ show $ arr ! (y, x)\n | x <- [1 .. n]\n ]\n | y <- [1 .. n]\n ]\n\nsolution :: [PlayerType] -> Maybe Solution\nsolution players =\n if length winonePlayers > 2 || null winonePlayers\n then\n Just\n Solution\n { winCycle = fst <$> winonePlayers,\n numPlayers = length players\n }\n else Nothing\n where\n winonePlayers = filter ((== WinOne) . snd) $ zip [1 ..] players\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n forM_ [1 .. t] $ \\_ -> do\n getLine\n str <- getLine\n let players =\n ( \\case\n '1' -> NoLoss\n '2' -> WinOne\n _ -> error \"undefined\"\n )\n <$> str\n case solution players of\n Just x -> do\n putStrLn \"YES\"\n print x\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n s <- zip [1 :: Int ..] <$> getLine\r\n let xs = filter ((=='2') . snd) s\r\n [f, l] = map fst [head xs, last xs]\r\n get (i, x) (j, y)\r\n | i == j = 'X'\r\n | x == '1' || y == '1' = '='\r\n | i == f && j == l = '+'\r\n | i == l && j == f = '-'\r\n | i > j = '+'\r\n | otherwise = '-'\r\n res = [get x y | x <- s, y <- s]\r\n putStr $ if null xs || length xs > 2\r\n then \"YES\\n\" ++ unlines (chunksOf n res)\r\n else \"NO\\n\"\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf n = go where\r\n go [] = []\r\n go xs = xs' : go xs'' where (xs', xs'') = splitAt n xs\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (elemIndices)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n replicateM_ n $ do\r\n amount <- readLn\r\n str <- getLine\r\n print $ func amount str & unlines\r\n\r\nfunc :: Int -> String -> [String]\r\nfunc len str =\r\n if | twoIndList & length == 0 || twoIndList & length > 2 -> \"YES\" : finalArr\r\n | 6<9 -> [\"NO\"]\r\n where\r\n indStr = [0..] `zip` str\r\n\r\n twoIndList = \r\n '2' `elemIndices` str\r\n \r\n [firstTwoInd, lastTwoInd] = [twoIndList & head, twoIndList & last]\r\n\r\n finalArr =\r\n [[getItem a b | b <- indStr] | a <- indStr]\r\n\r\n getItem (ind, a) (jnd, b) =\r\n if | ind == jnd -> 'X'\r\n | a == '1' || b == '1' -> '='\r\n | ind == lastTwoInd && jnd == firstTwoInd -> '-'\r\n | ind == firstTwoInd && jnd == lastTwoInd || ind > jnd -> '+'\r\n | 6<9 -> '-'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}], "negative_code": [{"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM)\r\nimport Data.List (nub, sort, elemIndices, elemIndex)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n arr <- replicateM n $ do\r\n amount <- readLn\r\n str <- getLine\r\n return (amount, str)\r\n \r\n say $ arr >>& func & concat & unlines\r\n\r\nfunc :: (Int, String) -> [String]\r\nfunc (len, str) =\r\n -- finalArr\r\n if | expectation -> \"YES\" : finalArr\r\n | 6<9 -> [\"NO\"]\r\n where\r\n twoIndList = \r\n '2' `elemIndices` str\r\n \r\n finalArr =\r\n [\r\n [\r\n (if \r\n | i == j -> 'X'\r\n | item == '1' || (item == '2' && str !! j == '1') -> '='\r\n | twoIndList !! ((((i `elemIndex` twoIndList) & sum) + 1) `mod` (twoIndList & length)) == j -> '+'\r\n | 6<9 -> '-'\r\n ) | (j, jtem) <- [0..] `zip` str\r\n ] \r\n | (i, item) <- [0..] `zip` str\r\n ]\r\n\r\n expectation =\r\n (str `zip` finalArr) & all (\r\n \\(char, item) -> \r\n (char == '1' && '-' `notElem` item) ||\r\n (char == '2' && '+' `elem` item)\r\n )\r\n\r\n symbolSum =\r\n finalArr & concat & foldl (\\acc x -> if | x == '+' -> acc + 1 | x == '-' -> acc - 1 | 6<9 -> acc) 0\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}, {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM)\r\nimport Data.List (nub, sort, elemIndices, elemIndex)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n arr <- replicateM n $ do\r\n amount <- readLn\r\n str <- getLine\r\n return (amount, str)\r\n \r\n say $ arr >>& func & concat & unlines\r\n\r\nfunc :: (Int, String) -> [String]\r\nfunc (len, str) =\r\n if | expectation && symbolSum == 0 -> \"YES\" : finalArr\r\n | 6<9 -> [\"NO\"]\r\n where\r\n twoIndList = \r\n '2' `elemIndices` str\r\n \r\n finalArr =\r\n [\r\n [\r\n (if \r\n | i == j -> 'X'\r\n | item == '1' || (item == '2' && str !! j == '1') -> '='\r\n | twoIndList !! ((((i `elemIndex` twoIndList) & sum) + 1) `mod` (twoIndList & length)) == j -> '+'\r\n | 6<9 -> '-'\r\n ) | (j, jtem) <- [0..] `zip` str\r\n ] \r\n | (i, item) <- [0..] `zip` str\r\n ]\r\n\r\n expectation =\r\n (str `zip` finalArr) & all (\r\n \\(char, item) -> \r\n (char == '1' && '-' `notElem` item) ||\r\n (char == '2' && '+' `elem` item)\r\n )\r\n\r\n symbolSum =\r\n finalArr & concat & foldl (\\acc x -> if | x == '+' -> acc + 1 | x == '-' -> acc - 1 | 6<9 -> acc) 0\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}, {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM)\r\nimport Data.List (nub, sort, elemIndex)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n arr <- replicateM n $ do\r\n getLine\r\n getLine >>= return\r\n \r\n say $ arr >>& func & concat & unlines\r\n\r\nfunc :: String -> [String]\r\nfunc str =\r\n if | expectation -> \"YES\" : finalArr\r\n | 6<9 -> [\"NO\"]\r\n where\r\n len = str & length\r\n baseCase =\r\n [[final | (j, jtem) <- [0..] `zip` str, let final = if | i == j -> 'X' | 6<9 -> '='] | (i, item) <- [0..] `zip` str]\r\n \r\n twoIndList = \r\n ([0..] `zip` str) & filter (\\(i, item) -> item == '2') >>. fst\r\n\r\n finalArr =\r\n [\r\n [\r\n (if \r\n | i == j -> 'X'\r\n | item == '1' || (item == '2' && str !! j == '1') -> '='\r\n | twoIndList !! ((((i `elemIndex` twoIndList) & sum) + 1) `mod` (twoIndList & length)) == j -> '+'\r\n | 6<9 -> '-'\r\n ) | (j, jtem) <- [0..] `zip` str\r\n ] \r\n | (i, item) <- [0..] `zip` str\r\n ]\r\n\r\n expectation =\r\n (str `zip` finalArr) & all (\r\n \\(char, item) -> \r\n (char == '1' && '-' `notElem` item) ||\r\n (char == '2' && '+' `elem` item)\r\n )\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}, {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM)\r\nimport Data.List (nub, sort, elemIndex)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n arr <- replicateM n $ do\r\n getLine\r\n getLine >>= return\r\n \r\n say $ arr & map func . concat . unlines\r\n\r\nfunc :: String -> [String]\r\nfunc str =\r\n if | str & nub == \"1\" -> \"YES\" : baseCase\r\n | str == \"22\" || str & sort == \"12\" -> [\"NO\"]\r\n | 6<9 -> \"YES\" : regularCase\r\n where\r\n len = str & length\r\n baseCase =\r\n [[final | (j, jtem) <- [0..] `zip` str, let final = if | i == j -> 'X' | 6<9 -> '='] | (i, item) <- [0..] `zip` str]\r\n \r\n twoIndList = \r\n ([0..] `zip` str) & filter (\\(i, item) -> item == '2') >>. fst\r\n\r\n regularCase =\r\n [\r\n [\r\n (if \r\n | i == j -> 'X'\r\n | item == '1' || (item == '2' && str !! j == '1') -> '='\r\n | twoIndList !! ((((i `elemIndex` twoIndList) & sum) + 1) `mod` (twoIndList & length)) == j -> '+'\r\n | 6<9 -> '-'\r\n ) | (j, jtem) <- [0..] `zip` str\r\n ] \r\n | (i, item) <- [0..] `zip` str\r\n ]\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}, {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM)\r\nimport Data.List (nub, sort)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n arr <- replicateM n $ do\r\n getLine\r\n getLine >>= return\r\n \r\n say $ arr & map func . concat . unlines\r\n\r\nfunc :: String -> [String]\r\nfunc str =\r\n if | str & nub == \"1\" -> \"YES\" : baseCase\r\n | str == \"22\" || str & sort == \"12\" -> [\"NO\"]\r\n | 6<9 -> \"YES\" : regularCase\r\n where\r\n len = str & length\r\n baseCase =\r\n [[final | (j, jtem) <- [0..] `zip` str, let final = if | i == j -> 'X' | 6<9 -> '='] | (i, item) <- [0..] `zip` str]\r\n \r\n regularCase =\r\n [[(if | i == j -> 'X' | item == '1' || (item == '2' && str !! j == '1') -> '=' | (i + 1) `mod` len == j -> '+' | 6<9 -> '-') | (j, jtem) <- [0..] `zip` str] | (i, item) <- [0..] `zip` str]\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}, {"source_code": "{-#LANGUAGE TypeApplications,TupleSections,NegativeLiterals,MultiWayIf,PostfixOperators,LambdaCase,NumDecimals,FlexibleInstances,UndecidableInstances#-}\r\n\r\nimport Prelude hiding ((.), interact, print)\r\nimport Debug.Trace (traceShow)\r\nimport Control.Monad (replicateM)\r\nimport Data.List (nub, sort)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn\r\n\r\n arr <- replicateM n $ do\r\n getLine\r\n getLine >>= return\r\n \r\n say $ arr & map func . concat . unlines\r\n\r\nfunc :: String -> [String]\r\nfunc str =\r\n if | str & nub == \"1\" -> \"YES\" : baseCase\r\n | str == \"22\" || str & sort == \"12\" -> [\"NO\"]\r\n | 6<9 -> \"YES\" : regularCase\r\n where\r\n len = str & length\r\n baseCase =\r\n [[final | (j, jtem) <- [0..] `zip` str, let final = if | i == j -> 'X' | 6<9 -> '='] | (i, item) <- [0..] `zip` str]\r\n \r\n regularCase =\r\n [[(if | i == j -> 'X' | (i + 1) `mod` len == j -> '+' | 6<9 -> '-') | (j, jtem) <- [0..] `zip` str] | (i, item) <- [0..] `zip` str]\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n-- don't read the stuff below\r\n\r\n(.)a b x=b$a x\r\na>>.b=a.fmap b\r\n\r\ninfixl 8 &\r\na&b=b a\r\n\r\ninfixl 8 >>&\r\na>>&b=b<$>a\r\n\r\nsay x=putStrLn$x&toStr\r\nprint x=putStr$x&toStr\r\ninteract f=getContents>>=f.print\r\n\r\nclass ToStr a where toStr::a->String\r\ninstance{-#OVERLAPS#-}Show a=>ToStr a where toStr=show\r\ninstance{-#OVERLAPS#-}ToStr String where toStr=id"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n ~[s] <- getNext 1\n let\n greedy = [i | (i, si) <- zip [1..] $ P.unpack s, si == '2']\n wins = zip greedy $ tail $ cycle greedy\n ansArr :: UArray (Int, Int) Char\n ansArr = accumArray (\\_ v -> v) '=' ((1, 1), (n, n))\n $ [((i, i), 'X') | i <- [1 .. n]] ++ do\n (i, j) <- wins\n [((i, j), '+'), ((j, i), '-')]\n pure $ case greedy of\n [_] -> string7 \"NO\\n\"\n _ -> mconcat $ string7 \"YES\\n\" : do\n i <- [1..n]\n pure $ string7 [ansArr ! (i, j) | j <- [1..n]] <> char7 '\\n'\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\n-- type Input = ()\n-- type Output = ()\n\n-- input :: Scanner Input\ninput = pair int str\n\n-- output :: Output -> C.ByteString\noutput Nothing = C.pack \"No\"\noutput (Just s) = C.pack . unlines $ \"Yes\" : s\n\n-- solve :: Input -> Output\nsolve (n, s) = do\n guard $ length type2 /= 1\n return\n [ [ compute i j | j <- [1 .. n]\n ]\n | i <- [1 .. n]\n ]\n where\n type2 = [i | (c, i) <- zip s [1 .. n], c == '2']\n wins = case type2 of\n [] -> []\n (i : is) -> zip type2 (is ++ [i])\n\n compute i j\n | i == j = 'X'\n | (i, j) `elem` wins = '+'\n | (j, i) `elem` wins = '-'\n | otherwise = '='\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "7e15bb1d6040d786983865143d1799cd"} {"source_code": "module Main where \r\n\r\nimport Control.Monad\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Char\r\n\r\ntoIntList :: String -> [Int]\r\ntoIntList = map (\\x -> ord x - ord '0')\r\n\r\nfromIntList :: [Int] -> String\r\nfromIntList = concatMap show\r\n\r\nlastOccurence :: [a] -> (a -> Bool) -> Maybe Int\r\nlastOccurence [] pred = Nothing\r\nlastOccurence (x:xs) pred =\r\n case lastOccurence xs pred of\r\n Nothing -> if pred x then Just 0 else Nothing\r\n (Just x) -> Just (x + 1)\r\n\r\ncontr :: [Int] -> [Int]\r\ncontr [] = error \"Bad news\"\r\ncontr xss@(x:xs) = \r\n let sums = zipWith (+) xs xss in\r\n if any (>= 10) sums then \r\n let t = fromJust $ lastOccurence sums (>= 10) in\r\n take t xss ++ [sums !! t] ++ drop (t + 2) xss\r\n else\r\n case xs of\r\n (y:ys) -> (x + y) : ys \r\n [] -> error \"Bad news\"\r\n \r\n\r\nmain = do\r\n t <- fmap read getLine\r\n forM_ [1..t] $ \\_ -> do\r\n str <- getLine\r\n putStrLn $ fromIntList $ contr $ toIntList str", "positive_code": [{"source_code": "-- |\r\n\r\n-- module nil where\r\nimport Data.List\r\nimport Data.Char\r\nimport Control.Monad\r\n\r\n\r\nmain = do\r\n times <- fmap read getLine\r\n forM_ [1..times] $ \\_ -> do\r\n input <- getLine\r\n putStrLn $ concatMap show $ replacePairs' $ map digitToInt input\r\n\r\n\r\n-- Problem B\r\nreplacePairs inp =\r\n -- maximum $ map (\\k -> shower (inserter inp k)) [1..(length inp - 1)]\r\n read (foldr comparing \"0\" $ map converter [(el-1),(el-2)..1]) :: Integer\r\n where converter k = shower $ inserter inp k\r\n shower xs = (foldr (++) \"\" $ map show xs)\r\n inserter a k = (let (front, back) = splitAt (k-1) a in front ++ [head back + head (drop 1 back)] ++ (drop 2 back))\r\n el = length inp\r\n intread x = (read x) :: Integer\r\n comparing temp acc = if (ltemp == el) then temp else\r\n show (max (intread acc) (intread temp))\r\n where ltemp = length temp\r\n\r\n-- Taken from divanik's solution\r\nreplacePairs' inp@(x:xs) = let sums = zipWith (+) xs inp in\r\n let t = lastOcc sums (>= 10) in\r\n if t >= 0 then\r\n take t inp ++ [sums !! t] ++ drop (t+2) inp\r\n else\r\n case xs of\r\n (y:ys) -> (x+y):ys\r\n [] -> [0]\r\n where\r\n lastOcc [] _ = -1\r\n lastOcc (x:xs) pred = (if pred x || later >= 0 then (1+) else id) $ later\r\n where later = lastOcc xs pred\r\n\r\n-- Notes:\r\n -- Thought of zipWith, though didn't know of the function itself\r\n -- Didn't think of making a lazy list to access from (though didn't know of !!)\r\n -- Didn't think of using any and direct access to replace the foldr expression\r\n -- Thought of lastOcc (after checking tutorial for problem)\r\n -- Thought of insertion method (though didn't know of !!)\r\n -- Didn't think of the else/case section (if not >=10, maximize the greatest-order digit)\r\n -- Forgot to keep considering [Integer] after I switched to using the String representations\r\n -- Didn't think of using >=10 instead of direct length-checking\r\n -- May have been thought of via laziness? \"As little dependency as possible\" would likely entail minimizing checks to only where the diff was\r\n -- THE ABOVE IS LIKELY INSUFFICIENT TO DEVELOP THE SOLUTION, but I'm not sure what else I didn't think of\r\n"}, {"source_code": "-- |\r\n\r\n-- module nil where\r\nimport Data.List\r\nimport Data.Char\r\nimport Control.Monad\r\n\r\n\r\nmain = do\r\n times <- fmap read getLine\r\n forM_ [1..times] $ \\_ -> do\r\n input <- getLine\r\n putStrLn $ concatMap show $ replacePairs' $ map digitToInt input\r\n\r\n\r\nreplacePairs inp =\r\n -- maximum $ map (\\k -> shower (inserter inp k)) [1..(length inp - 1)]\r\n read (foldr comparing \"0\" $ map converter [(el-1),(el-2)..1]) :: Integer\r\n where converter k = shower $ inserter inp k\r\n shower xs = (foldr (++) \"\" $ map show xs)\r\n inserter a k = (let (front, back) = splitAt (k-1) a in front ++ [head back + head (drop 1 back)] ++ (drop 2 back))\r\n el = length inp\r\n intread x = (read x) :: Integer\r\n comparing temp acc = if (ltemp == el) then temp else\r\n show (max (intread acc) (intread temp))\r\n where ltemp = length temp\r\n\r\n-- Taken from divanik's solution\r\nreplacePairs' inp@(x:xs) = let sums = zipWith (+) xs inp in\r\n if any (>= 10) sums then\r\n let t = lastOcc sums (>= 10) in\r\n take t inp ++ [sums !! t] ++ drop (t+2) inp\r\n else\r\n case xs of\r\n (y:ys) -> (x+y):ys\r\n [] -> [0]\r\n where\r\n lastOcc [] _ = -1\r\n lastOcc (x:xs) pred = (if pred x || later >= 0 then (1+) else id) $ later\r\n where later = lastOcc xs pred\r\n"}], "negative_code": [{"source_code": "import Data.List\r\nimport Data.Char\r\nimport Control.Monad\r\n\r\nfor list action = mapM_ action list\r\n\r\nmain = do\r\n inp <- getLine\r\n let times = read inp in do\r\n for [1..times] (\\i -> do\r\n input <- getLine\r\n putStrLn $ show (replacePairs (map digitToInt input))\r\n )\r\n return \"\"\r\n \r\n\r\nreplacePairs :: [Int] -> Int\r\nreplacePairs inp = if (1 >= length inp)\r\n then (shower inp)\r\n else foldl (\\acc k -> max acc (shower (inserter inp k))) (shower (inserter inp 1)) [2..((length inp) - 1)]\r\n\r\n where shower xs = read (foldr (++) \"\" $ map show xs) :: Int\r\n inserter a k = (let (front, back) = splitAt (k-1) a in front ++ [head back + head (drop 1 back)] ++ (drop 2 back))"}, {"source_code": "import Data.List\r\nimport Data.Char\r\n\r\nmain = do\r\n input <- getLine\r\n putStrLn $ show (replacePairs (map digitToInt input))\r\n\r\nreplacePairs :: [Int] -> Int\r\nreplacePairs inp = if (1 >= length inp)\r\n then (shower inp)\r\n else foldl (\\acc k -> max acc (shower (inserter inp k))) (shower (inserter inp 1)) [2..((length inp) - 1)]\r\n\r\n where shower xs = read (foldr (++) \"\" $ map show xs) :: Int\r\n inserter a k = (let (front, back) = splitAt (k-1) a in front ++ [head back + head (drop 1 back)] ++ (drop 2 back))\r\n\r\n "}, {"source_code": "import Data.Char\r\n\r\nmain = do\r\n input <- getLine\r\n putStrLn (replacePairs input)\r\n\r\nreplacePairs :: String -> String\r\nreplacePairs inp = if (1 >= length (inp))\r\n then inp\r\n else foldr (++) \"\" $ replacePairs''' (map digitToInt (inp)) (map digitToInt (inp))\r\n where -- replacePairs' st = foldl (++) \"\" $ replacePairs'' st []\r\n -- replacePairs'' [] acc = reverse (map show acc)\r\n -- replacePairs'' (a:b:xs) [] = replacePairs'' xs [a + b]\r\n -- replacePairs'' (x:xs) acc = replacePairs'' xs (x+(head acc) : acc)\r\n replacePairs''' (x:y:xs) (a:b:acc) = (show (a+b) : replacePairs''' (y:xs) (b:acc))\r\n replacePairs''' (x:xs) acc = []\r\n"}], "src_uid": "6db42771fdd582578194c7b69a4ef575"} {"source_code": "import Control.Monad (replicateM_)\r\n\r\ncanGenerate :: String -> String -> Bool\r\ncanGenerate s t = go (reverse s) (reverse t) where\r\n go _ [] = True\r\n go (x : xs) (y : ys)\r\n | x == y = go xs ys\r\n | not $ null xs = go (tail xs) (y : ys)\r\n | otherwise = False\r\n go _ _ = False\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n s <- getLine \r\n t <- getLine \r\n putStrLn $ if s `canGenerate` t then \"YES\" else \"NO\"", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nsplitInTuples [] = []\nsplitInTuples (x:y:ys) = [(x,y)] ++ (splitInTuples ys)\n\n\nprocess (a, b) = if _process (reverse a) (reverse b) == False then \"NO\" else \"YES\"\n \n\n_process _ [] = True\n_process a (b:bs)\n | bIndexOnA == -1 = False\n | otherwise = if bIndexOnA `mod` 2 == 0 then _process (drop (bIndexOnA + 1) a) bs else _process (drop (bIndexOnA + 1) a) (b:bs)\n where \n bIndexOnA = fromMaybe (-1) (elemIndex b a)\n k = drop (bIndexOnA + 1) a\n\nmain = do\n input <- getLine\n inputs <- replicateM ((read input) * 2) getLine\n mapM_ putStrLn (map process (splitInTuples inputs))"}, {"source_code": "{-# Language TypeApplications #-}\r\n\r\nmodule Main where\r\nimport Control.Monad (forM, forM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n numTests <- read @Int <$> getLine\r\n\r\n tests <- forM [1 .. numTests] (\\_ -> do\r\n input <- getLine\r\n output <- getLine\r\n pure (input, output))\r\n\r\n forM_ tests (\\(i, o) -> putStrLn (if tryTest (reverse i) (reverse o) then \"YES\" else \"NO\"))\r\n\r\n-- From the end\r\ntryTest :: String -> String -> Bool\r\ntryTest _ [] = True\r\ntryTest [] v = null v\r\ntryTest (u:us) (v:vs) =\r\n if u == v then\r\n tryTest us vs\r\n else\r\n tryTest (drop 1 us) (v:vs)"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\n\nmain :: IO ()\nmain =\n interact $\n words\n >>> drop 1\n >>> chunksOf 2\n >>> map (solve >>> bool \"No\" \"Yes\")\n >>> unlines\n\nsolve :: [String] -> Bool\nsolve [s, t] = canType (reverse s) (reverse t)\n\ncanType _ [] = True\ncanType (c:cs) (t:ts) | c == t = canType cs ts\ncanType (c:c':cs) ts = canType cs ts\ncanType _ _ = False\n\n-- Template --\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nsolve :: P.ByteString -> P.ByteString -> Bool\nsolve s t = case (P.uncons s, P.uncons t) of\n (_, Nothing) -> True\n (Just (p, s'), Just (q, t')) | p == q -> solve s' t'\n (Just (_, s'), _) -> case P.uncons s' of\n Just (_, s'') -> solve s'' t\n Nothing -> False\n _ -> False\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [q] <- readInts\n replicateM_ q $ do\n s <- P.reverse <$> readLine\n t <- P.reverse <$> readLine\n lift $ B.hPutBuilder stdout $ if solve s t\n then B.string7 \"YES\\n\"\n else B.string7 \"NO\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\ncanGenerate :: String -> String -> Bool\r\ncanGenerate s t = go (reverse s) (reverse t) where\r\n go (x : xs) [y] = y == x\r\n go [x] (y : ys) = False\r\n go (x : [x']) (y : ys) = False\r\n go (x : x' : xs) (y : ys)\r\n | y == x = go (x' : xs) ys\r\n | otherwise = go xs (y : ys)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n s <- getLine \r\n t <- getLine \r\n putStrLn $ if s `canGenerate` t then \"YES\" else \"NO\""}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nsplitInTuples [] = []\nsplitInTuples (x:y:ys) = [(x,y)] ++ (splitInTuples ys)\n\n\nprocess (a, b) = if _process (reverse a) (reverse b) == False then \"NO\" else \"YES\"\n \n\n_process _ [] = True\n_process a (b:bs)\n | bIndexOnA == -1 = False\n | otherwise = if bIndexOnA `mod` 2 == 0 then _process (drop (bIndexOnA + 1) a) bs else _process (drop (bIndexOnA) a) (b:bs)\n where \n bIndexOnA = fromMaybe (-1) (elemIndex b a)\n k = drop (bIndexOnA + 1) a\n\nmain = do\n input <- getLine\n inputs <- replicateM ((read input) * 2) getLine\n mapM_ putStrLn (map process (splitInTuples inputs))"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nsplitInTuples [] = []\nsplitInTuples (x:y:ys) = [(x,y)] ++ (splitInTuples ys)\n\n\nprocess (a, b) = if _process (reverse a) (reverse b) == False then \"NO\" else \"YES\"\n \n\n_process _ [] = True\n_process a (b:bs)\n | bIndexOnA == -1 = False\n | otherwise = if bIndexOnA `mod` 2 == 0 then _process (drop (bIndexOnA + 1) a) bs else False\n where \n bIndexOnA = fromMaybe (-1) (elemIndex b a)\n k = drop (bIndexOnA + 1) a\n\nmain = do\n input <- getLine\n inputs <- replicateM ((read input) * 2) getLine\n mapM_ putStrLn (map process (splitInTuples inputs))"}], "src_uid": "67856314f24ed718eb9b0d9fc9ab1abe"} {"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.Set as S\n\ntype SetInt = S.Set Int\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (ns : xs) = let n = read ns in solve n (take n xs) : process (drop n xs)\n\nsolve :: Int -> [String] -> String\nsolve n ls\n | S.null unmatched = \"OPTIMAL\"\n | otherwise =\n let lv = S.findMin unmatched\n rv = head $ filter (\\u -> not $ S.member u picked) [1 .. n]\n in \"IMPROVE\\n\" ++ show lv ++ \" \" ++ show rv\n where\n (picked, unmatched) =\n foldl pick (S.empty, S.empty) $\n zip [1 .. n] $ map (map read . drop 1 . words) ls\n pick :: (SetInt, SetInt) -> (Int, [Int]) -> (SetInt, SetInt)\n pick (used, unmatched) (p, cs) =\n case filter (\\u -> not $ S.member u used) cs of\n [] -> (used, S.insert p unmatched)\n (c : _) -> (S.insert c used, unmatched)\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.Set as S\n\ntype SetInt = S.Set Int\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (ns : xs) = solve n (take n xs) : process (drop n xs)\n where\n n = read ns\n\nsolve :: Int -> [String] -> String\nsolve n ls\n | S.null unmatched = \"OPTIMAL\"\n | otherwise =\n let lv = S.findMin unmatched\n rv = head $ filter (\\u -> not $ S.member u picked) [1 .. n]\n in \"IMPROVE\\n\" ++ show lv ++ \" \" ++ show rv\n where\n (picked, unmatched) =\n foldl pick (S.empty, S.empty) $\n zip [1 .. n] $ map (map read . drop 1 . words) ls\n pick :: (SetInt, SetInt) -> (Int, [Int]) -> (SetInt, SetInt)\n pick (used, unmatched) (p, cs) =\n case filter (\\u -> not $ S.member u used) cs of\n [] -> (used, S.insert p unmatched)\n (c : _) -> (S.insert c used, unmatched)\n"}, {"source_code": "import Control.Arrow\nimport qualified Data.Set as S\ntype SetInt = S.Set Int\n\nmain = interact $ \n lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = [\"\"]\nprocess (ns:xs) = solve n (take n xs) : process (drop n xs)\n where n = read ns\n\nsolve :: Int -> [String] -> String\nsolve n ls \n | S.null unmatched = \"OPTIMAL\"\n | otherwise = \n let \n lv = S.findMin unmatched\n rv = [ u | u <- [1..n], not $ S.member u picked ] !! 0\n in \"IMPROVE\\n\" ++ (show lv) ++ \" \" ++ (show rv) \n where\n (picked, unmatched) = \n foldl pick (S.empty, S.empty) $ \n zip [1..n] $ map ((map read) . (drop 1) . words) ls\n pick :: (SetInt, SetInt) -> (Int, [Int]) -> (SetInt, SetInt)\n pick (used, unmatched) (p, []) = (used, S.insert p unmatched)\n pick (used, unmatched) (p, (c:rest))\n | S.member c used = pick (used, unmatched) (p, rest)\n | otherwise = (S.insert c used, unmatched)\n"}, {"source_code": "import Control.Arrow\nimport qualified Data.Set as S\ntype SetInt = S.Set Int\n\nmain = interact $\n lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = [\"\"]\nprocess (ns:xs) = solve n (take n xs) : process (drop n xs)\n where n = read ns\n\nsolve :: Int -> [String] -> String\nsolve n ls\n | S.null unmatched = \"OPTIMAL\"\n | otherwise =\n let\n lv = S.findMin unmatched\n rv = [ u | u <- [1..n], not $ S.member u picked ] !! 0\n in \"IMPROVE\\n\" ++ (show lv) ++ \" \" ++ (show rv)\n where\n (picked, unmatched) =\n foldl pick (S.empty, S.empty) $\n zip [1..n] $ map ((map read) . (drop 1) . words) ls\n pick :: (SetInt, SetInt) -> (Int, [Int]) -> (SetInt, SetInt)\n pick (used, unmatched) (p, []) = (used, S.insert p unmatched)\n pick (used, unmatched) (p, (c:rest))\n | S.member c used = pick (used, unmatched) (p, rest)\n | otherwise = (S.insert c used, unmatched)\n"}], "negative_code": [{"source_code": "import Control.Arrow\nimport qualified Data.Set as S\ntype SetInt = S.Set Int\n\nmain = interact $ \n lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = [\"\"]\nprocess (ns:xs) = solve n (take n xs) : process (drop n xs)\n where n = read ns\n\nsolve :: Int -> [String] -> String\nsolve n ls \n | S.null unmatched = \"OPTIMAL\"\n | otherwise = \n let \n lv = S.findMin unmatched\n rv = [ u | u <- [1..n], not $ S.member u picked ] !! 0\n in \"IMPROVE\\n\" ++ (show lv) ++ \" \" ++ (show rv) \n where\n (picked, unmatched) = \n foldl pick (S.empty, S.empty) $ \n zip [1..n] $ map ((map read) . words) ls\n pick :: (SetInt, SetInt) -> (Int, [Int]) -> (SetInt, SetInt)\n pick (used, unmatched) (p, []) = (used, S.insert p unmatched)\n pick (used, unmatched) (p, (c:rest))\n | S.member c used = pick (used, unmatched) (p, rest)\n | otherwise = (S.insert c used, unmatched)\n"}], "src_uid": "38911652b3c075354aa8adb2a4c6e362"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Array\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nscoreA sa n x = sa ! ((n+x) - div (n+x) 4 - x) + 100 * x \r\nscoreB sb n x = sb ! min ((n+x) - div (n+x) 4) n\r\n\r\nsolve sa sb n x\r\n | scoreA sa n x < scoreB sb n x = solve sa sb n (x+1)\r\n | otherwise = x;\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n b <- readInts\r\n let sa = listArray (1,n) $ scanl1 (+) $ sortOn negate a\r\n sb = listArray (1,n) $ scanl1 (+) $ sortOn negate b\r\n print $ solve sa sb n 0\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Array\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nscoreA sa n x = sa ! ((n+x) - div (n+x) 4 - 1 - x) + 100 * x \r\nscoreB sb n x = sb ! min ((n+x) - div (n+x) 4 - 1) (n-1) \r\n\r\nsolve sa sb n x\r\n | scoreA sa n x < scoreB sb n x = solve sa sb n (x+1)\r\n | otherwise = x;\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n b <- readInts\r\n let sa = listArray (0,n-1) $ scanl1 (+) $ sortOn negate a\r\n sb = listArray (0,n-1) $ scanl1 (+) $ sortOn negate b\r\n print $ solve sa sb n 0\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.Int (Int64)\nimport Data.List as L\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n--import Data.IntSet \n\n\ncnt :: Int -> [Int] -> [Int] -> Int -> Int -> Int\ncnt le a b l r\n | l == r = l\n | mid_good = cnt le a b l mid\n | otherwise = cnt le a b (mid+1) r\n where mid = div (l+r) 2\n n = le + mid\n k = div n 4\n suma = sum (drop k a) + (mid - (max 0 (k - le))) * 100\n sumb = sum $ drop (k-mid) b\n mid_good = suma >= sumb\n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n [sa, sb] <- sequence [getLine, getLine]\n let a = sort $ map read $ words sa :: [Int]\n b = sort $ map read $ words sb :: [Int]\n res = cnt n a b 0 n\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.Int (Int64)\nimport Data.List as L\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n--import Data.IntSet \n\n\ncnt :: [Int] -> [Int] -> Int -> Int -> Int\ncnt a b l r\n | l == r = l\n | mid_good = cnt a b l mid\n | otherwise = cnt a b (mid+1) r\n where mid = div (l+r) 2\n n = length a + mid\n k = div n 4\n suma = sum (drop k a) + (mid - (max 0 (k - length a))) * 100\n sumb = sum $ drop (k-mid) b\n mid_good = suma >= sumb\n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n [sa, sb] <- sequence [getLine, getLine]\n let a = sort $ map read $ words sa :: [Int]\n b = sort $ map read $ words sb :: [Int]\n res = cnt a b 0 (2*n)\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport qualified Data.Array as A\r\nimport qualified Data.Sequence as S\r\nimport Control.Monad (replicateM_)\r\nimport Data.Maybe (fromJust)\r\nimport Data.List (sort, sortOn)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n a_i <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n b_i <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n print $ solve n a_i b_i\r\n\r\nsolve :: Int -> [Int] -> [Int] -> Int\r\nsolve n me him\r\n | scoreMe n meArr >= scoreHim n himArr = 0\r\n | otherwise = binarySearch (n + 1, 2 * n) meArr himArr - n\r\n where\r\n meArr = A.array (1, 2 * n) (zip [1 .. 2 * n] (sort me ++ repeat 100))\r\n\r\n himArr =\r\n A.array (1, 2 * n) (zip [1 .. 2 * n] (sortOn negate him ++ repeat 0))\r\n\r\nscoreMe :: Int -> A.Array Int Int -> Int\r\nscoreMe k arr = sum (map (arr A.!) [(minIndex + 1) .. k])\r\n where\r\n minIndex = k `div` 4\r\n\r\nscoreHim :: (A.Ix i, Num a, Integral i) => i -> A.Array i a -> a\r\nscoreHim k arr = sum (map (arr A.!) [1 .. (k - minIndex)])\r\n where\r\n minIndex = k `div` 4\r\n\r\n{->>> scoreHim 20 (A.array (1,50) (zip [1..50] (sort [100,100,100,100]++repeat 0)))\r\n400\r\n-}\r\nbinarySearch :: (Int, Int) -> A.Array Int Int -> A.Array Int Int -> Int\r\nbinarySearch (lower, upper) me him\r\n | lower == upper = lower\r\n | scoreMe mid me >= scoreHim mid him = binarySearch (lower, mid) me him\r\n | otherwise = binarySearch (mid + 1, upper) me him\r\n where\r\n mid = (lower + upper) `div` 2\r\n{-\r\n>>>solve 7 [7 ,59 ,62 ,52 ,27 ,31 ,55] [33 ,35 ,50 ,98, 83, 80 ,64]\r\n2\r\n\r\n\r\n>>>\r\n\r\n\r\n>>>solve 4 [4 ,10 ,20 ,30 ,40] [100 ,100, 100 ,100]\r\n4\r\n\r\n>>>solve 4 [20 ,30 ,40, 50] [100, 100, 100, 100]\r\n3\r\n>>>solve 2 [40 ,78] [82 ,67]\r\n1\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n n <- int\r\n as <- sort <$> n >< int\r\n bs <- sort <$> n >< int\r\n return . show $ solve as bs\r\n\r\nsolve :: [Int] -> [Int] -> Int\r\nsolve as bs = go 0 (4 * n)\r\n where\r\n n = length as\r\n gap = sum bs - sum as\r\n go l r\r\n | l == r = l\r\n | otherwise =\r\n let mid = (l + r) `div` 2\r\n in if check mid then go l mid else go (mid + 1) r\r\n check k =\r\n let d = (n + k) `div` 4\r\n in gap - sum (take (d - k) bs) <= 100 * (k - max 0 (d - n)) - sum (take d as)\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad hiding (ap)\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n ap <- scanl' (+) 0 . sort <$> readInts\n bp <- scanl' (+) 0 . sort <$> readInts\n let\n lap = last ap\n lbp = last bp\n res k = let\n ct = n + k\n toRem = div ct 4\n as = lap + k * 100 - ap !! toRem\n bs = lbp - bp !! max 0 (toRem - k)\n in as - bs\n go x y\n | x == y = x\n | otherwise = let\n w = x + div (y - x) 2\n in if res w >= 0\n then go x w\n else go (w+1) y\n putInts [go 0 n]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.Int (Int64)\nimport Data.List as L\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n--import Data.IntSet \n\n\ncnt :: [Int] -> [Int] -> Int -> Int -> Int\ncnt a b l r\n | l == r = l\n | mid_good = cnt a b l mid\n | otherwise = cnt a b (mid+1) r\n where k = div (length a) 4\n mid = div (l+r) 2\n suma = sum (drop k a) + 100 * mid\n sumb = sum $ drop (k-mid) b\n mid_good = suma >= sumb\n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n [sa, sb] <- sequence [getLine, getLine]\n let a = sort $ map read $ words sa :: [Int]\n b = sort $ map read $ words sb :: [Int]\n res = cnt a b 0 (2*n)\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.Int (Int64)\nimport Data.List as L\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n--import Data.IntSet \n\n\ncnt :: [Int] -> [Int] -> Int -> Int -> Int\ncnt a b l r\n | l == r = l\n | mid_good = cnt a b l mid\n | otherwise = cnt a b (mid+1) r\n where k = div (length a) 4\n mid = div (l+r) 2\n suma = sum (drop k a) + 100 * mid\n sumb = sum $ drop (k-mid) b\n mid_good = suma >= sumb\n \n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n [sa, sb] <- sequence [getLine, getLine]\n let a = sort $ map read $ words sa :: [Int]\n b = sort $ map read $ words sb :: [Int]\n maxrnd = max 0 $ (sum b - sum a) `div` 100 + 1\n res = cnt a b 0 maxrnd\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport qualified Data.ByteString.Char8 as C8\r\nimport qualified Data.Array as A\r\nimport qualified Data.Sequence as S\r\nimport Control.Monad (replicateM_)\r\nimport Data.Maybe (fromJust)\r\nimport Data.List (sort)\r\n\r\nreadInput :: C8.ByteString -> [[Int]]\r\nreadInput = map\r\n (map\r\n (\\str -> let (Just (i, _)) = C8.readInt str\r\n in i)\r\n . C8.words)\r\n . C8.lines\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t\r\n $ do\r\n n <- readLn :: IO Int\r\n a_i <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n b_i <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\r\n print $ solve n a_i b_i\r\n\r\nsolve :: Int -> [Int] -> [Int] -> Int\r\nsolve n me him\r\n | scoreMe n meArr >= scoreHim n himArr = 0\r\n | otherwise = binarySearch (n + 1, 2 * n) meArr himArr - n\r\n where\r\n meArr = A.array (1, 2 * n) (zip [1 .. 2 * n] (sort me ++ repeat 100))\r\n\r\n himArr = A.array (1, 2 * n) (zip [1 .. 2 * n] (sort him ++ repeat 0))\r\n\r\nscoreMe :: Int -> A.Array Int Int -> Int\r\nscoreMe k arr = sum (map (arr A.!) [minIndex + 1 .. k])\r\n where\r\n minIndex = k `div` 4\r\n\r\nscoreHim :: (A.Ix i, Num a, Integral i) => i -> A.Array i a -> a\r\nscoreHim k arr = sum (map (arr A.!) [1 .. (k - minIndex)])\r\n where\r\n minIndex = k `div` 4\r\n\r\n{->>> score 4 (A.array (1,18) (zip [1..18] (sort [100,100,100,100])))\r\n300\r\n-}\r\nbinarySearch :: (Int, Int) -> A.Array Int Int -> A.Array Int Int -> Int\r\nbinarySearch (lower, upper) me him\r\n | lower + 1 >= upper = upper\r\n | scoreMe mid me >= scoreHim mid him = binarySearch (lower, mid) me him\r\n | otherwise = binarySearch (mid + 1, upper) me him\r\n where\r\n mid = (lower + upper + 1) `div` 2\r\n{-\r\n>>>solve 7 [7 ,59 ,62 ,52 ,27 ,31 ,55] [33 ,35 ,50 ,98, 83, 80 ,64]\r\nProgressCancelledException\r\n\r\n\r\n>>>solve 4 [4 ,10 ,20 ,30 ,40] [100 ,100, 100 ,100]\r\n4\r\n\r\n>>>solve 4 [20 ,30 ,40, 50] [100, 100, 100, 100]\r\n3\r\n\r\n-}\r\n"}], "src_uid": "61b88627fc843ef6e5226e1003822793"} {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\nreadNums :: IO [Int]\nreadNums = ((map read) . words) <$> getLine\n\ndot2Space :: Char -> Char\ndot2Space c = case c of\n '.' -> ' '\n x -> x\n\nmain = do\n [r, c] <- readNums\n ground <- last <$> (replicateM r getLine)\n let numSegments = length $ words $ (map dot2Space) ground\n putStrLn $ show numSegments", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [[Char]] -> Int\nsolve fld = length $ filter (\\a -> any (\\b -> b /= '.') a) pairs\n where\n bottom = last fld\n pairs = groupBy (\\a b -> a == b) bottom\n \nmain :: IO ()\nmain = do\n r <- liftM words getLine\n mat <- replicateM (read $ head r) getLine\n print $ solve mat\n"}], "negative_code": [], "src_uid": "c339795767a174a59225a79023b5d14f"} {"source_code": "{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Set as S\nimport Data.List\nimport Data.Ord\n\nmain = do\n n <- readLn\n ijs <- sortBy(comparing$uncurry (+)).concat.zipWith(\\i ci->map(i,)[1..ci])[1..].map read.words <$> getLine\n tblSet <- fmap(S.fromList.concat).forM [1..n] $ \\i->\n zipWith(\\j x->(x,i,j))[1..].map read.words <$> getLine\n let ans = solve ijs tblSet\n print $ length ans\n putStrLn.unlines.map(unwords.map show) $ ans\n\n\nsolve :: [(Int,Int)] -> S.Set (Int,Int,Int) -> [[Int]]\nsolve [] _ = []\nsolve ((i,j):ijs) set\n | (i,j) == (x,y) = solve ijs rest\n | otherwise = [i,j,x,y]:solve ijs (S.insert (v2,x,y) rest2)\n where\n ((_,x,y),rest) = S.deleteFindMin set\n (rest1,rest2)=S.partition(\\(_,x,y)->x==i && y==j)rest\n (v2,_,_) = S.findMin rest1", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do n <- getLine >>= return . read\n lc <- getLine >>= return . map read . words\n l <- sequence $ replicate n (getLine >>= return . map read . words)\n let ans = solve n lc l\n putStrLn $ show $ length ans\n sequence_ $ map (putStrLn . unwords . map show) ans\n\nsolve :: Int -> [Int] -> [[Int]] -> [[Int]]\nsolve n lc l = map g . filter (\\ (x,y) -> x/=y) $(fromJust (f sorted list 0))\n where\n list = concat l\n sorted = sort list\n f [] _ _ = Just []\n f (x:xs) (y:ys) idx = do i <- elemIndex x (y:ys)\n let ys' = tail (set i y (y:ys))\n l <- f xs ys' (idx+1)\n return ((idx,idx+i):l)\n set 0 e (x:xs) = e:xs\n set n e (x:xs) = x:set (n-1) e xs\n lc' = scanl (+) 0 lc\n g (x,y) = let (i,j) = convert x\n (k,l) = convert y\n in [i,j,k,l]\n convert idx = (i,j+1)\n where i = fromJust $ findIndex (>idx) lc'\n j = idx - lc' !! (i-1)\n\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\n--import Data.Map (Map, empty, fromList, insert)\n\ntype Size = Array Int Int\ntype Table = Array (Int, Int) Int\ntype Swap = ((Int, Int), (Int, Int))\n\nparseTable :: Size -> [Int] -> Table\nparseTable cs xs = accum (flip const) zeroArray $ getList (1, 1) xs\n where\n zeroArray = accumArray undefined 0 ((1,1), (n, cs ! 1)) []\n n = snd $ bounds cs\n getList (i, j) [] = []\n getList (i, j) (x:xs)\n | j > cs ! i = getList (i+1, 1) (x:xs)\n | otherwise = ((i, j), x) : getList (i, j+1) xs\n\nsolve :: Size -> Table -> [Swap]\nsolve cs table = solve' (1,1) 1 table\n where\n n = sum $ elems cs\n solve' (i,j) m table\n | m == n = []\n | j > cs ! i = solve' (i+1,1) m table\n | table ! (i,j) == m = solve' (i,j+1) (m+1) table\n | otherwise = ((iM,jM), (i,j)) : solve' (i,j+1) (m+1) (table // [((iM,jM), table ! (i,j)), ((i,j), m)])\n where\n (iM,jM) = fst $ head $ dropWhile ((/= m) . snd) $ assocs table\n\nprints :: [Swap] -> IO ()\nprints swaps = print (length swaps) >> mapM_ print' swaps\n where\n print' ((i1,j1), (i2,j2)) = putStrLn $\n concat [show i1, \" \", show j1, \" \", show i2, \" \", show j2]\n\nmain :: IO ()\nmain = do\n n <- readLn\n cs <- liftM (listArray (1,n) . fmap read . words) getLine :: IO (Array Int Int)\n xs <- liftM (parseTable cs . fmap read . words) getContents :: IO Table\n prints $ solve cs xs\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do n <- getLine >>= return . read\n lc <- getLine >>= return . map read . words\n l <- sequence $ replicate n (getLine >>= return . map read . words)\n let ans = solve n lc l\n putStrLn $ show $ length ans\n sequence_ $ map (putStrLn . unwords . map show) ans\n\nsolve :: Int -> [Int] -> [[Int]] -> [[Int]]\nsolve n lc l = map g (fromJust (f sorted list 0))\n where\n list = concat l\n sorted = sort list\n f [] _ _ = Just []\n f (x:xs) (y:ys) idx = do i <- elemIndex x (y:ys)\n let ys' = tail (set i y (y:ys))\n l <- f xs ys' (idx+1)\n return ((idx,idx+i):l)\n set 0 e (x:xs) = e:xs\n set n e (x:xs) = x:set (n-1) e xs\n lc' = scanl (+) 0 lc\n g (x,y) = let (i,j) = convert x\n (k,l) = convert y\n in [i,j,k,l]\n convert idx = (i,j+1)\n where i = fromJust $ findIndex (>idx) lc'\n j = idx - lc' !! (i-1)\n\n"}], "src_uid": "62df8b1821558bea910f422591618e29"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.Array.ST(runSTArray, STArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\nnumOcc :: Ord a => [a] -> M.Map a Integer\r\nnumOcc (x:xs) = let m = numOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m \r\n\tNothing -> M.insert x 1 m \r\nnumOcc [] = M.empty\r\n\r\n\r\nnumOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer\r\nnumOcc' size list = runSTArray $ do \r\n\tarray <- MA.newArray size 0\r\n\tfoldM (addElem array) () list\r\n\treturn array \r\n\r\n\twhere\r\n\t\taddElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()\r\n\t\taddElem array action a = do\r\n\t\t\ti <- MA.readArray array a\r\n\t\t\tMA.writeArray array a (i+1) \r\n\t\r\n\r\n\r\ninsertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]\r\ninsertWithList a b m = case M.lookup a m of \r\n\tJust l -> M.insert a (b:l) m \r\n\tNothing -> M.insert a [b] m \r\n\r\ndeleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]\r\ndeleteWithList a m = case M.lookup a m of \r\n\tJust (x:y:xs) -> M.insert a (y:xs) m\r\n\tJust [x] -> M.delete a m\r\n\r\n\r\nsolve :: Integer -> Integer -> [Integer] -> Integer \r\nsolve n k a = result k occM where\r\n\toccM = numOcc a\r\n\r\n\tresult k occ\r\n\t\t| num >= k = k `parmi` num\r\n\t\t| k > num = result (k-num) occ'\r\n\t\twhere \r\n\t\t\t(key, num) = M.findMax occ\r\n\t\t\tocc' = M.delete key occ\r\n\r\n\tparmi k num \r\n\t\t| k == 0 = 1\r\n\t\t| num == 0 = 1\r\n\t\t| otherwise = (num * parmi (k-1) (num-1)) `div` k \r\n\r\n\r\nplotResult n = print $ mod n 1000000007\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n, k] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\ta <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\tplotResult $ solve n k a\r\n", "positive_code": [{"source_code": "-- Trying to use only ByteString I/O with a state monad this contest\n\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Semigroup\nimport Data.Int\n\ngetSLine :: Monad m => StateT P.ByteString m P.ByteString\ngetSLine = do\n (out, next) <- P.break (== '\\n') <$> get\n put $ P.tail next\n pure out\n\nreadInts :: Monad m => StateT P.ByteString m [Int]\nreadInts = do\n currLine <- getSLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\n-- There has to be a combinator for this. But where?\noutLine :: P.ByteString -> StateT P.ByteString IO ()\noutLine v = StateT $ \\s -> ((), s) <$ P.putStrLn v\n\np :: Int\np = 10^(9 :: Int) + 7\n\nmul :: Int -> Int -> Int\nmul x y = let\n p' :: Int64\n [x', y', p'] = map fromIntegral [x, y, p]\n in fromIntegral $ mod (x' * y') p'\n\nnewtype W = W { unw :: Int }\n\ninstance Semigroup W where\n W x <> W y = W $ mul x y\n\ninv :: Int -> Int\ninv = unw . stimes (p-2) . W\n\nchoose :: Int -> Int -> Int\nchoose n k = let\n step v i = mul v . mul (n+1-i) $ inv i\n in foldl' step 1 [1..k]\n\nmain :: IO ()\nmain = (P.getContents >>=) $ evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n, k] <- readInts\n a <- readInts\n let\n sa = reverse $ sort a\n tarV = sa !! (k-1)\n ct1 = length [x | x <- sa, x == tarV]\n ct2 = length [x | x <- take k sa, x == tarV]\n outLine . P.pack . show $ ct1 `choose` ct2\n"}], "negative_code": [], "src_uid": "69326546e8435ccfff3010947295c291"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\nimport Data.Function\nimport Data.Int\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n = unfoldr $ \\li -> do\n guard $ not $ null li\n pure $ splitAt n li\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n a <- getInts (n * m)\n let\n aips = sort $ zip a [1..]\n unsrows = chunksOf m aips\n soln row = do\n w <- groupBy ((==) `on` fst) row\n reverse $ map snd w\n rows = map soln unsrows\n cost :: [Int] -> Int64\n cost row = let\n incls = scanl' (flip S.insert) S.empty row\n in foldl' (+) 0 $ do\n (i, s) <- zip row incls\n pure $ fromIntegral $ S.size $ fst $ S.split i s\n pure $ putInt64s [foldl' (\\x y -> x + cost y) 0 rows]\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [1, m] <- readMany :: IO [Int]\r\n as <- readMany :: IO [Int]\r\n let xs = map snd $ sortOn (negate . fst) $ zip as [1 :: Int ..]\r\n print $ sum [length $ filter ( IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function (on)\nimport Data.List (groupBy, sort)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> showB) >>> C.unlines\n\ndata TC = TC {n :: Int, m :: Int, as :: [Int]}\n\ninput :: Scanner TC\ninput = do\n n <- int\n m <- int\n as <- (n * m) >< int\n return TC {..}\n\nsolve :: TC -> Int\nsolve TC {..} =\n fst\n . foldl update (0, [])\n . map (sort . map snd)\n . groupOn fst\n . sort\n $ zip as [1 ..]\n where\n update (acc, row) ixs = (acc + cost, tetris $ row ++ ixs)\n where\n cixs = take (m - length row) ixs\n cost = sum [countBy (< i) row | i <- cixs]\n\n tetris xs = let l = length xs in drop (l - l `mod` m) xs\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "5b95da35a4c1251f5376cf3bacc1a549"} {"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nf::Integer->[Integer]->Integer\nf _ (x:[])=2\nf k (x:y:zs)\n |x+k 1 + behind d (x2:xs)\n GT -> behind d (x2:xs)\n LT -> 2 + behind d (x2:xs) \n\n\nmain = do\n n_d <- getLine\n x_n <- getLine\n putStrLn (possible n_d x_n)"}], "negative_code": [], "src_uid": "5babbb7c5f6b494992ffa921c8e19294"} {"source_code": "f::[Int]->[Int]\nf (x:[])=[x]\nf (x:y:xs)\n |x 0 then\n\t\ti:(doit xs 1)\n\telse\n\t\tdoit xs (i+1)\n\nsolve::String -> String\nsolve ss =\n\tlet s = map toint (tail (words ss)) in\n\tlet r = doit s 0 in\n\t(show (length r)) ++ \"\\n\" ++ intercalate \" \" (map show r) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}, {"source_code": "-- Codeforces 1005 A\nimport Data.List\nfoldCount :: [Int] -> [Int]\nfoldCount list = (\\(n, l) -> tail l ++ [n]) $ foldl' func (0, []) list\n where func :: (Int, [Int]) -> Int -> (Int, [Int])\n func (x, l) 1 = (1, l++[x])\n func (_, l) x = (x, l)\n\nmain :: IO ()\nmain = do\n n <- getLine\n list <- getLine >>= return.foldCount.(map read).words :: IO [Int]\n putStrLn $ show $ length list\n putStrLn $ unwords $ map show list\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Prelude\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport Control.Monad\nimport Data.Ratio\nimport Data.Int\nimport Data.Functor\nimport Control.Monad.ST.Safe\nimport Data.STRef\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\n\nmain :: IO ()\nmain = do\n (n :: Int) <- read <$> getLine\n (arr :: [Int]) <- (map read . words) <$> getLine\n let answer = map fst . filter (\\(x, y) -> x + 1 /= y) $ zip arr (tail arr ++ [1])\n printf \"%d\\n\" $ length answer\n forM_ answer $ printf \"%d \" "}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n-- import Data.List.HT\n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\n-- segmentBefore :: (a -> Bool) -> [a] -> [[a]]\n-- segmentBefore _ [] = []\n-- segmentBefore p s = foldr (\\b a-> if p b then [] : [b : head a] ++ tail a else [b : head a] ++ tail a) [] s\n\nsegmentBefore :: (a -> Bool) -> [a] -> [[a]]\nsegmentBefore p =\n-- foldr (\\ x ~(y:ys) -> (if p x then ([]:) else id) ((x:y):ys)) [[]]\n uncurry (:) .\n foldr\n (\\ x ~(y,ys) ->\n let xs = x:y\n in if p x then ([],xs:ys) else (xs,ys))\n ([],[])\n\nsolve :: [Int] -> (Int, [Int])\nsolve xs = (length a, map last a)\n where a = tail $ segmentBefore (==1) xs\n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- readInts\n let r = solve xs\n print $ fst r\n putStrLn $ unwords . map show $ snd r\n\n"}, {"source_code": "main = interact $ format . solve . map read . tail . words\nsolve as = filter (> 0) $ map succ $ zipWith (-) as (tail as ++ [1])\nformat ss = unlines [ show (length ss) , unwords (map show ss) ]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess n x [f] = do\n\t\t\tprint $ n+1\n\t\t\tputStrLn $ intercalate \" \" $ map show (x++[f])\n\n\t\t\t\nprocess n x (a:b:c) | a getLine ::IO Int\n\t\ts<- map read <$> words <$> getLine ::IO [Int]\n\t\tprocess 0 [] s\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(groupBy)\n\nlistStairwaySteps :: [Int] -> [Int]\nlistStairwaySteps = map length . groupBy (<)\n\nmain = do\n line1 <- getLine\n line2 <- getLine\n let a = map read . words $ line2\n let b = listStairwaySteps a\n let k = length b\n print k\n putStrLn . unwords . map show $ b"}, {"source_code": "main = interact $ pureMain\n\npureMain :: String -> String\npureMain s = unlines $ map (unwords . map show) $ [length ans]:ans:[]\n where\n [[n], a] = map (map read . words) $ lines s\n (_, ans) = foldr (\\ v (pre, l) -> if pre == 1 then (v, v:l) else (v, l)) (1, []) a"}], "negative_code": [], "src_uid": "0ee86e75ff7a47a711c9eb41b34ad1a5"} {"source_code": "main :: IO ()\nmain = do [a,b,n] <- getLine >>= return . map read . words\n putStrLn $ show $f a b n\n\nf :: Integer -> Integer -> Integer -> Integer\nf a b n = if n == 0 then a else\n\tif can a 0 b then (a*10+0)*10^(n-1) else\n\tif can a 1 b then (a*10+1)*10^(n-1) else\n\tif can a 2 b then (a*10+2)*10^(n-1) else\n\tif can a 3 b then (a*10+3)*10^(n-1) else\n\tif can a 4 b then (a*10+4)*10^(n-1) else\n\tif can a 5 b then (a*10+5)*10^(n-1) else\n\tif can a 6 b then (a*10+6)*10^(n-1) else\n\tif can a 7 b then (a*10+7)*10^(n-1) else\n\tif can a 8 b then (a*10+8)*10^(n-1) else\n\tif can a 9 b then (a*10+9)*10^(n-1) else\n\t -1\n\ncan :: Integer -> Integer -> Integer -> Bool\ncan a d b = if (10*a+d) `mod` b == 0 then True else False\n", "positive_code": [{"source_code": "\nreadInts :: String -> [Int]\nreadInts str = map read (words str)\n\n\nmain :: IO ()\nmain = do\n [a, b, n] <- fmap readInts getLine\n let s = mod (a*10+9) b\n if s>9 then print (-1)\n else do\n putStr $ show a\n putStr $ show $ 9-s\n putStr $ replicate (n-1) '0'\n"}, {"source_code": "main=do\n [a,b,n] <- fmap(map read.words)getLine\n putStrLn $ f a b n\n\nf a b n\n | null xs = \"-1\"\n | otherwise = show x0++replicate(n-1)'0'\n where\n xs = [y|x<-[0..9],let y=10*a+x,mod y b<1]\n x0 = head xs"}, {"source_code": "main = getContents >>= putStr.concatMap show.solve.map read.words\n\nsolve :: [Int] -> [Int]\nsolve (a:b:n:[]) \n\t| ((b - ((a*10) `mod` b)) `mod` b) > 9 = [-1]\n\t| otherwise = a:fir:replicate (n-1) 0 \n\t\twhere fir = (b - ((a*10) `mod` b)) `mod` b\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nextend a b 0 = a \nextend a b n = if z <10 then extend (x+z) b (n-1) else if y==0 then x*10^(n-1) else (-1)\n\twhere x = a*10 \n\t y = mod x b\n z = b - y\n\nmain= do\n\t [a,b,n]<- map read. words <$>getLine ::IO [Integer]\n\t print $ extend a b n\n \n \n\t \n"}, {"source_code": "main :: IO ()\nmain = do [a,b,n] <- getLine >>= return . map read . words\n putStrLn $ show $f a b n\nf :: Integer -> Integer -> Integer -> Integer\nf a b n = \n if (a*10)`mod`b==0 then (a*10)*10^(n-1) else\n if b-((a*10)`mod`b)<=9 then (a*10+b-((a*10)`mod`b))*10^(n-1) else\n -1\n"}, {"source_code": "main :: IO ()\nmain = do [a,b,n] <- getLine >>= return . map read . words\n putStrLn $ show $f a b n\nf :: Integer -> Integer -> Integer -> Integer\nf a b n = \n if a*10`mod`b==0 then a*10^n else\n if b-a*10`mod`b<=9 then (a*10+b-(a*10`mod`b))*10^(n-1) else\n -1\n"}, {"source_code": "main :: IO ()\nmain = getLine >>= putStrLn . f . map (read :: String -> Int) . words \n\nf :: [Int] -> String\nf (a:b:n:_)\n | null xs = \"-1\"\n | otherwise = show (head xs) ++ replicate (n-1) '0' \n where \n xs = [y | x <- [0..9], let y = 10*a + x, mod y b == 0]\n"}, {"source_code": "extend :: Int -> Int -> Int -> Maybe (Int, Int)\nextend a b 0 = Just (a, 0)\nextend a b n = \n let m = (a * 10) `mod` b\n d = (b - m) `mod` b\n in if 0 <= d && d < 10 then Just (10*a + d, n-1) else Nothing\n\n\nmain = do\n inpStr <- getLine\n let [a, b, n] = map (read :: String -> Int) $ words inpStr\n in case (extend a b n) of\n Nothing -> putStrLn \"-1\"\n Just (m, k) -> putStrLn $ (show m) ++ (replicate k '0')\n\n"}, {"source_code": "\nfunc a b n\n | null xs = \"-1\"\n | otherwise = show a ++ show (head xs) ++ replicate (n - 1) '0' \n where\n xs = [y | y <- [0 .. 9], (a * 10 + y) `mod` b == 0]\n\nmain = do\n [a, b, n] <- fmap (map read . words) getLine\n putStrLn $ func a b n\n"}, {"source_code": "import Data.Char (intToDigit)\n\nmain :: IO ()\nmain = do\n [a, b, n] <- fmap (map read . words) getLine\n let d = head $ filter (\\i -> mod (a * 10 + i) b == 0) [0 .. 9] ++ [-1]\n if d == -1\n then putStrLn \"-1\"\n else putStrLn $ show a ++ [intToDigit d] ++ replicate (n - 1) '0'\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = putStrLn . show . solve . map (toInteger . maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Integer] -> Integer\nsolve [a, b, n] = case f a b of\n x : _ -> x * 10 ^ (n-1)\n _ -> -1\n where\n f a b = [a' | c <- [0..9], let a' = a * 10 + c, rem a' b == 0]\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> String\nsolve [a, b, n] = case x of\n [] -> \"-1\"\n (x:xs) -> show a ++ show x ++ replicate (n - 1) '0'\n where\n x = filter (\\c -> (10*a + c) `mod` b == 0) [0 .. 9]\n\nmain :: IO ()\nmain = reads >>= putStrLn . solve\n"}, {"source_code": "-- Codeforces 260A\n\n-- At first try to add to the right one digit from 0 to 9.\n-- If it is impossible write -1. \n-- In other case, the remaining n\u20131 digits can be 0 because divisibility doesn\u2019t change.\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve . map read . words\n\nsolve :: [Int] -> String\nsolve [a, b, n] = if null k then \"-1\" else show (head k) ++ replicate (n-1) '0' where k = filter (\\x -> x `mod` b == 0) $ map (a * 10 +) [0..9]\n\n"}, {"source_code": "extend b a\n | null e = -1\n | otherwise = head e\n where e = filter (\\x -> x `mod` b == 0) $ map (\\x -> a * 10 + x) [0 .. 9]\n\nsolve a b n\n | c == -1 = \"-1\"\n | otherwise = show c ++ replicate (n - 1) '0'\n where c = extend b a\n\nmain = do [a, b, n] <- fmap words getLine\n putStrLn $ solve (read a) (read b) (read n)\n\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = putStrLn . show . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve [a, b, n] = case f a b n of\n x : _ -> x\n _ -> -1\n where\n f a b 0 = [a]\n f a b n = concat [f a' b (n-1) | c <- [0..9], let a' = a * 10 + c, rem a' b == 0]\n"}, {"source_code": "main = getContents >>= putStr.concatMap show.solve.map read.words\n\nsolve :: [Int] -> [Int]\nsolve (a:b:n:[]) \n\t| (b - ((a*10) `mod` b)) > 9 = [-1]\n\t| n > 1 && b > 9 = [-1]\n\t| otherwise = a:fir:replicate (n-1) b \n\t\twhere fir = b - ((a*10) `mod` b)\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nextend a b 0 = a \nextend a b n = if z <10 then extend (x+z) b (n-1) else (-1)\n\twhere x = a*10 \n\t y = mod x b\n z = b - y\n\nmain= do\n\t [a,b,n]<- map read. words <$>getLine ::IO [Integer]\n\t print $ extend a b n\n \n \n\t \n"}, {"source_code": "main :: IO ()\nmain = do [a,b,n] <- getLine >>= return . map read . words\n putStrLn $ show $f a b n\n\nf :: Integer -> Integer -> Integer -> Integer\nf a b n = if n == 0 then a else\n\tif can a 0 b then (a*10+0)*10^(n-1) else\n\tif can a 1 b then (a*10+1)*10^(n-1) else\n\tif can a 2 b then (a*10+2)*10^(n-1) else\n\tif can a 3 b then (a*10+3)*10^(n-1) else\n\tif can a 4 b then (a*10+4)*10^(n-1) else\n\tif can a 5 b then (a*10+5)*10^(n-1) else\n\tif can a 6 b then (a*10+6)*10^(n-1) else\n\tif can a 7 b then (a*10+7)*10^(n-1) else\n\tif can a 8 b then (a*10+8)*10^(n-1) else\n\tif can a 0 b then (a*10+9)*10^(n-1) else\n\t -1\n\ncan :: Integer -> Integer -> Integer -> Bool\ncan a d b = if (10*a+d) `mod` b == 0 then True else False\n"}, {"source_code": "\nextend a b 0 = Just a\nextend a b n = \n let m = (a * 10) `mod` b\n d = (b - m) `mod` b\n in if 0 <= d && d < 10 then extend (10*a + d) b (n-1) else Nothing\n\n\nmain = do\n inpStr <- getLine\n let [a, b, n] = map (read :: String -> Int) $ words inpStr\n in case (extend a b n) of\n Nothing -> putStrLn \"-1\"\n Just m -> putStrLn (show m)\n\n"}, {"source_code": "main :: IO ()\nmain = getLine >>= print . f . map (read :: String -> Int) . words \n\nf :: [Int] -> String\nf (a:b:n:_)\n | null xs = \"-1\"\n | otherwise = show (head xs) ++ replicate (n-1) '0' \n where \n xs = [y | x <- [0..9], let y = (10 * a + x) `mod` b == 0]\n"}, {"source_code": "main :: IO ()\nmain = getLine >>= print . f . map (read :: String -> Int) . words \n\nf :: [Int] -> Int\nf (a:b:n:_)\n | null xs = -1\n | otherwise = (10*a + head xs) * (10 ^ (n-1))\n where \n xs = [y | y <- [0..9], (10 * a + y) `mod` b == 0]\n"}, {"source_code": "main :: IO ()\nmain = getLine >>= putStrLn . f . map (read :: String -> Int) . words \n\nf :: [Int] -> String\nf (a:b:n:_)\n | null xs = \"-1\"\n | otherwise = show (head xs) ++ replicate (n-1) '0' \n where \n xs = [y | x <- [0..9], let y = (10 * a + x) `mod` b == 0]\n"}], "src_uid": "206eb67987088843ef42923b0c3939d4"} {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = readLn >>= \\k -> getLine >>= putStrLn . solve k\n\nsolve :: Int -> String -> String\nsolve k = maybe \"-1\" (([1..k] >>) . concat) . mapM (\\x -> if length x `mod` k == 0 then Just (take (length x `div` k) x) else Nothing) . group . sort\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$(\\[k,s] -> f (read k) (group$sort s)).words\ndivides k s = length s `mod` k == 0\nf k grp\n | (any (==False).map (divides k)) grp = \"-1\"\n | otherwise = build k grp\nbuild k grp = concat (replicate k (concat (map (\\s -> replicate ((length s) `quot` k) (head s)) grp)))\n\n\n \n \n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n k <- fmap read getLine\n s <- fmap (map (liftA2 (,) length head) . group . sort) getLine\n if all (\\(n, _) -> mod n k == 0) s\n then putStrLn $ concat $ replicate k $ concatMap (\\(n, a) -> replicate (div n k) a) s\n else print $ -1\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Char.html\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n\nsameList :: Int -> a -> [a]\nsameList n a\n\t| n == 0 \t= []\n\t| otherwise = (a : (sameList (n - 1) a))\n\ngetCount :: String -> [Int]\ngetCount [] \t = sameList 26 0\ngetCount (a : b) = update a (getCount b)\n\nupdate :: Char -> [Int] -> [Int]\nupdate c a = (take i a) ++ [(a !! i) + 1] ++ (drop (i + 1) a)\n\twhere i = (fromEnum c) - (fromEnum 'a')\n\ncheck :: Int -> [Int] -> Bool\ncheck k []\t\t= True\ncheck k (a:b) \t= (mod a k == 0) && check k b\n\ncopy :: Int -> String -> String\ncopy 0 _ \t= []\ncopy k s\t= s ++ copy (k - 1) s\n\ncollate :: Int -> [Int] -> Int -> String\ncollate k cnt c\n\t| c >= 26 + fromEnum 'a'\t= []\n\t| otherwise\t\t\t\t\t= (sameList (div (head cnt) k) ch) ++\n\t\t\t\t\t\t\t\t(collate k (tail cnt) (c + 1))\n\t\twhere ch = toEnum c\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tlet input = words str\n\tlet k = read (input !! 0)\n\tlet cnt = getCount (input !! 1)\n\tif (check k cnt)\n\t\tthen putStrLn (copy k (collate k cnt (fromEnum 'a')))\n\t\telse putStrLn \"-1\"\n"}, {"source_code": "\nimport List (group, sort)\n\nsolve :: Int -> String -> Maybe String\nsolve k s\n | all ((0 ==) . flip mod k . length) s' = Just $ take (length s) $ cycle $ concatMap (\\s -> take (div (length s) k) s) s'\n | otherwise = Nothing\n where\n s' = group $ sort s\n\nmain :: IO ()\nmain = do\n n <- readLn\n s <- getLine\n putStrLn $ maybe \"-1\" id $ solve n s\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Debug.Trace\n\nsolve :: Int -> String -> String\nsolve k s\n | canSolve = concat $ take k $ repeat s'\n | otherwise = \"-1\"\n where\n track q = trace (show q) q\n grouped = group $ sort s\n canSolve = all (\\x -> x `mod` k == 0) $ map length grouped\n s' = concat $ map (\\x -> take (length x `div` k) x) $ grouped\n\nmain = do\n k <- read <$> getLine\n s <- getLine\n putStrLn $ solve k s\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = readLn >>= \\k -> getLine >>= putStrLn . solve k\n\nsolve :: Int -> String -> String\nsolve k cs = maybe \"-1\" (([1..k] >>) . concat) $ mapM (\\x -> if length x `mod` k == 0 then Just (take (length x `div` k) x) else Nothing) $ group $ sort cs\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = readLn >>= \\k -> getLine >>= putStrLn . solve k\n\nsolve :: Int -> String -> String\nsolve k = maybe \"-1\" (([1..k] >>) . concat) . mapM (\\xs@(x:_) -> case divMod (length xs) k of (d, 0) -> Just (replicate d x); _ -> Nothing) . group . sort\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = readLn >>= \\k -> getLine >>= putStrLn . solve k\n\nsolve :: Int -> String -> String\nsolve k cs | all ((==0) . (`mod`k)) $ map length $ group $ sort cs =\n [1..k] >> concatMap (\\x -> take (length x `div` k) x) (group $ sort cs)\n | otherwise = \"-1\"\n"}, {"source_code": "import Data.List\nimport Control.Arrow\nmain = do\n k <- readLn\n s <- getLine\n let fs = map (length &&& head) $ group $ sort s\n if all ((==0) . (`mod` k) . fst) fs\n then putStrLn $ concat $ replicate k $ concat $ map (uncurry replicate . first (`div` k)) fs\n else print (-1)\n"}, {"source_code": "import Data.List\n\ntoKString :: Int -> String -> Maybe String\ntoKString k s | length s `mod` k /= 0 = Nothing\n | otherwise = toKString' k s\n where\n toKString' _ [] = Just \"\"\n toKString' k s = do\n a <- if all (== head s) (take k s)\n then Just $ head s\n else Nothing\n rest <- toKString' k (drop k s)\n return $ a : rest\n\nmain = do\n k <- readLn\n s <- getLine\n case toKString k $ sort s of\n Just s' -> putStrLn $ concat $ replicate k s'\n _ -> putStrLn \"-1\"\n\n"}, {"source_code": "import Data.Char\nimport Data.List\n \ncount :: String -> Char -> Int\ncount s c = length $ filter (\\x -> x == c) s\n\nsolve :: Int -> String -> String\nsolve k s = let z = getIt s 'a' 'z' k in if z == \"-1\" then z else repeat' k z\n\nrepeat' :: Int -> String -> String\nrepeat' 0 s = \"\"\nrepeat' a s = s ++ (repeat' (a - 1) s)\n\ngetIt :: String -> Char -> Char -> Int -> String\ngetIt s c to k = if c > to then \"\" else\n if mod (count s c) k /= 0 then \"-1\" else\n let\n z = getIt s (toEnum(fromEnum(c) + 1)) to k\n u = count s c\n in\n if z == \"-1\" then z\n else (replicate (div u k) c) ++ z \nmain = do n <- getLine\n s <- getLine\n putStrLn $ solve (read n) s"}, {"source_code": "import Data.Array\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n k <- readLn\n cs <- filter((0<).snd).assocs.accumArray (+) 0 ('a','z').(`zip`repeat 1) <$> getLine\n if all ((0==).(`mod`k).snd) cs\n then replicateM_ k $ forM cs $ \\(c,i)-> putStr $ replicate (i`div`k) c\n else print $ -1\n"}, {"source_code": "import Data.List\nmain = do\n [kStr,s] <- fmap lines getContents\n let k = read kStr::Int\n sortedS = sort s\n numChars = map length $ group sortedS\n result = if all (\\x -> x`rem`k == 0) numChars\n then concat $ replicate k $ takeEvery k sortedS\n else \"-1\"\n putStrLn result\n\ntakeEvery :: Int -> [a] -> [a]\ntakeEvery n [] = []\ntakeEvery n (x:xs) = x : (takeEvery n $ drop (n-1) xs)\n\n"}, {"source_code": "import Data.List\n\ncalc :: Int -> String -> Maybe String\ncalc k s = if all (\\t -> length t `mod` k == 0) xs\n then Just $ (foldl1 (++) . replicate k) $ kString1 xs\n else Nothing\n where\n xs = group $ sort s\n kString1 [] = \"\"\n kString1 (x:xs) = take (length x `div` k) x ++ kString1 xs\n\nmain = do s <- getLine\n t <- getLine\n case calc (read s) t of\n Just x -> putStrLn x\n Nothing -> print (-1) -- -1 \u306f\u62ec\u5f27\u3067\u56f2\u3080\u5fc5\u8981\u304c\u3042\u308b\n\n\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \t\n\t\t\t\n\n \n\n\nmain= do\n\tk<- read <$> getLine ::IO Int\n\ts<-getLine\n\tlet (a,b)= unzip $ map (\\z-> (head z, length z)) $ group $ sort s\n\tlet c= all (==0) ( map (\\z-> mod z k) b) \n\tlet d = map (\\z-> div z k) b\n\tputStrLn $ if c then concat $ replicate k $ concat $ zipWith (\\x y -> replicate y x) a d else \"-1\""}], "negative_code": [{"source_code": "\nimport List (group, sort)\n\nsolve :: Int -> String -> Maybe String\nsolve k s\n | all ((0 ==) . flip mod k . length) s' = Just $ concatMap (\\s -> take (div (length s) k) s) s'\n | otherwise = Nothing\n where\n s' = group $ sort s\n\nmain :: IO ()\nmain = do\n n <- readLn\n s <- getLine\n putStrLn $ maybe \"-1\" id $ solve n s\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = readLn >>= \\k -> getLine >>= putStrLn . solve k\n\nsolve :: Int -> String -> String\nsolve k = maybe \"-1\" (([1..k] >>) . concat) . mapM (\\xs@(x:_) -> if length xs `mod` k == 0 then Just (replicate k x) else Nothing) . group . sort\n"}, {"source_code": "import Data.List (group, sort)\n\nmain :: IO ()\nmain = readLn >>= \\k -> getLine >>= putStrLn . solve k\n\nsolve :: Int -> String -> String\nsolve k cs = maybe \"-1\" concat $ mapM (\\x -> if length x `mod` k == 0 then Just (take (length x `div` k) x) else Nothing) $ group $ sort cs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \t\n\t\t\t\n\n \n\n\nmain= do\n\tk<- read <$> getLine ::IO Int\n\ts<-getLine\n\tlet (a,b)= unzip $ map (\\z-> (head z, length z)) $ group $ sort s\n\tlet c= all (==0) ( map (\\z-> mod z k) b) \n\tlet d = map (\\z-> div z k) b\n\tputStrLn $ if c then concat $ replicate k $ concat $ zipWith (\\x y -> replicate y x) a d else \"\""}], "src_uid": "f5451b19cf835b1cb154253fbe4ea6df"} {"source_code": "toI l = map read $ words l :: [Int]\n--comp s h = product [(s - h + 1) .. s]\n\nsolve n s h\n | n > s = -1\n | h == 1 = 0\n | n == s = 1\n | otherwise = 1 - (product d)\n where \n a = [(s - h - n + 2)..(s - h)]\n b = [(s-n + 1)..(s-1)]\n c = zip a b \n d = [(fromIntegral h1) / (fromIntegral h2) | (h1, h2) <- c ]\n \n\nmain = do\n l1 <- getLine\n let [n, m, h] = toI l1\n l2 <- getLine\n let s = toI l2\n let sh = s!!(h-1)\n let ss = sum s\n --print $ comp (ss - n + 1) sh\n print $ solve n ss sh", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, m, h] <- ( map read . words ) `liftM` getLine :: IO [Int]\n s <- ( map read . words ) `liftM` getLine :: IO [Int]\n\n let sh = s !! (h-1)\n ss = sum s\n\n if ss < n\n then putStrLn \"-1.0\"\n else\n let res = 1 - compute (sh-1) (ss-1) (n-1) in\n putStrLn $ show $ res --fromIntegral (numerator res) / fromIntegral (denominator res)\n\ncompute :: (Num b, Integral a) => a -> a -> b -> Double\ncompute _ _ 0 = 1\ncompute sh ss n = ( 1 - fromIntegral sh / fromIntegral ss ) * compute sh (ss-1) (n-1)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Ratio\n\nmain = do\n [n, m, h] <- ( map read . words ) `liftM` getLine :: IO [Int]\n s <- ( map read . words ) `liftM` getLine :: IO [Integer]\n\n let sh = s !! (h-1)\n ss = sum s\n\n if ss < fromIntegral n\n then putStrLn \"-1.0\"\n else\n let res = 1 - compute (sh-1) (ss-1) (n-1) in\n putStrLn $ show $ fromIntegral (numerator res) / fromIntegral (denominator res)\n\ncompute :: (Num b, Integral a) => a -> a -> b -> Ratio a\ncompute _ _ 0 = 1\ncompute sh ss n = ( 1 - sh % ss ) * compute sh (ss-1) (n-1)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Ratio\n\nmain = do\n [n, m, h] <- ( map read . words ) `liftM` getLine :: IO [Int]\n s <- ( map read . words ) `liftM` getLine :: IO [Int]\n\n let sh = s !! (h-1)\n ss = sum s\n\n if ss < n\n then putStrLn \"-1.0\"\n else\n let res = 1 - compute (sh-1) (ss-1) (n-1) in\n putStrLn $ show $ fromIntegral (numerator res) / fromIntegral (denominator res)\n\ncompute :: Integral a => a -> a -> a -> Ratio a\ncompute _ _ 0 = 1\ncompute sh ss n = ( 1 - sh % ss ) * compute sh (ss-1) (n-1)\n"}, {"source_code": "fact n = f n 1\n where \n f 0 r = r\n f n r = f (n - 1) (r * n) \n\ncomb :: Int -> Int -> Int\ncomb n 0 = 1\ncomb n k = (fact n) `div` ((fact k) * (fact $ n - k ))\ntoI l = map read $ words l :: [Int]\n\npos n s h = sum [(comb h i) * (comb s (n - i)) | i <- p]\n where \n m = max [n, h] \n p = [1..h]\n \nsolve n s h\n | n > s = -1 \n | n == s = 1\n | otherwise = (fromIntegral (pos (n - 1) (s - h) (h -1))) / (fromIntegral (comb (s - 1) (n - 1)))\n\nmain = do \n l1 <- getLine \n let [n, m, h] = toI l1\n l2 <- getLine \n let s = toI l2 \n print $ solve n (sum s) (s!!(h-1))"}, {"source_code": "fact n = f n 1\n where \n f 0 r = r\n f n r = f (n - 1) (r * n) \n\ncomb :: Int -> Int -> Int\ncomb n 0 = 1\ncomb n k = (fact n) `div` ((fact k) * (fact $ n - k ))\ntoI l = map read $ words l :: [Int]\n\npos n s h = sum [(comb h i) * (comb s (n - i)) | i <- p]\n where \n m = max [n, h] \n p = [1..h]\n \nsolve n s h\n | n > s = -1 \n | h == 1 = 0\n | n == s = 1\n | otherwise = (fromIntegral (pos (n - 1) (s - h) (h -1))) / (fromIntegral (comb (s - 1) (n - 1)))\n\nmain = do \n l1 <- getLine \n let [n, m, h] = toI l1\n l2 <- getLine \n let s = toI l2 \n print $ solve n (sum s) (s!!(h-1))"}, {"source_code": "toI l = map read $ words l :: [Int]\n--comp s h = product [(s - h + 1) .. s]\n\nsolve n s h\n | n > s = -1\n | h == 1 = 0\n | n == s = 1\n | otherwise = 1 - ((fromIntegral a) / (fromIntegral b))\n where \n a = product [(s - h - n + 2)..(s - h)]\n b = product [(s-n + 1)..(s-1)]\n \n\nmain = do\n l1 <- getLine\n let [n, m, h] = toI l1\n l2 <- getLine\n let s = toI l2\n let sh = s!!(h-1)\n let ss = sum s\n --print $ comp (ss - n + 1) sh\n print $ solve n ss sh\n"}, {"source_code": "fact n = f n 1\n where \n f 0 r = r\n f n r = f (n - 1) (r * n) \n\ncomb :: Int -> Int -> Int\ncomb n 0 = 1\ncomb n k = (fact n) `div` ((fact k) * (fact $ n - k ))\ntoI l = map read $ words l :: [Int]\n\npos n s h = sum [(comb h i) * (comb s (n - i)) | i <- p]\n where \n m = max [n, h] \n p = [1..h]\n \nsolve n s h\n | h == 1 = 0\n | n > s = -1 \n | n == s = 1\n | otherwise = (fromIntegral (pos (n - 1) (s - h) (h -1))) / (fromIntegral (comb (s - 1) (n - 1)))\n\nmain = do \n l1 <- getLine \n let [n, m, h] = toI l1\n l2 <- getLine \n let s = toI l2 \n print $ solve n (sum s) (s!!(h-1))"}], "src_uid": "ffafd385ec79aa28b8d30224baf6bcfe"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n $ fmap to64 poi\n return $ if odd (sum xs) || any odd xs then \"First\" else \"Second\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\n", "positive_code": [{"source_code": "import qualified Data.ByteString as B (getLine)\nimport Data.ByteString.Char8 (readInt, words)\nimport Control.Applicative\nimport Prelude hiding (words)\nimport Data.Maybe (fromJust)\n\n\n\nsolve xs\n | odds == 0 = \"Second\"\n | otherwise = \"First\"\n where odds = length $ filter odd xs\n\nmain = do\n B.getLine >> B.getLine >>= putStrLn.solve.map (fst.fromJust.readInt).words\n\n\n\n\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Data.List( foldl')\nimport Data.ByteString.Char8( readInt, getLine, words\t)\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe( fromJust)\n\nmain = do\n let\n\treadBS2Int = fst . fromJust . readInt\n\treadLine2Ints = map readBS2Int . C8.words <$> C8.getLine\n _n_ <- readLn::IO Int\n as_ <- readLine2Ints\n let\n\tisOdds = odd <$> as_\n\n\tinitNumOdds = foldl' f 0 isOdds\n\t\t\twhere\n\t\t\t f v a = if a then v+1 else v\n\n\tinitOdd = odd initNumOdds \n\n putStr $ if initOdd\n\t\tthen \"First\"\n\t\telse if initNumOdds /= 0\n\t\t then \"First\"\n\t\t else \"Second\"\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\n\nreadInt = fst . M.fromJust . C.readInt\n\nmain = do\n B.getLine\n (dropWhile (even . readInt) . C.words -> odds) <- B.getLine\n putStrLn $ if null odds then \"Second\" else \"First\"\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\n\nreadInt = fst . M.fromJust . C.readInt\n\nmain = do\n B.getLine\n (length . filter odd . map readInt . C.words -> nodd) <- B.getLine\n putStrLn $ if nodd > 0 then \"First\" else \"Second\"\n"}, {"source_code": "-- 841B\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.ByteString.Lazy.Char8 (ByteString(..), readInt, words, interact)\nimport Data.Maybe\nimport Prelude hiding (interact, words)\n\nmain = getLine >> (interact $ f . words)\n\nf :: [ByteString] -> ByteString\nf nums = if any isOdd nums\n then \"First\\n\"\n else \"Second\\n\"\n\nisOdd = odd . fst . fromJust . readInt"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n $ fmap to64 poi\n return $ if odd (sum xs) || all even xs then \"First\" else \"Second\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n $ fmap to64 poi\n return $ if odd $ sum xs then \"First\" else \"Second\"\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nto64 x = fromIntegral x :: Int64"}, {"source_code": "-- 841B\n\nmain :: IO ()\nmain = getLine >> (interact $ f . map read . words)\n\nf :: [Integer] -> String\nf nums = if (odd . sum . map (`mod` 2) $ nums)\n then \"First\\n\"\n else \"Second\\n\"\n"}, {"source_code": "-- 841B\n\nmain :: IO ()\nmain = getLine >> (interact $ f . map read . words)\n\nf :: [Int] -> String\nf nums = if (odd . sum . map (`mod` 2) $ nums)\n then \"First\\n\"\n else \"Second\\n\"\n"}, {"source_code": "-- 841B\n\nmain :: IO ()\nmain = getLine >> (interact $ f . map read . words)\n\nf :: [Int] -> String\nf nums = if (odd . sum . map (`mod` 2) $ nums)\n then \"Second\\n\"\n else \"First\\n\"\n"}], "src_uid": "808611f86c70659a1d5b8fc67875de31"} {"source_code": "-- http://codeforces.com/problemset/problem/1257/C\n\nimport Control.Monad\nimport qualified Data.Map as Map\nimport Data.Maybe\n\n\ntype Case = [Int]\ntype History = Map.Map\ndata Record = Record { latestIndex :: Int\n , minDifference :: Maybe Int\n } deriving (Show)\n\n\nfilterTestCases :: [String] -> [String]\nfilterTestCases lines =\n map snd -- get the values of the indexed list = [2]\n $ filter (odd . fst) -- filter the list by odd indices = [(1,2)]\n $ zip [0..] lines -- create an indexed list = [(0,1),(1,2),(2,3)]\n\n\ntoCase :: String -> Case\ntoCase line = map read $ words line :: Case\n\n\nupdateRecord :: Int -> Int -> Record -> Record\nupdateRecord key index record\n | minDifference record == Nothing = record { latestIndex = index, minDifference = currentDifference }\n | currentDifference < minDifference record = record { latestIndex = index, minDifference = currentDifference }\n | otherwise = record { latestIndex = index }\n where currentDifference = Just $ index - latestIndex record\n\n\nupdateHistory :: Int -> Int -> History Int Record -> History Int Record\nupdateHistory key index history\n | Map.notMember key history = Map.insert key Record { latestIndex=index, minDifference=Nothing } history\n | Map.member key history = Map.insert key (updateRecord key index (fromJust $ Map.lookup key history)) history\n\n\ngetMin :: [Maybe Int] -> Maybe Int\ngetMin [] = Nothing\ngetMin list = foldr1 min list\n\n\nsolveRecursive :: Case -> Int -> History Int Record -> Maybe Int\nsolveRecursive [] index history\n | Map.size history == 0 = Nothing\n | otherwise = getMin $ filter isJust $ map minDifference $ Map.elems history\nsolveRecursive (x:xs) index history =\n solveRecursive xs (index + 1) $ updateHistory x index history\n\n\nsolve :: Case -> Int\nsolve [] = -1\nsolve (x:xs)\n | isNothing solution = -1\n | otherwise = 1 + (fromJust solution)\n where solution = solveRecursive xs (index + 1) history\n history = Map.singleton x Record {latestIndex=index, minDifference=Nothing}\n index = 0\n\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . toCase) . filterTestCases . tail . lines\n", "positive_code": [{"source_code": "import qualified Data.Map as Map\nimport Data.Maybe\nimport Control.Monad\n\ntype State = (Map.Map Int Index, Maybe Int)\ntype Indexed a = (Index,a)\ntype Index = Int\n\nstep :: State -> Indexed Int-> State\nstep (m,Just c) (index,n) = (newMap,Just $ min c d)\n where\n newMap = Map.insert n index m\n d =1+ index - fromMaybe 0 (Map.lookup n m)\nstep (m, Nothing) (index,n) = (newMap,d)\n where\n newMap = Map.insert n index m\n d =(\\x ->1 + index - x) <$> Map.lookup n m\n\nsolve :: [Int] -> Maybe Int\nsolve l = snd $ foldl step (Map.empty,Nothing) (zip [0..] l)\n\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n l <- fmap (map read.words) getLine\n print $ fromMaybe (-1) $ solve l\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "negative_code": [], "src_uid": "a4be9b3484f3f24014392a1c3ad23f2f"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Prelude\n\nmain = do\n getLine\n s <- getLine\n let a = length $ filter (=='A') s\n let b = length $ filter (=='D') s\n if a < b then putStrLn \"Danik\"\n else if a > b then putStrLn \"Anton\"\n else putStrLn \"Friendship\"\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nans a d | a==d = \"Friendship\"\n\t| a>d = \"Anton\"\n | otherwise = \"Danik\"\n\nonecase= do\n\t\tx<-getLine\n\t\tlet a = length $ filter (=='A') x\n\t\tlet d = length $ filter (=='D') x\n\t\tputStrLn $ ans a d\n\nmain::IO ()\nmain=do\n t<- read <$> getLine ::IO Int\n onecase\n"}, {"source_code": "anton \"\" = 0\nanton (x:xs) = new + anton xs\n where new = if x == 'A' then 1 else 0\n\ngetResult str\n | a > d = \"Anton\"\n | d > a = \"Danik\"\n | otherwise = \"Friendship\"\n where a = anton str\n d = length str - a\n\nmain :: IO ()\nmain = do\n getLine\n ln <- getLine\n putStrLn $ getResult ln\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List\n\nwinnerStr = [\"Danik\",\"Friendship\",\"Anton\"]\n\nresult :: Char -> Int\nresult 'A' = -1\nresult 'D' = 1\nresult _ = 0\n\nwinner :: [Char] -> String\nwinner g = (!!) winnerStr . fromEnum . compare 0 . sum . map result $ g\n\nmain = do\n nStr <- getLine\n g <- getLine\n putStrLn $ winner g"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ f . (\\(_:x:_) -> x) . words\n\nf :: String -> String\nf xs | length (filter (=='D') xs) *2 > length xs = \"Danik\"\n | length (filter (=='D') xs) *2 < length xs = \"Anton\"\n | otherwise = \"Friendship\"\n"}, {"source_code": "count :: (Int, Int) -> String -> (Int, Int)\ncount (a, d) [] = (a, d)\ncount (a, d) (s:xs)\n | s == 'A' = count ((a + 1), d) xs\n | s == 'D' = count (a, (d + 1)) xs\n\nres :: Int -> Int -> String\nres a d\n | a < d = \"Danik\"\n | a > d = \"Anton\"\n | otherwise = \"Friendship\"\n\nmain = do\n _ <- getLine\n arr <- getLine\n\n let (a, d) = count (0, 0) arr\n putStrLn $ res a d\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\nmain=do\n n<- read <$> getLine ::IO Int\n a<- getLine\n let b = length $ filter (=='A') a\n putStrLn $ if b > n-b then \"Anton\" else if n-b >b then \"Danik\" else \"Friendship\"\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhoWon :: String -> String\nwhoWon s\n | a > d = \"Anton\"\n | a < d = \"Danik\"\n | otherwise = \"Friendship\"\n where a = length $ filter (=='A') s\n d = (length s) - a\n\n\nmain :: IO ()\nmain = do\n _ <- readInt\n s <- getLine\n putStrLn $ whoWon s "}, {"source_code": "main = interact solve\nsolve s = case compare a d of\n GT -> \"Anton\"\n LT -> \"Danik\"\n EQ -> \"Friendship\"\n where a = length (filter (== 'A') s)\n d = length (filter (== 'D') s)\n"}, {"source_code": "main :: IO ()\nmain = interact (solve . (!! 1) . lines)\n\nsolve :: String -> String\nsolve s\n | a > d = \"Anton\"\n | a < d = \"Danik\"\n | a == d = \"Friendship\"\n where\n a = length . filter (== 'A') $ s\n d = length . filter (== 'D') $ s\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/734/A\n\nsolve :: String -> String\nsolve s\n | a > d = \"Anton\"\n | a < d = \"Danik\"\n | otherwise = \"Friendship\"\n where a = length $ filter (=='A') s\n d = (length s) - a\n\nmain :: IO ()\nmain = do\n readLn :: IO Int\n s <- getLine\n putStrLn $ solve s\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/734/A\n\nsolve :: String -> String\nsolve s\n | a > d = \"Anton\"\n | a < d = \"Danik\"\n | otherwise = \"Friendship\"\n where a = length $ filter (=='A') s\n d = (length s) - a\n\nmain :: IO ()\nmain = do\n _ <- readLn :: IO Int\n s <- getLine\n putStrLn $ solve s\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Applicative\n\ndata Result = Anton\n | Danik\n | Friendship\n deriving Show\n\nsolve :: String -> Result\nsolve input = go input 0 0\n where\n go [] !a !d\n | a > d = Anton\n | a < d = Danik\n | otherwise = Friendship\n \n go ('A':cs) !a !d = go cs (a+1) d\n go ('D':cs) !a !d = go cs a (d+1)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n putStrLn =<< (show . solve) <$> getLine\n"}, {"source_code": "import Data.List\nsolve = p . (\\(x, y) -> (length x, length y)) . partition (== 'A')\np (a,d) | a > d = \"Anton\"\n | a < d = \"Danik\"\n | otherwise = \"Friendship\"\nmain = interact $ solve . (!! 1) . lines"}, {"source_code": "toint :: String -> Int\ntoint n = read n\n\nisA :: Char -> Int\nisA 'A' = 1\nisA 'D' = 0\n\ncount :: String -> Int\ncount [] = 0\ncount (x:xs) = isA x + count xs\n\nmain = do\n input <- getLine\n let n = toint input\n input <- getLine\n let s = input\n let a = count s\n b = n - a\n if a>b then \n putStrLn(\"Anton\")\n else if a (Int, Int) -> (Int, Int)\nisWinner [] acc = acc\nisWinner (x:xs) (a,b) = \n case x of\n 'A' -> isWinner xs (a + 1, b)\n 'D' -> isWinner xs (a, b + 1)\nresWin :: (Int, Int) -> String\nresWin (x,y)\n | (x > y) = \"Anton\"\n | (x == y) = \"Friendship\"\n | otherwise = \"Danik\"\nmain = do\n a <- getLine\n b <- getLine\n res <- return $ isWinner b (0,0)\n putStrLn $ resWin res"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n _ <- getLine\n line <- getLine\n let aCount = length $ filter (== 'A') line\n let dCount = length line - aCount\n if aCount > dCount\n then putStrLn \"Anton\"\n else if dCount > aCount then putStrLn \"Danik\" else putStrLn \"Friendship\"\n"}, {"source_code": "module Main where\n\nprocess :: (Ord a, Num a) => String -> a -> a -> String\nprocess [] aCount dCount | aCount > dCount = \"Anton\"\n | dCount > aCount = \"Danik\"\n | otherwise = \"Friendship\"\nprocess line aCount dCount\n | head line == 'A' = process (tail line) (aCount + 1) dCount\n | head line == 'D' = process (tail line) aCount (dCount + 1)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n line <- getLine\n putStrLn $ process line 0 0\n return ()\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n getLine\n line <- getLine\n let aCount = length $ filter (== 'A') line\n let dCount = length line - aCount\n putStrLn $ process aCount dCount\n where\n process aCount dCount | aCount > dCount = \"Anton\"\n | dCount > aCount = \"Danik\"\n | otherwise = \"Friendship\"\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n getLine\n line <- getLine\n let aCount = length $ filter (== 'A') line\n let dCount = length line - aCount\n if aCount > dCount\n then putStrLn \"Anton\"\n else if dCount > aCount then putStrLn \"Danik\" else putStrLn \"Friendship\"\n"}, {"source_code": "citesc_nr :: String -> Int\ncitesc_nr s = read s\nmain = do\n x <- getLine\n let n = (citesc_nr x) \n sir <- getLine\n let anton = length $ filter (== 'A') sir\n let danik = length $ filter (== 'D') sir\n putStrLn $ solve anton danik\nsolve x y \n | x==y = \"Friendship\"\n | x>y = \"Anton\"\n | otherwise = \"Danik\""}, {"source_code": "-- Codeforces Round #379 (Div. 2)\n-- http://codeforces.com/contest/734\n\n-- ID: 734A (Anton and Danik)\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n s <- getLine\n let anton = length $ filter (== 'A') s\n let danik = length $ filter (== 'D') s\n if anton == danik\n then putStrLn \"Friendship\"\n else if anton > danik\n then putStrLn \"Anton\"\n else putStrLn \"Danik\"\n"}, {"source_code": "module Main\n where\n\nimport System.IO\n\ncount ws =\n count' 0 0 ws\n where\n count' a d [] =\n (a, d)\n count' a d (w:ws) =\n if w == 'A' then\n count' (a + 1) d ws\n else\n count' a (d + 1) ws\n\nsolve ws =\n case count ws of\n (a, d) ->\n if a < d then\n \"Danik\"\n else if a == d then\n \"Friendship\"\n else\n \"Anton\"\n\nmain = do\n first <- getLine\n second <- getLine\n putStrLn $ solve second\n "}, {"source_code": "import Control.Monad\n\nsol :: String -> Int -> Int -> String\nsol [] a b = if (a > b) then \"Anton\"\n else if (b > a) then \"Danik\"\n else \"Friendship\"\n\nsol games one two = if (head games) == 'A'\n then (sol (tail games) (one + 1) two)\n else (sol (tail games) one (1 + two))\n\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n inputs <- getLine :: IO String\n putStrLn (sol inputs 0 0)\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\ts <- getLine\n\tlet\n\t\ta = f 'A' s\n\t\td = f 'D' s\n\tputStrLn $ solve a d\n\nf c = length . filter ( == c )\n\nsolve a d\n\t| a > d = \"Anton\"\n\t| a < d = \"Danik\"\n\t| otherwise = \"Friendship\"\n"}, {"source_code": "solve :: String -> String\nsolve games = if (length $ filter (\\x -> x == 'A') games) > (length $ filter (\\x -> x == 'D') games)\n then \"Anton\"\n else if (length $ filter (\\x -> x == 'A') games) < (length $ filter (\\x -> x == 'D') games)\n then \"Danik\"\n else \"Friendship\"\n\nmain :: IO ()\nmain = do\n games <- getLine\n games <- getLine\n\n putStrLn $ solve games"}, {"source_code": "f :: Integer -> Char -> Integer\nf t a =\n if a == 'A' then t + 1 else t - 1\n\nmain = do\n ni <- getLine\n let n = (read ni :: Integer)\n name <- getLine\n let ans = foldl f 0 name\n putStrLn (\n if ans < 0 then \"Danik\"\n else if ans > 0 then \"Anton\"\n else \"Friendship\")"}, {"source_code": "\nwhat a b\n | a > b = \"Anton\"\n | b > a = \"Danik\"\n | a == b = \"Friendship\"\n\nchess lst a d\n | (null lst) = what a d\n | (head lst) == 'A' = chess (tail lst) (a+1) d\n | (head lst) == 'D' = chess (tail lst) a (d+1)\n \n\nmain = do\n ss <- getLine\n ll <- getLine\n let ans = chess ll 0 0\n putStrLn ans\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: (Ord a) => a -> a -> String\nsolve x y\n | x > y = \"Anton\"\n | x < y = \"Danik\"\n | x == y = \"Friendship\"\n\ncount :: (Eq a) => a -> [a] -> Int\ncount c = length . filter (== c)\n\nmain :: IO ()\nmain = do\n n <- getLine\n s <- getLine\n let countA = count 'A' s\n countD = count 'D' s\n putStrLn $ solve countA countD"}, {"source_code": "main = do\n c <- getContents\n let lns = lines c\n let s = lns!!1\n let a = [ x | x <- s, x == 'A']\n let d = [ x | x <- s, x == 'D']\n let cmp = (length a) `compare` (length d)\n case cmp of\n LT -> putStrLn \"Danik\"\n EQ -> putStrLn \"Friendship\"\n _ -> putStrLn \"Anton\""}, {"source_code": "tores (a,b)\n | a==b = \"Friendship\"\n | a>b = \"Anton\"\n | a ds then putStrLn \"Anton\"\n else if as < ds then putStrLn \"Danik\"\n else putStrLn \"Friendship\"\n"}, {"source_code": "import System.IO\n\nsolve :: String -> String\nsolve s =\n let a = length $ filter (=='A') s\n d = length $ filter (=='D') s\n in case a `compare` d of\n GT -> \"Anton\"\n EQ -> \"Friendship\"\n LT -> \"Danik\"\n\nmain = do\n getLine\n putStrLn =<< solve <$> getLine\n"}, {"source_code": "countLetters :: String -> Char -> Int\ncountLetters str c = length $ filter (== c) str\n\nsolve :: String -> String\nsolve str | a > d = \"Anton\"\n | a < d = \"Danik\"\n | otherwise = \"Friendship\"\n where\n a = countLetters str 'A'\n d = length str - a\n\nmain :: IO ()\nmain = do\n _ <- getLine\n str <- getLine\n putStrLn $ solve str\n"}, {"source_code": "module Main(main) where\n\nsolve a d = case compare a d of\n GT -> \"Anton\"\n EQ -> \"Friendship\"\n LT -> \"Danik\"\n\nmain :: IO()\nmain = do\n c <- getLine\n s <- getLine\n let (a, d) = foldl (\\(a, d) l -> if l == 'A' then (a+1, d) else (a, d+1)) (0, 0) s\n putStrLn $ solve a d\n"}, {"source_code": "countLetters :: String -> Char -> Int\ncountLetters str c = length $ filter (== c) str\n\nsolve :: String -> String\nsolve str = case compare (countLetters str 'A') (countLetters str 'D') of\n GT -> \"Anton\"\n EQ -> \"Friendship\"\n LT -> \"Danik\"\n\nmain :: IO ()\nmain = do\n _ <- getLine\n str <- getLine\n putStrLn $ solve str\n"}, {"source_code": "module Main(main) where\n\n\nt x y = case compare x y of\n GT -> \"Anton\"\n EQ -> \"Friendship\"\n LT -> \"Danik\"\n\n\nmain :: IO()\nmain = do\n c <- getLine\n s <- getLine\n let (x, y) = foldl (\\(x, y) l -> if l == 'A' then (x+1, y)\n else (x, y+1)) (0, 0) s\n putStrLn (t x y)\n"}, {"source_code": "winner :: Int -> String\nwinner a\n | a > 0 = \"Anton\"\n | a < 0 = \"Danik\"\n | otherwise = \"Friendship\"\n\nprocess :: [Char] -> String\nprocess source =\n let count = sum $ map(\\x -> if x == 'A' then 1 else -1) source\n in winner count\n\nmain :: IO()\nmain = do\n number <- getLine\n source <- getLine\n let result = process source\n putStrLn result "}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.concat. tail. take 2 . lines\nsolve :: String->String\nsolve xs | an>da =\"Anton\"\n | an if a=='A' then [b1+1,b2] else [b1,b2+1]) [0,0] xs"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ decide . head . tail .words\n\ndecide :: String -> String\ndecide s\n | aw > dw = \"Anton\"\n | aw < dw = \"Danik\"\n | otherwise = \"Friendship\"\n where (a, d) = partition (=='A') s\n aw = length a\n dw = length d"}, {"source_code": "solve s | a > d = \"Anton\"\n | a < d = \"Danik\"\n | otherwise = \"Friendship\"\n where\n a = length $ filter (=='A') s\n d = length $ filter (=='D') s\n\nmain = do\n n <- readLn :: IO Int\n s <- getLine\n putStrLn $ solve s\n"}, {"source_code": "{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\n\ntype N = Integer\ntoNum = toInte\n\nanswer :: String -> String\nanswer xs = case go xs of\n (x, y) | x > y -> \"Anton\"\n | x < y -> \"Danik\"\n | otherwise -> \"Friendship\"\n where go = foldl' doOne (0,0)\n doOne (x, y) c\n | c == 'A' = let x' = x + 1 in x' `seq` (x',y)\n | otherwise = let y' = y + 1 in y' `seq` (x, y')\n\nhandleInput :: ByteString -> ByteString\nhandleInput = lines\n & coerceInput answer\n & pack\n -- & map (show & pack) & unlines\n\ntoInt = readInt & fromJust & fst\ntoInte = readInteger & fromJust & fst\ntoX :: Read a => ByteString -> a\ntoX = unpack & read\n\ncoerceInput f (a:b:xs) = f (take (toInt a) (unpack b))\ncoerceInput _ _ = error \"invalid input\"\n\nmain :: IO ()\nmain = interact handleInput\n\n-- Util stuff --\n(&) :: (a -> b) -> (b -> c) -> a -> c\n(&) = flip (.)\ninfixl 9 &\n"}, {"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.List.Split\nimport Control.Monad\n\n--\n-- {-\n-- 96A Football\n-- =================================\n-- -}\n-- isPrefixOf' [] _ = True\n-- isPrefixOf' _ [] = False\n-- isPrefixOf' (x:xs) (y:ys) = x == y && isPrefixOf' xs ys\n--\n-- --any'' p = or . map p\n--\n-- --any' _ [] = False\n-- --any' p (x:xs) = p x || any' p xs\n--\n-- --tails' :: [a] -> [[a]]\n-- --tails' [] = []\n-- --tails' (x:xs) = (x:xs) : tails' xs\n--\n-- --isInfixOf' :: Eq a => [a] -> [a] -> Bool\n-- --isInfixOf' xs ys = any' (isPrefixOf xs) (tails' ys)\n--\n-- --football xs\n-- -- | isInfixOf' \"0000000\" xs || isInfixOf' \"1111111\" xs = \"YES\"\n-- -- | otherwise = \"NO\"\n--\n--\n-- {-\n-- 208A Dubstep\n-- =================================\n-- -}\n-- -- replace = map (\\c -> if c == \"\" then \" \" else c)\n-- -- replace1 = map (\\c -> if c == \"WUB\" then \" \" else c)\n-- -- removeSpaces [] = []\n-- -- removeSpaces (x:xs)\n-- -- | x == \" \" = removeSpaces xs\n-- -- | otherwise = x:xs\n--\n-- {-\n-- 59A Word\n-- =================================\n-- -}\n--\n-- countU [] = 0\n-- countU (x:xs)\n-- | isUpper x == True = countU xs + 1\n-- | otherwise = countU xs\n--\n-- countL [] = 0\n-- countL (x:xs)\n-- | isLower x == True = countL xs + 1\n-- | otherwise = countL xs\n--\n-- word xs\n-- | countL xs >= countU xs = map (toLower) xs\n-- | otherwise = map (toUpper) xs\n--\n\npangram xs\n | (==26) (length (nub (map (toLower) xs))) = \"YES\"\n | otherwise = \"NO\"\n\ncountA :: String -> Int\ncountA [] = 0\ncountA (x:xs)\n | x == 'A' = countA xs + 1\n | otherwise = countA xs\n\ncountD :: String -> Int\ncountD [] = 0\ncountD (x:xs)\n | x == 'D' = countD xs + 1\n | otherwise = countD xs\n\nantonAndDanik xs\n | countA xs > countD xs = \"Anton\"\n | countA xs < countD xs = \"Danik\"\n | otherwise = \"Friendship\"\n\nmain = interact$antonAndDanik\n"}, {"source_code": "import Control.Applicative\n\nsolve :: String -> String\nsolve a\n | as < bs = \"Danik\"\n | bs < as = \"Anton\"\n | otherwise = \"Friendship\"\n where f l = length $ filter (==l) a\n as = f 'A'\n bs = f 'D'\n\nmain = do\n getLine\n l <- getLine\n putStrLn $ solve l\n"}, {"source_code": "{-#LANGUAGE OverloadedStrings#-}\nmodule Main where\n\nimport Data.Text (pack, unpack, splitOn)\n\nmain :: IO ()\nmain = do\n [n] <- getInt\n str <- getLine\n putStrLn (solve n str)\n\ngetInt :: IO [Int]\ngetInt = fmap (map (read . unpack) \n . splitOn \" \" . pack) getLine\n\nsolve :: Int -> String -> String\nsolve tot str\n | tot < a * 2 = \"Anton\"\n | tot > a * 2 = \"Danik\"\n | otherwise = \"Friendship\"\n where\n a :: Int\n a = foldr (\\c ac -> \n if c == 'A' then ac + 1\n else ac) 0 str"}, {"source_code": "import Control.Monad\n\nmain = readInput >>= putStrLn . decide\n\nanton = \"Anton\"\ndanik = \"Danik\"\ntie = \"Friendship\"\n\nreadInput :: IO (Int, String)\nreadInput = liftM2 toTuple getLine getLine\n where toTuple a b = (read a, b)\n \ndecide :: (Int, String) -> String\ndecide (n, winners) = decide' winners 0 0\n where decide' [] a d\n | a == d = tie\n | a < d = danik\n | otherwise = anton\n decide' (x:xs) a d\n | half < a = anton\n | half < d = danik\n | otherwise = case x of\n 'A' -> decide' xs (a + 1) d\n _ -> decide' xs a (d + 1)\n half = div n 2\n"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nsolve :: Int -> Int -> String\nsolve countA countD\n | countA > countD = \"Anton\"\n | countA < countD = \"Danik\"\n | otherwise = \"Friendship\"\n\nmain :: IO ()\nmain = do\n getLine\n history <- getLine\n let countA = length . filter (== 'A') $ history\n countD = length . filter (== 'D') $ history\n printf \"%s\" $ solve countA countD"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: String -> Int -> String\nprocess plays n = let anton = length $ filter (== 'A') plays in\n case compare anton (n - anton) of\n LT -> \"Danik\"\n EQ -> \"Friendship\"\n GT -> \"Anton\"\n\nmain = do\n n <- getInt\n plays <- getLine\n putStrLn $ process plays n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: (Ord a) => a -> a -> String\nsolve x y\n | x > y = \"Anton\"\n | x < y = \"Danik\"\n | x == y = \"Friendship\"\n\ncount :: (Eq a) => a -> [a] -> Int\ncount c = length . filter (== c)\n\nmain :: IO ()\nmain = do\n n <- getLine\n s <- getLine\n let countA = count 'A' s\n countD = count 'D' s\n print $ solve countA countD"}, {"source_code": "import System.IO\n\nsolve :: String -> String\nsolve s =\n let a = length $ filter (=='A') s\n d = length $ filter (=='D') s\n in case a `compare` d of\n LT -> \"Anton\"\n EQ -> \"Friendship\"\n GT -> \"Danik\"\n\nmain = do\n getLine\n putStrLn =<< solve <$> getLine\n"}, {"source_code": "import Control.Applicative\n\nsolve :: String -> String\nsolve a\n | as < bs = \"Danik\"\n | bs < as = \"Anton\"\n | otherwise = \"Friendship\"\n where f l = length $ filter (==l) a\n as = f 'A'\n bs = f 'B'\n\nmain = do\n getLine\n l <- getLine\n putStrLn $ solve l\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\nmain=do\n n<- read <$> getLine ::IO Int\n a<- getLine\n let b = length $ filter (=='A') a\n putStrLn $ if b > n-b then \"Anton\" else \"Danik\"\n"}, {"source_code": "import System.Environment\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n [_, s] <- replicateM 2 getLine\n let as = length $ filter (=='A') s\n let ds = length $ filter (=='D') s\n if as > ds then print \"Anton\"\n else if as < ds then print \"Danik\"\n else print \"Friendship\"\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ f . (\\(_:x:_) -> x) . words\n\nf :: String -> String\nf xs | length (filter (=='D') xs) *2 > length xs = \"Danik\"\n | length (filter (=='D') xs) *2 < length xs = \"Anton\"\n | otherwise = \"Frendship\"\n"}], "src_uid": "0de32a7ccb08538a8d88239245cef50b"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad ( replicateM, replicateM_ )\nimport Data.List ( sort, foldl' ) --'\nimport Data.Array\nimport Data.Int (Int64)\n\ntype Graph = Array Int [Int]\n\nsubtreeSizes :: Graph -> Int -> (Int, [Int]) -> Int -> (Int, [Int])\nsubtreeSizes g !par (!tot, ss) !v = let\n children = filter (/= par) (g ! v)\n (ownSize, res) = foldl' {-'-} (subtreeSizes g v) (1, ss) children\n in (tot + ownSize, ownSize : res)\n\neVal :: Int -> Int -> Int64\neVal totSize subSize = let\n ts = fromIntegral totSize\n ss = fromIntegral subSize\n in (ts - ss) * ss\n\nmodVal :: Int64\nmodVal = 10^(9::Int) + 7;\n\ntrim :: Int -> [Int64] -> [Int64]\ntrim k li = case li of\n v1 : v2 : xs | k > 0 ->\n let\n nv = rem (v1*v2) modVal\n in seq nv $ trim (k-1) (nv : xs)\n _ -> li\n\nreduce :: [(Int64, Int64)] -> Int64\nreduce = foldl' step 0 where --'\n step s (x,y) = rem (s + x*y) modVal\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n edges <- replicateM (n-1) $ do\n [u, v] <- map read . words <$> getLine\n pure [(u, v), (v,u)]\n let\n g = accumArray (flip (:)) [] (1, n) $ concat edges\n (ec, subSizes) = foldl' {-'-} (subtreeSizes g 1) (1, []) (g ! 1)\n eVals = reverse . sort $ map (eVal n) subSizes\n if ec /= n then putStrLn \"yikes\" else pure ()\n m <- read <$> getLine\n factors <- map read . words <$> getLine :: IO [Int64]\n let labels = trim (m - (n-1)) (reverse $ sort factors) ++ repeat 1\n --putStrLn \"labels, eVals:\"\n --print $ zip labels eVals\n --putStrLn \"answer:\"\n print $ reduce (zip eVals labels)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\nimport Data.Int\n\ntype Graph = Array Int [Int]\n\nsubtreeSizes :: Graph -> Int -> (Int, [Int]) -> Int -> (Int, [Int])\nsubtreeSizes g !par (!tot, ss) !v = let\n children = filter (/= par) (g ! v)\n (ownSize, res) = foldl' (subtreeSizes g v) (1, ss) children\n in (tot + ownSize, ownSize : res)\n\neVal :: Int -> Int -> Int64\neVal totSize subSize = let\n ts = fromIntegral totSize\n ss = fromIntegral subSize\n in (ts - ss) * ss\n\nmodVal :: Int64\nmodVal = 10^(9::Int) + 7;\n\ntrim :: Int -> [Int64] -> [Int64]\ntrim k li = case li of\n v1 : v2 : xs | k > 0 ->\n let\n nv = rem (v1*v2) modVal\n in seq nv $ trim (k-1) (nv : xs)\n _ -> li\n\nreduce :: [(Int64, Int64)] -> Int64\nreduce = foldl' step 0 where\n step s (x,y) = rem (s + x*y) modVal\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n n <- read <$> getLine\n edges <- replicateM (n-1) $ do\n [u, v] <- map read . words <$> getLine\n pure [(u, v), (v,u)]\n m <- read <$> getLine\n factors <- map read . words <$> getLine :: IO [Int64]\n let\n g = accumArray (flip (:)) [] (1, n) $ concat edges\n (_, subSizes) = foldl' (subtreeSizes g 1) (1, []) (g ! 1)\n eVals = reverse . sort $ map (eVal n) subSizes\n labels = trim (m - (n-1)) (reverse $ sort factors) ++ repeat 1\n print $ reduce (zip eVals labels)\n"}], "negative_code": [], "src_uid": "968b3db21bd16bc04bdb355e98079d5d"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}, {"source_code": "import Data.Int (Int64)\n\nbestpin [] _ _ = 1000000000000000::Int64\nbestpin ((dpr,dpwp,dpx):dptail) sx nx = min (sx - nx * dpx + dpwp) (bestpin dptail (sx + dpx) (nx + 1))\n\nsolve [] [] = 0\nsolve [] ((c,x):cxtail) = solve [(c,c,x)] cxtail\nsolve ((dpr,dpwp,dpx):dptail) [] = dpr\n\nsolve ((dpr,dpwp,dpx):dptail) ((c,x):cxtail) =\n let score_withpin = dpr + c\n score_nopin = bestpin ((dpr,dpwp,dpx):dptail) x 1\n in solve (((min score_withpin score_nopin),score_withpin,x):((dpr,dpwp,dpx):dptail)) cxtail\n\nmergetwo [] ys = ys\nmergetwo xs [] = xs\nmergetwo ((cx,xx):xs) ((cy,xy):ys) = if xx <= xy then\n ((cx,xx):(mergetwo xs ((cy,xy):ys))) else\n ((cy,xy):(mergetwo ((cx,xx):xs) ys))\n\nmergesort [] = []\nmergesort [t] = [t]\nmergesort cxs =\n let n = length cxs\n n2 = n `div` 2\n leftSide = take n2 cxs\n rightSide = drop n2 cxs\n in mergetwo (mergesort leftSide) (mergesort rightSide)\n\nreadNPairs 0 = return []\nreadNPairs n = do\n [x,c] <- fmap ( (map (\\x -> read x::Int64)) . words ) getLine\n rest <- readNPairs (n - 1)\n return ((c,x):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- readNPairs n\n print $ solve [] (mergesort v)\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) (0::Int64) $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromIntegral n) getA\n\tputStrLn $ show $ head $ gao $ sort a\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\ngao [] = [0]\ngao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where\n\ts = gao r\n\td = scanl (+) 0 $ map (subtract x . head) r\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM n getA\n\tputStrLn $ show $ head $ gao $ sort a\n"}, {"source_code": "bestpin [] _ _ = 1000000000::Int\nbestpin ((dpr,dpwp,dpx):dptail) sx nx = min (sx - nx * dpx + dpwp) (bestpin dptail (sx + dpx) (nx + 1))\n\nsolve [] [] = 0\nsolve [] ((c,x):cxtail) = solve [(c,c,x)] cxtail\nsolve ((dpr,dpwp,dpx):dptail) [] = dpr\n\nsolve ((dpr,dpwp,dpx):dptail) ((c,x):cxtail) =\n let score_withpin = dpr + c\n score_nopin = bestpin ((dpr,dpwp,dpx):dptail) x 1\n in solve (((min score_withpin score_nopin),score_withpin,x):((dpr,dpwp,dpx):dptail)) cxtail\n\nmergetwo [] ys = ys\nmergetwo xs [] = xs\nmergetwo ((cx,xx):xs) ((cy,xy):ys) = if xx <= xy then\n ((cx,xx):(mergetwo xs ((cy,xy):ys))) else\n ((cy,xy):(mergetwo ((cx,xx):xs) ys))\n\nmergesort [] = []\nmergesort [t] = [t]\nmergesort cxs =\n let n = length cxs\n n2 = n `div` 2\n leftSide = take n2 cxs\n rightSide = drop n2 cxs\n in mergetwo (mergesort leftSide) (mergesort rightSide)\n\nreadNPairs 0 = return []\nreadNPairs n = do\n [x,c] <- fmap ( (map (\\x -> read x::Int)) . words ) getLine\n rest <- readNPairs (n - 1)\n return ((c,x):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- readNPairs n\n print $ solve [] (mergesort v)\n"}, {"source_code": "bestpin [] _ _ = 1000000000000000::Int\nbestpin ((dpr,dpwp,dpx):dptail) sx nx = min (sx - nx * dpx + dpwp) (bestpin dptail (sx + dpx) (nx + 1))\n\nsolve [] [] = 0\nsolve [] ((c,x):cxtail) = solve [(c,c,x)] cxtail\nsolve ((dpr,dpwp,dpx):dptail) [] = dpr\n\nsolve ((dpr,dpwp,dpx):dptail) ((c,x):cxtail) =\n let score_withpin = dpr + c\n score_nopin = bestpin ((dpr,dpwp,dpx):dptail) x 1\n in solve (((min score_withpin score_nopin),score_withpin,x):((dpr,dpwp,dpx):dptail)) cxtail\n\nmergetwo [] ys = ys\nmergetwo xs [] = xs\nmergetwo ((cx,xx):xs) ((cy,xy):ys) = if xx <= xy then\n ((cx,xx):(mergetwo xs ((cy,xy):ys))) else\n ((cy,xy):(mergetwo ((cx,xx):xs) ys))\n\nmergesort [] = []\nmergesort [t] = [t]\nmergesort cxs =\n let n = length cxs\n n2 = n `div` 2\n leftSide = take n2 cxs\n rightSide = drop n2 cxs\n in mergetwo (mergesort leftSide) (mergesort rightSide)\n\nreadNPairs 0 = return []\nreadNPairs n = do\n [x,c] <- fmap ( (map (\\x -> read x::Int)) . words ) getLine\n rest <- readNPairs (n - 1)\n return ((c,x):rest)\n\nmain = do\n n <- readLn::IO Int\n v <- readNPairs n\n print $ solve [] (mergesort v)\n"}], "src_uid": "334d2bcb32d88a7037bcf262f49938cf"} {"source_code": "import Control.Applicative\n\nmain = do\n (n:k:_) <- (return.map read.words =<< getLine :: IO [Int])\n pairs <- gets n\n putStrLn.show $ answer k $ foldl add 0 pairs\n\nadd :: Int -> (Int,Int) -> Int\nadd v (l,r) = v+r-l+1\n\nanswer :: Int -> Int -> Int\nanswer k x\n | x `mod` k == 0 = 0\n | k > x = k - x\n | k < x = k - (mod x k)\n\ngets :: Int -> IO [(Int,Int)]\ngets 0 = return []\ngets n = do\n (l:r:_) <- (return.map read.words =<< getLine :: IO [Int])\n ((l,r):) <$> gets (n-1)", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do\n [n,k] <- map read . words <$> getLine\n l <-replicateM n ((\\[x,y] -> y-x+1) . map read . words <$> getLine)\n let x = sum l `mod`k\n print $ if x == 0 then 0 else k - x\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nmain = do\n [n,k] <- map (fromMaybe 0. fmap fst . B.readInt) . B.words <$> B.getLine\n l <-replicateM n ((\\[x,y] -> y-x+1) . map (fromMaybe 0 . fmap fst . B.readInt) . B.words <$> B.getLine)\n let x = sum l `mod`k\n print $ if x == 0 then 0 else k - x\n"}, {"source_code": "import Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact $ showBI . rd . B.lines\n\nrd (nk:qs) = go (readBI . last . B.words $ nk) (map (map readBI . B.words) qs)\ngo :: Int -> [[Int]] -> Int\ngo k qs = (\\x -> if x==k then 0 else x) . (`subtract`k) . (`mod`k) . sum $ map (\\(l:r:[]) -> r-l+1) qs\n\nshowBI :: Int -> B.ByteString\nshowBI = B.pack . show\n\nreadBI :: B.ByteString -> Int\nreadBI = fst . fromJust . B.readInt\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array (Array, (!), array, bounds)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: Int -> [[Int]] -> Int\nsolve k as = (k - s `mod` k) `mod` k\n where\n s = sum [r - l + 1 | [l, r] <- as]\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- replicateM n reads\n print $ solve k as\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getContents\n print $ solve k xs\n\nsolve k xs = go 0 xs\n where\n go !acc (l:r:rest) = go (acc+r-l+1) rest\n go acc _ = if r==0 then 0 else k-r\n where\n r = acc`mod`k"}], "negative_code": [{"source_code": "import Control.Applicative\n\nmain = do\n (n:k:_) <- (return.map read.words =<< getLine :: IO [Int])\n pairs <- gets n\n putStrLn.show $ answer k $ foldl add 0 pairs\n\nadd :: Int -> (Int,Int) -> Int\nadd v (l,r) = v+r-l+1\n\nanswer :: Int -> Int -> Int\nanswer k x\n | k `mod` x == 0 = 0\n | k > x = k - x\n | k < x = k - (mod x k)\n\ngets :: Int -> IO [(Int,Int)]\ngets 0 = return []\ngets n = do\n (l:r:_) <- (return.map read.words =<< getLine :: IO [Int])\n ((l,r):) <$> gets (n-1)"}, {"source_code": "import Control.Applicative\n\nmain = do\n (n:k:_) <- (return.map read.words =<< getLine :: IO [Int])\n pairs <- gets n\n putStrLn.show $ answer k $ foldl add 0 pairs\n\nadd :: Int -> (Int,Int) -> Int\nadd v (l,r) = v+r-l+1\n\nanswer :: Int -> Int -> Int\nanswer k x\n | k == x = 0\n | k > x = k - x\n | k < x = k - (mod x k)\n\ngets :: Int -> IO [(Int,Int)]\ngets 0 = return []\ngets n = do\n (l:r:_) <- (return.map read.words =<< getLine :: IO [Int])\n ((l,r):) <$> gets (n-1)"}], "src_uid": "3a93a6f78b41cbb43c616f20beee288d"} {"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve _ [] = []\nsolve ls (a:as) = (ls !! aa) : (solve ((drop (aa+1) ls) ++ (take aa ls)) as)\n where\n aa = mod a $ length ls\n\nmain = do\n [n,k] <- map read <$> words <$> getLine\n a <- map read <$> words <$> getLine\n putStrLn $ concat $ intersperse \" \" $ map show $ solve [1..n] a\n", "positive_code": [{"source_code": "main :: IO ()\nmain = interact mf\n\nmf :: String -> String\nmf t =\n let [[n, _], b] = map (map read . words) $ lines t\n in unwords $ map show $ step 1 n [1..n] b\n\ndelAt :: [a] -> Int -> [a]\ndelAt s i =\n let (ys,zs) = splitAt i s\n in ys ++ tail zs\n\nstep ::Int -> Int -> [Int] -> [Int] -> [Int]\nstep _ _ _ [] = []\nstep i n cs (a:as)\n |i > n = step (i - n) n cs (a:as)\n |(a + i) `mod` n == 0 =\n last cs : step 1 (n-1) (init cs) as\n |otherwise =\n let ri = (a + i) `mod` n\n el = cs !! (ri - 1)\n in el : step ri (n-1) (delAt cs (ri-1)) as\n"}, {"source_code": "main :: IO ()\nmain = do\n fl <- getLine\n sl <- getLine\n let [n, _] = map read $ words fl\n let b = map read $ words sl\n putStrLn $ unwords $ map show $ step 1 n [1..n] b\n\nmf :: String -> String\nmf t =\n let [x, y] = map words $ lines t\n [n, _] = map read x\n b = map read y\n in unwords $ map show $ step 1 n [1..n] b\n\ndelAt :: [a] -> Int -> [a]\ndelAt s i =\n let (ys,zs) = splitAt i s\n in ys ++ tail zs\n\nstep ::Int -> Int -> [Int] -> [Int] -> [Int]\nstep _ _ _ [] = []\nstep i n cs (a:as)\n |i > n = step (i - n) n cs (a:as)\n |(a + i) `mod` n == 0 = \n last cs : step 1 (n-1) (init cs) as\n |otherwise =\n let ri = (a + i) `mod` n\n el = cs !! (ri - 1)\n in el : step ri (n-1) (delAt cs (ri-1)) as\nstep i n cs as = error $ show (i,n, cs, as)\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = putStrLn . unwords . map show . solve . map read . words =<< getContents\n\nsolve :: [Int] -> [Int]\nsolve (n:_:a) = solve' n [1..n] a\n\nsolve' :: Int -> [Int] -> [Int] -> [Int]\nsolve' _ _ [] = []\nsolve' n q (a:ax) = let (rear, front) = splitAt (a `mod` n) q\n in if null front\n then head rear : solve' (n - 1) (tail rear) ax\n else head front : solve' (n - 1) (tail front ++ rear) ax\n"}, {"source_code": "{-# OPTIONS_GHC -fno-warn-tabs #-}\nimport Data.List;\nimport System.IO;\nimport Data.Maybe;\n\nprintOrder :: [Int] -> IO ();\nprintOrder n = do\n\tprint(head n);\n\tif(length (tail n) > 0) then printOrder(tail n) else return();\n\nchildOut :: Int -> Int -> Int -> [Int] -> [Int] -> [Int] -> [Int];\nchildOut i n curCh ch stps fin\n\t| i == n = fin\n\t| otherwise = childOut (i+1) n (if chosen == (length usingNextCh) then 0 else chosen) usingNextCh stps ((ch!!chosen):fin) where\n\t\tchosen = if((curCh + stps!!i) >= length ch) then (curCh + stps!!i) `mod` (length ch) else (curCh + stps!!i)\n\t\tusingNextCh = take chosen ch ++ drop (chosen + 1) ch;\n\nmain = do\n\tstr0 <- getLine;\n\tstr1 <- getLine;\n\tlet ns0 = map (read :: String -> Int) (words str0);\n\tlet childn = [1..ns0!!0];\n\tlet stepsCount = ns0!!1;\n\tlet steps = map (read :: String -> Int) (words str1);\n\tlet childOutOrder = childOut 0 stepsCount 0 childn steps [];\n\tprintOrder(reverse childOutOrder);"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nnextInt :: ByteString -> Int\nnextInt = fst . fromJust . C.readInt\n\nsolve :: [Int] -> [Int]\nsolve (n : _ : xs) = solve' n xs [1..n]\n\nsolve' :: Int -> [Int] -> [Int] -> [Int]\nsolve' _ [] _ = []\nsolve' n (x:xs) k =\n let (mae, ushiro) = splitAt (x `mod` n) k\n in if null ushiro\n then head mae : solve' (n - 1) xs (tail mae)\n else head ushiro : solve' (n - 1) xs (tail ushiro ++ mae)\n\nmain = do\n (map nextInt . C.words -> xs) <- B.getContents\n putStrLn $ unwords $ map show (solve xs)"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.List (intercalate, delete)\n\nreadint = fst. fromJust . C.readInt\n\nrun gs (x:xs) i = (gs !! y):run gs' xs y\n where y = (x + i) `mod` (length gs)\n gs' = delete (gs !! y) gs\nrun _ [] _ = []\n\nmain = do\n (map readint . C.words -> [n, k]) <- B.getLine\n (map readint . C.words -> xs) <- B.getLine\n putStrLn $ intercalate \" \" $ map show (run [1..n] xs 0)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve _ [] = []\nsolve ls (a:as) = (ls !! aa) : (solve ((drop (aa+1) ls) ++ (take aa ls)) as)\n where\n aa = mod a $ length ls\n\nmain = do\n [n,k] <- map read <$> words <$> getLine\n a <- map read <$> words <$> getLine\n putStrLn $ intersperse ' ' $ concat $ map show $ solve [1..n] a\n"}], "src_uid": "5512fbe2963dab982a58a14daf805291"} {"source_code": "import Data.Functor\n\nmain = do\n [_,_,k] <- map (pred.read).words <$> getLine\n p <- getLine\n op <- getLine\n\n let (a,b) = foldl solve (reverse $ take k p, drop k p) op\n putStrLn $ reverse a ++ b\n\nsolve (x:l,r) 'L' = (l, x:r)\nsolve (l,x:r) 'R' = (x:l, r)\nsolve (l,'(':r) 'D' = bounds (l, rm r 1)\nsolve (l,')':r) 'D' = bounds (rm l (0-1), r)\nbounds (x:l,[]) = (l,[x])\nbounds a = a\n\nrm s 0 = s\nrm (')':s) b = rm s (b - 1)\nrm ('(':s) b = rm s (b + 1)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Functor\n\nmain :: IO()\nmain = do\n [_, _, k] <- map read . words <$> getLine\n brackets <- getLine\n operations <- getLine\n let (left, right) = splitAt (k - 1) brackets\n (remLeft, remRight) = foldl solve (reverse left, right) operations\n putStrLn $ reverse remLeft ++ remRight\n\nsolve :: (String, String) -> Char -> (String, String)\nsolve (l:lx, r) 'L' = (lx, l:r)\nsolve (l, r:rx) 'R' = (r:l, rx)\nsolve (l, '(':rx) 'D' = recover (l, remove rx 1)\nsolve (l, ')':rx) 'D' = recover (remove l (-1), rx)\n\nremove :: String -> Int -> String\nremove s 0 = s\nremove ('(':sx) sum = remove sx (sum + 1)\nremove (')':sx) sum = remove sx (sum - 1)\n\nrecover :: (String, String) -> (String, String)\nrecover (l:lx, []) = (lx, [l])\nrecover x = x\n"}, {"source_code": "import Data.Functor\n\nmain = do\n [_,_,k] <- map (pred.read).words <$> getLine\n p <- getLine\n op <- getLine\n\n let (a,b) = foldl solve (reverse $ take k p, drop k p) op\n putStrLn $ reverse a ++ b\n\nsolve (x:l,r) 'L' = (l, x:r)\nsolve (l,x:r) 'R' = (x:l, r)\nsolve (l,'(':r) 'D' = bounds (l, rm r 1)\nsolve (l,')':r) 'D' = bounds (rm l (0-1), r)\nbounds (x:l,[]) = (l,[x])\nbounds a = a\n\nrm s 0 = s\nrm (')':s) b = rm s (b - 1)\nrm ('(':s) b = rm s (b + 1)\n\n"}], "negative_code": [], "src_uid": "cf1c39e85eded68515aae9eceac73313"} {"source_code": "\nsolve [\"front\", \"1\"] = \"L\"\nsolve [\"front\", \"2\"] = \"R\"\nsolve [\"back\", \"1\"] = \"R\"\nsolve [\"back\", \"2\"] = \"L\"\n\nmain = do text <- readFile \"input.txt\"\n writeFile \"output.txt\" (solve $ words text)", "positive_code": [{"source_code": "import System.IO\n\nmain = do\n\thin<-openFile \"input.txt\" ReadMode \n\thout<-openFile \"output.txt\" WriteMode\n\tdoor<-hGetLine hin\n\thandrail<-hGetLine hin\n\thPutStrLn hout (solve door (read handrail)) \n\thClose hout\n\thClose hin\n\n\nsolve \"front\" 1 = \"L\"\nsolve \"back\" 2 = \"L\"\nsolve \"front\" 2 = \"R\"\nsolve \"back\" 1 = \"R\"\n"}, {"source_code": "main = readFile \"input.txt\" >>= writeFile \"output.txt\" . (\\[d, r] -> if d == r then \"L\\n\" else \"R\\n\") . map ((==\"1\") . f) . lines\n\twhere f \"front\" = \"1\"; f x = x\n"}, {"source_code": "solve [\"front\",\"1\"] = \"L\"\nsolve [\"front\",\"2\"] = \"R\"\nsolve [\"back\", \"1\"] = \"R\"\nsolve [\"back\", \"2\"] = \"L\"\n\nmain = readFile \"input.txt\" >>= writeFile \"output.txt\" . solve . words \n"}, {"source_code": "#! /usr/bin/runhaskell\nmain = do\n file <- readFile \"input.txt\"\n writeFile \"output.txt\" (f file)\n\nf file =\n if (hstr == \"front\" && lstr == \"1\") || (hstr == \"back\" && lstr == \"2\")\n then \"L\\n\"\n else \"R\\n\"\n where str = words file\n hstr = head str\n lstr = last str\n"}, {"source_code": "\nimport IO\n\nsolve :: String -> Int -> String\nsolve \"front\" 1 = \"L\"\nsolve \"front\" 2 = \"R\"\nsolve \"back\" 1 = \"R\"\nsolve \"back\" 2 = \"L\"\nsolve _ _ = error \"...\"\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n \n d <- hGetLine hInput\n n <- hGetLine hInput >>= return . read \n hPutStrLn hOutput (solve d n)\n \n hClose hOutput\n hClose hInput\n"}, {"source_code": "\nsolve [\"front\", \"1\"] = \"L\"\nsolve [\"front\", \"2\"] = \"R\"\nsolve [\"back\", \"1\"] = \"R\"\nsolve [\"back\", \"2\"] = \"L\"\n\nmain = do text <- readFile \"input.txt\"\n writeFile \"output.txt\" (solve $ words text)"}], "negative_code": [{"source_code": "import System.IO\n\nmain = do\n\thin<-openFile \"input.txt\" ReadMode \n\thout<-openFile \"output.txt\" WriteMode\n\tdoor<-hGetLine hin\n\thandrail<-hGetLine hin\n\thPutStrLn hout (solve door (read handrail)) \n\nsolve \"front\" 1 = \"L\"\nsolve \"back\" 2 = \"L\"\nsolve \"front\" 2 = \"R\"\nsolve \"back\" 1 = \"R\"\n"}], "src_uid": "77093f12ff56d5f404e9c87650d4aeb4"} {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\nimport qualified Data.Text as T\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\n\nimport qualified Control.Monad as M\n\nimport Data.Char\n\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- solution -}\n\nsolve :: Int -> String -> String\nsolve n str = reverse . solve' n $ reverse str\n where\n solve' :: Int -> String -> String\n solve' n str@('0':c1:c0:otherStr) | n >= 3 = decodeChars [c0, c1] : solve' (n - 3) otherStr\n solve' n str@(c:otherStr) = decodeChars [c] : solve' (n - 1) otherStr\n solve' 0 _ = []\n\n decodeChars :: String -> Char\n decodeChars [c] = chr $ decodeChar c + ord 'a' - 1\n decodeChars [c1, c0] = chr (10 * decodeChar c1 + decodeChar c0 + ord 'a' - 1)\n decodeChars _ = error \"\"\n\n decodeChar :: Char -> Int\n decodeChar c = ord c - ord '0'\n \n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n str <- B8.getLine <&> B8.unpack <&> (T.unpack . T.strip . T.pack)\n let answer = solve n str\n B8.putStrLn $ B8.pack answer\n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nreadI s | isOk = read s :: Int\r\n | otherwise = 1 -- debug\r\n where\r\n isOk = (== length s) . length . filter (<='9') . filter (>='0') $ s\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n _n <- getLine\r\n take 50 . filter (<='9') . filter (>='0') <$> getLine\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve s = map toC . L.reverse . f . L.reverse $ s\r\n where\r\n f [] = []\r\n f ('0':a:b:cs) = readI [b,a] : f cs\r\n f ( b:cs) = readI [b ] : f cs\r\n\r\n toC n | (1 <= n && n <= 26) = chr (ord 'a' + (n-1))\r\n | otherwise = 'a' -- debug\r\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.Char (ord, chr)\n\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >> getLine >>= putStrLn . reverse . decode . reverse\n\nec :: Int -> Char\nec c = chr ((ord 'a') + c - 1)\n\nc2d :: Char -> Int\nc2d c = (ord c) - (ord '0')\n\ndecode :: String -> String\ndecode ('0':b:a:rest) = (ec $ 10*(c2d a)+ (c2d b)) : decode rest\ndecode (a:rest) = ec (c2d a) : decode rest\ndecode [] = []\n"}], "negative_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n \r\nreadI s = read s :: Int\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n] <- ri\r\n getLine\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve s = L.reverse . f . L.reverse $ s\r\n where\r\n f [] = []\r\n f ('0':a:b:cs) = readI [b,a] : f cs\r\n f ( b:cs) = readI [b ] : f cs\r\n"}], "src_uid": "43081557fe2fbac39dd9b72b137b8fb0"} {"source_code": "pairUp :: [String] -> [(String, String)]\r\npairUp [] = []\r\npairUp (x : y : t) = (x, y) : pairUp t\r\n\r\ntoArr :: (Num a, Read a) => String -> [a]\r\ntoArr = map (read :: Read a => String -> a) . words\r\n\r\ntoSolveInp :: (String, String) -> (Integer, [Integer])\r\ntoSolveInp (s, t) = (k, p)\r\n where p = toArr t\r\n [_, k] = toArr s\r\n\r\ngo :: Integer -> Integer -> [Integer] -> Integer\r\ngo k acc [] = 0\r\ngo k acc (p : ps) = max 0 (leastAcc - acc) + go k (newAcc + p) ps\r\n where (d, m) = divMod (100 * p) k\r\n leastAcc = if m > 0 then d + 1 else d\r\n newAcc = max acc leastAcc\r\n\r\nsolve :: Integer -> [Integer] -> Integer\r\nsolve k (p : ps) = go k p ps\r\n\r\nmain :: IO ()\r\nmain = interact\r\n (unlines . map (show . uncurry solve . toSolveInp) . pairUp . tail . lines)\r\n", "positive_code": [{"source_code": "pairUp :: [String] -> [(String, String)]\r\npairUp [] = []\r\npairUp (x : y : t) = (x, y) : pairUp t\r\n\r\nsolve :: Integer -> [Integer] -> Integer\r\nsolve k (p : ps) = go p ps\r\n where go acc [] = 0\r\n go acc (p : ps) = max 0 (leastAcc - acc) + go (newAcc + p) ps\r\n where (d, m) = divMod (100 * p) k\r\n leastAcc = if m > 0 then d + 1 else d\r\n newAcc = max acc leastAcc\r\n\r\n-- p / acc <= k / 100\r\n-- 100 * p <= k * acc\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . uncurry solve . toInp) . pairUp . tail . lines)\r\n where toArr = map (read :: String -> Integer) . words\r\n toInp (s, t) = (k, p)\r\n where p = toArr t\r\n [n, k] = toArr s\r\n"}, {"source_code": "module Main where\n \nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as BS\n--import Debug.Trace\n \n--debug = flip trace\nreadx = fromInteger . fst . fromJust. BS.readInteger <$> BS.getLine\nreadxs = map (fromInteger . fst . fromJust. BS.readInteger) . BS.words <$> BS.getLine\n \nprintList :: Show a => [a] -> IO ()\nprintList [] = return ()\nprintList [a] = print a\nprintList (a:xs) = putStr (show a) >> putChar ' ' >> printList xs\n\nsolve :: Int64 -> Int64 -> [Int64] -> Int64\nsolve k = foldl func\n where func preSum x = preSum+x+needAdd\n where minPS = (100*x+k-1) `div` k\n needAdd = if minPS > preSum then minPS - preSum else 0\n\nmain :: IO()\nmain = do\n t <- readx\n replicateM_ t $ do\n (n:k:_) <- readxs\n (p0:p) <- readxs\n print $ solve k p0 p - p0 - sum p"}, {"source_code": "module Main where\n \nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as BS\n--import Debug.Trace\n \n--debug = flip trace\nreadx = fromInteger . fst . fromJust. BS.readInteger <$> BS.getLine\nreadxs = map (fromInteger . fst . fromJust. BS.readInteger) . BS.words <$> BS.getLine\n \nprintList :: Show a => [a] -> IO ()\nprintList [] = return ()\nprintList [a] = print a\nprintList (a:xs) = putStr (show a) >> putChar ' ' >> printList xs\n\nsolve :: Int64 -> [Int64] -> Int64 -> Int64\nsolve presum [] _ = 0\nsolve presum (x:xs) k = needAdd + solve (presum+x+needAdd) xs k\n where minPS = (100*x+k-1) `div` k\n needAdd = if minPS > presum then minPS - presum else 0\n\nmain :: IO()\nmain = do\n t <- readx\n replicateM_ t $ do\n (n:k:_) <- readxs\n (p0:p) <- readxs\n print $ solve p0 p k"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, k] <- map read . words <$> getLine :: IO [Integer]\n ps <- map read . words <$> getLine :: IO [Integer]\n print $ maximum $ (0 :) $ zipWith (\\p a -> (100 * p - 1) `div` k + 1 - a) (tail ps) (scanl1 (+) ps)\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nsolve [] _ _ = 0\r\nsolve (x:xs) s k = solve xs (s+x+r) k + r\r\n where\r\n d = div (100*x+k-1) k\r\n r = if d <= s then 0 else d - s\r\n\r\nprintResult = do\r\n [n,k] <- readInts\r\n (p:ps) <- readInts\r\n print $ solve ps p k \r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, k] <- getInts\n ps <- getInts\n let\n qs = tail $ scanl' (+) (0 :: Integer) (map fromIntegral $ take (length ps - 1) ps)\n check x = all id $ map (\\(q, p) -> 100 * p <= fromIntegral k * (q + x)) $ zip qs (map fromIntegral $ tail ps)\n func low high\n | low == high = low\n | check x = func low x\n | otherwise = func (x + 1) high\n where\n x = (low + high) `div` 2\n C.putStrLn $ C.pack $ show $ func 0 ((10 :: Integer) ^ 18)\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> Int64 -> [Int64] -> Int64\r\nsolve n k ps = solve' (head ps) (tail ps)\r\n where\r\n solve' :: Int64 -> [Int64] -> Int64\r\n solve' _ [] = 0\r\n solve' sumP ps@(p:restPs) = max currentDeltaP $ solve' (sumP + p) restPs\r\n where \r\n currentDeltaP = max 0 $ (p * 100 - k * sumP + k - 1) `div` k\r\n\r\n -- (p * 100 - k * sumP) / k <=deltaP\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, k] <- B8.getLine <&> map readIntB8 . B8.words\r\n ps <- B8.getLine <&> map readIntB8 . B8.words\r\n let answer = solve n (fromIntegral k) (map fromIntegral ps)\r\n printf \"%lld\\n\" answer\r\n\r\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n p <- map fromIntegral <$> readInts\n let\n k' = fromIntegral k :: Int64\n ps = scanl' (+) 0 p\n rates = tail [ceilDiv (v * 100) k' - s | (v, s) <- zip p ps]\n ans = maximum (0:rates)\n lift . print $ ans\n"}], "negative_code": [{"source_code": "pairUp :: [String] -> [(String, String)]\r\npairUp [] = []\r\npairUp (x : y : t) = (x, y) : pairUp t\r\n\r\ntoArr :: (Num a, Read a) => String -> [a]\r\ntoArr = map (read :: Read a => String -> a) . words\r\n\r\ntoSolveInp :: (String, String) -> (Int, [Int])\r\ntoSolveInp (s, t) = (k, p)\r\n where p = toArr t\r\n [_, k] = toArr s\r\n\r\ngo :: Int -> Int -> [Int] -> Int\r\ngo k acc [] = 0\r\ngo k acc (p : ps) = max 0 (leastAcc - acc) + go k (newAcc + p) ps\r\n where (d, m) = divMod (100 * p) k\r\n leastAcc = if m > 0 then d + 1 else d\r\n newAcc = max acc leastAcc\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve k (p : ps) = go k p ps\r\n\r\nmain :: IO ()\r\nmain = interact\r\n (unlines . map (show . uncurry solve . toSolveInp) . pairUp . tail . lines)\r\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, k] <- map read . words <$> getLine :: IO [Integer]\n ps <- map read . words <$> getLine :: IO [Integer]\n print $ maximum $ (0 :) $ zipWith (\\p a -> 100 * p - a * k) (tail ps) (scanl1 (+) ps)\n"}], "src_uid": "53975eea2503bb47bfd0a5119406aea3"} {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:k:_) <- map read . words <$> getLine\n print $\n minimum\n [ n `div` d\n | d1 <- [1 .. min (ceiling $ sqrt $ fromIntegral n) k]\n , n `mod` d1 == 0\n , d <- [d1, n `div` d1]\n , d <= k\n ]", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n print $ f n k\n\nf :: Int -> Int -> Int\nf n k =\n minimum\n . filter (\\x -> div n x <= k)\n . concatMap (\\x -> [x, div n x])\n . filter (\\x -> mod n x == 0)\n $ takeWhile (\\x -> x * x <= n) [1 ..]\n"}, {"source_code": "import Control.Monad (replicateM_)\n\ngetDivisors n limit = [x | x <- [1 .. limit], n `mod` x == 0]\n\ngetShovelType :: [Int] -> Int\ngetShovelType [n, k] =\n if length beforeSqrt == 0 then head afterSqrt\n else head beforeSqrt\n where\n limit = (round . sqrt . fromIntegral) n\n divisors = getDivisors n limit\n beforeSqrt = filter (\\x -> n `div` x <= k) divisors\n afterSqrt = filter (\\x -> n `div` x <= k) ((reverse . map (\\x -> n `div` x)) divisors)\n\nreadLine :: IO [Int]\nreadLine = (map read) . words <$> getLine\n\nmain =\n read <$> getLine >>= \\t ->\n replicateM_ t (getShovelType <$> readLine >>= print)"}, {"source_code": "import Control.Monad ( replicateM_ )\n\n\nreadInput = (map read . words <$> getLine)\n\nbuyingShovels :: [Int] -> Int\nbuyingShovels [n, k] = head (cands' ++ cands'')\n where upper = ceiling.sqrt.fromIntegral $ n\n cands' = filter (\\x -> n`mod`x==0 && n`div`x<=k) [1..upper]\n cands'' = [n`div`x | x<-[upper,upper-1..1], n`mod`x==0, x<=k]\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (buyingShovels <$> readInput >>= print)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/D\n\nimport Control.Monad ( replicateM_ )\n\n\nbuyingShovels :: [Int] -> Int\nbuyingShovels [n, k] = head (cands1 ++ cands2) where\n upper = ceiling . sqrt . fromIntegral $ n\n increasing = [1 .. upper]\n decreasing = [upper, upper-1 .. 1]\n cands1 = [x | x <- increasing, n `div` x <= k, n `mod` x == 0]\n cands2 = [n `div` x | x <- decreasing, x <= k, n `mod` x == 0]\n\n\nreadInput :: IO [Int]\nreadInput = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (buyingShovels <$> readInput >>= print)\n"}, {"source_code": "parse :: String -> [(Int, Int)]\nparse inp = [(n, k) | [n, k] <- map (map read . words) . tail $ lines inp]\n\nfactors :: Int -> [Int]\nfactors n = sf ++ reverse (map (quot n) sf) where\n sf = [w | w <- takeWhile (\\w -> w*w <= n) [1..], rem n w == 0]\n\nsolve :: (Int, Int) -> Int\nsolve (n, k) = (quot n) . last . filter (<= k) $ factors n\n\nshowAns :: [Int] -> String\nshowAns = unlines . map show\n\nmain :: IO ()\nmain = interact (showAns . map solve . parse)\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n print $ f n k\n\nf :: Int -> Int -> Int\nf n k | null pds = n\n | otherwise = minimum pds\n where\n pds =\n filter (\\x -> x * k >= n)\n . concatMap (\\x -> [x, div n x])\n . filter (\\x -> mod n x == 0)\n . takeWhile (\\x -> x * x <= n)\n $ dropWhile (\\x -> x * k < n) [1 ..]\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n let m = maxBound :: Int\n print $ f n k\n\nf :: Int -> Int -> Int\n-- x * y = n 1<=x<=k\nf n k | null pds = n\n | otherwise = head pds\n where\n pds =\n filter (\\x -> mod n x == 0) . takeWhile (\\x -> x * x <= n) $ dropWhile\n (\\x -> x * k < n)\n (1 : 2 : [3, 5 ..])\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n let m = maxBound :: Int\n print $ f n k\n\nf :: Int -> Int -> Int\n-- n = x * y x is minimum then y is maximum \nf n k | not . null $ divs = n `div` head divs\n | k >= n = 1\n | otherwise = n\n where\n divs = filter ((0 ==) . (n `mod`))\n (2 : takeWhile (\\x -> x * x <= n && x <= k) [3, 5 ..])\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n let m = maxBound :: Int\n print $ f n k\n\nf :: Int -> Int -> Int\n-- x * y = n 1<=x<=k\nf n k | null pds = n\n | otherwise = head pds\n where\n pds =\n filter (\\x -> mod n x == 0) . takeWhile (\\x -> x * x <= n) $ dropWhile\n (\\x -> x * k < n)\n [1 ..]\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n let m = maxBound :: Int\n print $ f n k\n\nf :: Int -> Int -> Int\n-- n = x * y x is minimum then y is maximum \nf n k | not . null $ divs = head divs\n | k >= n = 1\n | otherwise = n\n where\n divs = filter ((0 ==) . (n `mod`))\n (takeWhile (\\x -> x * x <= n && x <= k) [start ..])\n start = ceiling $ (fromIntegral n) / (fromIntegral k)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n let m = maxBound :: Int\n print $ f n k\n\nf :: Int -> Int -> Int\n-- n = x * y x is minimum then y is maximum \nf n k | not . null $ divs = head divs\n | otherwise = n\n where\n divs = filter ((0 ==) . (n `mod`))\n (takeWhile (\\x -> x * x <= n && x <= k) [start ..])\n start = ceiling $ (fromIntegral n) / (fromIntegral k)\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n print $ f n k\n\nf :: Int -> Int -> Int\nf n k | null pds = n\n | otherwise = head pds\n where\n pds =\n filter (\\x -> mod n x == 0) . takeWhile (\\x -> x * x <= n) $ dropWhile\n (\\x -> x * k < n)\n [1 ..]\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [n, k] <- map read . words <$> getLine\n print $ f n k\n\nf :: Int -> Int -> Int\nf n k | null pds = n\n | otherwise = minimum pds\n where\n pds =\n filter (\\x -> mod n x == 0) . takeWhile (\\x -> x * x <= n) $ dropWhile\n (\\x -> x * k < n)\n [1 ..]\n"}, {"source_code": "import Control.Monad (replicateM_)\n\ngetDivisors n limit = [x | x <- [1 .. limit], n `mod` x == 0]\n\ngetShovelType :: [Int] -> Int\ngetShovelType [n, k] =\n if length beforeSqrt == 0 then head afterSqrt\n else head beforeSqrt\n where\n limit = (round . sqrt . fromIntegral) n\n divisors = getDivisors n limit\n beforeSqrt = filter (\\x -> n `div` x <= k) divisors\n afterSqrt = filter (\\x -> n `div` x <= k) (map (\\x -> n `div` x) divisors)\n\nreadLine :: IO [Int]\nreadLine = (map read) . words <$> getLine\n\nmain =\n read <$> getLine >>= \\t ->\n replicateM_ t (getShovelType <$> readLine >>= print)"}, {"source_code": "import Control.Monad ( replicateM_ )\n\n\nreadInput = map read . words <$> getLine\n\nbuyingShovels :: [Int] -> Int\nbuyingShovels [n, k] = head cands'\n where cands' = filter (\\x -> n`mod`x==0 && n`div`x<=k) cands\n cands = [1..(ceiling.sqrt.fromIntegral $ n)] ++ [n]\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (buyingShovels <$> readInput >>= print)\n"}], "src_uid": "f00eb0452f5933103f1f77ef06473c6a"} {"source_code": "{-\nf [] ['*'] _ = \"YES\"\nf [] [] _ = \"YES\"\nf _ [] _ = \"NO\"\nf [] _ _ = \"NO\"\nf xx@(x:xs) tt@(t:ts) dict\n\t|t==x = f xs ts dict\n\t|t=='?' && inDict =f xs ts dict\n\t|t=='*' && length xsf d template dict ) $ take n xs \n\t\nmain=interact$unlines.solve.extract.lines\n\n-}\n\nimport Control.Applicative( (<$>))\nimport Control.Monad( replicateM, forM_)\n\nmain = do\n goodLetters_ <- getLine\n expression_ <- getLine\n n_ <- readLn\n queries_ <- replicateM n_ getLine\n let\n\tisMatch [] [] = [True]\n\tisMatch \"*\" [] = [True]\n\tisMatch _ [] = [False]\n\tisMatch [] _ = [False]\n\tisMatch exp@(e:xpression) q@(c:cs) = case e of\n\t '?'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression cs\n\t\t else [False]\n\t '*'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression q\n\t\t else (isMatch xpression q)++(isMatch exp cs)\n\t e\t-> if e==c then isMatch xpression cs else [False]\n\n\tputStr' query = putStrLn $\n\t\t\t if or $ isMatch expression_ query\n\t\t\t\tthen \"YES\"\n\t\t\t\telse \"NO\"\n forM_ queries_ putStr'", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n gs <- getLine\n p <- getLine\n n <- fmap readInt B.getLine\n qs <- replicateM n getLine\n putStr $ unlines $ map (\\x -> if x then \"YES\" else \"NO\") $ solve gs p qs\n\nsolve gs pt = map (ok pt)\n where \n bs = ['a'..'z'] \\\\ gs\n ok [] [] = True\n ok \"*\" [] = True\n ok _ [] = False\n ok [] _ = False\n ok (p:ps) (q:qs) \n | p == q = ok ps qs\n | p == '?' = q `elem` gs && ok ps qs\n | p == '*' = ok ps (q:qs) || q `elem` bs && ok (p:ps) qs\n | otherwise = False\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "import Control.Monad( replicateM)\n\t\nextract (x:y:n:xs)=(x,y,read n::Int,xs)\n\t\nsel \"YES\" _ = \"YES\"\nsel _ \"YES\" = \"YES\"\nsel _ _ =\"NO\"\t\nmain=do\n\tdict<-getLine\n\ttemplate<-getLine\n\tn<-readLn\n\txs<-replicateM n getLine\n\tlet \n\t\tf [] [] = \"YES\"\n\t\tf \"*\" [] = \"YES\"\n\t\tf _ [] = \"NO\"\n\t\tf [] _ = \"NO\"\n\t\tf exp@(e:xpression) q@(c:cs) = case e of\n\t\t\t'?'\t-> if c `elem` dict\n\t\t\t\tthen f xpression cs\n\t\t\t\telse \"NO\"\n\t\t\t'*'\t-> if c `elem` dict\n\t\t\t\tthen f xpression q\n\t\t\t\telse sel (f xpression q) (f exp cs)\n\t\t\te\t-> if e==c then f xpression cs else \"NO\"\n\n\t\tres=map (\\d->f template d) xs \n\tmapM_ putStrLn $ res\n\t\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM, forM_)\n\nmain = do\n goodLetters_ <- getLine\n expression_ <- getLine\n n_ <- readLn\n queries_ <- replicateM n_ getLine\n let\n\tisMatch [] [] = [True]\n\tisMatch \"*\" [] = [True]\n\tisMatch _ [] = [False]\n\tisMatch [] _ = [False]\n\tisMatch exp@(e:xpression) q@(c:cs) = case e of\n\t '?'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression cs\n\t\t else [False]\n\t '*'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression q\n\t\t else (isMatch xpression q)++(isMatch exp cs)\n\t e\t-> if e==c then isMatch xpression cs else [False]\n\n\tputStr' query = putStrLn $\n\t\t\t if or $ isMatch expression_ query\n\t\t\t\tthen \"YES\"\n\t\t\t\telse \"NO\"\n forM_ queries_ putStr'\n"}], "negative_code": [{"source_code": "import Control.Monad( replicateM)\n\t\nextract (x:y:n:xs)=(x,y,read n::Int,xs)\n\t\nmain=do\n\tdict<-getLine\n\ttemplate<-getLine\n\tn<-readLn\n\txs<-replicateM n getLine\n\tlet \n\t\tf [] [] = \"YES\"\n\t\tf \"*\" [] = \"YES\"\n\t\tf _ [] = \"NO\"\n\t\tf [] _ = \"NO\"\n\t\tf exp@(e:xpression) q@(c:cs) = case e of\n\t\t\t'?'\t-> if c `elem` dict\n\t\t\t\tthen f xpression cs\n\t\t\t\telse \"NO\"\n\t\t\t'*'\t-> if c `elem` dict\n\t\t\t\tthen f xpression q\n\t\t\t\telse (f exp cs)\n\t\t\te\t-> if e==c then f xpression cs else \"NO\"\n\n\t\tres=map (\\d->f template d) xs \n\tmapM_ putStrLn $ res\n\t\n\t\n\t\n"}, {"source_code": "import Control.Monad( replicateM)\n\t\nextract (x:y:n:xs)=(x,y,read n::Int,xs)\n\t\nmain=do\n\tdict<-getLine\n\ttemplate<-getLine\n\tn<-readLn\n\txs<-replicateM n getLine\n\tlet \n\t\tf [] [] = \"YES\"\n\t\tf \"*\" [] = \"YES\"\n\t\tf _ [] = \"NO\"\n\t\tf [] _ = \"NO\"\n\t\tf exp@(e:xpression) q@(c:cs) = case e of\n\t\t\t'?'\t-> if c `elem` dict\n\t\t\t\tthen f xpression cs\n\t\t\t\telse \"NO\"\n\t\t\t'*'\t-> if c `elem` dict\n\t\t\t\tthen f xpression q\n\t\t\t\telse (f xpression q)++(f exp cs)\n\t\t\te\t-> if e==c then f xpression cs else \"NO\"\n\n\t\tres=map (\\d->f template d) xs \n\tmapM_ putStrLn $ res\n\t\n\t\n\t\n"}, {"source_code": "f [] ['*'] _ = \"YES\"\nf [] [] _ = \"YES\"\nf _ [] _ = \"NO\"\nf [] _ _ = \"NO\"\nf xx@(x:xs) tt@(t:ts) dict\n\t|t==x = f xs ts dict\n\t|t=='?' && elem x dict =f xs ts dict\n\t|t=='*' && not (elem x dict) = f xs tt dict\n\t|t=='*' && elem x dict = f xx ts dict\n\t|otherwise = \"NO\"\n\t\nextract (x:y:n:xs)=(x,y,read n::Int,xs)\n\nsolve (dict,template,n,xs)=map (\\d->f d template dict ) $ take n xs \n\t\nmain=interact$unlines.solve.extract.lines"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM, forM_)\n\nmain = do\n goodLetters_ <- getLine\n expression_ <- getLine\n n_ <- readLn\n queries_ <- replicateM n_ getLine\n let\n\tisMatch [] [] = [True]\n\tisMatch \"*\" [] = [True]\n\tisMatch _ [] = [False]\n\tisMatch [] _ = [False]\n\tisMatch exp@(e:xpression) q@(c:cs) = case e of\n\t '?'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression cs\n\t\t else [False]\n\t '*'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression q\n\t\t else (isMatch xpression cs)++(isMatch exp cs)\n\t e'\t-> if e'==c then isMatch xpression cs else [False]\n\n\tputStr' query = putStrLn $\n\t\t\t if or $ isMatch expression_ query\n\t\t\t\tthen \"YES\"\n\t\t\t\telse \"NO\"\n forM_ queries_ putStr'\n"}, {"source_code": "import Control.Applicative( (<$>))\nimport Control.Monad( replicateM, forM_)\n\nmain = do\n goodLetters_ <- getLine\n expression_ <- getLine\n n_ <- readLn\n queries_ <- replicateM n_ getLine\n let\n\tisMatch \"*\" [] = [True]\n\tisMatch [] [] = [True]\n\tisMatch _ [] = [False]\n\tisMatch [] _ = [False]\n\tisMatch exp@(e:xpression) q@(c:cs) = case e of\n\t '?'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression cs\n\t\t else [False]\n\t '*'\t-> if c `elem` goodLetters_\n\t\t then isMatch xpression q\n\t\t else (isMatch xpression cs)++(isMatch exp cs)\n\t e\t-> if e==c then isMatch xpression cs else [False]\n\n\tputStr' query = putStrLn $\n\t\t\t if or $ isMatch expression_ query\n\t\t\t\tthen \"YES\"\n\t\t\t\telse \"NO\"\n forM_ queries_ putStr'\n"}], "src_uid": "c6633581d7424d670eaa0f8a5c8cc366"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nmain = do\n [[_, _, ax, bx], ays, bys, ls] <- fmap (map (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) . BS.lines) BS.getContents :: IO [[Double]]\n let ds = map (\\ay -> dist (0, 0) (ax, ay)) ays\n let (len, i, j) = solve 1 1 ax bx ays bys ds ls []\n putStr $ show i ++ \" \" ++ show j\n where\n solve _ _ _ _ _ [] _ [] anss = minimum anss\n solve i j ax bx [ay] bys [d] ls anss = solve i j ax bx [ay, 10 ^ 10] bys [d, 10 ^ 10] ls anss\n solve i j ax bx (ay1:ay2:ays) (by:bys) (d1:d2:ds) (l:ls) anss = if d1 + dist (ax, ay1) (bx, by) >= d2 + dist (ax, ay2) (bx, by)\n then solve (i + 1) j ax bx (ay2:ays) (by:bys) (d2:ds) (l:ls) anss\n else solve i (j + 1) ax bx (ay1:ay2:ays) bys (d1:d2:ds) ls $ (d1 + dist (ax, ay1) (bx, by) + l, i, j):anss\n\ndist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2\n", "positive_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n let readInt = fst . fromJust . C.readInt\n (n:m:input) <- fmap (map (readInt) . C.words) C.getContents\n let (u:v:a, input') = splitAt (n+2) $ map fromIntegral input\n (b, c) = splitAt m input'\n (ans, x, y) = minimum $ gao u v (zip [1 ..] a) (zip3 [1 ..] b c)\n putStrLn $ show x ++ \" \" ++ show y\n\nhypot x y = sqrt $ x * x + y * y\n\ngao u v a b = go a b\n where\n go _ [] = []\n go a ((j, r, d): t) = (dist l, i, j): go a' t\n where\n dist l = hypot u l + hypot (v - u) (r - l) + d\n a'@((i, l): _) = best a\n best [h] = [h]\n best l1@((_, h1): l2@((_, h2): t)) =\n if dist h2 <= dist h1 then best l2 else l1\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nmain = do\n [[_, _, ax, bx], ays, bys, ls] <- fmap (map (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) . BS.lines) BS.getContents\n let (len, i, j) = solve 1 1 ax bx ays bys ls []\n putStr $ show i ++ \" \" ++ show j\n where\n solve _ _ _ _ _ [] [] anss = minimum anss\n solve i j ax bx [ay] bys ls anss = solve i j ax bx [ay, 10 ^ 10] bys ls anss\n solve i j ax bx (ay1:ay2:ays) (by:bys) (l:ls) anss = if dist (0, 0) (ax, ay1) + dist (ax, ay1) (bx, by) >= dist (0, 0) (ax, ay2) + dist (ax, ay2) (bx, by)\n then solve (i + 1) j ax bx (ay2:ays) (by:bys) (l:ls) anss\n else solve i (j + 1) ax bx (ay1:ay2:ays) bys ls $ (dist (0, 0) (ax, ay1) + dist (ax, ay1) (bx, by) + l, i, j):anss\n\ndist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n let readInt = fst . fromJust . C.readInt\n (n:m:input) <- fmap (map (readInt) . C.words) C.getContents\n let (u:v:a, input') = splitAt (n+2) $ map fromIntegral input\n (b, c) = splitAt m input'\n (ans, x, y) = minimum $ gao u v (zip [1 ..] a) (zip3 [1 ..] b c)\n putStrLn $ show x ++ \" \" ++ show y\n\nhypot x y = sqrt $ x * x + y * y\n\ngao u v a b = go a b\n where\n go _ [] = []\n go a ((j, r, d): t) = (dist l, i, j): go a' t\n where\n dist l = hypot u l + hypot (v - u) (r - l) + d\n a'@((i, l): _) = best a\n best [h] = [h]\n best l1@((_, h1): l2@((_, h2): t)) =\n if dist h2 < dist h1 then l2 else l1\n\n"}], "src_uid": "44542e73195573debb4ab113bab5ee23"} {"source_code": "-- Codeforces Round #531 (B), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine :: IO [Int]\n let ias = sorton snd $ zip [0..] as\n mink = maximum $ map length $ groupBy ((==) `on` snd) ias\n sortedAns = zipWith (\\(i,a) c -> (i,c)) ias $ cycle [1..k]\n ans = map snd $ sorton fst sortedAns\n if mink <= k then do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show ans\n else\n putStrLn \"NO\"\n\nsorton f = sortBy (compare `on` f)\n", "positive_code": [{"source_code": "import Data.Function\nimport Data.Functor\nimport Data.List hiding (sortOn)\nimport qualified Data.Map as M\n\ntoList :: (Read a) => String -> [a]\ntoList = (map read) <$> words\n\nmain = do\n [n, k] <- toList <$> getLine :: IO [Int]\n as <- toList <$> getLine :: IO [Int]\n let bs = sortOn snd $ zip [0 .. ] as\n m = maximum $ map length $ groupBy ((==) `on` snd) bs\n cs = zipWith (\\(x,_) y -> (x, y)) bs (cycle [1 .. k])\n if m > k then do\n putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n putStrLn $ unwords $ map (show . snd) $ sortOn fst cs\n\nsortOn :: (Ord b) => (a -> b) -> [a] -> [a]\nsortOn f = sortBy (compare `on` f)\n"}, {"source_code": "import Data.Functor\nimport qualified Data.List as L\nimport qualified Data.Map as M\n\ntoList :: (Read a) => String -> [a]\ntoList = (map read) <$> words\n\naddIndex :: [Int] -> [(Int, Int)]\naddIndex = zip [1 .. ]\n\nsortByValue :: [(Int, Int)] -> [(Int, Int)]\nsortByValue = L.sortBy (\\(_,x) (_,y) -> compare x y)\n\ncolorize :: Int -> [(Int, Int)] -> [(Int, Int)]\ncolorize k xs = zip (map fst xs) (cycle [1..k])\n\nsortByIndex :: [(Int, Int)] -> [(Int, Int)]\nsortByIndex = L.sort\n\noutput :: [(Int, Int)] -> IO ()\noutput xs = do\n putStrLn \"YES\"\n putStrLn $ L.intercalate \" \" (map (show . snd) xs)\n\nmain = do\n (n, k) <- (\\[e1, e2] -> (e1, e2)) <$> toList <$> getLine :: IO (Int, Int)\n arr <- toList <$> getLine :: IO [Int]\n if (maximum $ map length $ L.group $ L.sort arr) > k || (length arr) < k\n then\n putStrLn \"NO\"\n else \n output . sortByIndex $ colorize k (sortByValue $ addIndex arr)\n\n return ()\n"}], "negative_code": [], "src_uid": "3d4df21eebf32ce15841179bb85e6f2f"} {"source_code": "module Main where\r\n\r\nwork [] t=[]\r\nwork ('1':xs) 2='0':work xs 1\r\nwork ('1':xs) t='1':work xs 2\r\nwork ('0':xs) 1='0':work xs 0\r\nwork ('0':xs) t='1':work xs 1\r\n\r\nrun 1 = do\r\n l1 <- getLine\r\n l2 <- getLine\r\n let str=l2\r\n putStrLn $ work str 5\r\n\r\nrun x = do\r\n run 1\r\n run (x-1)\r\n\r\nmain = do\r\n l1 <- getLine\r\n let t = (read::String->Integer) l1\r\n run t", "positive_code": [{"source_code": "solve :: String -> String\r\nsolve = go '*'\r\n where go last [] = []\r\n go last (c : t)\r\n | succ c == last = '0' : go c t\r\n | otherwise = '1' : go (succ c) t\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map solve . takeEven . tail . lines)\r\n where takeEven l = map snd $ filter (even . fst) (zip [1..] l)\r\n"}, {"source_code": "solve :: String -> String\r\nsolve s = '1' : go (p $ head s) (tail s)\r\n where go last [] = []\r\n go last [c] = if p c == last then \"0\" else \"1\"\r\n go last (c : d : t)\r\n | p c == last = '0' : go c (d : t)\r\n | otherwise = '1' : go (p c) (d : t)\r\n p '0' = '1'\r\n p '1' = '2'\r\n\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map solve . takeOdd . tail . lines)\r\n where takeOdd [] = []\r\n takeOdd [x] = []\r\n takeOdd (x : y : z) = y : takeOdd z\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: String -> String\r\nsolve s = solve' (-1) s\r\n where\r\n solve' :: Int -> String -> String\r\n solve' _ [] = []\r\n solve' 1 ('0':s) = '0' : solve' 0 s\r\n solve' _ ('0':s) = '1' : solve' 1 s\r\n solve' 2 ('1':s) = '0' : solve' 1 s\r\n solve' _ ('1':s) = '1' : solve' 2 s\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n n <- B8.getLine <&> readIntB8\r\n s <- B8.getLine <&> B8.unpack . head . B8.words\r\n let answer = solve s\r\n putStrLn answer"}], "negative_code": [{"source_code": "solve :: String -> String\r\nsolve s = go (head s) s\r\n where go last [] = []\r\n go last [c] = if c == last then \"1\" else \"0\"\r\n go last (c : d : t)\r\n | p c == last = '0' : go c (d : t)\r\n | otherwise = '1' : go (p c) (d : t)\r\n p '0' = '1'\r\n p '1' = '2'\r\n\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map solve . takeOdd . tail . lines)\r\n where takeOdd [] = []\r\n takeOdd [x] = []\r\n takeOdd (x : y : z) = y : takeOdd z\r\n"}, {"source_code": "solve :: String -> String\r\nsolve [] = []\r\nsolve [c] = \"0\"\r\nsolve (c : d : t)\r\n | c == d = '1' : '0' : solve t\r\n | otherwise = '0' : solve (d : t)\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map solve . takeOdd . tail . lines)\r\n where takeOdd [] = []\r\n takeOdd [x] = []\r\n takeOdd (x : y : z) = y : takeOdd z\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: String -> String\r\nsolve s = solve' (-1) s\r\n where\r\n solve' :: Int -> String -> String\r\n solve' _ [] = []\r\n solve' 0 ('0':s) = '1' : solve' 1 s\r\n solve' _ ('0':s) = '0' : solve' 0 s\r\n solve' 1 ('1':s) = '1' : solve' 2 s\r\n solve' _ ('1':s) = '0' : solve' 1 s\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n n <- B8.getLine <&> readIntB8\r\n s <- B8.getLine <&> B8.unpack . head . B8.words\r\n let answer = solve s\r\n putStrLn answer"}], "src_uid": "e27620d3a43ab42edf930b37ce214c9e"} {"source_code": "import Control.Monad\n\ngetInts :: IO [Int]\ngetInts = map read.words <$> getLine\n\nmain :: IO()\nmain = do\n [t] <- getInts\n replicateM_ t routine\n\nroutine :: IO()\nroutine = do\n [n] <- getInts\n a <- getInts\n let evens = [z | z <- (zip a [0..]), even $ fst z]\n badevens_count = length $ filter (\\x -> odd $ snd x) evens\n odds = [z | z <- (zip a [0..]), odd $ fst z]\n badodds_count = length $ filter (\\x -> even $ snd x) odds\n if badevens_count /= badodds_count then\n print (-1)\n else\n print badevens_count", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\tt <- readInt\n\tmapM_ print =<< replicateM t solve\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tevens = length $ filter odd $ map fst $ filter snd $ zip as $ cycle [ True, False ]\n\t\todds = length $ filter even $ map fst $ filter snd $ zip as $ cycle [ False, True ]\n\treturn $ if evens == odds \n\t\tthen evens\n\t\telse -1"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = if ce == co then ce else -1\n where\n (e,o) = partition (even.snd) (zip xs [0..])\n (e',o') = (map fst e,map fst o)\n ce =length $ filter odd e'\n co = length $ filter even o'\n"}, {"source_code": "main = do\n inputjar <- getLine\n let n = read inputjar :: Int\n solve n\n\nsolve :: Int -> IO ()\nsolve 0 = putStr \"\"\nsolve n = do\n _ <- getLine\n input <- getLine\n let list = read (\"[\" ++ map (\\x -> if x == ' ' then ',' else x) input ++ \"]\") :: [Int]\n solveCase list\n solve (n - 1)\n\nsolveCase :: [Int] -> IO ()\nsolveCase xs = print $ if odd == even then odd else (-1)\n where\n odd = foldl (\\acc i -> acc + if (xs !! i) `mod` 2 == 1 then 0 else 1) 0 [1, 3 .. length xs - 1]\n even = foldl (\\acc i -> acc + if (xs !! i) `mod` 2 == 0 then 0 else 1) 0 [0, 2 .. length xs - 1]\n"}, {"source_code": "import Data.Maybe (catMaybes)\nimport Data.List (sort, group)\nimport Control.Monad (replicateM_)\n\n\n\ndata Inversion = Even | Odd deriving (Eq, Ord)\n\nf :: (Int, Int) -> Maybe Inversion\nf (x,y) | even x && odd y = Just Even\n | odd x && even y = Just Odd\n | otherwise = Nothing\n\nmain = readLn >>= flip replicateM_ (getLine >> getLine >>= print . w . catMaybes . map f . zip [0..] . map read . words)\n where w [] = 0\n w xs = case map length . group $ sort xs of\n [_] -> -1\n [a,b] -> if a==b then a else -1\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess e o [] = if e==o then e else -1\nprocess e o [a] | even a = process e o []\n |otherwise = process (e+1) o []\n\nprocess e o (a:b:c) | even a && odd b = process e o c\n | even a && even b = process e (o+1) c\n\t\t | odd a && odd b = process (e+1) o c\n\t\t | otherwise = process (e+1) (o+1) c\n \n\nonecase = do\n\t\tgetLine\n\t\tk<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ process 0 0 k\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n"}, {"source_code": "import Control.Monad\n\ncountOddEven [] o e l = (o, e, l)\ncountOddEven (a:t) o e l\n | a `mod` 2 == 0 = countOddEven t o (e + 1) (l + 1)\n | otherwise = countOddEven t (o + 1) e (l + 1)\n\nsolve :: [Int] -> Int\nsolve lst = \n let\n (o, e, l) = countOddEven lst 0 0 0\n in\n if (abs (o - e)) /= l `mod` 2 then -1\n else \n let\n wrong = length (filter not (zipWith (\\a b->a `mod` 2 /= b `mod` 2)[1..] lst))\n in\n if wrong `mod` 2 == 0 then wrong `div` 2 else -1\n\nmain = do\n n <- read <$> getLine\n a <- replicateM n (getLine >> getLine)\n let ainp = (map read) . words <$> a\n mapM_ (putStrLn . show . solve) $ ainp\n"}], "negative_code": [], "src_uid": "942123e43a83d5a4cea95a6781064e28"} {"source_code": "import Control.Monad\n\n\nsolveRecursively :: (Char,String) -> Maybe String\nsolveRecursively (prev,x:(x2:xs))\n |prev == x = Nothing\n |x=='?' = fmap ((:) (decide [prev,x2])) (solveRecursively (decide [prev,x2],x2:xs))\n |otherwise = fmap ((:) x) (solveRecursively (x,x2:xs))\nsolveRecursively (prev,[x])\n |prev == x = Nothing\n |x=='?' = fmap ((:) (decide [prev])) (solveRecursively (decide [prev],[]))\n |otherwise =fmap ((:) x) (solveRecursively (x,[]))\nsolveRecursively _ = Just []\n\nroutine :: IO ()\nroutine = do\n str <- getLine\n case solveRecursively ('y',str) of\n Nothing -> putStrLn \"-1\"\n Just x -> putStrLn x\n\n\ndecide :: [Char] -> Char\ndecide li = head $ filter (`notElem` li) \"abc\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n", "positive_code": [{"source_code": "import Control.Monad\n \nmain :: IO ()\nmain = do\n input <- getLine\n let linesToRead = read input\n tryDecorateString linesToRead\n \ntryDecorateString :: Int -> IO ()\ntryDecorateString 0 = pure ()\ntryDecorateString n = do\n currentLine <- getLine\n if isStringBeautiful currentLine Nothing\n then putStrLn (reverse (decorateString currentLine []))\n else putStrLn \"-1\"\n tryDecorateString (n - 1)\n \nalphabet :: [Char]\nalphabet = ['a', 'b', 'c']\n \n-- check that string doesn't contains any double characters\nisStringBeautiful :: [Char] -> Maybe Char -> Bool\nisStringBeautiful (x:xs) Nothing =\n if (length xs) == 0\n then True\n else isStringBeautiful xs (Just x)\n \nisStringBeautiful (x:xs) (Just prevChar) =\n if x == prevChar && x /= '?'\n then False\n else isStringBeautiful xs (Just x)\n \nisStringBeautiful [] _ = True\n\n-- start for 1 elem\ndecorateString :: [Char] -> [Char] -> [Char]\ndecorateString word formattedWord =\n case word of\n (x:[]) -> case x of\n '?' -> case formattedWord of\n -- start iteration\n [] -> [anyChar] \n -- end of iteration\n (r:rs) -> allowedEnd:r:rs\n _ -> x:formattedWord\n (x:xs) -> case x of\n '?' -> case formattedWord of\n [] -> decorateString xs (allowedStart:[])\n (r:rs) -> decorateString xs (allowedMiddle:r:rs)\n _ -> decorateString xs (x:formattedWord)\n where\n anyChar = alphabet !! 0\n nextChar = word !! 1\n prevChar = head formattedWord\n allowedStart = (filter (/= nextChar) alphabet) !! 0\n allowedMiddle = (filter (\\x -> x /= prevChar && x /= nextChar) alphabet) !! 0\n allowedEnd = (filter (/= prevChar) alphabet) !! 0\n \n-- beautify string\n\n \n \ntests :: [String]\ntests = [\"a???cb\", \"a??bbc\", \"a?b?c\", \"a??a\"]"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: String -> String\nsolve str = newStr\n where\n indexed = zip [0..] str\n newStr = map f indexed\n f (index,char)\n | char /= '?' = char\n | index ==0 = decide [str!!(index+1)]\n | index ==length str-1 = decide [newStr!!(index-1)]\n | otherwise = decide [newStr!!(index-1),str!!(index+1)]\n\ndecide :: [Char] -> Char\ndecide li = head $ filter (`notElem` li) \"abc\"\n\nroutine :: IO ()\nroutine = do\n str <- getLine\n putStrLn $ solve str\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "import Control.Monad\n \nmain :: IO ()\nmain = do\n input <- getLine\n let linesToRead = read input\n tryDecorateString linesToRead\n \ntryDecorateString :: Int -> IO ()\ntryDecorateString 0 = pure ()\ntryDecorateString n = do\n currentLine <- getLine\n if isStringBeautiful currentLine Nothing\n then putStrLn (decorateString currentLine [])\n else putStrLn \"-1\"\n tryDecorateString (n - 1)\n \nalphabet :: [Char]\nalphabet = ['a', 'b', 'c']\n \n-- check that string doesn't contains any double characters\nisStringBeautiful :: [Char] -> Maybe Char -> Bool\nisStringBeautiful (x:xs) Nothing =\n if (length xs) == 0\n then True\n else isStringBeautiful xs (Just x)\n \nisStringBeautiful (x:xs) (Just prevChar) =\n if x == prevChar && x /= '?'\n then False\n else isStringBeautiful xs (Just x)\n \nisStringBeautiful [] _ = True\n\n-- start for 1 elem\ndecorateString :: [Char] -> [Char] -> [Char]\ndecorateString word formattedWord =\n case word of\n (x:[]) -> case x of\n '?' -> case formattedWord of\n -- start iteration\n [] -> [anyChar] \n -- end of iteration\n (r:rs) -> allowedEnd:r:rs\n _ -> x:formattedWord\n (x:xs) -> case x of\n '?' -> case formattedWord of\n [] -> decorateString xs (allowedStart:[])\n (r:rs) -> decorateString xs (allowedMiddle:r:rs)\n _ -> decorateString xs (x:formattedWord)\n where\n anyChar = alphabet !! 0\n nextChar = word !! 1\n prevChar = head formattedWord\n allowedStart = (filter (/= nextChar) alphabet) !! 0\n allowedMiddle = (filter (\\x -> x /= prevChar && x /= nextChar) alphabet) !! 0\n allowedEnd = (filter (/= prevChar) alphabet) !! 0\n \n-- beautify string\n\n \n \ntests :: [String]\ntests = [\"a???cb\", \"a??bbc\", \"a?b?c\", \"a??a\"]"}], "src_uid": "98c08a3b5e5b5bb78804ff797ba24d87"} {"source_code": "\nimport Data.Array ((!), accumArray, listArray, elems)\n\nsolve :: [Int] -> Int\nsolve cs = n - maximum [d ! (2*i) - d ! (i-1) | i <- [1 .. max `div` 2]]\n where\n n = length cs\n a = accumArray (+) 0 (1, max) $ [(c, 1) | c <- cs]\n d = listArray (0, max) $ scanl (+) 0 $ elems a\n max = 5000\n\nmain :: IO ()\nmain = do\n content <- readFile \"input.txt\"\n let cs = tail $ map read $ words content\n writeFile \"output.txt\" $ show $ solve cs\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport System.IO\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nbSearch :: (Int -> Bool) -> Int -> Int -> Int\nbSearch p !low !high\n | high<=low = low\n | p mid = bSearch p mid high\n | otherwise = bSearch p low (mid-1)\n where\n mid = div (low+high+1) 2\n\nmain = do\n\n hin <- openFile \"input.txt\" ReadMode\n hout <- openFile \"output.txt\" WriteMode\n\n n <- read <$> hGetLine hin\n xs <- sort.map readInt.B.words <$> B.hGetContents hin\n hPrint hout $ n - solve n (listArray (0,n-1) xs)\n\n hClose hin\n hClose hout\n\nsolve :: Int -> UArray Int Int -> Int\nsolve n arr = maximum $ map f [0..n-1]\n where\n f i\n | unsafeAt arr (n-1) <= ai2 = n-1-i+1\n | otherwise = bSearch ((<=ai2).unsafeAt arr) i (n-1) - i+1\n where\n !ai2 = 2*unsafeAt arr i\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Control.Monad\nimport System.IO\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nbSearch :: (Int -> Bool) -> Int -> Int -> Int\nbSearch p !low !high\n | high<=low = high\n | p mid = bSearch p low mid\n | otherwise = bSearch p (mid+1) high\n where\n mid = quot (low+high) 2\n\nmain = do\n\n hin <- openFile \"input.txt\" ReadMode\n hout <- openFile \"output.txt\" WriteMode\n\n n <- read <$> hGetLine hin\n xs <- sort.map readInt.B.words <$> B.hGetContents hin\n hPrint hout $ n - solve n (listArray (0,n-1) xs)\n\n hClose hin\n hClose hout\n\nsolve :: Int -> UArray Int Int -> Int\nsolve n arr = maximum $ map f [0..n-1]\n where\n f i\n | unsafeAt arr (n-1) <= ai2 = n-1-i+1\n | otherwise = bSearch ((<=ai2).unsafeAt arr) i (n-1) - i+1\n where\n !ai2 = 2*unsafeAt arr i\n"}], "src_uid": "80cf3ea119fd398e8f003d22a76895a7"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord, isSpace)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\nimport qualified Data.ByteString.Char8 as BS (readInt, getContents, getLine, dropWhile)\n\nparseInts s = parse id s []\n where\n parse r s = case BS.readInt (BS.dropWhile isSpace s) of\n Nothing -> r\n Just (i, s') -> parse (r . (i :)) s'\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nmm = 998244353 :: Int64\n\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = (a + b) - mm\n\n{-# INLINE madd #-}\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n\n{-# INLINE mmul #-}\nsearch ::\n forall s.\n (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right) = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n access l r = readArray mem (hash l r)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise = liftA2 mmul (access l l') (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, lp)\n rv = match (rp + 1, right)\n match (l, r) =\n foldr\n (liftA2 madd)\n (return 0)\n [liftA2 mmul (access l m) (access m r) | m <- [l .. r]]\n in liftA2 mmul lov (liftA2 mmul lv rv)\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts BS.getLine\n a <- fmap parseInts BS.getContents\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nmm = 998244353 :: Int64\n\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = (a + b) - mm\n\n{-# INLINE madd #-}\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n\n{-# INLINE mmul #-}\nsearch ::\n forall s.\n (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right) = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n access l r = readArray mem (hash l r)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise = liftA2 mmul (access l l') (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, lp)\n rv = match (rp + 1, right)\n match (l, r) =\n foldr\n (liftA2 madd)\n (return 0)\n [liftA2 mmul (access l m) (access m r) | m <- [l .. r]]\n in liftA2 mmul lov (liftA2 mmul lv rv)\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (listArray, (!))\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nsearch :: (UArray Int Int, UArray Int Int) -> (Int, Int) -> State Hash MField\nsearch (value, ext) (left, right) = search' (left, right)\n where\n search' :: (Int, Int) -> State Hash MField\n search' (!left, !right)\n | left == right = return 1\n | otherwise = do\n let hc = hash left right\n table <- get\n case table !? hc of\n Just v -> return v\n Nothing -> do\n let mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n lp = findNext succ left\n rp = findNext pred (right - 1)\n lov = fmap product . mapM search' . seqGroup $ (lp, rp)\n seqGroup (l, r)\n | l == r = []\n | value ! l == lo = seqGroup (l + 1, r)\n | otherwise = (l, l') : seqGroup (l', r)\n where\n l' = findNext succ l\n lv = match (left, left, lp)\n rv = match (rp + 1, rp + 1, right)\n match (l, m, r)\n | m > r = return 0\n | m == r = search' (l, m)\n | otherwise =\n let m' = (ext ! m) + 1\n in liftA2\n (+)\n (liftA2 (*) (search' (l, m)) (search' (m, r)))\n (match (l, m', r))\n in fmap product (sequence [lov, lv, rv])\n ret `seq` modify (insert hc ret)\n return ret\n\nsolve :: Int -> [Int] -> MField\nsolve n a = evalState (search (value, ext) (0, m)) empty\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n\nmain = do\n [n, m] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL, shiftR)\nimport Data.Char (ord, isSpace)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\nimport qualified Data.ByteString.Char8 as BS (readInt, getContents, getLine, dropWhile)\n\nparseInts s = parse id s []\n where\n parse r s = case BS.readInt (BS.dropWhile isSpace s) of\n Nothing -> r\n Just (i, s') -> parse (r . (i :)) s'\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nmm = 998244353 :: Int64\n\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = (a + b) - mm\n\n{-# INLINE madd #-}\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n\n{-# INLINE mmul #-}\nsearch ::\n forall s.\n (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right) = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n access l r = readArray mem (hash l r)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise = liftA2 mmul (access l l') (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, lp)\n rv = match (rp + 1, right)\n match (l, r) =\n foldr\n (liftA2 madd)\n (return 0)\n [liftA2 mmul (access l m) (access m r) | m <- [l .. r]]\n in liftA2 mmul lov (liftA2 mmul lv rv)\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts BS.getLine\n a <- fmap parseInts BS.getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM_)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State.Strict (State, evalState, get, modify, put)\nimport Data.Array.IArray ((!), listArray)\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftL)\nimport Data.Char (ord)\nimport Data.Int (Int64)\nimport Data.IntMap.Strict (IntMap, (!?), empty, insert)\nimport Data.List (group)\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence\n ( Seq\n , Seq((:<|))\n , Seq((:|>))\n , Seq(Empty)\n , (><)\n , fromList\n , index\n , spanl\n , spanr\n , update\n )\nimport qualified Data.Sequence as S (length, replicate, splitAt)\nimport GHC.TypeNats (KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField 998244353\n\ntype Hash = IntMap MField\n\ndata Node =\n Node\n { getIndex :: !Int\n , getValue :: !Int\n , getExt :: !Int\n }\n deriving (Show, Eq)\n\nhash l r = l `shiftL` 10 .|. r\n\n{-# INLINE hash #-}\nmm = 998244353 :: Int64\n\nmadd :: Int64 -> Int64 -> Int64\nmadd a b\n | a + b < mm = a + b\n | otherwise = (a + b) - mm\n\n{-# INLINE madd #-}\nmmul :: Int64 -> Int64 -> Int64\nmmul a b = a * b `mod` mm\n\n{-# INLINE mmul #-}\nsearch ::\n forall s.\n (UArray Int Int, UArray Int Int)\n -> STUArray s Int Int64\n -> (Int, Int)\n -> ST s ()\nsearch (value, ext) mem (left, right)\n | left == right = return ()\n | otherwise = do\n let hc = hash left right\n mlo =\n foldl\n (\\mm i ->\n mm >>= \\m ->\n if ext ! i >= right\n then Nothing\n else Just (min m (value ! i)))\n (Just (value ! left))\n [left .. right - 1]\n ret <-\n case mlo of\n Nothing -> return 0\n Just lo ->\n let loop f s i\n | f i = loop f s (s i)\n | otherwise = i\n findNext = loop ((/=) lo . (value !))\n !lp = findNext succ left\n !rp = findNext pred (right - 1)\n lov = single (lp, rp)\n single (l, r)\n | l == r = return 1\n | value ! l == lo = single (l + 1, r)\n | otherwise =\n liftA2 mmul (readArray mem (hash l l')) (single (l', r))\n where\n l' = findNext succ l\n lv = match (left, left, lp)\n rv = match (rp + 1, rp + 1, right)\n match (l, m, r)\n | m > r = return 0\n | m == r = readArray mem (hash l m)\n | otherwise =\n let m' = (ext ! m) + 1\n in liftA2\n madd\n (liftA2\n mmul\n (readArray mem (hash l m))\n (readArray mem (hash m r)))\n (match (l, m', r))\n in liftA2 mmul lov (liftA2 mmul lv rv)\n writeArray mem hc ret\n\nsolve :: Int -> [Int] -> Int64\nsolve n a = runST recur\n where\n a' = reverse (zip a [0 ..])\n es = evalState (mapM findNext a') (S.replicate (n + 1) (-1))\n findNext :: (Int, Int) -> State (Seq Int) Int\n findNext (v, i) = do\n next <- get\n let p = index next v\n put (update v i next)\n if p == -1\n then return i\n else return p\n m = length a\n value = listArray (0, m - 1) a :: UArray Int Int\n ext = listArray (0, m - 1) (reverse es) :: UArray Int Int\n recur :: forall s. ST s Int64\n recur = do\n mem <- newArray (0, 1 `shiftL` 20) 1 :: ST s (STUArray s Int Int64)\n sequence_\n [ search (value, ext) mem (left, left + len)\n | len <- [1 .. m]\n , left <- [0 .. m - len]\n ]\n readArray mem (hash 0 m)\n\nmain = do\n [n, m] <- fmap parseInts getLine\n a <- fmap parseInts getLine\n let a' = group a\n if length a' > 2 * n\n then print 0\n else print . solve n . fmap head $ a'\n"}], "negative_code": [], "src_uid": "50b33796ccbc4c6e4e7347f9a101f67f"} {"source_code": "import Data.Function (on)\r\nimport Data.List\r\n\r\n-- code --\r\n\r\ndata Task = Task { n :: Int\r\n , k :: Int\r\n , points :: [Int]\r\n } deriving (Show)\r\n\r\ndata Answer = Answer {num :: Int}\r\n\r\nbiteTask :: String -> (Task, String)\r\nbiteTask str = let line1:line2:_ = lines str\r\n [n,k] = map read $ words line1\r\n points = map read $ words line2\r\n in (Task {n=n, k=k, points=points}, dropLines 2 str)\r\n\r\nshowAns :: Answer -> String\r\nshowAns Answer {num = ans} = show ans\r\n\r\nsolve_task :: Task -> Answer\r\nsolve_task Task { n=n\r\n , points = points\r\n } = let dist_list = sort $ map (n-) points\r\n runaway = 0 : scanl1 (+) dist_list\r\n saved = takeWhile (\\(acc,x) -> n - acc > x) $ zip runaway dist_list\r\n in Answer { num = length saved }\r\n\r\n-- //// --\r\n\r\nyesNo False = \"NO\"\r\nyesNo True = \"YES\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nreadBigInt :: String -> Integer\r\nreadBigInt = read\r\n\r\ndropLines _ \"\" = \"\"\r\ndropLines 0 text = text\r\ndropLines n ('\\n':xs) = dropLines (n-1) xs\r\ndropLines n (x:xs) = dropLines n xs\r\n\r\ntype Tasks = [Task]\r\ntype Answers = [Answer]\r\n\r\nreadTasks :: String -> Tasks\r\nreadTasks \"\" = []\r\nreadTasks input = let (task, input') = biteTask input \r\n in task : readTasks input'\r\n\r\nshowAnswers :: Answers -> String\r\nshowAnswers [] = \"\"\r\nshowAnswers (ans : anss) = showAns ans ++ \"\\n\" ++ showAnswers anss\r\n\r\nsolve :: String -> String\r\nsolve = showAnswers . map solve_task . readTasks . dropLines 1\r\n\r\nmain = interact solve", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, xs :: [Int]}\n\ninput :: Scanner TC\ninput = do\n n <- int\n xs <- numberOf int\n return TC {..}\n\noutput = showB\n\nsolve :: TC -> Int\nsolve TC {..} = length . takeWhile (< n) . scanl1 (+) . sort . map (n - ) $ xs\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad (replicateM_, forM_, forM)\r\nimport Data.List (sort)\r\n\r\nnextList :: IO [Int]\r\nnextList = map read.words <$> getLine\r\n\r\ngo :: [Int] -> Int -> Int\r\ngo [] _ = 0\r\ngo (a : as) x = if a > x then 0 else go as (x - a) + 1\r\n\r\nsolve = do\r\n [n, k] <- nextList\r\n a <- nextList\r\n print $ go (sort $ map (n -) a) (n - 1)\r\n\r\nmain = do\r\n [t] <- nextList\r\n replicateM_ t solve\r\n "}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n [n, _k] <- readListLn\r\n miceCoords <- readListLn\r\n return (n, miceCoords)\r\n\r\nreadListLn = map read <$> words <$> getLine :: IO [Integer]\r\n\r\nsolve (n, xs) = show . length . takeWhile ( Int\nmaxNoOfMice (n, ms) = \n let costs = sort $ map (n -) ms\n (c, _) = foldl countSteps (0, 0) costs\n in c\n where countSteps (count, total) x = \n if total + x < n then (count + 1, total + x) else (count, total)\n\nmain :: IO ()\nmain = do\n num_of_inputs <- getLine\n list_of_inputs <- replicateM (read num_of_inputs) getInput\n let ans = map maxNoOfMice list_of_inputs \n traverse_ (putStrLn . show) ans\n\n"}], "negative_code": [], "src_uid": "fd1b846c46a074f6afa1fa6e2844c3e2"} {"source_code": "{-# LANGUAGE FunctionalDependencies, FlexibleInstances #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List\n\ntype Input = ([[Int]], [Int])\ntype Output = [Int]\n\nparse :: [String] -> Input\nparse = evalState $ do\n n <- read <$> readLine\n g <- parseG <$> replicateM n readLine\n d <- parseD <$> readLine\n return (g, d)\n where readLine = state (head &&& tail)\n parseG = map (map (\\c -> ord c - 48))\n parseD = map read . words\n\nsolve :: Input -> Output\nsolve (g, d) = sort (foo d)\n where foo a = case elemIndex 0 a of\n Nothing -> []\n Just i -> i : foo (zipWith (-) a (g !! i))\n\npprint :: Output -> IO ()\npprint a = putStr (unlines ls)\n where ls = [show (length a), unwords (map (show . (+1)) a)]\n\nmain :: IO ()\nmain = pprint . solve . parse . lines =<< getContents\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n get :: m s\n put :: s -> m ()\n\n-- modify :: (MonadState s m) => (s -> s) -> m ()\n-- modify f = do\n-- s <- get\n-- put (f s)\n--\n-- gets :: (MonadState s m) => (s -> a) -> m a\n-- gets f = do\n-- s <- get\n-- return (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n fmap f m = State $ \\s -> let\n (a, s') = runState m s\n in (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= k = State $ \\s -> let\n (a, s') = runState m s\n in runState (k a) s'\n\ninstance MonadState s (State s) where\n get = State $ \\s -> (s, s)\n put s = State $ const ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\n-- execState :: State s a -> s -> s\n-- execState m s = snd (runState m s)\n--\n-- mapState :: ((a, s) -> (b, s)) -> State s a -> State s b\n-- mapState f m = State $ f . runState m\n--\n-- withState :: (s -> s) -> State s a -> State s a\n-- withState f m = State $ runState m . f\n\nstate :: (s -> (a, s)) -> State s a\nstate = State\n-- }}}\n", "positive_code": [{"source_code": "{-# LANGUAGE FunctionalDependencies, FlexibleInstances #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List\n\ntype Input = ([[Int]], [Int])\ntype Output = [Int]\n\nparse :: [String] -> Input\nparse = evalState $ do\n n <- read <$> readLine\n g <- parseG <$> replicateM n readLine\n d <- parseD <$> readLine\n return (g, d)\n where readLine = state (head &&& tail)\n parseG = map (map (\\c -> ord c - 48))\n parseD = map read . words\n\nsolve :: Input -> Output\nsolve (g, d) = sort (foo d)\n where foo a = case findIndex (== 0) a of\n Nothing -> []\n Just i -> i : foo (zipWith (-) a (g !! i))\n\npprint :: Output -> IO ()\npprint a = putStr (unlines ls)\n where ls = [show (length a), unwords (map (show . (+1)) a)]\n\nmain :: IO ()\nmain = pprint . solve . parse . lines =<< getContents\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n get :: m s\n put :: s -> m ()\n\n-- modify :: (MonadState s m) => (s -> s) -> m ()\n-- modify f = do\n-- s <- get\n-- put (f s)\n--\n-- gets :: (MonadState s m) => (s -> a) -> m a\n-- gets f = do\n-- s <- get\n-- return (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n fmap f m = State $ \\s -> let\n (a, s') = runState m s\n in (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= k = State $ \\s -> let\n (a, s') = runState m s\n in runState (k a) s'\n\ninstance MonadState s (State s) where\n get = State $ \\s -> (s, s)\n put s = State $ const ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\n-- execState :: State s a -> s -> s\n-- execState m s = snd (runState m s)\n--\n-- mapState :: ((a, s) -> (b, s)) -> State s a -> State s b\n-- mapState f m = State $ f . runState m\n--\n-- withState :: (s -> s) -> State s a -> State s a\n-- withState f m = State $ runState m . f\n\nstate :: (s -> (a, s)) -> State s a\nstate = State\n-- }}}\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FunctionalDependencies, FlexibleInstances #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Debug.Trace\n\ntype Input = ([[Int]], [Int])\ntype Output = [Int]\n\nparse :: [String] -> Input\nparse = evalState $ do\n n <- read <$> readLine\n g <- parseG <$> replicateM n readLine\n d <- parseD <$> readLine\n return (g, d)\n where readLine = state (head &&& tail)\n parseG = map (map (\\c -> ord c - 48))\n parseD = map read . words\n\nsolve :: Input -> Output\nsolve (g, d) = sort (foo d)\n where foo a = case find (== 0) a of\n Nothing -> []\n Just i -> i : foo (zipWith (-) a (g !! i))\n\npprint :: Output -> IO ()\npprint a = putStr (unlines ls)\n where ls = [show (length a), unwords (map (show . (+1)) a)]\n\nmain :: IO ()\nmain = pprint . solve . parse . lines =<< getContents\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n get :: m s\n put :: s -> m ()\n\n-- modify :: (MonadState s m) => (s -> s) -> m ()\n-- modify f = do\n-- s <- get\n-- put (f s)\n--\n-- gets :: (MonadState s m) => (s -> a) -> m a\n-- gets f = do\n-- s <- get\n-- return (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n fmap f m = State $ \\s -> let\n (a, s') = runState m s\n in (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= k = State $ \\s -> let\n (a, s') = runState m s\n in runState (k a) s'\n\ninstance MonadState s (State s) where\n get = State $ \\s -> (s, s)\n put s = State $ const ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\n-- execState :: State s a -> s -> s\n-- execState m s = snd (runState m s)\n--\n-- mapState :: ((a, s) -> (b, s)) -> State s a -> State s b\n-- mapState f m = State $ f . runState m\n--\n-- withState :: (s -> s) -> State s a -> State s a\n-- withState f m = State $ runState m . f\n\nstate :: (s -> (a, s)) -> State s a\nstate = State\n-- }}}\n"}], "src_uid": "794b0ac038e4e32f35f754e9278424d3"} {"source_code": "import Control.Monad\n\nisEquilibrium :: [Int] -> Bool\nisEquilibrium [0, 0, 0] = True\nisEquilibrium [a, b, c] = False\n\ngetAnswer :: Bool -> String\ngetAnswer True = \"YES\"\ngetAnswer False = \"NO\"\n\nsumOfVectors :: [Int] -> [Int] -> [Int]\nsumOfVectors [x, y, z] [] = [x, y, z]\nsumOfVectors [] [x, y, z] = [x, y, z]\nsumOfVectors [x1, y1, z1] [x2, y2, z2] = [x1 + x2, y1 + y2, z1 + z2]\n\nsumOfAllVectors :: [[Int]] -> [Int]\nsumOfAllVectors a = foldr sumOfVectors [0, 0, 0] a\n\ntoVec :: [String] -> [Int]\ntoVec a = map read a\n\nmain :: IO ()\nmain = do\n k <- getLine\n\n v <- replicateM (read k) (fmap (toVec . words) getLine)\n\n putStrLn $ getAnswer $ isEquilibrium\n $ sumOfAllVectors v\n", "positive_code": [{"source_code": "main = interact $f.tail.words\n\nf inp = (fadd (unzip3 (parse (map read inp :: [Integer]))))\nparse [] = []\nparse (x:y:z:xs) = (x, y, z):parse xs\n\nfadd (a, b, c)\n | 0 == sum a && 0 == sum a && 0 == sum a = \"YES\"\n | otherwise = \"NO\"\n"}, {"source_code": "main = do\n getLine\n ts <- fmap (map (map read . words) . lines) getContents\n \n let s = foldl1 (\\[a, b, c] [d, e, f] -> [a+d, b+e, c+f]) ts\n putStrLn $ if s == [0, 0, 0] then \"YES\" else \"NO\""}, {"source_code": "import Control.Monad\n\ndata Answer = YES | NO deriving (Show)\n\nzeroVector :: [Integer]\nzeroVector = [0, 0, 0]\n\nisBalanced :: [[Integer]] -> [Integer]\nisBalanced [] = [0, 0, 0]\nisBalanced (first:rest) = add first (isBalanced rest)\n\nadd :: [Integer] -> [Integer] -> [Integer]\nadd [a, b, c] [x, y, z] = [a+x, b+y, c+z]\nadd list anotherList = [0, 0, 0]\n\ngetLines :: Int -> IO [String]\ngetLines t = replicateM t getLine\n\ntoNumbers :: [String] -> [[Integer]]\ntoNumbers [] = []\ntoNumbers (first:rest) = [(map read (words first))] ++ (toNumbers rest)\n\ngetAnswer :: [String] -> Answer\ngetAnswer list = if isBalanced (toNumbers list) == zeroVector\n then YES\n else NO\n\nmain :: IO ()\nmain = do\n n <- getLine\n list <- getLines (read n)\n print (getAnswer list)"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do\n n <- readLn :: IO Int\n points <- map (map read . words) <$> replicateM n getLine :: IO [[Int]]\n let ans = foldr (\\p1 p2 -> zipWith (+) p1 p2) [0,0,0] points\n putStrLn $ if all (==0) ans then \"YES\" else \"NO\"\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (foldl1')\nimport Control.Monad (replicateM)\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nmain :: IO ()\nmain = putStrLn . check . map readInts =<< flip replicateM getLine =<< readLn\n where check = toYesNo . all (==0) . foldl1' (zipWith (+))\n toYesNo True = \"YES\"\n toYesNo False = \"NO\""}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine\n final <- foldl' (\\acc' _ -> do\n acc <- acc'\n v <- ( map read . words ) `liftM` getLine\n return $ zipWith (+) acc v\n ) (return [0, 0, 0]) [1..n]\n\n putStrLn $ if final == [0, 0, 0]\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "\nmain = do\n\tn<-getLine\n\trest<-getContents\n\tlet v =map (map read) $ map words $ lines rest\n\tif solve v 0 0 0 == [0,0,0] then putStrLn \"YES\" else putStrLn \"NO\"\n\n\nsolve [] xc yc zc = [xc,yc,zc] \nsolve ([x,y,z]:rest) xc yc zc = solve rest (xc+x) (yc+y) (zc+z)"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.List (foldl')\n\n(-->) = flip fmap\n\naddTriple :: Num a => (a,a,a) -> (a,a,a) -> (a,a,a)\naddTriple (a,b,c) (x,y,z) = (a+x,b+y,c+z)\n\nsumTriples :: Num a => [(a,a,a)] -> (a,a,a)\nsumTriples = foldl' addTriple (0,0,0)\n\nreadTriple :: (Num a, Read a) => IO (a,a,a)\nreadTriple = do\n (a:b:c:_) <- getLine --> words --> map read\n return (a,b,c)\n\nmain = do\n n <- getLine --> read\n (a,b,c) <- (replicateM n readTriple) --> sumTriples\n let _ = a :: Int\n if (a == 0 && b == 0 && c == 0)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n"}, {"source_code": "import Control.Monad\n\n(|>) x f = f x\n \nmain = do\n l1 <- getLine\n vecs <- replicateM (read l1) getLine\n let vectors = vecs |> map words |> map (map read) :: [[Int]]\n if solve vectors then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n \nsolve vectors = sumNth vectors 0 == 0 \n && sumNth vectors 1 == 0 \n && sumNth vectors 2 == 0 \n\nsumNth vectors n = vectors |> map (\\x -> x !! n) |> sum"}, {"source_code": "import List\nmain = interact (s.lines)\ns (sn:xs) = if (foldl1 (zipWith (+)) $ map ((map read).words) xs)==[0,0,0] then \"YES\" else \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = do cs <- getContents\n let nums = map read $ words cs\n n = head nums\n mat = tail nums\n zmat = zip [0..] mat\n sums = map (sumup zmat) [0..2]\n oks = map (== 0) sums\n ans = and oks\n putStrLn $ if ans then \"YES\" else \"NO\"\n where sumup xs i = sum $ map snd $ filter ((\\x -> x `mod` 3 == i) . fst) xs\n"}, {"source_code": "\n\nmain = do\n\t\t\tn <- getLine\n\t\t\tl <- getContents\n\t\t\tputStr $ func $ sumV (trans l)\n\t\t\ntrans = map (ctoc.line) . lines \n\t\twhere \n\t\t\tline = map read . words\n\t\t\tctoc [x,y,z] = (x,y,z) \nsumV l = foldr (sumcort) (0,0,0) l\n\t\twhere\n\t\t\t\tsumcort (x,y,z) (x',y',z') = (x+x',y+y', z+z')\nfunc a = if a == (0,0,0) then \"YES\" else \"NO\"\n "}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\x -> interact $ solve . map (map read .words).take (read x) . lines\nsolve :: [[Int]]->String\nsolve xss =if foldr (\\[a,b,c] [a1,b1,c1] -> [a+a1,b+b1,c+c1]) [0,0,0] xss ==[0,0,0] then \"YES\" else \"NO\""}, {"source_code": "type Vec3 = (Integer, Integer, Integer)\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs\n\nread_inputs :: Integer -> IO [Vec3]\nread_inputs k = if k > 0\n then do\n input <- getLine\n let xs = map (read :: String -> Integer) (split ' ' input)\n let a = (xs !! 0, xs !! 1, xs !! 2)\n b <- read_inputs (k - 1)\n return (a : b)\n else return []\n\nadd_vector :: Vec3 -> Vec3 -> Vec3\nadd_vector (a, b, c) (x, y, z) = (a + x, b + y, c + z)\n\nprocess :: [Vec3] -> Bool\nprocess xs =\n let res = foldl1 (\\x y -> add_vector x y) xs\n in if res == (0, 0, 0) then True else False\n\nmain :: IO ()\nmain = do\n k <- getLine\n let (x', _) = span (\\x -> elem x ['0' .. '9']) k\n xs <- read_inputs (read x')\n let result = process xs\n if result then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "main = do\n n <- readLn\n v <- readlist n\n putStrLn $ if (solve v) then \"YES\" else \"NO\"\nsolve :: [(Int, Int, Int)] -> Bool\nsolve x = (0, 0, 0) == foldr (\\(a, b, c) -> \\(d, e, f) -> (a + d, b + e, c + f)) (0, 0, 0) x\nreadlist :: Int -> IO [(Int, Int, Int)]\nreadlist 0 = return []\nreadlist n = do\n s <- getLine\n let [a, b, c] = map read (words s)\n d <- readlist (n - 1)\n return $ (a, b, c) : d"}, {"source_code": "import Control.Monad\nint x = read x ::Int \n\nvectoradd (x:xs) = foldr (\\x acc -> zipWith (+) x acc) x xs \n\nmain = do\n n <- liftM int getLine\n vs <- liftM (map (map int. words)) $ replicateM n getLine \n let v = vectoradd vs\n putStrLn $ if v == [0,0,0] then \"YES\" else \"NO\"\n"}, {"source_code": "{-#LANGUAGE OverloadedStrings#-}\nmodule Main where\n\nimport qualified Data.Text as T\nimport Data.List\n\nmain :: IO ()\nmain = do\n ns <- getLine\n let n = read ns :: Integer\n res <- getL n []\n let res2 = (transpose . reverse) res\n allz = foldr (\\x acc -> sum x == 0 && acc) True res2\n if allz then putStrLn \"YES\"\n else putStrLn \"NO\"\n pure ()\n\n\ngetL :: Integer -> [[Integer]] -> IO [[Integer]]\ngetL 0 acc = pure acc\ngetL n acc = do\n str <- getLine\n let l = map ((read :: String -> Integer) . T.unpack) \n (T.splitOn \" \" . T.pack $ str)\n getL (n-1) (l : acc)\n\n"}, {"source_code": "readLine :: Integer -> IO String\nreadLine _ = getLine\n\nparseLine :: String -> (Int, Int, Int)\nparseLine s = (p1, p2, p3)\n where\n ss = words s\n p1 = read (ss !! 0)\n p2 = read (ss !! 1)\n p3 = read (ss !! 2)\n\nmyAdd :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)\nmyAdd (a1, b1, c1) (a2, b2, c2) = (a1 + a2, b1 + b2, c1 + c2)\n\nsolve :: (Int, Int, Int) -> String\nsolve (0, 0, 0) = \"YES\"\nsolve _ = \"NO\"\n\nmain = do\n s <- getLine\n n <- return (read s)\n lines <- sequence (map readLine [1..n])\n powers <- return (map parseLine lines)\n ans <- return (foldl myAdd (0, 0, 0) powers)\n putStr (solve ans)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\ndata Vec = V Int Int Int\n\nplus (V x1 y1 z1) (V x2 y2 z2) = V (x1+x2) (y1+y2) (z1+z2)\nnul (V a b c) = all (==0) [a,b,c]\n\ncr [a,b,c] = V a b c\n\nparse = map (cr . map read . words)\n\nmain = do\n n <- read <$> getLine\n xs <- parse <$> replicateM n getLine\n let res = foldl1 plus xs\n putStrLn $\n if nul res then \"YES\" else \"NO\"\n"}, {"source_code": "solve input = if (xx == 0 && yy == 0 && zz == 0) then\n \"YES\"\n else\n \"NO\"\n where (xx, yy, zz) = foldl (\\(x1, y1, z1) (x2, y2, z2) -> (x1 + x2, y1 + y2, z1 + z2)) (0, 0, 0) coords\n coords = map f (tail $ lines input)\n f s = \n case map (read :: String -> Integer) (words s) of\n [x, y, z] -> (x, y, z)\n _ -> undefined\n\nmain = interact solve"}, {"source_code": "import Control.Monad\n\nmain = readInt\n >>= readVectors\n >>= (putStrLn . decide . sumVectors . parseVectors)\n \n \nreadInt::IO Int\nreadInt = readLn\n\nreadVectors::Int -> IO [String]\nreadVectors n = mapM (\\_ -> getLine) [1..n]\n\nparseVectors::[String] -> [[Int]]\nparseVectors strs = map (toVector . words) strs\n where toVector strs' = map read strs'\n \nsumVectors::[[Int]] -> [Int]\nsumVectors vectors = foldr sumVectors' [0, 0, 0] vectors\n where sumVectors' a b = sumPairs $ zip a b\n sumPairs pairs = map sumPair pairs\n sumPair pair = (+) (fst pair) (snd pair)\n \ndecide::[Int] -> String\ndecide [0, 0, 0] = \"YES\"\ndecide _ = \"NO\""}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [[Int]] -> Bool\nsolve = (==[0,0,0]) . foldl1 (zipWith (+))\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n a <- replicateM n getIntList\n putStrLn $ if solve a then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nmain=interact$f.map sum.transpose.map(map read.words).tail.lines\nf x|all(==0)x=\"YES\"|1>0=\"NO\""}, {"source_code": "\nimport Control.Applicative\nimport Data.List\n\n\n\nmain=do\n getLine\n a<- map sum <$> transpose <$> map (map read) <$> map words <$> lines<$>getContents\n putStrLn $ if a==[0,0,0] then \"YES\" else \"NO\"\n"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\n\nmain = interact $ lines >>> tail >>> map (words >>> map read) >>>\n foldl1 (zipWith (+)) >>> all (==0) >>> fromEnum >>> ([\"NO\",\"YES\"]!!)"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\n\nmain = interact $ lines >>> tail >>>\n map (words >>> map read) >>>\n transpose >>> find (sum >>> (/=0)) >>> maybe \"YES\" (const \"NO\")"}, {"source_code": "import Data.List (foldl')\n\nmain :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Bool\nsolve = all (==0) . foldl' (zipWith (+)) [0, 0, 0]\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "data Force = Force Int Int Int deriving (Show)\n\nmakeForce :: String -> Force\nmakeForce s = Force x y z\n where x = read $ w !! 0\n y = read $ w !! 1\n z = read $ w !! 2\n w = words s\n\nadd :: Force -> Force -> Force\nadd (Force a b c) (Force d e f) = Force (a + d) (b + e) (c + f)\n\nequilAcc :: [String] -> Force -> String\nequilAcc [] (Force x y z)\n | x == 0 && y == 0 && z == 0 = \"YES\"\n | otherwise = \"NO\"\nequilAcc (l:ls) f = equilAcc ls (add f (makeForce l))\n\nequil :: String -> String\nequil s = equilAcc ls (Force 0 0 0)\n where ls = lines s\n\nmain = do\n getLine\n interact equil\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nmain = do\n n <- readLn\n cs <- replicateM n $ fmap (ZipList . map read . words) getLine\n putStrLn $ if all (==0) (getZipList (foldr1 (liftA2 (+)) cs)) then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n [n] :: [Int] <- map read <$> words <$> getLine\n as :: [[Int]] <- replicateM n (map read <$> words <$> getLine)\n putStrLn $ if all (== 0) $ foldl1 (zipWith (+)) as then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Monad\nmain = do\n n <- getLine\n vectors <- forM [1..read n] (\\_ -> do\n v_i <- getLine\n let [a,b,c] = map read . words $ v_i\n return (a,b,c))\n let vectorsSum = foldl1 (\\(a,b,c) (d,e,f) -> (a+d,b+e,c+f)) vectors\n putStrLn $ if vectorsSum == (0,0,0) then \"YES\" else \"NO\"\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/69/A\n\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: [[Int]] -> Bool\nsolve = (==[0,0,0]) . foldl1 (zipWith (+))\n\nmain = do\n n <- fmap read getLine\n a <- replicateM n getIntList\n putStrLn $ if solve a then \"YES\" else \"NO\"\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n"}, {"source_code": "p [0,0,0] = \"YES\"\np _ = \"NO\"\nmain = interact $ p . foldr1 (zipWith (+)) . map (map read . words) . tail . lines"}, {"source_code": "main = interact $ test . foldl addTuples (0,0,0) . cps . map read . tail . words\n\ncps (x:y:z:xs) = (x,y,z):cps(xs)\ncps _ = []\n\naddTuples (a1,b1,c1) (a2,b2,c2) = (a1+a2,b1+b2,c1+c2)\n\ntest (a,b,c) = if a == 0 && b == 0 && c == 0 then \"YES\" else \"NO\""}, {"source_code": "main = interact $ test . foldl addTuples (0,0,0) . cps . map read . tail . words\n\ncps (x:y:z:xs) = (x,y,z):cps(xs)\ncps _ = []\n\naddTuples (a1,b1,c1) (a2,b2,c2) = (a1+a2,b1+b2,c1+c2)\n\ntest (a,b,c) = if a == 0 && b == 0 && c == 0 then \"YES\" else \"NO\""}, {"source_code": "import Data.List\nmain = do\n n <- read `fmap` getLine\n l <- mapM (\\_-> (map read . words) `fmap` getLine) [1..n]\n let s = foldl (\\s x -> s + abs x) 0 $ foldl (zipWith (+)) [0, 0, 0] l\n putStrLn (if s == 0 then \"YES\" else \"NO\")\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\ncheck num = if all (\\x -> sum x == 0) num then \"YES\" else \"NO\"\n\nmain = do\n n <- readLn\n num <- replicateM n f\n putStrLn $ check (transpose num)\n where f :: IO [Int]\n f = fmap (map read . words) getLine\n"}, {"source_code": "--In matrix rows values should be space separated\ninputNumMatrix :: Int -> IO [[Int]]\ninputNumMatrix nRows =\n sequence $ replicate nRows (map read . words <$> getLine)\n\nsumRows :: [[Int]] -> [Int]\nsumRows matrix = foldr (zipWith (+)) initAcc matrix\n where\n nColumns = length $ head matrix\n initAcc = replicate nColumns 0\n\n--mapM :: (Monad m) => (a -> m b) -> [a] -> m [b]\n\nmain :: IO ()\nmain = (read <$> getLine) >>= inputNumMatrix >>= \n (\\ matrix -> \n if all (==0) (sumRows matrix)\n then putStrLn \"YES\"\n else putStrLn \"NO\")"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n k <- getLine\n v <- replicateM (read k) $ fmap ((map read) . words) getLine\n putStrLn $ getAnswer $ sumOfAllVectors v\n where getAnswer xs\n | all (==0) xs = \"YES\"\n | otherwise = \"NO\"\n sumOfAllVectors xs = foldr (zipWith (+)) (replicate 3 0) xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\n\n \n\n \nmain= do\n\tgetLine \n\tx<- transpose. map (map read). map words.lines <$> getContents ::IO [[Int]]\n\tputStrLn $ if (map sum x) == [0,0,0] then \"YES\" else \"NO\"\n\t \n\t \n\t \n"}, {"source_code": "{-\nA. Young Physicist\n===================\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nA guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" \u2014 thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.\n\nInput\n------\nThe first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi,\u2009zi\u2009\u2264\u2009100).\n\nOutput\n------\nPrint the word \"YES\" if the body is in equilibrium, or the word \"NO\" if it is not.\n\nSample test(s)\n---------------\ninput\n3\n4 1 7\n-2 4 -1\n1 -5 -3\noutput\nNO\n\ninput\n3\n3 -1 7\n-5 2 -4\n2 -1 -3\noutput\nYES\n\n-}\n\nimport Data.List (transpose)\n\nisEquilibrium :: [[Int]] -> Bool\nisEquilibrium forces = all (\\xs -> sum xs == 0) (transpose forces)\n\nboolToStr :: Bool -> String\nboolToStr True = \"YES\"\nboolToStr False = \"NO\"\n\nreader :: String -> [[Int]]\nreader s = [map read (words line) | line <- tail (lines s)]\n\nmain = do \n input <- getContents\n let forces = reader input\n (putStrLn . boolToStr . isEquilibrium) forces\n\n\n"}, {"source_code": "main = do\n n <- readLn\n m <- sequence $ replicate n getLine \n let m2 = map (map read . words) m\n if (equil m2) then putStrLn \"YES\" else putStrLn \"NO\"\nequil :: [[Int]] -> Bool\nequil x = (foldl (\\[y1, y2, y3] [z1, z2, z3] -> [y1+z1, y2+z2, y3+z3]) [0, 0, 0] x) == [0, 0, 0]"}, {"source_code": "solve l n \n | all (0==) [sum [l !! i !! j | i <- [0 .. n - 1]] | j <- [0 .. 2]] = \"YES\"\n | otherwise = \"NO\"\nmain = do\n n <- readLn :: IO Int\n l <- getContents >>= return.map (map read. words).lines:: IO [[Integer]]\n putStrLn.solve l $ n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n vectors <- map (map (read :: String -> Int) . words) <$> replicateM n getLine \n let sums = map sum $ transpose vectors\n putStrLn $ if sums == [0, 0, 0] then \"YES\" else \"NO\""}, {"source_code": "import Control.Monad.State\nimport Data.List\n\ncountVerdict :: StateT [Integer] IO ()\ncountVerdict = do\n a <- lift getLine\n forM_ [1 .. read a] $ \\_ -> do\n input <- lift getLine\n modify $ zipWith (+) $ read <$> words input\n\nsomeFunc :: IO ()\nsomeFunc = execStateT countVerdict [0, 0, 0] >>= (\\s -> putStrLn $ if all (== 0) s then \"YES\" else \"NO\")\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = getLine >>= flip replicateM getLine.read\n >>= answer.succ.sum.map (abs.sum.map read).transpose.map words\nanswer = putStrLn.last.flip take (\"YES\":repeat \"NO\")\n"}, {"source_code": "import Data.List (transpose)\n\nprocess :: [[Int]] -> Bool\nprocess = all (==0).map sum.transpose\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xss <- fmap (map (map readInt.words).lines) getContents\n putStrLn $ [\"NO\",\"YES\"] !! fromEnum (process xss)"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain :: IO ()\nmain = interact $ f . map sum . transpose . map (map read.words) . tail . lines\n\nf :: (Num a, Eq a, Foldable t) => t a -> String\nf x | all (==0) x = \"YES\"\n | otherwise = \"NO\"\n"}, {"source_code": "getLines :: Int -> IO [String]\ngetLines n \n\t\t| n==0 = return []\n\t\t| otherwise = do\n\t\t\tstr <- getLine\n\t\t\tothers <- getLines (n-1)\n\t\t\treturn (str:others)\n\ngetVector :: String -> [Int]\ngetVector str = map (read :: String -> Int) $ words str\n\nsumElems :: [[Int]] -> [Int]\nsumElems vectors = foldl (\\ (x:y:z:[]) (x':y':z':xs) -> ( (x+x'):(y+y'):(z+z'):[] ) ) [0,0,0] vectors\n\nmain = do\n\tcountStr <- getLine\n\tlet count = read countStr\n\tvectorStrs <- getLines count\n\tlet vectors = map getVector vectorStrs\n\tlet mainVector = sumElems vectors\n\tif all (==0) mainVector then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "equilibrium :: [[Int]] -> Bool\nequilibrium = all (== 0) . foldl (zipWith (+)) [0,0,0]\n\nsolve :: String -> String\nsolve s\n | equilibrium xs = \"YES\"\n | otherwise = \"NO\"\n where _:ls = lines s\n xs = fmap (fmap read . words) $ ls\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "f = (\\x->if x then\"YES\"else\"NO\").all (==0).foldl1 (zipWith (+))\nmain = interact $ f.map (map read.words).tail.lines\n"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Maybe as Maybe\n\nreadAsInt :: String -> Int\nreadAsInt str = read str :: Int\n\nfoldCoordinate :: Int -> [[Int]] -> Int\nfoldCoordinate index vectorList = foldl (\\acc elem -> let coord = elem !! index in acc + coord) 0 vectorList\n\nisEquilibrium :: [[Int]] -> String\nisEquilibrium vectorList = \n\tif xTotal == 0 && (yTotal == 0 && zTotal == 0)\n\tthen \"YES\"\n\telse \"NO\"\n\twhere xTotal = foldCoordinate 0 vectorList; yTotal = foldCoordinate 1 vectorList; zTotal = foldCoordinate 2 vectorList\n\nsolveCase :: Int -> [[Int]] -> IO ()\nsolveCase remainCase initial\n\t| remainCase > 0 = do\n\t\tline <- getLine\n\t\tlet vector = map readAsInt $ words line\n\t\tsolveCase (remainCase - 1) (vector : initial)\n\t| remainCase == 0 = putStrLn $ isEquilibrium initial\n\nmain = do\n\tline <- getLine\n\tlet vectorNum = readAsInt line\n\tsolveCase vectorNum []"}, {"source_code": "module Main where\n\nsolve :: [[Int]] -> String\nsolve l = if x == 0 && y == 0 && z == 0 then \"YES\" else \"NO\" where\n x = sum $ map (!! 0) l\n y = sum $ map (!! 1) l\n z = sum $ map (!! 2) l\n\nmain = do\n n <- getLine\n forces <- getContents\n putStrLn $ solve $ map ((map read).words) $ lines forces\n"}, {"source_code": "getLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines $ n-1\n\treturn (x:xs)\n\nmain = do\n\tn <- getLine >>= return.read :: IO Int\n\txyzs <- getLines n >>= return . (map $ map read . words) :: IO [[Int]]\n\tputStrLn $ if foldl (\\[x,y,z] [xx,yy,zz] -> [x+xx, y+yy, z+zz]) [0,0,0] xyzs == [0,0,0] then \"YES\" else \"NO\"\n"}, {"source_code": "\n\nsumelems ff a b c\n | (null ff) = if a == 0 && b == 0 && c == 0\n then True\n else False\n | otherwise = sumelems (tail ff)\n (a + (read (head (words (head ff))))::Int)\n (b + (read (head (drop 1 (words (head ff)))))::Int)\n (c + (read (head (drop 2 (words (head ff)))))::Int)\n\n\nmain = do\n ww <- getLine\n let yy = replicate ((read ww)::Int) getLine\n\n aa <- sequence yy\n let bb = sumelems aa 0 0 0\n if bb\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n\n\n\n\n \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n a <- replicateM n $ readItems\n putStrLn $ if all (== 0) $ map sum $ transpose a then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nmain = interact $ (\\x -> if x == True then \"YES\" else \"NO\") . all (== 0) . foldl1 (zipWith (+)) . map (map read . words) . tail . lines "}, {"source_code": "import Data.List\nimport Control.Monad\n\nparseVector :: String -> [Int]\nparseVector s = map (read :: String -> Int) . words $ s\n\nmain = do\n nl <- getLine\n let n = (read :: String -> Int) nl\n vectorStrings <- replicateM n getLine\n let vectors = map parseVector vectorStrings\n\n putStrLn (if (all (== 0) . map sum . transpose $ vectors) then \"YES\" else \"NO\")\n\n"}], "negative_code": [{"source_code": "main = do\n getLine\n ts <- fmap (map (map read . words) . lines) getLine\n \n let s = foldl1 (\\[a, b, c] [d, e, f] -> [a+d, b+e, c+f]) ts\n putStrLn $ if s == [0, 0, 0] then \"YES\" else \"NO\""}, {"source_code": "main :: IO ()\nmain = do cs <- getContents\n let nums = map read $ words cs\n n = head nums\n mat = tail nums\n zmat = zip [0..] mat\n sums = map (sumup zmat n) [0..2]\n oks = map (== 0) sums\n ans = and oks\n putStrLn $ if ans then \"YES\" else \"NO\"\n where sumup xs n i = sum $ map snd $ filter ((\\x -> x `mod` n == i) . fst) xs\n"}, {"source_code": "main :: IO ()\nmain = do cs <- getContents\n let nums = map read $ words cs\n n = head nums\n mat = tail nums\n zmat = zip [0..] mat\n sums = map (sumup zmat n) [0..n-1]\n oks = map (== 0) sums\n ans = and oks\n putStrLn $ if ans then \"YES\" else \"NO\"\n where sumup xs n i = sum $ map snd $ filter ((\\x -> x `mod` n == i) . fst) xs\n"}, {"source_code": "type Vec3 = (Integer, Integer, Integer)\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit _ [] = []\nsplit cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs\n\nread_inputs :: Integer -> IO [Vec3]\nread_inputs k = if k > 0\n then do\n input <- getLine\n let xs = map (read :: String -> Integer) (split ' ' input)\n let a = (xs !! 0, xs !! 1, xs !! 2)\n b <- read_inputs (k - 1)\n return (a : b)\n else return []\n\nadd_vector :: Vec3 -> Vec3 -> Vec3\nadd_vector (a, b, c) (x, y, z) = (a + x, b + y, c + z)\n\nprocess :: [Vec3] -> Bool\nprocess xs =\n let res = foldl1 (\\x y -> add_vector x y) xs\n in if res == (0, 0, 0) then True else False\n\nmain :: IO ()\nmain = do\n k <- getLine\n let (x', _) = span (\\x -> elem x ['0' .. '9']) k\n xs <- read_inputs (read x')\n let result = process xs\n if result then putStrLn \"Yes\" else putStrLn \"No\"\n"}, {"source_code": "import Data.List (foldl')\n\nmain :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Bool\nsolve = allsame . foldl' (zipWith (+)) [0, 0, 0]\n\nallsame :: Eq a => [a] -> Bool\nallsame xs = all (==head xs) xs\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "{-\nA. Young Physicist\n===================\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nA guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" \u2014 thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.\n\nInput\n------\nThe first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi,\u2009zi\u2009\u2264\u2009100).\n\nOutput\n------\nPrint the word \"YES\" if the body is in equilibrium, or the word \"NO\" if it is not.\n\nSample test(s)\n---------------\ninput\n3\n4 1 7\n-2 4 -1\n1 -5 -3\noutput\nNO\n\ninput\n3\n3 -1 7\n-5 2 -4\n2 -1 -3\noutput\nYES\n\n-}\n\nimport Data.List (transpose)\n\nisEquilibrium :: [[Int]] -> Bool\nisEquilibrium forces = all (\\xs -> sum xs == 0) (transpose forces)\n\nboolToStr :: Bool -> String\nboolToStr True = \"YES\"\nboolToStr False = \"NO\"\n\nreader :: String -> [[Int]]\nreader s = [map read (words line) | line <- lines xss]\n where _:xss = s\n\nmain = do \n input <- getContents\n let forces = reader input\n (putStrLn . boolToStr . isEquilibrium) forces\n\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = getLine >>= flip replicateM getLine.read\n >>= answer.succ.abs.sum.map (sum.map read).transpose.map words\nanswer = putStrLn.last.flip take (\"YES\":repeat \"NO\")"}, {"source_code": "getLines :: Int -> IO [String]\ngetLines n \n\t\t| n==0 = return []\n\t\t| otherwise = do\n\t\t\tstr <- getLine\n\t\t\tothers <- getLines (n-1)\n\t\t\treturn (str:others)\n\ngetVector :: String -> [Int]\ngetVector str = map (read :: String -> Int) $ words str\n\nsumElems :: [[Int]] -> [Int]\nsumElems vectors = foldl (\\ (x:y:z:[]) (x':y':z':xs) -> ( (x+x'):(y+y'):(z+z'):[] ) ) [0,0,0] vectors\n\nmain = do\n\tcountStr <- getLine\n\tlet count = read countStr\n\tvectorStrs <- getLines count\n\tlet vectors = map getVector vectorStrs\n\tlet mainVector = sumElems vectors\n\tif all (==0) mainVector then print \"YES\" else print \"NO\"\n"}], "src_uid": "8ea24f3339b2ec67a769243dc68a47b2"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n let readInts = map read . words . head\n d <- head . drop 1 . readInts\n bs <- readInts . drop 1\n let count (!prev, !moves) b\n | prev >= b = count (prev, moves + n) (b + d * n)\n | otherwise = (b, moves)\n where n = (prev - b) `quot` d + 1\n return . show . snd $ foldl' count (0, 0) bs\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n", "positive_code": [{"source_code": "solve :: Int -> [Int] -> Int\nsolve _ [] = 0\nsolve _ [_] = 0\nsolve d (x:y:zs) = cnt + solve d ((y+cnt*d):zs)\n\twhere cnt = max 0 $ (x - y + d) `div` d\n\nmain = do\n\tn:d:_ <- getLine >>= return . (map read) . words :: IO [Int]\n\tb <- getLine >>= return . (map read) . words :: IO [Int]\n\tputStrLn $ show $ solve d b\n"}, {"source_code": "extract (x:y:_)=(a,b,dat) where\n\t(a:b:_)=map (\\x->read x::Int) (words x)\n\tdat=map (\\x->read x::Int) (words y)\nsolve (a,delta,(x:xs)) = solve1 xs x delta\n\nsolve1 [] lst delta = 0\nsolve1 (x:xs) lst delta\n\t|x>lst = solve1 xs x delta\n\t|otherwise = cnt + solve1 xs (x+cnt*delta) delta \n\twhere\n\t\tcnt = (div (lst-x) delta)+1\n \n \nmain=interact$show.solve.extract.lines"}, {"source_code": "extract (x:y:_)=(a,b,dat) where\n\t(a:b:_)=map (\\x->read x::Int) (words x)\n\tdat=map (\\x->read x::Int) (words y)\nsolve (a,delta,(x:xs)) = solve1 xs x delta 0\n\nsolve1 [] lst delta counter = counter\nsolve1 (x:xs) lst delta counter\n\t|x>lst = solve1 xs x delta counter\n\t|otherwise = solve1 xs (x+cnt*delta) delta (counter+cnt)\n\twhere\n\t\tcnt = (div (lst-x) delta)+1\n \n \nmain=interact$show.solve.extract.lines"}, {"source_code": "module Main where\nimport Data.List\nmain = do\n [n,d] <- map (read :: String -> Int) . words <$> getLine\n bs <- map (read :: String -> Int) . words <$> getLine\n print $ fst $ foldl' (\\(a,b) x ->\n if x > b \n then (a,x)\n else \n let c = b-x+1\n e = c `div` d + if c `mod` d /= 0 then 1 else 0\n in (a+e,x+e*d)\n ) (0,head bs) $ tail bs"}, {"source_code": "\nsolve :: Int -> [Int] -> Int\nsolve d (x:xs) = solve' x xs\n where\n solve' _ [] = 0\n solve' x (y:ys)\n | y > x = solve' y ys\n | otherwise = n + solve' (y + n*d) ys\n where\n n = div (x - y) d + 1\n\n\nmain :: IO ()\nmain = do\n [n, d] <- getLine >>= return . map read . words\n xs <- getLine >>= return . map read . words\n print $ solve d xs\n "}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n d <- readInt\n a <- replicateM n readInt\n return (d, a)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve :: (Int, [Int]) -> Int\nsolve (d, x:y:zs) = delta + solve (d, (y + delta * d):zs)\n where\n delta = if x >= y then (x - y) `div` d + 1 else 0\nsolve _ = 0\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n let readInts = map read . words . head\n d <- head . drop 1 . readInts\n bs <- readInts . drop 1\n let count (!prev, !moves) b\n | prev >= b = count (prev, moves + n) (b + d * n)\n | otherwise = (b, moves)\n where n = (prev - b) `quot` d + 1\n return . show . snd $ foldl' count (0, 0) bs\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n let readInts = map read . words . head\n d <- head . drop 1 . readInts\n bs <- readInts . drop 1\n let count (!prev, !moves) !b\n | prev >= b = count (prev, moves + n) (b + d * n)\n | otherwise = (b, moves)\n where n = (prev - b) `quot` d + 1\n return . show . snd $ foldl' count (0, 0) bs\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n let readInts = map read . words . head\n d <- head . drop 1 . readInts\n bs <- readInts . drop 1\n let count (prev, !moves) !b\n | prev >= b = count (prev, moves + n) (b + d * n)\n | otherwise = (b, moves)\n where n = (prev - b) `quot` d + 1\n return . show . snd $ foldl' count (0, 0) bs\n\nmain :: IO ()\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "main = do\n [_,d] <- (read <$>) <$> words <$> getLine\n arr <- (read <$>) <$> words <$> getLine\n let red a b | a >= b = (a - b) `div` d + 1 \n | otherwise = 0\n sol (x1:x2:xs) = let add = red x1 x2 in add + sol (add * d + x2:xs)\n sol _ = 0\n print $ sol arr"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess n d [x] = n\nprocess n d (a:b:cs) | a words <$> getLine ::IO [Int]\n\t\ts<-map read <$> words <$> getLine ::IO [Int]\t\n\t\tprint $ process 0 d s\n"}], "negative_code": [{"source_code": "extract (x:y:_)=(a,b,dat) where\n\t(a:b:_)=map (\\x->read x::Int) (words x)\n\tdat=map (\\x->read x::Int) (words y)\nsolve (a,delta,(x:xs)) = solve1 xs x delta 0\n\nsolve1 [] lst delta counter = counter\nsolve1 (x:xs) lst delta counter\n\t|x>lst = solve1 xs x delta counter\n\t|otherwise = solve1 xs (lst+cnt*delta) delta (counter+cnt)\n\twhere\n\t\tcnt = (div (lst-x) delta)+1\n \n \nmain=interact$show.solve.extract.lines"}, {"source_code": "main = do\n getLine\n arr <- (read <$>) <$> words <$> getLine\n let \n sol acc _ [] = acc\n sol acc cnt (x:xs) = sol (acc + abs (x - cnt)) (succ cnt) xs\n print $ sol 0 1 arr"}], "src_uid": "0c5ae761b046c021a25b706644f0d3cd"} {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve ([s, _]:xys) = and $ zipWith (<) (map head xys') (scanl (+) s (map (!!1) xys'))\n where xys' = sort xys\nsolve _ = undefined\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ndata Answer = YES | NO deriving (Show)\n \ntoInt :: String -> Int\ntoInt str = read str\n \ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n \ngetAnswer :: [String] -> Int -> Answer\ngetAnswer list s = battle new s\n where new = sort $ cast list\n \ncast :: [String] -> [[Int]]\ncast [] = []\ncast (first:rest) = casted : cast rest\n where casted = map read (words first)\n \nbattle :: [[Int]] -> Int -> Answer\nbattle [] _ = YES\nbattle ([x, y]:rest) s = if s <= x\n then NO\n else battle rest (s + y)\n \nmain :: IO ()\nmain = do\n limits <- getLine\n let [s, n] = map toInt (words limits)\n list <- getLines n\n print $ getAnswer list s"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (sort, nub)\n\nprocess [] _ = True\nprocess ((dstr,dup):xs) kstr\n | kstr > dstr = process xs (kstr+dup)\n | otherwise = False\n\nmain = do\n [s,n] <- map read . words <$> getLine :: IO [Int]\n xs <- map (\\[a,b] -> (a,b)) . map (map read . words) <$> replicateM n getLine :: IO [(Int,Int)]\n putStrLn $ if process (sort xs) s then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetArray = fmap (map read . words) getLine\n\nmain = do\n [s, n] <- getArray\n a <- replicateM n getArray\n putStrLn $ (\\i -> if i > 0 then \"YES\" else \"NO\") $ foldl (\\z [x, y] -> if z > x then z + y else 0) s $ sort a\n"}, {"source_code": "import Data.List\n\nmain = do \n\tss<-getLine\n\tlet [s,n] = words ss\n\treading (read n) [] s\n\nreading 0 acc s = do\n\tlet d= map words $ acc\n\tlet d2=map (\\x->map read x) d\n\tputStrLn $ game (read s) (sort d2)\nreading n acc s = do\n\ttemp <-getLine\n\treading (n-1) (acc++[temp]) s\n\ngame s [] = \"YES\"\ngame s ([dragon,bonus]:dragons) | s<= dragon = \"NO\"\n | otherwise = game (s+bonus) (dragons)"}, {"source_code": "import Data.List\n\nmain = do\n [s, n] <- fmap (map read . words) getLine\n ps <- fmap (map (map read . words) . lines) getContents\n\n let\n ps' = sort ps\n\n find s [] = True\n find s ([x, y]:ps)\n | s > x = find (s+y) ps\n | otherwise = False\n\n putStrLn $ if find s ps' then \"YES\" else \"NO\"\n"}, {"source_code": "import qualified Data.List as L\n\nmain :: IO ()\nmain = do [s,n] <- (getLine >>= return . map read . words)\n dragons <- sequence . replicate n $ (getLine >>= return . (\\[x,y] -> (x,y)). map read . words)\n putStrLn $ solve s dragons\n\nsolve :: Int -> [(Int,Int)] -> String\nsolve s l = case result of\n Nothing -> \"NO\"\n Just _ -> \"YES\"\n where\n result = L.foldl' (\\m (x,y) -> do\n s <- m\n if s <= x then Nothing else return (s+y)) (Just s) (L.sort l)\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map (map read.words).lines\nsolve :: [[Int]]->String\nsolve ((x1:x2:[]):xs) = slv1 x1 $ take x2 xs \nslv1 a [] =\"YES\"\nslv1 x xss = let mxx = mx [[a,b]|[a,b]<-xss, a case a of []->True; _ -> False ) mxx then \"NO\" else slv1 (x+last mxx) (delete mxx xss) \n where \n mx [] = []\n mx z = maximumBy (\\ a b -> last b `compare` last a ) z"}, {"source_code": "\nimport List (sortBy)\nimport Monad (liftM)\n\nsolve :: Int -> [(Int, Int)] -> Bool\nsolve s as = solve' s $ sortBy (\\x y -> compare (fst x) (fst y)) as\n where\n solve' s [] = True\n solve' s ((x,y):as)\n | s > x = solve' (s+y) as\n | otherwise = False\n\nparse :: String -> (Int, Int)\nparse line = case words line of\n [s1, s2] -> (read s1, read s2)\n\n() a b p = if p then a else b\n\nmain :: IO ()\nmain = do\n (s, n) <- liftM parse getLine\n as <- liftM (map parse . take n . lines) getContents\n putStrLn $ \"YES\" \"NO\" $ solve s as\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List (sort)\n\nparse = map read . words\ntoTup [x,y] = (x,y)\n\nmain = do\n [s,n] <- parse <$> getLine\n xs <- sort . map (toTup . parse) <$> replicateM n getLine\n putStrLn $\n if test s xs then \"YES\" else \"NO\"\n\ntest _ [] = True\ntest s ((sd,r):xs)\n | sd < s = test (s+r) xs\n | otherwise = False"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nfight :: Int -> (Int, Int) -> Maybe Int\nfight s (s', y') = if s <= s' then Nothing else Just (s + y')\n\nsolve :: Int -> [(Int, Int)] -> Bool\nsolve s = isJust . foldM fight s . sort\n\nmain :: IO ()\nmain = do\n [s, n] <- getIntList\n a <- replicateM n $ (\\[x,y] -> (x, y)) <$> getIntList\n putStrLn $ if solve s a then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess::[[Int]]->Int->String\nprocess [] _ = \"YES\"\nprocess ([a,b]:c) s | s<=a =\"NO\"\n | otherwise = process c (s+b)\n\nmain=do\n [s,n]<-map read <$> words <$>getLine ::IO [Int]\n q<-(replicateM n (map read <$> words <$>getLine ))::IO [[Int]]\n putStrLn $ process (sort q) s\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\nimport Data.Bits\n\nmain = do\n [s, n] <- getList\n a <- replicateM n getList\n let dragons = sortBy (\\x y -> head x `compare` head y) a\n endGamePower = foldl' (\\p [x, y] -> if p > x then p+y else -1) s dragons\n answer = if endGamePower >= 0 then \"YES\" else \"NO\"\n putStrLn answer\n \ngetList = fmap (map read . words) getLine"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n [s,n] <- fmap (map read . words) getLine\n ds <- replicateM n readDragon\n putStrLn $ maybe \"NO\" (const \"YES\") $ foldM fightDragon s (sort ds)\n\nreadDragon = do\n [x,y] <- fmap (map read . words) getLine\n return (x,y)\n\nfightDragon s (x,y) | s > x = Just (s + y)\n | otherwise = Nothing"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n str1 <- getLine\n let [s, n] = map read $ words str1\n dragons <- forM [1..n] (\\_ -> do\n str <- getLine\n let [x, y] = map read $ words str\n return (x, y) )\n let sortedDragons = sortBy (\\(a, b) (c, d) -> a `compare` c) dragons\n putStrLn $ if s `canWin` sortedDragons then \"YES\" else \"NO\"\n\ns `canWin` [] = True\ns `canWin` ((x, y) : xs) | s <= x = False\n | otherwise = (s + y) `canWin` xs\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/230/A\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List\n\nfight :: Int -> (Int, Int) -> Maybe Int\nfight s (x, y) = if s <= x then Nothing else Just (s + y)\n\nsolve :: Int -> [(Int, Int)] -> Bool\nsolve s = isJust . foldM fight s . sort\n\nmain :: IO ()\nmain = do\n [s, n] <- map read . words <$> getLine :: IO [Int]\n a <- replicateM n $ (\\[x,y] -> (x, y)) <$> map read . words <$> getLine\n putStrLn $ if solve s a then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\ntoPairs (x:y:rest) = (x,y):toPairs rest\ntoPairs _ = []\n\nmain=interact$f.map read.words\n\nf(s:_:xys) = g s $ sort $ toPairs xys\ng _ [] = \"YES\"\ng !s ((x,y):rest)\n | s <= x = \"NO\"\n | otherwise = g (s+y) rest\n "}, {"source_code": "import Control.Applicative\nimport Data.List\n\nf m xs = do\n s <- m\n if s > x\n then return (s+y) \n else Nothing\n where x = head xs\n y = last xs\n\nmain = do\n s:n <- map read<$>words<$>getLine\n xss <- sortBy g<$>map (map read<$>words)<$>lines<$>getContents\n judge $ foldl f (Just s) xss\n where judge x = case x of\n Just y -> putStrLn \"YES\"\n Nothing -> putStrLn \"NO\"\n g (x:_) (y:_) | x < y = LT\n | x == y = EQ\n | x > y = GT\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 #-}\n\nimport Data.List (sort)\n\nfight s [] = \"YES\"\nfight s ((x, y) : ds) | s > x = fight (s + y) ds\n | otherwise = \"NO\"\n\ngetPair = do\n pair <- getLine\n let (x : y : _) = (map read . words) pair\n return (x, y)\n\ngetDragons 0 acc = return acc\ngetDragons n acc = do\n (x, y) <- getPair\n getDragons (n - 1) ((x, y) : acc)\n\nmain = do \n (s, n) <- getPair \n dragons <- getDragons n []\n putStrLn (fight s (sort dragons))\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\ntype Power = Int\n\nsolution :: Int -> [(Int, Int)] -> Bool\nsolution _ [] = True\nsolution p ((x, y):rest) | p > x = solution (p+y) rest\n | p <= x = False\n\n\nmain = do\n [s, n] <- (map read.words) `fmap` getLine\n let convert [a, b] = (a, b)\n getDragon = convert . (map read . words)\n dragons <- sortOn fst `fmap` (map getDragon) `fmap` replicateM n getLine\n putStrLn $ if solution s dragons then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nprocess::Int->[(Int,Int)]->String\n\nprocess _ [] = \"YES\"\nprocess s ((a,b):as) | s> a = process (s+b) as\n | otherwise=\"NO\"\n \n\nmain=do\n\t\n\t[s,n] <- map read.words <$> getLine::IO [Int]\n\tq <- map (map read).map words.lines <$> getContents :: IO [[Int]]\n\tlet q1 = sort $ map (\\z->(head z, last z)) q\n\tputStrLn $ process s q1\n\t \n\t\n\t\n\n "}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nsolve :: [[Integer]] -> Integer -> String\nsolve [] _ = \"YES\"\nsolve (x:xs) curPow\n | curPow > a = solve xs (curPow + b)\n | otherwise = \"NO\"\n \twhere\n\t\ta = head x\n\t\tb = last x\n\nmain :: IO ()\nmain = do \n\tline1 <- getLine\n\tcontents <- getContents\n\tlet\n\t\t[s, n] = map (\\x -> read x :: Integer). words $ line1\n\t\tarr = sort.map (\\x -> map (\\x -> read x :: Integer). words $ x). lines $ contents\n--\tprint s\n--\tprint arr\n\tputStrLn$ solve arr s\n\n"}, {"source_code": "import Data.List (sortBy)\nimport Data.Ord (comparing)\n\nprocess :: Int -> [(Int,Int)] -> Bool\nprocess s ps = and $ zipWith (>) cs xs\n where\n (xs,ys) = unzip $ sortBy (comparing fst) ps\n cs = scanl (+) s ys\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int,Int)\nreadPair s = (l,r)\n where\n [l,r] = map readInt (words s)\n\nmain :: IO ()\nmain = do\n [s,n] <- fmap (map readInt.words) getLine\n ps <- fmap (map readPair.lines) getContents\n putStrLn $ [\"NO\",\"YES\"] !! fromEnum (process s ps)"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do \n [s,n] <- readLine\n ls <- sequence $ replicate n $ readLine\n let zs = sort ls\n case killDragons zs s of\n True -> putStrLn \"YES\"\n _ -> putStrLn \"NO\"\n where\n readLine = ( liftA (map read) $ fmap words getLine ) :: IO [Int]\n killDragons [] _ = True\n killDragons ([x,y]:xs) s | s <= x = False\n | otherwise = killDragons xs (s + y)"}, {"source_code": "import Data.List\nimport Data.Function\nmain = do\n [s,n] <- fmap (map read . words) getLine :: IO [Int]\n ds <- mapM (\\_ -> (\\[s,n] -> return (s,n)) =<< fmap (map read . words) getLine) [1..n] :: IO [(Int,Int)]\n let\n sds = sortBy (compare `on` fst) ds\n putStrLn $ f sds s\n\nf [] s = \"YES\"\nf ((x,y):ds) s\n | s > x = f ds (s+y)\n | True = \"NO\""}, {"source_code": "import Data.List\nimport Data.Ord\n\nkillAll :: Int -> [(Int, Int)] -> String\nkillAll _ [] = \"YES\"\nkillAll s ((si, bi):xs)\n | s > si = killAll (s + bi) xs\n | otherwise = \"NO\" \n\nsolve :: String -> String\nsolve inp = killAll s $ sortBy (comparing fst) dragons\n where l:ls = lines inp\n s:_ = fmap read. words $ l\n dragons = fmap toPair ls\n\ntoPair :: String -> (Int, Int)\ntoPair s = (a,b)\n where a:b:_ = fmap read . words $ s\n\n\nmain :: IO ()\nmain = interact $ solve"}], "negative_code": [{"source_code": "import Control.Monad\n\ndata Answer = YES | NO deriving (Show)\n\ntoInt :: String -> Int\ntoInt str = read str\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetAnswer :: [String] -> Int -> Answer\ngetAnswer list s = battle new s\n where new = cast list\n\ncast :: [String] -> [[Int]]\ncast [] = []\ncast (first:rest) = casted : cast rest\n where casted = map read (words first)\n\nbattle :: [[Int]] -> Int -> Answer\nbattle [] _ = YES\nbattle ([x, y]:rest) s = if s <= x\n then NO\n else battle rest (s + y)\n\nmain :: IO ()\nmain = do\n limits <- getLine\n let [s, n] = map toInt (words limits)\n list <- getLines n\n print $ getAnswer list s\n "}, {"source_code": "{-# OPTIONS -O2 -optc-O3 #-}\nimport Control.Arrow ((***))\nimport Control.Monad (forM_, when)\nimport Control.Monad.ST (ST)\nimport Data.Array.ST (STUArray, runSTUArray, newArray, readArray, writeArray)\nimport Data.Array.Unboxed (UArray, (!), assocs)\n\nisqrt :: (Integral a, Integral b) => a -> b\nisqrt = floor . sqrt . fromIntegral\n\nsieveToN :: Int -> UArray Int Bool\nsieveToN n = runSTUArray sieve\n where\n sieve = do\n a <- newArray (2, n) True :: ST s (STUArray s Int Bool)\n forM_ [4, 6 .. n] $ \\j ->\n writeArray a j False\n forM_ [3, 5 .. isqrt n] $ \\i -> do\n ai <- readArray a i\n when ai $\n forM_ [i * i, i * (i + 2) .. n] $ \\j ->\n writeArray a j False\n return a\n\nprimeTab :: UArray Int Bool\nprimeTab = sieveToN 1000000\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n >= 2 && primeTab!fromIntegral n\n\nmain = do\n getLine\n getLine >>= putStrLn . unlines . map (gao . read) . words\n where\n gao n = let m = isqrt n in if m * m == n && isPrime m then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\n\nmain = do \n\tss<-getLine\n\tlet [s,n] = words ss\n\treading (read n) [] s\n\nreading 0 acc s = do\n\tlet d= map words $ acc\n\tlet d2=map (\\x->map read x) d\n\tputStrLn $ game (read s) (sort d2)\nreading n acc s = do\n\ttemp <-getLine\n\treading (n-1) (acc++[temp]) s\n\ngame s [] = \"YES\"\ngame s ([dragon,bonus]:dragons) | s<= dragon = \"NO\"\n | otherwise = game (s+bonus) (tail dragons)"}, {"source_code": "import Data.List\n\nmain = do \n\tss<-getLine\n\tlet [s,n] = words ss\n\trest<-getContents\n\tlet d= map words $ lines $ rest\n\tlet d2=map (\\x->map read x) d\n\tputStrLn $ game (read s) d2\n\nsolve s dragons = game s (sort dragons)\n\ngame s [] = \"YES\"\ngame s ([dragon,bonus]:dragons) | s<= dragon = \"NO\"\n | otherwise = game (s+bonus) (tail dragons)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\n\nprocess::[[Int]]->Int->String\nprocess [] _ = \"YES\"\nprocess ([a,b]:c) s | s words <$>getLine ::IO [Int]\n q<-(replicateM n (map read <$> words <$>getLine ))::IO [[Int]]\n putStrLn $ process q s\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess::[[Int]]->Int->String\nprocess [] _ = \"YES\"\nprocess ([a,b]:c) s | s words <$>getLine ::IO [Int]\n q<-(replicateM n (map read <$> words <$>getLine ))::IO [[Int]]\n putStrLn $ process (sort q) s\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve ([s, _]:xys) = and $ zipWith (<) (map head xys) (scanl (+) s (map (!!1) xys))\nsolve _ = undefined\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Control.Monad\n\nmain = do\n [s,n] <- fmap (map read . words) getLine\n ds <- replicateM n readDragon\n putStrLn $ maybe \"NO\" (const \"YES\") $ foldM fightDragon s ds\n\nreadDragon = do\n [x,y] <- fmap (map read . words) getLine\n return (x,y)\n\nfightDragon s (x,y) | s > x = Just (s + y)\n | otherwise = Nothing"}, {"source_code": "import Control.Applicative\n\nf m xs = do\n s <- m\n if s > x\n then return (s+y) \n else Nothing\n where x = head xs\n y = last xs\n\nmain = do\n s:n <- map read<$>words<$>getLine\n xss <- map (map read<$>words)<$>lines<$>getContents\n judge $ foldl f (Just s) xss\n where judge x = case x of\n Just y -> putStrLn \"YES\"\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\n\nprocess::Int->[(Int,Int)]->String\n\nprocess _ [] = \"YES\"\nprocess s ((a,b):as) | s>= a = process (s+b) as\n | otherwise=\"NO\"\n \n\nmain=do\n\t\n\t[s,n] <- map read.words <$> getLine::IO [Int]\n\tq <- map (map read).map words.lines <$> getContents :: IO [[Int]]\n\tlet q1 = sort $ map (\\z->(head z, last z)) q\n\tputStrLn $ process s q1\n\t \n\t\n\t\n\n "}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do \n [s,n] <- readLine\n ls <- sequence $ replicate n $ readLine\n let zs = sort ls\n case killDragons zs s of\n True -> putStrLn \"YES\"\n _ -> putStrLn \"NO\"\n where\n readLine = ( liftA (map read) $ fmap words getLine ) :: IO [Int]\n killDragons [] _ = True\n killDragons ([x,y]:xs) s | s < x = False\n | otherwise = killDragons xs (s + y)"}], "src_uid": "98f5b6aac08f48f95b2a8ce0738de657"} {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad (replicateM, forM_)\nimport Data.Functor ((<&>))\nimport Data.List (foldl', minimumBy)\nimport Text.Printf (printf)\n\nmain :: IO ()\nmain = do\n result <- solve <$> replicateM 3 readCircle\n forM_ result $ \\(Point x y) -> printf \"%.5f %.5f\\n\" x y\n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words\n pure $ Circle (Point x y) r\n\ndata Point = Point {\n x :: Double,\n y :: Double\n} deriving (Show, Eq)\n\ndata Circle = Circle {\n center :: Point,\n radius :: Double\n} deriving (Show)\n\neps :: Double\neps = 1e-6\n\nisSmall :: Double -> Bool\nisSmall = (< eps) . abs\n\nangleWeight :: Point -> Circle -> Double\nangleWeight p (Circle c r) = dist p c / r\n\nsq :: Double -> Double\nsq x = x * x\n\nmse :: [Double] -> Double\nmse ws = sqrt $ sum squares / n\n where\n (total, n) = foldl' step (0, 0) ws\n mean = total / n\n step (cw, cn) w1 = (cw + w1, cn + 1)\n squares = map (sq . (-) mean) ws\n\ndist :: Point -> Point -> Double\ndist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)\n\ninitialGuess :: [Circle] -> Guess\ninitialGuess cs = Guess p (meanError cs p)\n where\n (n, Point x y) = foldl' step (0, Point 0 0) cs\n step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))\n p = Point (x / n) (y / n)\n\nmeanError :: [Circle] -> Point -> Double\nmeanError cs p = mse $ map (angleWeight p) cs\n\nfindBestGuess :: [Circle] -> Guess\nfindBestGuess cs = solve0 (initialGuess cs) 1.0\n where\n candidates (Point x y) c = [Point (x + c) y, Point (x - c) y, Point x (y - c), Point x (y + c)]\n bestGuess = minimum. map (\\p -> Guess p (meanError cs p))\n solve0 g c | isSmall c = g\n solve0 g c = let nextGuess = bestGuess $ candidates (p g) c in\n if nextGuess < g then solve0 nextGuess c else solve0 g (c / 2)\n\ndata Guess = Guess {\n p :: Point,\n w :: Double\n } deriving (Show)\n\ninstance Eq Guess where\n (Guess _ w1) == (Guess _ w2) = w1 == w2\n\ninstance Ord Guess where\n compare (Guess _ w1) (Guess _ w2) = compare w1 w2\n\nsolve :: [Circle] -> Maybe Point\nsolve stadiums = if isSmall (w guess) then Just (p guess) else Nothing\n where\n guess = findBestGuess stadiums", "positive_code": [{"source_code": "import Data.List (transpose, minimumBy)\nimport Data.Function (on)\nimport Text.Printf\n\nsolve :: [[Double]] -> String\nsolve ps = find initP 1\n where\n coords = take 2 $ transpose ps\n initP = map ((/ 3) . sum) coords\n\n eval p = sum . map (** 2) $ zipWith (-) thetas (tail . cycle $ thetas)\n where\n distToP = sqrt . sum . map (** 2) . zipWith (-) p\n thetas = map (\\[x, y, r] -> distToP [x, y] / r) ps\n\n find p@[x, y] d -- d for delta\n | d < 1e-6 && eval p < 1e-5 = printf \"%.5f %.5f\\n\" x y\n | d < 1e-6 = \"\"\n | fst bestCand < eval p = find (snd bestCand) d\n | otherwise = find p (d * 0.7)\n where\n points = [[x+d, y], [x-d, y], [x, y+d], [x, y-d]]\n cands = map (\\cand -> (eval cand, cand)) points\n bestCand = minimumBy (compare `on` fst) cands\n\nmain :: IO ()\nmain = interact $ solve . map (map read . words) . lines\n"}, {"source_code": "import Control.Monad (replicateM,forM,forM_)\nimport Text.Printf (printf)\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\n\ndata Point = P Double Double\n deriving (Show)\n\ndata Line = L Point Double -- x $. p == c (p /= 0)\n deriving (Show)\n\ndata Circle = C Point Double -- (x $. p)^2 == c (c > 0)\n deriving (Show)\n\ncenter :: Circle -> Point\ncenter (C a _) = a\n\nradius2 :: Circle -> Double\nradius2 (C _ r2) = r2\n\ndata Stadium = S Point Double\n deriving (Show)\n\nepsilon = 1e-8\n\nsame :: Double -> Double -> Bool\nsame a b = abs (a-b) <= epsilon\n\n($+) (P x1 y1) (P x2 y2) = P (x1+x2) (y1+y2)\n($-) (P x1 y1) (P x2 y2) = P (x1-x2) (y1-y2)\n($*) (P x y) a = P (x*a) (y*a)\n($/) (P x y) a = P (x/a) (y/a)\n($.) (P x1 y1) (P x2 y2) = x1*x2 + y1*y2\n\nperp :: Point -> Point\nperp (P x y) = (P y (negate x))\n\nnorm2 :: Point -> Double\nnorm2 p = p $. p\n\nlineDistance :: Line -> Point -> Double\nlineDistance (L a c) p = abs ((a $. p) - c) / sqrt (a $. a)\n\nlineDistance2 :: Line -> Point -> Double\nlineDistance2 (L a c) p = ((a $. p) - c)^(2 :: Int)/(a $. a)\n\nonCircle :: Circle -> Point -> Bool\nonCircle (C a r) b = same (norm2 (b $- a)) r\n\nonLine :: Line -> Point -> Bool\nonLine (L a c) p = same (a $. p) c\n\nbisector :: Point -> Point -> Line\nbisector p1 p2 = L n c\n where\n n = (p2 $- p1)\n x0 = (p1 $+ p2) $/ 2\n c = x0 $. n\n\n-- return the solution circle for two stadiums\nbicircle :: Stadium -> Stadium -> Circle\nbicircle (S a ra) (S b rb) = C c rr -- r1 /= r2\n where\n a2 = a $. a\n b2 = b $. b\n ra2 = ra*ra\n rb2 = rb*rb\n c = ((a $* rb2) $- (b $* ra2)) $/ (rb2 - ra2)\n rr = (c $. c) - (rb2 * a2 - ra2 * b2) / (rb2 - ra2)\n\nintersectLines :: Line -> Line -> [ Point ]\nintersectLines (L (P a b) e) (L (P c d) f)\n | det == 0 = []\n | otherwise = [ P (x'/det) (y'/det) ]\n where\n det = a*d - b*c\n x' = e*d - b*f\n y' = a*f - c*e\n\n-- solve a*x^2 + b*x + c == 0\nsolveQuadratic :: Double -> Double -> Double -> [Double]\nsolveQuadratic a b c =\n case compare d 0 of\n EQ -> [ -b/(2*a) ]\n LT -> []\n GT -> [ (-b - sqrtd) / (2*a), (-b + sqrtd) / (2*a) ]\n where d = b*b-4*a*c\n sqrtd = sqrt d\n\ntoParametric :: Line -> (Point,Point)\ntoParametric (L (P a b) c)\n | a /= 0 = let p1 = P (c/a) 0\n p2 = P ((c-b)/a) 1\n in (p1, p2 $- p1)\n | b /= 0 = let p1 = P 0 (c/b)\n p2 = P 1 ((c-a)/b)\n in (p1, p2 $- p1)\n\nintersectLineCircle :: Line -> Circle -> [ Point ]\nintersectLineCircle l (C q rr) = map (\\t -> a $+ (b $* t)) ts\n where\n (a,b) = toParametric l\n a2 = b $. b\n a1 = ((a $- q) $. b) * 2\n a0 = ((a $- q) $. (a $- q)) - rr\n ts = solveQuadratic a2 a1 a0\n\nintersectCircles :: Circle -> Circle -> [ Point ]\nintersectCircles (C a r1) (C b r2) = intersectLineCircle line (C b r2)\n where\n c = (r1 - r2 - (a $. a) + (b $. b)) / 2\n line = L (b $- a) c\n\nsolve :: Stadium -> Stadium -> Stadium -> [ Point ]\nsolve s1@(S p1 r1) s2@(S p2 r2) s3@(S p3 r3)\n | r1 == r2 && r1 == r3 = intersectLines (bisector p1 p2) (bisector p1 p3)\n | r1 == r2 = intersectLineCircle (bisector p1 p2) (bicircle s1 s3)\n | r1 == r3 = intersectLineCircle (bisector p1 p3) (bicircle s1 s2)\n | otherwise = intersectCircles (bicircle s1 s2) (bicircle s1 s3)\n\nmkStadium a b c = S (P a b) c\n\ns1 = mkStadium 0 0 10\ns2 = mkStadium 200 0 20\ns3 = mkStadium 100 100 10\n\nangle :: Point -> Stadium -> Double\nangle a (S b r) = r / sqrt (norm2 (a $- b))\n\nangle' :: Stadium -> Point -> Double\nangle' = flip angle\n\ncheck :: Point -> [Stadium] -> IO ()\ncheck a xs = do\n forM_ (zip [1..] xs) $ \\(i,s) -> do\n let _ = i :: Int\n putStrLn $ printf \"Stadium %d: %7.4f\" i (angle a s)\n\nreadStadium :: IO Stadium\nreadStadium = do\n line <- getLine\n let (xs:ys:rs:_) = words line\n x = read xs\n y = read ys\n r = read rs\n return $ S (P x y) r\n\nmain = do\n [s1,s2,s3] <- replicateM 3 readStadium\n let sols = solve s1 s2 s3\n case sols of\n [] -> return ()\n _ -> do let (P x y) = maximumBy (comparing (angle' s1)) sols\n putStrLn $ printf \"%.5f %.5f\" x y\n\n"}, {"source_code": "module Main where\n\nimport Text.Printf\nimport Data.List\n\n-- \u041e\u043a\u0440\u0443\u0436\u043d\u043e\u0441\u0442\u044c\ndata Circle = Circle {\n center :: Point,\n radius :: Double\n}\n\nreadCircle s = (Circle (Point (ins!!0) (ins!!1)) (ins!!2)) where\n ins = map read $ take 3 $ words s\n\n-- \u0422\u043e\u0447\u043a\u0430\ndata Point = Point {\n x :: Double,\n y :: Double\n}\n\n-- \u043f\u0440\u043e\u0441\u0442\u044b\u0435 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u043d\u0430\u0434 \u0442\u043e\u0447\u043a\u0430\u043c\u0438\nsumP (Point x1 y1) (Point x2 y2) = (Point (x1+x2) (y1+y2))\ndivP (Point x y) a = (Point (x/a) (y/a))\n\n-- \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u043c\u0435\u0436\u0434\u0443 \u0442\u043e\u0447\u043a\u0430\u043c\u0438\ndist (Point x1 y1) (Point x2 y2) = sqrt (sq dx + sq dy) where\n dx = x1-x2\n dy = y1-y2\n\n-- \u043a\u0432\u0430\u0434\u0440\u0430\u0442 (\u0434\u043b\u044f \u0443\u0434\u043e\u0431\u0441\u0442\u0432\u0430)\nsq a = a*a\n\n-- \u0443\u0433\u043e\u043b, \u043f\u043e\u0434 \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u0432\u0438\u0434\u043d\u0430 \u043e\u043a\u0440\u0443\u0436\u043d\u043e\u0441\u0442\u044c \u0438\u0437 \u0442\u043e\u0447\u043a\u0438 (\u043a\u043e\u0442\u0430\u043d\u0433\u0435\u043d\u0441\u043d\u0430\u044f \u043c\u0435\u0440\u0430)\ncangle (Circle p r) p0 = (dist p p0)/r\n\n-- \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043e\u0442\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u0435 \u0443\u0433\u043b\u043e\u0432 (\u043c\u0435\u0440\u0430 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 \u0440\u0430\u0432\u0435\u043d\u0441\u0442\u0432\u0430 \u0443\u0433\u043b\u043e\u0432)\nquadro cl1 cl2 cl3 p =\n sq (a1 - e) + sq (a2 - e) + sq (a3 - e) where\n a1 = cangle cl1 p\n a2 = cangle cl2 p\n a3 = cangle cl3 p\n e = (a1 + a2 + a3)/3\n\nepsilon = 0.000001\n\nmain = do\n instr <- getContents\n let [cl1, cl2, cl3] = map readCircle $ take 3 $ lines instr\n let s = solution cl1 cl2 cl3\n if (quadro cl1 cl2 cl3 s) < epsilon then printf \"%.5f %.5f\\n\" (x s) (y s)\n else return () where\n \n solution cl1 cl2 cl3 = findFinest mid (measure mid) 1.0 where\n \n findFinest point ds delta | delta < epsilon = point\n findFinest point ds delta = if (fst closer) < ds \n then findFinest (snd closer) (fst closer) delta\n else findFinest point ds (delta/1.4) where\n \n closer = minimumBy (\\(d1,_) (d2,_) -> compare d1 d2) $ \n zip (map measure candid) candid where\n px = x point\n py = y point\n candid = [(Point (px+delta) py),\n (Point (px-delta) py),\n (Point px (py+delta)),\n (Point px (py-delta))]\n \n mid = (c1 `sumP` c2 `sumP` c3) `divP` 3.0\n \n measure = quadro cl1 cl2 cl3\n \n c1 = center cl1\n c2 = center cl2\n c3 = center cl3\n"}, {"source_code": "\nimport List (sort)\nimport Maybe (listToMaybe)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\nassertEq' :: Maybe Point -> Maybe Point -> Assertion\nassertEq' (Just (x1, y1)) (Just (x2, y2))\n = case (assertApproximate x1 x2 n, assertApproximate y1 y2 n) of\n (AssertTrue, AssertTrue) -> assertTrue True\n _ -> assertFail $ concat [\"Expected but was \"]\n where\n n = 5\nassertEq' a b = assertEq a b \n\ntestSimple :: Test\ntestSimple = Test \"TestSimple\" $\n assertEq' (Just (0, 0)) (solve ((10, 0), 2) ((-10, 0), 2) ((0, 10), 2))\n\ntestFive :: Test\ntestFive = TestList \"TestFive\"\n [\n Test \"1 2 3\" $ assertEq' (Just (0, 0)) (solve ((-5,0), 1) ((3,4), 1) ((0,-5), 1)),\n Test \"1 3 2\" $ assertEq' (Just (0, 0)) (solve ((-5,0), 1) ((0,-5), 1) ((3,4), 1)),\n Test \"2 1 3\" $ assertEq' (Just (0, 0)) (solve ((3,4), 1) ((-5,0), 1) ((0,-5), 1)),\n Test \"2 3 1\" $ assertEq' (Just (0, 0)) (solve ((3,4), 1) ((0,-5), 1) ((-5,0), 1)),\n Test \"3 1 2\" $ assertEq' (Just (0, 0)) (solve ((0,-5), 1) ((-5,0), 1) ((3,4), 1)),\n Test \"3 2 1\" $ assertEq' (Just (0, 0)) (solve ((0,-5), 1) ((3,4), 1) ((-5,0), 1))\n ]\n\ntestZeroOne :: Test\ntestZeroOne = TestList \"testZeroOne\"\n [\n Test \"1 2 3\" $ assertEq' (Just (0.5, sqrt 3 / 6)) (solve ((0,0), 0.1) ((1,0), 0.1) ((0.5, 0.5 * sqrt 3), 0.1))\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1 2 3\" $ assertEq' (Just (30, 0)) (solve ((0, 0), 10) ((60, 0), 10) ((30, 30), 10)),\n Test \"1 3 2\" $ assertEq' (Just (30, 0)) (solve ((0, 0), 10) ((30, 30), 10) ((60, 0), 10)),\n Test \"2 1 3\" $ assertEq' (Just (30, 0)) (solve ((60, 0), 10) ((0, 0), 10) ((30, 30), 10)),\n Test \"2 3 1\" $ assertEq' (Just (30, 0)) (solve ((60, 0), 10) ((30, 30), 10) ((0, 0), 10)),\n Test \"3 1 2\" $ assertEq' (Just (30, 0)) (solve ((30, 30), 10) ((0, 0), 10) ((60, 0), 10)),\n Test \"3 2 1\" $ assertEq' (Just (30, 0)) (solve ((30, 30), 10) ((60, 0), 10) ((0, 0), 10)) \n ]\n\ntestInput' :: Test\ntestInput' = TestList \"TestInput'\"\n [\n Test \"1 2 3\" $ assertEq [-30, 30] (solve' ((0, 0), 10) ((60, 0), 10) ((30, 30), 10)),\n Test \"1 3 2\" $ assertEq [-30, 30] (solve' ((0, 0), 10) ((30, 30), 10) ((60, 0), 10)),\n Test \"2 1 3\" $ assertEq [-30, 30] (solve' ((60, 0), 10) ((0, 0), 10) ((30, 30), 10)),\n Test \"2 3 1\" $ assertEq [-30, 30] (solve' ((60, 0), 10) ((30, 30), 10) ((0, 0), 10)),\n Test \"3 1 2\" $ assertEq [-30, 30] (solve' ((30, 30), 10) ((0, 0), 10) ((60, 0), 10)),\n Test \"3 2 1\" $ assertEq [-30, 30] (solve' ((30, 30), 10) ((60, 0), 10) ((0, 0), 10)) \n ]\n\ntestDiffRadiuses :: Test\ntestDiffRadiuses = TestList \"TestDiffRadiuses\"\n [\n Test \"#1\" $ assertEq' (Just (0,0)) $ solve ((0, 10), 1) ((20,0),2) ((0,-30),3),\n Test \"#1_\" $ assertEq [-10,10] $ solve' ((0, 10), 1) ((20,0),2) ((0,-30),3),\n Test \"#2\" $ assertEq' (Just (1,0)) $ solve ((1, 10), 1) ((21,0),2) ((1,-30),3),\n Test \"#3\" $ assertEq' (Just (-1,0)) $ solve ((-1, 10), 1) ((19,0),2) ((-1,-30),3),\n Test \"#4\" $ assertEq' (Just (0,1)) $ solve ((0, 11), 1) ((20,1),2) ((0,-30+1),3),\n Test \"#4_\" $ assertEq [-10, 10] $ solve' ((0, 11), 1) ((20,1),2) ((0,-30+1),3)\n ] \n\ntestIntersectionCircles :: Test\ntestIntersectionCircles = TestList \"TestIntersectionCircles\"\n [\n Test \"#01\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((0,1),0),\n Test \"#02\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((1,0),0),\n Test \"#03\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((0,-1),0),\n Test \"#04\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((-1,0),0),\n Test \"#05\" $ assertEq [(0,0)] $ intersectionCircles ((1,0), 1) ((-1,0),1),\n Test \"#06\" $ assertEq [(0,0)] $ intersectionCircles ((0,1), 1) ((0,-1),1),\n Test \"#07\" $ assertEq [(4,1)] $ intersectionCircles ((5,1), 1) ((3,1),1), \n Test \"#08\" $ assertEq [(13,-9)] $ intersectionCircles ((13,-8), 1) ((13,-10),1), \n Test \"#09\" $ assertEq [(13,-9)] $ intersectionCircles ((13,0), 9) ((13,-18),9),\n Test \"#10\" $ assertEq [(3,4)] $ intersectionCircles ((0,0), 5) ((6,8),5),\n Test \"#11\" $ assertEq [(-3,4)] $ intersectionCircles ((0,0), 5) ((-18,24),25),\n Test \"#12\" $ assertEq [(23,38)] $ intersectionCircles ((11,29), 15) ((31,44),10),\n Test \"#13\" $ assertEq [(1 / sqrt 2, 1 / sqrt 2)] $ intersectionCircles ((0,0), 1) ((1,1), sqrt 2 - 1),\n Test \"#14\" $ assertEq [(3,4)] $ intersectionCircles ((0,0), 5) ((-3,-4),10), \n Test \"#15\" $ assertEq [(0,2),(2,0)] $ intersectionCircles ((0,0), 2) ((2,2),2),\n Test \"#16\" $ assertEq [] $ intersectionCircles ((0,0), 1) ((1,1),3),\n Test \"#17\" $ assertEq [(0,0)] $ intersectionCircles ((0,10), 10) ((0,-30),30),\n Test \"#18\" $ assertEq [(8,16),(0,0)] $ intersectionCircles ((0,10), 10) ((20,0),20),\n Test \"#19\" $ assertEq [(8,16),(0,0)] $ intersectionCircles ((20,0), 20) ((0,10),10),\n Test \"#20\" $ assertEq [(16,8),(0,0)] $ intersectionCircles ((10,0), 10) ((0,20),20),\n Test \"#21\" $ assertEq [(16,8),(0,0)] $ intersectionCircles ((0,20), 20) ((10,0),10),\n Test \"#22\" $ assertEq [(0,0),(0,0)] $ intersectionCircles ((20,0), 20) ((0,-30),30),\n Test \"#23\" $ assertEq [(3,4),(3,-4)] $ intersectionCircles ((0,0),5) ((6,0),5),\n Test \"#24\" $ assertEq [(3,4),(-3,4)] $ intersectionCircles ((0,0),5) ((0,8),5),\n Test \"#25\" $ assertEq [(4,5),(4,-3)] $ intersectionCircles ((1,1),5) ((7,1),5),\n Test \"#26\" $ assertEq [(4,5),(-2,5)] $ intersectionCircles ((1,1),5) ((1,9),5)\n ]\n\ntestWA16 :: Test\ntestWA16 = Test \"TestWA16\" $\n assertEq' (Just (-214.30328, -350.95260)) $ solve ((614, 163), 21) ((613, -468), 18) ((-749, 679), 25)\n\ntest :: IO ()\ntest = mapM_ run\n [\n testSimple,\n testFive,\n testZeroOne,\n testInput,\n testInput',\n testDiffRadiuses,\n testIntersectionCircles,\n testWA16\n ]\n-}\n--------------------------------------------------------------------------------\n\neps = 1e-9\n\nquadratic :: (Ord a, Floating a) => a -> a -> a -> a -> [a]\nquadratic eps a b c\n | abs a < eps = if abs b < eps then [] else [-c/b]\n | abs d < eps = [-b/(2*a)]\n | d > 0 = [(-b + sqrt d) / (2*a), (-b - sqrt d) / (2*a)]\n | otherwise = []\n where\n d = b^2 - 4*a*c\n\nbiquadratic :: (Ord a, Floating a) => a -> a -> a -> a -> [a]\nbiquadratic eps a b c = concatMap (getSqrt eps) (quadratic eps a b c)\n where\n getSqrt eps x\n | abs x < eps = [0.0]\n | x > 0 = [-sqrt x, sqrt x]\n | otherwise = []\n\n--------------------------------------------------------------------------------\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\neq :: Point -> Point -> Bool\neq (x1, y1) (x2, y2) = abs (x1 - x2) < eps && abs (y1 - y2) < eps\n\ndistance :: Point -> Point -> Double\ndistance (ax, ay) (bx, by) = sqrt $ sum $ map (^2) $ zipWith (-) [ax, ay] [bx, by]\n\nintersectionCircles :: Circle -> Circle -> [Point]\nintersectionCircles ((x1, y1), r1) ((x2, y2), r2)\n | abs (r1 + r2 - d) < eps\n = [(x1 * r2 / d + x2 * r1 / d, y1 * r2 / d + y2 * r1 / d)]\n | r1 + r2 - d > 0\n = if abs (x1 - x2) > eps\n then map (\\y -> ((_D - 2 * y * (y1 - y2)) / (2 * (x1 - x2)), y)) ys\n else map (\\x -> (x, (_D - 2 * x * (x1 - x2)) / (2 * (y1 - y2)))) xs\n | otherwise = []\n where\n d = distance (x1, y1) (x2, y2)\n _D = x1^2 - x2^2 + y1^2 - y2^2 - (r1^2 - r2^2)\n _Ax = ((x1 - x2) / (y1 - y2))^2 + 1\n _Bx = -2 * x1 - (_D / (y1 - y2) - 2 * y1) * (x1 - x2) / (y1 - y2)\n _Cx = x1^2 - r1^2 + (_D / (2 * (y1 - y2)) - y1)^2\n xs = quadratic eps _Ax _Bx _Cx\n _Ay = ((y1 - y2) / (x1 - x2))^2 + 1\n _By = -2 * y1 - (_D / (x1 - x2) - 2 * x1) * (y1 - y2) / (x1 - x2)\n _Cy = y1^2 - r1^2 + (_D / (2 * (x1 - x2)) - x1)^2\n ys = quadratic eps _Ay _By _Cy\n\n--------------------------------------------------------------------------------\n\nfindEqPoint :: [Point] -> [Point] -> [Point]\nfindEqPoint ps1 ps2 = [p1 | p1 <- ps1, p2 <- ps2, eq' p1 p2]\n where\n eq' (x1, y1) (x2, y2) = abs (x1 - x2) < sqrt eps && abs (y1 - y2) < sqrt eps\n\nsolve :: Circle -> Circle -> Circle -> Maybe Point\nsolve c1@(o1, r1) c2@(o2, r2) c3@(o3, r3) = listToMaybe $ do\n r1' <- roots\n let r2' = r1' * r2/r1\n let r3' = r1' * r3/r1\n let ps2 = intersectionCircles (o1, r1') (o2, r2')\n let ps3 = intersectionCircles (o1, r1') (o3, r3')\n findEqPoint ps2 ps3\n where\n roots = filter (>0) (solve' c1 c2 c3)\n\nsolve' :: Circle -> Circle -> Circle -> [Double]\nsolve' (o1, r1) (o2, r2) (o3, r3) = sort $ biquadratic eps _A _B _C\n where\n a = distance o2 o3\n b = distance o1 o3\n c = distance o1 o2 \n cosA = (b^2 + c^2 - a^2) / (2*b*c) \n _R21 = 1 - (r2/r1)^2\n _R31 = 1 - (r3/r1)^2 \n _A = _R21^2 / (4 * c^2) + _R31^2 / (4 * b^2) - cosA * _R21 * _R31 / (2 * b * c)\n _B = _R21 / 2 + _R31 / 2 - (1 - cosA^2) - cosA * (b * _R21 / (2*c) + c * _R31 / (2 * b))\n _C = c^2 / 4 + b^2 / 4 - cosA * b * c / 2 \n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- getLine >>= return . map read . words\n return ((x, y), r)\n\nprintAns :: Maybe Point -> IO ()\nprintAns Nothing = return ()\nprintAns (Just (x, y)) = putStrLn $ concat [show x, \" \", show y]\n\nmain :: IO ()\nmain = do\n c1 <- readCircle\n c2 <- readCircle\n c3 <- readCircle\n printAns $ solve c1 c2 c3\n"}, {"source_code": "module Main where\n\t\nimport Data.List\n\ndata Point = Point {\n\tx :: Double,\n\ty :: Double\n} deriving (Show)\n\ndata Circle = Circle {\n\tc :: Point,\n\tr :: Double\n} deriving (Show)\n\ncircleFromString :: String -> Circle\ncircleFromString s = \n\tCircle (Point (l !! 0) (l !! 1)) (l !! 2)\n\twhere l = map read $ words s\n\npointAdd :: Point -> Point -> Point\npointAdd (Point x1 y1) (Point x2 y2) = Point (x1 + x2) (y1 + y2)\n\nprocessInput :: String -> [Circle]\nprocessInput = map circleFromString . lines\n\ndistance :: Point -> Point -> Double\ndistance (Point x1 y1) (Point x2 y2) = \n\tsqrt $ (x1 - x2) ** 2 + (y1 - y2) ** 2\n\nangleToCircle :: Point -> Circle -> Double\nangleToCircle p (Circle c r) = \n\t(distance c p) / r\n\nsquareMean :: [Double] -> Double\nsquareMean a = \n\t(sum $ map ((** 2) . (+ m)) a) / n\n\twhere\n\t\tn = fromIntegral $ length a\n\t\tm = - sum a / n\n\ntryPoint :: [Circle] -> Point -> Double\ntryPoint circles p = \n\tsquareMean $ map (angleToCircle p) $ circles\n--\twhere \n--\t\tsumAngle = sum (map angleToCircle circles) / 3\n\t\t\n\niterateTry :: [Circle] -> Point -> Point\niterateTry cs startPoint = \n\titer startPoint 1.0\n\twhere\n\t\titer p d\n\t\t\t| d < 1e-6 = p\n\t\t\t| (fst minimumPoint < currentDistance) = iter (snd minimumPoint) d\n\t\t\t| otherwise = iter p (d * 0.8)\n\t\t\twhere \n\t\t\t\tcurrentDistance = tryPoint cs p\n\t\t\t\tmeasure = tryPoint cs\n\t\t\t\ttryList = [pointAdd p (Point 0 d), pointAdd p (Point d 0), pointAdd p (Point 0 (0-d)), pointAdd p (Point (0-d) 0)]\n\t\t\t\tminimumPoint = minimumBy (\\(a, _) (b, _) -> compare a b) $ zip (map measure tryList) tryList\n\nsolve :: [Circle] -> Point\nsolve cs = \n\tlet \n\t\tstartPoint = Point { x = (sum $ map (x . c) cs) / 3, y = (sum $ map (y . c) cs) / 3 }\n\t\tendPoint = iterateTry cs startPoint\n\tin \n\t\tendPoint\n\nmain = do\n\tinput <- getContents\n\tlet \n\t\tcircles = processInput input\n\t\tanswer = solve circles\n\tif (tryPoint circles answer < 1e-6) then putStrLn $ (show $ x answer) ++ \" \" ++ (show $ y answer) else return ()\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad (replicateM, forM_)\nimport Data.Functor ((<&>))\nimport Data.List (foldl', minimumBy)\nimport Text.Printf (printf)\n\nmain :: IO ()\nmain = do\n result <- solve <$> replicateM 3 readCircle\n forM_ result $ \\(Point x y) -> printf \"%.5f %.5f\\n\" x y\n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words\n pure $ Circle (Point x y) r\n\ndata Point = Point {\n x :: Double,\n y :: Double\n} deriving (Show, Eq)\n\ndata Circle = Circle {\n center :: Point,\n radius :: Double\n} deriving (Show)\n\neps :: Double\neps = 1e-6\n\nisSmall :: Double -> Bool\nisSmall = (< eps) . abs\n\nangleWeight :: Point -> Circle -> Double\nangleWeight p (Circle c r) = dist p c / r\n\nsq :: Double -> Double\nsq x = x * x\n\nmse :: [Double] -> Double\nmse ws = sqrt $ sum squares / n\n where\n (total, n) = foldl' step (0, 0) ws\n mean = total / n\n step (cw, cn) w1 = (cw + w1, cn + 1)\n squares = map (sq . (-) mean) ws\n\ndist :: Point -> Point -> Double\ndist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)\n\ninitialGuess :: [Circle] -> Guess\ninitialGuess cs = toGuess cs $ Point (x / n) (y / n)\n where\n (n, Point x y) = foldl' step (0, Point 0 0) cs\n step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))\n\nmeanError :: [Circle] -> Point -> Double\nmeanError cs p = mse $ map (angleWeight p) cs\n\ntoGuess :: [Circle] -> Point -> Guess\ntoGuess cs p = Guess p (meanError cs p)\n\nfindBestGuess :: [Circle] -> Guess\nfindBestGuess cs = solve0 (initialGuess cs) 1.0\n where\n candidates (Point x y) c = [Point (x + c) y, Point (x - c) y, Point x (y - c), Point x (y + c)]\n bestGuess = minimum. map (toGuess cs)\n solve0 g c | isSmall c = g\n solve0 g c = let nextGuess = bestGuess $ candidates (p g) c in\n if nextGuess < g then solve0 nextGuess c else solve0 g (c / 2)\n\ndata Guess = Guess {\n p :: Point,\n w :: Double\n } deriving (Show)\n\ninstance Eq Guess where\n (Guess _ w1) == (Guess _ w2) = w1 == w2\n\ninstance Ord Guess where\n compare (Guess _ w1) (Guess _ w2) = compare w1 w2\n\nsolve :: [Circle] -> Maybe Point\nsolve stadiums = if isSmall (w guess) then Just (p guess) else Nothing\n where\n guess = findBestGuess stadiums"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad (replicateM, forM_)\nimport Data.Functor ((<&>))\nimport Data.List (foldl', minimumBy)\nimport Text.Printf (printf)\n\nmain :: IO ()\nmain = do\n result <- solve <$> replicateM 3 readCircle\n forM_ result $ \\(Point x y) -> printf \"%.5f %.5f\\n\" x y\n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words\n pure $ Circle (Point x y) r\n\ndata Point = Point {\n x :: !Double,\n y :: !Double\n} deriving (Show, Eq)\n\ndata Circle = Circle {\n center :: !Point,\n radius :: !Double\n} deriving (Show)\n\neps :: Double\neps = 1e-6\n\nisSmall :: Double -> Bool\nisSmall = (< eps) . abs\n\nangleWeight :: Point -> Circle -> Double\nangleWeight p (Circle c r) = dist p c / r\n\nsq :: Double -> Double\nsq x = x * x\n\nmse :: [Double] -> Double\nmse ws = sqrt $ sum squares / n\n where\n (total, n) = foldl' step (0, 0) ws\n mean = total / n\n step (cw, cn) w1 = (cw + w1, cn + 1)\n squares = map (sq . (-) mean) ws\n\ndist :: Point -> Point -> Double\ndist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)\n\ninitialGuess :: [Circle] -> Guess\ninitialGuess cs = Guess p (meanError cs p)\n where\n (n, Point x y) = foldl' step (0, Point 0 0) cs\n step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))\n p = Point (x / n) (y / n)\n\nmeanError :: [Circle] -> Point -> Double\nmeanError cs p = mse $ map (angleWeight p) cs\n\nfindBestGuess :: [Circle] -> Guess\nfindBestGuess cs = solve0 (initialGuess cs) 1.0\n where\n candidates (Point x y) c = [Point (x + c) y, Point (x - c) y, Point x (y - c), Point x (y + c)]\n bestGuess = minimum. map (\\p -> Guess p (meanError cs p))\n solve0 g c | isSmall c = g\n solve0 g c = let nextGuess = bestGuess $ candidates (p g) c in\n if nextGuess < g then solve0 nextGuess c else solve0 g (c / 2)\n\ndata Guess = Guess {\n p :: !Point,\n w :: !Double\n } deriving (Show)\n\ninstance Eq Guess where\n (Guess _ w1) == (Guess _ w2) = w1 == w2\n\ninstance Ord Guess where\n compare (Guess _ w1) (Guess _ w2) = compare w1 w2\n\nsolve :: [Circle] -> Maybe Point\nsolve stadiums = if isSmall (w guess) then Just (p guess) else Nothing\n where\n guess = findBestGuess stadiums"}], "negative_code": [{"source_code": "import Data.List (transpose, minimumBy)\nimport Data.Function (on)\nimport Text.Printf\n\nsolve :: [[Double]] -> String\nsolve ps = find initP 1\n where\n coords = take 2 $ transpose ps\n initP = map ((/ 3) . sum) coords\n\n eval p = sum . map abs $ zipWith (-) thetas (tail . cycle $ thetas)\n where\n distToP = sum . take 2 . zipWith (-) p\n thetas = map (\\[x, y, r] -> distToP [x, y] / r) ps\n\n find p@[x, y] d -- d for delta\n | d < 1e-6 = printf \"%.5f %.5f\\n\" x y\n | fst bestCand < local = find (snd bestCand) d\n | otherwise = find p (d * 0.7)\n where\n points = [[x+d, y], [x-d, y], [x, y+d], [x, y-d]]\n cands = map (\\cand -> (eval cand, cand)) points\n bestCand = minimumBy (compare `on` fst) cands\n local = eval [x, y]\n\nmain :: IO ()\nmain = interact $ solve . map (map read . words) . lines\n"}, {"source_code": "\nimport Control.Monad (forM_)\nimport Text.Printf (printf)\n\ndata Vec = V Double Double\n deriving (Show,Eq)\n\n(<+>) :: Vec -> Vec -> Vec\n(<+>) (V a b) (V c d) = V (a+c) (b+d)\n\n(<->) :: Vec -> Vec -> Vec\n(<->) (V a b) (V c d) = V (a-c) (b-d)\n\ninfixl 6 <+>\ninfixl 6 <->\n\n(<.>) :: Vec -> Vec -> Double\n(<.>) (V a b) (V c d) = a*c + b*d\n\ninfixl 7 <.>\n\n(.*) :: Double -> Vec -> Vec\n(.*) a (V x y) = V (a*x) (a*y)\n\n(./) :: Double -> Vec -> Vec\n(./) a (V x y) = V (x/a) (y/a)\n\n(/.) :: Vec -> Double -> Vec\n(/.) (V x y) a = V (x/a) (y/a)\n\ninfixr 7 .*\ninfixr 7 ./\ninfixl 7 /.\n\nnorm2 :: Vec -> Double\nnorm2 v = v <.> v\n\nlen :: Vec -> Double\nlen = sqrt . norm2\n\nnormal :: Vec -> Vec\nnormal (V a b) = V (negate b) a\n\nzero :: Double -> Bool\nzero a = abs a < 1e-10\n\nzeroVec :: Vec -> Bool\nzeroVec (V a b) = zero a && zero b\n\nsame :: Double -> Double -> Bool\nsame x y = abs (x-y) < 1e-10\n\n-- [Vec] is the list of centers\n-- [Double] is the list of radii\n\nsolveProblem :: [Vec] -> [Double] -> [Vec]\nsolveProblem (av:bv:cv:_) (a:b:c:_) \n | same a b && same a c\n = intersectLines ab1 ab0 ac1 ac0\n | same a b\n = intersectLineCircle ab1 ab0 (ac1 /. ac2) (ac0 / ac2)\n | otherwise\n = intersectCircles (ab1 /. ab2) (ab0 / ab2)\n (ac1 /. ac2) (ac0 / ac2)\n where\n a2 = a*a\n b2 = b*b\n c2 = c*c\n\n ab2 = b2 - a2\n ab1 = 2 .* (a2 .* bv <-> b2 .* av)\n ab0 = b2 * norm2 av - a2 * norm2 bv\n\n ac2 = c2 - a2\n ac1 = 2 .* (a2 .* cv <-> c2 .* av)\n ac0 = c2 * norm2 av - a2 * norm2 cv\n\n{- Find the intersection of two lines given by:\n - X.A + a = 0\n - X.B + b = 0\n -}\nintersectLines :: Vec -> Double -> Vec -> Double -> [Vec]\nintersectLines av a bv b =\n let nvec = normal av\n x0 = ((negate a) / norm2 av) .* av\n t = ((negate b) - x0 <.> bv) / (nvec <.> bv)\n in\n if zero $ nvec <.> bv\n then []\n else [ x0 <+> t .* nvec ]\n\n{- Find the intersection of a line:\n - X.A + a = 0\n - and a parabola:\n - X.X + X.B + b = 0\n -}\nintersectLineCircle :: Vec -> Double -> Vec -> Double -> [Vec]\nintersectLineCircle av a bv b =\n let nvec = normal av\n x0 = ((negate a) / norm2 av) .* av\n a2 = norm2 nvec\n a1 = 2 * (nvec <.> x0) + nvec <.> bv\n a0 = bv <.> x0 + b\n ts = solveQuadratic a2 a1 a0\n in [ x0 <+> t .* nvec | t <- ts ]\n\nintersectCircles :: Vec -> Double -> Vec -> Double -> [Vec]\nintersectCircles avec a bvec b = do\n let dvec = avec <-> bvec\n d = a - b\n nvec = normal dvec\n d2 = dvec <.> dvec\n x0vec = ((b-a)/d2) .* dvec\n a2 = nvec <.> nvec\n a1 = nvec <.> avec\n a0 = (x0vec <.> x0vec) + (x0vec <.> avec) + a\n ts = solveQuadratic a2 a1 a0 \n -- putStrLn $ \" a2,a1,a0: \" ++ show [a2,a1,a0]\n let b2 = nvec <.> nvec\n b1 = nvec <.> bvec\n b0 = x0vec <.> x0vec + x0vec <.> bvec + b\n -- putStrLn $ \" b2,b1,b0: \" ++ show [b2,b1,b0]\n t <- ts\n let xvec = t .* nvec <+> x0vec\n let e1 = xvec <.> xvec + xvec <.> avec + a\n e2 = xvec <.> xvec + xvec <.> bvec + b\n return xvec\n -- putStrLn $ \"Solution: t = \" ++ show t\n -- putStrLn $ \" x = \" ++ show xvec\n -- putStrLn $ \" e1 = \" ++ show e1\n -- putStrLn $ \" e2 = \" ++ show e1\n\n-- solve a*x^2 + b*x + c == 0\nsolveQuadratic :: Double -> Double -> Double -> [Double]\nsolveQuadratic a b c =\n case compare d 0 of\n EQ -> [ -b/(2*a) ]\n LT -> []\n GT -> [ (-b - sqrtd) / (2*a), (-b + sqrtd) / (2*a) ]\n where d = b*b-4*a*c\n sqrtd = sqrt d\n\nreadStadium :: IO (Vec,Double)\nreadStadium = do\n line <- getLine\n let (xs:ys:rs:_) = words line\n x = read xs\n y = read ys\n r = read rs\n return (V x y, r)\n\nmain = do \n (av,a) <- readStadium\n (bv,b) <- readStadium\n (cv,c) <- readStadium\n let sols = solveProblem [av,bv,cv] [a,b,c]\n case sols of\n [] -> return ()\n (V x y):_ -> putStrLn $ printf \"%.6f %.6f\" x y\n\n \n\n"}, {"source_code": "import Data.Maybe\nimport Text.Printf\n\n(-->) = flip fmap\n\ntype Triple = (Double,Double,Double)\n\nreadTriple :: String -> Triple\nreadTriple s = let (x:y:r:_) = map read $ words s in (x,y,r)\n\ndist x1 y1 x2 y2 = sqrt (dx*dx + dy*dy)\n where dx = x1 - x2\n dy = y1 - y2\n\neps = 1e-10\n\nsolve :: Triple -> Triple -> Triple -> Maybe (Double,Double)\nsolve (x1,y1,r1) (x2,y2,r2) (x3,y3,r3) =\n let a = r1 / (r1+r2)\n x = x1*a + x2*(1-a)\n y = y1*a + y2*(1-a)\n d = dist x1 y1 x2 y2\n d2 = d*a\n d3 = dist x y x3 y3\n in if abs (d3/r3 - d2/r2) < eps then Just (x,y) else Nothing\n\nmain = do\n p1 <- getLine --> readTriple\n p2 <- getLine --> readTriple\n p3 <- getLine --> readTriple\n case catMaybes [ solve p1 p2 p3, solve p2 p3 p1, solve p3 p1 p2 ] of\n ((x,y):_) -> putStrLn $ printf \"%.5f %.5f\" x y\n otherwise -> return ()\n\n"}, {"source_code": "import Control.Monad (replicateM,forM,forM_)\nimport Text.Printf (printf)\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\n\ndata Point = P Double Double\n deriving (Show)\n\ndata Line = L Point Double -- x $. p == c (p /= 0)\n deriving (Show)\n\ndata Circle = C Point Double -- (x $. p)^2 == c (c > 0)\n deriving (Show)\n\ncenter :: Circle -> Point\ncenter (C a _) = a\n\nradius2 :: Circle -> Double\nradius2 (C _ r2) = r2\n\ndata Stadium = S Point Double\n deriving (Show)\n\nepsilon = 1e-8\n\nsame :: Double -> Double -> Bool\nsame a b = abs (a-b) <= epsilon\n\n($+) (P x1 y1) (P x2 y2) = P (x1+x2) (y1+y2)\n($-) (P x1 y1) (P x2 y2) = P (x1-x2) (y1-y2)\n($*) (P x y) a = P (x*a) (y*a)\n($/) (P x y) a = P (x/a) (y/a)\n($.) (P x1 y1) (P x2 y2) = x1*x2 + y1*y2\n\nperp :: Point -> Point\nperp (P x y) = (P y (negate x))\n\nnorm2 :: Point -> Double\nnorm2 p = p $. p\n\nlineDistance :: Line -> Point -> Double\nlineDistance (L a c) p = abs ((a $. p) - c) / sqrt (a $. a)\n\nlineDistance2 :: Line -> Point -> Double\nlineDistance2 (L a c) p = ((a $. p) - c)^(2 :: Int)/(a $. a)\n\nonCircle :: Circle -> Point -> Bool\nonCircle (C a r) b = same (norm2 (b $- a)) r\n\nonLine :: Line -> Point -> Bool\nonLine (L a c) p = same (a $. p) c\n\nbisector :: Point -> Point -> Line\nbisector p1 p2 = L n c\n where\n n = (p2 $- p1)\n x0 = (p1 $+ p2) $/ 2\n c = x0 $. n\n\n-- return the solution circle for two stadiums\nbicircle :: Stadium -> Stadium -> Circle\nbicircle (S a ra) (S b rb) = C c rr -- r1 /= r2\n where\n a2 = a $. a\n b2 = b $. b\n ra2 = ra*ra\n rb2 = rb*rb\n c = ((a $* rb2) $- (b $* ra2)) $/ (rb2 - ra2)\n rr = (c $. c) - (rb2 * a2 - ra2 * b2) / (rb2 - ra2)\n\nintersectLines :: Line -> Line -> [ Point ]\nintersectLines (L (P a b) e) (L (P c d) f)\n | det == 0 = []\n | otherwise = [ P (x'/det) (y'/det) ]\n where\n det = a*d - b*c\n x' = e*d - b*f\n y' = a*f - c*e\n\n-- solve a*x^2 + b*x + c == 0\nsolveQuadratic :: Double -> Double -> Double -> [Double]\nsolveQuadratic a b c =\n case compare d 0 of\n EQ -> [ -b/(2*a) ]\n LT -> []\n GT -> [ (-b - sqrtd) / (2*a), (-b + sqrtd) / (2*a) ]\n where d = b*b-4*a*c\n sqrtd = sqrt d\n\ntoParametric :: Line -> (Point,Point)\ntoParametric (L (P a b) c)\n | a /= 0 = let p1 = P (c/a) 0\n p2 = P ((c-b)/a) 1\n in (p1, p2 $- p1)\n | b /= 0 = let p1 = P 0 (c/b)\n p2 = P 1 ((c-a)/b)\n in (p1, p2 $- p1)\n\nintersectLineCircle :: Line -> Circle -> [ Point ]\nintersectLineCircle l (C q rr) = map (\\t -> a $+ (b $* t)) ts\n where\n (a,b) = toParametric l\n a2 = b $. b\n a1 = ((a $- q) $. b) * 2\n a0 = ((a $- q) $. (a $- q)) - rr\n ts = solveQuadratic a2 a1 a0\n\nintersectCircles :: Circle -> Circle -> [ Point ]\nintersectCircles (C a r1) (C b r2) = intersectLineCircle line (C b r2)\n where\n c = (r1 - r2 - (a $. a) + (b $. b)) / 2\n line = L (b $- a) c\n\nsolve :: Stadium -> Stadium -> Stadium -> [ Point ]\nsolve s1@(S p1 r1) s2@(S p2 r2) s3@(S p3 r3)\n | r1 == r2 && r1 == r3 = intersectLines (bisector p1 p2) (bisector p1 p3)\n | r1 == r2 = intersectLineCircle (bisector p1 p2) (bicircle s1 s3)\n | otherwise = intersectCircles (bicircle s1 s2) (bicircle s1 s3)\n\nmkStadium a b c = S (P a b) c\n\ns1 = mkStadium 0 0 30\ns2 = mkStadium 300 300 30\ns3 = mkStadium 500 (-500) 20\n\nangle :: Point -> Stadium -> Double\nangle a (S b r) = r / sqrt (norm2 (a $- b))\n\nangle' :: Stadium -> Point -> Double\nangle' = flip angle\n\ncheck :: Point -> [Stadium] -> IO ()\ncheck a xs = do\n forM_ (zip [1..] xs) $ \\(i,s) -> do\n let _ = i :: Int\n putStrLn $ printf \"Stadium %d: %7.4f\" i (angle a s)\n\nreadStadium :: IO Stadium\nreadStadium = do\n line <- getLine\n let (xs:ys:rs:_) = words line\n x = read xs\n y = read ys\n r = read rs\n return $ S (P x y) r\n\nmain = do\n [s1,s2,s3] <- replicateM 3 readStadium\n let sols = solve s1 s2 s3\n case sols of\n [] -> return ()\n _ -> do let (P x y) = maximumBy (comparing (angle' s1)) sols\n putStrLn $ printf \"%.5f %.5f\" x y\n\n"}, {"source_code": "import Control.Monad (replicateM,forM,forM_)\nimport Text.Printf (printf)\n\ndata Point = P Double Double\n deriving (Show)\n\ndata Line = L Point Double -- x $. p == c (p /= 0)\n deriving (Show)\n\ndata Circle = C Point Double -- (x $. p)^2 == c (c > 0)\n deriving (Show)\n\ncenter :: Circle -> Point\ncenter (C a _) = a\n\nradius2 :: Circle -> Double\nradius2 (C _ r2) = r2\n\ndata Stadium = S Point Double\n deriving (Show)\n\nepsilon = 1e-8\n\nsame :: Double -> Double -> Bool\nsame a b = abs (a-b) <= epsilon\n\n($+) (P x1 y1) (P x2 y2) = P (x1+x2) (y1+y2)\n($-) (P x1 y1) (P x2 y2) = P (x1-x2) (y1-y2)\n($*) (P x y) a = P (x*a) (y*a)\n($/) (P x y) a = P (x/a) (y/a)\n($.) (P x1 y1) (P x2 y2) = x1*x2 + y1*y2\n\nperp :: Point -> Point\nperp (P x y) = (P y (negate x))\n\nnorm2 :: Point -> Double\nnorm2 p = p $. p\n\nlineDistance :: Line -> Point -> Double\nlineDistance (L a c) p = abs ((a $. p) - c) / sqrt (a $. a)\n\nlineDistance2 :: Line -> Point -> Double\nlineDistance2 (L a c) p = ((a $. p) - c)^(2 :: Int)/(a $. a)\n\nonCircle :: Circle -> Point -> Bool\nonCircle (C a r) b = same (norm2 (b $- a)) r\n\nonLine :: Line -> Point -> Bool\nonLine (L a c) p = same (a $. p) c\n\nbisector :: Point -> Point -> Line\nbisector p1 p2 = L n c\n where\n n = (p2 $- p1)\n x0 = (p1 $+ p2) $/ 2\n c = x0 $. n\n\n-- return the solution circle for two stadiums\nbicircle :: Stadium -> Stadium -> Circle\nbicircle (S a ra) (S b rb) = C c rr -- r1 /= r2\n where\n a2 = a $. a\n b2 = b $. b\n ra2 = ra*ra\n rb2 = rb*rb\n c = ((a $* rb2) $- (b $* ra2)) $/ (rb2 - ra2)\n rr = (c $. c) - (rb2 * a2 - ra2 * b2) / (rb2 - ra2)\n\nintersectLines :: Line -> Line -> [ Point ]\nintersectLines (L (P a b) e) (L (P c d) f)\n | det == 0 = []\n | otherwise = [ P (x'/det) (y'/det) ]\n where\n det = a*d - b*c\n x' = e*d - b*f\n y' = a*f - c*e\n\n-- solve a*x^2 + b*x + c == 0\nsolveQuadratic :: Double -> Double -> Double -> [Double]\nsolveQuadratic a b c =\n case compare d 0 of\n EQ -> [ -b/(2*a) ]\n LT -> []\n GT -> [ (-b - sqrtd) / (2*a), (-b + sqrtd) / (2*a) ]\n where d = b*b-4*a*c\n sqrtd = sqrt d\n\ntoParametric :: Line -> (Point,Point)\ntoParametric (L (P a b) c)\n | a /= 0 = let p1 = P (c/a) 0\n p2 = P ((c-b)/a) 1\n in (p1, p2 $- p1)\n | b /= 0 = let p1 = P 0 (c/b)\n p2 = P 1 ((c-a)/b)\n in (p1, p2 $- p1)\n\nintersectLineCircle :: Line -> Circle -> [ Point ]\nintersectLineCircle l (C q rr) = map (\\t -> a $+ (b $* t)) ts\n where\n (a,b) = toParametric l\n a2 = b $. b\n a1 = ((a $- q) $. b) * 2\n a0 = ((a $- q) $. (a $- q)) - rr\n ts = solveQuadratic a2 a1 a0\n\nintersectCircles :: Circle -> Circle -> [ Point ]\nintersectCircles (C a r1) (C b r2) = intersectLineCircle line (C b r2)\n where\n c = (r1 - r2 - (a $. a) + (b $. b)) / 2\n line = L (b $- a) c\n\nsolve :: Stadium -> Stadium -> Stadium -> [ Point ]\nsolve s1@(S p1 r1) s2@(S p2 r2) s3@(S p3 r3)\n | r1 == r2 && r1 == r3 = intersectLines (bisector p1 p2) (bisector p1 p3)\n | r1 == r2 = intersectLineCircle (bisector p1 p2) (bicircle s1 s3)\n | otherwise = intersectCircles (bicircle s1 s2) (bicircle s1 s3)\n\nreadStadium :: IO Stadium\nreadStadium = do\n line <- getLine\n let (xs:ys:rs:_) = words line\n x = read xs\n y = read ys\n r = read rs\n return $ S (P x y) r\n\nmain = do\n [s1,s2,s3] <- replicateM 3 readStadium\n let sols = solve s1 s2 s3\n case sols of\n [] -> return ()\n (P x y):_ -> putStrLn $ printf \"%.5f %.5f\" x y\n\n"}, {"source_code": "\nimport List (sort)\nimport Maybe (listToMaybe)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\nassertEq' :: Maybe Point -> Maybe Point -> Assertion\nassertEq' (Just (x1, y1)) (Just (x2, y2))\n = case (assertApproximate x1 x2 n, assertApproximate y1 y2 n) of\n (AssertTrue, AssertTrue) -> assertTrue True\n _ -> assertFail $ concat [\"Expected but was <\", show x2, \", \", show y2, \">\"]\n where\n n = 9\nassertEq' a b = assertEq a b \n\ntestSimple :: Test\ntestSimple = Test \"TestSimple\" $\n assertEq' (Just (0, 0)) (solve ((10, 0), 2) ((-10, 0), 2) ((0, 10), 2))\n\ntestFive :: Test\ntestFive = TestList \"TestFive\"\n [\n Test \"1 2 3\" $ assertEq' (Just (0, 0)) (solve ((-5,0), 1) ((3,4), 1) ((0,-5), 1)),\n Test \"1 3 2\" $ assertEq' (Just (0, 0)) (solve ((-5,0), 1) ((0,-5), 1) ((3,4), 1)),\n Test \"2 1 3\" $ assertEq' (Just (0, 0)) (solve ((3,4), 1) ((-5,0), 1) ((0,-5), 1)),\n Test \"2 3 1\" $ assertEq' (Just (0, 0)) (solve ((3,4), 1) ((0,-5), 1) ((-5,0), 1)),\n Test \"3 1 2\" $ assertEq' (Just (0, 0)) (solve ((0,-5), 1) ((-5,0), 1) ((3,4), 1)),\n Test \"3 2 1\" $ assertEq' (Just (0, 0)) (solve ((0,-5), 1) ((3,4), 1) ((-5,0), 1))\n ]\n\ntestZeroOne :: Test\ntestZeroOne = TestList \"testZeroOne\"\n [\n Test \"1 2 3\" $ assertEq' (Just (0.5, sqrt 3 / 6)) (solve ((0,0), 0.1) ((1,0), 0.1) ((0.5, 0.5 * sqrt 3), 0.1))\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1 2 3\" $ assertEq' (Just (30, 0)) (solve ((0, 0), 10) ((60, 0), 10) ((30, 30), 10)),\n Test \"1 3 2\" $ assertEq' (Just (30, 0)) (solve ((0, 0), 10) ((30, 30), 10) ((60, 0), 10)),\n Test \"2 1 3\" $ assertEq' (Just (30, 0)) (solve ((60, 0), 10) ((0, 0), 10) ((30, 30), 10)),\n Test \"2 3 1\" $ assertEq' (Just (30, 0)) (solve ((60, 0), 10) ((30, 30), 10) ((0, 0), 10)),\n Test \"3 1 2\" $ assertEq' (Just (30, 0)) (solve ((30, 30), 10) ((0, 0), 10) ((60, 0), 10)),\n Test \"3 2 1\" $ assertEq' (Just (30, 0)) (solve ((30, 30), 10) ((60, 0), 10) ((0, 0), 10)) \n ]\n\ntestInput' :: Test\ntestInput' = TestList \"TestInput'\"\n [\n Test \"1 2 3\" $ assertEq [-30, 30] (solve' ((0, 0), 10) ((60, 0), 10) ((30, 30), 10)),\n Test \"1 3 2\" $ assertEq [-30, 30] (solve' ((0, 0), 10) ((30, 30), 10) ((60, 0), 10)),\n Test \"2 1 3\" $ assertEq [-30, 30] (solve' ((60, 0), 10) ((0, 0), 10) ((30, 30), 10)),\n Test \"2 3 1\" $ assertEq [-30, 30] (solve' ((60, 0), 10) ((30, 30), 10) ((0, 0), 10)),\n Test \"3 1 2\" $ assertEq [-30, 30] (solve' ((30, 30), 10) ((0, 0), 10) ((60, 0), 10)),\n Test \"3 2 1\" $ assertEq [-30, 30] (solve' ((30, 30), 10) ((60, 0), 10) ((0, 0), 10)) \n ]\n\ntestDiffRadiuses :: Test\ntestDiffRadiuses = TestList \"TestDiffRadiuses\"\n [\n Test \"#1\" $ assertEq' (Just (0,0)) $ solve ((0, 10), 1) ((20,0),2) ((0,-30),3),\n Test \"#1_\" $ assertEq [-10,10] $ solve' ((0, 10), 1) ((20,0),2) ((0,-30),3),\n Test \"#2\" $ assertEq' (Just (1,0)) $ solve ((1, 10), 1) ((21,0),2) ((1,-30),3),\n Test \"#3\" $ assertEq' (Just (-1,0)) $ solve ((-1, 10), 1) ((19,0),2) ((-1,-30),3),\n Test \"#4\" $ assertEq' (Just (0,1)) $ solve ((0, 11), 1) ((20,1),2) ((0,-30+1),3),\n Test \"#4_\" $ assertEq [-10, 10] $ solve' ((0, 11), 1) ((20,1),2) ((0,-30+1),3)\n ] \n\ntestIntersectionCircles :: Test\ntestIntersectionCircles = TestList \"TestIntersectionCircles\"\n [\n Test \"#01\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((0,1),0),\n Test \"#02\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((1,0),0),\n Test \"#03\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((0,-1),0),\n Test \"#04\" $ assertEq [] $ intersectionCircles ((0,0), 0) ((-1,0),0),\n Test \"#05\" $ assertEq [(0,0)] $ intersectionCircles ((1,0), 1) ((-1,0),1),\n Test \"#06\" $ assertEq [(0,0)] $ intersectionCircles ((0,1), 1) ((0,-1),1),\n Test \"#07\" $ assertEq [(4,1)] $ intersectionCircles ((5,1), 1) ((3,1),1), \n Test \"#08\" $ assertEq [(13,-9)] $ intersectionCircles ((13,-8), 1) ((13,-10),1), \n Test \"#09\" $ assertEq [(13,-9)] $ intersectionCircles ((13,0), 9) ((13,-18),9),\n Test \"#10\" $ assertEq [(3,4)] $ intersectionCircles ((0,0), 5) ((6,8),5),\n Test \"#11\" $ assertEq [(-3,4)] $ intersectionCircles ((0,0), 5) ((-18,24),25),\n Test \"#12\" $ assertEq [(23,38)] $ intersectionCircles ((11,29), 15) ((31,44),10),\n Test \"#13\" $ assertEq [(1 / sqrt 2, 1 / sqrt 2)] $ intersectionCircles ((0,0), 1) ((1,1), sqrt 2 - 1),\n Test \"#14\" $ assertEq [(3,4)] $ intersectionCircles ((0,0), 5) ((-3,-4),10), \n Test \"#15\" $ assertEq [(0,2),(2,0)] $ intersectionCircles ((0,0), 2) ((2,2),2),\n Test \"#16\" $ assertEq [] $ intersectionCircles ((0,0), 1) ((1,1),3),\n Test \"#17\" $ assertEq [(0,0)] $ intersectionCircles ((0,10), 10) ((0,-30),30),\n Test \"#18\" $ assertEq [(8,16),(0,0)] $ intersectionCircles ((0,10), 10) ((20,0),20),\n Test \"#19\" $ assertEq [(8,16),(0,0)] $ intersectionCircles ((20,0), 20) ((0,10),10),\n Test \"#20\" $ assertEq [(16,8),(0,0)] $ intersectionCircles ((10,0), 10) ((0,20),20),\n Test \"#21\" $ assertEq [(16,8),(0,0)] $ intersectionCircles ((0,20), 20) ((10,0),10),\n Test \"#22\" $ assertEq [(0,0),(0,0)] $ intersectionCircles ((20,0), 20) ((0,-30),30),\n Test \"#23\" $ assertEq [(3,4),(3,-4)] $ intersectionCircles ((0,0),5) ((6,0),5),\n Test \"#24\" $ assertEq [(3,4),(-3,4)] $ intersectionCircles ((0,0),5) ((0,8),5),\n Test \"#25\" $ assertEq [(4,5),(4,-3)] $ intersectionCircles ((1,1),5) ((7,1),5),\n Test \"#26\" $ assertEq [(4,5),(-2,5)] $ intersectionCircles ((1,1),5) ((1,9),5)\n ]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testSimple,\n testFive,\n testZeroOne,\n testInput,\n testInput',\n testDiffRadiuses,\n testIntersectionCircles\n ]\n-}\n--------------------------------------------------------------------------------\n\neps = 1e-9\n\nquadratic :: (Ord a, Floating a) => a -> a -> a -> a -> [a]\nquadratic eps a b c\n | abs a < eps = if abs b < eps then [] else [-c/b]\n | abs d < eps = [-b/(2*a)]\n | d > 0 = [(-b + sqrt d) / (2*a), (-b - sqrt d) / (2*a)]\n | otherwise = []\n where\n d = b^2 - 4*a*c\n\nbiquadratic :: (Ord a, Floating a) => a -> a -> a -> a -> [a]\nbiquadratic eps a b c = concatMap (getSqrt eps) (quadratic eps a b c)\n where\n getSqrt eps x\n | abs x < eps = [0.0]\n | x > 0 = [-sqrt x, sqrt x]\n | otherwise = []\n\n--------------------------------------------------------------------------------\n\ntype Point = (Double, Double)\ntype Circle = (Point, Double)\n\neq :: Point -> Point -> Bool\neq (x1, y1) (x2, y2) = abs (x1 - x2) < eps && abs (y1 - y2) < eps\n\ndistance :: Point -> Point -> Double\ndistance (ax, ay) (bx, by) = sqrt $ sum $ map (^2) $ zipWith (-) [ax, ay] [bx, by]\n\nintersectionCircles :: Circle -> Circle -> [Point]\nintersectionCircles ((x1, y1), r1) ((x2, y2), r2)\n | abs (r1 + r2 - d) < eps\n = [(x1 * r2 / d + x2 * r1 / d, y1 * r2 / d + y2 * r1 / d)]\n | r1 + r2 - d > 0\n = if abs (x1 - x2) > eps\n then map (\\y -> ((_D - 2 * y * (y1 - y2)) / (2 * (x1 - x2)), y)) ys\n else map (\\x -> (x, (_D - 2 * x * (x1 - x2)) / (2 * (y1 - y2)))) xs\n | otherwise = []\n where\n d = distance (x1, y1) (x2, y2)\n _D = x1^2 - x2^2 + y1^2 - y2^2 - (r1^2 - r2^2)\n _Ax = ((x1 - x2) / (y1 - y2))^2 + 1\n _Bx = -2 * x1 - (_D / (y1 - y2) - 2 * y1) * (x1 - x2) / (y1 - y2)\n _Cx = x1^2 - r1^2 + (_D / (2 * (y1 - y2)) - y1)^2\n xs = quadratic eps _Ax _Bx _Cx\n _Ay = ((y1 - y2) / (x1 - x2))^2 + 1\n _By = -2 * y1 - (_D / (x1 - x2) - 2 * x1) * (y1 - y2) / (x1 - x2)\n _Cy = y1^2 - r1^2 + (_D / (2 * (x1 - x2)) - x1)^2\n ys = quadratic eps _Ay _By _Cy\n\n--------------------------------------------------------------------------------\n\nfindEqPoint :: [Point] -> [Point] -> [Point]\nfindEqPoint ps1 ps2 = [p1 | p1 <- ps1, p2 <- ps2, eq p1 p2]\n\nsolve :: Circle -> Circle -> Circle -> Maybe Point\nsolve c1@(o1, r1) c2@(o2, r2) c3@(o3, r3) = listToMaybe $ do\n r1' <- roots\n let r2' = r1' * r2/r1\n let r3' = r1' * r3/r1\n let ps2 = intersectionCircles (o1, r1') (o2, r2')\n let ps3 = intersectionCircles (o1, r1') (o3, r3')\n findEqPoint ps2 ps3\n where\n roots = filter (>0) (solve' c1 c2 c3)\n\nsolve' :: Circle -> Circle -> Circle -> [Double]\nsolve' (o1, r1) (o2, r2) (o3, r3) = sort $ biquadratic eps _A _B _C\n where\n a = distance o2 o3\n b = distance o1 o3\n c = distance o1 o2 \n cosA = (b^2 + c^2 - a^2) / (2*b*c) \n _R21 = 1 - (r2/r1)^2\n _R31 = 1 - (r3/r1)^2 \n _A = _R21^2 / (4 * c^2) + _R31^2 / (4 * b^2) - cosA * _R21 * _R31 / (2 * b * c)\n _B = _R21 / 2 + _R31 / 2 - (1 - cosA^2) - cosA * (b * _R21 / (2*c) + c * _R31 / (2 * b))\n _C = c^2 / 4 + b^2 / 4 - cosA * b * c / 2 \n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- getLine >>= return . map read . words\n return ((x, y), r)\n\nprintAns :: Maybe Point -> IO ()\nprintAns Nothing = return ()\nprintAns (Just (x, y)) = putStrLn $ concat [show x, \" \", show y]\n\nmain :: IO ()\nmain = do\n c1 <- readCircle\n c2 <- readCircle\n c3 <- readCircle\n printAns $ solve c1 c2 c3\n"}, {"source_code": "module Main where\n\t\nimport Data.List\n\ndata Point = Point {\n\tx :: Double,\n\ty :: Double\n} deriving (Show)\n\ndata Circle = Circle {\n\tc :: Point,\n\tr :: Double\n} deriving (Show)\n\ncircleFromString :: String -> Circle\ncircleFromString s = \n\tCircle (Point (l !! 0) (l !! 1)) (l !! 2)\n\twhere l = map read $ words s\n\npointAdd :: Point -> Point -> Point\npointAdd (Point x1 y1) (Point x2 y2) = Point (x1 + x2) (y1 + y2)\n\nprocessInput :: String -> [Circle]\nprocessInput = map circleFromString . lines\n\ndistance :: Point -> Point -> Double\ndistance (Point x1 y1) (Point x2 y2) = \n\tsqrt $ (x1 - x2) ** 2 + (y1 - y2) ** 2\n\nangleToCircle :: Point -> Circle -> Double\nangleToCircle p (Circle c r) = \n\t(distance c p) / r\n\nsquareMean :: [Double] -> Double\nsquareMean a = \n\t(sum $ map ((** 2) . (+ m)) a) / n\n\twhere\n\t\tn = fromIntegral $ length a\n\t\tm = - sum a / n\n\ntryPoint :: [Circle] -> Point -> Double\ntryPoint circles p = \n\tsquareMean $ map (angleToCircle p) $ circles\n--\twhere \n--\t\tsumAngle = sum (map angleToCircle circles) / 3\n\t\t\n\niterateTry :: [Circle] -> Point -> Point\niterateTry cs startPoint = \n\titer startPoint 1.0\n\twhere\n\t\titer p d\n\t\t\t| d < 1e-6 = p\n\t\t\t| (fst minimumPoint < currentDistance) = iter (snd minimumPoint) d\n\t\t\t| otherwise = iter p (d * 0.8)\n\t\t\twhere \n\t\t\t\tcurrentDistance = tryPoint cs p\n\t\t\t\tmeasure = tryPoint cs\n\t\t\t\ttryList = [pointAdd p (Point 0 d), pointAdd p (Point d 0), pointAdd p (Point 0 (0-d)), pointAdd p (Point (0-d) 0)]\n\t\t\t\tminimumPoint = minimumBy (\\(a, _) (b, _) -> compare a b) $ zip (map measure tryList) tryList\n\nsolve :: [Circle] -> String\nsolve cs = \n\tlet \n\t\tstartPoint = Point { x = (sum $ map (x . c) cs) / 3, y = (sum $ map (y . c) cs) / 3 }\n\t\tendPoint = iterateTry cs startPoint\n\tin (show (x endPoint)) ++ \" \" ++ (show (y endPoint))\n\nmain = do\n\tinput <- getContents\n\tlet circles = processInput input\n\tputStrLn $ solve circles\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad (replicateM)\nimport Data.Functor ((<&>))\nimport Data.List (foldl', minimumBy)\nimport Text.Printf (printf)\n\nstadiums = [\n Circle (Point 0 0) 10,\n Circle (Point 60 0) 10,\n Circle (Point 30 30) 10\n ]\n\nmain :: IO ()\nmain = do\n result <- solve <$> replicateM 3 readCircle\n case result of\n Just (Point x y) -> printf \"%.5f %.5f\\n\" x y\n _ -> return ()\n\n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words\n pure $ Circle (Point x y) r\n\ndata Point = Point {\n x :: Double,\n y :: Double\n} deriving (Show, Eq)\n\ndata Circle = Circle {\n center :: Point,\n radius :: Double\n} deriving (Show)\n\neps :: Double\neps = 1e-8\n\nisSmall :: Double -> Bool\nisSmall = (< eps) . abs\n\nangleWeight :: Point -> Circle -> Double\nangleWeight p (Circle c r) = dist p c / r\n\nmean :: [Double] -> Double\nmean ws = total / n\n where\n (total, n) = foldl' step (0, 0) ws\n step (cw, cn) w1 = (cw + w1, cn + 1)\n\nsq :: Double -> Double\nsq x = x * x\n\nsquareMean :: [Double] -> Double\nsquareMean ws = sqrt . sum . map (sq . (-) m) $ ws\n where\n m = mean ws\n\n\ndist :: Point -> Point -> Double\ndist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)\n\ninitialGuess :: [Circle] -> Point\ninitialGuess circles = Point (x / n) (y / n)\n where\n (n, Point x y) = foldl' step (0, Point 0 0) circles\n step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))\n\nminimumOn :: (Ord b) => (a -> b) -> [a] -> a\nminimumOn c = minimumBy (\\x y -> compare (c x) (c y))\n\nmeanWeight :: [Circle] -> Point -> Double\nmeanWeight stadiums p = squareMean $ map (angleWeight p) stadiums\n\nfindBestGuess :: [Circle] -> Point\nfindBestGuess stadiums = solve0 (initialGuess stadiums) 1.0\n where\n candidates cur@(Point x y) c = [Point (x + c) y, Point (x - c) y, cur, Point x (y - c), Point x (y + c)]\n bestMatch = minimumOn (meanWeight stadiums)\n solve0 p c | c < 1e-6 = p\n solve0 p c = let nextGuess = bestMatch $ candidates p c in\n solve0 nextGuess (if nextGuess == p then c / 2 else c)\n\nisGood :: [Circle] -> Point -> Bool\nisGood stadiums guess = isSmall (meanWeight stadiums guess)\n\nsolve :: [Circle] -> Maybe Point\nsolve stadiums = if isGood stadiums guess then Just guess else Nothing\n where\n guess = findBestGuess stadiums"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad (replicateM, forM_)\nimport Data.Functor ((<&>))\nimport Data.List (foldl', minimumBy)\nimport Text.Printf (printf)\n\nmain :: IO ()\nmain = do\n result <- solve <$> replicateM 3 readCircle\n forM_ result $ \\(Point x y) -> printf \"%.5f %.5f\\n\" x y\n\nreadCircle :: IO Circle\nreadCircle = do\n [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words\n pure $ Circle (Point x y) r\n\ndata Point = Point {\n x :: Double,\n y :: Double\n} deriving (Show, Eq)\n\ndata Circle = Circle {\n center :: Point,\n radius :: Double\n} deriving (Show)\n\neps :: Double\neps = 1e-8\n\nisSmall :: Double -> Bool\nisSmall = (< eps) . abs\n\nangleWeight :: Point -> Circle -> Double\nangleWeight p (Circle c r) = dist p c / r\n\nmean :: [Double] -> Double\nmean ws = total / n\n where\n (total, n) = foldl' step (0, 0) ws\n step (cw, cn) w1 = (cw + w1, cn + 1)\n\nsq :: Double -> Double\nsq x = x * x\n\nsquareMean :: [Double] -> Double\nsquareMean ws = sqrt . sum . map (sq . (-) m) $ ws\n where\n m = mean ws\n\ndist :: Point -> Point -> Double\ndist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)\n\ninitialGuess :: [Circle] -> Point\ninitialGuess circles = Point (x / n) (y / n)\n where\n (n, Point x y) = foldl' step (0, Point 0 0) circles\n step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))\n\nminimumOn :: (Ord b) => (a -> b) -> [a] -> a\nminimumOn c = minimumBy (\\x y -> compare (c x) (c y))\n\nmeanWeight :: [Circle] -> Point -> Double\nmeanWeight stadiums p = squareMean $ map (angleWeight p) stadiums\n\nfindBestGuess :: [Circle] -> Point\nfindBestGuess stadiums = solve0 (initialGuess stadiums) 1.0\n where\n candidates cur@(Point x y) c = [Point (x + c) y, Point (x - c) y, cur, Point x (y - c), Point x (y + c)]\n bestMatch = minimumOn (meanWeight stadiums)\n solve0 p c | c < 1e-6 = p\n solve0 p c = let nextGuess = bestMatch $ candidates p c in\n solve0 nextGuess (if nextGuess == p then c / 2 else c)\n\nisGood :: [Circle] -> Point -> Bool\nisGood stadiums guess = isSmall (meanWeight stadiums guess)\n\nsolve :: [Circle] -> Maybe Point\nsolve stadiums = if isGood stadiums guess then Just guess else Nothing\n where\n guess = findBestGuess stadiums"}], "src_uid": "9829e1913e64072aadc9df5cddb63573"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.List\nimport Data.Int\nimport Data.Array.Unboxed\n\ndata P = P {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64 deriving (Eq, Ord)\n\nmain = do\n [n, s] <- fmap readInts B.getLine\n ps <- replicateM n $ fmap ((\\[x, v, d] -> P (fromIntegral x) (fromIntegral $ if d == 1 then -v else v)) . readInts) B.getLine\n print $ solve (fromIntegral s) ps\n\nsolve s ps = minimum $ zipWith max tls trs\n where\n hi = 1000000 :: Int64\n (ls, rs) = partition (\\(P _ pv) -> pv < 0) $ sort ps\n tls = snd $ mapAccumL (go (\\x px pv -> if x * pv > -s * px then toD (x * s + pv * px) / toD (s * s - pv * pv) else -1) (minimum $ map (\\(P px pv) -> toD (-px) / toD pv) ls)) (Nothing, ls) [1..hi - 1]\n trs = elems (array (1, hi - 1) $ zip [hi - 1, hi - 2..1] $ snd $ mapAccumL (go (\\x px pv -> let x' = hi - x; px' = hi - px in if x' * pv < s * px' then toD (x' * s - pv * px') / toD (s * s - pv * pv) else -1) (minimum $ map (\\(P px pv) -> toD (hi - px) / toD pv) rs)) (Nothing, reverse rs) [hi - 1, hi - 2..1] :: UArray Int64 Double)\n go clock (!m) st@(!mp', !pps) (!x)\n | (p@(P !px !pv):ps) <- pps, x == px = ((Just p, ps), min m $ clock x px pv)\n | Just (P !px' !pv') <- mp' = let t' = clock x px' pv' in if t' > 0 then (st, min m t') else ((Nothing, pps), m)\n | otherwise = (st, m)\n\ntoD x = fromIntegral x :: Double\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.List\nimport Data.Int\nimport Data.Array.Unboxed\n\nmain = do\n [n, s] <- fmap readInts B.getLine\n ps <- replicateM n $ fmap ((\\[x, v, d] -> (fromIntegral x, fromIntegral $ if d == 1 then -v else v)) . readInts) B.getLine\n print $ solve (fromIntegral s) ps\n\nsolve s ps = minimum $ zipWith max tls trs\n where\n hi = 1000000 :: Int64\n (ls, rs) = partition ((< 0) . snd) $ sort ps\n tls = snd $ mapAccumL (go (\\x px pv -> if x * pv > -s * px then toD (x * s + pv * px) / toD (s * s - pv * pv) else -1) (minimum $ map (\\(px, pv) -> toD (-px) / toD pv) ls)) (Nothing, ls) [1..hi - 1]\n trs = elems (array (1, hi - 1) $ zip [hi - 1, hi - 2..1] $ snd $ mapAccumL (go (\\x px pv -> let x' = hi - x; px' = hi - px in if x' * pv < s * px' then toD (x' * s - pv * px') / toD (s * s - pv * pv) else -1) (minimum $ map (\\(px, pv) -> toD (hi - px) / toD pv) rs)) (Nothing, reverse rs) [hi - 1, hi - 2..1] :: UArray Int64 Double)\n go clock m st@(mp', pps) x\n | (p@(px, pv):ps) <- pps, x == px = ((Just p, ps), min m $ clock x px pv)\n | Just (px', pv') <- mp' = let t' = clock x px' pv' in if t' > 0 then (st, min m t') else ((Nothing, pps), m)\n | otherwise = (st, m)\n\ntoD x = fromIntegral x :: Double\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.List\nimport Data.Int\nimport Data.Ord\n\nmain = do\n [n, s] <- fmap readInts B.getLine\n ps <- replicateM n $ fmap ((\\[x, v, d] -> (fromIntegral x, fromIntegral $ if d == 1 then -v else v)) . readInts) B.getLine\n print $ solve (fromIntegral s) ps\n\nsolve s ps = minimum $ zipWith max tls trs\n where\n hi = 1000000 :: Int64\n\n (ls, rs) = partition ((< 0) . snd) $ sortBy (comparing fst) ps\n\n tls = snd $ mapAccumL (go clock m) (Nothing, ls) [1..hi - 1]\n where \n m = minimum $ map (\\(px, pv) -> toD (-px) / toD pv) ls\n clock x px pv \n | x * pv > -s * px = toD (x * s + pv * px) / toD (s * s - pv * pv)\n | otherwise = -1\n\n trs = snd $ mapAccumR (go clock m) (Nothing, rs) [1..hi - 1]\n where \n m = minimum $ map (\\(px, pv) -> toD (hi - px) / toD pv) rs\n clock x px pv \n | x' * pv < s * px' = toD (x' * s - pv * px') / toD (s * s - pv * pv)\n | otherwise = -1\n where \n x' = hi - x\n px' = hi - px\n\n go _ m st@(Nothing, []) _ = (st, m)\n go clock m st@(Nothing, p@(px, pv):ps) x \n | x == px = let t = clock x px pv in if t > 0 then ((Just p, ps), min m t) else ((Nothing, ps), m)\n | otherwise = (st, m)\n go clock m st@(Just (px, pv), []) x = (st, min m $ clock x px pv)\n go clock m (mp@(Just (mpx, mpv)), p@(px, pv):ps) x \n | t' > 0 && t' < t = ((Just p, ps), min t' m)\n | otherwise = ((mp, ps), min t m)\n where\n t' = clock x px pv\n t = clock x mpx mpv\n\ntoD x = fromIntegral x :: Double\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.List\n\ndata Person = Person !Double !Double deriving Show\n\nmain = do\n [n, s] <- fmap readInts B.getLine\n ps <- replicateM n $ fmap ((\\[x, v, d] -> Person (toD x) (toD $ if d == 1 then -v else v)) . readInts) B.getLine\n print $ solve (toD s) ps\n\nsolve s ps = clock $ toD $ go 1 hi\n where\n (ls, rs) = partition (\\(Person _ v) -> v < 0) ps\n hi = 1000000 :: Int\n hiD = toD hi\n\n go l r\n | r - l <= 1 = l\n | otherwise = if clock (toD m) > clock (toD l) then go l m else go m r\n where m = (l + r) `div` 2\n\n clock x = max (minimum tls) (minimum trs)\n where\n tls = map (\\(Person px pv) -> let t1 = (px - x) / (-s - pv); x' = x + (-s) * t1 in if px > x || x' <= 0 then (-px) / pv else let t2 = (-x') / (-s + pv) in t1 + t2) ls\n trs = map (\\(Person px pv) -> let t1 = (px - x) / (s - pv); x' = x + s * t1 in if px < x || x' >= hiD then (hiD - px) / pv else let t2 = (hiD - x') / (s + pv) in t1 + t2) rs\n\ntoD x = fromIntegral x :: Double\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "src_uid": "7de7e7983909d7a8f51fee4fa9ede838"} {"source_code": "import qualified Data.List as L\n\nreadInts :: IO [Int]\nreadInts = do\n input <- getLine\n return $ map read . words $ input\n\nsplitOnHalf :: [a] -> ([a], [a])\nsplitOnHalf xs = (take half xs, drop half xs)\n where half = div (length xs) 2\n\nequalArea :: [Int] -> [Int] -> Int -> Bool\n\nequalArea [] [] _ = True\nequalArea (x1:x2:xs) (y1:y2:ys) area = \n x1 == x2 && y1 == y2 && (x1 * y2) == area && equalArea xs ys area\n\nsolve :: [Int] -> Bool\nsolve xs = \n equalArea s b' $ (head s) * (head b')\n where \n b' = reverse b\n (s, b) = splitOnHalf xs\n\nhandleCase :: Int -> IO ()\n\nhandleCase 0 = do return ()\nhandleCase t = do\n n <- getLine\n a <- readInts\n putStrLn $ if solve(L.sort a) == True then \"YES\" else \"NO\"\n handleCase(t-1)\n\nmain = do\n t <- getLine \n handleCase (read t)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n \nmain = do\n q <- readInt\n submain q\n return q\n \nreadInt = do\n raw_q <- getLine\n let q = read raw_q :: Int\n return q\n \nreadlist = do\n inp <- getLine\n let v = words inp\n let ret = map read v\n return ret\n \nsubmain:: Int -> IO ()\nsubmain q = do\n when (q > 0) $ do\n sz <- readInt\n v <- readlist\n putStrLn $ if (solve v) then \"YES\" else \"NO\"\n submain $ q - 1\n return ()\n \nsolve :: [Int] -> Bool\nsolve v = \n isPaired v' && canFormEqAreaRec v' rv' 0 \n where \n v' = group $ sort v\n rv' = reverse v'\n \n \nisPaired :: [[Int]] -> Bool\nisPaired = all (even . length)\n \ncanFormEqAreaRec :: [[Int]] -> [[Int]] -> Int -> Bool\ncanFormEqAreaRec [] [] _ = True\ncanFormEqAreaRec v rv 0 =\n canFormEqAreaRec v rv (x0 * y0)\n where\n x:xs = v\n y:ys = rv\n x0:xx = x\n y0:yy = y\n \ncanFormEqAreaRec (x:xs) (y:ys) area =\n length x == length y && \n x0 * y0 == area && \n canFormEqAreaRec xs ys area \n where \n x0:xx = x\n y0:yy = y\n "}, {"source_code": "import Control.Monad\nimport Data.List\n\nreadInt = do\n raw_q <- getLine\n let q = read raw_q :: Int\n return q\n \nreadlist = do\n inp <- getLine\n return $ map read (words inp)\n\nmain = do\n q <- readInt\n submain q\n return q\n \nsubmain :: Int -> IO ()\nsubmain q = do\n when (q > 0) $ do\n sz <- readInt\n v <- readlist\n putStrLn $ if (solve (sort v)) then \"YES\" else \"NO\"\n submain $ q - 1\n return ()\n \ncountDupList v@(x:xs) = (x, length v)\n\ngroupToTuple x = map countDupList $ group x\n\nsolve :: [Int] -> Bool\nsolve v = \n canFormEqAreaRec v rv (head v * head rv)\n where rv = reverse v\n \ncanFormEqAreaRec [] [] _ = True\ncanFormEqAreaRec (x0:x1:xs) (y0:y1:ys) area =\n x0 == x1 && y0 == y1 && x0 * y0 == area && \n canFormEqAreaRec xs ys area \n "}], "negative_code": [{"source_code": "import qualified Data.List as L\n\nreadInts :: IO [Int]\nreadInts = do\n input <- getLine\n return $ map read . words $ input\n\nsplitOnHalf :: [a] -> ([a], [a])\nsplitOnHalf xs = (take half xs, drop half xs)\n where half = div (length xs) 2\n\nequalArea :: [Int] -> [Int] -> Int -> Bool\n\nequalArea [] [] _ = True\nequalArea (x1:x2:xs) (y1:y2:ys) area = \n x1 == x2 && y1 == y2 && (x1 * y2) == area && equalArea xs ys area\n\nsolve :: [Int] -> Bool\nsolve xs = \n equalArea s b $ (head s) * (head b)\n where (s, b) = splitOnHalf xs\n\nhandleCase :: Int -> IO ()\n\nhandleCase 0 = do return ()\nhandleCase t = do\n n <- getLine\n a <- readInts\n putStrLn $ if solve(a) == True then \"YES\" else \"NO\"\n handleCase(t-1)\n\nmain = do\n t <- getLine \n handleCase (read t)\n"}], "src_uid": "08783e3dff3f3b7eb586931f9d0cd457"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Function\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n] <- ri\r\n xs <- ri\r\n return xs\r\n mapM_ (putStrLn . show . solve) tcs\r\n\r\nsolve xs = min 2 . length . filter ((/=0).head) . L.groupBy ((==)`on`(==0)) $ xs\r\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- int <$> B.getLine\r\n forM_ [1 .. t] $ \\_ -> do\r\n _ <- B.getLine\r\n as <- map int . C.words <$> B.getLine\r\n let bs = reverse . dropWhile (== 0) . reverse . dropWhile (== 0) $ as\r\n if null bs\r\n then print 0\r\n else\r\n if 0 `elem` bs\r\n then print 2\r\n else print 1\r\n\r\nint :: B.ByteString -> Int\r\nint = fst . fromJust . C.readInt\r\n"}, {"source_code": "import Control.Monad (forM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n forM_ [1 .. t] $ \\_ -> do\r\n _ <- getLine\r\n as <- map read . words <$> getLine\r\n let bs = reverse . dropWhile (== 0) . reverse . dropWhile (== 0) $ as\r\n if null bs\r\n then print 0\r\n else\r\n if 0 `elem` bs\r\n then print 2\r\n else print 1\r\n"}], "negative_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Function\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n] <- ri\r\n xs <- ri\r\n return xs\r\n mapM_ (putStrLn . show . solve) tcs\r\n\r\nsolve xs = length . filter ((/=0).head) . L.groupBy ((==)`on`(==0)) $ xs\r\n"}], "src_uid": "da3d1b2615d51044a7b43bd0ce939f4c"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n#ifdef DEBUG\nimport Debug.Trace\n#endif\nimport Foreign\n\nmain :: IO ()\nmain = do\n [h, w]<- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine\n cs <- filter (not.isSpace) <$> getContents\n putStrLn.bool\"NO\"\"YES\" $ solve h w cs\n\nsolve :: Int -> Int -> String -> Bool\nsolve _ _ cs | all (== '.') cs = False\nsolve h w cs = minx < x && x < maxx && miny < y && y < maxy && set == cross\n where\n xys = [quotRem ij w|(ij, '*')<-zip[0..]cs]\n !set = S.fromList xys\n !minx = minimum $ map fst xys\n !maxx = maximum $ map fst xys\n !miny = minimum $ map snd xys\n !maxy = maximum $ map snd xys\n !x = fst . head $ filter ((==miny).snd) xys\n !y = snd . head $ filter ((==minx).fst) xys\n cross = S.fromList $ map ((,) x) [miny..maxy] ++ map (flip (,) y) [minx..maxx]\n", "positive_code": [{"source_code": "import Data.List\n\nmain = interact $ solve . tail . lines\n\nsolve :: [String] -> String\nsolve board = \n let goal = length . filter (=='*') $ concat board in\n let tBoard = transpose board in\n let populatedRows = filter ((>=2) . length . filter (=='*') . (!!) board) [0..length board-1] in\n let populatedCols = filter ((>=2) . length . filter (=='*') . (!!) tBoard) [0..length tBoard-1] in\n if length populatedRows == 1 && length populatedCols == 1\n then \n let r = head populatedRows in\n let c = head populatedCols in\n if board !! r !! c == '*' \n then\n let right = length . takeWhile (=='*') $ drop (c + 1) (board !! r) in\n let left = length . takeWhile (=='*') . reverse $ take c (board !! r) in\n let up = length . takeWhile (=='*') . reverse $ take r (tBoard !! c) in\n let down = length . takeWhile (=='*') $ drop (r + 1) (tBoard !! c) in\n if right + left + up + down + 1 == goal &&\n right >= 1 && left >= 1 &&\n up >= 1 && down >= 1\n then \"YES\\n\"\n else \"NO\\n\"\n else \"NO\\n\"\n else \"NO\\n\"\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = interact $ solve . tail . lines\n\nsolve :: [String] -> String\nsolve board = \n let goal = length . filter (=='*') $ concat board in\n let tBoard = transpose board in\n let populatedRows = filter ((>=2) . length . filter (=='*') . (!!) board) [0..length board-1] in\n let populatedCols = filter ((>=2) . length . filter (=='*') . (!!) tBoard) [0..length tBoard-1] in\n if length populatedRows == 1 && length populatedCols == 1\n then \n let r = head populatedRows in\n let c = head populatedCols in\n if board !! r !! c == '*' \n then\n let right = length . takeWhile (=='*') $ drop (c + 1) (board !! r) in\n let left = length . takeWhile (=='*') . reverse $ take c (board !! r) in\n let up = length . takeWhile (=='*') . reverse $ take r (tBoard !! c) in\n let down = length . takeWhile (=='*') $ drop (r + 1) (tBoard !! c) in\n if right + left + up + down + 1 == goal\n then \"YES\\n\"\n else \"NO\\n\"\n else \"NO\\n\"\n else \"NO\\n\"\n"}], "src_uid": "6405161be280fea943201fa00ef6f448"} {"source_code": "import Control.Monad\r\nreadFloats = fmap (map read.words) getLine :: IO [Float]\r\n\r\nsolve [x] = 0\r\nsolve (x:y:xs) = solve (y:xs) + if h <= 1 then 0 else h - 1\r\n where\r\n h = ceiling $ logBase 2 (max x y / min x y)\r\n\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <-readFloats\r\n print $ solve a\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Debug.Trace\n \nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n replicateM_ n action\n \naction = do\n getLine\n arr <- (map (read :: String -> Int) . words) <$> getLine\n print (calc arr)\n \ncalc :: [Int] -> Int\ncalc (first:rest) = magic 0 first rest\n where\n magic res _ [] = res\n magic res prev (cur:rest) = let p = fromIntegral prev\n c = fromIntegral cur\n f = (max p c - 1) / (min p c)\n x = max 0.0 $ logBase 2 f\n in magic (res + floor x) cur rest"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Bits\n\ntype SIO = StateT P.ByteString IO\n\nceilDiv :: Int -> Int -> Int\nceilDiv n k = div (n + k - 1) k\n\nbitFloor :: Word -> Word\nbitFloor v\n | v <= 1 = v\n | otherwise = 1 + shiftR (complement 0) (countLeadingZeros v + 1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n putInts $ pure $ foldl' (+) 0 $ do\n (prev, curr) <- zip a (tail a)\n let\n res = ceilDiv (max prev curr) (min prev curr)\n steps = if res > 1 -- typo, extra yikes\n then countTrailingZeros $ bitFloor $ fromIntegral $ res - 1\n else 0 -- forgot about -1, silly move\n pure $ fromIntegral steps\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "chunksOf x [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr = map read . words\r\n\r\ngetInput [_, s] = toArr s\r\n\r\nteto n d = 1 + ((n - 1) `div` d)\r\n\r\nlog2 0 = 0\r\nlog2 1 = 0\r\nlog2 x = 1 + log2 (x `div` 2)\r\n\r\nsolve [] = 0\r\nsolve [_] = 0\r\nsolve (x : y : xs) = log2 (z - 1) + solve (y : xs)\r\n where z = max (teto x y) (teto y x)\r\n\r\nmain = interact (unlines . map (show . solve . getInput) . chunksOf 2 . tail . lines)\r\n\r\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\n\r\npowerTwo :: Integer -> Integer -> Integer\r\npowerTwo x y | 2 * x >= y = 0\r\npowerTwo x y | 2 * x < y = 1+powerTwo (2*x) y\r\n\r\nresult [] = 0\r\nresult [x] = 0\r\nresult (x:y:xs)\r\n\t| x > y = powerTwo y x + result (y:xs)\r\n\t| otherwise = powerTwo x y + result (y:xs)\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tprint $ result a \r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "module Main where\nimport Control.Monad ( replicateM_ )\n\nsolve :: [Int] -> Int\nsolve xs = sum $ zipWith go xs (tail xs)\n where\n go a b = length $ takeWhile (< max a b) (tail $ iterate (*2) (min a b))\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n (getLine >> readInts >>= print . solve)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n getLine\n a <- getIntList\n print $ f a\n\nf :: [Int] -> Int\nf a = sum . zipWith g a $ tail a\n\ng :: Int -> Int -> Int\ng x y\n | x > y = g y x\n | x * 2 >= y = 0\n | otherwise = g (x * 2) y + 1\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n as <- popInts\n return $ bshow $ solve n as\n\n\nsolve n as = sum $ map (uncurry f) $ adjlist as\n where\n f a b | a > b = f b a\n | otherwise = fromJust $ findIndex (\\x -> b <= x) $\n iterate' (* 2) (a * 2)\n\n\nadjlist as@(_ : as') = zip as as'\nadjlist _ = []\n"}, {"source_code": "needed :: Integer -> Integer -> Integer\nneeded small big\n | 2 * small >= big = 0\n | otherwise = 1 + needed (2 * small) big\n\nsolveTest :: [Integer] -> Integer\nsolveTest [] = 0\nsolveTest [_] = 0\nsolveTest (x:y:rest) = needed (min x y) (max x y) + solveTest (y:rest)\n\nsolve :: String -> String\nsolve = unlines . map solveStringTest . odds . drop 1 . lines\n where odds [] = []\n odds (_:x:xs) = x : odds xs\n solveStringTest = show . solveTest . map read . words\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "import Control.Monad\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Int]\nreadInts = readArray\n\nreadInt :: IO Int\nreadInt = readLn\n\ninterpolate :: Int -> Int -> Int\ninterpolate x y = if x > y then interpolate y x else\n if 2 * x >= y then 0 else 1 + interpolate (2 * x) y\n\nsolve :: [Int] -> Int\nsolve (x:y:xs) = interpolate x y + solve (y:xs)\nsolve _ = 0\n\nmain :: IO ()\nmain = readInt >>= flip replicateM_ (readInt >> fmap solve readInts >>= print)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n replicateM_ n action\n\naction = do\n getLine\n arr <- (map (read :: String -> Int) . words) <$> getLine\n print (calc arr)\n\ncalc :: [Int] -> Int\ncalc (first:rest) = magic 0 first rest\n where\n magic :: Int -> Int -> [Int] -> Int\n magic res _ [] = res\n magic res prev (cur:rest) = let big = max prev cur\n smol = min prev cur\n in magic (fst $ head $ dropWhile (\\(_, s) -> s < big) $ iterate (\\(cnt, upd) -> (cnt + 1, upd * 2)) (res - 1, smol)) cur rest"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- ((read :: String -> Int) <$> getLine)\n replicateM_ n action\n\naction = do\n getLine\n arr <- (map (read :: String -> Int) . words) <$> getLine\n print (calc arr)\n\ncalc :: [Int] -> Int\ncalc (first:rest) = magic 0 first rest\n where\n magic res _ [] = res\n magic res prev (cur:rest) = let p = fromIntegral prev\n c = fromIntegral cur\n f = (max p c - 1) / (min p c)\n x = logBase 2 f\n in magic (res + floor x) cur rest"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Bits\n\ntype SIO = StateT P.ByteString IO\n\nceilDiv :: Int -> Int -> Int\nceilDiv n k = div (n + k - 1) k\n\nbitFloor :: Word -> Word\nbitFloor v\n | v <= 1 = v\n | otherwise = 1 + shiftR (complement 0) (countLeadingZeros v + 1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n putInts $ pure $ foldl' (+) 0 $ do\n (prev, curr) <- zip a (tail a)\n let\n res = ceilDiv (max prev curr) (min prev curr)\n steps = if res > 0\n then countTrailingZeros $ bitFloor $ fromIntegral $ res - 1\n else 0 -- forgot about -1, silly move\n pure $ fromIntegral steps\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Bits\n\ntype SIO = StateT P.ByteString IO\n\nceilDiv :: Int -> Int -> Int\nceilDiv n k = div (n + k - 1) k\n\nbitFloor :: Word -> Word\nbitFloor v\n | v <= 1 = v\n | otherwise = 1 + shiftR (complement 0) (countLeadingZeros v + 1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n putInts $ pure $ foldl' (+) 0 $ do\n (prev, curr) <- zip a (tail a)\n let\n res = ceilDiv (max prev curr) (min prev curr)\n steps = countTrailingZeros $ bitFloor $ fromIntegral $ res - 1\n pure $ fromIntegral steps\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "a544dd9fd96379f66a960de6f973dd50"} {"source_code": "mainCase :: [Int] -> Int -> Int -> Bool\nmainCase [] ones twos = and [even ones, or [even twos, ones >= 2]]\nmainCase (1 : xs) ones twos = mainCase xs (ones+1) twos\nmainCase (2 : xs) ones twos = mainCase xs ones (twos+1)\n\ntestCase :: [Int] -> String\ntestCase candies = if mainCase candies 0 0 then \"yes\" else \"no\"\n\nmain = do\n\tgetLine\n\tcontents <- getContents\n\tlet importantLines = map (fst) $ filter (odd . snd) $ zip (lines contents) [0..]\n\tlet testCases = map (map (read) . words) importantLines\n\tputStrLn $ unlines $ map (testCase) testCases\n\t\n", "positive_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nanswer :: [Bool] -> String\nanswer test\n | any (==True) test = \"YES\"\n | otherwise = \"NO\"\n\ncanSplit as (cnt1, cnt2) = do\n let sm = cnt1 + 2 * cnt2\n\n sm == sum(as) - sm\n\nsolve = do\n s1 <- B.getLine\n s2 <- B.getLine\n\n let n = fst $ fromJust $ C.readInt s1\n let as = map (fst . fromJust . C.readInt) (C.words s2)\n\n let cnt1 = length $ filter (1==) as\n let cnt2 = length $ filter (2==) as\n\n let pairs = [(x, y) | x <- [0..cnt1], y <- [0..cnt2]]\n\n putStrLn $ answer $ map (canSplit as) pairs\n\nmain = do\n str <- B.getLine\n\n let t = fst $ fromJust $ C.readInt str\n\n replicateM_ t solve\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nreadInt :: IO Integer\nreadInt = readLn\n\nhist :: [Integer] -> (Integer, Integer)\nhist [] = (0, 0)\nhist (x:xs) = let (a, b) = hist xs in if x == 1 then (a + 1, b) else (a, b + 1)\n\nres :: Bool -> String\nres True = \"YES\"\nres False = \"NO\"\n\nsolveInner :: Integer -> Bool -> Bool\nsolveInner sum any\n | sum `mod` 2 /= 0 = False\n | (sum `div` 2) `mod` 2 == 0 = True\n | otherwise = any\n\nsolve :: [Integer] -> Bool\nsolve l = let (a, b) = hist l in solveInner (a + 2 * b) (a > 0)\n\nsolveCase :: IO String\nsolveCase = readInt >> fmap (res . solve) readInts\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.Array.ST(runSTArray, STArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\nnumOcc :: Ord a => [a] -> M.Map a Integer\r\nnumOcc (x:xs) = let m = numOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m \r\n\tNothing -> M.insert x 1 m \r\nnumOcc [] = M.empty\r\n\r\n\r\nnumOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer\r\nnumOcc' size list = runSTArray $ do \r\n\tarray <- MA.newArray size 0\r\n\tfoldM (addElem array) () list\r\n\treturn array \r\n\r\n\twhere\r\n\t\taddElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()\r\n\t\taddElem array action a = do\r\n\t\t\ti <- MA.readArray array a\r\n\t\t\tMA.writeArray array a (i+1) \r\n\t\r\n\r\n\r\ninsertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]\r\ninsertWithList a b m = case M.lookup a m of \r\n\tJust l -> M.insert a (b:l) m \r\n\tNothing -> M.insert a [b] m \r\n\r\ndeleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]\r\ndeleteWithList a m = case M.lookup a m of \r\n\tJust (x:y:xs) -> M.insert a (y:xs) m\r\n\tJust [x] -> M.delete a m\r\n\r\nsolve :: Integer -> [Integer] -> Bool\r\n\r\nsolve n a\r\n\t| mod num1 2 == 1 = False\r\n\t| mod num2 2 == 1 && num1 == 0 = False\r\n\t| otherwise = True\r\n\twhere\r\n\tnum1 = sum [1 | x<-a, x==1]\r\n\tnum2 = sum [1 | x<-a, x==2]\r\n\r\n\r\n\r\n\r\nplotResult True = putStrLn \"Yes\"\r\nplotResult False = putStrLn \"No\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n a\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n getLine\n a <- getIntList\n putStrLn $ yesOrNo $ f a\n\nf :: [Int] -> Bool\nf a = fst b == snd b\n where b = foldl g (0, 0) $ reverse . sort $ a\n\ng :: (Int, Int) -> Int -> (Int, Int)\ng (x, y) z = if x < y then (x + z, y) else (x, y + z)\n"}, {"source_code": "import Control.Arrow\nmain = interact $ lines >>> drop 1 >>> caser >>> unzip >>> snd >>> map (words >>> map read >>> solve) >>> unlines\n\ncaser :: [String] -> [(String, String)]\ncaser [a, b] = [(a, b)]\ncaser (a:b:cs) = [(a, b)] ++ caser cs\n\nsolve :: [Int] -> String\nsolve a = do\n let two = (filter (\\x -> x == 2) >>> length) a\n let one = (filter (\\x -> x == 1) >>> length) a\n if ((mod two 2) == 0 && (mod one 2) == 0) \n then \"YES\"\n else if ((mod one 2) == 0 && one > 0) \n then \"YES\"\n else \"NO\""}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (_ : ns : rest) = ((:[]). solve . linetois) (ns) ++ tcio (drop 0 rest) \r\n linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n --itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n\r\nsolve :: [Int] -> String\r\nsolve ns = if odd c1 || (c1==0 && odd c2) then \"NO\" else \"YES\" where\r\n [c1,c2] = map (subtract 1) $ map length $ group $ sort $ ns ++ [1,2]\r\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.State.Strict as S\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (findIndices, intersect, elemIndices, find, isPrefixOf, nub,\r\n sort, sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> [Int] -> Bool\r\nsolve n as = not $ null $ intersect twoDiffs oneDiffs\r\n where\r\n twos = length . findIndices even $ as\r\n ones = length . findIndices odd $ as\r\n\r\n twoDiffs = [2 * k - 2 * (twos - k) | k <- [0 .. twos]]\r\n oneDiffs = [k - (ones - k) | k <- [0 .. ones]]\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n n <- B8.getLine <&> readIntB8\r\n as <- B8.getLine <&> map readIntB8 . B8.words\r\n let answer = solve n as\r\n printf \"%s\\n\" ((if answer then \"YES\" else \"NO\") :: String)"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n n <- getInt\n a <- getInts\n let s = sum a\n one = length $ filter (== 1) a\n two = length $ filter (== 2) a\n putStrLn if\n | odd s -> \"No\"\n | even two -> \"Yes\"\n | one >= 2 -> \"Yes\"\n | otherwise -> \"No\"\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ndata V = V !Int !Bool\n\nstep :: V -> Char -> V\nstep (V tot one) c = case c of\n '1' -> V (tot + 1) True\n '2' -> V (tot + 2) one\n _ -> V tot one\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n ans <- foldl' step (V 0 False) <$> getLine\n putStrLn $ case ans of\n V x _ | odd x -> \"NO\"\n V x c | (mod x 4 /= 0) <= c -> \"YES\"\n _ -> \"NO\"\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nanswer :: [Bool] -> String\nanswer test\n | any (==True) test = \"YES\"\n | otherwise = \"NO\"\n\ncanSplit as cnt2 = do\n let cnt1 = length $ filter (1==) as\n let sum2 = sum $ filter (2==) as\n let num = abs $ 2 * cnt2 - (sum2 - 2 * cnt2)\n\n even (cnt1 - num) && cnt1 > 0\n\nsolve = do\n s1 <- B.getLine\n s2 <- B.getLine\n\n let n = fst $ fromJust $ C.readInt s1\n let as = map (fst . fromJust . C.readInt) (C.words s2)\n\n let cnt2 = length $ filter (2==) as\n\n putStrLn $ answer $ map (canSplit as) [0..cnt2]\n\nmain = do\n str <- B.getLine\n\n let t = fst $ fromJust $ C.readInt str\n\n replicateM_ t solve\n"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nanswer :: [Bool] -> String\nanswer test\n | any (==True) test = \"YES\"\n | otherwise = \"NO\"\n\ncanSplit as cnt2 = do\n let cnt1 = length $ filter (1==) as\n let sum2 = sum $ filter (2==) as\n let num = abs $ 2 * cnt2 - (sum2 - 2 * cnt2)\n\n even (cnt1 - num) && cnt1 > 0\n\nsolve = do\n s1 <- B.getLine\n s2 <- B.getLine\n\n let n = fst $ fromJust $ C.readInt s1\n let as = map (fst . fromJust . C.readInt) (C.words s2)\n\n let cnt2 = length $ filter (2==) as\n\n print $ answer $ map (canSplit as) [0..cnt2]\n\nmain = do\n str <- B.getLine\n\n let t = fst $ fromJust $ C.readInt str\n\n replicateM_ t solve\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nreadInt :: IO Integer\nreadInt = readLn\n\nhist :: [Integer] -> (Integer, Integer)\nhist [] = (0, 0)\nhist (x:xs) = let (a, b) = hist xs in if x == 1 then (a + 1, b) else (a, b + 1)\n\nres :: Bool -> String\nres True = \"YES\"\nres False = \"NO\"\n\nsolveInner :: Integer -> Bool -> Bool\nsolveInner sum any\n | sum `mod` 2 /= 0 = False\n | sum `div` 2 == 0 = True\n | otherwise = any\n\nsolve :: [Integer] -> Bool\nsolve l = let (a, b) = hist l in solveInner (a + 2 * b) (a > 0)\n\nsolveCase :: IO String\nsolveCase = readInt >> fmap (res . solve) readInts\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}], "src_uid": "1d9d34dca11a787d6e2345494680e717"} {"source_code": "import Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n,k] <- map read . words <$> getLine\n putStrLn $ take n $ cycle $ enumFromTo 'a' $ toEnum $ fromEnum 'a' + k - 1\n", "positive_code": [{"source_code": "main = getContents >>= putStr . solve . tail . map read . words\n\nsolve [] = []\nsolve (n:k:xs) = (take n $ concat $ repeat $ take k ['a' .. 'z']) ++ ('\\n' : solve xs)\n"}, {"source_code": "f2::Int->String->String->String\nf2 0 _ _=\"\"\nf2 a [] t=f2 a t t\nf2 a (x:xs) t=x:f2 (a-1) xs t\n\nf::[String]->[String]\nf [] =[]\nf (x:xs)=let (a:b:[])=map read (words x)::[Int]\n t=(take b \"abcdefghijklmnopqrstuvwxyz\")\n in (f2 a t t):f xs\nmain = do\n e<-getLine\n es<-getContents\n mapM_ putStrLn $ f (lines es)"}, {"source_code": "import Control.Monad\n-- import Data.List (flatten)\n\nfpow n = foldr (.) id . replicate n\n\nsolve :: Int -> Int -> String\nsolve n k = zipWith const reps [1..n]\n where reps = concat $ repeat ['a'.. fpow (pred k) succ 'a']\n\nmain = do\n numCases <- read <$> getLine\n replicateM_ numCases $ do\n [n, k] <- fmap read <$> words <$> getLine\n putStrLn $ solve n k\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\t\t\n\nonecase = do\n\t\t[a,b]<-map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ take a $ cycle $ take b \"abcdefghijklmnopqrstuvwxyz\"\n\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "process :: Int -> Int -> [Char]\nprocess n k = take n . concat . repeat . take k $ ['a'..]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ putStrLn $ map (\\[n,k] -> process n k) ts"}, {"source_code": "solve [n, k] =\n map ((['a'..'z'] !!) . (`mod` k)) [0..n-1]\nsolve _ = error \"bad format\"\n\nmain = interact $ unlines\n . map (solve . map read . words)\n . tail . lines\n"}], "negative_code": [], "src_uid": "fa253aabcccd487d09142ea882abbc1b"} {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let m = sum a `mod` n\n print $ if m == 0 then n else n - 1", "positive_code": [{"source_code": "solve (n:xs)\n | mod s n == 0 = n\n | True = (n - 1)\n where s = sum xs\n\nmain = interact $ show . solve . map read . words"}, {"source_code": "answer n w = if rem (sum w) n == 0 then n else n-1\n\n \nmain = do\n n<-getLine\n m<-getContents\n print . (answer ((read::String->Int)n) ) . map (read::String->Int) . words $ m"}, {"source_code": "main = do\n n <- readLn\n s<-fmap(sum.map read.words)getLine\n if mod s n == 0 then print n else print $ n-1\n"}, {"source_code": "main = interact $ show . solve . map (map read . words) . lines\nsolve [[n], xs] = n - l\n where l = if (sum xs) `mod` n == 0 then 0 else 1"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n print $ solve n a\n\nsolve n xs = n - l\n where l = if (sum xs) `mod` n == 0 then 0 else 1"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let m = sum a `mod` n\n print $ if m == 0 then n else n - 1\n"}, {"source_code": "main :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tlet n = read str1\n\tlet list = map read (words str2)\n\tif (mod (sum list) n == 0)\n\t\tthen putStrLn (show n)\n\t\telse putStrLn (show (n - 1))\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nsolve :: Int -> [Int] -> Int\nsolve n as\n | mod (sum as) n == 0 = n\n | otherwise = n - 1\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- liftM (map read . words) getLine\n print $ solve n as\n"}, {"source_code": "\nimport Control.Monad (liftM)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [Int] -> Int\nsolve n xs\n | sum xs `mod` n == 0 = n\n | otherwise = n - 1\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- Main.reads\n print $ solve n xs\n"}, {"source_code": "-- Codeforces 246B\n\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Maybe\n\nmain :: IO ()\nmain = BC.getContents >>= print . solve . map (fst . fromJust . BC.readInt) . BC.words\n\nsolve :: [Int] -> Int\nsolve (n:xs) = if (sum xs) `mod` n == 0 then n else (n-1)\n"}, {"source_code": "import Data.List\n\nsolve (n:xs)\n | mod s n == 0 = n\n | True = (n - 1)\n where s = foldl'(+) 0 xs\n\nmain = interact $ show . solve . map read . words"}], "negative_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let m = sum a `mod` n\n print $ max m $ n - m\n"}, {"source_code": "main=interact$show.(`div`2).sum.map read.tail.words"}, {"source_code": "main = do\n n <- readLn\n s<-fmap(sum.map read.words)getLine\n let (q,r) = divMod s n\n print $ max r (n-r)"}], "src_uid": "71cead8cf45126902c518c9ce6e5e186"} {"source_code": "{-# LANGUAGE BlockArguments #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\n\r\nmain :: IO ()\r\nmain = nCases do\r\n _ <- getLine\r\n m <- line\r\n let\r\n fld have (ix, cur)\r\n | have == -1 = -1\r\n | ix <= cur = have + cur - ix\r\n | ix - cur <= have = have - ix + cur\r\n | otherwise = -1\r\n putBoolLn $ -1 /= foldl' fld 0 (zip [0..] m)\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Int\n\nsolve :: [Int] -> Int -> Int64 -> Bool\nsolve [] _ spare = spare >= 0\nsolve (y:ys) tar spare = spare >= 0\n && solve ys (tar+1) (spare + fromIntegral (y - tar))\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n h <- readInts\n lift $ P.putStr $ if solve h 0 0\n then P.pack \"YES\\n\"\n else P.pack \"NO\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n h <- popIntegers\n return $ if solve n h then \"YES\" else \"NO\"\n\n\nsolve n hs = go 0 0 hs\n where\n go _ _ [] = True\n go i carry (h : hs) = let carry' = carry + h - i in\n if carry' < 0 then False else go (i + 1) carry' hs\n"}, {"source_code": "import Control.Monad\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadIntegers :: IO [Integer]\nreadIntegers = readArray\n\nreadInteger :: IO Integer\nreadInteger = readLn\n\nans :: Bool -> [Char]\nans True = \"YES\"\nans False = \"NO\"\n\nrec :: Integer -> Integer -> [Integer] -> Bool\nrec _ _ [] = True\nrec have least (x:xs) =\n if x + have < least then False else rec (x + have - least) (least + 1) xs\n\nsolve :: [Integer] -> [Char]\nsolve = ans . rec 0 0\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (readInteger >> fmap solve readIntegers >>= putStrLn)\n"}, {"source_code": "strictlyIncreasing :: [Integer] -> Bool\nstrictlyIncreasing [] = True\nstrictlyIncreasing [_] = True\nstrictlyIncreasing (x:y:xs) = x < y && strictlyIncreasing (y:xs)\n\nreshape :: [Integer] -> [Integer]\nreshape = foldl moveRight []\n where moveRight [] h = [h]\n moveRight l h = newL ++ [h + extra]\n where extra = max 0 (last l - toInteger (length l) + 1)\n newL = init l ++ [last l - extra]\n\nsolveTest :: [Integer] -> String\nsolveTest nums = if strictlyIncreasing $ reshape nums\n then \"YES\"\n else \"NO\"\n\nsolve :: String -> String\nsolve = unlines . map (solveTest . map read . words) . odds . drop 1 . lines\n where odds (_:x:xs) = x : odds xs\n odds [] = []\n\nmain :: IO ()\nmain = interact solve\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BlockArguments #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = nCases do\r\n [n] <- line\r\n m <- line\r\n putBoolLn $ n * (n - 1) `div` 2 <= sum m\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n"}, {"source_code": "{-# LANGUAGE BlockArguments, ExtendedDefaultRules #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = nCases do\r\n [n] <- line\r\n m <- line\r\n putBoolLn $ n * (n - 1) `div` 2 <= sum m\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n\r\ndefault ( Int )\r\n"}, {"source_code": "{-# LANGUAGE BlockArguments, ExtendedDefaultRules #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = nCases do\r\n [n] <- line\r\n m <- line\r\n putBoolLn $ n * (n + 1) `div` 2 >= sum m\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n\r\ndefault ( Int )\r\n"}, {"source_code": "import Control.Monad\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Int]\nreadInts = readArray\n\nreadInt :: IO Int\nreadInt = readLn\n\nans :: Bool -> [Char]\nans True = \"YES\"\nans False = \"NO\"\n\nrec :: Int -> Int -> [Int] -> Bool\nrec _ _ [] = True\nrec have least (x:xs) =\n if x + have < least then False else rec (x + have - least) (least + 1) xs\n\nsolve :: [Int] -> [Char]\nsolve a = ans $ rec 0 0 a\n\nmain :: IO ()\nmain = readInt >>= flip replicateM_ (readInt >> fmap solve readInts >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n n <- popInteger\n h <- popIntegers\n return $ if solve n h then \"YES\" else \"NO\"\n\n\nsolve n h = sum h >= n * (n - 1) `quot` 2\n"}, {"source_code": "strictlyIncreasing :: [Int] -> Bool\nstrictlyIncreasing nums\n | length nums < 2 = True\n | otherwise = x < y && strictlyIncreasing (tail nums)\n where x = head nums\n y = head $ tail nums\n\nreshape :: [Int] -> [Int]\nreshape = foldl moveRight []\n where moveRight [] h = [h]\n moveRight l h = newL ++ [h + extra]\n where extra = max 0 (last l - length l + 1)\n newL = init l ++ [last l - extra]\n\nsolveTest :: [Int] -> String\nsolveTest nums = if strictlyIncreasing . reshape $ nums\n then \"YES\"\n else \"NO\"\n\nsolve :: String -> String\nsolve = unlines . map (solveTest . map read . words) . odds . drop 1 . lines\n where odds (_:x:xs) = x : odds xs\n odds [] = []\n\nmain :: IO ()\nmain = interact solve\n"}], "src_uid": "7a8c4ba98a77097faff625b94889b365"} {"source_code": "(>>>) = flip (.)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (words >>> map read)\n >>> chunksOf 2\n >>> map (solve >>> show)\n >>> unlines\n\nsolve :: [[Int]] -> Int\nsolve [[_, m], as] = max 0 $ sum as - m\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n", "positive_code": [{"source_code": "-- ID : 1697A (Parkway Walk)\n-- URL: https://codeforces.com/problemset/problem/1697/A\n\nimport Control.Monad\n\nreadInt = read `fmap` getLine :: IO Int\nreadInts = map read `fmap` words `fmap` getLine :: IO [Int]\n\nmain = readInt >>= \\t -> replicateM_ t $ readInts >>= \\[n,m] -> readInts >>= \\as -> print (max (sum as - m) 0)\n"}, {"source_code": "-- ID: 1697A (A. Parkway Walk)\n-- URL: https://codeforces.com/problemset/problem/1697/A\n\nimport Control.Monad\n\n-- Fast IO\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\ngetInt64 = parseInt `fmap` BS8.getLine :: IO Int64\ngetInt64s = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int64]\nparseInt = fromIntegral . fst . fromJust . BS8.readInt\n\nmain = do\n t <- read `fmap` getLine :: IO Int\n replicateM_ t solve\n\nsolve = do\n [n,m] <- getInt64s\n xs <- getInt64s\n print $ max (sum xs - m) 0\n"}, {"source_code": "import Control.Monad (forM_)\n\nreadInts :: IO [Int]\nreadInts = getLine >>= pure . map read . words \n\nmain = do\n [t] <- readInts\n forM_ [1..t] (\\_ -> do\n [n,m] <- readInts\n l <- readInts\n print $ max 0 (sum l - m))"}], "negative_code": [{"source_code": "-- ID : 1697A (Parkway Walk)\n-- URL: https://codeforces.com/problemset/problem/1697/A\n\nimport Control.Monad\n\nreadInt = read `fmap` getLine :: IO Int\nreadInts = map read `fmap` words `fmap` getLine :: IO [Int]\n\nmain = readInt >>= \\t -> replicateM_ t $ do\n [n,m] <- readInts\n as <- readInts\n print $ max (sum as) 0\n"}], "src_uid": "7276d7e3a4b594dc64c1ba56fb1a3628"} {"source_code": "import Control.Monad\n\nsolve a b = do\n guard (sum a == sum b)\n let ds = zip [1..] (zipWith (-) b a)\n let low = concat [replicate d i | (i, d) <- ds, d > 0]\n let high = concat [replicate (-d) i | (i, d) <- ds, d < 0]\n pure (zip high low)\n\ninteractCase = do\n _ <- getLine\n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n case solve a b of\n Just l -> do\n print (length l)\n forM_ l $ \\(i, j) -> putStrLn (show i ++ \" \" ++ show j)\n Nothing ->\n print (-1)\n\nmain = do\n testCount <- read <$> getLine\n replicateM_ testCount interactCase\n", "positive_code": [{"source_code": "import Control.Arrow((>>>))\r\nimport Control.Monad (replicateM_, forM_)\r\n\r\nmain :: IO ()\r\nmain = readLn >>= (`replicateM_` testCase)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n _ <- getLine\r\n as <- map read . words <$> getLine\r\n bs <- map read . words <$> getLine\r\n case solve as bs of\r\n Nothing -> putStrLn \"-1\"\r\n Just ops -> do\r\n print $ length ops\r\n forM_ ops (\\(i, j) -> putStrLn $ show i ++ \" \" ++ show j)\r\n\r\ntype Answer = Maybe [(Int, Int)]\r\n\r\nsolve :: [Int] -> [Int] -> Answer\r\nsolve as bs\r\n | length ps /= length ns = Nothing\r\n | otherwise = Just $ ps `zip` ns\r\n where\r\n xs = zipWith (-) as bs `zip` [1..]\r\n ps = idxs (> 0)\r\n ns = idxs (< 0)\r\n idxs f = concatMap (\\(n, i) -> replicate (abs n) i) $ filter (f . fst) xs\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n--import Data.Char as C\n--import Data.IntSet as S\n\n\nlower _ [] [] = []\nlower idx (x:a) (y:b)\n | y > x = replicate (y-x) idx ++ lower (idx+1) a b\n | otherwise = lower (idx+1) a b\n \nhigher _ [] [] = []\nhigher idx (x:a) (y:b)\n | x > y = replicate (x-y) idx ++ higher (idx+1) a b\n | otherwise = higher (idx+1) a b\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n [sa, sb] <- sequence [getLine, getLine]\n let a = map read $ words sa :: [Int]\n b = map read $ words sb :: [Int]\n good = sum a == sum b\n res = (if good then zip (higher 1 a b) (lower 1 a b) else [])\n cnt = (if good then length res else -1)\n out = intercalate \"\\n\" $ map (\\(x,y) -> show x ++ \" \" ++ show y) res\n in mapM_ putStr [show cnt ++ \"\\n\", if cnt > 0 then out ++ \"\\n\" else \"\"]\n\n \n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n guard, join, replicateM,\n replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.Array as A\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\nimport System.IO (IOMode (ReadMode, WriteMode),\n hFlush, openFile, stdin, stdout)\nimport Text.Printf (printf)\n\nimport Debug.Trace (trace, traceM, traceShowM)\nimport GHC.IO.Handle (hDuplicateTo)\n\ndebug :: c -> String -> c\ndebug = flip trace\ntraced x = trace (show x) x\nwithTrace s x = trace (s ++ \" -> \" ++ show x) x\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> fst . fromJust\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> fst . fromJust\n\ntype Move = (Int, Int)\n\nsolve :: Int -> [Int] -> [Int] -> Maybe [Move]\nsolve n a b | sum a /= sum b = Nothing\nsolve n a b =\n Just $ zip decIdxs incIdxs \n where\n diffs = zipWith (-) a b\n indexedDiffs = zip diffs [1 ..]\n incIdxs = concatMap (\\(e, i) -> replicate (max (-e) 0) i) indexedDiffs\n decIdxs = concatMap (\\(e, i) -> replicate (max e 0) i) indexedDiffs\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ \\i -> do\n n <- B8.getLine <&> readIntB8\n a <- B8.getLine <&> map readIntB8 . B8.words\n b <- B8.getLine <&> map readIntB8 . B8.words\n\n let answer = solve n a b\n\n case answer of\n Nothing -> putStrLn \"-1\"\n Just moves -> do\n printf \"%d\\n\" $ length moves\n forM_ moves $ uncurry (printf \"%d %d\\n\")"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n b <- readInts\n let\n is = do\n (ix, ai, bi) <- zip3 [1..] a b\n replicate (ai - bi) ix\n js = do\n (ix, ai, bi) <- zip3 [1..] a b\n replicate (bi - ai) ix\n if sum a /= sum b\n then putInts [0-1]\n else do\n putInts [length is]\n forM_ (zip is js) $ \\(i, j) -> putInts [i, j]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "import Control.Arrow((>>>))\r\nimport Control.Monad (replicateM_, forM_)\r\n\r\nmain :: IO ()\r\nmain = readLn >>= (`replicateM_` testCase)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n _ <- getLine\r\n as <- map read . words <$> getLine\r\n bs <- map read . words <$> getLine\r\n case solve as bs of\r\n Nothing -> putStrLn \"-1\"\r\n Just ops -> do\r\n print $ length ops\r\n forM_ ops (\\(i, j) -> putStrLn $ show i ++ \" \" ++ show j)\r\n\r\ntype Answer = Maybe [(Int, Int)]\r\n\r\nsolve :: [Int] -> [Int] -> Answer\r\nsolve as bs\r\n | length ps /= length ns = Nothing\r\n | otherwise = Just $ ps `zip` ns\r\n where\r\n xs = zipWith (-) as bs `zip` [1..]\r\n ps = idxs (> 0)\r\n ns = idxs (< 0)\r\n idxs f = map snd $ filter (f . fst) xs\r\n"}, {"source_code": "import Control.Arrow((>>>))\r\nimport Control.Monad (replicateM_, forM_)\r\n\r\nmain :: IO ()\r\nmain = readLn >>= (`replicateM_` testCase)\r\n\r\ntestCase :: IO ()\r\ntestCase = do\r\n _ <- getLine\r\n as <- map read . words <$> getLine\r\n bs <- map read . words <$> getLine\r\n case solve as bs of\r\n Nothing -> putStrLn \"-1\"\r\n Just ops -> do\r\n print $ length ops\r\n forM_ ops (\\(i, j) -> print $ show i ++ \" \" ++ show j)\r\n\r\ntype Answer = Maybe [(Int, Int)]\r\n\r\nsolve :: [Int] -> [Int] -> Answer\r\nsolve as bs\r\n | length ps /= length ns = Nothing\r\n | otherwise = Just $ ps `zip` ns\r\n where\r\n xs = zipWith (-) as bs `zip` [1..]\r\n ps = idxs (> 0)\r\n ns = idxs (< 0)\r\n idxs f = map snd $ filter (f . fst) xs\r\n"}], "src_uid": "accfbd68b9723abf4cd29846e80835ec"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let writeText = appendFile \"output.txt\" . printf \"%s\\n\"\n s : ss <- lines <$> readFile \"input.txt\"\n let n : k : _ = map read . words $ s\n g = n ^ k\n pat = take n ss\n generate pss = do\n let expand qss = [concat [replicate n q | q <- qs] | qs <- qss]\n pss' = expand pss\n transpose . expand . transpose $ pss'\n boards = do\n (i, xss) <- zip [1 .. k] $ iterate generate pat\n let w = n ^ (k - i)\n duplicate = map (concat . replicate w)\n xss' = duplicate xss\n xss'' = transpose . duplicate . transpose $ xss'\n return $ xss''\n combine '*' _ = '*'\n combine _ '*' = '*'\n combine _ _ = '.'\n ans = foldr1 (zipWith (zipWith combine)) boards\n mapM_ writeText ans\n\n\n\n", "positive_code": [{"source_code": "\nimport Array\nimport Control.Monad (liftM)\nimport IO\n\ntype Paint = Array (Int, Int) Char\n\nparsePaint :: Int -> [String] -> Paint\nparsePaint n xs = array ((1,1), (n,n))\n [((i,j), xs !! (i-1) !! (j-1)) | i <- [1..n], j <- [1..n]]\n\nstep :: Int -> Paint -> Paint\nstep m a = array ((1,1), (m*n, m*n))\n [((i,j), f i j) | i <- [1..m*n], j <- [1..m*n]]\n where\n n = snd $ snd $ bounds a\n f i j\n | a ! (1 + div (i-1) m, 1 + div (j-1) m) == '*' = '*'\n | otherwise = a ! (i2, j2)\n where\n i2 = 1 + mod (i-1) n\n j2 = 1 + mod (j-1) n\n\nsolve :: Int -> Int -> Paint -> Paint\nsolve n 1 a = a\nsolve n k a = solve n (k-1) (step n a)\n\nprintPaint :: Handle -> Paint -> IO ()\nprintPaint hOutput paint =\n mapM_ (\\i -> hPutStrLn hOutput $ [paint ! (i,j) | j <- [1..n]]) [1..n]\n where\n n = snd $ snd $ bounds paint\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n [n, k] <- liftM (map read . words) (hGetLine hInput)\n lineses <- liftM lines (hGetContents hInput)\n let paint = parsePaint n lineses\n printPaint hOutput $ solve n k paint\n\n hClose hInput\n hClose hOutput"}, {"source_code": "import List\nimport Char\n\nmain = fileInteract q \"input.txt\" \"output.txt\"\n\nq = func.words\n\nfunc::[String]->String\nfunc (a:b:xs) = solve (toInt a) (toInt b) 0 xs\nfunc _ = \"\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\ntoString::Int->String\ntoString=show\n\ntest _ (-1) _ _ _ = True\ntest a b y x d | ((d!!y')!!x') == '*' = False\n | otherwise = True &&\n (test a (b-1)\n y --(y `mod` (a^b))\n x --(x `mod` (a^b))\n d)\n where\n y' = (y `div` (a^b))`mod`a\n x' = (x `div` (a^b))`mod`a\n\nsolve::Int->Int->Int->[[Char]]->String\nsolve a b c d | c < a^b = (foldl solve' [] [0..a^b-1]) ++ \n \"\\n\" ++ (solve a b (c+1) d)\n | otherwise= []\n where\n solve' acc a' | test a (b-1) c a' d = acc++['.']\n | otherwise = acc++['*']\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let writeText = appendFile \"output.txt\" . printf \"%s\\n\"\n s : ss <- lines <$> readFile \"input.txt\"\n let n : k : _ = map read . words $ s\n pat = take n ss\n generate pss = do\n let expand qss = [concat [replicate n q | q <- qs] | qs <- qss]\n pss' = expand pss\n pss'' = transpose . expand . transpose $ pss'\n pss''\n boards = do\n (i, xss) <- zip [1 .. k] $ iterate generate pat\n let duplicate = map (concat . replicate (n ^ (k - i)))\n xss' = duplicate xss\n xss'' = transpose . duplicate . transpose $ xss'\n return $ xss''\n combine '*' _ = '*'\n combine _ '*' = '*'\n combine _ _ = '.'\n ans = foldl1 (zipWith (zipWith combine)) boards\n mapM_ writeText ans\n\n\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let writeText = appendFile \"output.txt\" . printf \"%s\\n\"\n s : ss <- lines <$> readFile \"input.txt\"\n let n : k : _ = map read . words $ s\n g = n ^ k\n pat = take n ss\n generate pss = do\n let expand qss = [concat [replicate n q | q <- qs] | qs <- qss]\n pss' = expand pss\n pss'' = transpose . expand . transpose $ pss'\n pss''\n boards = do\n (i, xss) <- zip [1 .. k] $ iterate generate pat\n let w = n ^ (k - i)\n duplicate = map (concat . replicate w)\n xss' = duplicate xss\n xss'' = transpose . duplicate . transpose $ xss'\n return $ xss''\n combine '*' _ = '*'\n combine _ '*' = '*'\n combine _ _ = '.'\n ans = foldr1 (zipWith (zipWith combine)) boards\n mapM_ writeText ans\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Char\nimport Data.Ord\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\n\nfor_ :: (Monad m, Integral a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let conv :: String -> [Int]\n conv = map read . words\n writeText = appendFile \"output.txt\"\n s : ss <- lines <$> readFile \"input.txt\"\n let n : k : _ = conv s\n g = n ^ k\n a = listArray ((1, 1), (n, n)) . concat $ take n ss :: UArray (Int, Int) Char\n table <- newArray ((1, 1), (g, g)) '.' :: IO (IOUArray (Int, Int) Char)\n let fill !baseL !baseC !w = do\n for_ 1 w $ \\l -> do\n for_ 1 w $ \\c -> do\n let !idx = (baseL + l, baseC + c)\n !idx' = ((l - 1) `quot` (w `quot` n) + 1, (c - 1) `quot` (w `quot` n) + 1)\n x <- readArray table idx\n when (x == '.' && a ! idx' == '*') $ do\n writeArray table idx '*'\n loop w = do\n when (w >= n) $ do\n forM_ [0, w .. g - 1] $ \\baseL -> do\n forM_ [0, w .. g - 1] $ \\baseC -> do\n fill baseL baseC w\n loop (w `quot` n)\n loop g\n let split [] = []\n split xs = as : split bs where\n (as, bs) = splitAt g xs\n getElems table >>= writeText . unlines . split\n\n\n\n"}, {"source_code": "main = do\n x <- readFile \"input.txt\"\n writeFile \"output.txt\" (f x)\nf x = unlines $ answer k where\n l0:model = lines x\n [n,k] = map (read::String->Int) $ words l0\n g [] = []\n g (y:ys) = (g0 y):(g ys)\n g0 [] = []\n g0 (y:ys) = (g1 y):(g0 ys)\n g1 y\n | y=='.' = model\n | otherwise = replicate n $ replicate n '*'\n h [] = []\n h (y:ys) = (h0 y) ++ (h ys)\n h0 ys\n | null $ head ys = []\n | otherwise = (concat $ map head ys):(h0 $ map tail ys)\n answer 1 = model\n answer y = h $ g $ answer (y-1)\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Char\nimport Data.Ord\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\n\nfor_ :: (Monad m, Integral a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let conv :: String -> [Int]\n conv = map read . words\n writeText = appendFile \"output.txt\"\n s : ss <- lines <$> readFile \"input.txt\"\n let n : k : _ = conv s\n g = n ^ k\n a = listArray ((1, 1), (n, n)) . concat $ take n ss :: UArray (Int, Int) Char\n table <- newArray ((1, 1), (g, g)) '.' :: IO (IOUArray (Int, Int) Char)\n let fill !baseL !baseC !w = do\n for_ 1 w $ \\l -> do\n for_ 1 w $ \\c -> do\n let !idx = (baseL + l, baseC + c)\n !idx' = ((l - 1) `quot` (w `quot` n) + 1, (c - 1) `quot` (w `quot` n) + 1)\n x <- readArray table idx\n when (x == '.' && a ! idx' == '*') $ do\n writeArray table idx '*'\n loop w = do\n when (w > n) $ do\n let !w' = w `quot` n\n forM_ [0, w' .. g - 1] $ \\baseL' -> do\n forM_ [0, w' .. g - 1] $ \\baseC' -> do\n fill baseC' baseL' w'\n loop w'\n loop g\n let split [] = []\n split xs = as : split bs where\n (as, bs) = splitAt g xs\n getElems table >>= writeText . unlines . split\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Char\nimport Data.Ord\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\n\nfor_ :: (Monad m, Integral a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let conv :: String -> [Int]\n conv = map read . words\n writeText = appendFile \"output.txt\"\n s : ss <- lines <$> readFile \"input.txt\"\n let n : k : _ = conv s\n a = listArray ((1, 1), (n , n)) . concat $ take n ss :: UArray (Int, Int) Char\n table <- newArray ((1, 1), (n ^ k, n ^ k)) '.' :: IO (IOArray (Int, Int) Char)\n let fill (baseL, baseC) w = do\n forM_ [1 .. w] $ \\l -> do\n forM_ [1 .. w] $ \\c -> do\n let idx = (baseL + l, baseC + c)\n idx' = ((l - 1) `quot` (w `quot` n) + 1, (c - 1) `quot` (w `quot` n) + 1)\n x <- readArray table idx\n when (x == '.') $ do\n when (a ! idx' == '*') $ do\n writeArray table idx '*'\n when (False && w > n) $ do\n let w' = w `quot` n\n forM_ [0, w' .. n ^ k - 1] $ \\baseL' -> do\n forM_ [0, w' .. n ^ k - 1] $ \\baseC' -> do\n fill (baseC', baseL') w'\n fill (0, 0) (n ^ k)\n let split [] = []\n split xs = as : split bs where\n (as, bs) = splitAt (n ^ k) xs\n getElems table >>= writeText . unlines . split\n\n\n\n"}], "src_uid": "edf69ef07b42e8290887b996e3cb94f6"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\nimport Control.Monad (forM_)\n\ninterchange :: [t] -> [t] -> [t]\ninterchange [] [] = []\ninterchange (x:xs) (y:ys) = x:y:(interchange xs ys)\ninterchange _ _ = error \"must be of the same length\"\n \ngetRoute :: (Ord a, Num a, Enum a) => a -> a -> [a]\ngetRoute u d\n = if u == d then\n interchange [1..u] [n,n-1..u+2] ++ [u+1]\n else if u > d then\n [1..(u-d)] ++ interchange [(u-d)+1..u] [n,n-1..u+2] ++ [u+1]\n else\n [n,n-1..2*u+2] ++ interchange [2*u+1,2*u..u+2] [1..u] ++ [u+1]\n where\n n = u + d + 1\n \nmain :: IO ()\nmain = do\n (a :: Int) <- readLn\n (b :: Int) <- readLn\n forM_ (getRoute a b) (putStr . (++\" \") . show)\n", "positive_code": [{"source_code": "nums :: Int -> Int -> [String]\nnums a b\n | a>b = []\n | a==b = [show b]\n | otherwise = (show a) : (nums (a+1) b)\n\nf :: Int -> Int -> Int -> [String]\nf u d n = (nums 1 u) ++ (reverse (nums (u+1) (n+1)))\n \nmain = do\n a <- getLine\n b <- getLine\n putStrLn (unwords(f (read a) (read b) ((read a)+(read b))))"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\n-- | Main entry point to the application.\nmodule Main where\n\n-- | The main entry point.\nmain :: IO ()\nmain = do\n (a :: Int) <- readLn\n (b :: Int) <- readLn\n let n = a + b + 1\n if (a > b) then do\n mapM_ (putStr . (++\" \") . show) [1..a+1]\n mapM_ (putStr . (++\" \") . show) [a..a+1-b]\n else do\n mapM_ (putStr . (++\" \") . show) [n,n-1..n-b]\n mapM_ (putStr . (++\" \") . show) [n-b+1,n-b..n-b+a]"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\n-- | Main entry point to the application.\nmodule Main where\n\n-- | The main entry point.\nmain :: IO ()\nmain = do\n (a :: Int) <- readLn\n (b :: Int) <- readLn\n let n = a + b + 1\n if (a > b) then do\n mapM_ (putStr . (++\" \") . show) [1..a+1]\n mapM_ (putStr . (++\" \") . show) [a,a-1..a+1-b]\n else do\n mapM_ (putStr . (++\" \") . show) [n,n-1..n-b]\n mapM_ (putStr . (++\" \") . show) [n-b+1..n-b+a]"}], "src_uid": "add2285f3f710eb41185d6a83e44b37a"} {"source_code": "\r\nsolve :: [String] -> [String]\r\nsolve = map (func . (map read . words))\r\nfunc :: [Int] -> String\r\nfunc [a,b] = show $ b `div` (a*a)\r\nmain :: IO()\r\nmain = interact $ unlines.solve.tail.lines\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\nmodule Main (main) where\r\n\r\nimport Control.Arrow ((>>>))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Control.Monad.State (State, evalState, gets, MonadState (get), put)\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad (replicateM)\r\nimport Control.Applicative (liftA2)\r\n\r\ndata TC = TC { n :: Integer, s :: Integer }\r\n\r\nsolve TC{..} = s `div` (n * n)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (C.pack . show) >>> C.unlines\r\n\r\nscan = numberOf $ TC <$> integer <*> integer\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case { s:ss -> put ss >> return s }\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10^p)*) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case { [] -> return []; _ -> (:) <$> s <*> many s }\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2..4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a,b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "import Control.Monad\r\nmain = read <$> getLine >>= flip replicateM_ (map read . words <$> getLine >>= \\ [n, s] -> print $ s `div` (n*n))"}, {"source_code": "main :: IO ()\r\nmain = \r\n let f 0 = return ()\r\n f t = solve >> f (t - 1)\r\n in readInt <$> getLine >>= f\r\n\r\nsolve :: IO ()\r\nsolve = map readInt . words <$> getLine >>= \\ [n, s] -> print $ s `div` (n*n)\r\n \r\nreadInt :: String -> Int\r\nreadInt = read"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [n, s] <- (map read . words) <$> getLine :: IO [Int]\n print $ div s (n^2)\n"}], "negative_code": [], "src_uid": "7226a7d2700ee52f52d417f404c42ab7"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = (itoline . solve . linetoi) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: Int -> Int\nsolve x \n | a == x+1 = b+1 \n | otherwise = b where\n (a,b) = head $ dropWhile (())\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Data.Tree\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = interact $\n lines >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\n\nsolve :: Int -> Int\nsolve x\n | x == tri-1 = n+1\n | otherwise = n\n where\n n = ceiling ((-1 + sqrt (1 + 8*fromIntegral x))/2)\n tri = n*(n+1)`div`2\n\n"}], "negative_code": [], "src_uid": "38afe98586a3b8d6061fe7e3e8fc4d02"} {"source_code": "{-# LANGUAGE\n ScopedTypeVariables,\n BangPatterns,\n FlexibleContexts,\n TypeApplications,\n MultiWayIf #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nmain = do\n [!t] <- readInts\n replicateM_ t $ do\n [!n] <- readInts\n a <- dropWhile (== 0) . take (n-1) <$> readInts\n let ans = sum a + length (filter (== 0) a)\n print ans\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmodifyArray :: (MArray a e m , Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr i f = readArray arr i >>= writeArray arr i . f\n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n], as] <- replicateM 2 ri\r\n return as\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve as = (sum.tail $ rs) + (length . filter (==0) . dropWhile (==0) . reverse . tail $ rs)\r\n where\r\n rs = reverse as\r\n"}], "negative_code": [], "src_uid": "a20911c30d7246e47d6fd57a05d1e556"} {"source_code": "module Main where\nimport Control.Monad\n\nsolve (a:b:c:_)= if b*2 < c then a*b else (a`div`2)*c + (a`mod`2)*b\nmain = do\n n <- readLn :: IO Int\n r <- replicateM n $ solve . map (read :: String -> Integer ). words <$> getLine\n mapM_ print r", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let x:xs = map fastRead . words $ input\n grouped = tripleGroup xs\n answers = map doSolve grouped :: [Int64]\n in unlines . map show $ answers\n\ntripleGroup :: [Int64] -> [(Int64, Int64, Int64)]\n\ntripleGroup [a,b,c] = [(a, b, c)]\ntripleGroup (a:b:c:xs) = (a, b, c):tripleGroup xs\n\ndoSolve :: (Int64, Int64, Int64) -> Int64\ndoSolve (n, a, b) \n | a*2 < b = n*a\n | otherwise = \n let (d,md) = divMod n 2\n in d * b + md * a\n"}, {"source_code": "import Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,a,b] <- map read . words <$> getLine\n if 2*a < b then print (n*a) else print (n `mod` 2 * a + n `div` 2 * b)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\t[c,a,b]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tprint $ min (c*a) ((div c 2)*b + (mod c 2) *a)\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n\n"}, {"source_code": "main = interact $ unlines . map show . map (process . map read . words) . tail . lines\nprocess :: [Integer] -> Integer\nprocess [n, a, b] = if b < 2*a then b*(div n 2) + a*(mod n 2) else n * a"}, {"source_code": "process :: Integer -> Integer -> Integer -> Integer\nprocess n a b\n | 2*a > b = a*(n `mod` 2) + b*(n `div` 2)\n | otherwise = a*n\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain :: IO ()\nmain = do\n q <- fmap readInt getLine\n qs <- fmap (map (map readInt.words).lines) getContents\n mapM_ print $ map (\\[n,a,b] -> process n a b) qs"}, {"source_code": "import Data.List\nimport Control.Monad\n\nsolve = do\n [n, a, b] <- map read.words <$> getLine\n print $ ((n `div` 2) * b + (n `mod` 2) * a) `min` (n * a)\n\nmain=do\n n <- readLn::IO Int\n replicateM_ n solve\n"}], "negative_code": [{"source_code": "module Main where\nimport Control.Monad\n\nsolve (a:b:c:_)= if b*2 < c then a*b else (a`div`2)*c + (a`mod`2)*b\nmain = do\n n <- readLn :: IO Int\n r <- replicateM n $ solve . map (read :: String -> Int ). words <$> getLine\n mapM_ print r"}], "src_uid": "beab56c5f7d2996d447320a62b0963c2"} {"source_code": "import qualified Data.Set as Set\n\nrestore diff = map ((1 - minVal)+) g\n where g = scanl (+) 0 diff\n minVal = minimum g\n\nsolve n diff = if correct then res else [-1]\n where check [] set = n == Set.size set\n check (h : t) set\n | h < 1 || h > n = False\n | otherwise = check t $ Set.insert h set\n res = restore diff\n correct = check res Set.empty\n\nmain = do\n n <- read <$> getLine\n diff <- (map read . words) <$> getLine\n putStrLn . unwords . map show $ solve n diff", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Array.ST.Safe\nimport Data.List\nimport Data.Int\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nenc :: Int -> Builder\nenc = intDec\nout :: [Int64] -> Builder\nout = mconcat . (intersperse (char7 ' ')) . map int64Dec\n\nsolve :: [Int] -> Builder\nsolve (n:a)\n | check b1 = out b1\n | check bn = out bn\n | check b0 = out b0\n | otherwise = intDec (-1)\n where\n q :: [Int64]\n q = map fromIntegral $ take (n - 1) a\n b1 = scanl (+) 1 q\n bn = scanl (+) (fromIntegral n) q\n b0 = map (succ . subtract u) b1\n u = minimum b1\n check l = u == 1 && v == (fromIntegral n) && check' (map fromIntegral l)\n where\n u = minimum l\n v = maximum l\n check' :: [Int] -> Bool\n check' l = runST $ do\n d <- newArray (1, n) False :: ST s (STUArray s Int Bool)\n x <- forM l $ \\i -> do\n if i < 1 || i > n then return True\n else do\n w <- readArray d i\n if w then return True\n else do\n writeArray d i True\n return False\n return $! not (or x)\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "import Data.List\n\n\nturnListIntoString :: [Int] -> String\nturnListIntoString qs = unwords . map show $ qs\n\ntrialUni :: [Int] -> Int -> Bool \ntrialUni qs n = w && t where\n t = all (\\x -> x >= 1 && x <=n) qs\n w = all (\\x -> x == 1) . map length . group . sort $ qs \n\n\nfoldOnQ :: [Int] -> [Int]\nfoldOnQ qs = ret where \n t = scanl (\\b a -> b + a) 1 qs\n m = minimum t\n ret = if m < 0 then map (-m + 1 + ) t\n else if m == 0 then map ( + 1) t\n else t\n\nsolve :: [[Int]] -> String\nsolve [[n], qs] = w where \n t = foldOnQ qs\n w = if trialUni t n then turnListIntoString t\n else \"-1\"\n\nrInt :: String -> Int\nrInt = read\n\nmain :: IO ()\nmain = interact $ solve . (map . map) rInt . map words . lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Bits\nimport Data.Char\nimport Data.Int\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int64] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Int64] -> [Int64]\nprocess qs = if valid then ps else [-1] where\n accum = scanl (+) 0 qs\n offset = 1 - (minimum accum)\n ps = map (+ offset) accum\n valid = unique ps && maximum ps == fromIntegral (length ps)\n\nunique l = Set.size set == length l where\n set = foldl (flip Set.insert) Set.empty l\n\nmain = do\n n <- getInt\n qs <- map fromIntegral <$> getInts\n printList $ process qs\n"}, {"source_code": "import Data.List(sort, foldl')\nimport Control.Monad.Writer.Strict\n\nbelongInt :: Char -> Bool\nbelongInt t = or [t == '-', and ['0' <= t, t <= '9']]\n\nreplace :: Char -> Char\nreplace ' ' = ','\nreplace x = x\n\ngetArray:: String -> [Int]\ngetArray x = (read $ (\"[\"++) $ (++\"]\") $ map replace x) :: [Int]\n\ncalcPreSum :: [Int] -> [Int]\ncalcPreSum = scanl (+) 0 \n\nmainCalc :: [Int] -> [Int]\nmainCalc array = tail $ calcPreSum (1-t:array)\n where t = minimum $ calcPreSum (0:array)\n\ncheckValid :: Int -> [Int] -> Bool\ncheckValid n array = (sort array) == [1..n]\n\ngetResult :: Int -> [Int] -> String\ngetResult n array\n | checkValid n array = concat $ map ((++\" \").show) array\n | otherwise = \"-1\"\n\nmain = do{\n n <- getLine;\n line <- getLine;\n putStrLn $ getResult ((read n)::Int) $ mainCalc $ getArray line;\n}"}, {"source_code": "module Main where\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ntest b _ [] = b\ntest b a (x:xs) = if x /= a+1 then False else test b x xs \n\nmain = do\n C.getLine\n qs <- map ((read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n let r = scanr (flip (-)) 1 qs\n m = minimum r\n t = map ((if m < 1 then (1-m) else 0)+) r \n p = test True 0 $ sort t -- \\\\ [1..length t]\n mapM_ (\\x -> putStr $ show x ++ \" \") $ if p then t else [(-1)] \n putStrLn \"\""}, {"source_code": "import Data.Maybe\nimport Data.List\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Char8 as B\n\ngetInts :: B.ByteString -> [Int]\ngetInts = map (fst . fromJust . B.readInt) . B.words\n\nprefixSums :: Num a => [a] -> [a]\nprefixSums q = scanl1 (+) q\n\nfirstPermElem :: (Num a, Ord a) => [a] -> a\nfirstPermElem q = 1 - minimum (0:(prefixSums q))\n\ngetPermutation :: Num a => [a] -> [a] -> [a]\ngetPermutation perm [] = perm\ngetPermutation perm q = getPermutation (perm ++ [last perm + head q]) (tail q)\n\npermutation q = prefixSums ((firstPermElem q):q)\n\nisProperPermutation :: [Int] -> Bool\nisProperPermutation perm = (sort perm) == (sort [1..length(perm)])\n\nsolve :: [Int] -> [Int]\nsolve q = if isProperPermutation (permutation q) then permutation q\n else [-1]\n\nlistToStr :: Show a => [a] -> String\nlistToStr l = unwords $ map (show) (l)\n\nmain = getLine >> B.getLine >>= putStrLn . listToStr . solve . getInts\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ intercalate \" \" . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (n:difs) = if (hasDup . sort $ res) || hasGreater n res then [-1] else res\n where res = map ((+) (1 + abs (minimum cbp))) cbp\n cbp = basePerm difs\n\nhasGreater :: Int -> [Int] -> Bool\nhasGreater _ [] = False\nhasGreater n (x:xs) = n < x || hasGreater n xs\n\nhasDup :: Eq a => [a] -> Bool\nhasDup (x:y:xs) = x == y || hasDup (y:xs)\nhasDup _ = False\n\narithSum :: Int -> Int\narithSum n = (n * (n+1)) `div` 2\n\nbasePerm :: [Int] -> [Int]\nbasePerm (x:[]) = [0 - x] ++ [0]\nbasePerm (x:xs) = [head restPerm - x] ++ restPerm\n where restPerm = basePerm xs\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\nmain = do\n C.getLine\n qs <- map ((read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n let r = scanr (flip (-)) 1 qs\n m = minimum r\n t = map ((if m < 1 then (1-m) else 0)+) r \n p = let q = S.fromList t in if length q == length t then True else False\n mapM_ (\\x -> putStr $ show x ++ \" \") $ if p then t else [(-1)] \n putStrLn \"\""}, {"source_code": "module Main where\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\nmain = do\n C.getLine\n qs <- map ((read :: String -> Int) . C.unpack) . C.words <$> C.getLine\n let r = scanr (flip (-)) 1 qs\n m = minimum r\n t = map ((if m < 1 then (1-m) else 0)+) r \n p = not $ any (>length t) t\n mapM_ (\\x -> putStr $ show x ++ \" \") $ if p then t else [(-1)] \n putStrLn \"\""}, {"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Array.ST.Safe\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nenc :: Int -> Builder\nenc = intDec\nout :: [Int] -> Builder\nout = mconcat . (intersperse (char7 ' ')) . map intDec\n\nsolve :: [Int] -> Builder\nsolve (n:a)\n | check b1 = out b1\n | check bn = out bn\n | check b0 = out b0\n | otherwise = intDec (-1)\n where\n q = take (n - 1) a\n b1 = scanl (+) 1 q\n bn = scanl (+) n q\n b0 = map (succ . subtract u) b1\n u = minimum b1\n check l = runST $ do\n d <- newArray (1, n) False :: ST s (STUArray s Int Bool)\n x <- forM l $ \\i -> do\n if i < 1 || i > n then return True\n else do\n w <- readArray d i\n if w then do\n writeArray d i True\n return True\n else return False \n return $! not (or x)\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "import Data.List\n\n\nturnListIntoString :: [Int] -> String\nturnListIntoString qs = unwords . map show $ qs\n\ntrialUni :: [Int] -> Int -> Bool \ntrialUni qs n = w && t where\n t = all (\\x -> x >= 1 && x <=n) qs\n w = all (\\x -> x == 1) . map length . group $ qs \n\n\nfoldOnQ :: [Int] -> [Int]\nfoldOnQ qs = ret where \n t = scanl (\\b a -> b + a) 1 qs\n m = minimum t\n ret = if m < 0 then map (-m + 1 + ) t\n else if m == 0 then map ( + 1) t\n else t\n\nsolve :: [[Int]] -> String\nsolve [[n], qs] = w where \n t = foldOnQ qs\n w = if trialUni t n then turnListIntoString t\n else \"-1\"\n\nrInt :: String -> Int\nrInt = read\n\nmain :: IO ()\nmain = interact $ solve . (map . map) rInt . map words . lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.Bits\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Int] -> [Int]\nprocess qs = if valid then ps else [-1] where\n accum = scanl (+) 0 qs\n offset = 1 - (minimum accum)\n ps = map (+ offset) accum\n valid = unique ps && maximum ps == length ps\n\nunique l = Set.size set == length l where\n set = foldl (flip Set.insert) Set.empty l\n\nmain = do\n n <- getInt\n qs <- getInts\n printList $ process qs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.Bits\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Int] -> [Int]\nprocess qs = if valid then ps else [-1] where\n accum = scanl (+) 0 qs\n offset = 1 - (minimum accum)\n ps = map (+ offset) accum\n valid = maximum ps == length ps\n\nmain = do\n n <- getInt\n qs <- getInts\n printList $ process qs\n"}], "src_uid": "b6ac7c30b7efdc7206dbbad5cfb86db7"} {"source_code": "f::[Int]->Int\nf (_:_:[])=0\nf (1:0:1:xs)=1+f (0:0:xs)\nf (x:xs)=f xs\n\nmain = do\n e<-getLine\n e2<-getLine\n let xs=map read (words e2)::[Int]\n print $ f xs", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve [_, _] = 0\nsolve (a:b:c:d) \n | a == 1 && b == 0 && c == 1 = 1 + solve (0:0:d)\n | otherwise = solve (b:c:d)\n\nmain :: IO ()\nmain = do\n _ <- readInt\n xs <- readInts\n print $ solve xs"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (1:0:1:fs) = 1 + solve fs\nsolve (_:fs) = solve fs\nsolve [] = 0\n"}, {"source_code": "solve :: [Int] -> Int\nsolve [] = 0\nsolve (a:[]) = 0\nsolve (a:b:[]) = 0\nsolve (1:0:1:tail) = 1+ solve(0:0:tail)\nsolve (a:b) = solve b\n\n\nmain :: IO()\nmain = do\n n <- getLine\n s <- getLine\n (putStrLn . show . solve . (map (read::String->Int)) . words) s"}, {"source_code": "readInt :: String -> Int\nreadInt = read\n\nparseInt :: String -> [Int]\nparseInt file\n = [ readInt word | word <- words $ last $ lines file ]\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve [_] = 0\nsolve [_, _] = 0\nsolve (1 : 0 : 1 : xs) = 1 + solve (0 : xs)\nsolve (x : xs) = solve xs\n\nmain = do interact $ (\\t -> show t ++ \"\\n\") . solve . parseInt\n"}, {"source_code": "import Data.Maybe\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nparseInput :: String -> [Int]\nparseInput file\n = [ readInt word | word <- words $ last $ lines file ]\n\nprocessInput :: [Int] -> Int\nprocessInput = adjust . disturbed 0\n\nshowOutput :: Int -> String\nshowOutput x = show x ++ \"\\n\"\n\n\nmain = interact $ showOutput . processInput . parseInput\n\ndisturbed :: Int -> [Int] -> [Int]\ndisturbed _ [] = []\ndisturbed _ [_] = []\ndisturbed _ [_, _] = []\ndisturbed m (x:y:z:zs)\n = if x == 1 && y == 0 && z == 1\n then (m + 1) : disturbed (m + 2) (z:zs)\n else disturbed (m + 1) (y:z:zs)\n\nadjust :: [Int] -> Int\nadjust [] = 0\nadjust [_] = 1\nadjust (i:j:js)\n = if j == i + 2\n then 1 + adjust js\n else 1 + adjust (j : js)\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nparseInput :: String -> [Int]\nparseInput file\n = [ readInt word | word <- words $ last $ lines file ]\n\nprocessInput :: [Int] -> Int\nprocessInput xs = (adjust . disturbed . zeros) xs\n where zeros = findIndices ( == 0)\n disturbed :: [Int] -> [Int]\n disturbed [] = []\n disturbed [x] = if x == (length xs) - 1 || x == 0 then [] else [x]\n disturbed (x:y:ys)\n = if y == x + 1\n then disturbed ys\n else if x == 0 then disturbed (y:ys) else x : disturbed (y:ys)\n\nshowOutput :: Int -> String\nshowOutput x = show x ++ \"\\n\"\n\nadjust :: [Int] -> Int\nadjust [] = 0\nadjust [_] = 1\nadjust (i:j:js)\n = if j == i + 2\n then 1 + adjust js\n else 1 + adjust (j : js)\n\nmain = interact $ showOutput . processInput . parseInput\n"}, {"source_code": "import Data.Maybe\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nparseInput :: String -> [Int]\nparseInput file\n = [ readInt word | word <- words $ last $ lines file ]\n\nprocessInput :: [Int] -> Int\nprocessInput xs = (adjust . disturbed . zeros) xs\n where zeros = findIndices ( == 0)\n disturbed :: [Int] -> [Int]\n disturbed [] = []\n disturbed [x] = if x == (length xs) - 1 then [] else [x]\n disturbed (x:y:ys)\n = if y == x + 1\n then disturbed ys\n else if x == 0 then disturbed (y:ys) else x : disturbed (y:ys)\n\nshowOutput :: Int -> String\nshowOutput x = show x ++ \"\\n\"\n\nadjust :: [Int] -> Int\nadjust [] = 0\nadjust [_] = 1\nadjust (i:j:js)\n = if j == i + 2\n then 1 + adjust js\n else 1 + adjust (j : js)\n\nmain = interact $ showOutput . processInput . parseInput\n"}], "src_uid": "ea62b6f68d25fb17aba8932af8377db0"} {"source_code": "\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nrInt = fst . fromJust . C.readInteger\nrList = fmap (map rInt . C.words)\n\nsolve as bs sa sb c | ae || be = if (sa+(sum as)) /= (sb+(sum bs)) then -1 else c+1\n | sa == sb = solve ta tb (sa+a) (sb+b) (c+1)\n | sa < sb = solve ta bs (sa+a) sb c\n | sa > sb = solve as tb sa (sb+b) c\n where ae = as == []; be = bs == []\n a = head as ; b = head bs\n ta = tail as ; tb = tail bs\n\nmain = do\n C.getLine\n as <- rList C.getLine\n C.getLine\n bs <- rList C.getLine\n print $ solve (tail as) (tail bs) (head as) (head bs) 0\n", "positive_code": [{"source_code": "\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nrInt = fst . fromJust . C.readInteger\nrList = fmap (map rInt . C.words)\n\nsolve as bs sa sb c | ae && be = if sa /= sb then -1 else c+1\n | ae || be = solve [] [] (sa+(sum as)) (sb+(sum bs)) c\n | sa == sb = solve ta tb (sa+a) (sb+b) (c+1)\n | sa < sb = solve ta bs (sa+a) sb c\n | sa > sb = solve as tb sa (sb+b) c\n where ae = as == []; be = bs == []\n a = head as ; b = head bs\n ta = tail as ; tb = tail bs\n\nmain = do\n C.getLine\n as <- rList C.getLine\n C.getLine\n bs <- rList C.getLine\n print $ solve (tail as) (tail bs) (head as) (head bs) 0\n"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nrInt = fst . fromJust . C.readInteger\nrList = fmap (map rInt . C.words)\n\n\nsolve (x:xs) (y:ys) =\n if x + y == 0 then 0\n else if x == y then 1 + solve xs ys\n else if x > y then solve (y:ys) (x:xs)\n else if (head xs) == 0 then inf\n else solve ((x+(head xs)):(tail xs)) (y:ys)\n \ninf=10000000000000\n\nfunc x = if x >= inf then -1 else x\n\nmain = do\n C.getLine\n as <- rList C.getLine\n C.getLine\n bs <- rList C.getLine\n print $ func (solve (as++[0,0..]) (bs++[0,0..]))\n "}], "negative_code": [{"source_code": "\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nrInt = fst . fromJust . C.readInt\nrList = fmap (map rInt . C.words)\n\nsolve as bs sa sb c | ae && be = if sa /= sb then -1 else c+1\n | ae || be = solve [] [] (sa+(sum as)) (sb+(sum bs)) c\n | sa == sb = solve ta tb (sa+a) (sb+b) (c+1)\n | sa < sb = solve ta bs (sa+a) sb c\n | sa > sb = solve as tb sa (sb+b) c\n where ae = as == []; be = bs == []\n a = head as ; b = head bs\n ta = tail as ; tb = tail bs\n\nmain = do\n C.getLine\n as <- rList C.getLine\n C.getLine\n bs <- rList C.getLine\n print $ solve (tail as) (tail bs) (head as) (head bs) 0\n"}, {"source_code": "\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nrInt = fst . fromJust . C.readInt\nrList = fmap (map rInt . C.words)\n\nsolve (a:as) (b:bs) sa sb c | as == [] || bs == [] =\n solve [] [] (sa+a+(sum as)) (sb+b+(sum bs)) c\n | sa == sb = solve as bs (sa+a) (sb+b) (c+1)\n | sa < sb = solve as (b:bs) (sa+a) sb c\n | sa > sb = solve (a:as) bs sa (sb+b) c\n\nsolve [] [] sa sb c = if sa /= sb then -1 else c+1\n\nmain = do\n C.getLine\n as <- rList C.getLine\n C.getLine\n bs <- rList C.getLine\n print $ solve as bs (head as) (head bs) 0\n"}], "src_uid": "8c36ab13ca1a4155cf97d0803aba11a3"} {"source_code": "main = interact $ show.solve.map ((\\[x,y]->(x,y)).map read.words).tail.lines\n\nsolve :: [(Int,Int)] -> Int\nsolve xys = length $ filter (flip p xys) xys\n\np (x,y) xys = (or $ map h xys)&&(or $ map j xys)&&(or $ map k xys)&&(or $ map l xys)\n where h (z,w)= zw\n l (z,w)= z>x && y==w\n\nh (x,y) (z,w) = zw\nl (x,y) (z,w) = z>x && y==w\n", "positive_code": [{"source_code": "import System.IO\nimport Data.Array\n\nparse h = do\n n <- fmap read (hGetLine h)\n ps <- mapM f [1..n]\n return (n, ps)\n where\n f _ = fmap (g . map read . words) (hGetLine h)\n g [x,y] = (x,y)\n\nsolve (n, ps) = length $ filter f ps\n where\n f (x,y) = left ! y /= x\n && right ! y /= x\n && bottom ! x /= y\n && top ! x /= y\n left = accumArray min inf b ps'\n right = accumArray max (-inf) b ps'\n bottom = accumArray min inf b ps\n top = accumArray max (-inf) b ps\n ps' = map (\\(x, y) -> (y, x)) ps\n b = (-1000, 1000)\n inf = 10^4\n\nmain = print . solve =<< parse stdin\n\n-- vim: set expandtab:\n"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n n <- (liftM read) getLine\n p <- replicateM n $ (liftM $ (\\[x,y] -> (read x, read y) :: (Int, Int)) . words) getLine\n let left = filter (\\(x,y) -> any (\\(x',y') -> x' < x && y == y') p) p\n right = filter (\\(x,y) -> any (\\(x',y') -> x' > x && y == y') p) p\n up = filter (\\(x,y) -> any (\\(x',y') -> y' > y && x == x') p) p\n down = filter (\\(x,y) -> any (\\(x',y') -> y' < y && x == x') p) p\n super = filter (\\u -> all (\\l -> elem u l) [left, right, up, down]) p\n putStrLn . show $ length super\n"}, {"source_code": "import Control.Applicative\n\nbelow (x, y) (x', y') = x < x' && y == y'\nrotate (x, y) = (-y, x)\n\nsolve ps =\n\t\tlength $ filter supercentral ps\n\twhere\n\t\tsupercentral p = and [any (below p') ps' | (p', ps') <- take 4 $ zip (iterate rotate p) (iterate (map rotate) ps)]\n\nmain = do\n\t_ <- getLine\n\tps <- map ((\\[a,b] -> (a,b)) . map read . words) . lines <$> getContents\n\tprint $ solve ps\n"}, {"source_code": "\nimport Array\n\ntype Point = (Int, Int)\n\nn :: Int\nn = 1000\n\nmaxInt, minInt :: Int\nmaxInt = maxBound\nminInt = minBound\n\nsolve :: [Point] -> Int\nsolve ps = length $ filter f ps\n where\n f :: Point -> Bool\n f (x, y)\n | x >= lefts ! y = False\n | x <= rights ! y = False\n | y >= uppers ! x = False\n | y <= downs ! x = False\n | otherwise = True\n uppers = accumArray max minInt (-n, n) [(x, y) | (x, y) <- ps]\n downs = accumArray min maxInt (-n, n) [(x, y) | (x, y) <- ps]\n lefts = accumArray max minInt (-n, n) [(x, y) | (y, x) <- ps]\n rights = accumArray min maxInt (-n, n) [(x, y) | (y, x) <- ps]\n\nparsePoint :: String -> Point\nparsePoint s = (x, y)\n where\n [x, y] = map read (words s)\n\nmain :: IO ()\nmain = do\n n <- readLn\n lines <- mapM (const getLine) [1..n]\n let points = map parsePoint lines\n print $ solve points\n"}, {"source_code": "import Data.Bits\n\nt :: [Int] -> [Int] -> Int\nt [a, c] [b, d]\n | a == b && c < d = 1\n | a == b && c > d = 2\n | a < b && c == d = 4\n | a > b && c == d = 8\n | True = 0\n\ns q = length $ filter (\\p -> foldl (.|.) 0 (map (t p) q) == 15) q\nmain = interact $ show . s . map (map read . words) . tail . lines\n\n"}, {"source_code": "import Data.Bits\n\nt :: [Int] -> [Int] -> Int\nt [x1, y1] [x2, y2]\n | x1 == x2 && y1 < y2 = 1\n | x1 == x2 && y1 > y2 = 2\n | x1 < x2 && y1 == y2 = 4\n | x1 > x2 && y1 == y2 = 8\n | True = 0\n\ns q = length $ filter (\\p -> foldl (.|.) 0 (map (t p) q) == 15) q\nmain = interact $ show . s . map (map read . words) . tail . lines\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n ((,) <$> readInt <*> readInt)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ncheck1 (x1, y1) (x2, y2) = x1 == x2 && y1 > y2\ncheck2 (x1, y1) (x2, y2) = x1 == x2 && y1 < y2\ncheck3 (x1, y1) (x2, y2) = y1 == y2 && x1 > x2\ncheck4 (x1, y1) (x2, y2) = y1 == y2 && x1 < x2\n\nsolve pts = length [ a\n | a <- pts\n , and [ any (check a) pts\n | check <- [check1, check2, check3, check4]\n ]\n ]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (toTuple . map read . words) . tail . lines\n\nsolve :: [(Int, Int)] -> Int\nsolve xys = length [ (x, y) | (x, y) <- xys, all (flip any xys . ($ (x, y))) [ left, right, lower, upper ] ]\n where left (x, y) (x', y') = x' > x && y' == y\n right (x, y) (x', y') = x' < x && y' == y\n lower (x, y) (x', y') = x' == x && y' < y\n upper (x, y) (x', y') = x' == x && y' > y\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "main = print . solve . pairs . map read . tail . words =<< getContents\npairs (x:y:zs) = (x,y) : pairs zs\npairs _ = []\nsolve :: [(Int,Int)] -> Int\nsolve ps = length (filter (superCentral ps) ps)\nsuperCentral ps p = hasNeighbor right ps p &&\n hasNeighbor left ps p &&\n hasNeighbor lower ps p &&\n hasNeighbor upper ps p\nhasNeighbor dir ps p = not $ null $ filter (dir p) ps\nright (x,y) (x',y') = x' > x && y' == y\nleft (x,y) (x',y') = x' < x && y' == y\nupper (x,y) (x',y') = x' == x && y' < y\nlower (x,y) (x',y') = x' == x && y' > y"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\nimport Control.Monad\nimport Control.Applicative\nimport Text.Printf\nimport Data.List\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Char as C\n\natoi :: B.ByteString -> Int\natoi s | B.head s == '-' = - (atoi' $ B.tail s)\n | otherwise = atoi' s\n\natoi' :: B.ByteString -> Int\natoi' = B.foldl' (\\a c -> a*10 + C.ord c - C.ord '0') 0\n\ntype P = (Int, Int)\n\nrot :: P -> P\nrot (x, y) = (y, -x)\n\nsolve :: [P] -> Int\nsolve ps = length $ filter (supercentral ps) ps\n\nsupercentral :: [P] -> P -> Bool\nsupercentral ps = all (uncurry anybelow) . flip zip rss . iterate rot\n where rss = take 4 $ iterate (map rot) ps\n\nanybelow :: P -> [P] -> Bool\nanybelow p = any (isbelow p)\n\nisbelow :: P -> P -> Bool\nisbelow (x, y) (x', y') = (x == x') && (y < y')\n\nmain = do\n n <- head . map atoi . B.words <$> B.getLine\n ps <- replicateM n $ do\n [x, y] <- map atoi . B.words <$> B.getLine\n return (x, y)\n printf \"%d\\n\" $ solve ps\n"}, {"source_code": "import Control.Applicative\n\nbelow (x, y) (x', y') = x < x' && y == y'\nrotate (x, y) = (-y, x)\n\nsolve ps =\n\t\tlength [p | p <- ps, supercentral p]\n\twhere\n\t\tsupercentral p = and [any (below p') ps' | (p', ps') <- take 4 $ zip (iterate rotate p) (iterate (map rotate) ps)]\n\nmain = do\n\tn <- readLn :: IO Int\n\tps <- map ((\\[a,b] -> (a,b)) . map (read :: String -> Int) . words) . lines <$> getContents\n\tprint $ solve ps\n"}, {"source_code": "readPoint = do\n line <- getLine\n let ints = map (read::String->Int) (words line)\n return (ints !! 0, ints !! 1)\n \ntop (x1,y1) (x2,y2) = x1 == x2 && y1 < y2 \nleft (x1,y1) (x2,y2) = x1 < x2 && y1 == y2\nright (x1,y1) (x2,y2) = x1 > x2 && y1 == y2\nbottom (x1,y1) (x2,y2) = x1 == x2 && y1 > y2\n\nsupercentral xs p = any (top p) xs && any (bottom p) xs && any (right p) xs && any (left p) xs\n\ncount xs = foldl (\\acc b -> if b then acc + 1 else acc) 0 xs\n\nmain = do\n n <- readLn :: IO Int\n pts <- mapM (\\_ -> readPoint) [1..n]\n let supers = count (map (supercentral pts) pts)\n print supers"}, {"source_code": "import Control.Monad\nimport Data.Char\n\nmain :: IO ()\nmain = do \n input <- getLine\n let n = read input :: Int\n input <- replicateM n getLine\n let coords = [getAsInt item | item <- input]\n print $ length $ filter (isCentral coords) coords\n\nisCentral :: [(Int, Int)] -> (Int, Int) -> Bool\nisCentral coords (x, y)\n | getNeightbour (x, y) coords \"top\" && getNeightbour (x, y) coords \"left\" && getNeightbour (x, y) coords \"right\" && getNeightbour (x, y) coords \"bottom\" = True\n | otherwise = False\n\ngetNeightbour :: (Int, Int) -> [(Int, Int)] -> String -> Bool\ngetNeightbour item [(x, y)] part = isTrue item (x, y) part\ngetNeightbour item ((x, y):xs) part\n | isTrue item (x, y) part = True\n | otherwise = getNeightbour item xs part\n\ngetAsInt :: String -> (Int, Int)\ngetAsInt w = (head r, last r)\n where\n r = map read $ words w\n\nisTrue :: (Int, Int) -> (Int, Int) -> String -> Bool\nisTrue (x', y') (x, y) part\n | part == \"left\" = x'\u2009>\u2009x && y'\u2009==\u2009y\n | part == \"right\" = x'\u2009<\u2009x && y'\u2009==\u2009y\n | part == \"top\" = x'\u2009==\u2009x && y'\u2009>\u2009y\n | part == \"bottom\" = x'\u2009==\u2009x && y'\u2009<\u2009y"}, {"source_code": "import Data.Bits\n\nt :: [Int] -> [Int] -> Int\nt [a, c] [b, d]\n | a == b && c < d = 1\n | a == b && c > d = 2\n | a < b && c == d = 4\n | a > b && c == d = 8\n | True = 0\n\ns q = length $ filter (\\p -> foldl (.|.) 0 (map (t p) q) == 15) q\nmain = interact $ show . s . map (map read . words) . tail . lines"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = getLine >>= return . read\n >>= flip replicateM getLine\n >>= return . map (map read . words)\n >>= putStrLn . show . solve\n\nsolve ar = length . filter (==5) $ map (flip sl ar) ar\n\nsl a = length . filter (elem 0) . nub . map mw\n where mw = map signum . zipWith (-) a\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map (\\[a, b] -> (a, b)) . map (map read . words) . tail . lines)\n\nsolve :: [(Int, Int)] -> Int\nsolve points = length central where\n central = filter (\\p -> haveRight p &&\n haveLeft p &&\n haveTop p &&\n haveBottom p) points\n\n\n haveRight (x, y) = any (\\(x', y') -> y == y' && x < x') points\n haveLeft (x, y) = any (\\(x', y') -> y == y' && x' < x) points\n haveTop (x, y) = any (\\(x', y') -> y < y' && x' == x) points\n haveBottom (x, y) = any (\\(x', y') -> y' < y && x' == x) points\n"}, {"source_code": "import Data.Function\nimport Data.List\nimport Control.Monad\n\nt1 (a, _, _) = a\nt2 (_, a, _) = a\nt3 (_, _, a) = a\n\n\n-- subsolve :: [[(Int, Int, Int)]] -> [[(Int, Int, Int)]]\nsubsolve points f = map subsub points\n where\n subsub l = (let \n sorted = sortBy (compare `on` f) l\n in \n (head sorted) : (subsub' $ tail sorted))\n subsub' [] = []\n subsub' [foo] = [foo]\n subsub' ((x, y, cnt):l) = (x, y, cnt + 2) : (subsub' l)\n\n-- solve :: [(Int, Int, Int)] -> Int\nsolve points = \n let p1 = concat $ subsolve (groupBy ((==) `on` t1) (sortBy (compare `on` t1) points)) t2\n p2 = concat $ subsolve (groupBy ((==) `on` t2) (sortBy (compare `on` t2) p1)) t1\n in\n length (filter (\\x -> (t3 x) == 4) p2)\n\ntuplify [x, y] = (x, y, 0)\n\nmain = do\n n <- getLine >>= return . (read::String->Int)\n points <- forM [1..n] (\\_ -> getLine >>= (return . tuplify . map (read::String->Int) . words))\n -- print points\n print $ solve points\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n ((,) <$> readInt <*> readInt)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ncheck1 (x1, y1) (x2, y2) = x1 == x2 && y1 > y2\ncheck2 (x1, y1) (x2, y2) = x1 == x2 && y1 < y2\ncheck3 (x1, y1) (x2, y2) = y1 == y2 && x1 > x2\ncheck4 (x1, y1) (x2, y2) = y1 == y2 && x1 > x2\n\nsolve pts = length [ a\n | a <- pts\n , and [ any (check a) pts\n | check <- [check1, check2, check3, check4]\n ]\n ]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "main = interact $ show.solve.map ((\\[x,y]->(x,y)).map read.words).tail.lines\n\nsolve :: [(Int,Int)] -> Int\nsolve xys = let minx = minimum.map fst $ xys\n miny = minimum.map snd $ xys\n maxx = maximum.map fst $ xys\n maxy = maximum.map snd $ xys\n p (x,y) = x==minx || y==miny || x==maxx || y==maxy\n zs = filter p xys\n q (x,y) = (x,y)`notElem`zs && any (`elem`zs) [(x,y+1),(x,y-1),(x+1,y),(x-1,y)]\n in length $ filter q xys"}, {"source_code": "import Data.Function\nimport Data.List\nimport Control.Monad\n\nt1 (a, _, _) = a\nt2 (_, a, _) = a\nt3 (_, _, a) = a\n\n\n-- subsolve :: [[(Int, Int, Int)]] -> [[(Int, Int, Int)]]\nsubsolve points f = map subsub points\n where\n subsub l = (head l) : (subsub' . tail $ sortBy (compare `on` f) l)\n subsub' [] = []\n subsub' [foo] = [foo]\n subsub' ((x, y, cnt):l) = (x, y, cnt + 2) : (subsub' l)\n\n-- solve :: [(Int, Int, Int)] -> Int\nsolve points = \n let p1 = concat $ subsolve (groupBy ((==) `on` t1) (sortBy (compare `on` t1) points)) t2\n p2 = concat $ subsolve (groupBy ((==) `on` t2) (sortBy (compare `on` t2) p1)) t1\n in\n length (filter (\\x -> (t3 x) == 4) p2)\n\ntuplify [x, y] = (x, y, 0)\n\nmain = do\n n <- getLine >>= return . (read::String->Int)\n points <- forM [1..n] (\\_ -> getLine >>= (return . tuplify . map (read::String->Int) . words))\n -- print points\n print $ solve points"}, {"source_code": "import Data.Function\nimport Data.List\nimport Control.Monad\n\nt1 (a, _, _) = a\nt2 (_, a, _) = a\nt3 (_, _, a) = a\n\n\n-- subsolve :: [[(Int, Int, Int)]] -> [[(Int, Int, Int)]]\nsubsolve points f = map subsub points\n where\n subsub l = (head l) : (subsub' . tail $ sortBy (compare `on` f) l)\n subsub' [] = []\n subsub' [foo] = [foo]\n subsub' ((x, y, cnt):l) = (x, y, cnt + 2) : (subsub' l)\n\n-- solve :: [(Int, Int, Int)] -> Int\nsolve points = \n let p1 = concat $ subsolve (groupBy ((==) `on` t1) (sortBy (compare `on` t1) points)) t2\n p2 = concat $ subsolve (groupBy ((==) `on` t2) (sortBy (compare `on` t2) p1)) t1\n in\n length (filter (\\x -> (t3 x) == 4) p2)\n\ntuplify [x, y] = (x, y, 0)\n\nmain = do\n n <- getLine >>= return . (read::String->Int)\n points <- forM [1..n] (\\_ -> getLine >>= (return . tuplify . map (read::String->Int) . words))\n -- print points\n print $ solve points"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\nimport Control.Monad\nimport Control.Applicative\nimport Text.Printf\nimport Data.List\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Char as C\n\natoi :: B.ByteString -> Int\natoi = B.foldl' (\\a c -> a*10 + C.ord c - C.ord '0') 0\n\ntype P = (Int, Int)\n\nrot :: P -> P\nrot (x, y) = (y, -x)\n\nsolve :: [P] -> Int\nsolve ps = length $ filter (supercentral ps) ps\n\nsupercentral :: [P] -> P -> Bool\nsupercentral ps = all (uncurry anybelow) . flip zip rss . iterate rot\n where rss = take 4 $ iterate (map rot) ps\n\nanybelow :: P -> [P] -> Bool\nanybelow p = any (isbelow p)\n\nisbelow :: P -> P -> Bool\nisbelow (x, y) (x', y') = (x == x') && (y < y')\n\nmain = do\n n <- head . map atoi . B.words <$> B.getLine\n ps <- replicateM n $ do\n [x, y] <- map atoi . B.words <$> B.getLine\n return (x, y)\n printf \"%d\\n\" $ solve ps\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\nimport Control.Monad\nimport Control.Applicative\nimport Text.Printf\nimport Data.List\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Char as C\n\natoi :: B.ByteString -> Int\natoi = B.foldl' (\\a c -> a*10 + C.ord c - C.ord '0') 0\n\ntype P = (Int, Int)\n\nrot :: P -> P\nrot (x, y) = (y, -x)\n\nsolve :: [P] -> Int\nsolve ps = length $ filter (supercentral ps) ps\n\nsupercentral :: [P] -> P -> Bool\nsupercentral ps = all (uncurry anybelow) . flip zip rss . iterate rot\n where rss = take 4 $ iterate (map rot) ps\n\nanybelow :: P -> [P] -> Bool\nanybelow p = any (isbelow p)\n\nisbelow :: P -> P -> Bool\nisbelow (x, y) (x', y') = (x == x') && (y < y')\n\ntopairs :: [Int] -> [P]\ntopairs [] = []\ntopairs (x:y:xs) = (x,y) : topairs xs\n\nmain = do\n (_:xs) <- map atoi . B.words <$> B.getContents\n printf \"%d\\n\" . solve $ topairs xs\n"}], "src_uid": "594e64eef7acd055d59f37710edda201"} {"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = tail (lines input)\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n n = read input\r\n result = findDistanceToPowerOfTwo n\r\n output = show result\r\n\r\n\r\nfindDistanceToPowerOfTwo :: Integer -> Int\r\nfindDistanceToPowerOfTwo starting_number = min_distance\r\n where\r\n starting_string = show starting_number\r\n powers_of_two = map (2^) [0..]\r\n potential_targets = map show powers_of_two\r\n max_distance = findTransformationCost starting_string (head potential_targets)\r\n max_length_allowed = length starting_string + max_distance\r\n interesting_targets = takeWhile\r\n ((<= max_length_allowed) . length)\r\n potential_targets\r\n distances_variants = map (findTransformationCost starting_string) interesting_targets\r\n min_distance = minimum distances_variants\r\n\r\n\r\nfindTransformationCost :: String -> String -> Int\r\nfindTransformationCost start target\r\n | null start = length target\r\n | can_reuse_first_char = findTransformationCost (drop 1 start) (drop 1 target)\r\n | otherwise = 1 + findTransformationCost (drop 1 start) target\r\n where\r\n can_reuse_first_char = take 1 start == take 1 target\r\n", "positive_code": [{"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t readLn :: IO [Integer]\n\n (putStr . unlines . map (show . solve . show)) tcs\n\nmaxP2Len = (9+1)*2\np2pwrs = takeWhile ((maxP2Len>=).length) . map show . iterate (*2) $ (1::Integer)\n\nsolve :: String -> Int\nsolve = minimum . ($ p2pwrs) . map . solvePwr\n\nsolvePwr :: String -> String -> Int\nsolvePwr s p2 = length s + length p2 - (2 * longestPref s p2)\n\nlongestPref \"\" _ = 0\nlongestPref _ \"\" = 0\nlongestPref (c:cs) (p:ps) | (c == p) = 1 + longestPref cs ps\n | otherwise = 0 + longestPref cs (p:ps)\n"}, {"source_code": "import Data.Int (Int64)\n\nmain = do\n t <- read <$> getLine :: IO Int\n mapM_ (solve (map split [2 ^ (i :: Int64) | i <- [0..60]])) [1..t]\n\nsolve :: [[Int]] -> Int -> IO ()\nsolve powerOf2 _ = do\n n <- read <$> getLine :: IO Int\n print $ foldr1 min (map (dist $ split n) powerOf2)\n\nsplitHelper :: Integral a => a -> [Int]\nsplitHelper n\n | n == 0 = []\n | otherwise = let (x, y) = n `quotRem` 10 in fromIntegral y : splitHelper x\n\nsplit :: Integral a => a -> [Int]\nsplit = reverse . splitHelper\n\ndist :: [Int] -> [Int] -> Int\ndist (x:xs) ay@(y:ys) = if x == y then dist xs ys else 1 + dist xs ay\ndist xs [] = length xs\ndist [] ys = length ys"}, {"source_code": "import Data.List (genericLength)\r\n\r\n\r\nmain :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = tail (lines input)\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n n = read input\r\n result = findDistanceToPowerOfTwo n\r\n output = show result\r\n\r\n\r\nfindDistanceToPowerOfTwo :: Integer -> Integer\r\nfindDistanceToPowerOfTwo starting_number = min_distance\r\n where\r\n starting_string = show starting_number\r\n powers_of_two = map (2^) [0..]\r\n potential_targets = map show powers_of_two\r\n max_distance = findTransformationCost starting_string (head potential_targets)\r\n max_length_allowed = genericLength starting_string + max_distance\r\n interesting_targets = takeWhile\r\n ((<= max_length_allowed) . genericLength)\r\n potential_targets\r\n distances_variants = map (findTransformationCost starting_string) interesting_targets\r\n min_distance = minimum distances_variants\r\n\r\n\r\nfindTransformationCost :: String -> String -> Integer\r\nfindTransformationCost start target\r\n | null start = genericLength target\r\n | can_reuse_first_char = findTransformationCost (drop 1 start) (drop 1 target)\r\n | otherwise = 1 + findTransformationCost (drop 1 start) target\r\n where\r\n can_reuse_first_char = take 1 start == take 1 target\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ncountSteps :: String -> String -> Int\ncountSteps [] s2 = length s2\ncountSteps s1 [] = length s1\ncountSteps (x:xs) (s:ss) | x == s = countSteps xs ss\ncountSteps (x:xs) s = 1+(countSteps xs s)\n\ncalc :: String -> Int\ncalc str =\n let one = 1 :: Int64\n powers = take 61 $ map show $ iterate (*2) one\n in\n minimum $ map (countSteps str) powers\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n print $ calc line\n"}], "negative_code": [{"source_code": "import Data.Int (Int64)\n\nmain = do\n t <- read <$> getLine :: IO Int\n mapM_ (solve (map factor [2 ^ (i :: Int64) | i <- [0..60]])) [1..t]\n\nsolve :: [[Int]] -> Int -> IO ()\nsolve powerOf2 _ = do\n n <- read <$> getLine :: IO Int\n print $ foldr1 min (map (dist $ factor n) powerOf2)\n\nfactorHelper :: Integral a => a -> [Int]\nfactorHelper n = if n == 0\n then []\n else let (x, y) = n `quotRem` 10 in fromIntegral y : factor (x `quot` 10)\n\nfactor :: Integral a => a -> [Int]\nfactor = reverse . factorHelper\n\ndist :: [Int] -> [Int] -> Int\ndist (x:xs) ay@(y:ys) = if x == y then dist xs ys else 1 + dist xs ay\ndist xs [] = length xs\ndist [] ys = length ys"}], "src_uid": "728e0e5e5d8350a2b79e6a4b5bef407b"} {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\njoins :: [String] -> String\njoins [] = \"\"\njoins [x] = x\njoins (x:xs) = x ++ \" \" ++ (joins xs)\n\nsolve :: [Int] -> String\nsolve list = (show $ length answer) ++ \"\\n\" ++ (joins answer)\n where total = sum list\n n = length list\n answer = map show [index | (index , value) <- zip [1..] list , value * (n-1) == total - value]\nmain = interact$solve.(map read).tail.words", "positive_code": [{"source_code": "\nimport Char (digitToInt)\n--import CPUTime (getCPUTime)\nimport Data.List (foldl')\n\nmyReads :: String -> [Int]\nmyReads s = reverse (reads' s [])\n where\n reads' [] acc = acc\n reads' (' ':s) acc = reads' s acc\n reads' s acc = reads'' s 0 acc\n where\n reads'' [] x acc = let acc' = x:acc in acc' `seq` acc'\n reads'' (' ':s) x acc = let acc' = x:acc in acc' `seq` reads' s acc'\n reads'' (c:s) x acc = x' `seq` reads'' s x' acc\n where\n x' = 10 * x + digitToInt c\n\nsolve :: [Int] -> [Int]\nsolve xs\n | mod s n == 0 = solve' (div s n) xs\n | otherwise = []\n where\n solve' m xs = [i | (x, i) <- zip xs [1..], m == x]\n (s, n) = foldl' f (0, 0) xs\n where\n f (s, n) x = n `seq` s `seq` (s + x, n + 1)\n\nprintAns :: [Int] -> IO ()\nprintAns xs = print (length xs) >> printAns_ xs\n where\n printAns_ [] = return ()\n printAns_ [x] = print x\n printAns_ (x:xs) = putStr (show x ++ \" \") >> printAns_ xs\n\ncalcTime :: Fractional a => Integer -> Integer -> a\ncalcTime startTime endTime = fromIntegral (endTime - startTime) * 1e-12\n \nmain :: IO ()\nmain = do\n --t0 <- getCPUTime\n getLine >> getLine >>= printAns . solve . myReads\n --t1 <- getCPUTime\n --print (calcTime t0 t1)\n"}, {"source_code": "n=length\ns l=[a|(a,x)<-zip[1..]l,x*n l==sum l]\np l=unlines[show$n l,unwords$map show l]\nmain=interact$p.s.map read.tail.words"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve :: Int -> [Int] -> String\nsolve n l = let s = sum l\n in\n if s `mod` n /= 0 then\n \"0\"\n else\n let ave = s `div` n\n l_with_i = zipWith (\\a -> \\b -> (a,b)) l [1,2..]\n avenums = map (show.snd) $ filter (\\(a,b) -> a==ave) l_with_i\n len = length avenums\n in\n (show len)++\"\\n\"++(unwords avenums)\n\nmain = do n <- scan :: IO Int\n l <- scanlist :: IO [Int]\n puts $ solve n l"}, {"source_code": "import Data.List\nmain = do \n x <- getLine\n xs_l <- getLine\n let xs' = (map read (words xs_l))::[Double]\n let xs = zip xs' [1..]\n putStrLn $ show (length $ boll xs)\n putStrLn $ unwords $ map show (map snd (boll xs))\n\nboll xs = filter (\\(x,y)-> (x==avg (map fst xs))) xs --[x| x <- map ((==)(avg (map fst xs)))(xs)]\n\navg xs = avg' 0 0 xs\navg' count sum [] = sum / count\navg' count sum (x:xs) = avg' (count + 1) (sum + x) xs"}, {"source_code": "s l=map fst $ filter (isGood.snd) $ zip [1..] l where\n ss = sum l\n n = length l\n isGood x = x * n == ss\np l = unlines[show$length l,unwords$map show l]\nmain = interact$p.s.map read.tail.words\n"}, {"source_code": "n=length\ns l=[a|(a,x)<-zip[1..]l,x*n l==sum l]\np l=unlines[show$n l,unwords$map show l]\nmain=interact$p.s.map read.tail.words"}, {"source_code": "s l=map fst$filter((\\x->x*length l==sum l).snd)(zip [1..]l)where\np l=unlines[show$length l,unwords$map show l]\nmain=interact$p.s.map read.tail.words"}, {"source_code": "import Data.List\nmain = do\t\n\tx <- getLine\n\txs_l <- getLine\n\tlet xs' = (map read (words xs_l))::[Double]\n\tlet xs = zip xs' [1..]\n\tputStrLn $ show (length $ boll xs)\n\tputStrLn $ unwords $ map show (map snd (boll xs))\n\nboll xs = filter (\\(x,y)-> (x==avg (map fst xs))) xs --[x| x <- map ((==)(avg (map fst xs)))(xs)]\n\navg xs = avg' 0 0 xs\navg' count sum [] = sum / count\navg' count sum (x:xs) = avg' (count + 1) (sum + x) xs"}, {"source_code": "main = interact $ unlines.solve. map read. words. head. tail. lines\nsolve x = [show . length . gao $ x, unwords.map show. gao $ x] \ngao x = map fst. filter (ismean s l.snd) . zip [1..] $ x\n\twhere s = foldl1 (+) x\n\t\tl = length x\nismean s l x = x * l == s\n\n\n"}, {"source_code": "import Data.List\n\nprintAnswer :: [Int] -> String\nprintAnswer lst = (show.length $ lst) ++ \"\\n\" ++ putList lst\n where \n putList [] = \"\"\n putList (x:xs) = show x ++ \" \" ++ putList xs\n\nsolve :: [Int] -> [Int]\nsolve (n:xs) = numbers \n where \n (_, numbers) = unzip $ filter (isAverage n $ sum xs) $ zip xs $ iterate (+1) 1\n isAverage n s (x, _) = s == n * x\n\nmain = interact $ printAnswer.solve.map read.words"}], "negative_code": [{"source_code": "import Data.List\n\nprintAnswer :: [Int] -> String\nprintAnswer lst = (show.length $ lst) ++ \"\\n\" ++ putList lst\n where \n putList [] = \"\"\n putList (x:xs) = show x ++ \" \"\n\nsolve :: [Int] -> [Int]\nsolve (n:xs) = filter (isAverage (n - 1) $ sum xs) xs\n where isAverage n s x = s - x == n * x\n\nmain = interact $ printAnswer.solve.map read.words"}, {"source_code": "import Data.List\n\nprintAnswer :: [Int] -> String\nprintAnswer lst = (show.length $ lst) ++ \"\\n\" ++ putList lst\n where \n putList [] = \"\"\n putList (x:xs) = show x ++ \" \"\n\nsolve :: [Int] -> [Int]\nsolve (n:xs) = numbers \n where \n (_, numbers) = unzip $ filter (isAverage n $ sum xs) (zip xs $ iterate (+1) 1)\n isAverage n s (x, _) = s == n * x\n\nmain = interact $ printAnswer.solve.map read.words"}, {"source_code": "readWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> [Int]\nsolve a = filter myF a\n where\n myF x = (mod (s-x) (n-1) == 0) && (div (s-x) (n-1) == x)\n s = sum a\n n = length a\n\nprintAns :: [Int] -> IO ()\nprintAns a = do\n print (length a)\n printAns_ a\n where\n printAns_ [] = putStrLn \"\"\n printAns_ [x] = putStr (show x)\n printAns_ (x:xs) = putStr (show x ++ \" \") >> printAns_ xs\n\nmain :: IO ()\nmain = do\n getLine\n a <- Main.reads\n printAns (solve a)"}, {"source_code": "import List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> [Int]\nsolve xs\n | mod s n /= 0 = []\n | otherwise = map (+1) (map snd (filter (\\(a, b) -> a == m) (zipWith (\\x y -> (x, y)) xs [1..])))\n where\n s = sum xs\n n = length xs\n m = div s n\n \nprintAns :: [Int] -> IO ()\nprintAns xs = print (length xs) >> printAns_ xs\n where\n printAns_ [] = return ()\n printAns_ [x] = print x\n printAns_ (x:xs) = putStr (show x ++ \" \") >> printAns_ xs\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= printAns . solve\n"}, {"source_code": "readWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> [Int]\nsolve a = solve_ (sum a) (length a - 1) 1 a\n where\n solve_ _ _ _ [] = []\n solve_ s n i (x:xs)\n | myF x = i:(solve_ s n (i+1) xs)\n | otherwise = solve_ s n (i+1) xs\n where\n myF x = (mod (s-x) n == 0) && (s == x * (n+1))\n\nprintAns :: [Int] -> IO ()\nprintAns a = do\n print (length a)\n printAns_ a\n where\n printAns_ [] = putStrLn \"\"\n printAns_ [x] = putStrLn (show x)\n printAns_ (x:xs) = putStr (show x ++ \" \") >> printAns_ xs\n\nmain :: IO ()\nmain = do\n n <- readLn::(IO Int)\n a <- Main.reads\n case n of\n 200000 -> printAns [1..200000]\n _ -> if (n `elem` [5,4,3,2,10,10000]) then (printAns (solve a)) else putStrLn \"NO\""}, {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\njoins :: [String] -> String\njoins [] = \"\"\njoins [x] = x\njoins (x:xs) = x ++ \" \" ++ (joins xs)\n\nsolve :: [Int] -> String\nsolve list = joins $ map show [index | (index , value) <- zip [1..] list , value * (n-1) == total - value]\n where total = sum list\n n = length list\nmain = interact$solve.(map read).tail.words"}], "src_uid": "1a22bc82ddf6b3dfbf270bc5e3294c28"} {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n\ngetRank :: Integer -> Int\ngetRank a\n | a == 1 = -100000\n | a == 2 = 0\n | a == 13 = 1\n | mod a 12 == 0 = 2 + getRank (div a 12)\n | mod a 12 == 1 = 1 + getRank (div a 12 + 1)\n | otherwise = -100000\n\nrankList :: Int -> [Integer]\nrankList k = zipWith (+) s (reverse s)\n where s = map (12 ^) [0..k]\n\nlistToString :: [Integer] -> String\nlistToString [] = \"\"\nlistToString (x:xs) = (show x) ++ \" \" ++ listToString xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let a = read str\n let k = getRank a\n if (k < 0)\n then putStrLn \"NO\"\n else putStrLn (\"YES\\n1\\n\" ++ (show (k + 1)) ++ \"\\n\"\n ++ (show (div k 2)) ++ \"\\n\"\n ++ listToString (reverse (take (div k 2) (filter (a /=) (rankList k)))))\n \n", "positive_code": [{"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n\ngetRank :: Integer -> Int\ngetRank a\n | a == 1 = -100000\n | a == 2 = 0\n | a == 13 = 1\n | mod a 12 == 0 = 2 + getRank (div a 12)\n | mod a 12 == 1 = 1 + getRank (div a 12 + 1)\n | otherwise = -100000\n\nrankList :: Int -> [Integer]\nrankList k = zipWith (+) s (reverse s)\n where s = map (12 ^) [0..k]\n\nlistToString :: [Integer] -> String\nlistToString [] = \"\"\nlistToString (x:xs) = (show x) ++ \" \" ++ listToString xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let a = read str\n let k = getRank a\n if (k < 0)\n then putStrLn \"NO\"\n else putStrLn (\"YES\\n1\\n\" ++ (show (k + 1)) ++ \"\\n\"\n ++ (show (div k 2)) ++ \"\\n\"\n ++ listToString (reverse (take (div k 2) (filter (a /=) (rankList k)))))\n \n"}, {"source_code": "main = do interact (gao . read)\ngao n = if a!!y /= m then \"NO\" else unlines $ \"YES\": map show c where\n\ta = let f i j = i: f j (13 * j - 12 * i) in f 2 13\n\tx = last $ takeWhile ((==0) . mod n . (12^)) [0 ..]\n\tm = div n (12 ^ x)\n\ty = head $ dropWhile (( Int\ngetRank a\n | a == 1 = -100000\n | a == 2 = 0\n | a == 13 = 1\n | mod a 12 == 0 = 2 + getRank (div a 12)\n | mod a 12 == 1 = 1 + getRank (div a 12 + 1)\n | otherwise = -100000\n\nrankList :: Int -> [Integer]\nrankList k = zipWith (+) s (reverse s)\n where s = map (12 ^) [0..k]\n\nlistToString :: [Integer] -> String\nlistToString [] = \"\"\nlistToString (x:xs) = (show x) ++ \" \" ++ listToString xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let a = read str\n let k = getRank a\n if (k < 0)\n then putStrLn \"NO\"\n else putStrLn (\"YES\\n1\\n\" ++ (show (k + 1)) ++ \"\\n\"\n ++ (show (div k 2)) ++ \"\\n\"\n ++ listToString (drop (div k 2) (filter (a /=) (rankList k))))\n \n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n\ngetRank :: Integer -> Int\ngetRank a\n | a == 1 = -100000\n | a == 2 = 0\n | a == 13 = 1\n | mod a 12 == 0 = 2 + getRank (div a 12)\n | mod a 12 == 1 = 1 + getRank (div a 12 + 1)\n | otherwise = -100000\n\nrankList :: Int -> [Integer]\nrankList k = zipWith (+) s (reverse s)\n where s = map (12 ^) [0..k]\n\nlistToString :: [Integer] -> String\nlistToString [] = \"\"\nlistToString (x:xs) = (show x) ++ \" \" ++ listToString xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let a = read str\n let k = getRank a\n if (k < 0)\n then putStrLn \"NO\"\n else putStrLn (\"YES\\n1\\n\" ++ (show (k + 1)) ++ \"\\n\"\n ++ (show (div k 2)) ++ \"\\n\"\n ++ listToString (take (div k 2) (filter (a /=) (rankList k))))\n \n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n\ngetRank :: Integer -> Int\ngetRank a\n | a == 1 = -1\n | a == 2 = 0\n | a == 13 = 1\n | mod a 12 == 0 = 2 + getRank (div a 12)\n | mod a 12 == 1 = 1 + getRank (div a 12 + 1)\n | otherwise = -1\n\nrankList :: Int -> [Integer]\nrankList k = zipWith (+) s (reverse s)\n where s = map (12 ^) [0..k]\n\nlistToString :: [Integer] -> String\nlistToString [] = \"\"\nlistToString (x:xs) = (show x) ++ \" \" ++ listToString xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let a = read str\n let k = getRank a\n if (k == -1)\n then putStrLn \"NO\"\n else putStrLn (\"YES\\n1\\n\" ++ (show (k + 1)) ++ \"\\n\"\n ++ (show (div k 2)) ++ \"\\n\"\n ++ listToString (take (div k 2) (filter (a /=) (rankList k))))\n \n"}], "src_uid": "0ef5e0621f13107d0c8786766ae2ac56"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\ndata Point = P {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64 deriving (Eq, Ord)\n\ninstance Show Point where\n show (P x y) = show (x,y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P (fromIntegral n) 0\n\ninfixr 7 *:\n(*:) :: Int64 -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Int64\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\nmain :: IO ()\nmain = do\n _n <- getLine\n xs <- map (fromIntegral.readInt).B.words <$> B.getContents\n putStr.unlines.map show. solve $ perse xs\n\nperse :: [Int64] -> [[(Point, Point)]]\nperse (x0:y0:a0:b0:x1:y1:a1:b1:x2:y2:a2:b2:x3:y3:a3:b3:rest) = [(P x0 y0,P a0 b0)\n ,(P x1 y1,P a1 b1)\n ,(P x2 y2,P a2 b2)\n ,(P x3 y3,P a3 b3)\n ] : perse rest\nperse _ = []\n\nrot0, rot90, rot180, rot270 :: Point -> Point -> Point\nrot0 _ xy = xy\nrot90 (P a b) (P x y)= P ((b - y) + a) ((x - a) + b)\nrot180 p = rot90 p.rot90 p\nrot270 p = rot90 p.rot90 p.rot90 p\n{-# INLINE rot0 #-}\n{-# INLINE rot90 #-}\n{-# INLINE rot180 #-}\n{-# INLINE rot270 #-}\n\nisSquare :: [Point] -> Bool\nisSquare points = and [ v `dot` v == u `dot` u\n , v `dot` u == 0\n , p3 == p1 + (p2 - p0)\n , v /= P 0 0\n ]\n where\n [p0,p1,p2,p3] = sort points\n !v = p1 - p0\n !u = p2 - p0\n\nsolve :: [[(Point,Point)]] -> [Int]\nsolve moles = map query moles\n where\n query moles = case res of\n [] -> (-1)\n res -> minimum res\n where\n res = map (sum.map fst) $ filter p [zipWith (#) fs moles|fs <- replicateM 4 [(0,rot0),(1,rot90),(2,rot180),(3,rot270)]]\n (i,rot)#(xy, ab) = (i, rot ab xy)\n p ixys = isSquare $ map snd ixys\n ", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = interact $ unlines . map show . solve . tail . map (map read . words) . lines\n\nrotate0 (x, y) n \n\t| n == 0 = (x, y)\n\t| n == 1 = (-y, x)\n\t| n == 2 = (-x, -y)\n\t| otherwise = (y, -x)\n\nrotate (x:y:a:b:_) n = (tx + a, ty + b)\n\t\t\t\t\twhere (tx, ty) = rotate0 (x - a, y - b) n\n\nminimum' [] = -1\nminimum' xs = minimum xs\n\ndis (x, y) (x1, y1) = (x - x1) ^ 2 + (y - y1) ^ 2\n\nisSquare xs = isSqure' ss\n\t\twhere ss = group $ sort [dis a b | a <- xs, b <- xs];\n\t\t\t isSqure' (a:b:c:[]) = head a == 0 && head b * 2 == head c && length a == 4 && length b == 8 && length c == 4;\n\t\t\t isSqure' _ = False\n\nsolve :: [[Integer]] -> [Integer]\nsolve [] = []\nsolve (m1:m2:m3:m4:xs) = res : solve xs\n\t\twhere res = minimum' [n1 + n2 + n3 + n4 | n1 <- [0..3], n2 <- [0..3], n3 <- [0..3], n4 <- [0..3], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tisSquare [rotate m1 n1, rotate m2 n2, rotate m3 n3, rotate m4 n4]]\n\n\n\n\n\n\t\t\t \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ndata Vector = Vector Int Int Int Int deriving (Show, Eq)\n\nrotate :: Vector -> Vector\nrotate (Vector a b x y) = Vector a b (a - beta) (b + alpha)\n where\n alpha = x - a; beta = y - b\n\nisSquare :: [Vector] -> Bool\nisSquare vecs@(v1:vs@[v2, v3, v4]) =\n dis_x /= -1 &&\n dist vb vd == dis_x &&\n dist vc vb == dis_z && dist vc vd == dis_z &&\n dis_x /=0 && dis_z /= 0\n where\n dist (Vector _ _ x y) (Vector _ _ x' y') = (x'-x)^2+(y'-y)^2\n [d1,d2,d3] = map (dist v1) vs\n (dis_z, dis_x, vc)\n | d1 == d2 = (d1, d3, v4)\n | d2 == d3 = (d2, d1, v2)\n | d1 == d3 = (d1, d2, v3)\n | otherwise = (-1, -1, v1)\n [vb, vd] = delete vc vs\n\nmain :: IO ()\nmain = do\n n <- fmap (head . map read . words) getLine\n forM_ [1..n] (\\_ -> do\n moles <- replicateM 4 $ do\n [x, y, a, b] <- fmap (map read . words) getLine\n return $ Vector a b x y\n let squares = filter (isSquare . map snd) $ mapM (zip [0..] . take 4 . iterate rotate) moles\n print $ if null squares\n then -1\n else minimum $ map (sum . map fst) squares\n )\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ndata Vector = Vector Int Int Int Int deriving (Show, Eq)\n\nrotate :: Vector -> Vector\nrotate (Vector a b x y) = Vector a b (a - beta) (b + alpha)\n where\n alpha = x - a; beta = y - b\n\nisSquare :: [Vector] -> Bool\nisSquare vecs@(v1:vs@[v2, v3, v4]) =\n dis_x /= -1 &&\n dist vb vd == dis_x &&\n dist vc vb == dis_z && dist vc vd == dis_z &&\n not (and $ zipWith (==) vecs (tail vecs))\n where\n dist (Vector _ _ x y) (Vector _ _ x' y') = (x'-x)^2+(y'-y)^2\n [d1,d2,d3] = map (dist v1) vs\n (dis_z, dis_x, vc)\n | d1 == d2 = (d1, d3, v4)\n | d2 == d3 = (d2, d1, v2)\n | d1 == d3 = (d1, d2, v3)\n | otherwise = (-1, -1, v1)\n [vb, vd] = delete vc vs\n\nmain :: IO ()\nmain = do\n n <- fmap (head . map read . words) getLine\n forM_ [1..n] (\\_ -> do\n moles <- replicateM 4 $ do\n [x, y, a, b] <- fmap (map read . words) getLine\n return $ Vector a b x y\n let squares = filter (isSquare . map snd) $ mapM (zip [0..] . take 4 . iterate rotate) moles\n print $ if null squares\n then -1\n else minimum $ map (sum . map fst) squares\n )\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = interact $ unlines . map show . solve . tail . map (map read . words) . lines\n\nrotate0 (x, y) n \n\t| n == 0 = (x, y)\n\t| n == 1 = (-y, x)\n\t| n == 2 = (-x, -y)\n\t| otherwise = (y, -x)\n\nrotate (x:y:a:b:_) n = (tx + a, ty + b)\n\t\t\t\t\twhere (tx, ty) = rotate0 (x - a, y - b) n\n\nminimum' [] = -1\nminimum' xs = minimum xs\n\ndis (x, y) (x1, y1) = (x - x1) ^ 2 + (y - y1) ^ 2\n\nisSquare xs = isSqure' ss\n\t\twhere ss = group $ sort [dis a b | a <- xs, b <- xs];\n\t\t\t isSqure' (a:b:c:[]) = head a == 0 && head b * 2 == head c && length a == 4 && length b == 8 && length c == 4;\n\t\t\t isSqure' _ = False\n\nsolve :: [[Int]] -> [Int]\nsolve [] = []\nsolve (m1:m2:m3:m4:xs) = res : solve xs\n\t\twhere res = minimum' [n1 + n2 + n3 + n4 | n1 <- [0..3], n2 <- [0..3], n3 <- [0..3], n4 <- [0..3], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tisSquare [rotate m1 n1, rotate m2 n2, rotate m3 n3, rotate m4 n4]]\n\n\n\n\n\n\t\t\t \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n _n <- getLine\n xs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show. solve $ perse xs\n\nperse :: [Int] -> [[(Int,Int,Int,Int)]]\nperse (x0:y0:a0:b0:x1:y1:a1:b1:x2:y2:a2:b2:x3:y3:a3:b3:rest) = [(x0,y0,a0,b0),(x1,y1,a1,b1),(x2,y2,a2,b2),(x3,y3,a3,b3)] : perse rest\nperse _ = []\n\nrot90 :: (Int,Int,Int,Int) -> (Int,Int,Int,Int)\nrot90 (x,y,a,b) = (x',y',a,b)\n where\n !x' = (-y) + a + b\n !y' = x - a + b\n{-# INLINE rot90 #-}\n\nrot180 = rot90.rot90\nrot270 = rot90.rot90.rot90\n{-# INLINE rot180 #-}\n{-# INLINE rot270 #-}\n\ndot :: (Int,Int) -> (Int,Int) -> Int\ndot (x,y) (a,b) = a*x+b*y\n{-# INLINE dot #-}\n\nisRect :: [(Int,Int,Int,Int)] -> Bool\nisRect moles = length(nub [(x0,y0),(x1,y1),(x2,y2),(x3,y3)]) == 4\n && (x1-x0,y1-y0)`dot`(x2-x0,y2-y0) == 0\n && (x3,y3) == (x1+x2-x0,y1+y2-y0)\n where\n sorted@[(x0,y0,_,_),(x1,y1,_,_),(x2,y2,_,_),(x3,y3,_,_)] = sort moles\n\nsolve :: [[(Int,Int,Int,Int)]] -> [Int]\nsolve moles = map query moles\n where\n query moles = case res of\n [] -> (-1)\n res -> minimum res\n where\n res = map (sum.map fst) $ filter p [zipWith (#) fs moles|fs <-mapM(const[(0,id),(1,rot90),(2,rot180),(3,rot270)]) [1..4]]\n (i,f)#xyab = (i, f xyab)\n p ixys = isRect $ map snd ixys\n "}], "src_uid": "41d791867f27a57b50eebaad29754520"} {"source_code": "import Data.List\ns[n,m]=take n$cycle$map snd$sort[(abs(i*2-m-1),i)|i<-[1..m]]\nmain=interact$unlines.map show.s.map read.words", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n\n let\n r\n | odd m = [c] ++ concat (zipWith (\\a b -> [a, b]) (reverse [1..c-1]) [c+1..m])\n | even m = concat $ zipWith (\\a b -> [a, b]) (reverse [1..c]) [c+1..m]\n where\n c = (m+1) `div` 2\n\n putStr $ unlines $ map show $ take n $ concat $ repeat r\n"}, {"source_code": "import Data.List (sort)\n\npt :: (Show a) => [a] -> IO()\npt [] = return ()\npt (x:xs) = do\n\tputStrLn $ show x\n\tpt xs\n\nmain = do\n\tstr <- getLine\n\tlet [n,m] = [read x::Int | x <- words str]\n\tlet lst = [ (abs $ m+1-2*i,i) | i<-[1..m]]\n\tlet srt = sort lst\n\tlet ret = take n $ cycle $ map snd srt\n\tpt ret\n"}, {"source_code": "solve :: Int -> [Int]\nsolve n\n | odd n = cycle $ take n $ solveR (div n 2) (div n 2 + 1)\n | otherwise = solveL (div n 2) (div n 2 + 1)\n where\n solveL l r\n | l == 1 = l : solveR (div n 2) r\n | otherwise = l : solveR (l - 1) r\n solveR l r \n | r == n = r : solveL l (div n 2 + 1)\n | otherwise = r : solveL l (r + 1)\n\nmain :: IO ()\nmain = do\n [m, n] <- getLine >>= return . map read . words\n mapM_ print $ take m (solve n)"}, {"source_code": "main = interact$unlines.map show.solve.map read.words\n\nsolve :: [Int] -> [Int]\nsolve [n,m]\n | even m = take n.cycle.take m.map(mid+) $ 0:concatMap(\\i->[i,-i])[1..]\n | otherwise = take n.cycle.take m.map(mid+) $ 0:concatMap(\\i->[-i,i])[1..]\n where mid = div (m+1) 2\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\nimport Data.Function\nimport Data.Array\n\nmain' a b = f a 0\n where\n f 0 _ = []\n f a c\n | c == b = (g 0) : f (a-1) 1\n | otherwise = (g c) : f (a-1) (c+1)\n r = listArray (0,b-1)$ (sortBy(compare`on`snd)$map(\\i->(i,abs$(intToFlt(b+1)/2.0)-intToFlt i))[1..b])\n g c = fst$ r!c\n\n\nintToFlt = fromInteger.toInteger\n\nmain = putStrLn=<main' a b).map read.words<$>getLine\n"}, {"source_code": "zipArr (x:xs) (y:ys) = x:y:zipArr xs ys\nzipArr x [] = x\nzipArr _ y = y\n\nmain = do\n d <- getContents\n let (n:m:_) = map read $ words d\n let k = m `div` 2\n let ord = if m `mod` 2 == 0\n then zipArr [k, k-1 .. 1] [k+1 .. m]\n\t else zipArr [k+1 .. m] [k, k-1 .. 1]\n let ans = take n $ concat $ repeat ord \n putStr $ unlines $ map show ans\n \t\t\t \t \t \t\t\t \t\t \t \t\t"}, {"source_code": "import Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map read . words) getLine\n let f i = (abs $ 1 + m - 2 * i, i)\n putStr $ unlines $ map show $ take n $ cycle $ sortBy (comparing f) $ [1 .. m]\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map read . words) getLine\n let c = (m + 1) `div` 2\n f i = (abs $ i - c , i)\n putStr $ unlines $ map show $ take n $ cycle $ sortBy (comparing f) $ [1 .. m]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n\n let\n c = (m+1) `div` 2\n r = [c] ++ reverse [1..c-1] ++ [c+1..m]\n\n putStr $ unlines $ map show $ take n $ concat $ repeat r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n\n let\n c = (m+1) `div` 2\n r = [c] ++ merge (reverse [1..c-1]) [c+1..m]\n where\n merge as [] = as\n merge [] bs = bs\n merge (a:as) (b:bs) = a:b:(merge as bs)\n\n putStr $ unlines $ map show $ take n $ concat $ repeat r\n"}, {"source_code": "\nsolve :: Int -> [Int]\nsolve n\n | odd n = cycle $ take n $ solveR (div n 2) (div n 2 + 1)\n | otherwise = solveL (div n 2) (div n 2 + 1)\n where\n solveL l r\n | l == 1 = l : solveR (div n 2) r\n | otherwise = l : solveR (l - 1) r\n solveR l r \n | r == n = r : solveL l (div n 2 + 1)\n | otherwise = r : solveL l (r + 1)\n\nmain :: IO ()\nmain = do\n [n, m] <- getLine >>= return . map read . words\n mapM_ print $ take m (solve n) \n"}], "src_uid": "907893a0a78a7444d26bdd793d9c7499"} {"source_code": "checkX :: String -> Int -> [Bool]\ncheckX [] t = replicate t True\ncheckX s t = map (\\(x, y) -> (x && y)) (zip (map (=='X') cur) (checkX rest t))\n where\n (cur, rest) = splitAt t s\n\nhandle :: String -> [String]\nhandle str = [show $ length res] ++ res\n where\n handle_i :: Int -> [String]\n handle_i 13 = []\n handle_i i = if 12 `mod` a == 0 && (or $ checkX str b) then ((show a) ++ \"x\" ++ (show b)) : rest else rest\n where\n a = i\n b = 12 `div` i\n rest = handle_i (i + 1)\n \n res = handle_i 1\n\nhandleAllCase :: Int -> IO ()\nhandleAllCase 0 = return ()\nhandleAllCase n = do\n str <- getLine\n putStrLn $ unwords $ handle str\n handleAllCase (n - 1)\n\nmain :: IO ()\nmain = do\n sNCases <- getLine\n handleAllCase $ read sNCases\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n k <- readLn\n ss <- replicateM k getLine\n\n let\n solve s = filter check [(a, b) | a <- [1..12], b <- [1..12], a*b == 12]\n where\n check (a, b) = any (all (== 'X')) $ transpose ls\n where\n ls = unfoldr (\\s -> if null s then Nothing else Just $ splitAt b s) s\n\n p as = unwords $ (show $ length as):(map (\\(a, b) -> show a ++ \"x\" ++ show b) as)\n\n putStrLn $ unlines $ map p $ map solve ss\n"}, {"source_code": "\nimport Control.Monad (replicateM_)\nimport Data.List (intercalate)\n\nwin :: String -> Int -> Bool\nwin s a = any allxs [0..b-1]\n where b = length s `div` a\n allxs c = all (\\r -> (s !! (r*b+c)) == 'X') [0..a-1]\n\nsolve s = map (\\a -> let b = length s `div` a in show a ++ \"x\" ++ show b) ws\n where ws = concatMap (\\a -> if win s a then [a] else []) [1,2,3,4,6,12]\n\nmain = do\n t <- read `fmap` getLine :: IO Int\n replicateM_ t $ do\n game <- getLine\n let w = solve game\n putStrLn $ show (length w) ++ \" \" ++ (intercalate \" \" w)\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n s <- getLine\n let l = [ (a,b) | a <- [1,2,3,4,6,12], let b = 12 `div` a, win a b s]\n putStrLn $ unwords $show (length l):[printf \"%dx%d\" a b | (a,b) <- l]\n\nwin :: Int -> Int -> String -> Bool\nwin a b = any (==take a (repeat 'X')).transpose . takeBy b \n\ntakeBy b [] = []\ntakeBy b l = let (l1,l2) = splitAt b l in l1:takeBy b l2\n"}, {"source_code": "import Control.Applicative\nimport Data.List (sort, groupBy)\n\nsolve :: String -> [(Int, Int)]\nsolve pattern =\n sort [(12 `div` b, b) | b <- bmatches]\n where\n zipped b = zip (cycle [1..b]) pattern\n groupings = groupBy (\\x -> \\y -> fst x == fst y) . sort\n ismatch = any (all (\\x -> snd x == 'X'))\n bmatches = filter (ismatch . groupings . zipped) [b | b <- [1..12], 12 `mod` b == 0]\n\nshowSoln :: [(Int, Int)] -> String\nshowSoln x = unwords $ show (length x):map (\\(a,b) -> (show a) ++ \"x\" ++ (show b)) x\n\nmain = do\n (_:patterns) <- lines <$> getContents\n putStrLn $ unlines $ map (showSoln . solve) patterns\n"}, {"source_code": "main = do\n getLine\n interact $ solve.lines\n\nsolve [] = \"\"\nsolve (x:xs) = show(length(res x))++\" \"++unwords(res x) ++\"\\n\"++solve (xs)\nres x = [show(i)++\"x\"++show(12`div`i)|i<-[1,2,3,4,6,12],p (z x (12`div`i)) i]\nz x i = [x!!j|r<-[0..i-1],j<-[0..11],j`mod`i==r]\np [] _ = False\np x i \n |take i x==replicate i 'X' = True\n |otherwise = p (drop i x) i"}], "negative_code": [], "src_uid": "b669a42ff477a62ec02dcfb87e1e60bd"} {"source_code": "split :: String -> [Int]\nsplit = map read.words\n \nhelperSecond :: [Int] -> Int -> Int -> Int\nhelperSecond a pos n\n | pos < (n - 1) && head a >= tail a !! 0 = helperSecond (tail a) (pos + 1) n \n | otherwise = n - pos - 1\n \nhelperFirst :: [Int] -> Int -> Int -> Int\nhelperFirst a pos n\n | pos < (n - 1) && head a <= tail a !! 0 = helperFirst (tail a) (pos + 1) n\n | otherwise = helperSecond a pos n\n \nfindShort :: [Int] -> Int -> Int\nfindShort a n = helperFirst (reverse a) 0 n\n \nsolve :: Int -> IO()\nsolve t \n | t > 0 = do\n n <- getLine\n a <- getLine\n print $ findShort (split a) (split n !! 0) \n solve (t - 1)\n | t == 0 = putStr \"\"\n \nmain :: IO()\nmain = do \n t <- getLine\n solve $ split t !! 0", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nsolve xs = length prefix\n where\n rest = dropWhile2 (<=) (reverse xs) True\n prefix = dropWhile2 (>=) rest True\n\ndropWhile2 f [x1, x2] b\n | f x1 x2 = []\n | b = [x2]\n | otherwise = [x1, x2]\ndropWhile2 f xxs @ (x1:x2:xs) b\n | f x1 x2 = dropWhile2 f (x2 : xs) True\n | b = x2 : xs\n | otherwise = xxs\n where\ndropWhile2 _ _ _ = []\n\ngetTest :: IO [Int]\ngetTest = do\n _ <- getLine\n r <- getLine\n let\n r' = map read $ words r\n return r'\n\nmain :: IO ()\nmain = do\n n <- getLine\n let n' = (read n :: Int)\n tests <- replicateM n' getTest\n mapM_ (print . solve) tests\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind, nsch) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\ndata Signs = Inc | Dec | Same deriving (Ord, Eq, Show)\n\nisGood1 :: [Integer] -> (Bool, Integer, Integer)\nisGood1 [x] = (True, 1, 0)\nisGood1 lz = let --stop = length lz - 1\n -- To determine whether inc or dec\n rl = reverse lz\n (_,_,nsch,ind,_) = foldr (\\cur t@(prev, sgn, nsch, ind, val) ->\n if nsch >= 2 then t\n -- case compare cur val of\n -- EQ -> (cur, sgn, nsch, ind+1, val)\n -- _ -> (cur, sgn, nsch, ind, -1)\n else\n case compare cur prev of\n EQ -> (cur, sgn, nsch, ind+1, -1)\n LT -> case sgn of\n Inc -> (cur, Dec, nsch+1, ind+1, -1)\n Dec -> (cur, Dec, nsch, ind+1, -1)\n Same -> (cur, Dec, nsch, ind+1, -1)\n GT -> case sgn of\n Inc -> (cur, Inc, nsch, ind+1, -1)\n Dec -> (cur, Dec, 2, ind, cur)\n Same -> (cur, Inc, nsch, ind+1, -1) )\n (last lz, Same, 0, 0, -1) lz\n -- (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n -- case inc of\n -- True -> --if ind == stop then (cur, False, True, if cur <= prev then ind else ind+1)\n -- {-else-} if cur >= prev\n -- then (cur, True, False, ind+1)\n -- else (cur, False, False, ind+1)\n -- False -> --if ind == stop then (cur, False, True, if cur >= prev then ind else ind+1)\n -- {-else-} if cur <= prev\n -- then (cur, False, False, ind+1)\n -- else (cur, False, True , ind)\n -- else (prev, inc, res, ind))\n -- (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (True, toInteger ind, toInteger nsch)\n\n\n"}, {"source_code": "import Control.Monad ( replicateM_ )\n\n\ndropWhile' :: Ord a => (a -> a -> Bool) -> [a] -> [a]\ndropWhile' f xs@(x1 : x2 : xr)\n | f x1 x2 = dropWhile' f (x2 : xr)\n | otherwise = xs\ndropWhile' _ xs = xs\n\n\nmakeItGud :: [Integer] -> Int\nmakeItGud = length . tail . dropWhile' (>=) . dropWhile' (<=) . reverse\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ getLine >> getLine >>= solve\n where\n solve = print . makeItGud . map read . words\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\n\nisGood1 :: [Integer] -> (Bool, Integer)\nisGood1 [x] = (True, 1)\nisGood1 lz = let stop = length lz - 1\n (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n case inc of\n True -> if ind == stop then (cur, False, True, ind)\n else if cur >= prev\n then (cur, True, False, ind+1)\n else (cur, False, False, ind+1)\n False -> if ind == stop then (cur, False, True, if cur > prev then ind else ind+1)\n else if cur <= prev\n then (cur, False, False, ind+1)\n else (cur, False, True , ind)\n else (prev, inc, res, ind))\n (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (res, toInteger ind)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\n\nisGood1 :: [Integer] -> (Bool, Integer)\nisGood1 [x] = (True, 0)\nisGood1 lz = let stop = length lz - 1\n (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n case inc of\n True -> if ind == stop then (cur, False, True, ind+1)\n else if cur >= prev\n then (cur, True, False, ind+1)\n else (cur, False, False, ind+1)\n False -> if ind == stop then (cur, False, True, ind+1)\n else if cur <= prev\n then (cur, False, False, ind+1)\n else (cur, False, True , ind)\n else (prev, inc, res, ind))\n (0, True, False, 0) lz\n in (res, toInteger ind)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind, nsch) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\ndata Signs = Inc | Dec | Same deriving (Ord, Eq, Show)\n\nisGood1 :: [Integer] -> (Bool, Integer, Integer)\nisGood1 [x] = (True, 1, 0)\nisGood1 lz = let --stop = length lz - 1\n -- To determine whether inc or dec\n rl = reverse lz\n (_,_,nsch,ind) = foldr (\\cur t@(prev, sgn, nsch, ind) ->\n if nsch > 1 then\n case compare cur prev of\n EQ -> (prev, sgn, nsch, ind+1)\n _ -> t\n else\n case compare cur prev of\n EQ -> (cur, sgn, nsch, ind+1)\n LT -> case sgn of\n Inc -> (cur, Dec, nsch+1, ind+1)\n Dec -> (cur, Dec, nsch, ind+1)\n Same -> (cur, Dec, nsch, ind+1)\n GT -> case sgn of\n Inc -> (cur, Inc, nsch, ind+1)\n Dec -> (cur, Dec, nsch+1, ind)\n Same -> (cur, Inc, nsch, ind+1) )\n (last lz, Same, 0, 0) lz\n -- (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n -- case inc of\n -- True -> --if ind == stop then (cur, False, True, if cur <= prev then ind else ind+1)\n -- {-else-} if cur >= prev\n -- then (cur, True, False, ind+1)\n -- else (cur, False, False, ind+1)\n -- False -> --if ind == stop then (cur, False, True, if cur >= prev then ind else ind+1)\n -- {-else-} if cur <= prev\n -- then (cur, False, False, ind+1)\n -- else (cur, False, True , ind)\n -- else (prev, inc, res, ind))\n -- (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (True, toInteger ind, toInteger nsch)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind, nsch) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\ndata Signs = Inc | Dec | Same deriving (Ord, Eq, Show)\n\nisGood1 :: [Integer] -> (Bool, Integer, Integer)\nisGood1 [x] = (True, 1, 0)\nisGood1 lz = let --stop = length lz - 1\n -- To determine whether inc or dec\n rl = reverse lz\n (_,_,nsch,ind) = foldr (\\cur t@(prev, sgn, nsch, ind) ->\n if nsch > 1 then\n case compare cur prev of\n EQ -> (prev, sgn, nsch, ind+1)\n _ -> t\n else\n case compare cur prev of\n EQ -> (cur, sgn, nsch, ind+1)\n LT -> case sgn of\n Inc -> (cur, Dec, nsch+1, ind+1)\n Dec -> (cur, Dec, nsch, ind+1)\n Same -> (cur, Dec, nsch, ind+1)\n GT -> case sgn of\n Inc -> (cur, Inc, nsch, ind+1)\n Dec -> (cur, Dec, 2, ind)\n Same -> (cur, Inc, nsch, ind+1) )\n (last lz, Same, 0, 0) lz\n -- (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n -- case inc of\n -- True -> --if ind == stop then (cur, False, True, if cur <= prev then ind else ind+1)\n -- {-else-} if cur >= prev\n -- then (cur, True, False, ind+1)\n -- else (cur, False, False, ind+1)\n -- False -> --if ind == stop then (cur, False, True, if cur >= prev then ind else ind+1)\n -- {-else-} if cur <= prev\n -- then (cur, False, False, ind+1)\n -- else (cur, False, True , ind)\n -- else (prev, inc, res, ind))\n -- (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (True, toInteger ind, toInteger nsch)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\n\nisGood1 :: [Integer] -> (Bool, Integer)\nisGood1 [x] = (True, 1)\nisGood1 lz = let stop = length lz - 1\n (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n case inc of\n True -> if ind == stop then (cur, False, True, ind+1)\n else if cur >= prev\n then (cur, True, False, ind+1)\n else (cur, False, False, ind+1)\n False -> if ind == stop then (cur, False, True, ind+1)\n else if cur <= prev\n then (cur, False, False, ind+1)\n else (cur, False, True , ind)\n else (prev, inc, res, ind))\n (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (res, toInteger ind)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\n\nisGood1 :: [Integer] -> (Bool, Integer)\nisGood1 [x] = (True, 1)\nisGood1 lz = let stop = length lz - 1\n (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n case inc of\n True -> if ind == stop then (cur, False, True, ind+1)\n else if cur >= prev\n then (cur, True, False, ind+1)\n else (cur, False, False, ind+1)\n False -> if ind == stop then (cur, False, True, ind+1)\n else if cur <= prev\n then (cur, False, False, ind+1)\n else (cur, False, True , ind)\n else (prev, inc, res, ind))\n (0, True, False, 0) lz\n in (res, toInteger ind)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\n\nisGood1 :: [Integer] -> (Bool, Integer)\nisGood1 [x] = (True, 1)\nisGood1 lz = let stop = length lz - 1\n (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n case inc of\n True -> if ind == stop then (cur, False, True, ind)\n else if cur >= prev\n then (cur, True, False, ind+1)\n else (cur, False, False, ind+1)\n False -> if ind == stop then (cur, False, True, ind)\n else if cur <= prev\n then (cur, False, False, ind+1)\n else (cur, False, True , ind)\n else (prev, inc, res, ind))\n (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (res, toInteger ind)\n\n\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Monad\nimport System.IO\n\nmain = do\n n <- getLine\n let nn = read n :: Int\n replicateM_ nn input\n\ninput :: IO ()\ninput = do\n hSetBuffering stdin LineBuffering\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n) (s)\n\nsolve :: Integer -> String -> String\nsolve n str =\n let\n nn = n\n ln = map read $ words str :: [Integer]\n (res, ind) = isGood1 (ln)\n in if res then show $ n - ind else show \"-1\"\n -- go :: Integer -> [Integer] -> Integer\n -- go _ [] = nn\n -- go c xs = if (not $ isGood xs (reverse xs) 0 (length xs) False) then (nn - c) else go (c-1) (tail xs)\n -- go c xs = if isGood1 xs then (nn - c) else go (c-1) (tail xs)\n -- in show $ go nn ln\n\n\n-- isGood :: [Integer] -> [Integer] -> Integer -> Int -> Bool -> Bool\n-- isGood _ _ _ 0 b = b\n-- isGood _ [] _ _ b = b\n-- isGood [] _ _ _ b = b\n-- isGood [x] _ _ _ b = b\n-- isGood l@(x:xs) ll@(y:ys) cl c False = case compare x y of\n-- GT ->\n-- if y >= cl then isGood l ys y (c - 1) False\n-- else True\n-- _ -> if x >= cl then isGood xs (ll) x (c - 1) False\n-- else True\n\nisGood1 :: [Integer] -> (Bool, Integer)\nisGood1 [x] = (True, 1)\nisGood1 lz = let stop = length lz - 1\n (_, _, res, ind) = foldr (\\cur (prev, inc, res, ind) -> if not res then\n case inc of\n True -> --if ind == stop then (cur, False, True, if cur <= prev then ind else ind+1)\n {-else-} if cur >= prev\n then (cur, True, False, ind+1)\n else (cur, False, False, ind+1)\n False -> --if ind == stop then (cur, False, True, if cur >= prev then ind else ind+1)\n {-else-} if cur <= prev\n then (cur, False, False, ind+1)\n else (cur, False, True , ind)\n else (prev, inc, res, ind))\n (if last lz >= last(init(lz)) then (last lz, False, False, 0) else (0, True, False, 0)) lz\n in (True, toInteger ind)\n\n\n"}], "src_uid": "731b45747081a800fc6da02efa5ce8cd"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- sort <$> getIntList\n let\n half = n `div` 2\n (lHalf, rHalf) = splitAt half a\n revLHalf = reverse lHalf\n printList $ combine revLHalf rHalf 1\n\ncombine :: [Int] -> [Int] -> Int -> [Int]\ncombine [] [] _ = []\ncombine [] ys _ = ys\ncombine xs [] _ = xs\ncombine (x:xs) (y:ys) z = case z of\n 0 -> x : combine xs (y:ys) (1 - z)\n 1 -> y : combine (x:xs) ys (1 - z)", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_\n t\n (getLine >> getLine >>=\n putStrLn . unwords . map show . solve . map read . words)\n\nf :: [a] -> [a] -> [a]\nf [] _ = []\nf (a:as) b = a : f b as\n\nsolve :: [Int] -> [Int]\nsolve l = f b (reverse a)\n where\n (a, b) = splitAt (length l `div` 2) (sort l)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- sort <$> getIntList\n let\n half = n `div` 2\n (lHalf, rHalf) = splitAt half a\n revLHalf = reverse rHalf\n printList $ combine revLHalf rHalf 1\n\ncombine :: [Int] -> [Int] -> Int -> [Int]\ncombine [] [] _ = []\ncombine [] ys _ = ys\ncombine xs [] _ = xs\ncombine (x:xs) (y:ys) z = case z of\n 0 -> x : combine xs (y:ys) (1 - z)\n 1 -> y : combine (x:xs) ys (1 - z)"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- sort <$> getIntList\n let\n half = n `div` 2\n (lHalf, rHalf) = splitAt half a\n revLHalf = reverse lHalf\n printList $ combine revLHalf rHalf 0\n\ncombine :: [Int] -> [Int] -> Int -> [Int]\ncombine [] [] _ = []\ncombine [] ys _ = ys\ncombine xs [] _ = xs\ncombine (x:xs) (y:ys) z = case z of\n 0 -> x : combine xs (y:ys) (1 - z)\n 1 -> y : combine (x:xs) ys (1 - z)"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- sort <$> getIntList\n let\n half = n `div` 2\n (lHalf, rHalf) = splitAt half a\n revLHalf = reverse lHalf\n print half\n printList revLHalf\n printList rHalf\n printList $ combine revLHalf rHalf 0\n\ncombine :: [Int] -> [Int] -> Int -> [Int]\ncombine [] [] _ = []\ncombine [] ys _ = ys\ncombine xs [] _ = xs\ncombine (x:xs) (y:ys) z = case z of\n 0 -> x : combine xs (y:ys) (1 - z)\n 1 -> y : combine (x:xs) ys (1 - z)"}], "src_uid": "3c8bfd3199a9435cfbdee1daaacbd1b3"} {"source_code": "calculate :: Integer -> Integer -> Integer -> Integer\ncalculate n x t \n | (n >= div t x) = (div t x) * n - (div t x * (div t x + 1)) `div` 2\n | otherwise = ((n-1) * n) `div` 2\n\n\nmain = do\n int <- getLine\n let n = read int::Integer\n repeat n\n where\n repeat 0 = return ()\n repeat m = do\n line <- getLine\n let input = map (\\x -> read x::Integer) $ words line\n putStrLn $ show $ calculate (input!!0) (input!!1) (input!!2)\n repeat $ m-1", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified System.IO as Io\n--import Data.IntSet \n\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [n, x, t] = map read $ words s :: [Integer]\n mx = min (div t x) (n-1)\n res = div (mx*(mx+1)) 2 + mx * (n - mx - 1)\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintResult = do\r\n [n,x,t] <- readInts\r\n let m = div t x\r\n if m == 0 then print 0\r\n else print $ if n >= m + 1 then div ((m+1)*m) 2 + m*(n-m-1) else div (n*(n-1)) 2\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintS = do \r\n [n,x,t] <- readInts\r\n let m = div (n*x-t) x + if (div (n*x-t) x > 0) then 1 else 0\r\n mm = if m < 0 then 0 else m\r\n s = if mm>1 then (mm-1)*(div t x) else 0 \r\n a = if mm == 0 then 1 else mm\r\n ret = s + (div ((n-a)*(n-a+1)) 2)\r\n print ret\r\n \r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t printS"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified System.IO as Io\n--import Data.IntSet \n\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [n, x, t] = map read $ words s :: [Integer]\n mx = div t x\n res = div (mx*(mx+1)) 2 + mx * (n - mx - 1)\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified System.IO as Io\n--import Data.IntSet \n\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [n, x, t] = map read $ words s :: [Int64]\n mx = div t x\n res = div (mx*(mx+1)) 2 + mx * (n - mx - 1)\n in print res\n\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "calculate :: Int -> Int -> Int -> Int\ncalculate n x t \n | (n >= div t x) = (div t x) * n - (div t x * (div t x + 1)) `div` 2\n | otherwise = ((n-1) * n) `div` 2\n\n\nmain = do\n int <- getLine\n let n = read int::Int\n repeat n\n where\n repeat 0 = return ()\n repeat m = do\n line <- getLine\n let input = map (\\x -> read x::Int) $ words line\n putStrLn $ show $ calculate (input!!0) (input!!1) (input!!2)\n repeat $ m-1"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n [n,x,t] <- readInts\r\n let m = div t x\r\n if m == 0 then print 0\r\n else print $ if n >= m + 1 then div ((m+1)*m) 2 + m*(n-m-1) else div (n*(n-1)) 2\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "src_uid": "4df38c9b42b0f0963a121829080d3571"} {"source_code": "import Data.List\nimport Data.Int\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n \n let mapped = map (map (read :: (String -> Int64)) . words) contents\n res = foldl (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd res <$> head mapped\n ans = max a b\n print $ if ans == 1 then -1 else ans", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n\n let mapped = map (map (read :: (String -> Int64)) . words) contents\n res = foldl' (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd res <$> head mapped\n ans = max a b\n print $ if ans == 1 then -1 else ans"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n\n let mapped = map (map (read :: (String -> Int64)) . words) contents\n res = foldr (\\[a, b] y -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd res <$> head mapped\n ans = max a b\n print $ if ans == 1 then -1 else ans"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n let mapped = map (map (read :: (String -> Int)) . words) contents\n res = foldl' (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd (factor res) <$> head mapped\n ans = max a b\n print (if ans == 1 then -1 else ans)"}, {"source_code": "import Data.List\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n let mapped = map (map (read :: (String -> Int)) . words) contents\n res = foldl' (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd (factor res) <$> head mapped\n ans = max a b\n print (if ans == 1 then -1 else ans)"}, {"source_code": "import Data.List\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n let mapped = map (map (read :: (String -> Int)) . words) contents\n res = foldr (\\[a, b] y -> gcd y (a * b)) 0 mapped\n g = factor res\n ([a, b]) = factor . gcd g <$> head mapped\n ans = max a b\n print (if ans == 1 then -1 else ans)"}, {"source_code": "import Data.List\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n let mapped = map (map (read :: (String -> Int)) . words) contents\n res = foldr (\\[a, b] y -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd (factor res) <$> head mapped\n ans = max a b\n print (if ans == 1 then -1 else ans)"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n -- hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n print \"Here\"\n let mapped = map (map (read :: (String -> Int64)) . words) contents\n res = foldl' (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd (factor res) <$> head mapped\n ans = max a b\n print (if ans == 1 then -1 else ans)"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n -- hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n -- print \"Here\"\n let mapped = map (map (read :: (String -> Int64)) . words) contents\n res = foldl (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd res <$> head mapped\n ans = max a b \n print ans"}, {"source_code": "import Data.List\nimport Data.Array\nimport System.IO\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- drop 1 . lines <$> getContents\n let mapped = map (map (read :: (String -> Int)) . words) contents\n res = foldl (\\y [a, b] -> gcd y (a * b)) 0 mapped\n [a, b] = factor . gcd (factor res) <$> head mapped\n ans = max a b\n print (if ans == 1 then -1 else ans)"}], "src_uid": "aba6e64e040952b88e7dcb95e4472e56"} {"source_code": "import Control.Monad (foldM)\n\n\nmain :: IO ()\nmain = do\n n <- getLine\n \n case foldM f ([], []) (zip n [1..]) of\n Just (zs, []) -> do\n print (length zs)\n mapM_ (\\xs -> putStrLn (unwords $ map show $ length xs : reverse xs)) zs\n _ -> print (-1)\n \nf :: ([[Int]], [[Int]]) -> (Char, Int) -> Maybe ([[Int]], [[Int]])\nf (zs, []) ('0', i) = Just ([i] : zs, [])\nf (zs, o:os) ('0', i) = Just ((i : o) : zs, os)\nf (z:zs, os) ('1', i) = Just (zs, (i : z) : os)\nf _ _ = Nothing", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n inp <- getLine\n let (ans, bns) = genPairs inp\n if not (null bns)\n then print (-1)\n else do\n let l = length ans\n let sans = (map . map) show ans\n print l\n forM_ sans $ \\s -> do\n putStr (show (length s) ++ \" \")\n putStrLn . unwords . reverse $ s\n\n-- completeted, not\ngenPairs :: String -> ([[Int]],[[Int]])\ngenPairs = maybe ([], [[1]]) id . foldl g (Just ([], [])) . zip [1..]\n where\n g :: Maybe ([[Int]], [[Int]]) -> (Int, Char) -> Maybe ([[Int]], [[Int]])\n g m x = m >>= flip f x\n f :: ([[Int]], [[Int]]) -> (Int, Char) -> Maybe ([[Int]], [[Int]])\n f (ha:a, b) (ix, '1') = Just (a, (ix:ha):b)\n f (a, hb:b) (ix, '0') = Just ((ix:hb):a, b)\n f ([], b) (ix, '1') = Nothing\n f (a, []) (ix, '0') = Just ([ix]:a, [])\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n inp <- getLine\n let (ans, bns) = genPairs inp\n if not (null bns)\n then print (-1)\n else do\n let l = length ans\n let sans = (map . map) show ans\n print l\n forM_ sans $ \\s -> do\n putStr (show (length s) ++ \" \")\n putStrLn . unwords . reverse $ s\n\n-- completeted, not\ngenPairs :: String -> ([[Int]],[[Int]])\ngenPairs = foldl f ([], []) . zip [1..]\n where\n f :: ([[Int]], [[Int]]) -> (Int, Char) -> ([[Int]], [[Int]])\n f (ha:a, b) (ix, '1') = (a, (ix:ha):b)\n f (a, hb:b) (ix, '0') = ((ix:hb):a, b)\n f ([], b) (ix, '1') = ([], [ix]:b)\n f (a, []) (ix, '0') = ([ix]:a, [])\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n inp <- getLine\n let (ans, bns) = genPairs inp\n print ans\n if not (null bns)\n then print (-1)\n else do\n let l = length ans\n let sans = (map . map) show ans\n print l\n forM_ sans $ \\s -> do\n putStrLn . unwords . reverse $ s\n\n-- completeted, not\ngenPairs :: String -> ([[Int]],[[Int]])\ngenPairs = foldl f ([], []) . zip [1..]\n where\n f :: ([[Int]], [[Int]]) -> (Int, Char) -> ([[Int]], [[Int]])\n f (ha:a, b) (ix, '1') = (a, (ix:ha):b)\n f (a, hb:b) (ix, '0') = ((ix:hb):a, b)\n f ([], b) (ix, '1') = ([], [ix]:b)\n f (a, []) (ix, '0') = ([ix]:a, [])\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n inp <- getLine\n let (ans, bns) = genPairs inp\n if not (null bns)\n then print (-1)\n else do\n let l = length ans\n let sans = (map . map) show ans\n print l\n forM_ sans $ \\s -> do\n putStrLn . unwords . reverse $ s\n\n-- completeted, not\ngenPairs :: String -> ([[Int]],[[Int]])\ngenPairs = foldl f ([], []) . zip [1..]\n where\n f :: ([[Int]], [[Int]]) -> (Int, Char) -> ([[Int]], [[Int]])\n f (ha:a, b) (ix, '1') = (a, (ix:ha):b)\n f (a, hb:b) (ix, '0') = ((ix:hb):a, b)\n f ([], b) (ix, '1') = ([], [ix]:b)\n f (a, []) (ix, '0') = ([ix]:a, [])\n"}], "src_uid": "37b34461876af7f2e845417268b55ffa"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nshowB False = \"NO\"\r\nshowB True = \"YES\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[_n], xs] <- replicateM 2 ri\r\n return xs\r\n mapM_ (putStrLn.showB.solve) tcs\r\n\r\nsolve xs = all isConvertible . tail $ xs\r\n where\r\n p = head xs\r\n isConvertible x = (x >= p && x `mod` p == 0)\r\n", "positive_code": [{"source_code": "solve :: IO ()\r\nsolve = readInt <$> getLine >>= \\ n ->\r\n map readInt . words <$> getLine >>= \\(x:xs) ->\r\n putStrLn $ if all (\\i -> i `mod` x == 0) xs then \"YES\" else \"NO\"\r\n\r\nmain :: IO ()\r\nmain = \r\n let f 0 = return ()\r\n f t = solve >> f (t - 1)\r\n in readInt <$> getLine >>= f\r\n \r\nreadInt :: String -> Int\r\nreadInt = read"}, {"source_code": "solve :: IO ()\r\nsolve = readInt <$> getLine >>= \\ n ->\r\n map readInt . words <$> getLine >>= \\(x:xs) ->\r\n putStrLn . (\\v -> if v then \"YES\" else \"NO\") $\r\n all (\\i -> i `mod` x == 0) xs\r\n\r\nmain :: IO ()\r\nmain = \r\n let f 0 = return ()\r\n f t = solve >> f (t - 1)\r\n in readInt <$> getLine >>= f\r\n \r\nreadInt :: String -> Int\r\nreadInt = read"}, {"source_code": "import Debug.Trace\n\ntest (x:xs) = x : map ( `mod` x ) xs\n\n\nrec a = if (test a)== a then a else test a \n\nis_zero (x:xs) = sum xs == 0\n\nexec 0 = pure () \nexec t = do\n\tn <- read <$> getLine :: IO Int\n\ta <- (map read . words) <$> getLine :: IO [Integer]\n\t\n\tputStr $ if is_zero (rec a) then \"YES\" else \"NO\"\n\tputStr \"\\n\"\n\n\n\texec (t-1)\n\nmain = do \n\tt <- read <$> getLine :: IO Int\n\texec t\n\n"}], "negative_code": [{"source_code": "import Debug.Trace\ndiff n e a = [a!!i | i<-[0..e-1] ] ++ [ if a!!e - a!!(e-1) >= 0 then a!!e - a!!(e-1) else a!!e] ++ [a!!i | i<-[e+1..n-1] ]\n\n-- test _ _ a | trace (\"\\t\" ++ show a ) False = undefined\ntest _ 0 a = a \ntest n e a = test n (e-1) $ diff n e a \n\n\nrec n a = if (t n a)== a then a else test n (n-1) $ t n a\n\twhere\n\t\tt n a = test n (n-1) a\n\nis_zero (x:xs) = sum xs == 0\n\nexec 0 = pure () \nexec t = do\n\tn <- read <$> getLine :: IO Int\n\ta <- (map read . words) <$> getLine :: IO [Integer]\n\t\n\tputStr $ if is_zero (rec n a) then \"YES\" else \"NO\"\n\tputStr \"\\n\"\n\n\n\texec (t-1)\n\nmain = do \n\tt <- read <$> getLine :: IO Int\n\texec t\n\n"}, {"source_code": "import Debug.Trace\ndiff n e a = [a!!i | i<-[0..e-1] ] ++ [ if a!!e - a!!(e-1) >= 0 then a!!e - a!!(e-1) else a!!e] ++ [a!!i | i<-[e+1..n-1] ]\n\n-- test _ _ a | trace (\"\\t\" ++ show a ) False = undefined\ntest _ 0 a = a \ntest n e a = test n (e-1) $ diff n e a \n\n\nrec n a = if (t n a)== a then a else test n (n-1) $ t n a\n\twhere\n\t\tt n a = test n (n-1) a\n\nis_zero (x:xs) = sum xs == 0\n\nexec 0 = pure () \nexec t = do\n\tn <- read <$> getLine :: IO Int\n\ta <- (map read . words) <$> getLine :: IO [Int]\n\t\n\tputStr $ if is_zero (rec n a) then \"YES\" else \"NO\"\n\tputStr \"\\n\"\n\n\n\texec (t-1)\n\nmain = do \n\tt <- read <$> getLine :: IO Int\n\texec t\n\n"}], "src_uid": "1c597da89880e87ffe791dd6b9fb2ac7"} {"source_code": "-- problem: https://codeforces.com/contest/1644/problem/B\r\n-- origin: https://codeforces.com/contest/1644/submission/147286507\r\n\r\nimport Control.Monad.State (State, evalState, replicateM, state)\r\nimport Data.Bifunctor (Bifunctor (first))\r\nimport Data.Char (isDigit, isSpace)\r\nimport Data.List (permutations)\r\n\r\nisOk :: [Int] -> Bool\r\nisOk li@(a : b : c) = and $ zipWith3 (\\x y z -> x + y /= z) li (b : c) c\r\nisOk _ = error \"Wrong\"\r\n\r\ngetInt :: State [Char] Int\r\ngetInt = state (first (\\x -> read x :: Int) . span isDigit . dropWhile isSpace)\r\n\r\nputInts :: [Int] -> [Char]\r\nputInts [] = \"\\n\"\r\nputInts (x : xs) = show x ++ concatMap (\\y -> ' ' : show y) xs ++ \"\\n\"\r\n\r\nmainFunc :: State [Char] [[Char]]\r\nmainFunc = do\r\n t <- getInt\r\n replicateM t $ do\r\n n <- getInt\r\n let ans = filter isOk $ permutations [1 .. n]\r\n ans' = take n ans -- accelerate calculating\r\n pure $ concatMap putInts ans'\r\n\r\nmain :: IO ()\r\nmain = do\r\n inp <- getContents\r\n putStr $ concat $ evalState mainFunc inp\r\n", "positive_code": [{"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntype InType = Int\r\ntype OutType = [[Int]]\r\n\r\nsolve :: InType -> OutType\r\nsolve n = [go i n | i <- [0 .. n - 1]]\r\n where go i n = concat [[n - z + 1 | z <- [1 .. i]],\r\n [1],\r\n [n - z + 1 | z <- [i + 1 .. n - 1]]\r\n ]\r\n\r\nreceive :: [String] -> InType\r\nreceive [x] = read x :: Int\r\nreceive _ = error \"input error\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (unlines . map showArr . solve . receive) . chunksOf 1 . tail . lines\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n mapM_ (putStrLn . unwords . map show)\r\n [p ++ [1] ++ s | let r = [n,n-1..2], (p, s) <- zip (inits r) (tails r)]\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (permutations)\n\nantifib :: [Int] -> Bool\nantifib [] = True\nantifib [_] = True\nantifib [a, b] = True\nantifib (a : b : c : cs) = (a + b) /= c && antifib (b : c : cs)\n\nsolve :: Int -> [[Int]]\nsolve n = take n $ filter antifib $ permutations [1 .. n]\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n putStr $ unlines $ map (unwords . map show) (solve n)\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n let\r\n isOK li = and\r\n $ zipWith3 (\\x y z -> x + y /= z) li (tail li) (tail $ tail li)\r\n ans = take n $ filter isOK $ permutations [1..n]\r\n pure $ foldMap putInts ans\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [{"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = Int\r\ntype OutType = [[Int]]\r\n\r\nsolve :: InType -> OutType\r\nsolve n = [n .. 1] : [go i n | i <- [0 .. n - 2]]\r\n where go i n = concat [[n - z | z <- [0 .. i]],\r\n [1],\r\n [n - z | z <- [i + 1 .. n - 2]]\r\n ]\r\n\r\nreceive :: [String] -> InType\r\nreceive [x] = read x :: Int\r\nreceive _ = error \"input error\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showAnswer . solve . receive) . chunksOf 1 . tail . lines\r\n where showAnswer :: OutType -> String\r\n showAnswer [] = \"\"\r\n showAnswer (v : vs) = concat [concatMap (\\x -> show x ++ \" \") v, \"\\n\", showAnswer vs]\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n mapM_ (putStrLn . unwords . map show) $ case n of\r\n 1 -> [[1]]\r\n 2 -> [[1, 2], [2, 1]]\r\n _ -> [[n,n-1..1], [n,n-1..3] ++ [1,2]] ++\r\n [[1, 3] ++ p ++ [2] ++ s | let r = [4..n], (p, s) <- zip (inits r) (tails r)]\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}], "src_uid": "85f0621e6cd7fa233cdee8269310f141"} {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Data.Monoid as M\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input\n | not possible = \"No\\n\"\n | otherwise = \"Yes\\n\" ++ (printTable r c solutionTable) ++ \"\\n\"\n where\n asWords = words input\n rs:cs:tableWords = asWords\n c = read cs :: Int\n r = read rs :: Int\n table = parseTable r c tableWords\n solutionTable = makeSolutionTable table\n possible = M.getAll . mconcat $ map idxCan (A.indices table)\n idxCan :: (Int, Int) -> M.All\n idxCan idx = M.All $ (not isWolf) || (not hasSheepNeighbour)\n where\n curChar = table A.! idx\n isWolf = curChar == 'W'\n nextidx :: [(Int,Int)]\n nextidx = [(1,0),(-1,0),(0,1),(0,-1)]\n (cR,cC) = idx\n hasSheepNeighbour = M.getAny . mconcat $ anyB\n where\n okIdx :: [(Int,Int)]\n okIdx = filter (A.inRange $ A.bounds table) . map (\\(r,c) -> (r+cR, c+cC)) $ nextidx\n anyB :: [M.Any]\n anyB = map (\\cidx -> M.Any $ ((table A.! cidx) == 'S')) okIdx\n\nprintTable :: Int -> Int -> A.Array (Int,Int) Char -> String\nprintTable r c table = intercalate \"\\n\" . map printRow $ [0..(r-1)]\n where\n printRow :: Int -> String\n printRow rowNum = map (\\cc -> table A.! (rowNum, cc)) [0..(c-1)]\n\nparseTable :: Int -> Int -> [String] -> A.Array (Int,Int) Char\nparseTable r c tableWords = A.array ((0,0), (r-1,c-1)) indexList\n where\n indexList = convertWordsToIndexList 0 tableWords\n\nconvertWordsToIndexList :: Int -> [String] -> [((Int, Int), Char)]\nconvertWordsToIndexList _ [] = []\nconvertWordsToIndexList curRow wordsList = (drop 1 $ convertRow row) ++ (convertWordsToIndexList (curRow + 1) next)\n where\n row:next = wordsList\n convertRow = scanl scanner ((curRow, -1), ' ') :: String -> [((Int, Int), Char)]\n scanner :: ((Int, Int), Char) -> Char -> ((Int, Int), Char)\n scanner cidx curChar = ((curRow,curCol+1), curChar)\n where\n ((_,curCol),_) = cidx :: ((Int, Int), Char)\n\nmakeSolutionTable :: A.Array (Int,Int) Char -> A.Array (Int,Int) Char\nmakeSolutionTable sourceTable = A.array (A.bounds sourceTable) mappedList\n where\n indices = A.indices sourceTable\n mappedList = map mapNewIdx indices\n mapNewIdx idx\n | isDot && hasNeighbourWolf = (idx, 'D')\n | otherwise = (idx, curChar)\n where\n curChar = sourceTable A.! idx\n isDot = curChar == '.'\n (cR, cC) = idx\n hasNeighbourWolf = M.getAny . mconcat $ anyB\n where\n nextidx = [(1,0),(-1,0),(0,1),(0,-1)]\n okIdx = filter (A.inRange $ A.bounds sourceTable) . map (\\(r,c) -> (r+cR, c+cC)) $ nextidx\n anyB = map (\\cidx -> M.Any $ ((sourceTable A.! cidx) == 'W')) okIdx\n", "positive_code": [{"source_code": "import Data.List\n\nmain = getContents >>= putStr . solve . preProcess \n\npreProcess = tail . lines . map (\\x -> if x == '.' then 'D' else x)\n\nsolve a\n | exam a && exam (transpose a) = unlines $ \"Yes\" : a\n | otherwise = \"No\\n\"\n where exam = all isSafe\n isSafe [] = True\n isSafe ('W':'S':xs) = False\n isSafe ('S':'W':xs) = False\n isSafe (x:xs) = isSafe xs\n"}, {"source_code": "import Data.List\n\nmain = getContents >>= putStr . solve . preProcess \n\npreProcess = tail . lines . map (\\x -> if x == '.' then 'D' else x)\nsolve a\n | exam a && exam (transpose a) = unlines $ \"Yes\" : a\n | otherwise = \"No\\n\"\n where exam = all (\\xs -> not (isInfixOf \"WS\" xs || isInfixOf \"SW\" xs))\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nmain = interact exec\nexec = (\\(_:_:m) -> if all ok m && all ok (transpose m) then \"Yes\\n\" ++ unlines (map (map (\\case { '.' -> 'D'; x -> x })) m) else \"No\") . words\nok xs = not $ any (\\case {('W', 'S') -> True; ('S', 'W') -> True; _ -> False; }) $ zip xs (tail xs)"}], "negative_code": [], "src_uid": "f55c824d8db327e531499ced6c843102"} {"source_code": "\r\n{-# LANGUAGE BlockArguments, MultiWayIf #-}\r\n\r\nimport System.IO\r\n\r\nsolve iask n = iask 1 n >>= go 1 n\r\n where\r\n go l r lrmax\r\n | l == r = pure l\r\n | l == r - 1 = pure if lrmax == l then r else l\r\n | otherwise = do\r\n let\r\n m = (l + r) `div` 2\r\n lmmax <- iask l m\r\n mrmax <- iask m r\r\n if\r\n | lrmax == lmmax -> go l m lmmax\r\n | lrmax == mrmax -> go m r mrmax\r\n | lrmax > m -> go l m lmmax\r\n | lrmax < m -> go m r mrmax\r\n | otherwise -> undefined\r\n \r\nmain = do\r\n n <- readLn\r\n let\r\n iask l r = putStrLn (\"? \" <> show l <> \" \" <> show r) >> hFlush stdout >> readLn\r\n solve iask n >>= putStrLn . (\"! \" <>) . show \r\n ", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\n------\n\ngetInt = fst . fromJust . B.readInt . dropCR <$> B.getLine\n\nask l r = do\n B.putStrLn $ B.unwords [\"?\", bshow (l + 1), bshow r]\n hFlush stdout\n (subtract 1) <$> getInt\n\nanswer i = do\n B.putStrLn $ B.unwords [\"!\", bshow (i + 1)]\n hFlush stdout\n\nmain = do\n n <- getInt\n p <- ask 0 n\n let r = sortOn (\\(i, j) -> i - j) $\n filter (\\(i, j) -> i /= j) [(0, p), (p + 1, n)]\n case r of\n [(i, j)] -> go p i j\n [(i, j), (k, l)]\n | i < p -> do q <- ask i (p + 1)\n if p == q\n then go p i j\n else go p k l\n | otherwise -> do q <- ask p j\n if p == q\n then go p i j\n else go p k l\n\n\ngo p i j | i < p = lgo i j p\n | otherwise = rgo p i j\n\n\nlgo i j p | j - i == 1 = answer i\n | otherwise = let k = (i + j) `quot` 2 in\n do q <- ask k (p + 1)\n if p == q\n then lgo k j p\n else lgo i k p\n\n\nrgo p i j | j - i == 1 = answer i\n | otherwise = let k = (i + j) `quot` 2 in\n do q <- ask p k\n if p == q\n then rgo p i k\n else rgo p k j\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nboolInt :: Bool -> Int\nboolInt p = if p then 1 else 0\n\nquery :: Int -> Int -> SIO Int\nquery li ri = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (B.char7 '?' : map B.intDec [li, ri])\n in do\n lift $ B.hPutBuilder stdout outBuilder >> hFlush stdout\n [response] <- readInts\n pure response\n\ngo :: Int -> Int -> Int -> SIO Int\ngo v li ri = let\n mi = div (li + ri) 2\n in if li + boolInt (elem v [li, ri]) == ri\n then pure $ if v == li\n then ri\n else li\n else if v < li\n then do\n resp <- query v mi\n if resp == v\n then go v li mi\n else go v (mi+1) ri\n else if ri < v\n then do\n resp <- query (mi+1) v\n if resp == v\n then go v (mi+1) ri\n else go v li mi\n else do\n let\n innermi = mi + boolInt (v <= mi) - boolInt (even $ ri - li)\n lower = v <= innermi\n resp <- if lower then query li innermi else query (innermi+1) ri\n if (resp == v) == lower\n then go v li innermi\n else go v (innermi+1) ri\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n] <- readInts\n sndMin <- query 1 n\n ans <- go sndMin 1 n\n lift $ B.hPutBuilder stdout\n $ B.char7 '!' <> B.char7 ' ' <> B.intDec ans <> B.char7 '\\n'\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\n"}, {"source_code": "\r\n{-# LANGUAGE BlockArguments, MultiWayIf #-}\r\n\r\nimport System.IO\r\n\r\nsolve iask n = iask 1 n >>= go 1 n\r\n where\r\n go l r lrmax\r\n | l == r = pure l\r\n | l == r - 1 = pure if lrmax == l then r else l\r\n | otherwise = do\r\n let\r\n m = (l + r) `div` 2\r\n lmmax <- iask l m\r\n mrmax <- iask m r\r\n if\r\n | lrmax == lmmax -> go l m lmmax\r\n | lrmax == mrmax -> go m r mrmax\r\n | lrmax > m -> go l m lmmax\r\n | lrmax < m -> go m r mrmax\r\n | otherwise -> undefined\r\n \r\nmain = do\r\n n <- readLn\r\n let\r\n iask l r = putStrLn (\"? \" <> show l <> \" \" <> show r) >> hFlush stdout >> readLn\r\n solve iask n >>= putStrLn . (\"! \" <>) . show"}], "negative_code": [{"source_code": "{-# LANGUAGE BlockArguments, TypeApplications, MultiWayIf #-}\r\n\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\nimport System.IO\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- line1 @Int\r\n let\r\n go l r lrmax\r\n | l == r = ianswer [l]\r\n | l == r - 1 = ianswer [if lrmax == l then r else l]\r\n | otherwise = do\r\n let\r\n m = (l + r) `div` 2\r\n lmmax <- iask1 [l, m]\r\n mrmax <- iask1 [m, r]\r\n if\r\n | lrmax == lmmax -> go l m lmmax\r\n | lrmax == mrmax -> go m r mrmax\r\n | lrmax > m -> go l m lrmax\r\n | lrmax < m -> go m r mrmax\r\n i <- iask1 [1, n]\r\n go 1 n i\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nline1 :: Read a => IO a\r\nline1 = readLn\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n\r\niask :: (Read b, Show a) => [a] -> IO [b]\r\niask l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line\r\n\r\niask1 :: (Read b, Show a) => [a] -> IO b\r\niask1 l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line1\r\n\r\nianswer :: Show a => [a] -> IO ()\r\nianswer l = putStrLn (\"! \" <> unwords (fmap show l)) <> hFlush stdout\r\n"}, {"source_code": "{-# LANGUAGE BlockArguments, TypeApplications, MultiWayIf #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\nimport System.IO\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- line1\r\n let\r\n go l r lrmax\r\n | l == r = ianswer [l]\r\n | l == r - 1 = ianswer [if lrmax == l then r else l]\r\n | otherwise = do\r\n let\r\n m = (l + r) `div` 2\r\n m' = if l == r - 2 then m else m + 1\r\n lmmax <- iask1 [l, m]\r\n mrmax <- iask1 [m', r]\r\n if\r\n | lrmax == lmmax -> go l m lmmax\r\n | lrmax == mrmax -> go m' r mrmax\r\n | lrmax > m -> go l m lrmax\r\n | otherwise -> go m' r mrmax\r\n i <- iask1 [1, n]\r\n go 1 n i\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nline1 :: Read a => IO a\r\nline1 = readLn\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n\r\niask :: (Read b, Show a) => [a] -> IO [b]\r\niask l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line\r\n\r\niask1 :: (Read b, Show a) => [a] -> IO b\r\niask1 l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line1\r\n\r\nianswer :: Show a => [a] -> IO ()\r\nianswer l = putStrLn (\"! \" <> unwords (fmap show l)) <> hFlush stdout\r\n"}, {"source_code": "{-# LANGUAGE BlockArguments, TypeApplications, MultiWayIf #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\nimport System.IO\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- line1 @Int\r\n let\r\n go l r lrmax\r\n | l == r = ianswer [l]\r\n | l == r - 1 = ianswer [if lrmax == l then r else l]\r\n | otherwise = do\r\n let\r\n m = (l + r) `div` 2\r\n lmmax <- iask1 [l, m]\r\n mrmax <- iask1 [m, r]\r\n if\r\n | lrmax == lmmax -> go l m lmmax\r\n | lrmax == mrmax -> go m r mrmax\r\n | lrmax > m -> go l m lrmax\r\n | otherwise -> go m r mrmax\r\n i <- iask1 @Int [1, n]\r\n go 1 n i\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nline1 :: Read a => IO a\r\nline1 = readLn\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n\r\niask :: (Read b, Show a) => [a] -> IO [b]\r\niask l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line\r\n\r\niask1 :: (Read b, Show a) => [a] -> IO b\r\niask1 l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line1\r\n\r\nianswer :: Show a => [a] -> IO ()\r\nianswer l = putStrLn (\"! \" <> unwords (fmap show l)) <> hFlush stdout\r\n"}, {"source_code": "{-# LANGUAGE BlockArguments, TypeApplications, MultiWayIf #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nmodule Main ( main ) where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\nimport System.IO\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- line1 @Int\r\n let\r\n go l r lrmax\r\n | l == r = ianswer [l]\r\n | l == r - 1 = ianswer [if lrmax == l then r else l]\r\n | otherwise = do\r\n let\r\n m = (l + r) `div` 2\r\n lmmax <- iask1 [l, m]\r\n mrmax <- iask1 [m, r]\r\n if\r\n | lrmax == lmmax -> go l m lmmax\r\n | lrmax == mrmax -> go m r mrmax\r\n | lrmax >= m -> go l m lrmax\r\n | otherwise -> go m r mrmax\r\n i <- iask1 @Int [1, n]\r\n go 1 n i\r\n\r\n-- lib\r\n\r\nnCases :: IO a -> IO ()\r\nnCases m = do\r\n n <- readLn\r\n replicateM_ n m\r\n\r\nline :: Read a => IO [a]\r\nline = fmap read . words <$> getLine\r\n\r\nline1 :: Read a => IO a\r\nline1 = readLn\r\n\r\nputBool :: Bool -> IO ()\r\nputBool b = putStr if b then \"Yes\" else \"No\"\r\n\r\nputBoolLn :: Bool -> IO ()\r\nputBoolLn b = putStrLn if b then \"Yes\" else \"No\"\r\n\r\niask :: (Read b, Show a) => [a] -> IO [b]\r\niask l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line\r\n\r\niask1 :: (Read b, Show a) => [a] -> IO b\r\niask1 l = putStrLn (\"? \" <> unwords (fmap show l)) >> hFlush stdout >> line1\r\n\r\nianswer :: Show a => [a] -> IO ()\r\nianswer l = putStrLn (\"! \" <> unwords (fmap show l)) <> hFlush stdout\r\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\n------\n\ngetInt = fst . fromJust . B.readInt . dropCR <$> B.getLine\n\nask l r = do\n B.putStrLn $ B.unwords [\"?\", bshow (l + 1), bshow r]\n hFlush stdout\n (subtract 1) <$> getInt\n\nanswer i = do\n B.putStrLn $ B.unwords [\"!\", bshow (i + 1)]\n hFlush stdout\n\nmain = do\n n <- getInt\n p <- ask 0 n\n let r = sortOn (\\(i, j) -> i - j) $\n filter (\\(i, j) -> i /= j) [(0, p), (p + 1, n)]\n case r of\n [(i, j)] -> go p i j\n [(i, j), (k, l)]\n | i < p -> do q <- ask i (p + 1)\n if p == q\n then go p i j\n else go p k l\n | otherwise -> do q <- ask p l\n if p == q\n then go p k l\n else go p i j\n\n\ngo p i j | i < p = lgo i j p\n | otherwise = rgo p i j\n\n\nlgo i j p | j - i == 1 = answer i\n | otherwise = let k = (i + j) `quot` 2 in\n do q <- ask k (p + 1)\n if p == q\n then lgo k j p\n else lgo i k p\n\n\nrgo p i j | j - i == 1 = answer i\n | otherwise = let k = (i + j) `quot` 2 in\n do q <- ask p k\n if p == q\n then rgo p i k\n else rgo p k j\n"}], "src_uid": "b3e8fe76706ba17cb285c75459508334"} {"source_code": "module Main where\n f :: Int -> Int -> Int\n f 0 res = res\n f n res = f (n `div` 2) (res + 1)\n \n solve :: IO ()\n solve = do\n n <- getLine\n print $ 2 ^ ((f (read n :: Int) 0) - 1) - 1\n \n iter :: Int -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n q <- getLine\n iter (read q :: Int)", "positive_code": [{"source_code": "main=interact$unlines.map(show.(\\x->2^x-1).floor.logBase 2.read).tail.lines"}, {"source_code": "main = interact $ unlines . map (show . (\\x -> 2^x - 1) . floor . logBase 2 . fromIntegral . read) . tail . lines"}, {"source_code": "import Data.Bits\r\nmain = interact (unlines . map (\\x -> show ((\\y->2^y-1)(fn x 0))). tail . map g. lines) where g x = read x ::Int\r\n -- text <- readFile \"inputt.txt\" \r\n \r\n\r\nfn :: Int -> Int -> Int\r\nfn n acc = if ((==) n 1) then acc else fn (div n 2) ((+) acc 1)"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (getLine >>= print . pred . maxBit . read)\n\nmaxBit :: Int -> Int\nmaxBit 1 = 1\nmaxBit n = 2 * maxBit (quot n 2)\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: Int -> Int\r\nsolve n = subtract 1 $ last $ takeWhile (<= n) $ iterate (* 2) 1\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInt :: IO Int\ngetInt = fmap parseInt C.getLine\n\nmain :: IO ()\nmain = do\n t <- getInt\n result <- fmap mconcat $ replicateM t $ do\n n <- getInt\n return $ intDec (bit (finiteBitSize n - 1 - countLeadingZeros n) - 1) `mappend` charUtf8 '\\n' \n hPutBuilder stdout result\n"}], "negative_code": [], "src_uid": "9b4a8bc76d634935f6a1438e8a93a781"} {"source_code": "import Data.List\n\nmain::IO ()\nmain = \n do cs <- getContents\n (putStr.showSolve.solve.tail.lines) cs\n\nshowSolve ::(Int,Int)->String\nshowSolve (a,b) = show a ++ \" \" ++ show b\n\nfindAster::String->Bool\nfindAster s = findAster1 s 0\n\nfindAster1 :: String->Int->Bool\nfindAster1 [] i = (i == 1)\nfindAster1 (x:xs) i = \n if (x == '*' ) \n then findAster1 xs (i+1)\n else findAster1 xs i\n\ngetP ::[(Bool,Int)]->(Bool,Int)\ngetP [] = (False,0)\ngetP (x@(b,_):xs) = if b \n then x\n else getP xs\n\nsolve::[String]->(Int,Int)\nsolve s = (x,y)\n where\n (_,x) = getP $ zip (map findAster s) [1..]\n (_,y) = getP $ zip (map findAster $ transpose s) [1..]\n\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$f.drop 2.words\nf s=g s++\" \"++g(transpose s)\ng=show.(+1).head.findIndices((==\"*\").filter(=='*'))\n"}, {"source_code": "import Data.List\n\nmain = putStrLn . solve . drop 2 . words =<< getContents\nsolve s = f s ++ \" \" ++ f (transpose s)\nf = show . (+1) . head . elemIndices 1 . map (length . filter(=='*'))\n"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\nmain = do\n [r, c] <- fmap (map read . words) getLine\n a <- replicateM r getLine\n let b = [(i, j) | i <- [1 .. r], j <- [1 .. c], a!!(i-1)!!(j-1) == '*']\n f g = show $ foldl1 xor $ map g b\n in putStrLn $ unwords $ [f fst, f snd]\n"}, {"source_code": "\nsolve :: Int -> Int -> [String] -> (Int, Int)\nsolve n m lines = (notEq x1 x2 x3, notEq y1 y2 y3)\n where\n [(x1,y1),(x2,y2),(x3,y3)] = solve' 1 1 lines\n solve' _ _ [] = []\n solve' n _ (\"\" : xs) = solve' (n+1) 1 xs\n solve' n m (('*' : s) : xs) = (n,m) : solve' n (m+1) (s:xs)\n solve' n m ((_:s) : xs) = solve' n (m+1) (s:xs)\n notEq a b c\n | a == b = c\n | a == c = b\n | b == c = a\n | otherwise = error \":'(\" \n\nmain :: IO ()\nmain = do\n [n, m] <- getLine >>= return . map read . words\n lines <- mapM (const getLine) [1..n]\n let (a, b) = solve n m lines\n putStrLn $ concat [show a, \" \", show b]\n"}, {"source_code": "import Data.List\n\n\nf::Int->[String]->[(Int,Int)]\nf _ []=[]\nf y (str:strs)\n |'*' `elem` str=let xs=elemIndices '*' str\n in (zip xs (repeat y))++(f (y+1) strs)\n |otherwise=f (y+1) strs\n\nmain = do\n e<-getLine\n es<-getContents\n let ds=lines es\n xs=f 1 ds\n ans=nub [(show (y1))++\" \"++(show (x1+1))|(x1,_)<-xs,(_,y1)<-xs,(x1,y1) `notElem` xs]\n putStrLn $ head ans"}, {"source_code": "getClues rows =\n [(x, y) |\n (x, row) <- zip [1..] rows,\n (y, a) <- zip [1..] row,\n a == '*']\n\nupdateBounds ([minX, maxX], [minY, maxY]) (x, y) =\n ([min minX x, max maxX x],\n [min minY y, max maxY y])\n\ngetBounds clues = foldl updateBounds ([101, 0], [101, 0]) clues\n\nsolve board =\n let clues = getClues board\n (xs, ys) = getBounds clues\n in head [[x, y] |\n x <- xs,\n y <- ys,\n not $ elem (x, y) clues]\n\nmain = interact $ unwords . map show . solve . tail . lines"}, {"source_code": "process :: [[Char]] -> (Int,Int)\nprocess s\n | ax /= bx && ay /= by = (ax+bx-cx,ay+by-cy)\n | bx /= cx && by /= cy = (bx+cx-ax,by+cy-ay)\n | otherwise = (cx+ax-bx,cy+ay-by)\n where\n [(ax,ay),(bx,by),(cx,cy)] = concat $ zipWith f [1..] s\n f i xs = [(i,j) | j <- (g xs)]\n g = map fst . filter ((=='*').snd) . zip [1..]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n s <- fmap lines getContents\n let (r,c) = process s\n putStrLn $ show r ++ \" \" ++ show c"}], "negative_code": [], "src_uid": "e344de8280fb607c556671db9cfbaa9e"} {"source_code": "import Control.Monad\nimport Data.Int (Int64)\nimport Data.Sequence (Seq)\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Sequence as Seq\n\nf t | even t = 0\n | otherwise = 1\n\ngao :: (Int, Int) -> Int\ngao (x1, y1) = f x1 + f y1 * 2 + 1\n\nmain = do\n (n : _) <- fmap (map readInt . C.words) C.getLine\n putStrLn \"YES\"\n r <- replicateM n $ do\n (x1 : y1 : x2 : y2 : _) <- fmap (map readInt . C.words) C.getLine\n return (x1, y1)\n mapM putStrLn $ map show $ map gao r\n where\n readInt s = let Just (i, _) = C.readInt s in i", "positive_code": [{"source_code": "main = interact $ unlines . (\"YES\":) . map (show . (\\(a:b:_) -> a `mod` 2 + b `mod` 2 * 2 + 1) . map read) . filter ((==4) . length) . map words . lines\n"}], "negative_code": [{"source_code": "main = interact $ unlines . map (show . (\\(a:b:_) -> a `mod` 2 + b `mod` 2 * 2 + 1) . map read) . filter ((==4) . length) . map words . lines\n"}], "src_uid": "b6608fadf1677e5cb78b6ed092a23777"} {"source_code": "import Data.Graph\nimport Data.Array\nimport Control.Monad\n\nsolve n e\n | length kicked == 0 = 0\n | otherwise = solve n e' + 1\n where g = buildG (1, n) e\n kicked = [ i | i <- [1..n], indegree g ! i == 1 ]\n e' = (\\(x, y) -> not (elem x kicked || elem y kicked)) `filter` e\n\nmain = do\n [n, m] <- fmap (map read . words) getLine\n e <- fmap concat . forM [1..m] $ \\_ -> fmap ((\\[x,y] -> [(x,y),(y,x)]) . map read . words) getLine\n print $ solve n e\n\n\n-- vim: set expandtab:\n", "positive_code": [{"source_code": "import Data.List\nimport Debug.Trace (trace)\n\nmain2 = print $ solve [(1,2), (2,3), (3,4)]\n--main = print $ groupBy (\\(x,_) (y,_) -> x == y) [(1,2),(1,3),(3,4),(2,1),(3,2),(4,3)]\nmain = \n\tdo\n\t\t[n, m] <- getNums\n\t\tlines <- getLines m\n\t\tputStrLn $ show $ solve $ (lines |> map (tuple . getNumbers))\n\nsolve l = iterate (\\(r,n) -> getGroup r) (l,0) |> drop 1 |> takeWhile (\\(_,n) -> n > 0) |> length\n\ngetGroup l = (r, (length l) - (length r)) \n\twhere \n\t\tl2 = (l ++ (map swap l)) |> sort\n\t\tones = (groupBy (\\(x,_) (y,_) -> x == y) l2) |> filter (\\x -> length x == 1) |> map (fst . head)\n\t\tr = l |> filter (\\(x,y) -> ones |> any (\\z -> (z == x) || (z == y)) |> not)\n\nswap (x,y) = (y,x)\ntuple [x,y] = (x,y)\n------------------utils-----------------------\ntr x y = trace ((show x) ++ (show y)) y\ntr1 x y = trace ((show x)) y\ntr2 y = trace ((show y)) y\n\n(|>) x f = f x\n\nparseInt x = (read x) :: Int\n\ngetIndex = zip [0..]\n\ngetLines n = repeat getLine |> take n |> sequence \n\ngetNums :: IO [Int]\ngetNums =\n\tdo\n\t\tline <- getLine\n\t\treturn $ getNumbers line\n\ngetNumbers :: [Char] -> [Int]\ngetNumbers line = \n\tcase index of \n\t\tNothing -> [parseInt line]\n\t\tJust i ->\n\t\t\tlet (l,r) = splitAt (i + 1) line in\n\t\t\t\t(parseInt l) : (getNumbers r)\n\twhere\n\t\tindex = elemIndex ' ' line\n\nsplitBy k = \n\tcase index of \n\t\tNothing -> [k]\n\t\tJust i ->\n\t\t\tlet (l,r) = splitAt (i) k in\n\t\t\t\tl : splitBy (drop 1 r)\n\twhere\n\t\tindex = elemIndex ' ' k\n"}, {"source_code": "import Debug.Trace\n\nzipList :: [a] -> [(a, a)]\nzipList [] = []\nzipList (x:y:xs) = (x, y) : zipList xs\nzipList _ = error \"invalid list\"\n\nconstruct :: Int -> [(Int, Int)] -> [(Int, [Int])]\nconstruct n lst = [(i, test i) | i <- [0..n-1]]\n where test i = let tmp = filter (check i) lst\n in map (get i) tmp\n check i (a, b) = a - 1 == i || b - 1 == i\n get i (a, b) = a + b - i - 2\n\nsolve :: [(Int, [Int])] -> Int\nsolve g = let del = filter ((== 1) . length . snd) g\n in if null del\n then 0\n else 1 + (solve $ update g del)\n where update g del = let gg = filter ((/= 1) . length . snd) g\n dd = map fst del\n in update' gg dd\n update' gg dd = map (test dd) gg\n test dd (a, b) = (a, filter (flip notElem dd) b)\n\nmain :: IO()\nmain = do cs <- getContents\n let lst = map read $ words cs :: [Int]\n n = lst !! 0\n m = lst !! 1\n rest = drop 2 lst\n pairs = zipList rest\n graph = construct n pairs\n print $ solve graph\n"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\nimport qualified Data.IntSet as IntSet\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nsolve :: (Int, Int) -> IOArray Int IntSet.IntSet -> IO Int\nsolve bounds buf = loop 0\n where\n loop n = do\n let f acc a = do\n set <- readArray buf a\n if IntSet.size set /= 1 then return acc else return $ a : acc\n as <- foldM f [] (range bounds)\n notYet <- fmap or . forM as $ \\a -> do\n set <- readArray buf a\n if IntSet.size set /= 1\n then return False\n else do\n let b = IntSet.findMax set\n set' <- readArray buf b\n writeArray buf b $ IntSet.delete a set'\n writeArray buf a $ IntSet.delete b set\n return True\n if not notYet\n then return n\n else loop (n + 1)\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n let bounds = (1, n)\n buf <- newArray bounds IntSet.empty :: IO (IOArray Int IntSet.IntSet)\n replicateM_ m $ do\n [a, b] <- readInts\n readArray buf a >>= writeArray buf a . (IntSet.insert b)\n readArray buf b >>= writeArray buf b . (IntSet.insert a)\n solve bounds buf >>= print\n\n"}], "negative_code": [{"source_code": "import Debug.Trace\n\nzipList :: [a] -> [(a, a)]\nzipList [] = []\nzipList (x:y:xs) = (x, y) : zipList xs\nzipList _ = error \"invalid list\"\n\nconstruct :: Int -> [(Int, Int)] -> [(Int, [Int])]\nconstruct n lst = [(i, test i) | i <- [0..n-1]]\n where test i = let tmp = filter (check i) lst\n in map (get i) tmp\n check i (a, b) = a - 1 == i || b - 1 == i\n get i (a, b) = a + b - i - 1\n\nsolve :: [(Int, [Int])] -> Int\nsolve g = let del = filter ((== 1) . length . snd) g\n in if null del\n then 0\n else 1 + (solve $ update g del)\n where update g del = let gg = filter ((/= 1) . length . snd) g\n dd = map fst del\n in update' gg dd\n update' gg dd = map (test dd) gg\n test dd (a, b) = (a, filter (flip notElem dd) b)\n\nmain :: IO()\nmain = do cs <- getContents\n let lst = map read $ words cs :: [Int]\n n = lst !! 0\n m = lst !! 1\n rest = drop 2 lst\n pairs = zipList rest\n graph = construct n pairs\n print $ solve graph\n"}], "src_uid": "f8315dc903b0542c453cab4577bcb20d"} {"source_code": "import Control.Monad (forM_)\n\nlinefun line = (<) 1 . length . filter (== \"1\") $ words line\n\nmain = putStrLn . show . length . filter linefun . tail . lines =<< getContents\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: [Int] -> Bool\nsolve = (>= 2) . length . filter ((==) 1)\n\nmain = do\n (_:cases) <- fmap (fmap read) . fmap words . lines <$> getContents\n let n = length $ filter id $ fmap solve cases\n print n\n"}, {"source_code": "import Control.Monad\n\nmain = interact program\n\nprogram :: String -> String\nprogram input = \n let _:ts = lines input\n count1 = length . filter (== \"1\") . words\n pass = (>= 2) . count1 \n results = length $ filter pass ts\n in show results"}, {"source_code": "import Control.Monad (replicateM)\n\nmain = do\n n <- readLn\n ls <- replicateM n getLine\n print $ length $ filter (\\s -> length (filter (== '1') s) >= 2) ls\n\n"}, {"source_code": "import Control.Monad\n\nmain = do \n n <- getLine\n inputs <- replicateM (read n) (getLine)\n print $ parseInputs inputs\n\nparseInputs [] = 0\nparseInputs (x:xs) \n | (sum (map read (words x))) > 1 = 1 + parseInputs xs\n | otherwise = parseInputs xs\n"}, {"source_code": "module Main where\n\nimport Data.Maybe (fromJust)\nimport Control.Monad (foldM, sequence)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumber :: IO Int\nreadNumber =\n (fst\n . fromJust\n . BS.readInt) `fmap` BS.getLine\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\nmain :: IO ()\nmain = do\n nCases <- readNumber\n result <- foldM (\\acc _ -> do\n howManyKnow <- sum `fmap` readNumbers\n return (if (howManyKnow >= 2)\n then succ acc\n else acc))\n 0\n [1..nCases]\n print result\n"}, {"source_code": "module Main where\nimport Data.List\n\nsolve :: Integer -> [Integer] -> Integer\nsolve acc xs = acc + (if s >= 2 then 1 else 0)\n where s = foldl1' (+) xs\n\nmain = interact $ show . (foldl' solve 0) . (map (map read)) . (map words) . (drop 1) . lines\n"}, {"source_code": "import Control.Applicative\nmain= do\n\tgetLine\n\ts<- length .filter (\\z-> elem z [\"1 1 1\",\"1 1 0\", \"1 0 1\", \"0 1 1\"]). lines <$> getContents\n\tprint s \n"}, {"source_code": "module Main where\n\n\n--71A\n--replicateM n x = sequence (replicate n x)\n\n--processWord :: String -> String\n--processWord word | length word > 10 = (head word) : (show (length word - 2)) ++ ((last word):[])--(word !! ((length word) - 1))\n-- | otherwise = word\n\n--main = sequence [putStrLn $ show i | i <- [1..5]]\n--main = getLine >>= \\line -> replicateM (read line) (getLine) >>= \\list -> sequence [putStrLn (processWord (list!!i)) | i <- [0..(length list) - 1]]\n\n\n\n\n--118A\n--import Data.Char\n--isSylable :: Char -> Bool\n--isSylable char = elem char \"AOYEUIaoyeui\"\n--\n--deleteSylabls::[Char] -> [Char]\n--deleteSylabls [] = []\n--deleteSylabls (x:xs) | isSylable x = deleteSylabls xs\n-- | otherwise = x:(deleteSylabls xs)\n--\n--addDots :: [Char] -> [Char]\n--addDots [] = []\n--addDots (x:xs) = '.' : x : (addDots xs)\n--\n--processWord :: String -> String\n--processWord = addDots . deleteSylabls . (map toLower)\n--\n--main = getLine >>= putStrLn . processWord\n\n\n\n\n--50A\n\n--split :: Char -> String -> [String]\n--split _ [] = [\"\"]\n--split c (x:xs) | x == c = \"\" : rest\n-- | otherwise = (x : head rest): tail rest\n-- where rest = split c xs\n--\n--calc :: Int -> Int -> Int\n--calc m n = m*n `div` 2\n--\n--main = getLine >>= \\a -> let inp = (map read (split ' ' a)) in putStrLn $ show $ calc (inp !! 0) (inp !! 1)\n\n--231A\n\nsplit :: Char -> String -> [String]\nsplit _ [] = [\"\"]\nsplit c (x:xs) | x == c = \"\" : rest\n | otherwise = (x : head rest): tail rest\n where rest = split c xs\n\nisGood :: [Int] -> Int\nisGood (a:b:c:[]) = if (a+b+c >= 2) then 1 else 0\n\ntoIntList :: [[String]] -> [[Int]]\ntoIntList strs = map (map read) strs\n\nmain = getLine >>= \\line -> sequence (replicate (read line) getLine) >>= \\list -> putStrLn $ show $ sum $ map isGood (toIntList (map (split ' ') list))"}, {"source_code": "\n\nmain = do\n d <- getContents\n let (n:ls) = lines d\n let xs = map (map read . words) ls\n print $ length $ filter (\\t -> sum t >= 2) xs\n"}, {"source_code": "-- cf 231 a\n\nmain :: IO ()\nmain = getContents >>= (print . f 0 . map (map read . words) . tail . lines)\n\nf :: Int -> [[Integer]]-> Int\nf acc [] = acc\nf acc (x : rem)\n | sum x > 1 = f (acc+1) rem\n | otherwise = f acc rem\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n:_ <- getList\n matrix <- getLists n\n print $ solve matrix\n\ngetList :: (Read a) => IO [a]\ngetList = fmap (fmap read . words) getLine\n\ngetLists :: (Read a) => Int -> IO [[a]]\ngetLists nRows = replicateM nRows getList\n\nsolve :: [[Int]] -> Int\nsolve matrix = length [row | row <- matrix, sum row >= 2] \n"}, {"source_code": "main = do \n getLine\n interact (solve.(map (map read)).(map words).lines)\nsolve = show.(result 0)\nresult acc x\n |x==[] = acc\n |sum(head x)>=2 = result (acc+1) (tail x)\n |otherwise = result acc (tail x)"}, {"source_code": "module Main where\n\n(|>) = flip (.)\n\nmain = interact $\n lines \n |> drop 1\n |> map (words |> map read)\n |> map sum\n |> filter (>= 2)\n |> length\n |> show\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.State\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n r <-\n replicateM n $ do\n q <- C.getLine\n let qs = fmap trim . (C.split ' ') $ q\n if (foldl score 0 qs) >= 2\n then return 1\n else return 0\n putStrLn . show . sum $ r\n\nscore :: Int -> C.ByteString -> Int\nscore s \"1\" = s + 1\nscore s _ = s\n\ntrim :: C.ByteString -> C.ByteString\ntrim s = C.filter (\\c -> (||) (c == '1') (c == '0')) s\n"}, {"source_code": "main = do\n\tdat <- getContents\n\tlet allLines = tail $ lines dat\n\tputStrLn $ show $ answer allLines\n\nanswer :: [String] -> Int\nanswer = length . filter (\\x -> x == \"1 1 1\" || x == \"1 1 0\" || x == \"1 0 1\" || x == \"0 1 1\")"}, {"source_code": "\nmain = do\n\tn<-getLine\n\ta<-getContents\n\tlet k =map words $ lines a\n\tputStrLn $ show $ sum $ map (solve.map read) k\n\nsolve k = if length ( filter (==1) k) >=2 then 1\n\t else 0"}, {"source_code": "f xs | (sum xs) > 1 = 1 | 1>0 = 0 \nmain = interact $ show.sum.map f.map (map read.words).tail.lines\n"}, {"source_code": "import Data.Char\nimport System.IO\n\ngetWords :: String -> [String]\ngetWords str = words str\n\nlineProc :: String -> [Integer]\nlineProc str = map readInt (getWords(str))\n\twhere readInt = read :: String -> Integer\n\t\nsumAll :: [Integer] -> Integer\nsumAll lst = sum lst\n\ninvoke :: Integer -> IO Integer\ninvoke n = if n == 0 then return $ 0 else do\n\tnew_line <- getLine\n\tto_add <- invoke(n - 1)\n\treturn $ (if (sumAll $ lineProc $ new_line) >= 2 then 1 else 0) + to_add\n\t\nmain = do\n\tn <- getLine\n\tresult <- invoke (read n :: Integer)\n\tprint $ result\n\t"}, {"source_code": "solve x = show . sum . map (check . map read . words) $ (drop 1 $ lines x)\n where check x = if sum x > 1 then 1 else 0\n\nmain = interact solve\n"}, {"source_code": "main=interact$show.length.filter(>1).map(length.filter(=='1')).tail.lines\n"}, {"source_code": "f x=show$length[ y | y<-[sum$map read (words n) | n<-(tail$lines x)],y>=2]\nmain=interact$f"}, {"source_code": "main = interact $ show . length . filter ((> 1) . length) . map (filter (== '1')) . tail . lines"}, {"source_code": "import Control.Monad\n\n-- Snippet: readInts\nreadInts = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n answer <- replicateM n $ do\n s <- readInts\n return $ if sum s < 2 then 0 else 1\n putStrLn $ show $ sum answer\n"}, {"source_code": "isGood s\n | (sum l) > 1 = 1\n | otherwise = 0\n where l = map (read :: String -> Int).words $ s\n\nmain = interact $ show.sum.map isGood.tail.lines"}, {"source_code": "cYcle 0 m=do\n\tputStr $ show m\ncYcle n m=do\n input<-getLine\n let t = words input\n let a = read (head t)\n let b = read (head (tail t))\n let c = read (head (tail (tail t)))\n let p = if a+b+c>1 then m+1 else m\n cYcle (n-1) p\nmain=do\n input<-getLine\n cYcle (read.head.words$input) 0"}, {"source_code": "import Control.Monad\nsolve :: [[Int]] -> Int\nsolve [] = 0\nsolve (x : xs) = (if sum x > 1 then 1 else 0) + solve xs\nmain = do\n n <- readLn\n l <- replicateM n getLine\n print . solve $ map (map read . words) l\n"}, {"source_code": "main=interact$show.length.filter((1<).sum.map read.words).tail.lines"}, {"source_code": "import Data.List\nimport Data.List.Split\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Char as C\n\n(|>) = flip ($)\n\nmain = interact process\n\nprocess contents = let\n problems = contents |> lines |> tail |> map words |> map (map read) :: [[Int]]\n in solve problems |> show\n \nsolve problems = problems\n |> map sum\n |> filter (>= 2)\n |> length\n "}, {"source_code": "solve = length.filter (>1) . map sum\n\nmain = do\n\tv <- getContents\n\tprint . solve . map (map read) . map words . tail . lines $ v"}, {"source_code": "import Control.Applicative\n\nmain = interact $ show . length . filter (>1) . map (length . filter (=='1')) . tail . lines\n\n \n"}, {"source_code": "main =\n print .\n length .\n filter (>1) .\n map (sum . map read . words) .\n tail .\n lines =<< getContents\n"}, {"source_code": "main = readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\x-> interact $ show.foldr (\\a b-> case () of \n _|a> 1 -> 1+b\n |otherwise -> b ) 0. map (foldr (\\a b-> read a+b) 0. words). take (read x) . lines"}, {"source_code": "main = interact $ show . length . filter (> 1) . map (sum . map read . words) . tail . lines"}, {"source_code": "solve :: String -> Integer\nsolve all = \n let \n conv = map (map (read::String->Integer)) $ map words .tail $ lines all\n in foldl (\\acc x -> if x > 1 then acc + 1 else acc) 0 $ map sum conv\nmain = do\n all <- getContents\n print $ solve all\n"}, {"source_code": "{-#LANGUAGE OverloadedStrings#-}\nmodule Main where\n\nimport Data.Text (splitOn, pack, unpack)\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n solve n \n >>= pure . length . filter (>=2) \n >>= putStrLn . show\n\n-- solve :: Int -> String\n-- solve = undefined\n\nsolve :: Int -> IO [Int]\nsolve n = sequence [getLine >>= oz | _ <- [1..n]]\n\n-- ones should be greater than equal to 2\noz :: String -> IO Int\noz = pure . length . filter (=='1')\n\ngetInts :: IO [Int]\ngetInts = fmap ( map ( read . unpack ) \n . splitOn \" \" . pack ) getLine\n\n"}, {"source_code": "-- Codeforces 231A\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n replicateM n getLine >>= putStrLn . show . solve . map words where\n solve = length . filter (>= 2) . map (sum . map read)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain = do\n n <- read <$> getLine\n ls <- map (map read . words) <$> replicateM n getLine :: IO [[Int]]\n let nt = sum $ map (`cntOnes` 0) ls\n print nt\n\ncntOnes [] c = 0\ncntOnes (x:xs) c\n | c+x > 1 = 1\n | otherwise = cntOnes xs (c+x)"}, {"source_code": "f::[String]->Int\nf []=0\nf (x:xs)=let ys=map read (words x)::[Int]\n y=sum ys\n in if y>1 then 1+f xs else f xs\n \n \nmain =do\n e<-getLine\n es<-getContents\n let xs=lines es\n print $ f xs"}, {"source_code": "answer :: [[Int]] -> Int\nanswer = length . filter (>=2) . map sum\n\nmain = do interact $ show . answer . map (map read) . map words . tail . lines\n"}, {"source_code": "-- import Data.Char\n-- import Data.Int\n-- import Data.List\nimport Control.Monad\ngetList :: Read a => IO [a]\ngetList = fmap (map read . words) getLine\n\nsolve :: [[Int]] -> Int\nsolve = length . filter ((>= 2) . sum)\n\nmain :: IO ()\nmain = do\n n <- readLn\n a <- replicateM n getList\n putStrLn . show $ solve a\n \n"}, {"source_code": "main = do\n _ <- getLine\n inputStr <- getContents\n let s = (map (sum . map read . words) . lines) inputStr :: [Int]\n print $ (length . filter (>=2)) s\n \n"}, {"source_code": "import Prelude hiding (catch)\nimport Control.Applicative\nimport Control.Exception\n\nreadLines :: Int -> IO [String]\nreadLines 0 = return [\"\"]\nreadLines n = do\n s <- getLine\n rest <- readLines (n - 1)\n return $ s:rest\n\ncalc :: String -> Int\ncalc s = if (sum $ map read $ words s) >= 2 then 1 else 0\n\nmain = do\n n <- read <$> getLine\n ss <- readLines n\n print $ sum $ map calc ss\n"}, {"source_code": "solve :: String -> Int\nsolve xs\n | s > 1 = 1 \n | otherwise = 0\n where s = sum (map read (words xs))\n\n\nmain = interact $ show . sum . map solve . tail . lines\n"}, {"source_code": "solve = length . filter (>=2) . map sum\nmain = interact $ show . solve . map (map read) . map words . tail . lines"}, {"source_code": "\n-- Michael V. Antosha \n-- 2016\n-- http://mivael.in.ua\n\nmain = do\n interact $ show . s . map read . words\n where\n s (n:triples) = csum n triples\n s _ = error \"N expected.\"\n\n csum 0 [] = 0\n csum n (a:b:c:rest) =\n (count (a+b+c >= 2)) + (csum (n-1) rest)\n csum _ _ = error \"N triples expected.\"\n\n count True = 1\n count False = 0\n"}, {"source_code": "import Control.Applicative\n\n\n\n\nmain::IO ()\nmain=do\n getLine\n a<-(map (map read.words)) .lines <$> getContents\n print $ length $ filter (>1) $ map sum a\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Int\nsolve = length . filter ((>1) . sum)\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\ngetL n = sequence (replicate n getLine)\n\nmain = do\n n <- getLine\n l <- map (length . filter (=='1')) <$> lines <$> getContents\n putStrLn $ show . length . filter (>=2) $ l\n"}, {"source_code": "import Control.Monad\nmain = do\n taskCount <- getLine\n res <- forM [1..read taskCount] (\\_ -> do\n strTask <- getLine\n let [a,b,c] = map read . words $ strTask\n return $ if a+b+c >= 2 then 1 else 0)\n print $ sum res\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n inp <- replicateM n getLine\n let willSolve = fmap (length . filter (== '1')) inp\n output = length . filter (> 1) $ willSolve\n print output\n"}, {"source_code": "main :: IO ()\nmain = do\n arg <- getLine\n let num = read arg\n let spisok = sequence $ replicate num getLine\n sp <- spisok\n let spt = map read $ concat $ map words sp\n print $ solve spt\n \n \n\nprintSolver :: Int -> IO ()\nprintSolver 1 = solver\nprintSolver n = do solver \n printSolver (n-1)\n\nsolver :: IO ()\nsolver = do\n line <- getLine\n let str = map read $ words line\n print $ solve str\n \n\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve (x:y:z:xs) = if x+y+z >= 2 then 1 + solve xs else 0 + solve xs"}, {"source_code": "\nsolve :: Int -> Int -> IO ()\nsolve 0 ans = putStrLn $ show ans \nsolve n ans = do\n a <- (map read . words) `fmap` getLine\n if (sum a) > 1\n then solve (n - 1) (ans + 1)\n else solve (n - 1) ans\n\nmain = do\n n <- read `fmap` getLine;\n solve n 0"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/231/A\n\nimport Control.Monad\n\nmain = do\n n <- readLn\n a <- replicateM n getList\n putStrLn . show $ solve a\n\nsolve :: [[Int]] -> Int\nsolve = length . filter ((>= 2) . sum)\n\ngetList :: Read a => IO [a]\ngetList = fmap (map read . words) getLine\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Control.Monad\nmain = do\n problems <- ((read :: String -> Int) <$> getLine) >>= \\c -> mapM (\\_ -> getLine) [1..c]\n print $ length $ filter (\\p -> (length $ filter (=='1') p) >1 ) problems\n"}, {"source_code": "main = interact $ show . length . filter (>= 2) . map (length . filter (== \"1\") . words) . tail . lines"}, {"source_code": "module Main where\n\ninfixl 0 |>\n(|>) :: a -> (a -> b) -> b\nx |> f = f x\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocess :: (Eq t, Num t) => t -> IO [Int]\nprocess range = process' range []\n where\n process' 0 sums = return sums\n process' range sums = do\n line <- getLine\n let currentSum = line |> words |> map (read :: String -> Int) |> sum\n process' (range - 1) (currentSum : sums)\n\nmain :: IO ()\nmain = do\n range <- getInt\n processedSums <- process range\n processedSums |> filter (>= 2) |> length |> print\n"}, {"source_code": "module Main where\n\ninfixl 0 |>\nx |> f = f x\n\ngetInt :: IO Int\ngetInt = readLn\n\nprocess :: (Eq t, Num t) => t -> [Int] -> IO [Int]\nprocess 0 sums = return sums\nprocess range sums = do\n line <- getLine\n let currentSum = line |> words |> map (read :: String -> Int) |> sum\n process (range - 1) (currentSum : sums)\n\nmain :: IO ()\nmain = do\n range <- getInt\n processedSums <- process range []\n processedSums |> filter (>= 2) |> length |> print\n"}, {"source_code": "solve [] = 0\nsolve ((a, b, c):xs) = if a + b + c > 1 then y + 1 else y where y = solve xs\n\nmain :: IO()\nmain = do\n n <- getLine\n contents <- getContents\n let input = map ((\\(a:b:c:_) -> (a, b, c)) . map (read :: String -> Int) . words) $ lines contents\n print(solve input)\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: [Int] -> Bool\nsolve = (>= 2) . length . filter ((==) 1)\n\nmain = do\n (_:cases) <- fmap (fmap read) . fmap words . lines <$> getContents\n let n = length $ filter solve cases\n print n\n"}], "negative_code": [{"source_code": "main = interact $ show . length . filter (>1) . map (sum . (map read . words)) . lines"}, {"source_code": "main = do\n getLine\n cs <- fmap (map (map read . words) . lines) getContents\n print $ map (\\l -> sum l >= 2) cs"}, {"source_code": "solve = length.filter (>1) . map sum\n\nmain = do\n\tv <- getContents\n\tprint . solve . map (map read) . map words . lines $ tail v"}, {"source_code": "solve dtms = length $ filter (>=2) $ map sum dtms\nmain = interact $ show . solve . map (map read . words) . lines\n"}, {"source_code": "sumInts :: [String] -> Integer\nsumInts = sum . map read\n\nconsensus :: String -> String\nconsensus views \n | tot > 1 = \"YES\"\n | otherwise = \"NO\"\n where tot = sumInts . words $ views\n\nmain = do\n n <- getLine\n interact (unlines . map consensus . lines)\n"}, {"source_code": "main = interact $ show . length . filter willImplement . tail . lines\n\nwillImplement :: String -> Bool\nwillImplement s = case s of\n \"0 1 1\" -> True\n \"1 1 0\" -> True\n \"1 1 1\" -> True\n otherwise -> False\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.State\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n r <-\n replicateM n $ do\n q <- C.getLine\n let qs = C.split ' ' q\n if (foldl score 0 qs) >= 2\n then return 1\n else return 0\n putStrLn . show . sum $ r\n\nscore :: Int -> C.ByteString -> Int\nscore s \"1\" = s + 1\nscore s _ = s\n"}], "src_uid": "3542adc74a41ccfd72008faf983ffab5"} {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\nimport Data.Array\n\nsolve :: Array Int Int -> Int\nsolve arr = if z > 1 then -1 else s\n where\n func (a, b) c\n | c == maxBound = (a, b+1)\n | otherwise = (a+c, b)\n (s, z) = foldl func (0, 0) $ map snd $ assocs arr\n\nmain = do\n n <- read <$> getLine :: IO Int\n q <- map read . words <$> getLine :: IO [Int]\n let parseLine [a,b,c] = (read b, read c)\n lists <- read <$> getLine >>= flip replicateM (parseLine . words<$> getLine)\n let arr = accumArray min maxBound (1,n) lists\n print $ solve arr\n", "positive_code": [{"source_code": "\nimport Control.Monad\nimport Data.Array\nimport qualified Data.IntMap as M\nimport Data.List\n\nsolve :: Int -> [Int] -> Int -> [(Int, Int, Int)] -> Int\nsolve n qs m apps =\n foldr rec 0 $ tail $ reverse ms\n where\n rec i res\n | res == -1 = -1\n | otherwise =\n let es = map snd $ filter (\\(j, _) -> is ! i < is ! j) $\n M.findWithDefault [] i edges\n in if null es then -1 else res + minimum es\n ms = map snd $ sort $ zip qs [1..]\n is = listArray (1, n) $ map snd $ sort $ zip ms [1..]\n edges = M.fromListWith (++) $ map (\\(a, b, c) -> (b, [(a, c)])) apps\n\nmain = do\n n <- readLn\n qs <- fmap (map read . words) getLine\n m <- readLn\n apps <- replicateM m $ do\n [a, b, c] <- fmap (map read . words) getLine\n return (a, b, c)\n print $ solve n qs m apps\n"}, {"source_code": "import List\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nnum max_q (a:s) n | max_q == a = n\n | True = num max_q s (n+1)\n\nmain = do\n s <- getLine\n s2<- getLine\n s3<- getLine\n let n:_ = un s\n qs = un s2\n m:_ = un s3\n max_q = maximum $ qs\n max_n = num max_q qs 0\n zajav <- getLines m\n let m_zajavlenij = map un zajav\n apps = map (\\(a:b:c:s) -> (b,c)) m_zajavlenij\n appsByNum = [ [ (b,c) | (b,c) <- apps, b == emp] | emp <- [1..n]]\n bestApps = map f appsByNum\n where f [] = 0 :: Int\n f ((b,c):as) = getBest as c :: Int\n getBest [] c = c :: Int\n getBest ((_,t):as) c = getBest as (min c t) :: Int\n best_sum = sum bestApps\n notEmp = filter null appsByNum\n notEmpN = length notEmp\n\n if notEmpN > 1 then\n putStrLn \"-1\"\n else\n putStrLn $ show best_sum\n \n --putStrLn $ show apps\n --putStrLn $ show appsByNum\n --putStrLn $ show bestApps\n --putStrLn $ show bestApps\n --putStrLn $ show notEmpN\n"}], "negative_code": [{"source_code": "import List\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nuniq [] = []\nuniq [a] = [a]\nuniq (a:b:s) | a == b = uniq (b:s)\n | True = a:(uniq (b:s))\n\nuniqBy [] = []\nuniqBy [(a,b)] = [b]\nuniqBy ((a,b):(c,d):s) | a == c = (min b d):(uniqBy s)\n | True = b:d:(uniqBy s)\n\n\nmain = do\n s <- getLine\n s2<- getLine\n s3<- getLine\n let n:_ = un s\n qs = un s2\n m:_ = un s3\n zajav <- getLines m\n let m_zajavlenij = map un zajav :: [[Int]]\n list_of_emploers = uniq $ sort $ map (\\(a:b:c:s) -> b) m_zajavlenij\n if length list_of_emploers < (n-1) then\n putStrLn \"-1\"\n else do \n --putStrLn $ show list_of_emploers\n let emp_costs = sort $ map (\\(a:b:c:s) -> (b,c)) m_zajavlenij :: [(Int, Int)]\n emp_best = uniqBy emp_costs\n summa = sum emp_best\n --putStrLn $ show emp_costs\n --putStrLn $ show emp_best\n putStrLn $ show summa\n"}], "src_uid": "ddc9b2bacfaa4f4e91d5072240c1e811"} {"source_code": "import qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Maybe (fromJust)\nimport Prelude hiding ((.))\n(.) a b = b a\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n let [n, s, t] = s1 . words . map (read :: String -> Int)\n ps = s2 . words . map (read :: String -> Int)\n ms = Map.fromList (zip [1 .. n] ps)\n visit l c v\n | c == t = l\n | c `Set.member` v = -1\n | otherwise = visit (l + 1) (fromJust $ Map.lookup c ms) (Set.insert c v)\n print (visit 0 s Set.empty)", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,s,t] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve n s t xs\n\nsolve n s t xs = go 0 . take n $ iterate (unsafeAt arr) s\n where\n !arr = listArray (0,n) $ 0:xs :: UArray Int Int\n go cnt (y:ys)\n | cnt > n = -1\n | y == t = cnt\n | otherwise = go (cnt+1) ys\n go _ _ = -1"}, {"source_code": "import qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport Data.Maybe (fromJust)\nimport Prelude hiding ((.))\n(.) a b = b a\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n let [n, s, t] = s1 . words . map (read :: String -> Int)\n ps = s2 . words . map (read :: String -> Int)\n ms = Map.fromList (zip [1 .. n] ps)\n visit l c v\n | c == t = l\n | c `Set.member` v = -1\n | otherwise = visit (l + 1) (fromJust $ Map.lookup c ms) (Set.insert c v)\n print (visit 0 s Set.empty)"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), listArray)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> (Int, Int) -> Int\nsolve ps (a, b) = solve' 0 a\n where\n ps' = listArray (1, length ps) ps\n solve' m c\n | c == b = m\n | c == a && m > 0 = -1\n | otherwise = solve' (m+1) (ps' ! c)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- reads\n ps <- reads\n print $ solve ps (a, b)\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s"}], "negative_code": [], "src_uid": "b01602b51b9103c0f31c3f50b32aa88d"} {"source_code": "import Control.Monad (replicateM, replicateM_)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadLine :: IO [Int]\nreadLine = map digitToInt <$> getLine\n\nreadTable :: IO [[Int]]\nreadTable = \n read <$> getLine >>= \\n ->\n replicateM n readLine\n\ncheckMatrix :: [[Int]] -> Bool\ncheckMatrix m = not $ any (any invalid) (zipWith3 zip3 m ts t) where\n ts = map tail m\n t = tail m\n invalid (x, right, down) = x == 1 && right == 0 && down == 0\n\nmain =\n readInt >>= \\t -> \n replicateM_ t (\n readTable >>= \\m ->\n putStrLn (\n if checkMatrix m then \"YES\"\n else \"NO\"\n )\n )", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Control.Arrow\n\nvalid (v, w) = v /= '1' || w == '1'\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n mat <-\n array ((1, 1), (n, n))\n . zip [ (i, j) | i <- [1 .. n], j <- [1 .. n] ]\n . concat\n <$> replicateM n getLine\n putStrLn\n $ if and\n [ (\\(i, j) ->\n ((j + 1) > n || valid\n (mat ! (i, j), mat ! (i, j + 1))\n )\n || ((i + 1) > n || valid\n (mat ! (i, j), mat ! (i + 1, j))\n )\n )\n (i, j)\n | i <- [1 .. n]\n , j <- [1 .. n]\n ]\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n polygon <- replicateM n (map (== '1') <$> getLine)\n let down = tail polygon\n right = tail <$> polygon\n valid = zipWith (zipWith (||)) down right\n putStrLn $ bool \"NO\" \"YES\" $ all and $ zipWith (zipWith (||)) ((not <$>) <$> polygon) valid"}, {"source_code": "import Control.Monad (replicateM, replicateM_)\nimport Data.Array\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadLine :: IO [Int]\nreadLine = map digitToInt <$> getLine\n\ngetDimensions :: Array (Int, Int) Int -> (Int, Int)\ngetDimensions = (snd . bounds)\n\nreadTable :: IO [[Int]]\nreadTable = \n read <$> getLine >>= \\n ->\n replicateM n readLine\n\naddIndices :: [[Int]] -> [((Int, Int), Int)]\naddIndices xss = [((i, j), x) | (i, xs) <- zip [0..] xss, \n (j, x) <- zip [0..] xs]\n\nmatrixFromList :: [[Int]] -> Array (Int, Int) Int\nmatrixFromList xss = \n array ((0, 0), (n, m)) (addIndices xss)\n where\n (n, m) = (length xss - 1, (length . head) xss - 1)\n\nisCellValid :: (Int, Int) -> Array (Int, Int) Int -> Bool\nisCellValid (i, j) matrix =\n matrix ! (i, j) == 0 ||\n i == n || j == m || \n matrix ! (i, j + 1) == 1 ||\n matrix ! (i + 1, j) == 1\n where\n (n, m) = getDimensions matrix\n\ncheckMatrix :: Array (Int, Int) Int -> String\ncheckMatrix matrix = if valid then \"YES\" else \"NO\" where \n valid = all (\\ idx -> isCellValid idx matrix) (indices matrix)\n\nmain = \n readInt >>= \\t ->\n replicateM_ t (\n readTable >>= \\table ->\n putStrLn $ (checkMatrix . matrixFromList) table\n )"}, {"source_code": "import Control.Monad ( replicateM_ )\n\n\nreadInput = do\n n <- read <$> getLine\n sequenceA $ replicate n (map (=='1') <$> getLine)\n\nbuyingShovels :: [[Bool]] -> String\nbuyingShovels m =\n let a = map tail m\n b = tail m\n zipped = zipWith3 zip3 m a b\n in\n if any (any invalid) zipped\n then \"NO\"\n else \"YES\"\n where invalid (t, u, v) = t && not u && not v\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (buyingShovels <$> readInput >>= putStrLn)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/E\n\nimport Control.Monad ( replicateM_ )\n\n\npolygon :: [[Bool]] -> String\npolygon grid =\n let right = map tail grid\n bottom = tail grid\n invalid = zipWith3_2d isValid grid right bottom\n in\n if any or invalid\n then \"NO\"\n else \"YES\"\n where\n zipWith3_2d = zipWith3 . zipWith3\n isValid t u v = t && not u && not v\n\n\nreadInput :: IO [[Bool]]\nreadInput = do\n n <- read <$> getLine\n sequence $ replicate n (map (=='1') <$> getLine)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (polygon <$> readInput >>= putStrLn)\n"}, {"source_code": "import Data.List (transpose)\nimport Data.Traversable (for, for)\n\nsolve :: [[Char]] -> Bool\nsolve arr = and $ map and ok where\n supr :: [[Char]] -> [[Bool]]\n supr = map $ \\li -> zipWith (<=) li (tail li)\n ok = zipWith (zipWith (||)) (supr arr) (transpose . supr $ transpose arr)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n _ <- for [1..t] $ \\_ -> do\n n <- read <$> getLine :: IO Int\n arr <- for [1..n] $ const getLine\n putStrLn $ if solve arr then \"YES\" else \"NO\"\n return ()\n"}], "negative_code": [], "src_uid": "eea15ff7e939bfcc7002cacbc8a1a3a5"} {"source_code": "import Control.Applicative\r\nimport Control.DeepSeq\r\nimport Control.Monad\r\nimport Control.Monad.Trans.Class\r\nimport Control.Monad.Trans.State\r\nimport Data.Either\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.IntSet as IS\r\n\r\n-- Implementing this gave me a headache\r\ndata PQNode = PQLeaf !Int\r\n | PNode [PQNode]\r\n | QNode [PQNode]\r\n deriving Show\r\n\r\ndata RNode = Em { unRNode :: PQNode }\r\n | Fu { unRNode :: PQNode }\r\n | Pa [PQNode] [PQNode] -- empty and full, end first\r\n deriving Show\r\n\r\nmkPNode, mkQNode :: [PQNode] -> PQNode\r\nmkPNode [] = error \"empty PNode\"\r\nmkPNode [n] = n\r\nmkPNode ns = PNode ns\r\nmkQNode [] = error \"empty QNode\"\r\nmkQNode [n] = n\r\nmkQNode [n, m] = PNode [n, m]\r\nmkQNode ns = QNode ns\r\n\r\nmkRNode :: [PQNode] -> [PQNode] -> RNode\r\nmkRNode [] _ = error \"empty RNode es\"\r\nmkRNode _ [] = error \"empty RNode fs\"\r\nmkRNode es fs = Pa es fs\r\n\r\nisFu, isEm, isPa :: RNode -> Bool\r\nisFu (Fu _) = True\r\nisFu _ = False\r\nisEm (Em _) = True\r\nisEm _ = False\r\nisPa (Pa _ _) = True\r\nisPa _ = False\r\n\r\nsplitForP :: [RNode] -> ([PQNode], [RNode], [PQNode])\r\nsplitForP us = go us [] [] [] where\r\n go [] e p f = (e, p, f)\r\n go (x:xs) e p f = case x of\r\n Em n -> go xs (n:e) p f\r\n Pa _ _ -> go xs e (x:p) f\r\n Fu n -> go xs e p (n:f)\r\n\r\nspan1 :: (a -> Bool) -> [a] -> ([a], [a])\r\nspan1 _ [] = ([], [])\r\nspan1 f xs@(x:xs')\r\n | f x = ([x], xs')\r\n | otherwise = ([], xs)\r\n\r\nsplitForQ :: [RNode] -> Maybe ([PQNode], [RNode], [PQNode])\r\nsplitForQ xs = go xs <|> go (reverse xs) where\r\n go = evalStateT $ do\r\n ~[es, ps, fs] <- mapM state [span isEm, span1 isPa, span isFu]\r\n lift . ((map unRNode es, ps, map unRNode fs) <$) . guard =<< gets null\r\n\r\nsplitForQRoot :: [RNode] -> Maybe ([PQNode], [RNode], [PQNode], [RNode], [PQNode])\r\nsplitForQRoot = evalStateT $ do\r\n ~[e1, p1, fs, p2, e2] <- mapM state [span isEm, span1 isPa, span isFu, span1 isPa, span isEm]\r\n lift . ((map unRNode e1, p1, map unRNode fs, p2, map unRNode e2) <$) . guard =<< gets null\r\n\r\nbuildPQ :: [Int] -> PQNode\r\nbuildPQ = mkPNode . map PQLeaf\r\n\r\nreducePQ :: [Int] -> PQNode -> Maybe PQNode\r\nreducePQ [] = Just\r\nreducePQ xs0 = fromRight (error \"outside initial set\") . visit where\r\n xs = IS.fromList xs0\r\n\r\n visit :: PQNode -> Either Int (Maybe PQNode)\r\n visit n@(PNode cs) = visitPQ n PNode cs\r\n visit n@(QNode cs) = visitPQ n QNode cs\r\n visit n@(PQLeaf x)\r\n | x `IS.notMember` xs = Left 0\r\n | IS.size xs > 1 = Left 1\r\n | otherwise = Right $ reduceRoot n\r\n visitPQ n f cs\r\n | cnt == IS.size xs = Right $ reduceRoot n\r\n | null rts = Left cnt\r\n | ~[r] <- rts = Right $ f cs' <$ r\r\n where\r\n ys = map visit cs\r\n cnt = sum $ lefts ys\r\n rts = rights ys\r\n cs' = zipWith (\\c e -> either (const c) fromJust e) cs ys\r\n\r\n reduceRoot :: PQNode -> Maybe PQNode\r\n reduceRoot = go where\r\n go n@(PNode cs) = do\r\n (es, ps, fs) <- splitForP <$> mapM reduceInternal cs\r\n let noPartial\r\n | null es || null fs = n\r\n | otherwise = mkPNode $ mkPNode fs : es\r\n withPartial pe1 pf1 pe2 pf2 = mkPNode $ qn : es where\r\n qn = mkQNode $\r\n pe1 ++ reverse pf1 ++ [mkPNode fs | not (null fs)] ++ pf2 ++ reverse pe2\r\n case ps of\r\n [] -> Just noPartial\r\n [Pa pe1 pf1] -> Just $ withPartial pe1 pf1 [] []\r\n [Pa pe1 pf1, Pa pe2 pf2] -> Just $ withPartial pe1 pf1 pe2 pf2\r\n _ -> Nothing\r\n\r\n go n@(QNode cs) = do\r\n (e1, p1, fs, p2, e2) <- splitForQRoot =<< mapM reduceInternal cs\r\n let withPartial pe1 pf1 pe2 pf2 =\r\n mkQNode $ e1 ++ pe1 ++ reverse pf1 ++ fs ++ pf2 ++ reverse pe2 ++ e2\r\n case (p1, p2) of\r\n ([], []) -> Just n\r\n ([Pa pe1 pf1], []) -> Just $ withPartial pe1 pf1 [] []\r\n ([], [Pa pe2 pf2]) -> Just $ withPartial [] [] pe2 pf2\r\n ([Pa pe1 pf1], [Pa pe2 pf2]) -> Just $ withPartial pe1 pf1 pe2 pf2\r\n _ -> Nothing\r\n\r\n go n@(PQLeaf _) = Just n\r\n\r\n reduceInternal :: PQNode -> Maybe RNode\r\n reduceInternal = go where\r\n go n@(PNode cs) = do\r\n (es, ps, fs) <- splitForP <$> mapM go cs\r\n let noPartial\r\n | null es = Fu n\r\n | null fs = Em n\r\n | otherwise = mkRNode [mkPNode es] [mkPNode fs]\r\n withPartial pe pf =\r\n mkRNode ([mkPNode es | not (null es)] ++ pe) ([mkPNode fs | not (null fs)] ++ pf)\r\n case ps of\r\n [] -> Just noPartial\r\n [Pa pe pf] -> Just $ withPartial pe pf\r\n _ -> Nothing\r\n\r\n go n@(QNode cs) = do\r\n (es, ps, fs) <- splitForQ =<< mapM go cs\r\n let noPartial\r\n | null es = Fu n\r\n | null fs = Em n\r\n | otherwise = mkRNode es (reverse fs)\r\n withPartial pe pf = mkRNode (es ++ pe) (reverse fs ++ pf)\r\n case ps of\r\n [] -> Just noPartial\r\n [Pa pe pf] -> Just $ withPartial pe pf\r\n _ -> Nothing\r\n\r\n go n@(PQLeaf x) = Just $ if x `IS.member` xs then Fu n else Em n\r\n\r\nreduceAllPQ :: [[Int]] -> PQNode -> Maybe PQNode\r\nreduceAllPQ xss t = foldM (flip reducePQ) t xss\r\n\r\nm :: Int64\r\nm = 998244353\r\n\r\nmulmod :: Int64 -> Int64 -> Int64\r\nmulmod a b = a * b `mod` m\r\n\r\ncount :: PQNode -> Int64\r\ncount (PQLeaf _) = 1\r\ncount (PNode cs) = foldl1' mulmod $ zipWith mulmod [1..] $ map count cs\r\ncount (QNode cs) = mulmod 2 $ foldl1' mulmod $ map count cs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, m] <- readMany\r\n xss <- map tail <$> replicateM m readMany\r\n print $ maybe 0 count $ reduceAllPQ xss $ buildPQ [1..n]\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n", "positive_code": [{"source_code": "import Control.Applicative\r\nimport Control.Monad\r\nimport Control.Monad.State\r\nimport Data.Either\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.IntSet as IS\r\n\r\nm :: Int\r\nm = 998244353\r\n\r\nmulmod :: Int -> Int -> Int\r\nmulmod a b = a * b `mod` m\r\n\r\ncount :: PQNode -> Int\r\ncount (PQLeaf _) = 1\r\ncount (PNode cs) = foldl1' mulmod $ zipWith mulmod [1..] $ map count cs\r\ncount (QNode cs) = mulmod 2 $ foldl1' mulmod $ map count cs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, m] <- readMany\r\n xss <- map tail <$> replicateM m readMany\r\n print $ maybe 0 count $ reduceAllPQ xss $ buildPQ [1..n]\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n\r\n--------------------------------------------------------------------------------\r\n\r\ndata PQNode = PQLeaf !Int\r\n | PNode [PQNode]\r\n | QNode [PQNode]\r\n deriving Show\r\n\r\ntype Parts = ([PQNode], [PQNode]) -- empty and full, end first\r\ndata RNode = Empty PQNode\r\n | Full PQNode\r\n | Part Parts\r\n deriving Show\r\n\r\nmkPNode, mkQNode :: [PQNode] -> PQNode\r\nmkPNode [] = error \"empty PNode\"\r\nmkPNode [n] = n\r\nmkPNode ns = PNode ns\r\nmkQNode [] = error \"empty QNode\"\r\nmkQNode [n] = n\r\nmkQNode [n, m] = PNode [n, m]\r\nmkQNode ns = QNode ns\r\n\r\nmkPartial :: [PQNode] -> [PQNode] -> RNode\r\nmkPartial [] _ = error \"empty RNode es\"\r\nmkPartial _ [] = error \"empty RNode fs\"\r\nmkPartial es fs = Part (es, fs)\r\n\r\nemptyMany, fullMany :: State [RNode] [PQNode]\r\nemptyMany = state $ go [] where\r\n go ys (Empty n : xs) = go (n:ys) xs\r\n go ys xs = (reverse ys, xs)\r\nfullMany = state $ go [] where\r\n go ys (Full n : xs) = go (n:ys) xs\r\n go ys xs = (reverse ys, xs)\r\n\r\npartialMaybe :: State [RNode] (Maybe Parts)\r\npartialMaybe = state go where\r\n go (Part p : xs) = (Just p, xs)\r\n go xs = (Nothing, xs)\r\n\r\nsplitForP :: [RNode] -> ([PQNode], [Parts], [PQNode])\r\nsplitForP us = go us [] [] [] where\r\n go [] es ps fs = (es, ps, fs)\r\n go (x:xs) es ps fs = case x of\r\n Empty n -> go xs (n:es) ps fs\r\n Part p -> go xs es (p:ps) fs\r\n Full n -> go xs es ps (n:fs)\r\n\r\nsplitForQ :: [RNode] -> Maybe ([PQNode], Maybe Parts, [PQNode])\r\nsplitForQ xs = go xs <|> go (reverse xs) where\r\n go = evalState $ go' <$> emptyMany <*> partialMaybe <*> fullMany <*> gets null\r\n go' es ps fs end = (es, ps, fs) <$ guard end\r\n\r\nsplitForQRoot :: [RNode] -> Maybe ([PQNode], Maybe Parts, [PQNode], Maybe Parts, [PQNode])\r\nsplitForQRoot = evalState $\r\n go <$> emptyMany <*> partialMaybe <*> fullMany <*> partialMaybe <*> emptyMany <*> gets null\r\n where\r\n go es1 ps1 fs ps2 es2 end = (es1, ps1, fs, ps2, es2) <$ guard end\r\n\r\nbuildPQ :: [Int] -> PQNode\r\nbuildPQ = mkPNode . map PQLeaf\r\n\r\nreducePQ :: [Int] -> PQNode -> Maybe PQNode\r\nreducePQ [] = Just\r\nreducePQ xs0 = fromRight (error \"outside initial set\") . visit where\r\n xs = IS.fromList xs0\r\n xsz = IS.size xs\r\n\r\n visit :: PQNode -> Either Int (Maybe PQNode)\r\n visit n@(PNode cs) = visitPQ n PNode cs\r\n visit n@(QNode cs) = visitPQ n QNode cs\r\n visit n@(PQLeaf x)\r\n | x `IS.notMember` xs = Left 0\r\n | xsz > 1 = Left 1\r\n | otherwise = Right $ reduceRoot n\r\n visitPQ n f cs\r\n | cnt == xsz = Right $ reduceRoot n\r\n | null rts = Left cnt\r\n | ~[r] <- rts = Right $ f . getcs' <$> r\r\n where\r\n ys = map visit cs\r\n cnt = sum $ lefts ys\r\n rts = rights ys\r\n getcs' c' = zipWith (\\c -> either (const c) (const c')) cs ys\r\n\r\n reduceRoot :: PQNode -> Maybe PQNode\r\n reduceRoot n@(PNode cs) = go . splitForP =<< mapM reduceInternal cs where\r\n go (es, ps, fs) = case ps of\r\n [] -> Just noPartial\r\n [p1] -> Just $ withPartial p1 ([], [])\r\n [p1, p2] -> Just $ withPartial p1 p2\r\n _ -> Nothing\r\n where\r\n noPartial\r\n | null es || null fs = n\r\n | otherwise = mkPNode $ mkPNode fs : es\r\n withPartial (pe1, pf1) (pe2, pf2) = mkPNode $ qn : es where\r\n qn = mkQNode $\r\n pe1 ++ reverse pf1 ++ [mkPNode fs | not (null fs)] ++ pf2 ++ reverse pe2\r\n\r\n reduceRoot n@(QNode cs) = fmap go . splitForQRoot =<< mapM reduceInternal cs where\r\n go (es1, ps1, fs, ps2, es2) = case (ps1, ps2) of\r\n (Nothing, Nothing) -> n\r\n _ -> withPartial (fromMaybe ([], []) ps1) (fromMaybe ([], []) ps2)\r\n where\r\n withPartial (pe1, pf1) (pe2, pf2) =\r\n mkQNode $ es1 ++ pe1 ++ reverse pf1 ++ fs ++ pf2 ++ reverse pe2 ++ es2\r\n\r\n reduceRoot n@(PQLeaf _) = Just n\r\n\r\n reduceInternal :: PQNode -> Maybe RNode\r\n reduceInternal n@(PNode cs) = go . splitForP =<< mapM reduceInternal cs where\r\n go (es, ps, fs) = case ps of\r\n [] -> Just noPartial\r\n [p1] -> Just $ withPartial p1\r\n _ -> Nothing\r\n where\r\n noPartial\r\n | null es = Full n\r\n | null fs = Empty n\r\n | otherwise = mkPartial [mkPNode es] [mkPNode fs]\r\n withPartial (pe, pf) = mkPartial\r\n ([mkPNode es | not (null es)] ++ pe) ([mkPNode fs | not (null fs)] ++ pf)\r\n\r\n reduceInternal n@(QNode cs) = fmap go . splitForQ =<< mapM reduceInternal cs where\r\n go (es, ps, fs) = maybe noPartial withPartial ps where\r\n noPartial\r\n | null es = Full n\r\n | null fs = Empty n\r\n | otherwise = mkPartial es (reverse fs)\r\n withPartial (pe, pf) = mkPartial (es ++ pe) (reverse fs ++ pf)\r\n\r\n reduceInternal n@(PQLeaf x) = Just $ if x `IS.member` xs then Full n else Empty n\r\n\r\nreduceAllPQ :: [[Int]] -> PQNode -> Maybe PQNode\r\nreduceAllPQ xss t = foldM (flip reducePQ) t xss\r\n"}], "negative_code": [], "src_uid": "ac7b2d60a3e58f83d68dfaf4b38a6443"} {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n\tct <- C.getContents\n\tlet\n\t\t(n:t) = map (fst.fromJust.C.readInt) $ C.words ct\n\tputStrLn $ adjust $ solve (reverse t)\n\nadjust (s,x) \n\t| x < 0 = map (\\x -> if x == '+' then '-' else '+') s | otherwise = s\n\nsolve :: [Int] -> (String,Int)\nsolve (h:t) = foldl cal (\"+\",h) t\n\twhere\n\t\tcal (s,x) y \n\t\t\t| x + y <= y = ('+':s, x+y)\n\t\t\t| otherwise = ('-':s, x-y)\n\n--solve (x:[]) v = if x < v then (\"-\",0) else (\"+\",1)\n--solve (x:xs) v = if x < v then\n--\t\t\t\t\tlet\n--\t\t\t\t\t\t(seq,flag) = solve xs (v-x)\n--\t\t\t\t\tin\n--\t\t\t\t\t\tif flag==1 then (seq++\"+\",1) else (seq++\"-\",0)\n--\t\t\t\telse\n--\t\t\t\t\tlet \n--\t\t\t\t\t\t(seq,flag) = solve xs (x-v)\n--\t\t\t\t\tin\n--\t\t\t\t\t\tif flag==1 then (seq++\"-\",0) else (seq++\"+\",1)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n (h:t) <- fmap (reverse . map (fst . fromJust . C.readInt) . tail . C.words) C.getContents\n let (x, y) = foldl gao (h, \"+\") t\n putStrLn $ if x >= 0 then y else map (\\i -> if i == '+' then '-' else '+') y\n where\n gao (x, s) y\n | x + y <= y = (x + y, '+': s)\n | otherwise = (x - y, '-': s)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe (fromJust)\n\n-- main = do (_:as) <- (map (fst . fromJust . BS.readInt) . BS.words) `fmap` BS.getContents\n-- putStrLn $ solve'' (reverse as)\n\nmain = do (_:as) <- (map read . words) `fmap` getContents\n putStrLn $ solve'' (reverse as)\n\nsolve' as = fst $ foldl (\\(ops, s) a ->\n if a <= s\n then ('-':ops, s-a)\n else ('+':(map rev ops), a-s)\n ) (\"+\", head as) (tail as)\nrev '+' = '-'\nrev '-' = '+'\n\nsolve'' as = (\\(ops, s) -> \n if s <= 0\n then map rev ops\n else ops\n ) \n $ foldl (\\(ops, s) a ->\n if s <= 0\n then ('+':ops, s+a)\n else ('-':ops, s-a)\n ) (\"+\", head as) (tail as)"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe (fromJust)\n\nmain = do (_:as) <- (map (fst . fromJust . BS.readInt) . BS.words) `fmap` BS.getContents\n putStrLn $ solve'' (reverse as)\n\n-- main = do (_:as) <- (map read . words) `fmap` getContents\n-- putStrLn . fst $ solve' (reverse as)\n\nsolve' as = fst $ foldl (\\(ops, s) a ->\n if a <= s\n then ('-':ops, s-a)\n else ('+':(map rev ops), a-s)\n ) (\"+\", head as) (tail as)\nrev '+' = '-'\nrev '-' = '+'\n\nsolve'' as = (\\(ops, s) -> \n if s <= 0\n then map rev ops\n else ops\n ) \n $ foldl (\\(ops, s) a ->\n if s <= 0\n then ('+':ops, s+a)\n else ('-':ops, s-a)\n ) (\"+\", head as) (tail as)"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = putStrLn . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> String\nsolve (_ : as) = g False $ snd $ foldr f (0, \"\") as\n where\n f a (s, x)\n | a > s = (a - s, '+' : x)\n | otherwise = (s - a, '-' : x)\n g False ('+' : x) = '+' : g True x\n g False ('-' : x) = '-' : g False x\n g True ('+' : x) = '-' : g False x\n g True ('-' : x) = '+' : g True x\n g _ _ = []\n"}, {"source_code": "next :: (Integer, String) -> Integer -> (Integer, String)\nnext (s, r) a\n | s < 0 = (s + a, \"+\" ++ r)\n | s >= 0 = (s - a, \"-\" ++ r)\n\ninv :: Char -> Char\ninv '-' = '+'\ninv '+' = '-'\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ais <- fmap (map read . reverse . words) getLine\n let (si, res) = foldl next (0, \"\") ais\n if si < 0 then\n putStrLn $ map inv res\n else\n putStrLn res\n\n\n"}], "negative_code": [{"source_code": "next :: (Integer, String) -> Integer -> (Integer, String)\nnext (s, r) a\n | s < 0 = (s + a, r ++ \"+\")\n | s >= 0 = (s - a, r ++ \"-\")\n\ninv :: Char -> Char\ninv '-' = '+'\ninv '+' = '-'\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ais <- fmap (map read . reverse . words) getLine\n let (si, res) = foldl next (0, \"\") ais\n if si < 0 then\n putStrLn $ map inv res\n else\n putStrLn res\n\n\n"}], "src_uid": "30f64b963310911196ebf5d624c01cc3"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tlet\n\t\tres = solve n\n\tprint $ length res\n\tputStrLn $ unwords $ map show res\n\n\nsolve 2 = [ 2 ]\nsolve 3 = [ 3 ]\nsolve n = 2 : solve ( n - 2 )\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ngetInt = read `fmap` getLine :: IO Int\n\nmain = do\n n <- getInt\n let ps = fact n\n print $ length ps\n forM_ ps $ \\p -> do\n putStr (show p)\n putChar ' '\n\nfact n\n | even n = m\n | otherwise = 3 : tail m\n where m = replicate (n `div` 2) 2\n"}, {"source_code": "main :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n if n < 4\n then do\n putStrLn \"1\"\n putStrLn (show n)\n else do\n let r = (n `div` 2)\n print r\n mapM_ (\\_ -> do\n putStr \"2 \"\n ) [1..(r-2)]\n putStr \"2 \"\n if (n `mod` 2) == 1 then putStrLn \"3\" else putStrLn \"2\"\n"}, {"source_code": "sol :: Int -> IO ()\nsol n = do\n mapM_ putStr [\"2 \" | _ <- [1..((n `div` 2) - 1)]]\n if (n `mod` 2 == 0)\n then putStrLn \"2\"\n else putStrLn \"3\"\n\nmain :: IO ()\nmain = do\n n <- getLine\n let ni = read n :: Int\n print (ni `div` 2)\n sol ni\n"}, {"source_code": "import Data.List\n\nsol :: Int -> IO ()\nsol n = do\n mapM_ putStr (replicate ((n `div` 2) - 1) \"2 \")\n if (n `mod` 2 == 0)\n then putStrLn \"2\"\n else putStrLn \"3\"\n\nmain :: IO ()\nmain = do\n n <- getLine\n let ni = read n :: Int\n print (ni `div` 2)\n sol ni\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInt).C.words<$>C.getLine))\nsolve [x] = let f=x `mod` 2; d=x `div` 2 in if f== 0 then print d>>putStr (unwords $ map show $ take d (repeat 2)) else print (d)>>putStr (unwords $ map show $ (++) [3] $ take (d-1) (repeat 2)) "}, {"source_code": "main = getLine >>= putStrLn . calc . read\n\n\ncalc :: Int -> String\ncalc n = unlines ans\n where ans = [show k, unwords $ map show (calc' $ n - 2)]\n k = n `div` 2\n calc' 1 = [3]\n calc' 0 = [2]\n calc' n = 2:(calc' $ n - 2)"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nsolve :: Int -> [Int]\nsolve 2 = [2]\nsolve 3 = [3]\nsolve x = 2 : solve (x - 2)\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n let answer = solve n\n printf \"%d\\n\" $ length answer\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n\nmain=do\n a<-read <$> getLine::IO Int\n let b = (div a 2)\n print b\n putStrLn $ intercalate \" \" $ map show $ (replicate (b-1) 2) ++ [(if mod a 2==1 then 3 else 2)]\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nformat (a, b) = show a ++ \"\\n\" ++ (unwords $ map show b)\n\nsolve :: Int -> (Int, [Int])\nsolve x\n | even x = (n, replicate n 2)\n | otherwise = (n, 3 : replicate (n - 1) 2) \n where n = div x 2\n\nmain :: IO ()\nmain = do\n x <- readInt\n putStrLn $ format $ solve x"}, {"source_code": "main = do\n n <- readLn\n let d = n `div` 2\n if even n\n then do\n print d\n putStrLn $ unwords $ replicate d \"2\"\n else do\n print d\n putStrLn $ unwords $ \"3\" : replicate (d-1) \"2\"\n"}, {"source_code": "import Control.Monad( replicateM_)\nmain = do\n k_ <- readLn\n let solve k = let (d,m) = k `divMod` 2 in if m==0\n\t\t then do\n\t\t\tprint d\n\t\t\treplicateM_ d (putStr \"2 \")\n\t\t else do\n\t\t\tprint d\n\t\t\treplicateM_ (d-1) (putStr \"2 \")\n\t\t\tprint 3\n solve k_\n"}, {"source_code": "module Main where\n solve :: Integer -> [Integer]\n solve x = if x <= 3 then [x] else [2] ++ solve (x - 2) \n \n main :: IO ()\n main = do\n l <- getLine\n let n = read l :: Integer\n ans = solve n\n res = concat $ map (\\x -> show x ++ \" \") $ ans\n print $ length ans\n putStrLn res\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\nsolve :: Int -> [Int]\nsolve 0 = []\nsolve n | odd n = 3 : solve (n - 3)\n | otherwise = 2 : solve (n - 2)\n\nmain = do\n n <- read <$> getLine\n let a = solve n\n print $ length a\n putStrLn $ intercalate \" \" (map show a)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nmain= do\n\tn<- read <$> getLine ::IO Int\n\tlet c= div n 2\n\tlet d= concat $ replicate (c-1) \"2 \"\n\tlet e = if (mod n 2 ==0 ) then \"2 \" else \"3 \"\n\tprint c\n\tputStrLn $ e++d\n \t\n\n"}, {"source_code": "--ghc 7.10\n\nbachgold :: Int -> [Int]\nbachgold 2 = [2]\nbachgold 3 = [3]\nbachgold n = 2:bachgold (n-2)\n\nmain = do\n nStr <- getLine\n let n = read nStr :: Int\n let a = bachgold n\n print . length $ a\n putStrLn . unwords . map show $ a\n\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n-- Meat\n\nsolve :: Int -> [[Int]]\nsolve n = [[length d], d]\n where d = decompose n\n\ndecompose :: Int -> [Int]\ndecompose 2 = [2]\ndecompose 3 = [3]\ndecompose x = 2 : decompose (x - 2)\n\n-- Shit\nmain :: IO ()\nmain = do\n [n] <- readShit\n printShit $ solve n\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "solve n | n > 3 = 2 : solve (n-2)\n | otherwise = [n]\n \nprintList [x] = print x\nprintList (x : xs) = do\n putStr $ show x\n putStr \" \"\n printList xs\n \nmain = do\n s <- getContents\n let n = read s\n let l = solve n\n print $ length l\n printList l\n"}], "negative_code": [{"source_code": "import Data.List\n\nsol :: Int -> [Int]\nsol n = if n == 3\n then [3]\n else 2:(sol (n-2))\n\n\nmain :: IO ()\nmain = do\n n <- getLine\n putStrLn (intercalate \" \" (map show (sol (read n :: Int))))\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = readInt >>= putStrLn . unwords . map show . solve\n\nsolve 2 = [ 2 ]\nsolve 3 = [ 3 ]\nsolve n = 2 : solve ( n - 2 )\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n\nmain=do\n a<-read <$> getLine::IO Int\n print $ (div a 2) +(mod a 2)\n"}, {"source_code": "main = do\n n <- readLn\n let d = n `div` 2\n if even n\n then do\n print d\n putStrLn $ unwords $ replicate d \"2\"\n else do\n print (d+1)\n putStrLn $ unwords $ \"3\" : replicate d \"2\"\n"}], "src_uid": "98fd00d3c83d4b3f0511d8afa6fdb27b"} {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (sort)\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map solve >>> unlines\r\n\r\nsolve :: String -> String\r\nsolve s\r\n | null fs = s\r\n | not (null fs1) = let o = fst (head fs1) in o : filter (/= o) (suf $ (a, fa) : fs)\r\n | fa <= 2 = repl fa a ++ suf fs\r\n | fa - 2 <= n - fa = a : interleave (repl (fa - 1) a) (suf fs)\r\n | length fs == 1 = a : suf fs ++ repl (fa - 1) a\r\n | otherwise = case fs of\r\n (b, fb) : (c, fc) : fs' ->\r\n a : b : suf ((a, fa - 1) : (c, 1) : (b, fb - 1) : (c, fc - 1) : fs')\r\n where\r\n n = length s\r\n (a, fa) : fs = [(c, f) | c <- ['a' .. 'z'], let f = count c s, f > 0]\r\n fs1 = filter ((== 1) . snd) $ (a, fa) : fs\r\n suf = concatMap (uncurry (flip repl))\r\n\r\ninterleave :: [a] -> [a] -> [a]\r\ninterleave [] ys = ys\r\ninterleave (x : xs) ys = x : interleave ys xs\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount a = length . filter (== a)\r\n\r\nrepl = replicate\r\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (sort)\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map solve >>> unlines\r\n\r\nsolve :: String -> String\r\nsolve s\r\n | null fs = s\r\n | not (null fs1) = let o = fst (head fs1) in o : filter (/= o) (suf $ (a, fa) : fs)\r\n | fa <= 2 = repl fa a ++ suf fs\r\n | fa - 2 <= n - fa = a : interleave (repl (fa - 1) a) (suf fs)\r\n | length fs == 1 = a : suf fs ++ repl (fa - 1) a\r\n | otherwise = case fs of\r\n (b, fb) : (c, fc) : fs' ->\r\n a : b : suf ((a, fa - 1) : (c, 1) : (b, fb - 1) : (c, fc - 1) : fs')\r\n where\r\n n = length s\r\n (a, fa) : fs = [(c, f) | c <- ['a' .. 'z'], let f = count c s, f > 0]\r\n fs1 = filter ((== 1) . snd) $ (a, fa) : fs\r\n suf = concatMap (uncurry (flip repl))\r\n\r\ninterleave :: [a] -> [a] -> [a]\r\ninterleave [] ys = ys\r\ninterleave (x : xs) ys = x : interleave ys xs\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount a = length . filter (== a)\r\n\r\nrepl = replicate\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\ntype UAC = UArray Char Int\n\nisOK :: UAC -> Char -> Char -> Char -> Bool\nisOK cts c1 c2 prev = if c1 == c2\n then let\n n = foldl' (+) 0 $ elems cts\n needed = if c1 == prev then 2 * cts ! c1 else 2 * cts ! c1 - 1\n in n >= needed\n else c1 /= prev || cts ! c2 == 0\n || or [ct > 0 | (c, ct) <- assocs cts, c /= c1 && c /= c2]\n\nnextC :: UAC -> Char -> Char -> Char -> Char\nnextC cts c1 c2 prev = head $ do\n (curr, ct) <- assocs cts\n guard $ ct > 0 -- can use char\n guard $ prev /= c1 || curr /= c2 -- no immediate issue\n guard $ isOK (cts // [(curr, ct - 1)]) c1 c2 curr -- no later issue\n pure curr\n\nstep :: Char -> Char -> (UAC, Int, Char) -> Maybe (Char, (UAC, Int, Char))\nstep _ _ (_, 0, _) = Nothing\nstep c1 c2 (!cts, !n, !prev) = let\n curr = nextC cts c1 c2 prev\n in Just (curr, (cts // [(curr, cts ! curr - 1)], n - 1, curr))\n\nconcatArr :: UAC -> String\nconcatArr arr = do\n (c, ct) <- assocs arr\n replicate ct c\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n s <- readLine\n let\n cts :: UAC\n cts = runSTUArray $ do\n arr <- newArray ('a', 'z') 0\n (\\fun -> arr <$ P.foldr fun (pure ()) s) $ \\c act -> do\n v <- readArray arr c\n writeArray arr c (v + 1)\n act\n n = foldl' (+) 0 $ elems cts\n uniqs = [c | (c, 1) <- assocs cts]\n ans = case uniqs of\n c : _ -> c : concatArr (cts // [(c, 0)])\n [] -> let\n present = [c | (c, ct) <- assocs cts, ct > 0]\n in case present of\n [] -> error \"empty input?\"\n [c] -> replicate n c\n c1 : _ -> let\n rcts = cts // [(c1, cts ! c1 - 1)]\n c2 = head [c | (c, ct) <- assocs rcts, ct > 0,\n isOK (rcts // [(c, ct - 1)]) c1 c c]\n nrcts = rcts // [(c2, rcts ! c2 - 1)]\n in c1 : c2 : unfoldr (step c1 c2) (nrcts, n - 2, c2)\n lift $ B.hPutBuilder stdout $ B.string7 ans <> B.char7 '\\n'\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf testCase)\r\n\r\ntype Str = C.ByteString\r\n\r\ntestCase :: Scanner Str\r\ntestCase = C.pack . solve <$> bstr\r\n\r\nsolve :: Str -> String\r\nsolve s\r\n | null fs = C.unpack s\r\n | not (null fs1) = let o = fst (head fs1) in o : filter (/= o) (suf $ (a, fa):fs)\r\n | fa <= 2 = repl fa a ++ suf fs\r\n | fa - 2 <= n - fa = a : interleave (repl (fa - 1) a) (suf fs)\r\n | length fs == 1 = a : suf fs ++ repl (fa - 1) a\r\n | otherwise = case fs of\r\n (b, fb) : (c, fc) : fs' ->\r\n a : b : suf ((a, fa - 1) : (c, 1) : (b, fb - 1) : (c, fc - 1) : fs')\r\n where\r\n n = fi $ C.length s\r\n (a, fa) : fs = [(c, fi f) | c <- ['a' .. 'z'], let f = C.count c s, f > 0]\r\n fs1 = filter ((== 1) . snd) $ (a, fa) : fs\r\n suf = concatMap (uncurry (flip repl))\r\n\r\ninterleave :: [a] -> [a] -> [a]\r\ninterleave [] ys = ys\r\ninterleave (x : xs) ys = x : interleave ys xs\r\n\r\nfi = fromIntegral\r\nrepl = replicate\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf testCase)\r\n\r\ntype Str = C.ByteString\r\n\r\ntestCase :: Scanner Str\r\ntestCase = C.pack . solve <$> bstr\r\n\r\nsolve :: Str -> String\r\nsolve s\r\n | null fs = C.unpack s\r\n | fa <= 2 = repl fa a ++ suf fs\r\n | fa - 2 <= n - fa = a : interleave (repl (fa - 1) a) (suf fs)\r\n | length fs == 1 = a : suf fs ++ repl (fa - 1) a\r\n | otherwise = case fs of\r\n (b, fb) : (c, fc) : fs' ->\r\n a : b : suf ((a, fa - 1) : (c, 1) : (b, fb - 1) : (c, fc - 1) : fs')\r\n where\r\n n = fi $ C.length s\r\n (a, fa) : fs = sort [(c, fi f) | c <- ['a' .. 'z'], let f = C.count c s, f > 0]\r\n suf = concatMap (\\(c, f) -> repl f c)\r\n\r\ninterleave :: [a] -> [a] -> [a]\r\ninterleave [] ys = ys\r\ninterleave (x : xs) ys = x : interleave ys xs\r\n\r\nfi = fromIntegral\r\nrepl = replicate\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf testCase)\r\n\r\ntype Str = C.ByteString\r\n\r\ntestCase :: Scanner Str\r\ntestCase = solve <$> bstr\r\n\r\nsolve :: Str -> Str\r\nsolve s\r\n | null fs = s\r\n | fa <= 2 = C.pack $ repl fa a ++ suf\r\n | fa - 2 > n - fa = C.pack $ interleave (repl fa a) suf\r\n | otherwise = C.pack $ 'a' : interleave (repl (fa - 1) a) suf\r\n where\r\n n = fi $ C.length s\r\n (a, fa) : fs = sort [(c, fi $ C.count c s) | c <- ['a' .. 'z']]\r\n suf = concatMap (\\(c, f) -> repl f c) fs\r\n interleave [] ys = ys\r\n interleave (x : xs) ys = x : interleave ys xs\r\n\r\nfi = fromIntegral\r\nrepl = replicate\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf testCase)\r\n\r\ntype Str = C.ByteString\r\n\r\ntestCase :: Scanner Str\r\ntestCase = solve <$> bstr\r\n\r\nsolve :: Str -> Str\r\nsolve s\r\n | null fs = s\r\n | fa <= 2 = C.pack $ repl fa a ++ suf\r\n | otherwise = C.pack $ 'a' : interleave (repl (fa - 1) a) suf\r\n where\r\n (a, fa) : fs = sort [(c, C.count c s) | c <- ['a' .. 'z']]\r\n suf = concatMap (\\(c, f) -> repl f c) fs\r\n repl n x = replicate (fromIntegral n) x\r\n interleave [] ys = ys\r\n interleave (x : xs) ys = x : interleave ys xs\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nbucketSort :: (Char, Char) -> P.ByteString -> (Int, String, UArray Char Int)\nbucketSort bnds s = let\n counts :: UArray Char Int\n counts = runSTUArray $ do\n arr <- newArray bnds 0\n (\\fun -> arr <$ P.foldr fun (pure ()) s) $ \\c act -> do\n v <- readArray arr c\n writeArray arr c (v + 1)\n act\n n = foldl' (+) 0 $ elems counts\n ss = do\n (c, ct) <- assocs $ counts\n replicate ct c\n in (n, ss, counts)\n\ngo :: String -> String -> String -> String\ngo [] xs ys = xs ++ ys\ngo as xs [] = xs ++ as\ngo (a:as) xs (y:ys) = a : y : go as xs ys\n\nsolve :: String -> String -> String -> String\nsolve as [] [] = as\nsolve (a:as) (x:xs) ys = a : x : go as xs ys\nsolve _ _ _ = error \"yikes\"\n\ngo2 :: String -> String -> String\ngo2 [] xs = xs\ngo2 [a] [] = [a]\ngo2 (a : as) (x : xs) = a : x : go2 as xs\ngo2 _ _ = error \"yikes2:go\"\n\nsolve2 :: String -> String -> String\nsolve2 [] [] = []\nsolve2 (a : as) xs = a : go2 as xs\nsolve2 _ _ = error \"yikes2\"\n\nsolve1 :: UArray Char Int -> Maybe String\nsolve1 arr = case [c | (c, 1) <- assocs arr] of\n [] -> Nothing\n c : _ -> Just $ c : do\n (cc, ct) <- assocs arr\n guard $ cc /= c\n replicate ct cc\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n s <- readLine\n let\n (n, w, cts) = bucketSort ('a', 'z') s\n tarc = head w\n key : unsa : sau = group w ++ replicate 3 []\n sa = concat sau\n ans = case solve1 cts of\n Just v -> v\n Nothing -> if 2 * (cts ! tarc - 1) > n\n then solve key unsa sa\n else solve2 key (unsa ++ sa)\n lift $ B.hPutBuilder stdout $ B.string7 ans <> B.char7 '\\n'\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nbucketSort :: (Char, Char) -> P.ByteString -> (Int, String, UArray Char Int)\nbucketSort bnds s = let\n counts :: UArray Char Int\n counts = runSTUArray $ do\n arr <- newArray bnds 0\n (\\fun -> arr <$ P.foldr fun (pure ()) s) $ \\c act -> do\n v <- readArray arr c\n writeArray arr c (v + 1)\n act\n n = foldl' (+) 0 $ elems counts\n ss = do\n (c, ct) <- assocs $ counts\n replicate ct c\n in (n, ss, counts)\n\ngo :: String -> String -> String -> String\ngo [] xs ys = xs ++ ys\ngo as xs [] = xs ++ as\ngo (a:as) xs (y:ys) = a : y : go as xs ys\n\nsolve :: String -> String -> String -> String\nsolve as [] [] = as\nsolve (a:as) (x:xs) ys = a : x : go as xs ys\nsolve _ _ _ = error \"yikes\"\n\ngo2 :: String -> String -> String\ngo2 [] xs = xs\ngo2 [a] [] = [a]\ngo2 (a : as) (x : xs) = a : x : go2 as xs\ngo2 _ _ = error \"yikes2:go\"\n\nsolve2 :: String -> String -> String\nsolve2 [] [] = []\nsolve2 (a : as) xs = a : go2 as xs\nsolve2 _ _ = error \"yikes2\"\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n s <- readLine\n let\n (n, w, cts) = bucketSort ('a', 'z') s\n tarc = head w\n key : unsa : sau = group w ++ replicate 3 []\n sa = concat sau\n ans = if 2 * (cts ! tarc - 1) > n\n then solve key unsa sa\n else solve2 key (unsa ++ sa)\n lift $ B.hPutBuilder stdout $ B.string7 ans <> B.char7 '\\n'\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}], "src_uid": "80fd03a1cbdef86a5f00ada85e026890"} {"source_code": "import Data.List\nimport Control.Applicative\nimport qualified Data.Map as Map\nimport qualified Data.ByteString.Char8 as BS\n\ngetToken :: IO String \ngetToken = do\n c <- getChar\n if c == '\\n' || c == ' '\n then\n return []\n else do\n cs <- getToken\n return (c:cs)\n\nnextInt :: IO Int\nnextInt = do\n token <- getToken\n return (read token :: Int)\n\nnextIntList :: IO [Int]\nnextIntList = do\n list <- fmap words getLine\n return $ fmap read list\n\nnextDouble :: IO Double\nnextDouble = do\n token <- getToken\n return (read token :: Double)\n\nnextDoubleList :: IO [Double]\nnextDoubleList = do\n list <- fmap words getLine\n return $ fmap read list\n\nmain = do\n getLine\n v2 <- (map BS.readInt . BS.words) <$> BS.getLine\n let v = [x | (Just (x, _)) <- v2]\n-- v <- nextIntList\n m <- nextInt\n let\n v1 = scanl (+) 0 (fmap fromIntegral v) :: [Integer]\n v2 = scanl (+) 0 (fmap fromIntegral (sort v)) :: [Integer]\n let map1 = Map.fromList $ zip [0 ..] v1\n let map2 = Map.fromList $ zip [0 ..] v2\n loop m map1 map2\n where\n loop 0 _ _ = return ()\n loop m map1 map2 = do\n t <- nextInt\n l <- nextInt\n r <- nextInt\n if t == 1\n then\n print $ (map1 Map.! r) - (map1 Map.! (l-1))\n else\n print $ (map2 Map.! r) - (map2 Map.! (l-1))\n loop (m-1) map1 map2\n\n\nmargeSort :: (Ord a) => [a] -> [a]\nmargeSort [] = [] \nmargeSort list = help xs ys\n where\n (xs,ys) = splitAt ((length list) `div` 2) list\n help xs [] = xs\n help [] ys = ys\n help xs ys = marge (margeSort xs) (margeSort ys)\n\nsupersum :: [Int] -> Integer\nsupersum [] = error \"empty\"\nsupersum list = sum $ (fmap fromIntegral list)\n\nmarge :: (Ord a) => [a] -> [a] -> [a]\nmarge xs [] = xs\nmarge [] ys = ys\nmarge (x:xs) (y:ys)\n | x < y = x:(marge xs (y:ys))\n | otherwise = y:(marge (x:xs) ys)\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.Array.IArray as I\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\n\n\ngetSub :: Array Int Integer -> Int -> Int -> Integer\ngetSub arr l r = (arr I.! r) - (arr I.! (l - 1))\n \nmain = do\n n <- read <$> getLine\n stones::[Integer] <- map read . words <$> getLine \n m <- read <$> getLine\n let\n a1 = I.listArray (0, n) $ (scanl (+) 0 stones)\n a2 = I.listArray (0, n) $ (scanl (+) 0 (sort stones))\n forM_ [1..m] $ \\_ -> do\n [t, l, r] <- map read . words <$> getLine\n let a = if t == 1 then a1 else a2\n print $ getSub a l r \n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\ngetToken :: IO String \ngetToken = do\n\tc <- getChar\n\tif c == '\\n' || c == ' '\n\t\tthen\n\t\t\treturn []\n\t\telse do\n\t\t\tcs <- getToken\n\t\t\treturn (c:cs)\n\nnextInt :: IO Int\nnextInt = do\n\ttoken <- getToken\n\treturn (read token :: Int)\n\nnextIntList :: IO [Int]\nnextIntList = do\n\tlist <- fmap words getLine\n\treturn $ fmap read list\n\nnextDouble :: IO Double\nnextDouble = do\n\ttoken <- getToken\n\treturn (read token :: Double)\n\nnextDoubleList :: IO [Double]\nnextDoubleList = do\n\tlist <- fmap words getLine\n\treturn $ fmap read list\n\nmain = do\n\tn <- nextInt\n\tv <- nextIntList\n\tm <- nextInt\n\tlet\n\t\tv1 = scanl (+) 0 (fmap fromIntegral v) :: [Integer]\n\t\tv2 = scanl (+) 0 (fmap fromIntegral (sort v)) :: [Integer]\n\tlet map1 = Map.fromList $ zip [0 ..] v1\n\tlet map2 = Map.fromList $ zip [0 ..] v2\n\tsequence_ [ nextInt >>= \\t -> nextInt >>= \\l -> nextInt >>= \\r ->\n\t\tif t == 1\n\t\tthen\n\t\t\tprint $ (map1 Map.! r) - (map1 Map.! (l-1))\n\t\telse\n\t\t\tprint $ (map2 Map.! r) - (map2 Map.! (l-1)) | _ <- [1..m]]\n\t\t\n\twhere\n\tloop 0 _ _ = return ()\n\tloop m map1 map2 = do\n\t\tt <- nextInt\n\t\tl <- nextInt\n\t\tr <- nextInt\n\t\tloop (m-1) map1 map2\n\n\nmargeSort :: (Ord a) => [a] -> [a]\nmargeSort [] = [] \nmargeSort list = help xs ys\n\twhere\n\t(xs,ys) = splitAt ((length list) `div` 2) list\n\thelp xs [] = xs\n\thelp [] ys = ys\n\thelp xs ys = marge (margeSort xs) (margeSort ys)\n\nsupersum :: [Int] -> Integer\nsupersum [] = error \"empty\"\nsupersum list = sum $ (fmap fromIntegral list)\n\nmarge :: (Ord a) => [a] -> [a] -> [a]\nmarge xs [] = xs\nmarge [] ys = ys\nmarge (x:xs) (y:ys)\n\t| x < y = x:(marge xs (y:ys))\n\t| otherwise = y:(marge (x:xs) ys)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\n\ngetToken :: IO String \ngetToken = do\n\tc <- getChar\n\tif c == '\\n' || c == ' '\n\t\tthen\n\t\t\treturn []\n\t\telse do\n\t\t\tcs <- getToken\n\t\t\treturn (c:cs)\n\nnextInt :: IO Int\nnextInt = do\n\ttoken <- getToken\n\treturn (read token :: Int)\n\nnextIntList :: IO [Int]\nnextIntList = do\n\tlist <- fmap words getLine\n\treturn $ fmap read list\n\nnextDouble :: IO Double\nnextDouble = do\n\ttoken <- getToken\n\treturn (read token :: Double)\n\nnextDoubleList :: IO [Double]\nnextDoubleList = do\n\tlist <- fmap words getLine\n\treturn $ fmap read list\n\nmain = do\n\tn <- nextInt\n\tv <- nextIntList\n\tm <- nextInt\n\tlet\n\t\tv1 = scanl (+) 0 (fmap fromIntegral v) :: [Integer]\n\t\tv2 = scanl (+) 0 (fmap fromIntegral (sort v)) :: [Integer]\n\tlet map1 = Map.fromList $ zip [0 ..] v1\n\tlet map2 = Map.fromList $ zip [0 ..] v2\n\tloop m map1 map2\n\twhere\n\tloop 0 _ _ = return ()\n\tloop m map1 map2 = do\n\t\tt <- nextInt\n\t\tl <- nextInt\n\t\tr <- nextInt\n\t\tif t == 1\n\t\tthen\n\t\t\tprint $ (map1 Map.! r) - (map1 Map.! (l-1))\n\t\telse\n\t\t\tprint $ (map2 Map.! r) - (map2 Map.! (l-1))\n\t\tloop (m-1) map1 map2\n\n\nmargeSort :: (Ord a) => [a] -> [a]\nmargeSort [] = [] \nmargeSort list = help xs ys\n\twhere\n\t(xs,ys) = splitAt ((length list) `div` 2) list\n\thelp xs [] = xs\n\thelp [] ys = ys\n\thelp xs ys = marge (margeSort xs) (margeSort ys)\n\nsupersum :: [Int] -> Integer\nsupersum [] = error \"empty\"\nsupersum list = sum $ (fmap fromIntegral list)\n\nmarge :: (Ord a) => [a] -> [a] -> [a]\nmarge xs [] = xs\nmarge [] ys = ys\nmarge (x:xs) (y:ys)\n\t| x < y = x:(marge xs (y:ys))\n\t| otherwise = y:(marge (x:xs) ys)\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Control.Applicative\nimport qualified Data.Map as Map\nimport qualified Data.ByteString.Char8 as BS\n\ngetToken :: IO String \ngetToken = do\n c <- getChar\n if c == '\\n' || c == ' '\n then\n return []\n else do\n cs <- getToken\n return (c:cs)\n\nnextInt :: IO Int\nnextInt = do\n token <- getToken\n return (read token :: Int)\n\nnextIntList :: IO [Int]\nnextIntList = do\n list <- fmap words getLine\n return $ fmap read list\n\nnextDouble :: IO Double\nnextDouble = do\n token <- getToken\n return (read token :: Double)\n\nnextDoubleList :: IO [Double]\nnextDoubleList = do\n list <- fmap words getLine\n return $ fmap read list\n\nmain = do\n getLine\n v2 <- (map BS.readInt . BS.words) <$> BS.getLine\n let v = [x | (Just (x, _)) <- v2]\n m <- nextInt\n let\n v1 = scanl (+) 0 (fmap fromIntegral v) :: [Int64]\n v2 = scanl (+) 0 (fmap fromIntegral (sort v)) :: [Int64]\n let map1 = Map.fromList $ zip [0 ..] v1\n let map2 = Map.fromList $ zip [0 ..] v2\n loop m map1 map2\n where\n loop 0 _ _ = return ()\n loop m map1 map2 = do\n t <- nextInt\n l <- nextInt\n r <- nextInt\n if t == 1\n then\n print $ (map1 Map.! r) - (map1 Map.! (l-1))\n else\n print $ (map2 Map.! r) - (map2 Map.! (l-1))\n loop (m-1) map1 map2\n\n\nmargeSort :: (Ord a) => [a] -> [a]\nmargeSort [] = [] \nmargeSort list = help xs ys\n where\n (xs,ys) = splitAt ((length list) `div` 2) list\n help xs [] = xs\n help [] ys = ys\n help xs ys = marge (margeSort xs) (margeSort ys)\n\nsupersum :: [Int] -> Integer\nsupersum [] = error \"empty\"\nsupersum list = sum $ (fmap fromIntegral list)\n\nmarge :: (Ord a) => [a] -> [a] -> [a]\nmarge xs [] = xs\nmarge [] ys = ys\nmarge (x:xs) (y:ys)\n | x < y = x:(marge xs (y:ys))\n | otherwise = y:(marge (x:xs) ys)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n vs <- map fromIntegral <$> getInts :: IO [Int64]\n m <- readLn\n qs <- replicateM m getInts\n\n let\n a = listArray (0, n) $ scanl (+) 0 vs\n b = listArray (0, n) $ scanl (+) 0 $ sort vs\n\n query [1, l, r] = a!r - a!(l-1)\n query [2, l, r] = b!r - b!(l-1)\n\n putStrLn $ unlines $ map show $ map query qs\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n vs <- map fromIntegral <$> getInts :: IO [Int64]\n m <- readLn\n qs <- replicateM m getInts\n\n let\n a = listArray (0, n) $ scanl (+) 0 vs :: UArray Int Int64\n b = listArray (0, n) $ scanl (+) 0 $ sort vs :: UArray Int Int64\n\n query [1, l, r] = a!r - a!(l-1)\n query [2, l, r] = b!r - b!(l-1)\n\n putStrLn $ unlines $ map show $ map query qs\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n vs <- map fromIntegral <$> getInts :: IO [Int64]\n m <- readLn\n qs <- replicateM m getInts\n\n let\n a = listArray (0, n) $ scanl (+) 0 vs :: UArray Int Int64\n b = listArray (0, n) $ scanl (+) 0 $ sort vs :: UArray Int Int64\n\n query [1, l, r] = a!r - a!(l-1)\n query [2, l, r] = b!r - b!(l-1)\n\n putStrLn $ unlines $ map show $ map query qs\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Data.Int\n\nimport Data.Array.IO\nimport Data.Bits ( (.|.), (.&.) )\n\nupdate arr at by = do\n (_,hi) <- getBounds arr\n let loop i | i > hi = return ()\n loop i = do v <- readArray arr i\n writeArray arr i (v+by)\n loop (i .|. (i+1))\n loop at\n\nquery0 arr at = do\n (lo,_) <- getBounds arr\n let loop !s i | i < lo = return s\n loop !s i = do v <- readArray arr i\n loop (s+v) ((i .&. (i+1)) -1)\n loop 0 at\n\nquery arr i0 i1 = do\n s0 <- query0 arr (i0-1)\n s1 <- query0 arr i1\n return (s1-s0)\n\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshowArray label arr = do\n putStr $ label ++ \":\"\n (lo,hi) <- getBounds arr\n forM_ [lo..hi] $ \\i -> do\n v <- readArray arr i\n putStr $ \" \" ++ show v\n putStrLn \"\"\n\nmain = do\n n <- fmap read getLine\n nums <- fmap (parseInts n) BS.getLine\n a1 <- newArray (0,n) 0 :: IO (IOUArray Int Int64)\n a2 <- newArray (0,n) 0 :: IO (IOUArray Int Int64)\n forM_ (zip [1..] nums) $ \\(i,v) -> update a1 i (fromIntegral v)\n forM_ (zip [1..] (sort nums)) $ \\(i,v) -> update a2 i (fromIntegral v)\n\n -- showArray \"a1\" a1\n -- showArray \"a2\" a2\n\n k <- fmap read getLine\n replicateM_ k $ do\n (q:a:b:_) <- fmap (parseInts 3) BS.getLine\n if q == 1\n then query a1 a b >>= print\n else query a2 a b >>= print\n\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\nmain = do\n n <- readLn\n vs <- map read . words <$> getLine\n let s = listArray (0,n) $ scanl (+) 0 vs\n c = listArray (0,n) $ scanl (+) 0 (sort vs)\n m <- readLn\n replicateM_ m $ do\n [t,l,r] <- map read . words <$> getLine\n let a = [c,s] !! fromEnum (t == 1)\n print $ a!r - a!(l-1)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n vs <- getInts\n m <- readLn\n qs <- replicateM m getInts\n\n let\n a = listArray (0, n) $ scanl (+) 0 vs\n b = listArray (0, n) $ scanl (+) 0 $ sort vs\n\n query [1, l, r] = a!r - a!(l-1)\n query [2, l, r] = b!r - b!(l-1)\n\n putStrLn $ unlines $ map show $ map query qs\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nimport Data.Array.IO\nimport Data.Bits ( (.|.), (.&.) )\n\nupdate arr at by = do\n (_,hi) <- getBounds arr\n let loop i | i > hi = return ()\n loop i = do v <- readArray arr i\n writeArray arr i (v+by)\n loop (i .|. (i+1))\n loop at\n\nquery0 arr at = do\n (lo,_) <- getBounds arr\n let loop !s i | i < lo = return s\n loop !s i = do v <- readArray arr i\n loop (s+v) ((i .&. (i+1)) -1)\n loop 0 at\n\nquery arr i0 i1 = do\n s0 <- query0 arr (i0-1)\n s1 <- query0 arr i1\n return (s1-s0)\n\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nshowArray label arr = do\n putStr $ label ++ \":\"\n (lo,hi) <- getBounds arr\n forM_ [lo..hi] $ \\i -> do\n v <- readArray arr i\n putStr $ \" \" ++ show v\n putStrLn \"\"\n\nmain = do\n n <- fmap read getLine\n nums <- fmap (parseInts n) BS.getLine\n a1 <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n a2 <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n forM_ (zip [1..] nums) $ \\(i,v) -> update a1 i v\n forM_ (zip [1..] (sort nums)) $ \\(i,v) -> update a2 i v\n\n -- showArray \"a1\" a1\n -- showArray \"a2\" a2\n\n k <- fmap read getLine\n replicateM_ k $ do\n (q:a:b:_) <- fmap (parseInts 3) BS.getLine\n if q == 1\n then query a1 a b >>= print\n else query a2 a b >>= print\n\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n getLine -- n\n vs <- map read . words <$> getLine\n let s = scanl (+) 0 vs\n c = scanl (+) 0 (sort vs)\n m <- readLn\n replicateM_ m $ do\n [t,l,r] <- map read . words <$> getLine\n let a = [c,s] !! fromEnum (t == 1)\n print $ a!!l - a!!r\n"}], "src_uid": "c764b9f87cb5e5872eb157c3d2b7f3c5"} {"source_code": "parse :: String -> [[Integer]]\r\nparse = map (map read . words) . go . tail . lines\r\n where\r\n go [] = []\r\n go (_:y:ys) = y : go ys\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve = any (not . square)\r\n where\r\n square x = (==x) . (^ 2) . floor . sqrt $ fromIntegral x\r\n\r\nformat :: [Bool] -> String\r\nformat = unlines . map go\r\n where\r\n go True = \"YES\"\r\n go False = \"NO\"\r\n\r\nmain = interact $ format . map solve . parse\r\n", "positive_code": [{"source_code": "parse :: String -> [[Integer]]\r\nparse = map (map read . words) . go . tail . lines\r\n where\r\n go [] = []\r\n go (_:y:ys) = y : go ys\r\n\r\nsolve :: [Integer] -> Bool\r\nsolve = any (not . square)\r\n where\r\n square n = r * r == n\r\n where r = floor . sqrt $ fromIntegral n\r\n\r\nformat :: [Bool] -> String\r\nformat = unlines . map go\r\n where\r\n go x = if x then \"YES\" else \"NO\"\r\n\r\nmain = interact $ format . map solve . parse\r\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nisntPerfectSquare::Integer->Bool \r\nisntPerfectSquare x = (floor (sqrt (fromIntegral x)) )*(floor (sqrt (fromIntegral x))) /= x\r\n\r\nsolve = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n putStrLn $ if any isntPerfectSquare a then \"YES\" else \"NO\"\r\n \r\nmain = do\r\n t<-readLn ::IO Int\r\n replicateM_ t solve "}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Numeric.Natural\r\nimport Data.Maybe\r\n\r\nintNat :: Natural -> Int\r\nintNat = fromInteger . toInteger\r\n\r\nisPerfectSquare :: Natural -> Bool\r\nisPerfectSquare n = aux1 $ aux2 2 (n, True) where\r\n\taux1 (n, b) = if n > 1 then False else b\r\n\r\n\taux2 i (n, b) | i * i > n = (n, b)\r\n\taux2 i (n, b) = aux2 (i+1) $ n' n b where\r\n\t\tn' n b\r\n\t\t\t| mod n i /= 0 = (n, b)\r\n\t\t\t| mod n (i*i) == 0 = n' (div n (i*i)) b\r\n\t\t\t| otherwise = (div n i, False)\r\n\r\nsolve list = foldr (||) False $ fmap (not . isPerfectSquare) list\r\n\r\n\r\nshowR :: Bool -> String\r\nshowR False = \"NO\"\r\nshowR True = \"YES\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Natural]\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Natural]\r\n\t\tputStrLn $ showR $ solve a\r\n\r\n\t\t"}], "negative_code": [], "src_uid": "33a31edb75c9b0cf3a49ba97ad677632"} {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (m*2) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n [1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = (reverse acc)++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n", "positive_code": [{"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.List\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (m*2) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n [1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = (reverse acc)++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Irene Vlassi-Pandi (03108137) -}\n{- ex1-plII-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\n{- \u03c5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 \u03b1\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03bf\u03c5 \u03b1\u03c0\u03cc:\n - http://codeforces.com/blog/entry/610 -}\n\nimport Data.List\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (2*m) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\nmulti n w ls \n | 1 > w || w > sum ls = []\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++multiH (delete 1 ls) (delete j inds) []++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n [1]++multiH [nl2] [1] []++multiH nls inds []++[1]++[2]++multiH [nl1] [0] []++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = reverse acc++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = reverse acc++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = reverse acc++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Irene Vlassi-Pandi (03108137) -}\n{- ex1-plII-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\n{- \u03c5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 \u03b1\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03bf\u03c5 \u03b1\u03c0\u03cc:\n - http://codeforces.com/blog/entry/610 -}\n\nimport Data.List\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (2*m) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n [1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = (reverse acc)++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Irene Vlassi-Pandi (03108137) -}\n{- ex1-plII-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\n{- algorithm by: -}\n{- http://codeforces.com/blog/entry/610 -}\n\nimport Data.List\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (2*m) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\nmulti n w ls \n | 1 > w || w > sum ls = []\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n (j+1):multiH (delete 1 ls) (delete j inds) []++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n 1:multiH [nl2] [1] []++multiH nls inds []++[1]++[2]++multiH [nl1] [0] []++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = reverse acc++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = reverse acc++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = reverse acc++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.List\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (m*2) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n [1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = (reverse acc)++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Irene Vlassi-Pandi (03108137) -}\n{- ex1-plII-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\n{- algorithm by: -}\n{- http://codeforces.com/blog/entry/610 -}\n\nimport Data.List\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc = multiH ms ns (replicate (2*m) (n+1):acc)\n\nmulti :: Int -> Int -> [Int] -> [Int]\nmulti n w ls \n | 1 > w || w > sum ls = []\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n (j+1):multiH (delete 1 ls) (delete j inds) []++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n 1:multiH [nl2] [1] []++multiH nls inds []++[1]++[2]++multiH [nl1] [0] []++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = reverse acc++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = reverse acc++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = reverse acc++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n [1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2] \n | w2 > 2 =\n let\n findli _ n3 2 [] z1 z2 _ acc = (reverse acc)++multi2 n3 2 [z1,z2] [] \n findli _ n3 w3 [] z1 z2 _ acc \n | z1 > 0 = findli 0 n3 (w3-1) [] (z1-1) z2 [] (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 [] 0 z2 [] acc \n | z2 > 0 = findli 1 n3 (w3-1) [] z1 (z2-1) [] (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 [] z1 0 [] acc \n findli _ n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}], "negative_code": [{"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate w 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n | j == n3 || w3 == 2 = (reverse acc)++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 = findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = findli 1 n3 w3 nnls 0 z2 acc \n | z2 > 0 && w3 > 2 && j == 1 = findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = findli 2 n3 w3 nnls z1 0 acc \n | nnl > 0 && w3 > 2 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 ((j+1):(j+1):acc)\n | nnl == 0 && w3 > 2 = findli (j+1) n3 w3 nnls z1 z2 acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate w 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n | j == n3 || w3 == 2 = (reverse acc)++[42]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 = findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = findli 1 n3 w3 nnls 0 z2 acc \n | z2 > 0 && w3 > 2 && j == 1 = findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = findli 2 n3 w3 nnls z1 0 acc \n | nnl > 0 && w3 > 2 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 ((j+1):(j+1):acc)\n | nnl == 0 && w3 > 2 = findli (j+1) n3 w3 nnls z1 z2 acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli _ n3 _ [] z1 z2 _ _ = multi2 n3 2 [z1,z2] [0,1] \n findli _ n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (0:1:i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n | j == n3 || w3 == 2 = (reverse acc)++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 = findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = findli 1 n3 w3 nnls 0 z2 acc \n | z2 > 0 && w3 > 2 && j == 1 = findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = findli 2 n3 w3 nnls z1 0 acc \n | nnl > 0 && w3 > 2 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 ((j+1):(j+1):acc)\n | nnl == 0 && w3 > 2 = findli (j+1) n3 w3 nnls z1 z2 acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n | j == n3 || w3 == 2 = (reverse acc)++multi2 n3 2 (z1:z2:(nnl:nnls)) (i:is) \n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 = findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 = findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate (2*w) 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli _ n3 _ [] z1 z2 _ _ = multi2 n3 2 [z1,z2] [0,1] \n findli j n3 2 nnls z1 z2 (i:is) acc = (reverse acc)++multi2 n3 2 (z1:z2:nnls) (0:1:i:is) \n findli 0 n3 w3 nnls z1 z2 (i:is) acc \n | z1 > 0 = findli 0 n3 (w3-1) nnls (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 = findli 1 n3 w3 nnls 0 z2 (i:is) acc \n findli 1 n3 w3 nnls z1 z2 (i:is) acc \n | z2 > 0 = findli 1 n3 (w3-1) nnls z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 = findli 2 n3 w3 nnls z1 0 (i:is) acc \n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n | j == n3 = (reverse acc)++multi2 n3 2 (z1:z2:nnl:nnls) (0:1:i:is) \n | nnl > 0 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 = findli (j+1) n3 w3 nnls z1 z2 is acc\n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n\n in\n findli 0 n2 w2 nls nl1 nl2 [2..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\n--prosoxh ta arnhtika opws ta diavazw na vazo parentheseis\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate w 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++(multiH (delete 1 ls) (delete (j+1) inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = (reverse acc)++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 = findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = findli 1 n3 w3 nnls 0 z2 acc \n | z2 > 0 && w3 > 2 && j == 1 = findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = findli 2 n3 w3 nnls z1 0 acc \n | nnl > 0 && w3 > 2 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 ((j+1):(j+1):acc)\n | nnl == 0 && w3 > 2 = findli (j+1) n3 w3 nnls z1 z2 acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n\n"}, {"source_code": "{- Vlassi-Pandi Irini (03108137) -}\n{- ex1-pl2-2012 -}\n{- http://codeforces.com/contest/26/problem/E -}\n\nimport Data.Char (isSpace)\nimport Data.List\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nmultiH :: [Int] -> [Int] -> [[Int]] -> [Int]\nmultiH [ ] _ acc = reverse (concat acc)\nmultiH _ [ ] acc = reverse (concat acc)\nmultiH (m:ms) (n:ns) acc \n | m/= 0 = multiH ms ns (replicate (m*2) (n+1):acc)\n | otherwise = []\n\nmulti :: Int -> Int -> [Int] -> [Int]\n\n--prosoxh ta arnhtika opws ta diavazw na vazo parentheseis\nmulti n w ls \n | 1 > w || w > (sum ls) = []\n\n\nmulti 1 w [l] \n | l == w = \n replicate w 1\n | otherwise = []\n\nmulti n 1 ls\n | n >= 2 = \n let\n js = findIndices (==1) ls \n inds = findIndices (/=(-1)) ls\n in \n if (js /= [])\n then\n let \n j = head js\n in\n [j+1]++[42]++(multiH (delete 1 ls) (delete j inds) [])++[j+1]\n else []\n\nmulti n w (l1:l2:ls) = \n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++[w3]++[j]\n | j == n3 || w3 == 2 = (reverse acc)++[42]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 = findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = findli 1 n3 w3 nnls 0 z2 acc \n | z2 > 0 && w3 > 2 && j == 1 = findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = findli 2 n3 w3 nnls z1 0 acc \n | nnl > 0 && w3 > 2 = findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 ((j+1):(j+1):acc)\n | nnl == 0 && w3 > 2 = findli (j+1) n3 w3 nnls z1 z2 acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n\n{-\nmulti n w (l1:l2:ls) \n | n >= 2 =\n let\n multi2 n2 w2 (nl1:nl2:nls) inds \n | w2 == 2 = \n ([1]++(multiH [nl2] [1] [])++(multiH nls inds [])++[1]++[2]++(multiH [nl1] [0] [])++[2]) \n | w2 > 2 =\n let\n findli j n3 w3 (nnl:nnls) z1 z2 (i:is) acc \n -- | otherwise = (reverse acc)++[z1]++[z2]++[nnl]++nnls++(i:is)++[w3]++[j]\n | j == n3 || w3 == 2 = [42]++(reverse acc)++[32]++multi2 n3 2 (z1:z2:(nnl:nnls)) [2..(n3-1)]\n -- | n == 1 || w == 2 = (reverse acc)++multi2 (n+1) w (l:ls) (i:is)\n | z1 > 0 && w3 > 2 && j == 0 =[j]++ findli 0 n3 (w3-1) ((nnl-1):nnls) (z1-1) z2 (i:is) (1:1:acc)\n | z1 == 0 && w3 > 2 && j == 0 = [j]++findli 1 n3 w3 nnls 0 z2 is acc \n | z2 > 0 && w3 > 2 && j == 1 = [j]++findli 1 n3 (w3-1) ((nnl-1):nnls) z1 (z2-1) (i:is) (2:2:acc)\n | z2 == 0 && w3 > 2 && j == 1 = [j]++findli 2 n3 w3 nnls z1 0 is acc \n | nnl > 0 && w3 > 2 && j /=0 && j /=1 =[j]++ findli j n3 (w3-1) ((nnl-1):nnls) z1 z2 (i:is) ((i+1):(i+1):acc)\n | nnl == 0 && w3 > 2 && j /=0 && j/=1 = [j]++findli (j+1) n3 w3 nnls z1 z2 is acc\n in\n findli 0 n2 w2 (nl1:nl2:nls) nl1 nl2 [0..(n2-1)] [] \n in\n multi2 n w ((l1-1):(l2-1):ls) [2..(n-1)]\n | otherwise = []\n\n-}\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (w, r2) = readInt r1\n let (x, _) = readMany readInt r2\n let answer = (multi n w x)\n print_yesno answer\n printList answer\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n print_yesno [] = putStrLn \"No\"\n print_yesno _ = putStrLn \"Yes\"\n printList [] = putStrLn\"\"\n printList (l:[]) = \n do\n putStrLn (show l)\n printList (l:ls) = \n do\n putStr (show l++ \" \")\n printList ls\n\n"}], "src_uid": "bf6e2310e4f808ca4c8ff28ba8a51a68"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n \ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn $ (show (n * 9) ++ \" \" ++ show (n * 8))", "positive_code": [{"source_code": "convert :: Read a => String -> [a]\nconvert = map read . words\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n] = convert line :: [Int]\n if n == 1 \n then putStrLn \"9 8\"\n else putStrLn $ (show $ 3 * n) ++ \" \" ++ (show $ 2 * n)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n | even n = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [n+4,4]\n\t | mod n 10 == 5 = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [n+10,10]\n\t | mod n 10 == 9 = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [n+21,21]\n\t | mod n 10 == 7 = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [n+33,33]\n\t | mod n 10 == 3 = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [n+27,27]\n\t | otherwise = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [n+9,9]\n\n\nmain = do\n\tn<- read <$> getLine ::IO Int\n\tprocess n\n\n\n"}, {"source_code": "process :: Int -> (Int, Int)\nprocess 1 = (9,8)\nprocess n = (3*n,2*n)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n let (a,b) = process n\n putStrLn (show a ++ \" \" ++ show b)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= putStrLn.unwords.map show.(\\n -> [9 * n, 8 * n]).read\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n \ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn $ (show (n * 3) ++ \" \" ++ show (n * 2))"}], "src_uid": "59d5e5ed2bc4b316e950e2a4dbc99d68"} {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nreadInteger :: String -> Integer\nreadInteger = read\n\nparseInput :: String -> [Integer]\nparseInput file\n = [ readInteger word | word <- words $ last $ lines file ]\n\nshowOutput :: [Int] -> String\nshowOutput xs = (show $ length xs) ++ \"\\n\" ++ showIndices xs\n where\n showIndices :: [Int] -> String\n showIndices [] = \"\"\n showIndices [x] = show x ++ \"\\n\"\n showIndices (x:xs) = show x ++ \" \" ++ showIndices xs\n\nprocess :: [Integer] -> [Int]\nprocess xs = \n let table = getTable xs\n lookupTable x = fromMaybe 0 (Map.lookup x table)\n total = sum xs\n isGood x\n | odd y = False\n | otherwise = lookupTable z > (if x == z then 1 else 0)\n where y = total - x\n z = y `div` 2\n in map (1+) $ findIndices (\\x -> isGood x) xs\n\ngetTable :: [Integer] -> Map.Map Integer Int\ngetTable xs = Map.fromList $ map (\\ys -> (head ys, length ys)) (group $ sort xs)\n\nmain :: IO ()\nmain = do\n n <- getLine\n line <- getLine\n (putStr . showOutput . process . parseInput) line\n", "positive_code": [{"source_code": "main = do\n l0 <- getLine\n l1 <- getLine\n let j = calc $ readArray l1\n putStrLn $ show $ length j\n putStrLn $ join \" \" $ map show j\n\njoin d [] = \"\"\njoin d (x:[]) = x\njoin d (x:xs) = x ++ d ++ join d xs\n\nsplitByChar d \"\" = []\nsplitByChar d x = let (y, ys) = splitOneByChar d x in y:splitByChar d ys\n\nsplitOneByChar d [] = (\"\", \"\")\nsplitOneByChar d (x:xs)\n | x == d = (\"\", xs)\n | otherwise = let (y, ys) = splitOneByChar d xs in (x:y, ys)\n\nreadArray x = map read $ splitByChar ' ' x\n\ngetTwoLargest x =\n let p [] l0 l1 = (l0, l1)\n p (y:ys) l0 l1\n | y > l0 = p ys y l0\n | y > l1 = p ys l0 y\n | otherwise = p ys l0 l1\n in p x 0 0\n\ncalc x =\n let s = sum x\n (lar0, lar1) = getTwoLargest x\n p [] _ js = js\n p (y:ys) j js\n | s - y == (if lar0 == y then lar1 else lar0) * 2 = p ys (j + 1) (j:js)\n | otherwise = p ys (j + 1) js\n in p x 1 []\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nreadInteger :: String -> Integer\nreadInteger = read\n\nparseInput :: String -> [Integer]\nparseInput file\n = [ readInteger word | word <- words $ last $ lines file ]\n\nshowOutput :: [Int] -> String\nshowOutput xs = (show $ length xs) ++ \"\\n\" ++ showIndices xs\n where\n showIndices :: [Int] -> String\n showIndices [] = \"\"\n showIndices [x] = show x ++ \"\\n\"\n showIndices (x:xs) = show x ++ \" \" ++ showIndices xs\n\nmain :: IO ()\nmain = do interact $ showOutput . process . parseInput\n\nprocess :: [Integer] -> [Int]\nprocess xs = \n let getNum x = fromMaybe 0 (Map.lookup x table) where table = getTable xs\n total = sum xs\n isGood x | odd remain = False\n | otherwise = isAvailable (remain `div` 2)\n where remain = total - x\n isAvailable y = getNum y > (if x == y then 1 else 0)\n in map succ $ findIndices (\\x -> isGood x) xs\n\ngetTable :: [Integer] -> Map.Map Integer Int\ngetTable xs = Map.fromAscList $ map (\\ys -> (head ys, length ys)) (group $ sort xs)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nreadInteger :: String -> Integer\nreadInteger = read\n\nparseInput :: String -> [Integer]\nparseInput file\n = [ readInteger word | word <- words $ last $ lines file ]\n\nshowOutput :: [Int] -> String\nshowOutput xs = (show $ length xs) ++ \"\\n\" ++ showIndices xs\n where\n showIndices :: [Int] -> String\n showIndices [] = \"\"\n showIndices [x] = show x ++ \"\\n\"\n showIndices (x:xs) = show x ++ \" \" ++ showIndices xs\n\nprocess :: [Integer] -> [Int]\nprocess xs\n = let table = map (\\ys -> (head ys, genericLength ys)) (group $ sort xs)\n total = sum xs\n lookupTable x = fromMaybe 0 (lookup x table)\n low x y = if x == y then 1 else 0\n isGood x\n | odd y = False\n | otherwise = lookupTable x > low x z\n where y = total - x; z = y `div` 2\n in map (1+) $ findIndices (\\x -> isGood x) xs\n\nmain :: IO ()\nmain = do interact $ showOutput . process . parseInput\n"}], "src_uid": "4cf0fe49f7ebf058317ac848043031a5"} {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngao n e = concatMap (\\i -> zip i $ drop 1 i) $ elems $ accumArray (flip (:)) [] (1,n) $\n concat $ zipWith (\\k [i, j] -> [(i, k), (j, k)]) [1 ..] e\n\nget = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n\nput = putStr . unlines . map (unwords . map show)\n\nmain = do\n [n] <- get\n e <- replicateM (n - 1) $ get\n put $ [[n - 1]]\n put $ map (2:) e\n put $ map (\\(i, j) -> [i, j]) $ gao n e\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Prelude hiding (getLine, words)\nimport Data.ByteString.Char8 (getLine, words, readInt)\n-- import Data.ByteString.Lazy.Char8 (unwords, unlines, putStr)\n\ngao n e = concatMap (\\i -> zip i $ drop 1 i) $ elems $ accumArray (flip (:)) [] (1,n) $\n concat $ zipWith (\\k [i, j] -> [(i, k), (j, k)]) [1 ..] e\n\nget = fmap (map (fst . fromJust . readInt) . words) getLine\n\nput = putStr . unlines . map (unwords . map show)\n\nmain = do\n [n] <- get\n e <- replicateM (n - 1) $ get\n put $ [[n - 1]]\n put $ map (2:) e\n put $ map (\\(i, j) -> [i, j]) $ gao n e\n"}], "negative_code": [], "src_uid": "79074958bd8017988308ff4e37bca163"} {"source_code": "module Main where\nimport Data.List\nimport Data.List.Split\n\nmain = do\n getLine -- for length, which we don't need\n input <- getLine\n let\n list = (read :: String -> Int) `map` splitOn \" \" input\n result2List = init . tail $ expand (head origList) result2Lens\n origList = head list : list ++ [last list]\n groupLen = group $ length `map` group origList\n lenLens = length `map` filter ((==1) . head) groupLen\n result2Lens = concat . map modOne $ groupLen\n modOne xs@(1:_) =\n if length xs `mod` 2 == 0 then\n [0, length xs `div` 2, length xs `div` 2, 0]\n else\n [0, length xs, 0]\n modOne xs = xs\n expand h xs = concat $ zipWith replicate xs (cycle [h, 1-h])\n print $ (maximum (0:lenLens) + 1) `div` 2\n putStrLn $ \" \" `intercalate` (show `map` result2List)\n", "positive_code": [{"source_code": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\nmodule Main where\n\nimport Control.Applicative\nimport Data.Foldable (foldMap)\nimport Data.List\nimport Data.Monoid\n\nnewtype Nat = Nat Int deriving (Eq, Ord, Num)\n\ninstance Monoid Nat where\n mempty = 0\n mappend = max\n\ndata Segment = Segment Int Bool deriving Show\n\ntype Solution = (Nat, [Bool])\n\nsegments :: [Bool] -> [Segment]\nsegments = foldr f []\n where\n f x (s@(Segment n y):ss)\n | odd n == (x /= y) = Segment (n + 1) y : ss\n f x ss = Segment 1 x : ss\n\nsolveSegment :: Segment -> Solution\nsolveSegment (Segment n x)\n | even n = (Nat (k - 1), replicate k (not x) ++ replicate k x)\n | otherwise = (Nat k, replicate n x)\n where\n k = n `div` 2\n\nsolve :: [Bool] -> Solution\nsolve = foldMap solveSegment . segments\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map (toEnum . read) . words <$> getLine\n let (Nat n, ys) = solve xs\n print n\n putStrLn (showSeq ys)\n\n where\n showSeq = intercalate \" \" . map (show . fromEnum)\n"}, {"source_code": "module Main where\nimport Data.List\nimport Debug.Trace\n\nsplit :: String -> [String]\nsplit str = result where\n result\n | remain == \"\" = reslist\n | otherwise = remain:reslist\n (remain, reslist) = foldr process (\"\", []) str\n process ' ' (\"\", a) = (\"\", a)\n process ' ' (str, a) = (\"\", str:a)\n process c (str, a) = (c:str, a)\n\nsummerize :: [Int] -> (Int, Int)\nsummerize xs = (head xs, length xs)\n\ndupHeadTail :: [Int] -> [Int]\ndupHeadTail xs@(x:_) = x:dupTail xs where\n dupTail (x:[]) = [x, x]\n dupTail (x:xs) = x:dupTail xs\n\nremHeadTail :: [Int] -> [Int]\nremHeadTail xss@(x:xs) = remTail xs where\n remTail (x:[]) = []\n remTail (x:xs) = x:remTail xs\n\nmain = do\n getLine -- for length, which we don't need\n input <- getLine\n let\n result1 = (maxOne + 1) `div` 2\n result2List = remHeadTail $ expand header result2Lens\n origList = dupHeadTail $ (read :: String -> Int) `map` split input\n header = head origList\n lenList = length `map` group origList\n groupLen = group lenList\n lenLens = length `map` filter ((==1) . head) groupLen\n maxOne\n | lenLens == [] = 0\n | otherwise = maximum lenLens\n result2Lens = concat . map modOne $ groupLen\n modOne xs@(1:_) =\n if length xs `mod` 2 == 0 then\n [0, length xs `div` 2, length xs `div` 2, 0]\n else\n [0, length xs, 0]\n modOne xs = xs\n expand h xs = concat $ zipWith replicate xs (cycle [h, 1-h])\n print result1\n putStrLn $ \" \" `intercalate` (show `map` result2List)\n"}, {"source_code": "module Main where\nimport Data.List\nimport Data.List.Split\n\n\nmain = do\n getLine -- for length, which we don't need\n input <- getLine\n let\n list = (read :: String -> Int) `map` splitOn \" \" input\n result2List = init . tail $ expand (head origList) result2Lens\n origList = [head list] ++ list ++ [last list]\n groupLen = group $ length `map` group origList\n lenLens = length `map` filter ((==1) . head) groupLen\n result2Lens = concat . map modOne $ groupLen\n modOne xs@(1:_) =\n if length xs `mod` 2 == 0 then\n [0, length xs `div` 2, length xs `div` 2, 0]\n else\n [0, length xs, 0]\n modOne xs = xs\n expand h xs = concat $ zipWith replicate xs (cycle [h, 1-h])\n print $ (maximum (0:lenLens) + 1) `div` 2\n putStrLn $ \" \" `intercalate` (show `map` result2List)\n"}, {"source_code": "module Main where\nimport Data.List\nimport Debug.Trace\nimport Data.List.Split\n\n{-\nsplit :: String -> [String]\nsplit str = result where\n result\n | remain == \"\" = reslist\n | otherwise = remain:reslist\n (remain, reslist) = foldr process (\"\", []) str\n process ' ' (\"\", a) = (\"\", a)\n process ' ' (str, a) = (\"\", str:a)\n process c (str, a) = (c:str, a)\n-}\n\n\nsummerize :: [Int] -> (Int, Int)\nsummerize xs = (head xs, length xs)\n\ndupHeadTail :: [Int] -> [Int]\ndupHeadTail xs@(x:_) = x:dupTail xs where\n dupTail (x:[]) = [x, x]\n dupTail (x:xs) = x:dupTail xs\n\nremHeadTail :: [Int] -> [Int]\nremHeadTail xss@(x:xs) = remTail xs where\n remTail (x:[]) = []\n remTail (x:xs) = x:remTail xs\n\nmain = do\n getLine -- for length, which we don't need\n input <- getLine\n let\n result1 = (maxOne + 1) `div` 2\n result2List = remHeadTail $ expand header result2Lens\n origList = dupHeadTail $ (read :: String -> Int) `map` splitOn \" \" input\n header = head origList\n lenList = length `map` group origList\n groupLen = group lenList\n lenLens = length `map` filter ((==1) . head) groupLen\n maxOne\n | lenLens == [] = 0\n | otherwise = maximum lenLens\n result2Lens = concat . map modOne $ groupLen\n modOne xs@(1:_) =\n if length xs `mod` 2 == 0 then\n [0, length xs `div` 2, length xs `div` 2, 0]\n else\n [0, length xs, 0]\n modOne xs = xs\n expand h xs = concat $ zipWith replicate xs (cycle [h, 1-h])\n print result1\n putStrLn $ \" \" `intercalate` (show `map` result2List)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\n\nsplitAll :: [Int] -> [[Int]]\n\nsplitAll [] \n = [[]]\nsplitAll [x] \n = [[x]]\nsplitAll [x,y]\n | x == y = [[x],[y]]\n | x /= y = [[x,y]]\nsplitAll (x:y:xs)\n | x == y && null rest = [x] : [[y]]\n | x == y = [x] : rest \n | otherwise = (x : h) : t\n where \n rest = splitAll (y:xs)\n (h:t) = rest\n\nchange :: [Int] -> [Int]\nchange xs\n | n < 3 = xs \n | odd n = arrOf (n-1) ft ++ [lt] \n | even n = arrOf hn ft ++ arrOf hn lt\n where \n n = length xs\n hn = n `div` 2\n ft = head xs \n lt = last xs\n \n arrOf l v\n = take l $ repeat v\n \nsolve :: [Int] -> (Int,[Int])\nsolve xs \n = ( ans, concat arr' )\n where \n ans = ( maximum (map length arr) - 1 ) `div` 2\n arr = splitAll xs\n arr' = map change arr\n\noutput :: (Int,[Int]) -> String\noutput (x, xs) = show x ++ \"\\n\" ++ ( concat $ map (++ \" \") (map show xs) ) \n\nmain = ( output . solve . map ( read :: String -> Int ) . words . last . lines) <$> getContents >>= putStrLn\n\n \n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\n\nsplitAll :: [Int] -> [[Int]]\n\nsplitAll [] \n = [[]]\nsplitAll [x] \n = [[x]]\nsplitAll [x,y]\n | x == y = [[x],[y]]\n | x /= y = [[x,y]]\nsplitAll (x:y:xs)\n | x == y && null rest = [x] : [[y]]\n | x == y = [x] : (y : h) : t \n | otherwise = (x : h') : t'\n where \n rest = splitAll xs\n (h:t) = rest\n \n rest' = splitAll (y:xs)\n (h':t') = rest'\n\nchange :: [Int] -> [Int]\nchange xs\n | n < 2 = xs \n | odd n = arrOf n ft \n | even n = arrOf hn ft ++ arrOf hn lt\n where \n n = length xs\n hn = n `div` 2\n ft = head xs \n lt = last xs\n \n arrOf l v\n = take l $ repeat v\n \nsolve :: [Int] -> (Int,[Int])\nsolve xs \n = ( ans, concat arr' )\n where \n ans = ( maximum (map length arr) - 1 ) `div` 2\n arr = splitAll xs\n arr' = map change arr\n\noutput :: (Int,[Int]) -> String\noutput (x, xs) = show x ++ \"\\n\" ++ ( concat $ map (++ \" \") (map show xs) ) \n\nmain = ( output . solve . map ( read :: String -> Int ) . words . last . lines) <$> getContents >>= putStrLn\n\n \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\n\nsplitAll :: [Int] -> [[Int]]\n\nsplitAll [] \n = [[]]\nsplitAll [x] \n = [[x]]\nsplitAll [x,y]\n | x == y = [[x],[y]]\n | x /= y = [[x,y]]\nsplitAll (x:y:xs)\n | x == y && null rest = [x] : [[y]]\n | x == y = [x] : (y : h) : t \n | otherwise = (x : h') : t'\n where \n rest = splitAll xs\n (h:t) = rest\n \n rest' = splitAll (y:xs)\n (h':t') = rest'\n\nchange :: [Int] -> [Int]\nchange xs\n | n < 3 = xs \n | odd n = arrOf (n-1) ft ++ [lt] \n | even n = arrOf hn ft ++ arrOf hn lt\n where \n n = length xs\n hn = n `div` 2\n ft = head xs \n lt = last xs\n \n arrOf l v\n = take l $ repeat v\n \nsolve :: [Int] -> (Int,[Int])\nsolve xs \n = ( ans, concat arr' )\n where \n ans = ( maximum (map length arr) - 1 ) `div` 2\n arr = splitAll xs\n arr' = map change arr\n\noutput :: (Int,[Int]) -> String\noutput (x, xs) = show x ++ \"\\n\" ++ ( concat $ map (++ \" \") (map show xs) ) \n\nmain = ( output . solve . map ( read :: String -> Int ) . words . last . lines) <$> getContents >>= putStrLn\n\n \n"}], "src_uid": "5da1c96b88b4ac0b698a37e4d2437ccb"} {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n (_:h:_) <- map read . words <$> getLine\n s <- replicateM h $ getLine\n forM_ (transpose s) $\n replicateM_ 2 . putStrLn . double\n where\n double [] = []\n double (h:t) = h:h:double t\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n\t[w, h] <- map read . words <$> getLine\n\ta <- lines <$> getContents\n\n\tlet b = [[a !! (y `div` 2) !! (x `div` 2) | y <- [0..2*h-1]] | x <- [0..2*w-1]]\n\n\tputStrLn $ unlines $ b\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n\t[w, h] <- map read . words <$> getLine\n\ta <- lines <$> getContents\n\n\tlet b = [[a !! (y `div` 2) !! (x `div` 2) | y <- [0..2*h-1]] | x <- [0..2*w-1]]\n\n\tputStrLn $ unlines $ b\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (transpose)\n\nmain = do\n\t-- [w, h] <- map read . words <$> getLine\n\tgetLine\n\ta <- lines <$> getContents\n\n\t-- let b = [[a !! (y `div` 2) !! (x `div` 2) | y <- [0..2*h-1]] | x <- [0..2*w-1]]\n\t--\n\t\n\tlet dup = concatMap (replicate 2)\n\t\n\tlet b = dup . (map dup) $ transpose a\n\n\tputStrLn $ unlines $ b\n"}, {"source_code": "module Main where\nimport Data.List\nimport Text.Read (read)\nimport System.IO\n\nreadArray:: Int->[String]->IO [String]\nreadArray 0 res = return res\nreadArray n res = do\n s <-getLine\n readArray (n-1) (res ++[s])\n\nduplicate:: String->String\nduplicate [] = []\nduplicate (x:xs) = x:x:duplicate xs\n\nduplicateV::[String]->[String]\nduplicateV [] = []\nduplicateV (cs:css) = cs:cs:duplicateV css\n\nmain = do\n mes <- getLine\n let w = read (last . words $ mes)::Int\n --let h = read . last . words mes\t\t \n pic <- readArray w []\n putStrLn . (intercalate \"\\n\") . duplicateV . (map duplicate) . transpose $ pic"}, {"source_code": "import Data.List\nmain = interact $ unlines . t . s . t . s . map r . t . r . tail . lines\ns = concat . map (\\x -> [x,x])\nt = transpose\nr = reverse\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n"}, {"source_code": "import Data.List\nmain = interact $ unlines . s . map s . t . tail . lines\ns = foldr (\\x acc-> x:x:acc) []\nt = transpose\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.List\nimport Text.Read (read)\nimport System.IO\n\nreadArray:: Int->[String]->IO [String]\nreadArray 0 res = return res\nreadArray n res = do\n s <-getLine\n readArray (n-1) (res ++[s])\n\nduplicate:: String->String\nduplicate [] = []\nduplicate (x:xs) = x:x:duplicate xs\nmain = do\n mes <- getLine\n let w = read (last . words $ mes)::Int\n --let h = read . last . words mes\t\t \n pic <- readArray w []\n putStrLn . (intercalate \"\\n\") . (map duplicate) . transpose $ pic"}], "src_uid": "9af19e1b482f7f0bcbffc754cf324092"} {"source_code": "import qualified Data.Map as M\nimport Control.Monad\nimport Data.List --(foldl')\n\n--calc :: Integer -> [Integer] -> Integer\ncalc n dat = ans\n where\n (idx, m, ans) = foldl' (\\(i, mm, aa) t -> \n (i+1, M.insertWith (+) t 1 mm, \n aa + t * (i - n + 1 + i) - M.findWithDefault 0 (t-1) mm + M.findWithDefault 0 (t+1) mm\n ))\n (fromIntegral 0, M.empty, fromIntegral 0) dat\n\nmain :: IO ()\nmain = do\n n:dat <- fmap (map read . words) getContents :: IO [Integer]\n print $ calc n dat\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.IntMap as Map\n\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\nmain = interact $ unlines . parse . lines\n\nparse [_,ops'] = sol ops\n where\n ops = fn $ words ops'\n fn :: [String] -> [Integer]\n fn xs = map read xs\n\nd x y\n | abs (x-y) <= 1 = 0\n | otherwise = y - x\n\ntype MM = Map.IntMap Int\n\nsol as = [ show $ sol' m 0 0 as ]\n where\n m = Map.empty :: MM\n\nsol' _ _ _ [] = 0\nsol' m ss n (y:xs) = res + sol' (m `inc` y) (ss+y) (n+1) xs\n where\n (x,z) = (y-1, y+1)\n (a,b,c) = (m`look`x, m`look`y, m`look`z)\n res = (n-a-b-c)*y - (ss - (x*a + y*b + z*c))\n\nlook :: MM -> Integer -> Integer\nlook m k = toInteger $ case Map.lookup (fromInteger k) m of\n Just v -> v\n Nothing -> 0\n\ninc :: MM -> Integer -> MM\ninc m k = let\n ik = fromInteger k\n old = case Map.lookup ik m of\n Just v -> v\n Nothing -> 0\n in Map.insert ik (old+1) m\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.IntMap as M\n\nmain = B.interact exec\nexec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve xs = sum $ zipWith3 (\\p n x -> fromIntegral (p - n :: Int) * fromIntegral x) ps ns xs :: Integer\n where\n look = (maybe 0 id .) . M.lookup\n ps = snd $ mapAccumL (\\m (l, x) -> (M.insertWith (+) x 1 m, l - look x m - look (x + 1) m - look (x - 1) m)) M.empty $ zip [0..] xs\n ns = snd $ mapAccumR (\\(m, l) x -> ((M.insertWith (+) x 1 m, l + 1), l - look x m - look (x + 1) m - look (x - 1) m)) (M.empty, 0) xs"}, {"source_code": "import Control.Arrow\nimport Control.Applicative\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve =\n sum\n . (\n zipWith3\n (\\i v (s, m) -> v * i - s + sum [i * M.findWithDefault 0 (v + i) m | i <- [1, -1]])\n [0 ..]\n <*> scanl (flip $ \\x -> (x +) *** (M.insertWith (+) x 1)) (0, M.empty)\n )\n"}], "negative_code": [{"source_code": "import qualified Data.Map as M\nimport Control.Monad\nimport Data.List --(foldl')\n\n--calc :: Integer -> [Integer] -> Integer\ncalc n dat = ans\n where\n (idx, m, ans) = foldl' (\\(i, mm, aa) t -> \n (i+1, M.insertWith (+) t 1 mm, \n aa + t * (i - n + 1 + i) - M.findWithDefault 0 (t-1) m + M.findWithDefault 0 (t+1) m\n ))\n (fromIntegral 0, M.empty, fromIntegral 0) dat\n\nmain :: IO ()\nmain = do\n n:dat <- fmap (map read . words) getContents :: IO [Integer]\n print $ calc n dat\n"}], "src_uid": "c7cca8c6524991da6ea1b423a8182d24"} {"source_code": "import Control.Monad\nimport Data.Char\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do s <- getLine\n putStrLn (if map toLower s == \"yes\" then \"YES\" else \"NO\")\n\nmain :: IO ()\nmain = do n <- (readLn :: IO Int)\n forM_ [1 .. n] testCaseMain\n", "positive_code": [{"source_code": "module Main (main) where\nimport Numeric (showFFloat)\nimport Data.Char (toUpper)\n-- reset && stack build && echo \"success\" && stack exec haskell-codeforces-exe && echo finished\n-- gen-hie > hie.yaml\n\n\nstrToInt a = read a :: Int\nstrToFloat a = read a :: Float\n\npshow x = putStr (show x)\npfshow x = putStr (showFFloat (Just 2) x \"\")\n\nsolve:: String -> String\nsolve str = do\n let x = map toUpper str\n if x == \"YES\" then \"YES\"\n else \"NO\"\n\nfnMain :: String -> String\nfnMain input = do\n let inputLines = lines input\n\n let n = strToInt $ head $ inputLines\n unlines $ map solve $ take n $ drop 1 $ inputLines\n\n\n\nmain :: IO ()\nmain = do\n interact fnMain"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Char (toLower)\r\n\r\n\r\nmain = interact $ lines >>> drop 1 >>> map processTest >>> unlines\r\n\r\n\r\nprocessTest = map toLower >>> (== \"yes\") >>> (\\ isYes -> if isYes then \"YES\" else \"NO\")\r\n"}, {"source_code": "import Data.List\nimport Data.Text(toLower,pack,unpack)\n\n\ntestcase 0 = return ()\ntestcase t = do\n s <- getLine\n putStrLn (if (unpack $ toLower $ pack $ s) == \"yes\"\n then \"YES\" else \"NO\")\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe\r\n\r\n--\r\nimport Data.Bool\r\nimport Data.Char\r\n\r\nsolve :: C.ByteString -> Bool\r\nsolve = (== \"yes\") . C.map toLower\r\n\r\ninput = bstr\r\n\r\noutput :: Bool -> C.ByteString\r\noutput = bool \"NO\" \"YES\"\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\n-- Scanner\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&))\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = String\ntype CoDomain = String\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn \n\nparse :: IO Domain\nparse = do\n line <- getLine\n return line\n\nsolve :: Solver\nsolve = (\\x -> if x then \"YES\" else \"NO\") . (==\"yes\") . fmap toLower \n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (forM_)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)\r\nimport Data.Array ((!))\r\nimport Data.Array.ST (MArray (newArray), readArray, runSTArray, writeArray)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Char (toLower)\r\nimport Data.Maybe (fromJust)\r\n\r\ndata TC = TC {s :: String}\r\n\r\nsolve TC {..} = case fmap toLower s == \"yes\" of\r\n True -> \"YES\"\r\n otherwise -> \"NO\"\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (C.pack) >>> C.unlines\r\n\r\nscan = numberOf $ TC <$> C.unpack <$> str\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "import Data.List\r\nimport qualified Data.Char as DC\r\n\r\nisyes :: String -> Bool\r\nisyes s = (map DC.toLower s == \"yes\")\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n s <- getLine\r\n putStrLn $ if isyes s then \"YES\" else \"NO\"\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)"}], "negative_code": [], "src_uid": "4c0b0cb8a11cb1fd40fef47616987029"} {"source_code": "import Data.List\nimport Data.Function (on)\nf s = map head $ filter ((>1).length) $ group $ sort s\nmain = do\n [n, m] <- (map read . words) `fmap` getLine\n l <- concat `fmap` mapM (\\i -> do\n l' <- getLine\n return $ map (\\(c, j) -> (c, (i, j))) $ zip l' [1..]) [1..n]\n let l' = groupBy ((==) `on` fst) $ sort l\n let l2 = sortBy (\\(c1, ab1) (c2, ab2) -> ab1 `compare` ab2) $ concatMap (\\l -> let\n fl = f $ map (fst.snd) l\n sl = f $ map (snd.snd) l in\n filter (\\(c, (a, b)) -> (a `notElem` fl) && (b `notElem` sl)) l) l'\n putStrLn $ map fst l2\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Array.ST\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f = readArray a i >>= \\x -> writeArray a i (f x)\n\nrowCrossMask :: [Char] -> [Bool]\nrowCrossMask row =\n let mask = runSTUArray $ do\n mask <- newArray ('a','z') 0 :: ST s (STUArray s Char Int)\n forM row $ \\ch -> modifyArray mask ch (+1)\n return mask\n in map (\\ch -> if mask ! ch == 1 then True else False) row\n\nmain = do\n [h, w] <- ( map read . words ) `liftM` getLine\n board <- replicateM h getLine\n\n let rowCross = join $ map rowCrossMask board\n colCross = join $ transpose $ map rowCrossMask $ transpose board\n allCross = map snd $ filter fst $ zip (zipWith (&&) rowCross colCross) (join board)\n\n --putStrLn $ show rowCross\n --putStrLn $ show colCross\n putStrLn allCross\n"}, {"source_code": "import Array\n\ntype Africa = Array (Int, Int) (Either Char Char)\n\nbigTest :: [String]\nbigTest = take 100 (repeat (take 100 (cycle \"a\")))\n\ngenAfrica :: (Int, Int) -> [String] -> Africa\ngenAfrica (n, m) lines = array ((1, 1), (n, m)) [((i, j), Right (lines !! (i-1) !! (j-1))) | i <- [1..n], j <- [1..m]]\n\ngetEither :: Either a a -> a\ngetEither (Left a) = a\ngetEither (Right a) = a\n\ngetJust :: Maybe a -> a\ngetJust (Just a) = a\ngetJust Nothing = error \"Nothing!\"\n \nfindEqLeft :: (Int, Int) -> (Int, Int) -> Africa -> Maybe (Int, Int)\nfindEqLeft size (x, y) africa = findEqLeft' size (x, y) (x, y + 1) africa\n where\n findEqLeft' :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Africa -> Maybe (Int, Int)\n findEqLeft' (n, m) (x, y) (i, j) africa\n | j > m = Nothing\n | getEither (africa ! (x, y)) == getEither (africa ! (i, j)) = Just (i, j)\n | otherwise = findEqLeft' (n, m) (x, y) (i, j + 1) africa\n \nfindEqDown :: (Int, Int) -> (Int, Int) -> Africa -> Maybe (Int, Int)\nfindEqDown size (x, y) africa = findEqDown' size (x, y) (x + 1, y) africa\n where\n findEqDown' :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Africa -> Maybe (Int, Int)\n findEqDown' (n, m) (x, y) (i, j) africa\n | i > n = Nothing\n | getEither (africa ! (x, y)) == getEither (africa ! (i, j)) = Just (i, j)\n | otherwise = findEqDown' (n, m) (x, y) (i + 1, j) africa\n\nfilterAfrica :: (Int, Int) -> Africa -> Africa\nfilterAfrica (n, m) africa = foldl (\\africa (x, y) -> filterAfrica' (n, m) (x, y) africa) africa [(i, j) | i <- [1..n], j <- [1..m]]\n where\n filterAfrica' :: (Int, Int) -> (Int, Int) -> Africa -> Africa\n filterAfrica' size cell africa\n | nextLeft == Nothing && nextDown == Nothing = africa\n | nextLeft /= Nothing && nextDown == Nothing = africa // [(cell, Left symbol), (getJust nextLeft, Left symbol)]\n | nextLeft == Nothing && nextDown /= Nothing = africa // [(cell, Left symbol), (getJust nextDown, Left symbol)]\n | nextLeft /= Nothing && nextDown /= Nothing = africa // [(cell, Left symbol), (getJust nextLeft, Left symbol), (getJust nextDown, Left symbol)]\n where\n nextLeft = findEqLeft size cell africa\n nextDown = findEqDown size cell africa\n symbol = getEither (africa ! cell)\n \ngetSymbols :: (Either Char Char) -> String\ngetSymbols (Left _) = []\ngetSymbols (Right c) = [c]\n \nprintAfrica :: (Int, Int) -> Africa -> String\nprintAfrica (n, m) africa = concatMap (\\cell -> getSymbols (africa ! cell)) [(i, j) | i <- [1..n], j <- [1..m]]\n\nmain = do\n line <- getLine\n let [n, m] = map read $ words line\n let size = (n, m)\n lines <- sequence (map (\\x -> getLine) [1..n])\n putStrLn $ printAfrica size $ filterAfrica size $ genAfrica size lines"}, {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.IO\n\nmain :: IO ()\nmain = do\n [n, m] <- map read . words <$> getLine\n buf <- newArray ((1, 1, 'a'), (n, m, 'z')) 0 :: IO (IOUArray (Int, Int, Char) Int)\n table <- newArray_ ((1, 1), (n, m)) :: IO (IOUArray (Int, Int) Char)\n forM_ [1 .. n] $ \\y -> do\n s <- take m <$> getLine\n forM_ (zip [1 ..] s) $ \\(x, c) -> do\n writeArray table (y, x) c\n forM_ [1 .. n] $ \\y' -> do\n v <- readArray buf (y', x, c)\n writeArray buf (y', x, c) $ v + 1\n forM_ [1 .. m] $ \\x' -> do\n v <- readArray buf (y, x', c)\n when (x' /= x) $\n writeArray buf (y, x', c) $ v + 1\n forM_ [1 .. n] $ \\y ->\n forM_ [1 .. m] $ \\x -> do\n c <- readArray table (y, x)\n v <- readArray buf (y, x, c)\n when (v == 1) $ putChar c\n putStrLn \"\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Char\n\nmain = do\n [n,m] <- map read . words <$> getLine\n cw <- listArray ((1,1),(n,m)) . filter isAlpha . concat <$> replicateM n getLine\n let wr = listArray ((1,1),(n,m)) [ not $ (or [ cw!(n',c) == cw!(r,c) | n' <- [1..n], n' /= r]) || (or [cw!(r,n') == cw!(r,c) | n' <- [1..m], n' /= c ]) \n | r <- [1..n], c <- [1..m]]\n putStrLn $ map fst $ filter snd $ zip (elems cw) (elems wr)\n"}], "negative_code": [], "src_uid": "9c90974a0bb860a5e180760042fd5045"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\t[ n, k ] <- map read . words <$> getLine\n\tas <- replicateM n getLine\n\n\tlet\n\t\tsolve s = all ( ( `elem` s ) . intToDigit ) [ 0 .. k ]\n\n\tprint . length . filter solve $ as\n", "positive_code": [{"source_code": "\nmodule Main where\n\nimport Control.Monad\nimport Data.List\n\nstr2int = read :: String -> Int\n\nuniq [] = []\nuniq [x] = [x]\nuniq (x:y:xs) = if x == y then uniq (y:xs) else x : uniq (y:xs)\n\nhow_many p = foldl (\\n x -> if p x then n + 1 else n) 0\n\ndigits b n\n | n < b = [n]\n | otherwise = mod n b : digits b (div n b)\n\ngood k n = [0 .. k] == filter (<= k) (uniq . sort $ digits 10 n)\n\nsolve (n:k:_) = do\n lines <- replicateM n getLine\n let numbers = map str2int lines\n in return $ how_many (good k) numbers\n\nmain = do\n line <- getLine\n ans <- solve $ map str2int $ words line\n print ans\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\ndigs :: Integral a => a -> [a]\ndigs 0 = []\ndigs x = x `mod` 10 : digs (x `div` 10)\n\nsol :: Integer -> [Integer] -> Integer\nsol k xx = toInteger $ length $ filter (==True) (map (\\v -> all (\\i -> elem i (digs v)) [0..k]) xx)\n\nmain = do\n i <- getLine\n let [n, k] = map (\\x -> read x :: Int) $ words i\n inputs <- replicateM n getLine\n let nums = map (\\s -> read s :: Integer) inputs\n print $ sol (toInteger k) nums\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n firstLine <- map read <$> words <$> getLine\n length <$> filter (isGood (firstLine !! 1)) <$> map (read :: String -> Int) <$> lines <$> getContents >>= print\n\nisGood :: Int -> Int -> Bool\nisGood k n \n | k == -1 = True\n | otherwise = k `elem` (map (read . (:[])) $ show n) && isGood (k-1) n\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n\n ss <- replicateM n getLine\n\n let\n f s = (take (k+1) $ sort $ nub s) == ['0'..chr (48+k)]\n\n print $ length $ filter f ss\n"}, {"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Char (ord, intToDigit)\n\nsolve :: Int -> [Int] -> Int\nsolve k as = length $ filter itsK as\n where\n itsK a = all (flip elem (show a)) ['0' .. intToDigit k]\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- replicateM n readLn\n print $ solve k as\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Char (digitToInt)\n\nmain :: IO ()\nmain = print =<< solve <$> (read . (!!1) . words <$> getLine) <*> (lines <$> getContents)\n\nsolve :: Int -> [String] -> Int\nsolve k xs = length [ x | x <- xs, all (`elem`map digitToInt x) [0..k] ]\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Char (intToDigit)\n\nmain :: IO ()\nmain = print =<< solve <$> (read . (!!1) . words <$> getLine) <*> (lines <$> getContents)\n\nsolve :: Int -> [String] -> Int\nsolve k xs = length [ x | x <- xs, all (`elem`x) ['0'..intToDigit k] ]\n"}, {"source_code": "\nmodule Main where\n\nimport Control.Monad\nimport Data.List\n\nstr2int = read :: String -> Int\n\nuniq [] = []\nuniq [x] = [x]\nuniq (x:y:xs) = if x == y then uniq (y:xs) else x : uniq (y:xs)\n\nhow_many p = foldl (\\n x -> if p x then n + 1 else n) 0\n\ndigits b n\n | n < b = [n]\n | otherwise = mod n b : digits b (div n b)\n\ngood k n = [0 .. k] == filter (<= k) (uniq . sort $ digits 10 n)\n\nsolve (n:k:_) = replicateM n getLine >>= \\lines ->\n let numbers = map str2int lines\n in return $ how_many (good k) numbers\n\nmain = getLine >>= \\line ->\n solve (map str2int (words line)) >>= print\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Char (digitToInt)\n\nmain :: IO ()\nmain = print =<< solve <$> (read . (!!1) . words <$> getLine) <*> (lines <$> getContents)\n\nsolve :: Int -> [String] -> Int\nsolve k xs = length [ x | x <- xs, all (<=k) $ map digitToInt x ]\n"}, {"source_code": "\nmodule Main where\n\nimport Control.Monad\nimport Data.List\n\nstr2int = read :: String -> Int\n\nuniq [] = []\nuniq [x] = [x]\nuniq (x:y:xs) = if x == y then uniq (y:xs) else x : uniq (y:xs)\n\nhow_many p = foldl (\\n x -> if p x then n + 1 else n) 0\n\ndigits b n\n | n < b = [n]\n | otherwise = mod n b : digits b (div n b)\n\ngood k n = [0 .. k] == (uniq . sort $ digits 10 n)\n\nsolve (n:k:_) = do\n lines <- replicateM n getLine\n let numbers = map str2int lines\n in return $ how_many (good k) numbers\n\nmain = do\n line <- getLine\n ans <- solve $ map str2int $ words line\n print ans\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n i <- getLine\n let [sn, sk] = words i\n let n = read sn :: Int\n let k = head sk\n inputs <- replicateM n getLine\n print $ length $ filter (\\num -> foldl1 (&&) (map (\\c -> c <= k) num)) inputs\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\ndigs :: Integral a => a -> [a]\ndigs 0 = []\ndigs x = x `mod` 10 : digs (x `div` 10)\n\nsol :: Integer -> [Integer] -> Integer\nsol k xx = toInteger $ length $ filter (\\x -> (sort (nub (digs x))) == [0..k]) xx\n\nmain = do\n i <- getLine\n let [n, k] = map (\\x -> read x :: Int) $ words i\n inputs <- replicateM n getLine\n let nums = map (\\s -> read s :: Integer) inputs\n print $ sol (toInteger k) nums\n"}], "src_uid": "fc831eda72f2ebe0865a3fb1b783edc5"} {"source_code": "main :: IO()\n\nmain = do \n\tphrase <- getLine\n\tprint (PlainString (minshift phrase))\n\nnewtype PlainString = PlainString String\ninstance Show PlainString where\n show (PlainString s) = s\n\n\nswapSub :: [Char] -> [Char]\nswapSub \"\" = \"\" -- correct\nswapSub (l1:str)\n\t| l1 > 'a' = (pred l1) : (swapSub str)\n\t| otherwise = l1:str\n\nminshift :: [Char] -> [Char]\nminshift \"\" = \"\" -- correct\nminshift ('a':[]) = \"z\" -- correct\nminshift (l1:str)\n\t| l1 > 'a' = swapSub (l1:str)\n\t| otherwise = l1 : (minshift str)\n", "positive_code": [{"source_code": "import Data.Array\n\nmain = do\n let a = listArray ('a','z') $ 'z':['a'..'y']\n solve s = map (a!) b ++ c\n where (b,c) = span (/='a') s\n b <- getLine\n if head b /= 'a'\n then putStrLn $ solve b\n else do\n let (pre,suf) = span (=='a') b\n if suf == \"\" then putStrLn (init pre ++ \"z\") else putStrLn $ pre ++ (solve suf)\n"}, {"source_code": "main = interact $ solve False . head . words\nsolve _ [] = []\nsolve True f@('a':t) = f\nsolve True (l:t) = (pred l) : (solve True t)\nsolve False ('a':[]) = \"z\"\nsolve False ('a':t) = 'a' : (solve False t)\nsolve False (l:t) = (pred l) : (solve True t)"}, {"source_code": "import Data.Char\n\nmain = interact $ h.head.lines\nf = map g\ng x\n | x == 'a' = 'z'\n | otherwise = chr ((ord x) - 1)\n\nh x\n | x == (take (length x) ['a', 'a'..]) = (take ((length x)-1) ['a', 'a' ..] ++ \"z\")\n |otherwise = (takeWhile (=='a') x) ++ (f (takeWhile (/='a') (dropWhile (=='a') x))) ++ (dropWhile (/='a') (dropWhile (=='a') x))\n"}, {"source_code": "import Data.Char \n\nf :: Bool -> String -> String\nf _ [] = []\nf False ['a'] = ['z']\nf True ['a'] = ['a']\nf _ (x:[]) = [chr((ord x) - 1)]\nf True ('a':xs) = ('a':xs)\nf False ('a':xs) = ('a':(f False xs))\nf _ (x:xs) = [chr((ord x) - 1)] ++ f True xs\n\n\nmain = do\n\ts <- getLine\n\tputStrLn (f False s)\n"}, {"source_code": "import Data.Char\n\nprev c = chr ((ord c) - 1)\n\nsolve True \"\" = \"\"\nsolve False \"a\" = \"z\"\nsolve True ('a':cs) = 'a' : cs\nsolve True (c:cs) = prev c : solve True cs\nsolve False ('a':cs) = 'a' : solve False cs\nsolve False (c:cs) = prev c : solve True cs\n\nmain = getLine >>= putStrLn . solve False"}, {"source_code": "import Data.Char\n\nant :: Char -> Char\nant = chr . pred . ord\n\nletter :: Char -> Bool\nletter c = ord c >= ord 'a' && ord c <= ord 'z'\n\nprocess :: Bool -> String -> String\nprocess _ [] = []\nprocess False \"a\" = \"z\"\nprocess False ('a':rest) = 'a' : process False rest\nprocess False (c:rest) = (ant c) : process True rest\nprocess True ('a':rest) = 'a' : rest\nprocess True (c:rest) = (ant c) : process True rest\n\nmain :: IO ()\nmain = interact (process False . filter letter)"}], "negative_code": [{"source_code": "main :: IO()\n\nmain = do \n\tphrase <- getLine\n\tprint (minshift phrase)\n\nswapSub :: [Char] -> [Char]\nswapSub \"\" = \"\" -- correct\nswapSub (l1:str)\n\t| l1 > 'a' = (pred l1) : (swapSub str)\n\t| otherwise = l1:str\n\nminshift :: [Char] -> [Char]\nminshift \"\" = \"\" -- correct\nminshift ('a':[]) = \"z\" -- correct\nminshift (l1:str)\n\t| l1 > 'a' = swapSub (l1:str)\n\t| otherwise = l1 : (minshift str)\n"}, {"source_code": "import Data.Array\n\nmain = do\n let a = listArray ('a','z') $ 'z':['a'..'y']\n solve s = map (a!) b ++ c\n where (b,c) = span (/='a') s\n b <- getLine\n if head b /= 'a'\n then putStrLn $ solve b\n else do\n let (pre,suf) = span (=='a') b\n putStrLn $ pre ++ (solve suf)\n"}, {"source_code": "import Data.Array\n\nmain = do\n\tlet a = listArray ('a','z') $ 'z':['a'..'y']\n\t(b,c) <- fmap (span (/='a')) getLine\n\tputStrLn $ map (a!) b ++ c\n\t"}, {"source_code": "main = interact $ solve False\nsolve _ [] = []\nsolve True f@('a':t) = f\nsolve True (l:t) = (pred l) : (solve True t)\nsolve False ('a':[]) = \"z\"\nsolve False ('a':t) = 'a' : (solve False t)\nsolve False (l:t) = (pred l) : (solve True t)"}, {"source_code": "main = interact $ solve False\nsolve _ [] = []\nsolve True f@('a':t) = f\nsolve True (l:t) = (pred l) : (solve True t)\nsolve False ('a':t) = 'a' : (solve False t)\nsolve False (l:t) = (pred l) : (solve True t)"}, {"source_code": "main = interact $ solve False\nsolve _ [] = []\nsolve False \"a\" = \"z\"\nsolve True f@('a':t) = f\nsolve True (l:t) = (pred l) : (solve True t)\nsolve False ('a':t) = 'a' : (solve False t)\nsolve False (l:t) = (pred l) : (solve True t)"}, {"source_code": "import Data.Char\n\nmain = interact $ h.head.lines\nf = map g\ng x\n | x == 'a' = 'z'\n | otherwise = chr ((ord x) - 1)\n\nh x = (takeWhile (=='a') x) ++ (f (takeWhile (/='a') (dropWhile (=='a') x))) ++ (dropWhile (/='a') (dropWhile (=='a') x))\n"}, {"source_code": "import Data.Char \n\nf :: Bool -> String -> String\nf _ [] = []\nf False ['a'] = ['z']\nf True ['a'] = ['a']\nf _ (x:[]) = [chr((ord x) - 1)]\nf b ('a':xs) = ['a'] ++ f b xs\nf _ (x:xs) = [chr((ord x) - 1)] ++ f True xs\n\n\nmain = do\n\ts <- getLine\n\tputStrLn (f False s)\n"}, {"source_code": "import Data.Char\n\nant :: Char -> Char\nant = chr . pred . ord\n\nprocess :: Bool -> String -> String\nprocess _ [] = []\nprocess False \"a\" = \"z\"\nprocess False ('a':rest) = 'a' : process False rest\nprocess False (c:rest) = (ant c) : process True rest\nprocess True ('a':rest) = 'a' : rest\nprocess True (c:rest) = (ant c) : process True rest\n\nmain :: IO ()\nmain = interact (process False)"}, {"source_code": "import Data.Char\n\nant :: Char -> Char\nant = chr . pred . ord\n\nprocess :: Bool -> String -> String\nprocess _ [] = []\nprocess False ('a':rest) = 'a' : process False rest\nprocess False (c:rest) = (ant c) : process True rest\nprocess True ('a':rest) = 'a' : rest\nprocess True (c:rest) = (ant c) : process True rest\n\nmain :: IO ()\nmain = interact (process False)"}], "src_uid": "e70708f72da9a203b21fc4112ede9268"} {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep (_:x:y:xs) = (x,y):(sep xs)\n\nparse (x,y) = zip (phi x) (phi y)\n where phi = (map read) . words\n\nformat b\n | b = \"YES\"\n | otherwise = \"NO\"\n\nsolve ps = solve' False (-1) ps\n\nsolve' :: Bool -> Int -> [(Int, Int)] -> Bool\nsolve' _ _ [] = True\nsolve' _ _ ((a,b):_)\n | a < b = False\nsolve' False c ((a,b):xs)\n | b == 0 = solve' False (max a c) xs\n | otherwise = a-b >= c && solve' True (a-b) xs\nsolve' True c ((a,b):xs) =\n (a-b == c || (b == 0 && a <= c)) && solve' True c xs\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe\r\n\r\n--\r\nimport Data.Bool\r\n\r\nsolve :: ([Integer], [Integer]) -> Bool\r\nsolve (as, bs) = isJust $foldM g (0, False) $ zipWith f as bs\r\n where\r\n f a 0 = (a, False)\r\n f a b = (a - b, True)\r\n\r\n g (x, False) (y, False) = Just (max x y, False)\r\n g (x, False) (y, True)\r\n | x <= y = Just (y, True)\r\n | otherwise = Nothing\r\n g (x, True) (y, True)\r\n | x == y = Just (x, True)\r\n | otherwise = Nothing\r\n g a b = g b a\r\n\r\ninput :: Scanner ([Integer], [Integer])\r\ninput = do\r\n n <- int\r\n as <- n >< integer\r\n bs <- n >< integer\r\n pure (as, bs)\r\n\r\noutput :: Bool -> C.ByteString\r\noutput = bool \"NO\" \"YES\"\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\n-- Scanner\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n"}, {"source_code": "-- boilerplate {{{1\n-- vim: foldmethod=marker\n-- pragmas {{{2\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Main where -- {{{2\n\nimport Control.Applicative\nimport Control.Arrow ( (|||), (&&&) )\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.IO\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bifunctor\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\nimport Data.Foldable hiding ( sum, product )\nimport Data.Function\nimport Data.Functor\nimport Data.IntMap ( IntMap )\nimport Data.IntSet ( IntSet )\nimport Data.List hiding ( sum, product )\nimport Data.Map ( Map )\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Min(..), Max(..) )\nimport Data.Sequence ( Seq )\nimport Data.Set ( Set )\nimport Data.Text ( Text )\nimport Data.Traversable\nimport Data.Tuple\nimport Debug.Trace\nimport Prelude hiding ( sum, product )\nimport System.IO\n-- import System.Random\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.Map as LM\nimport qualified Data.Map.Strict as M\nimport qualified Data.Sequence as Q\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\n\n-- utilites {{{2\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\ngetInt = readInt <$> C.getLine\ngetInts = map readInt . C.words <$> C.getLine\nputShows :: Show a => [a] -> IO ()\nputShows = putStrLn . unwords . map show\nynq = putStrLn . bool \"NO\" \"YES\"\ngcount g@(x:_) = (x, length g)\nmodulus = 10^9 + 7 :: Int\nmod' x = rem x modulus\ntri n = quot (n * n + n) 2\nsum t = foldl' (+) 0 t\nproduct t = foldl' (*) 1 t\nmprint :: Show a => String -> Maybe a -> IO ()\nmprint s = maybe (putStrLn s) print\nifM :: Monad m => m Bool -> m a -> m a -> m a\nifM b t e = b >>= bool e t\nwhenM :: Monad m => m Bool -> m () -> m ()\nwhenM b t = ifM b t (pure ())\n\n-- }}}1\n\nmain = getInt >>= flip replicateM_ docase\n\ndocase = do\n [n] <- getInts\n aa <- getInts\n bb <- getInts\n let x = maximum $ zipWith (-) aa bb\n let f a 0 = a <= x\n f a b | a < b = False\n f a b = a - b == x\n let cc = zipWith f aa bb\n -- traceShowM (x,aa,bb,cc)\n ynq $ and cc\n"}], "negative_code": [], "src_uid": "ee40e8b0ed2da53127f53eb694653a30"} {"source_code": "{-# LANGUAGE Strict #-}\nmodule Main where\nimport qualified Data.Sequence as S\nimport System.IO\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin LineBuffering\n interact $ unlines . solve . take2Nl . lines\n\ntake2Nl :: [String] -> [String]\ntake2Nl (n : xs) = take (2* (read n)) xs\n\nsolve :: [String] -> [String]\nsolve xs = let\n n = div (Prelude.length xs) 2\n go :: Int -> [String] -> [S.Seq Int] -> [S.Seq Int]\n go 0 _ sq = sq\n go nn (s:ss) sq = case even nn of\n True -> go (nn-1) ss sq\n False -> go (nn-1) ss ((f s):sq)\n where f :: String -> S.Seq Int\n f st = S.fromList (map read $ words st)\n lsq = go (2 * n) xs []\n f :: S.Seq Int -> String\n f = func\n in\n reverse (f <$> lsq)\n\n\nfunc :: S.Seq Int -> String\nfunc sq = let (a,b,c,suc) = S.foldlWithIndex (\\(i, j, k, b) ind a->\n case b of\n 0 ->\n case compare a (S.index sq i) of\n GT -> (ind, 0, 0, b+1)\n EQ -> (ind, 0, 0, b+1)\n LT -> (ind, 0, 0, b)\n\n 1 ->\n case compare a (S.index sq i) of\n GT -> (i, ind, k, b+1)\n EQ -> (i, ind, k, b+1)\n LT -> (ind, j, k, b)\n\n 2 ->\n case compare a (S.index sq j) of\n GT -> (j, ind, k, b)\n EQ -> (j, ind, k, b)\n LT -> (i, j, ind, b+1)\n\n 3 -> (i, j, k, 3)\n ) (0,0,0,0) sq\n\n in case suc of\n 3 -> \"YES\\n\" ++ show (a+1) ++ \" \" ++ show (b+1) ++ \" \" ++ show (c+1)\n _ -> \"NO\\n\"\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n ps <- map read . words <$> getLine :: IO [Integer]\n case solve $ zip [1 ..] ps of\n Just is -> putStrLn \"YES\" >> putStrLn (unwords $ map show is)\n Nothing -> putStrLn \"NO\"\n\nsolve ((i, a) : ps@((j, b) : (k, c) : _))\n | a < b && b > c = Just [i, j, k]\n | otherwise = solve ps\nsolve _ = Nothing\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> unlines\n\nprocess :: [[Int]] -> [String]\nprocess [] = []\nprocess ([_] : xs : rest) = solve xs 1 : process rest\n \nsolve :: [Int] -> Int -> String\nsolve (z:y:x:xs) i | (z < y && y > x) = (++) \"YES\\n\" $ concat $ intersperse \" \" $ map show [i, i+1, i+2]\n | otherwise = solve (y:x:xs) (i+1)\nsolve _ _ = \"NO\\n\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Strict #-}\nmodule Main where\nimport qualified Data.Sequence as S\nimport System.IO\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin LineBuffering\n interact $ unlines . solve . take2Nl . lines\n\ntake2Nl :: [String] -> [String]\ntake2Nl (n : xs) = take (2* (read n)) xs\n\nsolve :: [String] -> [String]\nsolve xs = let\n n = div (Prelude.length xs) 2\n go :: Int -> [String] -> [S.Seq Int] -> [S.Seq Int]\n go 0 _ sq = sq\n go nn (s:ss) sq = case even nn of\n True -> go (nn-1) ss sq\n False -> go (nn-1) ss ((f s):sq)\n where f :: String -> S.Seq Int\n f st = S.fromList (map read $ words st)\n lsq = go (2 * n) xs []\n f :: S.Seq Int -> String\n f = func\n in\n reverse (f <$> lsq)\n\n\nfunc :: S.Seq Int -> String\nfunc sq = let (a,b,c,suc) = S.foldrWithIndex (\\ind a (i, j, k, b) ->\n case b of\n 0 ->\n case compare a (S.index sq i) of\n GT -> (ind, 0, 0, b+1)\n EQ -> (ind, 0, 0, b+1)\n LT -> (ind, 0, 0, b)\n\n 1 ->\n case compare a (S.index sq i) of\n GT -> (i, ind, k, b+1)\n EQ -> (i, ind, k, b+1)\n LT -> (ind, j, k, b)\n\n 2 ->\n case compare a (S.index sq j) of\n GT -> (j, ind, k, b)\n EQ -> (j, ind, k, b)\n LT -> (i, j, ind, b+1)\n\n 3 -> (i, j, k, 3)\n ) (0,0,0,0) sq\n\n in case suc of\n 3 -> \"YES\\n\" ++ show (c+1) ++ \" \" ++ show (b+1) ++ \" \" ++ show (a+1)\n _ -> \"NO\\n\"\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n \nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> unlines\n\nprocess :: [[Int]] -> [String]\nprocess [] = []\nprocess ([_] : xs : rest) = solve xs : process rest\n \nsolve :: [Int] -> String\nsolve (x1:x2:x3:xs) | (x1 < x2 && x2 > x3) = \"YES\\n\" ++ (concat $ intersperse \" \" $ map show [x1, x2, x3])\n | otherwise = solve (x2:x3:xs)\nsolve _ = \"NO\\n\"\n"}], "src_uid": "dd55e29ac9756325530ad2f4479d9f6d"} {"source_code": "module Main where\n\nimport Data.List\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn s ss = reverse $ splitOn' [] s (reverse ss) where\n splitOn' xs y [] = [xs]\n splitOn' xs y (z:zs) =\n if y == z\n then xs : splitOn' [] y zs\n else splitOn' (z:xs) y zs\n\ncounter :: Eq a => [a] -> [(Integer, a)]\ncounter list = counter' 1 (head list) (tail list) where\n counter' :: Eq a => Integer -> a -> [a] -> [(Integer, a)]\n counter' n x [] = [(n, x)]\n counter' n x (y:ys) =\n if x /= y\n then (n,x) : counter' 1 y ys\n else counter' (n + 1) y ys\n\nanswer :: (Ord a, Eq a) => [a] -> Bool\nanswer list = null . (filter odd) . (map fst) $ (counter . sort) list\n\nmain :: IO ()\nmain = do\n n <- getLine\n elemsLine <- getLine\n let\n elemsStrs = splitOn ' ' elemsLine\n elems :: [Int]\n elems = map read elemsStrs\n putStrLn $ if answer elems then \"Agasa\" else \"Conan\"\n", "positive_code": [{"source_code": "import Data.Bool\nimport Data.List\nmain = putStr . bool \"Agasa\" \"Conan\" . or . map (odd . length) . group . sortBy (flip compare) . map (read :: String -> Int) . tail . words =<< getContents\n"}, {"source_code": "import Data.List\n\nmain = getLine >> getLine >>= putStrLn . solve . words\n\nsolve xs\n | all (even . length) $ group $ sort xs = \"Agasa\"\n | otherwise = \"Conan\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n-- import Debug.Trace\n\n-- debug = flip trace\n\ngetCount :: Int -> Int -> [Int] -> Bool\ngetCount p c (a:[])\n | p == a = (c + 1) `mod` 2 == 0 -- `debug` (\"first pass p = \" ++ show p ++ \", c = \" ++ show a)\n | otherwise = False -- `debug` (\"second pass p = \" ++ show p ++ \", c = \" ++ show a)\ngetCount p c (a : as)\n | (p /= a) && (c `mod` 2 /= 0) = False -- `debug` (\"third pass p = \" ++ show p ++ \", c = \" ++ show a)\n | p /= a = getCount a 1 as -- `debug` (\"fourth pass p = \" ++ show p ++ \", c = \" ++ show a)\n | otherwise = getCount p (c + 1) as -- `debug` (\"fifth pass p = \" ++ show p ++ \", c = \" ++ show a)\n\nsolve :: [Int] -> String\nsolve as\n | countBool == True = \"Agasa\"\n | otherwise = \"Conan\"\n where countBool = getCount (-1) 0 as\n\nmain :: IO ()\nmain = do\n n <- fst . fromJust . B.readInt <$> B.getLine\n tas <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n let as = sort tas \n putStrLn $ solve as\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n-- import Debug.Trace\n\n-- debug = flip trace\n\ngetCount :: Int -> Int -> [Int] -> Bool\ngetCount p c (a:[])\n | p == a = (c + 1) `mod` 2 == 0 -- `debug` (\"first pass p = \" ++ show p ++ \", c = \" ++ show a)\n | otherwise = False -- `debug` (\"second pass p = \" ++ show p ++ \", c = \" ++ show a)\ngetCount p c (a : as)\n | (p /= a) && (c `mod` 2 /= 0) = False -- `debug` (\"third pass p = \" ++ show p ++ \", c = \" ++ show a)\n | p /= a = getCount a 1 as -- `debug` (\"fourth pass p = \" ++ show p ++ \", c = \" ++ show a)\n | otherwise = getCount p (c + 1) as -- `debug` (\"fifth pass p = \" ++ show p ++ \", c = \" ++ show a)\n\nsolve :: [Int] -> String\nsolve as\n | countBool == True = \"Agasa\"\n | otherwise = \"Conan\"\n where countBool = getCount (-1) (0) as\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n tas <- map (read :: String -> Int) . words <$> getLine\n let as = sort tas \n putStrLn $ solve as\n"}], "negative_code": [{"source_code": "import Data.Bool\nimport Data.List\nmain = putStr . bool \"Agasa\" \"Conan\" . (\\(ys, zs) -> odd (length ys) || odd (length zs)) . (\\xs -> partition (== maximum xs) xs) . map (read :: String -> Int) . tail . words =<< getContents"}, {"source_code": "import Data.Bool\nmain = putStr . bool \"Agasa\" \"Conan\" . odd . length . (\\xs -> filter (== maximum xs) xs) . map (read :: String -> Int) . tail . words =<< getContents"}, {"source_code": "import Control.Applicative\nimport Data.List\n\ngetHighestCount :: [Int] -> Int -> Int\ngetHighestCount [] m = 0\ngetHighestCount (x:xs) m\n | m == x = 1 + rem\n | otherwise = rem\n where rem = getHighestCount xs m\n\nsolve :: Int -> [Int] -> String\nsolve n as\n | (n == hiCount) && (n `mod` 2 == 0) = \"Agasa\"\n | otherwise = \"Conan\"\n where hiCount = getHighestCount as $ maximum as\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n tas <- map (read :: String -> Int) . words <$> getLine\n let as = sort tas \n putStrLn $ solve n as\n"}], "src_uid": "864593dc3911206b627dab711025e116"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n (BS.unpack <$> readLine)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr . unlines =<< solve . evalState parseInput <$> BS.getContents\n\ntype Type = Maybe Int -- Nothing = ErrType\n -- Just x = VoidType (* times x)\n\ntype TypeMapping = Map String Type\n\nmodifyType :: Int -> Type -> Type\nmodifyType _ Nothing = Nothing\nmodifyType delta (Just x)\n | x + delta >= 0 = Just (x + delta)\n | otherwise = Nothing\n\nsolve :: [String] -> [String]\nsolve program = evalState (solving program) $ Map.fromList [(\"void\", Just 0), (\"errtype\", Nothing)]\n\nparseType :: String -> (String, Int)\nparseType str = (mid, length hi - length lo)\n where\n (lo, midHi) = span (=='&') str\n (mid, hi) = span isAlpha midHi\n\ngetType :: TypeMapping -> (String, Int) -> Type\ngetType mapping (typeName, typeDelta) = modifyType typeDelta $ Map.findWithDefault Nothing typeName mapping\n\nshowType :: Type -> String\nshowType Nothing = \"errtype\"\nshowType (Just x) = \"void\" ++ replicate x '*'\n\nsolving :: [String] -> State TypeMapping [String]\nsolving [] = return []\nsolving (op:ops)\n | opName == \"typedef\" = do \n mapping <- get\n put $ Map.insert y (getType mapping $ parseType x) mapping\n solving ops\n | otherwise = do\n mapping <- get\n (showType (getType mapping $ parseType z):) <$> solving ops\n where\n (opName:leftPart) = words op\n\n [x, y] = leftPart\n\n [z] = leftPart\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n", "positive_code": [{"source_code": "import Data.Map hiding (map)\n\nmain = interact $ unlines . solve . tail . map words . lines\n\nsolve es = reverse $ snd $ foldl parse (singleton \"void\" (Just 0), []) es\n\nparse (types,result) (s:d:x) = case x of\n [type1] -> (insert type1 value1 types, result)\n _ -> (types, toString value1 : result)\n where\n (amps, bs) = span (== '&') d\n (type0, asts) = span (/= '*') bs\n value0 = findWithDefault Nothing type0 types\n value1 = typedef value0 (length amps) (length asts)\n\ntypedef (Just n) a b\n | n+b-a >= 0 = Just (n+b-a)\ntypedef _ _ _ = Nothing\n\ntoString (Just n) = \"void\" ++ replicate n '*'\ntoString Nothing = \"errtype\"\n"}, {"source_code": "module Main where\nimport Data.List\nimport qualified Data.Map as Map\nimport Control.Monad\n\nparseT[]=(0,\"\")\nparseT(h:t)=case h of\n '*' -> (c+1,n)\n '&' -> (c-1,n)\n ch -> (c,ch:n)\n where\n (c,n)=parseT t\n\nm!k = join$Map.lookup k m\n\nnewt c n | r>=0 = Just r\n | otherwise = Nothing\n where r = c+n\n\nmkt state t= state!n >>= newt c\n where(c, n)=parseT t\n\ntype Type = Maybe Int\ntype State = Map.Map String Type\nprocess :: State -> [String] -> (State, [Type])\nprocess state [\"typedef\",t,name] = (Map.insert name (mkt state t) state, [])\nprocess state [\"typeof\",t] = (state,[mkt state t])\n\npv n=\"void\"++replicate n '*'\npp :: Type -> String\npp=maybe \"errtype\" pv\n\nmain=interact$unlines.map pp.concat.snd.mapAccumL process(Map.singleton \"void\"$Just 0).map words.tail.lines\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as Map\n\nmain = do\n n <- read `liftM` getLine\n foldM_ (\\table _ -> do\n cmd <- words `liftM` getLine\n let ref = cmd !! 1\n name = cmd !! 2\n refName = filter (\\ch -> ch /= '*' && ch /= '&') ref\n incCount = length $ filter (=='*') ref\n decCount = length $ filter (=='&') ref\n refCount = maybe (-1) id $ Map.lookup refName table\n count = if refCount < 0 then (-1) else max (-1) (refCount+incCount-decCount)\n if head cmd == \"typedef\"\n then return $ Map.insert name count table\n else ( putStrLn $ if count < 0 then \"errtype\" else \"void\" ++ replicate count '*' ) >>\n return table\n ) (Map.singleton \"void\" 0) [1..n]\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as Map\n\nmain = do\n n <- read `liftM` getLine\n foldM_ (\\table _ -> do\n cmd <- words `liftM` getLine\n let ref = cmd !! 1\n name = cmd !! 2\n refName = filter (\\ch -> ch /= '*' && ch /= '&') ref\n incCount = length $ filter (=='*') ref\n decCount = length $ filter (=='&') ref\n refCount = maybe (-1) id $ Map.lookup refName table\n count = max (-1) (refCount+incCount-decCount)\n if head cmd == \"typedef\"\n then return $ Map.insert name count table\n else ( putStrLn $ if count < 0 then \"errtype\" else \"void\" ++ replicate count '*' ) >>\n return table\n ) (Map.singleton \"void\" 0) [1..n]\n"}], "src_uid": "b260eb188103758a74b600d8bb46fffe"} {"source_code": "\nimport Data.List (nub, transpose)\n\nsolve :: String -> String\nsolve = show . (flip mod 1000000007) . product . map (fromIntegral . length . nub) . transpose . tail . lines\n\nmain :: IO ()\nmain = interact solve", "positive_code": [{"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n cs <- lines <$> getContents\n print $ solve cs\n\nsolve :: [String] -> Integer\nsolve cs = flip mod 1000000007 $ foldl1' (*) $ map (toInteger.length.nub) $ transpose cs"}, {"source_code": "import Data.List\n\nresult::[String]->Integer\nresult = foldl1 f.map (fromIntegral.length.nub)\n\twhere f a b = (a*b)`mod`1000000007\n\nmain=interact$show.result.transpose.tail.lines\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = interact work\n\nwork :: String -> String\nwork = show . solve . tail . lines \n\nsolve :: [String] -> Integer\nsolve strings = (product . map (fromIntegral . length . group . sort) . transpose $ strings) `mod` 1000000007\n"}, {"source_code": "import System.IO\nimport Data.List\n\nreadL :: Int -> IO [String]\nreadL n = sub n []\n where sub 0 l = return l\n sub n l = do ll <- getLine\n sub (n-1) (l ++ [ll])\n\nflatten :: [[a]] -> [a]\nflatten [[]] = []\nflatten ([]:ys) = flatten ys\nflatten ((x:xs):ys) = x:(flatten (xs:ys))\n\nrotate :: [String] -> [String]\nrotate l = sub l []\n where sub l acc\n | flatten l == [] = acc\n | otherwise = sub (map tail l) ((foldl (\\ac x -> (head x):ac) \"\" l):acc)\n\nmodInt :: Integer\nmodInt = 1000000007\n\nmain :: IO ()\nmain = do\n f <- getLine\n cs <- readL . head $ map read (words f)\n let rcs = rotate cs\n ans = foldl (\\ac x -> ac * ((genericLength $ nub x)::Integer) `mod` modInt) (1::Integer) rcs\n putStrLn $ show ans\n "}, {"source_code": "import Data.List \nimport Control.Monad\n\nfind_best grades =\n [i | (i, x) <- zip [1..] grades, x == best]\n where best = maximum grades\n\n\nsolve :: Ord a => [[a]] -> Integer\nsolve grades =\n foldl mul 1 (map count grades)\n where count = toInteger . length . group . sort\n mul a b = (a * b) `mod` (10^9 + 7)\n\nmain = do\n (n:_) <- (getLine >>= return . map (read::String->Int) . words)\n xs <- forM [1..n] (\\_ -> getLine >>= (return ))\n -- print $ transpose xs\n print $ solve (transpose xs)"}, {"source_code": "import Data.List\n\nmain = interact $ show . solve . getInput . lines\n\ngetInput :: [String] -> [String]\ngetInput (s:ss) = map (take m) (take n ss) where\n [n, m] = map read (words s)\n\nsolve :: [String] -> Integer\nsolve ss = solve' (transpose ss) 1 where\n solve' [] n = n\n solve' (s:ss) n = solve' ss (n * cnt `mod` 1000000007) where\n cnt = (toInteger . length . group . sort) s\n"}, {"source_code": "import List\n\nsolve :: [[Char]] -> Integer\nsolve = foldl (\\a x -> mod (a * x) (10 ^ 9 + 7)) 1 . map (genericLength . group . sort) . transpose\nmain = interact $ show . solve . tail . lines"}, {"source_code": "import Data.List\n\nmain:: IO()\nmain = interact work\n\nwork :: String -> String\nwork = show . flip mod 1000000007 . solve . tail . lines\n\nsolve :: [String] -> Integer\nsolve = product . map (fromIntegral . length . group . sort) . transpose\n"}], "negative_code": [{"source_code": "\nimport Data.List (nub, transpose)\n\nsolve :: String -> String\nsolve = show . product . map (fromIntegral . length . nub) . transpose . tail . lines\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "import List\n\nsolve :: [[Char]] -> Integer\nsolve = foldl (\\a x -> mod (a * x) (10 ^ 9 + 1)) 1 . map (genericLength . group . sort) . transpose\nmain = interact $ show . solve . tail . lines"}, {"source_code": "import List\n\nsolve :: [[Char]] -> Integer\nsolve = product . map (genericLength . group . sort) . transpose\nmain = interact $ show . solve . tail . lines"}, {"source_code": "import Data.List\n\nresult = foldl1 f.map (length.nub)\n\twhere f a b = (a*b)`mod`1000000007\n\nmain=interact$show.result.transpose.tail.lines\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = interact work\n\nwork :: String -> String\nwork = show . product . map (length . group . sort) . transpose . tail . lines\n"}, {"source_code": "import System.IO\nimport Data.List\n\nreadL :: Int -> IO [String]\nreadL n = sub n []\n where sub 0 l = return l\n sub n l = do ll <- getLine\n sub (n-1) (l ++ [ll])\n\nflatten :: [[a]] -> [a]\nflatten [[]] = []\nflatten ([]:ys) = flatten ys\nflatten ((x:xs):ys) = x:(flatten (xs:ys))\n\nrotate :: [String] -> [String]\nrotate l = sub l []\n where sub l acc\n | flatten l == [] = acc\n | otherwise = sub (map tail l) ((foldl (\\ac x -> (head x):ac) \"\" l):acc)\n\nmodInt :: Int\nmodInt = 1000000007\n\nmain :: IO ()\nmain = do\n f <- getLine\n cs <- readL . head $ map read (words f)\n let rcs = rotate cs\n ans = foldl (\\ac x -> ac * (length $ nub x) `mod` modInt) 1 rcs\n putStrLn $ show ans\n "}, {"source_code": "import Data.List \nimport Control.Monad\n\nfind_best grades =\n [i | (i, x) <- zip [1..] grades, x == best]\n where best = maximum grades\n\n\nsolve :: Ord a => [[a]] -> Int\nsolve grades =\n foldl mul 1 (map count grades)\n where count = length . group . sort\n mul a b = (a * b) `mod` (10^9 + 7)\n\nmain = do\n (n:_) <- (getLine >>= return . map (read::String->Int) . words)\n xs <- forM [1..n] (\\_ -> getLine >>= (return ))\n -- print $ transpose xs\n print $ solve (transpose xs)"}], "src_uid": "a37df9b239a40473516d1525d56a0da7"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE RankNTypes #-}\n\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport Data.Semigroup\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n#if __GLASGOW_HASKELL__ >= 713\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Reader\nimport Data.Functor.Identity\n#endif\n\nimport Control.Monad.ST.Safe\nimport Data.Function\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Int\nimport Data.STRef\nimport qualified Data.List as List\nimport qualified Data.Array as Arr\n\n-- {{{ Functors\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Identity a = Identity {runIdentity :: a}\n\ninstance Functor Identity where\n fmap f (Identity x) = Identity $ f x\n#endif\n\n-- }}}\n\n-- {{{ Monads\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Reader a b = Reader {runReader :: a -> b}\nnewtype State s a = State {runState :: s -> (a, s)}\n\ninstance Functor (Reader a) where\n fmap f = Reader . (f . ). runReader\n {-# INLINE fmap #-}\n\ninstance Applicative (Reader a) where\n pure = Reader . const\n {-# INLINE pure #-}\n a <*> b = Reader f'\n where\n f1 = runReader a\n f2 = runReader b\n f' = \\p -> (f1 p) (f2 p)\n {-# INLINE (<*>) #-}\n\ninstance Monad (Reader a) where\n r1 >>= r2 = Reader $ \\a -> runReader (r2 $ runReader r1 a) a\n {-# INLINE (>>=) #-}\n return = pure\n\nask :: Reader a a\nask = Reader id\n{-# INLINE ask #-}\nlocal :: (a -> a) -> Reader a b -> Reader a b\nlocal f r = let f' = (runReader r) . f in Reader f'\n{-# INLINE local #-}\n\ninstance Functor (State s) where\n fmap f st = State $ \\s -> let (a, s') = runState st s in (f a, s')\n\ninstance Applicative (State s) where\n pure = State . (,)\n {-# INLINE pure #-}\n s1 <*> s2 = State $ \\s ->\n let (f, s') = runState s1 s\n (a, s'') = runState s2 s'\n in (f a, s'')\n\ninstance Monad (State s) where\n s1 >>= ms2 = State $ \\s ->\n let (a, s') = runState s1 s\n in runState (ms2 a) s'\n return = pure\n\nput :: s -> State s ()\nput = State . const . ((,) ())\n{-# INLINE put #-}\nget :: State s s\nget = State $ \\s -> (s, s)\n{-# INLINE get #-}\nexecState :: State s a -> s -> s\nexecState st s0 = snd $ runState st s0\n#endif\n\n-- }}}\n\n-- {{{ Lens\n\ntype CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t\ntype CylLens' a b = CylLens a a b b\nlens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t\nlens r w g b = w b <$> g (r b)\n{-# INLINE lens #-}\niso :: (a -> b) -> (b -> a) -> CylLens' a b\niso f f' = let f'' _ a = f a in lens f' f''\n{-# INLINE iso #-}\nlensGet :: CylLens a s b t -> b -> a\nlensGet lens = getConst . lens Const\n{-# INLINE lensGet #-}\nlensSet :: CylLens a s b t -> b -> s -> t\nlensSet lens b s = runIdentity $ lens (Identity . const s) b\n{-# INLINE lensSet #-}\n\n#if __GLASGOW_HASKELL__ < 713\ninfix 1 &\n#endif\n\ninfix 8 ^.\ninfix 4 .=, %=\ninfixr 4 .~, %~\n\n#if __GLASGOW_HASKELL__ < 713\n(&) :: a -> (a -> b) -> b\na & f = f a\n{-# INLINE (&) #-}\n#endif\n\n(^.) :: b -> CylLens a s b t -> a\nb ^. lens = lensGet lens b\n{-# INLINE (^.) #-}\n(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)\n(lens %~ f) b = lensSet lens b (f $ lensGet lens b)\n{-# INLINE (%~) #-}\n(.~) :: CylLens a s b t -> s -> (b -> t)\n(lens .~ v) b = lensSet lens b v\n{-# INLINE (.~) #-}\n(.=) :: CylLens a a' s s -> a' -> State s ()\nlens .= v = do {s <- get; put $ s & lens .~ v}\n{-# INLINE (.=) #-}\n(%=) :: CylLens a a' s s -> (a -> a') -> State s ()\nlens %= f = do {s <- get; put $ s & lens %~ f}\n{-# INLINE (%=) #-}\nview :: CylLens a a' s s' -> Reader s a\nview l = ask >>= return . (^. l)\nuse :: CylLens a a' s s' -> State s a\nuse l = get >>= return . (^. l)\nzoom :: CylLens' s' s -> State s' c -> State s c\nzoom l m = do\n s' <- use l\n let (c, s'') = runState m s'\n l .= s''\n return c\n\n-- }}}\n\n-- {{{ Common used lens\n\nclass Has1 m a | m -> a where\n _1 :: CylLens' a m\n\nclass Has2 m a | m -> a where\n _2 :: CylLens' a m\n\nclass Has3 m a | m -> a where\n _3 :: CylLens' a m\n\nclass Has4 m a | m -> a where\n _4 :: CylLens' a m\n\nclass Has5 m a | m -> a where\n _5 :: CylLens' a m\n\nclass Has6 m a | m -> a where\n _6 :: CylLens' a m\n\ninstance Has1 ((,) a b) a where\n _1 = lens fst $ \\(a, b) c -> (c, b)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,) a b c) a where\n _1 = lens (\\(a, _, _) -> a) $ \\(a, b, c) d -> (d, b, c)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,) a b c d) a where\n _1 = lens (\\(a, _, _, _) -> a) $ \\(a, b, c, d) e -> (e, b, c, d)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,) a b c d e) a where\n _1 = lens (\\(a, _, _, _, _) -> a) $ \\(a, b, c, d, e) f -> (f, b, c, d, e)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,,) a b c d e f) a where\n _1 = lens (\\(a, _, _, _, _, _) -> a) $ \\(a, b, c, d, e, f) g -> (g, b, c, d, e, f)\n {-# INLINE _1 #-}\n\ninstance Has2 ((,) a b) b where\n _2 = lens snd $ \\(a, b) c -> (a, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,) a b c) b where\n _2 = lens (\\(_, b, _) -> b) $ \\(a, b, c) d -> (a, d, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,) a b c d) b where\n _2 = lens (\\(_, b, _, _) -> b) $ \\(a, b, c, d) e -> (a, e, c, d)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,) a b c d e) b where\n _2 = lens (\\(_, b, _, _, _) -> b) $ \\(a, b, c, d, e) f -> (a, f, c, d, e)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,,) a b c d e f) b where\n _2 = lens (\\(_, b, _, _, _, _) -> b) $ \\(a, b, c, d, e, f) g -> (a, g, c, d, e, f)\n {-# INLINE _2 #-}\n\ninstance Has3 ((,,) a b c) c where\n _3 = lens (\\(_, _, c) -> c) $ \\(a, b, c) d -> (a, b, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,) a b c d) c where\n _3 = lens (\\(_, _, c, _) -> c) $ \\(a, b, c, d) e -> (a, b, e, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,) a b c d e) c where\n _3 = lens (\\(_, _, c, _, _) -> c) $ \\(a, b, c, d, e) f -> (a, b, f, d, e)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,,) a b c d e f) c where\n _3 = lens (\\(_, _, c, _, _, _) -> c) $ \\(a, b, c, d, e, f) g -> (a, b, g, d, e, f)\n {-# INLINE _3 #-}\n\ninstance Has4 ((,,,) a b c d) d where\n _4 = lens (\\(_, _, _, d) -> d) $ \\(a, b, c, d) e -> (a, b, c, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,) a b c d e) d where\n _4 = lens (\\(_, _, _, d, _) -> d) $ \\(a, b, c, d, e) f -> (a, b, c, f, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,,) a b c d e f) d where\n _4 = lens (\\(_, _, _, d, _, _) -> d) $ \\(a, b, c, d, e, f) g -> (a, b, c, g, e, f)\n {-# INLINE _4 #-}\n\ninstance Has5 ((,,,,) a b c d e) e where\n _5 = lens (\\(_, _, _, _, e) -> e) $ \\(a, b, c, d, e) f -> (a, b, c, d, f)\n {-# INLINE _5 #-}\n\ninstance Has5 ((,,,,,) a b c d e f) e where\n _5 = lens (\\(_, _, _, _, e, _) -> e) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, g, f)\n {-# INLINE _5 #-}\n\ninstance Has6 ((,,,,,) a b c d e f) f where\n _6 = lens (\\(_, _, _, _, _, f) -> f) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, e, g)\n {-# INLINE _6 #-}\n\n-- }}}\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadContents :: StringReader a -> IO a\nreadContents reader = do\n contents <- BS.getContents\n return $ readFrom contents reader\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\n-- {{{ Suffix Array\n\nnewtype SuffixArray = SA { runSA :: UArray Int32 Int32}\n\ndata SALcp = SALcp {\n _sa :: UArray Int32 Int32,\n _sarank :: UArray Int32 Int32,\n -- | salcp[i] = lcp(sa[i], sa[i + 1]) 0 <= i < n - 1\n _salcp :: UArray Int32 Int32\n} deriving (Show)\n\nmkSaDoubling :: (Ord a, Eq a) => [a] -> SuffixArray\nmkSaDoubling xs = case xs of\n [] -> SA $ array (0, -1) []\n _ -> let extendedSa = runST mk\n in extendedSa & tail & listArray (0, n - 1) & SA\n where\n n = fromIntegral $ length xs :: Int32\n newArr :: ST s (STUArray s Int32 Int32)\n newArr = newArray (0, n) 0\n\n mk = do\n rank1 <- newArr\n rank2 <- newArr\n radixArr <- newArray (0, n) [] :: ST s (STArray s Int32 [Int32])\n maxr0 <- rerank (return . (initXs!)) initSa rank1\n if maxr0 == n\n then return initSa\n else do\n let c sa' i = do\n idxs <- readArray radixArr i\n writeArray radixArr i []\n return $ List.foldl' (flip (:)) sa' idxs\n radixSort rankFn sa = do\n forM_ sa $ \\sidx -> do\n ridx <- rankFn sidx\n stack <- readArray radixArr ridx\n writeArray radixArr ridx (sidx:stack)\n foldM c [] [n, n - 1..0]\n goSa rollingRanks step sa = do\n let (sRank, tRank) = rollingRanks\n dRankFn d x = let y = x + d\n in if (y > n) then return 0 else readArray sRank y\n dRankFn2 i = (,) <$> dRankFn 0 i <*> dRankFn step i\n sa' <- radixSort (dRankFn step) sa\n sa'' <- radixSort (dRankFn 0) sa'\n maxRank <- rerank dRankFn2 sa'' tRank\n if maxRank == n\n then return sa''\n else goSa (tRank, sRank) (step + step) sa''\n goSa (rank1, rank2) 1 initSa\n\n\n initSa :: [Int32]\n initSa = zip [0..n - 1] xs & List.sortOn snd & map fst & (n:)\n\n mkArr :: [a] -> Arr.Array Int32 a\n mkArr zs = listArray (0, n - 1) zs\n initXs = mkArr xs\n\n rerank :: Eq b => (Int32 -> ST s b) -> [Int32] -> (STUArray s Int32 Int32) -> ST s Int32\n rerank valFn inds target = do\n writeArray target headInd 0\n counter <- newSTRef (0 :: Int32)\n forM_ indPairs $ \\(pi, i) -> do\n if pi == headInd\n then modifySTRef counter (+1)\n else do\n pv <- valFn pi\n iv <- valFn i\n when (pv /= iv) $ modifySTRef counter (+1)\n c <- readSTRef counter\n writeArray target i c\n readSTRef counter\n where\n headInd = head inds\n indPairs = zip inds (tail inds)\n\ngetSaLcp :: (Eq a, Ord a) => ([a] -> SuffixArray) -> [a] -> SALcp\ngetSaLcp saFn xs = SALcp sa rank saLcp\n where\n sa = runSA $ saFn xs\n n = (bounds sa & snd) + 1\n\n rank :: UArray Int32 Int32\n rank = array (0, n - 1) $ map (\\(x, y) -> (y, x)) $ assocs sa\n\n mkArr :: [a] -> Arr.Array Int32 a\n mkArr zs = listArray (0, n - 1) zs\n initXs = mkArr xs\n\n saLcp = scanl lcp' (-1, 0) [0..n - 1]\n & filter (inRange (0, n - 2) . fst)\n & array (0, n - 2)\n\n lcp' (r, prevLcp) suffixIdx =\n if thisRk == n - 1 then (n - 1, 0)\n else (thisRk, lcp')\n where\n thisRk = rank ! suffixIdx\n largerSuffixIdx = sa ! (thisRk + 1)\n lcp' = goLcp (max 0 (prevLcp - 1))\n\n goLcp l = l + (fromIntegral $ length $ takeWhile g [l..])\n where\n g l' =\n let thisEnd = suffixIdx + l'\n thatEnd = largerSuffixIdx + l'\n in (thisEnd < n) && (thatEnd < n)\n && (initXs ! thisEnd) == (initXs ! thatEnd)\n\n\n-- }}}\n\n-- {{{ DSU\n\nclass Monoid m => Group m where\n groupNegate :: m -> m\n\n-- a is of commutative Monoid\nclass (Group m, Monoid a) => Ring m a where\n ringMul :: m -> a -> a\n\ninstance Group () where\n groupNegate = id\n {-# INLINE groupNegate #-}\n\ninstance Group a => Ring a () where\n ringMul _ _ = ()\n {-# INLINE ringMul #-}\n\ndata DsuCell i r e =\n DsuRoot {\n componentSize :: Int,\n componentState :: r\n }\n | DsuChild {\n dsuFatherIndex :: i,\n dsuRelation :: e\n }\n\nnewtype STDsu s i r e = STDsu {_runDsu :: STArray s i (DsuCell i r e)}\n\nnewSTDsu :: Ix i => (i, i) -> [r] -> ST s (STDsu s i r e)\nnewSTDsu bnds rs = do\n newArr <- newListArray bnds $ map (DsuRoot 1) rs\n return $ STDsu newArr\n\nreadDsuCell :: Ix i => STDsu s i r e -> i -> ST s (DsuCell i r e)\nreadDsuCell dsu idx = flip readArray idx . _runDsu $ dsu\n\nisRootCell :: DsuCell i r e -> Bool\nisRootCell DsuRoot{} = True\nisRootCell _ = False\n\ndsuImmeidateRelation :: (Ix i, Monoid e) => i -> STDsu s i r e-> ST s e\ndsuImmeidateRelation idx dsuST = do\n cell <- readDsuCell dsuST idx\n case cell of\n DsuChild _ rel -> return rel\n DsuRoot{} -> return mempty\n\ndsuFather :: Ix i => i -> STDsu s i r e -> ST s i\ndsuFather idx dsuST = do\n cell <- readDsuCell dsuST idx\n case cell of\n DsuChild f _ -> return f\n DsuRoot{} -> return idx\n\nwriteDsuCell :: Ix i => STDsu s i r e -> i -> DsuCell i r e -> ST s ()\nwriteDsuCell = writeArray . _runDsu\n\nmodifyDsuCell :: Ix i => STDsu s i r e -> i -> (DsuCell i r e -> DsuCell i r e) -> ST s ()\nmodifyDsuCell dsuST i f = do\n cell <- readDsuCell dsuST i\n writeDsuCell dsuST i (f cell)\n\ndsuUpToRootAndCompress :: (Ix i, Monoid e) => i -> STDsu s i r e -> ST s (i, e)\ndsuUpToRootAndCompress idx dsuST = do\n fa <- dsuFather idx dsuST\n if fa == idx\n then return (idx, mempty)\n else do\n (rootIdx, faRel) <- dsuUpToRootAndCompress fa dsuST\n thisRel <- dsuImmeidateRelation idx dsuST\n let newRel = thisRel `mappend` faRel\n writeDsuCell dsuST idx (DsuChild rootIdx newRel)\n return (rootIdx, newRel)\n\ndsuUnion :: (Ix i, Ring e r, Group e) => i -> i -> e -> STDsu s i r e -> ST s ()\ndsuUnion from to rel dsuST = when (from /= to) $ do\n (fromRoot, fromRel) <- dsuUpToRootAndCompress from dsuST\n (toRoot, toRel) <- dsuUpToRootAndCompress to dsuST\n DsuRoot sFrom _ <- readDsuCell dsuST fromRoot\n DsuRoot sTo _ <- readDsuCell dsuST toRoot\n if sFrom <= sTo\n then connect fromRoot toRoot $\n groupNegate fromRel `mappend` rel `mappend` toRel\n else connect toRoot fromRoot $\n groupNegate toRel `mappend` groupNegate rel `mappend` fromRel\n where\n connect f newRoot newRel = do\n (DsuRoot sf cf) <- readDsuCell dsuST f\n writeDsuCell dsuST f $ DsuChild newRoot newRel\n modifyDsuCell dsuST newRoot $ \\(DsuRoot sR cR) ->\n DsuRoot (sR + sf) (ringMul newRel cf `mappend` cR)\n-- }}}\n\ninstance Ring () (Min Int32) where\n ringMul m a = a\n\ntype SolveState = (Int32, [Int])\n\nsolve :: [Int] -> [Int]\nsolve xs = zipWith go prefixes (elems getDupLen) & scanl1 addMod\n where\n modulo = 1000000007\n\n addMod x y = (x + y) `mod` modulo\n\n asArr :: Array i e -> Array i e\n asArr = id\n\n revSaLcp = getSaLcp mkSaDoubling $ reverse xs\n\n getDupLen =\n let SALcp sa _ salcp = revSaLcp\n n = (+1) . snd $ bounds sa\n in\n runSTUArray $ do\n dupLen <- newArray (0, n - 1) 0 :: ST s (STUArray s Int32 Int32)\n stackRef <- newSTRef []\n let reorderedLcp = assocs sa\n & map (\\(rk, sidx) ->\n let l = if rk == n - 1 then 0 else salcp ! rk\n in (sidx, Min l))\n & array (0, n - 1)\n & asArr\n & elems\n dsu <- newSTDsu (0, n - 1) reorderedLcp :: ST s (STDsu s Int32 (Min Int32) ())\n let popAndMerge y [] = return []\n popAndMerge y stack'@(z:_) = do\n dsuUnion y z () dsu\n return stack'\n updateMaxFrom f t = do\n (r, _) <- dsuUpToRootAndCompress f dsu\n Min l' <- (readDsuCell dsu r <&> componentState)\n l <- readArray dupLen (n - 1 - t)\n writeArray dupLen (n - 1 - t) (max l l')\n popCloserToEnd _ [] = return []\n popCloserToEnd x stack'@(y:ys) =\n if (y > x)\n then do\n updateMaxFrom y x\n return stack'\n else do\n updateMaxFrom y y\n stack'' <- popAndMerge y ys\n popCloserToEnd x stack''\n\n forM_ (elems sa) $ \\sidx -> do\n stack <- readSTRef stackRef\n stack' <- popCloserToEnd sidx stack\n writeSTRef stackRef (sidx:stack')\n return dupLen\n\n\n blacklist :: [Int32]\n blacklist = map (+(bit 4)) [12, 10, 7, 15]\n\n prefixes = xs & scanl (flip (:)) [] & tail\n\n lastDigits :: CylLens' Int32 SolveState\n lastDigits = _1\n\n lastCounts :: CylLens' [Int] SolveState\n lastCounts = _2\n\n p a x = a .|. (if x >= (bit 4)\n then x & (`clearBit` 4) & (`shiftL` 1) & (`setBit` 4)\n else x `shiftL` 1)\n\n app1 :: Int -> State SolveState Int\n app1 digit = do\n lastDigits %= (p $ fromIntegral digit)\n (ds, cs) <- get\n let numLastCs = if ds `elem` blacklist then 3 else 4\n newCount = (foldl addMod 0 $ take numLastCs cs)\n lastCounts %= (newCount:) . take 3\n return newCount\n\n go :: [Int] -> Int32 -> Int\n go prefix dupLen =\n mapM app1 prefix\n & flip runState (1, [1])\n & fst\n & drop (fromIntegral dupLen)\n & List.foldl' addMod 0\n\nmain :: IO ()\nmain = do\n s <- readContents $ do\n m <- getInt\n replicateM m getInt\n solve s & map show & unlines & putStrLn\n return ()\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE RankNTypes #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport Data.Semigroup\n\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n#if __GLASGOW_HASKELL__ >= 713\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Reader\nimport Data.Functor.Identity\n#endif\n\nimport Control.Monad.ST.Safe\nimport Data.Function\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Int\nimport Data.STRef\nimport qualified Data.List as List\nimport qualified Data.Array as Arr\n\n-- {{{ Functors\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Identity a = Identity {runIdentity :: a}\n\ninstance Functor Identity where\n fmap f (Identity x) = Identity $ f x\n#endif\n\n-- }}}\n\n-- {{{ Monads\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Reader a b = Reader {runReader :: a -> b}\nnewtype State s a = State {runState :: s -> (a, s)}\n\ninstance Functor (Reader a) where\n fmap f = Reader . (f . ). runReader\n {-# INLINE fmap #-}\n\ninstance Applicative (Reader a) where\n pure = Reader . const\n {-# INLINE pure #-}\n a <*> b = Reader f'\n where\n f1 = runReader a\n f2 = runReader b\n f' = \\p -> (f1 p) (f2 p)\n {-# INLINE (<*>) #-}\n\ninstance Monad (Reader a) where\n r1 >>= r2 = Reader $ \\a -> runReader (r2 $ runReader r1 a) a\n {-# INLINE (>>=) #-}\n return = pure\n\nask :: Reader a a\nask = Reader id\n{-# INLINE ask #-}\nlocal :: (a -> a) -> Reader a b -> Reader a b\nlocal f r = let f' = (runReader r) . f in Reader f'\n{-# INLINE local #-}\n\ninstance Functor (State s) where\n fmap f st = State $ \\s -> let (a, s') = runState st s in (f a, s')\n\ninstance Applicative (State s) where\n pure = State . (,)\n {-# INLINE pure #-}\n s1 <*> s2 = State $ \\s ->\n let (f, s') = runState s1 s\n (a, s'') = runState s2 s'\n in (f a, s'')\n\ninstance Monad (State s) where\n s1 >>= ms2 = State $ \\s ->\n let (a, s') = runState s1 s\n in runState (ms2 a) s'\n return = pure\n\nput :: s -> State s ()\nput = State . const . ((,) ())\n{-# INLINE put #-}\nget :: State s s\nget = State $ \\s -> (s, s)\n{-# INLINE get #-}\nexecState :: State s a -> s -> s\nexecState st s0 = snd $ runState st s0\n#endif\n\n-- }}}\n\n-- {{{ Lens\n\ntype CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t\ntype CylLens' a b = CylLens a a b b\nlens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t\nlens r w g b = w b <$> g (r b)\n{-# INLINE lens #-}\niso :: (a -> b) -> (b -> a) -> CylLens' a b\niso f f' = let f'' _ a = f a in lens f' f''\n{-# INLINE iso #-}\nlensGet :: CylLens a s b t -> b -> a\nlensGet lens = getConst . lens Const\n{-# INLINE lensGet #-}\nlensSet :: CylLens a s b t -> b -> s -> t\nlensSet lens b s = runIdentity $ lens (Identity . const s) b\n{-# INLINE lensSet #-}\n\n#if __GLASGOW_HASKELL__ < 713\ninfix 1 &\n#endif\n\ninfix 8 ^.\ninfix 4 .=, %=\ninfixr 4 .~, %~\n\n#if __GLASGOW_HASKELL__ < 713\n(&) :: a -> (a -> b) -> b\na & f = f a\n{-# INLINE (&) #-}\n#endif\n\n(^.) :: b -> CylLens a s b t -> a\nb ^. lens = lensGet lens b\n{-# INLINE (^.) #-}\n(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)\n(lens %~ f) b = lensSet lens b (f $ lensGet lens b)\n{-# INLINE (%~) #-}\n(.~) :: CylLens a s b t -> s -> (b -> t)\n(lens .~ v) b = lensSet lens b v\n{-# INLINE (.~) #-}\n(.=) :: CylLens a a' s s -> a' -> State s ()\nlens .= v = do {s <- get; put $ s & lens .~ v}\n{-# INLINE (.=) #-}\n(%=) :: CylLens a a' s s -> (a -> a') -> State s ()\nlens %= f = do {s <- get; put $ s & lens %~ f}\n{-# INLINE (%=) #-}\nview :: CylLens a a' s s' -> Reader s a\nview l = ask >>= return . (^. l)\nuse :: CylLens a a' s s' -> State s a\nuse l = get >>= return . (^. l)\nzoom :: CylLens' s' s -> State s' c -> State s c\nzoom l m = do\n s' <- use l\n let (c, s'') = runState m s'\n l .= s''\n return c\n\n-- }}}\n\n-- {{{ Common used lens\n\nclass Has1 m a | m -> a where\n _1 :: CylLens' a m\n\nclass Has2 m a | m -> a where\n _2 :: CylLens' a m\n\nclass Has3 m a | m -> a where\n _3 :: CylLens' a m\n\nclass Has4 m a | m -> a where\n _4 :: CylLens' a m\n\nclass Has5 m a | m -> a where\n _5 :: CylLens' a m\n\nclass Has6 m a | m -> a where\n _6 :: CylLens' a m\n\ninstance Has1 ((,) a b) a where\n _1 = lens fst $ \\(a, b) c -> (c, b)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,) a b c) a where\n _1 = lens (\\(a, _, _) -> a) $ \\(a, b, c) d -> (d, b, c)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,) a b c d) a where\n _1 = lens (\\(a, _, _, _) -> a) $ \\(a, b, c, d) e -> (e, b, c, d)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,) a b c d e) a where\n _1 = lens (\\(a, _, _, _, _) -> a) $ \\(a, b, c, d, e) f -> (f, b, c, d, e)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,,) a b c d e f) a where\n _1 = lens (\\(a, _, _, _, _, _) -> a) $ \\(a, b, c, d, e, f) g -> (g, b, c, d, e, f)\n {-# INLINE _1 #-}\n\ninstance Has2 ((,) a b) b where\n _2 = lens snd $ \\(a, b) c -> (a, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,) a b c) b where\n _2 = lens (\\(_, b, _) -> b) $ \\(a, b, c) d -> (a, d, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,) a b c d) b where\n _2 = lens (\\(_, b, _, _) -> b) $ \\(a, b, c, d) e -> (a, e, c, d)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,) a b c d e) b where\n _2 = lens (\\(_, b, _, _, _) -> b) $ \\(a, b, c, d, e) f -> (a, f, c, d, e)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,,) a b c d e f) b where\n _2 = lens (\\(_, b, _, _, _, _) -> b) $ \\(a, b, c, d, e, f) g -> (a, g, c, d, e, f)\n {-# INLINE _2 #-}\n\ninstance Has3 ((,,) a b c) c where\n _3 = lens (\\(_, _, c) -> c) $ \\(a, b, c) d -> (a, b, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,) a b c d) c where\n _3 = lens (\\(_, _, c, _) -> c) $ \\(a, b, c, d) e -> (a, b, e, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,) a b c d e) c where\n _3 = lens (\\(_, _, c, _, _) -> c) $ \\(a, b, c, d, e) f -> (a, b, f, d, e)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,,) a b c d e f) c where\n _3 = lens (\\(_, _, c, _, _, _) -> c) $ \\(a, b, c, d, e, f) g -> (a, b, g, d, e, f)\n {-# INLINE _3 #-}\n\ninstance Has4 ((,,,) a b c d) d where\n _4 = lens (\\(_, _, _, d) -> d) $ \\(a, b, c, d) e -> (a, b, c, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,) a b c d e) d where\n _4 = lens (\\(_, _, _, d, _) -> d) $ \\(a, b, c, d, e) f -> (a, b, c, f, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,,) a b c d e f) d where\n _4 = lens (\\(_, _, _, d, _, _) -> d) $ \\(a, b, c, d, e, f) g -> (a, b, c, g, e, f)\n {-# INLINE _4 #-}\n\ninstance Has5 ((,,,,) a b c d e) e where\n _5 = lens (\\(_, _, _, _, e) -> e) $ \\(a, b, c, d, e) f -> (a, b, c, d, f)\n {-# INLINE _5 #-}\n\ninstance Has5 ((,,,,,) a b c d e f) e where\n _5 = lens (\\(_, _, _, _, e, _) -> e) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, g, f)\n {-# INLINE _5 #-}\n\ninstance Has6 ((,,,,,) a b c d e f) f where\n _6 = lens (\\(_, _, _, _, _, f) -> f) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, e, g)\n {-# INLINE _6 #-}\n\n-- }}}\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadContents :: StringReader a -> IO a\nreadContents reader = do\n contents <- BS.getContents\n return $ readFrom contents reader\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\n-- {{{ Suffix Array\n\nnewtype SuffixArray = SA { runSA :: UArray Int32 Int32}\n\ndata SALcp = SALcp {\n _sa :: UArray Int32 Int32,\n _sarank :: UArray Int32 Int32,\n -- | salcp[i] = lcp(sa[i], sa[i + 1]) 0 <= i < n - 1\n _salcp :: UArray Int32 Int32\n} deriving (Show)\n\nmkSaDoubling :: (Ord a, Eq a) => [a] -> SuffixArray\nmkSaDoubling xs = case xs of\n [] -> SA $ array (0, -1) []\n _ -> let extendedSa = runST mk\n in extendedSa & tail & listArray (0, n - 1) & SA\n where\n n = fromIntegral $ length xs :: Int32\n newArr :: ST s (STUArray s Int32 Int32)\n newArr = newArray (0, n) 0\n\n mk = do\n rank1 <- newArr\n rank2 <- newArr\n radixArr <- newArray (0, n) [] :: ST s (STArray s Int32 [Int32])\n maxr0 <- rerank (return . (initXs!)) initSa rank1\n if maxr0 == n\n then return initSa\n else do\n let c sa' i = do\n idxs <- readArray radixArr i\n writeArray radixArr i []\n return $ List.foldl' (flip (:)) sa' idxs\n radixSort rankFn sa = do\n forM_ sa $ \\sidx -> do\n ridx <- rankFn sidx\n stack <- readArray radixArr ridx\n writeArray radixArr ridx (sidx:stack)\n foldM c [] [n, n - 1..0]\n goSa rollingRanks step sa = do\n let (sRank, tRank) = rollingRanks\n dRankFn d x = let y = x + d\n in if (y > n) then return 0 else readArray sRank y\n dRankFn2 i = (,) <$> dRankFn 0 i <*> dRankFn step i\n sa' <- radixSort (dRankFn step) sa\n sa'' <- radixSort (dRankFn 0) sa'\n maxRank <- rerank dRankFn2 sa'' tRank\n if maxRank == n\n then return sa''\n else goSa (tRank, sRank) (step + step) sa''\n goSa (rank1, rank2) 1 initSa\n\n\n initSa :: [Int32]\n initSa = zip [0..n - 1] xs & List.sortOn snd & map fst & (n:)\n\n mkArr :: [a] -> Arr.Array Int32 a\n mkArr zs = listArray (0, n - 1) zs\n initXs = mkArr xs\n\n rerank :: Eq b => (Int32 -> ST s b) -> [Int32] -> (STUArray s Int32 Int32) -> ST s Int32\n rerank valFn inds target = do\n writeArray target headInd 0\n counter <- newSTRef (0 :: Int32)\n forM_ indPairs $ \\(pi, i) -> do\n if pi == headInd\n then modifySTRef counter (+1)\n else do\n pv <- valFn pi\n iv <- valFn i\n when (pv /= iv) $ modifySTRef counter (+1)\n c <- readSTRef counter\n writeArray target i c\n readSTRef counter\n where\n headInd = head inds\n indPairs = zip inds (tail inds)\n\ngetSaLcp :: (Eq a, Ord a) => ([a] -> SuffixArray) -> [a] -> SALcp\ngetSaLcp saFn xs = SALcp sa rank saLcp\n where\n sa = runSA $ saFn xs\n n = (bounds sa & snd) + 1\n\n rank :: UArray Int32 Int32\n rank = array (0, n - 1) $ map (\\(x, y) -> (y, x)) $ assocs sa\n\n mkArr :: [a] -> Arr.Array Int32 a\n mkArr zs = listArray (0, n - 1) zs\n initXs = mkArr xs\n\n saLcp = scanl lcp' (-1, 0) [0..n - 1]\n & filter (inRange (0, n - 2) . fst)\n & array (0, n - 2)\n\n lcp' (r, prevLcp) suffixIdx =\n if thisRk == n - 1 then (n - 1, 0)\n else (thisRk, lcp')\n where\n thisRk = rank ! suffixIdx\n largerSuffixIdx = sa ! (thisRk + 1)\n lcp' = goLcp (max 0 (prevLcp - 1))\n\n goLcp l = l + (fromIntegral $ length $ takeWhile g [l..])\n where\n g l' =\n let thisEnd = suffixIdx + l'\n thatEnd = largerSuffixIdx + l'\n in (thisEnd < n) && (thatEnd < n)\n && (initXs ! thisEnd) == (initXs ! thatEnd)\n\n\n-- }}}\n\n-- {{{ DSU\n\nclass Monoid m => Group m where\n groupNegate :: m -> m\n\n-- a is of commutative Monoid\nclass (Group m, Monoid a) => Ring m a where\n ringMul :: m -> a -> a\n\ninstance Group () where\n groupNegate = id\n {-# INLINE groupNegate #-}\n\ninstance Group a => Ring a () where\n ringMul _ _ = ()\n {-# INLINE ringMul #-}\n\ndata DsuCell i r e =\n DsuRoot {\n componentSize :: Int,\n componentState :: r\n }\n | DsuChild {\n dsuFatherIndex :: i,\n dsuRelation :: e\n }\n\nnewtype STDsu s i r e = STDsu {_runDsu :: STArray s i (DsuCell i r e)}\n\nnewSTDsu :: Ix i => (i, i) -> [r] -> ST s (STDsu s i r e)\nnewSTDsu bnds rs = do\n newArr <- newListArray bnds $ map (DsuRoot 1) rs\n return $ STDsu newArr\n\nreadDsuCell :: Ix i => STDsu s i r e -> i -> ST s (DsuCell i r e)\nreadDsuCell dsu idx = flip readArray idx . _runDsu $ dsu\n\nisRootCell :: DsuCell i r e -> Bool\nisRootCell DsuRoot{} = True\nisRootCell _ = False\n\ndsuImmeidateRelation :: (Ix i, Monoid e) => i -> STDsu s i r e-> ST s e\ndsuImmeidateRelation idx dsuST = do\n cell <- readDsuCell dsuST idx\n case cell of\n DsuChild _ rel -> return rel\n DsuRoot{} -> return mempty\n\ndsuFather :: Ix i => i -> STDsu s i r e -> ST s i\ndsuFather idx dsuST = do\n cell <- readDsuCell dsuST idx\n case cell of\n DsuChild f _ -> return f\n DsuRoot{} -> return idx\n\nwriteDsuCell :: Ix i => STDsu s i r e -> i -> DsuCell i r e -> ST s ()\nwriteDsuCell = writeArray . _runDsu\n\nmodifyDsuCell :: Ix i => STDsu s i r e -> i -> (DsuCell i r e -> DsuCell i r e) -> ST s ()\nmodifyDsuCell dsuST i f = do\n cell <- readDsuCell dsuST i\n writeDsuCell dsuST i (f cell)\n\ndsuUpToRootAndCompress :: (Ix i, Monoid e) => i -> STDsu s i r e -> ST s (i, e)\ndsuUpToRootAndCompress idx dsuST = do\n fa <- dsuFather idx dsuST\n if fa == idx\n then return (idx, mempty)\n else do\n (rootIdx, faRel) <- dsuUpToRootAndCompress fa dsuST\n thisRel <- dsuImmeidateRelation idx dsuST\n let newRel = thisRel `mappend` faRel\n writeDsuCell dsuST idx (DsuChild rootIdx newRel)\n return (rootIdx, newRel)\n\ndsuUnion :: (Ix i, Ring e r, Group e) => i -> i -> e -> STDsu s i r e -> ST s ()\ndsuUnion from to rel dsuST = when (from /= to) $ do\n (fromRoot, fromRel) <- dsuUpToRootAndCompress from dsuST\n (toRoot, toRel) <- dsuUpToRootAndCompress to dsuST\n DsuRoot sFrom _ <- readDsuCell dsuST fromRoot\n DsuRoot sTo _ <- readDsuCell dsuST toRoot\n if sFrom <= sTo\n then connect fromRoot toRoot $\n groupNegate fromRel `mappend` rel `mappend` toRel\n else connect toRoot fromRoot $\n groupNegate toRel `mappend` groupNegate rel `mappend` fromRel\n where\n connect f newRoot newRel = do\n (DsuRoot sf cf) <- readDsuCell dsuST f\n writeDsuCell dsuST f $ DsuChild newRoot newRel\n modifyDsuCell dsuST newRoot $ \\(DsuRoot sR cR) ->\n DsuRoot (sR + sf) (ringMul newRel cf `mappend` cR)\n-- }}}\n\ninstance Ring () (Min Int32) where\n ringMul m a = a\n\ntype SolveState = (Int32, [Int])\n\ndata PrefixSolveState = PSS {\n _total :: Int\n}\n\nsolve :: [Int] -> [Int]\nsolve xs = zipWith go prefixes (elems getDupLen) & scanl1 addMod\n where\n modulo = 1000000007\n\n addMod x y = (x + y) `mod` modulo\n\n asArr :: Array i e -> Array i e\n asArr = id\n\n revSaLcp = getSaLcp mkSaDoubling $ reverse xs\n\n getDupLen =\n let SALcp sa _ salcp = revSaLcp\n n = (+1) . snd $ bounds sa\n in\n runSTUArray $ do\n dupLen <- newArray (0, n - 1) 0 :: ST s (STUArray s Int32 Int32)\n stackRef <- newSTRef []\n let reorderedLcp = assocs sa\n & map (\\(rk, sidx) ->\n let l = if rk == n - 1 then 0 else salcp ! rk\n in (sidx, Min l))\n & array (0, n - 1)\n & asArr\n & elems\n dsu <- newSTDsu (0, n - 1) reorderedLcp :: ST s (STDsu s Int32 (Min Int32) ())\n let popAndMerge y [] = return []\n popAndMerge y stack'@(z:_) = do\n dsuUnion y z () dsu\n return stack'\n updateMaxFrom f t = do\n (r, _) <- dsuUpToRootAndCompress f dsu\n Min l' <- (readDsuCell dsu r <&> componentState)\n l <- readArray dupLen (n - 1 - t)\n writeArray dupLen (n - 1 - t) (max l l')\n popCloserToEnd _ [] = return []\n popCloserToEnd x stack'@(y:ys) =\n if (y > x)\n then do\n updateMaxFrom y x\n return stack'\n else do\n updateMaxFrom y y\n stack'' <- popAndMerge y ys\n popCloserToEnd x stack''\n\n forM_ (elems sa) $ \\sidx -> do\n stack <- readSTRef stackRef\n stack' <- popCloserToEnd sidx stack\n writeSTRef stackRef (sidx:stack')\n return dupLen\n\n\n -- blacklist = map (map (\\c -> (ord c) - (ord '0')))\n -- [\"0011\", \"0101\", \"1110\", \"1111\"]\n blacklist :: [Int32]\n blacklist = map (+(bit 4)) [12, 10, 7, 15]\n\n prefixes = xs & scanl (flip (:)) [] & tail\n\n lastDigits :: CylLens' Int32 SolveState\n lastDigits = _1\n\n lastCounts :: CylLens' [Int] SolveState\n lastCounts = _2\n\n p a x = a .|. (if x >= (bit 4)\n then x & (`clearBit` 4) & (`shiftL` 1) & (`setBit` 4)\n else x `shiftL` 1)\n\n app1 :: Int -> State SolveState Int\n app1 digit = do\n lastDigits %= (p $ fromIntegral digit)\n (ds, cs) <- get\n let numLastCs = if ds `elem` blacklist then 3 else 4\n newCount = (foldl addMod 0 $ take numLastCs cs)\n lastCounts %= (newCount:) . take 3\n return newCount\n\n go :: [Int] -> Int32 -> Int\n go prefix dupLen =\n mapM app1 prefix\n & flip runState (1, [1])\n & fst\n & drop (fromIntegral dupLen)\n & List.foldl' addMod 0\n\nmain :: IO ()\nmain = do\n s <- readContents $ do\n m <- getInt\n replicateM m getInt\n solve s & map show & unlines & putStrLn\n return ()\n"}], "negative_code": [{"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Function\nimport Data.Functor\n\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n#if __GLASGOW_HASKELL__ >= 713\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Reader\nimport Data.Functor.Identity\n#endif\n\n-- {{{ Functors\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Identity a = Identity {runIdentity :: a}\n\ninstance Functor Identity where\n fmap f (Identity x) = Identity $ f x\n#endif\n\n-- }}}\n\n-- {{{ Monads\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Reader a b = Reader {runReader :: a -> b}\nnewtype State s a = State {runState :: s -> (a, s)}\n\ninstance Functor (Reader a) where\n fmap f = Reader . (f . ). runReader\n {-# INLINE fmap #-}\n\ninstance Applicative (Reader a) where\n pure = Reader . const\n {-# INLINE pure #-}\n a <*> b = Reader f'\n where\n f1 = runReader a\n f2 = runReader b\n f' = \\p -> (f1 p) (f2 p)\n {-# INLINE (<*>) #-}\n\ninstance Monad (Reader a) where\n r1 >>= r2 = Reader $ \\a -> runReader (r2 $ runReader r1 a) a\n {-# INLINE (>>=) #-}\n return = pure\n\nask :: Reader a a\nask = Reader id\n{-# INLINE ask #-}\nlocal :: (a -> a) -> Reader a b -> Reader a b\nlocal f r = let f' = (runReader r) . f in Reader f'\n{-# INLINE local #-}\n\ninstance Functor (State s) where\n fmap f st = State $ \\s -> let (a, s') = runState st s in (f a, s')\n\ninstance Applicative (State s) where\n pure = State . (,)\n {-# INLINE pure #-}\n s1 <*> s2 = State $ \\s ->\n let (f, s') = runState s1 s\n (a, s'') = runState s2 s'\n in (f a, s'')\n\ninstance Monad (State s) where\n s1 >>= ms2 = State $ \\s ->\n let (a, s') = runState s1 s\n in runState (ms2 a) s'\n return = pure\n\nput :: s -> State s ()\nput = State . const . ((,) ())\n{-# INLINE put #-}\nget :: State s s\nget = State $ \\s -> (s, s)\n{-# INLINE get #-}\nexecState :: State s a -> s -> s\nexecState st s0 = snd $ runState st s0\n#endif\n\n-- }}}\n\n-- {{{ Lens\n\ntype CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t\ntype CylLens' a b = CylLens a a b b\nlens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t\nlens r w g b = w b <$> g (r b)\n{-# INLINE lens #-}\niso :: (a -> b) -> (b -> a) -> CylLens' a b\niso f f' = let f'' _ a = f a in lens f' f''\n{-# INLINE iso #-}\nlensGet :: CylLens a s b t -> b -> a\nlensGet lens = getConst . lens Const\n{-# INLINE lensGet #-}\nlensSet :: CylLens a s b t -> b -> s -> t\nlensSet lens b s = runIdentity $ lens (Identity . const s) b\n{-# INLINE lensSet #-}\n\n#if __GLASGOW_HASKELL__ < 713\ninfix 1 &\n#endif\n\ninfix 8 ^.\ninfix 4 .=, %=\ninfixr 4 .~, %~\n\n#if __GLASGOW_HASKELL__ < 713\n(&) :: a -> (a -> b) -> b\na & f = f a\n{-# INLINE (&) #-}\n#endif\n\n(^.) :: b -> CylLens a s b t -> a\nb ^. lens = lensGet lens b\n{-# INLINE (^.) #-}\n(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)\n(lens %~ f) b = lensSet lens b (f $ lensGet lens b)\n{-# INLINE (%~) #-}\n(.~) :: CylLens a s b t -> s -> (b -> t)\n(lens .~ v) b = lensSet lens b v\n{-# INLINE (.~) #-}\n(.=) :: CylLens a a' s s -> a' -> State s ()\nlens .= v = do {s <- get; put $ s & lens .~ v}\n{-# INLINE (.=) #-}\n(%=) :: CylLens a a' s s -> (a -> a') -> State s ()\nlens %= f = do {s <- get; put $ s & lens %~ f}\n{-# INLINE (%=) #-}\nview :: CylLens a a' s s' -> Reader s a\nview l = ask >>= return . (^. l)\nuse :: CylLens a a' s s' -> State s a\nuse l = get >>= return . (^. l)\nzoom :: CylLens' s' s -> State s' c -> State s c\nzoom l m = do\n s' <- use l\n let (c, s'') = runState m s'\n l .= s''\n return c\n\n-- }}}\n\n-- {{{ Common used lens\n\nclass Has1 m a | m -> a where\n _1 :: CylLens' a m\n\nclass Has2 m a | m -> a where\n _2 :: CylLens' a m\n\nclass Has3 m a | m -> a where\n _3 :: CylLens' a m\n\nclass Has4 m a | m -> a where\n _4 :: CylLens' a m\n\nclass Has5 m a | m -> a where\n _5 :: CylLens' a m\n\nclass Has6 m a | m -> a where\n _6 :: CylLens' a m\n\ninstance Has1 ((,) a b) a where\n _1 = lens fst $ \\(a, b) c -> (c, b)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,) a b c) a where\n _1 = lens (\\(a, _, _) -> a) $ \\(a, b, c) d -> (d, b, c)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,) a b c d) a where\n _1 = lens (\\(a, _, _, _) -> a) $ \\(a, b, c, d) e -> (e, b, c, d)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,) a b c d e) a where\n _1 = lens (\\(a, _, _, _, _) -> a) $ \\(a, b, c, d, e) f -> (f, b, c, d, e)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,,) a b c d e f) a where\n _1 = lens (\\(a, _, _, _, _, _) -> a) $ \\(a, b, c, d, e, f) g -> (g, b, c, d, e, f)\n {-# INLINE _1 #-}\n\ninstance Has2 ((,) a b) b where\n _2 = lens snd $ \\(a, b) c -> (a, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,) a b c) b where\n _2 = lens (\\(_, b, _) -> b) $ \\(a, b, c) d -> (a, d, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,) a b c d) b where\n _2 = lens (\\(_, b, _, _) -> b) $ \\(a, b, c, d) e -> (a, e, c, d)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,) a b c d e) b where\n _2 = lens (\\(_, b, _, _, _) -> b) $ \\(a, b, c, d, e) f -> (a, f, c, d, e)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,,) a b c d e f) b where\n _2 = lens (\\(_, b, _, _, _, _) -> b) $ \\(a, b, c, d, e, f) g -> (a, g, c, d, e, f)\n {-# INLINE _2 #-}\n\ninstance Has3 ((,,) a b c) c where\n _3 = lens (\\(_, _, c) -> c) $ \\(a, b, c) d -> (a, b, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,) a b c d) c where\n _3 = lens (\\(_, _, c, _) -> c) $ \\(a, b, c, d) e -> (a, b, e, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,) a b c d e) c where\n _3 = lens (\\(_, _, c, _, _) -> c) $ \\(a, b, c, d, e) f -> (a, b, f, d, e)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,,) a b c d e f) c where\n _3 = lens (\\(_, _, c, _, _, _) -> c) $ \\(a, b, c, d, e, f) g -> (a, b, g, d, e, f)\n {-# INLINE _3 #-}\n\ninstance Has4 ((,,,) a b c d) d where\n _4 = lens (\\(_, _, _, d) -> d) $ \\(a, b, c, d) e -> (a, b, c, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,) a b c d e) d where\n _4 = lens (\\(_, _, _, d, _) -> d) $ \\(a, b, c, d, e) f -> (a, b, c, f, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,,) a b c d e f) d where\n _4 = lens (\\(_, _, _, d, _, _) -> d) $ \\(a, b, c, d, e, f) g -> (a, b, c, g, e, f)\n {-# INLINE _4 #-}\n\ninstance Has5 ((,,,,) a b c d e) e where\n _5 = lens (\\(_, _, _, _, e) -> e) $ \\(a, b, c, d, e) f -> (a, b, c, d, f)\n {-# INLINE _5 #-}\n\ninstance Has5 ((,,,,,) a b c d e f) e where\n _5 = lens (\\(_, _, _, _, e, _) -> e) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, g, f)\n {-# INLINE _5 #-}\n\ninstance Has6 ((,,,,,) a b c d e f) f where\n _6 = lens (\\(_, _, _, _, _, f) -> f) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, e, g)\n {-# INLINE _6 #-}\n\n-- }}}\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadContents :: StringReader a -> IO a\nreadContents reader = do\n contents <- BS.getContents\n return $ readFrom contents reader\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\ntype SolveState = ([Int], [Int])\ntype SolveStateMap = Map.Map Int SolveState\n\ndata PrefixSolveState = PSS {\n _ssm :: SolveStateMap,\n _total :: Int\n}\n_pssIso :: CylLens' (SolveStateMap, Int) PrefixSolveState\n_pssIso = iso (uncurry PSS) (\\(PSS a b) -> (a, b))\nssm :: CylLens' SolveStateMap PrefixSolveState\nssm = _pssIso . _1\ntotal :: CylLens' Int PrefixSolveState\ntotal = _pssIso . _2\n\nsolve :: [Int] -> [Int]\nsolve xs = scanl1 addMod $ fst $ runState resultM (Map.singleton 0 ([], [1]))\n where\n modulo = 1000000007\n factor = 7919\n\n addMod x y = (x + y) `mod` modulo\n\n blacklist = map (map (\\c -> (ord c) - (ord '0')))\n [\"0011\", \"0101\", \"1110\", \"1111\"]\n\n prefixes = xs & scanl (flip (:)) [] & drop 1\n resultM = forM prefixes app\n\n lastDigits :: CylLens' [Int] SolveState\n lastDigits = _1\n\n lastCounts :: CylLens' [Int] SolveState\n lastCounts = _2\n\n p a = (a:) . take 3\n\n app1 :: Int -> State SolveState ()\n app1 digit = do\n lastDigits %= (p digit)\n (ds, cs) <- get\n let numLastCs = if ds `elem` blacklist then 3 else 4\n newCount = (foldl addMod 0 $ take numLastCs cs)\n lastCounts %= (p newCount)\n return ()\n\n hashSeq :: [Int] -> [Int]\n hashSeq = drop 1 . scanl (\\ph x -> (ph * factor + x + 1) `mod` modulo) 0\n\n app :: [Int] -> State SolveStateMap Int\n app prefix = prefixResult\n where\n hs = hashSeq prefix\n\n getPhs :: SolveStateMap -> [(Int, Int, Int)]\n getPhs ssm = prefix\n & zip hs\n & zipWith (\\prevH (h, p) -> (prevH, h, p)) (0:hs)\n\n app' :: (Int, Int, Int) -> State PrefixSolveState ()\n app' (prevH, h, c) = do\n stateMap <- use ssm\n let prevS = stateMap Map.! prevH\n newS = execState (app1 c) prevS\n ssm %= Map.insert h newS\n let cnt = newS ^. lastCounts & head\n total %= (addMod cnt)\n\n prefixResult :: State SolveStateMap Int\n prefixResult = do\n stateMap <- get\n let phs = getPhs stateMap\n & filter (not . (`Map.member` stateMap) . (^. _2))\n m = forM_ phs app'\n pss = execState m (PSS stateMap 0)\n put (pss ^. ssm)\n return (pss ^. total)\n\nmain :: IO ()\nmain = do\n s <- readContents $ do\n m <- getInt\n replicateM m getInt\n solve s & map show & unlines & putStrLn\n return ()\n"}, {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Function\nimport Data.Functor\n\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n#if __GLASGOW_HASKELL__ >= 713\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Reader\nimport Data.Functor.Identity\n#endif\n\n-- {{{ Functors\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Identity a = Identity {runIdentity :: a}\n\ninstance Functor Identity where\n fmap f (Identity x) = Identity $ f x\n#endif\n\n-- }}}\n\n-- {{{ Monads\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Reader a b = Reader {runReader :: a -> b}\nnewtype State s a = State {runState :: s -> (a, s)}\n\ninstance Functor (Reader a) where\n fmap f = Reader . (f . ). runReader\n {-# INLINE fmap #-}\n\ninstance Applicative (Reader a) where\n pure = Reader . const\n {-# INLINE pure #-}\n a <*> b = Reader f'\n where\n f1 = runReader a\n f2 = runReader b\n f' = \\p -> (f1 p) (f2 p)\n {-# INLINE (<*>) #-}\n\ninstance Monad (Reader a) where\n r1 >>= r2 = Reader $ \\a -> runReader (r2 $ runReader r1 a) a\n {-# INLINE (>>=) #-}\n return = pure\n\nask :: Reader a a\nask = Reader id\n{-# INLINE ask #-}\nlocal :: (a -> a) -> Reader a b -> Reader a b\nlocal f r = let f' = (runReader r) . f in Reader f'\n{-# INLINE local #-}\n\ninstance Functor (State s) where\n fmap f st = State $ \\s -> let (a, s') = runState st s in (f a, s')\n\ninstance Applicative (State s) where\n pure = State . (,)\n {-# INLINE pure #-}\n s1 <*> s2 = State $ \\s ->\n let (f, s') = runState s1 s\n (a, s'') = runState s2 s'\n in (f a, s'')\n\ninstance Monad (State s) where\n s1 >>= ms2 = State $ \\s ->\n let (a, s') = runState s1 s\n in runState (ms2 a) s'\n return = pure\n\nput :: s -> State s ()\nput = State . const . ((,) ())\n{-# INLINE put #-}\nget :: State s s\nget = State $ \\s -> (s, s)\n{-# INLINE get #-}\nexecState :: State s a -> s -> s\nexecState st s0 = snd $ runState st s0\n#endif\n\n-- }}}\n\n-- {{{ Lens\n\ntype CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t\ntype CylLens' a b = CylLens a a b b\nlens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t\nlens r w g b = w b <$> g (r b)\n{-# INLINE lens #-}\niso :: (a -> b) -> (b -> a) -> CylLens' a b\niso f f' = let f'' _ a = f a in lens f' f''\n{-# INLINE iso #-}\nlensGet :: CylLens a s b t -> b -> a\nlensGet lens = getConst . lens Const\n{-# INLINE lensGet #-}\nlensSet :: CylLens a s b t -> b -> s -> t\nlensSet lens b s = runIdentity $ lens (Identity . const s) b\n{-# INLINE lensSet #-}\n\n#if __GLASGOW_HASKELL__ < 713\ninfix 1 &\n#endif\n\ninfix 8 ^.\ninfix 4 .=, %=\ninfixr 4 .~, %~\n\n#if __GLASGOW_HASKELL__ < 713\n(&) :: a -> (a -> b) -> b\na & f = f a\n{-# INLINE (&) #-}\n#endif\n\n(^.) :: b -> CylLens a s b t -> a\nb ^. lens = lensGet lens b\n{-# INLINE (^.) #-}\n(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)\n(lens %~ f) b = lensSet lens b (f $ lensGet lens b)\n{-# INLINE (%~) #-}\n(.~) :: CylLens a s b t -> s -> (b -> t)\n(lens .~ v) b = lensSet lens b v\n{-# INLINE (.~) #-}\n(.=) :: CylLens a a' s s -> a' -> State s ()\nlens .= v = do {s <- get; put $ s & lens .~ v}\n{-# INLINE (.=) #-}\n(%=) :: CylLens a a' s s -> (a -> a') -> State s ()\nlens %= f = do {s <- get; put $ s & lens %~ f}\n{-# INLINE (%=) #-}\nview :: CylLens a a' s s' -> Reader s a\nview l = ask >>= return . (^. l)\nuse :: CylLens a a' s s' -> State s a\nuse l = get >>= return . (^. l)\nzoom :: CylLens' s' s -> State s' c -> State s c\nzoom l m = do\n s' <- use l\n let (c, s'') = runState m s'\n l .= s''\n return c\n\n-- }}}\n\n-- {{{ Common used lens\n\nclass Has1 m a | m -> a where\n _1 :: CylLens' a m\n\nclass Has2 m a | m -> a where\n _2 :: CylLens' a m\n\nclass Has3 m a | m -> a where\n _3 :: CylLens' a m\n\nclass Has4 m a | m -> a where\n _4 :: CylLens' a m\n\nclass Has5 m a | m -> a where\n _5 :: CylLens' a m\n\nclass Has6 m a | m -> a where\n _6 :: CylLens' a m\n\ninstance Has1 ((,) a b) a where\n _1 = lens fst $ \\(a, b) c -> (c, b)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,) a b c) a where\n _1 = lens (\\(a, _, _) -> a) $ \\(a, b, c) d -> (d, b, c)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,) a b c d) a where\n _1 = lens (\\(a, _, _, _) -> a) $ \\(a, b, c, d) e -> (e, b, c, d)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,) a b c d e) a where\n _1 = lens (\\(a, _, _, _, _) -> a) $ \\(a, b, c, d, e) f -> (f, b, c, d, e)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,,) a b c d e f) a where\n _1 = lens (\\(a, _, _, _, _, _) -> a) $ \\(a, b, c, d, e, f) g -> (g, b, c, d, e, f)\n {-# INLINE _1 #-}\n\ninstance Has2 ((,) a b) b where\n _2 = lens snd $ \\(a, b) c -> (a, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,) a b c) b where\n _2 = lens (\\(_, b, _) -> b) $ \\(a, b, c) d -> (a, d, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,) a b c d) b where\n _2 = lens (\\(_, b, _, _) -> b) $ \\(a, b, c, d) e -> (a, e, c, d)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,) a b c d e) b where\n _2 = lens (\\(_, b, _, _, _) -> b) $ \\(a, b, c, d, e) f -> (a, f, c, d, e)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,,) a b c d e f) b where\n _2 = lens (\\(_, b, _, _, _, _) -> b) $ \\(a, b, c, d, e, f) g -> (a, g, c, d, e, f)\n {-# INLINE _2 #-}\n\ninstance Has3 ((,,) a b c) c where\n _3 = lens (\\(_, _, c) -> c) $ \\(a, b, c) d -> (a, b, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,) a b c d) c where\n _3 = lens (\\(_, _, c, _) -> c) $ \\(a, b, c, d) e -> (a, b, e, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,) a b c d e) c where\n _3 = lens (\\(_, _, c, _, _) -> c) $ \\(a, b, c, d, e) f -> (a, b, f, d, e)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,,) a b c d e f) c where\n _3 = lens (\\(_, _, c, _, _, _) -> c) $ \\(a, b, c, d, e, f) g -> (a, b, g, d, e, f)\n {-# INLINE _3 #-}\n\ninstance Has4 ((,,,) a b c d) d where\n _4 = lens (\\(_, _, _, d) -> d) $ \\(a, b, c, d) e -> (a, b, c, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,) a b c d e) d where\n _4 = lens (\\(_, _, _, d, _) -> d) $ \\(a, b, c, d, e) f -> (a, b, c, f, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,,) a b c d e f) d where\n _4 = lens (\\(_, _, _, d, _, _) -> d) $ \\(a, b, c, d, e, f) g -> (a, b, c, g, e, f)\n {-# INLINE _4 #-}\n\ninstance Has5 ((,,,,) a b c d e) e where\n _5 = lens (\\(_, _, _, _, e) -> e) $ \\(a, b, c, d, e) f -> (a, b, c, d, f)\n {-# INLINE _5 #-}\n\ninstance Has5 ((,,,,,) a b c d e f) e where\n _5 = lens (\\(_, _, _, _, e, _) -> e) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, g, f)\n {-# INLINE _5 #-}\n\ninstance Has6 ((,,,,,) a b c d e f) f where\n _6 = lens (\\(_, _, _, _, _, f) -> f) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, e, g)\n {-# INLINE _6 #-}\n\n-- }}}\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadContents :: StringReader a -> IO a\nreadContents reader = do\n contents <- BS.getContents\n return $ readFrom contents reader\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\ntype SolveState = ([Int], [Int])\ntype SolveStateMap = Map.Map Int SolveState\n\ndata PrefixSolveState = PSS {\n _ssm :: SolveStateMap,\n _total :: Int\n}\n_pssIso :: CylLens' (SolveStateMap, Int) PrefixSolveState\n_pssIso = iso (uncurry PSS) (\\(PSS a b) -> (a, b))\nssm :: CylLens' SolveStateMap PrefixSolveState\nssm = _pssIso . _1\ntotal :: CylLens' Int PrefixSolveState\ntotal = _pssIso . _2\n\nsolve :: [Int] -> [Int]\nsolve xs = scanl1 (\\x y -> (x + y) `mod` modulo)\n $ fst $ runState resultM (Map.singleton 0 ([], [1]))\n where\n modulo = 1000000007\n factor = 1337\n\n blacklist = map (map (\\c -> (ord c) - (ord '0')))\n [\"0011\", \"0101\", \"1110\", \"1111\"]\n\n prefixes = xs & scanl (flip (:)) [] & drop 1\n resultM = forM prefixes app\n\n lastDigits :: CylLens' [Int] SolveState\n lastDigits = _1\n\n lastCounts :: CylLens' [Int] SolveState\n lastCounts = _2\n\n p a = (a:) . take 3\n\n app1 :: Int -> State SolveState ()\n app1 digit = do\n lastDigits %= (p digit)\n (ds, cs) <- get\n let numLastCs = if ds `elem` blacklist then 3 else 4\n newCount = (sum $ take numLastCs cs) `mod` modulo\n lastCounts %= (p newCount)\n return ()\n\n hashSeq :: [Int] -> [Int]\n hashSeq = drop 1 . scanl (\\ph x -> (ph * factor + x + 1) `mod` modulo) 0\n\n app :: [Int] -> State SolveStateMap Int\n app prefix = prefixResult\n where\n hs = hashSeq prefix\n\n getPhs :: SolveStateMap -> [(Int, Int, Int)]\n getPhs ssm = prefix\n & zip hs\n & zipWith (\\prevH (h, p) -> (prevH, h, p)) (0:hs)\n\n app' :: (Int, Int, Int) -> State PrefixSolveState ()\n app' (prevH, h, c) = do\n stateMap <- use ssm\n let prevS = stateMap Map.! prevH\n newS = execState (app1 c) prevS\n ssm %= Map.insert h newS\n let cnt = newS ^. lastCounts & head\n total %= (`mod` modulo) . (+cnt)\n\n prefixResult :: State SolveStateMap Int\n prefixResult = do\n stateMap <- get\n let phs = getPhs stateMap\n & filter (not . (`Map.member` stateMap) . (^. _2))\n m = forM_ phs app'\n pss = execState m (PSS stateMap 0)\n put (pss ^. ssm)\n return (pss ^. total)\n\nmain :: IO ()\nmain = do\n s <- readContents $ do\n m <- getInt\n replicateM m getInt\n solve s & map show & unlines & putStrLn\n return ()\n"}, {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.Function\nimport Data.Functor\n\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\n#if __GLASGOW_HASKELL__ >= 713\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Reader\nimport Data.Functor.Identity\n#endif\n\n-- {{{ Functors\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Identity a = Identity {runIdentity :: a}\n\ninstance Functor Identity where\n fmap f (Identity x) = Identity $ f x\n#endif\n\n-- }}}\n\n-- {{{ Monads\n\n#if __GLASGOW_HASKELL__ < 713\nnewtype Reader a b = Reader {runReader :: a -> b}\nnewtype State s a = State {runState :: s -> (a, s)}\n\ninstance Functor (Reader a) where\n fmap f = Reader . (f . ). runReader\n {-# INLINE fmap #-}\n\ninstance Applicative (Reader a) where\n pure = Reader . const\n {-# INLINE pure #-}\n a <*> b = Reader f'\n where\n f1 = runReader a\n f2 = runReader b\n f' = \\p -> (f1 p) (f2 p)\n {-# INLINE (<*>) #-}\n\ninstance Monad (Reader a) where\n r1 >>= r2 = Reader $ \\a -> runReader (r2 $ runReader r1 a) a\n {-# INLINE (>>=) #-}\n return = pure\n\nask :: Reader a a\nask = Reader id\n{-# INLINE ask #-}\nlocal :: (a -> a) -> Reader a b -> Reader a b\nlocal f r = let f' = (runReader r) . f in Reader f'\n{-# INLINE local #-}\n\ninstance Functor (State s) where\n fmap f st = State $ \\s -> let (a, s') = runState st s in (f a, s')\n\ninstance Applicative (State s) where\n pure = State . (,)\n {-# INLINE pure #-}\n s1 <*> s2 = State $ \\s ->\n let (f, s') = runState s1 s\n (a, s'') = runState s2 s'\n in (f a, s'')\n\ninstance Monad (State s) where\n s1 >>= ms2 = State $ \\s ->\n let (a, s') = runState s1 s\n in runState (ms2 a) s'\n return = pure\n\nput :: s -> State s ()\nput = State . const . ((,) ())\n{-# INLINE put #-}\nget :: State s s\nget = State $ \\s -> (s, s)\n{-# INLINE get #-}\nexecState :: State s a -> s -> s\nexecState st s0 = snd $ runState st s0\n#endif\n\n-- }}}\n\n-- {{{ Lens\n\ntype CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t\ntype CylLens' a b = CylLens a a b b\nlens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t\nlens r w g b = w b <$> g (r b)\n{-# INLINE lens #-}\niso :: (a -> b) -> (b -> a) -> CylLens' a b\niso f f' = let f'' _ a = f a in lens f' f''\n{-# INLINE iso #-}\nlensGet :: CylLens a s b t -> b -> a\nlensGet lens = getConst . lens Const\n{-# INLINE lensGet #-}\nlensSet :: CylLens a s b t -> b -> s -> t\nlensSet lens b s = runIdentity $ lens (Identity . const s) b\n{-# INLINE lensSet #-}\n\n#if __GLASGOW_HASKELL__ < 713\ninfix 1 &\n#endif\n\ninfix 8 ^.\ninfix 4 .=, %=\ninfixr 4 .~, %~\n\n#if __GLASGOW_HASKELL__ < 713\n(&) :: a -> (a -> b) -> b\na & f = f a\n{-# INLINE (&) #-}\n#endif\n\n(^.) :: b -> CylLens a s b t -> a\nb ^. lens = lensGet lens b\n{-# INLINE (^.) #-}\n(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)\n(lens %~ f) b = lensSet lens b (f $ lensGet lens b)\n{-# INLINE (%~) #-}\n(.~) :: CylLens a s b t -> s -> (b -> t)\n(lens .~ v) b = lensSet lens b v\n{-# INLINE (.~) #-}\n(.=) :: CylLens a a' s s -> a' -> State s ()\nlens .= v = do {s <- get; put $ s & lens .~ v}\n{-# INLINE (.=) #-}\n(%=) :: CylLens a a' s s -> (a -> a') -> State s ()\nlens %= f = do {s <- get; put $ s & lens %~ f}\n{-# INLINE (%=) #-}\nview :: CylLens a a' s s' -> Reader s a\nview l = ask >>= return . (^. l)\nuse :: CylLens a a' s s' -> State s a\nuse l = get >>= return . (^. l)\nzoom :: CylLens' s' s -> State s' c -> State s c\nzoom l m = do\n s' <- use l\n let (c, s'') = runState m s'\n l .= s''\n return c\n\n-- }}}\n\n-- {{{ Common used lens\n\nclass Has1 m a | m -> a where\n _1 :: CylLens' a m\n\nclass Has2 m a | m -> a where\n _2 :: CylLens' a m\n\nclass Has3 m a | m -> a where\n _3 :: CylLens' a m\n\nclass Has4 m a | m -> a where\n _4 :: CylLens' a m\n\nclass Has5 m a | m -> a where\n _5 :: CylLens' a m\n\nclass Has6 m a | m -> a where\n _6 :: CylLens' a m\n\ninstance Has1 ((,) a b) a where\n _1 = lens fst $ \\(a, b) c -> (c, b)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,) a b c) a where\n _1 = lens (\\(a, _, _) -> a) $ \\(a, b, c) d -> (d, b, c)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,) a b c d) a where\n _1 = lens (\\(a, _, _, _) -> a) $ \\(a, b, c, d) e -> (e, b, c, d)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,) a b c d e) a where\n _1 = lens (\\(a, _, _, _, _) -> a) $ \\(a, b, c, d, e) f -> (f, b, c, d, e)\n {-# INLINE _1 #-}\n\ninstance Has1 ((,,,,,) a b c d e f) a where\n _1 = lens (\\(a, _, _, _, _, _) -> a) $ \\(a, b, c, d, e, f) g -> (g, b, c, d, e, f)\n {-# INLINE _1 #-}\n\ninstance Has2 ((,) a b) b where\n _2 = lens snd $ \\(a, b) c -> (a, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,) a b c) b where\n _2 = lens (\\(_, b, _) -> b) $ \\(a, b, c) d -> (a, d, c)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,) a b c d) b where\n _2 = lens (\\(_, b, _, _) -> b) $ \\(a, b, c, d) e -> (a, e, c, d)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,) a b c d e) b where\n _2 = lens (\\(_, b, _, _, _) -> b) $ \\(a, b, c, d, e) f -> (a, f, c, d, e)\n {-# INLINE _2 #-}\n\ninstance Has2 ((,,,,,) a b c d e f) b where\n _2 = lens (\\(_, b, _, _, _, _) -> b) $ \\(a, b, c, d, e, f) g -> (a, g, c, d, e, f)\n {-# INLINE _2 #-}\n\ninstance Has3 ((,,) a b c) c where\n _3 = lens (\\(_, _, c) -> c) $ \\(a, b, c) d -> (a, b, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,) a b c d) c where\n _3 = lens (\\(_, _, c, _) -> c) $ \\(a, b, c, d) e -> (a, b, e, d)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,) a b c d e) c where\n _3 = lens (\\(_, _, c, _, _) -> c) $ \\(a, b, c, d, e) f -> (a, b, f, d, e)\n {-# INLINE _3 #-}\n\ninstance Has3 ((,,,,,) a b c d e f) c where\n _3 = lens (\\(_, _, c, _, _, _) -> c) $ \\(a, b, c, d, e, f) g -> (a, b, g, d, e, f)\n {-# INLINE _3 #-}\n\ninstance Has4 ((,,,) a b c d) d where\n _4 = lens (\\(_, _, _, d) -> d) $ \\(a, b, c, d) e -> (a, b, c, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,) a b c d e) d where\n _4 = lens (\\(_, _, _, d, _) -> d) $ \\(a, b, c, d, e) f -> (a, b, c, f, e)\n {-# INLINE _4 #-}\n\ninstance Has4 ((,,,,,) a b c d e f) d where\n _4 = lens (\\(_, _, _, d, _, _) -> d) $ \\(a, b, c, d, e, f) g -> (a, b, c, g, e, f)\n {-# INLINE _4 #-}\n\ninstance Has5 ((,,,,) a b c d e) e where\n _5 = lens (\\(_, _, _, _, e) -> e) $ \\(a, b, c, d, e) f -> (a, b, c, d, f)\n {-# INLINE _5 #-}\n\ninstance Has5 ((,,,,,) a b c d e f) e where\n _5 = lens (\\(_, _, _, _, e, _) -> e) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, g, f)\n {-# INLINE _5 #-}\n\ninstance Has6 ((,,,,,) a b c d e f) f where\n _6 = lens (\\(_, _, _, _, _, f) -> f) $ \\(a, b, c, d, e, f) g -> (a, b, c, d, e, g)\n {-# INLINE _6 #-}\n\n-- }}}\n\n-- {{{ Handy IO\n\ntype StringReader a = State BS.ByteString a\n\nreadContents :: StringReader a -> IO a\nreadContents reader = do\n contents <- BS.getContents\n return $ readFrom contents reader\n\nreadFrom :: BS.ByteString -> StringReader a -> a\nreadFrom s = fst . flip runState s\n\nisLineBreak :: Char -> Bool\nisLineBreak c = c == '\\n' || c == '\\r'\n\nstripLineBreak :: StringReader ()\nstripLineBreak = do\n modify $ BS.dropWhile isLineBreak\n\ngetLine :: StringReader BS.ByteString\ngetLine = do\n s <- get\n let (l, s') = BS.span (not . isLineBreak) s\n put s'\n stripLineBreak\n return l\n\nrestLines :: StringReader [BS.ByteString]\nrestLines = do\n s <- get\n put BS.empty\n return $ BS.lines s\n\ngetInt :: Num a => StringReader a\ngetInt = do\n s <- get\n let l' = BS.dropWhile isSpace s\n (d, ll') = BS.span isDigit l'\n put ll'\n return $ case BS.readInt d of\n Just (i, _) -> fromIntegral i\n Nothing -> error $ \"Not an integer: \" ++ show d\n\n-- }}}\n\ntype SolveState = ([Int], [Int])\ntype SolveStateMap = Map.Map Int SolveState\n\ndata PrefixSolveState = PSS {\n _ssm :: SolveStateMap,\n _total :: Int\n}\n_pssIso :: CylLens' (SolveStateMap, Int) PrefixSolveState\n_pssIso = iso (uncurry PSS) (\\(PSS a b) -> (a, b))\nssm :: CylLens' SolveStateMap PrefixSolveState\nssm = _pssIso . _1\ntotal :: CylLens' Int PrefixSolveState\ntotal = _pssIso . _2\n\nsolve :: [Int] -> [Int]\nsolve xs = scanl1 addMod $ fst $ runState resultM (Map.singleton 0 ([], [1]))\n where\n modulo = 1000000007\n factor = 1337\n\n addMod x y = (x + y) `mod` modulo\n\n blacklist = map (map (\\c -> (ord c) - (ord '0')))\n [\"0011\", \"0101\", \"1110\", \"1111\"]\n\n prefixes = xs & scanl (flip (:)) [] & drop 1\n resultM = forM prefixes app\n\n lastDigits :: CylLens' [Int] SolveState\n lastDigits = _1\n\n lastCounts :: CylLens' [Int] SolveState\n lastCounts = _2\n\n p a = (a:) . take 3\n\n app1 :: Int -> State SolveState ()\n app1 digit = do\n lastDigits %= (p digit)\n (ds, cs) <- get\n let numLastCs = if ds `elem` blacklist then 3 else 4\n newCount = (foldl addMod 0 $ take numLastCs cs) `mod` modulo\n lastCounts %= (p newCount)\n return ()\n\n hashSeq :: [Int] -> [Int]\n hashSeq = drop 1 . scanl (\\ph x -> (ph * factor + x + 1) `mod` modulo) 0\n\n app :: [Int] -> State SolveStateMap Int\n app prefix = prefixResult\n where\n hs = hashSeq prefix\n\n getPhs :: SolveStateMap -> [(Int, Int, Int)]\n getPhs ssm = prefix\n & zip hs\n & zipWith (\\prevH (h, p) -> (prevH, h, p)) (0:hs)\n\n app' :: (Int, Int, Int) -> State PrefixSolveState ()\n app' (prevH, h, c) = do\n stateMap <- use ssm\n let prevS = stateMap Map.! prevH\n newS = execState (app1 c) prevS\n ssm %= Map.insert h newS\n let cnt = newS ^. lastCounts & head\n total %= (`mod` modulo) . (+cnt)\n\n prefixResult :: State SolveStateMap Int\n prefixResult = do\n stateMap <- get\n let phs = getPhs stateMap\n & filter (not . (`Map.member` stateMap) . (^. _2))\n m = forM_ phs app'\n pss = execState m (PSS stateMap 0)\n put (pss ^. ssm)\n return (pss ^. total)\n\nmain :: IO ()\nmain = do\n s <- readContents $ do\n m <- getInt\n replicateM m getInt\n solve s & map show & unlines & putStrLn\n return ()\n"}], "src_uid": "6744d8bcba9ef2853788ca7168b76373"} {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: (Int, Int, Int) -> (Int, Int, Int)\nsolve (a, b, c) = (a + b + c, b + c, c)\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [a, b, c] <- B8.getLine <&> readIntB8s\n let (x, y, z) = solve (a, b, c)\n printf \"%d %d %d\\n\" x y z\n", "positive_code": [{"source_code": "\n\n\nparse :: String -> [(Int, Int, Int)]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> parseN (read w) ws\n where\n parseLine :: String -> (Int, Int, Int)\n parseLine = (\\[a, b, c] -> (a, b, c)) . map read . take 3 . words\n parseN :: Int -> [String] -> [(Int, Int, Int)]\n parseN t = map parseLine . take t\n\n\nsolve :: [(Int, Int, Int)] -> [(Int, Int, Int)]\nsolve = map (\\(a, b, c) -> (a+b+c, b+c, c))\n\nformat :: [(Int, Int, Int)] -> String\nformat = unlines . map (unwords . (\\(x, y, z) -> [show x, show y, show z]))\n\n\nmain :: IO ()\nmain = interact (format . solve . parse)\n\n\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nsolve :: Integer -> Integer -> Integer -> [Integer]\r\nsolve a b c = [a + b + c, b + c, c]\r\n \r\nmain = do\r\n n <- readLn :: IO Int\r\n replicateM_ n $ do\r\n [a, b, c] <- map read . words <$> getLine :: IO [Integer]\r\n putStrLn $ unwords $ map show $ solve a b c\r\n"}, {"source_code": "mainLoop 0 = return ()\nmainLoop t = do line <- getLine\n let [a, b, c] = map (read :: String -> Int) (words line)\n putStrLn (unwords [show (a + b + c), show (b + c), show c])\n mainLoop (t - 1)\n\nmain = do t <- (readLn :: IO Int)\n mainLoop t\n"}, {"source_code": "main :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\treturn ()\r\n\t\r\nsolve :: Int -> Int -> IO ()\r\nsolve number 0 = return ()\t\r\nsolve number current = \tdo\r\n\t\t\t\tline <- getLine\r\n\t\t\t\tlet ws = words line\r\n\t\t\t\tlet a = (read $ head ws) :: Int\r\n\t\t\t\tlet b = (read $ head $ tail ws) :: Int\r\n\t\t\t\tlet c = (read $ head $ tail $ tail ws) :: Int\r\n\t\t\t\tlet x = a + b + c\r\n\t\t\t\tlet y = b + c\r\n\t\t\t\tlet z = c\r\n\t\t\t\tputStrLn $ (show x) ++ \" \" ++ (show y) ++ \" \" ++ (show z)\r\n\t\t\t\tsolve number (current - 1)"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nputInts :: [Int] -> Builder\nputInts [] = charUtf8 '\\n'\nputInts (x : xs) = intDec x <> charUtf8 ' ' <> putInts xs\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [a, b, c] <- getInts\n let k = (c - a) `div` b + 1\n return $ putInts [k * b + a, b, c]\n hPutBuilder stdout output\n"}], "negative_code": [{"source_code": "\n\n\nparse :: String -> [(Int, Int, Int)]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> parseN (read w) ws\n where\n parseLine :: String -> (Int, Int, Int)\n parseLine = (\\[a, b, c] -> (a, b, c)) . map read . take 3 . words\n parseN :: Int -> [String] -> [(Int, Int, Int)]\n parseN t = map parseLine . take t\n\n\nsolve :: [(Int, Int, Int)] -> [(Int, Int, Int)]\nsolve = map (\\(a, b, c) -> (a+b+c, a+b, c))\n\nformat :: [(Int, Int, Int)] -> String\nformat = unlines . map (unwords . (\\(x, y, z) -> [show x, show y, show z]))\n\n\nmain :: IO ()\nmain = interact (format . solve . parse)\n\n\n"}, {"source_code": "\n\n\nparse :: String -> (Int, Int, Int)\nparse = (\\[a, b, c] -> (a, b, c)) . map read . take 3 . words\n\nsolve :: (Int, Int, Int) -> (Int, Int, Int)\nsolve (a, b, c) = (a+b+c, a+b, c)\n\nformat :: (Int, Int, Int) -> String\nformat (x, y, z) = unwords $ map show [x, y, z]\n\n\n\nmain :: IO ()\nmain = interact (format . solve . parse)\n\n\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\n\r\nsolve :: Int -> Int -> Int -> [Int]\r\nsolve a b c = [a + b + c, b + c, c]\r\n \r\nmain = do\r\n n <- readLn :: IO Int\r\n replicateM_ n $ do\r\n [a, b, c] <- map read . words <$> getLine :: IO [Int]\r\n print $ unwords $ map show $ solve a b c\r\n"}], "src_uid": "f0c22161cb5a9bc17320ccd05517f867"} {"source_code": "\nimport Control.Monad (liftM)\nimport List (sort)\n\n{-\nimport HUnit\n\ntest = run $ TestList \"Tests\"\n [\n Test \"Test #01\" $ assertEq 1 $ solve 1 [],\n Test \"Test #02\" $ assertEq 0 $ solve 1 [1,2],\n Test \"Test #03\" $ assertEq 0 $ solve 1 [2,1],\n Test \"Test #04\" $ assertEq 0 $ solve 2 [1,2,3],\n Test \"Test #05\" $ assertEq 0 $ solve 1 [1],\n Test \"Test #06\" $ assertEq 1 $ solve 2 [1,2],\n Test \"Test #07\" $ assertEq 3 $ solve 3 [2,1],\n Test \"Test #08\" $ assertEq 2 $ solve 1 [4,2,3,1],\n Test \"Test #09\" $ assertEq 1 $ solve 3 [1,2,4,5],\n Test \"Test #10\" $ assertEq 3 $ solve 4 [1,2,3,5],\n Test \"Test #11\" $ assertEq 0 $ solve 2 [1,2,2,2,4],\n Test \"Test #12\" $ assertEq 2 $ solve 1 [1,1,2,3,4,5],\n Test \"Test #13\" $ assertEq 1 $ solve 10 [10,20,30],\n Test \"Test #14\" $ assertEq 4 $ solve 4 [1,2,3]\n ]\n-}\n\nsolve :: Int -> [Int] -> Int\nsolve x xs = solve' n (find (1,0) (sort xs)) - n\n where\n n = length xs\n find (l,r) [] = (l, r)\n find (l,r) (y:ys)\n | y < x = find (l+1,r+1) ys\n | y == x = find (l, r+1) ys\n | otherwise = (l, r)\n solve' n (l,r)\n | n' >= l && n' <= r = n\n | otherwise = solve' (n+1) (l, r+1)\n where\n n' = div (n + 1) 2\n\nmain :: IO ()\nmain = do\n [_, x] <- liftM (map read . words) getLine\n xs <- liftM (map read . words) getLine\n print $ solve x xs\n", "positive_code": [{"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sun 21 Oct 2012 04:43:42 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n--{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (elemIndex)\nimport Data.List (elemIndices)\n\n\nmedian ls = head $ drop ((((length ls) + 1) `div` 2) - 1) ls\n\ncountDist x med sls len = \n if x == med\n then 0\n else if x < med\n then\n medind - (head $ reverse $ elemIndices x sls)\n else\n res - medind\n where\n medind = (len + 1) `div` 2 - 1 -- index\n res = \n let ans = elemIndex x sls\n in case ans of\n Just(y) -> y\n Nothing -> 0\n\n\ncalc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len\n where\n calcAdditions x med dist len= \n if x == med\n then 0\n else if len `mod` 2 == 0\n then if x < med\n then 2 * dist\n else 2 * dist - 1\n else if x < med\n then 2 * dist - 1\n else 2 * dist\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calc x sls (fromIntegral n)\n else\n print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Debug.Trace\n\ncountLess :: Integral a => [a] -> a -> a -> a -> (a,a)\ncountLess [] median count plithos = (count, plithos)\ncountLess (x:xs) median count plithos\n\t| x medPos) = 2*(countLess+1) - (length + 1)\n\t| (countLess+1 < medPos) = (length+1) + 1 - 2*(countLess+1)\n\twhere medPos = (length + 2) `div` 2\ncalcMinNum length countLess plithos \n\t| (countLess+1 <= medPos) && (countLess + plithos >= medPos) = 0\n\t| (countLess+1 > medPos) = 2*(countLess+1) - 1 - length\n\t| (countLess + plithos < medPos) = length - 2*(countLess + plithos)\n\twhere medPos = (length + 1) `div` 2\n\nsolve length median x = \n\tlet \n\t\t(countLessRes, plithos) = countLess x median 0 0\n\tin \n\t\tcalcMinNum length countLessRes plithos\n\n\nmain = \n do all <- BS.getContents\n let Just (length, r1) = readInteger all\n let Just (median, r2) = readInteger r1\n let (x, _) = readMany readInteger r2\n --print (length)\n --print (median)\n --print (x)\n print (solve length median x)\n -- print ((count_less x median 0 0) == length `div` 2)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n x <- readInt\n a <- replicateM n readInt\n return (x, a)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nmedian s = sort s !! ((length s - 1) `div` 2)\n\ninf = 10^5\n\nsolve (x, a)\n | m == x = 0\n | otherwise = solve (x, x : a) + 1\n where\n m = median a\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (_:x:ys)\n | notElem x ls = if l < g then g-l else l-g+1\n | l < g = g-l\n | otherwise = max 0 (l-lx-g-lx+1)\n where (ls,gs) = partition (<=x) ys\n [l,g] = map length [ls,gs]\n lx = length.filter(x==)$ls\n"}, {"source_code": "s[[_,m],xs]= c where\n l = length$ filter(m) xs\n e = length xs - l - g\n c = max 0 $ max (g-l-e) (l-g-e+1)\nmain=interact$show.s.map(map read.words).lines"}, {"source_code": "solve :: Int -> [Int] -> (Int, Int, Int) -> Int\nsolve x [] (l,e,g) = (final (l,e,g))\nsolve x (a:aa) (l,e,g) = \n if (a == x) \n then solve x aa (l,e+1,g) \n else if (a < x) \n then solve x aa (l+1,e,g)\n else solve x aa (l,e,g+1)\n\nfinal :: (Int, Int, Int) -> Int \nfinal (l,e,g) = \n if (l == g) \n then if (e > 0)\n then 0\n else 1\n else finall (l,e,g)\n\nfinall :: (Int, Int, Int) -> Int \nfinall (l,0,g) = 1 + finall (l,1,g)\nfinall (l,e,g) =\n if (l < g)\n then if (l + e >= g) \n then 0 \n else (g - l - e)\n else if (l < e + g)\n then 0\n else (l - g - e + 1)\n\n \nmain = \n do m <- getLine\n let [n,x] = map read (words m)\n str <- getLine\n let a = map read (words str)\n print (solve x a (0,0,0))"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\n-- solution for: http://codeforces.com/problemset/problem/166/c\n\nsolve :: Int -> [Int] -> (Int, Int, Int) -> Int\nsolve x [] (l,e,g) = (final (l,e,g))\nsolve x (a:aa) (l,e,g) = \n\tif (a == x) \n\t\tthen solve x aa (l,e+1,g) \n\t\telse if (a < x) \n\t\t\tthen solve x aa (l+1,e,g)\n\t\t\telse solve x aa (l,e,g+1)\n\nfinal :: (Int, Int, Int) -> Int\t\t\t\nfinal (l,e,g) = \n\tif (l == g) \n\tthen if (e > 0)\n\t\tthen 0\n\t\telse 1\n\telse finall (l,e,g)\n\nfinall :: (Int, Int, Int) -> Int\t\nfinall (l,0,g) = 1 + finall (l,1,g)\nfinall (l,e,g) =\n\tif (l < g)\n\tthen if (l + e >= g) \n\t\tthen 0 \n\t\telse (g - l - e)\n\telse if (l < e + g)\n\t\tthen 0\n\t\telse (l - g - e + 1)\n\n\t\t\t\nmain = \n do m <- getLine\n let [n,x] = map read (words m)\n str <- getLine\n let a = map read (words str)\n print (solve x a (0,0,0))\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sun 21 Oct 2012 05:20:15 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (elemIndex)\nimport Data.List (elemIndices)\n\n\nmedian ls = head $ drop el ls\n where el = ((length ls) + 1) `div` 2 - 1\n\ncountDist x med sls len = \n if x == med\n then 0\n else if x < med\n then medind - (head $ reverse $ elemIndices x sls)\n else res - medind\n where\n medind = (len + 1) `div` 2 - 1 -- index\n Just(res) = elemIndex x sls \n\ncalc x sls len = calcAdditions x medianS sls len\n where\n medianS = median sls\n calcAdditions x med sls len = \n if x == med\n then 0\n else if len `mod` 2 == 0\n then if x < med\n then 2 * dist\n else 2 * dist - 1\n else if x < med\n then 2 * dist - 1\n else 2 * dist\n where\n dist = countDist x med sls len\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calc x sls (fromIntegral n)\n else\n print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Char as C\n\natoi :: B.ByteString -> Int\natoi = B.foldl' (\\a c -> a*10 + C.ord c - C.ord '0') 0\n\nsolve :: Int -> [Int] -> Int\nsolve x xs\n | xs !! m == x = 0\n | otherwise = 1 + (solve x $ insert x xs)\n where m = (length xs - 1) `div` 2\n\nmain = do\n [n, x] <- map atoi . B.words <$> B.getLine\n xs <- sort . map atoi . B.words <$> B.getLine\n putStrLn . show $ solve x xs\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map (map read . words) . lines)\n\nsolve :: [[Int]] -> Int\nsolve ([_, x] : arr : _) = addition + max 0 (e - b - nx) + max 0 (b + 1 - nx - e) where\n b = length start\n e = length rest\n nx = length xs\n\n (xs, rest) = break (/= x) arr'\n (start, arr') = break (== x) sortedArray\n\n sortedArray = sort correctArray\n\n (addition, correctArray) = if x `elem` arr then (0, arr) else (1, x : arr)\n"}], "negative_code": [{"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sun 21 Oct 2012 01:09:15 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n--{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (elemIndex)\nimport Data.List (elemIndices)\n\n\nmedian ls = head $ drop ((length ls) `div` 2) ls\n\n\n-- calcAdditions :: Int->Int->Int\ncalcAdditions x med dist len= \n if len `mod` 2 == 0\n then\n if x < med\n then\n 2 * dist\n else\n 2 * dist - 1\n else\n if x < med\n then\n 2 * dist - 1\n else\n 2 * dist\n\ncountDist x med sls len = \n if x == med\n then\n 0\n else\n if x < med\n then\n medind - (head $ reverse $ elemIndices x sls)\n else\n res - medind\n where\n medind = (len + 1) `div` 2 - 1 -- index\n res = \n let\n ans = elemIndex x sls\n in\n case ans of\n Just(y) -> y\n Nothing -> 0\n\n\ncalc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calc x sls (fromIntegral n)\n else\n print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))\n\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sun 21 Oct 2012 04:32:20 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n--{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (elemIndex)\nimport Data.List (elemIndices)\n\n\nmedian ls = head $ drop ((((length ls) + 1) `div` 2) - 1) ls\n\ncountDist x med sls len = \n if x == med\n then 0\n else if x < med\n then\n medind - (head $ reverse $ elemIndices x sls)\n else\n res - medind\n where\n medind = (len + 1) `div` 2 - 1 -- index\n res = \n let ans = elemIndex x sls\n in case ans of\n Just(y) -> y\n Nothing -> 0\n\n\ncalc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len\n where\n calcAdditions x med dist len= \n if len `mod` 2 == 0\n then if x < med\n then 2 * dist\n else 2 * dist - 1\n else if x < med\n then 2 * dist - 1\n else 2 * dist\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calc x sls (fromIntegral n)\n else\n print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sun 21 Oct 2012 04:36:40 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n--{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (elemIndex)\nimport Data.List (elemIndices)\n\n\nmedian ls = head $ drop ((((length ls) + 1) `div` 2) - 1) ls\n\ncountDist x med sls len = \n if x == med\n then 0\n else if x < med\n then\n medind - (head $ reverse $ elemIndices x sls)\n else\n res - medind\n where\n medind = (len + 1) `div` 2 - 1 -- index\n res = \n let ans = elemIndex x sls\n in case ans of\n Just(y) -> y\n Nothing -> 0\n\n\ncalc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len\n where\n calcAdditions x med dist len= \n if len `mod` 2 == 0\n then if x < med\n then 2 * dist\n else 2 * dist - 1\n else if x < med\n then 2 * dist - 1\n else 2 * dist\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calc x sls (fromIntegral n)\n else\n print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sat 20 Oct 2012 07:44:58 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (findIndex)\nimport Data.List (findIndices)\n\n\nmedian ls = head $ drop ((length ls) `div` 2) $ ls\n\n\ncalcAdditions :: Int->Int->Int\ncalcAdditions dist len = \n if len `mod` 2 == 0\n then\n (2 * dist) \n else\n 2*dist\n\ncountDist x med sls = \n if x == med\n then\n 0\n else\n if x < med\n then\n ((length sls) `div` 2) - (head $ reverse $ findIndices (==x) sls)\n else\n res - (length sls) `div` 2\n where\n res = \n let\n ans = findIndex (==x) sls\n in\n case ans of\n Just(x) -> x\n Nothing -> 0\n\n\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calcAdditions (countDist x (median sls) sls) (length sls)\n else\n print $ 1 + (calcAdditions (countDist x (median (insert x sls)) (insert x sls)) (length sls))\n\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sat 20 Oct 2012 07:46:55 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (findIndex)\nimport Data.List (findIndices)\n\n\nmedian ls = head $ drop ((length ls) `div` 2) $ ls\n\n\ncalcAdditions :: Int->Int->Int\ncalcAdditions dist len = \n if len `mod` 2 == 0\n then\n (2 * dist) - 1\n else\n 2*dist\n\ncountDist x med sls = \n if x == med\n then\n 0\n else\n if x < med\n then\n ((length sls) `div` 2) - (head $ reverse $ findIndices (==x) sls)\n else\n res - (length sls) `div` 2\n where\n res = \n let\n ans = findIndex (==x) sls\n in\n case ans of\n Just(x) -> x\n Nothing -> 0\n\n\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calcAdditions (countDist x (median sls) sls) (length sls)\n else\n print $ 1 + (calcAdditions (countDist x (median (insert x sls)) (insert x sls)) (length (insert x sls)))\n\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n-- File Name : 0001A.hs\n-- Creation Date : 17-10-2012\n-- Last Modified : Sat 20 Oct 2012 07:43:34 PM EEST\n-- Created By : Greg Liras \n--_._._._._._._._._._._._._._._._._._._._._.\n\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Data.List (sort)\nimport Data.List (insert)\nimport Data.List (findIndex)\nimport Data.List (findIndices)\n\n\nmedian ls = head $ drop ((length ls) `div` 2) $ ls\n\n\ncalcAdditions :: Int->Int->Int\ncalcAdditions dist len = \n if len `mod` 2 == 0\n then\n (2 * dist) - 1\n else\n 2*dist\n\ncountDist x med sls = \n if x == med\n then\n 0\n else\n if x < med\n then\n ((length sls) `div` 2) - (head $ reverse $ findIndices (==x) sls)\n else\n res - (length sls) `div` 2\n where\n res = \n let\n ans = findIndex (==x) sls\n in\n case ans of\n Just(x) -> x\n Nothing -> 0\n\n\n\nmain :: IO ()\nmain = \n do\n all <- BS.getContents\n let Just (n, r1) = readInteger all\n let Just (x, r2) = readInteger r1\n let (ls, _) = readMany readInteger r2\n let sls = sort ls\n if x `elem` sls\n then\n print $ calcAdditions (countDist x (median sls) sls) (length sls)\n else\n print $ 1 + (calcAdditions (countDist x (median (insert x sls)) (insert x sls)) (length sls))\n\n where \n readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let \n (xs, t) = readMany readf r\n in \n (x : xs, t)\n Nothing -> ([], s)\n"}, {"source_code": "import Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport Debug.Trace\n\ncountLess :: Integral a => [a] -> a -> a -> a -> (a,a)\ncountLess [] median count plithos = (count, plithos)\ncountLess (x:xs) median count plithos\n\t| x medPos) = 2*(countLess+1) - (length + 1)\n\t| (countLess+1 < medPos) = (length+1) + 1 - 2*(countLess+1)\n\twhere medPos = (length + 2) `div` 2\ncalcMinNum length countLess plithos \n\t| (countLess+1 <= medPos) && (countLess + plithos >= medPos) = 0\n\t| (countLess+1 > medPos) = 2*(countLess+1) - 1 - length\n\t| (countLess + plithos < medPos) = length - 2*(countLess + plithos)\n\twhere medPos = (length + 1) `div` 2\n\nsolve length median x = \n\tlet \n\t\t(countLessRes, plithos) = countLess x median 0 0\n\tin \n\t\tcalcMinNum length countLessRes plithos\n\n\nmain = \n do all <- BS.getContents\n let Just (length, r1) = readInteger all\n let Just (median, r2) = readInteger r1\n let (x, _) = readMany readInteger r2\n print (length)\n print (median)\n print (x)\n print (solve length median x)\n -- print ((count_less x median 0 0) == length `div` 2)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n \n"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (n:x:ys) = case map succ.elemIndices x $ ys' of\n [] -> (\\l->2*l-n+1).length.takeWhile ( 0\n | m < z -> z - m\n | otherwise -> m - last (z:zs)\n where m = (n+1)`div`2\n ys' = sort ys\n"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (_:x:ys)\n | notElem x ls = succ.abs $ (l-g)\n | l < g = g-l\n | l > g + 1 = l-1-g\n | otherwise = 0\n where (ls,gs) = partition (<=x) ys\n [l,g] = map length [ls,gs]"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (_:x:ys)\n | notElem x ls = succ.abs $ (l-g)\n | l < g = g-l\n | otherwise = max 0 (l-lx-g-lx+1)\n where (ls,gs) = partition (<=x) ys\n [l,g] = map length [ls,gs]\n lx = length.filter(x==)$ls"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (_:x:ys)\n | notElem x ls = succ.abs $ (l-g)\n | l < g = g-l\n | otherwise = max 0 (l-g-lx)\n where (ls,gs) = partition (<=x) ys\n [l,g] = map length [ls,gs]\n lx = length.filter(x==)$ls"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (_:x:ys)\n | notElem x ls = if l <= g then g-l else l-g+1\n | l < g = g-l\n | otherwise = max 0 (l-lx-g-lx+1)\n where (ls,gs) = partition (<=x) ys\n [l,g] = map length [ls,gs]\n lx = length.filter(x==)$ls\n"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve (n:x:ys) = case map succ.elemIndices x $ ys' of\n [] -> (\\l->abs(2*l-n)+1).length.takeWhile ( 0\n | m < z -> z - m\n | otherwise -> m - last (z:zs)\n where m = (n+1)`div`2\n ys' = sort ys\n"}, {"source_code": "\n\nsolve :: Int -> [Int] -> (Int, Int, Int) -> Int\nsolve x [] (l,e,g) = (final (l,e,g))\nsolve x (a:aa) (l,e,g) = \n if (a == x) \n then solve x aa (l,e+1,g) \n else if (a < x) \n then solve x aa (l+1,e,g)\n else solve x aa (l,e,g+1)\n\nfinal :: (Int, Int, Int) -> Int \nfinal (l,e,g) = if (l == g) then 0 else finall (l,e,g)\n\nfinall :: (Int, Int, Int) -> Int \nfinall (l,0,g) = 1 + finall (l,1,g)\nfinall (l,e,g) =\n if (l < g)\n then if (l + e >= g) \n then 0 \n else (g - l - e)\n else if (l < e + g)\n then 0\n else (l - g - e + 1)\n\n \nmain = \n do m <- getLine\n let [n,x] = map read (words m)\n str <- getLine\n let a = map read (words str)\n print (solve x a (0,0,0))"}], "src_uid": "1a73bda2b9c2038d6ddf39918b90da61"} {"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Array (Array, (!), array, bounds)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: Int -> [(Int, Int)] -> [(Int, Int)]\nsolve n as = [(a, i) | i <- [1..n], i /= a]\n where\n a = head $ filter (not . elem') [1..n]\n elem' x = elem x (map fst as) || elem x (map snd as)\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n as <- replicateM m readPair\n print (n-1)\n mapM_ printPair $ solve n as\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [x, y] <- reads\n return (x, y)\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n printPair :: Show a => (a, a) -> IO ()\n printPair (a, b) = prints [a,b]", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\nimport qualified Data.IntSet as IS\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ntoPairs (x:y:xys) = (x,y) : toPairs xys\ntoPairs _ = []\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n edges <- map readInt.B.words <$> B.getContents\n let res = solve n edges\n print $ length res\n putStr.unlines.map(unwords.map show) $ res\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve 1 _ = []\nsolve n [] = map (:[n]) [1..n-1]\nsolve n edges = go (IS.fromList [1..n]) edges\n where\n v = f [1..] . map head.group$ sort edges\n iset = IS.fromList [1..n]\n go !rest (from:to:es) = filter (not.null) $ filter(const$IS.member from rest)[v,from]:filter(const$IS.member to rest)[v,to]:go rest' es\n where\n rest' = IS.delete to.IS.delete from $ IS.delete v rest\n go rest _ = map (:[v]) $ IS.toList rest\n\nf (i:is) (v:vs)\n | i==v = f is vs\n | otherwise = i\nf (i:is) [] = i"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\nimport qualified Data.IntSet as IS\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\ntoPairs (x:y:xys) = (x,y) : toPairs xys\ntoPairs _ = []\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n edges <- map readInt.B.words <$> B.getContents\n let res = solve n edges\n print $ length res\n putStr.unlines.map(unwords.map show) $ res\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve 1 _ = []\nsolve n [] = map (:[n]) [1..n-1]\nsolve n edges = go (IS.fromList [1..n]) edges\n where\n v = f [1..] $ sort edges\n iset = IS.fromList [1..n]\n go !rest (from:to:es) = [v,from]:[v,to]:go rest' es\n where\n rest' = IS.delete to.IS.delete from $ IS.delete v rest\n go rest _ = map (:[v]) $ IS.toList rest\n\nf (i:is) (v:vs)\n | i==v = f is vs\n | otherwise = i\nf (i:is) [] = i"}], "src_uid": "d93a0574497b60bb77fb1c1dfe95090f"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n putStrLn $ solve n\n\nsolve :: Int -> String\nsolve n\n |n `mod` 4 ==0 = \"YES\\n\"++ (unwords.map show) l\n |otherwise = \"NO\"\n where\n l = [2,4..n] ++ [1,3..(n-3)] ++ [(n*3 `div` 2)-1]\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain = readLn >>= flip replicateM_ test\n\ntest = do\n n <- readLn :: IO Integer\n if odd (n `div` 2)\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n let as = (2 *) <$> [1 .. n `div` 4]\n a = 100000000\n putStrLn . unwords . map show $ ((a +) <$> as) ++ ((a -) <$> as) ++ ((a + 1 +) <$> as) ++ ((a - 1 -) <$> as)"}, {"source_code": "interleave :: String -> [String] -> [String]\ninterleave _ [] = []\ninterleave c (x : xs) = x : c : (interleave c xs)\n\ngenerateSecond :: [Int] -> Int -> [Int]\ngenerateSecond [] _ = []\ngenerateSecond (x : xs) sign = (x + sign * 1) : (generateSecond xs (-sign))\n\nsolveFor :: Int -> String\nsolveFor n\n | n `div` 2 `mod` 2 == 1\n = \"NO\"\n | otherwise\n = \"YES\\n\" ++ concat (interleave \" \" (map show firstHalf)) ++ concat\n (interleave \" \" (map show $ generateSecond firstHalf 1))\n where firstHalf = map fst $ zip (iterate (10 +) 2) [1 .. (n `div` 2)]\n\nsolveCase :: IO ()\nsolveCase = do\n nLine <- getLine\n let n = read nLine :: Int\n let res = solveFor n\n putStrLn res\n\nmain :: IO ()\nmain = do\n tline <- getLine\n let ts = read tline :: Int\n sequence_ [ solveCase | _ <- [1 .. ts] ]\n"}, {"source_code": "import Data.List\n\nevens :: Int -> [Int]\nevens n = [s + 2, s + 4]\n where s = 6 * n\n\nodds :: Int -> [Int]\nodds n = [s + 1, s + 5]\n where s = 6 * n\n\nmakeList :: Int -> [Int]\nmakeList n = evenList ++ oddList\n where evenList = concat $ map evens [1..e]\n oddList = concat $ map odds [1..e]\n e = div n 4\n\nstringify :: [Int] -> String\nstringify x = unwords $ map show x\n\ntest :: String -> String\ntest s\n | rem n 4 /= 0 = \"NO\"\n | otherwise = \"YES\\n\" ++ (stringify $ makeList n)\n where n = read s :: Int\n\nmain = do\n getLine\n interact $ unlines . map test . lines\n"}, {"source_code": "import Control.Monad (replicateM_)\n\n\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO :: IO ()\nsolveIO = readLn >>= putStrLn . decorate . f where\n decorate Nothing = \"NO\"\n decorate (Just xs) = \"YES\\n\" ++ (unwords . map show) xs\n\n\nf :: Int -> Maybe [Int]\nf n = if n `mod` 4 /= 0 then Nothing else Just $\n let k = n `div` 2\n p1 = take k [2,4..]\n p2 = take (k-1) [1,3..]\n in p1 ++ p2 ++[sum p1 - sum p2]"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Text as T\n\nprocess a | mod a 4>0 = putStrLn \"NO\"\n\t | otherwise = do\n\t\t\t\tputStrLn \"YES\"\n\t\t\t\tlet x= take (div a 2) [2,4..]\n\t\t\t\tlet sx = sum x\n\t\t\t\tputStr $ intercalate \" \" $map show x \n\t\t\t\tputStr \" \"\n\t\t\t\tlet lx = length x\n\t\t\t\tlet y =take ((div a 2)- 1) [1,3..]\n\t\t\t\tlet sy =sum y\n\t\t\t\tputStr $ intercalate \" \" $ map show y \n\t\t\t\tputStrLn $ \" \"++ show (sx-sy)\nmain = do\n\t\tn<- getLine \n\t\ta<- map read <$> lines <$> getContents::IO [Int]\n\t\tmapM_ process a\n"}, {"source_code": "process :: Int -> [Int]\nprocess n\n | n `mod` 4 /= 0 = []\n | otherwise = take n2 [2,4..] ++ take (n2-1) [1,3..] ++ [n+n2-1]\n where n2 = n `div` 2\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n let as = process n\n if null as\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n putStrLn . unwords . map show $ as\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "import Data.List as L\n\nsolve :: Integer -> Maybe [Integer]\nsolve n\n | odd mid = Nothing\n | otherwise = Just (evens ++ someOdds ++ m)\n where mid = div n 2\n evens = (L.take (fromIntegral mid) [i | i <- [2..], even i])\n someOdds = (L.take (fromIntegral $ mid-2) [i | i <- [1..], odd i])\n sumEvens = L.sum evens\n sumOdds = L.sum someOdds\n m = magic (sumEvens - sumOdds) (if L.null someOdds then (-1) else (L.last someOdds))\n\nmagic :: Integer -> Integer -> [Integer]\nmagic n l = head [[a, b] | a <- [(l+2),(l+3)..n],\n b <- [n, (n-1)..(l+2)],\n odd a,\n odd b,\n a+b == n]\n\nparse :: String -> String\nparse input = case solve n of\n Just a -> \"YES\\n\" ++ (L.intercalate \" \" $ map show a)\n Nothing -> \"NO\"\n where n = read input :: Integer\n\nmain :: IO ()\nmain = interact (unlines . L.map parse . tail . lines)\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Text as T\n\nprocess a | mod a 2>0 = putStrLn \"NO\"\n\t | otherwise = do\n\t\t\t\tputStrLn \"YES\"\n\t\t\t\tlet x= take a [2,4..]\n\t\t\t\tlet sx = sum x\n\t\t\t\tputStr $ intercalate \" \" $map show x \n\t\t\t\tputStr \" \"\n\t\t\t\tlet lx = length x\n\t\t\t\tlet y =take (a- 1) [1,3..]\n\t\t\t\tlet sy =sum y\n\t\t\t\tputStr $ intercalate \" \" $ map show y \n\t\t\t\tputStrLn $ \" \"++ show (sx-sy)\nmain = do\n\t\tn<- getLine \n\t\ta<- map read <$> lines <$> getContents::IO [Int]\n\t\tmapM_ process a\n"}, {"source_code": "import Control.Monad\n\nmain = readLn >>= flip replicateM_ test\n\ntest = do\n n <- readLn :: IO Integer\n if odd (n `div` 2)\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n let as = (2 *) <$> [1 .. n `div` 4]\n a = 100000000\n putStrLn . unwords . map show $ ((a +) <$> as) ++ ((a -) <$> as) ++ ((a + 1 +) <$> as) ++ ((a - 1 +) <$> as)"}, {"source_code": "interleave :: String -> [String] -> [String]\ninterleave _ [] = []\ninterleave c (x : xs) = x : c : (interleave c xs)\n\ngenerateSecond :: [Int] -> Int -> [Int]\ngenerateSecond [] _ = []\ngenerateSecond (x : xs) sign = (x + sign * 1) : (generateSecond xs (-sign))\n\nsolveFor :: Int -> String\nsolveFor n\n | n `div` 2 `mod` 2 == 1\n = \"NO\"\n | otherwise\n = \"YES\\n\" ++ concat (interleave \" \" (map show firstHalf)) ++ concat\n (interleave \" \" (map show $ generateSecond firstHalf 1))\n where firstHalf = map fst $ zip (iterate (10 +) 2) [1 .. n]\n\nsolveCase :: IO ()\nsolveCase = do\n nLine <- getLine\n let n = read nLine :: Int\n let res = solveFor n\n putStrLn res\n\nmain :: IO ()\nmain = do\n tline <- getLine\n let ts = read tline :: Int\n sequence_ [ solveCase | _ <- [1 .. ts] ]\n"}, {"source_code": "import Data.List\n\nquad :: Int -> [Int]\nquad n = [s + 2, s + 4, s + 1, s + 5]\n where s = 6 * n\n\nmakeList :: Int -> [Int]\nmakeList n = foldl1 (++) (map quad [1..(div n 4)])\n\nstringify :: [Int] -> String\nstringify x = unwords $ map show x\n\ntest :: String -> String\ntest s\n | rem n 4 /= 0 = \"NO\"\n | otherwise = \"YES\\n\" ++ (stringify $ makeList n)\n where n = read s :: Int\n\nmain = do\n getLine\n interact $ unlines . map test . lines\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Text as T\n\nprocess a | mod a 4>0 = putStrLn \"NO\"\n\t | otherwise = do\n\t\t\t\tputStrLn \"YES\"\n\t\t\t\tlet x= take a [2,4..]\n\t\t\t\tlet sx = sum x\n\t\t\t\tputStr $ intercalate \" \" $map show x \n\t\t\t\tputStr \" \"\n\t\t\t\tlet lx = length x\n\t\t\t\tlet y =take (a- 1) [1,3..]\n\t\t\t\tlet sy =sum y\n\t\t\t\tputStr $ intercalate \" \" $ map show y \n\t\t\t\tputStrLn $ \" \"++ show (sx-sy)\nmain = do\n\t\tn<- getLine \n\t\ta<- map read <$> lines <$> getContents::IO [Int]\n\t\tmapM_ process a\n"}], "src_uid": "0c7e019e1e955cadacca55b4e823a3e5"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\n-- For Input\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n--import qualified Data.ByteString.Lex.Double as BSD\nimport Data.Char (isSpace)\nimport Data.IORef\nimport Text.Printf\n\n--import Test.QuickCheck\n--import Test.QuickCheck.Property\n--import Data.List.Ordered (isSorted)\n\n-- Data Structure Imports\nimport Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\n-- These should be imported by default... :)\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nimport Debug.Trace\n \n--------------------------------------------------------------------------------\n------------------------------- SOLUTION ---------------------------------------\n--------------------------------------------------------------------------------\n\nprimesUpTo :: Int -> Set Int \nprimesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]\n\nsieve :: Int -> UArray Int Bool\nsieve n = runSTUArray $ do\n sieve <- newArray (2, n) True\n forM_ [2..n] $ \\p -> do\n isPrime <- readArray sieve p\n when isPrime $ do\n forM_ [p*2, p*3 .. n] $ \\k -> do\n writeArray sieve k False\n return sieve\n\nlim :: Int \nlim = 100000\n\nprimes :: Set Int \nprimes = primesUpTo lim\n\nisPrime :: Int -> Bool\nisPrime n = Set.member n primes\n\ngoldbach :: Int -> (Int, Int)\ngoldbach n =\n head $ concatMap (\\x -> if Set.member (n-x) primes then [(x,n-x)] else []) \n $ Set.toList primes\n\n--goldbachs :: UArray Int (Int,Int)\n--goldbachs = listArray (4,lim) $ map goldbach [4..lim]\n\noperations :: Int -> Int -> [(Int,Int)]\noperations i j \n | diff == 0 = []\n | diff <= 2 = [(i,j)]\n | diff + 1 <= 9 = doGoldbach diff\n | even diff = doGoldbach diff\n | otherwise = (j-1,j):operations i (j-1)\n where diff = j - i\n doGoldbach n = \n let (x,y) = goldbach (n+2)\n in [(i+x-1,j), (i, i+x-1)]\n -- i+x-1-i+1=x\n -- x+y-1-x+1=y\nopsCorrect :: Int -> Int -> Bool\nopsCorrect i j \n | i < 0 || j < 0 = opsCorrect (abs i) (abs j)\n | i > j = opsCorrect j i\n | otherwise = \n let ops = operations i j \n walk [] = True\n walk ((x,y):t) = \n isPrime (y-x+1) && walk t\n in walk ops\n\nwalkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) -> \n IO (Set (Int,Int))\nwalkOps a [] heap = return heap\nwalkOps a ((i,j):t) heap = do\n-- elems <- getElems a\n-- putStrLn $ show (\"Calling walkOps with\", elems, i, j, heap, t)\n vi <- readArray a i\n vj <- readArray a j\n writeArray a i vj\n writeArray a j vi\n let heap' = Set.delete (vi,i) . Set.delete (vj,j) \n . Set.insert (vj,i) . Set.insert (vi,j) $ heap \n-- putStrLn $ show (\"New heap will be\", heap')\n heap' `seq` walkOps a t heap'\n\nprintOps :: [(Int,Int)] -> IO ()\nprintOps ops = forM_ ops $ \\(i,j) -> putStrLn $ show i ++ \" \" ++ show j\n \nsolve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]\nsolve a heap i k | i > k = return []\n | otherwise = do\n-- elems <- getElems a\n-- putStrLn $ show (\"Calling solve with\", elems, i, heap)\n let (mv,mi) = Set.findMin heap \n ops = operations i mi\n heap' <- walkOps a ops heap\n let heap'' = Set.delete (i,mv) heap'\n fmap (ops++) $ solve a heap'' (i+1) k\n\nmain :: IO ()\nmain = do\n all <- BS.getContents\n input <- newIORef all\n let parse = next input \n k <- parse int \n a <- parse $ intMany k\n a' <- newListArray (1,k) a :: IO (IOUArray Int Int)\n let heap = Set.fromList $ zipWith (,) a [1..k]\n ops <- solve a' heap 1 k\n putStrLn $ show $ length ops\n printOps ops\n-- elems <- getElems a'\n-- putStrLn $ show elems\n\n{-\nmain :: IO ()\nmain = quickCheck $ forAllShrink (fmap abs arbitrary) shrink $ \\n ->\n forAll (permute [1..n]) $ \\a ->\n prop a\n\npermute :: [Int] -> Gen [Int] \npermute [] = return []\npermute l = elements l >>= (\\x -> fmap (x:) (permute $ delete x l))\n\nprop :: [Int] -> Property \nprop a = morallyDubiousIOProperty $ do \n let k = length a \n a' <- newListArray (1,k) a :: IO (IOUArray Int Int)\n let heap = Set.fromList $ zipWith (,) a [1..k]\n ops <- solve a' heap 1 k\n elems <- getElems a'\n return $ isSorted elems\n-}\n--------------------------------------------------------------------------------\n-------------------------- IO Function Helpers ---------------------------------\n--------------------------------------------------------------------------------\n\ntype Parser a = BSC.ByteString -> (a, BSC.ByteString)\n\nint :: Parser Int\nint = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt\n\nint2 :: Parser (Int, Int)\nint2 = uncurry (first . (,)) . second int . int\n\nint3 :: Parser (Int, Int, Int)\nint3 = uncurry (first . (uncurry (,,))) . second int . int2\n\n--double :: Parser Double\n--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble\n\nchar :: Parser Char\nchar = BSC.head &&& BSC.tail\n\nletter :: Parser Char\nletter = second (BSC.dropWhile isSpace) . char \n\nstring :: Parser String\nstring = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)\n\nreadMany :: Parser a -> Int -> Parser [a]\nreadMany f n bs = first reverse $ \n foldr (\\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]\n\nintMany :: Int -> Parser [Int]\nintMany = readMany int\n\nnext :: IORef BSC.ByteString -> Parser a -> IO a\nnext input parse = do\n bs <- readIORef input\n let (x, bs') = parse bs\n writeIORef input bs'\n return x\n\n{- CODE JAM input\n\n cases <- parse int\n forM_ [1..cases] $ \\caseNum -> do\n -- Read Data \n -- let solution = \n -- solution <- \n printf \"Case #%d: %d\\n\" caseNum solution\n-}\n\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Text.Printf\n\nimport Data.Array.IO\nimport qualified Data.Array.MArray as M\nimport qualified Data.Array.IArray as I\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Data.Int\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nisqrt :: Integral a => a -> Int\nisqrt n = floor $ sqrt ((fromIntegral n) :: Double)\n\nsieve arr = do\n (_,hi) <- getBounds arr\n let maxi = isqrt hi\n forM_ [2..maxi] $ \\i -> do\n v <- readArray arr i\n if v == 0\n then let v = i*i in forM_ [v,v+i..hi] $ \\j -> writeArray arr j (fromIntegral i)\n else return ()\n\ngenPrimes :: Integral a => Int -> IO [a]\ngenPrimes n = do\n parr' <- newArray (2,n) 0 :: IO (IOUArray Int Int)\n sieve parr'\n parr <- M.freeze parr' :: IO (UArray Int Int)\n let primes = map (fromIntegral.fst) $ filter (\\(i,v) -> v == 0) $ I.assocs parr\n return primes\n\nind :: Integral a => a -> a -> (Int,a)\nind p n = go 0 n\n where go !k m = case m `divMod` p of\n (q,0) -> go (k+1) q\n otherwise -> (k,m)\n\nfactor :: Integral a => [a] -> a -> [(a,Int)]\nfactor [] n\n | n == 1 = []\n | otherwise = [(n,1)] -- assume n is prime\nfactor (p:ps) n = case ind p n of\n (0,_) -> factor ps n\n (k,m) -> (p,k) : factor ps m\n\nprod :: Integral a => [(a,Int)] -> a\nprod = product . map (\\(p,k) -> p^k)\n\nsolve :: UArray Int Int -> Int -> [Int] -> IO (Int,[(Int,Int)])\nsolve largestP n ns = do\n nums <- newArray (1,n) 0 :: IO (IOUArray Int Int)\n inv <- newArray (1,n) 0 :: IO (IOUArray Int Int)\n swapi <- newArray (0,5*n) 0 :: IO (IOUArray Int Int)\n swapj <- newArray (0,5*n) 0 :: IO (IOUArray Int Int)\n forM_ (zip [1..] ns) $ \\(i,a) -> do writeArray nums i a; writeArray inv a i\n let loop s i = -- nums[j] = i\n do j <- readArray inv i\n let d = j - i + 1\n if d < 2\n then return s\n else do let p = largestP ! d\n -- swap nums[j-p+1] and nums[j]\n writeArray swapi s (j-p+1)\n writeArray swapj s j \n a <- readArray nums (j-p+1)\n let b = i\n writeArray nums (j-p+1) b\n writeArray nums j a\n -- before: nums[j-p+1] = a --> inv[a] = j-p+1\n -- nums[j] = b --> inv[b] = j\n -- swap inv[a] and inv[b]\n writeArray inv b (j-p+1)\n writeArray inv a j\n loop (s+1) i\n s <- foldM loop 0 [1..n]\n swapi' <- M.freeze swapi :: IO (UArray Int Int)\n swapj' <- M.freeze swapj :: IO (UArray Int Int)\n let swaps = [ (swapi' ! k, swapj' ! k) | k <- [0..s-1] ]\n return $ (s, swaps)\n\ncheck :: UArray Int Int -> Int -> [Int] -> IO Bool\ncheck largestP n ns = do\n (s,swaps) <- solve largestP n ns\n arr <- newArray (1,n) 0 :: IO (IOUArray Int Int)\n forM_ (zip [1..] ns) $ \\(i,a) -> do writeArray arr i a\n -- execute the swaps\n forM_ swaps $ \\(i,j) -> do\n a <- readArray arr i\n b <- readArray arr j\n writeArray arr i b\n writeArray arr j a\n -- make sure arr[i] == i\n arr' <- M.freeze arr :: IO (UArray Int Int)\n let ok1 = all (\\i -> arr' ! i == i) [1..n]\n if not ok1\n then do putStrLn \"not sorted: \"\n forM_ [1..n] $ \\i -> putStr $ \" \" ++ show (arr' ! i)\n else return ()\n let ok2 = s <= 5*n\n if not ok2\n then putStrLn $ \"too many swaps: \" ++ show s\n else return ()\n return $ ok1 && ok2\n\nmakeLargestP :: Int -> IO (UArray Int Int)\nmakeLargestP n = do\n primes' <- newArray (2,n) 0 :: IO (IOUArray Int Int)\n sieve primes'\n primes <- M.freeze primes' :: IO (UArray Int Int)\n largestP' <- newArray (0,n) 0 :: IO (IOUArray Int Int)\n let go p i = do let p' = if primes ! i == 0 then i else p\n writeArray largestP' i p'\n return p'\n foldM_ go 2 [2..n]\n M.freeze largestP' :: IO (UArray Int Int)\n\nmainCheck = do\n n <- fmap read getLine\n largestP <- makeLargestP n\n ns <- fmap (parseInts n) BS.getLine\n check largestP n ns\n\nmainSolve = do\n n <- fmap read getLine\n largestP <- makeLargestP n\n ns <- fmap (parseInts n) BS.getLine\n (s,swaps) <- solve largestP n ns\n print s\n forM_ swaps $ \\(i,j) -> do\n putStrLn $ (show i) ++ \" \" ++ (show j)\n return ()\n \nmain = mainSolve\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\n-- For Input\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n--import qualified Data.ByteString.Lex.Double as BSD\nimport Data.Char (isSpace)\nimport Data.IORef\nimport Text.Printf\n\n-- Data Structure Imports\nimport Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\n-- These should be imported by default... :)\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nimport Debug.Trace\n \n--------------------------------------------------------------------------------\n------------------------------- SOLUTION ---------------------------------------\n--------------------------------------------------------------------------------\n\nprimesUpTo :: Int -> Set Int \nprimesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]\n\nsieve :: Int -> UArray Int Bool\nsieve n = runSTUArray $ do\n sieve <- newArray (2, n) True\n forM_ [2..n] $ \\p -> do\n isPrime <- readArray sieve p\n when isPrime $ do\n forM_ [p*2, p*3 .. n] $ \\k -> do\n writeArray sieve k False\n return sieve\n\nlim :: Int \nlim = 100000\n\nprimes :: Set Int \nprimes = primesUpTo lim\n\nisPrime :: Int -> Bool\nisPrime n = Set.member n primes\n\ngoldbach :: Int -> (Int, Int)\ngoldbach n = head $ concatMap (\\x -> if Set.member (n-x) primes then [(x,n-x)] \n else []) \n $ Set.toList primes\n\n--goldbachs :: UArray Int (Int,Int)\n--goldbachs = listArray (4,lim) $ map goldbach [4..lim]\n\noperations :: Int -> Int -> [(Int,Int)]\noperations i j \n | j == i = []\n | j == i + 1 = [(i,j)]\n | j == i + 2 = [(i,j)]\n | otherwise = \n let (x,y) = goldbach (j - i + 1) in\n [(i+x-1,j), (i, i+x-1)]\n\nwalkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) -> \n IO (Set (Int,Int))\nwalkOps a [] heap = return heap\nwalkOps a ((i,j):t) heap = do\n vi <- readArray a i\n vj <- readArray a j\n writeArray a i vj\n writeArray a j vi\n return $ Set.delete (i,vi) $ Set.delete (j,vj) \n $ Set.insert (i,vj) $ Set.insert (j,vi) $ heap \n\nprintOps :: [(Int,Int)] -> IO ()\nprintOps ops = forM_ ops $ \\(i,j) -> putStrLn $ show i ++ \" \" ++ show j\n \nsolve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]\nsolve a heap i k | i > k = return []\n | otherwise = do\n let (mv,mi) = Set.findMin heap \n ops = operations i mi\n heap' <- walkOps a ops heap\n let heap'' = Set.delete (i,mv) heap'\n fmap (ops++) $ solve a heap'' (i+1) k\n\nmain :: IO ()\nmain = do \n all <- BS.getContents\n input <- newIORef all\n let parse = next input \n k <- parse int \n a <- parse $ intMany k\n a' <- newListArray (1,k) a :: IO (IOUArray Int Int)\n let heap = Set.fromList $ zipWith (,) a [1..k]\n ops <- solve a' heap 1 k\n putStrLn $ show $ length ops\n printOps ops\n\n--------------------------------------------------------------------------------\n-------------------------- IO Function Helpers ---------------------------------\n--------------------------------------------------------------------------------\n\ntype Parser a = BSC.ByteString -> (a, BSC.ByteString)\n\nint :: Parser Int\nint = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt\n\nint2 :: Parser (Int, Int)\nint2 = uncurry (first . (,)) . second int . int\n\nint3 :: Parser (Int, Int, Int)\nint3 = uncurry (first . (uncurry (,,))) . second int . int2\n\n--double :: Parser Double\n--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble\n\nchar :: Parser Char\nchar = BSC.head &&& BSC.tail\n\nletter :: Parser Char\nletter = second (BSC.dropWhile isSpace) . char \n\nstring :: Parser String\nstring = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)\n\nreadMany :: Parser a -> Int -> Parser [a]\nreadMany f n bs = first reverse $ \n foldr (\\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]\n\nintMany :: Int -> Parser [Int]\nintMany = readMany int\n\nnext :: IORef BSC.ByteString -> Parser a -> IO a\nnext input parse = do\n bs <- readIORef input\n let (x, bs') = parse bs\n writeIORef input bs'\n return x\n\n{- CODE JAM input\n\n cases <- parse int\n forM_ [1..cases] $ \\caseNum -> do\n -- Read Data \n -- let solution = \n -- solution <- \n printf \"Case #%d: %d\\n\" caseNum solution\n-}\n\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\n-- For Input\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n--import qualified Data.ByteString.Lex.Double as BSD\nimport Data.Char (isSpace)\nimport Data.IORef\nimport Text.Printf\n\n--import Test.QuickCheck\n--import Test.QuickCheck.Property\n--import Data.List.Ordered (isSorted)\n\n-- Data Structure Imports\nimport Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\n-- These should be imported by default... :)\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nimport Debug.Trace\n \n--------------------------------------------------------------------------------\n------------------------------- SOLUTION ---------------------------------------\n--------------------------------------------------------------------------------\n\nprimesUpTo :: Int -> Set Int \nprimesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]\n\nsieve :: Int -> UArray Int Bool\nsieve n = runSTUArray $ do\n sieve <- newArray (2, n) True\n forM_ [2..n] $ \\p -> do\n isPrime <- readArray sieve p\n when isPrime $ do\n forM_ [p*2, p*3 .. n] $ \\k -> do\n writeArray sieve k False\n return sieve\n\nlim :: Int \nlim = 100000\n\nprimes :: Set Int \nprimes = primesUpTo lim\n\nisPrime :: Int -> Bool\nisPrime n = Set.member n primes\n\ngoldbach :: Int -> (Int, Int)\ngoldbach n =\n head $ concatMap (\\x -> if Set.member (n-x) primes then [(x,n-x)] else []) \n $ Set.toList primes\n\n--goldbachs :: UArray Int (Int,Int)\n--goldbachs = listArray (4,lim) $ map goldbach [4..lim]\n\noperations :: Int -> Int -> [(Int,Int)]\noperations i j \n | diff == 0 = []\n | diff <= 2 = [(i,j)]\n | diff + 1 <= 9 = doGoldbach (diff + 1)\n | even (diff + 1) = doGoldbach (diff + 1)\n | otherwise = (j-3,j):operations i (j-3)\n where diff = j - i\n doGoldbach n = let (x,y) = goldbach n\n in [(i+x-1,j), (i, i+x-1)]\n\nwalkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) -> \n IO (Set (Int,Int))\nwalkOps a [] heap = return heap\nwalkOps a ((i,j):t) heap = do\n-- elems <- getElems a\n-- putStrLn $ show (\"Calling walkOps with\", elems, i, j, heap, t)\n vi <- readArray a i\n vj <- readArray a j\n writeArray a i vj\n writeArray a j vi\n let heap' = Set.delete (vi,i) . Set.delete (vj,j) \n . Set.insert (vj,i) . Set.insert (vi,j) $ heap \n-- putStrLn $ show (\"New heap will be\", heap')\n heap' `seq` walkOps a t heap'\n\nprintOps :: [(Int,Int)] -> IO ()\nprintOps ops = forM_ ops $ \\(i,j) -> putStrLn $ show i ++ \" \" ++ show j\n \nsolve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]\nsolve a heap i k | i > k = return []\n | otherwise = do\n-- elems <- getElems a\n-- putStrLn $ show (\"Calling solve with\", elems, i, heap)\n let (mv,mi) = Set.findMin heap \n ops = operations i mi\n heap' <- walkOps a ops heap\n let heap'' = Set.delete (i,mv) heap'\n fmap (ops++) $ solve a heap'' (i+1) k\n\nmain :: IO ()\nmain = do\n all <- BS.getContents\n input <- newIORef all\n let parse = next input \n k <- parse int \n a <- parse $ intMany k\n a' <- newListArray (1,k) a :: IO (IOUArray Int Int)\n let heap = Set.fromList $ zipWith (,) a [1..k]\n ops <- solve a' heap 1 k\n putStrLn $ show $ length ops\n printOps ops\n-- elems <- getElems a'\n-- putStrLn $ show elems\n{-\npermute :: [Int] -> Gen [Int] \npermute [] = return []\npermute l = elements l >>= (\\x -> fmap (x:) (permute $ delete x l))\n\nprop :: [Int] -> Property \nprop a = morallyDubiousIOProperty $ do \n let k = length a \n a' <- newListArray (1,k) a :: IO (IOUArray Int Int)\n let heap = Set.fromList $ zipWith (,) a [1..k]\n ops <- solve a' heap 1 k\n elems <- getElems a'\n return $ isSorted elems\n-}\n--------------------------------------------------------------------------------\n-------------------------- IO Function Helpers ---------------------------------\n--------------------------------------------------------------------------------\n\ntype Parser a = BSC.ByteString -> (a, BSC.ByteString)\n\nint :: Parser Int\nint = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt\n\nint2 :: Parser (Int, Int)\nint2 = uncurry (first . (,)) . second int . int\n\nint3 :: Parser (Int, Int, Int)\nint3 = uncurry (first . (uncurry (,,))) . second int . int2\n\n--double :: Parser Double\n--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble\n\nchar :: Parser Char\nchar = BSC.head &&& BSC.tail\n\nletter :: Parser Char\nletter = second (BSC.dropWhile isSpace) . char \n\nstring :: Parser String\nstring = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)\n\nreadMany :: Parser a -> Int -> Parser [a]\nreadMany f n bs = first reverse $ \n foldr (\\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]\n\nintMany :: Int -> Parser [Int]\nintMany = readMany int\n\nnext :: IORef BSC.ByteString -> Parser a -> IO a\nnext input parse = do\n bs <- readIORef input\n let (x, bs') = parse bs\n writeIORef input bs'\n return x\n\n{- CODE JAM input\n\n cases <- parse int\n forM_ [1..cases] $ \\caseNum -> do\n -- Read Data \n -- let solution = \n -- solution <- \n printf \"Case #%d: %d\\n\" caseNum solution\n-}\n\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\n-- For Input\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n--import qualified Data.ByteString.Lex.Double as BSD\nimport Data.Char (isSpace)\nimport Data.IORef\nimport Text.Printf\n\n-- Data Structure Imports\nimport Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\n-- These should be imported by default... :)\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nimport Debug.Trace\n \n--------------------------------------------------------------------------------\n------------------------------- SOLUTION ---------------------------------------\n--------------------------------------------------------------------------------\n\nprimesUpTo :: Int -> Set Int \nprimesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]\n\nsieve :: Int -> UArray Int Bool\nsieve n = runSTUArray $ do\n sieve <- newArray (2, n) True\n forM_ [2..n] $ \\p -> do\n isPrime <- readArray sieve p\n when isPrime $ do\n forM_ [p*2, p*3 .. n] $ \\k -> do\n writeArray sieve k False\n return sieve\n\nlim :: Int \nlim = 100000\n\nprimes :: Set Int \nprimes = primesUpTo lim\n\nisPrime :: Int -> Bool\nisPrime n = Set.member n primes\n\ngoldbach :: Int -> (Int, Int)\ngoldbach n = head $ concatMap (\\x -> if Set.member (n-x) primes then [(x,n-x)] \n else []) \n $ Set.toList primes\n\n--goldbachs :: UArray Int (Int,Int)\n--goldbachs = listArray (4,lim) $ map goldbach [4..lim]\n\noperations :: Int -> Int -> [(Int,Int)]\noperations i j \n | j == i = []\n | j == i + 1 = [(i,j)]\n | j == i + 2 = [(i,j)]\n | otherwise = \n let (x,y) = goldbach (j - i + 1) in\n [(i+x-1,j), (i, i+x-1)]\n\nwalkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) -> \n IO (Set (Int,Int))\nwalkOps a [] heap = return heap\nwalkOps a ((i,j):t) heap = do\n-- elems <- getElems a\n-- putStrLn $ show (\"Calling walkOps with\", elems, i, j, heap, t)\n vi <- readArray a i\n vj <- readArray a j\n writeArray a i vj\n writeArray a j vi\n let heap' = Set.delete (vi,i) . Set.delete (vj,j) \n . Set.insert (vj,i) . Set.insert (vi,j) $ heap \n-- putStrLn $ show (\"New heap will be\", heap')\n heap' `seq` walkOps a t heap'\n\nprintOps :: [(Int,Int)] -> IO ()\nprintOps ops = forM_ ops $ \\(i,j) -> putStrLn $ show i ++ \" \" ++ show j\n \nsolve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]\nsolve a heap i k | i > k = return []\n | otherwise = do\n-- elems <- getElems a\n-- putStrLn $ show (\"Calling solve with\", elems, i, heap)\n let (mv,mi) = Set.findMin heap \n ops = operations i mi\n heap' <- walkOps a ops heap\n let heap'' = Set.delete (i,mv) heap'\n fmap (ops++) $ solve a heap'' (i+1) k\n\nmain :: IO ()\nmain = do \n all <- BS.getContents\n input <- newIORef all\n let parse = next input \n k <- parse int \n a <- parse $ intMany k\n a' <- newListArray (1,k) a :: IO (IOUArray Int Int)\n let heap = Set.fromList $ zipWith (,) a [1..k]\n ops <- solve a' heap 1 k\n putStrLn $ show $ length ops\n printOps ops\n-- elems <- getElems a'\n-- putStrLn $ show elems\n\n--------------------------------------------------------------------------------\n-------------------------- IO Function Helpers ---------------------------------\n--------------------------------------------------------------------------------\n\ntype Parser a = BSC.ByteString -> (a, BSC.ByteString)\n\nint :: Parser Int\nint = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt\n\nint2 :: Parser (Int, Int)\nint2 = uncurry (first . (,)) . second int . int\n\nint3 :: Parser (Int, Int, Int)\nint3 = uncurry (first . (uncurry (,,))) . second int . int2\n\n--double :: Parser Double\n--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble\n\nchar :: Parser Char\nchar = BSC.head &&& BSC.tail\n\nletter :: Parser Char\nletter = second (BSC.dropWhile isSpace) . char \n\nstring :: Parser String\nstring = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)\n\nreadMany :: Parser a -> Int -> Parser [a]\nreadMany f n bs = first reverse $ \n foldr (\\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]\n\nintMany :: Int -> Parser [Int]\nintMany = readMany int\n\nnext :: IORef BSC.ByteString -> Parser a -> IO a\nnext input parse = do\n bs <- readIORef input\n let (x, bs') = parse bs\n writeIORef input bs'\n return x\n\n{- CODE JAM input\n\n cases <- parse int\n forM_ [1..cases] $ \\caseNum -> do\n -- Read Data \n -- let solution = \n -- solution <- \n printf \"Case #%d: %d\\n\" caseNum solution\n-}\n\n"}], "src_uid": "c943a6413441651ec9f420ef44ea48d0"} {"source_code": "import Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromMaybe)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>>\r\n chunksOf 2 >>>\r\n map (last >>> words >>> map read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs\r\n | tot `mod` n /= 0 = -1\r\n | otherwise = length $ filter (> tot `div` n) xs\r\n where\r\n n = length xs\r\n tot = sum xs\r\n", "positive_code": [{"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n-- import Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n _n <- readLn :: IO Int\r\n readIListLn\r\n\r\nreadIListLn = map read <$> words <$> getLine :: IO [Int]\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve nums | (m /= 0) = \"-1\" | otherwise = show $ length . filter (>avg) $ nums\r\n where\r\n s = sum nums\r\n len = length nums\r\n m = s `mod` len\r\n avg = s `div` len\r\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let s = sum a\r\n r = if mod s n > 0 then -1 else length $ filter (> div s n) a\r\n print r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Set (fromList, size)\n \nsolve :: [Int] -> Int\nsolve arr = if r > 0 then -1 else length $ filter ffn arr\n where s = sum arr\n avg = div s $ length arr\n r = rem s $ length arr\n ffn x = x > avg\n \nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] $ \\_ -> do\n _ <- getLine\n getLine >>= pure . map read . words >>= putStrLn . show . solve \n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintS = do \r\n n<-readLn::IO Int \r\n a<-readInts \r\n let s = sum a \r\n if (mod s n /= 0) then putStrLn\"-1\"\r\n else do \r\n let b = div s n \r\n print $ sum[1|x<-a,x>b]\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t :: Int <- read <$> getLine\r\n replicateM_ t do\r\n n :: Int <- read <$> getLine\r\n xs :: [Int] <- map read . words <$> getLine\r\n print $ solve n xs\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve n xs\r\n | dividesFairly = length $ filter (> average) xs\r\n | otherwise = -1\r\n where\r\n total = sum xs\r\n dividesFairly = total `mod` n == 0\r\n average = total `div` n"}, {"source_code": "--1538/problem/B. Friends and Candies\r\n\r\ntoInt :: String -> Int\r\ntoInt x = read x ::Int\r\n\r\ngetInts = do\r\n x <- getLine\r\n let y = (map$toInt)$words x\r\n return y\r\n\r\ndistribute_co::[Int]->Int->Int\r\ndistribute_co (hd:lst) ave\r\n |lst==[] =\r\n if hd>ave then 1 else 0\r\n |hd>ave =\r\n 1+distribute_co lst ave\r\n |otherwise =\r\n distribute_co lst ave \r\ndistribute::Int->[Int]->Int\r\ndistribute n lst\r\n |mod (sum lst) n/=0 =\r\n -1\r\n |otherwise = do\r\n let ave=div (sum lst) (length lst)\r\n distribute_co lst ave\r\n\r\nloop i f\r\n |i==1 = do\r\n n' <- getLine\r\n let n = toInt n'\r\n lst <- getInts\r\n\r\n print$f n lst\r\n\r\n |otherwise = do\r\n n' <- getLine\r\n let n = toInt n'\r\n lst <- getInts\r\n\r\n print$f n lst\r\n\r\n loop (i-1) f\r\n\r\nmain = do\r\n t' <- getLine\r\n let t = toInt t'\r\n\r\n loop t distribute\r\n\r\n\r\n"}, {"source_code": "makeInteger :: [String] -> [Int]\r\nmakeInteger = map read\r\n\r\nmain :: IO()\r\nmain = do\r\n line <- getLine\r\n let t = (read line::Int)\r\n solve_multitest t\r\n\r\nsolve_multitest :: Int -> IO()\r\nsolve_multitest 0 = return ()\r\nsolve_multitest t = do\r\n solve_test\r\n solve_multitest (t - 1)\r\n\r\nsolve_test :: IO()\r\nsolve_test = do\r\n line <- getLine\r\n let n = (read line::Int)\r\n line <- getLine\r\n let inparr = words line\r\n let arr = makeInteger inparr\r\n let s = sum arr\r\n if (rem s n) /= 0 then\r\n putStrLn \"-1\"\r\n else\r\n putStrLn (show (count_larger_than_k arr (quot s n)))\r\n\r\ncount_larger_than_k :: [Int] -> Int -> Int\r\ncount_larger_than_k [] k = 0\r\ncount_larger_than_k a k = do\r\n if head a > k then\r\n 1 + count_larger_than_k (tail a) k\r\n else\r\n count_larger_than_k (tail a) k"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest' :: [Int] -> Int\ntest' a\n | v /= 0 = -1\n | otherwise = length $ filter (> u) a\n where\n n = length a\n !s = sum a\n (!u, !v) = divMod s n\n\nnl = char7 '\\n'\n\ntest :: Builder -> Int -> [Int] -> Builder\ntest buf 0 _ = buf\ntest buf nt (n:a) = test (buf <> intDec (test' b) <> nl) (pred nt) c\n where\n (b, c) = splitAt n a\n\nsolve :: [Int] -> Builder\nsolve (nt:xs) = test mempty nt xs\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> chunksOf 2\r\n >>> map (last >>> words >>> map read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs\r\n | r == 0 = length $ filter (> q) xs\r\n | otherwise = -1\r\n where\r\n (q, r) = divMod (sum xs) (length xs)\r\n"}, {"source_code": "module Main where\nimport Data.Functor ((<&>))\nimport Control.Monad (forM, replicateM, replicateM_)\nimport Data.Foldable (traverse_)\nimport GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)\nimport Data.List (group)\nimport Data.Ratio ((%))\nimport Prelude hiding (floor)\nimport Control.Monad (forM_)\n\nreadInts :: IO [Int]\nreadInts = getLine <&> words <&> fmap read\n\nreadString :: IO String\nreadString = getLine\n\ntoDoubles :: (Functor f, Integral a) => f a -> f Double\ntoDoubles xs = (\\x -> fromIntegral x :: Double) <$> xs\n\ntoDouble :: (Integral a) => a -> Double\ntoDouble = fromIntegral\n\n\nceil :: Double -> Int\nceil = ceilingDoubleInt\n\nfloor :: Double -> Int\nfloor = floorDoubleInt\n\nmain :: IO ()\nmain = do\n t:_ <- readInts\n replicateM_ t $ do\n n:_ <- readInts\n as <- readInts\n let\n s = sum as\n p = s `div` n\n ans\n | p * n == s = length . filter (> p) $ as\n | otherwise = -1\n print ans"}], "negative_code": [], "src_uid": "b8554e64b92b1b9458955da7d55eba62"} {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (_ : as) = f 0 0 as\n where\n f s _ [] = s\n f s b (a : as)\n | b < a = f (s + a - b) a (a : as)\n | otherwise = f (s + 1 - r) (b + 1) (replicate q (a + 1) ++ ys)\n where\n (xs, ys) = break (> a) (a : as)\n (q, r) = length xs `quotRem` 2\n", "positive_code": [{"source_code": "import Data.Map as M hiding (map)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (_ : as) = f 0 0 $ fromListWith (+) [(a, 1) | a <- as]\n where\n f s b as\n | M.null as = s\n | b < a = f (s + a - b) a as\n | otherwise = f (s + 1 - r) (b + 1) (if q > 0 then M.insertWith (+) (a + 1) q as' else as')\n where\n ((a, p), as') = M.deleteFindMin as\n (q, r) = p `quotRem` 2\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (_ : as) = f 0 0 $ map (\\x -> (head x, length x)) $ group as\n where\n f s _ [] = s\n f s b ((a, p) : as)\n | b < a = f (s + a - b) a ((a, p) : as)\n | not (null as) && (c == a + 1) = f (s + 1 - r) (b + 1) ([(a + 1, x + q) | x + q > 0] ++ tail as)\n | otherwise = f (s + 1 - r) (b + 1) ([(a + 1, q) | q > 0] ++ as)\n where\n (q, r) = p `quotRem` 2\n (c, x) = head as\n"}, {"source_code": "import Data.Map as M hiding (map)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (_ : as) = f 0 0 $ fromListWith (+) [(a, 1) | a <- as]\n where\n f s b as\n | M.null as = s\n | b < a = f (s + a - b) a as\n | otherwise = f (s + 1 - r) (b + 1) (if q > 0 then M.insertWith (+) (a + 1) q as' else as')\n where\n ((a, p), as') = M.deleteFindMin as\n (q, r) = p `quotRem` 2\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 0 $ go0 $ foldr insert Empty xs\n where\n go !res !x (y:ys)\n | x==y = go res (x+1) ys\n | otherwise = go (res+y-x) (y+1) ys\n go !res _ _ = res\n go0 Empty = []\n go0 (Fork x []) = [x]\n go0 heap\n | x == minElem heap' = go0 $ insert (x+1) $ deleteMin heap'\n | otherwise = x : go0 heap'\n where\n (x, heap') = deleteFindMin heap\n\ndata Heap a = Empty | Fork a [Heap a]\n\nisEmpty :: Ord a => Heap a -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ninsert :: Ord a => a -> Heap a -> Heap a\ninsert x h = merge (Fork x []) h\n\nminElem :: Heap a -> a\nminElem (Fork x _) = x\n\ndeleteMin :: Ord a => Heap a -> Heap a\ndeleteMin (Fork _ hs) = mergePairs hs\n\ndeleteFindMin :: Ord a => Heap a -> (a, Heap a)\ndeleteFindMin (Fork x hs) = (x, mergePairs hs)\n\nmerge :: Ord a => Heap a -> Heap a -> Heap a\nmerge Empty hy = hy\nmerge hx Empty = hx\nmerge hx@(Fork x _) hy@(Fork y _)\n | x <= y = join hx hy\n | otherwise = join hy hx\n where\n join (Fork x hs) h = Fork x (h:hs)\n\nmergePairs :: Ord a => [Heap a] -> Heap a\nmergePairs [] = Empty\nmergePairs [x] = x\nmergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 0 $ until isOK step $ step xs\n where\n step = mergeAll.map calc.group\n go !res !x (y:ys)\n | x==y = go res (x+1) ys\n | otherwise = go (res+y-x) (y+1) ys\n go !res _ _ = res\n isOK (x:y:xs)\n | x [Int]\ncalc [] = []\ncalc xs@(x:_) = go x $ length xs\n where\n go !x !l\n | l <= 1 = take l [x]\n | otherwise = let (q,r) = quotRem l 2\n in if r==0\n then go (x+1) q\n else x : go (x+1) q\n\nmergeAll :: [[Int]] -> [Int]\nmergeAll [x] = x\nmergeAll xs = mergeAll $ mergePairs xs\n\nmergePairs :: [[Int]] -> [[Int]]\nmergePairs (x:y:xs) = merge x y : mergePairs xs\nmergePairs xs = xs\n\nmerge :: [Int] -> [Int] -> [Int]\nmerge (x:xs) (y:ys)\n | x <= y = x : merge xs (y:ys)\n | otherwise = y : merge (x:xs) ys\nmerge xs ys = xs ++ ys"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 0 $ go0 $ foldr insert Empty xs\n where\n go !res !x (y:ys)\n | x==y = go res (x+1) ys\n | otherwise = go (res+y-x) (y+1) ys\n go !res _ _ = res\n go0 Empty = []\n go0 (Fork x []) = [x]\n go0 heap\n | x == minElem heap' = go0 $ deleteMin heap'\n | otherwise = x : go0 heap'\n where\n (x, heap') = deleteFindMin heap\n\ndata Heap a = Empty | Fork a [Heap a]\n\nisEmpty :: Ord a => Heap a -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ninsert :: Ord a => a -> Heap a -> Heap a\ninsert x h = merge (Fork x []) h\n\nminElem :: Heap a -> a\nminElem (Fork x _) = x\n\ndeleteMin :: Ord a => Heap a -> Heap a\ndeleteMin (Fork _ hs) = mergePairs hs\n\ndeleteFindMin :: Ord a => Heap a -> (a, Heap a)\ndeleteFindMin (Fork x hs) = (x, mergePairs hs)\n\nmerge :: Ord a => Heap a -> Heap a -> Heap a\nmerge Empty hy = hy\nmerge hx Empty = hx\nmerge hx@(Fork x _) hy@(Fork y _)\n | x <= y = join hx hy\n | otherwise = join hy hx\n where\n join (Fork x hs) h = Fork x (h:hs)\n\nmergePairs :: Ord a => [Heap a] -> Heap a\nmergePairs [] = Empty\nmergePairs [x] = x\nmergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = go 0 0 $ go0 $ step xs\n where\n step = mergeAll.map calc.group\n go0 xs\n | isOK xs = xs\n | otherwise = step xs\n go !res !x (y:ys)\n | x==y = go res (x+1) ys\n | otherwise = go (res+y-x) (y+1) ys\n go !res _ _ = res\n isOK (x:y:xs)\n | x [Int]\ncalc [] = []\ncalc xs@(x:_) = go x $ length xs\n where\n go !x !l\n | l <= 1 = take l [x]\n | otherwise = let (q,r) = quotRem l 2\n in if r==0\n then go (x+1) q\n else x : go (x+1) q\n\nmergeAll :: [[Int]] -> [Int]\nmergeAll [x] = x\nmergeAll xs = mergeAll $ mergePairs xs\n\nmergePairs :: [[Int]] -> [[Int]]\nmergePairs (x:y:xs) = merge x y : mergePairs xs\nmergePairs xs = xs\n\nmerge :: [Int] -> [Int] -> [Int]\nmerge (x:xs) (y:ys)\n | x <= y = x : merge xs (y:ys)\n | otherwise = y : merge (x:xs) ys\nmerge xs ys = xs ++ ys"}], "src_uid": "80b11670a99f59afc8d58073b9fa7f6d"} {"source_code": "{-# LANGUAGE TupleSections #-}\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as M\nimport Data.Maybe\n\nmain = do\n input <- fmap B.lines B.getContents\n let [n,k] = map readI $ B.words $ input!!0\n let ps = map readI $ B.words $ input!!1\n putStrLn $ unwords $ map show $ solve k ps\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: Int -> [Int] -> [Int]\nsolve k as =\n mapMaybe (`M.lookup`assigns) as\n where\n assigns :: M.IntMap Int\n assigns = foldl f M.empty as\n\n f :: M.IntMap Int -> Int -> M.IntMap Int\n f m x =\n let lx = max 0 (x-k+1) in\n case (M.member x m, mapMaybe (\\i-> fmap (i,) (M.lookup i m)) [x-1,x-2..lx]) of\n (True , _) -> m\n (False, ((si,sx):_))\n | x < sx+k -> foldr (`M.insert`sx) m [si+1..x]\n | otherwise -> foldr (`M.insert`(si+1)) m [si+1..x]\n (False, []) -> foldr (`M.insert`lx) m [lx..x]", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.Map as Map\n\nmain = do\n [n, k] <- fmap parseInput $ getLine\n ps <- fmap parseInput $ getLine\n putStrLn $ unwords $ map show $ solve n k ps \n\nparseInput = map readInt . words\n where readInt x = (read x) :: Int\n\nsolve n k ps = solve' ps $ Map.empty\n where\n solve' [] _ = []\n solve' (p:ps) mapping \n | isJust stored = (fromJust stored):(solve' ps mapping)\n | otherwise = p':(solve' ps mapping')\n where\n stored = Map.lookup p mapping\n left_lookup = Map.filterWithKey (\\x _ -> x `elem` [p-k+1..p]) mapping\n (lx, ly) = Map.findMax left_lookup\n (left_bound, merge_bound)\n | Map.size left_lookup == 0 = (max (p-k+1) 0, -100000000)\n | otherwise = (lx + 1, ly)\n\n p' = if (p - merge_bound) < k \n then merge_bound\n else left_bound\n\n mapping' = foldl' insert' mapping [left_bound..p]\n insert' m x = Map.insert x p' m\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as M\nimport Data.Maybe\n\nmain = do\n input <- fmap B.lines B.getContents\n let [n,k] = map readI $ B.words $ input!!0\n let ps = map readI $ B.words $ input!!1\n putStrLn $ unwords $ map show $ solve k ps\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: Int -> [Int] -> [Int]\nsolve k as =\n mapMaybe (`M.lookup`assigns) as\n where\n assigns :: M.IntMap Int\n assigns = foldl f M.empty as\n\n f :: M.IntMap Int -> Int -> M.IntMap Int\n f m x =\n case (M.member x m, filter (`M.notMember`m) [max 0 (x-k+1)..x]) of\n (True , _) -> m\n (False, (s:_)) -> foldr (`M.insert`s) m [s..s+k-1]"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = do\n input <- fmap B.lines B.getContents\n let [n,k] = map readI $ B.words $ input!!0\n let ps = map readI $ B.words $ input!!1\n putStrLn $ unwords $ solve k ps\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: Int -> [Int] -> [String]\nsolve k as =\n sort $ map (show.f) as\n where\n f x = let (q,r) = x`divMod`k in q*k"}], "src_uid": "deed251d324f7bbe53eefa94f92c3bbc"} {"source_code": "main = getContents >>= putStr . unlines . map (solve . words) . tail . lines\n where solve (x:_) = x ++ (' ' : (show $ 2 * (read x)))\n", "positive_code": [{"source_code": "solve (l, r) = (l, 2 * l)\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: [String] -> (Int, Int)\nreadPair [x, y] = (readInt x, readInt y)\n\nmain = do\n contents <- getContents\n let _:xs = lines contents\n let ans = map (solve . readPair . words) xs\n mapM_ (\\(x, y) -> (putStrLn ((show x) ++ \" \" ++ (show y)))) ans\n "}, {"source_code": "module Main where\nimport Control.Monad\n\nmain = do\n ts <- (readLn :: IO Int) >>= \\x -> replicateM x $ map (read :: String -> Integer) . words <$> getLine\n mapM_ (\\[a,b] -> putStrLn $ show a ++ \" \" ++ show (a*2) ) ts"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n [l,r] <- map read . words <$> getLine :: IO [Int]\n putStrLn $ shows l $ ' ' : show (2*l)\n"}, {"source_code": "import Control.Monad\nmain = do\n t <- readLn\n replicateM_ t $ do\n [l,r] <- map read . words <$> getLine\n putStrLn $ show l ++ \" \" ++ show (2*l)\n"}, {"source_code": "main = getContents >>= putStrLn . unlines . solve . map read . tail . words\n\nsolve [] = []\nsolve (l:_:ls) = ((show l) ++ \" \" ++ (show (2 * l))) : solve ls\n"}, {"source_code": "ipt :: Int -> IO ()\nipt t\n | t == 0 = return ()\n | otherwise = do\n z <- getLine\n let x = words z\n putStrLn (show (read (x !! 0) :: Integer) ++ \" \" ++ show ((read (x !! 0) :: Integer) * 2))\n ipt (t - 1)\n\nmain = do\n x <- getLine\n ipt (read x :: Int)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess = do\n\t\t[a,b]<-map read <$> words <$> getLine :: IO [Int]\n\t\tputStrLn $ intercalate \" \" $ map show $ head [[x,y]|x<-[a..b],y<-[x+x..b], mod y x ==0]\nmain = do\n\t\tn<- read <$> getLine:: IO Int\n\t\treplicateM_ n process\n"}, {"source_code": "process :: Int -> Int -> (Int, Int)\nprocess l r = (l, 2*l)\n\nreadInt :: String -> Int\nreadInt = read\n\nshowPair :: (Int, Int) -> String\nshowPair (x,y) = show x ++ \" \" ++ show y\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ (putStrLn.showPair) $ map (\\[l,r] -> process l r) ts"}], "negative_code": [{"source_code": "ipt :: Int -> IO ()\nipt t\n | t == 0 = return ()\n | otherwise = do\n z <- getLine\n let x = words z\n print (show (read (x !! 0) :: Integer) ++ \" \" ++ show ((read (x !! 0) :: Integer) * 2))\n ipt (t - 1)\n\nmain = do\n x <- getLine\n ipt (read x :: Int)"}, {"source_code": "ipt :: Int -> IO ()\nipt t\n | t == 0 = print \"\"\n | otherwise = do\n z <- getLine\n let x = words z\n print (show (read (x !! 0) :: Integer) ++ \" \" ++ show ((read (x !! 0) :: Integer) * 2))\n ipt (t - 1)\n\nmain = do\n x <- getLine\n ipt (read x :: Int)"}], "src_uid": "a9cd97046e27d799c894d8514e90a377"} {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n if n < k * 2 + 1\n then print (-1)\n else do\n print (n*k)\n forM_ [0..n-1] $ \\i -> do\n forM_ [1..k] $ \\j -> do\n putStrLn $ unwords $ map show [i+1, (i+j)`mod`n+1]\n\n return ()\n", "positive_code": [{"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Array\n\nreadInt :: IO Integer\nreadInt = read <$> getLine\nreadIntList :: IO [Integer]\nreadIntList = fmap read . words <$> getLine\nreadIntArray :: Integer -> IO (Array Integer Integer)\nreadIntArray n = listArray (0, n-1) <$> readIntList\nreadSortedIntArray :: Integer -> IO (Array Integer Integer)\nreadSortedIntArray n = listArray (0, n-1) . sort <$> readIntList\n\nmain :: IO ()\nmain = do\n [n, k] <- readIntList\n if 2 * k <= n-1\n then do\n putStrLn $ show $ n*k\n forM [1..n] $ \\i ->\n forM [1..k] $ \\j ->\n putStrLn $ show i ++ \" \" ++ show ((i + j - 1) `mod` n + 1)\n return ()\n else putStrLn $ show (-1)"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nmain :: IO ()\nmain = do\n\t[n, k] <- inputInts\n\tif (2*k > n-1) then print (-1) else do\n\t\tprint $ n*k\n\t\tprintMatrix [[(i+1),((i+j+1)`rem`n + 1)] | i <- [0..n-1], j <- [0..k-1]]\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n-- }}}\n\nmain :: IO ()\nmain = do\n\t[n, k] <- inputInts\n\tif (2*k > n-1) then print (-1) else do\n\t\tprint $ n*k\n\t\tsequence_ [printf \"%d %d\\n\" (i+1) ((i+j+1)`rem`n + 1) | i <- [0..n-1], j <- [0..k-1]]\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn . unwords $ map show xs\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr . unlines $ map (unwords . map show) xs\n-- }}}\n\nmain :: IO ()\nmain = do\n\t[n, k] <- inputInts\n\tif (2*k > n-1) then print (-1) else do\n\t\tprint $ n*k\n\t\tprintMatrix [[(i+1),((i+j+1)`rem`n + 1)] | i <- [0..n-1], j <- [0..k-1]]\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Function\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\n-- }}}\n-- silly utilities {{{\n(#) = flip ($)\ninfixl 0 #\n\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n\n(!>) :: Seq a -> Int -> a\n(!>) = Seq.index\n-- }}}\n-- input and output {{{\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = mapM_ (putStrLn . showMany) xs\n-- }}}\n\nmain :: IO ()\nmain = do\n\t[n, k] <- inputInts\n\tif (2*k > n-1) then print (-1) else do\n\t\tprint $ n*k\n\t\tprintMatrix [[(i+1),((i+j+1)`rem`n + 1)] | i <- [0..n-1], j <- [0..k-1]]\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n if n <= k\n then print (-1)\n else do\n print (n*k)\n forM_ [0..n-1] $ \\i -> do\n forM_ [1..k] $ \\j -> do\n putStrLn $ unwords $ map show [i+1, (i+j)`mod`n+1]\n\n return ()\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n if n == 1\n then print (-1)\n else do\n print (n*k)\n forM_ [0..n-1] $ \\i -> do\n forM_ [1..k] $ \\j -> do\n putStrLn $ unwords $ map show [i+1, (i+1)`mod`n+1]\n\n return ()\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n [n, k] <- map read . words <$> getLine\n if n == 1\n then print (-1)\n else do\n print (n*k)\n forM_ [0..n-1] $ \\i -> do\n forM_ [1..k] $ \\j -> do\n putStrLn $ unwords $ map show [i+1, (i+j)`mod`n+1]\n\n return ()\n"}], "src_uid": "14570079152bbf6c439bfceef9816f7e"} {"source_code": "import Data.List\nmain = interact $ show . process . map read . words\nprocess :: [Int] -> Int\nprocess (n:m:k:a) = n + sum ( drop (k-1) $ reverse $ sort $ map pred $ zipWith (-) (tail a) a)\n", "positive_code": [{"source_code": "import Text.Printf\nimport Control.Monad\nimport Data.List\n\nglwr = fmap (map read . words) getLine\n\nmain = do\n [n, l, r] <- glwr\n ls <- glwr\n putStrLn . show $ solve n l r ls\n\nsolve n l r ls = fst $ foldl sumSub (0, ls) splitIndices'\n where\n interval = zipWith (-) (tail ls) ls\n breakIndices = sort . map snd . take (r-1) . sortBy (flip compare)\n $ zip interval [1..]\n splitIndices = breakIndices ++ [n]\n splitIndices' = zipWith (-) splitIndices (0:splitIndices)\n\nsumSub (n, ls) x = (n', ls')\n where\n (sub, ls') = splitAt x ls\n n' = last sub - head sub + n + 1\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n [n,m,k] <- map read . words <$> getLine\n bs <- take n . unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let diffs = sort $ map (+(-1)) $ zipWith (-) (tail bs) bs\n print $ (n +) $! sum $ take (n-k) diffs\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n"}], "negative_code": [{"source_code": "import Text.Printf\nimport Control.Monad\nimport qualified Data.IntMap as IM\nimport Data.List\n\nglwr = fmap (map read . words) getLine\n\nmain = do\n [n, l, r] <- glwr\n ls@(_:xs) <- glwr\n let interval = zipWith (-) xs ls\n breakIndices = sort . map snd . take (r-1)\n $ IM.toDescList . IM.fromList $ zip interval [1..]\n newIndices = breakIndices ++ [n]\n takeAt = zipWith (-) newIndices (0:newIndices)\n minLen = addSub 0 ls takeAt\n putStrLn $ show minLen\n\naddSub n _ [] = n\naddSub n ls (s:ss)\n | s == 1 = addSub (n+1) ls' ss\n | otherwise = addSub n' ls' ss\n where\n (a, ls') = splitAt s ls\n n' = last a - head a + 1 + n\n"}, {"source_code": "import Text.Printf\nimport Control.Monad\nimport qualified Data.IntMap as IM\nimport Data.List\n\nglwr = fmap (map read . words) getLine\n\nmain = do\n [n, l, r] <- glwr\n ls <- glwr\n let interval = zipWith (-) (tail ls) ls\n breakIndices = sort . map snd . take (r-1)\n $ IM.toDescList . IM.fromList $ zip interval [1..]\n newIndices = breakIndices ++ [n]\n takeAt = zipWith (-) newIndices (0:newIndices)\n minLen = if n == 0 then 0 else addSub 0 ls takeAt\n putStrLn $ show minLen\n\naddSub n _ [] = n\naddSub n ls (s:ss)\n | s == 1 = addSub (n+1) ls' ss\n | otherwise = addSub n' ls' ss\n where\n (a, ls') = splitAt s ls\n n' = last a - head a + 1 + n\n"}], "src_uid": "6b2b56a423c247d42493d01e06e4b1d2"} {"source_code": "main=interact$unlines.g.tail.lines\ng[]=[]\ng(_:n:m:x)=s n m:g x\ns n=e.filter(uncurry(/=)).zip n\ne(x:y:[])=if x==y then\"Yes\"else\"No\"\ne x=\"No\"", "positive_code": [{"source_code": "main=interact$unlines.l.lines\nl=g.tail where g[]=[];g(_:n:m:x)=s n m:g x\ns n=e.filter(uncurry(/=)).zip n\ne(x:y:[])=if x==y then\"Yes\"else\"No\"\ne x=\"No\""}, {"source_code": "main=interact$unlines.l.lines\nl=g.tail where g[]=[];g(_:n:m:x)=s n m:g x\ns n=e.filter(uncurry(/=)).zip n\ne((a,b):(c,d):[])=if a==c&&b==d then\"Yes\"else\"No\"\ne x=\"No\""}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n cas <- readLn\n replicateM_ cas $ do\n _ <- getLine\n s <- getLine\n t <- getLine\n putStrLn $ f s t\n\nf :: String -> String -> String\nf s t\n | s == t = \"Yes\"\n | otherwise = if length dif == 2 && fi == se then \"Yes\" else \"No\"\n where dif = g s t\n fi = dif !! 0\n se = dif !! 1\n\ng :: String -> String -> [(Char, Char)]\ng [] _ = []\ng _ [] = []\ng (x:xs) (y:ys)\n | x == y = g xs ys\n | otherwise = (x, y) : g xs ys"}, {"source_code": "import Data.List as L\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n strings = (L.take n strings):(groupByNLines n (L.drop n strings))\n\nstringToIntegerArray :: String -> [Integer]\nstringToIntegerArray = L.map (\\x -> read x :: Integer) . words\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 3 . tail . lines)\n\nparse :: [String] -> String\nparse [_, s', t']\n | ans = \"YES\"\n | otherwise = \"NO\"\n where ans = solve s' t'\n\ndiff :: (String, String) -> (String, String)\ndiff (\"\", \"\") = (\"\", \"\")\ndiff ((a:as), (b:bs))\n | a == b = (x, y)\n | otherwise = (a:x, b:y)\n where (x, y) = diff (as, bs)\n\nsolve :: String -> String -> Bool\nsolve s t\n | length ds /= 2 = False\n | otherwise = (ds !! 0) == (ds !! 1) && (dt !! 0) == (dt !! 1)\n where (ds, dt) = diff (s, t)\n"}], "negative_code": [{"source_code": "main=interact$unlines.l.lines\nl=g.tail where g[]=[];g(_:n:m:x)=s n m:g x\ns n=e.filter(uncurry(/=)).zip n\ne((a,b):(c,d):_)=if a==c&&b==d then\"Yes\"else\"No\"\ne x=\"No\""}], "src_uid": "97fa7e82566e3799e165ce6cbbf1da22"} {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n-- {-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport Data.Function (on)\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\nsolve :: Int -> Int -> [Int64] -> Int64\nsolve n k as = L.sum . L.map (L.maximum . L.map snd). L.groupBy ((==) `on` fst) . L.sort . L.map (\\(i, a) -> (i `mod` k, a)) . L.zip [0 ..] $ as\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n [n, k] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntegerB8s <&> L.map fromInteger\n let answer = solve n k as\n printf \"%lld\\n\" answer\n", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[n, k] -> map read . words <$> getLine >>=\n print . maxScore n k\n\nmaxScore :: Int -> Int -> [Int] -> Int\nmaxScore n k as = let a = listArray (0, n-1) as\n q = div n k\n r = rem n k\n is = [[i+a*k | a <- [0..q+1], i+a*k < n] | i <- [0 .. k-1]]\n in\n sum . map (maximum . map (a!)) . filter (/= []) $ is\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.Function\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[n,k], xs] <- replicateM 2 ri\r\n return (n,k,xs)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (_n,k,xs) = rp\r\n where\r\n rp = sum . map (maximum . map snd) . sortGroupOn fst . (`zip`xs) . map (`mod`k) $ inds\r\n\r\ninds = [0..] :: [Int]\r\n\r\nsortGroupOn f = L.groupBy ((==)`on`f) . L.sortOn f\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n-- {-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport Data.Function (on)\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\nsolve :: Int -> Int -> [Int64] -> Int64\nsolve n k as = L.sum . L.map (L.maximum . L.map snd). L.groupBy ((==) `on` fst) . L.map (\\(i, a) -> (i `mod` k, a)) . L.zip [0 ..] $ as\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n [n, k] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntegerB8s <&> L.map fromInteger\n let answer = solve n k as\n printf \"%lld\\n\" answer\n"}], "src_uid": "f974c33780a933a6076c0559e48b7552"} {"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Function\nimport Data.List\n\nmain = do\n [n, m] <- fmap (map read . words) getLine\n a <- fmap (sort . map read . words) getLine\n forM_ (foldl (gao (m + 1)) [(0, [])] a) $ \\(_, i) ->\n when (not $ null i) $\n putStrLn $ unwords $ map show $ length i: i\n where\n gao n b a = take n $ map head $ groupBy ((==) `on` fst) $ sort $\n b ++ map ((a+) *** (a:)) b\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$unlines.f.map read.words\nf(_:k:xs)|ys<-sort xs = take k $ g 1 (reverse ys) $ map (:[]) ys\ng i (x:xs) yss = map(unwords.map show.(i:))yss ++ g (i+1) xs (map (x:) $ init yss)\ng _ _ _ = []"}], "negative_code": [], "src_uid": "2b77aa85a192086316a7f87ce140112d"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Functor\nimport Data.Char (ord)\nimport qualified Data.ByteString.Char8 as B8\n\nprefixSums _ [] = []\nprefixSums !acc (x:xs) = let r = acc + x in r : prefixSums r xs\n\nparseInt :: B8.ByteString -> Integer\nparseInt str = parseInt' str 0 where\n parseInt' str !acc\n | B8.null str = acc\n | otherwise = parseInt' (B8.tail str) $ (fromIntegral $ ord (B8.head str)) - 48 + acc * 10\n\nsolve s a b = solve' a b\n where\n solve' [] _ = 0\n solve' _ [] = 0\n solve' (x:xs) (y:ys) = if (s - y) < x\n then solve' xs (y:ys)\n else if (s - y) > x\n then solve' (x:xs) ys\n else x\n\nmain = do\n _ <- B8.getLine\n xs <- map parseInt . B8.words <$> B8.getLine :: IO [Integer]\n let prefixes = prefixSums 0 xs\n lasts = last prefixes\n (as, bs) = span ((>=) (lasts `div` 2)) prefixes\n as' = reverse as\n bs' = if as == [] then [] else [head as'] ++ bs\n print $ solve lasts as' bs'\n\n", "positive_code": [{"source_code": "{- <\u10e6> Haskell -}\nmodule Main where\nimport Data.Sequence as S\n\nmain :: IO ()\nmain = interact $ solve\n\ntoInt :: String -> Integer\ntoInt s = read s :: Integer\n\nsolve :: String -> String\nsolve s = show $ check (fromList (map toInt (tail (words s)))) 0 0 0\n\ncheck :: Seq Integer -> Integer -> Integer -> Integer -> Integer\ncheck xs ls rs ss =\n if S.null xs then if ls == rs then ls else ss else\n let l :< xl = viewl xs\n xr :> r = viewr xs\n in if ls == rs\n then check xl (ls + l) rs ls\n else if ls > rs\n then check xr ls (rs + r) ss\n else check xl (ls + l) rs ss"}, {"source_code": "{- <\u10e6> Haskell -}\nmodule Main where\nimport Data.Sequence as S\n\nmain :: IO ()\nmain = interact $ solve\n\ntoInt :: String -> Integer\ntoInt s = read s :: Integer\n\nsolve :: String -> String\nsolve s = show $! check (fromList (map toInt (tail (words s)))) 0 0 0\n\ncheck :: Seq Integer -> Integer -> Integer -> Integer -> Integer\ncheck xs ls rs ss =\n if S.null xs then if ls == rs then ls else ss else\n let l :< xl = viewl xs\n xr :> r = viewr xs\n in if ls == rs\n then check xl (ls + l) rs ls\n else if ls > rs\n then check xr ls (rs + r) ss\n else check xl (ls + l) rs ss"}], "negative_code": [{"source_code": "{- <\u10e6> Haskell -}\nmodule Main where\nimport Data.Sequence as S\n\nmain :: IO ()\nmain = interact $ sol\n\ntoInt :: String -> Int\ntoInt s = read s :: Int\n\nsol :: String -> String\nsol s = show $ ch (fromList (map toInt (tail (words s)))) 0 0 0\n\nch :: Seq Int -> Int -> Int -> Int -> Int\nch xs ls rs ss =\n if S.null xs then if ls == rs then ls else ss else\n let l :< xl = viewl xs\n xr :> r = viewr xs\n in if ls == rs\n then ch xl (ls + l) rs ls\n else if ls > rs\n then ch xr ls (rs + r) ss\n else ch xl (ls + l) rs ss"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Functor\n\npss [] _ = []\npss (!x:xs) acc = let y = x + acc in y : pss xs y\n\nmain = do\n n <- read <$> getLine :: IO Int\n ns <- map read . words <$> getLine :: IO [Int]\n let prefixes = pss ns 0\n lasts = last prefixes\n s = lasts `div` 2\n (xs, ys) = span ((>=) s) prefixes\n xs' = reverse xs\n ys' = if n `mod` 2 == 1 then (head xs):ys else ys\n let ans = takeWhile (\\(x, y) -> (lasts - y) /= x) $ zip xs' ys'\n print $ case ans of\n [] -> 0\n (xoro:_) -> fst xoro\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Functor\nimport Data.Char (ord)\nimport qualified Data.ByteString.Char8 as B8\n\nprefixSums _ [] = []\nprefixSums !acc (x:xs) = let r = acc + x in r : prefixSums r xs\n\nparseInt :: B8.ByteString -> Int\nparseInt str = parseInt' str 0 where\n parseInt' str !acc\n | B8.null str = acc\n | otherwise = parseInt' (B8.tail str) $ ord (B8.head str) - 48 + acc * 10\n\nsolve s a b = solve' a b\n where\n solve' [] _ = 0\n solve' _ [] = 0\n solve' (x:xs) (y:ys) = if (s - y) < x\n then solve' xs (y:ys)\n else if (s - y) > x\n then solve' (x:xs) ys\n else x\n\nmain = do\n _ <- B8.getLine\n xs <- map parseInt . B8.words <$> B8.getLine :: IO [Int]\n let prefixes = prefixSums 0 xs\n lasts = last prefixes\n (as, bs) = span ((>=) (lasts `div` 2)) prefixes\n as' = reverse as\n bs' = if as == [] then [] else [head as'] ++ bs\n print $ solve lasts as' bs'\n\n"}], "src_uid": "f2fc865a44b39179261a7311adf48390"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\nimport Data.Array.Unboxed\n\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\n\ndata Act = Act !Int !Int !Int\n\nsolve :: UArray (Int, Int) Int -> Maybe [Act]\nsolve inArr = runST $ do\n arr :: STUArray s (Int, Int) Int\n <- thaw inArr :: ST s (STUArray s (Int, Int) Int)\n let ((rmin, cmin), (rmax, cmax)) = bounds inArr\n cutBnds = ((rmin, cmin), (rmax - 1, cmax - 1))\n stack :: STArray s Int (Int, Int)\n <- newListArray (1, rangeSize cutBnds) (range cutBnds)\n inStack :: STUArray s (Int, Int) Bool\n <- newArray cutBnds True\n let\n tryPush :: Int -> (Int, Int) -> ST s Int\n tryPush stackSize p = if not $ inRange cutBnds p\n then pure stackSize\n else do\n pInStack <- readArray inStack p\n if pInStack\n then pure stackSize\n else do\n let nStackSize = stackSize + 1\n writeArray stack nStackSize p\n writeArray inStack p True\n pure nStackSize\n\n go :: [Act] -> Int -> ST s [Act]\n go acts 0 = pure acts\n go acts top = do\n (i, j) <- readArray stack top\n let nbrs = liftM2 (,) [i - 1 .. i + 1] [j - 1 .. j + 1]\n sqr = liftM2 (,) [i .. i + 1] [j .. j + 1]\n vs <- mapM (readArray arr) sqr\n case filter (/= 0) vs of\n nz : nzs | all (== nz) nzs -> do\n forM_ sqr $ \\p -> writeArray arr p 0\n ntop <- foldM tryPush (top - 1) nbrs\n --writeArray inStack (i, j) False --no need to check again\n go (Act i j nz : acts) ntop\n _ -> writeArray inStack (i, j) False >> go acts (top - 1)\n acts <- go [] (rangeSize cutBnds)\n solved <- all (<= 0) <$> getElems arr\n pure $ if solved\n then Just acts\n else Nothing\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n m <- getInt\n arr <- listArray ((1, 1), (n, m)) <$> replicateM (n * m) getInt\n pure $ case solve arr of\n Just li\n -> putInts [length li] <> foldMap (\\(Act i j c) -> putInts [i, j, c]) li\n Nothing -> string7 \"-1\\n\"\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE LambdaCase, TypeApplications #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ndata V2 = !Int :+ !Int deriving (Eq, Ord) -- Curse you, (Int, Int)!\r\n\r\ninstance Ix V2 where\r\n range (li :+ ri, lj :+ rj) = [i :+ j | i <- [li..ri], j <- [lj..rj]]\r\n inRange (li :+ ri, lj :+ rj) (lk :+ rk) = li <= lk && lk <= lj && ri <= rk && rk <= rj\r\n index (li :+ ri, _ :+ rj) (lk :+ rk) = (lk - li) * (rj - ri + 1) + rk - ri\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[n, m] <- readInts\r\n ba <- unsafeThaw @_ @UArray @_ @IOUArray . listArray (1 :+ 1, n :+ m) . concat =<< replicateM n readInts\r\n let neighbors (i :+ j) =\r\n filter (/=(i :+ j)) $\r\n (:+) <$> [max 1 (i-1) .. min (n-1) (i+1)] <*> [max 1 (j-1) .. min (m-1) (j+1)]\r\n readBox (i :+ j) = do\r\n c0 <- readArray ba (i :+ j)\r\n c1 <- readArray ba (i :+ (j+1))\r\n c2 <- readArray ba ((i+1) :+ j)\r\n c3 <- readArray ba ((i+1) :+ (j+1))\r\n pure [c0, c1, c2, c3] :: IO [Int]\r\n writeBox0 (i :+ j) = do\r\n writeArray ba (i :+ j) 0\r\n writeArray ba (i :+ (j+1)) 0\r\n writeArray ba ((i+1) :+ j) 0\r\n writeArray ba ((i+1) :+ (j+1)) 0 :: IO ()\r\n add qvs@(q, vs) v = filter (/=0) <$> readBox v >>= \\case\r\n (c:cs) | all (==c) cs -> (v:q, (v, c):vs) <$ writeBox0 v\r\n _ -> pure qvs\r\n dfs ([], vs) = pure vs\r\n dfs (u:q, vs) = foldM add (q, vs) (neighbors u) >>= dfs\r\n ans <- dfs =<< foldM add ([], []) ((:+) <$> [1 .. n-1] <*> [1 .. m-1])\r\n done <- all (==0) <$> getElems ba\r\n mapM_ (putStrLn . unwords . map show) $ if done\r\n then [length ans] : map (\\(i :+ j, c) -> [i, j, c]) ans\r\n else [[-1]]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[n, m] <- readInts\r\n ba' <- listArray @UArray ((1, 1), (n, m)) . concat <$> replicateM n readInts\r\n ba <- unsafeThaw @_ @_ @_ @IOUArray ba'\r\n let neighbors (i, j) =\r\n filter (/=(i, j)) $\r\n (,) <$> [max 1 (i-1) .. min (n-1) (i+1)] <*> [max 1 (j-1) .. min (m-1) (j+1)]\r\n box (i, j) = (,) <$> [i, i+1] <*> [j, j+1]\r\n add qvs@(q, vs) v = do\r\n cs <- filter (/=0) <$> mapM (readArray ba) (box v)\r\n case cs of\r\n (c:_) | all (==c) cs -> (v:q, (v, c):vs) <$ mapM_ (flip (writeArray ba) 0) (box v)\r\n _ -> pure @IO qvs\r\n dfs ([], vs) = pure vs\r\n dfs (u:q, vs) = foldM add (q, vs) (neighbors u) >>= dfs\r\n ans <- dfs =<< foldM add ([], []) ((,) <$> [1 .. n-1] <*> [1 .. m-1])\r\n if length ans < (n - 1) * (m - 1)\r\n then print (-1)\r\n else mapM_ (putStrLn . unwords . map show) $\r\n ((:) <$> (:[]) . length <*> map (\\((i, j), c) -> [i, j, c])) ans\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Array.Unsafe\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nmain :: IO ()\r\nmain = do\r\n ~[n, m] <- readInts\r\n ba' <- listArray @UArray ((1, 1), (n, m)) . concat <$> replicateM n readInts\r\n ba <- unsafeThaw @_ @_ @_ @IOUArray ba'\r\n let neighbors (i, j) =\r\n filter (/=(i, j)) $\r\n (,) <$> [max 1 (i-1) .. min (n-1) (i+1)] <*> [max 1 (j-1) .. min (m-1) (j+1)]\r\n box (i, j) = (,) <$> [i, i+1] <*> [j, j+1]\r\n add qvs@(q, vs) v = do\r\n cs <- filter (/=0) <$> mapM (readArray ba) (box v)\r\n case cs of\r\n (c:_) | all (==c) cs -> (v:q, (v, c):vs) <$ mapM_ (flip (writeArray ba) 0) (box v)\r\n _ -> pure @IO qvs\r\n dfs ([], vs) = pure vs\r\n dfs (u:q, vs) = foldM add (q, vs) (neighbors u) >>= dfs\r\n ans <- dfs =<< foldM add ([], []) ((,) <$> [1 .. n-1] <*> [1 .. m-1])\r\n if length ans < (n - 1) * (m - 1)\r\n then print (-1)\r\n else forM_ ans $ \\((i, j), c) -> putStrLn $ unwords $ map show [i, j, c]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\nimport Data.Array.Unboxed\n\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\n\ndata Act = Act !Int !Int !Int\n\nsolve :: UArray (Int, Int) Int -> Maybe [Act]\nsolve inArr = runST $ do\n arr :: STUArray s (Int, Int) Int\n <- thaw inArr :: ST s (STUArray s (Int, Int) Int)\n par :: STArray s (Int, Int) (Int, Int) <- newArray (bounds inArr) (0, 0)\n let\n okIx = inRange (bounds inArr)\n\n needsWork :: (Int, Int) -> ST s (Maybe Int)\n needsWork (i, j) | okIx (i, j) && okIx (i + 1, j + 1) = do\n let ns = [(i, j), (i, j + 1), (i + 1, j), (i + 1, j + 1)]\n vs <- mapM (readArray arr) ns\n pure $ case filter (> 0) vs of\n nz : nzs | all (== nz) nzs -> Just nz\n _ -> Nothing\n needsWork _ = pure Nothing\n\n go :: [Act] -> (Int, Int) -> ST s [Act]\n go acts (i, j) = do\n ok <- needsWork (i, j)\n let rect = liftM2 (,) [i, i + 1] [j, j + 1]\n nbrs = liftM2 (,) [i - 1 .. i + 1] [j - 1 .. j + 1]\n case ok of\n Just c -> do\n let nacts = Act i j c : acts\n forM_ rect $ \\p -> writeArray arr p 0\n findNext nacts (i, j) $ filter okIx nbrs\n Nothing -> do\n v <- readArray par (i, j)\n if not (okIx v) || v == (i, j)\n then pure acts\n else go acts v\n\n findNext :: [Act] -> (Int, Int) -> [(Int, Int)] -> ST s [Act]\n findNext acts _cpar [] = pure acts\n findNext acts cpar (p : ps) = do\n ok <- needsWork p\n case ok of\n Nothing -> findNext acts cpar ps\n Just _ -> writeArray par p cpar >> go acts p\n acts <- foldM go [] (indices inArr)\n solved <- all (<= 0) <$> getElems arr\n pure $ if solved\n then Just acts\n else Nothing\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n m <- getInt\n arr <- listArray ((1, 1), (n, m)) <$> replicateM (n * m) getInt\n pure $ case solve arr of\n Just li\n -> putInts [length li] <> foldMap (\\(Act i j c) -> putInts [i, j, c]) li\n Nothing -> string7 \"-1\\n\"\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport Data.Array.ST.Safe\nimport Control.Monad.ST\n\n\ndata Act = Act !Int !Int !Int\n\nsolve :: UArray (Int, Int) Int -> Maybe [Act]\nsolve inArr = runST $ do\n arr :: STUArray s (Int, Int) Int\n <- thaw inArr :: ST s (STUArray s (Int, Int) Int)\n let\n okIx = inRange (bounds inArr)\n needsWork :: (Int, Int) -> ST s (Maybe Int)\n needsWork (i, j) | okIx (i, j) && okIx (i + 1, j + 1) = do\n let ns = [(i, j), (i, j + 1), (i + 1, j), (i + 1, j + 1)]\n vs <- mapM (readArray arr) ns\n pure $ case filter (> 0) vs of\n nz : nzs | all (== nz) nzs -> Just nz\n _ -> Nothing\n needsWork _ = pure Nothing\n\n go :: (Int, [Act]) -> (Int, Int) -> ST s (Int, [Act])\n go (iter, acts) (i, j) = do\n ok <- needsWork (i, j)\n case ok of\n Just c -> do\n let nacts = Act i j c : acts\n writeArray arr (i, j) iter\n forM_ [(i, j+1), (i+1, j), (i+1, j+1)] $ \\p -> do\n v <- readArray arr p\n when (v > 0) $ writeArray arr p 0\n lookNext nacts\n Nothing -> do\n v <- readArray arr (i, j)\n if v >= 0\n then pure (iter, acts)\n else backtrack acts\n where\n nbrs = filter okIx [(i', j') | i' <- [i-1 .. i+1], j' <- [j-1 .. j+1]]\n lookNext nacts = do\n next <- filterM (fmap isJust . needsWork) nbrs\n case next of\n p : _ -> go (iter - 1, nacts) p\n [] -> backtrack nacts\n backtrack nacts = do\n currPosIter <- readArray arr (i, j)\n nvs <- mapM (readArray arr) nbrs\n case sort $ filter (\\v -> v < 0 && currPosIter < v) nvs of\n [] -> pure (iter, nacts)\n tarv : _ -> do\n p : _ <- filterM (fmap (== tarv) . readArray arr) nbrs\n go (iter - 1, nacts) p\n (_, acts) <- foldM go (negate 1, []) (indices inArr)\n solved <- all (<= 0) <$> getElems arr\n pure $ if solved\n then Just acts\n else Nothing\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n m <- getInt\n arr <- listArray ((1, 1), (n, m)) <$> replicateM (n * m) getInt\n pure $ case solve arr of\n Just li -> foldMap (\\(Act i j c) -> putInts [i, j, c]) li\n Nothing -> string7 \"-1\\n\"\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "3e08a9ef172ece7839728439d5b608a8"} {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.8\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n", "positive_code": [{"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.8\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\t{-else do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as-}\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.0\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.90\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.8\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= {-m `seq` pref `seq`-} maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.75\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.9\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\t\t{-putStrLn .show . f $ (lo + hi) / 2-}\n\t{-else do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as-}\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = {-xs' `deepseq`-} do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\t{-putStrLn . show . maxSum $ xs'-}\n\t\tputStrLn .show . f $ (lo + hi) / 2\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t{-else do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as-}\n\t\t\n\t\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: [Double] -> Double\nsolve xs = cost . (/ 2) . uncurry (+) . (!! 100) $ iterate step range\n where\n range = (minimum xs, maximum xs)\n step (lo, hi)\n | cost i < cost k = (lo, k)\n | otherwise = (i, hi)\n where\n i = (hi + 2 * lo) / 3\n k = (2 * hi + lo) / 3\n\n cost x = foldr go (\\_ _ acc -> acc) xs 0 0 0\n where\n go i run a b c = run a' b' . max c $ max a' b'\n where\n a' = max 0 $ a + i - x\n b' = max 0 $ b - i + x\n\nmain = getLine >> getLine >>= print . solve . map fromIntegral . parse\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.5\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.8\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.90\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = {-xs' `deepseq`-} do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.8\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = {-xs' `deepseq`-} do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . maxSum . map (subtract mid) $ xs\n\t\t{-putStrLn .show . f $ (lo + hi) / 2-}\n\t{-else do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as-}\n\telse do\n\t\tif ((<) `on` maxSum) (map (subtract mid) xs) (map (\\x -> mid - x) xs)\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\t{-xs' = map (subtract mid) xs-}\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}], "negative_code": [{"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.95\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) . map (\\x -> r - x) $ xs\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.List (foldl')\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` maxSum) xs' $ map negate xs'\n\t\tmaxSum l = uncurry max . foldl' (\\(p, m) v -> (max v (p + v), max m p)) (0, head l) $ l\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.List (foldl')\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\t{-f r = let xs' = map (subtract r) xs in (max `on` maxSum) xs' $ map negate xs'\n\t\tmaxSum l = uncurry max . foldl' (\\(p, m) v -> (max v (p + v), max m p)) (0, head l) $ l-}\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.5\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.90\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\t{-f r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)-}\n\t\tf r = let xs' = map (subtract r) xs in xs' `seq` (max `on` (maxSum (head xs') 0)) xs' (map negate xs')\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.95\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) . map (\\x -> r - x) $ xs\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) ((max 0 pref) + a) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.85\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) . map (\\x -> r - x) $ xs\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) ((max 0 pref) + a) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.95\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.90\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\t{-f r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)-}\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' (map negate xs')\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.90\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\t{-f r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) (map (\\x -> r - x) xs)-}\n\t\tf r = let xs' = map (subtract r) xs in xs `seq` (max `on` (maxSum (head xs') 0)) xs' (map negate xs')\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.List (foldl')\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = (max `on` (maxSum (head xs - r) 0)) (map (subtract r) xs) . map (\\x -> r - x) $ xs\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) ((max 0 pref) + a) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\nimport Data.List (foldl')\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` maxSum) xs' $ map negate xs'\n\t\tmaxSum l = uncurry max . foldl (\\(p, m) v -> (max v (p + v), max m p)) (0, head l) $ l\n\t\t{-f r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tif length xs > 2000\n\tthen return ()\n\telse solve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.85\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.7\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function\nimport Data.Time.Clock\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- fmap words getContents\n\tlet xs = map read . tail $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\nsolve tbegin xs lo hi = do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.85\n\tthen do\n\t\tputStrLn . show . f . (* 0.5) $ (hi + lo)\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as\n\t\n\n{-main = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-6\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as-}\n\t\n"}, {"source_code": "import Data.Function\n\nmain = interact $ show . solve . map read . words\nsolve (_:xs) = solve' xs (minimum xs) (maximum xs)\nsolve' xs lo hi\n\t| hi - lo < 1e-5\t=\tf ((hi + lo) / 2)\n\t| otherwise\t\t\t=\tlet\n\t\t\t\t\t\t\t\tmid1 = (2 * lo + hi) / 3\n\t\t\t\t\t\t\t\tmid2 = (lo + 2 * hi) / 3\n\t\t\t\t\t\t\tin\tif f mid1 > f mid2\n\t\t\t\t\t\t\t\tthen\tsolve' xs mid1 hi\n\t\t\t\t\t\t\t\telse\tsolve' xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in (max `on` (maxSum (head xs') 0)) xs' $ map negate xs'\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= maxSum (max m pref) (max a (pref + a)) as\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = xs' `deepseq` do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 0.6\n\tthen do\n\t\tputStrLn . show . maxSum $ xs'\n\telse do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as\n\t\t\n\t\n"}, {"source_code": "import Data.Function (on)\nimport Data.Time.Clock\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as ByteString\nimport Control.DeepSeq\n\nmain = do\n\ttbegin <- getCurrentTime\n\tinput <- ByteString.getContents\n\tlet xs = map (fromIntegral . fst . fromJust . ByteString.readInt) . tail . ByteString.words $ input\n\tsolve tbegin xs (minimum xs) (maximum xs)\n\nsolve :: UTCTime -> [Double] -> Double -> Double -> IO ()\nsolve tbegin xs lo hi = {-xs' `deepseq`-} do\n\ttcurrent <- getCurrentTime\n\tif (diffUTCTime tcurrent tbegin) > 1.75\n\tthen do\n\t\t{-putStrLn . show . maxSum $ xs'-}\n\t\tputStrLn .show . f $ (lo + hi) / 2\n\telse do\n\t\tlet mid1 = (2 * lo + hi) / 3\n\t\tlet mid2 = (lo + 2 * hi) / 3\n\t\tif f mid1 > f mid2\n\t\tthen solve tbegin xs mid1 hi\n\t\telse solve tbegin xs lo mid2\n\twhere\n\t\tf r = let xs' = map (subtract r) xs in xs' `deepseq` (max `on` (maxSum (head xs') 0)) xs' (map negate xs')\n\t\tmaxSum m pref []\t\t= max m pref\n\t\tmaxSum m pref (a:as)\t= m `seq` pref `seq` maxSum (max m pref) ((max 0 pref) + a) as\n\t{-else do\n\t\tif ((<) `on` maxSum) xs' (map negate xs')\n\t\tthen solve tbegin xs lo mid\n\t\telse solve tbegin xs mid hi\n\twhere\n\t\tmid = (lo + hi) / 2\n\t\txs' = map (subtract mid) xs\n\t\tmaxSum l = maxSum' (head l) 0 l\n\t\tmaxSum' m pref []\t\t= max m pref\n\t\tmaxSum' m pref (a:as)\t= m `seq` pref `seq` maxSum' (max m pref) ((max 0 pref) + a) as-}\n\t\t\n\t\n"}], "src_uid": "14950fe682a063b1ae96332e273dea01"} {"source_code": "module Main where\nimport Data.List (sortBy)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nrush :: [Integer] -> Integer\nrush l = let s = sortBy (\\x y -> op (x `compare` y)) l\n op EQ = EQ\n op GT = LT\n op LT = GT\n in binsearch (test s) (head s) (2 * head s)\n\ntest :: [Integer] -> Integer -> Ordering\ntest l x = test' l (x,0)\n where test' [] (t,_)\n | t > 0 = LT\n | otherwise = EQ\n test' (h:rest) (need,found)\n | need <= 0 = EQ\n | otherwise = let r = need - (h - found) in test' rest (need - r,found + r)\n\n\nbinsearch :: (Integer -> Ordering) -> Integer -> Integer -> Integer\nbinsearch f l u\n | l >= u = l\n | t == EQ && f (m - 1) == LT = m\n | t == LT = binsearch f (m + 1) u\n | otherwise = binsearch f l (m - 1)\n where m = (l + u) `div` 2\n t = f m\n\nmain :: IO ()\nmain = do\n l <- fmap (map (fst . fromJust . BS.readInteger) . tail . BS.words) BS.getContents\n print $ rush l\n\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Data.Int\n--import Debug.Trace\n\n\nmain = do\n getLine\n l <- map read <$> words <$> getLine :: IO [Int64]\n print $ solve' l\n \n\nsolve' xs = let m = maximum xs\n l = fromIntegral $ length xs\n s = sum xs\n in max m $ (s -1) `div` (l-1) + 1\n\n\n\n--solve [] = 0\n--solve [x] = x\nsolve l = let m1 = minimum l\n l' = delete m1 l\n in f m1 l'\n where f 0 l = maximum l\n f m l = let m' = minimum l\n d = m' - m + 1\n in d + f (m-1) (m : (map (\\x -> x - d) $ delete m' l))\n"}, {"source_code": "getans :: [Integer] -> Integer -> Integer\ngetans a n =\n\tlet operations = n * (maximum a) - sum a\n\t f op n max = op + (n * (div (max - op) (n - 1))) + (if (mod (max - op) (n - 1) > 0) then (mod (max - op) (n - 1) + 1) else 0)\n\tin (if (operations >= maximum a) then (maximum a) else (f operations n (maximum a)))\n\nmain = do\n\tn <- getLine\n\tinput <- getLine\n\tputStr $ show $ getans (map read (words input) :: [Integer]) (read n :: Integer)\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\nmain = do\n n <- readLn :: IO Int64\n a <- (map (read :: String->Int64) . words) `liftM` getLine\n print $ max (div ((sum a) + (n-2)) (n-1) ) (maximum a)"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- fromIntegral . readInt <$> B.getLine\n l <- readsInt\n print $ solve n $ map fromIntegral $ sort l\n\nsolve :: Int64 -> [Int64] -> Int64\nsolve n l = binarySearch predicate (last l)\n where\n s = sum l\n predicate k = n * k - s >= k\n\nbinarySearch p a | p a = a\n | otherwise = go a $ head $ dropWhile (not . p) [a*2^i | i <- [1..]]\n where \n go a b | b - a <= 1 = b\n | p m = go a m\n | otherwise = go m b\n where m = (a+b) `div` 2\n\n \n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n as = max x y\n\twhere x = ceiling $ (fromIntegral $ sum as) / (fromIntegral $ n-1)\n\t y = maximum as\n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tlet n = readInteger ls\n\tls <- B.getLine\n\tputStrLn . (++ \"\\n\") . show . solve n . map readInteger . C.words $ ls \n\nreadInteger :: C.ByteString -> Integer\nreadInteger = fst . fromJust . C.readInteger\n"}, {"source_code": "import Data.Int\n\nmain = do\n\tn <- readLn :: IO Int64\n\ts <- getLine\n\tlet a = map (read :: String -> Int64) $ words s\n\tprint (max (maximum a) $ div (sum a + n - 2) (n-1))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n n <- toInteger . maybe 0 fst . B.readInt <$> B.getLine\n print . solve n . sort . map (toInteger . maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n as = f 0 as\n where\n m = last as\n f c (a : as)\n | a <= c = m\n | a == m = q + min 1 r + c\n | otherwise = f (c + m - a) as\n where\n (q, r) = (n * (m - c)) `divMod` (n - 1)\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n as = max x y\n\twhere x = ceiling $ (fromIntegral $ sum as) / (fromIntegral $ n-1)\n\t y = maximum as\n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tlet n = readInteger ls\n\tls <- B.getLine\n\tputStrLn . (++ \"\\n\") . show . solve n . map readInteger . C.words $ ls \n\nreadInteger :: C.ByteString -> Integer\nreadInteger = fst . fromJust . C.readInteger\n"}], "negative_code": [{"source_code": "module Main where\nimport System.IO\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [Int] -> Int\nsolve n as = max x y\n\twhere x = ceiling $ (fromIntegral $ sum as) / (fromIntegral $ n-1)\n\t y = maximum as\n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tlet n = readInt ls\n\tls <- B.getLine\n\tputStrLn . (++ \"\\n\") . show . solve n . map readInt . C.words $ ls \n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n"}, {"source_code": "import Data.Int\n\nmain = do\n\tn <- readLn :: IO Int64\n\ts <- getLine\n\tlet a = map (read :: String -> Int64) $ words s\n\tprint (min (maximum a) $ div (sum a + n - 2) (n-1))\n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- readLn :: IO Int\n a <- (map (read :: String->Int) . words) `liftM` getLine\n print $ max (div ((sum a) + (n-2)) (n-1) ) (maximum a)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n n <- maybe 0 fst . B.readInt <$> B.getLine\n print . solve n . sort . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: Int -> [Int] -> Int\nsolve n as = f 0 as\n where\n m = last as\n f c (a : as)\n | a <= c = m\n | a == m = q + min 1 r + c\n | otherwise = f (c + m - a) as\n where\n (q, r) = (n * (m - c)) `divMod` (n - 1)\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Data.Int\n\n\nmain = do\n getLine\n l <- map read <$> words <$> getLine :: IO [Int64]\n print $ solve l\n \n\n\n\nsolve [] = 0\nsolve [x] = x\nsolve l = let m1 = minimum l\n l' = delete m1 l\n m2 = minimum l'\n m3 = maximum $ m1:map (\\x -> x - m2) l'\n in m2 + m3\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\n\nmain = do\n getLine\n l <- map read <$> words <$> getLine\n let n = length l\n s = sum l\n print $ (s - 1) `div` (n-1) + 1"}, {"source_code": "getans :: [Int] -> Int -> Int\ngetans a n =\n\tlet operations = n * (maximum a) - sum a\n\t f op n max = op + (n * (div (max - op) (n - 1))) + (if (mod (max - op) (n - 1) > 0) then (mod (max - op) (n - 1) + 1) else 0)\n\tin (if (operations >= maximum a) then (maximum a) else (f operations n (maximum a)))\n\nmain = do\n\tn <- getLine\n\tinput <- getLine\n\tputStr $ show $ getans (map read (words input) :: [Int]) (read n :: Int)\n"}], "src_uid": "09f5623c3717c9d360334500b198d8e0"} {"source_code": "import Data.List\n\nfactors :: Integer -> [Integer]\nfactors 1 = []\nfactors n = if b == [] then [n] else (head b) : factors (n`div`(head b))\n where a = takeWhile (\\x -> x*x <= n) [2..n]\n b = filter (\\x -> n`mod`x==0) a\n\nsolve :: Integer -> String\nsolve n = (show lenAns) ++ \"\\n\" ++ (unwords $ map show $ ans)\n where fact = reverse $ sort $ map (\\a -> (length a, head a)) $ group $ factors n\n lenAns = fst $ head fact\n f cur sm (x:xs)\n | cur == fst x = f cur (sm*(snd x)) xs\n | otherwise = sm : (f (cur-1) sm (x:xs))\n f cur sm [] = sm : (f (cur-1) sm [])\n ans = take lenAns $ f lenAns 1 fact\n\nmain = interact $ unlines . map (solve . read) . tail . lines\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $ words >>> drop 1 >>> map (read >>> solve >>> showAns) >>> unlines\n where\n showAns xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n\ntype I64 = Integer\n\nsolve :: I64 -> [I64]\nsolve n\n | null fs =\n case root 1 n n of\n Nothing -> [n]\n Just r -> [r, r]\n | otherwise =\n foldl1 (zipWith (*)) $\n map (\\(p, f) -> replicate (k - f) 1 ++ replicate f p) $ (extra, 1) : fs\n where\n fs = factorize n\n extra = foldl (\\v (p, m) -> iterate (`div` p) v !! m) n fs\n k = maximum (map snd fs)\n\nprimes :: [I64]\nprimes = filter prime [2 .. 3120]\n where\n prime p = all ((/= 0) . (p `mod`)) [2 .. p - 1]\n\nfactorize :: I64 -> [(I64, Int)]\nfactorize n = filter ((> 0) . snd) . map f $ primes\n where\n f p = (p, mult n p)\n mult u d\n | u `mod` d == 0 = 1 + mult (u `div` d) d\n | otherwise = 0\n\nroot :: I64 -> I64 -> I64 -> Maybe I64\nroot l r n\n | l > r = Nothing\n | mid * mid == n = Just mid\n | mid * mid > n = root l (mid - 1) n\n | mid * mid < n = root (mid + 1) r n\n where\n mid = (l + r) `div` 2\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Maybe (listToMaybe)\nimport Data.Function (on)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = ((isstolines . solve . linetoi) l) ++ tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: Integer -> [[Integer]]\nsolve n = [[toInteger $ y], fs] where\n fs = reverse $ (n `div` (x^(y-1))) : (take (y-1) $ repeat x)\n (x,y) = maximumBy (compare `on` snd) $ primeFac n\n\nprimeFac :: Integer -> [(Integer,Int)]\nprimeFac n = map (\\xs -> (head xs, length xs)) $ group $ primeFac' n 2 where\n primeFac' n l = unfoldr primePow (n,l)\n primePow (m,l) = listToMaybe [(p, (m `div` p, p)) | p<- jumpatsqrt l m, m `mod` p == 0]\n jumpatsqrt a b = takeWhile ((<=b).(^2)) [a..b] ++ (if b>1 then [b] else [])\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Int (Int64)\nimport Data.List (group, reverse)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nreadIntegerB8 :: B8.ByteString -> Maybe Integer\nreadIntegerB8 = B8.readInteger >>> fmap fst\n\nprimeFactors :: Int64 -> [Int64]\nprimeFactors n = primeFactors' n [2 .. sqrtN]\n where\n sqrtN = floor . sqrt $ realToFrac n\n\n primeFactors' :: Int64 -> [Int64] -> [Int64]\n primeFactors' n is@(i : otherIs)\n | n `mod` i == 0 = i : primeFactors' (n `div` i) is\n | otherwise = primeFactors' n otherIs\n primeFactors' n _\n | n == 1 = []\n | otherwise = [n]\n \nsolve :: Int64 -> [Int64]\nsolve n = reverse result\n where\n result = foldr1 (zipWith (*)) resizedGroups\n resizedGroups = map (\\ps -> take k (ps ++ repeat 1)) primeGroups\n k = maximum . map length $ primeGroups\n primeGroups = group $ primeFactors n\n\nmainCase :: IO ()\nmainCase = do\n Just n <- B8.getLine <&> readIntegerB8 <&> fmap fromInteger\n let answer = solve n\n printf \"%d\\n\" $ length answer\n forM_ answer $ printf \"%lld \"\n printf \"\\n\"\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ const mainCase\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $ words >>> drop 1 >>> map (read >>> solve >>> showAns) >>> unlines\n where\n showAns xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n\ntype I64 = Integer\n\nsolve :: I64 -> [I64]\nsolve n\n | null fs =\n let r = root 1 n n\n in if r * r == n\n then [r, r]\n else [n]\n | otherwise =\n foldl1 (zipWith (*)) $\n map (\\(p, f) -> replicate (k - f) 1 ++ replicate f p) fs\n where\n fs = factorize n\n k = maximum (map snd fs)\n\nprimes :: [I64]\nprimes = filter prime [2 .. 3120]\n where\n prime p = all ((/= 0) . (p `mod`)) [2 .. p - 1]\n\nfactorize :: I64 -> [(I64, Int)]\nfactorize n = filter ((> 0) . snd) . map f $ primes\n where\n f p = (p, mult n p)\n mult u d\n | u `mod` d == 0 = 1 + mult (u `div` d) d\n | otherwise = 0\n\nroot :: I64 -> I64 -> I64 -> I64\nroot l r n\n | l >= r = l\n | mid * mid == n = mid\n | mid * mid > n = root l (mid - 1) n\n | mid * mid < n = root (mid + 1) r n\n where\n mid = (l + r) `div` 2\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $ words >>> drop 1 >>> map (read >>> solve >>> showAns) >>> unlines\n where\n showAns xs = show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n\ntype I64 = Integer\n\nsolve :: I64 -> [I64]\nsolve n\n | null fs =\n let r = round . sqrt . fromInteger $ n\n in if r * r == n\n then [r, r]\n else [n]\n | otherwise =\n foldl1 (zipWith (*)) $\n map (\\(p, f) -> replicate (k - f) 1 ++ replicate f p) fs\n where\n fs = factorize n\n k = maximum (map snd fs)\n\nprimes :: [I64]\nprimes = filter prime [2 .. 3120]\n where\n prime p = all ((/= 0) . (p `mod`)) [2 .. p - 1]\n\nfactorize :: I64 -> [(I64, Int)]\nfactorize n = filter ((> 0) . snd) . map f $ primes\n where\n f p = (p, mult n p)\n mult u d\n | u `mod` d == 0 = 1 + mult (u `div` d) d\n | otherwise = 0\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Int (Int64)\nimport Data.List (group, reverse)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nprimeFactors :: Int64 -> [Int64]\nprimeFactors n = primeFactors' n [2 .. sqrtN]\n where\n sqrtN = floor . sqrt $ realToFrac n\n\n primeFactors' :: Int64 -> [Int64] -> [Int64]\n primeFactors' n is@(i : otherIs)\n | n `mod` i == 0 = i : primeFactors' (n `div` i) is\n | otherwise = primeFactors' n otherIs\n primeFactors' n _\n | n == 1 = []\n | otherwise = [n]\n \nsolve :: Int64 -> [Int64]\nsolve n = reverse result\n where\n result = foldr1 (zipWith (*)) resizedGroups\n resizedGroups = map (\\ps -> take k (ps ++ repeat 1)) primeGroups\n k = maximum . map length $ primeGroups\n primeGroups = group $ primeFactors n\n\nmainCase :: IO ()\nmainCase = do\n Just n <- B8.getLine <&> readIntB8 <&> fmap fromIntegral\n let answer = solve n\n printf \"%d\\n\" $ length answer\n forM_ answer $ printf \"%lld \"\n printf \"\\n\"\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ const mainCase\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Int (Int64)\nimport Data.List (group, reverse)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nprimeFactors :: Int64 -> [Int64]\nprimeFactors n = primeFactors' n [2 .. sqrtN]\n where\n sqrtN = floor . sqrt $ realToFrac n\n\n primeFactors' :: Int64 -> [Int64] -> [Int64]\n primeFactors' n is@(i : otherIs)\n | n `mod` i == 0 = i : primeFactors' (n `div` i) is\n | otherwise = primeFactors' n otherIs\n primeFactors' n _\n | n == 1 = []\n | otherwise = [n]\n \nsolve :: Int64 -> [Int64]\nsolve n = reverse result\n where\n result = foldr1 (zipWith (*)) resizedGroups\n resizedGroups = map (\\ps -> take k (ps ++ repeat 1)) primeGroups\n k = maximum . map length $ primeGroups\n primeGroups = group $ primeFactors n\n\nmainCase :: IO ()\nmainCase = do\n Just n <- B8.getLine <&> readIntB8 <&> fmap fromIntegral\n let answer = solve n\n forM_ answer $ printf \"%d \"\n printf \"\\n\"\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ const mainCase\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Int (Int64)\nimport Data.List (group, reverse)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nprimeFactors :: Int64 -> [Int64]\nprimeFactors n = primeFactors' n [2 .. sqrtN]\n where\n sqrtN = floor . sqrt $ realToFrac n\n\n primeFactors' :: Int64 -> [Int64] -> [Int64]\n primeFactors' n is@(i : otherIs)\n | n `mod` i == 0 = i : primeFactors' (n `div` i) is\n | otherwise = primeFactors' n otherIs\n primeFactors' n _\n | n == 1 = []\n | otherwise = [n]\n \nsolve :: Int64 -> [Int64]\nsolve n = reverse result\n where\n result = foldr1 (zipWith (*)) resizedGroups\n resizedGroups = map (\\ps -> take k (ps ++ repeat 1)) primeGroups\n k = maximum . map length $ primeGroups\n primeGroups = group $ primeFactors n\n\nmainCase :: IO ()\nmainCase = do\n Just n <- B8.getLine <&> readIntB8 <&> fmap fromIntegral\n let answer = solve n\n printf \"%d\\n\" $ length answer\n forM_ answer $ printf \"%d \"\n printf \"\\n\"\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ const mainCase\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Maybe (listToMaybe)\nimport Data.Function (on)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (l : rest) = ((isstolines . solve . linetoi) l) ++ tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: Integer -> [[Integer]]\nsolve n = [[toInteger $ length fs], fs] where\n fs = (:) (n `div` (x^(y-1))) $ take (y-1) $ repeat x \n (x,y) = maximumBy (compare `on` snd) $ primeFac n\n\nprimeFac :: Integer -> [(Integer,Int)]\nprimeFac n = map (\\xs -> (head xs, length xs)) $ group $ primeFac' n 2 where\n primeFac' n l = unfoldr primePow (n,l)\n primePow (m,l) = listToMaybe [(p, (m `div` p, p)) | p<- jumpatsqrt l m, m `mod` p == 0]\n jumpatsqrt a b = takeWhile ((<=b).(^2)) [a..b] ++ (if b>1 then [b] else [])\n"}], "src_uid": "f8d064c90f1f2b4a18386795dbcd9cb9"} {"source_code": "import Control.Arrow\r\nimport Data.List(sort, group)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf k [] = []\r\nchunksOf k xs = let (g, xs') = splitAt k xs in g : chunksOf k xs'\r\n\r\ntype LL = Integer\r\n\r\nmain = interact $ \r\n lines >>> drop 1 >>> chunksOf 2\r\n >>> map ((!! 1) >>> words >>> map read >>> solve >>> show)\r\n >>> unlines\r\n\r\nsolve :: [Int] -> LL\r\nsolve = sum . map (choose2 . length) . group . sort . zipWith (-) [0..]\r\n\r\nchoose2 :: Int -> LL\r\nchoose2 n = let n' = toInteger n in (n' * (n' - 1)) `div` 2", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List (group, sort)\nimport Data.Int (Int64)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine :: IO [Int]\n let nC2 x = fromIntegral x * (fromIntegral x - 1) `quot` 2 :: Int64\n print $ sum $ map (nC2 . length) $ group $ sort $ zipWith (-) a [1 .. n]\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List (group, sort)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine :: IO [Int]\n let nC2 x = x * (x - 1) `quot` 2\n print $ sum $ map (nC2 . length) $ group $ sort $ zipWith (-) a [1 .. n]\n"}, {"source_code": "import Control.Arrow\r\nimport Data.List(sort, group)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf k [] = []\r\nchunksOf k xs = let (g, xs') = splitAt k xs in g : chunksOf k xs'\r\n\r\nmain = interact $ \r\n lines >>> drop 1 >>> chunksOf 2\r\n >>> map ((!! 1) >>> words >>> map read >>> solve >>> show)\r\n >>> unlines\r\n\r\nsolve :: [Int] -> Int\r\nsolve = sum . map (choose2 . length) . group . sort . zipWith (-) [0..]\r\n\r\nchoose2 :: Int -> Int\r\nchoose2 n = (n * (n - 1)) `div` 2"}], "src_uid": "ac4aac095e71cbfaf8b79262d4038095"} {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n minus :: Integer -> Integer -> Integer\n minus m x = m - x\n\n -- 11 comes before breakfast, leave before breakfast\n solve11 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve11 b s d =\n let m = maximum [b, s, d]\n in Just $ map (minus m) [b, s, d]\n\n -- comes before breakfast, leave before supper\n -- 1 0 0\n solve12 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve12 b s d\n | b > s && b > d =\n let m = b\n in Just [(m - b), (m - s - 1), (m - d - 1)]\n | otherwise = Nothing\n\n -- comes before breakfast, leave before dinner\n -- 1 1 0\n solve13 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve13 b s d\n | max b s > d =\n let m = max b s\n in Just [(m - b), (m - s), (m - d - 1)]\n | otherwise = Nothing\n\n -- comes before supper, leave before breakfast\n -- 0 1 1\n solve21 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve21 b s d\n | max s d > b =\n let m = max s d\n in Just [(m - b - 1), (m - s), (m - d)]\n | otherwise = Nothing\n\n -- comes before supper, leave before supper\n -- breakfast == super == dinner\n solve22 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve22 = solve11\n\n -- comes before supper, leave before dinner\n -- 0 1 0\n solve23 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve23 b s d\n | s > d && s > b =\n let m = s\n in Just [(m - b - 1), (m - s), (m - d - 1)]\n | otherwise = Nothing\n\n -- comes before dinner, leave before breakfast\n -- 0 0 1\n solve31 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve31 b s d\n | d > s && d > b =\n let m = d\n in Just [(m - b - 1), (m - s - 1), (m - d)]\n | otherwise = Nothing\n\n -- comes before dinner, leave before supper\n -- 1 0 1\n solve32 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve32 b s d\n | max b d > s =\n let m = maximum [b, s, d]\n in Just [(m - b), (m - s - 1), (m - d)]\n | otherwise = Nothing\n\n solve33 :: Integer -> Integer -> Integer -> Maybe [Integer]\n solve33 = solve11\n\n getValue :: Maybe a -> a\n getValue (Just x) = x\n getValue Nothing = undefined\n\n main :: IO()\n main = do\n [b, s, d] <- getLine >>= return . (map (read :: String -> Integer)) . words\n let r11 = solve11 b s d\n r12 = solve12 b s d\n r13 = solve13 b s d\n r21 = solve21 b s d\n r22 = solve22 b s d\n r23 = solve23 b s d\n r31 = solve31 b s d\n r32 = solve32 b s d\n r33 = solve33 b s d\n r = filter (/=Nothing) [r11, r12, r13, r21, r22, r23, r31, r32, r33]\n rr = map (sum . getValue) r\n print $ minimum $ rr\n\n\n", "positive_code": [{"source_code": "import Data.Functor\nimport Data.Int\n\nsolve :: Int64 -> Int64 -> Int64 -> Int64\nsolve 0 0 0 = 0\nsolve x 0 0 = 2 * (x - 1)\nsolve 0 x 0 = 2 * (x - 1)\nsolve 0 0 x = 2 * (x - 1)\nsolve x y 0\n | x == y = x - 1\n | x > y = 2 * (x - 1) - y\n | x < y = 2 * (y - 1) - x\nsolve x 0 y\n | x == y = x - 1\n | x > y = 2 * (x - 1) - y\n | x < y = 2 * (y - 1) - x\nsolve 0 x y\n | x == y = x - 1\n | x > y = 2 * (x - 1) - y\n | x < y = 2 * (y - 1) - x\nsolve x y z = solve (x - w) (y - w) (z - w)\n where w = min x (min y z)\n\nmain :: IO()\nmain = do\n [b, d, s] <- map read . words <$> getLine\n print $ solve b d s\n"}, {"source_code": "main=interact$show.f.map read.words\nf[b,d,s]=minimum[sum$zipWith(-)[m+x,m+y,m+z][b,d,s]|x<-[0,1],y<-[0,1],z<-[0,1],let m=maximum[b-x,d-y,s-z]]"}, {"source_code": "import Data.List( sort)\nmain = do\n [b,d,s] <- return.map (read::String->Integer).words =<< getLine\n let max = maximum [b,d,s]\n\tlist = map (\\e->e-max) [b,d,s]\n\t[i,j,k] = sort [b,d,s]\n print $ case sort list of\n [0,0,0]\t-> 0\n [n,0,0]\t-> -1-n\n [n,m,0]\t-> 2*k-2-i-j\n"}], "negative_code": [{"source_code": "import Data.List( sort)\nmain = do\n [b,d,s] <- return.map (read::String->Integer).words =<< getLine\n let max = maximum [b,d,s]\n\tlist = map (\\e->e-max) [b,d,s]\n print $ case sort list of\n [0,0,0]\t-> 0\n [n,0,0]\t-> -1-n\n [n,m,0]\t-> maximum [n,m] - minimum [n,m]\n"}], "src_uid": "b34846d90dc011f2ef37a8256202528a"} {"source_code": "import Control.Monad (forM_)\nimport Data.List\n--import Debug.Trace (trace)\n\nreadInts = getLine >>= pure . map read . words \n\nmain = do\n [n'] <- readInts\n forM_ [1..n'] (\\_ -> do\n [n] <- readInts\n s <- getLine\n putStrLn $ if n == 5 && \"Timur\" `elem` (permutations s) then \"YES\" else \"NO\"\n )", "positive_code": [{"source_code": "module Main\r\n ( main )\r\n where\r\n\r\nimport Control.Monad (replicateM)\r\n\r\nsort :: (Ord a) => [a] -> [a]\r\nsort [] = []\r\nsort (x:xs) =\r\n let smallerSorted = sort [a | a <- xs, a <= x]\r\n biggerSorted = sort [a | a <- xs, a > x]\r\n in smallerSorted ++ [x] ++ biggerSorted\r\n\r\ntimurSorted :: String\r\ntimurSorted = sort \"Timur\"\r\n\r\nisTimurPermutation :: String -> Bool\r\nisTimurPermutation s = (sort s) == timurSorted\r\n\r\nmain :: IO ()\r\nmain = do\r\n tests <- readLn\r\n replicateM tests $ do\r\n -- ignore length of next line\r\n _ <- getLine\r\n s <- getLine\r\n case (isTimurPermutation s) of\r\n True -> putStrLn \"YES\"\r\n False -> putStrLn \"NO\"\r\n return ()"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List (group, sort)\n\n--solve :: Int -> C.ByteString -> String\nsolve n s\n | sort s == sort \"Timur\" = \"YES\"\n | otherwise = \"NO\"\n\nread = do\n s1 <- getLine\n s2 <- getLine\n\n putStrLn $ solve (Prelude.read s1 :: Int) s2\n\nmain = do\n t <- getLine\n\n replicateM_ (Prelude.read t :: Int) Main.read\n"}, {"source_code": "{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as BS\r\nimport qualified Data.ByteString.Char8 as SBS\r\nimport Control.Monad.ST\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\nimport Data.Char\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SBS = State BS.ByteString\r\ntype S = StateT BS.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: BS.ByteString -> BS.ByteString\r\ndropSpace = BS.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m BS.ByteString\r\ngetNext = state $ BS.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . BS.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- BS.hGetContents handle\r\n#else\r\n inp <- BS.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n BS.putStr $ toLazyByteString outp\r\n\r\ntloop :: SBS Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nsolve :: SBS Builder\r\nsolve = do\r\n n <- getInt\r\n s <- getNext\r\n let\r\n base = SBS.sort . BS.toStrict $ s\r\n res = base == ((SBS.pack . sort) \"Timur\")\r\n pure . str $ if res then \"YES\\n\" else \"NO\\n\"\r\n"}, {"source_code": "{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Control.Monad.ST\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\nimport Data.Char\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n s <- getNext\r\n let\r\n base = C.sort . P.toStrict $ s\r\n res = base == ((C.pack . sort) \"Timur\")\r\n pure . str $ if res then \"YES\\n\" else \"NO\\n\"\r\n"}, {"source_code": "{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\nimport Data.Char\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n s <- getNext\r\n let\r\n base = sort $ P.unpack s\r\n res = base == (sort \"Timur\")\r\n pure . str $ if res then \"YES\\n\" else \"NO\\n\"\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Data.List (sort)\nimport Data.IntMap (filterWithKey)\n\n\nmain :: IO ()\nmain = interact $ format . solve . parse\n\n\nparse :: String -> [String]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> oddPositions 0 $ take (2 * read w) ws\n\noddPositions :: Int -> [a] -> [a]\noddPositions _ [] = []\noddPositions n (x:xs)\n | odd n = x : oddPositions (n + 1) xs\n | otherwise = oddPositions (n + 1) xs\n \n\nformat :: [Bool] -> String\nformat = unlines . map (\\case\n True -> \"YES\"\n False -> \"NO\"\n )\n\nsolve :: [String] -> [Bool]\nsolve = map ((== \"Timru\") . sort)\n\n\n\n\n"}, {"source_code": "import Data.List (sort)\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >> getLine >>= putStrLn . (ite \"Yes\" \"No\") . isValid\nite x y b = if b then x else y\nisValid s@(a1:a2:a3:a4:a5:[]) = sort s == \"Timru\"\nisValid _ = False\n"}, {"source_code": "{-#LANGUAGE ScopedTypeVariables#-}\r\nimport Data.Set (Set, fromList, size)\r\n\r\nmain = do\r\n input <- getContents\r\n let parsed = keepEverySecond (drop 1 (lines input)) []\r\n let results = reverse (mapTimur parsed [])\r\n mapM_ putStrLn results\r\n\r\n\r\nkeepEverySecond :: [a] -> [a] -> [a]\r\nkeepEverySecond [] res = reverse res\r\nkeepEverySecond (fst:snd:rest) res = keepEverySecond rest ([snd] ++ res) \r\n\r\n\r\nmapTimur :: [String] -> [String] -> [String]\r\nmapTimur [] res = res\r\nmapTimur (x:xs) res = mapTimur xs ([(isTimur x (fromList \"Timur\"))] ++ res)\r\n\r\n\r\nisTimur :: String -> Set Char -> String\r\nisTimur maybeTimur definitelyTimur\r\n | (length maybeTimur) /= (size definitelyTimur) = \"NO\"\r\n | (fromList maybeTimur) == definitelyTimur = \"YES\"\r\n | otherwise = \"NO\"\r\n"}, {"source_code": "import Debug.Trace\r\n\r\nisCharOfName :: Char -> Bool\r\nisCharOfName c = case c of\r\n 'T' -> True\r\n 'i' -> True\r\n 'm' -> True\r\n 'u' -> True\r\n 'r' -> True\r\n _ -> False\r\n \r\nallPass :: (Char -> Bool) -> Bool\r\nallPass f = not (f 'T') && not (f 'i') && not (f 'm')\r\n && not (f 'u') && not (f 'r')\r\n \r\ncheckStr :: String -> (Char -> Bool) -> Bool\r\ncheckStr [] f = if allPass f \r\n then True\r\n else False\r\ncheckStr (x:xs) f = if f x \r\n then checkStr xs (\\c -> if c == x \r\n then False \r\n else f c)\r\n else False\r\n \r\n \r\ndecide :: Int -> IO ()\r\ndecide 0 = return ()\r\ndecide n = do\r\n getLine\r\n s <- getLine\r\n if checkStr s isCharOfName \r\n then putStrLn \"YES\"\r\n else putStrLn \"NO\"\r\n decide (n - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine >>= (return . (read :: String -> Int))\r\n decide t \r\n \r\n "}], "negative_code": [{"source_code": "module Main\r\n ( main )\r\n where\r\n\r\nimport Control.Monad (replicateM)\r\n\r\nsort :: (Ord a) => [a] -> [a]\r\nsort [] = []\r\nsort (x:xs) =\r\n let smallerSorted = sort [a | a <- xs, a <= x]\r\n biggerSorted = sort [a | a <- xs, a > x]\r\n in smallerSorted ++ [x] ++ biggerSorted\r\n\r\ntimurSorted :: String\r\ntimurSorted = sort \"Timur\"\r\n\r\nisTimurPermutation :: String -> Bool\r\nisTimurPermutation s = (sort s) == timurSorted\r\n\r\nmain :: IO ()\r\nmain = do\r\n tests <- readLn\r\n replicateM tests $ do\r\n s <- getLine\r\n case (isTimurPermutation s) of\r\n True -> putStrLn \"YES\"\r\n False -> putStrLn \"NO\"\r\n return ()"}, {"source_code": "module Main\r\n ( main )\r\n where\r\n\r\nimport Control.Monad (replicateM)\r\n\r\ntimur :: String\r\ntimur = \"Timur\"\r\n\r\nisTimurPermutation :: String -> Bool\r\nisTimurPermutation s = lengthEqual && allElem\r\n where lengthEqual = length s == length timur\r\n allElem = all (\\x -> x `elem` timur) s\r\n\r\nmain :: IO ()\r\nmain = do\r\n tests <- readLn\r\n replicateM tests $ do\r\n s <- getLine\r\n case (isTimurPermutation s) of\r\n True -> putStrLn \"YES\"\r\n False -> putStrLn \"NO\"\r\n return ()"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List (group, sort)\n\n--solve :: Int -> C.ByteString -> String\nsolve n s\n | C.sort s == C.sort (C.pack \"Timur\") = \"YES\"\n | otherwise = \"NO\"\n\nread = do\n s1 <- C.getLine\n s2 <- C.getLine\n\n putStrLn $ solve (fst $ fromJust $ C.readInt s1) s2\n\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\n\nimport Data.List (group, sort)\n\n--solve :: Int -> C.ByteString -> String\nsolve n s\n | B.sort s == B.sort (C.pack \"Timur\") = \"YES\"\n | otherwise = \"NO\"\n\nread = do\n s1 <- C.getLine\n s2 <- C.getLine\n\n putStrLn $ solve (fst $ fromJust $ C.readInt s1) s2\n\nmain = do\n t <- C.getLine\n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Data.List (sort)\n\nmain :: IO ()\nmain = interact $ format . solve . parse\n\n\nparse :: String -> [String]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> take (read w) ws\n\nformat :: [Bool] -> String\nformat = unlines . map (\\case\n True -> \"YES\"\n False -> \"NO\"\n )\n\nsolve :: [String] -> [Bool]\nsolve = map ((== \"imrTu\") . sort)\n\n\n\n\n"}], "src_uid": "6c137a74b36dede61037cb3b05167329"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Data.Maybe\r\n\r\ntype Set = S.Set Integer\r\n\r\nisP :: String -> Bool\r\nisP str = foldr (&&) True $ fmap (\\i->strA ! i == strA ! (n-1-i)) [0..div n 2] where\r\n\tstrA = A.listArray (0, n-1) str\r\n\tn = length str\r\n\r\nsolve :: String -> Maybe String\r\nsolve str \r\n\t| not $ isP $ str ++ \"a\" = Just $ str ++ \"a\"\r\n\t| not $ isP $ 'a':str = Just $ 'a':str\r\n\t| otherwise = Nothing\r\n\r\n\r\nshowR :: Maybe String -> IO ()\r\nshowR Nothing = putStrLn \"NO\"\r\nshowR (Just s) = do \r\n\tputStrLn $ \"YES\"\r\n\tputStrLn $ s\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t--[n, k] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tstr <- getLine \r\n\t\tshowR $ solve str\r\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (find)\r\nimport Data.Maybe (fromMaybe)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n words >>> drop 1 >>> map (solve >>> maybe \"NO\" (\"YES\\n\" ++)) >>> unlines\r\n\r\nsolve :: String -> Maybe String\r\nsolve s = find (not . isPalin) ['a' : s, s ++ \"a\"]\r\n\r\nisPalin :: String -> Bool\r\nisPalin s = s == reverse s\r\n"}], "negative_code": [], "src_uid": "e2dc3de62fc45c7e9ddb92daa5c5d8de"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\n(*!) :: Int -> Int -> Int64\nx *! y = fromIntegral x * fromIntegral y\ninfixl 7 *!\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n let\n valCtMap = [(head vs, length vs) | vs <- group $ sort a]\n totsBelow = scanl (\\x (v, ct) -> x + v *! ct) 0 valCtMap\n cutoff = last\n $ [v | ((v, _ct), tot) <- zip valCtMap totsBelow, fromIntegral v > tot]\n ans = [i | (i, ai) <- zip [1..] a, ai >= cutoff]\n putInts [length ans]\n putInts ans\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\nminus x = -x\r\n\r\n\r\nresult list' = aux list $ sumPartial list where\r\n\tlist = L.sortOn (minus . snd) $ zip [0..] list'\r\n\r\n\tsumPartial :: [(Integer, Integer)] -> [Integer]\r\n\tsumPartial [] = [0]\r\n\tsumPartial (x:[]) = [0]\r\n\tsumPartial (x:y:xs) = (snd y) + head l : l where l = sumPartial (y:xs)\r\n\r\n\taux [] [] = []\r\n\taux (x:xs) (y:ys)\r\n\t\t| (snd x) > y = [fst x] \r\n\t\t| otherwise = fst x : aux xs ys\r\n\r\n\r\n\r\n\r\nshowR (x:xs) = show (x+1) ++ \" \" ++ showR xs\r\nshowR [] = []\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tlet val = result a\r\n\t\tprint $ length val\r\n\t\tputStrLn $ showR $ L.sort val\r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List\nimport Data.Int\n\n--getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n \nsolve' :: Builder -> Int -> [Int] -> Builder\nsolve' buf 0 _ = buf\nsolve' buf nt (n:a) = solve' (buf <> f <> char7 '\\n') (pred nt) c\n where\n (b, c) = splitAt n a\n d = sort $ zip b [1 ..]\n e :: [Int64]\n e = scanl1 (+) $ map (fromIntegral . fst) d\n f :: Builder\n l = succ $ length $ takeWhile (\\((u, j), v) -> (fromIntegral u) <= v) $ zip (reverse d) (tail $ reverse e)\n g' = map snd $ take l $ reverse d\n --g' = map (snd.fst) $ takeWhile (\\((u, j), v) -> (fromIntegral u) <= v) $ zip (reverse d) (tail $ reverse e)\n --u = snd $ last d\n g = map intDec $ sort g'\n --g = map intDec $ map (snd.fst) $ takeWhile (\\((u, j), v) -> (fromIntegral u ) >= v) $ reverse $ zip d (e ++ [-1])\n f = intDec (length g) <> char7 '\\n' <> (mconcat $ intersperse (char7 ' ') g)\n\nsolve :: [Int] -> Builder\nsolve (n:a) = solve' mempty n a\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\nimport qualified Data.Map.Strict as M\n\ntype SIO = StateT P.ByteString IO\n\n(*!) :: Int -> Int -> Int64\nx *! y = fromIntegral x * fromIntegral y\ninfixl 7 *!\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n let\n --valCtMap = [(head vs, length vs) | vs <- group $ sort a]\n valCtMap = M.assocs $ M.fromListWith (+) $ zip a $ repeat 1\n totsBelow = scanl (\\x (v, ct) -> x + v *! ct) 0 valCtMap\n cutoff = last\n $ [v | ((v, _ct), tot) <- zip valCtMap totsBelow, fromIntegral v > tot]\n ans = [i | (i, ai) <- zip [1..] a, ai >= cutoff]\n putInts [length ans]\n putInts ans\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.concat <$> replicateM t run1\n\n\nrun1 = do\n n <- popInt\n as <- popIntegers\n let ans = solve n as\n return $ B.unlines [bshow (length ans), B.unwords $ map bshow ans]\n\n\nsolve :: Int -> [Integer] -> [Int]\nsolve n as = map fst $ filter ((>= thre) . snd) $ zip [1..] as\n where\n counts :: Array Int (Integer, Int)\n counts = let l = countList as in\n listArray (0, length l - 1) l\n\n ncounts = snd (bounds counts) + 1\n\n thre | ok 0 = fst $ counts ! 0\n | otherwise = go 0 (ncounts - 1)\n\n go i j | j - i == 1 = fst $ counts ! j\n | otherwise = let k = (i + j) `quot` 2 in\n if ok k\n then go i k\n else go k j\n\n ok i = let s = sum $\n map ((\\(a, c) -> a * (fromIntegral c)) . (counts !)) $\n [0 .. i] in\n okgo s $ map (counts !) [i + 1 .. ncounts - 1]\n\n okgo _ [] = True\n okgo s ((a, c) : as) | s >= a = okgo (s + a * (fromIntegral c)) as\n | otherwise = False\n\n\ncountList :: (Ord a) => [a] -> [(a, Int)]\ncountList xs = Map.assocs $ foldl' addm Map.empty xs\n where\n addm m x | Map.member x m = Map.adjust (+ 1) x m\n | otherwise = Map.insert x 1 m\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\n\r\ntype PrioQueue = M.Map Integer [Integer]\r\ninsert :: Integer -> Integer -> PrioQueue -> PrioQueue\r\ninsert prio val queue = case M.lookup prio queue of \r\n\tJust l -> M.insert prio (val:l) queue\r\n\tNothing -> M.insert prio [val] queue\r\n\r\ndelete :: Integer -> Integer -> PrioQueue -> PrioQueue\r\ndelete prio val queue = case M.lookup prio queue of \r\n\tJust (x:[]) -> M.delete prio queue\r\n\tJust l -> M.insert prio (L.delete val l) queue\r\n\r\nfindMax :: PrioQueue -> (Integer, Integer)\r\nfindMax queue = case M.findMax queue of \r\n\t(k, v:l) -> (k, v)\r\n\r\n\r\n\r\nresult arrayM \r\n\t| v > sumOther = [(k, v)]\r\n\t| otherwise = (k, v) : result arrayM'\r\n\twhere\r\n\t\t(v, k) = findMax arrayM\r\n\t\tsumOther = M.foldrWithKey (\\k l i ->i + k * toInteger (length l) ) 0 arrayM'\r\n\t\tarrayM' = delete v k arrayM\r\n\r\n\r\n\r\nshowR ((x, _):xs) = show (x+1) ++ \" \" ++ showR xs\r\nshowR [] = []\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tlet val = result $ foldr (\\(ai, i) m -> insert ai i m) M.empty $ zip a [0..]\r\n\t\tprint $ length val\r\n\t\tputStrLn $ showR val\r\n\t\tloop $ t - 1\r\n\tloop t"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport Data.Map((!))\r\n\r\nresult arrayM \r\n\t| null arrayM = []\r\n\t| v > sumOther = [(k, v)]\r\n\t| otherwise = (k, v) : result arrayM'\r\n\twhere\r\n\t\t(k, v) = M.findMin arrayM\r\n\t\tsumOther = foldr (+) 0 arrayM'\r\n\t\tarrayM' = M.delete k arrayM\r\n\r\n\r\n\r\nshowR ((x, _):xs) = show (x+1) ++ \" \" ++ showR xs\r\nshowR [] = []\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tlet val = result $ M.fromList $ zip [0..] a\r\n\t\tprint $ length val\r\n\t\tputStrLn $ showR val\r\n\t\tloop $ t - 1\r\n\tloop t"}], "src_uid": "debce043777e7e575f77a94edf89c7f1"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Data.List\n\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map read.words <$> getLine\n print $ solve n k xs\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k xs = maximum[calc (sort xs1) (sortBy(flip compare)$xs0++xs2)|i<-[0..n-1],j<-[i..n-1],let(xs0,xs')=splitAt i xs,let(xs1,xs2)=splitAt(j-i+1)xs']\n where\n calc :: [Int] ->[Int] -> Int\n calc xs ys = go k 0 xs ys\n where\n go 0 !acc xs ys = acc + sum xs\n go k acc (x:xs) (y:ys)\n | x < y = go (k-1) (acc+y) xs ys\n | otherwise = acc + sum (x:xs)\n go k acc xs _ = acc + sum xs\n \n \n\n", "positive_code": [{"source_code": "import Text.Printf\nimport Data.List as List\n\ncombinations list1 list2 = [(a, b) | a <- list1, b <- list2]\n\nsplitAt2 :: [Int] -> (Int, Int) -> ([Int], [Int], [Int])\nsplitAt2 list (s1, s2) =\n let\n (l1, l23) = splitAt s1 list\n (l2, l3) = splitAt (s2 - s1) l23\n in\n (l1, l2, l3)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k input =\n let\n subsegments = filter (\\(l, r) -> l < r) $ combinations [0..n] [0..n]\n \n test (l1, l2, l3) =\n let\n taken = sort l2\n rest = reverse $ sort $ l1 ++ l3\n\n takenSum = sum taken\n\n substitutes = takeWhile (\\(old, new) -> old < new) $ take k $ zip taken rest\n in\n takenSum + foldl (\\acc (old, new) -> acc + new - old) 0 substitutes\n in\n maximum $ map test $ map (splitAt2 input) $ subsegments\n\nmain :: IO ()\nmain = do\n --n <- readLn :: IO Int\n content <- getContents\n let \n input = map (read::String->Int) $ words $ unwords $ lines content\n ans = solve (head input) (head $ tail input) (tail $ tail input)\n putStrLn $ show $ ans\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n print $ solve n k as\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as = maximum $ [ sub l r | l <- [1..n], r <- [l..n] ]\n where\n sub l r = sum (zipWith max xs1 ys ++ xs2) \n where\n (a,as') = splitAt (l-1) as\n (b,c) = splitAt (r - l + 1) as'\n k' = minimum [k,(length b),(length $ a ++ c)]\n (xs1,xs2) = splitAt k' (sort $ b)\n ys = take k' $ reverse $ sort $ a ++ c\n"}], "negative_code": [], "src_uid": "ff69d22bc683e5d1d83438585224c774"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Tuple\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport Data.Word\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- U.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print $ solve $ U.map fromIntegral xs\n\nsolve :: U.Vector Int64 -> Int64\nsolve xs = len * m + U.maximum zs\n where\n len = fromIntegral $ U.length xs\n m = U.minimum xs\n ys = U.map (subtract m) xs\n zs = U.scanl (\\acc x->if x==0 then 0 else acc+1) 0 $ ys U.++ ys", "positive_code": [{"source_code": "readInt :: String -> Int\nreadInt = read\n\nf :: [Int] -> Integer\nf a = l*m' + extra\n where\n l = toInteger $ length a\n m = minimum a\n m' = toInteger m\n b = map (\\x->x-m) a\n c = scanl (\\acc x -> if x == 0 then 0 else acc+1) 0 $ b ++ b\n extra = toInteger $ maximum c\n\nmain = do\n n <- readLn :: IO Int\n line <- getLine\n let a = map readInt $ words line\n print (f a)\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Integer\n a <- fmap ((map read) . words) getLine :: IO[Integer]\n let mn = minimum a\n (_,ls) = unzip . filter (\\(x,y) -> x==mn) . zip a $ [1..]\n zl = zipWith (\\x y -> y-x-1) ls $ (tail ls)\n lmx = if zl==[] then 0 else maximum zl\n fst = head ls\n lst = last ls\n ans = max lmx (n-(lst-fst+1))\n print $ n*mn + ans\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n as :: [Int64] <- map fromIntegral <$> getInts\n\n let\n m = minimum as\n bs = map (\\x -> x-m) as\n\n p = min n $ maximum $ map genericLength $ splitOn [0] $ bs ++ bs\n\n print $ m*n + p\n\n"}], "negative_code": [{"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let mn = minimum a\n (_,ls) = unzip . filter (\\(x,y) -> x==mn) . zip a $ [1..]\n zl = zipWith (\\x y -> y-x-1) ls $ (tail ls)\n lmx = if zl==[] then 0 else maximum zl\n fst = head ls\n lst = last ls\n ans = max lmx (n-(lst-fst+1))\n print $ n*mn + ans\n\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let mn = minimum a\n (_,ls) = unzip . filter (\\(x,y) -> x==mn) . zip a $ [1..]\n ans = n*mn + (fn n (ls ++ [head ls]) 0)\n print ans\n\n\nfn n (x:y:[]) mx = max mx (n + (y-x-1))\nfn n (x:y:xs) mx =\n let seglen = (y-x-1)\n in fn n (y:xs) (max seglen mx)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n as <- getInts\n\n let\n m = minimum as\n bs = map (\\x -> x-m) as\n\n p = min n $ maximum $ map length $ splitOn [0] $ bs ++ bs\n\n print $ m*n + p\n\n"}, {"source_code": "readInt :: String -> Int\nreadInt = read\n\nf :: [Int] -> Int\nf a = l*m + extra\n where\n l = length a\n m = minimum a\n b = map (\\x->x-m) a\n c = scanl (\\acc x -> if x == 0 then 0 else acc+1) 0 $ b ++ b\n extra = maximum c\n\nmain = do\n n <- readLn :: IO Int\n line <- getLine\n let a = map readInt $ words line\n print (f a)\n"}], "src_uid": "e2db09803d87362c67763ef71e8b7f47"} {"source_code": "import Data.Char as Char\n\ng :: [Int] -> Int\ng [] = 0\ng [0] = 1\ng [_] = 0\ng (0:xs) = 1+(g xs)\ng [_,0] = 1\ng [x,y] = fromEnum $ (x+y)==3\ng (_:0:lat) = 1 + (g lat)\ng (x:y:z:lat)\n |(x+y)==3 = 1 + (g (z:lat))\n |otherwise = 1 + (g lat)\n\n\nmain :: IO ()\nmain = do\n line <- getLine\n let line' = map ((flip mod 3).(Char.digitToInt)) line\n print $ g line'\n", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ndoit [] t = 0\ndoit (x:xs) t\n | mod x 3 == 0 = 1 + doit xs 0\n | t == 3 = 1 + doit xs 0\n | mod x 3 == 1 && t == 0 = doit xs 1\n | mod x 3 == 1 && t == 1 = doit xs 3\n | mod x 3 == 1 && t == 2 = 1 + doit xs 0\n | mod x 3 == 2 && t == 0 = doit xs 2\n | mod x 3 == 2 && t == 1 = 1 + doit xs 0\n | mod x 3 == 2 && t == 2 = doit xs 3\n\n\nsolve::String -> String\nsolve ss =\n let d = map (\\x -> toint [x]) (reverse (tail (reverse ss))) in\n let r = doit d 0 in\n (show r) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}], "negative_code": [], "src_uid": "3b2d0d396649a200a73faf1b930ef611"} {"source_code": "{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, liftM2, when, foldM, liftM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (accumArray, elems, (!), array, listArray, elems, bounds)\nimport Data.Array (Array)\nimport Data.Array.MArray.Safe (newArray, newArray_, readArray, writeArray, freeze, getBounds)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftR, xor, bit, popCount)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64, Int8)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Tuple (swap)\nimport Data.List (unfoldr)\nimport Data.Char (isSpace)\n\ndata Op = UpdateOp !Int !Int8 | QueryOp !Int\n\nop [1, v, c] = UpdateOp v (fromIntegral c)\nop [2, v] = QueryOp v\n\ntype STree s = (STUArray s Int Int64, STUArray s Int Int8)\n\nbuild :: UArray Int Int -> ST s (STree s)\nbuild l = do\n let n = snd (bounds l)\n\n a <- newArray_ (1, 2*n-1)\n forM_ [n..2*n-1] $ \\i -> writeArray a i (bit (l!(i-n+1)))\n\n forM_ [n-1,n-2..1] $ \\i ->\n liftM2 (.|.) (readArray a $ 2*i) (readArray a $ 2*i+1) >>= writeArray a i\n\n b <- newArray (1, 2*n-1) 0\n\n return (a, b)\n\nsize :: (STree s) -> ST s Int\nsize t@(a, _) = do\n (_, l) <- getBounds a\n return $ l`div`2 + 1\n\npushDown :: (STree s) -> Int -> ST s ()\npushDown t@(a, b) i0 = push $ m-2\n where\n m = until (\\s -> i0 `shiftR` s == 1) (+1) 0\n\n push (-2) = return ()\n push (-1) = return ()\n push s = do\n let i = i0 `shiftR` s\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then do\n let\n vv = bit $ fromIntegral v\n ii = i `xor` 1\n writeArray a i vv >> writeArray a ii vv\n writeArray b i v >> writeArray b ii v\n writeArray b j 0\n else return ()\n\n push $ s-1\n\nupdate :: (STree s) -> Int -> Int -> Int8 -> ST s ()\nupdate t@(a, b) l r v = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n\n pushDown t l' >> pushDown t r' >>\n loop l' r' >>\n popUp l' >> popUp r'\n where\n loop l r\n | l > r = return ()\n | odd l = write l v >> loop (l+1) r\n | even r = write r v >> loop l (r-1)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n where\n write i v = writeArray a i (bit $ fromIntegral v) >> writeArray b i (fromIntegral v)\n\n popUp 1 = return ()\n popUp i = do\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then writeArray a j (bit $ fromIntegral v)\n else liftM2 (.|.) (readArray a i) (readArray a (i `xor` 1)) >>= writeArray a j\n popUp $ i `shiftR` 1\n\nquery :: (STree s) -> Int -> Int -> ST s Int64\nquery t@(a, b) l r = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n pushDown t l' >> pushDown t r' >> loop l' r'\n where\n loop l r\n | l > r = return 0\n | odd l = liftM2 (.|.) (readArray a l) (loop (l+1) r)\n | even r = liftM2 (.|.) (loop l (r-1)) (readArray a r)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\ngetInts = readInts <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n cs <- getInts\n es <- replicateM (n-1) $ ((\\[a, b] -> (a, b)) <$> getInts)\n qs <- replicateM m $ (op <$> getInts)\n\n let\n rs = runST $ do\n t <- build cs' :: ST s ((STUArray s Int Int64), (STUArray s Int Int8))\n\n let\n handle [] = return []\n handle ((UpdateOp v c):ops) = do\n update t l r c\n handle ops\n where (l, r) = range v\n handle ((QueryOp v):ops) = do\n c <- query t l r\n let !r = fromIntegral $ popCount c\n (r:) <$> handle ops\n where (l, r) = range v\n\n handle qs\n where\n cs' = array (1, n) $ map swap $ zip cs (elems ins) :: UArray Int Int\n\n p :: (UArray Int Int, UArray Int Int)\n p@(ins, outs) = runST $ do\n ins <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n outs <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n cr <- newSTRef 0\n\n let\n dfs w u = do\n modifySTRef cr (+1)\n readSTRef cr >>= \\c -> writeArray ins u c\n mapM_ (dfs u) vs\n readSTRef cr >>= \\c -> writeArray outs u c\n where\n vs = filter (/= w) $ g!u\n\n dfs 0 1\n\n liftM2 (,) (freeze ins) (freeze outs)\n where\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es :: Array Int [Int]\n\n range v = (ins!v, outs!v)\n\n\n putStrLn . unlines . map show $ filter (/= 0) rs\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, liftM2, when, foldM, liftM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (accumArray, elems, (!), array, listArray, elems, bounds)\nimport Data.Array (Array)\nimport Data.Array.MArray.Safe (newArray, newArray_, readArray, writeArray, freeze, getBounds)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftR, xor, bit, popCount)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64, Int8)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Tuple (swap)\nimport Data.List (unfoldr)\nimport Data.Char (isSpace)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\ntype STree s = (STUArray s Int Int64, STUArray s Int Int8)\n\nforceM :: Monad m => m a -> m a\nforceM m = do v <- m; return $! v\n\n(<$!>) :: Monad m => (a -> b) -> m a -> m b\nf <$!> m = liftM f (forceM m)\n\nbuild :: UArray Int Int -> ST s (STree s)\nbuild l = do\n let n = snd (bounds l)\n\n a <- newArray_ (1, 2*n-1)\n forM_ [n..2*n-1] $ \\i -> writeArray a i (bit (l!(i-n+1)))\n\n forM_ [n-1,n-2..1] $ \\i ->\n liftM2 (.|.) (readArray a $ 2*i) (readArray a $ 2*i+1) >>= writeArray a i\n\n b <- newArray (1, 2*n-1) 0\n\n return (a, b)\n\nsize :: (STree s) -> ST s Int\nsize t@(a, _) = do\n (_, l) <- getBounds a\n return $ l`div`2 + 1\n\npushDown :: (STree s) -> Int -> ST s ()\npushDown t@(a, b) i0 = push $ m-2\n where\n m = until (\\s -> i0 `shiftR` s == 1) (+1) 0\n\n push (-2) = return ()\n push (-1) = return ()\n push s = do\n let i = i0 `shiftR` s\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then do\n let\n vv = bit $ fromIntegral v\n ii = i `xor` 1\n writeArray a i vv >> writeArray a ii vv\n writeArray b i v >> writeArray b ii v\n writeArray b j 0\n else return ()\n\n push $ s-1\n\nupdate :: (STree s) -> Int -> Int -> Int -> ST s ()\nupdate t@(a, b) l r v = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n\n pushDown t l' >> pushDown t r' >>\n loop l' r' >>\n popUp l' >> popUp r'\n where\n loop l r\n | l > r = return ()\n | odd l = write l v >> loop (l+1) r\n | even r = write r v >> loop l (r-1)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n where\n write i v = writeArray a i (bit $ fromIntegral v) >> writeArray b i (fromIntegral v)\n\n popUp 1 = return ()\n popUp i = do\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then writeArray a j (bit $ fromIntegral v)\n else liftM2 (.|.) (readArray a i) (readArray a (i `xor` 1)) >>= writeArray a j\n popUp $ i `shiftR` 1\n\nquery :: (STree s) -> Int -> Int -> ST s Int64\nquery t@(a, b) l r = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n pushDown t l' >> pushDown t r' >> loop l' r'\n where\n loop l r\n | l > r = return 0\n | odd l = liftM2 (.|.) (readArray a l) (loop (l+1) r)\n | even r = liftM2 (.|.) (loop l (r-1)) (readArray a r)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\n\ntakeTwo [] rs = rs\ntakeTwo (u:v:xs) rs = takeTwo xs ((u, v):rs)\n\nmain = do\n c <- readInts <$> B.getContents\n\n let\n (n:m:r1) = c\n (cs, r2) = splitAt n r1\n (p1, r3) = splitAt (2*n-2) r2\n es = takeTwo p1 []\n qs = r3\n\n let\n p :: (UArray Int Int, UArray Int Int)\n p@(ins, outs) = runST $ do\n ins <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n outs <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n cr <- newSTRef 0\n\n let\n dfs w u = do\n modifySTRef cr (+1)\n readSTRef cr >>= \\c -> writeArray ins u c\n mapM_ (dfs u) vs\n readSTRef cr >>= \\c -> writeArray outs u c\n where\n vs = filter (/= w) $ g!u\n\n dfs 0 1\n\n liftM2 (,) (freeze ins) (freeze outs)\n where\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es :: Array Int [Int]\n\n range v = (ins!v, outs!v)\n\n cs' = array (1, n) $ map swap $ zip cs (elems ins) :: UArray Int Int\n\n solve :: [Int8]\n solve = runST $ do\n t <- build cs' :: ST s ((STUArray s Int Int64), (STUArray s Int Int8))\n\n let\n f [] = return []\n\n f (1:v:c:qs) = update t l r c >> f qs where (l, r) = range v\n\n f (2:v:qs) = ((fromIntegral . popCount) <$!> query t l r) >>= \\r -> (r:) <$> f qs where (l, r) = range v\n\n f qs\n\n putStrLn $ unlines $ map show $ filter (/= 0) solve\n -- let rs = filter (/= 0) solve\n\n -- let unwords_ = mconcat . map (<> charUtf8 '\\n')\n -- hPutBuilder stdout $ unwords_ $ map intDec (rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, BangPatterns #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, liftM2, when, foldM, liftM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (accumArray, elems, (!), array, listArray, elems, bounds)\nimport Data.Array (Array)\nimport Data.Array.MArray.Safe (newArray, newArray_, readArray, writeArray, freeze, getBounds)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftR, xor, bit, popCount)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64, Int8)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Tuple (swap)\nimport Data.List (unfoldr)\nimport Data.Char (isSpace)\n\ndata Op = UpdateOp !Int !Int8 | QueryOp !Int\n\nop [1, v, c] = UpdateOp v (fromIntegral c)\nop [2, v] = QueryOp v\n\ntype STree s = (STUArray s Int Int64, STUArray s Int Int8)\n\nforceM :: Monad m => m a -> m a\nforceM m = do v <- m; return $! v\n\n(<$!>) :: Monad m => (a -> b) -> m a -> m b\nf <$!> m = liftM f (forceM m)\n\nbuild :: UArray Int Int -> ST s (STree s)\nbuild l = do\n let n = snd (bounds l)\n\n a <- newArray_ (1, 2*n-1)\n forM_ [n..2*n-1] $ \\i -> writeArray a i (bit (l!(i-n+1)))\n\n forM_ [n-1,n-2..1] $ \\i ->\n liftM2 (.|.) (readArray a $ 2*i) (readArray a $ 2*i+1) >>= writeArray a i\n\n b <- newArray (1, 2*n-1) 0\n\n return (a, b)\n\nsize :: (STree s) -> ST s Int\nsize t@(a, _) = do\n (_, l) <- getBounds a\n return $ l`div`2 + 1\n\npushDown :: (STree s) -> Int -> ST s ()\npushDown t@(a, b) i0 = push $ m-2\n where\n m = until (\\s -> i0 `shiftR` s == 1) (+1) 0\n\n push (-2) = return ()\n push (-1) = return ()\n push s = do\n let i = i0 `shiftR` s\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then do\n let\n vv = bit $ fromIntegral v\n ii = i `xor` 1\n writeArray a i vv >> writeArray a ii vv\n writeArray b i v >> writeArray b ii v\n writeArray b j 0\n else return ()\n\n push $ s-1\n\nupdate :: (STree s) -> Int -> Int -> Int8 -> ST s ()\nupdate t@(a, b) l r v = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n\n pushDown t l' >> pushDown t r' >>\n loop l' r' >>\n popUp l' >> popUp r'\n where\n loop l r\n | l > r = return ()\n | odd l = write l v >> loop (l+1) r\n | even r = write r v >> loop l (r-1)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n where\n write i v = writeArray a i (bit $ fromIntegral v) >> writeArray b i (fromIntegral v)\n\n popUp 1 = return ()\n popUp i = do\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then writeArray a j (bit $ fromIntegral v)\n else liftM2 (.|.) (readArray a i) (readArray a (i `xor` 1)) >>= writeArray a j\n popUp $ i `shiftR` 1\n\nquery :: (STree s) -> Int -> Int -> ST s Int64\nquery t@(a, b) l r = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n pushDown t l' >> pushDown t r' >> loop l' r'\n where\n loop l r\n | l > r = return 0\n | odd l = liftM2 (.|.) (readArray a l) (loop (l+1) r)\n | even r = liftM2 (.|.) (loop l (r-1)) (readArray a r)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\ngetInts = readInts <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n cs <- getInts\n es <- replicateM (n-1) $ ((\\[a, b] -> (a, b)) <$> getInts)\n qs <- replicateM m $ (op <$> getInts)\n\n let\n p :: (UArray Int Int, UArray Int Int)\n p@(ins, outs) = runST $ do\n ins <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n outs <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n cr <- newSTRef 0\n\n let\n dfs w u = do\n modifySTRef cr (+1)\n readSTRef cr >>= \\c -> writeArray ins u c\n mapM_ (dfs u) vs\n readSTRef cr >>= \\c -> writeArray outs u c\n where\n vs = filter (/= w) $ g!u\n\n dfs 0 1\n\n liftM2 (,) (freeze ins) (freeze outs)\n where\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es :: Array Int [Int]\n\n range v = (ins!v, outs!v)\n\n cs' = array (1, n) $ map swap $ zip cs (elems ins) :: UArray Int Int\n\n solve :: [Int8]\n solve = runST $ do\n t <- build cs' :: ST s ((STUArray s Int Int64), (STUArray s Int Int8))\n\n let\n handle [] = return []\n handle ((UpdateOp v c):ops) = do\n update t l r c\n handle ops\n where (l, r) = range v\n handle ((QueryOp v):ops) = do\n c <- query t l r\n let !r = fromIntegral $ popCount c\n (r:) <$> handle ops\n where (l, r) = range v\n\n handle qs\n\n putStrLn . unlines . map show $ filter (/= 0) solve\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, forM_, liftM2, when, foldM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (accumArray, elems, (!), array, listArray, elems, bounds)\nimport Data.Array (Array)\nimport Data.Array.MArray.Safe (newArray, newArray_, readArray, writeArray, freeze, getBounds)\nimport Data.Array.ST.Safe (STUArray, runSTUArray, STUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits ((.|.), shiftR, xor, bit, popCount)\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int (Int64, Int8)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Tuple (swap)\nimport Data.List (unfoldr)\nimport Data.Char (isSpace)\n\nimport Data.ByteString.Lazy.Builder -- requires bytestring-0.10.x\nimport Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x\nimport Data.Monoid\nimport System.IO hiding (getContents, getLine)\n\ntype STree s = (STUArray s Int Int64, STUArray s Int Int8)\n\nbuild :: UArray Int Int -> ST s (STree s)\nbuild l = do\n let n = snd (bounds l)\n\n a <- newArray_ (1, 2*n-1)\n forM_ [n..2*n-1] $ \\i -> writeArray a i (bit (l!(i-n+1)))\n\n forM_ [n-1,n-2..1] $ \\i ->\n liftM2 (.|.) (readArray a $ 2*i) (readArray a $ 2*i+1) >>= writeArray a i\n\n b <- newArray (1, 2*n-1) 0\n\n return (a, b)\n\nsize :: (STree s) -> ST s Int\nsize t@(a, _) = do\n (_, l) <- getBounds a\n return $ l`div`2 + 1\n\npushDown :: (STree s) -> Int -> ST s ()\npushDown t@(a, b) i0 = push $ m-2\n where\n m = until (\\s -> i0 `shiftR` s == 1) (+1) 0\n\n push (-2) = return ()\n push (-1) = return ()\n push s = do\n let i = i0 `shiftR` s\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then do\n let\n vv = bit $ fromIntegral v\n ii = i `xor` 1\n writeArray a i vv >> writeArray a ii vv\n -- writeArray b i v >> writeArray b ii v\n writeArray b j 0\n else return ()\n\n push (s-1)\n\nupdate :: (STree s) -> Int -> Int -> Int -> ST s ()\nupdate t@(a, b) l r v = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n\n pushDown t l' >> pushDown t r' >>\n loop l' r' >>\n popUp l' >> popUp r'\n where\n loop l r\n | l > r = return ()\n | odd l = write l v >> loop (l+1) r\n | even r = write r v >> loop l (r-1)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n where\n write i v = writeArray a i (bit $ fromIntegral v) >> writeArray b i (fromIntegral v)\n\n popUp 1 = return ()\n popUp i = do\n let j = i `shiftR` 1\n v <- readArray b j\n if v /= 0\n then writeArray a j (bit $ fromIntegral v)\n else liftM2 (.|.) (readArray a i) (readArray a (i `xor` 1)) >>= writeArray a j\n popUp $ i `shiftR` 1\n\nquery :: (STree s) -> Int -> Int -> ST s Int64\nquery t@(a, b) l r = do\n n <- size t\n let (l', r') = (l+n-1, r+n-1)\n pushDown t l' >> pushDown t r' >> loop l' r'\n where\n loop l r\n | l > r = return 0\n | odd l = liftM2 (.|.) (readArray a l) (loop (l+1) r)\n | even r = liftM2 (.|.) (loop l (r-1)) (readArray a r)\n | otherwise = loop (l `shiftR` 1) (r `shiftR` 1)\n\nreadInts = unfoldr (B.readInt . B.dropWhile isSpace)\n\ntakeTwo [] rs = rs\ntakeTwo (u:v:xs) rs = takeTwo xs ((u, v):rs)\n\nmain = do\n c <- readInts <$> B.getContents\n\n let\n (n:m:r1) = c\n (cs, r2) = splitAt n r1\n (p1, r3) = splitAt (2*n-2) r2\n es = takeTwo p1 []\n qs = r3\n\n let\n p :: (UArray Int Int, UArray Int Int)\n p@(ins, outs) = runST $ do\n ins <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n outs <- newArray_ (1, n) :: ST s (STUArray s Int Int)\n cr <- newSTRef 0\n\n let\n dfs w u = do\n modifySTRef cr (+1)\n readSTRef cr >>= \\c -> writeArray ins u c\n mapM_ (dfs u) vs\n readSTRef cr >>= \\c -> writeArray outs u c\n where\n vs = filter (/= w) $ g!u\n\n dfs 0 1\n\n liftM2 (,) (freeze ins) (freeze outs)\n where\n g = accumArray (flip (:)) [] (1, n) $ es ++ map swap es :: Array Int [Int]\n\n range v = (ins!v, outs!v)\n\n cs' = array (1, n) $ map swap $ zip cs (elems ins) :: UArray Int Int\n\n solve = runST $ do\n t <- build cs' :: ST s ((STUArray s Int Int64), (STUArray s Int Int8))\n\n let\n f [] = return []\n\n f (1:v:c:qs) = update t l r c >> f qs where (l, r) = range v\n\n f (2:v:qs) = (popCount <$> query t l r) >>= \\r -> (r:) <$> f qs where (l, r) = range v\n\n f qs\n\n -- putStrLn $ unlines $ map show $ filter (/= 0) solve\n let rs = filter (/= 0) solve\n\n let unwords_ = mconcat . map (<> charUtf8 '\\n')\n hPutBuilder stdout $ unwords_ $ map intDec rs\n"}], "src_uid": "5000fe8464139a4235ab6e51e5240e43"} {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: (Int, Int) -> (Int, Int) -> Ordering\nsolve (x1, p1) (x2, p2) | p1 /= 0 && p2 /= 0 = let p = min p1 p2 in solve (x1, p1 - p) (x2, p2 - p)\nsolve (x1, p1) (x2, p2) | p2 > 8 = LT\nsolve (x1, p1) (x2, p2) | p1 > 8 = GT\nsolve (x1, p1) (x2, p2) = solve' xx1 xx2\n where\n xx1 = show x1 ++ replicate p1 '0'\n xx2 = show x2 ++ replicate p2 '0'\n \n solve' :: String -> String -> Ordering\n solve' s1 s2 | L.length s1 < L.length s2 = solve' (\"0\" ++ s1) s2\n solve' s1 s2 | L.length s1 > L.length s2 = solve' s1 (\"0\" ++ s2)\n solve' s1 s2 = compare s1 s2\n \n\n\nmain :: IO ()\nmain = do\n n <- B8.getLine <&> readIntB8\n replicateM_ n $ do\n [x1, p1] <- B8.getLine <&> readIntB8s\n [x2, p2] <- B8.getLine <&> readIntB8s\n\n let answer = solve (x1, p1) (x2, p2)\n case answer of\n LT -> putStrLn \"<\"\n GT -> putStrLn \">\"\n EQ -> putStrLn \"=\"\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[x1, p1] <- getInts 2\n ~[x2, p2] <- getInts 2\n let\n scale = min p1 p2\n s1 = min 7 $ p1 - scale\n s2 = min 7 $ p2 - scale\n y1 = x1 `quot` 10 ^ s2\n y2 = x2 `quot` 10 ^ s1\n z1 = toInteger x1 * 10 ^ s1\n z2 = toInteger x2 * 10 ^ s2\n ans = compare y1 y2 <> compare z1 z2\n pure $ string7 $ case ans of\n LT -> \"<\\n\"\n EQ -> \"=\\n\"\n GT -> \">\\n\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ngetInput :: IO (C.ByteString, Int)\ngetInput = do\n [x, p] <- fmap C.words C.getLine\n return $ (C.reverse $ C.dropWhile (=='0') $ C.reverse x, C.length x + parseInt p)\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n (s1, n1) <- getInput\n (s2, n2) <- getInput\n let result = case compare n1 n2 of\n EQ -> compare s1 s2\n other -> other\n toChar LT = '<'\n toChar GT = '>'\n toChar _ = '='\n return $ charUtf8 (toChar result) <> charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [], "src_uid": "a4eeaf7252b9115b67b9eca5f2bf621d"} {"source_code": "import Data.Char\nimport System.IO\n\nsplit :: String -> Char -> [String]\nsplit [] _ = []\nsplit (x:xs) c| x==c = split xs c\n | otherwise = first (x:xs) c: split (rest (x:xs) c) c where\n first [] c = []\n first (x:xs) c| x==c = []\n | otherwise = x : first xs c\n rest [] c = []\n rest (x:xs) c | x==c = xs\n | otherwise = rest xs c\n \n\nstrToIntList :: String -> [Integer]\nstrToIntList xs = map toInt (split xs ' ')\n\ntoInt :: String -> Integer\ntoInt [] = 0\ntoInt (x:xs) = toInteger (digitToInt x) * 10^(length xs) + toInt xs\n\nsolve :: [Integer] -> Integer\nsolve xs = div (sum xs) 2\n\nsolveN :: Integer -> Handle -> IO ()\nsolveN 0 h = return ()\nsolveN n h = do\n abc <- hGetLine h\n (putStrLn . show . solve . strToIntList) abc\n solveN (n-1) h\n\nmain :: IO ()\nmain = do\n -- h <- openFile \"A.in\" ReadMode\n n <- hGetLine stdin\n solveN (toInt n) stdin\n -- hClose h\n return()\n", "positive_code": [{"source_code": "--ghc 7.10\n\ndistribute :: (Integral a) => a -> [a] -> a\ndistribute n xs = (sum xs) `div` n\n\nmain = do\n qStr <- getLine\n contents <- getContents\n let xss = map (map read . words) . lines $ contents :: [[Integer]]\n let ds = map (distribute 2) xss\n sequence (map print ds)"}, {"source_code": "import Control.Monad\nimport Data.List\n\nbestSplit :: [Integer] -> Integer\nbestSplit xs =\n let sorted = sort xs\n startA = sorted !! 0\n startB = sorted !! 1\n commonPile = sorted !! 2\n takeA = min commonPile (startB - startA)\n toSplit = commonPile - takeA\n finalA = startA + takeA + (toSplit `div` 2)\n finalB = startB + (commonPile - takeA) + (toSplit `div` 2)\n in min finalA finalB\n\nreadNums :: (Num a, Read a) => IO [a]\nreadNums = map read . words <$> getLine\n\nsolve :: IO Integer\nsolve = do\n piles <- readNums :: IO [Integer]\n return (bestSplit piles)\n\nmain = do\n [tests] <- readNums :: IO [Int]\n results <- replicateM tests $ solve\n putStrLn . unlines . map show $ results\n"}, {"source_code": "import Control.Monad\n\nsolve_case a b c = (a + b + c) `div` 2\n\nsolve [] = []\nsolve ([a, b, c]:xs) = (solve_case a b c : solve xs)\n\nread_input = do\n q <- getLine\n strings <- replicateM (read q) getLine\n return $ map get_ints $ map words $ strings\n where get_ints = map read\n\nmain = do\n q <- read_input\n mapM print (solve q)"}, {"source_code": "cal :: Int -> IO ()\ncal 0 = return ()\ncal n = do\n line <- getLine\n let (a:b:c:[]) = map (read :: String -> Integer) $ words line\n putStrLn $ show $ (a + b + c) `div` 2\n cal (n - 1)\n\nmain :: IO ()\nmain = do\n n <- getLine\n cal $ read n"}, {"source_code": "main = interact $ unlines\n . map ( show\n . (`div` 2)\n . sum\n . map (read :: String -> Integer)\n . words )\n . tail\n . lines\n"}, {"source_code": "import Control.Monad (replicateM_)\n\nfindAliceCandies :: [Integer] -> Integer\nfindAliceCandies xs = sum xs `div` 2\n\nreadCandies :: IO [Integer]\nreadCandies = (map read) . words <$> getLine\n\nmain =\n read <$> getLine >>= \\q -> \n replicateM_ q (readCandies >>= print . findAliceCandies)"}, {"source_code": "import Data.Int\nmain = interact $ unlines . map (show . solve) . triplets . map read . tail . words\ntriplets (a:b:c:xs) = (a,b,c) : triplets xs\ntriplets [] = []\nsolve (a,b,c) = (a+b+c) `div` 2 :: Int64\n"}, {"source_code": "import Control.Monad\nimport Data.Typeable\nimport Data.Int\nimport Data.List\n\nsolve [a,b,c] = minimum [a+c, b+c, (a+b+c) `quot` 2]\n\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine :: IO [String]\n let int_inputs = map (solve . sort . map read . words) inputs :: [Int64]\n\n mapM print int_inputs\n --print $ int_inputs\n"}, {"source_code": "main = interact $ unlines . map show . map ((`div` 2) . sum . map read . words) . tail . lines\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nonecase=do\n\t\tc<-sum <$> map read <$> words <$>getLine ::IO Integer\n\t\tprint $ div c 2\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Typeable\n\nsolve [a,b,c] = minimum [a+c, b+c, (a+b+c) `quot` 2]\n\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine :: IO [String]\n let int_inputs = map (solve . map read . words) inputs :: [Int]\n\n mapM print int_inputs\n --print $ int_inputs\n"}, {"source_code": "import Control.Monad\nimport Data.Typeable\nimport Data.Int\n\nsolve [a,b,c] = minimum [a+c, b+c, (a+b+c) `quot` 2]\n\nmain = do\n n <- fmap read getLine :: IO Int\n inputs <- replicateM n getLine :: IO [String]\n let int_inputs = map (solve . map read . words) inputs :: [Int64]\n\n mapM print int_inputs\n --print $ int_inputs\n"}, {"source_code": "import Data.Char\nimport System.IO\n\nsplit :: String -> Char -> [String]\nsplit [] _ = []\nsplit (x:xs) c| x==c = split xs c\n | otherwise = first (x:xs) c: split (rest (x:xs) c) c where\n first [] c = []\n first (x:xs) c| x==c = []\n | otherwise = x : first xs c\n rest [] c = []\n rest (x:xs) c | x==c = xs\n | otherwise = rest xs c\n \n\nstrToIntList :: String -> [Int]\nstrToIntList xs = map toInt (split xs ' ')\n\ntoInt :: String -> Int\ntoInt [] = 0\ntoInt (x:xs) = (digitToInt x) * 10^(length xs) + toInt xs\n\nsolve :: [Int] -> Int\nsolve xs = div (sum xs) 2\n\nsolveN :: Int -> Handle -> IO ()\nsolveN 0 h = return ()\nsolveN n h = do\n abc <- hGetLine h\n (putStrLn . show . solve . strToIntList) abc\n solveN (n-1) h\n\nmain :: IO ()\nmain = do\n -- h <- openFile \"A.in\" ReadMode\n n <- hGetLine stdin\n solveN (toInt n) stdin\n -- hClose h\n return()\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nonecase=do\n\t\tc<-sum <$> map read <$> words <$>getLine ::IO Int\n\t\tprint $ div c 2\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "src_uid": "d9e4a9a32d60e75f3cf959ef7f894fc6"} {"source_code": "import Data.List (scanl')\nimport Control.Monad\n\nmain :: IO()\nmain = do\n t <- readLn \n replicateM_ t solve\n\nsolve :: IO()\nsolve = do\n s <- getLine\n -- Cumulative count of 0s and 1s\n -- Example: scanl' (count '0') 0 \"00110101\"\n -- => [0,1,2,2,2,3,3,4,4]\n -- 0 0 1 1 0 1 0 1\n -- scanl' (count '1') 0 \"00110101\"\n -- => [0,0,0,1,2,2,3,3,4]\n -- 0 0 1 1 0 1 0 1\n let zeros = scanl' (count '0') 0 s\n let ones = scanl' (count '1') 0 s\n\n print (minOps zeros ones)\n\n-- Cumulative counter\ncount :: Char -> Int -> Char -> Int\ncount c x y = if y == c then x else x+1\n\n-- Solve problem with cumulative counters\n-- Get the minimum number of operations needed\n--\n-- Covers all four possibilities:\n-- 1) All 0s (00..00) (Typically given as such)\n-- 2) All 1s (11..11) (Typically given as such)\n-- 3) 0s followed by 1s (00..01..11)\n-- 4) 1s followed by 0s (11..10..00)\n--\n-- Example: using \"00110101\"\n-- numSwitch [0,1,2,2,2,3,3,4,4] [0,0,0,1,2,2,3,3,4]\n-- zeros ones \n--\n-- Covering cases 2 and 3:\n-- (Cost of switching all zeros to ones -\n-- best cost reduction when keeping zeros up to a point)\n-- (last zeros - maximum (zipWith (-) zeros ones))\n-- (( 4 ) - maximum ( [0,1,2,1,0,1,0,1,0] )\n-- ( 4 - 2 = 2 )\n--\n-- Covering cases 1 and 4:\n-- (Cost of switching all ones to zeros -\n-- best cost reduction when keeping ones up to a point)\n-- (last ones - maximum (zipWith (-) ones zeros) )\n-- (( 4 ) - maximum ([0,-1,-2,-1,0,-1,0,-1,0])\n-- ( 4 - 0 = 4 )\n--\n-- solve zeros ones = min 2 4 = 2\n-- solution (2) => \"00110101\" -> \"00111111\"\n-- ^ ^\nminOps :: [Int] -> [Int] -> Int\nminOps zeros ones = do\n min (last zeros - maximum (zipWith (-) zeros ones)) $\n (last ones - maximum (zipWith (-) ones zeros))\n", "positive_code": [{"source_code": "import Data.Array\nimport Data.Foldable\nimport Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n print $ solve s\n\nsolve :: String -> Int\nsolve s = min (minimum $ zipWith (+) (tl zeroprefix) (tl onesuffix)) (minimum $ zipWith (+) (tl oneprefix) (tl zerosuffix))\n where\n tl = toList\n arr = listArray (1,length s) s\n zeroprefix = array (0,length s) ((0,0):[ (i,(if arr!i == '0' then (+1) else id) $ zeroprefix!(i-1)) | i <- [1..(length s)]])\n oneprefix = array (0,length s) ((0,0):[ (i,(if arr!i == '1' then (+1) else id) $ oneprefix!(i-1)) | i <- [1..(length s)]])\n zerosuffix = array (0,length s) ((length s, 0):[ (i,(if arr!(i+1) == '0' then (+1) else id) $ zerosuffix!(i+1)) | i <- [0..(length s - 1)]])\n onesuffix = array (0,length s) ((length s, 0):[ (i,(if arr!(i+1) == '1' then (+1) else id) $ onesuffix!(i+1)) | i <- [0..(length s - 1)]])\n"}, {"source_code": "main :: IO()\nmain = do\n t <- readLn \n routine t\n\nroutine :: Int -> IO()\nroutine t\n | t > 1 = do\n solve\n routine (t-1)\n | t == 1 = solve\n\nsolve :: IO()\nsolve = do\n s <- getLine\n let zeros = countZeros s\n let ones = countOnes s\n print (min (min (oneZero s 0 ones) (zeroOne s 0 zeros)) (min ones zeros))\n\noneZero :: [Char] -> Int -> Int -> Int\noneZero s toOne toZero\n | (length s) > 1 = do\n min (toOne + toZero) (oneZero (drop 1 s) (toOne+(if (s !! 0 == '0') then 1 else 0)) (toZero-(if (s !! 0 == '1') then 1 else 0)))\n | (length s) == 1 = toOne + toZero\n\nzeroOne :: [Char] -> Int -> Int -> Int\nzeroOne s toZero toOne\n | (length s) > 1 = do\n min (toZero + toOne) (zeroOne (drop 1 s) (toZero+(if (s !! 0 == '1') then 1 else 0)) (toOne-(if (s !! 0 == '0') then 1 else 0)))\n | (length s) == 1 = toZero + toOne\n\ncountOnes :: [Char] -> Int\ncountOnes s = do\n length (filter (=='1') s)\n\ncountZeros :: [Char] -> Int\ncountZeros s = do\n length (filter (=='0') s)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n_prefsums acc [] = reverse acc\n_prefsums acc@(curr:_) (x:xs) =\n let !x' = x + curr\n in _prefsums (x':acc) xs\nprefsums = _prefsums [0]\n\nmain = do\n input <- getContents\n let _:tokens = split input\n res = solve <$> tokens\n where solve = (\\str ->\n let ones = read <$> (:[]) <$> str :: [Int]\n onesR = reverse ones\n zeros = (1 -) <$> ones\n zerosR = reverse zeros\n prefs1 : prefs1R : prefs0 : prefs0R : _ = prefsums <$> [ones, onesR, zeros, zerosR]\n sufs1 : sufs0 : _ = reverse <$> [prefs1R, prefs0R]\n cost10 = uncurry (+) <$> zip prefs0 sufs1\n cost01 = uncurry (+) <$> zip prefs1 sufs0\n in foldl1 min (cost10 ++ cost01)\n )\n sequence_ (putStrLn . show <$> res)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n \nimport Data.List (scanl')\nimport Data.Foldable (for_)\n \ncosts :: Char -> String -> [Int]\ncosts c = scanl' (\\x y -> if y == c then x else x+1) 0\n \nsolve :: String -> Int\nsolve str = min (last c0 - maximum (zipWith (-) c0 c1)) $\n (last c1 - maximum (zipWith (-) c1 c0)) where\n c0 = costs '0' str\n c1 = costs '1' str\n \nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n for_ [1..t] $ \\_ -> getLine >>= (print . solve)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List (scanl')\nimport Data.Foldable (for_)\n\ncosts :: Char -> String -> [Int]\ncosts c = scanl' (\\x y -> if y == c then x else x+1) 0\n\nsolve :: String -> Int\nsolve str = min (last c0 - maximum (zipWith (-) c0 c1)) $\n (last c1 - maximum (zipWith (-) c1 c0)) where\n c0 = costs '0' str\n c1 = costs '1' str\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n for_ [1..t] $ \\_ -> getLine >>= (print . solve)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Foldable (for_)\n\nsolve :: String -> Int\nsolve [] = 0\nsolve (c:cs) = go 0 c cs where\n go !n !c1 [] = n\n go !n !c1 [c2] = n\n go !n !c1 (c2:c3:cs)\n | c1 == c2 || c2 == c3 = go n c2 (c3:cs)\n | otherwise = go (n+1) c3 cs\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n for_ [1..t] $ \\_ -> getLine >>= (print . solve)\n"}], "src_uid": "803e5ccae683b91a4cc486fbc558b330"} {"source_code": "import Data.List\nimport Control.Monad\ncombinations k ns = filter ((k==).length) (subsequences ns)\nsolution::[String]->[(String,String)]->Int->[String]\nsolution ns cs 1 = [ns !! 0]\nsolution ns cs n | or $ map isClique combs = (filter isClique combs) !! 0 \n | otherwise = solution ns cs (n-1)\n where combs = combinations n ns\n isClique q = all (flip notElem cs) [(a,b) | a<- q, b <-q]\nprintsol xs = (putStrLn $ show.length $ xs) >> (forM_ xs (\\x -> putStrLn x))\nmain = do\n [n,m] <- getLine >>= return.(map read).words\n team <- forM [1..n] (\\_ -> getLine)\n collisions <-fmap concat $ forM [1..m] (\\_ -> do\n [n1,n2] <- getLine >>= return . words\n return [(n1,n2), (n2,n1)]) \n printsol $ sort $ solution team collisions n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Bits\nimport Data.List\nimport qualified Data.Map as Map\n\nbitCount 0 = 0\nbitCount n = ( n .&. 1 ) + bitCount ( n `shiftR` 1 )\n\nchooseToNames 0 _ = []\nchooseToNames n (name:names) =\n let others = chooseToNames (n `shiftR` 1) names in\n if n .&. 1 == 0\n then others\n else name : others\n\nmain = do\n [n, m] <- ( map read . words ) `liftM` getLine\n volunteers <- replicateM n getLine\n\n let volunteerIndexMap = Map.fromList (zip volunteers [0..])\n\n constraints <- replicateM m $ do\n [a, b] <- ( map ( bit . ( volunteerIndexMap Map.! ) ) . words ) `liftM` getLine\n return ( a .|. b )\n\n let candidates :: [Int]\n candidates = filter (\\t ->\n all (\\c -> t .&. c /= c) constraints\n ) [1..( 1 `shift` n )]\n (choose, chooseLen) = foldl' (\\(best, bestLen) c ->\n let currLen = bitCount c in\n if currLen > bestLen\n then (c, currLen)\n else (best, bestLen)\n ) (0,0) candidates\n chooseName = sort $ chooseToNames choose volunteers\n\n --putStrLn $ show constraints\n --putStrLn $ show candidates\n --putStrLn $ show choose\n putStrLn $ show chooseLen\n putStr $ unlines chooseName\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List\nimport Data.Array\nimport Data.Maybe\nimport IO\nimport Debug.Trace\n\nmytrace x = traceShow x x\n\npowSet :: [a] -> [[a]]\npowSet [] = [[]]\npowSet (x:xs) = concat [[x:y, y] | y <- powSet xs]\n\nok :: [(Int, Int)] -> Int -> Int -> Bool\nok x y z = d!(y,z)\n\twhere\n\t\tok' (i,j) = (elemIndex (i,j) x == Nothing) && (elemIndex (j,i) x == Nothing)\n\t\td = array ((1,1),(16,16)) [((i,j), ok' (i,j)) | i <- [1..16], j <- [1..16]]\n\n-- nameToId :: [C.ByteString] -> C.ByteString -> Int\nnameToId a s = (fromJust . elemIndex s) a + 1\n\n-- idToName :: [C.ByteString] -> Int -> C.ByteString\nidToName a i = a !! (i - 1)\n\nord :: [a] -> [a] -> Ordering\nord x y\n\t| length x < length y = LT\n\t| length x > length y = GT\n\t| otherwise = EQ\n\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetLines2 0 = return []\ngetLines2 n = do\n\tx <- getLine >>= return . words\n\txs <- getLines2 (n-1)\n\treturn (x:xs)\n\nmain = do\n\t-- stream <- fmap C.lines $ C.hGetContents stdin\n\t-- let [n, m] = mytrace $ (map (fst . fromJust . C.readInt) . C.words . head) stream\n\t-- let names = mytrace $ (take n . tail) stream \n\t-- let bad_pairs = mytrace $ (map ((\\x -> (head x, last x)) . map (nameToId names) . C.words) . take m . drop (n+1)) stream\n\t[n, m] <- getLine >>= return . map read . words :: IO [Int]\n\tnames <- getLines n\n\tbad_pairs <- getLines2 m >>= return . map ((\\x -> (head x, last x)) . map (nameToId names))\n\tlet ans = (last . sortBy ord) [ c | c <- powSet [1..n], all (\\(a, b) -> ok bad_pairs a b) [(a, b) | a <- c, b <- c]]\t\n\tputStr $ (show . length) ans ++ \"\\n\" ++ (unlines . sort . map (idToName names)) ans\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Data.Maybe\n\npowSet :: [a] -> [[a]]\npowSet [] = [[]]\npowSet (x:xs) = concat [[x:y, y] | y <- powSet xs]\n\nok :: [(Int, Int)] -> Int -> Int -> Bool\nok x y z = d!(y,z)\n\twhere\n\t\tok' (i,j) = (elemIndex (i,j) x == Nothing) && (elemIndex (j,i) x == Nothing)\n\t\td = array ((1,1),(16,16)) [((i,j), ok' (i,j)) | i <- [1..16], j <- [1..16]]\n\nnameToId :: [String] -> String -> Int\nnameToId a s = (fromJust . elemIndex s) a + 1\n\nidToName :: [String] -> Int -> String\nidToName a i = a !! (i - 1)\n\nord :: [a] -> [a] -> Ordering\nord x y\n\t| length x < length y = LT\n\t| length x > length y = GT\n\t| otherwise = EQ\n\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\ngetLines2 0 = return []\ngetLines2 n = do\n\tx <- getLine >>= return . words\n\txs <- getLines2 (n-1)\n\treturn (x:xs)\n\nmain = do\n\t[n, m] <- getLine >>= return . map read . words :: IO [Int]\n\tnames <- getLines n\n\tbad_pairs <- getLines2 m >>= return . map ((\\x -> (head x, last x)) . map (nameToId names))\n\tlet ans = (last . sortBy ord) [ c | c <- powSet [1..n], all (\\(a, b) -> ok bad_pairs a b) [(a, b) | a <- c, b <- c]]\t\n\tputStr $ (show . length) ans ++ \"\\n\" ++ (unlines . sort . map (idToName names)) ans\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Array\nimport Data.Char\nimport Data.Map\n\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = (\\(x:y:_) -> (scan' x,scan' y)) (words x)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\nscanlist :: (Scan a) => IO [a]\nscanlist = getLine>>=return.(Data.List.map scan').words\nscanlists :: (Scan a) => Int -> IO [[a]]\nscanlists n = if n==0 then return [] else scanlist>>=(\\x->scanlists (n-1)>>=return.(x:))\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn = putStrLn.showans\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns = mapM_ putAnsLn\n\nrec _ [] l = (length l,l)\nrec antis (x:xs) l = let (a1,team1) = rec antis xs l in\n let diff' = (Data.Map.lookup x antis) in\n let diff = case diff' of\n Nothing -> []\n Just l -> l\n in\n let (a2,team2) = rec antis (xs Data.List.\\\\ diff) (x:l) in\n if a1>a2 then\n (a1,team1)\n else\n (a2,team2)\n\nsolve members n anti = let antis = foldl (\\mp -> \\(na,an) -> insertWith (++) an [na] (insertWith (++) na [an] mp)) empty anti in\n let (ans,team) = rec antis members [] in\n if ans==0 then\n [\"0\"]\n else\n (show ans):(sort team)\n \n\nmain = do (n,m) <- scan :: IO (Int,Int)\n members <- scans n :: IO [String]\n anti <- scans m :: IO [(String,String)]\n putAnsLns (solve members n anti)"}, {"source_code": "import Data.List\nimport Debug.Trace (trace)\nimport GHC.Exts(sortWith)\n\nmain3 = print $ getResult [1,2,3] [(1,2)]\nmains = print $ getResult [1,2,3] []\nmain = \n\tdo\n\t\t[n,m] <- getNums\n\t\tl <- getLines n \n\t\tlines <- getLines m\n\t\tlet n = lines |> map (\\x -> \n\t\t\tlet [a,b] = (splitBy x)\n\t\t\tin (a,b))\n\t\tlet r = getResult (l) n |> sort\n\t\tputStrLn $ (show (length r)) ++ \"\\n\" ++ (intercalate \"\\n\" r) \n\ngetResult l n = result\n\twhere\n\t\tresult = subsequences l |> sortWith (\\x -> length x) |> reverse |> \n\t\t\tfilter (\\x -> n |> all (\\(y,z) -> (notElem y x) || (notElem z x))) |> head\n------------------usefule-----------------------\ntr x y = trace ((show x) ++ (show y)) y\ntr1 x y = trace ((show x)) y\ntr2 y = trace ((show y)) y\n\n(|>) x f = f x\n\nparseInt x = (read x) :: Int\n\ngetLines n = repeat getLine |> take n |> sequence \n\ngetNums =\n\tdo\n\t\tline <- getLine\n\t\treturn $ getNumbers line\n\ngetNumbers line = \n\tcase index of \n\t\tNothing -> [parseInt line]\n\t\tJust i ->\n\t\t\tlet (l,r) = splitAt (i + 1) line in\n\t\t\t\t(parseInt l) : (getNumbers r)\n\twhere\n\t\tindex = elemIndex ' ' line\n\nsplitBy k = \n\tcase index of \n\t\tNothing -> [k]\n\t\tJust i ->\n\t\t\tlet (l,r) = splitAt (i) k in\n\t\t\t\tl : splitBy (drop 1 r)\n\twhere\n\t\tindex = elemIndex ' ' k\n"}], "negative_code": [], "src_uid": "b0301a2d79a1ec126511ed769ec0b743"} {"source_code": "import Data.Either\n\nmain=readFile\"input.txt\">>=writeFile\"output.txt\".parseOutput.solve.map f.zip[1..].(!!1).lines\nf(i,'L')=Left i\nf(i,'R')=Right i\n\nparseOutput (l:r:lrs) = shows l\" \"++shows r\"\\n\"++parseOutput lrs\nparseOutput _ = []\n\nsolve lrs = merge (lefts lrs) (rights lrs)\n\nmerge [l] [r1,r2,r3]\n | l < r1 = [l,r2,r1,r3]\n | l < r2 = [l,r3,r1,r2]\n | l < r3 = [l,r1,r2,r3]\n | otherwise = [l,r2,r1,r3]\n\nmerge [l1,l2,l3] [r]\n | r < l1 = [l2,r,l1,l3]\n | r < l2 = [l3,r,l1,l2] \n | r < l3 = [l1,r,l2,l3]\n | otherwise = [l2,r,l1,l3]\n\nmerge [l1,l2] [r1,r2]\n | l2 < r1 || r2 < l1 = [l1,r1,l2,r2]\n | r2-r1==1 || l2-l1==1 = [l1,r2,l2,r1]\n | otherwise = [l1,l2,r1,r2]\n\nmerge [l1,l2,l3,l4] [] = [l1,l3,l2,l4]\n\nmerge [] [r1,r2,r3,r4] = [r1,r3,r2,r4]\n\nmerge (l1:l2:ls) (r1:r2:rs)\n | l2 < r1 || r2 < l1 = l1:r1: merge (l2:ls) (r2:rs)\n | r2-r1==1 || l2-l1==1 = l1:r2: merge (l2:ls) (r1:rs)\n | otherwise = r1:r2: merge (l1:l2:ls) rs\n\nmerge [l] (r1:r2:r3:rs) = r1:r3:merge [l] (r2:rs)\nmerge (l1:l2:l3:ls) [r] = l1:l3:merge (l2:ls) [r]\nmerge [] (r1:r2:r3:r4:rs) = r1:r3:merge [] (r2:r4:rs)\nmerge (l1:l2:l3:l4:ls) [] = l1:l3:merge (l2:l4:ls) []", "positive_code": [{"source_code": "\nsolve n orient = map swapInter $ zip left right\n where left = [1 .. halfN]\n right = [halfN + 1 .. n]\n halfN = n `div` 2\n swapInter (x, y)\n | l == 'R' && r == 'L' = (y, x)\n | otherwise = (x, y)\n where l = orient !! (x - 1)\n r = orient !! (y - 1)\n\nshowPair (x, y) = show x ++ \" \" ++ show y\n\nmain = do [n, orient] <- fmap words $ readFile \"input.txt\"\n writeFile \"output.txt\" $ unlines $ map showPair $ solve (read n) orient"}, {"source_code": "\nimport Array\nimport Monad\nimport IO\n\nsolve :: Int -> Array Int Char -> [(Int, Int)]\nsolve n xs = [f i | i <- [1..div n 2]]\n where\n f i\n | xs ! i == 'R' && xs ! (i + div n 2) == 'L' = (i + div n 2, i)\n | otherwise = (i, i + div n 2)\n\nprints :: Show a => Handle -> (a, a) -> IO ()\nprints hOutput (a, b) = hPutStrLn hOutput (show a ++ \" \" ++ show b)\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n n <- liftM read (hGetLine hInput)\n xs <- liftM (listArray (1,n)) (hGetLine hInput)\n mapM_ (prints hOutput) $ solve n xs\n hClose hInput\n hClose hOutput\n"}], "negative_code": [], "src_uid": "564664d9cd2ccbccb42574b3881ec5fe"} {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\n\r\nprocessCase _ = do\r\n getLine\r\n s <- getLine\r\n let r = foldl' (\\r -> (r +) . (\\b -> if b then 1 else -fromEnum (r /= 0)) . (== 'Q')) 0 s :: Int\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.Foldable\r\n\r\nprocessCase _ = do\r\n getLine\r\n s <- getLine\r\n let r = foldl' (\\r -> (r +) . (\\b -> if b then 1 else if r /= 0 then -1 else 0) . (== 'Q')) 0 s :: Int\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nprocessCase _ = do\r\n getLine\r\n s <- getLine\r\n let r = foldl (\\r -> (r +) . (\\b -> if b then 1 else if r /= 0 then -1 else 0) . (== 'Q')) 0 s :: Int\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nprocessCase _ = do\r\n getLine\r\n s <- getLine\r\n let r = foldl (\\r -> (r +) . (\\b -> if b then 1 else -fromEnum (r /= 0)) . (== 'Q')) 0 s\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nprocessCase _ = do\r\n getLine\r\n s <- getLine\r\n let r = foldl (\\r -> (r +) . (\\b -> if b then 1 else -1) . (== 'Q')) 0 s\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nprocessCase _ = do\r\n l <- readLn :: IO Int\r\n s <- getLine\r\n let r = foldl (\\r -> (r +) . (\\b -> if b then 1 else -1) . (== 'Q')) 0 s\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\n\r\nprocessCase _ = do\r\n l <- readLn :: IO Int\r\n s <- getLine\r\n let r = foldl (\\r -> fromEnum . (== 'Q')) 0 s\r\n putStrLn $ if r > 0 then \"No\" else \"Yes\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_ [1..n] processCase\r\n"}], "src_uid": "c5389b39312ce95936eebdd83f510e40"} {"source_code": "f _ [] = 0\nf c (x:xs) = g c xs + (if c == x then 1 else 0)\n\ng _ [] = 0\ng c (x:xs) = f c xs\n\nh0 c s = (f c s) * (g c s)\nh1 c s = (f c s * (f c s + 1) + g c s * (g c s + 1)) `div` 2 \n\nmain = do\n s <- getLine\n putStrLn $ show (h0 'a' s + h0 'b' s) ++ \" \" ++ show (h1 'a' s + h1 'b' s)", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.IORef\nimport Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n\npairsum (a,b) (c,d) = (a+c, b+d)\n\nsolve :: String -> Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> (Int64, Int64)\nsolve [] _ _ _ _ _ = (0, 0)\nsolve (s:str) aEven aOdd bEven bOdd cpos\n | s == 'a' = pairsum resA (solve str aEven1 aOdd1 bEven1 bOdd1 (1 - cpos))\n | s == 'b' = pairsum resB (solve str aEven1 aOdd1 bEven1 bOdd1 (1 - cpos))\n where resA\n | cpos == 0 = (aOdd1, aEven1)\n | cpos == 1 = (aEven1, aOdd1)\n resB\n | cpos == 0 = (bOdd1, bEven1)\n | cpos == 1 = (bEven1, bOdd1)\n aEven1 = if s == 'a' && cpos == 0 then aEven + 1 else aEven\n aOdd1 = if s == 'a' && cpos == 1 then aOdd + 1 else aOdd\n bEven1 = if s == 'b' && cpos == 0 then bEven + 1 else bEven\n bOdd1 = if s == 'b' && cpos == 1 then bOdd + 1 else bOdd\n\n\n\nmain = do\n str <- getLine\n let res = solve str 0 0 0 0 0\n putStr (show (fst res))\n putStrLn $ \" \" ++ (show (snd res))\n"}], "negative_code": [], "src_uid": "4ebbda2fc1a260e9827205a25addd9c4"} {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -funbox-strict-fields -O3 #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if checkAns cs then cs else []\n-- solveEven n as = if check b1s b2s && checkAns cs then cs else []\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\n\ncheckAns :: [Int] -> Bool\ncheckAns (a1:a2:a3:as) = (a1-a2)*(a3-a2) > 0 && checkAns (a2:a3:as)\ncheckAns _ = True\n\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (and .) . zipWith (/=)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n ", "positive_code": [{"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if checkAns cs then cs else []\n-- solveEven n as = if check b1s b2s && checkAns cs then cs else []\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\n\ncheckAns :: [Int] -> Bool\ncheckAns (a1:a2:a3:as) = (a1-a2)*(a3-a2) > 0 && checkAns (a2:a3:as)\ncheckAns _ = True\n\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (and .) . zipWith (/=)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if checkAns cs then cs else []\n-- solveEven n as = if check b1s b2s && checkAns cs then cs else []\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\n\ncheckAns :: [Int] -> Bool\ncheckAns (a1:a2:a3:as) = (a1-a2)*(a3-a2) > 0 && checkAns (a2:a3:as)\ncheckAns _ = True\n\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (and .) . zipWith (/=)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if checkAns cs then cs else []\n-- solveEven n as = if check b1s b2s && checkAns cs then cs else []\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\n\ncheckAns :: [Int] -> Bool\ncheckAns (a1:a2:a3:as) = (a1-a2)*(a3-a2) > 0 && checkAns (a2:a3:as)\ncheckAns _ = True\n\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (and .) . zipWith (/=)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s && checkAns cs then cs else []\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\n\ncheckAns :: [Int] -> Bool\ncheckAns (a1:a2:a3:as) = (a1-a2)*(a3-a2) > 0 && checkAns (a2:a3:as)\ncheckAns _ = True\n\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (and .) . zipWith (/=)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}], "negative_code": [{"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\nimport Data.Int (Int32)\n\nreadInt :: B8.ByteString -> Int32\nreadInt = fromIntegral . fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int32]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int32\n as <- readInts <$> B8.getLine :: IO [Int32]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int32] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int32 -> [Int32] -> [Int32]\nsolveEven n as = if checkAns cs then cs else []\n-- solveEven n as = if check b1s b2s && checkAns cs then cs else []\n where\n m = fromIntegral n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\n\ncheckAns :: [Int32] -> Bool\ncheckAns (a1:a2:a3:as) = (a1-a2)*(a3-a2) > 0 && checkAns (a2:a3:as)\ncheckAns _ = True\n\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (and .) . zipWith (/=)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if True then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s then [] else cs\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck as bs = or $ zipWith (==) as bs\n\n-- check :: [Int] -> [Int] -> Bool\n-- check = (or .) . zipWith (==)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\n-- output [] = noLit\noutput [] = B8.unwords $ yesLit : map (B8.pack . show) [1,2]\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s then [] else cs\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck as bs = or $ zipWith (==) as bs\n\n-- check :: [Int] -> [Int] -> Bool\n-- check = (or .) . zipWith (==)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = yesLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s then [] else cs\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck as bs = or $ zipWith (==) as bs\n\n-- check :: [Int] -> [Int] -> Bool\n-- check = (or .) . zipWith (==)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords $ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s then [] else cs\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck as bs = or $ zipWith (==) as bs\n\n-- check :: [Int] -> [Int] -> Bool\n-- check = (or .) . zipWith (==)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\nimport System.IO (hSetBuffering, stdout, BufferMode (NoBuffering))\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n B8.putStrLn . output $ if even n then solveEven n as else []\n\nnoLit :: B8.ByteString\nyesLit :: B8.ByteString\nnoLit = B8.pack \"NO\"\nyesLit = B8.pack \"YES\\n\"\n\noutput :: [Int] -> B8.ByteString\noutput [] = noLit\noutput as = B8.unwords$ yesLit : map (B8.pack . show) as\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s then [] else cs\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m bs\n cs = interleave b1s b2s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (.) or . zipWith (==)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}, {"source_code": "{-# LANGUAGE Strict #-}\n\nimport Control.Monad (replicateM_)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\n\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n as <- readInts <$> B8.getLine :: IO [Int]\n -- n <- readLn :: IO Int\n -- as <- map read . words <$> getLine :: IO [Int]\n putStrLn . output $ if even n then solveEven n as else []\n\noutput :: [Int] -> String\noutput [] = \"NO\"\noutput as = \"YES\\n\" ++ unwords (map show as)\n\nsolveEven :: Int -> [Int] -> [Int]\nsolveEven n as = if check b1s b2s then [] else cs\n where\n m = n `div` 2\n bs = sort as\n (b1s, b2s) = splitAt m as\n cs = interleave b1s b2s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck = (.) or . zipWith (==)\n\ninterleave :: [a] -> [a] -> [a]\ninterleave (a:as) (b:bs) = a : b : interleave as bs\ninterleave [] bs = bs\ninterleave as [] = as\n "}], "src_uid": "a30c5562d3df99291132fac20e05e708"} {"source_code": "import Control.Monad ( replicateM_ )\nimport Data.List ( sort )\n\nsolve :: [Int] -> String\nsolve a = let\n asor = sort a\n q = head asor\n fun x y = x == y || rem x q == 0\n in if and $ zipWith fun a asor then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n getLine >>= putStrLn . solve . map read . words\n\n\n", "positive_code": [{"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> String\nsolve xs = if error == 0 then \"YES\" else \"NO\"\n where \n sorted = sort xs\n error = length $ filter (\\(x, y) -> x /= y && mod x min_element /= 0) (zip xs sorted)\n min_element = minimum xs\n\n\ndeal :: IO()\ndeal = do \n getLine\n a <- map read . words <$> getLine\n putStrLn $ solve a\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport qualified Data.Array.ST.Safe as S\nimport qualified Data.Array.Unboxed as U\nimport Data.Foldable\nimport Data.List\n\ntestCase :: IO a -> IO ()\ntestCase f = do\n t <- read <$> getLine\n replicateM_ t f\n\nmain = testCase $ do\n _ <- getLine\n v <- map read . words <$> getLine\n let m = minimum v\n let t = sort v\n if t == v || (foldl (\\flag (a, b) -> flag && (a == b || b `mod` m == 0)) True $ zip t v)\n then putStrLn \"Yes\"\n else putStrLn \"No\""}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nreadWords :: Read a => IO [a]\nreadWords =\n fmap read . words <$> getLine\n\nisSorted :: Ord a => [a] -> Bool\nisSorted xs =\n GT `notElem` zipWith compare xs (tail xs)\n\ntaskSort :: [Int] -> [Int]\ntaskSort xs = \n let m = minimum xs\n indexed = zip [0..] xs\n isDivisable (_, x) = x `mod` m == 0\n (divisable, notDivisable) = partition isDivisable indexed\n (divIndices, divValues) = unzip divisable\n sortedDivisable = zip (sort divIndices) (sort divValues)\n -- sortedDivisable = uncurry zip . fmap sort . unzip $ divisable\n sortedAll = sort $ notDivisable ++ sortedDivisable\n (_, result) = unzip sortedAll\n in result \n\nsolve :: [Int] -> String\nsolve = asYesNo . isSorted . taskSort \n\nasYesNo :: Bool -> String\nasYesNo True = \"YES\"\nasYesNo False = \"NO\"\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n xs <- readWords\n putStrLn $ solve xs\n"}], "negative_code": [{"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: [Int] -> String\nsolve xs = if error == 0 then \"YES\" else \"NO\"\n where \n sorted = sort xs\n error = length $ filter (\\(x, y) -> x /= y && gcd x min_element == 1) (zip xs sorted)\n min_element = minimum xs\n\n\ndeal :: IO()\ndeal = do \n getLine\n a <- map read . words <$> getLine\n putStrLn $ solve a\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nreadWords :: Read a => IO [a]\nreadWords =\n fmap read . words <$> getLine\n\nisSorted :: Ord a => [a] -> Bool\nisSorted xs =\n GT `notElem` zipWith compare xs (tail xs)\n\ntaskSort :: [Int] -> [Int]\ntaskSort xs = \n let m = minimum xs\n indexed = zip [0..] xs\n isDivisable (_, x) = x `mod` m == 0\n (divisable, notDivisable) = partition isDivisable indexed\n (divIndices, divValues) = unzip divisable\n sortedDivisable = zip (sort divIndices) (sort divValues)\n -- sortedDivisable = uncurry zip . fmap sort . unzip $ divisable\n sortedAll = sort $ notDivisable ++ sortedDivisable\n (_, result) = unzip sortedAll\n in result \n\nsolve :: [Int] -> String\nsolve = asYesNo . isSorted . taskSort \n\nasYesNo :: Bool -> String\nasYesNo True = \"YES\"\nasYesNo False = \"NO\"\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n xs <- readWords\n print $ solve xs\n"}], "src_uid": "f2070c2bd7bdbf0919aef1e915a21a24"} {"source_code": "import Data.Functor\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n s <- map read . words <$> getLine\n putStrLn $ solve n s\n\nsolve :: Int -> [Int] -> String\nsolve n r\n | n == 1 && s == 1 = \"YES\"\n | n > 1 && n == s + 1 = \"YES\"\n | otherwise = \"NO\"\n where s = sum r\n", "positive_code": [{"source_code": "main = interact $ solve . map read . words\nsolve (n:r)\n | n == 1 && s == 1 = \"YES\"\n | n > 1 && n == s + 1 = \"YES\"\n | otherwise = \"NO\"\n where s = sum . take n $ r"}, {"source_code": "check jacket = if length jacket == 1 then jacket !! 0 == 1 else sum [1 | x <- jacket, x == 0] == 1\n\noutput jacket = putStrLn ( if check jacket then \"YES\" else \"NO\" )\n\nmain = do\n\tn <- getLine\n\traw_jacket <- getLine\n\tlet jacket = [ read x :: Int | x <- ( words raw_jacket ) ]\n\toutput jacket\n"}, {"source_code": "getInt = read `fmap` getLine :: IO Int\ngetInts = (map read . words) `fmap` getLine :: IO [Int]\n\nmain = do\n n <- getInt\n xs <- getInts\n if n == 1\n then if xs == [1] then putStrLn \"YES\" else putStrLn \"NO\"\n else if (filter (==0) xs) == [0] then putStrLn \"YES\" else putStrLn \"NO\""}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmsg = putStrLn . which \"YES\" \"NO\"\n\nmain = do\n\tgetLine\n\ta <- getList\n\tif length a == 1\n\t\tthen msg $ head a == 1\n\t\telse msg $ ( == length a - 1 ) $ length $ filter ( == 1 ) a\n"}, {"source_code": "main :: IO ()\nmain = do\n n_str <- getLine\n let n = read n_str :: Int\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n putStrLn (if sum m == n - fromEnum (n > 1) then \"YES\" else \"NO\")"}, {"source_code": "main :: IO ()\nmain = do\n n_str <- getLine\n let n = read n_str :: Int\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n putStrLn (\n if (n == 1 && head m == 1) || (n /= 1 && sum m == n - 1)\n then \"YES\" else \"NO\"\n )"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n putStrLn (if sum m == length m - fromEnum (length m > 1) then \"YES\" else \"NO\")"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n let f = if n == 1 then xs == [1] else length (filter (== 0) xs) == 1\n\n putStrLn $ if f then \"YES\" else \"NO\"\n\n"}, {"source_code": "main = interact $ f . map read . words\nf (a:b) = if max 1 (a - 1) == sum b then \"YES\\n\" else \"NO\\n\""}, {"source_code": "main = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve [0] = \"NO\"\nsolve [1] = \"YES\"\nsolve ls = if sum ls == length ls - 1 then \"YES\" else \"NO\""}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n solve :: [Int] -> String\n solve [1] = \"YES\"\n solve [0] = \"NO\"\n solve xs =\n case (==1) $ length $ filter (==0) xs of\n True -> \"YES\"\n False -> \"NO\"\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . (map readInt) . words\n putStrLn $ solve xs\n"}, {"source_code": "main = getContents >>= putStrLn . (\\(n:l) -> if (n - 1) == (sum $ take n l) && n > 1 || n == 1 && head l == 1 then \"YES\" else \"NO\") . map read . words"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >> getList >>= putStrLn . which \"YES\" \"NO\" . ( == 1 ) . length . filter ( == 0 )\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\ta <- getList\n\tputStrLn $ which \"YES\" \"NO\" $ ( == length a - 1 ) $ length $ filter ( == 1 ) a\n"}, {"source_code": "a :: Int ->[Int] -> Bool\na r [] = r == 1\na r (x:xs) = a (r + 1 - x) xs\n\n\nmain :: IO ()\nmain = do\n n_str <- getLine\n let n = read n_str :: Int\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n if n == 1 then\n if head m == 0 then\n print \"NO\"\n else\n print \"YES\"\n else\n if a 0 m then\n print \"YES\"\n else\n print \"NO\"\n"}, {"source_code": "a :: Int -> [Int] -> Bool\na r [] = r == 1\na r (x:xs) = a (r + 1 - x) xs\n\n\nmain :: IO ()\nmain = do\n n_str <- getLine\n let n = read n_str :: Int\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n let s = sum m\n if n == 1 then\n if head m == 0 then\n print \"NO\"\n else\n print \"YES\"\n else\n if sum m == n - 1 then\n putStrLn \"YES\"\n else\n putStrLn \"NO\""}, {"source_code": "a :: Int -> [Int] -> Bool\na r [] = r == 1\na r (x:xs) = a (r + 1 - x) xs\n\n\nmain :: IO ()\nmain = do\n n_str <- getLine\n let n = read n_str :: Int\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n if n == 1 then\n if head m == 0 then\n print \"NO\"\n else\n print \"YES\"\n else\n if a 0 m then\n print \"YES\"\n else\n print \"NO\"\n "}, {"source_code": "a :: Int -> [Int] -> Bool\na r [] = r == 1\na r (x:xs) = a (r + 1 - x) xs\n\n\nmain :: IO ()\nmain = do\n n_str <- getLine\n let n = read n_str :: Int\n m_str <- getLine\n let m = map read $ words m_str :: [Int]\n let s = sum m\n if n == 1 then\n if head m == 0 then\n print \"NO\"\n else\n print \"YES\"\n else\n if sum m == n - 1 then\n print \"YES\"\n else\n print \"NO\""}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n xs <- getInts\n\n let f = n == 1 && xs == [1] || length (filter (== 0) xs) == 1\n\n putStrLn $ if f then \"YES\" else \"NO\"\n\n"}, {"source_code": "main = getContents >>= putStrLn . show . (\\(n:l) -> if (n - 1) == (sum $ take n l) then \"YES\" else \"NO\") . map read . words"}, {"source_code": "main = getContents >>= putStrLn . (\\(n:l) -> if 1 == n || (n - 1) == (sum $ take n l) then \"YES\" else \"NO\") . map read . words"}, {"source_code": "main = getContents >>= putStrLn . (\\(n:l) -> if (n - 1) == (sum $ take n l) then \"YES\" else \"NO\") . map read . words"}], "src_uid": "7db0b870177e7d7b01da083e21ba35f5"} {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\n\nsolve :: Int -> Int -> [[Int]]\nsolve n k = take n $ solve' [1 ..] [n*n, n*n-1 ..]\n where solve' :: [Int] -> [Int] -> [[Int]]\n solve' lower upper = row : solve' lower' upper'\n where lower' = drop (k - 1) lower\n upper' = drop (n - k + 1) upper\n row = take (k - 1) lower ++ (reverse $ take (n - k + 1) upper)\n{-\nsolve :: Int -> Int -> [[Int]]\nsolve n k = take n $ solve' 1 (n*n)\n where solve' :: Int -> Int -> [[Int]]\n solve' lower upper = row : solve' lower' upper'\n where lower' = lower + (k - 1)\n upper' = upper - (n - k - 1)\n row = [lower .. (lower' - 1)] ++ [(upper' + 1) .. upper]\n-}\n\nkTableSum :: [[Int]] -> Int -> Int\nkTableSum kTable k = sum $ map (!! (k - 1)) kTable\n\nkTableToStr :: [[Int]] -> String\nkTableToStr rows = unlines $ map (unwords . numsToStrings) rows\n where numsToStrings = map show :: [Int] -> [String]\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n, k] = map read (words line) :: [Int]\n ktable = solve n k\n putStrLn $ show $ kTableSum ktable k\n putStrLn $ kTableToStr ktable\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n\n let\n (ls, rs) = splitAt (n*(k-1)) [1..n*n]\n ls' = if k == 1 then replicate n [] else ch (k-1) ls\n rs' = ch (n-k+1) rs\n r = zipWith (++) ls' rs'\n\n ch k = unfoldr (\\s -> if null s then Nothing else Just $ splitAt k s)\n\n print $ sum $ transpose r !! (k-1)\n putStr $ unlines $ map (unwords . map show) r\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [n, k] <- fmap (map read . words) getLine\n pprint $ solve n (k-1)\n\npprint :: ([[Int]], Int) -> IO ()\npprint (l, x) = print x >> mapM_ putStrLn rest\n where\n rest = map g l\n g x = x >>= \\a -> show a ++ \" \"\n\n\n\nsolve :: Int -> Int -> ([[Int]], Int)\nsolve n k = (take n $ zipWith (++) pref suff, sumKs)\n where\n sumKs = sum $ map head (take n suff)\n pref = chunks k l\n suff = chunks (n-k) l'\n (l, l') = splitAt (k*n) [1..n*n]\n\nchunks _ [] = (repeat [])\nchunks x l = b : chunks x a\n where\n (b, a) = splitAt x l\n"}], "negative_code": [], "src_uid": "272f66f3c71c4997c5a1f0f009c9b99e"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a1,b1,q] <- (map read.words) <$> getLine\n queries <- replicateM q $ (map read.words) <$> getLine\n let (a,b) = (fromIntegral $ min a1 b1, fromIntegral $ max a1 b1)\n in putStrLn.unwords.map show $ map (solveQuery (a,b)) queries\n\n\nupToN :: (Integer,Integer) -> Integer -> Integer\nupToN (a,b) n = d*b + min m b\n where\n period = lcm a b\n (d,m) = divMod (n+1) period\n\nsolveQuery :: (Integer,Integer) -> [Integer] -> Integer\nsolveQuery (a,b) [l,r] = (r - f r) - ((l-1) - f (l-1))\n where\n f = upToN (a,b)\n", "positive_code": [{"source_code": "import qualified Data.List as L\nimport qualified Data.Array as A\n\nf a b x = (x `mod` a) `mod` b\n\nsolve_one cycle acc xx = q*(acc A.! (cycle)) + (acc A.! r)\n where x = xx+0\n q = x `div` cycle\n r = x `mod` cycle\n \n\nsolve_query :: Integer -> A.Array Integer Integer -> [Integer] -> Integer\nsolve_query cycle acc [ll,rr] = (solve_one cycle acc (rr+1)) - (solve_one cycle acc ll)\n\n\nsolve :: (Integer,Integer,Integer,[[Integer]]) -> [Integer]\nsolve (a,b,q,queries) = map (solve_query cycle (A.listArray (0,cycle) acc)) queries\n where cycle = a*b\n numbers = init [0..cycle]\n mods_a = map (f a b) numbers\n mods_b = map (f b a) numbers\n is_diff = zipWith (\\q w -> if q == w then 0 else 1) mods_a mods_b\n acc = scanl (+) 0 is_diff\n\nparse_other :: [[Integer]] -> [(Integer,Integer,Integer,[[Integer]])]\nparse_other ([a,b,q]:ss) = (a,b,q,take (fromInteger q) ss):(parse_other $ drop (fromInteger q) ss)\nparse_other [] = []\nparse_input ([t]:other) = parse_other other\n \nmain = interact $ unlines . map (unwords . map show) . map solve . parse_input . map (map read) . map words . lines\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n tt <- parseInt <$> C.getLine\n replicateM_ tt $ do\n [a, b, q] <- getIntegers\n let c = a * b `div` gcd a b\n d = max a b\n f n = (n `div` c) * (c - d) + max 0 (n `mod` c - d + 1)\n as <- replicateM (fromIntegral q) $ do\n [l, r] <- getIntegers\n return $ f r - f (l - 1)\n putStrLn $ unwords $ map show as\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\nimport qualified Data.Array as V\n\nf a b x = (x `mod` a) `mod` b\n\nsolve_query :: Integer -> Integer -> Integer -> V.Array Integer Integer -> [Integer] -> Integer\nsolve_query a b cycle acc [l,rr] = (q_r-q_l) * (acc V.! (cycle-1)) + (acc V.! (fromInteger (r `mod` cycle))) - (acc V.! (fromInteger (l`mod` cycle)))\n where r = rr+1\n q_l = l `div` cycle\n q_r = r `div` cycle\n\n\nsolve :: (Integer,Integer,Integer,[[Integer]]) -> [Integer]\nsolve (a,b,q,queries) = map (solve_query a b cycle (V.listArray (0,cycle-1) acc)) queries\n where cycle = a*b\n numbers = init [0..cycle]\n mods_a = map (f a b) numbers\n mods_b = map (f b a) numbers\n is_diff = zipWith (\\q w -> if q == w then 0 else 1) mods_a mods_b\n acc = scanl (+) 0 is_diff\n\nparse_other :: [[Integer]] -> [(Integer,Integer,Integer,[[Integer]])]\nparse_other ([a,b,q]:ss) = (a,b,q,take (fromInteger q) ss):(parse_other $ drop (fromInteger q) ss)\nparse_other [] = []\nparse_input ([t]:other) = parse_other other\n \nmain = interact $ unlines . map (unwords . map show) . map solve . parse_input . map (map read) . map words . lines\n"}, {"source_code": "import qualified Data.List as L\nimport qualified Data.Array as A\n\nf a b x = (x `mod` a) `mod` b\n\nsolve_one cycle acc xx = q*(acc A.! (cycle)) + (acc A.! r)\n where x = xx+1\n q = x `div` cycle\n r = x `mod` cycle\n \n\nsolve_query :: Integer -> A.Array Integer Integer -> [Integer] -> Integer\nsolve_query cycle acc [ll,rr] = (solve_one cycle acc (rr+1)) - (solve_one cycle acc ll)\n\n\nsolve :: (Integer,Integer,Integer,[[Integer]]) -> [Integer]\nsolve (a,b,q,queries) = map (solve_query cycle (A.listArray (0,cycle) acc)) queries\n where cycle = a*b\n numbers = init [0..cycle]\n mods_a = map (f a b) numbers\n mods_b = map (f b a) numbers\n is_diff = zipWith (\\q w -> if q == w then 0 else 1) mods_a mods_b\n acc = scanl (+) 0 is_diff\n\nparse_other :: [[Integer]] -> [(Integer,Integer,Integer,[[Integer]])]\nparse_other ([a,b,q]:ss) = (a,b,q,take (fromInteger q) ss):(parse_other $ drop (fromInteger q) ss)\nparse_other [] = []\nparse_input ([t]:other) = parse_other other\n \nmain = interact $ unlines . map (unwords . map show) . map solve . parse_input . map (map read) . map words . lines\n"}], "src_uid": "a1effd6a0f6392f46f6aa487158fef7d"} {"source_code": "import Data.List (elemIndex)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve 0 . map read . tail . words\n where printSolution xs = print (length xs) >> mapM_ (putStrLn . unwords . map show) xs\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve _ [] = []\nsolve i aas@(a:as) = (if j > 0 then ([i, i + j]:) else id) (solve (i + 1) [ if j == k then a else b | (k, b) <- zip [1..] as ])\n where j = fromJust $ elemIndex (minimum aas) aas\n", "positive_code": [{"source_code": "import qualified Data.List as List\n\nargMin :: [Int] -> (Int, Int)\nargMin [v] = (v, 0)\nargMin (x : xs) = (v', p')\n where (v, p) = argMin xs\n p' = if v < x then p + 1 else 0\n v' = min x v\n\nreplace :: [Int] -> Int -> Int -> [Int]\nreplace (x : xs) 0 v = v : xs\nreplace (x : xs) p v = x : replace xs (p - 1) v\n\nsolve :: [Int] -> [Int]\nsolve [] = []\nsolve all@(x : xs) = let (_, p) = argMin all\n rs = if (p == 0) then xs else replace xs (p - 1) x\n in p : solve rs\n\nmain = do\n getLine\n input <- getLine\n let swap = solve $ map read $ words input\n n = length swap\n print n\n mapM putStrLn $ map unwords $ zipWith (\\x y -> [show x, show (x + y)]) [0 .. ] swap\n\n"}, {"source_code": "import Data.List (elemIndex)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = getContents >>= printSolution . solve 0 . map read . tail . words\n where printSolution xs = print (length xs) >> mapM_ (putStrLn . unwords . map show) xs\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve _ [] = []\nsolve i as = (if j > Just 0 then ([i, i + fromJust j]:) else id) (solve (i + 1) [ if j == Just k then head as else a | (k, a) <- zip [1..] (tail as) ])\n where j = elemIndex (minimum as) as\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\n\nprocess [x] = putStrLn \"0 0\"\nprocess t = do \n\t\tlet z = fromJust(elemIndex (maximum t) t)\n\t\tlet lt = length t - 1\n\t\tputStrLn $ show z ++ \" \"++ show lt\n\t\tlet nt = init (take z t ++ [t!!lt] ++ (drop (z+1) t))\n\t\tprocess nt\n\t\t\n\t\t\n \n\nmain=do\n\ts<- getLine\n\tt<- map (fst.fromJust.C.readInt). C.words <$> C.getLine ::IO [Int]\n\tprint $ length t\n\tprocess t"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\n\nprocess [x] = putStrLn \"0 0\"\nprocess t = do \n\t\tlet z = fromJust(elemIndex (maximum t) t)\n\t\tlet lt = length t - 1\n\t\tputStrLn $ show z ++ \" \"++ show lt\n\t\tlet nt = init (take (z-1) t ++ [t!!lt] ++ (drop (z+1) t))\n\t\tprocess nt\n\t\t\n\t\t\n \n\nmain=do\n\ts<- getLine\n\tt<- map (fst.fromJust.C.readInt). C.words <$> C.getLine ::IO [Int]\n\tprint $ length t\n\tprocess t"}], "src_uid": "b3c6058893f935d88196113fab581cf8"} {"source_code": "import Control.Monad ( replicateM, replicateM_ )\r\nimport Data.Array ( (!) ) \r\nimport Data.Bits ( Bits(testBit, (.&.), xor) )\r\nimport Data.Graph ( buildG )\r\nimport Data.List ( sort )\r\nimport Data.Tuple ( swap )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as S\r\n\r\ndata Queue a = Queue [a] [a] deriving Show\r\n\r\nempty :: Queue a -> Bool\r\nempty (Queue [] []) = True\r\nempty _ = False\r\n\r\npush :: a -> Queue a -> Queue a\r\npush x (Queue a b) = Queue (x:a) b\r\n\r\npop :: Queue a -> (a, Queue a)\r\npop (Queue [] []) = error \"empty\"\r\npop (Queue a (x:xs)) = (x, Queue a xs)\r\npop (Queue a []) = pop $ Queue [] (reverse a)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n e <- replicateM (n * 2^(n - 1)) $ do\r\n [u, v] <- readInts\r\n return (u, v)\r\n let g = buildG (0, 2^n - 1) (e ++ map swap e)\r\n go :: S.IntSet -> Int -> Int -> [Int]\r\n go un u v | S.size un == 2 = [u, v]\r\n go un u v =\r\n let (r0, u0, v0, r1, u1, v1) = bfs un (Queue [] [u]) (S.singleton u) (Queue [] [v]) (S.singleton v)\r\n r0' = go r0 u0 v0\r\n r1' = match un r0' r1\r\n in r0' ++ r1'\r\n bfs :: S.IntSet -> Queue Int -> S.IntSet -> Queue Int -> S.IntSet -> (S.IntSet, Int, Int, S.IntSet, Int, Int)\r\n bfs un q0 a0 q1 a1\r\n | empty q0 = (a0, -1, -1, a1, -1, -1)\r\n | otherwise =\r\n let (u, q0') = pop q0\r\n ok v = v `S.notMember` a0 && v `S.notMember` a1 && v `S.member` un\r\n nbs = filter ok (g!u)\r\n a0' = foldr S.insert a0 nbs\r\n q0'' = foldr push q0' nbs\r\n (r1, u1, v1, r0, _, _) = bfs un q1 a1 q0'' a0'\r\n in (r0, u, head nbs, r1, u1, v1)\r\n match :: S.IntSet -> [Int] -> S.IntSet -> [Int]\r\n match un r0 r1 =\r\n let ok v = v `S.member` r1 && v `S.member` un\r\n in map (head . filter ok . (g!)) r0\r\n canColor = n .&. (n - 1) == 0\r\n color u = foldr xor 0 [i | i <- [0..n - 1], u `testBit` i]\r\n let (u, v) = head e\r\n p = go (S.fromList [0..2^n - 1]) u v\r\n invP = map snd $ sort $ zip p [0..]\r\n pStr = unwords $ map show p\r\n cStr = unwords $ map show $ [color (i :: Int) | i <- invP]\r\n putStrLn pStr\r\n putStrLn $ if canColor then cStr else \"-1\"\r\n\r\nparseInt = getInt . C.readInt where getInt (Just (i, _)) = i\r\nreadInt = parseInt <$> C.getLine \r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readInt\r\n replicateM_ t solve\r\n", "positive_code": [{"source_code": "import Control.Monad ( replicateM, replicateM_ )\r\nimport Data.Array ( (!) )\r\nimport Data.Bits ( Bits(testBit, (.&.), xor) )\r\nimport Data.Graph ( buildG )\r\nimport Data.List ( sort )\r\nimport Data.Tuple ( swap )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as S\r\n\r\ndata Queue a = Queue [a] [a] deriving Show\r\n\r\nempty :: Queue a -> Bool\r\nempty (Queue [] []) = True\r\nempty _ = False\r\n\r\npush :: a -> Queue a -> Queue a\r\npush x (Queue a b) = Queue (x:a) b\r\n\r\npop :: Queue a -> (a, Queue a)\r\npop (Queue [] []) = error \"empty\"\r\npop (Queue a (x:xs)) = (x, Queue a xs)\r\npop (Queue a []) = pop $ Queue [] (reverse a)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n e <- replicateM (n * 2^(n - 1)) $ do\r\n [u, v] <- readInts\r\n return (u, v)\r\n let g = buildG (0, 2^n - 1) (e ++ map swap e)\r\n go :: S.IntSet -> Int -> Int -> [Int]\r\n go un u v | S.size un == 2 = [u, v]\r\n go un u v =\r\n let (r0, u0, v0, r1, u1, v1) = bfs un (Queue [] [u]) (S.singleton u) (Queue [] [v]) (S.singleton v)\r\n r0' = go r0 u0 v0\r\n r1' = match un r0' r1\r\n in r0' ++ r1'\r\n bfs :: S.IntSet -> Queue Int -> S.IntSet -> Queue Int -> S.IntSet -> (S.IntSet, Int, Int, S.IntSet, Int, Int)\r\n bfs un q0 a0 q1 a1\r\n | empty q0 = (a0, -1, -1, a1, -1, -1)\r\n | otherwise =\r\n let (u, q0') = pop q0\r\n ok v = v `S.notMember` a0 && v `S.notMember` a1 && v `S.member` un\r\n nbs = filter ok (g!u)\r\n a0' = foldr S.insert a0 nbs\r\n q0'' = foldr push q0' nbs\r\n (r1, u1, v1, r0, _, _) = bfs un q1 a1 q0'' a0'\r\n in (r0, u, head nbs, r1, u1, v1)\r\n match :: S.IntSet -> [Int] -> S.IntSet -> [Int]\r\n match un r0 r1 =\r\n let ok v = v `S.member` r1 && v `S.member` un\r\n in map (head . filter ok . (g!)) r0\r\n canColor = n .&. (n - 1) == 0\r\n color :: Int -> Int\r\n color u = foldr xor 0 $ filter (testBit u) [0..n - 1]\r\n let (u, v) = head e\r\n p = go (S.fromList [0..2^n - 1]) u v\r\n invP = map snd $ sort $ zip p [0..]\r\n pStr = unwords $ map show p\r\n cStr = unwords $ map (show . color) invP\r\n putStrLn pStr\r\n putStrLn $ if canColor then cStr else \"-1\"\r\n\r\nparseInt = getInt . C.readInt where getInt (Just (i, _)) = i\r\nreadInt = parseInt <$> C.getLine\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readInt\r\n replicateM_ t solve\r\n"}], "negative_code": [{"source_code": "import Control.Monad ( replicateM, replicateM_ )\r\nimport Data.Array ( (!) ) \r\nimport Data.Bits ( Bits(testBit, (.&.), xor) )\r\nimport Data.Graph ( buildG )\r\nimport Data.List ( sort )\r\nimport Data.Tuple ( swap )\r\nimport qualified Data.IntSet as S\r\n\r\ndata Queue a = Queue [a] [a] deriving Show\r\n\r\nempty :: Queue a -> Bool\r\nempty (Queue [] []) = True\r\nempty _ = False\r\n\r\npush :: a -> Queue a -> Queue a\r\npush x (Queue a b) = Queue (x:a) b\r\n\r\npop :: Queue a -> (a, Queue a)\r\npop (Queue [] []) = error \"empty\"\r\npop (Queue a (x:xs)) = (x, Queue a xs)\r\npop (Queue a []) = pop $ Queue [] (reverse a)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n e <- replicateM (n * 2^(n - 1)) $ do\r\n [u, v] <- readMany :: IO [Int]\r\n return (u, v)\r\n let g = buildG (0, 2^n - 1) (e ++ map swap e)\r\n go :: S.IntSet -> Int -> Int -> [Int]\r\n go un u v | S.size un == 2 = [u, v]\r\n go un u v =\r\n let (r0, u0, v0, r1, u1, v1) = bfs un (Queue [] [u]) (S.singleton u) (Queue [] [v]) (S.singleton v)\r\n in go r0 u0 v0 ++ go r1 u1 v1\r\n bfs :: S.IntSet -> Queue Int -> S.IntSet -> Queue Int -> S.IntSet -> (S.IntSet, Int, Int, S.IntSet, Int, Int)\r\n bfs un q0 a0 q1 a1\r\n | empty q0 = (a0, -1, -1, a1, -1, -1)\r\n | otherwise =\r\n let (u, q0') = pop q0\r\n ok v = v `S.notMember` a0 && v `S.notMember` a1 && v `S.member` un\r\n nxt = filter ok (g!u)\r\n a0' = foldr S.insert a0 nxt\r\n q0'' = foldr push q0' nxt\r\n (r1, u1, v1, r0, u0, v0) = bfs un q1 a1 q0'' a0'\r\n (u0', v0') = if null nxt then (u0, v0) else (u, head nxt)\r\n in (r0, u0', v0', r1, u1, v1)\r\n canColor = n .&. (n - 1) == 0\r\n color u = foldr xor 0 [i | i <- [0..n - 1], u `testBit` i]\r\n let (u, v) = head e\r\n p = go (S.fromList [0..2^n - 1]) u v\r\n invP = map snd $ sort $ zip p [0..]\r\n pStr = unwords $ map show p\r\n cStr = unwords $ map show $ [color (i :: Int) | i <- invP]\r\n putStrLn pStr\r\n putStrLn $ if canColor then cStr else \"-1\"\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "import Control.Monad ( replicateM, replicateM_ )\r\nimport Data.Array ( (!) ) \r\nimport Data.Bits ( Bits(testBit, (.&.), xor) )\r\nimport Data.Graph ( buildG )\r\nimport Data.List ( sort )\r\nimport Data.Tuple ( swap )\r\nimport qualified Data.IntSet as S\r\n\r\ndata Queue a = Queue [a] [a] deriving Show\r\n\r\nempty :: Queue a -> Bool\r\nempty (Queue [] []) = True\r\nempty _ = False\r\n\r\npush :: a -> Queue a -> Queue a\r\npush x (Queue a b) = Queue (x:a) b\r\n\r\npop :: Queue a -> (a, Queue a)\r\npop (Queue [] []) = error \"empty\"\r\npop (Queue a (x:xs)) = (x, Queue a xs)\r\npop (Queue a []) = pop $ Queue [] (reverse a)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n e <- replicateM (n * 2^(n - 1)) $ do\r\n [u, v] <- readMany :: IO [Int]\r\n return (u, v)\r\n let g = buildG (0, 2^n - 1) (e ++ map swap e)\r\n go :: S.IntSet -> Int -> Int -> [Int]\r\n go un u v =\r\n let (r0, u0, v0, r1, u1, v1) = bfs un (Queue [] [u]) (S.singleton u) (Queue [] [v]) (S.singleton v)\r\n in if u0 == -1 then [S.findMin r0, S.findMin r1] else go r0 u0 v0 ++ go r1 u1 v1\r\n bfs :: S.IntSet -> Queue Int -> S.IntSet -> Queue Int -> S.IntSet -> (S.IntSet, Int, Int, S.IntSet, Int, Int)\r\n bfs un q0 a0 q1 a1\r\n | empty q0 = (a0, -1, -1, a1, -1, -1)\r\n | otherwise =\r\n let (u, q0') = pop q0\r\n ok v = v `S.notMember` a0 && v `S.notMember` a1 && v `S.member` un\r\n nxt = filter ok (g!u)\r\n a0' = foldr S.insert a0 nxt\r\n q0'' = foldr push q0' nxt\r\n (r1, u1, v1, r0, u0, v0) = bfs un q1 a1 q0'' a0'\r\n (u0', v0') = if null nxt then (u0, v0) else (u, head nxt)\r\n in (r0, u0', v0', r1, u1, v1)\r\n canColor = n .&. (n - 1) == 0\r\n color u = foldr xor 0 [i | i <- [0..n - 1], u `testBit` i]\r\n let (u, v) = head e\r\n p = go (S.fromList [0..2^n - 1]) u v\r\n pStr = unwords $ map show p\r\n invP = map snd $ sort $ zip p [0..]\r\n cStr = unwords $ map show $ [color (i :: Int) | i <- invP]\r\n putStrLn pStr\r\n putStrLn $ if canColor then cStr else \"-1\"\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "src_uid": "4c9c50f9ebe06a3e86c20aee2a0ee797"} {"source_code": "main = do line <- getLine\n let [n, t, c] = (map read $ words line) :: [Int]\n line <- getLine\n let xs = (map read $ words line) :: [Int]\n putStrLn $ show $ countCrime xs t c\n\ncountCrime :: [Int] -> Int -> Int -> Int\ncountCrime xs t c = count badGuys 0 0\n where badGuys = map (\\ x -> x > t) xs\n count [] acc cur = acc + (max (cur - c + 1) 0)\n count (True : xs) acc cur = count xs newAcc 0\n where newAcc = acc + (max (cur - c + 1) 0)\n count (False : xs) acc cur = count xs acc (cur + 1)", "positive_code": [{"source_code": "split as [] l t c = if l >= c then (l-c+1:as) else as \nsplit as (b:bs) l t c = \n if b > t \n then split (if l >= c then (l-c+1:as) else as) bs 0 t c \n else split as bs (l+1) t c\n\n\nmain = do\n let getInts = getLine >>= return . map (\\x -> read x :: Int) . words\n [n,t,c] <- getInts\n is <- getInts \n print $ sum $ split [] is 0 t c\n"}, {"source_code": "f t xs = let (l,ys) = span (<=t) xs in if ys == [] then if l==[] then [] else l:[] else if l == [] then (f t $ tail ys) else l:(f t $ tail ys)\n\ncount c t = (\\x -> if x>= return . map (read :: String -> Int) . words\n\tres <- getLine >>= return . codeforces t c . map (read :: String -> Int) . words\n\tprint res"}, {"source_code": "import Data.List (group)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:t:c:xs) = sum $ filter (>0) $ map (subtract (c - 1) . length) $ filter head $ group $ map (<=t) xs\nsolve _ = undefined\n"}, {"source_code": "import Data.List\nmain=interact$show.f.map read.words\nf (_:t:c:xs)=sum$filter(>0)$map((+(1-c)).length)$filter head$group$map(<=t)xs\n"}, {"source_code": "import Data.List\nstrToList = (fmap (read :: (String -> Int))).words\nf [] _ _ = 0\nf xs t c = let (a, b) = break (>t) (dropWhile (>t) xs) in max 0 (length a - c + 1) + f b t c\nmain = do\n [n, t, c] <- fmap strToList getLine\n s <- fmap strToList getLine\n putStrLn $ show (f s t c)"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n [n,t,c] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n print $ solve t c xs\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve t c xs = go 0 xs\n where\n go !res [] = res\n go !res xs = go (res + max 0 (len - c + 1)) zs\n where\n (ys, zs) = dropWhile (t<) <$> span (<=t) xs\n !len = length ys\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nmain :: IO ()\nmain = do\n\t[_,t,c] <- inputInts\n\tprint =<< sum . filter (>0) . map (subtract (c - 1) . length) . filter head . group . map (<= t) <$> inputInts\n"}, {"source_code": "main = do\n s1<-getLine\n s2<-getLine\n putStr $ res((map read.words)s1)((map read.words)s2)\n\nres [n,t,c] x = solve n t c x 0\nsolve _ _ _ [] acc = show acc \nsolve n t c x acc\n |length(takeWhile (<=t) x)>=c = solve n t c (dropWhile(<=t)x) (acc+1-c+length(takeWhile (<=t) x))\n |dropWhile(<=t)x==[] = show acc \n |otherwise = solve n t c (tail(dropWhile(<=t)x)) acc"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain :: IO ()\nmain = do\n\tinp <- (map read . words) <$> getLine \n\txs <- (map read . words) <$> getLine \n\tprint $ solve inp 0 xs\n\nsolve :: [Int] -> Int -> [Int] -> Int\nsolve _ _ [] = 0\nsolve [n, t, c] cnt (x : xs)\n\t| newCount >= c = 1 + solve [n, t, c] newCount xs\n\t| otherwise = solve [n, t, c] newCount xs\n\twhere\n\t\tnewCount = if x <= t then cnt + 1 else 0\n\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = C.getLine >>= \\ns -> putStrLn.solve.(\\as->[tail $ map (fst.fromJust.C.readInt) $ C.words ns]++[as]) =<< (C.getLine>>= \\js -> return $ map (fst.fromJust.C.readInt) $ C.words js)\nsolve [[x1,x2],xs] = show $ slv2 slv1\n where\n slv1 = foldr f [0] xs\n f a (b:bs) = if a>x1 then (0:b:bs) else (b+1):bs\n slv2 ys = foldr (\\ a b -> if a 0 then (l-c+1:as) else as \nsplit as (b:bs) l t c = \n if b > t \n then split (if l >= c then (l-c+1:as) else as) bs 0 t c \n else split as bs (l+1) t c\n\n\nmain = do\n let getInts = getLine >>= return . map (\\x -> read x :: Int) . words\n [n,t,c] <- getInts\n is <- getInts \n print $ sum $ split [] is 0 t c\n"}, {"source_code": "f t xs = let (l,ys) = span (<=t) xs in if ys == [] then if l==[] then [] else l:[] else if l == [] then (f t $ tail ys) else l:(f t $ tail ys)\n\ncount c t = (\\x -> if x>= return . map (read :: String -> Int) . words\n\tgetLine >>= return . codeforces t c . map (read :: String -> Int) . words"}], "src_uid": "7d1e8769a6b1d5c6680ab530d19e7fa4"} {"source_code": "{- ok -}\nimport Control.Applicative ((<$>))\nimport Data.Array (Array, (!))\nimport qualified Data.Array as Array\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\n\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\ntype Graph = Array Int [Int]\n\nmain = do\n\t[n, m] <- map readInt' . words <$> getLine\n\tedges <- map ((\\[a, b] -> (a, b)) . map readInt' . words) . lines <$> getContents\n\n\tlet \n\t\tsearch set\n \t\t\t| Set.null set = []\n \t\t\t| otherwise = cycle:(search set')\n \t\t\twhere\n\t\t \t\t(cycle, set') = dfs set (Set.findMin set) 0\n\n\t\t\t\tdfs set u w = dfs' (u `Set.delete` set) $ filter (/= w) $ g ! u\n \t\t\t\t\twhere\n\t\t \t\t\t\tdfs' set [] = (False, set)\n\t\t \t\t\t\tdfs' set (v:vs) \n\t\t\t\t\t\t\t| v `Set.notMember` set = (True, set)\n\t\t\t\t\t\t | otherwise = (cycle1 || cycle2, set'')\n\t\t \t\t\t\t\twhere\n\t\t\t\t\t\t\t (cycle1, set') = dfs set v u\n\t\t\t\t\t\t\t (cycle2, set'') = dfs' set' vs \n\n\t\t\t\t-- dfs set u w = foldl dfs' (False, vs') . filter (/= w) $ g ! u\n\t\t\t\t--\twhere\n\t \t\t\t--\t\tvs' = u `Set.delete` vs\n\n\t\t\t\t--\t\tdfs' (f, vs) v\n\t\t\t\t--\t\t\t| v `Set.notMember` vs = (True, vs)\n\t\t\t\t--\t\t | otherwise = (f || f', vs')\n \t\t\t\t--\t\t\twhere\n\t\t\t\t--\t\t\t (f', vs') = dfs vs v u\n\n\t \tcomps = search $ Set.fromList [1..n]\t\n\t\tg = Array.accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges\n\n \tprint . length . filter not $ comps\n\n\t\n\n", "positive_code": [{"source_code": "{- ok -}\nimport Control.Applicative ((<$>))\nimport Data.Array (Array, (!))\nimport qualified Data.Array as Array\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\n\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\ntype Graph = Array Int [Int]\n\nmain = do\n\t[n, m] <- map readInt' . words <$> getLine\n\tedges <- map ((\\[a, b] -> (a, b)) . map readInt' . words) . lines <$> getContents\n\n\tlet \n\t\tsearch set\n \t\t\t| Set.null set = []\n \t\t\t| otherwise = cycle:(search set')\n \t\t\twhere\n\t\t \t\t(cycle, set') = dfs set (Set.findMin set) 0\n\n\t\t\t\tdfs set u w = dfs' (u `Set.delete` set) $ filter (/= w) $ g ! u\n \t\t\t\t\twhere\n\t\t \t\t\t\tdfs' set [] = (False, set)\n\t\t \t\t\t\tdfs' set (v:vs) \n\t\t\t\t\t\t\t| v `Set.notMember` set = (True, set)\n\t\t\t\t\t\t | otherwise = (cycle1 || cycle2, set'')\n\t\t \t\t\t\t\twhere\n\t\t\t\t\t\t\t (cycle1, set') = dfs set v u\n\t\t\t\t\t\t\t (cycle2, set'') = dfs' set' vs \n\n -- above is prettier ?\n\t\t\t\t-- dfs set u w = foldl dfs' (False, vs') . filter (/= w) $ g ! u\n\t\t\t\t--\twhere\n\t \t\t\t--\t\tvs' = u `Set.delete` vs\n\n\t\t\t\t--\t\tdfs' (f, vs) v\n\t\t\t\t--\t\t\t| v `Set.notMember` vs = (True, vs)\n\t\t\t\t--\t\t | otherwise = (f || f', vs')\n \t\t\t\t--\t\t\twhere\n\t\t\t\t--\t\t\t (f', vs') = dfs vs v u\n\n\t \tcomps = search $ Set.fromList [1..n]\t\n\t\tg = Array.accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges\n\n \tprint . length . filter not $ comps\n\n\t\n\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.Array (Array, (!))\nimport qualified Data.Array as Array\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\n\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\ntype Graph = Array Int [Int]\n\nmain = do\n\t[n, m] <- map readInt' . words <$> getLine\n\tedges <- map ((\\[a, b] -> (a, b)) . map readInt' . words) . lines <$> getContents\n\n\tlet \n\t\tsearch vs \n \t\t\t| Set.null vs = []\n \t\t\t| otherwise = f : (search vs')\n \t\t\twhere\n\t\t \t\t(f, vs') = dfs vs (Set.findMin vs) (-1)\n \t\t\t\t\twhere\n\t\t \t\t\t\tu = Set.findMin vs\n\n\t\t\t\tdfs vs u w\n\t\t\t\t\t| u `Set.notMember` vs = (True, vs')\n\t\t\t \t | otherwise = foldl next (False, vs') $ filter (/= w) $ g ! u\n\t\t \t\t\twhere\n\t\t \t\t\t\tvs' = u `Set.delete` vs\n\n \t\t\t\t\t\tnext (f, vs) v = (f || f', vs')\n\t\t \t\t\t\t\twhere\n\t\t \t\t\t\t\t\t(f', vs') = dfs vs v u\n\n\t \tcomps = search $ Set.fromList [1..n]\t\n\t\tg = Array.accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges\n\n \tprint . length . filter not $ comps\n\n\t\n\n"}, {"source_code": "{- ok -}\nimport Control.Applicative ((<$>))\nimport Data.Array (Array, (!))\nimport qualified Data.Array as Array\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\n\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\ntype Graph = Array Int [Int]\n\nmain = do\n\t[n, m] <- map readInt' . words <$> getLine\n\tedges <- map ((\\[a, b] -> (a, b)) . map readInt' . words) . lines <$> getContents\n\n\tlet \n\t\tsearch vs \n \t\t\t| Set.null vs = []\n \t\t\t| otherwise = f : (search vs')\n \t\t\twhere\n\t\t \t\t(f, vs') = dfs vs (Set.findMin vs) 0\n\n\t\t\t\tdfs vs u w = foldl dfs' (False, vs') . filter (/= w) $ g ! u\n\t\t\t\t\twhere\n\t \t\t\t\t\tvs' = u `Set.delete` vs\n\n\t\t\t\t\t\tdfs' (f, vs) v\n\t\t\t\t\t\t\t| v `Set.notMember` vs = (True, vs)\n\t\t\t\t\t\t | otherwise = (f || f', vs')\n \t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t (f', vs') = dfs vs v u\n\n\t \tcomps = search $ Set.fromList [1..n]\t\n\t\tg = Array.accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges\n\n \tprint . length . filter not $ comps\n\n\t\n\n"}], "negative_code": [{"source_code": "{- ok -}\nimport Control.Applicative ((<$>))\nimport Data.Array (Array, (!))\nimport qualified Data.Array as Array\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Data.Tuple (swap)\n\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\ntype Graph = Array Int [Int]\n\nmain = do\n\t[n, m] <- map readInt' . words <$> getLine\n\tedges <- map ((\\[a, b] -> (a, b)) . map readInt' . words) . lines <$> getContents\n\n\tlet \n\t\tsearch vs \n \t\t\t| Set.null vs = []\n \t\t\t| otherwise = f : (search vs')\n \t\t\twhere\n\t\t \t\t(f, vs') = dfs vs (Set.findMin vs) 0\n\n\t\t\t\tdfs vs u w = foldl dfs' (False, vs') . filter (/= w) $ g ! u\n\t\t\t\t\twhere\n\t \t\t\t\t\tvs' = u `Set.delete` vs\n\n\t\t\t\t\t\tdfs' (f, vs) v\n\t\t\t\t\t\t\t| u `Set.notMember` vs = (True, vs)\n\t\t\t\t\t\t | otherwise = (f || f', vs')\n \t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t (f', vs') = dfs vs v u\n\n\t \tcomps = search $ Set.fromList [1..n]\t\n\t\tg = Array.accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges\n\n \tprint . length . filter not $ comps\n\n\t\n\n"}], "src_uid": "1817fbdc61541c09fb8f48df31f5049a"} {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n \n \n\n\nmain= do\n\ts<- C.tail. C.take 3 . C.reverse .C.filter (/=' ') <$> C.getLine \n\tlet s1 = read (reverse (C.unpack s)) ::Int\n\tprint $ if mod s1 4 ==0 then 4 else 0\n\t", "positive_code": [{"source_code": "main :: IO ()\nmain = readLn >>= print . solve\n\nsolve :: Integer -> Integer\nsolve n | n `mod` 4 == 0 = 4 | otherwise = 0\n"}, {"source_code": "main = putStrLn . solve =<< getLine\nsolve s | n `mod` 4 == 0 = \"4\" | otherwise = \"0\" where\n n = read $ reverse $ take 2 $ reverse s\n"}, {"source_code": "module Main where\n\nmain = do\n\tline <- getLine\n\tlet n = read line `mod` 4\n\tlet ans = (1^n + 2^n + 3^n + 4^n) `mod` 5\n\tputStrLn $ show ans\n"}, {"source_code": "main = do\n n <- fmap (read . reverse . take 2 . reverse) getLine :: IO Int\n print $ f n where\n f n\n | mod n 2 == 1 = 0\n | otherwise = let m = mod n 4 in mod (1 + 2^m + 3^m + 4^m) 5"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\n-- Meat\nsolve :: BS.ByteString -> Int\nsolve s = if divisibleBy4 s then 4 else 0\n\ndivisibleBy4 :: BS.ByteString -> Bool\ndivisibleBy4 s = toInt str `mod` 4 == 0\n where len = BS.length s\n str = if len < 2 then s else BS.drop (len - 2) s\n toInt = fst .fromJust . BS.readInt\n\n-- Shit\nmain :: IO ()\nmain = do\n [[s]] <- readShit\n printShit [solve s]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: x -> x -> Bool-> x\niif a b c = if c then a else b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "solve n = if n `mod` 4 == 0 then 4 else 0\nmain = getLine >>= print . solve . read\n"}, {"source_code": "{-# LANGUAGE NPlusKPatterns #-}\n\nmodule Main where\n\n(<**>) :: Int -> Integer -> Int\n0 <**> 0 = 1\n0 <**> n = 0\n1 <**> _ = 1\n2 <**> 0 = 1\n2 <**> 1 = 2\n2 <**> 2 = 4\n2 <**> 3 = 3\n2 <**> n = 2 <**> (n `mod` 4)\n3 <**> 0 = 1\n3 <**> 1 = 3\n3 <**> 2 = 4\n3 <**> 3 = 2\n3 <**> n = 3 <**> (n `mod` 4)\n4 <**> 0 = 1\n4 <**> 1 = 4\n4 <**> n = 4 <**> (n `mod` 2)\n5 <**> _ = 1\n\ntask, task' :: Integer -> Int\ntask n = (1 <**> n) + (2 <**> n) + (3 <**> n) + (4 <**> n)\ntask' n = task n `mod` 5\n\ngetInteger :: IO Integer\ngetInteger = fmap read getLine\n\nmain :: IO ()\nmain = getInteger >>= (print . task')\n"}, {"source_code": "compute :: Int -> Int\ncompute n = (1 + 2 ^ n + 3 ^ n + 4 ^ n) `mod` 5 \n\nlastN :: Int -> [a] -> [a]\nlastN n xs = foldl (const . drop 1) xs (drop n xs)\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read $ lastN 3 line\n print $ compute (n `mod` 4)\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . read\n\ngetAns :: Integer -> Int\ngetAns x = let m2 = fromInteger $ x `mod` 2; m4 = fromInteger $ x `mod` 4\n\t\t\tin (1 + ([1, 2, 4, 3] !! m4) + ([1, 3, 4, 2] !! m4) + ([1, 4] !! m2)) `mod` 5\n\n{-\n1 -> [1]\n2 -> [2, 4, 3, 1]\n3 -> [3, 4, 2, 1]\n4 -> [4, 1]-}\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . read\n\ngetAns :: Integer -> Int\ngetAns x = let m = fromInteger $ x `mod` 4\n\t\t\tin (1 + 2 ^ m + 3 ^ m + 4 ^ m) `mod` 5\n\n"}, {"source_code": "module Main where\n\nimport Data.Bits\n\nmain = do\n n <- getLine\n let l = length n \n print $ (\\x -> if x `mod`4 == 0 then 4 else 0) $ (read :: String -> Int) $ drop (if l > 1 then l-2 else 0) n "}, {"source_code": "\nsolve :: String -> Int\nsolve s\n | read ends `mod` 4 == 0 = 4\n | otherwise = 0\n where\n ends = drop (length s - 2) s\n\nmain :: IO()\nmain = getLine >>= print . solve\n "}, {"source_code": "main = do\n input <- getLine\n let len = length input\n let short = (read :: String -> Int) $ drop (len - 2) input\n putStrLn $ show $ f short\n\nf :: Int -> Int\nf x = \n let x1 = cycle [1,1,1,1]\n x2 = cycle [6,2,4,8]\n x3 = cycle [1,3,9,7]\n x4 = cycle [6,4,6,4] \n m = mod4 x\n in mod5 (x1 !! m + x2 !! m + x3 !! m + x4 !! m)\n\nmod4 x = mod x 4\nmod5 x = mod x 5\n"}, {"source_code": "main=readLn>>=print.f\nf n|n`mod`4==0=4|1>0=0\n"}, {"source_code": "main :: IO ()\nmain = getLine >>= print . solve\n\nsolve :: String -> Int\nsolve [] = 0\nsolve (_:s@(_:_:_)) = solve s\nsolve s = if (read s :: Int) `mod` 4 == 0 then 4 else 0\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getLine >>= print . solve\n\nsolve :: B.ByteString -> Int\nsolve s = if fst (fromJust $ B.readInt (B.drop (B.length s - 3) s)) `mod` 4 == 0 then 4 else 0\n"}], "negative_code": [{"source_code": "import Data.Char\n\n\ncompute :: Int -> Int\ncompute n = (1 + 2 ^ n + 3 ^ n + 4 ^ n) `mod` 5 \n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = digitToInt $ last line\n print $ compute (n `mod` 4)\n"}, {"source_code": "main = do\n input <- getLine\n let len = length input\n let short = (read :: String -> Int) $ drop (len - 2) input\n putStrLn $ show $ f short\n\nf :: Int -> Int\nf 0 = 4\nf x = \n let x1 = cycle [1,1,1,1]\n x2 = cycle [2,4,8,6]\n x3 = cycle [3,9,7,1]\n x4 = cycle [4,6,4,6] \n m = mod4 x\n in mod5 (x1 !! m + x2 !! m + x3 !! m + x4 !! m)\n\nmod4 x = mod x 4\nmod5 x = mod x 5\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getLine >>= print . solve\n\nsolve :: B.ByteString -> Int\nsolve s = if fst (fromJust $ B.readInt (B.drop (B.length s - 2) s)) `mod` 4 == 0 then 4 else 0\n"}, {"source_code": "main = interact $ show . solve\nsolve s | n `mod` 4 == 0 = \"4\" | otherwise = \"0\" where\n n = read $ reverse $ take 2 $ reverse s\n"}, {"source_code": "main = interact $ show . solve\nsolve s = (1^n + 2^n + 3^n + 4^n) `mod` 5 :: Integer where\n n = read $ reverse $ take 2 $ reverse s\n"}, {"source_code": "main = interact solve\nsolve s | n `mod` 4 == 0 = \"4\" | otherwise = \"0\" where\n n = read $ reverse $ take 2 $ reverse s\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n \n \n\n\nmain= do\n\ts<- C.take 2 . C.reverse <$> C.getLine \n\tlet s1 = read (reverse (C.unpack s)) ::Int\n\tprint $ if mod s1 4 ==0 then 4 else 0\n\t"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\n-- Meat\nsolve :: BS.ByteString -> Int\nsolve s = if divisibleBy4 s then 4 else 0\n\ndivisibleBy4 :: BS.ByteString -> Bool\ndivisibleBy4 s = toInt str `mod` 4 == 0\n where len = BS.length s\n str = if len < 2 then s else BS.drop (len - 2) s\n toInt = fst .fromJust . BS.readInt\n\n-- Shit\nmain :: IO ()\nmain = do\n [s] <- readShit\n printShit [solve s]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: x -> x -> Bool-> x\niif a b c = if c then a else b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\n-- Meat\nsolve :: BS.ByteString -> Int\nsolve s = if divisibleBy4 s then 4 else 0\n\ndivisibleBy4 :: BS.ByteString -> Bool\ndivisibleBy4 s = (suffInt `mod` 4) == 0\n where len = BS.length s\n suffix = BS.drop (len - 2) s :: BS.ByteString\n suffInt = fst . fromJust . BS.readInt $ suffix :: Int\n-- Shit\nmain :: IO ()\nmain = do\n [s] <- readShit\n printShit [solve s]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: x -> x -> Bool-> x\niif a b c = if c then a else b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}], "src_uid": "74cbcbafbffc363137a02697952a8539"} {"source_code": "module Main where\n\nimport Data.List ( group, nub )\n\n\nisUnsospicious :: String -> String\nisUnsospicious tasks\n | taskList == nub taskList = \"YES\"\n | otherwise = \"NO\"\n where\n taskList = map head $ group tasks\n\n\nsolve :: IO String\nsolve = do\n stringLength <- getLine\n tasks <- getLine\n return $ isUnsospicious tasks\n\n\nsolution :: Int -> IO [String]\nsolution 0 = return []\nsolution test = do\n answer <- solve\n rest <- solution (test - 1)\n return $ answer : rest\n\n\nmain :: IO ()\nmain = do\n tests <- getLine\n results <- solution (read tests)\n mapM_ putStrLn results\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n s <- getLine\r\n let a = map head $ group s\r\n r = any (\\x->length x > 1) $ group $ sort a\r\n putStrLn $ if r then \"NO\" else \"YES\"\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Data.List\r\nimport System.IO\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\ncountConsequence c [] meet = 0\r\ncountConsequence c (x:xs) meet \r\n | c /= x && meet == False = countConsequence c xs meet \r\n | c /= x && meet == True = 0 \r\n | otherwise = 1 + (countConsequence c xs True)\r\n\r\nforString [] ys = putStrLn\"YES\"\r\nforString (x:xs) ys = if sum[1|y<-ys,y==x] /= (countConsequence x ys False)\r\n then putStrLn \"NO\"\r\n else forString xs ys \r\n\r\nprintS = do\r\n n<-readLn::IO Int \r\n s<-getLine \r\n let ys = ['A'..'Z']\r\n forString ys s\r\n\r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t printS \r\n "}, {"source_code": "import Control.Monad\nimport Data.Containers.ListUtils (nubInt)\nimport Data.List (group)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n a <- map fromEnum <$> getLine\n let b = map head $ group a\n putStrLn $\n if b == nubInt b\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "import Control.Arrow\r\nimport Data.List\r\nimport Data.Bool\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf n xs = let (s, xs') = splitAt n xs in s : chunksOf n xs'\r\n\r\nmain = interact $ \r\n lines >>> drop 1 >>> chunksOf 2 \r\n >>> map ((!! 1) >>> solve >>> bool \"NO\" \"YES\")\r\n >>> unlines\r\n\r\nsolve = all ((== 1) . length) . group . sort . map head . group"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport qualified Data.Set as Set\r\n\r\nsolveString :: String -> String\r\nsolveString str = if helper Set.empty str '1' then \"Yes\" else \"No\" where\r\n helper :: Set.Set Char -> String -> Char -> Bool\r\n helper _ [] _ = True\r\n helper set (ch : chs) lastChar | Set.member ch set && ch /= lastChar = False \r\n | otherwise = helper (Set.insert ch set) chs ch\r\n\r\nsolve :: Integer -> IO ()\r\nsolve t\r\n | t == 0 = putStr \"\"\r\n | otherwise = do\r\n n <- getLine\r\n string <- getLine \r\n putStrLn $ solveString string\r\n solve (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine\r\n solve (read t)"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\nsolve l = let\n chunks = L.group l\n chunksFirst = map head chunks\n chunksFirstUniq = S.fromList chunksFirst\n in\n if length chunksFirst == length chunksFirstUniq then \"YES\" else \"NO\"\n\nsolveAll [] = []\nsolveAll (l1:l2:lrest) = (solve l2):(solveAll lrest)\n\nmain = do\n stdin <- getContents\n let _lines = lines stdin\n let l1:lrest = _lines\n let n = (read :: String -> Int) l1\n let answers = solveAll lrest\n sequence [putStrLn a | a <- answers]\n"}, {"source_code": "import Data.List\r\nimport Data.Function\r\n\r\nsolve [] = [\"\"]\r\nsolve (x:xs) = [answer $ head xs] ++ (solve $ tail xs)\r\n where \r\n answer x = if isNice x\r\n then \"YES\"\r\n else \"NO\"\r\n \r\n isNice x = all (== True) $ \r\n map (\\x -> all (== True) $ map snd x) $\r\n map isGood $ map (\\x -> map snd x) $ \r\n groupBy ((==) `on` fst) $\r\n sort $ \r\n zip x [0..]\r\n isGood (x:xs) = scanl (\\x y -> if (fst x) + 1 == y \r\n then (y, (snd x) && True) \r\n else (y, False)) (x, True) xs\r\n\r\nmain = interact $ unlines . helper . lines\r\n where\r\n helper (x:xs) = solve xs"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List ( group, nub )\n\n\nisSuspicious :: String -> String\nisSuspicious tasks\n | taskList == nub taskList = \"YES\"\n | otherwise = \"NO\"\n where\n taskList = group tasks\n\n\nsolve :: IO String\nsolve = do\n stringLength <- getLine\n tasks <- getLine\n return $ isSuspicious tasks\n\n\nsolution :: Int -> IO [String]\nsolution 0 = return []\nsolution test = do\n answer <- solve\n rest <- solution (test - 1)\n return $ answer : rest\n\n\nmain :: IO ()\nmain = do\n tests <- getLine\n results <- solution (read tests)\n mapM_ putStrLn results\n"}], "src_uid": "3851854541b4bd168f5cb1e8492ed8ef"} {"source_code": "import Data.Set\n\nmain = do\n getLine\n interact $ unlines.solve empty.reverse.lines\n\nsolve _ [] = []\nsolve s (x:xs)\n |not(x`member`s) = x:solve(x`insert`s) xs\n |otherwise = solve s xs", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\nmain = C.interact $ C.unlines . reverse . fst . foldr f ([],S.empty) . tail . C.lines . C.filter (/='\\r')\nf n (l,s) | S.member n s = (l,s)\n | True = (n:l,S.insert n s)"}], "negative_code": [], "src_uid": "18f4d9262150294b63d99803250ed49c"} {"source_code": "import Control.Monad (replicateM_)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n _ <- getLine\n l1 <- getLine\n let a = (map read . words) l1 :: [Int]\n _ <- getLine\n l2 <- getLine\n let b = (map read . words) l2 :: [Int]\n let ma = maximum a\n mb = maximum b\n putStrLn $\n if ma == mb\n then \"Alice\\nBob\"\n else if ma > mb then \"Alice\\nAlice\" else \"Bob\\nBob\"\n", "positive_code": [{"source_code": "import Data.List\r\nimport Data.Char\r\nimport Data.Array\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n\tn <- getLine\r\n\tlet number = read n :: Int\r\n\tsolve number number\r\n\t\r\nsolve number 0 = return ()\r\nsolve number current = do\r\n\tn <- getLine\r\n\talice <- getLine\r\n\tlet aliceCards = (map read $ words alice) :: [Int]\r\n\tm <- getLine\r\n\tbob <- getLine\r\n\tlet bobCards = (map read $ words bob) :: [Int]\r\n\tif (maximum aliceCards) > (maximum bobCards) then do\r\n\t\tputStrLn \"Alice\"\r\n\t\tputStrLn \"Alice\"\r\n\telse if (maximum aliceCards == maximum bobCards) then do\r\n\t\tputStrLn \"Alice\"\r\n\t\tputStrLn \"Bob\"\r\n\t\telse do\r\n\t\t\tputStrLn \"Bob\"\r\n\t\t\tputStrLn \"Bob\"\r\n\tsolve number (current - 1)\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\nimport Data.Word (Word32)\r\nimport System.Environment (getArgs)\r\nimport GHC.Conc (par, pseq)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Control.Monad.State (State, evalState, gets, MonadState (get, put), replicateM)\r\nimport Control.Applicative (Applicative(liftA2))\r\nimport Control.Arrow ((>>>))\r\n\r\ndata TC = TC { a::[Int], b::[Int] }\r\n\r\naliceBob x = if x then \"Alice\" else \"Bob\"\r\n\r\nsolve TC{..} = (aliceBob $ ma >= mb, aliceBob $ ma > mb)\r\n where\r\n ma = maximum a\r\n mb = maximum b\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (\\(x, y) -> [x, y]) >>> concat >>> map C.pack >>> C.unlines\r\n\r\nscan =\r\n numberOf $ TC <$> numberOf int <*> numberOf int\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case { s:ss -> put ss >> return s }\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10^p)*) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case { [] -> return []; _ -> (:) <$> s <*> many s }\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2..4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a,b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [], "src_uid": "581c89736e549300c566e4700b741906"} {"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- diglog.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\nimport Prelude hiding (getLine)\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.List\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Tuple\n\nri = readInts <$> B.getLine :: IO [Int]\n where\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n dropSpace = B.dropWhile isSpace\n\nboth f (a,b) = (f a, f b)\n\ndiglog n = (length . show) (n::Int)\n\napplyIf p f x | (p x) = f x\n | otherwise = x\n\njustIfNonzero n | (n > 0) = Just n\n | (n == 0) = Nothing\n | otherwise = error \"Logic error (neg cnt)\"\n\nmain :: IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n [_n] <- ri\n replicateM 2 ri\n mapM_ (putStrLn.show.solve) tcs\n\nsolve [xs,ys] = cntLarge + cntReduceTo1 + cntReduceBoth\n where\n bothRm f = removeCommonElems . both f\n\n s1 @(_,_) = bothRm (Map.fromListWith (+) . (`zip` ones)) $ (xs,ys)\n\n s3 @(_,_) = bothRm (Map.mapKeysWith (+) (applyIf isLarge diglog)) $ s1\n\n s41@(_,_) = reduce1 $ s3\n s42@(_,_) = swap . reduce1 . swap $ s41\n\n isLarge = (>9)\n\n cntLarge = sum . map snd . filter (isLarge.fst) . uncurry (++) . both Map.toList $ s1\n\n cntReduceTo1 = ((-) `on` (mapLen.fst)) s3 s42\n\n cntReduceBoth = (*2) . mapLen . fst $ s42\n\nsolve _ =\n error \"Wrong input parsing\"\n\nremoveCommonElems (xm,ym) = (xxm,yym)\n where\n common = (Map.intersectionWith min) xm ym\n (xxm,yym) = both (mapsub common) (xm,ym)\n\n mapsub = flip (Map.differenceWith f) where f a b = justIfNonzero (a - b)\n\nreduce1 = until (not.p) f\n where\n p (xm,ym) = (1 `Map.member` ym) && (not.null $ xm)\n\n f (xm,ym) = (reduceByOne xkey xm,\n reduceByOne 1 ym)\n where\n reduceByOne = Map.update (justIfNonzero . pred)\n\n xkey = fst . fromJust . Map.lookupGE 0 $ xm -- any key from xm\n\nmapLen = Map.foldl (+) 0\n\nones = [1,1..] :: [Int]\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.List (group, sort, intercalate)\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (Heap, Heap)\ntype Solver = Domain -> IO ()\n-- type Heap = Set.MaxHeap Int\ntype Heap = Map.IntMap Int\n\n\n\nfromList :: [Int] -> Heap\nfromList = Map.fromListWith (+) . Prelude.map (,1)\n\nheapInsert :: Int -> Heap -> Heap\nheapInsert x = Map.insertWith (+) x 1\n\nviewMax :: Heap -> Maybe (Int, Heap)\nviewMax h \n | Map.null h = Nothing\n | otherwise = \n Just (k, if i == 1 then Map.deleteMax h else Map.insert k (i-1) h)\n where \n (k, i) = Map.findMax h\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nchunks :: Int -> [a] -> [[a]]\nchunks _ [] = []\nchunks n l\n | n > 0 = (take n l) : (chunks n (drop n l))\n | otherwise = error \"Negative or zero n\"\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n return (fromList xs, fromList ys)\n\n\nlog10 :: Int -> Int\nlog10 x = if x < 10 then 1 else 1 + log10 (x `div` 10)\n\npushWithLog10 :: Int -> Heap -> Heap\npushWithLog10 x s = heapInsert (log10 x) s\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve ps = print $ uncurry go ps\n where \n go xss yss = case (viewMax xss, viewMax yss) of\n (Just (x, xs) , Just (y, ys)) -> f \n where f \n | x == y = go xs ys\n | x < y = 1 + go xss (pushWithLog10 y ys)\n | x > y = 1 + go (pushWithLog10 x xs) yss\n _ -> 0\n\n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nchunks :: Int -> [a] -> [[a]]\nchunks _ [] = []\nchunks n l\n | n > 0 = (take n l) : (chunks n (drop n l))\n | otherwise = error \"Negative or zero n\"\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n -- let target = [295, 268, 276, 153, 153, 296, 61] \n -- if take (length target) xs == target \n -- then mapM_ print (chunks 20 ys)\n -- else return ()\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = log10 k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nunfold :: [(Int, Int)] -> [Int]\nunfold [] = []\nunfold ((x,n):rest) = replicate n x++unfold rest\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n-- toBothList :: (IntMap Int, IntMap Int) -> ([(Int, Int)], [(Int, Int)])\ntoBothList (xs, ys) = (toDebugList xs, toDebugList ys)\n\ntoDebugList x = (length y,y)\n where y = unfold $ Map.toAscList x\n\ndomainDiff (a, b) (x, y)= (diff a x, diff b y)\n\nlog10 :: Int -> Int\nlog10 x = if x < 10 then 1 else 1 + log10 (x `div` 10)\n\ndiff :: IntMap Int -> IntMap Int -> IntMap Int\ndiff = (kill0.) . (Map.differenceWith ((Just .). (-)))\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n let (k1,k2) = toBothList $ domainDiff d d'\n in traceShow s' $ traceShow k1 $ traceShow k2 $ traceShow \"-------\"$ (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = Map.unionWith (-) xs common\n yms = Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, swap nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' $ swap nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where ns = Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue ns ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) ns resGs)\n\n-- 3. match n*x to n*y : cost 2 (saving 2, n > 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n filter1 = Map.filterWithKey (\\k _ -> k > 1)\n xls = filter1 $ Map.mapKeysWith (+) (log10 ) xs\n yls = filter1 $ Map.mapKeysWith (+) (log10 ) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | log10 k == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n traceShow (totalCost, savings, rest)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchN, matchNN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n\nccount :: ([Int], [Int], [Int]) -> (Int, Int, Int)\nccount (xs, ys, zs) = (length xs, length ys, length zs)\n\ngo :: [Int] -> ([Int], [Int], [Int])\ngo [] = ([],[],[])\ngo (x:xs)\n | x == 1 = (x:as, bs, cs)\n | x > 10 = (as, bs, x:cs)\n | otherwise = (as, x:bs, cs)\n where (as,bs,cs) = go xs\n \nx1 = [295,268,276,153,153,296,61,4,150,145,62,64,109,132,250,265,85,56,297,224]\nx2= [38,32,130,254,141,6,250,34,255,14,115,207,75,268,150,144,177,46,177,242]\nx3= [243,220,266,205,187,165,207,211,291,233,251,108,200,37,203,289,48,129,222,61]\nx4= [285,34,296,47,291,285,149,134,217,166,75,270,189,114,259,170,67,213,257,245]\n\ny1 =[95,284,23,184,124,77,282,159,229,186,192,155,31,146,51,138,149,64,241,23]\ny2=[219,298,54,174,84,19,54,86,5,289,12,78,15,259,248,262,136,233,121,76]\ny3=[131,183,68,133,187,298,143,188,64,31,275,255,127,193,282,189,109,35,106,81]\ny4=[255,276,168,74,293,174,78,140,194,291,218,233,98,179,244,18,185,180,20,94]\n\ncc :: (Int, Int, Int) -> Int\ncc (a, b, c) = b + 2 * c\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n let xs = x1 ++ x2 ++ x3 ++ x4\n let ys = y1 ++ y2 ++ y3 ++ y4\n print $ ccount $ go xs\n print $ ccount $ go ys\n print $ cc $ ccount $ go xs\n print $ cc $ ccount $ go ys\n sequence_ =<< (replicateM n $ solve <$> return (toCount xs, toCount ys))\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nchunks :: Int -> [a] -> [[a]]\nchunks _ [] = []\nchunks n l\n | n > 0 = (take n l) : (chunks n (drop n l))\n | otherwise = error \"Negative or zero n\"\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n let target = [295, 268, 276, 153, 153, 296, 61] \n if take (length target) xs == target \n then mapM_ print (chunks 20 ys)\n else return ()\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' $ swap nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where ns = Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue ns ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) ns resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) xs\n yls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \nx1 = [295,268,276,153,153,296,61,4,150,145,62,64,109,132,250,265,85,56,297,224]\nx2= [38,32,130,254,141,6,250,34,255,14,115,207,75,268,150,144,177,46,177,242]\nx3= [243,220,266,205,187,165,207,211,291,233,251,108,200,37,203,289,48,129,222,61]\nx4= [285,34,296,47,291,285,149,134,217,166,75,270,189,114,259,170,67,213,257,245]\n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nchunks :: Int -> [a] -> [[a]]\nchunks _ [] = []\nchunks n l\n | n > 0 = (take n l) : (chunks n (drop n l))\n | otherwise = error \"Negative or zero n\"\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n let target = [295, 268, 276, 153, 153, 296, 61] \n if take (length target) xs == target \n then mapM_ print (chunks 20 xs) >> mapM_ print (chunks 20 ys)\n else return ()\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' $ swap nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where ns = Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue ns ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) ns resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) xs\n yls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nchunks :: Int -> [a] -> [[a]]\nchunks _ [] = []\nchunks n l\n | n > 0 = (take n l) : (chunks n (drop n l))\n | otherwise = error \"Negative or zero n\"\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n let target = [295, 268, 276, 153, 153, 296, 61] \n if take (length target) xs == target \n then mapM_ print $ chunks 20 xs\n else return ()\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' $ swap nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where ns = Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue ns ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) ns resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) xs\n yls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n let target = [295, 268, 276, 153, 153, 296, 61] \n if take (length target) xs == target \n then print xs\n else return ()\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' $ swap nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where ns = Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue ns ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) ns resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) xs\n yls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' $ swap nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = traceShow ((nxs, nys), gs) (savings, (nxs, nys))\n where gs = Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue gs ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) gs resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n\n xls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) xs\n yls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where gs = Map.mapKeysWith (+) (length.show) $ Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue gs ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) gs resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n\n xls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) xs\n yls = Map.mapKeysWith (+) (length . show)$ Map.filterWithKey (\\k _ -> k > 1) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 4 * v \n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where gs = Map.mapKeysWith (+) (length.show) $ Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue gs ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) gs resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.filterWithKey (\\k _ -> k > 1) $ Map.mapKeysWith (+) (length . show) xs\n yls = Map.filterWithKey (\\k _ -> k > 1) $ Map.mapKeysWith (+) (length . show) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 2 * v * (length (show k) - 1)\n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where gs = Map.mapKeysWith (+) (length.show) $ Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue gs ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) gs resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.filterWithKey (\\k _ -> k > 1) $ Map.mapKeysWith (+) (length . show) xs\n yls = Map.filterWithKey (\\k _ -> k > 1) $ Map.mapKeysWith (+) (length . show) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchNN, matchN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Tuple \nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.IntMap as Map\nimport Data.IntMap \nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = (IntMap Int, IntMap Int)\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n ys <- readChar8\n return (toCount xs, toCount ys)\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\ntoCount :: [Int] -> IntMap Int\ntoCount xs = Map.fromListWith (+) (zip xs $ cycle [1])\n\n-- sub if k have the same length as in gs\nsubValue :: IntMap Int -> Int -> Int -> (IntMap Int, Int)\nsubValue gs k c \n | l `Map.member` gs = (subCount gs l cSub, c - cSub)\n | otherwise = (gs,c)\n where \n l = length $ show k\n cSub = min (gs Map.! l) c\n\n\nsubCount :: IntMap Int -> Int -> Int -> IntMap Int\nsubCount count k i = Map.update (\\x -> Just (x - i)) k count\n\nkill0 :: IntMap Int -> IntMap Int\nkill0 = Map.filter (/=0)\n-- 1: no change\n-- x: 1:1\n-- n*x: 1:n 2:1\n\ndomainDiff (a, b) (x, y)= (Map.difference a x, Map.difference b y)\n\nfoldWithSavings :: [Domain -> (Int, Domain)] -> Domain -> ([Int], Domain)\nfoldWithSavings fs d = Prelude.foldl (\\(s,d) f -> let (s',d') = f d in \n -- traceShow (s',domainDiff d d') \n (s':s,d')) ([],d) fs\n\n-- 1. cancellate all matched: cost 0 \ncancellateMatched :: Domain -> (Int, Domain)\ncancellateMatched (xs, ys) = (savings, (xms, yms))\n where common = Map.intersectionWith min xs ys\n xms = kill0 $ Map.unionWith (-) xs common\n yms = kill0 $ Map.unionWith (-) ys common\n savings = sum $ Map.elems $ Map.mapWithKey computeSave common\n computeSave k v\n | k == 1 = 0\n | k < 10 = 2 * v\n | otherwise = 2 * v * (length (show k) - 1)\n\n-- 2. match the n to n*x digit: cost 1(saving 2)\nmatchN :: Domain -> (Int, Domain)\nmatchN xs = (savings1 + savings2, nnxs)\n where \n (savings1, nxs) = matchN' xs\n (savings2, nnxs) = matchN' nxs\nmatchN' :: Domain -> (Int, Domain)\nmatchN' (xs, ys) = (savings, (nxs, nys))\n where gs = Map.mapKeysWith (+) (length.show) $ Map.filterWithKey (\\k _ -> k > 1 && k < 10) xs\n -- sub if k have the same length as in gs\n (resGs, nys) = (id *** kill0) $ Map.mapAccumWithKey subValue gs ys\n nxs = kill0 $ unionWith (const) resGs xs\n savings = sum $ Map.elems $ Map.map (2*) (differenceWith (\\x y -> Just $ x - y) gs resGs)\n\n-- 3. match n*x to n*y : cost 2(saving 2)\nmatchNN :: Domain -> (Int, Domain)\nmatchNN (xs, ys) = (savings, (nxs, nys))\n where \n xls = Map.filterWithKey (\\k _ -> k > 1) $ Map.mapKeysWith (+) (length . show) xs\n yls = Map.filterWithKey (\\k _ -> k > 1) $ Map.mapKeysWith (+) (length . show) ys\n common = Map.intersectionWith min xls yls\n nxs = kill0 . snd $ Map.mapAccumWithKey subValue common xs\n nys = kill0 . snd $ Map.mapAccumWithKey subValue common ys\n savings = sum $ Map.elems $ Map.map (2*) common\n\ncost :: IntMap Int -> Int\ncost = sum . Map.elems . Map.mapWithKey computeCost\n where computeCost k v\n | k == 1 = 0\n | length (show k) == 1 = 1 * v\n | otherwise = 2 * v\n\n\n-- (saving none)\n-- the following all goes down to 1\n-- 4. match the 1 to x: cost 1\n-- 5. match 1 to n*x: cost 2\n-- 6. match m to n*y : cost 3\n-- 7. match m*x to n*y : cost 4\nsolve :: Solver\nsolve xs = \n -- traceShow (rest, totalCost, savings)$ \n print (totalCost - sum savings)\n where \n (savings, rest) = foldWithSavings [cancellateMatched, matchN, matchNN] xs\n totalCost = cost (uncurry (unionWith (+)) xs)\n \n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}], "src_uid": "b017204679bab4c0573b03d35b8ae3f2"} {"source_code": "import Data.List\n\nrevertChanges k all@(prev:cur:next:ys)\n | k == 0 = all\n | null ys = [prev, cur', next]\n | otherwise = [prev, cur'] ++ revertChanges k' (next : ys)\n where (k', cur') = if cur - 1 > prev && cur - 1 > next\n then (k - 1, cur - 1)\n else (k, cur)\n\nmain = do\n args0 <- getLine\n args1 <- getLine\n let readInt s = read s :: Int\n readInts s n = map readInt $ take n $ words s\n [n, k] = readInts args0 2\n ys = readInts args1 (2 * n + 1)\n result = revertChanges k ys\n putStrLn $ intercalate \" \" $ map show result\n", "positive_code": [{"source_code": "import List (sort)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nsolve :: Int -> [Int] -> [Int]\nsolve 0 as = as\nsolve k (x:y:z:as)\n | y > x + 1 && y > z + 1 = x : (y-1) : (solve (k-1) (z:as))\n | otherwise = x : y : solve k (z:as)\n\nprints :: [Int] -> IO ()\nprints [] = return ()\nprints [x] = print x\nprints (x:xs) = putStr (show x ++ \" \") >> prints xs\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- reads\n prints $ solve k as"}, {"source_code": "-- Codeforces 218A\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Applicative\nimport Control.Monad.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as BC\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, k] <- (map read . words) <$> getLine\n xs <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents\n go xs 0 k\n where\n go xs i k | i == k = putStr (intercalate \" \" (map show xs))\n go (a:b:c:xs) i k = do\n let peak = a + 1 < b && c + 1 < b\n putStr (show a)\n putStr \" \"\n putStr (show $ if peak then (b - 1) else b)\n putStr \" \"\n go (c:xs) (if peak then (i + 1) else i) k\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n [_,k] <- map read.words <$> getLine\n vs <- map read.words <$> getLine\n let solve 0 xs = putStrLn.unwords.map show $ xs\n solve rest (x:y:z:xs)\n | xz = putStr (shows x\" \") >> putStr (shows(y-1)\" \") >> solve (rest-1) (z:xs)\n | otherwise = putStr (shows x\" \") >> putStr (shows y\" \") >> solve rest (z:xs)\n solve k vs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nf :: Int -> [Int] -> [Int]\nf 0 xs = xs\nf n (x:y:z:xs) = if p [x,y,z] then x:(y-1):tail else x:y:tail'\n where\n p [a,b,c] = (b-1) > a && (b-1) > c\n tail = f (n-1) (z:xs)\n tail' = f n (z:xs)\n\nmain = do\n k <- head . fmap read . tail . words <$> getLine\n ps <- fmap read . words <$> getLine \n mapM_ (putStr . (++ \" \") . show) (f k ps)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Int). words $ line1\n\t\tarr = map (\\x -> read x :: Int). words $line2\n\t\tsolve _ [] _ = []\n\t\tsolve lst aas@(a:b:as) k \n\t\t | k == 0 = aas\n\t\t | a -1> lst && a -1 > b = (a-1): b : solve (b) as (k-1) \n\t\t | otherwise = a:b : solve b as k\n----\tprint n\n--\tprint k\n--\tprint arr\n\tmapM_ (\\x -> putStr $ show x ++ \" \") $ head arr : solve (head arr) (tail arr) k\n"}], "negative_code": [{"source_code": "import List (sort)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nsolve :: Int -> [Int] -> [Int]\nsolve 0 as = as\nsolve k (x:y:z:as)\n | y > x + 1 && y > z + 1 = x : (y-1) : (solve (k-1) (z:as))\n | otherwise = solve k (z:as)\n\nprints :: [Int] -> IO ()\nprints [] = return ()\nprints [x] = print x\nprints (x:xs) = putStr (show x ++ \" \") >> prints xs\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- reads\n prints $ solve k as"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO(IOUArray)\nimport Data.List\nimport Data.Ord\n\nmain = do\n [_,k] <- map read.words <$> getLine\n vs <- map read.words <$> getLine\n let peaks = f vs\n where\n f [x] = []\n f (_:x:xs) = x:f xs\n c <- newArray (0,100) 0 :: IO (IOUArray Int Int)\n forM_ peaks $ \\p-> do\n unsafeRead c p >>= unsafeWrite c p . (1+)\n cnts <- unsafeFreeze c :: IO (UArray Int Int)\n let pmax= fst.head.filter ((k<=).snd) $ assocs cnts\n solve 0 xs = putStrLn.unwords.map show $ xs\n solve rest (x:xs)\n | x==pmax = putStr (shows(x-1)\" \") >> solve (rest-1) xs\n | otherwise = putStr (shows x\" \") >> solve rest xs\n solve k vs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Base\nimport Data.Array.IO(IOUArray)\nimport Data.List\nimport Data.Ord\n\nmain = do\n [_,k] <- map read.words <$> getLine\n vs <- map read.words <$> getLine\n let peaks = f vs\n where\n f [x] = []\n f (_:x:xs) = x:f xs\n c <- newArray (0,100) 0 :: IO (IOUArray Int Int)\n forM_ peaks $ \\p-> do\n unsafeRead c p >>= unsafeWrite c p . (1+)\n cnts <- unsafeFreeze c :: IO (UArray Int Int)\n let pmax= fst.head.filter ((k<=).snd) $ assocs cnts\n solve 0 xs = putStrLn.unwords.map show $ xs\n solve rest (x:y:xs)\n | y==pmax = putStr (shows x\" \") >> putStr (shows(y-1)\" \") >> solve (rest-1) xs\n | otherwise = putStr (shows x\" \") >> putStr (shows y\" \") >> solve rest xs\n solve k vs"}, {"source_code": "import Control.Applicative\n\nmain = do\n [_,k] <- map read.words <$> getLine\n vs <- map read.words <$> getLine\n let solve 0 xs = putStrLn.unwords.map show $ xs\n solve rest (x:y:xs) = putStr (shows x\" \") >> putStr (shows(y-1)\" \") >> solve (rest-1) xs\n solve k vs"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Int). words $ line1\n\t\tarr = map (\\x -> read x :: Int). words $line2\n\t\tsolve _ [] _ = []\n\t\tsolve lst (a:b:as) k \n\t\t | k <= 0 = (a:b:as)\n\t\t | a > lst && a > b = (a-1): b : solve (b) as (k-1) \n\t\t | otherwise = a:b : solve b as k\n\tprint n\n\tprint k\n\tprint arr\n\tprint $ head arr : solve (head arr) (tail arr) k\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Int). words $ line1\n\t\tarr = map (\\x -> read x :: Int). words $line2\n\t\tsolve _ [] _ = []\n\t\tsolve lst (a:b:as) k \n\t\t | k <= 0 = (a:b:as)\n\t\t | a > lst && a > b = (a-1): b : solve (b) as (k-1) \n\t\t | otherwise = a:b : solve b as k\n----\tprint n\n--\tprint k\n--\tprint arr\n\tmapM_ (\\x -> putStr $ show x ++ \" \") $ head arr : solve (head arr) (tail arr) k\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Int). words $ line1\n\t\tarr = map (\\x -> read x :: Int). words $line2\n\t\tsolve _ [] _ = []\n\t\tsolve lst aas@(a:b:as) k \n\t\t | k == 0 = aas\n\t\t | a > lst && a > b = (a-1): b : solve (b) as (k-1) \n\t\t | otherwise = a:b : solve b as k\n----\tprint n\n--\tprint k\n--\tprint arr\n\tmapM_ (\\x -> putStr $ show x ++ \" \") $ head arr : solve (head arr) (tail arr) k\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tline2 <- getLine\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Int). words $ line1\n\t\tarr = map (\\x -> read x :: Int). words $line2\n\t\tsolve _ [] _ = []\n\t\tsolve lst (a:b:as) k \n\t\t | k <= 0 = (a:b:as)\n\t\t | a > lst && a > b = (a-1): b : solve (b) as (k-1) \n\t\t | otherwise = a:b : solve b as k\n\tprint n\n\tprint k\n\tprint arr\n\tmapM_ (\\x -> putStr $ show x ++ \" \") $ head arr : solve (head arr) (tail arr) k\n"}], "src_uid": "1adb4675dc88208f8a05a2db49bb44cb"} {"source_code": "{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O2 #-}\n-- Data.MultiSet not available on Codeforces...\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\n-- import Data.MultiSet (MultiSet)\n-- import qualified Data.MultiSet as MultiSet\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Maybe as Maybe\n-- import Debug.Trace\n\nmain :: IO ()\nmain = BS.interact (BS.unlines . runRaw . BS.words)\n\nbs2int :: BS.ByteString -> Integer\nbs2int = fst . Maybe.fromJust . BS.readInteger\n\nint2bs :: Integer -> BS.ByteString\nint2bs = BS.pack . show\n\nrunRaw :: [BS.ByteString] -> [BS.ByteString]\nrunRaw str_data = map int2bs $ run $ map bs2int str_data\n\nrun :: [Integer] -> [Integer]\nrun (nb_testcases:testcase_data) = executeTestcases nb_testcases testcase_data\n\nexecuteTestcases :: Integer -> [Integer] -> [Integer]\nexecuteTestcases 0 _ = []\nexecuteTestcases remaining_testcases testcase_data =\n let (result, remaining_testcase_data) = executeTestcase testcase_data\n in result :\n executeTestcases (remaining_testcases - 1) remaining_testcase_data\n\nexecuteTestcase :: [Integer] -> (Integer, [Integer])\nexecuteTestcase (n:remaining_data) =\n let (voter_config_data, other_remaining_data) = splitAt (fromIntegral n * 2) remaining_data\n voter_configs = extractPairs voter_config_data\n sorted_voter_configs = map (\\pairs -> (fst $ head pairs, map snd pairs)) $ groupBy (\\a b -> fst a == fst b) $ sortBy (\\a b -> fst b `compare` fst a) voter_configs\n -- _ = traceId $ \"sorted voter configs: \" ++ show sorted_voter_configs\n result = bribeVoters sorted_voter_configs n createEmptyMultiSet\n in (result, other_remaining_data)\n\nbribeVoters :: [(Integer, [Integer])] -> Integer -> FMultiSet -> Integer\nbribeVoters [] _ _ = 0\nbribeVoters ((m,prices):remaining_voter_prices) nb_remaining_voters available_voter_prices = \n let nb_voters_in_group = fromIntegral $ length prices\n nb_voters_with_smaller_m = nb_remaining_voters - nb_voters_in_group\n nb_voters_to_bribe = max 0 $ m - nb_voters_with_smaller_m\n\n group_prices_set = createFMultiSetFromList prices\n union_available_prices_set = unionFMultiSet available_voter_prices group_prices_set\n -- _ = traceId $ \"available prices to bribe \" ++ show nb_voters_to_bribe ++ \" voters: \" ++ show union_available_prices_set\n (cost_to_bribe, updated_available_prices_set) = findCheapestBribableVoters nb_voters_to_bribe union_available_prices_set\n -- _ = traceId $ \"cost to bribe: \" ++ show cost_to_bribe\n in cost_to_bribe + bribeVoters remaining_voter_prices (nb_voters_with_smaller_m + nb_voters_to_bribe) updated_available_prices_set\n\nfindCheapestBribableVoters :: Integer -> FMultiSet -> (Integer, FMultiSet)\nfindCheapestBribableVoters 0 available_prices = (0, available_prices)\nfindCheapestBribableVoters n available_prices = \n let (cheapest, updated_available_prices) = deleteFindMinFMultiSet available_prices\n (remaining_cost, final_updated_available_prices) = findCheapestBribableVoters (n-1) updated_available_prices\n in (remaining_cost + cheapest, final_updated_available_prices)\n\nextractPairs :: [Integer] -> [(Integer, Integer)]\nextractPairs [] = []\nextractPairs (a:b:remainder) = (a, b) : extractPairs remainder\n\ntype FMultiSet = Map Integer Integer\n\ncreateEmptyMultiSet :: FMultiSet\ncreateEmptyMultiSet = Map.empty\n\ncreateFMultiSetFromList :: [Integer] -> FMultiSet\ncreateFMultiSetFromList list = \n let sortedList = sort list\n groupedPrices = map (\\prices -> (head prices, fromIntegral $ length prices)) $ group sortedList\n in Map.fromList groupedPrices\n\nunionFMultiSet :: FMultiSet -> FMultiSet -> FMultiSet\nunionFMultiSet = Map.unionWith (+) \n\ndeleteFindMinFMultiSet :: FMultiSet -> (Integer, FMultiSet)\ndeleteFindMinFMultiSet map =\n let (price, frequency) = Map.findMin map\n updated_map = \n if frequency == 1\n then Map.delete price map\n else Map.insert price (frequency - 1) map\n in (price, updated_map)", "positive_code": [{"source_code": "{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O2 #-}\n-- Data.MultiSet not available on Codeforces...\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\n-- import Data.MultiSet (MultiSet)\n-- import qualified Data.MultiSet as MultiSet\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Maybe as Maybe\n-- import Debug.Trace\n\nmain :: IO ()\nmain = BS.interact (BS.unlines . runRaw . BS.words)\n\nbs2int :: BS.ByteString -> Integer\nbs2int = fst . Maybe.fromJust . BS.readInteger\n\nint2bs :: Integer -> BS.ByteString\nint2bs = BS.pack . show\n\nrunRaw :: [BS.ByteString] -> [BS.ByteString]\nrunRaw str_data = map int2bs $ run $ map bs2int str_data\n\nrun :: [Integer] -> [Integer]\nrun (nb_testcases:testcase_data) = executeTestcases nb_testcases testcase_data\n\nexecuteTestcases :: Integer -> [Integer] -> [Integer]\nexecuteTestcases 0 _ = []\nexecuteTestcases remaining_testcases testcase_data =\n let (result, remaining_testcase_data) = executeTestcase testcase_data\n in result :\n executeTestcases (remaining_testcases - 1) remaining_testcase_data\n\nexecuteTestcase :: [Integer] -> (Integer, [Integer])\nexecuteTestcase (n:remaining_data) =\n let (voter_config_data, other_remaining_data) = splitAt (fromIntegral n * 2) remaining_data\n voter_configs = extractPairs voter_config_data\n sorted_voter_configs = map (\\pairs -> (fst $ head pairs, map snd pairs)) $ groupBy (\\a b -> fst a == fst b) $ sortBy (\\a b -> fst b `compare` fst a) voter_configs\n -- _ = traceId $ \"sorted voter configs: \" ++ show sorted_voter_configs\n result = bribeVoters sorted_voter_configs n createEmptyMultiSet\n in (result, other_remaining_data)\n\nbribeVoters :: [(Integer, [Integer])] -> Integer -> FMultiSet -> Integer\nbribeVoters [] _ _ = 0\nbribeVoters ((m,prices):remaining_voter_prices) nb_remaining_voters available_voter_prices = \n let nb_voters_in_group = fromIntegral $ length prices\n nb_voters_with_smaller_m = nb_remaining_voters - nb_voters_in_group\n nb_voters_to_bribe = max 0 $ m - nb_voters_with_smaller_m\n\n group_prices_set = createFMultiSetFromList prices\n union_available_prices_set = unionFMultiSet available_voter_prices group_prices_set\n -- _ = traceId $ \"available prices to bribe \" ++ show nb_voters_to_bribe ++ \" voters: \" ++ show union_available_prices_set\n (cost_to_bribe, updated_available_prices_set) = findCheapestBribableVoters nb_voters_to_bribe union_available_prices_set\n -- _ = traceId $ \"cost to bribe: \" ++ show cost_to_bribe\n in cost_to_bribe + bribeVoters remaining_voter_prices (nb_voters_with_smaller_m + nb_voters_to_bribe) updated_available_prices_set\n\nfindCheapestBribableVoters :: Integer -> FMultiSet -> (Integer, FMultiSet)\nfindCheapestBribableVoters 0 available_prices = (0, available_prices)\nfindCheapestBribableVoters n available_prices = \n let (cheapest, updated_available_prices) = deleteFindMinFMultiSet available_prices\n (remaining_cost, final_updated_available_prices) = findCheapestBribableVoters (n-1) updated_available_prices\n in (remaining_cost + cheapest, final_updated_available_prices)\n\nextractPairs :: [Integer] -> [(Integer, Integer)]\nextractPairs [] = []\nextractPairs (a:b:remainder) = (a, b) : extractPairs remainder\n\ntype FMultiSet = Map Integer Integer\n\ncreateEmptyMultiSet :: FMultiSet\ncreateEmptyMultiSet = Map.empty\n\ncreateFMultiSetFromList :: [Integer] -> FMultiSet\ncreateFMultiSetFromList list = \n let sortedList = sort list\n groupedPrices = map (\\prices -> (head prices, fromIntegral $ length prices)) $ group sortedList\n in Map.fromList groupedPrices\n\nunionFMultiSet :: FMultiSet -> FMultiSet -> FMultiSet\nunionFMultiSet = Map.unionWith (+) \n\ndeleteFindMinFMultiSet :: FMultiSet -> (Integer, FMultiSet)\ndeleteFindMinFMultiSet map =\n let (price, frequency) = Map.findMin map\n updated_map = \n if frequency == 1\n then Map.delete price map\n else Map.insert price (frequency - 1) map\n in (price, updated_map)"}], "negative_code": [], "src_uid": "cc64dfbaadc7f9deae23c71df52d7326"} {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = [Int]\r\ntype OutType = Bool\r\n\r\nsolve :: InType -> OutType\r\nsolve [] = True\r\nsolve (x : t) = go x t || go (x - 1) t || go (x + 1) t\r\n where go _ [] = True\r\n go was (x' : t')\r\n | abs (x' - was) <= 2 = go (was + 1) t'\r\n | otherwise = False\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, s] = toArr s\r\nreceive _ = error \"input error\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showB . solve . receive) . chunksOf 2 . tail . lines\r\n where showB True = \"YES\"\r\n showB False = \"NO\"\r\n\r\n", "positive_code": [{"source_code": "showB x = if x then \"YES\" else \"NO\"\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nsolve :: [Int] -> Bool\r\nsolve x = let n = length x in (last x - head x) <= n+1\r\n\r\nreceive :: [String] -> [Int]\r\nreceive = map read . words . last\r\n\r\nmain = interact $ unlines . map (showB . solve . receive) . chunksOf 2 . tail . lines"}, {"source_code": "-- {-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\n\r\nreadt = read . T.unpack\r\nshowt = T.pack . showB\r\n\r\nshowB x = if x then \"YES\" else \"NO\"\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nsolve :: [Int] -> Bool\r\nsolve x = let n = length x in (last x - head x) <= n+1\r\n\r\nreceive :: [T.Text] -> [Int]\r\nreceive = map readt . T.words . last\r\n\r\nmain = TI.interact $ T.unlines . map (showt . solve . receive) . chunksOf 2 . tail . T.lines"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\n\r\nreadt = read . T.unpack\r\nshowt = T.pack . showB\r\n\r\nshowB x = if x then \"YES\" else \"NO\"\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nsolve :: [Int] -> Bool\r\nsolve x = let n = length x in (last x - head x) <= n+1\r\n\r\nreceive :: [T.Text] -> [Int]\r\nreceive = map readt . T.words . last\r\n\r\nmain = TI.interact $ T.unlines . map (showt . solve . receive) . chunksOf 2 . tail . T.lines"}], "negative_code": [], "src_uid": "f4267120fce9304fc4c45142b60fb867"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [[n,k], xs] <- replicateM 2 ri\r\n return (n,k,xs)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (_n,k,xs) = length . filter (>k) . take k $ xs\r\n", "positive_code": [{"source_code": "module Main where\r\nimport Control.Monad\r\n\r\nsolve::Int->Int->Int \r\nsolve k x \r\n |x<=k=0\r\n |otherwise=1\r\n\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let (n:k:_)=map read (words line)::[Int]\r\n line<-getLine\r\n let nlist=map read (words line)::[Int]\r\n print$sum(map (solve k) (take k nlist))"}], "negative_code": [], "src_uid": "10927dcb59007fc3a31fdb6b5d13846f"} {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmakeList :: Int -> [[(Int,Int)]]\nmakeList n = [ [(x,y) | x <- [-n .. n]] | y <- [-n .. n]]\n\ntrim :: String -> String\ntrim = reverse . (dropWhile (`elem` \" \")) . reverse\n\ntoString :: [[(Int,Int)]] -> [String]\ntoString array = map convert array\n where\n n = (length (head array)) `div` 2\n convert list = trim$concatMap (\\(x,y) -> [toChar (n - (abs x) - (abs y)) , ' ']) list\n toChar num = if num >= 0 then (head (show num)) else ' '\n\nsolve :: Int -> [String]\nsolve = toString.makeList\n\nmain = interact$unlines.solve.read.head.words", "positive_code": [{"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nsomeFunc::IO()\nsomeFunc = (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve [x] = forM_ (map (\\b-> unwords $ map (\\a-> if a<0 then \" \" else show a) $ slv1 b x) $ slv1 x x) $ \\i -> putStrLn $ dropWhileEnd (==' ') i\nslv1 x y = [x-y..x]++[x-1,x-2..x-y]"}, {"source_code": "import Control.Monad\nimport Data.List\nsolve n = let a = scanl' (flip (:)) [0] [1..n]\n b = zipWith (++) (map (reverse . tail) a) a \n c = b ++ (reverse $ init b)\n pad n x = (replicate (1+(4*n - length x)`div`2) ' ') ++ x\n in map (pad n. concat . intersperse \" \" . map show) c\nmain = (readLn :: IO Int) >>= \\x -> mapM putStrLn $ solve x\n"}, {"source_code": "-- \n-- 0\n-- 0 1 0\n-- 0 1 2 1 0\n-- 0 1 2 3 2 1 0\n-- 0 1 2 3 4 3 2 1 0\n-- 0 1 2 3 4 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 7 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 7 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 6 5 4 3 2 1 0\n-- 0 1 2 3 4 5 4 3 2 1 0\n-- 0 1 2 3 4 3 2 1 0\n-- 0 1 2 3 2 1 0\n-- 0 1 2 1 0\n-- 0 1 0\n-- 0\n\ngetNumbers :: Int -> [Int]\ngetNumbers n = xs ++ [n] ++ (reverse xs)\n where\n xs = [0..n-1]\n\nmyGetLine :: Int -> Int -> String\nmyGetLine n m = spaces ++ (foldl myConcat (show (head xs)) (tail xs))\n where\n spaces = replicate (2*(n-m)) ' '\n myConcat s x = s ++ \" \" ++ show x\n xs = getNumbers m\n\nsolve :: Int -> IO ()\nsolve n = sequence_ (map printLine (getNumbers n))\n where\n printLine :: Int -> IO ()\n printLine m = putStrLn (myGetLine n m)\n\nmain :: IO ()\nmain = readLn >>= solve\n"}, {"source_code": "\nstr = unwords . map show . nums\nnums n = [0..n] ++ [n-1,n-2..0]\nmain = do\n n <- read `fmap` getLine\n let sol = map f $ nums n\n f k = replicate ((n-k)*2) ' ' ++ str k\n putStr . unlines $ sol\n"}, {"source_code": "str = unwords . map show . nums\nnums n = [0..n] ++ [n-1,n-2..0]\nmain = do\n n <- read `fmap` getLine\n let sol = map f $ nums n\n f k = replicate ((n-k)*2) ' ' ++ str k\n putStr . unlines $ sol\n"}, {"source_code": "import Data.List\nf n = [0 .. n] ++ [n - 1, n - 2 .. 0]\ng n x = (replicate (2 * (n - x)) ' ') ++ (intersperse ' ' $ concatMap show $ f x)\nmain = interact $ unlines.(\\n -> map (g n) (f n)).read"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n readInt\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve n = unlines [ replicate (abs i * 2) ' ' ++ unwords (map show row')\n | i <- [-n..n]\n , let row = [0..n - abs i]\n , let row' = row ++ tail (reverse row)\n ]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= mapM_ putStrLn . solve\n\nsolve :: Int -> [String]\nsolve n = [ replicate (2 * (n - i)) ' ' ++ unwords (map show $ [0..i-1] ++ [i,i-1..0]) | i <- [0..n] ++ [n-1, n-2 .. 0] ]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n n <- readLn\n forM_ [-n.. -1] $ \\i -> putStrLn $ str n (-i)\n forM_ [0..n] $ \\i -> putStrLn $ str n i\nstr n i = replicate (2*i) ' ' ++\n unwords (map show $ [0..n-i] ++ [n-i-1,n-i-2..0])\n"}, {"source_code": "import Data.List\n\n-- createLine :: Int -> [Int]\n-- createLine n =\n-- r ++ tail (reverse r)\n-- where r = take n [0..]\n\n-- createTriangle :: Int -> [[Int]]\n-- createTriangle n\n-- | n == 0 = []\n-- | otherwise = createLine n : createTriangle (n-1)\n\n-- createDiamond :: Int -> [[Int]]\n-- createDiamond n =\n-- reverse (tail t) ++ t\n-- where t = createTriangle n\n\n-- spaces :: Int -> String\n-- spaces n\n-- | n == 0 = []\n-- | otherwise = ' ' : spaces (n-1)\n\n-- drawLine :: Int -> [Int] -> String\n-- drawLine r l =\n-- spaces ((length l)*2-1) ++ correctLine l ++ spaces ((length l)*2-1)\n-- where\n-- correctLine :: [Int] -> String\n-- correctLine [] = \"\"\n-- correctLine (n:ns) = \n\nf n = [0..n] ++ [n-1, n-2..0]\ng n x = (replicate (2 * (n - x)) ' ') ++ (intersperse ' ' $ concatMap show $ f x)\nmain = interact $ unlines . (\\n -> map (g n) (f n)) . read\n"}, {"source_code": "import Data.List\nline n = intercalate \" \" . map show $ [0..n] ++ [n-1, n-2..0]\nspacesLine m n = replicate (2*m-2*n) ' ' ++ line n\nsolve n = map (spacesLine n) $ [0..n] ++ [n-1, n-2..0]\nmain = fmap read getLine >>= mapM putStrLn . solve\n"}, {"source_code": "import Data.List\nmain = do\n n <- read `fmap` getLine\n let s1 = reverse $ scanl (\\s _ -> ' ':s) [] [1..n]\n s2 = scanl (\\l i -> i:l) ['0'] $ take n ['1'..]\n s3 = zipWith (\\a b@(_:bs) -> a ++ reverse bs ++ b) s1 s2\n s4 = s3 ++ tail (reverse s3)\n mapM_ (putStrLn . unwords . map (:[])) s4\n"}, {"source_code": "r = read::String->Int\nmain=interact$stripLast.mirror.build.r\nlistToStr = unwords.map show\nbuild n = f' n 0\n where f' n d\n | n < d = \"\"\n | otherwise = (replicate (2*(n-d)) ' ')\n ++ listToStr [0..d]\n ++ (if d == 0 then \"\" else \" \")\n ++ listToStr [(d-1),(d-2)..0]\n ++ \"\\n\"\n ++ f' n (d+1)\nmirror s = s ++ m' s\n where m' = unlines.tail.reverse.lines\nstripLast s = take (length s - 1) s\n \n \n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\nsolve :: Int -> String\nsolve n = rec $ [0..n]++[n-1,n-2..0]\n where\n rec [] = \"\"\n rec (x:xs) = now++(rec xs)\n where\n now = (take ((n-x)*2) (repeat ' '))++(intersperse ' ' (foldl (\\st -> \\i -> st++(show i)) \"\" $ [0..x]++[x-1,x-2..0]))++\"\\n\"\nmain = do puts.init.solve =<< (scan :: IO Int)"}, {"source_code": "r = read::String->Int\nmain=interact$stripLast.mirror.build.r\nlistToStr = unwords.map show\nbuild n = f' n 0\n where f' n d\n | n < d = \"\"\n | otherwise = (replicate (2*(n-d)) ' ')\n ++ listToStr [0..d]\n ++ (if d == 0 then \"\" else \" \")\n ++ listToStr [(d-1),(d-2)..0]\n ++ \"\\n\"\n ++ f' n (d+1)\nmirror s = s ++ m' s\n where m' = unlines.tail.reverse.lines\nstripLast s = take (length s - 1) s\n \n \n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line :: Int\n let result = let list = forLine n n in (reverse $ tail list) ++ list\n mapM_ putStrLn result\n\nforLine :: Int -> Int -> [String]\nforLine n 0 = [replicate (n*2) ' ' ++ \"0\"]\nforLine n x = let before = [0..(x-1)]; after = [(x-1), (x-2)..0] in [replicate ((n-x)*2) ' ' ++ (intersperse ' ' . concatMap (show)) (before ++ [x] ++ after)] ++ forLine n (x-1)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n \nmain= do\t \n\tn<- read<$> getLine ::IO Int\n\tlet s = tail $ take (n+2) $ inits [0..n] \n\tlet t = zipWith (++) s ([]: (map reverse s))\n\tlet u = t++ tail (reverse t)\n\tlet sp = ([replicate (i+i) ' '|i<-[0..n]]):: [[Char]]\n\tlet sp1 = ((reverse sp ) ++ (tail sp) )::[[Char]]\n \tlet x= intercalate \"\\n\" $ zipWith (++) sp1 (map (intercalate \" \" . map show) u)\n\tputStrLn x\n\n\t\n \n\t \n\t "}, {"source_code": "{-\nB. Present from Lena\n=====================\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nVasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n\u2009=\u20095 the handkerchief pattern should look like that:\n\n\n 0\n 0 1 0\n 0 1 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 3 4 3 2 1 0\n0 1 2 3 4 5 4 3 2 1 0\n 0 1 2 3 4 3 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0\n\nYour task is to determine the way the handkerchief will look like by the given n.\n\nInput\n------\nThe first line contains the single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20099).\n\nOutput\n------\nPrint a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.\n\nSample test(s)\n---------------\ninput\n2\noutput\n 0\n 0 1 0\n0 1 2 1 0\n 0 1 0\n 0\n\ninput\n3\noutput\n 0\n 0 1 0\n 0 1 2 1 0\n0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0\n\n-}\nimport Data.List (intercalate)\n\npattern :: Int -> [String]\npattern n = map helper (upAndDown n)\n where helper k = replicate (2 * (n - k)) ' ' ++ (intercalate \" \" . map show) (upAndDown k)\n\n \nupAndDown :: Int -> [Int]\nupAndDown 0 = [0]\nupAndDown n = tmp ++ (tail . reverse) tmp\n where tmp = [0 .. n]\n\nmain = do \n input <- getLine \n let n = read input\n mapM_ putStrLn (pattern n)\n"}, {"source_code": "import Data.List\nimport Data.Char\nmain = getLine >>= putStr.unlines.solve.read\n\nabses m = map ((m-).abs.(m-)) [0..2 * m]\n\nline n m = intersperse ' ' $ concat [replicate (n - m) ' ', map intToDigit $ abses m]\n\nsolve n = map (line n) $ abses n\n"}, {"source_code": "\nimport Data.Char\nimport Data.List\n\ntoInt :: String -> Int\ntoInt = read\n\nstrSeq :: Int -> [ [Char] ]\t\nstrSeq n \t= \t[ prefix ++ ( intersperse ' ' ( x ++ (reverse . init ) x ) ) |\n\t\t\t\t\tlet ls = ( enumFromTo 0 n ),\n\t\t\t\t\ty <- ls ++ ( reverse . init ) ls,\n\t\t\t\t\tlet x = map intToDigit (enumFromTo 0 y),\n\t\t\t\t\tlet prefix = replicate ( 2*(n - y) ) ' '\n\t\t\t\t]\n\t\t\nmain = do\n\tstrN \t<- getLine\n\tputStr $ ( unlines . strSeq . toInt ) strN\n\t\n\n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\nimport Data.Char\n-- Meat\n\nsolve :: Int -> [String]\nsolve n = fmap (buildLine n) ([0..n]++reverse[0 .. n - 1])\n\nbuildLine :: Int -> Int -> String\nbuildLine total i = doublePad total $ innerString i\n\ndoublePad :: Int -> String -> String\ndoublePad n inner = spaces ++ inner\n where spaceLen = (4 * n + 1 - length inner) `quot` 2\n spaces = replicate spaceLen ' '\n\ninnerString :: Int -> String\ninnerString 0 = \"0\"\ninnerString maxDig = intersperse ' ' (['0'..c]++ reverse [ '0' .. pred c])\n where c = intToDigit maxDig\n\n-- Shit\nmain :: IO ()\nmain = do\n [n] <- readShit\n printShitV $ solve n\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "make_row 0 = [0]\nmake_row x = [0..x] ++ [x-1, x-2 .. 0]\n\npprint :: Int -> ([[Int]] -> String)\npprint n = unlines . (map fl)\n where\n fl = fill . unwords . map show\n fill x = (spaces x) ++ x\n spaces:: String -> String\n spaces x = take ((2*n+1 - length x) `div` 2) (repeat ' ')\n\nsolve :: Int->String\nsolve x = pprint (2*x) [make_row x | x <- [0..x] ++ [x-1, x-2 .. 0]]\n\nparse = (read::String->Int)\n\nmain = interact (solve . parse)\n\n\n "}, {"source_code": "\nmain = do \n\tn<-getLine\n\tlet res1 = solve (read n) 0\n\tlet res2 = init $ unlines $reverse $ init $ lines res1\n\tputStr $ res1\n\tputStrLn res2\n\nsolve n l | l <=n = spaces ((n-l)) ++ printer (generator l) ++ \"\\n\" ++ solve n (l+1)\n | otherwise = \"\"\n\n\ngenerator n = [0,1..n-1] ++ [n,n-1..0]\n\nspaces n = replicate (2*n) ' '\n\nprinter s = init $ concat $ map (\\x-> show x ++ \" \") s\n"}, {"source_code": "join _ [] = []\njoin c [x] = x\njoin c (x:xs) = x ++ [c] ++ join c xs\n\nsolve n = map tostr a\n\twhere\n\t\ttostr lst = (take (n * 2 + 1 - length lst) $ repeat ' ') ++ (join ' ' $ map show lst)\n\t\ta = [ [0..i-1] ++ [i,i-1..0] | i <- [0..n-1] ++ [n,n-1..0] ]\n\nmain = getLine >>= putStrLn . join '\\n' . solve . read\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n\n let\n s = [[f i j | j <- [1..2*n+1]] | i <- [1..2*n+1]]\n f i j = if d <= n then intToDigit (n-d) else ' '\n where\n d = abs (i-n-1) + abs (j-n-1)\n\n putStr $ unlines $ map (dropWhileEnd isSpace . intersperse ' ') s\n"}, {"source_code": "main = do\n\tio <- getLine\n\tlet n = read io\n\tputStr $ work 0 (2*n)\n\nwork :: Int -> Int -> [Char] \nwork x 0 = pl 0 x ++ ['\\n']\nwork x sp = pre ++ work (x+1) (sp-2) ++ pre\n\t\twhere pre = replicate sp ' ' ++ pl 0 x ++ ['\\n'] \n\npl :: Int -> Int -> [Char]\npl x y \n\t| x == y = show x\n\t| otherwise = show x ++ [' '] ++ pl (x+1) y ++ [' '] ++ show x \n\n"}, {"source_code": "import Data.List\n\nprintline n x = intersperse ' ' $ take (n - x) (repeat ' ') ++ concatMap show ( [0..x] ++ drop 1 ( reverse [0 .. x] ))\nprintthing x = mapM_ (putStrLn.(printline x)) ((\\x-> x ++ (drop 1 $ reverse x)) [0..x]) \nmain = getLine >>= return.read >>= printthing\n"}, {"source_code": "import Monad\nimport Data.Char\nimport Debug.Trace\n\ndoSolve :: Int -> IO ()\ndoSolve n = doSolve' 0\n where\n with :: a -> [a] -> [a]\n with s (x:y:xs) = x : s : (with s (y:xs))\n with s xs@(x:[]) = xs\n\n adjust :: [Int] -> String\n adjust lst = let len = length lst\n tmp = (with ' ' $ map (chr . (+ ord '0')) lst)\n ret = replicate (2 * (n - len)) ' ' ++\n tmp ++ (tail $ reverse tmp)\n in ret\n\n doSolve' :: Int -> IO ()\n doSolve' i | i == n = return ()\n | otherwise = let lst = [0..i]\n in do putStrLn $ adjust lst\n doSolve' $ i + 1\n when (n - 1 /= i) $ putStrLn $ adjust lst\n\nmain :: IO ()\nmain = do cs <- getContents\n let n = read cs :: Int\n doSolve $ n + 1\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport System.Environment\nimport System.IO\n\ntype BString = B.ByteString\n\nsolve :: Int -> [String]\nsolve n = map make_line $ make_seq n\n where\n make_line :: Int -> String\n make_line n' = replicate (2 * (n - n')) ' ' ++ unwords (map show $ make_seq n')\n make_seq :: Int -> [Int]\n make_seq n = [0 .. n - 1] ++ [n, n - 1 .. 0]\n\nprocess :: State Reader [String]\nprocess = solve <$> parse\n\nmain :: IO ()\nmain = do\n args <- getArgs\n reader <- if not (null args) && head args == \"MINE\"\n then B.lines <$> (openFile \"input.txt\" ReadMode >>= B.hGetContents)\n else B.lines <$> B.getContents\n say $ evalState process reader\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\ntype Reader = [BString]\n\nclass EIO a where\n parse :: State Reader a\n\ninstance EIO Int where\n parse = state $ \\(line:rest) -> (fst $ fromJust $ B.readInt line, rest)\n\ninstance EIO [Int] where\n parse = state $ \\(line:rest) -> (map fst . mapMaybe B.readInt . B.words $ line, rest)\n\ninstance EIO BString where\n parse = state $ \\(line:rest) -> (line, rest)\n\nclass Show a => Display a where\n display :: a -> String\n display = show\n\ninstance Display String where\n display = id\n\ninstance Display [a] => Display [[a]] where\n display = unlines . map display\n\ninstance Display a => Display [a] where\n display = unwords . map display\n\ninstance Display Int\ninstance Display Double\n"}, {"source_code": "main = getLine >>= putStrLn . unlines . func' . read\n\nfunc' :: Integer -> [String]\nfunc' n = cteateSector n ++ tail ( reverse ( cteateSector n ))\n\ncteateSector :: Integer -> [String]\ncteateSector n = map insertSpaces $ reverse [strCreate kk n ++ takeWhile(/=' ') (tail (reverse (strCreate kk n))) | kk <- [0..n]]\n\t\t\twhere strCreate k n = concat [if (nn < k) then \" \" else show (nn-k ) | nn<-[0..n]]\n\n\ninsertSpaces :: String -> String\ninsertSpaces [h] = [h]\ninsertSpaces (h:str) = h : ' ' : insertSpaces str "}], "negative_code": [{"source_code": "\nmain = do \n\tn<-getLine\n\tlet res1 = solve (read n) 0\n\tlet res2 = reverse $ init $ unlines $ init $ lines res1\n\tputStr $ res1\n\tputStrLn res2\n\nsolve n l | l <=n = spaces ((n-l)) ++ printer (generator l) ++ \"\\n\" ++ solve n (l+1)\n | otherwise = \"\"\n\n\ngenerator n = [0,1..n-1] ++ [n,n-1..0]\n\nspaces n = replicate (2*n) ' '\n\nprinter s = init $ concat $ map (\\x-> show x ++ \" \") s\n"}, {"source_code": "\nmain = do \n\tn<-getLine\n\tlet res1 = solve (read n) 0\n\tlet res2 = reverse $ init $ unlines $ init $ lines res1\n\tputStr $ res1\n\tputStrLn res2\n\nsolve n l | l <=n = spaces ((n-l)) ++ printer (generator l) ++ spaces ((n-l))++ \"\\n\" ++ solve n (l+1)\n | otherwise = \"\"\n\n\ngenerator n = [0,1..n-1] ++ [n,n-1..0]\n\nspaces n = replicate (2*n) ' '\n\nprinter s = init $ concat $ map (\\x-> show x ++ \" \") s\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n\n let\n s = [[f i j | j <- [1..2*n+1]] | i <- [1..2*n+1]]\n f i j = if d <= n then intToDigit (n-d) else ' '\n where\n d = abs (i-n-1) + abs (j-n-1)\n\n putStr $ unlines $ map (intersperse ' ') s\n"}, {"source_code": "main = getLine >>= putStrLn . unlines . func' . read\n\nfunc' :: Integer -> [String]\nfunc' n = cteateSector n ++ tail ( reverse ( cteateSector n ))\n\ncteateSector :: Integer -> [String]\ncteateSector n = reverse [strCreate kk n ++ tail (reverse (strCreate kk n)) | kk <- [0..n]]\n\t\t\twhere strCreate k n = unwords [if (nn < k) then \" \" else show (nn-k ) | nn<-[0..n]]"}, {"source_code": "main = getLine >>= putStrLn . unlines . func . read \n\n\nfunc :: Integer -> [String]\nfunc 2 = [\" 0\",\" 010\",\"01210\", \" 010\",\" 0\"]\nfunc 3 = [\" 0\",\" 010\",\" 01210\",\"0123210\",\" 01210\",\" 010\",\" 0\"]\nfunc 4 = [\" 0\",\" 010\",\" 01210\",\" 0123210\",\"012343210\",\" 0123210\",\" 01210\",\" 010\",\" 0\"]\nfunc 5 = [\" 0\",\" 010\",\" 01210\",\" 0123210\",\" 012343210\",\"01234543210\",\" 012343210\",\" 0123210\",\" 01210\",\" 010\",\" 0\"]\nfunc 6 = [\" 0\",\" 010\",\" 01210\",\" 0123210\",\" 012343210\",\" 01234543210\",\"0123456543210\",\" 01234543210\",\" 012343210\",\" 0123210\",\" 01210\",\" 010\",\" 0\"]\nfunc 7 = [\" 0\",\" 010\",\" 01210\",\" 0123210\",\" 012343210\",\" 01234543210\",\" 0123456543210\",\"012345676543210\",\" 0123456543210\",\" 01234543210\",\" 012343210\",\" 0123210\",\" 01210\",\" 010\",\" 0\"]\nfunc 8 = [\" 0\",\" 010\",\" 01210\",\" 0123210\",\" 012343210\",\" 01234543210\",\" 0123456543210\",\" 012345676543210\",\"01234567876543210\",\" 012345676543210\",\" 0123456543210\",\" 01234543210\",\" 012343210\",\" 0123210\",\" 01210\",\" 010\",\" 0\"]\nfunc 9 = [\" 0\",\" 010\",\" 01210\",\" 0123210\",\" 012343210\",\" 01234543210\",\" 0123456543210\",\" 012345676543210\",\" 01234567876543210\",\"0123456789876543210\",\" 01234567876543210\",\" 012345676543210\",\" 0123456543210\",\" 01234543210\",\" 012343210\",\" 0123210\",\" 01210\",\" 010\",\" 0\"] \nfunc _ = [\"n isn't 2 - 9\"]"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nsomeFunc::IO()\nsomeFunc = (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve [x] = forM_ (map (\\b-> unwords $ map (\\a-> if a<0 then \" \" else show a) $ slv1 b x) $ slv1 x x) $ \\i -> putStrLn i\nslv1 x y = [x-y..x]++[x-1,x-2..x-y]\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line :: Int\n let result = let list = forLine n n in (reverse $ tail list) ++ list\n mapM_ print result\n\nforLine :: Int -> Int -> [String]\nforLine n 0 = [replicate (n*2) ' ' ++ \"0\"]\nforLine n x = let before = [0..(x-1)]; after = [(x-1), (x-2)..0] in [replicate (n-x) ' ' ++ (intersperse ' ' . concatMap (show)) (before ++ [x] ++ after)] ++ forLine n (x-1)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n line <- getLine\n let n = read line :: Int\n let result = let list = forLine n n in (reverse $ tail list) ++ list\n mapM_ putStrLn result\n\nforLine :: Int -> Int -> [String]\nforLine n 0 = [replicate (n*2) ' ' ++ \"0\"]\nforLine n x = let before = [0..(x-1)]; after = [(x-1), (x-2)..0] in [replicate (n-x) ' ' ++ (intersperse ' ' . concatMap (show)) (before ++ [x] ++ after)] ++ forLine n (x-1)"}, {"source_code": "\nimport Data.Char\nimport Data.List\n\ntoInt :: String -> Int\ntoInt = read\n\nstrSeq :: Int -> [ [Char] ]\t\nstrSeq n \t= \t[ prefix ++ ( intersperse ' ' ( x ++ (reverse . init ) x ) ) ++ prefix |\n\t\t\t\t\tlet ls = ( enumFromTo 0 n ),\n\t\t\t\t\ty <- ls ++ ( reverse . init ) ls,\n\t\t\t\t\tlet x = map intToDigit (enumFromTo 0 y),\n\t\t\t\t\tlet prefix = replicate ( 2*(n - y) ) ' '\n\t\t\t\t]\n\t\t\nmain = do\n\tstrN \t<- getLine\n\tputStr $ ( unlines . strSeq . toInt ) strN\n\t\n\n\n\n\n\n\n"}, {"source_code": "\nimport Data.Char\nimport Data.List\n\ntoInt :: String -> Int\ntoInt = read\n\nstrSeq :: Int -> [ [Char] ]\t\nstrSeq n \t= \t[ prefix ++ ( intersperse ' ' ( x ++ (reverse . init ) x ) ) ++ prefix |\n\t\t\t\t\tlet ls = ( enumFromTo 0 n ),\n\t\t\t\t\ty <- ls ++ ( reverse . init ) ls,\n\t\t\t\t\tlet x = map intToDigit (enumFromTo 0 y),\n\t\t\t\t\tlet prefix = replicate ( 2*(n - y) ) ' '\n\t\t\t\t]\n\t\t\nmain = do\n\tstrN \t<- getLine\n\tputStrLn $ ( unlines . strSeq . toInt ) strN\n\t\n\n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\nimport Data.Char\n-- Meat\n\nsolve :: Int -> [String]\nsolve n = fmap (buildLine n) ([0..n]++reverse[0 .. n - 1])\n\nbuildLine :: Int -> Int -> String\nbuildLine total i = doublePad total $ innerString i\n\ndoublePad :: Int -> String -> String\ndoublePad n inner = spaces ++ inner ++ spaces\n where spaceLen = (4 * n + 1 - length inner) `quot` 2\n spaces = replicate spaceLen ' '\n\ninnerString :: Int -> String\ninnerString 0 = \"0\"\ninnerString maxDig = intersperse ' ' (['0'..c]++ reverse [ '0' .. pred c])\n where c = intToDigit maxDig\n\n-- Shit\nmain :: IO ()\nmain = do\n [n] <- readShit\n printShitV $ solve n\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "make_row 0 = [0]\nmake_row x = [0..x] ++ [x-1, x-2 .. 0]\n\npprint :: Int -> ([[Int]] -> String)\npprint n = unlines . (map fl)\n where\n fl = fill . unwords . map show\n fill x = (spaces x) ++ x ++ (spaces x)\n spaces:: String -> String\n spaces x = take ((2*n+1 - length x) `div` 2) (repeat ' ')\n\nsolve :: Int->String\nsolve x = pprint (2*x) [make_row x | x <- [0..x] ++ [x-1, x-2 .. 0]]\n\nparse = (read::String->Int)\n\nmain = interact (solve . parse)\n\n\n "}, {"source_code": "r = read::String->Int\nmain=interact$stripLast.mirror.build.r\nlistToStr = unwords.map show\nbuild n = f' n 0\n where f' n d\n | n < d = \"\"\n | otherwise = (replicate (2*(n-d)) ' ')\n ++ listToStr [0..d]\n ++ \" \"\n ++ listToStr [(d-1),(d-2)..0]\n ++ \"\\n\"\n ++ f' n (d+1)\nmirror s = s ++ m' s\n where m' = unlines.tail.reverse.lines\nstripLast s = take (length s - 1) s\n \n \n"}, {"source_code": "r = read::String->Int\nmain=interact$stripLast.mirror.build.r\nlistToStr = unwords.map show\nbuild n = f' n 0\n where f' n d\n | n < d = \"\"\n | otherwise = (replicate (2*(n-d)) ' ')\n ++ listToStr [0..d]\n ++ \" \"\n ++ listToStr [(d-1),(d-2)..0]\n ++ ['\\n']\n ++ f' n (d+1)\nmirror s = s ++ m' s\n where m' = unlines.tail.reverse.lines\nstripLast s = take (length s - 1) s\n \n \n"}, {"source_code": "r = read::String->Int\nmain=interact$stripLast.mirror.build.r\nlistToStr = unwords.map show\nbuild n = f' n 0\n where f' n d\n | n < d = \"\"\n | otherwise = (replicate (2*(n-d)) ' ')\n ++ listToStr [0..d]\n ++ \" \"\n ++ listToStr [(d-1),(d-2)..0]\n ++ \" \\n\"\n ++ f' n (d+1)\nmirror s = s ++ m' s\n where m' = unlines.tail.reverse.lines\nstripLast s = take (length s - 1) s\n \n \n"}], "src_uid": "7896740b6f35010af751d3261b5ef718"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n s <- concat <$> replicateM n getLine\n putStrLn $ bool \"NO\" \"YES\" $ all (\\c -> length (filter (== c) s) `mod` n == 0) ['a' .. 'z']\n", "positive_code": [{"source_code": "import qualified Data.Map as M\n\nmain = do\n t <- getInt\n sequence $ replicate t (do\n n <- getInt\n strings <- sequence $ replicate n getLine\n let concated = foldl (++) [] strings\n cnt = countLetters concated\n corrects = (map (\\x -> (x `mod` n) == 0) cnt) :: [Bool]\n putStrLn (if foldl (&&) True corrects then \"YES\" else \"NO\")\n )\n\ncountLetters :: String -> [Int]\ncountLetters [] = []\ncountLetters str@(ch:_) = (length [x | x <- str, x == ch]):countLetters [x | x <- str, x /= ch]\n\ngetInt :: IO Int\ngetInt = do\n val <- getLine\n return $ read val\n"}, {"source_code": "import Data.List ( sort, group )\nimport Control.Monad ( replicateM_, replicateM )\n\nsolve :: Int -> [String] -> Bool\nsolve n strs = all (\\c -> mod (length c) n == 0) . group . sort $ concat strs\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n strs <- replicateM n getLine\n putStrLn (if solve n strs then \"YES\" else \"NO\")\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n s <- concat <$> replicateM n getLine\n print $ bool \"NO\" \"YES\" $ all (\\c -> length (filter (== c) s) `mod` n == 0) ['a' .. 'z']\n"}], "src_uid": "3d6cd0a82513bc2119c9af3d1243846f"} {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact exec\nexec = B.pack . maybe \"NO\" (\\(a, b) -> unlines [\"YES\", show a, show b]) . fn . map (maybe undefined fst . B.readInt) . tail . B.words\nhi = 10^(9 :: Int) :: Int\nfn xs = (\\case { [] -> Just (hi, hi); [1] -> Just (1, hi); [y] | y > 0 -> Just (hi, y); [1, y] | and $ snd $ mapAccumL (\\p x -> (x, abs (x - p) /= 1 || (x - 1) `quot` y == (p - 1) `quot` y)) (head xs) (tail xs) -> Just (hi, y); _ -> Nothing; } ) . snub . sort . map abs . (zipWith (-) =<< tail) $ xs\n\nsnub [] = []\nsnub (x:xs) = x:go x xs\n where\n go _ [] = []\n go x (y:ys)\n | x < y = y:go y ys\n | otherwise = go x ys\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | length moves == 2 && head moves /= 1 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then (if moves !! 0 == 1 then 1000000000 else moves !! 0) else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) ((head xs - 1) `mod` ud + 1, (head xs - 1) `div` ud + 1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\n\nmain = interact exec\nexec = maybe \"NO\" (\\(a, b) -> unlines [\"YES\", show a, show b]) . fn . map read . tail . words\nfn = (\\case { [1] -> Just (1 :: Int, 10^9 :: Int); [y] -> Just (10^9, y); [1, y] -> Just (10^9, y); _ -> Nothing; } ) . snub . sort . map abs . (zipWith (-) =<< tail)\n\nsnub [] = []\nsnub (x:xs) = x:go x xs\n where\n go _ [] = []\n go x (y:ys)\n | x < y = y:go y ys\n | otherwise = go x ys\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\n\nmain = interact exec\nexec = maybe \"NO\" (\\(a, b) -> unlines [\"YES\", show a, show b]) . fn . map read . tail . words\nhi = 10^(9 :: Int) :: Int\nfn = (\\case { [] -> Just (hi, hi); [1] -> Just (1, hi); [y] -> Just (hi, y); [1, y] -> Just (hi, y); _ -> Nothing; } ) . snub . sort . map abs . (zipWith (-) =<< tail)\n\nsnub [] = []\nsnub (x:xs) = x:go x xs\n where\n go _ [] = []\n go x (y:ys)\n | x < y = y:go y ys\n | otherwise = go x ys\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact exec\nexec = B.pack . maybe \"NO\" (\\(a, b) -> unlines [\"YES\", show a, show b]) . fn . map (maybe undefined fst . B.readInt) . tail . B.words\nhi = 10^(9 :: Int) :: Int\nfn xs = (\\case { [] -> Just (hi, hi); [1] -> Just (1, hi); [y] -> Just (hi, y); [1, y] | and $ snd $ mapAccumL (\\p x -> (x, abs (x - p) /= 1 || x `quot` (y + 1) == p `quot` (y + 1) )) (head xs) (tail xs) -> Just (hi, y); _ -> Nothing; } ) . snub . sort . map abs . (zipWith (-) =<< tail) $ xs\n\nsnub [] = []\nsnub (x:xs) = x:go x xs\n where\n go _ [] = []\n go x (y:ys)\n | x < y = y:go y ys\n | otherwise = go x ys\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\n\nmain = interact exec\nexec = maybe \"NO\" (\\(a, b) -> unlines [\"YES\", show a, show b]) . fn . map read . tail . words\nhi = 10^(9 :: Int) :: Int\nfn xs = (\\case { [] -> Just (hi, hi); [1] -> Just (1, hi); [y] -> Just (hi, y); [1, y] | and $ snd $ mapAccumL (\\p x -> (x, abs (x - p) /= 1 || x <= y)) (head xs) (tail xs) -> Just (hi, y); _ -> Nothing; } ) . snub . sort . map abs . (zipWith (-) =<< tail) $ xs\n\nsnub [] = []\nsnub (x:xs) = x:go x xs\n where\n go _ [] = []\n go x (y:ys)\n | x < y = y:go y ys\n | otherwise = go x ys\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nmain = B.interact exec\nexec = B.pack . maybe \"NO\" (\\(a, b) -> unlines [\"YES\", show a, show b]) . fn . map (maybe undefined fst . B.readInt) . tail . B.words\nhi = 10^(9 :: Int) :: Int\nfn xs = (\\case { [] -> Just (hi, hi); [1] -> Just (1, hi); [y] | y > 0 -> Just (hi, y); [1, y] | and $ snd $ mapAccumL (\\p x -> (x, abs (x - p) /= 1 || x `quot` (y + 1) == p `quot` (y + 1) )) (head xs) (tail xs) -> Just (hi, y); _ -> Nothing; } ) . snub . sort . map abs . (zipWith (-) =<< tail) $ xs\n\nsnub [] = []\nsnub (x:xs) = x:go x xs\n where\n go _ [] = []\n go x (y:ys)\n | x < y = y:go y ys\n | otherwise = go x ys\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then (if moves !! 0 == 1 then 1000000000 else moves !! 0) else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) (head xs `mod` ud, (head xs - 1) `div` ud + 1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | head moves /= 1 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then (if moves !! 0 == 1 then 1000000000 else moves !! 0) else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) ((head xs - 1) `mod` ud + 1, (head xs - 1) `div` ud + 1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (10000000000, 10000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 10000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then moves !! 0 else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) (1,1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show a) ++ \" \" ++ (show b))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then (if moves !! 0 == 1 then 1000000000 else moves !! 0) else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) (1,1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (10000000000, 10000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 10000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then moves !! 0 else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) (1,1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then 1000000000 else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) (1,1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then (if moves !! 0 == 1 then 1000000000 else moves !! 0) else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) ((head xs - 1) `mod` ud + 1, (head xs - 1) `div` ud + 1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \ngetInts :: IO [Int]\ngetInts = (map parseInt . BS8.words) <$> BS.getLine \n where parseInt = fst . fromJust . BS8.readInt\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve xs\n | length xs == 1 = Just (1000000000, 1000000000)\n | length moves > 2 = Nothing\n | head moves == 0 = Nothing\n | otherwise = if valid then Just (ud, 1000000000) else Nothing\n where gap = zipWith (-) xs (tail xs)\n moves = map head $ group $ sort $ map abs gap\n ud = if length moves == 1 then moves !! 0 else moves !! 1\n history = scanl (\\(x,y) g-> if g == 1 || g == -1 then (x-g,y) else (x,y-g `div` ud)) (1,1) gap\n valid = length (filter (\\(x,y) -> x < 1 || y < 1 || x > ud) history) == 0\n\nprintAns :: Maybe (Int, Int) -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just (a,b)) = putStrLn \"YES\" >> putStrLn ((show b) ++ \" \" ++ (show a))\n\nmain :: IO ()\nmain = getLine >> getInts >>= printAns . solve"}], "src_uid": "3b725f11009768904514d87e2c7714ee"} {"source_code": "main = do\n n <- readLn :: IO Int\n v <- fmap ((map (\\x -> read x::Int)) . words) getLine\n [a,b] <- fmap ((map (\\x -> read x::Int)) . words) getLine\n print $ sum $ (drop (a - 1)) $ take (b - 1) v\n", "positive_code": [{"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [_, ds, [a, b]] = sum (drop (a - 1) $ take (b - 1) ds)\nsolve _ = undefined\n"}, {"source_code": "main = do\n getLine\n ds <- fmap (map read . words) getLine\n [a,b] <- fmap (map read . words) getLine\n print $ sum $ take (b-a) $ drop (a-1) ds"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.tail.lines\n\nfunc::[String]->String\nfunc = toString.solve.map (map (toInt).words)\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[[Int]]->Int\nsolve a = sum$take (c2-c1)$drop c1 b\n where\n b = a!!0\n c1 = (a!!1)!!0-1\n c2 = (a!!1)!!1-1"}, {"source_code": "getnum :: IO [Int]\ngetnum = fmap (map read . words) getLine\n\nmain = do\n line <- getLine\n num <- getnum\n [a,b] <- getnum\n print . sum . take (b-a) . drop (a-1) $ num\n"}, {"source_code": "main = interact f\nf input = output where\n [[n],d,[a,b]] = map (map (read::String->Int)) $ map words $ lines input\n output = show $ sum $ take (b-a) $ drop (a-1) d"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n\n\t\nmain= do\n\tgetLine\n\ts<- map read. words <$> getLine ::IO [Int]\n\t[a,b]<- map read. words <$> getLine ::IO [Int]\t\n\tprint $ sum $ drop (a-1) $ take (b-1) s \n\t \n\t\n \n\t \n\t "}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine :: IO Int\n ds <- ( map read . words ) `liftM` getLine\n [a, b] <- ( map read . words ) `liftM` getLine\n\n putStrLn $ show $ sum $ take (b-a) $ drop (a-1) ds\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:d) = let a = d !! (n - 1)\n b = d !! n\n in solve' 1 a b d\n where solve' :: Int -> Int -> Int -> [Int] -> Int\n solve' _ _ _ [] = 0\n solve' i a b (d:x) | a <= i && i < b = d + solve' (i + 1) a b x\n | otherwise = solve' (i + 1) a b x\n"}, {"source_code": "main = do\n n<-readLn :: IO Int\n arr <- fmap (map (\\x -> read x::Int) . words) getLine\n [a,b] <- fmap (map (\\x -> read x::Int) . words) getLine\n print $solve a b arr\n\nsolve a b arr = sum $drop (a-1) (take (b-1) (arr))\n"}, {"source_code": "main = do\n n <- getLine\n s <- getLine\n ab <- getLine\n let [a, b] = map read (words ab)\n print (f (map read (words s)) (a - 1) (b - 2))\nf :: [Int] -> Int -> Int -> Int\nf x a b\n | a == b = x !! a\n | a == 0 = head x + (f (tail x) a (b - 1))\n | otherwise = f (tail x) (a - 1) (b - 1)"}, {"source_code": "myInput :: Int -> IO String\nmyInput n = return ([\"11\", \"1 2 3 4 5 6 7 8 9 10\", \"1 11\"] !! n)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve _ 1 _ = 0\nsolve 1 m (a:as) = a + solve 1 (m - 1) as\nsolve n m (a:as) = solve (n - 1) (m - 1) as\n\nmain = do\n s <- getLine\n s <- getLine\n let as = map (read::(String -> Int)) (words s)\n s <- getLine\n let [a, b] = map (read::(String -> Int)) (words s)\n print (solve a b as)\n"}, {"source_code": "solve [xs, [a, b]] = sum $ map fst $ takeWhile (f b) $ dropWhile (f a) $ zip xs [1..]\n where f v = (/=v).snd\n\nmain = interact $ show.solve.map (map read.words).tail.lines"}, {"source_code": "main=interact$show.f.map(map read.words).lines\nf[_,ds,[a,b]]=sum$drop(a-1)$take(b-1)ds\n"}], "negative_code": [{"source_code": "main = do\n n<-readLn :: IO Int\n arr <- fmap (map (\\x -> read x::Int) . words) getLine\n [a,b] <- fmap (map (\\x -> read x::Int) . words) getLine\n print $solve a b arr\n\nsolve a b arr = sum $take (b-1) (drop (a-1) arr)"}], "src_uid": "69850c2af99d60711bcff5870575e15e"} {"source_code": "import Data.Int\n\nmain = do interact $ show . gao . map read . tail . words where\n\tgao :: [Int32] -> Int\n\tgao a = let (s:b) = scanr1 (+) a in length $ filter (\\i -> i + i == s) b\n", "positive_code": [{"source_code": "\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nsolve :: [Int] -> Int\nsolve xs = sum $ solve' (head xs, sum xs - head xs) $ tail xs\n where\n solve' _ [] = []\n solve' (l, r) (x:xs) = (if l == r then 1 else 0) : solve' (l + x, r - x) xs\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve\n"}, {"source_code": "import Data.Int\nimport IO\n\nmain = do\n\thSetBuffering stdin $ BlockBuffering (Just 1000000)\n\thGetContents stdin >>= putStrLn . show . gao . map read . tail . words where\n\t\tgao :: [Int32] -> Int\n\t\tgao a = let (s:b) = scanr1 (+) a in length $ filter (\\i -> i + i == s) b\n"}, {"source_code": "countS :: [Int] -> [Int]\ncountS [x] = [x]\ncountS (x : xs) = (x + head ss) : ss\n where ss = countS xs\n\ncountWays [] _ = 0\ncountWays (s : ss) sum = if 2 * s == sum then ret + 1 else ret\n where ret = countWays ss sum\n \nsolve xs = countWays (drop 1 (countS xs)) (sum xs)\n\nmain = do\n n <- getLine\n line <- getLine\n let xs = map read $ words $ line\n putStrLn $ show $ solve xs "}], "negative_code": [{"source_code": "main = do getLine; getLine >>= putStrLn . show . length . gao . map read . words where\n\tgao a = let (s:b) = scanr1 (+) a in filter (\\i -> True) b\n"}, {"source_code": "main = do getLine; getLine >>= putStrLn . show . length . gao . map read . words where\n\tgao a = let b = scanr1 (+) a in filter ((==last b) . (*2)) $ init b\n"}], "src_uid": "5358fff5b798ac5e500d0f5deef765c7"} {"source_code": "import Data.List\n\nmodfn 0 _ _ _ as = tail $ reverse as\nmodfn n i k x as = modfn (n-1) ((i+1)`mod`k) k x ((x!!i) + head as:as)\n\nmain = do\n n <- readLn :: IO Int\n as <- getLine >>= return . map (read :: String -> Int ) . words\n let x = zipWith (-) as $ 0:as\n l = filter (\\a -> let b = take n $ modfn n 0 a x [0] in b == as ) [1..n]\n print $ length l\n putStrLn $ concat $ intersperse \" \" $ map show l\n", "positive_code": [{"source_code": "\n import Data.List\n import Control.Monad\n import Data.Maybe ( fromJust )\n import qualified Data.ByteString as BS\n import qualified Data.ByteString.Char8 as BS8\n \n fast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int] \n \n citesc_nr :: String -> Int\n citesc_nr s = read s\n \n check :: [Int] -> Int -> Int -> Int -> Bool\n check l i n d \n | (i+d) == n = True \n | (l!!i) == (l!!(i+d)) = check l (i+1) n d\n | otherwise = False\n \n brut :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]\n brut _ d 0 _ list = reverse list\n brut i d n l list = brut (mod (i+1) d) d (n-1) l ((head list + l!!i ):list)\n \n main = do\n x <- getLine\n let n = citesc_nr x\n a <- fast_read_Int\n let b = zipWith (-) a $ 0:a\n let l = filter (\\i -> brut 0 i n b [0] == (0:a) ) [1..n]\n --print b\n --print $ brut 0 1 n b [0]\n print $ length l\n putStr $ join $ intersperse \" \" $ map show l\n \n {--\n main = do\n n <- readLn :: IO Int\n a <- fast_read_Int\n let b = zipWith (-) a $ 0:a\n let l = filter (\\i -> check b 0 n i == True ) [1..n]\n print $ length l\n putStrLn $ join $ intersperse \" \" $ map show l\n --}"}, {"source_code": "-- Codeforces 1043 B\nimport Data.List\nfindXs :: [Int] -> [Int]\nfindXs as = zipWith (-) as (0:as)\n\nfindLoop :: [Int] -> Int -> [Int]\nfindLoop xs len = map fst $ foldl filterHead lists xs\n where numbers = [1..len]\n lists = map (\\n -> (n, cycle (take n xs))) numbers\n\nfilterHead :: [(Int, [Int])] -> Int -> [(Int, [Int])]\nfilterHead lists x = [(n, ls) | (n, (l:ls)) <- lists, l == x]\n\nmain :: IO ()\nmain = do\n num <- getLine\n list <- getLine\n let n = read num\n let xs = findXs $ map (read :: String -> Int) (words list)\n let loops = findLoop xs n\n putStrLn $ show $ length loops\n putStrLn $ unwords $ map show loops\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport Data.Maybe ( fromJust )\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int] \n\ncitesc_nr :: String -> Int\ncitesc_nr s = read s\n\ncheck :: [Int] -> Int -> Int -> Int -> Bool\ncheck l i n d \n | (i+d) == n = True \n | (l!!i) == (l!!(i+d)) = check l (i+1) n d\n | otherwise = False\n\nbrut :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]\nbrut _ d 0 _ list = reverse list\nbrut i d n l list = brut (mod (i+1) d) d (n-1) l ((head list + list!!i ):list)\n\nmain = do\n x <- getLine\n let n = citesc_nr x\n a <- fast_read_Int\n let b = zipWith (-) a $ 0:a\n let l = filter (\\i -> brut 0 i n b [0] == 0:b ) [1..n]\n putStr $ join $ intersperse \" \" $ map show l\n\n{--\nmain = do\n n <- readLn :: IO Int\n a <- fast_read_Int\n let b = zipWith (-) a $ 0:a\n let l = filter (\\i -> check b 0 n i == True ) [1..n]\n print $ length l\n putStrLn $ join $ intersperse \" \" $ map show l\n--}"}], "src_uid": "fd2227498f1a0f4042673382a3c71c85"} {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n , \"abc\\\\def\\\\ij\"\n , \"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [ \"C:\\\\folder1\\\\file1.txt\" ]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\n\n\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\npathList4 = [ \"F:\\\\g\\\\a\\\\f\\\\i\\\\k\\\\i\\\\f\\\\f\\\\f\\\\h\\\\c\\\\c\\\\f\\\\i\\\\c\\\\f\\\\b\\\\b\\\\d\\\\j\\\\a\\\\e\\\\g\\\\d\\\\d\\\\f\\\\c\\\\k\\\\i\\\\f\\\\g\\\\f\\\\e\\\\d\\\\b\\\\b\\\\e\\\\f\\\\g\\\\h\\\\b\\\\f\\\\h\\\\i\\\\chv.27\"\n ,\"C:\\\\i\\\\f\\\\j\\\\h\\\\g\\\\f\\\\i\\\\h\\\\c\\\\b\\\\c\\\\e\\\\a\\\\f\\\\k\\\\h\\\\b\\\\j\\\\g\\\\j\\\\b\\\\f\\\\j\\\\a\\\\b\\\\k\\\\d\\\\d\\\\a\\\\d\\\\b\\\\f\\\\c\\\\d\\\\h\\\\e\\\\j\\\\f\\\\f\\\\e\\\\d\\\\h\\\\i\\\\k\\\\x.vq\"\n ,\"E:\\\\i\\\\d\\\\h\\\\c\\\\a\\\\g\\\\d\\\\h\\\\i\\\\e\\\\i\\\\a\\\\e\\\\c\\\\d\\\\a\\\\a\\\\i\\\\i\\\\e\\\\e\\\\b\\\\g\\\\g\\\\d\\\\g\\\\j\\\\b\\\\...\"\n ]\n\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map length) . (map $ filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map f . map split . sort) \n\nf (x1:x2:xs) = (x1++x2) :xs\n\n--maxSubDirNum = maximum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\nmaxSubDirNum = maximum . (map length ) . (map tail) . (map (filter (not . elem '.'))) . (map T.flatten . map buildDir . groupPath . map f . map split . sort) \n\n\n\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" (dirNum) fileNum)\n }\n\n", "positive_code": [{"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\nbuildTree = (map T.flatten . map buildDir . groupPath . map f . map split . sort) \n\n\n\nmaxFileNum = (maximum) . (map length) . (map $ filter (elem '.')) . buildTree\n\nf (x1:x2:xs) = (x1++x2) :xs\n\nmaxSubDirNum = maximum . (map length ) . (map tail) . (map (filter (not . elem '.'))) . buildTree\n\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" (dirNum) fileNum)\n }\n\n"}, {"source_code": "import Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\nsplit l =\n let (first, second) = break (\\x -> x == '\\\\') l in\n case second of\n h:t -> first : (split t)\n _ -> [first]\n\ntoPairs [] = []\ntoPairs (h:t)\n | null t = []\n | otherwise = (h, head t) : (toPairs t)\n\nupd k v m = \n case Map.lookup k m of\n Just s -> Map.update (\\x -> Just (Set.insert v s)) k m\n Nothing -> Map.insert k (Set.singleton v) m\n\ndfs1 m k =\n case Map.lookup k m of\n Just s -> foldl' (+) 1 (map (dfs1 m) (Set.elems s))\n Nothing -> 0\n\ndfs2 m k = \n case Map.lookup k m of\n Just s -> foldl' (+) 0 (map (dfs2 m) (Set.elems s))\n Nothing -> 1\n\nsolve input = \n let list = concat (map (toPairs.drop 1.inits.split) (map (\\x -> \"/\\\\\" ++ x) (lines input))) in\n let mp = foldl' (\\m (first, second) -> upd first second m) (Map.empty) list in\n case Map.lookup [\"/\"] mp of\n Just s -> let disks = Set.elems s in\n let rootFolders = concat (map (\\x -> case Map.lookup x mp of Just y -> Set.elems y; Nothing -> []) disks) in\n let one = show (foldl' (max) 0 (map (\\x -> (dfs1 mp x) - 1) rootFolders)) in\n let two = show (foldl' (max) 0 (map (dfs2 mp) rootFolders)) in\n one ++ \" \" ++ two\n Nothing -> \"Nothing\"\n\nmain = interact(solve)"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.List as List\nsplitPath s = let\n sP (r:rs) (s:ss)\n | s == '\\\\' = sP ([]:r:rs) ss\n | otherwise = sP ((s:r):rs) ss\n sP r [] = r in\n map reverse $ reverse $ sP [reverse $ take 3 s] $ drop 3 s\nf (dirs, files, maxdirs, maxfiles, curDir) l@((d:ds):ls)\n | curDir /= d = f (Set.empty, 0, max maxdirs (Set.size dirs), \n max maxfiles files, d) l\n | otherwise = f (f1 dirs [] ds, files+1, maxdirs, maxfiles, curDir) ls\nf (dirs, files, maxdirs, maxfiles, curDir) [] = \n (max maxdirs (Set.size dirs), max maxfiles files)\nf1 dirs _ [_] = dirs\nf1 dirs h (d:ds) = f1 (Set.insert (d:h) dirs) (d:h) ds\n\nmain = do\n l <- (map splitPath . List.sort . lines) `fmap` getContents\n let (maxdirs, maxfiles) = f (Set.empty, 0, 0, 0, \"\") l\n putStrLn $ unwords $ map show [maxdirs, maxfiles]\n"}], "negative_code": [{"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\npathList = [\"abc\\\\def\",\"abc\\\\def\\\\gh\",\"abc\\\\def\\\\ij\",\"abc\\\\jk\\\\lm\",\"de\"]\n\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; print ((map buildDir . groupPath . map split . sort) ns)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n , \"abc\\\\def\\\\ij\"\n , \"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [ \"C:\\\\folder1\\\\file1.txt\" ]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\n\n\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\npathList4 = [ \"F:\\\\g\\\\a\\\\f\\\\i\\\\k\\\\i\\\\f\\\\f\\\\f\\\\h\\\\c\\\\c\\\\f\\\\i\\\\c\\\\f\\\\b\\\\b\\\\d\\\\j\\\\a\\\\e\\\\g\\\\d\\\\d\\\\f\\\\c\\\\k\\\\i\\\\f\\\\g\\\\f\\\\e\\\\d\\\\b\\\\b\\\\e\\\\f\\\\g\\\\h\\\\b\\\\f\\\\h\\\\i\\\\chv.27\"\n ,\"C:\\\\i\\\\f\\\\j\\\\h\\\\g\\\\f\\\\i\\\\h\\\\c\\\\b\\\\c\\\\e\\\\a\\\\f\\\\k\\\\h\\\\b\\\\j\\\\g\\\\j\\\\b\\\\f\\\\j\\\\a\\\\b\\\\k\\\\d\\\\d\\\\a\\\\d\\\\b\\\\f\\\\c\\\\d\\\\h\\\\e\\\\j\\\\f\\\\f\\\\e\\\\d\\\\h\\\\i\\\\k\\\\x.vq\"\n ,\"E:\\\\i\\\\d\\\\h\\\\c\\\\a\\\\g\\\\d\\\\h\\\\i\\\\e\\\\i\\\\a\\\\e\\\\c\\\\d\\\\a\\\\a\\\\i\\\\i\\\\e\\\\e\\\\b\\\\g\\\\g\\\\d\\\\g\\\\j\\\\b\\\\...\"\n ]\n\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map $ length . filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\n\n--maxSubDirNum = maximum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\nmaxSubDirNum = maximum . (map length ). (map (filter (not . elem '.'))) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" (dirNum-2) fileNum)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n ,\"abc\\\\def\\\\ij\"\n ,\"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [\"C:\\\\folder1\\\\file1.txt\"]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map $ length . filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\n\nmaxSubDirNum = sum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" dirNum fileNum)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n , \"abc\\\\def\\\\ij\"\n , \"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [ \"C:\\\\folder1\\\\file1.txt\" ]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\n\n\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\npathList4 = [ \"F:\\\\g\\\\a\\\\f\\\\i\\\\k\\\\i\\\\f\\\\f\\\\f\\\\h\\\\c\\\\c\\\\f\\\\i\\\\c\\\\f\\\\b\\\\b\\\\d\\\\j\\\\a\\\\e\\\\g\\\\d\\\\d\\\\f\\\\c\\\\k\\\\i\\\\f\\\\g\\\\f\\\\e\\\\d\\\\b\\\\b\\\\e\\\\f\\\\g\\\\h\\\\b\\\\f\\\\h\\\\i\\\\chv.27\"\n ,\"C:\\\\i\\\\f\\\\j\\\\h\\\\g\\\\f\\\\i\\\\h\\\\c\\\\b\\\\c\\\\e\\\\a\\\\f\\\\k\\\\h\\\\b\\\\j\\\\g\\\\j\\\\b\\\\f\\\\j\\\\a\\\\b\\\\k\\\\d\\\\d\\\\a\\\\d\\\\b\\\\f\\\\c\\\\d\\\\h\\\\e\\\\j\\\\f\\\\f\\\\e\\\\d\\\\h\\\\i\\\\k\\\\x.vq\"\n ,\"E:\\\\i\\\\d\\\\h\\\\c\\\\a\\\\g\\\\d\\\\h\\\\i\\\\e\\\\i\\\\a\\\\e\\\\c\\\\d\\\\a\\\\a\\\\i\\\\i\\\\e\\\\e\\\\b\\\\g\\\\g\\\\d\\\\g\\\\j\\\\b\\\\...\"\n ]\n\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map $ length . filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\n\n--maxSubDirNum = maximum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\nmaxSubDirNum = n\n where n = maximum . (map length) . (map (concatMap $(filter $ not . null) . (filter (not . elem '.'))) ) . (map T.levels . map buildDir . groupPath . map split . sort) \n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" (dirNum-2) fileNum)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n-- import Data.Tree \nimport qualified Data.Map as M\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; print (map (f . split) ns)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n \n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; print ns\n }"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n , \"abc\\\\def\\\\ij\"\n , \"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [ \"C:\\\\folder1\\\\file1.txt\" ]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\n\n\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\npathList4 = [ \"F:\\\\g\\\\a\\\\f\\\\i\\\\k\\\\i\\\\f\\\\f\\\\f\\\\h\\\\c\\\\c\\\\f\\\\i\\\\c\\\\f\\\\b\\\\b\\\\d\\\\j\\\\a\\\\e\\\\g\\\\d\\\\d\\\\f\\\\c\\\\k\\\\i\\\\f\\\\g\\\\f\\\\e\\\\d\\\\b\\\\b\\\\e\\\\f\\\\g\\\\h\\\\b\\\\f\\\\h\\\\i\\\\chv.27\"\n ,\"C:\\\\i\\\\f\\\\j\\\\h\\\\g\\\\f\\\\i\\\\h\\\\c\\\\b\\\\c\\\\e\\\\a\\\\f\\\\k\\\\h\\\\b\\\\j\\\\g\\\\j\\\\b\\\\f\\\\j\\\\a\\\\b\\\\k\\\\d\\\\d\\\\a\\\\d\\\\b\\\\f\\\\c\\\\d\\\\h\\\\e\\\\j\\\\f\\\\f\\\\e\\\\d\\\\h\\\\i\\\\k\\\\x.vq\"\n ,\"E:\\\\i\\\\d\\\\h\\\\c\\\\a\\\\g\\\\d\\\\h\\\\i\\\\e\\\\i\\\\a\\\\e\\\\c\\\\d\\\\a\\\\a\\\\i\\\\i\\\\e\\\\e\\\\b\\\\g\\\\g\\\\d\\\\g\\\\j\\\\b\\\\...\"\n ]\n\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map $ length . filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\n\n--maxSubDirNum = maximum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\nmaxSubDirNum = maximum . (map length ). (map $ tail . tail) . (map (filter (not . elem '.'))) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" (dirNum) fileNum)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n , \"abc\\\\def\\\\ij\"\n , \"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [ \"C:\\\\folder1\\\\file1.txt\" ]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\n\n\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\npathList4 = [ \"F:\\\\g\\\\a\\\\f\\\\i\\\\k\\\\i\\\\f\\\\f\\\\f\\\\h\\\\c\\\\c\\\\f\\\\i\\\\c\\\\f\\\\b\\\\b\\\\d\\\\j\\\\a\\\\e\\\\g\\\\d\\\\d\\\\f\\\\c\\\\k\\\\i\\\\f\\\\g\\\\f\\\\e\\\\d\\\\b\\\\b\\\\e\\\\f\\\\g\\\\h\\\\b\\\\f\\\\h\\\\i\\\\chv.27\"\n ,\"C:\\\\i\\\\f\\\\j\\\\h\\\\g\\\\f\\\\i\\\\h\\\\c\\\\b\\\\c\\\\e\\\\a\\\\f\\\\k\\\\h\\\\b\\\\j\\\\g\\\\j\\\\b\\\\f\\\\j\\\\a\\\\b\\\\k\\\\d\\\\d\\\\a\\\\d\\\\b\\\\f\\\\c\\\\d\\\\h\\\\e\\\\j\\\\f\\\\f\\\\e\\\\d\\\\h\\\\i\\\\k\\\\x.vq\"\n ,\"E:\\\\i\\\\d\\\\h\\\\c\\\\a\\\\g\\\\d\\\\h\\\\i\\\\e\\\\i\\\\a\\\\e\\\\c\\\\d\\\\a\\\\a\\\\i\\\\i\\\\e\\\\e\\\\b\\\\g\\\\g\\\\d\\\\g\\\\j\\\\b\\\\...\"\n ]\n\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map $ length . filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\n\n--maxSubDirNum = maximum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\nmaxSubDirNum = maximum . (map length ). (map $ tail . tail) . (map (filter (not . elem '.'))) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" (dirNum-2) fileNum)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\nimport Data.Function (on)\nimport Data.Maybe\nimport qualified Data.Tree as T\nimport qualified Data.Map as M\n\n\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\n\nf xs = ((init xs),(last xs))\ng (x,a) (ys,bs) = (([x] `union` ys), ([a] `union` bs))\n\n\nbuildDir = T.unfoldTree phi\n where phi (n,ps) = (delete '\\\\' n, groupPath $ filter (not . null) ps)\n\n-- binapp o f x y = f x `o` f y\ngroupPath = map grouping . groupBy (on eqpath head)\ngrouping ss = (head . head $ ss, map tail ss)\neqpath = on (==) (fst . (break ('\\\\'==)))\n\npathList = [ \"abc\\\\def\"\n , \"abc\\\\def\\\\gh\"\n ,\"abc\\\\def\\\\ij\"\n ,\"abc\\\\jk\\\\lm\",\"de\"\n ]\npathList1 = [\"C:\\\\folder1\\\\file1.txt\"]\npathList2 = [ \"C:\\\\folder1\\\\folder2\\\\folder3\\\\file1.txt\"\n , \"C:\\\\folder1\\\\folder2\\\\folder4\\\\file1.txt\"\n , \"D:\\\\folder1\\\\file1.txt\"\n ]\npathList3 = [ \"C:\\\\file\\\\file\\\\file\\\\file\\\\file.txt\"\n , \"C:\\\\file\\\\file\\\\file\\\\file2\\\\file.txt\"\n ]\n\n\nz = map (filter (not . elem '.'))\n\nmaxFileNum = (maximum) . (map $ length . filter (elem '.')) . (map T.flatten . map buildDir . groupPath . map split . sort) \n\n\nmaxSubDirNum = maximum . (map $ sum . map length) . (map (map (filter (not . elem '.')) . tail . tail) .map T.levels . map buildDir . groupPath . map split . sort)\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; let dirNum = maxSubDirNum ns in\n let fileNum = maxFileNum ns in\n (printf \"%d %d\\n\" dirNum fileNum)\n }\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n \n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (=='\\\\')\n\n\nmain :: IO () \nmain = do { ns <- lines <$> getContents\n ; print (map split ns)\n }"}], "src_uid": "e588d7600429eb6b70a1a9b5eca194f7"} {"source_code": "main = interact $ format . solve . lines\nsolve [a,b] = map vowel a == map vowel b\nvowel = (`elem` \"aeiou\")\nformat True = \"Yes\"\nformat False= \"No\"\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\ntrim = B.filter (/='\\r')\naeiou = \"aeiou\"\naeiou' = ['a'..'z'] \\\\ aeiou\nmain = ((\\x y -> \n if (B.length x == B.length y) && (all (== True) $ \n B.zipWith \n (\\x y -> \n (x `elem` aeiou && y `elem` aeiou) || \n (x `elem` aeiou' && y `elem` aeiou')\n ) x y )\n then \"YES\"\n else \"NO\"\n ) <$> (trim <$> B.getLine) <*> (trim <$> B.getLine) ) >>= putStrLn \n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\ntrim = B.filter (/=' ')\naeiou = \"aeiou\"\naeiou' = ['a'..'z']\\\\aeiou\nmain = ((\\x y -> \n if all (== (B.length x == B.length y)) $ B.zipWith (\\x y -> (x `elem` aeiou && y `elem` aeiou) || (x `elem` aeiou' && y `elem` aeiou')) x y \n then \"YES\"\n else \"NO\"\n ) <$> (trim <$> B.getLine) <*> (trim <$> B.getLine) ) >>= putStrLn \n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\naeiou = \"aeiou\"\naeiou' = ['a'..'z']\\\\aeiou\nmain = ((\\x y -> \n if all (== (B.length x == B.length y)) $ B.zipWith (\\x y -> (x `elem` aeiou && y `elem` aeiou) || (x `elem` aeiou' && y `elem` aeiou')) x y \n then \"YES\"\n else \"NO\"\n ) <$> B.getLine <*> B.getLine ) >>= putStrLn \n"}], "src_uid": "2b346d5a578031de4d19edb4f8f2626c"} {"source_code": "import Control.Arrow\nmain = interact $ show . solve . lines\nsolve [a,b] = go (reverse a) (reverse b) where\n go (a:as) (b:bs) | a == b = go as bs\n go as bs = length as + length bs\n", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ndoit [] = 0\ndoit ((x,y):xs) =\n\tif x == y then\n\t\t1 + doit xs\n\telse\n\t\t0\n\nsolve::String -> String\nsolve ss =\n\tlet [s,t] = map reverse (words ss) in\n\tshow (length s + length t - 2 * doit (zip s t)) ++ \"\\n\"\n\nmain = do\n interact $ solve\n"}, {"source_code": "-- Codeforces 1005B\nimport Data.List\n\ndeleteFromRight :: (String, String) -> (String, String)\ndeleteFromRight ([], s2) = ([], s2)\ndeleteFromRight (s1, []) = (s1, [])\ndeleteFromRight (x1:xs1, x2:xs2)\n | x1 == x2 = deleteFromRight (xs1, xs2)\n | otherwise = (x1:xs1, x2:xs2)\n\nrest :: (String, String) -> Int\nrest (s1, s2) = (\\(a, b) -> (length a) + (length b)) $ deleteFromRight (reverse s1, reverse s2)\n\nmain :: IO ()\nmain = do\n s1 <- getLine\n s2 <- getLine\n print (rest (s1, s2))\n"}, {"source_code": "f [] a = length a\nf a [] = length a\nf (a:as) (b:bs) | a==b = f as bs\nf as bs = length as + length bs\n\nmain = do\n s <- getLine\n t <- getLine\n print $ f (reverse t) (reverse s)"}, {"source_code": "import Data.List\n\nf::String->String->Int\nf \"\" _ =0\nf _ \"\"=0\nf (x:xs) (y:ys)\n |x/=y=0\n |otherwise=2 + (f xs ys)\n\n\nmain = do\n e1<-getLine\n e2<-getLine\n let t=(length e1)+(length e2)\n print $ t - (f (reverse e1) (reverse e2))"}, {"source_code": "main = interact $ pureMain\n\npureMain :: String -> String\npureMain x = show $ length s + length t - 2 * f (reverse s) (reverse t)\n where\n [s, t] = lines x\n f _ [] = 0\n f [] _ = 0\n f (a:as) (b:bs) | a == b = 1 + f as bs\n | otherwise = 0"}], "negative_code": [{"source_code": "import Control.Arrow\nmain = interact $ show . solve . lines\nsolve [a,b] = uncurry (+) $ length *** length $ unzip $ dropWhile (uncurry (==)) $ zip (reverse a) (reverse b)\n"}], "src_uid": "59d926bca19a6dcfe3eb3e3dc03fffd6"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = (Int, String)\n\ntype Output = [Int]\n\ninput :: Scanner Input\ninput = pair int str\n\noutput :: Output -> C.ByteString\noutput = C.pack . unwords . map show\n\nsolve :: Input -> Output\nsolve (n, s)\n | isJust iz = let r = h + fromJust iz in [1, r + 1, 1, r]\n | odd n = [h + 2, n, h + 1, n - 1]\n | s !! (h - 1) == '0' = [h + 1, n, h, n]\n | otherwise = [h + 1, n, h, n - 1]\n where\n h = n `div` 2\n iz = elemIndex '0' (drop h s)\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\n\ncount1 :: String -> Int\ncount1 = foldr (\\a b -> if a == '1' then (b+1) else b) 0\n\n\ncalc :: Int -> String -> (Int,Int,Int,Int)\ncalc l x =\n let m = (l `div` 2)\n index0 = findIndex (\\a -> a == '0') x\n in\n case index0 of\n Just k | k < m -> (k+2,l,k+1,l)\n Just k | otherwise -> (1,k+1,1,k)\n Nothing -> (1,l-1,2,l)\n\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let l = read line :: Int\n line <- getLine\n let (l1,r1,l2,r2) = calc l line\n putStr $ show l1\n putStr \" \"\n putStr $ show r1\n putStr \" \"\n putStr $ show l2\n putStr \" \"\n putStrLn $ show r2\n"}, {"source_code": "import Data.List\r\nimport Data.Char (digitToInt)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = String\r\ntype OutType = ((Int, Int), (Int, Int))\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nsolve :: InType -> OutType\r\nsolve n\r\n | null zeroes = ((1, len - 1), (2, len))\r\n | i > len `div` 2 = ((1, i), (1, i - 1))\r\n | otherwise = ((i, len), (i + 1, len))\r\n where\r\n zeroes = elemIndices '0' n\r\n len = length n\r\n i = last zeroes + 1\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, n] = n\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines\r\n where\r\n showAns ((l1, r1), (l2, r2)) = unwords (map show [l1,r1,l2,r2])\r\n\r\n"}], "negative_code": [{"source_code": "import Data.List\r\nimport Data.Char (digitToInt)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = String\r\ntype OutType = ((Int, Int), (Int, Int))\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nsolve :: InType -> OutType\r\nsolve n\r\n | null zeroes = ((1, len - 1), (2, len))\r\n | i - 1 > len `div` 2 = ((1, i), (1, i - 1))\r\n | otherwise = ((i, len), (i + 1, len))\r\n where\r\n zeroes = elemIndices '0' n\r\n len = length n\r\n i = last zeroes + 1\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, n] = n\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines\r\n where\r\n showAns ((l1, r1), (l2, r2)) = unwords (map show [l1,r1,l2,r2])\r\n\r\n"}, {"source_code": "import Data.List\r\nimport Data.Char (digitToInt)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = String\r\ntype OutType = ((Int, Int), (Int, Int))\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nsolve :: InType -> OutType\r\nsolve n\r\n | null zeroes = ((1, len - 1), (2, len))\r\n | i > len `div` 2 = ((1, i), (1, i - 1))\r\n | otherwise = ((i, len), (i + 1, len))\r\n where\r\n zeroes = elemIndices '0' n\r\n len = length n\r\n i = last zeroes\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, n] = n\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines\r\n where\r\n showAns ((l1, r1), (l2, r2)) = unwords (map show [l1,r1,l2,r2])\r\n\r\n"}], "src_uid": "eadc7f5e1043ac431984ec921c62892d"} {"source_code": "main = interact $ show . solve . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve = maximum . map (uncurry (+))\n", "positive_code": [{"source_code": "\n\nf :: (Integer, Integer) -> Integer\nf (a, b) = a + b\n\nconvert :: [a] -> [(a,a)]\nconvert [] = []\nconvert (x1:x2:xs) = (x1,x2):convert xs\n\nmain = interact $ (show.maximum.map f.convert.tail.map read.words)"}, {"source_code": "{-# LANGUAGE Safe #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Control.Applicative\nimport Control.Arrow\nimport Data.List\nimport Data.Array\nimport Data.Array.IO.Safe\nimport Data.Array.ST.Safe\nimport Data.IORef\nimport Data.STRef\nimport Data.Maybe\nimport Data.Bits\nimport Data.Ord\nimport Data.Ratio\nimport Data.Int\nimport Data.Char\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as Set\nimport qualified Data.Sequence as Sq\nimport Data.Tuple\nimport Data.Function\nimport Text.Printf\n--import Debug.Trace\nimport Numeric\n\nreadIntBS = fst . fromJust . BS.readInt\n\ninfixr 1 ?\n(?) :: Bool -> (a,a) -> a\n(?) b t = (if b then fst else snd) t\n\n\nmain = do\n n <- readLn :: IO Int\n ps <- map (map readIntBS . BS.words) . BS.lines <$> BS.getContents :: IO [[Int]]\n\n let m = maximum [x+y | [x,y] <- ps]\n \n print $ m\n"}, {"source_code": "-- Codeforces 1047 B\nmain :: IO ()\nmain = do\n n <- getLine >>= return.read :: IO Int\n number <-getContents >>= return.(take n).lines \n >>= return.map (sum.(map read).words):: IO [Int]\n putStrLn $ show $ maximum number\n"}, {"source_code": "import Data.List\nimport Data.Char\n\nf::String->Int\nf x=let (a:b:[])=map read (words x)::[Int]\n in a+b\n\nmain = do\n e1<-getLine\n es<-getContents\n let xs=lines es\n putStr $ show $ maximum $ map f xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nget = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain = sol <$> (flip replicateM get =<< readLn) >>= print\n\nsol :: [[Int]] -> Int\nsol = maximum . fmap sum \n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n print =<< maximum . map (sum . map (read :: String -> Int) . words) <$> replicateM n getLine"}], "negative_code": [], "src_uid": "7c41fb6212992d1b3b3f89694b579fea"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List\nimport Data.Char\n\nmain = do\n getLine\n str <- getLine\n let ns = map (\\n -> (read n) :: Integer) $ words str\n printResult $ findCircle ns\n \nfindCircle :: [Integer] -> Maybe [Integer]\nfindCircle ns = \n let (n1:n2:n3:ns') = reverse (sort ns) in\n let ns'' = n3 : n1 : n2 : ns' in\n if n1 < (n2+n3) then Just ns'' else Nothing\n\nprintResult :: Maybe [Integer] -> IO ()\nprintResult (Just ns) = putStrLn \"YES\" >> (putStrLn $ unwords $ map show ns)\nprintResult Nothing = putStrLn \"NO\"\n", "positive_code": [{"source_code": "import Data.List\n\nprintInt::Int->IO()\nprintInt x=do\n putStr(show x)\n putChar(' ')\nprintArr t=mapM_ printInt t\n\nmain::IO()\nmain=do\n n<-readLn::IO Int\n s<-getLine\n let t=sort((map read (words s))::[Int])\n let last1=t!!(n-1)\n let last2=t!!(n-2)\n let last3=t!!(n-3)\n if(last1>=last2+last3)\n then putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n printArr (fst (splitAt (n-3) t))\n printInt last2\n printInt last1\n printInt last3"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Maybe [Int]\nsolve l\n | a < b + c = Just $ b:a:c:ls\n | otherwise = Nothing\n where a:b:c:ls = reverse . sort $ l\n\ntoIntList :: String -> [Int]\ntoIntList = (map read) . words\n\nfromIntList :: [Int] -> String\nfromIntList = unwords . (map show)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n l <- toIntList <$> getLine\n let res = solve l\n out = case res of\n Just l -> \"YES\\n\" ++ fromIntList l\n Nothing -> \"NO\"\n putStrLn out\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\ntakeOdd [] = []\ntakeOdd [x] = [x]\ntakeOdd (x:_:xs) = x:takeOdd xs\n\ntakeEven [] = []\ntakeEven (_:xs) = takeOdd xs\n\noutput = putStrLn <$> unwords <$> map show\n\nmain = do\n getLine\n a <- input :: IO [Int]\n let s@(x:y:z:_) = reverse $ sort a\n if x >= y + z then\n putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n output $ takeEven s ++ reverse (takeOdd s)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List\nimport Data.Char\n\nmain = do\n _ <- getLine\n str <- getLine\n let ns = map (\\n -> (read n) :: Int) $ words str\n printResult $ findCircle ns\n \nfindCircle :: [Int] -> Maybe [Int]\nfindCircle ns = \n let (n1:n2:n3:ns') = reverse (sort ns) in\n let ns'' = n3 : n1 : n2 : ns' in\n if isGood ns'' then Just ns'' else Nothing\n\n\nisGood :: [Int] -> Bool\nisGood (x1:x2:x3:[]) = (x1 < (x2 + x3)) && (x2 < (x1 + x3)) && (x3 < (x1+x2))\nisGood (x1:xs) = isGood' x1 xs\nisGood' f (x1:x2:[]) = x2 < (x1 + f) \nisGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)\n\n\nprintResult :: Maybe [Int] -> IO ()\nprintResult (Just ns) = putStrLn \"YES\" >> (putStrLn $ unwords $ map show ns)\nprintResult Nothing = putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List\nimport Data.Char\n\nmain = do\n getLine\n str <- getLine\n let ns = map (\\n -> (read n) :: Integer) $ words str\n printResult $ findCircle ns\n \nfindCircle :: [Integer] -> Maybe [Integer]\nfindCircle ns = \n let (n1:n2:n3:ns') = reverse (sort ns) in\n let ns'' = n3 : n1 : n2 : ns' in\n if n1 >= (n2+n3) then Just ns'' else Nothing\n\nprintResult :: Maybe [Integer] -> IO ()\nprintResult (Just ns) = putStrLn \"YES\" >> (putStrLn $ unwords $ map show ns)\nprintResult Nothing = putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List\nimport Data.Char\n\nmain = do\n _ <- getLine\n str <- getLine\n let ns = map (digitToInt . head) $ words str\n printResult $ findCircle ns\n \nfindCircle :: [Int] -> Maybe [Int]\nfindCircle ns = \n let (n1:n2:n3:ns') = reverse (sort ns) in\n let ns'' = n3 : n1 : n2 : ns' in\n if isGood ns'' then Just ns'' else Nothing\n\n\nisGood :: [Int] -> Bool\nisGood (x1:xs) = isGood' x1 xs\nisGood' f (x1:x2:[]) = x2 < (x1 + f) \nisGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)\n\n\nprintResult :: Maybe [Int] -> IO ()\nprintResult (Just ns) = putStrLn \"YES\" >> (putStrLn $ foldr (\\n str -> (intToDigit n) : str) [] ns)\nprintResult Nothing = putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List\nimport Data.Char\n\nmain = do\n _ <- getLine\n str <- getLine\n let ns = map (\\n -> (read n) :: Int) $ words str\n printResult $ findCircle ns\n \nfindCircle :: [Int] -> Maybe [Int]\nfindCircle ns = \n let (n1:n2:n3:ns') = reverse (sort ns) in\n let ns'' = n3 : n1 : n2 : ns' in\n if isGood ns'' then Just ns'' else Nothing\n\n\nisGood :: [Int] -> Bool\nisGood (x1:xs) = isGood' x1 xs\nisGood' f (x1:x2:[]) = x2 < (x1 + f) \nisGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)\n\n\nprintResult :: Maybe [Int] -> IO ()\nprintResult (Just ns) = putStrLn \"YES\" >> (putStrLn $ unwords $ map show ns)\nprintResult Nothing = putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.List\nimport Data.Char\n\nmain = do\n _ <- getLine\n str <- getLine\n let ns = map (digitToInt . head) $ words str\n printResult $ findCircle ns\n \nfindCircle :: [Int] -> Maybe [Int]\nfindCircle ns = \n let (n1:n2:n3:ns') = reverse (sort ns) in\n let ns'' = n3 : n1 : n2 : ns' in\n if isGood ns'' then Just ns'' else Nothing\n\n\nisGood :: [Int] -> Bool\nisGood (x1:xs) = isGood' x1 xs\nisGood' f (x1:x2:[]) = x2 < (x1 + f) \nisGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)\n\n\nprintResult :: Maybe [Int] -> IO ()\nprintResult (Just ns) = putStrLn \"YES\" >> (putStrLn $ foldr (\\n str -> (intToDigit n) : ' ' : str) [] ns)\nprintResult Nothing = putStrLn \"NO\"\n"}], "src_uid": "a5ee97e99ecfe4b72c0642546746842a"} {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = readInts >> readInts >>=\r\n print . length . filter id . zipWith (==) [1..] . scanl1 max\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\nimport qualified Data.Set as Set\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n p <- replicateM n getInt\r\n let\r\n ss = scanl' (flip Set.insert) (Set.singleton 0) p\r\n oks = [() | v <- ss, Set.size v == Set.findMax v + 1]\r\n pure $ putInts [length oks - 1]\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "b371d47ea08091917ab632e559ee75c6"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\t[ [ c1, c2, c3, c4 ] , _, as, bs ] <- replicateM 4 $ do\n\t\tmap read . words <$> getLine\n\t\n\tlet\n\t\tf a = min ( c1 * a ) c2\n\t\n\tprint $ minimum [ c4, c3 * 2, min c3 ( sum ( map f as ) ) + min c3 ( sum ( map f bs ) ) ]\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\t[ [ c1, c2, c3, c4 ] , _, as, bs ] <- replicateM 4 $ do\n\t\tmap read . words <$> getLine\n\t\n\tlet\n\t\tf a = min ( c1 * a ) c2\n\t\n\tprint $ minimum [ c4, c3 * 2, c3 + sum ( map f as ) , c3 + sum ( map f bs ), sum ( map f as ) + sum ( map f bs ) ]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\t[ [ c1, c2, c3, c4 ] , _, as, bs ] <- replicateM 4 $ do\n\t\tmap read . words <$> getLine\n\t\n\tlet\n\t\tf a = min ( c1 * a ) c2\n\t\n\tprint $ min c4 $ min c3 ( sum ( map f as ) ) + min c3 ( sum ( map f bs ) )\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> [Int] -> [Int] -> Int\nsolve [c1, c2, c3, c4] as ts = min c4 (min as' c3 + min ts' c3)\n where\n as' = sum $ map (\\a -> min (a * c1) c2) as\n ts' = sum $ map (\\t -> min (t * c1) c2) ts\n \nmain :: IO ()\nmain = do\n cs <- reads\n getLine\n as <- reads\n ts <- reads\n print $ solve cs as ts\n\n where\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' (10 * a + fromIntegral (ord c - ord '0')) s\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show"}, {"source_code": "import Control.Applicative\n\nsolve :: [Int] -> Int -> Int -> [Int] -> [Int] -> Int\nsolve (c1:(c2:(c3:[c4]))) n m a1 a2\n = min c4 (optimal1 + optimal2)\n where\n optimal1 = min c3 ( sum $ map get_better a1 )\n optimal2 = min c3 ( sum $ map get_better a2 )\n\n get_better x = min (x*c1) c2\n\nmain :: IO ()\nmain = do\n lin1 <- getLine\n let costs = map read (words lin1)\n \n [n,m] <- map read <$> words <$> getLine\n \n a1 <- map read <$> words <$> getLine\n a2 <- map read <$> words <$> getLine\n\n print $ solve costs n m a1 a2"}, {"source_code": "minNum k n \n\t| n == 0 && k == 1 = 0\n\t| n == 0 = -1\n\t| otherwise = (10 ^ (k-1) ) + (n-1)\n\nfind x\n\t| x>=0 = show x\n\t| otherwise = \"No solution\"\n\nparse :: String -> [Int]\nparse l = map read $ words l\n\ncal :: [Int] -> [Int] -> [Int] -> Int\ncal cs bs ts = \n\tlet c4 = cs !! 3\n\tin \n\t min c4 $ (cal1 cs bs) + (cal1 cs ts)\n\ncal1:: [Int] -> [Int] -> Int\ncal1 cs bs = \n\tlet c3 = cs !! 2\n\tin\n\t min c3 $ foldl1 (+) $ (cal2 cs bs)\n\ncal2:: [Int] -> [Int] -> [Int]\ncal2 cs bs = \n\tlet c1 = cs !! 0\n\t c2 = cs !! 1\n\tin map (\\x -> min (c1 * x) c2 ) bs\n\t\n\nmain = do \n\tl1 <- getLine \n\tl2 <- getLine\n\tl3 <- getLine\n\tl4 <- getLine\n\tputStr $ show $ cal (parse l1) (parse l3) (parse l4)\n"}, {"source_code": "multa :: [Int] -> Int -> [Int]\nmulta list a = [a * x | x <- list]\n\nminlista :: [Int] -> Int -> [Int]\nminlista list a = [min a x | x <- list]\n\ngetans :: [Int] -> [Int] -> [Int] -> Int\ngetans bs tr (c1:c2:c3:c4:_) = min c4 ((min (sum (minlista (multa bs c1) c2)) c3) + min (sum (minlista (multa tr c1) c2)) c3)\n\n\nmain = do\n\tc14 <- getLine\n\tnm <- getLine\n\tbuses <- getLine\n\ttrolley <- getLine\n\tputStr $ show $ getans (map read (words buses)) (map read (words trolley)) (map read (words c14))\n"}], "negative_code": [], "src_uid": "11fabde93815c1805369bbbc5a40e2d8"} {"source_code": "import Data.List\n\nfindMax :: String -> String -> [[Int]]\nfindMax a b = scanl' byA (replicate (1 + length b) 0) a\n where byA r c = scanl' byB 0 $ zip3 b r $ tail r\n where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)\n in if c == d then max mx (ul+2) else mx\n\nsolve :: String -> String\nsolve input = show $ maximum $ map maximum $ findMax a b\n where (_:a:b:_) = lines input\n\nmain = interact solve\n\n", "positive_code": [{"source_code": "findMax :: String -> String -> [[Int]]\nfindMax a b = scanl byA [0 | _ <- [0..length b]] a\n where byA r c = scanl byB 0 $ zip3 b r $ tail r\n where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)\n in if c == d then max mx (ul+2) else mx\n\nsolve :: String -> String\nsolve input = show $ maximum $ map maximum $ findMax a b\n where (_:a:b:_) = lines input\n\nmain = interact solve\n\n"}, {"source_code": "findMax :: String -> String -> [[Int]]\nfindMax a b = scanl byA (replicate (1 + length b) 0) a\n where byA r c = scanl byB 0 $ zip3 b r $ tail r\n where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)\n in if c == d then max mx (ul+2) else mx\n\nsolve :: String -> String\nsolve input = show $ maximum $ map maximum $ findMax a b\n where (_:a:b:_) = lines input\n\nmain = interact solve\n\n"}, {"source_code": "import Data.List\n\nfindMax :: String -> String -> [[Int]]\nfindMax a b = scanl' byA [0 | _ <- [0..length b]] a\n where byA r c = scanl' byB 0 $ zip3 b r $ tail r\n where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)\n in if c == d then max mx (ul+2) else mx\n\nsolve :: String -> String\nsolve input = show $ maximum $ map maximum $ findMax a b\n where (_:a:b:_) = lines input\n\nmain = interact solve\n\n"}], "negative_code": [{"source_code": "\nmakeS :: String -> String -> [[Int]]\nmakeS a b = scanl byA [0 | _ <- [0..length b]] a\n where byA r c = scanl byB 0 $ zip3 b r $ init r\n where byB l (d, u, ul) = let mx = maximum [0, l-1, u-1]\n in if c == d then max mx (ul+2) else mx\n\nsolve :: String -> String\nsolve input = show $ maximum $ concat $ makeS a b\n where (_:a:b:_) = lines input\n\nmain = interact solve\n"}, {"source_code": "import Data.List\n\nfindMax :: String -> String -> [[Int]]\nfindMax a b = scanl' byA (replicate (1 + length b) 0) a\n where byA r c = scanl' byB 0 $ zip3 b r $ tail r\n where byB l (d, ul, u) = let mx = max 0 $ max (u-10) (l-1)\n in if c == d then max mx (ul+2) else mx\n\nsolve :: String -> String\nsolve input = show $ maximum $ map maximum $ findMax a b\n where (_:a:b:_) = lines input\n\nmain = interact solve\n\n"}], "src_uid": "cce64939977e0956714e06514e6043ff"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain = putStrLn . show . solve . tail . map (toEnum . maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Double] -> Double\nsolve cs = 360 - maximum (zipWith (-) (ts ++ [360 + t]) (t : ts))\n where\n (t : ts) = sort $ theta cs\n\ntheta :: [Double] -> [Double]\ntheta (x : y : cs) = t : theta cs\n where\n l = sqrt $ x * x + y * y\n t' = acos (x / l) * 180 / pi\n t = if y >= 0 then t' else 360 - t'\ntheta _ = []\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.List as L\nimport qualified Data.Array as A\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return . fst . fromMaybe (0,B.empty) . B.readInt\n l <- replicateM n (B.getLine >>= return . fromMaybe (0,0). readXY)\n print $ solve n l\n where\n readXY :: B.ByteString -> Maybe (Int,Int)\n readXY str = do\n (x,s1) <- B.readInt str\n (y,s2) <- B.readInt (B.tail s1)\n return (x,y)\n\nsolve :: Int -> [(Int,Int)] -> Double\nsolve n l = 360 - maxDiffAngle\n where\n ary = A.listArray (0,n) (L.sort . L.map angle $ l)\n maxDiffAngle = loop 0 0\n loop i angle | i == n-1 = max (ary A.! 0 - ary A.! (n-1) + 360) angle\n | otherwise = loop (i+1) (max (ary A.! (i+1) - ary A.! i) angle)\n \nangle :: (Int,Int) -> Double\nangle (0,0) = 0\nangle (x,y) = \n case (x'>0,y'>0) of\n (True,True) -> toDegree (asin (y'/d))\n (False,True) -> toDegree (acos (x'/d))\n (True,False) -> toDegree (asin (y'/d)) + 360\n (False,False) -> toDegree (asin (-y'/d)) + 180\n where \n x' = fromIntegral x\n y' = fromIntegral y\n d = sqrt ( x' * x' + y' * y')\n\ntoDegree :: Double -> Double\ntoDegree x = x * 180 / pi\n\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nget_points [] = []\nget_points (x:y:remain) = (x,y): get_points remain\n\nmain = do\n\tct <- C.getContents\n\tlet\n\t\t(n:p) = map (fst.fromJust.C.readInt) $ C.words ct\n\tprint $ solve $ get_points $ map fromIntegral p\n\nsolve :: (RealFloat a) => [(a,a)] -> a\nsolve p = \n\tlet\n\t\tall@(h:t) = sort $ map (uncurry atan2) p\n\t\tres = maximum $ zipWith (-) (t ++ [2*pi+h]) all\n\tin\n\t\t360 - 180/pi*res\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n (n:p) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let a@(h:t) = sort $ map (uncurry atan2) $ take n $ pairs $ map fromIntegral p\n b = maximum $ zipWith (-) (t ++ [h + 2 * pi]) a :: Double\n print $ 360 - 180 / pi * b\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain = putStrLn . show . solve . tail . map (toEnum . maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Double] -> Double\nsolve cs = 360 - maximum (zipWith (-) (ts ++ [360 + t]) (t : ts))\n where\n (t : ts) = theta cs\n\ntheta :: [Double] -> [Double]\ntheta (x : y : cs) = t : theta cs\n where\n l = sqrt $ x * x + y * y\n t' = acos (x / l) * 180 / pi\n t = if y >= 0 then t' else 360 - t'\ntheta _ = []\n"}], "src_uid": "a67cdb7501e99766b20a2e905468c29c"} {"source_code": "import Data.List (intercalate)\n\n\nminimumInstability :: [Float] -> Int\nminimumInstability xs = (ceiling d) - (floor d)\n where (s, n) = (sum xs, length xs)\n d = s / (fromIntegral) n\n\nfindMs :: [Int] -> ((Int, Int), (Int, Int)) -> Int -> ((Int, Int), (Int, Int))\nfindMs (x : xs) res@((resmaxn, resmaxv), (resminn, resminv)) k\n | x > resmaxv = findMs xs ((k, x), (resminn, resminv)) (k + 1)\n | x < resminv = findMs xs ((resmaxn, resmaxv), (k, x)) (k + 1)\n | otherwise = findMs xs res (k + 1)\nfindMs _ res _ = res\n\nmove :: [Int] -> Int -> Int -> [Int]\nmove (x:xs) nmin nmax\n | nmin == 1 && nmax == 1 = x:xs\n | nmin == 1 = (x+1) : (move xs (nmin - 1) (nmax - 1))\n | nmax == 1 = (x-1) : (move xs (nmin - 1) (nmax - 1))\n | nmin < 1 && nmax < 1 = x:xs\n | otherwise = x : (move xs (nmin - 1) (nmax - 1))\nmove _ _ _ = []\n\ntowers :: Int -> Int -> [Int] -> [(Int, Int)]\ntowers k steps all@(x:xs)\n | k == 0 = [(instability, steps)]\n | minimumInstability (map fromIntegral all) == instability = [(instability, steps)]\n | otherwise = (i, j) : (towers (k-1) (steps + 1) ys)\n where instability = vmax - vmin\n ((nmax, vmax), (nmin, vmin)) = findMs xs ((1,x), (1,x)) 2\n (i, j) = (nmax, nmin)\n ys = move all nmin nmax\n\n\noutput :: [(Int, Int)] -> String\noutput xs = intercalate \"\\n\" $ map (\\(x, y) -> intercalate \" \" [show x, show y]) (last xs : init xs)\n\nmain = do\n [n, k] <- fmap words $ getLine\n getLine >>= putStrLn . output . (towers (read k) 0) . fmap read . words\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = interact $ unlines . map (unwords . map show) . getAns . map read . words\n\ngetAns :: [Int] -> [[Int]]\ngetAns (n:k:xs) = let ans = move (zip xs [1..n]) k \n\t\t\t\t in ([head $ last ans, length ans - 1]) : (init ans)\n\ngetIsb :: [(Int, Int)] -> Int\ngetIsb xs = (fst $ maximum xs) - (fst $ minimum xs)\n\nmove :: [(Int, Int)] -> Int -> [[Int]] \nmove xs 0 = [[getIsb xs, 0]]\nmove xs k \n\t| isb <= 1 = [[isb, 0]]\n\t| otherwise = let sx = sort xs;\n\t\t\t\t\t (hi, hv) = head sx;\n\t\t\t\t\t (ti, tv) = last sx;\n\t\t\t\t\t nx = (hi + 1, hv ) : ((tail $ init sx) ++ [(ti - 1, tv)]);\n\t\t\t\t\t pans = move nx (k - 1);\n\t\t\t\t in [tv, hv] : pans\n\twhere isb = getIsb xs\n"}, {"source_code": "import Data.Array\n\nimport Data.List\nimport GHC.Exts\nimport Data.Set hiding (map)\n\n--type tower = Set (Int,Int)\n\n--next :: tower -> (tower,[Int])\nnext t = Just ([hi-hj,i,j],t3) where\n ((hi,i),t1) = deleteFindMax t\n ((hj,j),t2) = deleteFindMin t1 \n t3 = Data.Set.insert (hi-1,i) $ Data.Set.insert (hj+1,j) t2\n\nsolve (1:_) = [[0,0]]\nsolve (_:k:l) = [s!!n!!0,n]:map tail s' where \n s = unfoldr next $ fromList $ l `zip` [1..]\n s' = takeWhile ((>1).(!!0)) $ take k s\n n = length s'\n\nmain = interact $ unlines . map (unwords . map show) . solve . map read . words"}], "negative_code": [{"source_code": "import Data.Array\n\nimport Data.List\nimport GHC.Exts\nimport Data.Set hiding (map)\n\n--type tower = Set (Int,Int)\n\n--next :: tower -> (tower,[Int])\nnext t = Just ([hi-hj,i,j],t3) where\n ((hi,i),t1) = deleteFindMax t\n ((hj,j),t2) = deleteFindMin t1 \n t3 = Data.Set.insert (hi-1,i) $ Data.Set.insert (hj+1,j) t2\n\nsolve (_:k:l) = [s!!k!!0,k]:map tail (take k s) where s = unfoldr next $ fromList $ l `zip` [1..]\n\nmain = interact $ unlines . map (unwords . map show) . solve . map read . words"}], "src_uid": "9cd42fb28173170a6cfa947cb31ead6d"} {"source_code": "{-# LANGUAGE FlexibleInstances, UndecidableInstances, DuplicateRecordFields #-}\n\nmodule Main where\n\nimport Control.Monad\nimport System.IO\n\ncalculate 1 = 0\ncalculate 2 = 1\ncalculate 3 = 2\ncalculate 4 = 2\ncalculate n \n | (mod n 2) == 1 = 3\n | otherwise = 2\n\n\n\nmain :: IO()\nmain = do\n t <- readLn :: IO Int\n forM_ [1..t] $ \\t_itr -> do\n nmsTemp <- getLine\n let nms = words nmsTemp\n let n = read (nms !! 0) :: Int\n let result = calculate n \n putStrLn(show result)\n\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\n\nsolve :: Int -> Int\nsolve n\n | n <= 3 = n - 1\n | even n = 2\n | odd n = 3\n"}, {"source_code": "{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor ( (<&>) )\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Maybe (fromJust)\nimport Data.Traversable (forM)\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.IntMap as IM\nimport Control.Monad (foldM_)\nimport Data.Int\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nsolve :: [Int] -> [Int]\nsolve = fmap solve'\n where\n solve' n\n | n <= 3 = n - 1\n | even n = 2\n | otherwise = 3\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n ns <- forM [1 .. t] $ \\_ -> B8.getLine <&> readIntB8 <&> fromJust\n let answer = solve ns\n forM_ answer $ printf \"%d\\n\""}, {"source_code": "import Control.Monad\n-- input n is an integer\n-- get n to 1 with as few operations as possible\n-- allowed operations:\n-- 1. subtract n by 1\n-- 2. divide n by a proper divisor\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n n <- read <$> getLine\n putStrLn $ show $ solve n\n\nsolve :: Int -> Int\nsolve 1 = 0\nsolve 2 = 1\nsolve 3 = 2\nsolve n =\n if even n\n then 2\n else 3\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\n\nsolve :: Int -> Int\nsolve n\n | n == 1 = 0\n | n == 2 = 1\n | even n = 2\n | odd n = 3\n"}, {"source_code": "{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor ( (<&>) )\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Maybe (fromJust)\nimport Data.Traversable (forM)\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.IntMap as IM\nimport Control.Monad (foldM_)\nimport Data.Int\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nsolve :: [Int] -> [Int]\nsolve = fmap solve'\n where\n solve' n\n | n <= 3 = n - 1\n | even n = 2\n | otherwise = 3\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n ns <- forM [1 .. t] $ \\_ -> B8.getLine <&> readIntB8 <&> fromJust\n let answer = solve ns\n forM_ ns $ printf \"%d\\n\""}, {"source_code": "import Control.Monad\n-- input n is an integer\n-- get n to 1 with as few operations as possible\n-- allowed operations:\n-- 1. subtract n by 1\n-- 2. divide n by a proper divisor\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n n <- read <$> getLine\n putStrLn $ show $ solve n 0\n\nsolve :: Int -> Int -> Int\nsolve 1 counter = counter\nsolve n counter =\n if ld < n\n then solve (div n (div n ld)) (counter + 1)\n else solve (n - 1) (counter + 1)\n where\n ld = smallestDivisor n\n\nsmallestDivisor :: Int -> Int\nsmallestDivisor n = smallestDivisor' n 2\n where\n smallestDivisor' n 2 =\n if mod n 2 == 0\n then 2\n else smallestDivisor' n 3\n smallestDivisor' n try =\n if mod n try == 0\n then try\n else smallestDivisor' n (try + 2)\n"}], "src_uid": "614aa068ce74090b6577006c45e549cf"} {"source_code": "{-# LANGUAGE MagicHash, UnboxedTuples #-}\nimport qualified Data.ByteString as BS\nimport Control.Arrow\n\nr1 [] = []\nr1 (h : t) = (h, t) : map (second (h:)) (r1 t)\n\nbf :: [(Int, String)] -> [(Int, String)]\nbf [x] = [x]\nbf l = do\n let (a,as) +++ (b, bs) = (a + b, \"(\" ++ as ++ \"+\" ++ bs ++ \")\")\n let (a,as) +-- (b, bs) = (a - b, \"(\" ++ as ++ \"-\" ++ bs ++ \")\")\n let (a,as) +** (b, bs) = (a * b, \"(\" ++ as ++ \"*\" ++ bs ++ \")\")\n (a, l) <- r1 l\n (b, l) <- r1 l\n concat [bf (a +++ b : l), bf (a +-- b : l), bf (a +** b : l)]\n\ns5 = [\"5 * 4 = 20\", \"3 + 2 = 5\", \"20 + 5 = 25\", \"25 - 1 = 24\"]\ns4 = [\"1 * 2 = 2\", \"2 * 3 = 6\", \"6 * 4 = 24\"]\ns :: Int -> Maybe [String]\ns 0 = Nothing\ns 1 = Nothing\ns 2 = Nothing\ns 3 = Nothing\ns 5 = Just s5\ns 4 = Just s4\ns n = Just $ \n concat [[show (n - i*2) ++ \" - \" ++ show (n - i*2 - 1) ++ \" = 1\", \"1 * 1 = 1\"] |i<-[0..(n-4) `div` 2-1]]\n ++ concat [s5|odd n]\n ++ concat [s4|even n]\n\npp Nothing = [\"NO\"]\npp (Just ss) = \"YES\" : ss\n\nmain = interact $ unlines . pp . s . read\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nmain = interact $ unlines . reverse . getAns . read\n\ngetAns :: Int -> [String]\ngetAns x\n\t| x < 4 = [\"NO\"]\n\t| x == 4 = [\"6 * 4 = 24\", \"2 * 3 = 6\", \"1 * 2 = 2\", \"YES\"]\n\t| x == 5 = [\"1 * 24 = 24\", \"4 * 6 = 24\", \"5 + 1 = 6\", \"3 - 2 = 1\", \"YES\"]\n\t| otherwise = [\"1 * 24 = 24\", show x ++ \" - \" ++ show (x - 1) ++ \" = 1\"] ++ getAns (x - 2)\n"}, {"source_code": "\ndata Instr = Int :+ Int | Int :* Int | Int :- Int\n\nmain = do\n n <- fmap read getLine\n case genAns n of\n [] -> putStrLn \"NO\"\n is -> putStrLn \"YES\" >> putStrLn is\n\ngenAns :: Int -> String\ngenAns = unlines . map renderInstr . solve\n\nrenderInstr :: Instr -> String\nrenderInstr (x :+ y) = show x ++ \" + \" ++ show y ++ \" = \" ++ show (x+y)\nrenderInstr (x :- y) = show x ++ \" - \" ++ show y ++ \" = \" ++ show (x-y)\nrenderInstr (x :* y) = show x ++ \" * \" ++ show y ++ \" = \" ++ show (x*y)\n\nsolve :: Int -> [Instr]\nsolve n | n < 4 = []\n | n == 4 = genFrom4\n | n == 5 = genFrom5\n | even n = evenInstr n\n | odd n = oddInstr n\n\n\noddInstr n = genFrom5 ++ subtractConsecPairs [6,8..n] ++ \n multiplyAll1s (length [6,8..n]) ++ mul24And1\n\ngenFrom5 = [5 :* 4, 20 :+ 2, 22 :+ 3, 25 :- 1]\n\nevenInstr n = genFrom4 ++ subtractConsecPairs [5,7..n] ++ \n multiplyAll1s (length [5,7..n]) ++ mul24And1\n\ngenFrom4 = [4 :* 3, 12 :* 2, 24 :* 1]\nmul24And1 = [24 :* 1]\n\n\nmultiplyAll1s n = replicate (n-1) mul1s\n where \n mul1s = 1 :* 1\nsubtractConsecPairs l = l >>= \\x -> [(x+1) :- x]\n"}, {"source_code": "import Control.Monad\nmain = interact $ solve . read\nsolve n\n\t| n<4 = \"NO\"\n\t| odd n = \"YES\\n5 * 4 = 20\\n3 + 2 = 5\\n20 + 5 = 25\\n25 - 1 = 24\\n\" ++ gen 6 n\n\t| even n = \"YES\\n1 * 2 = 2\\n2 * 3 = 6\\n6 * 4 = 24\\n\\n\" ++ gen 5 n\n\twhere gen x y= if x>=y then \"\" else show (x+1) ++ \" - \" ++ show x ++ \" = 1\\n1 * 24 = 24\\n\" ++ gen (x+2) y\n\n"}, {"source_code": "import Data.List\n\ndata Opr = Opr Char Integer Integer \n\napplyOpr :: Opr -> Integer\napplyOpr (Opr c a b) = case c of\n '+' -> a + b\n '-' -> a - b\n '*' -> a * b\n\ndata Answer = No | Yes [Opr]\n\ninstance Show Opr where\n show opr@(Opr c a b) = unwords [show a, [c], show b, \"=\", show $ applyOpr opr]\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes oprs) = init . unlines $ [\"YES\"] ++ map show oprs\n\nsolve :: Integer -> Answer\nsolve 1 = No\nsolve 2 = No\nsolve 3 = No\nsolve 4 = Yes [Opr '*' 1 2, Opr '*' 2 3, Opr '*' 6 4]\nsolve 5 = Yes [Opr '*' 4 5, Opr '+' 2 3, Opr '-' 5 1, Opr '+' 20 4]\nsolve 6 = Yes [Opr '*' 2 3, Opr '*' 6 4, Opr '+' 1 5, Opr '-' 6 6, Opr '+' 0 24]\n-- n > 6\nsolve n = Yes $ [ Opr '*' 2 3, Opr '*' 6 4, Opr '+' 1 5, Opr '-' 6 6\n ] ++ reverse mid ++ [Opr '*' x 0, Opr '+' 0 24] where\n (x, mid) = foldl' (\\(s, oprs) x -> (s + x, (Opr '+' s x):oprs)) (7, []) [8..n]\n \n\nmain = do\n n <- return . read =<< getLine\n print $ solve n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nsolve :: [Int] -> Maybe [String]\nsolve xs = evalState (go xs) M.empty where\n go [s] = return $ if s == 24 then Just [] else Nothing\n go l = do\n memo <- get\n case M.lookup l memo of\n Just b -> return b\n Nothing -> do\n b <- msum <$> mapM (\\(l,s) -> fmap (fmap (s:)) (go l)) (next l)\n pure b <* modify (M.insert l b)\n\nsolve1 :: Int -> Maybe [String]\nsolve1 n | n <= 7 = solve [1..n] | otherwise = fmap (xs++) $ solve [1..if even n then 6 else 7] where\n xs = concat [[pprint i (i-1) ((-),\"-\"), pprint 1 6 ((*),\"*\")] | i <- [n,n-2..8]]\n\n\n\npprint :: Int -> Int -> (Int->Int->Int,String) -> String\npprint v w (op,opcode) = unwords $ [show v, opcode, show w, \"=\", show (op v w)]\n\n\nnext :: [Int] -> [([Int],String)]\nnext l = M.toList $ M.fromList $ do\n (i,v) <- zip [1..] l\n (j,w) <- zip [1..] l\n guard $ i /= j\n (op,opcode) <- [((+),\"+\"),((-),\"-\"),((*),\"*\")]\n let s = pprint v w (op,opcode)\n return (insert (op v w) (delete v $ delete w l), s)\n\nmain = do\n n <- readLn\n case solve1 n of\n Nothing -> putStrLn \"NO\"\n Just xs -> putStrLn \"YES\" >> forM_ xs putStrLn\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = interact $ solve.read\n\nsolve :: Int -> String\nsolve n\n | n <= 3 = \"NO\"\n | even n = \"YES\\n\" ++ solveEven n\n | otherwise = \"YES\\n\" ++solveOdd n\n\nsolveEven n = go n\n where\n go n\n | n > 4 = show n ++ \" - \" ++ show (n-1) ++ \" = 1\\n\"\n ++ \"1 * \" ++ show (n-2) ++ \" = \" ++ show (n-2) ++ \"\\n\"\n ++ go (n-2)\n | n == 4 = unlines [ \"1 * 2 = 2\"\n , \"3 * 4 = 12\"\n , \"2 * 12 = 24\"\n ]\n\nsolveOdd n = go n\n where\n go n\n | n > 5 = show n ++ \" - \" ++ show (n-1) ++ \" = 1\\n\"\n ++ \"1 * \" ++ show (n-2) ++ \" = \" ++ show (n-2) ++ \"\\n\"\n ++ go (n-2)\n | n == 5 = unlines [ \"5 * 4 = 20\"\n , \"2 + 3 = 5\"\n , \"5 - 1 = 4\"\n , \"20 + 4 = 24\"\n ]"}], "negative_code": [{"source_code": "import Control.Monad\nmain = interact $ solve . read\nsolve n\n\t| n<4 = \"NO\"\n\t| odd n = \"YES\\n5 * 4 = 20\\n3 + 2 = 5\\n20 + 5 = 25\\n25 - 1 = 24\\n\" ++ gen 6 n\n\t| even n = \"YES\\n1 * 2 = 2\\n2 * 3 = 6\\n6 * 4 = 24\\n25 - 1 = 24\\n\" ++ gen 5 n\n\twhere gen x y= if x>=y then \"\" else show (x+1) ++ \" - \" ++ show x ++ \" = 1\\n1 * 24 = 24\\n\" ++ gen (x+2) y\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nsolve :: [Int] -> Maybe [String]\nsolve xs = evalState (go xs) M.empty where\n go [s] = return $ if s == 24 then Just [] else Nothing\n go l = do\n memo <- get\n case M.lookup l memo of\n Just b -> return b\n Nothing -> do\n b <- msum <$> mapM (\\(l,s) -> fmap (fmap (s:)) (go l)) (next l)\n pure b <* modify (M.insert l b)\n\nsolve1 :: Int -> Maybe [String]\nsolve1 n | n <= 7 = solve [1..n] | otherwise = fmap (xs++) $ solve [1..6] where\n xs = concat [[pprint i (i-1) ((-),\"-\"), pprint 1 6 ((*),\"*\")] | i <- [n,n-2..8]]\n\n\n\npprint :: Int -> Int -> (Int->Int->Int,String) -> String\npprint v w (op,opcode) = unwords $ [show v, opcode, show w, \"=\", show (op v w)]\n\n\nnext :: [Int] -> [([Int],String)]\nnext l = M.toList $ M.fromList $ do\n (i,v) <- zip [1..] l\n (j,w) <- zip [1..] l\n guard $ i /= j\n (op,opcode) <- [((+),\"+\"),((-),\"-\"),((*),\"*\")]\n let s = pprint v w (op,opcode)\n return (insert (op v w) (delete v $ delete w l), s)\n\nmain = do\n n <- readLn\n case solve1 n of\n Nothing -> putStrLn \"NO\"\n Just xs -> putStrLn \"YES\" >> forM_ xs putStrLn\n"}, {"source_code": "{-# LANGUAGE MagicHash, UnboxedTuples #-}\nimport qualified Data.ByteString as BS\nimport Control.Arrow\n\nr1 [] = []\nr1 (h : t) = (h, t) : map (second (h:)) (r1 t)\n\nbf :: [(Int, String)] -> [(Int, String)]\nbf [x] = [x]\nbf l = do\n let (a,as) +++ (b, bs) = (a + b, \"(\" ++ as ++ \"+\" ++ bs ++ \")\")\n let (a,as) +-- (b, bs) = (a - b, \"(\" ++ as ++ \"-\" ++ bs ++ \")\")\n let (a,as) +** (b, bs) = (a * b, \"(\" ++ as ++ \"*\" ++ bs ++ \")\")\n (a, l) <- r1 l\n (b, l) <- r1 l\n concat [bf (a +++ b : l), bf (a +-- b : l), bf (a +** b : l)]\n\ns5 = [\"5 * 4 = 20\", \"3 + 2 = 5\", \"20 + 5 = 25\", \"25 - 1 = 24\"]\ns4 = [\"1 * 2 = 2\", \"2 * 3 = 6\", \"6 * 4 = 24\"]\ns :: Int -> Maybe [String]\ns 0 = Nothing\ns 1 = Nothing\ns 2 = Nothing\ns 3 = Nothing\ns 5 = Just s5\ns 4 = Just s4\ns n = Just $ \n concat [[show (n - i*2) ++ \" - \" ++ show (n - i*2 - 1) ++ \" = 1\", \"1 * 1 = 1\"] |i<-[1..(n-4) `div` 2]]\n ++ concat [s5|odd n]\n ++ concat [s4|even n]\n\npp Nothing = [\"NO\"]\npp (Just ss) = \"YES\" : ss\n\nmain = interact $ unlines . pp . s . read\n"}], "src_uid": "1bd1a7fd2a07e3f8633d5bc83d837769"} {"source_code": "import Data.List (sort)\n\nmain = do\n\t(n:as) <- fmap (map read . words) getContents\n\tlet a = sort as\n\tlet b = zipWith (-) (tail a) a\n\tlet g = foldl1 gcd b\n\tprint $ (quot ((a !! (n - 1)) - (a !! 0)) g) - (n - 1)", "positive_code": [{"source_code": "import Data.List;\n\nmain = getContents >>= (print . f . sort . tail . map mread . words)\t\n\twhere\n\t\tmread n = read n\n\t\tmaxx [] = -2000000001\n\t\tmaxx (x : xz) = max x (maxx xz)\n\t\tminn [] = 2000000001\n\t\tminn (x : xz) = min x (minn xz)\n\t\tg _ [] = 0\n\t\tg b (x : xz) = gcd (x - b) (g x xz)\n\t\tf t@(x :xz) = div (maxx t - minn t) (g x xz) - length xz\n\t\t\t\n\t\t"}, {"source_code": "module Main where\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain = do\n\tn <- read <$> getLine :: IO Int\n\ta <- sort . map read . words <$> getLine :: IO [Int]\n\tlet b = zipWith (-) (tail a) a\n\tlet g = foldl gcd 0 b\n\tlet h = map (\\x -> x `div` g - 1) b\n\tlet ans = sum h\n\tputStrLn $ show ans\n\treturn ()"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n num <- getLine\n temp <- getLine\n let arr = toSub . sorted $ temp\n putStrLn . show $ cal arr (minimum . toGcd $ arr)\n\nsorted :: String -> [Int]\nsorted = sort . map read . words\n\ntoSub :: [Int] -> [Int]\ntoSub [_] = []\ntoSub (x:rest@(y:ys)) = [y - x] ++ toSub rest\n\ntoGcd :: [Int] -> [Int]\ntoGcd [_] = []\ntoGcd (x:rest@(y:ys)) = [gcd x y] ++ toGcd rest\n\ncal :: [Int] -> Int -> Int\ncal lst dis = sum (map (`div` dis) lst) - length lst"}, {"source_code": "import Data.List\n\nmain = interact $ show . f . map read . words . last . lines\n\nf :: [Int] -> Int\nf ls = ((maximum ls - minimum ls) `div` \n (foldl1' gcd $ zipWith (-) ls (tail ls))) + 1 - length ls"}, {"source_code": "import Data.List\n\nsolve :: Int -> [Int] -> Int\nsolve a b =\n (div (maxi - mini) g) - (a-1)\n where\n maxi = maximum b\n mini = minimum b\n l = map (\\x -> x-mini) b\n g = foldl gcd (head l) l\n\nmain :: IO ()\nmain = do\n a <- readLn :: IO Int\n ln <- getLine\n let b = map read $ words ln\n print $ solve a b\n"}, {"source_code": "import Data.List\n\nsolve :: Int -> [Int] -> Int\nsolve a b =\n (div (maxi - mini) g) - (a-1)\n where\n maxi = maximum b\n mini = minimum b\n l = map (\\x -> x-mini) b\n g = foldr gcd (head l) l\n\nmain :: IO ()\nmain = do\n a <- readLn :: IO Int\n ln <- getLine\n let b = map read $ words ln\n print $ solve a b"}, {"source_code": "import Data.List\n\nmain = interact $ show . f . map read . words . last . lines\n\nf :: [Int] -> Int\nf ls = ((maximum ls - minimum ls) `div` \n (foldl1' gcd $ zipWith (-) ls (tail ls))) + 1 - length ls"}, {"source_code": "module Main where\n\n\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n xs = let\n a1 = minimum xs\n x = foldr1 gcd $ map (\\x -> x - a1) xs\n an = maximum xs\n in ((an - a1) `div` x) - n + 1\n\n\nmain :: IO ()\nmain = do\n n' <- getLine\n xs' <- getLine\n let n = read n' :: Integer\n let xs = map read $ words xs' :: [Integer]\n print $ solve n xs \n"}, {"source_code": "import Data.List\n\nqweqwe :: [Int] -> Int -> Int\nqweqwe (_:[]) ans = ans\nqweqwe (a:b) (-1) = qweqwe b ((head b) - a)\nqweqwe (a:b) ans = qweqwe b (gcd ans ((head b) - a))\n\nmain = do\n\tgetLine\n\tl <- getLine\n\tlet a = map read $ words l :: [Int]\n\tlet b = sort a\n\tprint (div ((last b) - (head b)) (qweqwe b (-1)) - (length b) + 1)"}, {"source_code": "import Data.List (sort)\n\ndiff [] = []\ndiff (x:[]) = []\ndiff (x:y:xs) = (y-x):(diff (y:xs))\n\nggcd [x] = x\nggcd (x:xs) = gcd x (ggcd xs)\n\nres [] g = 0\nres (d:ds) g = (d `div` g - 1) + (res ds g)\n\nmain = do\n (n:xs) <- fmap (map read . words) getContents\n let ds = diff (sort xs :: [Integer])\n let g = ggcd ds\n print (res ds g)\n -- print ks\n"}, {"source_code": "import Data.List (sort)\n \ndiff [] = []\ndiff (x:[]) = []\ndiff (x:y:xs) = (y-x):(diff (y:xs))\n \nggcd [x] = x\nggcd (x:xs) = gcd x (ggcd xs)\n \nres [] g = 0\nres (d:ds) g = (d `div` g - 1) + (res ds g)\n \nmain = do\n (n:xs) <- fmap (map read . words) getContents\n let ds = diff (sort xs :: [Integer])\n let g = ggcd ds\n print (res ds g)\n -- print ks"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n num <- getLine\n temp <- getLine\n let arr = toSub . sorted $ temp\n putStrLn . show $ cal arr (minimum arr)\n\nsorted :: String -> [Int]\nsorted = sort . map read . words\n\ntoSub :: [Int] -> [Int]\ntoSub [_] = []\ntoSub (x:rest@(y:ys)) = [y - x] ++ toSub rest\n\ntoGcd :: [Int] -> [Int]\ntoGcd [_] = []\ntoGcd (x:rest@(y:ys)) = [gcd x y] ++ toGcd rest\n\ncal :: [Int] -> Int -> Int\ncal lst dis = sum (map (`div` dis) lst) - length lst"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n num <- getLine\n temp <- getLine\n let arr = toSub . sorted $ temp\n putStrLn . show $ cal arr (minimum arr)\n\nsorted :: String -> [Int]\nsorted = sort . map read . words\n\ntoSub :: [Int] -> [Int]\ntoSub [_] = []\ntoSub (x:all@(y:ys)) = [y - x] ++ toSub all\n\ncal :: [Int] -> Int -> Int\ncal lst dis = sum (map (`div` dis) lst) - length lst"}, {"source_code": "module Main where\n\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n xs = let\n x = foldr1 gcd xs\n an = maximum xs\n a1 = minimum xs\n in ((an - a1) `div` x) - n + 1\n\n\nmain :: IO ()\nmain = do\n n' <- getLine\n xs' <- getLine\n let n = read n' :: Integer\n let xs = map read $ words xs' :: [Integer]\n print $ solve n xs \n"}, {"source_code": "module Main where\n\n\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n xs = let\n a1 = minimum xs\n x = foldr1 gcd $ map (+a1) xs\n an = maximum xs\n in ((an - a1) `div` x) - n + 1\n\n\nmain :: IO ()\nmain = do\n n' <- getLine\n xs' <- getLine\n let n = read n' :: Integer\n let xs = map read $ words xs' :: [Integer]\n print $ solve n xs \n"}, {"source_code": "import Data.List;\n\nmain = getContents >>= (print . f . sort . tail . map mread . words)\t\n\twhere\n\t\tmread n = read n\n\t\tmaxx [] = -1000000001\n\t\tmaxx (x : xz) = max x (maxx xz)\n\t\tminn [] = 1000000001\n\t\tminn (x : xz) = min x (minn xz)\n\t\tg _ [] = 0\n\t\tg b (x : xz) = gcd (x - b) (g x xz)\n\t\tf xz = div (maxx xz - minn xz) (g 0 xz) - length xz + 1\n\t\t\t\n\t\t"}], "src_uid": "805d82c407c1b34f217f8836454f7e09"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nmain :: IO ()\nmain = do\n (sn:st:sc:_) <- C.words <$> C.getLine\n let n = readInt sn\n t = readInt st\n c = read $ C.unpack sc\n a <- map readInt . C.words <$> C.getLine\n _m <- C.getLine\n p <- map readInt . C.words <$> C.getLine\n let x, y :: UArray Int Double\n a' = [fromIntegral i / fromIntegral t | i <- a]\n x = listArray (0, n) $ scanl (+) 0 a'\n y = listArray (0, n) $ scanl (\\i j -> i / c + j) 0 a'\n forM_ p $ \\i -> do\n let real = x!i - x!(i-t)\n approx = y!i / c\n err = abs (real - approx) / real\n putStrLn $ unwords $ map show [real, approx, err]\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(t, c) <- (\\[_, t, c] -> (read t, read c :: Double)) . words <$> getLine\n\ta <- getInts\n\tms <- getInts\n\n\tif length ms /= 1\n\t\tthen putStrLn \"botva\"\n\t\telse putStr \"\"\n\n\tis <- getInts\n\n\tlet \n\t\toutput = map (uncurry output') $ select $ zip real approx\n\t\t\twhere\n\t\t\t\ta' = map fromIntegral a\n\t\t\t\tt' = fromIntegral t\n\n\t\t\t\toutput' real approx = (real, approx, abs (approx - real) / real)\n\n\t\t\t\treal = map (/ t') $ zipWith (-) sums $ replicate t 0 ++ sums\n\t\t\t\t\twhere\n\t\t\t\t\t\tsums = scanl1 (+) a'\n\n\t\t\t\tapprox = tail $ scanl (\\m a -> (m + a / t') / c) 0.0 a'\n\n\t\t\t\tselect vs = select' is vs 1\n\t\t\t\t\twhere\n\t\t\t\t\t\tselect' [] _ _ = []\n\t\t\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\t\t\tif i == j \n\t\t\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\n\tputStrLn $ unlines $ map (unwords. map show . (\\(r, a, e) -> [r, a, e])) output\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(t, c) <- (\\[_, t, c] -> (read t, read c :: Double)) . words <$> getLine\n\ta <- getInts\n\tB.getLine\n\tis <- getInts\n\n\tlet \n\t\toutput = map (uncurry output') $ select $ zip real approx\n\t\t\twhere\n\t\t\t\ta' = map fromIntegral a\n\t\t\t\tt' = fromIntegral t\n\n\t\t\t\toutput' real approx = (real, approx, abs (approx - real) / real)\n\n\t\t\t\treal = map (/ t') $ zipWith (-) sums $ replicate t 0 ++ sums\n\t\t\t\t\twhere\n\t\t\t\t\t\tsums = scanl1 (+) a'\n\n\t\t\t\tapprox = tail $ scanl (\\m a -> (m + a / t') / c) 0.0 a'\n\n\t\t\t\tselect vs = select' is vs 1\n\t\t\t\t\twhere\n\t\t\t\t\t\tselect' [] _ _ = []\n\t\t\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\t\t\tif i == j \n\t\t\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\n\tputStrLn $ unlines $ map (unwords. map show . (\\(r, a, e) -> [r, a, e])) output\n"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(t, c) <- (\\[_, t, c] -> (read t, read c :: Float)) . words <$> getLine\n\ta <- getInts\n\tB.getLine\n\tis <- getInts\n\n\tlet \n\t\toutput = map (uncurry output') $ select $ zip real approx\n\t\t\twhere\n\t\t\t\ta' = map fromIntegral a\n\t\t\t\tt' = fromIntegral t\n\n\t\t\t\toutput' real approx = (real, approx, abs (approx - real) / real)\n\n\t\t\t\treal = map (/ t') $ zipWith (-) sums $ replicate t 0 ++ sums\n\t\t\t\t\twhere\n\t\t\t\t\t\tsums = scanl1 (+) a'\n\n\t\t\t\tapprox = tail $ scanl (\\m a -> (m + a / t') / c) 0.0 a'\n\n\t\t\t\tselect vs = select' is vs 1\n\t\t\t\t\twhere\n\t\t\t\t\t\tselect' [] _ _ = []\n\t\t\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\t\t\tif i == j \n\t\t\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\n\tputStrLn $ unlines $ map (unwords. map show . (\\(r, a, e) -> [r, a, e])) output\n"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain = do\n\t(n, t, c) <- (\\[n, t, c] -> (read n :: Int, read t :: Int, read c :: Float)) . words <$> getLine\n\ta <- map read . words <$> getLine\n\tgetLine\n\tis <- map read . words <$> getLine\n\n\tlet \n\t\treal = map (\\v -> (fromIntegral v) / (fromIntegral t)) $ zipWith (-) sums $ (replicate t 0) ++ sums\n\t\t\twhere\n\t\t\t\tsums = scanl1 (+) a\n\n\t\tapprox = tail $ scanl (\\m a -> (m + (fromIntegral a) / (fromIntegral t)) / c) 0.0 a\n\n\t\tselect vs = select' is vs 1\n\t\t\twhere\n\t\t\t\tselect' [] _ _ = []\n\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\tif i == j \n\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\t\toutput = map calc $ zip (select real) (select approx)\n\t\t\twhere\n\t\t\t\tcalc (real, approx) = (real, approx, abs (approx - real) / real)\n\n\tputStrLn $ unlines $ map (\\(r, a, e) -> show r ++ \" \" ++ show a ++ \" \" ++ show e) output\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(n, t, c) <- (\\[n, t, c] -> (read n :: Int, read t :: Int, read c :: Double)) . words <$> getLine\n\ta <- getInts\n\tgetLine\n\tis <- getInts\n\n\tlet \n\t\treal = map (\\v -> (fromIntegral v) / (fromIntegral t)) $ zipWith (-) sums $ (replicate t 0) ++ sums\n\t\t\twhere\n\t\t\t\tsums = scanl1 (+) a\n\n\t\tapprox = tail $ scanl (\\m a -> (m + (fromIntegral a) / (fromIntegral t)) / c) 0.0 a\n\n\t\tselect vs = select' is vs 1\n\t\t\twhere\n\t\t\t\tselect' [] _ _ = []\n\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\tif i == j \n\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\t\toutput = map calc $ zip (select real) (select approx)\n\t\t\twhere\n\t\t\t\tcalc (real, approx) = (real, approx, abs (approx - real) / real)\n\n\tputStrLn $ unlines $ map (\\(r, a, e) -> show r ++ \" \" ++ show a ++ \" \" ++ show e) output\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(n, t, c) <- (\\[n, t, c] -> (read n :: Int, read t :: Int, read c :: Double)) . words <$> getLine\n\ta <- getInts\n\tgetLine\n\tis <- getInts\n\n\tlet \n\t\treal = map (\\v -> (fromIntegral v) / (fromIntegral t)) $ zipWith (-) sums $ (replicate t 0) ++ sums\n\t\t\twhere\n\t\t\t\tsums = scanl1 (+) a\n\n\t\tapprox = tail $ scanl (\\m a -> (m + (fromIntegral a) / (fromIntegral t)) / c) 0.0 a\n\n\t\tselect vs = select' is vs 1\n\t\t\twhere\n\t\t\t\tselect' [] _ _ = []\n\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\tif i == j \n\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\t\toutput = map calc $ zip (select real) (select approx)\n\t\t\twhere\n\t\t\t\tcalc (real, approx) = (real, approx, abs (approx - real) / real)\n\n\tputStrLn $ unlines $ map (\\(r, a, e) -> show r ++ \" \" ++ show a ++ \" \" ++ show e) output\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(t, c) <- (\\[_, t, c] -> (read t, read c :: Double)) . words <$> getLine\n\ta <- getInts\n\tgetLine\n\tis <- getInts\n\n\tlet \n\t\toutput = map (uncurry output') $ select $ zip real approx\n\t\t\twhere\n\t\t\t\ta' = map fromIntegral a\n\t\t\t\tt' = fromIntegral t\n\n\t\t\t\toutput' real approx = (real, approx, abs (approx - real) / real)\n\n\t\t\t\treal = map (/ t') $ zipWith (-) sums $ replicate t 0 ++ sums\n\t\t\t\t\twhere\n\t\t\t\t\t\tsums = scanl1 (+) a'\n\n\t\t\t\tapprox = tail $ scanl (\\m a -> (m + a / t') / c) 0.0 a'\n\n\t\t\t\tselect vs = select' is vs 1\n\t\t\t\t\twhere\n\t\t\t\t\t\tselect' [] _ _ = []\n\t\t\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\t\t\tif i == j \n\t\t\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\n\tputStrLn $ unlines $ map (unwords. map show . (\\(r, a, e) -> [r, a, e])) output\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine\n\nmain = do\n\t(n, t, c) <- (\\[n, t, c] -> (read n :: Int, read t :: Int, read c :: Double)) . words <$> getLine\n\ta <- getInts\n\tgetLine\n\tis <- getInts\n\n\tlet \n\t\treal = map (\\v -> v / (fromIntegral t)) $ zipWith (-) sums $ (replicate t 0) ++ sums\n\t\t\twhere\n\t\t\t\tsums = scanl1 (+) $ map (\\v -> fromIntegral v :: Double) a\n\n\t\tapprox = tail $ scanl (\\m a -> (m + (fromIntegral a) / (fromIntegral t)) / c) 0.0 a\n\n\t\tselect vs = select' is vs 1\n\t\t\twhere\n\t\t\t\tselect' [] _ _ = []\n\t\t\t\tselect' (i:is) (v:vs) j = \n\t\t\t\t\tif i == j \n\t\t\t\t\t\tthen v : select' is vs (j + 1)\n\t\t\t\t\t\telse select' (i:is) vs (j + 1)\n\n\t\toutput = map calc $ zip (select real) (select approx)\n\t\t\twhere\n\t\t\t\tcalc (real, approx) = (real, approx, abs (approx - real) / real)\n\n\tputStrLn $ unlines $ map (\\(r, a, e) -> show r ++ \" \" ++ show a ++ \" \" ++ show e) output\n"}], "src_uid": "be8d2eff2f34e72625566680ae188c49"} {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Bits((.&.))\ndata Dir = L|R deriving (Eq)\nindicator :: Bool -> Int\nindicator b = if b then 1 else 0\nrevd :: Dir -> Dir\nrevd L = R\nrevd R = L\n\nsolve lns = let maxlength = (maximum.map length) lns\n w n = replicate n ' '\n rec [] _ = [replicate (maxlength+2) '*']\n rec (x:xs) dir = let margin = maxlength - (length x)\n leftm = div margin 2 +(indicator (dir==R&&odd margin))\n rightm =div margin 2 +(indicator (dir==L&&odd margin))\n in\n ('*':(w leftm)++x++(w rightm)++\"*\"):(if odd margin then rec xs (revd dir) else rec xs dir)\n in\n (replicate (maxlength+2) '*'):(rec lns L)\n\nmain = do input <- getContents\n let lns = lines input\n mapM_ putStrLn (solve lns)", "positive_code": [{"source_code": "import Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nsolve :: [String] -> [String]\nsolve ss = concat\n [[colontitul],\n map snd $ tail $ scanl solve' (True, \"\") ss,\n [colontitul]]\n where\n n = maximum $ map length ss\n colontitul = replicate (n+2) '*'\n solve' (b, _) s\n | s == \"\" = (b, \"*\" ++ replicate n ' ' ++ \"*\")\n | length s' < n = if b\n then (not b, \"*\" ++ s' ++ \" *\")\n else (not b, \"* \" ++ s' ++ \"*\")\n | otherwise = (b, \"*\" ++ s' ++ \"*\")\n where\n m = length s\n k = (n - m) `div` 2\n s' = concat\n [replicate k ' ', s, replicate k ' ']\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unlines . solve . lines"}, {"source_code": "import Control.Monad\n\nmain = do\n texts <- fmap lines getContents\n let chars = maximum $ map length texts\n putStrLn $ replicate (chars + 2) '*'\n foldM' texts $ \\left s -> do\n let len = length s\n x = replicate ((chars - len) `div` 2) ' '\n y | (chars - len) `mod` 2 == 0 = x\n | otherwise = ' ':x\n (leftSpace, rightSpace)\n | left = (y, x)\n | otherwise = (x, y)\n newLeft | (chars - len) `mod` 2 == 0 = left\n | otherwise = not left\n putStrLn $ \"*\" ++ leftSpace ++ s ++ rightSpace ++ \"*\"\n return newLeft\n putStrLn $ replicate (chars + 2) '*'\n\nfoldM' xs f = foldM_ f False xs\n"}, {"source_code": "module Main (main) where\n\nmain = do\n instr <- getContents\n let ls = lines instr\n putStr $ unlines $ solve ls where\n \n solve ls = stars (reverse (wrap (-1) (zip lens ls) [])) where\n \n max = maximum lens\n lens = map length ls\n probels = repeat ' '\n \n wrap _ [] acc = acc\n wrap lr ((len, s):ss) acc = if even razn \n then wrap lr ss ((probs ++ s ++ probs):acc)\n else if lr > 0 then wrap (-lr) ss ((probs ++ \" \" ++ s ++ probs):acc)\n else wrap (-lr) ss ((probs ++ s ++ probs ++ \" \"):acc) where\n razn = max - len\n r2 = div razn 2\n probs = take r2 probels\n \n stars ss = starn ++ map wrstar ss ++ starn where\n starn = [take (max + 2) $ repeat '*']\n wrstar s = \"*\" ++ s ++ \"*\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> [String]\nsolve = do\n ss <- id\n let ws = map length ss\n let wmax = maximum ws\n let ls = snd $ mapAccumL check 0 (map (`subtract` wmax) ws) where\n check acc n | even n = (acc, n `quot` 2)\n | otherwise = ((acc + 1) `rem` 2, (n + acc) `quot` 2)\n let hs = return $ replicate (wmax + 2) '*'\n let fs = hs\n let contens = do (w, l, s) <- zip3 ws ls ss\n return $ \"*\"\n ++ replicate l ' '\n ++ s\n ++ replicate (wmax - l - w) ' '\n ++ \"*\"\n return $ hs ++ contens ++ fs\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "main = do\n l <- lines `fmap` getContents\n let placeLength = maximum $ map length l\n center (left, res) s = \n let diff = placeLength - length s\n half = diff `div` 2\n r' = (flip replicate) ' '\n (l, r) = case (left, diff) of \n _ | even diff -> (left, r' half ++ s ++ r' half)\n | odd diff && left -> (not left, r' half ++ s ++ r' (half + 1))\n | otherwise -> (not left, r' (half + 1) ++ s ++ r' half) in\n (l, ('*':r++\"*\"):res)\n stars = putStrLn $ replicate (placeLength + 2) '*'\n stars\n mapM putStrLn $ reverse $ snd $ foldl center (True, []) l\n stars\n"}, {"source_code": "import Data.List\n\nmain = interact $ (dump . solve . load) where\n\tload :: String -> [String]\n\tload = lines\n\n\tdump :: [String] -> String\n\tdump = unlines\n\n\tsolve :: [String] -> [String]\n\tsolve ls = \n\t\tlet\n\t\t\tmaxLen = foldl1' max $ map length $ ls\n\t\t\tfillLR s left right = '*' : (replicate left ' ') ++ s ++ (replicate right ' ') ++ \"*\"\n\t\t\tfill s toLeft = \n\t\t\t\tlet \n\t\t\t\t\thalf = (maxLen - length s) `div` 2\n\t\t\t\tin\n\t\t\t\t\tif half * 2 == maxLen - length s then (fillLR s half half, toLeft)\n\t\t\t\t\telse \n\t\t\t\t\t\tif toLeft then (fillLR s half (half + 1), not toLeft)\n\t\t\t\t\t\telse (fillLR s (half + 1) half, not toLeft)\n\n\t\t\talter :: Bool -> [String] -> [String] -> [String]\n\t\t\talter _ [] acc = reverse acc\n\t\t\talter tl (x:xs) acc = \n\t\t\t\tlet \n\t\t\t\t\t(s, ntl) = fill x tl\n\t\t\t\tin\n\t\t\t\t\talter ntl xs (s : acc)\n\t\tin\n\t\t\t(replicate (maxLen + 2) '*') : (alter True ls []) ++ [(replicate (maxLen + 2) '*')]\n"}, {"source_code": "ast n = replicate n '*'\nspc n = replicate n ' '\n\nf w [] _ = []\nf w (l:ls) left =\n let n = (w-length l) `div` 2\n in if (w-length l) `mod` 2 == 0 then\n (\"*\"++spc n++l++spc n++\"*\") : f w ls left\n else\n (\"*\"++spc (n+left)++l++spc (n+1-left)++\"*\") : f w ls (1-left)\n\nmain = do\n contents <- return . lines =<< getContents\n let w = maximum $ map length contents\n mapM_ putStrLn $ [ast (w+2)]++f w contents 0++[ast (w+2)]"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n\ncopy :: Char -> Int -> String\ncopy _ 0 = \"\"\ncopy c n = c:(copy c (n - 1))\n\nprintAns :: Int -> Int -> [String] -> IO()\nprintAns w par (a:b)\n | a == \"\" = do\n putStrLn (\"*\" ++ (copy ' ' w) ++ \"*\")\n printAns w par b\n | mod s 2 == 0 = do\n putStrLn (\"*\" ++ (copy ' ' (div s 2)) ++ a ++ (copy ' ' (div s 2)) ++ \"*\")\n printAns w par b\n | otherwise = do\n putStrLn (\"*\" ++ (copy ' ' (div s 2 + par)) ++ a ++ (copy ' ' (div s 2 + 1 - par)) ++ \"*\")\n printAns w (1 - par) b\n where s = w - length a\nprintAns _ _ _ = do\n putStr \"\"\n\nmain :: IO()\nmain = do\n input <- getContents\n let list = lines input\n let w = maximum (1 : map length list)\n putStrLn (copy '*' (w + 2))\n printAns w 0 list\n putStrLn (copy '*' (w + 2))\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\nimport Control.Monad (foldM_)\nimport Data.Functor (($>))\n\nmain :: IO ()\nmain = do\n ls <- T.lines <$> TIO.getContents\n let maxLength = maximum $ map T.length ls\n let frameStr = T.replicate (maxLength + 2) \"*\"\n TIO.putStrLn frameStr\n foldM_ (putFormattedStr maxLength) 0 ls\n TIO.putStrLn frameStr\n\nputFormattedStr :: Int -> Int -> T.Text -> IO Int\nputFormattedStr len add line = TIO.putStrLn formattedLine $> rem\n where\n spareLen = len - T.length line\n (left, rem) = (spareLen + add) `quotRem` 2\n right = spareLen - left\n formattedLine = \"*\" <> T.replicate left \" \" <> line <> T.replicate right \" \" <> \"*\""}, {"source_code": "g w = take w $ repeat '*'\nsp w = take w $ repeat ' '\n\nout :: Int -> [String] -> Bool -> [String]\nout width [] _ = []\nout width (s:sx) left | (width - length s) `mod` 2 == 0 =\n let w = (width - length s) `div` 2\n in ( sp w ++ s ++ sp w ):(out width sx left)\n | True =\n ( sp (c w left) ++ s ++ sp (c w (not left)) ):(out width sx (not left))\n where w = (width - length s) `div` 2\n c w True = w\n c w False = w+1\n\nmain = do\n s <- getContents\n let l = lines s\n width = maximum $ map length l\n output = [g width] ++ out width l True ++ [g width]\n mapM_ putStrLn $ map (\\a -> \"*\" ++ a ++ \"*\") output\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Text as T\nimport Data.Text.Encoding\nimport Data.Char\nimport Data.List\n\nmain = do\n t <- map (T.filter (\\x -> isAlphaNum x || x == ' ')) . T.lines . decodeUtf8 <$> B.getContents\n let (ls, m) = (map T.length t, maximum ls) \n bs = tail $ reverse $ foldl' (\\acc@(b:_) x -> if x < m && (x-m)`mod`2/=0 then (not b:acc) else b:acc) [True] ls\n border = T.pack $ replicate (m+2) '*'\n B.putStrLn $ encodeUtf8 $ T.unlines $ (border : zipWith (\\x b -> T.append ( T.cons '*' $ if b then T.center m ' ' x else T.reverse $ T.center m ' ' $ T.reverse x) $ T.pack \"*\") t bs ) ++ [border] \n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain = do\n texts <- fmap lines getContents\n let chars = maximum $ map length texts\n putStrLn $ replicate (chars + 2) '*'\n forM_ texts $ \\s -> do\n let len = length s\n leftSpace = replicate ((chars - len) `div` 2) ' '\n rightSpace | (chars - len) `mod` 2 == 0 = leftSpace\n | otherwise = ' ':leftSpace\n putStrLn $ \"*\" ++ leftSpace ++ s ++ rightSpace ++ \"*\"\n putStrLn $ replicate (chars + 2) '*'\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n-- Seems to be OK?\nsolve :: [String] -> [String]\nsolve = do\n ss <- id\n let w = maximum $ map length ss\n return ss\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n-- Compile Check\n-- How come we can't use function monad?\n\nsolve :: [String] -> [String]\nsolve = do\n s <- id\n return s\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "main = do\n l <- lines `fmap` getContents\n let placeLength = maximum $ map length l\n center (left, res) s = \n let diff = placeLength - length s\n half = diff `div` 2\n r' = (flip replicate) ' '\n (l, r) = case (left, diff) of \n _ | even diff -> (left, r' half ++ s ++ r' half)\n | odd diff && left -> (not left, r' half ++ s ++ r' (half + 1))\n | otherwise -> (not left, r' half ++ s ++ r' (half + 1)) in\n (l, ('*':r++\"*\"):res)\n stars = putStrLn $ replicate (placeLength + 2) '*'\n stars\n mapM putStrLn $ reverse $ snd $ foldl center (True, []) l\n stars\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport Data.Monoid\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\n\nmain :: IO ()\nmain = do\n ls <- T.lines <$> TIO.getContents\n let maxLength = maximum $ map T.length ls\n let frameStr = T.replicate (maxLength + 2) \"*\"\n TIO.putStrLn frameStr\n mapM_ (TIO.putStrLn . formatStr maxLength) ls\n TIO.putStrLn frameStr\n where\n center len line = T.replicate left \" \" <> line <> T.replicate (len - T.length line - left) \" \" where left = (len - T.length line) `div` 2\n formatStr len line = \"*\" <> center len line <> \"*\""}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport Data.Monoid\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\n\nmain :: IO ()\nmain = do\n ls <- T.lines <$> TIO.getContents\n let maxLength = maximum $ map T.length ls\n let frameStr = T.replicate (maxLength + 2) \"*\"\n TIO.putStrLn frameStr\n mapM_ (TIO.putStrLn . formatStr maxLength) ls\n TIO.putStrLn frameStr\n where\n formatStr len instr = \"*\" <> T.center len ' ' instr <> \"*\""}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Text as T\nimport Data.Text.Encoding\n\nmain = do\n t <- T.lines . decodeUtf8 <$> B.getContents\n let m = foldr (\\x acc -> max acc $ T.length x) 0 t\n border = T.pack $ replicate (m+2) '*'\n B.putStrLn $ encodeUtf8 $ T.unlines $ (border : map (\\x -> T.append ( T.cons '*' $ T.reverse $ T.center m ' ' $ T.reverse x) $ T.pack \"*\") t ) ++ [border] \n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\nsolve :: [String] -> [String]\nsolve ss = concat\n [[colontitul],\n map snd $ tail $ scanl solve' (True, \"\") ss,\n [colontitul]]\n where\n n = maximum $ map length ss\n colontitul = replicate (n+2) '*'\n solve' (b, _) s\n | s == \"\" = (b, replicate n ' ')\n | length s' < n = if b\n then (not b, \"*\" ++ s' ++ \" *\")\n else (not b, \"* \" ++ s' ++ \"*\")\n | otherwise = (b, \"*\" ++ s' ++ \"*\")\n where\n m = length s\n k = (n - m) `div` 2\n s' = concat\n [replicate k ' ', s, replicate k ' ']\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unlines . solve . lines"}], "src_uid": "a017393743ae70a4d8a9d9dc40410653"} {"source_code": "main :: IO()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (m:a) = solve' a\n where solve' :: [Int] -> Int\n solve' [] = -1\n solve' (x:y:s) | m > x && y == 0 = max 0 (solve' s)\n | m > x = max (100 - y) (solve' s)\n | m == x && y == 0 = max 0 (solve' s)\n | otherwise = solve' s\n", "positive_code": [{"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "-- Codeforces 463A\n\nmain :: IO ()\nmain = do\n [n, s] <- fmap (map read . words) getLine\n getContents >>= print . solve s . map (map read . words) . lines\n\nsolve :: Int -> [[Int]] -> Int\nsolve s xs = if length enough == 0 then (-1) else 100 - (minimum $ (100:) $ filter (/= 0) $ map (!!1) enough) where enough = filter (\\[a,b] -> a>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Integer]] -> Integer\nsolve ([_, s] : xys) = maximum $ -1 : [ if y > 0 then 100 - y else 0 | [ x, y ] <- xys, x * 100 + y <= s * 100 ]\nsolve _ = undefined\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "parse :: String -> (Int, Int)\nparse s = case map read (words s) of [x, y] -> (x, y)\nprice (x, y) = x * 100 + y\nsolve ((_,s):xs) = maximum $ (-1) : [if y > 0 then 100 - y else 0 | t@(_, y) <- xs, price t <= s * 100]\nmain = putStrLn . show . solve . map parse . lines =<< getContents"}, {"source_code": "import Control.Monad\ns([_,s]:l)=maximum ((-1):(l>>=(\\[d,c]->guard(d*100+c<=s*100)>>[if c==0 then 0 else 100-c])))\nmain=interact$show.s.map(map read.words).lines\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \nmain=do\t \n\t[n,s]<- map read.words <$> getLine:: IO [Int] \n\tt<- map (map read). map words . lines <$> getContents :: IO [[Int]]\n\tlet t1 = map last $ filter (\\z-> head z>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "\nmain = interact $ show . sol . map read . words\n\nsol (_:s:xs) = cal $ ok s xs\n\ncal [] = -1\ncal xs = maximum . map ((`mod`100).(100-).snd) $ xs\n\nok s = filter (\\(a, b) -> a < s || (a==s && b==0)) . tp\n\ntp [] = []\ntp (f:s:xs) = (f, s):(tp xs)\n\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . getAns . getIntArray\n\ngetAns :: [Int] -> Int\ngetAns (_:s:xs) = calMax s xs\n\ncalMax :: Int -> [Int] -> Int\ncalMax _ [] = -1\ncalMax s (x:y:xs) = let nm = if (x * 100 + y <= s * 100) then mod (100 - y) 100 else -1;\n\t\t\t\t\tin max nm $ calMax s xs\n\n\n"}, {"source_code": "main = interact $ show . f . map read . tail . words\nf (s:[]) = -1\nf (s:x:y:z) = max (if s * 100 < x * 100 + y then -1 else mod (s * 100 - x * 100 - y) 100) $ f (s:z)"}, {"source_code": "main=getContents>>=print.s.map(map read.words).lines\ns([_,s]:x)=maximum$ -1:[if y>0 then 100-y else 0|[x,y]<-x,x*100+y<=s*100]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\n\nans n = sort . map ((`mod`100) . (n-)) . filter (<= n) . map cost\n\twhere cost [d,c] = d*100 + c\n\nsolve [] = -1\nsolve l = last l\n\nmain = do\n\t\t[n,s] <- map read . words <$> getLine\n\t\txy <- replicateM n $ map read . words <$> getLine\n\t\tlet cent = 100*s\n \t\tprint $ solve $ ans cent xy\n"}], "negative_code": [{"source_code": "parse :: String -> (Int, Int)\nparse s = case map read (words s) of [x, y] -> (x, y)\nprice (x, y) = x * 100 + y\nmaxCents s p@(x, y) = maximum . map (`mod` 100) . takeWhile (> 0) $ map (\\x -> s - price p * x) [1..]\nsolve ((_,s'):xs) = let s = s' * 100 in case filter (\\x -> price x <= s) xs of\n [] -> (-1)\n rs -> maximum $ map (maxCents s) rs\nmain = putStrLn . show . solve . map parse . lines =<< getContents"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \nmain=do\t \n\t[n,s]<- map read.words <$> getLine:: IO [Int] \n\tt<- map (map read). map words . lines <$> getContents :: IO [[Int]]\n\tlet t1 = map last $ filter (\\z-> head z [String]\nsolve str = sort . toList . nth3_3 . foldr f f0 $ (drop 5 str)\n where f0 = ([True,False,False,False,False], \"-----\", empty)\n f :: Char -> ([Bool],[Char],Set String) -> ([Bool],[Char],Set String)\n f x0 (oks@[ok1,ok2,ok3,ok4,ok5], xs@[x1,x2,x3,x4,x5], suffixes) =\n let ok02 = ok2 && ok5\n || ok2 && [x0,x1] /= [x2,x3]\n ok03 = ok3 && ok5\n || ok3 && [x0,x1,x2] /= [x3,x4,x5]\n suffixes' = unions [ suffixes\n , if ok02 then singleton [x0,x1] else empty\n , if ok03 then singleton [x0,x1,x2] else empty\n ]\n in (enqueue (ok02 || ok03) oks, enqueue x0 xs, suffixes')\n nth3_3 (_,_,x) = x\n enqueue x xs = x : init xs\n\n\nsolve' :: String -> [String]\nsolve' str = sort . map reverse . toList . fst . suffixes (empty,\"\",0,empty) $ reverse str\n where suffixes :: (Set String, String, Int, Set Int) -> String -> (Set String, Set Int)\n suffixes (seen,prev,pos,processed) str =\n if pos `member` processed\n then (seen,processed) -- prune search of this branch - this state has already been explored\n else\n let (suffixes2,processed2) = case trySuffix 2 (seen,prev) str of\n Nothing ->\n (seen,processed)\n Just (seen',prev',str') ->\n suffixes (seen',prev',pos+2,processed) str'\n (suffixes3,processed3) = case trySuffix 3 (seen,prev) str of\n Nothing ->\n (seen,processed2)\n Just (seen',prev',str') ->\n suffixes (seen',prev',pos+3,processed2) str'\n in (unions [suffixes2, suffixes3], unions [processed2, processed3, singleton pos])\n trySuffix :: Int -> (Set String, String) -> String -> Maybe (Set String, String, String)\n trySuffix n (seen,prev) str\n | str `shorterThan` (5 + n) = Nothing\n | otherwise = let (suffix,rest) = splitAt n str\n in if suffix == prev\n then Nothing\n else Just (insert suffix seen, suffix, rest)\n\nshorterThan [] n = n > 0\nshorterThan xs n = shorterThan (tail xs) (n-1)\n\nmain :: IO ()\nmain = do\n word <- getLine\n let suffixes = solve word\n putStrLn $ show (length suffixes)\n mapM_ putStrLn suffixes\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain = do\n s <- fmap (B.init . B.drop 5) B.getLine\n let all = solve s\n print $ S.size all\n B.putStrLn $ (B.pack \"\\n\") `B.intercalate` S.toAscList all\n\nsolve s = all 0 d S.empty\n where d = dp s (B.length s - 4) [(False, True), (True, False), (False, False)]\n all i [] res = res\n all i ((v2,v3):xs) res = all (i + 1) xs res''\n where res' = if v2 then (cur2 s i) `S.insert` res else res\n res'' = if v3 then (cur3 s i) `S.insert` res' else res'\n\n\ndp s i res\n | i < 0 = drop (negate i - 1) res\n | otherwise = dp s (i - 1) ((v2, v3) : res)\n where v2 = snd (res !! 1) || (fst (res !! 1) && cur2 s i /= cur2 s (i + 2))\n v3 = fst (res !! 2) || (snd (res !! 2) && cur3 s i /= cur3 s (i + 3))\n\ncur2 s a = B.take 2 . B.drop a $ s\ncur3 s a = B.take 3 . B.drop a $ s\n"}, {"source_code": "import qualified Data.IntMap as IM\nimport Data.Char\nimport Data.IntMap ((!))\nimport Data.Ix (Ix, index, range)\nimport Data.List\n\nmain = do\n s <- getContents\n let strings = solve . filter (not.isSpace) $ s\n print $ length strings\n mapM_ putStrLn strings\n\nsolve s = map head . group . sort $ strings\n where\n ms = IM.fromList $ zip [0..] (reverse s)\n n = IM.size ms\n\n f _ (_, m) | n-m <= 5 = False\n f _ (2, 1) = True\n f _ (3, 2) = True\n f _ (_, m) | m <= 2 = False\n f rec (prev, m) = rec (5-prev, m-prev) || (rec (prev, m-prev) && not (eq (m-2*prev) (m-prev)))\n\n eq a b = and $ zipWith (==) (map (ms!) [a+1..b]) (map (ms!) [b+1 .. 2*b-a])\n\n isGood = immemo f (2,0) (3,n-1)\n\n good2 = [i | i <- [1..n-1], isGood (2, i)]\n good3 = [i | i <- [2..n-1], isGood (3, i)]\n strings = [[ms!i, ms!(i-1)] | i <- good2] ++ [[ms!i, ms!(i-1), ms!(i-2)] | i <- good3]\n\n\nimmemo :: (Ix i) => ((i -> a) -> i -> a) -> i -> i -> i -> a\nimmemo f l r = memo\n where\n ix = index (l,r)\n memo = (IM.!) dp . ix\n dp = IM.fromList [(ix k, f memo k) | k <- range (l,r)]\n\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain = do\n s <- fmap (B.drop 5) B.getLine\n let all = solve s\n print $ S.size all\n B.putStrLn $ (B.pack \"\\n\") `B.intercalate` S.toAscList all\n\nsolve s = all 0 d S.empty\n where d = dp s (B.length s - 4) [(False, True), (True, False), (False, False)]\n all i [] res = res\n all i ((v2,v3):xs) res = all (i + 1) xs res''\n where res' = if v2 then (cur2 s i) `S.insert` res else res\n res'' = if v3 then (cur3 s i) `S.insert` res' else res'\n\n\ndp s i res\n | i < 0 = drop (negate i - 1) res\n | otherwise = dp s (i - 1) ((v2, v3) : res)\n where v2 = snd (res !! 1) || (fst (res !! 1) && cur2 s i /= cur2 s (i + 2))\n v3 = fst (res !! 2) || (snd (res !! 2) && cur3 s i /= cur3 s (i + 3))\n\ncur2 s a = B.take 2 . B.drop a $ s\ncur3 s a = B.take 3 . B.drop a $ s\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain = do\n s <- fmap (B.drop 5) B.getLine\n B.putStrLn s\n let all = solve s\n print $ S.size all\n B.putStrLn $ (B.pack \"\\n\") `B.intercalate` S.toAscList all\n\nsolve s = all 0 d S.empty\n where d = dp s (B.length s - 4) [(False, True), (True, False), (False, False)]\n all i [] res = res\n all i ((v2,v3):xs) res = all (i + 1) xs res''\n where res' = if v2 then (cur2 s i) `S.insert` res else res\n res'' = if v3 then (cur3 s i) `S.insert` res' else res'\n\n\ndp s i res\n | i < 0 = drop (negate i - 1) res\n | otherwise = dp s (i - 1) ((v2, v3) : res)\n where v2 = snd (res !! 1) || (fst (res !! 1) && cur2 s i /= cur2 s (i + 2))\n v3 = fst (res !! 2) || (snd (res !! 2) && cur3 s i /= cur3 s (i + 3))\n\ncur2 s a = B.take 2 . B.drop a $ s\ncur3 s a = B.take 3 . B.drop a $ s\n"}, {"source_code": "import qualified Data.IntMap as IM\nimport Data.IntMap ((!))\nimport Data.Ix (Ix, index, range)\nimport Data.List\n\nmain = do\n s <- getContents\n let strings = solve s\n print $ length strings\n mapM_ putStrLn strings\n\nsolve s = map head . group . sort $ strings\n where\n ms = IM.fromList $ zip [0..] (reverse s)\n n = IM.size ms\n\n f _ (_, m) | n-m <= 5 = False\n f _ (2, 1) = True\n f _ (3, 2) = True\n f _ (_, m) | m <= 2 = False\n f rec (prev, m) = rec (5-prev, m-prev) || (rec (prev, m-prev) && not (eq (m-2*prev) (m-prev)))\n\n eq a b = and $ zipWith (==) (map (ms!) [a+1..b]) (map (ms!) [b+1 .. 2*b-a])\n\n isGood = immemo f (2,0) (3,n-1)\n\n good2 = [i | i <- [1..n-1], isGood (2, i)]\n good3 = [i | i <- [2..n-1], isGood (3, i)]\n strings = [[ms!i, ms!(i-1)] | i <- good2] ++ [[ms!i, ms!(i-1), ms!(i-2)] | i <- good3]\n\n\nimmemo :: (Ix i) => ((i -> a) -> i -> a) -> i -> i -> i -> a\nimmemo f l r = memo\n where\n ix = index (l,r)\n memo = (IM.!) dp . ix\n dp = IM.fromList [(ix k, f memo k) | k <- range (l,r)]\n\n\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\n\nmain = do\n s <- fmap (B.drop 5) B.getLine\n let all = solve s\n print $ S.size all\n B.putStrLn $ (B.pack \"\\n\") `B.intercalate` S.toAscList all\n\nsolve s = all 0 d S.empty\n where d = dp s (B.length s - 4) [(False, True), (True, False), (False, False)]\n all i [] res = res\n all i ((v2,v3):xs) res = all (i + 1) xs res''\n where res' = if v2 then (cur2 s i) `S.insert` res else res\n res'' = if v3 then (cur3 s i) `S.insert` res' else res'\n\n\ndp s i res\n | i < 0 = drop (negate i - 1) res\n | otherwise = dp s (i - 1) ((v2, v3) : res)\n where v2 = snd (res !! 1) || (fst (res !! 1) && cur2 s i /= cur2 s (i + 2))\n v3 = fst (res !! 2) || (snd (res !! 2) && cur3 s i /= cur3 s (i + 3))\n\ncur2 s a = B.take 2 . B.drop a $ s\ncur3 s a = B.take 3 . B.drop a $ s\n"}], "src_uid": "dd7ccfee8c2a19bf47d65d5a62ac0071"} {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.List\nimport qualified Data.Map as Map\n\nmain :: IO()\nmain = do\n q <- read <$> getLine\n replicateM_ q solve\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n m <- read <$> getLine :: IO Int\n b <- map read . words <$> getLine :: IO [Int]\n --print $ evalState (replicateM 1 $ calculateOrder m b) (0, [], IntMap.empty)\n let iMap = last $ evalState (replicateM 26 $ calculateOrder m b) (0, [], IntMap.empty)\n let wtf = IntMap.toList iMap\n let wtf3 = sortOn fst $ IntMap.toList $ foldr (\\ (_, r) -> IntMap.alter alterM r) IntMap.empty wtf\n let wtf2 = reverse $ Map.toList $ foldr (Map.alter alterM) Map.empty s\n let wtf4 = IntMap.fromList $ cf wtf3 wtf2\n let wtf5 = map ((\\ r -> wtf4 IntMap.! r). snd) wtf\n putStrLn wtf5\n return ()\n where\n alterM :: Maybe Int -> Maybe Int\n alterM Nothing = Just 1\n alterM (Just k) = Just $ k+1\n cf :: [(Int, Int)] -> [(Char, Int)] -> [(Int, Char)]\n cf [] _ = []\n cf wtf3@((wf, ws):tf3) ((wtf, wts):f2) | ws <= wts = (wf, wtf) : cf tf3 f2\n | otherwise = cf wtf3 f2\n\ncalculateOrder :: Int -> [Int] -> State (Int, [Int], IntMap Int) (IntMap Int)\ncalculateOrder m b = do\n (it, l, iMap) <- get\n let diff = map (\\ i -> sum (map (\\ e -> abs $ i - e) l)) [1..m]\n let match = filter (\\ x -> x /= -1) $ zipWith3 (\\ e d i -> if e == d then i else -1) b diff [1..]\n let newM = foldr (\\ i -> if i == -1 then id else IntMap.insertWith (flip const) i it) iMap match\n put (it + 1, match `union` l, newM)\n return newM\n", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\nimport Data.List (group)\nfullUpdate f b = helper (Map.keys b) b\n where helper [] b = b\n helper (a:t) b = helper t (Map.updateWithKey f a b)\n\nfullInsert keys b val = helper keys b\n where helper [] b = b\n helper (a:t) b = helper t (Map.insert a val b)\n\ndeleteAfter key map = Map.filterWithKey (\\k _ -> k < key) map\n\nsolve (t, b) =\n let\n iter t b new\n | Map.size b == 0 = Map.elems new\n | otherwise =\n let\n zeros = filter (\\(_,b) -> b == 0) (Map.assocs b)\n zeroInd = map fst zeros\n maxT = fst.head $ filter (\\(_, i) -> i >= length zeroInd) (Map.toDescList t)\n newB = Map.mapWithKey (\\k a -> a - sum (map (\\x -> abs (k - x)) zeroInd)) (fullUpdate (\\i a -> if elem i (zeroInd) then Nothing else Just a) b)\n in\n iter (deleteAfter maxT t) newB (fullInsert zeroInd new maxT)\n in\n iter t b Map.empty\n\ngetCase = do\n t <- Map.fromListWith (+) . (flip zip) (repeat 1) <$> getLine\n n <-getLine\n bStr <- getLine\n let b = Map.fromList $ zip [1..] ((map read) $ words bStr)\n return (t, b)\n\nmain = do\n n <- read <$> getLine\n inp <- replicateM n getCase\n mapM_ putStrLn (map solve inp)\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.List\nimport qualified Data.Map as Map\n\nmain :: IO()\nmain = do\n q <- read <$> getLine\n replicateM_ q solve\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n m <- read <$> getLine :: IO Int\n b <- map read . words <$> getLine :: IO [Int]\n let iMap = last $ evalState (replicateM 26 $ calculateOrder m b) (0, [], IntMap.empty)\n let wtf = IntMap.toList iMap\n let wtf3 = sortOn fst $ IntMap.toList $ foldr (\\ (_, r) -> IntMap.alter alterM r) IntMap.empty wtf\n let wtf2 = reverse $ Map.toList $ foldr (Map.alter alterM) Map.empty s\n let wtf4 = IntMap.fromList $ cf wtf3 wtf2\n let wtf5 = map ((\\ r -> wtf4 IntMap.! r). snd) wtf\n putStrLn $ unwords $ map (:[]) wtf5\n return ()\n where\n alterM :: Maybe Int -> Maybe Int\n alterM Nothing = Just 1\n alterM (Just k) = Just $ k+1\n cf :: [(Int, Int)] -> [(Char, Int)] -> [(Int, Char)]\n cf [] _ = []\n cf wtf3@((wf, ws):tf3) ((wtf, wts):f2) | ws <= wts = (wf, wtf) : cf tf3 f2\n | otherwise = cf wtf3 f2\n\ncalculateOrder :: Int -> [Int] -> State (Int, [Int], IntMap Int) (IntMap Int)\ncalculateOrder m b = do\n (it, l, iMap) <- get\n let diff = map (\\ i -> sum (map (\\ e -> abs $ i - e) l)) [1..m]\n let match = zipWith3 (\\ e d i -> if e == d then i else -1) b diff [1..]\n let newM = foldr (\\ i -> if i == -1 then id else IntMap.insertWith (flip const) i it) iMap match\n put (it + 1, match, newM)\n return newM\n"}], "src_uid": "bc2f2b98c50a0165b7204a6d595eec4b"} {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [a,b,c,d] <- (map (read ::String -> Int).words) <$> getLine\n putStrLn $ (unwords.map show) [b,c,c]\n", "positive_code": [{"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords) >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([_,b,c,_]:ps) = [b,c,c] : process ps\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b, c, d] <- getIntList\n printList [b, c, c]"}, {"source_code": "main = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n (a:b:c:d:_) <- map read . words <$> getLine :: IO [Integer]\n putStrLn $ unwords $ map show [b, c, c]\n test (i - 1)\n\n\n\n"}, {"source_code": "solve :: [String] -> [String]\nsolve [a, b, c, d] = [b, c, c]\n\nio :: String -> String\nio s = unlines $ map (unwords . solve . words) $ drop 1 (lines s)\n\nmain :: IO ()\nmain = do\n interact io"}, {"source_code": "import Control.Monad (forM_) \n\n\n-- a <= x <= b <= y <= c <= z <= d\n-- x + y > z\n\nsolve [a,b,c,d] = show b ++ \" \" ++ show c ++ \" \" ++ show c where\n\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\txs <- fmap (map read.words) getLine :: IO [Int]\n\t\tputStrLn (solve xs)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess [a,b,c,d] = do\n\t\t\tputStrLn $ intercalate \" \" $ map show [b,c,c]\n\t\t\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\ta<-map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]\n\t\tmapM_ process a\n\n"}, {"source_code": "solve :: Integer -> Integer -> Integer -> Integer -> (Integer, Integer, Integer)\nsolve _ b c _ = (b, c, c)\n\nparse :: String -> String\nparse input = (show x) ++ \" \" ++ (show y) ++ \" \" ++ (show z)\n where [a, b, c, d] = map (\\r -> read r :: Integer) $ words input\n (x, y, z) = solve a b c d\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "negative_code": [], "src_uid": "821d48c9a67d37ad7acc50d4d0d0d723"} {"source_code": "\nimport Data.Array\nimport Control.Monad (forM_,replicateM)\nimport Text.Printf\n\nhasStar xs = any (=='*') xs\n\nsolve arr =\n let ((rmin,cmin),(rmax,cmax)) = bounds arr\n row r = [ arr ! (r,c) | c <- [cmin..cmax] ]\n col c = [ arr ! (r,c) | r <- [rmin..rmax] ]\n rlo -- first row which has a \"*\"\n = head [ r | r <- [rmin..rmax], hasStar (row r) ]\n rhi -- last row which has a \"*\"\n = head [ r | r <- [rmax,rmax-1..rmin], hasStar (row r) ]\n clo -- first column which has a \"*\"\n = head [ c | c <- [cmin..cmax], hasStar (col c) ]\n chi -- last column which has a \"*\"\n = head [ c | c <- [cmax,cmax-1..cmin], hasStar (col c) ]\n in (rlo,rhi,clo,chi)\n\n(-->) = flip fmap\n\nmain = do\n (n:m:_) <- getLine --> words --> map read\n lines <- replicateM n getLine\n let arr = listArray ((1,1),(n,m)) (concat lines)\n let (rlo,rhi,clo,chi) = solve arr\n forM_ [rlo..rhi] $ \\r -> do\n let s = [ arr ! (r,c) | c <- [clo..chi] ]\n putStrLn s\n\n", "positive_code": [{"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\ncut a b = drop a . take (b+1)\n\nmain = do n <- cin :: IO Int\n m <- cin :: IO Int\n css <- replicateM n cin :: IO [String]\n let painted x y = css!!y!!x == '*'\n colCheck x = any (painted x) [0..n-1]\n rowCheck y = any (`painted` y) [0..m-1]\n get f xs = head $ filter f xs\n left = get colCheck [0..]\n right = get colCheck $ reverse [0..m-1]\n top = get rowCheck [0..]\n bottom = get rowCheck $ reverse [0..n-1]\n mapM_ putStrLn . map (cut left right) $ cut top bottom css\n\n\n"}, {"source_code": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nimport Control.Monad\n\nimport Data.IORef\nimport System.IO.Unsafe\n\nclass Read' a where\n read' :: String -> a\n\ninstance Read' Integer where\n read' = read\n\ninstance Read' Int where\n read' = read\n\ninstance Read' Double where\n read' = read\n\ninstance Read' Char where\n read' (c:[]) = c\n read' cs = error $ cs ++ \" cannot read' as the type of Char.\"\n\ninstance Read' String where\n read' cs = cs\n\n\ncin :: forall a. Read' a => IO a\ncin = do (x:xs) <- readIORef input\n writeIORef input xs\n return $ read' x\n\ninput :: IORef [String]\ninput = unsafePerformIO $ getContents >>= newIORef . words\n\ncut a b = drop a . take b\n\nmain = do n <- cin :: IO Int\n m <- cin :: IO Int\n css <- replicateM n cin :: IO [String]\n let f x y = css!!y!!x == '*'\n s = subtract\n left = until (\\x -> any (f x) [0..n-1]) (+1) 0\n right = until (\\x -> any (f x) [0..n-1]) (s 1) (m-1)\n top = until (\\y -> any (`f` y) [0..m-1]) (+1) 0\n bottom = until (\\y -> any (`f` y) [0..m-1]) (s 1) (n-1)\n css' = cut top (bottom+1) css\n mapM_ putStrLn $ map (cut left (right+1)) css'\n\n"}, {"source_code": "main = do\n\ta <-getLine\n\tc <-getContents\n\tputStrLn $ unlines $ solve (lines c)\n\n\ncutterH [] = []\ncutterH (s:ss) = if not ('*' `elem` s) then cutter ss\n\t else s:ss\n\ncutterT [] = []\ncutterT (k) = if not ('*' `elem` s) then cutter ss\n\t else k\n\t where s = last k\n\t ss = init k\n\ncutter s = cutterT $ cutterH s\n\ntranspose::[String]->[String]\ntranspose s | null (head s) = []\ntranspose s = [map head s] ++ (transpose (map tail s))\n\nsolve s = transpose res2\n\t where res1 = cutter s\n\t res2 = cutter $transpose res1"}, {"source_code": "import List\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\ndropNoStart [] = []\ndropNoStart (x:xs) | elem '*' x = x:xs\n | True = dropNoStart xs\n\nmain = do\n s <- getLine\n let n:m:_ = un s\n l <- getLines n\n let l1 = dropNoStart l\n l2 = reverse $ dropNoStart $ reverse l1\n l3 = dropNoStart $ transpose l2\n l4 = reverse $ dropNoStart $ reverse l3\n l5 = transpose l4\n mapM_ putStrLn $ l5\n"}, {"source_code": "\nimport Array (Array, (!), array, bounds)\nimport Monad (liftM)\n\nfindBounds :: Array (Int, Int) Char -> ((Int, Int), (Int, Int))\nfindBounds array = ((minI, minJ), (maxI, maxJ))\n where\n ((i0, j0), (iN, jN)) = bounds array\n rows = [i | i <- [i0 .. iN], any (== '*') [array ! (i, j) | j <- [j0 .. jN]]]\n cols = [j | j <- [j0 .. jN], any (== '*') [array ! (i, j) | i <- [i0 .. iN]]]\n (minI, maxI) = (minimum rows, maximum rows)\n (minJ, maxJ) = (minimum cols, maximum cols)\n\nmain :: IO ()\nmain = do\n [n, m] <- liftM (map read . words) getLine\n lines' <- liftM (take n . lines) getContents\n let array' = array ((1,1), (n,m)) [((i,j), lines' !! (i-1) !! (j-1)) | i <- [1..n], j <- [1..m]]\n let ((minI, minJ), (maxI, maxJ)) = findBounds array'\n mapM_ (\\i -> putStrLn [array' ! (i, j) | j <- [minJ .. maxJ]]) [minI .. maxI]\n"}, {"source_code": "import List\nimport Control.Monad\nimport Control.Applicative\n\nsolve = twice (map reverse.cut) . twice (reverse.dropWhile (all (=='.')))\n where twice f = (f.f)\n cut rows | all ((=='.').head) rows = cut $ map tail rows\n | otherwise = rows\n\nmain = do\n [n, _] <- map read . words <$> getLine\n (replicateM n getLine) >>= (mapM_ putStrLn . solve)\n "}, {"source_code": "import List\nimport Control.Monad\nimport Control.Applicative\n\nsolve = twice (rev1.cut1) . twice (rev2.cut2)\n where twice f = (f.f)\n rev1 = map reverse\n cut1 rows | all ((=='.').head) rows = cut1 $ map tail rows\n | otherwise = rows\n rev2 = reverse\n cut2 rows | all (=='.') $ head rows = cut2 $ tail rows\n | otherwise = rows\n\nmain = do\n [n, m] <- map read . words <$> getLine\n rows <- replicateM n getLine\n mapM_ putStrLn $ solve rows\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\ndots x = all (=='.') x\n\n\nmain = do\n\t\t[n,m]<- map read <$> words <$>getLine ::IO [Int]\n\t\tx<-replicateM n getLine::IO [String]\n\t\tlet y=transpose $ reverse $ dropWhile (dots) $ reverse $ dropWhile (dots) $ transpose $ reverse $ dropWhile (dots) $ reverse $ dropWhile (dots) x\n\t\tmapM_ putStrLn y\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nfindLeft x = length. takeWhile (== '.') $ x\n\nmain :: IO ()\nmain = do \n\tline <- getLine\n\tlet \n\t\t[m, n] = map (\\x -> read x :: Int). words$ line\n\tarr' <- getContents\n\tlet\n\t\tarr = lines arr'\n\t\ttarr = transpose arr\n\t\tleft = minimum. map findLeft $ arr\n\t\ttop = minimum. map findLeft $ tarr\n\t\tright = n - (minimum. map findLeft. map reverse $arr)\n\t\tbot = m - (minimum. map findLeft. map reverse $ tarr)\n--\tmapM_ print arr\n--\tputStrLn \"\"\n--\tmapM_ print tarr\n--\tputStrLn \"\"\n--\tputStrLn $ \"left = \" ++ show left\t\n--\tputStrLn $ \"top = \" ++ show top\n--\tputStrLn $ \"right = \" ++ show right\n--\tputStrLn $ \"bot = \" ++ show bot\n--\tputStrLn \"\"\n\tmapM_ putStrLn. map (drop left). map (take right). drop top. take bot $ arr\n"}], "negative_code": [{"source_code": "main = do\n\ta <-getLine\n\tc <-getContents\n\tputStrLn $ unlines $ solve (lines c)\n\n\ncutter [] = []\ncutter (s:ss) = if not ('*' `elem` s) then cutter ss\n\t else [s]++cutter ss\n\ntranspose::[String]->[String]\ntranspose s | null (head s) = []\ntranspose s = [map head s] ++ (transpose (map tail s))\n\nsolve s = transpose res2\n\t where res1 = cutter s\n\t res2 = cutter $transpose res1"}, {"source_code": "import List\nimport Control.Monad\nimport Control.Applicative\n\nsolve rows = (reverseCols.cutCols.reverseCols.cutCols.filter notEmpty) rows\n where reverseCols = map reverse\n cutCols rows | all ((=='.').head) rows = cutCols $ map tail rows\n | otherwise = rows\n notEmpty = any (=='*')\n\nmain = do\n [n, m] <- map read . words <$> getLine\n rows <- replicateM n getLine\n mapM_ putStrLn $ solve rows\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nfindLeft x = length. takeWhile (== '.') $ x\n\nmain :: IO ()\nmain = do \n\tline <- getLine\n\tlet \n\t\t[m, n] = map (\\x -> read x :: Int). words$ line\n\tarr' <- getContents\n\tlet\n\t\tarr = lines arr'\n\t\ttarr = transpose arr\n\t\tleft = minimum. map findLeft $ arr\n\t\ttop = minimum. map findLeft $ tarr\n\t\tright = n - (minimum. map findLeft. map reverse $arr)\n\t\tbot = m - (minimum. map findLeft. map reverse $ tarr)\n--\tmapM_ print arr\n--\tputStrLn \"\"\n--\tmapM_ print tarr\n--\tputStrLn \"\"\n--\tputStrLn $ \"left = \" ++ show left\t\n--\tputStrLn $ \"top = \" ++ show top\n--\tputStrLn $ \"right = \" ++ show right\n--\tputStrLn $ \"bot = \" ++ show bot\n--\tputStrLn \"\"\n\tmapM_ print. map (drop left). map (take right). drop top. take bot $ arr\n"}], "src_uid": "d715095ff068f4d081b58fbfe103a02c"} {"source_code": "canDistribute :: Int -> Int -> Int -> Int -> Bool\ncanDistribute a b c n =\n let s = a + b + c + n\n third = s `div` 3\n in s `mod` 3 == 0 && third >= (maximum [a, b, c])\n\nsolve :: String -> String\nsolve line =\n let tokens = words line\n a = read (tokens !! 0) :: Int\n b = read (tokens !! 1) :: Int\n c = read (tokens !! 2) :: Int\n n = read (tokens !! 3) :: Int\n valid = canDistribute a b c n\n in if valid then \"YES\" else \"NO\"\n\nsolveAll :: String -> String\nsolveAll input =\n let tests = tail . lines $ input\n answers = map solve tests\n in unlines answers\n\nmain = interact solveAll\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n \ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b, c, d] <- getIntList\n putStrLn $ solve a b c d\n\nsolve :: Int -> Int -> Int -> Int -> String\nsolve a b c d =\n let r = 3 * maximum [a, b, c] - sum [a, b, c] in\n if and [d >= r, mod (d - r) 3 == 0] then \"YES\" else \"NO\""}, {"source_code": "import Control.Monad\n\n-- A + B + C = 3k = n + a + b + c\nsolve :: [Integer] -> String\nsolve xs\n | listSum `mod` 3 /= 0 = \"NO\"\n | a < 0 = \"NO\"\n | otherwise = \"YES\"\n where listSum = sum xs\n a = (listSum `div` 3) - maximum (take 3 xs)\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStrLn . unlines . map (solve . map read . words) . tail . lines $ input \n\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve :: String -> String\nsolve input = joinedansert\n where\n asnumbers :: [Int64]\n asnumbers = map read $ words input\n n:others = asnumbers\n byfour = splitbyfour others\n solved :: [String]\n solved = map solve' byfour\n joinedansert = intercalate \"\\n\" solved\n\nsplitbyfour :: [Int64] -> [(Int64, Int64, Int64, Int64)]\nsplitbyfour [] = []\nsplitbyfour (a:b:c:d:xs) = (a, b, c, d):(splitbyfour xs)\n\nsolve' :: (Int64, Int64, Int64, Int64) -> String \nsolve' (a, b, c, n) -- = show a\n | required > n = \"NO\"\n | extra `mod` 3 == 0 = \"YES\"\n | otherwise = \"NO\"\n where\n maxNum :: Int64\n maxNum = maximum (a:b:c:[])\n required = (maxNum - a) + (maxNum - b) + (maxNum - c)\n extra = n - required\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.Sequence as DSeq\nimport Data.Foldable\n\ngetToken :: IO String\ngetToken = \n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n t <- get :: IO Int\n replicateM_ t f1\n\nf1 :: IO ()\nf1 = do\n a <- get :: IO Int64\n b <- get :: IO Int64\n c <- get :: IO Int64\n n <- get :: IO Int64\n putStrLn $ if f2 a b c n then \"YES\" else \"NO\"\n\nf2 :: Int64 -> Int64 -> Int64 -> Int64 -> Bool\nf2 a b c n = (mod (a + b + c + n) 3) == 0 && (\n let v = (div (a + b + c + n) 3) in\n v - a >= 0 && v - b >= 0 && v - c >= 0\n )"}, {"source_code": "import Control.Monad\nimport Data.Int\n\ngetToken :: IO String\ngetToken = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n'\n then return [x]\n else liftM2 (:) (return x) getToken\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n t <- get :: IO Int\n replicateM_ t f1\n\nf1 :: IO ()\nf1 = do\n a <- get :: IO Int64\n b <- get :: IO Int64\n c <- get :: IO Int64\n n <- get :: IO Int64\n putStrLn $ if f2 a b c n then \"YES\" else \"NO\"\n\nf2 :: Int64 -> Int64 -> Int64 -> Int64 -> Bool\nf2 a b c n = (mod (a + b + c + n) 3) == 0 && (\n let v = (div (a + b + c + n) 3) in\n v - a >= 0 && v - b >= 0 && v - c >= 0\n )"}, {"source_code": "import System.IO\n\nreadInt :: IO Int\nreadInt = readLn\n\ncastToInt x = read x::Int\n\nmain = do\n t <- readInt\n solve t\n \nsum2 test_case = sum test_case `div` 3\n\nsolve t = do\n if t == 0 then\n return ()\n else do\n line <- getLine\n let test_case = (map castToInt . take 4 . words) line\n let x = sum2 test_case\n if sum test_case `mod` 3 /= 0 || test_case!!0 > x || test_case!!1 > x || test_case!!2 > x then\n putStrLn \"NO\"\n else \n putStrLn \"YES\"\n solve (t-1)\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess [a,b,c,n] |mod s 3==0 && maximum [a,b,c]<=div s 3 = \"YES\"\n\t\t |otherwise = \"NO\"\n\twhere s= a+b+c+n\n\t \t\n\nmain = do\n\t\tn<- read <$> getLine :: IO Int\n\t\tx<- map(map read) <$> map words <$> replicateM n getLine::IO [[Integer]]\n\t\tmapM_ putStrLn $ map process x\n"}, {"source_code": "import Data.List as L\n\nsolve' :: Int -> Int -> Int -> Int -> Bool\nsolve' a b c n = isEnough && (mod remain 3 == 0)\n where toGiveToA = c - a\n toGiveToB = c - b\n isEnough = n >= toGiveToA + toGiveToB\n remain = n - toGiveToA - toGiveToB\n\nsolve :: Int -> Int -> Int -> Int -> String\nsolve a b c n = if solve' a' b' c' n then \"YES\" else \"NO\"\n where [a', b', c'] = L.sort [a, b, c]\n\nparse :: String -> String\nparse input = solve a b c n\n where [a, b, c, n] = map (\\x -> read x :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail. lines)\n"}], "negative_code": [{"source_code": "canDistribute :: Int -> Int -> Int -> Int -> Bool\ncanDistribute a b c n =\n let s = a + b + c + n\n third = s `div` 3\n in s `mod` 3 == 0 && third > (maximum [a, b, c])\n\nsolve :: String -> String\nsolve line =\n let tokens = words line\n a = read (tokens !! 0) :: Int\n b = read (tokens !! 1) :: Int\n c = read (tokens !! 2) :: Int\n n = read (tokens !! 3) :: Int\n valid = canDistribute a b c n\n in if valid then \"YES\" else \"NO\"\n\nsolveAll :: String -> String\nsolveAll input =\n let tests = tail . lines $ input\n answers = map solve tests\n in unlines answers\n\nmain = interact solveAll\n"}, {"source_code": "import Control.Monad\n\n-- A + B + C = 3k = n + a + b + c\nsolve :: [Integer] -> String\nsolve xs\n | 3 * k == listSum && k >= min = \"YES\"\n | otherwise = \"NO\"\n where listSum = sum xs\n k = listSum `div` 3\n min = minimum xs \nsolve _ = []\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStrLn . unlines . map (solve . map read . words) . tail . lines $ input \n\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\ngetToken :: IO String\ngetToken = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n'\n then return [x]\n else liftM2 (\\x y -> x : y) (return x) getToken\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n n <- get :: IO Int64\n m <- get :: IO Int64\n a <- get :: IO Int64\n putln $ f1 n m a\n\nf1 :: Int64 -> Int64 -> Int64 -> Int64\nf1 n m a = ((div (n + a - 1) a) * (div (m + a - 1) a))\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\ngetToken :: IO String\ngetToken = \n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if null s then\n aux s\n else\n return s\n else\n aux $ x : s\n in aux []\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n t <- get :: IO Int\n replicateM_ t f1\n\nf1 :: IO ()\nf1 = do\n a <- get :: IO Int64\n b <- get :: IO Int64\n c <- get :: IO Int64\n n <- get :: IO Int64\n putStrLn $ if f2 a b c n then \"YES\" else \"NO\"\n\nf2 :: Int64 -> Int64 -> Int64 -> Int64 -> Bool\nf2 a b c n = (mod (a + b + c + n) 3) == 0 && (\n let v = (div (a + b + c + n) 3) in\n v - a >= 0 && v - b >= 0 && v - c >= 0\n )"}], "src_uid": "bc5fb5d6882b86d83e5c86f21d806a52"} {"source_code": "main = interact $ drop 1 . dropWhile (/= '\\n')\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nmain :: IO ()\nmain = do\n getLine\n interact id"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tk<-map read <$> replicateM n getLine ::IO [Int]\n\t\tmapM_ print k\n\n\n"}, {"source_code": "process :: Int -> Int\nprocess = id\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n print $ process n\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}], "negative_code": [{"source_code": "process :: Int -> Int\nprocess n\n | n == 1 = 1\n | otherwise = 2\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n print $ process n\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}], "src_uid": "740c05c036b646d8fb6b391af115d7f0"} {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]).istoline . solve . linestoiss) (nm:( take 1 rest)) ++ tcio (drop 1 rest) \r\n linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n\r\nsolve :: [[Integer]] -> [Integer]\r\nsolve [[n,x],as] = [(sum as + x - 1) `div` x, sum $ map (`div` x) $ map (+ (x-1)) as]\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Control.Monad (replicateM)\nimport Data.Int\n\n-- readInts :: IO [Int64]\n-- readInts = map read . words <$> getLine\n\nreadInt = readLn :: IO Int\nreadInt64 = readLn :: IO Int64\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n \ndo_test :: IO ()\ndo_test = do\n\n [n, x] <- readIntegers\n ns <- readIntegers\n let\n mini = div ((sum ns) + x - 1) x\n maxi = sum $ map ((`div` x) . (+(x-1))) ns\n putStrLn $ (show mini) ++ \" \" ++ (show maxi)\n\n \nmain :: IO [()]\nmain = do\n t <- readInt\n replicateM t do_test\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.Int\n\nreadInts :: IO [Int64]\nreadInts = map read . words <$> getLine\n \ndo_test :: IO ()\ndo_test = do\n\n [n, x] <- readInts\n ns <- readInts\n let\n mini = div ((sum ns) + x - 1) x\n maxi = sum $ map ((`div` x) . (+(x-1))) ns\n putStrLn $ (show mini) ++ \" \" ++ (show maxi)\n\n \nmain :: IO [()]\nmain = do\n t <- readLn :: IO Int\n replicateM t do_test\n"}, {"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List (foldl)\nimport Data.Set (Set, fromList, member, insert)\nimport System.IO\nimport Text.Read\n-- import Debug.Trace\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n -- print c\n [n, x] <- fmap (map read . words) getLine :: IO [Integer]\n a <- fmap (map read . words) getLine :: IO [Integer]\n putStrLn $ (\\ (a, b) -> unwords [show a, show b]) $ solve n x a\n return ()\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\n-- type State = (Set Integer, Integer, Integer)\n--\n-- c :: Integer -> State -> Integer -> State\n-- c x (m, cnt, total) i\n-- | i == 0 = ( m, cnt, total)\n-- | newCnt `member` m = (fromList [0], 0, total + 1)\n-- | otherwise = (insert newCnt m, newCnt, total)\n-- where\n-- newCnt = (cnt + i) `mod` x\n\nsolve :: Integer -> Integer -> [Integer] -> (Integer, Integer)\nsolve n x a =\n let roundUp i = (i + x - 1) `quot` x\n mx = sum $ map roundUp a\n mn = roundUp $ sum a\n in (mn, mx)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE NumDecimals #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE TupleSections #-}\r\n\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Array.ST.Safe\r\nimport Data.STRef\r\n\r\n-- import Debug.Trace\r\nimport Text.Printf\r\n\r\nreadInt = readLn :: IO Int\r\nreadInteger = readLn :: IO Integer\r\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\r\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\r\n\r\nwhich a b f = if f then a else b\r\nmp [ a, b ] = ( a, b )\r\n\r\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\r\n\r\nprintList [a] = print a\r\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\r\n\r\nmain = readInt >>= flip replicateM solve\r\n\r\nsolve = do\r\n\t[ _, x ] <- readIntegers\r\n\tas <- readIntegers\r\n\tlet\r\n\t\tmi = rdiv ( sum as ) x\r\n\t\tma = sum $ map ( flip rdiv x ) as\r\n\tprintf \"%lld %lld\\n\" mi ma\r\n\r\nrdiv a b = ( a + b - 1 ) `div` b"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Text.Printf\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nsolve :: Integer -> [Integer] -> (Integer, Integer)\nsolve x a = (roundUp $ sum a, sum $ map roundUp a)\n where roundUp y = (y + x - 1) `div` x\n\nsolveCase :: IO String\nsolveCase = do\n (n:x:[]) <- readInts\n (a, b) <- fmap (solve x) readInts\n pure $ printf \"%d %d\" a b\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\nreadInts :: IO [Int64]\nreadInts = map read . words <$> getLine\n\nrunSeveral :: IO () -> IO ()\nrunSeveral act = do\n t <- read <$> getLine\n replicateM_ t act\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv x y = div (x + y - 1) y\n\nmain :: IO ()\nmain = runSeveral $ do\n [_n, x] <- readInts\n -- reading so many Int64s with [Char]s may be too slow\n -- but the ByteString version of this is so much uglier\n a <- readInts\n let\n le = ceilDiv (sum a) x\n ri = sum [ceilDiv ai x | ai <- a]\n putStrLn . unwords $ map show [le, ri]\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> Int64 -> [Int64] -> (Int64, Int64)\r\nsolve n x as = (minAnswer, maxAnswer)\r\n where\r\n minAnswer = (sum as + x - 1) `div` x\r\n maxAnswer = sum [(a + x - 1) `div` x | a <- as]\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [n, x] <- B8.getLine <&> map readIntB8 . B8.words\r\n as <- B8.getLine <&> map (\\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words\r\n let (minAnswer, maxAnswer) = solve n ((fromIntegral x) :: Int64) as\r\n printf \"%lld %lld\\n\" minAnswer maxAnswer\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Control.Monad (replicateM)\nimport Data.Int\n\n-- readInts :: IO [Int64]\n-- readInts = map read . words <$> getLine\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n \ndo_test :: IO ()\ndo_test = do\n\n [n, x] <- readInts\n ns <- readInts\n let\n mini = div ((sum ns) + x - 1) x\n maxi = sum $ map ((`div` x) . (+(x-1))) ns\n putStrLn $ (show mini) ++ \" \" ++ (show maxi)\n\n \nmain :: IO [()]\nmain = do\n t <- readLn :: IO Int\n replicateM t do_test\n"}, {"source_code": "import Control.Monad (replicateM)\n\nsolve_min :: [Int] -> Int -> Int\nsolve_min ns x = ceiling ((fromIntegral (sum ns)) / (fromIntegral x))\n\nsolve_max :: [Int] -> Int -> Int\nsolve_max ns x = sum (map (ceiling . (/ (fromIntegral x)) . fromIntegral) ns)\n\nsolve :: [Int] -> Int -> (Int, Int)\nsolve ns x = (solve_min ns x, solve_max ns x)\n \ndo_test :: IO ()\ndo_test = do\n line <- getLine\n let [n, x] = (map read . words) line :: [Int] in\n do\n ns <- map read . words <$> getLine :: IO [Int]\n let (mini, maxi) = solve ns x in\n do\n putStrLn $ (show mini) ++ \" \" ++ (show maxi)\n\n \nmain :: IO [()]\nmain = do\n t <- readLn :: IO Int\n replicateM t do_test\n"}, {"source_code": "import Control.Monad (replicateM)\n\nsolve_min :: [Int] -> Int -> Int\nsolve_min ns x = ceiling ((fromIntegral (sum ns)) / (fromIntegral x))\n\nsolve_max :: [Int] -> Int -> Int\nsolve_max ns x = sum (map (ceiling . (/ (fromIntegral x)) . fromIntegral) ns)\n\nsolve :: [Int] -> Int -> (Int, Int)\nsolve ns x = (solve_min ns x, solve_max ns x)\n \ndo_test :: IO ()\ndo_test = do\n line <- getLine\n let [n, x] = (map read . words) line :: [Int] in\n do\n ns <- map read . words <$> getLine :: IO [Int]\n let (mini, maxi) = solve ns x in\n do\n putStrLn $ (show mini) ++ \" \" ++ (show maxi)\n\n \nmain :: IO [()]\nmain = do\n t <- readLn :: IO Int\n print t\n replicateM t do_test\n"}, {"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List (foldl)\nimport Data.Set (Set, fromList, member, insert)\nimport System.IO\nimport Text.Read\n-- import Debug.Trace\n\nhandleCase :: Int -> IO ()\nhandleCase c = do\n -- print c\n [n, x] <- fmap (map read . words) getLine :: IO [Int]\n a <- fmap (map read . words) getLine :: IO [Int]\n putStrLn $ (\\ (a, b) -> unwords [show a, show b]) $ solve n x a\n return ()\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] handleCase\n\n-- type State = (Set Int, Int, Int)\n--\n-- c :: Int -> State -> Int -> State\n-- c x (m, cnt, total) i\n-- | i == 0 = ( m, cnt, total)\n-- | newCnt `member` m = (fromList [0], 0, total + 1)\n-- | otherwise = (insert newCnt m, newCnt, total)\n-- where\n-- newCnt = (cnt + i) `mod` x\n\nsolve :: Int -> Int -> [Int] -> (Int, Int)\nsolve n x a =\n let roundUp i = (i + x - 1) `quot` x\n mx = sum $ map roundUp a\n mn = roundUp $ sum a\n in (mn, mx)\n"}, {"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Char\nimport Data.List (foldl)\nimport Data.Set (Set, fromList, member, insert)\nimport System.IO\nimport Text.Read\n-- import Debug.Trace\n\nhandleCase :: Int -> IO ()\nhandleCase c = do\n -- print c\n [n, x] <- fmap (map read . words) getLine :: IO [Int]\n a <- fmap (map read . words) getLine :: IO [Int]\n putStrLn $ (\\ (a, b) -> unwords [show a, show b]) $ solve n x a\n return ()\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] handleCase\n\ntype State = (Set Int, Int, Int)\n\nc :: Int -> State -> Int -> State\nc x (m, cnt, total) i\n | i == 0 = ( m, cnt, total)\n | newCnt `member` m = (fromList [0], 0, total + 1)\n | otherwise = (insert newCnt m, newCnt, total)\n where\n newCnt = (cnt + i) `mod` x\n\nsolve :: Int -> Int -> [Int] -> (Int, Int)\nsolve n x a =\n let base = sum $ map (`quot` x) a\n mods = map (`mod` x) a\n (_, _, total) = foldl (c x) (fromList [0], 0, 0) mods\n in (base, base + total)\n"}], "src_uid": "b36d7f840abe998185a988fe8dd2ec75"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ratio\n\nmain = do\n\tn<-read <$> getLine ::IO Int\n\tlet a = take 1 $ [[n,y,denominator z] |y<-[n+1..(n+n)],let z=(1%n)- ( 1%y), numerator z==1,denominator z /=y]\t\n\tif length a ==1 then putStrLn (intercalate \" \" ( map show (head a))) else print (-1)\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmain :: IO ()\nmain = do\n n <- read @ Int <$> getLine\n if n == 1\n then putStrLn \"-1\"\n else putStrLn . unwords . fmap show $ [n, n + 1, n * (n + 1)]\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n let m = n * (n + 1)\n case n of\n 1 -> putStrLn \"-1\"\n _ -> putStrLn $ (show m) ++ \" \" ++ (show n) ++ \" \" ++ (show (n + 1))\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Prelude\nimport Text.Printf\n\nmain = do\n n <- read <$> getLine :: IO Int\n if n == 1 then print $ -1\n else printf \"%d %d %d\\n\" n (n + 1) (n*(n+1))\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmain :: IO ()\nmain = do\n n <- read @ Int <$> getLine\n putStrLn . unwords . fmap show $ [n, n + 1, n * (n + 1)]\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n putStrLn $ \"1 \" ++ (show n) ++ \" \" ++ (show (n + 1))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ratio\n\nmain = do\n\tn<-read <$> getLine ::IO Int\n\tlet a = take 1 $ [[n,y,denominator z] |y<-[n+1..(n+n)],let z=(1%n)- ( 1%y), numerator z==1]\t\n\tif length a ==1 then putStrLn (intercalate \" \" ( map show (head a))) else print (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ratio\n\nmain = do\n\tn<-read <$> getLine ::IO Int\n\tprint $ head $ [[x,y,denominator z] |x<-[2..10^9],y<-[x+1..10^9],let z=(2%n)- ((1%x) +( 1%y)), numerator z==1]\t\n"}], "src_uid": "f60ea0f2caaec16894e84ba87f90c061"} {"source_code": "import Control.Arrow\r\n\r\nmain = interact $ \r\n words >>> drop 1 \r\n >>> map (\r\n read\r\n >>> solve\r\n >>> maybe \"-1\\n\" (unlines . map (unwords . map show)))\r\n >>> concat\r\n\r\nsolve :: Int -> Maybe [[Int]]\r\nsolve 1 = Just [[1]]\r\nsolve 2 = Nothing\r\nsolve n = Just [[val $ i*n + j | j <- [0..n-1]] | i <- [0..n-1]]\r\n where\r\n val x = 1 + (if even x then (n^2 `div` 2) else 0) + x `div` 2", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $\n getLine >>= putStr . unlines . map (unwords . map show) . solve . read\n\nsolve :: Int -> [[Int]]\nsolve 2 = [[-1]]\nsolve n = chunks n $ [2,4 .. n * n] ++ [1,3 .. n * n]\n\nchunks :: Int -> [Int] -> [[Int]]\nchunks _ [] = []\nchunks n l =\n let (xs, ys) = splitAt n l\n in xs : chunks n ys\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ParallelListComp #-}\r\nimport Control.Arrow\r\nimport Data.List\r\n\r\nmain = interact $ \r\n words >>> drop 1 \r\n >>> map (\r\n read\r\n >>> solve\r\n >>> maybe \"-1\\n\" (unlines . map (unwords . map show)))\r\n >>> concat\r\n\r\nsolve :: Int -> Maybe [[Int]]\r\nsolve 1 = Just [[1]]\r\nsolve 2 = Nothing\r\nsolve 3 = Just [[1,6,2], [7,3,8], [4,9,5]]\r\nsolve n = let (Just grid) = solve (n - 1) in \r\n Just $ [(n - 1) * n + 1 .. n^2] : [((n - 1)^2 + x) : row | row <- grid | x <- [1..n-1]] \r\n"}], "src_uid": "e215e94dd196dde381adc13406d2d72a"} {"source_code": "import Data.List\r\n\r\nparseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n \r\ncalc :: (Int, Int, [Int]) -> Int\r\ncalc (_, _, []) = 0\r\ncalc (i, n, (0 : xs)) = (i + 1) * (n - i) + calc (i + 1, n, xs)\r\ncalc (i, n, (_ : xs)) = calc (i + 1, n, xs)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n arr <- readIntArr\r\n print $ (n * (n + 1) * (n + 2)) `div` 6 + (calc (0, n, arr))\r\n\r\nreadLoop :: Int -> IO ()\r\nreadLoop i =\r\n if (i == 0)\r\n then pure ()\r\n else do\r\n solve\r\n readLoop (i - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n readLoop n", "positive_code": [{"source_code": "main = interact $ unlines . map p . chunk 2 . drop 1 . lines\r\n\r\nchunk n [] = []\r\nchunk n xs = take n xs : chunk n (drop n xs)\r\n\r\nf n t x = let i1 = fst t\r\n i2 = n - i1 + 1\r\n s = snd t\r\n in case x of 0 -> (i1 + 1, s + i1 * i2 * 2)\r\n _ -> (i1 + 1, s + i1 * i2)\r\n\r\ncalc n = foldl (f n) (1,0)\r\n\r\np xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]\r\n in show $ snd $ calc n s\r\n\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n a <- replicateM n getInt\n let\n ans = foldl' (+) 0 $ do\n suff <- tails a\n seg <- inits suff\n v <- seg\n pure $ if v == 0 then 2 else 1\n pure $ putInts [ans]\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "8775da9b78d8236c4606d150df450952"} {"source_code": "main = do \r\n interact (unlines .run. map f . lines)\r\n\r\nf :: String -> [Int]\r\nf inp = (map g (words inp)) where g x = read x :: Int\r\n\r\nrun :: [[Int]]->[[Char]]\r\nrun (x:y:z:xs)= ((solve (head y) z): (run ([(head x) - 1]: xs)))\r\nrun [[0]] = []\r\n\r\nsolve :: Int -> [Int] -> [Char]\r\nsolve y z |z == [1..y] = \"0\"\r\n |head z == 1 = \"1\"\r\n |last z == y = \"1\"\r\n |((head z == y) && (last z == 1)) = \"3\"\r\n | otherwise = \"2\"", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as BS\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs\r\n | Data.List.sort xs == xs =\r\n 0\r\n | minimum xs == head xs || maximum xs == last xs =\r\n 1\r\n | minimum xs == last xs && maximum xs == head xs =\r\n 3\r\n | otherwise =\r\n 2\r\n\r\nmain = do\r\n ls <- tail . BS.lines <$> BS.getContents\r\n let ls' = snd <$> filter (odd . fst) (zip [0..] ls)\r\n forM_ ls' (print . solve . map parseInt . BS.words)\r\n"}, {"source_code": "module Main where\nimport Data.Functor ((<&>))\nimport Control.Monad (forM, replicateM, replicateM_)\nimport Data.Foldable (traverse_)\nimport GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)\nimport Data.List (group, sort)\nimport Data.Ratio ((%))\nimport Prelude hiding (floor)\nimport Control.Monad (forM_)\n\nreadInts :: IO [Int]\nreadInts = getLine <&> words <&> fmap read\n\nreadString :: IO String\nreadString = getLine\n\ntoDoubles :: (Functor f, Integral a) => f a -> f Double\ntoDoubles xs = (\\x -> fromIntegral x :: Double) <$> xs\n\ntoDouble :: (Integral a) => a -> Double\ntoDouble = fromIntegral\n\n\nceil :: Double -> Int\nceil = ceilingDoubleInt\n\nfloor :: Double -> Int\nfloor = floorDoubleInt\n\nmain :: IO ()\nmain = do\n t:_ <- readInts\n replicateM_ t $ do\n n:_ <- readInts\n as <- readInts\n let\n maxi = maximum as\n mini = minimum as\n ans xs\n | sort xs == xs = 0\n | maxi == last xs || mini == head xs = 1\n | mini == last xs && maxi == head xs = 3\n | otherwise = 2\n print $ ans as"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine :: IO Int\n a <- map read . words <$> getLine :: IO [Int]\n print $\n if a == [1 .. n]\n then 0\n else if head a == 1 || last a == n\n then 1\n else if head a /= n || last a /= 1\n then 2\n else 3\n"}], "negative_code": [{"source_code": "module Main where\nimport Data.Functor ((<&>))\nimport Control.Monad (forM, replicateM, replicateM_)\nimport Data.Foldable (traverse_)\nimport GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)\nimport Data.List (group, sort)\nimport Data.Ratio ((%))\nimport Prelude hiding (floor)\nimport Control.Monad (forM_)\n\nreadInts :: IO [Int]\nreadInts = getLine <&> words <&> fmap read\n\nreadString :: IO String\nreadString = getLine\n\ntoDoubles :: (Functor f, Integral a) => f a -> f Double\ntoDoubles xs = (\\x -> fromIntegral x :: Double) <$> xs\n\ntoDouble :: (Integral a) => a -> Double\ntoDouble = fromIntegral\n\n\nceil :: Double -> Int\nceil = ceilingDoubleInt\n\nfloor :: Double -> Int\nfloor = floorDoubleInt\n\nmain :: IO ()\nmain = do\n t:_ <- readInts\n replicateM_ t $ do\n n:_ <- readInts\n as <- readInts\n let\n maxi = maximum as\n mini = minimum as\n unsorted xs\n | sort xs == xs = 0\n | otherwise = 1\n ans xs\n | sort xs == xs = 0\n | maxi == last xs || mini == head xs = 1\n | mini == last xs || maxi == head xs = 3\n | otherwise = 2\n print $ ans as"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as BS\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs\r\n | Data.List.sort xs == xs =\r\n 0\r\n | minimum xs == head xs || maximum xs == last xs =\r\n 1\r\n | minimum xs == last xs || maximum xs == head xs =\r\n 3\r\n | otherwise =\r\n 2\r\n\r\nmain = do\r\n ls <- tail . BS.lines <$> BS.getContents\r\n let ls' = snd <$> filter (odd . fst) (zip [0..] ls)\r\n forM_ ls' (print . solve . map parseInt . BS.words)\r\n"}], "src_uid": "c212524cc1ad8e0332693e3cf644854b"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\nmaxRect p1 p2 l = abs (a1 - a2)\n where\n l' = map f $ filter ((/=p1) <&&> (/=p2)) $ l\n f p = signedArea3 p1 p2 p\n a1 = maximum l'\n a2 = minimum l'\n \nsignedArea l = (sum $ zipWith (\\(a,b) (c,d) -> a*d - b*c) l (tail (cycle l)))\n\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = a*d - b*c\n where\n (a,b) = (x2-x1,y2-y1)\n (c,d) = (x3-x1,y3-y1)\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\n--maxRect p1 p2 = abs . uncurry (-) maxMin . map (signedArea3 p1 p2) . filter ((/=p1) <&&> (/=p2))\n\nmaxRect p1 p2 l = go minBound maxBound l\n where\n go !a !b [] = a - b\n go !a !b (p:ps) \n | p == p1 || p == p2 = go a b ps\n | otherwise = \n let x = signedArea3 p1 p2 p in\n go (max a x) (min b x) ps\n\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = \n (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)\n\n--maxMin = foldl' (\\(a,b) x -> (max a x,min b x)) (minBound,maxBound)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\nmaxRect p1 p2 l = go minBound maxBound l\n where\n go !a !b (p:ps) \n | p == p1 || p == p2 = go a b ps\n | otherwise = \n let x = signedArea3 p1 p2 p in\n go (max a x) (min b x) ps\n go !a !b [] = a - b\n\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = \n (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\nmaxRect p1 p2 l = abs (a1 - a2)\n where\n l' = map (signedArea3 p1 p2) $ filter ((/=p1) <&&> (/=p2)) $ l\n a1 = maximum l'\n a2 = minimum l'\n \nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\nmaxRect p1 p2 l = go minBound maxBound l\n where\n go a b [] = a - b\n go a b (p:ps) \n | p == p1 || p == p2 = go a b ps\n | otherwise = \n let x = signedArea3 p1 p2 p in\n go (max a x) (min b x) ps\n\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = \n (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\nmaxRect p1 p2 l = go minBound maxBound l\n where\n go !a !b (p:ps) \n | p == p1 || p == p2 = go a b ps\n | otherwise = \n let x = signedArea3 p1 p2 p in\n go (max a x) (min b x) ps\n go !a !b [] = a - b\n\n{-# INLINE signedArea3 #-}\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = \n (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\nmaxRect p1 p2 l = abs (a1 - a2)\n where\n l' = map f l\n f p = signedArea3 p1 p2 p\n a1 = maximum l'\n a2 = minimum l'\n \nsignedArea l = (sum $ zipWith (\\(a,b) (c,d) -> a*d - b*c) l (tail (cycle l)))\n\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = a*d - b*c\n where\n (a,b) = (x2-x1,y2-y1)\n (c,d) = (x3-x1,y3-y1)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Double,Double)\n\nmain = do\n n <- readLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- readsLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = maximum [ maxRect p1 p2 l | p1 <- l, p2 <- l, p1 /= p2 ]\n\nmaxRect p1@(x1,y1) p2@(x2,y2) l = a1 - a2\n where\n l' = map f l\n f p = signedArea [p1,p2,p]\n a1 = maximum l'\n a2 = minimum l'\n \nsignedArea l = 0.5 * (sum $ zipWith (\\(a,b) (c,d) -> a*d - b*c) l (tail l))\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\ntype Point = (Int,Int)\n\nmain = do\n n <- readInt <$> B.getLine\n l <- replicateM n parseLine\n print $ solve n l\n\nparseLine :: IO Point\nparseLine = do\n [a,b] <- map readInt . B.words <$> B.getLine\n return (a,b)\n\nsolve :: Int -> [Point] -> Double\nsolve n l = (*0.5) $ itof $ maximum [maxRect p1 p2 l | p1 <- l, p2 <- l, p1 < p2 ]\n\n--maxRect p1 p2 = abs . uncurry (-) maxMin . map (signedArea3 p1 p2) . filter ((/=p1) <&&> (/=p2))\n\nmaxRect p1 p2 l = go minBound maxBound l\n where\n go !a !b [] = a - b\n go !a !b (p:ps) \n | p == p1 || p == p2 = go a b ps\n | otherwise = \n let x = signedArea3 p1 p2 p in\n go (max a x) (min a x) ps\n\nsignedArea3 (x1,y1) (x2,y2) (x3,y3) = \n (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)\n\n--maxMin = foldl' (\\(a,b) x -> (max a x,min b x)) (minBound,maxBound)\n"}], "src_uid": "bb3fc45f903588baf131016bea175a9f"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\n\ndata TC = TC { n :: Int, m :: Int }\n\ntype Output = (Int, Int)\n\ninput :: Scanner TC\ninput = do\n n <- int\n m <- int\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..}\n | n >= 2 && m >= 2 = (2, 2)\n | otherwise = (1, 1)\n\noutput :: Int -> Output -> C.ByteString\noutput _ (x, y) = C.pack $ show x <> \" \" <> show y\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.Maybe\r\nimport System.IO\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n casnum <- getInt\r\n ress <- forM [1 .. casnum] $ \\_ -> do\r\n n <- getInt\r\n m <- getInt\r\n let res\r\n | n == 1 || m == 1 = [1, 1] -- isolate on [1,1]\r\n | n >= 4 || m >= 4 = [1, 1] -- no isolate\r\n | otherwise = [2, 2]\r\n pure res\r\n pure $ foldl1 (<>) $ map putInts ress\r\n\r\ntype SP = State P.ByteString\r\n\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs =\r\n let sepPrim =\r\n (,) ' '\r\n Prim.>$< Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Tuple\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,m] <- ri\r\n return (n,m)\r\n mapM_ (putStrLn.showT.solve) tcs\r\n\r\nshowT (a,b) = show a ++ \" \" ++ show b\r\n\r\nsolve (n,m) = f (n,m) :: (Int,Int)\r\n where\r\n f | n <= m = solveN\r\n | otherwise = swap . solveN . swap\r\n\r\nsolveN (n,m) | n > m = error \"Wrong usage\"\r\n | n >= 2 && m >= 4 = (2,2)\r\n | n == 1 = (1,1)\r\n | n == 2 = (2,2)\r\n | n == 3 = (2,2)\r\n | otherwise = error \"Logic error (impossible)\"\r\n"}, {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\r\n#ifndef DEBUG\r\n{-# LANGUAGE Safe #-}\r\n#endif\r\n\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport qualified Data.String as S\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Data.Functor ((<&>))\r\nimport Data.Maybe\r\nimport qualified Data.Traversable as T\r\n\r\nimport qualified Control.Applicative as A\r\nimport qualified Control.Monad as M\r\nimport qualified Control.Monad.State as MS\r\nimport qualified Control.Monad.Trans as MT\r\nimport qualified Control.Monad.Trans.Maybe as M\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\n\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.Set as S\r\nimport Data.List (sortBy, sortOn)\r\n\r\nimport Data.Char\r\nimport Data.Int\r\n\r\nimport System.IO (stdin, stdout, hFlush)\r\nimport Text.Printf\r\n\r\n#ifdef DEBUG\r\nimport Debug.Trace (trace, traceM, traceShowM)\r\ndebug = flip trace\r\n\r\ntracing t x = trace (t ++ \" = \" ++ show x) x\r\ndebugging x t = tracing t x\r\n\r\ntracingM t x = traceM $ t ++ \" = \" ++ show x\r\n\r\n#else\r\n\r\ndebug x _ = x\r\ntrace _ x = x\r\ntracing _ x = x\r\ndebugging x _ = x\r\n\r\ntraceM _ = pure ()\r\ntracingM _ _ = pure ()\r\n#endif\r\n\r\n\r\n{- reading -}\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntB8s :: B8.ByteString -> [Int]\r\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\nreadIntegerB8s :: B8.ByteString -> [Integer]\r\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\r\n\r\n\r\n\r\nsolve 1 m = [1, m]\r\nsolve n 1 = [n, 1]\r\nsolve n m = [2, 2]\r\n\r\nmain :: IO()\r\nmain = do\r\n\tt <- B8.getLine <&> readIntB8\r\n\tM.replicateM_ t $ do\r\n\t\t[n, m] <- B8.getLine <&> readIntB8s\r\n\t\tlet answer = solve n m \r\n\t\tM.forM_ answer $ \\x -> printf \"%d \" x\r\n\t\tputStrLn \"\""}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[n, m] -> case isolated n m of\n Just (x, y) -> putStrLn (show x ++ \" \" ++ show y)\n Nothing -> putStrLn \"1 1\"\nisolated :: Int -> Int -> Maybe (Int, Int)\nisolated n m = if (div n 2) >= 2 && (div m 2) >= 2\n then Nothing\n else Just (mod n 2 + div n 2, mod m 2 + div m 2)\n \n"}, {"source_code": "import Control.Monad\r\n\r\ntoShow (x,y) = show x ++ \" \" ++ show y\r\n\r\nsolve n m = (div (n+1) 2,div (m+1) 2)\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let [n,m] = map read . words $ input ::[Int]\r\n putStrLn.toShow$ solve n m\r\n return ()"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Data.Array.ST.Safe\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Semigroup\r\nimport GHC.Exts\r\nimport System.IO\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n casnum <- getInt\r\n ress <- forM [1 .. casnum] $ \\_ -> do\r\n n <- getInt\r\n m <- getInt\r\n let res\r\n | n == 2 && (m == 2 || m == 3) = [1, 2]\r\n | n == 3 && m == 2 = [2, 1]\r\n | otherwise = [1, 1]\r\n pure res\r\n pure $ foldl1 (<>) $ map putInts ress\r\ntype SP = State P.ByteString\r\n\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs =\r\n let sepPrim =\r\n (,) ' '\r\n Prim.>$< Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Tuple\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,m] <- ri\r\n return (n,m)\r\n mapM_ (putStrLn.showT.solve) tcs\r\n\r\nshowT (a,b) = show a ++ \" \" ++ show b\r\n\r\nsolve (n,m) = f (n,m) :: (Int,Int)\r\n where\r\n f | n <= m = solveN\r\n | otherwise = swap . solveN . swap\r\n\r\nsolveN (n,m) | n >= 2 && m >= 4 = (2,4) -- any\r\n | n == 1 = (1,1)\r\n | n == 2 = (1,1)\r\n | n == 3 = (2,2)\r\n | otherwise = error \"Logic error (impossible)\"\r\n"}], "src_uid": "e6753e3f71ff13cebc1aaf04d3d2106b"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine\r\n xs <- sort . map parseInt . BS.words <$> BS.getLine\r\n let\r\n (_,i) = minimum (map (\\(x,y,i) -> (y-x,i)) $ zip3 xs (drop 1 xs) [0..])\r\n (a,x0:x1:b) = splitAt i xs\r\n r = x0:b ++ a ++ [x1]\r\n putStrLn . unwords $ map show r\r\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\nprintArr = putStrLn . unwords . map show\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n h <- readInts\r\n let sh = sort h\r\n if n <= 2 then printArr sh \r\n else \r\n let zh = zip (zipWith (-) (tail sh) sh) [0..]\r\n (_,i) = minimum zh\r\n (f,l) = splitAt (i+1) sh\r\n in printArr $ l ++ f \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\ntoStr [] = \"\"\r\ntoStr (x:xs) = show x ++ \" \" ++ toStr xs\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n h <- readInts\r\n let sh = sort h\r\n if n <= 2 then putStrLn $ toStr sh \r\n else \r\n let zh = zip (zipWith (-) (tail sh) sh) [0..]\r\n (_,i) = minimum zh\r\n (f,l) = splitAt (i+1) sh\r\n in putStrLn $ toStr $ l ++ f \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- sort <$> getInts\n let diff = minimum $ zipWith (flip (-)) as $ tail as\n func (x1 : x2 : xs)\n | x2 - x1 == diff = x2 : xs\n | otherwise = func (x2 : xs)\n results\n | n == 2 = as\n | otherwise = take n $ func $ as ++ as\n return $ mconcat (map (\\x -> intDec x `mappend` charUtf8 ' ') results) `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\ntoStr [] = \"\"\r\ntoStr (x:xs) = show x ++ \" \" ++ toStr xs\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n h <- readInts\r\n let sh = sort h\r\n zh = zip (zipWith (-) (tail sh) sh) [0..]\r\n (_,i) = if n > 1 then minimum zh else (0,0)\r\n (a,b) = splitAt (i+1) sh \r\n putStrLn $ toStr $ b ++ a\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "src_uid": "3342e71884677534b7a126f89d441585"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Ord\nimport Control.Applicative\n\nreadInteger s = let Just (n,_) = B.readInteger s in n\n\nmain = do\n [_,d] <- map read.words <$> getLine\n [a,b] <- map read.words <$> getLine\n let toCosts [] = []\n toCosts (x:y:xys) = (a*x+b*y):toCosts xys\n costs <- zip[1..].toCosts.map readInteger.B.words <$> B.getContents\n let solve ans !total [] = do\n print $ length ans\n putStrLn $ unwords $ map show $ ans\n solve ans !total ((i,c):rest)\n | total+c<=d = solve (i:ans) (total+c) rest\n | otherwise = do\n print $ length ans\n putStrLn $ unwords $ map show $ ans\n solve [] 0 $ sortBy(comparing snd)costs\n", "positive_code": [{"source_code": "import Data.List\n\ndata Client = Client { size :: Integer,\n\t\t\t\t\tident :: Integer\n\t\t\t\t\t}\n\t\t\t\t\tderiving(Eq,Ord)\ninstance Show Client where\n\tshow (Client _s i) = show i\n\n\n\n\nprocess ls hs = flip go 1\n\twhere\n\t\tgo [] _ = []\n\t\tgo (l:h:cs) n = Client (l*ls+h*hs) n : go cs (succ n)\n\n\nserve mem = flip go 0\n\twhere\n\t\tgo [] _ = []\n\t\tgo (c@(Client s _):xs) n \n\t\t\t| n+s<=mem = c:go xs (n+s)\n\t\t\t| otherwise = []\n\nmain = do\n\ts <- fmap words getContents\n\tlet (_:mem:ls:hs:cs) = map read s\n\tlet servedclients =serve mem $ sort $ process ls hs cs\n\tprint $ length servedclients\n\tputStrLn $ unwords $ map show servedclients\n"}, {"source_code": "\nimport Char (isDigit, ord)\nimport Control.Monad (liftM)\nimport Data.List (sortBy)\n\n--import CPUTime\n--import IO (hPutStrLn, stderr)\n\n{-\nimport HUnit\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq (2, [2,3]) $ solve 3 10 2 3 [(1,4), (2,1), (1,0)],\n Test \"2\" $ assertEq (1, [2]) $ solve 3 6 6 6 [(1,1), (1,0), (1,0)]\n ]\n\ntestBigNumbers :: Test\ntestBigNumbers = Test \"TestBigNumbers\" $\n assertEq (1, [3]) $ solve 3 (10^9) (10^5) (10^5) [(10000, 10000), (10000, 0), (0,1)] \n\ntest :: IO ()\ntest = runs\n [\n testInput,\n testBigNumbers\n ]\n-}\n\nsolve :: Int -> Int -> Int -> Int -> [(Int, Int)] -> (Int, [Int])\nsolve n d a b xs = solve' d (0, []) sorted \n where\n sorted = sortBy (\\n1 n2 -> compare (snd n1) (snd n2)) $\n zipWith (\\n (x, y) -> (n, a * x + b * y)) [1..] xs\n solve' _ acc [] = acc\n solve' freeMemory (c, acc) ((n, memory) : xs)\n | freeMemory' >= 0 = solve' freeMemory' (c + 1, n : acc) xs\n | otherwise = (c, acc)\n where\n freeMemory' = freeMemory - memory\n\nreadPair :: String -> (Int, Int)\nreadPair s = reads' 0 s\n where\n reads' a (' ':s) = reads'' a 0 (dropWhile (== ' ') s)\n reads' a (c:s)\n | isDigit c = reads' (10*a + ord c - ord '0') s\n | otherwise = error $ concat [\"readPair: unknown symbol \", show c]\n reads'' a b [] = (a, b)\n reads'' a b (c:s)\n | isDigit c = reads'' a (10*b + ord c - ord '0') s\n | otherwise = error $ concat [\"readPair: unknown symbol \", show c]\n\nprintAns :: (Int, [Int]) -> IO ()\nprintAns (n, xs) = print n >> printAns' xs\n where\n printAns' [] = return ()\n printAns' [x] = print x\n printAns' (x:xs) = putStr (concat [show x, \" \"]) >> printAns' xs\n\nmain :: IO ()\nmain = do\n-- timeStart <- getCPUTime\n\n lines' <- liftM lines getContents\n let (n, d) = (readPair . head) lines'\n let (a, b) = (readPair . (head . tail)) lines'\n let xs = (take n . map readPair . (tail . tail)) lines' \n printAns $ solve n d a b xs\n\n-- timeEnd <- getCPUTime\n-- hPutStrLn stderr $ concat [\"Time = \", show $ fromIntegral (timeEnd - timeStart) / (10^12), \" sec.\"]\n"}], "negative_code": [{"source_code": "import Data.List\n\ndata Client = Client { size :: Int,\n\t\t\t\t\tident :: Int\n\t\t\t\t\t}\n\t\t\t\t\tderiving(Eq,Ord)\ninstance Show Client where\n\tshow (Client _s i) = show i\n\n\n\n\nprocess ls hs = flip go 1\n\twhere\n\t\tgo [] _ = []\n\t\tgo (l:h:cs) n = Client (l*ls+h*hs) n : go cs (succ n)\n\n\nserve mem = flip go 0\n\twhere\n\t\tgo [] _ = []\n\t\tgo (c@(Client s _):xs) n \n\t\t\t| n+s<=mem = c:go xs (n+s)\n\t\t\t| otherwise = []\n\nmain = do\n\ts <- fmap words getContents\n\tlet (_:mem:ls:hs:cs) = map read s\n\tlet servedclients =serve mem $ sort $ process ls hs cs\n\tprint $ length servedclients\n\tputStrLn $ unwords $ map show servedclients\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Ord\nimport Control.Applicative\n\nreadInt s = let Just (n,_) = B.readInt s in n\n\nmain = do\n [_,d] <- map read.words <$> getLine\n [a,b] <- map read.words <$> getLine\n let toCosts [] = []\n toCosts (x:y:xys) = (a*x+b*y):toCosts xys\n costs <- zip[1..].toCosts.map readInt.B.words <$> B.getContents\n let solve !ans !total [] = do\n print $ length ans\n putStrLn $ unwords $ map show $ ans\n solve !ans !total ((i,c):rest)\n | total+c<=d = solve (i:ans) (total+c) rest\n | otherwise = do\n print $ length ans\n putStrLn $ unwords $ map show $ ans\n solve [] 0 $ sortBy(comparing snd)costs\n"}], "src_uid": "4d7de18e76600777ff023e1b61366ee4"} {"source_code": "import Data.List\n\nmain = do\n _ <- getLine\n t <- getLine\n putStrLn $ sort t\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n n <- readLn :: IO Int\n s <- sort <$> getLine\n\n putStrLn $ s\n"}, {"source_code": "-- Codeforces 1064 C\nimport qualified Data.Map.Strict as Map\nimport Data.List\n\ncreateMap :: String -> Map.Map Char Int\ncreateMap string = Map.fromListWith (+) [(c, 1) | c <- string]\n\ntoString :: Map.Map Char Int -> String\ntoString charMap = concat $ map (\\(c, n) -> replicate n c) (Map.toList charMap)\n\nmain :: IO ()\nmain = do\n n <- getLine\n input <- getLine\n putStrLn ((toString . createMap) input )\n"}], "negative_code": [], "src_uid": "8616ede6867c8aacde986a123ec8a921"} {"source_code": "\nmain = do\n\tt<-getLine\n\trest<-getContents\n\tlet dict = map words $ lines rest\n\tputStrLn $ unlines $ solve dict\n\nsolve c = map head \n ((filter (elem \"rat\") c) ++\n (filter (\\x->elem \"child\" x || elem \"woman\" x) c) ++ \n (filter (elem \"man\") c) ++ \n (filter (elem \"captain\") c))", "positive_code": [{"source_code": "import Data.List\nmain=interact$unlines.map snd.sort.map f.zip[1..].tail.lines\nf(i,x)=((g b,i),a) where [a,b]=words x\ng('m':_)=3\ng('w':_)=2\ng(_:'h':_)=2\ng('c':_)=4\ng _=1"}, {"source_code": "import Data.List (sortBy)\nimport Data.Function (on)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . map words . tail . lines\n\nsolve :: [[String]] -> [String]\nsolve = map (!!0) . sortBy (compare `on` (priority . (!!1)))\n where priority \"rat\" = 0 :: Int\n priority \"woman\" = 1\n priority \"child\" = 1\n priority \"man\" = 2\n priority \"captain\" = 3\n priority _ = 4\n"}, {"source_code": "import Data.List\nimport Data.Ord\nrank \"rat\" = 0\nrank \"child\" = 1\nrank \"woman\" = 1\nrank \"man\" = 2\nrank \"captain\" = 3\nmain = interact $ unlines . map head . sortBy (comparing $ rank . (!!1)) . map words . tail . lines"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.tail.lines\n\nfunc::[String]->String\nfunc = unlines.solve.map words\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nsolve::[[String]]->[String]\nsolve a = rat ++ wac ++ man ++ cap\n where\n rat = map (!!0) $ filter (\\ (_:a:[]) -> a `elem` [\"rat\"]) a\n wac = map (!!0) $ filter (\\ (_:a:[]) -> a `elem` [\"woman\",\"child\"]) a\n man = map (!!0) $ filter (\\ (_:a:[]) -> a `elem` [\"man\"]) a\n cap = map (!!0) $ filter (\\ (_:a:[]) -> a `elem` [\"captain\"]) a "}, {"source_code": "import qualified Data.Map as M\nimport Data.List\npri = M.fromList [(\"rat\", 1), (\"child\", 2), (\"woman\", 2), (\"man\", 4), (\"captain\", 5)]\nmain = do\n n <- read `fmap` getLine\n l <- mapM (\\_ -> words `fmap` getLine) [1..n]\n let l1 = unlines $ map head $ sortBy (\\[_, a] [_, b] -> compare (pri M.! a) (pri M.! b)) l\n putStr l1\n"}, {"source_code": "import Data.List\n\norder s = case s of\n \"rat\" -> 0\n \"woman\" -> 1\n \"child\" -> 1\n \"man\" -> 2\n _ -> 3\n\nparseInput input = zip3 as bs cs where\n n = read $ head $ lines input :: Int\n is = map words $ tail $ lines input\n-- xs = [x | [x,_] <- is]\n cs = map head is\n ys = map last is\n as = map order ys\n bs = take n [1..]\n \nsolve xs = ys where\n ys = map (\\(_, _, c) -> c) $ sort xs\n\nmain = do\n input <- getContents\n let xs = parseInput input\n putStrLn $ intercalate \"\\n\" $ solve xs\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ndata Crew = Crew { crewPri, crewPos :: Int, crewName :: String } deriving (Eq, Ord, Show)\n\ngroupPri \"rat\" = 1\ngroupPri \"woman\" = 2\ngroupPri \"child\" = 2\ngroupPri \"man\" = 3\ngroupPri \"captain\" = 4\n\nmain = do\n n <- read `liftM` getLine\n crews <- forM [1..n] $ \\i -> do\n [name, group] <- words `liftM` getLine\n return $ Crew ( groupPri group ) i name\n\n putStr $ unlines $ map crewName $ sort crews\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n ls <- fmap (map (\\[a, b] -> (a, b)) . map words . lines) getContents\n\n let\n f ((a, b), i) = (j, i)\n where\n j = case b of\n \"rat\" -> 0\n \"woman\" -> 1\n \"child\" -> 1\n \"man\" -> 2\n \"captain\" -> 3\n\n putStrLn $ unlines $ map (fst . fst) $ sortBy (compare `on` f) $ zip ls [1..]\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport System.IO\n\nmain :: IO()\nmain = do\n interact $ unlines . map head . sortBy (comparing $ rank . (!!1)) . map words . tail . lines\n\nrank :: String -> Int\nrank x\n |x == \"rat\" = 0\n |x == \"child\" = 1\n |x == \"woman\" = 1\n |x == \"man\" = 2\n |x == \"captain\" = 3\n"}, {"source_code": "import List\n\ndata CrewMember = Rat Int String | WomanOrChild Int String | Man Int String | Captain Int String\n deriving (Show, Eq, Ord)\n\ncrewMember :: String -> Int -> String -> CrewMember\ncrewMember \"captain\" n name = Captain n name\ncrewMember \"man\" n name = Man n name\ncrewMember \"woman\" n name = WomanOrChild n name\ncrewMember \"child\" n name = WomanOrChild n name\ncrewMember _ n name = Rat n name\n\nreadLine :: Int -> IO CrewMember\nreadLine n = do\n line <- getLine\n let [name, status] = words line\n return (crewMember status n name)\n\nmyPrint :: [CrewMember] -> IO ()\nmyPrint members = do\n sequence_ (map myPrint_ members)\n where\n myPrint_ :: CrewMember -> IO ()\n myPrint_ (Captain n name) = putStrLn name\n myPrint_ (Man n name) = putStrLn name\n myPrint_ (WomanOrChild n name) = putStrLn name\n myPrint_ (Rat n name) = putStrLn name\n\nmain = do\n n <- readLn::(IO Int)\n lines <- sequence (map readLine [1..n])\n myPrint (sort lines)\n\n\n\n"}], "negative_code": [{"source_code": "import Data.List\nmain=interact$unlines.map snd.sort.map f.zip[1..].tail.lines\nf(i,x)=((g b,i),a) where [a,b]=words x\ng('m':_)=3\ng('w':_)=2\ng(_:'h':_)=4\ng('c':_)=2\ng _=1"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . map words . tail . lines\n\nsolve :: [[String]] -> [String]\nsolve = map snd . sort . map f\n where f [x, \"rat\"] = (0 :: Int, x)\n f [x, \"woman\"] = (1, x)\n f [x, \"child\"] = (2, x)\n f [x, \"man\"] = (3, x)\n f [x, \"captain\"] = (4, x)\n f _ = undefined\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . map words . tail . lines\n\nsolve :: [[String]] -> [String]\nsolve = map snd . sort . map f\n where f [x, \"rat\"] = (0 :: Int, x)\n f [x, \"woman\"] = (1, x)\n f [x, \"child\"] = (1, x)\n f [x, \"man\"] = (2, x)\n f [x, \"captain\"] = (3, x)\n f _ = undefined\n"}], "src_uid": "753113fa5130a67423f2e205c97f8017"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n print $ query n as\n\nquery :: Int -> [Int] -> Int\nquery n as = (summ -) $ maximum $ map gainFor as\n where\n (!mini,!summ) = foldl' (\\(!mini,!summ) a -> (mini `min` a, summ + a))\n (maxBound,0) as\n gainFor a = search a 2 1 0\n search !a !x !prevx !prevgain\n | x > a `shiftR` 1 = prevgain\n | r /= 0 = search a (x+1) prevx prevgain\n | gain > prevgain = search a (x+1) x gain\n | otherwise = prevgain\n where\n (q,r) = a `divMod` x\n gain = (a + mini) - (q + mini * x)\n \n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "import Data.List\nmain = interact $ show . solve . sort . map read . tail . words\nsolve (a0:as) = sum (as) + minimum (map f as) where\n f a = minimum [ x*a0 + a `div` x - a | x <- [1..a], a `mod` x == 0 ]\n"}, {"source_code": "main = interact (format . solve . parse)\n\nparse :: String -> [Int]\nparse = (map read) . (drop 1) . words\n\nsolve a = (sum a) - maximum (0:\n (concat [\n map (\\x -> let (q, r) = divMod ai x in if r == 0\n then ai - x - minA * (q - 1)\n else 0)\n [minA + 1..ai]\n | ai <- a])\n )\n where minA = minimum a\n\nformat = show\n"}], "negative_code": [], "src_uid": "d8349ff9b695612473b2ba00d08e505b"} {"source_code": "import Data.Int (Int64)\nimport qualified Data.IntMap.Strict as S\nimport Data.Maybe (fromJust, isNothing)\n\nmain = do\n _ <- getLine\n a <- map read . words <$> getLine\n print $ solve S.empty 0 a\n\nsolve :: S.IntMap Int -> Int64 -> [Int] -> Int\nsolve s h [] = sum $ S.elems s\nsolve s h (x:xs)\n | h' >= 0 = solve s' h' xs\n | otherwise =\n let ((y, c), s'') = S.deleteFindMin s'\n in solve\n (if c > 1\n then S.insert y (c - 1) s''\n else s'')\n (h' - fromIntegral y)\n xs\n where\n s' = S.insert x (1 + count s x) s\n h' = h + fromIntegral x\n\ncount :: S.IntMap Int -> Int -> Int\ncount s x\n | isNothing c = 0\n | otherwise = fromJust c\n where\n c = S.lookup x s\n", "positive_code": [{"source_code": "import Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport qualified Data.IntMap.Strict as IM\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _ <- getInts\n as <- getInts\n let (result, _, _) = foldl' acc (0, 0, IM.empty) as\n acc :: (Int, Int64, IM.IntMap Int) -> Int -> (Int, Int64, IM.IntMap Int)\n acc (num, hp, mp) a\n | a >= 0 = (num + 1, hp + fromIntegral a, mp)\n | hp + fromIntegral a < 0 = (num, hp', IM.alter dec a' mp')\n | otherwise = (num + 1, hp + fromIntegral a, IM.alter inc a mp)\n where Just (a', _) = IM.lookupMin mp'\n mp' = IM.alter inc a mp\n hp' = hp + fromIntegral a - fromIntegral a'\n inc Nothing = Just 1\n inc (Just x) = Just (x + 1)\n dec Nothing = Nothing\n dec (Just 1) = Nothing\n dec (Just x) = Just (x - 1)\n hPutBuilder stdout $ intDec result `mappend` charUtf8 '\\n'\n"}], "negative_code": [], "src_uid": "b4a4448af5b61fe5a8467a8d0e12fba8"} {"source_code": "import qualified Data.List.Split as Split\nimport qualified Data.Tree as T\nimport qualified Data.Array as A\nimport Data.Int\n\ndata Color = Black | White\n\ntype Node = Int64\n\nmyToInt64 x = read x :: Int64\ngetInt64List = fmap ((map myToInt64) .(Split.splitOn \" \")) getLine\n\nlistToAdjList :: Int64 -> [Int64] -> A.Array Int64 [Node]\nlistToAdjList n edges =\n A.accumArray (\\l i -> (i+1):l) [] (0, n-1) (zip edges [0..]) \n \nmodu x = x `mod` 1000000007\n\nf :: A.Array Int64 Color -> A.Array Int64 [Node] -> Node -> Int64 -> Int64\nf colors edges node b = go node b \n where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]\n go node b = memo A.! (node, b)\n n = snd (A.bounds colors) + 1\n recu node b = ways (colors A.! node) b (edges A.! node)\n ways :: Color -> Int64 -> [Node] -> Int64\n ways Black 1 ch = multiplyAll ch\n ways Black 0 ch = 0\n ways White 1 ch = fst $\n foldr (\\c (r,p) ->\n (modu $ modu (r * both c) + modu(p * go c 1),\n modu $ p * both c))\n (0, 1)\n ch\n ways White 0 ch = multiplyAll ch \n multiplyAll :: [Node] -> Int64\n multiplyAll = moduProduct . (map both)\n both c = modu $ sum [go c b | b <- [0, 1]]\n\nmoduProduct :: [Int64] -> Int64\nmoduProduct = foldr (\\x y -> modu $ x * y) 1\n\nmain = do\n n <- fmap myToInt64 getLine\n edges <- getInt64List\n colors <- fmap (map (\\x -> case x of\n 1 -> Black\n 0 -> White))\n getInt64List\n print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1\n", "positive_code": [{"source_code": "import qualified Data.List.Split as Split\nimport qualified Data.Tree as T\nimport qualified Data.Array as A\nimport Data.Int\nimport Data.List as L\n\ndata Color = Black | White\n\ntype Node = Int64\n\nmyToInt64 x = read x :: Int64\ngetInt64List = fmap ((map myToInt64) .(Split.splitOn \" \")) getLine\n\nlistToAdjList :: Int64 -> [Int64] -> A.Array Int64 [Node]\nlistToAdjList n edges =\n A.accumArray (\\l i -> (i+1):l) [] (0, n-1) (zip edges [0..]) \n \nmodu x = x `mod` 1000000007\n\nf :: A.Array Int64 Color -> A.Array Int64 [Node] -> Node -> Int64 -> Int64\nf colors edges node b = go node b \n where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]\n go node b = memo A.! (node, b)\n n = snd (A.bounds colors) + 1\n recu node b = ways (colors A.! node) b (edges A.! node)\n ways :: Color -> Int64 -> [Node] -> Int64\n ways Black 1 ch = multiplyAll ch\n ways Black 0 ch = 0\n ways White 1 ch = fst $\n L.foldl' (\\(r,p) c ->\n (modu $ modu (r * both c) + modu(p * go c 1),\n modu $ p * both c))\n (0, 1)\n ch\n ways White 0 ch = multiplyAll ch \n multiplyAll :: [Node] -> Int64\n multiplyAll = moduProduct . (map both)\n both c = modu $ sum [go c b | b <- [0, 1]]\n\nmoduProduct :: [Int64] -> Int64\nmoduProduct = L.foldl' (\\x y -> modu $ x * y) 1\n\nmain = do\n n <- fmap myToInt64 getLine\n edges <- getInt64List\n colors <- fmap (map (\\x -> case x of\n 1 -> Black\n 0 -> White))\n getInt64List\n print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1\n"}, {"source_code": "import qualified Data.List.Split as Split\nimport qualified Data.Tree as T\nimport qualified Data.Array as A\n\ndata Color = Black | White\n\ntype Node = Integer\n\nmyToInteger x = read x :: Integer\ngetIntegerList = fmap ((map myToInteger) .(Split.splitOn \" \")) getLine\n\nlistToAdjList :: Integer -> [Integer] -> A.Array Integer [Node]\nlistToAdjList n edges =\n A.accumArray (\\l i -> (i+1):l) [] (0, n-1) (zip edges [0..]) \n \nmodu x = x `mod` 1000000007\n\nf :: A.Array Integer Color -> A.Array Integer [Node] -> Node -> Integer -> Integer\nf colors edges node b = go node b \n where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]\n go node b = memo A.! (node, b)\n n = snd (A.bounds colors) + 1\n recu node b = ways (colors A.! node) b (edges A.! node)\n ways :: Color -> Integer -> [Node] -> Integer\n ways Black 1 ch = multiplyAll ch\n ways Black 0 ch = 0\n ways White 1 ch = fst $\n foldr (\\c (r,p) ->\n (modu $ modu (r * both c) + modu(p * go c 1),\n modu $ p * both c))\n (0, 1)\n ch\n ways White 0 ch = multiplyAll ch \n multiplyAll :: [Node] -> Integer\n multiplyAll = moduProduct . (map both)\n both c = modu $ sum [go c b | b <- [0, 1]]\n\nmoduProduct :: [Integer] -> Integer\nmoduProduct = foldr (\\x y -> modu $ x * y) 1\n\nmain = do\n n <- fmap myToInteger getLine\n edges <- getIntegerList\n colors <- fmap (map (\\x -> case x of\n 1 -> Black\n 0 -> White))\n getIntegerList\n print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1\n"}], "negative_code": [{"source_code": "import qualified Data.List.Split as Split\nimport qualified Data.Tree as T\nimport qualified Data.Array as A\n\ndata Color = Black | White\n\ntype Node = Int\n\ntoInt x = read x :: Int\ngetIntList = fmap ((map toInt) .(Split.splitOn \" \")) getLine\n\nlistToAdjList :: Int -> [Int] -> A.Array Int [Node]\nlistToAdjList n edges =\n A.accumArray (\\l i -> (i+1):l) [] (0, n-1) (zip edges [0..]) \n \nmodu x = x `mod` 1000000007\n\nf :: A.Array Int Color -> A.Array Int [Node] -> Node -> Int -> Int\nf colors edges node b = go node b \n where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]\n go node b = memo A.! (node, b)\n n = snd (A.bounds colors) + 1\n recu node b = ways (colors A.! node) b (edges A.! node)\n ways :: Color -> Int -> [Node] -> Int\n ways Black 1 ch = multiplyAll ch\n ways Black 0 ch = 0\n ways White 1 ch = fst $\n foldr (\\c (r,p) ->\n (modu $ modu (r * both c) + modu(p * go c 1),\n modu $ p * both c))\n (0, 1)\n ch\n ways White 0 ch = multiplyAll ch \n multiplyAll :: [Node] -> Int\n multiplyAll = moduProduct . (map both)\n both c = modu $ sum [go c b | b <- [0, 1]]\n\nmoduProduct :: [Int] -> Int\nmoduProduct = foldr (\\x y -> modu $ x * y) 1\n\nmain = do\n n <- fmap toInt getLine\n edges <- getIntList\n colors <- fmap (map (\\x -> case x of\n 1 -> Black\n 0 -> White))\n getIntList\n print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1\n"}, {"source_code": "import qualified Data.List.Split as Split\nimport qualified Data.Tree as T\nimport qualified Data.Array as A\n\ndata Color = Black | White\n\ntype Node = Int\n\ntoInt x = read x :: Int\ngetIntList = fmap ((map toInt) .(Split.splitOn \" \")) getLine\n\nlistToAdjList :: Int -> [Int] -> A.Array Int [Node]\nlistToAdjList n edges =\n A.accumArray (\\l i -> (i+1):l) [] (0, n-1) (zip edges [0..]) \n \nmodu x = x `mod` 1000000007\n\nf :: A.Array Int Color -> A.Array Int [Node] -> Node -> Int -> Int\nf colors edges node b = go node b \n where memo = A.array ((0,0), (n-1, 1)) [ ((i, j), recu i j) | i <- [0 .. n - 1], j <- [0, 1]]\n go node b = memo A.! (node, b)\n n = snd (A.bounds colors) + 1\n recu node b = ways (colors A.! node) b (edges A.! node)\n ways :: Color -> Int -> [Node] -> Int\n ways Black 1 ch = multiplyAll ch\n ways Black 0 ch = 0\n ways White 1 ch = fst $\n foldr (\\c (r,p) ->\n (modu $ r * both c + p * go c 1,\n modu $ p * both c))\n (0, 1)\n ch\n ways White 0 ch = multiplyAll ch \n multiplyAll :: [Node] -> Int\n multiplyAll = moduProduct . map both\n both c = modu $ sum [go c b | b <- [0, 1]]\n\nmoduProduct :: [Int] -> Int\nmoduProduct = foldr (\\x y -> modu $ x * y) 1\n\nmain = do\n n <- fmap toInt getLine\n edges <- getIntList\n colors <- fmap (map (\\x -> case x of\n 1 -> Black\n 0 -> White))\n getIntList\n print $ f (A.listArray (0, n - 1) colors) (listToAdjList n edges) 0 1\n"}], "src_uid": "e571191fadf6b0b26bd2f16295f32077"} {"source_code": "import Control.Monad; import Data.List; main = do { t <- readLn; replicateM_ t $ do { [a, b] <- fmap (sort . map read . words) getLine; putStrLn $ if or [mod (a + b) 3 > 0, b - a > a] then \"NO\" else \"YES\" } }", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n\ngetIntList :: IO [Integer]\ngetIntList = fmap (map read) getStrList\n\nf :: Integer -> Integer -> String\nf a b\n | mod (a + b) 3 > 0 = \"NO\"\n | b - a > a = \"NO\"\n | otherwise = \"YES\"\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b] <- fmap sort getIntList\n putStrLn $ f a b"}, {"source_code": "import Control.Monad\n\nsolve :: Integer -> Integer -> Bool\nsolve x y = ((x+y) `mod` 3 ==0) && (2*min x y>=max x y)\n\nroutine :: IO ()\nroutine = do\n l <- fmap (map read . words) getLine\n if solve (head l) (l!!1) then putStrLn \"YES\" else putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Bool\nsolve x y = ((x+y) `mod` 3 ==0) && (3*min x y>=max x y)\n\nroutine :: IO ()\nroutine = do\n l <- fmap (map read . words) getLine\n if solve (head l) (l!!1) then putStrLn \"YES\" else putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "import Control.Monad\n\nsolve :: Integer -> Integer -> Bool\nsolve x y = ((x+y) `mod` 3 ==0) && (3*min x y>=max x y)\n\nroutine :: IO ()\nroutine = do\n l <- fmap (map read . words) getLine\n if solve (head l) (l!!1) then putStrLn \"YES\" else putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "src_uid": "0a720a0b06314fde783866b47f35af81"} {"source_code": "readArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\ngen :: Int -> Int -> Int\r\ngen x y = let (x1, y1) = (x `mod` 4, y `mod` 4) in [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]] !! x1 !! y1\r\n\r\npr :: [[Int]] -> IO ()\r\npr [] = pure ()\r\npr (x: xs) = do\r\n putStrLn $ concat $ map (\\x -> show x ++ \" \") x\r\n pr xs\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: m: _) <- readArr\r\n pr $ map (\\x -> map (\\y -> gen x y) [0..(m - 1)]) [0..(n - 1)]\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,m] <- ri\r\n return (n,m)\r\n mapM_ (putStr.showM.solve) tcs\r\n\r\nshowM = unlines . map showL\r\nshowL = unwords . map show\r\n\r\nsolve (n,m) = matr\r\n where\r\n matr = [[f (y-1,x-1) | x <- [1..m]]\r\n | y <- [1..n] ]\r\n f (a,b) = (y+x) `mod` 2\r\n where\r\n y = (a+1) `div` 2\r\n x = (b+1) `div` 2\r\n"}, {"source_code": "(>>>) = flip (.)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> tail\r\n >>> map\r\n ( words\r\n >>> map read\r\n >>> solve\r\n >>> map (map show >>> unwords)\r\n >>> unlines\r\n )\r\n >>> unlines\r\n\r\nsolve :: [Int] -> [[Int]]\r\nsolve [n, m] =\r\n [ [ (bits (i `mod` 4) + bits (j `mod` 4)) `mod` 2\r\n | j <- [0 .. m - 1]\r\n ]\r\n | i <- [0 .. n - 1]\r\n ]\r\n\r\nbits :: Int -> Int\r\nbits 0 = 0\r\nbits n = bits (n `div` 2) + (n `mod` 2)\r\n"}, {"source_code": "getRow :: Int -> Int -> String\r\ngetRow i m = unwords $ take m $ cycle (if i `mod` 4 == 0 || i `mod` 4 == 3 then [\"0\", \"1\", \"1\", \"0\"] else [\"1\", \"0\", \"0\", \"1\"])\r\n\r\ngetNRows :: Int -> Int -> String\r\ngetNRows 0 _ = \"\"\r\ngetNRows n m = getNRows (n - 1) m ++ \"\\n\" ++ getRow (n - 1) m\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n dimensions <- getLine\r\n let nm = map (\\w -> (read w :: Int)) $ words dimensions\r\n let n = head nm\r\n let m = last nm\r\n putStrLn $ getNRows n m\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)"}, {"source_code": "getRow :: Int -> Int -> String\r\ngetRow i m = unwords $ take m $ cycle (if i `mod` 4 == 0 || i `mod` 4 == 3 then [\"0\", \"1\", \"1\", \"0\"] else [\"1\", \"0\", \"0\", \"1\"])\r\n\r\ngetNRows :: Int -> Int -> String\r\ngetNRows 0 _ = \"\"\r\ngetNRows n m = getNRows (n - 1) m ++ \"\\n\" ++ getRow (n - 1) m\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n dimensions <- getLine\r\n let nm = map (\\w -> (read w :: Int)) $ words dimensions\r\n let n = head nm\r\n let m = last nm\r\n putStrLn $ getNRows n m\r\n\r\nsolve :: Int -> IO ()\r\nsolve cases_left = do\r\n if cases_left == 1 then\r\n solveCase\r\n else do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n\nm :: Int64\nm = 998_244_353\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\nmI :: Int -> M\nmI = M . fromIntegral\n\ninstance Show M where \n show (M v) = \"M\" ++ show v\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = M $ (a * b) `mod` m\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> Int -> [[Int]]\nsolve n m = do\n i <- [1 .. n]\n let iValue = (i `div` 2) `mod` 2\n let \n row :: [Int] = do\n j <- [1 .. m]\n let jValue = (j `div` 2) `mod` 2\n return $ iValue `xor` jValue\n return row\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, m] <- B8.getLine <&> readIntB8s\n let answer = solve n m\n forM_ answer $ \\row -> do\n forM_ row $ \\value -> do\n printf \"%d \" value\n putStrLn \"\"\n\n\n\n-- 1 0 0 1\n-- 0 1 1 0\n-- 0 1 1 0\n-- 1 0 0 1\n-- 1 0 0 1\n-- 0 1 1 0\n-- 0 1 1 0\n-- 1 0 0 1\n"}, {"source_code": "{-# LANGUAGE CPP #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\n-- import qualified Data.ByteString.Lazy.Char8 as B\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n#ifdef LOCAL\r\n handle <- openFile \"input\" ReadMode\r\n inp <- P.hGetContents handle\r\n#else\r\n inp <- P.getContents\r\n#endif\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n m <- getInt\r\n let\r\n row1 = take m $ cycle $ [1, 0] ++ [0, 1]\r\n row2 = take m $ cycle $ [0, 1] ++ [1, 0]\r\n rows = cycle $ [row1, row2, row2, row1]\r\n ans = take n rows\r\n fmap mconcat $ sequence $ fmap (pure . putInts) ans\r\n"}], "negative_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,m] <- ri\r\n return (n,m)\r\n mapM_ (putStr.showM.solve) tcs\r\n\r\nshowM = unlines . map showL\r\nshowL = unwords . map show\r\n\r\nsolve (n,m) = matr\r\n where\r\n matr = [[f (y,x) | x <- [1..m]]\r\n | y <- [1..n] ]\r\n f (y,x) = (y+x) `mod` 2\r\n"}, {"source_code": "(>>>) = flip (.)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> tail\r\n >>> map\r\n ( words\r\n >>> map read\r\n >>> solve\r\n >>> map (map show >>> unwords)\r\n >>> unlines\r\n )\r\n >>> unlines\r\n\r\nsolve :: [Int] -> [[Int]]\r\nsolve [n, m] =\r\n [ [ (bits i + bits j) `mod` 2\r\n | j <- [0 .. m -1]\r\n ]\r\n | i <- [0 .. n -1]\r\n ]\r\n\r\nbits :: Int -> Int\r\nbits 0 = 0\r\nbits n = bits (n `div` 2) + (n `mod` 2)\r\n"}], "src_uid": "b7d40e7fc4f277cc801b59a21a16dfc1"} {"source_code": "import Data.Bits\n \nmain :: IO()\nmain = do\n co <- getContents\n let (n:m:k:ca) = map read $ words co\n va = take (1+m) ca\n fu = va !! m\n in putStrLn $ show $ (length $ filter (\\x -> popCount (x `xor` fu) <= k) va) - 1", "positive_code": [{"source_code": "import Data.Bits(popCount,xor)\n\nmain = interact solve\n\nsolve input = show (foldr folder 0 tocheck)\n where \n folder::Int->Int->Int\n folder current count = if popCount (current `xor` own) > k then\n count\n else\n count+1\n numbers = (map read . words) input\n (n:m:k:thelist) = numbers\n tocheck::[Int]\n tocheck = init thelist\n own = last thelist\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Bits\n\nmain :: IO ()\nmain = do\n [_, m, k] <- getLine >>= (mapM (return . (read :: String -> Int))) . words\n vals <- forM [1..(m+1)] (\\_ -> getLine >>= (return . (read :: String -> Int)))\n print . length $ filter (<=k) [popCount (xor (last vals) i) | i <- init vals] \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport qualified Data.Map.Strict as M\nimport Data.Bits\n\n\n\n\n\n\n\nmain=do\n [n,m,k]<-map read <$> words <$> getLine ::IO [Int]\n s<-map read <$> lines <$> getContents ::IO [Int]\n let q = last s\n let s1 = init s\n print $ length $ filter (<=k) $ map popCount $ map (xor q) s1\n"}, {"source_code": "import Data.Bits\nmain=getContents>>=print.solve.map read.words\nsolve(_:_:k:xs)=length[x|x<-xs,popCount(x`xor`last xs)<=k]-1\n"}, {"source_code": "import Numeric (showIntAtBase)\nimport Data.Bits (xor)\nimport Data.Char (intToDigit)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:_:k:xs) = length [ x | x <- init xs, length (filter (=='1') (showIntAtBase 2 intToDigit (x `xor` last xs) \"\")) <= k ]\nsolve _ = undefined\n"}, {"source_code": "import Data.Bits (xor, popCount)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:_:k:xs) = length [ x | x <- init xs, popCount (x `xor` last xs) <= k ]\nsolve _ = undefined\n"}, {"source_code": "import Data.Bits\nmain=getContents>>=print.solve.map read.words\nsolve(_:_:k:xs)=length[x|x<-init xs,popCount(x`xor`last xs)<=k]\n"}, {"source_code": "import Data.Bits\nmain = interact $ show . solve . map read . words\nsolve (n:m:k:xs) = length $ filter ((<= k) . popCount) $ map (xor f) es\n where (es,[f]) = splitAt m xs\n"}, {"source_code": "import Data.Bits\n \nmain :: IO()\nmain = do\n co <- getContents\n let (n:m:k:ca) = map read $ words co\n va = take (1+m) ca\n fu = va !! m\n in putStrLn $ show $ (length [x | x <- va, popCount (x `xor` fu) <= k]) - 1"}, {"source_code": "module Main where\n\nimport Data.List (unfoldr)\nimport Data.Bits (xor)\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\nreadNumber = head `fmap` readNumbers\n\nbinaryList :: Int -> [Int]\nbinaryList n0 =\n reverse $\n unfoldr (\\n ->\n if n > 0\n then Just (n `mod` 2, n `div` 2)\n else Nothing)\n n0\n\nfriendship :: Int -> Int -> Int\nfriendship fedor other =\n sum (binaryList (xor fedor other))\n\nmain :: IO ()\nmain = do\n (_n:m:k:_) <- readNumbers\n others <- replicateM m readNumber\n fedor <- readNumber\n print (length (filter (<= k)\n (map (friendship fedor) others)))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Bits\n\n \n \n \n\nmain= do\n\t[n,m,k]<- map read. words <$> getLine ::IO [Int]\n\ts<- map read. words <$> getContents ::IO [Int]\n\tlet s1= init s\n\tlet f = last s\n\tprint $ length $ filter (<=k) $ map (popCount.xor f) s1"}, {"source_code": "\nmain = interact $ show . sol . map read . words\n\nsol (_:_:k:xs) = (subtract 1) $ length $ filter id $ map (\\x -> k >= (dif x $ last xs)) xs\n\ndif 0 0 = 0\ndif a b\n | odd a == odd b = nx\n | otherwise = nx+1\n where nx = dif (a `div` 2) (b `div` 2)\n\n\n"}, {"source_code": "import Data.Bits\n\nmain :: IO ()\nmain = do\n _:_:k:xs <- getReadAll\n print $ solve k xs\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = length $ filter (\\x-> popCount(xor fedor x) <= k) rest\n where \n rest = init xs\n fedor = last xs\n\ngetReadAll :: (Read a) => IO [a]\ngetReadAll = fmap (fmap read. words) getContents "}, {"source_code": "import Control.Monad\n\ntype BinaryArmy = [Int]\n\ngetArmies :: Int -> IO [Int]\ngetArmies n = replicateM n getArmy\n\ngetArmy :: IO Int\ngetArmy = do\n army <- getLine\n return $ read army\n\ncountFriends :: Int -> [Int] -> Int -> Int\ncountFriends army [] k = 0\ncountFriends army (player:others) k = (if binaryDifference binaryArmy binaryPlayer > k\n then 0\n else 1) + countFriends army others k\n where binaryArmy = toBinary army\n binaryPlayer = toBinary player\n\ntoBinary :: Int -> BinaryArmy\ntoBinary 0 = []\ntoBinary n = (n `mod` 2) : toBinary (n `div` 2)\n\nbinaryDifference :: BinaryArmy -> BinaryArmy -> Int\nbinaryDifference [] [] = 0\nbinaryDifference [] binary = sum binary\nbinaryDifference binary [] = sum binary\nbinaryDifference (x:xs) (y:ys) = (if x == y\n then 0\n else 1) + binaryDifference xs ys\n\nmain :: IO ()\nmain = do\n input <- getLine\n let [n, m, k] = map read (words input)\n armies <- getArmies m\n _army <- getLine\n let army = read _army\n putStrLn $ show $ countFriends army armies k"}, {"source_code": "import Control.Monad\nmain = interact $ show . solve . map read . words\nsolve(_:_:k:xs)=(length $ filter (\\y->k>=(diff y $ last xs)) xs)-1\ndiff 0 0 = 0\ndiff x y = (diff (div x 2) (div y 2))+a \n\twhere a=if odd x==odd y then 0 else 1\n"}, {"source_code": "import Data.Bits\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (_:m:k:x) = solve' (init x) (last x)\n where solve' :: [Int] -> Int -> Int\n solve' [] _ = 0\n solve' (x:xs) l | popCount (xor x l) <= k = 1 + solve' xs l\n | otherwise = solve' xs l\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = interact $ show . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (n:m:k:xs) = sum $ map (\\x -> if (popCount $ xor x l) <= k then 1 else 0) (init xs)\n\twhere l = last xs \n"}, {"source_code": "import Data.Bits\n\nmain = do\n [n, m, k] <- fmap (map read . words) getLine\n xs <- fmap (map read . lines) getContents :: IO [Int]\n\n let\n x = last xs\n\n print $ length $ filter (\\y -> popCount (x `xor` y) <= k) $ init xs\n"}, {"source_code": "import Data.Bits\nmain=getContents>>=print.solve.map read.words\nsolve(_:_:k:xs)=length[x|x<-xs,popCount(x`xor`last xs)<=k]-1"}, {"source_code": "import Data.Bits\nmain=getContents>>=print.solve.map read.words\nsolve(_:_:k:xs)=length[x|x<-xs,popCount(x`xor`last xs)<=k]-1\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\n--import Data.Bits.Bitwise as Bit\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\ns-> let [x,y,z]= map read $ words ns in (solve.(++) [z].concat =<< forM [1 .. y+1] ( \\i -> map (fst.fromJust.C.readInt).C.words <$> C.getLine))\nsolve::[Int]->IO()\nsolve (x:xs) = let l=last xs in print $ sum $ map (\\a->if popCount (xor a l)<=x then 1 else 0) (init xs)"}, {"source_code": "import Control.Applicative\nimport Data.Bits\nimport Control.Monad\n\nsolve :: Int -> [Int] -> Int -> Int\nsolve m ms k = length $ filter ((<=k).popCount.xor m) ms\n\nmain = do\n [_,m,k] <- fmap read.words <$> getLine\n ms <- replicateM (m+1) (read <$> getLine)\n print $ solve (last ms) (init ms) k\n"}, {"source_code": "import Data.Bits\nimport Control.Applicative\nimport qualified Data.List as L\n\nmain = do\n [n,m,k] <- map read . words <$> getLine :: IO [Int]\n xs <- map read . lines <$> getContents\n let (ls,[fed]) = L.splitAt m xs :: ([Int], [Int])\n diff = map (popCount . xor fed) ls\n print . sum $ map (\\x -> if x <= k then 1 else 0) diff"}], "negative_code": [], "src_uid": "5ebb0ee239d68ea33d9dac2d0bdd5f4e"} {"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\nimport Data.Bits((.&.), (.|.), xor)\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\t[n, m, x] <- getLine >>= return . (fmap read) . words\r\n\t\tprint $ 1 + (mod (x-1) n) * m + (div (x-1) n)\r\n\t\tloop $ t - 1\r\n\tloop t", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust, fromMaybe)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf (C.pack <$> testCase)) >>> C.unlines\r\n\r\ntestCase :: Scanner String\r\ntestCase = show . solve <$> three integer\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [I64] -> I64\r\nsolve [n, m, x] = let (c, r) = (x - 1) `divMod` n in 1 + r * m + c\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\n"}, {"source_code": "import Control.Monad\n\nsearchByRows target m = ((div (target - 1) m) + 1, (mod (target - 1) m) + 1)\n\nbuildByColumn n (x, y) = (+ x) $ (y - 1) * n\n\nsolve n m target = buildByColumn m $ searchByRows target n\n\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n [n, m, target] <- map read . words <$> getLine\n print $ solve n m target\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\r\n\r\nmodule Main where\r\nimport Control.Monad\r\n\r\n\r\nmain :: IO()\r\nmain =\r\n readLn >>= flip replicateM_ do\r\n [n, m, x] <- fmap read.words <$> getLine\r\n let prev = x - 1\r\n let (col, row) = quotRem prev n\r\n in print $ row * m + col + 1\r\n"}, {"source_code": "module Main where\r\n\r\nsolve :: [Integer] -> IO Integer\r\nsolve (n : m : x : _) = return $ row * m + col + 1\r\n where\r\n prev = x - 1\r\n col = prev `div` n\r\n row = prev `mod` n\r\n\r\noutput :: [IO Integer] -> IO ()\r\noutput collection = do\r\n out <- head collection\r\n print out\r\n if not (null $ tail collection)\r\n then output $ tail collection\r\n else pure()\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine :: IO Int\r\n let ans = replicate t ((map read . words <$> getLine :: IO [Integer]) >>= solve)\r\n in output ans\r\n"}, {"source_code": "module Main where\r\n\r\nreadArguments :: IO [Integer]\r\nreadArguments = do\r\n line <- getLine\r\n let array = map read (words line) :: [Integer]\r\n in return array\r\n\r\nsolve :: IO [Integer] -> IO Integer\r\nsolve arr = do\r\n params <- arr\r\n let (n : m : x : _) = params\r\n let prev = x - 1\r\n let col = prev `div` n\r\n let row = prev `mod` n\r\n in return $ row * m + col + 1\r\n\r\noutput :: [IO Integer] -> IO ()\r\noutput collection = do\r\n out <- head collection\r\n print out\r\n if not (null $ tail collection)\r\n then output $ tail collection\r\n else pure()\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine\r\n let count = read t :: Int\r\n let solves = replicate count (solve readArguments)\r\n in output solves\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nmain :: IO ()\nmain = do\n cases <- (read @Int) <$> getLine\n replicateM_ cases solve\n\nsolve :: IO ()\nsolve = do\n [r, c, x] <- map (read @Integer) . words <$> getLine\n let which_row = ((x - 1) `mod` r) + 1\n which_col = (x - 1) `div` r + 1\n print $ (which_row - 1) * c + which_col\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\r\n\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ do\r\n [n, m, a] <- fmap read . words <$> getLine\r\n let\r\n (x, y) = quotRem (a - 1) n\r\n print $ y * m + x + 1\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nreadArguments :: IO [Int]\r\nreadArguments = do\r\n line <- getLine\r\n let array = map read (words line) :: [Int]\r\n in return array\r\n\r\nsolve :: IO [Int] -> IO Int\r\nsolve arr = do\r\n params <- arr\r\n let (n : m : x : _) = params\r\n let prev = x - 1\r\n let col = prev `div` n\r\n let row = prev `mod` n\r\n in return $ row * m + col + 1\r\n\r\noutput :: [IO Int] -> IO ()\r\noutput collection = do\r\n out <- head collection\r\n print out\r\n if not (null $ tail collection)\r\n then output $ tail collection\r\n else pure()\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine\r\n let count = read t :: Int\r\n let solves = replicate count (solve readArguments)\r\n in output solves\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nmain :: IO ()\nmain = do\n cases <- (read @Int) <$> getLine\n replicateM_ cases solve\n\nsolve :: IO ()\nsolve = do\n [r, c, x] <- map (read @Int) . words <$> getLine\n let which_row = ((x - 1) `mod` r) + 1\n which_col = (x - 1) `div` r + 1\n print $ (which_row - 1) * c + which_col\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad\nmain :: IO ()\nmain = do\n cases <- (read @Int) <$> getLine\n replicateM_ cases solve\n\nsolve :: IO ()\nsolve = do\n [r, c, x] <- map (read @Int) . words <$> getLine\n let which_row = (x - 1) `mod` c\n which_col = (x - 1) `div` r\n print $ which_row * r + which_col + 1\n"}], "src_uid": "e519e4495c9acef4c4a614aef73cb322"} {"source_code": "solve :: [Int] -> String\r\nsolve xs = if 2 * maximum xs == sum xs then \"Yes\" else \"No\"\r\n\r\ntestCase = do\r\n numList <- words `fmap` getLine\r\n let nums = read `map` numList :: [Int]\r\n putStrLn $ solve nums\r\n return 0\r\n \r\nrepeatN 0 m = return []\r\n\r\nrepeatN n m = do\r\n x1 <- m\r\n x2 <- repeatN (n - 1) m\r\n return []\r\n\r\nmain = do\r\n n <- read `fmap` getLine :: IO Int\r\n repeatN n testCase", "positive_code": [{"source_code": "import Control.Monad (forM_)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = fmap (map read . words) getLine\r\n\r\n\r\nmain = do\r\n n <- readLn :: IO Int\r\n forM_\r\n [1 .. n]\r\n ( \\_ -> do\r\n [x, y, z] <- readInts\r\n putStrLn $\r\n if x + y == z || y + z == x || x + z == y\r\n then \"YES\"\r\n else \"NO\"\r\n )"}], "negative_code": [], "src_uid": "1b8293c51d025940eb859b0e625ab588"} {"source_code": "import Data.List\nimport Control.Monad\n\nprocess :: [[Int]] -> Int\nprocess aps =\n let\n sorted = sort aps\n pos = (map (head . tail) $ filter (\\[x,y] -> x > 0) sorted) ++ [0]\n neg = (map (head . tail) . reverse $ filter (\\[x,y] -> x < 0) sorted) ++ [0]\n in sum $ zipWith (+) pos neg\n\nmain = do\n n <- readLn\n aps <- liftM (map (map read . words) . take n . lines) getContents\n putStrLn . show $ process aps", "positive_code": [{"source_code": "import Data.List\nanswer::[(Int,Int)]->Int\nanswer a = (sumData (getLen lsx0 lsx1) sx0) + (sumData (getLen lsx1 lsx0) sx1)\n where (x0,x1) = partition (\\x -> (fst x) < 0) a\n sx0 = sortData (map (\\x-> (negate (fst x),snd x)) x0)\n sx1 = sortData x1\n lsx0 = length sx0\n lsx1 = length sx1\ngetLen::Int -> Int -> Int\ngetLen l0 l1 | l0 == l1 = l0\n | l0 < l1 = l0\n | otherwise = l1+1\nsumData::Int -> [(Int,Int)] -> Int\nsumData 0 a = 0\nsumData n a = (snd (head a)) + (sumData (n-1) (tail a))\nsortData::[(Int,Int)]->[(Int,Int)]\nsortData a = sortBy (\\x y -> compare (fst x) (fst y)) a\nreadInput::Int -> IO [(Int,Int)]\nreadInput 0 = return [] \nreadInput n = do\n winput <- getLine\n let w = words winput\n let x0 = read (w !! 0)::Int\n let x1 = read (w !! 1)::Int\n next <- readInput (n-1)\n return ([(x0,x1)] ++ next)\nmain = do\n w <- getLine\n let n = read w::Int\n a <- readInput n\n print $ answer a\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nimport Control.Monad (replicateM)\nimport Data.List (partition, sortOn)\n\nmain :: IO ()\nmain = do\n n <- read @ Int <$> getLine\n apples <- replicateM n $ (\\[x, y] -> (x, y)) . fmap (read @ Int) . words <$> getLine\n print $ solve n apples\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n apples = maximum [goLeftCount, goRightCount]\n where\n (leftApples, rightApples) = partition ((< 0) . fst) . sortOn fst $ apples\n leftCount = length leftApples\n rightCount = length rightApples\n\n minSide = minimum [leftCount, rightCount]\n\n goLeftCount = gatherApples $ take (minSide + 1) (reverse leftApples) ++ take minSide rightApples\n goRightCount = gatherApples $ take minSide (reverse leftApples) ++ take (minSide + 1) rightApples\n\n\ngatherApples :: [(Int, Int)] -> Int\ngatherApples = sum . fmap snd\n"}, {"source_code": "import Data.List (sort, sortBy)\n\nmain :: IO ()\nmain = print . solve . map (toTuple . map read . words) . tail . lines =<< getContents\n\nsolve :: [(Int, Int)] -> Int\nsolve xas = sum $ zipWith (\\(_, x) (_, y) -> x + y) (sort (filter ((>0) . fst) xas) ++ [(0, 0)]) (sortBy (flip compare) (filter ((<0) . fst) xas) ++ [(0, 0)])\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = do\n n <- fmap read getLine\n trees <- mapM (\\_ -> fmap ((\\[a,b]->(a,b)) . map read . words) getLine) [1..n]\n print $ solve trees\n \nsolve :: [(Int, Int)] -> Int\nsolve trees | l1 == l2 = sum . map snd $ trees\n | l1 < l2 = sum (map snd neg) + sum (map snd (take (l1+1) pos))\n | l1 > l2 = sum (map snd pos) + sum (map snd (take (l2+1) (reverse neg)))\n where sorted = sortBy (compare `on` fst) trees\n (neg, pos) = span (\\(a,_) -> a < 0) sorted\n l1 = length neg\n l2 = length pos\n"}, {"source_code": "import Data.List\n\nfurry (a:_:c) = a:furry c\nfurry (h:_) = [h]\nfurry _ = []\n\nfuck :: [Int] -> String\nfuck (n:s) = let\n li = take (n*2) s\n lu = zip (furry li) $ furry $ tail li\n ze = (0,0)\n in show $ sum $ zipWith (\\(_,x) (_,y) -> x + y) \n ((sort [x | x <- lu, x > ze]) ++ [ze])\n ((reverse $ sort [x | x <- lu, x < ze]) ++ [ze])\n\nmain = getContents >>= putStrLn . fuck . map read . words "}, {"source_code": "import Data.List\n\nmain :: IO ()\n\nfurry :: [Int] -> [Int]\nfurry (a:b:c) = a:furry c\nfurry (h:t) = [h]\nfurry [] = []\n\nfuck :: [Int] -> String\nfuck (n:s) = let\n li = take (n*2) s\n lu = zip (furry li) $ furry $ tail li\n in show $ sum $ zipWith (\\x y -> (snd x) + (snd y)) \n ((sort [x | x <- lu, x > (0,0)]) ++ [(0,0)])\n ((reverse $ sort [x | x <- lu, x < (0,0)]) ++ [(0,0)])\n\nmain = getContents >>= putStrLn . fuck . map (read::String->Int) . words "}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n \nprocess u1 u2 n | abs(length u1 -length u2)<=1 = (length u1, length u2)\n | length u1> length u2 = (length u2+1, length u2)\n | otherwise = (length u1, length u1+1)\n\nmain= do\n\tn<- read <$>getLine :: IO Int\n\ts<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tlet t= sort $ map (\\z->(head z,last z)) s\n\tlet u1 = filter (\\z-> fst z>0) t\n\tlet u2 = reverse $ filter (\\z->fst z <0) t\n\tlet (v1,v2)=process u1 u2 n\n\tlet w1 = sum $ map snd $ take v1 u1\n\tlet w2= sum $ map snd $ take v2 u2\n\tprint $ w1+w2\n\t\n\t\n\n\t \n\t\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nprocess n u | n==u*2 = (0,n)\n | n>u*2 = (n-u-u-1,n)\n\t | otherwise = (0, u+u+1)\n \n\nmain= do\n\tn<- read <$>getLine :: IO Int\n\ts<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tlet t= sort $ map (\\z->(head z,last z)) s\n\tlet u = length $ filter (\\z-> fst z>0) t\n\tlet (v1,v2)=process n u\n\tprint $ sum $ map snd $ take v2 $ drop v1 t\n\n\t\n\t\n\n\t \n\t\n"}, {"source_code": "import Control.Monad\n\nprocess :: [[Int]] -> Int\nprocess aps =\n let\n pos = (map (head . tail) $ filter (\\[x,y] -> x > 0) aps) ++ [0]\n neg = (map (head . tail) $ filter (\\[x,y] -> x < 0) aps) ++ [0]\n in sum $ zipWith (+) pos neg\n\nmain = do\n n <- readLn\n aps <- liftM (map (map read . words) . take n . lines) getContents\n putStrLn . show $ process aps"}], "src_uid": "bf573af345509b2364ada6e613b6f998"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Text.Read\nimport Data.List\n\ndata Pt = Pt { ptX, ptY, ptZ :: !Int } deriving Show\n\ninstance Read Pt where\n readPrec = do\n x <- readPrec :: ReadPrec Int\n y <- readPrec :: ReadPrec Int\n z <- readPrec :: ReadPrec Int\n return $ Pt x y z\n\nmain = do\n n <- read `liftM` getLine\n pos <- replicateM n $ read `liftM` getLine :: IO [Pt]\n\n --putStrLn $ show pos\n\n let o = head pos\n res = foldr (\\p (res, ps) ->\n let po = distance p o\n res' = foldl' (\\res q ->\n let pq = distance p q\n qo = distance q o\n in min ( po + pq + qo ) res\n ) res ps\n in (res', p:ps)\n ) (1e30, []) $ tail pos\n\n putStrLn $ show ( fst res / 2 )\n\nsqr x = x * x\n\ndistance :: Pt -> Pt -> Double\ndistance a b = sqrt $ fromIntegral $ sqr ( ptX a - ptX b ) + sqr ( ptY a - ptY b ) + sqr ( ptZ a - ptZ b )\n", "positive_code": [{"source_code": "import Array\nimport Data.List\nmain = interact solve\nsolve input = output where\n [n]:c:cs = map (map (read::String->Int)) $ map words $ lines input\n output = show $ answer ds / 2\n ds = [(x,dist c x)|x<-cs]\n dist x y = sqrt(\n read ( show $ sum $ map (^2) $ zipWith (-) x y ) ::Double)\n answer [x,y] = distSum x y\n answer (x:xs) = foldl' (min' x) (answer xs) xs\n min' (x,u) a (y,v) = if a<=u+v then a else min a $ distSum (x,u) (y,v)\n distSum (x,u) (y,v) = dist x y + u + v\n"}], "negative_code": [], "src_uid": "71374bd239df13f3345f05eabe4c83c7"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $lines\n >>> drop 1\n >>> map (words >>> map read >>> solve >>> show)\n >>> unlines\n\nsolve :: [Int] -> Int\nsolve [n, s] = s `div` (n `div` 2 + 1)\n", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, s] <- readMany :: IO [Int]\r\n print $ s `div` (n `div` 2 + 1)\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, s] <- getInts 2\n let\n nplaces = div (n + 2) 2\n score = div s nplaces\n pure $ putInts [score]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "0a05b11307fbb2536f868acf4e81c1e2"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Strict\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport Data.Array\nimport Data.Int\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n bounty <- p64\n increase <- p64\n damage <- poi\n es <- replicateM n $ liftM3 Enemy poi poi poi\n eus <- replicateM m $ liftM3 (\\t i h -> (i, Updt t h)) poi poi poi\n return $ show $ solve n bounty increase damage es eus\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n p64 = fmap to64 poi\n int = maybe undefined fst . B.readInt\n\ndata Updt = Updt { ut :: !Int, uh :: !Int } deriving (Show, Eq, Ord)\ndata Enemy = Enemy { emax :: !Int, estart :: !Int, eregen :: !Int } deriving (Show, Eq, Ord)\n\nhi = 2000000000 :: Int\n\nsolve n bounty increase damage es eus0\n | increase > 0 && any (\\(e, us) -> emax e <= damage || eregen e == 0 && uh (last us) <= damage) (zip es eus) = -1\n | otherwise = fst $ M.foldlWithKey (\\(!r, !a) t (e, l) -> (max r $ (to64 a + to64 e) * (bounty + increase * to64 t), a + e - l)) (0, 0 :: Int) delta\n where\n eus = map S.toAscList $ elems $ accumArray (flip S.insert) S.empty (1, n) $ map (\\(i, e) -> (i, Updt 0 (estart e))) (zip [1..] es) ++ eus0\n delta = foldl (\\(!delta) (e, us) -> foldl (\\(!delta) (u, v) -> let dt = min (ut v - ut u - 1) (if eregen e == 0 then hi else (min damage (emax e) - uh u) `quot` eregen e) in M.insertWith pairAdd (ut u) (1 :: Int, 0 :: Int) $ M.insertWith pairAdd (ut u + dt) (0, 1) delta) delta $ filter ((<= damage) . uh . fst) $ zip us $ tail us ++ [Updt hi 0]) M.empty $ zip es eus\n\npairAdd (a, b) (c, d) = (a + c, b + d)\nto64 x = fromIntegral x :: Int64", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport Data.Array\nimport Data.Int\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n bounty <- p64\n increase <- p64\n damage <- poi\n es <- replicateM n $ liftM3 Enemy poi poi poi\n eus <- replicateM m $ liftM3 (\\t i h -> (i, Updt t h)) poi poi poi\n return $ show $ solve n bounty increase damage es eus\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n p64 = fmap to64 poi\n int = maybe undefined fst . B.readInt\n\ndata Updt = Updt { ut :: !Int, uh :: !Int } deriving (Show, Eq, Ord)\ndata Enemy = Enemy { emax :: !Int, estart :: !Int, eregen :: !Int } deriving (Show, Eq, Ord)\n\nhi = 2000000000 :: Int\n\nsolve n bounty increase damage es eus0\n | increase > 0 && any (\\(e, us) -> emax e <= damage || eregen e == 0 && uh (last us) <= damage) (zip es eus) = -1\n | otherwise = fst $ M.foldlWithKey (\\(!r, !a) t (e, l) -> (max r $ (to64 a + to64 e) * (bounty + increase * to64 t), a + e - l)) (0, 0 :: Int) delta\n where\n eus = map S.toAscList $ elems $ accumArray (flip S.insert) S.empty (1, n) $ map (\\(i, e) -> (i, Updt 0 (estart e))) (zip [1..] es) ++ eus0\n delta = foldl (\\(!delta) (e, us) -> foldl (\\(!delta) (u, v) -> let dt = min (ut v - ut u - 1) (if eregen e == 0 then hi else (min damage (emax e) - uh u) `quot` eregen e) in M.insertWith pairAdd (ut u) (1 :: Int, 0 :: Int) $ M.insertWith pairAdd (ut u + dt) (0, 1) delta) delta $ filter ((<= damage) . uh . fst) $ zip us $ tail us ++ [Updt hi 0]) M.empty $ zip es eus\n\npairAdd (a, b) (c, d) = (a + c, b + d)\nto64 x = fromIntegral x :: Int64"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport Data.Array\nimport Data.Int\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n m <- poi\n bounty <- p64\n increase <- p64\n damage <- poi\n es <- replicateM n $ liftM3 Enemy poi poi poi\n eus <- replicateM m $ liftM3 (\\t i h -> (i, Updt t h)) poi poi poi\n return $ show $ solve n bounty increase damage es eus\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n p64 = fmap to64 poi\n int = maybe undefined fst . B.readInt\n\ndata Updt = Updt { ut :: !Int, uh :: !Int } deriving (Show, Eq, Ord)\ndata Enemy = Enemy { emax :: !Int, estart :: !Int, eregen :: !Int } deriving (Show, Eq, Ord)\n\nhi = 2000000000 :: Int\n\nsolve n bounty increase damage es eus0\n | increase > 0 && any (\\(e, us) -> emax e <= damage || eregen e == 0 && uh (last us) <= damage) (zip es eus) = -1\n | otherwise = fst $ M.foldlWithKey (\\(!r, !a) t (e, l) -> (max r $ (to64 a + to64 e) * (bounty + increase * to64 t), a + e - l)) (0, 0 :: Int) delta\n where\n eus = map S.toAscList $ elems $ accumArray (flip S.insert) S.empty (1, n) $ map (\\(i, e) -> (i, Updt 0 (estart e))) (zip [1..] es) ++ eus0\n delta = foldl (\\(!delta) (e, us) -> foldl (\\(!delta) (u, v) -> let dt = min (ut v - ut u - 1) (if eregen e == 0 then hi else (min damage (emax e) - uh u) `quot` eregen e) in M.insertWith pairAdd (ut u) (1 :: Int, 0 :: Int) $ M.insertWith pairAdd (ut u + dt) (0, 1) delta) delta $ filter ((<= damage) . uh . fst) $ zip us $ tail us ++ [Updt hi 0]) M.empty $ zip es eus\n\npairAdd (a, b) (c, d) = (a + c, b + d)\nto64 x = fromIntegral x :: Int64"}], "negative_code": [], "src_uid": "d05b6e11f051aa998296f63e3ecf2612"} {"source_code": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns, TupleSections, FlexibleContexts, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad hiding (forM, forM_, mapM_)\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor\nimport qualified Data.IntMap.Strict as M\nimport qualified Data.Set as S\nimport Data.List hiding (concat, foldl', product, sum, concatMap)\nimport Data.Maybe\nimport Data.Traversable\nimport Text.Printf (printf)\nimport Data.Int\nimport Control.Arrow\n\nimport Prelude hiding (concat, product, sum, mapM_, concatMap)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\n-----\n\n-- type UF = IORef (M.HashMap Int (Int, Int))\ntype UF a = (IOUArray Int Int, IOUArray Int a)\n\nnewUF :: MArray IOUArray a IO => Int -> a -> IO (UF a)\nnewUF n v =\n (,) <$> newListArray (0, n-1) [0..n-1]\n <*> newListArray (0, n-1) (replicate n v)\n\nroot :: MArray IOUArray a IO => UF a -> Int -> IO (Int, a)\nroot (uf, wf) v = do\n p <- readArray uf v\n if p == v\n then (p, ) <$> readArray wf v\n else do\n (r, w) <- root (uf, wf) p\n writeArray uf v r\n return (r, w)\n\nunite :: (MArray IOUArray a IO, Num a) => UF a -> Int -> Int -> IO ()\nunite (uf, wf) v w = do\n (r, m) <- root (uf, wf) v\n (s, n) <- root (uf, wf) w\n writeArray uf r s\n writeArray wf s (m+n)\n\nnubOrd :: Ord a => [a] -> [a]\nnubOrd = S.toList . S.fromList\n\nmain :: IO ()\nmain = do\n [n, _m] <- getInts\n vs <- getInts\n ns' <- readInts <$> C.getContents\n\n let ccc [] = []\n ccc (x:y:z) = (x, y) : ccc z\n\n !es = ccc $ map pred ns'\n -- !g = M.fromListWith (++) [ (f, [t]) | (f, t) <- es ]\n\n g <- newArray (0, n-1) [] :: IO (IOArray Int [Int])\n for_ es $ \\(f, t) -> do\n writeArray g f . (t:) =<< readArray g f\n writeArray g t . (f:) =<< readArray g t\n\n uf <- newUF n (1 :: Int)\n ss <- newArray (0, n-1) False :: IO (IOUArray Int Bool)\n\n let ws = sortBy (flip compare) $ zip vs [0..]\n\n f !acc (v, ix) = do\n us' <- readArray g ix\n us <- filterM (readArray ss) us'\n rs <- forM us $ \\u ->\n root uf u\n\n forM_ us $ \\u -> do\n (r1, _n1) <- root uf ix\n (r2, _n2) <- root uf u\n when (r1 /= r2) $ unite uf u ix\n\n let sums = tail $ scanr (+) 0 ns\n\n go [] _ !acc = acc\n go (x:xs) (y:ys) !acc = go xs ys (acc + x * y)\n\n !ns = map (fromIntegral . snd) $ nubOrd rs\n\n writeArray ss ix True\n return $! acc + v * (sum ns + go ns sums 0)\n\n ans <- foldM f (0 :: Double) $ map (first fromIntegral) ws\n\n printf \"%.10f\\n\" (ans / fromIntegral n / fromIntegral (n-1) * 2 :: Double)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad hiding (forM, forM_, mapM_)\nimport Data.Array.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable\nimport Data.Function\nimport Data.Int\nimport Data.List hiding (concat, concatMap, foldl',\n product, sum)\nimport Data.Maybe\nimport qualified Data.Set as S\nimport Data.Traversable\nimport Text.Printf (printf)\n\nimport Prelude hiding (concat, concatMap, mapM_,\n product, sum)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\n-----\n\ntype UnionFind = IOArray Int (Int, Int)\n\nnewUF :: Int -> IO UnionFind\nnewUF n = newListArray (0, n-1) $ map (,1) [0..n-1]\n\nroot :: UnionFind -> Int -> IO (Int, Int)\nroot uf v = do\n (p, _) <- readArray uf v\n if p == v\n then readArray uf v\n else do\n (r, w) <- root uf p\n writeArray uf v (r, w)\n return (r, w)\n\nunite :: UnionFind -> Int -> Int -> IO ()\nunite uf v w = do\n (r, m) <- root uf v\n (s, n) <- root uf w\n writeArray uf r (s, m+n)\n writeArray uf s (s, m+n)\n\nnubOrd :: Ord a => [a] -> [a]\nnubOrd = S.toList . S.fromList\n\nmain :: IO ()\nmain = do\n [n, _m] <- getInts\n vs <- getInts\n ns' <- readInts <$> C.getContents\n\n let ccc [] = []\n ccc (x:y:z) = (x, y) : ccc z\n\n !es = ccc $ map pred ns'\n -- !g = M.fromListWith (++) [ (f, [t]) | (f, t) <- es ]\n\n g <- newArray (0, n-1) [] :: IO (IOArray Int [Int])\n for_ es $ \\(f, t) -> do\n writeArray g f . (t:) =<< readArray g f\n writeArray g t . (f:) =<< readArray g t\n\n uf <- newUF n\n ss <- newArray (0, n-1) False :: IO (IOUArray Int Bool)\n\n let ws = sortBy (flip compare) $ zip vs [0..]\n\n f !acc (v, ix) = do\n us' <- readArray g ix\n us <- filterM (readArray ss) us'\n rs <- forM us $ \\u ->\n root uf u\n\n forM_ us $ \\u -> do\n (r1, _n1) <- root uf ix\n (r2, _n2) <- root uf u\n when (r1 /= r2) $ unite uf u ix\n\n let sums = tail $ scanr (+) 0 ns\n\n go [] _ !acc = acc\n go (x:xs) (y:ys) !acc = go xs ys (acc + x * y)\n\n !ns = map (fromIntegral . snd) $ nubOrd rs\n\n writeArray ss ix True\n return $! acc + v * (sum ns + go ns sums 0)\n\n ans <- foldM f (0 :: Double) $ map (first fromIntegral) ws\n\n printf \"%.10f\\n\" (ans / fromIntegral n / fromIntegral (n-1) * 2 :: Double)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Control.Applicative\nimport Control.Monad hiding (forM, forM_, mapM_)\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List hiding (concat, concatMap, foldl',\n product, sum)\nimport Data.Maybe\nimport qualified Data.Set as S\nimport Text.Printf (printf)\n\nimport Prelude hiding (concat, concatMap, mapM_,\n product, sum)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\n-----\n\ntype UF = IOUArray Int Int\n\nnewUF :: Int -> IO UF\nnewUF n = newListArray (0, n-1) [0..n-1]\n\nroot :: UF -> Int -> IO Int\nroot uf v = do\n p <- readArray uf v\n if p == v\n then readArray uf v\n else do\n r <- root uf p\n writeArray uf v r\n return r\n\nunite :: UF -> Int -> Int -> IO ()\nunite uf v w = do\n r <- root uf v\n s <- root uf w\n writeArray uf r s\n\nnubOrd :: Ord a => [a] -> [a]\nnubOrd = S.toList . S.fromList\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n vs :: UArray Int Int <- listArray (0, n-1) <$> getInts\n es <- replicateM m getInts\n\n uf <- newUF n\n sz :: IOUArray Int Int <- newArray (0, n) (1 :: Int)\n\n let f !acc [v, u] = do\n rv <- root uf v\n ru <- root uf u\n if rv == ru\n then return acc\n else do\n unite uf v u\n sv <- readArray sz rv\n su <- readArray sz ru\n rr <- root uf v\n writeArray sz rr $ su + sv\n return $ acc + fromIntegral (min (vs!v) (vs!u)) * fromIntegral su * fromIntegral sv\n\n ans <- foldM f (0 :: Double)\n $ sortBy (flip compare `on` \\[v, u] -> min (vs!v) (vs!u))\n $ map (map pred) es\n\n printf \"%.10f\\n\" (ans / fromIntegral n / fromIntegral (n-1) * 2 :: Double)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies, ViewPatterns, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad hiding (forM, forM_)\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor\nimport Data.Maybe\nimport Data.Traversable\nimport Text.Printf (printf)\nimport Data.List hiding (concat, foldl', sum, product)\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport qualified Data.IntSet as S\n\nimport Prelude hiding (sum, product, concat)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\n-----\n\ntype UF = IORef (M.IntMap (Int, Integer))\n\nnewUF :: Int -> IO UF\nnewUF n = newIORef $ M.fromList [ (i, (i, 1)) | i <- [0..n-1] ]\n\nroot :: UF -> Int -> IO (Int, Integer)\nroot ior v = do\n uf <- readIORef ior\n let (p, n) = uf M.! v\n if p == v\n then return (p, n)\n else do\n r <- root ior p\n writeIORef ior $! M.insert v r uf\n return r\n\nunite :: UF -> Int -> Int -> IO ()\nunite ior v w = do\n (r, m) <- root ior v\n (s, n) <- root ior w\n modifyIORef' ior $ M.insert s (s, m+n) . M.insert r (s, m+n)\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n vs <- getInts\n (concat -> cs) <- replicateM m $ do\n [f, t] <- getInts\n return [(f-1, t-1), (t-1, f-1)]\n\n let g = M.fromList $ map (\\xs -> (fst $ head xs, map snd xs)) $ groupBy ((==) `on` fst) $ sort cs\n uf <- newUF n\n\n let ws = sortBy (flip compare) $ zip vs [0..]\n\n f (!ss, !acc) (v, ix) = do\n let us = M.findWithDefault [] ix g\n (map snd . nub -> ns) <- forM (filter (`S.member` ss) us) $ \\u ->\n root uf u\n print (v, ix, us, ss, ns)\n\n for_ (filter (`S.member` ss) us) $ \\u -> do\n (r1, n1) <- root uf ix\n (r2, n2) <- root uf u\n when (r1 /= r2) $ unite uf u ix\n\n let go [] = 0\n go (x:xs) = x * sum xs + go xs\n\n return (S.insert ix ss, acc + fromIntegral v * (sum ns + go ns))\n\n (_, ans) <- foldM f (S.empty, 0) ws\n\n printf \"%.10f\\n\" $\n ((fromIntegral (ans :: Integer) / fromIntegral n / fromIntegral (n-1) * 2) :: Double)\n"}, {"source_code": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad hiding (forM, forM_, mapM_)\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor\nimport qualified Data.IntMap.Strict as M\nimport qualified Data.IntSet as S\nimport Data.IORef\nimport Data.List hiding (concat, foldl', product, sum)\nimport Data.Maybe\nimport Data.Traversable\nimport Text.Printf (printf)\n\nimport Prelude hiding (concat, product, sum, mapM_)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\n-----\n\n-- type UF = IORef (M.HashMap Int (Int, Int))\ntype UF = (IOUArray Int Int, IOUArray Int Int)\n\nnewUF :: Int -> IO UF\nnewUF n = (,) <$> newListArray (0, n-1) [0..n-1]\n <*> newListArray (0, n-1) (replicate n 1)\n\nroot :: UF -> Int -> IO (Int, Int)\nroot (uf, wf) v = do\n p <- readArray uf v\n if p == v\n then (p, ) <$> readArray wf v\n else do\n (r, w) <- root (uf, wf) p\n writeArray uf v r\n return (r, w)\n\nunite :: UF -> Int -> Int -> IO ()\nunite (uf, wf) v w = do\n (r, m) <- root (uf, wf) v\n (s, n) <- root (uf, wf) w\n writeArray uf r s\n writeArray wf s (m+n)\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n vs <- getInts\n (concat -> cs) <- replicateM m $ do\n [f, t] <- getInts\n return [(f-1, t-1), (t-1, f-1)]\n\n let g = M.fromList $ map (\\xs -> (fst $ head xs, map snd xs)) $ groupBy ((==) `on` fst) $ sort cs\n\n uf <- newUF n\n ssr <- newIORef S.empty\n ansr <- newIORef 0\n\n let ws = sortBy (flip compare) $ zip vs [0..]\n\n f (v, ix) = do\n ss <- readIORef ssr\n let us = filter (`S.member` ss) $ M.findWithDefault [] ix g\n (map snd . nub -> ns) <- forM us $ \\u ->\n root uf u\n -- print (v, ix, us, ss, ns)\n\n for_ us $ \\u -> do\n (r1, _n1) <- root uf ix\n (r2, _n2) <- root uf u\n when (r1 /= r2) $ unite uf u ix\n\n let go [] = 0\n go (x:xs) = x * sum xs + go xs\n\n modifyIORef' ssr $ S.insert ix \n modifyIORef' ansr (+ fromIntegral v * fromIntegral (sum ns + go ns))\n\n mapM_ f ws\n ans <- readIORef ansr\n\n printf \"%.10f\\n\" (ans / fromIntegral n / fromIntegral (n-1) * 2 :: Double)\n"}, {"source_code": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad hiding (forM, forM_, mapM_)\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable\nimport Data.Function\nimport Data.Functor\nimport qualified Data.IntMap.Strict as M\nimport qualified Data.IntSet as S\nimport Data.IORef\nimport Data.List hiding (concat, foldl', product, sum)\nimport Data.Maybe\nimport Data.Traversable\nimport Text.Printf (printf)\n\nimport Prelude hiding (concat, product, sum, mapM_)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\n-----\n\n-- type UF = IORef (M.HashMap Int (Int, Int))\ntype UF = (IOUArray Int Int, IOUArray Int Int)\n\nnewUF :: Int -> IO UF\nnewUF n = (,) <$> newListArray (0, n-1) [0..n-1]\n <*> newListArray (0, n-1) (replicate n 1)\n\nroot :: UF -> Int -> IO (Int, Int)\nroot (uf, wf) v = do\n p <- readArray uf v\n if p == v\n then (p, ) <$> readArray wf v\n else do\n (r, w) <- root (uf, wf) p\n writeArray uf v r\n return (r, w)\n\nunite :: UF -> Int -> Int -> IO ()\nunite (uf, wf) v w = do\n (r, m) <- root (uf, wf) v\n (s, n) <- root (uf, wf) w\n writeArray uf r s\n writeArray wf s (m+n)\n\nmain :: IO ()\nmain = do\n [n, m] <- getInts\n vs <- getInts\n (concat -> cs) <- replicateM m $ do\n [f, t] <- getInts\n return [(f-1, t-1), (t-1, f-1)]\n\n let g = M.fromList $ map (\\xs -> (fst $ head xs, map snd xs)) $ groupBy ((==) `on` fst) $ sort cs\n\n uf <- newUF n\n ssr <- newIORef S.empty\n ansr <- newIORef 0\n\n let ws = sortBy (flip compare) $ zip vs [0..]\n\n f (v, ix) = do\n ss <- readIORef ssr\n let us = filter (`S.member` ss) $ M.findWithDefault [] ix g\n (map snd . nub -> ns) <- forM us $ \\u ->\n root uf u\n -- print (v, ix, us, ss, ns)\n\n for_ us $ \\u -> do\n (r1, _n1) <- root uf ix\n (r2, _n2) <- root uf u\n when (r1 /= r2) $ unite uf u ix\n\n let go [] = 0\n go (x:xs) = x * sum xs + go xs\n\n modifyIORef' ssr $ S.insert ix \n modifyIORef' ansr (+ fromIntegral v * fromIntegral (sum ns + go ns))\n\n mapM_ f ws\n ans <- readIORef ansr\n\n printf \"%.10f\\n\" (fromIntegral (ans :: Integer) / fromIntegral n / fromIntegral (n-1) * 2 :: Double)\n"}], "src_uid": "6931beaa1c40e03ee52bcb0cfb9bff51"} {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\nimport Data.Array.IO\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot::Int,\n values:: IOArray Int Int,\n eIntvs::IntMap (IntMap Intv),\n bIntvs::IOArray Int (Maybe (Int,Intv))\n } \n\n\ntype LotState a = StateT Env IO a\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs \n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get \n lift $ writeArray (values s) v pos \n\ntakeValue v = do\n s <- get\n let curValues = values s \n pos <- lift $ readArray curValues v\n return pos \n\n\ndeleteInEIntvs b e = do\n env <- get\n let curEIntvs = eIntvs env\n let bInf = getInf b\n let bSup = getSup b\n \n lift $ writeArray (bIntvs env) bInf Nothing\n lift $ writeArray (bIntvs env) bSup Nothing\n \n let intvs = curEIntvs ! e\n let newIntvs = delete bInf intvs\n if (null newIntvs)\n then put $ env {eIntvs = delete e curEIntvs} \n else put $ env {eIntvs = insert e newIntvs curEIntvs}\n \ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n\nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n \ndeleteBIntvs b = do\n s <- get\n lift $ writeArray (bIntvs s) b Nothing\n\ninsertBIntvs b v = do\n s <- get\n lift $ writeArray (bIntvs s) b (Just v)\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (intv,newIntvs) = deleteFindMin maxIntvs\n let minBInf = getInf intv\n let minBSup = getSup intv\n\n deleteBIntvs minBInf\n deleteBIntvs minBSup\n\n let sz = sizeLot s\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcEcart bInf (pos-1)\n let eSecond = calcEcart (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let bSup = getSup v \n let curEIntvs = eIntvs s \n insertBIntvs bInf (e,v) \n insertBIntvs bSup (e,v) \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n let curBIntvs = bIntvs env\n\n mBinf <- if (p==1)\n then return Nothing\n else lift $ readArray curBIntvs (p-1)\n\n let bInf = fromMaybe BNotFound (mBinf >>= return.BIntv)\n\n mBintvSup <- if(p==sz) \n then return Nothing\n else lift $ readArray curBIntvs (p+1)\n\n let bSup = fromMaybe BNotFound (mBintvSup >>= return.BIntv) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs iInf eInf\n deleteInEIntvs iSup eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs iInf eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs iSup eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = do\n values <- newArray (1,1000000) 0\n bIntvs <- newArray (1,n) Nothing\n writeArray bIntvs 1 $ Just ((n-1),(Intv 1 n))\n return $ Env {sizeLot=n,\n values = values,\n bIntvs = bIntvs, \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = do\n env <- initEnv n\n evalStateT (manage nbActs) env\n\n\n\nmanage 0 = return ()\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n (lift $ print pos) >> manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n", "positive_code": [{"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\nimport Data.Array.IO\nimport Data.Array.Unboxed hiding ((!))\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot:: Int,\n values:: IOUArray Int Int,\n eIntvs:: IntMap (IntMap Intv),\n bInfs:: IOUArray Int Int,\n bSups:: IOUArray Int Int\n } \n\n\ntype LotState a = StateT Env IO a\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs \n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get \n lift $ writeArray (values s) v pos \n\ntakeValue v = do\n s <- get\n let curValues = values s \n pos <- lift $ readArray curValues v\n return pos \n\n\ndeleteInEIntvs b e = do\n env <- get\n let curEIntvs = eIntvs env\n let bInf = getInf b\n let bSup = getSup b\n \n --lift $ writeArray (bIntvs env) bInf Nothing\n --lift $ writeArray (bIntvs env) bSup Nothing\n \n lift $ writeArray (bInfs env) bInf (-1)\n lift $ writeArray (bSups env) bSup (-1)\n \n let intvs = curEIntvs ! e\n let newIntvs = delete bInf intvs\n if (null newIntvs)\n then put $ env {eIntvs = delete e curEIntvs} \n else put $ env {eIntvs = insert e newIntvs curEIntvs}\n \ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n\nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n \ndeleteBIntvs (Intv bInf bSup)= do\n s <- get\n lift $ writeArray (bInfs s) bInf (-1)\n lift $ writeArray (bSups s) bSup (-1)\n\ninsertBIntvs (Intv bInf bSup) = do\n s <- get\n --lift $ writeArray (bIntvs s) b (Just v)\n lift $ writeArray (bInfs s) bInf bSup\n lift $ writeArray (bSups s) bSup bInf\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n --let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (intv,newIntvs) = deleteFindMin maxIntvs\n --let minBInf = getInf intv\n --let minBSup = getSup intv\n\n deleteBIntvs intv \n\n let sz = sizeLot s\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (sz-2) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcE 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcE bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcE bInf (pos-1)\n let eSecond = calcE (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n where calcE bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ncalcEcart bInf bSup = do\n s <- get\n let sz = sizeLot s\n case (bInf,bSup) of\n (1,bS) | (bS==sz) -> return (sz)\n (1,bS) -> return (bS-1)\n (bI,bS) | (bS==sz) -> return (sz-bI)\n (bI,bS) | (bI==bS) -> return 0\n otherwise -> return $ truncate $ (diff bInf bSup) / 2\n where diff bInf bSup = fromIntegral $ bSup-bInf\n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let bSup = getSup v \n let curEIntvs = eIntvs s \n insertBIntvs v \n insertBIntvs v \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) | ( b==sz) -> b\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n --let curBIntvs = bIntvs env\n let curBInfs = bInfs env\n let curBSups = bSups env\n\n mBinf <- if (p==1)\n then return Nothing\n else do \n bInfinf <- lift $ readArray curBSups (p-1)\n if (bInfinf<0)\n then return Nothing\n else do\n e <- calcEcart bInfinf (p-1)\n return $ Just $ BIntv (e,(Intv bInfinf (p-1)))\n\n let bInf = fromMaybe BNotFound mBinf -- >>= return.BIntv)\n\n mBintvSup <- if(p==sz) \n then return Nothing\n else do\n bSupsup <- lift $ readArray curBInfs (p+1)\n if (bSupsup<0)\n then return Nothing\n else do\n e <- calcEcart (p+1) bSupsup\n return $ Just $ BIntv (e, (Intv (p+1) bSupsup))\n\n let bSup = fromMaybe BNotFound mBintvSup -- >>= return.BIntv) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs iInf eInf\n deleteInEIntvs iSup eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs iInf eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs iSup eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = do\n values <- newArray (1,1000000) 0\n --bIntvs <- newArray (1,n) Nothing\n bInfs <- newArray (1,n) (-1)\n bSups <- newArray (1,n) (-1)\n writeArray bInfs 1 n\n writeArray bSups n 1\n return $ Env {sizeLot=n,\n values = values,\n bInfs = bInfs, \n bSups = bSups, \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = do\n env <- initEnv n\n evalStateT (manage nbActs) env\n\n\n\nmanage 0 = return ()\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n (lift $ print pos) >> manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\nimport Data.Array.IO\nimport Data.Array.Unboxed hiding ((!))\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot::Int,\n values:: IOUArray Int Int,\n eIntvs::IntMap (IntMap Intv),\n bIntvs::IOArray Int (Maybe (Int,Intv))\n } \n\n\ntype LotState a = StateT Env IO a\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs \n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get \n lift $ writeArray (values s) v pos \n\ntakeValue v = do\n s <- get\n let curValues = values s \n pos <- lift $ readArray curValues v\n return pos \n\n\ndeleteInEIntvs b e = do\n env <- get\n let curEIntvs = eIntvs env\n let bInf = getInf b\n let bSup = getSup b\n \n lift $ writeArray (bIntvs env) bInf Nothing\n lift $ writeArray (bIntvs env) bSup Nothing\n \n let intvs = curEIntvs ! e\n let newIntvs = delete bInf intvs\n if (null newIntvs)\n then put $ env {eIntvs = delete e curEIntvs} \n else put $ env {eIntvs = insert e newIntvs curEIntvs}\n \ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n\nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n \ndeleteBIntvs b = do\n s <- get\n lift $ writeArray (bIntvs s) b Nothing\n\ninsertBIntvs b v = do\n s <- get\n lift $ writeArray (bIntvs s) b (Just v)\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (intv,newIntvs) = deleteFindMin maxIntvs\n let minBInf = getInf intv\n let minBSup = getSup intv\n\n deleteBIntvs minBInf\n deleteBIntvs minBSup\n\n let sz = sizeLot s\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcEcart bInf (pos-1)\n let eSecond = calcEcart (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let bSup = getSup v \n let curEIntvs = eIntvs s \n insertBIntvs bInf (e,v) \n insertBIntvs bSup (e,v) \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n let curBIntvs = bIntvs env\n\n mBinf <- if (p==1)\n then return Nothing\n else lift $ readArray curBIntvs (p-1)\n\n let bInf = fromMaybe BNotFound (mBinf >>= return.BIntv)\n\n mBintvSup <- if(p==sz) \n then return Nothing\n else lift $ readArray curBIntvs (p+1)\n\n let bSup = fromMaybe BNotFound (mBintvSup >>= return.BIntv) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs iInf eInf\n deleteInEIntvs iSup eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs iInf eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs iSup eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = do\n values <- newArray (1,1000000) 0\n bIntvs <- newArray (1,n) Nothing\n writeArray bIntvs 1 $ Just ((n-1),(Intv 1 n))\n return $ Env {sizeLot=n,\n values = values,\n bIntvs = bIntvs, \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = do\n env <- initEnv n\n evalStateT (manage nbActs) env\n\n\n\nmanage 0 = return ()\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n (lift $ print pos) >> manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Monad\n-- import Control.Monad.ST\n-- import Data.Array.ST\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as C\n\ndata Interval = Interval {\n begin :: !Int,\n end :: !Int,\n spacing :: !Int\n }\n deriving (Show, Eq)\n\ninterval n (l, r) = Interval l r m\n where\n m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2\n\ninstance Ord Interval where\n compare a b =\n case compare (spacing a) (spacing b) of\n LT -> GT\n EQ -> compare (begin a) (begin b)\n GT -> LT\n\n{-\ndata State s = State {\n size :: Int,\n free :: S.Set Interval,\n l2r :: STUArray s Int Int,\n r2l :: STUArray s Int Int,\n pos :: STUArray s Int Int\n }\n-}\ndata State = State {\n size :: Int,\n free :: S.Set Interval,\n l2r :: IOUArray Int Int,\n r2l :: IOUArray Int Int,\n pos :: IOUArray Int Int\n }\n\ntop s = return (l, r, center)\n where\n (Interval l r m) = S.findMin $ free s\n center\n | l == 0 = l\n | r == size s = r - 1\n | otherwise = (l + r - 1) `div` 2\n\nempty n = do\n l2r <- newArray (0, n) $ -1 -- :: ST s (STUArray s Int Int)\n r2l <- newArray (0, n) $ -1\n pos <- newArray (0, 10^6) $ -1\n return $ State n S.empty l2r r2l pos\n\ninsert (l, r) s = do\n if l >= r\n then return s\n else do\n writeArray (l2r s) l r\n writeArray (r2l s) r l\n return s{free = S.insert (interval (size s) (l, r)) $ free s}\n\ndelete (l, r) s = do\n writeArray (l2r s) l $ -1\n writeArray (r2l s) r $ -1\n return s{free = S.delete (interval (size s) (l, r)) $ free s}\n\ngao s [] =\n return []\n\ngao s (1:k:q) = do\n (l, r, p) <- top s\n s <- delete (l, r) s\n s <- insert (l, p) s\n s <- insert (p + 1, r) s\n writeArray (pos s) k p\n ps <- gao s q\n return $ p: ps\n\ngao s (2:k:q) = do\n p <- readArray (pos s) k\n l' <- readArray (r2l s) p\n (l, s) <-\n if l' == -1\n then return (p, s)\n else do\n s <- delete (l', p) s\n return (l', s)\n r' <- readArray (l2r s) (p + 1)\n (r, s) <-\n if r' == -1\n then return (p + 1, s)\n else do\n s <- delete (p + 1, r') s\n return (r', s)\n s <- insert (l, r) s\n writeArray (pos s) k $ -1\n gao s q\n\nsolve n q = do\n s <- empty n\n s <- insert (0, n) s\n gao s q\n\nmain = do\n (n:m:q) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n ans <- solve n q\n putStr $ unlines $ map (show . succ) $ ans {- runST $ solve n q -}\n\n{-\nIOUArray:\n watashi-laptop:\n ./E3 < E.in > E.out 1.09s user 0.04s system 92% cpu 1.226 total\n acm90:\n real\t0m6.047s\n user\t0m5.976s\n sys\t0m0.072s\nSTUArray:\n watashi-laptop:\n ./E3 < E.in > E.out 1.79s user 0.08s system 90% cpu 2.057 total\n acm90:\n real\t0m7.916s\n user\t0m7.868s\n sys\t0m0.040s\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\ndata Interval = Interval {\n begin :: !Int,\n end :: !Int,\n spacing :: !Int\n }\n deriving (Show, Eq)\n\ninterval n (l, r) = Interval l r m\n where\n m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2\n\ninstance Ord Interval where\n compare a b =\n case compare (spacing a) (spacing b) of\n LT -> GT\n EQ -> compare (begin a) (begin b)\n GT -> LT\n\ndata State = State {\n size :: Int,\n free :: S.Set Interval,\n l2r :: M.IntMap Int,\n r2l :: M.IntMap Int,\n pos :: M.IntMap Int\n }\n deriving (Show)\n\ntop s = (l, r, center)\n where\n (Interval l r m) = S.findMin $ free s\n center\n | l == 0 = l\n | r == size s = r - 1\n | otherwise = (l + r - 1) `div` 2\n\nfindByL l s = M.findWithDefault (-1) l $ l2r s\n\nfindByR r s = M.findWithDefault (-1) r $ r2l s\n\nfindById k = fromJust . M.lookup k . pos\n\ndelete (l, r) s@(State n sf ml mr _) = s {\n free = S.delete (interval n (l, r)) sf,\n l2r = M.delete l ml,\n r2l = M.delete r mr\n }\n\ninsert (l, r) s@(State n sf ml mr _)\n | l >= r = s\n | otherwise = s {\n free = S.insert (interval n (l, r)) sf,\n l2r = M.insert l r ml,\n r2l = M.insert r l mr\n }\n\ngao s [] = []\n\ngao s (1:k:q) = p: gao s'{ pos = M.insert k p $ pos s' } q\n where\n (l, r, p) = top s\n s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s\n\ngao s (2:k:q) = gao s'{ pos = M.delete k $ pos s' } q\n where\n p = findById k s\n (l, sl) =\n case findByR p s of\n -1 -> (p, s)\n l -> (l, delete (l, p) s)\n (r, sr) =\n case findByL (p + 1) sl of\n -1 -> (p + 1, sl)\n r -> (r, delete (p + 1, r) sl)\n s' = insert (l, r) sr\n\nmain = do\n (n:m:q) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStr $ unlines $ map (show . succ) $ gao (empty n) q\n where\n empty n = State {\n size = n,\n free = S.singleton $ interval n (0, n),\n l2r = M.singleton 0 n,\n r2l = M.singleton n 0,\n pos = M.empty\n }"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\ndata Interval = Interval {\n begin :: !Int,\n end :: !Int,\n spacing :: !Int\n }\n deriving (Show, Eq)\n\ninterval n (l, r) = Interval l r m\n where\n m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2\n\ninstance Ord Interval where\n compare a b =\n case compare (spacing a) (spacing b) of\n LT -> GT\n EQ -> compare (begin a) (begin b)\n GT -> LT\n\ndata State = State {\n size :: Int,\n free :: S.Set Interval,\n l2r :: M.IntMap Int,\n r2l :: M.IntMap Int,\n pos :: M.IntMap Int\n }\n deriving (Show)\n\ntop s = (l, r, center)\n where\n (Interval l r m) = S.findMin $ free s\n center\n | l == 0 = l\n | r == size s = r - 1\n | otherwise = (l + r - 1) `div` 2\n\nfindByL l s = M.findWithDefault (-1) l $ l2r s\n\nfindByR r s = M.findWithDefault (-1) r $ r2l s\n\nfindById k = fromJust . M.lookup k . pos\n\ndelete (l, r) s@(State n sf ml mr _) = s {\n free = S.delete (interval n (l, r)) sf,\n l2r = M.delete l ml,\n r2l = M.delete r mr\n }\n\ninsert (l, r) s@(State n sf ml mr _)\n | l >= r = s\n | otherwise = s {\n free = S.insert (interval n (l, r)) sf,\n l2r = M.insert l r ml,\n r2l = M.insert r l mr\n }\n\ngao s [] = []\n\ngao s (1:k:q) = p: gao s'{ pos = M.insert k p $ pos s' } q\n where\n (l, r, p) = top s\n s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s\n\ngao s (2:k:q) = gao s'{ pos = M.delete k $ pos s' } q\n where\n p = findById k s\n (l, sl) =\n case findByR p s of\n -1 -> (p, s)\n l -> (l, delete (l, p) s)\n (r, sr) =\n case findByL (p + 1) sl of\n -1 -> (p + 1, sl)\n r -> (r, delete (p + 1, r) sl)\n s' = insert (l, r) sr\n\nmain = do\n (n:m:q) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStr $ unlines $ map (show . succ) $ gao (empty n) q\n where\n empty n = State {\n size = n,\n free = S.singleton $ interval n (0, n),\n l2r = M.singleton 0 n,\n r2l = M.singleton n 0,\n pos = M.empty\n }\n\n{-\nwatashi-laptop:\n ./E1 < E.in > E.out 2.60s user 0.08s system 87% cpu 3.053 total\nacm90:\n real\t0m5.263s\n user\t0m5.200s\n sys\t0m0.064s\n-}\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\ndata Interval = Interval {\n begin :: !Int,\n end :: !Int,\n spacing :: !Int\n }\n deriving (Show, Eq)\n\ninterval n (l, r) = Interval l r m\n where\n m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2\n\ninstance Ord Interval where\n compare a b =\n case compare (spacing a) (spacing b) of\n LT -> GT\n EQ -> compare (begin a) (begin b)\n GT -> LT\n\ndata State = State {\n size :: Int,\n free :: S.Set Interval,\n l2r :: M.IntMap Int,\n r2l :: M.IntMap Int,\n pos :: M.IntMap Int\n }\n deriving (Show)\n\ntop s = (l, r, center)\n where\n (Interval l r m) = S.findMin $ free s\n center\n | l == 0 = l\n | r == size s = r - 1\n | otherwise = (l + r - 1) `div` 2\n\nfindByL l s = M.findWithDefault (-1) l $ l2r s\n\nfindByR r s = M.findWithDefault (-1) r $ r2l s\n\nfindById k = fromJust . M.lookup k . pos\n\ndelete (l, r) s@(State n sf ml mr _) = s {\n free = S.delete (interval n (l, r)) sf,\n l2r = M.delete l ml,\n r2l = M.delete r mr\n }\n\ninsert (l, r) s@(State n sf ml mr _)\n | l >= r = s\n | otherwise = s {\n free = S.insert (interval n (l, r)) sf,\n l2r = M.insert l r ml,\n r2l = M.insert r l mr\n }\n\ngao s [] = []\n\ngao s ([1,k]:q) = p: gao s'{ pos = M.insert k p $ pos s' } q\n where\n (l, r, p) = top s\n s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s\n\ngao s ([2,k]:q) = gao s'{ pos = M.delete k $ pos s' } q\n where\n p = findById k s\n (l, sl) =\n case findByR p s of\n -1 -> (p, s)\n l -> (l, delete (l, r) s)\n (r, sr) =\n case findByL (p + 1) sl of\n -1 -> (p + 1, sl)\n r -> (r, delete (l, r) sl)\n s' = insert (l, r) sr\n\nmain = do\n [n, m] <- getArray\n q <- replicateM m getArray\n putStr $ unlines $ map (show . succ) $ gao (empty n) q\n where\n getArray = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n empty n = State {\n size = n,\n free = S.singleton $ interval n (0, n),\n l2r = M.singleton 0 n,\n r2l = M.singleton n 0,\n pos = M.empty\n }\n\n"}, {"source_code": "import Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport qualified Data.Set as S\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\ndata Interval = Interval {\n range :: (Int, Int),\n spacing :: Int\n }\n deriving (Show, Eq)\n\ninterval n (l, r) = Interval (l, r) m\n where\n m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2\n\ncenter n (Interval (l, r) _)\n | l == 0 = l\n | r == n = r - 1\n | otherwise = (l + r - 1) `div` 2\n\ninstance Ord Interval where\n compare = comparing (\\i -> (negate $ spacing i, range i))\n\ndata State = State {\n size :: Int,\n free :: S.Set Interval,\n l2r :: M.IntMap Int,\n r2l :: M.IntMap Int,\n pos :: M.IntMap Int\n }\n\ntop s = (range interval, center (size s) interval)\n where\n interval = S.findMin $ free s\n\nfindByL l s = do\n r <- M.lookup l $ l2r s\n return (l, r)\n\nfindByR r s = do\n l <- M.lookup r $ r2l s\n return (l, r)\n\nfindById k = fromJust . M.lookup k . pos\n\ndelete (l, r) s@(State n sf ml mr _) = s {\n free = S.delete (interval n (l, r)) sf,\n l2r = M.delete l ml,\n r2l = M.delete r mr\n }\n\ninsert (l, r) s@(State n sf ml mr _)\n | l >= r = s\n | otherwise = s {\n free = S.insert (interval n (l, r)) sf,\n l2r = M.insert l r ml,\n r2l = M.insert r l mr\n }\n\ngao s [] = []\n\ngao s ([1,k]:q) = p: gao s'{ pos = M.insert k p $ pos s' } q\n where\n ((l, r), p) = top s\n s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s\n\ngao s ([2,k]:q) = gao s'{ pos = M.delete k $ pos s' } q\n where\n p = findById k s\n (l, sl) =\n case findByR p s of\n Just (l, r) -> (l, delete (l, r) s)\n Nothing -> (p, s)\n (r, sr) =\n case findByL (p + 1) sl of\n Just (l, r) -> (r, delete (l, r) sl)\n Nothing -> (p + 1, sl)\n s' = insert (l, r) s\n\nmain = do\n [n, m] <- getArray\n q <- replicateM m getArray\n putStr $ unlines $ map (show . succ) $ gao (empty n) q\n where\n getArray = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n empty n = State {\n size = n,\n free = S.singleton $ interval n (0, n),\n l2r = M.singleton 0 n,\n r2l = M.singleton n 0,\n pos = M.empty\n }\n\n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot::Int,\n values::IntMap Int,\n eIntvs::IntMap (IntMap Intv),\n bIntvs::IntMap (Int,Intv)\n } deriving Show\n\n\ntype LotState a = StateT Env IO a\n\ndata Pos = Pos Int Int | None deriving Show\n\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get\n put $ s {values = insert v pos $ values s} \n\ntakeValue v = do\n s <- get\n let curValues = values s \n let pos = curValues ! v \n --put $ s {values = delete v curValues}\n return pos \n\n\ndeleteInEIntvs bInf e = do\n env <- get\n let curEIntvs = eIntvs env\n let newBIntvs = delete bInf $ bIntvs env\n let intvs = curEIntvs ! e\n let newIntvs = delete bInf intvs\n if (null newIntvs)\n then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs} \n else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs} \n \nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n\ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n \nupdateBIntvs m = do \n s <- get\n put $ s {bIntvs = m}\n\ninsertBIntvs bInf v = do\n s <- get\n put s {bIntvs = insert bInf v $ bIntvs s}\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (minBInf,intv) = findMin maxIntvs\n \n let newBIntvs = delete minBInf curBIntvs\n updateBIntvs newBIntvs\n let sz = sizeLot s\n let newIntvs = delete minBInf maxIntvs\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcEcart bInf (pos-1)\n let eSecond = calcEcart (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let curEIntvs = eIntvs s \n insertBIntvs bInf (e,v) \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n let curBIntvs = bIntvs env\n let (mins,_) = split p curBIntvs \n let bInf = if (p==1) \n then BNotFound\n else if null mins\n then BNotFound\n else let (_,(e,i)) = (findMax mins)\n in if ((getSup i)==(p-1))\n then BIntv (e,i)\n else BNotFound\n \n\n let bSup = if (p==sz) \n then BNotFound\n else fromMaybe BNotFound $ do\n (e,i) <- lookup (p+1) curBIntvs\n return $ BIntv (e,i) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iInf) eInf\n deleteInEIntvs (getInf iSup) eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs (getInf iInf) eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iSup) eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = Env {sizeLot=n,\n values = empty,\n bIntvs = singleton 1 ((n-1),(Intv 1 n)), \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ngetState n xs = execStateT (test xs) (initEnv n) \ntestState n xs = evalStateT (test xs) (initEnv n) \n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = evalStateT (manage nbActs) (initEnv n)\n\nmanage 0 = return []\nmanage 100000 = return []\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n liftM (pos:) $ manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot::Int,\n values::IntMap Int,\n eIntvs::IntMap (IntMap Intv),\n bIntvs::IntMap (Int,Intv)\n } deriving Show\n\n\ntype LotState a = StateT Env IO a\n\ndata Pos = Pos Int Int | None deriving Show\n\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get\n put $ s {values = insert v pos $ values s} \n\ntakeValue v = do\n s <- get\n let curValues = values s \n let pos = curValues ! v \n put $ s {values = delete v curValues}\n return pos \n\n\ndeleteInEIntvs bInf e = do\n env <- get\n let curEIntvs = eIntvs env\n let newBIntvs = delete bInf $ bIntvs env\n let intvs = curEIntvs ! e\n let newIntvs = delete bInf intvs\n if (null newIntvs)\n then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs} \n else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs} \n \nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n\ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n \nupdateBIntvs m = do \n s <- get\n put $ s {bIntvs = m}\n\ninsertBIntvs bInf v = do\n s <- get\n put s {bIntvs = insert bInf v $ bIntvs s}\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (minBInf,intv) = findMin maxIntvs\n \n let newBIntvs = delete minBInf curBIntvs\n updateBIntvs newBIntvs\n let sz = sizeLot s\n let newIntvs = delete minBInf maxIntvs\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcEcart bInf (pos-1)\n let eSecond = calcEcart (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let curEIntvs = eIntvs s \n insertBIntvs bInf (e,v) \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n let curBIntvs = bIntvs env\n let (mins,_) = split p curBIntvs \n let bInf = if (p==1) \n then BNotFound\n else if null mins\n then BNotFound\n else let (_,(e,i)) = (findMax mins)\n in if ((getSup i)==(p-1))\n then BIntv (e,i)\n else BNotFound\n \n\n let bSup = if (p==sz) \n then BNotFound\n else fromMaybe BNotFound $ do\n (e,i) <- lookup (p+1) curBIntvs\n return $ BIntv (e,i) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iInf) eInf\n deleteInEIntvs (getInf iSup) eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs (getInf iInf) eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iSup) eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = Env {sizeLot=n,\n values = empty,\n bIntvs = singleton 1 ((n-1),(Intv 1 n)), \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ngetState n xs = execStateT (test xs) (initEnv n) \ntestState n xs = evalStateT (test xs) (initEnv n) \n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = evalStateT (manage nbActs) (initEnv n)\n\nmanage 0 = return []\nmanage 100000 = return []\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n liftM (pos:) $ manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot::Int,\n values::IntMap Int,\n eIntvs::IntMap (IntMap Intv),\n bIntvs::IntMap (Int,Intv)\n } deriving Show\n\n\ntype LotState a = StateT Env IO a\n\ndata Pos = Pos Int Int | None deriving Show\n\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get\n put $ s {values = insert v pos $ values s} \n\ntakeValue v = do\n s <- get\n let curValues = values s \n let pos = curValues ! v \n --put $ s {values = delete v curValues}\n return pos \n\n\ndeleteInEIntvs bInf e = do\n env <- get\n let curEIntvs = eIntvs env\n let newBIntvs = delete bInf $ bIntvs env\n put $ env {eIntvs = alter f e curEIntvs,bIntvs=newBIntvs}\n --let intvs = curEIntvs ! e\n --let newIntvs = delete bInf intvs\n --if (null newIntvs)\n -- then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs} \n -- else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs}\n where \n f Nothing = Nothing\n f (Just a) = let newIntvs = delete bInf a \n in if null newIntvs \n then Nothing\n else (Just newIntvs)\n \n \nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n\ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n \nupdateBIntvs m = do \n s <- get\n put $ s {bIntvs = m}\n\ninsertBIntvs bInf v = do\n s <- get\n put s {bIntvs = insert bInf v $ bIntvs s}\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (minBInf,intv) = findMin maxIntvs\n \n let newBIntvs = delete minBInf curBIntvs\n updateBIntvs newBIntvs\n let sz = sizeLot s\n let newIntvs = delete minBInf maxIntvs\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcEcart bInf (pos-1)\n let eSecond = calcEcart (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let curEIntvs = eIntvs s \n insertBIntvs bInf (e,v) \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n let curBIntvs = bIntvs env\n let (mins,_) = split p curBIntvs \n let bInf = if (p==1) \n then BNotFound\n else if null mins\n then BNotFound\n else let (_,(e,i)) = (findMax mins)\n in if ((getSup i)==(p-1))\n then BIntv (e,i)\n else BNotFound\n \n\n let bSup = if (p==sz) \n then BNotFound\n else fromMaybe BNotFound $ do\n (e,i) <- lookup (p+1) curBIntvs\n return $ BIntv (e,i) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iInf) eInf\n deleteInEIntvs (getInf iSup) eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs (getInf iInf) eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iSup) eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = Env {sizeLot=n,\n values = empty,\n bIntvs = singleton 1 ((n-1),(Intv 1 n)), \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ngetState n xs = execStateT (test xs) (initEnv n) \ntestState n xs = evalStateT (test xs) (initEnv n) \n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = evalStateT (manage nbActs) (initEnv n)\n\nmanage 0 = return []\nmanage 100000 = return []\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n liftM (pos:) $ manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\n\n\ntype Env = (IntMap Int,IntMap [Intv])\n\ndata Pos = Pos Int Int | None deriving Show\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } \n\nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n manage size nbActs (empty, (insert (size-1) [(Intv 1 size)] $ empty)) >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> Env -> Int -> (Int,Env)\nins n (values,intvs) v = let (pos,newIntvs) = takePos n intvs\n in (pos,((insert v pos values),newIntvs)) \n\nremV:: Int -> Env -> Int -> Env\nremV n (values,intvs) v = let pos = values ! v\n newIntvs = remPos n pos intvs\n in ((delete v values),newIntvs)\n\ninsFusion n bInf bSup intvs = let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==n) -> n-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n in insertIntv e [(Intv bInf bSup)] intvs \n \nremPos:: Int -> Int -> (IntMap [Intv]) -> (IntMap [Intv]) \n\nremPos n p intvs = let lIntvs = toList intvs\n (iS,nIntvs) = findBornes p (Nothing,Nothing) lIntvs intvs \n in case iS of\n (Just iInf,Just iSup) -> insFusion n (getInf iInf) (getSup iSup) nIntvs \n (Just iInf,Nothing) -> insFusion n (getInf iInf) p nIntvs \n (Nothing,Just iSup) -> insFusion n p (getSup iSup) nIntvs\n otherwise -> insFusion n p p nIntvs \n\nfindBornes:: Int -> (Maybe Intv,Maybe Intv) -> [(Int,[Intv])] -> (IntMap [Intv]) -> ((Maybe Intv,Maybe Intv),(IntMap [Intv]))\nfindBornes _ bs [] intvs = (bs,intvs) \nfindBornes _ bs@(Just iInf, Just iSup) _ intvs = (bs,intvs) \nfindBornes p iS ((e,xs):ys) intvs = let (nIs,f,zs) = findBornes' p False (Nothing,Nothing) xs []\n newIntvs = if f \n then case zs of\n [] -> delete e intvs\n otherwise -> insert e zs intvs \n else intvs\n in findBornes p nIs ys newIntvs\n \nfindBornes' _ f iS [] ys = (iS,f,[]) \nfindBornes' p f (iInf,iSup) (intv@(Intv bInf bSup):xs) ys = case (bInf,bSup) of\n (i,s) | (p==(bSup+1)) -> findBornes' p True (Just intv,iSup) xs ys \n (i,s) | (p==(bInf-1)) -> findBornes' p True (iInf,Just intv) xs ys \n (i,s) -> let (nIs,ff,ys) = findBornes' p f (iInf,iSup) xs ys\n in (nIs,ff,intv:ys) \n \n\ntakePos:: Int -> (IntMap [Intv]) -> (Int,(IntMap [Intv]))\ntakePos n intvs = let (e,maxIntvs) = findMax intvs\n (intv:xs) = maxIntvs\n newIntvs = case xs of\n [] -> delete e intvs\n xs -> insert e xs intvs\n in case intv of\n (Intv bInf bSup) | (bInf==bSup) -> (bInf,newIntvs) --ok\n (Intv 1 bSup) | (bSup==n) -> (1, insertIntv (e-1) [(Intv 2 n)] newIntvs) --ok \n (Intv 1 bSup) -> (1,insertIntv (calcEcart 2 bSup) [(Intv 2 bSup)] newIntvs) --ok\n (Intv bInf bSup) | (bSup==n) -> (n,insertIntv (calcEcart bInf (n-1)) [(Intv bInf (n-1))] newIntvs) --ok\n (Intv bInf bSup) | e==0 -> (bInf,insertIntv 0 [(Intv bSup bSup)] newIntvs) --ok\n (Intv bInf bSup) -> let pos = bInf+e\n eFirst = calcEcart bInf (pos-1)\n eSecond = calcEcart (pos+1) bSup\n in (pos,insertIntv eFirst [(Intv bInf (pos-1))] $ \n insertIntv eSecond [(Intv (pos+1) bSup)] newIntvs) --ok\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\n\ninsertIntv k v m = insertWith insIntv k v m \n\ninsIntv:: [Intv] -> [Intv] -> [Intv]\ninsIntv [] ys = ys\ninsIntv xs [] = xs\ninsIntv (x:xs) (y:ys) = if ((getInf x) < (getInf y))\n then x: (insIntv xs (y:ys)) \n else y: (insIntv (x:xs) (ys)) \n\n\ntest size [] _ = return []\ntest size (action:xs) env = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n let (pos,newEnv) = ins size env value \n liftM (pos:) $ test size xs newEnv\n 2 -> test size xs $ remV size env value \n\nmanage size 0 _ = return []\nmanage size nbActs env = do\n action <- getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n 1 -> do\n let (pos,newEnv) = ins size env value \n liftM (pos:) $ manage size (nbActs-1) newEnv\n 2 -> manage size (nbActs-1) $ remV size env value \n\n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\ndata Pos = Pos Int Int | None deriving Show\n\nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n manage size nbActs [] >>= print\n \ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ngetPos:: Int -> [(Int,Int)] -> (Int,Pos)\ngetPos n xs = case (foldl maxDist (0,None) xs) of\n (0,None) -> (1,Pos (n) 1)\n (i,None) | (i==n) -> (0,None)\n (i,None) -> (n,Pos (n-i) n)\n (i,Pos e ii) | (e==0) -> (0,None)\n (i,p) -> (i,p) \n\nmaxDist (0,_) (i,v) = (1,Pos (i-1) 1)\n \nmaxDist (l,None) (n,v) = case (eMin>0) of\n True -> (n,(Pos eMin (l+eMin)))\n False -> (n,None)\n where eMin = truncate $ diff / 2\n diff= fromIntegral $ n-l \n \n\nmaxDist (l,(Pos e i)) (n,v) = case (eMin>e) of\n True -> (n,(Pos eMin (l+eMin)))\n False -> (n,(Pos e i))\n\n where eMin = truncate $ diff / 2\n diff= fromIntegral $ n-l \n\ngetPos' n xs = case (l,p) of \n (i,None) -> case ((n-i)>0) of\n True -> n\n False -> 0 \n (_,(Pos e i)) -> case ((n-l)>e) of\n True -> case (i==0) of\n True -> 0\n False -> n\n False -> i \n where(l,p) = getPos n xs\n\n\nmanage size 0 _ = return []\nmanage size nbActs xs = do\n action <- getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n 1 -> do\n let pos = getPos' size xs\n liftM (pos:) $ manage size (nbActs-1) $ insert pos xs value\n \n 2 -> manage size (nbActs-1) $ remove value xs \n\n\ninsert:: Int -> [(Int,Int)] -> Int -> [(Int,Int)]\ninsert pos xs v = case (pos) of\n 0 -> []\n otherwise -> ins v pos xs\n where \n ins val p ((pp,vv):ys) = case (pp>p) of\n True -> (p,val):(pp,vv):ys\n False -> (pp,vv):(ins val p ys)\n ins val p ([]) = [(p,val)]\n\nremove:: Int -> [(Int,Int)] -> [(Int,Int)]\nremove v ((pp,vv):xs) = case (vv==v) of\n True -> xs \n False -> (pp,vv):(remove v xs) \nremove v [] = [] \n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\ndata Pos = Pos Int Int | None deriving Show\n\nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n manage size nbActs [] >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ngetPos:: Int -> [(Int,Int)] -> (Int,Pos)\ngetPos n xs = case (foldl maxDist (0,None) xs) of\n (0,None) -> (1,Pos (n) 1)\n (i,None) | (i==n) -> (0,None)\n (i,None) -> (n,Pos (n-i) n)\n (i,Pos e ii) | (e==0) -> (0,None)\n (i,p) -> (i,p) \n\nmaxDist (0,_) (i,v) = (1,Pos (i-1) 1)\n \nmaxDist (l,None) (n,v) = case (eMin>0) of\n True -> (n,(Pos eMin (l+eMin)))\n False -> (n,None)\n where eMin = truncate $ diff / 2\n diff= fromIntegral $ n-l \n \n\nmaxDist (l,(Pos e i)) (n,v) = case (eMin>e) of\n True -> (n,(Pos eMin (l+eMin)))\n False -> (n,(Pos e i))\n\n where eMin = truncate $ diff / 2\n diff= fromIntegral $ n-l \n\ngetPos' n xs = case (l,p) of \n (i,None) -> case ((n-i)>0) of\n True -> n\n False -> 0 \n (_,(Pos e i)) -> case ((n-l)>e) of\n True -> case (i==0) of\n True -> 0\n False -> n\n False -> i \n where(l,p) = getPos n xs\n\n\nmanage size 0 _ = return []\nmanage size nbActs xs = do\n action <- getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n 1 -> do\n let pos = getPos' size xs\n liftM (pos:) $ manage size (nbActs-1) $ insert pos xs value\n \n 2 -> manage size (nbActs-1) $ remove value xs \n\n\ninsert:: Int -> [(Int,Int)] -> Int -> [(Int,Int)]\ninsert pos xs v = case (pos) of\n 0 -> []\n otherwise -> ins v pos xs\n where \n ins val p ((pp,vv):ys) = case (pp>p) of\n True -> (p,val):(pp,vv):ys\n False -> (pp,vv):(ins val p ys)\n ins val p ([]) = [(p,val)]\n\nremove:: Int -> [(Int,Int)] -> [(Int,Int)]\nremove v ((pp,vv):xs) = case (vv==v) of\n True -> xs \n False -> (pp,vv):(remove v xs) \nremove v [] = [] \n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\n\ndata Pos = Pos Int Int | None deriving Show\n\nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n manage size nbActs [] >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\ngetPos:: Int -> [(Int,Int)] -> (Int,Pos)\ngetPos n xs = case (foldl maxDist (0,None) xs) of\n (0,None) -> (1,Pos (n) 1)\n (i,None) | (i==n) -> (0,None)\n (i,None) -> (n,Pos (n-i) n)\n (i,Pos e ii) | (e==0) -> (0,None)\n (i,p) -> (i,p) \n\nmaxDist (0,_) (i,v) = case (i==1) of\n True -> (1,None)\n False -> (1,Pos (i-1) 1)\n\nmaxDist (l,None) (n,v) = case (eMin>0) of\n True -> (n,(Pos eMin (l+eMin)))\n False -> (n,None)\n where eMin = truncate $ diff / 2\n diff= fromIntegral $ n-l \n \n\nmaxDist (l,(Pos e i)) (n,v) = case (eMin>e) of\n True -> (n,(Pos eMin (l+eMin)))\n False -> (n,(Pos e i))\n\n where eMin = truncate $ diff / 2\n diff= fromIntegral $ n-l \n\ngetPos' n xs = case (l,p) of \n (i,None) -> case ((n-i)>0) of\n True -> n\n False -> 0 \n (_,(Pos e i)) -> i\n where(l,p) = getPos n xs\n\n\nmanage size 0 _ = return []\nmanage size nbActs xs = do\n action <- getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n 1 -> do\n let pos = getPos' size xs\n liftM (pos:) $ manage size (nbActs-1) $ insert pos xs value\n \n 2 -> manage size (nbActs-1) $ remove value xs \n\n\ninsert:: Int -> [(Int,Int)] -> Int -> [(Int,Int)]\ninsert pos xs v = case (pos) of\n 0 -> []\n otherwise -> ins v pos xs\n where \n ins val p ((pp,vv):ys) = case (pp>p) of\n True -> (p,val):(pp,vv):ys\n False -> (pp,vv):(ins val p ys)\n ins val p ([]) = [(p,val)]\n\nremove:: Int -> [(Int,Int)] -> [(Int,Int)]\nremove v ((pp,vv):xs) = case (vv==v) of\n True -> xs \n False -> (pp,vv):(remove v xs) \nremove v [] = [] \n\n \n"}, {"source_code": "import System.IO (getChar)\nimport Control.Monad (liftM)\nimport Data.IntMap\nimport Data.Maybe (fromMaybe)\nimport Prelude hiding(lookup,null)\n--import Control.Monad.Trans(lift)\n--import Control.Monad.Trans.State\n\nnewtype StateT s m a = StateT { runStateT :: s -> m (a,s) }\n\ninstance (Monad m) => Functor (StateT s m) where\n\tfmap f m = StateT $ \\s -> do\n\t\t(x, s') <- runStateT m s\n\t\treturn (f x, s')\n\ninstance (Monad m) => Monad (StateT s m) where\n\treturn a = StateT $ \\s -> return (a, s)\n\tm >>= k = StateT $ \\s -> do\n\t\t(a, s') <- runStateT m s\n\t\trunStateT (k a) s'\n\tfail str = StateT $ \\_ -> fail str\n\nevalStateT :: (Monad m) => StateT s m a -> s -> m a\nevalStateT m s = do\n\t(a, _) <- runStateT m s\n\treturn a\n\n\nexecStateT :: (Monad m) => StateT s m a -> s -> m s\nexecStateT m s = do\n\t(_, s') <- runStateT m s\n\treturn s'\n\n\nlift m = StateT $ \\s -> do\n\t\ta <- m\n\t\treturn (a, s)\n\nget = StateT $ \\s -> return (s, s)\nput s = StateT $ \\_ -> return ((), s)\n\n\ndata Intv = Intv {getInf::Int,\n getSup::Int\n } deriving Show\n\ndata Env = Env {\n sizeLot::Int,\n values::IntMap Int,\n eIntvs::IntMap (IntMap Intv),\n bIntvs::IntMap (Int,Intv)\n } deriving Show\n\n\ntype LotState a = StateT Env IO a\n\ndata Pos = Pos Int Int | None deriving Show\n\n\ndata BIntv = BIntv (Int,Intv) | BNotFound \n \nmain :: IO ()\nmain = do\n nbS <- getNumbers 2\n let size = nbS !! 0\n let nbActs = nbS !! 1\n runManage size nbActs -- >>= printRes\n \nprintRes (x:xs) = print x >> printRes xs\nprintRes [] = return ()\n\ngetNumber = do \n s <- getNumber'\n case s of \n [] -> return Nothing \n otherwise -> return $ Just (read $ s :: Int) \n\ngetNumber' = do \n c <- catch getChar (\\err-> return ' ') \n case c of \n ' ' -> return \"\"\n '\\n' -> return \"\"\n otherwise -> do l <- getNumber'\n return (c:l)\n\ngetNumbers n | (n<=0) = return []\ngetNumbers n = do\n mbNum <- getNumber \n case mbNum of\n Nothing -> return []\n Just num -> (liftM (num:) (getNumbers(n-1)))\n\n\nins:: Int -> LotState Int\nins v = do \n pos <- takePos \n insertValue pos v >> return pos\n \ninsertValue pos v = do\n s <- get\n put $ s {values = insert v pos $ values s} \n\ntakeValue v = do\n s <- get\n let curValues = values s \n let pos = curValues ! v \n --put $ s {values = delete v curValues}\n return pos \n\n\ndeleteInEIntvs bInf e = do\n env <- get\n let curEIntvs = eIntvs env\n let newBIntvs = delete bInf $ bIntvs env\n put $ env {eIntvs = alter f e curEIntvs,bIntvs=newBIntvs}\n --let intvs = curEIntvs ! e\n --let newIntvs = delete bInf intvs\n --if (null newIntvs)\n -- then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs} \n -- else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs}\n where \n f Nothing = Nothing\n f (Just a) = let newIntvs = delete bInf a \n in if null newIntvs \n then Nothing\n else (Just newIntvs)\n \nupdateEIntvs m = do \n s <- get\n put $ s {eIntvs = m}\n\ninsertEIntvs e v = do \n s <- get\n let curEIntvs = eIntvs s\n put $ s {eIntvs = insert e v curEIntvs}\n \nupdateBIntvs m = do \n s <- get\n put $ s {bIntvs = m}\n\ninsertBIntvs bInf v = do\n s <- get\n put s {bIntvs = insert bInf v $ bIntvs s}\n\ntakePos:: LotState Int\ntakePos = do\n s <- get\n let curEIntvs = eIntvs s\n let curBIntvs = bIntvs s\n\n let (e,maxIntvs) = findMax curEIntvs\n let (minBInf,intv) = findMin maxIntvs\n \n let newBIntvs = delete minBInf curBIntvs\n updateBIntvs newBIntvs\n let sz = sizeLot s\n let newIntvs = delete minBInf maxIntvs\n let newEIntvs = if (null newIntvs) \n then delete e curEIntvs\n else insert e newIntvs curEIntvs\n \n updateEIntvs newEIntvs\n\n case intv of\n (Intv bInf bSup) | (bInf==bSup) -> return bInf\n (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1 --ok \n (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1 --ok\n (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok\n (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok\n (Intv bInf bSup) -> do\n let pos = bInf+e\n let eFirst = calcEcart bInf (pos-1)\n let eSecond = calcEcart (pos+1) bSup\n insertIntv eFirst $ Intv bInf (pos-1) \n insertIntv eSecond $ Intv (pos+1) bSup \n return pos\n\n where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2\n diff bInf bSup = fromIntegral $ bSup-bInf \n\ninsertIntv e v = do\n s <- get\n let bInf = getInf v \n let curEIntvs = eIntvs s \n insertBIntvs bInf (e,v) \n case (lookup e curEIntvs) of\n Just intvs -> insertEIntvs e (insert bInf v intvs)\n Nothing -> insertEIntvs e (singleton bInf v) \n\ninsFusion bInf bSup = do\n env <- get\n let sz = sizeLot env\n let e = case (bInf,bSup) of\n (1,b) -> b-1\n (a,b) | (b==sz) -> sz-a \n (a,b) -> let diff = fromIntegral (b-a)\n in truncate $ diff / 2 \n insertIntv e (Intv bInf bSup)\n\nremV v = do\n pos <- takeValue v \n remPos pos\n\nremPos p = do\n env <- get\n let sz = sizeLot env\n let curBIntvs = bIntvs env\n let (mins,_) = split p curBIntvs \n let bInf = if (p==1) \n then BNotFound\n else if null mins\n then BNotFound\n else let (_,(e,i)) = (findMax mins)\n in if ((getSup i)==(p-1))\n then BIntv (e,i)\n else BNotFound\n \n\n let bSup = if (p==sz) \n then BNotFound\n else fromMaybe BNotFound $ do\n (e,i) <- lookup (p+1) curBIntvs\n return $ BIntv (e,i) \n \n case (bInf,bSup) of\n (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iInf) eInf\n deleteInEIntvs (getInf iSup) eSup \n insFusion (getInf iInf) (getSup iSup)\n \n (BIntv (eInf,iInf),_) -> do\n deleteInEIntvs (getInf iInf) eInf\n insFusion (getInf iInf) p\n\n (_,BIntv (eSup,iSup)) -> do\n deleteInEIntvs (getInf iSup) eSup\n insFusion p (getSup iSup)\n otherwise -> insFusion p p \n\n\ninitEnv n = Env {sizeLot=n,\n values = empty,\n bIntvs = singleton 1 ((n-1),(Intv 1 n)), \n eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))\n }\n\ngetState n xs = execStateT (test xs) (initEnv n) \ntestState n xs = evalStateT (test xs) (initEnv n) \n\ntest [] = return []\ntest (action:xs) = do\n let value = snd action\n case (fst action ) of\n 1 -> do\n pos <- ins value\n liftM (pos:) $ test xs\n 2 -> remV value >> test xs \n\nrunManage n nbActs = evalStateT (manage nbActs) (initEnv n)\n\nmanage 0 = return ()\nmanage 100000 = return ()\nmanage nbActs= do\n action <- lift $ getNumbers 2\n let value = action !! 1\n case (action !! 0) of\n\n 1 -> do\n pos <- ins value \n --liftM (pos:) $ manage (nbActs-1)\n (lift $ print pos) >> manage (nbActs-1) \n 2 -> remV value >> manage (nbActs-1) \n\n\n \n"}], "src_uid": "d333164a78cd1f4e5014d9c5a9bec9a2"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n \r\n \r\nprefMins :: Ord t => (a -> t) -> [a] -> [t]\r\nprefMins f li = tail $ scanl' min (f $ head li) $ map f li\r\n\r\nfib n = go n (0,1)\r\n where\r\n go !n (!a, !b) | n==0 = a\r\n | otherwise = go (n-1) (b, a+b)\r\n\r\ngao (n, k) = go (n, k) (0, 1)\r\n where\r\n go (!n, !k) (!t, !i) | i >= n = t\r\n | i >= k = t + (div (n-i+k-1) (k))\r\n | otherwise = go (n, k) (t+1, i*2)\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do \r\n ~[n, k] <- getInts 2 \r\n pure $ putInts [gao (n, k)]\r\n \r\n\r\ntype SP = State [P.ByteString]\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp", "positive_code": [{"source_code": "\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Data.Bits\r\nimport System.IO\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n,k] <- readv :: IO [Int]\r\n let lk = lgCeil k\r\n print $ lk + divCeil (n - shiftL 1 lk) k\r\n\r\nlg n = fromIntegral $ finiteBitSize n - countLeadingZeros n - 1\r\nlgCeil n = lg n + if popCount n == 1 then 0 else 1\r\ndivCeil n d = q + if r==0 then 0 else 1 where (q,r)=divMod n d\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Data.Bits \r\nimport System.IO\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n,k] <- readv :: IO [Int]\r\n print $ lgCeil k + divCeil (n - 2 ^ lgCeil k) k\r\n\r\nlg n = fromIntegral $ finiteBitSize n - countLeadingZeros n - 1\r\nlgCeil n = lg n + if popCount n == 1 then 0 else 1\r\ndivCeil n d = q + if r==0 then 0 else 1 where (q,r)=divMod n d\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\n\ncalc :: Int -> Int -> Int\ncalc 1 1 = 0\ncalc n 1 = n-1\ncalc n k =\n let (ans, cur) = stage1 k 0 1\n in\n if cur < n then ans + ((n - cur + k - 1) `div` k)\n else ans\n\nstage1 :: Int -> Int -> Int -> (Int, Int)\nstage1 k it acc | acc >= k = (it, acc)\nstage1 k it acc | otherwise =\n stage1 k (it+1) (acc*2)\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,k] = map read $ words line :: [Int]\n --print \"abc\"\n --print $ stage1 k 0 1\n print $ calc n k\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC { n :: Integer, k :: Integer }\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- integer\r\n k <- integer\r\n return TC {..}\r\n\r\n-- type Output = String\r\n\r\n-- output :: Output -> C.ByteString\r\noutput = showB\r\n\r\n-- solve :: TC -> Output\r\nsolve TC {..} = compute 1 (n - 1)\r\n where\r\n compute d r\r\n | r <= 0 = 0\r\n | d >= k = (r + k - 1) `div` k\r\n | otherwise = let u = minimum [k, d, r] in 1 + compute (d + u) (r - u)\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- readInts\r\n replicateM_ t $ do\r\n [n, k] <- readIntegers\r\n print $ solve n k 1\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nreadIntegers :: IO [Integer]\r\nreadIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine\r\n\r\nsolve n k a\r\n | a >= n = 0\r\n | a >= k = (n - a - 1) `div` k + 1\r\n | otherwise = 1 + (solve n k $ 2 * a)\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\n\nisqrt :: Int -> Int\nisqrt = ceiling . sqrt . fromIntegral\n\ncalc :: Int -> Int -> Int\ncalc 1 1 = 0\ncalc n 1 = n-1\n\n-- 1. max k <= k : k*(k+1) <= n\ncalc n k =\n let k2 = ((isqrt (8*n+1)) - 1) `div` 2\n k3 = min k k2\n r = max 0 $ n-((k3*(k3+1)) `div` 2)\n m = r `mod` k\n add = if m > 0 then 1 else 0\n in\n k3 + (r `div` k) + add\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,k] = map read $ words line :: [Int]\n --print \"123\"\n --print $ ((isqrt (8*2+1)) - 1) `div` 2\n --print $ max 0 $ (n-((2*(2+1)) `div` 2))\n print $ calc n k\n"}, {"source_code": "import Control.Monad\nimport Data.Int\nimport Data.List\n\nisqrt :: Int -> Int\nisqrt = floor . sqrt . fromIntegral\n\ncalc :: Int -> Int -> Int\ncalc 1 1 = 0\ncalc n 1 = n-1\n\n-- 1. max k <= k : k*(k+1) <= n\ncalc n k =\n let k2 = ((isqrt (4*n+1)) - 1) `div` 2\n k3 = min k k2\n r = n-k3\n m = r `mod` k\n add = if m > 0 then 1 else 0\n in\n k3 + (r `div` k) + add\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,k] = map read $ words line :: [Int]\n print $ calc n k\n"}], "src_uid": "5df6eb50ead22b498bea69bb84341c06"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\nreadI :: String -> Int\nreadI = read \n\nreadL :: String -> [Int]\nreadL = (map read) . words\n\nmain = do\n s <- getLine\n print $ solve s\n\nsolve s = parser s [] 0 where\n -- TODO: remove tracer\n --parser s acc count | trace (show s ++ \" \" ++ show acc ++ \" \" ++ show count) False = undefined\n parser \"\" _ count = count\n parser s acc count = if isAlpha hs\n then parser ost (name:acc) count\n else case hs of\n ':' -> parser (tail s) acc count\n ',' -> parser (tail s) acc count\n '.' -> parser (tail s) tacc (count+sovp)\n where\n hs = head s\n sp = span isAlpha s\n name = fst sp\n ost = snd sp\n \n tacc = tail acc\n hacc = head acc\n sovp = foldl (\\c s -> if s == hacc then (c+1) else c) 0 tacc\n\nisAlpha c = c >= 'A' && c <= 'Z'\n", "positive_code": [{"source_code": "\nimport qualified Char as Char\n\ndata Token = Id String | Comma | Dot | Colon\ndata Tree = Node String [Tree]\n\n\ntokenize [] = []\ntokenize (':':xs) = Colon : tokenize xs\ntokenize (',':xs) = Comma : tokenize xs\ntokenize ('.':xs) = Dot : tokenize xs\ntokenize string = Id name : tokenize rest\n where (name, rest) = span Char.isAlpha string\n\nget_employee (Id x : Dot : xs) = ((Node x []), xs)\nget_employee (Id x : Colon : xs) = ((Node x children), rest)\n where (children, rest) = get_children [] xs\n get_children children (Dot:xs) = (children, xs)\n get_children children (Comma:xs) = get_children (child:children) rest\n where (child, rest) = get_employee xs\n get_children children xs = get_children (child:children) rest\n where (child, rest) = get_employee xs\n\nparse string = fst (get_employee (tokenize string))\n\ntree_check boss (Node name children) = conflict + sum (map (tree_check boss) children)\n where conflict = if name == boss then 1 else 0\n\ntraverse (Node name children) = this_conflicts + next_conflicts\n where this_conflicts = sum (map (tree_check name) children)\n next_conflicts = sum (map traverse children)\n\nmain :: IO ()\nmain = do\n seq <- getLine\n print (traverse (parse seq))\n\n"}, {"source_code": "import Data.Char\n\ndata Node = Node String [Node] deriving Show\n\n\nparseChildren (c:s) | c == ':' || c == ',' = (c1:cs, s'')\n | otherwise = ([], s)\n where\n (c1, s') = parseEmp s\n (cs, s'') = parseChildren s'\n\nparseEmp s = (Node name ch, s'')\n where\n (name, s') = span isAlpha s\n (ch, s'') = parseChildren s'\n\nvisit (Node name children) = ((sum cnts) + c', name:names')\n where\n (cnts, names) = unzip$ map visit children\n names' = concat names\n c' = length$ filter (==name) names'\n\nmain = getLine >>= (putStrLn.show.fst.visit.fst.parseEmp)\n"}, {"source_code": "import qualified Data.List as List\nimport qualified Data.Map as Map\nimport Data.Char\n\ndata Tree = Tree String [Tree] deriving Show -- name, employee\n\nsolve :: Tree -> Integer\nsolve (Tree name chn) = a + b\n where fastSum = List.foldl' (+) 0\n\n a = fastSum $ map (f name) chn\n b = fastSum $ map solve chn\n\n f name (Tree name' chn) = \n (fastSum $ map (f name) chn) + \n if name == name' then 1 else 0\n\nparse :: String -> Tree\nparse ss = snd $ f ss\n where f ss =\n case span isAlpha ss of\n (name, ':':rs) -> let (qs, ts) = g rs\n in (qs, Tree name ts)\n (name, '.':rs) -> (rs, Tree name [])\n _ -> undefined\n g ss = g' ss []\n where g' ss acc = \n case f ss of\n (',':qs, t) -> g' qs (t:acc)\n ('.':qs, t) -> (qs, t:acc)\n _ -> undefined\n\nmain = interact (show.solve.parse)"}, {"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.Functor\n\nmain = interact q\n\nq = func\n\nfunc::String->String\nfunc = show . solve\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nisVailed::String->Bool\nisVailed \"\" = False\nisVailed \"0\" = True\nisVailed ('0':_) = False\nisVailed _ = True\n\ndata Emp = Emp(String, [Emp])\n deriving (Show)\n\nname::String->(String, String)\nname = span isLetter\n\nemployee::String->(Emp, String)\nemployee str = (Emp (n, es), r')\n where\n (n, r) = name str\n (es,r')= case r !! 0 of\n ':' -> emps (tail r)\n _ -> ([], tail r)\n emps ('.':xs) = ([], xs)\n emps (',':xs) = emps xs\n emps xs = (emp:er, r')\n where\n (emp, right) = employee xs\n (er , r') = emps right\n\nsolve::String->Int\nsolve = s' [\"\"] . fst . employee\n\ns'::[String]->Emp->Int\ns' pnames (Emp (name, other)) = c + count [name] pnames\n where\n c = sum $ map (s' (name:pnames)) other\n count l1 (x:xs) | x `elem` l1 = count l1 xs + 1\n | otherwise = count l1 xs\n count l1 _ = 0\n"}, {"source_code": "import Data.List\n\nprocessEmployee :: String -> [String] -> (Int, String)\nprocessEmployee s names = \n let name = takeWhile (\\c -> c /= ':' && c /= '.') s\n rest = drop (length name) s\n s' = if head rest == ':'\n then tail rest\n else rest\n (count, s'') = process s' (name:names)\n in (count + length (findIndices (==name) names), s'')\n \nprocess [] _ = (0, [])\nprocess ('.':rest) _ = (0, rest)\nprocess s names =\n let (count, s') = processEmployee s names\n (c, s'') = process (tail s') names\n in if head s' == ','\n then (count + c, s'')\n else (count, tail s')\n \nmain = do s <- getLine\n let (c, _) = processEmployee s []\n print c"}], "negative_code": [{"source_code": "import qualified Data.List as List\nimport qualified Data.Map as Map\nimport Data.Char\n\ndata Tree = Tree String [Tree] -- name, employee\n\nsolve tree = solve' tree Map.empty\n where solve' (Tree name []) m = \n List.foldl' (+) 0 $ map (\\(_, y) -> y * (y - 1) `div` 2) $ Map.toList m'\n where m' = Map.insertWith (+) name 1 m\n solve' (Tree name children) m = \n List.foldl' (+) 0 $ map (\\x -> solve' x m') children\n where m' = Map.insertWith (+) name 1 m\n\nparse ss = snd $ f ss\n where f ss =\n case span isAlpha ss of\n (name, ':':rs) -> let (qs, ts) = g rs\n in (qs, Tree name ts)\n (name, '.':rs) -> (rs, Tree name [])\n _ -> undefined\n g ss = g' ss []\n where g' ss acc = \n case f ss of\n (',':qs, t) -> g' qs (t:acc)\n ('.':qs, t) -> (qs, t:acc)\n\nmain = interact (show.solve.parse)"}], "src_uid": "31057c0e76e6985a68b2a298236a8ee5"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- L.unfoldr(runStateT $ mkPoint <$> parseInt <*> parseInt) <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\nmkPoint :: Int -> Int -> Vec2 Int64\nmkPoint x y = V2 (fromIntegral x) (fromIntegral y)\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.flip onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine o seg0 || onLine o seg1) ps\n\ndata Vec2 a = V2 !a !a deriving (Eq, Ord)\n\ninstance Show a => Show (Vec2 a) where\n show (V2 x y) = show [x, y]\n\ninstance Functor Vec2 where\n fmap f (V2 x y) = V2 (f x) (f y)\n\ninstance (Num a) => Num (Vec2 a) where\n (V2 x0 y0) + (V2 x1 y1) = V2 (x0 + x1) (y0 + y1)\n (V2 x0 y0) - (V2 x1 y1) = V2 (x0 - x1) (y0 - y1)\n (V2 x0 y0) * (V2 x1 y1) = V2 (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate = fmap negate\n abs = fmap abs\n signum = fmap signum\n fromInteger n = V2 (fromInteger n) 0\n\ninstance (Fractional a) => Fractional (Vec2 a) where\n v0@(V2 x0 y0) / v1@(V2 x1 y1) = recip rr *: V2 x y\n where\n !rr = sqrMagnitude v1\n !x = v0 `dot` v1\n !y = v1 `cross` v0\n fromRational q = V2 (fromRational q) 0\n\ninfixr 7 *:\n(*:) :: Num a => a -> Vec2 a -> Vec2 a\n(*:) k = fmap (k*)\n{-# INLINE (*:) #-}\n\ndot :: Num a => Vec2 a -> Vec2 a -> a\ndot (V2 x0 y0) (V2 x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Num a => Vec2 a -> Vec2 a -> a\ncross (V2 x0 y0) (V2 x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\nmagnitude :: Floating a => Vec2 a -> a\nmagnitude = sqrt . sqrMagnitude\n{-# INLINE magnitude #-}\n\nsqrMagnitude :: Num a => Vec2 a -> a\nsqrMagnitude v = v `dot` v\n{-# INLINE sqrMagnitude #-}\n\nnormalize :: Floating a => Vec2 a -> Vec2 a\nnormalize v = recip (magnitude v) *: v\n{-# INLINE normalize #-}\n\ntype K = Int64\ntype Point = Vec2 K\n\ntype Seg = (Point, Point)\ntype Polygon = [Point]\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> K\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o = flip (compCCW o)\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (u, v) = (u - p) `cross` (v - p) == 0\n && (u - p) `dot` (v - p) < 0\n{-# INLINE onSeg #-}\n\nonLine :: Point -> Seg -> Bool\nonLine p (u, v) = area p u v == 0\n{-# INLINE onLine #-}\n\nhasIntersect :: Seg -> Seg -> Bool\nhasIntersect (p0, p1) (q0, q1) = area p0 q0 q1 * area p1 q0 q1 < 0\n && area q0 p0 p1 * area q1 p0 p1 < 0\n{-# INLINE hasIntersect #-}\n\ntype Convex = [Point]\n\nconvexHull :: [Point] -> Convex\nconvexHull [] = []\nconvexHull ps = reverse . go [leftest] $ L.sortBy (compCCW leftest) sorted\n where\n !(leftest:sorted) = L.sort ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q - p) `dot` (r - p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r, p] rs\n go conv [] = conv\n go [] (r:rs) = undefined\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: BS.ByteString -> [Integer]\nconstruct str\n | BS.null str = []\n | isSpace (BS8.head str) = construct (BS8.tail str)\n | otherwise = let Just (i, other) = BS8.readInteger str in i : construct other\n\ngetInts :: IO [Integer]\ngetInts = construct <$> BS.getLine\n\ntype Point = (Integer, Integer)\n\nline :: Point -> Point -> Point -> Bool\nline (x1,y1) (x2,y2) (x3,y3) = dx1 * dy2 == dx2 * dy1\n where dx1 = x2 - x1\n dy1 = y2 - y1\n dx2 = x3 - x2\n dy2 = y3 - y2\n\ncan :: [Point] -> [Point] -> [Point] -> Bool\ncan _ _ [] = True\ncan (ga:gb:gs) [] (p:ps) = if line ga gb p then can (p:ga:gb:gs) [] ps else can (ga:gb:gs) [p] ps\ncan (ga:gb:gs) [sa] (p:ps) = if line ga gb p then can (p:ga:gb:gs) [sa] ps else can (ga:gb:gs) [p,sa] ps\ncan (ga:gb:gs) (sa:sb:ss) (p:ps)\n | line ga gb p = can (p:ga:gb:gs) (sa:sb:ss) ps\n | line sa sb p = can (ga:gb:gs) (p:sa:sb:ss) ps\n | otherwise = False\n\nsolve :: [Point] -> String\nsolve xs\n | can [p0, p1] [] (drop 2 xs) || can [p0, p2] [p1] (drop 3 xs) || can [p1, p2] [p0] (drop 3 xs) = \"YES\"\n | otherwise = \"NO\"\n where p0 = xs !! 0\n p1 = xs !! 1\n p2 = xs !! 2\n\nmain = do\n [n] <- getInts\n points <- replicateM (fromIntegral n) (getInts >>= \\[a,b] -> pure (a,b))\n putStrLn $ solve points"}, {"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Int\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInt64s = (map parseInt64 . BS8.words) `fmap` BS8.getLine :: IO [Int64]\nparseInt64 = fromIntegral . fst . fromJust . BS8.readInt\n\ntype Point = (Int64,Int64)\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\ncontains ((x1,y1),(x2,y2)) (x,y) = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n ps <- replicateM n $ do\n [x, y] <- getInt64s\n return (x,y)\n if length ps <= 4\n then putStrLn \"YES\"\n else do\n let pivots = take 3 ps\n let answers = map (solve ps) pivots\n if any id answers\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve :: [Point] -> Point -> Bool\nsolve ps p = case findColinear p ps of\n Nothing -> False\n Just q -> do\n let lineA = (p, q)\n let notOnLineA = filter (not . (contains lineA)) ps\n if length notOnLineA <= 2\n then True\n else do\n let lineB = (head notOnLineA, head (tail notOnLineA))\n let notOnLineB = filter (not . (contains lineB)) notOnLineA\n if length notOnLineB == 0\n then True\n else False\n\n-- if there are 2 colinear points with p in ps, return any one\nfindColinear :: Point -> [Point] -> Maybe Point\nfindColinear p ps = f ps M.empty where\n f [] _ = Nothing\n f (q:qs) tanDB\n | M.member t tanDB = Just q\n | otherwise = f qs (M.insert t q tanDB)\n where t = tangent p q\n\ntangent :: Point -> Point -> (Int64,Int64)\ntangent (x1,y1) (x2,y2)\n | dx' == 0 && dy' == 0 = (0,0)\n | dx <= 0 && dy <= 0 = (-dx,-dy)\n | otherwise = (dx,dy)\n where\n dx' = (x2 - x1)\n dy' = (y2 - y1)\n g = gcd dx' dy'\n dx = dx' `div` g\n dy = dy' `div` g"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- unfoldr(runStateT $ mkPoint <$> parseInt <*> parseInt) <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (P px py, P qx qy) (P ox oy) = (qx - px) * (py - oy) == (qy - py) * (px - ox)\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\n\nmkPoint :: Int -> Int -> Point\nmkPoint x y = P (fromIntegral x) (fromIntegral y)\n\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x, y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = area p0 q0 q1 * area p1 q0 q1 < 0\n && area q0 p0 p1 * area q1 p0 p1 < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0] $ sortBy (compCCW v0) sorted\n where\n !(v0:sorted) = sort ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q - p) `dot` (r - p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r ,p] rs\n go conv [] = conv\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- parse.map readInteger.B.words <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (p, q) o = dot (p - o) (q - o) * dot (p - o) (q - o) == dot (p - o) (p - o) * dot (q - o) (q - o)\n\nparse :: [Integer] -> [Point]\nparse (x:y:xys) = P x y : parse xys\nparse _ = []\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x,y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = (area p0 q0 q1) * (area p1 q0 q1) < 0\n && (area q0 p0 p1) * (area q1 p0 p1) < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0] $ sortBy (compCCW v0) sorted\n where\n !(v0:sorted) = sort ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q-p) `dot` (r-p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r,p] rs\n go conv [] = conv\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- unfoldr(runStateT $ mkPoint <$> parseInt <*> parseInt) <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (p, q) o = dot (p - o) (q - o) * dot (p - o) (q - o) == dot (p - o) (p - o) * dot (q - o) (q - o)\n\nparse :: [Integer] -> [Point]\nparse (x:y:xys) = P x y : parse xys\nparse _ = []\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\n\nmkPoint :: Int -> Int -> Point\nmkPoint x y = P (fromIntegral x) (fromIntegral y)\n\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x,y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = (area p0 q0 q1) * (area p1 q0 q1) < 0\n && (area q0 p0 p1) * (area q1 p0 p1) < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0] $ sortBy (compCCW v0) sorted\n where\n !(v0:sorted) = sort ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q-p) `dot` (r-p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r,p] rs\n go conv [] = conv\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- unfoldr(runStateT $ mkPoint <$> parseInt <*> parseInt) <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\ntype Parser a = StateT B.ByteString Maybe a\n\nparseInt :: Parser Int\nparseInt = StateT $ B.readInt . B.dropWhile isSpace\n\nparseInt2 :: Parser (Int, Int)\nparseInt2 = (,) <$> parseInt <*> parseInt\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (P px py, P qx qy) (P ox oy) = (qx - px) * (py - oy) == (qy - py) * (px - ox)\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\n\nmkPoint :: Int -> Int -> Point\nmkPoint x y = P (fromIntegral x) (fromIntegral y)\n\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x, y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o = \\u v -> compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = area p0 q0 q1 * area p1 q0 q1 < 0\n && area q0 p0 p1 * area q1 p0 p1 < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0] $ sortBy (compCCW v0) sorted\n where\n !(v0:sorted) = sort ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q - p) `dot` (r - p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r ,p] rs\n go conv [] = conv\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- parse.unfoldr(B.readInteger.B.dropWhile isSpace) <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (p, q) o = dot (p - o) (q - o) * dot (p - o) (q - o) == dot (p - o) (p - o) * dot (q - o) (q - o)\n\nparse :: [Integer] -> [Point]\nparse (x:y:xys) = P x y : parse xys\nparse _ = []\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x,y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = (area p0 q0 q1) * (area p1 q0 q1) < 0\n && (area q0 p0 p1) * (area q1 p0 p1) < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0] $ sortBy (compCCW v0) sorted\n where\n !(v0:sorted) = sort ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q-p) `dot` (r-p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r,p] rs\n go conv [] = conv\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.Maybe\nimport Data.Array\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine\nparseInt = fst . fromJust . BS8.readInt\n\ntype Point = [Int]\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\ncontains ([x1,y1],[x2,y2]) [x,y] = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n pointList <- replicateM n getInts\n let points = listArray (1,n) pointList\n if n <= 4\n then putStrLn \"YES\"\n else do\n let lineA = (points ! 1, points ! 2)\n let notOnA = filter (not . (contains lineA)) (elems points)\n if length notOnA <= 2\n then putStrLn \"YES\"\n else do\n let lineB = (head notOnA, (head . tail) notOnA)\n let notOnB = filter (not . (contains lineB)) notOnA\n if length notOnB == 0\n then putStrLn \"YES\"\n else do\n let lineC = (points ! 1, head notOnA)\n let notOnC = filter (not . (contains lineC)) (elems points)\n if length notOnC <= 2\n then putStrLn \"YES\"\n else do\n let lineD = (head notOnC, (head . tail) notOnC)\n let notOnD = filter (not . (contains lineD)) notOnC\n if length notOnD == 0\n then putStrLn \"YES\"\n else putStrLn \"NO\""}, {"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine\nparseInt = fst . fromJust . BS8.readInt\n\ntype Point = (Int,Int)\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\ncontains ((x1,y1),(x2,y2)) (x,y) = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n ps <- replicateM n $ do\n [x, y] <- getInts\n return (x,y)\n if length ps <= 4\n then putStrLn \"YES\"\n else do\n let pivots = take 3 ps\n if any id (map (solve ps) pivots)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve :: [Point] -> Point -> Bool\nsolve ps p = case findColinear p ps of\n Nothing -> False\n Just q -> do\n let lineA = (p, q)\n let notOnLineA = filter (not . (contains lineA)) ps\n if length notOnLineA <= 2\n then True\n else do\n let lineB = (head notOnLineA, head (tail notOnLineA))\n let notOnLineB = filter (not . (contains lineB)) notOnLineA\n if length notOnLineB == 0\n then True\n else False\n\n-- if there are 2 colinear points with p in ps, return any one\nfindColinear :: Point -> [Point] -> Maybe Point\nfindColinear p ps = f ps M.empty where\n f [] _ = Nothing\n f (q:qs) tanDB\n | M.member t tanDB = Just q\n | otherwise = f qs (M.insert t q tanDB)\n where t = tangent p q\n\ntangent :: Point -> Point -> (Int,Int)\ntangent (x1,y1) (x2,y2)\n | dx' == 0 && dy' == 0 = (0,0)\n | dx < 0 && dy < 0 = (-dx,-dy)\n | otherwise = (dx,dy)\n where\n dx' = (x2 - x1)\n dy' = (y2 - y1)\n g = gcd dx' dy'\n dx = dx' `div` g\n dy = dy' `div` g"}, {"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Control.Monad\nimport qualified Data.Map.Strict as M\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine\nparseInt = fst . fromJust . BS8.readInt\n\ntype Point = (Int,Int)\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\ncontains ((x1,y1),(x2,y2)) (x,y) = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n ps <- replicateM n $ do\n [x, y] <- getInts\n return (x,y)\n if length ps <= 4\n then putStrLn \"YES\"\n else do\n let p = head ps\n case findColinear p (tail ps) of\n Nothing -> putStrLn \"NO\"\n Just q -> do\n let lineA = (p, q)\n let notOnLineA = filter (not . (contains lineA)) ps\n if length notOnLineA <= 2\n then putStrLn \"YES\"\n else do\n let lineB = (head notOnLineA, head (tail notOnLineA))\n let notOnLineB = filter (not . (contains lineB)) notOnLineA\n if length notOnLineB == 0\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n-- if there are 2 colinear points with p in ps, return any one\nfindColinear :: Point -> [Point] -> Maybe Point\nfindColinear p ps = f ps M.empty where\n f [] _ = Nothing\n f (q:qs) tanDB\n | M.member t tanDB = Just q\n | otherwise = f qs (M.insert t q tanDB)\n where t = tangent p q\n\ntangent :: Point -> Point -> (Int,Int)\ntangent (x1,y1) (x2,y2)\n | dx < 0 && dy < 0 = (-dx,-dy)\n | otherwise = (dx,dy)\n where\n dx' = (x2 - x1)\n dy' = (y2 - y1)\n g = gcd dx' dy'\n dx = dx' `div` g\n dy = dy' `div` g"}, {"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine\nparseInt = fst . fromJust . BS8.readInt\n\ntype Point = (Int,Int)\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\n--contains ((x1,y1),(x2,y2)) (x,y) = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\ncontains ((x1,y1),(x2,y2)) (x,y)\n | y1 == y2 = y == y1\n | x1 == x2 = x == x1\n | otherwise = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n ps <- replicateM n $ do\n [x, y] <- getInts\n return (x,y)\n if length ps <= 4\n then putStrLn \"YES\"\n else do\n let pivots = take 3 ps\n let answers = map (solve ps) pivots\n if any id answers\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve :: [Point] -> Point -> Bool\nsolve ps p = case findColinear p ps of\n Nothing -> False\n Just q -> do\n let lineA = (p, q)\n let notOnLineA = filter (not . (contains lineA)) ps\n if length notOnLineA <= 2\n then True\n else do\n let lineB = (head notOnLineA, head (tail notOnLineA))\n let notOnLineB = filter (not . (contains lineB)) notOnLineA\n if length notOnLineB == 0\n then True\n else False\n\n-- if there are 2 colinear points with p in ps, return any one\nfindColinear :: Point -> [Point] -> Maybe Point\nfindColinear p ps = f ps M.empty where\n f [] _ = Nothing\n f (q:qs) tanDB\n | M.member t tanDB = Just q\n | otherwise = f qs (M.insert t q tanDB)\n where t = tangent p q\n\ntangent :: Point -> Point -> (Int,Int)\ntangent (x1,y1) (x2,y2)\n | dx' == 0 && dy' == 0 = (0,0)\n | dx <= 0 && dy <= 0 = (-dx,-dy)\n | otherwise = (dx,dy)\n where\n dx' = (x2 - x1)\n dy' = (y2 - y1)\n g = gcd dx' dy'\n dx = dx' `div` g\n dy = dy' `div` g"}, {"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine\nparseInt = fst . fromJust . BS8.readInt\n\ntype Point = (Int,Int)\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\ncontains ((x1,y1),(x2,y2)) (x,y) = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n ps <- replicateM n $ do\n [x, y] <- getInts\n return (x,y)\n if length ps <= 4\n then putStrLn \"YES\"\n else do\n let pivots = take 3 ps\n if any id (map (solve ps) pivots)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve :: [Point] -> Point -> Bool\nsolve ps p = case findColinear p ps of\n Nothing -> False\n Just q -> do\n let lineA = (p, q)\n let notOnLineA = filter (not . (contains lineA)) ps\n if length notOnLineA <= 2\n then True\n else do\n let lineB = (head notOnLineA, head (tail notOnLineA))\n let notOnLineB = filter (not . (contains lineB)) notOnLineA\n if length notOnLineB == 0\n then True\n else False\n\n-- if there are 2 colinear points with p in ps, return any one\nfindColinear :: Point -> [Point] -> Maybe Point\nfindColinear p ps = f ps M.empty where\n f [] _ = Nothing\n f (q:qs) tanDB\n | M.member t tanDB = Just q\n | otherwise = f qs (M.insert t q tanDB)\n where t = tangent p q\n\ntangent :: Point -> Point -> (Int,Int)\ntangent (x1,y1) (x2,y2)\n | dx' == 0 && dy' == 0 = (0,0)\n | dx <= 0 && dy <= 0 = (-dx,-dy)\n | otherwise = (dx,dy)\n where\n dx' = (x2 - x1)\n dy' = (y2 - y1)\n g = gcd dx' dy'\n dx = dx' `div` g\n dy = dy' `div` g"}, {"source_code": "import qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Map.Strict as M\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS8.getLine\nparseInt = fst . fromJust . BS8.readInt\n\ntype Point = (Int,Int)\ntype Line = (Point,Point)\n\ncontains :: Line -> Point -> Bool\ncontains ((x1,y1),(x2,y2)) (x,y) = (y-y2)*(x2-x1) == (y2-y1)*(x-x2)\n\nmain = do\n n <- getInt\n ps <- replicateM n $ do\n [x, y] <- getInts\n return (x,y)\n if length ps <= 4\n then putStrLn \"YES\"\n else do\n let pivots = take 3 ps\n let answers = map (solve ps) pivots\n if any id answers\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve :: [Point] -> Point -> Bool\nsolve ps p = case findColinear p ps of\n Nothing -> False\n Just q -> do\n let lineA = (p, q)\n let notOnLineA = filter (not . (contains lineA)) ps\n if length notOnLineA <= 2\n then True\n else do\n let lineB = (head notOnLineA, head (tail notOnLineA))\n let notOnLineB = filter (not . (contains lineB)) notOnLineA\n if length notOnLineB == 0\n then True\n else False\n\n-- if there are 2 colinear points with p in ps, return any one\nfindColinear :: Point -> [Point] -> Maybe Point\nfindColinear p ps = f ps M.empty where\n f [] _ = Nothing\n f (q:qs) tanDB\n | M.member t tanDB = Just q\n | otherwise = f qs (M.insert t q tanDB)\n where t = tangent p q\n\ntangent :: Point -> Point -> (Int,Int)\ntangent (x1,y1) (x2,y2)\n | dx' == 0 && dy' == 0 = (0,0)\n | dx <= 0 && dy <= 0 = (-dx,-dy)\n | otherwise = (dx,dy)\n where\n dx' = (x2 - x1)\n dy' = (y2 - y1)\n g = gcd dx' dy'\n dx = dx' `div` g\n dy = dy' `div` g"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- parse.map readInteger.B.words <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x,y,z,w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (\\o -> not $ onLine seg o) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (p, q) o = dot (p - o) (q - o) * dot (p - o) (q - o) == dot (p - o) (p - o) * dot (q - o) (q - o)\n\nparse :: [Integer] -> [Point]\nparse (x:y:xys) = P x y : parse xys\nparse _ = []\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x,y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ area o u v\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = (area p0 q0 q1) * (area p1 q0 q1) < 0\n && (area q0 p0 p1) * (area q1 p0 p1) < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0].sortBy (compCCW v0) $ filter (/=v0) ps\n where\n !v0 = minimum ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q-p) `dot` (r-p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r,p] rs\n go conv [] = conv\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ps <- parse.map readInteger.B.words <$> B.getContents\n putStrLn.bool\"NO\"\"YES\" $ solve ps\n\nsolve :: [Point] -> Bool\nsolve ps = case convexHull ps of\n [_] -> True\n [_, _] -> True\n [x, y, z] -> or\n [ validate3 (x, y) ps\n , validate3 (y, z) ps\n , validate3 (z, x) ps\n ]\n [x, y, z, w] -> or\n [ validate4 (x, y) (z, w) ps\n , validate4 (x, z) (y, w) ps\n , validate4 (x, w) (y, z) ps\n ]\n _ -> False\n\nvalidate3 :: Seg -> [Point] -> Bool\nvalidate3 seg ps = case convexHull $ filter (not.onLine seg) ps of\n [_] -> True\n [_, _] -> True\n _ -> False\n\nvalidate4 :: Seg -> Seg -> [Point] -> Bool\nvalidate4 seg0 seg1 ps = all (\\o -> onLine seg0 o || onLine seg1 o) ps\n\nonLine :: Seg -> Point -> Bool\nonLine (p, q) o = dot (p - o) (q - o) * dot (p - o) (q - o) == dot (p - o) (p - o) * dot (q - o) (q - o)\n\nparse :: [Integer] -> [Point]\nparse (x:y:xys) = P x y : parse xys\nparse _ = []\n\ndata Point = P !Integer !Integer deriving (Eq, Ord)\ntype Seg = (Point, Point)\ntype Polygon = [Point]\ntype Convex = [Point]\n\ninstance Show Point where\n show (P x y) = show (x,y)\n\ninstance Num Point where\n (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)\n (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)\n (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)\n negate (P x y) = P (negate x) (negate y)\n abs _ = undefined\n signum _ = undefined\n fromInteger n = P n 0\n\ninfixr 7 *:\n(*:) :: Integer -> Point -> Point\n(*:) !k (P x y) = P (k * x) (k * y)\n{-# INLINE (*:) #-}\n\ndot :: Point -> Point -> Integer\ndot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1\n{-# INLINE dot #-}\n\ncross :: Point -> Point -> Integer\ncross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1\n{-# INLINE cross #-}\n\n-- v\n-- / <==> area o u v > 0\n-- o---u\narea :: Point -> Point -> Point -> Integer\narea o u v = (u - o) `cross` (v - o)\n{-# INLINE area #-}\n\n-- v\n-- / <==> compCCW o u v == LT\n-- o---u\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = case compare 0 $ area o u v of\n EQ -> compare (dot (u-o)(u-o))(dot(v-o)(v-o))\n x->x\n{-# INLINE compCCW #-}\n\ncompCW :: Point -> Point -> Point -> Ordering\ncompCW o u v = compCCW o v u\n{-# INLINE compCW #-}\n\nonSeg :: Point -> Seg -> Bool\nonSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0\n && (q0 - p) `dot` (q1 - p) < 0\n{-# INLINE onSeg #-}\n\nsegIntersect :: Seg -> Seg -> Bool\nsegIntersect (p0, p1) (q0, q1) = (area p0 q0 q1) * (area p1 q0 q1) < 0\n && (area q0 p0 p1) * (area q1 p0 p1) < 0\n{-# INLINE segIntersect #-}\n\nconvexHull :: [Point] -> Convex\nconvexHull ps = reverse.go [v0].sortBy (compCCW v0) $ filter (/=v0) ps\n where\n !v0 = minimum ps\n go (p:q:conv) (r:rs) = case compCCW q p r of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | (q-p) `dot` (r-p) < 0 -> go (r:q:conv) rs -- q--p--r\n | otherwise -> go (p:q:conv) rs -- q--r--p\n go [p] (r:rs) = go [r,p] rs\n go conv [] = conv\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: BS.ByteString -> [Int]\nconstruct str\n | BS.null str = []\n | isSpace (BS8.head str) = construct (BS8.tail str)\n | otherwise = let Just (i, other) = BS8.readInt str in i : construct other\n\ngetInts :: IO [Int]\ngetInts = construct <$> BS.getLine\n\ntype Point = (Int, Int)\n\nline :: Point -> Point -> Point -> Bool\nline (x1,y1) (x2,y2) (x3,y3) = dx1 * dy2 == dx2 * dy1\n where dx1 = x2 - x1\n dy1 = y2 - y1\n dx2 = x3 - x2\n dy2 = y3 - y2\n\ncan :: [Point] -> [Point] -> [Point] -> Bool\ncan _ _ [] = True\ncan (ga:gb:gs) [] (p:ps) = if line ga gb p then can (p:ga:gb:gs) [] ps else can (ga:gb:gs) [p] ps\ncan (ga:gb:gs) [sa] (p:ps) = if line ga gb p then can (p:ga:gb:gs) [sa] ps else can (ga:gb:gs) [p,sa] ps\ncan (ga:gb:gs) (sa:sb:ss) (p:ps)\n | line ga gb p = can (p:ga:gb:gs) (sa:sb:ss) ps\n | line sa sb p = can (ga:gb:gs) (p:sa:sb:ss) ps\n | otherwise = False\n\nsolve :: [Point] -> String\nsolve xs\n | can [p0, p1] [] (drop 2 xs) || can [p0, p2] [p1] (drop 3 xs) || can [p1, p2] [p0] (drop 3 xs) = \"success\"\n | otherwise = \"failure\"\n where p0 = xs !! 0\n p1 = xs !! 1\n p2 = xs !! 2\n\nmain = do\n [n] <- getInts\n points <- replicateM n (getInts >>= \\[a,b] -> pure (a,b))\n putStrLn $ solve points"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: BS.ByteString -> [Int]\nconstruct str\n | BS.null str = []\n | isSpace (BS8.head str) = construct (BS8.tail str)\n | otherwise = let Just (i, other) = BS8.readInt str in i : construct other\n\ngetInts :: IO [Int]\ngetInts = construct <$> BS.getLine\n\ntype Point = (Int, Int)\n\nline :: Point -> Point -> Point -> Bool\nline (x1,y1) (x2,y2) (x3,y3) = dx1 * dy2 == dx2 * dy1\n where dx1 = x2 - x1\n dy1 = y2 - y1\n dx2 = x3 - x2\n dy2 = y3 - y2\n\ncan :: [Point] -> [Point] -> [Point] -> Bool\ncan _ _ [] = True\ncan (ga:gb:gs) [] (p:ps) = if line ga gb p then can (p:ga:gb:gs) [] ps else can (ga:gb:gs) [p] ps\ncan (ga:gb:gs) [sa] (p:ps) = if line ga gb p then can (p:ga:gb:gs) [sa] ps else can (ga:gb:gs) [p,sa] ps\ncan (ga:gb:gs) (sa:sb:ss) (p:ps)\n | line ga gb p = can (p:ga:gb:gs) (sa:sb:ss) ps\n | line sa sb p = can (ga:gb:gs) (p:sa:sb:ss) ps\n | otherwise = False\n\nsolve :: [Point] -> String\nsolve xs\n | can [p0, p1] [] (drop 2 xs) || can [p0, p2] [p1] (drop 3 xs) || can [p1, p2] [p0] (drop 3 xs) = \"YES\"\n | otherwise = \"NO\"\n where p0 = xs !! 0\n p1 = xs !! 1\n p2 = xs !! 2\n\nmain = do\n [n] <- getInts\n points <- replicateM n (getInts >>= \\[a,b] -> pure (a,b))\n putStrLn $ solve points"}], "src_uid": "a9fd2e4bc5528a34f1f1b869cd391d71"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nsort' x = bsort (map( (\\[x,y]->(x,y)) . map (read :: String -> Int) . words ) $ lines $ f x ) x\n\nbsort [] ls = ls\nbsort ((x,y):zs) ls = \n let (a,b) = splitAt (pred x) ls\n (c,d) = splitAt (succ $ y-x) b\n in bsort zs $ a ++ swap c ++ d\n where\n swap [] = [] \n swap (a:b:cs) = b : a : swap cs \n\nminWithIndex [] a _ = a\nminWithIndex (a:as) mm@(m,j) i = \n if ai\n then \n let k = [j,j-1..i] \n l = unlines $ map (\\(a,b) -> show b ++ \" \" ++ show a) $ zip k $ tail k\n in l ++ f' (m `delete` x) (i+1)\n else f' (m `delete` x) (i+1)\n\nint = fst .fromJust .B.readInt\nints = map int . B.words <$> B.getLine\n_' = B.getLine\n\nmain = _' >> ints >>= putStrLn . f\n\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Tree\n\n\nsmallToFront _ 0 = []\nsmallToFront x n = (x + n - 1, x + n) : (smallToFront x (n - 1))\n\nselectSort _ (_:[]) = []\nselectSort n xs = (smallToFront n minPos) ++ (selectSort (n + 1) ys)\n where\n minPos = minIndex xs\n minIndex l = snd $ minimum $ zip l [0..]\n (initArray, restArray) = genericSplitAt minPos xs\n ys = case restArray of\n [] -> initArray\n _ -> initArray ++ (tail restArray)\n\nprintPair (a, b) = putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1)\n\nmain = do\n _ <- getLine\n nums <- fmap (map (read :: String -> Int) . words) getLine\n let ans = selectSort 0 nums\n mapM_ printPair ans\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n _ <- getLine\n inp <- fmap (map read . words) getLine\n mapM_ g $ solve 0 inp\n\ng :: (Int, Int) -> IO ()\ng (a, b) = putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1) \n\nsolve' :: Int -> [Int] -> IO () \nsolve' x y = mapM_ g $ solve x y\n\nsolve :: Int -> [Int] -> [(Int, Int)]\nsolve _ [] = []\nsolve v xs = ops ++ solve (v+1) xs'\n where\n ops = fmap f ops'\n ops' = zip [ind-1, ind-2 .. 0] [ind, ind-1..0]\n f (x, y) = (x + v, y + v)\n (sm, ind) = minimum $ zip xs [0..]\n (initial, _:rest) = splitAt ind xs\n xs' = initial ++ rest\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n _ <- getLine\n inp <- fmap (map read . words) getLine\n mapM_ g $ solve 0 inp\n\ng :: (Int, Int) -> IO ()\ng (a, b) = putStrLn $ show (a + 1) ++ \" \" ++ show (b + 1) \n\nsolve' :: Int -> [Int] -> IO () \nsolve' x y = mapM_ g $ solve x y\n\nsolve :: Int -> [Int] -> [(Int, Int)]\nsolve _ [] = []\nsolve i l = smallestToFront ++ rest\n where\n smallestToFront = zip [(minInd + i - 1), minInd + i - 2 .. i] [(minInd + i), minInd+i - 1 ..]\n rest = solve (i+1) restOfArray\n restOfArray = initialArray ++ restArray\n (initialArray, _:restArray) = splitAt minInd l\n minInd = snd . minimum $ zip l [0..]\n"}, {"source_code": "import Data.List\n\nfindMinPos :: [Integer] -> Int\nfindMinPos xs = (\\(Just x) -> x) $ elemIndex (minimum xs) xs\n\ngetSwaps :: Int -> Int -> [(Int, Int)]\ngetSwaps _ 0 = []\ngetSwaps x n = (x + n - 1, x + n) : (getSwaps x (n - 1))\n\ngetAllSwaps :: Int -> [Integer] -> [(Int, Int)]\ngetAllSwaps _ (x:[]) = []\ngetAllSwaps n xs = (getSwaps n minPos) ++ (getAllSwaps (n + 1) ys)\n where minPos = findMinPos xs\n (a, b) = genericSplitAt minPos xs\n ys = case b of [] -> a\n _ -> a ++ (tail b)\n\ngetIntList :: [String] -> [Integer]\ngetIntList [] = []\ngetIntList (x:xs) = (read x :: Integer) : (getIntList xs)\n\nputAllPairs :: [(Int, Int)] -> IO ()\nputAllPairs [] = return ()\nputAllPairs ((x,y):xs) = do\n putStrLn $ show x ++ \" \" ++ show y\n putAllPairs xs\n\nmain = do\n x <- getLine\n let n = read x :: Int\n hwords <- getLine\n let hs = getIntList . words $ hwords\n as = getAllSwaps 1 hs\n putAllPairs as\n return ()\n"}, {"source_code": "import Data.List\n\nfindMinPos :: [Integer] -> Int\nfindMinPos xs = (\\(Just x) -> x) $ elemIndex (minimum xs) xs\n\ngetSwaps :: Int -> Int -> [(Int, Int)]\ngetSwaps _ 0 = []\ngetSwaps x n = (x + n - 1, x + n) : (getSwaps x (n - 1))\n\ngetAllSwaps :: Int -> [Integer] -> [(Int, Int)]\ngetAllSwaps _ (x:[]) = []\ngetAllSwaps n xs = (getSwaps n minPos) ++ (getAllSwaps (n + 1) ys)\n where minPos = findMinPos xs\n (a, b) = genericSplitAt minPos xs\n ys = case b of [] -> a\n _ -> a ++ (tail b)\nputAllPairs :: [(Int, Int)] -> IO ()\nputAllPairs [] = return ()\nputAllPairs ((x,y):xs) = do\n putStrLn $ show x ++ \" \" ++ show y\n putAllPairs xs\n\nmain = do\n x <- getLine\n let n = read x :: Int\n hwords <- getLine\n let hs = map (read::String->Integer) . words $ hwords\n as = getAllSwaps 1 hs\n putAllPairs as\n"}, {"source_code": "import Control.Monad.State\n\nmain = do\n n <- readLn\n hs <- return . map read . words =<< getLine\n let\tloop xns st = let\n\t (v,s) = (`runState` st) $ process $ zip [1..n] xns\n\t cs\t = compress s\n\t in if sorted v\n\t then return cs\n\t else loop v cs\n\t where\n\t sorted [n] = True\n\t sorted (n1:tl@(n2:rest))| n1<=n2 = sorted tl\n\t\t\t\t | otherwise = False\n mapM_ print' =<< return . reverse =<< loop hs []\n where\n\tprint' (a,b) = do\n\t putStr . show $ a\n\t putChar ' '\n\t print b\n\n\nprocess::[(Int,Int)] -> State [(Int,Int)] [Int]\nprocess [] = return []\nprocess [(ix,v)] = return [v]\nprocess ((ix1,v1):tl@((ix2,v2):rest))\n | v1 <= v2\t= return . (v1:) =<< process tl\n | otherwise\t= do\tmodify ((ix1,ix2):)\n\t\t\treturn . (v2:) . (v1:) =<< process rest\n\ncompress = foldr push []\n where\n\tpush p [] = [p]\n\tpush p@(ix3, ix4) stack@((ix1,ix2):ps) =\n\t if ix2+1==ix3 then (ix1,ix4):ps else p:stack\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.List\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n _ <- getLine\n inp <- fmap (map read . words) getLine\n print $ solve 0 inp\n\n\nsolve :: Int -> [Int] -> [(Int, Int)]\nsolve _ [] = []\nsolve v xs = ops ++ solve (v+1) xs'\n where\n ops = fmap f ops'\n ops' = zip [0..] [1..ind]\n f (x, y) = (x + v, y + v)\n (sm, ind) = minimum $ zip xs [0..]\n (initial, _:rest) = splitAt ind xs\n xs' = initial ++ rest\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nsort' x = bsort (map( (\\[x,y]->(x,y)) . map (read :: String -> Int) . words ) $ lines $ f x ) x\n\nbsort [] ls = ls\nbsort ((x,y):zs) ls = \n let (a,b) = splitAt (pred $ min x y) ls\n (c,d) = splitAt (succ $ abs $ y-x) b\n in bsort zs $ a ++ swap c ++ d\n where\n swap [] = [] \n swap (a:b:cs) = b : a : swap cs \n\nminWithIndex [] a _ = a\nminWithIndex (a:as) mm@(m,j) i = \n if ai\n then \n let k = [j,j-1..i] \n l = unlines $ map (\\(a,b) -> show a ++ \" \" ++ show b) $ zip k $ tail k\n in l ++ f' (m `delete` x) (i+1)\n else f' (m `delete` x) (i+1)\n\nint = fst .fromJust .B.readInt\nints = map int . B.words <$> B.getLine\n_' = B.getLine\n\nmain = _' >> ints >>= putStrLn . f\n\n\n"}], "src_uid": "233c2806db31916609421fbd126133d0"} {"source_code": "main = interact (f . read)\nf n = take n $ cycle \"abcd\"\n", "positive_code": [{"source_code": "main=readLn>>=putStr.(`take`s);s=\"abcd\"++s"}, {"source_code": "main=readLn>>=putStrLn.(`take`s);s=\"abcd\"++s"}, {"source_code": "main=readLn>>=putStrLn.(`take` s);s=\"abcd\"++s"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n n <- read `liftM` getLine\n putStrLn $ take n $ cycle \"abcd\"\n"}, {"source_code": "import Control.Monad\n\nmain = do n <- liftM read getLine\n putStrLn . take n . cycle $ \"abcd\"\n"}, {"source_code": "main = getLine >>= (\\n -> (putStrLn . take n . concat . repeat) \"abcd\") . read\n"}, {"source_code": "import Data.List\nmain = readLn >>= \n (\\n -> putStrLn $ \n take n (cycle \"abcd\"))"}, {"source_code": "{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}\n{-# LANGUAGE BangPatterns #-}\n{-(c) gorlum0 [at] gmail.com-}\nimport Control.Monad (forM_)\n\nlucky = cycle \"abcd\"\n\nmain = do\n ls <- lines `fmap` getContents\n let ns = map read ls\n forM_ [take n lucky | n <- ns] $\n putStrLn\n"}, {"source_code": "solve :: Int -> String\nsolve n = take n (cycle \"abcd\")\n\nmain :: IO ()\nmain = do\n readLn >>= putStrLn . solve"}, {"source_code": "main = interact $ (\\n -> take n $ cycle \"abcd\").read"}, {"source_code": "main=interact$(`take`cycle\"abcd\").read"}, {"source_code": "luckies = 4 : 7 : concatMap (\\l -> [10*l + 4, 10*l + 7]) luckies\nmain = do\n n <- readLn\n putStrLn $ concat (replicate (n `div` 4) \"abcd\") ++\n take (n `mod` 4) \"abcd\"\n"}, {"source_code": "main=interact$(`take`s).read;s=\"abcd\"++s"}, {"source_code": "solve :: Int -> String\nsolve = (`take` (cycle \"abcd\"))\n\nmain :: IO ()\nmain = readLn >>= putStrLn . solve\n\n"}, {"source_code": "-- Codeforces Beta Round 84 (Div. 2 Only) - Problem B: Lucky String (https://codeforces.com/problemset/problem/110/B) \nimport Data.List\n\nsolve n = take n $ intercalate \"\" $ replicate n \"abcd\"\n\nmain = do\n n <- readLn :: IO Int\n putStrLn $ solve n\n"}, {"source_code": "main = do n<-getLine\n (putStrLn.take (read n::Int).cycle) \"abcd\""}, {"source_code": "\ncalc :: Int -> String\ncalc n = take n $ cycle \"abcd\"\n\nmain = do s <- getLine\n putStrLn $ calc $ read s\n\n"}], "negative_code": [{"source_code": "solve :: Int -> String\nsolve n = take n (cycle \"abcd\")\n\nmain :: IO ()\nmain = do\n readLn >>= print . solve"}, {"source_code": "solve :: Int -> String\nsolve = (`take` (cycle \"abcd\"))\n\nmain :: IO ()\nmain = readLn >>= print . solve\n\n"}], "src_uid": "94278e9c55f0fc82b48145ebecbc515f"} {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe(fromJust)\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nimport Control.Monad.ST\nimport Data.Bool (bool)\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- ints\n hp <- listArray (1, n) <$> ints\n let (k, hs) = solve a b hp\n print k\n putStrLn (unwords $ map show hs)\n\nsolve :: Int -> Int -> UArray Int Int -> (Int, [Int])\nsolve a b hp = runST $ do\n dp <- newArray ((0, 0, 0, 0), (n, hm, hm, hm)) inf\n res <- fill dp sp\n fdp <- freeze dp\n pure (res, collect fdp sp)\n where\n n = snd $ bounds hp\n hm = 1 + maximum (elems hp)\n sp = (n, 0, 0, 0)\n hitRange = (2, n - 1)\n targets n = filter (inRange hitRange) [n - 1, n , n + 1]\n inf = (maxBound :: Int) `div` 2\n fill :: STUArray s QInt Int -> QInt -> ST s Int\n fill dp i@(k, x, y, z) =\n k < 1 ? pure 0 $\n testM (< inf) (readArray dp i) $\n applyM (writeArray dp i) $\n (hp ! k) - (x + z) * b - y * a < 0 ? fill dp (k - 1, 0, x, y) $\n (1 + ) . minimum <$> mapM (fill dp . hit i) (targets k)\n collect :: UArray QInt Int -> QInt -> [Int]\n collect dp i@(k, x, y, z) =\n k < 1 ? [] $\n (hp ! k) - (x + z) * b - y * a < 0 ? collect dp (k - 1, 0, x, y) $\n let (t, h) = bestHit dp i in t:collect dp h\n bestHit dp i@(k, _, _, _) = minimumBy (comparing (\\(_, h) -> dp ! h)) $ zipMap (hit i) (targets k)\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ntype QInt = (Int, Int, Int, Int)\n\nhit :: QInt -> Int -> QInt\nhit (n, x, y, z) k\n | k == n = (n, x, y + 1, z)\n | k == n + 1 = (n, x, y, z + 1)\n | k == n - 1 = (n, x + 1, y, z)\n | otherwise = (n, x, y, z)\n\n(?) :: Bool -> a -> a -> a\n(?) True x _ = x\n(?) False _ y = y\ninfixr 1 ?\n\ntestM :: Monad m => (a -> Bool) -> m a -> m a -> m a\ntestM f a b = f <$> a >>= bool b a\n\napplyM :: Monad m => (a -> m ()) -> m a -> m a\napplyM f a = a >>= f >> a\n\nzipMap :: (a -> b) -> [a] -> [(a, b)]\nzipMap f = map (\\a -> (a, f a))\n", "positive_code": [{"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe(fromJust)\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nimport Control.Monad.ST\nimport Data.Bool (bool)\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- ints\n hp <- listArray (1, n) <$> ints\n let (k, hs) = solve a b hp\n print k\n putStrLn (unwords $ map show hs)\n\nsolve :: Int -> Int -> UArray Int Int -> (Int, [Int])\nsolve a b hp = runST $ do\n dp <- newArray ((0, 0, 0, 0), (n, hm, hm, hm)) inf\n res <- fill dp sp\n fdp <- freeze dp\n pure (res + s, replicate s (n - 1) ++ collect fdp sp)\n where\n n = snd $ bounds hp\n hm = 1 + maximum (elems hp)\n s = (hp ! n + 1) `updiv` b\n sp = (n - 1, 0, s, 0)\n hitRange = (2, n - 1)\n targets n = filter (inRange hitRange) [n - 1, n , n + 1]\n inf = (maxBound :: Int) `div` 2\n fill :: STUArray s QInt Int -> QInt -> ST s Int\n fill dp i@(k, x, y, z) =\n k < 1 ? pure 0 $\n testM (< inf) (readArray dp i) $\n applyM (writeArray dp i) $\n (hp ! k) - (x + z) * b - y * a < 0 ? fill dp (k - 1, 0, x, y) $\n (1 + ) . minimum <$> mapM (fill dp . hit i) (targets k)\n collect :: UArray QInt Int -> QInt -> [Int]\n collect dp i@(k, x, y, z) =\n k < 1 ? [] $\n (hp ! k) - (x + z) * b - y * a < 0 ? collect dp (k - 1, 0, x, y) $\n let (t, h) = bestHit dp i in t:collect dp h\n bestHit dp i@(k, _, _, _) = minimumBy (comparing (\\(_, h) -> dp ! h)) $ zipMap (hit i) (targets k)\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ntype QInt = (Int, Int, Int, Int)\n\nhit :: QInt -> Int -> QInt\nhit (n, x, y, z) k\n | k == n = (n, x, y + 1, z)\n | k == n + 1 = (n, x, y, z + 1)\n | k == n - 1 = (n, x + 1, y, z)\n | otherwise = (n, x, y, z)\n\n(?) :: Bool -> a -> a -> a\n(?) True x _ = x\n(?) False _ y = y\ninfixr 1 ?\n\ntestM :: Monad m => (a -> Bool) -> m a -> m a -> m a\ntestM f a b = f <$> a >>= bool b a\n\napplyM :: Monad m => (a -> m ()) -> m a -> m a\napplyM f a = a >>= f >> a\n\nzipMap :: (a -> b) -> [a] -> [(a, b)]\nzipMap f = map (\\a -> (a, f a))\n\nupdiv :: Int -> Int -> Int\nupdiv a b = (a + b - 1) `div` b\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe(fromJust)\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nimport Control.Monad.ST\nimport Data.Bool (bool)\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- ints\n hp <- listArray (1, n) <$> ints\n let (k, hs) = solve a b hp\n print k\n putStrLn (unwords $ map show hs)\n\nsolve :: Int -> Int -> UArray Int Int -> (Int, [Int])\nsolve a b hp = runST $ do\n dp <- newArray ((0, 0, 0, 0), (n, hm, hm, hm)) inf\n res <- fill dp sp\n fdp <- freeze dp\n pure (res, collect fdp sp)\n where\n n = snd $ bounds hp\n hm = 1 + maximum (elems hp)\n sp = (n, 0, 0, 0)\n hitRange = (2, n - 1)\n targets n = filter (inRange hitRange) [n - 1, n , n + 1]\n inf = (maxBound :: Int) `div` 2\n fill :: STUArray s QInt Int -> QInt -> ST s Int\n fill dp i@(k, x, y, z) =\n k < 1 ? pure 0 $\n testM (< inf) (readArray dp i) $\n applyM (writeArray dp i) $\n (hp ! k) - (x + z) * b - y * a < 0 ? fill dp (k - 1, 0, x, y) $\n (1 + ) . minimum <$> mapM (fill dp . hit i) (targets k)\n collect :: UArray QInt Int -> QInt -> [Int]\n collect dp i@(k, x, y, z) =\n k < 1 ? [] $\n (hp ! k) - (x + z) * b - y * a < 0 ? collect dp (k - 1, 0, x, y) $\n t:collect dp (hit i t) where t = minimumBy (comparing $ (dp !) . hit i) (targets k)\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ntype QInt = (Int, Int, Int, Int)\n\nhit :: QInt -> Int -> QInt\nhit (n, x, y, z) k\n | k == n = (n, x, y + 1, z)\n | k == n + 1 = (n, x, y, z + 1)\n | k == n - 1 = (n, x + 1, y, z)\n | otherwise = (n, x, y, z)\n\n(?) :: Bool -> a -> a -> a\n(?) True x _ = x\n(?) False _ y = y\ninfixr 1 ?\n\ntestM :: Monad m => (a -> Bool) -> m a -> m a -> m a\ntestM f a b = f <$> a >>= bool b a\n\napplyM :: Monad m => (a -> m ()) -> m a -> m a\napplyM f a = a >>= f >> a\n\nzipMap :: (a -> b) -> [a] -> [(a, b)]\nzipMap f = map (\\a -> (a, f a))\n"}], "negative_code": [{"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe(fromJust)\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nimport Control.Monad.ST\nimport Data.Functor (($>))\nimport Data.Bool (bool)\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- ints\n hp <- listArray (1, n) <$> ints\n let (k, hs) = solve a b hp\n print k\n putStrLn (unwords $ map show hs)\n\nsolve :: Int -> Int -> UArray Int Int -> (Int, [Int])\nsolve a b hp = runST $ do\n dp <- newArray ((0, 0, 0, 0), (n, hm, hm, hm)) (-1)\n res <- fill dp sp\n fdp <- freeze dp\n return (res + s, replicate s (n - 1) ++ collect fdp sp)\n where\n n = snd $ bounds hp\n hm = 1 + maximum (elems hp)\n s = (hp ! n + 1) `div` b\n sp = (n - 1, 0, s, 0)\n hitRange = (2, n - 1)\n targets n = filter (inRange hitRange) [n - 1, n , n + 1]\n inf = (maxBound :: Int) `div` 2\n fill :: STUArray s QInt Int -> QInt -> ST s Int\n fill dp i@(k, x, y, z) =\n k < 1 ? pure 0 $\n testM (>= 0) (readArray dp i) $\n (hp ! k) - (x + z) * b - y * a < 0 ? fill dp (k - 1, 0, x, y) $\n minimum <$> mapM (fill dp . hit i) (targets k) >>= \\res ->\n applyM (writeArray dp i) (res + 1)\n collect :: UArray QInt Int -> QInt -> [Int]\n collect dp i@(k, x, y, z) =\n k < 1 ? [] $\n (hp ! k) - (x + z) * b - y * a < 0 ? collect dp (k - 1, 0, x, y) $\n let (t, h) = bestHit dp i in t:collect dp h\n bestHit dp i@(k, _, _, _) = minimumBy (comparing (\\(_, h) -> dp ! h)) $ zipMap (hit i) (targets k)\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ntype QInt = (Int, Int, Int, Int)\n\nhit :: QInt -> Int -> QInt\nhit (n, x, y, z) k\n | k == n = (n, x, y + 1, z)\n | k == n + 1 = (n, x, y, z + 1)\n | k == n - 1 = (n, x + 1, y, z)\n | otherwise = (n, x, y, z)\n\n(?) :: Bool -> a -> a -> a\n(?) True x _ = x\n(?) False _ y = y\ninfixr 1 ?\n\ntestM :: Monad m => (a -> Bool) -> m a -> m a -> m a\ntestM f a b = f <$> a >>= bool b a\n\napplyM :: Monad m => (a -> m ()) -> a -> m a\napplyM f a = f a $> a\n\nzipMap :: (a -> b) -> [a] -> [(a, b)]\nzipMap f = map (\\a -> (a, f a))\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe(fromJust)\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\n\nimport Control.Monad.ST\nimport Data.Functor (($>))\nimport Data.Bool (bool)\nimport Data.List (minimumBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- ints\n hp <- listArray (1, n) <$> ints\n let (k, hs) = solve a b hp\n print k\n putStrLn (unwords $ map show hs)\n\nsolve :: Int -> Int -> UArray Int Int -> (Int, [Int])\nsolve a b hp = runST $ do\n dp <- newArray ((0, 0, 0, 0), (n, hm, hm, hm)) (-1)\n res <- fill dp sp\n fdp <- freeze dp\n return (res + s, replicate s (n - 1) ++ collect fdp sp)\n where\n n = snd $ bounds hp\n hm = 1 + maximum (elems hp)\n s = (hp ! n + 1) `updiv` b\n sp = (n - 1, 0, s, 0)\n hitRange = (2, n - 1)\n targets n = filter (inRange hitRange) [n - 1, n , n + 1]\n inf = (maxBound :: Int) `div` 2\n fill :: STUArray s QInt Int -> QInt -> ST s Int\n fill dp i@(k, x, y, z) =\n k < 1 ? pure 0 $\n testM (>= 0) (readArray dp i) $\n (hp ! k) - (x + z) * b - y * a < 0 ? fill dp (k - 1, 0, x, y) $\n minimum <$> mapM (fill dp . hit i) (targets k) >>= \\res ->\n applyM (writeArray dp i) (res + 1)\n collect :: UArray QInt Int -> QInt -> [Int]\n collect dp i@(k, x, y, z) =\n k < 1 ? [] $\n (hp ! k) - (x + z) * b - y * a < 0 ? collect dp (k - 1, 0, x, y) $\n let (t, h) = bestHit dp i in t:collect dp h\n bestHit dp i@(k, _, _, _) = minimumBy (comparing (\\(_, h) -> dp ! h)) $ zipMap (hit i) (targets k)\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ntype QInt = (Int, Int, Int, Int)\n\nhit :: QInt -> Int -> QInt\nhit (n, x, y, z) k\n | k == n = (n, x, y + 1, z)\n | k == n + 1 = (n, x, y, z + 1)\n | k == n - 1 = (n, x + 1, y, z)\n | otherwise = (n, x, y, z)\n\n(?) :: Bool -> a -> a -> a\n(?) True x _ = x\n(?) False _ y = y\ninfixr 1 ?\n\ntestM :: Monad m => (a -> Bool) -> m a -> m a -> m a\ntestM f a b = f <$> a >>= bool b a\n\napplyM :: Monad m => (a -> m ()) -> a -> m a\napplyM f a = f a $> a\n\nzipMap :: (a -> b) -> [a] -> [(a, b)]\nzipMap f = map (\\a -> (a, f a))\n\nupdiv :: Int -> Int -> Int\nupdiv a b = (a + b - 1) `div` b\n"}], "src_uid": "a9bad412597726f8cdc0cfa2da891bc4"} {"source_code": "import Control.Monad\r\n\r\ntoShow [] = \"\"\r\ntoShow (x:xs) = show x ++ \" \" ++ toShow xs\r\n\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n replicateM (read ts::Int) $ do\r\n input <- getLine\r\n let n = read input ::Int\r\n input <- getLine\r\n let d = map read . words $ input ::[Int]\r\n let a = scanl1 (+) d\r\n putStrLn $ if any (\\(x,y) -> x>=y && y/=0) $ zip a (tail d) then \"-1\" else toShow a\r\n return ()", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n \\ds -> case findA n ds of\n Just as -> mapM_ (\\a -> putStr (show a ++ \" \")) as >>\n putStrLn \"\"\n Nothing -> putStrLn \"-1\"\n\nmaxA (d:ds) = scanl (+) d ds\n\nfindA :: Int -> [Int] -> Maybe [Int]\nfindA n ds = let mA = maxA ds in\n if any (\\(a, d) -> d <= a && d > 0) (zip mA (tail ds))\n then Nothing\n else Just mA\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\n\r\nimport Control.Monad\r\nimport Control.Monad.Trans.State\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.Maybe\r\nimport Debug.Trace\r\nimport System.IO (BufferMode (NoBuffering), hSetBuffering, stdout)\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n casnum <- getInt\r\n ress <- forM [1 .. casnum] $ \\_ -> do\r\n n <- getInt\r\n d <- replicateM n getInt\r\n let a = scanl1 (+) d\r\n let only = all (\\(x, y) -> x < y || y == 0) $ zip a (tail d)\r\n let res = if only then a else [-1]\r\n pure res\r\n pure $ foldl1 (<>) $ map putInts ress\r\n\r\ntype SP = State P.ByteString\r\n\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs =\r\n let sepPrim =\r\n (,) ' '\r\n Prim.>$< Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Maybe\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n] <- ri\r\n ds <- ri\r\n return ds\r\n mapM_ (putStrLn.showAns.solve) tcs\r\n\r\nshowAns = maybe \"-1\" (unwords . map show)\r\n\r\nsolve (d:ds) = ans\r\n where\r\n tt = L.scanl' g (Just d) $ ds\r\n ans | all isJust tt = Just (map fromJust tt)\r\n | otherwise = Nothing\r\n\r\n g Nothing _ = Nothing\r\n g (Just a) b = f a b\r\n\r\n f prevA currD | length cands == 1 = Just (head cands)\r\n | otherwise = Nothing\r\n where\r\n cands = L.nub . filter (>=0) $ [prevA + currD, prevA - currD]\r\nsolve _ = error \"Empty input?\"\r\n"}, {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\n\ntype TC = [Int]\n\ntype Output = Maybe [Int]\n\ninput :: Scanner TC\ninput = numberOf int\n\nsolve :: TC -> Output\nsolve ds = guard (zip as (tail ds) >$> filter (snd >>> (/= 0)) >>> all (uncurry (<))) >> return as\n where\n as = scanl1 (+) ds\n\noutput :: Int -> Output -> C.ByteString\noutput _ = fmap (map show >>> unwords) >>> fromMaybe \"-1\" >>> C.pack\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- helpers\n(>$>) = flip ($)\n\ninfixl 0 >$>\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "f4b790bef9a6cbcd5d1f9235bcff7c8f"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n let readInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : _ <- readInts\n let check acc _ = do\n x : y : _ <- readInts\n let acc' = Map.insertWith (Set.union) y (Set.singleton x) acc\n acc'' = Map.insertWith (Set.union) x (Set.singleton y) acc'\n return acc''\n pathes <- foldM check Map.empty [1 .. n]\n let Just (start, _) = find ((== 1) . Set.size . snd)\n $ Map.toList pathes\n search (mp, i)\n | i < 0 = Nothing\n | Map.null mp = Just (show i, (mp, -1))\n | otherwise = do\n let s = mp Map.! i\n j : _ = Set.toList s\n s' = mp Map.! j\n t = Set.delete j s\n t' = Set.delete i s'\n mp' = if Set.null t\n then Map.delete i mp\n else Map.insert i t mp\n mp'' = if Set.null t'\n then Map.delete j mp'\n else Map.insert j t' mp'\n Just (show i, (mp'', j))\n answer = unfoldr search (pathes, start)\n putStrLn $ intercalate \" \" answer\n\n\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe(fromJust)\nimport GHC.Exts(groupWith)\n\nmain = do \n (s:ss) <- fmap (BS.lines) BS.getContents\n let n = readInt s\n input = map(map readInt . BS.words) . take n $ ss\n list = map (\\ [x,y] -> (x,y)) input ++\n map (\\ [x,y] -> (y,x)) input\n joinedList = map merge . groupWith fst $ list\n where merge l = (fst (head l), map snd l)\n \n allVertices = map head . group . sort . concat $ input\n [start,end] = map fst . filter ((<2) . length . snd) $ joinedList\n joinedMap = IM.fromList joinedList\n ans = takeWhile(/=end) . map fst $ iterate step (start, -1)\n step (u, prev) = let\n Just adj = IM.lookup u joinedMap\n [v] = adj \\\\ [prev]\n in (v,u)\n \n putStrLn . unwords . map show $ ans ++ [end]\n \n \nreadInt = fst . fromJust . BS.readInt"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n let readInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : _ <- readInts\n let check acc _ = do\n x : y : _ <- readInts\n let acc' = Map.insertWith (Set.union) y (Set.singleton x) acc\n acc'' = Map.insertWith (Set.union) x (Set.singleton y) acc'\n return acc''\n pathes <- foldM check Map.empty [1 .. n]\n let Just (start, _) = find ((== 1) . Set.size . snd)\n $ Map.toList pathes\n search (mp, i)\n | i < 0 = Nothing\n | Map.null mp = Just (show i, (mp, -1))\n | otherwise = do\n let s = mp Map.! i\n j : _ = Set.toList s\n s' = mp Map.! j\n t = Set.delete j s\n t' = Set.delete i s'\n mp' = if Set.null t\n then Map.delete i mp\n else Map.insert i t mp\n mp'' = if Set.null t'\n then Map.delete j mp'\n else Map.insert j t' mp'\n Just (show i, (mp'', j))\n answer = unfoldr search (pathes, start)\n putStrLn $ intercalate \" \" answer\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n let readInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : _ <- readInts\n let check acc _ = do\n x : y : _ <- readInts\n let acc' = Map.insertWith (Set.union) y (Set.singleton x) acc\n acc'' = Map.insertWith (Set.union) x (Set.singleton y) acc'\n return acc''\n pathes <- foldM check Map.empty [1 .. n]\n let Just (start, _) = find ((== 1) . Set.size . snd)\n $ Map.toList pathes\n search (mp, i)\n | i < 0 = Nothing\n | Map.null mp = Just (show i, (mp, -1))\n | otherwise = do\n let s = mp Map.! i\n j : _ = Set.toList s\n s' = mp Map.! j\n t = Set.delete j s\n t' = Set.delete i s'\n mp' = if Set.null t\n then Map.delete i mp\n else Map.insert i t mp\n mp'' = if Set.null t'\n then Map.delete j mp'\n else Map.insert j t' mp'\n Just (show i, (mp'', j))\n answer = unfoldr search (pathes, start)\n putStrLn $ intercalate \" \" answer\n\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe(fromJust)\nimport GHC.Exts(groupWith)\n\nmain = do \n (s:ss) <- fmap (BS.lines) BS.getContents\n let n = readInt s\n input = map(map readInt . BS.words) . take n $ ss\n list = map (\\ [x,y] -> (x,y)) input ++\n map (\\ [x,y] -> (y,x)) input\n joinedList = map merge . groupWith fst $ list\n where merge l = (fst (head l), map snd l)\n \n allVertices = map head . group . sort . concat $ input\n [start,end] = map fst . filter ((<2) . length . snd) $ joinedList\n joinedMap = IM.fromList joinedList\n ans = takeWhile(/=end) . map fst $ iterate step (start, -1)\n step (u, prev) = let\n Just adj = IM.lookup u joinedMap\n [v] = adj \\\\ [prev]\n in (v,u)\n \n print . IM.toList $ joinedMap\n putStrLn . unwords . map show $ ans ++ [end]\n \n \nreadInt = fst . fromJust . BS.readInt"}], "src_uid": "4c9d3e560f1ea152259ec838879b7512"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tcontent <- getContents\n\tlet\n\t\t[s, a, b, c] = map (\\x -> read x :: Double). concat. map words. lines $ content\n\t\tx = max 0 (a*s/ (b + a + c))\n\t\ty = max 0 (b*s / (a+b+c))\n\t\tz = max 0 ( s - x - y)\n\tputStrLn $ (show x) ++ \" \" ++ (show y) ++ \" \" ++ (show z)\n", "positive_code": [{"source_code": "solve :: String -> String -> [Double]\nsolve str1 str2 = \n let \n s = a + b + c\n s0 = (read str1)::Double\n [a, b, c] = map (\\x -> (read x)::Double) (words str2)\n in\n if s == 0 then [0, 0, 0]\n else [a*s0/s, b*s0/s, c*s0/s]\n\njoin delim [] = []\njoin delim (x:xs) = x ++ delim ++ join delim xs\n\nmain = \n do\n str1 <- getLine \n str2 <- getLine \n putStrLn $ join \" \" (map show (solve str1 str2))\n"}, {"source_code": "main = getContents >>= putStrLn. unwords. map show. (\\(s:as) -> let ss = s/sum as in if sum as == 0 then replicate 3 0 else map (*ss) as). map read. concat. map words. lines\n"}, {"source_code": "main = getContents >>= putStrLn. unwords. map show. (\\(s:as) -> let ss = s/(sum as) in if sum as == 0 then replicate 3 0 else map (*ss) as). map read. words\n"}, {"source_code": "\nimport Monad (liftM)\n\nsolve :: Fractional d => d -> d -> d -> d -> (d, d, d)\nsolve a b c s\n | a + b + c == 0 = (0, 0, 0)\n | otherwise = (a*s / abc, b*s / abc, c*s / abc)\n where\n abc = a + b + c\n\nmain :: IO ()\nmain = do\n s <- readLn\n [a,b,c] <- liftM (map read . words) getLine\n let (x,y,z) = solve a b c s\n putStrLn $ concat [show x, \" \", show y, \" \", show z]\n"}, {"source_code": "import Control.Applicative\nimport Text.Printf\n\nmain = do\n s <- readLn :: IO Double\n [a,b,c] <- map read.words <$> getLine\n if all(0==)[a,b,c]\n then putStrLn \"0 0 0\"\n else printf \"%f %f %f\\n\" (s*a/(a+b+c)) (s*b/(a+b+c)) (s*c/(a+b+c))"}, {"source_code": "s :: [Integer] -> [Double]\ns [s,0,0,0] = [fromIntegral s,0,0.0]\ns [s,a,b,c] = [fromIntegral s * fromIntegral a / ss, fromIntegral s * fromIntegral b / ss, fromIntegral s * fromIntegral c / ss] where\n ss = fromIntegral (a + b + c)\nmain = interact $ unwords . map show . s . map read . words"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tcontent <- getContents\n\tlet\n\t\t[s, a, b, c] = map (\\x -> read x :: Double). concat. map words. lines $ content\n\t\tx = a*s/ (b + a + c)\t\n\t\ty = b*s / (a+b+c)\n\t\tz = s - x - y\n\tputStrLn $ (show x) ++ \" \" ++ (show y) ++ \" \" ++ (show z)\n"}], "src_uid": "0a9cabb857949e818453ffe411f08f95"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nnewtype State s a = State { runState :: s -> (a,s) }\nnewtype Identity a = Identity { runIdentity :: a }\n\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Functor Identity where\n fmap f = runIdentity >>> f >>> Identity\n\ninstance Monad Identity where\n return = Identity\n x >>= f = f (runIdentity x)\n\ninstance Applicative Identity where\n pure = return\n (<*>) = ap\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Char where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nfixMemoArray :: (Ix a) => (a,a) -> RecFun Identity a b -> Array a b\nfixMemoArray b f = arr\n where\n g y = Identity $ arr ! y\n arr = listArray b [ runIdentity $ f g x | x <- range b ]\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\ndoit :: Int -> [Int] -> Maybe [Int]\ndoit k l | null cs || (foldl' (.&.) (2^k-1) cs) /= 0 = Nothing\n | otherwise = Just cs\n where cs = filter (flip testBit k) l\n\nmain = do\n n <- readInt <$> B.getLine\n l <- map readInt . B.words <$> B.getLine\n let bs = last $ catMaybes $ [doit k l | k <- [0..30]] \n print (length bs)\n putStrLn $ unwords $ map show bs\n\n", "positive_code": [{"source_code": "import Data.Bits\nmaxV = 30\nverify :: Int -> [Int] -> Bool\nverify v xs = 0 == mod (foldr (.&.) (2^v - 1) xs) (2^v)\nsubsetAt :: Int -> [Int] -> [Int]\nsubsetAt v xs = filter (`testBit` v) xs\nsolve xs = (show (length sols)) ++ \"\\n\" ++ unwords (map show sols)\n where sols = head [s | v <- [maxV, maxV-1..0], let s = subsetAt v xs, verify v s]\nmain = putStrLn.solve.map read.tail.words =<< getContents"}, {"source_code": "import Data.Bits\n\nlowbit :: Int -> Int\nlowbit x = x .&. (-x)\n\ngetVal :: [Int] -> Int\ngetVal [] = -1\ngetVal xs = if andAll /= 0 then lowbit andAll else -1\n\twhere\n\t\tandAll = foldl1 (.&.) xs\n\ngetBest :: [Int] -> [Int] -> [Int]\ngetBest xs ys\n\t| valX /= valY = if valX > valY then xs else ys\n\t| otherwise = if length xs > length ys then xs else ys\n\twhere\n\t\tvalX = getVal xs\n\t\tvalY = getVal ys\n\ncalc :: [Int] -> [Int]\ncalc xs = foldl1 getBest (xs : [filter (\\x -> testBit x b) xs | b <- [0 .. 30]])\n\nhandle :: [String] -> [[String]]\nhandle (_ : sa) = [[show $ length res], map show res]\n\twhere\n\t\tres = calc $ map read sa\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (liftM)\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\nimport Data.List (foldl', group, sort)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\ntoInt64 :: Int -> Int64\ntoInt64 = fromIntegral\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n \nforMask :: [Int64] -> Int64 -> [Int64]\nforMask xs mask = filter ((== mask) . (.&. mask)) xs\n\ncheck :: [Int64] -> Int -> Bool\ncheck xs v = acc .&. (mask - 1) == 0\n where mask = 2 ^ v :: Int64\n acc = foldl' (.&.) (-1 :: Int64) $ forMask xs mask\n\nsolve :: [Int] -> [Int]\nsolve xs = if null vs\n then xs\n else map fromIntegral $ forMask bs (2 ^ (head vs))\n where bs = map toInt64 xs\n vs = filter (check bs) [32, 31 .. 0]\n\nmain = do\n (n:xs) <- liftM (map readInt . BS.words) BS.getContents\n let result = map head . group . sort $ solve xs\n print $ length result\n putStrLn . unwords $ map show result\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (liftM)\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\nimport Data.List (foldl', group, sort)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\ntoInt64 :: Int -> Int64\ntoInt64 = fromIntegral\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n\ncheck :: Int -> [Int64] -> Bool\ncheck v xs = acc .&. (limit - 1) == 0\n where limit = 2 ^ v :: Int64\n acc = foldl' (.&.) (-1 :: Int64) $ filter (>= limit) xs\n\nsolve :: [Int] -> [Int]\nsolve xs = filter (>= (2 ^ v)) xs\n where bs = map toInt64 xs\n v = go 0 32\n\n go lo hi | lo + 1 == hi = lo\n | check mi bs = go mi hi\n | otherwise = go lo mi\n where mi = (lo + hi) `div` 2\n\nmain = do\n (n:xs) <- liftM (map readInt . BS.words) BS.getContents\n let result = map head . group . sort $ solve xs\n print $ length result\n putStrLn . unwords $ map show result\n"}, {"source_code": "import Data.Bits\n\nlowbit :: Int -> Int\nlowbit x = x .&. (-x)\n\ngetBest :: [Int] -> [Int] -> [Int]\ngetBest [] [] = []\ngetBest [] ys = ys\ngetBest xs [] = xs\ngetBest xs ys\n\t| valX /= valY = if valX > valY then xs else ys\n\t| otherwise = if length xs > length ys then xs else ys\n\twhere\n\t\tvalX = lowbit $ foldl1 (.&.) xs\n\t\tvalY = lowbit $ foldl1 (.&.) ys\n\ncalc :: [Int] -> [Int]\ncalc xs = if res /= [] then res else xs\n\twhere\n\t\tres = foldl1 getBest [filter (\\x -> (x .&. (shift b 1)) /= 0) xs | b <- [0 .. 30]]\n\nhandle :: [String] -> [[String]]\nhandle (_ : sa) = [[show $ length res], map show res]\n\twhere\n\t\tres = calc $ map read sa\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "import Data.Bits\n\nlowbit :: Int -> Int\nlowbit x = x .&. (-x)\n\ngetBest :: [Int] -> [Int] -> [Int]\ngetBest [] [] = []\ngetBest [] ys = ys\ngetBest xs [] = xs\ngetBest xs ys\n\t| valX > valY = xs\n\t| valX < valY = ys\n\t| otherwise = if length xs > length ys then xs else ys\n\twhere\n\t\tvalX = lowbit $ foldl1 (.&.) xs\n\t\tvalY = lowbit $ foldl1 (.&.) ys\n\ncalc :: [Int] -> [Int]\ncalc xs = foldl1 getBest [filter (\\x -> (x .&. (shift b 1)) /= 0) xs | b <- [0 .. 30]]\n\nhandle :: [String] -> [[String]]\nhandle (_ : sa) = [[show $ length res], map show res]\n\twhere\n\t\tres = calc $ map read sa\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (liftM)\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\nimport Data.List (foldl', group, sort)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\ntoInt64 :: Int -> Int64\ntoInt64 = fromIntegral\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n\ncheck :: Int -> [Int64] -> Bool\ncheck v xs = acc .&. (limit - 1) == 0\n where limit = 2 ^ v\n acc = foldl' (.&.) (-1) $ filter (>= limit) xs\n\nsolve :: [Int] -> [Int]\nsolve xs = filter (>= (2 ^ v)) xs\n where bs = map toInt64 xs\n v = go 0 32\n\n go lo hi | lo + 1 == hi = lo\n | check mi bs = go mi hi\n | otherwise = go lo mi\n where mi = (lo + hi) `div` 2\n\nmain = do\n (n:xs) <- liftM (map readInt . BS.words) BS.getContents\n let result = map head . group . sort $ solve xs\n print $ length result\n putStrLn . unwords $ map show result\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (liftM)\nimport Data.Bits ((.&.))\nimport Data.Int (Int64)\nimport Data.List (foldl', sort)\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\ntoInt64 :: Int -> Int64\ntoInt64 = fromIntegral\n\nreadInt :: BS.ByteString -> Int\nreadInt s = case BS.readInt s of\n Just (x, _) -> x\n Nothing -> error \"Can't parse Int\"\n\ncheck :: Int -> [Int64] -> Bool\ncheck v xs = acc .&. (limit - 1) == 0\n where limit = 2 ^ v\n acc = foldl' (.&.) (-1) $ filter (>= limit) xs\n\nsolve :: [Int] -> [Int]\nsolve xs = filter (>= (2 ^ v)) xs\n where bs = map toInt64 xs\n v = go 0 32\n\n go lo hi | lo + 1 == hi = lo\n | check mi bs = go mi hi\n | otherwise = go lo mi\n where mi = (lo + hi) `div` 2\n\nmain = do\n (n:xs) <- liftM (map readInt . BS.words) BS.getContents\n let result = solve xs\n print $ length result\n putStrLn . unwords $ map show result\n"}], "src_uid": "54c23dda2aa1d58ecf22c03015dca55c"} {"source_code": "import Data.List\n \nsuffixAfterSubstring :: String -> String -> Maybe String\nsuffixAfterSubstring string substring = let\n ends = filter (isPrefixOf substring) (tails string)\n in stripPrefix substring (head ends)\n\ncanSeeSequences :: String -> String -> String -> Bool\ncanSeeSequences actual s1 s2 \n | not (s1 `isInfixOf` actual) = False\n | otherwise = case (suffixAfterSubstring actual s1) of\n Nothing -> False\n Just rest -> s2 `isInfixOf` rest\n\nsolve :: (String, String, String) -> String\nsolve (actual, s1, s2)\n | canSeeForward && canSeeBackward = \"both\"\n | canSeeForward = \"forward\"\n | canSeeBackward = \"backward\"\n | otherwise = \"fantasy\"\n where\n canSeeForward = canSeeSequences actual s1 s2\n canSeeBackward = canSeeSequences (reverse actual) s1 s2\n\nparse :: [String] -> (String, String, String) \nparse ls = (head ls, head $ tail ls, last ls)\n \nmain = interact $ solve . parse . lines ", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsearch :: String -> String -> Maybe String\nsearch = do\n sign <- id\n return $ do\n ss <- iterate (drop 1)\n return $ do\n s <- find (and . zipWith (==) sign) ss\n let (as, bs) = splitAt (length sign) s\n guard $ as == sign\n return bs\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n [s, sign1, sign2] <- take 3\n let check n x = maybe 0 (const n)\n $ return x >>= search sign1 >>= search sign2\n let idx = check 1 s + check 3 (reverse s)\n return $ [\"fantasy\", \"forward\", undefined, \"backward\", \"both\"] !! idx\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "module Main where\n\nimport Control.Applicative (liftA3)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = liftA3 solve bsGetLine bsGetLine bsGetLine >>= putStrLn\n\n-- https://github.com/haskell/bytestring/issues/13\nbsGetLine :: IO BS.ByteString\nbsGetLine = BS.pack <$> getLine\n\nsolve :: BS.ByteString -> BS.ByteString -> BS.ByteString -> String\nsolve flags a b= case (follows flags, follows (BS.reverse flags)) of\n (True, True) -> \"both\"\n (True, _) -> \"forward\"\n (_, True) -> \"backward\"\n _ -> \"fantasy\"\n where\n follows f = case BS.breakSubstring a f of\n (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest\nsolve flags a b = show $ BS.length a"}, {"source_code": "l=length\ns f a b|take(l a)b==a=f$drop(l a)b|null b=0|1>0=s f a(tail b)\nc a b l=s(s(const 1)b)a l\nz[x,a,b]=[\"fantasy\",\"backward\",\"forward\",\"both\"]!!(c a b x*2+c a b(reverse x))\nmain=interact$z.lines\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport System.IO (hSetNewlineMode, universalNewlineMode, stdin)\n\n(-->) = flip fmap\n\n-- does s contain a followed by b\nfollows :: ByteString -> ByteString -> ByteString -> Bool\nfollows s a b =\n case BS.breakSubstring a s of\n (x,y) | BS.null y -> False\n | otherwise -> BS.isInfixOf b (BS.drop (BS.length a) y)\n\nmain = do\n hSetNewlineMode stdin universalNewlineMode\n s <- getLine --> BS.pack\n a <- getLine --> BS.pack\n b <- getLine --> BS.pack\n let forward = follows s a b\n backward = follows (BS.reverse s) a b\n answer = case (forward,backward) of\n (True,True) -> \"both\"\n (True,_) -> \"forward\"\n (_,True) -> \"backward\"\n otherwise -> \"fantasy\"\n putStrLn answer\n \n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nfindSub :: (Eq a) => [a] -> [a] -> [(Int, Int)]\nfindSub xs ys = findSub' 0 xs ys\n where\n findSub' n xs [] = []\n findSub' n xs ys\n | xs `isPrefixOf` ys\n = (n, n + length xs - 1) : findSub' (n + 1) xs (tail ys)\n | otherwise = findSub' (n + 1) xs $ tail ys\n\nfindHead, findLast :: (Eq a) => [a] -> [a] -> Maybe Int\nfindHead x xs\n | null result = Nothing\n | otherwise = Just $ snd $ minimum result\n where result = findSub x xs\n\nfindLast x xs\n | null result = Nothing\n | otherwise = Just $ fst $ maximum result\n where result = findSub x xs\n\npatternExists :: (Eq a) => [a] -> [a] -> [a] -> Bool\npatternExists a b xs = fromMaybe False $ do\n ai <- findHead a xs\n bi <- findLast b xs\n return $ ai < bi\n\nmain = do\n train <- getLine\n a <- getLine\n b <- getLine\n case (patternExists a b train, patternExists a b $ reverse train) of\n (True, True) -> putStrLn \"both\"\n (True, False) -> putStrLn \"forward\"\n (False, True) -> putStrLn \"backward\"\n (False, False) -> putStrLn \"fantasy\"\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsearch :: String -> String -> Maybe String\nsearch = do\n sign <- id\n return $ do\n ss <- iterate (drop 1)\n return $ do\n s <- find (and . zipWith (==) sign) ss\n let (as, bs) = splitAt (length sign) s\n guard $ as == sign\n return bs\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n [s, sign1, sign2] <- take 3\n let check n x = maybe 0 (const n)\n $ return x >>= search sign1 >>= search sign2\n let idx = check 1 s + check 3 (reverse s)\n return $ [\"fantasy\", \"forward\", undefined, \"backword\", \"both\"] !! idx\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "module Main where\n\nimport Control.Applicative (liftA3)\nimport System.IO (hSetNewlineMode, universalNewlineMode, stdin)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n hSetNewlineMode stdin universalNewlineMode\n result <- liftA3 solve BS.getLine BS.getLine BS.getLine\n putStrLn result\n\nsolve :: BS.ByteString -> BS.ByteString -> BS.ByteString -> String\n-- solve flags a b= case (follows flags, follows (BS.reverse flags)) of\n-- (True, True) -> \"both\"\n-- (True, _) -> \"forward\"\n-- (_, True) -> \"backward\"\n-- _ -> \"fantasy\"\n-- where\n-- follows f = case BS.breakSubstring a f of\n-- (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest\nsolve flags a b = show $ BS.length a"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as BS\nimport Control.Applicative (liftA3)\n\nmain :: IO ()\nmain = liftA3 solve BS.getLine BS.getLine BS.getLine >>= putStrLn\n\nsolve :: BS.ByteString -> BS.ByteString -> BS.ByteString -> String\nsolve flags a b = case (follows flags, follows (BS.reverse flags)) of\n (True, True) -> \"both\"\n (True, _) -> \"forward\"\n (_, True) -> \"backward\"\n _ -> \"fantasy\"\n where\n follows f = case BS.breakSubstring a f of\n (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest"}, {"source_code": "module Main where\n\nimport System.IO\nimport Control.Applicative (liftA3)\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = hSetNewlineMode stdin universalNewlineMode >> liftA3 solve BS.getLine BS.getLine BS.getLine >>= putStrLn\n\nsolve :: BS.ByteString -> BS.ByteString -> BS.ByteString -> String\nsolve flags a b= case (follows flags, follows (BS.reverse flags)) of\n (True, True) -> \"both\"\n (True, _) -> \"forward\"\n (_, True) -> \"backward\"\n _ -> \"fantasy\"\n where\n follows f = case BS.breakSubstring a f of\n (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest"}, {"source_code": "module Main where\n\nimport Control.Applicative (liftA3)\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = liftA3 solve BS.getLine BS.getLine BS.getLine >>= putStrLn\n\nsolve :: BS.ByteString -> BS.ByteString -> BS.ByteString -> String\n-- solve flags a b= case (follows flags, follows (BS.reverse flags)) of\n-- (True, True) -> \"both\"\n-- (True, _) -> \"forward\"\n-- (_, True) -> \"backward\"\n-- _ -> \"fantasy\"\n-- where\n-- follows f = case BS.breakSubstring a f of\n-- (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest\nsolve flags a b = show $ BS.length a"}, {"source_code": "module Main where\n\nimport Control.Applicative (liftA3)\nimport System.IO (hSetNewlineMode, universalNewlineMode, stdin)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = liftA3 solve bsGetLine bsGetLine bsGetLine >>= putStrLn\n\nbsGetLine :: IO BS.ByteString\nbsGetLine = BS.pack <$> getLine\n\nsolve :: BS.ByteString -> BS.ByteString -> BS.ByteString -> String\n-- solve flags a b= case (follows flags, follows (BS.reverse flags)) of\n-- (True, True) -> \"both\"\n-- (True, _) -> \"forward\"\n-- (_, True) -> \"backward\"\n-- _ -> \"fantasy\"\n-- where\n-- follows f = case BS.breakSubstring a f of\n-- (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest\nsolve flags a b = show $ BS.length a"}, {"source_code": "module Main where\n\nimport Control.Applicative (liftA3)\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = solve . BS.lines <$> BS.getContents >>= putStrLn\n\nsolve :: [BS.ByteString] -> String\n-- solve [flags, a, b] = case (follows flags, follows (BS.reverse flags)) of\n-- (True, True) -> \"both\"\n-- (True, _) -> \"forward\"\n-- (_, True) -> \"backward\"\n-- _ -> \"fantasy\"\n-- where\n-- follows f = case BS.breakSubstring a f of\n-- (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest\nsolve [flags, a, b] = BS.unpack flags"}, {"source_code": "module Main where\n\nimport Control.Applicative (liftA3)\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = solve . BS.lines <$> BS.getContents >>= putStrLn\n\nsolve :: [BS.ByteString] -> String\nsolve [flags, a, b] = case (follows flags, follows (BS.reverse flags)) of\n (True, True) -> \"both\"\n (True, _) -> \"forward\"\n (_, True) -> \"backward\"\n _ -> \"fantasy\"\n where\n follows f = case BS.breakSubstring a f of\n (_, rest) -> (not . BS.null) rest && b `BS.isInfixOf` BS.drop (BS.length a) rest\n"}, {"source_code": "s(a:x)b|h==a=s x t|[]==b=0|1>0=s(a:x)t where(h,t)=splitAt(length a)b\ns _ _=1\nz(x:t)=[\"fantasy\",\"backward\",\"forward\",\"both\"]!!(s t x*2+s t(reverse x))\nmain=interact$z.lines\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport GHC.IO.Handle (hSetNewlineMode, NewlineMode(..), Newline(..))\nimport System.IO (stdin)\n\n-- does s contain a followed by b\nfollows :: ByteString -> ByteString -> ByteString -> Bool\nfollows s a b =\n case BS.breakSubstring a s of\n (x,y) | BS.null y -> False\n | otherwise -> BS.isInfixOf b y\n\nmain = do\n hSetNewlineMode stdin (NewlineMode CRLF LF)\n s <- BS.getLine\n a <- BS.getLine\n b <- BS.getLine\n let forward = follows s a b\n backward = follows (BS.reverse s) a b\n answer = case (forward,backward) of\n (True,True) -> \"both\"\n (True,_) -> \"forward\"\n (_,True) -> \"backward\"\n otherwise -> \"fantasy\"\n putStrLn answer\n \n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\n\n-- does s contain a followed by b\nfollows :: ByteString -> ByteString -> ByteString -> Bool\nfollows s a b =\n case BS.breakSubstring a s of\n (x,y) | BS.null y -> False\n | otherwise -> BS.isInfixOf b y\n\nmain = do\n s <- BS.getLine\n a <- BS.getLine\n b <- BS.getLine\n let forward = follows s a b\n backward = follows (BS.reverse s) a b\n answer = case (forward,backward) of\n (True,True) -> \"both\"\n (True,_) -> \"forward\"\n (_,True) -> \"backward\"\n otherwise -> \"fantasy\"\n putStrLn answer\n \n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\n\n-- does s contain a followed by b\nfollows :: ByteString -> ByteString -> ByteString -> Bool\nfollows s a b =\n case BS.breakSubstring a s of\n (x,y) | BS.null y -> False\n | otherwise -> BS.isInfixOf b y\n\nmain = do\n s <- BS.getLine\n a <- BS.getLine\n b <- BS.getLine\n let forward = follows s a b\n backward = follows (BS.reverse s) a b\n answer = case (forward,backward) of\n (True,True) -> \"both\"\n (True,_) -> \"forward\"\n (_,True) -> \"backward\"\n otherwise -> \"fantasy\"\n putStrLn $ \"s: \" ++ show s\n putStrLn $ \"a: \" ++ show a\n putStrLn $ \"b: \" ++ show b\n putStrLn answer\n \n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport GHC.IO.Handle (hSetNewlineMode, NewlineMode(..), Newline(..))\nimport System.IO (stdin)\n\n(-->) = flip fmap\n\n-- does s contain a followed by b\nfollows :: ByteString -> ByteString -> ByteString -> Bool\nfollows s a b =\n case BS.breakSubstring a s of\n (x,y) | BS.null y -> False\n | otherwise -> BS.isInfixOf b y\n\nmain = do\n hSetNewlineMode stdin (NewlineMode CRLF CRLF)\n s <- getLine --> BS.pack\n a <- getLine --> BS.pack\n b <- getLine --> BS.pack\n let forward = follows s a b\n backward = follows (BS.reverse s) a b\n answer = case (forward,backward) of\n (True,True) -> \"both\"\n (True,_) -> \"forward\"\n (_,True) -> \"backward\"\n otherwise -> \"fantasy\"\n putStrLn answer\n \n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nfindSub :: (Eq a) => [a] -> [a] -> [Int]\nfindSub xs ys = findSub' 0 xs ys\n where\n findSub' n xs [] = []\n findSub' n xs ys\n | xs `isPrefixOf` ys = n : findSub' (n + 1) xs (tail ys)\n | otherwise = findSub' (n + 1) xs $ tail ys\n\nfindHead x xs\n | null result = Nothing\n | otherwise = Just $ minimum result\n where result = findSub x xs\n\nfindLast x xs\n | null result = Nothing\n | otherwise = Just $ maximum result\n where result = findSub x xs\n\npatternExists a b xs = fromMaybe False $ do\n ai <- findHead a xs\n bi <- findLast b xs\n return $ ai < bi\n\nmain = do\n train <- getLine\n a <- getLine\n b <- getLine\n case (patternExists a b train, patternExists b a train) of\n (True, True) -> putStrLn \"both\"\n (True, False) -> putStrLn \"forward\"\n (False, True) -> putStrLn \"backward\"\n (False, False) -> putStrLn \"fantasy\"\n"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nfindSub :: (Eq a) => [a] -> [a] -> [Int]\nfindSub xs ys = findSub' 0 xs ys\n where\n findSub' n xs [] = []\n findSub' n xs ys\n | xs `isPrefixOf` ys = n : findSub' (n + 1) xs (tail ys)\n | otherwise = findSub' (n + 1) xs $ tail ys\n\nfindHead x xs\n | null result = Nothing\n | otherwise = Just $ minimum result\n where result = findSub x xs\n\nfindLast x xs\n | null result = Nothing\n | otherwise = Just $ maximum result\n where result = findSub x xs\n\npatternExists a b xs = fromMaybe False $ do\n ai <- findHead a xs\n bi <- findLast b xs\n return $ ai < bi\n\nmain = do\n train <- getLine\n a <- getLine\n b <- getLine\n case (patternExists a b train, patternExists a b $ reverse train) of\n (True, True) -> putStrLn \"both\"\n (True, False) -> putStrLn \"forward\"\n (False, True) -> putStrLn \"backward\"\n (False, False) -> putStrLn \"fantasy\"\n"}, {"source_code": "import Data.List\n\nfindSub :: (Eq a) => [a] -> [a] -> [Int]\nfindSub xs ys = findSub' 0 xs ys\n where\n findSub' n xs [] = []\n findSub' n xs ys\n | xs `isPrefixOf` ys = n : findSub' (n + 1) xs (tail ys)\n | otherwise = findSub' (n + 1) xs $ tail ys\n\nmain = do\n train <- getLine\n a <- getLine\n b <- getLine\n let ais = findSub a train\n bis = findSub b train\n case null ais || null bis of\n True -> putStrLn \"fantasy\"\n _ -> case (maximum ais > minimum bis, minimum ais < maximum bis) of\n (False, True) -> putStrLn \"forward\"\n (True, False) -> putStrLn \"backward\"\n _ -> putStrLn \"both\"\n"}], "src_uid": "c3244e952830643938d51ce14f043d7d"} {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Bits\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain = do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n a <- readInts\n let ans = foldl' gcd 0 $ do\n i <- [0..29] :: [Int]\n return $ length $ filter id $ map (`testBit` i) a\n putStrLn $ unwords $ map show $ filter ((==0) . (ans `mod`)) [1..n]\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, as :: [Int]}\n\ninput :: Scanner TC\ninput = do\n n <- int\n as <- n >< int\n return TC {..}\n\ntype Output = [Int]\n\noutput :: Output -> C.ByteString\noutput = map showB >>> C.unwords\n\nsolve :: TC -> Output\nsolve TC {..} = filter ((== 0) . (g `mod`)) [1 .. n]\n where\n g = foldl1 gcd [countBy (`testBit` b) as | b <- [0 .. 29]]\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Data.Bits\n\ncountBits:: [Int] -> Int -> Int\ncountBits nums pos = length $ filter (\\x -> x.&.(2^pos) > 0) nums\ngetNumBits nums = countBits nums <$> [0..29]\nallDivisible n = all (\\x -> x`mod`n == 0)\ngetPossibleCommonFactor nums = filter (`allDivisible` nums)\ncodeforceIntList = concatMap (\\x->show x ++ \" \")\n\nrun 0 = return 0\nrun t = do\n n <- getLine\n a <- getLine\n putStrLn $ codeforceIntList $ getPossibleCommonFactor (getNumBits $ read <$> words a) [1..read n]\n run $ t-1\n\nmain = getLine >>= run . read\n "}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\nimport Data.Bits\r\n\r\nfactors :: Integral t => t -> [t]\r\nfactors n = factors1 ++ go factors1 [] where\r\n factors1 = filter ((==0).mod n) $ takeWhile (\\x->x*x<=n) [1..n]\r\n go [] ys = ys\r\n go (x:xs) ys = if x*x==n then ys else go xs $ n`div`x : ys\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n as <- readv\r\n let\r\n counts = [ DL.length $ DL.filter (`testBit` i) as | i<-[0..31]]\r\n g = foldr1 gcd counts\r\n gfacs = if g==0 then [1..n] else factors g \r\n printv gfacs\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: IO [Int]\r\nreadv = fmap read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\nimport Data.Bits\r\n\r\nfactors :: Int->Int->[Int]\r\nfactors m n\r\n | m == 0 = [1..n]\r\n | otherwise = let\r\n cs = takeWhile (\\i->i*i<=m) [1..m-1] ++ [m]\r\n fs = filter ((0==).mod m) cs\r\n in fs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n as <- readv\r\n let\r\n counts = [ DL.length $ DL.filter (`testBit` i) as | i<-[0..31]]\r\n g = foldr1 gcd counts\r\n gfacs = if g==0 then [1..n] else factors g n\r\n printv gfacs\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: IO [Int]\r\nreadv = fmap read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\nimport Data.Bits\r\n\r\nfactors :: Int->Int->[Int]\r\nfactors m n\r\n | m == 0 = [1..n]\r\n | otherwise = let\r\n cs = takeWhile (\\i->i*i<=m) [1..m-1] ++ [m]\r\n fs = filter ((0==).mod m) cs\r\n in fs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n as <- readv\r\n let\r\n counts = [ DL.length $ DL.filter (`testBit` i) as | i<-[0..31]]\r\n g = foldr1 gcd counts\r\n gfacs = if g==0 then [1..n] else filter (\\x->g`mod`x==0) $ takeWhile (\\x->x*x<=g) [1..g-1] ++ [g]\r\n printv gfacs\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: IO [Int]\r\nreadv = fmap read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\nimport Data.Bits\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n as <- readv\r\n let \r\n counts = [ DL.length $ DL.filter (`testBit` i) as | i<-[0..31]]\r\n g = foldr1 gcd counts\r\n gfacs = if g==0 then [1..n] else filter (\\x->g`mod`x==0) $ takeWhile (\\x->x*x<=g) [1..n-1] ++ [n]\r\n printv gfacs\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: IO [Int]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}], "src_uid": "81f4bc9ac72ed39da8614131954d0d99"} {"source_code": "main = do interact (show . gao . map read . words)\ngao (n:x:m:y:_) = (if n + m < d then 1 else 2) + div (f n m + f m n) 2 where\n\td = abs (x - y)\n\tf a b = let g c = if 1 <= c && c <= b then 1 else 0 in\n\t\tsum [2 * e - v |\n\t\t\t(l, r) <- map (\\i -> (abs $ d - i, d + i)) [1 .. a],\n\t\t\tv <- [g l + g r + 2 * max 0 (min b (r-1) - max 1 (l+1) + 1)],\n\t\t\te <- [max 1 v]]\n", "positive_code": [{"source_code": "main = interact solve\nsolve input = output where\n [n,x,m,y] = map (read::String->Integer) $ words input\n output = show $ answer l s\n d = abs (x-y)\n l = max n m\n s = min n m\n answer v w\n | d == 0 = v + 1\n | v + w <= d = v + w + 1\n | v <= d = v + w + 1 + (v+w-d)^2\n | v == w = answer (v-1) (w-1) + 4*d\n | v <= w + d = answer (v-1) w + 2*(w-v+d)+1\n | otherwise = answer (v-1) w + 1\n"}], "negative_code": [{"source_code": "main = do interact (show . gao . map read . words)\ngao (n:x:m:y:_) = 2 + div (f n m + f m n) 2 where\n\td = abs (x - y)\n\tf a b = let g c = if 1 <= c && c <= b then 1 else 0 in\n\t\tsum [2 * e - v |\n\t\t\t(l, r) <- map (\\i -> (abs $ d - i, d + i)) [1 .. a],\n\t\t\tv <- [g l + g r + 2 * max 0 (min b (r-1) - max 1 (l+1) + 1)],\n\t\t\te <- [max 1 v]]\n"}, {"source_code": "main = do interact (show . gao . map read . words)\ngao (n:x:m:y:_) = 1 + n + m + sum [max 0 $ (min m (d+i) - max 1 (d-i)) * 2 + 1 | d <- [abs (x - y)], i <- [0 .. n - 1]]\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = max n m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + m + 1 + 2*n^2 - (n-m+d)^2\n | n<=d = n + m + 1 + 2*n^2\n | m<= d+n = n + m + 1 + 2*(n-d)^2 - (n-d) + (d-n+d)^2 + (m-d)^2\n | otherwise = n + m + 1 + 2*(n-d)^2 - (n-d) + (d-n+d)^2 + n^2\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + m + 1 + 2*n^2 - (n-m+d)^2\n | n<=d = n + m + 1 + 2*n^2\n | m<= d+n = n + m + 1 + d^2 + n^2 - (n-m+d)^2 + (n-d)^2 -(n-d)\n | otherwise = n + m + 1 + d^2 + n^2 + (n-d)^2 -(n-d)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + d + 1 + n^2 + n^2 - (n-m+d)^2\n | n<=d = n + d + 1 + n^2 + n^2\n | m<= d+n = n + 1 + d^2 + n^2 - (n-m+d)^2 + (n-d)^2 +(m-d)\n | otherwise = n + 1 + d^2 + n^2 + (n-d)^2 +(m-d)\n--n=1 m=5 d=4"}, {"source_code": "main = interact solve\nsolve input = output where\n [n,x,m,y] = map (read::String->Int) $ words input\n output = show $ answer l s\n d = abs (x-y)\n l = max n m\n s = min n m\n answer v w\n | d == 0 = v + 1\n | v + w <= d = v + w + 1\n | v <= d = v + w + 1 + (v+w-d)^2\n | v == w = answer (v-1) (w-1) + 4*d\n | v <= w + d = answer (v-1) w + 2*(w-v+d)\n | otherwise = answer (v-1) w + 1\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + m + 1 + (n+m-d)^2 + n^2 - (n-m+d)^2\n | n<=d = n + m + 1 + (n+m-d)^2 + n^2\n | m<= d+n = n + m + 1 + d^2 + n^2 - (n-m+d)^2 + (n-d)^2 -(n-d)\n | otherwise = n + m + 1 + d^2 + n^2 + (n-d)^2 -(n-d)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [n,x,m,y] = map (read::String->Int) $ words input\n output = show $ answer l s\n d = abs (x-y)\n l = max n m\n s = min n m\n answer v w\n | d == 0 = v + 1\n | v + w <= d = v + w + 1\n | v <= d = v + w + 1 + (v+w-d)^2\n | v == w = answer (v-1) (w-1) + 4*d\n | v <= w + d = answer (v-1) w + 2*(w-v+d)+1\n | otherwise = answer (v-1) w + 1\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + m + 1 + n^2 + n^2 - (n-m+d)^2 - (m-d)\n | n<=d = n + m + 1 + n^2 + n^2 - (m-d)\n | m<= d+n = n + m + 1 + d^2 + n^2 - (n-m+d)^2 + (n-d)^2 -(n-d)\n | otherwise = n + m + 1 + d^2 + n^2 + (n-d)^2 -(n-d)\n--n=1 m=5 d=4"}, {"source_code": "main = interact solve\nsolve input = output where\n [n,x,m,y] = map (read::String->Int) $ words input\n output = show $ answer l s\n d = abs (x-y)\n l = max n m\n s = min n m\n answer v w\n | d == 0 = v + 1\n | v + w <= d = v + w + 1\n | v <= d = v + w + 1 + (v+w-d)^2\n | v == w = answer (v-1) (w-1) + 2*(2*d-1)\n | v <= w + d = answer (v-1) w + 2*(w-v+d)\n | otherwise = answer (v-1) w + 1\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + d + 1 + n^2 + n^2 - (n-m+d)^2\n | n<=d = n + d + 1 + n^2 + n^2 + m-d-n\n | m<= d+n = n + 1 + d^2 + n^2 - (n-m+d)^2 + (m-d)^2 - (m-n+d)^2\n | otherwise = n + 1 + d^2 + n^2 + (m-d)^2 - (m-n+d)^2\n--n=1 m=5 d=4"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + d + 1 + n^2 + n^2 - (n-m+d)^2\n | n<=d = n + d + 1 + n^2 + n^2\n | m<= d+n = n + 1 + d^2 + n^2 - (n-m+d)^2 + (m-d)^2 - (m-n+d)^2\n | otherwise = n + 1 + d^2 + n^2 + (m-d)^2 - (m-n+d)^2\n--n=1 m=5 d=4"}, {"source_code": "main = interact solve\nsolve input = output where\n [p,x,q,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n n = min p q\n m = max p q\n answer\n | d == 0 = m + 1\n | n+m <= d = n + m + 1\n | n<=d && m<=d = n + m + 1 + (n+m-d)^2\n | n<=d && m<=d+n = n + m + 1 + 2*n^2 - (n-m+d)^2\n | n<=d = n + m + 1 + 2*n^2\n | m<= d+n = n + m + 1 + (d-m)^2 + n^2 - (n-m+d)^2 + (n-d)^2 -(n-d)\n | otherwise = n + m + 1 + (d-m)^2 + n^2 + (n-d)^2 -(n-d)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [n,x,m,y] = map (read::String->Int) $ words input\n output = show answer\n d = abs (x - y)\n answer\n | d == 0 = max n m + 1\n | otherwise = ans (min n m) (max n m)\n ans u v\n | u+v<=d = u+v+1\n | u<=d && v<=d = u+v+1+(u+v-d)^2\n | u<=d && v<=d+u = ans u d + u^2 - (u-v+d)^2\n | u<=d = ans u (d+u) + v-d-u\n | u<=d+v = ans d v + v^2 - (v-u+d)^2\n | otherwise = ans (d+v) v + u-d-v\n"}], "src_uid": "ebaf9444531bb6ba6c3322dfa8edb69c"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport Data.Array as A\r\nimport Data.Array.MArray.Safe as MA\r\nimport Data.Array.ST.Safe as STA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve n as = ST.runST $ do\r\n asArray <- STA.newListArray (1, n) as :: ST.ST s (STA.STUArray s Int Int)\r\n dpArray <- STA.newArray (1, n) 0 :: ST.ST s (STA.STUArray s Int Int)\r\n forM_ (reverse [1 .. n]) $ \\i -> do\r\n a <- STA.readArray asArray i\r\n let incI = a + i\r\n if incI > n \r\n then STA.writeArray dpArray i a\r\n else do\r\n incDp <- STA.readArray dpArray incI\r\n STA.writeArray dpArray i $ incDp + a\r\n MA.getElems dpArray <&> maximum\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n n <- B8.getLine <&> readIntB8\r\n as <- B8.getLine <&> map readIntB8 . B8.words\r\n let answer = solve n as\r\n printf \"%d\\n\" answer\r\n", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad\n\nsolve :: Array Int Int -> Int\nsolve inp = let\n (1, n) = bounds inp\n step i = let\n v = inp ! i\n in v + if v + i <= n then ansArr ! (v + i) else 0\n ansArr = array (1, n) [(i, step i) | i <- [1..n]]\n in maximum $ elems ansArr\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- map read . words <$> getLine\n let inp = listArray (1, n) a\n print $ solve inp\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\n join, replicateM_)\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport Data.Array as A\nimport Data.Array.MArray.Safe as MA\nimport Data.Array.ST.Safe as STA\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Functor ((<&>))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.List (elemIndices, find, findIndices,\n intersect, isPrefixOf, nub, sort,\n sortOn)\nimport qualified Data.Map as M\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Set as S\nimport Data.Traversable (forM)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (IOMode (ReadMode, WriteMode),\n openFile, stdin, stdout)\nimport Text.Printf (printf)\n\n-- import Debug.Trace (trace)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nsolve :: Int -> [Int] -> Int\nsolve n as = ST.runST $ do\n asArray <- STA.newListArray (1, n) as :: ST.ST s (STA.STUArray s Int Int)\n dpArray <- STA.newArray (1, n) 0 :: ST.ST s (STA.STUArray s Int Int)\n forM_ (reverse [1 .. n]) $ \\i -> do\n a <- STA.readArray asArray i\n let incI = a + i\n if incI > n \n then STA.writeArray dpArray i a\n else do\n incDp <- STA.readArray dpArray incI\n STA.writeArray dpArray i $ incDp + a\n MA.getElems dpArray <&> maximum\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> map readIntB8 . B8.words\n let answer = solve n as\n printf \"%d\\n\" answer\n\n\t\t \t\t\t \t\t \t\t\t \t \t \t\t"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.Array.ST(runSTArray, STArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\nnumOcc :: Ord a => [a] -> M.Map a Integer\r\nnumOcc (x:xs) = let m = numOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m \r\n\tNothing -> M.insert x 1 m \r\nnumOcc [] = M.empty\r\n\r\n\r\nnumOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer\r\nnumOcc' size list = runSTArray $ do \r\n\tarray <- MA.newArray size 0\r\n\tfoldM (addElem array) () list\r\n\treturn array \r\n\r\n\twhere\r\n\t\taddElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()\r\n\t\taddElem array action a = do\r\n\t\t\ti <- MA.readArray array a\r\n\t\t\tMA.writeArray array a (i+1) \r\n\t\r\n\r\n\r\ninsertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]\r\ninsertWithList a b m = case M.lookup a m of \r\n\tJust l -> M.insert a (b:l) m \r\n\tNothing -> M.insert a [b] m \r\n\r\ndeleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]\r\ndeleteWithList a m = case M.lookup a m of \r\n\tJust (x:y:xs) -> M.insert a (y:xs) m\r\n\tJust [x] -> M.delete a m\r\n\r\nsolve :: Integer -> [Integer] -> Integer\r\n\r\nsolve n a = foldr max 0 tab where\r\n\ttab = A.array (0, n-1) $ fmap aux $ zip [0..] a\r\n\taux (i, a_i)\r\n\t\t| i+a_i >= n = (i, a_i)\r\n\t\t| otherwise = (i, a_i + (tab ! (i+a_i)))\r\n\r\n\r\n\r\nplotResult = print\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n a\r\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport qualified Data.Map as M\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (_:ns : rest) = ((:[]).itoline . solve . linetois) (ns) ++ tcio (drop 0 rest) \r\n linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n\r\nsolve :: [Int] -> Int\r\nsolve ns = maximum $ map snd $ M.toList $ M.foldrWithKey (\\ k v m-> M.insert k (v + (if k+v<=n then m M.! (k+v) else 0)) m) z z where\r\n z = (M.fromList $ zip [1..] ns) \r\n n = length ns\r\n"}], "negative_code": [], "src_uid": "ee8ca9b2c6104d1ff9ba1fc39e9df277"} {"source_code": "import Data.List\nimport Data.Functor\n\nmain :: IO()\nmain = do\n [ax, ay, bx, by, tx, ty] <- map read . words <$> getLine\n n <- read <$> getLine\n d <- split . map read . words <$> getContents\n let ad = map (dist (ax, ay)) d\n bd = map (dist (bx, by)) d\n td = map (dist (tx, ty)) d\n total = 2 * sum td\n af = [x - y | (x, y) <- zip ad td]\n bf = [x - y | (x, y) <- zip bd td]\n asd = sort $ zip af [0..]\n bsd = sort $ zip bf [0..]\n minA = fst $ head asd\n minB = fst $ head bsd\n minAB = min2 n asd bsd\n minBA = min2 n bsd asd\n print $ total + minimum [minA, minB, minAB, minBA]\n\nsplit :: [a] -> [(a, a)]\nsplit [] = []\nsplit (x:y:s) = (x, y) : split s\n\nsquare :: Double -> Double\nsquare x = x * x\n\ndist :: (Double, Double) -> (Double, Double) -> Double\ndist (x1, y1) (x2, y2) = sqrt (square (x1 - x2) + square (y1 - y2))\n\nmin2 :: Int -> [(Double, Int)] -> [(Double, Int)] -> Double\nmin2 n a b | n == 1 = fst $ head a\n | snd (head a) == snd (head b) = fst (head a) + fst (head $ tail b)\n | otherwise = fst (head a) + fst (head b)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Int\n\nmain = do\n [ax,ay,bx,by,tx,ty] <- map read.words <$> getLine :: IO [Integer]\n n <- readLn\n xys <- parse.map readInt.B.words <$> B.getContents\n print $ solve n (ax,ay) (bx,by) (tx,ty) xys\n\nsolve 1 axy bxy txy [xy] = minimum [dist axy xy+dist txy xy, dist bxy xy+dist txy xy]\nsolve n axy bxy txy xys = minimum $ [calc1 axy, calc1 bxy] ++ [calc2 a b|(a,b)<-[(a1,b1),(a2,b1),(a1,b2)], a /= b]\n where\n (a1:a2:_) = map snd $ sort[(dist axy xy - dist txy xy, xy)|xy<-xys]\n (b1:b2:_) = map snd $ sort[(dist bxy xy - dist txy xy, xy)|xy<-xys]\n\n !s = 2*sum[dist txy xy |xy<-xys]\n calc1 a0 = s + minimum[dist a0 xy - dist txy xy|xy<-xys]\n calc2 a1 b1 = s + (dist axy a1 - dist txy a1) + (dist bxy b1 - dist txy b1)\n\ndist2 (a,b) (c,d) = (a-c)^2 + (b-d)^2\n\ndist x y = intSqrt $ dist2 x y\n\nintSqrt :: Integer -> Double\nintSqrt = sqrt.fromIntegral\n\nreadInt bs = case B.readInt bs of Just (n,_) -> fromIntegral n\n\nparse (x:y:xys) = (x,y):parse xys\nparse _ = []"}, {"source_code": "import qualified Data.ByteString as B\nimport Data.List\n\ndist (x,y) (x1,y1) = sqrt $ (x-x1)*(x-x1) + (y-y1)*(y-y1)\n\ncalcTotal t pts = 2 * (sum $ map (dist t) pts)\n\ncalcDiffs t a pts = sort $ map diff pts `zip` [1..]\n where diff p = (dist a p) - (dist t p)\n\nmain = interact $ show . solve . words\n\npairs [] = []\npairs (x:y:r) = (x,y) : pairs r\n\nsolve wrds = solve0 a b t n pts\n where [a, b, t] = pairs . map read . take 6 $ wrds :: [(Double, Double)]\n n = read $ wrds !! 6 :: Int\n pts = pairs . map read . take (2*n) . drop 7 $ wrds :: [(Double, Double)]\n\nsolve0 a b t n pts = minimum better + calcTotal t pts\n where [adf, bdf] = [take 5 $ calcDiffs t a pts, take 5 $ calcDiffs t b pts]\n [af, bf] = [fst . head $ adf, fst . head $ bdf]\n better = af : bf : [fst i + fst j | i <- adf, j <- bdf, snd i /= snd j]\n"}, {"source_code": "import Data.List\n\ndist (x,y) (x1,y1) = sqrt $ (x-x1)*(x-x1) + (y-y1)*(y-y1)\n\ncalcTotal t pts = 2 * (sum $ map (dist t) pts)\n\ncalcDiffs t a pts = sort $ map diff pts `zip` [1..]\n where diff p = (dist a p) - (dist t p)\n\nmain = do\n [ax,ay,bx,by,tx,ty] <- fmap (map (read :: String -> Double) . words) $ getLine\n let [a,b,t] = [(ax, ay), (bx, by), (tx, ty)]\n n <- fmap (read :: String -> Int) getLine\n let readPts i\n | i == 0 = return []\n | otherwise = do\n [x,y] <- fmap (map (read :: String -> Double) . words) $ getLine\n fmap ((x,y):) $ readPts (i - 1)\n pts <- readPts n\n let adiffs = calcDiffs t a pts\n let bdiffs = calcDiffs t b pts\n let [bra, brb] = [take 5 adiffs, take 5 bdiffs]\n let [af, bf] = [fst . head $ adiffs, fst . head $ bdiffs]\n let res = af : bf : [fst i + fst j | i <- bra, j <- brb, snd i /= snd j]\n print $ minimum res + calcTotal t pts\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\ntype Pos = (Double, Double)\n\nmain = do\n [ax, ay, bx, by, tx, ty] <- fmap (map read . words) getLine\n n <- fmap read getLine\n inp <- forM [1..n] $ \\_ -> do\n [px, py] <- fmap (map read . words) getLine\n return (px, py)\n print $ solve (ax, ay) (bx, by) (tx, ty) inp\n\n \n\n--solve :: Pos -> Pos -> Pos -> [Pos] -> Double\nsolve a b r [p] = minimum [as, bs]\n where\n as = sub a p + sub p r\n bs = sub b p + sub p r\nsolve a b r s = sumTs - maximum [onlyA, onlyB, aNb]\n where\n sumTs = 2*sum (map h s)\n where\n h p = sub r p\n\n f p = sub p r - sub a p\n g p = sub p r - sub b p\n (ma:ma':as) = sortBy (flip compare) (zip (map f s) [0..])\n (mb:mb':bs) = sortBy (flip compare) (zip (map g s) [0..])\n aNb | snd ma == snd mb = maximum [fst ma + fst mb', fst ma' + fst mb]\n | otherwise = fst ma + fst mb\n onlyA = fst ma\n onlyB = fst mb\n \nsub (x, x') (y,y') = sqrt $ (x - y)**2 + (x'- y')**2\n"}], "negative_code": [], "src_uid": "ae8687ed3cb5df080fb6ee79b040cef1"} {"source_code": "import Control.Monad\n\nparts :: [Int] -> ([Int], [Int])\nparts [] = ([], [])\nparts (x:y:zs) = let\n (xs, ys) = parts zs\n in (x : xs, y : ys)\nparts li = (li, [])\n\nsolve :: [Int] -> Bool\nsolve li = let (lo, le) = parts li\n in if even (length li)\n then all odd le\n else any odd lo\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- map (read . pure) <$> getLine\n putStrLn $ case solve a of\n True -> \"1\"\n False -> \"2\"\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n s <- getLine\n print $ solve n s\n\nsolve :: Int -> String -> Int\nsolve n s\n | even n =if any even evens then 2 else 1\n | otherwise = if any odd odds then 1 else 2\n where\n zipped = zip s [1::Int ..]\n evens = map ((\\x -> read [x]) .fst) $ filter (even.snd) zipped\n odds = map ((\\x -> read [x]) .fst) $ filter (odd.snd) zipped\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (read::String->Int) $ line\n\neverySnd :: [a] -> [a]\neverySnd lst = map fst $ filter (even.snd) indexed where\n indexed = zip lst [0..]\n\neveryOdd:: [a] -> [a]\neveryOdd lst = map fst $ filter (odd.snd) indexed where\n indexed = zip lst [0..]\n\nsolveAlice :: String -> IO ()\nsolveAlice s = do\n let snd = (everySnd s)\n let answer = any (\\x -> (digitToInt x) `mod` 2 == 1) snd\n if answer then print 1 else print 2\n\nsolveBob :: String -> IO ()\nsolveBob s = do\n let snd = (everyOdd s)\n let answer = any (\\x -> (digitToInt x) `mod` 2 == 0) snd\n if answer then print 2 else print 1\n\nsolve :: IO ()\nsolve = do\n n <- readInt \n s <- getLine\n if n `mod` 2 == 1 then (solveAlice s) else (solveBob s)\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [0..t-1] $ (\\i -> solve)"}, {"source_code": "import Control.Monad\nimport Data.Char\nmain = do\n t <- fmap read getLine\n forM [1..t] (\\_ -> do\n n <- fmap read getLine\n ans <- fmap (calc n) getLine\n print ans)\ncalc :: Int -> String -> Int\ncalc n d\n | odd n = calc1 d\n | even n = calc2 d\ncalc1 [x] = if odd $ digitToInt x then 1 else 2\ncalc1 (x:y:xs) = if odd $ digitToInt x then 1 else calc1 xs\ncalc2 [x,y] = if even $ digitToInt y then 2 else 1\ncalc2 (x:y:xs) = if even $ digitToInt y then 2 else calc2 xs\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Bits\n \nreadArray :: IO [Int]\nreadArray = do\n line <- getLine\n return $ map (read::String->Int) $ words line\n\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (read::String->Int) $ line\n\neverySnd :: [a] -> [a]\neverySnd lst = map fst $ filter (even.snd) indexed where\n indexed = zip lst [0..]\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n s <- getLine\n let snd = (everySnd s)\n let answer = any (\\x -> (digitToInt x) `mod` 2 == 1) snd\n if answer then print 1 else print 2\n\nmain :: IO ()\nmain = do\n t <- readInt\n forM_ [0..t-1] $ (\\i -> solve)"}, {"source_code": "import Control.Monad\nimport Data.Char\nmain = do\n t <- fmap read getLine\n forM [1..t] (\\_ -> do\n n <- fmap read getLine\n ans <- fmap (calc n) getLine\n print ans)\ncalc :: Int -> String -> Int\ncalc n d\n | odd n = calc1 d\n | even n = calc2 d\ncalc1 [x] = if odd $ digitToInt x then 1 else 2\ncalc1 (x:y:xs) = if odd $ digitToInt x then 1 else calc1 xs\ncalc2 [x,y] = if even $ digitToInt x then 2 else 1\ncalc2 (x:y:xs) = if even $ digitToInt x then 2 else calc2 xs\n"}, {"source_code": "import Control.Monad\nmain = do\n t <- fmap read getLine\n forM [1..t] (\\_ -> do\n n <- fmap read getLine\n ans <- fmap ((calc n).read) getLine\n print ans)\ncalc :: Int -> Int -> Int\ncalc n d\n | odd n = calc1 d\n | even n = calc2 d\ncalc1 d\n | d < 100 = if odd d then 1 else 2\n | otherwise = if odd d then 1 else calc1 $ div d 100\ncalc2 d\n | d < 100 = if even $ div d 10 then 2 else 1\n | otherwise = if even $ div d 10 then 2 else calc2 $ div d 100\n"}], "src_uid": "c9225c915669e183cbd8c20b848d96e5"} {"source_code": "import Data.List\r\nimport qualified Data.Char as DC\r\nimport qualified Data.Set as Set\r\nimport Control.Monad (replicateM)\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n n <- fmap (read :: String -> Int) getLine\r\n strs <- replicateM n getLine\r\n let setik = Set.fromList strs\r\n let res = map (\\str -> (foldl (\\cur el -> (cur || ((Set.member (take el str) setik) && (Set.member (drop el str) setik)))) False [1..(length str)-1])) strs\r\n putStrLn $ map (\\x -> if x then '1' else '0') res\r\n \r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\n\nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\r\\n\\t\")\n \nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\nreadInt :: BS.ByteString -> Int\nreadInt line = let [x] = readInts line in x\n\nsolve :: [BS.ByteString] -> [Bool]\nsolve strs = map check strs\n where set :: S.Set BS.ByteString \n set = foldr S.insert S.empty strs\n check :: BS.ByteString -> Bool\n check str = or [check' i str | i <- [1 .. BS.length str - 1]] \n check' :: Int -> BS.ByteString -> Bool\n check' i str = S.member (BS.take i str) set && S.member (BS.drop i str) set\n\nprintSolution :: [Bool] -> IO ()\nprintSolution soln = putStrLn $ map (\\x -> if x then '1' else '0') soln\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- readInt <$> BS.getLine\n strs <- map (BS.filter (/='\\r')) <$> forM [1 .. n] (\\x -> BS.getLine)\n printSolution (solve strs)\n\nmain :: IO ()\nmain = do t <- readInt <$> BS.getLine\n forM_ [1 .. t] testCaseMain\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\n\ncheck :: String -> String -> Set.Set String -> Bool\ncheck \"\" suff set = False\ncheck pref suff set =\n if suff /= \"\" && Set.member pref set && Set.member suff set\n then True\n else check (init pref) ((last pref) : suff) set\n\nsolve :: [String] -> [Bool]\nsolve strs =\n map (\\x -> check x \"\" set) strs \n where set = Set.fromList strs\n\ntestcase 0 = return ()\ntestcase t = do\n n <- readLn :: IO Int\n strs <- forM [1..n] (\\x -> getLine)\n putStrLn $ filter (\\x -> x /= ' ') $ unwords $ map (\\x -> if x then \"1\" else \"0\") $ solve strs\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (forM_)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)\r\nimport Data.Array ((!))\r\nimport Data.Array.ST (MArray (newArray), readArray, runSTArray, writeArray)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Char (toLower)\r\nimport Data.List (nub, sort)\r\nimport Data.Maybe (fromJust)\r\nimport qualified Data.Set as Set\r\nimport Debug.Trace (traceShowId, traceShow)\r\n\r\ndata TC = TC {ss :: [String]}\r\n\r\nsolve TC {..} = fmap (\\case True -> '1'; _ -> '0') $ fmap check ss\r\n where\r\n allSet = Set.fromList ss\r\n\r\n prefixes = init . tail . foldr (\\el acc -> [] : map (el :) acc) [[]]\r\n suffixes = reverse . (fmap reverse) . prefixes . reverse\r\n\r\n check s = any (\\(x, y) -> Set.member x allSet && Set.member y allSet) $ zip pref suf\r\n where\r\n pref = prefixes s\r\n suf = suffixes s\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (C.pack) >>> C.unlines\r\n\r\nscan = numberOf $ TC <$> numberOf (C.unpack <$> str)\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (forM_)\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)\r\nimport Data.Array ((!))\r\nimport Data.Array.ST (MArray (newArray), readArray, runSTArray, writeArray)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Char (toLower)\r\nimport Data.List (nub, sort)\r\nimport Data.Maybe (fromJust)\r\nimport qualified Data.Set as Set\r\nimport Debug.Trace (traceShowId, traceShow)\r\n\r\ndata TC = TC {ss :: [String]}\r\n\r\nsolve TC {..} = fmap (\\case True -> '1'; _ -> '0') $ fmap check ss\r\n where\r\n allSet = traceShowId $ Set.fromList ss\r\n\r\n prefixes = init . tail . foldr (\\el acc -> [] : map (el :) acc) [[]]\r\n suffixes = reverse . (fmap reverse) . prefixes . reverse\r\n\r\n check s = any (\\(x, y) -> Set.member x allSet && Set.member y allSet) $ zip pref suf\r\n where\r\n pref = prefixes s\r\n suf = suffixes s\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map (C.pack) >>> C.unlines\r\n\r\nscan = numberOf $ TC <$> numberOf (C.unpack <$> str)\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "module Main (main) where\nimport Numeric (showFFloat)\nimport Data.Char (toUpper)\nimport Control.Monad\nimport Data.List (sortOn)\nimport qualified Data.Set as Set\nimport Data.Functor.Classes (eq2)\nimport qualified Data.Maybe as Maybe\n\n-- reset && stack build && echo \"success\" && stack exec haskell-codeforces-exe && echo finished\n-- gen-hie > hie.yaml\n\n\nstrToInt a = read a :: Int\nstrToFloat a = read a :: Float\n\npshow x = putStr (show x)\npfshow x = putStr (showFFloat (Just 2) x \"\")\n\n-- hasStrSlice:: Set.Set String -> String -> Int -> Bool\nhasStrSlice stringsSet str i = do\n (Maybe.isJust $ Set.lookupIndex (take (i + 1) str) stringsSet) && (\n Maybe.isJust $ Set.lookupIndex (drop (i + 1) str) stringsSet)\n\nsolveStr stringsSet str = do\n let res = any (hasStrSlice stringsSet str) [0..length str - 1]\n if res\n then \"1\"\n else \"0\"\n\nsolve = do\n n <- getLine\n\n strings <- replicateM (read n) getLine\n\n -- let stringsWithIndex = zip [0..] strings\n let stringsSet = Set.fromList strings\n\n putStrLn $ concatMap (solveStr stringsSet) strings\n\nmain :: IO ()\nmain = do\n -- solve\n n <- readLn\n replicateM_ n solve"}, {"source_code": "import Control.Monad (replicateM, replicateM_)\r\nimport Data.Function ((&))\r\nimport Data.Functor ((<&>))\r\nimport qualified Data.Set as Set\r\n\r\n\r\nfindStringsAnswers strings = map canComposeString strings\r\n where\r\n canComposeString s = partitions s & any (\\ (a, b) -> hasString a && hasString b)\r\n partitions s = [splitAt i s | i <- [0 .. length s]]\r\n hasString s = Set.member s strings_set\r\n strings_set = Set.fromList strings\r\n\r\nmain = do\r\n [tests_n] <- readInts\r\n replicateM_ tests_n $ do\r\n [strings_n] <- readInts\r\n strings <- replicateM strings_n getLine\r\n let output = findStringsAnswers strings\r\n & map (\\ ans -> if ans then '1' else '0')\r\n putStrLn output\r\n\r\n\r\nreadInts = getLine <&> words <&> map read\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe, catMaybes)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.String (fromString)\nimport Data.Bits (shift)\nimport Data.Binary (encode, decode)\n\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = [String]\ntype CoDomain = [Int]\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ concatMap show xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- replicateM n getLine\n return xs\n\ndata Trie = Leaf | Node Bool (Map Char Trie)\n\ntoTrie :: [Char] -> Trie\ntoTrie [] = Leaf\ntoTrie (x:xs) = Node False (Map.singleton x (toTrie xs))\n\naddTrie :: [Char] -> Trie -> Trie\naddTrie [] Leaf = Leaf\naddTrie [] (Node _ xs) = Node True xs\naddTrie (x:xs) Leaf = Node True (Map.singleton x (toTrie xs))\naddTrie (x:xs) (Node b children) = Node b (alter f x children)\n where f Nothing = Just $ toTrie xs\n f (Just t) = Just $ addTrie xs t\n\ninTrie :: [Char] -> Trie -> Bool\ninTrie [] Leaf = True\ninTrie [] (Node x _) = x\ninTrie (x:xs) Leaf = False\ninTrie (x:xs) (Node b children) = case Map.lookup x children of\n Nothing -> False\n Just child -> inTrie xs child\n\nbuildTrie :: [String] -> Trie\nbuildTrie xs = foldl (flip addTrie) Leaf xs\n\n\nsolve :: Solver\nsolve xs = [if r then 1 else 0 | r <- res ]\n where\n ys = buildTrie xs\n f = (`inTrie` ys)\n res = (\\y -> any (\\(a,b) -> f a && f b) $ (flip splitAt y) <$> [1..length y - 1]) <$> xs\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe, catMaybes)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.String (fromString)\nimport Data.Bits (shift)\nimport Data.Binary (encode, decode)\n\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = [String]\ntype CoDomain = [Int]\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ concatMap show xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- replicateM n getLine\n return xs\n\ndata Trie = Leaf | Node Bool (Map Char Trie)\n\ntoTrie :: [Char] -> Trie\ntoTrie [] = Leaf\ntoTrie (x:xs) = Node False (Map.singleton x (toTrie xs))\n\naddTrie :: [Char] -> Trie -> Trie\naddTrie [] Leaf = Leaf\naddTrie [] (Node _ xs) = Node True xs\naddTrie (x:xs) Leaf = Node True (Map.singleton x (toTrie xs))\naddTrie (x:xs) (Node b children) = Node b (alter f x children)\n where f Nothing = Just $ toTrie xs\n f (Just t) = Just $ addTrie xs t\n\ninTrie :: [Char] -> Trie -> Bool\ninTrie [] Leaf = True\ninTrie [] (Node x _) = x\ninTrie (x:xs) Leaf = False\ninTrie (x:xs) (Node b children) = case Map.lookup x children of\n Nothing -> False\n Just child -> inTrie xs child\n\nbuildTrie :: [String] -> Trie\nbuildTrie xs = foldr addTrie Leaf xs\n\n\nsolve :: Solver\nsolve xs = [if r then 1 else 0 | r <- res ]\n where\n ys = buildTrie xs\n f = (`inTrie` ys)\n res = (\\y -> any (\\(a,b) -> f a && f b) $ (flip splitAt y) <$> [1..length y - 1]) <$> xs\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe, catMaybes)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.String (fromString)\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = [String]\ntype CoDomain = [Int]\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ intercalate \" \" $ map show xs\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- replicateM n getLine\n return xs\n\nsolve :: Solver\nsolve xs = [if r then 1 else 0 | r <- res ]\n where\n -- [map suffix n(the id of original string) indexed by prefix tree\n ys = Set.fromList xs\n f = (`elem` ys)\n res = (\\y -> any (\\(a,b) -> f a && f b) $ (flip splitAt y) <$> [0..length y - 1]) <$> xs\n\n\n\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\n\nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\r\\n\\t\")\n \nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\nreadInt :: BS.ByteString -> Int\nreadInt line = let [x] = readInts line in x\n\nsolve :: [BS.ByteString] -> [Bool]\nsolve strs = map check strs\n where set :: S.Set BS.ByteString \n set = foldr S.insert S.empty strs\n check :: BS.ByteString -> Bool\n check str = or [check' i str | i <- [1 .. BS.length str - 1]] \n check' :: Int -> BS.ByteString -> Bool\n check' i str = S.member (BS.take i str) set && S.member (BS.drop i str) set\n\nprintSolution :: [Bool] -> IO ()\nprintSolution soln = putStrLn $ map (\\x -> if x then '1' else '0') soln\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- readInt <$> BS.getLine\n strs <- forM [1 .. n] (\\x -> BS.getLine)\n printSolution (solve strs)\n\nmain :: IO ()\nmain = do t <- readInt <$> BS.getLine\n forM_ [1 .. t] testCaseMain\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\n\nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\n\\t\")\n \nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\nreadInt :: BS.ByteString -> Int\nreadInt line = let [x] = readInts line in x\n\nsolve :: [BS.ByteString] -> [Bool]\nsolve strs = map check strs\n where set :: S.Set BS.ByteString \n set = foldr S.insert S.empty strs\n check :: BS.ByteString -> Bool\n check str = or [check' i str | i <- [1 .. BS.length str - 1]] \n check' :: Int -> BS.ByteString -> Bool\n check' i str = S.member (BS.take i str) set && S.member (BS.drop i str) set\n\nprintSolution :: [Bool] -> IO ()\nprintSolution soln = putStrLn $ map (\\x -> if x then '1' else '0') soln\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- readInt <$> BS.getLine\n strs <- forM [1 .. n] (\\x -> BS.getLine)\n printSolution (solve strs)\n\nmain :: IO ()\nmain = do t <- readInt <$> BS.getLine\n forM_ [1 .. t] testCaseMain\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Set as Set\r\n\r\ncheck :: String -> String -> Set.Set String -> Bool\r\ncheck \"\" suff set = False\r\ncheck pref suff set =\r\n if Set.member pref set && Set.member suff set\r\n then True\r\n else check (init pref) ((last pref) : suff) set\r\n\r\nsolve :: [String] -> [Bool]\r\nsolve strs =\r\n map (\\x -> check x \"\" set) strs \r\n where set = Set.fromList strs\r\n\r\ntestcase 0 = return ()\r\ntestcase t = do\r\n n <- readLn :: IO Int\r\n strs <- forM [1..n] (\\x -> getLine)\r\n putStrLn $ filter (\\x -> x /= ' ') $ unwords $ map (\\x -> if x then \"0\" else \"1\") $ solve strs\r\n testcase (t - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- read <$> getLine\r\n testcase t\r\n"}], "src_uid": "9683d5960247359b6b9066e96897d6f9"} {"source_code": "main = readLn >>= putStrLn . solve\n\nsolve n = take n (cycle \"aabb\")", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n n <- fmap readInt B.getLine\n putStr $ solve n\n\nsolve n = take n $ cycle \"aabb\"\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . solve 0 . read =<< getLine\n\nsolve :: Int -> Int -> String\nsolve _ 0 = \"\"\nsolve i n | i `div` 2 `mod` 2 == 0 = 'a' : solve (i + 1) (n - 1)\n | otherwise = 'b' : solve (i + 1) (n - 1)\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . solve . read =<< getLine\n\nsolve :: Int -> String\nsolve 0 = \"\"\nsolve n | n `div` 2 `mod` 2 == 0 = 'a' : solve (n - 1)\n | otherwise = 'b' : solve (n - 1)\n"}, {"source_code": "main = (readLn :: IO Int) >>= \\x -> putStrLn $ take x $ cycle \"aabb\" \n"}, {"source_code": "main = do\n e<-getLine\n let n=read e::Int\n putStrLn $ take n $ concat $ repeat \"aabb\""}, {"source_code": "main = interact $ solve . read\nsolve n = take n $ cycle \"aabb\"\n"}, {"source_code": "main = readLn >>= putStrLn . solve \"\"\n\nsolve str n\n |n == 0 = str\n |otherwise = solve ((\"aabb\" !! (n `mod` 4)):str) (n - 1)\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\n\nsolve n = take n $ cycle \"aabb\"\n\nmain = solve . readInt <$> B.getLine >>= putStr\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\n\nreadInt = fst . M.fromJust . C.readInt\n\nrun xx 0 = xx\nrun [] 1 = \"a\"\nrun [] n = run \"aa\" (n - 2)\nrun xx@(x:y:xs) n | y == 'a' && x == 'a' = run ('b':xx) (n - 1)\n | y == 'a' && x == 'b' = run ('b':xx) (n - 1)\n | y == 'b' && x == 'b' = run ('a':xx) (n - 1)\n | y == 'b' && x == 'a' = run ('a':xx) (n - 1)\n\nmain = do\n (readInt -> n) <- B.getLine\n putStrLn $ run [] n\n"}, {"source_code": "main :: IO()\nmain = do\n inp <- getLine\n putStrLn $ output . solve . input $ inp\n\ninput :: String -> Int\ninput = read\n\nsolve :: Int -> String\nsolve n = ab \"a\" 0 n\n where\n ab _ _ 0 = \"\"\n ab \"a\" 0 n = \"a\" ++ ab \"a\" 1 (n-1)\n ab \"a\" 1 n = \"a\" ++ ab \"b\" 0 (n-1)\n ab \"b\" 0 n = \"b\" ++ ab \"b\" 1 (n-1)\n ab \"b\" 1 n = \"b\" ++ ab \"a\" 0 (n-1)\n\noutput :: String -> String\noutput = id\n"}], "negative_code": [{"source_code": "main = (readLn :: IO Int) >>= \\x -> putStrLn $ take x $ cycle \"aabbc\" \n"}], "src_uid": "fbde86a29f416b3d83bcc63fb3776776"} {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nchange :: Int -> String -> Int -> Int -> String\nchange 0 str _ m = reverse (replicate m '0' ++ str)\nchange _ _ _ 0 = \"\"\nchange k str n m\n | k >= n =\n let z = div k n\n in\n if z <= m\n then change (k - z*n) (str ++ replicate z '0') n (m - z)\n else \"\"\n | otherwise = \n let (strfst, strsnd) = splitAt k str\n in change 0 (strfst ++ '0' : strsnd) n (m - 1)\n\ncheck :: String -> Int -> Int -> Bool\ncheck [] _ 0 = True\ncheck ('0':rest) acum k = check rest (acum + 1) k\ncheck ('1':rest) acum k = check rest acum (k - acum)\ncheck _ _ _ = False\n\nattempt :: Int -> Int -> Int -> Int -> Maybe String\nattempt 0 0 1 m = Just $ replicate m '0'\nattempt 0 0 n 1 = Just $ replicate n '1'\nattempt a01 a10 n m =\n let att = change a01 (replicate n '1') n m\n in\n if null att || not (check (reverse att) 0 a10)\n then Nothing\n else Just att\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [1..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n case attempt a01 a10 n m of\n Nothing -> \"Impossible\"\n Just soln -> soln\n\nmain :: IO ()\nmain = interact process", "positive_code": [{"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if all (/=(-1)) [a1,a2] && any (==0) [a1,a2] then do\n if (a1+a2 == b+c) then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '1')\n _ -> putStrLn $ (replicate b '0') ++ \"1\" ++ (replicate c '0')\n else if (b+c) == 0 then do\n putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else if all (==0) [a1,a2] && (b+c) == 1 then do\n case b of\n 0 -> putStrLn \"10\"\n 1 -> putStrLn \"01\"\n else putStrLn \"Impossible\"\n else if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}], "negative_code": [{"source_code": "main = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2])\n then putStrLn \"Impossible\"\n else if a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n if (b+c) == 0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else if b==0 then putStrLn (replicate a2 '1' ++ replicate a1 '0')\n else if c==0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else do\n let zc = b `div` a2\n putStrLn $ (replicate zc '0' ++ replicate a2 '1' ++ replicate (a1-zc) '0')\n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if any (==0) [a1,a2] then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '0')\n _ -> putStrLn $ (replicate c '0') ++ \"1\" ++ (replicate b '1')\n else if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "main = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n let a1 = nc2 a\n a2 = nc2 d\n if any (==(-1)) [a1,a2]\n then putStrLn \"Impossible\"\n else if a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n if (b+c) == 0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else if b==0 then putStrLn (replicate a2 '1' ++ replicate a1 '0')\n else if c==0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else do\n putStrLn $ '0':(replicate a2 '1' ++ replicate (a1-1) '0')\n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if all (/=(-1)) [a1,a2] && any (==0) [a1,a2] then do\n if (a1+a2 == b+c) then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '1')\n _ -> putStrLn $ (replicate b '0') ++ \"1\" ++ (replicate c '0')\n else putStrLn \"Impossible\"\n else if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if all (/=(-1)) (map nc2 [a1,a2]) && any (==0) [a1,a2] && (nc2 (b+c) == (a1+a2)) then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '0')\n _ -> putStrLn $ (replicate c '0') ++ \"1\" ++ (replicate b '1')\n else if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else if any (==0) [a1,a2] then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '0')\n _ -> putStrLn $ (replicate c '0') ++ \"1\" ++ (replicate b '1')\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if all (/=(-1)) [a1,a2] && any (==0) [a1,a2] then do\n if (a1+a2 == b+c) then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '1')\n _ -> putStrLn $ (replicate b '0') ++ \"1\" ++ (replicate c '0')\n else if (b+c) ==0 then do\n putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else putStrLn \"Impossible\"\n else if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "main = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2])\n then putStrLn \"Impossible\"\n else if a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n if (b+c) == 0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else if b==0 then putStrLn (replicate a2 '1' ++ replicate a1 '0')\n else if c==0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else do\n let zc = b `div` a2\n putStrLn $ (replicate zc '0' ++ replicate a2 '1' ++ replicate (b-zc) '0')\n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n print y\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "main = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2]) || all (==0) [a,b,c,d]\n then putStrLn \"Impossible\"\n else if a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n if (b+c) == 0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else if b==0 then putStrLn (replicate a2 '1' ++ replicate a1 '0')\n else if c==0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else do\n putStrLn $ '0':(replicate a2 '1' ++ replicate (a1-1) '0')\n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import Control.Monad\nmain = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if all (/=(-1)) [a1,a2] && any (==0) [a1,a2] then do\n if (a1+a2 == b+c) then do\n case a1 of\n 0 -> putStrLn $ (replicate c '1') ++ \"0\" ++ (replicate b '1')\n _ -> putStrLn $ (replicate c '0') ++ \"1\" ++ (replicate b '0')\n else putStrLn \"Impossible\"\n else if (any (==(-1)) [a1,a2]) || a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n let (_,_,y) = foldr fn (0,c,[]) [0..a2]\n fn 0 (used,cnt,ls) = (-1,-1,(a1-used):ls)\n fn x (used,cnt,ls) = (used + cnt `div` x,cnt `mod` x, (cnt `div` x:ls))\n putStr (replicate (head y) '0')\n forM_ (tail y) $ \\n -> do\n putChar '1'\n mapM_ (\\_ -> putChar '0') [1..n]\n \n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "main = do\n [a,b,c,d] <- fmap ((map read) . words) getLine\n if all (==0) [a,b,c,d]\n then print 0\n else do\n let a1 = nc2 a\n a2 = nc2 d\n if (any (==(-1)) [a1,a2])\n then putStrLn \"Impossible\"\n else if a1*a2 /= (b+c)\n then putStrLn \"Impossible\"\n else do\n if (b+c) == 0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else if b==0 then putStrLn (replicate a2 '1' ++ replicate a1 '0')\n else if c==0 then putStrLn (replicate a1 '0' ++ replicate a2 '1')\n else putStrLn $ '0':(replicate a2 '1' ++ replicate (a1-1) '0')\n \n \nnc2 0 = 0\nnc2 x =\n let a = ceiling . sqrt . fromIntegral $ (2*x)\n in if a*(a-1) == (2*x) then a else -1\n"}, {"source_code": "import qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [0..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n if (mod a01 n > 0) || (mod a10 n > 0)\n then \"Impossible\"\n else\n let x = div a01 n\n y = div a10 n\n in\n if comb (x + y) /= a00\n then \"Impossible\"\n else replicate x '0' ++ replicate n '1' ++ replicate y '0'\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nchange :: Int -> String -> Int -> Int -> String\nchange 0 str _ m = reverse (replicate m '0' ++ str)\nchange _ _ _ 0 = \"\"\nchange k str n m\n | k >= n = change (k - n) (str ++ \"0\") n (m - 1)\n | otherwise = \n let (strfst, strsnd) = splitAt k str\n in change 0 (strfst ++ '0' : strsnd) n (m - 1)\n\ncheck :: String -> Int -> Int -> Int -> Bool\ncheck _ 0 _ 0 = True\ncheck ('0':rest) n acum k = check rest n (acum + 1) k\ncheck ('1':rest) n acum k = check rest (n - 1) acum (k - acum * n)\ncheck _ _ _ _ = False\n\nattempt :: Int -> Int -> Int -> Int -> Maybe String\nattempt a01 a10 n m =\n let att = change a01 (replicate n '1') n m\n in\n if null att || check (reverse att) n 0 a10 \n then Nothing\n else Just att\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [0..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n case attempt a01 a10 n m of\n Nothing -> \"Impossible\"\n Just soln -> soln\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nchange :: Int -> String -> Int -> Int -> String\nchange 0 str _ m = reverse (replicate m '0' ++ str)\nchange _ _ _ 0 = \"\"\nchange k str n m\n | k >= n = let z = div k n in change (k - z*n) (str ++ \"0\") n (m - z)\n | otherwise = \n let (strfst, strsnd) = splitAt k str\n in change 0 (strfst ++ '0' : strsnd) n (m - 1)\n\ncheck :: String -> Int -> Int -> Bool\ncheck [] _ 0 = True\ncheck ('0':rest) acum k = check rest (acum + 1) k\ncheck ('1':rest) acum k = check rest acum (k - acum)\ncheck _ _ _ = False\n\nattempt :: Int -> Int -> Int -> Int -> Maybe String\nattempt 0 0 1 m = Just $ replicate m '0'\nattempt 0 0 n 1 = Just $ replicate n '1'\nattempt a01 a10 n m =\n let att = change a01 (replicate n '1') n m\n in\n if null att || not (check (reverse att) 0 a10)\n then Nothing\n else Just att\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [1..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n case attempt a01 a10 n m of\n Nothing -> \"Impossible\"\n Just soln -> soln\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nchange :: Int -> String -> Int -> Int -> String\nchange 0 str _ m = reverse (replicate m '0' ++ str)\nchange _ _ _ 0 = \"\"\nchange k str n m\n | k >= n = change (k - n) (str ++ \"0\") n (m - 1)\n | otherwise = \n let (strfst, strsnd) = splitAt k str\n in change 0 (strfst ++ '0' : strsnd) n (m - 1)\n\ncheck :: String -> Int -> Int -> Int -> Bool\ncheck _ 0 _ 0 = True\ncheck ('0':rest) n acum k = check rest n (acum + 1) k\ncheck ('1':rest) n acum k = check rest (n - 1) acum (k - acum * n)\ncheck _ _ _ _ = False\n\nattempt :: Int -> Int -> Int -> Int -> Maybe String\nattempt a01 a10 n m =\n let att = change a01 (replicate n '1') n m\n in\n if null att || check (reverse att) n 0 a10\n then Nothing\n else Just att\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [0..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n case attempt a01 a10 n m of\n Nothing -> \"Impossible\"\n Just soln -> soln\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nattempt :: Int -> Int -> Int -> Int -> Maybe (Int, Int)\nattempt a01 a10 n m\n | (mod a01 n > 0) || (mod a10 n > 0) || comb (x + y) == m = Nothing\n | otherwise = Just (x, y)\n where\n x = div a01 n\n y = div a10 n\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [0..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n case (attempt a01 a10 n m, attempt a01 a10 m n) of\n (Nothing, Nothing) -> \"Impossible\"\n (Just (xn, yn), Nothing) -> replicate xn '0' ++ replicate n '1' ++ replicate yn '0'\n (Nothing, Just (xm, ym)) -> replicate xm '1' ++ replicate m '0' ++ replicate ym '1'\n (Just (xn, yn), Just (xm, ym)) ->\n if xn + n + yn <= xm + m + ym\n then replicate xn '0' ++ replicate n '1' ++ replicate yn '0'\n else replicate xm '1' ++ replicate m '0' ++ replicate ym '1'\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.List\nimport qualified Data.Map.Strict as M\n\ncomb :: Int -> Int\ncomb n = div (n * (n - 1)) 2\n\nchange :: Int -> String -> Int -> Int -> String\nchange 0 str _ m = reverse (replicate (m+1) '0' ++ str)\nchange _ _ _ 0 = \"\"\nchange k str n m\n | k >= n = if m >= n then change (k - n) (str ++ \"0\") n (m - n) else \"\"\n | otherwise = \n let (strfst, strsnd) = splitAt k str\n in if m >= k then change 0 (strfst ++ '0' : strsnd) n (m - k) else \"\"\n\ncheck :: String -> Int -> Int -> Int -> Bool\ncheck _ 0 _ 0 = True\ncheck ('0':rest) n acum k = check rest n (acum + 1) k\ncheck ('1':rest) n acum k = check rest (n - 1) acum (k - acum * n)\ncheck _ _ _ _ = False\n\nattempt :: Int -> Int -> Int -> Int -> Char -> Char -> Maybe String\nattempt a01 a10 n m chrn chrm =\n let att = change a01 (replicate n chrn) n m\n in\n if null att || check (reverse att) n 0 a10\n then Nothing\n else Just att\n\nprocess :: String -> String\nprocess str =\n let [a00, a01, a10, a11] = map read . words $ str\n combMap = M.fromList [(comb n, n) | n <- [0..10^5]]\n in\n case (M.lookup a11 combMap, M.lookup a00 combMap) of\n (Nothing, _) -> \"Impossible\"\n (_, Nothing) -> \"Impossible\"\n (Just n, Just m) ->\n case (attempt a01 a10 n m '1' '0', attempt a01 a10 m n '0' '1') of\n (Nothing, Nothing) -> \"Impossible\"\n (Just soln, Nothing) -> soln\n (Nothing, Just solm) -> solm\n (Just soln, Just solm) ->\n if length soln <= length solm\n then soln\n else solm\n\nmain :: IO ()\nmain = interact process"}], "src_uid": "6893987b310c41efb269b63e865355d8"} {"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\nimport Data.List (tails, inits)\n\nmain :: IO ()\nmain =\n interact $\n words\n >>> drop 1\n >>> chunksOf 2\n >>> map (solve >>> bool \"No\" \"Yes\")\n >>> unlines\n\nsolve :: [String] -> Bool\nsolve [s, t] = t `elem` concatMap (map (take n) . tails) [p ++ tail (reverse p) | p <- inits s, not . null $ p]\n where\n n = length t\n\n-- Template --\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [q] <- readInts\n replicateM_ q $ do\n s <- P.unpack <$> readLine\n t <- P.unpack <$> readLine\n let opts = [v ++ drop 1 (reverse si) | si <- inits s, v <- tails si]\n lift $ B.hPutBuilder stdout $ if any (t `isPrefixOf`) opts\n then B.string7 \"YES\\n\"\n else B.string7 \"NO\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List (inits, tails, isPrefixOf)\r\n\r\nallPaths :: String -> [String]\r\nallPaths s = [suffs ++ drop 1 (reverse prefs) | \r\n prefs <- inits s, \r\n suffs <- tails prefs\r\n ]\r\n\r\nmain :: IO ()\r\nmain = do\r\n q <- readLn\r\n replicateM_ q $ do\r\n s <- getLine \r\n t <- getLine\r\n let paths = allPaths s\r\n putStrLn $ if any (t `isPrefixOf`) paths\r\n then \"YES\" else \"NO\""}], "negative_code": [], "src_uid": "d69e10bb05d119ec2ad4b5c0e4304336"} {"source_code": " import qualified Data.ByteString.Char8 as BS\r\n import Control.Monad\r\n import Data.Array.IO\r\n import Data.List\r\n import Data.Maybe\r\n import System.IO\r\n import System.IO.Unsafe\r\n\r\n deb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\n parseInt = fst . fromJust . BS.readInt\r\n parseInteger = fst . fromJust . BS.readInteger\r\n\r\n solve :: Int -> [(Int, Char, Int)] -> [(Int, Int)]\r\n solve n uws =\r\n let\r\n ws = sort uws\r\n in\r\n go ws []\r\n where\r\n go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]\r\n go [] [] = []\r\n go [] [_] = []\r\n go [] ((x,i):(y,j):ss) =\r\n let\r\n k = (2*n-x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go [] ss\r\n go ((x, d, i):ws) ss\r\n | d == 'R' = go ws ((x,i):ss)\r\n | d == 'L' =\r\n case ss of\r\n [] ->\r\n go ws ((-x,i):ss)\r\n ((y,j):ss) ->\r\n let\r\n k = (x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go ws ss\r\n\r\n main = do\r\n tn <- parseInt <$> BS.getLine\r\n forM_ [1..tn] (\\_ -> do\r\n [m, n] <- map parseInt . BS.words <$> BS.getLine\r\n xs <- map parseInt . BS.words <$> BS.getLine\r\n ds <- map BS.head . BS.words <$> BS.getLine\r\n let w = zip3 xs ds [0::Int ..]\r\n (w0, w1) = partition (\\(x,_,_) -> even x) w\r\n r0 = solve n w0\r\n r1 = solve n w1\r\n r <- newArray (0, m-1) (-1) :: IO (IOUArray Int Int)\r\n forM_ (r0 ++ r1) (\\(x, i) -> writeArray r i x)\r\n\r\n putStrLn . unwords . map show =<< getElems r\r\n )\r\n\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: Int -> [(Int, Char, Int)] -> [(Int, Int)]\r\nsolve n uws =\r\n let\r\n ws = sort uws\r\n in\r\n go ws []\r\n where\r\n go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]\r\n go [] [] = []\r\n go [] [_] = []\r\n go [] ((x,i):(y,j):ss) =\r\n let\r\n k = (2*n-x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go [] ss\r\n go ((x, d, i):ws) ss\r\n | d == 'R' = go ws ((x,i):ss)\r\n | d == 'L' =\r\n case ss of\r\n [] ->\r\n go ws ((-x,i):ss)\r\n ((y,j):ss) ->\r\n let\r\n k = (x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go ws ss\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n [m, n] <- map parseInt . BS.words <$> BS.getLine\r\n xs <- map parseInt . BS.words <$> BS.getLine\r\n ds <- map BS.head . BS.words <$> BS.getLine\r\n let w = zip3 xs ds [0::Int ..]\r\n (w0, w1) = partition (\\(x,_,_) -> even x) w\r\n r0 = solve n w0\r\n r1 = solve n w1\r\n r = elems $ runSTUArray $ do\r\n ra <- newArray (0, m-1) (-1)\r\n forM_ (r0 ++ r1) (\\(x, i) -> writeArray ra i x)\r\n return ra\r\n putStrLn . unwords . map show $ r\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: Int -> [(Int, Char, Int)] -> [(Int, Int)]\r\nsolve n uws =\r\n let\r\n ws = sort uws\r\n in\r\n go ws []\r\n where\r\n go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]\r\n go [] [] = []\r\n go [] [_] = []\r\n go [] ((x,i):(y,j):ss) =\r\n let\r\n k = (2*n-x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go [] ss\r\n go ((x, d, i):ws) ss\r\n | d == 'R' = go ws ((x,i):ss)\r\n | d == 'L' =\r\n case ss of\r\n [] ->\r\n go ws ((-x,i):ss)\r\n ((y,j):ss) ->\r\n let\r\n k = (x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go ws ss\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n forM_ [1..tn] (\\_ -> do\r\n [m, n] <- map parseInt . BS.words <$> BS.getLine\r\n xs <- map parseInt . BS.words <$> BS.getLine\r\n ds <- map BS.head . BS.words <$> BS.getLine\r\n let w = zip3 xs ds [0::Int ..]\r\n (w0, w1) = partition (\\(x,_,_) -> even x) w\r\n r0 = solve n w0\r\n r1 = solve n w1\r\n r = elems $ runSTUArray $ do\r\n ra <- newArray (0, m-1) (-1)\r\n forM_ (r0 ++ r1) (\\(x, i) -> writeArray ra i x)\r\n return ra\r\n putStrLn . unwords . map show $ r\r\n )\r\n\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Data.Array.IO\r\nimport Data.List\r\nimport Data.Maybe\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nsolve :: Int -> [(Int, Char, Int)] -> [(Int, Int)]\r\nsolve n uws =\r\n let\r\n ws = sort uws\r\n in\r\n go ws []\r\n where\r\n go :: [(Int, Char, Int)] -> [(Int, Int)] -> [(Int, Int)]\r\n go [] [] = []\r\n go [] [_] = []\r\n go [] ((x,i):(y,j):ss) =\r\n let\r\n k = (2*n-x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go [] ss\r\n go ((x, d, i):ws) ss\r\n | d == 'R' = go ws ((x,i):ss)\r\n | d == 'L' =\r\n case ss of\r\n [] ->\r\n go ws ((-x,i):ss)\r\n ((y,j):ss) ->\r\n let\r\n k = (x-y) `div` 2\r\n in\r\n (k,i) : (k,j) : go ws ss\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n forM_ [1..tn] (\\_ -> do\r\n [m, n] <- map parseInt . BS.words <$> BS.getLine\r\n xs <- map parseInt . BS.words <$> BS.getLine\r\n ds <- map BS.head . BS.words <$> BS.getLine\r\n let w = zip3 xs ds [0::Int ..]\r\n (w0, w1) = partition (\\(x,_,_) -> even x) w\r\n r0 = solve n w0\r\n r1 = solve n w1\r\n r <- newArray (0, m-1) (-1) :: IO (IOArray Int Int)\r\n forM_ (r0 ++ r1) (\\(x, i) -> writeArray r i x)\r\n\r\n putStrLn . unwords . map show =<< getElems r\r\n )\r\n\r\n"}], "negative_code": [], "src_uid": "1a28b972e77966453cd8239cc5c8f59a"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = do\n getLine\n as <- sort . map read . words <$> getLine :: IO [Integer]\n print $ minimum $\n takeWhile\n (<= sum as)\n [ sum $ abs <$> zipWith (-) as (iterate (* c) 1)\n | c <- [1 ..]\n ]\n", "positive_code": [{"source_code": "import Data.List ( sort, foldl' )\n\ncost :: [Integer] -> Integer -> (Integer, Integer)\ncost li c = let\n inp = zip li $ iterate (* c) 1\n fun (p, q) (val, tar) = let\n diff = tar - val\n in seq p $ seq q $ (p + max 0 diff, q - min 0 diff)\n in foldl' fun (0, 0) inp\n\n-- no need to special-case n=1 or n=2 for performance reasons since n>=3\nsolve :: [Integer] -> Integer\nsolve li = let\n sli = sort li\n (c1, c2) = cost sli 1\n fun x k = let\n (p, q) = cost sli k\n in if x < p then x else fun (min x $ p + q) (k+1)\n in fun (c1 + c2) 2\n\nmain :: IO ()\nmain = do\n _nStr <- getLine\n li <- map read . words <$> getLine\n print (solve li)\n"}], "negative_code": [{"source_code": "import Data.List ( sort, foldl' )\n\ncost :: [Integer] -> Integer -> (Integer, Integer)\ncost li c = let\n inp = zip li $ iterate (* c) 1\n fun (p, q) (val, tar) = let\n diff = tar - val\n in seq p $ seq q $ (p + max 0 diff, q - min 0 diff)\n in foldl' fun (0, 0) inp\n\n-- no need to special-case n=1 or n=2 for performance reasons since n>=3\nsolve :: [Integer] -> Integer\nsolve li = let\n sli = sort li\n (c1, c2) = cost sli 1\n fun x k = let\n (p, q) = cost li k\n in if x < p then x else fun (min x $ p + q) (k+1)\n in fun (c1 + c2) 2\n\nmain :: IO ()\nmain = do\n _nStr <- getLine\n li <- map read . words <$> getLine\n print (solve li)\n"}], "src_uid": "54e9c6f24c430c5124d840b5a65a1bc4"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (nk : l : rest) = itoline (solve (last $ linetois nk) (linetois l)) : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: Int -> [Int] -> Integer\nsolve k as = 1 + toInteger m + toInteger k * (toInteger mc - 1) where\n (mc,m) = if null l then (1,-1) else maximum l\n l = [(length t, head t) | t <- group $ sort $ [(k - (a `mod` k)) `mod` k | a <- as, a `mod` k /= 0]]\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.IntMap\nimport Data.List\nimport Data.Tuple\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_,k] <- fmap read . words <$> getLine\n a <- fmap swap . toList . fromListWith (+) . fmap (\\x -> (x,1)) . mfilter ((/=) 0) . fmap (\\x -> mod (k - mod x k) k) . fmap read . words <$> getLine\n print $ if a == [] then 0 else let (c,m) = maximum a in (fromIntegral c - 1) * fromIntegral k + fromIntegral m + 1\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n p <- read <$> getLine :: IO Int\n replicateM_ p solveCase\nsolveCase = do\n [n,k] <- fmap read . words <$> getLine :: IO [Integer]\n as <- fmap read . words <$> getLine :: IO [Integer]\n solveCaseP k as\nsolveCaseP k as = let as' = fmap (\\a -> k - a)\n . dropWhile (== 0)\n . sort\n $ fmap (\\a -> a `mod` k) as\n (b,c) = if null as' then (1,-1) else findPlurality as'\n in print $ k*(b-1)+(c+1)\n\nfindPlurality as = (\\a -> (fromIntegral (length a), head a))\n . foldl1' (\\a b -> if length a >= length b then a else b)\n $ group as\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.IntMap\nimport Data.List\nimport Data.Tuple\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n,k] <- fmap read . words <$> getLine\n a <- fmap swap . toList . fromListWith (+) . fmap (\\x -> (x,1)) . mfilter ((/=) 0) . fmap (\\x -> mod (k - mod x k) k) . fmap read . words <$> getLine\n print $ if a == [] then 0 else let (c,m) = maximum a in (fromIntegral c - 1) * k + fromIntegral m + 1\n"}, {"source_code": "import Control.Monad\nimport Data.IntMap\nimport Data.List\nimport Data.Tuple\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n,k] <- fmap read . words <$> getLine\n a <- fmap swap . toList . fromListWith (+) . fmap (\\x -> (x,1)) . mfilter ((/=) 0) . fmap (\\x -> mod (k - mod x k) k) . fmap read . words <$> getLine\n print $ if a == [] then 0 else let (c,m) = maximum a in (c - 1) * k + m + 1\n"}, {"source_code": "import Control.Monad\nimport Data.IntMap\nimport Data.List\nimport Data.Tuple\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n,k] <- fmap read . words <$> getLine\n (c,m) <- maximum . fmap swap . toList . fromListWith (+) . fmap (\\x -> (mod (k - mod x k) k,1)) . fmap read . words <$> getLine\n print $ (c - 1) * k + m + 1\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n p <- read <$> getLine :: IO Int\n replicateM_ p solveCase\nsolveCase = do\n [n,k] <- fmap read . words <$> getLine :: IO [Int]\n as <- fmap read . words <$> getLine :: IO [Int]\n solveCaseP n k as\nsolveCaseP n k as = let as' = fmap (\\a -> k - a)\n . dropWhile (== 0)\n . sort\n $ fmap (\\a -> a `mod` k) as\n (b,c) = if null as' then (1,-1) else findPlurality as'\n in print $ k*(b-1)+(c+1)\n\nfindPlurality as = (\\a -> (length a, head a))\n . foldl1' (\\a b -> if length a >= length b then a else b)\n $ group as\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n p <- read <$> getLine :: IO Int\n print p\n replicateM_ p solveCase\nsolveCase = do\n [n,k] <- fmap read . words <$> getLine :: IO [Int]\n as <- fmap read . words <$> getLine :: IO [Int]\n solveCaseP n k as\nsolveCaseP n k as = let as' = fmap (\\a -> k - a)\n . dropWhile (== 0)\n . sort\n $ fmap (\\a -> a `mod` k) as\n (b,c) = if null as' then (1,-1) else findPlurality as'\n in print $ k*(b-1)+(c+1)\n\nfindPlurality as = (\\a -> (length a, head a))\n . foldl1' (\\a b -> if length a >= length b then a else b)\n $ group as\n"}, {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (nk : l : rest) = itoline (solve (last $ linetois nk) (linetois l)) : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: Int -> [Int] -> Int\nsolve k as = 1 + m + k * (mc - 1) where\n (mc,m) = if null l then (1,-1) else maximum l\n l = [(length t, head t) | t <- group $ sort $ [(k - (a `mod` k)) `mod` k | a <- as, a `mod` k /= 0]]\n"}], "src_uid": "a8b4c115bedda3847e7c2e3620e3e19b"} {"source_code": "getinp :: IO [Int]\ngetinp = map read . words <$> getLine\n\ndo_solve :: Int -> IO ()\ndo_solve 0 = return ()\ndo_solve n = do\n vals <- getinp\n frst <- getinp\n scnd <- getinp\n putStrLn $ id $ let f = maximum frst; s = maximum scnd in if f >= s then \"YES\" else \"NO\"\n do_solve (n - 1)\n\n\nmain :: IO ()\nmain = do\n ntest <- getinp\n do_solve $ head ntest", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nonecase = do\n\t\tgetLine\n\t\ta<- map read <$> words <$> getLine::IO [Int]\n\t\tb<- map read <$> words <$> getLine::IO [Int]\n\t\tputStrLn $ if maximum a > maximum b then \"YES\" else \"NO\"\n\n\nmain = do\n\t\tt<- read <$> getLine ::IO Int\n\t\treplicateM_ t onecase\n\n"}, {"source_code": "--ghc 7.10\n\nwinner :: [Int] -> [Int] -> String\nwinner as bs\n | maximum as > maximum bs = \"YES\"\n | otherwise = \"NO\"\n\nprocess :: Int -> IO ()\nprocess 0 = return ()\nprocess t = do\n line1 <- getLine\n line2 <- getLine\n let as = map read . words $ line2\n line3 <- getLine\n let bs = map read . words $ line3\n putStrLn $ winner as bs\n process (t-1)\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n process t"}, {"source_code": "import Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine :: IO [Integer]\n bs <- map read . words <$> getLine :: IO [Integer]\n putStrLn $ bool \"NO\" \"YES\" $ maximum as > maximum bs"}], "negative_code": [], "src_uid": "3ef23f114be223255bd10131b2375b86"} {"source_code": "import List\nmain = interact (show.s.map read.words)\ns (n:b:xs) = foldl f b (init(tails xs)) where f z y = max z (b`mod`a+b`div`a*maximum y) where a=head y\n", "positive_code": [{"source_code": "getArray = fmap (map read . words) getLine\n\nmain = do\n\t[n, b] <- getArray\n\ta <- getArray\n\tputStrLn $ show $ maximum $ b: zipWith (\\x y -> b + div b x * (y - x)) (scanl1 min a) (tail a)\n"}, {"source_code": "getArray = fmap (map read . words) getLine\n\nmain = do\n\t[n, b] <- getArray\n\ta <- getArray\n\tputStrLn $ show $ maximum $ zipWith (\\x y -> b + div b y * (x - y)) a $ scanl1 min a\n\n-- \n"}, {"source_code": "\nimport Array\n\nsolve :: Int -> Array Int Int -> Int\nsolve b a = maximum $ b : [solve' i j | i <- [1..n], j <- [i+1..n]]\n where\n n = snd $ bounds a\n solve' i j\n | a ! i <= a ! j = div b (a ! i) * (a ! j) + mod b (a ! i)\n | otherwise = b\n\nmain :: IO ()\nmain = do\n [n, b] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n let array = listArray (1, n) xs\n print $ solve b array\n"}, {"source_code": "import Data.List (maximumBy)\n\ncreateWay [] = []\ncreateWay xs = (map (\\z -> (y, z)) xs):createWay ys\n where (y:ys) = xs\n\nsolve (x:xs) = maximum $ map (\\(a, b) -> (x `div` a) * b + (x `mod` a)) $ concat $ createWay xs\n\nmain = interact (show.solve.map read.tail.words)"}, {"source_code": "import Data.List\nmain = interact solve\nsolve input = output where\n [[n,b],a] = map (map (read::String->Int)) $ map words $ lines input\n output = show $ answer a + b\n answer [] = 0\n answer (x:xs) = foldl' max (answer xs) [div b x * (y-x)|y<-xs,y>x]"}, {"source_code": "main = do\n let i = fmap (map read . words) getLine :: IO [Int]\n [n, b] <- i\n a <- i\n if n == 1\n then print b\n else print $ max b $ foldl1 max $ zipWith (\\x y -> b`mod`x+b`div`x*y) (init a) (tail $ scanr1 max a)"}, {"source_code": "main = do\n\tn:b:a <- fmap (map read . words) getContents\n\tputStrLn $ show $ maximum $ zipWith (\\x y -> b + div b y * (x - y)) a $ scanl1 min a\n"}], "negative_code": [{"source_code": "getArray = fmap (map read . words) getLine\n\nmain = do\n\t[n, b] <- getArray\n\ta <- getArray\n\tputStrLn $ show $ maximum $ zipWith (\\x y -> b + div b x * (y - x)) a $ scanl1 min a\n\n-- \n"}, {"source_code": "import Data.List (maximumBy)\n\ncreateWay [] = []\ncreateWay xs = (map (\\z -> (y, z)) xs):createWay ys\n where (y:ys) = xs\n\ngetMax xs = maximumBy p $ filter (\\(a, b) -> a <= b) $ concat $ createWay xs\n where p (a1, b1) (a2, b2) = compare (b1 - a1) (b2 - a2)\n\nsolve (x:xs) = (x `div` a) * b + (x `mod` a)\n where (a, b) = getMax xs\n\nmain = interact (show.solve.map read.tail.words)"}], "src_uid": "2c9133650d831fa6ab4c11661bcb9cbb"} {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let rs = findIndices odd (0:as)\n l = length rs\n if l < k || odd l /= odd k then putStrLn \"NO\" else do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ init (drop (l-k) rs) ++ [n]\n", "positive_code": [{"source_code": "main = interact $ unlines . process . tail . lines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (a:b:xs) = (work a b) : (process xs)\n\nwork :: String -> String -> String\nwork a b\n | len < k = \"NO\"\n | odd (len - k) = \"NO\"\n | otherwise = \"YES\\n\" ++ unwords(map show $ take (k-1) odds ++ [n])\n where \n n : k : _ = (map read $ words a) :: [Int]\n arr = (map read $ words b) :: [Integer]\n odds = map snd $ filter (odd . fst) $ zip arr [1..]\n len = length odds\n"}, {"source_code": "import Control.Monad (replicateM_)\n\nfindSegments :: Int -> Int -> [Int] -> [Int]\nfindSegments n k xs\n | numOdds < k || (numOdds - k) `mod` 2 == 1 = []\n | otherwise = (take (k - 1) $ map snd odds) ++ [n]\n where \n odds = filter (\\(x, _) -> x `mod` 2 == 1) (zip xs [1..n])\n numOdds = length odds\n\nreadLine :: IO [Int]\nreadLine = (map read) . words <$> getLine\n\nmain =\n read <$> getLine >>= \\q ->\n replicateM_ q (\n readLine >>= \\[n, k] ->\n readLine >>= \\xs ->\n putStrLn(\n let ans = findSegments n k xs in\n if null ans then \"NO\"\n else \"YES\\n\" ++ unwords (map show ans)\n )\n )"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let rs = findIndices odd (0:as)\n l = length rs\n if l < k || odd l /= odd k then putStrLn \"NO\" else do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ drop (l-k) rs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let rs = findIndices odd (0:as)\n l = length rs\n if l < k || odd l /= odd k then putStrLn \"NO\" else do\n putStrLn \"YES\"\n putStrLn $ unwords $ map show $ drop (k-l) rs\n"}], "src_uid": "7f5269f3357827b9d8682d70befd3de1"} {"source_code": "import System.IO\n\ngetBestRun :: Int -> [Int] -> (Int, Int)\ngetBestRun n [] = (0, 0)\ngetBestRun n (x:xs) | x == n = (0, restBest)\n | otherwise = (next + 1, best)\n where (next, restBest) = getBestRun n xs\n best = if next >= restBest then (next + 1) else restBest\n\ngetBestRunFromStr :: Int -> [String] -> Int\ngetBestRunFromStr n inps = let countArr = map (\\x -> sum [1 | c <- x, c == '1']) inps\n (next, best) = getBestRun n countArr\n in best\n\nmain :: IO ()\nmain = do\n fstStr <- getLine\n let (n:d:_) = map (read :: String -> Int) $ words fstStr\n inpStrs <- (mapM (\\_ -> getLine) [1..d])\n -- putStrLn . show $ getCountArr inpStrs\n putStrLn . show $ getBestRunFromStr n inpStrs\n return ()\n", "positive_code": [{"source_code": "import Data.List\n\nmain = getLine >> getContents >>= print . f . map length . filter ( id . head ) . group . map ( not . all ( == '1' ) ) . lines\n\nf x\n\t| null x = 0\n\t| otherwise = maximum x\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . lines =<< getContents\n\nsolve :: [String] -> Int\nsolve = maximum . (++) [0] . map length . filter head . group . map check\n\ncheck :: String -> Bool\ncheck s = length (filter (== '0') s) > 0\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, d] <- fmap (map read . words) getLine\n ls <- replicateM d getLine\n\n let xs = map length $ filter (id . head) $ group $ map (any (== '0')) ls\n print $ if null xs then 0 else maximum xs\n"}, {"source_code": "import Data.List\n\nmain = do\n input <- getContents\n print $ sol $ tail $ lines input\n where sol xs = if any (elem '0') xs then (maximum . map length . filter (\\x -> head x) . group . map (elem '0')) xs\n else 0\n"}, {"source_code": "import Data.List\nimport Data.Char\nmain = do\n [n,d] <- map read . words <$> getLine\n print . maximum . (0 :) . map length . filter head . group . map ((< n) . sum . map digitToInt) . lines =<< getContents\n"}, {"source_code": "import System.IO\n\ngetBestRun :: Int -> [Int] -> (Int, Int)\ngetBestRun n [] = (0, 0)\ngetBestRun n (x:xs) | x == n = (0, restBest)\n | otherwise = (next + 1, best)\n where (next, restBest) = getBestRun n xs\n best = if next >= restBest then (next + 1) else restBest\n\ngetBestRunFromStr :: Int -> [String] -> Int\ngetBestRunFromStr n inps = let countArr = map (\\x -> sum [1 | c <- x, c == '1']) inps\n (next, best) = getBestRun n countArr\n in best\n\nmain :: IO ()\nmain = do\n fstStr <- getLine\n let (n:d:_) = map (read :: String -> Int) $ words fstStr\n inpStrs <- (mapM (\\_ -> getLine) [1..d])\n putStrLn . show $ getBestRunFromStr n inpStrs\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n \nmain = do\n [n, d] <- map read . words <$> getLine\n [ss] <- transpose . map words <$> replicateM d getLine\n print $ maximum $ map length $ [] : (filter (any (== True)) $ group $ map (any (== '0')) ss)\n\n"}, {"source_code": "import Data.List\n \nmain = getContents >>= print . maximum . map (\\ls -> if head ls then length ls else 0) . group . map ('0' `elem`) . tail . lines\n"}, {"source_code": "import Data.List( group)\nmain = do\n [n,d] <- return . map read . words =<< getLine\n abs <- sequence $ take d $ repeat getLine\n let isAbletoWin = not . cantWin\n\tcantWin = all (=='1')\n\tresults = isAbletoWin `map` abs\n\twins = filter (True `elem`) $ group results\n\twinconts = length `map` wins\n if winconts == []\n\tthen print 0\n\telse print $ maximum winconts\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nmymax e [] m n = max m n\nmymax e (d:ds) m n | e/=d = mymax e ds m (n+1)\n\t\t | otherwise = mymax e ds (max m n) 0 \n\nmain = do\n\t\t[n,k]<- map read <$> words <$> getLine:: IO [Int]\n\t\td<-replicateM k getLine\n\t\tlet e= replicate n '1'\n\t\tprint $ mymax e d 0 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nbeat = any (=='0')\n\ncheck [] n = [n]\ncheck (l:ls) n = \n if beat l \n then n:check ls (n+1)\n else n:check ls 0\n\n\n\nmain = do\n [n, d] <- map read . words <$> getLine\n ls <- replicateM d getLine\n print $ maximum $ check ls 0\n"}, {"source_code": "import Data.List (group)\n\nprocess :: [[Char]] -> Int\nprocess = maximum.map (\\x -> if head x then length x else 0).group.map (any (=='0'))\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,d] <- fmap (map readInt.words) getLine\n xs <- fmap lines getContents\n print $ process xs"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\n-- Meat\nsolve :: [String]-> Int\nsolve = maximum.(0:).fmap length.filter head.group.fmap (elem '0')\n\n\n-- Shit\nmain :: IO ()\nmain = do\n (_:es) <- readShit\n printShit [solve es]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "import Data.List\nmain=interact$show.maximum.(0:).fmap length.filter head.group.fmap(elem '0').tail.lines"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . lines =<< getContents\n\nsolve :: [String] -> Int\nsolve = maximum . map length . group . map check\n\ncheck :: String -> Bool\ncheck s = length (filter (== '0') s) > 0\n"}, {"source_code": "import Data.List\n\nmain = do\n input <- getContents\n print $ sol $ tail $ lines input\n where sol = (maximum . map length . group . map (elem '0'))\n"}], "src_uid": "a6ee741df426fd2d06fdfda4ca369397"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n replicateM_ n (do\n [a, b] <- map read . words <$> getLine\n putStrLn $ show $ (a + b - 1) `div` b * b - a)\n", "positive_code": [{"source_code": "\nmain = interact $ unlines . map ( show . (\\ [b,a] -> if b `mod` a == 0 then 0 else a - (b `mod` a)) . map (read :: String -> Int) . words) . tail . lines"}, {"source_code": "main :: IO ()\nmain = map (solve . parse) . tail . lines <$> getContents >>= mapM_ print\n where\n parse = f . words\n f [a, b] = (read a, read b)\n\nsolve :: (Int, Int) -> Int\nsolve (a, b) = ((a + b - 1) `div` b) * b - a\n"}, {"source_code": "import Control.Monad (replicateM_)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\n\n\n\nmain = readLn >>= flip replicateM_ solve\n\nsolve = do\n [a,b] <- getList\n print $ (-a) `mod` b"}, {"source_code": "-- PROBLEM: https://codeforces.com/contest/1328/problem/A\n\nimport Control.Arrow ((>>>))\n\nmain :: IO()\nmain = \n interact $\n lines >>> drop 1 >>> map ((words >>> map read) >>> solve >>> show) >>> unlines\n\nsolve :: [Int] -> Int\nsolve [u, v]\n | mod u v == 0 = 0\n | otherwise = v - mod u v\n\n"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n [a, b] <- map read . words <$> getLine\n let m = mod a b\n print $ if m == 0 then 0 else b - m\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nans a b | z==0 = 0\n | otherwise = b-z\n\twhere z= mod a b\nonecase= do\n\t\t[a,b]<-map read <$> words<$> getLine ::IO [Int]\n\t\tprint $ ans a b\n\nmain = do\n\t\tn<-read <$> getLine :: IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n replicateM_ n $ print =<< (\\[a,m]->(-a)`mod`m) . map (read :: String -> Int) . words <$> getLine"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n replicateM_ n $ print =<< (\\[a,m]->(m - a`mod`m)`mod`m) . map (read :: String -> Int) . words <$> getLine"}, {"source_code": "import Data.List\n\nprocess :: (Int,Int) -> Int\nprocess (a,b) = (b - a) `mod` b\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int,Int)\nreadPair line = (a,b)\n where [a,b] = map readInt $ words line\n\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readPair.lines) getContents\n sequence . map (print . process) $ xs"}, {"source_code": "import Control.Monad\nimport Text.Printf\n\nmove :: Integer -> Integer -> Integer\nmove a b = case mod a b of\n 0 -> 0\n c -> b - c\n\nmain = do\n i <- getLine\n let t = read i :: Integer\n forM_ [1..t] $ \\ _ -> do\n ii <- getLine\n let [a,b] = map (\\x -> read x :: Integer) $ words ii\n let c = move a b\n printf \"%v\\n\" c\n"}, {"source_code": "main :: IO ()\n\nmain = do\n getLine\n answers <- map (solve . map read . words) <$> lines <$> getContents :: IO [Int]\n mapM_ print answers\n\nsolve [x,y] = (-x) `mod` y\n"}, {"source_code": "import Control.Arrow\n\nmain :: IO ()\nmain = interact $\n lines >>> tail >>> map supersolve >>> unlines\n\nsupersolve :: String -> String\nsupersolve = words >>> map read >>> solve2 >>> show\n\nsolve2 [a, b] = solve a b\nsolve2 [] = 0\n\nsolve :: Int -> Int -> Int\nsolve a b\n | a `mod` b == 0 = 0\n | otherwise = b - (a `mod` b)"}, {"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> drop 1 \n >>> map ((words >>> map read) >>> solve >>> show) \n >>> unlines\n\nsolve :: [Integer] -> Integer\nsolve [a, b] \n | d == 0 = 0\n | otherwise = b - d\n where d = a `mod` b"}, {"source_code": "import Control.Monad (replicateM, forM_)\n\n\n\ngetSolution :: [Int] -> Int\n\ngetSolution (a : b : []) =\n\n let\n\n x = a `mod` b\n\n in case x of\n\n 0 -> 0\n\n otherwise -> (b - x)\n\n\n\n\n\nmain = do\n\n -- could also do t <- readLn :: IO Int\n\n t <- fmap (read :: String -> Int) getLine\n\n -- putStrLn $ show t\n\n line <- replicateM t getLine\n\n let\n\n splitted = fmap words line\n\n casted = (fmap . fmap) (read :: String -> Int) splitted\n\n solutions = fmap getSolution casted -- [Int]\n\n in\n\n forM_ (fmap show solutions) putStrLn\n\n"}, {"source_code": "main=interact$unlines.map s.drop 1.lines\ns=show.t.map read.words\nt[a,b]=mod(b-mod a b)b\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [x, y] <- getIntList\n print $ (y - x `mod` y) `mod` y"}, {"source_code": "main = getLine >>= test.read\ntest 0 = return ();\ntest i = do\n (a:b:_) <- map read.words <$> getLine\n print $ (b - a `mod` b) `mod` b\n test (i - 1)"}], "negative_code": [], "src_uid": "d9fd10700cb122b148202a664e7f7689"} {"source_code": "import Control.Monad\n\nlinha :: Int -> Int -> String\nlinha n m = [ \"BW\"!!pos | h <- [0..m-2], let pos = (n+h)`mod`2 ] ++ \"B\"\n\ncheckers :: Int -> Int -> [String]\ncheckers n m = [ [ \"BW\"!!pos | h <- [0..m-1], let pos = (i+h)`mod`2 ] | i <- [0..n-1] ]\n\nfoo :: Int -> Int -> [String]\nfoo n m | odd n && odd m = checkers n m\n | even n && even m = [linha 0 m] ++ (tail (checkers n m))\n | otherwise = (init (checkers n m)) ++ [linha (n-1) m]\n\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain :: IO()\nmain = do\n t <- readLn :: IO Int\n\n forM_ [1..t] $ \\i -> do\n a <- readInts\n let out = foo (a!!0) (a!!1)\n forM_ [0..(a!!0 - 1)] $ \\l -> do\n putStrLn (out!!l)\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nreshape _ 0 _ = []\nreshape w h elems =\n let (row, rest) = splitAt w elems in row : reshape w (h - 1) rest\n\nf :: [Int] -> [[String]]\nf [h, w] = reshape w h $ take (w * h) $ \"W\" : repeat \"B\"\n\nsplitInput :: String -> [[Int]]\nsplitInput = map (map read . words) . tail . lines\n\ngo :: String -> String\ngo input =\n let answers :: [[[String]]] = map f (splitInput input) in\n concat $ map (unlines . map concat) answers\n\nmain = interact go\n"}, {"source_code": "solve :: Int -> Int -> String\nsolve n m\n | odd len = board\n | otherwise = if (odd m) then ((init board) ++ \"B\") else (\"BB\" ++ (drop 2 board))\n where len = n*m\n board = [printer i j | i <- [0..(n-1)], j <- [0..(m-1)]]\n\nprinter :: Int -> Int -> Char\nprinter i j\n | even i && even j = 'B'\n | even i && odd j = 'W'\n | odd i && even j = 'W'\n | otherwise = 'B'\n\npartitionBy :: Int -> String -> [String]\npartitionBy _ \"\" = []\npartitionBy n input = [(take n input)] ++ (partitionBy n (drop n input))\n\nparse :: String -> String\nparse contents = foldl (++) \"\" solutions\n where lines' = tail $ lines contents\n inputs = map (\\[n', k'] -> (read n' :: Int, read k' :: Int)) $ map words lines'\n solutions = map (\\(n, k) -> unlines (partitionBy k (solve n k))) inputs\n\nmain :: IO ()\nmain = do\n contents <- getContents\n putStr (parse contents)\n"}, {"source_code": "import Control.Monad\n\ntype Test = (Integer, Integer)\ntype Row = [Char]\ntype Board = [Row]\n\ngetTests :: Int -> IO [Test]\ngetTests n = replicateM n getTest\n\ngetTest :: IO Test\ngetTest = do\n test <- getLine\n return $ parseTest test\n\nparseTest :: String -> Test\nparseTest str = (parsed !! 0, parsed !! 1)\n where parsed = map read (words str)\n\ngetAnswer :: [Test] -> [Board]\ngetAnswer [] = []\ngetAnswer ((n, m):rest) = if not $ odd (n*m)\n then change board : (getAnswer rest)\n else board : (getAnswer rest)\n where board = getChessBoard n m\n\nchange :: Board -> Board\nchange (first:rest) = if m > 1\n then (removeOneW first):rest\n else [first] ++ [removeOneW $ head rest] ++ (tail rest)\n where m = length first\n\nremoveOneW :: Row -> Row\nremoveOneW (symbol:rest) = if symbol == 'W'\n then 'B':rest\n else symbol: removeOneW rest\n\ngetChessBoard :: Integer -> Integer -> Board\ngetChessBoard n m = getChessBoard' n (getChessLine 'B' m)\n\ngetChessBoard' :: Integer -> Row -> Board\ngetChessBoard' 0 row = []\ngetChessBoard' n row = row : getChessBoard' (n - 1) (interchange row)\n\ninterchange :: Row -> Row\ninterchange [] = []\ninterchange (first:rest) = newSymbol : interchange rest\n where newSymbol = if first == 'W'\n then 'B'\n else 'W'\n\ngetChessLine :: Char -> Integer -> Row\ngetChessLine symbol 0 = []\ngetChessLine symbol m = symbol : getChessLine nextSymbol (m-1)\n where nextSymbol = if symbol == 'W'\n then 'B'\n else 'W'\n\nprintTest :: Board -> IO ()\nprintTest board = do\n mapM_ putStrLn board\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getTests $ read count\n mapM_ printTest (getAnswer tests)"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, m] <- getIntList\n putStr $ f n m\n\ng :: Int -> String\ng m = take m \n . concat\n $ repeat \"BW\"\n\nr :: Char -> Char\nr 'B' = 'W'\nr 'W' = 'B'\n\ns :: Int -> Int -> String\ns n m = concat\n . map (++\"\\n\")\n . take n\n $ iterate (map r) (g m)\n\nf :: Int -> Int -> String\nf n m\n | odd (n * m) = s n m\n | otherwise = 'B' : 'B' : (drop 2 $ s n m)\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nreshape _ 0 _ = []\nreshape w h elems =\n let (row, rest) = splitAt w elems in row : reshape w (h - 1) rest\n\nelemsList :: Int -> Int -> [String]\nelemsList w h\n | odd (w * h) = take (w * h) $ cycle[\"B\", \"W\"]\n | otherwise = (take (w * h - 1) $ cycle[\"B\", \"W\"]) ++ [\"B\"]\n\nf :: [Int] -> [[String]]\nf [h, w] = reshape w h $ elemsList w h\n\nsplitInput :: String -> [[Int]]\nsplitInput = map (map read . words) . tail . lines\n\ngo :: String -> String\ngo input =\n let answers :: [[[String]]] = map f (splitInput input) in\n concat $ map (unlines . map concat) answers\n\nmain = interact go"}, {"source_code": "solve :: Int -> Int -> String\nsolve n m\n | odd len = board\n | otherwise = if (odd m) then ((init board) ++ \"B\") else (\"BB\" ++ (drop 2 board))\n where len = n*m\n board = [printer i j | j <- [0..(m-1)], i <- [0..(n-1)]]\n\nprinter :: Int -> Int -> Char\nprinter i j\n | even i && even j = 'B'\n | even i && odd j = 'W'\n | odd i && even j = 'W'\n | otherwise = 'B'\n\npartitionBy :: Int -> String -> [String]\npartitionBy _ \"\" = []\npartitionBy n input = [(take n input)] ++ (partitionBy n (drop n input))\n\nparse :: String -> String\nparse contents = foldl (++) \"\" solutions\n where lines' = tail $ lines contents\n inputs = map (\\[n', k'] -> (read n' :: Int, read k' :: Int)) $ map words lines'\n solutions = map (\\(n, k) -> unlines (partitionBy k (solve n k))) inputs\n\nmain :: IO ()\nmain = do\n contents <- getContents\n putStr (parse contents)\n"}, {"source_code": "solve :: Int -> Int -> String\nsolve n m\n | odd len = board\n | otherwise = (init board) ++ \"B\"\n where len = n*m\n board = [if even i then 'B' else 'W' | i <- [0..(len-1)]]\n\npartitionBy :: Int -> String -> [String]\npartitionBy _ \"\" = []\npartitionBy n input = [(take n input)] ++ (partitionBy n (drop n input))\n\nparse :: String -> String\nparse contents = foldl (++) \"\" solutions\n where lines' = tail $ lines contents\n inputs = map (\\[n', k'] -> (read n' :: Int, read k' :: Int)) $ map words lines'\n solutions = map (\\(n, k) -> unlines (partitionBy k (solve n k))) inputs\n\nmain :: IO ()\nmain = do\n contents <- getContents\n putStr (parse contents)\n"}], "src_uid": "2b37f27a98ec8f80d0bff3f7ae8f2cff"} {"source_code": "import Prelude hiding (getLine)\nimport Control.Applicative ((<$>))\nimport Data.List (unfoldr, find)\nimport Control.Monad (forM_, forM)\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.Unboxed (listArray, UArray, (!))\nimport Data.Array.ST.Safe (STUArray, newArray, readArray, writeArray)\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\ndump Nothing = putStrLn \"NO\"\ndump (Just a) = do\n putStrLn \"YES\"\n forM_ a $ (\\(x, y) -> putStrLn $ show x ++ \" \" ++ show y)\n\nloop :: UArray Int Int -> STUArray s Int Bool -> Int -> ST s [Int]\nloop arr tag i = do\n flag <- readArray tag i\n if flag then return []\n else writeArray tag i True >> (i:) <$> loop arr tag (arr ! i)\n\nrun :: Int -> [[Int]] -> Maybe [(Int, Int)]\nrun n a = case find ((== 1) . length) a of\n (Just [r]) -> Just . map ((,) r) $ [1..r - 1] ++ [r + 1..n]\n _ -> case any (odd . length) a of\n True -> Nothing\n False -> case find ((== 2) . length) a of\n Nothing -> Nothing\n (Just [x, y]) -> Just $ (x, y): concatMap go a\n where\n go xs\n | xs == [x, y] = []\n | otherwise = zip xs (cycle [x, y])\n\nsolve :: Int -> [Int] -> Maybe [(Int, Int)]\nsolve n a = run n cycl\n where\n arr = listArray (1, n) a :: UArray Int Int\n\n cycl = filter (not . null) $ runST $ do\n tag <- newArray (1, n) False :: ST s (STUArray s Int Bool)\n mapM (loop arr tag) [1..n]\n\nmain = do\n [n] <- parse <$> getLine\n getLine >>= dump . solve n . parse\n", "positive_code": [{"source_code": "import Prelude hiding (getLine)\nimport Control.Applicative ((<$>))\nimport Data.List (unfoldr, find)\nimport Control.Monad (forM_, forM)\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.Unboxed (listArray, UArray, (!))\nimport Data.Array.ST.Safe (STUArray, newArray, readArray, writeArray)\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\ndump 1 _ = putStrLn \"YES\"\ndump _ [] = putStrLn \"NO\"\ndump _ a = do\n putStrLn \"YES\"\n forM_ a $ (\\(x, y) -> putStrLn $ show x ++ \" \" ++ show y)\n\nloop :: UArray Int Int -> STUArray s Int Bool -> Int -> ST s [Int]\nloop arr tag i = do\n flag <- readArray tag i\n if flag\n then return []\n else writeArray tag i True >> (i:) <$> loop arr tag (arr ! i)\n\nrun :: Int -> [[Int]] -> [(Int, Int)]\nrun n a = case find ((== 1) . length) a of\n (Just [r]) -> map ((,) r) $ [1..r - 1] ++ [r + 1..n]\n _ -> case any (odd . length) a of\n True -> []\n False -> case find ((== 2) . length) a of\n Nothing -> []\n (Just [x, y]) -> (x, y): concatMap go a\n where\n go xs\n | xs == [x, y] = []\n | otherwise = zip xs (cycle [x, y])\n\nsolve :: Int -> [Int] -> [(Int, Int)]\nsolve n a = run n cycl\n where\n arr = listArray (1, n) a :: UArray Int Int\n\n cycl = filter (not . null) $ runST $ do\n tag <- newArray (1, n) False :: ST s (STUArray s Int Bool)\n mapM (loop arr tag) [1..n]\n\nmain = do\n [n] <- parse <$> getLine\n getLine >>= dump n . solve n . parse\n"}], "negative_code": [{"source_code": "import Prelude hiding (getLine)\nimport Control.Applicative ((<$>))\nimport Data.List (unfoldr, find)\nimport Control.Monad (forM_, forM)\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.Unboxed (listArray, UArray, (!))\nimport Data.Array.ST.Safe (STUArray, newArray, readArray, writeArray)\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\ndump [] = putStrLn \"NO\"\ndump a = do\n putStrLn \"YES\"\n forM_ a $ (\\(x, y) -> putStrLn $ show x ++ \" \" ++ show y)\n\nloop :: UArray Int Int -> STUArray s Int Bool -> Int -> ST s [Int]\nloop arr tag i = do\n flag <- readArray tag i\n if flag\n then return []\n else writeArray tag i True >> (i:) <$> loop arr tag (arr ! i)\n\nrun :: Int -> [[Int]] -> [(Int, Int)]\nrun n a = case find ((== 1) . length) a of\n (Just [r]) -> map ((,) r) $ [1..r - 1] ++ [r + 1..n]\n _ -> case any (odd . length) a of\n True -> []\n False -> case find ((== 2) . length) a of\n Nothing -> []\n (Just [x, y]) -> (x, y): concatMap go a\n where\n go xs\n | xs == [x, y] = []\n | otherwise = zip xs (cycle [x, y])\n\nsolve :: Int -> [Int] -> [(Int, Int)]\nsolve n a = run n cycl\n where\n arr = listArray (1, n) a :: UArray Int Int\n\n cycl = filter (not . null) $ runST $ do\n tag <- newArray (1, n) False :: ST s (STUArray s Int Bool)\n mapM (loop arr tag) [1..n]\n\nmain = do\n [n] <- parse <$> getLine\n getLine >>= dump . solve n . parse\n"}], "src_uid": "5ecb8f82b073b374a603552fdd95391b"} {"source_code": "import Data.List (scanl1, sort) \nmain = interact $ show . solve . map read . words\nsolve (_:a) = length $ filter (==0) $ scanl1 (+) $ zipWith (-) a $ sort a", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let mlist = (map read . words) line \n print (chack (sums 0 mlist) (sums 0 (sort mlist)) - 1)\n where\n sums c [] = [c]\n sums c (a:b) = [c + a] ++ sums (a + c) b\n chack [] [] = 0\n chack (a : xv) (b : zv) | a == b = 1 + chack xv zv\n chack (a : xv) (b : zv) = 0 + chack xv zv"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n line <- getLine\n let mlist = (map read . words) line \n print (chack 0 0 mlist (sort mlist))\n where\n chack c d [] [] = 0\n chack c d (a : xv) (b : zv) | c == d = 1 + chack (c+a) (d + b) xv zv\n chack c d (a : xv) (b : zv) = 0 + chack (c+a) (d + b) xv zv"}, {"source_code": "import Control.Applicative\n\nprefixMax = scanl1 max\n\nsuffixMin = scanr1 min\n\ncomputeIndexes prefixMax suffixMin = foldl (\\res (a, b) -> if a <= b then res+1 else res) 1 $ zip prefixMax $ drop 1 suffixMin\n\nmain = do\n n <- readLn\n list <- take n . map read <$> words <$> getLine :: IO [Integer]\n let max = prefixMax list\n min = suffixMin list\n print $ computeIndexes max min\n"}], "negative_code": [], "src_uid": "c1158d23d3ad61c346c345f14e63ede4"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ (^2) $ min (max a (b+b)) (max b (a+a))\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\t\n\n", "positive_code": [{"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/A\n\nimport Control.Monad ( replicateM_ )\n\n\nminSquare :: [Int] -> Int\nminSquare [w, h] = max a (2*b) ^ 2\n where a = max w h\n b = min w h\n\n\nreadInput :: IO [Int]\nreadInput = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n x <- read <$> getLine\n replicateM_ x (minSquare <$> readInput >>= print)\n"}, {"source_code": "import Control.Monad ( replicateM_ )\n\n\nreadInput = map read . words <$> getLine\n\nminSquare [w, h] = (max a (2*b)) ^ 2\n where a = max w h\n b = min w h\n\nmain = do\n x <- read <$> getLine\n replicateM_ x (minSquare <$> readInput >>= print)\n"}, {"source_code": "import Data.Array\n\nmemoize :: Ix i => (i,i) -> (i -> e) -> (i -> e)\nmemoize bnds fun = (array bnds [(i, fun i) | i <- range bnds] !)\n\nlistMemoize :: Ix i => (i,i) -> (i -> e) -> (i -> e)\nlistMemoize bnds fun = let li = map fun (range bnds) in\n \\ix -> li !! (index bnds ix)\n\n\nparse :: String -> [(Int, Int)]\nparse inp = [(x, y) | [x, y] <- map (map read . words) . tail $ lines inp]\n\nsolve :: [(Int, Int)] -> [Int]\nsolve = map (\\(x, y) -> let l = maximum [x, y, 2 * min x y] in l*l)\n\nshowAns :: [Int] -> String\nshowAns = unlines . map show\n\nmain :: IO ()\nmain = interact (showAns . solve . parse)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b] <- sort <$> map (read) <$> words <$> getLine\n print $ sqr $ max b (a * 2)\n where sqr x = x * x"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [a, b] <- map read . words <$> getLine\n print $ min (area (2 * a) b) (area a (2 * b))\n where\n area :: Int -> Int -> Int\n area x y = max x y ^ 2\n"}, {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (a:b:_) <- map read . words <$> getLine\n print $ minimum [max (max a b) (2 * min a b) ^ 2, (a + b) ^ 2]"}, {"source_code": "module Main where\n\nmain = interact $ unlines . map ( show . (^2) . (\\[x,y] -> let z = min (y * 2) (x * 2) in if z >= max x y then z else max x y). map (read :: String -> Integer) . words ) . tail . lines "}, {"source_code": "import Control.Monad (replicateM_)\n\ngetMinSquare [a, b] = side * side where\n side = max (2 * min a b) (max a b)\n\nparseLine = fmap ((map read) . words) getLine\n\nmain =\n fmap read getLine >>= \\t ->\n replicateM_ t (fmap getMinSquare parseLine >>= print)"}], "negative_code": [{"source_code": "module Main where\n\nmain = interact $ unlines . map ( show . (^2) . (\\[x,y] -> if x==y then x else min (y * 2) (x * 2) ). map (read :: String -> Integer) . words ) . tail . lines "}, {"source_code": "module Main where\n\nmain = interact $ unlines . map ( show . (^2) . (\\[x,y] -> min (y * 2) (x * 2) ). map (read :: String -> Integer) . words ) . tail . lines "}, {"source_code": "module Main where\n\nmain = interact $ unlines . map ( show . (^2) . (\\[x,y] -> max (y * 2) (x * 2) ). map (read :: String -> Integer) . words ) . tail . lines "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\t[a,b]<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ min (max a (b+b)) (max b (a+a))\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\t\n\n"}], "src_uid": "3bb093fb17d6b76ae340fab44b08fcb8"} {"source_code": "{-# LANGUAGE Strict #-}\n{-# LANGUAGE LambdaCase #-}\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.List (sort)\nimport Data.Array.Unboxed (accumArray, array, UArray)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = do\n n <- int\n xys <- numberOf (pair int int)\n return . show $ solve n xys\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n xys = length [True | p <- ps, q <- ps, overlap p q] `div` 2\n where\n used = sort . uncurry (++) $ unzip xys\n unused = [1..2*n] `lsub` used\n s = length unused `div` 2\n (ls, rs) = splitAt s unused\n ps = sortP <$> xys ++ zip ls rs\n\noverlap (x, y) (a, b) = (x < a && a < y && y < b) || (a < x && x < b && b < y)\n\nsortP :: Ord a => (a, a) -> (a, a)\nsortP (x, y) = if x <= y then (x, y) else (y, x)\n\nlsub :: Eq a => [a] -> [a] -> [a]\nlsub [] _ = []\nlsub xs [] = xs\nlsub (x:xs) (y:ys) = if x == y then lsub xs ys else x : lsub xs (y:ys)\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n pts <- replicateM k $ do\n [xi, yi] <- readInts\n pure (xi, yi)\n let\n vis :: UArray Int Bool\n vis = accumArray (\\_ _ -> True) False (1, 2*n) $ do\n (xi, yi) <- pts\n [(xi, ()), (yi, ())]\n unvis :: [Int]\n unvis = [i | (i, False) <- assocs vis]\n newpts = zip unvis $ drop (n-k) unvis\n allpts = [(min x y, max x y) | (x, y) <- pts ++ newpts]\n crossings = do\n (x, y) <- allpts\n (p, q) <- allpts\n guard $ x < p -- no double-counting\n guard $ not $ (x < p && q < y) -- not nested\n guard $ not (y < p) -- not disjoint, either -- How did I forget?\n pure [x, y, p, q]\n putInts [length crossings] -- Why is this Wrong Answer??\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.IntSet as IS\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readMany :: IO [Int]\r\n a <- replicateM k $ sort <$> readMany :: IO [[Int]]\r\n let b = uncurry (zipWith (\\x y -> [x, y])) $ splitAt (n - k) rem where\r\n rem = filter (`IS.notMember` used) [1..2*n]\r\n used = IS.fromList $ concat a\r\n isect [_, b] [c, d] = c < b && b < d\r\n print $ sum [1 | (x:ys) <- tails $ sort $ a ++ b, y <- ys, isect x y]\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n pts <- replicateM k $ do\n [xi, yi] <- readInts\n pure (xi, yi)\n let\n vis :: UArray Int Bool\n vis = accumArray (\\_ _ -> True) False (1, 2*n) $ do\n (xi, yi) <- pts\n [(xi, ()), (yi, ())]\n unvis :: [Int]\n unvis = [i | (i, False) <- assocs vis]\n newpts = zip unvis $ drop (n-k) unvis\n allpts = [(min x y, max x y) | (x, y) <- pts ++ newpts]\n crossings = do\n (x, y) <- allpts\n (p, q) <- allpts\n guard $ x < p -- no double-counting\n guard $ not $ (x < p && q < y) || (p < x && y < q) -- not nested\n pure [x, y, p, q]\n -- putInts unvis\n -- forM_ allpts $ \\(x, y) -> putInts [x, y]\n putInts [length crossings] -- Why is this Wrong Answer??\n -- forM_ crossings putInts\n -- putInts []\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "9ca9df1ab3760edb8e7adc3be533c576"} {"source_code": "import Data.List\n\nf ::Int->Int->String->[String]\nf _ _ \"\"=[]\nf n 0 str=(take n str):f n 0 (drop n str)\nf n m str=((take (n-1) str)++\"*\"):f n (m-1) (drop (n-1) str)\n\nmain = do\n e<-getLine\n let t=(length e)\n (r,c,a)=head $ sort [(r,c,r*c-t)|r<-[1..5],c<-[1..20],r*c>=t,r*c-t<=r]\n putStrLn $ (show r)++\" \"++(show c)\n mapM_ putStrLn $ f c a e", "positive_code": [{"source_code": "import Data.List\n\npingo b culo concha [] = \"\"\npingo b culo concha s =\n\tlet q = culo + (if concha > 0 then 1 else 0) in\n\tlet t = take (b-q) s in\n\tt++(replicate q '*')++\"\\n\"++(pingo b culo (concha-1) $ drop (b-q) s)\n\nsolve::String -> String\nsolve ss =\n\tlet s = head $ words ss in\n\tlet n = length s in\n\tlet a = div (n+19) 20 in\n\tlet b = div (n+a-1) a in\n\tlet z = a*b-n in\n\tlet culo = div z a in\n\tlet concha = mod z a in\n\tshow(a)++\" \"++show(b)++\"\\n\"++pingo b culo concha s\n\nmain = do\n interact $ solve"}], "negative_code": [{"source_code": "import Data.List\n\npingo b [] = \"\"\npingo b s =\n\tlet t = take b s in\n\tt++\"\\n\"++(pingo b $ drop b s)\n\nsolve::String -> String\nsolve ss =\n\tlet s = head $ words ss in\n\tlet n = length s in\n\tlet a = div (n+19) 20 in\n\tlet b = div (n+a-1) a in\n\tlet s2 = s ++ (replicate (a*b-n) '*') in\n\tshow(a)++\" \"++show(b)++\"\\n\"++pingo b s2\n\nmain = do\n interact $ solve"}], "src_uid": "ac047ceede246b40892c80dbd696e6b4"} {"source_code": "module Main where\n\nimport Data.List\n\n\ngetPows :: [Integer] -> Integer -> [Integer]\ngetPows lst sum = map (\\x -> sum - x) lst\n\ngetIt :: [Integer] -> [(Integer, Integer)]\ngetIt (x:xs) = getPairLst xs 1 x\n\ngetPairLst :: [Integer] -> Integer -> Integer -> [(Integer, Integer)]\ngetPairLst [] numb curr = [(curr, numb)]\ngetPairLst (x:xs) numb curr = case (x == curr) of\n (True) -> getPairLst xs (numb+1) curr\n (False)-> (curr, numb) : getPairLst xs 1 x\n\ngiveNAnswer :: [(Integer, Integer)] -> Integer -> Integer\ngiveNAnswer (x:xs) prime = case ((snd x `mod` prime) == 0) of \n (False) -> fst x\n (True) -> giveNAnswer (addLst xs ((fst x)+1) (snd x `div` prime )) prime\n\naddLst :: [(Integer, Integer)] -> Integer -> Integer -> [(Integer, Integer)]\naddLst [] fstX sndX = [(fstX, sndX)]\naddLst (x:xs) fstX sndX = case (fstX == fst x) of\n (True) -> (fst x, (snd x)+sndX) : xs\n (False) -> (fstX, sndX) :x: xs\n\n\npowIt :: Integer -> Integer ->Integer\npowIt _ 0 = 1\npowIt based x = case (x `mod` 2) of\n 1 -> mod (based * (powIt based (x-1))) 1000000007\n 0 -> let r = powIt based (x `div` 2)\n in mod (r*r) 1000000007\n\nmain :: IO()\nmain = do\n line1 <- getLine\n line2 <- getLine\n let [n,prime] = map read (words line1)\n let arr = map (read) (words line2)\n let sm = sum arr \n let ans = getIt $(sort (getPows arr sm))\n let x = min (giveNAnswer ans prime) sm\n print $ powIt prime x\u2009", "positive_code": [{"source_code": "import Data.List as List\n\nreadInts :: String -> [Integer]\nreadInts str = map read (words str)\n\nmodnum = 1000000007\nexpmod :: Integer -> Integer -> Integer -> Integer\nexpmod a _ 0 = mod a modnum\nexpmod a x n\n |even n = expmod a (mod (x*x) modnum) (div n 2)\n |otherwise = expmod (mod (a*x) modnum) x (n-1)\n\n\ng :: Integer -> Integer -> Integer -> [Integer] -> Integer\ng _ 0 _ _ = 0\ng x s offset as@(a:_) = \n if offset/=a \n then a-offset + (g x (s-a+offset) a as) \n else\n let k = length $ head $ List.group as in\n if mod (fromIntegral k) x /=0 \n then 0\n else g x s offset ((replicate (div k $ fromInteger x) (offset+1)) ++ (drop k as))\n\nmain :: IO ()\nmain = do\n [n, x] <- fmap readInts getLine\n as' <- fmap readInts getLine\n let s = sum as' \n let as = map (s-) $ reverse $ List.sort as'\n print $ expmod 1 x $ g x s 0 as\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nitof :: Int -> Double\nitof = fromIntegral\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,x] <- readLns\n as <- readInts\n print $ solve n x as\n\nmodulo = 1000000007 \n\nnewtype Modulo = Modulo { getInteger :: Integer } deriving(Eq,Ord)\ninstance Num Modulo where\n Modulo a + Modulo b = Modulo ((a+b) `mod` modulo)\n Modulo a - Modulo b = Modulo ((a-b) `mod` modulo)\n Modulo a * Modulo b = Modulo ((a*b) `mod` modulo)\n abs (Modulo a) = Modulo (abs a)\n signum (Modulo a) = Modulo (signum a)\n fromInteger i = Modulo i\n\ninstance Show Modulo where\n show (Modulo i) = show i\n \nsolve :: Int -> Int -> [Int] -> Modulo\nsolve n x' as' = go bs\n where\n as = map fromIntegral as' :: [Integer]\n s = sum as\n x = fromIntegral x'\n bs = [(s - b,1) | b <- reverse as]\n go l | k1 `mod` x == 0 = go ((b+1,k1 `div` x):l2)\n | otherwise = Modulo x ^ min b s\n where\n (b,_) = head l\n (l1,l2) = span ((==b).fst) l\n k1 = sum $ map snd l1\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List\n\n\ngetPows :: [Integer] -> Integer -> [Integer]\ngetPows lst sum = map (\\x -> sum - x) lst\n\ngetIt :: [Integer] -> [(Integer, Integer)]\ngetIt (x:xs) = getPairLst xs 1 x\n\ngetPairLst :: [Integer] -> Integer -> Integer -> [(Integer, Integer)]\ngetPairLst [] numb curr = [(curr, numb)]\ngetPairLst (x:xs) numb curr = case (x == curr) of\n (True) -> getPairLst xs (numb+1) curr\n (False)-> (curr, numb) : getPairLst xs 1 x\n\ngiveNAnswer :: [(Integer, Integer)] -> Integer -> Integer\ngiveNAnswer (x:xs) prime = case ((snd x `mod` prime) == 0) of \n (False) -> fst x\n (True) -> giveNAnswer (addLst xs ((fst x)+1) (snd x `div` prime )) prime\n\naddLst :: [(Integer, Integer)] -> Integer -> Integer -> [(Integer, Integer)]\naddLst [] fstX sndX = [(fstX, sndX)]\naddLst (x:xs) fstX sndX = case (fstX == fst x) of\n (True) -> (fst x, (snd x)+sndX) : xs\n (False) -> (fst x, sndX) : xs\n\n\npowIt :: Integer -> Integer ->Integer\npowIt _ 0 = 1\npowIt based x = case (x `mod` 2) of\n 1 -> mod (based * (powIt based (x-1))) 1000000007\n 0 -> let r = powIt based (x `div` 2)\n in mod (r*r) 1000000007\n\nmain :: IO()\nmain = do\n line1 <- getLine\n line2 <- getLine\n let [n,prime] = map read (words line1)\n let arr = map (read) (words line2)\n let sm = sum arr \n let ans = getIt $(sort (getPows arr sm))\n let x = min (giveNAnswer ans prime) sm\n print $ powIt prime x\u2009"}, {"source_code": "import Data.List as List\n\nreadInts :: String -> [Integer]\nreadInts str = map read (words str)\n\nmodnum = 1000000007\nexpmod :: Integer -> Integer -> Integer -> Integer\nexpmod a _ 0 = mod a modnum\nexpmod a x n\n |even n = expmod a (mod (x*x) modnum) (div n 2)\n |otherwise = expmod (mod (a*x) modnum) x (n-1)\n\nhas :: Integer -> Integer -> Integer\nhas 0 _ = 0\nhas n x\n |mod n x == 0 = 1+(has (div n x) x)\n |otherwise = 0\n\nmain :: IO ()\nmain = do\n [n, x] <- fmap readInts getLine\n as' <- fmap readInts getLine\n if n==225 && x==5 then\n print $ map (\\lst->(head lst, length lst)) $ List.group as'\n else\n return ()\n let as = reverse $ List.sort as'\n let s = sum as\n let an = head as\n let k = fromIntegral $ length $ head $ List.group as\n\n let r1 = s-an\n let r2 = (min (has k x) an)\n let result = expmod 1 x (r1+r2)\n --print (r1, r2, result)\n print result\n \n"}, {"source_code": "import Data.List as List\n\nreadInts :: String -> [Integer]\nreadInts str = map read (words str)\n\nmodnum = 1000000007\nexpmod :: Integer -> Integer -> Integer -> Integer\nexpmod a _ 0 = mod a modnum\nexpmod a x n\n |even n = expmod a (mod (x*x) modnum) (div n 2)\n |otherwise = expmod (mod (a*x) modnum) x (n-1)\n\nhas :: Integer -> Integer -> Integer\nhas 0 _ = 0\nhas n x\n |mod n x == 0 = 1+(has (div n x) x)\n |otherwise = 0\n\nmain :: IO ()\nmain = do\n [n, x] <- fmap readInts getLine\n as' <- fmap readInts getLine\n if n==225 && x==5 then\n print $ map (\\lst->(head lst, length lst)) $ List.group as'\n else\n return ()\n let as = reverse $ List.sort as'\n let s = sum as\n let an = head as\n let k = fromIntegral $ length $ head $ List.group as\n\n let r1 = s-an\n let r2 = (min (has k x) an)\n let result = expmod 1 x (r1+r2)\n print (r1, r2, result)\n \n"}, {"source_code": "import Data.List as List\n\nreadInts :: String -> [Integer]\nreadInts str = map read (words str)\n\nmodnum = 1000000007\nexpmod :: Integer -> Integer -> Integer -> Integer\nexpmod a _ 0 = mod a modnum\nexpmod a x n\n |even n = expmod a (mod (x*x) modnum) (div n 2)\n |otherwise = expmod (mod (a*x) modnum) x (n-1)\n\n\n\nmain :: IO ()\nmain = do\n [n, x] <- fmap readInts getLine\n as' <- fmap readInts getLine\n let as = reverse $ List.sort as'\n let s = sum as\n let an = head as\n let k = fromIntegral $ length $ head $ List.group as\n print $ mod ((expmod 1 x (s-an)) * (gcd (expmod 1 x an) k)) modnum\n \n"}, {"source_code": "import Data.List as List\n\nreadInts :: String -> [Integer]\nreadInts str = map read (words str)\n\nmodnum = 1000000007\nexpmod :: Integer -> Integer -> Integer -> Integer\nexpmod a _ 0 = mod a modnum\nexpmod a x n\n |even n = expmod a (mod (x*x) modnum) (div n 2)\n |otherwise = expmod (mod (a*x) modnum) x (n-1)\n\nhas :: Integer -> Integer -> Integer\nhas 0 _ = 0\nhas n x\n |mod n x == 0 = 1+(has (div n x) x)\n |otherwise = 0\n\nmain :: IO ()\nmain = do\n [n, x] <- fmap readInts getLine\n as' <- fmap readInts getLine\n let as = reverse $ List.sort as'\n let s = sum as\n let an = head as\n let k = fromIntegral $ length $ head $ List.group as\n\n let r1 = s-an\n let r2 = (min (has k x) an)\n print $ expmod 1 x (r1+r2)\n \n"}], "src_uid": "4867d014809bfc1d90672b32ecf43b43"} {"source_code": "import Data.List (transpose)\n\nmain :: IO ()\nmain = getContents >>= print . solve . tail . lines\n\nsolve :: [String] -> Int\nsolve xss = length [ () | xs <- xss, any (uncurry (==)) $ zip xs (map maximum $ transpose xss) ]\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . lines =<< getContents\n\nsolve :: [String] -> Int\nsolve s = let s' = transpose s\n ms = map maximum s'\n in length [x | x <- s, any (uncurry (==)) (zip x ms)]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Char\n\nposs :: [Int] -> [Int]\nposs [] = []\nposs lst = elemIndices mx lst\n where mx = maximum lst\n\ntoints :: [String] -> [[Int]]\ntoints = map . map $ digitToInt\n\ncalc :: [String] -> Int\ncalc = length . nub . foldl1 (++) . map poss . transpose . toints\n\nmain = do\n nm <- fmap words getLine\n let nmi = map (\\x -> read x :: Int) nm\n n = nmi !! 0\n --m = nmi !! 1\n slist <- replicateM n getLine\n print $ calc slist"}, {"source_code": "import List\nimport Data.Char\ntapleMax ::(Int,Int) -> Int\ntapleMax x | fst x >= snd x = fst x\n | otherwise = snd x\ngetMax ::[Int] -> [Int] -> [Int]\ngetMax a b = [tapleMax y|y <- getTaple a b]\ngetTaple ::[Int] -> [Int] ->[(Int,Int)]\ngetTaple [] [] = []\ngetTaple (x:xs) (y:ys) =(x,y):getTaple xs ys\ngetBest ::[[Int]] ->[Int]\ngetBest [x] = x\ngetBest (x:xs) = getMax x (getBest xs)\nhasBest ::[Int] -> [Int] -> Bool\nhasBest [] [] = False\nhasBest (x:xs) (y:ys) | x<= y = True\n | otherwise = hasBest xs ys\ngetAns ::[[Int]] -> Int\ngetAns a = length$filter (hasBest (getBest a)) a\nmain=interact$show.getAns.(map (map digitToInt)).(drop 2).words"}, {"source_code": "\nimport Array\nimport Char\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\ngetLines :: Int -> IO [String]\ngetLines n = sequence (replicate n getLine)\n\ntoArray2 :: (Char -> e) -> [String] -> Array (Int, Int) e\ntoArray2 parser lines = array ((0, 0), (n-1, m-1))\n [((i, j), parser (lines !! i !! j)) | i <- [0..n-1], j <- [0..m-1]]\n where\n n = length lines\n m = length (head lines)\n\ngetArray2 :: (Char -> e) -> (Int, Int) -> IO (Array (Int, Int) e)\ngetArray2 parser (n, _) = getLines n >>= return . toArray2 parser\n\nsolve :: (Int, Int) -> Array (Int, Int) Int -> Int\nsolve (n, m) a = length (filter (\\i -> any (\\j -> a ! (i, j) == maximum (map (\\k -> a ! (k,j)) [0..n-1])) [0..m-1]) [0..n-1])\n\nmain :: IO ()\nmain = do\n [n, m] <- Main.reads\n a <- getArray2 digitToInt (n, m)\n print $ solve (n, m) a\n"}, {"source_code": "--import Data.Vector\nimport Numeric\nimport Data.List\nmain = do\n nm <- getLine\n cs <- getContents\n let (n:m:_) = map (fst.head.readDec) $ words nm\n print.answer (n,m).take n.lines $ cs\n\nanswer :: (Int,Int) -> [[Char]] -> Int\nanswer (n,m) xs =\n let xy = split n [(x,y) | x <- [0..m-1],y <- [0..n-1]]\n in length.group.sort.concat $ map (f xs) xy\n where\n f :: [[Char]] -> [(Int,Int)] -> [Int]\n f xs xys = let grades = map (value xs) xys\n maX = foldl max '1' grades\n in third.foldl g (maX ,0, []) $ grades\n g (a,k,success) b = if a == b then (a,k+1,k:success)\n else (a,k+1, success)\n\ncount (a,k) b = if a < b && a /= 0 then (b,k+1) else (a,k)\n\nthird (_,_,x) = x\n\nsplit n [] = []\nsplit n xs = a:split n b\n where\n (a,b) = splitAt n xs\n\nvalue xs (x,y) = (xs !! y ) !! x\n"}, {"source_code": "import List\n\nsolve :: [[Char]] -> Int\nsolve grades = let gradesT = transpose grades\n ms = map maximum gradesT\n isSuccessful ts = not $ null $ filter (\\(x, y) -> x == y) $ zip ts ms\n in length $ filter isSuccessful grades\n\nmain = interact $ show . solve . drop 2 . words"}, {"source_code": "import Data.List\n\ntest1 = [\"223\",\n \"232\",\n \"112\"]\n\ntest2 = [\"91728\",\n \"11828\",\n \"11111\"]\n\nsolve :: [[Char]] -> Int\nsolve grades = let gradesT = transpose grades\n ms = map maximum gradesT\n isSuccessful ts = not $ null $ filter (\\(x, y) -> x == y) $ zip ts ms\n in length $ filter isSuccessful grades\n\nmain = interact $ show . solve . drop 2 . words"}, {"source_code": "import Data.List\nmain=interact$show.f.tail.lines\nf y=length[x|x<-y,any(uncurry(==))$zip x$map maximum$transpose y]\n"}, {"source_code": "import Data.List\nmain=interact$show.f.tail.lines\nf y=length[()|x<-y,any(uncurry(==))$zip x(map maximum$transpose y)]\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n [n,m] <- liftM (map read . words) getLine\n gs <- liftM transpose (replicateM n getLine)\n print $ length $ filter id $ foldr1 (zipWith (||)) $ map best gs\nbest gs = map (== maximum gs) gs"}, {"source_code": "import Data.Char\nimport Data.List\nmain :: IO ()\nmain = interact work\n\nwork :: String -> String\nwork = (++\"\\n\") . show . length . filter id . solve . map (map digitToInt) . tail . lines\n\nsolve :: [[Int]] -> [Bool]\nsolve x = map (calc $ transpose x) x\n\ncalc :: [[Int]] -> [Int] -> Bool\ncalc grades student = or $ zipWith (>=) student $ map maximum grades\n\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n nms <- map (map digitToInt) <$> lines <$> getContents\n print $ solve nms\n\nsolve :: [[Int]] -> Int\nsolve nms = length $ filter id $ map (p nms) nms\np nms ms = or $ zipWith (>=) ms $ map maximum $ transpose nms"}, {"source_code": "main :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve xs = let \n lxs = lines xs\n top = words $ head lxs \n n = read $ head top\n m = read $ head $ drop 1 top\n rest = tail lxs\n dat = map (\\x->map (read.return) x) rest\n in show $ ans (n,m,dat)\n\nans :: (Int,Int,[[Int]]) -> Int\nans (n,m,dat) = foldr (\\x y->if x then y+1 else y) 0 $ map isSame [0..n-1] where\n isSame t = any (\\x->dat!!t!!x == maxP x) [0..m-1]\n maxP t = foldr max 0 [ dat!!p!!t | p<-[0..n-1]]"}, {"source_code": "import Data.List\nbests xs = map fst.filter ((== mx).snd).zip [0..]$xs\t\n\twhere mx = maximum xs\nsuccesful = length.nub.concat.map bests\nmain=interact$show.succesful.transpose.tail.lines\n"}, {"source_code": "import Data.List\nmain=interact$show.f.tail.lines\nf y=length[x|x<-y,any(uncurry(==))$zip x$map maximum$transpose y]"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n\nprocess t = map (\\z-> if z==ma then '1' else '0') t\n\twhere ma= maximum t \n\nmyor a b = zipWith myor1 a b\n\nmyor1 '0' '0' = '0'\nmyor1 _ _ = '1'\n\n\n \n\n\nmain= do\n\t[n,m]<- map read.words <$> getLine ::IO [Int]\n\ts<- transpose. lines <$> getContents ::IO [String]\n\tlet s1= foldl1 (myor) $ map process s\t\n\tprint $ length $ filter (=='1') s1\t"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\n\nreadL :: Int -> IO [String]\nreadL n = sub n []\n where sub 0 l = return l\n sub n l = do ll <- getLine\n sub (n-1) (l ++ [ll])\n\nflatten :: [[a]] -> [a]\nflatten [[]] = []\nflatten ([]:ys) = flatten ys\nflatten ((x:xs):ys) = x:(flatten (xs:ys))\n\nrotate :: [String] -> [String]\nrotate l = sub l []\n where sub l acc\n | flatten l == [] = acc\n | otherwise = sub (map tail l) ((foldl (\\ac x -> (head x):ac) \"\" l):acc)\n \ngetInt :: IO Int\ngetInt = readLn\n\ncntList :: String -> [Int]\ncntList str = sub '0' 0 str []\n where sub c idx [] l = l\n sub c idx (x:xs) l = if c < x then sub x (idx+1) xs [idx]\n else if c == x then sub x (idx+1) xs (idx:l)\n else sub c (idx+1) xs l\n\nmain :: IO ()\nmain = do\n f <- getLine\n let ps = map (\\x -> read x) (words f)\n cs <- readL $ head ps\n --putStrLn . show $ cs\n --putStrLn . show $ map cntList (rotate cs)\n putStrLn . show . length . nub . concat $ map cntList (rotate cs)\n-- mapM (\\x -> putStrLn x) $ rotate cs\n return ()\n "}, {"source_code": "import Data.List\nmain=getLine >>= (\\x -> (\\[n,m] -> print.(slv n m).(map (\\x -> map f x)).(take n).lines =<< getContents)(map read $ (words x)) )\nf :: Char -> Int; f '0'=0; f '1'=1;f '2'=2; f '3'=3;f '4'=4; f '5'=5;f '6'=6; f '7'=7;f '8'=8; f '9'=9;\nslv n m as = length $ filter (==True) $ map (\\x -> g n m x (transpose as)) as\ng n' m' s as = or $ [((s)!!m `best` (as!!m)) | m <- [0..(m'-1)], n <- [0..(n'-1)]]\nbest x xs = x >= maximum xs"}, {"source_code": "import Data.Char\nimport qualified Data.Set as Set\nimport Control.Monad\n\ntranspose ([]:_) = []\ntranspose l = \n (map (\\(x:xs) -> x) l) : (transpose (map (\\(x:xs) -> xs) l))\n\nfind_best grades =\n [i | (i, x) <- zip [1..] grades, x == best]\n where best = maximum grades\n\nsolve grades n = \n let students = map find_best grades\n all_students = Set.unions $ map Set.fromList students\n in\n Set.size all_students\n\n\nmain = do\n (n:_) <- (getLine >>= return . map (read::String->Int) . words)\n xs <- forM [1..n] (\\_ -> getLine >>= (return . map digitToInt))\n -- print $ transpose xs\n print $ solve (transpose xs) n"}], "negative_code": [{"source_code": "--import Data.Vector\nimport Numeric\nimport Data.List\nmain = do\n nm <- getLine\n cs <- getContents\n let (n:m:_) = map (fst.head.readDec) $ words nm\n print.answer (n,m).take n.lines $ cs\n\nanswer :: (Int,Int) -> [[Char]] -> Int\nanswer (n,m) xs =\n let xy = split n [(x,y) | x <- [0..m-1],y <- [0..n-1]]\n in snd.foldl count (0,1).sort.concat $ map (f xs) xy\n where\n f :: [[Char]] -> [(Int,Int)] -> [Int]\n f xs xys = let grades = map (value xs) xys\n maX = foldl max '1' grades\n in third.foldl g (maX ,0, []) $ grades\n g (a,k,success) b = if a == b then (a,k+1,k:success)\n else (a,k+1, success)\n\ncount (a,k) b = if a < b then (b,k+1) else (a,k)\n\nthird (_,_,x) = x\n\nsplit n [] = []\nsplit n xs = a:split n b\n where\n (a,b) = splitAt n xs\n\nvalue xs (x,y) = (xs !! y ) !! x\n"}, {"source_code": "--import Data.Vector\nimport Numeric\nimport Data.List\nmain = do\n nm <- getLine\n cs <- getContents\n let (n:m:_) = map (fst.head.readDec) $ words nm\n print.answer (n,m).take n.lines $ cs\n\nanswer :: (Int,Int) -> [[Char]] -> Int\nanswer (n,m) xs =\n let xy = split n [(x,y) | x <- [0..m-1],y <- [0..n-1]]\n in snd.foldl count (0,1).sort.concat $ map (f xs) xy\n where\n f :: [[Char]] -> [(Int,Int)] -> [Int]\n f xs xys = let grades = map (value xs) xys\n maX = foldl max '1' grades\n in third.foldl g (maX ,0, []) $ grades\n g (a,k,success) b = if a == b then (a,k+1,k:success)\n else (a,k+1, success)\n\ncount (a,k) b = if a < b && a /= 0 then (b,k+1) else (a,k)\n\nthird (_,_,x) = x\n\nsplit n [] = []\nsplit n xs = a:split n b\n where\n (a,b) = splitAt n xs\n\nvalue xs (x,y) = (xs !! y ) !! x\n"}], "src_uid": "41bdb08253cf5706573f5d469ab0a7b3"} {"source_code": "main = do\n n <- readLn\n print n\n putStrLn $ unwords $ replicate n \"1\"\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\t\t\n\n\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\tprint n\n\t\tputStrLn $ concat $ replicate n \"1 \"\n"}, {"source_code": "process :: Int -> [Int]\nprocess n = take n $ repeat 1\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n print n\n putStrLn.unwords.map show $ process n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE RankNTypes #-}\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Maybe\n-- import Data.List\n-- import qualified Data.Vector.Unboxed as VU\n-- import qualified Data.Vector.Unboxed.Mutable as VUM\n-- import Control.Monad\n-- import Control.Monad.ST\n-- import Debug.Trace\n-- trace _ = id\n\nsolve :: Int -> (Int, [Int])\nsolve n = (n, take n (repeat 1))\n\nreadBInt :: B.ByteString -> Int\nreadBInt = fst . fromJust . B.readInt\n\ntmain :: B.ByteString -> (Int, [Int])\ntmain cont =\n let remLines0 = map B.words (B.lines cont)\n [bs_n]:remLines1 = remLines0\n n = readBInt bs_n\n in solve n\n\noutAnswer :: (Int, [Int]) -> IO ()\noutAnswer (n, xs) = do\n putStrLn $ show $ n\n putStrLn $ unwords $ map show $ xs\n\nmain :: IO ()\nmain = outAnswer . tmain =<< B.getContents\n\n\n"}, {"source_code": "-- Codeforces Round #534 Div.2 (A), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n print $ n\n putStrLn $ intersperse ' ' $ replicate n '1'\n"}], "negative_code": [], "src_uid": "7c483498f497f4291e3d33375c0ebd53"} {"source_code": "solve :: [Int] -> [(Int, Int)]\nsolve [] = []\nsolve (x:xs) = (c1, c2) : solve xs\n where\n c2 = div (x + 1) 3\n c1 = x - c2 * 2\n\nparseIn = tail . map (read :: String -> Int) . words \n\nparseOut [] = \"\"\nparseOut ((x, y):l) = show x ++ \" \" ++ show y ++\"\\n\"++parseOut l\n\nmain :: IO ()\nmain = interact $ parseOut . solve . parseIn\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\nsolve n = if d1 < d2 \r\n then (c1, c2)\r\n else (c1 - 2, c2 + 1)\r\n where\r\n (d1, d2) = (n `rem` 3, 3 - n `rem` 3)\r\n (c1, c2) = (n `div` 3 + n `rem` 3, n `div` 3)\r\n\r\nmain :: IO ()\r\nmain = do \r\n t <- readLn \r\n replicateM_ t $ do\r\n (c1, c2) <- solve <$> readLn\r\n putStrLn $ show c1 ++ \" \" ++ show c2"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n words\r\n >>> drop 1\r\n >>> map (read >>> solve >>> (\\(x, y) -> show x ++ \" \" ++ show y))\r\n >>> unlines\r\n\r\nsolve :: Int -> (Int, Int)\r\nsolve n = let (q, r) = n `divMod` 3 in (q + bool 0 1 (r == 1), q + bool 0 1 (r == 2))\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n let cnt = div n 3\n (one, two) = case rem n 3 of 0 -> (cnt, cnt)\n 1 -> (cnt+1, cnt)\n 2 -> (cnt, cnt+1)\n in putStrLn $ show one ++ \" \" ++ show two\n \n \n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadrows 0 = return []\nreadrows n = do\n row <- readInts\n l <- readrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve :: Int -> (Int, Int)\r\nsolve n\r\n | a == 2 = (b, b + 1)\r\n | a == 1 = (b + 1, b)\r\n | otherwise = (b, b)\r\n where a = mod n 3\r\n b = div n 3\r\n\r\nprintSolve = do\r\n n <- readLn :: IO Int\r\n let p = solve n\r\n putStrLn (show (fst p) ++ \" \" ++ show (snd p))\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printSolve\r\n\r\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve n \r\n | mod n 3 == 2 = [r,r+1]\r\n | mod n 3 == 1 = [r+1,r]\r\n | otherwise = [r,r]\r\n where r = div n 3\r\n\r\nprintResult = do\r\n n <- readLn :: IO Integer\r\n putStrLn . unwords . map show $ solve n\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.List\r\nimport qualified Data.Set as S\r\n\r\ngetStrList :: IO [String]\r\ngetStrList = words <$> getLine\r\n\r\ngetIntList :: IO [Int]\r\ngetIntList = map read <$> getStrList\r\n\r\nprintList :: (Show a) => [a] -> IO ()\r\nprintList = putStrLn . list2Str\r\n\r\nlist2Str :: (Show a) => [a] -> String\r\nlist2Str = concat . intersperse \" \" . fmap show\r\n\r\nyesOrNo :: Bool -> String\r\nyesOrNo True = \"YES\"\r\nyesOrNo False = \"NO\"\r\n\r\ntCase :: IO () -> IO ()\r\ntCase x = do\r\n t <- readLn\r\n replicateM_ t $ x\r\n\r\nmain :: IO ()\r\nmain = tCase process\r\n\r\n--------------------------------------------------------------------------------\r\n\r\nprocess :: IO ()\r\nprocess = do\r\n n <- readLn :: IO Int\r\n let d = n `div` 3\r\n r = n `mod` 3\r\n printList $ if r == 0 then [d, d] else if r == 1 then [d+1, d] else [d, d+1]\r\n "}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\n\nsolution :: Int -> (Int, Int)\nsolution n = minimumBy (comparing $ \\(n1, n2) -> abs (n1 - n2)) ns\n where\n d = n `div` 3\n ns = (\\n2 -> (n - n2 * 2, n2)) <$> [d + i | i <- [-2 .. 2]]\n\nmain :: IO ()\nmain = do\n testCases <- read <$> getLine\n forM_ [1 .. testCases] $ \\_ -> do\n n <- read <$> getLine\n uncurry (printf \"%d %d\\n\") $ solution n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\n-- c1+2c2=n\n-- c1=c2+1\n-- c2+2c2+1 = n\n-- c2*3+1=n\n\n-- c2=c1+1\n-- c1+2c1+2=n\n\n-- c1=c1\n-- c1+2c1=n\n\ncalc :: Int -> [Int]\ncalc n | n `mod` 3 == 0 =\n let c1 = n `div` 3\n c2 = c1 in [c1,c2]\ncalc n | n `mod` 3 == 1 =\n let c2 = (n-1) `div` 3\n c1 = c2+1 in [c1,c2]\ncalc n | n `mod` 3 == 2 =\n let c1 = (n-2) `div` 3\n c2 = c1+1 in [c1,c2]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n putStrLn $ intercalate \" \" $ map show $ calc n\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t readLn :: IO [Integer]\n\n (putStr . unlines . map (showL . solve)) tcs\n\nsolve n | (m == 0) = [x, x]\n | (m == 1) = [x+1, x]\n | (m == 2) = [x, x+1]\n | otherwise = undefined\n where\n x = n `div` 3\n m = n `mod` 3\n\nshowL = intercalate \" \" . map show\n"}, {"source_code": "module Main where\nmain = interact solve\n\nsolve :: String -> String \nsolve inp = \n let\n t = read . head . lines $ inp :: Int \n arr = (read <$>) . take t . tail . lines $ inp :: [Int] \n logic x = \n case x `mod` 3 of \n 0 -> (x `div` 3, x `div` 3)\n 2 -> (x `div` 3, x `div` 3 + 1)\n _ -> (x `div` 3 + 1, x `div` 3)\n in\n unlines . map ((\\(a, b) -> show a ++ \" \" ++ show b) . logic) $ arr\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\n\nsolution :: Int -> (Int, Int)\nsolution n = minimumBy (comparing $ \\(n1, n2) -> abs (n1 - n2)) ns\n where\n d = n `div` 3\n ns = (\\n2 -> (n - n2 * 2, n2)) <$> [d + i | i <- [-2 .. 2]]\n\nmain :: IO ()\nmain = do\n testCases <- read <$> getLine\n forM_ [1 .. testCases] $ \\_ -> do\n n <- read <$> getLine\n uncurry (printf \"%d %d\") $ solution n\n"}, {"source_code": "import Control.Monad\nimport Text.Printf\n\nsolution :: Int -> (Int, Int)\nsolution n = (n1, n2)\n where\n n1 = n `div` 3\n n2 = n - n1 * 2\n\nmain :: IO ()\nmain = do\n testCases <- read <$> getLine\n forM_ [1 .. testCases] $ \\_ -> do\n n <- read <$> getLine\n uncurry (printf \"%d %d\") $ solution n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncalc :: Int -> [Int]\ncalc n | n == 1 = [1,0]\ncalc n | n == 2 = [0,1]\ncalc n | n `mod` 2 == 0 =\n let [a,b] = calc (n `div` 2) in\n [2*a,2*b]\ncalc n | n `mod` 2 == 1 =\n let [a,b] = calc (n-1) in\n [a+1,b]\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n putStrLn $ intercalate \" \" $ map show $ calc n\n"}], "src_uid": "71335a9489f0985f4e16435b14d6a34a"} {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\nmain :: IO()\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap (map (unBox . C.readInt) . C.words) C.getLine :: IO [Int]\n if n>m\n then putStrLn \"YES\"\n else do\n let solved = solve m a S.empty\n if S.member 0 solved then putStrLn \"YES\" else putStrLn \"NO\"\n\nsolve :: Int -> [Int] -> S.Set Int -> S.Set Int\nsolve m [] ans = ans\nsolve m (a:as) ans =\n let mV = a `rem` m\n newS = S.insert mV $ S.union (ans) (S.map (\\x -> rem (x+mV) m) ans)\n in solve m as newS\n\nunBox (Just (a,b)) = a\nunBox Nothing = 0", "positive_code": [{"source_code": "import qualified Data.Set as S\nmain=interact $ solve. map read. words\nsolve (_:m:x)= f S.empty x\n where f _ [] = \"NO\"\n f s (x:xs) = let members=S.toList s\n s'=S.fromList members\n s'' = S.insert (mod x m) $ foldl (\\s k->S.insert (mod (k+x) m) s) s' members\n in\n if S.member 0 s'' then \"YES\" else f s'' xs\n"}, {"source_code": "import qualified Data.List as L\nimport qualified Data.Set as S\n\nmain :: IO()\nmain = output . solve . L.map read . words =<< getContents\n\nsolve :: [Int] -> Bool\nsolve (n:m:a) = solve' a S.empty\n where\n solve' :: [Int] -> (S.Set Int) -> Bool\n solve' _ s | S.member 0 s = True\n solve' [] _ = False\n solve' (a:ax) s = let si = S.singleton (mod a m)\n sn = S.map (\\x -> mod (x + a) m) s\n ssi = S.union s si\n sin = S.union ssi sn\n in solve' ax sin\n\noutput :: Bool -> IO()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as SS\nreadInt bs = case SS.readInt bs of Just (i, _) -> i\nreadInts = map readInt . SS.words\nparse = map readInts . SS.lines\nsolve [[n,m], a] = helper a []\n where helper [] _ = \"NO\"\n helper (a0:as) l\n | 0 `elem` l' = \"YES\"\n | otherwise = helper as l'\n where l' = unique . sort . iter $ l\n iter l = a0 `mod` m:l ++ map (\\x -> (x + a0) `mod` m) l\n unique (a1:a2:as)\n | a1 == a2 = unique (a2:as)\n | otherwise = a1 : unique (a2:as)\n unique x = x\nmain = putStrLn . solve . parse =<< SS.getContents\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.Set as S\nmain :: IO()\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let solved = solve m a S.empty\n if S.member 0 solved then putStrLn \"YES\" else putStrLn \"NO\"\n\nsolve m [] ans = ans\nsolve m (a:as) ans =\n let mV = a `rem` m\n newS = S.union ans (S.map (\\x -> rem (x+mV) m) ans)\n in solve m as newS"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as SS\nreadInt bs = case SS.readInt bs of Just (i, _) -> i\nreadInts = map readInt . SS.words\nparse = map readInts . SS.lines\nsolve [[n,m], a] = helper a []\n where helper [] _ = \"NO\"\n helper (a0:as) l\n | 0 `elem` l' = \"YES\"\n | otherwise = helper as l'\n where l' = unique . sort . iter $ l\n iter l = (a0:l) ++ (map (\\x -> (x + a0) `mod` m) l)\n unique (a1:a2:as)\n | a1 == a2 = unique (a2:as)\n | otherwise = a1 : (unique (a2:as))\n unique x = x\nmain = putStrLn . solve . parse =<< SS.getContents\n"}], "src_uid": "25232f4244004fa4c130892957e5de84"} {"source_code": "inLine :: IO [Integer]\ninLine = (map read . words) `fmap` getLine\n\nmain :: IO ()\nmain = do\n n <- getLine\n xs <- inLine\n ys <- inLine\n zs <- inLine\n let a = sum xs\n b = sum ys\n c = sum zs\n print $ a - b\n print $ b - c\n\n", "positive_code": [{"source_code": "import Data.List\n\nparseList :: String -> [Integer]\nparseList str = map read (words str)\n\ngetAnswer :: [Integer] -> [Integer] -> [Integer] -> (Integer, Integer)\ngetAnswer first second third = (findRemoved f s, findRemoved s t)\n where f = sort first\n s = sort second\n t = sort third\n\nfindRemoved :: [Integer] -> [Integer] -> Integer\nfindRemoved [x] [] = x\nfindRemoved [] [y] = y\nfindRemoved [] [] = 0\nfindRemoved (x:xs) (y:ys) = if x == y\n then findRemoved xs ys\n else x\n\nmain :: IO ()\nmain = do\n n <- getLine\n first <- getLine\n second <- getLine\n third <- getLine\n let (a, b) = getAnswer (parseList first) (parseList second) (parseList third)\n putStrLn $ show a\n putStrLn $ show b"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\ngetInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\t[ a, b, c ] <- map sort <$> replicateM 3 getInts\n\tprint $ f a b\n\tprint $ f b c\n\nf (a:as) [] = a\nf (a:as) (b:bs)\n\t| a == b = f as bs\n\t| otherwise = a\n"}, {"source_code": "module Main (main)\n where\n\nimport Control.Monad (replicateM)\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nmain :: IO ()\nmain = putStr . toStr . solve . map readInts =<< (getLine >> replicateM 3 getLine)\n where solve [as,bs,cs] = let (x,y) = (sum as, sum bs)\n in [x - y, y - sum cs]\n toStr = unlines . map show"}, {"source_code": "-- https://wiki.haskell.org/Performance\n-- http://hackage.haskell.org/package/vector\n-- https://wiki.haskell.org/Unboxed_type\n-- http://hackage.haskell.org/package/vector-0.12.0.1/docs/Data-Vector-Generic.html\n\n\n\n\n\n\nconv lst uu\n | (null lst) = uu\n | otherwise = conv (tail lst) (((read (head lst))::Int) : uu)\n\nmain = do\n ff <- getLine\n gg <- getLine\n hh <- getLine\n dd <- getLine\n\n let aa = conv (words gg) []\n bb = conv (words hh) []\n cc = conv (words dd) []\n\n putStrLn (show (sum aa - sum bb))\n putStrLn (show (sum bb - sum cc))\n\n\n\n\n\n\n\n\n"}, {"source_code": "import Data.List\n\nans :: [Int] -> [Int] -> Int\nans a b = f (sort a) (sort b) where\n\tf [x] _ = x\n\tf (x:xs) (p:ps)\n\t\t| x /= p = x\n\t\t| otherwise = f xs ps\n\nmain :: IO()\nmain = do\n\tn <- getLine\n\ts1 <- fmap (map read . words) getLine \n\ts2 <- fmap (map read . words) getLine \n\ts3 <- fmap (map read . words) getLine \n\tputStrLn $ (show $ ans s1 s2)\n\tputStrLn $ (show $ ans s2 s3)\n\t"}, {"source_code": "-- http://codeforces.com/problemset/problem/519/B\n\nimport Data.List\nimport Data.Char\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\tlns <- getLines 4\n\t\n\tlet\n\t\tn = read $ lns !! 0 :: Int\n\t\te1 = map read $ words $ lns !! 1 :: [Int]\n\t\te2 = map read $ words $ lns !! 2 :: [Int]\n\t\te3 = map read $ words $ lns !! 3 :: [Int]\n\n\tputStrLn $ show $ findRemainder e1 e2\n\tputStrLn $ show $ findRemainder e2 e3\n\n-- If both list of errors are constructed purely from\n-- integers the fixed errors is the remainder of the\n-- difference betweeen the non-fixed list and fixed list\nfindRemainder :: [Int] -> [Int] -> Int\nfindRemainder (x:[]) [] = x\nfindRemainder (x:xs) (y:ys) = x - y + (findRemainder xs ys)"}, {"source_code": "main = do\n getLine\n a <- fmap (sum . map read . words) getLine\n b <- fmap (sum . map read . words) getLine\n c <- fmap (sum . map read . words) getLine\n\n print $ a - b\n print $ b - c\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> (mapM_ putStrLn).solve =<< (forM [1..3] $ \\i -> getLine>>= \\j -> return $ words j)\nsolve::[[String]]->[String]\nsolve [x,y,z] = let sx = sort x; sy= sort y; sz= sort z in [slv1 sx sy, slv1 sy sz]\nslv1 (x:xs) [] = x\nslv1 (x:xs) (y:ys) = if x/=y then x else slv1 xs ys"}, {"source_code": "-- Codeforces 519B\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Integer\n fmap (map read . words) getLine >>= solve 2\n\nsolve :: Integer -> [Integer] -> IO ()\nsolve 0 _ = return ()\nsolve n xs = do\n nxt <- fmap (map read . words) getLine\n print ((sum xs) - (sum nxt))\n solve (n-1) nxt\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\n\nf a b = if a==b then Nothing else Just (a-b)\n\n\nmain=do\n n<- read <$> getLine::IO Integer\n [q1,q2,q3]<- map (map (fst.fromJust.C.readInteger) ) <$> map (C.words) <$> C.lines <$> C.getContents::IO [[Integer]]\n let [m1,m2,m3] = map (\\z-> M.fromListWith (+) $ zip z (repeat 1)) [q1,q2,q3]\n print $ fst $ head $ M.toList $ M.differenceWith f m1 m2\n print $ fst $ head $ M.toList $ M.differenceWith f m2 m3\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= mapM_ print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Integer]] -> [Integer]\nsolve [ as, bs, cs ] = [ sum as - sum bs, sum bs - sum cs ]\nsolve _ = undefined\n"}, {"source_code": "main=getContents>>=mapM_ print.f.map(map read.words).tail.lines\nf[a,b,c]=[sum a-sum b,sum b-sum c]\n"}, {"source_code": "main = interact $ unlines . map show . solve . parse\nparse = map (sum . map read . words) . tail . lines\nsolve ns = zipWith (-) ns (tail ns) where\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\nmain = do\n B.getLine\n a <- readInts\n b <- readInts\n c <- readInts\n let [x,y,z] = map sum [a,b,c]\n putStrLn . unlines . map show $ [x-y,y-z]\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\nmain = do\n B.getLine\n a <- readInts\n b <- readInts\n c <- readInts\n let [x,y,z] = map sum [a,b,c]\n print $ x - y\n print $ y - z\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n ys <- map readInt.B.words <$> B.getLine\n zs <- map readInt.B.words <$> B.getLine\n putStr.unlines.map show $ solve (sort xs) (sort ys) (sort zs)\n\nsolve :: [Int] -> [Int] -> [Int] -> [Int]\nsolve xs ys zs = [go xs ys, go ys zs]\n where\n go (x:xs) (y:ys)\n | x == y = go xs ys\n | otherwise = x\n go [x] [] = x\n "}, {"source_code": "import Control.Applicative\n\nmain = do\n\t_ <- getLine\n\tset1 <- sum . map read . words <$> getLine\n\tset2 <- sum . map read . words <$> getLine\n\tset3 <- sum . map read . words <$> getLine\n\tprint $ set1 - set2\n\tprint $ set2 - set3\n"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.Map.Strict as M\n\nimport Data.List (foldl')\nimport Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n (b0:b1:b2:_) <- replicateM 3 (S.fromAscList . M.toAscList . buildDict . words <$> getLine)\n putStrLn $ fst . head $ S.toList (S.difference b0 b1)\n putStrLn $ fst . head $ S.toList (S.difference b1 b2)\n\n where\n buildDict = foldl' (\\m s -> M.insertWith (\\_ o -> o + 1) s 1 m) M.empty"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.Map.Strict as M\n\nimport Data.List (foldl')\nimport Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n (b0:b1:b2:_) <- replicateM 3 (S.fromAscList . M.toAscList . buildDict . words <$> getLine)\n putStrLn $ fst . head $ S.toList (S.difference b0 b1)\n putStrLn $ fst . head $ S.toList (S.difference b1 b2)\n\n where\n buildDict = foldr (\\s m -> M.insertWith (\\_ o -> o + 1) s 1 m) M.empty"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = case filter (uncurry (/=)) $ zip as' bs' of\n (a, _):_ -> a\n otherwise -> last as'\n where\n as' = sort as\n bs' = sort bs\n\nmain :: IO ()\nmain = do\n _ <- getLine\n as <- map read <$> words <$> getLine\n bs <- map read <$> words <$> getLine\n cs <- map read <$> words <$> getLine\n print $ solve as bs\n print $ solve bs cs"}, {"source_code": "module Main (main) where\n\nimport Control.Monad\nimport Data.Functor\n\nisDigit x = x>='0' && x<='9'\nsplit f l@(a:as) lft\n\t| f a = split f as (a:lft)\n\t| otherwise = (reverse lft, as)\nsplit _ [] lft = (reverse lft, [])\nreadInts::String -> [Integer]\nreadInts [] = []\nreadInts l@(x:xs)\n\t| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)\n\t| otherwise = readInts xs\n\nmain = do\n\t_ <- getLine\n\ta <- (sum.readInts) <$> getLine\n\tb <- (sum.readInts) <$> getLine\n\tc <- (sum.readInts) <$> getLine\n\tprint $ a-b\n\tprint $ b-c\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \n\nmain=do\n\tgetLine\n\ta<- sort.map (fst.fromJust.C.readInt).C.words <$> C.getLine::IO [Int]\n\tb<- sort.map (fst.fromJust.C.readInt).C.words <$> C.getLine::IO [Int] \n\tc<- sort.map (fst.fromJust.C.readInt).C.words <$> C.getLine::IO [Int]\t\n\tprint $ fst $ head $ filter (\\z-> fst z /= snd z) $ zip a (b++[0])\n print $ fst $ head $ filter (\\z-> fst z /= snd z) $ zip b (c++[0])"}, {"source_code": "import Control.Monad\n\ngetSumOfLine = do\n line <- getLine\n return(sum([read n :: Int | n <- words line]))\n\nmain = do\n getLine\n [a,b,c] <- replicateM 3 getSumOfLine\n print(a-b)\n print(b-c)"}, {"source_code": "main = do\n getLine\n m <- sequence $ replicate 3 getLine\n let mf = map (map read . words) m\n let [mf1, mf2, mf3] = map sum mf\n print $ mf1 - mf2\n print $ mf2 - mf3"}, {"source_code": "import Data.List\nsolve :: [Int] -> [Int] -> Int\nsolve [a] [] = a\nsolve (a:as) (b:bs)\n | a /= b = a\n | otherwise = solve as bs\nmain = do\n getLine\n [as, bs, cs] <- getContents >>= return. map (Data.List.sort. map read. words). lines\n print $ solve as bs\n print $ solve bs cs\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of\n Just (n,_) -> n\n _-> error $ \"readInt error : bs = \" ++ show bs\n\nsolve (x:_) [] = x\nsolve [] (y:_) = y\nsolve [] [] = 0\nsolve (x:xs) (y:ys)\n | x /= y = x\n | otherwise = solve xs ys\n\nmain :: IO ()\nmain = do\n _ <- getLine\n lst0 <- map readInt . B.words <$> B.getLine\n lst1 <- map readInt . B.words <$> B.getLine\n lst2 <- map readInt . B.words <$> B.getLine\n let [a, b, c] = map sum [lst0, lst1, lst2]\n print $ a - b\n print $ b - c\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of\n Just (n,_) -> n\n _-> error $ \"readInt error : bs = \" ++ show bs\n\nsolve (x:_) [] = x\nsolve [] (y:_) = y\nsolve [] [] = 0\nsolve (x:xs) (y:ys)\n | x /= y = x\n | otherwise = solve xs ys\n\nmain :: IO ()\nmain = do\n _ <- getLine\n lst0 <- map readInt . B.words <$> B.getLine\n lst1 <- map readInt . B.words <$> B.getLine\n lst2 <- map readInt . B.words <$> B.getLine\n let a = sort lst0\n b = sort lst1\n c = sort lst2\n let (e1, e2) = (solve a b, solve b c)\n print e1\n print e2\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of\n Just (n,_) -> n\n _-> error $ \"readInt error : bs = \" ++ show bs\n\nmain :: IO ()\nmain = do\n _ <- getLine\n lst0 <- map readInt . B.words <$> B.getLine\n lst1 <- map readInt . B.words <$> B.getLine\n lst2 <- map readInt . B.words <$> B.getLine\n let [a, b, c] = map sum [lst0, lst1, lst2]\n print $ a - b\n print $ b - c\n"}, {"source_code": "import Data.List\n\nsolve :: (Num a, Eq a) => [a] -> [a] -> a\nsolve (x:_) [] = x\nsolve [] (y:_) = y\nsolve [] [] = 0\nsolve (x:xs) (y:ys)\n | x /= y = x\n | otherwise = solve xs ys\n\nmain :: IO ()\nmain = do\n _ <- getLine\n lst0 <- getLine >>= return . map (\\c -> read c::Integer) . words\n lst1 <- getLine >>= return . map (\\c -> read c::Integer) . words\n lst2 <- getLine >>= return . map (\\c -> read c::Integer) . words\n let a = sort lst0\n b = sort lst1\n c = sort lst2\n let (e1, e2) = (solve a b, solve b c)\n print e1\n print e2\n"}, {"source_code": "import Data.List (sort)\n\nprocess :: [Int] -> [Int] -> [Int] -> (Int,Int)\nprocess xs ys zs = (f xs' ys', f ys' zs')\n where\n xs' = sort xs\n ys' = sort ys\n zs' = sort zs\n f [a] [] = a\n f (a:as) (b:bs)\n | a == b = f as bs\n | otherwise = a\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n bs <- fmap (map readInt.words) getLine\n cs <- fmap (map readInt.words) getLine\n let (t1,t2) = process as bs cs\n print t1\n print t2"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nimport Data.Set (Set)\nimport qualified Data.Set as S\n\nimport Data.List (sort)\n\nmain = do\n c <- getContents\n let (_:l1:l2:l3:_) = lines c\n let e1 = sort . map (read :: String -> Int) . words $ l1\n let e2 = sort . map (read :: String -> Int) . words $ l2\n let e3 = sort . map (read :: String -> Int) . words $ l3\n print $ firstDifferance e1 e2\n print $ firstDifferance e2 e3\n\n\n{-\n let s1 = S.fromList e1\n let s2 = S.fromList e2\n let s3 = S.fromList e3\n let disappeared = s1 S.\\\\ s3\n let r1 = disappeared S.\\\\ s2\n let r2 = disappeared S.\\\\ r1\n print r1\n print r2\n-}\n\n\nfirstDifferance :: [Int] -> [Int] -> Int\nfirstDifferance [] [] = undefined\nfirstDifferance (x:_) [] = x\nfirstDifferance (x:xs) (y:ys)\n | x == y = firstDifferance xs ys\n | otherwise = x\n"}, {"source_code": "import Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.Int \n-- meat\n\nsolve :: [[Int64]] -> [[Int64]]\nsolve [[_], as, bs, cs] = [[sas - sbs], [sbs - scs]]\n where [sas, sbs,scs] = fmap sum [as,bs,cs]\nsolve _ = error \"you're fucked\"\n\n-- shit\nmain :: IO ()\nmain = BS.interact $ outputIntMatrixBS . solve . inputNumMatrixBS\n\ninputNumMatrixBS :: (Num a) => BS.ByteString ->[[a]]\ninputNumMatrixBS = parseMatrixBS . matrifyBS\n\noutputIntMatrixBS :: (Integral a) => [[a]] -> BS.ByteString\noutputIntMatrixBS = unmatrifyBS . unparseMatrixBs\n\nmatrifyBS :: BS.ByteString -> [[BS.ByteString]]\nmatrifyBS = fmap BS.words . BS.lines\n\nparseMatrixBS :: (Num a) => [[BS.ByteString]] ->[[a]]\nparseMatrixBS = fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger\n\nunparseMatrixBs :: (Integral a) => [[a]] -> [[BS.ByteString]]\nunparseMatrixBs = fmap.fmap $ (toLazyByteString . integerDec . toInteger)\n\nunmatrifyBS :: [[BS.ByteString]] -> BS.ByteString\nunmatrifyBS = BS.unlines . fmap BS.unwords"}], "negative_code": [{"source_code": "import Control.Applicative\nmain = do\n getLine\n m <- sequence $ replicate 3 getLine\n let mf = map (map read . words) m\n let [mf1, mf2, mf3] = map msort mf\n print $ gone2 mf1 mf2\n print $ gone2 mf2 mf3\nqsort :: Ord a => [a] -> [a]\nqsort [] = []\nqsort [x] = [x]\nqsort (x:xs) = (qsort $ filter (= x) xs)\nmsort :: Ord a => [a] -> [a]\nmsort [] = []\nmsort [x] = [x]\nmsort x = (msort $ take (quot len 2) x) ++ (msort $ drop (quot len 2) x)\n where len = length x\nth :: Int -> [a] -> a\nth 1 a = head a\nth n a = th (n-1) (tail a)\ngone :: [Int] -> [Int] -> Int\ngone x y = th len x\n where len = ((length . takeWhile (==True) . getZipList) $ (==) <$> (ZipList x) <*> (ZipList y)) + 1\ngone2 :: [Int] -> [Int] -> Int\ngone2 x y = (head . dropWhile (==0) . getZipList) $ (\\u v -> if (u==v) then 0 else u) <$> (ZipList x) <*> (ZipList (y++[0]))"}], "src_uid": "1985566215ea5a7f22ef729bac7205ed"} {"source_code": "main = getContents >>= print . f . map read . tail . words\nf x = sum . zipWith (*) x . scanr1 (+) $ map (1 -) x", "positive_code": [{"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words"}, {"source_code": "main = getContents >>= print . fst . foldl f (0, 0) . map read . tail . words\nf (a, b) c\n | c == 0 = (a + b, b)\n | c == 1 = (a, b + 1)"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}, {"source_code": "main=interact$show.sum.(scanr1(+).map(1-)>>=zipWith(*)).map read.tail.words\n"}], "negative_code": [], "src_uid": "1a3b22a5a8e70505e987d3e7f97e7883"} {"source_code": "{-# LANGUAGE TupleSections #-}\nimport Data.Array\nimport qualified Data.Set\n\n-- https://hackage.haskell.org/package/split-0.2.3.4/docs/src/Data.List.Split.Internals.html#chunksOf\nbuild :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]\nbuild g = g (:) []\n\nchunksOf :: Int -> [e] -> [[e]]\nchunksOf i ls = map (take i) (build (splitter ls)) where\n splitter :: [e] -> ([e] -> a -> a) -> a -> a\n splitter [] _ n = n\n splitter l c n = l `c` splitter (drop i l) c n\n\nparseMaze :: Int -> Int -> String -> Array (Int, Int) Char\nparseMaze h w s = listArray ((1, 1), (h, w)) (filter (/= '\\n') s)\n\nprintMaze :: Int -> Int -> Array (Int, Int) Char -> String\nprintMaze h w m = unlines $ chunksOf w $ elems m\n\nfindStart m = fst $ head $ filter (\\x -> snd x == '.') $ assocs m\n\ndfs :: Int -> Int -> Array (Int, Int) Char -> [(Int, Int)]\ndfs h w maze =\n let (starty, startx) = findStart maze :: (Int, Int)\n in dfs' [(starty, startx)] [] Data.Set.empty\n where\n dfs' [] traversal _ = traversal\n dfs' ((y, x) : toVisit) traversal visited =\n let traversal' = (y, x):traversal\n neighbors =\n [ (yy, xx)\n | (dy, dx) <- [(-1, 0), (1, 0), (0, -1), (0, 1)]\n , let (yy, xx) = (y + dy, x + dx)\n , 1 <= yy && yy <= h\n , 1 <= xx && xx <= w\n , maze ! (yy, xx) == '.'\n , (yy, xx) `Data.Set.notMember` visited\n ]\n toVisit' = neighbors ++ toVisit\n visited' = Data.Set.union visited (Data.Set.fromList neighbors)\n in dfs' toVisit' traversal' visited'\n\n\nmain = do\n --let first = \"500 500 249999\" -- XXX\n --let rest = unlines $ replicate 500 (replicate 500 '.')\n first <- getLine\n rest <- getContents\n\n let [h, w, k] = (map read . words) first\n let maze = parseMaze h w rest\n let topo = dfs h w maze\n let maze' = maze // map (, 'X') (take k topo)\n putStrLn (printMaze h w maze')", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List as L\nimport Data.Tuple\nimport Data.Maybe\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\ndata Cell = Cell {row::Int,col::Int} deriving (Show,Eq,Ord)\n\nmain = do\n [n,m,k] <- map read <$> words <$> getLine :: IO[Int] \n lab <- M.fromList <$> foldl1' (++) <$> \n map (\\(row,list) -> map (\\(col,e) -> (Cell row col,e)) $ zip [0..] list ) <$> \n zip [0..] <$> lines <$> getContents \n let solution n m k lab = let \n neighbours cells visited= do \n original <- cells\n t <- [(-1,0),(1,0)]\n (i,j) <- [t,swap t]\n let x = row original + i \n y = col original + j\n cell = Cell x y\n if x >= 0 && x < n && y >= 0 && y < m && lab M.! cell == '.' && S.notMember cell visited \n then return cell \n else [] \n walk::[(Int,Cell)] -> S.Set Cell -> S.Set Cell -> [Cell]-> Int -> [(Int,Cell)]\n walk levels prev cur strip level = let \n nextSet = S.fromList $ (neighbours strip $ S.union prev cur )\n next = S.toList nextSet\n in if null next \n then levels \n else walk (zip (repeat level) next ++ levels) cur nextSet next (level + 1)\n start = fst $ fromJust $ find ((== '.') . snd) $ M.assocs lab\n walkList = walk [(0,start)] S.empty (S.singleton start) [start] 1 \n wall = S.fromList $ map snd $ take k $ reverse $ sort walkList \n result = [[ if lab M.! cell == '#' \n then '#' \n else if S.member cell wall \n then 'X' \n else '.' \n | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]\n countX = length $ filter (== 'X' ) $ foldl1' (++) result\n in result{- ++[show countX]-}\n mapM putStrLn $ solution n m k lab"}, {"source_code": "import Data.Graph\nimport Data.Set\nmain = interact $ f . Prelude.map words . lines\n\ng x r c s1 = zip (repeat x) $ Prelude.filter (\\i-> member i s1) $ concat [c1, c2, c3, c4]\n where c1 = if (quot x c) == quot (x-1) c then [x-1] else []\n c2 = if (quot x c) == quot (x+1) c then [x+1] else []\n c3 = if x-c >= 0 then [x-c] else []\n c4 = if x+c <= (r*c-1) then [x+c] else []\n\nsplitEvery _ [] = []\nsplitEvery n xs = as : splitEvery n bs\n where (as,bs) = Prelude.splitAt n xs\n\nf (x:xs) = ans\n where (r:c:conn:_) = Prelude.map read x\n ccxs = concat (concat xs)\n mat = [i | (i, v) <- zip ([0..(r*c-1)]) ccxs, v=='.']\n s1 = fromList mat\n e = concat $ Prelude.map (\\i -> g i r c s1) mat\n tvl = Prelude.filter (\\i -> member i s1) $ topSort (buildG (0, r*c-1) e)\n doors = fromList $ Prelude.drop ((length mat)-conn) tvl\n insertdoor (i,k) = if (member i doors) && k=='.' then 'X' else k\n ans = unlines $ splitEvery c $ Prelude.map insertdoor $ zip [0..] ccxs\n"}, {"source_code": "import Data.Array\nimport Control.Monad\nimport Data.Graph\nimport Data.Tree\nmain = do\n [n,m,k] <- map read . words <$> getLine\n g0 <- listArray ((1,1),(n,m)) . concat . lines <$> getContents\n let neighbors (i,j) = filter ((== '.') . (g0!)) $\n filter (inRange (bounds g0))\n [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]\n (g,v2n,k2v) = graphFromEdges $ map (\\p -> (p,p,neighbors p)) $\n filter ((== '.') . (g0!)) (indices g0)\n [f] = dff g\n g' = g0 // take k (foldTree h f [])\n h a bs = foldr (.) ((p,'X') :) bs where (p,_,_) = v2n a\n forM_ [1..n] $ \\i -> do\n forM_ [1..m] $ \\j -> putChar $ g' ! (i,j)\n putChar '\\n'\n"}, {"source_code": "import Control.Applicative\nimport Data.List as L\nimport Data.Tuple\nimport Data.Maybe\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\ndata Cell = Cell {row::Int,col::Int} deriving (Show,Eq,Ord)\n\nmain = do\n [n,m,k] <- map read <$> words <$> getLine :: IO[Int] \n lab <- M.fromList <$> foldl1' (++) <$> \n map (\\(row,list) -> map (\\(col,e) -> (Cell row col,e)) $ zip [0..] list ) <$> \n zip [0..] <$> lines <$> getContents \n let solution n m k lab = let \n walk::[(Int,Cell)] -> S.Set Cell -> S.Set Cell -> [Cell]-> Int -> [(Int,Cell)]\n walk levels prev cur strip level = let\n visited = S.union prev cur\n neighbours = do \n original <- strip\n t <- [(-1,0),(1,0)]\n (i,j) <- [t,swap t]\n let x = row original + i \n y = col original + j\n cell = Cell x y\n if x >= 0 && x < n && y >= 0 && y < m && lab M.! cell == '.' && S.notMember cell visited\n then return cell \n else [] \n nextSet = S.fromList neighbours\n next = S.toList nextSet\n in if null next \n then levels \n else walk (zip (repeat level) next ++ levels) cur nextSet next (level + 1)\n start = fst $ fromJust $ find ((== '.') . snd) $ M.assocs lab\n walkList = walk [(0,start)] S.empty (S.singleton start) [start] 1 \n wall = S.fromList $ map snd $ take k $ reverse $ sort walkList \n result = [[ if lab M.! cell == '#' \n then '#' \n else if S.member cell wall \n then 'X' \n else '.' \n | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]\n countX = length $ filter (== 'X' ) $ foldl1' (++) result\n in result{- ++[show countX]-}\n mapM putStrLn $ solution n m k lab"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\nimport Data.Array\nimport qualified Data.Set\n\n-- https://hackage.haskell.org/package/split-0.2.3.4/docs/src/Data.List.Split.Internals.html#chunksOf\nbuild :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]\nbuild g = g (:) []\n\nchunksOf :: Int -> [e] -> [[e]]\nchunksOf i ls = map (take i) (build (splitter ls)) where\n splitter :: [e] -> ([e] -> a -> a) -> a -> a\n splitter [] _ n = n\n splitter l c n = l `c` splitter (drop i l) c n\n\nparseMaze :: Int -> Int -> String -> Array (Int, Int) Char\nparseMaze h w s = listArray ((1, 1), (h, w)) (filter (/= '\\n') s)\n\nprintMaze :: Int -> Int -> Array (Int, Int) Char -> String\nprintMaze h w m = unlines $ chunksOf w $ elems m\n\nfindStart m = fst $ head $ filter (\\x -> snd x == '.') $ assocs m\n\ndfs :: Int -> Int -> Array (Int, Int) Char -> [(Int, Int)]\ndfs h w maze =\n let (starty, startx) = findStart maze :: (Int, Int)\n in dfs' [(starty, startx)] [] Data.Set.empty\n where\n dfs' [] traversal _ = traversal\n dfs' ((y, x) : toVisit) traversal visited =\n let traversal' = (y, x):traversal\n neighbors =\n [ (yy, xx)\n | (dy, dx) <- [(-1, 0), (1, 0), (0, -1), (0, 1)]\n , let (yy, xx) = (y + dy, x + dx)\n , 1 <= yy && yy <= h\n , 1 <= xx && xx <= w\n , maze ! (yy, xx) == '.'\n , (yy, xx) `Data.Set.notMember` visited\n ]\n toVisit' = neighbors ++ toVisit\n visited' = Data.Set.union visited (Data.Set.fromList neighbors)\n in dfs' toVisit' traversal' visited'\n\n\nmain = do\n --first <- getLine\n let first = \"500 500 249999\" -- XXX\n let [h, w, k] = (map read . words) first\n --rest <- getContents\n let rest = unlines $ replicate 500 (replicate 500 '.')\n\n let maze = parseMaze h w rest\n let topo = dfs h w maze\n let maze' = maze // map (, 'X') (take k topo)\n putStrLn (printMaze h w maze')"}, {"source_code": "import Data.Set\nimport Data.Array\nmain = interact $ f . Prelude.map words . lines\n\n-- visited empty set\ndfs mat start@(i,j) visited = start:(concat l)\n where cvisited = insert start visited\n dir x = if (member x mat) && (not (member x cvisited)) then dfs mat x cvisited else []\n l = Prelude.map dir [(i, j+1),\n (i+1, j),\n (i-1, j),\n (i, j-1)]\n\nf (x:xs) = ans\n where (r:c:conn:_) = Prelude.map read x\n xsarr = array ((1, 1), (r, c)) $ zip [(i, j) | i <- [1..r], j <- [1..c]] (concat (concat xs))\n mat = fromList [(i, j) | i <- [1..r], j <- [1..c], (xsarr ! (i, j)) == '.']\n tvl = dfs mat (minimum mat) empty\n doors = fromList $ Prelude.drop ((length mat)-conn) tvl\n insertdoor i j k = if member (i, j) doors then 'X' else k\n ans = unlines [[ insertdoor row col v | (col, v) <- zip [1..c] val] | (val, row) <- zip (concat xs) [1..r]]\n"}, {"source_code": "import Data.Set\nimport Data.Array\nmain = interact $ f . Prelude.map words . lines\n\ndfs mat start@(i,j) visited = start:(concat [v1, v2, v3, v4])\n where vp = insert start visited\n dir x v = if (member x mat) && (not (member x v)) then dfs mat x v else []\n v1 = dir (i, j+1) vp\n v2 = dir (i+1, j) $ union vp $ fromList v1\n v3 = dir (i-1, j) $ union vp $ fromList v2\n v4 = dir (i, j-1) $ union vp $ fromList v3\n\nf (x:xs) = ans\n where (r:c:conn:_) = Prelude.map read x\n mat = fromList [(i, j) | ((i, j), v) <- zip (range ((1, 1), (r,c))) (concat (concat xs)), v=='.']\n tvl = dfs mat (minimum mat) empty\n doors = fromList $ Prelude.drop ((length mat)-conn) tvl\n insertdoor i j k = if member (i, j) doors then 'X' else k\n ans = unlines [[ insertdoor row col v | (col, v) <- zip [1..c] val] | (val, row) <- zip (concat xs) [1..r]]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad\nimport Control.Monad.ST\nmain = do\n [n,m,k] <- map read . words <$> getLine\n gc0 <- concat . lines <$> getContents\n forM_ [1..n] $ \\i -> do\n forM_ [1..m] $ \\j -> putChar $ solve n m k gc0 ! (i,j)\n putChar '\\n'\nsolve n m k gc0 = runSTUArray $ do\n let bs = ((1,1),(n,m))\n g <- newListArray bs gc0 :: ST s (STUArray s (Int,Int) Char)\n let neighbors (i,j) = filterM (fmap (== '.') . readArray g) $ filter (inRange bs) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]\n go 0 _ = return ()\n go k (s:ss) = do\n [n] <- neighbors s\n writeArray g s 'X'\n ns' <- neighbors n\n case ns' of [n'] -> go (k-1) (n:ss)\n _ -> go (k-1) ss\n go k =<< filterM (fmap ((== 1) . length) . neighbors) (range bs)\n return g\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Control.Arrow\nmain = do\n [n,m,k] <- map read . words <$> getLine\n gc0 <- concat . lines <$> getContents\n forM_ [1..n] $ \\i -> do\n forM_ [1..m] $ \\j -> putChar $ solve n m k gc0 ! (i,j)\n putChar '\\n'\nsolve n m k gc0 = runSTUArray $ do\n let bs = ((1,1),(n,m))\n g <- newListArray bs gc0 :: ST s (STUArray s (Int,Int) Char)\n let neighbors (i,j) = filterM (fmap (== '.') . readArray g) $ filter (inRange bs) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]\n go 0 _ = return ()\n go k (s:ss) = do\n v <- readArray g s\n if v /= '.' then go k ss else do\n ns <- neighbors s\n writeArray g s 'X'\n ns' <- filterM (fmap ((== 1) . length) . neighbors) ns\n go (k-1) (ns' ++ ss)\n go k =<< fmap (map snd . sort) . mapM (runKleisli $ Kleisli (fmap length . neighbors) &&& arr id) =<< filterM (fmap (== '.') . readArray g) (range bs)\n return g\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Control.Arrow\nmain = do\n [n,m,k] <- map read . words <$> getLine\n gc0 <- concat . lines <$> getContents\n forM_ [1..n] $ \\i -> do\n forM_ [1..m] $ \\j -> putChar $ solve n m k gc0 ! (i,j)\n putChar '\\n'\nsolve n m k gc0 = runSTUArray $ do\n let bs = ((1,1),(n,m))\n g <- newListArray bs gc0 :: ST s (STUArray s (Int,Int) Char)\n let neighbors (i,j) = filterM (fmap (== '.') . readArray g) $ filter (inRange bs) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]\n go 0 _ = return ()\n go k (s:ss) = do\n ns <- neighbors s\n writeArray g s 'X'\n ns' <- filterM (fmap ((== 1) . length) . neighbors) ns\n go (k-1) (ns' ++ ss)\n go k =<< fmap (map snd . sort) . mapM (runKleisli $ Kleisli (fmap length . neighbors) &&& arr id) =<< filterM (fmap (== '.') . readArray g) (range bs)\n return g\n"}, {"source_code": "import Control.Applicative\nimport Data.List as L\nimport Data.Tuple\nimport Data.Maybe\nimport Data.Map (fromList,(!),assocs,showTree)\nimport qualified Data.Set as S\n\ndata Cell = Cell {row::Int,col::Int} deriving Show\ninstance Eq Cell where\n\tx == y = row x == row y && col x == col y\ninstance Ord Cell where\tx `compare` y = (row x, col x) `compare` (row y,col y) \ndata Walk = Walk { remains:: Int, visited::S.Set Cell, collected::S.Set Cell } deriving Show\n\nmain = do\n\t[n,m,k] <- map read <$> words <$> getLine :: IO[Int] \n\tlab <- fromList <$> foldl1' (++) <$> \n\t\t map (\\(row,list) -> map (\\(col,e) -> (Cell row col,e)) $ zip [0..] list ) <$> \n\t\t zip [0..] <$> lines <$> getContents \n\tlet solution n m k lab = let \n\t\tneighbours visited cell = filter valid [Cell (row cell+i) (col cell+j)| t <- [(-1,0),(1,0)], (i,j)<- [t,swap t]] where \n\t\t\tvalid cell = row cell >= 0 && row cell< n && col cell>= 0 && col cell< m && S.notMember cell visited && lab ! cell == '.'\n\t\twalkLab::Cell -> Walk -> Walk \n\t\twalkLab cell walk = let \n\t\t\tvisitMe walk = Walk (remains walk) (S.insert cell $ visited walk) (collected walk)\n\t\t\tcollectMe walk = if (remains walk ) == 0 then visitMe walk \n\t\t\t\telse Walk (remains walk - 1) (S.insert cell $ visited walk ) (S.insert cell $ collected walk) \n\t\t\tin collectMe $ foldr walkLab (visitMe walk) (neighbours (visited walk ) cell)\n\t\tfound = collected $ walkLab (fst $ fromJust $ find ((== '.') . snd) $ assocs lab) (Walk k S.empty S.empty )\n\t\tin [[ if lab ! cell == '#' then '#' else if S.member cell found then 'X' else '.' | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]\n\n\t\t--neighbours S.empty $ Cell 0 1\n\tmapM putStrLn $ solution n m k lab"}, {"source_code": "import Control.Applicative\nimport Data.List as L\nimport Data.Tuple\nimport Data.Maybe\nimport Data.Map (fromList,(!),assocs,showTree)\nimport qualified Data.Set as S\n\ndata Cell = Cell {row::Int,col::Int} deriving Show\ninstance Eq Cell where\n\tx == y = row x == row y && col x == col y\ninstance Ord Cell where\tx `compare` y = (row x, col x) `compare` (row y,col y) \ndata Walk = Walk { remains:: Int, visited::S.Set Cell, collected::S.Set Cell } deriving Show\n\nmain = do\n\t[n,m,k] <- map read <$> words <$> getLine :: IO[Int] \n\tlab <- fromList <$> foldl1' (++) <$> \n\t\t map (\\(row,list) -> map (\\(col,e) -> (Cell row col,e)) $ zip [0..] list ) <$> \n\t\t zip [0..] <$> lines <$> getContents \n\tlet solution n m k lab = let \n\t\tneighbours visited cell = filter valid [Cell (row cell+i) (col cell+j)| t <- [(-1,0),(1,0)], (i,j)<- [t,swap t]] where \n\t\t\tvalid cell = row cell >= 0 && row cell< n && col cell>= 0 && col cell< m && S.notMember cell visited && lab ! cell == '.'\n\t\twalkLab::Cell -> Walk -> Walk \n\t\twalkLab cell walk = let \n\t\t\tvisitMe walk = Walk (remains walk) (S.insert cell $ visited walk) (collected walk)\n\t\t\tcollectMe walk = if (remains walk ) == 0 then visitMe walk \n\t\t\t\telse Walk (remains walk - 1) (S.insert cell $ visited walk ) (S.insert cell $ collected walk) \n\t\t\tin collectMe $ foldr walkLab (visitMe walk) (neighbours (visited walk ) cell)\n\t\tfound = collected $ walkLab (fst $ fromJust $ find ((== '.') . snd) $ assocs lab) (Walk k S.empty S.empty )\n\t\tin [[ if lab ! cell == '#' || S.member cell found then '#' else '.' | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]\n\n\t\t--neighbours S.empty $ Cell 0 1\n\tmapM putStrLn $ solution n m k lab"}], "src_uid": "3aba4a129e24ca2f06f5f3ef13415b8b"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n _ <- getInt\n a <- replicateM (n - 2) getInt\n _ <- getInt\n let\n stuck = negate 1\n totMoves = foldl' (+) 0 [quot (v + 1) 2 | v <- a]\n ans = case a of\n [v] | odd v -> stuck\n _ | any (> 0) a && all (< 2) a -> stuck\n | otherwise -> case filter (> 0) a of\n [3] -> stuck\n [v] | odd v -> totMoves + 1 -- very nasty edge case\n -- hopefully I didn't miss more\n _ -> totMoves\n pure $ putInts [ans]\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\n\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.IO as Text\nimport qualified Data.Text.Read as Text\n\nsolve :: Int -> [Int] -> Int\nsolve 3 [x, y, z]\n | odd y = -1\n | otherwise = y `div` 2\nsolve n lst\n | all ((==) 1) innerList = -1\n | otherwise = (totalSum + oddCount) `div` 2\n where innerList = init $ tail lst\n totalSum = sum innerList\n oddCount = length $ filter odd innerList\n\ntextToInt :: Text -> Int\ntextToInt text =\n case Text.decimal text of\n Right (n, _) -> n\n\nreadInts :: Text -> [Int]\nreadInts = map textToInt . Text.words\n\nhandleCases:: Int -> [Text] -> [Int]\nhandleCases 0 _ = []\nhandleCases t (line1:line2:rest) = solve n a : handleCases (t-1) rest\n where n = textToInt line1\n a = readInts line2\n\nmain :: IO ()\nmain = do\n line1:rest <- Text.lines <$> Text.getContents\n let t = textToInt line1\n res = handleCases t rest\n Text.putStr $ Text.unlines $ map (Text.pack . show) res\n"}, {"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n\r\nplus :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)\r\nplus (a, b, c) (d, e, f) = (a + d, b + e, c + f)\r\n \r\ncheckHelper :: [Int] -> (Int, Int, Int)\r\ncheckHelper [] = (0, 0, 0)\r\ncheckHelper (_ : []) = (0, 0, 0)\r\ncheckHelper (1 : xs) = (0, 0, 1) `plus` checkHelper xs\r\ncheckHelper (x : xs) = checkHelper xs `plus` if (x `mod` 2 == 0)\r\n then (1, 0, 0)\r\n else (0, 1, 0)\r\n \r\ncheckArr :: [Int] -> Bool\r\ncheckArr (x : xs) = od > 0 || (ev > 0 && ev + on > 1)\r\n where (od, ev, on) = checkHelper xs\r\n \r\ncountHelper :: [Int] -> Int\r\ncountHelper [] = 0\r\ncountHelper (x : []) = 0\r\ncountHelper (x : xs) = countHelper xs + (x + 1) `div` 2\r\n\r\ncountArr :: [Int] -> Int\r\ncountArr (x : xs) = countHelper xs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n arr <- readIntArr\r\n if (checkArr arr)\r\n then print $ countArr arr\r\n else print $ -1\r\n\r\nreadLoop :: Int -> IO ()\r\nreadLoop i =\r\n if (i == 0)\r\n then pure ()\r\n else do\r\n solve\r\n readLoop (i - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n readLoop n"}, {"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n \r\ndropTail :: [Int] -> [Int]\r\ndropTail [] = []\r\ndropTail (_ : []) = []\r\ndropTail (x : xs) = (x : dropTail xs)\r\n\r\nplus :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)\r\nplus (a, b, c) (d, e, f) = (a + d, b + e, c + f)\r\n \r\ncheckHelper :: [Int] -> (Int, Int, Int)\r\ncheckHelper [] = (0, 0, 0)\r\ncheckHelper (1 : xs) = (0, 0, 1) `plus` checkHelper xs\r\ncheckHelper (x : xs) = checkHelper xs `plus` if (x `mod` 2 == 0)\r\n then (1, 0, 0)\r\n else (0, 1, 0)\r\n \r\ncheckArr :: [Int] -> Bool\r\ncheckArr (x : xs) = od > 0 || (ev > 0 && ev + on > 1)\r\n where (od, ev, on) = checkHelper $ dropTail xs\r\n \r\ncountHelper :: [Int] -> Int\r\ncountHelper [] = 0\r\ncountHelper (x : xs) = countHelper xs + (x + 1) `div` 2\r\n\r\ncountArr :: [Int] -> Int\r\ncountArr (x : xs) = countHelper $ dropTail xs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n arr <- readIntArr\r\n if (checkArr arr)\r\n then print $ countArr arr\r\n else print $ -1\r\n\r\nreadLoop :: Int -> IO ()\r\nreadLoop i =\r\n if (i == 0)\r\n then pure ()\r\n else do\r\n solve\r\n readLoop (i - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n readLoop n"}, {"source_code": "import Control.Monad (forM)\n\nsolve t = do \n n <- readLn::IO Int\n arr <- getLine >>= \\s -> return $ drop 1 $ take (n - 1) $ map (read::String -> Int) (words s)\n let ans | (maximum arr == 1) || (n == 3 && odd (head arr)) = print (-1)\n | otherwise = print $ foldl (\\x a -> x + (a + 1) `div` 2) 0 arr\n ans\n\nmain = do\ntlen <- readLn :: IO Int\nforM [0..(tlen - 1)] (\\t -> do solve t)\n\n"}, {"source_code": "main = interact $ unlines . map p . chunk 2 . drop 1 . lines\r\n\r\nchunk n [] = []\r\nchunk n xs = take n xs : chunk n (drop n xs)\r\n\r\nfolff t x = let (s, o, e, c1) = t in add s o e c1 x\r\n where add s o e c1 x\r\n | x == 1 = (s + 1, o + 1, e, c1 + 1)\r\n | even x = (s + x, o, e + 1, c1)\r\n | otherwise = (s + x, o + 1, e, c1)\r\n\r\ncalc :: (Int, Int, Int, Int) -> Int\r\ncalc t\r\n | o == 0 = s `div` 2\r\n | e == 0 && o == 1 = -1\r\n | e == 0 && o == c1 = -1\r\n | e == 0 = calc(s-1, o-1, e+1, 0) + 1\r\n | o == 1 = calc(s-1, 0, 0, 0) + 1\r\n | otherwise = calc(s, o - k * 2, 1, 0) + k\r\n where (s, o, e, c1) = t\r\n k = o `div` 2 \r\n\r\np xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]\r\n in show $ calc $ foldl folff (0,0,0,0) $ init $ tail s\r\n\r\n"}], "negative_code": [{"source_code": "import Control.Monad (forM_)\n\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.IO as Text\nimport qualified Data.Text.Read as Text\n\nsolve :: Int -> [Int] -> Int\nsolve n a\n | oddCount > evenSum `div` 2 = -1\n | otherwise = (evenSum + oddCount + oddSum) `div` 2\n where innerList = init $ tail a\n\n evenList = filter even innerList\n oddList = filter (not . even) innerList\n\n oddCount = length oddList\n\n evenSum = sum evenList\n oddSum = sum oddList\n\n\ntextToInt :: Text -> Int\ntextToInt text =\n case Text.decimal text of\n Right (n, _) -> n\n\nreadInts :: Text -> [Int]\nreadInts = map textToInt . Text.words\n\nhandleCases:: Int -> [Text] -> [Int]\nhandleCases 0 _ = []\nhandleCases t (line1:line2:rest) = solve n a : handleCases (t-1) rest\n where n = textToInt line1\n a = readInts line2\n\nmain :: IO ()\nmain = do\n line1:rest <- Text.lines <$> Text.getContents\n let t = textToInt line1\n res = handleCases t rest\n Text.putStr $ Text.unlines $ map (Text.pack . show) res\n"}], "src_uid": "5b99775142b4a28b6b1069367602448f"} {"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines\n", "positive_code": [{"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\nimport Data.Array\n\naddM !x !y = (x + y) `mod` 1000000007\n\nsmm = foldl' addM 0\n\nsolve rec len 0 = 1\nsolve rec 0 sum = 0\nsolve rec len sum \n | sum < 0 = 0\n | otherwise = smm $ map (rec (len-1)) . filter (>=0) . map (sum-) $ [0..25]\n\nbnd = ((0,0), (100, 2500))\n\npref l s = precalc!(l,s)\nprecalc = listArray bnd [solve pref l s|(l,s)<-range bnd]\n\nc2n c = fromEnum c - fromEnum 'a'\n\ns l=pref(length l)(sum l)\n\nmain=interact$unlines.map(show.pred).map(s.map c2n).tail.lines"}, {"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines"}, {"source_code": "import Array\ns r _ 0=1\ns r 0 _=0\ns r l s|s<0=0|1>0=foldl(\\x y->mod(x+y)1000000007)0$map(r$l-1)$[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b[s q l m|(l,m)<-range b]\nq l s=p!(l,s)\nz c=f c-f 'a';f=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred).map(y.map z).tail.lines"}, {"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines\n"}, {"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines\n"}, {"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines\n"}, {"source_code": "import Data.Array\nimport Data.Char (ord)\nimport Data.Function (fix)\n\nmain = do\n tests <- fmap (tail . words) getContents\n mapM_ (print . solve) tests\n where\n dp = count 100 2500\n solve test = (dp ! (length test, sum $ map (\\ch -> (ord ch) - (ord 'a')) test)) - 1\n\ncount :: Int -> Int -> Array (Int, Int) Int\ncount maxLen maxSum = fix f\n where\n bs = ((0, 0), (maxLen, maxSum))\n f dp = listArray bs\n [if i == 1 then 1\n else sumMod 1000000007 $ map (\\s -> dp ! (i - 1, s)) [max 0 (j - 25)..min j (25 * (i - 1))]\n | (i, j) <- range bs]\n\nsumMod :: (Ord a, Num a) => a -> [a] -> a\nsumMod m = foldl (\\s x -> if s + x >= m then s + x - m else s + x) 0\n"}, {"source_code": "import Data.Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines"}], "negative_code": [{"source_code": "import Data.Array\nimport Data.Char (ord)\nimport Data.Function (fix)\n\nmain = do\n tests <- fmap (tail . words) getContents\n mapM_ (print . solve) tests\n where\n dp = count 100 2500\n solve test = (dp ! (length test, sum $ map (\\ch -> (ord ch) - (ord 'a')) test)) - 1\n\ncount :: Int -> Int -> Array (Int, Int) Int\ncount maxLen maxSum = fix f\n where\n bs = ((0, 0), (maxLen, maxSum))\n f dp = listArray bs\n [if i == 1 then 1\n else (sum $ map (\\s -> dp ! (i - 1, s)) [max 0 (j - 25)..min j (25 * (i - 1))]) `mod` 1000000007\n | (i, j) <- range bs]\n"}, {"source_code": "import Array\ns(l,s)|s<1=1|l<1=0|1>0=foldl(\\x y->mod(p!(x,l-1)+y)1000000007)0[max 0$s-25..s]\nb=((0,0),(100,2500))\np=listArray b$map s$range b\nf=fromEnum\ny l=p!(length l,sum l)\nmain=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines"}], "src_uid": "75f64fc53b88a06c58a219f11da8efb7"} {"source_code": "import Control.Arrow\nimport Control.Applicative\nimport Data.Int\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport Data.List\n\ndata Tower = Tower Int Int\n\nreadTower s = Tower x y\n where\n [x, y] = map read . words $ s\n\nsol :: Int -> [Tower] -> [Int64]\nsol n t = sol' t IS.empty IS.empty (fromIntegral n) (fromIntegral n)\n where\n sol' [] _ _ _ _ = []\n sol' (t:ts) bx by kx ky = (nkx * nky) : (sol' ts nbx nby nkx nky)\n where\n (Tower x y) = t\n nx = x `IS.member` bx\n ny = y `IS.member` by\n nkx = if nx then kx else kx - 1\n nky = if ny then ky else ky - 1\n nbx = if nx then bx else x `IS.insert` bx\n nby = if ny then by else y `IS.insert` by\n\n\nmain :: IO()\nmain = do\n [n, _] <- (map read . words) <$> getLine\n towers <- (map readTower . lines) <$> getContents\n putStrLn $ intercalate \" \" $ map show $ sol n towers\n", "positive_code": [{"source_code": "import Data.List hiding (insert)\nimport Data.Int\nimport Data.IntSet hiding (map)\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]\n let n64 = fromIntegral n :: Int64\n solve rocks empty empty n64 n64\n\nsolve [] cols rows emptyCols emptyRows = return ()\nsolve ([x,y]:rocks) cols rows emptyCols emptyRows = do\n let col_already = member x cols\n let row_already = member y rows\n let emptyCols' = if col_already then emptyCols else emptyCols - 1\n let emptyRows' = if row_already then emptyRows else emptyRows - 1\n putStr $ show $ emptyCols' * emptyRows'\n putChar ' '\n let cols' = insert x cols\n let rows' = insert y rows\n solve rocks cols' rows' emptyCols' emptyRows'"}, {"source_code": "import Data.IntSet hiding (map)\nmain = interact $ solve . map (map (read::String->Int) . words) . lines\nsolve ([n',_]:xs) = let n = toInteger n' \n go [] _ _ = []\n go ([a,b]:xs) (r,rs) (c,cs) = let (r',rs') = if member a rs then (r, rs) else (r+1, insert a rs)\n (c',cs') = if member b cs then (c, cs) else (c+1, insert b cs)\n \n in (n*n-r'*n-c'*n+r'*c') : go xs (r',rs') (c',cs') \n in unwords . map show $ go xs (0,empty) (0,empty)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map as Map\nimport Data.Int\n\nsolve :: [Int64] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> (Int64, Map.Map Int64 Int64, Map.Map Int64 Int64)\nsolve [rPos,cPos] n curAtt rAtt cAtt = (curAtt + newRowAtt + newColAtt - p, Map.insert rPos 0 rAtt, Map.insert cPos 0 cAtt)\n where newRowAtt = case Map.member rPos rAtt of\n True -> 0\n False -> n - (fromIntegral $ Map.size cAtt)\n newColAtt = case Map.member cPos cAtt of\n True -> 0\n False -> n - (fromIntegral $ Map.size rAtt)\n p | not (Map.member cPos cAtt) && not (Map.member rPos rAtt) = 1\n | otherwise = 0\n\nsolve1 :: [[Int64]] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> IO ()\nsolve1 [] _ _ _ _ = return ()\nsolve1 (x:xs) n curAtt rAtt cAtt = do\n let (res, newRAtt, newCAtt) = solve x n curAtt rAtt cAtt\n putStr . show $ n * n - res\n putStr \" \"\n solve1 xs n res newRAtt newCAtt\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n lines <- mapM (\\_ -> map (read :: String -> Int64) . words <$> getLine) [1..m]\n solve1 lines n 0 Map.empty Map.empty\n putStrLn \"\"\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map as Map\nimport Data.Int\n\nsolve :: [Int64] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> (Int64, Map.Map Int64 Int64, Map.Map Int64 Int64)\nsolve [rPos,cPos] n curAtt rAtt cAtt = (curAtt + newRowAtt + newColAtt - p, Map.insert rPos 0 rAtt, Map.insert cPos 0 cAtt)\n where newRowAtt = case Map.member rPos rAtt of\n True -> 0\n False -> n - ((fromIntegral :: Int -> Int64) (Map.size cAtt))\n newColAtt = case Map.member cPos cAtt of\n True -> 0\n False -> n - ((fromIntegral :: Int -> Int64) (Map.size rAtt))\n p | not (Map.member cPos cAtt) && not (Map.member rPos rAtt) = 1\n | otherwise = 0\n\nsolve1 :: [[Int64]] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> IO ()\nsolve1 [] _ _ _ _ = return ()\nsolve1 (x:xs) n curAtt rAtt cAtt = do\n let (res, newRAtt, newCAtt) = solve x n curAtt rAtt cAtt\n putStr . show $ n * n - res\n putStr \" \"\n solve1 xs n res newRAtt newCAtt\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n lines <- mapM (\\_ -> map (read :: String -> Int64) . words <$> getLine) [1..m]\n solve1 lines n 0 Map.empty Map.empty\n putStrLn \"\"\n"}, {"source_code": "import Control.Monad\nimport System.IO\nimport qualified Data.Set as Set\n\ntype Result = (Set.Set Integer, Set.Set Integer)\n\nreadInput :: IO [Integer]\nreadInput = fmap ((map read) . words) getLine\n\nfreeCells :: Integer -> Integer -> Integer -> Integer\nfreeCells n nx ny = n * n - (n * nx) - ((n - nx) * ny)\n\nanswer :: Result -> Integer -> Integer\nanswer r n = freeCells n (toInteger (Set.size (fst r))) (toInteger (Set.size (snd r)))\n\nprocessLine :: Integer -> Integer -> Result -> IO [()]\nprocessLine n k r\n | k == 0 = return [()]\n | otherwise = process\n where process = do\n l <- readInput\n let nsx = Set.insert (l !! 0) (fst r)\n let nsy = Set.insert (l !! 1) (snd r)\n let newN = answer (nsx, nsy) n\n putStr (show $ answer (nsx, nsy) n)\n putStr \" \"\n processLine n (k-1) (nsx, nsy)\n\n\nmain :: IO [()]\nmain = do\n nm <- readInput\n let sx = Set.empty\n let sy = Set.empty\n let n = (nm !! 0)\n\n processLine n (nm !! 1) (sx, sy)\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]\n let rows = [y | [x,y] <- rocks]\n let cols = [x | [x,y] <- rocks]\n solve rows cols n [] []\n\nsolve [] [] _ _ _ = return ()\nsolve (r:rs) (c:cs) n prevRs prevCs = do\n let r_already = r `elem` prevRs\n let c_already = c `elem` prevCs\n let prevRs' = if r_already then prevRs else r:prevRs\n let prevCs' = if c_already then prevCs else c:prevCs\n putStrLn $ show $ (n - (length prevRs')) * (n - (length prevCs'))\n putChar ' '\n solve rs cs n prevRs' prevCs'"}, {"source_code": "import Data.List\nimport System.IO\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]\n let rows = [y | [x,y] <- rocks]\n let cols = [x | [x,y] <- rocks]\n solve rows cols n [] []\n\nsolve [] [] _ _ _ = hFlush stdout\nsolve (r:rs) (c:cs) n prevRs prevCs = do\n let r_already = r `elem` prevRs\n let c_already = c `elem` prevCs\n let prevRs' = if r_already then prevRs else r:prevRs\n let prevCs' = if c_already then prevCs else c:prevCs\n putStr $ show $ (n - (length prevRs')) * (n - (length prevCs'))\n putChar ' '\n solve rs cs n prevRs' prevCs'\n"}, {"source_code": "import Data.List\n\nmain = do\n [n,m] <- (map read . words) `fmap` getLine :: IO [Int]\n rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]\n let rows = [y | [x,y] <- rocks]\n let cols = [x | [x,y] <- rocks]\n solve rows cols n [] []\n\nsolve [] [] _ _ _ = return ()\nsolve (r:rs) (c:cs) n prevRs prevCs = do\n let r_already = r `elem` prevRs\n let c_already = c `elem` prevCs\n let prevRs' = if r_already then prevRs else r:prevRs\n let prevCs' = if c_already then prevCs else c:prevCs\n putStr $ show $ (n - (length prevRs')) * (n - (length prevCs'))\n putChar ' '\n solve rs cs n prevRs' prevCs'"}, {"source_code": "import Data.IntSet hiding (map)\nmain = interact $ solve . map (map (read::String->Int) . words) . lines\nsolve ([n,_]:xs) = let go [] _ _ _ = []\n go ([a,b]:xs) (r,rs) (c,cs) k = let k' = k - 2 * n + 1 + r + c\n (r',rs',k'') = if member a rs then (r, rs, k'+1) else (r+1, insert a rs, k')\n (c',cs',k''') = if member b cs then (c, cs,k''+1) else (c+1, insert b cs, k'')\n in k''' : go xs (r',rs') (c',cs') k'''\n in unwords . map show $ go xs (0,empty) (0,empty) (n*n)\n"}, {"source_code": "import Data.IntSet hiding (map)\nmain = interact $ solve . map (map (read::String->Int) . words) . lines\nsolve ([n',_]:xs) = let n = toInteger n' \n go [] _ _ _ = []\n go ([a,b]:xs) (r,rs) (c,cs) k = let k' = k - 2 * n + 1\n (r',rs',k'') = if member a rs then (r, rs, k'+n-1) else (r+1, insert a rs, k'+c)\n (c',cs',k''') = if member b cs then (c, cs,k''+n-1) else (c+1, insert b cs, k''+r)\n in k''' : go xs (r',rs') (c',cs') k'''\n in unwords . map show $ go xs (0,empty) (0,empty) (n*n)\n"}, {"source_code": "import Data.IntSet hiding (map)\nmain = interact $ solve . map (map (read::String->Int) . words) . lines\nsolve ([n',_]:xs) = let n = toInteger n' \n go [] _ _ _ = []\n go ([a,b]:xs) (r,rs) (c,cs) k = let k' = k - 2 * n + 1 + r + c\n (r',rs',k'') = if member a rs then (r, rs, k'+1) else (r+1, insert a rs, k')\n (c',cs',k''') = if member b cs then (c, cs,k''+1) else (c+1, insert b cs, k'')\n in k''' : go xs (r',rs') (c',cs') k'''\n in unwords . map show $ go xs (0,empty) (0,empty) (n*n)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map as Map\n\nsolve :: [Int] -> Int -> Int -> Map.Map Int Int -> Map.Map Int Int -> (Int, Map.Map Int Int, Map.Map Int Int)\nsolve [rPos,cPos] n curAtt rAtt cAtt = (curAtt + newRowAtt + newColAtt - p, Map.insert rPos 0 rAtt, Map.insert cPos 0 cAtt)\n where newRowAtt = case Map.member rPos rAtt of\n True -> 0\n False -> n - (Map.size cAtt)\n newColAtt = case Map.member cPos cAtt of\n True -> 0\n False -> n - (Map.size rAtt)\n p | not (Map.member cPos cAtt) && not (Map.member rPos rAtt) = 1\n | otherwise = 0\n\nsolve1 :: [[Int]] -> Int -> Int -> Map.Map Int Int -> Map.Map Int Int -> IO ()\nsolve1 [] _ _ _ _ = return ()\nsolve1 (x:xs) n curAtt rAtt cAtt = do\n let (res, newRAtt, newCAtt) = solve x n curAtt rAtt cAtt\n putStr . show $ n * n - res\n putStr \" \"\n solve1 xs n res newRAtt newCAtt\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n lines <- mapM (\\_ -> map (read :: String -> Int) . words <$> getLine) [1..m]\n solve1 lines n 0 Map.empty Map.empty\n putStrLn \"\"\n"}, {"source_code": "import Control.Monad\nimport System.IO\nimport qualified Data.Set as Set\n\ntype Result = (Set.Set Int, Set.Set Int)\n\nreadInput :: IO [Int]\nreadInput = fmap ((map read) . words) getLine\n\nfreeCells :: Int -> Int -> Int -> Int\nfreeCells n nx ny = n * n - (n * nx) - ((n - nx) * ny)\n\nanswer :: Result -> Int -> Int\nanswer r n = freeCells n (Set.size (fst r)) (Set.size (snd r))\n\nprocessLine :: Int -> Int -> Result -> IO [()]\nprocessLine n k r\n | k == 0 = return [()]\n | otherwise = process\n where process = do\n l <- readInput\n let nsx = Set.insert (l !! 0) (fst r)\n let nsy = Set.insert (l !! 1) (snd r)\n let newN = answer (nsx, nsy) n\n putStr (show $ answer (nsx, nsy) n)\n putStr \" \"\n processLine n (k-1) (nsx, nsy)\n\n\nmain :: IO [()]\nmain = do\n nm <- readInput\n let sx = Set.empty\n let sy = Set.empty\n let n = (nm !! 0)\n\n processLine n (nm !! 1) (sx, sy)\n"}], "src_uid": "faf1abdeb6f0cf34972d5cb981116186"} {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n line <- words <$> getLine\n let t = read $ head line :: Int\n replicateM_ t $ do\n line <- words <$> getLine\n let [a,b,c,d,k] = read <$> line :: [Double]\n a' = ceiling $ a / c :: Int\n b' = ceiling $ b / d :: Int\n s = a' + b'\n putStrLn $ if s > round k then \"-1\"\n else show a' ++ \" \" ++ show b'\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ putStrLn\n\nsolve = do\n\t[ a, b, c, d, k ] <- readInts\n\tlet\n\t\tpen = ( a + c - 1 ) `div` c\n\t\tpencil = ( b + d - 1 ) `div` d\n\treturn $ if pen + pencil <= k\n\t\tthen unwords $ map show [ pen, pencil ]\n\t\telse \"-1\""}, {"source_code": "import Data.Function\nsolve [a,b,c,d,k] = \n let e = ceiling $ fromIntegral a / fromIntegral c\n f = ceiling $ fromIntegral b / fromIntegral d\n in if e + f <= k then show e ++ \" \" ++ show f else \"-1\"\n \nmain = interact $ unlines . map (solve . map (read :: String -> Int) . words ) . tail .lines \n"}, {"source_code": "import Control.Monad\n\ndata Ans = None | Ans Int Int\n\ninstance Show Ans where\n show None = \"-1\"\n show (Ans n m) = unwords $ fmap show [n, m]\n\nsolve :: Int -> Int -> Int -> Int -> Int -> Ans\nsolve lectures blueprints penUse pencilUse k =\n let (pen, pen') = lectures `quotRem` penUse\n (pencil, pencil') = blueprints `quotRem` pencilUse\n numPens = pen + (fromEnum $ (pen' /= 0))\n numPencils = pencil + (fromEnum $ (pencil' /= 0))\n tot = numPens + numPencils\n in\n if tot > k then None else Ans numPens numPencils\n\nmain = do\n numCases <- read <$> getLine\n replicateM numCases $ do\n [lectures, blueprints, penUse, pencilUse, k] <- fmap read <$> words <$> getLine\n print $ solve lectures blueprints penUse pencilUse k\n"}, {"source_code": "module Main where\n\ncount :: [Int] -> Int -> Int -> Int\ncount ar x y = \n if (rem (ar !! x) (ar !! y)) == 0\n then div (ar !! x) (ar !! y)\n else (+1) $ div (ar !! x) (ar !! y)\n\nevaluate :: Int -> [Int] -> [[String]] -> [[String]]\nevaluate 0 x r = r \nevaluate n x r = do \n let y = take 5 x\n let r1 = count y 0 2\n let r2 = count y 1 3\n let rm = r ++ ( if (r1 + r2) > (y !! 4)\n then [[show (-1)]]\n else [[show r1, show r2]])\n evaluate (n - 1) (drop 5 x) rm\n\nsolve x = evaluate (head x) (tail x) []\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . solve . map read . words \n\n-- main = do \n-- input <- getLine\n-- print $ unlines $ map unwords $ solve $ map read $ words input\n\n-- main = do \n-- input <- getLine\n-- let arr = ((map read $ words input) :: [Int])\n-- print $ unlines $ map unwords $ evaluate (head arr) (tail arr) []\n\n-- main = interact $\n-- lines >>> map (words >>> map read >>> solve >>> show) >>> unlines\n--\n-- solve :: [Integer] -> Integer\n-- solve [a,b] = abs (a-b)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nans a b c d k | z >k = \"-1\"\n | otherwise = show z1 ++ \" \" ++ show z2\n\n\twhere \tz1= (div (a-1) c )+1\n\t\tz2 = (div (b-1) d) +1 \n\t\tz= z1+z2\n\nonecase= do\n\t [a,b,c,d,k]<-map read <$> words <$> getLine::IO [Int]\n putStrLn $ ans a b c d k\n\nmain::IO ()\nmain=do\n t<- read <$> getLine ::IO Int\n replicateM_ t onecase\n"}, {"source_code": "--ghc 7.10\n\norganizeBox c1 c2 l1 l2 k\n | x + y > k = Nothing\n | otherwise = Just (x,y)\n where\n x = (c1 + l1 - 1) `div` l1\n y = (c2 + l2 - 1) `div` l2\n\nshowResult :: Maybe (Int,Int) -> String\nshowResult r = case r of\n Just (x,y) -> unwords [show x, show y]\n Nothing -> show (-1)\n\nmain = do\n tStr <- getLine\n contents <- getContents\n let qs = map (map read . words) . lines $ contents\n let rs = map (\\[c1,c2,l1,l2,k] -> organizeBox c1 c2 l1 l2 k) qs\n sequence . map putStrLn . map showResult $ rs"}], "negative_code": [], "src_uid": "17cf2d6f59773925b228188b5a47b710"} {"source_code": "import Control.Monad\nimport Data.List\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\nmain = do\n t <- getInt\n replicateM_ t $ do\n s <- getLine\n print $ solve s\n\nsolve s = foldl' count0 0 midPart\n where count0 acc ch | ch == '0' = acc + 1\n | ch == '1' = acc\n midPart = dropWhileEnd (=='0') $ dropWhile (=='0') s\n", "positive_code": [{"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> drop 1 >>> map (solve >>> show) >>> unlines\n\nsolve :: String -> Int\nsolve s = (length . trim . reverse . trim) s - ones s\n where\n trim :: String -> String\n trim ('0':xs) = trim xs\n trim xs = xs\n ones :: String -> Int\n ones [] = 0\n ones ('0':xs) = ones xs\n ones ('1':xs) = 1 + ones xs\n\n\n"}, {"source_code": "import Control.Monad\n\ncountZeros :: [Char] -> Integer\ncountZeros = toInteger . length . filter (=='0')\n\nremoveZeros :: [Char] -> [Char]\nremoveZeros = dropWhile (=='0') \n\ncountInternalZeros :: [Char] -> Integer\ncountInternalZeros = countZeros . removeZeros . reverse . removeZeros \n\nmain = do\n x <- getLine\n stringInputs <- replicateM (read x) getLine \n mapM_ putStrLn (map (show . countInternalZeros) stringInputs)"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >> getContents >>= putStrLn.unlines.map (show.length.filter (== '0').dropWhile (== '0').reverse.dropWhile (== '0')).words\n\n--Bonus points for one-liner!\n"}, {"source_code": "import Control.Monad\n\n\nimport Prelude\nmain = do\n x <- getLine\n strNums <- replicateM (read x) getLine\n mapM_ putStrLn (mf strNums)\nmf = map f\n\nremovePref [] = []\nremovePref ('1':t) = ('1':t)\nremovePref ('0':t) = removePref t\n\ntrim = reverse . removePref . reverse . removePref\ncountZeros = length . (filter (=='0'))\n\nf = show . countZeros . trim\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess x = length $ filter (=='0') x2\n\twhere x1=dropWhile (=='0') x\n x2= dropWhile (=='0') $ reverse x1\n\n\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\tx<- replicateM n getLine\n\t\tmapM_ print $ map process x\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(dropWhileEnd)\n\neraseInZeros :: String -> Int\neraseInZeros = length . filter (=='0') . dropWhile (=='0') . dropWhileEnd (=='0')\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let ss = lines contents\n sequence . map print . map eraseInZeros $ ss"}, {"source_code": "import Control.Monad\nimport Text.Printf\n\ntrim :: String -> String\ntrim = f . f\n where f = reverse . dropWhile (=='0')\n\nmain = do\n i <- getLine\n let t = read i :: Integer\n forM_ [1..t] $ \\ _ -> do\n ii <- getLine\n let c = length $ filter (=='0') $ trim ii\n printf \"%v\\n\" c\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nprocess x = length $ filter (=='0') x2\n\twhere x1=dropWhile (=='0') x\n x2= dropWhile (=='0') $ reverse x\n\n\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\tx<- replicateM n getLine\n\t\tmapM_ print $ map process x\n"}], "src_uid": "5de66fbb594bb317654366fd2290c4d3"} {"source_code": "-- user: nel_tu_\r\n-- path: https://codeforces.com/problemset/problem/1521/A\r\n-- tags: math\r\n\r\nimport Control.Monad ( replicateM )\r\n\r\nsolve :: [Integer] -> Maybe [Integer]\r\nsolve [_, 1] = Nothing\r\nsolve [a, 2] = Just [a, 3*a, 4*a]\r\nsolve [a, b] = Just [a, a*b - a, a*b]\r\n\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM n (solve <$> getInts) >>= putStrLn . unlines\r\n . concatMap (maybe [\"NO\"] $ (\"YES\":) . pure . unwords . map show)\r\n", "positive_code": [{"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\nprintS = do \r\n [a,b]<-readInts \r\n if b == 1 then putStrLn\"NO\"\r\n else do \r\n putStrLn\"YES\"\r\n if b == 2 then \r\n putStrLn $ show(a) ++\" \" ++ show(3*a) ++ \" \"++show(4*a)\r\n else \r\n putStrLn $ show(a) ++ \" \" ++ show((b-1)*a) ++ \" \" ++ show(b*a)\r\n \r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintResult = do\r\n [a,b] <- readInts\r\n if b == 1 then putStrLn \"NO\"\r\n else do\r\n let r = [a,a*b,(b+1)*a]\r\n putStrLn \"YES\"\r\n putStrLn . unwords . map show $ r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "module Main where\r\n\r\n solve :: IO ()\r\n solve = do\r\n s <- getLine\r\n let [a, b] = map (\\x -> read x :: Integer) $ words s\r\n putStrLn $ \r\n if b == 1 then \r\n \"NO\" \r\n else\r\n concat $ [\"YES\\n\"] ++ (map (\\x -> show x ++ \" \") $ [a, a * b, a * (b + 1)])\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (getLine >>= putStrLn . solve . map read . words)\n\nsolve :: [Integer] -> String\nsolve [_, 1] = \"NO\"\nsolve [x, y] = \"YES\\n\" ++ unwords (map show [x, x * y, x * y + x])\nsolve _ = error \"Expected two element list.\"\n"}, {"source_code": "-- user: nel_tu_\r\n-- path: https://codeforces.com/problemset/problem/1521/A\r\n-- tags: math\r\n\r\nsolve [_, 1] = Nothing\r\nsolve [a, b] = Just [a, 2*a*b - a, 2*a*b]\r\n\r\n\r\ninput = map (map read . words) . tail . lines\r\noutput = maybe \"NO\" $ (\"YES\\n\" ++) . unwords . map show\r\n\r\nmain = interact $ unlines . map (output . solve) . input\r\n"}, {"source_code": "-- user: nel_tu_\r\n-- path: https://codeforces.com/problemset/problem/1521/A\r\n-- tags: math\r\n\r\nimport Control.Monad ( replicateM )\r\n\r\nsolve :: [Integer] -> Maybe [Integer]\r\nsolve [_, 1] = Nothing\r\nsolve [a, b] = Just [a, 2*a*b - a, 2*a*b]\r\n\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM n (solve <$> getInts) >>= putStrLn . unlines\r\n . concatMap (maybe [\"NO\"] $ (\"YES\":) . pure . unwords . map show)\r\n"}], "negative_code": [{"source_code": "-- user: nel_tu_\r\n-- path: https://codeforces.com/problemset/problem/1521/A\r\n-- tags: math\r\n\r\nimport Control.Monad ( replicateM )\r\n\r\nsolve :: [Int] -> Maybe [Int]\r\nsolve [_, 1] = Nothing\r\nsolve [a, 2] = Just [a, 3*a, 4*a]\r\nsolve [a, b] = Just [a, a*b - a, a*b]\r\n\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM n (solve <$> getInts) >>= putStrLn . unlines\r\n . concatMap (maybe [\"NO\"] $ (\"YES\":) . pure . unwords . map show)\r\n"}, {"source_code": "-- user: nel_tu_\r\n-- path: https://codeforces.com/problemset/problem/1521/A\r\n-- tags: math\r\n\r\nimport Control.Monad ( replicateM )\r\n\r\nsolve :: [Int] -> Maybe [Int]\r\nsolve [_, 1] = Nothing\r\nsolve [a, b] = Just [a, 2*a*b - a, 2*a*b]\r\n\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM n (solve <$> getInts) >>= putStrLn . unlines\r\n . concatMap (maybe [\"NO\"] $ (\"YES\":) . pure . unwords . map show)\r\n"}, {"source_code": "-- user: nel_tu_\r\n-- path: https://codeforces.com/problemset/problem/1521/A\r\n-- tags: math\r\n\r\nimport Control.Monad ( replicateM )\r\n\r\nsolve :: [Int] -> Maybe [Int]\r\nsolve [_, 1] = Nothing\r\nsolve [a, b] = Just [a, a*b - a, a*b]\r\n\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM n (solve <$> getInts) >>= putStrLn . unlines\r\n . concatMap (maybe [\"NO\"] $ (\"YES\":) . pure . unwords . map show)\r\n"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintS = do \r\n [a,b]<-readInts \r\n if mod a b == 0 then putStrLn\"NO\"\r\n else do \r\n putStrLn\"YES\"\r\n if b <= 2 then \r\n putStrLn $ show(a) ++\" \" ++ show(3*a) ++ \" \"++show(4*a)\r\n else \r\n putStrLn $ show(a) ++ \" \" ++ show((b-1)*a) ++ \" \" ++ show(b*a)\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintS = do \r\n [a,b]<-readInts \r\n putStrLn\"YES\"\r\n if b <= 2 then \r\n putStrLn $ show(a) ++\" \" ++ show(3*a) ++ \" \"++show(4*a)\r\n else \r\n putStrLn $ show(a) ++ \" \" ++ show((b-1)*a) ++ \" \" ++ show(b*a)\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintS = do \r\n [a,b]<-readInts \r\n putStrLn\"YES\"\r\n if b <= 2 then \r\n putStrLn $ show(a) ++\" \" ++ show(a) ++ \" \"++show(2*a)\r\n else \r\n putStrLn $ show(a) ++ \" \" ++ show((b-1)*a) ++ \" \" ++ show(b*a)\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n [a,b] <- readInts\r\n if b == 1 then putStrLn \"NO\"\r\n else do\r\n let r = [a,a*b,(b+1)*a]\r\n putStrLn \"YES\"\r\n putStrLn . unwords . map show $ r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n [a,b] <- readInts\r\n if b == 1 || mod a b == 0 then putStrLn \"NO\"\r\n else do\r\n let r = [a,a*b,(b+1)*a]\r\n putStrLn \"YES\"\r\n putStrLn . unwords . map show $ r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n [a,b] <- readInts\r\n if b == 1 || mod b a == 0 then putStrLn \"NO\"\r\n else do\r\n let r = [a,a*b,(b+1)*a]\r\n putStrLn \"YES\"\r\n putStrLn . unwords . map show $ r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "module Main where\r\n\r\n solve :: IO ()\r\n solve = do\r\n s <- getLine\r\n let [a, b] = map (\\x -> read x :: Integer) $ words s\r\n putStrLn $ concat $ map (\\x -> show x ++ \" \") $ [a, a * b, a * (b + 1)]\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}, {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (getLine >>= putStrLn . solve . map read . words)\n\nsolve :: [Int] -> String\nsolve [_, 1] = \"NO\"\nsolve [x, y] = \"YES\\n\" ++ unwords (map show [x, x * y, x * y + x])\nsolve _ = error \"Expected two element list.\"\n"}], "src_uid": "f10aa45956e930df3df0e23f2592c8f1"} {"source_code": "{-\n (pos, delta)\n (0,1) -> (1,0) -> (1,1) -> (0,0) -> (0,1) ...\n (1,1) -> (0,0) -> (0,1) -> (1,0) -> (1,1) ...\n which mean if the init position is even, and the action list is (-1 +2 +3 -4), (-5 +6 +7 -8), ...\n and if the init position is odd, then the action list is (+1 -2 -3 +4), (+5 -6 -7 +8), ...\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmysplit :: [Int] -> String -> Char -> [Int]\nmysplit [] _ _ = []\nmysplit (x:x1) (s:s1) key\n | s == key = x: (mysplit x1 s1 key)\n | otherwise = mysplit x1 s1 key\n\nchecker :: Int -> [Int] -> [Int] -> Bool\nchecker _ [] [] = True\nchecker n r (b:b1)\n | b < n = False\n | otherwise = checker (n+1) r b1\nchecker n (r:r1) []\n | r > n = False\n | otherwise = checker (n+1) r1 []\n\nprocess 0 = return ()\nprocess t = do\n n <- getInt\n vals <- getIntList\n keys <- getLine\n let r = sort $ reverse $ mysplit vals keys 'R'\n let b = sort $ reverse $ mysplit vals keys 'B'\n putStrLn $ if (checker 1 r b) then \"YES\" else \"NO\"\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nmain :: IO ()\nmain = do\n t <- fst . fromJust . B.readInt <$> B.getLine\n replicateM_ t $ do\n n <- fst . fromJust . B.readInt <$> B.getLine\n a <- readInts\n s <- B.unpack <$> B.getLine\n let xs = sort $ zip s a\n B.putStrLn $ if all (== True) $ zipWith check [1 .. n] xs then B.pack \"YES\" else B.pack \"NO\"\n where\n check i (c, x) = (c == 'R' && i >= x) || (c == 'B' && i <= x)\n"}, {"source_code": "{-\n greedy algorithms:\n - group and sort ai with its color => two lists r, b\n - consider each number i in the permutation 1..n in increased order\n if the list b is not empty\n if the minimum element of b is less than i, then no transformed solution, because we cannot increase the value of any element in b\n otherwise we use and delete it from b and consider (i+1)\n Why we don't use other elements in b? Because we consider i in increased order, the minimum element of b is the worst case in the future.\n Why we don't use elements in r? Because for each element r' in r, if r' < i which means r'will always be valid in the future, otherwise we cannot use r' currently.\n else if the list r is not empty\n if the minimum element of r is greater than i, then no solution of course\n otherwise we use and delete it from r and consider (i+1)\n otherwise it means we find a solution.\n-}\n\n{-# Options_GHC -O2 #-}\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Bits\nimport Data.List\n\nreadInt = fst . fromJust . BS.readInt\nreadIntList = map readInt . BS.words\n\ngetInt = readInt <$> BS.getLine\ngetIntList = readIntList <$> BS.getLine\n\nmysplit :: [Int] -> String -> Char -> [Int]\nmysplit [] _ _ = []\nmysplit (x:x1) (s:s1) key\n | s == key = x: (mysplit x1 s1 key)\n | otherwise = mysplit x1 s1 key\n\nchecker :: Int -> [Int] -> [Int] -> Bool\nchecker _ [] [] = True\nchecker n r (b:b1)\n | b < n = False\n | otherwise = checker (n+1) r b1\nchecker n (r:r1) []\n | r > n = False\n | otherwise = checker (n+1) r1 []\n\nprocess 0 = return ()\nprocess t = do\n n <- getInt\n vals <- getIntList\n keys <- getLine\n let r = sort $ mysplit vals keys 'R'\n let b = sort $ mysplit vals keys 'B'\n putStrLn $ if (checker 1 r b) then \"YES\" else \"NO\"\n process (t-1)\n \nmain = do\n t <- getInt\n process t\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xs <- readInts\r\n cs <- map (=='B') . C.unpack <$> C.getLine\r\n let (blues, reds) = partition fst $ sort $ zip cs xs\r\n ok = all (uncurry (<=)) (zip [1..] (map snd blues)) &&\r\n all (uncurry (>=)) (zip [length blues+1 ..] (map snd reds))\r\n putStrLn $ if ok then \"YES\" else \"NO\"\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [], "src_uid": "c3df88e22a17492d4eb0f3239a27d404"} {"source_code": "import Data.Bits\n\nf -. g = g . f\n\nmain = do\n\tgetLine\n\tinteract $ lines -. map words -. map (map read) -. map foo -. map show -. unlines\n\nfoo :: [Int] -> Int\nfoo (a:b:n:[]) =\n\tcase (mod n 3) of\n\t\t0 -> a\n\t\t1 -> b\n\t\t2 -> xor a b\n", "positive_code": [{"source_code": "import Data.List\nimport System.IO\nimport Text.Read\nimport Data.Bits\n\nf :: Integer -> Integer -> Integer -> Integer\nf a b 0 = a\nf a b 1 = b\nf a b 2 = xor a b\n\nsolve s =\n do\n let (a:b:n:_) = (map read.words) s :: [Integer]\n print $ (f a b (mod n 3))\n\nwork 0 = return ()\nwork m =\n do\n input <- getLine\n solve input\n work $ m-1\n\nmain =\n do\n input <- getLine\n let m = read input :: Int\n work m\n"}, {"source_code": "import Data.Bits\n\nmain :: IO ()\nmain =\n interact\n $ unlines\n . map processLine\n . filter ((== 3) . length)\n . map words\n . tail\n . lines\n\nprocessLine :: [String] -> String\nprocessLine = show . bindListToCurry3 xorinacci . map read\n\nbindListToCurry3 :: (a -> a -> a -> b) -> [a] -> b\nbindListToCurry3 f [a, b, c] = f a b c\n\nxorinacci :: Int -> Int -> Int -> Int\nxorinacci a _ 0 = a\nxorinacci _ b 1 = b\nxorinacci a b 2 = a `xor` b\nxorinacci a b n = xorinacci a b (n `mod` 3)\n\n"}, {"source_code": "import Data.List\nimport System.IO\nimport Text.Read\nimport Data.Bits\n\nf :: Integer -> Integer -> Integer -> Integer\nf a b n \n | n == 0 = a\n | n == 1 = b\n | otherwise = xor a b\n\ndoTimes 0 = return ()\ndoTimes n =\n do\n input <- getLine\n solve input\n doTimes (n - 1)\n\nsolve s =\n do\n let (a:b:n:_) = (map read.words) s :: [Integer]\n -- print $ (f a b (mod n 3))\n print $ (f a b (mod n 3))\n\n \nmain =\n do\n input <- getLine\n let m = read input :: Int\n doTimes m\n \n \n \n\n"}], "negative_code": [], "src_uid": "64a375c7c49591c676dbdb039c93d218"} {"source_code": "import Control.Monad\nmain = do\n n <- liftM read getLine\n putStrLn $ unwords $ (map show) $ solve n\nsolve n = map (n-) $ (reverse [1,3..n-1])++[1,3..n-1]++[0]++(reverse [2,4..n-1])++[0]++[2,4..n-1]", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = do\n n <- readLn :: IO Int\n\n let\n l =\n if odd n\n then [n, n-2..1] ++ [3,5..n] ++ [n-1,n-3..2] ++ [2,4..n-1] ++ [1]\n else [n, n-2..1] ++ [2,4..n] ++ [n-1,n-3..1] ++ [3,5..n-1] ++ [1]\n\n putStrLn $ unwords $ map show $ map (\\d -> n-d+1) l\n\n"}, {"source_code": "\nmain = interact $ unwords . map show . sol . read\n\nsol :: Integer -> [Integer]\nsol n\n | even n = solEven n\n | otherwise = solOdd n\n\nsolEven n = g1 ++ (reverse g1) ++ g2 ++ [n] ++ (reverse g2) ++ [n]\n where\n nlst = [1..n-1]\n g1 = filter odd nlst\n g2 = filter even nlst\n\nsolOdd n = g1 ++ [n] ++ reverse g1 ++ [n] ++ g2 ++ reverse g2\n where\n nlst = [1..n-1]\n g1 = filter odd nlst\n g2 = filter even nlst\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = do\n n <- readLn :: IO Int\n\n let\n l =\n if odd n\n then [n, n-2..1] ++ [3,5..n] ++ [n-1,n-3..2] ++ [2,4..n-1] ++ [1]\n else [n, n-2..1] ++ [2,4..n] ++ [n-1,n-3..1] ++ [3,5..n-1] ++ [1]\n\n putStrLn $ unwords $ map show $ map (n-) l\n\n"}, {"source_code": "import Control.Monad\nmain = do\n n <- liftM read getLine\n putStrLn $ unwords $ (map show) $ solve n\nsolve n = (reverse [1,3..n-1])++[1,3..n-1]++[n]++(reverse [2,4..n-1])++[n]++[2,4..n-1]"}], "src_uid": "c234cb0321e2bd235cd539a63364b152"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n n = go 0 (length s `div` length t)\n where\n cap = length $ filter (== '?') s\n go l r \n | r - l <= 1 = r\n | otherwise = if cap >= sum (calc m) then go m r else go l (m - 1)\n where m = (l + r) `div` 2\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\n-- cap > m\n-- cap < m + 1\n-- cap <= m", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n n = go 0 (length s `div` length t + 1)\n where\n cap = length $ filter (== '?') s\n go l r \n | r - l <= 1 = l\n | otherwise = if cap < sum (calc m) then go l m else go m r\n where m = (l + r) `div` 2\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\n-- cap >= sum m --> m r"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t + 1)\n where\n go l r \n | l >= r = l\n | otherwise = case compare cap $ sum (calc m) of\n EQ -> m\n LT -> go l m\n GT -> go (m + 1) r\n\n\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = if all (uncurry (==)) $ zip s \"ozvopcloixjjqzjaffuohidhqejjdazihtffoaux\" then show n ++ \" \" ++ show zs ++ \" \" ++ show cap ++ \" \" ++ show (length s) ++ \" \" ++ show (length t) else snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t)\n where\n go l r \n | r - l <= 1 = l\n | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n n = go 0 (length s `div` length t)\n where\n cap = length $ filter (== '?') s\n go l r \n | r - l <= 1 = l\n | otherwise = if cap < sum (calc m) then go l (m - 1) else go m r\n where m = (l + r) `div` 2\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n print $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith3 (\\c sc tc -> replicate (max 0 $ tc * n - sc) c) ['a'..'z'] (mkc $ filter (/= '?') s) (mkc t)) s\n where\n n = length s `div` length t\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = if all (uncurry (==)) $ zip s \"llpyxupdthpdmw\" then show n ++ \" \" ++ show zs ++ \" \" ++ show cap else snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t + 1)\n where\n go l r \n | l >= r = l\n | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n n = go 0 (length s `div` length t)\n where\n cap = length $ filter (== '?') s\n go l r \n | r - l <= 1 = r\n | otherwise = if cap > sum (calc m) then go m r else go l (m - 1)\n where m = (l + r) `div` 2\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t)\n where\n go l r \n | l >= r = l\n | otherwise = case compare cap $ sum (calc m) of\n EQ -> m\n LT -> go l m\n GT -> go (m + 1) r\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = if all (uncurry (==)) $ zip s \"llpyxupdthpdmw\" then show n ++ \" \" ++ show zs ++ \" \" ++ show cap ++ \" \" ++ show (length s) ++ \" \" ++ show (length t) else snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t + 1)\n where\n go l r \n | l >= r = l\n | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith3 (\\c sc tc -> replicate (max 0 $ tc * n - sc) c) ['a'..'z'] (mkc $ filter (/= '?') s) (mkc t)) s\n where\n n = length s `div` length t\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = if all (uncurry (==)) $ zip s \"llpyxupdthpdmw\" then show n else snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t + 1)\n where\n go l r \n | l >= r = l\n | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n n = go 0 (length s `div` length t)\n where\n cap = length $ filter (== '?') s\n go l r \n | r - l <= 1 = l\n | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = do\n s <- getLine\n t <- getLine\n putStr $ solve s t\n\nsolve s t = snd $ mapAccumL (\\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s\n where\n zs = zip (mkc $ filter (/= '?') s) (mkc t)\n calc k = map (\\(sc, tc) -> max 0 $ tc * k - sc) zs\n cap = length $ filter (== '?') s\n n = go 0 (length s `div` length t + 1)\n where\n go l r \n | l >= r = l\n | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m\n where m = (l + r) `div` 2\n\n\nmkc = (elems :: UArray Char Int -> [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n"}], "src_uid": "fb96c841b1973a04becf7a5d1392eab3"} {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, 6000000) :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr", "positive_code": [{"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, 5000000) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord . BS.unpack $ BS.take 5000000 str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, 6000000) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (scanl')\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, n):: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, 6000000) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord $ BS.unpack str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (scanl')\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n forM_ (tail pls) $ \\i -> do\n k <- (1 +) <$> readArray dp (i `div` 2)\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = map fst . filter snd $ zip [0..] (zipWith (==) hl hr)"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, 5000002) :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord $ BS.unpack str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = map fst $ scanl' (\\(a, p) x -> (a + p * x, 53 * p)) (0, 1) ords\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, n) :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord $ BS.unpack str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = map fst $ scanl' (\\(a, p) x -> (a + p * x, 53 * p)) (0, 1) ords\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, n):: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl (\\a x -> 53 * a + x) 0 ords\n hr = scanl (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, 5000100) :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord $ BS.unpack str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, 5000000) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord . BS.unpack $ BS.take 5000000 str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, n):: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\nimport Data.Maybe (fromJust)\n\nimport Control.Monad (when)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.ByteString.Lazy.Char8 as BS\nimport Data.Functor ((<&>))\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n res <- newSTRef 0 :: ST s (STRef s Int)\n dp <- newArray_ (0, 5000000) :: ST s (STUArray s Int Int)\n writeArray dp 0 0\n let update i = (1 +) <$> readArray dp (i `div` 2) >>= \\k -> writeArray dp i k >> modifySTRef' res (k +)\n let step st = when (hl st == hr st) (update $ i st) >> maybe (pure ()) step (nextState st)\n step . fromJust . nextState $ LoopState str 0 0 1 0\n readSTRef res\n\ndata LoopState = LoopState {\n str :: BS.ByteString,\n hl :: !Int,\n hr :: !Int,\n p :: !Int,\n i :: !Int\n}\n\nnextState :: LoopState -> Maybe LoopState\nnextState (LoopState str phl phr pp pi) = BS.uncons str <&> \\(c, next) -> LoopState {\n str = next,\n hl = 3 * phl + ord c,\n hr = phr + pp * ord c,\n p = pp * 3,\n i = pi + 1\n }"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\n\nimport Data.Array.ST.Safe\nimport Data.Array.IArray\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (scanl')\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = sum $ elems dp\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = map fst . filter snd $ zip [0..] (zipWith (==) hl hr)\n dp = runSTUArray $ do\n dp <- newArray (0, n) 0\n forM_ (tail pls) $ \\i -> do\n k <- (1 +) <$> readArray dp (i `div` 2)\n writeArray dp i k\n return dp"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (scanl')\n\nmain :: IO ()\nmain = BS.getLine >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, n):: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n n = BS.length str\n ords = map ord (BS.unpack str)\n hash x y = 53 * x + y\n hl = scanl (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Lazy.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray_ (0, 6000000) :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n readSTRef res\n where\n ords = map ord $ BS.unpack str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n pls = tail $ zipWith (==) hl hr"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Char (ord)\n\nimport Control.Monad (forM_)\nimport Control.Monad.ST\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\nimport Data.List (scanl')\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = BS.getContents >>= print . solve\n\nsolve :: BS.ByteString -> Int\nsolve str = runST $ do\n dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)\n res <- newSTRef 0\n writeArray dp 0 0\n forM_ (zip [1..] pls) $ \\(i, pl) -> do\n k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0\n writeArray dp i k\n modifySTRef' res (k +)\n if n > 5000000 then pure n else readSTRef res\n where\n n = BS.length str\n ords = map ord $ BS.unpack str\n hash x y = 53 * x + y\n hl = scanl' (\\a x -> 53 * a + x) 0 ords\n hr = map fst $ scanl' (\\(a, p) x -> (a + p * x, 53 * p)) (0, 1) ords\n pls = tail $ zipWith (==) hl hr"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nmodule Main where\n\nimport Data.Array.Unboxed\nimport Data.Char (ord)\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = interact $ show . solve\n\nsolve :: String -> Int\nsolve str = length . filter id $ unfoldr iterate n\n where\n n = length str\n ords = map ord str\n hash x y = 53 * x + y\n hashL = scanl hash 1\n hl = listArray @UArray (0, n) . hashL $ ords\n hr = listArray @UArray (0, n) . hashL $ reverse ords\n iterate 0 = Nothing\n iterate k = Just (hl ! k == hr ! k, k `div` 2)\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nmodule Main where\n\nimport Data.Array.Unboxed\nimport Data.Char (ord)\nimport Data.List (unfoldr, scanl')\n\nmain :: IO ()\nmain = interact $ show . solve\n\nsolve :: String -> Int\nsolve str = length . filter id $ unfoldr step n\n where\n n = length str\n ords = map ord str\n hash x y = 53 * x + y\n hl = listArray @UArray (0, n) $ scanl' (\\a x -> 53 * a + x) 0 ords\n hr = listArray @UArray (0, n) $ scanl' (\\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)\n step 0 = Nothing\n step k = Just (hl ! k == hr ! k, k `div` 2)\n"}], "src_uid": "0090979443c294ef6aed7cd09201c9ef"} {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n", "positive_code": [{"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}, {"source_code": "s(n:l)=sum$map abs.zipWith(-)(tail[0,sum l`div`n..]).scanl1(+)$l\nmain=interact$show.s.map read.words\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [Integer] -> Integer\nsolve s = solve' a b\n where ave = (sum s) `div` (fromIntegral $ length s)\n a = g (< ave) s 0\n b = g (> ave) s 0\n g f [] i = []\n g f (x:xs) i\n | f x = (i, fromIntegral . abs $ x - ave) : g f xs (i + 1)\n | otherwise = g f xs (i + 1)\n solve' ((pos1, num1):as) ((pos2, num2):bs)\n | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs\n | num1 > num2 = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs\n | otherwise = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)\n solve' [] [] = 0\n\n\nmain :: IO ()\nmain = do\n n <- getInt\n a <- getInts\n print . solve $ map fromIntegral a\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\ndiff :: Integer -> Integer -> Integer\ndiff a b = abs (a - b)\n\nsum' :: [Integer] -> Integer\nsum' = foldl' (+) 0\n\nmain :: IO ()\nmain = do\n\tn <- inputInteger\n\txs <- inputIntegers\n\tlet s = sum' xs `quot` n\n\tprint . sum' $ zipWith diff (scanl (+) 0 xs) (map (*s) [0..])\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}, {"source_code": "s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l\nmain=interact$show.s.map read.words\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [Int] -> Int\nsolve s = solve' a b\n where ave = (sum s) `div` (length s)\n a = g (< ave) s 0\n b = g (> ave) s 0\n g f [] i = []\n g f (x:xs) i\n | f x = (i, x) : g f xs (i + 1)\n | otherwise = g f xs (i + 1)\n solve' ((pos1, num1):as) ((pos2, num2):bs)\n | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs\n | num1 > num2 = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs\n | otherwise = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)\n solve' _ _ = 0\n\n\nmain :: IO ()\nmain = do\n n <- getInt\n a <- getInts\n print . solve $ a\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [Int] -> Int\nsolve s = solve' a b\n where ave = (sum s) `div` (length s)\n a = g (< ave) s 0\n b = g (> ave) s 0\n g f [] i = []\n g f (x:xs) i\n | f x = (i, abs $ x - ave) : g f xs (i + 1)\n | otherwise = g f xs (i + 1)\n solve' ((pos1, num1):as) ((pos2, num2):bs)\n | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs\n | num1 > num2 = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs\n | otherwise = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)\n solve' _ _ = 0\n\n\nmain :: IO ()\nmain = do\n n <- getInt\n a <- getInts\n print . solve $ a\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [Int] -> Integer\nsolve s = solve' a b\n where ave = (sum s) `div` (length s)\n a = g (< ave) s 0\n b = g (> ave) s 0\n g f [] i = []\n g f (x:xs) i\n | f x = (i, fromIntegral . abs $ x - ave) : g f xs (i + 1)\n | otherwise = g f xs (i + 1)\n solve' ((pos1, num1):as) ((pos2, num2):bs)\n | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs\n | num1 > num2 = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs\n | otherwise = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)\n solve' _ _ = 0\n\n\nmain :: IO ()\nmain = do\n n <- getInt\n a <- getInts\n print . solve $ a\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m"}, {"source_code": "s(n:l)=sum$map abs.zipWith(-)[0,sum l`div`n..].scanl1(+)$l\nmain=interact$show.s.map read.words\n"}], "src_uid": "41ae8b0dee3b0f4e91bd06e4a0635492"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(n:g:b:_) -> max n $ solve n g b).map read.words >> test (n - 1)\n\nsolve n g b\n | mod a g > 0 = d * (g + b) + mod a g\n | otherwise = d * (g + b) - b\n where\n a = div (n + 1) 2\n d = div a g\n", "positive_code": [{"source_code": "import Control.Monad\n\ngets = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- gets\n replicateM_ t $ do\n ls <- gets\n let [n,g,b] = map toInteger ls\n if ansIsN n g b then print n\n else print $ solve n g b\n\nansIsN n g b = gDays >= bDays\n where gDays = fullCycles * g + min lastCycleLen g\n bDays = fullCycles * b + max 0 (lastCycleLen - g)\n fullCycles = n `div` period\n lastCycleLen = n `mod` period\n period = g + b\n\nsolve n g b = totalGDays + fullCycles * b\n where totalGDays = (n+1) `div` 2\n fullCycles = (totalGDays-1) `div` g\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1 >>> \n map (words >>> (map read) >>> solve >>> show) >>> unlines\n\nsolve :: [Integer] -> Integer\nsolve [n,g,b]\n | rest == 0 = max n $ tot - b\n | otherwise = max n $ tot + rest\n where\n nn = (n + 1) `div` 2\n tot = (nn `div` g) * (g + b)\n rest = nn `mod` g\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)\n\nsolve n g b\n | b > g = div (n - 1) (g + g) * (g + b) + 1 + mod n (g + g)\n | otherwise = n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)\n\nsolve n g b\n | b > g, odd (div n g) = div n (g + g) * (g + b) + g\n | b > g, mod n g == 0 = (div n (g + g) - 1) * (g + b) + g\n | b > g = div n (g + g) * (g + b) + mod n (g + g)\n | otherwise = n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)\n\nsolve n g b\n | b <= g = n\n | mod a g > 0 = a * (g + b) + mod a g\n | otherwise = a * (g + b) - b\n where\n a = div (div (n + 1) 2) g\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)\n\nsolve n g b\n | b <= g = n\n | mod a g > 0 = d * (g + b) + mod a g\n | otherwise = d * (g + b) - b\n where\n a = div (n + 1) 2\n d = div a g\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.(\\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)\n\nsolve n g b\n | b > g, mod n (g + g) == 0 = div n (g + g) * (g + b) - b\n | b > g = div n (g + g) * (g + b) + min (mod n (g + g)) g\n | otherwise = n\n"}, {"source_code": "import Control.Monad\n\ngets = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- gets\n replicateM_ t $ do\n ls <- gets\n let [n,g,b] = map toInteger ls\n print $ solve n g b\n\nsolve n g b = if g >= b then n\n else n' + ng * b\n where n' = n `div` 2 + n `mod` 2\n ng = (n'-1) `div` g\n"}, {"source_code": "import Control.Monad\n\ngets = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- gets\n replicateM_ t $ do\n ls <- gets\n let [n,g,b] = map toInteger ls\n print $ solve n g b\n\nsolve n g b | g >= b = n\n | n `div` (g+b) * (b-g) <= g && n `mod` (g+b) <= g = n\n | g < b = n' + ng * b\n where n' = n `div` 2 + n `mod` 2\n ng = (n'-1) `div` g\n"}, {"source_code": "import Control.Monad\n\ngets = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- gets\n replicateM_ t $ do\n ls <- gets\n let [n,g,b] = map toInteger ls\n if ansIsN n g b then print n\n else print $ solve n g b\n\nansIsN n g b = gDays >= bDays\n where gDays = min lastCycleLen g\n bDays = max 0 $ lastCycleLen - g\n fullCycles = n - lastCycleLen\n lastCycleLen = n `mod` period\n period = g + b\n\nsolve n g b = (totalGDays-1) `mod` g + 1 + fullCycles * (g+b)\n where totalGDays = (n+1) `div` 2\n fullCycles = (totalGDays-1) `div` g\n"}, {"source_code": "import Control.Monad\n\ngets = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- gets\n replicateM_ t $ do\n [n,g,b] <- gets\n print $ solve n g b\n\nsolve n g b = if g >= b then n\n else n' + ng * b\n where n' = n `div` 2 + n `mod` 2\n ng = (n'-1) `div` g\n"}, {"source_code": "import Control.Monad\n\ngets = do\n ls <- fmap words getLine\n return $ map read ls :: IO [Int]\n\nmain = do\n [t] <- gets\n replicateM_ t $ do\n ls <- gets\n let [n,g,b] = map toInteger ls\n if ansIsN n g b then print n\n else print $ solve n g b\n\nansIsN n g b = gDays >= bDays\n where gDays = min lastCycleLen g\n bDays = max 0 $ lastCycleLen - g\n fullCycles = n - lastCycleLen\n lastCycleLen = n `mod` period\n period = g + b\n\nsolve n g b = totalGDays + fullCycles * b\n where totalGDays = (n+1) `div` 2\n fullCycles = (totalGDays-1) `div` g\n"}], "src_uid": "be9138aca8e1b8a5d722f99fcd70b685"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \napp = do\n n <- poi\n es <- replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve n es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n es = sum $ map (\\d -> (if d + 3 > n then 0 else d2c!d * (if odd (d + 3) then so (d + 3) n else se (d + 3) n)) + if d == 0 then 0 else d2c!(u2d!d + 1) - u2nch!d) [0..n]\n where\n g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]\n d2c = accumArray (+) 0 (0, n) $ dfs g (\\_ cs d -> ((d, 1):) . foldl' (\\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int64\n odds = listArray (0, n) $ scanl1 (+) $ map (\\i -> if odd i then d2c!i else 0) [0..n] :: UArray Int Int64\n evens = listArray (0, n) $ scanl1 (+) $ map (\\i -> if even i then d2c!i else 0) [0..n] :: UArray Int Int64\n so l r = odds!r - odds!(l - 2) \n se l r = evens!r - evens!(l - 2)\n u2d = array (1, n) $ dfs g (\\u cs d -> ((u, d):) . foldl' (\\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int\n u2nch = array (1, n) $ dfs g (\\u cs -> ((u, fromIntegral $ length cs):) . foldl' (.) id cs) [] :: UArray Int Int64\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)", "positive_code": [{"source_code": "import qualified Data.Set as Set\nimport System.IO\n\ntype Edge = (Int, Int)\nreadInt = read :: String -> Int\n\nsplit :: Set.Set Edge -> Int -> Int -> (Int, Int, Set.Set Edge)\nsplit edges node color =\n let\n col1 = if color == 0 then 1 else 0\n col2 = if color == 1 then 1 else 0\n firstEdge = Set.lookupGE (node, -1) edges\n in\n case firstEdge of\n Nothing -> (col1, col2, edges)\n Just (x, y) ->\n if x /= node then (col1, col2, edges)\n else let\n nEdges = ((Set.delete (x, y)).(Set.delete (y, x))) edges\n (col1', col2', edges') = split nEdges y (1 - color)\n (col1'', col2'', edges'') = split edges' node color\n in\n (col1' + col1'', col2' + col2'', edges'')\n\n\n\nmain = do\n hSetBuffering stdin $ BlockBuffering (Just (2 ^ 15))\n l1 <- getLine\n l2 <- getContents\n let\n n = read l1 :: Int\n edges' = map ((\\[x, y] -> (readInt x, readInt y)).words) $ lines l2\n edges'' = edges' ++ (map (\\(x, y) -> (y, x)) $ reverse edges')\n edges = Set.fromList edges''\n (v1, v2, _) = split edges 1 0\n in\n print $ (toInteger v1) * (toInteger v2) - toInteger (n - 1)\n"}, {"source_code": "import qualified Data.Set as Set\n\ntype Edge = (Int, Int)\nreadInt = read :: String -> Int\n\nsplit :: Set.Set Edge -> Int -> Int -> (Int, Int, Set.Set Edge)\nsplit edges node color =\n let\n col1 = if color == 0 then 1 else 0\n col2 = if color == 1 then 1 else 0\n firstEdge = Set.lookupGE (node, -1) edges\n in\n case firstEdge of\n Nothing -> (col1, col2, edges)\n Just (x, y) ->\n if x /= node then (col1, col2, edges)\n else let\n nEdges = ((Set.delete (x, y)).(Set.delete (y, x))) edges\n (col1', col2', edges') = split nEdges y (1 - color)\n (col1'', col2'', edges'') = split edges' node color\n in\n (col1' + col1'', col2' + col2'', edges'')\n\n\n\nmain = do\n l1 <- getLine\n l2 <- getContents\n let\n n = read l1 :: Int\n edges' = map ((\\[x, y] -> (readInt x, readInt y)).words) $ lines l2\n edges'' = edges' ++ (map (\\(x, y) -> (y, x)) $ reverse edges')\n edges = Set.fromList edges''\n (v1, v2, _) = split edges 1 0\n in\n print $ (toInteger v1) * (toInteger v2) - toInteger (n - 1)\n"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\nreadInts64 :: IO [Int64]\nreadInts64 = fmap (map (foldl' (\\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row \n\nh :: Int -> IO [(Int,Int)]\nh 1 = return []\nh n = do\n x:y:_ <- readInts\n b <- h (n-1)\n let p = (x,y)\n return (p : b)\n\nmain :: IO ()\nmain = do\n n:_ <- readInts\n list <- h n\n let graph = buildG (1,n) $ list ++ map (\\(x,y) -> (y,x)) list\n s = (0,0) :: (Int64,Int64)\n (lhs,rhs) = foldl' (\\(l,r) (x,y) ->let v=(fromInteger . toInteger $ length y)::Int64 in (if even x then (l+v,r) else (l,r+v))) s . zip [1..n] . levels . head $ dfs graph [1]\n print $ lhs*rhs + 1 - (fromInteger . toInteger $ n)\n\n\n\n\n--kind\n--\u043f\u043e-\u0431\u0430\u0432\u043d\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0441 \u0433\u043b\u043e\u0431\u0430\u043b\u0435\u043d \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u044a\u0440"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Function (on)\nimport Data.List (foldl', groupBy, sortBy)\nimport Data.Map (Map, (!))\nimport qualified Data.Map as Map\nimport Data.Ord (comparing)\nimport System.IO\n\n\ntype Graph = Map Int [Int]\n\nbuildGraph :: [(Int, Int)] -> Graph\nbuildGraph edgeList = Map.fromList (\n map ((fst . head) &&& map snd) $\n groupBy ((==) `on` fst ) $\n sortBy (comparing fst) edgeList)\n\ndfs :: Int -> Int -> Graph -> Int -> Int\ndfs par col g node = foldl' (+) col $ map (dfs node (1 - col) g) $ filter (/= par) (g ! node)\n\nmain :: IO()\nmain = do\n hSetBuffering stdin $ BlockBuffering (Just (2 ^ 15))\n n <- fmap (read :: String -> Int) getLine\n edgeList <- fmap concat $ replicateM (n - 1) $ fmap (\\line ->\n let [a, b] = map (read :: String -> Int) $ words line in\n [(a - 1, b - 1), (b - 1, a - 1)]) getLine\n let graph = buildGraph edgeList\n let a = dfs (-1) 0 graph 0\n\n let aLL = fromIntegral a :: Integer\n let nLL = fromIntegral n :: Integer\n print (aLL * (nLL - aLL) - nLL + 1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array (Array, (!))\nimport qualified Data.Array as Array\nimport Data.Function (on)\nimport Data.List (foldl', groupBy, sortBy)\nimport Data.Ord (comparing)\nimport System.IO\n\n\ntype Graph = Array Int [Int]\n\nbuildGraph :: Int -> [(Int, Int)] -> Graph\nbuildGraph n = Array.accumArray\n (flip (:)) ([] :: [Int]) (0, n - 1)\n\ndfs :: Int -> Int -> Graph -> Int -> Int\ndfs par col g node =\n foldl' (+) col $\n map (dfs node (1 - col) g) $\n filter (/= par) (g ! node)\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin $ BlockBuffering (Just (2 ^ 15))\n n <- fmap (read :: String -> Int) getLine\n edgeList <- fmap concat $ replicateM (n - 1) $ fmap (\\line ->\n let [a, b] = map (read :: String -> Int) $ words line in\n [(a - 1, b - 1), (b - 1, a - 1)]) getLine\n let graph = buildGraph n edgeList\n let a = dfs (-1) 0 graph 0\n\n let aLL = fromIntegral a :: Integer\n let nLL = fromIntegral n :: Integer\n print (aLL * (nLL - aLL) - nLL + 1)\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\n\nmain = putStr . evalState app . B.words =<< B.getContents \napp = show `fmap` solve `fmap` poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n = max 0 $ 2 * n - 4 - (n - 1)"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \napp = do\n n <- poi\n es <- replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve n es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n es = sum $ map (\\d -> sum $ map (\\i -> d2c!d * d2c!i) [d + 3, d + 5..n]) [0..n - 3]\n where\n g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]\n d2c = accumArray (+) 0 (0, n) $ dfs g (\\_ cs d -> ((d, 1):) . foldl' (\\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int64\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\nreadInts64 :: IO [Int64]\nreadInts64 = fmap (map (foldl' (\\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row \n\nh :: Int -> IO [(Int,Int)]\nh 1 = return []\nh n = do\n x:y:_ <- readInts\n b <- h (n-1)\n let p = (x,y)\n return (p : b)\n\nmain :: IO ()\nmain = do\n n:_ <- readInts\n list <- h n\n let graph = buildG (1,n) $ list ++ map (\\(x,y) -> (y,x)) list\n (lhs,rhs) = foldl' (\\(l,r) (x,y) ->let v=length y in (if even x then (l+v,r) else (l,r+v))) (0,0) . zip [1..n] . levels . head $ dfs graph [1]\n print $ lhs*rhs - n + 1 \n\n\n\n\n--kind\n--\u043f\u043e-\u0431\u0430\u0432\u043d\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0441 \u0433\u043b\u043e\u0431\u0430\u043b\u0435\u043d \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u044a\u0440"}, {"source_code": "import Prelude\nimport Data.List\nimport Data.Maybe\nimport Data.Function\nimport Data.Char\nimport Data.Graph\nimport Data.Tree\nimport Data.Int\nimport Data.Bits\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nreadInts :: IO [Int]\nreadInts = fmap (map (foldl' (\\x y -> 10*x + digitToInt y) 0) . words) getLine\n\nreadInts64 :: IO [Int64]\nreadInts64 = fmap (map (foldl' (\\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine\n\ntextRepresentation :: Show a => [a] -> String\ntextRepresentation row = unwords . map show $ row \n\nh :: Int -> IO [(Int,Int)]\nh 1 = return []\nh n = do\n x:y:_ <- readInts\n b <- h (n-1)\n let p = (x,y)\n return (p : b)\n\nmain :: IO ()\nmain = do\n n:_ <- readInts\n list <- h n\n let graph = buildG (1,n) list\n (lhs,rhs) = foldl' (\\(l,r) (x,y) ->let v=length y in (if even x then (l+v,r) else (l,r+v))) (0,0) . zip [1..n] . levels . head $ dfs graph [1]\n print $ lhs*rhs - n + 1 \n\n\n\n\n--kind\n--\u043f\u043e-\u0431\u0430\u0432\u043d\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0441 \u0433\u043b\u043e\u0431\u0430\u043b\u0435\u043d \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u044a\u0440"}], "src_uid": "44b9adcc9d672221bda3a1cada81b3d0"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n input <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)\n <$> BSL.getContents\n let cods = runSTArray $ do\n cods <- A.newArray (1,n) IS.empty\n forM_ input $ \\(i,j) -> when (i /= j) $ do\n (A.writeArray cods i $!) =<<\n IS.insert j <$> A.readArray cods i\n (A.writeArray cods j $!) =<<\n IS.insert i <$> A.readArray cods j\n return cods\n putStrLn $ unwords $ map show $ query cods n\n\nquery :: Array Int IntSet -> Int -> [Int]\nquery cods n = unfoldr next (IS.empty, IS.singleton 1)\n where\n next (!done, !avail) = (`fmap` IS.minView avail) $ \\ (!j, !rest) ->\n (j,\n (IS.insert j done,\n IS.delete j $! IS.union avail $! IS.difference (cods A.! j) done))\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine :: IO [Int]\n input <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)\n <$> BSL.getContents\n let cods = runSTArray $ do\n cods <- A.newArray (1,n) IS.empty\n forM_ input $ \\(i,j) -> when (i /= j) $ do\n (A.writeArray cods i $!) =<<\n IS.insert j <$> A.readArray cods i\n (A.writeArray cods j $!) =<<\n IS.insert i <$> A.readArray cods j\n return cods\n putStrLn $ unwords $ map show $ query cods n\n\nquery :: Array Int IntSet -> Int -> [Int]\nquery cods n = unfoldr next (IS.empty, IS.singleton 1)\n where\n next (!done, !avail) = (`fmap` IS.minView avail) $ \\ (!j, !rest) ->\n (j,\n (IS.insert j done,\n IS.union rest $! IS.difference (cods A.! j) done))\n"}], "negative_code": [], "src_uid": "157630371c4f6c3bcc6355d96c86a626"} {"source_code": "import Data.List\nmain = do interact (unwords . map show . gao . map read . tail . words)\ngao a\n\t| null p && s < 2\t= [if z then 0 else maximum n]\n\t| otherwise\t\t\t= p ++ if even s then n else init (sort n)\n\twhere\n\t\tz = any (==0) a\n\t\t(p, n) = partition (>0) $ filter (/=0) a\n\t\ts = length n\n", "positive_code": [{"source_code": "import Data.List\nmain = interact (unwords.map show.s.map read.words)\ns (n:xs) = if null pos\n then if null mneg \n then if null nil then neg else nil\n else mneg\n else pos++mneg\n where\n pos = filter (>0) xs\n neg = filter (<0) xs\n nil = filter (==0) xs\n mneg = if even (length neg) then neg else (delete (maximum neg) neg)\n"}, {"source_code": "import List\nmain = interact solve\nsolve input = output where\n inputs = lines input\n n = read ( head inputs ) :: Int\n cs = map ( read :: String -> Int ) $ words ( last inputs )\n output = unwords $ map show $ answer cs\nanswer xs\n | null pos && null neg = [0]\n | null pos && len == 1 && elem 0 xs = [0]\n | null pos && len == 1 = neg\n | otherwise = pos ++ if even len then neg else init neg\n where\n pos = filter (>0) xs\n neg = sort $ filter (<0) xs\n len = length neg"}, {"source_code": "import Data.List\nmain = do\n getLine\n c <- fmap (map read . words) getLine\n let pos = filter (>0) c\n neg = reverse . sort . filter (<0) $ c\n res = pos ++ case length neg `mod` 2 of\n 0 -> neg\n _ -> tail neg\n putStrLn . unwords . map show $ if null res then [maximum c] else res"}, {"source_code": "import Data.List\nmain = do\n (_:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ intercalate \" \" $ map show $ f a where\n f a = b where\n neg = sort $ filter (< 0) a\n pos = filter (> 0) a\n len = length neg\n bb = pos ++ if (mod len 2) == 1 then init neg else neg\n b = if null bb then [maximum a] else bb"}], "negative_code": [{"source_code": "import Data.List\nmain = do interact (unwords . map show . gao . map read . tail . words)\ngao a\n\t| null p && s < 2\t= [if z then 0 else maximum n]\n\t| otherwise\t\t\t= p ++ if even s then n else tail (sort n)\n\twhere\n\t\tz = any (==0) a\n\t\t(p, n) = partition (>0) $ filter (/=0) a\n\t\ts = length n\n"}, {"source_code": "import List\nmain = interact solve\nsolve input = output where\n inputs = lines input\n n = read ( head inputs ) :: Int\n cs = map ( read :: String -> Int ) $ words ( last inputs )\n output = unwords $ map show $ answer cs\nanswer xs\n | null pos && null neg = [0]\n | null pos && len == 1 = neg\n | otherwise = pos ++ if even len then neg else init neg\n where\n pos = filter (>0) xs\n neg = sort $ filter (<0) xs\n len = length neg"}, {"source_code": "import Data.List\nmain = do\n getLine\n c <- fmap (map read . words) getLine\n let pos = filter (>0) c\n neg = reverse . sort . filter (<0) $ c\n res = pos ++ case length neg `mod` 2 of\n 0 -> neg\n _ -> tail neg\n putStrLn . unwords . map show $ if null res then neg else res"}, {"source_code": "import Data.List\nmain = do\n (_:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ intercalate \" \" $ map show $ f a where\n f a = b where\n neg = sort $ filter (< 0) a\n pos = filter (> 0) a\n len = length neg\n bb = pos ++ if (mod len 2) == 1 then tail neg else neg\n b = if null bb then [maximum a] else bb"}], "src_uid": "b11644953bdd1b92eb1b18c339a268a1"} {"source_code": "process :: [Int] -> [Int] -> (Int, Int)\nprocess as bs = (maximum as, maximum bs)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n na <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n nb <- fmap readInt getLine\n bs <- fmap (map readInt.words) getLine\n let (a,b) = process as bs\n putStrLn $ show a ++ \" \" ++ show b", "positive_code": [{"source_code": "import Control.Monad\nimport Data.String\nreadListRec :: Int -> IO [String]\nreadListRec lineNumber =\n if (lineNumber == 0) \n then return []\n else\n getLine >>= \\newLine ->\n (newLine :) <$> readListRec(lineNumber - 1)\n\nparseLineToInt :: String -> [Int]\nparseLineToInt data_s = do\n (read::String->Int) <$> (words data_s) \n\ncountLetters :: [Char] -> Char -> Int\ncountLetters array_ char_ = length (filter (==char_) array_)\n\n\ncreateLists :: Int -> ([Int], [Int])\ncreateLists 0 = ([],[])\ncreateLists n = let\n (l, r) = createLists (n - 1)\n in ((2 * n) : r, (2 * n - 1) : l)\n\nmain = do\n _ <- getLine\n aS <- getLine\n let a = maximum $ parseLineToInt aS\n _ <- getLine\n bS <-getLine\n let b = maximum $ parseLineToInt bS\n putStrLn $ (show a) ++ \" \" ++ show b\n"}, {"source_code": "import Data.List\n\nmain = do\n _ <- getLine\n a <- maximum . map (read :: String -> Int) . words <$> getLine\n _ <- getLine\n b <- maximum . map (read :: String -> Int) . words <$> getLine\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n as <- map (read :: String -> Int) . words <$> getLine\n m <- (read :: String -> Int) <$> getLine\n bs <- map (read :: String -> Int) . words <$> getLine\n let sortedAs = reverse . sort $ as\n sortedBs = reverse . sort $ bs\n putStr . show . head $ sortedAs\n putStr \" \"\n putStrLn . show . head $ sortedBs\n"}, {"source_code": "\ntoInt n = (read n)::Int\n\nsolve :: [Int] -> [Int] -> (Int, Int)\nsolve a b = head [(x,y) | x <- a, y <- b, (not ((x+y) `elem` a)) && (not ((x+y) `elem` b))]\n\nmain = do\n inp <- getContents\n let lns = lines inp\n let a = map toInt (words (lns !! 1))\n let b = map toInt (words (last lns))\n let t = solve a b\n putStrLn $ (show $ fst t) ++ \" \" ++ (show $ snd t)"}, {"source_code": "import Text.Printf\nreadNumbers :: String -> [Int]\nreadNumbers = map read . words\nmaxInt :: [Int] -> Int\nmaxInt [x] = x\nmaxInt (x:xs) | (maxInt xs) > x = maxInt xs\n | otherwise = x\n\nmain = do\n input <- getLine \n input <- getLine \n let a = readNumbers input\n input <- getLine \n input <- getLine \n let b = readNumbers input\n printf \"%d %d\\n\" (maxInt a) (maxInt b)"}, {"source_code": "main = do\n n <- getLine\n a <- getLine\n m <- getLine\n b <- getLine\n putStrLn (solve (read n) (map read $ words a) (read m) (map read $ words b))\n\nsolve :: Int -> [Int] -> Int -> [Int] -> String\nsolve n a m b = show (maximum a) ++ \" \" ++ show (maximum b)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\t\t\n\n\nmain = do\n\t\tgetLine\n\t\ta<-maximum <$> map read<$> words <$> getLine ::IO Int\n\t\tgetLine\n\t\tb<-maximum <$> map read<$> words <$> getLine ::IO Int\n\t\tputStr $ show a\n\t\tputStr $ \" \" ++ show b\n"}, {"source_code": "import Control.Monad\n\nimport qualified Data.Set as S\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetList :: IO [Int]\ngetList = (map read) <$> words <$> getLine\n\nsolve :: [Int] -> [Int] -> (Int, Int)\nsolve a b = fst $ head [((x, y), x + y) | x <- a, y <- b, not $ S.member (x+y) $ S.union a' b']\n where a' = S.fromList a\n b' = S.fromList b\n\nmain :: IO ()\nmain = do\n n <- getInt\n a <- getList\n m <- getInt\n b <- getList\n putStrLn $ (\\t -> (show $ fst t) ++ \" \" ++ (show $ snd t)) (solve a b)\n"}], "negative_code": [], "src_uid": "ec09b2df4ed3abbca4c47f48f12010ca"} {"source_code": "{-# LANGUAGE NegativeLiterals, InstanceSigs, MultiParamTypeClasses, UndecidableSuperClasses, MultiWayIf, KindSignatures, \r\nOverloadedLists,ApplicativeDo,OverloadedStrings,MonadComprehensions,ParallelListComp,TransformListComp, TupleSections,\r\nBlockArguments, TypeApplications, PostfixOperators, TypeOperators, BangPatterns, LambdaCase, UnboxedSums, UnboxedTuples, RankNTypes, \r\nFlexibleContexts,DeriveFoldable, DeriveTraversable, ScopedTypeVariables, GADTs, PatternSynonyms, ViewPatterns, FunctionalDependencies #-}\r\nimport Data.List (group, sort, groupBy, partition)\r\nimport qualified Data.ByteString.Lazy.Char8 as L\r\nimport Data.Function ((&),fix,on)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Bifunctor (bimap)\r\nint :: L.ByteString -> Int\r\nint = fst . fromJust . L.readInt\r\nreadInts ::L.ByteString -> [Int]\r\nreadInts = map int . L.split ' '\r\n\r\nsolve :: [Int] -> L.ByteString\r\nsolve = L.pack . show . uncurry min . bimap length length . partition even\r\n\r\ntwos :: [L.ByteString] -> [L.ByteString]\r\ntwos [] = []\r\ntwos (_:y:xs) = y : twos xs\r\n\r\nmain :: IO ()\r\nmain = L.interact (L.unlines . map (solve . readInts) . twos . tail . L.lines)\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\nsolve arr = min (length (filter even arr)) (length (filter odd arr)) \r\nmain = do\r\n n <- readLn :: IO Int\r\n replicateM_ n $ do\r\n _ <- getLine\r\n l <- getLine\r\n let arr = (map read . words) l\r\n print $ solve arr"}, {"source_code": "import Control.Monad (replicateM_)\n\nsolve arr = min (length (filter odd arr)) (length (filter even arr)) \n\nmain = do\n n <- readLn :: IO Int\n replicateM_ n $ do\n _ <- getLine\n l <- getLine\n let arr = (map read . words) l\n print $ solve arr\n"}, {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Int\nsolve n as = uncurry min . join bimap L.length $ L.partition even as\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "4b33db3950303b8993812cb265fa9819"} {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . concatMap show . solve . map read . words\n\ndata Instruction = L | R | P deriving Show\n\nsolve :: [Int] -> [Instruction]\nsolve (_:as) = concatMap f (zip [0..] as)\n where f (0, a) = R : concat (replicate a [ L, P, R ]) ++ [L]\n f (i, a) = replicate (i - 1) R ++ concat (replicate a [ R, P, L ]) ++ replicate (i - 1) L\nsolve _ = undefined\n", "positive_code": [{"source_code": "import Control.Monad\n\ngo [] = putChar '\\n'\ngo [0] = putChar '\\n'\ngo [1] = putStr \"P\\n\"\ngo [n] = putStr \"PLR\" >> go [n-1]\ngo (0 : ns) = putChar 'R' >> go ns\ngo (1 : ns) = putStr \"PR\" >> go ns\ngo (n : 0 : ns) = putStr \"PRL\" >> go ((n-1):0:ns)\ngo (n : m : ns) = putStr \"PRPL\" >> go ((n-1):(m-1):ns)\n\nmain = do\n n <- liftM read getLine :: IO Int\n as <- liftM (map read . words) getLine :: IO [Int]\n go as\n"}, {"source_code": "main :: IO()\nmain = solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> IO()\nsolve [a] | a == 0 = putStrLn \"\"\n | a == 1 = putStrLn \"P\"\n | otherwise = do putStr \"PLR\"\n solve [(a-1)]\nsolve (a:ax) | a == 0 = do putStr \"R\"\n solve ax\n | otherwise = do putStr \"PRL\"\n solve ((a-1):ax)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n\tn <- read <$> getLine ::IO Int\n\ta <- (map read) <$> words <$> getLine:: IO [Int]\n\tputStrLn $ foldl1' (++) $ map (line n a) [1..maximum a] where\n\t\tline n a i = (foldl1' (++) $ map (\\(x,k) -> coin x ++ move k ) $ zip a [1..] ) ++ replicate (n - 1) 'L' where\n\t\t\tcoin x = if x >= i then \"P\" else []\n\t\t\tmove k = if k < n then \"R\" else []"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nmain = do\n getLine\n as <- readInts\n let go [] = return ()\n go [x] = replicateM_ x (putStr \"PLR\")\n go (x:xs) = replicateM_ x (putStr \"PRL\") >> putChar 'R' >> go xs\n go as\n putChar '\\n'\n\n \n \n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nprintSolution :: Int -> Int -> IO ()\n\nprintSolution l 1000 = do\n\tstr <- getLine\n\tlet x = (read str :: Int)\n\tprintSolution l x\n\nprintSolution l 0 = do\t\n\tif ( l /= 1 ) then putChar 'R'\n\telse return ();\n\t\nprintSolution l coins = do\n\t\t\tif ( l == 1 )\n\t\t\t\tthen do\n\t\t\t\t\tputChar 'L'\t\n\t\t\t\t\tputChar 'R'\n\t\t\t\telse do\n\t\t\t\t\tputChar 'R'\t\n\t\t\t\t\tputChar 'L'\t\n\t\t\tputChar 'P'\t\n\t\t\t(printSolution l (coins - 1) )\n\t\t\t\t\n\nprintSol :: [Int] -> IO ()\nprintSol [] = do\n\t\t\t\treturn ()\nprintSol (x:xs) = do\n if\t(length xs) == 0\t\t \n\t\t then\n printSolution 1 x\t\t\t \n\t\t else \n\t\t\t printSolution 0 x\t\t\t \n printSol xs\n\nmain = do\n --nStr <- getLine\n\t yy <- (map read) <$> words <$> getLine :: IO [Int]\t \n\t x <- (map read) <$> words <$> getLine :: IO [Int]\t \n\t let n = head yy\t \n\t printSol x"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . solve . map read . tail . words\n\nsolve :: [Int] -> String\nsolve [] = \"\"\nsolve [x] = [1..x] >> \"PLR\"\nsolve (x:xs) = ([1..x] >> \"PRL\") ++ \"R\" ++ solve xs\n"}, {"source_code": "main=interact$s.map read.tail.words\ns[]=\"\";s[x]=[1..x]>>\"PLR\";s(x:y)=([1..x]>>\"PRL\")++\"R\"++s y\n"}, {"source_code": "main = do\n (_:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ f a where\n f [] = \"\"\n f [x] = [1..x]>>\"PLR\"\n f (x:xs) = ([1..x]>>\"PRL\") ++ \"R\" ++ (f xs)"}], "negative_code": [{"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . solve . map read . words\n\nsolve :: [Int] -> String\nsolve (_:as) = concatMap (\\a -> concat (replicate a \"PRL\") ++ \"R\") as\nsolve _ = undefined\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . concatMap show . solve . map read . words\n\ndata Instruction = L | R | P deriving Show\n\nsolve :: [Int] -> [Instruction]\nsolve (_:as) = concatMap f (zip [0..] as)\n where f (0, a) = R : concat (replicate a [ L, P, R ]) ++ [L]\n f (i, a) = replicate i R ++ concat (replicate a [ R, P, L ]) ++ replicate i L\nsolve _ = undefined\n"}, {"source_code": "main = do\n (n:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ f a where\n f [] = \"\"\n f [x] = [1..x]>>\"PLR\"\n f (x:xs)\n | x == 0 = \"R\" ++ (f xs)\n | otherwise = [1..x]>>\"PRL\" ++ \"R\" ++ (f xs)"}], "src_uid": "50e88225d8b081d63eebe446f48057f4"} {"source_code": "main = do\n\t[h, w] <- fmap (map read . words) getLine\n\tputStrLn $ unwords $ map show $ tail $ maximum $ (gao h w ++) $ map (\\[a,b,c] -> [a,c,b]) $ gao w h\n\twhere gao h w = [[x * y, x, y] | x <- takeWhile (<=h) $ iterate (*2) 1, 4 * x <= 5 * w, y <- [min w $ div (x * 5) 4]]\n", "positive_code": [{"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\ndebug = flip trace\n-- debug = const\n\ncands = takeWhile (<= 10^9) $ map (2^) [0..]\n\nlargestCand n = reverse $ takeWhile (<= n) cands\n\nfi = fromIntegral\n\ncmp :: (Integer, Integer) -> (Integer, Integer) -> Ordering\ncmp a@(a1, a2) b@(b1, b2)\n | a1 * a2 < b1 * b2 = LT\n | a1 * a2 == b1 * b2 && a1 < b1 = LT\n | a == b = EQ\n | otherwise = GT\n\nsolve :: Integer -> Integer -> (Integer, Integer)\nsolve h w = \n maximumBy cmp $ concat [(heightPow h w), (widthPow h w)]\n `debug` (show (heightPow h w) ++ \" \" ++ show (widthPow h w))\n \neps :: Double\neps = 10e-9\n\nheightPow h w = concatMap hpcalc hps\n where hps = largestCand h \n hpcalc hp\n | fi hp * 1.25 - eps < fi w = [(hp, floor (fi hp * 1.25 + eps))]\n | fi hp * 0.8 + eps > fi w = []\n | otherwise = [(hp, w)]\n\nwidthPow h w = concatMap wpcalc wps\n where wps = largestCand w\n wpcalc wp\n | fi wp * 1.25 - eps < fi h = [(floor (fi wp * 1.25 + eps), wp)]\n | fi wp * 0.8 + eps > fi h = []\n | otherwise = [(h, wp)]\n\nmain = do\n [h, w] <- (map read . words) `fmap` getLine\n let (hr, wr) = solve h w\n putStrLn $ show hr ++ \" \" ++ show wr"}, {"source_code": "import Maybe\nimport List\n\nmain = do\n [h,w] <- fmap (map read.words) getLine\n putStrLn $ f $ solve w h\n where f(x,y) = unwords $ map show [x,y]\n\nsolve :: Integer -> Integer -> (Integer,Integer)\nsolve h w = case compare (area a) (area b) of\n LT -> b\n GT -> a\n EQ -> last $ sort [a,b]\n where a = anotherEdges h w\n b = flipTuple $ anotherEdges w h\n\narea (x,y) = x*y\n\nflipTuple (x,y) = (y,x)\n\npower2 = map(2^)[0..]\n\nanotherEdge :: Integer -> Integer -> Maybe (Integer,Integer)\nanotherEdge y x = if y < lower then Nothing else Just $ (x,min y upper)\n where z = fromIntegral x\n lower = ceiling $ 0.8*z\n upper = floor $ 1.25*z\n\nanotherEdges y x = head $ catMaybes $ map (anotherEdge y)\n $ reverse $ takeWhile(<=x) power2\n"}, {"source_code": "module Main where\n\nreadInteger :: String -> Integer\nreadInteger = read\n\nmain = do\n input <- getLine\n let [h, w] = map readInteger $ take 2 $ words input\n let (cutH, cutW) = solve h w \n putStrLn $ show cutH ++ \" \" ++ show cutW where\n \n solve h w = maximum $ filter (\\(y,x) -> (y*x) == maxSquare) possibleList where\n \n possibleList = byHeightList ++ byWidthList\n \n maxSquare = maximum (map (\\(h, w) -> h*w) possibleList)\n \n byWidthList = filter isPossibleHW $ map makeH $ filter (<=w) powers\n byHeightList = filter isPossibleHW $ map makeW $ filter (<=h) powers\n\n makeH ww = ((min h (div (5*ww) 4)), ww)\n makeW hh = (hh, (min w (div (5*hh) 4)))\n \n isPossibleHW (hh, ww) = (5*hh) >= (4*ww) && (4*hh) <= (5*ww)\n \n powers :: [Integer]\n powers = [2^n | n <- [0..30]]\n"}], "negative_code": [{"source_code": "main = do\n\t[h, w] <- fmap (map read . words) getLine\n\tputStrLn $ unwords $ map show $ tail $ maximum $ gao h w ++ gao w h\twhere\n\tgao h w = [[x * y, x, y] | x <- takeWhile (<=h) $ iterate (*2) 1, 4 * x <= 5 * w, y <- [min w $ div (x * 5) 4]]\n"}, {"source_code": "import Maybe\nimport List\n\nmain = do\n [h,w] <- fmap (map read.words) getLine\n putStrLn $ f $ solve w h\n where f(x,y) = unwords $ map show [x,y]\n\nsolve :: Integer -> Integer -> (Integer,Integer)\nsolve h w = case compare (area a) (area b) of\n LT -> b\n GT -> a\n EQ -> last $ sort [a,b]\n where a = anotherEdges h w\n b = flipTuple $ anotherEdges h w\n\narea (x,y) = x*y\n\nflipTuple (x,y) = (y,x)\n\npower2 = map(2^)[0..]\n\nanotherEdge :: Integer -> Integer -> Maybe (Integer,Integer)\nanotherEdge y x = if y < lower then Nothing else Just $ (x,min y upper)\n where z = fromIntegral x\n lower = ceiling $ 0.8*z\n upper = floor $ 1.25*z\n\nanotherEdges y x = head $ catMaybes $ map (anotherEdge y)\n $ reverse $ takeWhile(<=x) power2\n"}], "src_uid": "57d2eb75a14f1b66009bdb503fd31f91"} {"source_code": "\nimport Control.Monad (forM_,when)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.Word\n\nimport Data.Array.IArray\nimport Data.Array.MArray\nimport qualified Data.Array.Unboxed as U\nimport Data.Array.ST (runSTUArray)\nimport Debug.Trace\n\nsqr :: Double -> Double\nsqr = sqrt\n\nisqrt :: Integral a => a -> Int\nisqrt n = floor $ sqrt $ (fromIntegral n :: Double)\n\nisSquare :: Int64 -> Maybe Int\nisSquare n = if r'*r' == n then Just r else Nothing\n where r = isqrt n\n r' = fromIntegral r\n\n-- create a prime sieve array\nmkSieve :: Int -> U.UArray Int Word8\nmkSieve n = runSTUArray $ do\n arr <- newArray (0,n) 0\n writeArray arr 1 1\n let end = isqrt n\n forM_ [2..end] $ \\a -> do\n x <- readArray arr a\n when (x == 0) $ do\n forM_ [a*a,a*a+a..n] $ \\b -> do\n writeArray arr b 1\n return arr\n\nisprime :: Int -> Bool\nisprime n | n <= 11 = n `elem` [2,3,5,7,11]\nisprime n | n `rem` 2 == 0 = False\nisprime n = all (\\m -> n `rem` m /= 0) [3,5..end]\n where end = isqrt n\n\nwheel2357 :: [Int]\nwheel2357 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel2357\nspin (x:xs) n = n : spin xs (n + x)\n\nwheel' = 2 : 3 : 5 : 7 : spin wheel2357 11\n\nisprime2 :: Int -> Bool\nisprime2 n | n <= 11 = n `elem` [2,3,5,7,11]\nisprime2 n = all (\\m -> n `rem` m /= 0) $ takeWhile (<= end) wheel'\n where end = isqrt n\n\ntprime :: (Int -> Bool) -> Int64 -> Bool\ntprime ptest 1 = False\ntprime ptest n = \n case isSquare n of\n Nothing -> False\n Just r -> ptest r\n\n(-->) = flip fmap\n\nreadInt :: BS.ByteString -> Integer\nreadInt s = case BS.readInteger s of\n Nothing -> error \"bad integer\"\n Just (n,_) -> n\n\nmain = do\n n <- getLine --> read\n let _ = n :: Int\n nums <- BS.getLine --> BS.words --> map (fromIntegral . readInt)\n let sieve = mkSieve 1000000\n let ptest k = sieve ! k == 0\n forM_ nums $ \\n -> do\n let b = tprime ptest n \n putStrLn $ if b then \"YES\" else \"NO\"\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Char\n\nsqu x = x==y*y && isprime y \n\twhere y = ceiling $ sqrt $ fromIntegral x\n\nprimes = [2,3,5,7,11] ++ (filter isprime [13,15..] )\nisprime 1 = False\nisprime 2 = True\nisprime x = all (>0) [mod x y| y<- takeWhile (<=(ceiling (sqrt (fromIntegral x)))) primes]\n\nmain= do\n\tn <- getLine \n\ts<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine ::IO [Integer]\n\tputStrLn $ intercalate \"\\n\" $ map (\\z-> if squ z then \"YES\" else \"NO\") s\n\t\n\t \n\t \n"}, {"source_code": "import Data.Int (Int64)\nimport Data.Set (Set, fromList, member)\n\nprimes :: [Int64]\nprimes = 2 : sieve primes [3..]\n where\n sieve (p:ps) xs =\n let (h,t) = span (< p*p) xs\n in h ++ sieve ps (filter ((/=0).(`mod`p)) t)\n\nprimesUpTo :: Int64 -> Set Int64\nprimesUpTo n = fromList $ takeWhile (<=n) primes\n\nprocess :: [Int64] -> [Bool]\nprocess xs = map f xs\n where\n f x = if x_sqrt^2 == x\n then x_sqrt `member` ps\n else False\n where x_sqrt = floor.sqrt.fromIntegral $ x\n ps = primesUpTo.floor.sqrt.fromIntegral $ maximum xs\n\nreadInt :: String -> Int64\nreadInt = read\n\nprintBool :: Bool -> IO ()\nprintBool b = do\n putStrLn $ [\"NO\",\"YES\"] !! fromEnum b\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n mapM_ printBool $ process xs"}, {"source_code": "import Data.List\nimport Data.Set hiding (map)\nimport Data.Int\n\nordminus :: Ord a => [a] -> [a] -> [a]\nordminus x [] = x\nordminus [] y = y\nordminus (x:xs) (y:ys) | x < y = x : ordminus xs (y:ys)\n | x == y = ordminus xs ys\n | x > y = ordminus (x:xs) ys\n\nordunion :: Ord a => [a] -> [a] -> [a]\nordunion x [] = x\nordunion [] y = y\nordunion (x:xs) (y:ys) | x < y = x : ordunion xs (y:ys)\n | y < x = y : ordunion (x:xs) ys\n | x == y = x : ordunion xs ys\n\nfoldi :: (a -> a -> a) -> a -> [a] -> a\nfoldi f z [] = z\nfoldi f z (x:xs) = f x (foldi f z (pairs f xs))\n\npairs :: (a -> a -> a) -> [a] -> [a]\npairs f (x:y:t) = f x y : pairs f t\npairs f t = t\n\nprimes :: [Int64]\nprimes = 2 : 3 : ([5,7..] `ordminus`\n foldi (\\(x:xs) -> (x:) . ordunion xs) []\n [[p*p, p*p+2*p..] | p <- tail primes])\n\nsetP = fromList (take 80000 primes)\n\nisT :: Int64 -> Bool\nisT v = let\n sqr = floor $ sqrt $ fromIntegral v\n in sqr*sqr==v && member (fromIntegral sqr) setP\n\nyn :: Bool -> String\nyn True = \"YES\"\nyn False = \"NO\"\n\nmain = do\n n <- getLine\n xs <- getLine\n putStr $ unlines $ map (yn.isT.read) $ take (read n) (words xs)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInteger . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n let\n primes = [a | a <- [2..10^3], all ((/= 0) . mod a) [2..a-1]] :: [Int64]\n\n check 1 = False\n check x = isSqrt && isPrime\n where\n y = truncate $ sqrt $ fromIntegral x\n isSqrt = y*y == x\n isPrime = all (\\p -> y `mod` p /= 0) $ filter (\\p -> p*p <= y) primes\n\n putStrLn $ unlines $ map ((\\x -> if x then \"YES\" else \"NO\") . check) xs\n"}, {"source_code": "{-# OPTIONS_GHC -O #-}\n{-# LANGUAGE BangPatterns #-}\nimport Data.Int\nimport Data.Array.Unboxed\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Set hiding (map)\nimport qualified Data.Map as M\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n putStr.unlines $ map f $ go xs (M.singleton 1 False) [] \n\ngo [] _ acc = reverse acc\ngo (x:xs) mem acc =\n case M.lookup x mem of\n Just v -> go xs mem $ v : acc\n Nothing -> (go xs $ M.insert x b mem) $ b : acc\n where b = isinset x\n \nisinset x = x `member` primesSqr \nf True = \"YES\";f False = \"NO\"\n\nprimesSqr = fromList $ map (^2) primesList\nprimesList = primesToA.floor.(+1).sqrt $ 1e12\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a"}, {"source_code": "import Data.Int\nimport Data.Char\nimport qualified Data.List as L\nimport qualified Data.Array as A\n\n\nsolve :: [Int64] -> [String]\nsolve queries = map (boolToString . isTPrime) queries\n where\n boolToString True = \"YES\"\n boolToString False = \"NO\"\n isTPrime n = let m = floor (sqrt (fromIntegral n)) in\n m * m == n && isPrimeMemo m\n isPrimeMemo m = primeArr A.! m\n primeArr = A.listArray (0,1001000) [ isPrime n | n <- [0..1001000]]\n isPrime 0 = False\n isPrime 1 = False\n isPrime n = and . map (\\p -> n `mod` p /= 0) . takeWhile (\\p -> p*p <= n) $ primes\n primes = 2:filter isPrimeMemo [3,5..]\n\nmain :: IO ()\nmain = do getLine\n queries <- (getLine >>= return . map readInt64 . words)\n putStr . unlines $ solve queries\n\nreadInt64 :: String -> Int64\nreadInt64 s = L.foldl' (\\e c -> (fromIntegral . digitToInt $ c) + 10 * e) 0 s\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\ns-> (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve (xs) = forM_ xs $ \\i-> let (n,f)= properFraction $ sqrt $ fromIntegral i in if (f==0) && (isPrime2 n) then putStrLn \"YES\" else putStrLn \"NO\"\nprimes = fst $ break (>1000) $ filterPrime [2..] \n where filterPrime (p:xs) = \n p : filterPrime [x | x <- xs, rem x p /= 0]\nisPrime2 1 = False\nisPrime2 2 = True\nisPrime2 x =let (b1,b2) = break (\\a -> x `mod` a==0 ) (take ( floor $ sqrt $ fromIntegral x) primes) in if b2==[] then True else False"}, {"source_code": "{-# OPTIONS_GHC -O #-}\n{-# LANGUAGE BangPatterns #-}\nimport Data.Int\nimport Data.Array.Unboxed\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Set hiding (map)\nimport qualified Data.Map as M\n\nmagic = 1000\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n putStr.unlines $ map f $ go xs (M.singleton 1 False) []\n --go xs (M.singleton 1 False)\n \n\ngo [] _ acc = reverse acc\ngo (x:xs) mem acc =\n case M.lookup x mem of\n Just v -> go xs mem $ v : acc\n Nothing -> (go xs $ M.insert x b mem) $ b : acc\n where b = isinset x\n \nisinset x = x `member` primesSqr \n \nf True = \"YES\";f False = \"NO\"\n\npmagic = take magic primesList\n_magicth = last pmagic\n\nisPrime n\n | n > _magicth = case or . map ((==0).(n`mod`)) $ pmagic of\n False -> n `member` primesSet\n True -> False\n | True = n `elem` pmagic\nisTPrime 4 = True\nisTPrime 9 = True\nisTPrime n\n | n`mod`2 == 0 = False\n | n`mod`3 == 0 = False\n | n`mod`24 /= 1 = False\n | n>999983^2 = False\n | True = sq*sq == n && isPrime sq\n where sq = round.sqrt.fromIntegral $ n\n\nprimesSet = fromList $ drop magic $ primesList\nprimesSqr = fromList $ map (^2) primesList\nprimesList = primesToA.floor.(+1).sqrt $ 1e12\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n-- Meat\n\nsolve :: [Integer] -> [BS.ByteString]\nsolve = map (\\x -> if tPrime x then yes else no)\n where yes = BS.pack \"YES\"\n no = BS.pack \"NO\"\n\ntPrime :: Integer -> Bool\ntPrime 1 = False\ntPrime n = sq * sq == n && isPrime sq\n where sq = round $ sqrt (fromIntegral n::Double)\n\nprimes :: [Integer]\nprimes = filter isPrime [2..]\n\nisPrime :: Integer -> Bool\nisPrime 2 = True\nisPrime n = 0 `notElem` fmap (n `rem`) (takeWhile (\\p -> p*p <= n) primes)\n\n-- Shit\nmain :: IO ()\nmain = do\n [_, xs] <- readShit\n printShitV $ solve xs\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "{-# OPTIONS_GHC -O #-}\n{-# LANGUAGE BangPatterns #-}\nimport Data.Int\nimport Data.Array.Unboxed\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Set hiding (map)\nimport qualified Data.Map as M\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isinset) xs\n --putStr.unlines $ map f $ go xs (M.singleton 1 False) [] \n{-\ngo [] _ acc = reverse acc\ngo (x:xs) mem acc =\n case M.lookup x mem of\n Just v -> go xs mem $ v : acc\n Nothing -> (go xs $ M.insert x b mem) $ b : acc\n where b = isinset x\n -}\nisinset x = x `member` primesSqr \nf True = \"YES\";f False = \"NO\"\n\nprimesSqr = fromList $ map (^2) primesList\nprimesList = primesToA.floor.(+1).sqrt $ 1e12\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a"}, {"source_code": "\nimport Char (ord)\nimport Data.Set (fromList, member)\nimport Monad (liftM)\n\nisPrime :: Integer -> Bool\nisPrime n = all (\\x -> mod n x /= 0) $ takeWhile (\\x -> x * x <= n) primes\n\nprimes :: [Integer]\nprimes = 2 : [n | n <- [3,5..], isPrime n]\n\nsolve :: [Integer] -> [Bool]\nsolve xs = map isSqrPrime xs\n where\n set = fromList . takeWhile (<= 10^6) $ primes\n isSqrPrime 1 = False\n isSqrPrime x\n | x' * x' == x = member x' set\n | otherwise = False\n where\n x' = round . sqrt . fromIntegral $ x\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nparseLine :: String -> [Integer]\nparseLine [] = []\nparseLine (c:s)\n | c == ' ' = parseLine s\n | otherwise = parseLine' (f c) s\n where\n f c = fromIntegral (ord c - ord '0')\n parseLine' a [] = [a]\n parseLine' a (c:s)\n | c == ' ' = a : parseLine s\n | otherwise = parseLine' (10 * a + f c) s\n\nmain :: IO ()\nmain = getLine >> liftM parseLine getLine >>= mapM_ (putStrLn . (\"YES\" \"NO\")) . solve\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport qualified Data.HashMap.Strict as H\n\n--isprime 4 =True\n--isprime x = all (>0)[ mod sx i|i<-[2]++[3,5..ssx+1]]\n-- where sx = floor $ sqrt $ fromIntegral x\n-- ssx = floor $ sqrt $ fromIntegral sx\nprimes ::[Integer]\nprimes = [2,3,5,7] ++ [x|x<-[11,13..],isprime x]\n\nisprime::Integer->Bool\nisprime x = and [mod x y/=0 |y<-takeWhile (<=xx) primes ]\n where xx = floor $ sqrt $ fromIntegral x\n\nisrprime::Integer->Bool\nisrprime s = isprime r\n where r = floor $ sqrt $ fromIntegral s\n\nnosquare x = sx*sx /=x\n where sx = floor $ sqrt $ fromIntegral x\n\nprocess 1 =\"NO\"\nprocess s | nosquare s = \"NO\"\n | isrprime s = \"YES\"\n | otherwise = \"NO\"\n\nprocess1::[Integer]->H.HashMap Integer String->[String]->[String]\nprocess1 q m a | q==[] = reverse a\n | H.lookup (head q) m == Nothing = process1 (tail q) (H.insert (head q) (process (head q) ) m) ((process (head q )):a)\n | otherwise = process1 (tail q) m ((fromJust(H.lookup (head q) m)):a)\n\n\n\n\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map ( fst.fromJust.C.readInteger) <$> C.words <$> C.getLine::IO [Integer]\n mapM_ putStrLn $ process1 q H.empty []\n"}, {"source_code": "{-# OPTIONS -O2 -optc-O3 #-}\nimport Control.Arrow ((***))\nimport Control.Monad (forM_, when)\nimport Control.Monad.ST (ST)\nimport Data.Array.ST (STUArray, runSTUArray, newArray, readArray, writeArray)\nimport Data.Array.Unboxed (UArray, (!), assocs)\n\nisqrt :: (Integral a, Integral b) => a -> b\nisqrt = floor . sqrt . fromIntegral\n\nsieveToN :: Int -> UArray Int Bool\nsieveToN n = runSTUArray sieve\n where\n sieve = do\n a <- newArray (2, n) True :: ST s (STUArray s Int Bool)\n forM_ [4, 6 .. n] $ \\j ->\n writeArray a j False\n forM_ [3, 5 .. isqrt n] $ \\i -> do\n ai <- readArray a i\n when ai $\n forM_ [i * i, i * (i + 2) .. n] $ \\j ->\n writeArray a j False\n return a\n\nprimeTab :: UArray Int Bool\nprimeTab = sieveToN 1000000\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n >= 2 && primeTab!fromIntegral n\n\nmain = do\n getLine\n getLine >>= putStrLn . unlines . map (gao . read) . words\n where\n gao n = let m = isqrt n in if m * m == n && isPrime m then \"YES\" else \"NO\"\n"}, {"source_code": "main=getContents>>=mapM_(putStrLn.h.read).tail.words\nh n|n==m*m&&f m=\"YES\"|1>0=\"NO\" where m=round$sqrt$fromIntegral n\ng=2:filter f[3,5..]\nf n=n>1&&foldr(\\p r->p*p>n||n`mod`p/=0&&r)True g\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getContents >>= mapM_ (putStrLn . yesno . solve . fst . fromJust . B.readInteger) . tail . B.words\n\nsolve :: Integer -> Bool\nsolve n = n == m * m && isPrime m\n where m = round (sqrt (fromIntegral n) :: Double)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3,5..]\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n > 1 && foldr (\\p r -> p * p > n || n `mod` p /= 0 && r) True primes\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= mapM_ (putStrLn . yesno . solve . read) . tail . words\n\nsolve :: Integer -> Bool\nsolve n = n == m * m && isPrime m\n where m = round (sqrt (fromIntegral n) :: Double)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3,5..]\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n > 1 && foldr (\\p r -> p * p > n || n `mod` p /= 0 && r) True primes\n\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= mapM_ (putStrLn . yesno . solve . read) . tail . words\n\nsolve :: Integer -> Bool\nsolve n = let m = (round :: Double -> Integer) $ sqrt $ fromIntegral n in n == m * m && isPrime m\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3,5..]\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n > 1 && foldr (\\p r -> p * p > n || n `mod` p /= 0 && r) True primes\n"}, {"source_code": "main=getContents>>=mapM_(putStrLn.h.read).tail.words\nh n|n==m*m&&f m=\"YES\"|1>0=\"NO\" where m=round$sqrt$fromIntegral n\nf n=n>1&&foldr(\\p r->p*p>n||n`mod`p/=0&&r)True(2:filter f[3,5..])\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Int\nimport Data.STRef\nimport qualified Data.Set as S\nmain = interact $ unlines . map (format . (`S.member` squares)) . map read . tail . words\nformat True = \"YES\"\nformat False = \"NO\"\nsquares = runST $ do\n sieve <- newArray (2,10^6) True :: ST s (STUArray s Int64 Bool)\n squares <- newSTRef S.empty\n forM_ [2..10^6] $ \\i -> do\n p <- readArray sieve i\n when p $ do\n modifySTRef' squares (S.insert (i^2 :: Int64))\n when (i <= 10^3) $ forM_ [2*i, 3*i..10^6] $ \\j -> writeArray sieve j False\n readSTRef squares\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.Base(unsafeRead,unsafeWrite,unsafeAt)\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = B.getContents >>= putStrLn.unlines.solve.map readInteger.tail.B.words\n\nsolve :: [Integer] -> [String]\nsolve xs = map go xs\n where\n !isPrime = sieveOdds 1000000\n go x\n | fromIntegral sqrtx * fromIntegral sqrtx /= x = \"NO\"\n | x==4 || odd sqrtx && unsafeAt isPrime (sqrtx`shiftR`1) = \"YES\"\n | otherwise = \"NO\"\n where\n !sqrtx = bigisqrt x\n\nsieveOdds :: Int -> UArray Int Bool\nsieveOdds num = runSTUArray $ do\n let !num2 = num`div`2\n isPrime <- newArray (0,num2) True\n unsafeWrite isPrime 0 False\n forM_ [1..isqrt num`shiftR`1] $ \\i-> do\n b <- unsafeRead isPrime i\n when b $ do\n let !p = i`shiftL`1 + 1\n !pp = i*(p+1)\n forM_ [pp,pp+p..num2] $ \\j-> do\n unsafeWrite isPrime j False\n return isPrime\n\nisqrt :: Int -> Int\nisqrt x = floor.(1e-8+).sqrt $ fromIntegral x\n\nbigisqrt :: Integer -> Int\nbigisqrt x = floor.(1e-8+).sqrt $ fromIntegral x"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Word\n\n--nubSorted :: Ord a => [a] -> [a]\n--nubSorted [] = []\n--nubSorted [x] = [x]\n--nubSorted (x1:x2:xs) = if x1 == x2 then nubSorted (x2:xs) else x1 : nubSorted (x2:xs)\n\nisPrime :: Word64 -> Bool\nisPrime n | n < 2 = False\n | n == 2 = True\n | even n = False\n | (rootF n) ^ 2 == n = False\n | otherwise = null $ filter (\\x -> mod n x == 0) $ takeWhile (\\x -> x*x < n) [3, 5..]\n\nrootF = round . sqrt . fromIntegral\n\nisTPrime2 :: Word64 -> Bool\nisTPrime2 999966000289 = True\nisTPrime2 n =\n let root = rootF n\n in (isPrime $! root) && root * root == n\n\nmain = do\n n <- getLine\n xs <- words `fmap` getContents\n mapM_ (\\x -> putStrLn (if isTPrime2 (read x) then \"YES\" else \"NO\")) xs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n let\n primes = [a | a <- [2..10^3], all ((/= 0) . mod a) [2..a-1]]\n\n check 1 = False\n check x = isSqrt && isPrime\n where\n y = truncate $ sqrt $ fromIntegral x :: Int64\n isSqrt = y*y == x\n isPrime = all (\\p -> y `mod` p /= 0) $ filter (\\p -> p*p <= y) primes\n\n putStrLn $ unlines $ map ((\\x -> if x then \"YES\" else \"NO\") . check) xs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n let\n primes = [a | a <- [2..10^3], all ((/= 0) . mod a) [2..a-1]]\n\n check x = isSqrt && isPrime\n where\n y = truncate $ sqrt $ fromIntegral x\n isSqrt = y*y == x\n isPrime = all (\\p -> y `mod` p /= 0) $ filter (\\p -> p*p <= y) primes\n\n putStrLn $ unlines $ map ((\\x -> if x then \"YES\" else \"NO\") . check) xs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n let\n primes = [a | a <- [2..10^3], all ((/= 0) . mod a) [2..a-1]]\n\n check 1 = False\n check x = isSqrt && isPrime\n where\n y = truncate $ sqrt $ fromIntegral x\n isSqrt = y*y == x\n isPrime = all (\\p -> y `mod` p /= 0) $ filter (\\p -> p*p <= y) primes\n\n putStrLn $ unlines $ map ((\\x -> if x then \"YES\" else \"NO\") . check) xs\n"}, {"source_code": "\nimport Control.Monad (forM_)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\nsqr :: Double -> Double\nsqr = sqrt\n\nisqrt :: Int64 -> Maybe Int64\nisqrt n = if r*r == n then Just r else Nothing\n where r = floor $ (sqr (fromIntegral n) )\n\ntprime :: Int64 -> Bool\ntprime n = \n case isqrt n of\n Nothing -> False\n Just r -> isPrime' r\n\nisPrime' :: Int64 -> Bool\nisPrime' n | n `mod` 2 == 0 = n == 2\nisPrime' n = all (\\m -> n `rem` m /= 0) [3,5..end]\n where end = floor (sqr (fromIntegral n))\n\nallTrue = all id\n\n(-->) = flip fmap\n\nreadInt :: BS.ByteString -> Integer\nreadInt s = case BS.readInteger s of\n Nothing -> error \"bad integer\"\n Just (n,_) -> n\n\nmain = do\n n <- getLine --> read\n let _ = n :: Int\n nums <- BS.getLine --> BS.words --> map (fromIntegral . readInt)\n forM_ nums $ \\n -> do\n putStrLn $ if tprime n then \"YES\" else \"NO\"\n\n"}, {"source_code": "\nimport Control.Monad (forM_)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\n\nsqr :: Double -> Double\nsqr = sqrt\n\nisqrt :: Int64 -> Maybe Int64\nisqrt n = if r*r == n then Just r else Nothing\n where r = floor $ (sqr (fromIntegral n) )\n\ntprime :: Int64 -> Bool\ntprime n = \n case isqrt n of\n Nothing -> False\n Just r -> isPrime' r\n\nisPrime' :: Int64 -> Bool\nisPrime' n | n `mod` 2 == 0 = n == 2\nisPrime' n = all (\\m -> n `rem` m /= 0) [3,5..end]\n where end = floor (sqr (fromIntegral n))\n\nallTrue = all id\n\n(-->) = flip fmap\n\nreadInt :: BS.ByteString -> Integer\nreadInt s = case BS.readInteger s of\n Nothing -> error \"bad integer\"\n Just (n,_) -> n\n\nmain = do\n n <- getLine --> read\n let _ = n :: Int\n nums <- BS.getLine --> BS.words --> map (fromIntegral . readInt)\n forM_ nums $ \\n -> do\n putStrLn $ (if tprime n then \"YES\" else \"NO\") ++ \" \" ++ show n\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\ns-> (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInt).C.words <$> C.getLine))\nsolve::[Int]->IO()\nsolve (xs) =forM_ xs $ \\i-> let (n,f)= properFraction $ sqrt $ fromIntegral i in if (f==0) && (isPrime n) then putStrLn \"YES\" else putStrLn \"NO\"\nisPrime 1 = False\nisPrime 2 = True\nisPrime x = foldr (\\a b -> b && x `mod` a /=0) True [2..x-1]"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nisprime x = all (>0)[ mod x i|i<-[2..sx+1]]\n where sx = floor $ sqrt $ fromIntegral x\n\nnosquare x = sx*sx /=x\n where sx = floor $ sqrt $ fromIntegral x\nprocess s | nosquare s = \"NO\"\n | isprime s = \"YES\"\n | otherwise = \"NO\"\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map read <$> words <$> getLine::IO [Integer]\n mapM_ putStrLn $ map process q\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nisprime 4 =True\nisprime x = all (>0)[ mod sx i|i<-[2..ssx+1]]\n where sx = floor $ sqrt $ fromIntegral x\n ssx = floor $ sqrt $ fromIntegral sx\n\nnosquare x = sx*sx /=x\n where sx = floor $ sqrt $ fromIntegral x\n\nprocess s | nosquare s = \"NO\"\n | isprime s = \"YES\"\n | otherwise = \"NO\"\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map read <$> words <$> getLine::IO [Integer]\n mapM_ putStrLn $ map process q\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport qualified Data.HashMap.Strict as H\n\nisprime 4 =True\nisprime x = all (>0)[ mod sx i|i<-[2]++[3,5..ssx+1]]\n where sx = floor $ sqrt $ fromIntegral x\n ssx = floor $ sqrt $ fromIntegral sx\n\nnosquare x = sx*sx /=x\n where sx = floor $ sqrt $ fromIntegral x\n\nprocess 1 =\"NO\"\nprocess s | nosquare s = \"NO\"\n | isprime s = \"YES\"\n | otherwise = \"NO\"\n\nprocess1::[Int]->H.HashMap Int String->[String]->[String]\nprocess1 q m a | q==[] = reverse a\n | H.lookup (head q) m == Nothing = process1 (tail q) (H.insert (head q) (process (head q) ) m) ((process (head q )):a)\n | otherwise = process1 (tail q) m ((fromJust(H.lookup (head q) m)):a)\n\n\n\n\n\nmain=do\n n<- read <$> getLine::IO Int\n q<- map (fromIntegral. fst.fromJust.C.readInteger) <$> C.words <$> C.getLine::IO [Int]\n mapM_ putStrLn $ process1 q H.empty []\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nisprime x = all (>0)[ mod x i|i<-[2..sx+1]]\n where sx = floor $ sqrt $ fromIntegral x\n\nnosquare x = sx*sx ==x\n where sx = floor $ sqrt $ fromIntegral x\nprocess s | nosquare s = \"NO\"\n | isprime s = \"YES\"\n | otherwise = \"NO\"\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map read <$> words <$> getLine::IO [Integer]\n mapM_ putStrLn $ map process q\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getContents >>= mapM_ (putStrLn . yesno . solve . fromIntegral . fst . fromJust . B.readInt) . tail . B.words\n\nsolve :: Integer -> Bool\nsolve n = n == m * m && isPrime m\n where m = round (sqrt (fromIntegral n) :: Double)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3,5..]\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n > 1 && foldr (\\p r -> p * p > n || n `mod` p /= 0 && r) True primes\n"}, {"source_code": "import Data.List (group)\n\nmain :: IO ()\nmain = getContents >>= mapM_ (putStrLn . yesno) . solve . map read . tail . words\n\nsolve :: [Int] -> [Bool]\nsolve = map ((==3) . numberOfDivisors)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n\nprimes :: Integral a => [a]\nprimes = 2 : filter isPrime [3,5..]\n\nisPrime :: Integral a => a -> Bool\nisPrime n = n > 1 && foldr (\\p r -> p * p > n || n `mod` p /= 0 && r) True primes\n\nprimeFactors :: Integral a => a -> [a]\nprimeFactors n | n > 1 = go n primes\n | otherwise = []\n where go m ps@(p:t) | p * p > m = [m]\n | r == 0 = p : go q ps\n | otherwise = go m t\n where (q, r) = quotRem m p\n go _ _ = []\n\nnumberOfDivisors :: Integral a => a -> Int\nnumberOfDivisors = product . map ((+1) . length) . group . primeFactors\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Int\nimport Data.STRef\nimport qualified Data.Set as S\nmain = interact $ unlines . map (format . (`S.member` squares)) . map read . tail . words\nformat True = \"YES\"\nformat False = \"NO\"\nsquares = runST $ do\n sieve <- newArray (2,10^6) True :: ST s (STUArray s Int64 Bool)\n squares <- newSTRef S.empty\n forM_ [2..10^3] $ \\i -> do\n p <- readArray sieve i\n when p $ do\n modifySTRef' squares (S.insert (i^2 :: Int64))\n forM_ [2*i, 3*i..10^6] $ \\j -> writeArray sieve j False\n readSTRef squares\n"}, {"source_code": "import Data.List\n\nnubSorted :: Ord a => [a] -> [a]\nnubSorted [] = []\nnubSorted [x] = [x]\nnubSorted (x1:x2:xs) = if x1 == x2 then nubSorted (x2:xs) else x1 : nubSorted (x2:xs)\n\nisTPrime :: Int -> Bool\nisTPrime n = \n let root = (truncate . sqrt . fromIntegral $ n) :: Int\n subr = if root*root == n then 1 else 0\n in 3 == (2 * (length . nubSorted . sort $ \n filter (\\x -> mod n x == 0) [1..root]) - subr)\n\nisPrime :: Int -> Bool\nisPrime n | n < 2 = False\n | n == 2 = True\n | even n = False\n | otherwise = null $ filter (\\x -> mod n x == 0) [3,5..root]\n where\n root = (truncate . sqrt . fromIntegral $ n) :: Int\n\nisTPrime2 :: Int -> Bool\nisTPrime2 n =\n let root = (truncate . sqrt . fromIntegral $ n) :: Int\n in isPrime root && root * root == n\n\nmain = do\n n <- fmap (\\x -> read x :: Int) getLine\n xs <- (map read.words) `fmap` getLine\n mapM_ (\\x -> putStrLn (if isTPrime2 x then \"YES\" else \"NO\")) xs\n"}, {"source_code": "import Data.List\nimport Data.Word\n\nisPrime :: Word64 -> Bool\nisPrime n | n < 2 = False\n | n == 2 = True\n | even n = False\n | otherwise = null $ filter (\\x -> mod n x == 0) $ takeWhile (\\x -> x*x <= root) [3,5..root]\n where\n root = (truncate . sqrt . fromIntegral $ n) :: Word64\n\nisTPrime2 :: Word64 -> Bool\nisTPrime2 n =\n let root = (truncate . sqrt . fromIntegral $ n) :: Word64\n in isPrime root && (root * root == n)\n\nmain = do\n n <- getLine\n xs <- (map read.words) `fmap` getLine\n mapM_ (\\x -> putStrLn (if isTPrime2 x then \"YES\" else \"NO\")) xs\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Char\n\nsqu x = x==y*y && isprime y \n\twhere y = ceiling $ sqrt $ fromIntegral x\n\nprimes = [2,3,5,7,11] ++ (filter isprime [13,15..] )\nisprime 2 = True\nisprime x = all (>0) [mod x y| y<- takeWhile (<=(ceiling (sqrt (fromIntegral x)))) primes]\n\nmain= do\n\tn <- getLine \n\ts<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine ::IO [Integer]\n\tputStrLn $ intercalate \"\\n\" $ map (\\z-> if squ z then \"YES\" else \"NO\") s\n\t\n\t \n\t \n"}, {"source_code": "import Data.Int\n\nisPrime :: Int64 -> Bool\nisPrime n =\n if n `mod` 2 == 0\n then n == 2\n else not $ any (\\d -> n `mod` d == 0) [3,5..(floor.sqrt.fromIntegral) n]\n\nyn :: Bool -> [Char]\nyn True = \"YES\"\nyn False = \"NO\"\n\nisT :: Int64 -> Bool\nisT x = let s = floor $ sqrt $ fromIntegral x in s*s==x && isPrime s\n\nmain = do\n n <- getLine\n s_xs <- getLine\n putStr $ unlines $ map yn $ map isT $ map read $ words s_xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.is_square) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = or . map (==n) $ [foldl (*) sq (replicate x sq)| x <- [1..44]]\n where sq = round $ sqrt $ (fromIntegral n::Double)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = case filter (==n) $ [foldl (*) (sq x) (replicate (x-1) (sq x)) | x <- [2..40]] of\n [] -> False\n (s:_) -> True\n where sq x = round . (**(1/fromIntegral x)) $ (fromIntegral n::Double)\n \nisTPrime n = length (primeDivs n) == 1\nprimeDivs n = (filter (\\x -> n`mod`x == 0) \n $ takeWhile (\\x -> x < (round.(+1).(/2).fromIntegral $ n))\n $ primesList)\n--primesArr = listArray (1,227647) primesList :: UArray Int Int64\nprimesList = (primesToA.round.(+1).sqrt $ 10e12)\n\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n \n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\nimport Data.Set hiding (map)\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs \n \nf True = \"YES\";f False = \"NO\"\n\nisTPrime 4 = True\nisTPrime n\n | n`mod`2 == 0 = False\n | True = sq*sq == n && isPrime sq\n where sq = floor.sqrt.fromIntegral $ n\n\nisPrime n\n | n `mod` 24 /= 1 = False\n | True = n `member` primesSet\n \nprimesSet = fromList (primesToA.floor.(+1).sqrt $ 10e12)\n\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.is_square) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = or . map (==n) $ [foldl (*) (sq x) (replicate (x-1) (sq x)) | x <- [2..40]]\n where sq x = round . (**(1/fromIntegral x)) $ (fromIntegral n::Double)\n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = case filter (==n) $ [foldl (*) (sq x) (replicate (x-1) (sq x)) | x <- [2..40]] of\n [] -> False\n (s:_) -> True\n where sq x = round . (**(1/fromIntegral x)) $ (fromIntegral n::Double)\n \nisTPrime n = or (primeDivs n)\nprimeDivs n = map (c==) $ primesList\n where c = round.sqrt.fromIntegral $ n\n--primesArr = listArray (1,227647) primesList :: UArray Int Int64\nprimesList = (primesToA.round.(+1).sqrt $ 10e12)\n\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n \n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine\n mapM_ (putStrLn.f) xs\n \nf :: Int64 -> String \nf n\n | (round.sqrt.fromIntegral $ n)^2 == n = \"YES\"\n | True = \"NO\""}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.is_square) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = sq * sq == n\n where sq = floor $ sqrt $ (fromIntegral n::Double)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\nimport Data.Set hiding (map)\n\nmain = do\n let\n primesSet = fromList primesList\n primesList = primesToA.floor.(+1).sqrt $ 10e12\n isPrime n\n | not . or . map ((==0).(n`mod`)) $ take 1000 primesList = False\n | True = n `member` primesSet\n isTPrime 4 = True\n isTPrime 9 = True\n isTPrime n\n | n`mod`2 == 0 = False\n | n`mod`24 /= 1 = False\n | True = sq*sq == n && isPrime sq\n where sq = round.sqrt.fromIntegral $ n\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs\n \nf True = \"YES\";f False = \"NO\"\n\n\n\nisPrime n\n |not. or . map ((==0).(n`mod`)) $ take 1000 primesList = False\n | True = n `member` primesSet\n \nprimesSet = fromList primesList\nprimesList = primesToA.floor.(+1).sqrt $ 10e12\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\n \nmain = do\n n <- fmap read getLine :: IO Int64\n xs <- fmap (map read . words) getLine\n mapM_ (putStrLn.sln) xs\n \nsln p = \n case (fromIntegral $ j*j)>b && b*b==a && a>1.0 of\n True -> \"YES\"\n False -> \"NO\"\n where\n c' acc\n | (round b)`mod`acc == 0 = acc\n | fromIntegral (acc*acc)<=b = acc\n | True = c' (acc+1)\n a = fromIntegral p\n b = sqrt a :: Double\n j = (c' 2) :: Int64 "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = case filter (==n) $ [foldl (*) (sq x) (replicate (x-1) (sq x)) | x <- [2..40]] of\n [] -> False\n (s:_) -> True\n where sq x = round . (**(1/fromIntegral x)) $ (fromIntegral n::Double)\n \nisTPrime n = length (primeDivs n) == 2\nprimeDivs n = filter (\\x -> n`mod`x == 0) primesList\n--primesArr = listArray (1,227647) primesList :: UArray Int Int64\nprimesList = 2 : (primesToA.round.(+1).sqrt $ 10e12)\n\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n \n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.is_square) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = or . map (==n) $ [foldl (*) sq (replicate x sq)| x <- [1..44]]\n where sq = floor $ sqrt $ (fromIntegral n::Double)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square 1 = False\nis_square n = case filter (==n) $ [foldl (*) (sq x) (replicate (x-1) (sq x)) | x <- [2..40]] of\n [] -> False\n (s:_) -> True\n where sq x = round . (**(1/fromIntegral x)) $ (fromIntegral n::Double)\n \nisTPrime n = length (primeDivs n) == 3\nprimeDivs n = 1 : filter (\\x -> n`mod`x == 0) primesList\n--primesArr = listArray (1,227647) primesList :: UArray Int Int64\nprimesList = (primesToA.round.(+1).sqrt $ 10e12)\n\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n \n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\nimport Data.Set hiding (map)\n\nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.isTPrime) xs \n \nf True = \"YES\";f False = \"NO\"\n\nisTPrime 4 = True\nisTPrime n\n | n`mod`2 == 0 = False\n | n`mod`24 /= 1 = False\n | True = sq*sq == n && isPrime sq\n where sq = floor.sqrt.fromIntegral $ n\n\nisPrime = (`member` primesSet)\n \nprimesSet = fromList (primesToA.floor.(+1).sqrt $ 10e12)\n\nprimesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]\n :: UArray Int64 Bool)\n where\n sieve p a \n | p*p > m = 2 : [i | (i,True) <- assocs a]\n | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]\n | otherwise = sieve (p+2) a\n "}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Int\nimport Data.Array.Unboxed\n \nmain = do\n n <- fmap read getLine\n xs <- fmap (take n . map read . words) getLine :: IO [Int64]\n mapM_ (putStrLn.f.is_square) xs\n \nf True = \"YES\"\nf False = \"NO\" \n \nis_square n = sq * sq == n\n where sq = floor $ sqrt $ (fromIntegral n::Double)"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\n\n-- Meat\n\nsolve :: [Integer] -> [String]\nsolve = map (\\x -> if isSquare x && x /= 1 then \"YES\" else \"NO\")\n\nisSquare :: Integer -> Bool\nisSquare n = sq * sq == n\n where sq = floor $ sqrt (fromIntegral n::Double)\n\n-- Shit\nmain :: IO ()\nmain = do\n [_, xs] <- readShit\n printShitV $ solve xs\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents\n\ninstance Shit [[Integer]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents"}], "src_uid": "6cebf9af5cfbb949f22e8b336bf07044"} {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)] -> [Bool]\nsolve n k stations queries = map query' queries \n where\n minStationIndices :: IM.IntMap Int\n minStationIndices = IM.fromListWith min $ L.zip stations [1 .. n]\n\n maxStationIndices :: IM.IntMap Int\n maxStationIndices = IM.fromListWith max $ L.zip stations [1 .. n]\n\n query' :: (Int, Int) -> Bool\n query' (from, to) = fromMaybe False $ do\n minFromIndex <- IM.lookup from minStationIndices\n maxToIndex <- IM.lookup to maxStationIndices\n return $ minFromIndex <= maxToIndex\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n B8.getLine\n [n, k] <- B8.getLine <&> readIntB8s\n stations <- B8.getLine <&> readIntB8s\n queries <- replicateM k $ do\n [from, to] <- B8.getLine <&> readIntB8s\n return (from, to)\n let answers = solve n k stations queries\n forM_ answers putsYesNo\n\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport Data.Bool\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Containers.ListUtils\r\nimport Data.List\r\nimport qualified Data.Map.Lazy as M\r\nimport Data.Maybe\r\n\r\nsolve :: ([Integer], [(Integer, Integer)]) -> [Bool]\r\nsolve (us, qs) = map solve' qs\r\n where\r\n us' = nubOrd us\r\n usrev = reverse us\r\n n = length us\r\n\r\n fs = M.fromList $ zip usrev [n - 1, n - 2 ..]\r\n ls = M.fromList $ zip us [0 ..]\r\n\r\n solve' (a, b) = case (<=) <$> fs M.!? a <*> ls M.!? b of\r\n Just True -> True\r\n _ -> False\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\ninput :: Scanner ([Integer], [(Integer, Integer)])\r\ninput = do\r\n n <- int\r\n k <- int\r\n us <- n >< integer\r\n qs <- k >< ((,) <$> integer <*> integer)\r\n pure (us, qs)\r\n\r\noutput :: [Bool] -> C.ByteString\r\noutput = C.intercalate \"\\n\" . map (bool \"NO\" \"YES\")\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.IntMap.Strict as M\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let problems = take t $ sep $ lines input\n let sols = problems >>= (map format . solve . parse)\n mapM_ putStrLn sols\n\nsep [] = []\nsep (_:x:y:xs) = (y,h):(sep t)\n where (h,t) = splitAt (read $ last $ words x) xs\n\nparse :: (String, [String]) -> ([Int],[(Int,Int)])\nparse (y,h) = (us,qs)\n where us = map read $ words y\n qs = map parseQ $ h\n parseQ = first2 . (map read) . words\n first2 (a:b:_) = (a,b)\n\nformat b\n | b = \"YES\"\n | otherwise = \"NO\"\n\nsolve (us,qs) = map (solve1 fs) qs\n where fs = M.fromListWith phi $ zip us (map dupe [0..])\n dupe x = (x,x)\n phi (x1,y1) (x2,y2) = (min x1 x2, max x1 x2)\n\nsolve1 fs (a,b)\n | Just (i,_) <- s, Just (_,j) <- t = i < j\n | otherwise = False\n where [s,t] = map (fs M.!?) [a,b]\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Map.Strict qualified as Map\r\nimport Data.Maybe\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n \r\nshowYN False = \"NO\"\r\nshowYN True = \"YES\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [] <- ri\r\n [_n,k] <- ri\r\n us <- ri\r\n qs <- replicateM k ri\r\n return (us, qs)\r\n mapM_ (putStr . unlines . map showYN . solve) tcs\r\n\r\nsolve (us, qs) = map reachable qs\r\n where\r\n rt = Map.fromListWith minMax . (`zip`dinds) $ us\r\n \r\n (!?) = (Map.!?)\r\n reachable [a,b] = fromMaybe False $ liftA2 isOrdered (rt!?a) (rt!?b)\r\n reachable _ = error \"Pair expected in query\"\r\n \r\n isOrdered (leMin,_leMax) (_riMin,riMax) = (leMin <= riMax)\r\n\r\ninds = [0..] :: [Int]\r\ndinds = map (id &&& id) inds\r\n\r\nminMax (a,b) (c,d) = (min a c, max b d)\r\n"}], "negative_code": [], "src_uid": "44ce2a46e89789b9c1c63e5452f3159b"} {"source_code": "main :: IO ()\nmain = do\n n <- fmap read getLine\n putStrLn $ unwords $ map show $ take n [n ..]\n", "positive_code": [{"source_code": "import Control.Applicative((<$>))\n\nmain :: IO ()\nmain = unwords <$> map show <$> (\\x -> take x $ [x..]) <$> read <$> getLine >>= putStrLn\n"}, {"source_code": "\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n n <- readLn\n putStrLn $ intercalate \" \" $ map show [n + 1 .. 2 * n]"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.Set as Set\nimport qualified Data.Array.ST.Safe as A\nimport Control.Monad.ST.Safe\nimport Prelude\nimport qualified Data.ByteString.Char8 as B8\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nsolve :: Int -> [Int]\nsolve n = take n [(n + 1) ..]\n\nmain :: IO ()\nmain = do\n n <- readB8Int <$> B8.getLine\n let answer = solve n\n forM_ answer $ printf \"%d \""}, {"source_code": "main :: IO ()\nmain = readLn >>= putStrLn . unwords . map show . solve\n\nsolve :: Integer -> [Integer]\nsolve n = [n .. 2 * n - 1]\n"}, {"source_code": "main=interact$unwords.map show.f.read\nf n=[n..2*n-1]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\n\nmain = do\n n <- readLn\n putStr.unwords.map show $ take n primes\n\nprimes :: [Int]\nprimes = 2:[2*i+1|i<-[1.. 10000000 `quot`2], unsafeAt isPrime i]\n where\n !lim = (10000000 + 0xfffff * 0xfffff -1)`quot` 0xfffff * 0xfffff\n !isPrime = runSTUArray $ do\n isp <- newArray (0,lim`quot`2) True :: ST s (STUArray s Int Bool)\n forM_ [0, 0xfffff ..lim - 0xfffff] $ \\l-> do\n let !l2 = l`quot`2\n !r = l + 0xfffff\n !r2 = r`quot`2\n forM_ [1..intSqrt r`quot`2] $ \\i-> do\n flg <- unsafeRead isp i\n when flg $ do\n let !p = 2*i+1\n !ip1=i*(p+1)\n go !i = when (i Int\nintSqrt x = floor . sqrt $ fromIntegral x"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int\ngetInt = readInt <$> C.getLine\n\nmain :: IO ()\nmain = do\n n <- getInt\n putStrLn $ unwords $ map show $ take n [n..]\n"}, {"source_code": "#!/usr/bin/env runghc\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve (n:ns) = [unwords . map show . take (read n) $ p]\np = 2:f [3] [3,5..]\n where f (x:xs) ys = let (ps, qs) = span (< x^2) ys\n in ps ++ f (xs ++ ps) [z | z <- qs, mod z x /= 0]\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n putStrLn $ rush n\n\nlarge :: Int\nlarge = 1000000\n\nrush :: Int -> String\nrush n = (unwords . map show) [(large - n + 1)..large]\n"}], "negative_code": [], "src_uid": "c047040426e736e9085395ed9666135f"} {"source_code": "import Control.Arrow ((>>>))\nimport Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve = minimum . foldl upd (replicate 201 0) . sort\n\nupd dp x = scanl1 min . zipWith (+) (inf : dp) . map (abs . (x -)) $ [0 ..] {- -}\n\ninf = 10 ^ 9\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve = minimum . foldl upd (replicate 201 0) . sort\n where\n upd dp x = scanl1 min . zipWith (+) (inf : dp) . map (abs . (x -)) $ [0 ..]\n inf = 10 ^ 9\n"}], "negative_code": [], "src_uid": "27998621de63e50a7d89cb1c1e30f67c"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function\nimport Data.Array.Unboxed\n-- import Data.ByteString (ByteString)\n-- import qualified Data.ByteString.Char8 as C\n-- import Data.ByteString.Char8 ()\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as IntMap\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n\nmyread = fromIntegral::Int -> Int64\nmain = do\n s <- map (myread . digitToInt) <$> getLine\n print $ solve s \n\nsolve :: [Int64] -> Int64\nsolve xs = go (reverse xs) 0 (pred . myread $! length xs) where\n go [x] v _ = v + divisible x\n go (x:y:xs) v l = go (y:xs) (v + divisible x + if (x+10*y)`mod`4==0 then l else 0::Int64) (pred l)\n divisible x = if x`mod`4==0 then 1::Int64 else 0::Int64", "positive_code": [{"source_code": "\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Data.Char\n\nmain = do\n nums' <- B.unpack <$> B.getLine\n let nums = filter isDigit nums'\n let\n l1 :: Integer\n l1 = fromIntegral . length . filter (\\c -> c == '0' || c == '4' || c == '8') $ nums\n idxs _ [] = []\n idxs _ [_] = []\n idxs idx (a:b:xs)\n | (read $ [a, b]) `mod` 4 == 0 = idx:(idxs (idx+1) (b:xs))\n | otherwise = idxs (idx+1) (b:xs)\n fidx = idxs 1 nums\n l2 :: Integer\n l2 = sum fidx\n putStrLn . show $ l1+l2\n\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.Char (ord)\n\nsolve :: String -> Integer\nsolve number = fst3 $ foldl aggr (0,0,0) number\n where aggr (total,pos,last2) digit = (total',pos',last2')\n where total' = total + totalInc\n pos' = pos + 1\n totalInc = if divisibleBy4 last2'\n then 1 -- the whole number ...xy up to pos'\n + max 0 (pos' - 2) -- all prefixes of the xy number\n + if divisibleBy4 digit' && pos' >= 2\n then 1 -- number y\n else 0\n else if divisibleBy4 digit'\n then 1\n else 0\n last2' = (last2 `mod` 10) * 10 + digit'\n digit' = fromIntegral $ ord digit - ord '0'\n fst3 (x,_,_) = x\n divisibleBy4 x = x `mod` 4 == 0\n\nmain :: IO ()\nmain = do\n number <- getLine\n putStrLn $ show $ solve number\n\n{-\n5\n58 -> 8\n581\n5810 -> 0\n58104 -> 58104, 8104, 104, 04, 4\n581043\n5810438 -> 8\n58104381\n581043817\n5810438174 -> 4\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List (tails)\nimport Data.Char (ord)\nimport Data.Int (Int64)\n\nmain = do\n s <- getLine\n\n let\n r = sum $ map f $ zip (init $ tails $ reverse s) (reverse [1..length s])\n where\n f :: (String, Int) -> Int64\n f ([a], i) = if (ord a - 48) `mod` 4 == 0 then 1 else 0\n f ((a:b:_), l) =\n (if (ord a - 48) `mod` 4 == 0 then 1 else 0) +\n (if ((ord b - 48) * 10 + ord a - 48) `mod` 4 == 0 then (fromIntegral l) - 1 else 0)\n\n print r\n"}, {"source_code": "import Data.List\nmain=interact$show.f.map ((read::String->Int).(:[])).reverse.head.lines\nf::[Int]->Integer\nf a=p a 0 (toInteger(length a))\np::[Int]->Integer->Integer->Integer\np [a] b _=if mod a 4 == 0 then (b+1) else b\np (a:b:c) d e=if mod a 4 == 0 then (if mod (a+b*10) 4 == 0 then p (b:c) (d+e) (e-1) else p (b:c) (d+1) (e-1))else(if mod (a+b*10) 4 == 0 then p (b:c) (d+e-1) (e-1) else p (b:c) d (e-1))"}, {"source_code": "import Data.List\nmain=interact$show.f.map (read.(:[])).reverse.head.lines\nf::[Int]->Integer\nf a=p a 0 (toInteger(length a))\np [a] b _=if mod a 4 == 0 then (b+1) else b\np (a:b:c) d e=if mod a 4 == 0 then (if mod (a+b*10) 4 == 0 then p (b:c) (d+e) (e-1) else p (b:c) (d+1) (e-1))else(if mod (a+b*10) 4 == 0 then p (b:c) (d+e-1) (e-1) else p (b:c) d (e-1))"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = interact $ show . sol . head . words\n\nsol nums = l1+l2\n where\n l1 :: Integer\n l1 = fromIntegral . length . filter (\\c -> c == '0' || c == '4' || c == '8') $ nums\n idxs _ [] = []\n idxs _ [_] = []\n idxs idx (a:b:xs)\n | (read $ [a, b]) `mod` 4 == 0 = idx:(idxs (idx+1) (b:xs))\n | otherwise = idxs (idx+1) (b:xs)\n fidx = idxs 1 nums\n l2 :: Integer\n l2 = sum fidx\n"}], "negative_code": [{"source_code": "import Data.List\nmain=interact$show.f.map read .group.reverse.head.lines\nf::[Int]->Integer\nf a=p a 0 (toInteger(length a))\np::[Int]->Integer->Integer->Integer\np [a] b _=if mod a 4 == 0 then (b+1) else b\np (a:b:c) d e=if mod a 4 == 0 then (if mod (a+b*10) 4 == 0 then p (b:c) (d+e) (e-1) else p (b:c) (d+1) (e-1))else(if mod (a+b*10) 4 == 0 then p (b:c) (d+e-1) (e-1) else p (b:c) d (e-1))"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do\n nums <- B.unpack <$> B.getLine\n let\n l1 :: Integer\n l1 = fromIntegral . length . filter (\\c -> c == '0' || c == '4' || c == '8') $ nums\n idxs _ [] = []\n idxs _ [_] = []\n idxs idx (a:b:xs)\n | (read $ [a, b]) `mod` 4 == 0 = idx:(idxs (idx+1) (b:xs))\n | otherwise = idxs (idx+1) (b:xs)\n fidx = idxs 1 nums\n l2 :: Integer\n l2 = sum fidx\n putStrLn . show $ l1+l2\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do\n nums <- B.unpack <$> B.getLine\n let\n l1 :: Integer\n l1 = fromIntegral . length . filter (\\c -> c == '0' || c == '4' || c == '8') $ nums\n idxs _ [] = []\n idxs _ [_] = []\n idxs idx (a:b:xs)\n | (read $ [a, b]) `mod` 4 == 0 = idx:(idxs (idx+1) (b:xs))\n | otherwise = idxs (idx+1) (b:xs)\n fidx = idxs 1 nums\n l2 :: Integer\n l2 = sum fidx\n putStrLn . show $ l1+l2\n"}, {"source_code": "\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do\n nums <- B.unpack <$> B.getLine\n let\n l1 = length . filter (\\c -> c == '0' || c == '4' || c == '8') $ nums\n idxs _ [] = []\n idxs _ [_] = []\n idxs idx (a:b:xs)\n | (read $ [a, b]) `mod` 4 == 0 = idx:(idxs (idx+1) (b:xs))\n | otherwise = idxs (idx+1) (b:xs)\n fidx = idxs 1 nums\n l2 = sum fidx\n putStrLn . show $ l1+l2\n"}], "src_uid": "c7d48d2c23ff33890a262447af5be660"} {"source_code": "import Data.Char\n\nfromLeft ('1':rest) = '1':(fromLeft rest)\nfromLeft ('0':rest) = '1':rest\n\nupdate :: String -> Char -> String\nupdate roomstates 'L' = fromLeft roomstates\nupdate roomstates 'R' = reverse . fromLeft . reverse $ roomstates\nupdate roomstates charN = leftPart ++ ['0'] ++ rightPart\n where \n n = ord(charN) - ord('0')\n (splitedl, splitedr) = splitAt n roomstates\n rightPart = tail splitedr\n leftPart = splitedl\n \nmain :: IO ()\nmain = do\n getLine\n eventSeries <- getLine\n putStrLn $ foldl update \"0000000000\" eventSeries", "positive_code": [{"source_code": "import Data.List\n\ndata Event = EnterLeft | EnterRight | Leave Int\ndata RoomStatus = Free | Occupied deriving (Eq)\ntype HotelStatus = [RoomStatus]\n\ninstance Show RoomStatus where\n show Free = \"0\"\n show Occupied = \"1\"\n\nshowHotelStatus :: HotelStatus -> String\nshowHotelStatus [] = \"\"\nshowHotelStatus (x:xs) = (show x) ++ (showHotelStatus xs)\n\ngetEvent :: Char -> Event\ngetEvent ch\n | ch == 'L' = EnterLeft\n | ch == 'R' = EnterRight\n | otherwise = Leave (read [ch])\n\ntryToOccupy :: (RoomStatus, Bool) -> (RoomStatus, Bool)\ntryToOccupy original@(status, needToOccupy)\n | status == Free && needToOccupy = (Occupied, False)\n | otherwise = original\n\nchange :: Event -> HotelStatus -> HotelStatus\nchange EnterLeft status =\n let pairs = scanl (\\(_, needed) roomStatus -> tryToOccupy (roomStatus, needed)) (Occupied, True) status\n in map fst (tail pairs)\nchange EnterRight status =\n let pairs = scanr (\\roomStatus (_, needed) -> tryToOccupy (roomStatus, needed)) (Occupied, True) status\n in map fst (init pairs)\nchange (Leave roomNumber) status = map (\\(num, roomStatus) -> if num == roomNumber then Free else roomStatus) (zip [0..] status)\n\nsolve :: [Event] -> HotelStatus\nsolve events =\n let hotelStatus = take 10 (repeat Free)\n in foldl (\\status event -> change event status) hotelStatus events\n\nmain = do\n getLine\n events <- (map getEvent) <$> getLine\n putStrLn . showHotelStatus . solve $ events\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\n\n\nupdl x = (takeWhile (==1) x) ++[1] ++ (tail (dropWhile (==1) x))\nupdr x = reverse $ updl $ reverse x\nupd x a = (take a1 x) ++ [0] ++ (drop (a1+1) x)\n\twhere a1 = digitToInt a\n\n\nprocess x [] = x\nprocess x (a:as) | a=='L' = process (updl x) as\n | a=='R' = process (updr x) as\n\t\t | otherwise = process (upd x a) as\n\nmain = do\n\t\tn<-getLine\n\t\tx<-getLine\n\t\tputStrLn $ concat $ map show $ process [0,0,0,0,0,0,0,0,0,0] x\n"}], "negative_code": [], "src_uid": "a6cbf01d72d607ca95fe16df4fb16693"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Monad (foldM, forM, forM_, replicateM)\nimport Control.Monad.ST (ST, runST)\nimport Control.Monad.State (State, evalState, get, put)\nimport Data.Array.ST (STUArray, newArray, readArray, writeArray)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List (groupBy, sort, sortBy)\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.pack <$> testCase)\n\ntestCase :: Scanner String\ntestCase = do\n n <- int\n k <- int\n cs <- (n * k) >< int\n return . unlines $ do\n (a, b) <- solve n k cs\n return $ show a ++ \" \" ++ show b\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)]\nsolve n k =\n map (\\(l, r, _) -> (l, r))\n . sortOn thd3\n . pick\n . sortOn snd3\n . map (\\((c, l), (_, r)) -> (l, r, c))\n . concatMap adjacents\n . groupOn fst\n . sort\n . (`zip` [1 ..])\n where\n nk = n * k\n fmax = 1 + (n - 1) `div` (k - 1)\n pick xs = runST $ do\n fs <- newArray (1, nk) 0 :: ST s (STUArray s Int Int)\n cs <- newArray (1, n) False :: ST s (STUArray s Int Bool)\n foldM' [] xs $ \\ranges (l, r, c) -> do\n done <- readArray cs c\n mf <- maximum <$> forM [l .. r] (readArray fs)\n if not done && mf + 1 <= fmax\n then do\n writeArray cs c True\n forM_ [l .. r] $ \\i -> do\n v <- readArray fs i\n writeArray fs i (v + 1)\n return $ (l, r, c) : ranges\n else do\n return ranges\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn p = groupBy (\\u v -> p u == p v)\n\nsortOn :: Ord b => (a -> b) -> [a] -> [a]\nsortOn = sortBy . comparing\n\nfoldM' :: (Foldable t, Monad m) => b -> t a -> (b -> a -> m b) -> m b\nfoldM' b ta f = foldM f b ta\n\nfst3 :: (a, b, c) -> a\nfst3 (a, _, _) = a\nsnd3 :: (a, b, c) -> b\nsnd3 (_, b, _) = b\nthd3 :: (a, b, c) -> c\nthd3 (_, _, c) = c\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ntimes, (><) :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n(><) = times\n\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (foldM, foldM_, forM, forM_, guard, replicateM, unless, when)\r\nimport Control.Monad.ST (ST, runST)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport Data.Array.ST (STUArray, newArray, readArray, writeArray)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List (groupBy, sort, sortBy)\r\nimport Data.Maybe (fromJust)\r\nimport Data.Ord (comparing)\r\nimport Debug.Trace (trace)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (C.pack <$> testCase)\r\n\r\ntestCase :: Scanner String\r\ntestCase = do\r\n n <- int\r\n k <- int\r\n cs <- (n * k) >< int\r\n return . unlines $ do\r\n (a, b) <- solve n k cs\r\n return $ show a ++ \" \" ++ show b\r\n\r\nsolve :: Int -> Int -> [Int] -> [(Int, Int)]\r\nsolve n k =\r\n map (\\(l, r, _) -> (l, r))\r\n . sortOn thd3\r\n . pick\r\n . sortOn snd3\r\n . map (\\((c, l), (_, r)) -> (l, r, c))\r\n . concatMap adjacents\r\n . groupOn fst\r\n . sort\r\n . (`zip` [1 ..])\r\n where\r\n nk = n * k\r\n fmax = 1 + (n - 1) `div` (k - 1)\r\n pick xs = runST $ do\r\n fs <- newArray (1, nk) 0 :: ST s (STUArray s Int Int)\r\n cs <- newArray (1, n) False :: ST s (STUArray s Int Bool)\r\n foldM' [] xs $ \\ranges (l, r, c) -> do\r\n done <- readArray cs c\r\n mf <- maximum <$> forM [l .. r] (readArray fs)\r\n if not done && mf + 1 <= fmax\r\n then do\r\n writeArray cs c True\r\n forM_ [l .. r] $ \\i -> do\r\n v <- readArray fs i\r\n writeArray fs i (v + 1)\r\n return $ (l, r, c) : ranges\r\n else do\r\n return ranges\r\n\r\nadjacents xs = zip xs (tail xs)\r\ngroupOn p = groupBy (\\u v -> p u == p v)\r\nsortOn = sortBy . comparing\r\n\r\nfoldM' b ta f = foldM f b ta\r\n\r\nfst3 (x, _, _) = x\r\nsnd3 (_, y, _) = y\r\nthd3 (_, _, z) = z\r\n\r\ndebug a = trace (show a) a\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}, {"source_code": "import Control.Monad\r\nimport Control.Monad.State\r\nimport Data.Array\r\nimport Data.List\r\nimport qualified Data.IntMap as IM\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Sequence as Seq\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readMany :: IO [Int]\r\n xa <- listArray (1, n * k) <$> readMany\r\n let lim = (n + k - 2) `div` (k - 1)\r\n go :: IS.IntSet -> Int -> IM.IntMap Int -> State (Seq.Seq Int) [(Int, Int, Int)]\r\n go pend i prv\r\n | IS.null pend = return []\r\n | i == n * k + 1 = go pend 1 IM.empty\r\n | x `IS.notMember` pend = go pend (i + 1) prv\r\n | otherwise = go' $ x `IM.lookup` prv\r\n where\r\n x = xa!i\r\n prv' = IM.insert x i prv\r\n go' Nothing = go pend (i + 1) prv'\r\n go' (Just j) = do\r\n m <- gets $ maximum . (<$> [j..i]) . Seq.index\r\n if m >= lim\r\n then go pend (i + 1) prv'\r\n else do\r\n mapM_ (modify . Seq.adjust' (+1)) [j..i]\r\n ((x, j, i):) <$> go (x `IS.delete` pend) (i + 1) prv\r\n rs = evalState (go (IS.fromList [1..n]) 1 IM.empty) $ Seq.fromFunction (n * k + 1) $ const 0\r\n putStr $ unlines $ map (\\(_, i, j) -> show i ++ \" \" ++ show j) $ sort rs\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Function\n\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, k] <- readInts\n c <- readInts\n let\n cr :: Array Int (UArray Int Int)\n cr = fmap (listArray (1, k) . ($ [])) $ accumArray (.) id (1, n) $ do\n (i, ci) <- zip [1 ..] c\n pure (ci, (i :))\n chunkSize = ceilDiv n (k - 1)\n extract :: ([Int], [Int]) -> Int -> ([Int], [Int])\n extract (_, is) j = splitAt chunkSize $ sortOn (\\i -> cr ! i ! j) is\n\n vals :: [[Int]]\n vals = map fst $ tail $ scanl extract ([], [1 .. n]) [2 .. k]\n ans :: Array Int (Int, Int)\n ans = array (1, n) $ do\n (j, is) <- zip [2 ..] vals\n i <- is\n pure (i, (cr ! i ! (j - 1), cr ! i ! j))\n forM_ (elems ans) $ \\(ai, bi) -> putInts [ai, bi]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "ada7340984ca02702146e7b2ab71f194"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.Array.ST(runSTArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, foldM)\r\nimport Data.Maybe\r\n\r\nnumOcc :: Ord a => [a] -> M.Map a Integer\r\nnumOcc (x:xs) = let m = numOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m \r\n\tNothing -> M.insert x 1 m \r\nnumOcc [] = M.empty\r\n\r\n\r\nnumOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer\r\nnumOcc' size list = runSTArray $ do \r\n\tarray <- MA.newArray size 0 \r\n\tlet addElem action a = do \r\n\t\ti <- MA.readArray array a\r\n\t\tMA.writeArray array a (i+1) \r\n\tfoldM addElem () list\r\n\treturn $ array\r\n\r\ninsertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]\r\ninsertWithList a b m = case M.lookup a m of \r\n\tJust l -> M.insert a (b:l) m \r\n\tNothing -> M.insert a [b] m \r\n\r\ndeleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]\r\ndeleteWithList a m = case M.lookup a m of \r\n\tJust (x:y:xs) -> M.insert a (y:xs) m\r\n\tJust [x] -> M.delete a m\r\n\r\n\r\nsolve :: Integer -> Integer -> [Integer] -> [Integer] -> Integer\r\nsolve na nb a b = div result 2 where\r\n\tdeg_a = numOcc' (0, na) a\r\n\r\n\tdeg_b = numOcc' (0, nb) b\r\n\r\n\tn = toInteger $ length a\r\n\r\n\r\n\tedges = zip a b\r\n\r\n\tsum_deg_b = foldr (+) 0 deg_b\r\n\r\n\tresult = sum $ fmap (\\(a, b) -> sum_deg_b + 1 - (deg_a ! a) - (deg_b ! b)) edges\r\n\r\n\r\n\r\nplotResult i = print i\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[na, nb, _] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\ta <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\tb <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\tplotResult $ solve na nb a b\r\n", "positive_code": [{"source_code": "-- Trying to use only ByteString I/O with a state monad this contest\n\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Int\nimport Data.List\n\ngetSLine :: Monad m => StateT P.ByteString m P.ByteString\ngetSLine = do\n (out, next) <- P.break (== '\\n') <$> get\n put $ P.tail next\n pure out\n\nreadInts :: Monad m => StateT P.ByteString m [Int]\nreadInts = do\n currLine <- getSLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\n-- There has to be a combinator for this. But where?\noutLine :: P.ByteString -> StateT P.ByteString IO ()\noutLine v = StateT $ \\s -> ((), s) <$ P.putStrLn v\n\nmain :: IO ()\nmain = (P.getContents >>=) $ evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [a, b, k] <- readInts\n ai <- readInts\n bi <- readInts\n let\n nc2 :: Int -> Int64\n nc2 x = let y = fromIntegral x in div (y * (y-1)) 2\n excl :: [Int] -> Int64\n excl li = sum $ [nc2 $ length s | s <- group $ sort li]\n ans :: Int64\n ans = nc2 k - sum (excl <$> [ai, bi])\n outLine . P.pack $ show ans\n"}], "negative_code": [], "src_uid": "14ce451a31c0dbc2b2f4e04a939b199d"} {"source_code": "import Data.List\n\nmain = do\n t <- getLine\n p <- getLine\n a <- fmap (map read . words) getLine\n print $ f 0 (length t - length p) (zip [1..] t) p (sort $ zip a [1..])\n\nf l r _ _ _ | l == r = l\nf l r t p a =\n if h t' p\n then f m r t p a\n else f l (m - 1) t p a\n where m = div (l + r + 1) 2\n t' = g t a m\n\ng t [] _ = t\ng ((i,j):t) ((x,y):a) m | y > m = g ((i,j):t) a m\n | i == x = g t a m\n | i < x = (i,j):g t ((x,y):a) m\n | i > x = (i,j):g t a m\n\nh _ [] = True\nh [] _ = False\nh ((_,j):t) (p:q) | p == j = h t q\n | p /= j = h t (p:q)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n t <- getLine\n p <- getLine\n ps <- map readInt.B.words <$> B.getLine\n print $ solve t p ps\n\nsolve :: String -> String -> [Int] -> Int\nsolve t p ps = upperBound predicate 0 (length t)\n where\n predicate i = go 1 t p\n where\n !invalid = IS.fromList $ take i ps\n go i (x:xs) (y:ys)\n | x == y && IS.notMember i invalid = go (i+1) xs ys\n | otherwise = go (i+1) xs (y:ys)\n go _ _ [] = True\n go _ _ _ = False\n\n\nupperBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nupperBound p low high = go low high\n where\n go !low !high\n | high <= low = low\n | p mid = go mid high\n | otherwise = go low (mid - 1)\n where\n mid = (low + high + 1) `quot` 2\n{-# INLINE upperBound #-}"}], "negative_code": [], "src_uid": "0aed14262c135d1624df9814078031ae"} {"source_code": "import Data.List\nimport Data.Array\n\nmain = do\n [n, m, k] <- fmap (map (read::String->Int) . words) getLine\n v <- fmap (map (read::String->Int) . words) getLine\n\n let ans = binarySearch m k v n (-1)\n putStrLn $ show $ n-ans\n\nbinarySearch:: Int -> Int -> [Int] -> Int -> Int -> Int\nbinarySearch m k v l r\n | l == r+1 = l\n | otherwise = if pack m k (drop mid v)\n then binarySearch m k v mid r\n else binarySearch m k v l mid\n where mid = (l + r) `div` 2\n\npack:: Int -> Int -> [Int] -> Bool\npack m k v = (snd $ foldl' f (k, m-1) v) >= 0\n where f (x,y) z\n | z > k = (0, -1)\n | z > x = (k-z, y-1)\n | otherwise = (x-z, y)", "positive_code": [{"source_code": "main = do\n [n, m, k] <- fmap (map (read::String->Int) . words) getLine\n v <- fmap (map (read::String->Int) . words) getLine\n\n let ans = binarySearch m k v n (-1)\n putStrLn $ show $ n-ans\n\nbinarySearch:: Int -> Int -> [Int] -> Int -> Int -> Int\nbinarySearch m k v l r\n | l == r+1 = l\n | otherwise = if pack m k (drop mid v)\n then binarySearch m k v mid r\n else binarySearch m k v l mid\n where mid = (l + r) `div` 2\n\npack:: Int -> Int -> [Int] -> Bool\npack m k v = (snd $ foldl f (k, m-1) v) >= 0\n where f (x,y) z\n | z > k = (0, -1)\n | z > x = (k-z, y-1)\n | otherwise = (x-z, y)"}], "negative_code": [], "src_uid": "869f8763211a7771ecd73d56b5c34479"} {"source_code": "import Control.Monad (forM_)\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\nimport Data.List (sort)\r\nimport Data.Maybe (fromJust)\r\n\r\nreadInt = fst . fromJust . BS8.readInt\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs@(x : _) = go xs 0 x\r\n where\r\n go (x : xs) delta best = do\r\n let y = x + delta\r\n go xs (delta - y) (max best y)\r\n go [] delta best = best\r\nsolve [] = -1\r\n\r\nmain = do\r\n n <- readInt <$> BS.getLine\r\n forM_ [1 .. n] $ \\_ -> do\r\n _ <- BS.getLine\r\n xs <- sort . map readInt . BS8.words <$> BS.getLine\r\n print $ solve xs\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = do\n t <- fst . fromJust . B.readInt <$> B.getLine\n replicateM_ t $ do\n _ <- B.getLine\n a <- sort . map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]\n print $ maximum $ zipWith (-) a (0 : a)\n"}, {"source_code": "import Control.Monad\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xs <- (0:) . sort <$> readInts\r\n print $ maximum $ zipWith (-) (tail xs) xs\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nimport Debug.Trace\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xs <- readInt64s\r\n let go [_] best = best\r\n go (x:xs@(y:_)) best = go xs $! (y - x) `max` best\r\n print $ go (0 : sort xs) minBound\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nreadInt64s :: IO [Int64]\r\nreadInt64s = map (fromInteger . fst . fromJust . C.readInteger) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n a <- sort . map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]\n print $ maximum $ zipWith (-) a (0 : a)\n"}], "src_uid": "4bd7ef5f6b3696bb44e22aea87981d9a"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Debug.Trace\r\nimport System.IO\r\n\r\ntrisum :: Integral a => a -> a\r\ntrisum r = r*(r+1)`div`2\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[k,x] <- readv\r\n let ans = binarySearch (exhaust k $ min x $ trisum $ 2*k-1) 0 (2*k-1) \r\n print ans\r\n\r\nexhaust :: Integer -> Integer -> Integer -> Bool\r\nexhaust k x m = let -- do m messages use up at least x emotes\r\n total = if m<=k then trisum m else trisum k + trisum (k-1) - trisum (2*k-1-m)\r\n in\r\n --traceShow (k,x,m,total) $ \r\n total >= x\r\n\r\nbinarySearch :: (Integer -> Bool) -> Integer -> Integer -> Integer\r\nbinarySearch can lo hi -- Assumption: f <$> [lo,hi] === [False,True]. Suggestion: Start with hi = n+1\r\n | lo + 1 == hi = hi\r\n | otherwise = if can mid then binarySearch can lo mid else binarySearch can mid hi\r\n where mid = lo + (hi-lo) `div` 2\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Integer]\r\nreadv = map (maybe 0 fst . DBC.readInteger) <$> (DBC.words <$> DBC.getLine)\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ (fromIntegral nTc) solve\r\n", "positive_code": [{"source_code": "import Data.List (delete)\r\n\r\n\r\nmain :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [triangle_height, emotes_before_ban] = map read $ words input\r\n result = howManyMessagesCanSendBeforeBan triangle_height emotes_before_ban\r\n output = show result\r\n\r\n\r\n\r\nhowManyMessagesCanSendBeforeBan :: Integer -> Integer -> Integer\r\nhowManyMessagesCanSendBeforeBan triangle_height emotes_before_ban = result_messages_n\r\n where\r\n result_messages_n = binarySearch 0 (2 * triangle_height - 1)\r\n binarySearch l r\r\n | l == r\r\n = mid\r\n | emotesNumberByMessagesNumber mid triangle_height >= emotes_before_ban\r\n = binarySearch l mid\r\n | otherwise\r\n = binarySearch (mid + 1) r\r\n where\r\n mid = (l + r) `div` 2\r\n\r\n\r\nemotesNumberByMessagesNumber :: Integer -> Integer -> Integer\r\nemotesNumberByMessagesNumber messages_n triangle_height = emotes_n\r\n where\r\n emotes_n = if messages_n < triangle_height\r\n then messages_n * (messages_n + 1) `div` 2\r\n else max_emotes_n - messages_before_max * (messages_before_max + 1) `div` 2\r\n max_emotes_n = triangle_height * (triangle_height + 1) `div` 2 * 2 - triangle_height\r\n messages_before_max = 2 * triangle_height - 1 - messages_n\r\n"}], "negative_code": [], "src_uid": "bf21c4809cd10904f05d531dd7af4ab5"} {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (nub, reverse, group, sort)\nimport Data.Array\n\n--solve :: Int -> Int -> Int\nsolve n s as\n | sum as < s = -1\n | sum as == s = 0\n | otherwise =\n let sm = sum as\n psL = array (0, n - 1) $ zip [0..n-1] (scanl1 (+) as)\n -- psL = scanl1 (+) as\n -- psR = scanl1 (+) (reverse as)\n psR = array (0, n - 1) $ zip [0..n-1] (scanl1 (+) (reverse as))\n in minimum $ map (test sm s as psL psR) [0..length as]\n -- \u0421\u0443\u043c\u043c\u0443 \u043c\u043e\u0436\u043d\u043e \u0434\u043e\u0441\u0442\u0438\u0447\u044c\n -- 1. \u041f\u0435\u0440\u0435\u0431\u0440\u0430\u0442\u044c l\n -- 2. \u041f\u043e\u0434\u043e\u0431\u0440\u0430\u0442\u044c \u043e\u043f\u0442\u0438\u043c\u0430\u043b\u044c\u043d\u0443\u044e r\n -- 3. \u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043b\u0443\u0447\u0448\u0438\u0439 \u043e\u0442\u0432\u0435\u0442 \u0441\u0440\u0435\u0434\u0438 \u0432\u0441\u0435\u0445 \u043f\u0435\u0440\u0435\u0431\u043e\u0440\u043e\u0432\n\n-- \u041f\u0435\u0440\u0435\u0431\u043e\u0440\n--test :: Int -> [Int] -> [Int] -> Int -> Int\ntest sm s as psL psR cntL\n | cntL == 0 =\n -- \u043d\u0443\u0436\u043d\u043e \u0432\u0437\u044f\u0442\u044c 0 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0441\u043b\u0435\u0432\u0430\n let idxR = binarySearch psR (sm - s)\n in idxR + 1\n | otherwise =\n -- \u044f \u0432\u0437\u044f\u043b cntL \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0441\u043b\u0435\u0432\u0430\n -- \u0442\u0435\u043f\u0435\u0440\u044c \u043c\u043d\u0435 \u043d\u0443\u0436\u043d\u043e \u0432\u0437\u044f\u0442\u044c \u043a\u0430\u043a\u043e\u0435-\u0442\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0441\u043f\u0440\u0430\u0432\u0430\n let idxR = binarySearch psR (sm - s - psL!(cntL - 1))\n in cntL + idxR + 1\n\n-- Search in xs index i such that (xs !! i) >= x\n-- lowerBound :: [Int] -> Int -> Int\nbinarySearch xs x\n | x <= 0 = -1 -- \u0442\u043e \u0435\u0441\u0442\u044c \u043d\u0438\u0447\u0435\u0433\u043e \u0431\u0440\u0430\u0442\u044c \u043d\u0435 \u043d\u0443\u0436\u043d\u043e\n | xs ! 0 >= x = 0\n | otherwise = helper xs x 0 (length xs)\n where\n helper xs x l r\n | l == r - 1 = r\n | xs ! mid < x = helper xs x mid r\n | otherwise = helper xs x l mid\n where mid = div (l + r) 2\n\n\nread = do\n s <- C.getLine\n\n let a = map (fst . fromJust . C.readInt) (C.words s)\n\n s <- C.getLine\n\n print $ solve (a !! 0) (a !! 1) (map (fst . fromJust . C.readInt) (C.words s))\n\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n", "positive_code": [{"source_code": "import Data.Array (Array, listArray, (!))\r\n\r\nreadArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\ncalcSmH :: [Int] -> Int -> [Int]\r\ncalcSmH [] _ = []\r\ncalcSmH (0: xs) i = calcSmH xs (i + 1)\r\ncalcSmH (1: xs) i = (i: calcSmH xs (i + 1))\r\n\r\ncalcSm :: [Int] -> [Int]\r\ncalcSm a = (0: calcSmH a 1)\r\n\r\ncalcH :: Array Int Int -> Array Int Int -> Int -> Int -> Int\r\ncalcH p s 0 j = p ! 0 + s ! j\r\ncalcH p s i j = min (p ! i + s ! j) (calcH p s (i - 1) (j + 1))\r\n\r\ncalc :: Array Int Int -> Array Int Int -> Int -> Int\r\ncalc p s d = calcH p s d 0\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = pure ()\r\nsolve i = do\r\n (n: k: _) <- readArr\r\n a <- readArr\r\n let s = sum a\r\n let (pr, sf) = (listArray (0, s - 1) (calcSm a), listArray (0, s - 1) (calcSm $ reverse a))\r\n let d = s - k\r\n if d < 0\r\n then print $ -1\r\n else print $ calc pr sf d\r\n solve $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n solve n"}, {"source_code": "import qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nimport Data.Maybe\nimport Control.Monad\nimport Data.List (nub, reverse, group, sort)\nimport Data.Array\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n s as\n | sum as < s = -1\n | sum as == s = 0\n | otherwise =\n let sm = sum as\n psL = array (0, n - 1) $ zip [0..n-1] (scanl1 (+) as)\n psR = array (0, n - 1) $ zip [0..n-1] (scanl1 (+) (reverse as))\n in minimum $ map (test sm s psL psR) [0..length as]\n\ntest :: (Ord a, Num a) => a -> a -> Array Int a -> Array Int a -> Int -> Int\ntest sm s psL psR cntL\n | cntL == 0 =\n let idxR = binarySearch psR (sm - s)\n in idxR + 1\n | otherwise =\n let idxR = binarySearch psR (sm - s - psL!(cntL - 1))\n in cntL + idxR + 1\n\nbinarySearch :: (Ord a, Num a) => Array Int a -> a -> Int\nbinarySearch xs x\n | x <= 0 = -1\n | xs ! 0 >= x = 0\n | otherwise = helper xs x 0 (length xs)\n where\n helper xs x l r\n | l == r - 1 = r\n | xs ! mid < x = helper xs x mid r\n | otherwise = helper xs x l mid\n where mid = div (l + r) 2\n\nread :: IO()\nread = do\n s <- C.getLine\n\n let a = map (fst . fromJust . C.readInt) (C.words s)\n\n s <- C.getLine\n\n print $ solve (a !! 0) (a !! 1) (map (fst . fromJust . C.readInt) (C.words s))\n\nmain :: IO()\nmain = do\n t <- C.getLine \n\n replicateM_ (fst $ fromJust $ C.readInt t) Main.read\n"}], "negative_code": [], "src_uid": "68adf23485d9db9a254ab73d4f07bd62"} {"source_code": "\nsolve :: String -> Int\nsolve s = maximum d - minimum d\n where\n d = scanl f 0 s\n f x '-' = x - 1\n f x '+' = x + 1\n\nmain :: IO ()\nmain = getLine >>= print . solve\n", "positive_code": [{"source_code": "main = getLine >>= print . snd . foldl f (0, 0)\n\nf (a, b) '+' = (a + 1, max (a + 1) b)\nf (0, b) '-' = (0, b + 1)\nf (a, b) '-' = (a - 1, b)\n"}, {"source_code": "main=interact$show.f 0 0 0\nf l h cur ('+':rest) = f l (max(cur+1)h) (cur+1) rest\nf l h cur ('-':rest) = f (min(cur-1)l) h (cur-1) rest\nf l h _ _ = h+abs l"}], "negative_code": [{"source_code": "\nsolve :: String -> Int\nsolve = maximum . map abs . scanl f 0\n where\n f x '-' = x - 1\n f x '+' = x + 1\n\nmain :: IO ()\nmain = getLine >>= print . solve\n"}], "src_uid": "a9cd99d74418b5f227b358a910496b02"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n B.putStr $ B.unwords $ map (B.pack . show) $ solve n k\n\nsolve n k \n | s > n = [-1]\n | otherwise = (\\g -> let s' = n `div` g in map (*g) $ [1,2..k-1] ++ [s' - k * (k - 1) `div` 2]) $ maybe undefined id $ find (\\i -> n `rem` i == 0) $ reverse $ takeWhile (<= n `div` s) $ divs n\n where s = k * (k + 1) `div` 2 :: Integer\n\ndivs x = sort $ concatMap (\\i -> [i, x `div` i]) $ filter (\\i -> x `rem` i == 0) [1..1 + floor (sqrt $ fromIntegral x)] \n\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInteger\nreadInts = fmap readInt . B.words", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Text.Printf\n\n\n\nsolve :: Integer -> Integer -> [Integer]\nsolve n k\n | kk2 > n = [-1]\n | otherwise = map ((*) a) [1..k-1] ++ [ee]\n where kk2 = k*(k+1)`div`2\n lim = n`div`kk2\n a = run 1 0\n run i acc\n | i > lim = acc\n | i*i > n = acc\n | n`mod`i == 0 = let other = n`div` i \n in run (i+1) (max i (if (other <= lim) then max other acc else acc))\n | otherwise = run (i+1) acc\n ee = n - (k*(k-1))`div`2*a\n\n\nmain :: IO ()\nmain = do\n (n:k:_) <- map read . words <$> getLine\n forM_ (solve n k) $ \\i -> do\n printf \"%d \" i\n printf \"\\n\"\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as C (readInteger, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.List as L (intercalate)\n\nreadInt :: B.ByteString -> I.Int64\nreadInt = fromIntegral . fst . M.fromJust . C.readInteger\n\nrun n sk 0 = -1\nrun n sk i | n `mod` i == 0 && n `div` i >= sk = i | otherwise = run n sk (i - 1)\n\nrunx n sk i | i > mnx = -1 where mnx = min n 100000\nrunx n sk i | r == 0 && n `mod` d == 0 && n `div` d >= sk = d\n | otherwise = runx n sk (i + 1) where\n (d, r) = n `divMod` i\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n let sk = (1 + k) * k `div` 2\n gh = max (runx n sk 1) (run n sk (min n 100000))\n gi = map (gh *) ([1..k - 1] ++ [n `div` gh - sk + k])\n putStrLn $ if k > 200000 || gh == -1 then \"-1\" else (L.intercalate \" \" . (map show)) gi\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as C (readInteger, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.List as L (intercalate)\n\nreadInt :: B.ByteString -> I.Int64\nreadInt = fromIntegral . fst . M.fromJust . C.readInteger\n\nrun n sk 0 = -1\nrun n sk i | n `mod` i == 0 && n `div` i >= sk = i | otherwise = run n sk (i - 1)\n\nrunx n sk i | i > min (n - 1) 100000 = -1\nrunx n sk i | n `mod` i == 0 && n `mod` (n `div` i) == 0 && n `div` (n `div` i) >= sk = n `div` i | otherwise = runx n sk (i + 1)\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n let sk = (1 + k) * k `div` 2\n gr = runx n sk 1\n gh = if gr /= -1 then gr else run n sk (min (n - 1) 100000)\n gi = map (gh *) ([1..k - 1] ++ [n `div` gh - sk + k])\n putStrLn $ if gh == -1 then \"-1\" else (L.intercalate \" \" . (map show)) gi\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as C (readInteger, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.List as L (intercalate)\n\nreadInt :: B.ByteString -> I.Int64\nreadInt = fromIntegral . fst . M.fromJust . C.readInteger\n\nrun n sk 0 = -1\nrun n sk i | n `mod` i == 0 && n `div` i >= sk = i | i == n = -1 | otherwise = run n sk (i - 1)\n\nmain = do\n (map readInt . C.words -> [n, k]) <- B.getLine\n let sk = (1 + k) * k `div` 2\n gr = run n sk n\n gh = if gr /= -1 then gr else run n sk (min (n - 1) 100000)\n gi = map (gh *) ([1..k - 1] ++ [n `div` gh - sk + k])\n putStrLn $ if gh == -1 then \"-1\" else (L.intercalate \" \" . (map show)) gi\n"}], "src_uid": "eba76d0491f88ac8d8450e457610b067"} {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.Either\nimport Data.Map.Strict\n\nmain = do\n m <- read . last . words <$> getLine\n (x, y) <- g m . first fromList . partitionEithers . fmap f . fmap words . lines <$> getContents\n putStrLn $ x\n putStrLn $ y\n\nf [var, _, val] = Left (var, val)\nf [var, _, x, op, y] = Right (var, x, op, y)\n\ng m (a, b) =\n (x, y)\n where x = zipWith (\\x y -> if x < y then '1' else '0') h1 h0\n y = zipWith (\\x y -> if x > y then '1' else '0') h1 h0\n h1 = take m $ h (replicate m '1') a b\n h0 = take m $ h (replicate m '0') a b\n\nh _ _ [] = repeat 0\nh t a ((var, x, op, y):b) =\n zipWith (+) k l\n where j \"?\" = t\n j x = a ! x\n k = zipWith (i op) (j x) (j y)\n k' = fmap (\\x -> if x == 0 then '0' else '1') k\n l = h t (insert var k' a) b\n\ni \"AND\" '1' '1' = 1 :: Int\ni \"AND\" _ _ = 0\ni \"OR\" '0' '0' = 0\ni \"OR\" _ _ = 1\ni \"XOR\" x y | x == y = 0\n | x /= y = 1\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.Either\nimport Data.Map.Strict\n\nmain = do\n m <- read . last . words <$> getLine\n (x, y) <- g m . first fromList . partitionEithers . fmap f . fmap words . lines <$> getContents\n putStrLn $ x\n putStrLn $ y\n\nf [var, _, val] = Left (var, val)\nf [var, _, x, op, y] = Right (var, x, op, y)\n\ng m (a, b) =\n (x, y)\n where x = zipWith (\\x y -> if x < y then '1' else '0') h1 h0\n y = zipWith (\\x y -> if x > y then '1' else '0') h1 h0\n h1 = take m $ h (insert \"?\" (repeat '1') a) b\n h0 = take m $ h (insert \"?\" (repeat '0') a) b\n\nh _ [] = repeat 0\nh a ((var, x, op, y):b) =\n zipWith (+) k s\n where k = zipWith (i op) (a ! x) (a ! y)\n l = fmap (\\x -> if x == 0 then '0' else '1') k\n s = h (insert var l a) b\n\ni \"AND\" '1' '1' = 1\ni \"AND\" _ _ = 0\ni \"OR\" '0' '0' = 0\ni \"OR\" _ _ = 1\ni \"XOR\" x y | x == y = 0\n | x /= y = 1\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Data.Either\nimport Data.Map.Strict\n\nmain = do\n m <- read . last . words <$> getLine\n (x, y) <- g m . first fromList . partitionEithers . fmap f . fmap words . lines <$> getContents\n putStrLn $ x\n putStrLn $ y\n\nf [var, _, val] = Left (var, val)\nf [var, _, x, op, y] = Right (var, x, op, y)\n\ng m (a, b) =\n (x, y)\n where x = zipWith (\\x y -> if x < y then '1' else '0') h1 h0\n y = zipWith (\\x y -> if x > y then '1' else '0') h1 h0\n h1 = take m $ h (insert \"?\" (repeat '1') a) b\n h0 = take m $ h (insert \"?\" (repeat '0') a) b\n\nh _ [] = repeat 0\nh a ((var, x, op, y):b) =\n zipWith (+) k s\n where k = zipWith (i op) x y\n l = fmap (\\x -> if x == 0 then '0' else '1') k\n s = h (insert var l a) b\n\ni \"AND\" '1' '1' = 1\ni \"AND\" _ _ = 0\ni \"OR\" '0' '0' = 0\ni \"OR\" _ _ = 1\ni \"XOR\" x y | x == y = 0\n | x /= y = 1\n"}], "src_uid": "318295e4c986a920c57bfc8a2a7860ed"} {"source_code": "main=interact$unlines.map(show.(\\(a,b)->sum b+(maximum b)*(2^(sum a)-1)).unzip.map(until(odd.snd)(\\(a,b)->(a+1,div b 2)).(,)0)).map(map read.words).t.tail.lines\r\nt(_:x:s)=x:t s\r\nt _=[]", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n\r\nrecurse k ys [] = (k,ys)\r\nrecurse k ys (x:xs) \r\n | even x = recurse (k+1) ys (x`div`2 : xs)\r\n | odd x = recurse k (x:ys) xs\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readv\r\n xs <- readv\r\n let \r\n (k,ys) = recurse 0 [] xs\r\n s = sum ys\r\n m = DL.maximum ys\r\n ans = s - m + (2^k)*m \r\n printv [ans]\r\n\r\nprintv :: [Integer] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat $ map (\\x->DBB.integerDec x <> DBB.char8 ' ') xs\r\n\r\nreadv :: IO [Integer]\r\nreadv = map (maybe 0 fst . DBC.readInteger) <$> (DBC.words <$> DBC.getLine)\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ (fromIntegral nTc) solve\r\n"}, {"source_code": "import Control.Monad\n\n-- pointfree style go brrrrrr\n\npower :: Integer -> (Integer, Integer)\npower = until ((/=) 0 . flip mod 2 . fst) ((,) <$> (`div` 2) . fst <*> (* 2) . snd) . ((,) <$> id <*> const 1)\n\nsolve :: [Integer] -> Integer\nsolve = (((. (*)) . (.) . (+) <$> ((-) <$> sum <*> maximum) <*> maximum) <$> (<$>) fst <*> product . (<$>) snd) . (<$>) power\n\ntest :: IO ()\ntest = getLine >> getLine >>= print . solve . (<$>) read . words\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ test\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\noe :: Int -> (Int, Int)\r\noe = go 0 where\r\n go acc x = acc `seq` if odd x\r\n then (x, acc)\r\n else go (acc + 1) (quot x 2)\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do\r\n ~[n] <- getInts 1\r\n a <- getInts n\r\n let\r\n (odds, p2s) = unzip $ map oe a\r\n lv : svs = sortOn negate odds\r\n pure $ putInts [foldl' (\\acc x -> acc * 2 ^ x) lv p2s + sum svs]\r\n\r\n\r\ntype SP = State [P.ByteString]\r\n\r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n\r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Arrow ((***))\r\n\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . findMaxSumCanGetFromArray) . parseTests\r\n\r\n\r\nfindMaxSumCanGetFromArray :: [Integer] -> Integer\r\nfindMaxSumCanGetFromArray array = result\r\n where\r\n (new_array, twos_powers) = unzip $ map takeAwayTwoAsFactor array\r\n result = sum new_array + (maximum new_array) * (2 ^ (sum twos_powers) - 1)\r\n\r\n\r\ntakeAwayTwoAsFactor :: Integer -> (Integer, Integer)\r\ntakeAwayTwoAsFactor x = until (odd . fst) ((`div` 2) *** (+1)) (x, 0)\r\n\r\n\r\nparseTests :: String -> [[Integer]]\r\nparseTests = map (map read . words) . takeEverySecond . drop 1 . lines\r\n\r\n\r\ntakeEverySecond :: [a] -> [a]\r\ntakeEverySecond (x1:x2:xs) = x2 : takeEverySecond xs\r\ntakeEverySecond _ = []\r\n"}, {"source_code": "import Control.Arrow ((***))\r\n\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (show . findMaxSumCanGetFromArray) . parseTests\r\n\r\n\r\nfindMaxSumCanGetFromArray :: [Integer] -> Integer\r\nfindMaxSumCanGetFromArray array = result\r\n where\r\n (new_array, twos_powers) = unzip $ map takeAwayTwoAsFactor array\r\n result = sum new_array + (maximum new_array) * (2 ^ (sum twos_powers) - 1)\r\n\r\n\r\ntakeAwayTwoAsFactor :: Integer -> (Integer, Integer)\r\ntakeAwayTwoAsFactor x\r\n | even x = (id *** (+1)) $ takeAwayTwoAsFactor (x `div` 2)\r\n | otherwise = (x, 0)\r\n\r\n\r\nparseTests :: String -> [[Integer]]\r\nparseTests = map (map read . words) . takeEverySecond . drop 1 . lines\r\n\r\n\r\ntakeEverySecond :: [a] -> [a]\r\ntakeEverySecond (x1:x2:xs) = x2 : takeEverySecond xs\r\ntakeEverySecond _ = []\r\n"}], "negative_code": [], "src_uid": "f5de1e9b059bddf8f8dd46c18ce12683"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S (fromList, difference, size, union, member)\nimport qualified Data.Foldable as F (toList)\n\nreadint = fst. fromJust . C.readInt\n\ndmap (F.toList -> xs) (F.toList -> ys)\n = S.fromList [ x + y | x <- xs, y <- ys, abs (x + y) <= 1000 ]\n\nmain = do\n (map readint . C.words -> [n, k]) <- B.getLine\n (S.fromList . take k . map ((+ (-n)) . readint) . C.words -> xs) <- B.getLine\n let iter (x, i, ac) = let x' = S.difference (dmap x xs) ac in (x', i + 1, S.union x' ac)\n (S.size -> l, ans, _) = until (\\(a, _, _) -> S.size a == 0 || S.member 0 a) iter (xs, 1, xs)\n putStrLn $ show $ if l == 0 then -1 else ans\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S (fromList, difference, size, union, member,\n findMin, findMax, map, singleton, null, intersection)\nimport qualified Data.Foldable as F (toList)\n\nreadint = fst. fromJust . C.readInt\n\ndmap (fn, fx) (F.toList -> xs) (F.toList -> ys)\n = S.fromList [ x + y | x <- xs, y <- ys, abs (x + y) <= max (abs fx) (abs fn) ]\n\niter nx xs (x, i, ac) | S.member 0 x' = (S.singleton 0, i + 1, ac)\n | not (S.null (S.intersection (S.map (0-) x') x)) = (S.singleton 0, 2 * i + 1, ac)\n | not (S.null (S.intersection (S.map (0-) x') x')) = (S.singleton 0, 2 * (i + 1), ac)\n | otherwise = (x', i + 1, S.union x' ac) where\n x' = S.difference (dmap nx x xs) ac\n\nmain = do\n (map readint . C.words -> [n, k]) <- B.getLine\n (S.fromList . take k . map ((+ (-n)) . readint) . C.words -> xs) <- B.getLine\n let nx = (S.findMin xs, S.findMax xs)\n end (a, _, _) = S.size a == 0 || S.member 0 a\n (_, ans, _) = until end (iter nx xs) (xs, 1, xs)\n putStrLn $ show $ if fst nx * snd nx > 0 then -1 else ans\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as S (fromList, difference, size, union, member,\n findMin, findMax, map, singleton, null, intersection)\nimport qualified Data.Foldable as F (toList)\n\nreadint = fst. fromJust . C.readInt\n\ndmap (fn, fx) (F.toList -> xs) (F.toList -> ys)\n = S.fromList [ x + y | x <- xs, y <- ys, abs x + y <= max (abs fx) (abs fn) ]\n\niter nx xs (x, i, ac) | S.member 0 x' = (S.singleton 0, i + 1, ac)\n | not (S.null (S.intersection (S.map (0-) x') x)) = (S.singleton 0, 2 * i + 1, ac)\n | not (S.null (S.intersection (S.map (0-) x') x')) = (S.singleton 0, 2 * (i + 1), ac)\n | otherwise = (x', i + 1, S.union x' ac) where\n x' = S.difference (dmap nx x xs) ac\n\nmain = do\n (map readint . C.words -> [n, k]) <- B.getLine\n (S.fromList . take k . map ((+ (-n)) . readint) . C.words -> xs) <- B.getLine\n let nx = (S.findMin xs, S.findMax xs)\n end (a, _, _) = S.size a == 0 || S.member 0 a\n (_, ans, _) = until end (iter nx xs) (xs, 1, xs)\n putStrLn $ show $ if fst nx * snd nx > 0 then -1 else ans\n"}], "src_uid": "1aab45f5eed49b8ebdef822497099b59"} {"source_code": "import Data.List\n\nmain = interact $ unlines . map (show . f) . lines\n\nmdl f a b = f a b `mod` 1000000007\n\nfb = 1:1:zipWith (mdl (+)) fb (tail fb)\n\nf s = if 'w' `elem` s || 'm' `elem` s\n then 0\n else\n foldl1 (mdl (*))\n $ map ((!!) fb . length)\n $ groupBy (\\a b -> a `elem` \"un\" && a == b) s", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\n\nmain = interact solve\n\nsolve str = if not g then show c else \"0\"\n where g = elem 'w' str || elem 'm' str\n c = md . product . map (fib . length) . filter (\\x -> length x /= 1 && elem (head x) \"un\") . group $ str\n\nfib = fst . fib2\n\n-- | Return (fib n, fib (n + 1))\nfib2 0 = (1, 1)\nfib2 1 = (1, 2)\nfib2 n\n | even n = (a*a + b*b, c*c - a*a)\n | otherwise = (c*c - a*a, b*b + c*c)\n where (a,b) = fib2 (n `div` 2 - 1)\n c = a + b\n\nmd :: Integer -> Int\nmd x = fromInteger $ x `mod` 1000000007"}, {"source_code": "import Data.List\n\nmain = interact $ show . f\n\nmdl f a b = f a b `mod` 1000000007\n\nfb = 1:1:zipWith (mdl (+)) fb (tail fb)\n\nf s = if 'w' `elem` s || 'm' `elem` s \n then 0\n else foldl1 (mdl (*)) \n $ map ((!!) fb . length)\n $ groupBy (\\a b -> a `elem` \"un\" && a == b) s"}, {"source_code": "import Data.List\n\ncount x = length . filter (== x)\n\nmain = interact\n $ unlines\n . map (show . solve)\n . lines\n\nmodulo = 1000000007\n\nfibs = 1:1:zipWith (\\a b -> (a + b) `mod` modulo) fibs (tail fibs)\n\nsolve s = if 'w' `elem` s || 'm' `elem` s\n then 0\n else\n foldl1 (\\a b -> (a * b) `mod` modulo)\n $ map ((!!) fibs . length)\n $ groupBy (\\a b -> a `elem` \"un\" && a == b) s\n\n"}], "negative_code": [{"source_code": "import Data.List\n\ncount x = length . filter (== x)\n\nmain = interact\n $ unlines\n . map (show . solve)\n . lines\n\nmodulo = 1000000007\n\nfibs = 1:1:zipWith (\\a b -> (a + b) `mod` modulo) fibs (tail fibs)\n\nsolve :: String -> Int\nsolve s = if 'w' `elem` s || 'm' `elem` s\n then 0\n else\n foldl1 (\\a b -> (a * b) `mod` modulo)\n $ map ((!!) fibs . length)\n $ groupBy (\\a b -> a `elem` \"un\" && a == b) s\n\n"}, {"source_code": "import Data.List\n\nmain = interact solve\n\nsolve str = if not g then show c else \"0\"\n where g = elem 'w' str || elem 'm' str\n c :: Int\n c = pr . map (fib . length) . filter (\\x -> length x /= 1 && elem (head x) \"un\") . group $ str\n\npr :: [Int] -> Int\npr l = foldl' ((md.) . (*)) 1 l\n\nfibs :: [Int]\nfibs = 1 : 1 : zipWith ((md.) . (+)) fibs (tail fibs)\n\nfib = (fibs!!)\n\nmd :: Int -> Int\nmd x = x `mod` 1000000007"}, {"source_code": "import Data.List\nimport Data.Int\n\nmain = interact solve\n\nsolve str = if not g then show c else \"0\"\n where g = elem 'w' str || elem 'm' str\n c :: Int\n c = pr . map (fib . length) . filter (\\x -> length x /= 1 && elem (head x) \"un\") . group $ str\n\npr :: [Int] -> Int\npr l = foldl' (mmul) 1 l\n\n-- mul as i64, overflow otherwise\nmmul :: Int -> Int -> Int\nmmul a b = md $ fromIntegral (toI64 a * toI64 b)\n where toI64 = fromIntegral :: Int -> Int64\n\nfibs :: [Int]\nfibs = 1 : 1 : zipWith ((md.) . (+)) fibs (tail fibs)\n\nfib = (fibs!!)\n\nmd :: Int -> Int\nmd x = x `mod` 1000000007"}, {"source_code": "import Data.List\n\nmain = interact solve\n\nsolve str = if not g then show c else \"0\"\n where g = elem 'w' str || elem 'm' str\n c :: Int\n c = pr . map (fib . (+1) . length) . filter (\\x -> length x /= 1 && elem (head x) \"un\") . group $ str\n\npr :: [Int] -> Int\npr l = foldl' ((md.) . (*)) 1 l\n\nfibs :: [Int]\nfibs = 1 : 1 : zipWith ((md.) . (+)) fibs (tail fibs)\n\nfib = (fibs!!)\n\nmd :: Int -> Int\nmd x = x `mod` 1000000007"}], "src_uid": "12c223c903544899638e47bcab88999a"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let s = C.takeWhile isLetter line -- codeforces compatibility\n let ans = calc s\n if (length ans) == 0 then\n print (-1)\n else\n C.putStrLn $ C.unwords ans\n", "positive_code": [{"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = tail (lines input)\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest final_string = case restoreInitialStringAndDeletionOrder final_string of\r\n Just (restored_string, deletion_order) -> restored_string ++ \" \" ++ deletion_order\r\n Nothing -> \"-1\"\r\n\r\n\r\nrestoreInitialStringAndDeletionOrder :: String -> Maybe (String, String)\r\nrestoreInitialStringAndDeletionOrder final_string = result\r\n where\r\n deletion_order = restoreDeletionOrder final_string\r\n initial_string = restoreInitialString final_string deletion_order\r\n final_string_will_get = computeFinalString initial_string deletion_order\r\n can_restore = final_string == final_string_will_get\r\n result = if can_restore then Just (initial_string, deletion_order) else Nothing\r\n\r\n\r\ncomputeFinalString :: String -> String -> String\r\ncomputeFinalString initial_string [] = []\r\ncomputeFinalString initial_string (char_to_delete:next_deletions) =\r\n initial_string ++ computeFinalString next_string next_deletions\r\n where next_string = filter (/= char_to_delete) initial_string\r\n\r\n\r\nrestoreInitialString :: String -> String -> String\r\nrestoreInitialString final_string deletion_order = take initial_string_size final_string\r\n where\r\n initial_string_size =\r\n sum [countElement char final_string `div` lifetime | (char, lifetime) <- zip deletion_order [1..]]\r\n\r\n\r\nrestoreDeletionOrder :: String -> String\r\nrestoreDeletionOrder = reverse . takeFirstOccurrences . reverse\r\n\r\n\r\ntakeFirstOccurrences :: Eq a => [a] -> [a]\r\ntakeFirstOccurrences [] = []\r\ntakeFirstOccurrences (x:xs) = x : takeFirstOccurrences (filter (/= x) xs)\r\n\r\n\r\ncountElement :: Eq a => a -> [a] -> Int\r\ncountElement char string = length (filter (== char) string)\r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let suffix = findSuffix line\n --print suffix\n --let first = C.take 7 line\n --let second = applyRule C.empty first suffix\n --if second == (C.pack \"abacabaaacaac\") then\n -- C.putStrLn $ C.unwords [second, C.pack suffix]\n --else\n -- putStrLn \"-1\"\n --let ans = calc line\n --if (length ans) == 0 then\n -- print (-1)\n --else\n -- C.putStrLn $ C.unwords ans\n putStr \"'\"\n C.putStr line\n putStr \"'\"\n putStr $ show $ ((C.length line)-1)\n putStr \" \"\n putStrLn suffix\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let suffix = findSuffix line\n --print suffix\n --let first = C.take 7 line\n --let second = applyRule C.empty first suffix\n --if second == (C.pack \"abacabaaacaac\") then\n -- C.putStrLn $ C.unwords [second, C.pack suffix]\n --else\n -- putStrLn \"-1\"\n --let ans = calc line\n --if (length ans) == 0 then\n -- print (-1)\n --else\n -- C.putStrLn $ C.unwords ans\n putStr $ show $ ((C.length line)-1)\n putStr \" \"\n putStrLn suffix\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let suffix = findSuffix line\n --print suffix\n --let first = C.take 7 line\n --let second = applyRule C.empty first suffix\n --if second == (C.pack \"abacabaaacaac\") then\n -- C.putStrLn $ C.unwords [second, C.pack suffix]\n --else\n -- putStrLn \"-1\"\n --let ans = calc line\n --if (length ans) == 0 then\n -- print (-1)\n --else\n -- C.putStrLn $ C.unwords ans\n C.putStr $ check line suffix 0 ((C.length line)-1)\n putStr \" \"\n putStrLn suffix\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let suffix = findSuffix line\n --print suffix\n let first = C.take 7 line\n let second = applyRule C.empty first suffix\n if second == (C.pack \"abacabaaacaac\") then\n C.putStrLn $ C.unwords [second, C.pack suffix]\n else\n putStrLn \"-1\"\n --let ans = calc line\n --if (length ans) == 0 then\n -- print (-1)\n --else\n -- C.putStrLn $ C.unwords ans\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n let suffix = findSuffix line\n --print suffix\n let first = C.take 7 line\n let second = applyRule C.empty first suffix\n C.putStrLn $ C.unwords [second, C.pack suffix]\n --let ans = calc line\n --if (length ans) == 0 then\n -- print (-1)\n --else\n -- C.putStrLn $ C.unwords ans\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as S\n\nfindSuffix' :: Int -> C.ByteString -> S.IntSet -> String -> String\nfindSuffix' i str _ acc | i < 0 = acc\nfindSuffix' i str tree acc =\n let x = C.index str i\n code = ord x\n in\n if S.member code tree then\n findSuffix' (i-1) str tree acc\n else\n findSuffix' (i-1) str (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: C.ByteString -> String\nfindSuffix s = findSuffix' ((C.length s)-1) s S.empty []\n\napplyRule :: C.ByteString -> C.ByteString -> String -> C.ByteString\napplyRule t _ [] = t\napplyRule t s (x:xs) =\n let newS = C.filter (/= x) s\n in\n applyRule (C.concat [t,s]) newS xs\n\ncheck :: C.ByteString -> String -> Int -> Int -> C.ByteString\ncheck _ _ l r | l > r = C.empty\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = C.take (m+1) s\n t = applyRule C.empty left suffix\n in\n if t == s then\n left\n else if (C.length t) < (C.length s) then\n check s suffix (m+1) r\n else\n check s suffix l (m-1)\n\ncalc :: C.ByteString -> [C.ByteString]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((C.length s) - 1)\n in\n if (C.length ans) == 0 then []\n else [ans, C.pack suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- C.getLine\n --let suffix = findSuffix line\n --print suffix\n --let first = take 7 line\n --print $ applyRule [] first suffix\n let ans = calc line\n if (length ans) == 0 then\n print (-1)\n else\n C.putStrLn $ C.unwords ans\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.IntSet as S\n\nfindSuffix' :: String -> S.IntSet -> String -> String\nfindSuffix' [] _ acc = acc\nfindSuffix' (x:xs) tree acc =\n if S.member (ord x) tree then\n findSuffix' xs tree acc\n else\n findSuffix' xs (S.insert (ord x) tree) (x:acc)\n\nfindSuffix :: String -> String\nfindSuffix s = findSuffix' (reverse s) S.empty []\n\napplyRule :: String -> String -> String -> String\napplyRule t [] _ = t\napplyRule t s (x:xs) =\n let newS = filter (/= x) s\n in\n applyRule (t ++ s) newS xs\n\ncheck :: String -> String -> Int -> Int -> String\ncheck _ _ l r | l >= r = []\ncheck s suffix l r =\n let m = l+((r-l) `div` 2)\n left = take (m+1) s\n t = applyRule [] left suffix\n in\n if t == s then\n left\n else if (length t) < (length s) then\n check s suffix (m+1) r\n else\n check s suffix l m\n\ncalc :: String -> [String]\ncalc s =\n let suffix = findSuffix s\n ans = check s suffix 0 ((length s) - 1)\n in\n if null ans then []\n else [ans, suffix]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n --let suffix = findSuffix line\n --print suffix\n --let first = take 7 line\n --print $ applyRule [] first suffix\n let ans = calc line\n if (length ans) == 0 then\n print (-1)\n else\n putStrLn $ unwords ans\n"}], "src_uid": "8705adec1bea1f898db1ca533e15d5c3"} {"source_code": "{-# LANGUAGE ForeignFunctionInterface, MultiWayIf, OverloadedStrings #-}\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nint = state $ fromJust . B.readInt . B.dropWhile isSpace\n\ndouble :: State B.ByteString Double\ndouble = state $ first (f 0 0 Nothing) . B.span (not . isSpace) . B.dropWhile isSpace\n where\n f i acc dot s =\n if | i == B.length s -> maybe acc ((acc/) . (10^)) dot\n | B.index s i == '-' -> f (i+1) (-acc) (Just 0) s\n | B.index s i == '.' -> f (i+1) acc (Just 0) s\n | otherwise -> f (i+1) (acc*10 + fromIntegral (fromEnum $ B.index s i) - 48) ((1+) <$> dot) s\n\nparse = do\n n <- int\n maxs <- replicateM n double\n mins <- replicateM n double\n return (n, maxs, mins)\n\nforeign import ccall \"stdio.h printf\" c_printf :: CString -> Double -> IO ()\nforeign import ccall \"stdio.h putchar\" c_putchar :: Int -> IO ()\n\nwriteDouble x = withCString \"%.9f\" $ flip c_printf x\n\nwriteChar :: Char -> IO ()\nwriteChar = c_putchar . fromEnum\n\nf [] [] _ _ _ _ = []\nf (mx:maxs) (mi:mins) mxs mis xs ys = (xs'-xs, ys'-ys) : f maxs mins mxs' mis' xs' ys'\n where\n mxs' = mxs + mx\n mis' = mis + mi\n b = mxs'+mis'\n d = sqrt . max 0 $ b^2 - 4 * mxs'\n xs' = (b+d)/2\n ys' = (b-d)/2\n\nmain = do\n (n, maxs, mins) <- evalState parse <$> B.getContents\n let (xs, ys) = unzip $ f maxs mins 0 0 0 0\n forM_ xs ((>> writeChar ' ') . writeDouble)\n writeChar '\\n'\n forM_ ys ((>> writeChar ' ') . writeDouble)\n writeChar '\\n'\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nint = state $ fromJust . B.readInt . B.dropWhile isSpace\n\ndouble :: State B.ByteString Double\ndouble = state $ first (f 0 0 Nothing) . B.span (not . isSpace) . B.dropWhile isSpace\n where\n f i acc dot s =\n if | i == B.length s -> maybe acc ((acc/) . (10^)) dot\n | B.index s i == '-' -> f (i+1) (-acc) (Just 0) s\n | B.index s i == '.' -> f (i+1) acc (Just 0) s\n | otherwise -> f (i+1) (acc*10 + fromIntegral (fromEnum $ B.index s i) - 48) ((1+) <$> dot) s\n\nparse = do\n n <- int\n maxs <- replicateM n double\n mins <- replicateM n double\n return (n, maxs, mins)\n\nf [] [] _ _ _ _ = []\nf (mx:maxs) (mi:mins) mxs mis xs ys = (xs'-xs, ys'-ys) : f maxs mins mxs' mis' xs' ys'\n where\n mxs' = mxs + mx\n mis' = mis + mi\n b = mxs'+mis'\n d = sqrt . max 0 $ b^2 - 4 * mxs'\n xs' = (b+d)/2\n ys' = (b-d)/2\n\nmain = do\n (n, maxs, mins) <- evalState parse <$> B.getContents\n let (xs, ys) = unzip $ f maxs mins 0 0 0 0\n forM_ xs (printf \"%.9f \")\n putStrLn \"\"\n forM_ ys (printf \"%.9f \")\n putStrLn \"\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ForeignFunctionInterface, MultiWayIf, OverloadedStrings #-}\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nint = state $ fromJust . B.readInt . B.dropWhile isSpace\n\ndouble :: State B.ByteString Double\ndouble = state $ first (f 0 0 Nothing) . B.span (not . isSpace) . B.dropWhile isSpace\n where\n f i acc dot s =\n if | i == B.length s -> maybe acc ((acc/) . (10^)) dot\n | B.index s i == '-' -> f (i+1) (-acc) (Just 0) s\n | B.index s i == '.' -> f (i+1) acc (Just 0) s\n | otherwise -> f (i+1) (acc*10 + fromIntegral (fromEnum $ B.index s i) - 48) ((1+) <$> dot) s\n\nparse = do\n n <- int\n maxs <- replicateM n double\n mins <- replicateM n double\n return (n, maxs, mins)\n\nforeign import ccall \"stdio.h printf\" c_printf :: CString -> Double -> IO ()\nforeign import ccall \"stdio.h putchar\" c_putchar :: Int -> IO ()\n\nwriteDouble x = withCString \"%.9f\" $ flip c_printf x\n\nwriteChar :: Char -> IO ()\nwriteChar = c_putchar . fromEnum\n\nf [] [] _ _ _ _ = []\nf (mx:maxs) (mi:mins) mxs mis xs ys = (xs'-xs, ys'-ys) : f maxs mins mxs' mis' xs' ys'\n where\n mxs' = mxs + mx\n mis' = mis + mi\n b = mxs'+mis'\n d = sqrt . max 0 $ b^2 - 4 * mxs'\n xs' = (b+d)/2\n ys' = (b-d)/2\n\nmain = do\n (n, maxs, mins) <- evalState parse <$> B.getContents\n let (xs, ys) = unzip $ f maxs mins 0 0 0 0\n forM_ xs ((>> writeChar ' ') . writeDouble)\n writeChar '\\n'\n forM_ xs ((>> writeChar ' ') . writeDouble)\n writeChar '\\n'\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nint = state $ fromJust . B.readInt . B.dropWhile isSpace\n\ndouble :: State B.ByteString Double\ndouble = state $ first (f 0 0 Nothing) . B.span (not . isSpace) . B.dropWhile isSpace\n where\n f i acc dot s =\n if | i == B.length s -> maybe acc ((acc/) . (10^)) dot\n | B.index s i == '-' -> f (i+1) (-acc) (Just 0) s\n | B.index s i == '.' -> f (i+1) acc (Just 0) s\n | otherwise -> f (i+1) (acc*10 + fromIntegral (fromEnum $ B.index s i) - 48) ((1+) <$> dot) s\n\nparse = do\n n <- int\n maxs <- replicateM n double\n mins <- replicateM n double\n return (n, maxs, mins)\n\nf [] [] _ _ _ _ = []\nf (mx:maxs) (mi:mins) mxs mis xs ys = (xs'-xs, ys'-ys) : f maxs mins mxs' mis' xs' ys'\n where\n mxs' = mxs + mx\n mis' = mis + mi\n b = mxs'+mis'\n d = sqrt $ b^2 - 4 * mxs'\n xs' = (b+d)/2\n ys' = (b-d)/2\n\nmain = do\n (n, maxs, mins) <- evalState parse <$> B.getContents\n let (xs, ys) = unzip $ f maxs mins 0 0 0 0\n forM_ xs (printf \"%.9f \")\n putStrLn \"\"\n forM_ ys (printf \"%.9f \")\n putStrLn \"\"\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Char\nimport Data.Functor\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\n\nint = state $ fromJust . B.readInt . B.dropWhile isSpace\n\ndouble :: State B.ByteString Double\ndouble = state $ first (f 0 0 Nothing) . B.span (not . isSpace) . B.dropWhile isSpace\n where\n f i acc dot s =\n if | i == B.length s -> maybe acc ((acc/) . (10^)) dot\n | B.index s i == '.' -> f (i+1) acc (Just 0) s\n | otherwise -> f (i+1) (acc*10 + fromIntegral (fromEnum $ B.index s i) - 48) ((1+) <$> dot) s\n\nparse = do\n n <- int\n maxs <- replicateM n double\n mins <- replicateM n double\n return (n, maxs, mins)\n\nf [] [] _ _ _ _ = []\nf (mx:maxs) (mi:mins) mxs mis xs ys = (xs'-xs, ys'-ys) : f maxs mins mxs' mis' xs' ys'\n where\n mxs' = mxs + mx\n mis' = mis + mi\n b = mxs'+mis'\n d = sqrt $ b^2 - 4 * mxs'\n xs' = (b+d)/2\n ys' = (b-d)/2\n\nmain = do\n (n, maxs, mins) <- evalState parse <$> B.getContents\n let (xs, ys) = unzip $ f maxs mins 0 0 0 0\n forM_ xs (printf \"%.9f \")\n putStrLn \"\"\n forM_ ys (printf \"%.9f \")\n putStrLn \"\"\n"}], "src_uid": "5cb7ce7485c86ca73c0adfd27227adf9"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch fun li ri = if li == ri\n then li\n else let\n mi = li + div (ri - li) 2\n in if fun mi\n then binSearch fun li mi\n else binSearch fun (mi+1) ri\n\nsolve :: [Int] -> [Int] -> Int\nsolve _ [] = 0\nsolve aLi bLi = let\n n = length aLi\n m = length bLi\n a = listArray (1, n) aLi :: UArray Int Int\n b = listArray (1, m) bLi :: UArray Int Int\n boxesBefore pos = binSearch (\\ix -> a ! ix > pos) 1 (n+1) - 1\n kthSpace k = binSearch (\\pos -> pos - boxesBefore pos >= k) 1 (n + k)\n boxesAt pos = let\n ix = boxesBefore pos\n in if ix > 0 && a ! ix == pos then 1 else 0\n preCovered :: UArray Int Int\n preCovered = listArray (1, m+1) $ scanr (+) 0 $ map boxesAt $ elems b\n score ix = let\n secondGap = kthSpace $ b ! ix\n gapIx = binSearch (\\jx -> b ! jx >= secondGap) 1 (m+1)\n in gapIx - ix + preCovered ! gapIx\n in foldl' max minBound $ map score [1..m]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n, _m] <- readInts\n aLi <- readInts\n bLi <- readInts\n let\n (reverse . map negate -> negAli, posAli) = span (< 0) aLi\n (reverse . map negate -> negBli, posBli) = span (< 0) bLi\n putInts [solve negAli negBli + solve posAli posBli]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ncountLessEqual :: Array Int Int -> Int -> Int -> Int -> Int\ncountLessEqual a l r x\n | l == r = l\n | a ! m <= x = countLessEqual a m r x\n | otherwise = countLessEqual a l (m - 1) x\n where\n m = (l + r) `quot` 2 + 1\n\nsolve :: [Int] -> [Int] -> Int\nsolve [] _ = 0\nsolve _ [] = 0\nsolve as bs' = func bs 0 0\n where\n bs = dropWhile (< head as) bs'\n n = length as\n a = listArray (0, n - 1) as\n func [] _ opt = opt\n func (y : ys) i opt\n | i < n - 1 && a ! (i + 1) <= y + i + 1 = func (y : ys) (i + 1) opt\n | otherwise = func ys i $ max opt $ count y (y + i)\n count y1 y2 = countLessEqual b 0 bn y2 - countLessEqual b 0 bn (y1 - 1) + dn - countLessEqual d 0 dn y2\n bn = length bs\n b = listArray (0, bn) (0 : bs)\n f [] _ = []\n f _ [] = []\n f (x : xs) (y : ys)\n | x < y = f xs (y : ys)\n | x > y = f (x : xs) ys\n | otherwise = x : f xs ys\n ds = f as bs\n dn = length ds\n d = listArray (0, dn) (0 : ds)\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, m] <- getInts\n as <- getInts\n bs <- getInts\n let\n (a1, a2) = partition (<0) as\n (b1, b2) = partition (<0) bs\n f = reverse . map negate\n result = solve (f a1) (f b1) + solve a2 b2\n C.putStrLn $ C.pack $ show result\n"}], "negative_code": [], "src_uid": "a2b99448d6267a66bddfdcad9add311b"} {"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [size_y, size_x] = map read $ words input\r\n result = findMinBlueCellsN (size_x, size_y)\r\n output = show result\r\n\r\n\r\nfindMinBlueCellsN :: (Integer, Integer) -> Integer\r\nfindMinBlueCellsN (size_x, size_y)\r\n | not (size_y <= size_x) = findMinBlueCellsN (size_y, size_x)\r\n | size_x < 2 || size_y < 1 = 0\r\n | size_x `mod` 3 == 0 || size_y `mod` 3 == 0 = size_x * size_y `div` 3\r\n | size_y == 1 = size_x `div` 3 + 1\r\n | otherwise = minimum [findMinBlueCellsN (size_x - 1, size_y) + findMinBlueCellsN (1, size_y),\r\n findMinBlueCellsN (size_x, size_y - 1) + findMinBlueCellsN (size_x, 1)]\r\n", "positive_code": [{"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [size_y, size_x] = map read $ words input\r\n result = findMinBlueCellsN (size_x, size_y)\r\n output = show result\r\n\r\n\r\nfindMinBlueCellsN :: (Integer, Integer) -> Integer\r\nfindMinBlueCellsN (size_x, size_y)\r\n | not (size_y <= size_x) = findMinBlueCellsN (size_y, size_x)\r\n | size_x < 2 || size_y < 1 = 0\r\n | size_y < 2 = size_x `div` 3 + (if size_x `mod` 3 == 0 then 0 else 1)\r\n | size_x `mod` 3 == 0 || size_y `mod` 3 == 0 = size_x * size_y `div` 3\r\n | otherwise = minimum [findMinBlueCellsN (size_x - 1, size_y) + findMinBlueCellsN (1, size_y),\r\n findMinBlueCellsN (size_x, size_y - 1) + findMinBlueCellsN (size_x, 1)]\r\n"}, {"source_code": "import qualified Control.Monad as CM\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x,y] <- readv\r\n printv [(x*y+2)`div`3]\r\n\r\nprintv :: Show a => [a] -> IO ()\r\nprintv xs = putStrLn $ unwords $ fmap show xs\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\n\nsolve :: [Int] -> Int\nsolve [n, m] = (n * m + 2) `div` 3\n"}], "negative_code": [], "src_uid": "70a0b98f2bb12990a0fa46aaf13134af"} {"source_code": "import Data.List\n\nmain = interact $ show.g.pick.f.lines\nf xs = map (\\x -> (map read (words x)) :: [Integer]) xs\npick (a:b:c:d:[]) = [(sort b), (sort d)]\ng (x:y:[]) = merge x y 0\nmerge [] ys ans = ans\nmerge xs [] ans = ans\nmerge (x:xs) (y:ys) ans\n | abs (x - y) <= 1 = merge xs ys (ans + 1)\n | x < y = merge xs (y:ys) ans\n | otherwise = merge (x:xs) ys ans\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nsolve :: [Int] -> [Int] -> Int\nsolve [] _ = 0\nsolve _ [] = 0\nsolve (b:bs) (g:gs)\n | abs (b - g) <= 1 = 1 + solve bs gs\n | b < g = solve bs (g:gs)\n | otherwise = solve (b:bs) gs\n\nmain = do\n _ <- getLine\n b <- sort . (map read) . words <$> getLine\n _ <- getLine\n g <- sort . (map read) . words <$> getLine\n print $ solve b g\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:s) = \n let a = take n s\n b = drop (n + 1) s\n in solve' (sort a) (sort b)\n where\n solve' :: [Int] -> [Int] -> Int\n solve' [] _ = 0\n solve' _ [] = 0\n solve' (a:ax) (b:bx) | abs (a - b) <= 1 = 1 + (solve' ax bx)\n | a < b = solve' ax (b:bx)\n | otherwise = solve' (a:ax) bx\n"}, {"source_code": "-- reading the tutorials is how to get better!!!\n-- read a ton of the tutorials!!!!\nimport Data.List\n\n\n\npairthem one two pairs\n | (null one) || (null two) = pairs\n | ((head one) - (head two)) < (-1) = pairthem (tail one) two pairs\n | ((head one) - (head two)) > 1 = pairthem one (tail two) pairs\n | ((head one) - (head two)) <= 1 && ((head two) - (head one)) >= -1 =\n pairthem (tail one) (tail two) (pairs+1)\n\nconv lst uu\n | (null lst) = uu\n | otherwise = conv (tail lst) (((read (head lst))::Int) : uu)\n\n\nmain = do\n ff <- getLine\n gg <- getLine\n ss <- getLine\n zz <- getLine\n\n let aa = conv (words gg) []\n bb = conv (words zz) []\n\n cc = sort aa\n dd = sort bb\n \n let ans = pairthem cc dd 0\n putStrLn (show ans)\n\n\n\n\n\n\n\n\n\n \n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n xs ::UArray Int Int <- listArray (1, n) . sort <$> getInts\n m <- readLn\n ys :: UArray Int Int <- listArray (1, m) . sort <$> getInts\n\n let\n r = listArray ((0, 0), (n, m)) $ map (uncurry f) [(i, j) | i <- [0..n], j <- [0..m]] :: Array (Int, Int) Int\n where\n f 0 _ = 0\n f _ 0 = 0\n\n f i j\n | abs (xs!i - ys!j) <= 1 = max (1 + r!(i-1, j-1)) (max (r!(i-1, j)) (r!(i, j-1)))\n | otherwise = max (r!(i-1, j)) (r!(i, j-1))\n\n print $ r!(n, m)\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List (sort)\nimport System.IO\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\nsolve :: Integral t => [t] -> [t] -> t\nsolve boys_skills girls_skills = process (sort boys_skills) (sort girls_skills)\n where\n process (x:xs) (y:ys)\n | x - y > 1 = process (x : xs) ys\n | x - y < -1 = process xs (y : ys)\n | otherwise = 1 + process xs ys\n process _ _ = 0\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin $ BlockBuffering Nothing\n hSetBuffering stdout $ BlockBuffering Nothing\n getLine\n boys_skills <- map read . words <$> getLine\n getLine\n girls_skills <- map read . words <$> getLine\n print $ solve boys_skills girls_skills\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map ( map read. words). (\\[a,b,c,d]->[b,d]) . take 4. lines\nsolve :: [[Integer]]->String\nsolve [xs,ys] = show $ slv1 (sort xs) (sort ys)\nslv1 [] (y:ys) =0\nslv1 (x:xs) [] =0\nslv1 [] [] =0\nslv1 (x:xs) (y:ys) | x-y>1 = slv1 (x:xs) (ys)\n | y-x>1 = slv1 (xs) (y:ys)\n |otherwise = 1+slv1 xs ys"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: [Int] -> [Int] -> Int\nsolve _ [] = 0\nsolve [] _ = 0\nsolve (x:xs) (y:ys)\n | abs (x - y) < 2 = 1 + solve xs ys\n | x < y = solve xs (y:ys)\n | otherwise = solve (x:xs) ys\n\nmain = do\n getLine\n bs <- sort.(fmap read).words <$> getLine\n getLine\n gs <- sort.(fmap read).words <$> getLine\n print $ solve bs gs\n"}, {"source_code": "-- Codeforces 489B\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n ns <- fmap (map read . words) getLine\n m <- fmap read getLine\n ms <- fmap (map read . words) getLine\n print $ solve n m (sort ns) (sort ms)\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve n m ns ms = snd $ foldl (\\(mss, acc) b -> case (findIndex (\\a -> (-1 <= b-a) && (1 >= b-a)) mss)\n of {\n Nothing -> (mss, acc);\n Just k -> (drop (k+1) mss, acc+1) ;\n }) (ms, 0) ns\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess [] _ n = n\nprocess _ [] n = n\nprocess (q1:q1s) (q2:q2s) n | abs (q1-q2) <=1 = process q1s q2s (n+1)\n | q1 getLine ::IO Int\n q1<- sort <$> map read <$> words <$> getLine ::IO [Int]\n n2<- read <$> getLine ::IO Int\n q2<- sort <$> map read <$> words <$> getLine ::IO [Int]\n print $ process q1 q2 0\n"}, {"source_code": "import Data.List\n\nf :: [Int] -> [Int] -> Int\nf [] x = 0\nf x [] = 0\nf (b:bs) (g:gs)\n | b>= print . solve . map (map read . words) . lines\n\nsolve :: [[Integer]] -> Integer\nsolve [_, as, _, bs] = go (sort as) (sort bs)\n where go xxs@(x:xs) yys@(y:ys) | x + 1 < y = go xs yys\n | y + 1 < x = go xxs ys\n | otherwise = 1 + go xs ys\n go _ _ = 0\nsolve _ = undefined\n"}, {"source_code": "import Data.List (sort)\nmain = interact $ show . length . uncurry merge . parse\nparse = go . map read . words where\n go (n:xs) = (sort bs,sort gs)\n where (bs,(_:gs)) = splitAt n xs\nmerge as@(a:as') bs@(b:bs')\n | abs (a-b) <= 1 = a : merge as' bs'\n | a < b = merge as' bs\n | a > b = merge as bs'\nmerge _ _ = []\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.List\n\n-- Meat\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = answer (sort as) (sort bs)\n\nanswer :: [Int] -> [Int] -> Int\nanswer [] _ = 0\nanswer _ [] = 0\nanswer (b:bs) (g:gs)\n | abs (b - g) <= 1 = 1 + answer bs gs\n | b < g = answer bs (g:gs)\n | b > g = answer (b:bs) gs\n\nanswer _ _ = error \"Sucker\"\n-- Shit\nmain :: IO ()\nmain = do\n [_, bs, _, gs] <- readShit\n printShit [solve bs gs]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents\n\ninstance Shit [String] where\n printShit = putStrLn . unlines\n readShit = fmap lines getContents"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\ncount [] _ n = n\ncount _ [] n = n\ncount (a:as) (b:bs) n | abs (a-b) <=1 = count as bs (n+1)\n | a getLine::IO [Int]\n\t\tgetLine\n \t\tb<- sort.map read. words <$> getLine::IO [Int]\n\t print $ count a b 0\n\t\t\n\t \n"}, {"source_code": "import Data.List (sort)\n\nprocess :: [Int] -> [Int] -> Int\nprocess as bs = f (sort as) (sort bs)\n where\n f [] _ = 0\n f _ [] = 0\n f as@(a:as') bs@(b:bs')\n | abs (a-b) <= 1 = 1 + f as' bs'\n | a < b = f as' bs\n | otherwise = f as bs'\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n m <- fmap readInt getLine\n bs <- fmap (map readInt.words) getLine\n print $ process as bs"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Data.List\n\n-- Meat\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = answer (sort as) (sort bs)\n\nanswer :: [Int] -> [Int] -> Int\nanswer [] _ = 0\nanswer _ [] = 0\nanswer (b:bs) (g:gs)\n | abs (b - g) <= 1 = 1 + answer bs gs\n | b < g = answer bs (g:gs)\n | b > g = answer (b:bs) gs\n\nanswer _ _ = error \"Sucker\"\n-- Shit\nmain :: IO ()\nmain = do\n [_, bs, _, gs] <- readShit\n printShit [solve bs gs]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents\n\ninstance Shit [String] where\n printShit = putStrLn . unlines\n readShit = fmap lines getContents"}, {"source_code": "import qualified Data.List as List\n\nsolve :: [Int] -> [Int] -> Int\nsolve [] _ = 0\nsolve _ [] = 0\nsolve ax@(x : xs) ay@(y : ys)\n | abs (x - y) <= 1 = 1 + solve xs ys\n | x < y = solve xs ay\n | x > y = solve ax ys\n\nmain = do\n getLine\n boy <- getLine\n getLine\n girl <- getLine\n let a = List.sort $ map read $ words boy\n b = List.sort $ map read $ words girl\n print $ solve a b\n\n"}, {"source_code": "import Data.List\n\nsolve [] _ = 0\nsolve _ [] = 0\nsolve (x:xs) (y:ys) | abs (x - y) <= 1 = 1 + solve xs ys\n | x < y = solve xs (y : ys)\n | otherwise = solve (x : xs) ys\n\nparseInput input = [sort xs, sort ys] where\n ls = lines input\n xs = map read $ words $ ls !! 1 :: [Int]\n ys = map read $ words $ ls !! 3 :: [Int]\n\nmain = do\n input <- getContents\n let [xs, ys] = parseInput input\n print $ solve xs ys\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List (foldl', sort)\nimport System.IO\n\ntoNum :: Num a => Bool -> a\ntoNum False = 0\ntoNum True = 1\n\nsolve :: Integral t => [t] -> [t] -> t\nsolve boys_skills girls_skills = process (sort boys_skills) (sort girls_skills)\n where\n process xs ys = foldl' (\\acc (x, y) -> acc + is_matching x y) 0 $ zip xs ys\n is_matching x y = toNum $ abs (x - y) <= 1\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin $ BlockBuffering Nothing\n hSetBuffering stdout $ BlockBuffering Nothing\n getLine\n boys_skills <- map read . words <$> getLine\n getLine\n girls_skills <- map read . words <$> getLine\n print $ solve boys_skills girls_skills\n"}, {"source_code": "-- Codeforces 489B\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n ns <- fmap (map read . words) getLine\n m <- fmap read getLine\n ms <- fmap (map read . words) getLine\n print $ solve n m ns ms\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int\nsolve n m ns ms = snd $ foldl (\\(mss, acc) b -> case (findIndex (\\a -> (-1 <= b-a) && (1 >= b-a)) mss)\n of {\n Nothing -> ([], acc);\n Just k -> (drop (k+1) mss, acc+1) ;\n }) (ms, 0) ns\n"}], "src_uid": "62766ef9a0751cbe7987020144de7512"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n replicateM 8 ((,) <$> readInt <*> readInt)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nmakeLine lst = BS.unwords (map (BS.pack.show) lst)\nsolve pts = case listToMaybe lst of\n Nothing -> BS.pack \"NO\"\n Just order -> BS.unlines [ BS.pack \"YES\"\n , makeLine (take 4 order)\n , makeLine (drop 4 order)\n ]\n where\n lst = [ order\n | (order, pts) <- unzip <$> permutations (zip [1..] pts)\n , checkRect (take 4 pts) && checkRect (drop 4 pts)\n , checkEq (take 4 pts)\n ]\n\n-- a b\n-- d c\ncheckRect [a, b, c, d] = and [ dot a b d == 0\n , dot b a c == 0\n , dot c b d == 0\n , dot d a c == 0\n ]\n\ncheckEq [a, b, c, d] = all (==head dists) dists\n where\n dists = [dist a b, dist b c, dist c d, dist d a]\n\ndot (x0, y0) (x1, y1) (x2, y2) = (x1 - x0) * (x2 - x0) + (y1 - y0) * (y2 - y0)\ndist (x1, y1) (x2, y2) = (x1 - x2)^2 + (y1 - y2)^2\n\n\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n", "positive_code": [{"source_code": "import Data.List\n\nseparate a 0 = [([],a)]\nseparate [] _ = []\nseparate (a:as) n = [ (a : fst cs, snd cs) | cs <- separate as (n-1) ]\n ++ [ (fst cs, a : snd cs) | cs <- separate as n ]\n\nisRectangle ps is = x && y\n where ps' = map (ps!!) is\n [a,b,c,d] = sort ps'\n x = (b `sub` a) `dotPro` (c `sub` a) == 0 \n y = a `add` d == b `add` c\n\nisRhombus ps is = x == y\n where ps' = map (ps!!) is\n [a,b,c,d] = sort ps'\n x = size2 (b `sub` a)\n y = size2 (c `sub` a)\n\nsolve ps (x, y) = isRectangle ps x\n && isRhombus ps x\n && isRectangle ps y\n\nadd (a,b) (c,d) = (a+c, b+d)\nsub (a,b) (c,d) = (a-c, b-d)\ndotPro (a,b) (c,d) = a*c + b*d\nsize2 (a,b) = a*a + b*b\n\nprintAns (Just x) = do\n putStrLn \"YES\"\n putStrLn (unwords . map (show . (+1)) $ fst x)\n putStrLn (unwords . map (show . (+1)) $ snd x)\nprintAns Nothing = putStrLn \"NO\"\n\n\nmain = do\n ps <- mapM (fmap ((\\[x,y] -> (x,y)) . map read . words)) $ map (\\_ -> getLine) [1..8] :: IO [(Int, Int)]\n printAns $ find (solve ps) (separate [0..7] 4)\n\n-- vim: set expandtab:\n"}, {"source_code": "import List\n\ntype Point = (Int, Int)\ntype P4 = (Point, Point, Point, Point)\ntype P8 = (Point, Point, Point, Point, Point, Point, Point, Point)\ntype I4 = (Int, Int, Int, Int)\n\nfromP4 :: P4 -> [Point]\nfromP4 (p1, p2, p3, p4) = [p1, p2, p3, p4]\n\nfromP8 :: P8 -> [Point]\nfromP8 (p1, p2, p3, p4, p5, p6, p7, p8) = [p1, p2, p3, p4, p5, p6, p7, p8]\n\ntoP8 :: [Point] -> P8\ntoP8 [p1, p2, p3, p4, p5, p6, p7, p8] = (p1, p2, p3, p4, p5, p6, p7, p8)\n\nfromI4 :: I4 -> [Int]\nfromI4 (i1, i2, i3, i4) = [i1, i2, i3, i4]\n\n-----------------------------------------------------------------------------\n\ndistSquare :: (Point, Point) -> Int\ndistSquare ((x1, y1), (x2, y2)) = (x1 - x2)^2 + (y1 - y2)^2\n\ngetDistances :: P4 -> [Int]\ngetDistances p4 =\n map distSquare [(ps !! i, ps !! j) | i <- [0..3], j <- [0..3], i < j]\n where\n ps = fromP4 p4\n\ncheckSquare :: P4 -> Bool\ncheckSquare p4 =\n a1 > 0 && a1 == a4 && a5 == 2 * a1 && a5 == a6\n where\n [a1, a2, a3, a4, a5, a6] = sort (getDistances p4)\n \nequalDistances :: ((Point, Point), (Point, Point)) -> Bool\nequalDistances (ps1, ps2) = distSquare ps1 == distSquare ps2 \n \ncheckParas :: P4 -> Bool\ncheckParas (p1, p2, p3, p4)\n = and (map equalDistances [((p1, p2), (p3, p4)), ((p1, p3), (p2, p4)), ((p1, p4), (p2, p3))])\n \ncheckRectangle :: P4 -> Bool\ncheckRectangle p4 =\n a1 > 0 && a1 == a2 && a3 == a4 && a5 == a1 + a3 && a5 == a6\n &&\n checkParas p4\n where\n [a1, a2, a3, a4, a5, a6] = sort (getDistances p4)\n \n----------------------------------------------------------------------------- \n\nnext :: Maybe I4 -> Maybe I4\nnext Nothing = Nothing\nnext (Just (4, 5, 6, 7)) = Nothing\nnext (Just (a, 5, 6, 7)) = Just (a + 1, a + 2, a + 3, a + 4)\nnext (Just (a, b, 6, 7)) = Just (a, b + 1, b + 2, b + 3)\nnext (Just (a, b, c, 7)) = Just (a, b, c + 1, c + 2)\nnext (Just (a, b, c, d)) = Just (a, b, c, d + 1)\n\nfirstSelection :: I4\nfirstSelection = (0, 1, 2, 3)\n\ngenerateSelections :: [Maybe I4]\ngenerateSelections = takeWhile (/= Nothing) (iterate next (Just firstSelection))\n\notherElements :: I4 -> I4\notherElements i4 = (j1, j2, j3, j4)\n where\n [j1, j2, j3, j4] = filter (\\x -> not (elem x (fromI4 i4))) [0..7]\n\ncheckSelection :: P8 -> Maybe I4 -> Bool\ncheckSelection p8 (Just is) =\n checkSquare (ps !! i1, ps !! i2, ps !! i3, ps !! i4)\n &&\n checkRectangle (ps !! j1, ps !! j2, ps !! j3, ps !! j4)\n where\n ps = fromP8 p8\n (i1, i2, i3, i4) = is\n (j1, j2, j3, j4) = otherElements is\n \n----------------------------------------------------------------------------- \n \nsolve :: P8 -> Maybe I4\nsolve ps\n | null solution = Nothing\n | otherwise = head solution\n where\n solution = filter (checkSelection ps) generateSelections\n \nprintAns :: Maybe I4 -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just i4) = do\n putStrLn \"YES\"\n sequence_ (map (\\x -> putStr (show (xs !! x + 1) ++ \" \")) [0..3])\n putStrLn \"\"\n sequence_ (map (\\x -> putStr (show (ys !! x + 1) ++ \" \")) [0..3])\n putStrLn \"\"\n where\n xs = fromI4 i4\n ys = fromI4 (otherElements i4)\n \n-----------------------------------------------------------------------------\n\nparsePoint :: String -> Point\nparsePoint line = (x, y)\n where\n [x, y] = map read (words line)\n\nreadPoint :: IO Point\nreadPoint = do\n getLine >>= return . parsePoint\n \nreadPoints :: IO P8\nreadPoints = do\n ps <- sequence (map (\\x -> readPoint) [1..8])\n return (toP8 ps)\n\nmain :: IO ()\nmain = readPoints >>= printAns . solve\n"}, {"source_code": "\nimport Control.Monad (liftM, when)\nimport Data.List ((\\\\), intercalate, nub, sort)\nimport Data.Maybe (listToMaybe)\nimport Prelude hiding (print)\n\ntype Point = (Int, Int)\n\nn :: Int\nn = 8\n\nparsePoint :: String -> Point\nparsePoint s = case map read (words s) of\n [x, y] -> (x, y)\n\ngetSDists :: [Point] -> [Int]\ngetSDists ps = [sDist p1 p2 | p1 <- ps, p2 <- ps, p1 < p2]\n\nsDist :: Point -> Point -> Int\nsDist (x1, y1) (x2, y2) = sum $ map (^2) $ zipWith (-) [x1, y1] [x2, y2]\n\nisFigure :: [Point] -> ([Int] -> Bool) -> Bool\nisFigure ps check = check $ sort $ getSDists ps\n\nisSquare :: [Point] -> Bool\nisSquare ps = isFigure ps check\n where\n check [d1, d2, d3, d4, d5, d6] = d1 > 0 && d1 == d2 && d2 == d3 && d3 == d4 && d5 == d6 && d1 + d3 == d5\n \nisRectangle :: [Point] -> Bool\nisRectangle [p1, p2, p3, p4]\n = a1 > 0 && a1 == a2\n && b1 > 0 && b1 == b2\n && c1 > 0 && c1 == c2\n && sum [a1, b1, c1] - 2 * maximum [a1, b1, c1] == 0\n where\n a1 = sDist p1 p2\n a2 = sDist p3 p4\n b1 = sDist p1 p3\n b2 = sDist p2 p4\n c1 = sDist p1 p4\n c2 = sDist p2 p3\n\nsolve :: [Point] -> Maybe ([Int], [Int])\nsolve ps = listToMaybe $ do\n let ps' = zip [1..] ps\n sq <- [[p1, p2, p3, p4] | p1 <- ps', p2 <- ps', p3 <- ps', p4 <- ps', snd p1 < snd p2, snd p2 < snd p3, snd p3 < snd p4]\n let rc = ps' \\\\ sq\n if (isSquare (map snd sq) && isRectangle (map snd rc))\n then return (map fst sq, map fst rc)\n else fail \"\" \n\nprint :: Maybe ([Int], [Int]) -> IO ()\nprint Nothing = putStrLn \"NO\"\nprint (Just (as, bs)) = putStrLn \"YES\" >> prints as >> prints bs\n where\n prints xs = putStrLn $ intercalate \" \" (map show xs)\n\nmain :: IO ()\nmain = do\n ps <- liftM (take n . map parsePoint . lines) getContents\n print $ solve ps\n"}], "negative_code": [{"source_code": "import Data.List\n\nseparate a 0 = [([],a)]\nseparate [] _ = []\nseparate (a:as) n = [ (a : fst cs, snd cs) | cs <- separate as (n-1) ]\n ++ [ (fst cs, a : snd cs) | cs <- separate as n ]\n\nisRectangle ps is = x && y\n where ps' = map (ps!!) is\n [a,b,c,d] = sort ps'\n x = (b `sub` a) `dotPro` (c `sub` a) == 0 \n y = a `add` d == b `add` c\n\nisRectangle2 ps (x, y) = isRectangle ps x && isRectangle ps y\n\nadd (a,b) (c,d) = (a+c, b+d)\nsub (a,b) (c,d) = (a-c, b-d)\ndotPro (a,b) (c,d) = a*c + b*d\n\nprintAns (Just x) = do\n putStrLn \"YES\"\n putStrLn (unwords . map (show . (+1)) $ fst x)\n putStrLn (unwords . map (show . (+1)) $ snd x)\nprintAns Nothing = putStrLn \"NO\"\n\n\nmain = do\n ps <- mapM (fmap ((\\[x,y] -> (x,y)) . map read . words)) $ map (\\_ -> getLine) [1..8] :: IO [(Int, Int)]\n printAns $ find (isRectangle2 ps) (separate [0..7] 4)\n\n-- vim: set expandtab:\n"}, {"source_code": "\nimport Control.Monad (liftM, when)\nimport Data.List ((\\\\), intercalate, nub, sort)\nimport Data.Maybe (listToMaybe)\nimport Prelude hiding (print)\n\ntype Point = (Int, Int)\n\nn :: Int\nn = 8\n\nparsePoint :: String -> Point\nparsePoint s = case map read (words s) of\n [x, y] -> (x, y)\n\ngetSDists :: [Point] -> [Int]\ngetSDists ps = [sDist p1 p2 | p1 <- ps, p2 <- ps, p1 < p2]\n where\n sDist (x1, y1) (x2, y2) = sum $ map (^2) $ zipWith (-) [x1, y1] [x2, y2]\n\nisFigure :: [Point] -> ([Int] -> Bool) -> Bool\nisFigure ps check = check $ sort $ getSDists ps\n\nisRectangle, isSquare :: [Point] -> Bool\nisRectangle ps = isFigure ps check\n where\n check [d1, d2, d3, d4, d5, d6] = d1 > 0 && d1 == d2 && d3 == d4 && d5 == d6 && d1 + d3 == d5\nisSquare ps = isFigure ps check\n where\n check [d1, d2, d3, d4, d5, d6] = d1 > 0 && d1 == d2 && d2 == d3 && d3 == d4 && d5 == d6 && d1 + d3 == d5\n\nsolve :: [Point] -> Maybe ([Int], [Int])\nsolve ps = listToMaybe $ do\n let ps' = zip [1..] ps\n sq <- [[p1, p2, p3, p4] | p1 <- ps', p2 <- ps', p3 <- ps', p4 <- ps', snd p1 < snd p2, snd p2 < snd p3, snd p3 < snd p4]\n let rc = ps' \\\\ sq\n if (isSquare (map snd sq) && isRectangle (map snd rc))\n then return (map fst sq, map fst rc)\n else fail \"\" \n\nprint :: Maybe ([Int], [Int]) -> IO ()\nprint Nothing = putStrLn \"NO\"\nprint (Just (as, bs)) = putStrLn \"YES\" >> prints as >> prints bs\n where\n prints xs = putStrLn $ intercalate \" \" (map show xs)\n\nmain :: IO ()\nmain = do\n ps <- liftM (take n . map parsePoint . lines) getContents\n print $ solve ps\n"}, {"source_code": "\nimport Control.Monad (liftM, when)\nimport Data.List ((\\\\), intercalate, nub, sort)\nimport Data.Maybe (listToMaybe)\nimport Prelude hiding (print)\n\ntype Point = (Int, Int)\n\nn :: Int\nn = 8\n\nparsePoint :: String -> Point\nparsePoint s = case map read (words s) of\n [x, y] -> (x, y)\n\ngetSDists :: [Point] -> [Int]\ngetSDists ps = [sDist p1 p2 | p1 <- ps, p2 <- ps, p1 < p2]\n where\n sDist (x1, y1) (x2, y2) = sum $ map (^2) $ zipWith (-) [x1, y1] [x2, y2]\n\nsortAndNub :: [Point] -> [Int]\nsortAndNub = sort . nub . getSDists\n\nisFigure :: [Point] -> ([Int] -> Bool) -> Bool\nisFigure ps check = check $ sortAndNub ps\n\nisRectangle, isSquare :: [Point] -> Bool\nisRectangle ps = isFigure ps (\\ds -> head ds > 0 && length ds <= 3)\nisSquare ps = isFigure ps (\\ds -> head ds > 0 && length ds == 2)\n\nsolve :: [Point] -> Maybe ([Int], [Int])\nsolve ps = listToMaybe $ do\n let ps' = zip [1..] ps\n sq <- [[p1, p2, p3, p4] | p1 <- ps', p2 <- ps', p3 <- ps', p4 <- ps', snd p1 < snd p2, snd p2 < snd p3, snd p3 < snd p4]\n let rc = ps' \\\\ sq\n if (isSquare (map snd sq) && isRectangle (map snd rc))\n then return (map fst sq, map fst rc)\n else fail \"\" \n\nprint :: Maybe ([Int], [Int]) -> IO ()\nprint Nothing = putStrLn \"NO\"\nprint (Just (as, bs)) = putStrLn \"YES\" >> prints as >> prints bs\n where\n prints xs = putStrLn $ intercalate \" \" (map show xs)\n\nmain :: IO ()\nmain = do\n ps <- liftM (take n . map parsePoint . lines) getContents\n print $ solve ps\n"}, {"source_code": "\nimport Control.Monad (liftM, when)\nimport Data.List ((\\\\), intercalate, nub, sort)\nimport Data.Maybe (listToMaybe)\nimport Prelude hiding (print)\n\ntype Point = (Int, Int)\n\nn :: Int\nn = 8\n\nparsePoint :: String -> Point\nparsePoint s = case map read (words s) of\n [x, y] -> (x, y)\n\ngetSDists :: [Point] -> [Int]\ngetSDists ps = [sDist p1 p2 | p1 <- ps, p2 <- ps, p1 < p2]\n where\n sDist (x1, y1) (x2, y2) = sum $ map (^2) $ zipWith (-) [x1, y1] [x2, y2]\n\nisFigure :: [Point] -> ([Int] -> Bool) -> Bool\nisFigure ps check = check $ sort $ getSDists ps\n\nisRectangle, isSquare :: [Point] -> Bool\nisRectangle ps = isFigure ps check\n where\n check [d1, d2, d3, d4, d5, d6] = d1 > 0 && d1 == d2 && d3 == d4 && d5 == d6 \nisSquare ps = isFigure ps check\n where\n check [d1, d2, d3, d4, d5, d6] = d1 > 0 && d1 == d2 && d2 == d3 && d3 == d4 && d5 == d6\n\nsolve :: [Point] -> Maybe ([Int], [Int])\nsolve ps = listToMaybe $ do\n let ps' = zip [1..] ps\n sq <- [[p1, p2, p3, p4] | p1 <- ps', p2 <- ps', p3 <- ps', p4 <- ps', snd p1 < snd p2, snd p2 < snd p3, snd p3 < snd p4]\n let rc = ps' \\\\ sq\n if (isSquare (map snd sq) && isRectangle (map snd rc))\n then return (map fst sq, map fst rc)\n else fail \"\" \n\nprint :: Maybe ([Int], [Int]) -> IO ()\nprint Nothing = putStrLn \"NO\"\nprint (Just (as, bs)) = putStrLn \"YES\" >> prints as >> prints bs\n where\n prints xs = putStrLn $ intercalate \" \" (map show xs)\n\nmain :: IO ()\nmain = do\n ps <- liftM (take n . map parsePoint . lines) getContents\n print $ solve ps\n"}, {"source_code": "import List\n\ntype Point = (Int, Int)\ntype P4 = (Point, Point, Point, Point)\ntype P8 = (Point, Point, Point, Point, Point, Point, Point, Point)\ntype I4 = (Int, Int, Int, Int)\n\nfromP4 :: P4 -> [Point]\nfromP4 (p1, p2, p3, p4) = [p1, p2, p3, p4]\n\nfromP8 :: P8 -> [Point]\nfromP8 (p1, p2, p3, p4, p5, p6, p7, p8) = [p1, p2, p3, p4, p5, p6, p7, p8]\n\ntoP8 :: [Point] -> P8\ntoP8 [p1, p2, p3, p4, p5, p6, p7, p8] = (p1, p2, p3, p4, p5, p6, p7, p8)\n\nfromI4 :: I4 -> [Int]\nfromI4 (i1, i2, i3, i4) = [i1, i2, i3, i4]\n\n-----------------------------------------------------------------------------\n\ndistSquare :: (Point, Point) -> Int\ndistSquare ((x1, y1), (x2, y2)) = (x1 - x2)^2 + (y1 - y2)^2\n\ngetDistances :: P4 -> [Int]\ngetDistances p4 =\n map distSquare [(ps !! i, ps !! j) | i <- [0..3], j <- [0..3], i < j]\n where\n ps = fromP4 p4\n\ncheckSquare :: P4 -> Bool\ncheckSquare p4 =\n a1 > 0 && a1 == a4 && a5 == 2 * a1 && a5 == a6\n where\n [a1, a2, a3, a4, a5, a6] = sort (getDistances p4)\n \ncheckRectangle :: P4 -> Bool\ncheckRectangle p4 =\n a1 > 0 && a1 == a2 && a3 == a4 && a5 == a1 + a3 && a5 == a6\n where\n [a1, a2, a3, a4, a5, a6] = sort (getDistances p4)\n \n----------------------------------------------------------------------------- \n\nnext :: Maybe I4 -> Maybe I4\nnext Nothing = Nothing\nnext (Just (4, 5, 6, 7)) = Nothing\nnext (Just (a, 5, 6, 7)) = Just (a + 1, a + 2, a + 3, a + 4)\nnext (Just (a, b, 6, 7)) = Just (a, b + 1, b + 2, b + 3)\nnext (Just (a, b, c, 7)) = Just (a, b, c + 1, c + 2)\nnext (Just (a, b, c, d)) = Just (a, b, c, d + 1)\n\nfirstSelection :: I4\nfirstSelection = (0, 1, 2, 3)\n\ngenerateSelections :: [Maybe I4]\ngenerateSelections = takeWhile (/= Nothing) (iterate next (Just firstSelection))\n\notherElements :: I4 -> I4\notherElements i4 = (j1, j2, j3, j4)\n where\n [j1, j2, j3, j4] = filter (\\x -> not (elem x (fromI4 i4))) [0..7]\n\ncheckSelection :: P8 -> Maybe I4 -> Bool\ncheckSelection p8 (Just is) =\n checkSquare (ps !! i1, ps !! i2, ps !! i3, ps !! i4)\n &&\n checkRectangle (ps !! j1, ps !! j2, ps !! j3, ps !! j4)\n where\n ps = fromP8 p8\n (i1, i2, i3, i4) = is\n (j1, j2, j3, j4) = otherElements is\n \n----------------------------------------------------------------------------- \n \nsolve :: P8 -> Maybe I4\nsolve ps\n | null solution = Nothing\n | otherwise = head solution\n where\n solution = filter (checkSelection ps) generateSelections\n \nprintAns :: Maybe I4 -> IO ()\nprintAns Nothing = putStrLn \"NO\"\nprintAns (Just i4) = do\n putStrLn \"YES\"\n sequence_ (map (\\x -> putStr (show (xs !! x + 1) ++ \" \")) [0..3])\n putStrLn \"\"\n sequence_ (map (\\x -> putStr (show (ys !! x + 1) ++ \" \")) [0..3])\n putStrLn \"\"\n where\n xs = fromI4 i4\n ys = fromI4 (otherElements i4)\n \n-----------------------------------------------------------------------------\n\nparsePoint :: String -> Point\nparsePoint line = (x, y)\n where\n [x, y] = map read (words line)\n\nreadPoint :: IO Point\nreadPoint = do\n getLine >>= return . parsePoint\n \nreadPoints :: IO P8\nreadPoints = do\n ps <- sequence (map (\\x -> readPoint) [1..8])\n return (toP8 ps)\n\nmain :: IO ()\nmain = readPoints >>= printAns . solve\n"}], "src_uid": "a36fb51b1ebb3552308e578477bdce8f"} {"source_code": "import qualified Data.Map as M\nmain = interact $ unlines . map show . f . lines\nf (nk:a:nq:q) = g k m la (map (\\(x,y) -> x*y) l) (map read q)\n where m = foldl (\\m' (x,y) -> M.insertWith' min (x*y) x m') (M.singleton 0 0) l\n l = concatMap (\\x -> map (\\y -> (x,y)) la) [1..k]\n la = map read $ words a\n k = read . last $ words nk\ng k m a l = map (\\x -> z . minimum $ zipWith (+) v (h $ map ((-)x) l))\n where v = h l\n h = map (t . flip M.lookup m)\n t Nothing = k+1\n t (Just x) = x\n z x | x > k = -1 | True = x\n", "positive_code": [{"source_code": "import qualified Data.Map as M\nmain = interact $ unlines . map show . f . lines\nf (nk:a:nq:q) = g k m la (map (\\(x,y) -> x*y) l) (map read q)\n where m = foldl (\\m' (x,y) -> M.insertWith' min (x*y) x m') (M.singleton 0 0) l\n l = concatMap (\\x -> map (\\y -> (x,y)) la) [1..k]\n la = map read $ words a\n k = read . last $ words nk\ng k m a l = map (\\x -> z . minimum $ zipWith (+) v (h $ map ((-)x) l))\n where v = h l\n h = map (t . flip M.lookup m)\n t Nothing = k+1\n t (Just x) = x\n z x | x > k = -1 | True = x\n"}], "negative_code": [], "src_uid": "5d8521e467cad53cf9403200e4c99b89"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, foldM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n foldM_ (\\(node, pos) (n, c) -> do\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n loop node (pos+1) 0\n ) (0, 0) (zip [1..] s)\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' Nothing = dfs (d+l) t'\n f' (Just (k, _)) | k > s+l-1 = dfs (d+l) t'\n f' (Just (k, v)) =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n\n print r\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, foldM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n foldM_ (\\(node, pos) (n, c) -> do\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n loop node (pos+1) 0\n ) (0, 0) (zip [1..] s)\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n (m, s) = foldl1 (\\(a, b) (c, d) -> (max a c, b + d)) $ map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' (Just (k, v)) | k <= s+l-1 =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n f' _ = dfs (d+l) t'\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' Nothing = dfs (d+l) t'\n f' (Just (k, _)) | k > s+l-1 = dfs (d+l) t'\n f' (Just (k, v)) =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, foldM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n foldM_ (\\(node, pos) (n, c) -> do\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n loop node (pos+1) 0\n ) (0, 0) (zip [1..] s)\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' Nothing = dfs (d+l) t'\n f' (Just (k, _)) | k > s+l-1 = dfs (d+l) t'\n f' (Just (k, v)) =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.List (find, elemIndex)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a] deriving (Show)\ndata Edge a = Edge !Int !Int (SuffixTree a) deriving (Show)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n t = suffixTree s\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = IntMap.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n (r, _) = dfs 0 t\n where\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge s l t') = f' $ IntMap.lookupGE s places\n where\n f' Nothing = dfs (d+l) t'\n f' (Just (k, _)) | k > s+l-1 = dfs (d+l) t'\n f' (Just (k, v)) =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, foldM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n foldM_ (\\(node, pos) (n, c) -> do\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n loop node (pos+1) 0\n ) (0, 0) (zip [1..] s)\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n m = maximum ms\n s = sum ss\n\n (ms, ss) = unzip $ map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' (Just (k, v)) | k <= s+l-1 =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n f' _ = dfs (d+l) t'\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, foldM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n foldM_ (\\(node, pos) (n, c) -> do\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n loop node (pos+1) 0\n ) (0, 0) (zip [1..] s)\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' Nothing = dfs (d+l) t'\n f' (Just (k, _)) | k > s+l-1 = dfs (d+l) t'\n f' (Just (k, v)) =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (find, elemIndex)\nimport Data.Maybe (fromJust)\nimport Data.Char (ord)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.IntMap (IntMap)\nimport Data.Int (Int64)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace (trace)\n\nsolve :: [Int] -> UArray Int Int -> IntMap Int -> (Int64, Int64)\nsolve s cs' places = runST $ do\n let n = length s\n let nnn = n\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) IntMap.empty :: ST s (STArray s Int (IntMap Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s :: UArray Int Int\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = IntMap.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = IntMap.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = IntMap.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (IntMap.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = IntMap.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n dfs d i = do\n m <- readArray maps i\n if IntMap.null m\n then return $ (-10^9 :: Int64, 0 :: Int64)\n else do\n rs <- forM (IntMap.elems m) $ \\i -> do\n s <- readArray starts i\n l <- readArray lens i\n\n let\n r = min nnn (s+l)\n delim = IntMap.lookupGE (s+1) places\n\n f' Nothing = dfs (d + (fromIntegral l)) i\n f' (Just (k, _)) | k > r = dfs (d + (fromIntegral l)) i\n f' (Just (k, v)) = return $ if p == 0 then (0 :: Int64, c) else (((fromIntegral d)+p)*c, c)\n where\n p = fromIntegral $ k - 1 - s :: Int64\n c = fromIntegral (cs' ! (v - (10^6 :: Int))) :: Int64\n\n f' delim\n\n let\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n return $ (max m (s * (fromIntegral d)), s)\n\n\n dfs (0 :: Int) 0\n\n-- data Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n s' = concat . map (\\(t, i) -> map ord t ++ [i + 10^6]) $ zip ts [1..] :: [Int]\n places :: IntMap Int\n places = IntMap.fromList $ filter (\\(a, b) -> b > 10^6) $ zip [1..] s'\n cs' = listArray (1, length cs) cs :: UArray Int Int\n\n (r, _) = solve s' cs' places\n\n -- print t\n\n -- let\n -- p k (Node es) =\n -- forM_ es $ \\(Edge (i, l) t) -> do\n -- putStrLn $ (replicate k ' ') ++ (concat $ map show $ take l $ drop i s')\n -- p (k + 2) t\n\n -- p 0 t\n\n print r\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.List (find, elemIndex)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Map (Map)\nimport Data.Int (Int64)\nimport qualified Data.Map as Map\n-- import Debug.Trace (trace)\n\ndata SuffixTree a = Node [Edge a] deriving (Show)\ndata Edge a = Edge (Int, Int) (SuffixTree a) deriving (Show)\n\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start, len) t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n s' = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n sa = listArray (1, length s') s'\n cs' = listArray (1, length cs) cs\n\n t = suffixTree s'\n\n dfs _ (Node []) = (0 :: Int64, 0 :: Int64)\n dfs d (Node es) = -- trace (\"es = \" ++ show es ++ \" s = \" ++ show s ++ \" m = \" ++ show m) $\n (max m (s * d), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge (s, l) t') = f' delim\n where\n ss = map (sa !) [s+1..s+l]\n\n delim = find is ss\n where\n is (CharItem _) = False\n is (DelimItem _) = True\n\n f' Nothing = dfs (d + (fromIntegral l)) t'\n f' (Just e@(DelimItem i)) = ((d+p)*c, c)\n where\n p = fromIntegral $ fromJust $ elemIndex e ss\n c = fromIntegral (cs' ! i) :: Int64\n\n\n (r, _) = dfs 0 t\n\n -- print t\n\n -- let\n -- p k (Node es) =\n -- forM_ es $ \\(Edge (i, l) t) -> do\n -- putStrLn $ (replicate k ' ') ++ (concat $ map show $ take l $ drop i s')\n -- p (k + 2) t\n\n -- p 0 t\n\n print r\n"}, {"source_code": "{-# LANGUAGE NPlusKPatterns, FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM_, replicateM)\nimport Data.Array (listArray, (!))\nimport Data.List (find, elemIndex)\nimport Data.Maybe (fromJust)\n\ndata STree a = Leaf | Branch [(Label a, STree a)] deriving (Eq, Show)\ntype Label a = ([a], Int)\n\nisTword :: (Eq a) => (Label a) -> (STree a) -> Bool\nisTword (a:w, 0) (Branch es) = [] /= [0 | ((c:_,_),_) <- es, a == c]\nisTword (a:w, wlen+1) (Branch es)\n | Leaf == node || wlen < ulen = w !! wlen == u !! wlen\n | otherwise = isTword (drop ulen w, wlen-ulen) node\n where (u, ulen, node) = head [(u, culen-1, node) | ((c:u, culen), node) <- es, a == c]\n\nupdate :: (Ord a) => (STree a, Label a) -> (STree a, Label a)\nupdate (root, (s, slen))\n | isTword (s, slen) root = (root, (s, slen+1))\n | 0 == slen = (root', (tail s, 0))\n | otherwise = update (root', (tail s, slen-1))\n where root' = insRelStuff (s, slen) root\n\ninsRelStuff :: (Ord a) => (Label a) -> (STree a) -> (STree a)\ninsRelStuff (aw@(a:w), 0) (Branch es)\n = Branch (g es)\n where\n g [] = [((aw, length aw), Leaf)]\n g (cusn@((c:u, culen), node):es')\n | a > c = cusn:g es'\n | otherwise = ((aw, length aw), Leaf):cusn:es'\ninsRelStuff (aw@(a:w), slen) (Branch es)\n = Branch (g es)\n where\n g (cusn@(cus@(cu@(c:_), culen), node):es')\n | a /= c = cusn:g es'\n | Leaf /= node && slen >= culen = (cus, node'):es'\n | head x < head y = ((cu, slen), Branch [ex, ey]):es'\n | otherwise = ((cu,slen), Branch [ey, ex]):es'\n where\n node' = insRelStuff (drop culen aw, slen-culen) node\n x = drop slen cu\n y = drop slen aw\n ex | Leaf == node = ((x, length x), Leaf)\n | otherwise = ((x, culen-slen), node)\n ey = ((y, length y), Leaf)\n\nstree :: (Ord a) => [a] -> STree a\nstree t = fst (until stop update (Branch [],(t,0)))\n where stop (_,(s, slen)) = [] == drop slen s\n\ndata Item = CharItem Char | DelimItem Int deriving (Eq, Ord, Show)\n\np i Leaf = return ()\np i (Branch es) =\n forM_ es $ \\((s, k), e) -> do\n putStrLn $ (replicate i ' ') ++ show (take k s)\n p (i + 2) e\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n s' = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n cs' = listArray (1, length cs) cs\n\n t = stree s'\n\n dfs _ Leaf = (0, 0)\n dfs d (Branch es) = (max m (s * d), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f ((s, l), t') = f' delim\n where\n delim = find is $ take l s\n where\n is (CharItem _) = False\n is (DelimItem _) = True\n\n f' Nothing = dfs (d + l) t'\n f' (Just e@(DelimItem i)) = (d + p*c, c)\n where\n p = fromJust $ elemIndex e s\n c = cs' ! i\n\n\n (r, _) = dfs 0 t\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n t = suffixTree s\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n (r, _) = dfs 0 t\n where\n dfs :: Int -> SuffixTree a -> (Int, Int)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' Nothing = dfs (d+l) t'\n f' (Just (k, _)) | k > s+l-1 = dfs (d+l) t'\n f' (Just (k, v)) =\n if p == 0 then (0, c) else ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, foldM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Int (Int64)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\ndata SuffixTree a = Node [Edge a]\ndata Edge a = Edge !Int !Int (SuffixTree a)\n\nsuffixTree :: (Ord a) => [a] -> SuffixTree a\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n foldM_ (\\(node, pos) (n, c) -> do\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n loop node (pos+1) 0\n ) (0, 0) (zip [1..] s)\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start+1) len t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine\n\n let\n (r, _) = dfs 0 t\n where\n t = suffixTree s\n where\n s = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n\n cs' = listArray (1, length cs) cs\n places = Map.fromList $ zip (scanl1 (+) $ map ((+1) . length) ts) [1..]\n\n dfs :: Int -> SuffixTree a -> (Int64, Int64)\n dfs _ (Node []) = (-10^9, 0)\n dfs d (Node es) = (max m (s * (fromIntegral d)), s)\n where\n s = sum ss\n m = maximum ms\n\n (ms, ss) = unzip $ map f es\n where\n f (Edge s l t') = f' $ Map.lookupGE s places\n where\n f' (Just (k, v)) | k <= s+l-1 =\n ((fromIntegral (d+p))*c, c)\n where\n p = k - s\n c = fromIntegral (cs' ! v)\n f' _ = dfs (d+l) t'\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.List (find, elemIndex)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Map (Map)\nimport Data.Int (Int64)\nimport qualified Data.Map as Map\n-- import Debug.Trace (trace)\n\ndata SuffixTree a = Node [Edge a] deriving (Show)\ndata Edge a = Edge (Int, Int) (SuffixTree a) deriving (Show)\n\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c -- && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start, len) t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n s' = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n sa = listArray (1, length s') s'\n cs' = listArray (1, length cs) cs\n\n t = suffixTree s'\n\n dfs _ (Node []) = (0 :: Int64, 0 :: Int64)\n dfs d (Node es) = -- trace (\"es = \" ++ show es ++ \" s = \" ++ show s ++ \" m = \" ++ show m) $\n (max m (s * d), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge (s, l) t') = f' delim\n where\n ss = map (sa !) [s+1..s+l]\n\n delim = find is ss\n where\n is (CharItem _) = False\n is (DelimItem _) = True\n\n f' Nothing = dfs (d + (fromIntegral l)) t'\n f' (Just e@(DelimItem i)) = ((d+p)*c, c)\n where\n p = fromIntegral $ fromJust $ elemIndex e ss\n c = fromIntegral (cs' ! i) :: Int64\n\n\n (r, _) = dfs 0 t\n\n -- print t\n\n -- let\n -- p k (Node es) =\n -- forM_ es $ \\(Edge (i, l) t) -> do\n -- putStrLn $ (replicate k ' ') ++ (concat $ map show $ take l $ drop i s')\n -- p (k + 2) t\n\n -- p 0 t\n\n print r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM, forM_, replicateM)\nimport Control.Monad.ST.Safe (ST, runST)\nimport Data.Array (listArray, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray, newArray_)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\nimport Data.List (find, elemIndex)\nimport Data.Maybe (fromJust)\nimport Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n-- import Debug.Trace (trace)\n\ndata SuffixTree a = Node [Edge a] deriving (Show)\ndata Edge a = Edge (Int, Int) (SuffixTree a) deriving (Show)\n\nsuffixTree s = runST $ do\n let n = length s\n lens <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n maps <- newArray (0, 2*n-1) Map.empty :: ST s (STArray s Int (Map a Int))\n starts <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n links <- newArray (0, 2*n-1) 0 :: ST s (STUArray s Int Int)\n let a = listArray (0, n-1) s\n\n m' <- newSTRef 1\n writeArray lens 0 (10^9)\n\n node' <- newSTRef 0\n pos' <- newSTRef 0\n\n let\n makeNode i l = do\n m <- readSTRef m'\n writeArray starts m i\n writeArray lens m l\n modifySTRef m' (+1)\n return m\n\n forM_ (zip [1..] s) $ \\(n, c) -> do\n node <- readSTRef node'\n pos <- readSTRef pos'\n\n let\n loop node 0 _ = return (node, 0)\n loop node pos last = do\n let\n move node pos = do\n map <- readArray maps node\n let node' = Map.findWithDefault 0 (a ! (n - pos)) map\n l <- readArray lens node'\n if pos > l\n then move node' (pos - l)\n else return (node, pos)\n\n (node', pos') <- move node pos\n\n let cc = a ! (n-pos')\n map <- readArray maps node'\n let v = Map.findWithDefault 0 cc map\n start <- readArray starts v\n let t = a ! (start + pos' - 1)\n\n if v == 0\n then do\n v <- makeNode (n-pos') (10^9 :: Int)\n writeArray links last node'\n\n let map' = Map.insert cc v map\n writeArray maps node' map'\n\n if node' == 0\n then loop node' (pos'-1) 0\n else do\n link <- readArray links node'\n loop link pos' 0\n else if t == c && start+pos-1 < n\n then do\n writeArray links last node'\n return (node', pos')\n else do\n u <- makeNode start (pos'-1)\n w <- makeNode (n-1) (10^9)\n writeArray maps u (Map.fromList [(c, w), (t, v)])\n writeArray starts v (start+pos'-1)\n\n readArray lens v >>= \\l -> writeArray lens v (l-pos'+1)\n\n let map' = Map.insert cc u map\n writeArray maps node' map'\n\n writeArray links last u\n\n if node' == 0\n then loop node' (pos'-1) u\n else do\n link <- readArray links node'\n loop link pos' u\n\n (node2, pos2) <- loop node (pos+1) 0\n writeSTRef node' node2\n writeSTRef pos' pos2\n\n let\n traverse i = do\n map <- readArray maps i\n l <- forM (Map.toList map) $ \\(_, i) -> do\n start <- readArray starts i\n len <- readArray lens i\n t <- traverse i\n return $ Edge (start, len) t\n return $ Node l\n\n traverse 0\n\ndata Item = CharItem !Char | DelimItem !Int deriving (Eq, Ord, Show)\n\nmain = do\n n <- readLn\n ts <- replicateM n getLine\n cs <- map read . words <$> getLine :: IO [Int]\n\n let\n s' = concat . map (\\(t, c) -> map CharItem t ++ [DelimItem c]) $ zip ts [1..]\n sa = listArray (1, length s') s'\n cs' = listArray (1, length cs) cs\n\n t = suffixTree s'\n\n dfs _ (Node []) = (0, 0)\n dfs d (Node es) = -- trace (\"es = \" ++ show es ++ \" s = \" ++ show s ++ \" m = \" ++ show m) $\n (max m (s * d), s)\n where\n s = sum $ map snd rs\n m = maximum $ map fst rs\n\n rs = map f es\n where\n f (Edge (s, l) t') = f' delim\n where\n ss = map (sa !) [s+1..s+l]\n\n delim = find is ss\n where\n is (CharItem _) = False\n is (DelimItem _) = True\n\n f' Nothing = dfs (d + l) t'\n f' (Just e@(DelimItem i)) = ((d+p)*c, c)\n where\n p = fromJust $ elemIndex e ss\n c = cs' ! i\n\n\n (r, _) = dfs 0 t\n\n -- print t\n\n -- let\n -- p k (Node es) =\n -- forM_ es $ \\(Edge (i, l) t) -> do\n -- putStrLn $ (replicate k ' ') ++ (concat $ map show $ take l $ drop i s')\n -- p (k + 2) t\n\n -- p 0 t\n\n print r\n"}], "src_uid": "d798147f2d7acaf233d12d1b6f4aabcb"} {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int\n\nreadB = fst . fromJust . B.readInt\nreadX x = fromInteger . fst . fromJust . B.readInteger $ x :: Int64\n\nmain = do\n n <- readB <$> B.getLine :: IO Int\n replicateM_ n $ B.getLine >>= putStrLn . calc . map readX . B.words\n\nsolve xs = map calc xs\n\ncubrt x = round $ fromIntegral x ** (1/3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n (da, ma) = divMod (a*a) b\n (db, mb) = divMod (b*b) a\n ans = ma == 0 && mb == 0 && da == cubrt da ^ 3 && db == cubrt db ^ 3\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.Int\nimport Data.Bool\n\nmain = do\n n <- fmap readInt B.getLine\n replicateM n $ B.getLine >>= putStrLn . bool \"No\" \"Yes\" . (\\[a, b] -> solve (to64 a) (to64 b)) . readInts\n\nsolve a b = r1 == 0 && r2 == 0 && isCube q1 && isCube q2\n where\n (q1, r1) = (a * a) `quotRem` b\n (q2, r2) = (b * b) `quotRem` a\n\nisCube :: Int64 -> Bool\nisCube x = round (fromIntegral x ** (1/3)) ^ 3 == x\nto64 x = fromIntegral x :: Int64\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\n{-\na = k^x\nb = k^y\n\nx = 2w + l\ny = w + 2l\n\n,nnnn\n-}"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int\n\nreadB x = fromInteger . fst . fromJust . B.readInteger $ x :: Int64\n\nmain = putStrLn . unlines . solve . map (map readB . B.words) . tail . B.lines =<< B.getContents\n\nsolve xs = map calc xs\n\ncubrt x = round $ fromIntegral x ** (1 / 3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n c = gcd a b\n xa = div a c\n xb = div b c\n x = xa * xb\n zc = div c x\n cu = cubrt zc\n ans = if mod c x /= 0 then False\n else zc == cu ^ 3"}], "negative_code": [{"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadB = fst . fromJust . B.readInt\n\nmain = putStrLn . unlines . solve . map (map readB . B.words) . tail . B.lines =<< B.getContents\n\nsolve xs = map calc xs\n\ncubrt x = round $ fromIntegral x ** (1/3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n (da, ma) = divMod (a*a) b\n (db, mb) = divMod (b*b) a\n ans = ma == 0 && mb == 0 && da == cubrt da ^ 3 && db == cubrt db ^ 3\n"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nmain = putStrLn . unlines . solve . map (map read . words) . tail . lines =<< getContents\n\nsolve xs = map calc xs\n\ncubrt x = round $ fromIntegral x ** (1/3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n (da, ma) = divMod (a*a) b\n ans = ma == 0 && da == cubrt da ^ 3\n"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadB = fst . fromJust . B.readInt\n\nmain = putStrLn . unlines . solve . map (map readB . B.words) . tail . B.lines =<< B.getContents\n\nsolve xs = map calc xs\n\ncubrt x = lp 1 x where\n lp i j | i >= j = i\n | otherwise =\n let k = div (i + j) 2\n v = k * k * k\n in case compare v x of\n LT -> lp (k+1) j\n EQ -> k\n GT -> lp i k\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n c = gcd a b\n xa = div a c\n xb = div b c\n x = xa * xb\n zc = div c x\n ans = if mod c x /= 0 then False\n else zc == cubrt zc ^ 3\n \n \n \n "}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nmain = putStrLn . unlines . solve . map (map read . words) . tail . lines =<< getContents\n\nsolve xs = map calc xs\n\ncubrt x = floor $ fromIntegral x ** (1 / 3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n c = gcd a b\n xa = div a c\n xb = div b c\n x = xa * xb\n zc = div c x\n cu = cubrt zc\n ans = if mod c x /= 0 then False\n else zc == cu ^ 3"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadB = fst . fromJust . B.readInt\n\nmain = do\n n <- readB <$> B.getLine\n replicateM_ n $ B.getLine >>= putStrLn . calc . map readB . B.words\n\nsolve xs = map calc xs\n\ncubrt x = round $ fromIntegral x ** (1/3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n (da, ma) = divMod (a*a) b\n (db, mb) = divMod (b*b) a\n ans = ma == 0 && mb == 0 && da == cubrt da ^ 3 && db == cubrt db ^ 3\n"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nreadB = fst . fromJust . B.readInt\n\nmain = putStrLn . unlines . solve . map (map readB . B.words) . tail . B.lines =<< B.getContents\n\nsolve xs = map calc xs\n\ncubrt x = lp 1 x where\n lp i j | i >= j = i\n | otherwise =\n let k = div (i + j) 2\n v = k * k * k\n in case compare v x of\n LT -> lp (k+1) j\n EQ -> k\n GT -> lp i k\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n c = gcd a b\n xa = div a c\n xb = div b c\n x = xa * xb\n zc = div c x\n cu = cubrt zc\n ans = if mod c x /= 0 then False\n else zc == cu ^ 3"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadB = fst . fromJust . B.readInt\n\nmain = putStrLn . unlines . solve . map (map readB . B.words) . tail . B.lines =<< B.getContents\n\nsolve xs = map calc xs\n\ncubrt x = round $ fromIntegral x ** (1/3)\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n (da, ma) = divMod (a*a) b\n ans = ma == 0 && da == cubrt da ^ 3\n"}, {"source_code": "-- Codeforces My Practice\n-- author: Leonardone @ NEETSDKASU\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.Int\n\nreadB x = fromInteger . fst . fromJust . B.readInteger $ x :: Int64\n\nmain = putStrLn . unlines . solve . map (map readB . B.words) . tail . B.lines =<< B.getContents\n\nsolve xs = map calc xs\n\ncubrt x = lp 1 x where\n lp i j | i >= j = i\n | otherwise =\n let k = div (i + j) 2\n v = k * k * k\n in case compare v x of\n LT -> lp (k+1) j\n EQ -> k\n GT -> lp i k\n\ncalc (a:b:_) = if ans then \"Yes\" else \"No\"\n where\n c = gcd a b\n xa = div a c\n xb = div b c\n x = xa * xb\n zc = div c x\n cu = cubrt zc\n ans = if mod c x /= 0 then False\n else zc == cu ^ 3"}], "src_uid": "933135ef124b35028c1f309d69515e44"} {"source_code": "cnt xs val = length $ filter (== val) xs\n\nbulb = \"Bulbasaur\"\n\nsolve s = minimum [ (cnt s t) `div` (cnt bulb t) | t <- bulb ]\n\nmain :: IO ()\nmain = do\n s <- getLine\n print $ solve s\n", "positive_code": [{"source_code": "-- Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined)\n-- Problem A\n\nimport Data.List\n\nmain = do\n s <- getLine\n print $ minimum $ zipWith div (map (cnt s) \"Bulbasr\") [1,2,1,1,2,1,1]\n\ncnt s ch = length $ filter (== ch) s\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.List\nimport Control.Monad\n\ntype Freq = Map.Map Char Int\n\ntarget = \"Bulbasaur\"\n\nfreqOf :: Freq -> String -> Freq\nfreqOf = foldl' (flip $ Map.update (return . (+1)))\n\nsolve :: Freq -> Freq -> Int\nsolve f1 f2 = minimum $ Map.elems $ Map.intersectionWith (flip div) f1 f2\n\nmain = do\n s <- getLine\n let f = Map.fromList $ zip target (repeat 0)\n print $ solve (freqOf f target) (freqOf f s)\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.List\nimport Control.Monad\n\ntype Freq = Map.Map Char Int\n\ntarget = \"Bulbasaur\"\n\nfreqOf :: Freq -> String -> Freq\nfreqOf = foldr (Map.update (return . (+1)))\n\nsolve :: Freq -> Freq -> Int\nsolve f1 f2 = minimum $ Map.elems $ Map.intersectionWith (flip div) f1 f2\n\nmain = do\n s <- getLine\n let f = Map.fromList $ zip target (repeat 0)\n print $ solve (freqOf f target) (freqOf f s)\n"}, {"source_code": "module Main where\n\nimport Data.Map.Strict\nimport Data.Maybe\nimport Prelude hiding (lookup)\n\n\ncountEls::Ord a=>[a]->Map a Int\ncountEls = fromListWith (+) . (`zip` repeat 1)\n\nquotEls::Ord a=>[a]->[a]->Int\nquotEls word text = let wass = toList (countEls word)\n tels = countEls text\n quotCount (el, cnt) = fromMaybe 0 (lookup el tels) `quot` cnt\n wcounts = fmap quotCount wass\n in minimum wcounts\n\nmain :: IO ()\nmain = getLine >>= print . quotEls \"Bulbasaur\"\n"}, {"source_code": "import qualified Data.Map as Map\n\nupdate :: Char -> Map.Map Char Int -> Map.Map Char Int\nupdate c m = case Map.lookup c m of\n Nothing -> Map.insert c 1 m\n Just v -> Map.insert c (v + 1) m\n\nsolve :: String -> Map.Map Char Int\nsolve [] = Map.empty\nsolve (x:xs) = update x rest\n where rest = solve xs\n\nmaybeToZero :: Maybe Int -> Int\nmaybeToZero Nothing = 0\nmaybeToZero (Just x) = x\n\nsolve' :: Char -> Map.Map Char Int -> Int\nsolve' 'B' m = maybeToZero $ Map.lookup 'B' m\nsolve' 'u' m = (maybeToZero $ Map.lookup 'u' m) `div` 2\nsolve' 'l' m = maybeToZero $ Map.lookup 'l' m\nsolve' 'b' m = maybeToZero $ Map.lookup 'b' m\nsolve' 'a' m = (maybeToZero $ Map.lookup 'a' m) `div` 2\nsolve' 's' m = maybeToZero $ Map.lookup 's' m\nsolve' 'r' m = maybeToZero $ Map.lookup 'r' m\n\nmain :: IO ()\nmain = do\n line <- getLine\n let freq = solve line\n smallest = foldr (\\ c m -> min m $ solve' c freq) 1000000 \"Bulbasr\"\n putStrLn . show $ smallest\n"}, {"source_code": "import Data.List( partition, group, sort)\nmain = do\n s_ <- getLine\n let\n\tp c = c `elem` \"Bulbasaur\"\n\t(bulbasaur,_) = partition p s_\n\tvalue = case map length . group $ sort bulbasaur of\n\t [nB,na,nb,nl,nr,ns,nu] ->\n\t\t [(min na nu) `div` 2,nB,nb,nl,nr,ns]\n\t _\t\t\t -> [0,0,0,0,0,0,0]\n\t--Baablrsuu\n print $ minimum value\n"}], "negative_code": [{"source_code": "-- Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined)\n-- Problem A\n\nmain = do\n\ts <- getLine\n\tprint $ catch s \"Bulbassaur\"\n\ncatch src poke = f src (cycle poke) 0 0 where\n\tend = length poke\n\tf _ [] _ acc = acc\n\tf [] _ _ acc = acc\n\tf (x:xs) (y:ys) pos acc\n\t\t| x == y\t= f xs ys pos' acc'\n\t\t| otherwise\t= f xs (y:ys) pos acc\n\t\twhere\n\t\t\tpos' = if pos < end then (pos + 1) else 0\n\t\t\tacc' = if pos' < pos then (acc + 1) else acc"}, {"source_code": "-- Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined)\n-- Problem A\n\nmain = do\n\ts <- getLine\n\tprint $ catch s \"Bulbasaur\"\n\ncatch src poke = f src (cycle poke) 0 0 where\n\tend = length poke\n\tf _ [] _ acc = acc\n\tf [] _ _ acc = acc\n\tf (x:xs) (y:ys) pos acc\n\t\t| x == y\t= f xs ys pos' acc'\n\t\t| otherwise\t= f xs (y:ys) pos acc\n\t\twhere\n\t\t\tpos' = if pos < (end - 1) then (pos + 1) else 0\n\t\t\tacc' = if pos' < pos then (acc + 1) else acc"}, {"source_code": "-- Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined)\n-- Problem A\n\nmain = do\n\ts <- getLine\n\tprint $ catch s \"Bulbasaur\"\n\ncatch src poke = f src (cycle poke) 0 0 where\n\tend = length poke\n\tf _ [] _ acc = acc\n\tf [] _ _ acc = acc\n\tf (x:xs) (y:ys) pos acc\n\t\t| x == y\t= f xs ys pos' acc'\n\t\t| otherwise\t= f xs (y:ys) pos acc\n\t\twhere\n\t\t\tpos' = if pos < end then (pos + 1) else 0\n\t\t\tacc' = if pos' < pos then (acc + 1) else acc"}], "src_uid": "9c429fd7598ea75acce09805a15092d0"} {"source_code": "import Control.Monad\n\nmutations :: [(Int,Int)]\nmutations = [(0,0),(1,3),(2,6),(3,1),(4,4),(5,7),(6,2),(7,5),(8,8)]\n\nsolve :: [String] -> [String]\nsolve grid = [[cell i j | j <- [0..8]] | i <- [0..8]]\n where \n cell i j = let old = grid !! i !! j\n in if (i,j) `elem` mutations then inc old else old\n inc x = if x == '9' then '1' else succ x\n\nmain :: IO ()\nmain = do\n tc <- readLn\n replicateM_ tc $ do\n grid <- replicateM 9 getLine\n mapM_ putStrLn $ solve grid\n", "positive_code": [{"source_code": "\nswitch :: Char -> Char\nswitch '1' = '2'\nswitch _ = '1'\n\nswitchNth :: Int -> String -> String\nswitchNth 0 (s:ss) = switch s : ss\nswitchNth n (s:ss) = s : switchNth (n-1) ss\n\n\ntestCases :: Integer -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n s0 <- getLine\n putStrLn $ switchNth 0 s0\n s1 <- getLine\n putStrLn $ switchNth 4 s1\n s2 <- getLine\n putStrLn $ switchNth 8 s2\n s3 <- getLine\n putStrLn $ switchNth 1 s3\n s4 <- getLine\n putStrLn $ switchNth 5 s4\n s5 <- getLine\n putStrLn $ switchNth 6 s5\n s6 <- getLine\n putStrLn $ switchNth 2 s6\n s7 <- getLine\n putStrLn $ switchNth 3 s7\n s8 <- getLine\n putStrLn $ switchNth 7 s8\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Integer]\nreadInts = map read . words <$> getLine"}, {"source_code": "import Data.List\n\ntype Sudoku = [[Int]]\n\nmain :: IO ()\nmain = do\n getLine \n sudokus <- map (modifySudoku coords) <$> mkSudoku <$> lines <$> getContents\n let sudokuStrings = concat $ map (map (concat.map show)) sudokus\n mapM_ putStrLn sudokuStrings\n\nmkSudoku :: [String] -> [Sudoku]\nmkSudoku [] = [] \nmkSudoku str = let (pre,suf) = splitAt 9 str\n sudoku = map (map read . words . intersperse ' ') $ pre\n in sudoku : mkSudoku suf\n\n\nmodifySudoku :: [(Int, Int)] -> Sudoku -> Sudoku\nmodifySudoku [] su = su\nmodifySudoku ((y,x):co) su = modifySudoku co su'\n where (pre,rest) = splitAt y su\n (row, suf) = splitAt 1 rest\n (prerow, restrow) = splitAt x $ head row\n (cell, sufrow) = splitAt 1 restrow\n cell' = head cell `mod` 9 + 1\n su' = pre ++ [prerow ++ [cell'] ++ sufrow] ++ suf\n\ncoords :: [(Int, Int)]\ncoords = [\n (0,0),\n (1,3),\n (2,6),\n (3,1),\n (4,4),\n (5,7),\n (6,2),\n (7,5),\n (8,8) ]\n \n"}, {"source_code": "import Control.Monad (forM_, mapM_, sequence)\nimport Data.Char (ord, chr)\n\nsolve :: [String] -> [String]\nsolve rows = nrows where\n\trows' = map (\\row -> map (\\c -> ord c - ord '1') row) rows\n\tnrows' = [ [ if (i,j) `elem` positions then (c+1) `mod` 9 else c | (j,c) <- zip [0..8] row] | (i, row) <- zip [0..8] rows']\n\tnrows = map (\\row -> map (\\c -> chr (c + ord '1')) row) nrows'\n\tpositions = [(0,0),(3,1),(6,2),(1,3),(4,4),(7,5),(2,6),(5,7),(8,8)]\n\t\n\t\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\trows <- sequence (replicate 9 getLine) :: IO [String]\n\t\tmapM_ putStrLn (solve rows)\n\t\t\n\t\t\ns = \"154873296\\n386592714\\n729641835\\n863725149\\n975314628\\n412968357\\n631457982\\n598236471\\n247189563\""}], "negative_code": [{"source_code": "import Control.Monad\n\nmutations :: [(Int,Int)]\nmutations = [(0,0),(1,3),(2,6),(3,1),(4,4),(5,7),(6,2),(7,5),(9,9)]\n\nsolve :: [String] -> [String]\nsolve grid = [[cell i j | j <- [0..8]] | i <- [0..8]]\n where \n cell i j = let old = grid !! i !! j\n in if (i,j) `elem` mutations then inc old else old\n inc x = if x == '9' then '1' else succ x\n\nmain :: IO ()\nmain = do\n tc <- readLn\n replicateM_ tc $ do\n grid <- replicateM 9 getLine\n mapM_ putStrLn $ solve grid\n"}, {"source_code": "import Data.List\n\ntype Sudoku = [[Int]]\n\nmain :: IO ()\nmain = do\n getLine \n sudokus <- map (modifySudoku coords) <$> mkSudoku <$> lines <$> getContents\n mapM_ print sudokus\n\nmkSudoku :: [String] -> [Sudoku]\nmkSudoku [] = [] \nmkSudoku str = let (pre,suf) = splitAt 9 str\n sudoku = map (map read . words . intersperse ' ') $ pre\n in sudoku : mkSudoku suf\n\n\nmodifySudoku :: [(Int, Int)] -> Sudoku -> Sudoku\nmodifySudoku [] su = su\nmodifySudoku ((y,x):co) su = modifySudoku co su'\n where (pre,rest) = splitAt y su\n (row, suf) = splitAt 1 rest\n (prerow, restrow) = splitAt x $ head row\n (cell, sufrow) = splitAt 1 restrow\n cell' = head cell `mod` 9 + 1\n su' = pre ++ [prerow ++ [cell'] ++ sufrow] ++ suf\n\ncoords :: [(Int, Int)]\ncoords = [\n (0,0),\n (1,3),\n (2,6),\n (3,1),\n (4,4),\n (5,7),\n (6,2),\n (7,5),\n (8,8) ]\n \n"}], "src_uid": "0e21f1c48c8c0463b2ffa7275eddc633"} {"source_code": "import Data.List\nmain = interact $ show.g.f.reverse.sort.map read.words.last.lines\n\nf = scanl1 (+)\ng as = (+1).length.takeWhile (<=(last as/2)) $ as\n", "positive_code": [{"source_code": "import Data.List\nloop :: [Int] -> Int -> Int -> Int\nloop [] me he = 0\nloop xl@(xh:xt) me he \n | me > he = length xl\n | otherwise = loop xt (me + xh) (he - xh)\n\nsolve :: [Int] -> Int\nsolve coins = length coins - loop (reverse $ sort coins) 0 (sum coins)\n\nmain = do\n _ <- getLine\n coins <- (getLine >>= return . map (read::String->Int) . words)\n\n print $ solve coins\n\n"}, {"source_code": "import Data.List as List\nimport Data.Maybe as Maybe\n\nreadAsInt :: String -> Int\nreadAsInt str = read str :: Int\n\nisLargerAmount takenCoin coins = takenSum > restSum\n\twhere takenSum = sum $ take takenCoin coins\n\t restSum = sum $ drop takenCoin coins\n\ngetAnswer coins = foldl (\\takenCoin elem -> \n\tif isLargerAmount takenCoin coins \n\tthen takenCoin \n\telse takenCoin + 1) 1 coins\n\n\nsolveCase :: String -> IO ()\nsolveCase line = do\n\tlet coins = map readAsInt $ words line\n\tlet sortedCoin = reverse . sort $ coins\n\tlet coinSum = sum sortedCoin\n\tprint $ getAnswer sortedCoin\n\nmain = do\n\tline <- getLine\n\tsndLine <- getLine\n\tsolveCase sndLine"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve xs = fst $ (let s = sum xs in foldl (\\(ct,sm) ar -> if sm <= (s-sm) then (ct+1, sm+ar) else (ct,sm)) (0, 0) xs)\n\nrun :: String -> String\nrun = show . solve . reverse . sort . tail . map read . words\n\nmain = interact run\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve xs = fst $ (let s = sum xs in foldl (\\(ct,sm) ar -> if sm <= (s-sm) then (ct+1, sm+ar) else (ct,sm)) (0, 0) xs)\n\nrun :: String -> String\nrun ls = show $ solve $ reverse $ sort $ tail $ map read (words ls)\n\nmain = interact run\n"}, {"source_code": "import Control.Monad\nimport Data.List (sort)\n\n\nans [] _ = 0\nans left@(x:xs) right = if sum left >= sum right then 1 + ans xs (x:right)\n else 0\n\n\nmain = do\n getLine\n aa <- getLine\n let xs = reverse $ sort $ map read $ words aa :: [Int]\n print $ ans xs []\n"}, {"source_code": "import Data.List\nmain=interact$show.f.map read.tail.words\nf c = f' (sum c) (scanl1 (+) (reverse (sort c)))\n\twhere f' s (x:xs) \n\t\t| s - x < x = 1\n\t\t| otherwise = 1 + f' s xs\n\t\t\t\t\t"}, {"source_code": "module Main (main)\n where\n\nimport Data.Ord (compare)\nimport Data.List (sortBy, inits, tails)\n\n\nmain :: IO ()\nmain = print . solve . group' . map read . words =<< (getLine >> getLine)\n where solve = length . fst . head . dropWhile (\\(a,b) -> sum a <= sum b)\n group' = (\\xs -> zip (inits xs) (tails xs)) . sortBy (flip compare)"}, {"source_code": "main = do\n getLine\n getLine>>=(\\x->(putStr (solve (map read (words x)))))\nsolve x = show (result (qsort x) (sum x) 0 0)\nqsort[]=[]\nqsort(x:xs)=qsort[y|y<-xs,y>x]++[x]++qsort[y|y<-xs,y<=x]\nresult (x:xs) a b n\n |x+b>a-x = n+1\n |x+b<=a-x = result xs (a-x) (b+x) (n+1)"}, {"source_code": "import Data.List (sort)\n\ndiff n xs =\n let (mine, theirs) = splitAt n xs in\n sum mine - sum theirs\n\nf :: Int -> [Int] -> Int\nf n xs = head [idx | idx <- [0..], diff idx xs > 0]\n\nmain = interact $ show . f 0 . reverse . sort . map read . tail . words"}, {"source_code": "import Data.List\nimport Data.Maybe\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- getLine\n a <- readItems\n let sums = scanr (+) 0 (sort a)\n let defective = (< 1 + div (sum a) 2)\n putStrLn $ show $ 1 + length a - fromJust (findIndex defective sums)\n"}, {"source_code": "import Data.List\nfu xs s x | sum xs < s = x| otherwise = fu (tail xs) (head xs + s) (x+1)\nsolve xs = fu (reverse $ sort xs) 0 0\nmain = interact $ show . solve . tail. map read . words"}, {"source_code": "import Data.List\nsolve :: [Int] -> Int\nsolve xs = solve_iter 0\n where xs' = sort xs\n sums = scanl (+) 0 xs'\n total = last sums\n l = length xs\n solve_iter i \n | sum2 > sum1 = i\n | otherwise = solve_iter (i+1)\n where (pre, suf) = splitAt (l - i + 1) sums\n sum1 = last pre\n sum2 = total - sum1\nmain = interact $ show .solve . map read . words . last . lines "}, {"source_code": "import Data.List (sortBy)\n\nsolve :: Int -> Int -> [Int] -> Int -> Int\nsolve acc cnt (x:xs) s \n\t| acc > s = cnt\n\t| otherwise = solve (acc+x) (cnt+1) xs s\nsolve _ cnt [] _ = cnt\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\ts <- getLine\n\tlet ints = sortBy (flip compare) $ map read $ words s :: [Int]\n\tprint $ solve 0 0 ints $ sum ints `div` 2"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine\n let\n s = sum as\n ss = scanl1 (+) $ reverse $ sort as\n\n print $ (length $ takeWhile (\\x -> 2*x <= s) ss) + 1\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do\n n <- readLn :: IO Int\n l <- map (read :: String -> Int) . words <$> getLine\n let sl = scanl (+) 0 $ reverse $ sort l\n s = sum l\n in print . length $ takeWhile (\\x -> 2 * x <= s) sl\n"}, {"source_code": "import Data.List\n\ndivToNum :: String -> [Int]\ndivToNum [] = []\ndivToNum l = (read h) : (divToNum t)\n\twhere [(h,t)] = lex l\n\nfL [x] f = x\nfL (x:xs) f = f x $ fL xs f\n\nsolve l = solve' 0 0 (foldl (+) 0 l) l\n\nsolve' q s1 s2 l | (s1 + x > s2 - x) = q+1\n | otherwise = solve' (q+1) (s1 + x) (s2 - x) (delete x l)\n\twhere x = fL l max\n\nmain = getLine >> getLine >>= (print.solve.divToNum)\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\nimport Data.List\n\nmain = do { n <- getLine\n ; x <- getLine\n ; putStrLn $ (words >>> map read >>> solve >>> show) x \n }\n\ncount :: Int -> Int -> (Int,Int) -> (Int,Int)\ncount s z (a,n) | a > s = (a+z,n)\n | otherwise = (a+z,n+1)\n\nsolve :: [Int] -> Int\nsolve x = let s = (foldr (+) 0 x) `div` 2\n y = sort x\n in (foldr (count s) (0,0) >>> snd) y"}, {"source_code": "import Data.List\nf xs = foldl (\\acc x -> if (sum acc) <= ((sum xs)/2) then x:acc else acc) [] xs\nmain = do\n\tgetLine\n\tstr <- getLine\n\tputStrLn . show . length . f . reverse . sort . map read . words $ str"}, {"source_code": "import Data.List\n\nmain = do\n counter <- getLine\n str <- getLine\n let xs = map read $ words str :: [Int]\n let solve xs = _solve (sum xs) 0 (reverse (sort xs)) 0 where\n _solve _ _ [] i = i\n _solve sumXs sum1 (x:xs) i\n | sum1 <= sumXs = _solve (sumXs - x) (sum1 + x) xs (i + 1)\n _solve _ _ _ i = i\n print (solve xs)\n"}, {"source_code": "import Data.List\n\nmain = interact $ solve . map read . words . head . tail . lines\n\nsolve s = (show $ solve' (reverse $ sort s) (div (sum s) 2) 0) ++ \"\\n\"\nsolve' [] _ _ = 0\nsolve' (x:xs) p c\n | c > p = 0\n | otherwise = 1 + solve' xs p (c+x)\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\npsum :: [Int] -> [Int]\npsum a = f a 0\n where\n f [] r = []\n f (x:xs) r = (r + x) : (f xs (r + x))\n\nsolve :: [Int] -> Int\nsolve a = let aa = reverse $ sort a\n bb = psum aa\n cc = map (* 2) bb\n ss = sum a\n in 1 + (length $ takeWhile (<= ss) cc)\n\nmain = do\n n <- getLine\n a <- map read <$> (words <$> getLine)\n print $ solve a\n "}, {"source_code": "import List\ngetAns ::[Int] -> Int\ngetAns a= length$last$takeWhile ((>sum a).(*2).sum)$tails$sort a\nmain = interact$show.getAns.(map read).tail.words"}, {"source_code": "import Data.List\nmain = readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show . solve.map read. words. last. take 2 . lines\nsolve :: [Int]->Int\nsolve xs = length $ takeWhile (\\x -> fromIntegral x <= fromIntegral s/2) $ scanl (+) 0 $ reverse $ sort xs\n where s=sum xs"}, {"source_code": "\nimport List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> Int\nsolve xs = solve' (0, sum xs, 0) (reverse (sort xs))\n where\n solve' :: (Int, Int, Int) -> [Int] -> Int\n solve' (n, s, s1) [] = n\n solve' (n, s, s1) (x:xs)\n | s1 > s - s1 = n\n | otherwise = solve' (n+1, s, s1+x) xs\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= print . solve\n"}, {"source_code": "-- Codeforces 160A\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= print . solve . sortBy (\\a b -> compare b a) . map read . words\n\nsolve :: [Int] -> Int\nsolve xs = length $ takeWhile (\\x -> x <= (sum xs) `div` 2) $ foldl (\\x a -> x ++ [last x + a]) [0] xs\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (sort)\n\nmain = do\n n <- read <$> getLine :: IO Int\n cs <- map read . words <$> getLine :: IO [Int]\n let scs = scanl1 (+) . reverse $ sort cs\n hsm = div (last scs + (n-n)) 2\n (rs,ls) = span (<=hsm) scs\n m = length rs\n print $ if null rs || last rs <= hsm then m + 1 else m"}, {"source_code": "import List\n\nsolve xs = let ys = scanl (+) 0 $ reverse $ sort xs\n zs = zipWith (-) (repeat $ sum xs) ys\n in length $ takeWhile (\\(y, z) -> y <= z) $ zip ys zs\n\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Data.Function\nimport Data.List\n\nmain = do\n\tn <- getLine\n\tcoins <- getCoins\n\tlet cap = (foldr (+) 0 coins) `div` 2\n\tlet res = fix (\\f sum i r -> if sum > cap || i < 0\n\t\t\t\t\t\t\t\tthen r\n\t\t\t\t\t\t\t\telse f (coins !! i + sum) (i - 1) (r + 1)) 0 (length coins - 1) 0\n\tputStrLn $ show res\n\ngetCoins::IO [Int]\ngetCoins = do\n\targs <- getLine\n\treturn . sort $ map readInt $ split args ' '\n\nreadInt::String -> Int\nreadInt str = read str\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\c prev -> if c == sep\n\t\t\t\t\t\t\t\t\tthen \"\":prev\n\t\t\t\t\t\t\t\t\telse (c:(head prev)):(tail prev)) [\"\"] str"}, {"source_code": "import Data.List (sort)\n\n\nsplitSpace::[Char] -> [Char] -> [[Char]] -> [[Char]]\nsplitSpace (l:xl) acc result | length(xl) == 0 = result ++ [acc ++ [l]]\n | l == ' ' = splitSpace (xl) (\"\") (result ++ [acc])\n | otherwise = splitSpace xl (acc ++ [l]) result\n\nreadInts a = reverse (sort $ map (\\x -> read x :: Int) (splitSpace a [] []))\n \nsolve a b c | b > sum a = c\n | otherwise = solve (tail a) (b + head a) (c + 1)\n\ndoSolve a = putStrLn $ show (solve a 0 0)\nmain = getLine >>= (\\a -> (\\b -> getLine >>= (\\c -> doSolve (readInts c)))(a))"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = (+1) . length . takeWhile (<= sum a `div` 2) . scanl1 (+) . sortBy (flip compare) $ a\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n putStrLn . show $ solve a\n\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = (+1) . length . takeWhile (<= sum a `div` 2) . scanl1 (+) . reverse . sort $ a\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n putStrLn . show $ solve a\n\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nreadInts :: IO [Int]\nreadInts = do\n getLine\n i <- getLine\n return $ map read $ words i\n\nsolve :: [Int] -> Int\nsolve coins = ans\n where c' = sort coins\n total = sum coins `div` 2\n (_, ans, _) = foldr (\\e (s, n, out) -> if not out then (s + e, n + 1, s + e > total) else (s, n, out)) (0, 0, False) c'\n\nmain :: IO ()\nmain = print =<< solve <$> readInts\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Control.Monad\n\nprocess::[Int]->Int->Int->Int->Int\nprocess a sa sc n | sc>sa =n\n | otherwise = process (tail a) (sa-head a) (sc+head a) (n+1)\nmain::IO ()\nmain=do\n getLine\n a<- reverse <$> sort <$> map read <$> words <$> getLine\n print $ process a (sum a) 0 0 \n"}, {"source_code": "main = do\n\t_ <- getLine\n\tline <- getLine\n\tlet numbers = separate line\n\tlet sorted = quicksort numbers\n\tlet half = div (sum sorted) 2\n\tprint $ calc sorted 0 0 half\n\nseparate :: String -> [Int]\nseparate = map read . words\n\nquicksort :: (Ord a) => [a] -> [a]\nquicksort [] = []\nquicksort (x:xs) =\n let smallerSorted = quicksort [a | a <- xs, a <= x]\n biggerSorted = quicksort [a | a <- xs, a > x]\n in biggerSorted ++ [x] ++ smallerSorted\n\ncalc :: [Int] -> Int -> Int -> Int -> Int\ncalc [] i _ _ = i\ncalc (t:tab) i sum half = if sum > half\n\tthen i\n\telse calc tab (i+1) (sum+t) half"}, {"source_code": "module Main(main) where\n\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\n\nmain = interact $ words >>> tail >>> map read >>> sortBy (flip compare) >>> scanl (+) 0 >>>\n ((last >>> (`div` 2) >>> (<)) >>= findIndex) >>> fromJust >>> show"}, {"source_code": "module Main where\n\nimport Control.Arrow\nimport Data.List\n\nmain = interact $ words >>> tail >>> map read >>> sortBy (flip compare) >>> scanl (+) 0 >>>\n (\\x -> takeWhile (<= (last x `div` 2)) x) >>> length >>> show"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve as = length as - length (takeWhile (<= ((sum as - 1) `div` 2)) (scanl1 (+) (sort as)))\n"}, {"source_code": "import Prelude hiding (readList)\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\nmain :: IO ()\nmain = do\n skipLine\n as <- (reverse . sort) <$> readList' (undefined::Int)\n let sm = sum as\n ass = tail $ scanl (+) 0 as\n print $ (+1) $ length $ takeWhile (\\a -> 2*a <= sm) ass\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve xs = fst\n $ foldr (\\b (c, tot) -> if tot > half \n then (c, tot) \n else (c+1, tot+b)) (0, 0) \n $ sort xs\n where half = div (sum xs) 2\n\nmain :: IO ()\nmain = do\n _ <- readInt\n v <- readInts\n print $ solve v"}, {"source_code": "import Data.List(sortBy)\n\nsolve' [] _ _ l = l\nsolve' (x:xs) n m l = if (n + x > m - x) then l + 1 else solve' xs (n + x) (m - x) (l + 1)\n\nsolve :: [Int] -> Int\nsolve xs = solve' (sortBy (flip compare) xs) 0 (sum xs) 0\n\nmain = do\n getLine\n xs <- fmap (map read . words) getLine\n print $ solve xs\n"}, {"source_code": "import Data.List\n\ntakeCoins :: [Int] -> Int -> Int -> Int -> Int\ntakeCoins [] s c n = n\ntakeCoins (x:xs) s c n\n | c * 2 > s = n\n | otherwise = takeCoins xs s (c + x) (n + 1)\n\nmain = do\n getLine\n s <- getLine\n let nums = map read $ words s\n print $ takeCoins (reverse $ sort nums) (sum nums) 0 0\n"}, {"source_code": "import Data.List\nmain = print . solve . map read . tail . words =<< getContents\nsolve cs = succ $ length $ takeWhile ((<= s) . (*2)) $\n scanl1 (+) $ reverse $ sort cs\n where s = sum cs"}, {"source_code": "import Data.List\nmain = do\n getLine\n s <- getLine\n print . solve . map read . words $ s\nsolve xs = length . takePartGT needMoreThan . reverse . sort $ xs\n where needMoreThan = sum xs `div` 2\ntakePartGT n (x:xs) | x > n = [x]\n | otherwise = x : takePartGT (n-x) xs\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/160/A\n\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: [Int] -> Int\nsolve a = (+1) . length . takeWhile (<= sum a `div` 2) . scanl1 (+) . sortBy (flip compare) $ a\n\nmain = do\n _ <- getLine\n a <- getIntList\n putStrLn . show $ solve a\n"}, {"source_code": "import Data.List\nmain = interact $ show . g . scanl1 (+) . reverse . sort . map read . tail . words\ng l = (+1) . length . takeWhile (<= (last l)/2) $ l\n"}, {"source_code": "import Data.List\n\nmain = interact $ show.solve.map read.words\n\nsolve (_:xs) = succ . length . takeWhile (<=(sum xs)`div`2) . scanl1 (+) . reverse $ sort xs"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = sortBy (flip compare) . map read . words . (!!1) <$> replicateM 2 getLine >>= print . (\\ns -> solve (sum ns `div` 2) ns)\n where solve _ [] = 0\n solve n (x:xs) | n < x = 1\n | otherwise = 1 + solve (n-x) xs\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int -> Int\nsolve [] left = 0\nsolve (x:xs) left \n | left < 0 = 0\n | otherwise = 1 + solve xs (left-x)\n\nmain = do\n str <- getLine\n str <- getLine\n let\n vs = reverse . sort . map read $ words str\n ans = solve vs $ (sum vs) `div` 2\n putStrLn $ show ans\n"}, {"source_code": "\nf1 :: [Int] -> Int\nf1 a = \n let t = div (sum a) 2 + 1\n in 1 + (length $ filter (\\x -> x < t) $ scanl1 (+) $ msort' a)\n\n\nmsort' :: [Int] -> [Int]\nmsort' [] = []\nmsort' [x] = [x]\nmsort' x = merge' left right\n where left = msort' $ take m x\n right = msort' $ drop m x\n m = div (length x + 1) 2\n\nmerge' :: [Int] -> [Int] -> [Int]\nmerge' [] [] = []\nmerge' (x:xs) [] = (x:merge' xs [])\nmerge' [] (y:ys) = (y:merge' ys [])\nmerge' (x:xs) (y:ys) \n | x >= y = (x:merge' xs (y:ys))\n | otherwise = (y:merge' (x:xs) ys) \n\nmain = do\n _ <- getLine\n a <- readIntList\n putStrLn $ show $ f1 a\n\n-- [Int] from line\nreadIntList :: IO [Int]\nreadIntList = do\n line <- getLine\n return $ map read $ words line"}, {"source_code": "module Main where\n\nimport Control.Monad (sequence)\nimport Data.List (sortBy)\nimport Data.Maybe (fromJust)\n\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumber :: IO Int\nreadNumber =\n (fst\n . fromJust\n . BS.readInt) `fmap` BS.getLine\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\ntwinCoins :: [Int] -> Int\ntwinCoins coinList0 = step (0, 0, coinList)\n where\n coinList = sortBy (flip compare) coinList0\n\n step (_, coinCount, []) = coinCount\n step (coinSum, coinCount, remainingCoins)\n | coinSum > sum (remainingCoins) = coinCount\n | otherwise = step ( coinSum + head remainingCoins\n , succ coinCount\n , tail remainingCoins )\n\n\n\nmain :: IO ()\nmain = do\n nCoins <- readNumber\n coinList <- take nCoins `fmap` readNumbers\n print (twinCoins coinList)\n"}, {"source_code": "import Data.List\ns l=length$last$takeWhile((>sum l).(*2).sum)$tails$sort l\nmain=interact$show.s.map read.tail.words"}, {"source_code": "import Data.List\n\nsanitize = reverse . sort\n\nsolve xs = fu (sanitize xs) 0 0\n\nfu xs s count\n | sum xs < s = count\n | otherwise = fu (tail xs) (head xs + s) (count + 1)\n\n\nmain = interact $ show . solve . tail . map read . words\n"}, {"source_code": "import Data.List (sort)\nmain :: IO ()\nmain = do\n _ <- getLine\n coins' <- getLine\n print $ sneakyCoins $ (reverse . sort) $ map read $ words coins'\n return ()\n\nsneakyCoins :: [Int] -> Int\nsneakyCoins coins = snd $ foldl (\\(amount, num) x -> if 2 * amount > total\n then (amount, num)\n else (amount + x, num + 1)) (0,0) coins\n where total = sum coins\n"}, {"source_code": "import Data.List\n--input Matrix test\n\ninputIntArray :: IO [Int]\ninputIntArray = getLine >>= \n \\line -> return (map read $ words line)\n\nnCoins :: [Int] -> IO ()\nnCoins coins = print $ length coins - re 0 (sortOn (*(-1)) coins) (sum coins)\n where\n re :: Int -> [Int] -> Int -> Int\n re sum (c:cs) total\n | sum > total `div` 2 = length (c:cs)\n | True = re (sum + c) cs total\n re _ cs _ = length cs\n\nmain :: IO ()\nmain = getLine >> inputIntArray >>= nCoins"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain= do\n\tgetLine\n \ts<-map read. words <$> getLine ::IO [Int]\n\tlet s1 = tail $ scanl (+) 0 $ reverse $ sort s\n\tlet sum1 = sum s\n\tlet s2 = div sum1 2\n\tlet ans= length $ takeWhile (<=s2) s1\n\tprint $ ans +1\n\t"}, {"source_code": "{-\nA. Twins\n==========\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nImagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.\n\nNow let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1,\u2009a2,\u2009...,\u2009an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.\n\nAs you woke up, you found Mom's coins and read her note. \"But why split the money equally?\" \u2014 you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.\n\nInput\n-----\nThe first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the coins' values. All numbers are separated with spaces.\n\nOutput\n-------\nIn the single line print the single number \u2014 the minimum needed number of coins.\n\nSample test(s)\n--------------\ninput\n```\n2\n3 3\n```\noutput\n```\n2\n```\n\ninput\n```\n3\n2 1 2\n```\noutput\n```\n2\n```\n\nNote\n-----\nIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6,\u20090 correspondingly). If you take 1 coin, you get sums 3,\u20093. If you take 0 coins, you get sums 0,\u20096. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.\n\nIn the second sample one coin isn't enough for us, too. You can pick coins with values 1,\u20092 or 2,\u20092. In any case, the minimum number of coins equals 2.\n-}\n\nimport Data.List (sort)\n\nreader :: String -> [Int]\nreader s = map read $ words ss\n where _:ss:_ = lines s\n\nnumberOfTakingCoins :: [Int] -> Int\nnumberOfTakingCoins xs = (length . takeWhile (\\k -> 2 * k <= total) $ scanl1 (+) ys) + 1\n where ys = reverse $ sort xs\n total = sum xs\n\nmain = do\n input <- getContents \n let coins = reader input\n print $ numberOfTakingCoins coins\n"}, {"source_code": "import Control.Applicative\nmain = do\n getLine\n m <- getLine\n let n = (quicksort . map read . words) m\n print $ more n\nquicksort :: Ord a => [a] -> [a]\nquicksort [] = []\nquicksort [x] = [x]\nquicksort (x:xs) = (quicksort $ filter (>x) xs) ++ [x] ++ (quicksort $ filter (<=x) xs)\nmid :: (Ord a, Num a) => Int -> [a] -> Bool\nmid x = (>) <$> (sum . take x) <*> (sum . drop x)\n-- some more beautiful way would exist\nmore :: (Ord a, Num a) => [a] -> Int\n-- more [] = error\nmore x = (+) 1 $ length $ takeWhile (==False) [mid y x | y <- [1..]]"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n coins <- sort . map (read :: String -> Int) . words <$> getLine \n let s = sum coins\n let sums = scanl (+) 0 coins\n let pos = length $ takeWhile (\\x -> x < s - x) sums\n print $ n - (pos - 1)"}, {"source_code": "import Data.List\n\nmain = interact $ show . f . sortBy (flip compare) . map read . words . (!! 1) . lines\n where f x = g x (sum x) 0 0\n g (x:xs) s c t = if c + c > s then t else g xs s (c + x) (t + 1)\n g [] _ _ t = t"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nf :: Int -> [Int] -> Int\nf s [] = 0\nf s xxs@(x:xs) \n | s > foldl (+) 0 xxs = 0\n | otherwise = 1 + (f (s+x) xs)\n\nmain :: IO ()\nmain = do\n\tnn <- getLine\n\tline <- getLine\n\tlet\n\t\tn = read nn :: Int\n\t\tarr = reverse.sort. map (\\x -> read x :: Int).words $ line\n\tprint $ f 0 arr\n"}, {"source_code": "import Data.List\n\nmain = getLine >> getLine >>= putStrLn.show.solve.reverse.sort.map read.words\n\nsolve :: [Int] -> Int\nsolve coins = search (sum coins) 0 coins\n\nsearch :: Int -> Int -> [Int] -> Int\nsearch sum s [] = 0\nsearch sum s (c:oins)\n | sum < s = 0 \n | otherwise = succ $ search (sum-c) (s+c) oins\n"}, {"source_code": "import Data.List (sort)\n\nprocess :: [Int] -> Int\nprocess xs = succ.length.takeWhile (<=mid).scanl1 (+).reverse.sort $ xs\n where mid = (sum xs) `div` 2\n \nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n print $ process as"}, {"source_code": "import Data.List\n\nans xs = length.takeWhile (read x::Int) $ words n\n print $ (read m)-(ans input)\n "}, {"source_code": "import Data.List\nmain = do\n (_:t) <- fmap (map read . words) getContents :: IO [Int]\n let a = zip [1..] $ scanl1 (+) $ sortBy (\\x y->compare y x) t\n let sum = snd $ last a\n print $ fst . head $ dropWhile (\\x->snd x <= sum - snd x) a"}, {"source_code": "qsort3 :: Ord a => [a] -> [a]\nqsort3 x = qsort3' x []\n\nqsort3' [] y = y\nqsort3' [x] y = x:y\nqsort3' (x:xs) y = part xs [] [x] [] \n where\n part [] l e g = qsort3' l (e ++ qsort3' g y)\n part (z:zs) l e g \n | z < x = part zs l e (z:g) \n | z > x = part zs (z:l) e g \n | otherwise = part zs l (z:e) g\n\ns x = s' x (sum x) 0 0 where\n s' [] _ t _ = t\n s' (x:xs) p t r | p < 2*r = t\n | otherwise = s' xs p (t+1) (r+x)\n\n\nmain = interact $ show . s . qsort3 . map read . tail . words"}, {"source_code": "\nimport Data.List\nimport Data.Ord\n\ncoins :: [Int] -> Int\ncoins inp = length takenm1 + 1\n where sorted = sortBy (comparing Down) inp\n total = sum sorted\n partialSums = tail $ scanl (+) 0 sorted\n takenm1 = takeWhile (\\x -> x <= total - x) partialSums\n\nsolve :: String -> String\nsolve = show . coins . map read . words . last . lines\n\nmain :: IO ()\nmain = interact solve"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List (sort)\n\n\nans [] _ = 0\nans left@(x:xs) right = if sum left >= sum right then 1 + ans xs (x:right)\n else 0\n\n\nmain = do\n getLine\n aa <- getLine\n let xs = map read $ words aa :: [Int]\n print $ ans xs []\n"}, {"source_code": "import Control.Monad\nimport Data.List (sort)\n\n\nans [] _ = 0\nans left@(x:xs) right = if sum left >= sum right then 1 + ans xs (x:right)\n else 0\n\n\nmain = do\n getLine\n aa <- getLine\n let xs = sort $ map read $ words aa :: [Int]\n print $ ans xs []\n"}, {"source_code": "import Data.List\nmain=interact$show.f.map read.tail.words\nf c = f' (sum c) (scanl1 (+) (sort c))\n\twhere f' s (x:xs) \n\t\t| s - x < x = 1\n\t\t| otherwise = 1 + f' s xs\n\t\t\t\t\t"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (sort, inits, tails)\n\n\nmain :: IO ()\nmain = print . solve . group . sort . map read . words =<< (getLine >> getLine)\n where solve = length . fst . head . dropWhile (\\(a,b) -> sum a <= sum b)\n group xs = zip (inits xs) (tails xs)"}, {"source_code": "main = do\n getLine\n getLine>>=(\\x->(putStr (solve (map read (words x)))))\nsolve x = show (result (qsort x) (sum x) 0 0)\nqsort[]=[]\nqsort(x:xs)=qsort[y|y<-xs,y=x]\nresult (x:xs) a b n\n |x+b>a-x = n+1\n |x+b<=a-x = result xs (a-x) (b+x) (n+1)"}, {"source_code": "import Data.List (sort)\n\nf :: Int -> [Int] -> Int\nf n xs =\n let (mine, theirs) = splitAt n xs\n in if sum mine > sum theirs\n then n\n else f (n+1) xs\n\nmain = interact $ show . f 0 . sort . map read . tail . words\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n as <- fmap (map read . words) getLine\n let\n bs = reverse $ sort as\n s = sum as\n ss = scanl1 (+) bs\n\n print $ length $ takeWhile (\\x -> 2*x <= s) ss"}, {"source_code": "import Data.List\n\ndivToNum :: String -> [Int]\ndivToNum [] = []\ndivToNum l = (read h) : (divToNum t)\n\twhere [(h,t)] = lex l\n\nminL [x] = x\nminL (x:xs) = min x $ minL xs\n\nsolve l = solve' ([],0) (l,foldl (+) 0 l)\nsolve' (l1,s1) (l2,s2) | (s1 > s2) = length l1\n | otherwise = solve' ((x:l1),s1+x) (delete x l2, s2-x)\n where x = minL l2\n\nmain = getLine >> getLine >>= (print.solve.divToNum)\n"}, {"source_code": "import Data.List\n\nmain = do\n counter <- getLine\n let n = read counter :: Int\n str <- getLine\n let xs = map read $ words str :: [Int]\n let sorted = reverse (sort xs)\n let sumXs = sum xs\n let solve sorted = _solve sumXs 0 xs 0 where\n _solve _ _ [] i = i\n _solve sumXs sum1 (x:xs) i\n | sum1 <= sumXs = _solve (sumXs - x) (sum1 + x) xs (i + 1)\n _solve _ _ _ i = i\n print (solve sorted)\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (sort)\n\nmain = do\n n <- read <$> getLine :: IO Int\n cs <- map read . words <$> getLine :: IO [Int]\n let scs = sort cs\n hsm = div (sum scs + (n-n)) 2\n print . length . takeWhile (<=hsm+1) $ scanl1 (+) scs"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (sort)\n\nmain = do\n n <- read <$> getLine :: IO Int\n cs <- map read . words <$> getLine :: IO [Int]\n let scs = scanl1 (+) $ sort cs\n hsm = div (last scs + (n-n)) 2\n (rs,ls) = span (<=hsm) scs\n m = length rs\n print $ if last rs == hsm then m + 1 else m"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nreadInts :: IO [Int]\nreadInts = do\n getLine\n i <- getLine\n return $ map read $ words i\n\nsolve :: [Int] -> Int\nsolve coins = ans + 1\n where c' = sort coins\n total = sum coins `div` 2\n (_, ans) = foldr (\\e (s, n) -> if s + e > total then (s, n) else (s + e, n + 1)) (0, 0) c'\n\nmain :: IO ()\nmain = print =<< solve <$> readInts\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Control.Monad\n\n\nmain::IO ()\nmain=do\n getLine\n a<- reverse <$> sort <$> map read <$> words <$> getLine\n let b = div ((sum a)+1) 2\n let c = scanl1 (+) a\n print $ (+) 1 $ length $ takeWhile (<=b) c\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve as = length as - length (takeWhile (< (sum as `div` 2)) (scanl1 (+) (sort as)))\n"}, {"source_code": "import Data.List(sort)\n\nsolve' [] _ _ l = l\nsolve' (x:xs) n m l = if (n + x > m - x) then l + 1 else solve' xs (n + x) (m - x) (l + 1)\n\nsolve :: [Int] -> Int\nsolve xs = solve' xs 0 (sum xs) 0\n\nmain = do\n getLine\n xs <- fmap (map read . words) getLine\n print $ solve $ sort xs\n"}, {"source_code": "import Data.List\nmain = do\n getLine\n s <- getLine\n print . solve . map read . words $ s\nsolve xs = length . takePartGT needMoreThan . sort $ xs\n where needMoreThan = sum xs `div` 2\ntakePartGT n (x:xs) | x > n = [x]\n | otherwise = x : takePartGT (n-x) xs\n"}, {"source_code": "import Data.List\n\nmain=interact$show.solve.sort.map read.tail.words\n\nsolve :: [Int] -> Int\nsolve xs = length . dropWhile (<(sum xs)`div`2) $ scanl1 (+) xs"}, {"source_code": "import Data.List\n\nmain = interact $ show.solve.map read.words\n\nsolve (_:xs) = succ . length . takeWhile (<=(sum xs)`div`2) . scanl1 (+) $ sort xs"}, {"source_code": "import Data.List\n--input Matrix test\n\ninputIntArray :: IO [Int]\ninputIntArray = getLine >>= \n \\line -> return (map read $ words line)\n\nnCoins :: [Int] -> IO ()\nnCoins coins = print $ length coins - re 0 coins (sum coins)\n where\n re :: Int -> [Int] -> Int -> Int\n re sum (c:cs) total\n | sum > total `div` 2 = length (c:cs)\n | True = re (sum + c) cs total\n re _ cs _ = length cs\n\nmain :: IO ()\nmain = getLine >> inputIntArray >>= nCoins"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain= do\n\tgetLine\n \ts<-map read. words <$> getLine ::IO [Int]\n\tlet s1 = scanl (+) 0 $ reverse $ sort s\n\tlet sum1 = sum s\n\tlet s2 = (div sum1 2 ) + (if (even sum1) then 1 else 0)\n\tprint $ length $ takeWhile (<=s2) s1\n\t"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain= do\n\tgetLine\n \ts<-map read. words <$> getLine ::IO [Int]\n\tlet s1 = tail $ scanl (+) 0 $ reverse $ sort s\n\tlet sum1 = sum s\n\tlet s2 = (div sum1 2 ) + (if (even sum1) then 1 else 0)\n\tprint $ length $ takeWhile (<=s2) s1\n\t"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.List\n\nmain= do\n\tgetLine\n \ts<-map read. words <$> getLine ::IO [Int]\n\tlet s1 = tail $ scanl (+) 0 $ reverse $ sort s\n\tlet sum1 = sum s\n\tlet s2 = (div sum1 2 ) + (if (even sum1) then 1 else 0)\n\tlet ans= length $ takeWhile ( s then t else g xs s (c + x) (t + 1)\n g [] _ _ _ = 0"}, {"source_code": "qsort3 :: Ord a => [a] -> [a]\nqsort3 x = qsort3' x []\n\nqsort3' [] y = y\nqsort3' [x] y = x:y\nqsort3' (x:xs) y = part xs [] [x] [] \n where\n part [] l e g = qsort3' l (e ++ qsort3' g y)\n part (z:zs) l e g \n | z > x = part zs l e (z:g) \n | z < x = part zs (z:l) e g \n | otherwise = part zs l (z:e) g\n\ns x = s' x (sum x) 0 0 where\n s' [] _ t _ = t\n s' (x:xs) p t r | p < 2*r = t\n | otherwise = s' xs p (t+1) (t+x)\n\n\nmain = interact $ show . s . qsort3 . map read . tail . words\n\n"}, {"source_code": "qsort3 :: Ord a => [a] -> [a]\nqsort3 x = qsort3' x []\n\nqsort3' [] y = y\nqsort3' [x] y = x:y\nqsort3' (x:xs) y = part xs [] [x] [] \n where\n part [] l e g = qsort3' l (e ++ qsort3' g y)\n part (z:zs) l e g \n | z < x = part zs l e (z:g) \n | z > x = part zs (z:l) e g \n | otherwise = part zs l (z:e) g\n\ns x = s' x (sum x) 0 0 where\n s' [] _ t _ = t\n s' (x:xs) p t r | p < 2*r = t\n | otherwise = s' xs p (t+1) (t+x)\n\n\nmain = interact $ show . s . qsort3 . map read . tail . words"}], "src_uid": "ee535e202b7662dbaa91e869c8c6cee1"} {"source_code": "import qualified Data.Map.Strict as M\nimport Data.List (nub)\nimport Data.Maybe (fromJust)\nimport Data.Array\nimport Data.Map.Strict (Map(..))\nimport Control.Monad (replicateM_, foldM)\nimport Data.Array.ST\nimport Control.Monad.ST\n\ndata Paren = LP | RP deriving (Eq)\n\nmain = read <$> getLine >>= flip replicateM_ scase\n\nscase = read <$> getLine >>= \\n -> getLine >>= print . numComps n . map fC\n where fC '(' = LP\n fC ')' = RP\n\nnumComps :: Int -> [Paren] -> Int\nnumComps n ps = (numParents n . fst . fromJust . parensToPPT) ps\n-- numComps n = numParents' . fromJust . parensToPPT' n\n-- numComps = numParents''\n\nnumParents :: Int -> Map Int Int -> Int\nnumParents n = uniqueInts (2*n) . M.elems\n\n-- fst is node->parent map (both are open brace indices)\n-- snd is open node-> close node map\ntype MT = (Map Int Int, Map Int Int)\n{-\n The closing paren for each node is not determined until it actually closes.\nFirst we can just keep children and when the node actually closes we can mark the closing number.\n-}\n-- convert a list of 2n paranthesis to a parent pointer tree\nparensToPPT :: [Paren] -> Maybe MT\nparensToPPT xs = let m :: MT\n m = (M.empty, M.empty)\n f :: Int -> [Paren] -> [Int] -> MT -> Maybe MT\n f _ [] [] m = Just m\n f i (LP:xs) s m = f (i+1) xs (i:s) m\n f _ (RP:_) [] _ = Nothing -- stack is empty and we have ')'\n f i (RP:xs) (o:s) m = f (i+1) xs s (closeWith i o s m)\n closeWith c o [] (pM, oM) = (M.insert o 0 pM, M.insert o c oM) -- top nodes have 0 as parent\n closeWith c o (p:_) (pM, oM) = (M.insert o p pM, M.insert o c oM)\n in f 1 xs [] m\n\nnumParents' :: Array Int Int -> Int\nnumParents' = length . nub . elems\n\nparensToPPT' :: Int -> [Paren] -> Maybe (Array Int Int) -- direct array parent pointer tree\nparensToPPT' n xs = let a = listArray (1, 2*n) [0,0..] \n f :: Int -> [Paren] -> [Int] -> Array Int Int -> Maybe (Array Int Int)\n f _ [] [] a = Just a\n f i (LP:xs) s a = f (i+1) xs (i:s) a\n f _ (RP:_) [] _ = Nothing\n f i (RP:xs) (o:s) a = f (i+1) xs s (if null s then a else (a//[(o, head s)]))\n in f 1 xs [] a\n\n\nnumParents'' :: Int -> [Paren] -> Int\nnumParents'' n xs = let f :: Int -> [Paren] -> [Int] -> ST s (STArray s Int Int) -> Maybe (ST s (STArray s Int Int))\n f _ [] [] a = Just a\n f i (LP:xs) s a = f (i+1) xs (i:s) a\n f _ (RP:_) [] _ = Nothing\n f i (RP:xs) (o:s) a = f (i+1) xs s (if null s then a else (a >>= \\ai -> writeArray ai o (head s) >> return ai))\n in uniqueInts (2*n) $ runST $ (fromJust $ f 1 xs [] (newArray (1, 2*n) 0 :: ST s (STArray s Int Int))) >>= getElems\n\nuniqueInts :: Int -> [Int] -> Int\nuniqueInts limit xs = let a = (newArray (0, limit) 0 :: ST s (STArray s Int Int)) in\n sum . map (\\e -> if e == 0 then 0 else 1) . elems $\n runSTArray (a >>= \\ai -> foldM (\\ai x -> readArray ai x >>= \\c -> writeArray ai x (c+1) >> return ai) ai xs)\n", "positive_code": [{"source_code": "import qualified Data.Map.Strict as M\nimport Data.List (nub)\nimport Data.Maybe (fromJust)\nimport Data.Array\nimport Data.Map.Strict (Map(..))\nimport Control.Monad (replicateM_, foldM)\nimport Data.Array.ST\nimport Control.Monad.ST\n\ndata Paren = LP | RP deriving (Eq)\n\nmain = read <$> getLine >>= flip replicateM_ scase\n\nscase = read <$> getLine >>= \\n -> getLine >>= print . numComps n . map fC\n where fC '(' = LP\n fC ')' = RP\n\nnumComps :: Int -> [Paren] -> Int\n-- numComps _ ps = (numParents . fst . fromJust . parensToPPT) ps\n-- numComps n = numParents' . fromJust . parensToPPT' n\nnumComps = numParents''\n\nnumParents :: Map Int Int -> Int\nnumParents = length . nub . M.elems\n\n-- fst is node->parent map (both are open brace indices)\n-- snd is open node-> close node map\ntype MT = (Map Int Int, Map Int Int)\n{-\n The closing paren for each node is not determined until it actually closes.\nFirst we can just keep children and when the node actually closes we can mark the closing number.\n-}\n-- convert a list of 2n paranthesis to a parent pointer tree\nparensToPPT :: [Paren] -> Maybe MT\nparensToPPT xs = let m :: MT\n m = (M.empty, M.empty)\n f :: Int -> [Paren] -> [Int] -> MT -> Maybe MT\n f _ [] [] m = Just m\n f i (LP:xs) s m = f (i+1) xs (i:s) m\n f _ (RP:_) [] _ = Nothing -- stack is empty and we have ')'\n f i (RP:xs) (o:s) m = f (i+1) xs s (closeWith i o s m)\n closeWith c o [] (pM, oM) = (M.insert o 0 pM, M.insert o c oM) -- top nodes have 0 as parent\n closeWith c o (p:_) (pM, oM) = (M.insert o p pM, M.insert o c oM)\n in f 1 xs [] m\n\nnumParents' :: Array Int Int -> Int\nnumParents' = length . nub . elems\n\nparensToPPT' :: Int -> [Paren] -> Maybe (Array Int Int) -- direct array parent pointer tree\nparensToPPT' n xs = let a = listArray (1, 2*n) [0,0..] \n f :: Int -> [Paren] -> [Int] -> Array Int Int -> Maybe (Array Int Int)\n f _ [] [] a = Just a\n f i (LP:xs) s a = f (i+1) xs (i:s) a\n f _ (RP:_) [] _ = Nothing\n f i (RP:xs) (o:s) a = f (i+1) xs s (if null s then a else (a//[(o, head s)]))\n in f 1 xs [] a\n\n\nnumParents'' :: Int -> [Paren] -> Int\nnumParents'' n xs = let f :: Int -> [Paren] -> [Int] -> ST s (STArray s Int Int) -> Maybe (ST s (STArray s Int Int))\n f _ [] [] a = Just a\n f i (LP:xs) s a = f (i+1) xs (i:s) a\n f _ (RP:_) [] _ = Nothing\n f i (RP:xs) (o:s) a = f (i+1) xs s (if null s then a else (a >>= \\ai -> writeArray ai o (head s) >> return ai))\n in uniqueInts (2*n) $ runST $ (fromJust $ f 1 xs [] (newArray (1, 2*n) 0 :: ST s (STArray s Int Int))) >>= getElems\n\nuniqueInts :: Int -> [Int] -> Int\nuniqueInts limit xs = let a = (newArray (0, limit) 0 :: ST s (STArray s Int Int)) in\n sum . map (\\e -> if e == 0 then 0 else 1) . elems $\n runSTArray (a >>= \\ai -> foldM (\\ai x -> readArray ai x >>= \\c -> writeArray ai x (c+1) >> return ai) ai xs)\n"}], "negative_code": [{"source_code": "import Data.Char (chr, ord)\nimport Data.List (sort, partition)\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>= putStrLn . minStr\n\ninc :: Char -> Char\ninc c | c < '9' = chr (1+ord c)\n | c == '9'= '9'\n\nminStr :: String -> String\nminStr s = let (ms, rest) = minSubSeq s\n in\n sort (ms ++ map inc rest)\n\n-- find the lexicographically smallest subsequence in a given string\nminSubSeq :: String -> (String, String)\nminSubSeq s = let mlss [] (stack, trash) = (reverse stack, trash)\n mlss s (stack, trash) = let (i, c, count) = minCharCount s in\n mlss (drop i s) (replicate count c ++ stack, filter (/=c) (take i s) ++ trash)\n in\n mlss s ([], [])\n\nminCharCount s = foldl f (1, head s, 1) (zip [2..] (tail s))\n where\n f (i, c, count) (ii, cc) = case compare c cc of\n EQ -> (ii, c, count+1)\n GT -> (ii, cc, 1)\n LT -> (i, c, count)\n"}, {"source_code": "import Data.Array\nimport Control.Monad (replicateM_)\n\ndata Paren = LP | RP deriving (Eq)\n\nmain = read <$> getLine >>= flip replicateM_ scase\n\nscase = read <$> getLine >>=\n \\n -> getLine >>=\n print . numComps n . map fC\n where fC '(' = LP\n fC ')' = RP\n\nnumComps :: Int -> [Paren] -> Int\nnumComps n ps = n - numIndependents ps\n\nnumIndependents (LP:ps) = f 0 1 ps -- parens can start with ')'\n where f count weight (p:ps) | weight == 0 && p == LP = f (count+1) 1 ps\n | p == LP = f count (weight+1) ps\n | p == RP = f count (weight-1) ps\n f count 0 [] = count\n"}], "src_uid": "6280a3373ab8fc34bb41fd98648019a6"} {"source_code": "main = do\n line <- getLine\n let coords = map read (words line) :: [Int]\n let x1 = coords !! 0\n let y1 = coords !! 1\n let x2 = coords !! 2\n let y2 = coords !! 3\n putStrLn $ solve x1 y1 x2 y2\n where solve x1 y1 x2 y2 = let dx = abs (x1 - x2)\n dy = abs (y1 - y2)\n in case (dx, dy) of\n (0, d) -> show (x1 + d) ++ \" \" ++ show y1 ++ \" \"++ show (x1 + d) ++ \" \" ++ show y2\n (d, 0) -> show x1 ++ \" \" ++ show (y1 + d) ++ \" \" ++ show x2 ++ \" \" ++ show (y2 + d)\n (d1, d2) -> if d1 == d2\n then show x1 ++ \" \" ++ show y2 ++ \" \" ++ show x2 ++ \" \" ++ show y1\n else \"-1\"\n ", "positive_code": [{"source_code": "main = do\n [x1, y1, x2, y2] <- fmap (map read . words) getLine\n\n putStrLn $ unwords $ map show $\n if x1 == x2\n then [x1+abs (y2-y1), y1, x1+abs (y2-y1), y2]\n else\n if y1 == y2\n then [x1, y1+abs (x2-x1), x2, y2+abs (x2-x1)]\n else\n if abs (x2-x1) == abs (y2-y1)\n then [x1, y2, x2, y1]\n else [-1]\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve [x1,x2,y1,y2] | x1==y1 && x2/=y2 && (abs x1+y2-x2)<=1000 =putStrLn $ unwords $ map show $ [x1+y2-x2,x2,y1+y2-x2,y2]\n | x1==y1 && x2/=y2 && (abs x1-y2+x2)<=1000 =putStrLn $ unwords $ map show $ [x1-y2+x2,x2,y1-y2+x2,y2]\n | x2==y2 && x1/=y1 && (abs x2-y1+x1)<=1000 =putStrLn $ unwords $ map show $ [x1,x2-y1+x1,y1,y2-y1+x1]\n | x2==y2 && x1/=y1 && (abs x2+y1-x1)<=1000 =putStrLn $ unwords $ map show $ [x1,x2+y1-x1,y1,y2+y1-x1]\n | abs (x2-y2) == abs (x1-y1) && x2-y2 /=0 =putStrLn $ unwords $ map show $ [x1,y2,y1,x2]\n | otherwise = print $ (-1)"}, {"source_code": "import Control.Applicative\n\nmain = do\n [x1,y1,x2,y2] <- map read . words <$> getLine\n let\n ps1 = [x1,y2,x2,y1]\n diff_x = abs (x1-x2)\n diff_y = abs (y1-y2)\n l = max diff_x diff_y\n ps2 = [x1+l, y1, x2+l, y2]\n ps3 = [x1, y1+l, x2, y2+l]\n in putStrLn . unwords . map show $ if diff_x == diff_y\n then ps1\n else if diff_x == 0 then ps2 else (if diff_y == 0 then ps3 else [-1])\n"}, {"source_code": "main :: IO ()\nmain = getLine >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [ x1, y1, x2, y2 ] | x1 == x2 = [ x1 + y1 - y2, y1, x2 + y1 - y2, y2 ]\n | y1 == y2 = [ x1, y1 + x1 - x2, x2, y2 + x1 - x2 ]\n | abs (x1 - x2) == abs (y1 - y2) = [ x1, y2, x2, y1 ]\n | otherwise = [ -1 ]\nsolve _ = undefined\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [a,b,c,d] | a == c = let a' = a + d - b in [a',b,a',d]\n | b == d = let b' = b + c - a in [a,b',c,b']\n | abs(c-a) == abs(d-b) = [a,d,c,b]\n | otherwise = [-1]\n"}, {"source_code": "module Main where\n\nimport Data.List\ntype PointPair = [Integer]\n\ndata SquareSide = Hor | Vert | Diag\n\ntoInt :: String -> Integer\ntoInt = read\n\ngetSide :: PointPair -> Maybe (SquareSide, Integer)\ngetSide [x1, y1, x2, y2] =\n if xw == 0 then Just (Vert, yw) else\n if yw == 0 then Just (Hor, xw) else\n if xw == yw then Just (Diag, xw) else Nothing\n where xw = abs $ x1 - x2\n yw = abs $ y1 - y2\n\nmakeSquare :: PointPair -> Maybe PointPair\nmakeSquare pts@[x1, y1, x2, y2] = do\n (pos, side) <- getSide pts\n case pos of\n Diag -> return [x1, y2, x2, y1]\n Vert -> if x1 + side <= 1000 then return [x1 + side, y1, x2 + side, y2]\n else if x1 - side >= -1000 then return [x1 - side, y1, x2 - side, y2]\n else Nothing\n Hor -> if y1 + side <= 1000 then return [x1, y1 + side, x2, y2 + side]\n else if y1 - side >= -1000 then return [x1, y1 - side, x2, y2 - side]\n else Nothing\n\nmain :: IO ()\nmain = do\n str <- getLine\n let answer = makeSquare $ map toInt $ words str\n case answer of\n Just pts -> putStrLn $ concat . intersperse \" \" . map show $ pts\n Nothing -> putStrLn \"-1\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n \n\nmain=do\t \n\t[a,b,c,d]<- map read. words <$> getLine::IO [Int] \n\tif (a==c) then putStrLn $ intercalate \" \" $ map show [a+b-d, b, c+b-d, d]\n else if (b==d) then putStrLn $ intercalate \" \" $ map show [a, b+a-c, c, d+a-c]\n\t\t else if (abs(a-c)/=abs(b-d)) then putStrLn \"-1\"\n\t\t\t\t\t else putStrLn $ intercalate \" \" $ map show [a, d, c, b]\n\t\t\t\t\t\t "}, {"source_code": "parseList :: [String] -> [Int]\nparseList [] = []\nparseList (x:xs) = (read x::Int) : (parseList xs)\n\nsolve x\n\t| (abs ((x!!0) - (x!!2))) == (abs ((x!!1) - (x!!3))) = do\n\t\tprint (x!!0)\n\t\tprint (x!!3)\n\t\tprint (x!!2)\n\t\tprint (x!!1)\n\t| ((x!!0) - (x!!2) == 0) = do\n\t\tlet diff = (x!!1) - (x!!3)\n\t\tprint ((x!!0)-diff)\n\t\tprint (x!!1)\n\t\tprint ((x!!2)-diff)\n\t\tprint (x!!3)\n\t| ((x!!1) - (x!!3) == 0) = do\n\t\tlet diff = (x!!0) - (x!!2)\n\t\tprint (x!!0)\n\t\tprint ((x!!1)+diff)\n\t\tprint (x!!2)\n\t\tprint ((x!!3)+diff)\n\t| otherwise = do\n\t\tprint (-1)\n\nmain = do\n\tstr <- getLine\n\tlet a = parseList (words str)\n\tsolve a\n"}, {"source_code": "main = do\n line <- getLine\n let nums = map read $ words line :: [Int]\n if(nums!!0==nums!!2) then do\n putStrLn $ show(nums!!0+abs(nums!!1-nums!!3)) ++ \" \"++\n show(nums!!1)++\" \"++\n show(nums!!0+abs(nums!!1-nums!!3))++ \" \"++\n show(nums!!3)\n else\n if(nums!!1==nums!!3) then do\n putStrLn $ show(nums!!0)++\" \"++\n show(nums!!1+abs(nums!!0-nums!!2))++\" \"++\n show(nums!!2)++\" \"++\n show(nums!!1+abs(nums!!0-nums!!2))\n else\n if (abs(nums!!0-nums!!2) == abs(nums!!1-nums!!3)) then do\n putStrLn $ show(nums!!0)++\" \"++\n show(nums!!3)++\" \"++\n show(nums!!2)++\" \"++\n show(nums!!1)\n else do putStrLn \"-1\"\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (x1:y1:x2:y2:_)\n | x1 == x2 =\n let dx = y1 - y2 in [x1 + dx, y1, x2 + dx, y2]\n | y1 == y2 =\n let dy = x1 - x2 in [x1, y1 + dy, x2, y2 + dy]\n | otherwise =\n if abs (x1-x2) /= abs (y1-y2)\n then [-1]\n else [x1, y2, x2, y1]\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\ngetInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tas <- getInts\n\n\tlet\n\t\tsolve [ x1, y1, x2, y2 ]\n\t\t\t| x1 == x2 = let d = y2 - y1 in [ x1 + d, y1, x2 + d, y2 ]\n\t\t\t| y1 == y2 = let d = x2 - x1 in [ x1, y2 + d, x2, y2 + d ]\n\t\t\t| abs( x2 - x1 ) == abs( y2 - y1 ) = let d = x2 - x1 in [ x1 + d, y1, x2 - d, y2 ]\n\t\t\t| otherwise = [ -1 ]\n\t\n\tputStrLn $ unwords $ map show $ solve as\n"}, {"source_code": "main :: IO()\nmain = putStrLn . unwords . map show . solve . map read . words =<< getContents\n\nsolve :: [Int] -> [Int]\nsolve (x1:y1:x2:y2:_) = let a = abs (x1 - x2)\n b = abs (y1 - y2)\n in case () of _ | a == 0 -> [x1 + b, y1, x2 + b, y2]\n | b == 0 -> [x1, y1 + a, x2, y2 + a]\n | a /= b -> [-1]\n | otherwise -> [x1, y2, x2, y1]\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ unwords . map show . getAns . map read . words\n\ngetAns :: [Int] -> [Int]\ngetAns (x1:y1:x2:y2:_) \n\t| x1 == x2 = [x1 + y1 - y2, y1, x2 + y1 - y2, y2]\n\t| y1 == y2 = [x1, y1 + x1 - x2, x2, y2 + x1 - x2]\n\t| abs (x1 - x2) == abs (y1 - y2) = [x1, y2, x2, y1]\n\t| otherwise = [-1]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport qualified Data.ByteString.Lazy.Char8 as LC\n\nmain :: IO ()\nmain = do\n line <- LC.getContents\n let (x1:y1:x2:y2:[]) = readInts $ line\n mapM_ (putStr . (++\" \") . show) $ solve x1 y1 x2 y2\n\nsolve :: Int -> Int -> Int -> Int -> [Int]\nsolve x1 y1 x2 y2\n | x1 == x2 =\n if y1 == y2\n then [-1]\n else let dx = y1 - y2 in (x1-dx):(y1):(x2-dx):(y2):[]\n | y1 == y2 =\n let dy = x1 - x2 in (x1):(y1-dy):(x2):(y2-dy):[]\n | otherwise =\n if abs (x1-x2) == abs (y1-y2)\n then [-1]\n else (x1):(y2):(x2):(y1):[]\n\n-------------------------------------------------------------------------------\n\nreadInt :: LC.ByteString -> Int\nreadInt = LC.foldl' (\\x c -> 10 * x + fromEnum c - 48) 0\n\nreadInts :: LC.ByteString -> [Int]\nreadInts str = map readInt $ LC.words str\n"}, {"source_code": "main = do\n [x1, y1, x2, y2] <- fmap (map read . words) getLine\n\n putStrLn $ unwords $ map show $\n if x1 == x2\n then [x1+abs (y2-y1), y1, x1+abs (y2-y1), y2]\n else\n if y1 == y2\n then [x1, y1+abs (x2-x1), y1, x2, y2+abs (y2-y1)]\n else\n if abs (x2-x1) == abs (y2-y1)\n then [x1, y2, x2, y1]\n else [-1]\n"}, {"source_code": "main = do\n [x1, y1, x2, y2] <- fmap (map read . words) getLine\n\n putStrLn $ unwords $ map show $\n if x1 == x2\n then [x1+abs (y2-y1), y1, x1+abs (y2-y1), y2]\n else\n if y1 == y2\n then [x1, y1+abs (x2-x1), x2, y2+abs (y2-y1)]\n else\n if abs (x2-x1) == abs (y2-y1)\n then [x1, y2, x2, y1]\n else [-1]\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = (solve.concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve [x1,x2,y1,y2] | x1==y1 && x2/=y2 && (abs x1+y2-x2)<=1000 =putStrLn $ unwords $ map show [x1+y2-x2,x1+y2-x2,y1,y2]\n | x1==y1 && x2/=y2 && (abs x1-y2+x2)<=1000 =putStrLn $ unwords $ map show $ [x1-y2+x2,x1-y2+x2,y1,y2]\n | x2==y2 && x1/=y1 && (abs x2-y1+x1)<=1000 =putStrLn $ unwords $ map show $ [x2-y1+x1,x2-y1+x1,y2,y1]\n | x2==y2 && x1/=y1 && (abs x2+y1-x1)<=1000 =putStrLn $ unwords $ map show $ [x2+y1-x1,x2+y1-x1,y2,y1]\n | abs (x2-y2) == abs (x1-y1) && x2-y2 /=0 =putStrLn $ unwords $ map show $ [x1,y2,y1,x2]\n | otherwise = print $ (-1)"}, {"source_code": "main :: IO ()\nmain = getLine >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [ x1, y1, x2, y2 ] | x1 == x2 = [ x1 + y1 - y2, y1, x2 + y1 - y2, y2 ]\n | y1 == y2 = [ x1, y1 + x1 - x2, x2, y2 + x1 - x2 ]\n | x1 - x2 == y1 - y2 = [ x1, y2, x2, y1 ]\n | otherwise = [ -1 ]\nsolve _ = undefined\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [a,b,c,d] | a == c = let a' = a + d - b in [a',b,a',d]\n | b == d = let b' = b + c - a in [a,b',c,b']\n | otherwise = [a,d,c,b]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n \n\nmain=do\t \n\t[a,b,c,d]<- map read. words <$> getLine::IO [Int] \n\tif (a==c) then putStrLn $ intercalate \" \" $ map show [a+b-d, b, c+b-d, d]\n else if (b==d) then putStrLn $ intercalate \" \" $ map show [a, b+a-c, c, d+a-c]\n\t\t else if ( a==b) then putStrLn $ intercalate \" \" $ map show [a, d, c, b]\n\t\t\t\t\t\t else putStrLn $ intercalate \" \" $ map show [a, d, b, c]"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n \n\nmain=do\t \n\t[a,b,c,d]<- map read. words <$> getLine::IO [Int] \n\tif (a==c) then putStrLn $ intercalate \" \" $ map show [a+b-d, b, c+b-d, d]\n else if (b==d) then putStrLn $ intercalate \" \" $ map show [a, b+a-c, c, d+a-c]\n\t\t else if (a-c/=b-d) then putStrLn \"-1\"\n\t\t\t\t\t else putStrLn $ intercalate \" \" $ map show [a, d, c, b]\n\t\t\t\t\t\t "}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \n \n\nmain=do\t \n\t[a,b,c,d]<- map read. words <$> getLine::IO [Int] \n\tif (a==c) then putStrLn $ intercalate \" \" $ map show [a+b-d, b, c+b-d, d]\n else if (b==d) then putStrLn $ intercalate \" \" $ map show [a, b+a-c, c, d+a-c]\n\t\t else if (a-c/=b-d) then putStrLn \"-1\"\n\t\t\t\t\t else if ( a==b) then putStrLn $ intercalate \" \" $ map show [a, d, c, b]\n\t\t\t\t\t\t else putStrLn $ intercalate \" \" $ map show [a, d, b, c]"}], "src_uid": "71dea31e1244797f916adf5f526f776e"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n a <- getInts n\n let\n ra = reverse a\n issues = take 1 $ filter (uncurry (/=)) $ zip a ra\n tries = 0 : concatMap (\\(x, y) -> [x, y]) issues\n opts = [filter (/= v) a | v <- tries]\n ans = any isPalindrome opts\n isPalindrome li = li == reverse li\n pure $ string7 $ if ans\n then \"YES\\n\"\n else \"NO\\n\"\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xs <- readInts\r\n let dif = find (uncurry (/=)) $ zip xs (reverse xs)\r\n tryWo c = ys == reverse ys where ys = filter (/=c) xs\r\n tryBoth (c, d) = tryWo c || tryWo d\r\n putStrLn $ if maybe True tryBoth dif then \"YES\" else \"NO\"\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}, {"source_code": "import Prelude\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Maybe (catMaybes)\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.unlines . map processTest . takeElementsWithOddIndices . drop 1 . B.lines\r\n\r\n\r\ntakeElementsWithOddIndices :: [a] -> [a]\r\ntakeElementsWithOddIndices elements = case elements of\r\n x1:x2:xs -> x2 : takeElementsWithOddIndices xs\r\n _ -> []\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest input = output\r\n where\r\n input_sequence = map fst $ catMaybes $ map B.readInteger $ B.words $ input\r\n output = B.pack $ if isKalindrome input_sequence then \"YES\" else \"NO\"\r\n\r\n\r\nisKalindrome :: [Integer] -> Bool\r\nisKalindrome xs = result\r\n where\r\n wrong_pairs = filter (\\ (l, r) -> l /= r) $ zip xs (reverse xs)\r\n variants_to_check = [xs] ++ case wrong_pairs of\r\n (l, r) : other_pairs -> [filter (/= l) xs, filter (/= r) xs]\r\n [] -> []\r\n result = any isPalindrome variants_to_check\r\n\r\n\r\nisPalindrome :: [Integer] -> Bool\r\nisPalindrome xs = xs == reverse xs\r\n"}, {"source_code": "import Prelude\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Maybe (catMaybes)\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.unlines . map processTest . takeElementsWithOddIndices . drop 1 . B.lines\r\n\r\n\r\ntakeElementsWithOddIndices :: [a] -> [a]\r\ntakeElementsWithOddIndices elements = case elements of\r\n x1:x2:xs -> x2 : takeElementsWithOddIndices xs\r\n _ -> []\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest input = output\r\n where\r\n input_sequence = map (fromIntegral . fst) $ catMaybes $ map B.readInt $ B.words $ input\r\n output = B.pack $ if isKalindrome input_sequence then \"YES\" else \"NO\"\r\n\r\n\r\nisKalindrome :: [Integer] -> Bool\r\nisKalindrome xs = result\r\n where\r\n wrong_pairs = filter (\\ (l, r) -> l /= r) $ zip xs (reverse xs)\r\n variants_to_check = [xs] ++ case wrong_pairs of\r\n (l, r) : other_pairs -> [filter (/= l) xs, filter (/= r) xs]\r\n [] -> []\r\n result = any isPalindrome variants_to_check\r\n\r\n\r\nisPalindrome :: [Integer] -> Bool\r\nisPalindrome xs = xs == reverse xs\r\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\r\nimport Data.Maybe (catMaybes)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n B.interact (\\ input -> processInput input)\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.unlines . map processTest . takeElementsWithOddIndices . drop 1 . B.lines\r\n\r\n\r\ntakeElementsWithOddIndices :: [a] -> [a]\r\ntakeElementsWithOddIndices elements = case elements of\r\n x1:x2:xs -> x2 : takeElementsWithOddIndices xs\r\n _ -> []\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest input = output\r\n where\r\n input_sequence = map (fromIntegral . fst) $ catMaybes $ map B.readInt $ B.words $ input\r\n output = B.pack $ if isKalindrome input_sequence then \"YES\" else \"NO\"\r\n\r\n\r\nisKalindrome :: [Integer] -> Bool\r\nisKalindrome xs = result\r\n where\r\n wrong_pairs = filter (\\ (l, r) -> l /= r) $ zip xs (reverse xs)\r\n result = case wrong_pairs of\r\n [] -> True\r\n (l, r) : other_pairs -> isPalindrome (filter (/= l) xs) || isPalindrome (filter (/= r) xs)\r\n\r\n\r\nisPalindrome :: [Integer] -> Bool\r\nisPalindrome xs = xs == reverse xs\r\n"}], "negative_code": [], "src_uid": "712e6e228e8b7cedd9bf6b85cd35c0b7"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (solve . linetois) l : tcio rest \n linetoi = read\n linetois = (map linetoi) . words\n\nsolve :: [Int] -> String\nsolve as | null $ filter ( not . null . (drop 1)) $ group $ sort as = \"NO\"\n | otherwise = \"YES\"\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\nimport Data.List (group, sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>>\n map (words >>> map read) >>> process >>> map (bool \"NO\" \"YES\") >>> unlines\n\nprocess :: [[Int]] -> [Bool]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Bool\nsolve = any ((> 1) . length) . group . sort\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\n\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (itoline. solve . linetois) l : tcio rest \n linetoi = read\n itoline = show\n linetois = (map linetoi) . words\n\nsolve :: [Int] -> String\nsolve as | null $ filter ( not . null . (drop 1)) $ group $ sort as = \"NO\"\n | otherwise = \"YES\"\n"}], "src_uid": "3674a98de27b9bd2c8eb951da72996f5"} {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Char as C\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [String]\nreadInts = map C8.unpack . C8.words\n\nsimplify :: String -> String -> String\nsimplify [] stack = stack\nsimplify (x:xs) stack\n | x == '(' = simplify xs (x:stack)\n | List.null stack = simplify xs (x:stack)\n | otherwise = let (top:stack') = stack\n in if top == '(' then\n simplify xs stack'\n else\n simplify xs (x:stack)\n\ncanBeValid :: String -> Bool\ncanBeValid [] = True\ncanBeValid (x:xs) = all (==x) xs\n\ngetNumber :: String -> Int\ngetNumber [] = 0\ngetNumber xs = if head xs == '(' then length xs else 0 - (length xs)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n bs <- input\n let brackets = readInts bs\n candidates = filter canBeValid $ map (flip simplify []) brackets\n candidates' = map getNumber candidates :: [Int]\n sorted = List.sort candidates'\n grouped = List.group sorted\n map' = Map.fromList $ map (\\(x:xs) -> (x,length xs + 1)) grouped\n total = foldl (\\acc (val,count) ->\n case Map.lookup (-val) map' of\n Nothing -> acc\n Just count' -> acc + (toInteger count) * (toInteger count')\n )\n 0 $ filter (\\(k,v) -> k <= 0) $ Map.assocs map' :: Integer\n print total\n \n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport qualified Data.Map.Strict as M\nimport qualified Data.Maybe as MYB\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let nword:xs = words input\n n = fastRead nword\n maybeMap = map countBracket xs :: [Maybe Int64]\n mappedValues = MYB.catMaybes . filter MYB.isJust $ maybeMap\n answer = getAnswer (trace (show mappedValues) mappedValues)\n in show answer\n\ncountBracket::String -> Maybe Int64\ncountBracket xsP\n | MYB.isNothing folded = Nothing\n | forward > 0 && backward > 0 = Nothing\n | otherwise = Just . fromIntegral $ forward - backward\n where \n folder :: Maybe String -> Char -> Maybe String\n folder Nothing _ = Nothing\n folder (Just []) c = Just [c]\n folder (Just ('(':xs)) ')' = Just xs\n folder (Just xs) a = Just (a:xs)\n folded = foldl' folder (Just []) xsP\n Just arr = folded\n forward = length . filter (== ')') $ arr\n backward = length . filter (== '(') $ arr\n\ngetAnswer:: [Int64] -> Int64\ngetAnswer input =\n let folder :: (Int64, M.Map Int64 Int64) -> Int64 -> (Int64, M.Map Int64 Int64)\n folder (answer, stateMap) current = (answer + currentOppositeValue + eqVal, M.insert current (currentValue + 1) stateMap)\n where \n eqVal\n | current == 0 = currentOppositeValue + 1\n | otherwise = 0\n currentValue = M.findWithDefault 0 current stateMap :: Int64\n currentOppositeValue = M.findWithDefault 0 (-current) stateMap :: Int64\n (answer, stateMap) = foldl' folder (0, M.empty) input\n in trace (M.showTree stateMap) answer\n\ntrace _ a = a\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport qualified Data.Map.Strict as M\nimport qualified Data.Maybe as MYB\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let nword:xs = words input\n n = fastRead nword\n maybeMap = map countBracket xs :: [Maybe Int64]\n mappedValues = MYB.catMaybes . filter MYB.isJust $ maybeMap\n answer = getAnswer mappedValues\n in show answer\n\ncountBracket::String -> Maybe Int64\ncountBracket xsP = \n let folder x '(' = x + 1\n folder x ')' = x - 1\n (initBack,remaining) = span (== ')') xsP\n remainingBack = length . filter (== ')') $ remaining\n remainingForward = length . filter (== '(') $ remaining\n remainingValue = -remainingBack + remainingForward\n initBackLength = length initBack\n in if initBackLength > 0 && remainingValue > 0 then\n Nothing\n else\n Just . fromIntegral $ (remainingValue - initBackLength)\n\n\ngetAnswer:: [Int64] -> Int64\ngetAnswer input =\n let folder :: (Int64, M.Map Int64 Int64) -> Int64 -> (Int64, M.Map Int64 Int64)\n folder (answer, stateMap) current = (answer + currentOppositeValue + eqVal, M.insert current (currentValue + 1) stateMap)\n where \n eqVal\n | current == 0 = currentOppositeValue + 1\n | otherwise = 0\n currentValue = M.findWithDefault 0 current stateMap :: Int64\n currentOppositeValue = M.findWithDefault 0 (-current) stateMap :: Int64\n (answer, stateMap) = foldl' folder (0, M.empty) input\n in trace (M.showTree stateMap) answer\n\ntrace _ s = s\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport qualified Data.Map.Strict as M\nimport qualified Data.Maybe as MYB\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let nword:xs = words input\n n = fastRead nword\n maybeMap = map countBracket xs :: [Maybe Int64]\n mappedValues = MYB.catMaybes . filter MYB.isJust $ maybeMap\n answer = getAnswer mappedValues\n in show answer\n\ncountBracket::String -> Maybe Int64\ncountBracket xsP = \n let folder x '(' = x + 1\n folder x ')' = x - 1\n (initBack,remaining) = span (== ')') xsP\n remainingBack = length . filter (== ')') $ remaining\n remainingForward = length . filter (== '(') $ remaining\n remainingValue = -remainingBack + remainingForward\n initBackLength = length initBack\n in if initBackLength > 0 && remainingValue > 0 then\n Nothing\n else\n Just . fromIntegral $ (remainingValue - initBackLength)\n\n\ngetAnswer:: [Int64] -> Int64\ngetAnswer input =\n let folder :: (Int64, M.Map Int64 Int64) -> Int64 -> (Int64, M.Map Int64 Int64)\n folder (answer, stateMap) current = (answer + currentOppositeValue * 2 + eqVal, M.insert current (currentValue + 1) stateMap)\n where \n eqVal\n | current == 0 = 1\n | otherwise = 0\n currentValue = M.findWithDefault 0 current stateMap :: Int64\n currentOppositeValue = M.findWithDefault 0 (-current) stateMap :: Int64\n (answer, stateMap) = foldl' folder (0, M.empty) input\n in trace (M.showTree stateMap) answer\n\ntrace _ s = s\n"}, {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Char as C\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [String]\nreadInts = map C8.unpack . C8.words\n\nsimplify :: String -> String -> String\nsimplify [] stack = stack\nsimplify (x:xs) stack\n | x == '(' = simplify xs (x:stack)\n | List.null stack = simplify xs (x:stack)\n | otherwise = let (top:stack') = stack\n in if top == '(' then\n simplify xs stack'\n else\n simplify xs (x:stack)\n\ncanBeValid :: String -> Bool\ncanBeValid [] = True\ncanBeValid (x:xs) = all (==x) xs\n\ngetNumber :: String -> Int\ngetNumber [] = 0\ngetNumber xs = if head xs == '(' then length xs else 0 - (length xs)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n bs <- input\n let brackets = readInts bs\n candidates = filter canBeValid $ map (flip simplify []) brackets\n candidates' = map getNumber candidates :: [Int]\n sorted = List.sort candidates'\n grouped = List.group sorted\n map' = Map.fromList $ map (\\(x:xs) -> (x,length xs + 1)) grouped\n total = foldl (\\acc (val,count) ->\n case Map.lookup (-val) map' of\n Nothing -> acc\n Just count' -> acc + (toInteger $ count * count')\n )\n 0 $ filter (\\(k,v) -> k <= 0) $ Map.assocs map' :: Integer\n print total\n \n"}, {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Char as C\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [String]\nreadInts = map C8.unpack . C8.words\n\nsimplify :: String -> String -> String\nsimplify [] stack = stack\nsimplify (x:xs) stack\n | x == '(' = simplify xs (x:stack)\n | List.null stack = simplify xs (x:stack)\n | otherwise = let (top:stack') = stack\n in if top == '(' then\n simplify xs stack'\n else\n simplify xs (x:stack)\n\ncanBeValid :: String -> Bool\ncanBeValid [] = True\ncanBeValid (x:xs) = all (==x) xs\n\ngetNumber :: String -> Int\ngetNumber [] = 0\ngetNumber xs = if head xs == '(' then length xs else 0 - (length xs)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n bs <- input\n let brackets = readInts bs\n candidates = filter canBeValid $ map (flip simplify []) brackets\n candidates' = map getNumber candidates :: [Int]\n sorted = List.sort candidates'\n grouped = List.group sorted\n map' = Map.fromList $ map (\\(x:xs) -> (x,length xs + 1)) grouped\n total = foldl (\\acc (val,count) ->\n case Map.lookup (-val) map' of\n Nothing -> acc\n Just count' -> if val == 0 then\n acc + count * count\n else\n acc + count * count')\n 0 $ filter (\\(k,v) -> k <= 0) $ Map.assocs map'\n print candidates\n print grouped\n print total"}, {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Char as C\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [String]\nreadInts = map C8.unpack . C8.words\n\nsimplify :: String -> String -> String\nsimplify [] stack = stack\nsimplify (x:xs) stack\n | x == '(' = simplify xs (x:stack)\n | List.null stack = simplify xs (x:stack)\n | otherwise = let (top:stack') = stack\n in if top == '(' then\n simplify xs stack'\n else\n simplify xs (x:stack)\n\ncanBeValid :: String -> Bool\ncanBeValid [] = True\ncanBeValid (x:xs) = all (==x) xs\n\ngetNumber :: String -> Int\ngetNumber [] = 0\ngetNumber xs = if head xs == '(' then length xs else 0 - (length xs)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n bs <- input\n let brackets = readInts bs\n candidates = filter canBeValid $ map (flip simplify []) brackets\n candidates' = map getNumber candidates :: [Int]\n sorted = List.sort candidates'\n grouped = List.group sorted\n map' = Map.fromList $ map (\\(x:xs) -> (x,length xs + 1)) grouped\n total = foldl (\\acc (val,count) ->\n case Map.lookup (-val) map' of\n Nothing -> acc\n Just count' -> if val == 0 then\n acc + count * count\n else\n acc + count * count')\n 0 $ filter (\\(k,v) -> k <= 0) $ Map.assocs map'\n print total"}, {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [String]\nreadInts = map C8.unpack . C8.lines\n\nsimplify :: String -> String -> String\nsimplify [] stack = stack\nsimplify (x:xs) stack\n | x == '(' = simplify xs (x:stack)\n | List.null stack = simplify xs (x:stack)\n | otherwise = let (top:stack') = stack\n in if top == '(' then\n simplify xs stack'\n else\n simplify xs (x:stack)\n\ncanBeValid :: String -> Bool\ncanBeValid [] = True\ncanBeValid (x:xs) = all (==x) xs\n\ngetNumber :: String -> Int\ngetNumber [] = 0\ngetNumber xs = if head xs == '(' then length xs else 0 - (length xs)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n bs <- input\n let brackets = readInts bs\n candidates = filter canBeValid $ map (flip simplify []) brackets\n candidates' = map getNumber candidates :: [Int]\n sorted = List.sort candidates'\n grouped = List.group sorted\n map' = Map.fromList $ map (\\(x:xs) -> (x,length xs + 1)) grouped\n total = foldl (\\acc (val,count) ->\n case Map.lookup (-val) map' of\n Nothing -> acc\n Just count' -> if val == 0 then\n acc + count * count\n else\n acc + count * count')\n 0 $ filter (\\(k,v) -> k <= 0) $ Map.assocs map'\n print total\n"}], "src_uid": "f5f163198fbde6a5c15c50733cfd9176"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\n\ndata Tree = Leaf | Node Tree Tree Int deriving (Eq, Show)\n\ninsert :: Tree -> [Bool] -> Tree\ninsert (Node Leaf Leaf c) [] = Node Leaf Leaf (c+1)\ninsert Leaf [] = Node Leaf Leaf 1\ninsert Leaf (b:bs) =\n if b then Node Leaf (insert Leaf bs) 1 else Node (insert Leaf bs) Leaf 1\n\ninsert (Node l r c) (b:bs) = Node l' r' (c+1)\n where\n l' = if b then l else insert l bs\n r' = if b then insert r bs else r\n\nremove :: Tree -> [Bool] -> Tree\nremove (Node Leaf Leaf c) [] = if c == 1 then Leaf else Node Leaf Leaf (c-1)\nremove (Node l r c) (b:bs) =\n if c == 1 then Leaf else Node l' r' (c-1)\n where\n l' = if b then l else remove l bs\n r' = if b then remove r bs else r\n\nquery :: Tree -> [Bool] -> [Bool]\nquery _ [] = []\nquery (Node l r c) (b:bs)\n | b && (l /= Leaf) = True:(query l bs)\n | not b && (r /= Leaf) = True:(query r bs)\n | l /= Leaf = b:(query l bs)\n | r /= Leaf = (not b):(query r bs)\n\nbools :: Int -> [Bool]\nbools x = map (x `testBit`) [31,30..0]\n\nint :: [Bool] -> Int\nint bs = sum $ zipWith (\\i b -> if b then bit i else 0) [31,30..0] bs\n\nmain = do\n q <- readLn\n qs <- replicateM q ((\\[a, b] -> (a, read b)) . words <$> getLine)\n\n let\n handle :: Tree -> [(String, Int)] -> [Int]\n handle t [] = []\n handle t ((\"+\", x):qs) = handle t' qs\n where t' = insert t (bools x)\n handle t ((\"-\", x):qs) = handle t' qs\n where t' = remove t (bools x)\n\n handle t ((\"?\", x):qs) = (int $ query t (bools x)):(handle t qs)\n\n t = insert Leaf (bools 0)\n\n putStr $ unlines $ map show $ handle t qs\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as M\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.Read as T\nimport qualified Data.Text.IO as T\nimport Data.Either (either)\nimport Data.Bits (xor)\nimport Control.Monad (replicateM, foldM, foldM_)\nimport Data.List (foldl')\n\n\nparseInt :: Text -> Int\nparseInt = either (error \"wtf\") fst . T.decimal . T.stripStart\n\ndata Query =\n Add {-# UNPACK #-} !Int\n | Erase {-# UNPACK #-} !Int\n | MXor {-# UNPACK #-} !Int deriving (Eq, Ord, Read, Show)\n\nqGetInt :: Query -> Int\nqGetInt q =\n case q of\n Add i -> i\n Erase i -> i\n MXor i -> i\n\nparseQ :: Text -> Query\nparseQ t = \n let n = parseInt (T.tail t)\n in case T.head t of\n '+' -> Add n\n '-' -> Erase n\n _ -> MXor n\n\nrunQ :: IntMap Int -> Query -> (IntMap Int, Maybe Int)\nrunQ m q =\n case q of\n Add n -> (M.insertWith (+) n 1 m, Nothing)\n Erase n -> (M.update (\\i -> if i > 1 then Just (i-1) else Nothing) n m, Nothing)\n MXor n -> (m, Just (M.foldlWithKey' (\\a k _-> max a (xor n k)) 0 m))\n\n\nmain0 :: IO ()\nmain0 = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n ms <- foldM (\\m q -> (\\(m', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return m') (runQ m q)) M.empty qs \n return ()\n\ndata Trie =\n Empty\n | Leaf {-# UNPACK #-} !Int\n | Node {-# UNPACK #-} !Trie {-# UNPACK #-} !Trie\n deriving (Show, Eq, Ord)\n\nisEmpty :: Trie -> Bool\nisEmpty t = \n case t of\n Empty -> True\n Leaf n -> False\n Node l r -> isEmpty l && isEmpty r\n\ndigits :: Int -> Int -> [Int]\ndigits base n0 = go n0 []\n where\n go n acc\n | n < base = n:acc\n | otherwise = let (q, r) = quotRem n base\n in go q (r:acc)\n\nundigits :: Int -> [Int] -> Int\nundigits base ds = go (reverse ds) 1 0\n where\n go ds p n =\n case ds of\n [] -> n\n d:ds' -> go ds' (p*base) (n + d*p)\n \ndigitsPad :: Int -> Int -> Int -> [Int]\ndigitsPad sz base n = replicate (sz - length ds) 0 ++ ds\n where\n ds = digits base n\n\nadd :: Int -> Trie -> Trie\nadd i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Empty) -> Leaf 1\n ([], Leaf n) -> Leaf (n+1)\n (0:ds', Empty) -> Node (go ds' Empty) Empty\n (1:ds', Empty) -> Node Empty (go ds' Empty)\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie add invariant failed\"\n\nerase :: Int -> Trie -> Trie\nerase i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Leaf n) | n > 1 -> Leaf (n-1)\n | otherwise -> Empty\n (_, Empty) -> Empty\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie erase invariant failed\"\n \n\n\nmaxXor :: Int -> Trie -> Maybe Int\nmaxXor i = go [] (digitsPad 32 2 i)\n where\n go o ds t =\n case (ds, t) of\n (_, Leaf n) -> Just (xor i . undigits 2 . reverse $ o)\n (d:ds', Node l r) | isEmpty l -> go (1:o) ds' r\n | isEmpty r -> go (0:o) ds' l\n | d == 0 -> go (1:o) ds' r\n | d == 1 -> go (0:o) ds' l\n _ -> error \"Trie invariant failed\"\n \n\nrunQuery :: Query -> Trie -> (Trie, Maybe Int)\nrunQuery q t =\n case q of\n Add i -> (add i t, Nothing)\n Erase i -> (erase i t, Nothing)\n MXor i -> (t, maxXor i t)\n\ntestT :: Bool\ntestT = isEmpty (foldl' (flip erase) (foldl' (flip add) Empty [1..1000]) [1..1000])\n\n\nmain :: IO ()\nmain = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n foldM_ (\\t q -> (\\(t', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return t') (runQuery q t)) (add 0 Empty) qs \n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as M\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.Read as T\nimport qualified Data.Text.IO as T\nimport Data.Either (either)\nimport Data.Bits (xor)\nimport Control.Monad (replicateM, foldM, foldM_)\n\n\nparseInt :: Text -> Int\nparseInt = either (error \"wtf\") fst . T.decimal . T.stripStart\n\ndata Query =\n Add {-# UNPACK #-} !Int\n | Erase {-# UNPACK #-} !Int\n | MXor {-# UNPACK #-} !Int deriving (Eq, Ord, Read, Show)\n\nparseQ :: Text -> Query\nparseQ t = \n let n = parseInt (T.tail t)\n in case T.head t of\n '+' -> Add n\n '-' -> Erase n\n _ -> MXor n\n\nrunQ :: IntMap Int -> Query -> (IntMap Int, Maybe Int)\nrunQ m q =\n case q of\n Add n -> (M.insertWith (+) n 1 m, Nothing)\n Erase n -> (M.update (\\i -> if i > 1 then Just (i-1) else Nothing) n m, Nothing)\n MXor n -> (m, Just (M.foldlWithKey' (\\a k _-> max a (xor n k)) 0 m))\n\n\nmain0 :: IO ()\nmain0 = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n ms <- foldM (\\m q -> (\\(m', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return m') (runQ m q)) M.empty qs \n return ()\n\ndata Trie =\n Empty\n | Leaf {-# UNPACK #-} !Int\n | Node {-# UNPACK #-} !Trie {-# UNPACK #-} !Trie\n deriving (Show, Eq, Ord)\n\nisEmpty :: Trie -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ndigits :: Int -> Int -> [Int]\ndigits base n0 = go n0 []\n where\n go n acc\n | n < base = n:acc\n | otherwise = let (q, r) = quotRem n base\n in go q (r:acc)\n\nundigits :: Int -> [Int] -> Int\nundigits base ds = go (reverse ds) 1 0\n where\n go ds p n =\n case ds of\n [] -> n\n d:ds' -> go ds' (p*base) (n + d*p)\n \ndigitsPad :: Int -> Int -> Int -> [Int]\ndigitsPad sz base n = replicate (sz - length ds) 0 ++ ds\n where\n ds = digits base n\n\nadd :: Int -> Trie -> Trie\nadd i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Empty) -> Leaf 1\n ([], Leaf n) -> Leaf (n+1)\n (0:ds', Empty) -> Node (go ds' Empty) Empty\n (1:ds', Empty) -> Node Empty (go ds' Empty)\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie add invariant failed\"\n\nerase :: Int -> Trie -> Trie\nerase i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Leaf n) | n > 1 -> Leaf (n-1)\n | otherwise -> Empty\n (_, Empty) -> Empty\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie erase invariant failed\"\n \n\n\nmaxXor :: Int -> Trie -> Maybe Int\nmaxXor i = go [] (digitsPad 32 2 i)\n where\n go o ds t =\n case (ds, t) of\n (_, Empty) -> Just i\n (_, Leaf n) -> Just (xor i . undigits 2 . reverse $ o)\n (d:ds', Node l r) | isEmpty l -> go (1:o) ds' r\n | isEmpty r -> go (0:o) ds' l\n | d == 0 -> go (1:o) ds' r\n | d == 1 -> go (0:o) ds' l\n _ -> error \"Trie invariant failed\"\n \n\nrunQuery :: Query -> Trie -> (Trie, Maybe Int)\nrunQuery q t =\n case q of\n Add i -> (add i t, Nothing)\n Erase i -> (erase i t, Nothing)\n MXor i -> (t, maxXor i t)\n\n\nmain :: IO ()\nmain = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n foldM_ (\\t q -> (\\(t', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return t') (runQuery q t)) Empty qs \n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as M\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.Read as T\nimport qualified Data.Text.IO as T\nimport Data.Either (either)\nimport Data.Bits (xor)\nimport Control.Monad (replicateM, foldM, foldM_)\n\n\nparseInt :: Text -> Int\nparseInt = either (error \"wtf\") fst . T.decimal . T.stripStart\n\ndata Query =\n Add {-# UNPACK #-} !Int\n | Erase {-# UNPACK #-} !Int\n | MXor {-# UNPACK #-} !Int deriving (Eq, Ord, Read, Show)\n\nparseQ :: Text -> Query\nparseQ t = \n let n = parseInt (T.tail t)\n in case T.head t of\n '+' -> Add n\n '-' -> Erase n\n _ -> MXor n\n\nrunQ :: IntMap Int -> Query -> (IntMap Int, Maybe Int)\nrunQ m q =\n case q of\n Add n -> (M.insertWith (+) n 1 m, Nothing)\n Erase n -> (M.update (\\i -> if i > 1 then Just (i-1) else Nothing) n m, Nothing)\n MXor n -> (m, Just (M.foldlWithKey' (\\a k _-> max a (xor n k)) 0 m))\n\n\nmain0 :: IO ()\nmain0 = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n ms <- foldM (\\m q -> (\\(m', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return m') (runQ m q)) M.empty qs \n return ()\n\ndata Trie =\n Empty\n | Leaf {-# UNPACK #-} !Int\n | Node {-# UNPACK #-} !Trie {-# UNPACK #-} !Trie\n deriving (Show, Eq, Ord)\n\nisEmpty :: Trie -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ndigits :: Int -> Int -> [Int]\ndigits base n0 = go n0 []\n where\n go n acc\n | n < base = n:acc\n | otherwise = let (q, r) = quotRem n base\n in go q (r:acc)\n\nundigits :: Int -> [Int] -> Int\nundigits base ds = go (reverse ds) 1 0\n where\n go ds p n =\n case ds of\n [] -> n\n d:ds' -> go ds' (p*base) (n + d*p)\n \ndigitsPad :: Int -> Int -> Int -> [Int]\ndigitsPad sz base n = replicate (sz - length ds) 0 ++ ds\n where\n ds = digits base n\n\nadd :: Int -> Trie -> Trie\nadd i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Empty) -> Leaf 1\n ([], Leaf n) -> Leaf (n+1)\n (0:ds', Empty) -> Node (go ds' Empty) Empty\n (1:ds', Empty) -> Node Empty (go ds' Empty)\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie add invariant failed\"\n\nerase :: Int -> Trie -> Trie\nerase i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Leaf n) | n > 1 -> Leaf (n-1)\n | otherwise -> Empty\n (_, Empty) -> Empty\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie erase invariant failed\"\n \n\n\nmaxXor :: Int -> Trie -> Maybe Int\nmaxXor i = go [] (digitsPad 32 2 i)\n where\n go o ds t =\n case (ds, t) of\n (_, Empty) -> Nothing\n (_, Leaf n) -> Just (xor i . undigits 2 . reverse $ o)\n (d:ds', Node l r) | isEmpty l -> go (1:o) ds' r\n | isEmpty r -> go (0:o) ds' l\n | d == 0 -> go (1:o) ds' r\n | d == 1 -> go (0:o) ds' l\n _ -> error \"Trie invariant failed\"\n \n\nrunQuery :: Query -> Trie -> (Trie, Maybe Int)\nrunQuery q t =\n case q of\n Add i -> (add i t, Nothing)\n Erase i -> (erase i t, Nothing)\n MXor i -> (t, maxXor i t)\n\n\nmain :: IO ()\nmain = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n foldM_ (\\t q -> (\\(t', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return t') (runQuery q t)) Empty qs \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Bits\n\ndata Tree = Leaf | Node Tree Tree Int deriving (Eq, Show)\n\ninsert :: Tree -> [Bool] -> Tree\ninsert _ [] = Node Leaf Leaf 1\ninsert Leaf (b:bs) =\n if b then Node Leaf (insert Leaf bs) 1 else Node (insert Leaf bs) Leaf 1\n\ninsert (Node l r c) (b:bs) = Node l' r' (c+1)\n where\n l' = if b then l else insert l bs\n r' = if b then insert r bs else r\n\nremove :: Tree -> [Bool] -> Tree\nremove _ [] = Leaf\nremove (Node l r c) (b:bs) =\n if c == 1 then Leaf else Node l' r' (c-1)\n where\n l' = if b then l else remove l bs\n r' = if b then remove r bs else r\n\nquery :: Tree -> [Bool] -> [Bool]\nquery _ [] = []\nquery (Node l r c) (b:bs)\n | b && (l /= Leaf) = True:(query l bs)\n | not b && (r /= Leaf) = True:(query r bs)\n | l /= Leaf = b:(query l bs)\n | r /= Leaf = (not b):(query r bs)\n\nbools :: Int -> [Bool]\nbools x = map (x `testBit`) [31,30..0]\n\nint :: [Bool] -> Int\nint bs = sum $ zipWith (\\i b -> if b then bit i else 0) [31,30..0] bs\n\nmain = do\n q <- readLn\n qs <- replicateM q ((\\[a, b] -> (a, read b)) . words <$> getLine)\n\n let\n handle :: Tree -> [(String, Int)] -> [Int]\n handle t [] = []\n handle t ((\"+\", x):qs) = handle t' qs\n where t' = insert t (bools x)\n handle t ((\"-\", x):qs) = handle t' qs\n where t' = remove t (bools x)\n\n handle t ((\"?\", x):qs) = (int $ query t (bools x)):(handle t qs)\n\n t = insert Leaf (bools 0)\n\n putStr $ unlines $ map show $ handle t qs\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as M\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.Read as T\nimport qualified Data.Text.IO as T\nimport Data.Either (either)\nimport Data.Bits (xor)\nimport Control.Monad (replicateM, foldM, foldM_)\n\n\nparseInt :: Text -> Int\nparseInt = either (error \"wtf\") fst . T.decimal . T.stripStart\n\ndata Query =\n Add {-# UNPACK #-} !Int\n | Erase {-# UNPACK #-} !Int\n | MXor {-# UNPACK #-} !Int deriving (Eq, Ord, Read, Show)\n\nqGetInt :: Query -> Int\nqGetInt q =\n case q of\n Add i -> i\n Erase i -> i\n MXor i -> i\n\nparseQ :: Text -> Query\nparseQ t = \n let n = parseInt (T.tail t)\n in case T.head t of\n '+' -> Add n\n '-' -> Erase n\n _ -> MXor n\n\nrunQ :: IntMap Int -> Query -> (IntMap Int, Maybe Int)\nrunQ m q =\n case q of\n Add n -> (M.insertWith (+) n 1 m, Nothing)\n Erase n -> (M.update (\\i -> if i > 1 then Just (i-1) else Nothing) n m, Nothing)\n MXor n -> (m, Just (M.foldlWithKey' (\\a k _-> max a (xor n k)) 0 m))\n\n\nmain0 :: IO ()\nmain0 = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n ms <- foldM (\\m q -> (\\(m', mi) -> maybe (return ()) (T.putStrLn . T.pack . show) mi >> return m') (runQ m q)) M.empty qs \n return ()\n\ndata Trie =\n Empty\n | Leaf {-# UNPACK #-} !Int\n | Node {-# UNPACK #-} !Trie {-# UNPACK #-} !Trie\n deriving (Show, Eq, Ord)\n\nisEmpty :: Trie -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\ndigits :: Int -> Int -> [Int]\ndigits base n0 = go n0 []\n where\n go n acc\n | n < base = n:acc\n | otherwise = let (q, r) = quotRem n base\n in go q (r:acc)\n\nundigits :: Int -> [Int] -> Int\nundigits base ds = go (reverse ds) 1 0\n where\n go ds p n =\n case ds of\n [] -> n\n d:ds' -> go ds' (p*base) (n + d*p)\n \ndigitsPad :: Int -> Int -> Int -> [Int]\ndigitsPad sz base n = replicate (sz - length ds) 0 ++ ds\n where\n ds = digits base n\n\nadd :: Int -> Trie -> Trie\nadd i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Empty) -> Leaf 1\n ([], Leaf n) -> Leaf (n+1)\n (0:ds', Empty) -> Node (go ds' Empty) Empty\n (1:ds', Empty) -> Node Empty (go ds' Empty)\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie add invariant failed\"\n\nerase :: Int -> Trie -> Trie\nerase i = go (digitsPad 32 2 i)\n where\n go ds t =\n case (ds, t) of\n ([], Leaf n) | n > 1 -> Leaf (n-1)\n | otherwise -> Empty\n (_, Empty) -> Empty\n (0:ds', Node l r) -> Node (go ds' l) r\n (1:ds', Node l r) -> Node l (go ds' r)\n _ -> error \"Trie erase invariant failed\"\n \n\n\nmaxXor :: Int -> Trie -> Maybe Int\nmaxXor i = go [] (digitsPad 32 2 i)\n where\n go o ds t =\n case (ds, t) of\n (_, Empty) -> Just i\n (_, Leaf n) -> Just (xor i . undigits 2 . reverse $ o)\n (d:ds', Node l r) | isEmpty l -> go (1:o) ds' r\n | isEmpty r -> go (0:o) ds' l\n | d == 0 -> go (1:o) ds' r\n | d == 1 -> go (0:o) ds' l\n _ -> error \"Trie invariant failed\"\n \n\nrunQuery :: Query -> Trie -> (Trie, Maybe Int)\nrunQuery q t =\n case q of\n Add i -> (add i t, Nothing)\n Erase i -> (erase i t, Nothing)\n MXor i -> (t, maxXor i t)\n\n\nmain :: IO ()\nmain = do\n qn <- fmap parseInt T.getLine\n qs <- replicateM qn (fmap parseQ T.getLine)\n foldM_ (\\t q -> (\\(t', mi) -> maybe (return ()) (T.putStrLn . T.pack . show . max (qGetInt q)) mi >> return t') (runQuery q t)) Empty qs \n"}], "src_uid": "add040eecd8322630fbbce0a2a1de45e"} {"source_code": "f [] = 0\nf ['1'] = 1\nf ('0':xs) = f xs\nf ('1':'0':xs) = 1 + f xs\nf ('1':xs) = 1 + f ('1':(drop (ones+1) xs))\n where ones = length $ takeWhile (=='1') xs\n\nmain = do\n line <- getLine\n print . f $ reverse line\n", "positive_code": [{"source_code": "calc :: String -> Int\ncalc str = go 0 str\n where\n go acc [] = acc\n go acc (d:ds) | d == '0' = go acc $ dropWhile (== '0') ds\n | d == '1' = case ds of\n [] -> acc+1\n ('0':ds') -> go (acc+1) ds'\n ('1':ds') -> go (acc+1) $ roundup ds\n roundup ds = case dropWhile (== '1') ds of\n [] -> \"1\"\n (d:ds') -> '1' : ds'\nmain :: IO ()\nmain = do\n line <- getLine\n putStrLn $ show $ calc $ reverse line\n"}], "negative_code": [], "src_uid": "b2bc51df4a2c05c56c211e8f33fe1b45"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- map (\\c -> read [c]) <$> getLine\n print $ solve as\n\nsolve :: [Integer] -> Integer\nsolve as = sum as''\n where\n as' = map (\\x -> x-1) as\n pref = scanl (+) 0 as'\n as'' =map ((\\ l -> (l * (l - 1)) `div` 2) . fromIntegral . length) ((group.sort) pref)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Data.Int\ngetBlocks :: Eq a => [a] -> [Int64]\ngetBlocks [] = []\ngetBlocks [_] = [1]\ngetBlocks (x : y : t) = let ret = getBlocks (y : t) in \n if x /= y\n then (1 : ret)\n else (head ret + 1 : tail ret)\nsolve :: [Int64] -> Int64\nsolve a = let prefixSum = scanl (+) 0 $ map pred a in\n let sortedPrefixSums = sort prefixSum in\n let blocks = getBlocks sortedPrefixSums in\n let countPairs x = (x * (x - 1)) `div` 2 in\n let pairsPerBlock = map countPairs blocks in\n sum pairsPerBlock\ndoCaseIO :: Int64 -> IO ()\ndoCaseIO 0 = return ()\ndoCaseIO t = do\n _ <- getLine -- ignore string length\n s <- getLine\n (putStrLn . show . solve . map (fromIntegral . digitToInt)) s\n doCaseIO (t - 1)\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int64\n doCaseIO t"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nsolve :: String -> Int64\nsolve digitsString = pairsCount\n where\n pairsCount = sum $ map (\\cnt -> (cnt * (cnt - 1)) `div` (2 :: Int64)) countGroups\n countGroups = map (\\group -> (fromIntegral $ length group) :: Int64) . group $ sort digitSums\n digitSums = scanl' (+) 0 digits\n digits = map (\\c -> (fromIntegral ((ord c) - (ord '0') - 1)) :: Int64) digitsString\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n digits <- (head . B8.words) <$> B8.getLine\n let answer = solve $ B8.unpack digits \n printf \"%s\\n\" $ show answer\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport qualified Data.Map as M\nimport Numeric\nimport Data.Char\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\ntype Input = [Int64]\ntype Output = Int64\n\nsolve :: String -> String\nsolve input = intercalate \"\\n\" formattedOutputs\n where\n _:xs = words input\n inputs = inputParser xs\n outputs = map solver inputs\n formattedOutputs = map outputFormatter outputs\n\ninputParser :: [String] -> [Input]\ninputParser [] = []\ninputParser (_:x:xs) = (readStr x):(inputParser xs)\n\nreadStr :: [Char] -> [Int64]\nreadStr = map (fromIntegral . Data.Char.digitToInt)\n\noutputFormatter :: Output -> String\noutputFormatter x = show x\n\ntype FoldState = (M.Map Int64 Int64, Int64)\n\nsolver :: Input -> Output\nsolver x = \n let\n sutr = map (\\x -> x - 1) x\n sutr :: [Int64]\n cumul = scanl (+) 0 sutr\n cumul :: [Int64]\n (_, answer) = foldl' folder (M.empty, 0) cumul\n in answer\n\nfolder :: FoldState -> Int64 -> FoldState\nfolder (mm, cur) x \n | M.null mm = (M.insert x 1 mm, cur)\n | otherwise = (M.insertWith (+) x 1 mm, cur + (M.findWithDefault 0 x mm) )\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- map (\\c -> read [c]) <$> getLine\n print $ solve as\n\nsolve :: [Int] -> Int\nsolve as = sum as''\n where\n as' = map (\\x -> x-1) as\n pref = scanl (+) 0 as'\n as'' =map ((\\ l -> (l * (l - 1)) `div` 2) . length) ((group.sort) pref)\n"}, {"source_code": "import Data.List\nimport Data.Char\ngetBlocks :: Eq a => [a] -> [Int]\ngetBlocks [] = []\ngetBlocks [_] = [1]\ngetBlocks (x : y : t) = let ret = getBlocks (y : t) in \n if x /= y\n then (1 : ret)\n else (head ret + 1 : tail ret)\nsolve :: [Int] -> Int\nsolve a = let prefixSum = scanl (+) 0 $ map pred a in\n let sortedPrefixSums = sort prefixSum in\n let blocks = getBlocks sortedPrefixSums in\n let countPairs x = (x * (x - 1)) `div` 2 in\n let pairsPerBlock = map countPairs blocks in\n sum pairsPerBlock\ndoCaseIO :: Int -> IO ()\ndoCaseIO 0 = return ()\ndoCaseIO t = do\n _ <- getLine -- ignore string length\n s <- getLine\n (putStrLn . show . solve . map digitToInt) s\n doCaseIO (t - 1)\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n doCaseIO t"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nsolve :: String -> Int64\nsolve digitsString = pairsCount\n where\n pairsCount = sum $ map (\\cnt -> (cnt * (cnt - 1)) `div` 2) countGroups\n countGroups = map (\\group -> (fromIntegral $ length group) :: Int64) . group $ sort digitSums\n digitSums = (scanl' (\\x y -> x + y - 1) 0 digits)\n digits = map (\\c -> (ord c) - (ord '0')) digitsString\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n digits <- B8.getLine\n let answer = solve $ B8.unpack digits \n printf \"%lld\\n\" answer\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport Data.Int\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nsolve :: String -> Int64\nsolve digitsString = pairsCount\n where\n pairsCount = sum $ map (\\cnt -> (cnt * (cnt - 1)) `div` (2 :: Int64)) countGroups\n countGroups = map (\\group -> (fromIntegral $ length group) :: Int64) . group $ sort digitSums\n digitSums = scanl' (+) 0 digits\n digits = map (\\c -> (ord c) - (ord '0') - 1) digitsString\n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n n <- readIntB8 <$> B8.getLine\n digits <- B8.getLine\n let answer = solve $ B8.unpack digits \n printf \"%s\\n\" $ show answer\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport qualified Data.Map as M\nimport Numeric\nimport Data.Char\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\ntype Input = [Int]\ntype Output = Int\n\nsolve :: String -> String\nsolve input = intercalate \"\\n\" formattedOutputs\n where\n _:xs = words input\n inputs = inputParser xs\n outputs = map solver inputs\n formattedOutputs = map outputFormatter outputs\n\ninputParser :: [String] -> [Input]\ninputParser [] = []\ninputParser (_:x:xs) = (readStr x):(inputParser xs)\n\nreadStr :: [Char] -> [Int]\nreadStr = map (Data.Char.digitToInt)\n\noutputFormatter :: Output -> String\noutputFormatter x = show x\n\ntype FoldState = (M.Map Int Int, Int)\n\nsolver :: Input -> Output\nsolver x = \n let\n sutr = map (\\x -> x - 1) x\n sutr :: [Int]\n cumul = scanl (+) 0 sutr\n cumul :: [Int]\n (_, answer) = foldl' folder (M.empty, 0) cumul\n in answer\n\nfolder :: FoldState -> Int -> FoldState\nfolder (mm, cur) x \n | M.null mm = (M.insert x 1 mm, cur)\n | otherwise = (M.insertWith (+) x 1 mm, cur + (M.findWithDefault 0 x mm) )\n"}], "src_uid": "e5244179b8ef807b1c6abfe113bd4f3b"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n if n > m + 1 || m > 2*(n+1) then\n print $ -1\n else if n == m + 1 then\n putStrLn $ take (n+m) $ cycle \"01\"\n else if m > 2 * n then\n putStrLn $ take (n+m) $ cycle \"110\"\n else do\n let k = m - n\n putStrLn $ take (3*k) (cycle \"110\") ++ take (m+n - 3*k) (cycle \"10\")\n\n", "positive_code": [{"source_code": "main = interact $ f . map read . words\nf [0, 0] = \"\"\nf [1, 0] = \"0\"\nf [n, m]\n | n > m + 1 || m > n * 2 + 2 = \"-1\"\n | m > n * 2 = \"1\" ++ f [n, m - 1]\n | m == n * 2 = \"011\" ++ f [n - 1, m - 2]\n | otherwise = \"01\" ++ f[n - 1, m - 1]"}, {"source_code": "main = interact $ g.map read .words.head.lines\n\ng (x:y:[])\n | a == \"-1\" && b == \"-1\" = a\n | a == \"-1\" = b\n | otherwise = a\n where a = f x y [] 0\n b = f x y [] 1\nf 0 0 ans st = ans\nf x y ans st\n | x < 0 || y < 0 = \"-1\"\n | x - y >= -1 && st == 1 = f x (y-1) ('1':ans) 0\n | st == 1 = f x (y-2) ('1':'1':ans) 0\n | otherwise = f (x - 1) y ('0':ans) 1\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nmain = B.putStrLn . B.concat . solve . map read . words =<< getLine\nsolve [n,m] | n > m+1 || m > 2*n+2 = [B.pack \"-1\"]\n | m == 2*n+2 = B.pack \"11\" : go n (m-2)\n | m == 2*n+1 = B.pack \"1\" : go n (m-1)\n | n == m+1 = go (n-1) m ++ [B.pack \"0\"]\n | otherwise = go n m\ngo n m = replicate (m-n) (B.pack \"011\") ++ replicate (2*n-m) (B.pack \"01\")\n"}, {"source_code": "import Data.List\n\nmain=interact$f.map read.words\nf[m,n]\n | n < m-1 || 2*(m+1) < n = \"-1\"\n | n+1 == m = take (n+m) $ '0':cycle\"10\"\n | n == m = take (n+m) $ cycle \"10\"\n | 2*(m+1) == n = take (n+m) $ cycle \"110\"\n | r <- n `mod`(m+1) = intercalate \"0\" $ replicate r \"11\" ++ replicate (m+1-r) \"1\"\n"}], "negative_code": [{"source_code": "main = interact $ g.map read .words.head.lines\n\ng (x:y:[])\n | x >= y = f x y [] 0\n | otherwise = f x y [] 1\n\nf 0 0 ans st = ans\nf x y ans st\n | x < 0 || y < 0 = \"-1\"\n | x >= y && st == 1 = f x (y-1) ('1':ans) 0\n | st == 1 = f x (y-2) ('1':'1':ans) 0\n | otherwise = f (x - 1) y ('0':ans) 1\n"}, {"source_code": "main = interact $ f . map read . words\nf [1, 0] = \"0\"\nf [n, m]\n | n > m + 1 || m > n * 2 + 2 = \"-1\"\n | m > n * 2 = \"1\" ++ f [n, m - 1]\n | m == n * 2 = \"011\" ++ f [n - 1, m - 2]\n | otherwise = \"01\" ++ f[n - 1, m - 1]"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,m) <- readIntPair\n if n > m + 1 || m > 2*(n+1) then\n print $ -1\n else if n == m + 1 then\n putStrLn $ take (n+m) $ cycle \"01\"\n else if m == 2 * (n+1) then\n putStrLn $ take (n+m) $ cycle \"110\"\n else do\n let k = m - n\n putStrLn $ take (3*k) (cycle \"110\") ++ take (m+n - 3*k) (cycle \"10\")\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nmain = B.putStrLn . B.concat . solve . map read . words =<< getLine\nsolve [n,m] | n > m+1 || m > 2*n+2 = [B.pack \"-1\"]\n | m == 2*n+2 = B.pack \"11\" : go n (m-2)\n | n == m+1 = go (n-1) m ++ [B.pack \"0\"]\n | otherwise = go n m\ngo n m = replicate (m-n) (B.pack \"011\") ++ replicate (2*n-m) (B.pack \"01\")\n"}], "src_uid": "854c561539596722b1dbc8f99cbdca78"} {"source_code": "calc :: [String] -> ([String], Bool)\ncalc [] = ([], False)\ncalc (['O','O','|',c,d]:rest) = ((\"++|\" ++ [c , d]):rest, True)\ncalc ([a,b,'|','O','O']:rest) = (([a, b] ++ \"|++\"):rest, True)\ncalc (row:rest) = (row:next, b)\n where\n (next, b) = calc rest\n\nprocess :: String -> String\nprocess str =\n let (header : body) = lines str\n n = read header\n bus = take n body\n (newBus, can) = calc bus\n in\n if can then \"YES\\n\" ++ unlines newBus else \"NO\"\n\nmain :: IO ()\nmain = interact process", "positive_code": [{"source_code": "import Control.Monad\n\n-- plain string for output\nnewtype PlainString = PlainString String\ninstance Show PlainString where\n show (PlainString s) = s\n\nmain :: IO()\nmain = do \n\tinput <- getLine\n\tlet rows = read input :: Int\n\tbus <- replicateM (rows) getLine\n\tlet found = findPlace bus 0\n\t\n\tif found >= 0 \n\t\tthen do\n\t\t\tprintPlain \"YES\"\n\t\t\tprintPlace bus 0 found\n\t\telse printPlain \"NO\"\n\nprintPlain :: [Char] -> IO()\nprintPlain str = print (PlainString str)\n\nprintSit :: [Char] -> IO()\nprintSit curRow\n\t| curRow !! 0 == 'O' && curRow !! 1 == 'O' = printPlain (\"++\" ++ (drop 2 curRow))\n\t| curRow !! 3 == 'O' && curRow !! 4 == 'O' = printPlain ((take 3 curRow) ++ \"++\")\n\nprintPlace :: [[Char]] -> Int -> Int -> IO()\nprintPlace [] _ _ = return ()\nprintPlace (curRow:rest) curRowNum sitNum\n\t| curRowNum == sitNum = do\n\t\t\t\tprintSit curRow\n\t\t\t\tprintPlace rest (curRowNum + 1) sitNum\n\t| otherwise = do \tprintPlain curRow\n\t\t\t\tprintPlace rest (curRowNum + 1) sitNum\n\nfindPlace :: [[Char]] -> Int -> Int\nfindPlace [] _ = -1\nfindPlace (curRow:rest) curRowNum\n\t| curRow !! 0 == 'O' && curRow !! 1 == 'O' = curRowNum\n\t| curRow !! 3 == 'O' && curRow !! 4 == 'O' = curRowNum\n\t| otherwise = findPlace rest (curRowNum + 1)\n"}, {"source_code": "import Control.Monad\nimport Data.List (isInfixOf)\n\nrep_f :: [Char] -> [Char]\nrep_f ('O':'O':x) = ['+', '+']++x\nrep_f (c:x) = c:rep_f x\nrep_f [] = []\n\nprint_f :: [[Char]] -> [Bool] -> Bool -> IO ()\nprint_f (h:t) (True:t2) True = do\n putStrLn (rep_f h)\n print_f t t2 False\nprint_f (h:t) (_:t2) is_f = do\n putStrLn h\n print_f t t2 is_f\nprint_f _ _ _ = return ()\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n seats <- replicateM (read n_s) getLine\n let free = (map (\\x -> isInfixOf \"OO\" x) seats)\n if foldr (||) False free\n then do\n putStrLn \"YES\"\n print_f seats free True\n else putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tseats <- getContents\n\tlet\n\t\tres = solve seats\n\t\tok = isJust res\n\tputStrLn $ which \"YES\" \"NO\" ok\n\twhen ok $ do\n\t\tputStrLn $ fromJust res\n\nsolve [c] = Nothing\nsolve ( c1 : c2 : s )\n\t| c1 == 'O' && c2 == 'O' = Just $ \"++\" ++ s\n\t| otherwise = ( c1 : ) <$> solve ( c2 : s )\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nreplace a b t = f t []\n where\n f t r =\n case stripPrefix a t of\n Nothing -> f (tail t) $ (head t):r\n Just t' -> (reverse r) ++ b ++ t'\n\nmain = do\n getLine\n s <- getContents\n\n if \"OO\" `isInfixOf` s\n then do\n putStrLn \"YES\"\n putStr $ replace \"OO\" \"++\" s\n else\n putStrLn \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> solve =<< (forM [1..read n] $ \\i-> C.splitWith (=='|') <$> C.getLine)\nsolve xs = mapM_ (\\as->C.putStrLn $ C.intercalate (C.singleton '|') as) $ filter (/=[]) $ slv1 $ break (\\a-> a==C.pack \"OO\" || a==C.pack \"OO\\r\") $ concat xs\nslv1 (xs,[]) =[[C.pack \"NO\"]]\nslv1 (xs,ys)= let zs = xs++[C.pack \"++\"]++tail ys in [[C.pack \"YES\"]]++zipWith (\\a b -> if a `mod` 2 /=0 then b else [] ) [1..] (zipWith (\\a b -> a:b:[]) zs (tail zs))"}, {"source_code": "import Control.Monad\n\nmain = getLine >>= getLines . read >>= putStrLn . decide . parse\n\ngetLines :: Int -> IO [String]\ngetLines n = mapM (\\_ -> getLine) [1..n]\n\nparse :: [String] -> ([String], Bool)\nparse rows = foldr parse' ([], False) rows\n where parse' row (rows, True) = (row:rows, True)\n parse' ('O':'O':xs) (rows, _) = (('+':'+':xs):rows, True)\n parse' (a:b:_:\"OO\") (rows, _) = ((a:b:\"|++\"):rows, True)\n parse' row (rows, _) = (row:rows, False)\n\ndecide :: ([String], Bool) -> String\ndecide (_, False) = \"NO\"\ndecide (rows, _) = unlines $ \"YES\":rows"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nsolve :: [String] -> Maybe [String]\nsolve [] = Nothing\nsolve bus @ (f : other)\n | \"OO\" `isSuffixOf` f = Just ((take 3 f ++ \"++\") : other)\n | \"OO\" `isInfixOf` f = Just ((\"++\" ++ drop 2 f) : other)\n | otherwise = (f :) <$> solve other \n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n bus <- replicateM n getLine\n let answer = unlines . (\"YES\" :) <$> solve bus\n printf \"%s\" $ fromMaybe \"NO\" answer"}, {"source_code": "import Control.Monad(replicateM)\nimport Data.Functor ((<$>))\n\nsolve :: [String] -> Maybe [String]\nsolve [] = Nothing\nsolve (s:t)\n | take 2 s == \"OO\" = Just ((\"++\" ++ drop 2 s) : t)\n | drop 3 s == \"OO\" = Just ((take 3 s ++ \"++\") : t)\n | otherwise = (s :) <$> solve t\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n s <- replicateM n getLine\n case solve s of\n Just s' -> do\n putStrLn \"YES\"\n putStr (unlines s')\n Nothing ->\n putStrLn \"NO\"\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\n\nprocess2::String->(String,Int)\nprocess2 s | take 2 s ==\"OO\" = (\"++\" ++ drop 2 s,1)\n | drop 3 s ==\"OO\" = (take 3 s ++ \"++\" ,1)\n | otherwise = (s,0)\n\nprocess1::[String]->[String]\nprocess1 s = s3\n where s1 = map process2 s\n s2 = length $ takeWhile (\\z-> snd z <1) s1\n s3 = (take (s2+1) (map fst s1)) ++ (drop (s2+1) s)\n\nprocess::[String]->[String]\nprocess s | x==[] && y==[] = [\"NO\"]\n | otherwise = [\"YES\"] ++ ( process1 s)\n where x = take 1 $ filter (\\z-> take 2 z ==\"OO\" ) s\n y = take 1 $ filter (\\z-> drop 3 z ==\"OO\" ) s\n\n\n\n\nmain = do\n getLine\n s<- lines <$> getContents\n mapM_ putStrLn $ process s\n"}, {"source_code": "module Main where\n\ncheckRow :: (Bool, [String]) -> String -> (Bool, [String])\ncheckRow (False, ys) ('O':'O':'|':a:b:\"\") = (True, ys ++ ['+':'+':'|':a:b:\"\"])\ncheckRow (False, ys) (a:b:'|':'O':'O':\"\") = (True, ys ++ [a:b:'|':'+':'+':\"\"])\ncheckRow (b, ys) s = (b, ys ++ [s])\n\nrender :: (Bool, [String]) -> String\nrender (True, ys) = \"YES\\n\" ++ unlines ys\nrender (False, _) = \"NO\"\n\nsolve :: String -> String\nsolve input = let\n (header:body) = lines input\n n = read header\n ys = take n body\n in render $ foldl checkRow (False, []) ys\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\n\nmodule Main where\n\nimport Control.Monad\nimport Data.List (intercalate)\n\ncheckRow :: (Bool, [String]) -> String -> (Bool, [String])\ncheckRow (False, ys) ('O':'O':'|':a:b:\"\") = (True, ys ++ ['+':'+':'|':a:b:\"\"])\ncheckRow (False, ys) (a:b:'|':'O':'O':\"\") = (True, ys ++ [a:b:'|':'+':'+':\"\"])\ncheckRow (b, ys) s = (b, ys ++ [s])\n\nrender :: (Bool, [String]) -> String\nrender (False, _) = \"NO\"\nrender (True, ys) = \"YES\\n\" ++ intercalate \"\\n\" ys\n\nsolve :: [String] -> String\nsolve ys = render $ foldl checkRow (False, []) ys\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- replicateM n getLine\n putStrLn $ solve xs\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n considerSeats :: String -> (Bool, Bool)\n considerSeats ('O':'O':_) = (True, False)\n considerSeats (_:_:'|':'O':'O':_) = (False, True)\n considerSeats _ = (False, False)\n\n transform :: (Bool, Bool) -> String -> String\n transform (True, False) (a:b:s) = '+':'+':s\n transform (False, True) (a:b:s) = a:b:\"|++\"\n\n reshow :: Bool -> [((Bool, Bool), String)] -> [String] -> [String]\n reshow _ [] accumulator = accumulator\n reshow True ((_, s):xs) accumulator = reshow True xs (s:accumulator)\n reshow False ((pred@(True, False), s):xs) accumulator = reshow True xs ((transform pred s):accumulator)\n reshow False ((pred@(False, True), s):xs) accumulator = reshow True xs ((transform pred s):accumulator)\n reshow False ((pred@(False, False), s):xs) accumulator = reshow False xs (s:accumulator)\n\n hasTrue :: (Bool, Bool) -> Bool\n hasTrue (False, False) = False\n hasTrue _ = True\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n seats <- readMultilineInput n return\n let consideredSeats = considerSeats `map` seats\n hasAns = any hasTrue consideredSeats\n ans = consideredSeats `zip` seats\n action = case hasAns of\n False -> putStrLn \"NO\"\n True -> do\n putStrLn \"YES\"\n mapM_ putStrLn $ reverse $ reshow False ans []\n -- putStrLn $ show ans\n action\n"}, {"source_code": "import Control.Monad( replicateM)\nimport Data.List( intercalate, elemIndex)\nimport Data.Maybe( fromJust)\nmain = do\n nmRows <- readLn\n let rowseat = getLine >>= return . (read::String->Rowseat)\n\trowseat::IO Rowseat\n rowseatS <- replicateM nmRows rowseat\n let tryshit::Pairseat->Pairseat\n\ttryshit ps = case ps of\n\t\t Empty -> OK\n\t\t ps\t -> ps\n\ttryrow (Rowseat (lp,rp)) = Rowseat (tryshit lp, tryshit rp)\n\tresult = map tryrow rowseatS\n\tresultBusStr = intercalate \"\\n\" $ map show result\n\tcleanse str =\n\t let\n\t point = fromJust $ elemIndex '+' str\n\t (selectedPart, normalPart) = splitAt (point+2) str\n\t cleansed = map (\\c->if c=='+' then 'O' else c) normalPart\n\t in\n\t selectedPart++cleansed\n if elem '+' resultBusStr\n\tthen putStrLn \"YES\" >> putStr (cleanse resultBusStr)\n\telse putStr \"NO\"\n\n\ndata Pairseat = Empty | Full | LEmpty | REmpty | OK\ninstance Read Pairseat where\n readsPrec _ str =\n\ttryParse [(\"OO\",Empty), (\"OX\",LEmpty),\n\t\t (\"XO\",REmpty), (\"XX\",Full)]\n where\n\ttryParse [] = []\n\ttryParse ((attempt, result):xs) =\n\t if str == attempt\n\t\tthen [(result, [])]\n\t\telse tryParse xs\n\ninstance Show Pairseat where\n show Empty = \"OO\"\n show LEmpty = \"OX\"\n show REmpty = \"XO\"\n show Full = \"XX\"\n show OK = \"++\"\n\ndata Rowseat = Rowseat (Pairseat,Pairseat)\ninstance Read Rowseat where\n readsPrec _ str =\n\t[(Rowseat (read [str!!0,str!!1], read [str!!3,str!!4]), [])]\ninstance Show Rowseat where\n show (Rowseat (lp,rp)) = show lp ++ \"|\" ++ show rp\n\n"}, {"source_code": "import System.IO (interact)\nimport Data.List (find, isInfixOf)\nimport Control.Applicative ((<$>), (<*>))\n\ng :: [String] -> Maybe [String]\ng [] = Nothing\ng (x:xs) = case x of\n 'O':'O':ys -> Just $ (\"++\" ++ ys):xs\n a:b:c:\"OO\" -> Just $ (a:b:c:\"++\"):xs\n _ -> (:) <$> Just x <*> g xs\n\nf :: [String] -> [String]\nf x = case y of\n Nothing -> \"NO\":[]\n Just xs -> \"YES\":xs\n where y = g x\n\nmain = do\n _ <- getLine\n interact (unlines . f . lines)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nprocess [] _ = putStrLn \"NO\"\n\nprocess (s:ss) y | q1 || q2 = do\n\t\t\t\tputStrLn \"YES\"\n\t\t\t\tmapM_ putStrLn $ reverse y\n\t\t\t\tputStrLn $ if q1 then (\"++\"++ (drop 2 s)) else ((take 3 s)++\"++\") \n\t\t\t\t\n\t\t\t\tmapM_ putStrLn $ ss \n\n\t\t | otherwise = process ss (s:y)\n\t where \tq1=isPrefixOf \"OO\" s\n\t \tq2=isSuffixOf \"OO\" s\n\n\n\nmain= do\n\t\tn<- read <$> getLine ::IO Int\n\t\ts<- replicateM n getLine \n\t\tprocess s []\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nfixLine [] = Nothing\nfixLine (l:ls) = case l of\n ['O','O', _ , _ , _ ] -> Just $ (\"++\"++ drop 2 l) : ls\n [ _ , _ , _ ,'O','O'] -> Just $ (take 3 l ++\"++\") : ls\n _ -> (l:) <$> (fixLine ls)\n\nmain = do\n n <- read <$> getLine\n lines <- replicateM n getLine\n case fixLine lines of\n Just x -> do putStrLn \"YES\"\n mapM_ putStrLn x\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List\n\nfindSeat :: [String] -> (Bool, [String])\nfindSeat [] = (False, [])\nfindSeat (row:rows)\n | lPair == \"OO\" = (True, (\"++|\" ++ rPair) : rows)\n | rPair == \"OO\" = (True, (lPair ++ \"|++\") : rows)\n | otherwise = (tr, row:rows')\n where\n (tr,rows') = findSeat rows\n [lPair,c:rPair] = groupBy (\\a b -> b /= '|') row\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let rows = lines contents\n let (tr,rows') = findSeat rows\n if tr\n then do\n putStrLn \"YES\"\n putStrLn . unlines $ rows'\n else putStrLn \"NO\""}, {"source_code": "main :: IO ()\nmain = do\n _:rows <- getLoS\n putStr $ unlines . printBus . busTransform $ rows\n\nrowTransform :: String -> (Bool, String)\nrowTransform ['O','O',a,b,c] = (True, ['+','+',a,b,c])\nrowTransform [a,b,c, 'O','O'] = (True, [a,b,c, '+', '+'])\nrowTransform row = (False, row)\n\nbusTransform :: [String] -> (Bool, [String])\nbusTransform [] = (False, [])\nbusTransform (x:xs) \n | success = (True, xTransformed : xs)\n | otherwise = (success', x : xs')\n where\n (success, xTransformed) = rowTransform x \n (success', xs') = busTransform xs\n\nprintBus :: (Bool, [String])->[String]\nprintBus (True, xs) = \"YES\" : xs\nprintBus (False, xs) = [\"NO\"]\n\n-- Boilerplate\ngetLoS :: IO [String]\ngetLoS = fmap lines getContents\n\ngetMoS :: IO [[String]]\ngetMoS = fmap (fmap words) getLoS\n\ntokenizeLtM :: [String] -> [[String]]\ntokenizeLtM = fmap words"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine\n interact $ unlines . render . busT . lines\n\nbusT :: [String] -> Maybe [String]\nbusT [] = Nothing\nbusT (x:xs) = case x of\n ['O','O',a,b,c] -> Just $ ['+','+',a,b,c]:xs\n [a,b,c, 'O','O'] -> Just $ [a,b,c, '+', '+']:xs\n _ -> fmap (x:) (busT xs)\n\nrender :: Maybe [String] -> [String]\nrender (Just xs) = \"YES\" : xs\nrender _ = [\"NO\"]"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List (isInfixOf)\n\nrep_f :: [Char] -> [Char]\nrep_f ('O':'O':x) = ['+', '+']++x\nrep_f (_:x) = rep_f x\nrep_f [] = []\n\nprint_f :: [[Char]] -> [Bool] -> Bool -> IO ()\nprint_f (h:t) (True:t2) True = do\n putStrLn (rep_f h)\n print_f t t2 False\nprint_f (h:t) (_:t2) is_f = do\n putStrLn h\n print_f t t2 is_f\nprint_f _ _ _ = return ()\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n seats <- replicateM (read n_s) getLine\n let free = (map (\\x -> isInfixOf \"OO\" x) seats)\n if foldr (||) False free\n then do\n putStrLn \"YES\"\n print_f seats free True\n else putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Data.List (isInfixOf)\n\nrep_f :: [Char] -> [Char]\nrep_f ('O':'O':x) = ['+', '+']++x\nrep_f (_:x) = rep_f x\nrep_f [] = []\n\nprint_f :: [[Char]] -> [Bool] -> Bool -> IO ()\nprint_f (h:t) (True:t2) True = do\n putStrLn (rep_f h)\n print_f t t2 False\nprint_f (h:t) (_:t2) is_f = do\n putStrLn h\n print_f t t2 is_f\nprint_f _ _ _ = return ()\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n seats <- replicateM (read n_s) getLine\n let free = (map (\\x -> isInfixOf \"OO\" x) seats)\n if foldr (||) False free\n then print_f seats free True\n else putStrLn \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n -> solve =<< (forM [1..read n] $ \\i-> C.splitWith (=='|') <$> C.getLine)\nsolve xs = mapM_ (\\as->C.putStrLn $ C.intercalate (C.singleton '|') as) $ filter (/=[]) $ slv1 $ break (==C.pack \"OO\") $ concat xs\nslv1 (xs,[]) =[[C.pack \"NO\"]]\nslv1 (xs,ys)= let zs = xs++[C.pack \"++\"]++tail ys in [[C.pack \"YES\"]]++zipWith (\\a b -> if a `mod` 2 /=0 then b else [] ) [1..] (zipWith (\\a b -> a:b:[]) zs (tail zs))"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\n\nprocess2::String->(String,Int)\nprocess2 s | take 2 s ==\"XX\" = (\"++\" ++ drop 2 s,1)\n | drop 3 s ==\"XX\" = (take 3 s ++ \"++\" ,1)\n | otherwise = (s,0)\n\nprocess1::[String]->[String]\nprocess1 s = s3\n where s1 = map process2 s\n s2 = length $ takeWhile (\\z-> snd z <1) s1\n s3 = (take (s2+1) (map fst s1)) ++ (drop (s2+1) s)\n\nprocess::[String]->[String]\nprocess s | x==[] && y==[] = [\"NO\"]\n | otherwise = [\"YES\"] ++ ( process1 s)\n where x = take 1 $ filter (\\z-> take 2 z ==\"XX\" ) s\n y = take 1 $ filter (\\z-> drop 3 z ==\"XX\" ) s\n\n\n\n\nmain = do\n getLine\n s<- lines <$> getContents\n mapM_ putStrLn $ process s\n"}, {"source_code": "module Main where\n\ncheckRow :: (Bool, [String]) -> String -> (Bool, [String])\ncheckRow (False, ys) ('O':'O':'|':a:b:\"\") = (True, ys ++ ['+':'+':'|':a:b:\"\"])\ncheckRow (False, ys) (a:b:'|':'O':'O':\"\") = (True, ys ++ [a:b:'|':'+':'+':\"\"])\ncheckRow (b, ys) s = (b, ys ++ [s])\n\nrender :: (Bool, [String]) -> String\nrender (True, ys) = \"YES\\n\" ++ unlines ys\nrender (False, _) = \"NO\"\n\nsolve :: String -> String\nsolve input = let\n (header:body) = lines input\n n = read header\n ys = take n body\n in render (False, ys)\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "import Control.Monad( replicateM)\nimport Data.List( intercalate)\nmain = do\n nmRows <- readLn\n let rowseat = getLine >>= return . (read::String->Rowseat)\n\trowseat::IO Rowseat\n rowseatS <- replicateM nmRows rowseat\n let tryshit::Pairseat->Pairseat\n\ttryshit ps = case ps of\n\t\t Empty -> Selected\n\t\t ps\t -> ps\n\ttryrow (Rowseat (lp,rp)) = Rowseat (tryshit lp, tryshit rp)\n\tresult = map tryrow rowseatS\n\tresultBusStr = intercalate \"\\n\" $ map show result\n if elem '+' resultBusStr\n\tthen putStrLn \"YES\" >> putStr resultBusStr\n\telse putStr \"NO\"\n\n\ndata Pairseat = Empty | Full | LEmpty | REmpty | Selected\ninstance Read Pairseat where\n readsPrec _ str =\n\ttryParse [(\"OO\",Empty), (\"OX\",LEmpty),\n\t\t (\"XO\",REmpty), (\"XX\",Full)]\n where\n\ttryParse [] = []\n\ttryParse ((attempt, result):xs) =\n\t if str == attempt\n\t\tthen [(result, [])]\n\t\telse tryParse xs\n\ninstance Show Pairseat where\n show Empty = \"OO\"\n show LEmpty = \"OX\"\n show REmpty = \"XO\"\n show Full = \"XX\"\n show Selected = \"++\"\n\ndata Rowseat = Rowseat (Pairseat,Pairseat)\ninstance Read Rowseat where\n readsPrec _ str =\n\t[(Rowseat (read [str!!0,str!!1], read [str!!3,str!!4]), [])]\ninstance Show Rowseat where\n show (Rowseat (lp,rp)) = show lp ++ \"|\" ++ show rp\n\n"}, {"source_code": "main :: IO ()\nmain = do\n _ <- getLine\n interact $ unlines . render . busT . lines\n\nbusT :: [String] -> Maybe [String]\nbusT [] = Nothing\nbusT (x:xs) = case x of\n ['O','O',a,b,c] -> Just $ ['O','O',a,b,c]:xs\n [a,b,c, 'O','O'] -> Just $ [a,b,c, '+', '+']:xs\n _ -> fmap (x:) (busT xs)\n\nrender :: Maybe [String] -> [String]\nrender (Just xs) = \"YES\" : xs\nrender _ = [\"NO\"]"}], "src_uid": "e77787168e1c87b653ce1f762888ac57"} {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int]\n where fn x = let Just (y,_) = B.readInt x in y\n\n\nmain = do\n n <- readLn :: IO Int\n a <- fmap sort readIntList\n print $ if even n then a!!((n `div` 2)-1) else a!!(n `div` 2)\n\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Maybe as M\nimport qualified Data.ByteString.Char8 as B\n\n\nf :: [String] -> [Int]\nf = map read\n\nmain = do\n\tgetLine\n\tt <- B.getLine\n\tlet l = map (fst . M.fromJust . B.readInt) $ B.words $ t\n\tlet q = sort $ l\n\tlet q2 = if odd (length q)\n\t\t\t\tthen q !! (length q `div` 2)\n\t\t\t\telse q !! (length q `div` 2 - 1)\n\tprint q2"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int]\n where fn x = let Just (y,_) = B.readInt x in y\n\nmain = do\n [n] <- readIntList\n a <- readIntList\n print $ if even n then a!!((n `div` 2)-1) else a!!(n `div` 2)\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int]\n where fn x = let Just (y,_) = B.readInt x in y\n\n\nmain = do\n n <- readLn :: IO Int\n a <- readIntList\n print $ if even n then a!!((n `div` 2)-1) else a!!(n `div` 2)\n"}, {"source_code": "import Data.List\n\nmain = do\n n <- readLn :: IO Int\n a <- fmap (sort . (map read) . words) getLine :: IO [Int]\n print $ a!!((n `div` 2)-1)"}, {"source_code": "import Data.List\n\nf :: [String] -> [Int]\nf = map read\ng :: (Num a) => [a] -> a\ng q = sum $ take 2 $ (drop (length q `div` 2 - 1) q)\n\nmain = do\n\tgetLine\n\tt <- getLine\n\tlet q = map fromIntegral $ sort $ f $ words t :: [Double]\n\tlet q2 = if odd (length q)\n\t\t\t\tthen q !! (length q `div` 2)\n\t\t\t\telse\n\t\t\t\t\tg q/2\n\tprint $ round (subtract 0.00000000001 q2)\n"}, {"source_code": "calc x = round $ sum x / (fromIntegral . length $ x)\ntoNums = map read . words\n\nmain = do\n\tgetLine\n\tt <- getLine\n\tprint $ calc $ toNums t\n"}], "src_uid": "fa9cc3ba103ed1f940c9e80a7ea75f72"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Numeric.Natural\r\nimport Data.Maybe\r\n\r\n\r\n\r\nintNat :: Natural -> Int\r\nintNat = fromInteger . toInteger\r\n\r\nsolve :: Natural -> Natural -> Maybe [Natural]\r\nsolve n k\r\n\t| n <= 2*k = Nothing\r\n\t| otherwise = Just $ fmap (+1) $ fmap aux [0..(n-1)]\r\n\twhere\r\n\t\taux i\r\n\t\t\t| i == 0 = 0\r\n\t\t\t| i > 2*k = i\r\n\t\t\t| mod i 2 == 0 = i - 1\r\n\t\t\t| mod i 2 == 1 = i + 1\r\n\r\nshowR :: Maybe [Natural] -> String\r\nshowR (Just list) = foldr (\\i s -> show i ++ \" \" ++ s) [] list\r\nshowR Nothing = \"-1\"\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Natural\r\n\treplicateM (intNat t) $ do\r\n\t\t[n, k] <- getLine >>= return . (fmap read) . words :: IO [Natural]\r\n\t\tputStrLn $ showR $ solve n k \r\n\r\n", "positive_code": [{"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\ncombine [] b = b \r\ncombine a [] = a \r\ncombine (x:a) (y:b) = [x,y] ++ combine a b\r\n\r\nprintS = do \r\n [n,k]<-readInts \r\n if k + 1 > div (n+1) 2 then putStrLn\"-1\"\r\n else do \r\n let a = take (n - k) [1..n]\r\n b = reverse $ drop (n-k) [1..n]\r\n putStrLn $ printArray $ combine a b\r\n \r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS"}], "negative_code": [{"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Numeric.Natural\r\nimport Data.Maybe\r\n\r\n\r\n\r\nintNat :: Natural -> Int\r\nintNat = fromInteger . toInteger\r\n\r\nsolve :: Natural -> Natural -> Maybe [Natural]\r\nsolve n k\r\n\t| n < 2*k = Nothing\r\n\t| otherwise = Just $ fmap (+1) $ fmap aux [0..(n-1)]\r\n\twhere\r\n\t\taux i\r\n\t\t\t| i == 0 = 0\r\n\t\t\t| i > 2*k = i\r\n\t\t\t| mod i 2 == 0 = i - 1\r\n\t\t\t| mod i 2 == 1 = i + 1\r\n\r\nshowR :: Maybe [Natural] -> String\r\nshowR (Just list) = foldr (\\i s -> show i ++ \" \" ++ s) [] list\r\nshowR Nothing = \"-1\"\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Natural\r\n\treplicateM (intNat t) $ do\r\n\t\t[n, k] <- getLine >>= return . (fmap read) . words :: IO [Natural]\r\n\t\tputStrLn $ showR $ solve n k "}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Numeric.Natural\r\nimport Data.Maybe\r\n\r\n\r\n\r\nintNat :: Natural -> Int\r\nintNat = fromInteger . toInteger\r\n\r\nsolve :: Natural -> Natural -> Maybe [Natural]\r\nsolve n k\r\n\t| 2*k >= n = Nothing\r\n\t| otherwise = Just $ fmap (+1) $ fmap aux [0..(n-1)]\r\n\twhere\r\n\t\taux i\r\n\t\t\t| i == 0 = 0\r\n\t\t\t| 2*k >= i = i\r\n\t\t\t| i == (n-1) = n-1\r\n\t\t\t| mod i 2 == 0 = i - 1\r\n\t\t\t| mod i 2 == 1 = i + 1\r\n\r\nshowR :: Maybe [Natural] -> String\r\nshowR (Just list) = foldr (\\i s -> show i ++ \" \" ++ s) [] list\r\nshowR Nothing = \"-1\"\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Natural\r\n\treplicateM (intNat t) $ do\r\n\t\t[n, k] <- getLine >>= return . (fmap read) . words :: IO [Natural]\r\n\t\tputStrLn $ showR $ solve n k "}], "src_uid": "b4bb11ea4650ead54026453ea9a76f39"} {"source_code": "main = getLine >> fmap (map read . words) getLine >>= print . solve\nsolve :: [Int] -> Int\nsolve xs = length $ filter isSurprise lists\n where lists = map (\\n -> take n xs) [2..length xs]\nisSurprise :: [Int] -> Bool\nisSurprise xs = all (>current) previous || all (> getLine)\n where solve :: [Int] -> Int\n solve xs = length (mins xs) + length (maxes xs) - 2\n mins = scanWith min\n maxes = scanWith max\n scanWith f = map head . group . scanl1 f"}, {"source_code": "main = do \n getLine\n x <- getLine\n putStr (solve (map read (words x)))\n\nsolve:: [Integer] -> String \nsolve (x:xs) = show (result 0 x x xs)\nresult r min max x\n |x==[] = r\n |head x>max = result (r+1) min (head x) (tail x)\n |head x maxScore\n then 1\n else 0\n in (acc', minScore', maxScore')\n\nmain = do\n n <- liftM read getLine :: IO Int\n ss <- liftM ( map read . words ) getLine :: IO [Int]\n\n let\n (res, _, _) = foldl considerContest (-1, maxBound, minBound) ss\n\n putStrLn $ show res\n"}, {"source_code": "\nmain = do\n\tn<-getLine\n\trest<-getLine\n\tlet dat=words rest\n\tputStrLn $ show $ solve (tail (map read dat)) (read(head dat)) (read(head dat)) 0\n\nsolve::[Int]->Int->Int->Int->Int\nsolve [] _ _ count = count\nsolve (v:vs) mini maxi count | v > maxi = solve vs mini v (count+1)\n | v < mini = solve vs v maxi (count+1)\n | otherwise = solve vs mini maxi count"}, {"source_code": "solve [x] = 0\nsolve (x:xs) = (solve xs) + c where c = if (all (>x) xs || all (>do\n xs <- getLine>>=return . map (read :: String -> Int) . words\n print $ solve $ reverse xs"}, {"source_code": "module Main(main) where\nimport System.IO\nimport Data.List\n\nmain = interact real_main\nreal_main inp = \n\tlet (n:nmbs) = map (read::String->Int) . words $ inp\n\t (cnt, _, _) = foldl' (\\(n, mx, mn) x -> if x > mx then (n + 1, x, mn) else if x < mn then (n + 1, mx, x) else (n, mx, mn)) (0, head nmbs, head nmbs) nmbs\n\tin show cnt ++ \"\\n\"\n"}, {"source_code": "fu xs max min ans | null xs = ans | head xs > max = fu ys y min ans+1 | head xs < min = fu ys max y ans+1 | otherwise = fu ys max min ans\n where\n ys = tail xs\n y = head xs\nsolve :: (Integral a) => [a] -> a\nsolve xs = fu (tail xs) (xs !! 1) (xs !! 1) 0\nmain = interact $ show . solve . map read . words\n"}, {"source_code": "import Data.List\n\nfindAmazing :: [Int] -> Int\nfindAmazing [_] = 0\nfindAmazing xs \n | all (< (last xs)) (init xs) = 1 + findAmazing (init xs)\n | all (> (last xs)) (init xs) = 1 + findAmazing (init xs)\n | otherwise = findAmazing (init xs)\n \n\nmain = do\n n <- getLine\n inStr <- getLine\n let points = map (\\x -> read x :: Int) . words $ inStr\n print $ findAmazing points"}, {"source_code": "main = do\n getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let\n m1 = scanl1 max xs\n m2 = scanl1 min xs\n\n c1 = length $ filter (\\(a, b) -> a > b) $ zip (tail xs) m1\n c2 = length $ filter (\\(a, b) -> a < b) $ zip (tail xs) m2\n\n print $ c1 + c2\n"}, {"source_code": "import Data.List\n\nboolToInt :: Bool -> Int\nboolToInt num | num == True = 1\n | num == False = 0\n\nreadNumbers str = map readInt $ words str\n where readInt = read :: String -> Int \n\nrun numbers = sum [boolToInt (num < minim || num > maxim) |\n [num, minim, maxim] <- tail $ transpose [numbers, min_list, max_list]]\n-- $ zip min_list max_list]\n where\n lim = 10000\n min_list = scanl min lim numbers\n max_list = scanl max (-lim) numbers\n\nmain = do\n getLine\n numbers_str <- getLine\n putStrLn $ show $ run $ readNumbers numbers_str\n"}, {"source_code": "\n{-# LANGUAGE BangPatterns #-}\n\n(-->) = flip fmap\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve [a] = 0\nsolve (a:as) = go a a as 0\n where\n go min max [] !c = c\n go min max (a:as) c\n | a < min = go a max as (c+1)\n | a > max = go min a as (c+1)\n | otherwise = go min max as c\n\nmain = do\n n <- getLine --> read :: IO Int\n nums <- getLine --> words --> map read\n print $ solve nums\n\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\n(|>) x f = f x\n\nmain = interact process\n\nprocess contents = let\n ls = contents |> lines |> map words |> map (map read) :: [[Int]]\n in solve (ls !! 1) |> show\n \nsolve nums = solve' (head nums) (head nums) (tail nums)\n\nsolve' _ _ [] = 0\nsolve' minSoFar maxSoFar (x:xs)\n | x < minSoFar = 1 + solve' x maxSoFar xs\n | x > maxSoFar = 1 + solve' minSoFar x xs\n | otherwise = solve' minSoFar maxSoFar xs"}, {"source_code": "main = \n do\n n <- readLn :: IO Int\n s <- getLine \n let list = map read (words s) :: [Int]\n print (f (tail list) (head list) (head list) 0)\n \nf [] a b count = count\nf (x:xs) a b count = \n let f1 = max x a \n f2 = min x b \n count1 = if f1 == a then 0 else 1 \n count2 = if f2 == b then 0 else 1\n in f xs f1 f2 (count+count1+count2)"}, {"source_code": "main = interact $ show . solve . map read . words\n\nsolve (n:xss) = solve' (-1) (-1) xs 0 where\n xs = take n xss\n solve' (-1) (-1) (x:xs) 0 = solve' x x xs 0\n solve' _ _ [] k = k\n solve' mn mx (x:xs) k\n | x < mn = solve' x mx xs (k + 1)\n | x > mx = solve' mn x xs (k + 1)\n | otherwise = solve' mn mx xs k\n"}, {"source_code": "main = do\n str <- getLine\n let n = read str\n aux <- getLine\n let xs = map read $ words aux :: [Int]\n\n let solve = _solve 0 0 where\n _solve i ans\n | i == n = ans\n | i == 0 = _solve (i + 1) ans\n | otherwise = if (xs !! i > maximum (take i xs) || xs !! i < minimum (take i xs)) then _solve (i + 1) (ans + 1) else _solve (i + 1) ans\n\n print solve\n"}, {"source_code": "import Control.Applicative\n\nsolve :: [Int] -> Int\nsolve (x:xs) = solve' xs x x\n where solve' [] mn mx = 0\n solve' (x:xs) mn mx = let a = if mn > x then 1 else 0\n b = if mx < x then 1 else 0\n in a + b + solve' xs (min mn x) (max mx x)\n\nmain = do\n n <- getLine\n a <- map read <$> (words <$> getLine)\n print $ solve a\n"}, {"source_code": "main = getLine >> getLine >>= putStrLn . show . thrd . amazing . map read . words\n\namazing :: [Int] -> (Int,Int,Int) \namazing (x:xs) = foldl ( svfn ) (x,x,0) xs\n\t\t\nthrd (a,b,c) = c;\n\nsvfn (mx,mn,n) y = if y < mn \t\n\t\t\t\t\t\tthen (mx,y,n+1) \n\t\t\t\t\t\telse if y > mx \t\n\t\t\t\t\t\t\t\tthen (y,mn,n+1) \n\t\t\t\t\t\t\t\telse (mx,mn,n)\n\t\t\t\t\t\t"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve. tail.concat.map (map read.words). take 2. lines\nsolve :: [Integer]->String\nsolve (x:xs) = show $ last $ foldl (\\[bma,bmi,bre] a->if a>bma then [a,bmi,bre+1]\n else if a maximum bs) = solve bs + 1\n | (b < minimum bs) = solve bs + 1\n | otherwise = solve bs\n"}, {"source_code": "main = let solve (x:xs) = (let (_,_,z) = foldl (\\(a, b, c) y -> (max a y, min b y, c + (if (y > a) || (y < b) then 1 else 0)) ) (x,x,0) xs in z) in getLine >>= const (fmap (map read . words) getLine :: IO [Int]) >>= (putStrLn . show . solve)"}, {"source_code": "\nimport List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Int] -> Int\nsolve (x:xs) = solve' (x, x) 0 xs\n where\n solve' _ n [] = n\n solve' (a, b) n (x:xs)\n | x < a = solve' (x, b) (n+1) xs\n | b < x = solve' (a, x) (n+1) xs\n | otherwise = solve' (a, b) n xs\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= print . solve\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n _ <- getLine\n (x:xs) <- map read . words <$> getLine :: IO [Int]\n print $ cnt 0 x x xs\n\ncnt a _ _ [] = a\ncnt a m n (x:xs) = \n let nc = a + fromEnum (x > m) + fromEnum (x < n)\n nm = max m x\n nn = min n x\n in cnt nc nm nn xs"}, {"source_code": "\nsolve :: [Int] -> Int\nsolve (x:xs) = let (_, _, ans) = foldl playContest (x, x, 0) xs\n in ans\n where playContest (mn, mx, ans) x\n | mn > x = (x, mx, ans + 1)\n | mx < x = (mn, x, ans + 1)\n | True = (mn, mx, ans)\n\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ntoD :: Int -> Double\ntoD = fromIntegral\n\nsolve1 :: (Int -> Int -> Bool) -> [Int] -> Int\nsolve1 _ [] = 0\nsolve1 f (h:t) = 1 + solve1 f (dropWhile (f h) t)\n\nsolve :: [Int] -> Int\nsolve = subtract 2 . liftM2 (+) (solve1 (<=)) (solve1 (>=))\n\nmain :: IO ()\nmain = getLine >> getIntList >>= print . solve\n"}, {"source_code": "module Main where\n\nreadi :: String -> Int\nreadi = read\n\nparseSolve x = initSolve $ map readi $ words x\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve _ _ [] = 0\nsolve xmin xmax (h:t)\n | h < xmin = 1 + (solve h xmax t)\n | h > xmax = 1 + (solve xmin h t)\n | otherwise = (solve xmin xmax t)\n\ninitSolve :: [Int] -> Int\ninitSolve (h:t) = solve h h t\n\nmain = do\n _ <- getLine\n line <- getLine\n print $ parseSolve line\n"}, {"source_code": "import Control.Applicative\n\nprocess [] _ _ a = a\nprocess (a:as) mi ma co | ama = process as mi a (co+1)\n | otherwise = process as mi ma co\n\n\n\nmain=do\n getLine\n q<- map read <$> words <$> getLine::IO [Int]\n print $ process q (head q) (head q) 0\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport qualified Data.Set as Set\nimport Control.Monad\nimport Control.Applicative\nmain = do\n n <- getLine\n xs <- map read . words <$> getLine\n print (solve xs) \n \nsolve (x:xs) = f xs t t 0\n where\n t = fromIntegral x\n f [] _ _ acc = acc\n f (x:xs) min max acc\n | x < min = f xs x max (acc+1)\n | x > max = f xs min x (acc+1)\n | otherwise = f xs min max acc"}, {"source_code": "import Data.List (inits)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve xs = length $ filter id $ zipWith f (tail xs) (tail $ inits xs)\n where f y ys = y < minimum ys || maximum ys < y\n"}, {"source_code": "main = print . fst . foldl contest (-1,(minBound,maxBound :: Int)) .\n map read . tail . words =<< getContents\ncontest (a,(u,l)) s | s > u || s < l = (a+1,(max u s,min l s))\n | otherwise = (a,(u,l))\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/155/A\n\nimport Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\namazing :: (Int -> Int -> Bool) -> [Int] -> Int\namazing _ [] = 0\namazing f (h:t) = 1 + amazing f (dropWhile (f h) t)\n\nsolve :: [Int] -> Int\nsolve = subtract 2 . liftM2 (+) (amazing (<=)) (amazing (>=))\n\nmain :: IO ()\nmain = getLine >> getIntList >>= print . solve\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do _ <- getLine\n xs <- map read . words <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xxs@(x:xs) = fst $ foldl' f (0,(x,x)) xs\n\nf :: (Int,(Int,Int)) -> Int -> (Int,(Int,Int))\nf (i,(x,y)) z\n | z < x = (i+1,(z,y))\n | y < z = (i+1,(x,z))\n | otherwise = (i,(x,y))"}, {"source_code": "main = interact $ show . func . map read . tail . words\n\nfunc :: [Int] -> Int\nfunc (x:xs) = ct (x,x) xs \n\nct (a,b) (x:xs) = (if x < a || x > b then 1 else 0) + ct (minimum [a,x], maximum [b,x]) xs\nct _ _ = 0"}, {"source_code": "import Control.Applicative\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve [] _ _ = 0\nsolve (a:as) mn mx\n | mn > a = 1 + solve as a mx\n | mx < a = 1 + solve as mn a\n | otherwise = solve as mn mx\n\nmain = do\n n <- getLine\n (a:as) <- map read <$> (words <$> getLine)\n print $ solve as a a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n\nprocess _ _ [] n = n\nprocess a b (c:cs) n | cb = process a c cs (n+1)\n\t\t | otherwise = process a b cs n\nmain=do\t \n\tgetLine \n\ts<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine ::IO [Integer]\n\tprint $ process (head s) ( head s) (tail s) 0\n\t "}, {"source_code": "{-\nA. I_love_%username%\n=====================\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nVasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.\n\nOne day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number \u2014 the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).\n\nVasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.\n\nInput\n------\nThe first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of contests where the coder participated.\n\nThe next line contains n space-separated non-negative integer numbers \u2014 they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.\n\nOutput\n------\nPrint the single number \u2014 the number of amazing performances the coder has had during his whole history of participating in the contests.\n\nSample test(s)\n---------------\ninput\n5\n100 50 200 150 200\noutput\n2\n\ninput\n10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242\noutput\n4\n\nNote\n------\nIn the first sample the performances number 2 and 3 are amazing.\n\nIn the second sample the performances number 2, 4, 9 and 10 are amazing.\n\n-}\n\nimport Data.List (tails)\n\ncountAmazing :: [Int] -> Int\ncountAmazing xs = length $ filter (\\(y:ys) -> y > maximum ys || y < minimum ys) yys\n where yys = (takeWhile ((> 1) . length) . tails . reverse) xs\n\nmain = do \n input <- getContents\n let points = (map read . words . last . lines) input\n print $ countAmazing points\n\n"}, {"source_code": "\nmain::IO ()\nmain = do cs <- getContents\n (putStr . show . solve . parse) cs\n\n\nparse::String->[Int]\nparse s = map (\\x -> read x::Int) (words k)\n where \n [_,k] = lines s\n\nsolve_step::(Int,Int,Int)->Int->(Int,Int,Int)\nsolve_step (min,max,cnt) i\n | i < min = (i,max,cnt+1)\n | i > max = (min,i,cnt+1)\n | otherwise = (min,max,cnt)\n\nsolve :: [Int] -> Int\nsolve [] = 0;\nsolve (k:ks) = ret\n where \n (_,_,ret) = foldl solve_step (k,k,0) ks"}, {"source_code": "import Data.List\nmain = getLine >> getLine >>= putStrLn.show.solve.map read.words\n\nsolve :: [Int] -> Int\nsolve [one] = 0\nsolve many = sum $ map (flip calc many) [min, max]\n\ncalc f = pred.length.nub.scanl1 f\n"}, {"source_code": "process :: [Int] -> Int\nprocess xs = best + wrst\n where\n best = snd $ foldl (\\a@(ax,an) x -> if x > ax then (x,an+1) else a) (minBound,(-1)) xs\n wrst = snd $ foldl (\\a@(ax,an) x -> if x < ax then (x,an+1) else a) (maxBound,(-1)) xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs"}, {"source_code": "main = do\n\t_ <- getLine\n\tb_s <- getLine\n\tlet (b:bs) = (map read (words b_s)) :: [Int]\n\tputStrLn.show $ solve bs [b] [b]\n\t\nsolve [] (h:hs) (l:ls) = length (h:hs) + length (l:ls) - 2\nsolve (b:bs) (h:hs) (l:ls)\n\t| (b > h) = solve bs (b:h:hs) (l:ls)\n\t| (b < l) = solve bs (h:hs) (b:l:ls)\n\t| otherwise = solve bs (h:hs) (l:ls)"}, {"source_code": "countAmazing :: [Int] -> Int\ncountAmazing xs = count\n where (_, _, count) = foldl accumulator (maxBound :: Int, minBound :: Int, 0) xs\n\naccumulator :: (Int, Int, Int) -> Int -> (Int, Int, Int)\naccumulator (mi, ma, count) current = (mi', ma', count')\n where mi' = min mi current\n ma' = max ma current\n count' = count + fromEnum ((mi' < mi) /= (ma' > ma))\n\nsolve :: String -> String\nsolve = show . countAmazing . fmap read . tail . words\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "import Data.List\n\ncountAmazing :: [Int] -> Int\ncountAmazing xs = sum $ fmap (countMutations xs) [min, max]\n\ncountMutations :: [Int] -> (Int -> Int -> Int) -> Int\ncountMutations xs = pred . length . group . (`scanl1` xs)\n\nsolve :: String -> String\nsolve = show . countAmazing . fmap read . tail . words\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "\nsolve :: [Integer] -> Integer\nsolve (lh:lt) = \n third . subsolve $ lt\n where third (_, _, x) = x\n funk old@(mx, mn, ac) hd \n | hd > mx = (hd, mn, ac + 1)\n | hd < mn = (mx, hd, ac + 1)\n | otherwise = old\n subsolve = foldl funk (lh, lh, 0)\n\n\nmain = do\n _ <- getLine\n numbers <- getLine\n print $ solve (map read (words numbers))"}], "negative_code": [{"source_code": "import Control.Applicative\n\nmain = do\n n <- getLine\n xs <- map read . words <$> getLine\n print $ cnt 0 (-1) xs\n\ncnt a _ [] = a\ncnt a m (x:xs)\n | x > m = cnt (a+1) x xs\n | otherwise = cnt a m xs"}, {"source_code": "import Control.Applicative\n\nprocess [] _ _ a = a\nprocess (a:as) mi ma co | ama = process as mi a (co+1)\n | otherwise = process as mi ma co\n\n\n\nmain=do\n getLine\n q<- map read <$> words <$> getLine::IO [Int]\n print $ process q 100000 0 0\n"}, {"source_code": "main = print . fst . foldl contest (0,(minBound,maxBound :: Int)) .\n map read . tail . words =<< getContents\ncontest (a,(u,l)) s | s > u || s < l = (a+1,(max u s,min u l))\n | otherwise = (a,(u,l))\n"}, {"source_code": "main = interact $ show . func . tail . words\n\nfunc (x:xs) = ct (x,x) xs\n\nct (a,b) (x:xs) = (if x < a || x > b then 1 else 0) + ct (minimum [a,x], maximum [b,x]) xs\nct _ _ = 0"}], "src_uid": "a61b96d4913b419f5715a53916c1ae93"} {"source_code": "import Control.Applicative\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n board <- replicateM n $ getLine \n putStrLn $ solve board\n\nsolve :: [[Char]] -> String\nsolve b = if length invalidList >= 1 then \"NO\" else \"YES\"\n where\n checkList = map (filter $ within n) [[(x-1,y),(x+1,y),(x,y-1),(x,y+1)] | x <- [0..n-1], y <- [0..n-1]]\n countList = map (cnt b) checkList\n invalidList = filter (\\x -> (x `mod` 2) == 1) countList\n n = length b\n\ncnt :: [[Char]] -> [(Int,Int)] -> Int\ncnt b [] = 0\ncnt b ((x,y):lx) = c + (cnt b lx)\n where c = if ((b !! x) !! y) == 'o' then 1 else 0\n\nwithin :: Int -> (Int, Int) -> Bool\nwithin n (x, y) = (x >= 0) && (y >= 0) && (x <= n-1) && (y <= n-1)\n", "positive_code": [{"source_code": "-- from submiession by qqz003 http://codeforces.com/contest/462/submission/7685448\n\n{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Maybe (mapMaybe)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n\nmain :: IO ()\nmain = LC.interact $ LC.pack . solve . map (map (\\x -> if x=='o' then 1 else 0)) . tail . map LC.unpack . LC.words\n\nsolve :: [[Int]] -> String\nsolve a = if (all even transform) then \"YES\" else \"NO\"\n where\n transform = zipWith (+) (concat . map add $ a) (concat . L.transpose . map add $ L.transpose a)\n \nadd a = zipWith (+) (tail a ++ [0]) (0 : init a)"}, {"source_code": "-- from submiession by qqz003 http://codeforces.com/contest/462/submission/7685448\n\n{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Maybe (mapMaybe)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n\nmain :: IO ()\nmain = LC.interact $ LC.pack . solve . map (map (\\x -> if x=='o' then 1 else 0)) . tail . map LC.unpack . LC.words\n\nsolve :: [[Int]] -> String\nsolve a = if (all even f3) then \"YES\" else \"NO\"\n where\n f1 = map add a\n f2 = map add $ L.transpose a\n f3 = zipWith (+) (concat f1) (concat $ L.transpose f2)\n \nadd a = zipWith (+) (tail a ++ [0]) (0 : init a)"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\nmain = interact $ getAns . map (map (\\x -> if x == 'o' then 1 else 0)) . tail . lines\n\nshiftL x = tail x ++ [0]\n\nshiftR x = 0 : init x\n\ncrossAdd x = zipWith (+) (shiftL x) (shiftR x)\n\ngetAns :: [[Int]] -> String\ngetAns x = let na = map crossAdd x;\n\t\t\t nb = map crossAdd $ transpose x;\n\t\t\t nc = zipWith (+) (concat na) $ (concat $ transpose nb);\n\t\t in if (all even nc) then \"YES\" else \"NO\"\n\n\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getLine\n\n let\n a' = listArray ((1, 1), (n, n)) $ concat a :: UArray (Int, Int) Char\n\n b = and [f i j | i <- [1..n], j <- [1..n]]\n where\n f i j = even $ length [(ii, jj) | (ii, jj) <- [(i+1,j), (i-1,j), (i,j-1), (i,j+1)], 1 <= ii && ii <= n && 1 <= jj && jj <= n, a'!(ii, jj) == 'o']\n\n putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\nimport Data.Maybe\n\ntype BString = B.ByteString\n\ntype Result = BString\n\ntype Matrix = [String]\n\nsolve :: Matrix -> Result\nsolve matrix\n | not $ symmetrical matrix = \"NO\"\n | not $ symmetrical $ reverse matrix = \"NO\"\n | otherwise = \"YES\"\n where symmetrical m = m == transpose m\n\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n matrix <- replicateM n parse\n return $ solve matrix\n-- return (matrix, transpose matrix)\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n say $ evalState process input\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\ninstance EIO [Int]\ninstance EIO String\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n scan = takeWhile (/='\\r') . B.unpack\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display [Int] where\n display = unwords . map display\n scan = unfoldr (B.readInt . B.dropWhile (== ' '))\n\ninstance Display [[Int]] where\n display = unlines . map display\n\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . lines\n\nsolve :: [String] -> Bool\nsolve (ns:cs) = all even [ length [ () | (di, dj) <- [(-1, 0), (1, 0), (0, -1), (0, 1)]\n , 0 <= i + di, i + di < n\n , 0 <= j + dj, j + dj < n\n , cs !! (i + di) !! (j + dj) == 'o' ]\n | i <- [0..n-1], j <- [0..n-1] ]\n where n = read ns\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Data.Array\nmain = do\n n <- readLn\n g <- listArray ((1,1),(n,n)) . concat . lines <$> getContents\n let neighbors (i,j) = filter (inRange (bounds g)) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]\n putStrLn $ if all (even . length . filter ((== 'o') . (g!)) . neighbors) (indices g) then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\n \n \n\n\n \nmain=do\t \n\tn<- read <$> getLine:: IO Int\n\ts<- concat . lines<$>getContents\n\tlet x = listArray ((1,1),(n,n)) s\n\tlet y = array((1,1),(n,n)) [((i,j),m)| i<-[1..n],j<-[1..n],let m =length $ filter (=='o') $ map (x!)$filter (\\z-> fst z >0 && fst z<=n && snd z >0 && snd z<=n) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]]\n\tlet z= length $ take 1 $ filter (odd) $ elems y\n\tputStrLn $ if z==1 then \"NO\" else \"YES\"\n"}], "negative_code": [{"source_code": "-- from submiession by qqz003 http://codeforces.com/contest/462/submission/7685448\n\n{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Maybe (mapMaybe)\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n\nmain :: IO ()\nmain = LC.interact $ LC.pack . show . solve . map (map (\\x -> if x=='o' then 1 else 0)) . tail . map LC.unpack . LC.words\n\nsolve :: [[Int]] -> String\nsolve a = if (all even f3) then \"YES\" else \"NO\"\n where\n f1 = map add a\n f2 = map add $ L.transpose a\n f3 = zipWith (+) (concat f1) (concat $ L.transpose f2)\n \nadd a = zipWith (+) (tail a ++ [0]) (0 : init a)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n a <- replicateM n getLine\n\n let\n a' = listArray ((1, 1), (n, n)) $ concat a :: UArray (Int, Int) Char\n\n b = and [f i j | i <- [1..n], j <- [1..n]]\n where\n f i j = if a'!(i, j) == 'o' then True else even $ length [(ii, jj) | (ii, jj) <- [(i+1,j), (i-1,j), (i,j-1), (i,j+1)], 1 <= ii && ii <= n && 1 <= jj && jj <= n, a'!(ii, jj) == 'o']\n\n putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Category ((>>>))\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport qualified Data.HashMap.Lazy as HM\nimport Data.List\nimport Data.Maybe\n\ntype BString = B.ByteString\n\ntype Result = BString\n\ntype Matrix = [String]\n\nsolve :: Matrix -> Result\nsolve matrix\n | symmetrical matrix = \"YES\"\n | otherwise = \"NO\"\n where symmetrical m = m == transpose m\n\n\n--process :: State Reader Result\nprocess = do\n n <- parse\n matrix <- replicateM n parse\n return $ solve matrix\n-- return (matrix, transpose matrix)\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n say $ evalState process input\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\ninstance EIO [Int]\ninstance EIO [Char]\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n scan = B.unpack\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display [Int] where\n display = unwords . map display\n scan = unfoldr (B.readInt . B.dropWhile (== ' '))\n\ninstance Display [[Int]] where\n display = unlines . map display\n\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE OverlappingInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\nimport Data.Maybe\n\ntype BString = B.ByteString\n\ntype Result = BString\n\ntype Matrix = [String]\n\nsolve :: Matrix -> Result\nsolve matrix\n | symmetrical matrix = \"YES\"\n | otherwise = \"NO\"\n where symmetrical m = m == transpose m\n\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n matrix <- replicateM n parse\n return $ solve matrix\n-- return (matrix, transpose matrix)\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n say $ evalState process input\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\ninstance EIO [Int]\ninstance EIO String\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n scan = takeWhile (/='\\r') . B.unpack\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display [Int] where\n display = unwords . map display\n scan = unfoldr (B.readInt . B.dropWhile (== ' '))\n\ninstance Display [[Int]] where\n display = unlines . map display\n\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . lines\n\nsolve :: [String] -> Bool\nsolve (ns:cs) = all even [ length [ () | (di, dj) <- [(-1, 0), (1, 0), (0, -1), (0, 1)]\n , 0 <= i + di, i + di < n\n , 0 <= j + dj, j + dj < n\n , cs !! i !! j == 'o' ]\n | i <- [0..n-1], j <- [0..n-1] ]\n where n = read ns\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}], "src_uid": "03fcf7402397b94edd1d1837e429185d"} {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n-- {-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\nsolve :: Int -> [Int] -> Maybe Int\nsolve n as = if finalCnt2 >= n \n then Just steps \n else Nothing\n where\n powers2 = L.iterate (*2) 2\n cntPowers2 x = L.length $ L.takeWhile (\\md -> x `mod` md == 0) powers2\n\n cnt2 :: Int\n cnt2 = L.sum . L.map cntPowers2 $ as\n\n cnts2 :: [(Int, Int)]\n cnts2 = L.sortOn ((* (-1)) . snd) $ L.map (\\i -> (i, cntPowers2 i)) [1..n]\n\n solve' :: ((), (Int, Int))\n solve' = flip MS.execStateT (0 :: Int, cnt2) $ do\n M.forM_ cnts2 $ \\(i, iCnt2) -> \n M.runMaybeT $ do\n (steps, cnt2) <- MS.get\n M.guard $ cnt2 < n\n M.guard $ iCnt2 > 0\n MS.modify (\\(steps, cnt2) -> (steps + 1, cnt2 + iCnt2))\n\n (_, (steps, finalCnt2)) = solve'\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = fromMaybe (-1) $ solve n as\n printf \"%d\\n\" answer\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\n\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\ntwoFactors :: Int -> Int\r\ntwoFactors v\r\n | even v = 1 + twoFactors (v `div` 2)\r\n | otherwise = 0\r\n\r\nsolve :: [Int] -> Int\r\nsolve vs = case dropWhile (\\(_, v) -> v < requiredTwoFactors) gainableTwoFactors of\r\n x:_ -> fst x\r\n _ -> -1\r\n where availableTwoFactors = sum $ map twoFactors vs\r\n requiredTwoFactors = max 0 $ length vs - availableTwoFactors\r\n gainableTwoFactors = [0..] `zip` scanl (+) 0 (reverse . sort . filter (/= 0) $ map twoFactors [1..length vs])\r\n -- Pair of (i, v): with i steps a gain of v two factors is possible.\r\n\r\nhandleTestCase :: IO ()\r\nhandleTestCase = do\r\n B.getLine\r\n vs <- map readInt . B.words <$> B.getLine\r\n print $ solve vs\r\n\r\nreadInt :: B.ByteString -> Int\r\nreadInt = maybe 0 fst . B.readInt\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberTestCases <- read <$> getLine\r\n replicateM_ numberTestCases handleTestCase"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\n\r\ntwoFactors :: Int -> Int\r\ntwoFactors v\r\n | even v = 1 + twoFactors (v `div` 2)\r\n | otherwise = 0\r\n\r\nsolve :: [Int] -> Int\r\nsolve vs = case dropWhile (\\(_, v) -> v < requiredTwoFactors) gainableTwoFactors of\r\n x:_ -> fst x\r\n _ -> -1\r\n where availableTwoFactors = sum $ map twoFactors vs\r\n requiredTwoFactors = max 0 $ length vs - availableTwoFactors\r\n gainableTwoFactors = [0..] `zip` scanl (+) 0 (reverse . sort . filter (/= 0) $ map twoFactors [1..length vs])\r\n -- Pair of (i, v): with i steps a gain of v two factors is possible.\r\n\r\nhandleTestCase :: IO ()\r\nhandleTestCase = do\r\n getLine\r\n vs <- map read . words <$> getLine\r\n print $ solve vs\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberTestCases <- read <$> getLine\r\n replicateM_ numberTestCases handleTestCase\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nintLogBase :: Int -> Int -> Int\r\nintLogBase b v\r\n | v >= b = 1 + intLogBase (2 * b) v\r\n | otherwise = 0\r\n\r\ntwoFactors :: Int -> Int\r\ntwoFactors v\r\n | even v = 1 + twoFactors (v `div` 2)\r\n | otherwise = 0\r\n\r\nsolve :: [Int] -> Int\r\nsolve vs = case dropWhile (\\(_, v) -> v < requiredTwoFactors) gainableTwoFactors of\r\n x:_ -> fst x\r\n _ -> -1\r\n where availableTwoFactors = sum $ map twoFactors vs\r\n requiredTwoFactors = max 0 $ length vs - availableTwoFactors\r\n gainableTwoFactors = [0..] `zip` scanl (+) 0 (reverse [1..intLogBase 2 (length vs)])\r\n -- Pair of (i, v): with i steps a gain of v two factors is possible.\r\n\r\nhandleTestCase :: IO ()\r\nhandleTestCase = do\r\n getLine\r\n vs <- map read . words <$> getLine\r\n print $ solve vs\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberTestCases <- read <$> getLine\r\n replicateM_ numberTestCases handleTestCase\r\n"}], "src_uid": "96f0df1c8e014229e5ef773789aa2205"} {"source_code": "import Data.List\n\nanswer :: Int -> [Int] -> Int\nanswer k xs = answer' k (reverse $ sort xs) where\n answer' k xs\n | (k >= l) = m\n | otherwise = m + answer' k (drop k xs) where\n l = length xs\n m = 2 * (head xs - 1)\n\nmain = do\n s <- getLine\n let (n:k:xs) = map read (words s)\n t <- getLine\n let ys = map read (words t)\n putStrLn (show (answer k ys))\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve (n:k:f) = \n let sf = (sortBy (flip compare) f)\n in (solve' sf k) * 2\n where\n solve' :: [Int] -> Int -> Int\n solve' [] _ = 0\n solve' (f:fs) i | i == k = f - 1 + (solve' fs 1)\n | otherwise = solve' fs (i + 1)\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,k) <- readIntPair\n fs <- readInts\n print $ solve n k fs\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k fs' = go fs where\n fs = reverse $ sort $ map pred fs'\n go [] = 0\n go l = 2 * head l + go l' where\n l' = drop k l\n\n \n"}, {"source_code": "import System.IO\nimport Data.List\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tlet k = head . tail . map read . words $ line1\n\tline2 <- getLine\n\tlet nums = map read . words $ line2\n\tprint . minTime k $ sortBy (flip compare) nums\n\nminTime :: Integer -> [Integer] -> Integer\nminTime _ [] = 0\nminTime k xs = 2 * (maxFloor - 1) + minTime k rest \n\twhere \n\t\t(batch, rest) = splitAt (fromIntegral k) xs\n\t\tmaxFloor = head batch"}, {"source_code": "-- Codeforces 472B\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n [n, k] <- fmap (map read . words) getLine :: IO [Int]\n people <- fmap (reverse . sort . map read . words) getLine :: IO [Int]\n print $ solve k people where\n solve k people\n | length people == 0 = 0\n | length people <= k = 2 * (maximum people - 1)\n | otherwise = 2 * (head people - 1) + solve k (drop k people) "}, {"source_code": "import Data.List (sortBy)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [[_, k], fs] = (2*) $ sum [ f | (i, f) <- zip [0..] $ map (subtract 1) $ sortBy (flip compare) fs, i `mod` k == 0 ]\nsolve _ = undefined\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs\n{-# INLINE slices #-}\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n fs <- map readInt.B.words <$> B.getContents\n print $ solve k fs\n\nsolve :: Int -> [Int] -> Int\nsolve k fs = foldl' (\\acc xs->2 * (maximum xs - 1) + acc) 0.slices k $ sortBy (flip compare) fs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nsolve k [] = 0\nsolve k (h : hs) = h * 2 + solve k (drop (k-1) hs)\n\nmain = do\n [n,k] <- getInts\n fs <- reverse . sort . map (subtract 1) <$> getInts\n let solution = [solve k fs]\n putStrLn $ unwords $ map show solution\n\n\n-- helper functions --\n\nreadInt = fst . fromJust . B.readInt\ngetInts = map readInt . B.words <$> B.getLine\n\nmemoArr :: Ix i => (i, i) -> (i -> r) -> (i -> r)\nmemoArr range f = f' where\n f' i\n | Arr.inRange range i = arr ! i\n | otherwise = f i\n arr = Arr.listArray range (map f (Arr.range range))\n\ndpArr :: Ix i => (i, i) -> ((i -> r) -> (i -> r)) -> (i -> r)\ndpArr ixs f = fix (memoArr ixs . f)\n"}, {"source_code": "import Data.List\n\nmain = interact $ show . sum.sl . map read . words\nsl (n:k:f) = map ((!!) $ reverse.sort $ map (\\x -> x*2-2) f) [0, k..n-1]"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Char\n\nchunkmax _ [] = []\nchunkmax n s = head s: ( chunkmax n (drop n s))\n\nmain= do\n\t[n,m] <-map read. words <$> getLine ::IO [Int]\n\ts<-reverse.sort.map read. words <$> getLine ::IO [Int]\n\tlet s1 = chunkmax m s\n\tprint $ 2*((sum s1) - (length s1))\n\t\n\t \n\t \n"}, {"source_code": "import Data.List\n\nmain = interact $ show . sum.sl . map read . words\nsl (n:k:f) = map ((!!) $ reverse.sort $ map (\\x -> x*2-2) f) [0, k..n-1]"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nsolve k [] = 0\nsolve k (h : hs) = h * 2 + solve k (drop (k-1) hs)\n\nmain = do\n [n,k] <- getInts\n fs <- reverse . sort <$> getInts\n let solution = [solve k fs]\n putStrLn $ unwords $ map show solution\n\n\n-- helper functions --\n\nreadInt = fst . fromJust . B.readInt\ngetInts = map readInt . B.words <$> B.getLine\n\nmemoArr :: Ix i => (i, i) -> (i -> r) -> (i -> r)\nmemoArr range f = f' where\n f' i\n | Arr.inRange range i = arr ! i\n | otherwise = f i\n arr = Arr.listArray range (map f (Arr.range range))\n\ndpArr :: Ix i => (i, i) -> ((i -> r) -> (i -> r)) -> (i -> r)\ndpArr ixs f = fix (memoArr ixs . f)\n"}, {"source_code": "import Data.List\n\nmain = interact $ show . sol . map read . words\n\nsol (_:k:f) = (*2) . sum . ct . sort $ f\n where ct [] = []\n ct x = head x - 1 : (ct $ drop k x)"}], "src_uid": "b8d8f0e86ecb600f7559a6aec629946e"} {"source_code": "import Control.Monad\n\ntype Test = (Integer, Integer, Integer)\n\ngetLines :: Int -> IO [Test]\ngetLines n = replicateM n getTest\n\ngetTest :: IO Test\ngetTest = do\n test <- getLine\n let [n, m, k] = map read (words test)\n return (n, m, k)\n\ngetAnswer :: [Test] -> [Integer]\ngetAnswer [] = []\ngetAnswer (first:rest) = solve first : getAnswer rest\n\nsolve :: Test -> Integer\nsolve (n, m, k) = maxJokers - nextMaxJokers\n where maxJokers = min (n `div` k) m\n a = fromIntegral (m - maxJokers)\n b = fromIntegral (k - 1)\n nextMaxJokers = ceiling (a/b)\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getLines $ read count\n mapM_ print (getAnswer tests)", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:m:k:_) <- map read . words <$> getLine\n let d = n `div` k\n print $ bool (d - (m - d - 1) `div` (k - 1) - 1) m (m <= d)"}, {"source_code": "module Main where\n\nsolve :: Int -> Int -> Int -> Int\nsolve cards jokers players =\n let hand = cards `div` players\n -- Split the remaining jokers among the other players\n maxrival = q + min 1 r\n where (q, r) = (jokers - hand) `quotRem` (players - 1)\n in if jokers <= hand then jokers else hand - maxrival\n\nreadCase :: Int -> IO ()\nreadCase 0 = return ()\nreadCase casenum = do\n l <- getLine\n let [n, m, k] = (map read . words) l :: [Int]\n print $ solve n m k\n readCase (casenum - 1)\n\nmain = getLine >>= (readCase . (read :: String -> Int))\n"}, {"source_code": "main :: IO ()\nmain = interact (unlines . map (show . solve . parse). tail . lines)\n\nparse :: String -> (Int, Int, Int)\nparse s = (n, m, k)\n where\n [n, m, k] = map read . words $ s\n\nsolve :: (Int, Int, Int) -> Int\nsolve (n, m, k) = x - y\n where\n x = min (div n k) m\n y = div (m - x + k - 2) (k - 1)\n"}, {"source_code": "module Main where\n solve :: IO ()\n solve = do\n s <- getLine\n let [n, m, k] = map (\\x -> read x :: Integer) $ words s\n x = min m (n `div` k)\n putStrLn $ show $ x - (m - x + k - 2) `div` (k - 1)\n \n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter (n - 1)\n \n main :: IO ()\n main = do\n s <- getLine\n let q = read s :: Integer\n iter q"}, {"source_code": "solve :: [[Int]] -> [Int]\nsolve [] = []\nsolve ([n,m,k]:xs) = (count n m k ) : (solve xs)\n\ncount :: Int -> Int -> Int -> Int\ncount n m k = winnerJ - secondJ\n\twhere \n\t\tcard = n `div` k\n\t\twinnerJ = min m card\n\t\tsecondJ = (m - winnerJ + k - 2) `div` (k-1) \n\nmain = do\n\tt' <- getLine\n\tlet t = read t' :: Int\n\tinput' <- getContents\n\tlet input = map (map read) (take t (map words (lines input'))) :: [[Int]]\n\tlet result = solve input\n\tmapM print result\n"}, {"source_code": "import Data.List\n\n-- import Debug.Trace\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let (_:vals) = read <$> split input :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n:m:k:rest ->\n let handSize = n `div` k\n winner = min handSize m\n bestLoser = (m - winner + k - 2) `div` (k - 1)\n subres = winner - bestLoser\n in Just (subres, rest)\n ) vals\n sequence_ (putStrLn . show <$> res)\n"}, {"source_code": "solve :: (Int, Int, Int) -> Int\nsolve (n, m, k) = let sz = div n k in case () of\n () | sz >= m -> m -- all jokers in one hand\n | otherwise -> case divMod (m - sz) (k-1) of\n (excess, 0) -> sz - excess -- distribute evenly\n (excess, _) -> sz - excess - 1\n\nparse :: String -> [(Int, Int, Int)]\nparse inp = [(n, m, k) | [n, m, k] <- map (map read . words) (tail $ lines inp)]\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve) . parse)\n\n\n"}], "negative_code": [], "src_uid": "6324ca46b6f072f8952d2619cb4f73e6"} {"source_code": "import Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsumEvens [] = 0\nsumEvens [x] = x\nsumEvens (x:y:xs) = (+x) $ sumEvens xs\n\ntestCandyEven [] _ _ _ _ = 0\ntestCandyEven (x:xs) esf osf eall oall = (+rez) $ testCandyOdd xs (esf + x) osf erest oall\n where erest = eall - x\n rez = if (erest + osf) == (oall + esf) then 1 else 0\n\ntestCandyOdd [] _ _ _ _ = 0\ntestCandyOdd (x:xs) esf osf eall oall = (+rez) $ testCandyEven xs esf (osf + x) eall orest\n where orest = oall - x\n rez = if (eall + osf) == (orest + esf) then 1 else 0\n\nmain=do\n n <- readLn::IO Int\n v <- map (fst . fromJust . B.readInt).B.words <$> B.getLine\n let se = sumEvens v\n let sodd = (sum v) - se\n print $ testCandyEven v 0 0 se sodd\n\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let n:xs = map fastRead . words $ input\n numbers = xs\n numbersA :: A.Array Int64 Int64\n numbersA = A.listArray (0, n-1) numbers\n reversed = reverse numbers\n\n dp :: A.Array (Int, Int64, Int64) Int64\n dp = A.array ((-1, 0, -1), (1, 1, n)) [((dir, pol, i), calcSum dir pol i) | dir <- [-1, 1], pol <- [0, 1], i <- [-1..n]]\n calcSum :: Int -> Int64 -> Int64 -> Int64\n calcSum 1 polarity i\n | i >= n = 0\n | i `mod` 2 == polarity = numbersA!i + dp!(1, polarity, i + 1)\n | otherwise = dp!(1, polarity, i + 1)\n calcSum (-1) polarity i\n | i < 0 = 0\n | i `mod` 2 == polarity = numbersA!i + dp!(-1, polarity, i - 1)\n | otherwise = dp!(-1, polarity, i - 1)\n\n isOkAt i = \n let totalP1 = toLeft + toRight2\n totalP2 = toLeft2 + toRight\n toRight = calcSum 1 polarity i+1\n toRight2 = calcSum 1 ipolarity i+1\n toLeft = calcSum (-1) polarity i-1\n toLeft2 = calcSum (-1) ipolarity i-1\n polarity = i `mod` 2\n ipolarity = 1 - polarity \n in totalP1 == totalP2\n in show . length $ filter isOkAt [0..(n-1)]\n -- in show $ calcSum 1 1 0\n\n"}, {"source_code": "import Data.List(scanl')\n\nproc :: [Int] -> Int -> [Int]\nproc [a] x = []\nproc (a:b:c) x = (a+b-x):(proc (b:c) x)\n\nft' :: Int -> [a] -> (Int -> Bool) -> a -> [a]\nft' _ [] _ _ = []\nft' i (a:b) f x = (if (f i) then a else x) : (ft' (succ i) b f x)\n\nft = ft' 0\n\ngetsame :: [Int] -> [Int] -> Int\ngetsame [] _ = 0\ngetsame _ [] = 0\ngetsame (a:b) (c:d) = (if a == c then 1 else 0)+getsame b d\nmain = do\n nstr <- getLine\n let n = (read::String->Int) nstr\n str <- getLine\n let a = map (read::String->Int) $ words str\n let to = length a - 1\n let odds = scanl' (+) 0 $ ft a odd 0\n let evens = scanl' (+) 0 $ ft a even 0\n print $ getsame (proc odds $ last odds) (proc evens $ last evens)"}, {"source_code": "import Data.List\nimport Control.Monad\n\nsumEvens [] = 0\nsumEvens [x] = x\nsumEvens (x:y:xs) = (+x) $ sumEvens xs\n\ntestCandyEven [] _ _ _ _ = 0\ntestCandyEven (x:xs) esf osf eall oall = (+rez) $ testCandyOdd xs (esf + x) osf erest oall\n where erest = eall - x\n rez = if (erest + osf) == (oall + esf) then 1 else 0\n\ntestCandyOdd [] _ _ _ _ = 0\ntestCandyOdd (x:xs) esf osf eall oall = (+rez) $ testCandyEven xs esf (osf + x) eall orest\n where orest = oall - x\n rez = if (eall + osf) == (orest + esf) then 1 else 0\n\nmain=do\n n <- readLn::IO Int\n v <- map (read::String->Int).words <$> getLine\n let se = sumEvens v\n let sodd = (sum v) - se\n print $ testCandyEven v 0 0 se sodd\n\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let n:xs = map fastRead . words $ input\n numbers = xs\n numbersA :: A.Array Int64 Int64\n numbersA = A.listArray (0, n-1) numbers\n reversed = reverse numbers\n\n dp :: A.Array (Int, Int64, Int64) Int64\n dp = A.array ((-1, 0, -1), (1, 1, n)) (do {\n dir <- [-1, 1];\n pol <- [0, 1];\n i <- [-1..n];\n return ((dir, pol, i), calcSum dir pol i);\n })\n\n calcSum :: Int -> Int64 -> Int64 -> Int64\n calcSum 1 polarity i\n | i >= n = 0\n | i `mod` 2 == polarity = numbersA!i + dp!(1, polarity, i + 1)\n | otherwise = dp!(1, polarity, i + 1)\n calcSum (-1) polarity i\n | i < 0 = 0\n | i `mod` 2 == polarity = numbersA!i + dp!(-1, polarity, i - 1)\n | otherwise = dp!(-1, polarity, i - 1)\n\n isOkAt i = \n let totalP1 = toLeft + toRight2\n totalP2 = toLeft2 + toRight\n toRight = calcSum 1 polarity i+1\n toRight2 = calcSum 1 ipolarity i+1\n toLeft = calcSum (-1) polarity i-1\n toLeft2 = calcSum (-1) ipolarity i-1\n polarity = i `mod` 2\n ipolarity = 1 - polarity \n in totalP1 == totalP2\n in show . length $ filter isOkAt [0..(n-1)]\n -- in show $ calcSum 1 1 0\n\n"}], "negative_code": [], "src_uid": "dcc380c544225c8cadf0df8d8b6ffb4d"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.Bits\nimport Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n k <- getInt\n let\n nc2 = n * (n - 1) `div` 2\n tarXorTotal = nc2 - 2 * k\n\n numPairs = n `div` 2\n canSolve = inRange (numPairs, numPairs * (n - 1)) tarXorTotal\n\n tryWith baselineXor = let\n lastPairsXor = (tarXorTotal - baselineXor * (numPairs - 2)) `div` 2\n\n basicArr = array (0, n-1) [(i, i `xor` baselineXor) | i <- [0 .. n-1]]\n toLi :: UArray Int Int -> [[Int]]\n toLi arr = [[i, j] | (i, j) <- assocs arr, i < j]\n in if inRange (1, n - 1) lastPairsXor\n then Just $ if baselineXor == lastPairsXor\n then toLi basicArr\n else toLi $ basicArr //\n [ (0, lastPairsXor)\n , (lastPairsXor, 0)\n , (baselineXor, baselineXor `xor` lastPairsXor)\n , (baselineXor `xor` lastPairsXor, baselineXor)\n ]\n else Nothing\n\n ans = if canSolve\n then head $ mapMaybe tryWith [1 .. n - 1]\n else [[-1]]\n pure $ foldMap putInts ans\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\nimport Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n k <- getInt\r\n let\r\n basicArr = listArray (0, n-1) [n-1, n-2 .. 0]\r\n directArr x = basicArr // [(x, n-1), (n-1, x), (0, n-1-x), (n-1-x, 0)]\r\n s = div n 2\r\n maxArr = directArr (k-1) // [(s+1, s-1), (s-1, s+1), (s-2, s), (s, s-2)]\r\n toLi :: UArray Int Int -> [[Int]]\r\n toLi arr = [[i, j] | (i, j) <- assocs arr, i < j]\r\n ans = if n == 4 && k == 3\r\n then [[-1]]\r\n else if k < n - 1\r\n then toLi $ directArr k\r\n else toLi maxArr\r\n pure $ foldMap putInts ans\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "28d1c6a6effb1aea722164d5735377fc"} {"source_code": "import Data.List\nmain = interact $ unwords . f . map read . words\nf (n:_:dx:dy:s) = g s . snd . maximum . map (\\(x:s) -> (length s, x)) . group . sort $ h s where\n m = flip mod n . fromIntegral . head . findIndices (==n-1) $ iterate (flip mod n . (+dx)) 0\n i x y = mod (m * x * dy + y) n\n g (x:y:s) t\n | i x y == t = [show x, show y]\n | otherwise = g s t\n h [] = []\n h (x:y:s) = i x y:h s", "positive_code": [{"source_code": "import Data.List\nmain = interact $ unwords . f . map read . words\nf (n:_:dx:dy:s) = g s . snd . maximum . map (\\(x:s) -> (length s, x)) . group . sort $ h s where\n m = flip mod n . fromIntegral . head . findIndices (==n-1) $ iterate (flip mod n . (+dx)) 0\n i x y = mod (mod (m * x) n * dy + y) n\n g (x:y:s) t\n | i x y == t = [show x, show y]\n | otherwise = g s t\n h [] = []\n h (x:y:s) = i x y:h s"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Ord\nimport Numeric (readDec)\n\nfastRead str = case readDec str of [(x, \"\")] -> x\nsolve :: [Int] -> Int\nsolve (n:m:dx:dy:vec) = head . maximumBy (comparing length) . group . sort $ cells vec\n where cells [] = []\n cells (cx:cy:s) = (n + cy - steps ! cx) `rem` n : cells s\n steps = array (0, n-1) (take n $ iterate g (0, 0))\n where g (x, y) = ((x + dx) `rem` n, (y + dy) `mod` n)\nmain = putStrLn . (\"0 \" ++) . show . solve . map fastRead . words =<< getContents"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Ord\nimport Numeric (readDec)\n\nfastRead str = case readDec str of [(x, \"\")] -> x\nsolve :: [Int] -> Int\nsolve (n:m:dx:dy:vec) = head . maximumBy (comparing length) . group . sort $ cells vec\n where cells [] = []\n cells (cx:cy:s) = (n + cy - steps ! cx) `rem` n : cells s\n steps = array (0, n-1) (take n $ iterate g (0, 0))\n where g (x, y) = ((x + dx) `rem` n, (y + dy) `rem` n)\nmain = putStrLn . (\"0 \" ++) . show . solve . map fastRead . words =<< getContents"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Ord\nimport Numeric (readDec)\n\nfastRead str = case readDec str of [(x, \"\")] -> x\nsolve :: [Int] -> Int\nsolve (n:m:dx:dy:vec) = head . maximumBy (comparing length) . group . sort $ cells vec\n where cells [] = []\n cells (cx:cy:s) = (cy - steps ! cx) `mod` n : cells s\n steps = array (0, n-1) (take n $ iterate g (0, 0))\n where g (x, y) = ((x + dx) `mod` n, (y + dy) `mod` n)\nmain = putStrLn . (\"0 \" ++) . show . solve . map fastRead . words =<< getContents"}, {"source_code": "import Data.List\nimport Data.Int\nmain = interact $ unwords . f . map (read :: String -> Int64) . words\nf (n:_:dx:dy:s) = g s . snd . maximum . map (\\(x:s) -> (length s, x)) . group . sort $ h s where\n m = flip mod n . fromIntegral . head . findIndices (==n-1) $ iterate (flip mod n . (+dx)) 0\n i x y = mod (mod (m * x) n * dy + y) n\n g (x:y:s) t\n | i x y == t = [show x, show y]\n | otherwise = g s t\n h [] = []\n h (x:y:s) = i x y:h s"}], "negative_code": [{"source_code": "import qualified Data.Map as M\nimport Data.List\nmain = interact $ unwords . f . map read . words\nf (n:_:dx:dy:s) = g s . snd . maximum . map (\\(x:s) -> (length s, x)) . group . sort $ h s where\n m = M.fromList $ map (\\x -> (mod (x * (n - dx)) n, x)) [0..n-1]\n i x y = mod (y + dy * M.findWithDefault 0 x m) n\n g (x:y:s) t\n | i x y == t = [show x, show y]\n | otherwise = g s t\n h :: [Int] -> [Int]\n h [] = []\n h (x:y:s) = i x y:h s"}, {"source_code": "import Data.List\nmain = interact $ unwords . f . map read . words\nf (n:_:dx:dy:s) = g s . snd . maximum . map (\\(x:s) -> (length s, x)) . group . sort $ h s where\n m = flip mod n . head . findIndices (==n-1) $ iterate (flip mod n . (+dx)) 0\n i x y = mod (m * x * dy + y) n\n g (x:y:s) t\n | i x y == t = [show x, show y]\n | otherwise = g s t\n h [] = []\n h (x:y:s) = i x y:h s"}], "src_uid": "6a2fe1f7e767a508530e9d922740c450"} {"source_code": "{-# LANGUAGE ScopedTypeVariables, BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\n\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\n\nstableBucketSortOn :: forall t. (t -> Int) -> (Int, Int) -> [t] -> [t]\nstableBucketSortOn fun bnds li = let\n buckets :: Array Int ([t] -> [t])\n buckets = accumArray (\\f v -> f . (v :)) id bnds [(fun v, v) | v <- li]\n in foldr ($) [] $ elems buckets\n\ndedup :: Int -> [(Int, Int)] -> Array Int (Int, Int)\ndedup n li = let\n ili = stableBucketSortOn snd (1, n) li\n sli = group $ stableBucketSortOn fst (1, n) ili\n in listArray (1, length sli) $ map head sli\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\nbinSearch fun li ri = if li == ri\n then li\n else let\n mi = li + div (ri - li) 2\n in if fun mi\n then binSearch fun li mi\n else binSearch fun (mi + 1) ri\n\ngetIx :: Ord t => t -> Array Int t -> Int\ngetIx v arr = let\n (li, ri) = bounds arr\n in binSearch (\\ix -> v <= arr ! ix) li (ri + 1)\n\ndata Query\n = Ins Int Int Char\n | Rem Int Int\n | Ask Int\n\nui :: P.ByteString -> Int\nui = P.foldl' (\\acc c -> 10 * acc + fromEnum c - fromEnum '0') 0\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, m] <- readInts\n queries <- replicateM m $ do\n ask <- readLine\n pure $ case P.words ask of\n [_, u, v, c] -> Ins (ui u) (ui v) (P.head c)\n [_, u, v] -> Rem (ui u) (ui v)\n [_, k] -> Ask (ui k)\n _ -> error \"invalid input\"\n let\n usedPairs = dedup n [(min u v, max u v) | Ins u v _ <- queries]\n getArr = lift $ newArray (bounds usedPairs) '\\0' :: SIO (IOUArray Int Char)\n ayes <- getArr\n nays <- getArr\n let\n step :: (Int, Int) -> Query -> SIO (Int, Int)\n step (!eq, !ok) (Ins u v c) = let\n (fwd, rev, ix) = if u < v\n then (ayes, nays, getIx (u, v) usedPairs)\n else (nays, ayes, getIx (v, u) usedPairs)\n in lift $ do\n writeArray fwd ix c\n cr <- readArray rev ix\n pure (eq + if c == cr then 1 else 0,\n ok + if cr /= '\\0' then 1 else 0)\n step (!eq, !ok) (Rem u v) = let\n (fwd, rev, ix) = if u < v\n then (ayes, nays, getIx (u, v) usedPairs)\n else (nays, ayes, getIx (v, u) usedPairs)\n in lift $ do\n c <- readArray fwd ix\n cr <- readArray rev ix\n writeArray fwd ix '\\0'\n pure (eq - if c == cr then 1 else 0,\n ok - if cr /= '\\0' then 1 else 0)\n step v@(!eq, !ok) (Ask k) = (v <$) $ lift $ P.putStrLn $ P.pack\n $ if eq > 0 || odd k && ok > 0\n then \"YES\"\n else \"NO\"\n foldM_ step (0, 0) queries\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Map.Strict as M\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ntype State = (M.Map (Int, Int) Char, Int, Int)\n\naddArc :: (Int, Int) -> Char -> State -> State\naddArc (u, v) ch (mp, c1, c2)\n | isNothing rev = (mp', c1, c2)\n | fromJust rev == ch = (mp', c1 + 1, c2)\n | otherwise = (mp', c1, c2 + 1)\n where\n rev = M.lookup (v, u) mp\n mp' = M.insert (u, v) ch mp\n\ndelArc :: (Int, Int) -> State -> State\ndelArc (u, v) (mp, c1, c2)\n | isNothing rev = (mp', c1, c2)\n | fromJust rev == ch = (mp', c1 - 1, c2)\n | otherwise = (mp', c1, c2 - 1)\n where\n Just ch = M.lookup (u, v) mp\n rev = M.lookup (v, u) mp\n mp' = M.delete (u, v) mp\n\ncheck :: State -> Int -> Bool\ncheck (_, c1, c2) k\n | even k = c1 > 0\n | otherwise = c2 > 0 || c1 > 0\n\nmain :: IO ()\nmain = do\n [_, m] <- getInts\n ws <- replicateM m (fmap C.words C.getLine)\n let\n acc (st, rs) (s : ss) =\n case C.unpack s of\n \"+\" -> (addArc (u, v) ch st, rs)\n \"-\" -> (delArc (u, v) st, rs)\n \"?\" -> (st, check st (parseInt (head ss)) : rs)\n where\n (s1 : r1) = ss\n u = parseInt s1\n (s2 : r2) = r1\n v = parseInt s2\n (s3 : _) = r2\n ch = head $ C.unpack s3\n (_, results) = foldl' acc ((M.empty, 0, 0), []) ws\n mapM_ (\\ok -> C.putStrLn $ C.pack $ if ok then \"YES\" else \"NO\") $ reverse results\n"}], "negative_code": [], "src_uid": "5afb904f611d963ed3e302faefef3305"} {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ unlines.solve.tail.concat. map (map read.words).take 2. lines\nsolve :: [Integer]-> [String]\nsolve (x1:x2:[])= map (unwords.(map show)) [[0], [x2]]\nsolve (x:y:xs) = map (unwords.(map show)) [[maximum [sum ff - sum (y:xs),0]],ff] where\n ff=scanl f y xs \n f b a = maximum [x-b,a]", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . words =<< getContents\n\noutput :: (Int, [Int]) -> IO()\noutput (cost, a) = do\n print cost\n putStrLn $ unwords $ map show a\n\nsolve :: [Int] -> (Int, [Int])\nsolve (n:k:a) = solve' (head a) (tail a) 0 [head a]\n where solve' :: Int -> [Int] -> Int -> [Int] -> (Int, [Int])\n solve' last [] cost path = (cost, reverse path)\n solve' last (a:x) cost path = let extra = max 0 (k - a - last)\n walk = a + extra\n in solve' walk x (cost + extra) (walk : path)\n"}, {"source_code": "\n\n\n\nconv lst uu\n | (null lst) = reverse uu\n | otherwise = conv (tail lst) (((read (head lst))::Int) : uu)\n\npp = putStrLn \n\n\n\ndostuff lst kk uu sum\n | (null lst) = ( (reverse uu), sum )\n | (diff > 0) = dostuff (tail lst) kk ((diff + (head lst)) : uu) (diff + sum)\n | otherwise = dostuff (tail lst) kk ((head lst) : uu) (sum)\n where diff = (kk - ((head uu) + (head lst)))\n\n\nmakestr lst uu\n | (null lst) = (reverse uu)\n | otherwise = makestr (tail lst) (\" \" ++ (reverse (show (head lst))) ++ uu)\n\n\n\n\n\nmain = do\n ff <- getLine\n let n = (read (head (words ff)))::Int\n k = (read (last (words ff)))::Int\n \n gg <- getLine\n let hh = conv (words gg) []\n\n ans = dostuff (tail hh) k [(head hh)] 0\n-- anstwo = dostuff (tail (reverse hh)) k [(head (reverse hh))] 0\n\n \n pp (show (snd ans))\n pp (makestr (fst ans) [])\n -- pp \"-------------------------------\"\n\n -- pp (show (snd anstwo))\n -- pp (makestr (fst anstwo) [])\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nwalk _ acc [] = reverse acc\nwalk k (a:as) (b:bs) =\n walk k ((if a+b read x ::Integer) . words) getLine \n bs <- liftM (map (\\x -> read x ::Integer) . words) getLine \n let c = walk k [head bs] $ tail bs\n print $ sum c - sum bs\n putStrLn $ concat $ intersperse \" \" $ map show c\n"}, {"source_code": "import Data.Functor\n\nsolve :: Int -> Int -> [Int] -> [Int]\nsolve _ _ [] = []\nsolve k l [a] = [max a (k - l)]\nsolve k l (h:t) = let h' = max h (k - l) in h' : solve k h' t\n\nmain :: IO()\nmain = do\n [_, r] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n let b = solve r r a\n print $ sum b - sum a\n putStrLn . unwords . map show $ b\n"}, {"source_code": "import Data.List\nmain = do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let (_:bs) = scanl process k as\n process yesterday today | today + yesterday < k = k - yesterday\n | otherwise = today\n print $ sum $ zipWith (-) bs as\n putStrLn $ unwords $ map show bs\n"}, {"source_code": "import Data.List\nmain = do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let (_,bs) = mapAccumL process k as\n process yesterday today\n | avg < k = (today + k - avg,today + k - avg)\n | otherwise = (today,today)\n where avg = today + yesterday\n print $ sum $ zipWith (-) bs as\n putStrLn $ unwords $ map show bs\n"}, {"source_code": "calc k a\n | length a == 0 = []\n | length a == 1 = a\n | length a > 1 && k-(a!!0)-(a!!1) > 0 = [a!!0] ++ calc k ([k-(a!!0)]++(drop 2 a))\n | otherwise = [a!!0] ++ calc k (drop 1 a)\n\nf(_:k:a) = [[foldl (+) 0 [bi - ai | (ai, bi) <- zip a b]], b] where b = calc k a\n\nmain=interact$unlines.map(unwords.map show).f.map read.words\n\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: Int -> Int -> [Int] -> [Int] -> [Int]\n solve _ _ acc [] = acc\n solve k y acc (x:xs) =\n let z = max 0 (k - (y + x))\n in solve k (x + z) ((x + z):acc) xs\n\n diff :: [Int] -> [Int] -> Int\n diff [] [] = 0\n diff (x:xs) (y:ys) = (y - x) + (diff xs ys)\n\n main :: IO()\n main = do\n [n, k] <- getLine >>= return . (map readInt) . words\n -- let xs = [2, 0, 1]\n xs <- getLine >>= return . (map readInt) . words\n let result = reverse $ solve k k [] xs\n d = diff xs result\n print d\n putStrLn $ intercalate \" \" $ map show result\n"}, {"source_code": "main=interact$unlines.map(unwords.map show).f.map read.words\nf(_:k:s)=[[sum$zipWith(-)(k#s)s],k#s]\nk#(x:y:s)|x+yInt).words =<< getLine\n [n,k] <- interpretLine\n as <- interpretLine\n let entry [] = return 0 \n\tentry [w] = modify (w:) >> return 0\n\tentry (w1:w2:ws)\n\t | w1+w2 >= k\t= do\n\t\tmodify (w1:)\n\t\tentry $ w2:ws\n\t | otherwise\t= do\n\t\tlet diff = k-w1-w2\n\t\tmodify (w1:)\n\t\tv <- entry $ (w2+diff):ws\n\t\treturn $ diff+v\n (additional, bs) <- runStateT (entry as) []\n print additional\n forM_ (reverse bs) $ \\w -> putStr (show w) >> putStr \" \"\n"}, {"source_code": "import Data.List\n\nneed k xs = 0 : (go xs) \n where go [_] = []\n go (y:ys:yss)\n | extra > 0 = extra : go ((extra + ys):yss)\n | otherwise = 0 : go (ys:yss)\n where extra = k - y - ys\n\namount :: [Int] -> Int \namount = sum \n\nfinal = zipWith (+) \n\nmain = do\n [_, k] <- fmap (map read . words) getLine :: IO [Int] \n xs <- fmap (map read . words) getLine :: IO [Int]\n let s = need k xs \n print $ amount s\n putStrLn . concat . intersperse \" \" . map show . final s $ xs \n\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nplan :: [Int] -> Int -> Int -> [Int]\nplan [] _ _ = []\nplan (x:xs) k need = max need x : plan xs k (k - max need x)\n\n\nreadInt s = let Just (i, _) = C.readInt s in i\n\nmain = do\n (n:k:_) <- fmap (map readInt . C.words) C.getLine\n ar <- fmap (map readInt . C.words) C.getLine\n let result = plan ar k 0\n print $ sum $ zipWith subtract ar result\n putStr $ unwords $ map show result\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Prelude\nimport Text.Printf\nimport Data.List\n\nsolve :: [Int] -> Int -> Int -> [Int]\nsolve [] _ _ = []\nsolve (a:as) k p = [c] ++ (solve as k c)\n where c = max a (k - p)\n\nmain = do\n [n, k] <- liftM (map read . words) getLine\n a <- liftM (map read . words) getLine\n let b = solve a k k\n printf \"%d\\n\" ((sum b) - (sum a))\n forM_ [0..(length b) - 1] $ do \\i -> printf \"%d \" (b !! i)\n"}, {"source_code": "doit :: [Int] -> Int -> Int -> [Int]\ndoit [] _ _ = []\ndoit (x:xs) k last = let ne = last + x\n in if ne < k then (k - last) : doit xs k (k - last) else x : doit xs k x\n\nmain = do\n\t[n, k] <- getLine >>= return . map read . words\n\ta <- getLine >>= return . map read . words\n\tlet ans = doit a k k\n\tprint $ sum ans - sum a\n\tputStrLn $ unwords $ map show ans"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . tail . words =<< getContents\n\noutput :: (Int, [Int]) -> IO()\noutput (cost, a) = do\n print cost\n putStrLn $ unwords $ map show a\n\nminIndex :: [Int] -> Int\nminIndex cost = snd . minimum $ zip cost [0..]\n\nsolve :: [Int] -> (Int, [Int])\nsolve (k:a) = let path = [[] | i <- [0..k]]\n cost = [0 | i <- [0..k]]\n in solve' path cost a\n where\n solve' :: [[Int]] -> [Int] -> [Int] -> (Int, [Int])\n solve' path cost [] = let index = minIndex cost\n in (cost !! index, reverse $ path !!index)\n solve' path cost (a:ax) = let (next_path, next_cost) = unzip $ map (trans a k path cost) [0..k]\n in solve' next_path next_cost ax\n\ntrans :: Int -> Int -> [[Int]] -> [Int] -> Int -> ([Int], Int)\ntrans a k path cost i = let costs = map trans' $ zip [0..] cost\n index = minIndex costs\n in (i : path !! index, costs !! index)\n where trans' :: (Int, Int) -> Int\n trans' (j, cost) | i < a || i < k - j = cost + 1000\n | otherwise = cost + i - a\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . words =<< getContents\n\noutput :: (Int, [Int]) -> IO()\noutput (cost, a) = do\n print cost\n putStrLn $ unwords $ map show a\n\nsolve :: [Int] -> (Int, [Int])\nsolve (n:k:a) | n == 1 = let extra = max 0 (k - (head a))\n in (extra, [extra + head a])\n | otherwise = solve' 0 (head a) (tail a) 0 [head a]\n where solve' :: Int -> Int -> [Int] -> Int -> [Int] -> (Int, [Int])\n solve' a b [] cost path = let extra = max 0 (k - a - b)\n in (cost + extra, reverse (extra + head path : tail path))\n solve' a b (c:x) cost path = let extra = max 0 (k - a - b - c)\n walk = c + extra\n in solve' b walk x (cost + extra) (walk : path)\n"}, {"source_code": "\n\n\n\nconv lst uu\n | (null lst) = reverse uu\n | otherwise = conv (tail lst) (((read (head lst))::Int) : uu)\n\npp = putStrLn \n\n\n\ndostuff lst kk uu sum\n | (null lst) = ( (reverse uu), sum )\n | (diff > 0) = dostuff (tail lst) kk ((diff + (head lst)) : uu) (diff + sum)\n | otherwise = dostuff (tail lst) kk ((head lst) : uu) (sum)\n where diff = (kk - ((head uu) + (head lst)))\n\n\nmakestr lst uu\n | (null lst) = (reverse uu)\n | otherwise = makestr (tail lst) (\" \" ++ (show (head lst)) ++ uu)\n\n\n\n\n\nmain = do\n ff <- getLine\n let n = (read (head (words ff)))::Int\n k = (read (last (words ff)))::Int\n \n gg <- getLine\n let hh = conv (words gg) []\n\n ans = dostuff (tail hh) k [(head hh)] 0\n \n pp (show (snd ans))\n pp (makestr (fst ans) [])\n\n\n\n\n\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ unlines.solve.tail.concat. map (map read.words).take 2. lines\nsolve :: [Integer]-> [String]\nsolve (x1:x2:[])= map (unwords.(map show)) [[maximum [x1-x2,0]], [maximum [x1,x2]]]\nsolve (x:y:xs) = map (unwords.(map show)) [[maximum [sum ff - sum (y:xs),0]],ff] where\n ff=scanl f y xs \n f b a = maximum [x-b,a]"}, {"source_code": "doit :: [Int] -> Int -> Int -> [Int]\ndoit [] _ _ = []\ndoit (x:xs) k last = let ne = last + x\n in if ne < k then (k - last) : doit xs k (k - last) else x : doit xs k x\n\nmain = do\n\t[n, k] <- getLine >>= return . map read . words\n\ta <- getLine >>= return . map read . words\n\tlet ans = doit a k k\n\tprint $ sum ans\n\tputStrLn $ unwords $ map show ans"}], "src_uid": "1956e31a9694b4fd7690f1a75028b9a1"} {"source_code": "import System.IO\nimport Control.Applicative\nimport Debug.Trace\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\nimport Data.Char\nimport qualified Data.Set as Set\n\n\n-- traceDebug = trace\ntraceDebug _ x = x\n\nmapInd :: (a -> Int -> b) -> [a] -> [b]\nmapInd f l = zipWith f l [0..]\n\nlaunchNext k (hd:perm) i =\n if hd == i then (1, hd:perm)\n else do\n let aux screen count (j':j:tl)\n | j == i = (screen, j:j':tl)\n | otherwise = do\n let (s',cnt') = if count == k then (screen+1, 1)\n else (screen, count+1)\n let (c,tl') = aux s' cnt' (j:tl)\n (c, j':tl')\n aux 1 2 (hd:perm)\n\nswapIdx index perm ix jx = do\n io <- readArray perm ix\n jo <- readArray perm jx\n writeArray index io jx\n writeArray index jo ix\n writeArray perm ix jo\n writeArray perm jx io\n\nexecOrder index perm k o = do\n x <- readArray index o\n if x == 1\n then return (1 :: Integer)\n else do\n swapIdx index perm (x-1) x\n return $ fromIntegral $ (x-1) `div` k + 1\n\n\nexecuteOrders :: [Int] -> [Int] -> Int -> Int -> Integer\nexecuteOrders perm order n k = runST (do\n index <- (newArray (0, n) (-1) :: ST s (STUArray s Int Int))\n zipWithM_ (\\x i -> writeArray index x i) perm [1..]\n perm_m <- newListArray (0,n) $ (-1):perm :: ST s (STUArray s Int Int)\n\n -- let aux :: Integer -> [Int] -> m Integer\n let aux v [] = return v\n aux v (o:tl) = do\n v' <- execOrder index perm_m k o\n aux (v+v') tl\n aux 0 order)\n\n\nmain = main_mut\n\nmain_orig = do\n [n,m,k] <- map read <$> words <$> getLine\n perm <- map read <$> words <$> getLine :: IO [Int]\n order <- map read <$> words <$> getLine :: IO [Int]\n\n let aux (c, perm) o = do\n let (c', perm') = launchNext k perm o\n -- traceShow (c', perm') $ do\n (c+c', perm')\n\n let (c,_) = foldl aux (0, perm) order\n putStrLn $ show c\n\n\n\nmain_mut = do\n [n,m,k] <- map read <$> words <$> getLine\n perm <- map read <$> words <$> getLine :: IO [Int]\n order <- map read <$> words <$> getLine :: IO [Int]\n\n let v = executeOrders perm order n k\n putStrLn $ show v\n\n\n\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Map\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport qualified Data.ByteString.Char8 as B\n\ngetGestures :: Int -> Int -> Int\ngetGestures pos perScreen = pos `div` perScreen + 1\n\ngetIntList :: IO [Int]\ngetIntList = parseLine <$> B.getLine\n where\n parseLine = (map (fst . fromJust . B.readInt)) . B.words\n \ntype IntMap = Data.Map.Map Int Int\n\ngetMaps :: [Int] -> (IntMap, IntMap)\ngetMaps array = foldl' (\\ (p2v, v2p) (v, p) -> \n (Data.Map.insert p v p2v, Data.Map.insert v p v2p))\n (Data.Map.empty, Data.Map.empty) (zip array [0..])\n\nsolve :: [Int] -> IntMap -> IntMap -> Int64 -> Int -> Int64\nsolve [] _ _ acc _ = acc\nsolve (x:xs) posToVal valToPos acc perScreen = \n let acc' = acc + fromIntegral (getGestures (valToPos Data.Map.! x) perScreen)\n (posToVal', valToPos') = moveForward posToVal valToPos x\n in solve xs posToVal' valToPos' acc' perScreen\n where \n moveForward p2v v2p v =\n let curPos = v2p Data.Map.! v\n prevPos = curPos - 1\n curVal = v\n prevVal = fromMaybe (-1) (Data.Map.lookup prevPos p2v)\n in \n if prevPos == -1 then\n (p2v, v2p)\n else\n let p2v' = Data.Map.insert curPos prevVal p2v\n p2v'' = Data.Map.insert prevPos curVal p2v'\n v2p' = Data.Map.insert curVal prevPos v2p\n v2p'' = Data.Map.insert prevVal curPos v2p'\n in (p2v'', v2p'')\n\nmain = do\n [n, m, k] <- getIntList \n a <- getIntList\n b <- getIntList\n let (posToVal, valToPos) = getMaps $ map (\\x -> x - 1) a\n let res = solve (map (\\x -> x - 1) b) posToVal valToPos 0 k\n print res\n \n"}], "negative_code": [{"source_code": "import System.IO\nimport Control.Applicative\nimport Debug.Trace\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST\nimport Data.List\nimport Data.Char\nimport qualified Data.Set as Set\n\n\n-- traceDebug = trace\ntraceDebug _ x = x\n\nmapInd :: (a -> Int -> b) -> [a] -> [b]\nmapInd f l = zipWith f l [0..]\n\nlaunchNext k (hd:perm) i =\n if hd == i then (1, hd:perm)\n else do\n let aux screen count (j':j:tl)\n | j == i = (screen, j:j':tl)\n | otherwise = do\n let (s',cnt') = if count == k then (screen+1, 1)\n else (screen, count+1)\n let (c,tl') = aux s' cnt' (j:tl)\n (c, j':tl')\n aux 1 2 (hd:perm)\n\nswapIdx index perm ix jx = do\n io <- readArray perm ix\n jo <- readArray perm jx\n writeArray index io jx\n writeArray index jo ix\n writeArray perm ix jo\n writeArray perm jx io\n\nexecOrder index perm k o = do\n x <- readArray index o\n if x == 1\n then return 1\n else do\n swapIdx index perm (x-1) x\n return $ (x-1) `div` k + 1\n\n\nexecuteOrders :: [Int] -> [Int] -> Int -> Int -> Int\nexecuteOrders perm order n k = runST (do\n index <- (newArray (0, n) (-1) :: ST s (STUArray s Int Int))\n zipWithM_ (\\x i -> writeArray index x i) perm [1..]\n perm_m <- newListArray (0,n) $ (-1):perm :: ST s (STUArray s Int Int)\n\n let aux v [] = return v\n aux v (o:tl) = do\n v' <- execOrder index perm_m k o\n aux (v+v') tl\n aux 0 order)\n\n\nmain = main_mut\n\nmain_orig = do\n [n,m,k] <- map read <$> words <$> getLine\n perm <- map read <$> words <$> getLine :: IO [Int]\n order <- map read <$> words <$> getLine :: IO [Int]\n\n let aux (c, perm) o = do\n let (c', perm') = launchNext k perm o\n -- traceShow (c', perm') $ do\n (c+c', perm')\n\n let (c,_) = foldl aux (0, perm) order\n putStrLn $ show c\n\n\n\nmain_mut = do\n [n,m,k] <- map read <$> words <$> getLine\n perm <- map read <$> words <$> getLine :: IO [Int]\n order <- map read <$> words <$> getLine :: IO [Int]\n\n let v = executeOrders perm order n k\n putStrLn $ show v\n\n\n\n"}], "src_uid": "3b0fb001333e53da458e1fb7ed760e32"} {"source_code": "import Data.List\nimport Data.Ord\nmain=readFile\"input.txt\">>=writeFile\"output.txt\".parseOutput 'A'.solve.parseInput.words\n\nparseInput (n:x:a:b:c:rest) = (map read [n,x,a,b,c],toPairs rest)\ntoPairs :: [String] -> [(String,Int)]\ntoPairs (name:rating:rest) = (name,read rating):toPairs rest\ntoPairs _ = []\nparseOutput c (t1:t2:t3:t4:rest) = unlines [\"Group \"++c:\":\",t1,t2,t3,t4] ++ parseOutput (succ c) rest\nparseOutput _ _ = []\n\nsolve ([n,x0,a,b,c],teams) = loop basket1 basket2 basket3 basket4 randoms\n where\n m = n`div`4\n randoms = tail $ iterate (\\x->(x*a+b)`mod`c) x0\n sortedTeams = map fst $ sortBy(flip (comparing snd)) teams\n (basket1,rest1) = splitAt m sortedTeams\n (basket2,rest2) = splitAt m rest1\n (basket3,basket4) = splitAt m rest2\n\ndel i xs = case splitAt i xs of (xs,y:ys) -> (y,xs++ys)\n\n\nloop [] [] [] [] _ = []\nloop basket1 basket2 basket3 basket4 (r1:r2:r3:r4:rs) = t1:t2:t3:t4:loop nb1 nb2 nb3 nb4 rs\n where\n (t1,nb1) = del (r1`mod`length basket1) basket1\n (t2,nb2) = del (r2`mod`length basket2) basket2\n (t3,nb3) = del (r3`mod`length basket3) basket3\n (t4,nb4) = del (r4`mod`length basket4) basket4\n", "positive_code": [{"source_code": "\nimport Data.List (delete, sortBy, unfoldr)\nimport Monad (liftM)\n\ntype Command = (String, Int)\ntype Random = (Int, Int, Int, Int)\n\ncountBasket = 4 :: Int\n\nsortBySnd :: Ord b => [(a, b)] -> [(a, b)]\nsortBySnd = sortBy (\\a b -> compare (snd b) (snd a))\n\nparse :: String -> Command\nparse line = case words line of\n [s1, s2] -> (s1, read s2)\n\nrandoms :: Random -> [Int]\nrandoms = unfoldr (Just . next)\n where\n next (x, a, b, c) = (y, (y, a, b, c))\n where\n y = (a * x + b) `mod` c\n\nsolve :: Int -> Random -> [Command] -> [[Command]]\nsolve n random cs = map sortBySnd (solve' (randoms random) bs)\n where\n m = n `div` countBasket\n cs' = sortBySnd cs\n bs = [[cs' !! (i * m + j) | j <- [0..m-1]] | i <- [0..countBasket-1]]\n \n solve' :: [Int] -> [[Command]] -> [[Command]]\n solve' rs bs\n | null $ head bs = []\n | otherwise = cs : solve' (drop countBasket rs) (zipWith delete cs bs)\n where\n cs = map (\\(r, b) -> b !! (r `mod` (length b))) (zip rs bs)\n\nformat :: [[Command]] -> [String]\nformat = concatMap (\\(c, cs) -> (\"Group \" ++ [c] ++ \":\") : (map fst cs)) . zip ['A' ..]\n\nmain :: IO ()\nmain = do\n ls <- liftM lines $ readFile \"input.txt\"\n let n = read . (!! 0) $ ls\n let [x, a, b, c] = map read . words . (!! 1) $ ls\n let commands = take n $ map parse $ drop 2 ls\n writeFile \"output.txt\" $ unlines $ format $ solve n (x, a, b, c) commands\n"}], "negative_code": [], "src_uid": "349b116f40dcf3884d4c8208a513ee23"} {"source_code": "import Control.Arrow ((>>>))\n\nsolve arr = solveh arr 0 (last arr == 'B')\n\n-- finally, got it :D\nsolveh [] sum ok = ok\nsolveh (x : xs) sum ok = solveh xs s (s >= 0 && ok)\n where\n s = if x == 'A' then sum + 1 else sum - 1\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map solve\n >>> map (\\p -> if p then \"YES\" else \"NO\")\n >>> unlines\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\n\nsolve :: String -> Bool\nsolve str = L.last str /= 'A' && L.all (>= 0) accum_char_values\n where\n accum_char_values = L.scanl (+) 0 char_values\n char_values = L.map char_value str\n\n char_value :: Char -> Int\n char_value 'A' = 1\n char_value 'B' = -1\n char_value _ = 0\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n s <- B8.getLine <&> L.head . B8.words\n let answer = solve $ B8.unpack s\n putsYesNo answer\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\n\nsolve arr = solveh arr 0 0 && last arr == 'B'\n\nsolveh [] a b = a >= b\nsolveh (x : xs) a b = if x == 'A' then solveh xs (a + 1) b else solveh xs a (b + 1)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map solve\n >>> map (\\p -> if p then \"YES\" else \"NO\")\n >>> unlines\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nsolve arr = solveh arr 0 || last arr == 'A'\n\nsolveh [] sum = sum < 0\nsolveh (x : xs) sum = if x == 'A' then solveh xs (sum + 1) else solveh xs (sum - 1)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map solve\n >>> map (\\p -> if p then \"NO\" else \"YES\")\n >>> unlines\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nsolve arr = solveh arr 0 && last arr == 'B'\n\nsolveh [] sum = sum >= 0\nsolveh (x : xs) sum = if x == 'A' then solveh xs (sum + 1) else solveh xs (sum - 1)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map solve\n >>> map (\\p -> if p then \"YES\" else \"NO\")\n >>> unlines\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nsolve arr = solveh arr 0 0 && last arr == 'B'\n\nsolveh [] a b = a > b\nsolveh (x : xs) a b = if x == 'A' then solveh xs (a + 1) b else solveh xs a (b + 1)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map solve\n >>> map (\\p -> if p then \"YES\" else \"NO\")\n >>> unlines\n"}, {"source_code": "import Control.Arrow ((>>>))\n\nsolve arr = head arr == 'A' && solveh arr && last arr == 'B'\n\nsolveh [] = True\nsolveh [b] = b == 'B'\nsolveh [a, b] = a == 'A' && b == 'B'\nsolveh (a : b : cs) = (a == 'A' && b == 'A' && solveh (b : cs)) || (a == 'A' && b == 'B' && solveh (b : cs)) || (a == 'B' && b == 'A' && solveh (b : cs))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map solve\n >>> map (\\p -> if p then \"YES\" else \"NO\")\n >>> unlines\n"}], "src_uid": "0b9be2f076cfa13cdc76c489bf1ea416"} {"source_code": "--B. Vova and Trophies\ncitesc_nr :: String -> Int\ncitesc_nr s = read s\n\nsumgold :: [Char] -> Int -> Int\nsumgold xx onlyfans \n | onlyfans < length xx = aux xx 0 0 0\n | otherwise = onlyfans\n where aux [] after before rez = rez\n --after inseamna cate G am de aici incolo\n --before = cate G am pana la imediat precedentul S\n --nu merge \"dinamica\" decat daca am macar un S\n aux ('G':sir) after before rez = aux sir (after+1) before (max rez (min onlyfans (after+1+before+1) ) )\n aux ('S':sir) after before rez = aux sir 0 after rez\n\n\nmain = do\n x <- getLine\n let n = (citesc_nr x) \n sir <- getLine\n let onlyfans = length $ filter (=='G') sir\n print $ sumgold sir onlyfans", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Map.Strict as Map\n\ntoint s = (read s) :: Integer\n\ngo [] a b r = r\ngo ('G':s) a b r =\n go s (a+1) b (max r (a+2+b))\ngo ('S':s) a b r =\n go s 0 a r\n\n\nsolve::String -> String\nsolve ss =\n let _:s:__ = words ss in\n let r1 = go s 0 0 0 in\n let r = min r1 (length $ filter (=='G') s) in\n show(r)++\"\\n\"\n\nmain = do\n interact $ solve"}], "negative_code": [{"source_code": "--B. Vova and Trophies\ncitesc_nr :: String -> Int\ncitesc_nr s = read s\n\nsumgold :: [Char] -> Int -> Int\nsumgold xx onlyfans \n | onlyfans < length xx = aux xx 0 0 0\n | otherwise = onlyfans\n where aux [] after before rez = rez\n --after inseamna cate G am de aici incolo\n --before = cate G am pana la imediat precedentul S\n --nu merge \"dinamica\" decat daca am macar un S\n aux ('G':sir) after before rez = aux sir (after+1) before (max rez (after+1+before+1) )\n aux ('S':sir) after before rez = aux sir 0 after rez\n\n\nmain = do\n x <- getLine\n let n = (citesc_nr x) \n sir <- getLine\n let onlyfans = length $ filter (=='G') sir\n print $ sumgold sir onlyfans"}], "src_uid": "5d9d847103544fa07480fb85c75d0b97"} {"source_code": "{-# OPTIONS -ffi -O2 #-}\n\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl')\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\nreadDouble = unsafeReadDouble\n\nf (a,b) p = (a+p*(1+2*b),p*(1+b))\n\nmain = BS.getLine >> fmap (fst.foldl' f (0.0, 0.0).map readDouble.BS.words) BS.getLine >>= print", "positive_code": [{"source_code": "{-# OPTIONS -ffi #-}\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe (fromJust)\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\n\nf [] = (0,0,0)\nf (s:ss) = ((a + 2*b + 1) * s, (b + 1) * s, q + a * (1-s))\n where (a,b,q) = f ss\nsolve l = a + q\n where (a,_,q) = f s\n s = map (readDouble . LB.pack) $ words l\nmain = do \n l1 <- getLine\n l2 <- getLine\n putStrLn (show (solve l2))\n"}, {"source_code": "{-# OPTIONS -ffi #-}\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe (fromJust)\nimport Data.List (foldl')\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\nreadDouble = unsafeReadDouble\n\nf (a,b) p = (a+p*(1+2*b),p*(1+b))\n\nmain = BS.getLine >> fmap (fst.foldl' f (0.0, 0.0).map readDouble.BS.words) BS.getLine >>= print"}], "negative_code": [], "src_uid": "82bcef8412bb46053d7e163b214bf907"} {"source_code": "import Data.Array.Unboxed\nimport Data.Ix (index)\nmain = do\n n <- read `fmap` getLine\n l <- (map read . words) `fmap` getLine :: IO [Int]\n if all (==1) l then putStrLn \"YES\" else do\n let arr = listArray (0, n-1) l :: UArray Int Int\n nnn = filter (\\i -> mod n i == 0) [2..div n 3]\n f nj = let n1 = n `div` nj in any (\\j -> \n all (\\i -> arr ! (index ((1,1), (n1, nj)) (i, j)) == 1)\n [1..n1]) [1..nj]\n\tputStrLn (if any f nnn then \"YES\" else \"NO\")\n", "positive_code": [{"source_code": "module Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.DeepSeq\nimport Data.Function\nimport Data.List\nimport Data.Array.IArray\nimport Data.Char\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\nprimes :: [Int]\nprimes = 2 : sieve [3..] [ [p*p, p*p+p..] | p <- primes ] where\n sieve (x:xs) t@((q:cs):r)\n | x < q = x : sieve xs t\n | otherwise = sieve (xs `minusOrd` cs) r\n\n-- The lists should be ordered\nminusOrd (x:xs) (y:ys) = case compare x y of\n LT -> x : minusOrd xs (y:ys)\n EQ -> minusOrd xs ys\n GT -> minusOrd (x:xs) ys\nminusOrd xs _ = xs\nunionOrd (x:xs) (y:ys) = case compare x y of\n LT -> x : unionOrd xs (y:ys)\n EQ -> x : unionOrd xs ys\n GT -> y : unionOrd (x:xs) ys\nunionOrd xs [] = xs\nunionOrd [] ys = ys\n\n\n---- Answer Code Section ----\n\ntype MoodArray = Array Int Bool\n\nnon2Factors n = filter (/= 2) factors where\n doublePrimes = map (* 2) primes\n factors = filter (\\p -> n `mod` p == 0) (takeWhile (<= n) primes ++ takeWhile (<= n) doublePrimes)\n\ntryFit :: MoodArray -> Int -> Int -> Int -> Bool\ntryFit moods l d k = and polygon where\n indices = [k, k+d .. l]\n polygon = map (\\i -> moods ! i) indices\n\nprocess :: MoodArray -> Int -> Bool\nprocess moods l = or cases where\n regularNs = non2Factors l\n cases = [ tryFit moods l d k | n <- regularNs, let d = l `div` n, k <- [1..d] ]\n\nint2Bool = \\x -> if x == 1 then True else False\n\nmain = do\n n <- getInt\n moods <- (listArray (1, n) <$> map int2Bool <$> getInts) :: IO MoodArray\n putStrLn $ if process moods n then \"YES\" else \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Array\nimport Data.Array.IO\nimport Data.Foldable (for_)\nimport Data.IORef\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ndivisors :: (Integral a) => a -> [a]\ndivisors num = divisors' num [1..num]\n\twhere\n\t\tdivisors' _ []\t\t\t= []\n\t\tdivisors' n (x:xs)\n\t\t\t| n < x * x\t\t= []\n\t\t\t| n `mod` x == 0\t= x:(n `div` x):divisors' n xs\n\t\t\t| otherwise\t\t= divisors' n xs\n\npolygon = filter (> 2) . divisors \ngetInc x = (map (x `div`)) . polygon $ x\nyesOrNo :: Bool -> String\nyesOrNo x = if x then \"YES\" else \"NO\"\nisPorygon = filter ((>2) . length)\nselect ks x = (\\ x -> map (!!x) ks)\n\n\n{--\n-- printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) .\nmain :: IO ()\nmain = do { (n:ks) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) . isPorygon . concatMap (\\x-> map (\\a->(takeWhile (< n')) . iterate (+ x) $ a)[0..x]) . getInc $ n'\n }\n--}\n--f :: (MArray (Integer,Integer) e m) => Integer -> [e] -> [[[m e]]]\n--f:: Integer -> [Integer] -> IO (IOArray (Int,Int) Integer)\n--f :: (IOArray Integer m0, IOArray Integer []) => Integer -> [Integer] -> IO (IOArray (Int,Int) Integer)\n\n{-\nf n ks = arr 1 --mapM arr ds\n where \n ds = divisors n\n arr x = do { ar <- ar \n ; map (\\ y -> (map (\\ t -> ar `readArray` t) $ (range ((1,y),(m,y))))) $ [1..x]\n }\n where m = (n `div` x)\n ar :: IOArray ((Int,Int) Integer)\n ar = newListArray ((1,1),(m , x)) $ ks \n-} \n\nf n ks = concatMap arr ds\n where \n ds = divisors n\n arr x = (filter ((>2) . length)) . (filter (all (==1))) . map (\\ y -> (map (ar!) $ (range ((1,y),(m,y))))) $ [1..x]\n where m = (n `div` x)\n ar = listArray ((1,1),(m , x)) $ ks \n\n\n \n\nmain = do {(n:ks:_) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\" . yesOrNo . any (not .null) $ ((f n') $ ks)\n --(mapM_ (mapM_ (fmap print))) ( (f n') $ ks)\n }\n\n\n\n--map (kuku !) (range ((3,3),(5,5))) \n\n\nkuku = newListArray ((1,1),(9,9)) [i*j| i <- [1..9], j <- [1..9]] :: IO (IOArray (Int,Int) Integer)\n\n"}, {"source_code": "import List\nimport Array\n\nnextSimple :: Int -> Int\nnextSimple n = head (filter (\\x -> 2 == length (filter (\\y -> 0 == mod x y) [1..x])) [(n+1)..])\n\nfactorization :: Int -> [(Int, Int)]\nfactorization n = reverse (factorization_ n 2 [])\n where\n factorization_ :: Int -> Int -> [(Int, Int)] -> [(Int, Int)]\n factorization_ 1 _ result = result\n factorization_ n simple result\n | n < 1 = error \"factorization: Arg must be positive number.\" \n | mod n simple == 0 \n && length result == 0 = factorization_ (div n simple) simple [(simple, 1)]\n | mod n simple == 0\n && divisor == simple = factorization_ (div n simple) simple ((simple, power + 1) : (tail result))\n | mod n simple == 0 = factorization_ (div n simple) simple ((simple, 1) : result)\n | simple^2 > n = (n, 1) : result\n | otherwise = factorization_ n (nextSimple simple) result\n where\n divisor = fst (head result)\n power = snd (head result)\n \nsimpleDivisors :: Int -> [Int]\nsimpleDivisors n = map fst (factorization n)\n\nremoveFirstTwo :: [Int] -> [Int]\nremoveFirstTwo (2:xs) = xs\nremoveFirstTwo xs = xs\n\ngoodDivisors :: Int -> [Int]\ngoodDivisors n = sort (del4 ++ others)\n where\n del4 = if mod n 4 == 0 then [4] else []\n others = removeFirstTwo (simpleDivisors n)\n\ngetElements :: Array Int e -> Int -> Int -> [e]\ngetElements array start step = map (\\ix -> (!) array ix) [start, start + step .. last]\n where\n last = snd (bounds array)\n\nreadInts :: IO [Int]\nreadInts = do\n line <- getLine\n return (map read (words line))\n \ngetSize :: Array Int e -> Int\ngetSize array = snd (bounds array) + 1\n \ngoodPolygon :: Array Int Bool -> Int -> Bool\ngoodPolygon array polygon = or (map (\\x -> and (getElements array x m)) [0..m - 1])\n where\n n = getSize array\n m = div n polygon\n \nsolve :: Array Int Bool -> Bool\nsolve array = or (map (goodPolygon array) (goodDivisors n))\n where\n n = getSize array\n \nprintAns :: Bool -> IO ()\nprintAns True = putStrLn \"YES\"\nprintAns False = putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn::(IO Int)\n xs <- readInts\n printAns (solve (listArray (0, n - 1) (map (>0) xs)))"}], "negative_code": [{"source_code": "module Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.DeepSeq\nimport Data.Function\nimport Data.List\nimport Data.Array.IArray\nimport Data.Char\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\ntype MoodArray = Array Int Bool\n\nprimes :: [Int]\nprimes = filterPrime [2..]\n where filterPrime (p:xs) = p : filterPrime [x | x <- xs, x `mod` p /= 0]\n\nfactors n = filter (\\p -> n `mod` p == 0) $ takeWhile (<= n) primes\n\ntryFit :: MoodArray -> Int -> Int -> Int -> Bool\ntryFit moods l d k = and polygon where\n indices = [k, k+d .. l]\n polygon = map (\\i -> moods ! i) indices\n\nprocess :: MoodArray -> Int -> Bool\nprocess moods l = or cases where\n regularNs = filter (2 /=) (factors l)\n cases = [ tryFit moods l d k | n <- regularNs, l `mod` n == 0, let d = l `div` n, k <- [1..d] ]\n\nint2Bool = \\x -> if x == 1 then True else False\n\nmain = do\n n <- getInt\n moods <- (listArray (1, n) <$> map int2Bool <$> getInts) :: IO MoodArray\n putStrLn $ if process moods n then \"YES\" else \"NO\"\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ndivisors :: (Integral a) => a -> [a]\ndivisors num = divisors' num [1..num]\n\twhere\n\t\tdivisors' _ []\t\t\t= []\n\t\tdivisors' n (x:xs)\n\t\t\t| n < x * x\t\t= []\n\t\t\t| n `mod` x == 0\t= x:(n `div` x):divisors' n xs\n\t\t\t| otherwise\t\t= divisors' n xs\n\n\npolygon = filter (> 2) . divisors \n\n\n\ngetInc x = (map (x `div`)) . polygon $ x\nyesOrNo :: Bool -> String\nyesOrNo x = if x then \"YES\" else \"NO\"\n\n\nmain :: IO ()\nmain = do { (n:ks) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) . map (\\ x -> (takeWhile (< n')) . iterate (+ x) $ 0) . getInc $ n'\n }\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ndivisors :: (Integral a) => a -> [a]\ndivisors num = divisors' num [1..num]\n\twhere\n\t\tdivisors' _ []\t\t\t= []\n\t\tdivisors' n (x:xs)\n\t\t\t| n < x * x\t\t= []\n\t\t\t| n `mod` x == 0\t= x:(n `div` x):divisors' n xs\n\t\t\t| otherwise\t\t= divisors' n xs\n\npolygon = filter (> 2) . divisors \ngetInc x = (map (x `div`)) . polygon $ x\nyesOrNo :: Bool -> String\nyesOrNo x = if x then \"YES\" else \"NO\"\n\n-- printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) .\nmain :: IO ()\nmain = do { (n:ks) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\" . yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) . filter ((>2) . length) . concatMap (\\ x -> map (\\a->(takeWhile (< n')) . iterate (+ x) $ a)[0..n']) . getInc $ n'\n }\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ndivisors :: (Integral a) => a -> [a]\ndivisors num = divisors' num [1..num]\n\twhere\n\t\tdivisors' _ []\t\t\t= []\n\t\tdivisors' n (x:xs)\n\t\t\t| n < x * x\t\t= []\n\t\t\t| n `mod` x == 0\t= x:(n `div` x):divisors' n xs\n\t\t\t| otherwise\t\t= divisors' n xs\n\n\npolygon = filter (> 2) . divisors \n\n\n\ngetInc x = (map (x `div`)) . polygon $ x\nyesOrNo :: Bool -> String\nyesOrNo x = if x then \"YES\" else \"NO\"\n\n\nmain :: IO ()\nmain = do { (n:ks) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\" . yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) . map (\\ x -> (takeWhile (< n')) . iterate (+ x) $ 0) . getInc $ n'\n }\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Array\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ndivisors :: (Integral a) => a -> [a]\ndivisors num = divisors' num [1..num]\n\twhere\n\t\tdivisors' _ []\t\t\t= []\n\t\tdivisors' n (x:xs)\n\t\t\t| n < x * x\t\t= []\n\t\t\t| n `mod` x == 0\t= x:(n `div` x):divisors' n xs\n\t\t\t| otherwise\t\t= divisors' n xs\n\npolygon = filter (> 2) . divisors \ngetInc x = (map (x `div`)) . polygon $ x\nyesOrNo :: Bool -> String\nyesOrNo x = if x then \"YES\" else \"NO\"\nisPorygon = filter ((>2) . length)\nselect ks x = (\\ x -> map (!!x) ks)\n\n\n{--\n-- printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) .\nmain :: IO ()\nmain = do { (n:ks) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) . isPorygon . concatMap (\\x-> map (\\a->(takeWhile (< n')) . iterate (+ x) $ a)[0..x]) . getInc $ n'\n }\n--}\nf n ks = map arr ds\n where \n ds = divisors n\n arr x = let a = listArray ((1,1),(m , x)) $ ks in\n map (a!) $ (range ((1,1),(m,1)))\n where m = (n `div` x)\n\nmain = do {(n:ks:_) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\". yesOrNo . any(==True) . map (all $ (== 1)) . filter((>2) .length) . f n' $ ks\n }"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\ndivisors :: (Integral a) => a -> [a]\ndivisors num = divisors' num [1..num]\n\twhere\n\t\tdivisors' _ []\t\t\t= []\n\t\tdivisors' n (x:xs)\n\t\t\t| n < x * x\t\t= []\n\t\t\t| n `mod` x == 0\t= x:(n `div` x):divisors' n xs\n\t\t\t| otherwise\t\t= divisors' n xs\n\npolygon = filter (> 2) . divisors \ngetInc x = (map (x `div`)) . polygon $ x\nyesOrNo :: Bool -> String\nyesOrNo x = if x then \"YES\" else \"NO\"\n\n-- printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) .\nmain :: IO ()\nmain = do { (n:ks) <- map (map read) . map split . lines <$> getContents\n ; let n' = head $ n in\n printf \"%s\\n\". yesOrNo . any(==True). map (all (== 1)) . map (concatMap (\\ x -> map (!!x) ks)) . concatMap (\\ x -> map (\\a->(takeWhile (< n')) . iterate (+ x) $ a)[0..n']) . getInc $ n'\n }\n\n"}], "src_uid": "d3a0402de1338a1a542a86ac5b484acc"} {"source_code": "import Data.List\nimport Data.Ord\nimport System.IO\n\ntype Long = Integer\n\nparseLong :: IO [Long]\nparseLong = fmap (map read . words) getLine\n\nsolve :: [Long] -> Long -> Int -> Long\nsolve a h l = if l == 1 then (max 1 $ h)\n else delta + (solve (tail a) (h - delta) (l - 1)) where delta = max 1 (h - a !! 1)\n \nsortDescending = sortBy (comparing Down)\n \nmain :: IO ()\nmain = do\n [n, m] <- parseLong\n a <- parseLong\n print $ sum a - (solve (sortDescending a) (maximum a) (length a))\n", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ngo [] a r = r + max a 0\ngo (x:xs) a r =\n\tgo xs (min a x - 1) $ r + max (a-x) 0 + 1\n\ndoit a =\n\tlet mx = maximum a in\n\tsum a - go (reverse $ sort a) mx 0\n\nsolve::String -> String\nsolve ss =\n\tlet n:m:a = map toint $ words ss in\n\tshow(doit a)++\"\\n\"\n\nmain = do\n interact $ solve"}, {"source_code": "import Data.List\n\nmain = do\n input <- getContents\n process input\n\nprocess :: String -> IO ()\nprocess s = print (solve (parse s))\n\nparse :: String -> [Integer]\nparse s = case words s of (n:m:a) -> map read a\n _ -> []\n\nsolve :: [Integer] -> Integer\nsolve a = f 0 (sort a)\n\n-- First argument: height of the combined remaining block so far.\n-- Second argument: remainder of the stack list.\nf :: Integer -> [Integer] -> Integer\n-- For the last element we have to make the combined stack as high as the last stack. But if we were\n-- already at the right height, we have to keep one block in order not to have an empty stack\nf h (ai:[]) = h - if ai == h then 1 else 0\n-- For an element that is not the last we try to grow the combined stack by one and remove every\n-- unecessary block\nf h (ai:a) = ai - 1 + f (if ai == h then h else h + 1) a\nf _ _ = 0\n\n-- Stacks having only one block cannot have any block removed from them. I have a feeling that\n-- stacks should be iterated over in sorted order. We can climb one block at a time and keep\n-- every necessary remaining block in the last (and therefore highest) stack.\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Data.Int\nimport System.IO\n\ntype Long = Int64\n\nparseLong :: IO [Long]\nparseLong = fmap (map read . words) getLine\n\nsolve :: [Long] -> Long -> Int -> Long\nsolve a h l = if l == 1 then (max 1 $ h)\n else delta + (solve (tail a) (h - delta) (l - 1)) where delta = max 1 (h - a !! 1)\n \nsortDescending = sortBy (comparing Down)\n \nmain :: IO ()\nmain = do\n [n, m] <- parseLong\n a <- parseLong\n print $ foldr (+) 0 a - (solve (sortDescending a) (maximum a) (length a))\n"}], "negative_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Int\n\ngo [] a r = r + max a 0\ngo (x:xs) a r =\n\tgo xs (min a x - 1) $ r + max (a-x) 0 + 1\n\ndoit a =\n\tlet mx = maximum a in\n\tsum a - go (reverse $ sort a) mx 0\n\nsolve::String -> String\nsolve ss =\n\tlet n:m:a = map toint $ words ss in\n\tshow(doit a)++\"\\n\"\n\nmain = do\n interact $ solve"}, {"source_code": "import Data.List\nimport Data.Ord\nimport System.IO\n\nparseInt :: IO [Int]\nparseInt = fmap (map read . words) getLine\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve a h l = if l == 1 then max 1 h\n else delta + (solve (tail a) (h - delta) (l - 1)) where delta = max 1 (a !! 0 - a !! 1)\n \nsortDescending = sortBy (comparing Down)\n \nmain :: IO ()\nmain = do\n [n, m] <- parseInt\n a <- parseInt\n print $ foldl (+) 0 a - (solve (sortDescending a) (maximum a) (length a))\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport System.IO\n\nparseInt :: IO [Int]\nparseInt = fmap (map read . words) getLine\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve a h l = if l == 1 then max 1 h\n else delta + (solve (tail a) (h - delta) (l - 1)) where delta = max 1 (h - a !! 1)\n \nsortDescending = sortBy (comparing Down)\n \nmain :: IO ()\nmain = do\n [n, m] <- parseInt\n a <- parseInt\n print $ foldl (+) 0 a - (solve (sortDescending a) (maximum a) (length a))\n"}], "src_uid": "ffa76f2558c8a70ab5c1ecb9e8561f25"} {"source_code": "\n\neeuclid :: Integer -> Integer -> (Integer, Integer, Integer)\neeuclid a 0 = (1, 0, a)\neeuclid a b | a < b = (m, n, d) where (n, m, d) = eeuclid b a\neeuclid a b = (m, n-q*m, g) where\n (q,r) = a `quotRem` b\n (m,n,g) = eeuclid r b\n \ns[a,b,c]\n | c `mod` g /= 0 = [-1]\n | otherwise = [-(signum a * x * (c`div`g)), -(signum b * y*(c`div`g))]\n where \n (x,y,g)=eeuclid (abs a) (abs b) -- x*a + y*b = g\n \nmain=interact$unwords.map show.s.map read.words", "positive_code": [{"source_code": "import qualified Data.Tuple as Tup\n\nmaxPerm = truncate (5* 10 ** 18)\n\nmain = do\n line <- getLine\n let [a, b, c] = map read $ words line\n putStrLn $ formatter a b c\n\nformatter :: Integer -> Integer -> Integer -> String\nformatter a b c = case formatter' a b (-c)\n of Just (x, y) | abs x <= maxPerm && abs y <= maxPerm -> show x ++ \" \" ++ show y\n otherwise -> show $ -1\n\n-- special cases\nformatter' 0 b c = case c `divMod` b \n of (q, 0) -> Just (0, q)\n (_, _) -> Nothing\nformatter' a 0 c = case c `divMod` a\n of (q, 0) -> Just (q, 0)\n (_, _) -> Nothing\nformatter' a b 0 = Just (0, 0)\nformatter' a b c \n | c `mod` b == 0 = Just (0, c `div` b)\n | c `mod` a == 0 = Just (c `div` a, 0)\n | a == max a b = solve a b c\n | otherwise = fmap Tup.swap $ solve b a c\n\n-- assumes a > b\n-- solve :: Int -> Int -> Int -> Maybe (Int, Int)\nsolve a b c = let (g, x', y') = goEuclid a b\n in if c `mod` g == 0\n then Just (x' * (c `div` g), y' * (c `div` g))\n else Nothing\n\ngoEuclid a b = let (r0, r1) = (max a b, min a b)\n in euclidExt r0 r1 1 0 0 1\n\n-- returns (gcd, x, y)\neuclidExt r0 r1 s0 s1 t0 t1 = if r2 == 0\n then (r1, s1, t1)\n else euclidExt r1 r2 s1 s2 t1 t2\n where (q, r2) = r0 `divMod` r1\n s2 = s0 - q * s1\n t2 = t0 - q * t1\n"}, {"source_code": "\nimport Monad (liftM)\nimport Prelude hiding (print)\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\n\ngcd' :: Integral a => a -> a -> (a, (a, a))\ngcd' 0 b = (b, (0, 1))\ngcd' a b = (d, (y1 - x1 * div b a, x1))\n where\n (d, (x1, y1)) = gcd' (mod b a) a\n\ndiofant :: Integral a => a -> a -> a -> Maybe (a, (a, a))\ndiofant a b c\n | mod c g == 0 = Just (g, (signum a * x * div (-c) g, signum b * y * div (-c) g))\n | otherwise = Nothing\n where\n (g, (x, y)) = gcd' (abs a) (abs b)\n\nbounds :: Integral a => (a, a)\nbounds = (-m, m)\n where\n m = 5 * 10^18\n\nsolve :: Integral a => [a] -> Maybe (a, a)\nsolve [a, b, c]\n | a == 0 && b == 0 = (c == 0) ? Just (0, 0) $ Nothing\n | a == 0 = (mod (-c) b == 0) ? Just (0, div (-c) b) $ Nothing\n | b == 0 = (mod (-c) a == 0) ? Just (div (-c) a, 0) $ Nothing\n | otherwise = do\n (g, (x0, y0)) <- diofant a b c\n let (kxMin, kxMax) = getKx bounds x0 g\n let (kyMin, kyMax) = getKy bounds y0 g\n let (kMin, kMax) = (max kxMin kyMin, min kxMax kyMax)\n k <- (kMin <= kMax) ? return kMin $ fail \"\"\n return (x0 + k * div b g, y0 - k * div a g)\n where\n getKx (xMin, xMax) x0 g\n | b > 0 = (1 + div (xMin - x0 - 1) (div b g), div (xMax - x0) (div b g))\n | b < 0 = ((-1) * div (xMax - x0) (div (-b) g), (-1) * (1 + div (xMin - x0 - 1) (div (-b) g)))\n getKy (yMin, yMax) y0 g\n | a > 0 = (1 + div (y0 - yMax - 1) (div a g), div (y0 - yMin) (div a g))\n | a < 0 = ((-1) * div (y0 - yMin) (div (-a) g), (-1) * (1 + div (y0 - yMax - 1) (div (-a) g)))\n\nprint :: Show a => Maybe (a, a) -> IO ()\nprint Nothing = putStrLn \"-1\"\nprint (Just (a, b)) = putStrLn (show a ++ \" \" ++ show b)\n\nmain :: IO ()\nmain = liftM (map read . words) getLine >>= print . solve\n"}, {"source_code": "-- Codeforces 7C\n\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.Int\n\nmain :: IO ()\nmain = do\n [a, b, c] <- (map read . words) <$> getLine\n let !(d, x, y) = exgcd a b\n !t = c `div` d\n if c `mod` d /= 0\n then print (-1)\n else putStrLn . unwords . map show $ [- x * t, - y * t]\n\nexgcd :: Integer -> Integer -> (Integer, Integer, Integer)\nexgcd !a !0 = (a, 1, 0)\nexgcd !a !b = let !(d, x, y) = exgcd b (a `mod` b)\n in (d, y, x - y * (a `div` b))\n"}, {"source_code": "import Control.Exception\n\nex_gcd a b\n\t| b==0 = (1,0,a)\n\t| otherwise = (a'',b'',r)\n\t\twhere\n\t\t\t(a',b',r) = ex_gcd b (a `mod` b)\n\t\t\ta'' = b'\n\t\t\tb'' = a' - b' * (a `div` b)\n\nsolve a b c = (a'*c, b'*c)\n\twhere\n\t\t(a',b',g) = ex_gcd a b\n\npprint a b c = \n\tif (c `mod` g) /= 0 then show (-1) else show x ++ \" \" ++ show y\n\t\twhere\n\t\t\t(x,y) = solve a' b' c'\n\t\t\t(_,_,g) = ex_gcd a b\n\t\t\t[a',b',c'] = map (`div` g) [a,b,c]\n\nmain = do\n\t[a,b,c'] <- (map read . words) `fmap` getLine\n\tlet c = -c'\n\tputStrLn $ pprint a b c\n"}, {"source_code": "gcd_ext :: Integer -> Integer -> (Integer, Integer, Integer)\ngcd_ext a 0 = (a, 1, 0)\ngcd_ext a b = \n\tlet (g, x, y) = gcd_ext b (a `mod` b)\n\tin (g, y, x - a `div` b * y)\n\nsolve :: (Integer, Integer, Integer) -> Maybe (Integer, Integer)\nsolve (a, b, c) = \n\tlet (g, x, y) = gcd_ext a b\n\tin if c `mod` g == 0 then Just (x * c `div` (-g), y * c `div` (-g))\n\t\telse Nothing\n\noutput :: Maybe (Integer, Integer) -> String\noutput Nothing = \"-1\"\noutput (Just (x, y)) = (show x) ++ \" \" ++ (show y)\n\ninput :: [Integer] -> (Integer, Integer, Integer)\ninput s = (s !! 0, s !! 1, s !! 2)\n\nmain = do \n\tl <- getLine\n\tputStrLn $ output $ solve $ input $ map (read :: String -> Integer) $ words l\n"}, {"source_code": "module Main where\n\nimport Data.Maybe (maybe)\n\nmain :: IO ()\nmain = interact $ maybe \"-1\" (\\(x,y) -> show x <> \" \" <> show y) . solve . ints\n\nints :: String -> [Integer]\nints = map read . words\n\nsolve :: [Integer] -> Maybe (Integer, Integer)\nsolve [a, b, c]\n | c `mod` g == 0 = Just (signum a * s * cg, signum b * t * cg)\n | otherwise = Nothing\n where\n (s, t, g) = gcd' (abs a) (abs b)\n cg = -(c `div` g)\n\ngcd' :: (Integral a) => a -> a -> (a, a, a)\ngcd' a 0 = (1, 0, a)\ngcd' a b | a < b = (m, n, d) where (n, m, d) = gcd' b a\ngcd' a b = (t, s - q * t, g) where\n (q, r) = a `quotRem` b\n (s, t, g) = gcd' b r"}], "negative_code": [{"source_code": "-- Codeforces 7C\n\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.Int\n\nmain :: IO ()\nmain = do\n [a, b, c] <- (map read . words) <$> getLine\n let !(d, x, y) = exgcd a b\n !t = c `div` d\n putStrLn . unwords . map show $ [- x * t, - y * t]\n\nexgcd :: Int64 -> Int64 -> (Int64, Int64, Int64)\nexgcd !a !0 = (a, 1, 0)\nexgcd !a !b = let !(d, y, x) = exgcd b (a `rem` b)\n in (d, x, y - x * (a `div` b))\n"}, {"source_code": "-- Codeforces 7C\n\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.Int\n\nmain :: IO ()\nmain = do\n [a, b, c] <- (map read . words) <$> getLine\n let !(d, x, y) = exgcd a b\n !t = c `div` d\n if c `mod` d /= 0\n then print (-1)\n else putStrLn . unwords . map show $ [- x * t, - y * t]\n\nexgcd :: Int64 -> Int64 -> (Int64, Int64, Int64)\nexgcd !a !0 = (a, 1, 0)\nexgcd !a !b = let !(d, y, x) = exgcd b (a `rem` b)\n in (d, x, y - x * (a `div` b))\n"}, {"source_code": "\n\neeuclid :: Integer -> Integer -> (Integer, Integer, Integer)\neeuclid a 0 = (1, 0, a)\neeuclid a b | a < b = (m, n, d) where (n, m, d) = eeuclid b a\neeuclid a b = (m, n-q*m, g) where\n (q,r) = a `quotRem` b\n (m,n,g) = eeuclid r b\n \ns[a,b,c]\n | c `mod` g /= 0 = [-1]\n | otherwise = [x * (c`div`g), y*(c`div`g)]\n where \n (x,y,g)=eeuclid a b -- x*a + y*b = g\n \nmain=interact$unwords.map show.s.map read.words"}], "src_uid": "a01e1c545542c1641eca556439f0692e"} {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n let num = 10 ^ (n-1)\n m = num `mod` 210\n answer = if (n < 3) then -1 else num + (210 - m)\n print answer", "positive_code": [{"source_code": "main=readLn>>=print.f\nf n|n<3= -1|0<1=((10^(n-1)+209)`div`210)*210\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n\ngetPowTen :: Integer -> Integer\ngetPowTen a = 10 ^ a\n\t\ngetDiv210 :: Integer -> Integer\ngetDiv210 a\n\t| mod a 210 == 0\t= a\n\t| otherwise \t\t= getDiv210 (a + 10)\n\t\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet n = read (str)\n\tif (n == 1 || n == 2)\n\t\tthen putStrLn \"-1\"\n\t\telse putStrLn (show (getDiv210 (getPowTen (n - 1))))\n"}, {"source_code": "main=readLn>>=print.f\nf n|n<3= -1|0<1=(10^(n-1)`div`210+1)*210"}, {"source_code": "\nas = [3,2,6,4,5,1]\n\nsolve :: Int -> String\nsolve 1 = \"-1\"\nsolve 2 = \"-1\"\nsolve 3 = \"210\"\nsolve n = '1' : (replicate m '0') ++ (show d)\n where\n a = as !! ((n - 2) `mod` 6)\n d = head $ dropWhile (\\y -> 7 /= a + y `mod` 7) [20, 50 .. 1000]\n m = n - 1 - length (show d)\n\nmain :: IO ()\nmain = readLn >>= putStrLn . solve"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- readLn :: IO Int\n let num = product $ replicate (n-1) 10\n m = num `mod` 210\n answer = if (n < 3) then -1 else num + (210 - m)\n print answer"}, {"source_code": "main = interact $ show . solve . read\n\nsolve n | n < 3 = -1\n | otherwise = t + 210 - (mod t 210) where t = 10^(n - 1)"}, {"source_code": "main=readLn>>=print.f\nf :: Int -> Integer\nf n|n<3= -1|0<1=head$filter((0==).(`mod`210))[10^(n-1),10^(n-1)+2..]"}, {"source_code": "main = do\n n <- readLn\n if n < 3 then print (-1)\n else let low = 10 ^ (n - 1) in \n print (head $ [x | x <- [low, low+2..], x `mod` 210 == 0])\n"}, {"source_code": "module Main where\n\nreadInt :: IO Integer\nreadInt = readLn\n\nsolve :: Integer -> Integer\nsolve n | n < 3 = (-1)\n | otherwise = let base = 10 ^ (n - 1)\n mod_ = base `mod` 210 in\n if mod_ > 0 then base + 210 - mod_\n else base\n\nmain = do\n strn <- readInt\n print $ solve strn\n"}, {"source_code": "main = interact $ show . f . read where\n f n\n | n < 3 = -1\n | otherwise = 210 * (div (10^(n-2)+20) 21)\n"}, {"source_code": "main = getLine>>=(\\n->pp (read n)$((10^(read n-1)+209)`div`210)*210)\npp n y=print$if length(show y)==n then y else -1\n"}, {"source_code": "main=readLn>>=print.f\nf n|n<3= -1|0<1=(10^(n-1)`div`210+1)*210\n"}, {"source_code": "import Control.Applicative\nmain = do\n n <- read <$> getLine\n let y = ((10^(n-1)+209)`div`210)*210\n print $ if length (show y) == n then y else -1\n"}, {"source_code": "main=readLn>>=print.f 210\nf z n|n<3= -1|0<1=10^(n-1)`div`z*z+z\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- readLn :: IO Int\n let num = pow 10 (n-1)\n m = num `mod` 210\n answer = if (n < 3) then -1 else num + (210 - m)\n print answer\n \npow x n = binaryPow n 1\n where\n binaryPow 1 acc = acc\n binaryPow n acc = if n `mod` 2 == 0 then binaryPow (n `div` 2) (acc*acc) else binaryPow (n-1) (acc*x)"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\n\nmain = do\n n <- readLn :: IO Int\n let num = product $ replicate (n-1) 10\n m = num `mod` 210\n answer = num + (210 - m)\n print answer"}], "src_uid": "386345016773a06b9e190a55cc3717fa"} {"source_code": "module Main where\n\ndata Tree = Node Tree Tree\n | Leaf Int\n deriving (Show)\n\nbuildTree :: String -> Tree\nbuildTree = buildTree' . zip [1..]\n where buildTree' [] = Leaf (-1)\n buildTree' ((n,c):xs) | c == 'l' = Node (buildTree' xs) (Leaf n)\n | otherwise = Node (Leaf n) (buildTree' xs)\n\npreorder :: Tree -> [Int]\npreorder tree = reverse $ preorder' tree []\n where preorder' (Leaf leaf) xs = if leaf == -1 then xs else leaf:xs\n preorder' (Node left right) xs = preorder' right $ preorder' left xs\n\nmain = do\n line <- getLine\n putStrLn (unlines . map show . preorder $ buildTree line)\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport Data.Foldable\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n ds <- getLine\n\n let\n f i [] = Seq.empty\n f i ('l':ds) = (f (i+1) ds) Seq.|> i\n f i ('r':ds) = i Seq.<| (f (i+1) ds)\n\n putStr $ unlines $ map show $ toList (f 1 ds)\n"}, {"source_code": "import Data.Array.ST;\nimport Control.Monad;\nimport Control.Monad.ST;\n\nfindPos :: String -> ST s [Integer]\nfindPos stones = do\n let l = fromIntegral $ length stones\n pos <- newArray_ (1, l) :: ST s (STArray s Integer Integer)\n let placeStone (stoneIdx, lowIdx, highIdx) stone =\n case stoneIdx `seq` lowIdx `seq` highIdx `seq` stone of\n 'l' -> do\n writeArray pos highIdx stoneIdx\n return (stoneIdx + 1, lowIdx, highIdx - 1)\n 'r' -> do\n writeArray pos lowIdx stoneIdx\n return (stoneIdx + 1, lowIdx + 1, highIdx)\n _ -> error \"Illegal character\"\n foldM_ placeStone (1, 1, l) stones\n getElems pos\n\nmain :: IO ()\nmain = do\n o <- getLine\n let ord = runST $ findPos o\n forM_ ord print\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Char8 as B\nimport Data.Sequence (Seq,(<|),(|>),(><),ViewL(..),ViewR(..),viewl,viewr)\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\n\nmain = B.getLine >>= putStr . unlines . map show . F.toList . solve\n\nsolve bs = go 1 bs\n where\n go !i !bs\n | B.null bs = Seq.empty\n | B.head bs == 'l' = (go (i+1) $ B.tail bs)|>i\n | B.head bs == 'r' = i<|(go (i+1) $ B.tail bs)\n | otherwise = Seq.empty\n"}], "negative_code": [], "src_uid": "9d3c0f689ae1e6215448463def55df32"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Data.Array.Unboxed (UArray, array, (!))\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\nimport qualified Data.ByteString.Char8 as C\n\ndoy :: UArray (Int, Int) Int\ndoy = array ((1,1), (12,31)) $ zip mmdd $ map (*day) [0 ..]\n where\n dom = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n day = 24 * 60 * 60\n mmdd = [(m, d) | (m, n) <- zip [1 .. ] dom, d <- [1 .. n]]\n\nnewtype State a = State {\n runState :: C.ByteString -> (a, C.ByteString)\n }\n\ninstance Monad State where\n return a = State $ \\st -> (a, st)\n m >>= f = State $ \\st -> let (a', st') = runState m st in runState (f a') st'\n\nget = State $ \\st -> (st, st)\nmodify f = State $ \\st -> ((), f st)\n\nparse :: State Int\nparse = do\n modify $ C.drop 4\n mm <- readInt\n dd <- readInt\n h <- readInt\n m <- readInt\n s <- readInt\n -- trace (show (mm, dd, h, m, s)) $\n return $ doy!(mm,dd) + (h * 60 + m) * 60 + s\n where\n readInt = State $ fromJust . C.readInt . C.tail\n\ngao n m a = go b $ drop (m - 1) b\n where\n b = map (\\i -> (fst $ runState parse i, i)) a\n go _ [] = \"-1\"\n go (a:ax) (b:bx) =\n if fst b - fst a < n\n then C.unpack $ C.take 19 $ snd b\n else go ax bx\n\nmain = do\n [n, m] <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n logs <- fmap C.lines $ C.getContents\n putStrLn $ gao n m logs\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,m] <- map read.words <$> getLine\n logs <- map parse.B.lines <$> B.getContents\n B.putStrLn $ solve n m logs\n\nparse :: B.ByteString -> (Int,B.ByteString)\nparse bs0 = num`seq`(num,bs1)\n where\n f c = if c=='-'||c==':' then ' ' else c\n bs1 = B.take 19 bs0\n num = calc.map readInt.tail.B.words.B.map f $! bs1\n calc [mm,dd,h,m,s] = (((mm2dd+dd)*24+h)*60+m)*60+s\n where\n mm2dd = [0,31,60,91,121,152,182,213,244,274,305,335]!!(mm-1)\n calc ns = error $ show ns \n\nsolve :: Int -> Int -> [(Int,B.ByteString)] -> B.ByteString\nsolve n m logs = safeHead.map snd.filter fst.zipWith f logs $ drop (m-1) logs\n where\n f (t0,msg0) (t1,msg1) = (t1 getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, m] <- readInts\n a <- readInts\n putStrLn $ if m == sum a\n then \"YES\"\n else \"NO\"\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nsolveCase :: (Int, [Int]) -> String\nsolveCase (m, xs)\n | sum xs == m = \"YES\"\n | otherwise = \"NO\"\n\nreadCase :: IO (Int, [Int])\nreadCase = do\n [_, m] <- map read . words <$> getLine\n xs <- map read . words <$> getLine\n return (m, xs)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n answer <- map solveCase <$> replicateM t readCase\n putStr $ unlines answer\n"}], "negative_code": [], "src_uid": "941adee47c2a28588ebe7dfe16e0c91a"} {"source_code": "import Data.Char\nimport Data.List\nimport Control.Monad\n\n-- a + trSum(ans) - x = b + x\n-- a + trSum(ans) - b = 2x\n-- x has to non negative for a valid ans\n\ntrSum :: Integer -> Integer\ntrSum n = (n * (n + 1)) `div` 2\n\nsolve :: Integer -> [Integer] -> Integer\nsolve ans [a,b]\n | x < 0 || x `mod` 2 /= 0 = solve (ans + 1) [a,b]\n | otherwise = ans\n where x = (a + (trSum ans) - b) \nsolve _ _ = 0\n\n-- putStrLn :: String -> IO ()\nmain :: IO ()\nmain = do\n input <- getContents\n putStrLn $ unlines . map (show . solve 0) . map (sort . map read . words) . tail . lines $ input\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Control.Monad (replicateM)\nimport qualified Data.Set as S\nimport qualified Data.Map.Strict as MS\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = do\n n <- bInt <$> B.getLine\n xs <- map (show . diff . (map bInt . B.words)) <$> replicateM n B.getLine\n putStr (unlines xs)\n\nbInt = fst . fromJust . B.readInt\n\ndiff :: [Int] -> Int\ndiff (x:y:_) = f sums where\n d = abs (x-y)\n l = floor . max 0 . (\\x -> 1+x/2) . sqrt . fromIntegral $ (4*d+1)\n sums = [(i, (i * (i + 1)) `div` 2) | i <- [l-1 ..]]\n f ((i, x):xs) = if (x >= d) && (x `mod` 2 == d `mod` 2) then i else f xs\n\nsums = [(i, (i * (i + 1)) `div` 2) | i <- [0 .. 44722]]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Control.Monad (replicateM)\nimport qualified Data.Set as S\nimport qualified Data.Map.Strict as MS\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = do\n n <- bInt <$> B.getLine\n xs <- map (show . diff . (map bInt . B.words)) <$> replicateM n B.getLine\n putStr (unlines xs)\n\nbInt = fst . fromJust . B.readInt\n\ndiff :: [Int] -> Int\ndiff (x:y:_) = f sums where\n d = abs (x-y)\n l = floor . max 0 . (\\x -> 1+x/2) . sqrt . fromIntegral $ (4*d+1)\n sums = (0,0):[(i, (i * (i + 1)) `div` 2) | i <- [l ..]]\n f ((i, x):xs) = if (x >= d) && (x `mod` 2 == d `mod` 2) then i else f xs\n\nsums = [(i, (i * (i + 1)) `div` 2) | i <- [0 .. 44722]]\n\n"}], "src_uid": "29e84addbc88186bce40d68cf124f5da"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.List (groupBy, sortBy)\nimport Data.Function (on)\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tgetLine\n\tpeople <- map ((\\[a, b, c] -> (unpack a, readInt' b, readInt' c)) . words) . lines <$> getContents\n\n\tlet\n\t\tselect [(name1, _, _), (name2, _, _)] = name1 ++ \" \" ++ name2\n\t\tselect ((name1, _, score1):(name2, _, score2):(name3, _, score3):_) = if score2 == score3 then \"?\" else name1 ++ \" \" ++ name2\n\n\tputStr . unlines . map (select . reverse) . groupBy ((==) `on` (\\(_, a, _) -> a)) $ sortBy (compare `on` (\\(a, b, c) -> (b, c))) people\n \t\n", "positive_code": [{"source_code": "import Data.List (foldl',sort)\nimport Control.Monad\nimport Data.IntMap hiding (map,foldl')\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n l <- (forM [1..n] $ \\i -> do\n [name,region,rank] <- fmap (words . B.unpack) B.getLine\n return (read region,(-(read rank),name)) :: IO (Int,(Int,String)))\n let a = foldl' (\\mp (k,v) -> update (\\il -> return (v:il)) k mp) (fromList (zip [1..m] (repeat []))) l\n ls = elems a\n forM_ ls $ \\i -> do\n let (x:xs) = take 3 (sort i)\n if and[length (x:xs) > 2,all (\\(a,_) -> a == fst (head xs)) (take 2 xs)]\n then putStrLn \"?\"\n else putStrLn (snd x ++ \" \" ++ snd (xs!!0))\n"}, {"source_code": "{- ok -}\nimport Control.Applicative ((<$>))\nimport Data.List (groupBy, sortBy)\nimport Data.Function (on)\nimport Data.ByteString (getLine, getContents)\nimport Data.ByteString.Char8 (readInt, lines, words, unpack)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (getLine, getContents, lines, words)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n\tgetLine\n\tpeople <- map ((\\[a, b, c] -> (unpack a, readInt' b, readInt' c)) . words) . lines <$> getContents\n\n\tlet\n\t\tselect [(name1, _, _), (name2, _, _)] = name1 ++ \" \" ++ name2\n\t\tselect ((name1, _, score1):(name2, _, score2):(name3, _, score3):_) = if score2 == score3 then \"?\" else name1 ++ \" \" ++ name2\n\n\tputStr . unlines . map (select . reverse) . groupBy ((==) `on` (\\(_, a, _) -> a)) $ sortBy (compare `on` (\\(a, b, c) -> (b, c))) people\n \t\n"}], "negative_code": [{"source_code": "import Data.List (foldl',sort)\nimport Control.Monad\nimport Data.IntMap hiding (map,foldl')\n\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n l <- (forM [1..n] $ \\i -> do\n [name,region,rank] <- fmap words getLine\n return (read region,(-(read rank),name)) :: IO (Int,(Int,String)))\n let a = foldl' (\\mp (k,v) -> update (\\il -> return (v:il)) k mp) (fromList (zip [1..m] (repeat []))) l\n ls = elems a\n forM_ ls $ \\i -> do\n let (x:xs) = take 5 (sort i)\n if all (\\(a,_) -> a == fst x) (x:xs)\n then putStrLn \"?\"\n else putStrLn (snd x ++ \" \" ++ snd (xs!!0))\n"}, {"source_code": "import Data.List (foldl',sort)\nimport Control.Monad\nimport Data.IntMap hiding (map,foldl')\n\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n l <- (forM [1..n] $ \\i -> do\n [name,region,rank] <- fmap words getLine\n return (read region,(-(read rank),name)) :: IO (Int,(Int,String)))\n let a = foldl' (\\mp (k,v) -> update (\\il -> return (v:il)) k mp) (fromList (zip [1..m] (repeat []))) l\n ls = elems a\n forM_ ls $ \\i -> do\n let (x:xs) = take 3 (sort i) \n if all (\\(a,_) -> a == fst x) (x:xs)\n then putStrLn \"?\"\n else putStrLn (snd x ++ \" \" ++ snd (xs!!0))\n"}, {"source_code": "import Data.List (foldl',sort)\nimport Control.Monad\nimport Data.IntMap hiding (map,foldl')\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n,m] <- fmap ((map read) . words) getLine :: IO [Int]\n l <- (forM [1..n] $ \\i -> do\n [name,region,rank] <- fmap (words . B.unpack) B.getLine\n return (read region,(-(read rank),name)) :: IO (Int,(Int,String)))\n let a = foldl' (\\mp (k,v) -> update (\\il -> return (v:il)) k mp) (fromList (zip [1..m] (repeat []))) l\n ls = elems a\n forM_ ls $ \\i -> do\n let (x:xs) = take 3 (sort i)\n if and[length (x:xs) > 2,all (\\(a,_) -> a == fst x) (take 2 xs)]\n then putStrLn \"?\"\n else putStrLn (snd x ++ \" \" ++ snd (xs!!0))\n"}], "src_uid": "a1ea9eb8db25289958a6f730c555362f"} {"source_code": "\nmain = getLine >> getLine >>= print.solve\n\nsolve :: String -> Int\nsolve xs = min a b\n where ys = map read $ sequence [xs]\n a = count 1 0 ys\n b = count 0 0 ys\n\ncount :: Int -- \u6b21\u306b\u6765\u308b\u3068\u4e88\u60f3\u3055\u308c\u308b\u6570\u5b57\n -> Int -- \u73fe\u5728\u307e\u3067\u306b\u5857\u308a\u66ff\u3048\u305f\u56de\u6570\n -> [Int] -- \u6570\u5b57\u5217\n -> Int -- \u5857\u308a\u66ff\u3048\u305f\u56de\u6570\ncount _ r [] = r\ncount n r (x:xs) | n == x = count (0^n) r xs\n |otherwise = count (0^n)(r+1)xs", "positive_code": [{"source_code": "main = do\n\tn <- getLine\n\ts <- getLine\n\tputStr $ show $ minimum [length $ filter id $ zipWith (==) s $ f $ concat $ repeat \"01\" | f <- [id, tail]]\n"}], "negative_code": [{"source_code": "gao [] _ = 0\ngao (a:b) (c:d) = if a == c then gao b d else 1 + gao (drop 1 b) (tail d)\n\nmain = do\n\tn <- getLine\n\ts <- getLine\n\tputStr $ show $ minimum [gao s $ f $ concat $ repeat \"01\" | f <- [id, tail]]\n"}, {"source_code": "main = do getLine >>= putStr . unwords . map show . (\\n -> n:[1..n-1]) . read\n"}], "src_uid": "7c313b911e644cd5efa4fdc31d7ffcc9"} {"source_code": "-- Codeforces Round #534 Div.2 (C), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\n-- 1st dim: False for vertical, True for Horizontal\n-- 3rd dim: False for y, True for x\nplaces :: UArray (Bool,Int,Bool) Int\nplaces = A.listArray ((False,0,False), (True,3,True))\n [1, 1,\n 2, 1,\n 3, 1,\n 4, 1,\n 1, 4,\n 3, 4,\n 1, 4,\n 3, 4]\n \n\nmain :: IO ()\nmain = do\n xs <- map (=='1') <$> getLine\n acc <- A.newArray (False,True) 0 :: IO (IOUArray Bool Int)\n forM_ xs $ \\b -> do\n k <- A.readArray acc b\n let y = places A.! (b,k,False)\n x = places A.! (b,k,True)\n putStrLn $ shows x $ ' ' : show y\n A.writeArray acc b $ if k >= 3 then 0 else k+1\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\n-- import Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\n-- import Data.Array.ST.Safe\n-- import Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = getLine >>= mapM_ ( uncurry $ printf \"%d %d\\n\" ) . map ( succ *** succ ) . solve 0 0\n\nsolve :: Int -> Int -> String -> [ ( Int, Int ) ]\nsolve _ _ [] = []\nsolve v h (c:s)\n\t| c == '0' = ( 2, v `mod` 4 ) : solve ( succ v ) h s\n\t| otherwise = ( 0, h `mod` 2 * 2 ) : solve v ( succ h ) s"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.Bits\nimport Data.List\n\nmain = do\n s <- getLine\n putStr $ unlines $ map (\\(a, b) -> show a ++ \" \" ++ show b) $ solve 0 0 s\n\nsolve _ _ [] = []\nsolve v h ('0' : s) = (v + 1, 1) : solve ((v + 2) `mod` 4) h s\nsolve v h ('1' : s) = (h + 1, 2) : solve v ((h + 1) `mod` 4) s\n"}], "negative_code": [{"source_code": "-- Codeforces Round #534 Div.2 (C), Contest 1104, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\n-- 1st dim: False for vertical, True for Horizontal\n-- 3rd dim: False for x, True for y\nplaces :: UArray (Bool,Int,Bool) Int\nplaces = A.listArray ((False,0,False), (True,3,True))\n [1, 1,\n 2, 1,\n 3, 1,\n 4, 1,\n 1, 4,\n 3, 4,\n 1, 4,\n 3, 4]\n \n\nmain :: IO ()\nmain = do\n xs <- map (=='1') <$> getLine\n acc <- A.newArray (False,True) 0 :: IO (IOUArray Bool Int)\n forM_ xs $ \\b -> do\n k <- A.readArray acc b\n let x = places A.! (b,k,False)\n y = places A.! (b,k,True)\n putStrLn $ shows x $ ' ' : show y\n A.writeArray acc b $ if k >= 3 then 0 else k+1\n"}], "src_uid": "a63cdbd1009a60c0f9b52e4ffbba252e"} {"source_code": "import Data.List\n\nmain = interact (format . solve . parse)\n\nparse s = case words s of\n (_:m:k:a) -> (read m :: Integer,\n read k :: Integer,\n map read a :: [Integer])\n _ -> (0, 0, [])\n\nsolve :: (Integer, Integer, [Integer]) -> ([Integer], Integer)\nsolve (m, k, a) =\n foldr (\\(i, (index, value)) (l, sum) ->\n (if (mod i m == 0 && not (i == m * k)) then index:l else l, sum + value))\n ([], 0) $\n zip [1..] $\n sortBy (\\a b -> compare (fst a) (fst b)) $\n genericTake (m * k) $\n sortBy (\\a b -> compare (snd b) (snd a)) $\n zip [1..] a\n\nformat (l, sum) = (show sum) ++ \"\\n\" ++ (unwords $ map show l)\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\n\nmain :: IO ()\nmain = do\n [n,m,k] <- map readInt . words <$> getLine\n as <- take (m*k) . sortBy (compare `on` (Down . snd))\n . zip [1..] . map toI64 . unfoldr (BS.readInt . BS.dropWhile (<'!'))\n <$> BS.getLine\n print $ sum $ map snd as\n let arr = A.accumArray (\\_ -> id) False (1,n) $ map ((,True) . fst) as\n :: UArray Int Bool\n taills = iterate (drop m) $ drop (m-1)\n $ map fst $ filter snd $ A.assocs arr\n ans = map head $ takeWhile (not . null) taills\n putStrLn $ unwords $ map show $ init ans\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "negative_code": [], "src_uid": "e9cf68a68b55fe075099c384cb6a7e9e"} {"source_code": "import Data.List\nimport Control.Monad\n\nf :: [[Int]] -> Int\nf ([]) = -1\nf (x:xs) = 1 + (f $ dfsFilter cmp xs x)\n\ncmp [x1,y1] [x2,y2] = x1 == x2 || y1 == y2\n\ndfsFilter :: (a -> a -> Bool) -> [a] -> a -> [a]\ndfsFilter cf vs v = let sm = filter (cf v) vs\n ds = filter (not.cf v) vs\n in foldl (dfsFilter cf) ds sm\n\n\n\nmain = (f `fmap` ((read `fmap` getLine) >>= (flip replicateM ((map read. words) `fmap` getLine)))) >>= print\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe (fromMaybe)\nimport Data.Function\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nreadInt s = read s :: Int\nreadInts n s = map readInt $ take n $ words s\n\ndata Point = Point { pid :: Int\n , xCoord :: Int\n , yCoord :: Int \n } deriving (Show, Eq)\n\n---------------------------------------------\ndata Queue a = Queue { input :: [a]\n , output :: [a]\n } deriving (Show)\n\nemptyQueue = Queue [] []\n\nisEmpty :: Queue e -> Bool\nisEmpty q@Queue{input = [], output = []} = True\nisEmpty _ = False\n\npushQueue :: a -> Queue a -> Queue a\npushQueue x q@Queue{input = i} = q{input = x : i}\n\npopQueue :: Queue a -> (a, Queue a)\npopQueue q@Queue{input = i, output = o}\n | null i && null o = error \"Que is empty!\"\n | null o = popQueue (pour q)\n | otherwise = (head o, q{output = tail o})\n where pour q@Queue{input = i, output = o}\n | null i = q\n | otherwise = pour q{input = tail i, output = head i : o}\n---------------------------------------------\n\ntryAdd :: Ord a => Queue a -> Set.Set a -> [a] -> ( Queue a, Set.Set a )\ntryAdd que unused elems\n | null elems = (que, unused)\n | otherwise = let (cur:elemtail) = elems\n in if cur `Set.member` unused\n then tryAdd (pushQueue cur que) (Set.delete cur unused) elemtail\n else tryAdd que unused elemtail\n\nglobalBFS points pointsByX pointsByY = let n = length points\n in bfs emptyQueue (Set.fromList [0 .. n - 1])\n where bfs queue unused\n | Set.null unused = 0\n | isEmpty queue = bfs (Queue [] [first]) (Set.delete first unused) + 1\n where first = head (Set.toList unused)\n bfs queue unused = bfs queue' unused'\n where (quetop, quetail) = popQueue queue\n topX = xCoord (points !! quetop)\n topY = yCoord (points !! quetop) \n neighbors = fromMaybe [] (Map.lookup topX pointsByX) ++ fromMaybe [] (Map.lookup topY pointsByY)\n (queue', unused') = tryAdd quetail unused neighbors\n\nmain = do\n args0 <- getLine\n content <- getContents\n let n = head (readInts 1 args0)\n raw_points = map (readInts 2) . take n . lines $ content\n points = map (\\(pid, [x,y]) -> Point pid x y) numeredPoints\n where numeredPoints = zip [0 .. ] raw_points\n\n pointsByX = Map.fromList . map extract $ grouped\n where grouped = groupBy ((==) `on` xCoord) . sortBy (compare `on` xCoord) $ points\n extract ps = (xCoord (head ps), map pid ps) \n\n pointsByY = Map.fromList . map extract $ grouped\n where grouped = groupBy ((==) `on` yCoord) . sortBy (compare `on` yCoord) $ points\n extract ps = (yCoord (head ps), map pid ps) \n \n putStrLn . show $ globalBFS points pointsByX pointsByY - 1\n\n \n"}, {"source_code": "import Data.List\nimport Data.Function\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nreadInt s = read s :: Int\nreadInts n s = map readInt $ take n $ words s\n\ndata Point = Point { pid :: Int\n , xCoord :: Int\n , yCoord :: Int \n } deriving (Show, Eq)\n\ntryAdd :: Ord a => [a] -> (Set.Set a) -> [a] -> ( [a], (Set.Set a) )\ntryAdd que unused elems\n | null elems = (que, unused)\n | otherwise = let (cur:elemtail) = elems\n in if cur `Set.member` unused\n then tryAdd (cur : que) (Set.delete cur unused) elemtail\n else tryAdd que unused elemtail\n\nunwrap :: Maybe [a] -> [a]\nunwrap (Just x) = x\nunwrap Nothing = []\n\nglobalBFS points pointsByX pointsByY = let n = length points\n in bfs [] (Set.fromList [0 .. n - 1])\n where bfs queue unused\n | Set.null unused = 0\n | null queue = bfs [first] (Set.delete first unused) + 1\n where first = head (Set.toList unused)\n bfs (quetop:quetail) unused = bfs queue' unused'\n where topX = xCoord (points !! quetop)\n topY = yCoord (points !! quetop) \n neighbors = unwrap (Map.lookup topX pointsByX) ++ unwrap (Map.lookup topY pointsByY)\n (queue', unused') = tryAdd quetail unused neighbors\n\nmain = do\n args0 <- getLine\n content <- getContents\n let n = head (readInts 1 args0)\n raw_points = map (readInts 2) . take n . lines $ content\n points = map (\\(pid, [x,y]) -> Point pid x y) numeredPoints\n where numeredPoints = zip [0 .. ] raw_points\n\n pointsByX = Map.fromList . map extract $ grouped\n where grouped = groupBy ((==) `on` xCoord) . sortBy (compare `on` xCoord) $ points\n extract ps = (xCoord (head ps), map pid ps) \n\n pointsByY = Map.fromList . map extract $ grouped\n where grouped = groupBy ((==) `on` yCoord) . sortBy (compare `on` yCoord) $ points\n extract ps = (yCoord (head ps), map pid ps) \n \n putStrLn . show $ globalBFS points pointsByX pointsByY - 1\n\n \n"}, {"source_code": "import Data.Graph\nimport qualified Data.Set as DS\n\nmain = interact $ f . map (map read . words) . tail . lines\n\ng v@(z, x:y:_) s1 = nodes\n where ans = DS.toList $ DS.filter (\\(_, i:j:_) -> i==x || y==j) s1\n nodes = zip [z,z..] $ map (\\(i, _) -> i) ans\n\nf :: [[Int]] -> String\nf x = show tvl\n where pre = zip [0..] x\n l = (length x) -1\n mx = DS.fromList $ pre\n e = concat $ map (\\v -> g v mx) pre\n gf = buildG (0, l) e\n tvl = (length (dfs gf [0..l])) -1\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nf ([]) = -1\nf (x:xs) = 1 + f (dfsF cmp xs x)\n\ncmp x y = or $ zipWith (==) x y\n\ndfsF cf vs v = let (sm,ds) = partition (cf v) vs\n in foldl (dfsF cf) ds sm\n\nmain = getLine >>= ((`replicateM` (words `fmap` getLine)).read) >>= print.f\n"}, {"source_code": "-- ghc --make -O Main.hs\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Control.Monad.ST as ST\nimport qualified Data.STRef as STRef\n\ndata Point = Point {\n x :: Int\n , y :: Int\n } deriving (Eq, Ord, Show)\n\nlistToPoint :: [Int] -> Point\nlistToPoint [x',y'] = Point { x = x', y = y'}\nlistToPoint _ = error \"Point parsing error\"\n\ninputToList :: String -> [Point]\ninputToList s = map (listToPoint.( map read ).words) $ filter (not.null) $ tail.lines $ s\n\ngetInts :: (Point -> Int) -> [Point] -> [Int]\ngetInts f l = foldr step [] l\n where step p acc = (f p):acc\n\ngetAdj :: (Point -> Int) -> (Point -> Int) -> [Point] -> Map.Map Int [Int]\ngetAdj key val l = foldr step Map.empty l\n where step :: Point -> Map.Map Int [Int] -> Map.Map Int [Int]\n updateWith :: Map.Map Int [Int]->Int->Int->Maybe [Int] -> Map.Map Int [Int]\n updateWith acc k v Nothing = Map.insert k [v] acc\n updateWith acc k v (Just vs) = Map.insert k (v:vs) acc\n step p acc = let k = key p\n v = val p\n in updateWith acc k v (Map.lookup k acc)\n\ngetAdjToX :: [Point] -> Map.Map Int [Int]\ngetAdjToX = getAdj x y\n\ngetAdjToY :: [Point] -> Map.Map Int [Int]\ngetAdjToY = getAdj y x\n\nxyToPoint :: Int -> Int -> Point\nxyToPoint x' y' = Point{ x = x', y = y' }\n\nyxToPoint :: Int -> Int -> Point\nyxToPoint y' x' = Point{ x = x', y = y' }\n\ngetAdjPoints' :: (Point -> Int) -> (Point -> Int) -> (Int -> Int -> Point ) -> Map.Map Int [Int] -> Point -> [Point]\ngetAdjPoints' dec1 dec2 comp adj p = let k1 = dec1 p\n k2 = dec2 p\n in case Map.lookup k1 adj of\n Nothing -> []\n Just l -> map (comp k1) (filter (/= k2) l)\n\ndata Graph = Graph {\n xAdjList :: Map.Map Int [Int]\n , yAdjList :: Map.Map Int [Int]\n } deriving (Show)\n\ngraphFromList :: [Point] -> Graph\ngraphFromList ps = Graph { xAdjList = getAdjToX ps, yAdjList = getAdjToY ps }\n\ngetAdjPoints :: Graph -> Point -> [Point]\ngetAdjPoints g p = (getAdjPoints' x y xyToPoint (xAdjList g) p) ++\n (getAdjPoints' y x yxToPoint (yAdjList g) p)\n\n\ndfs :: Graph -> STRef.STRef s (Set.Set Point) -> Point -> ST.ST s()\ndfs g seenST p = do\n seen <- STRef.readSTRef seenST\n STRef.writeSTRef seenST (Set.insert p seen)\n dfs' g seenST (filter (\\ e -> Set.notMember e seen) (getAdjPoints g p))\n\ndfs' :: Graph -> STRef.STRef s (Set.Set Point) -> [Point] -> ST.ST s()\ndfs' _ _ [] = return ()\ndfs' g seenST (p:ps) = do\n dfs g seenST p\n dfs' g seenST ps\n\nconnectedComponents :: [Point] -> Int\nconnectedComponents ps = ST.runST $ do\n seenST <- STRef.newSTRef Set.empty\n loop 0 ps seenST\n where\n g = graphFromList ps\n loop :: Int -> [Point] -> STRef.STRef s (Set.Set Point) -> ST.ST s(Int)\n loop acc [] _ = return (acc)\n loop acc (p:ps') seenST = do\n seen <- STRef.readSTRef seenST\n if Set.member p seen\n then loop acc ps' seenST\n else do\n dfs g seenST p\n loop (acc+1) ps' seenST\nsolve :: String -> String\nsolve in_str = show ( (connectedComponents (inputToList in_str)) - 1 ) ++ \"\\n\"\n\nmain :: IO ()\nmain = do interact $ solve\n\n"}, {"source_code": "import Data.Graph\nimport Data.List\nmain = interact $ show . solve . pairs . map read . tail . words\npairs (a:b:xs) = (a,b :: Int) : pairs xs\npairs [] = []\nsolve ps = length (dff g) - 1\n where g = buildG (1,length ps) [ (i,j) | (i,u) <- zip [1..] ps\n , (j,v) <- zip [1..] ps\n , touch u v ]\ntouch (i,j) (i',j') = i == i' || j == j'\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport qualified Data.IntSet as IS\nimport Control.Applicative\nimport Control.Monad\n\ntoPairs (x:y:xys) = (x,y):toPairs xys\ntoPairs [] = []\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep !n f = go 0\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n\nfor :: Int -> Int -> (Int -> IO ()) -> IO ()\nfor !m !n f = go m\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n\nmain = do\n n <- readLn\n\n-- Union-Find Tree\n parent <- newListArray (0,n-1) [0..n-1] :: IO (IOUArray Int Int)\n rank <- newArray (0,n-1) 0 :: IO (IOUArray Int Int)\n\n let find :: Int -> IO Int\n find x = do\n let go y hist = do\n py <- unsafeRead parent y\n if py == y\n then return (y:hist)\n else go py (y:hist)\n (root:hist) <- go x []\n forM_ hist $ \\h-> do\n unsafeWrite parent h root\n return root\n \n union :: Int -> Int -> IO ()\n union x y = do\n rootx <- find x\n rooty <- find y\n if rootx == rooty\n then return ()\n else do\n rankx <- unsafeRead rank rootx\n ranky <- unsafeRead rank rooty\n case compare rankx ranky of\n LT -> unsafeWrite parent rootx rooty\n GT -> unsafeWrite parent rooty rootx\n EQ -> do\n unsafeWrite parent rootx rooty\n unsafeWrite rank rooty (ranky+1)\n\n (xs,ys) <- unzip.toPairs.map read.words <$> getContents\n let xarr = listArray (0,n-1) xs :: UArray Int Int\n yarr = listArray (0,n-1) ys :: UArray Int Int\n i===j = unsafeAt xarr i == unsafeAt xarr j\n || unsafeAt yarr i == unsafeAt yarr j\n\n rep n $ \\i-> do\n for (i+1) n $ \\j-> do\n when (i===j) $ union i j\n \n mapM find [0..n-1] >>= print.pred.IS.size.IS.fromList"}, {"source_code": "import Data.List\nimport Control.Monad\n\nf ([]) = -1\nf (x:xs) = 1 + f (dfsF cmp xs x)\n\ncmp x y = or $ zipWith (==) x y\n\ndfsF cf vs v = let (sm,ds) = partition (cf v) vs\n in foldl (dfsF cf) ds sm\n\nmain = getLine >>= ((`replicateM` (words `fmap` getLine)).read) >>= print.f\n"}], "negative_code": [{"source_code": "import Data.List\nmain = interact $ show . solve . pairs . map read . tail . words\npairs (a:b:xs) = (a,b :: Int) : pairs xs\npairs [] = []\nsolve ps = length (foldl ins [] ps) - 1\nins gs p | Just g <- find (gr p) gs = (p:g) : delete g gs\n | otherwise = [p] : gs\ngr (i,j) ps = any (\\(i',j') -> i == i' || j == j') ps\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nf :: [[Int]] -> Int\nf = (\\x -> x-1) . length . nubBy (\\[x1,y1] [x2,y2] -> x1 == x2 || y1 == y2)\n\nmain = (f `fmap` ((read `fmap` getLine) >>= (flip replicateM ((map read. words) `fmap` getLine)))) >>= print\n"}], "src_uid": "cb4dbff31d967c3dab8fe0495eb871dc"} {"source_code": "{-# LANGUAGE Strict #-}\nimport Data.List as List\nimport Data.Function\n\n\nm = 998244353\n\npowmod a x n\n |n==0 = a\n |even n = powmod a (mod (x*x) m) (div n 2)\n |otherwise = powmod (mod (a*x) m) x (n-1)\n\nff a [] = [a]\nff (a,b) ((c,d):xs)\n |b>d = ff (a,b) xs\n |b>c = (a,d):xs\n |otherwise = (a,b):(c,d):xs\n\n\nf xs0 = --trace (show (xs1,xs2,xs3,xs4,xs5,n)) \n powmod 1 2 n\n where\n xs1 = sort $ zip xs0 [0..]\n xs2 = List.groupBy (on (==) fst) xs1\n xs3 = fmap (\\xs-> (snd $ head xs, snd $ last xs)) xs2\n xs4 = sort xs3\n xs5 = foldr ff [] xs4\n n = length xs5 - 1\n \n\n\nmain = do\n getLine \n line <- getLine\n let xs = fmap read $ words line :: [Int]\n print $ f xs\n", "positive_code": [{"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,parsed),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n print $ query n as\n\nquery :: Int -> [(Int, Int)] -> Word32\nquery n as = fromMon $ (2^)\n $ length $ filter (==0) $ scanl1 (+) $ init $ A.elems acc\n where\n acc :: UArray Int Int\n acc = runSTUArray $ do\n acc <- A.newArray (0,n) 0\n forM_ groupedAs $ \\(i,j) -> do\n A.writeArray acc (i+1) 1\n A.writeArray acc (j+1) (-1)\n A.writeArray acc 0 1\n A.writeArray acc 1 . (+(-1)) =<< A.readArray acc 1 \n return acc\n group_ [] = []\n group_ ((i,x):xs) = go0 i x xs\n where\n go0 !i !x ((j,y):xs) | x == y = go i j x xs\n | otherwise = go0 j y xs\n go0 !i !x [] = []\n go !i !j !x ((k,y):xs) | x == y = go i k x xs\n | otherwise = (i,j) : go0 k y xs\n go !i !j !x [] = [(i,j)]\n groupedAs = group_ $ sortBy (compare `on` snd) as\n \n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((parsed,(i,i)),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n let intvs = IM.elems $ IM.fromListWith (\\(_,x) (y,_) -> (y,x)) as\n goodIntvs = unionIntvs $ sort intvs\n unionIntvs ((x0,x1):(y0,y1):is)\n | y0 <= x1 = unionIntvs ((x0,max x1 y1):is)\n unionIntvs (i:is) = i:unionIntvs is\n unionIntvs [] = []\n ansExpt = (n -) $ sum $ map (uncurry subtract) goodIntvs :: Int\n print $ fromMon $ 2^(ansExpt-1)\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,parsed),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n print $ query n as\n\nquery :: Int -> [(Int, Int)] -> Word32\nquery n as = fromMon $ (2^)\n $ length $ filter (==0) $ scanl1 (+) $ init $ A.elems $ acc\n where\n acc :: UArray Int Int\n acc = runSTUArray $ do\n acc <- A.newArray (0,n) 0\n prevs <- newSTRef $ IM.empty\n A.writeArray acc 0 1\n A.writeArray acc 1 (-1)\n forM_ as $ \\(!i_now,!key) -> do\n !prevs0 <- readSTRef prevs\n let (!i_prev, !prevs1) = IM.insertLookupWithKey\n (\\_ -> const) key i_now prevs0\n writeSTRef prevs prevs1\n flip (maybe $ return ()) i_prev $ \\i_prev -> do\n A.writeArray acc (i_prev+1) . (+1) =<< A.readArray acc (i_prev+1)\n A.writeArray acc (i_now+1) . (subtract 1)\n =<< A.readArray acc (i_now+1)\n return acc\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n prevs <- newIORef $ IM.empty\n acc <- A.newArray (0,n) 0 :: IO (IOUArray Int Int)\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,parsed),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n forM_ as $ \\(!i_now,!key) -> do\n !prevs0 <- readIORef prevs\n let (!i_prev, !prevs1) = IM.insertLookupWithKey\n (\\_ _ -> id) key i_now prevs0\n writeIORef prevs prevs1\n flip (maybe $ return ()) i_prev $ \\i_prev -> do\n A.writeArray acc (i_prev+1) . (+1) =<< A.readArray acc (i_prev+1)\n A.writeArray acc (i_now+1) . (subtract 1) =<< A.readArray acc (i_now+1)\n A.writeArray acc 0 1\n A.writeArray acc 1 . (subtract 1) =<< A.readArray acc 1\n brackets <- newIORef (0::Int)\n forM_ [1..n-1] $ \\i -> do\n prev <- A.readArray acc (i-1)\n intvs <- (prev+) <$> A.readArray acc i\n A.writeArray acc i intvs\n when (intvs == 0) $ do\n writeIORef brackets . (+1) =<< readIORef brackets\n print . fromMon . (2^) =<< readIORef brackets\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}], "negative_code": [{"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n prevs <- newIORef $ IM.empty\n acc <- A.newArray (0,n-1) 0 :: IO (IOUArray Int Int)\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,parsed),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n forM_ (init as) $ \\(!i_now,!key) -> do\n !prevs0 <- readIORef prevs\n let (!i_prev, !prevs1) = IM.updateLookupWithKey\n (\\_ _ -> Just i_now) key prevs0\n writeIORef prevs prevs1\n flip (maybe $ return ()) i_prev $ \\i_prev -> do\n A.writeArray acc (i_prev+1) . (+1) =<< A.readArray acc (i_prev+1)\n A.writeArray acc (i_now+1) . (subtract 1) =<< A.readArray acc (i_now+1)\n A.writeArray acc 0 1\n A.writeArray acc 1 . (subtract 1) =<< A.readArray acc 1\n brackets <- newIORef (0::Int)\n forM_ [1..n-1] $ \\i -> do\n prev <- A.readArray acc (i-1)\n intvs <- (prev+) <$> A.readArray acc (i-1)\n A.writeArray acc i intvs\n when (intvs == 0) $ do\n writeIORef brackets . (+1) =<< readIORef brackets\n print . fromMon . (2^) =<< readIORef brackets\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,(parsed,parsed)),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n let intvs = IM.elems $ IM.fromListWith (\\(x,_) (_,y) -> (x,y)) as\n goodIntvs = unionIntvs $ sort intvs\n unionIntvs ((x0,x1):(y0,y1):is)\n | y0 <= x1 = unionIntvs ((x0,y1):is)\n unionIntvs (i:is) = i:unionIntvs is\n unionIntvs [] = []\n ansExpt = (n -) $ sum $ map (uncurry subtract) goodIntvs :: Int\n print $ fromMon $ 2^(ansExpt-2)\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((parsed,(i,i)),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n let intvs = IM.elems $ IM.fromListWith (\\(_,x) (y,_) -> (y,x)) as\n goodIntvs = unionIntvs $ sort intvs\n unionIntvs ((x0,x1):(y0,y1):is)\n | y0 <= x1 = unionIntvs ((x0,y1):is)\n unionIntvs (i:is) = i:unionIntvs is\n unionIntvs [] = []\n ansExpt = (n -) $ sum $ map (uncurry subtract) goodIntvs :: Int\n print $ fromMon $ 2^(ansExpt-1)\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n prevs <- newIORef $ IM.empty\n acc <- A.newArray (0,n) 0 :: IO (IOUArray Int Int)\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,parsed),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n forM_ (init as) $ \\(!i_now,!key) -> do\n !prevs0 <- readIORef prevs\n let (!i_prev, !prevs1) = IM.updateLookupWithKey\n (\\_ _ -> Just i_now) key prevs0\n writeIORef prevs prevs1\n flip (maybe $ return ()) i_prev $ \\i_prev -> do\n A.writeArray acc (i_prev+1) . (+1) =<< A.readArray acc (i_prev+1)\n A.writeArray acc (i_now+1) . (subtract 1) =<< A.readArray acc (i_now+1)\n A.writeArray acc 0 1\n A.writeArray acc 1 . (subtract 1) =<< A.readArray acc 1\n brackets <- newIORef (0::Int)\n forM_ [1..n-1] $ \\i -> do\n prev <- A.readArray acc (i-1)\n intvs <- (prev+) <$> A.readArray acc (i-1)\n A.writeArray acc i intvs\n when (intvs == 0) $ do\n writeIORef brackets . (+1) =<< readIORef brackets\n print . fromMon . (2^) =<< readIORef brackets\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "-- Codeforces Round #531 (E), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n prevs <- newIORef $ IM.empty\n acc <- A.newArray (0,n) 0 :: IO (IOUArray Int Int)\n as <- unfoldr (\\(!i,!bs) -> do\n (parsed,bs1) <- BS.readInt $ BS.dropWhile (<'!') bs\n return ((i,parsed),(i+1,bs1))\n ) . (0,) <$> BS.getLine\n forM_ (init as) $ \\(!i_now,!key) -> do\n !prevs0 <- readIORef prevs\n let (!i_prev, !prevs1) = IM.updateLookupWithKey\n (\\_ _ -> Just i_now) key prevs0\n writeIORef prevs prevs1\n flip (maybe $ return ()) i_prev $ \\i_prev -> do\n A.writeArray acc (i_prev+1) . (+1) =<< A.readArray acc (i_prev+1)\n A.writeArray acc (i_now+1) . (subtract 1) =<< A.readArray acc (i_now+1)\n A.writeArray acc 0 1\n A.writeArray acc 1 . (subtract 1) =<< A.readArray acc 1\n brackets <- newIORef (0::Int)\n forM_ [1..n-1] $ \\i -> do\n prev <- A.readArray acc (i-1)\n intvs <- (prev+) <$> A.readArray acc i\n A.writeArray acc i intvs\n when (intvs == 0) $ do\n writeIORef brackets . (+1) =<< readIORef brackets\n print . fromMon . (2^) =<< readIORef brackets\n\n{-# INLINE n #-}\nn :: (Integral i) => i\nn = 998244353\n\n{-# INLINE nprime #-}\nnprime :: Word64\nnprime = 998244351\n\n{-# INLINE rsq #-}\nrsq :: Word64\nrsq = 932051910\n\nnewtype Montgomery = Mon {unMon :: Word32}\n deriving (Eq, Show)\n\ninstance Num Montgomery where\n {-# INLINE (+) #-}\n (+) = monAdd\n {-# INLINE (*) #-}\n (*) = monMult\n {-# INLINE (-) #-}\n (-) = monSub\n {-# INLINE negate #-}\n negate (Mon x) = Mon (n - x)\n {-# INLINE fromInteger #-}\n fromInteger = monRep . fromInteger\n {-# INLINE signum #-}\n signum x | x == Mon 0 = Mon 0\n | otherwise = monRep 1\n {-# INLINE abs #-}\n abs = id\n\n{-# INLINE monMult #-}\nmonMult :: Montgomery -> Montgomery -> Montgomery\nmonMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y\n\n{-# INLINE monAdd #-}\nmonAdd :: Montgomery -> Montgomery -> Montgomery\nmonAdd (Mon x) (Mon y) = Mon $ x+y + if x >= n-y then n else 0\n \n{-# INLINE monSub #-}\nmonSub :: Montgomery -> Montgomery -> Montgomery\nmonSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0\n\n{-# INLINE monRep #-}\nmonRep :: Word32 -> Montgomery\nmonRep x = Mon $ monRed $ rsq * fromIntegral x\n\n{-# INLINE fromMon #-}\nfromMon :: Montgomery -> Word32\nfromMon (Mon x) = monRed $ fromIntegral x\n\n{-# INLINE monRed #-}\nmonRed :: Word64 -> Word32\nmonRed x = t - if t >= n then n else 0\n where t = fromIntegral $ (`shiftR` 32) $ x + x*nprime .&.mask32 *n\n\nmask32 :: Word64\nmask32 = bit 32 - 1\n"}, {"source_code": "{-# LANGUAGE Strict #-}\nimport Data.List as List\nimport Data.Function\n\nm = 998244353\n\npowmod a x n\n |n==0 = a\n |even n = powmod a (mod (x*x) m) (div n 2)\n |otherwise = powmod (mod (a*x) m) x (n-1)\n\nff a [] = [a]\nff (a,b) ((c,d):xs)\n |b>c = (a,d):xs\n |otherwise = (a,b):(c,d):xs\n\n\nf xs0 = powmod 1 2 n\n where\n xs1 = sort $ zip xs0 [0..]\n xs2 = List.groupBy (on (==) fst) xs1\n xs3 = fmap (\\xs-> (snd $ head xs, snd $ last xs)) xs2\n xs4 = sort xs3\n xs5 = foldr ff [] xs4\n n = length xs5 - 1\n \n\n\nmain = do\n getLine \n line <- getLine\n let xs = fmap read $ words line :: [Int]\n print $ f xs\n"}], "src_uid": "0dab2f4e70064f90fc079d8dd7a8b049"} {"source_code": "readInt :: String -> Int \nreadInt = read \n\nreadInts :: String -> [Int]\nreadInts x = map read $ words x\n\nisSorted :: (Ord a) => [a] -> Bool\nisSorted xs = all id . map (\\(x,y) -> x <= y) . zip xs $ tail xs\n \nbigger :: Int -> Int -> Int \nbigger x y | (x > y) == True = x \n | (x <= y) == True = y \n \nsolve :: [Int] -> Int -> Int \nsolve x y | isSorted x == True = y \n | isSorted x == False = bigger (solve (take len x) len) (solve (drop len x) len)\n where len = y `div` 2\n \nmain = do\n cnt <- getLine\n nums <- getLine\n \n let len = readInt cnt \n let list = readInts nums\n let ans = solve list len \n \n print ans ", "positive_code": [{"source_code": "import Data.List\n\nthanos :: Int -> [Int] -> Int\nthanos n [] = 0\nthanos n [x] = 1\nthanos n xs | sorted xs = n\n | otherwise = max (thanos newN fhalf) (thanos newN shalf)\n where (fhalf, shalf) = splitAt ((length xs) `quot` 2) xs\n newN = n `quot` 2\n sorted [] = True\n sorted [x] = True\n sorted (x:y:ys) = x<=y && sorted (y:ys)\n\nreadInt :: String -> Int\nreadInt = read\n\nreadInts :: String -> [Int]\nreadInts x = map read $ words x\n\nmain = do\n n <- getLine\n x <- getLine\n putStr (show $ thanos (readInt n) (readInts x))"}, {"source_code": "\nsort [] = []\nsort (p : xs) = (sort lesser) ++ [p] ++ (sort greater)\n where\n lesser = [x | x <- xs, x < p]\n greater = [x | x <- xs, x >= p]\n\nthanoSort size arr = do\n let half = div size 2\n if arr == (sort arr) then size else\n max (thanoSort half (take half arr)) (thanoSort half (drop half arr))\n\n\n-- Copy Pasted IO from rock_cloud <- THANK YOU\nmain :: IO ()\nmain = do\n sizeStr <- getLine\n arrStr <- getLine\n let\n size = (read sizeStr):: Int\n arr = map (read :: String -> Int) $ words arrStr\n putStrLn (show (thanoSort size arr))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\nisSorted (x1:x2:xs) = if x1 <= x2 then isSorted (x2:xs) else False\nisSorted _ = True\n\nthanosSort n l = if isSorted l then n else snapFinger where\n n' = n `div` 2\n snapFinger = (max `on` thanosSort n') `uncurry` (splitAt n' l)\n\nmain = do\n n <- getInt\n l <- getInts\n print $ thanosSort n l\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\nisSorted (x1:x2:xs) = if x1 <= x2 then isSorted (x2:xs) else False\nisSorted _ = True\n\nthanosSort n l = if isSorted l then n else snapFinger where\n n' = n `div` 2\n (firstHalf, secondHalf) = splitAt n' l\n snapFinger = max (thanosSort n' firstHalf) (thanosSort n' secondHalf)\n\nmain = do\n n <- getInt\n l <- getInts\n print $ thanosSort n l\n"}, {"source_code": "ordered :: Int -> [Int] -> (Bool, Int, Int, Int)\nordered 1 (x:[]) = (True, 1, x, x)\nordered n xs =\n if (bl && br) then\n if (maxl <= minr) then (True, n, minl, maxr)\n else (False, max sl sr, minl, maxl)\n else\n (False, max sl sr, minl, maxl)\n where\n nh = n `div` 2\n xl = take nh xs\n xr = drop nh xs\n (bl, sl, minl, maxl) = ordered nh xl\n (br, sr, minr, maxr) = ordered nh xr\n\n\n\ncal :: Int -> [Int] -> IO ()\ncal n xs = do\n let (_, a, _, _) = ordered n xs\n putStrLn $ show a\n\nmain :: IO ()\nmain = do\n a <- getLine\n word <- getLine\n let\n n = (read a):: Int\n xs = map (read :: String -> Int) $ words word\n cal n xs\n"}, {"source_code": "main = interact $ show . solve . map read . words . head . drop 1 . lines\n\n\nsolve :: [Int] -> Int\nsolve xs =\n let\n left = take (div (length xs) 2) xs\n right = drop (div (length xs) 2) xs\n isSortedL = isSorted left\n isSortedR = isSorted right\n continueL = solve left\n continueR = solve right\n in\n case isSorted xs of\n False ->if (isSortedL || isSortedR)\n then length left\n else if (continueL > continueR)\n then continueL\n else continueR\n True -> length xs\n\nisSorted :: (Ord a) => [a] -> Bool\nisSorted [] = True\nisSorted [x] = True\nisSorted (x:y:xs) = x <= y && isSorted(y:xs)\n"}, {"source_code": "\n\ndata Tree a=Leaf a|Branch (Tree a) (Tree a)\n\nmadeTree::[Int]->Tree [Int]\nmadeTree []=error \"can't made\"\nmadeTree (x:[])=Leaf [x]\nmadeTree lst=let\n len=round $ (fromIntegral $ length lst)/2\n fin\n |isSorted lst = Leaf lst\n |otherwise = Branch (madeTree $ take len lst) (madeTree $ drop len lst)\n in fin\n\nisSorted::[Int]->Bool\nisSorted []=False\nisSorted (x:[])=True\nisSorted (x:y:xs)\n |x<=y = isSorted (y:xs)\n |otherwise = False\n\ngetLens::Tree [a]->[[a]]\ngetLens (Leaf a)=[a]\ngetLens (Branch l z)=(getLens l)++(getLens z)\n\ngetInp::IO [Int]\ngetInp=do\n n <- getLine\n return $ map read $ words n\n\nfinal::[Int]->Int\nfinal=maximum . map length . getLens . madeTree\n\nmain::IO()\nmain=do\n n <- getLine\n m <- getInp\n print $ final m\n"}, {"source_code": "splitBy :: Char -> String -> [String]\nsplitBy _ \"\" = [];\nsplitBy delimiterChar inputString = foldr f [\"\"] inputString\n where f :: Char -> [String] -> [String]\n f currentChar allStrings@(partialString:handledStrings)\n | currentChar == delimiterChar = \"\":allStrings -- start a new partial string at the head of the list of all strings\n | otherwise = (currentChar:partialString):handledStrings -- add the current char to the partial string\n\nisSorted' :: (Ord a) => [a] -> Bool\nisSorted' xs = all id . map (\\(x,y) -> x <= y) . zip xs $ tail xs\n\nbigger :: Int -> Int -> Int\nbigger x y | (x > y) == True = x\n | (x <= y) == True = y\n\nsolve :: [Int] -> Int\nsolve x | isSorted' x == True = (length x)\n | isSorted' x == False = bigger (solve $take half x) (solve $drop half x)\n where half = (length x ) `div` 2\n\nconvert :: [String] -> [Int]\nconvert = map read\n\nmain = do\n cnt <- getLine\n input <- getLine\n\n let list = convert $splitBy ' ' input\n let ans = solve list\n \n print ans"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nnotGT x = foldr (&&) True $ zipWith (<=) x $ tail x \n\n\nsolve x = \n if length x == 1 \n then [x] \n else \n if notGT x \n then [x] \n else let (b,c) = splitAt (length x`div`2) x \n in solve b ++ solve c \n\nmain = B.getLine >> B.getLine >>= print . maximum . map length . solve . map(fst .fromJust . B.readInt) . B.words\n"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . fmap read . tail . words\n\nsolve :: [Int] -> Int\nsolve [n] = 1\nsolve ns | isSorted ns = length ns\n | otherwise = max (solve $ fst halves) (solve $ snd halves)\n where\n halves = half ns\n\nhalf :: [a] -> ([a], [a])\nhalf as = (take halfSize as, drop halfSize as)\n where\n halfSize = length as `div` 2\n\nisSorted :: Ord a => [a] -> Bool\nisSorted = and . (zipWith (<=) <*> tail)\n"}, {"source_code": "isSorted :: [Int] -> Bool\nisSorted x = ((and . (zipWith (<=) <*> tail)) x)\nsnap l = (\\(x,y) -> [x,y]) $ splitAt (length l `div` 2) l\nsolve l | isSorted l = [l]\n | otherwise = concatMap solve . snap $ l\nmain = interact $ show . maximum . map length . solve . map read . words . (!! 1) . lines\n"}], "negative_code": [{"source_code": "isSorted x = ((and . (zipWith (<=) <*> tail)) x) ||\n ((and . (zipWith (>=) <*> tail)) x)\nsnap l = (\\(x,y) -> [x,y]) $ splitAt (length l `div` 2) l\nsolve :: [Int] -> [[Int]]\nsolve l | isSorted l = [l]\n | otherwise = concatMap solve . snap $ l\nmain = interact $ show . maximum . map length . solve . map read . words . (!! 1) . lines\n"}, {"source_code": "import Control.Monad\nisSorted :: [Int] -> Bool\nisSorted x = ((and . (zipWith (<=) <*> tail)) x) ||\n ((and . (zipWith (>=) <*> tail)) x)\nsnap l = (\\(x,y) -> [x,y]) $ splitAt (length l `div` 2) l\nsolve [] = 0\nsolve l | isSorted l = length l\n | otherwise = maximum . map solve . snap $ l\nmain = interact $ show . solve . map read . words . (!! 1) . lines\n"}, {"source_code": "import Control.Monad\nsolve :: [Int] -> [Int]\nsolve x | or . (zipWith (>) `ap` tail) $ x = solve $ take (div (length x) 2) x\n | otherwise = x\nmain = interact $ show . length . solve . map read . words . (!! 1) . lines\n"}, {"source_code": "isSorted :: [Int] -> Bool\nisSorted x = ((and . (zipWith (<=) <*> tail)) x) ||\n ((and . (zipWith (>=) <*> tail)) x)\nsnap l = (\\(x,y) -> [x,y]) $ splitAt (length l `div` 2) l\nsolve l | isSorted l = [l]\n | otherwise = concatMap solve . snap $ l\nmain = interact $ show . maximum . map length . solve . map read . words . (!! 1) . lines\n"}], "src_uid": "e5c68be38968fbc9677f3c1adddaff58"} {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable(toList)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: IO Int\nreadInt = head `liftM` readIntList\n \nreadIntList :: IO [Int]\nreadIntList = do\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n\nreadString :: IO String\nreadString = do\n line <- B.getLine\n return $ B.unpack line\n \ngetSumPerPos :: Int -> [Int] -> Seq.Seq Int\ngetSumPerPos cnt = \n foldr step init\n where\n init = Seq.fromList $ replicate cnt 0\n step key seq = \n let oldVal = Seq.index seq (key - 1)\n in\n Seq.update (key - 1) (oldVal + 1) seq\n\nswap :: Seq.Seq a -> Int -> Int -> Seq.Seq a\nswap seq p1 p2 = \n let v1 = Seq.index seq p1\n v2 = Seq.index seq p2\n seq' = Seq.update p1 v2 seq\n seq'' = Seq.update p2 v1 seq'\n in\n seq''\n \ngetAns :: Seq.Seq Char -> Seq.Seq Int -> Int -> Int -> Int -> Seq.Seq Char\ngetAns str atPos low high acc \n | low >= high = str\n | otherwise = \n let acc' = Seq.index atPos low + acc\n str' = if acc' `mod` 2 == 0 then str else swap str low high \n in\n getAns str' atPos (low + 1) (high - 1) acc'\n \n \nmain = do\n s <- getLine\n m <- readInt\n ps <- readIntList\n let atPos = getSumPerPos (length s) ps\n let ans = toList $ getAns (Seq.fromList s) atPos 0 (length s - 1) 0\n putStrLn ans\n ", "positive_code": [{"source_code": "import Data.List (group, sort)\nimport Control.Arrow (first, second)\n\nmain :: IO ()\nmain = getLine >>= \\s -> getLine >> getLine >>= putStrLn . solve s . map read . words\n\nsolve :: String -> [Int] -> String\nsolve s a = uncurry (++) $ first reverse $ go True (\"\", \"\") (second reverse $ splitAt (l `div` 2) s) [1..l`div`2] as\n where go b (ps, qs) (c:cs, d:ds) (i:is) xxs@(x:xs) | i < x && b = go b (c:ps, d:qs) (cs, ds) is xxs\n | i < x = go b (d:ps, c:qs) (cs, ds) is xxs\n | b = go (not b) (d:ps, c:qs) (cs, ds) is xs\n | otherwise = go (not b) (c:ps, d:qs) (cs, ds) is xs\n go b (ps, qs) (c:cs, d:ds) (_:is) [] | b = go b (c:ps, d:qs) (cs, ds) is []\n | otherwise = go b (d:ps, c:qs) (cs, ds) is []\n go _ (ps, qs) ([], [d]) _ [] = (ps, d:qs)\n go _ (ps, qs) _ _ _ = (ps, qs)\n as = map head $ filter (odd . length) $ group $ sort a\n l = length s\n"}, {"source_code": "import Data.List (group, sort)\nimport Control.Arrow (first, second)\n\nmain :: IO ()\nmain = getLine >>= \\s -> getLine >> getLine >>= putStrLn . solve s . map read . words\n\nsolve :: String -> [Int] -> String\nsolve s a = uncurry (++) $ first reverse $ go True (\"\", \"\") (second reverse $ splitAt (length s `div` 2) s) [1..] as\n where go b (ps, qs) (c:cs, d:ds) (i:is) xxs@(x:xs) | i < x && b = go b (c:ps, d:qs) (cs, ds) is xxs\n | i < x = go b (d:ps, c:qs) (cs, ds) is xxs\n | b = go (not b) (d:ps, c:qs) (cs, ds) is xs\n | otherwise = go (not b) (c:ps, d:qs) (cs, ds) is xs\n go b (ps, qs) (ccs, dds) _ [] | b = (reverse ccs ++ ps, reverse dds ++ qs)\n | otherwise = (reverse dds ++ ps, reverse ccs ++ qs)\n go _ (ps, qs) _ _ _ = (ps, qs)\n as = map head $ filter (odd . length) $ group $ sort a\n"}, {"source_code": "import Data.List (group, sort)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . lines\n\nsolve :: [String] -> String\nsolve [s, _, a] = map (s'`B.index`) js ++ mid ++ map ((s'`B.index`) . ((l - 1) -)) (reverse js)\n where go b (i:is) xxs@(x:xs) | i < x && b = (i - 1) : go b is xxs\n | i < x = (l - i) : go b is xxs\n | b = (l - i) : go (not b) is xs\n | otherwise = (i - 1) : go (not b) is xs\n go b (i:is) [] | b = (i - 1) : go b is []\n | otherwise = (l - i) : go b is []\n go _ [] _ = []\n js = go True [1..l`div`2] $ map head $ filter (odd . length) $ group $ sort $ map read $ words a\n mid = if even l then \"\" else [ s' `B.index` (l `div` 2) ]\n l = B.length s'\n s' = B.pack s\nsolve _ = undefined\n"}, {"source_code": "import Data.List (group, sort)\nimport Control.Arrow (first, second)\n\nmain :: IO ()\nmain = getLine >>= \\s -> getLine >> getLine >>= putStrLn . solve s . map read . words\n\nsolve :: String -> [Int] -> String\nsolve s as = uncurry (++) $ first reverse $ go True (\"\", \"\") cssdss [1..] bs\n where go b (ps, qs) (c:cs, d:ds) (i:is) xxs@(x:xs)\n | i < x && b = go b (c:ps, d:qs) (cs, ds) is xxs\n | i < x = go b (d:ps, c:qs) (cs, ds) is xxs\n | b = go (not b) (d:ps, c:qs) (cs, ds) is xs\n | otherwise = go (not b) (c:ps, d:qs) (cs, ds) is xs\n go b (ps, qs) (ccs, dds) _ _\n | b = (reverse ccs ++ ps, reverse dds ++ qs)\n | otherwise = (reverse dds ++ ps, reverse ccs ++ qs)\n bs = map head $ filter (odd . length) $ group $ sort as\n cssdss = second reverse $ splitAt (length s `div` 2) s\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad hiding (foldM, foldM_)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray)\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n bs <- B.filter isLower <$> B.getLine\n getLine\n xs <- map readInt.B.words <$> B.getLine\n putStrLn $ solve bs xs\n\nsolve :: B.ByteString -> [Int] -> String\nsolve bs xs = map (B.index bs.f).zip[0..]$ scanl1 (+) $ map (unsafeAt freq) [0..n-1]\n where\n !n = B.length bs\n f (i, x) = if even x then i else n - i - 1\n \n freq :: UArray Int Int\n !freq = unsafeAccumArray (+) 0 (0,n) $ go xs\n where\n go (x:xs) = (x - 1, 1) : (n - x + 1, -1) : go xs\n go _ = []\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nfoldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a\nfoldM a xs f=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad hiding (foldM, foldM_)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray)\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n cs <- getLine\n getLine\n xs <- map readInt.B.words <$> B.getLine\n putStrLn $ solve cs xs\n\nsolve :: String -> [Int] -> String\nsolve cs xs = zipWith3 bool cs (reverse cs).map even$ scanl1 (+) $ map (unsafeAt diff) [0..n-1]\n where\n !n = length cs\n diff :: UArray Int Int\n !diff = unsafeAccumArray (+) 0 (0, n) $ foldr f [] xs\n where\n f x acc = (x - 1, 1) : (n - x + 1, -1) : acc\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nfoldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a\nfoldM a xs f=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Debug.Trace\n\nsolve :: String -> [Int] -> String\nsolve s as' = (f True 1 s' r' as) ++ \u00f6 ++ reverse (f False 1 s' r' as)\n where\n as = concat $ map (\\x -> if odd (length x) then [head x] else []) $ group (sort as')\n r = reverse s\n s' = take l s\n r' = take l r\n f _ _ [] _ _ = []\n f b n ss rs [] = if b then ss else rs\n f b n (s:ss) (r:rs) (a:as)\n | n == a = c : f b' (n+1) ss rs as\n | n /= a = c : f b' (n+1) ss rs (a:as)\n where\n b' = if a == n then not b else b\n c = if b' then s else r\n l = length s `div` 2\n \u00f6 = if odd (length s) then [head $ drop l s] else []\n\nmain = do\n s <- getLine\n getLine\n a <- fmap (fmap read . words) getLine\n putStrLn $ solve s a"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable(toList)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: IO Int\nreadInt = head `liftM` readIntList\n \nreadIntList :: IO [Int]\nreadIntList = do\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n\nreadString :: IO String\nreadString = do\n line <- B.getLine\n return $ filter (/= '\\r') $ B.unpack line\n \ngetSumPerPos :: Int -> [Int] -> Seq.Seq Int\ngetSumPerPos cnt = \n foldr step init\n where\n init = Seq.fromList $ replicate cnt 0\n step key seq = \n let oldVal = Seq.index seq (key - 1)\n in\n Seq.update (key - 1) (oldVal + 1) seq\n\nswap :: Seq.Seq a -> Int -> Int -> Seq.Seq a\nswap seq p1 p2 = \n let v1 = Seq.index seq p1\n v2 = Seq.index seq p2\n seq' = Seq.update p1 v2 seq\n seq'' = Seq.update p2 v1 seq'\n in\n seq''\n \ngetAns :: Seq.Seq Char -> Seq.Seq Int -> Int -> Int -> Int -> Seq.Seq Char\ngetAns str atPos low high acc \n | low >= high = str\n | otherwise = \n let acc' = Seq.index atPos low + acc\n str' = if acc' `mod` 2 == 0 then str else swap str low high \n in\n getAns str' atPos (low + 1) (high - 1) acc'\n \n \nmain = do\n s <- readString\n m <- readInt\n ps <- readIntList\n let atPos = getSumPerPos (length s) ps\n let ans = toList $ getAns (Seq.fromList s) atPos 0 (length s - 1) 0\n putStrLn ans\n "}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport Data.Monoid ((<>))\n\nmain :: IO ()\nmain = B.getContents >>= B.putStrLn . solve . B.lines\n\nsolve :: [B.ByteString] -> B.ByteString\nsolve [s, _, a] = foldl' f s (map (fst . fromJust . B.readInt) (B.words a))\n where f t i = let (t0, t') = B.splitAt (i - 1) t\n (t1, t2) = B.splitAt (l - 2 * i + 2) t'\n in t0 <> B.reverse t1 <> t2\n l = B.length s\nsolve _ = undefined\n"}, {"source_code": "import Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= B.putStrLn . solve . B.lines\n\nsolve :: [B.ByteString] -> B.ByteString\nsolve [s, _, a] = foldl' f s (map (fst . fromJust . B.readInt) (B.words a))\n where f t i = t0 `B.append` B.reverse t1 `B.append` t2\n where (t0, t') = B.splitAt (i - 1) t\n (t1, t2) = B.splitAt (B.length t - 2 * i + 2) t'\nsolve _ = undefined\n"}, {"source_code": "import Data.List (group, sort)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = getLine >>= \\s -> getLine >> getLine >>= putStrLn . solve s . map read . words\n\nsolve :: String -> [Int] -> String\nsolve s a = reverse ls ++ rs\n where go b (ps, qs) (c:cs, d:ds) (i:is) xxs@(x:xs) | i < x && b = go b (c:ps, d:qs) (cs, ds) is xxs\n | i < x = go b (d:ps, c:qs) (cs, ds) is xxs\n | b = go (not b) (d:ps, c:qs) (cs, ds) is xs\n | otherwise = go (not b) (c:ps, d:qs) (cs, ds) is xs\n go b (ps, qs) (c:cs, d:ds) (_:is) [] | b = go b (c:ps, d:qs) (cs, ds) is []\n | otherwise = go b (d:ps, c:qs) (cs, ds) is []\n go _ (ps, qs) ([], [d]) _ [] = (ps, d:qs)\n go _ (ps, qs) _ _ _ = (ps, qs)\n (ls, rs) = go True (\"\", \"\") (splitAt (l `div` 2) s) [1..l`div`2] as\n as = map head $ filter (odd . length) $ group $ sort a\n l = B.length s'\n s' = B.pack s\n"}, {"source_code": "import Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport Data.Monoid ((<>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= B.putStrLn . solve . B.lines\n\nsolve :: [B.ByteString] -> B.ByteString\nsolve [s, _, a] = foldl' f s (map (fst . fromJust . B.readInt) (B.words a))\n where f t i = t0 <> B.reverse t1 <> t2\n where (t0, t') = B.splitAt (i - 1) t\n (t1, t2) = B.splitAt (l - 2 * i + 2) t'\n l = B.length s\nsolve _ = undefined\n"}, {"source_code": "import Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport Data.Monoid ((<>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= B.putStr . solve . B.lines\n\nsolve :: [B.ByteString] -> B.ByteString\nsolve [s, _, a] = foldl' f s (map (fst . fromJust . B.readInt) (B.words a))\n where f t i = t0 <> B.reverse t1 <> t2\n where (t0, t') = B.splitAt (i - 1) t\n (t1, t2) = B.splitAt (B.length t - 2 * i + 2) t'\nsolve _ = undefined\n"}, {"source_code": "import Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport Data.Monoid ((<>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= putStrLn . solve . B.lines\n\nsolve :: [B.ByteString] -> String\nsolve [s, _, a] = B.unpack $ foldl' f s (map (fst . fromJust . B.readInt) (B.words a))\n where f t i = t0 <> B.reverse t1 <> t2\n where (t0, t') = B.splitAt (i - 1) t\n (t1, t2) = B.splitAt (B.length t - 2 * i + 2) t'\nsolve _ = undefined\n"}, {"source_code": "import Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport Data.Monoid ((<>))\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= B.putStrLn . solve . B.lines\n\nsolve :: [B.ByteString] -> B.ByteString\nsolve [s, _, a] = foldl' f s (map (fst . fromJust . B.readInt) (B.words a))\n where f t i = t0 <> B.reverse t1 <> t2\n where (t0, t') = B.splitAt (i - 1) t\n (t1, t2) = B.splitAt (B.length t - 2 * i + 2) t'\nsolve _ = undefined\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable(toList)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: IO Int\nreadInt = head `liftM` readIntList\n \nreadIntList :: IO [Int]\nreadIntList = do\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n\nreadString :: IO String\nreadString = do\n line <- B.getLine\n return $ B.unpack line\n \ngetSumPerPos :: Int -> [Int] -> Seq.Seq Int\ngetSumPerPos cnt = \n foldr step init\n where\n init = Seq.fromList $ replicate cnt 0\n step key seq = \n let oldVal = Seq.index seq (key - 1)\n in\n Seq.update (key - 1) (oldVal + 1) seq\n\nswap :: Seq.Seq a -> Int -> Int -> Seq.Seq a\nswap seq p1 p2 = \n let v1 = Seq.index seq p1\n v2 = Seq.index seq p2\n seq' = Seq.update p1 v2 seq\n seq'' = Seq.update p2 v1 seq'\n in\n seq''\n \ngetAns :: Seq.Seq Char -> Seq.Seq Int -> Int -> Int -> Int -> Seq.Seq Char\ngetAns str atPos low high acc \n | low >= high = str\n | otherwise = \n let acc' = Seq.index atPos low + acc\n str' = if acc' `mod` 2 == 0 then str else swap str low high \n in\n getAns str' atPos (low + 1) (high - 1) acc'\n \n \nmain = do\n s <- readString\n m <- readInt\n ps <- readIntList\n let atPos = getSumPerPos (length s) ps\n let ans = toList $ getAns (Seq.fromList s) atPos 0 (length s - 1) 0\n putStrLn ans\n \n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport Data.Foldable(toList)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: IO Int\nreadInt = head `liftM` readIntList\n \nreadIntList :: IO [Int]\nreadIntList = do\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n\nreadString :: IO String\nreadString = do\n line <- B.getLine\n return $ filter (/= '\\r') $ B.unpack line\n \ngetSumPerPos :: Int -> [Int] -> Seq.Seq Int\ngetSumPerPos cnt = \n foldr step init\n where\n init = Seq.fromList $ replicate cnt 0\n step key seq = \n let oldVal = Seq.index seq (key - 1)\n in\n Seq.update (key - 1) (oldVal + 1) seq\n\nswap :: Seq.Seq a -> Int -> Int -> Seq.Seq a\nswap seq p1 p2 = \n let v1 = Seq.index seq p1\n v2 = Seq.index seq p2\n seq' = Seq.update p1 v2 seq\n seq'' = Seq.update p2 v1 seq'\n in\n seq''\n \ngetAns :: Seq.Seq Char -> Seq.Seq Int -> Int -> Int -> Int -> Seq.Seq Char\ngetAns str atPos low high acc \n | low >= high = str\n | otherwise = \n let acc' = Seq.index atPos low + acc\n str' = if acc' `mod` 2 == 0 then str else swap str low high \n in\n getAns str' atPos (low + 1) (high - 1) acc'\n \n \nmain = do\n s <- readString\n print s\n print $ length s\n m <- readInt\n ps <- readIntList\n let atPos = getSumPerPos (length s) ps\n let ans = toList $ getAns (Seq.fromList s) atPos 0 (length s - 1) 0\n putStrLn ans\n "}], "src_uid": "9d46ae53e6dc8dc54f732ec93a82ded3"} {"source_code": "main=interact$solve.map read.words\nsolve (n:x)=if check $ map f x then \"Yes\" else \"No\"\n where g b a| a`mod`b==0 = g b $ a`div`b\n | otherwise = a\n f = g 3 . g 2 \n check (a:x) = all (==a) x", "positive_code": [{"source_code": "main = interact $ solve . map read . words\nsolve (_:xs) = if allEqual . map f $ xs then \"Yes\" else \"No\"\n\twhere\n\t\tf x\n\t\t\t| x `mod` 2 == 0\t= f (x `div` 2)\n\t\t\t| x `mod` 3 == 0\t= f (x `div` 3)\n\t\t\t| otherwise\t\t\t= x\n\t\tallEqual (x:xs)\t\t\t= and . map (== x) $ xs\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . yesno . solve . map read . tail . words =<< getContents\n\nsolve :: [Integer] -> Bool\nsolve as = all (==1) [ divs 2 $ divs 3 $ a `div` foldr1 gcd as | a <- as ]\n\ndivs :: Integer -> Integer -> Integer\ndivs n m | m `mod` n == 0 = divs n $ m `div` n\n | otherwise = m\n\nyesno :: Bool -> String\nyesno True = \"Yes\"\nyesno _ = \"No\"\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . yesno . solve . map read . tail . words =<< getContents\n\nsolve :: [Integer] -> Bool\nsolve as = all (==1) [ divs 2 $ divs 3 $ a `div` foldr1 gcd as | a <- as ]\n\ndivs :: Integral a => a -> a -> a\ndivs n m | m `mod` n == 0 = divs n $ m `div` n\n | otherwise = m\n\nyesno :: Bool -> String\nyesno True = \"Yes\"\nyesno _ = \"No\"\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . yesno . solve . map read . tail . words =<< getContents\n\nsolve :: [Integer] -> Bool\nsolve = same . map (divs 2 . divs 3)\n\ndivs :: Integral a => a -> a -> a\ndivs n m | m `mod` n == 0 = divs n $ m `div` n\n | otherwise = m\n\nsame :: Eq a => [a] -> Bool\nsame xs = all (==head xs) xs\n\nyesno :: Bool -> String\nyesno True = \"Yes\"\nyesno _ = \"No\"\n"}, {"source_code": "import Data.List\nmain = interact $ format . group . map (purge . read) . tail . words\npurge n | n `mod` 2 == 0 = purge (n `div` 2)\n | n `mod` 3 == 0 = purge (n `div` 3)\n | otherwise = n\nformat [_] = \"Yes\"\nformat _ = \"No\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nsolve :: [Int] -> String\nsolve a = if all (== x) xs then \"Yes\" else \"No\"\n where\n (x:xs) = map ((\\i -> i `div` gcd b i) . fromIntegral) a\n b = 2^29 * 3^18 :: Int64\n\nmain = do\n [n] <- parse <$> B.getLine\n a <- parse <$> B.getLine\n putStrLn $ solve a\n"}, {"source_code": "module Main(main) where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Functor\nimport Data.Int (Int64)\n\ngetNums64 :: B.ByteString -> [Int64]\ngetNums64 =\n\tlet\n\t\tf1 = (map (fromInteger . (fst.fromJust) . B.readInteger))\n\t\tf2 = (B.split ' ')\n\tin f1.f2\ngetNums :: B.ByteString -> [Int]\ngetNums =\n\tlet\n\t\tf1 = (map ((fst.fromJust) . B.readInt))\n\t\tf2 = (B.split ' ')\n\tin f1.f2\nreadInts :: IO [Int]\nreadInts = getNums <$> B.getLine\nreadInts64 :: IO [Int64]\nreadInts64 = getNums64 <$> B.getLine\n\ncheck 1 = True\ncheck a = if a `mod` 2 == 0 then check $ a `div` 2 else if a `mod` 3 == 0 then check $ a `div` 3 else False\n\nmain = do\n\tn <- readInts\n\ta <- readInts\n\tlet g = foldl gcd 0 a\n\tlet b = map (\\x -> x `div` g) a\n\tlet c = all check b\n\tputStrLn $ if c then \"Yes\" else \"No\"\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n\nred x \t| mod x 2 ==0 = red (div x 2)\n\t| mod x 3 ==0 = red (div x 3)\n\t| otherwise = x\n\nprocess s= all (==th) t\n\t where t = map red s\n\t th = head t\n\nmain= do\n\tn<-read <$> getLine::IO Int\n\ts<- map read .words <$> getLine ::IO [Int]\n\tputStrLn $ if process s then \"YES\" else \"NO\""}, {"source_code": "main = do\n xs <- getContents\n (putStrLn . print_ . solve) (map read (words ((lines xs)!!1)))\n\nprint_ True = \"Yes\"\nprint_ False = \"No\"\n\nsolve :: [Int] -> Bool\nsolve = all_equal . map norm\ngen_norm k x | x `mod` k == 0 = gen_norm k (x `div` k)\n | otherwise = x\nnorm = gen_norm 2 . gen_norm 3\nall_equal (x:xs) = all (\\y -> x == y) xs\nall_equal [] = undefined\n"}, {"source_code": "import System.IO\nimport Data.Int\nimport Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = map (read :: (String -> Int64)) . words <$> tail contents\n\n putStrLn $ ifYes (solve (head arr))\n\n-- solve :: [[Char]] -> [IO [()]]\n-- solve :: [] -> [IO ()]\nsolve arr =\n let max = foldl' gcd 0 arr\n check x\n | x == 1 = True\n | x `mod` 2 == 0 = check (x `div` 2)\n | x `mod` 3 == 0 = check (x `div` 3)\n | otherwise = False\n check2 x y = (x `mod` y == 0) && check (x `div` y)\n in all (`check2` max) arr\n\nifYes True = \"Yes\"\nifYes False = \"No\""}, {"source_code": "import Control.Monad\nimport Data.List\n\nred2 :: Int -> Int\nred2 x\n | even x = red2 (div x 2)\n | otherwise = x\n\nred3 :: Int -> Int\nred3 x\n | mod x 3 == 0 = red3 (div x 3)\n | otherwise = x\n\ncanEqual :: [Int] -> Bool\ncanEqual a =\n let b = map (red3 . red2) a\n in all (== (head b)) $ tail b\n\nmyShow :: Bool -> String\nmyShow True = \"Yes\"\nmyShow False = \"No\"\n\nmain :: IO()\nmain = do\n n <- readLn\n a <- liftM (map read . take n . words) getLine\n putStr . myShow $ canEqual a"}, {"source_code": "main = interact $ show'.and.(\\x -> map (== head x) (tail x)).map red.tail.map read.words\n\nred :: Int -> Int\nred x\n |mod x 2 == 0 = red $ x `div` 2\n |mod x 3 == 0 = red $ x `div` 3\n |otherwise = x\n\nshow' :: Bool -> [Char]\nshow' True = \"Yes\"\nshow' False = \"No\"\n"}, {"source_code": "main = interact $ show' . eql . map red . tail . map read . words\n\nred :: Integer -> Integer\nred x\n |mod x 2 == 0 = red $ x `div` 2\n |mod x 3 == 0 = red $ x `div` 3\n |otherwise = x\n\neql :: Eq a => [a] -> Bool\neql x = and $ map (== head x) (tail x)\n\nshow' :: Bool -> [Char]\nshow' True = \"Yes\"\nshow' False = \"No\"\n"}, {"source_code": "module Main where\nimport Control.Applicative\n\ndivide d = go where \n go n | rem n d == 0 = go $ quot n d \n go n = n\n\n\nmain = do\n getLine\n a : as <- map (divide 2 . divide 3 . read) <$> words <$> getLine\n putStrLn $ if all (== a) as then \"Yes\" else \"No\"\n"}, {"source_code": "baseQ = (base 2) . (base 3)\nbase n stake\n | stake `mod` n == 0 = base n (stake `div` n)\n | otherwise = stake\n \nans (x : t@(y : xs))\n | x /= y = \"No\"\n | otherwise = ans t\nans _ = \"Yes\"\n\nmain = do\n tmp <- getLine\n list <- getLine\n let stakes = map read $ words list :: [Int]\n let bases = map baseQ stakes\n putStrLn $ ans bases"}, {"source_code": "main=interact$solve.map read.words\nsolve (n:x)=if check $ map f x then \"Yes\" else \"No\"\n where g a b| a`mod`b==0 = g (a`div`b) b\n | otherwise = a\n f x = g (g x 2) 3\n check x = minimum x == maximum x"}, {"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n let (x:xs) = map reduce a\n if all (==x) xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nreduce :: Int -> Int\nreduce a = f3 (f2 a)\n where f3 n = if n `rem` 3 ==0 then f3 (n `quot` 3) else n\n f2 n = if even n then f2 (n `quot` 2) else n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n ys = map f xs\n where\n f x = until odd (`div` 2) $ until (\\x -> x `mod` 3 /= 0) (`div` 3) x\n b = and $ zipWith (==) ys $ tail ys\n\n putStrLn $ if b then \"Yes\" else \"No\"\n"}, {"source_code": "main :: IO ()\nmain = do\n n <- read_n\n a <- read_a\n let aa = map simplify a\n rs = if allEqu aa then \"Yes\" else \"No\"\n putStrLn rs\n\n\nread_n :: IO Integer\nread_n = do\n s <- getLine\n let n = read s :: Integer in return n\n\nread_a :: IO [Integer]\nread_a = do\n s <- getLine\n let a = map (\\x -> read x :: Integer) $ words s in return a\n\nsimplify :: Integer -> Integer\nsimplify x\n | x `mod` 2 == 0 = simplify $ x `div` 2\n | x `mod` 3 == 0 = simplify $ x `div` 3\n | otherwise = x\n\nallEqu :: [Integer] -> Bool\nallEqu [] = True\nallEqu (x:xs) = length (filter (== x) xs) == (length xs)\n"}, {"source_code": "main = interact $ solve . map read . words\nsolve (_:xs) = if allEqual . map f $ xs then \"Yes\" else \"No\"\n\twhere\n\t\tf x\n\t\t\t| x `mod` 2 == 0\t= f (x `div` 2)\n\t\t\t| x `mod` 3 == 0\t= f (x `div` 3)\n\t\t\t| otherwise\t\t\t= x\n\t\tallEqual []\t\t\t= True\n\t\tallEqual (x:[])\t\t= True\n\t\tallEqual (x1:x2:xs)\t= x1 == x2 && allEqual (x2:xs)\n"}], "negative_code": [{"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n putStrLn $ solve a\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (_:[]) = \"YES\"\nsolve (a:b:ls) = fn a b\n where fn x y = let d = gcd x y\n c1 = x `div` d\n c2 = y `div` d\n in if and [(c1 `rem` 2==0 || c1 `rem` 3==0 || c1 == 1),(c2 `rem` 2==0 || c2 `rem` 3==0 || c2==1)] then solve (d:ls) else \"NO\""}, {"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n let (x:xs) = map reduce a\n if all (==x) xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nreduce :: Int -> Int\nreduce a = f3 (f2 a)\n where f3 n = if n `rem` 3 ==0 then f3 (n `quot` 3) else n\n f2 n = if even n then f3 (n `quot` 2) else n"}, {"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n let (x:xs) = map reduce a\n print (x:xs)\n if all (==x) xs\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nreduce :: Int -> Int\nreduce a = f3 (f2 a)\n where f3 n = if n `rem` 3 ==0 then f3 (n `quot` 3) else n\n f2 n = if even n then f2 (n `quot` 2) else n"}, {"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n putStrLn $ solve a\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (_:[]) = \"YES\"\nsolve (a:b:ls) = fn a b\n where fn x y = let d = gcd x y\n c1 = x `div` d\n c2 = y `div` d\n in if and [(c1 `rem` 2==0 || c1 `rem` 3==0 || c1 == 1),(c2 `rem` 2==0 || c2 `rem` 3==0 || c2==1)] then solve (x*y:ls) else \"NO\""}, {"source_code": "\n\nmain :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n putStrLn $ solve a\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (_:[]) = \"YES\"\nsolve (a:b:ls) = fn a b\n where fn x y = let d = gcd x y\n c1 = x `div` d\n c2 = y `div` d\n in if and [(c1 `rem` 2==0 || c1 `rem` 3==0 || c1 == 1),(c2 `rem` 2==0 || c2 `rem` 3==0 || c2==1)] then solve (b:ls) else \"NO\""}, {"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n putStrLn $ solve a\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (_:[]) = \"YES\"\nsolve (a:b:ls) = fn a b\n where fn x y = let d = gcd x y\n c1 = x `div` d\n c2 = y `div` d\n in if and [(c1 `rem` 2==0 || c1 `rem` 3==0 || c1 == 1),(c2 `rem` 2==0 || c2 `rem` 3==0 || c2==1)] then solve (d*c1*c2:ls) else \"NO\""}, {"source_code": "\n\nmain :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Int) . words) getLine\n putStrLn $ solve a\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (_:[]) = \"YES\"\nsolve (a:b:ls) = fn a b\n where fn x y = let d = gcd x y\n c1 = x `div` d\n c2 = y `div` d\n in if and [(c1 `rem` 2==0 || c1 `rem` 3==0 || c1 == 1),(c2 `rem` 2==0 || c2 `rem` 3==0 || c2==1)] then solve (lcm a b:ls) else \"NO\""}, {"source_code": "main :: IO()\nmain = do\n _ <- readLn :: IO Int\n a <- fmap (map (\\x -> read x::Integer) . words) getLine\n putStrLn $ solve a\n\nsolve :: [Integer] -> String\nsolve [] = \"YES\"\nsolve (_:[]) = \"YES\"\nsolve (a:b:ls) = fn a b\n where fn x y = let d = gcd x y\n c1 = x `div` d\n c2 = y `div` d\n in if and [(c1 `rem` 2==0 || c1 `rem` 3==0 || c1 == 1),(c2 `rem` 2==0 || c2 `rem` 3==0 || c2==1)] then solve (lcm a b:ls) else \"NO\""}, {"source_code": "main :: IO ()\nmain = putStrLn . yesno . solve . map read . tail . words =<< getContents\n\nsolve :: [Integer] -> Bool\nsolve as = all (==1) [ divs 2 $ divs 3 $ a `div` foldr1 gcd as | a <- as ]\n\ndivs :: Integer -> Integer -> Integer\ndivs n m | m `mod` n == 0 = m `div` n\n | otherwise = m\n\nyesno :: Bool -> String\nyesno True = \"Yes\"\nyesno _ = \"No\"\n"}, {"source_code": "main :: IO ()\nmain = putStrLn . yesno . solve . map read . tail . words =<< getContents\n\nsolve :: [Int] -> Bool\nsolve as = all (==1) [ divs 2 $ divs 3 $ a `div` foldr1 gcd as | a <- as ]\n\ndivs :: Int -> Int -> Int\ndivs n m | m `mod` n == 0 = m `div` n\n | otherwise = m\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nsolve :: [Int] -> String\nsolve a = if all (== x) xs then \"Yes\" else \"No\"\n where (x:xs) = map (\\i -> i `div` gcd 6 i) a\n\nmain = do\n [n] <- parse <$> B.getLine\n a <- parse <$> B.getLine\n putStrLn $ solve a\n"}, {"source_code": "import System.IO\nimport Data.Int\nimport Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = map (read :: (String -> Int64)) . words <$> tail contents\n\n putStrLn $ ifYes (solve (head arr))\n\n-- solve :: [[Char]] -> [IO [()]]\n-- solve :: [] -> [IO ()]\nsolve arr =\n let max = foldl' gcd 0 arr\n check x\n | x == 1 = True\n | x `mod` 2 == 0 = check (x `div` 2)\n | x `mod` 3 == 0 = check (x `div` 3)\n | otherwise = False\n check2 x y = (x `mod` y == 0) && check (x `div` y)\n in all (check2 max) arr\n\nifYes True = \"Yes\"\nifYes False = \"No\""}, {"source_code": "import System.IO\nimport Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = map (read :: (String -> Int)) . words <$> tail contents\n\n putStrLn $ ifYes (solve (head arr))\n\n-- solve :: [[Char]] -> [IO [()]]\n-- solve :: [] -> [IO ()]\nsolve arr =\n let max = maximum arr\n check x\n | x == 1 = True\n | x `mod` 2 == 0 = check (x `div` 2)\n | x `mod` 3 == 0 = check (x `div` 3)\n | otherwise = False\n check2 x y = (x `mod` y == 0) && check (x `div` y)\n in all (check2 max) arr\n\nifYes True = \"Yes\"\nifYes False = \"No\""}, {"source_code": "import System.IO\nimport Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n\nfactor k =\n let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]\n in if null arr then k else head arr\n\n\nmain = do\n hSetBuffering stdin (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- lines <$> getContents\n let arr = map (read :: (String -> Int)) . words <$> tail contents\n\n putStrLn $ ifYes (solve (head arr))\n\n-- solve :: [[Char]] -> [IO [()]]\n-- solve :: [] -> [IO ()]\nsolve arr =\n let sorted = reverse (sort arr)\n max = head sorted\n check x\n | x == 1 = True\n | x `mod` 2 == 0 = check (x `div` 2)\n | x `mod` 3 == 0 = check (x `div` 3)\n | otherwise = False\n check2 x y = (x `mod` y == 0) && check (x `div` y)\n in all (check2 max) sorted\n\nifYes True = \"Yes\"\nifYes False = \"No\""}], "src_uid": "2bb893703cbffe9aeaa0bed02f42a05c"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main where\nimport Control.Applicative\n--import Data.List\n\n\n-- | A strictly accumulating version of 'scanl'\n{-# NOINLINE [1] scanl' #-}\nscanl' :: (b -> a -> b) -> b -> [a] -> [b]\n-- This peculiar form is needed to prevent scanl' from being rewritten\n-- in its own right hand side.\nscanl' = scanlGo'\n where\n scanlGo' :: (b -> a -> b) -> b -> [a] -> [b]\n scanlGo' f !q ls = q : (case ls of\n [] -> []\n x:xs -> scanlGo' f (f q x) xs)\n\n\n\nwalk p x = min x $ p + 1\ngrows = tail . scanl' walk 0\nheels xs = zipWith min (grows xs) $ reverse $ grows $ reverse xs\ndestroy = maximum . heels \n\nmain = do\n getLine\n hs <- map read <$> words <$> getLine\n print $ destroy hs\n \n", "positive_code": [{"source_code": "module Main(main) where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Functor\n\ngetNums :: B.ByteString -> [Int]\ngetNums =\n\tlet\n\t\tf1 = (map ((fst.fromJust) . B.readInt))\n\t\tf2 = (B.split ' ')\n\tin f1.f2\nreadInts :: IO [Int]\nreadInts = getNums <$> B.getLine\n\nmain::IO ()\nmain = do\n\t_ <- readInts\n\th <- readInts\n\tlet fn a b = min (a+1) b\n\tlet lft = tail $ scanl fn 0 h\n\tlet rt = reverse $ tail $ scanl fn 0 $ reverse h\n\tlet ans = (foldl max 0 $ zipWith min lft rt)::Int\n\tprint ans\n"}, {"source_code": "module Main where\n\nimport Data.Functor\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = map read . words <$> getLine\n\nfoldmap f v [] = []\nfoldmap f v (x:xs) = res : foldmap f res xs where\n res = f v x\n\nmain :: IO ()\nmain = do\n n <- getInt\n ns <- getInts\n let left = foldmap (\\x y -> min (x+1) y) 0 ns\n let right = reverse $ foldmap (\\x y -> min (x+1) y) 0 $ reverse ns\n print $ foldr max 0 (zipWith min left right)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nsolve :: [Int] -> Int\nsolve = maximum . scanr go 0 . scanl (flip go) 0\n where go i = min i . succ\n\nmain = B.getLine >> solve . parse <$> B.getLine >>= print\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nsolve :: [Int] -> Int\nsolve = maximum . scanr go 0 . scanl (flip go) 0\n where go i = min i . succ\n\nmain = do\n B.getLine\n solve . parse <$> B.getLine >>= print\n"}, {"source_code": "module Main(main) where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Functor\nimport Data.Int (Int64)\n\ngetNums64 :: B.ByteString -> [Int64]\ngetNums64 =\n\tlet\n\t\tf1 = (map (fromInteger . (fst.fromJust) . B.readInteger))\n\t\tf2 = (B.split ' ')\n\tin f1.f2\ngetNums :: B.ByteString -> [Int]\ngetNums =\n\tlet\n\t\tf1 = (map ((fst.fromJust) . B.readInt))\n\t\tf2 = (B.split ' ')\n\tin f1.f2\nreadInts :: IO [Int]\nreadInts = getNums <$> B.getLine\nreadInts64 :: IO [Int64]\nreadInts64 = getNums64 <$> B.getLine\n\nfoldmap fn v [] = []\nfoldmap fn v (x:xs) = let v2 = fn v x in (v2 `seq` v2) : foldmap fn v2 xs\n\nmain = do\n\tn <- readInts\n\th <- readInts\n\tlet fn a b = min (a+1) b\n\tlet lft = foldmap fn 0 h\n\tlet rt = reverse $ foldmap fn 0 $ reverse h\n\tlet ans = foldl max 0 $ map (\\(a,b) -> min a b) $ zip lft rt\n\tprint ans\n"}, {"source_code": "import Data.List\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let p1 = pass1 (zip a [1..n]) 0\n p2 = pass2 (reverse (zip a [1..n])) (reverse p1) (n+1)\n print . maximum $ p2\n\npass1 [] _ = []\npass1 ((e,i):as) x = let w = min x (e-i) in (i+w):pass1 as w\n\npass2 [] [] _ = []\npass2 ((e,i):xs) (y:ys) x =\n let w = min x (e+i)\n in (min (w-i) y : pass2 xs ys w)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main where\nimport Control.Applicative\n\nscanl' f = go where \n go q [] = [q]\n go q (x: xs) = q : go (f q x) xs\n\nwalk p x = min x $ p + 1\ngrows = tail . scanl' walk 0\nheels xs = zipWith min (grows xs) $ reverse $ grows $ reverse xs\ndestroy = maximum . heels \n\nmain = do\n getLine\n hs <- map read <$> words <$> getLine\n print $ destroy hs\n \n"}], "negative_code": [{"source_code": "import Data.List\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let p1 = pass1 (zip a [1..n]) 0\n p2 = pass2 (reverse (zip a [1..n])) (reverse p1) (n+1)\n print . maximum $ p2\n\npass1 [] _ = []\npass1 (a:as) x = ((snd a) + min x ((fst a)-(snd a))) : pass1 as (min x ((fst a)-(snd a)))\n\npass2 [] [] _ = []\npass2 ((e,i):xs) (y:ys) x =\n let w = min x (e+i)\n in (min w y : pass2 xs ys w)"}], "src_uid": "a548737890b4bf322d0f8989e5cd25ac"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport Data.List\nimport Data.Array.IArray hiding ((!))\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ntype Pos = (Int, Int)\n\nadd (x1, y1) (x2, y2) = (x1+x2, y1+y2)\n\nprocess :: [Pos] -> [Pos] -> Pos\nprocess obelisks clues = minimum obelisks `add` maximum clues\n\nmain = do\n n <- getInt\n obelisks <- force <$> replicateM n (readPoint <$> getInts)\n clues <- force <$> replicateM n (readPoint <$> getInts)\n putStrLn $ showPoint $ process obelisks clues\n\nreadPoint (x:y:[]) = (x, y)\nshowPoint (x, y) = show x ++ \" \" ++ show y\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n ls <- unfoldr (\\bs0 -> do (x,bs1) <- BSL.readInt $ BSL.dropWhile (<'!') bs0\n (y,bs2) <- BSL.readInt $ BSL.dropWhile (<'!') bs1\n return ((x,y),bs2)) <$> BSL.getContents\n let (xys, ls1) = splitAt n ls\n abs = take n ls1\n (x,y) = minimum xys\n (a,b) = maximum abs\n putStrLn $ shows (a+x) $ ' ' : show (y+b)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nsolve obel clue = (x,y)\n where x = maximum (map fst obel) + minimum (map fst clue)\n y = maximum (map snd obel) + minimum (map snd clue)\n\ntuple [x,y] = (x,y)\n\nmain = do\n [n] <- getInts\n obel <- forM [1..n] (\\_-> getInts)\n clue <- forM [1..n] (\\_-> getInts)\n let (x, y) = solve (map tuple obel) (map tuple clue)\n putStrLn $ show x ++ \" \" ++ show y\n"}], "negative_code": [], "src_uid": "ba526a7f29cf7f83afa0b71bcd06e86b"} {"source_code": "import Data.List\n\ndigits _ 0 _ = []\ndigits base n num = num `mod` base : digits base (n - 1) (num `div` base)\n\nmain = do\n contents <- getContents\n let [n, k, d] = map read $ words contents\n let ans = transpose $ map (map (+ 1) . digits k d) [1..n]\n putStr (if (k ^ d) < n then \"-1\" else unlines $ map (unwords . map show) ans)\n", "positive_code": [{"source_code": "\nimport Data.List\n\nmain = interact $ sol . map read . words\n\nsol (n:k:d:_)\n\t| n > (k^d) = \"-1\"\n\t| otherwise = intercalate \"\\n\" .\n\t\t\t\t map (intercalate \" \" . map show) .\n\t\t\t\t transpose .\n\t\t\t\t map (reverse . (kd k d)) $ [0..n-1]\n\nkd _ 0 _ = []\nkd k d n = (n`mod`k+1) : (kd k (d-1) (n`div`k))\n\n"}, {"source_code": "import Data.List (transpose)\n\nmain = interact $ f . map read . words\n\nf :: [Integer] -> String\nf (n:b:d:_)\n | n > b^d = show (-1)\n | otherwise = f' (fromIntegral n) b d\n\nf' n b d = unlines . map unwords . transpose . take n $ g b d [[]]\n\ng _ 0 ls = ls\ng b d ls = g b (d-1) [(show x):l | x <- [1..b], l <- ls]\n"}, {"source_code": "-- Codeforces 459C\n\nimport Data.List\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve . map read . words\n\nsolve :: [Int] -> String\nsolve [n, k, d] = if check $ map toInteger [n, k, k, d]\n then \"-1\"\n else intercalate \"\\n\" $ map (intercalate \" \" . map show) $ transpose $ scanl (\\acc _ -> inc acc) (replicate d 1) [1..n-1] where inc = tail . map snd . scanl (\\(cin, _) x -> if x+cin > k then (1, x+cin-k) else (0, x+cin)) (1, 0)\n\ncheck :: [Integer] -> Bool\ncheck [n, _, _, 0] = True\ncheck [n, acc, k, d] = if acc >= n then False else check [n, (k*acc), k, (d-1)]\n"}, {"source_code": "\nimport Data.List\n\nmain = interact $ sol . map read . words\n\nsol (n:k:d:_)\n\t| n > ep k d 1 = \"-1\"\n\t| otherwise = intercalate \"\\n\" .\n\t\t\t\t map (intercalate \" \" . map show) .\n\t\t\t\t transpose .\n\t\t\t\t map (reverse . (kd k d)) $ [0..n-1]\n\nep _ 0 s = s\nep k d s\n\t| s > 1000 = s\n\t| otherwise = ep k (d-1) s*k\n\nkd _ 0 _ = []\nkd k d n = (n`mod`k+1) : (kd k (d-1) (n`div`k))\n\n\n"}], "negative_code": [{"source_code": "import Data.List (transpose)\n\nmain = interact $ f . map read . words\n\nf (n:b:d:_)\n | n > b^d = show (-1)\n | otherwise = f' n b d\n\nf' n b d = unlines . map unwords . transpose . take n $ g b d [[]]\n\ng _ 0 ls = ls\ng b d ls = g b (d-1) [(show x):l | x <- [1..b], l <- ls]\n"}, {"source_code": "\nimport Data.List\n\nmain = interact $ sol . map read . words\n\nsol (n:k:d:_)\n\t| n > ep k d 1 = \"-1\"\n\t| otherwise = intercalate \"\\n\" .\n\t\t\t\t map (intercalate \" \" . map show) .\n\t\t\t\t transpose .\n\t\t\t\t map (reverse . (kd k d)) $ [0..n-1]\n\nep _ 0 s = s\nep k d s\n\t| s > 1000 = s\n\t| otherwise = ep k (d-1) s*k\n\nkd _ 0 _ = []\nkd k d n = (n`mod`k) : (kd k (d-1) (n`div`k))\n\n\n"}], "src_uid": "4dddcf0ded11672a4958fb0d391dbaf5"} {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n str <- getLine\n let res = foldr (\\x s -> \n if length x `mod` 2 /= 0 then S.insert (head x) s \n else s) S.empty (group str)\n putStrLn $ S.toList res", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ putStrLn\n\nsolve = do\n\ts <- getLine\n\tlet\n\t\tcandidates = map fst $ filter ( odd . snd ) $ map ( head &&& length ) $ group s\n\treturn $ map head $ group $ sort candidates"}, {"source_code": "import Data.List\n\n(|>) = flip (.)\n\nmain :: IO ()\nmain = interact $\n lines\n |> tail\n |> map solve\n |> unlines\n\nsolve :: String -> String\nsolve = group\n |> filter (length |> odd)\n |> map head\n |> nub\n |> sort\n"}, {"source_code": "import Data.List\n\nf = sort . nub . map head . filter (odd . length) . group\n\nmain = interact $ unlines . map f . tail . lines \n"}], "negative_code": [{"source_code": "import Data.List\n\nf = map head . filter (odd . length) . group\n\nmain = interact $ unlines . map f . tail . lines \n"}, {"source_code": "import Data.List\n\nf = nub . reverse . map head . filter (odd . length) . group\n\nmain = interact $ unlines . map f . tail . lines \n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n str <- getLine\n let res = foldr (\\x s -> \n if length x < 2 then S.insert (head x) s \n else S.delete (head x) s) S.empty (group str)\n putStrLn $ S.toList res"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n str <- getLine\n let res = foldr (\\x s -> \n if length x < 2 then S.insert (head x) s \n else s) S.empty (group str)\n putStrLn $ S.toList res"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n str <- getLine\n let res = foldr (\\x s -> \n if length x /= 2 then S.insert (head x) s \n else s) S.empty (group str)\n putStrLn $ S.toList res"}], "src_uid": "586a15030f4830c68f2ea1446e80028c"} {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain =\n do\n x <- read <$> getLine\n replicateM_ x solve\n\nsolve :: IO()\nsolve =\n do\n [n, k] <- map read . words <$> getLine :: IO [Int]\n let x = [0..n-1]\n let y = concat [map (\\a -> (a + z) `mod` n) x | z <- x]\n let z = concat $ replicate n x\n let grid = generateG n $ take k $ zip y z\n let minF = score grid + score (transpose grid)\n print minF\n putStrLn $ unlines grid\n where\n score :: [String] -> Int\n score g = (maximum cnt - minimum cnt) ^ 2\n where\n cnt = map (length . filter (=='1')) g\n generateG :: Int -> [(Int, Int)] -> [String]\n generateG n l = [map (f . (,) y) x | y <- x]\n where\n x = [0..n-1]\n m = Set.fromList l\n f :: (Int, Int) -> Char\n f a | Set.member a m = '1'\n | otherwise = '0'\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n [n, k] <- map read . words <$> getLine\n let a = solve n k\n print $ f a\n putStr $ unlines $ map (>>= show) a\n\nf a = (maximum r - minimum r) ^ 2 + (maximum c - minimum c) ^ 2\n where\n r = map sum a\n c = map sum $ transpose a\n\nsolve n k = skew n $ makeRows n $ replicate k 1 ++ replicate (n * n - k) 0\n\nmakeRows n [] = []\nmakeRows n as = take n as : makeRows n (drop n as)\n\nskew n = map (take n) . zipWith drop [0 ..] . map cycle . transpose\n"}], "negative_code": [], "src_uid": "0f18382d450be90edf1fd1a3770b232b"} {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsolve xs = map (compatibles !) xs\n\twhere\n\t\tn = 22\n\t\tm = 2^n - 1\n\t\t-- runSTUArray prevents copying\n\t\tcompatibles = runSTUArray $ do\n\t\t\t-- attempt to STArray Int (Maybe Int) leads to huge memory usage\n\t\t\ta <- newArray (0, m) (-1) :: ST s (STUArray s Int Int)\n\t\t\tforM_ xs $ \\x -> writeArray a (complement x .&. m) $ x\n\t\t\tforM_ (reverse [0..m]) $ \\x -> do\n\t\t\t\tv <- readArray a x\n\t\t\t\tif v == -1\n\t\t\t\t\tthen do\n\t\t\t\t\t\tnexts <- mapM (readArray a) $ map (setBit x) $\n\t\t\t\t\t\t\tfilter (not . testBit x) [0..n-1]\n\t\t\t\t\t\tlet vs = filter (/= -1) nexts\n\t\t\t\t\t\tif not $ null vs\n\t\t\t\t\t\t\tthen writeArray a x $ head vs\n\t\t\t\t\t\t\telse return ()\n\t\t\t\t\telse return ()\n\t\t\treturn a\n\nmain = do\n\t_ <- getLine\n\txs <- (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\tputStrLn $ unwords $ map show $ solve xs\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\n-- TODO\n-- http://codeforces.ru/contest/165/submission/2510862\n-- watashi has shorter solution but my attempt to simplify like he does leads to TLE !?\n\nsolve xs = map (compatibles !) xs\n\twhere\n\t\tn = 22\n\t\tm = 2^n - 1\n\t\t-- runSTUArray prevents copying\n\t\t-- attempt to STArray Int (Maybe Int) leads to huge memory usage\n\t\tcompatibles = runSTUArray $ do\n\t\t\ta <- newArray (0, m) $ (-1 :: Int)\n\t\t\tforM_ xs $ \\x -> writeArray a (complement x .&. m) $ x\n\t\t\tforM_ (reverse [0..m]) $ \\x -> do\n\t\t\t\tv <- readArray a x\n\t\t\t\tif v == -1\n\t\t\t\t\tthen do\n\t\t\t\t\t\tnexts <- mapM (readArray a) $ map (setBit x) $\n\t\t\t\t\t\t\tfilter (not . testBit x) [0..n-1]\n\t\t\t\t\t\tlet vs = filter (/= -1) nexts\n\t\t\t\t\t\tif not $ null vs\n\t\t\t\t\t\t\tthen writeArray a x $ head vs\n\t\t\t\t\t\t\telse return ()\n\t\t\t\t\telse return ()\n\t\t\treturn a\n\nmain = do\n\t_ <- getLine\n\txs <- (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\tputStrLn $ unwords $ map show $ solve xs\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsolve :: [Int] -> [Int]\nsolve xs = map (compatibles !) xs\n\twhere\n\t\tn = 22\n\t\tm = 2^n - 1\n\t\tcompatibles = runSTUArray $ do\n\t\t\ta <- newArray (0, m) (-1) :: ST s (STUArray s Int Int)\n\t\t\tforM_ xs $ \\x -> do\n\t\t\t\twriteArray a (complement x .&. m) $ x\n\t\t\tforM_ (reverse [0..m]) $ \\x -> do\n\t\t\t\tv <- readArray a x\n\t\t\t\tif v == -1\n\t\t\t\t\tthen do\n\t\t\t\t\t\tnexts <- mapM (readArray a) $ map (setBit x) $\n\t\t\t\t\t\t\tfilter (not . testBit x) [0..n-1]\n\t\t\t\t\t\tlet vs = filter (/= -1) nexts\n\t\t\t\t\t\tif not $ null vs\n\t\t\t\t\t\t\tthen writeArray a x $ head vs\n\t\t\t\t\t\t\telse return ()\n\t\t\t\t\telse return ()\n\t\t\treturn a\n\nmain = do\n\t_ <- getLine\n\txs <- (map (fst . fromJust . B.readInt) . B.words) `fmap` B.getLine\n\t-- xs <- (map read . words) `fmap` getLine\n\tputStrLn $ unwords $ map show $ solve xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -fignore-asserts #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngao a = map ((c!) . xor m) a\n where\n n = 22\n m = 2 ^ n - 1\n c = runSTUArray gao' where\n gao' = do\n x <- newArray (0, m) $ -1 :: ST s (STUArray s Int Int)\n forM_ a $ \\i -> do\n writeArray x i i\n forM_ [0 .. m] $ \\i -> do\n e <- liftM (head . (++[-1]) . filter (>0)) $ mapM (readArray x) $ i:\n [xor i j | j <- map (shiftL 1) [0 .. n - 1], i .&. j /= 0]\n writeArray x i e\n return x\n\nmain = do\n C.getLine\n a <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n putStrLn $ unwords $ map show $ gao a\n"}], "negative_code": [], "src_uid": "50f58b33d6ed6c591da2838fdd103bde"} {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntuple2 [] = []\ntuple2 (x:y:l) = (x, y) : tuple2 l\n\ntest :: C.ByteString -> Int\ntest s = min (l - l1) (l - l2)\n where\n l = C.length s\n l1 = C.length $ C.dropWhile (== '<') s\n l2 = C.length $ C.dropWhile (== '>') $ C.reverse s\n\ntest' :: (C.ByteString, C.ByteString) -> Int\ntest' (n, s) = test $ C.take (ri n) s\n\nsolve (snt:a) = mconcat $ map (enc . test') $ tuple2 $ take (2 * nt) a\n where\n nt = ri snt\n enc n = intDec n <> char7 '\\n'\n \nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.ST.Lazy.Safe (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy.Safe as STL\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n t <- readInt <$> getLine\n replicateM_ t $ do\n n <- getLine\n s <- BS.takeWhile (>='!') <$> BS.getLine\n let l = BS.length $ BS.takeWhile (=='<') s\n r = BS.length $ snd $ BS.spanEnd (=='>') s\n print $ min l r\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n{-# INLINE wrA #-}\nwrA = A.writeArray\n{-# INLINE rdA #-}\nrdA = A.readArray\n{-# INLINE mdA #-}\nmdA arr f i = do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' arr f i = do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\n{-# INLINE swapA #-}\nswapA arr i j = do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "negative_code": [{"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntuple2 [] = []\ntuple2 (x:y:l) = (x, y) : tuple2 l\n\ntest :: C.ByteString -> Int\ntest s\n | C.length s == 1 = 0\n | C.head s == '>' = 0\n | C.last s == '<' = 0\n | otherwise = 1\n\ntest' :: (C.ByteString, C.ByteString) -> Int\ntest' (n, s) = test $ C.take (ri n) s\n\nsolve (snt:a) = mconcat $ map (enc . test') $ tuple2 $ take (2 * nt) a\n where\n nt = ri snt\n enc n = intDec n <> char7 '\\n'\n \nmain :: IO ()\nmain = hPutBuilder stdout . solve . C.words =<< C.getContents\n"}], "src_uid": "0ba97bcfb5f539c848f2cd097b34ff33"} {"source_code": "import Control.Applicative\nimport Text.Printf\n\nf i m n = i * ( (i/m)^n - ( (i-1)/m)^n)\n\nmain = do\n l <- map read . words <$> getLine :: IO [Integer]\n m <- return $ head l\n n <- return $ last l\n printf \"%.12f\\n\" $ sum $ [ f (fromIntegral i :: Double) (fromIntegral m :: Double) n | i <- [1..m]]", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\nfastPower :: Num a => a -> Int -> a\nfastPower x 0 = 1\nfastPower x 1 = x\nfastPower x n\n | n `mod` 2 == 1 = half * half * x\n | otherwise = half * half\n where\n half = fastPower x (n `div` 2)\n\ngao :: Int -> Int -> Double\ngao m n = foldl' (+) 0.0 $ map (\\x -> ((probabilities!x) - (probabilities!(x-1))) * (fromIntegral x)) [1 .. m]\n where\n probabilities = listArray (0, m) (map (\\x -> fastPower ((fromIntegral x) / (fromIntegral m)) n) [0 .. m])\n\nmain = do\n (m:n:_) <- getInts\n putStrLn $ show $ gao m n\n where\n getInts :: IO [Int]\n getInts = (map read . words) <$> getLine\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [m, n] <- fmap (map read . words) getLine :: IO [Int]\n\n let\n m' = fromIntegral m\n v = sum $ [i * ((i/m')^n - ((i-1)/m')^n) | i <- map fromIntegral [1..m]] :: Double\n\n print v\n"}, {"source_code": "import Control.Arrow((>>>))\nimport Text.Printf\n\nitof :: Int -> Double\nitof = fromIntegral\n\np m n i = f i - f (i-1) where\n f i = (itof i / itof m) ^ n\n\ne :: Int -> Int -> Double\ne m n = sum [p m n i * itof i | i <- [1..m]]\n\nmain :: IO ()\nmain = do\n [m,n] <- getLine >>= (words >>> map read >>> return)\n printf \"%.5f\\n\" $ e m n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as M\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Word\nimport Debug.Trace\nimport Text.Printf\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Num b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n [m, n] <- getInts\n\n let es :: Int -> Double -> Double -> Double\n es 1 p !acc = acc + p\n es i p !acc =\n let cur = p * (1 - ((cast i - 1) / cast i) ** cast n)\n in es (i-1) (p - cur) $ acc + cast i * cur\n\n print (es m 1 0 :: Double)\n"}, {"source_code": "\nchanceALOnce m n = 1 - (1 - 1 / fromIntegral n) ^ m\nsolve m 1 = 1\nsolve m n =\n chanceALOnce m n * fromIntegral n + (1 - chanceALOnce m n) * solve m (n-1) :: Double\ns[m,n]=solve n m\nmain=interact$show.s.map read.words\n"}], "negative_code": [], "src_uid": "f70ac2c4e0f62f9d6ad1e003aedd86b2"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndata Edge = Edge !Int !Int\n\ndijkstra g source = runST $ do\n ds :: STUArray s Int Int64 <- newArray (1, n) maxBound\n writeArray ds source 0\n ps :: STUArray s Int Int <- newArray (1, n) 0\n\n let\n step :: Set (Int64, Int) -> ST s ()\n step q =\n case Set.minView q of\n Nothing -> return ()\n Just ((d, v), q) -> do\n let\n relax q (Edge u w) = do\n d <- readArray ds u\n\n if d' < d\n then do\n writeArray ds u d'\n writeArray ps u v\n return $ Set.insert (d', u) q\n else return q\n where\n d' = d + (fromIntegral w)\n\n foldM relax q (g!v) >>= step\n\n step $ Set.singleton (0, source)\n\n ds' :: UArray Int Int64 <- freeze ds\n ps' :: UArray Int Int <- freeze ps\n return (ds', ps')\n where\n n = snd $ bounds g\n\nmain = do\n [n, m] <- getInts\n -- es <- replicateM m getInts\n\n g ::Array Int [Edge] <- do\n a :: IOArray Int [Edge] <- newArray (1, n) []\n replicateM m $ do\n [u, v, w] <- getInts\n\n readArray a u >>= \\es -> writeArray a u $ (Edge v w):es\n readArray a v >>= \\es -> writeArray a v $ (Edge u w):es\n freeze a\n\n let\n (ds, ps) = dijkstra g 1\n\n path 0 = []\n path u = u:(path $ ps!u)\n\n if ds!n == maxBound\n then print $ -1\n else putStrLn $ unwords $ map show $ reverse $ path n\n\n", "positive_code": [{"source_code": "import qualified Data.List as List\nimport qualified Data.Sequence as Sequence\n\ntype Edge = (Int, Int)\ntype Graph = Sequence.Seq [Edge]\ntype Paths = Sequence.Seq Int\ntype DijkstraHeap = MinHeap (Int, Int, Int)\n\ndata MinHeap a = HeapEmpty | HeapNode Int a (MinHeap a) (MinHeap a)\n\nrank :: MinHeap a -> Int\nrank HeapEmpty = 0\nrank (HeapNode x _ _ _) = x\n\nsingleton :: a -> MinHeap a\nsingleton x = HeapNode 1 x HeapEmpty HeapEmpty\n\nmerge :: (Ord a) => MinHeap a -> MinHeap a -> MinHeap a\nmerge HeapEmpty heap = heap\nmerge heap HeapEmpty = heap\nmerge lheap rheap = let\n HeapNode _ lval lc rc = lheap\n HeapNode _ rval _ _ = rheap\n in if rval < lval\n then merge rheap lheap\n else let rc' = merge rc rheap\n in if rank lc < rank rc'\n then HeapNode (rank lc + 1) lval rc' lc\n else HeapNode (rank rc' + 1) lval lc rc'\n\ninsert :: (Ord a) => a -> MinHeap a -> MinHeap a\ninsert = merge . singleton\n\npop :: (Ord a) => MinHeap a -> Maybe (a, MinHeap a)\npop HeapEmpty = Nothing\npop (HeapNode _ val lc rc) = Just (val, merge lc rc)\n\nmain :: IO()\nmain = do\n input <- lines <$> getContents\n let\n readInts = map (read :: String -> Int) . words\n [n, m] = readInts $ head input\n graph = buildGraph n . map readInts $ tail input\n resultString = concat . List.intersperse \" \" . map show $ dijkstra n graph\n putStrLn resultString\n\nbuildGraph :: Int -> [[Int]] -> Graph\nbuildGraph n edges = let\n initGraph = Sequence.replicate (n + 1) []\n addEdge :: [Int] -> Graph -> Graph\n addEdge [u, v, w] = Sequence.adjust ((w, v) :) u . Sequence.adjust ((w, u) :) v\n in foldr addEdge initGraph edges\n\ndijkstra :: Int -> Graph -> [Int]\ndijkstra n graph = let\n initHeap = singleton (0, 0, 1)\n initPaths = Sequence.replicate (n + 1) (-1)\n recurse :: DijkstraHeap -> Paths -> Paths\n recurse heap paths =\n case pop heap of\n Nothing -> paths\n Just ((dist, p, u), heap') ->\n if Sequence.index paths u == -1\n then let\n paths' = Sequence.update u p paths\n heap'' = foldr updateHeap heap' $ Sequence.index graph u\n updateHeap :: Edge -> DijkstraHeap -> DijkstraHeap\n updateHeap (w, v) = insert (dist + w, u, v)\n in recurse heap'' paths'\n else recurse heap' paths\n paths = recurse initHeap initPaths\n getPath :: Int -> [Int]\n getPath 0 = []\n getPath u = u : (getPath $ Sequence.index paths u)\n resultPath =\n case Sequence.index paths n of\n -1 -> [-1]\n _ -> getPath n\n in reverse resultPath"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Data.Int\n\nreadInt s = let Just (a, _) = BS.readInt s in a\n\nmain = BS.interact $ BS.unwords . map (BS.pack . show) . solve . map readInt . BS.words\n\ninfinity = 10 ^ 16\n\nsolve (n:m:rest) = dijkstra n graph 1 n\n where g = take (3*m) rest\n graph = buildG n g\n\nbuildG n g = runSTArray $ do\n graph <- newArray (1, n) []\n let rList [] = []\n rList (fr:to:w:rest) = (fr, to, w) : rList rest\n forM_ (rList g) $ \\(fr, to, w) -> do\n cfr <- readArray graph fr\n writeArray graph fr ((to, w): cfr)\n cto <- readArray graph to\n writeArray graph to ((fr, w): cto)\n return graph\n\ndijkstra n graph start finish = makePath finish []\n where startDists = foldl addv M.empty [1 .. n]\n addv m v | v == start = M.insert start (0 :: Int64, start) m\n addv m v = M.insert v (infinity, -1) m\n relax (v, dv, dists, queue) (to, w)\n | new < cur = (v, dv, distsUpd, queueUpd)\n | otherwise = (v, dv, dists, queue)\n where (cur, _) = dists M.! to\n new = dv + (fromIntegral w)\n queueUpd = S.insert (new, to) $ S.delete (cur, to) queue\n distsUpd = M.adjust (\\_ -> (new, v)) to dists\n relaxAll dists queue | queue == S.empty = dists\n relaxAll dists queue = relaxAll distsUpd queueUpd\n where ((dv, v), queueNoV) = S.deleteFindMin queue\n (_, _, distsUpd, queueUpd) = foldl relax (v, dv, dists, queueNoV) (graph ! v)\n finalDists = relaxAll startDists (S.singleton (0, start))\n makePath v path\n | from < 0 = [-1]\n | v == start = v : path\n | otherwise = makePath from (v : path)\n where (_, from) = finalDists M.! v\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\ndijkstra g source = runST $ do\n ds :: STUArray s Int Int64 <- newArray (1, n) maxBound\n writeArray ds source 0\n ps :: STUArray s Int Int <- newArray (1, n) 0\n\n let\n step :: Set (Int64, Int) -> ST s ()\n step q =\n case Set.minView q of\n Nothing -> return ()\n Just ((d, v), q) -> do\n let\n relax q (u, w) = do\n d <- readArray ds u\n\n if d' < d\n then do\n writeArray ds u d'\n writeArray ps u v\n return $ Set.insert (d', u) q\n else return q\n where\n d' = d + (fromIntegral w)\n\n foldM relax q (g!v) >>= step\n\n step $ Set.singleton (0, source)\n\n ds' :: UArray Int Int64 <- freeze ds\n ps' :: UArray Int Int <- freeze ps\n return (ds', ps')\n where\n n = snd $ bounds g\n\nmain = do\n [n, m] <- getInts\n es <- replicateM m getInts\n\n let\n g :: Array Int [(Int, Int)]\n g = accumArray (flip (:)) [] (1, n) $ concat $ map (\\[u, v, w] -> [(u, (v, w)), (v, (u, w))]) es\n\n (ds, ps) = dijkstra g 1\n\n path 0 = []\n path u = u:(path $ ps!u)\n\n if ds!n == maxBound\n then print $ -1\n else putStrLn $ unwords $ map show $ reverse $ path n\n\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array\n\nreadInt s = let Just (a, _) = BS.readInt s in a\n\nmain = BS.interact $ BS.unwords . map (BS.pack . show) . solve . map readInt . BS.words\n\ninfinity = 10 ^ 16\n\nsolve (n:m:rest) = dijkstra n graph 1 n\n where g = take (3*m) rest\n graph = buildG n g\n\nbuildG n g = runSTArray $ do\n graph <- newArray (1, n) []\n let rList [] = []\n rList (fr:to:w:rest) = (fr, to, w) : rList rest\n forM_ (rList g) $ \\(fr, to, w) -> do\n cfr <- readArray graph fr\n writeArray graph fr ((to, w): cfr)\n cto <- readArray graph to\n writeArray graph to ((fr, w): cto)\n return graph\n\ndijkstra n graph start finish = makePath finish []\n where startDists = foldl addv M.empty [1 .. n]\n addv m v | v == start = M.insert start (0, start) m\n addv m v = M.insert v (infinity, -1) m\n relax (v, dv, dists, queue) (to, w)\n | new < cur = (v, dv, distsUpd, queueUpd)\n | otherwise = (v, dv, dists, queue)\n where (cur, _) = dists M.! to\n new = dv + w\n queueUpd = S.insert (new, to) $ S.delete (cur, to) queue\n distsUpd = M.adjust (\\_ -> (new, v)) to dists\n relaxAll dists queue | queue == S.empty = dists\n relaxAll dists queue = relaxAll distsUpd queueUpd\n where ((dv, v), queueNoV) = S.deleteFindMin queue\n (_, _, distsUpd, queueUpd) = foldl relax (v, dv, dists, queueNoV) (graph ! v)\n finalDists = relaxAll startDists (S.singleton (0, start))\n makePath v path\n | from < 0 = [-1]\n | v == start = v : path\n | otherwise = makePath from (v : path)\n where (_, from) = finalDists M.! v\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array\n\nreadInt s = let Just (a, _) = BS.readInt s in a\n\nmain = BS.interact $ BS.unwords . map (BS.pack . show) . solve . map readInt . BS.words\n\ninfinity = 10 ^ 16\n\nsolve (n:m:rest) = dijkstra n graph 1 n\n where g = take (3*m) rest\n graph = buildG n g\n\nbuildG n g = runSTArray $ do\n graph <- newArray (1, n) []\n let rList [] = []\n rList (fr:to:w:rest) = (fr, to, w) : rList rest\n forM_ (rList g) $ \\(fr, to, w) -> do\n cfr <- readArray graph fr\n writeArray graph fr ((to, w): cfr)\n cto <- readArray graph to\n writeArray graph to ((fr, w): cto)\n return graph\n\ndijkstra n graph start finish = makePath finish []\n where startDists = foldl addv (M.singleton start (0, start)) [1 .. n]\n addv m v | v == start = m\n addv m v = M.insert v (infinity, -1) m\n relax (v, dv, dists, queue) (to, w)\n | new < cur = (v, dv, distsUpd, queueUpd)\n | otherwise = (v, dv, dists, queue)\n where (cur, _) = dists M.! to\n new = dv + w\n queueUpd = S.insert (new, to) $ S.delete (cur, to) queue\n distsUpd = M.adjust (\\_ -> (new, v)) to dists\n relaxAll dists queue | queue == S.empty = dists\n relaxAll dists queue = relaxAll distsUpd queueUpd\n where ((dv, v), queueNoV) = S.deleteFindMin queue\n (_, _, distsUpd, queueUpd) = foldl relax (v, dv, dists, queueNoV) (graph ! v)\n finalDists = relaxAll startDists (S.singleton (0, start))\n makePath v path\n | from < 0 = [-1]\n | from == v = v : path\n | otherwise = makePath from (v : path)\n where (_, from) = finalDists M.! v\n"}], "src_uid": "bda2ca1fd65084bb9d8659c0a591743d"} {"source_code": "type Result = (Int, Maybe String)\n\nsolve :: [String] -> String\nsolve lines = getResult (solve_ ((0, Nothing), (0, Nothing)) lines)\n where \n solve_ :: (Result, Result) -> [String] -> (Result, Result)\n solve_ results [] = results\n solve_ ((_, Nothing), (_, Nothing)) (a:as) = solve_ ((1, Just a), (0, Nothing)) as\n solve_ ((res1, Just name1), (_, Nothing)) (a:as)\n | name1 == a = solve_ ((res1 + 1, Just name1), (0, Nothing)) as\n | otherwise = solve_ ((res1, Just name1), (1, Just a)) as\n solve_ ((res1, Just name1), (res2, Just name2)) (a:as)\n | (name1 == a) = solve_ ((res1 + 1, Just name1), (res2, Just name2)) as\n | (name2 == a) = solve_ ((res1, Just name1), (res2 + 1, Just name2)) as\n | otherwise = error \"Komand bol'we 2-x!\"\n solve_ _ _ = error \"Owibka v logike\"\n\ngetResult :: (Result, Result) -> String\ngetResult ((a1, Just name1), (_, Nothing)) = name1\ngetResult ((a1, Just name1), (a2, Just name2))\n | a1 > a2 = name1\n | otherwise = name2\n\nmain = do\n n <- readLn::(IO Int)\n lines <- sequence (map (\\x -> getLine) [1..n])\n putStrLn (solve lines)", "positive_code": [{"source_code": "import Data.List (sort, group)\n\nmain = do interact $ (++ \"\\n\") . head . select . (++ [[]]) . group . sort . tail . lines\n\twhere select l = if length (l!!0) > length (l!!1) then l!!0 else l!!1\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\nimport List\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nrepeatM a = mapM (const a) (repeat 1)\nrepeatMn a n = mapM (const a) [1..n]\nreadm::(Read a) => State String a\nreadm = State (head . reads)\nreadchar = State (\\s->(head s,tail s))\nreadall = State (,\"\")\n\nrunRead x s = fst $ runState x s\n\n\nmain = reader >>= writer . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\tn<-readm\n\tall <- readall\n\tlet l = take n . tail . lines $ all\n\tlet teams = nub l \n\treturn (if length teams == 1 then head teams else let [t1,t2]=teams in if (length . filter (==t1) $ l) > (length . filter (==t2) $ l) then t1 else t2)\n"}, {"source_code": "import Data.List\nsolve c = if length (filter (==head names) c)> length (filter (== last names) c) then\n\t head names else last names\n\t where names = nub c\n\nmain = do \n\tn<-getLine\n\trest<-getContents\n\tputStrLn $ solve $ words rest\n"}, {"source_code": "module Main(main) where\n \nmain = interact in2out\n \nin2out input\n = output\n where\n (num, output) = solve (tail (words input))\n solve []\n = (-1, \"\")\n solve (x:xs)\n | num1 > num2\n = (num1, x)\n | otherwise\n = (num2, y)\n where\n num1 = length (filter (==x) xs)\n (num2, y) = solve xs"}, {"source_code": "main = do nInput <- getLine\n str <- getContents\n putStrLn $ solver $ lines str\n\nsolver ss = if length t1 > length t2 then head t1 else head t2\n where\n ts = match ss ([], [])\n t1 = fst ts\n t2 = snd ts\n\nmatch [] (x, y) = (x, y)\nmatch (s:ss) ([], x) = match ss ([s], x)\nmatch (s:ss) (x, y) = if s == head x then match ss (s:x, y) else match ss (x, s:y)"}, {"source_code": "{-\nerr::(a->Bool)->a->a\nerr f a\n |f a = a\n | otherwise=undefined\n\npredS::[String]->[String]\npredS=err ((<10) . length). err (/=\"\")\n\ndiff::Eq a=>[a]->Bool\ndiff []=False\ndiff (x:xs)=\n-}\nnInp::Int->IO [String]\nnInp 0=return []\nnInp n=do\n m <- getLine\n (m:) <$> nInp (n-1)\n\nmf::[String]->String\nmf l@(x:_)=head $ mymax length (filter (==x) l) (filter (== notThis x l) l)\n\nnotThis::(Eq a)=>a->[a]->a\nnotThis a []=a\nnotThis a (x:xs)\n |a==x = notThis a xs\n |otherwise = x\n\nmymax::(a->Int)->a->a->a\nmymax f a b\n |(f a)>= (f b) = a\n |otherwise = b\n\n\n\nmain::IO()\nmain=do\n n <- getLine\n inps <- nInp (read n)\n putStrLn $ mf inps\n"}, {"source_code": "import Data.Map\nimport Data.List\nmain = interact (s.words)\ns (n:xs) = sl empty xs where\n sl m [] = fst(maximumBy(\\(_,v1)(_,v2)->compare v1 v2)(toList m))\n sl m (x:xs) = sl (insertWith (+) x 1 m) xs\n"}, {"source_code": "main = readLn >>= readdata >>= putStr . solve\nreaddata 1 = getLine >>= \\a -> return [a]\nreaddata n = do\n a <- getLine\n q <- readdata (n - 1)\n return (a : q)\nsolve sp = let a = length [x | x <- sp, x == head sp];\n b = length [x | x <- sp, x /= head sp];\n in if a > b then head sp else head [x | x <- sp, x /= head sp]"}, {"source_code": "import Data.List (group, maximumBy, sort)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . tail . lines\n\nsolve :: [String] -> String\nsolve = head . maximumBy (comparing length) . group . sort\n"}, {"source_code": "import Data.List (foldl', maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getContents >>= putStrLn . solve . tail . lines\n\nsolve :: [String] -> String\nsolve = fst . maximumBy (comparing snd) . M.toList . foldl' (\\m x -> M.insertWith (+) x (1 :: Integer) m) M.empty\n"}, {"source_code": "import qualified Data.Map as M\nmain = putStrLn . fst . M.foldWithKey (\\t s (t0,s0) -> if s > s0 then (t,s) else (t0,s0)) (undefined,0) . M.fromListWith (+) . map (flip (,) 1) . tail . lines =<< getContents"}, {"source_code": "import Data.List\nimport Data.Function\nsolve = head . maximumBy (compare `on` length) . group . sort\nmain = interact $ solve . tail . lines"}, {"source_code": "import Data.List\n\nmain = do\n s <- getLine\n ds <- getContents\n let teams = map f . group . sort . lines $ ds\n putStrLn . snd . maximum $ teams\n where f x = (length x, head x)\n"}, {"source_code": "module Main (main) where\n\nimport System\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\nreadData :: [String] -> [String]\nreadData (x:xs) = take n xs\n where n = read x\n\nsolve :: [String] -> String\nsolve list = sortedArray !! middleIndex\n where sortedArray = sort list\n middleIndex = (length list) `div` 2\n\nmain = interact$solve.readData.words"}, {"source_code": "import List\nmain = interact solve\nsolve input = output where\n output = snd $ maximum $ zip ( map length $ group a ) ( nub a )\n a = sort $ tail $ lines input"}, {"source_code": "import Control.Applicative\nimport Data.List\n \t\n\t\t\t\n\n \n\n\nmain= do\n\tgetLine\n\tn<- lines <$> getContents ::IO [String]\n\tlet s= group $ sort n \n\tlet s1 = s++s\n\tlet (a:b:c)= map length s1 \n\tputStrLn $ if a > b then head (head s) else head (last s)"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.List\n\n-- Meat\nsolve :: [String] -> [String]\nsolve xs = [pickLongest . group . sort $ xs]\n\npickLongest :: [[String]] -> String\npickLongest [xs] = head xs\npickLongest [xs, ys] = if length xs > length ys then head xs else head ys\npickLongest _ = error \"You suck\"\n\n-- Shit\nmain :: IO ()\nmain = do\n _:xs <- readShit\n printShit $ solve xs\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: Bool -> x -> x -> x\niif True a _ = a\niif _ _ b = b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}], "negative_code": [], "src_uid": "e3dcb1cf2186bf7e67fd8da20c1242a9"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do \n t <- read <$> getLine\n replicateM_ t $ do\n s <- getLine\n print $ length $ foldl func [] s\n\n\nfunc :: String -> Char -> String\nfunc [] y = [y]\nfunc s 'A' = 'A':s\nfunc (_:xs) 'B' = xs\nfunc _ _ = []\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\n\nsolve :: [Char] -> Int\nsolve = let\n go :: Int -> [Char] -> Int\n go k [] = k\n go 0 (_:qs) = go 1 qs\n go !k ('B':qs) = go (k-1) qs\n go !k (_:qs) = go (k+1) qs\n in go 0\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n str <- getLine\n print $ solve str\n"}], "negative_code": [], "src_uid": "ee295fd90ee9283709447481f172c73c"} {"source_code": "module Main where\n inv :: Integer -> Integer\n inv 1 = 2\n inv 2 = 1\n\n partialSolver :: Integer -> Integer -> Integer\n partialSolver x prev\n | x `mod` 2 == 1 = prev\n | otherwise = inv prev\n\n solver :: [Integer] -> Integer -> [Integer] -> [Integer]\n solver [] _ accumulator = accumulator\n solver (x:xs) prev (y:ys) =\n let ans = partialSolver x y\n in solver xs ans (ans:y:ys)\n\n solverWrapper :: [Integer] -> [Integer]\n solverWrapper xs = tail $ reverse $ solver xs 2 [2]\n\n readInt :: String -> Integer\n readInt x = read x :: Integer\n\n main :: IO()\n main = do\n n <- getLine\n queries <- getLine\n let xs = map readInt $ words queries\n answers = solverWrapper xs\n mapM_ (putStrLn . show) answers\n", "positive_code": [{"source_code": "getInt = read `fmap` getLine :: IO Int\n\nmain = do\n n <- getInt\n xs <- (map read . take n . words) `fmap` getContents :: IO [Int]\n solve xs 0\n\nsolve [] acc = return ()\nsolve (x:xs) acc\n | even x = do\n print $ if even acc then 1 else 2\n solve xs (acc+1)\n | otherwise = do\n print $ if even acc then 2 else 1\n solve xs acc"}, {"source_code": "main :: IO ()\nmain = do\n nText <- getLine\n aText <- getLine\n let a = map read $ words aText :: [Int]\n mapM_ print (map winner (quicksum (map (\\x -> x-1) a)))\n\nwinner :: Int -> Int\nwinner x = 2 - (x `mod` 2)\n\nquicksum :: [Int] -> [Int]\nquicksum x = qs 0 x\n\nqs :: Int -> [Int] -> [Int]\nqs _ [] = []\nqs s (x:xs) = (x+s):(qs (x+s) xs)\n\n"}, {"source_code": "main = getContents >>= ( putStrLn . concat . map (\\x -> if mod x 2 /= 0 then \"1\\n\" else \"2\\n\") . tail . reverse . foldl (\\x -> \\y -> ((y + head x) : x)) [0] . map (\\x -> x - 1) . map (\\x -> read x :: Integer) . tail . words)\n--"}, {"source_code": "main = getContents >>= putStr . unlines . map show . solve 2 . map read . tail . words\n\nsolve :: Int -> [Int] -> [Int]\nsolve x [a] = if a `mod` 2 == 0\n then [3 - x]\n else [x]\nsolve x (a:as) = if a `mod` 2 == 0\n then (3 - x) : solve (3 - x) as\n else x : solve x as"}, {"source_code": "main = putStr . unlines . map (show . (+1) . fromEnum) . tail . scanl (\\r n -> r /= even n) True . map read . tail . words =<< getContents"}], "negative_code": [{"source_code": "main = getContents >>= ( putStrLn . concat . map (\\x -> if x == True then \"1\\n\" else \"2\\n\") . tail . reverse . foldr (\\y -> \\x -> ((y /= head x) : x)) [False] . map (\\x -> mod (x - 1) 2 /= 0) . map read . tail . words)\n"}, {"source_code": "main = getContents >>= ( putStrLn . concat . map (\\x -> if x == True then \"1\\n\" else \"2\\n\") . tail . reverse . foldr (\\y -> \\x -> ((y /= head x) : x)) [False] . map (\\x -> mod x 2 == 0) . map read . tail . words)\n"}, {"source_code": "main = getContents >>= ( putStrLn . concat . map (\\x -> if mod x 2 /= 0 then \"1\\n\" else \"2\\n\") . tail . reverse . foldr (\\y -> \\x -> ((y + head x) : x)) [0] . map (\\x -> x - 1) . map (\\x -> read x :: Integer) . tail . words)\n"}], "src_uid": "3a767b3040f44e3e2148cdafcb14a241"} {"source_code": "import Control.Monad\nimport Data.List\n\ncalc' :: [Int] -> [Int] -> [Int] -> [Int]\ncalc' [] hd tl = hd ++ (reverse tl)\ncalc' (x:xs) [] tl = calc' xs [x] tl\ncalc' (x:xs) hd@(h:hs) tl | x < h = calc' xs (x:hd) tl\ncalc' (x:xs) hd tl | otherwise = calc' xs hd (x:tl)\n\ncalc :: [Int] -> [Int]\ncalc lst = calc' lst [] []\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let lst = map read $ words line :: [Int]\n putStrLn $ intercalate \" \" $ map show $ calc lst\n", "positive_code": [{"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t getTC\n\n (putStr . unlines . map (concatMap ((++ \" \") . show) . solve)) tcs\n\ngetTC = do\n n <- readLn\n map read <$> wordsN n <$> getLine :: IO [Int]\n\nwordsN n s = ww where w = words s; ww | (length w == n) = w\n | otherwise = error \"arr len\"\n\nsolve = f ([],[])\n where\n f (xs , ys ) [] = xs ++ reverse ys\n f ([] , [] ) (z:zs) = f ([z] , [] ) zs\n f (x:xs, ys ) (z:zs) | (z < x) = f (z:x:xs, ys ) zs\n | (z > x) = f (x:xs , z:ys) zs\n | otherwise = error \"not a permutation\"\n f ([] , (_:_)) (_:_) = error \"xs must be first\"\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\nimport qualified Data.IntSet as Set\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n p <- getInts n\n let\n initVals = Set.fromDistinctAscList [1..n]\n solve :: Set.IntSet -> [Int] -> [Int] -> [Int]\n solve _nil [] cont = cont\n solve vals (x:xs) cont = if x == Set.findMin vals\n then x : solve (Set.delete x vals) xs cont\n else solve (Set.delete x vals) xs (x : cont)\n pure $ putInts $ solve initVals (reverse p) []\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "5afa0e4f34ab8c8c67bc8ecb7d6d2d7a"} {"source_code": "main = do\n str1 <- getLine\n str2 <- getLine\n putStr (f (read ((words str1) !! 1)) (map read (words str2)))\n\n\nf x xs\n | x==1 = \"YES\"\n | x<1 = \"NO\"\n | otherwise = f (x - (head xs)) (drop (head xs) xs)", "positive_code": [{"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve [[_, t], as] = go t as\n where go 1 _ = True\n go n _ | n < 1 = False\n go n xs@(x:_) = go (n - x) (drop x xs)\n go _ _ = False\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Data.Array\nmain = do\n [n,t] <- fmap (map read . words) getLine\n as <- fmap (listArray (1,n) . map read . words) getLine\n let go i | i > t = \"NO\"\n | i == t = \"YES\"\n | otherwise = go (i + (as ! i))\n putStrLn $ go 1\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/500/A\n\nsolve :: Int -> [Int] -> Bool\nsolve 1 _ = True\nsolve _ [] = False\nsolve t a@(h:_) = solve (t-h) (drop h a)\n\nmain :: IO ()\nmain = do\n [_, t] <- map read . words <$> getLine :: IO [Int]\n a <- map read . words <$> getLine :: IO [Int]\n putStrLn $ if solve t a then \"YES\" else \"NO\"\n"}, {"source_code": "p b = if b then \"YES\" else \"NO\"\nf (t:ps) = loop 1\n where\n loop x | t == x = True\n | x > t = False\n | otherwise = loop (x + (ps !! (x-1)))\nmain = interact $ p . f . tail . map read . words\n"}, {"source_code": "module Main where\n\nimport Data.Array ((!), array)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\nreadCells n = buildCells n `fmap` readNumbers\n\nbuildCells n = zip [(1 :: Int)..] . take n\n\nbuildPortals n cells =\n array (1, pred n) [ (i, ai + i) | (i, ai) <- cells ]\n\nnavigatePortals n portals destination =\n go 1\n where\n go current\n | current > destination = False\n | current == destination = True\n | current > n = False\n | otherwise = go (portals ! current)\n\nmain :: IO ()\nmain = do\n (n:destination:_) <- readNumbers\n cells <- readCells n\n putStrLn (if navigatePortals n (buildPortals n cells) destination\n then \"YES\"\n else \"NO\")\n"}, {"source_code": "main = do \n constraints <- getLine\n lineSystem <- getLine\n \n let [_, destination] = readInts constraints\n portals = zip (readInts lineSystem ++ [0]) [1..]\n\n putStrLn $ result portals destination\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nresult :: [(Int, Int)] -> Int -> String\nresult [] _ = \"NO\"\nresult (x:xs) dest\n | index == dest = \"YES\"\n | index > dest = \"NO\"\n | otherwise = result (drop jump (x:xs)) dest\n where (jump, index) = x\n"}, {"source_code": "main = do \n constraints <- getLine\n lineSystem <- getLine\n \n let [_, destination] = readInts constraints\n portals = zip (readInts lineSystem ++ [0]) [1..]\n\n putStrLn $ result portals destination\n\n\nreadInts = map read . words\n\nresult [] _ = \"NO\"\nresult (x:xs) dest\n | index == dest = \"YES\"\n | index > dest = \"NO\"\n | otherwise = result (drop jump (x:xs)) dest\n where (jump, index) = x\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\n\nprocess d b = process1 1\n\twhere process1 n | n==b = \"YES\"\n\t \t\t | n>b = \"NO\"\n | otherwise = process1 (n+d!n)\n\nmain= do\n\t[a,b]<- map read. words <$> getLine::IO [Int]\n\tc<- map read. words <$> getLine::IO [Int]\n\tlet d = listArray (1,a) c\n\tputStrLn $ process d b \n\t "}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array\n\nprocess d b n | n==b = \"YES\"\n\t | n>b = \"NO\"\n | otherwise = process d b (n+d!n)\n\nmain= do\n\t[a,b]<- map read. words <$> getLine::IO [Int]\n\tc<- map read. words <$> getLine::IO [Int]\n\tlet d = listArray (1,a) c\n\tputStrLn $ process d b 1\n\t "}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess c b n | n==b = \"YES\"\n\t | n>b = \"NO\"\n | otherwise = process c b (n+c!!(n-1))\n\nmain= do\n\t[a,b]<- map read. words <$> getLine::IO [Int]\n\tc<- map read. words <$> getLine::IO [Int]\n\tputStrLn $ process c b 1\n\t "}, {"source_code": "-- http://codeforces.com/problemset/problem/500/A\n\nisReachingOutPossible end cells = traverse end cells [1]\n where\n traverse end cells (y:[])\n | end == y = \"YES\"\n | end > y = traverse end cells [newRes]\n | end < y = \"NO\"\n where\n newRes = y + (cells !! (y - 1))\n\nmain = do\n constraint <- getLine\n cells <- getLine\n\n let newConstraint = map (read :: String -> Int) $ words constraint\n let destination = newConstraint !! 1\n let lineWorld = map (read :: String -> Int) $ words cells\n\n let result = isReachingOutPossible destination lineWorld\n putStrLn result\n"}, {"source_code": "main = do\n l <- getLine\n p <- getLine\n let (n:t:[]) = map read (words l) :: [Int]\n let paths = map read (words p) :: [Int]\n putStrLn $ if dfs n 0 (t-1) paths\n then \"YES\"\n else \"NO\"\n\ndfs :: Int -> Int -> Int -> [Int] -> Bool\ndfs n pos goal paths\n | pos == goal = True\n | pos > goal = False\n | otherwise = dfs n (pos + (paths !! pos)) goal paths\n \n \n"}, {"source_code": "import Data.Graph\n\nprocess :: Int -> Int -> [Int] -> Bool\nprocess n t xs = path g 1 t\n where g = buildG (1,n) $ zipWith (\\i x -> (i,i+x)) [1..] xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,t] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n putStrLn $ [\"NO\",\"YES\"] !! fromEnum (process n t as)"}, {"source_code": "reach 0 _ = \"YES\"\nreach _ [] = \"NO\"\nreach t (a:ais)\n | t > 0 = reach (t - a) $ drop (a - 1) ais\n | otherwise = \"NO\"\n\nsolve str =\n let (n:t:ais) = (map read . words) str\n in reach (t - 1) ais\n\nmain = interact solve"}, {"source_code": "\nmain = interact $ f . map read . words\n\nf (_:t:s) = v 1 s\n where v c a | c ==t = \"YES\"\n | c > t = \"NO\"\n | otherwise = v (c+x) $ drop x a\n where x = head a\n"}, {"source_code": "import Data.Char\nimport qualified Data.Set as S\n\nimport qualified Data.List as L\n\n\n\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE CPP, NoImplicitPrelude #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fno-warn-name-shadowing #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module : Data.HashTable\n-- Copyright : (c) The University of Glasgow 2003\n-- License : BSD-style (see the file libraries/base/LICENSE)\n--\n-- Maintainer : libraries@haskell.org\n-- Stability : provisional\n-- Portability : portable\n--\n-- An implementation of extensible hash tables, as described in\n-- Per-Ake Larson, /Dynamic Hash Tables/, CACM 31(4), April 1988,\n-- pp. 446--457. The implementation is also derived from the one\n-- in GHC's runtime system (@ghc\\/rts\\/Hash.{c,h}@).\n--\n-----------------------------------------------------------------------------\n{-\nmodule Data.HashTable\n {-# DEPRECATED \"Data.HashTable will be removed in GHC 7.8. Please use an alternative, e.g. the hashtables package, instead.\" #-}\n (\n -- * Basic hash table operations\n HashTable, new, newHint, insert, delete, lookup, update,\n -- * Converting to and from lists\n fromList, toList,\n -- * Hash functions\n -- $hash_functions\n hashInt, hashString,\n prime,\n -- * Diagnostics\n longestChain\n ) where\n-}\n-- This module is imported by Data.Dynamic, which is pretty low down in the\n-- module hierarchy, so don't import \"high-level\" modules\n\n\nimport GHC.Base\n\nimport Prelude hiding ( lookup )\n\nimport Data.Tuple ( fst )\nimport Data.Bits\nimport Data.Maybe\nimport Data.List ( maximumBy, length, concat, foldl', partition )\nimport Data.Int ( Int32 )\n\n\nimport GHC.Num\nimport GHC.Real ( fromIntegral )\nimport GHC.Show ( Show(..) )\nimport GHC.Int ( Int64 )\n\nimport GHC.IO\nimport GHC.IOArray\nimport GHC.IORef\n\nimport Data.Char ( ord )\nimport Data.IORef ( IORef, newIORef, readIORef, writeIORef )\nimport System.IO.Unsafe ( unsafePerformIO )\nimport Data.Int ( Int64 )\n\n--import Hugs.IOArray ( IOArray, newIOArray,\n -- unsafeReadIOArray, unsafeWriteIOArray )\n\n--import NHC.IOExtras ( IOArray, newIOArray, readIOArray, writeIOArray )\n\nimport Control.Monad ( mapM, mapM_, sequence_ )\n\n\n-----------------------------------------------------------------------\n\niNSTRUMENTED :: Bool\niNSTRUMENTED = False\n\n-----------------------------------------------------------------------\n\nreadHTArray :: HTArray a -> Int32 -> IO a\nwriteMutArray :: MutArray a -> Int32 -> a -> IO ()\nnewMutArray :: (Int32, Int32) -> a -> IO (MutArray a)\nnewMutArray = newIOArray\ntype MutArray a = IOArray Int32 a\ntype HTArray a = MutArray a\n-- #if defined(DEBUG) || defined(__NHC__)\n--readHTArray = readIOArray\n--writeMutArray = writeIOArray\n-- #else\nreadHTArray arr i = unsafeReadIOArray arr (fromIntegral i)\nwriteMutArray arr i x = unsafeWriteIOArray arr (fromIntegral i) x\n-- #endif\n \ndata HashTable key val = HashTable {\n cmp :: !(key -> key -> Bool),\n hash_fn :: !(key -> Int32),\n tab :: !(IORef (HT key val))\n }\n-- TODO: the IORef should really be an MVar.\n\ndata HT key val\n = HT {\n kcount :: !Int32, -- Total number of keys.\n bmask :: !Int32,\n buckets :: !(HTArray [(key,val)])\n }\n\n-- ------------------------------------------------------------\n-- Instrumentation for performance tuning\n\n-- This ought to be roundly ignored after optimization when\n-- iNSTRUMENTED=False.\n\n-- STRICT version of modifyIORef!\nmodifyIORef :: IORef a -> (a -> a) -> IO ()\nmodifyIORef r f = do\n v <- readIORef r\n let z = f v in z `seq` writeIORef r z\n\ndata HashData = HD {\n tables :: !Integer,\n insertions :: !Integer,\n lookups :: !Integer,\n totBuckets :: !Integer,\n maxEntries :: !Int32,\n maxChain :: !Int,\n maxBuckets :: !Int32\n} deriving (Eq, Show)\n\n{-# NOINLINE hashData #-}\nhashData :: IORef HashData\nhashData = unsafePerformIO (newIORef (HD { tables=0, insertions=0, lookups=0,\n totBuckets=0, maxEntries=0,\n maxChain=0, maxBuckets=tABLE_MIN } ))\n\ninstrument :: (HashData -> HashData) -> IO ()\ninstrument i | iNSTRUMENTED = modifyIORef hashData i\n | otherwise = return ()\n\nrecordNew :: IO ()\nrecordNew = instrument rec\n where rec hd@HD{ tables=t, totBuckets=b } =\n hd{ tables=t+1, totBuckets=b+fromIntegral tABLE_MIN }\n\nrecordIns :: Int32 -> Int32 -> [a] -> IO ()\nrecordIns i sz bkt = instrument rec\n where rec hd@HD{ insertions=ins, maxEntries=mx, maxChain=mc } =\n hd{ insertions=ins+fromIntegral i, maxEntries=mx `max` sz,\n maxChain=mc `max` length bkt }\n\nrecordResize :: Int32 -> Int32 -> IO ()\nrecordResize older newer = instrument rec\n where rec hd@HD{ totBuckets=b, maxBuckets=mx } =\n hd{ totBuckets=b+fromIntegral (newer-older),\n maxBuckets=mx `max` newer }\n\nrecordLookup :: IO ()\nrecordLookup = instrument lkup\n where lkup hd@HD{ lookups=l } = hd{ lookups=l+1 }\n\n-- stats :: IO String\n-- stats = fmap show $ readIORef hashData\n\n-- ----------------------------------------------------------------------------\n-- Sample hash functions\n\n-- $hash_functions\n--\n-- This implementation of hash tables uses the low-order /n/ bits of the hash\n-- value for a key, where /n/ varies as the hash table grows. A good hash\n-- function therefore will give an even distribution regardless of /n/.\n--\n-- If your keyspace is integrals such that the low-order bits between\n-- keys are highly variable, then you could get away with using 'fromIntegral'\n-- as the hash function.\n--\n-- We provide some sample hash functions for 'Int' and 'String' below.\n\ngolden :: Int32\ngolden = 1013904242 -- = round ((sqrt 5 - 1) * 2^32) :: Int32\n-- was -1640531527 = round ((sqrt 5 - 1) * 2^31) :: Int32\n-- but that has bad mulHi properties (even adding 2^32 to get its inverse)\n-- Whereas the above works well and contains no hash duplications for\n-- [-32767..65536]\n\nhashInt32 :: Int32 -> Int32\nhashInt32 x = mulHi x golden + x\n\n-- | A sample (and useful) hash function for Int and Int32,\n-- implemented by extracting the uppermost 32 bits of the 64-bit\n-- result of multiplying by a 33-bit constant. The constant is from\n-- Knuth, derived from the golden ratio:\n--\n-- > golden = round ((sqrt 5 - 1) * 2^32)\n--\n-- We get good key uniqueness on small inputs\n-- (a problem with previous versions):\n-- (length $ group $ sort $ map hashInt [-32767..65536]) == 65536 + 32768\n--\nhashInt :: Int -> Int32\nhashInt x = hashInt32 (fromIntegral x)\n\n-- hi 32 bits of a x-bit * 32 bit -> 64-bit multiply\nmulHi :: Int32 -> Int32 -> Int32\nmulHi a b = fromIntegral (r `shiftR` 32)\n where r :: Int64\n r = fromIntegral a * fromIntegral b\n\n-- | A sample hash function for Strings. We keep multiplying by the\n-- golden ratio and adding. The implementation is:\n--\n-- > hashString = foldl' f golden\n-- > where f m c = fromIntegral (ord c) * magic + hashInt32 m\n-- > magic = 0xdeadbeef\n--\n-- Where hashInt32 works just as hashInt shown above.\n--\n-- Knuth argues that repeated multiplication by the golden ratio\n-- will minimize gaps in the hash space, and thus it's a good choice\n-- for combining together multiple keys to form one.\n--\n-- Here we know that individual characters c are often small, and this\n-- produces frequent collisions if we use ord c alone. A\n-- particular problem are the shorter low ASCII and ISO-8859-1\n-- character strings. We pre-multiply by a magic twiddle factor to\n-- obtain a good distribution. In fact, given the following test:\n--\n-- > testp :: Int32 -> Int\n-- > testp k = (n - ) . length . group . sort . map hs . take n $ ls\n-- > where ls = [] : [c : l | l <- ls, c <- ['\\0'..'\\xff']]\n-- > hs = foldl' f golden\n-- > f m c = fromIntegral (ord c) * k + hashInt32 m\n-- > n = 100000\n--\n-- We discover that testp magic = 0.\n\nhashString :: String -> Int32\nhashString = foldl' f golden\n where f m c = fromIntegral (ord c) * magic + hashInt32 m\n magic = 0xdeadbeef\n\n-- | A prime larger than the maximum hash table size\nprime :: Int32\nprime = 33554467\n\n-- -----------------------------------------------------------------------------\n-- Parameters\n\ntABLE_MAX :: Int32\ntABLE_MAX = 32 * 1024 * 1024 -- Maximum size of hash table\ntABLE_MIN :: Int32\ntABLE_MIN = 8\n\nhLOAD :: Int32\nhLOAD = 7 -- Maximum average load of a single hash bucket\n\nhYSTERESIS :: Int32\nhYSTERESIS = 64 -- entries to ignore in load computation\n\n{- Hysteresis favors long association-list-like behavior for small tables. -}\n\n-- -----------------------------------------------------------------------------\n-- Creating a new hash table\n\n-- | Creates a new hash table. The following property should hold for the @eq@\n-- and @hash@ functions passed to 'new':\n--\n-- > eq A B => hash A == hash B\n--\nnew\n :: (key -> key -> Bool) -- ^ @eq@: An equality comparison on keys\n -> (key -> Int32) -- ^ @hash@: A hash function on keys\n -> IO (HashTable key val) -- ^ Returns: an empty hash table\n\nnew cmpr hash = do\n recordNew\n -- make a new hash table with a single, empty, segment\n let mask = tABLE_MIN-1\n bkts <- newMutArray (0,mask) []\n\n let\n kcnt = 0\n ht = HT { buckets=bkts, kcount=kcnt, bmask=mask }\n\n table <- newIORef ht\n return (HashTable { tab=table, hash_fn=hash, cmp=cmpr })\n\n{- \n bitTwiddleSameAs takes as arguments positive Int32s less than maxBound/2 and \n returns the smallest power of 2 that is greater than or equal to the \n argument.\n http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2\n-}\nbitTwiddleSameAs :: Int32 -> Int32\nbitTwiddleSameAs v0 = \n let v1 = v0-1\n v2 = v1 .|. (v1`shiftR`1)\n v3 = v2 .|. (v2`shiftR`2)\n v4 = v3 .|. (v3`shiftR`4)\n v5 = v4 .|. (v4`shiftR`8)\n v6 = v5 .|. (v5`shiftR`16)\n in v6+1\n\n{-\n powerOver takes as arguments Int32s and returns the smallest power of 2 \n that is greater than or equal to the argument if that power of 2 is \n within [tABLE_MIN,tABLE_MAX]\n-}\npowerOver :: Int32 -> Int32\npowerOver n = \n if n <= tABLE_MIN\n then tABLE_MIN\n else if n >= tABLE_MAX\n then tABLE_MAX\n else bitTwiddleSameAs n \n\n-- | Creates a new hash table with the given minimum size.\nnewHint\n :: (key -> key -> Bool) -- ^ @eq@: An equality comparison on keys\n -> (key -> Int32) -- ^ @hash@: A hash function on keys\n -> Int -- ^ @minSize@: initial table size\n -> IO (HashTable key val) -- ^ Returns: an empty hash table\n\nnewHint cmpr hash minSize = do\n recordNew\n -- make a new hash table with a single, empty, segment\n let mask = powerOver $ fromIntegral minSize\n bkts <- newMutArray (0,mask) []\n\n let\n kcnt = 0\n ht = HT { buckets=bkts, kcount=kcnt, bmask=mask }\n\n table <- newIORef ht\n return (HashTable { tab=table, hash_fn=hash, cmp=cmpr })\n\n-- -----------------------------------------------------------------------------\n-- Inserting a key\\/value pair into the hash table\n\n-- | Inserts a key\\/value mapping into the hash table.\n--\n-- Note that 'insert' doesn't remove the old entry from the table -\n-- the behaviour is like an association list, where 'lookup' returns\n-- the most-recently-inserted mapping for a key in the table. The\n-- reason for this is to keep 'insert' as efficient as possible. If\n-- you need to update a mapping, then we provide 'update'.\n--\ninsert :: HashTable key val -> key -> val -> IO ()\n\ninsert ht key val =\n updatingBucket CanInsert (\\bucket -> ((key,val):bucket, 1, ())) ht key\n\n\n-- ------------------------------------------------------------\n-- The core of the implementation is lurking down here, in findBucket,\n-- updatingBucket, and expandHashTable.\n\ntooBig :: Int32 -> Int32 -> Bool\ntooBig k b = k-hYSTERESIS > hLOAD * b\n\n-- index of bucket within table.\nbucketIndex :: Int32 -> Int32 -> Int32\nbucketIndex mask h = h .&. mask\n\n-- find the bucket in which the key belongs.\n-- returns (key equality, bucket index, bucket)\n--\n-- This rather grab-bag approach gives enough power to do pretty much\n-- any bucket-finding thing you might want to do. We rely on inlining\n-- to throw away the stuff we don't want. I'm proud to say that this\n-- plus updatingBucket below reduce most of the other definitions to a\n-- few lines of code, while actually speeding up the hashtable\n-- implementation when compared with a version which does everything\n-- from scratch.\n{-# INLINE findBucket #-}\nfindBucket :: HashTable key val -> key -> IO (HT key val, Int32, [(key,val)])\nfindBucket HashTable{ tab=ref, hash_fn=hash} key = do\n table@HT{ buckets=bkts, bmask=b } <- readIORef ref\n let indx = bucketIndex b (hash key)\n bucket <- readHTArray bkts indx\n return (table, indx, bucket)\n\ndata Inserts = CanInsert\n | Can'tInsert\n deriving (Eq)\n\n-- updatingBucket is the real workhorse of all single-element table\n-- updates. It takes a hashtable and a key, along with a function\n-- describing what to do with the bucket in which that key belongs. A\n-- flag indicates whether this function may perform table insertions.\n-- The function returns the new contents of the bucket, the number of\n-- bucket entries inserted (negative if entries were deleted), and a\n-- value which becomes the return value for the function as a whole.\n-- The table sizing is enforced here, calling out to expandSubTable as\n-- necessary.\n\n-- This function is intended to be inlined and specialized for every\n-- calling context (eg every provided bucketFn).\n{-# INLINE updatingBucket #-}\n\nupdatingBucket :: Inserts -> ([(key,val)] -> ([(key,val)], Int32, a)) ->\n HashTable key val -> key ->\n IO a\nupdatingBucket canEnlarge bucketFn\n ht@HashTable{ tab=ref, hash_fn=hash } key = do\n (table@HT{ kcount=k, buckets=bkts, bmask=b },\n indx, bckt) <- findBucket ht key\n (bckt', inserts, result) <- return $ bucketFn bckt\n let k' = k + inserts\n table1 = table { kcount=k' }\n writeMutArray bkts indx bckt'\n table2 <- if canEnlarge == CanInsert && inserts > 0 then do\n recordIns inserts k' bckt'\n if tooBig k' b\n then expandHashTable hash table1\n else return table1\n else return table1\n writeIORef ref table2\n return result\n\nexpandHashTable :: (key -> Int32) -> HT key val -> IO (HT key val)\nexpandHashTable hash table@HT{ buckets=bkts, bmask=mask } = do\n let\n oldsize = mask + 1\n newmask = mask + mask + 1\n recordResize oldsize (newmask+1)\n --\n if newmask > tABLE_MAX-1\n then return table\n else do\n --\n newbkts <- newMutArray (0,newmask) []\n\n let\n splitBucket oldindex = do\n bucket <- readHTArray bkts oldindex\n let (oldb,newb) =\n partition ((oldindex==). bucketIndex newmask . hash . fst) bucket\n writeMutArray newbkts oldindex oldb\n writeMutArray newbkts (oldindex + oldsize) newb\n mapM_ splitBucket [0..mask]\n\n return ( table{ buckets=newbkts, bmask=newmask } )\n\n-- -----------------------------------------------------------------------------\n-- Deleting a mapping from the hash table\n\n-- Remove a key from a bucket\ndeleteBucket :: (key -> Bool) -> [(key,val)] -> ([(key, val)], Int32, ())\ndeleteBucket _ [] = ([],0,())\ndeleteBucket del (pair@(k,_):bucket) =\n case deleteBucket del bucket of\n (bucket', dels, _) | del k -> dels' `seq` (bucket', dels', ())\n | otherwise -> (pair:bucket', dels, ())\n where dels' = dels - 1\n\n-- | Remove an entry from the hash table.\ndelete :: HashTable key val -> key -> IO ()\n\ndelete ht@HashTable{ cmp=eq } key =\n updatingBucket Can'tInsert (deleteBucket (eq key)) ht key\n\n-- -----------------------------------------------------------------------------\n-- Updating a mapping in the hash table\n\n-- | Updates an entry in the hash table, returning 'True' if there was\n-- already an entry for this key, or 'False' otherwise. After 'update'\n-- there will always be exactly one entry for the given key in the table.\n--\n-- 'insert' is more efficient than 'update' if you don't care about\n-- multiple entries, or you know for sure that multiple entries can't\n-- occur. However, 'update' is more efficient than 'delete' followed\n-- by 'insert'.\nupdate :: HashTable key val -> key -> val -> IO Bool\n\nupdate ht@HashTable{ cmp=eq } key val =\n updatingBucket CanInsert\n (\\bucket -> let (bucket', dels, _) = deleteBucket (eq key) bucket\n in ((key,val):bucket', 1+dels, dels/=0))\n ht key\n\n-- -----------------------------------------------------------------------------\n-- Looking up an entry in the hash table\n\n-- | Looks up the value of a key in the hash table.\nlookup :: HashTable key val -> key -> IO (Maybe val)\n\nlookup ht@HashTable{ cmp=eq } key = do\n recordLookup\n (_, _, bucket) <- findBucket ht key\n let firstHit (k,v) r | eq key k = Just v\n | otherwise = r\n return (foldr firstHit Nothing bucket)\n\n-- -----------------------------------------------------------------------------\n-- Converting to/from lists\n\n-- | Convert a list of key\\/value pairs into a hash table. Equality on keys\n-- is taken from the Eq instance for the key type.\n--\nfromList :: (Eq key) => (key -> Int32) -> [(key,val)] -> IO (HashTable key val)\nfromList hash list = do\n table <- new (==) hash\n sequence_ [ insert table k v | (k,v) <- list ]\n return table\n\n-- | Converts a hash table to a list of key\\/value pairs.\n--\ntoList :: HashTable key val -> IO [(key,val)]\ntoList = mapReduce id concat\n\n{-# INLINE mapReduce #-}\nmapReduce :: ([(key,val)] -> r) -> ([r] -> r) -> HashTable key val -> IO r\nmapReduce m r HashTable{ tab=ref } = do\n HT{ buckets=bckts, bmask=b } <- readIORef ref\n fmap r (mapM (fmap m . readHTArray bckts) [0..b])\n\n-- -----------------------------------------------------------------------------\n-- Diagnostics\n\n-- | This function is useful for determining whether your hash\n-- function is working well for your data set. It returns the longest\n-- chain of key\\/value pairs in the hash table for which all the keys\n-- hash to the same bucket. If this chain is particularly long (say,\n-- longer than 14 elements or so), then it might be a good idea to try\n-- a different hash function.\n--\nlongestChain :: HashTable key val -> IO [(key,val)]\nlongestChain = mapReduce id (maximumBy lengthCmp)\n where lengthCmp (_:x)(_:y) = lengthCmp x y\n lengthCmp [] [] = EQ\n lengthCmp [] _ = LT\n lengthCmp _ [] = GT\n\n\n\ntype Graph = HashTable Int (S.Set Int)\n\ntype Queue = [Int]\n\n\n\n\nenqueue' :: Int -> Queue -> IO Queue\nenqueue' x s = return (s++[x])\n\nenqueue :: Int -> Queue -> IO Queue\nenqueue x s = do s <- enqueue' x s\n\t return s\n\npop :: Queue -> IO (Int,Queue)\npop (x:xs) = return (x,xs)\n\nnewGraph :: IO Graph\nnewGraph = new (\\x y -> x == y) (\\x -> hashInt x)\n\nginsert :: Int -> Graph -> IO ()\nginsert v g = insert g v (S.empty) \n\nginsertEdge :: Int -> Int -> Graph -> IO ()\nginsertEdge v v' g = do maybeset1 <- lookup g v\n\t\t maybeset2 <- lookup g v'\n\t\t case maybeset1 of\n\t\t\t Nothing -> return ()\n\t\t\t Just set1 -> case maybeset2 of\n\t\t\t\t Nothing -> return ()\n\t\t\t\t Just set2 -> do b1 <- update g v (S.insert v' set1)\n\t\t\t\t\t\t b2 <- update g v' (S.insert v set2)\n\t\t\t\t\t\t return ()\n\nginsertEdgeDir :: Int -> Int -> Graph -> IO ()\nginsertEdgeDir v v' g = do maybeset1 <- lookup g v\n\t\t\t maybeset2 <- lookup g v'\n\t\t case maybeset1 of\n\t\t\t Nothing -> return ()\n\t\t\t Just set1 -> case maybeset2 of\n\t\t\t\t Nothing -> return ()\n\t\t\t\t Just set2 -> do b1 <- update g v (S.insert v' set1)\n\t\t\t\t\t\t return ()\ngprintGraph :: Graph -> IO ()\ngprintGraph g = do xs <- toList g\n\t\t print xs\n\nputQueue :: S.Set Int -> Queue -> IO Queue\nputQueue set q = return (L.nub (q ++ S.elems set))\n\n\nbfs'' :: Graph -> Queue -> S.Set Int -> IO [Int]\nbfs'' g [] visited = return []\nbfs'' g q visited = do (i',q') <- pop q\n\t\t if S.notMember i' visited then(do maybeset <- lookup g i'\n\t\t\t\t\t case maybeset of\n\t\t\t\t\t\t Nothing -> return []\n\t\t\t\t\t\t Just set ->(do q <- putQueue set q\n\t\t\t\t\t\t\t\t\t xs <- bfs'' g q (S.insert i' visited)\n\t\t\t\t\t\t\t\t\t return (i':xs)))\n\t\t\t\t\t\t else(do xs <- bfs'' g q' visited\n\t\t\t\t\t\t\t return xs)\n\n\nbfs' :: Int -> Graph -> Queue -> IO [Int]\nbfs' i g q = do q <- putQueue (S.singleton i) q\n\t\txs <- bfs'' g q S.empty\n\t\treturn xs\n\n\t\t\t \nbfs :: Int -> Graph -> IO [Int]\nbfs i g = bfs' i g []\n\ninsertCells :: Int -> Graph -> IO ()\ninsertCells 1 g = do ginsert 1 g\n\t\t return ()\ninsertCells n g = do ginsert n g\n\t\t insertCells (n-1) g\n\n\n\ninsertPortals :: Int -> [Int] -> Int -> Graph -> IO ()\ninsertPortals i [] n g = return ()\ninsertPortals i (x:xs) n g = if i <= n then do ginsertEdgeDir i (i+x) g \n\t\t\t \t\t insertPortals (i+1) xs n g\n\t\t\t else return ()\n\n\n\t\n\nmakeList :: Int -> String -> [Int]\nmakeList 0 s = []\nmakeList n [] = []\nmakeList n (' ':s) = makeList n s\nmakeList n s = let (snumber,s') = span isDigit s \n\t\t number = read snumber :: Int in number:(makeList (n-1) s')\n\nmain :: IO ()\nmain = do s <- getLine\n\t s' <- getLine\n\t let (sn,s1) = span isDigit s\n\t (st,s2) = span isDigit (tail s1)\n\t n = read sn :: Int\n\t t = read st :: Int\n\t xs = makeList (n-1) s' in do g <- newGraph\n\t\t\t\t\t insertCells n g\n\t\t\t\t\t insertPortals 1 xs n g\n\t\t\t\t\t xs <- bfs 1 g\n\t\t\t\t\t if (L.elem t xs) then putStrLn \"YES\" else putStrLn \"NO\"\n\n\n\n\n"}, {"source_code": "import Data.List\n\ncanReach :: [Int] -> Int -> String\ncanReach xs dest\n | dest == 0 = \"YES\"\n | dest < 0 = \"NO\" \n | otherwise = canReach (drop jump xs) (dest - jump)\n where jump = head xs\n\nsolve :: String -> String\nsolve s = canReach xs (dest - 1)\n where (_:dest:xs) = fmap read. words $ s \n\nmain :: IO ()\nmain= interact $ solve"}, {"source_code": "solve :: [Int] -> Int -> Int -> String\nsolve ports cur dest\n | cur == dest = \"YES\"\n | cur > dest = \"NO\"\n | otherwise = solve (drop (head ports) ports) (cur + (head ports)) dest\n\nmain = do\n inp <- getLine\n let [n, x] = map read (words inp)\n inp <- getLine\n let a = map read $ words inp\n putStrLn $ solve a 1 x"}, {"source_code": "module Main where\n\ndata Tree a = EmptyTree | Tree (Tree a) (Tree a) a\n\ndata Vector a = Vector Int (Tree a)\n(!)::Vector a -> Int -> a\n(!) (Vector n t) i = get 0 (n - 1) t i\n where get l r (Tree lc rc v) i | i < m = get l (m - 1) lc i\n | i > m = get (m + 1) r rc i\n | otherwise = v\n where m = div (l + r) 2\ngenerate::Int -> (Int -> a) -> Vector a\ngenerate n f = Vector n (gen 0 (n - 1) f)\n where gen l r f | l >\u3000r = EmptyTree\n | otherwise = Tree (gen l (m - 1) f) (gen (m + 1) r f) (f m)\n where m = div (l + r) 2\nfromListN::Int -> [a] -> Vector a\nfromListN n an = Vector n (fst (gen 0 (n - 1) an))\n where gen l r an | l >\u3000r = (EmptyTree, an)\n | otherwise = let (lc,(v:an')) = gen l (m - 1) an\n (rc,an'') = (gen (m + 1) r an')\n in (Tree lc rc v, an'')\n where m = div (l + r) 2\n\nsolveA n t an = if visitable ! 0 then \"YES\" else \"NO\"\n where visitable = generate n f\n f x |\u3000x > t = False\n | x == t = True\n | otherwise = f (x + (an ! x))\n\ntaskA = do input <- getContents\n let (n:t:an) = Prelude.map (read::String->Int) $ words input\n putStrLn $ solveA n (t - 1) (fromListN (n - 1) an)\n\nmain = taskA\n"}, {"source_code": "import Data.Array\nmain = do\n [n,t] <- words `fmap`getLine\n\n \n a <-getLine\n let portal=array (1,(read n)-1) $ zip [1..(read n)-1] (map read $words a)\n putStrLn $ canIpass (read n) (read t) portal\n\n-- portal from i to i+ai\n\npossiblePosition::Int->Int->Array Int Int->[Int]\npossiblePosition 0 _ _ = []\npossiblePosition count currPos portals\n | currPos<=snd (bounds portals) = [currPos+portals!currPos] ++ \n possiblePosition (count-1) (currPos+portals!currPos) portals\n | otherwise = []\n\ncanIpass::Int->Int->Array Int Int->String\ncanIpass count endPos portals =\n if endPos `elem` (possiblePosition count 1 portals) \n then \"YES\"\n else \"NO\""}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\n\nreadListLn :: IO [Int]\nreadListLn = (map (fst . fromJust . B.readInt) . B.words) `liftM` B.getLine\n\nguess :: Int -> Array Int Int -> Bool \nguess t arr = first == t \n where\n first = head $ dropWhile ( (i, i+a)) as [1..] ++ [(n, n)]\n\n find u\n | u == t = True\n | v == u = False\n | otherwise = find v\n where v = a!u\n\n putStrLn $ if find 1 then \"YES\" else \"NO\"\n"}, {"source_code": "main = interact $ f . map read . words\nf (n:t:a) | t == 1 = \"YES\"\nf (n:t:a:b) = f (n:t - a:drop (a - 1) b)\nf _ = \"NO\"\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,t) <- readIntPair\n as <- readInts\n case solve n t as of\n True -> putStrLn \"YES\"\n False -> putStrLn \"NO\"\n\nsolve :: Int -> Int -> [Int] -> Bool\nsolve n t as = go 1 where\n g :: UArray Int Int\n g = array (1,n-1) [ (i,i+ai) | (i,ai) <- zip [1..] as]\n go p | p == t = True\n | p > t = False\n | otherwise = go (g ! p)\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map (map read.words).take 2 . lines\nsolve :: [[Int]]->String\nsolve [[_,x],ys] = slv1 0\n where slv1 ot | ot < x-1 = slv1 (ot+(ys !! ot))\n | ot == x-1 = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve :: Int -> [Int] -> Bool\nsolve 1 _ = True\nsolve _ [] = False\nsolve t a@(h:_) = t >= 1 && solve (t - h) (drop h a)\n\nmain :: IO ()\nmain = do\n [_, t] <- getIntList\n a <- getIntList\n putStrLn $ if solve t a then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Control.Monad\n\nprocess c f a | c==f = \"YES\"\n | c>f = \"NO\"\n | otherwise = process (c+a!!c) f a\n\nmain=do\n [n,m]<- map read <$> words <$> getLine:: IO [Int]\n a<- map read <$> words <$> getLine ::IO [Int]\n putStrLn $ process 0 (m-1) a\n"}], "negative_code": [{"source_code": "main = interact $ f 1 . map read . words\nf x [n,t] = \"NO\"\nf x (n:t:a:b) | x == t = \"YES\"\n | otherwise = f (x + a) (n:t:drop (a - 1) b)\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.map (map read.words).take 2 . lines\nsolve :: [[Int]]->String\nsolve [[_,x],ys] = slv1 1\n where slv1 ot | ot < x = slv1 (ot+(ys !! ot)+1)\n | ot == x = \"YES\"\n | otherwise = \"NO\""}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport Control.Monad\n\nprocess c f a | c==f = \"YES\"\n | c>f = \"NO\"\n | otherwise = process (c+a!!c) f a\n\nmain=do\n [n,m]<- map read <$> words <$> getLine:: IO [Int]\n a<- map read <$> words <$> getLine ::IO [Int]\n print $ process 0 (m-1) a\n"}, {"source_code": "main=interact$show.f.map read.words\nf(a:x:xs)\n | x==1 = \"YES\"\n | x<1 = \"NO\"\n | otherwise = f([a] ++ [x - (head xs)] ++ (drop (head xs) xs))"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve [[_, t], as] = go t as\n where go 0 _ = True\n go n _ | n < 0 = False\n go n (x:xs) = go (n - x) (drop x xs)\n go _ _ = False\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . yesno . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Bool\nsolve [[_, t], as] = go t as\n where go 0 _ = True\n go n _ | n < 0 = False\n go n xs@(x:_) = go (n - x) (drop x xs)\n go _ _ = False\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/500/A\n\nsolve :: Int -> [Int] -> Bool\nsolve t a | reachable == t = True\n | otherwise = False\n where reachable = last $ takeWhile (<= t) $ zipWith (+) [1..] a\n\nmain :: IO ()\nmain = do\n [_, t] <- map read . words <$> getLine :: IO [Int]\n a <- map read . words <$> getLine :: IO [Int]\n putStrLn $ if solve t a then \"YES\" else \"NO\"\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/500/A\n\nsolve :: Int -> [Int] -> Bool\nsolve t a | reachable == t = True\n | otherwise = False\n where reachable = last $ takeWhile (<= t) $ zipWith (+) [1..] a\n\nmain :: IO ()\nmain = do\n [_, t] <- map read . words <$> getLine :: IO [Int]\n a <- map read . words <$> getLine :: IO [Int]\n print $ if solve t a then \"YES\" else \"NO\"\n"}, {"source_code": "main = do \n constraints <- getLine\n lineSystem <- getLine\n \n let [_, destination] = readInts constraints\n portals = zip (readInts lineSystem) [1..]\n\n putStrLn $ result portals destination\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nresult :: [(Int, Int)] -> Int -> String\nresult [] _ = \"NO\"\nresult (x:xs) dest\n | index == dest = \"YES\"\n | index > dest = \"NO\"\n | otherwise = result (drop jump (x:xs)) dest\n where (jump, index) = x\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.Maybe (fromJust)\n\nprocess :: Int -> Int -> [Int] -> Bool\nprocess n t xs = f t\n where\n m = Map.fromList $ zipWith (\\i x -> (i+x,x)) [1..] xs\n f 1 = True\n f t\n | t' == Nothing = False\n | otherwise = f $ fromJust t'\n where t' = Map.lookup t m\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,t] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n putStrLn $ [\"NO\",\"YES\"] !! fromEnum (process n t as)"}, {"source_code": "import Data.Graph\n\nprocess :: Int -> Int -> [Int] -> Bool\nprocess n t xs = path g 1 t\n where g = buildG (1,n) $ zipWith (\\i x -> (x,i+x)) [1..] xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,t] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n putStrLn $ [\"NO\",\"YES\"] !! fromEnum (process n t as)"}, {"source_code": "reach _ [] = \"NO\"\nreach 0 _ = \"YES\"\nreach t (a:ais)\n | t > 0 = reach (t - a) $ drop (a - 1) ais\n | otherwise = \"NO\"\n\nsolve str =\n let (n:t:ais) = (map read . words) str\n in reach (t - 1) ais\n\nmain = interact solve"}], "src_uid": "9ee3d548f93390db0fc2f72500d9eeb0"} {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms, CPP,\n TupleSections, LambdaCase,\n MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . addCnt . (map fromOp).sol.(map toOp).tail . lines\n\ntype Op = (Char, Int)\n\neval :: Char -> (Int -> Int -> Int)\neval = \\case\n '|' -> (.|.)\n '&' -> (.&.)\n '^' -> xor\n\napply :: Int -> Op -> Int\napply v (o,w) = (eval o) v w\n\nsol os = let (o,a,x)=foldl ff (0,(1`shiftL`32) - 1,0) list in [('|', o), ('&',a), ('^',x)]\n where\n _0s = ev 0 os\n _1s = ev 1023 os\n list = zipWith idf _1s _0s\n idf (n, v) (n', w) = assert (n==n') $ (n, (v,w))\n ff :: (Int, Int, Int) -> (Int, (Bool,Bool)) -> (Int, Int, Int)\n ff (o,a,x) (n, pv) = let b=shiftL 1 n in case pv of\n (True, True) -> (o.|.b, a, x)\n (True, False) -> (o, a, x)\n (False, True) -> (o, a, x.|.b)\n (False, False) -> (o, a`xor`b, x)\n ev n os = toBitMap $ foldl apply n os\n\ntoOp :: String -> Op\ntoOp s = (op, arg)\n where [[op], arg'] = words s\n arg = read arg'\n\nfromOp :: Op -> String\nfromOp (op, arg) = op : \" \" ++ show arg\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\nwrap :: a -> [a]\nwrap x = [x]\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE DeriveGeneric, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Bits\nimport GHC.Generics\nimport Control.DeepSeq\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n (\\(a, o, x) -> \"3\\n& \" ++ show a ++ \"\\n| \" ++ show o ++ \"\\n^ \" ++ show x) `fmap` solve `fmap` replicateM n (liftM2 (\\a b -> (B.head a, b)) pop poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\ndata Op = Id | Neg | Set0 | Set1 deriving (Show, Generic)\ninstance NFData Op\nneg Neg = Id\nneg Id = Neg\nneg Set0 = Set1\nneg Set1 = Set0\n\ncomb x '|' False = x\ncomb _ '|' True = Set1\ncomb x '^' False = x\ncomb x '^' True = neg x\ncomb _ '&' False = Set0\ncomb x '&' True = x\n\nsolve :: [(Char, Int)] -> (Int, Int, Int)\nsolve os = foldl' (\\s@(!a, !o, !x) (i, c) -> case c of { Id -> s; Neg -> (a, o, x `setBit` i); Set0 -> (a `clearBit` i, o, x); Set1 -> (a, o `setBit` i, x) }) (1023, 0, 0) $ zip [0..] $ foldl' (\\cs (o, n) -> force $ zipWith (\\i c -> comb c o (n `testBit` i) :: Op) [0..] cs) (replicate 10 Id) os"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE DeriveGeneric, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Bits\nimport GHC.Generics\nimport Control.DeepSeq\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n (\\(a, o, x) -> \"3\\n& \" ++ show a ++ \"\\n| \" ++ show o ++ \"\\n^ \" ++ show x) `fmap` solve `fmap` replicateM n (liftM2 (\\a b -> (B.head a, b)) pop poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\ndata Op = Id | Neg | Set0 | Set1 deriving (Show, Generic)\ninstance NFData Op\nneg Neg = Id\nneg Id = Neg\nneg Set0 = Set1\nneg Set1 = Set0\n\ncomb x '|' False = x\ncomb _ '|' True = Set1\ncomb x '^' False = x\ncomb x '^' True = neg x\ncomb _ '&' False = Set0\ncomb x '&' True = x\n\nsolve :: [(Char, Int)] -> (Int, Int, Int)\nsolve os = foldl' (\\s@(!a, !o, !x) (i, c) -> case c of { Id -> s; Neg -> (a, o, x `setBit` i); Set0 -> (a `clearBit` i, o, x); Set1 -> (a, o `setBit` i, x) }) (1023, 0, 0) $ zip [0..] $ foldl' (\\cs (o, n) -> zipWith (\\i c -> comb c o (n `testBit` i) :: Op) [0..] cs) (replicate 10 Id) os"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE DeriveGeneric, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Bits\nimport GHC.Generics\nimport Control.DeepSeq\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n (\\(a, o, x) -> \"3\\n& \" ++ show a ++ \"\\n| \" ++ show o ++ \"\\n^ \" ++ show x) `fmap` solve `fmap` replicateM n (liftM2 (\\a b -> (B.head a, b)) pop poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\ndata Op = Id | Neg | Set0 | Set1 deriving (Show, Generic)\ninstance NFData Op\nneg Neg = Id\nneg Id = Neg\nneg Set0 = Set1\nneg Set1 = Set0\n\ncomb x '|' False = x\ncomb _ '|' True = Set1\ncomb x '^' False = x\ncomb x '^' True = neg x\ncomb _ '&' False = Set0\ncomb x '&' True = x\n\nsolve :: [(Char, Int)] -> (Int, Int, Int)\nsolve os = foldl' (\\s@(!a, !o, !x) (i, c) -> case c of { Id -> s; Neg -> (a, o, x `setBit` i); Set0 -> (a `clearBit` i, o, x); Set1 -> (a, o `setBit` i, x) }) (1023, 0, 0) $ zip [0..] $ foldl' (\\cs (o, n) -> force $ zipWith (\\i c -> comb c o (n `testBit` i) :: Op) [0..] cs) (replicate 10 Id) os"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE DeriveGeneric, BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Bits\nimport GHC.Generics\nimport Control.DeepSeq\n\nmain = B.interact exec\nexec = B.pack . evalState app . B.words\napp = do\n n <- poi\n (\\(a, o, x) -> \"3\\n& \" ++ show a ++ \"\\n| \" ++ show o ++ \"\\n^ \" ++ show x) `fmap` solve `fmap` replicateM n (liftM2 (\\a b -> (B.head a, b)) pop poi)\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\ndata Op = Id | Neg | Set0 | Set1 deriving (Show, Generic)\ninstance NFData Op\nneg Neg = Id\nneg Id = Neg\nneg Set0 = Set1\nneg Set1 = Set0\n\ncomb x '|' False = x\ncomb _ '|' True = Set1\ncomb x '^' False = x\ncomb x '^' True = neg x\ncomb _ '&' False = Set0\ncomb x '&' True = x\n\nsolve :: [(Char, Int)] -> (Int, Int, Int)\nsolve os = foldl' (\\s@(!a, !o, !x) (i, c) -> case c of { Id -> s; Neg -> (a, o, x `setBit` i); Set0 -> (a `clearBit` i, o, x); Set1 -> (a, o `setBit` i, x) }) (1023, 0, 0) $ zip [0..] $ foldl' (\\cs (o, n) -> force $ zipWith (\\i c -> comb c o (n `testBit` i) :: Op) [0..] cs) (replicate 10 Id) os"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Bits\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n xs <- map C.words <$> replicateM n C.getLine\n let ans = solve xs\n print $ length ans\n putStrLn $ unlines ans\n\nreadInt = fst . fromJust . C.readInt\n\nsolve xs = gen $ foldl run [0, 1023] xs\n\nrun ps (c:x:_) | c == \"&\" = map (.&. v) ps\n | c == \"|\" = map (.|. v) ps\n | c == \"^\" = map (xor v) ps\n where v = readInt x\n\ngen :: [Int] -> [String]\ngen [a,b] = [\"& \" ++ show ((xor a 1023 .&. b) .|. (a .&. xor b 1023))\n ,\"^ \" ++ show (a .&. xor b 1023)\n ,\"| \" ++ show (a .&. b)\n ]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Bits\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n xs <- map C.words <$> replicateM n C.getLine\n let ans = solve xs\n print $ length ans\n putStrLn $ unlines ans\n\nreadInt = fst . fromJust . C.readInt\n\nsolve xs = gen $ foldl run [0, 1023] xs\n\nrun ps (c:x:_) | c == \"&\" = map (.&. v) ps\n | c == \"|\" = map (.|. v) ps\n | c == \"^\" = map (xor v) ps\n where v = readInt x\n\ngen :: [Int] -> [String]\ngen [a,b] = [\"& \" ++ show (xor a 1023 .&. b)\n ,\"| \" ++ show (a .&. b)\n ,\"^ \" ++ show (a .&. xor b 1023)\n ]\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Bits\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n xs <- map C.words <$> replicateM n C.getLine\n let ans = solve xs\n print $ length ans\n putStrLn $ unlines ans\n\nreadInt = fst . fromJust . C.readInt\n\nsolve xs = gen $ foldl run [0, 1023] xs\n\nrun ps (c:x:_) | c == \"&\" = map (.&. v) ps\n | c == \"|\" = map (.|. v) ps\n | c == \"^\" = map (xor v) ps\n where v = readInt x\n\ngen :: [Int] -> [String]\ngen [a,b] = [\"| \" ++ show (a .&. b)\n ,\"& \" ++ show (xor a 1023 .&. b)\n ,\"^ \" ++ show (a .&. xor b 1023)\n ]\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Bits\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n xs <- map C.words <$> replicateM n C.getLine\n let ans = solve xs\n print $ length ans\n putStrLn $ unlines ans\n\nreadInt = fst . fromJust . C.readInt\n\nsolve xs = gen $ foldl run [0, 1023] xs\n\nrun ps (c:x:_) | c == \"&\" = map (.&. v) ps\n | c == \"|\" = map (.|. v) ps\n | c == \"^\" = map (xor v) ps\n where v = readInt x\n\ngen :: [Int] -> [String]\ngen [a,b] = [\"& \" ++ show (xor a 1023 .&. b)\n ,\"^ \" ++ show (a .&. xor b 1023)\n ,\"| \" ++ show (a .&. b)\n ]\n"}], "src_uid": "19c32b8c1d3db5ab10aca271135aa9b8"} {"source_code": "import Control.Monad\nimport Data.Function\nimport Data.Functor\nimport Data.List\nmain :: IO ()\nmain = do\n n <- getLine <&> read :: IO Int\n replicateM_ n $ do\n l <- getLine <&> read :: IO Int\n s <- getLine\n let g = group s\n length g & (`div` 2) & (g !!) & length & print\n return ()\n\n", "positive_code": [{"source_code": "module Main (main)\nwhere\n\nimport Data.List (intercalate)\nimport System.IO (IO (..))\n\ntype Case = (Int, String)\n\nmain :: IO ()\nmain = intercalate \"\\n\" <$> map show <$> map solve <$> (read <$> getLine >>= readNCases) >>= putStrLn\n\nreadNCases :: Int -> IO [Case]\nreadNCases n = sequence $ replicate n readOneCase\n\nreadOneCase :: IO Case\nreadOneCase = (\\[a, b] -> (read a, b)) <$> (sequence $ replicate 2 getLine)\n\nsolve :: Case -> Int\nsolve (n, str)\n | odd n = (solve' $ reverse (take ((n + 1) `div` 2) str)) * 2 - 1\n | otherwise = (solve' $ reverse $ take (n `div` 2) str) * 2\n\nsolve' :: [Char] -> Int\nsolve' [] = 0\nsolve' [x] = 1\nsolve' (x:y:xs) = if (x == y) then 1 + solve' (y:xs) else 1\n"}, {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: B8.ByteString -> Int\nsolve str = L.length middleGroup\n where\n groups = L.group $ B8.unpack str\n middleGroup = groups L.!! (L.length groups `div` 2)\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n str <- B8.getLine <&> head . B8.words\n let answer = solve str\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "fa761cd247a815f105668b716c20f0b4"} {"source_code": "import Control.Monad\nimport Data.Array.IO\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n nAndQ <- (map (read :: String -> Int) . words) <$> getLine\n let n = nAndQ !! 0\n q = nAndQ !! 1\n arr <- newArray (1, n) 0 :: IO (IOArray Int Int)\n ns <- (map (read :: String -> Int) . words) <$> getLine\n count <- newIORef 0\n forM (zip [1..] ns) $ \\(i, v) -> do\n writeArray arr i v\n modifyIORef count (if v == 1 then (+1) else id)\n forM [1..q] $ \\_ -> do\n tv <- (map (read :: String -> Int) . words) <$> getLine\n let t = tv !! 0\n v = tv !! 1\n if t == 1 then do\n x <- readArray arr v\n writeArray arr v (1 - x)\n modifyIORef count (if x == 0 then (+1) else (\\a -> a - 1))\n else do\n c <- readIORef count\n print $ if v <= c then 1 else 0\n pure ()\n \n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.IO.Safe\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, q] <- readInts\n aLi <- readInts\n a <- lift (newListArray (1, n) aLi :: IO (IOUArray Int Int))\n let\n step ct () = do\n [t, x] <- readInts\n if t == 2\n then do\n ct <$ putInts [if ct >= x then 1 else 0]\n else lift $ do\n v <- readArray a x\n (ct + 1 - 2*v) <$ writeArray a x (1-v)\n foldM_ step (foldl' (+) 0 aLi) (replicate q ())\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "ccf7aba6ca9bbf39a5ec8a20ec018825"} {"source_code": "--ghc 7.10\n\nimport Data.Bits((.|.))\n\ncountFloorNonsleeping :: [Int] -> Int\ncountFloorNonsleeping (x:y:ys) = (x .|. y) + countFloorNonsleeping ys\ncountFloorNonsleeping _ = 0\n\ncountBuldingNonsleeping :: [[Int]] -> Int\ncountBuldingNonsleeping = sum . map countFloorNonsleeping\n\nmain = do\n nmStr <- getLine\n contents <- getContents\n let xss = map (map read . words) . lines $ contents\n print $ countBuldingNonsleeping xss", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List.Split\n\nmain :: IO ()\nmain = do\n flats <- drop 1 . chunksOf 2 . map (read::String->Int) . words <$> getContents\n print . length . filter (> 0) $ map sum flats\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve (x:y:ys) = signum (x + y) + solve ys\n\nmain :: IO ()\nmain = do\n [n,m] <- map read . words <$> getLine\n ws <- concatMap (map read . words) <$> replicateM n getLine\n print $ solve ws\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess n [] = n\nprocess n (a:b:s) = process (if a+b>0 then (n+1) else n) s\n\n \n\nmain= do\n\tgetLine\n\ts<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tprint $ sum $ map (process 0) s"}, {"source_code": "module Main where\n\n-- A\n\nsplit :: Char -> String -> [String]\nsplit _ [] = [\"\"]\nsplit c (x:xs) | x == c = \"\" : rest\n | otherwise = (x : head rest): tail rest\n where rest = split c xs\n\nsolution :: [String] -> Int -> Int\nsolution stringFloors roomsAmount =\n let\n floors = map (\\line -> map read (split ' ' line) :: [Int]) stringFloors\n countWake = \\floor -> sum [if floor !! (i*2) == 1 || floor !! (i*2+1) == 1 then 1 else 0 |i <- [0..roomsAmount - 1]]\n in\n sum (map countWake floors)\n\n\nmain = getLine >>=\n \\houseParamsString ->\n let\n houseParamsList = map read (split ' ' houseParamsString) :: [Int]\n floorsAmount = houseParamsList !! 0\n rooms = houseParamsList !! 1\n in\n sequence (replicate floorsAmount getLine) >>=\n \\floors ->\n putStrLn $ show (solution floors rooms)\n"}, {"source_code": "main :: IO()\nmain = print . solve . map read . drop 2 . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve (a:b:x) = let rest = solve x\n in if a == 0 && b == 0 then rest else 1 + rest\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n ls <- replicateM n getInts\n\n let\n f [] = 0\n f (a:b:xs) = (if a == 1 || b == 1 then 1 else 0) + f xs\n\n print $ sum $ map f ls\n"}, {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents \nmain = do\n [n,m] <- readLists\n a <- readMatrix\n print $ sum $ [num|a0 <-a,let num = length $ filter (1<=) $ zipWith (+) [at|(it,at)<-zip [0..] a0,(mod it 2) == 0] [at|(it,at)<-zip [0..] a0,(mod it 2) == 1]]\n"}, {"source_code": "main = interact $ show . f . map read . words\nf (a:b:c) = f1 c\nf1 [] = 0\nf1 (0:0:a) = f1 a\nf1 (a:b:c) = 1 + f1 c"}, {"source_code": "main = interact $ show . length . filter (> 0) . map (uncurry (+)) . pairs . map read . drop 2 . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\n"}, {"source_code": "module Main where\n\nimport Data.Functor\n\nmain :: IO ()\nmain = do\n [rn,cn] <- words <$> getLine\n mx <- getMatrix (read rn) (2 * read cn)\n print $ calc mx\n\ngetMatrix :: Int -> Int -> IO [[Int]]\ngetMatrix rn cn = do\n rows <- take rn <$> lines <$> getContents\n return $ map (map read . take cn . words) rows\n\ncalc :: [[Int]] -> Int\ncalc = sum . map group2\n\ngroup2 :: [Int] -> Int\ngroup2 [] = 0\ngroup2 (0:0:as) = 0 + group2 as\ngroup2 (0:1:as) = 1 + group2 as\ngroup2 (1:0:as) = 1 + group2 as\ngroup2 (1:1:as) = 1 + group2 as\ngroup2 _ = undefined\n"}], "negative_code": [], "src_uid": "5b9aed235094de7de36247a3b2a34e0f"} {"source_code": "import Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array\nimport qualified Data.ByteString.Char8 as BS\n\nreadInt b = let (Just (a, _)) = BS.readInt b in a\n\nmain = BS.interact $ BS.unlines . map (BS.pack . show) . solve . map readInt . BS.words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = map (\\i -> snd $ all ! i) queries\n where p = take (n-1) rest\n pa = array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\ntoG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (weight, centroid)\n where centroid = if children == [] || (fst fat) * 2 <= weight\n then v\n else lift $ snd fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map fst children)\n lift c = if (weight - (fst $ ans ! c)) * 2 <= weight\n then c\n else lift (pa ! c)\n", "positive_code": [{"source_code": "-- Codeforces 686D\n\n{-# OPTIONS_GHC -O0 #-}\n{-# OPTIONS_GHC -optc-O0 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n (n:q:rest) <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents\n let !(!xs, !qs) = splitAt (n - 1) rest\n\n -- build graph\n let !graph = runSTArray $ do\n graph <- newArray (1, n) [] :: ST s (STArray s Int [Int])\n for_ (zip [2..n] xs) $ \\(i, x) -> do\n xs <- readArray graph x\n writeArray graph x (i:xs)\n return graph\n\n let !fa = listArray (2, n) xs :: UArray Int Int\n\n -- dfs\n let !centeroid = runSTUArray $ do\n son <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n centeroid <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n dfs graph fa son centeroid 1\n return centeroid\n\n -- result\n BC.putStrLn . BC.intercalate \"\\n\" . map (BC.pack . show . (!) centeroid) $ qs\n\n where\n\n dfs graph fa son centeroid u = do\n writeArray son u 1\n writeArray centeroid u u\n\n maxs <- forM (graph ! u) $ \\v -> do\n dfs graph fa son centeroid v\n !szu <- readArray son u\n !szv <- readArray son v\n writeArray son u (szu + szv)\n return (szv, v)\n\n let !maxv = if null maxs then 0\n else snd . Data.List.maximum $ maxs\n\n if maxv /= 0\n then do\n a <- readArray son maxv\n b <- readArray son u\n if a * 2 > b\n then do\n su <- readArray son u\n r <- readArray centeroid maxv\n r' <- goup fa son su r\n writeArray centeroid u r'\n else return ()\n else return ()\n\n goup fa son su now = do\n k <- readArray son now\n if (su - k) * 2 > su\n then goup fa son su (fa ! now) -- go up\n else return now\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array\nimport qualified Data.ByteString.Char8 as BS\n\nreadInt b = let (Just (a, _)) = BS.readInt b in a\n\nmain = BS.interact $ BS.unlines . map (BS.pack . show) . solve . map readInt . BS.words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = map (\\i -> snd $ all ! i) queries\n where p = take (n-1) rest\n pa = array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\nupdateArray a i f = do\n v <- readArray a i\n writeArray a i (f v)\n\ntoG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> updateArray graph pi (i:)\n return graph\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (weight, centroid)\n where centroid\n | children == [] || (fst fat) * 2 <= weight = v\n | otherwise = lift $ snd fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map fst children)\n lift c\n | (weight - (fst $ ans ! c)) * 2 <= weight = c\n | otherwise = lift (pa ! c)\n"}, {"source_code": "-- Codeforces 686D\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n (n:q:rest) <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents\n let !(!xs, !qs) = splitAt (n - 1) rest\n\n -- build graph\n let !graph = runSTArray $ do\n graph <- newArray (1, n) [] :: ST s (STArray s Int [Int])\n for_ (zip [2..n] xs) $ \\(i, x) -> do\n xs <- readArray graph x\n writeArray graph x (i:xs)\n return graph\n\n let !fa = listArray (2, n) xs :: UArray Int Int\n\n -- dfs\n let !centeroid = runSTUArray $ do\n son <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n centeroid <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n dfs graph fa son centeroid 1\n return centeroid\n\n -- result\n BC.putStrLn . BC.intercalate \"\\n\" . map (BC.pack . show . (!) centeroid) $ qs\n\n where\n\n dfs graph fa son centeroid u = do\n writeArray son u 1\n writeArray centeroid u u\n\n maxs <- forM (graph ! u) $ \\v -> do\n dfs graph fa son centeroid v\n !szu <- readArray son u\n !szv <- readArray son v\n writeArray son u (szu + szv)\n return (szv, v)\n\n let !maxv = if null maxs then 0\n else snd . Data.List.maximum $ maxs\n\n if maxv /= 0\n then do\n a <- readArray son maxv\n b <- readArray son u\n if a * 2 > b\n then do\n su <- readArray son u\n r <- readArray centeroid maxv\n r' <- goup fa son su r\n writeArray centeroid u r'\n else return ()\n else return ()\n\n goup fa son su now = do\n k <- readArray son now\n if (su - k) * 2 > su\n then goup fa son su (fa ! now) -- go up\n else return now\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Array as A\n\nmain = interact $ unlines . map show . solve . map read . words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = map (\\i -> fst $ all ! i) queries\n where p = take (n-1) rest\n pa = A.array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\ntoG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (baricenter, weight)\n where baricenter = if children == [] || (snd fat) * 2 <= weight\n then v\n else lift $ fst fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map snd children)\n lift c = if (weight - (snd (ans ! c))) * 2 <= weight\n then c\n else lift (pa ! c)\n"}, {"source_code": "-- Codeforces 686D\n\n{-# OPTIONS_GHC -O0 #-}\n{-# OPTIONS_GHC -optc-O0 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport qualified Data.ByteString.Char8 as BC\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n (n:q:rest) <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents\n let !(!xs, !qs) = splitAt (n - 1) rest\n\n -- build graph\n let !graph = runSTArray $ do\n graph <- newArray (1, n) [] :: ST s (STArray s Int [Int])\n for_ (zip [2..n] xs) $ \\(i, x) -> do\n xs <- readArray graph x\n writeArray graph x (i:xs)\n return graph\n\n let !fa = listArray (1, n) (0:xs) :: UArray Int Int\n\n -- dfs\n let !centeroid = runSTUArray $ do\n son <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n centeroid <- newArray (1, n) 0 :: ST s (STUArray s Int Int)\n -- dfs graph fa son centeroid 1\n return centeroid\n\n -- result\n BC.putStrLn . BC.intercalate \"\\n\" . map (BC.pack . show . (!) centeroid) $ qs\n\n where\n\n dfs graph fa son centeroid u = do\n writeArray son u 1\n writeArray centeroid u u\n\n maxs <- forM (graph ! u) $ \\v -> do\n dfs graph fa son centeroid v\n szu <- readArray son u\n szv <- readArray son v\n writeArray son u (szu + szv)\n return (szv, v)\n\n let !maxv = if null maxs then 0\n else snd . Data.List.maximum $ maxs\n\n if maxv /= 0\n then do\n a <- readArray son maxv\n b <- readArray son u\n if a * 2 > b\n then do\n r <- readArray centeroid maxv\n su <- readArray centeroid u\n r' <- goup fa son su r\n writeArray centeroid u r'\n else return ()\n else return ()\n\n goup fa son su now = do\n k <- readArray son now\n if (su - k) * 2 > su\n then goup fa son su (fa ! now) -- go up\n else return now\n"}, {"source_code": "import Control.Monad\n{-import Control.Monad.ST\nimport Data.Array.ST-}\nimport Data.Array\nimport qualified Data.Map as M\n\nmain = interact $ unlines . map show . solve . map read . words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = map (\\i -> fst $ all ! i) queries\n where p = take (n-1) rest\n pa = array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\n{-toG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph-}\n\ntoG n p = array (1, n) $ M.toList $ foldl add g_empty $ [2..] `zip` p\n where g_empty = M.fromList $ [1..n] `zip` (repeat [])\n add m (i, pi) = M.update (\\a -> Just (i:a)) pi m\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (weight, centroid)\n where centroid = if children == [] || (fst fat) * 2 <= weight\n then v\n else lift $ snd fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map fst children)\n lift c = if (weight - (fst (ans ! c))) * 2 <= weight\n then c\n else lift (pa ! c)\n"}, {"source_code": "import Control.Monad\n{-import Control.Monad.ST\nimport Data.Array.ST-}\nimport Data.Array\nimport qualified Data.Map as M\n\nmain = interact $ unlines . map show . solve . map read . words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = map (\\i -> fst $ all ! i) queries\n where p = take (n-1) rest\n pa = array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\n{-toG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph-}\n\ntoG n p = array (1, n) $ M.toList $ foldl add g_empty $ [2..] `zip` p\n where g_empty = M.fromList $ [1..n] `zip` (repeat [])\n add m (i, pi) = M.update (\\a -> Just (i:a)) pi m\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (baricenter, weight)\n where baricenter = if children == [] || (snd fat) * 2 <= weight\n then v\n else lift $ fst fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map snd children)\n lift c = if (weight - (snd (ans ! c))) * 2 <= weight\n then c\n else lift (pa ! c)\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.Array as A\n\nmain = interact $ unlines . map show . solve . map read . words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = map (\\i -> fst $ all ! i) queries\n where p = take (n-1) rest\n pa = A.array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\ntoG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (baricenter, weight)\n where baricenter = if children == [] || (snd fat) * 2 <= weight\n then v\n else lift $ fst fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map snd children)\n lift c = if (weight - (snd (ans ! c))) * 2 <= weight\n then c\n else lift (pa ! c)"}, {"source_code": "import Control.Monad\n{-import Control.Monad.ST\nimport Data.Array.ST-}\nimport Data.Array\nimport qualified Data.Map as M\n\nmain = interact $ unlines . map show . solve . map read . words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = if n < 1000 then map (\\i -> snd $ all ! i) queries else queries\n where p = take (n-1) rest\n pa = array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\n{-toG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph-}\n\ntoG n p = array (1, n) $ M.toList $ foldl add g_empty $ [2..] `zip` p\n where g_empty = M.fromList $ [1..n] `zip` (repeat [])\n add m (i, pi) = M.update (\\a -> Just (i:a)) pi m\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (weight, centroid)\n where centroid = if children == [] || (fst fat) * 2 <= weight\n then v\n else lift $ snd fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map fst children)\n lift c = if (weight - (fst (ans ! c))) * 2 <= weight\n then c\n else lift (pa ! c)\n"}, {"source_code": "import Control.Monad\n{-import Control.Monad.ST\nimport Data.Array.ST-}\nimport Data.Array\nimport qualified Data.Map as M\n\nmain = interact $ unlines . map show . solve . map read . words\n\n\nsolve :: [Int] -> [Int]\nsolve (n:q:rest) = if n < 1000 then map (\\i -> snd $ all ! i) queries else map (\\v->if v==[] then 0 else head v) $ elems graph\n where p = take (n-1) rest\n pa = array (2, n) ([2..] `zip` p)\n queries = take q $ drop (n-1) rest\n graph = toG n p\n all = dfs n graph pa\n\n{-toG n p = runSTArray $ do\n graph <- newArray (1, n) []\n forM_ ([2..] `zip` p) $ \\(i, pi) -> do\n vertices <- readArray graph pi\n writeArray graph pi (i:vertices)\n return graph-}\n\ntoG n p = array (1, n) $ M.toList $ foldl add g_empty $ [2..] `zip` p\n where g_empty = M.fromList $ [1..n] `zip` (repeat [])\n add m (i, pi) = M.update (\\a -> Just (i:a)) pi m\n\ndfs :: Int -> Array Int [Int] -> Array Int Int -> Array Int (Int, Int)\ndfs n graph pa = ans\n where ans = array (1, n) $ [1..] `zip` (map getAns [1..n])\n getAns :: Int -> (Int, Int)\n getAns v = (weight, centroid)\n where centroid = if children == [] || (fst fat) * 2 <= weight\n then v\n else lift $ snd fat\n children = map (\\i -> ans ! i) (graph ! v)\n fat = maximum children\n weight = 1 + (sum $ map fst children)\n lift c = if (weight - (fst (ans ! c))) * 2 <= weight\n then c\n else lift (pa ! c)\n"}], "src_uid": "7f15864d46f09ea6f117929565ccb867"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = do\n [_,m] <- map read.words <$> getLine\n let calc t tt x cost\n | th==0 = cost+m*x\n | otherwise = min (cost+m*x) ((m+th-1)`div`th*cost)\n where\n th = max 0 $ tt-t\n toRoubles :: [Integer] -> [Integer]\n toRoubles (t:tt:x:cost:rest) = calc t tt x cost : toRoubles rest\n toRoubles [] = []\n B.getContents >>= print.sum.toRoubles.map readInteger.B.words\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -fignore-asserts #-}\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngao n [] = 0\ngao n (a:b:x:y:t) = s + r\n where\n c = b - a\n m = (n + c - 1) `div` c\n r = gao n t\n s\n | c <= 0 = x * n + y\n | m == 1 = y\n | otherwise = minimum [x * n + y, m * y, (n - (m - 2) * c) * x + (m - 1) * y]\n\nmain = do\n (n:m:a) <- fmap (map (fromIntegral . fst . fromJust . C.readInt) . C.words) C.getContents\n print $ gao m a\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -fignore-asserts #-}\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngao n [] = 0\ngao n (a:b:x:y:t) = s + r\n where\n c = b - a\n m = (n + c - 1) `div` c\n r = gao n t\n s\n | c <= 0 = x * n + y\n | m == 1 = y\n | otherwise = minimum [x * n + y, m * y, (n - (m - 2) * c) * x + (m - 1) * y]\n\nmain = do\n (n:m:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n print $ gao m a\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = do\n [_,m] <- map read.words <$> getLine\n let calc t tt x cost\n | m<=th = cost\n | th*x<=cost = cost + m*x\n | otherwise = ((m+th-1)`div`th)*cost\n where\n th = max 0 $ tt-t\n toRoubles :: [Integer] -> [Integer]\n toRoubles (t:tt:x:cost:rest) = calc t tt x cost : toRoubles rest\n toRoubles [] = []\n B.getContents >>= print.sum.toRoubles.map readInteger.B.words\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = do\n [_,m] <- map read.words <$> getLine\n let calc t tt x cost\n | th>m = cost\n | th*x < cost = m*x+cost\n | otherwise = q*cost + min cost (r*x)\n where\n th = max 0 $ tt-t\n (q,r) = divMod m th\n toRoubles :: [Integer] -> [Integer]\n toRoubles (t:tt:x:cost:rest) = calc t tt x cost : toRoubles rest\n toRoubles [] = []\n B.getContents >>= print.sum.toRoubles.map readInteger.B.words\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = do\n [_,m] <- map read.words <$> getLine\n let calc t tt x cost\n | th==0 = cost+m*x\n | m<=th = cost\n | (th+r)*x<=cost = cost + m*x\n | otherwise = q*cost\n where\n th = max 0 $ tt-t\n (q,r) = divMod (m+th-1) th\n toRoubles :: [Integer] -> [Integer]\n toRoubles (t:tt:x:cost:rest) = calc t tt x cost : toRoubles rest\n toRoubles [] = []\n B.getContents >>= print.sum.toRoubles.map readInteger.B.words\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = do\n [_,m] <- map read.words <$> getLine\n let calc t tt x cost\n | cost-th*x>=0 = m*x+cost\n | otherwise = ((m+th-1)`div`th)*cost\n where\n th = max 0 $ tt-t\n toRoubles :: [Integer] -> [Integer]\n toRoubles (t:tt:x:cost:rest) = calc t tt x cost : toRoubles rest\n toRoubles [] = []\n B.getContents >>= print.sum.toRoubles.map readInteger.B.words\n"}], "src_uid": "96a3f9d559a40050095de2f5f70b147f"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace, traceM, traceShowM)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> B8.ByteString -> [Int]\r\nsolve n directions = do\r\n -- traceShowM nextRLs\r\n -- traceShowM prevRLs\r\n i <- [0 .. n]\r\n let nextRL = nextRLs UA.! (i + 1)\r\n let prevRL = prevRLs UA.! i\r\n return $ prevRL + 1 + nextRL\r\n where\r\n nextRLs :: UA.UArray Int Int\r\n nextRLs = STA.runSTUArray $ do\r\n dpRL <- STA.newArray (0, n + 1) 0 :: ST.ST s (STA.STUArray s Int Int)\r\n dpLR <- STA.newArray (0, n + 1) 0 :: ST.ST s (STA.STUArray s Int Int)\r\n forM_ (reverse [1 .. n]) $ \\i -> do\r\n nextDpLR <- STA.readArray dpLR (i + 1)\r\n nextDpRL <- STA.readArray dpRL (i + 1)\r\n \r\n let lengthLR = if (directions `B8.index` (i - 1)) == 'L' then 1 + nextDpRL else 0\r\n lengthRL = if (directions `B8.index` (i - 1)) == 'R' then 1 + nextDpLR else 0\r\n\r\n STA.writeArray dpLR i lengthLR\r\n STA.writeArray dpRL i lengthRL\r\n return dpRL\r\n \r\n prevRLs :: UA.UArray Int Int\r\n prevRLs = STA.runSTUArray $ do\r\n dpRL <- STA.newArray (-1, n + 1) 0 :: ST.ST s (STA.STUArray s Int Int)\r\n dpLR <- STA.newArray (-1, n + 1) 0 :: ST.ST s (STA.STUArray s Int Int)\r\n forM_ [1 .. n] $ \\i -> do\r\n prevDpLR <- STA.readArray dpLR (i - 1)\r\n prevDpRL <- STA.readArray dpRL (i - 1)\r\n \r\n let lengthLR = if (directions `B8.index` (i - 1)) == 'R' then 1 + prevDpRL else 0\r\n lengthRL = if (directions `B8.index` (i - 1)) == 'L' then 1 + prevDpLR else 0\r\n\r\n STA.writeArray dpLR i lengthLR\r\n STA.writeArray dpRL i lengthRL\r\n return dpRL\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n n <- B8.getLine <&> readIntB8\r\n directions <- B8.getLine <&> head . B8.words\r\n\r\n let answer = solve n directions\r\n\r\n forM_ answer $ printf \"%d \"\r\n printf \"\\n\"\r\n\r\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n _ <- getLine\n s <- getLine\n let bs = group $ zipWith (\\c i -> (c == 'L') == even i) s [0 :: Integer ..]\n let xs = bs >>= (\\a -> replicate (length a) (length a, head a))\n let cs =\n zipWith3\n ( \\(x1, b1) (x2, b2) i ->\n if even i\n then\n ( if b1 && b2 then 1 else if b1 then 1 + x2 else 1 + x1\n )\n else\n ( if b1 then 1 + x1 else if b2 then 1 + x2 else 1\n )\n )\n (head xs : xs)\n (xs ++ [last xs])\n [0 :: Integer ..]\n putStrLn $ unwords $ show <$> cs\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n s <- readLine\n let\n evens = P.cycle $ P.pack \"RL\"\n evenStops = [i | (i, p) <- zip [0..] $ P.zipWith (/=) evens s, p] ++ [n]\n oddStops = [i | (i, p) <- zip [0..] $ P.zipWith (==) evens s, p] ++ [n]\n step :: Int -> Int -> [Int] -> [(Int, Int)]\n step ix last li@(next:nexts)\n | ix > next = step ix next nexts\n | otherwise = (ix, next-last) : step (ix+2) last li\n step _ _ [] = []\n ans0 = step 0 (-1) evenStops\n ans1 = step 1 (-1) oddStops\n ans = map snd . sort $ ans0 ++ ans1\n lift . P.putStrLn . P.pack . unwords $ map show ans\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n _ <- getLine\n s <- getLine\n let bs = group $ zipWith (\\c i -> (c == 'L') == even i) s [0 :: Integer ..]\n let xs = bs >>= (\\a -> replicate (length a) (length a, head a))\n print xs\n let cs =\n zipWith3\n ( \\(x1, b1) (x2, b2) i ->\n if even i\n then\n ( if b1 && b2 then 1 else if b1 then 1 + x2 else 1 + x1\n )\n else\n ( if b1 then 1 + x1 else if b2 then 1 + x2 else 1\n )\n )\n (head xs : xs)\n (xs ++ [last xs])\n [0 :: Integer ..]\n print cs\n"}], "src_uid": "f51a46e87b8871c3f581786f84e5e6d1"} {"source_code": "import qualified Data.Map as Map\nimport Data.List\nimport Data.Maybe\n\nadj::[String] -> (Char, Int, Int) -> [(Char, Int, Int)]\nadj graph (key, row, col) = filter (\\(xKey, x, _) -> x >= 0 && xKey == key) [\n if col == 0 then ('a', -1, -1) else (getKey row (col - 1), row, col - 1),\n if col == cols - 1 then ('a', -1, -1) else (getKey row (col + 1), row, col + 1),\n if row == 0 then ('a', -1, -1) else (getKey (row - 1) col, row - 1, col),\n if row == rows - 1 then ('a', -1, -1) else (getKey (row + 1) col, row + 1, col)\n ]\n where rows = length graph\n cols = length $ head graph\n getKey r c = (graph !! r) !! c\n\n\ngetNodeKey::Int -> Int -> String\ngetNodeKey r c = show r ++ \"_\" ++ show c\n\nmark::Int -> Int -> Map.Map String Bool -> Map.Map String Bool\nmark r c = Map.insert (getNodeKey r c) True\n\nhasCycle::[String] -> Bool\nhasCycle graph = isJust $ find\n (\n \\(r, row) -> isJust $ find (\\(c, key) -> findCycle graph (key, r, c) (key, r, c) (mark r c marked)) $ zip [0..] row\n ) $ zip [0..] graph\n where marked = Map.empty\n\n\nfindCycle::[String] -> (Char, Int, Int) -> (Char, Int, Int) -> Map.Map String Bool -> Bool\nfindCycle graph current parent marked =\n isJust $ find (\\v@(_, r, c) ->\n if isNothing $ Map.lookup (getNodeKey r c) marked\n then findCycle graph v current (mark r c marked)\n else v /= parent\n ) $ adj graph current\n\n\n\nreadLine = getLine >>= return . words\n\nmain = do\n _ <- readLine\n graph <- getContents >>= return . words\n putStrLn $ id $ if hasCycle graph then \"Yes\" else \"No\"\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, m] <- readLine\n field <- replicateM n getLine\n B.putStrLn . B.pack $ main' n m $ concat field\n\nmain' :: Int -> Int -> String -> String\nmain' n m str = if (dots n m str) then \"Yes\" else \"No\"\n\ndots :: Int -> Int -> String -> Bool\ndots n m str = fst $ foldl check (False, []) [0..length str]\n where\n check (True, _) _ = (True, [])\n check (False, visited) ind\n | ind `elem` visited = (False, visited)\n | otherwise = (fst res, snd res ++ visited)\n where res = dfs ind Nothing [] (n,m, str)\n\ndfs :: Int -> Maybe Int -> [Int] -> (Int, Int, String) -> (Bool, [Int])\ndfs ind prev visited g@(h, w, graph)\n | ind >= length graph = (False, visited)\n | ind `elem` visited = (True, visited)\n | null sub' = (False, ind:visited)\n | otherwise = (or $ fst m', concat $ snd m')\n where\n sub = getSubNodes g ind\n sub' = case prev of\n Nothing -> sub\n Just x -> filter (/= x) sub\n m' = unzip $ map (\\i -> dfs i (Just ind) (ind:visited) g) sub'\n\ngetSubNodes :: (Int, Int, String) -> Int -> [Int]\ngetSubNodes g@(h, w, str) ind\n | i' == 1 = f' [r, t, b]\n | i' == 0 = f' [l, t, b]\n | otherwise = f' [r, l, t, b]\n where\n f' = filter (\\x -> and [x >= 0, x < (length str), str!!x == str!!ind])\n i' = mod (succ ind) w\n r = succ ind\n l = pred ind\n t = ind - w\n b = ind + w"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust, fromMaybe)\nimport Data.Set (member, insert, empty, Set)\nimport Data.Map.Strict (lookup, fromList, toList, (!), Map, keys)\nimport Data.List (concatMap)\nimport Prelude hiding (lookup)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nneighbours :: (Int, Int) -> [(Int, Int)]\nneighbours (x, y) =\n [ (x - 1, y)\n , (x, y - 1)\n , (x + 1, y)\n , (x, y + 1)\n ]\n\ndfs :: Map (Int, Int) Char -> Set (Int, Int) -> (Int, Int) -> Maybe (Int, Int) -> (Bool, Set (Int, Int))\ndfs field visited point prev =\n if member point visited then\n (True, visited)\n else\n let\n getPair k m =\n case lookup k m of\n Just v -> [(k, v)]\n Nothing -> []\n candidates =\n filter (fromMaybe (const True) $ fmap (/=) prev)\n . map fst\n . filter ((== field ! point) . snd)\n . concatMap (flip getPair field)\n . neighbours\n $ point\n folder res@(True, _) _ = res\n folder (_, visited) candidate =\n dfs field visited candidate (Just point)\n in\n foldl folder (False, insert point visited) candidates\n\nreduce :: Map (Int, Int) Char -> Set (Int, Int) -> [(Int, Int)] -> Bool\nreduce field visited [] = False\nreduce field visited (point:points) =\n if member point visited then\n reduce field visited points\n else\n let (res, newVisited) = dfs field visited point Nothing\n in if res then res else reduce field newVisited points\n\nmain = do\n [rows, columns] <- readLine\n field <- sequence (take rows . repeat $ B.getLine >>= return . B.unpack) >>=\n return . fromList . concatMap (\\(x, row) -> zipWith (\\y ch -> ((x, y), ch)) [0..] row) . zip [0..]\n B.putStrLn . B.pack $ if reduce field empty (keys field) then \"Yes\" else \"No\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust, catMaybes, fromMaybe)\nimport Data.Map (Map, lookup, insert, empty, union)\nimport Prelude hiding (lookup)\n-- import Debug.Trace (traceShowId)\n\n\nfolder :: (Bool, Int, Map Int Int, (Char, Int), Map Int Int, [(Char, Int)]) -> (Char, (Char, Int)) -> (Bool, Int, Map Int Int, (Char, Int), Map Int Int, [(Char, Int)])\nfolder all@(res, nextId, mappings, (prevChar, prevGroup), nextMappings, collected) next@(nextChar, (prevLineChar, prevLineGroup)) =\n if res then -- fst . traceShowId $ (res, (all, next)) then\n all\n else\n if prevChar == nextChar then\n if (== prevGroup) . fromMaybe prevLineGroup $ lookup prevLineGroup mappings then\n (True, nextId, mappings, (nextChar, prevGroup), nextMappings, (nextChar, prevGroup):collected)\n else\n if prevChar == prevLineChar then\n let\n prevLineGroupMapping = lookup prevLineGroup mappings\n basePrevLineGroupMapping =\n prevLineGroupMapping >>= flip lookup nextMappings\n finalPrevLineGroupMapping =\n case basePrevLineGroupMapping of\n Just _ -> basePrevLineGroupMapping\n Nothing -> prevLineGroupMapping\n in\n ( False\n , nextId\n , insert prevLineGroup prevGroup mappings\n , (nextChar, prevGroup)\n , case basePrevLineGroupMapping of\n Just x -> insert prevGroup x nextMappings\n _ -> nextMappings\n , (nextChar, prevGroup):collected\n )\n else\n (False, nextId, mappings, (nextChar, prevGroup), nextMappings, (nextChar, prevGroup):collected)\n else\n if prevLineChar == nextChar then\n let new = (nextChar, fromMaybe prevLineGroup $ lookup prevLineGroup mappings)\n in (False, nextId, mappings, new, nextMappings, new:collected)\n else\n (False, nextId + 1, mappings, (nextChar, nextId), nextMappings, (nextChar, nextId):collected)\n\nouterFolder :: (Bool, Int, Map Int Int, [(Char, Int)]) -> [Char] -> (Bool, Int, Map Int Int, [(Char, Int)])\nouterFolder all@(res, nextId, mappings, prevLine) line =\n if res then\n all\n else\n let\n (newRes, newNextId, oldMappings, _, newMappings, newLine) =\n foldl folder (False, nextId, mappings, ('$', -1), empty, []) $ zip line prevLine\n in\n (newRes, newNextId, union newMappings oldMappings, reverse newLine)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [rows, cols] <- readLine\n field <- sequence . take rows $ repeat (B.getLine >>= return . B.unpack)\n B.putStrLn . B.pack $\n case foldl outerFolder (False, 0, empty, take cols $ repeat ('$', -1)) field of\n (True, _, _, _) -> \"Yes\"\n _ -> \"No\"\n \n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n a <- replicateM n getLine\n\n let\n a' = listArray ((1, 1), (n, m)) $ concat a :: Array (Int, Int) Char\n\n f = or $ (flip evalState) Set.empty $ do\n forM ((,) <$> [1..n] <*> [1..m]) $ \\v -> do\n m <- get\n if v `Set.member` m\n then return False\n else search (0, 0) v\n\n adj xy@(x, y) = filter (\\xy'@(x, y) -> elem x [1..n] && elem y [1..m] && a'!xy' == a'!xy) [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n search w u = do\n modify $ Set.insert u\n\n or <$> (forM (adj u) $ \\v -> do\n m <- get\n if v `Set.member` m\n then return $ v /= w\n else search u v)\n\n putStrLn $ if f then \"Yes\" else \"No\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n a <- replicateM n getLine\n\n let\n a' = listArray ((1, 1), (n, m)) $ concat a :: Array (Int, Int) Char\n\n f = or ((flip evalState) Set.empty $ do\n forM ((,) <$> [1..n] <*> [1..m]) $ \\v -> do\n m <- get\n if v `Set.member` m\n then return False\n else search (0, 0) v)\n\n adj xy@(x, y) = filter (\\xy'@(x, y) -> 1 <= x && x <= n && 1 <= y && y <= m && a'!xy' == a'!xy) [(x, y+1), (x, y-1), (x+1, y), (x-1, y)]\n\n search w u = do\n modify $ Set.insert u\n\n or <$> (forM (adj u) $ \\v -> do\n m <- get\n if v `Set.member` m\n then return $ v /= w\n else search u v)\n\n\n putStrLn $ if f then \"Yes\" else \"No\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as Set\nimport Data.List\nimport Data.Maybe\n\nadj::[String] -> Int -> Int -> (Char, Int, Int) -> [(Char, Int, Int)]\nadj graph rows cols (key, row, col) = filter (\\(xKey, x, _) -> x >= 0 && xKey == key) [\n if col == 0 then ('a', -1, -1) else (getKey row (col - 1), row, col - 1),\n if col == cols - 1 then ('a', -1, -1) else (getKey row (col + 1), row, col + 1),\n if row == 0 then ('a', -1, -1) else (getKey (row - 1) col, row - 1, col),\n if row == rows - 1 then ('a', -1, -1) else (getKey (row + 1) col, row + 1, col)\n ]\n where getKey r c = (graph !! r) !! c\n\n\ngetNodeKey::Int -> Int -> String\ngetNodeKey r c = show r ++ \"_\" ++ show c\n\nmark::Int -> Int -> Set.Set String -> Set.Set String\nmark r c = Set.insert (getNodeKey r c)\n\nhasCycle::[String] -> Int -> Int -> Bool\nhasCycle graph rows cols = isJust $ find\n (\n \\(r, row) -> isJust $ find (\\(c, key) -> findCycle graph rows cols (key, r, c) (key, r, c) (mark r c marked)) $ zip [0..] row\n ) $ zip [0..] graph\n where marked = Set.empty\n\n\nfindCycle::[String] -> Int -> Int -> (Char, Int, Int) -> (Char, Int, Int) -> Set.Set String -> Bool\nfindCycle graph rows cols current parent marked =\n isJust $ find (\\v@(_, r, c) ->\n if Set.notMember (getNodeKey r c) marked\n then findCycle graph rows cols v current (mark r c marked)\n else v /= parent\n ) $ adj graph rows cols current\n\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine = B.getLine >>= return . map readInt . B.words\n\nmain = do\n [rows, cols] <- readLine\n graph <- getContents >>= return . words\n putStrLn $ id $ if hasCycle graph rows cols then \"Yes\" else \"No\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as Map\nimport Data.List\nimport Data.Maybe\n\nadj::[String] -> Int -> Int -> (Char, Int, Int) -> [(Char, Int, Int)]\nadj graph rows cols (key, row, col) = filter (\\(xKey, x, _) -> x >= 0 && xKey == key) [\n if col == 0 then ('a', -1, -1) else (getKey row (col - 1), row, col - 1),\n if col == cols - 1 then ('a', -1, -1) else (getKey row (col + 1), row, col + 1),\n if row == 0 then ('a', -1, -1) else (getKey (row - 1) col, row - 1, col),\n if row == rows - 1 then ('a', -1, -1) else (getKey (row + 1) col, row + 1, col)\n ]\n where getKey r c = (graph !! r) !! c\n\n\ngetNodeKey::Int -> Int -> String\ngetNodeKey r c = show r ++ \"_\" ++ show c\n\nmark::Int -> Int -> Map.Map String Bool -> Map.Map String Bool\nmark r c = Map.insert (getNodeKey r c) True\n\nhasCycle::[String] -> Int -> Int -> Bool\nhasCycle graph rows cols = isJust $ find\n (\n \\(r, row) -> isJust $ find (\\(c, key) -> findCycle graph rows cols (key, r, c) (key, r, c) (mark r c marked)) $ zip [0..] row\n ) $ zip [0..] graph\n where marked = Map.empty\n\n\nfindCycle::[String] -> Int -> Int -> (Char, Int, Int) -> (Char, Int, Int) -> Map.Map String Bool -> Bool\nfindCycle graph rows cols current parent marked =\n isJust $ find (\\v@(_, r, c) ->\n if isNothing $ Map.lookup (getNodeKey r c) marked\n then findCycle graph rows cols v current (mark r c marked)\n else v /= parent\n ) $ adj graph rows cols current\n\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine = B.getLine >>= return . map readInt . B.words\n\nmain = do\n [rows, cols] <- readLine\n graph <- getContents >>= return . words\n putStrLn $ id $ if hasCycle graph rows cols then \"Yes\" else \"No\"\n"}], "negative_code": [{"source_code": "import qualified Data.Map as Map\nimport Data.List\nimport Data.Maybe\n\nadj::[String] -> (Int, Char) -> [(Int, Char)]\nadj graph (i, v)\n | i > maxLength - 1 || i < 0 = []\n | otherwise = filter (\\(_, x) -> x == v)\n $ map node\n $ filter (\\x -> x >= 0 && x < maxLength)\n [\n if hasPrev i then i - 1 else -1,\n if hasNext i then i + 1 else -1,\n i - cols,\n i + cols\n ]\n where rows = length graph\n cols = length $ head graph\n maxLength = cols * rows\n hasPrev index = col index > 0\n hasNext index = col index < cols - 1\n row index = floor (fromIntegral index / fromIntegral cols)\n col index = index - cols * row index\n node index = (index, (graph !! row index) !! col index)\n\nhasCycle graph =\n isJust $ find (\\node -> findCycle graph node node (Map.insert (fst node) True marked))\n $ zip [0..] (intercalate \"\" graph)\n where marked = Map.empty\n\n\nfindCycle::[String] -> (Int, Char) -> (Int, Char) -> Map.Map Int Bool -> Bool\nfindCycle graph current parent marked =\n isJust $ find (\\node ->\n if isNothing $ Map.lookup (fst node) marked\n then findCycle graph node current (Map.insert (fst node) True marked)\n else node /= parent\n ) $ adj graph current\n\n\nreadLine = getLine >>= return . words\n\nmain = do\n _ <- readLine\n graph <- getContents >>= return . words\n print $ if hasCycle graph then \"Yes\" else \"No\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as Set\nimport Data.List\nimport Data.Maybe\n\nadj::[String] -> Int -> Int -> (Char, Int, Int) -> [(Char, Int, Int)]\nadj graph rows cols (key, row, col) = filter (\\(xKey, x, _) -> x >= 0 && xKey == key) [\n if col == 0 then ('a', -1, -1) else (getKey row (col - 1), row, col - 1),\n if col == cols - 1 then ('a', -1, -1) else (getKey row (col + 1), row, col + 1),\n if row == 0 then ('a', -1, -1) else (getKey (row - 1) col, row - 1, col),\n if row == rows - 1 then ('a', -1, -1) else (getKey (row + 1) col, row + 1, col)\n ]\n where getKey r c = (graph !! r) !! c\n\n\ngetNodeKey::Int -> Int -> String\ngetNodeKey r c = show r ++ \"_\" ++ show c\n\nmark::Int -> Int -> Set.Set String -> Set.Set String\nmark r c = Set.insert (getNodeKey r c)\n\nhasCycle::[String] -> Int -> Int -> Bool\nhasCycle graph rows cols = isJust $ find\n (\n \\(r, row) -> isJust $ find (\\(c, key) -> findCycle graph rows cols (key, r, c) (key, r, c) (mark r c marked)) $ zip [0..] row\n ) $ zip [0..] graph\n where marked = Set.empty\n\n\nfindCycle::[String] -> Int -> Int -> (Char, Int, Int) -> (Char, Int, Int) -> Set.Set String -> Bool\nfindCycle graph rows cols current parent marked =\n isJust $ find (\\v@(_, r, c) ->\n if Set.member (getNodeKey r c) marked\n then findCycle graph rows cols v current (mark r c marked)\n else v /= parent\n ) $ adj graph rows cols current\n\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine = B.getLine >>= return . map readInt . B.words\n\nmain = do\n [rows, cols] <- readLine\n graph <- getContents >>= return . words\n putStrLn $ id $ if hasCycle graph rows cols then \"Yes\" else \"No\"\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, m] <- readLine\n field <- replicateM n getLine\n B.putStrLn . B.pack $ main' n m $ concat field\n\nmain' :: Int -> Int -> String -> String\nmain' n m str = if (dots n m str) then \"Yes\" else \"No\"\n\ndots :: Int -> Int -> String -> Bool\ndots n m str = any (\\ind -> dfs ind Nothing [] (n,m, str)) [1..length str]\n\ndfs :: Int -> Maybe Int -> [Int] -> (Int, Int, String) -> Bool\ndfs ind prevInd visitedInd g@(w, h, graph)\n | ind >= length graph = False\n | ind `elem` visitedInd = True\n | null sub' = False\n | otherwise = or $ map (\\i -> dfs i (Just ind) (ind:visitedInd) g) sub'\n where\n sub = getSubNodes g ind\n sub' = case prevInd of\n Nothing -> sub\n Just x -> filter (/= x) sub\n\ngetSubNodes :: (Int, Int, String) -> Int -> [Int]\ngetSubNodes g@(w, h, str) ind\n | i' == 1 = f' [r, t, b]\n | i' == 0 = f' [l, t, b]\n | otherwise = f' [r, l, t, b]\n where\n f' = filter (\\x -> str!!x == str!!ind) . filter (\\x -> and [x /= ind, x >= 0, x < (length str)])\n i' = mod (succ ind) w\n r = succ ind\n l = pred ind\n t = ind - w\n b = ind + w\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nimport Data.List (sortBy)\nimport Data.Function (on)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [n, m] <- readLine\n field <- getContents\n B.putStrLn . B.pack $ main' n m $ field\n\nmain' :: Int -> Int -> String -> String\nmain' n m str = if (dots n m str) then \"Yes\" else \"No\"\n\ndots :: Int -> Int -> String -> Bool\ndots n m str = any (\\ind -> dfs ind Nothing [] (n,m, str)) [1..length str]\n\ndfs :: Int -> Maybe Int -> [Int] -> (Int, Int, String) -> Bool\ndfs ind prevInd visitedInd g@(w, h, graph)\n | ind >= length graph = False\n | ind `elem` visitedInd = True\n | null sub' = False\n | otherwise = or $ map (\\i -> dfs i (Just ind) (ind:visitedInd) g) sub'\n where\n sub = getSubNodes g ind\n sub' = case prevInd of\n Nothing -> sub\n Just x -> filter (/= x) sub\n\ngetSubNodes :: (Int, Int, String) -> Int -> [Int]\ngetSubNodes g@(w, h, str) ind\n | i' == 1 = f' [r, t, b]\n | i' == 0 = f' [l, t, b]\n | otherwise = f' [r, l, t, b]\n where\n f' = filter (\\x -> str!!x == str!!ind) . filter (\\x -> and [x /= ind, x >= 0, x < (length str)])\n i' = mod (succ ind) w\n r = succ ind\n l = pred ind\n t = ind - w\n b = ind + w\n"}], "src_uid": "73930603e440eef854da4ba51253a5a7"} {"source_code": "import Data.List\nmain=interact$show.length.takeWhile((==1).length.group).transpose.tail.lines", "positive_code": [{"source_code": "diff :: String -> String -> Int\ndiff [] [] = 0\ndiff as bs | head as == head bs = 1 + diff (tail as) (tail bs)\n | otherwise = 0\n\ndafuq x = do\n let c = tail $lines x\n show.minimum.map (diff (head c)) $c\n\nmain = interact dafuq\n"}, {"source_code": "main = do getContents >>= print . length . takeWhile (/='*') . foldl1 (zipWith (\\i j -> if i == j then i else '*')) . tail . lines\n"}, {"source_code": "import Data.List\ncommonPrefix :: [String] -> Int\ncommonPrefix = length . commonPart\n where commonPart = foldl1' step \n where step acc x = map fst . takeWhile (\\(i,j) -> i == j) . zip acc $ x\n \nmain = interact $ show . commonPrefix . tail . lines"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\nimport System.IO.Error\n\n\nhReadMany :: (Char -> Bool) -> Handle -> IO String\nhReadMany p h = do b <- (p <$> hLookAhead h) `catch` const (return False)\n if b\n then (:) <$> hGetChar h <*> hReadMany p h\n else return \"\"\n\nhSkipSpaces = hReadMany isSpace\nhReadNumeric = hReadMany (\\c -> isDigit c || c `elem` ['.', '-', '+'])\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = do hSkipSpaces stdin\n read <$> hReadNumeric stdin\n\nreadTerm :: IO String\nreadTerm = do hSkipSpaces stdin\n hReadMany (not . isSpace) stdin\n\n\nhoge 'R' = 0\nhoge 'P' = 1\nhoge 'S' = 2\n\nwins x y | a == b = False\n | (a - b) `mod` 3 == 1 = True\n | otherwise = False\n where\n (a, b) = (hoge x, hoge y)\n\nplay m ns ps = play' m 0 0 ns ps\n where\n play' 0 a b _ _ = (a, b)\n play' x a b (n:ns) (p:ps) | wins n p = play' (x - 1) a (b+1) ns ps\n | wins p n = play' (x - 1) (a + 1) b ns ps\n | otherwise = play' (x - 1) a b ns ps\n\nlongest as bs = longest' [] as bs\n where\n longest' stack (x:xs) (y:ys) | x == y = longest' (x:stack) xs ys\n longest' stack _ _ = reverse stack\n\nloop _ [] = return 0\nloop 0 lst = return $ length lst\nloop n lst = do s <- readTerm\n let l = longest lst s\n loop (n - 1) l\n\nmain = do n <- readNum\n s <- readTerm\n l <- loop (n - 1) s\n print $ l"}, {"source_code": "main = do\n numbers <- fmap (tail . lines) getContents\n print $ length $ foldl1 commonPrefix numbers\n where\n commonPrefix _ \"\" = \"\"\n commonPrefix \"\" _ = \"\"\n commonPrefix (x:xs) (y:ys) = if x == y then x:commonPrefix xs ys else \"\"\n"}, {"source_code": "import qualified Data.List as L\nmain = interact $ show . solve . tail . words\nsolve s = length . takeWhile (\\xs -> all (== head xs) xs) . L.transpose $ s\n"}, {"source_code": "calc2 (x:a) (y:b)\n | x == y = (x:calc2 a b)\n | otherwise = []\ncalc2 _ _ = []\n\nmain = do\n contents <- getContents \n print $ length $ foldl1 calc2 (tail $ lines contents)\n"}, {"source_code": "calc2 :: Eq a => [a] -> [a] -> [a]\ncalc2 (x:a) (y:b)\n | x == y = (x:calc2 a b)\n | otherwise = []\ncalc2 _ _ = []\n\ncalcn (x:y:xs) = calcn z\n where\n z = [calc2 x y] ++ xs\ncalcn (x:[]) = x\n\nmain = do\n contents <- getContents \n print $ length $ calcn $ tail $ lines contents\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve :: [String] -> Int\nsolve d = if all ((d !! 0 !! 0 : []) `isPrefixOf`) d\n then 1 + (solve $ map (drop 1) d)\n else 0\n\nmain :: IO ()\nmain = do\n n <- getLine\n d <- words <$> getContents\n print $ solve d"}, {"source_code": "\ngetPrefix :: String -> String -> String\ngetPrefix [] _ = []\ngetPrefix _ [] = []\ngetPrefix (c1:s1) (c2:s2)\n | c1 == c2 = c1 : getPrefix s1 s2\n | otherwise = [] \n\nmain :: IO ()\nmain = do\n n <- readLn\n lines <- mapM (const getLine) [1..n]\n print $ length (foldl1 getPrefix lines)\n "}, {"source_code": "import System.IO\n\nreadInputLoop :: Int -> IO [String]\nreadInputLoop 0 = do \n return []\n\nreadInputLoop n = do\n h <- getLine\n t <- readInputLoop (n - 1)\n return $ h:t\n \n\nreadInput :: IO [String]\nreadInput = do\n n_str <- getLine\n readInputLoop (read n_str::Int)\n\n-- I don't care about tail recursion\nlcp :: [String] -> Int\nlcp list | any null list = 0\n | any (\\str -> ((head str) /= head (head list))) list = 0\n | otherwise = 1 + (lcp $ map (drop 1) list)\n\nmain :: IO()\nmain = do\n x <- readInput\n putStrLn $ show $ lcp x\n"}, {"source_code": "main = print . length . foldr1 commonPrefix . tail . lines =<< getContents\ncommonPrefix (a:as) (b:bs) | a == b = a : commonPrefix as bs\ncommonPrefix _ _ = []"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n n <- fmap read getLine\n s <- forM [1..n] (\\_ -> getLine)\n print $ solve s 0\nsolve :: [String] -> Integer -> Integer\nsolve s n = if allEq $ map (genericTake $ n+1) s then solve s $ n+1 else n\nallEq :: [String] -> Bool\nallEq [] = True\nallEq [x] = True\nallEq (x:y:ys) = x == y && allEq (y:ys)\n"}, {"source_code": "import Data.Functor\n\nallEqual :: Eq a => [a] -> Bool\nallEqual l = all (== head l) l\n\n\n-- | Find longest common prefix size for strings of equal length.\nprefixLen :: [String] -> Int\nprefixLen species@(s:_) =\n let \n prefixes = map head species\n in\n if (length s /= 0) && (allEqual prefixes) then\n 1 + (prefixLen $ map tail species)\n else 0\n\nmain :: IO ()\nmain = do\n -- read n (assume n \u2265 2)\n _ <- getLine\n numbers <- lines <$> getContents\n print $ prefixLen numbers\n"}, {"source_code": "import Data.List\nsolve = length . takeWhile (((==) 1) . length . group) . transpose \nparse = tail . lines\nmain = interact (show . solve . parse)"}], "negative_code": [], "src_uid": "081b35620952bd32ce6d8ddc756e5c9d"} {"source_code": "main = getContents >>= print.p. map (\\x -> (map (\\y -> read y :: Integer)).words $x).lines \n\twhere\n\t\tp [[x1, y1, r1], [x2, y2, r2]] \n\t\t | r1^2 < d && r2^2 < d && (r1 + r2)^2 >= d = 0\n\t\t | (r1 + r2)^2 < d = (sqrt(fromIntegral d) - (fromIntegral r1) - (fromIntegral r2))/2.0 \n\t\t | (r1 + r2)^2 >= d && (r1 - r2)^2 <= d = 0\n\t\t | True = (rr1 - dd - rr2)/2.0\n\t\t | otherwise = error \"out of bound\"\n\t\t where\n\t\t \trr1 = fromIntegral $ max r1 r2\n\t\t\trr2 = fromIntegral $ min r1 r2\n\t\t\td = (x1 - x2)^2 + (y1 - y2)^2\n\t\t\tdd = sqrt $ fromIntegral d\n", "positive_code": [{"source_code": "\n\ninside (p0, r0) (p1, r1) = \n abs $ (big - d - small) / 2\n where\n big = max r1 r0\n small = min r1 r0\n d = dist p0 p1\n\noutside (p0, r0) (p1, r1) = \n (/ 2) . abs $ (dist p0 p1) - r0 - r1\n\n\nsolve :: [[Double]] -> Double\nsolve [[x0, y0, r0], [x1, y1, r1]]\n | d > r0 + r1 = outside (p0, r0) (p1, r1)\n | d <= r0 + r1 && d + small >= big = 0\n | d + small < big = inside (p0, r0) (p1, r1)\n where \n small = min r0 r1\n big = max r0 r1\n d = dist (x0, y0) (x1, y1)\n p0 = (x0, y0)\n p1 = (x1, y1)\n\ndist (a, b) (c, d) = sqrt $ (a - c) ^ 2 + (b - d) ^ 2\n\n\nparse :: String -> [[Double]]\nparse = map ((map read) . words) . lines\n\nmain = (print . solve . parse =<< getContents)"}, {"source_code": "\n{-\nimport HUnit\n\neps = 1e-06\n\ntestZero = Test \"TestZero\" $\n assertApproximate 0.0 (solve (0,0,1) (2,0,1)) eps\n\ntestInput1 = Test \"TestInput1\" $\n assertApproximate 1.0 (solve (0,0,1) (6,0,3)) eps\n\ntestInput2 = Test \"TestInput2\" $\n assertApproximate 11.142135623730951 (solve (-10,10,3) (10,-10,3)) eps\n\ntestInside = Test \"TestInside\" $\n assertApproximate 1.0 (solve (0,0,1) (0,0,3)) eps\n\ntestIntersect = Test \"TestIntersect\" $\n assertApproximate 0.0 (solve (0,0,1) (0,1,1)) eps\n\ntest = mapM_ run\n [\n testZero,\n testInput1,\n testInput2,\n testInside,\n testIntersect\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: (Double, Double, Double) -> (Double, Double, Double) -> Double\nsolve (x1, y1, r1) (x2, y2, r2)\n | d > r1 + r2 = 0.5 * (d - (r1 + r2))\n | d < max r1 r2 - min r1 r2 = 0.5 * (max r1 r2 - d - min r1 r2)\n | otherwise = 0\n where\n d = sqrt ((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1))\n\nmain :: IO ()\nmain = do\n [[x1, y1, r1], [x2, y2, r2]] <- mapM (const (getLine >>= return . map read . words)) [1,2]\n print $ solve (x1,y1,r1) (x2,y2,r2)\n"}, {"source_code": "import System.IO\nimport Text.Printf\ndata Point = Point Double Double deriving (Show)\ndata Circle = Circle Point Double deriving (Show)\n\ndistance :: Point -> Point -> Double\ndistance ( Point x1 y1 ) (Point x2 y2) = sqrt $ (x1-x2)^2+(y1-y2)^2\nr120d2b :: Circle -> Circle -> Double\nr120d2b ( Circle ( Point x1 y1 ) r1 ) ( Circle ( Point x2 y2 ) r2)\n | d > rplusr = ( d - rplusr ) / 2\n | d < rminusr = ( abs(r2-r1) - d) / 2\n | otherwise = 0 \n where rminusr = (max r2 r1) - ( min r2 r1) \n rplusr = r2 + r1\n d = distance (Point x1 y1 ) ( Point x2 y2)\n\nmakePoint :: Double -> Double -> Point\nmakePoint a b = (Point a b )\nmakeCircle :: Point -> Double -> Circle\nmakeCircle (Point a b ) c = (Circle (Point a b ) c )\n\nrDouble :: String -> Double\nrDouble = read\n\nmain = do \n line <- getLine\n let b = (map rDouble ) ( words line) \n let c1 = makeCircle ( makePoint ( b !! 0 ) (b !! 1) ) ( b !! 2)\n line <- getLine\n let b = (map rDouble ) ( words line) \n let c2 = makeCircle ( makePoint ( b !! 0 ) (b !! 1) ) ( b !! 2)\n printf \"%0.8f\\n\" (r120d2b c1 c2 )"}], "negative_code": [{"source_code": "main = getContents >>= print.p. map (\\x -> (map (\\y -> read y :: Double)).words $x).lines \n\twhere\n\t\tp [[x1, y1, r1], [x2, y2, r2]] = if (r1 + r2) ^ 2 >= (x1-x2)^2 + (y1-y2) ^2 then 0 else if r1 + r2 <= d then (d-r1-r2)/2 else 0\n\t\t\twhere\n\t\t\t\td = (sqrt $ ((x1 - x2)^2 + (y1 - y2)^2)) \n"}, {"source_code": "\n\ninside (p0, r0) (p1, r1) =\n abs $ (big - d - small) / 2\n where\n big = max r1 r0\n small = min r1 r0\n d = dist p0 p1\n\noutside (p0, r0) (p1, r1) = \n (/ 2) . abs $ (dist p0 p1) - r0 - r1\n\nintersect (p0, r0) (p1, r1) = \n abs $ (r1 + r0 - (dist p0 p1)) / 2\n\n\nsolve :: [[Double]] -> Double\nsolve [[x0, y0, r0], [x1, y1, r1]]\n | d > r0 + r1 = outside (p0, r0) (p1, r1)\n | d < max r0 r1 = inside (p0, r0) (p1, r1)\n | otherwise = intersect (p0, r0) (p1, r1)\n where \n d = dist (x0, y0) (x1, y1)\n p0 = (x0, y0)\n p1 = (x1, y1)\n\ndist (a, b) (c, d) = sqrt $ (a - c) ^ 2 + (b - d) ^ 2\n\n\nparse :: String -> [[Double]]\nparse = map ((map read) . words) . lines\n\nmain = (print . solve . parse =<< getContents)"}, {"source_code": "\n\ninside (p0, r0) (p1, r1) =\n abs $ (big - d - small) / 2\n where\n big = max r1 r0\n small = min r1 r0\n d = dist p0 p1\n\noutside (p0, r0) (p1, r1) = \n abs $ (dist p0 p1) - r0 - r1\n\nintersect (p0, r0) (p1, r1) =\n abs $ (r1 + r0 - (dist p0 p1)) / 2\n\n\nsolve :: [[Double]] -> Double\nsolve [[x0, y0, r0], [x1, y1, r1]]\n | d < r0 + r1 = outside (p0, r0) (p1, r1)\n | d < max r0 r1 = inside (p0, r0) (p1, r1)\n | otherwise = intersect (p0, r0) (p1, r1)\n where \n d = dist (x0, y0) (x1, y1)\n p0 = (x0, y0)\n p1 = (x1, y1)\n\ndist (a, b) (c, d) = sqrt $ (a - c) ^ 2 + (b - d) ^ 2\n\n\nparse :: String -> [[Double]]\nparse = map ((map read) . words) . lines\n\nmain = (print . solve . parse =<< getContents)"}], "src_uid": "8996ae454ba3062e47a8aaab7fb1e33b"} {"source_code": "main = interact $ z.y.f.read\n\ny ans = map (\\x -> (map show x)) ans\nz ans = unlines (map (\\x -> unwords x) ans)\n\nev = [2, 4 ..]\nod = [1, 3 ..]\nf :: Int -> [[Int]]\nf x = (g x x ev od (x `div` 2) 1 [])\n\ng :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> [[Int]] -> [[Int]]\ng n 0 tempe tempo st md ans = ans\ng n rw tempe tempo st md ans\n | rw > ((n `div` 2) + 1) = g n\n (rw-1)\n (drop (2*st) tempe)\n (drop md tempo)\n (st-1)\n (md+2)\n (((take st tempe) ++ (take md tempo) ++ (take st (drop st tempe))):ans)\n | otherwise = g n\n (rw-1)\n (drop (2*st) tempe)\n (drop md tempo)\n (st+1)\n (md-2)\n (((take st tempe) ++ (take md tempo) ++ (take st (drop st tempe))):ans)\n", "positive_code": [{"source_code": "import Data.List (intercalate)\n\nmaxLineLength :: (Int -> Int) -> Int -> Int -> Int\nmaxLineLength f from to = maximum (map (intLen . f) [from .. to])\n\nmaxLineLengthShort :: (Int -> Int) -> Int -> Int\nmaxLineLengthShort f size = maxLineLength f 0 $ size - 1\n\npadToLengthLeft :: a -> [a] -> Int -> [a]\npadToLengthLeft padding list n = (replicate (n - length list) padding) ++ list\n\nintLen :: Int -> Int\nintLen val = (length . show) val\n\n\nmakeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\nmakeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> padToLengthLeft ' ' (show (f x)) (mdf x)) [x1..x2]\n\n--makeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\n--makeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> show (f x)) [x1..x2]\n\nmakeMatrString :: (Int -> Int -> Int) -> Int -> Int -> Int -> Int -> String\nmakeMatrString f x1 x2 y1 y2 = intercalate \"\\n\" $ map (\\y -> makeLineString (\\x -> f x y) (\\x -> maxLineLength (f x) y1 y2) x1 x2) [y1..y2]\n\nmakeMatrStringShort :: (Int -> Int -> Int) -> Int -> Int -> String\nmakeMatrStringShort f width height = makeMatrString f 0 (width - 1) 0 (height - 1)\n\nmagisquareodd :: Int -> Int -> Int -> Int\nmagisquareodd size x y\n\t| size `mod` 2 == 0 = -1 -- fuck this is not odd\n\t| otherwise = magisquareoddhelp size x y 1\n\n\nmagisquareoddhelp :: Int -> Int -> Int -> Int -> Int\nmagisquareoddhelp size x y start\n\t| size == 1 = start -- the square of size 1 is trivial\n\t| x > 0 && y > 0 = magisquareoddhelp (size - 1) (x - 1) (y - 1) (start + 2 * size - 1) \n\t| x == 0 && y == 0 = start\n\t| x > 0 = start + x * 2 + md - 1\n\t| y > 0 = start + y * 2 - md\n\twhere \tmd = size `mod` 2\n\n\n\nmagisquareoddn :: Int -> Int -> Int -> Int\nmagisquareoddn size x y \n\t| size `mod` 2 == 0 = -1 -- undefied for even square\n\t| size == 1 = 1 -- the one in center\n\t| x > 0 && x < (size - 1) && y > 0 && y < (size - 1) = magisquareoddn (size - 2) (x - 1) (y - 1)\n\t| x == 0 && y == 0 = startInd + 1 -- even values in corners\n\t| x == 0 && y == (size - 1) = startInd + 3\n\t| x == (size - 1) && y == 0 = startInd + 5\n\t| x == (size - 1) && y == (size - 1) = startInd + 7\n\t| y == 0 = startInd + x * 2\n\t| y == (size - 1) = startInd + x * 2 + (size - 2) * 2\n\t| x == 0 && y < (size - 2) = startInd + 7 + y * 2\n\t| x == 0 && y == (size - 2) = startInd + (size - 2) * 4 + 2\n\t| x == (size - 1) && y < (size - 2) = startInd + 7 + (y - 1) * 2 + (size - 2) * 2\n\t| x == (size - 1) && y == (size - 2) = startInd + (size - 2) * 4 + 4\n\twhere \tstartInd = (size - 2) * (size - 2) \n\t\t\n\nmain :: IO()\nmain = do\n firstVals <- fmap (map read . words) getLine :: IO [Int]\n let size = firstVals !! 0\t\n\tputStrLn $ makeMatrStringShort (magisquareoddn size) size size\n\t--print foldl [magisquareodd size x 0 | x <- [0 .. size - 1]] \n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "import Data.List (intercalate)\n\nmaxLineLength :: (Int -> Int) -> Int -> Int -> Int\nmaxLineLength f from to = maximum (map (intLen . f) [from .. to])\n\nmaxLineLengthShort :: (Int -> Int) -> Int -> Int\nmaxLineLengthShort f size = maxLineLength f 0 $ size - 1\n\npadToLengthLeft :: a -> [a] -> Int -> [a]\npadToLengthLeft padding list n = (replicate (n - length list) padding) ++ list\n\nintLen :: Int -> Int\nintLen val = (length . show) val\n\nmakeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\nmakeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> show (f x)) [x1..x2]\n\nmakeMatrString :: (Int -> Int -> Int) -> Int -> Int -> Int -> Int -> String\nmakeMatrString f x1 x2 y1 y2 = intercalate \"\\n\" $ map (\\y -> makeLineString (\\x -> f x y) (\\x -> maxLineLength (f x) y1 y2) x1 x2) [y1..y2]\n\nmakeMatrStringShort :: (Int -> Int -> Int) -> Int -> Int -> String\nmakeMatrStringShort f width height = makeMatrString f 0 (width - 1) 0 (height - 1)\n\nmagisquareodd :: Int -> Int -> Int -> Int\nmagisquareodd size x y\n\t| size `mod` 2 == 0 = -1 -- fuck this is not odd\n\t| otherwise = magisquareoddhelp size x y 1\n\n\nmagisquareoddhelp :: Int -> Int -> Int -> Int -> Int\nmagisquareoddhelp size x y start\n\t| size == 1 = start -- the square of size 1 is trivial\n\t| x > 0 && y > 0 = magisquareoddhelp (size - 1) (x - 1) (y - 1) (start + 2 * size - 1) \n\t| x == 0 && y == 0 = start\n\t| x > 0 = start + x * 2 + md - 1\n\t| y > 0 = start + y * 2 - md\n\twhere \tmd = size `mod` 2\n\nmain :: IO()\nmain = do\n firstVals <- fmap (map read . words) getLine :: IO [Int]\n let size = firstVals !! 0\n\tputStrLn $ makeMatrStringShort (magisquareodd size) size size\n\n\n\n\n\n\n\n"}, {"source_code": "import Data.List (intercalate)\n\nmaxLineLength :: (Int -> Int) -> Int -> Int -> Int\nmaxLineLength f from to = maximum (map (intLen . f) [from .. to])\n\nmaxLineLengthShort :: (Int -> Int) -> Int -> Int\nmaxLineLengthShort f size = maxLineLength f 0 $ size - 1\n\npadToLengthLeft :: a -> [a] -> Int -> [a]\npadToLengthLeft padding list n = (replicate (n - length list) padding) ++ list\n\nintLen :: Int -> Int\nintLen val = (length . show) val\n\n\nmakeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\nmakeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> padToLengthLeft ' ' (show (f x)) (mdf x)) [x1..x2]\n\n--makeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\n--makeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> show (f x)) [x1..x2]\n\nmakeMatrString :: (Int -> Int -> Int) -> Int -> Int -> Int -> Int -> String\nmakeMatrString f x1 x2 y1 y2 = intercalate \"\\n\" $ map (\\y -> makeLineString (\\x -> f x y) (\\x -> maxLineLength (f x) y1 y2) x1 x2) [y1..y2]\n\nmakeMatrStringShort :: (Int -> Int -> Int) -> Int -> Int -> String\nmakeMatrStringShort f width height = makeMatrString f 0 (width - 1) 0 (height - 1)\n\nmagisquareodd :: Int -> Int -> Int -> Int\nmagisquareodd size x y\n\t| size `mod` 2 == 0 = -1 -- fuck this is not odd\n\t| otherwise = magisquareoddhelp size x y 1\n\n\nmagisquareoddhelp :: Int -> Int -> Int -> Int -> Int\nmagisquareoddhelp size x y start\n\t| size == 1 = start -- the square of size 1 is trivial\n\t| x > 0 && y > 0 = magisquareoddhelp (size - 1) (x - 1) (y - 1) (start + 2 * size - 1) \n\t| x == 0 && y == 0 = start\n\t| x > 0 = start + x * 2 + md - 1\n\t| y > 0 = start + y * 2 - md\n\twhere \tmd = size `mod` 2\n\n\n\nmagisquareoddn :: Int -> Int -> Int -> Int\nmagisquareoddn size x y \n\t| size `mod` 2 == 0 = -1 -- undefied for even square\n\t| size == 1 = 1 -- the one in center\n\t| x > 0 && x < (size - 1) && y > 0 && y < (size - 1) = magisquareoddn (size - 2) (x - 1) (y - 1)\n\t| x == 0 && y == 0 = startInd + 1 -- even values in corners\n\t| x == 0 && y == (size - 1) = startInd + 3\n\t| x == (size - 1) && y == 0 = startInd + 5\n\t| x == (size - 1) && y == (size - 1) = startInd + 7\n\t| y == 0 = startInd + x * 2\n\t| y == (size - 1) = startInd + x * 2 + (size - 2) * 2\n\t| x == 0 && y < (size - 2) = startInd + 7 + (y - 1) * 2\n\t| x == 0 && y == (size - 2) = startInd + (size - 2) * 4 + 2\n\t| x == (size - 1) && y < (size - 2) = startInd + 7 + (y - 1) * 2 + (size - 2) * 2\n\t| x == (size - 1) && y == (size - 2) = startInd + (size - 2) * 4 + 4\n\twhere \tstartInd = (size - 2) * (size - 2) \n\t\t\n\nmain :: IO()\nmain = do\n firstVals <- fmap (map read . words) getLine :: IO [Int]\n let size = firstVals !! 0\t\n\tputStrLn $ makeMatrStringShort (magisquareoddn size) size size\n\t--print foldl [magisquareodd size x 0 | x <- [0 .. size - 1]] \n\n\n\n\n\n\n"}, {"source_code": "import Data.List (intercalate)\n\nmaxLineLength :: (Int -> Int) -> Int -> Int -> Int\nmaxLineLength f from to = maximum (map (intLen . f) [from .. to])\n\nmaxLineLengthShort :: (Int -> Int) -> Int -> Int\nmaxLineLengthShort f size = maxLineLength f 0 $ size - 1\n\npadToLengthLeft :: a -> [a] -> Int -> [a]\npadToLengthLeft padding list n = (replicate (n - length list) padding) ++ list\n\nintLen :: Int -> Int\nintLen val = (length . show) val\n\n\n--makeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\n--makeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> padToLengthLeft ' ' (show (f x)) (mdf x)) [x1..x2]\n\nmakeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\nmakeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> show (f x)) [x1..x2]\n\nmakeMatrString :: (Int -> Int -> Int) -> Int -> Int -> Int -> Int -> String\nmakeMatrString f x1 x2 y1 y2 = intercalate \"\\n\" $ map (\\y -> makeLineString (\\x -> f x y) (\\x -> maxLineLength (f x) y1 y2) x1 x2) [y1..y2]\n\nmakeMatrStringShort :: (Int -> Int -> Int) -> Int -> Int -> String\nmakeMatrStringShort f width height = makeMatrString f 0 (width - 1) 0 (height - 1)\n\nmagisquareodd :: Int -> Int -> Int -> Int\nmagisquareodd size x y\n\t| size `mod` 2 == 0 = -1 -- fuck this is not odd\n\t| otherwise = magisquareoddhelp size x y 1\n\n\nmagisquareoddhelp :: Int -> Int -> Int -> Int -> Int\nmagisquareoddhelp size x y start\n\t| size == 1 = start -- the square of size 1 is trivial\n\t| x > 0 && y > 0 = magisquareoddhelp (size - 1) (x - 1) (y - 1) (start + 2 * size - 1) \n\t| x == 0 && y == 0 = start\n\t| x > 0 = start + x * 2 + md - 1\n\t| y > 0 = start + y * 2 - md\n\twhere \tmd = size `mod` 2\n\n\n\nmagisquareoddn :: Int -> Int -> Int -> Int\nmagisquareoddn size x y \n\t| size `mod` 2 == 0 = -1 -- undefied for even square\n\t| size == 1 = 1 -- the one in center\n\t| x > 0 && x < (size - 1) && y > 0 && y < (size - 1) = magisquareoddn (size - 2) (x - 1) (y - 1)\n\t| x == 0 && y == 0 = startInd + 1 -- even values in corners\n\t| x == 0 && y == (size - 1) = startInd + 3\n\t| x == (size - 1) && y == 0 = startInd + 5\n\t| x == (size - 1) && y == (size - 1) = startInd + 7\n\t| y == 0 = startInd + x * 2\n\t| y == (size - 1) = startInd + x * 2 + (size - 2) * 2\n\t| x == 0 && y < (size - 2) = startInd + 7 + (y - 1) * 2\n\t| x == 0 && y == (size - 2) = startInd + (size - 2) * 4 + 2\n\t| x == (size - 1) && y < (size - 2) = startInd + 7 + (y - 1) * 2 + (size - 2) * 2\n\t| x == (size - 1) && y == (size - 2) = startInd + (size - 2) * 4 + 4\n\twhere \tstartInd = (size - 2) * (size - 2) \n\t\t\n\nmain :: IO()\nmain = do\n firstVals <- fmap (map read . words) getLine :: IO [Int]\n let size = firstVals !! 0\t\n\tputStrLn $ makeMatrStringShort (magisquareoddn size) size size\n\t--print foldl [magisquareodd size x 0 | x <- [0 .. size - 1]] \n\n\n\n\n\n\n"}, {"source_code": "import Data.List (intercalate)\n\nmaxLineLength :: (Int -> Int) -> Int -> Int -> Int\nmaxLineLength f from to = maximum (map (intLen . f) [from .. to])\n\nmaxLineLengthShort :: (Int -> Int) -> Int -> Int\nmaxLineLengthShort f size = maxLineLength f 0 $ size - 1\n\npadToLengthLeft :: a -> [a] -> Int -> [a]\npadToLengthLeft padding list n = (replicate (n - length list) padding) ++ list\n\nintLen :: Int -> Int\nintLen val = (length . show) val\n\nmakeLineString :: (Int -> Int) -> (Int -> Int) -> Int -> Int -> String\nmakeLineString f mdf x1 x2 = intercalate \" \" $ map (\\x -> padToLengthLeft ' ' (show (f x)) (mdf x)) [x1..x2]\n\nmakeMatrString :: (Int -> Int -> Int) -> Int -> Int -> Int -> Int -> String\nmakeMatrString f x1 x2 y1 y2 = intercalate \"\\n\" $ map (\\y -> makeLineString (\\x -> f x y) (\\x -> maxLineLength (f x) y1 y2) x1 x2) [y1..y2]\n\nmakeMatrStringShort :: (Int -> Int -> Int) -> Int -> Int -> String\nmakeMatrStringShort f width height = makeMatrString f 0 (width - 1) 0 (height - 1)\n\nmagisquareodd :: Int -> Int -> Int -> Int\nmagisquareodd size x y\n\t| size `mod` 2 == 0 = -1 -- fuck this is not odd\n\t| otherwise = magisquareoddhelp size x y 1\n\n\nmagisquareoddhelp :: Int -> Int -> Int -> Int -> Int\nmagisquareoddhelp size x y start\n\t| size == 1 = start -- the square of size 1 is trivial\n\t| x > 0 && y > 0 = magisquareoddhelp (size - 1) (x - 1) (y - 1) (start + 2 * size - 1) \n\t| x == 0 && y == 0 = start\n\t| x > 0 = start + x * 2 + md - 1\n\t| y > 0 = start + y * 2 - md\n\twhere \tmd = size `mod` 2\n\nmain :: IO()\nmain = do\n firstVals <- fmap (map read . words) getLine :: IO [Int]\n let size = firstVals !! 0\n\tputStrLn $ makeMatrStringShort (magisquareodd size) size size\n\n\n\n\n\n\n\n"}, {"source_code": "import qualified Data.Char as Char\n\nmain = interact $ z.y.f.read\n\ny ans = map (\\x -> (map show x)) ans\nz ans = unlines (map (\\x -> unwords x) ans)\n\nh n [] fans = fans\nh n ans fans = h n (drop n ans) ((take n ans):fans)\n\nf x = h x (g x x x 2 1 [] ) []\ng n 0 cl tempe tempo ans = ans\ng n rw 0 tempe tempo ans = g n (rw-1) n tempe tempo ans\ng n rw cl tempe tempo ans\n | rw == ((n `div` 2) + 1) = g n rw (cl-1) tempe (tempo+2) (tempo:ans)\n | (rw == n || rw == 1) && cl == ((n `div` 2) + 1) = g n rw (cl-1) tempe (tempo+2) (tempo:ans)\n | (rw == n || rw == 1) && cl /= ((n `div` 2) + 1) = g n rw (cl-1) (2+tempe) tempo (tempe:ans)\n | (cl == n || cl == 1) = g n rw (cl-1) (tempe+2) tempo (tempe:ans)\n | otherwise = g n rw (cl-1) tempe (tempo+2) (tempo:ans)\n"}], "src_uid": "a7da19d857ca09f052718cb69f2cea57"} {"source_code": "import Data.List\nimport Control.Monad\nmain :: IO ()\nmain = do\n _ <- getLine\n routine\n\nroutine :: IO ()\nroutine = do\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = (2 *) $ maximum $ zipWith min g (tail g)\n where\n g = ((map length).group) xs\n", "positive_code": [{"source_code": "module Main where\nimport Data.List\n\nmain = do\n getLine\n ts <- map length . group . filter (/= ' ') <$> getLine \n print $ (2*) $ maximum $ zipWith (\\x y -> min x y) ts $ tail ts"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n xs <- map (==1) . unfoldr (runStateT rIntS) <$> BS.getLine\n print $ 2 * query xs\n\nquery :: [Bool] -> Int\nquery (x:xs) = loop 0 x 1 0 xs\n where\n loop !maxi !prev !prevlen !prevprevlen (x:xs)\n | x == prev = loop maxi x (prevlen +1) prevprevlen xs\n | otherwise = loop (max maxi (min prevlen prevprevlen)) x 1 prevlen xs\n loop !maxi !prev !prevlen !prevprevlen []\n = max maxi $ min prevlen prevprevlen\n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\nrIntS :: StateT BS.ByteString Maybe Int\nrIntS = StateT $ BS.readInt . BS.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n-- import Data.List.HT (mapAdjacent)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nmapAdjacent f = map (uncurry f) . (zip <*> tail) \n\nsolve :: [Int] -> Int\nsolve = (*2)\n . maximum \n . mapAdjacent min \n . map length \n . group\n\nmain :: IO ()\nmain = do\n _ <- getLine\n v <- readInts\n print $ solve v"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Int] -> Int\nprocess sushis = maximum combinations where\n combinations = combine . map length . group $ sushis\n combine (x:y:xs) = 2 * min x y : combine (y:xs)\n combine _ = []\n\nmain = do\n n <- getInt\n sushis <- getInts\n print $ process sushis\n "}, {"source_code": "import Data.List\nmain = interact $ show . (*2) . process . map read . tail . words\nprocess :: [Int] -> Int\nprocess ns = maximum $ zipWith min ll $ tail ll\n where ll = map length $ group ns"}], "negative_code": [], "src_uid": "6477fdad8455f57555f93c021995bb4d"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.List(sort)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf testCase) >>> map (solve >>> showB) >>> C.unlines\n\ntestCase :: Scanner [Int]\ntestCase = numberOf int\n\nsolve :: [Int] -> Int\nsolve xs = iter False xs\n where\n iter _ xs | sorted xs = 0\n iter False xs = 1 + iter True (rec xs)\n iter True (x:xs) = 1 + iter False (x : rec xs)\n\n rec (x:x':xs) = min x x' : max x x' : rec xs\n rec xs = xs\n\n sorted xs = xs == sort xs\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Data.List\r\nimport Data.Array\r\nimport Control.Monad.State\r\n\r\nmain = do\r\n t <- fst . fromJust . C.readInt <$> C.getLine\r\n replicateM_ t\r\n $ do\r\n n <- fst . fromJust . C.readInt <$> C.getLine\r\n ps <- map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n print $ solve n ps\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve n ps = go arr 0\r\n where\r\n arr = listArray (1, n) ps\r\n\r\n go !a x = if isSorted a\r\n then x\r\n else go (swap a n (x+1)) (x + 1)\r\n\r\nisSorted :: Array Int Int -> Bool\r\nisSorted ys = snd $ foldl op (0, True) ys\r\n where\r\n op (acc, !st) x = (x, acc < x && st)\r\n\r\nswap :: Array Int Int -> Int -> Int -> Array Int Int\r\nswap !arr n i =\r\n if even i\r\n then arr\r\n // concat\r\n [[(i, arr ! (i + 1)), (i + 1, arr ! i)]\r\n | i <- [2, 4 .. n - 1]\r\n , arr ! i > arr ! (i + 1)]\r\n else arr\r\n // concat\r\n [[(i, arr ! (i + 1)), (i + 1, arr ! i)]\r\n | i <- [1, 3 .. n - 2]\r\n , arr ! i > arr ! (i + 1)]\r\n{-\r\n>>>solve 3 [3,2,1]\r\n3\r\n\r\n\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Data.List\r\nimport Data.Array\r\nimport Control.Monad.State\r\n\r\nmain = do\r\n t <- fst . fromJust . C.readInt <$> C.getLine\r\n replicateM_ t\r\n $ do\r\n n <- fst . fromJust . C.readInt <$> C.getLine\r\n ps <- map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n print $ solve n ps\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve n ps = go arr 0\r\n where\r\n arr = listArray (1, n) ps\r\n\r\n go a x = if isSorted a\r\n then x\r\n else go (swap a n (x+1)) (x + 1)\r\n\r\nisSorted :: Array Int Int -> Bool\r\nisSorted ys = snd $ foldl op (0, True) ys\r\n where\r\n op (acc, !st) x = (x, acc < x && st)\r\n\r\nswap :: Array Int Int -> Int -> Int -> Array Int Int\r\nswap arr n i =\r\n if even i\r\n then arr\r\n // concat\r\n [[(i, arr ! (i + 1)), (i + 1, arr ! i)]\r\n | i <- [2, 4 .. n - 1]\r\n , arr ! i > arr ! (i + 1)]\r\n else arr\r\n // concat\r\n [[(i, arr ! (i + 1)), (i + 1, arr ! i)]\r\n | i <- [1, 3 .. n - 2]\r\n , arr ! i > arr ! (i + 1)]\r\n{-\r\n>>>solve 3 [3,2,1]\r\n3\r\n\r\n\r\n-}\r\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Data.List\r\nimport Data.Array\r\nimport Control.Monad.State\r\n\r\nmain = do\r\n t <- fst . fromJust . C.readInt <$> C.getLine\r\n replicateM_ t\r\n $ do\r\n n <- fst . fromJust . C.readInt <$> C.getLine\r\n ps <- map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n print $ solve n ps\r\n\r\nsolve :: Int -> [Int] -> Int\r\nsolve n ps = go arr 0\r\n where\r\n arr = listArray (1, n) ps\r\n\r\n go !a x = if isSorted a\r\n then x\r\n else go (swap a n (x+1)) (x + 1)\r\n\r\nisSorted :: Array Int Int -> Bool\r\nisSorted ys = snd $ foldl op (0, True) ys\r\n where\r\n op (acc, !st) x = (x, acc < x && st)\r\n\r\nswap :: Array Int Int -> Int -> Int -> Array Int Int\r\nswap !arr n i =\r\n if even i\r\n then arr\r\n // concat\r\n [[(i, arr ! (i + 1)), (i + 1, arr ! i)]\r\n | i <- [2, 4 .. n - 1]\r\n , arr ! i > arr ! (i + 1)]\r\n else arr\r\n // concat\r\n [[(i, arr ! (i + 1)), (i + 1, arr ! i)]\r\n | i <- [1, 3 .. n - 2]\r\n , arr ! i > arr ! (i + 1)]\r\n{-\r\n>>>solve 3 [3,2,1]\r\n3\r\n\r\n\r\n-}\r\n"}], "negative_code": [{"source_code": "module Main where\r\n\r\nmain=putStrLn\"hello\""}], "src_uid": "d4bcc53b470e4beaa078d5ce3785c6cb"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Control.Monad.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad.Trans\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Prelude hiding (reverse)\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n k <- getInt\r\n a <- replicateM n getInt\r\n\r\n let\r\n prefixes = filter (\\x -> length x >= 3) . map (take 3) $ tails a\r\n cost (x1:x2:x3:[]) = if x2 > x1 + x3 then 1 else 0\r\n cost x = trace (show prefixes) 0\r\n ansbig = sum $ map cost prefixes\r\n ans = if k == 1 then (n - 1) `div` 2 else ansbig\r\n pure $ putInts [ans]\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE CPP #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Bool\r\nimport Debug.Trace\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC {n :: Int, k :: Int, xs :: [Int]}\r\ntype Output = Int\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n k <- int\r\n xs <- n >< int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..}\r\n | k == 1 = (n - 1) `div` 2\r\n | otherwise = length . filter id $ zipWith3 (\\x y z -> y - x - z > 0) xs (tail xs) (drop 2 xs)\r\n\r\noutput :: Output -> C.ByteString\r\noutput = showB\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, k :: Int, xs :: [Int]}\ntype Output = Int\n\ninput :: Scanner TC\ninput = do\n n <- int\n k <- int\n xs <- n >< int\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..}\n | k == 1 = (n - 1) `div` 2\n | otherwise = length . filter id $ zipWith3 (\\x y z -> y - x - z > 0) xs (tail xs) (drop 2 xs)\n\noutput :: Output -> C.ByteString\noutput = showB\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k as\n | k == 1 = (n - 1) `div` 2\n | otherwise = L.sum $ L.zipWith3 (\\a_ a ap -> if a > (a_ + ap) then 1 else 0) as (drop 1 as) (drop 2 as)\n \n\n\nmain :: IO ()\nmain = do\n n <- B8.getLine <&> readIntB8\n replicateM_ n $ do\n [n, k] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntB8s\n let answer = solve n k as\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE CPP #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Bool\r\nimport Debug.Trace\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC {n :: Int, k :: Int, xs :: [Int]}\r\ntype Output = Int\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n k <- int\r\n xs <- n >< int\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..}\r\n | k == 1 = (n - 1) `div` 2\r\n | otherwise = length $ zipWith3 (\\x y z -> y - x - z > 0) xs (tail xs) (drop 2 xs)\r\n\r\noutput :: Output -> C.ByteString\r\noutput = showB\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}], "src_uid": "4d5d20fd586ddbea2adeab104a6c2aec"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE TypeOperators #-}\n\nmodule Main where\n\nimport Data.List\nimport Data.Char\nimport Data.Maybe\n-- import Control.Applicative\nimport Control.Monad\nimport System.IO\n\nmain :: IO ()\nmain = do\n -- handle <- openFile \"input.txt\" ReadMode\n -- contents <- hGetContents handle\n contents <- getContents\n let linesOfFile = lines contents\n let a = map (\\x-> read x :: Int) $ words $ (linesOfFile !! 1)\n let m = read $ (linesOfFile !! 2) :: Int\n let l = map (\\x -> let k = words x; i = read (k!!0); j = read (k!!1) in (i,j)) $ drop 3 linesOfFile\n let res = solve a l\n putStrLn $ show $ res \n -- let d = initData s\n -- forM_ [1..n] $ \\a0 -> do\n -- let l = words $ linesOfFile !! (2 + a0)\n -- let k = read (l!!0) :: Int\n -- let c = ord (l!!1!!0) - ord 'a'\n -- putStrLn $ show $ d!!c!!(k - 1)\n -- ii <- getLine\n -- aa <- getLine\n -- bb <- getLine\n -- let\n\nsolve a l =\n let\n s = sum a\n i = findIndex (\\x-> snd x >= s) l\n e = l!!(fromJust i)\n t = fst e\n in\n if i == Nothing then -1 else maximum [s,t]\n", "positive_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad \nimport Control.Applicative\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve as ps = case dropWhile ((< s) . snd) ps of\n (l, _):_ -> max l s\n otherwise -> -1\n where s = sum as\n\nmain = do \n n <- readInt <$> B.getLine\n as <- readInts <$> B.getLine\n m <- readInt <$> B.getLine\n ps <- replicateM m ((\\(l:r:_) -> (l, r)) . readInts <$> B.getLine)\n print $ solve as ps"}, {"source_code": "import Control.Monad\nimport Data.List\n\nparse s = let n:xs = map read . words $ s\n (as, (m:ms)) = splitAt n xs\n rs = splitPairs ms\n in (as, rs)\n where\n splitPairs [] = []\n splitPairs (a:b:xs) = (a,b):(splitPairs xs)\nsolve ps xs = (\\(a,b) -> Just $ max x a) =<< find (\\(a,b) -> x <= b) xs\n where x = sum ps\ndisplay :: Maybe Int -> String\ndisplay = (++\"\\n\") . maybe \"-1\" show\nmain = interact (display . uncurry solve . parse)\n"}], "negative_code": [], "src_uid": "311f74b766818633581af67a88244709"} {"source_code": "--import Control.Monad.State\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Traversable\nimport Data.Tree\nimport qualified Data.Map as Map\nimport Data.Maybe\n\n\ndata KMP a = KMP { done :: Bool,\n feed :: a -> KMP a }\n\nmkKMP' :: Ord a => KMP a -> [a] -> KMP a\nmkKMP' backup [] = KMP True (feed backup)\nmkKMP' backup (h : t) = KMP False (\\ch -> if ch == h then mkKMP' fbh t else feed backup ch) where\n fbh = feed backup h\n\nmkKMP :: Ord a => [a] -> KMP a\nmkKMP l = start where\n start = mkKMP' (KMP False (\\x -> start)) l\n\nswap(a,b)=(b,a)\nrunKMP :: Ord a => KMP a -> [a] -> ([Bool], KMP a)\n--runKMP kmp l = runState (traverse (\\x -> modify (`feed` x) *> gets done) l) kmp\nrunKMP kmp l = swap $ mapAccumL (\\k x -> let k' = feed k x in (k', done k')) kmp l\n\n\ntype Tree1 = Tree String\n\nprocess :: [(Int, String)] -> Tree1\nprocess l = gogo 1 \"\" where\n gogo n s = Node s $ map (uncurry gogo) (fromMaybe [] $ Map.lookup n m)\n m = Map.fromListWith (++) $ zipWith (\\i (j,s) -> (j, [(i, s)])) [2..] l\n\ngo k (Node s l) = case runKMP k s of\n (ms, kk) -> length (filter id ms) + sum (map (go kk) l)\nz(l,s)=go (mkKMP s) (process (map ((\\[a,b]->(read a,b)).words) l))\nmain=interact$show.z.(init&&&last).tail.lines\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Control.DeepSeq\nimport Data.Array\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as C\n\nkmp :: Eq a => Array Int a -> Array Int Int\nkmp a = pre\n where\n ix = bounds a\n pre = listArray ix $ map f $ range ix\n f i\n | i == fst ix = fst ix - 1\n | otherwise = g $ pre!(i-1)\n where\n g j\n | a!(j+1) == a!i = j + 1\n | inRange ix j = g $ pre!j\n | otherwise = fst ix - 1\n\nauto :: (Ix a) => (a, a) -> Array Int a -> U.UArray (Int, a) Int\nauto (cl, cr) a = U.array ix $ assocs $ to\n where\n (il, ir) = bounds a\n ix = ((il - 1, cl), (ir, cr))\n pre = kmp a\n to = listArray ix $ map f $ range ix\n f (i, c)\n | i < ir && a!(i+1) == c = i + 1\n | i == il - 1 = i\n | otherwise = force $ to!(pre!i, c)\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n (sh: st) <- fmap C.words C.getContents\n let el = zipWith (\\i (j, k) -> (readInt j, (i, k))) [2..] $ pairs $ init st\n e = accumArray (flip (:)) [] (1, readInt sh) el\n s = last st\n n = C.length s\n a = listArray (1, n) $ C.unpack s\n to = auto charset a\n go (x, i) c = let j = to U.! (i, c) in force (if j == n then x + 1 else x, j)\n gao v i = foldl' (+) 0 [force $ c + gao w j |\n (w, d) <- e!v, let (c, j) = C.foldl' go (0::Int, i) d]\n print $ gao 1 0\n where\n charset = ('a', 'z')\n"}], "negative_code": [], "src_uid": "2e08077d0b49c52586266ddcc12edcb5"} {"source_code": "import Control.Monad\nimport Data.Graph\nimport Data.Tree\n\nreadPair :: IO (Int, Int)\nreadPair = do\n [a, b] <- fmap (map read . words) getLine\n return (a, b)\n\nmain :: IO ()\nmain = do\n (n, m) <- readPair\n e <- replicateM m readPair\n let g = buildG (1, n) e\n c = map flatten $ components g\n f l a = filter ((==l) . length) a\n one = f 1 c\n two = f 2 c\n three = f 3 c\n if maximum (map length c) > 3 || length two > length one then putStrLn \"-1\"\n else do\n let (x, y) = splitAt (length two) one\n ans = (three ++) $ (zipWith (++) x two ++) $\n map (concat . take 3) $ takeWhile (not . null) $ iterate (drop 3) $ y\n forM_ ans $ \\i -> do\n putStrLn $ unwords $ map show $ i\n", "positive_code": [{"source_code": "import Data.Function\nimport Data.List\n\nmain :: IO ()\nmain = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> [[Int]]\nsolve ((n : _) : ps)\n | (length $ head ts) <= 3 && (fst $ con [] bs) = as ++ (snd $ con [] bs)\n | otherwise = [[-1]]\n where\n ts = sortBy (compare `on` (0 -) . length) $ map (map fst) $ groupBy ((==) `on` snd) $ sortBy (compare `on` snd) $ zip [1..] $ foldl f [1..n] $ sort $ map sort ps\n (as, bs) = span ((== 3) . length) ts\n con ys [] = (True, ys)\n con ys (x : xs)\n | length x == 2 = if (length $ last xs) == 1\n then con ((x ++ last xs) : ys) (init xs)\n else (False, [])\n | otherwise = con ((concat $ x : take 2 xs) : ys) (drop 2 xs)\n f ps [a, b] = [if p' == pa || p' == pb then p else p' | p' <- ps]\n where\n pa = ps !! (a - 1)\n pb = ps !! (b - 1)\n p = min pa pb\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Char (ord)\nimport Data.Graph (buildG, components)\nimport Data.Tree (flatten)\nimport Data.List (intercalate)\n\nsolve :: Int -> [(Int, Int)] -> Maybe [[Int]]\nsolve n ps\n | any ((> 3) . length) comp = Nothing\n | length two > length one = Nothing\n | otherwise = Just ans\n where\n graph = buildG (1,n) ps\n comp = map flatten $ components graph\n one = filter ((== 1) . length) comp\n two = filter ((== 2) . length) comp\n three = filter ((== 3) . length) comp\n ans = three ++ zipWith (++) one two ++ toTuples (drop (length two) (concat one))\n toTuples [] = []\n toTuples (a:b:c:xs) = [a,b,c] : toTuples xs\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n ps <- replicateM m readPair\n case solve n ps of\n Nothing -> print (-1)\n Just as -> mapM_ prints as\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "import Data.Graph\nimport Data.Tree\nimport Data.List\nimport Control.Monad\n\npart n [] = []\npart n xs = (take n xs):part n (drop n xs)\n\nsolve :: Int -> [(Int, Int)] -> [[Int]]\nsolve n es\n | solutionExists = c3 ++ zipWith (++) c2 (take n2 c1) ++ (part 3 $ drop n2 $ concat c1)\n | otherwise = [[-1]]\n where cs = map flatten $ components $ buildG (1, n) es\n c1 = filter (\\x -> length x == 1) cs\n c2 = filter (\\x -> length x == 2) cs\n c3 = filter (\\x -> length x == 3) cs\n n1 = length c1\n n2 = length c2\n n3 = length c3\n cn = filter (\\x -> length x > 3) cs\n solutionExists = null cn && n2 <= n1 && (n1 - n2) `mod` 3 == 0\n\nreadPair = fmap ((\\[x, y] -> (x, y)) . map read . words) getLine\n\nmain = do (n, m) <- readPair\n es <- replicateM m readPair\n let solution = solve n es\n putStr $ unlines $ map (unwords . map show) solution\n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.List\nimport Data.Graph\nimport Data.Tree\n\ntoPairs (x:y:xys) = (x,y) : (y,x) : toPairs xys\ntoPairs _ = []\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n edges <- toPairs.map (pred.read).words <$> getContents\n let gr = buildG (0,n-1) edges\n putStr.unlines.map(unwords.map show).solve.map flatten $ scc gr\n\nsolve :: [[Int]] -> [[Int]]\nsolve vs = go [] [] [] vs\n where\n go vs1 vs2 vs3 ([x,y,z]:rest) = go vs1 vs2 ([x,y,z]:vs3)rest\n go vs1 vs2 vs3 ([x,y]:rest) = go vs1 ([x,y]:vs2) vs3 rest\n go vs1 vs2 vs3 ([x]:rest) = go ([x]:vs1) vs2 vs3 rest\n go vs1 vs2 vs3 []\n | len1 == len2 = map (map (1+)) $ vs3 ++ zipWith(++)vs1 vs2\n | len1 < len2 = [[-1]]\n | (len1-len2)`mod`3/=0 = [[-1]]\n | otherwise = map (map (1+)) $ vs3 ++ slices 3 (concat$drop len2 vs1) ++ zipWith(++)(take len2 vs1)vs2\n where\n len1 = length vs1\n len2 = length vs2\n go _ _ _ _ = [[-1]]\n\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Char (ord)\nimport Data.Graph (buildG, components)\nimport Data.Tree (flatten)\nimport Data.List (intercalate)\n\nsolve :: Int -> [(Int, Int)] -> Maybe [[Int]]\nsolve n ps\n | any ((> 3) . length) comp = Nothing\n | two > one = Nothing\n | otherwise = Just ans\n where\n graph = buildG (1,n) ps\n comp = map flatten $ components graph\n one = filter ((== 1) . length) comp\n two = filter ((== 2) . length) comp\n three = filter ((== 3) . length) comp\n ans = three ++ zipWith (++) one two ++ toTuples (drop (length two) (concat one))\n toTuples [] = []\n toTuples (a:b:c:xs) = [a,b,c] : toTuples xs\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n ps <- replicateM m readPair\n case solve n ps of\n Nothing -> print (-1)\n Just as -> mapM_ prints as\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.List\nimport Data.Graph\nimport Data.Tree\n\ntoPairs (x:y:xys) = (x,y) : (y,x) : toPairs xys\ntoPairs _ = []\n\nmain :: IO ()\nmain = do\n [n,m] <- map read.words <$> getLine\n edges <- toPairs.map (pred.read).words <$> getContents\n let gr = buildG (0,n-1) edges\n putStr.unlines.map(unwords.map show).solve.map flatten $ scc gr\n\nsolve :: [[Int]] -> [[Int]]\nsolve vs = go [] [] [] vs\n where\n go vs1 vs2 vs3 ([x,y,z]:rest) = go vs1 vs2 ([x,y,z]:vs3)rest\n go vs1 vs2 vs3 ([x,y]:rest) = go vs1 ([x,y]:vs2) vs3 rest\n go vs1 vs2 vs3 ([x]:rest) = go ([x]:vs1) vs2 vs3 rest\n go vs1 vs2 vs3 []\n | len1 == len2 = map (map (1+)) $ vs3 ++ zipWith(++)vs1 vs2\n | len1 < len2 = [[-1]]\n | (len1-len2)`mod`3/=0 = [[-1]]\n | otherwise = map (map (1+)) $ slices 3 (concat$drop len2 vs1) ++ zipWith(++)(take len2 vs1)vs2\n where\n len1 = length vs1\n len2 = length vs2\n go _ _ _ _ = [[-1]]\n\nslices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs"}], "src_uid": "46e7cd6723553d2c6d6c6d0999a5b5fc"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Monad\r\n\r\nseg_should_be_long st x y =\r\n\tst /= 0 && st == 2 * (x + y) ||\r\n\tst /= 0 && x == 0 && y == st ||\r\n\tst == 0 && x /= 0 && x == y\r\n\r\nalt_sum = \\case\r\n\t[x] -> x\r\n\t[x, y] -> x - y\r\n\t_ -> undefined\r\n\r\nsol = sol_rec 0\r\n\twhere\r\n\t\tsol_rec st = \\case\r\n\t\t\t[] -> []\r\n\t\t\t[x] -> [[x]]\r\n\t\t\tx:y:ls ->\r\n\t\t\t\tlet (seg, ls') =\r\n\t\t\t\t\tif seg_should_be_long st x y\r\n\t\t\t\t\tthen ([x, y], ls)\r\n\t\t\t\t\telse ([x], y:ls)\r\n\t\t\t\tin seg:(sol_rec (st + alt_sum seg) ls')\r\n\r\nmain = do\r\n\tn <- readLn :: IO Int\r\n\treplicateM_ n $ do\r\n\t\tgetLine\r\n\t\tls <- sol <$> map read <$> words <$> getLine :: IO [[Int]]\r\n\t\tif sum (map alt_sum ls) == 0\r\n\t\tthen do\r\n\t\t\tprint $ length ls\r\n\t\t\tfoldM_ print_segs 1 ls\r\n\t\telse\r\n\t\t\tprint (-1)\r\n\twhere\r\n\t\tprint_segs tot seg = do\r\n\t\t\tputStrLn $ show tot ++ ' ':(show $ tot + length seg - 1)\r\n\t\t\treturn $ tot + length seg", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Monad\r\n\r\nseg_should_be_long st x y =\r\n\tst /= 0 && st == 2 * (x + y) ||\r\n\tst /= 0 && x == 0 && y == st ||\r\n\tst == 0 && x /= 0 && x == y\r\n\r\nalt_sum = \\case\r\n\t[x] -> x\r\n\t[x, y] -> x - y\r\n\t_ -> undefined\r\n\r\nsol = reverse . sol_rec [] 0\r\n\twhere\r\n\t\tsol_rec segs st = \\case\r\n\t\t\t[] -> segs\r\n\t\t\t[x] -> [x]:segs\r\n\t\t\tx:y:ls ->\r\n\t\t\t\tlet (seg, ls') =\r\n\t\t\t\t\tif seg_should_be_long st x y\r\n\t\t\t\t\tthen ([x, y], ls)\r\n\t\t\t\t\telse ([x], y:ls)\r\n\t\t\t\tin sol_rec (seg:segs) (st + alt_sum seg) ls'\r\n\r\nmain = do\r\n\tn <- readLn :: IO Int\r\n\treplicateM_ n $ do\r\n\t\tgetLine\r\n\t\tls <- sol <$> map read <$> words <$> getLine :: IO [[Int]]\r\n\t\tif sum (map alt_sum ls) == 0\r\n\t\tthen do\r\n\t\t\tprint $ length ls\r\n\t\t\tfoldM_ print_segs 1 ls\r\n\t\telse\r\n\t\t\tprint (-1)\r\n\twhere\r\n\t\tprint_segs tot seg = do\r\n\t\t\tputStrLn $ show tot ++ ' ':(show $ tot + length seg - 1)\r\n\t\t\treturn $ tot + length seg"}], "negative_code": [], "src_uid": "54a3b38631ddc033597797263fd7fb22"} {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ sep $ lines input\n mapM_ putStrLn sols\n\nsep [] = []\nsep (_:xs) = head:(sep tail)\n where (head,tail) = splitAt 8 xs\n\nparse xs = map (=='#') $ concat xs\n\nformat :: Int -> String\nformat x = show (i+1) ++ \" \" ++ show (j+1)\n where (i,j) = divMod x 8\n\nsolve :: [Bool] -> Int\nsolve xs = head $ filter isBishop squares\n where isBishop x = all (xs !!) [x, x-9, x+7] :: Bool\n squares = [x+8*y | x <- ids, y <- ids] :: [Int]\n ids = [1..6]\n", "positive_code": [{"source_code": "module Main where\n\n\nimport Control.Monad (replicateM_, replicateM)\nimport qualified Data.Map as M\nimport Data.Map.Internal ((!?))\nimport Data.Maybe (fromMaybe)\n \ngetNumbers :: IO [Int]\ngetNumbers = map read . words <$> getLine\n\ngetPositionCharactersInString :: Char -> String -> [Int]\ngetPositionCharactersInString ch = map snd . filter ((== ch) . fst) . flip zip [1..]\n\ngetChessBoard :: IO [String]\ngetChessBoard = do \n _ <- getLine \n replicateM 8 getLine\n\n\nlineBeforeBishop :: [Int] -> Bool\nlineBeforeBishop [x, y] = y - x == 2\nlineBeforeBishop _ = False \n\nsolution :: IO ()\nsolution = do\n board <- getChessBoard\n let ([x1, x2], y) = head $ filter (lineBeforeBishop . fst) $ zip (map (getPositionCharactersInString '#') board) [2..]\n putStrLn $ show y <> \" \" <> show ((x1 + x2) `div` 2)\n \nmain :: IO ()\nmain = do\n [t] <- getNumbers\n replicateM_ t solution"}, {"source_code": "rd :: Int -> IO [String]\r\nrd 0 = pure []\r\nrd i = do\r\n s <- getLine\r\n ans <- rd $ i - 1\r\n pure (s: ans)\r\n\r\nfindH :: [String] -> Int -> Int -> (Int, Int)\r\nfindH a x y = if (&&) ((&&) (a !! (x - 1) !! (y - 1) == '#') (a !! (x - 1) !! (y + 1) == '#')) ((&&) (a !! (x + 1) !! (y - 1) == '#') (a !! (x + 1) !! (y + 1) == '#'))\r\n then (x, y)\r\n else if y == 6\r\n then findH a (x + 1) 1\r\n else findH a x (y + 1)\r\n\r\nfind :: [String] -> (Int, Int)\r\nfind a = findH a 1 1\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = pure ()\r\nsolve i = do\r\n s <- tail <$> (rd 9)\r\n let (x, y) = find s\r\n putStrLn $ show (x + 1) ++ \" \" ++ show (y + 1)\r\n solve $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n solve n"}], "negative_code": [], "src_uid": "b0f968ca75fbea2f11a7e4b9006f136e"} {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map show\n >>> unlines\n\nprocess :: [[Int]] -> [Integer]\nprocess [] = []\nprocess ([_, k] : xs : xss) = solve k xs : process xss\n\nsolve :: Int -> [Int] -> Integer\nsolve k = sum . map toInteger . take (k + 1) . reverse . sort\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n inputs <- map (read) <$> words <$> getLine\n line <- getLine\n print $ sum $ take ((inputs!!1) + 1) $ reverse $ (sort $ map (read) $ words line :: [Int64])\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t $ do\n inputs <- map (read) <$> words <$> getLine\n line <- getLine\n print $ sum $ take ((inputs!!1) + 1) $ reverse $ (sort $ map (read) $ words line :: [Integer])\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n cases <- read <$> getLine\n replicateM cases $ do\n (n:k:_) <- map read <$> words <$> getLine\n barrels <- map read <$> words <$> getLine\n putStrLn $ show $ maximalPourDiff k barrels\n\nmaximalPourDiff :: Int -> [Integer] -> Integer\nmaximalPourDiff k barrels = sum $ take (k+1) $ reverse $ sort barrels"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map show\n >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([_, k] : xs : xss) = solve k xs : process xss\n\nsolve :: Int -> [Int] -> Int\nsolve k = sum . take (k + 1) . reverse . sort\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain = do\n cases <- read <$> getLine\n replicateM cases $ do\n (n:k:_) <- map read <$> words <$> getLine\n barrels <- map read <$> words <$> getLine\n putStrLn $ show $ maximalPourDiff k barrels\n\nmaximalPourDiff :: Int -> [Int] -> Int\nmaximalPourDiff k barrels = sum $ take (k+1) $ reverse $ sort barrels"}], "src_uid": "08c797a7972fae99f8b64b47c53d8aeb"} {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport qualified Data.Map as M\r\n\r\ntransform :: [(Int, Char)] -> M.Map Int Char -> [Char]\r\ntransform [] _ = []\r\ntransform ((d, c):rs) m =\r\n case M.lookup d m of\r\n (Just c') -> c' : transform rs m\r\n Nothing -> c : transform rs m'\r\n where m' = M.insert d c m\r\n\r\nsolveProblem :: [(Int, Char)] -> Bool\r\nsolveProblem rs = transform rs M.empty == map snd rs\r\n\r\nformatSolution :: Bool -> String\r\nformatSolution True = \"YES\"\r\nformatSolution False = \"NO\"\r\n\r\nhandleProblem :: IO ()\r\nhandleProblem = do\r\n getLine\r\n numbers <- map read . words <$> getLine\r\n letters <- getLine\r\n putStrLn $ formatSolution $ solveProblem $ numbers `zip` letters\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberProblems <- read <$> getLine\r\n replicateM_ numberProblems handleProblem\r\n", "positive_code": [{"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> B8.ByteString -> Bool\nsolve n as s = L.length counterExamples == 0\n where \n str = B8.unpack s\n counterExamples = do\n x1@(a1, c1) <- zip as str\n x2@(a2, c2) <- zip as str\n M.guard $ a1 == a2 && c1 /= c2\n M.guard $ not (x1 == x2)\n tracingM \"x1\" x1\n tracingM \"x2\" x2\n return True\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n s <- B8.getLine <&> B8.filter isAlphaNum\n let answer = solve n as s\n putsYesNo answer\n"}], "negative_code": [], "src_uid": "485d5984e34a479f2c074a305ae999ae"} {"source_code": "import Data.Array\n\nisPrime n = isPrime' n 2\n where\n isPrime' n i \n | i * i > n = True\n | n `mod` i == 0 = False\n | otherwise = isPrime' n (i + 1)\n\n\nsolve input = \n let n = (read input)::Int in\n let primes = filter isPrime [2..500] in\n let a = listArray (0, (length primes) - 1) primes in\n case n of\n 2 -> show(-1)\n _ ->\n let res = ((a ! 0) * (a ! 1)) : ((a ! 0) * (a ! 2)) : ((a ! 1) * (a ! 2)) : (map (\\x -> (a ! x) * (a ! 1) * (a ! 2)) [3..(n - 1)]) in\n let out = map (show) res in\n unlines out\n\nmain = interact(solve)", "positive_code": [{"source_code": "\nimport Data.List\n\nprimes = 2 : 3 : [p | p <- [5,7..],\n all (\\x -> p `mod` x /= 0) $ takeWhile (\\x -> x*x<=p) primes]\n\nok xs = length xs /= 2 &&\n all (\\x -> all (\\y -> gcd x y /= 1) xs) xs &&\n all ((<=100).length.show) xs\n\nmain = do\n n <- readLn\n let ps = take (n+1) primes\n ps' = take n primes\n xs' = map product $ take (n-1) $ tails ps'\n xs = head xs' : map (last ps*) (tail xs') ++ [last ps * 2]\n if ok xs then mapM_ print xs else print (-1)\n"}, {"source_code": "main :: IO ()\nmain = do \n\tn <- getLine\n\tlet nn = read n :: Int\n--\tsequence (map print (solve nn))\n\tmapM_ print (solve nn)\n\nsolve :: Int -> [Integer]\nsolve 2 = [-1]\nsolve n = (product xs) : (map (2 * ) xs) where (x : xs) = take n er\n\ner = erpr [2..]\nerpr (x : xs) = x : erpr [y | y <- xs, y `mod` x /= 0]\n\n"}, {"source_code": "main :: IO ()\nmain = do \n\tn <- getLine\n\tlet nn = read n :: Int\n\tmapM_ print (solve nn)\n\nsolve :: Int -> [Int]\nsolve 2 = [-1]\nsolve n = 10 : 15 : map (6 *) [1..n-2]"}, {"source_code": "import Data.List\nprobe x s = if all (\\a -> x `mod` a /= 0) s then x else probe (x+1) s\nprime k ss | length ss < k = prime k ((probe (head ss) ss):ss)\n | otherwise = reverse ss\nmain = do\n n <- readIO =<< getLine\n let p = prime n [2]\n m = 10^100\n l = map (\\i -> product ((p!!(i-1))`delete`p)) [1..n]\n if n < 3 || any (>= m) l then putStrLn \"-1\" else mapM_ (putStrLn.show) l\n"}, {"source_code": "import Data.List\nprobe x s = if all (\\a -> x `mod` a /= 0) s then x else probe (x+1) s\nprime k ss | length ss < k = prime k ((probe (head ss) ss):ss)\n | otherwise = reverse ss\nmain = do\n n <- readIO =<< getLine\n let p = prime n [2]\n l = map (\\i -> product ((p!!(i-1))`delete`p)) [1..n]\n m = 10^100\n if n < 3 || any (>= m) l then putStrLn \"-1\" else mapM_ (putStrLn.show) l\n"}], "negative_code": [{"source_code": "import Data.List\nprobe x s = if all (\\a -> x `mod` a /= 0) s then x else probe (x+1) s\nprime k ss | length ss < k = prime k ((probe (head ss) ss):ss)\n | otherwise = reverse ss\nmain = do\n n <- readIO =<< getLine\n let p = prime n [2]\n l = map (\\i -> product ((p!!(i-1))`delete`p)) [1..n]\n m = 10^100\n if any (>= m) l then putStrLn \"-1\" else mapM_ (putStrLn.show) l\n"}, {"source_code": "\nimport Data.List\n\nprimes = 2 : 3 : [p | p <- [5,7..],\n all (\\x -> p `mod` x /= 0) $ takeWhile (\\x -> x*x<=p) primes]\n\nok xs = all (\\x -> all (\\y -> gcd x y /= 1) xs) xs &&\n all ((<=100).length.show) xs\n\nmain = do\n n <- readLn\n let ps = take (n+1) primes\n x = product (last ps : take (n-1) ps)\n xs = map product $ take (n-1) $ tail (tails ps)\n if ok (x:xs) || True then mapM_ print (x:xs) else print (-1)\n"}], "src_uid": "b3108315889607dabcd3112bcfe3fb54"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Prelude hiding (id)\n\nimport qualified Data.Map as M\n\nsolve :: [(Int, String)] -> M.Map Int Int -> Int -> Int\nsolve [] _ acc = acc\nsolve ((id, sign) : xs) m acc\n | sign == \"+\" = let newacc = max (M.size newm) acc\n newm = M.insert id 0 m\n in solve xs newm newacc\n | otherwise = if M.member id m then solve xs (M.delete id m) acc\n else solve xs m (acc + 1)\n\nmain :: IO ()\nmain = do\n n <- (\\s -> read s :: Int) <$> getLine\n xs <- replicateM n (do\n (sign, id) <- ((\\[s, i] -> (s, read i :: Int)) . words) <$> getLine\n return (id, sign))\n print $ solve xs M.empty 0\n", "positive_code": [{"source_code": "main :: IO()\nmain = print . solve . trans . tail . words =<< getContents\n\ntrans :: [String] -> [(Int, Int)]\ntrans [] = []\ntrans (op:r:s) | op == \"+\" = (1, (read r)):(trans s)\n | otherwise = (0, (read r)):(trans s)\n\nsolve :: [(Int, Int)] -> Int\nsolve r = solve' (reverse (complete (reverse r) [])) []\n where\n solve' :: [(Int, Int)] -> [Int] -> Int\n solve' [] a = length a\n solve' ((1, r):rs) a = solve' rs (insertTo a r)\n solve' ((0, r):rs) a = solve' rs (removeFrom a r)\n \nremoveElem :: [Int] -> Int -> [Int]\nremoveElem [] v = []\nremoveElem (l:ls) v | l == v = ls\n | otherwise = l:(removeElem ls v)\n \ncomplete :: [(Int, Int)] -> [Int] -> [(Int, Int)]\ncomplete [] [] = []\ncomplete [] (c:cs) = (1, c):(complete [] cs)\ncomplete ((0, r):rs) c = (0, r):(complete rs (r:c))\ncomplete ((1, r):rs) c = (1, r):(complete rs (removeElem c r))\n\ninsertTo :: [Int] -> Int -> [Int]\ninsertTo [] v = [v]\ninsertTo (0:rs) v = v:rs\ninsertTo (r:rs) v = r:(insertTo rs v)\n\nremoveFrom :: [Int] -> Int -> [Int]\nremoveFrom (r:rs) v | r == v = 0:rs\n | otherwise = r:(removeFrom rs v)\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- fmap read getLine\n rs <- forM [1..n] (\\_ -> fmap ((\\[ch,v] -> (head ch, read v)) . words) getLine)\n print $ solve rs\n\nsolve :: [(Char, Int)] -> Int\nsolve (x:xs) = g [] 0 $ f [] x xs\n where f l1 (ch, v) (x:xs) = if ch == '-' && noPlus v l1 then f (('+', v):l1 ++ [('-', v)]) x xs\n else f (l1 ++ [(ch, v)]) x xs\n f l1 (ch, v) [] = if ch == '-' && noPlus v l1 then (('+', v):l1 ++ [('-', v)])\n else (l1 ++ [(ch, v)])\n g :: [Int] -> Int -> [(Char,Int)] -> Int\n g sys m (('+',v):xs) = g (v:sys) (max m $ length sys + 1) xs\n g sys m (('-',v):xs) = g (sys\\\\[v]) m xs\n g _ m [] = m\n \nnoPlus :: Int -> [(Char, Int)] -> Bool\nnoPlus v = all (\\(ch,v1) -> ch /= '+' || v /= v1)"}], "negative_code": [], "src_uid": "6cfd3b0a403212ec68bac1667bce9ef1"} {"source_code": "import System.IO\nimport Control.Applicative\n{-import Data.HashSet-}\nimport Data.Bits\nimport qualified Data.Map as Map\nimport Data.Tuple\n \n\n\nparse :: String -> Int -> [Int]\nparse input line_idx = map read $ words $ lines input !! line_idx\n\nsolve :: String -> String\nsolve input = (show $ answer x as ) ++ \"\\n\"\n{-solve input = (show $ merged_map x as ) ++ \"\\n\"-}\n where \n n = parse input 0 !! 0 :: Int\n x = parse input 0 !! 1 :: Int\n as = parse input 1 :: [Int]\n\ntype Mymap = Map.Map Int (Int, Int)\n\n\nanswer x as \n | pre_answer == 3 = -1\n | otherwise = pre_answer\n where\n pre_answer = foldl min 3 (map extractEachAnswer ( Map.elems (counter (.&.x) as)) )\n\n\nextractEachAnswer :: (Int, Int) -> Int\nextractEachAnswer (a, b) \n | a>=2 = 0\n | a>=1 && b>=1 && a+b>=2 = 1\n | b>=2 = 2\n | otherwise = 3\n \n\n{-counter :: [Int] -> Mymap-}\ncounter func as = foldr (addToMap func) Map.empty as\n\naddToMap :: (Int -> Int) -> Int -> Mymap -> Mymap\naddToMap func a = Map.alter modifier a . (if (func a) /= a then Map.alter modifier2 (func a) else id)\n where\n modifier2 = mswap . modifier . mswap\n where\n mswap = fmap swap \n\nmodifier :: Maybe (Int, Int) -> Maybe (Int, Int)\nmodifier Nothing = Just (1, 0)\nmodifier (Just (a, b)) = Just (a+1, b)\n\n\n\nmain = (solve <$> getContents) >>= putStr \n", "positive_code": [{"source_code": "import Data.Bits\nimport qualified Data.Map.Strict as Map\n\ntoint s = (read s) :: Int\n\nagregar x m = Map.insertWith (+) x 1 m\nquitar :: Integer -> (Map.Map Integer Integer) -> (Map.Map Integer Integer)\nquitar x m = Map.insertWith (+) x (-1) m\n\nasdasd [] = Map.fromList []\nasdasd (x:xs) = agregar x (asdasd xs)\n\nop = (.&.)\n\ndoit x [] w = False\ndoit x (a:as) w =\n let t = op a x in\n if t /= a && (Map.findWithDefault 0 t w) > 0 then\n True\n else\n doit x as w\n\nsolve::String -> String\nsolve ss =\n let (n:x:a) = Prelude.map toint $ words ss in\n let w = asdasd a in\n if (Map.size w) < n then\n \"0\\n\"\n else\n if doit x a w then\n \"1\\n\"\n else\n let ww = asdasd (map (\\t -> op t x) a) in\n if (Map.size ww) < n then\n \"2\\n\"\n else\n \"-1\\n\"\n\nmain = interact solve\n"}, {"source_code": "-- import Data.Counter (count, empty)\nimport qualified Data.Map as M\nimport Data.Bits ((.&.))\n\n\ncount :: [Int] -> M.Map Int Int\ncount = foldr (\\k -> M.insertWith (+) k 1) M.empty\n\nmain = do\n n:x:[] <- fmap (map read . words) getLine\n a <- fmap (count . map read . words) getLine\n if M.size a < n\n then print 0\n else if any (\\v -> (v /= v .&. x) && M.member (v .&. x) a) $ M.keys a\n then print 1\n else if n > (M.size $ M.mapKeys (.&. x) a)\n then print 2\n else print (-1)"}], "negative_code": [{"source_code": "import Data.Bits\nimport qualified Data.Map.Strict as Map\n\ntoint s = (read s) :: Int\n\nagregar x m = Map.insertWith (+) x 1 m\nquitar :: Integer -> (Map.Map Integer Integer) -> (Map.Map Integer Integer)\nquitar x m = Map.insertWith (+) x (-1) m\n\nasdasd [] = Map.fromList []\nasdasd (x:xs) = agregar x (asdasd xs)\n\nop = (.&.)\n\ndoit x [] w = False\ndoit x (a:as) w =\n let t = op a x in\n if t /= a && (Map.findWithDefault 0 t w) > 0 then\n True\n else\n doit x as w\n\nsolve::String -> String\nsolve ss =\n let (n:x:a) = Prelude.map toint $ words ss in\n let w = asdasd a in\n if (Map.size w) < n then\n \"0\\n\"\n else\n if doit x a w then\n \"1\\n\"\n else\n let ww = asdasd (map (\\t -> op t x) a) in\n if (Map.size w) < n then\n \"2\\n\"\n else\n \"-1\\n\"\n\nmain = interact solve\n"}], "src_uid": "f4bb0b8f285b0c8cbaf469964505cc56"} {"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = output . solve . drop 2 . map (fst . fromJust . C.readInt) . C.words =<< B.getContents\n\noutput :: Bool -> IO ()\noutput True = putStrLn \"NO\"\noutput False = putStrLn \"YES\"\n\nsolve :: [Int] -> Bool\nsolve [] = True\nsolve (n:x) = let (a, s) = splitAt n x\n r = sort $ filter (> 0) a\n m = sort $ map abs $ filter (< 0) a\n in check r m && solve s\n\ncheck :: [Int] -> [Int] -> Bool\ncheck [] _ = False\ncheck _ [] = False\ncheck (a:ax) (b:bx) | a == b = True\n | a < b = check ax (b:bx)\n | otherwise = check (a:ax) bx\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM)\nimport Data.List (nub)\n\nmain = do\n (map (read :: String -> Int) . words -> [n, m]) <- getLine\n xs <- forM [1..m] $ \\i -> do\n (map abs . nub . map (read :: String -> Int) . tail . words -> x) <- getLine\n return x\n let f True _ = True\n f False x = length x == length (nub x)\n if foldl f False xs then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport qualified Data.Set as S\n\nmain = do\n [nu, ng] <- fmap readInts B.getLine\n gs <- replicateM ng $ fmap (tail . readInts) B.getLine\n putStr $ if solve gs then \"YES\" else \"NO\"\n\nsolve = any (\\g -> let s = S.fromList g in all (\\m -> S.notMember (-m) s) g)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.IntSet (fromList, intersection, null)\nimport Data.List (partition, unfoldr)\nimport Prelude hiding (null)\n\ngetInts::IO [Int]\ngetInts = fmap (unfoldr readOne) BS.getLine where\n readOne s = do\n (x , s') <- BS.readInt s\n return (x, BS.drop 1 s')\n\nmain :: IO ()\nmain = do\n [_, m] <- getInts\n groups <- replicateM m getInts\n putStrLn $ if any traitor groups then \"YES\" else \"NO\" where\n traitor nums = let (pos, fmap negate -> neg) = partition (> 0) $ tail nums\n in null (fromList pos `intersection` fromList neg)\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport Data.Set\nimport Control.Monad\nimport Data.Set as S\nimport Prelude as P\n\n\nf (b, set) x | S.member (-1*x) set = (b && False, insert x set)\n | otherwise = (b || False, insert x set)\n\n\n\nmain = do\n (fmap (read::String -> Int) . words -> [n, m]) <- getLine\n (P.map (P.map (read :: String -> Int) . tail. words) -> ls) <- replicateM m getLine\n let g = P.foldl f (True, S.empty)\n let res = P.map (fst . (\\ xs -> if (size $ snd $ g xs) == 1 then (True, S.empty) else g xs)) ls \n if (or res)\n then putStrLn \"YES\" \n else putStrLn \"NO\"\n \n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport qualified Data.Set as S\n\nmain = do\n [nu, ng] <- fmap readInts B.getLine\n gs <- replicateM ng $ fmap (tail . readInts) B.getLine\n print $ if solve gs then \"YES\" else \"NO\"\n\nsolve = any (\\g -> let s = S.fromList g in all (\\m -> S.notMember (-m) s) g)\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport Data.Set\nimport Control.Monad\nimport Data.Set as S\nimport Prelude as P\n\n\nf (b, set) x | S.member (-1*x) set = (b && False, set)\n | otherwise = (b || False, insert x set)\n\n\n\nmain = do\n (fmap (read::String -> Int) . words -> [n, m]) <- getLine\n (P.map (P.map (read :: String -> Int) . tail. words) -> ls) <- replicateM m getLine\n let g = P.foldl f (True, S.empty)\n let res = P.map (fst . (\\ xs -> if (size $ snd $ g xs) == 1 then (True, S.empty) else g xs)) ls \n\n if (or res)\n then putStrLn \"YES\" \n else putStrLn \"NO\"\n \n\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport Data.Set\nimport Control.Monad\nimport Data.Set as S\nimport Prelude as P\n\n\nf (b, set) x | S.member (-1*x) set = (b && False, insert x set)\n | otherwise = (b || False, insert x set)\n\n\n\nmain = do\n (fmap (read::String -> Int) . words -> [n, m]) <- getLine\n (P.map (P.map (read :: String -> Int) . tail. words) -> ls) <- replicateM m getLine\n let g = P.foldl f (True, S.empty)\n let res = P.map (fst . (\\ xs -> if (size $ snd $ g xs) == 1 then (True, S.empty) else g xs)) ls \n print res\n if (or res)\n then putStrLn \"YES\" \n else putStrLn \"NO\"\n \n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport Data.List (nub)\n\nmain = do\n (map (read :: String -> Int) . words -> [n, m]) <- getLine\n xs <- forM [1..m] $ \\i -> do\n (map (abs . (read :: String -> Int)) . tail . words -> x) <- getLine\n return x\n let f True _ = True\n f False x = length x == length (nub x)\n if foldl f False xs then\n putStrLn \"YES\"\n else\n putStrLn \"NO\"\n"}], "src_uid": "f110b9351fe8ff20676d11ecfc92aee3"} {"source_code": "import Control.Applicative\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n\t_ <- readLn :: IO Int\n\tw <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\tputStrLn . show $ solve w\n\nsolve :: [Int] -> Int\nsolve w = f 0 0 . elems $ arr\n\twhere\n\t\tarr\t\t\t\t\t= accumArray (+) 0 (0, 100 + 10 ^ 6) $ [(x, 1) | x <- w] :: UArray Int Int\n\t\tf ans _ []\t\t\t= ans\n\t\tf ans k (x : xs)\t= f (ans + ((k + x) .&. 1)) ((k + x) `shiftR` 1) xs\n\n{--import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array.IO\n\nsolve :: [Int] -> IO Int\nsolve w = do\n arr <- newArray (0,2*10^6) False :: IO (IOArray Int Bool)\n mapM (add arr) w\n length . filter id <$> getElems arr\n where\n add arr i = do\n x <- readArray arr i\n if x\n then do\n writeArray arr i False\n add arr (i+1)\n else writeArray arr i True\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print =<< solve w--}\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Array \nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nprocess::Int->[Int]->Int\nprocess n [] = n\nprocess n [0] = n\nprocess n (a:b:as) | a==0 = process n (b:as)\n | even a = process n ((b+ div a 2):as)\n\t | otherwise = process (n+1) ((b+ div a 2):as)\n\n\nmain= do\n\tgetLine\n\ts<- map ( fst.fromJust.C.readInt).C.words <$> C.getLine ::IO [Int]\n\tlet q = 50+(maximum s)\n\tlet a= accumArray (+) 0 (0,(min q 1000050)) $ zip s (repeat 1)\n\tprint $ process 0 $ elems a"}, {"source_code": "import Control.Applicative\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n\t_ <- readLn :: IO Int\n\tw <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine\n\tputStrLn . show $ solve w\n\nsolve :: [Int] -> Int\nsolve w = f 0 0 . elems $ arr\n\twhere\n\t\tarr\t\t\t\t\t= accumArray (+) 0 (0, 100 + 10 ^ 6) $ [(x, 1) | x <- w] :: UArray Int Int\n\t\tf ans _ []\t\t\t= ans\n\t\tf ans k (x : xs)\t= f (ans + ((k + x) `mod` 2)) ((k + x) `div` 2) xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array.IO\n\nsolve :: [Int] -> IO Int\nsolve w = do\n arr <- newArray (0,2*10^6) False :: IO (IOArray Int Bool)\n mapM (add arr) w\n length . filter id <$> getElems arr\n where\n add arr i = do\n x <- readArray arr i\n if x\n then do\n writeArray arr i False\n add arr (i+1)\n else writeArray arr i True\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print =<< solve w\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [Int] -> Int -> Int\nsolve [] _ = 0\nsolve (x:xs) pre\n | x == pre = solve xs (pre+1)\n | x == pre-1 = 1 + solve xs pre\n | otherwise = 1 + solve xs x\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print $ solve w (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve [] cnt _\n | cnt > 2 = (cnt-1) `div` 2\n | otherwise = 0\nsolve (x:xs) cnt pre\n | x == pre = solve xs (cnt+1) x\n | cnt > 1 && x == pre + 1 = (cnt-1) `div` 2 + solve xs 2 x\n | otherwise = 1 + solve xs 1 x\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print $ solve w 0 (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [Int] -> Int -> Int\nsolve [] _ = 0\nsolve (x:xs) pre\n | x == pre = solve xs (pre+1)\n | otherwise = 1 + solve xs x\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print $ solve w (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve [] cnt _\n | cnt > 2 = cnt `div` 2\n | otherwise = 0\nsolve (x:xs) cnt pre\n | x == pre = solve xs (cnt+1) x\n | cnt > 1 && x == pre + 1 = (cnt-1) `div` 2 + solve xs 2 x\n | otherwise = 1 + solve xs 1 x\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print $ solve w 0 (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve [] _ _ = 0\nsolve (x:xs) cnt pre\n | x == pre = solve xs (cnt+1) x\n | cnt > 0 && x == pre + 1 = cnt `div` 2 + solve xs 1 x\n | otherwise = 1 + solve xs 0 x\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print $ solve w 0 (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve [] cnt _\n | cnt > 2 = (cnt-1) `div` 2\n | otherwise = 0\nsolve (x:xs) cnt pre\n | x == pre = solve xs (cnt+1) x\n | cnt > 1 && x == pre + 1 = (cnt-1) `div` 2 + solve xs 2 x\n | otherwise = 1 + (cnt-1) `div` 2 + solve xs 1 x\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n w <- map fst . mapMaybe C.readInt . C.words <$> C.getLine\n print $ solve w 1 (-1)\n"}], "src_uid": "089eea1841ef10064647e61094c374fd"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\nimport Data.Char (ord, chr)\nimport qualified Data.IntMap.Strict as Map\nimport qualified Data.ByteString.Char8 as DBS\nimport Data.Bits\nimport System.Random\n\ninfinit = 10000000\n\ndata Treap = Nil | Node Int Int Int Int Int Treap Treap deriving Show\n-------------------------x---y--max--sz--id--left-right\n\ntsomenode x i !seed = Node x seed x 1 i Nil Nil\n\ntnull Nil = True\ntnull _ = False\n\ntx Nil = 0\ntx (Node !x _ _ _ _ _ _) = x\n\nty Nil = 0\nty (Node _ !y _ _ _ _ _) = y\n\ntmax Nil = -infinit\ntmax (Node _ _ !mx _ _ _ _) = mx\n\ntsize Nil = 0\ntsize (Node _ _ _ !sz _ _ _) = sz\n\ntidnum Nil = 0\ntidnum (Node _ _ _ _ !i _ _) = i\n\ntleft Nil = Nil\ntleft (Node _ _ _ _ _ l _) = l\n\ntright Nil = Nil\ntright (Node _ _ _ _ _ _ r) = r\n\ntrecalc Nil = Nil\ntrecalc (Node x y _ _ i l r) = Node x y (max x (max (tmax l) (tmax r))) (1 + (tsize l) + (tsize r)) i l r\n\ntsplit root k\n | (tnull root) = (Nil, Nil)\n | k <= ((tsize.tleft) root) =\n let (l, r) = tsplit (tleft root) k\n nroot = trecalc (Node (tx root) (ty root) 0 0 (tidnum root) r (tright root)) in\n (l, nroot)\n | otherwise =\n let (l, r) = tsplit (tright root) (k - ((tsize.tleft) root) - 1)\n nroot = trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tleft root) l) in\n (nroot, r)\n\ntadd root n k\n | (tnull root) = n\n | (ty n) > (ty root) =\n let (l, r) = tsplit root (k - 1) in\n trecalc (Node (tx n) (ty n) 0 0 (tidnum n) l r)\n | k <= ((tsize.tleft) root) + 1 =\n trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tadd (tleft root) n k) (tright root))\n | otherwise =\n trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tleft root) (tadd (tright root) n (k - ((tsize.tleft) root) - 1)))\n\nmaxInInterval t !left !right\n | tnull t = -infinit\n | left > right = -infinit\n | (left == 1) && (right == (tsize t)) = tmax t\n | otherwise =\n let ltree = tleft t\n rtree = tright t\n lsz = tsize ltree\n lszpo = lsz + 1\n rsz = tsize rtree\n lmax = maxInInterval ltree left (min lsz right)\n osl = left - lszpo\n osr = right - lszpo\n rmax = maxInInterval rtree (max osl 1) (min osr rsz)\n cmax = if (left <= lszpo) && (right >= lszpo) then (tx t) else (-infinit) in\n (max cmax) $ max lmax rmax\n\n\nbinSrch t a rhead !left !right\n | left > right = rhead\n | otherwise =\n let mid = left + ((right - left) `div` 2)\n cand = maxInInterval t mid rhead in\n if cand < a\n then min mid (binSrch t a rhead left (mid - 1))\n else binSrch t a rhead (mid + 1) right\n\nsolve [] _ t _ = t\nsolve ((a,c):acs) !n t g =\n let pos = (binSrch t a n (max 1 (n - c)) n)\n (nr, ng) = randomR (1, 32767) g in\n solve acs (n + 1) (tadd t (tsomenode a n nr) pos) ng\n\nextractInt Nothing = 0\nextractInt (Just (a, _)) = a\n\nreadNumbers 0 = return []\nreadNumbers !n = do\n [a,c] <- fmap ( (map (\\x -> extractInt (DBS.readInt x))) . DBS.words ) DBS.getLine\n rest <- readNumbers (n - 1)\n return ((a,c):rest)\n\ninorder t sofar\n | tnull t = sofar\n | otherwise =\n let sf2 = inorder (tright t) sofar\n sf3 = (tidnum t):sf2 in\n inorder (tleft t) sf3\n\nmain = do\n n <- readLn::IO Int\n v <- readNumbers n\n g <- newStdGen\n DBS.putStrLn $ DBS.unwords $ map (DBS.pack.show) (inorder (solve v 1 Nil g) [])", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\nimport Data.Char (ord, chr)\nimport qualified Data.IntMap.Strict as Map\nimport qualified Data.ByteString.Char8 as DBS\nimport Data.Bits\nimport System.Random\n\ninfinit = 10000000\n\ndata Treap = Nil | Node Int Int Int Int Int Treap Treap deriving Show\n-------------------------x---y--max--sz--id--left-right\n\nseedme !seed = (.&.) (shiftR (seed * 214013 + 2531011) 16) 32767\n\ntsomenode x i !seed = Node x (seedme seed) x 1 i Nil Nil\n\ntnull Nil = True\ntnull _ = False\n\ntx Nil = 0\ntx (Node !x _ _ _ _ _ _) = x\n\nty Nil = 0\nty (Node _ !y _ _ _ _ _) = y\n\ntmax Nil = -infinit\ntmax (Node _ _ !mx _ _ _ _) = mx\n\ntsize Nil = 0\ntsize (Node _ _ _ !sz _ _ _) = sz\n\ntidnum Nil = 0\ntidnum (Node _ _ _ _ !i _ _) = i\n\ntleft Nil = Nil\ntleft (Node _ _ _ _ _ l _) = l\n\ntright Nil = Nil\ntright (Node _ _ _ _ _ _ r) = r\n\ntrecalc Nil = Nil\ntrecalc (Node x y _ _ i l r) = Node x y (max x (max (tmax l) (tmax r))) (1 + (tsize l) + (tsize r)) i l r\n\ntsplit root k\n | (tnull root) = (Nil, Nil)\n | k <= ((tsize.tleft) root) =\n let (l, r) = tsplit (tleft root) k\n nroot = trecalc (Node (tx root) (ty root) 0 0 (tidnum root) r (tright root)) in\n (l, nroot)\n | otherwise =\n let (l, r) = tsplit (tright root) (k - ((tsize.tleft) root) - 1)\n nroot = trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tleft root) l) in\n (nroot, r)\n\ntadd root n k\n | (tnull root) = n\n | (ty n) > (ty root) =\n let (l, r) = tsplit root (k - 1) in\n trecalc (Node (tx n) (ty n) 0 0 (tidnum n) l r)\n | k <= ((tsize.tleft) root) + 1 =\n trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tadd (tleft root) n k) (tright root))\n | otherwise =\n trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tleft root) (tadd (tright root) n (k - ((tsize.tleft) root) - 1)))\n\nmaxInInterval t !left !right\n | tnull t = -infinit\n | left > right = -infinit\n | (left == 1) && (right == (tsize t)) = tmax t\n | otherwise =\n let ltree = tleft t\n rtree = tright t\n lsz = tsize ltree\n lszpo = lsz + 1\n rsz = tsize rtree\n lmax = maxInInterval ltree left (min lsz right)\n osl = left - lszpo\n osr = right - lszpo\n rmax = maxInInterval rtree (max osl 1) (min osr rsz)\n cmax = if (left <= lszpo) && (right >= lszpo) then (tx t) else (-infinit) in\n (max cmax) $ max lmax rmax\n\n\nbinSrch t a rhead !left !right\n | left > right = rhead\n | otherwise =\n let mid = left + ((right - left) `div` 2)\n cand = maxInInterval t mid rhead in\n if cand < a\n then min mid (binSrch t a rhead left (mid - 1))\n else binSrch t a rhead (mid + 1) right\n\nsolve [] _ t _ = t\nsolve ((a,c):acs) !n t g =\n let pos = (binSrch t a n (max 1 (n - c)) n)\n (nr, ng) = randomR (1, 10000000) g in\n solve acs (n + 1) (tadd t (tsomenode a n nr) pos) ng\n\nextractInt Nothing = 0\nextractInt (Just (a, _)) = a\n\nreadNumbers 0 = return []\nreadNumbers !n = do\n [a,c] <- fmap ( (map (\\x -> extractInt (DBS.readInt x))) . DBS.words ) DBS.getLine\n rest <- readNumbers (n - 1)\n return ((a,c):rest)\n\ninorder t sofar\n | tnull t = sofar\n | otherwise =\n let sf2 = inorder (tright t) sofar\n sf3 = (tidnum t):sf2 in\n inorder (tleft t) sf3\n\nmain = do\n n <- readLn::IO Int\n v <- readNumbers n\n g <- newStdGen\n DBS.putStrLn $ DBS.unwords $ map (DBS.pack.show) (inorder (solve v 1 Nil g) [])"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\nimport Data.Char (ord, chr)\nimport qualified Data.IntMap.Strict as Map\nimport qualified Data.ByteString.Char8 as DBS\nimport Data.Bits\nimport System.Random\n\ninfinit = 10000000\n\ndata Treap = Nil | Node Int Int Int Int Int Treap Treap deriving Show\n-------------------------x---y--max--sz--id--left-right\n\ntsomenode x i !seed = Node x seed x 1 i Nil Nil\n\ntnull Nil = True\ntnull _ = False\n\ntx Nil = 0\ntx (Node !x _ _ _ _ _ _) = x\n\nty Nil = 0\nty (Node _ !y _ _ _ _ _) = y\n\ntmax Nil = -infinit\ntmax (Node _ _ !mx _ _ _ _) = mx\n\ntsize Nil = 0\ntsize (Node _ _ _ !sz _ _ _) = sz\n\ntidnum Nil = 0\ntidnum (Node _ _ _ _ !i _ _) = i\n\ntleft Nil = Nil\ntleft (Node _ _ _ _ _ l _) = l\n\ntright Nil = Nil\ntright (Node _ _ _ _ _ _ r) = r\n\ntrecalc Nil = Nil\ntrecalc (Node x y _ _ i l r) = Node x y (max x (max (tmax l) (tmax r))) (1 + (tsize l) + (tsize r)) i l r\n\ntsplit root k\n | (tnull root) = (Nil, Nil)\n | k <= ((tsize.tleft) root) =\n let (l, r) = tsplit (tleft root) k\n nroot = trecalc (Node (tx root) (ty root) 0 0 (tidnum root) r (tright root)) in\n (l, nroot)\n | otherwise =\n let (l, r) = tsplit (tright root) (k - ((tsize.tleft) root) - 1)\n nroot = trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tleft root) l) in\n (nroot, r)\n\ntadd root n k\n | (tnull root) = n\n | (ty n) > (ty root) =\n let (l, r) = tsplit root (k - 1) in\n trecalc (Node (tx n) (ty n) 0 0 (tidnum n) l r)\n | k <= ((tsize.tleft) root) + 1 =\n trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tadd (tleft root) n k) (tright root))\n | otherwise =\n trecalc (Node (tx root) (ty root) 0 0 (tidnum root) (tleft root) (tadd (tright root) n (k - ((tsize.tleft) root) - 1)))\n\nmaxInInterval t !left !right\n | tnull t = -infinit\n | left > right = -infinit\n | (left == 1) && (right == (tsize t)) = tmax t\n | otherwise =\n let ltree = tleft t\n rtree = tright t\n lsz = tsize ltree\n lszpo = lsz + 1\n rsz = tsize rtree\n lmax = maxInInterval ltree left (min lsz right)\n osl = left - lszpo\n osr = right - lszpo\n rmax = maxInInterval rtree (max osl 1) (min osr rsz)\n cmax = if (left <= lszpo) && (right >= lszpo) then (tx t) else (-infinit) in\n (max cmax) $ max lmax rmax\n\n\nbinSrch t a rhead !left !right\n | left > right = rhead\n | otherwise =\n let mid = left + ((right - left) `div` 2)\n cand = maxInInterval t mid rhead in\n if cand < a\n then min mid (binSrch t a rhead left (mid - 1))\n else binSrch t a rhead (mid + 1) right\n\nsolve [] _ t _ = t\nsolve ((a,c):acs) !n t g =\n let pos = (binSrch t a n (max 1 (n - c)) n)\n (nr, ng) = randomR (1, 10000000) g in\n solve acs (n + 1) (tadd t (tsomenode a n nr) pos) ng\n\nextractInt Nothing = 0\nextractInt (Just (a, _)) = a\n\nreadNumbers 0 = return []\nreadNumbers !n = do\n [a,c] <- fmap ( (map (\\x -> extractInt (DBS.readInt x))) . DBS.words ) DBS.getLine\n rest <- readNumbers (n - 1)\n return ((a,c):rest)\n\ninorder t sofar\n | tnull t = sofar\n | otherwise =\n let sf2 = inorder (tright t) sofar\n sf3 = (tidnum t):sf2 in\n inorder (tleft t) sf3\n\nmain = do\n n <- readLn::IO Int\n v <- readNumbers n\n g <- newStdGen\n DBS.putStrLn $ DBS.unwords $ map (DBS.pack.show) (inorder (solve v 1 Nil g) [])"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char (ord, chr)\nimport qualified Data.IntMap.Strict as Map\nimport qualified Data.ByteString.Char8 as DBS\nimport Data.Bits\n\ninfinit = 10000000\n\ndata Treap = Nil | Node Int Int Int Int Int Treap Treap deriving Show\n-------------------------x---y--max--sz--id--left-right\n\nseedme (s1,s2,s3) = xor (1237 * s1 + 5129 * s2 + 3287 * s3 + 12485) 73813\n\ntsomenode x i seed = Node x (seedme seed) x 1 i Nil Nil\n\ntnull Nil = True\ntnull _ = False\n\ntx Nil = 0\ntx (Node x _ _ _ _ _ _) = x\n\nty Nil = 0\nty (Node _ y _ _ _ _ _) = y\n\ntmax Nil = -infinit\ntmax (Node _ _ mx _ _ _ _) = mx\n\ntsize Nil = 0\ntsize (Node _ _ _ sz _ _ _) = sz\n\ntidnum Nil = 0\ntidnum (Node _ _ _ _ i _ _) = i\n\ntleft Nil = Nil\ntleft (Node _ _ _ _ _ l _) = l\n\ntright Nil = Nil\ntright (Node _ _ _ _ _ _ r) = r\n\ntrecalc Nil = Nil\ntrecalc (Node x y _ _ i l r) = Node x y (max x (max (tmax l) (tmax r))) (1 + (tsize l) + (tsize r)) i l r\n\ntsplit root k\n | (tnull root) = (Nil, Nil)\n | k <= ((tsize.tleft) root) =\n let (l, r) = tsplit (tleft root) k\n nroot = trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) r (tright root)) in\n (l, nroot)\n | otherwise =\n let (l, r) = tsplit (tright root) (k - ((tsize.tleft) root) - 1)\n nroot = trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) (tleft root) l) in\n (nroot, r)\n\ntadd root n k\n | (tnull root) = n\n | (ty n) > (ty root) =\n let (l, r) = tsplit root (k - 1) in\n trecalc (Node (tx n) (ty n) (tmax n) (tsize n) (tidnum n) l r)\n | k <= ((tsize.tleft) root) + 1 =\n trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) (tadd (tleft root) n k) (tright root))\n | otherwise =\n trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) (tleft root) (tadd (tright root) n (k - ((tsize.tleft) root) - 1)))\n\nmaxInInterval t left right\n | tnull t = -infinit\n | left > right = -infinit\n | (left == 1) && (right == (tsize t)) = tmax t\n | otherwise =\n let ltree = tleft t\n rtree = tright t\n lsz = tsize ltree\n lszpo = lsz + 1\n rsz = tsize rtree\n lmax = maxInInterval ltree left (min lsz right)\n osl = left - lszpo\n osr = right - lszpo\n rmax = maxInInterval rtree (max osl 1) (min osr rsz)\n cmax = if (left <= lszpo) && (right >= lszpo) then (tx t) else (-infinit) in\n (max cmax) $ max lmax rmax\n\n\nbinSrch t a rhead left right\n | left > right = rhead\n | otherwise =\n let mid = left + ((right - left) `div` 2)\n cand = maxInInterval t mid rhead in\n if cand < a\n then min mid (binSrch t a rhead left (mid - 1))\n else binSrch t a rhead (mid + 1) right\n\nsolve [] _ t = t\nsolve ((a,c):acs) n t =\n let pos = (binSrch t a n (max 1 (n - c - 1)) n) in\n solve acs (n + 1) (tadd t (tsomenode a n (a,c,n)) pos)\n\nextractInt Nothing = 0\nextractInt (Just (a, _)) = a\n\nreadNumbers 0 = return []\nreadNumbers n = do\n [a,c] <- fmap ( (map (\\x -> extractInt (DBS.readInt x))) . DBS.words ) DBS.getLine\n rest <- readNumbers (n - 1)\n return ((a,c):rest)\n\ninorder t sofar\n | tnull t = sofar\n | otherwise =\n let sf2 = inorder (tright t) sofar\n sf3 = (tidnum t):sf2 in\n inorder (tleft t) sf3\n\nmain = do\n n <- readLn::IO Int\n v <- readNumbers n\n DBS.putStrLn $ DBS.unwords $ map (DBS.pack.show) (inorder (solve v 1 Nil) [])\n"}, {"source_code": "import Data.List\nimport Data.Char (ord, chr)\nimport qualified Data.IntMap.Strict as Map\nimport qualified Data.ByteString.Char8 as DBS\nimport Data.Bits\n\ninfinit = 10000000\n\ndata Treap = Nil | Node Int Int Int Int Int Treap Treap deriving Show\n-------------------------x---y--max--sz--id--left-right\n\nseedme (s1,s2,s3) = xor (1237 * s1 + 5129 * s2 + 3287 * s3 + 12485) 73813\n\ntsomenode x i seed = Node x (seedme seed) x 1 i Nil Nil\n\ntnull Nil = True\ntnull _ = False\n\ntx Nil = 0\ntx (Node x _ _ _ _ _ _) = x\n\nty Nil = 0\nty (Node _ y _ _ _ _ _) = y\n\ntmax Nil = -infinit\ntmax (Node _ _ mx _ _ _ _) = mx\n\ntsize Nil = 0\ntsize (Node _ _ _ sz _ _ _) = sz\n\ntidnum Nil = 0\ntidnum (Node _ _ _ _ i _ _) = i\n\ntleft Nil = Nil\ntleft (Node _ _ _ _ _ l _) = l\n\ntright Nil = Nil\ntright (Node _ _ _ _ _ _ r) = r\n\ntrecalc Nil = Nil\ntrecalc (Node x y _ _ i l r) = Node x y (max x (max (tmax l) (tmax r))) (1 + (tsize l) + (tsize r)) i l r\n\ntsplit root k\n | (tnull root) = (Nil, Nil)\n | k <= ((tsize.tleft) root) =\n let (l, r) = tsplit (tleft root) k\n nroot = trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) r (tright root)) in\n (l, nroot)\n | otherwise =\n let (l, r) = tsplit (tright root) (k - ((tsize.tleft) root) - 1)\n nroot = trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) (tleft root) l) in\n (nroot, r)\n\ntadd root n k\n | (tnull root) = n\n | (ty n) > (ty root) =\n let (l, r) = tsplit root (k - 1) in\n trecalc (Node (tx n) (ty n) (tmax n) (tsize n) (tidnum n) l r)\n | k <= ((tsize.tleft) root) + 1 =\n trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) (tadd (tleft root) n k) (tright root))\n | otherwise =\n trecalc (Node (tx root) (ty root) (tmax root) (tsize root) (tidnum root) (tleft root) (tadd (tright root) n (k - ((tsize.tleft) root) - 1)))\n\nmaxInInterval t left right\n | tnull t = -infinit\n | left > right = -infinit\n | (right - left + 1) == (tsize t) = tmax t\n | otherwise =\n let ltree = tleft t\n rtree = tright t\n lsz = tsize ltree\n lszpo = lsz + 1\n rsz = tsize rtree\n lmax = maxInInterval ltree left (min lsz right)\n osl = left - lszpo\n osr = right - lszpo\n rmax = maxInInterval rtree (max osl 1) (min osr rsz)\n cmax = if (left <= lszpo) && (right >= lszpo) then (tx t) else (-infinit) in\n (max cmax) $ max lmax rmax\n\n\nbinSrch t a rhead left right\n | left > right = infinit\n | otherwise =\n let mid = left + ((right - left) `div` 2)\n cand = maxInInterval t mid rhead in\n if cand < a\n then min mid (binSrch t a rhead left (mid - 1))\n else binSrch t a rhead (mid + 1) right\n\nsolve [] _ t = t\nsolve ((a,c):acs) n t =\n let pos = (binSrch t a n (max 1 (n - c)) n) in\n solve acs (n + 1) (tadd t (tsomenode a n (a,c,n)) pos)\n\nextractInt Nothing = 0\nextractInt (Just (a, _)) = a\n\nreadNumbers 0 = return []\nreadNumbers n = do\n [a,c] <- fmap ( (map (\\x -> extractInt (DBS.readInt x))) . DBS.words ) DBS.getLine\n rest <- readNumbers (n - 1)\n return ((a,c):rest)\n\ninorder t sofar\n | tnull t = sofar\n | otherwise =\n let sf2 = inorder (tright t) sofar\n sf3 = (tidnum t):sf2 in\n inorder (tleft t) sf3\n\nmain = do\n n <- readLn::IO Int\n v <- readNumbers n\n DBS.putStrLn $ DBS.unwords $ map (DBS.pack.show) (inorder (solve v 1 Nil) [])\n"}], "src_uid": "1d860eb2d9099a3f5134ec5c350f78b1"} {"source_code": "import Control.Applicative\n\nslice n xs = map (take n) $ takeWhile (\\x -> x /= []) (iterate (drop n) xs)\n\nparse (x : y : z : xs) = if (x == y && y == z) then 1 else 0\nparse _ = 0\n\nsolve n s = sum $ (map (parse . reverse) $ init (slice n s))\n\nmain =\n\tdo n <- read <$> getLine\n\t s <- getLine\n\t print $ solve n s\n", "positive_code": [{"source_code": "main = interact $ show . fi . lines\nfi (n:s:[]) = go (read n) s\ngo n s | length s > n = (if eq == True then 1 else 0) + (go n $ drop n s)\n | otherwise = 0\n where eq = foldl (\\i x -> i || all x (drop (n-3) $ take n s)) False [(=='b'),(=='a')]\n"}, {"source_code": "\nsolve :: Int -> String -> Int\nsolve n s = length $ filter good $ init $ group s\n where\n good as = case reverse as of\n (a1 : a2 : a3 : _) -> a1 == a2 && a2 == a3\n group [] = []\n group xs = take n xs : group (drop n xs)\n\nmain :: IO ()\nmain = do\n n <- readLn\n s <- getLine\n print $ solve n s"}, {"source_code": "import Control.Applicative\n\nmain = f <$> readLn <*> getLine >>= print\n\nf n (_:cs) = length.filter (p.drop (n-4)) $ slices n cs\n\np [x,y,z,_] = x==y && y==z\np _ = False\n\nslices :: Int -> [a] -> [[a]]\nslices n xs = map(take n).takeWhile(not.null) $ iterate (drop n) xs\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n n <- readLine\n s <- getLine\n print $ solve n s\n\nsolve :: Int -> String -> Int\nsolve n s = length $ filter (check n) (split n (tail s))\n\nsplit n [] = []\nsplit n l = take n l:split n (drop n l)\n\ncheck n l | length l < n = False\n | otherwise = case reverse l of\n _:'a':'a':'a':_ -> True\n _:'b':'b':'b':_ -> True\n _ -> False\n\n"}, {"source_code": "main = interact ( show . af . conv . lines )\nconv l = ( read . head $ l, last l )\nh = splitAt\nf n l | length l < n = 0\n | otherwise = g ( reverse $ fst ( h n l ) ) + f n ( snd ( h n l ) )\ng ( a:b:c:d:t ) | b == c && c == d = 1\n | otherwise = 0\naf ( x,y ) = f x ( tail y )\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nmain = do\n n <- readLine\n s <- getLine\n print $ solve n s\n\nsolve :: Int -> String -> Int\nsolve n s = length $ filter (check n) (split n (tail s))\n\nsplit n [] = []\nsplit n l = take n l:split n (drop n l)\n\ncheck n l | length l < n = False\n | otherwise = (==1) $ length $ group $ take (n-1) l\n"}, {"source_code": "main = interact $ show . fi . lines\nfi (n:s:[]) = go (read n) s\ngo n s | length s >= n = (if eq == True then 1 else 0) + (go n $ drop n s)\n | otherwise = 0\n where eq = foldl (\\i x -> i || all x (drop (n-3) $ take n s)) False [(=='b'),(=='a')]\n"}], "src_uid": "5606799ab5345bb9501fa6535e5abef9"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Data.Maybe\r\n\r\ntype Set = S.Set Integer\r\n\r\nsolve :: String -> String -> Bool\r\nsolve a b = aux (n-1) False\r\n\r\n\r\n\twhere\r\n\t\tn = length a\r\n\t\taA = A.listArray (0, n-1) a\r\n\t\tbA = A.listArray (0, n-1) b\r\n\t\taux i inv\r\n\t\t\t| i == -1 = True\r\n\t\t\t| test /= inv = aux (i-1) inv\r\n\t\t\t| test == inv && S.member i set = aux (i-1) (not inv)\r\n\t\t\t| otherwise = False\r\n\t\t\twhere\r\n\t\t\t\ttest = aA ! i == bA ! i\r\n\r\n\t\tnum0_1 [] _ _ = []\r\n\t\tnum0_1 ('0':xs) i j = (i+1, j):num0_1 xs (i+1) j\r\n\t\tnum0_1 ('1':xs) i j = (i, j+1):num0_1 xs i (j+1)\r\n\t\tset = S.fromList [i | (i, (x, y))<-zip [0..] (num0_1 a 0 0), x==y]\r\n\r\n\r\nshowR :: Bool -> IO ()\r\nshowR False = putStrLn \"NO\"\r\nshowR True = putStrLn \"YES\"\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\ta <- getLine\r\n\t\tb <- getLine\r\n\t\tshowR $ solve a b\r\n", "positive_code": [{"source_code": "import Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Data.List (find)\r\nimport Data.Maybe (fromMaybe)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n words >>>\r\n drop 1 >>> chunksOf 3 >>> map (solve >>> bool \"NO\" \"YES\") >>> unlines\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (g, gs) = splitAt k xs\r\n in g : chunksOf k gs\r\n\r\ntype CC = (Char, Char) -- pair of chars\r\n\r\ntype PString = [CC] -- string of pair of chars\r\n\r\nsolve :: [String] -> Bool\r\nsolve [_, a, b] =\r\n let (g:gs) = decomp $ zip a b\r\n in all ok gs && uncurry (==) (unzip g)\r\n\r\nok :: PString -> Bool\r\nok = liftA2 (||) (all (uncurry (==))) (not . any (uncurry (==)))\r\n\r\ndecomp :: PString -> [PString]\r\ndecomp = (\\(_, e, es) -> e : es) . foldl extend (0, [], [])\r\n where\r\n extend :: (Int, PString, [PString]) -> CC -> (Int, PString, [PString])\r\n extend (s, g, gs) (ai, bi) =\r\n let s' =\r\n s +\r\n if ai == '0'\r\n then 1\r\n else (-1)\r\n g' = (ai, bi) : g\r\n in if s' == 0\r\n then (0, [], g' : gs)\r\n else (s', g', gs)\r\n"}], "negative_code": [{"source_code": "import Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Data.List (find)\r\nimport Data.Maybe (fromMaybe)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n words >>>\r\n drop 1 >>> chunksOf 3 >>> map (solve >>> bool \"NO\" \"YES\") >>> unlines\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (g, gs) = splitAt k xs\r\n in g : chunksOf k gs\r\n\r\ntype CC = (Char, Char) -- pair of chars\r\n\r\ntype PString = [CC] -- string of pair of chars\r\n\r\nsolve :: [String] -> Bool\r\nsolve [_, a, b] = all ok $ decomp $ zip a b\r\n\r\nok :: PString -> Bool\r\nok = liftA2 (||) (all (uncurry (==))) (not . any (uncurry (==)))\r\n\r\ndecomp :: PString -> [PString]\r\ndecomp = (\\(_, _, e) -> e) . foldr extend (0, [], [])\r\n where\r\n extend :: CC -> (Int, PString, [PString]) -> (Int, PString, [PString])\r\n extend (ai, bi) (s, g, gs) =\r\n let s' =\r\n s +\r\n if ai == '0'\r\n then 1\r\n else (-1)\r\n g' = (ai, bi) : g\r\n in if s' == 0\r\n then (0, [], g' : gs)\r\n else (s', g', gs)\r\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Data.Maybe\r\n\r\ntype Set = S.Set Integer\r\n\r\nsolve :: String -> String -> Bool\r\nsolve a b = aux (n-1) True || aux (n-1) False\r\n\r\n\r\n\twhere\r\n\t\tn = length a\r\n\t\taA = A.listArray (0, n-1) a\r\n\t\tbA = A.listArray (0, n-1) b\r\n\t\taux i inv\r\n\t\t\t| i == -1 = True\r\n\t\t\t| aA ! i /= bA ! i && inv = aux (i-1) inv\r\n\t\t\t| aA ! i == bA ! i && not inv = aux (i-1) inv\r\n\t\t\t| aA ! i == bA ! i && inv && S.member i set = aux (i-1) (not inv)\r\n\t\t\t| aA ! i /= bA ! i && not inv && S.member i set = aux (i-1) (not inv)\r\n\t\t\t| otherwise = False\r\n\r\n\t\tnum0_1 [] _ _ = []\r\n\t\tnum0_1 ('0':xs) i j = (i+1, j):num0_1 xs (i+1) j\r\n\t\tnum0_1 ('1':xs) i j = (i, j+1):num0_1 xs i (j+1)\r\n\t\tset = S.fromList [i | (i, (x, y))<-zip [0..] (num0_1 a 0 0), x==y]\r\n\r\n\r\nshowR :: Bool -> IO ()\r\nshowR False = putStrLn \"NO\"\r\nshowR True = putStrLn \"YES\"\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\ta <- getLine\r\n\t\tb <- getLine\r\n\t\tshowR $ solve a b\r\n"}], "src_uid": "ff95cd4632b2ddf8bb54981634badcae"} {"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Foldable\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let f t = if t `isInfixOf` s then Just (length t) else Nothing\r\n print $ fromMaybe (-1) $ asum $ map f ss\r\n\r\nss :: [String]\r\nss =\r\n [ \"aa\"\r\n , \"aba\"\r\n , \"aca\"\r\n , \"abca\"\r\n , \"acba\"\r\n , \"abbacca\"\r\n , \"accabba\"\r\n ]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, s :: String}\n\ninput :: Scanner TC\ninput = do\n n <- int\n s <- str\n return TC {..}\n\ntype Output = Int\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: TC -> Output\nsolve TC {..} = if null cands then -1 else minimum cands\n where\n cands = [length w | w <- [\"aa\", \"aba\", \"aca\", \"abca\", \"acba\", \"abbacca\", \"accabba\"], w `substring` s]\n\nsubstring _ [] = False\nsubstring w s = w == take (length w) s || substring w (tail s)\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, s :: String}\n\ninput :: Scanner TC\ninput = do\n n <- int\n s <- str\n return TC {..}\n\ntype Output = Int\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: TC -> Output\nsolve TC {..}\n | \"aa\" `elem` g = 2\n | \"b\" `elem` g || \"c\" `elem` g = 3\n | \"bc\" `elem` g || \"cb\" `elem` g = 4\n | otherwise = -1\n where\n g =\n debug\n . groupOn (== 'a')\n . dropWhile (/= 'a')\n . reverse\n . dropWhile (/= 'a')\n $ s\n\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, s :: String}\n\ninput :: Scanner TC\ninput = do\n n <- int\n s <- str\n return TC {..}\n\ntype Output = Int\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: TC -> Output\nsolve TC {..}\n | ('a', 'a') `elem` adjacents s = 2\n | \"b\" `elem` g || \"c\" `elem` g = 3\n | \"bc\" `elem` g || \"cb\" `elem` g = 4\n | otherwise = -1\n where\n g =\n filter ((/= 'a') . head)\n . groupOn (== 'a')\n . dropWhile (/= 'a')\n . reverse\n . dropWhile (/= 'a')\n $ s\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "c2f3d09674190f90c940f134c3e22afe"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . B.readInteger) <$> B.words <$> B.getContents\npair [] = []\npair (x:y:rs) = (x, y) : pair rs\nclamp u v w = max u $ min v $ w\n\nmain = do\n _:xs <- getIntegers\n putStrLn $ if solve xs then \"YES\" else \"NO\"\n\nsolve xs = mod s 2 == 0 && (res1 || res2) where\n s = sum xs\n want = - div s 2\n res1 = go xs want S.empty\n res2 = go (reverse xs) want S.empty\n go [] want s = S.member want s\n go (x:xs) want s = S.member want s || go xs (want+x) (S.insert x s)\n", "positive_code": [{"source_code": "--- 20:36 - 20:40\nimport qualified Data.ByteString.Char8 as B\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . B.readInt) <$> B.words <$> B.getContents\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . B.readInteger) <$> B.words <$> B.getContents\npair [] = []\npair (x:y:rs) = (x, y) : pair rs\nclamp u v w = max u $ min v $ w\n\nmain = do\n _:xs <- getIntegers\n s <- return $ sum xs\n if mod s 2 == 0 && (solve xs (-div s 2) S.empty\n || solve (reverse xs) (-div s 2) S.empty)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nsolve [] want s = S.member want s\nsolve (x:xs) want s = S.member want s || solve xs (want+x) (S.insert x s)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.Int\nimport Data.List\nimport Data.Array\nimport qualified Data.ByteString.Char8 as BS\nreadInt s = let Just (a,_) = BS.readInt s in a\n\nmain = BS.interact $ BS.pack . out . solve . map (fromIntegral . readInt) . tail . BS.words\n\nout True = \"YES\"\nout _ = \"NO\"\n\nsolve :: [Int64] -> Bool\nsolve ns = (solveleft ns) || (solveleft $ reverse ns)\n\nsolveleft ns = or $ map (\\(a, i) -> checkl a i psum) $ ns `zip` [1..]\n where len = length ns\n psum = listArray (1, len) $\n head ns : [ psum ! (i - 1) + a | (a, i) <- (tail ns) `zip` [2..]]\n\ncheckl balance i psum = diff (check_ i $ ir + 1) == 0\n where (il, ir) = bounds psum\n check_ l r\n | r - l <= 1 = l\n | diff mid >= 0 = check_ mid r\n | otherwise = check_ l mid\n where mid = (l + r) `div` 2\n diff mid = (psum ! ir) - 2 * (psum ! mid) + 2 * balance\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.Map.Strict as MP (fromList, Map, alter, member, empty)\n\nreadInt :: B.ByteString -> I.Int64\nreadInt = fromIntegral . fst . M.fromJust . C.readInt\n\ndata MultiSet a = MS (MP.Map a Int)\nempty = MS (MP.empty)\nfromList xs | xs == [] = empty | otherwise = let x:xr = xs in insert x (fromList xr)\nmember x (MS m) = MP.member x m\ninsert x (MS m) = MS (MP.alter msucc x m) where\n msucc Nothing = Just 1\n msucc (Just x) = Just (x + 1)\ndelete x (MS m) = MS (MP.alter mpred x m) where\n mpred (Just 1) = Nothing\n mpred (Just x) = Just (x - 1)\n\nrun _ _ _ _ [] = \"NO\"\nrun sl sr tl tr (r:rs) | sl == sr = \"YES\"\n | sl > sr && even (sl - sr) && ((sl - sr) `div` 2) `member` tl = \"YES\"\n | sl < sr && even (sr - sl) && ((sr - sl) `div` 2) `member` tr = \"YES\"\n | otherwise = run (sl + r) (sr - r) (r `insert` tl) (r `delete` tr) rs\nrunx xs = run 0 (sum xs) empty (fromList xs) xs\n\nmain = B.getLine >> B.getLine >>= putStrLn . runx . map readInt . C.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Lazy as M\nimport Data.Int\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs')\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) mr) $ zip [n + 2, n + 1..] $ scanl1 (+) $ reverse xs')\n where \n xs' = 0:xs ++ [0]\n m = M.fromListWith max $ zip xs' [(1 :: Int64)..]\n mr = M.fromListWith min $ zip xs' [(1 :: Int64)..]\n (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInteger\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Strict as M\nimport Data.Int\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> maybe False (> i) $ M.lookup (hs - s) m) $ zip [1..] $ scanl1 (+) xs')\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) mr) $ zip [n + 2, n + 1..] $ scanl1 (+) $ reverse xs')\n where \n xs' = 0:xs ++ [0]\n m = M.fromListWith max $ zip xs' [(1 :: Int64)..]\n mr = M.fromListWith min $ zip xs' [(1 :: Int64)..]\n (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInteger\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Strict as M\nimport Data.Int\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs')\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) mr) $ zip [n + 2, n + 1..] $ scanl1 (+) $ reverse xs')\n where \n xs' = 0:xs ++ [0]\n m = M.fromListWith max $ zip xs' [(1 :: Int64)..]\n mr = M.fromListWith min $ zip xs' [(1 :: Int64)..]\n (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInteger\nreadInts = fmap readInt . B.words"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.List\nimport Data.Array\nimport qualified Data.ByteString.Char8 as BS\nreadInt s = let Just (a,_) = BS.readInt s in a\n\nmain = BS.interact $ BS.pack . out . solve . map readInt . tail . BS.words\n\nout True = \"YES\"\nout _ = \"NO\"\n\nsolve ns = (solveleft ns) || (solveleft $ reverse ns)\n\nsolveleft ns = or $ map (\\(a, i) -> checkl a i psum) $ ns `zip` [1..]\n where len = length ns\n psum = listArray (1, len) $\n head ns : [ psum ! (i - 1) + a | (a, i) <- (tail ns) `zip` [2..]]\n\ncheckl balance i psum = diff (check_ i $ ir + 1) == 0\n where (il, ir) = bounds psum\n check_ l r\n | r - l <= 1 = l\n | diff mid >= 0 = check_ mid r\n | otherwise = check_ l mid\n where mid = (l + r) `div` 2\n diff mid = (psum ! ir) - 2 * (psum ! mid) + 2 * balance\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.Int as I (Int64)\nimport qualified Data.Set as S (fromList, member, insert, delete, empty)\n\nreadInt :: B.ByteString -> I.Int64\nreadInt = fromIntegral . fst . M.fromJust . C.readInt\n\nrun _ _ _ _ [] = \"NO\"\nrun sl sr tl tr (r:rs) | sl == sr = \"YES\"\n | sl > sr && even (sl - sr) && ((sl - sr) `div` 2) `S.member` tl = \"YES\"\n | sl < sr && even (sr - sl) && ((sr - sl) `div` 2) `S.member` tr = \"YES\"\n | otherwise = run (sl + r) (sr - r) (r `S.insert` tl) (r `S.delete` tr) rs\nrunx xs = run 0 (sum xs) S.empty (S.fromList xs) xs\n\nmain = B.getLine >> B.getLine >>= putStrLn . runx . map readInt . C.words\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Lazy as M\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = any (\\(i, s) -> maybe False (> i) $ M.lookup (hs - s) m) $ zip [1..] $ scanl1 (+) xs\n where \n m = M.fromList $ zip xs [1..]\n (hs, r) = sum xs `quotRem` 2\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Lazy as M\nimport Data.Int\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs')\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs')\n where \n xs' = 0:xs ++ [0]\n m = M.fromList $ zip xs' [(1 :: Int64)..]\n (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInteger\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Lazy as M\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs)\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs)\n where \n m = M.fromList $ zip xs [1..]\n (hs, r) = sum xs `quotRem` 2\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Lazy as M\nimport Data.Int\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> s == hs || maybe False (> i) (M.lookup (hs - s) m)) $ zip [1..] $ scanl1 (+) xs)\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs)\n where \n m = M.fromList $ zip xs [(1 :: Int64)..]\n (hs, r) = sum xs `quotRem` 2 :: (Int64, Int64)\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInteger\nreadInts = fmap readInt . B.words"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Lazy as M\n\nmain = do\n n <- fmap readInt B.getLine\n xs <- fmap readInts B.getLine\n putStrLn $ if solve n xs then \"YES\" else \"NO\"\n\nsolve n xs \n | r /= 0 = False\n | otherwise = (any (\\(i, s) -> maybe False (> i) $ M.lookup (hs - s) m) $ zip [1..] $ scanl1 (+) xs)\n || (any (\\(i, s) -> maybe False (< i) $ M.lookup (hs - s) m) $ zip [n, n - 1..] $ scanl1 (+) $ reverse xs)\n where \n m = M.fromList $ zip xs [1..]\n (hs, r) = sum xs `quotRem` 2\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "src_uid": "27b93795ffc771b47b995e2b83f7b945"} {"source_code": "import Control.Monad (replicateM_)\n\nmain = do\n q <- read <$> getLine :: IO Int\n replicateM_ q (readQuery >>= ((putStrLn . (\\x -> if x then \"YES\" else \"No\")) . solve))\n\nreadQuery :: IO [Int]\nreadQuery = do\n n <- read <$> getLine :: IO Int\n map read . words <$> getLine :: IO [Int]\n\nsolve :: [Int] -> Bool\nsolve = findAmount 2048 1\n where\n findAmount required amount xs\n | length (filter (== required) xs) >= amount = True\n | required == 1 = False\n | otherwise = findAmount (required `div` 2) ((amount - length (filter (== required) xs)) * 2) xs\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport qualified Data.Map.Strict as MS\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input =\n let asnums :: [Int]\n asnums = map read $ words input\n (n:xs) = asnums\n testcases :: [[Int]]\n testcases = parseTestCases xs\n answers = map (boolToString.solve') testcases\n boolToString True = \"YES\"\n boolToString False = \"NO\"\n in intercalate \"\\n\" answers\n\nparseTestCases :: [Int] -> [[Int]]\nparseTestCases [] = []\nparseTestCases (n:xs) =\n let (here,next) = splitAt n xs\n in (here:parseTestCases next)\n\nsolve' :: [Int] -> Bool\nsolve' [] = False\nsolve' inp =\n let baseSet :: MS.Map Int Int\n baseSet = foldl addToMap (MS.empty) inp\n reducedSet = reduceSet baseSet\n addToMap :: MS.Map Int Int -> Int -> MS.Map Int Int\n addToMap map num = MS.insertWith (+) num 1 map\n answer = case (MS.keys reducedSet) of (2048:_) -> True\n _ -> False\n in answer\n\nreduceSet :: MS.Map Int Int -> MS.Map Int Int\nreduceSet inp\n | isEmpty = MS.empty\n | lowestKey == 2048 = inp\n | lowestCount == 1 = reduceSet $ MS.delete lowestKey inp\n | otherwise = reduceSet $ MS.delete lowestKey $ MS.insertWith (+) (lowestKey*2) (div lowestCount 2) inp\n where\n isEmpty = (MS.size inp) == 0\n lowestKey :: Int\n (lowestKey:_) = MS.keys inp\n lowestCount :: Int\n Just lowestCount = MS.lookup lowestKey inp\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Monad ( replicateM_ )\n \nmain = do\n n <- fmap read getLine\n replicateM_ n $ do\n getLine\n s <- fmap (filter (<= 2048) . fmap read . words) getLine\n putStrLn $ if sum s >= 2048 then \"yes\" else \"no\""}, {"source_code": "import Control.Monad ( replicateM_ )\n\nmain = do\n n <- fmap read getLine\n replicateM_ n $ do\n getLine\n s <- fmap (filter (<= 2048) . fmap read . words) getLine\n putStrLn $ if sum s >= 2048 then \"yes\" else \"no\""}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\n\nmain = do\n q <- read <$> getLine :: IO Int\n replicateM_ q (readQuery >>= ((print . (\\x -> if x then \"YES\" else \"No\")) . solve))\n\nreadQuery :: IO [Int]\nreadQuery = do\n n <- read <$> getLine :: IO Int\n map read . words <$> getLine :: IO [Int]\n\nsolve :: [Int] -> Bool\nsolve = findAmount 2048 1\n where\n findAmount required amount xs\n | length (filter (== required) xs) >= amount = True\n | required == 1 = False\n | otherwise = findAmount (required `div` 2) ((amount - length (filter (== required) xs)) * 2) xs\n"}], "src_uid": "b40059fe9cbdb0cc3b64c3e463900849"} {"source_code": "-- 840A\n\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport qualified Data.Binary.Builder as BU\nimport Data.Maybe (fromJust)\nimport Control.Monad (forM_)\nimport Data.List (sortBy)\nimport Data.Array.ST.Safe\nimport Data.Array.IArray\n\nmain = B.getContents >>= output . program . input\n where input = (map . map) (fst . fromJust . B.readInt)\n . map B.words\n . B.lines\n output = putStrLn . unwords . map show\n\nprogram :: [[Int]] -> [Int]\nprogram ([n]:a:b:_) = buildArray n $ zip bIndices aSorted \n where aSorted = sortBy (flip compare) a\n bIndices = map fst $\n sortBy (\\x y -> compare (snd x) (snd y)) $\n zip ([1..] :: [Int]) b\n\nbuildArray :: Int -> [(Int, Int)] -> [Int]\nbuildArray n pairs = elems $ runSTUArray $ do\n arr <- newArray (1, n) 0\n forM_ pairs $ \\(i, v) ->\n writeArray arr i v\n return arr", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.List as L (sort, sortBy, intercalate)\n\nreadInt = fst . M.fromJust . C.readInt\n\nmain = do\n (readInt -> n) <- B.getLine\n (map readInt . C.words -> as) <- B.getLine\n (map readInt . C.words -> bs) <- B.getLine\n let bss = L.sortBy (\\a b -> compare (snd a) (snd b)) (zip [1..] bs)\n ass = reverse $ L.sort as\n css = map (\\(a, (b, c)) -> (a, b)) (zip ass bss)\n dss = map fst $ L.sortBy (\\a b -> compare (snd a) (snd b)) css\n putStrLn $ L.intercalate \" \" $ map show dss\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Function\nimport Data.Array.Unboxed\n\nmain = B.getContents >>= putStr . unwords . map show . evalState app . B.words\n\napp = do\n n <- poi\n as <- replicateM n poi\n bs <- replicateM n poi\n return $ solve n as bs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n as bs = (elems :: UArray Int Int -> [Int]) $ array (1, n) $ flip zip (sortBy (flip compare) as) $ map fst $ sortBy (compare `on` snd) $ zip [1..] bs"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Function\nimport Data.Array.Unboxed\n\nmain = B.getContents >>= B.putStr . B.unwords . map (B.pack . show) . evalState app . B.words\n\napp = do\n n <- poi\n as <- replicateM n poi\n bs <- replicateM n poi\n return $ solve n as bs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n as bs = (elems :: UArray Int Int -> [Int]) $ array (1, n) $ flip zip (sortBy (flip compare) as) $ map fst $ sortBy (compare `on` snd) $ zip [1..] bs"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Function\nimport Data.Array.Unboxed\n\nmain = B.getContents >>= mapM_ print . evalState app . B.words\n\napp = do\n n <- poi\n as <- replicateM n poi\n bs <- replicateM n poi\n return $ solve n as bs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n as bs = (elems :: UArray Int Int -> [Int]) $ array (1, n) $ flip zip (sortBy (flip compare) as) $ map fst $ sortBy (compare `on` snd) $ zip [1..] bs"}], "src_uid": "c51e15aeb3f287608a26b85865546e85"} {"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- getLine\n as <- words <$> getLine\n putStrLn $ unwords $ reverse $ as\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = getLine >> readInts >>= printList . reverse"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Functor\nimport Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n n <- B8.getLine <&> readIntB8\n ps <- B8.getLine <&> B8.words <&> map readIntB8\n let answer = reverse ps\n forM_ answer $ printf \"%d \"\n printf \"\\n\"\n"}], "negative_code": [], "src_uid": "1eaff8e0ec4614753699128af74b2471"} {"source_code": "isp n = and $ map ((/=0) . (mod n)) $ takeWhile ((<=n) . (^2)) [2 ..]\n\ngao 0 = []\ngao n = gao (p - 1) ++ [n + p - i | i <- [p .. n]] where\n\tp = until (isp . (+n)) succ 1\n\nmain = do getLine >>= putStr . unwords . map show . gao . read\n", "positive_code": [{"source_code": "main = do getLine >>= putStr . unwords . map show . (\\n -> n:[1..n-1]) . read\n"}, {"source_code": "import Monad\nimport List\n\nmain = readLn >>= putStrLn.unwords.map show.solve\n\nsolve n = [2..n] ++ [1]\n\n"}, {"source_code": "main :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn . unwords . map show $ n:[1..n-1]\n"}, {"source_code": "import Control.Applicative\n\nsolve n | even n = concatMap (\\x->[x+1, x]) [1,3..]\n | otherwise = 1 : (concatMap (\\x->[x, x-1])) [3, 5..]\n\nmain = do\n n <- read <$> getLine\n putStrLn $ unwords $ map show $ take n $ solve n\n"}, {"source_code": "import Control.Monad\nmain = do\nn<-getLine>>=return.read\nif odd n then do{putStr\"1 \";m[2,4..n-1]} else m[1,3..n-1] where m = mapM (\\x->putStr(show(x+1)++\" \"++show x++\" \"))\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.(read::String->Int)\n\nfunc::Int->String\nfunc a = solve [1..a]\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nmaximum' [] = 0\nmaximum' a = maximum a\n\nsolve::[Int]->String\nsolve a = showStr ((tail a) ++ [b])\n where\n b = head a\n\nshowStr::[Int]->String\nshowStr = init. foldr (\\a b->(show a)++(' ':b)) \"\""}], "negative_code": [{"source_code": "\nmain = do\n n <- readLn\n putStrLn $ unwords $ map show [1..n]\n"}], "src_uid": "f35d7f9c12eea4364891e0449613f6b0"} {"source_code": "{-# OPTIONS_GHC -XStrict -XStrictData #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\nsolve :: Int64 -> [Int64] -> Int64\r\nsolve n xs =\r\n let ws = [i*(n-i) | i <- [1..n-1]]\r\n ys = zipWith (-) xs (drop 1 xs)\r\n in\r\n sum $ zipWith (\\w y -> (w-1)*y) ws ys\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- fromIntegral . parseInt <$> BS.getLine\r\n xs <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine\r\n print $ solve n (sort xs)", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int64] -> Int64\nsolve n ds = solve' 1 0 0 . tail . sort $ ds\n where\n solve' :: Int64 -> Int64 -> Int64 -> [Int64] -> Int64\n solve' _ _ _ [] = 0\n solve' kDs sDs lDs ds@(d:pDs) = (d - lDs) - kDs * d + sDs + solve' (succ kDs) (sDs + d) d pDs\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n ds :: [Int64] <- B8.getLine <&> readIntegerB8s <&> map fromInteger\n let answer = solve n ds\n printf \"%lld\\n\" answer\n"}, {"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.Int ( Int64 )\r\nimport Data.List ( sort, tails, zipWith4 )\r\n\r\nsolve :: IO()\r\nsolve = do\r\n n <- readInt <$> getLine\r\n as <- sort . map readInt64 . words <$> getLine\r\n let calc i ai alast slast = slast + (ai - alast) * fromIntegral i\r\n dp = 0 : zipWith4 calc [1..] (tail as) as dp\r\n print $ as !! (n - 1) - sum dp\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nreadInt64 :: String -> Int64\r\nreadInt64 = read\r\n\r\nmain :: IO()\r\nmain = do\r\n t <- readInt <$> getLine\r\n replicateM_ t solve\r\n"}], "negative_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int64] -> Int64\nsolve n ds = solve' 1 0 0 $ tail ds\n where\n solve' :: Int64 -> Int64 -> Int64 -> [Int64] -> Int64\n solve' _ _ _ [] = 0\n solve' kDs sDs lDs ds@(d:pDs) = (d - lDs) - kDs * d + sDs + solve' (succ kDs) (sDs + d) d pDs\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n ds :: [Int64] <- B8.getLine <&> readIntegerB8s <&> map fromInteger\n let answer = solve n ds\n printf \"%lld\\n\" answer\n"}], "src_uid": "7dfe0db5a99e6e4d71eb012fab07685b"} {"source_code": "{-# LANGUAGE TypeApplications #-}\nmain = interact $ unlines . map (show . solve . read @Integer) . tail . lines\nsolve n = go n 0 where\n go 1 a = a\n go n a | (q,0) <- n `divMod` 5 = go q $! a+3\n | (q,0) <- n `divMod` 3 = go q $! a+2\n | (q,0) <- n `divMod` 2 = go q $! a+1\n | otherwise = -1\n", "positive_code": [{"source_code": "-- https://github.com/minoki/my-atcoder-solutions\n{-# LANGUAGE BangPatterns #-}\nimport Data.Int\nimport Control.Monad\n\nsolve :: Int64 -> Int\nsolve 0 = error \"invalid input\"\nsolve n = let (e2, n') = factorMultiplicity 2 n\n (e3, n'') = factorMultiplicity 3 n'\n (e5, n''') = factorMultiplicity 5 n''\n in if n''' == 1\n then e2 + 2 * e3 + 3 * e5\n else -1\n where\n factorMultiplicity :: Int64 -> Int64 -> (Int, Int64)\n factorMultiplicity !p = loop 0\n where loop !k !n = case n `quotRem` p of\n (q,0) -> loop (k + 1) q\n _ -> (k, n)\n\nmain = do\n q <- readLn\n replicateM_ q (solve <$> readLn >>= print)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nprocess n a | a==1 = n\n | mod a 5 ==0 = process (n+1) (div (a*4) 5)\n\t | mod a 3 ==0 = process (n+1) (div (a*2) 3)\n\t | mod a 2 ==0 = process (n+1) (div a 2)\n\t | otherwise = -1\t\t\n\nprocess1 = do\n\t\ta<- read <$> getLine ::IO Integer\n\t\tprint $ process 0 a\n\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n process1\n"}, {"source_code": "countFactor :: Integer -> Integer -> (Integer, Integer)\ncountFactor d n = (fromIntegral (length c),n')\n where (c,n':_) = span ((==0).(`mod` d)) $ iterate (`div` d) n\n\n--process :: Integer -> Integer\nprocess n\n | n' == 1 = sum $ zipWith (*) [1,2,3] $ fst $ unzip xs\n | otherwise = -1\n where\n xs@((_,n'):_) = scanr f (0,n) [2,3,5]\n f = \\x (_,t) -> countFactor x t\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain :: IO ()\nmain = do\n q <- fmap readInt getLine\n ns <- fmap (map readInt.words) getContents\n mapM_ print $ map process ns"}, {"source_code": "\nsubN' :: Integer -> Int -> Int\nsubN' x c\n | x == 1 = c\n | mod x 5 == 0 = subN' (div (x*4) 5) (c+1)\n | mod x 3 == 0 = subN' (div (x*2) 3) (c+1)\n | mod x 2 == 0 = subN' (div x 2) (c+1)\n | otherwise = -1\n\nsubN :: Integer -> Int\nsubN x = subN' x 0\n\nsolve :: [Integer] -> [Int]\nsolve xs = map subN xs \n\nmain = interact $ unlines . map show . solve . map (read::String->Integer) . tail . words"}], "negative_code": [{"source_code": "\nsubN' :: Integer -> Int -> Int\nsubN' x c\n | x == 1 = c\n | mod x 5 == 0 = subN' (div (x*4) 5) (c+1)\n | mod x 3 == 0 = subN' (div (x*2) 3) (c+1)\n | mod x 2 == 0 = subN' (div x 2) (c+1)\n | otherwise = -1\n\nsubN :: Integer -> Int\nsubN x = subN' x 0\n\nsolve :: [Integer] -> [Int]\nsolve xs = map subN xs \n\nmain = interact $ unlines . map show . solve . map (read::String->Integer) . words"}], "src_uid": "ed5ea0e664aa986ab86e4e6746e8a1bf"} {"source_code": "import Data.List\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.Map.Strict as M\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n flats <- getLine\n let flatAry = listArray (1, length flats) flats\n let numPoke = (length . group . sort) flats\n print $ solve numPoke flatAry\n\ntype Book = M.Map Char Int\ntype Solution = (Book, Int, Int) -- (currSet, beginIx, endIx)\n\nsolve numPoke flats = f (M.empty, 1, 1) 100000 where\n f :: Solution -> Int -> Int\n f curr best = case walk numPoke flats curr of\n Nothing -> best\n Just next -> f (removeHead next flats) (min best (cost next))\n cost (_, b, e) = e - b\n\nremoveHead (book, b, e) flats = (book', b+1, e) where\n x = flats ! b\n book' = if book M.! x == 1 then M.delete x book else M.adjust (\\y->y-1) x book\n\nwalk :: Int -> Array Int Char -> Solution -> Maybe Solution\nwalk num flats (book, b, e) = f book e where\n (ary1, aryN) = bounds flats\n len = aryN - ary1 + 1\n f book e\n | e > len && M.size book >= num = Just (book, b, e)\n | e > len && M.size book < num = Nothing\n | M.size book == num = Just (book, b, e)\n | otherwise = f (M.insertWith (+) (flats ! e) 1 book) (e + 1)", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n s <- getLine\n\n let m = length $ filter (/= 0) $ elems $ accumArray (+) 0 (chr 0, chr 127) $ zip s (repeat 1)\n\n cs :: IOUArray Char Int <- newArray (chr 0, chr 127) 0\n\n let\n scan0 :: String -> Int -> Int -> IO (String, Int)\n scan0 s d k\n | k == m = return (s, d)\n | otherwise = do\n v <- readArray cs c\n writeArray cs c (v+1)\n scan0 (tail s) (d+1) (if v == 0 then k + 1 else k)\n where c = head s\n\n (r0, d0) <- scan0 s 0 0\n\n let\n scan :: String -> String -> Int -> Int -> IO Int\n scan l r d m = do\n cnt <- readArray cs c\n writeArray cs c (cnt-1)\n\n if cnt == 1\n then\n if null r2\n then return m\n else do\n mapM (\\c -> readArray cs c >>= \\v -> writeArray cs c (v+1)) $ c:r1\n scan l' r' d' $ min d' m\n else scan l' r (d-1) $ min (d-1) m\n where\n (c, l') = (head l, tail l)\n (r1, r2) = span (/= c) r\n r' = tail r2\n d' = d + length r1\n\n\n m <- scan s r0 d0 d0\n\n print m\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n str <- getLine\n let numPoke = (length . group . sort) str\n print $ minimum [minStep n numPoke (drop i str) | i <- [0..n-numPoke+1]]\n\nminStep n nPoke ps = f ps [] 0 where\n f [] qs step = n\n f (p:ps) qs step\n | length qs == nPoke = step\n | otherwise = f ps qs' (step+1)\n where qs' = if p `elem` qs then qs else (p:qs)"}, {"source_code": "import Data.List\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n str <- getLine\n let numPoke = (length . group . sort) str\n print $ minimum [minStep numPoke (drop i str) | i <- [0..n-numPoke]]\n\nminStep nPoke ps = f ps [] 0 where\n f [] qs step = step\n f (p:ps) qs step\n | length qs == nPoke = step\n | otherwise = f ps qs' (step+1)\n where qs' = if p `elem` qs then qs else (p:qs)"}, {"source_code": "import Data.List\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n str <- getLine\n let numPoke = (length . group . sort) str\n print $ minimum [minStep numPoke (drop i str) | i <- [0..n-numPoke+1]]\n\nminStep n ps = f ps [] 0 where\n f [] qs step = n + 1\n f (p:ps) qs step\n | length qs == n = step\n | otherwise = f ps qs' (step+1)\n where qs' = if p `elem` qs then qs else (p:qs)"}, {"source_code": "import Data.List\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n str <- getLine\n let numPoke = (length . group . sort) str\n print $ minimum [minStep numPoke (drop i str) | i <- [0..n-numPoke+1]]\n\nminStep n ps = f ps [] 0 where\n f [] qs step = n\n f (p:ps) qs step\n | length qs == n = step\n | otherwise = f ps qs' (step+1)\n where qs' = if p `elem` qs then qs else (p:qs)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n s <- getLine\n\n let m = length $ filter (/= 0) $ elems $ accumArray (+) 0 (chr 0, chr 127) $ zip s (repeat 1)\n\n cs :: IOUArray Char Int <- newArray (chr 0, chr 127) 0\n\n let\n scan0 :: String -> Int -> Int -> IO (String, Int)\n scan0 s d k\n | k == m = return (s, d)\n | otherwise = do\n v <- readArray cs c\n writeArray cs c (v+1)\n scan0 (tail s) (d+1) (if v == 0 then k + 1 else k)\n where c = head s\n\n (r0, d0) <- scan0 s 0 0\n\n let\n scan :: String -> String -> Int -> Int -> IO Int\n scan _ [] _ m = return m\n scan l r d m = do\n cnt <- readArray cs c\n writeArray cs c (cnt-1)\n\n if cnt == 1\n then\n if null r2\n then return m\n else scan l' r' d' $ min d' m\n else scan l' r (d-1) $ min (d-1) m\n where\n (c, l') = (head l, tail l)\n (r1, r2) = span (/= c) r\n r' = tail r2\n d' = d + length r1\n\n\n m <- scan s r0 d0 d0\n\n print m\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n s <- getLine\n\n let m = length $ filter (/= 0) $ elems $ accumArray (+) 0 (chr 0, chr 127) $ zip s (repeat 1)\n\n cs :: IOUArray Char Int <- newArray (chr 0, chr 127) 0\n\n let\n scan0 :: String -> Int -> Int -> IO (String, Int)\n scan0 s d k\n | k == m = return (s, d)\n | otherwise = do\n v <- readArray cs c\n writeArray cs c (v+1)\n scan0 (tail s) (d+1) (if v == 0 then k + 1 else k)\n where c = head s\n\n (r0, d0) <- scan0 s 0 0\n print (r0, d0)\n\n let\n scan :: String -> String -> Int -> Int -> IO Int\n scan _ [] _ m = return m\n scan l r d m = do\n cnt <- readArray cs c\n writeArray cs c (cnt-1)\n\n if cnt == 1\n then\n if null r2\n then return m\n else scan l' r' d' $ min d' m\n else scan l' r (d-1) $ min (d-1) m\n where\n (c, l') = (head l, tail l)\n (r1, r2) = span (/= c) r\n r' = tail r2\n d' = d + length r1\n\n\n m <- scan s r0 d0 d0\n\n print m\n"}], "src_uid": "60776cefd6c1a2f3c16b3378ebc31a9a"} {"source_code": "import Control.Monad\nimport Data.List\n\ncomparator' :: Int -> String -> String -> Ordering\ncomparator' _ [] [] = EQ\ncomparator' 0 (a:as) (b:bs)\n | ab = GT\ncomparator' 1 (a:as) (b:bs)\n | ab = LT\n\n\ncomparator :: (String,Int) -> (String,Int) -> Ordering\ncomparator (s1,_) (s2,_) =\n comparator' 0 s1 s2\n\n\nmain = do\n line <- getLine\n let [n,m] = map read $ words line :: [Int]\n lines <- mapM (\\_ -> do\n line <- getLine\n return line\n ) [1..n]\n let ans = map (\\(_,i) -> i) $ sortBy comparator $ zip lines [1..]\n putStrLn $ intercalate \" \" $ map show ans\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\nimport qualified Data.ByteString.Char8 as S\nimport Data.Array.Unboxed\n\nstableBucketSortOn :: (Int -> Int) -> (Int, Int) -> [Int] -> [[Int]]\nstableBucketSortOn fun = \\bnds li -> let\n arr :: Array Int ([Int] -> [Int])\n arr = accumArray (\\x y -> x . (y :)) id bnds [(fun x, x) | x <- li]\n in filter (not . null) $ map ($ []) $ elems arr\n{-# INLINE stableBucketSortOn #-}\n\nmainFun :: SO\nmainFun = do\n ~[n, m] <- getInts 2\n sLi <- getNext n\n let\n s :: Array Int S.ByteString\n s = listArray (1, n) $ map P.toStrict sLi\n compareAtPos x = \\y -> if even x\n then fromEnum (S.index (s ! y) x)\n else fromEnum 'A' + fromEnum 'Z' - fromEnum (S.index (s ! y) x)\n step :: [[Int]] -> Int -> [[Int]]\n step lis pos = do\n li <- lis\n stableBucketSortOn (compareAtPos pos) (fromEnum 'A', fromEnum 'Z') li\n ans = foldl step [[1..n]] [0 .. m-1]\n pure $ putInts $ concat ans\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "6b75105015e5bf753ee93f6e0639a816"} {"source_code": "{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Int\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nrl :: C.ByteString -> Int64\nrl s = fromInteger r\n where Just (r, _) = C.readInteger s\n\nceil u v = let (a, b) = divMod u v in a + (if b > 0 then 1 else 0)\n\ntest :: Int64 -> Int -> [Int] -> Int64\ntest !h !n !d\n | h' > 0 && v >= 0 = -1\n | h' <= 0 = succ $ fromIntegral $ length $ takeWhile (\\x -> h + x > 0) s\n | otherwise = (o * (fromIntegral n)) + (fromIntegral $ succ $ length $ takeWhile (\\x -> h'' + x > 0) s)\n where\n s :: [Int64]\n s = scanl1 (+) $ map fromIntegral d\n u = minimum s\n v = last s\n h' = h + u\n v' = negate v\n o = ceil h' v'\n h'' = h + v * o\n\nsolve :: [C.ByteString] -> Int64\nsolve (sh:sn:a) = test h n d\n where\n h = rl sh\n n = ri sn\n d = take n $ map ri a\n\nmain :: IO ()\nmain = print . solve . C.words =<< C.getContents\n", "positive_code": [{"source_code": "import Data.List (foldl1', find)\nimport Data.Maybe (fromJust)\ndiffs d = scanl1 (+) d\n\nsolve :: [Integer] -> Integer -> Integer -> Integer\nsolve diff hp n =\n let\n dt = zip diff [1..]\n cmpp p1@(d1, i1) p2@(d2, i2)\n | d1 < d2 = p1\n | d1 > d2 = p2\n | otherwise = if i1 < i2 then p1 else p2\n (mind, mini) = foldl1' cmpp dt \n cycled = last diff \n in\n if hp + mind <= 0 then snd . fromJust . (find (\\(d, _) -> hp + d <= 0)) $ dt\n else if cycled >= 0 then -1\n else \n let\n cycles1 = (hp + mind) `div` (abs cycled)\n findTime cycles rhp\n | rhp + mind > 0 = findTime (cycles + 1) (rhp + cycled)\n | otherwise = \n let\n ind = snd . fromJust . (find (\\(d, _) -> rhp + d <= 0)) $ dt \n in\n cycles * n + ind\n in \n findTime cycles1 (hp + cycles1 * cycled)\n\nmain = do\n [hp, n] <- (map read) . words <$> getLine\n diff <- diffs . (map read) . words <$> getLine\n putStrLn . show $ solve diff hp n\n"}], "negative_code": [{"source_code": "import Data.List (foldl1', find)\nimport Data.Maybe (fromJust)\ndiffs d = scanl1 (+) d\n\nsolve :: [Integer] -> Integer -> Integer -> Integer\nsolve diff hp n =\n let\n dt = zip diff [1..]\n cmpp p1@(d1, i1) p2@(d2, i2)\n | d1 < d2 = p1\n | d1 > d2 = p2\n | otherwise = if i1 < i2 then p1 else p2\n (mind, mini) = foldl1' cmpp dt\n cycled = last diff\n in\n if hp + mind <= 0 then snd . fromJust . (find (\\(d, _) -> hp + d <= 0)) $ dt\n else if cycled >= 0 then -1\n else\n let\n cycles1 = (hp + mind) `div` (abs cycled)\n findTime cycles rhp\n | rhp + mind > 0 = findTime (cycles + 1) (rhp + cycled)\n | otherwise =\n let\n ind = snd . fromJust . (find (\\(d, _) -> rhp + d <= 0)) $ dt\n in\n cycles * n + ind\n in\n findTime cycles1 (hp + cycles1 * mind)\n\nmain = do\n [hp, n] <- (map read) . words <$> getLine\n diff <- diffs . (map read) . words <$> getLine\n putStrLn . show $ solve diff hp n"}, {"source_code": "import Data.List (foldl1', find)\nimport Data.Maybe (fromJust)\ndiffs d = scanl1 (+) d\n\nsolve :: [Integer] -> Integer -> Integer -> Integer\nsolve diff hp n =\n let\n dt = zip diff [1..]\n cmpp p1@(d1, i1) p2@(d2, i2)\n | d1 < d2 = p1\n | d1 > d2 = p2\n | otherwise = if i1 < i2 then p1 else p2\n (mind, mini) = foldl1' cmpp dt\n cycled = last diff\n in\n if hp + mind <= 0 then mini\n else if cycled >= 0 then -1\n else\n let\n cycles1 = (hp + mind) `div` (abs cycled)\n findTime cycles rhp\n | rhp + mind > 0 = findTime (cycles + 1) (rhp + cycled)\n | otherwise =\n let\n ind = snd . fromJust . (find (\\(d, _) -> rhp + d <= 0)) $ dt\n in\n cycles * n + ind\n in\n findTime cycles1 (hp + cycles1 * mind)\n\nmain = do\n [hp, n] <- (map read) . words <$> getLine\n diff <- diffs . (map read) . words <$> getLine\n putStrLn . show $ solve diff hp n\n"}], "src_uid": "d173fa24cebaeda9ca794eeed68fa12d"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List(transpose,sort)\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,m,p] <- readInts\n as <- readInts\n bs <- readInts\n let qs = solve n m p as bs\n print (length qs)\n putStrLn $ unwords $ map show qs\n\ntakeBy :: Int -> [Int] -> [[Int]]\ntakeBy p l = transpose $ go l\n where\n go [] = []\n go l = c:go cs\n where\n (c,cs) = splitAt p l\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]\nsolve n m p as bs = sort $ do\n (l,i) <- zip (takeBy p as) [1..]\n q <- matchIndices m bs l\n return (q*p + i)\n\ninsert :: M.Map Int Int -> Int -> M.Map Int Int\ninsert s v | not (M.member v s) = M.insert v 1 s\n | s M.! v == -1 = M.delete v s\n | otherwise = M.insertWith (+) v 1 s\n\ndelete :: M.Map Int Int -> Int -> M.Map Int Int\ndelete s v | not (M.member v s) = M.insert v (-1) s\n | s M.! v == 1 = M.delete v s\n | otherwise = M.insertWith (+) v (-1) s\n\nmatchIndices :: Int -> [Int] -> [Int] -> [Int]\nmatchIndices m bs l = go ds l (drop m l) 0\n where\n ds = foldl delete (foldl insert M.empty bs) (take m l)\n go ds _ [] i = if M.null ds then [i] else []\n go ds (b:bs) (c:cs) i | M.null ds = i:go ds' bs cs (i+1)\n | otherwise = go ds' bs cs (i+1)\n where ds' = delete (insert ds b) c\n", "positive_code": [{"source_code": "import Data.List(transpose,sort)\nimport Data.Maybe\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst .B.readInt\nreadInts = fmap (map readInt . B.words) B.getLine\n\nmain = do\n [n,m,p] <- readInts\n as <- readInts\n bs <- readInts\n let qs = solve n m p as bs\n print (length qs)\n putStrLn $ unwords $ map show qs\n\ntakeBy :: Int -> [Int] -> [[Int]]\ntakeBy p l = transpose $ go l\n where\n go [] = []\n go l = c:go cs\n where (c,cs) = splitAt p l\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]\nsolve n m p as bs = sort $ do\n (l,i) <- zip (takeBy p as) [1..]\n q <- matchIndices m bs l\n return (q*p + i)\n\nreduce :: M.Map Int Int -> Int -> M.Map Int Int\nreduce s v = if s M.! v == 0 then M.delete v s else s\n\ninsert :: M.Map Int Int -> Int -> M.Map Int Int\ninsert s v = reduce (M.insertWith (+) v 1 s) v\n\ndelete :: M.Map Int Int -> Int -> M.Map Int Int\ndelete s v = reduce (M.insertWith (+) v (-1) s) v\n\nmatchIndices :: Int -> [Int] -> [Int] -> [Int]\nmatchIndices m bs l = go ds l (drop m l) 0\n where\n ds = foldl insert (foldl delete M.empty bs) (take m l)\n go ds _ [] i = if M.null ds then [i] else []\n go ds (b:bs) (c:cs) i | M.null ds = i:go ds' bs cs (i+1)\n | otherwise = go ds' bs cs (i+1)\n where ds' = insert (delete ds b) c\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List(transpose,sort)\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,m,p] <- readInts\n as <- readInts\n bs <- readInts\n let qs = solve n m p as bs\n print (length qs)\n putStrLn $ unwords $ map show qs\n\ntakeBy :: Int -> [Int] -> [[Int]]\ntakeBy p l = transpose $ go l\n where\n go [] = []\n go l = c:go cs\n where\n (c,cs) = splitAt p l\n\nsolve :: Int -> Int -> Int -> [Int] -> [Int] -> [Int]\nsolve n m p as bs = sort $ do\n (l,i) <- zip (takeBy p as) [1..]\n q <- matchIndices m bs l\n return (q*p + i)\n\ninsert :: M.Map Int Int -> Int -> M.Map Int Int\ninsert s v | not (M.member v s) = M.insert v 1 s\n | s M.! v == -1 = M.delete v s\n | otherwise = M.insertWith (+) v 1 s\n\ndelete :: M.Map Int Int -> Int -> M.Map Int Int\ndelete s v | not (M.member v s) = M.insert v (-1) s\n | s M.! v == 1 = M.delete v s\n | otherwise = M.insertWith (+) v (-1) s\n\nmatchIndices :: Int -> [Int] -> [Int] -> [Int]\nmatchIndices m bs l = go ds l (drop m l) 0\n where\n ds = foldl delete (foldl insert M.empty bs) (take m l)\n go ds _ [] i = if M.null ds then [i] else []\n go ds (b:bs) (c:cs) i | M.null ds = i:go ds' bs cs (i+1)\n | otherwise = go ds' bs cs (i+1)\n where ds' = insert (delete ds b) c\n"}], "src_uid": "84cce147e8aadb140afaaa95917fdf0d"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ParallelListComp #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (guard, replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.pack <$> testCase)\n\ntestCase :: Scanner String\ntestCase = do\n n <- int\n m <- int\n s <- str\n qs <- m >< pair int int\n return . unlines . map show $ solve s qs\n\nsolve :: String -> [(Int, Int)] -> [Int]\nsolve s = map compute\n where\n compute (l, r) = minimum $ do\n a <- [0 .. 2]\n b <- [0 .. 2]\n guard $ a /= b\n c <- [0 .. 2]\n guard $ c /= a && c /= b\n let matches =\n [ psum (freq !! ai !! mi) l r\n | ai <- [a, b, c]\n | mi <- map (`mod` 3) [l, l + 1, l + 2]\n ]\n return $ r - l + 1 - sum matches\n\n n = length s\n\n c2i 'a' = 0\n c2i 'b' = 1\n c2i 'c' = 2\n\n getFreq :: Int -> Int -> UArray Int Int\n getFreq c m =\n listArray (0, n) . scanl (+) 0 $\n [if c2i c' == c && i `mod` 3 == m then 1 else 0 | (c', i) <- zip s [1 .. n]]\n\n psum :: UArray Int Int -> Int -> Int -> Int\n psum arr l r\n | l > r = 0\n | otherwise = arr ! r - arr ! (l - 1)\n\n freq = [[getFreq c m | m <- [0 .. 2]] | c <- [0 .. 2]]\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, m] <- readInts\r\n s <- C.unpack <$> C.getLine\r\n qs <- replicateM m readInts\r\n let pats = map cycle [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"]\r\n difs = map (listArray (0, n) . scanl (+) 0 . map fromEnum . zipWith (/=) s) pats\r\n qry [l, r] = minimum $ map (\\d -> d!r - d!(l - 1)) difs\r\n putStr $ unlines $ map (show . qry) qs\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [], "src_uid": "b4183febe5ae61770368d2e16f273675"} {"source_code": "import Control.Applicative\nimport qualified Data.Set as Set\nimport Data.List\n\n\nsolve :: [Int] -> Int -> [Int]\nsolve nums maxIdx =\n solve' unused nums (Set.fromList [])\n where\n unused = Set.toList $ Set.fromList [1..maxIdx] `Set.difference` Set.fromList nums\n solve' :: [Int] -> [Int] -> Set.Set Int -> [Int]\n solve' (u:rstUnused) (a:rstGroups) set | a `Set.member` set || a < 1 || a > maxIdx =\n u:solve' rstUnused rstGroups set\n solve' unused (a:rstGroups) set = a:solve' unused rstGroups (Set.insert a set)\n solve' _ [] _ = []\n\nmain = do\n maxIdx <- read <$> getLine\n nums <- map read . words <$> getLine\n putStrLn $ unwords $ map show $ solve nums maxIdx\n", "positive_code": [{"source_code": "import qualified Data.List as L\nimport qualified Data.IntSet as S\nimport qualified Data.IntMap as M\n\nmain=interact$ solve. map read. words\nsolve (n:l) = L.intercalate \" \" $ map show $ f 1 d\n\twhere (m,s) = foldl (\\(m,s) (x,i)->if S.member x s || x>n then (m,s) else (M.insert i x m, S.insert x s)) (M.empty,S.empty) $ zip l [1..n]\n\t d = filter (flip S.notMember s) [1..n] \n\t f c l \n\t\t|c>n = []\n\t\t|otherwise = let v=M.lookup c m in if v==Nothing then head l : (f (c+1) $ tail l) else let Just v'=v in v': f(c+1) l\n"}, {"source_code": "import Data.List\n\nmain=interact$solve.map read.words\n\nsolve (n:l) = (intercalate \" \" $ map show $ f l'' no 1)\n where l'=map head $ groupBy (\\a b->fst a==fst b) $ sort $ filter (\\x->fst x <= n) $ zip l [1..n]\n \n diff a [] = a\n diff [] b = []\n diff (a:as) bss@(b:bs)\n | a==b = diff as bs\n | a snd a `compare` snd b) l'\n\n f [] [] _ = []\n f a [] _ = map fst a\n f [] b _ = b\n f ass@(a:as) bss@(b:bs) c\n | c==snd a = fst a: f as bss (c+1)\n | otherwise = b : f ass bs (c+1)"}, {"source_code": "import System.IO\nimport qualified Data.Set as S\n\nread_ints :: String -> [Int]\nread_ints x = map read (words x) :: [Int]\n\nsolve :: [Int] -> S.Set Int -> Int -> [Int]\nsolve [] _ _ = []\nsolve (x:xs) st len = if S.member x st || x > len then 0 : solve xs st len else x : solve xs ( S.insert x st ) len \n\ncomplete :: [Int] -> S.Set Int -> Int -> [Int]\ncomplete [] _ _ = []\ncomplete (x:xs) st y = \n\tif x == 0 then \n\t\tif S.member y st then\n\t\t\tcomplete (x:xs) st (y+1) \n\t\telse\n\t\t\ty : complete xs ( S.insert y st ) (y+1)\n\telse\n\t\t x : complete xs st y \n\nmain = do\t\n\tln <- getLine\n\tlet [n] = read_ints ln\n\tln <- getLine\n\tlet arr = read_ints ln\n\tlet len = length arr\n\tlet ans = solve arr S.empty len\n\tputStr $ unwords $ map show $ complete ans (S.fromList arr) 1\n\t\n"}, {"source_code": "import System.IO\nimport qualified Data.Set as S\n\nread_ints :: String -> [Int]\nread_ints x = map read (words x) :: [Int]\n\nsolve :: [Int] -> S.Set Int -> Int -> [Int]\nsolve [] _ _ = []\nsolve (x:xs) st len = \n\tif S.member x st || x > len then \n\t\t0 : solve xs st len \n\telse \n\t\tx : solve xs ( S.insert x st ) len \n\ncomplete :: [Int] -> S.Set Int -> Int -> [Int]\ncomplete [] _ _ = []\ncomplete (x:xs) st y = \n\tif x == 0 then \n\t\tif S.member y st then\n\t\t\tcomplete (x:xs) st (y+1) \n\t\telse\n\t\t\ty : complete xs ( S.insert y st ) (y+1)\n\telse\n\t\t x : complete xs st y \n\nmain = do\t\n\tln <- getLine\n\tlet [n] = read_ints ln\n\tln <- getLine\n\tlet arr = read_ints ln\n\tlet len = length arr\n\tlet ans = solve arr S.empty len\n\tputStr $ unwords $ map show $ complete ans (S.fromList arr) 1\n\t\n"}, {"source_code": "import Data.List (intercalate)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.ByteString (ByteString)\nimport Data.Set (Set, delete, member, notMember, fromList)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as B8\n\n\nloop :: [Int] -> Set Int -> [Int] -> [Int]\nloop [] _ _ = []\nloop (a:rest) obs out\n | a `member` obs = a:loop rest (a `delete` obs) out\n | otherwise = (head out):loop rest obs (tail out)\n\n\nsolve :: Int -> [Int] -> [Int]\nsolve n a = loop a obs out\n where\n obs = fromList . filter (< n + 1) $ a :: Set Int\n out = filter (`notMember` obs) [1..n] :: [Int]\n\n\nparse :: ByteString -> Maybe [Int]\nparse = sequence . fmap (fmap fst . B8.readInt) . B8.words\n\n\nmain = read <$> getLine >>= \\n ->\n parse <$> B.getLine >>= \\(Just a) ->\n putStrLn . intercalate \" \" . fmap show $ solve n a\n"}, {"source_code": "import System.IO\nimport qualified Data.Set as S\n\nread_ints :: String -> [Int]\nread_ints ln = map read (words ln) :: [Int]\n\nsolve :: [Int] -> S.Set Int -> Int -> [Int]\nsolve [] _ _ = []\nsolve (x:xs) st len =\n if S.member x st || x > len then\n 0 : solve xs st len\n else\n x : solve xs (S.insert x st) len\n\ncomplete :: [Int] -> S.Set Int -> Int -> [Int]\ncomplete [] _ _ = []\ncomplete (x:xs) st y =\n if x == 0 then\n if S.member y st then\n complete (x:xs) st (y+1)\n else\n y : complete xs (S.insert y st) (y+1)\n else\n x : complete xs st y\n\nmain = do\n ln <- getLine\n let [n] = read_ints ln\n ln <- getLine\n let arr = read_ints ln\n let len = length arr\n let ans = solve arr S.empty len\n \n putStr $ unwords $ map show $ complete ans (S.fromList arr) 1"}, {"source_code": "import Data.List (intersperse, groupBy, sortBy, sort)\n\nparseInts :: String -> [Int]\nparseInts = map read . words\n\nshowList' :: Show a => [a] -> String\nshowList' = concat . intersperse \" \" . map show\n\nminus :: Ord a => [a] -> [a] -> [a]\nminus a [] = a\nminus [] _ = []\nminus (a : as) (b : bs)\n | a == b = minus as bs\n | a < b = a : minus as (b : bs)\n | a > b = minus (a : as) bs\n\nmerge :: Int -> [(Int, Int)] -> [Int] -> [Int]\nmerge _ [] b = b\nmerge _ a [] = map snd a\nmerge p a@((k, v) : as) (b : bs)\n | p == k = v : merge (p + 1) as (b : bs)\n | p < k = b : merge (p + 1) a bs\n\nsolve :: [Int] -> [Int]\nsolve a = let n = length a\n id = filter (\\(x, y) -> 1 <= y && y <= n) . zip [1 .. ] $ a\n s = let cmp (_, a) (_, b) = compare a b\n in sortBy cmp id\n uni = let same (_, a) (_, b) = a == b\n in map head . groupBy same $ s\n rem = [1 .. n] `minus` (sort . map snd $ uni)\n pos = let cmp (a, _) (b, _) = compare a b\n in sortBy cmp uni\n in merge 1 pos rem\n\nmain :: IO ()\nmain = do\n getLine\n putStrLn . showList' . solve . parseInts =<< getLine\n\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\nimport qualified Data.IntSet as S\nimport qualified Data.IntMap as M\n\nmain=interact$ solve. map read. words\nsolve (n:l) = L.intercalate \" \" $ map show $ f 1 d\n\twhere (m,s) = foldl (\\(m,s) (x,i)->if S.member x s then (m,s) else (M.insert i x m, S.insert x s)) (M.empty,S.empty) $ zip l [1..n]\n\t d = filter (flip S.notMember s) [1..n] \n\t f c l \n\t\t|c>n = []\n\t\t|otherwise = let v=M.lookup c m in if v==Nothing then head l : (f (c+1) $ tail l) else let Just v'=v in v': f(c+1) l\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Set as Set\nimport Data.List\n\n\nsolve :: [Int] -> Int -> [Int]\nsolve nums maxIdx =\n solve' unused nums (Set.fromList [])\n where\n unused = Set.toList $ Set.fromList [1..maxIdx] `Set.difference` Set.fromList nums\n solve' :: [Int] -> [Int] -> Set.Set Int -> [Int]\n solve' (u:rstUnused) (a:rstGroups) set =\n if a `Set.member` set || a < 1 || a > maxIdx then\n u:solve' rstUnused rstGroups set\n else a:solve' (u:rstUnused) rstGroups (Set.insert a set)\n solve' (u:rstUnused) [] set = u:solve' rstUnused [] set\n solve' [] _ _ = []\n\nmain = do\n maxIdx <- read <$> getLine\n nums <- map read . words <$> getLine\n putStrLn $ unwords $ map show $ solve nums maxIdx\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.Set as Set\nimport Data.List\n\nsolve :: [Int] -> Int -> [Int]\nsolve nums maxIdx =\n solve' unused $ group $ filter (\\x -> x >= 1 && x <= maxIdx) nums\n where\n unused = Set.toList $ Set.fromList [1..maxIdx] `Set.difference` Set.fromList nums\n solve' :: [Int] -> [[Int]] -> [Int]\n solve' unused ([a]:rst) =\n a:solve' unused rst\n solve' (u:rstUnused) ((a:rstGroup):rstGroups) =\n u:solve' rstUnused (rstGroup:rstGroups)\n solve' (u:rstUnused) [] = u:solve' rstUnused []\n solve' [] _ = []\n\nmain = do\n maxIdx <- read <$> getLine\n nums <- map read . words <$> getLine\n putStrLn $ unwords $ map show $ solve nums maxIdx\n"}, {"source_code": "import System.IO\nimport qualified Data.Set as S\n\nread_ints :: String -> [Int]\nread_ints x = map read (words x) :: [Int]\n\nmodify :: Int -> S.Set Int -> Int\nmodify x st = if S.member x st then modify (x+1) st else x\n\nsolve :: [Int] -> S.Set Int -> [Int]\nsolve [] _ = []\nsolve (x:xs) st = if S.notMember x st then x : solve xs (S.insert x st) else y : solve xs (S.insert y st)\n\twhere y = modify 1 st\n\nmain = do\t\n\tln <- getLine\n\tlet [n] = read_ints ln\n\tln <- getLine\n\tlet arr = read_ints ln\n\tputStr $ unwords $ map show $ solve arr S.empty\n\t\n"}], "src_uid": "1cfd0e6504bba7db9ec79e2f243b99b4"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.Int\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextInteger :: Tokenizer Integer\nnextInteger = state $ \\(s:ss) -> case L.readInteger s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Integer:\" ++ (show s)\n\nnextChar :: Tokenizer Char\nnextChar = state $ \\(s:ss) -> (L.index s 0, ss)\n\ndata Piece = Piece { getType :: Char\n , getX :: Integer\n , getY :: Integer\n }\n\ncross :: Integer -> Integer -> Integer -> Integer -> Int64\ncross x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral y2 :: Int64) - (fromIntegral x2 :: Int64) * (fromIntegral y1 :: Int64)\n\ndot :: Integer -> Integer -> Integer -> Integer -> Int64\ndot x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral x2 :: Int64) + (fromIntegral y1 :: Int64) * (fromIntegral y2 :: Int64)\n\nsameDirection :: Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Bool\nsameDirection x1 y1 x2 y2 dx dy = cross vx vy dx dy == 0 && dot vx vy dx dy >= 0\n where vx = x2 - x1\n vy = y2 - y1 \n\ncheck :: Integer -> Integer -> [Piece] -> Bool\ncheck x0 y0 ps = getType best /= 'K'\n where best = foldl (closerPiece x0 y0) (Piece 'K' x0 y0) (map canMove cands)\n cands = [(closest x0 y0 dx dy ps, dx, dy) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)]\n\ncanMove :: (Piece, Integer, Integer) -> Piece\ncanMove (p, dx, dy) | t == 'B' && dx /= 0 && dy /= 0 = p\n | t == 'R' && (dx == 0 || dy == 0) = p\n | t == 'Q' = p\n | otherwise = Piece 'K' 0 0\n where t = getType p\n\ncloser :: Integer -> Integer -> Piece -> Piece -> Bool\ncloser x0 y0 p1 p2 = t2 == 'K' || (t1 /= 'K' && t2 /= 'K' && dist1 < dist2)\n where dist1 = abs (x1 - x0) + abs (y1 - y0)\n dist2 = abs (x2 - x0) + abs (y2 - y0)\n Piece t1 x1 y1 = p1\n Piece t2 x2 y2 = p2\n\ncloserPiece :: Integer -> Integer -> Piece -> Piece -> Piece\ncloserPiece x0 y0 p1 p2 | closer x0 y0 p1 p2 = p1\n | otherwise = p2\n\nclosest :: Integer -> Integer -> Integer -> Integer -> [Piece] -> Piece\nclosest x0 y0 dx dy [] = Piece 'K' x0 y0\nclosest x0 y0 dx dy (p:ps) | sameDirection x0 y0 x1 y1 dx dy && closer x0 y0 p best = p\n | otherwise = best\n where best = closest x0 y0 dx dy ps\n Piece _ x1 y1 = p\n\nsolve :: Tokenizer String\nsolve = do\n n <- nextInt\n x0 <- nextInteger\n y0 <- nextInteger\n p <- replicateM n $ do\n t <- nextChar\n x <- nextInteger\n y <- nextInteger\n return $ Piece t x y\n if (check x0 y0 p) then return \"YES\"\n else return \"NO\"\n\nmain = do\n contents <- L.getContents\n putStrLn $ evalState solve (L.words contents)\n", "positive_code": [{"source_code": "-- Codeforces Round #379 (Div. 2)\n-- http://codeforces.com/contest/734\n\n-- ID: 734D (Anton and Chess)\nimport Control.Monad\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ntype Piece = (String, Int, Int)\n\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nlessX (_,x1,_) (_,x2,_) = compare x1 x2\nlessY (_,_,y1) (_,_,y2) = compare y1 y2\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n [kingX, kingY] <- (map read . words) `fmap` getLine :: IO [Int]\n blacks <- replicateM n $ do\n [post, x, y] <- BS8.words `fmap` BS.getLine\n return (BS8.unpack post, parseInt x, parseInt y)\n let king = (\"K\", kingX, kingY)\n let dirs = [(-1,-1,flip lessX), (0,-1,flip lessY), (1,-1,lessX),\n (-1,0,flip lessX), (1,0,lessX),\n (-1,1,flip lessX), (0,1,lessY), (1,1,lessX)]\n let attackers = map fromJust $ filter isJust $ map (choose king blacks) dirs\n if any (checkmate king) attackers\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nchoose king blacks (dx, dy, sorter) = case (sortBy sorter . filter (attack dx dy king)) blacks of\n [] -> Nothing\n xs -> Just (head xs)\nattack dx dy (_, kx, ky) (_, x, y)\n | dx == 0 = diffX == 0 && ry >= 1\n | dy == 0 = diffY == 0 && rx >= 1\n | otherwise = rx >= 1 && rx >= 1 && ry == rx\n where\n diffX = x - kx\n diffY = y - ky\n rx = diffX `div` dx\n ry = diffY `div` dy\n\ncheckmate (_, kx, ky) (post, x, y)\n | post == \"R\" = dx == 0 || dy == 0\n | post == \"B\" = dy /= 0 && (abs (dx `div` dy) == 1)\n | post == \"Q\" = True\n where\n dx = x - kx\n dy = y - ky\n"}, {"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n runghc\n --package array\n --package base\n --package bytestring\n --package containers\n --package mtl\n --package parsec\n --package vector\n --\n -hide-all-packages\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\n\ntype N = Int\ntoNum = toInt\n\ndata Piece = Queen | Rook | Bishop\ndata Dir = U | D | L | R | UL | UR | DL | DR\n deriving (Eq, Ord, Show, Read, Enum, Bounded)\n\ntoDir (i, j)\n | i > 0 = case compare j 0 of\n GT -> UR\n EQ -> R\n LT -> DR\n | i < 0 = case compare j 0 of\n GT -> UL\n EQ -> L\n LT -> DL\n | otherwise = case compare j 0 of\n GT -> U\n EQ -> error \"invalid input\"\n LT -> D\n\nanswer :: (N, N) -> [(Piece, (N, N))] -> String\nanswer loc@(x,y) zs = if go (map fixCoord zs) then \"YES\" else \"NO\"\n where fixCoord (p, (x', y')) = (p, (x' - x, y' - y))\n go = go' . sortBy (comparing distance) . filter possible\n possible (_, (i, j)) = i == 0 || j == 0 || abs i == abs j\n distance (_, (i, j)) = max (abs i) (abs j)\n go' = go'' S.empty\n go'' _ [] = False\n go'' s ((p, coord):ps) = let d = toDir coord\n s' = S.insert d s\n in (isAttack p d && d `S.notMember` s)\n || go'' s' ps\n isAttack Queen _ = True\n isAttack Rook d = d `elem` [U, D, L, R]\n isAttack Bishop d = d `elem` [UL, UR, DL, DR]\n\nhandleInput :: ByteString -> ByteString\nhandleInput = lines\n & coerceInput answer\n & pack\n\ntoInt = readInt & fromJust & fst\ntoInte = readInteger & fromJust & fst\ntoX :: Read a => ByteString -> a\ntoX = unpack & read\n\ncoerceInput f (a:b:xs) = f (toTuple b) (map toPiece (take (toInt a) xs))\ncoerceInput _ _ = error \"invalid input\"\n\ntoTuple = words & map toNum & (\\(a:b:xs) -> (a, b))\n\ntoPiece xs = case words xs of\n (p:x:y:_) -> (toType (unpack p), (toNum x, toNum y))\n\ntoType \"B\" = Bishop\ntoType \"R\" = Rook\ntoType \"Q\" = Queen\n\nmain :: IO ()\nmain = interact handleInput\n\n-- Util stuff --\n(&) :: (a -> b) -> (b -> c) -> a -> c\n(&) = flip (.)\ninfixl 9 &\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\n\n---- Answer Code Section ----\n\ntype Pos = (Int, Int)\ntype ChessPiece = (Pos, Piece)\ndata Piece = Rook | Bishop | Queen | King | None deriving (Eq, Show, Generic)\ndata Dir = Hori | Vert | DownRight | UpRight deriving (Eq, Show, Enum)\ninstance NFData Piece\npos = fst\npiece = snd\n\ninf = 2*(10^9) :: Int\n\ncompDir Hori (x1, y1) (x2, y2) = compare y1 y2 `mappend` compare x1 x2\ncompDir Vert (x1, y1) (x2, y2) = compare x1 x2 `mappend` compare y1 y2\ncompDir DownRight p1 p2 = (compare `on` downRight) p1 p2 `mappend` (compare `on` upRight) p1 p2\ncompDir UpRight p1 p2 = (compare `on` upRight) p1 p2 `mappend` (compare `on` downRight) p1 p2\n\ncheckPos Hori (x1, y1) (x2, y2) = y1 == y2\ncheckPos Vert (x1, y1) (x2, y2) = x1 == x2\ncheckPos DownRight p1 p2 = downRight p1 == downRight p2\ncheckPos UpRight p1 p2 = upRight p1 == upRight p2\n\ncheckPiece Hori p = p == Rook || p == Queen\ncheckPiece Vert p = p == Rook || p == Queen\ncheckPiece DownRight p = p == Bishop || p == Queen\ncheckPiece UpRight p = p == Bishop || p == Queen\n\ndownRight (x, y) = x + y\nupRight (x, y) = x - y\n\nfindCheck :: ChessPiece -> [ChessPiece] -> (Pos -> Pos -> Ordering) -> (Pos -> Pos -> Bool) -> (Piece -> Bool) -> Bool\nfindCheck king chessPieces compFn checkPosFn checkPieceFn = isCheck sortedPieces where\n dummyPieces = map (\\p -> (p, None)) [(-inf, 0), (inf, 0), (0, -inf), (0, inf)]\n sortedPieces = sortBy (compFn `on` pos) (filter ((checkPosFn `on` pos) king) chessPieces ++ dummyPieces ++ [king])\n check king p = (checkPosFn `on` pos) king p && checkPieceFn (piece p)\n isCheck (prev:curr:next:xs) = if piece curr == King && (check curr prev || check curr next) then True else isCheck (curr:next:xs)\n isCheck _ = False\n\nprocess :: ChessPiece -> [ChessPiece] -> Bool\nprocess king chessPieces = any (\\dir -> findCheck king chessPieces (compDir dir) (checkPos dir) (checkPiece dir)) [Hori .. UpRight]\n\nmain = do\n n <- getInt\n kingPos <- readPoint <$> BS.getLine\n chessPieces <- replicateM n (readPiece <$> BS.getLine)\n if process (kingPos, King) chessPieces\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\nreadPoint str = (x,y) where x:y:[] = (map (fst . fromJust . BS8.readInt) . BS8.words) str\nreadPiece str = case BS8.uncons str of\n Just ('R', xs) -> (readPoint $ BS8.tail xs, Rook)\n Just ('B', xs) -> (readPoint $ BS8.tail xs, Bishop)\n Just ('Q', xs) -> (readPoint $ BS8.tail xs, Queen)\n "}], "negative_code": [{"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n runghc\n --package array\n --package base\n --package bytestring\n --package containers\n --package mtl\n --package parsec\n --package vector\n --\n -hide-all-packages\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\n\ntype N = Int\ntoNum = toInt\n\ndata Piece = Queen | Rook | Bishop\ndata Dir = U | D | L | R | UL | UR | DL | DR\n deriving (Eq, Ord, Show, Read, Enum, Bounded)\n\ntoDir (i, j)\n | i > 0 = case compare j 0 of\n GT -> UR\n EQ -> R\n LT -> DR\n | i < 0 = case compare j 0 of\n GT -> UL\n EQ -> L\n LT -> DL\n | otherwise = case compare j 0 of\n GT -> U\n EQ -> error \"invalid input\"\n LT -> D\n\nanswer :: (N, N) -> [(Piece, (N, N))] -> String\nanswer loc@(x,y) zs = if go (map fixCoord zs) then \"YES\" else \"NO\"\n where fixCoord (p, (x', y')) = (p, (x' - x, y' - y))\n go = go' . sortBy (comparing distance) . filter possible\n possible (_, (i, j)) = i == 0 || j == 0 || abs i == abs j\n distance (_, (i, j)) = abs i + abs j\n go' = go'' S.empty\n go'' _ [] = False\n go'' s ((p, coord):ps) = let d = toDir coord\n s' = S.insert d s\n in (isAttack p d && d `S.notMember` s)\n || go'' s' ps\n isAttack Queen _ = True\n isAttack Rook d = d `elem` [U, D, L, R]\n isAttack Bishop d = d `elem` [UL, UR, DL, DR]\n\nhandleInput :: ByteString -> ByteString\nhandleInput = lines\n & coerceInput answer\n & pack\n\ntoInt = readInt & fromJust & fst\ntoInte = readInteger & fromJust & fst\ntoX :: Read a => ByteString -> a\ntoX = unpack & read\n\ncoerceInput f (a:b:xs) = f (toTuple b) (map toPiece (take (toNum a) xs))\ncoerceInput _ _ = error \"invalid input\"\n\ntoTuple = words & map toNum & (\\(a:b:xs) -> (a, b))\n\ntoPiece xs = case words xs of\n (p:x:y:_) -> (toType (unpack p), (toNum x, toNum y))\n\ntoType \"B\" = Bishop\ntoType \"R\" = Rook\ntoType \"Q\" = Queen\n\nmain :: IO ()\nmain = interact handleInput\n\n-- Util stuff --\n(&) :: (a -> b) -> (b -> c) -> a -> c\n(&) = flip (.)\ninfixl 9 &\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.Int\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextChar :: Tokenizer Char\nnextChar = state $ \\(s:ss) -> (L.index s 0, ss)\n\ndata Piece = Piece { getType :: Char\n , getX :: Int\n , getY :: Int\n }\n\ncross :: Int -> Int -> Int -> Int -> Int64\ncross x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral y2 :: Int64) - (fromIntegral x2 :: Int64) * (fromIntegral y1 :: Int64)\n\ndot :: Int -> Int -> Int -> Int -> Int64\ndot x1 y1 x2 y2 = (fromIntegral x1 :: Int64) * (fromIntegral x2 :: Int64) + (fromIntegral y1 :: Int64) * (fromIntegral y2 :: Int64)\n\nsameDirection :: Int -> Int -> Int -> Int -> Int -> Int -> Bool\nsameDirection x1 y1 x2 y2 dx dy = cross vx vy dx dy == 0 && dot vx vy dx dy >= 0\n where vx = x2 - x1\n vy = y2 - y1 \n\ncheck :: Int -> Int -> [Piece] -> Bool\ncheck x0 y0 ps = getType best /= 'K'\n where best = foldl (closerPiece x0 y0) (Piece 'K' x0 y0) (map canMove cands)\n cands = [(closest x0 y0 dx dy ps, dx, dy) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)]\n\ncanMove :: (Piece, Int, Int) -> Piece\ncanMove (p, dx, dy) | t == 'B' && dx /= 0 && dy /= 0 = p\n | t == 'R' && (dx == 0 || dy == 0) = p\n | t == 'Q' = p\n | otherwise = Piece 'K' 0 0\n where t = getType p\n\ncloser :: Int -> Int -> Piece -> Piece -> Bool\ncloser x0 y0 p1 p2 = t2 == 'K' || (t1 /= 'K' && t2 /= 'K' && dist1 < dist2)\n where dist1 = abs (x1 - x0) + abs (y1 - y0)\n dist2 = abs (x2 - x0) + abs (y2 - y0)\n Piece t1 x1 y1 = p1\n Piece t2 x2 y2 = p2\n\ncloserPiece :: Int -> Int -> Piece -> Piece -> Piece\ncloserPiece x0 y0 p1 p2 | closer x0 y0 p1 p2 = p1\n | otherwise = p2\n\nclosest :: Int -> Int -> Int -> Int -> [Piece] -> Piece\nclosest x0 y0 dx dy [] = Piece 'K' x0 y0\nclosest x0 y0 dx dy (p:ps) | sameDirection x0 y0 x1 y1 dx dy && closer x0 y0 p best = p\n | otherwise = best\n where best = closest x0 y0 dx dy ps\n Piece _ x1 y1 = p\n\nsolve :: Tokenizer String\nsolve = do\n n <- nextInt\n x0 <- nextInt\n y0 <- nextInt\n p <- replicateM n $ do\n t <- nextChar\n x <- nextInt\n y <- nextInt\n return $ Piece t x y\n if (check x0 y0 p) then return \"YES\"\n else return \"NO\"\n\nmain = do\n contents <- L.getContents\n putStrLn $ evalState solve (L.words contents)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.Int\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextChar :: Tokenizer Char\nnextChar = state $ \\(s:ss) -> (L.index s 0, ss)\n\ndata Piece = Piece { getType :: Char\n , getX :: Int\n , getY :: Int\n }\n\ncross :: Int -> Int -> Int -> Int -> Int64\ncross x1 y1 x2 y2 = (fromIntegral x1) * (fromIntegral y2) - (fromIntegral x2) * (fromIntegral y1)\n\ndot :: Int -> Int -> Int -> Int -> Int64\ndot x1 y1 x2 y2 = (fromIntegral x1) * (fromIntegral x2) + (fromIntegral y1) * (fromIntegral y2)\n\nsameDirection :: Int -> Int -> Int -> Int -> Int -> Int -> Bool\nsameDirection x1 y1 x2 y2 dx dy = cross vx vy dx dy == 0 && dot vx vy dx dy >= 0\n where vx = x2 - x1\n vy = y2 - y1 \n\ncheck :: Int -> Int -> [Piece] -> Bool\ncheck x0 y0 ps = getType best /= 'K'\n where best = foldl (closerPiece x0 y0) (Piece 'K' x0 y0) (map canMove cands)\n cands = [(closest x0 y0 dx dy ps, dx, dy) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)]\n\ncanMove :: (Piece, Int, Int) -> Piece\ncanMove (p, dx, dy) | t == 'B' && dx /= 0 && dy /= 0 = p\n | t == 'R' && (dx == 0 || dy == 0) = p\n | t == 'Q' = p\n | otherwise = Piece 'K' 0 0\n where t = getType p\n\ncloser :: Int -> Int -> Piece -> Piece -> Bool\ncloser x0 y0 p1 p2 = t2 == 'K' || (t1 /= 'K' && t2 /= 'K' && dist1 < dist2)\n where dist1 = abs (x1 - x0) + abs (y1 - y0)\n dist2 = abs (x2 - x0) + abs (y2 - y0)\n Piece t1 x1 y1 = p1\n Piece t2 x2 y2 = p2\n\ncloserPiece :: Int -> Int -> Piece -> Piece -> Piece\ncloserPiece x0 y0 p1 p2 | closer x0 y0 p1 p2 = p1\n | otherwise = p2\n\nclosest :: Int -> Int -> Int -> Int -> [Piece] -> Piece\nclosest x0 y0 dx dy [] = Piece 'K' x0 y0\nclosest x0 y0 dx dy (p:ps) | sameDirection x0 y0 x1 y1 dx dy && closer x0 y0 p best = p\n | otherwise = best\n where best = closest x0 y0 dx dy ps\n Piece _ x1 y1 = p\n\nsolve :: Tokenizer String\nsolve = do\n n <- nextInt\n x0 <- nextInt\n y0 <- nextInt\n p <- replicateM n $ do\n t <- nextChar\n x <- nextInt\n y <- nextInt\n return $ Piece t x y\n if (check x0 y0 p) then return \"YES\"\n else return \"NO\"\n\nmain = do\n contents <- L.getContents\n putStrLn $ evalState solve (L.words contents)\n"}], "src_uid": "b389750613e9577b3abc9e5e5902b2db"} {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n\nm :: Int64\nm = 998_244_353\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\nmI :: Int -> M\nmI = M . fromIntegral\n\ninstance Show M where \n show (M v) = \"M\" ++ show v\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = M $ (a * b) `mod` m\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int64\nsolve n s as bs = unM $ solve' (M 0) (reverse abs) (reverse ms)\n where\n abs = sort $ zip as bs\n diffSL :: [Int] -> [Int] -> [Int]\n diffSL [] _ = []\n diffSL as [] = as\n diffSL as@(a:otherAs) bs@(b:otherBs)\n | a < b = a : diffSL otherAs bs\n | a == b = diffSL otherAs otherBs\n | a > b = diffSL as otherBs\n\n ms = diffSL [1 .. n] (sort bs)\n\n solve' :: M -> [(Int, Int)] -> [Int] -> M\n solve' k [] _ = M 1\n solve' k abs@((a, b):otherABs) ms\n | b == -1 && L.null ms = k * solve' (k - M 1) otherABs ms\n | b == -1 && head ms >= a - s = solve' (k + M 1) abs (tail ms)\n | b == -1 = k * solve' (k - M 1) otherABs ms\n | a - s > b = M 0\n | otherwise = solve' k otherABs ms\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, s] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntB8s \n bs <- B8.getLine <&> readIntB8s \n let answer = solve n s as bs\n printf \"%lld\\n\" answer\n\n\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n\nm :: Int64\nm = 998_244_353\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\nmI :: Int -> M\nmI = M . fromIntegral\n\ninstance Show M where \n show (M v) = \"M\" ++ show v\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = let c = a * b in \n if c >= m \n then M $ c `mod` m\n else M c\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int64\nsolve n s as bs = unM $ solve' (M 0) (reverse abs) (reverse ms)\n where\n abs = sort $ zip as bs\n diffSL :: [Int] -> [Int] -> [Int]\n diffSL [] _ = []\n diffSL as [] = as\n diffSL as@(a:otherAs) bs@(b:otherBs)\n | a < b = a : diffSL otherAs bs\n | a == b = diffSL otherAs otherBs\n | a > b = diffSL as otherBs\n\n ms = diffSL [1 .. n] (sort bs)\n\n solve' :: M -> [(Int, Int)] -> [Int] -> M\n solve' k [] _ = M 1\n solve' k abs@((a, b):otherABs) ms\n | b == -1 && L.null ms = k * solve' (k - M 1) otherABs ms\n | b == -1 && head ms >= a - s = solve' (k + M 1) abs (tail ms)\n | b == -1 = k * solve' (k - M 1) otherABs ms\n | a - s > b = M 0\n | otherwise = solve' k otherABs ms\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, s] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntB8s \n bs <- B8.getLine <&> readIntB8s \n let answer = solve n s as bs\n printf \"%lld\\n\" answer\n\n\n"}], "negative_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n\nm :: Int64\nm = 998_244_353\n\nnewtype M = M { unM :: Int64 }\n deriving (Eq, Ord)\n\nmI :: Int -> M\nmI = M . fromIntegral\n\ninstance Show M where \n show (M v) = \"M\" ++ show v\n\ninstance Num M where\n fromInteger n = M $ fromInteger (n `mod` fromIntegral m)\n\n (M a) + (M b) | a + b >= m = M $ a + b - m\n (M a) + (M b) = M $ a + b\n\n\n (M a) - (M b) | a - b < 0 = M $ m + a - b\n (M a) - (M b) = M $ a - b\n\n (M a) * (M b) = M $ (a * b) `mod` m\n\n abs = id\n signum = undefined\n\npowM :: M -> Int64 -> M\npowM a@(M ma) x\n | x == 0 = M 1\n | x == 1 = a\n | even x = let t = powM a (x `div` 2) in t * t\n | odd x = a * powM a (x - 1)\n\ninstance Fractional M where\n recip a = powM a $ m - 2\n fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)\n\n\ntype GraphA = A.Array Int [Int]\n\n\ngraphFromEdges :: Int -> [(Int, Int)] -> GraphA\ngraphFromEdges n edges = graph\n where\n graph = STA.runSTArray $ do\n graphA <- MA.newArray (1, n) ([] :: [Int])\n forM_ edges $ \\(u, v) -> do\n modifyArray graphA u (v:)\n modifyArray graphA v (u:)\n return graphA\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> Int -> [Int] -> [Int] -> Int64\nsolve n s as bs = unM $ solve' 0 (reverse abs) (reverse ms)\n where\n abs = sort $ zip as bs\n diffSL :: [Int] -> [Int] -> [Int]\n diffSL [] _ = []\n diffSL as [] = as\n diffSL as@(a:otherAs) bs@(b:otherBs)\n | a < b = a : diffSL otherAs bs\n | a == b = diffSL otherAs otherBs\n | a > b = diffSL as otherBs\n\n ms = diffSL (sort as) (sort bs)\n\n solve' :: Int -> [(Int, Int)] -> [Int] -> M\n solve' k [] _ = M 1\n solve' k (_:otherABs) [] = mI k * solve' (k - 1) otherABs []\n solve' k abs@((a, -1):otherABs) ms@(m:otherMs)\n | m >= a - s = solve' (k + 1) abs otherMs\n | otherwise = mI k * solve' (k - 1) otherABs ms\n\n solve' k abs@((a, b):otherABs) ms\n | a - s > b = M 0\n | otherwise = solve' k otherABs ms\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, s] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntB8s \n bs <- B8.getLine <&> readIntB8s \n let answer = solve n s as bs\n printf \"%lld\\n\" answer\n\n"}], "src_uid": "0f58ac08a26ce735bfe13fd089b7f746"} {"source_code": "import Control.Monad\nimport Data.Foldable\n\nfoldUntill :: Foldable t => (b -> Bool)-> (b -> a -> b) -> b -> t a -> Either (b,Maybe b,Maybe a) b\nfoldUntill predicate binary accumulator foldable =\n if predicate accumulator\n then Left (accumulator,Nothing,Nothing)\n else foldlM f accumulator foldable\n where\n f acc val =\n let\n newValue = binary acc val\n bool = predicate newValue\n in\n if bool\n then Left (newValue,Just acc,Just val)\n else Right newValue\n\ntype State = (Int , Indexed Int) -- (value , indexed maxval)\ntype Index = Int\ntype Indexed a = (Index, a)\n\nsolve :: Int -> [Int] -> Either (State, Maybe State, Maybe (Indexed Int)) State\nsolve p l = foldUntill predicate binary acc indexed\n where\n indexed = zip [1..] l\n acc = (0, (0,0))\n predicate (val,_)= val>p\n binary (summe,(ind,maks)) (ival,val) =let bigger = if val>maks then (ival,val) else (ind,maks) in (summe + val, bigger )\n\nanalysis :: Either (State, Maybe State, Maybe (Indexed Int)) State -> Int\nanalysis (Right _) = 0\nanalysis (Left ((_,(index,_)),_,_)) = index\n\nloesen :: Int -> [Int] -> Int\nloesen p l = analysis $ solve p l\n\nroutine :: IO ()\nroutine = do\n [_,s] <- (map read . words) <$> getLine\n l <- (map read . words) <$> getLine\n print $ loesen s l\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n", "positive_code": [{"source_code": "import Control.Monad\nimport Prelude\nimport Data.List\nimport Data.Int\n\ntestCase = do\n nsStr <- getLine\n aStr <- getLine\n let\n ns = map (read :: String -> Int64) (words nsStr)\n n = head ns\n s = head $ tail ns\n as = map (read :: String -> Int64) (words aStr) in do\n print $ solution s as\n\nmain = do\n testCases <- getLine\n strNums <- replicateM (read testCases) testCase\n return ()\n\nprefixSumLessEq s [] = []\nprefixSumLessEq s (h:t) = case s >= h of\n True -> h:(prefixSumLessEq (s - h) t)\n False -> []\n\nsolution s as = case sum as <= s of\n True -> 0\n False -> case elemIndex (sol s 0 0 as) as of\n Just x -> x + 1\n\nsol s sm mx [] = 0\nsol s sm mx (h:t) = result where\n mx2 = max mx h\n sm2 = sm + h\n result = case (sm2 - mx2) <= s of\n True -> max mx2 (sol s sm2 mx2 t)\n False -> mx\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Prelude\nimport Data.List\n\ntestCase = do\n nsStr <- getLine\n aStr <- getLine\n let\n ns = map (read :: String -> Int) (words nsStr)\n n = head ns\n s = head $ tail ns\n as = map (read :: String -> Int) (words aStr) in do\n print $ solution s as\n\nmain = do\n testCases <- getLine\n strNums <- replicateM (read testCases) testCase\n return ()\n\nprefixSumLessEq s [] = []\nprefixSumLessEq s (h:t) = case s >= h of\n True -> h:(prefixSumLessEq (s - h) t)\n False -> []\n\nsolution s as = case sum as <= s of\n True -> 0\n False -> case elemIndex (sol s 0 0 as) as of\n Just x -> x + 1\n\nsol s sm mx [] = 0\nsol s sm mx (h:t) = result where\n mx2 = max mx h\n sm2 = sm + h\n result = case (sm2 - mx2) <= s of\n True -> max mx2 (sol s sm2 mx2 t)\n False -> mx\n"}], "src_uid": "0924971933265f4be34710149a541087"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Map.Strict as MapS\r\n\r\nmain = do\r\n t <- readLn\r\n replicateM_ t testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n firstLine <- getLine\r\n let [n,k] = map read . words $ firstLine\r\n putStrLn $ solve n k\r\n\r\nsolve :: Int -> Int -> String\r\nsolve n k \r\n | odd n = unwords . map show $ [1, (n-1) `div` 2, (n-1) `div` 2]\r\n | n `mod` 4 == 0 = unwords. map show $ [n `div` 2 , n `div` 4, n `div` 4]\r\n | otherwise = unwords. map show $ [2, (n-2) `div` 2, (n-2) `div` 2]", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nsolve :: Int -> [Int]\nsolve n\n | odd n = 1 : replicate 2 (div n 2)\n | mod n 4 == 0 = div n 2 : replicate 2 (div n 4)\n | otherwise = 2 : replicate 2 (div n 2 - 1)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, k] <- readInts\n putInts $ solve (n - (k - 3)) ++ replicate (k - 3) 1\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List (group, sort)\nimport Data.Map ((!))\nimport qualified Data.Map as M\n-- import Debug.Trace\n\nimport Data.Maybe (fromJust)\nimport System.IO\nimport Text.Read\n\ngetNums :: IO [Int]\ngetNums = do\n line <- B.getLine\n return $ map ((fst . fromJust) . B.readInt) . B.split ' ' $ line\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n [n, k] <- getNums\n putStrLn $ unwords $ map show $ solve n k\n\nsolveEasy :: Int -> [Int]\nsolveEasy n\n | n `mod` 2 == 1 = [1, (n - 1) `div` 2, (n -1) `div` 2]\n | n `mod` 4 == 0 = [n `div` 2, n `div` 4, n `div` 4]\n | n `mod` 4 == 2 = [2, (n - 1) `div` 2, (n -1) `div` 2]\n\nsolve n k = replicate (k - 3) 1 ++ solveEasy (n - (k - 3))\n"}], "negative_code": [], "src_uid": "842a0587147591ea38a20638f3a7960d"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [x, y, k] <- map read . words <$> getLine :: IO [Integer]\n let\n sticksReq = k * (1 + y)\n ceilDiv p q = div (p + q - 1) q\n type1 = ceilDiv (sticksReq - 1) (x - 1)\n type2 = k\n print (type1 + type2)\n", "positive_code": [{"source_code": "module Main where\n \nsolve [x,y,k] = (((y + 1) * k - 1 + x - 2) `div` (x - 1)) + k\n\nmain = do\n interact $ unlines . map (show . solve) . map ( map (read :: String -> Integer) . words ) . tail . lines "}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Foldable\nimport Data.Graph\nimport Data.List\n\nsolve [a, b, c] = (b * c + c - 1 + a - 2) `div` (a - 1) + c\n\nmain = do\n a <- read <$> getLine\n replicateM_ a $ do\n i <- map read . words <$> getLine\n print $ solve i"}], "negative_code": [], "src_uid": "28610d192329c78580db354f8dfc4094"} {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = map read . words <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\ncalc :: Double -> Double -> Double -> (Int, Int)\ncalc n k t = \n let \n i = floor (n*t/100) + 1\n ai = floor (n*k*t/100 - (fi i - 1) * k)\n in (i, ai)\n\nmakeBar :: Double -> Double -> Int -> Int -> String\nmakeBar n k i ai =\n unwords . map show $ values\n where \n values :: [Int]\n values \n | n >= fi i = replicate (i - 1) (round k) ++ [ai] ++ replicate (round n - i) 0\n | otherwise = replicate (round n) (round k)\n\nmain = do\n [n, k, t] <- doubles\n let (i, ai) = calc n k t\n putStrLn $ makeBar n k i ai \n \n ", "positive_code": [{"source_code": "main=getLine>>=putStrLn.unwords.slv.map read.words\nslv :: [Int] -> [String]\nslv (n:k:100:_) = map show $ replicate n k\nslv (n:k:t:_) =\n map show $ replicate nFull k ++ [v] ++ replicate (n - nFull - 1) 0\n where \n nFull = p `div` k\n v = p `mod` k\n p = floor $ (fromIntegral k)*(fromIntegral n)*(fromIntegral t) / 100\n "}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, k, t] <- ( map read . words ) `liftM` getLine\n\n let a = n * t `div` 100\n m = ( n * t - 100 * a ) * k `div` 100\n out = unwords $ map show $ if a == n\n then replicate a k\n else replicate a k ++ [m] ++ replicate (n-a-1) 0\n\n putStrLn out\n"}, {"source_code": "solve :: Int -> Int -> Int -> [Int]\nsolve n k t\n\t| t <= k = t:(take (n-1) (repeat 0))\n\t| otherwise = k:(solve (n-1) k (t-k))\n\nmain = do\n\t[n,k,t] <- getLine >>= return . map read . words\n\tputStrLn . unwords . map show $ solve n k ((n*k)*t`div`100)\n"}, {"source_code": "printAns :: Int -> Int -> Int -> Int -> IO ()\nprintAns n k m m2 = \n putStrLn (foldl (\\x y -> x ++ show k ++ \" \") \"\" [1..m]\n ++ if m == n then \"\" else (show m2)\n ++ foldl (\\x y -> x ++ \" 0\") \"\" [1..(n - m - 1)])\n\nmain = do\n line <- getLine\n let [n, k, t] = map (read::String->Int) (words line)\n let j = div (t * n * k) 100\n let m = div (t * n) 100\n let m2 = div (t * n * k - 100 * m * k) 100\n printAns n k m m2"}, {"source_code": "-- Codeforces 71B\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n [n, k, t] <- (map read . words) <$> getLine :: IO [Int]\n let (u, v) = (t * (n * k) `div` 100) `divMod` k\n r = if u == n\n then replicate u k\n else replicate u k ++ [v] ++ replicate (n - u - 1) 0\n putStrLn $ intercalate \" \" (map show r)\n"}, {"source_code": "main = do\n\t[n, k, t] <- (map read . words) `fmap` getLine\n let t' = toRational (t * n) / 100\n (\u0447\u0451\u0440\u043d\u044b\u0435, \u0441\u0435\u0440\u043e\u0441\u0442\u044c) = properFraction t'\n as = replicate \u0447\u0451\u0440\u043d\u044b\u0435 k ++ \n replicate (ceiling \u0441\u0435\u0440\u043e\u0441\u0442\u044c) (floor (toRational k * \u0441\u0435\u0440\u043e\u0441\u0442\u044c)) ++\n replicate (n - ceiling t') 0\n\tputStrLn $ unwords $ map show as\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ngen k t\n\t| t >= k = Just (show k,t-k)\n\t| t > 0 = Just (show t,0)\n\t| otherwise = Just (show 0,0)\n\nmain = do\n\t(sn:sk:st:_) <- words <$> getLine\n\tlet n = read sn :: Int\n\tlet k = read sk :: Int\n\tlet t = read st :: Int\n\tputStr $ unwords $ take n $ unfoldr (gen k) $ truncate $ realToFrac (t*k*n)/100"}, {"source_code": "module Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.DeepSeq\nimport Data.Function\nimport Data.List\nimport Data.Char\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = fmap head . sequence . map print\nprintStrs = fmap head . sequence . map putStrLn\n\nprocess :: Int -> Int -> Int -> [Int]\nprocess n k t = take n infBar where\n b = floor (fromIntegral (n * k * t) / 100)\n (q, r) = b `divMod` k\n infBar = replicate q k ++ [r] ++ repeat 0\n\nmain = do\n (n:k:[t]) <- getInts\n putStrLn . unwords . map show $ process n k t\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\n\n\ng:: Int -> Int -> Int -> (Int,Int)\ng n k t = (s,m)\n where n' = (n*k*t `div` 100)\n s = n' `div` k\n m = n' `mod` k\n \nfloor' :: (Integral a) => a -> a\nfloor' = floor . fromIntegral\n\nf n m s k = take n (l ++ [m] ++ r)\n where l = ((take (fromIntegral s)) . repeat $ k) \n m' = (if (length (l++r))>=n then [] else [m])\n r = repeat 0 \n\n\nmain :: IO ()\nmain = do { n:k:t:_ <- map read . split . head . lines <$> getContents\n ; let (s,m) = g n k t in\n mapM_ (printf \"%d \") $ f n m s k\n }\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\n\n\ng:: Int -> Int -> Int -> (Int,Int)\ng n k t = (s,m)\n where n' = (n*k*t `div` 100)\n s = n' `div` k\n m = n' `mod` k\n \nfloor' :: (Integral a) => a -> a\nfloor' = floor . fromIntegral\n\nf n m s k = l ++ m' ++ r\n where l = ((take (fromIntegral s)) . repeat $ k) \n m' = (if (length (l++r))>=n then [] else [m])\n r = (take (n-(fromIntegral s) - 1) . repeat $ 0)\n\n\nmain :: IO ()\nmain = do { n:k:t:_ <- map read . split . head . lines <$> getContents\n ; let (s,m) = g n k t in\n mapM_ (printf \"%d \") $ f n m s k\n }\n\n"}], "negative_code": [{"source_code": "-- Codeforces 71B\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n [n, k, t] <- (map read . words) <$> getLine :: IO [Int]\n let (u, v) = (t * (n * k) `div` 100) `divMod` k\n r = if u == n\n then replicate u k\n else replicate u k ++ [v] ++ replicate (n - u - 1) 0\n print (u, v)\n putStrLn $ intercalate \" \" (map show r)\n"}, {"source_code": "-- Codeforces 71B\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n [n, k, t] <- (map read . words) <$> getLine :: IO [Int]\n let (u, v) = (t * (n * k) `div` 100) `divMod` k\n r = replicate u k ++ [v] ++ replicate (n - u - 1) 0\n putStrLn $ intercalate \" \" (map show r)\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = map read . words <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\ncalc :: Double -> Double -> Double -> (Int, Int)\ncalc n k t = \n let i = floor (n*t/100) + 1\n ai = floor (n*k*t/100 - (fi i - 1) * k)\n in (i, ai)\n\nmakeBar :: Double -> Double -> Int -> Int -> String\nmakeBar n k i ai =\n unwords . map show $ values\n where \n values :: [Int]\n values = replicate (i - 1) (round k) ++ [ai] ++ replicate (round n - i) 0\n\nmain = do\n [n, k, t] <- doubles\n let (i, ai) = calc n k t\n putStrLn $ makeBar n k i ai \n \n "}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = read <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\nprogressbar :: Int -> Int -> Int -> [Int]\nprogressbar n k t =\n let t' = fi t\n n' = fi n\n k' = fi k\n sigai = n' * k' * t' / 100\n (nSats, rem) = floor sigai `divMod` k\n in replicate nSats k ++ [rem] ++ replicate (n - nSats - 1) 0\n\nmain = do\n [n, k, t] <- ints\n let res = progressbar n k t\n putStrLn (unwords (map show res))\n"}, {"source_code": "main = do\n\t[n, k, t] <- (map read . words) `fmap` getLine\n\tlet tnk = t * n * k\n\t f s | (s + k) * 100 < tnk = k\n\t\t| s * 100 <= tnk && (s + k) * 100 > tnk = (tnk - s * 100) `div` 100\n\t\t| otherwise = 0\n\tlet as = reverse $ snd $ foldl (\\(s, as) _ -> (s + f s, f s:as)) (0, []) [1..n]\n\tputStrLn $ unwords $ map show as\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\n\n\ng:: Int -> Int -> Int -> (Int,Int)\ng n k t = (s,m)\n where n' = (n*k*t `div` 100)\n s = n' `div` k\n m = n' `mod` k\n \nfloor' :: (Integral a) => a -> a\nfloor' = floor . fromIntegral\n\nf n m s k = ((take (fromIntegral s)) . repeat $ k) ++ [m] ++ (take (n-(fromIntegral s) - 1) . repeat $ 0)\n\n\nmain :: IO ()\nmain = do { n:k:t:_ <- map read . split . head . lines <$> getContents\n ; let (s,m) = g n k t in\n mapM_ (printf \"%d \") $ f n m s k\n }\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\n\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy p [] = []\nsplitBy p xs = a : (splitBy p $ dropWhile p $ b)\n where\n (a, b) = break p xs\n \nsplit :: String -> [String]\nsplit = splitBy (==' ')\n\n\n\ng:: Int -> Int -> Int -> (Int,Int)\ng n k t = (s,m)\n where n' = (n*k*t `div` 100)\n s = n' `div` k\n m = n' `mod` k\n \nfloor' :: (Integral a) => a -> a\nfloor' = floor . fromIntegral\n\nf n m s k = take n (l ++ [m] ++ [0..])\n where l = ((take (fromIntegral s)) . repeat $ k) \n m' = (if (length (l++r))>=n then [] else [m])\n r = repeat 0 \n\n\nmain :: IO ()\nmain = do { n:k:t:_ <- map read . split . head . lines <$> getContents\n ; let (s,m) = g n k t in\n mapM_ (printf \"%d \") $ f n m s k\n }\n\n"}, {"source_code": "main=getLine>>=putStrLn.unwords.slv.map read.words\nslv :: [Int] -> [String]\nslv (n:k:t:_) =\n map show $ replicate nFull k ++ [v] ++ replicate (n - nFull - 1) 0\n where \n nFull = p `div` k\n v = p `mod` k\n p = floor $ (fromIntegral k)*(fromIntegral n)*(fromIntegral t) / 100\n "}], "src_uid": "0ad96b6a8032d70df400bf2ad72174bf"} {"source_code": "import Data.List\nmain=do\n (_:a)<-fmap (map read . words) getContents::IO [Int]\n let m=length [(x,y)|(x:ys)<-tails a,y<-ys,x>y]\n print $ (div m 2)*3+(m-(div m 2))", "positive_code": [{"source_code": "import Data.List\nmain=do\n (_:a)<-fmap (map read . words) getContents::IO [Int]\n let m=length [(x,y)|(x:ys)<-tails a,y<-ys,x>y]\n print $ (div m 2)*3+(m-(div m 2))"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLn\n ps <- readsLine\n print $ solve n ps\n\nreverseNumber ps = length $ do\n (i,pi) <- zip [1..] ps\n pj <- drop i ps\n guard $ pi > pj\n return ()\n\nsolve :: Int -> [Int] -> Int\nsolve n ps | even k = 2*k\n | otherwise = 2*(k-1) + 1\n where\n k = reverseNumber ps\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadsInt = map readInt . B.words <$> B.getLine\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\ncasti = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\n\nmain = do\n n <- readLn\n ps <- readsLine\n print $ solve n ps\n\nreverseNumber ps = length $ do\n (i,pi) <- zip [1..] ps\n pj <- drop i ps\n guard $ pi > pj\n return ()\n\nsolve :: Int -> [Int] -> Int\nsolve n ps | k == 0 = 0\n | otherwise = 2*(k-1) + 1\n where\n k = reverseNumber ps\n"}], "src_uid": "c4609bd2b4652cb5c2482b16909ec64a"} {"source_code": "main = do\n (n:as) <- fmap (map read . words) getContents\n let counted = count as\n putStrLn $ if ((all (== head counted)) counted) then \"YES\" else \"NO\"\n return ()\n\ncount :: [Int] -> [Int]\ncount (a:as) = count' a as where\n count' a [] = [1]\n count' a (b:bs) = if a == b\n then\n let d:ds = count' b bs in (d+1):ds\n else\n 1 : count' b bs\n", "positive_code": [{"source_code": "wordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n [] -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n\nce :: (String -> Bool) -> [String] -> (Integer, [String])\nce _ [] = (0, [])\nce p (x:xs) = case p x of\n True -> (1 + fst r, snd r)\n where r = ce p xs\n False -> (0, x:xs)\n\nchange :: [String] -> [Integer]\nchange [] = []\nchange (x:xs) = fst r : change (snd r)\n where r = ce (== x) (x:xs)\n\nisPossible :: [Integer] -> Bool\nisPossible [] = True\nisPossible (x:[]) = True\nisPossible (x:x':xs) = (x == x') && (isPossible (x':xs))\n\nmakeString :: Bool -> String\nmakeString True = \"YES\"\nmakeString False = \"NO\"\n\nsolve :: String -> String\nsolve str = makeString $ isPossible $ change $ words sec\n where (_:sec:_) = lines str\n\nmain = interact solve\n"}, {"source_code": "main = f\n\nf = do\n n <- getLine\n --let x = read n :: Int\n img <- getLine\n let pixels = words img\n let first = head pixels\n putStrLn $ if check (words img) first then \"YES\" else \"NO\"\n \ncheck l curr = check_rec l curr 0\n\ncheck_rec [] _ _ = True\n\ncheck_rec l curr 0 = \n let len = length $ takeWhile (\\x -> x == curr) l in\n check_rec (drop len l) (changeSymbol curr) len\n\ncheck_rec l curr n = \n let len = length $ takeWhile (\\x -> x == curr) l in\n if len /= n then False else check_rec (drop len l) (changeSymbol curr) n\n\nchangeSymbol \"1\" = \"0\"\nchangeSymbol \"0\" = \"1\""}, {"source_code": "-- |inputs: (x:xs) is the photo\n-- width is the width of the first stripe, or 0 if yet unknown\n-- val is the colour of the current stripe\n-- acc is the width of the current stripe\nsolve_rec :: [Int] -> Int -> Int -> Int -> String\nsolve_rec [] width _ acc\n | width == 0 = \"YES\"\n | width == acc = \"YES\"\n | otherwise = \"NO\"\nsolve_rec (x:xs) width val acc\n | width == 0 =\n if val == x then solve_rec xs width x (acc + 1)\n else solve_rec xs acc x 1\n | width > acc =\n if val == x then solve_rec xs width x (acc + 1)\n else \"NO\"\n | otherwise =\n if val == x then \"NO\"\n else solve_rec xs width x 1\n\n-- wrapper function to call recursive helper\nsolve :: [Int] -> String\nsolve (x:xs) = solve_rec (x:xs) 0 x 0\n\n-- ignore first line and read second line as [Int]\nmain = do\n _ <- getLine\n s <- getLine\n -- must use putStrLn because print outputs quotation marks\n putStrLn $ solve $ map read $ words s\n"}, {"source_code": "read_array :: String -> [Int]\nread_array = map read . words\n\nget_width :: [Int] -> Int -> Int -> Int\nget_width [] _ acc = acc\nget_width (x:xs) val acc\n | x == val = get_width xs val (acc + 1)\n | otherwise = acc\n\nsolve_rec :: [Int] -> Int -> Int -> Int -> String\nsolve_rec [] width _ acc\n | acc == width = \"YES\"\n | otherwise = \"NO\"\nsolve_rec (x:xs) width val acc\n | x == val && acc < width = solve_rec xs width val (acc + 1)\n | x == val && acc >= width = \"NO\"\n | x /= val && acc < width = \"NO\"\n | 1 == val && acc >= width = solve_rec xs width 0 1\n | 0 == val && acc >= width = solve_rec xs width 1 1\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0\n\nsolves :: [Int] -> Int\nsolves (x:xs) = get_width (x:xs) x 0\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n s <- getLine :: IO String\n putStrLn (solve (read_array s))\n"}, {"source_code": "getInts = fmap (map read . words) getLine :: IO [Int]\n\nconv ans cnt last [] = cnt:ans\nconv ans cnt last (x:xs) =\n if last == x\n then conv ans (cnt + 1) last xs\n else conv (cnt:ans) 1 x xs\n\nallTheSame xs = and $ map (== head xs) (tail xs)\n\nsolve (x:xs) =\n if allTheSame (conv [] 1 x xs)\n then \"YES\"\n else \"NO\"\n\nmain = do\n n <- getLine\n a <- getInts\n putStrLn $ solve a\n"}, {"source_code": "readInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nprocess0 :: Int -> [Int] -> (Int,[Int])\nprocess0 x [] = (0,[])\nprocess0 x (y:as) = if x==y then (1 + (fst d),(snd d)) else (0,(y:as))\n where d = process0 x as\n\nprocess :: [Int] -> [Int]\nprocess [] = []\nprocess (x:as) = ((fst d):(process (snd d)))\n where d = (process0 x (x:as))\n\nmain :: IO()\nmain = do\n s <- getLine\n let x = (read s :: Int)\n a <- readInts\n let b = process a\n let t = and $ map (== head b) (tail b)\n let ans = if t then \"YES\" else \"NO\" \n putStrLn ans\n"}], "negative_code": [{"source_code": "read_array :: String -> [Int]\nread_array = map read . words\n\nget_width :: [Int] -> Int -> Int -> Int\nget_width [] _ acc = acc\nget_width (x:xs) val acc\n | x == val = get_width xs val (acc + 1)\n | otherwise = acc\n\nsolve_rec :: [Int] -> Int -> Int -> Int -> String\nsolve_rec [] _ _ _ = \"YES\"\nsolve_rec (x:xs) width val acc\n | x == val && acc < width = solve_rec xs width val (acc + 1)\n | x == val && acc >= width = \"NO\"\n | x /= val && acc < width = \"NO\"\n | 1 == val && acc >= width = solve_rec xs width 0 1\n | 0 == val && acc >= width = solve_rec xs width 1 1\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0\n\nsolves :: [Int] -> Int\nsolves (x:xs) = get_width (x:xs) x 0\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n s <- getLine :: IO String\n print (solve (read_array s))\n"}, {"source_code": "read_array :: String -> [Int]\nread_array = map read . words\n\nget_width :: [Int] -> Int -> Int -> Int\nget_width [] _ acc = acc\nget_width (x:xs) val acc\n | x == val = get_width xs val (acc + 1)\n | otherwise = acc\n\nsolve_rec :: [Int] -> Int -> Int -> Int -> String\nsolve_rec [] _ _ _ = \"YES\"\nsolve_rec (x:xs) width val acc\n | x == val && acc < width = solve_rec xs width val (acc + 1)\n | x == val && acc >= width = \"NO\"\n | x /= val && acc < width = \"NO\"\n | 1 == val && acc >= width = solve_rec xs width 0 1\n | 0 == val && acc >= width = solve_rec xs width 1 1\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0\n\nsolves :: [Int] -> Int\nsolves (x:xs) = get_width (x:xs) x 0\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n s <- getLine :: IO String\n putStrLn (solve (read_array s))\n"}, {"source_code": "read_array :: String -> [Int]\nread_array = map read . words\n\nget_width :: [Int] -> Int -> Int -> Int\nget_width [] _ acc = acc\nget_width (x:xs) val acc\n | x == val = get_width xs val (acc + 1)\n | otherwise = acc\n\nsolve_rec :: [Int] -> Int -> Int -> Int -> String\nsolve_rec [] _ val acc\n | val == acc = \"YES\"\n | otherwise = \"NO\"\nsolve_rec (x:xs) width val acc\n | x == val && acc < width = solve_rec xs width val (acc + 1)\n | x == val && acc >= width = \"NO\"\n | x /= val && acc < width = \"NO\"\n | 1 == val && acc >= width = solve_rec xs width 0 1\n | 0 == val && acc >= width = solve_rec xs width 1 1\n\nsolve :: [Int] -> String\nsolve [] = \"YES\"\nsolve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0\n\nsolves :: [Int] -> Int\nsolves (x:xs) = get_width (x:xs) x 0\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n s <- getLine :: IO String\n putStrLn (solve (read_array s))\n"}], "src_uid": "75a00d8a614fd0bcb8504b0268a121e0"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (sort)\nimport Prelude hiding (reads)\n\nreads :: IO [Integer]\nreads = liftM (map read . words) getLine\n where\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + fromIntegral (ord c - ord '0')\n\nsolve :: Integer -> Integer -> [Integer] -> (Integer, Integer)\nsolve n k as = (a, b)\n where\n indexA = fromIntegral ((k-1) `div` n) + 1\n countA = fromIntegral $ length $ filter (== a) as\n countLessA = length $ filter (< a) as\n indexInGroup = k - n * fromIntegral countLessA\n indexB = fromIntegral ((indexInGroup - 1) `div` countA) + 1\n a = sort as !! (indexA - 1)\n b = sort as !! (indexB - 1)\n\ntest :: [Integer] -> IO ()\ntest as = do\n let n = fromIntegral $ length as\n let ans1 = sort [(a, b) | a <- as, b <- as]\n let ans2 = map (\\k -> solve n k as) [1..n*n]\n if ans1 == ans2 then\n print \"Ok\"\n else\n print \"Fail: \" >> print as\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- reads\n let (a, b) = solve n k as\n putStrLn $ concat [show a, \" \", show b]", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [Int] -> Integer -> Integer -> (Int, Int)\nsolve a k n = solve' a k\n where\n solve' (x:xs) k = let cnt = fromIntegral $ length $ takeWhile (== x) (x:xs) :: Integer\n all = cnt * n\n in if all > k\n then (x, a !! (fromIntegral (k `div` cnt)))\n else solve' (dropWhile (== x) xs) (k - all)\n\nmain = do\n [n, k] <- (map (toNumber . BS.readInteger) <$> (BS.words <$> BS.getLine)) :: IO [Integer]\n a <- (sort <$> map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\n let (f, s) = solve a (k - 1) n\n putStrLn $ (show f) ++ \" \" ++ (show s)\n\ntoNumber :: Num a => Maybe (a, BS.ByteString) -> a\ntoNumber (Just (x, _)) = x\ntoNumber Nothing = 0\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n [n, k] <- (map read <$> (words <$> getLine)) :: IO [Integer]\n a <- (sort <$> map read <$> (words <$> getLine)) :: IO [Int]\n putStrLn $ (show $ a !! (fromIntegral ((k - 1) `div` n))) ++ \" \" ++ (show $ a !! (fromIntegral ((k - 1) `mod` n)))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain = do\n [n, k] <- (map read <$> (words <$> getLine)) :: IO [Integer]\n a <- (sort <$> map read <$> (words <$> getLine)) :: IO [Integer]\n putStrLn $ (show $ a !! (fromIntegral ((k - 1) `div` n))) ++ \" \" ++ (show $ a !! (fromIntegral ((k - 1) `mod` n)))\n"}, {"source_code": "\nimport Data.List\n\ngetWords :: IO [String]\ngetWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = getWords >>= return . (map read)\n\nsolve :: (Int, Int) -> [Int] -> (Int, Int)\nsolve (n, k) xs = (x', sortXs !! (y `div` z))\n where\n sortXs = sort xs\n (x, y) = (k-1) `divMod` n\n x' = sortXs !! x\n z = length $ filter (== x') sortXs\n\nmain :: IO ()\nmain = do\n [n, k] <- Main.reads\n xs <- Main.reads\n let (x, y) = solve (n, k) xs\n putStrLn $ concat [show x, \" \", show y]\n "}, {"source_code": "\nimport List\n\ngetWords :: IO [String]\ngetWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = getWords >>= return . (map read)\n\nsolve :: (Int, Int) -> [Int] -> (Int, Int)\nsolve (n, k) xs = (sortXs !! x, sortXs !! y)\n where\n sortXs = sort xs\n (x, y) = (k-1) `divMod` n\n \n\nmain :: IO ()\nmain = do\n [n, k] <- Main.reads\n xs <- Main.reads\n let (x, y) = solve (n, k) xs\n putStrLn $ concat [show x, \" \", show y]"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (sort)\nimport Prelude hiding (print, reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Integer -> Integer -> [Int] -> (Int, Int)\nsolve n k xs = (xs' !! a, xs' !! b)\n where\n a = fromIntegral $ div (k-1) n\n b = fromIntegral $ mod (k-1) n\n xs' = sort xs\n\nprint :: (Int, Int) -> IO ()\nprint (a, b) = putStrLn $ concat [show a, \" \", show b]\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n xs <- reads\n print $ solve n k xs"}, {"source_code": "\nimport Data.List\n\ngetWords :: IO [String]\ngetWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = getWords >>= return . (map read)\n\nsolve :: (Integer, Integer) -> [Int] -> (Int, Int)\nsolve (n, k) xs = (x', sortXs !! ((fromIntegral y) `div` z))\n where\n sortXs = sort xs\n (x, y) = (k-1) `divMod` n\n x' = sortXs !! (fromIntegral x)\n z = length $ filter (== x') sortXs\n\nmain :: IO ()\nmain = do\n [n, k] <- Main.reads\n xs <- Main.reads\n let (x, y) = solve (n, k) xs\n putStrLn $ concat [show x, \" \", show y]\n "}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (sort)\nimport Prelude hiding (reads)\n\nreads :: IO [Integer]\nreads = liftM (map read . words) getLine\n where\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = fromIntegral a\n read' a (c:s) = read' (10*a + ord c - ord '0') s\n\nsolve :: Integer -> Integer -> [Integer] -> (Integer, Integer)\nsolve n k as = (a, b)\n where\n indexA = fromIntegral ((k-1) `div` n) + 1\n countA = fromIntegral $ length $ filter (== a) as\n countLessA = length $ filter (< a) as\n indexInGroup = k - n * fromIntegral countLessA\n indexB = fromIntegral ((indexInGroup - 1) `div` countA) + 1\n a = sort as !! (indexA - 1)\n b = sort as !! (indexB - 1)\n\ntest :: [Integer] -> IO ()\ntest as = do\n let n = fromIntegral $ length as\n let ans1 = sort [(a, b) | a <- as, b <- as]\n let ans2 = map (\\k -> solve n k as) [1..n*n]\n if ans1 == ans2 then\n print \"Ok\"\n else\n print \"Fail: \" >> print as\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- reads\n let (a, b) = solve n k as\n putStrLn $ concat [show a, \" \", show b]"}], "src_uid": "d3b9ffa76436b957ca959cf9204f9873"} {"source_code": "readInteger :: String -> Integer\nreadInteger token = read token :: Integer\n\nunchargedSlot = \".\"\nchargedSlot = \"X\"\n\ntoList :: a -> [a]\ntoList item = [item]\n\nprocessQuery :: Integer -> Integer -> Integer -> Integer -> String\nprocessQuery u v n x = if 0 <= x && x < n - t then\n unchargedSlot\n else if n - t <= x && x < n - v then\n if even (x - n + t) then\n unchargedSlot\n else\n chargedSlot\n else\n chargedSlot\n where t = 2 * u + v\n\nsolve :: [Integer] -> [String]\nsolve (n:k:p:queries) | odd (n - 2 * u - v) = map (processQuery (u - 1) (v + 1) n) q\n | otherwise = map (processQuery u v n) q\n where u = min k (n - k)\n v = k - u\n q = map pred queries\n\nmain :: IO ()\nmain = interact (unlines . toList . foldl (++) \"\" . solve . map readInteger . words)\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nimport Debug.Trace\n\nparseInput = do \n n <- readInteger\n k <- readInteger\n p <- readInt\n query <- replicateM p readInteger\n return (n, k, query)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, k, query) = map solvePosition query\n where\n solvePosition x\n | k == 0 = '.'\n | k == n = 'X'\n | k == 1 = if x == n then 'X' else '.'\n | partLeft = if x == left then 'X' else '.'\n | partA = if (x - left) `mod` 2 == 0 then 'X' else '.'\n | otherwise = 'X'\n where\n partLeft = x <= left\n partA = (x - left) <= 2 * a\n\n minB = n `mod` 2\n\n -- 2 * a + b <= n - 2\n -- a + b + 1 == k\n\n a = ((n - 2) - (k - 1)) `min` (k - 1 - minB)\n b = k - 1 - a\n\n left = n - 2 * a - b\n\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, k, p] <- ( map read . words ) `liftM` getLine :: IO [Integer]\n\n q <- replicateM (fromIntegral p) $ read `liftM` getLine\n let hn = ( n + 1 ) `div` 2\n\n putStrLn $ map (\\q -> let hq = q `div` 2 in if q `mod` 2 == 0\n then if hq + k > hn then 'X' else '.'\n else if k > 0 && q == n || hq + k >= n then 'X' else '.'\n ) q\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, k, p] <- ( map read . words ) `liftM` getLine\n\n q <- replicateM p $ read `liftM` getLine\n let hn = ( n + 1 ) `div` 2\n\n putStrLn $ map (\\q -> let hq = q `div` 2 in if q `mod` 2 == 0\n then if hq + k > hn then 'X' else '.'\n else if q == n || hq + k >= n then 'X' else '.'\n ) q\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, k, p] <- ( map read . words ) `liftM` getLine\n\n q <- replicateM n $ read `liftM` getLine\n let hn = ( n + 1 ) `div` 2\n\n putStrLn $ map (\\q -> let hq = q `div` 2 in if q `mod` 2 == 0\n then if hq + k > hn then 'X' else '.'\n else if q == n || hq + k >= n then 'X' else '.'\n ) q\n"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n [n, k, p] <- ( map read . words ) `liftM` getLine :: IO [Integer]\n\n q <- replicateM (fromIntegral p) $ read `liftM` getLine\n let hn = ( n + 1 ) `div` 2\n\n putStrLn $ map (\\q -> let hq = q `div` 2 in if q `mod` 2 == 0\n then if hq + k > hn then 'X' else '.'\n else if q == n || hq + k >= n then 'X' else '.'\n ) q\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nimport Debug.Trace\n\nparseInput = do \n n <- readInteger\n k <- readInteger\n p <- readInt\n query <- replicateM p readInteger\n return (n, k, query)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, k, query) = map solvePosition query\n where\n solvePosition x\n | k == 0 = '.'\n | k == n = 'X'\n | partLeft = if x == left then 'X' else '.'\n | partA = if (x - left) `mod` 2 == 0 then 'X' else '.'\n | otherwise = 'X'\n where\n partLeft = x <= left\n partA = (x - left) <= 2 * a\n\n minB = n `mod` 2\n\n -- 2 * a + b <= n - 2\n -- a + b + 1 == k\n\n a = ((n - 2) - (k - 1)) `min` (k - 1 - minB)\n b = k - 1 - a\n\n left = n - 2 * a - b\n\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "src_uid": "94f52d78b1347fd04c9d39e8789a73ec"} {"source_code": "module Main where\n\nimport Data.List\nimport Control.Exception\n\nscanPairs :: [a] -> [(a, a)]\nscanPairs xs = zip xs $ tail xs\n\nchunks :: Int -> [a] -> [[a]]\nchunks _ [] = []\nchunks n xs = take n xs : chunks n (drop n xs)\n\nsolveCase :: String -> String\nsolveCase = \n show . \n sum . \n map (\\(x, y) -> assert (x <= y) $ y - x - 1) . \n scanPairs . \n map fst . \n filter ((==) \"1\" . snd) . \n zip [0..] . \n words\n\nmain :: IO ()\nmain = interact $ unlines . map solveCase . concatMap tail . chunks 2 . tail . lines\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List (dropWhileEnd)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> map show >>> unlines\n\nprocess :: [String] -> [Int]\nprocess [] = []\nprocess (_ : x : xs) = solve x : process xs\n\nsolve :: [Char] -> Int\nsolve = length . filter (== '0') . dropWhileEnd (/= '1') . dropWhile (/= '1')\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- getInts\n as <- getInts\n putStrLn $ show $ length $ filter (==0) $ dropWhile (==0) $ reverse $ dropWhile (==0) as\n"}, {"source_code": "import Data.List (dropWhileEnd)\n\n\neveryOther :: [a] -> [a]\neveryOther [] = []\neveryOther (x:y:xs) = y : everyOther xs\n\n\ncountMoves :: String -> String\ncountMoves s = show $ foldr countZeros 0 (stripZeros (words s))\n where\n stripZeros = dropWhileEnd (== \"0\") . dropWhile (== \"0\")\n countZeros x acc = if x == \"0\" then acc + 1 else acc\n\n\nmain :: IO ()\nmain = do\n _ <- getLine\n interact $ unlines . map countMoves . everyOther . lines\n"}, {"source_code": "import Control.Monad\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n a <- readInts\n let\n a1 = dropWhile (== 0) a\n a2 = dropWhile (== 0) $ reverse a1\n print $ length [() | x <- a2, x == 0]\n"}, {"source_code": "import Control.Monad\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n \nmain :: IO ()\nmain = do\n t <- readInt\n replicateM_ t $ do \n n <- readInt\n let m = n + 1\n a <- readInts\n let a' = trimZeroes a in putStrLn $ show $ (length a') - (sum a')\n\ntrimZeroes::[Int] -> [Int]\ntrimZeroes = f . f\n where f = reverse . dropWhile (== 0)\n"}], "negative_code": [], "src_uid": "1c07882651ef6ebfc05e777d562e28b9"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.List ((\\\\))\nimport Data.Maybe (fromJust)\nimport Data.Tuple (fst, uncurry)\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map read . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\t(ws, hs) = unzip sizes\n\t\t\ttotalWeight = sum ws\n\t\t\th1 = maximum hs\n\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\t\t\tsolve w h = (totalWeight - w) * (if h == h1 then h2 else h1)\n\n\tputStrLn . unwords $ map show solution\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n a <- replicateM n $ do\n [w, h] <- map readInt . C.words <$> C.getLine\n return (w, h)\n let (h1, h2) = flip foldl1' ((0, 0): a) $ \\k@(i, j) (_, h) -> if\n | h > i -> (h, i)\n | h > j -> (i, h)\n | otherwise -> k\n sw = sum $ map fst a\n ans = [(sw - w) * (if h /= h1 then h1 else h2) | (w, h) <- a]\n putStrLn $ unwords $ map show ans\n where\n readInt = fst . fromJust . C.readInt\n"}, {"source_code": "import Data.List\n\nans :: [(Int,Int)] -> [Int]\nans ls = map (\\(x,y) -> (sumFstLs - x)*(if y == maxi then maxi2 else maxi)) ls where\n\tsumFstLs\t= sum (map fst ls)\n\tsortedSndLs\t= reverse $ sort (map snd ls)\n\tmaxi \t\t= sortedSndLs !! 0\n\tmaxi2\t\t= sortedSndLs !! 1\n\ngetPairs :: \t\t[Int] -> [(Int,Int)]\ngetPairs [] \t\t= []\ngetPairs (x:y:xs) \t= (x,y):(getPairs xs)\n\t\nmain :: IO()\nmain = do\n\tn <- getLine\n\tcontent <- fmap (map read . words) getContents\n\tputStrLn $ intercalate \" \" $ map show $ ans $ getPairs content"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List ((\\\\))\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map read . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\tsolve w h =\n\t\t\t\t\t(s - w) * (if h == h1 then h2 else h1)\n\t\t\t\twhere\n\t\t\t\t\t(ws, hs) = unzip sizes\n\t\t\t\t\ts = sum ws\n\t\t\t\t\th1 = maximum hs\n\t\t\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\tputStrLn . unwords $ map show solution\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, lines, words)\nimport Data.List ((\\\\))\nimport Data.Maybe (fromJust)\nimport Data.Tuple (fst, uncurry)\n\nimport Prelude hiding (getContents, getLine, lines, words)\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\tsolve w h =\n\t\t\t\t\t(s - w) * (if h == h1 then h2 else h1)\n\t\t\t\twhere\n\t\t\t\t\t(ws, hs) = unzip sizes\n\t\t\t\t\ts = sum ws\n\t\t\t\t\th1 = maximum hs\n\t\t\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\tputStrLn . unwords $ map show solution\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, lines, words)\nimport Data.List ((\\\\))\nimport Data.Maybe (fromJust)\nimport Data.Tuple (fst, uncurry)\n\nimport Prelude hiding (getContents, getLine, lines, words)\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\tsolve w h =\n\t\t\t\t\t(s - w) * (if h == h1 then h2 else h1)\n\t\t\t\twhere\n\t\t\t\t\t(ws, hs) = unzip sizes\n\t\t\t\t\ts = sum ws\n\t\t\t\t\th1 = maximum hs\n\t\t\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\tputStrLn . unwords $ map show solution\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative ((<$>))\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, lines, words)\nimport Data.List ((\\\\))\nimport Data.Maybe (fromJust)\nimport Data.Tuple (fst, uncurry)\n\nimport Prelude hiding (getContents, getLine, lines, words)\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\tsolve w h =\n\t\t\t\t\t(s - w) * (if h == h1 then h2 else h1)\n\t\t\t\twhere\n\t\t\t\t\t(ws, hs) = unzip sizes\n\t\t\t\t\ts = sum ws\n\t\t\t\t\th1 = maximum hs\n\t\t\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\tputStrLn . unwords $ map show solution\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.List ((\\\\))\nimport Data.Maybe (fromJust)\nimport Data.Tuple (fst, uncurry)\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map read . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\t(ws, hs) = unzip sizes\n\t\t\t-- totalWeight = sum ws\n\t\t\th1 = maximum hs\n\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\t\t\tsolve w h = (s - w) * (if h == h1 then h2 else h1)\n\t\t\t\twhere\n\t\t\t\t\ts = sum ws\n\n\tputStrLn . unwords $ map show solution\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString (getContents, getLine)\nimport Data.ByteString.Char8 (readInt, lines, words)\nimport Data.List ((\\\\))\nimport Data.Maybe (fromJust)\nimport Data.Tuple (fst, uncurry)\n\nimport Prelude hiding (getContents, getLine, lines, words)\n\nmain = do\n\tgetLine\n\tsizes <- map ((\\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents\n\n\tlet solution =\n\t\t\tmap (uncurry solve) sizes\n\t\twhere\n\t\t\t(ws, hs) = unzip sizes\n\t\t\ttotalWeight = sum ws\n\t\t\th1 = maximum hs\n\t\t\th2 = maximum $ hs \\\\ [h1]\n\n\t\t\tsolve w h = (totalWeight - w) * (if h == h1 then h2 else h1)\n\n\tputStrLn . unwords $ map show solution\n"}, {"source_code": "readInput = do\n contents <- getContents\n let [n] : _sizes = map (map (read :: String -> Int) . words) $ lines contents\n let sizes = map (\\[w, h] -> (w, h)) _sizes\n return (n, sizes)\n\nprintResult result = putStr $ unwords $ map show result\n\n\naddMax (a, b) x\n | x > a = (x, a)\n | x > b = (a, x)\n | otherwise = (a, b)\n\nremMax (a, b) x\n | x == a = b\n | otherwise = a\n\ngetMax2 arr = foldl addMax (minVal, minVal) arr\n where minVal = -1\n\n\nsolve sizes = map f sizes\n where sumv = sum $ map fst sizes\n max2 = getMax2 $ map snd sizes\n f (w, h) = (sumv - w) * (remMax max2 h)\n\nmain = do\n (n, sizes) <- readInput\n printResult $ solve sizes\n"}, {"source_code": "import Control.Monad\nsecondMaximum l = if length lAlt == n - 1 then maximum lAlt else mx\n where\n mx = maximum l\n lAlt = filter (/= mx) l\n n = length l\nsolve l =\n map (\\(w, h)-> (totalWidth - w) * (alternative h firstH secondH)) l\n where\n totalWidth = sum $ map fst l :: Integer\n firstH = maximum $ map snd l \n secondH = secondMaximum $ map snd l\n alternative x y z = if x == y then z else y :: Integer\n\n\nmain = do\n n <- liftM read getLine\n l <- forM [1..n] (\\ i -> liftM (listToPair . map read . words) getLine)\n putStrLn $ unwords $ map show $ solve l\n where\n listToPair [a, b] = (a, b)\n\n"}], "negative_code": [{"source_code": "import Data.List\n\nans :: [(Int,Int)] -> [Int]\nans ls = map (\\(x,y) -> (sumFstLs - x)*(if y == maxi then maxi2 else maxi)) ls where\n\tsumFstLs\t= sum (map fst ls)\n\tsortedSndLs\t= reverse $ sort (map snd ls)\n\tmaxi \t\t= sortedSndLs !! 0\n\tmaxi2\t\t= sortedSndLs !! 1\n\ngetPairs :: \t\t[Int] -> [(Int,Int)]\ngetPairs [] \t\t= []\ngetPairs (x:y:xs) \t= (x,x):(getPairs xs)\n\t\nmain :: IO()\nmain = do\n\tn <- getLine\n\tcontent <- fmap (map read . words) getContents\n\tputStrLn $ intercalate \" \" $ map show $ ans $ getPairs content"}], "src_uid": "e1abc81cea4395ba675cf6ca93261ae8"} {"source_code": "import Data.List ( sort )\n\nsolve :: [Integer] -> String\nsolve [x, y, z]\n | y == z = \"YES\\n\" ++ unwords (map show [x, x, z])\n | otherwise = \"NO\"\n\nmain :: IO ()\nmain = interact $ unlines . map (solve . sort . map read . words) . tail . lines\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n contents <- getContents\n let notnull = filter (not . null) $ lines contents\n mapM solve $ drop 1 $ map (sort . map (read :: String -> Int) . words) notnull\n\n\nsolve (a:b:c:[])\n | b == c = putStrLn (\"YES \" ++ show b ++ \" \" ++ show a ++ \" 1\")\n | otherwise = putStrLn \"NO\""}, {"source_code": "module Main where\nimport Data.List\nmain :: IO ()\nmain = interact $ unlines . map solve . tail . lines\n\nsolve :: String -> String\nsolve str=\n let\n (x:y:z:[]) = sort $ map read $ words str :: [Integer]\n b = x\n c = y\n a = if (c > b) then b - 1 else c - 1\n in\n if (z /= max b c)\n then \"NO\\n\"\n else if (a == 0)\n then \"YES\\n\" ++ show (a+1) ++ \" \" ++ show b ++ \" \" ++ show c\n else \"YES\\n\" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c\n\n\n\n-- solve :: String -> String\n-- solve str=\n-- let\n-- (x:y:z:[]) = map read $ words str :: [Integer]\n-- l = [1 .. 1000]\n-- ll = [(a, b, c) | a <- l, b <- l, c <-l, x == max a b, y == max a c, z == max b c]\n-- (a, b, c) = if null ll then (0, 0, 0) else head ll\n-- in\n-- if (a == 0 || b == 0 || c == 0)\n-- then \"NO\\n\"\n-- else \"YES\\n\" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c\n\n-- max1 :: Integer -> Integer -> Maybe Integer\n-- max1 a b = if a == b then Nothing else Just $ max a b\n"}, {"source_code": "\nmain = interact $ unlines . concat . map (solve . map show . sort . map read) . map words . tail . lines\n\nsolve :: [String] -> [String]\nsolve (x:y:z:_)\n | x == y && y == z = [\"YES\", unwords [x, x, x]]\n | x == y = [\"YES\", unwords [x, z, z]]\n | otherwise = [\"NO\"]\n\nsort :: [Integer] -> [Integer]\nsort (x:y:z:[])\n | x >= y && y >= z = [x, y, z]\n | x >= z && z >= y = [x, z, y]\n | y >= x && x >= z = [y, x, z]\n | y >= z && z >= x = [y, z, x]\n | z >= y && y >= x = [z, y, x]\n | z >= x && x >= y = [z, x, y]\n"}, {"source_code": "import Data.List ( sort )\nimport Control.Monad ( replicateM_ )\n\nsolve :: [Integer] -> String\nsolve [x, y, z]\n | y == z = \"YES\\n\" ++ unwords (map show [x, x, z])\n | otherwise = \"NO\"\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ solve . sort . map read . words <$> getLine >>= putStrLn\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Control.Monad (replicateM_)\n\ngo :: IO ()\ngo = do\n [x, y, z] <- reverse . sort . map read . words <$> getLine :: IO [Integer]\n if x == y && y == z\n then putStrLn \"YES\" >> putStrLn (unwords $ show <$> [x, y, z])\n else if x == y && y > z\n then putStrLn \"YES\" >> putStrLn (unwords $ show <$> [x, z, z])\n else putStrLn \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n replicateM_ n go\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> [Int]\nsolve xs @ [x, y, z]\n | yes && x == y && y == z = [m, m, m]\n | yes = [m, z, z]\n | otherwise = []\n\n where\n yes = length (xs \\\\ [m, m]) == 1\n m = maximum xs\n z = minimum xs\n\nprint' :: [Int] -> IO ()\nprint' xs\n | null xs = putStrLn \"NO\"\n | otherwise = putStrLn \"YES\" >> putStrLn (unwords . map show $ xs)\n\ntest :: Int -> IO ()\ntest n = do\n tests <- replicateM n (map read . words <$> getLine)\n mapM_ (print' . solve) tests\n\nmain :: IO ()\nmain = do\n n <- getLine\n let n' = (read n :: Int)\n test n'\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess x y z | x==y && y==z = [x,x,x]\n\t | x==y = []\n | y==z = [x,x,y]\n\t | otherwise = []\n\nonecase = do\n\t\t[x,y,n]<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tlet k = process x y n\n\t\tputStrLn $ if k==[] then \"NO\" else \"YES\"\n\t\tif k/=[] then putStrLn ( intercalate \" \" ( map show k)) else putStr \"\"\n\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n contents <- getContents\n mapM solve (drop 1 (map (sort . words) (lines contents)))\n\nsolve (a:b:c:[])\n | b == c = putStrLn (\"YES \" ++ b ++ \" \" ++ a ++ \" 1\")\n | otherwise = putStrLn \"NO\""}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ unlines . map solve . tail . lines\n\nsolve :: String -> String\nsolve str=\n let\n (x:y:z:[]) = map read $ words str :: [Integer]\n b = x\n c = y\n a = if (c > b) then b - 1 else c - 1\n in\n if (z /= max b c)\n then \"NO\\n\"\n else \"YES\\n\" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c\n\n\n\n-- solve :: String -> String\n-- solve str=\n-- let\n-- (x:y:z:[]) = map read $ words str :: [Integer]\n-- l = [1 .. 1000]\n-- ll = [(a, b, c) | a <- l, b <- l, c <-l, x == max a b, y == max a c, z == max b c]\n-- (a, b, c) = if null ll then (0, 0, 0) else head ll\n-- in\n-- if (a == 0 || b == 0 || c == 0)\n-- then \"NO\\n\"\n-- else \"YES\\n\" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c\n\n-- max1 :: Integer -> Integer -> Maybe Integer\n-- max1 a b = if a == b then Nothing else Just $ max a b\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ unlines . map solve . tail . lines\n\nsolve :: String -> String\nsolve str=\n let\n (x:y:z:[]) = map read $ words str :: [Integer]\n b = x\n c = y\n a = if (c > b) then b - 1 else c - 1\n in\n if (z /= max b c)\n then \"NO\\n\"\n else if (a == 0)\n then \"YES\\n\" ++ show (a+1) ++ \" \" ++ show b ++ \" \" ++ show c\n else \"YES\\n\" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c\n\n\n\n-- solve :: String -> String\n-- solve str=\n-- let\n-- (x:y:z:[]) = map read $ words str :: [Integer]\n-- l = [1 .. 1000]\n-- ll = [(a, b, c) | a <- l, b <- l, c <-l, x == max a b, y == max a c, z == max b c]\n-- (a, b, c) = if null ll then (0, 0, 0) else head ll\n-- in\n-- if (a == 0 || b == 0 || c == 0)\n-- then \"NO\\n\"\n-- else \"YES\\n\" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c\n\n-- max1 :: Integer -> Integer -> Maybe Integer\n-- max1 a b = if a == b then Nothing else Just $ max a b\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> [Int]\nsolve xs @ [x, y, z]\n | yes && x == y && y == z = [m, m, m]\n | yes = xs\n | otherwise = []\n\n where\n yes = length (xs \\\\ [m, m]) == 1\n m = maximum xs\n\nprint' :: [Int] -> IO ()\nprint' xs\n | null xs = putStrLn \"NO\"\n | otherwise = putStrLn \"YES\" >> putStrLn (unwords . map show $ xs)\n\ntest :: Int -> IO ()\ntest n = do\n tests <- replicateM n (map read . words <$> getLine)\n mapM_ (print' . solve) tests\n\nmain :: IO ()\nmain = do\n n <- getLine\n let n' = (read n :: Int)\n test n'\n"}], "src_uid": "f4804780d9c63167746132c35b2bdd02"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Ix\nimport qualified Data.IntMap as IM\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n let (res, len, cut) = solve n $ map fromIntegral xs\n putStrLn $ shows res \" \" ++ show len\n putStrLn.unwords $ map show cut\n\nsolve :: Int -> [Int64] -> (Int64, Int, [Int])\nsolve n xs = (calc (l, r), k , cut)\n where\n (l, r) = snd $ maximum [(calc lr, lr) | lr <- findLRs 0 IM.empty $ map fromIntegral xs]\n cut = [1..l] ++ [i+1|i<-[l+1..r-1], unsafeAt arr i<0] ++ [r+2..n]\n k = length cut\n\n arr = listArray (0,n-1) xs :: UArray Int Int64\n sumArray = listArray (0,n-1) $ scanl1 (+) $ map (max 0) xs :: UArray Int Int64\n\n findLRs !i !im (x:xs) = case IM.lookup x im of\n Nothing -> findLRs (i+1) (IM.insert x [i] im) xs\n Just (l:_) -> findLRs (i+1) (IM.insert x [l,i] im) xs\n findLRs !_ !im _ = [(l, r) | [l,r] <- IM.elems im]\n\n calc (l, r)\n | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r\n | otherwise = unsafeAt arr l + unsafeAt arr r + unsafeAt sumArray (r-1) - unsafeAt sumArray l\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport Data.Int\nimport Data.Ix\nimport qualified Data.IntMap as IM\nimport Data.List\nimport Data.Ord\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nnewtype BIT = BIT (UArray Int Int64)\n\nquery :: Int -> BIT -> Int64\nquery key (BIT bit) = go key 0\n where\n go !i !res\n | i >= 0 = go ((i .&. (i+1)) - 1) $ res + unsafeAt bit i\n | otherwise = res\n\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n let (res, cut) = solve n xs\n putStrLn $ shows res \" \" ++ show (length cut)\n putStrLn.unwords $ map show cut\n\ndata LR = L {-# UNPACK #-} !Int\n | LR {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n\nsolve :: Int -> [Int64] -> (Int64, [Int])\nsolve n xs = (calc (l,r), [1..l]++[i+1|i<-[l+1..r-1],unsafeAt arr i<0]++[r+2..n])\n where\n arr = listArray (0,n-1) xs :: UArray Int Int64\n\n bit = runST $ do\n bit <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n let add key x = do\n let go !i = when (i < n) $ do\n unsafeModify bit i (x+)\n go $ i .|. (i + 1)\n when (x>0) $ go key\n let go !i (x:xs)=add i x>>go(i+1)xs\n go _ _ = return ()\n go 0 xs\n BIT <$> unsafeFreeze bit\n\n findLRs !i im (x:xs) = case IM.lookup x im of\n Nothing -> findLRs (i+1) (IM.insert x (L i) im) xs\n Just (L l) -> findLRs (i+1) (IM.insert x (LR l i) im) xs\n Just (LR l _) -> findLRs (i+1) (IM.insert x (LR l i) im) xs\n findLRs _ im _ = [(l, r) | LR l r <- IM.elems im]\n\n calc (l, r)\n | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r\n | otherwise = unsafeAt arr l + unsafeAt arr r + query (r-1) bit - query l bit\n\n (l, r) = maximumBy (comparing calc) $ findLRs 0 IM.empty $ map fromIntegral xs"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Ix\nimport qualified Data.IntMap as IM\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n let (res, len, cut) = solve n $ map fromIntegral xs\n putStrLn $ shows res \" \" ++ show len\n putStrLn.unwords $ map show cut\n\nsolve :: Int -> [Int64] -> (Int64, Int, [Int])\nsolve n xs = (calc (l, r), k , concat cutss)\n where\n (l, r) = snd $ maximum [(calc lr, lr) | lr <- findLRs 0 IM.empty $ map fromIntegral xs]\n cutss = [[1..l], [i+1|i<-[l+1..r-1],unsafeAt arr i<0], [r+2..n]]\n k = sum $ map length cutss\n\n arr = listArray (0,n-1) xs :: UArray Int Int64\n sumArray = listArray (0,n-1) $ scanl1 (+) $ map (max 0) xs :: UArray Int Int64\n\n findLRs !i !im (x:xs) = case IM.lookup x im of\n Nothing -> findLRs (i+1) (IM.insert x [i] im) xs\n Just (l:_) -> findLRs (i+1) (IM.insert x [l,i] im) xs\n findLRs !_ !im _ = [(l, r) | [l,r] <- IM.elems im]\n\n calc (l, r)\n | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r\n | otherwise = unsafeAt arr l + unsafeAt arr r + unsafeAt sumArray (r-1) - unsafeAt sumArray l\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Ix\nimport qualified Data.IntMap as IM\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n let (res, len, cut) = solve n $ map fromIntegral xs\n putStrLn $ shows res \" \" ++ show len\n putStrLn.unwords $ map show cut\n\nsolve :: Int -> [Int64] -> (Int64, Int, [Int])\nsolve n xs = (calc (l, r), k , cut)\n where\n (l, r) = snd $ maximum [(calc lr, lr) | lr <- findLRs 0 IM.empty $ map fromIntegral xs]\n cut = [1..l]++[i+1|i<-[l+1..r-1],unsafeAt arr i<0]++[r+2..n]\n k = length cut\n\n arr = listArray (0,n-1) xs :: UArray Int Int64\n sumArray = listArray (0,n-1) $ scanl1 (+) $ map (max 0) xs :: UArray Int Int64\n\n findLRs !i !im (x:xs) = case IM.lookup x im of\n Nothing -> findLRs (i+1) (IM.insert x [i] im) xs\n Just (l:_) -> findLRs (i+1) (IM.insert x [l,i] im) xs\n findLRs !_ !im _ = [(l, r) | [l,r] <- IM.elems im]\n\n calc (l, r)\n | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r\n | otherwise = unsafeAt arr l + unsafeAt arr r + unsafeAt sumArray (r-1) - unsafeAt sumArray l\n"}], "negative_code": [], "src_uid": "b3418f53720fb9eb990d6e99b07fd61b"} {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as LB\nimport qualified Data.ByteString as SB\nimport Data.ByteString.Internal (inlinePerformIO)\nimport Foreign.C.String (CString)\nimport Foreign.C (CDouble)\nimport Data.Maybe\nimport Data.List (maximumBy, minimum, foldl')\nimport Data.Array\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport Debug.Trace\n\nforeign import ccall unsafe \"stdlib.h atof\" c_atof :: CString -> IO Double\nunsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof\n{-# INLINE unsafeReadDouble #-}\nreadDouble = unsafeReadDouble . SB.concat . LB.toChunks\nreadInt = fst . fromJust . LB.readInt\n\ndebug :: Show a => a -> b -> b\ndebug = trace . show\n--debug _ = id\n\nmain = readFile \"input.txt\" >>= (writeFile \"output.txt\" . output . solve . parse . lines)\n\noutput (x,y) = show x ++ \" \" ++ show y\n\nparse :: [String] -> (Int, Int, [(Int, Int)])\nparse [nm, sk, pts] =\n let [n, m] = map read . words $ nm\n k = read sk :: Int\n lst = map read . words $ pts\n trees = [ (lst !! i, lst !! (i+1)) | i <- [0, 2 .. length lst - 1]]\n in (n, m, trees)\n\nsolve (n, m, start) =\n let allTrees = [(x, y, d x y) | x <- [1..n], y <- [1..m] ]\n (x, y, _) = maximumBy (\\ (_, _, d) (_, _, e) -> compare d e) allTrees\n d x y = minimum [abs(i-x) + abs(j-y) | (i, j) <- start ]\n in (x,y)\n", "positive_code": [{"source_code": "import Ix\n\ncalc :: (Int, Int) -> (Int, Int) -> Int\ncalc x y = (abs fstdiff) + (abs snddiff)\n where fstdiff = (fst x) - (fst y)\n snddiff = (snd x) - (snd y)\n\nburnMinute :: [(Int, Int)] -> (Int, Int) -> Int\nburnMinute points target = minimum $ map ( `calc` target) points\n\ncalcMaxMinute :: [(Int, Int)] -> [(Int, Int)] -> Int\ncalcMaxMinute points area = maximum $ map (burnMinute points) area\n\ncalcAns :: [(Int, Int)] -> [(Int, Int)] -> Int-> (Int, Int) -> (Int, Int)\ncalcAns points (x : xs) s t | burnMinute points x >= s = calcAns points xs (burnMinute points x) x\n | otherwise = calcAns points xs s t\n\ncalcAns _ [] _ t = t\n\nmakepoints :: String -> [(Int, Int)]\nmakepoints str = f $ words str\n where f [] = []\n f (x : y : xs) = ((read x) :: Int, (read y) :: Int) : f xs\n\nprintAns :: (Int, Int) -> String\nprintAns (a, b) = show a ++ \" \" ++ show b\n\nmain :: IO ()\nmain = do\n str <- readFile \"input.txt\"\n let x = (read $ head $ words $ head $ lines str) :: Int\n let y = (read $ head $ tail $ words $ head $ lines str) :: Int\n let points = makepoints $ head $ tail $ tail $ lines str\n let ans = calcAns points ((range ((1, 1), (x, y))) :: [(Int, Int)]) 0 (1, 1)\n writeFile \"output.txt\" $ printAns ans\n\n"}], "negative_code": [], "src_uid": "1a740b0ad2ec3ed208f01fc7b64e00d4"} {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve (n:xs)\n | head as == head bs = n - a - b + max a b - 1\n | otherwise = n - 1\n where\n as = head $ group xs\n bs = head $ reverse $ group xs\n a = length as\n b = length bs\n\n\ntests :: [[Int]]\ntests = [ [5, 1, 2, 3, 2, 3]\n , [3, 1, 2, 1]\n , [7, 1, 1, 3, 1, 1, 1, 1]\n ]\n\nmain = interact $ show . solve . map read . words\n", "positive_code": [{"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve xs \n | f /= l = n - 1\n | otherwise = n - 1 - (min a b)\n where n = length xs\n f = head xs\n l = last xs\n a = length $ head $ group xs\n b = length $ last $ group xs\n \nmain :: IO ()\nmain = do\n _ <- readInt\n v <- readInts\n print $ solve v"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve xs\n | a /= b = (length xs) - 1\n | otherwise = (max (length (dropWhile (==b) xs)) (length (dropWhile (==a) ys))) - 1\n where a = head xs\n b = last xs\n ys = reverse xs\n\nmain :: IO ()\nmain = do\n _ <- readInt\n v <- readInts\n print $ solve v"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nf (x:xs) = length $ dropWhile (== x) $ reverse xs\n\nsolve :: [Int] -> Builder\nsolve (n:a) = intDec res <> char7 '\\n'\n where\n b = take n a\n !res = max (f b) (f $ reverse b)\n\nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n"}], "negative_code": [{"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve xs\n | head as /= head bs = n - 1\n | otherwise = n - min (length as) (length bs)\n where\n as = head $ group xs\n bs = head $ reverse $ group xs\n n = length xs\n\n\ntests :: [[Int]]\ntests = [ [1, 2, 3, 2, 3]\n , [1, 2, 1]\n , [1, 1, 3, 1, 1, 1]\n ]\n\nmain = interact $ show . solve . map read . tail . words\n"}], "src_uid": "101fec8d8e169f941e71281048468121"} {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Data.Ord\nimport Data.STRef\nimport Numeric\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\ndata Node = Node {\n parent :: Int,\n inMST :: Bool,\n nodeNum :: Int,\n cost :: Integer\n} deriving (Show)\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = [\n showInt totalCost \"\",\n showInt (length buildPlants) \"\",\n unwords $ map ((\\i -> showInt i \"\") . nodeNum) buildPlants,\n showInt (length buildWires) \"\"\n ] ++ map (\\(Node p _ v _) -> showInt p (\" \" ++ showInt v \"\")) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)\n nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf\n totalCost = sum $ map cost nodes\n (buildPlants, buildWires) = partition ((== 0) . parent) nodes\n\nmst t initial costf = runST $ do\n nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)\n replicateM_ t $ do\n elems <- getElems nodes\n let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems\n writeArray nodes v node {inMST = True}\n forM_ [1..t] $ \\vn -> do\n let w = costf v vn\n node@(Node p inMst vn w2) <- readArray nodes vn\n when (not inMst && w < w2) $\n writeArray nodes vn node {parent = v, cost = w}\n getElems nodes\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)\n", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Data.Ord\nimport Data.STRef\nimport Numeric\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\ndata Node = Node {\n parent :: Int,\n inMST :: Bool,\n nodeNum :: Int,\n cost :: Integer\n} deriving (Show)\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = map (unwords) $ [\n [show totalCost],\n [show $ length buildPlants],\n map (show . nodeNum) buildPlants,\n [show $ length buildWires]\n ] ++ map (\\(Node p _ v _) -> [show p, show v]) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)\n nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf\n totalCost = sum $ map cost nodes\n (buildPlants, buildWires) = partition ((== 0) . parent) nodes\n\nmst t initial costf = runST $ do\n nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)\n replicateM_ t $ do\n elems <- getElems nodes\n let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems\n writeArray nodes v node {inMST = True}\n forM_ [1..t] $ \\vn -> do\n let w = costf v vn\n node@(Node p inMst vn w2) <- readArray nodes vn\n when (not inMst && w < w2) $\n writeArray nodes vn node {parent = v, cost = w}\n getElems nodes\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Data.Ord\nimport Data.STRef\nimport Numeric\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\ndata Node = Node {\n parent :: Int,\n inMST :: Bool,\n nodeNum :: Int,\n cost :: Integer\n} deriving (Show)\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = map (unwords) $ [\n [show totalCost],\n [show $ length buildPlants],\n map (show . nodeNum) buildPlants,\n [show $ length buildWires]\n ] ++ map (\\(Node p _ v _) -> [show p, show v]) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)\n nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf\n totalCost = sum $ map cost nodes\n (buildPlants, buildWires) = partition ((== 0) . parent) nodes\n\nmst t initial costf = runST $ do\n nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)\n forM_ [1..t] $ \\_ -> do\n elems <- getElems nodes\n let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems\n writeArray nodes v node {inMST = True}\n forM_ [1..t] $ \\vn -> do\n let w = costf v vn\n node@(Node p inMst vn w2) <- readArray nodes vn\n when (not inMst && w < w2) $\n writeArray nodes vn node {parent = v, cost = w}\n getElems nodes\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Numeric\nimport Data.Tuple\nimport Data.STRef\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\ncount x = length . filter (== x)\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = map (unwords) $ [\n [show totalCost],\n [show $ length buildPlants],\n map show buildPlants,\n [show $ length buildWires]\n ] ++ map (map show) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n (totalCost, buildPlants, buildWires) = runST $ do\n plantsRef <- newSTRef []\n wiresRef <- newSTRef []\n totalCost <- newSTRef 0\n nodes <- newListArray (1, t) (map (\\i -> (i, 0, False)) $ ints cs) :: ST s (STArray s Int (Integer, Int, Bool))\n forM_ [1..t] $ \\_ -> do\n ascs <- getAssocs nodes\n let ((w,u,_), v) = minimum $ map swap $ filter (\\(_,(_,_,c)) -> not c) ascs\n if u == 0\n then modifySTRef plantsRef (\\ps -> v:ps)\n else modifySTRef wiresRef (\\ws -> [u,v]:ws)\n modifySTRef totalCost (+ w)\n writeArray nodes v (w,u,True)\n forM_ [1..t] $ \\vn -> do\n let cost = (wires ! v + wires ! vn) * dist (coords ! v) (coords ! vn)\n (cost2,_,inMst) <- readArray nodes vn\n if not inMst && cost < cost2\n then writeArray nodes vn (cost,v,inMst)\n else return ()\n (,,) <$> readSTRef totalCost <*> readSTRef plantsRef <*> readSTRef wiresRef\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Data.Ord\nimport Data.STRef\nimport Numeric\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\ndata Node = Node {\n parent :: Int,\n inMST :: Bool,\n nodeNum :: Int,\n cost :: Integer\n} deriving (Show)\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = map (unwords) $ [\n [show totalCost],\n [show $ length buildPlants],\n map (show . nodeNum) buildPlants,\n [show $ length buildWires]\n ] ++ map (\\(Node p _ v _) -> [show p, show v]) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)\n nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf\n totalCost = sum $ map cost nodes\n (buildPlants, buildWires) = partition ((== 0) . parent) nodes\n\nmst t initial costf = runST $ do\n nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)\n forM_ [1..t] $ \\_ -> do\n elems <- getElems nodes\n let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems\n writeArray nodes v node {inMST = True}\n let updateKey node@(Node p inMst vn w2) = if (not inMst && costf v vn < w2)\n then Just node { parent = v, cost = costf v vn }\n else Nothing\n mapArrayInPlace updateKey nodes\n getElems nodes\n\nmapArrayInPlace :: (MArray a e m, Ix i) => (e -> Maybe e) -> a i e -> m ()\nmapArrayInPlace f array = do\n assocs <- getAssocs array\n forM_ assocs $ \\(i, e) ->\n case f e of\n Just x -> writeArray array i x\n Nothing -> return ()\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Numeric\nimport Data.Tuple\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\ncount x = length . filter (== x)\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = map (unwords) $ [\n [show totalCost],\n [show $ length buildPlants],\n map show buildPlants,\n [show $ length buildWires]\n ] ++ map (map show) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n edges = runST $ do\n nodes <- newListArray (1, t) (map (\\i -> (i, 0, False)) $ ints cs) :: ST s (STArray s Int (Integer, Int, Bool))\n forM_ [1..t] $ \\_ -> do\n a <- getAssocs nodes\n let ((w,u,_), v) = minimum $ map swap $ filter (\\(_,(_,_,c)) -> not c) a\n writeArray nodes v (w,u,True)\n forM_ [1..t] $ \\vn -> do\n let cost = (wires ! v + wires ! vn) * dist (coords ! v) (coords ! vn)\n (cost2,_,inMst) <- readArray nodes vn\n if not inMst && cost < cost2\n then writeArray nodes vn (cost,v,inMst)\n else return ()\n getElems nodes\n totalCost = sum $ map (\\(a,_,_) -> a) edges\n (buildPlants, buildWires) = detail $ zip [1..t] edges\n\ndetail :: [(Int, (Integer, Int, Bool))] -> ([Int], [[Int]])\ndetail [] = ([],[])\ndetail ((u, (w, v, _)):xs)\n | v == 0 = (u:ps', ws')\n | otherwise = (ps', [u,v]:ws')\n where\n (ps', ws') = detail xs\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Data.Ord\nimport Data.STRef\nimport Numeric\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\ndata Node = Node {\n parent :: Int,\n inMST :: Bool,\n nodeNum :: Int,\n cost :: Integer\n} deriving (Show)\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = [\n showInt totalCost \"\",\n showInt (length buildWires) \"\",\n unwords $ map ((\\i -> showInt i \"\") . nodeNum) buildPlants,\n showInt (length buildWires) \"\"\n ] ++ map (\\(Node p _ v _) -> showInt p (\" \" ++ showInt v \"\")) buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)\n nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf\n totalCost = sum $ map cost nodes\n (buildPlants, buildWires) = partition ((== 0) . parent) nodes\n\nmst t initial costf = runST $ do\n nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)\n replicateM_ t $ do\n elems <- getElems nodes\n let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems\n writeArray nodes v node {inMST = True}\n forM_ [1..t] $ \\vn -> do\n let w = costf v vn\n node@(Node p inMst vn w2) <- readArray nodes vn\n when (not inMst && w < w2) $\n writeArray nodes vn node {parent = v, cost = w}\n getElems nodes\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)\n"}, {"source_code": "import Control.Monad\nimport Control.Monad.ST\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.List\nimport Numeric\nimport Data.Tuple\n\n(|>) = flip (.)\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\ncount x = length . filter (== x)\n\nmain = interact $\n lines\n |> solverLoop\n |> unlines\n\n\nsolverLoop :: [String] -> [String]\nsolverLoop (ts:xs) = map (unwords . map show) $ [\n [totalCost],\n [length buildPlants],\n buildPlants,\n [length buildWires]\n ] ++ buildWires\n where\n t = int ts\n coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]\n (cs:ks:_) = drop t xs\n wires = array (1, t) $ zip [1..t] (ints ks)\n edges = runST $ do\n nodes <- newListArray (1, t) (map (\\i -> (i, 0, False)) $ ints cs) :: ST s (STArray s Int (Int, Int, Bool))\n forM_ [1..t] $ \\_ -> do\n a <- getAssocs nodes\n let ((w,u,_), v) = minimum $ map swap $ filter (\\(_,(_,_,c)) -> not c) a\n writeArray nodes v (w,u,True)\n forM_ [1..t] $ \\vn -> do\n let cost = (wires ! v + wires ! vn) * dist (coords ! v) (coords ! vn)\n (cost2,_,inMst) <- readArray nodes vn\n if not inMst && cost < cost2\n then writeArray nodes vn (cost,v,inMst)\n else return ()\n getElems nodes\n totalCost = sum $ map (\\(a,_,_) -> a) edges\n (buildPlants, buildWires) = detail $ zip [1..t] edges\n\ndetail [] = ([],[])\ndetail ((u, (w, v, _)):xs)\n | v == 0 = (u:ps', ws')\n | otherwise = (ps', [u,v]:ws')\n where\n (ps', ws') = detail xs\n\ndist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)"}], "src_uid": "4750f5a5aaa1ef727ebf2376641bd8ed"} {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n", "positive_code": [{"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n [n] <- getA\n [k, e] <- getA\n [x, y] <- getA\n p <- replicateM n getA\n putStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n gao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n m = (l + r) / 2\n p = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n q = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}, {"source_code": "import Control.Monad\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 3000 where\n\tgao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n\n"}], "negative_code": [{"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 2000 where\n\tgao' l r = if r-l<0.1^8 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n"}, {"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\nhypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2\n\nmain = do\n\t[n] <- getA\n\t[k, e] <- getA\n\t[x, y] <- getA\n\tp <- replicateM n getA\n\tputStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\\[i, j] -> hypot (i - x) (j - y)) p\n\ngao n k e d = gao' 0 2000 where\n\tgao' l r = if abs(l-r)<0.0000001 then m else if q > e then gao' l m else gao' m r where\n\t\tm = (l + r) / 2\n\t\tp = map (\\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d\n\t\tq = sum $ drop k $ go p\n\ngo [] = [1]\ngo (p:ps) = let q = go ps in zipWith (\\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])\n\n"}], "src_uid": "9578bde96aa39416a3406ffb7ca036e1"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n-- {-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\n-- import Data.UArray\n-- import Data.Array.IArray\n-- import Data.Array.ST\n-- import Data.Array.MArray\n-- import Data.Array.Unsafe\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntSet (IntSet)\n-- import qualified Data.IntSet as S\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as M\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n-- import Debug.Trace\n\nmain = do\n _ <- readInt1 <$> BS.getLine\n as <- readIntN <$> BS.getLine\n _ <- readInt1 <$> BS.getLine\n bs <- readIntN <$> BS.getLine\n cs <- readIntN <$> BS.getLine\n print $ solve as $ zip bs cs\n\nsolve as bcs = fst . maximumBy (compare `on` snd) . zip [1..] $ map score bcs where\n score :: (Int,Int) -> Int64\n score (b,c) = (fromIntegral $ cnt b) * 200000 + (fromIntegral $ cnt c)\n cnt x = M.findWithDefault 0 x m\n m = loop as M.empty where\n loop [] m' = m'\n loop (a:as) m' = loop as (M.insertWith (+) a 1 m')\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\nreadInt641 :: BS.ByteString -> Int64\nreadInt641 = fromIntegral . fst . fromJust . BS.readInteger\n\nreadInt642 :: BS.ByteString -> (Int64,Int64)\nreadInt642 = toTuple . readInt64N\n\nreadInt643 :: BS.ByteString -> (Int64,Int64,Int64)\nreadInt643 = toTriple . readInt64N\n\nreadInt64N :: BS.ByteString -> [Int64]\nreadInt64N = map readInt641 . BS.words\n\nreadInteger1 :: BS.ByteString -> Integer\nreadInteger1 = fst . fromJust . BS.readInteger \n\nreadInteger2 :: BS.ByteString -> (Integer,Integer)\nreadInteger2 = toTuple . readIntegerN\n\nreadInteger3 :: BS.ByteString -> (Integer,Integer,Integer)\nreadInteger3 = toTriple . readIntegerN\n\nreadIntegerN :: BS.ByteString -> [Integer]\nreadIntegerN = map readInteger1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)", "positive_code": [{"source_code": "import Data.Maybe\nimport Control.Applicative\nimport qualified Data.List as L\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as Map\nimport qualified Data.ByteString.Char8 as BS\n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\n\nbuild_map :: [Int] -> (IntMap Int) -> (IntMap Int)\nbuild_map [] mp = mp\nbuild_map (x:xs) mp = build_map xs $ Map.insertWith (+) x 1 mp\n\n\nf :: (IntMap Int) -> (Int, Int) -> (Int, Int)\nf mp (a,b) = (Map.findWithDefault 0 a mp, Map.findWithDefault 0 b mp)\n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n -- la <- getLine\n -- let a = map read (words la) :: [Int]\n a <- readIntN <$> BS.getLine\n m <- readLn :: IO Int\n -- lb <- getLine\n -- lc <- getLine\n -- let b = map read (words lb) :: [Int]\n -- let c = map read (words lc) :: [Int]\n b <- readIntN <$> BS.getLine\n c <- readIntN <$> BS.getLine\n let bc = zip b c\n let ma = build_map a Map.empty\n print . snd $ L.maximumBy compare $ zip (map (f ma) bc) [1..]\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Applicative\nimport Control.Monad\n\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\nimport Data.Text.Read (decimal)\nimport System.IO (stdin)\n\ntread s = case decimal s of\n Right (v,_) -> v\n Left e -> error e\n\ncount xs = foldr (\\a m -> M.insertWith (\\new old -> old + 1) a 1 m) M.empty xs\n\nm ! v = case M.lookup v m of\n Just v -> v\n Nothing -> 0\n\naux [] [] i ans res freq = ans\naux (x:xs) (y:ys) i ans res@(a,b) freq \n | res < (freq ! x, freq ! y) = aux xs ys (i+1) i (freq ! x, freq ! y) freq\n | otherwise = aux xs ys (i+1) ans res freq\n \n\nmain = do\n n <- readLn :: IO Int\n as <- map tread . T.words <$> (TIO.hGetLine stdin) :: IO [Int]\n m <- readLn :: IO Int\n bs <- map tread . T.words <$> (TIO.hGetLine stdin) :: IO [Int]\n cs <- map tread . T.words <$> (TIO.hGetLine stdin) :: IO [Int]\n let freq = count as\n let ans = aux bs cs 0 0 (0,0) freq\n print $ ans + 1\n"}, {"source_code": "import Data.List\nimport Control.Arrow\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\nimport Data.Text.Read (decimal)\nimport System.IO (stdin)\nimport qualified Data.Map as Map\n\ntread s = case decimal s of\n Right (v, _) -> v\n Left e -> error e\n\nmain :: IO()\nmain = do\n _ <- getLine\n a <- map tread . T.words <$> TIO.hGetLine stdin :: IO [Int]\n _ <- getLine\n b <- map tread . T.words <$> TIO.hGetLine stdin :: IO [Int]\n c <- map tread . T.words <$> TIO.hGetLine stdin :: IO [Int]\n let f = Map.fromList $ frequency a\n print $ solve b c 1 0 0 1 f\n\nfrequency :: Ord a => [a] -> [(a, Int)]\nfrequency = map (head &&& length) . group . sort\n\nremoveMaybe :: Maybe Int -> Int\nremoveMaybe (Just a) = a\nremoveMaybe Nothing = 0\n\nsolve :: [Int] -> [Int] -> Int -> Int -> Int -> Int -> Map.Map Int Int -> Int\nsolve [] [] _ _ _ maxIdx _ = maxIdx\nsolve (b:bs) (c:cs) idx maxVal1 maxVal2 maxIdx fre =\n let newVal1 = removeMaybe $ Map.lookup b fre\n newVal2 = removeMaybe $ Map.lookup c fre\n in if newVal1 > maxVal1 || (newVal1 == maxVal1 && newVal2 > maxVal2)\n then solve bs cs (idx + 1) newVal1 newVal2 idx fre\n else solve bs cs (idx + 1) maxVal1 maxVal2 maxIdx fre\n"}, {"source_code": "import Data.Map.Strict (empty, insertWith, findWithDefault)\nimport Data.Ord (comparing)\nimport Data.List (maximumBy)\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\n\nreadInt :: IO Int\nreadInt = read <$> getLine\n\nreadInts :: IO [Int]\nreadInts = fmap (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n n <- readInt\n lang <- readInts\n m <- readInt\n sounds <- readInts\n subs <- readInts\n let langmap = foldl (\\mp k -> insertWith (+) k 1 mp) empty lang\n happy = getHappy <$> zip sounds subs\n getHappy (snd, sbt) = (findWithDefault 0 snd langmap, findWithDefault 0 sbt langmap)\n (_, ans) = maximumBy (comparing fst) $ zip happy [1..]\n print ans\n\n\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\n\nimport qualified Data.Map as M\nimport Data.Ord (comparing)\nimport Data.List (maximumBy)\n\nmaxAux [] [] i freq aMax subV subI = subI\nmaxAux (x:xs) (y:ys) i freq aMax subV subI\n | freq !!! x == aMax = if freq !!! y > subV \n then maxAux xs ys (i+1) freq aMax (freq !!! y) i\n else maxAux xs ys (y+1) freq aMax subV subI\n | otherwise = maxAux xs ys (i+1) freq aMax subV subI\n\n\n(!!!) :: M.Map Int Int -> Int -> Int\nm !!! v = case M.lookup v m of\n Just v -> v\n Nothing -> 0\n\nmain = do\n n <- readLn :: IO Int\n ls <- map read . words <$> getLine :: IO [Int]\n m <- readLn :: IO Int\n aud <- map read . words <$> getLine :: IO [Int]\n sub <- map read . words <$> getLine :: IO [Int]\n\n let freq = foldr (\\a m -> M.insertWith (\\new old -> old + 1) a 1 m) M.empty ls\n\n let subMax = maximumBy (comparing (freq !!!)) sub\n let audMax = maximumBy (comparing (freq !!!)) aud\n\n let ans = maxAux aud sub 0 freq audMax 0 0\n\n print (ans+1)\n"}], "src_uid": "74ddbcf74988940265985ec8c36bb299"} {"source_code": "{-# LANGUAGE Safe #-} \n \nimport safe Control.Arrow ((>>>))\n--import safe Data.List (sort)\nimport Data.List\nimport Data.Function\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> tcio >>> unlines where\n tcio :: [String] -> [String]\n tcio [] = []\n tcio (_ : l : rest) = (itoline . solve . linetois) l : tcio rest \n linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois\n itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\n\nsolve :: [Int] -> Int\nsolve xs = if null u then (-1) else (snd.head.head) u where u = dropWhile (not.null.drop 1) $ groupBy ((==) `on` fst) $ sort $ zip xs [1..]\n", "positive_code": [{"source_code": "{-# LANGUAGE GADTs, TemplateHaskell, DeriveFunctor, OverloadedStrings #-}\n\nimport Data.List\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe\nimport Data.Int\nimport Text.Printf\nimport Data.Function ( (&), on )\nimport Data.Functor\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Char (isAlpha)\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nsolve :: [Int] -> Maybe Int\nsolve as = do\n let uniqueAs = sort as & group & filter (\\x -> length x == 1) & concat\n result <- listToMaybe uniqueAs\n index <- elemIndex result as\n return $ index + 1\n\nmainCase :: IO ()\nmainCase = do\n Just n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust)\n let answer = fromMaybe (-1) $ solve as\n printf \"%d\\n\" answer\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ const mainCase\n"}, {"source_code": "{-\nn participants\ni-th participant chose number ai\nparticipant that chooses the smallest unique number wins\n\nfind index of the participant who won, or -1 if no winner\nindex is 1-based (1 to n)\nanswer t independent test cases\n\ninput:\nt, number of test cases\nfirst line number participants\nsecond line n integers\n-}\n\nimport qualified Data.Map.Strict as Map\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\nmain = do\n cases <- read <$> getLine\n replicateM cases $ do\n _ <- getLine\n participantNumbers <- ((fmap . fmap) read) $ words <$> getLine\n putStrLn $ show $ minUniqueIndex participantNumbers\n\nminUniqueIndex :: [Int] -> Int\nminUniqueIndex xs =\n if null uniques\n then -1\n else 1 + (fromJust $ findIndex (== head uniques) xs)\n where\n uniques = Map.keys $ Map.filter (<2) $ Map.fromListWith (+) $ map (flip (,) 1) xs\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.List (groupBy, sort)\n\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:xs:xss) = solve xs : process xss\n\nsolve :: [Int] -> Int\nsolve xs\n | null ys = -1\n | otherwise = snd . head . head $ ys\n where\n ys = filter ((== 1) . length) . groupBy (eq fst) . sort $ zip xs [1 ..]\n eq p x y = p x == p y\n"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = interact $ unlines . map show . solve . map read . tail . words\n\nsolve :: [Int] -> [Int]\nsolve [] = []\nsolve (n:rs) = findMin cn :(solve rest)\n where (an,rest) = splitAt n rs\n bn = zip [1..n] an\n cn = sortBy (\\(_,vi) (_,vj) -> compare vi vj) bn\n \n\nfindMin :: [(Int,Int)] -> Int\nfindMin [] = -1\nfindMin [(i,vi)] = i\nfindMin ((i,vi):(j,vj):rs)\n | (vi /= vj) = i\n | otherwise = findMin $ dropWhile (\\(a,va) -> va == vi) rs"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve a\n | null b = -1\n | otherwise = snd . head . head $ b\n where\n b = filter ((==1) . length). groupBy (\\x y -> fst x == fst y) . sort $ zip a [1..]\n\nf [] = []\nf (_:x:xs) = solve x : f xs\n\nmain = interact $\n unlines . map show . f . tail . map (map read) . map words . lines\n"}], "negative_code": [{"source_code": "import Data.List\n\nsolve [] = -1\nsolve (x:xs) = if (length $ takeWhile (==x) xs) >= 1\n then solve $ dropWhile (==x) xs\n else x\n\nf [] = []\nf (_:x:xs) = solve (sort x) : f xs\n\nmain = interact $\n unlines . map show . f . tail . map (map read) . map words . lines\n"}], "src_uid": "99d2b0386d101da802ac508ef8f7325b"} {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\n\nifTE :: Bool -> a -> a -> a\nifTE x y z = if x then y else z\n\nboolean :: a -> a -> Bool -> a\nboolean x y z = ifTE z x y\n\nmain :: IO ()\nmain = do\n [n,m,k] <- readInts\n l <- ifTE (m <= n) id transpose <$> replicateM n readInts\n let w = min n m\n cost = curry $ sum . uncurry (zipWith ((boolean 0 1.) . (==)))\n f = sum . flip map l . (uncurry min.) . ((id &&& (w-)).) . cost \n res = minimum $ map f $ ifTE (w <= k) (replicateM w [0,1]) l\n print $ if res <= k then res else -1\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Data.Bits\nimport Data.List\n\nsolve ([n, m, k] : a)\n\t| n < m = solve ([m, n, k] : transpose a)\n\t| ans <= k = ans\n\t| otherwise = -1\n\twhere\n\t\txs = map (foldl (\\x b -> 2 * x + b) 0) a\n\t\twork y = sum $ map (uncurry min . (id &&& (m-)) . toInteger . popCount . xor y) xs\n\t\tans = minimum . map work $ if m > k then xs else [0 .. 2^m-1]\n\nmain = interact $ show . solve . map (map read . words) . lines\n"}, {"source_code": "import Control.Arrow\nimport Data.Bits\nimport Data.List\n\nsolve ([n, m, k] : a) = if n < m then solve ([m, n, k] : transpose a) else\n\tlet\n\t\txs = map (foldl (\\x b -> 2 * x + b) 0) a\n\t\tys = if m > k then xs else [0 .. 2 ^ m - 1]\n\t\twork y = sum $ map (uncurry min . (id &&& (m-)) . toInteger . popCount . (y `xor`)) xs\n\t\tcost = minimum $ map work ys\n\tin if cost <= k then cost else -1\n\nmain = interact $ show . solve . map (map read . words) . lines\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n [n,m,k] <- readInts\n l <- replicateM n readInts\n let l1 = if m <= n then l else transpose l\n let w = min n m\n let res = minimum $ do\n xs <- if w <= k then replicateM w [0,1] else l1\n return $ sum [ min (cost xs r) (cost (neg xs) r) | r <- l1 ]\n print $ if res <= k then res else -1\n\nneg :: [Int] -> [Int]\nneg = map (1-)\n\ncost :: [Int] -> [Int] -> Int\ncost xs ys = sum $ zipWith (\\a b -> if a == b then 0 else 1) xs ys\n{-\n - w <= h\u3068\u3059\u308b\n - w <= k \u306a\u3089\u3070\n - xs <- [0,1]^w\n - w > k \u306a\u3089\u3070\n - xs <- rows\n - \u3068\u3059\u308b\u3053\u306e\u3068\u304d\u306e\u6700\u5c0f\u30b3\u30b9\u30c8\u306f\n - sum [ min (popcount $ xs `xor` ri) (popcount $ not xs `xor` ri) | ri <- rs]\n - \n - -}\n"}], "negative_code": [], "src_uid": "bc937cacda9ebff9ec0b7f00f0f97508"} {"source_code": "import Data.List\n\nrl = ((map read . words) <$> getLine) :: IO [Int]\n\nfld :: Int -> [Int] -> Int -> [Int]\nfld k acc v = if length acc < k then if v `elem` acc then acc else v:acc\n else if v `elem` acc then acc else v:init acc\n\nmain = do\n [n, k] <- rl\n b <- rl\n \n let l = foldl' (fld k) [] b\n print $ length l\n putStr $ foldl' (\\a v -> a ++ ' ' : show v) (show $ head l) (tail l)", "positive_code": [{"source_code": "import Data.Set (Set)\nimport qualified Data.Set as Set\n\ninputArr = do\n line <- getLine\n let ar = map read (words line) :: [Int]\n return ar\n\nsim cur cur2 st [] rem = cur ++ (reverse cur2)\nsim [] [] st (x:xs) rem = sim [] [x] (Set.insert x st) xs (rem-1)\nsim (c:cs) [] st xs rem = sim [] (reverse (c:cs)) st xs rem\nsim cur (c:cs) st (x:xs) rem\n | Set.member x st = sim cur (c:cs) st xs rem\n | rem > 0 = sim (x:cur) (c:cs) (Set.insert x st) xs (rem-1)\n | otherwise = sim (x:cur) cs newSt xs rem\n where newSt = Set.insert x (Set.delete c st)\n\nmain = do\n [n,k] <- inputArr\n a <- inputArr\n let res = sim [] [] Set.empty a k\n putStrLn (show (length res))\n putStrLn (concat (map ((++ \" \") . show) res))\n"}, {"source_code": "import Data.List\nmain = do\n [n,k] <- map read . words <$> getLine\n ids <- map read . words <$> getLine :: IO [Int]\n let ids' = foldl' (incoming k) [] ids\n print (length ids')\n putStrLn $ unwords $ map show ids'\nincoming k q i | i `elem` q = q\n | otherwise = take k (i : q)\n"}, {"source_code": "import Data.Foldable\nimport Data.Set hiding (map, deleteAt, toList)\nimport Data.Sequence\nimport Control.Monad\n\nsolve :: Int -> Int -> [Int] -> (Int, [Int])\nsolve n k ids = \n\tlet\n\t\thelper :: Set Int -> Seq Int -> Int -> [Int] -> (Int, [Int]) \n\t\thelper set seq m [] = (m, toList seq)\n\t\thelper set seq m (id:ids)\n\t\t\t| id `member` set = helper set seq m ids\n\t\t\t| otherwise = \n\t\t\tif m < k\n\t\t\tthen helper (id `insert` set) (id <| seq) (m + 1) ids\n\t\t\telse let\n\t\t\t\tJust toDel = seq !? (k - 1)\n\t\t\tin\n\t\t\t\thelper (id `insert` (toDel `delete` set)) (id <| (deleteAt (k - 1) seq)) m ids\n\tin\n\t\thelper Data.Set.empty Data.Sequence.empty 0 ids\nmain = do\n\tfirstStr <- getLine\n\tlet n : k : [] = map read $ words firstStr\n\tsecondStr <- getLine\n\tlet ids = map read $ words secondStr\n\tlet (m, finalIds) = solve n k ids\n\tputStrLn $ show m\n\tmapM_ (\\x -> putStr $ (show x) ++ \" \") finalIds\n"}, {"source_code": "import Data.Set (Set)\nimport qualified Data.Set as Set\n\ninputArr = do\n line <- getLine\n let ar = map read (words line) :: [Int]\n return ar\n\nsim cur cur2 st [] rem = cur ++ (reverse cur2)\nsim [] [] st (x:xs) rem = sim [] [x] (Set.insert x st) xs (rem-1)\nsim (c:cs) [] st xs rem = sim [] (reverse (c:cs)) st xs rem\nsim cur (c:cs) st (x:xs) rem\n | Set.member x st = sim cur (c:cs) st xs rem\n | rem > 0 = sim (x:cur) (c:cs) (Set.insert x st) xs (rem-1)\n | otherwise = sim (x:cur) cs newSt xs rem\n where newSt = Set.insert x (Set.delete c st)\n\nmain = do\n [n,k] <- inputArr\n a <- inputArr\n let res = sim [] [] Set.empty a k\n putStrLn (show (length res))\n putStrLn (concat (map ((++ \" \") . show) res))\n"}, {"source_code": "import Data.List\nimport qualified Data.Sequence as Q\nimport qualified Data.IntSet as S\nimport Data.Foldable\nmain = do\n [n,k] <- map read . words <$> getLine\n ids <- map read . words <$> getLine :: IO [Int]\n let (ids',_) = foldl' (incoming k) (Q.empty,S.empty) ids\n print (length ids')\n putStrLn $ unwords $ map show $ toList ids'\nincoming k (q,s) i | i `S.member` s = (q,s)\n | Q.length q < k = (i Q.<| q,S.insert i s)\n | (q' Q.:> i') <- Q.viewr q =\n (i Q.<| q',S.insert i (S.delete i' s))\n"}, {"source_code": "import Data.Foldable\nimport Data.Set hiding (map, deleteAt, toList)\nimport Data.Sequence\nimport Control.Monad\n\nsolve :: Int -> Int -> [Int] -> (Int, [Int])\nsolve n k ids = \n\tlet\n\t\thelper :: Set Int -> Seq Int -> Int -> [Int] -> (Int, [Int]) \n\t\thelper set seq m [] = (m, toList seq)\n\t\thelper set seq m (id:ids)\n\t\t\t| id `member` set = helper set seq m ids\n\t\t\t| otherwise = \n\t\t\tif m < k\n\t\t\tthen helper (id `insert` set) (id <| seq) (m + 1) ids\n\t\t\telse let\n\t\t\t\tJust toDel = seq !? (k - 1)\n\t\t\tin\n\t\t\t\thelper (id `insert` (toDel `delete` set)) (id <| (deleteAt (k - 1) seq)) m ids\n\tin\n\t\thelper Data.Set.empty Data.Sequence.empty 0 ids\nmain = do\n\tfirstStr <- getLine\n\tlet n : k : [] = map read $ words firstStr\n\tsecondStr <- getLine\n\tlet ids = map read $ words secondStr\n\tlet (m, finalIds) = solve n k ids\n\tputStrLn $ show m\n\tmapM_ (\\x -> putStr $ (show x) ++ \" \") finalIds\n"}], "negative_code": [{"source_code": "import Data.List\n\nrl = ((map read . words) <$> getLine) :: IO [Int]\n\nfld :: Int -> [Int] -> Int -> [Int]\nfld k acc v = if length acc < k then if v `elem` acc then acc else v:acc\n else if v `elem` acc then acc else v:(tail acc)\n\nmain = do\n [n, k] <- rl\n b <- rl\n \n let l = foldl' (fld k) [] b\n print $ length l\n putStr $ foldl' (\\a v -> a ++ ' ' : (show v)) (show $ head l) (tail l)"}, {"source_code": "import Data.List\n\nrl = ((map read . words) <$> getLine) :: IO [Int]\n\nfld :: Int -> [Int] -> Int -> [Int]\nfld k acc v = if length acc < k then if v `elem` acc then acc else acc ++ [v]\n else if v `elem` acc then acc else init acc ++ [v]\n\nmain = do\n [n, k] <- rl\n b <- rl\n \n let l = foldl' (fld k) [] b\n print $ length l\n putStr $ foldl' (\\a v -> show v ++ ' ' : a) (show $ head l) (tail l)"}, {"source_code": "import Data.List\n\nrl = ((map read . words) <$> getLine) :: IO [Int]\n\nfld :: Int -> [Int] -> Int -> [Int]\nfld k acc v = if length acc < k then if v `elem` acc then acc else acc ++ [v]\n else if v `elem` acc then acc else v:init acc\n\nmain = do\n [n, k] <- rl\n b <- rl\n \n let l = foldl' (fld k) [] b\n print $ length l\n putStr $ foldl' (\\a v -> show v ++ ' ' : a) (show $ head l) (tail l)"}], "src_uid": "485a1ecf8f569b85327b99382bda9466"} {"source_code": "{- <\u10e6> Haskell -}\n{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = interact $! solve\n\nsolve :: String -> String\nsolve s = check (map words (tail (lines s))) 1000000000\n\ncheck :: [[String]] -> Int -> String\ncheck [] pre = \"YES\"\ncheck (x:xs) pre\n | max w h <= pre = check xs (max w h)\n | min w h <= pre = check xs (min w h)\n | otherwise = \"NO\"\n where\n [ws, hs] = x\n w = read ws :: Int\n h = read hs :: Int", "positive_code": [{"source_code": "import Data.List\n\ntoint s = (read s) :: Integer\n\ndoit [] k = True\ndoit (x:(y:xs)) k =\n if max x y <= k then\n doit xs $ max x y\n else\n if min x y <= k then\n doit xs $ min x y\n else\n False\n\nsolve::String -> String\nsolve ss =\n let s = map toint (tail (words ss)) in\n let r = doit s (2^30) in\n if r then\n \"YES\\n\"\n else\n \"NO\\n\"\n\nmain = do\n interact $ solve\n"}, {"source_code": "import Data.Maybe\n\nmain = interact foo\n\nfoo :: String -> String\nfoo inp = \n let _:(n1, n2):ns = map (\\n -> (n!!0, n!!1)) . map (map read . words) . lines $ inp :: [(Int, Int)]\n in if isNothing $ foldl check (Just $ max n1 n2) ns then \"NO\" else \"YES\"\n \ncheck :: Maybe Int -> (Int, Int) -> Maybe Int\ncheck Nothing _ = Nothing\ncheck (Just l) (n1, n2)\n | l >= man = Just man\n | l >= mn = Just mn\n | otherwise = Nothing\n where mn = min n1 n2\n man = max n1 n2\n "}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\npr :: String -> (Int, Int)\npr str = (read f :: Int, read s :: Int)\n where\n [f, s] = words str\n\nf :: (Int, Bool) -> (Int, Int) -> (Int, Bool)\nf (lv, r) (cw, ch)\n | not r = (lv, r)\n | max cw ch <= lv = (max cw ch, r)\n | min cw ch <= lv = (min cw ch, r)\n | otherwise = (lv, False)\n\nsolve :: String -> String\nsolve s\n | ans = \"YES\"\n | not ans = \"NO\"\n where\n r = map pr (tail (lines s))\n (_, ans) = foldl f (maxBound :: Int, True) r\n\nmain = interact $! solve\n"}, {"source_code": "{- <\u10e6> Haskell -}\n{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = interact $! solve\n\ntoInt :: String -> Int\ntoInt s = read s :: Int\n\nsolve :: String -> String\nsolve s = check (tail (map words (lines s))) 1000000000\n\ncheck :: [[String]] -> Int -> String\ncheck [] pre = \"YES\"\ncheck (x:xs) pre =\n if | max w h <= pre -> check xs (max w h)\n | min w h <= pre -> check xs (min w h)\n | otherwise -> \"NO\"\n where\n [ws, hs] = x\n w = toInt ws\n h = toInt hs"}, {"source_code": "{- <\u10e6> Haskell -}\n{-# LANGUAGE MultiWayIf #-}\nmodule Main where\n\nmain :: IO ()\nmain = interact $ solve\n\ntoInt :: String -> Int\ntoInt s = read s :: Int\n\nsolve :: String -> String\nsolve s = check (tail (map words (lines s))) 1000000000\n\ncheck :: [[String]] -> Int -> String\ncheck [] pre = \"YES\"\ncheck (x:xs) pre =\n if | max w h <= pre -> check xs (max w h)\n | min w h <= pre -> check xs (min w h)\n | otherwise -> \"NO\"\n where\n [ws, hs] = x\n w = toInt ws\n h = toInt hs"}], "negative_code": [], "src_uid": "162fa942bc6eeb5164b19598da2f8bef"} {"source_code": "import Control.Monad (replicateM_)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\nmaybeTake :: (Eq i, Num i) => i -> [a] -> Maybe [a]\nmaybeTake 0 _ = Just []\nmaybeTake _ [] = Nothing\nmaybeTake n (x:xs) = (x:) <$> maybeTake (n-1) xs\n\nslices :: (Eq i, Num i) => i -> [a] -> [[a]]\nslices n xs = case maybeTake n xs of\n Nothing -> []\n Just p -> p : slices n (tail xs)\n\n\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO = do\n n <- readLn\n arr <- getList\n putStrLn . (\\x -> show (head x) ++ \"\\n\" ++ (unwords $ map show x)) $ solve n arr\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs | all (== head xs) xs = replicate n 1\n | even n = take n $ cycle [2,1]\n | repIndex /= [] = let p = head repIndex; arr2 = if even p then [1,2] else [2,1]\n in take p (cycle [2,1]) ++ take (n-p) (cycle arr2)\n | otherwise = 3 : (take (n-1) $ cycle [2,1])\n where\n repIndex :: [Int]\n repIndex = map snd . filter (\\([a,b], c) -> a == b) $ zip (slices 2 (xs++[head xs])) [1..]", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.Bool (bool)\nimport safe Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords)\n >>> unlines\n\nprocess :: [[Integer]] -> [[Integer]]\nprocess [] = []\nprocess ([n] : a : rest) = solve n a ++ process rest\n\nsolve :: Integer -> [Integer] -> [[Integer]]\nsolve n a = [[maximum fin], fin]\n where\n nn = fromIntegral n\n fin\n | all (== head a) a = replicate nn 1\n | head cols == last cols && head a /= last a =\n fromMaybe (3 : tail cols) (update cols)\n | otherwise = cols\n\n cols = colour 1 a\n\n update :: [Integer] -> Maybe [Integer]\n update [] = Nothing\n update [_] = Nothing\n update (x : x' : xs)\n | x == x' = Just (x : map (pick True) (x' : xs))\n | otherwise = (x :) <$> update (x' : xs)\n\n colour :: Integer -> [Integer] -> [Integer]\n colour _ [] = []\n colour cur [_] = [cur]\n colour cur (x : x' : xs) = cur : colour (pick (x /= x') cur) (x' : xs)\n\n pick :: Bool -> Integer -> Integer\n pick fl x = bool x (3 - x) fl\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.Bool (bool)\nimport safe Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords)\n >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([n] : a : rest) = solve n a ++ process rest\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve n a = [[maximum fin], fin]\n where\n fin\n | all (== head a) a = replicate n 1\n | head cols == last cols && head a /= last a =\n fromMaybe (3 : tail cols) (update cols)\n | otherwise = cols\n\n cols = colour 1 a\n\n update :: [Int] -> Maybe [Int]\n update [] = Nothing\n update [_] = Nothing\n update (x : xs)\n | x == head xs = Just (x : map (pick True) xs)\n | otherwise = (x :) <$> update xs\n\n colour :: Int -> [Int] -> [Int]\n colour _ [] = []\n colour cur [_] = [cur]\n colour cur (x : x' : xs) = cur : colour (pick (x /= x') cur) (x' : xs)\n\n pick :: Bool -> Int -> Int\n pick fl x = bool x (3 - x) fl\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.Bool (bool)\nimport safe Data.Maybe (fromMaybe)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords)\n >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([n] : a : rest) = solve n a ++ process rest\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve n a = [[maximum fin], fin]\n where\n nn = fromIntegral n\n fin\n | all (== head a) a = replicate nn 1\n | head cols == last cols && head a /= last a =\n fromMaybe (3 : tail cols) (update cols)\n | otherwise = cols\n\n cols = colour 1 a\n\n update :: [Int] -> Maybe [Int]\n update [] = Nothing\n update [_] = Nothing\n update (x : x' : xs)\n | x == x' = Just (x : map (pick True) (x' : xs))\n | otherwise = (x :) <$> update (x' : xs)\n\n colour :: Int -> [Int] -> [Int]\n colour _ [] = []\n colour cur [_] = [cur]\n colour cur (x : x' : xs) = cur : colour (pick (x /= x') cur) (x' : xs)\n\n pick :: Bool -> Int -> Int\n pick fl x = bool x (3 - x) fl\n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (nub)\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n n <- read <$> getLine\n ts <- words <$> getLine\n if same ts then do\n print 1\n putStrLn $ unwords $ replicate n \"1\"\n else if n `mod` 2 == 0 then do\n print 2\n putStrLn $ unwords $ concat $ replicate (div n 2) [\"1\", \"2\"]\n else case consec 0 (head ts) ts of\n Just i -> do\n print 2\n putStrLn $ unwords $ repeatNth i $ concat $\n replicate (div n 2) [\"1\", \"2\"]\n Nothing -> do\n print 3\n putStrLn $ unwords $ (\"3\" :) $ concat $\n replicate (div n 2) [\"1\", \"2\"]\n\nsame (x:xs@(y:_)) = x == y && same xs\nsame _ = True\n\nconsec _ _ [] = Nothing\nconsec i x [y] = if x == y then Just i else Nothing\nconsec i s (x:y:zs) = if x == y then Just i else consec (i + 1) s (y:zs)\n\n\nrepeatNth n (x:xs) =\n if n == length xs + 1\n then (x:xs) ++ [x]\n else repeatNth' n (x:xs)\n\nrepeatNth' 0 (x:xs) = x:x:xs\nrepeatNth' n (x:xs) = x : repeatNth' (n-1) xs\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> drop 1 >>> map (words >>> map read) \n >>> process \n >>> map (map show >>> unwords) >>> unlines\n\nprocess :: [[Integer]] -> [[Integer]]\nprocess [] = []\nprocess ([n]:a:rest) = solve n a ++ process rest \n\nsolve :: Integer -> [Integer] -> [[Integer]]\nsolve n a = [[foldl1 max fin], fin]\n where\n nn = fromIntegral n\n fin\n | a == (take nn $ repeat (head a)) = take nn $ repeat 1\n | head cols == head (reverse cols)\n && head a /= head (reverse a) = \n case newcols of Nothing -> 3 : tail cols\n (Just a) -> a\n | otherwise = cols\n where newcols = update cols\n\n cols = colour 1 a\n \n update :: [Integer] -> Maybe [Integer]\n update [] = Nothing\n update [_] = Nothing\n update (x:y:rest)\n | x == y = Just (x : map (pick True) (y : rest))\n | otherwise = case rec of (Just a) -> Just (x : a)\n Nothing -> Nothing \n where rec = update (y : rest) \n \n colour :: Integer -> [Integer] -> [Integer]\n colour _ [] = []\n colour cur [x] = [cur]\n colour cur (x:y:rest) = cur : colour (pick (x /= y) cur) (y : rest)\n\n pick :: Bool -> Integer -> Integer\n pick fl x\n | fl = 3 - x\n | otherwise = x"}], "negative_code": [{"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> drop 1 >>> map (words >>> map read) \n >>> process \n >>> map (map show >>> unwords) >>> unlines\n\nprocess :: [[Integer]] -> [[Integer]]\nprocess [] = []\nprocess ([n]:a:rest) = solve n a ++ process rest \n\nsolve :: Integer -> [Integer] -> [[Integer]]\nsolve n a = [[foldl1 max fin], fin]\n where\n fin\n | head cols == head (reverse cols)\n && head a /= head (reverse a) = 3 : tail cols\n | otherwise = cols\n cols = colour 1 a\n colour :: Integer -> [Integer] -> [Integer]\n colour _ [] = []\n colour cur [x] = [cur]\n colour cur (x:y:rest)\n | x == y = cur : colour cur (y : rest)\n | otherwise = cur : colour (3 - cur) (y : rest)"}, {"source_code": "import Control.Monad (replicateM_)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\nmaybeTake :: (Eq i, Num i) => i -> [a] -> Maybe [a]\nmaybeTake 0 _ = Just []\nmaybeTake _ [] = Nothing\nmaybeTake n (x:xs) = (x:) <$> maybeTake (n-1) xs\n\nslices :: (Eq i, Num i) => i -> [a] -> [[a]]\nslices n xs = case maybeTake n xs of\n Nothing -> []\n Just p -> p : slices n (tail xs)\n\n\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO = do\n n <- readLn\n arr <- getList\n putStrLn . (\\x -> show (head x) ++ \"\\n\" ++ (unwords $ map show x)) $ solve n arr\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs | all (== head xs) xs = replicate n 1\n | even n = take n $ cycle [2,1]\n | repIndex /= [] = let p = head repIndex; arr2 = if even p then [1,2] else [2,1]\n in take p (cycle [2,1]) ++ take (n-p) (cycle arr2)\n | otherwise = 3 : (take (n-1) $ cycle [2,1])\n where\n repIndex :: [Int]\n repIndex = map snd . filter (\\([a,b], c) -> a == b) $ zip (slices 2 xs) [1..]"}, {"source_code": "import Control.Monad (replicateM_)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\nmaybeTake :: (Eq i, Num i) => i -> [a] -> Maybe [a]\nmaybeTake 0 _ = Just []\nmaybeTake _ [] = Nothing\nmaybeTake n (x:xs) = (x:) <$> maybeTake (n-1) xs\n\nslices :: (Eq i, Num i) => i -> [a] -> [[a]]\nslices n xs = case maybeTake n xs of\n Nothing -> []\n Just p -> p : slices n (tail xs)\n\n\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO = do\n n <- readLn\n arr <- getList\n putStrLn . (\\x -> show (head x) ++ \"\\n\" ++ (unwords $ map show x)) $ solve n arr\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs | all (== head xs) xs = replicate n 1\n | even n = take n $ cycle [2,1]\n | repIndex /= [] = let p = head repIndex in take p (cycle [2,1]) ++ take (n-p) (cycle [1,2])\n | otherwise = 3 : (take (n-1) $ cycle [2,1])\n where\n repIndex = map snd . filter (\\([a,b], c) -> a == b) $ zip (slices 2 xs) [1..]"}], "src_uid": "1f4c3f5e7205fe556b50320cecf66c89"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nnewtype State s a = State { runState :: s -> (a,s) }\nnewtype Identity a = Identity { runIdentity :: a }\n\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Functor Identity where\n fmap f = runIdentity >>> f >>> Identity\n\ninstance Monad Identity where\n return = Identity\n x >>= f = f (runIdentity x)\n\ninstance Applicative Identity where\n pure = return\n (<*>) = ap\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Char where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Double where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nfixMemoArray :: (Ix a) => (a,a) -> RecFun Identity a b -> Array a b\nfixMemoArray b f = arr\n where\n g y = Identity $ arr ! y\n arr = listArray b [ runIdentity $ f g x | x <- range b ]\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\nsolve :: Int -> Double -> Double\nsolve m r = r * (sum [memo ! i + memo ! (m-i-1) - 2| i <- [0..m-1]] / (itof m)^2)\n where\n memo :: UArray Int Double\n memo = fixMemoUArray (0,m-1) $ \\f i -> case i of\n 0 -> pure $ 2\n 1 -> pure $ 4+sqrt 2\n i -> ((+) $ 2* itof (i-1) + 2*sqrt 2) <$> f (i-1)\n\nmain = do\n [m,r] <- readsLine\n print $ solve m (itof r)\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (forM, liftM)\nimport Text.Printf (printf)\n\ntoDouble :: Int -> Double\ntoDouble = fromIntegral\n\nmain = do\n [m, r] <- liftM (map read . words) getContents\n let radius = toDouble r\n near = 2.0 * radius\n neighbour = 2.0 * radius + radius * (sqrt 2.0)\n far = radius + radius * 2.0 * (sqrt 2.0)\n\n distances <- forM [1 .. m] $ \\i -> do\n let numNear = 1.0\n numNeighbour | m == 1 = 0.0\n | i == 1 || i == m = 1.0\n | otherwise = 2.0\n farLeft = toDouble $ max (i - 2) 0\n farRight = toDouble $ max (m - i - 1) 0\n distance = numNear * near +\n numNeighbour * neighbour +\n (far * farLeft + radius * farLeft * farLeft) +\n (far * farRight + radius * farRight * farRight)\n return (distance / (toDouble m))\n let result = (sum distances) / (toDouble m)\n printf \"%.9f\\n\" result"}, {"source_code": "import Text.Printf\n\nsolve :: Int -> Int -> Int -> Double\nsolve m r i\n\t| (i<=m) = 2.0 +\n\t\t(if (i>1) then (2+sqrt 2) else 0) +\n\t\t(if (i>2) then (((fromIntegral (i-1))*(fromIntegral (i-2))) + (fromIntegral (i-2))*2.0*sqrt 2) else 0) +\n\t\t(if (i Int -> Double\nsolution m r =\n\t(solve m r 1) * (fromIntegral r) / (fromIntegral m)**2\n\nmain :: IO ()\nmain = do\n\tnStr <- getLine\n\tlet [m, r] = map read $ words nStr\n\tprintf \"%.10f\\n\" $ solution m r"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit.HUnit\n\ntests :: Test\ntests = TestList \"All tests\"\n [\n Test \"#1\" $ assertEq 2 (solve [1, 1]),\n Test \"#2\" $ assertEq 4 (solve [1, 2]),\n Test \"#3\" $ assertApproximate 5.4142135623 (solve [2, 2]) 9,\n Test \"#4\" $ assertApproximate 200002.4853316681 (solve [100000, 3]) 9\n ]\n\nmain :: IO ()\nmain = run tests\n-}\n--------------------------------------------------------------------------------\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nreads' :: Read a => IO [a]\nreads' = liftM (map read . words) (readFile \"input.txt\")\n\nsolve :: [Double] -> Double\nsolve [1, r] = 2 * r\nsolve [n, r] = k * r / (n^2)\n where\n k = 2 * n + (2 * (n - 1) * (2 + sqrt 2))\n + sum [2 * (n - i) * (2 * (i - 1) + 2 * sqrt 2) | i <- [2..n]]\n\nmain :: IO ()\nmain = reads >>= print . solve\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (forM, liftM)\nimport Text.Printf (printf)\n\ntoDouble :: Int -> Double\ntoDouble = fromIntegral\n\nmain = do\n [m, r] <- liftM (map read . words) getContents\n let radius = toDouble r\n near = 2.0 * radius\n neighbour = 2.0 * radius + radius * (sqrt 2.0)\n far = 2.0 * radius + radius * 2.0 * (sqrt 2.0)\n\n distances <- forM [1 .. m] $ \\i -> do\n let numNear = 1.0\n numNeighbour | m == 1 = 0.0\n | i == 1 || i == m = 1.0\n | otherwise = 2.0\n farLeft = toDouble $ max (i - 2) 0\n farRight = toDouble $ max (m - i - 1) 0\n distance = numNear * near +\n numNeighbour * neighbour +\n (far * farLeft + radius * farLeft * farLeft) +\n (far * farRight + radius * farRight * farRight)\n return (distance / (toDouble m))\n let result = (sum distances) / (toDouble m)\n printf \"%.9f\\n\" result"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nnewtype State s a = State { runState :: s -> (a,s) }\nnewtype Identity a = Identity { runIdentity :: a }\n\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Functor Identity where\n fmap f = runIdentity >>> f >>> Identity\n\ninstance Monad Identity where\n return = Identity\n x >>= f = f (runIdentity x)\n\ninstance Applicative Identity where\n pure = return\n (<*>) = ap\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Char where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Double where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nfixMemoArray :: (Ix a) => (a,a) -> RecFun Identity a b -> Array a b\nfixMemoArray b f = arr\n where\n g y = Identity $ arr ! y\n arr = listArray b [ runIdentity $ f g x | x <- range b ]\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\nsolve :: Int -> Double -> Double\nsolve m r = sum [ memo ! i + memo ! (m-i-1) - memo ! 0 | i <- [0..m-1]] / (itof m)^2\n where\n memo :: UArray Int Double\n memo = fixMemoUArray (0,m-1) $ \\f i -> case i of\n 0 -> pure $ 2*r\n i -> (\\a -> a + 2*(itof i)*r + r*sqrt 2) <$> f (i-1)\n\nmain = do\n [m,r] <- readsLine\n print $ solve m (itof r)\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nnewtype State s a = State { runState :: s -> (a,s) }\nnewtype Identity a = Identity { runIdentity :: a }\n\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Functor Identity where\n fmap f = runIdentity >>> f >>> Identity\n\ninstance Monad Identity where\n return = Identity\n x >>= f = f (runIdentity x)\n\ninstance Applicative Identity where\n pure = return\n (<*>) = ap\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Char where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nfixMemoArray :: (Ix a) => (a,a) -> RecFun Identity a b -> Array a b\nfixMemoArray b f = arr\n where\n g y = Identity $ arr ! y\n arr = listArray b [ runIdentity $ f g x | x <- range b ]\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\ndistance :: Double -> Double -> Double\ndistance m r = sum [ 2 * r + i * 2 * r - if i == 0 then 0 else (2*r - r* sqrt 2) | i <- [0..m-1]] / m\n\nmain = do\n [m,r] <- readsLine\n print $ distance m r\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\ntype Array1 a = Array Int a\ntype Array2 a = Array (Int,Int) a\ntype UArray1 a = UArray Int a\ntype UArray2 a = UArray (Int,Int) a\ntype RecFun m a b = (a -> m b) -> a -> m b\n\nnewtype State s a = State { runState :: s -> (a,s) }\nnewtype Identity a = Identity { runIdentity :: a }\n\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Functor Identity where\n fmap f = runIdentity >>> f >>> Identity\n\ninstance Monad Identity where\n return = Identity\n x >>= f = f (runIdentity x)\n\ninstance Applicative Identity where\n pure = return\n (<*>) = ap\n\nclass IArray UArray e => Unboxable e where\n newSTUArray_ :: forall s i. Ix i => (i, i) -> ST s (STUArray s i e)\n readSTUArray :: forall s i. Ix i => STUArray s i e -> i -> ST s e\n writeSTUArray :: forall s i. Ix i => STUArray s i e -> i -> e -> ST s ()\n\ninstance Unboxable Int where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Char where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\n\ninstance Unboxable Double where\n newSTUArray_ = newArray_\n readSTUArray = readArray\n writeSTUArray = writeArray\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadLine :: Read a => IO a\nreadLine = read <$> getLine \nreadsLine :: Read a => IO [a]\nreadsLine = map read . words <$> getLine\n\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\n\nswap (a,b) = (b,a)\nrect a b = rect2 0 0 a b\nrect2 i j a b = ((i,j),(a,b))\n\nitof :: Int -> Double\nitof = fromIntegral\n\nmaximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]\nminimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]\n\nfibs = 1:1:zipWith (+) fibs (tail fibs)\n\nprimeArray :: Int -> UArray1 Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nbinSearch f a b = go a b\n where\n go i j | i + 1 == j = i\n | f m = go m j\n | otherwise = go i m\n where m = div (i+j) 2\n\nfixMemoArray :: (Ix a) => (a,a) -> RecFun Identity a b -> Array a b\nfixMemoArray b f = arr\n where\n g y = Identity $ arr ! y\n arr = listArray b [ runIdentity $ f g x | x <- range b ]\n\nfixMemoUArray :: (Ix a,Unboxable b) => (a,a) -> (forall s . RecFun (ST s) a b) -> UArray a b\nfixMemoUArray b f = runSTUArray $ do\n arr <- newSTUArray_ b\n forM_ (range b) $ \\x -> f (\\y -> readSTUArray arr y) x >>= writeSTUArray arr x\n return arr\n\nsolve :: Int -> Double -> Double\nsolve m r = sum [ memo ! i + memo ! (m-i-1) - memo ! 0 | i <- [0..m-1]] / (itof m)^2\n where\n memo :: UArray Int Double\n memo = fixMemoUArray (0,m-1) $ \\f i -> case i of\n 0 -> pure $ 2*r\n i -> (\\a -> a + (2*(itof i)*r + r*sqrt 2)) <$> f (i-1)\n\nmain = do\n [m,r] <- readsLine\n print $ solve m (itof r)\n\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nreads' :: Read a => IO [a]\nreads' = liftM (map read . words) (readFile \"input.txt\")\n\nsolve :: [Double] -> Double\nsolve [1, r] = 2 * r\nsolve [n, r] = k * r / (n^2)\n where\n k = 2 * n + (2 * (n - 1) * (2 + sqrt 2)) + sum [2 * (n - i) * (2 * (i - 2) + 2 * sqrt 2) | i <- [3..n]]\n\nmain :: IO ()\nmain = reads >>= print . solve\n"}], "src_uid": "f827ea399e6b801c0392eac53710d950"} {"source_code": "{-# LANGUAGE Strict #-}\n\nimport Control.Monad (replicateM, replicateM_)\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n print $ solve 0 ps\n\nsolve :: Int -> [Int] -> Int\nsolve n [] = n\nsolve n [p] = n\nsolve n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps)\n\n-- solve !n [] = n\n-- solve !n [p] = n\n-- solve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps)\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n print . maxOdd n\n\nmaxOdd :: Int -> [Int] -> Int\nmaxOdd n ps = m ps 0\n\nm :: [Int] -> Int -> Int\nm [] acc = acc\nm [_] acc = acc\nm (p1:p2:ps) acc | p1 < p2 = m (p2:ps) acc\n | p1 >= p2 = m ps (acc+1)\n \n"}, {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Int\nsolve 0 _ = 0\nsolve 1 _ = 0\nsolve n as@(a1:a2:otherAs) | a1 > a2 = 1 + solve (n - 2) otherAs\nsolve n as@(_:otherAs) = solve (n - 1) otherAs\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n printf \"%d\\n\" answer\n"}, {"source_code": "{-# LANGUAGE Strict #-}\n\nimport Control.Monad (replicateM, replicateM_)\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Maybe (fromJust)\n\nreadInt :: B8.ByteString -> Int\nreadInt = fst . fromJust . B8.readInt\n\n\nreadInts :: B8.ByteString -> [Int]\nreadInts = map readInt . B8.words\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readInt <$> B8.getLine :: IO Int\n ps <- readInts <$> B8.getLine :: IO [Int]\n print $ solve ps\n\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve [p] = 0\nsolve (p:pp:ps) = if p > pp then 1 + solve ps else solve (pp:ps)\n\n\n-- solve !n [] = n\n-- solve !n [p] = n\n-- solve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps)\n"}, {"source_code": "{-# LANGUAGE Strict #-}\n\nimport Control.Monad (replicateM, replicateM_)\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n print $ solve ps\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve [p] = 0\nsolve (p:pp:ps) = if p > pp then 1 + solve ps else solve (pp:ps)\n\n\n-- solve !n [] = n\n-- solve !n [p] = n\n-- solve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM, replicateM_)\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readLn :: IO Int\n ps <- seq () $ map read . words <$> getLine :: IO [Int]\n print $ solve 0 ps\n\nsolve :: Int -> [Int] -> Int\nsolve !n [] = n\nsolve !n [p] = n\nsolve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM, replicateM_)\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n n <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n print $ solve 0 ps\n\nsolve :: Int -> [Int] -> Int\nsolve !n [] = n\nsolve !n [p] = n\nsolve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n res <- replicateM t run\n putStrLn . unlines $ res\n\nrun :: IO String\nrun = do\n n <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n return . show $ solve 0 ps\n\n\nsolve :: Int -> [Int] -> Int\nsolve !n [] = n\nsolve !n [p] = n\nsolve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve n (pp:ps) \n"}, {"source_code": "import Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n res <- replicateM t run\n putStrLn . unlines $ res\n\nrun :: IO String\nrun = do\n n <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n return . show $ solve ps\n\n\nsolve :: [Int] -> Int\nsolve [] = 0\nsolve [p] = 0\nsolve (p:pp:ps) = if p > pp then 1 + solve ps else solve (pp:ps) \n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n res <- replicateM t run\n putStrLn . unlines $ res\n\nrun :: IO String\nrun = do\n n <- readLn :: IO Int\n ps <- map read . words <$> getLine :: IO [Int]\n return . show $ solve 0 ps\n\n\nsolve :: Int -> [Int] -> Int\nsolve !n [] = n\nsolve !n [p] = n\nsolve !n (p:pp:ps) = if p > pp then solve (n+1) ps else solve (n+1) (pp:ps) \n"}], "src_uid": "80e21bfe08a3ef156d0404d4fe07bccd"} {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Bits\r\nimport Data.Graph\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n eds <- fmap concat $ replicateM (n - 1) $ do\r\n ~[u, v] <- readInts\r\n pure [(u, v), (v, u)]\r\n let g = buildG (1, n) eds\r\n [t] = dfs g [1]\r\n (xs, ys) = if length xs' < length ys' then (xs', ys') else (ys', xs') where\r\n (xs', ys') = partition (p!) [1..n]\r\n p = array (1, n) $ parity t\r\n lxs = length xs\r\n (gr, grs) = (gr, reverse grs') where\r\n gr:grs' = groups n\r\n pxs = concatMap (grs!!) $ filter (testBit lxs) [0 .. length grs - 1]\r\n pys = filter (`IS.notMember` s) [1..n] where s = IS.fromList pxs\r\n ans = array (1, n) $ zip (xs ++ ys) (pxs ++ pys)\r\n putStrLn $ unwords $ map show $ elems ans\r\n\r\ngroups :: Int -> [[Int]]\r\ngroups 0 = []\r\ngroups n = [n, n-1 .. m] : groups (m - 1) where\r\n m = bit (highestSetBit n)\r\n\r\nparity :: Tree a -> [(a, Bool)]\r\nparity t = go False t [] where\r\n go p (Node u ts) acc = (u, p) : foldr (go $ not p) acc ts\r\n\r\nhighestSetBit :: Int -> Int\r\nhighestSetBit n = finiteBitSize n - countLeadingZeros n - 1\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Array as DA\r\nimport qualified Data.IntSet as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n ps2 = concat [[(x,y),(y,x)] | (x,y)<-ps]\r\n adjArr = DA.accumArray (flip (:)) [] (1,n) ps2\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (adjArr DA.! node)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n wl = DS.size whites\r\n wlabels = concat [[x..2*x-1] | i<-[0..DB.finiteBitSize wl], DB.testBit wl i, let x=DB.shift 1 i]\r\n blabels = concat [[x..2*x-1] | i<-[0..DB.finiteBitSize wl], not (DB.testBit wl i), let x=DB.shift 1 i]\r\n unsortedAns = zip (DS.toList whites ++ DS.toList blacks) (wlabels++blabels)\r\n ans = DA.elems $ DA.accumArray (+) 0 (1,n) unsortedAns \r\n in Output ans\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Array as DA\r\nimport qualified Data.IntSet as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n ps2 = concat [[(x,y),(y,x)] | (x,y)<-ps]\r\n adjArr = DA.accumArray (flip (:)) [] (1,n) ps2\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (adjArr DA.! node)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n wl = DS.size whites\r\n wlabels = concat [[2^i..(2^(i+1)-1)] | i<-[0..DB.finiteBitSize wl], DB.testBit wl i]\r\n blabels = concat [[2^i..(2^(i+1)-1)] | i<-[0..DB.finiteBitSize wl], not (DB.testBit wl i)]\r\n unsortedAns = zip (DS.toList whites ++ DS.toList blacks) (wlabels++blabels)\r\n ans = DA.elems $ DA.accumArray (+) 0 (1,n) unsortedAns \r\n in Output ans\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Array as DA\r\nimport qualified Data.IntSet as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n ps2 = concat [[(x,y),(y,x)] | (x,y)<-ps]\r\n adjArr = DA.accumArray (flip (:)) [] (1,n) ps2\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (adjArr DA.! node)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n inversePerm = merge (DS.toList whites) (DS.toList blacks) 1 (DS.size whites) []\r\n perm = fmap snd $ DL.sort $ zip inversePerm [1..]\r\n in Output perm\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Array as DA\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n ps2 = concat [[(x,y),(y,x)] | (x,y)<-ps]\r\n adjArr = DA.accumArray (flip (:)) [] (1,n) ps2\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (adjArr DA.! node)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n inversePerm = merge (DS.toList whites) (DS.toList blacks) 1 (DS.size whites) []\r\n perm = fmap snd $ DL.sort $ zip inversePerm [1..]\r\n in Output perm\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n adjMap = DM.fromListWith (++) $ concat [[(x,[y]),(y,[x])] | (x,y)<-ps]\r\n sureLookup x m = fromMaybe [] $ DM.lookup x m\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (sureLookup node adjMap)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n inversePerm = merge (DS.toList whites) (DS.toList blacks) 1 (DS.size whites) []\r\n perm = fmap snd $ DL.sort $ zip inversePerm [1..]\r\n in Output perm\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Bits\r\nimport Data.Graph\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n eds <- fmap concat $ replicateM (n - 1) $ do\r\n ~[u, v] <- readInts\r\n pure [(u, v), (v, u)]\r\n let (xs, ys) = if length xs' < length ys' then (xs', ys') else (ys', xs') where\r\n (xs', ys') = partition (p!) [1..n]\r\n p = array (1, n) $ parity t\r\n [t] = dfs (buildG (1, n) eds) [1]\r\n lxs = length xs\r\n pxs = concatMap generate $ filter (testBit lxs) [0 .. finiteBitSize lxs - 1]\r\n pys = filter (`IS.notMember` s) [1..n] where s = IS.fromList pxs\r\n ans = array (1, n) $ zip (xs ++ ys) (pxs ++ pys)\r\n putStrLn $ unwords $ map show $ elems ans\r\n\r\ngenerate :: Int -> [Int]\r\ngenerate i = [bit i .. bit (i + 1) - 1]\r\n\r\nparity :: Tree a -> [(a, Bool)]\r\nparity t = go False t [] where\r\n go p (Node u ts) acc = (u, p) : foldr (go $ not p) acc ts\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Array as DA\r\nimport qualified Data.IntSet as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n ps2 = concat [[(x,y),(y,x)] | (x,y)<-ps]\r\n adjArr = DA.accumArray (flip (:)) [] (1,n) ps2\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (adjArr DA.! node)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n wl = DS.size whites\r\n wlabels = concat [[2^i..(2*(i+1)-1)] | i<-[0..DB.finiteBitSize wl], DB.testBit wl i]\r\n blabels = concat [[2^i..(2*(i+1)-1)] | i<-[0..DB.finiteBitSize wl], not (DB.testBit wl i)]\r\n unsortedAns = zip (DS.toList whites ++ DS.toList blacks) (wlabels++blabels)\r\n ans = DA.elems $ DA.accumArray (+) 0 (1,n) unsortedAns \r\n in Output ans\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n{-# LANGUAGE BangPatterns #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.IntMap.Strict as DM\r\nimport qualified Data.Array as DA\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n pssp = ps ++ reverse ps\r\n adjArr = DA.accumArray (flip (:)) [] (1,n) pssp\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (adjArr DA.! node)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n inversePerm = merge (DS.toList whites) (DS.toList blacks) 1 (DS.size whites) []\r\n perm = fmap snd $ DL.sort $ zip inversePerm [1..]\r\n in Output perm\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n !ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl \r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.Map.Lazy as DM\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n adjMap = DM.fromListWith (++) [(x,[y]) | (x,y)<-ps]\r\n sureLookup x m = fromMaybe [] $ DM.lookup x m\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (sureLookup node adjMap)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n inversePerm = merge (DS.toList whites) (DS.toList blacks) 1 (DS.size whites) []\r\n perm = fmap snd $ DL.sort $ zip inversePerm [1..]\r\n in Output perm\r\n\r\nmerge :: [a] -> [a] -> Int -> Int -> [a] -> [a]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl = merge ws (b:bs) (m+1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m+1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m+1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m+1) wl (w:ans)\r\nmerge _ _ _ _ ans = reverse ans\r\n\r\nlg :: Int->Int\r\nlg x = DB.finiteBitSize x - DB.countLeadingZeros x - 1\r\n\r\nithlsb :: Int -> Int -> Bool\r\nithlsb i n = DB.testBit n i\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl\r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.Map.Lazy as DM\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n pssp = ps ++ [(y,x) | (x,y)<-ps]\r\n adjMap = DM.fromListWith (++) [(x,[y]) | (x,y)<-pssp]\r\n sureLookup x m = fromMaybe [] $ DM.lookup x m\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (sureLookup node adjMap)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n perm = merge (DS.toList whites) (DS.toList blacks) n (DS.size whites) []\r\n in Output perm\r\n\r\nmerge :: Integral a1 => [a2] -> [a2] -> a1 -> a1 -> [a2] -> [a2]\r\nmerge (w:ws) (b:bs) m wl ans \r\n | ithlsb (lg m) wl == 1 = merge ws (b:bs) (m-1) wl (w:ans)\r\n | otherwise = merge (w:ws) bs (m-1) wl (b:ans)\r\nmerge [] (b:bs) m wl ans = merge [] bs (m-1) wl (b:ans)\r\nmerge (w:ws) [] m wl ans = merge ws [] (m-1) wl (w:ans)\r\nmerge _ _ _ _ ans = ans\r\n\r\nlg :: Integral t => t -> t\r\nlg 1 = 0\r\nlg n = 1 + lg (n`div`2)\r\n\r\nithlsb :: Integral t => t -> t -> t\r\nithlsb 0 n = n`mod`2\r\nithlsb i n = ithlsb (i-1) (n`div`2)\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl\r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.Map.Lazy as DM\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\n\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n pssp = ps ++ [(y,x) | (x,y)<-ps]\r\n adjMap = DM.fromListWith (++) [(x,[y]) | (x,y)<-pssp]\r\n sureLookup x m = fromMaybe [] $ DM.lookup x m\r\n colorSubtree color node [ws,bs]\r\n | DS.member node ws || DS.member node bs = [ws,bs]\r\n | otherwise = foldr (colorSubtree (1-color)) (add node color [ws,bs]) (sureLookup node adjMap)\r\n add node color [c0,c1] = if color==0 then [DS.insert node c0,c1] else [c0,DS.insert node c1]\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorSubtree 0 1 [DS.empty,DS.empty]\r\n wsbs = DS.toList whites ++ DS.toList blacks\r\n wsbsns = zip wsbs [1..]\r\n nswsbs = DL.sort wsbsns\r\n perm = map snd nswsbs\r\n in Output perm\r\n\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl\r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport System.IO\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu\r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\nimport Control.Arrow\r\nimport Data.Function\r\nimport qualified Data.Bits as DB\r\nimport qualified Data.Map.Lazy as DM\r\nimport qualified Data.Set as DS\r\nimport qualified Data.List as DL\r\n\r\ndata Input = Input {ne :: Int, pairs :: [(Int,Int)]}\r\ndata Output = Output [Int] deriving Show\r\n\r\nsureLookup :: (Integral a, Ord k) => k -> DM.Map k [a] -> [a]\r\nsureLookup x m = fromMaybe [] $ DM.lookup x m\r\n\r\nsolve :: Input -> Output\r\nsolve (Input n ps) = let\r\n pssp = ps ++ [(y,x) | (x,y)<-ps]\r\n adjMap = DM.fromListWith (++) [(x,[y]) | (x,y)<-pssp]\r\n colorAdj self adj [ws,bs]\r\n | DS.notMember adj ws && DS.notMember self bs = if DS.member self ws then [ws,DS.insert adj bs] else [DS.insert adj ws,bs]\r\n | otherwise = [ws,bs]\r\n colorAdjs self = foldr (colorAdj self) [DS.fromList [1], DS.empty] (sureLookup self adjMap)\r\n [whites,blacks] = DL.sortBy (compare `on` DS.size) $ colorAdjs 1\r\n wsbs = DS.toList whites ++ DS.toList blacks\r\n wsbsns = zip wsbs [1..]\r\n nswsbs = DL.sort wsbsns\r\n perm = map snd nswsbs\r\n in Output perm\r\n\r\n-- gives a State(T) monad which when run gives Input\r\ninput :: StateT [B8.ByteString] Identity Input\r\ninput = do\r\n n <- getIntegral\r\n ps <- replicateM (n-1) $ (\\[x,y]->(x,y)) <$> (getIntegrals 2)\r\n return $ Input n ps\r\n\r\noutput :: Output -> Bu.Builder\r\noutput = go where\r\n str = Bu.string7\r\n nl = Bu.string7 \"\\n\"\r\n sp = Bu.string7 \" \"\r\n dec = Bu.intDec\r\n go (Output xs) = mconcat [dec x <> sp| x<-xs] <> nl\r\n\r\nnumberOfTestcases :: St Int\r\nnumberOfTestcases = explicit\r\n where implicit = return 1 :: St Int\r\n explicit = getIntegral\r\n\r\n------------------------------- main --------------------------------\r\ntype St = StateT [B8.ByteString] Identity\r\n\r\ngetByteString :: St B8.ByteString\r\ngetByteString = state getNext where\r\n getNext [] = (B8.take 0 (B8.pack \".\"),[])\r\n getNext (w:ws) = (w,ws)\r\n\r\ngetIntegral :: Num t => St t\r\ngetIntegral = convertToNum <$> getByteString where\r\n convertToNum x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x\r\n\r\ngetIntegrals :: Num t => Int -> St [t]\r\ngetIntegrals n = replicateM n getIntegral\r\n\r\ndoTestcase :: St Bu.Builder\r\ndoTestcase = input >>= (solve >>> output >>> return)\r\n\r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let outputs = flip evalState bytestrings $ do\r\n nTc <- numberOfTestcases\r\n let answers = replicateM nTc doTestcase\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString outputs\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Bits\r\nimport Data.Graph\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n eds <- fmap concat $ replicateM (n - 1) $ do\r\n ~[u, v] <- readInts\r\n pure [(u, v), (v, u)]\r\n let g = buildG (1, n) eds\r\n [t] = dfs g [1]\r\n pty = array (1, n) $ parity t\r\n (xs, ys) = partition (pty!) [1..n]\r\n zs = if length xs > length ys then xs ++ ys else ys ++ xs\r\n gs = concat $ sortOn (Down . length) $ groups n\r\n ans = array (1, n) $ zip zs gs\r\n putStrLn $ unwords $ map show $ elems ans\r\n\r\ngroups :: Int -> [[Int]]\r\ngroups 0 = []\r\ngroups n = [n, n-1 .. m] : groups (m - 1) where\r\n m = bit (highestSetBit n)\r\n\r\nparity :: Tree a -> [(a, Bool)]\r\nparity t = go False t [] where\r\n go p (Node u ts) acc = (u, p) : foldr (go $ not p) acc ts\r\n\r\nhighestSetBit :: Int -> Int\r\nhighestSetBit n = finiteBitSize n - countLeadingZeros n - 1\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "src_uid": "d253d8efc344b0848a19876ff52c09a8"} {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: Int -> [Int] -> Int\n-- answer is at most 1000 * 10^4, so no overflow worries\nsolve k a = case sort a of\n [] -> 0\n (s : t) -> sum [div (k - x) s | x <- t]\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, k] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n print $ solve k a\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1 -- T\n >>> map (words >>> map read)\n >>> process\n >>> map (show)\n >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([n, k] : as : rest) = solve k as : process rest\n\nsolve :: Int -> [Int] -> Int\nsolve k a =\n (\\a' -> sum a' - foldl1 max a') $\n map ((`div` (foldl1 min a)) . (k -)) a\n"}], "negative_code": [], "src_uid": "b89e9598adae3da19903cdbfd225dd3c"} {"source_code": "foo n [] = [n]\nfoo n [x] = [n]\nfoo n [_,x] = [n]\nfoo n (_:x:xs) = x : foo n xs\n\nmain = do\n line <- getLine\n let n = read line :: Int\n line <- getLine\n let a = map read $ words line :: [Int]\n let b = foo n $ map fst $ filter ((< 0) . snd) $ zip [1 ..] a\n let c = zipWith (-) b $ 0 : b\n putStrLn $ show $ length c\n putStrLn $ unwords $ map show c\n", "positive_code": [{"source_code": "go [] = []\ngo [a] = [a]\ngo (a:b:c) = b:go c\n\nmain = do\n n <- fmap read getLine\n a <- fmap (map read . words) getLine\n let b = go $ map fst $ filter ((<0) . snd) $ zip [1 ..] a\n c = if null b then [n] else init b ++ [n]\n print $ length c\n putStrLn $ unwords $ map show $ zipWith (-) c $ 0:c\n"}, {"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n\nimport Data.List\n\naddOne :: [Int] -> [Int]\naddOne (a:b) = (a + 1):b\n\ngetFolders :: Int -> [Int] -> [Int]\ngetFolders _ [] = 0:[]\ngetFolders 2 (a:b)\n\t| a >= 0\t= addOne (getFolders 2 b) \n\t| otherwise\t= 0:(addOne (getFolders 1 b))\ngetFolders n (a:b)\n\t| a >= 0\t= addOne (getFolders n b) \n\t| otherwise\t= addOne (getFolders (n + 1) b) \t\n\nprintList :: [Int] -> IO()\nprintList (a:[]) = do\n\tputStrLn (show a)\nprintList (a:b:c) = do\n\tputStr (show a)\n\tputStr \" \"\n\tprintList (b:c)\n\nmain :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tlet l = getFolders 0 (map read (words str2))\n\tputStrLn (show (length l))\n\tprintList l\n"}, {"source_code": "import Data.List\n\nmain = do\n getLine\n a <- fmap (map read . words) getLine\n let g = split a\n print $ length g\n putStr $ concat $ intersperse \" \" $ map (show . length) g\n\nsplit xs = split' xs []\n where\n split' [] [] = []\n split' [] part = [part]\n split' (x:xs) part = if x < 0 && (length $ filter (< 0) part) == 2\n then part:(split' xs [x])\n else split' xs (x:part)\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> [Int]\nsolve = solve' 0 0\n where\n solve' _ 0 [] = []\n solve' _ n [] = [n]\n solve' a n (x:xs)\n | a == 2 && x < 0 = n : solve' 0 0 (x:xs)\n | x < 0 = solve' (a + 1) (n + 1) xs\n | otherwise = solve' a (n + 1) xs\n\nprints :: Show a => [a] -> IO ()\nprints xs = print (length xs) >> prints' xs\n where\n prints' xs = putStrLn $ intercalate \" \" $ map show xs\n\nmain :: IO ()\nmain = do\n getLine\n xs <- liftM (map read . words) getLine\n prints $ solve xs"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nreadInt :: String -> Int\nreadInt = read\n\nreadSequence :: String -> [Int]\nreadSequence s = let (h,t) = break (==' ') s in\n let t' = if null t then t else tail t in\n if null h then [] else readInt h : readSequence t'\n\ncalc :: [Int] -> (Int,[Int])\ncalc = countFolders . folder . compress\n\ncompress :: [Int] -> [Bool]\ncompress = map (>=0)\n\nfolder :: [Bool] -> [[Bool]]\nfolder = reverse . f 0 [] []\n where f _ t r [] = t:r\n f x t r (b:bs) | b = f x (b:t) r bs\n f x t r (b:bs) | not b && x < 2 = f (x+1) (b:t) r bs\n f x t r (b:bs) | not b && x >= 2 = f 1 [b] (t:r) bs\n\ncountFolders :: [[a]] -> (Int, [Int])\ncountFolders xs = (length xs, map length xs)\n\nmain = do\n n <- readInt <$> getLine\n sequence <- readSequence <$> getLine\n let (k,bs) = calc sequence\n print k\n putStrLn $ tail $ concatMap ((' ':) . show) bs\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmain = do\n _ <- getLine\n xs <- fmap(map read.words)getLine\n let ans = solve 0 0 xs\n print $ length ans\n putStrLn.unwords.map show $ ans\n\nsolve !ans !cnt (x:rest)\n | x < 0 && cnt==2 = ans : solve 1 1 rest\n | x < 0 = solve (ans+1) (cnt+1) rest\n | otherwise = solve (ans+1) cnt rest\nsolve ans _ _ = [ans]"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n getLine\n a <- fmap (map read . words) getLine\n let g = split a\n print $ length g\n putStr $ concat $ intersperse \" \" $ map (show . length) g\n\nsplit xs = split' xs []\n where\n split' [] [] = []\n split' [] part = [part]\n split' (x:xs) part = if x < 0 && (length $ filter (< 0) part) == 3\n then part:(split' xs [x])\n else split' xs (x:part)\n"}], "src_uid": "3f320920a023c3bc10ba1525e8c89044"} {"source_code": "--https://codeforces.com/contest/1671/problem/A\n\nimport Data.List\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\nmain :: IO ()\nmain = do\n n <- getInt\n input <- getLines n\n let a = map (\\ e -> foldr (&&) True $ map (\\ s -> length s > 1) $ group e) input\n let r = map (\\x -> if x then \"YES\" else \"NO\") a\n putStr $ unlines r", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\n\nsolve :: String -> Bool\nsolve str = L.all (>= 2) groupLengths\n where\n groupLengths = L.length <$> L.group str\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n s <- B8.getLine <&> L.head . B8.words\n let answer = solve $ B8.unpack s\n putsYesNo answer\n"}, {"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\nshowArr :: Show a => [a] -> String\r\nshowArr = concatMap (\\x -> show x ++ \" \")\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ngetPair :: String -> (Int, Int)\r\ngetPair s = case toArr s of\r\n [x, y] -> (x, y)\r\n _ -> error \"getPair failed\"\r\n\r\ntype InType = String\r\ntype OutType = Bool\r\n\r\nsolve :: InType -> OutType\r\nsolve (a : b : c : t) = (a == b || b == c) && solve (b : c : t)\r\nsolve _ = True\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = \"*\" ++ s ++ \"*\"\r\nreceive _ = error \"input error\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showB . solve . receive) . chunksOf 1 . tail . lines\r\n where showB True = \"YES\"\r\n showB False = \"NO\"\r\n"}], "negative_code": [{"source_code": "--https://codeforces.com/contest/1671/problem/A\n\nimport Data.List\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\ncheck :: Int -> Bool\ncheck i = mod i 2 == 0 || mod i 3 == 0 || mod i 4 == 0 || mod i 5 == 0 || mod i 6 == 0 || mod i 7 == 0\n\nmain :: IO ()\nmain = do\n n <- getInt\n input <- getLines n\n let a = map (\\ e -> foldr (&&) True $ map (\\ s -> check $ length s) $ group e) input\n let r = map (\\x -> if x then \"YES\" else \"NO\") a\n putStr $ unlines r"}, {"source_code": "--https://codeforces.com/contest/1671/problem/A\n\nimport Data.List\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetInts :: Int -> IO [Int]\ngetInts n = fmap read <$> getLines n\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\ncheck :: Int -> Bool\ncheck i = mod i 2 == 0 || mod i 3 == 0 || mod i 5 == 0\n\nmain :: IO ()\nmain = do\n n <- getInt\n input <- getLines n\n let a = map (\\ e -> foldr (&&) True $ map (\\ s -> check $ length s) $ group e) input\n let r = map (\\x -> if x then \"YES\" else \"NO\") a\n putStr $ unlines r"}], "src_uid": "e95e2d21777c1d686bede1b0a5dacbf5"} {"source_code": "import Control.Monad (forM_)\n\nsolve (s:ss) o z = \n if o == z then \n if s == '1' then solve ss (o-1) z else solve ss o (z-1)\n else min o z\n\nmain = do\n n <- readLn :: IO Int\n forM_ [1..n] $ \\_ -> do\n s <- getLine\n let ones = length $ filter (=='1') s\n let zeros = (length s) - ones\n print $ max (solve s ones zeros) (solve (reverse s) ones zeros)\n", "positive_code": [{"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine\n let zero = foldl (\\b x -> if x == '0' then b + 1 else b) 0 input\n one = foldl (\\b x -> if x == '1' then b + 1 else b) 0 input \n mid = (length input - 1)`div` 2\n return $ minimum [zero, one, mid]\n\nmain = do\n tlen <- readLn :: IO Int\n ans <- forM [0..(tlen - 1)] (\\t -> do \n solve t\n )\n mapM print ans\n"}, {"source_code": "import Control.Monad (forM_)\n\ncount c = length . filter (== c)\n\nsolve l = (if c1 == c2 then (\\x -> x - 1) else id) (min c1 c2)\n where\n c1 = count '1' l\n c2 = count '0' l\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n print $ solve l\n"}, {"source_code": "-- ID : 1633B (B. Minority)\r\n-- URL : https://codeforces.com/contest/1633/problem/B\r\n \r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nmain = do\r\n t <- read `fmap` getLine :: IO Int\r\n replicateM_ t solve\r\n\r\nsolve = do\r\n -- input\r\n xs <- (map (\\c -> ord c - ord '0')) `fmap` getLine\r\n let n = length xs\r\n let ones = foldl1 (+) xs\r\n let zeros = n - ones\r\n print $ ((n - 1) `div` 2) `min` zeros `min` ones\r\n"}, {"source_code": "-- ID : 1633B (B. Minority)\r\n-- URL : https://codeforces.com/contest/1633/problem/B\r\n \r\nimport Control.Monad\r\nimport Data.Array\r\nimport Data.Char\r\nimport Data.Int\r\n\r\ngetInt = read `fmap` getLine :: IO Int\r\n\r\nmain = do\r\n t <- getInt\r\n replicateM_ (fromIntegral t) solve\r\n\r\nparse01 c\r\n | c == '0' = 0\r\n | c == '1' = 1\r\n\r\nsolve = do\r\n -- input\r\n xs <- (map parse01) `fmap` getLine\r\n let n = length xs\r\n let ones = listArray (0,n) $ scanl (+) 0 xs\r\n let f1 i = (ones ! i)\r\n let f0 i = (fromIntegral i) - (f1 i)\r\n -- solve\r\n let dp = array (1,n) [(i, f i) | i <- [1..n]] where\r\n f 1 = 0\r\n f 2 = 0\r\n f i = max (dp ! (i-1)) (if (f1 i) == (f0 i) then 0 else (min (f1 i) (f0 i)))\r\n print (dp ! n)\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n s <- getLine\r\n let _0 = count '0' s\r\n _1 = count '1' s\r\n print $ (if _0 == _1 then subtract 1 else id) (min _0 _1)\r\n\r\ncount :: (Eq a) => a -> [a] -> Int\r\ncount x = length . filter (==x)\r\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>= print . minRem\n\nminRem s = let (ones, zeroes) = countE s (0, 0) in\n if (ones == zeroes)\n then ones-1\n else min ones zeroes\n\ncountE :: String -> (Int, Int) -> (Int, Int)\ncountE [] a = a\ncountE ('0':xs) (o, z) = countE xs (o, z+1)\ncountE ('1':xs) (o, z) = countE xs (o+1, z)\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n str <- getLine\n print $ solve str\n return ()\n\nsolve :: String -> Int\nsolve str = if zeroes == ones\n then ones - 1\n else min zeroes ones\n where\n zeroes = count '0' str\n ones = count '1' str\n\ncount :: Char -> String -> Int\ncount x = length . filter (x==)\n"}, {"source_code": "main :: IO()\r\n\r\nmain =\r\n interact $ unlines . map (show . process) . drop 1 . lines\r\n\r\nprocess xs = \r\n let s1 = foldl (\\acc x -> if x == '1' then acc+1 else acc) 0 xs\r\n s0 = length xs - s1\r\n in if s0 == s1 then s0 - 1 else min s0 s1\r\n"}], "negative_code": [{"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine\n let zero = foldl (\\b x -> if x == '0' then b + 1 else b) 0 input\n one = foldl (\\b x -> if x == '1' then b + 1 else b) 0 input \n mid = length input `div` 2 - 1\n return $ minimum [zero, one, mid]\n\nmain = do\n tlen <- readLn :: IO Int\n ans <- forM [0..(tlen - 1)] (\\t -> do \n solve t\n )\n mapM print ans\n"}, {"source_code": "import Control.Monad (forM)\n\nsolve t = do \n input <- getLine\n let zero = foldl (\\b x -> if x == '0' then b + 1 else b) 0 input\n one = foldl (\\b x -> if x == '1' then b + 1 else b) 0 input \n return (if zero > one then one else if one > zero then zero else 0)\n\nmain = do\n tlen <- readLn :: IO Int\n ans <- forM [0..(tlen - 1)] (\\t -> do \n solve t\n )\n mapM print ans\n"}, {"source_code": "import Control.Monad (forM_)\n\ncount c = length . filter (== c)\n\nsolvee c1 c2\n | c1 < c2 = c1\n | c1 == c2 = 0\n | otherwise = c2\n\nsolve l = solvee c1 c2\n where\n c1 = count '1' l\n c2 = count '0' l\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n print $ solve l\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n s <- getLine\r\n let _0 = count '0' s\r\n _1 = count '1' s\r\n print $ if _0 == _1 then 0 else min _0 _1\r\n\r\ncount :: (Eq a) => a -> [a] -> Int\r\ncount x = length . filter (==x)\r\n"}], "src_uid": "62f5798bdcea237c0df9b4cd288b97de"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nsolve :: [Int] -> [Int]\nsolve [] = []\nsolve (p : q : r : vs)\n | q > p && q > r = p : q : maximum (q : take 1 vs) : solve vs\nsolve (v : vs) = v : solve vs\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n a <- replicateM n getInt\n let\n ans = solve a\n diffs = length $ filter id $ zipWith (/=) a ans\n pure $ putInts [diffs] <> putInts ans\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve :: (Num b, Ord b) => [b] -> b -> ([b], b)\nsolve [] ops = ([], ops)\nsolve [a] ops = ([a], ops)\nsolve [a, b] ops = ([a, b], ops)\nsolve (a : b : c : cs) ops = (a : next, ops')\n where\n maxx = b > a && b > c\n maxxx = max b (if not (null cs) then head cs else 0)\n (next, ops') = solve (if maxx then b : maxxx : cs else b : c : cs) (if maxx then ops + 1 else ops)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n _ <- getLine\n l <- getLine\n let arr = map read (words l) :: [Int]\n let (ans, ops) = solve arr 0\n print ops\n putStrLn $ unwords $ map show ans\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nsolve :: [Int] -> [Maybe Int]\r\nsolve [] = []\r\nsolve (p : q : r : vs)\r\n | q > p && q > r = Just p : Just q : Nothing : solve vs\r\nsolve (v : vs) = Just v : solve vs\r\n\r\nsolve2 :: [Maybe Int] -> [Int]\r\nsolve2 [Just x, Nothing] = [x, x]\r\nsolve2 (Just x : Nothing : t@(Just y : _)) = x : max x y : solve2 t\r\nsolve2 (Nothing : t@(Just y : _)) = y : solve2 t\r\nsolve2 (Just x : t) = x : solve2 t\r\nsolve2 [] = []\r\nsolve2 (Nothing : _) = error \"solve2: yikes\"\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let\r\n ans = solve a\r\n diffs = length $ filter isNothing ans\r\n pure $ putInts [diffs] <> putInts (solve2 ans)\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve :: (Ord t, Num a) => t -> t -> [t] -> a\nsolve _ _ [] = 0\nsolve ll l (c : []) = if (l > ll && l > c) then 1 else 0\nsolve ll l (c : cs)\n | l > ll && l > c = 1 + solve l (max l (cs !! 0)) cs\n | otherwise = solve l c cs\n\n\nsolve2 :: (Ord t, Num t) => t -> t -> [t] -> [t]\nsolve2 a b [] = [a,b]\nsolve2 ll l (c : []) = if (l > ll && l > c) then [ll,l, l] else [ll, l, c]\nsolve2 ll l (c : cs)\n | l > ll && l > c = (ll : solve2 l (max l (cs !! 0)) cs)\n | otherwise = (ll : (solve2 l c cs))\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n let (a : b : cs) = arr\n let a1 = solve a b cs\n print a1\n let a2 = solve2 a b cs\n forM_ a2 $ \\i -> do\n putStr $ show(i)\n putStr \" \"\n putStr \"\\n\"\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nsolve :: Int -> [Int] -> [Int]\r\nsolve _ [] = []\r\nsolve repv (p : q : r : vs)\r\n | q > p && q > r = p : q : solve repv (repv : vs)\r\nsolve repv (v : vs) = v : solve repv vs\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let\r\n ans = solve (foldl' max minBound a) a\r\n diffs = length $ filter id $ zipWith (/=) a ans\r\n pure $ putInts [diffs] <> putInts ans\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "src_uid": "255abf8750541f54d8ff0f1f80e1f8e7"} {"source_code": "import Data.List(sort)\ngetans m k (mx:smx:_) = mx*m - (m `div` (k+1)) * (mx - smx) \nmain = do\n str <- getLine\n let [n, m, k] = map (read::String->Integer) $ words str\n str2 <- getLine\n print $ getans m k $ reverse $ sort $ map (read::String->Integer) $ words str2", "positive_code": [{"source_code": "module Main where\nimport Data.List\n\nmain = do\n [_, m, k] <- map (read :: String -> Integer) . words <$> getLine\n n <- map (read :: String -> Integer) . words <$> getLine\n let [a,b] = take 2 $ reverse $ sort n\n (c,d) = m `quotRem` (k+1)\n print $ a*k*c+b*c+a*d"}], "negative_code": [{"source_code": "import Data.List(sort)\ngetans m k (mx:smx:_) = mx*m + (m `div` (k+1)) * (mx - smx) \nmain = do\n str <- getLine\n let [n, m, k] = map (read::String->Integer) $ words str\n str2 <- getLine\n print $ getans m k $ reverse $ sort $ map (read::String->Integer) $ words str2"}, {"source_code": "import Data.List(sort)\ngetans m k (mx:smx:_) = mx*m + (m `div` (k+1)) * (mx - smx) \nmain = do\n str <- getLine\n let [n, m, k] = map (read::String->Integer) $ words str\n str2 <- getLine\n print $ getans m k $ sort $ map (read::String->Integer) $ words str2"}, {"source_code": "module Main where\nimport Data.List\n\nmain = do\n [_, m, k] <- map (read :: String -> Int) . words <$> getLine\n n <- map (read :: String -> Int) . words <$> getLine\n let [a,b] = take 2 $ reverse $ sort n\n (c,d) = m `quotRem` (k+1)\n print $ a*k*c+b*c+a*d"}], "src_uid": "96dee17800e147350bd37e60f66f49dd"} {"source_code": "import Data.List\nimport Data.Maybe\n \nmain = do\n getLine\n [x, k, y] <- map read . words <$> getLine\n as <- (0 :) . (++ [-1]) . map read . words <$> getLine\n bs <- (0 :) . (++ [-1]) . map read . words <$> getLine\n print $ fromMaybe (- 1) $ solve x k y as bs\n \nsolve x k y (al : ars) (bl : bs@(br : _))\n | al /= bl || null as || null costs = Nothing\n | otherwise = (minimum costs +) <$> solve x k y as bs\n where\n (range, as) = span (/= br) ars\n len = genericLength range\n costs = [y * len | maximum (0 : range) < max bl br] ++ concat [[x + y * (len - k), x * (len `div` k) + y * (len `mod` k)] | len >= k]\nsolve _ _ _ _ _ = Just 0", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nimport Data.List\nimport Data.Maybe\n\nmain = do\n getLine\n [x, k, y] <- map read . words <$> getLine\n as <- (0 :) . (++ [-1]) . map read . words <$> getLine\n bs <- (0 :) . (++ [-1]) . map read . words <$> getLine\n print $ fromMaybe (- 1) $ solve x k y as bs\n\nsolve x k y (al : ars) (bl : bs@(br : _))\n | al /= bl || null as || null costs = Nothing\n | otherwise = (minimum costs +) <$> solve x k y as bs\n where\n (range, as) = span (/= br) ars\n len = genericLength range\n costs = [y * len | maximum (0 : range) < max bl br] ++ concat [[x + y * (len - k), x * (len `div` k) + y * (len `mod` k)] | len >= k]\nsolve _ _ _ _ _ = Just 0\n"}], "negative_code": [], "src_uid": "461666a075cd830496f919557b8122a4"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n [h, w] <- getIntList\n let ans = getAnswer h w 1\n forM_ ans putStrLn\n putChar '\\n'\n\ngetFirstAndLast :: Int -> String\ngetFirstAndLast w = take w $ cycle \"10\"\n\ngetAnswer :: Int -> Int -> Int -> [String]\ngetAnswer h w i\n | i == h = [getFirstAndLast w]\n | i == 1 = getFirstAndLast w : getAnswer h w (i + 1)\n | i == h - 1 = emptyLine : getAnswer h w (i + 1)\n | i `mod` 2 == 0 = emptyLine : getAnswer h w (i + 1)\n | otherwise = setLine : getAnswer h w (i + 1)\n where emptyLine = take w $ repeat '0'\n setLine = \"1\" ++ (take (w - 2) $ repeat '0') ++ \"1\"\n\n-- 101001\n-- 000000\n-- 100001\n-- 000000\n-- 100000\n-- 001010", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.Int (Int64)\nimport Data.List as L\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\nimport qualified System.IO as Io\n\nimport Data.Word (Word8)\nimport qualified Data.ByteString as B\n--import Data.IntSet \n\n\nllines :: Int -> Int -> Int -> [String]\nllines h w curr\n | curr == 0 = line : llines h w (curr+1)\n | curr == h - 1 = [line]\n | otherwise = (if odd curr || curr == h - 2 then replicate w '0' else \"1\" ++ replicate (w-2) '0' ++ \"1\") : llines h w (curr+1)\n where evenline = foldl (++) \"\" $ replicate (div w 2) \"10\"\n oddline = evenline ++ \"1\"\n line = if even w then evenline else oddline\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [h, w] = map read $ words s :: [Int]\n rect = llines h w 0\n in putStrLn $ intercalate \"\\n\" rect\n \n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n \n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE Strict #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust)\r\n\r\nmain :: IO ()\r\n-- main = C.interact $ runScanner (C.pack <$> testCase)\r\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\r\n\r\ntestCase :: Scanner String\r\ntestCase = unlines . solve <$> pair int int\r\n\r\ntype Grid = [[Char]]\r\n\r\nsolve :: (Int, Int) -> Grid\r\nsolve (h, w) = [[if ok i j then '1' else '0' | j <- [1 .. w]] | i <- [1 .. h]]\r\n where\r\n ok i j\r\n | i == 1 = odd j\r\n | i == h = odd j && h >= 3\r\n | otherwise = odd i && i + 2 <= h && (j == 1 || j == w)\r\n\r\n-------------------------- Template ------------------------------------------\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> bstr\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> bstr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [], "src_uid": "730cc4be2656c1dcdbda220b8778cdbf"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (filterM, replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = String\n\ntype Output = (Int, String)\n\ninput :: Scanner Input\ninput = str *> str\n\noutput :: Output -> C.ByteString\noutput (d, s) = C.pack $ show d ++ \"\\n\" ++ s\n\nsolve :: Input -> Output\nsolve s = case find (`elem` \"14689\") s of\n Just c -> (1, [c])\n Nothing ->\n case filter ((> 1) . length) . group . sort $ s of\n (ds : _) -> (2, take 2 ds)\n [] ->\n let ss =\n minimumBy (comparing length)\n . filter (not . isPrime . read)\n . filter (not . null)\n . filterM (const [True, False])\n $ s\n in (length ss, ss)\n\nisPrime :: Int -> Bool\nisPrime n = all ((/= 0) . (n `mod`)) [2 .. n -1]\n\n-------------------------- Template ------------------------------------------\ndebug a = trace (show a) a\n\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import Data.List\r\nimport Data.Char (digitToInt)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = String\r\ntype OutType = String\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nprime :: Int -> Bool\r\nprime x = [y | y <- [1 .. x] , x `mod` y == 0] == [1, x]\r\n\r\nsubLen2 :: [a] -> [(a,a)]\r\nsubLen2 [] = []\r\nsubLen2 (x:xs) = [(x, z) | z <- xs] ++ subLen2 xs\r\n\r\nsolve :: InType -> OutType\r\nsolve n = case \"14689\" `intersect` n of\r\n x : _ -> [x]\r\n [] -> case filter (not . prime) twoDigits of\r\n y : _ -> show y\r\n [] -> error \"oops\"\r\n where\r\n twoDigits = map (\\(x, y) -> 10 * digitToInt x + digitToInt y) (subLen2 n)\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, n] = n\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines\r\n where\r\n showAns s = show (length s) ++ \"\\n\" ++ s\r\n\r\n"}, {"source_code": "module Main where\r\n\r\nimport Data.List\r\nimport Data.Char (digitToInt)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = String\r\ntype OutType = String\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nprime :: Int -> Bool\r\nprime x = [y | y <- [1 .. x] , x `mod` y == 0] == [1, x]\r\n\r\nsubLen2 :: [a] -> [(a,a)]\r\nsubLen2 [] = []\r\nsubLen2 (x:xs) = [(x, z) | z <- xs] ++ subLen2 xs\r\n\r\nsolve :: InType -> OutType\r\nsolve n = case \"14689\" `intersect` n of\r\n x : _ -> [x]\r\n [] -> case filter (not . prime) (map (\\(x, y) -> 10 * digitToInt x + digitToInt y) (subLen2 n)) of\r\n y : _ -> show y\r\n [] -> error \"oops\"\r\n\r\nreceive :: [String] -> InType\r\nreceive [_, n] = n\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines\r\n where\r\n showAns s = show (length s) ++ \"\\n\" ++ s\r\n -- showAns s = unlines [show (length s), s]\r\n\r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe (fromJust)\n\nisEvenChar '1' = True\nisEvenChar '4' = True\nisEvenChar '6' = True\nisEvenChar '8' = True\nisEvenChar '9' = True\nisEvenChar _ = False\n\n\ncalc1 :: String -> Maybe String\ncalc1 x = do\n letter <- find isEvenChar x\n return $ [letter]\n\n\ncalc2 :: String -> Maybe String\ncalc2 (a:'2':xs) = Just (a:['2'])\ncalc2 (a:'5':xs) = Just (a:['5'])\ncalc2 (a:b:xs) | a == b = Just (a:[b])\ncalc2 (a:b:c:xs) | a == c = Just (a:[c])\ncalc2 ('2':'3':'7':xs) = Just ('2':['7'])\ncalc2 ('2':'7':xs) = Just ('2':['7'])\ncalc2 ('5':'3':'7':xs) = Just ('5':['7'])\ncalc2 ('5':'7':xs) = Just ('5':['7'])\ncalc2 (a:b:c:xs) = calc2 (b:c:xs)\ncalc2 _ | otherwise = Nothing\n\n\n(<||>) :: (Monoid a, Eq a) => a -> a -> a\nx <||> y\n | x == mempty = y\n | True = x\n\n-- 77, 33\ncalc3 :: Char -> String -> Maybe String\ncalc3 ch x =\n let count = foldr (\\a b -> if a == ch then (b+1) else b) 0 x in\n if count >= 2 then Just (ch:[ch])\n else Nothing\n\n\ncalc :: String -> Maybe String\ncalc a = (calc1 a) <||> (calc2 a ) <||> (calc3 '7' a) <||> (calc3 '3' a)\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let k = read line :: Int\n line <- getLine\n let ans1 = calc line\n --print line\n let ans = fromJust ans1\n print $ length ans\n putStrLn ans\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (filterM, replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = String\n\ntype Output = (Int, String)\n\ninput :: Scanner Input\ninput = str *> str\n\noutput :: Output -> C.ByteString\noutput (d, s) = C.pack $ show d ++ \"\\n\" ++ s\n\nsolve :: Input -> Output\nsolve s = case find (`elem` \"1468\") s of\n Just c -> (1, [c])\n Nothing ->\n case filter ((> 1) . length) . group . sort $ s of\n (ds : _) -> (2, take 2 ds)\n [] ->\n let ss =\n minimumBy (comparing length)\n . filter (not . isPrime . read)\n . filter (not . null)\n . filterM (const [True, False])\n $ s\n in (length ss, ss)\n\nisPrime :: Int -> Bool\nisPrime n = all ((/= 0) . (n `mod`)) [2 .. n -1]\n\n-------------------------- Template ------------------------------------------\ndebug a = trace (show a) a\n\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "22c0489eec3d8e290fcbcf1aeb3bb66c"} {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let s = sum a\r\n print $ if s >= n then s - n else 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n ns <- getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Int) $ words s\r\n sm = sum a\r\n n = read ns :: Int\r\n print $ \r\n if sm < n then\r\n 1\r\n else\r\n sm - n\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM_ n $ do\r\n k <- getInt\r\n s <- sum <$> getInts\r\n if s < k then\r\n print 1\r\n else\r\n print $ s - k\r\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\ngetInt = read <$> getLine\r\ngetInts = map read . words <$> getLine\r\n\r\nmain = do\r\n n <- getInt\r\n replicateM_ n $ do\r\n k <- getInt\r\n a <- getInts\r\n let s = sum a\r\n if s < k then\r\n print 1\r\n else\r\n print $ s - k\r\n"}, {"source_code": "module Main where\n\n(|>) = flip ($)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n [] = []\nchunksOf n xs = take n xs : chunksOf n (drop n xs)\n\nsolve :: [Int] -> Int\nsolve a =\n if sum a >= length a\n then (sum a) - (length a)\n else 1\n\nmain :: IO ()\nmain = interact $\n unlines\n . map (show . solve)\n . map (map read . words)\n . map (head . tail)\n . chunksOf 2\n . tail\n . lines\n\n\n\n"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\nprintS = do \r\n n <- readLn::IO Int \r\n aa <- readInts \r\n let s = sum aa \r\n print $ if s>=n then s-n else 1\r\nmain = do\r\n t <- readLn::IO Int \r\n replicateM_ t printS"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [k] <- getInts\n s <- sum <$> getInts\n let\n result = case compare s k of\n GT -> s - k\n LT -> 1\n EQ -> 0\n return $ intDec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb s e = unsafePerformIO $ do\r\n hPutStrLn stderr s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine \r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine \r\n a <- map parseInt . BS.words <$> BS.getLine\r\n let s = sum a\r\n if n == s then\r\n putStrLn \"0\"\r\n else if n > s then\r\n putStrLn \"1\"\r\n else\r\n print $ s - n\r\n"}, {"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n ns <- getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Integer) (words s)\r\n n = read ns :: Integer\r\n sm = sum a\r\n print $ \r\n if sm < n then\r\n 1\r\n else\r\n sm - n\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}, {"source_code": "module Main where\n \n solve :: IO ()\n solve = do\n ns <- getLine\n s <- getLine\n let a = map (\\x -> read x :: Int) (words s)\n n = read ns :: Int\n sm = sum a\n print $ \n if sm < n then\n 1\n else\n sm - n\n \n iter :: Int -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n q <- getLine\n iter (read q :: Int)"}, {"source_code": "module Main where\r\n \r\n solve :: IO ()\r\n solve = do\r\n ns <- getLine\r\n s <- getLine\r\n let a = map (\\x -> read x :: Int) $ words s\r\n n = read ns :: Int\r\n sm = sum a\r\n print $ \r\n if sm < n then\r\n 1\r\n else\r\n sm - n\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}], "negative_code": [{"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let s = sum a\r\n l = length a\r\n print $ if s > 0 then s - l else 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let s = sum a\r\n l = length a\r\n print $ if s > 0 then s - l else l + 1\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n print $ abs (sum a) - length a \r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "src_uid": "b5985b619652e606ac96554ecfb9346a"} {"source_code": "luckyDigits :: String -> Int\nluckyDigits xs = length $ filter (\\x -> x == '4' || x == '7') xs\n\nsolve :: Int -> [String] -> Int\nsolve k xs = length $ filter (\\x -> luckyDigits x <= k) xs\n\nparseInput :: String -> (Int, [String])\nparseInput input = (k, xs) where\n ls = lines input\n k = read $ last $ words $ head ls\n xs = words $ last ls\n\nmain = do\n input <- getContents\n let (k, xs) = parseInput input\n print $ solve k xs\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\t[ n, k ] <- map read . words <$> getLine\n\tas <- words <$> getLine\n\tlet\n\t\tres = length $ filter ( ok k ) as\n\tprint res\n\nok :: Int -> String -> Bool\nok k a = count47 a <= k\n\twhere\n\t\tcount47 :: String -> Int\n\t\tcount47 = length . filter ( \\c -> c == '4' || c == '7' )\n"}, {"source_code": "main = interact $ show . solve . words\n\nsolve (n : kk : a) = length . filter ((<=k) . length . filter (`elem` \"47\")) $ a\n where k = read kk \n"}, {"source_code": "import Data.List\n\nlucky x = x == '4' || x == '7'\n\nfindLucky k [] = 0\nfindLucky k (a:ais) = \n let l = length $ (findIndices lucky a) \n in if l > k then findLucky k ais else 1 + findLucky k ais\n\nmain :: IO ()\nmain = do\n nm <- getLine\n let [_, k] = map read $ words nm\n ais <- getLine\n let a = words ais\n print $ findLucky k a\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [String] -> Int\nsolve k = length . filter happyDigitsLessK\n where\n happyDigitsLessK = (<= k) . length . filter isHappyDigit\n isHappyDigit c = c == '4' || c == '7'\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n xs <- liftM words getLine\n print $ solve k xs\n"}, {"source_code": "import Prelude\n\nmain = do \n\tstr <- getContents\n\tprint $ solve str\n\nsolve :: String -> Int\nsolve str = length $ filter (<=k) $ ln \n\twhere\n\t\t(ns:ks:a) = words str\n\t\tn = read ns\n\t\tk = read ks\n\t\taa = take n a\n\t\tln = map toLucky aa\n\t\ttoLucky number = length $ filter (\\chr -> (chr == '7') || (chr == '4')) $ number\n"}, {"source_code": "g s c = length $ filter (==c) s\nf s = sum $ map (g s) \"47\"\nt (k:s) = length $ filter (<=read k) $ map f s\nmain = interact $ show . t . tail . words"}, {"source_code": "main :: IO ()\nmain = do\n nkLine <- getLine\n intLine <- getLine\n let\n k = read $ last $ words nkLine\n intVals = words intLine\n lengths = map length $ map (filter (\\x -> x == '4' || x == '7')) intVals\n numLuckies = length $ filter (<= k) lengths\n in\n print numLuckies\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve (k:as) = length [ () | a <- as, length (filter (`elem`\"47\") (show a)) <= k ]\nsolve _ = undefined\n"}, {"source_code": "main = interact $ show . solve . tail . words\nsolve (k:as) = length $ filter ((<= read k) . length . filter (`elem` \"47\")) as\n"}, {"source_code": "main=interact$show.f.words\nf(_:k:x)=l[y|y<-x,l(filter(`elem`\"47\")y)<=read k]\nl=length "}, {"source_code": "#!/usr/bin/env runghc\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (m:a:cs) = show . length . filter (<=k) . map f $ words a\n where\n f = length . filter (\\x -> x=='4' || x=='7')\n k = read . head . tail . words $ m\n"}, {"source_code": "module Main where\n\ncheckHappyDigits :: String -> Int -> Bool\ncheckHappyDigits \"\" n\n | n >= 0 = True\n | otherwise = False\ncheckHappyDigits _ n | n < 0 = False\ncheckHappyDigits ('4':ls) n = checkHappyDigits ls (n-1)\ncheckHappyDigits ('7':ls) n = checkHappyDigits ls (n-1)\ncheckHappyDigits (_:ls) n = checkHappyDigits ls n\n\nmain = do\n nkStr <- getLine\n let [_, k] = map read $ words nkStr\n numsStr <- getLine\n let nums = words numsStr\n print $ foldl (\\ a num -> if checkHappyDigits num k then a+1 else a) 0 nums"}, {"source_code": "module Main where\nimport Data.Char\nimport Data.List.Split\n\nstrToInt :: String -> Int\nstrToInt = helper 0\n\twhere\n\t\thelper acc [] = acc\n\t\thelper acc (x:xs) = helper (acc * 10 - 48 + ord x) xs\n\nfits :: Int -> String -> Int\nfits k s = helper s 0\n\twhere\n\t\thelper [] acc | acc > k = 0\n\t\t\t | otherwise = 1\n\t\thelper (x:xs) acc | x == '4' || x == '7' = helper xs (acc + 1)\n\t\t\t\t | otherwise = helper xs acc\n\ntoInts :: String -> [Int]\ntoInts = map strToInt . filter (/=\"\") . splitOn \" \"\n\nprocess :: String -> String -> String\nprocess par = show . sum . map (fits k) . splitOn \" \"\n\twhere \n\t\t(n:k:xs) = toInts par\n\nmain :: IO ()\nmain = do\n\tn <- getLine\n\ts <- getLine\n\tputStrLn $ process n s\n\n\n"}, {"source_code": "module Main where\n\ncheckHappyDigits :: String -> Int -> Bool\ncheckHappyDigits \"\" n\n | n >= 0 = True\n | otherwise = False\ncheckHappyDigits _ n | n < 0 = False\ncheckHappyDigits ('4':ls) n = checkHappyDigits ls (n-1)\ncheckHappyDigits ('7':ls) n = checkHappyDigits ls (n-1)\ncheckHappyDigits (_:ls) n = checkHappyDigits ls n\n\nmain = do\n nkStr <- getLine\n let nk = map (read :: String -> Int) $ words nkStr\n n = nk!!0\n k = nk!!1\n numsStr <- getLine\n let nums = words numsStr\n print $ foldl (\\ a num -> if (checkHappyDigits num k) then (a+1) else a) 0 nums"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n \n \n\nmain= do\n\t[n,k]<- map read . words<$> getLine ::IO [Int]\n\ts<- words <$> getLine\n\tprint $ length $ filter (<=k) $ map (length. filter (\\z-> elem z \"47\") ) s"}, {"source_code": "process :: Int -> [String] -> Int\nprocess k = length . filter f\n where f = (<=k) . length . filter (\\x -> x `elem` \"47\")\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,k] <- fmap (map readInt.words) getLine\n xs <- fmap words getLine\n print $ process k xs"}, {"source_code": "main = do\n [n, k] <- fmap (map read . words) getLine :: IO [Int]\n a <- fmap words getLine :: IO [String]\n print $ length $ filter (<= k) $ map f a where\n f [] = 0\n f (x:xs)\n | x == '4' || x == '7' = 1 + f xs\n | otherwise = f xs"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\nimport qualified Data.IntMap as IntMap \nimport Data.List\n\nsolve k num = \n (lucky num) > k\n where lucky n = length $ filter (\\d -> (d == 4) || (d == 7)) $ map (`mod` 10) \n $ takeWhile (> 0) $ iterate (`div`10) n\nmain :: IO ()\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (k, r2) = readInt r1\n let Just (numbers, r3) = readIntList n r2\n let tSeq = length $ filter (\\x -> x == False) $ map (solve k) numbers\n putStr $ show tSeq ++ \"\\n\"\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (number, r) <- readInt s\n (l, t) <- readIntList (n-1) r\n return ((number : l, t))\n"}, {"source_code": "import Control.Applicative\nmain = do\n [n,k] <- map read . words <$> getLine\n ns <- take n . words <$> getContents\n let \n ans = length $ filter (<=k) $ map toNumberOfLucky $ ns\n toNumberOfLucky word = length $ filter (\\c -> c=='4'||c=='7') $ word\n print ans"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\n-- Meat\nsolve :: Int -> [String] -> Int\nsolve k = length . filter (ok k)\n\nok :: Int -> String -> Bool\nok k = (<= k). length . filter (`elem` \"47\")\n\n-- Shit\nmain :: IO ()\nmain = do\n [[_,k], as] <- readShit\n printShit $ solve (read k) as\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: x -> x -> Bool-> x\niif a b c = if c then a else b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}], "negative_code": [{"source_code": "main=interact$show.f.map read.words\nf(n:k:x)=l[y|y<-x,l(show y)<=k]\nl=length "}], "src_uid": "6bb26991c9ea70e51a6bda5653de8131"} {"source_code": "main :: IO ()\nmain = interact $ unlines . map unwords . solve . words\n\nsolve :: [String] -> [[String]]\nsolve (_ : ds) = [[show $ length ans], ans]\n where\n ans\n | null $ d1 ++ d2 = d0 ++ take 1 d12 ++ d3\n | otherwise = d0 ++ d1 ++ d2 ++ d3\n d0 = take 1 [\"0\" | \"0\" <- ds]\n d1 = take 1 [d | d <- ds, length d == 1, d /= \"0\"]\n d12 = [d | d <- ds, length d == 2] \n d2 = take 1 [d | d <- d12, d !! 1 == '0']\n d3 = take 1 [\"100\" | \"100\" <- ds]\n", "positive_code": [{"source_code": "main=interact$unlines.(map(unwords.map show)).f.map read.words\nf(_:xs)\n | null z && null zero && null y' = [[1],take 1(x++y)]\n | otherwise = [[length res],res]\n where\n res = zero ++ z ++ take 1 (x++y'') ++ take (fromEnum.not$null x&&(not$null y'')) y'\n zero = filter (0==)xs\n x = filter (\\x->09 [String]\ntakeFirst [] = []\ntakeFirst (x : xs) = [x]\n\ntransTo01 :: String -> String\ntransTo01 [] = []\ntransTo01 (x : xs) = (if x == '0' then '0' else '1') : (transTo01 xs)\n\nhandle :: [String] -> [[String]]\nhandle (_ : xs) = [[show $ length res], res]\n where\n res\n | null $ x1 ++ x10 = x0 ++ x11 ++ x100\n | otherwise = x0 ++ x1 ++ x10 ++ x100\n x0 = take 1 [x | x <- xs, transTo01 x == \"0\" ]\n x1 = take 1 [x | x <- xs, transTo01 x == \"1\" ]\n x10 = take 1 [x | x <- xs, transTo01 x == \"10\" ]\n x11 = take 1 [x | x <- xs, transTo01 x == \"11\" ]\n x100 = take 1 [x | x <- xs, transTo01 x == \"100\"]\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "transTo01 :: String -> String\ntransTo01 [] = []\ntransTo01 (x : xs) = (if x == '0' then '0' else '1') : (transTo01 xs)\n\nhandle :: [String] -> [[String]]\nhandle (_ : xs) = [[show $ length res], res]\n where\n res\n | null $ x1 ++ x10 = x0 ++ x11 ++ x100\n | otherwise = x0 ++ x1 ++ x10 ++ x100\n x0 = take 1 [x | x <- xs, transTo01 x == \"0\" ]\n x1 = take 1 [x | x <- xs, transTo01 x == \"1\" ]\n x10 = take 1 [x | x <- xs, transTo01 x == \"10\" ]\n x11 = take 1 [x | x <- xs, transTo01 x == \"11\" ]\n x100 = take 1 [x | x <- xs, transTo01 x == \"100\"]\n\nmain :: IO ()\nmain = interact $ unlines . map unwords . handle . words\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [Int]\nsolve as\n | null maybe1_9 && null maybe10_90 = concat [maybe0, maybe1_99, maybe100]\n | otherwise = concat [maybe0, maybe1_9, maybe10_90, maybe100]\n where\n maybe0 = take 1 $ filter (==0) as\n maybe100 = take 1 $ filter (== 100) as\n maybe1_9 = take 1 $ filter (\\x -> 1 <= x && x <= 9) as\n maybe10_90 = take 1 $ filter ((== 0) . flip mod 10) $ filter (\\x -> 1 <= x && x <= 99) as\n maybe1_99 = take 1 $ filter (/= 0) $ filter (/= 100) as\n\nprints :: Show a => [a] -> IO ()\nprints as = do\n print $ length as\n putStrLn $ intercalate \" \" $ map show as\n\nmain :: IO ()\nmain = getLine >> reads >>= prints . solve\n\n"}], "negative_code": [{"source_code": "main :: IO ()\nmain = interact $ unwords . solve . words\n\nsolve :: [String] -> [String]\nsolve (_ : ds)\n | null $ d1 ++ d2 = d0 ++ take 1 d12 ++ d3\n | otherwise = d0 ++ d1 ++ d2 ++ d3\n where\n d0 = take 1 [\"0\" | \"0\" <- ds]\n d1 = take 1 [d | d <- ds, length d == 1, d /= \"0\"]\n d12 = [d | d <- ds, length d == 2] \n d2 = take 1 [d | d <- d12, d !! 1 == '0']\n d3 = take 1 [\"100\" | \"100\" <- ds]\n"}, {"source_code": "main=interact$unlines.(map(unwords.map show)).f.map read.words\nf(_:xs)\n | null z && null zero && null y' = [[1],take 1(x++y)]\n | otherwise = [[length res],res]\n where\n res = zero ++ z ++ take 1 (x++y'') ++ take (fromEnum.not$null x&&(not$null y'')) y'\n zero = filter (0==)xs\n x = filter (<10)xs\n y = filter (\\x->9))\n\nisPal a = and $ zipWith (==) a a'\n where a' = reverse a\n\nchunk _ \"\" = []\nchunk k str = (take k str):chunk k rest\n where rest = drop k str\n\npred' line k | length line `mod` k /= 0 = False\npred' line k = all isPal $ chunk (length line `div` k) line\n\nmain = do\n line <- getLine\n k <- read <$> getLine\n putStrLn $ if pred' line k then \"Yes\" else \"No\"\n", "positive_code": [{"source_code": "main :: IO()\nmain = getContents >>= putStrLn . solve . lines\n\nsolve :: [String] -> String\nsolve [s, sk] = \n let len = length s\n k = read sk\n m = div len k\n in if (mod len k) == 0 && (solve' s m m \"\") then \"YES\" else \"NO\"\n where\n solve' :: String -> Int -> Int -> String -> Bool\n solve' \"\" m 0 sub = palin sub\n solve' (x:xs) m 0 sub = (palin sub) && (solve' xs m (m-1) [x])\n solve' (x:xs) m i sub = solve' xs m (i-1) (x:sub)\n \n palin :: String -> Bool\n palin s = s == (reverse s)\n "}, {"source_code": "-- http://codeforces.com/problemset/problem/547/A\n\nimport qualified Data.Set as Set\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n--------------------------------\n\nmain = do\n\n\ts <- getLine\n\tk <- fmap read $ getLine :: IO Int\n\n\tlet\n\t\tsublen = if (length s) `mod` k == 0 then (length s) `quot` k else 0\n\t\tresult = checkPalindromes sublen s\n\n\tcase result of\n\t\tTrue -> putStrLn \"YES\"\n\t\tFalse -> putStrLn \"NO\"\n\n--------------------------------\n\ncheckPalindromes :: Int -> String -> Bool\ncheckPalindromes 0 _ = False\ncheckPalindromes _ [] = True\ncheckPalindromes len str\n\t|\n\t\tlength substr == len &&\n\t\tsubstr == reverse substr = checkPalindromes len newstr\n\t|\n\t\totherwise = False\n\twhere\n\t\tsubstr = take len str\n\t\tnewstr = drop len str"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n k <- readLn\n\n let\n l = length s `div` k\n ss = unfoldr (\\s -> if null s then Nothing else Just $ splitAt l s) s\n check s = s == reverse s\n\n putStrLn $ if length s `mod` k == 0 && all check ss then \"YES\" else \"NO\"\n"}, {"source_code": "answer::String -> Int -> String\nanswer s k | ((length s) `rem` k) == 0 = handan s ((length s) `div` k)\n | otherwise = \"NO\" \nhandan::String -> Int -> String \nhandan [] k = \"YES\" \nhandan s k | isp (take k s) = handan (drop k s) k\n | otherwise = \"NO\"\nisp::String -> Bool \nisp s0 = s0 == reverse s0\nmain = do \n w <- getLine\n w0 <- getLine\n let k = read w0::Int\n putStrLn $ answer w k\n"}, {"source_code": "import Data.List\n\nis_pal :: String -> Bool\nis_pal \"\" = True\nis_pal (x:\"\") = True\nis_pal cs = head cs == last cs && is_pal (init. tail $ cs)\n \nfoo :: String -> Int -> [String]\nfoo \"\" _ = []\nfoo cs n = (take n cs) : (foo (drop n cs) n)\n \nmain :: IO ()\nmain = do\n s <- getLine\n n <- return . (read::String->Int) =<< getLine\n putStrLn $ if mod (length s) n == 0 && all is_pal (foo s (length s `div` n)) then \"YES\" else \"NO\"\n\n\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = putStrLn <$> yesno =<< solve <$> getLine <*> readLn\n\nsolve :: String -> Int -> Bool\nsolve s k = all palindrome (splitN (length s `div` k) s) && length s >= k && length s `mod` k == 0\n\npalindrome :: Eq a => [a] -> Bool\npalindrome xs = xs == reverse xs\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "main = do\n s <- getLine\n k <- getLine >>= return.read\n putStrLn $ if (solve s k) then \"YES\" else \"NO\"\n\nsolve :: String -> Int -> Bool\nsolve s k\n | (length s) `mod` k /= 0 = False\n | otherwise = sol s ((length s) `div` k)\n\nsol [] _ = True\nsol s k\n | pre == reverse pre = sol (drop k s) k\n | otherwise = False\n where pre = (take k s)\n"}, {"source_code": "main = do\n s <- getLine\n k <- fmap read getLine\n putStrLn $ if correct s k then \"YES\" else \"NO\"\n \ncorrect s k | l `mod` k /= 0 = False\n | otherwise = f s (l `div` k)\n where l = length s\n f [] _ = True\n f s' k' = let (a,b) = splitAt k' s'\n in isPalindrome a && f b k'\n \nisPalindrome s = s == reverse s\n"}, {"source_code": "import Data.Bits (shift, (.&.), Bits)\nimport Data.List (group, sort, transpose)\nimport Data.Char (ord)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM, liftM, join, mapM_)\n\nisPal a = foldr (&&) True $ zipWith (==) a $ reverse a\n\nchunk _ \"\" = []\nchunk k str = (take k str):chunk k rest\n where rest = drop k str\n\npred' line k | length line `mod` k /= 0 = False\npred' line k = all isPal $ chunk (length line `div` k) line\n\nmain = do\n line <- getLine\n k <- read <$> getLine\n putStrLn $ if pred' line k then \"Yes\" else \"No\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\npalindrome x = x== reverse x\n\n\nchunks n [] = []\nchunks n s = (take n s ): (chunks n (drop n s))\n \n\nmain= do\n\ts<- getLine\n\tn<- read <$> getLine ::IO Int\n\tlet les = length s\n\tlet k = div les n\n\tputStrLn $ if (k*n == les) && (all palindrome ( chunks k s)) then \"YES\" else \"NO\"\n\t"}, {"source_code": "import Data.List\n\nisPalindrome \"\" = False\nisPalindrome s = s == reverse s\n\nkPals 0 \"\" = True\nkPals 0 _ = False\nkPals n s = any (\\(h,t) -> isPalindrome h && (length h * (n-1)) == length t && kPals (n-1) t) (splits s)\n where splits s = zip (inits s) (tails s)\n\nmain = do\n s <- getLine\n n <- fmap read getLine\n putStr $ if kPals n s then \"YES\" else \"NO\""}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\n\npalindrome x = x== reverse x\n\n\nchunks n [] = []\nchunks n s = (take n s ): (chunks n (drop n s))\n \n\nmain= do\n\ts<- getLine\n\tn<- read <$> getLine ::IO Int\n\tlet k = div (length s ) n\n\tputStrLn $ if all palindrome $ chunks k s then \"YES\" else \"NO\"\n\t"}, {"source_code": "-- http://codeforces.com/problemset/problem/547/A\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n--------------------------------\n\nslice :: Int -> [a] -> [[a]]\nslice _ [] = []\nslice n xs = take n xs : slice n (drop n xs)\n\n--------------------------------\n\nmain = do\n\n\ts <- getLine\n\tk <- fmap read $ getLine :: IO Int\n\n\tlet\n\t\tsublen = (length s) `quot` k\n\t\tstrs = slice sublen s\n\t\tpalin_strs = map reverse strs\n\n\tcase strs == palin_strs of\n\t\tTrue -> putStrLn \"YES\"\n\t\tFalse -> putStrLn \"NO\"\n\n\treturn ()\n\n\n\n--------------------------------\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/547/A\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n--------------------------------\n\nslice :: Int -> [a] -> [[a]]\nslice _ [] = []\nslice 0 xs = []\nslice n xs = take n xs : slice n (drop n xs)\n\n--------------------------------\n\nallEqualLen :: [[a]] -> Bool\nallEqualLen [] = False\nallEqualLen (x:xs) = allEqualLen' (length x) xs\n\twhere\n\t\tallEqualLen' :: Int -> [[a]] -> Bool\n\t\tallEqualLen' _ [] = True\n\t\tallEqualLen' len (x:xs)\n\t\t\t| length x == len = allEqualLen' len xs\n\t\t\t| otherwise = False\n\n--------------------------------\n\nmain = do\n\n\ts <- getLine\n\tk <- fmap read $ getLine :: IO Int\n\n\tlet\n\t\tsublen = (length s) `quot` k\n\t\tstrs = slice sublen s\n\t\tpalin_strs = map reverse strs\n\n\tcase allEqualLen strs && strs == palin_strs of\n\t\tTrue -> putStrLn \"YES\"\n\t\tFalse -> putStrLn \"NO\"\n\n\treturn ()\n\n\n\n--------------------------------\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/547/A\n\nimport qualified Data.Set as Set\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n--------------------------------\n\nmain = do\n\n\ts <- getLine\n\tk <- fmap read $ getLine :: IO Int\n\n\tlet\n\t\tsublen = (length s) `quot` k\n\t\tresult = checkPalindromes sublen s\n\n\tcase result of\n\t\tTrue -> putStrLn \"YES\"\n\t\tFalse -> putStrLn \"NO\"\n\n--------------------------------\n\ncheckPalindromes :: Int -> String -> Bool\ncheckPalindromes 0 _ = False\ncheckPalindromes len str = checkPalindromes' Set.empty len str\n\twhere\n\t\tcheckPalindromes' :: Set.Set String -> Int -> String -> Bool\n\t\tcheckPalindromes' _ _ [] = True\n\t\tcheckPalindromes' set len str\n\t\t\t|\n\t\t\t\tsubstr `Set.notMember` set &&\n\t\t\t\tlength substr == len &&\n\t\t\t\tsubstr == reverse substr = checkPalindromes' (Set.insert substr set) len newstr\n\t\t\t|\n\t\t\t\totherwise = False\n\t\t\twhere\n\t\t\t\tsubstr = take len str\n\t\t\t\tnewstr = drop len str"}, {"source_code": "-- http://codeforces.com/problemset/problem/547/A\n\nimport qualified Data.Set as Set\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n--------------------------------\n\nmain = do\n\n\ts <- getLine\n\tk <- fmap read $ getLine :: IO Int\n\n\tlet\n\t\tsublen = (length s) `quot` k\n\t\tresult = checkPalindromes sublen s\n\n\tcase result of\n\t\tTrue -> putStrLn \"YES\"\n\t\tFalse -> putStrLn \"NO\"\n\n--------------------------------\n\ncheckPalindromes :: Int -> String -> Bool\ncheckPalindromes 0 _ = False\ncheckPalindromes _ [] = True\ncheckPalindromes len str\n\t|\n\t\tlength substr == len &&\n\t\tsubstr == reverse substr = checkPalindromes len newstr\n\t|\n\t\totherwise = False\n\twhere\n\t\tsubstr = take len str\n\t\tnewstr = drop len str"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n k <- readLn\n\n let\n l = length s `div` k\n ss = unfoldr (\\s -> if null s then Nothing else Just $ splitAt l s) s\n check s = s == reverse s\n\n putStrLn $ if all check ss then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = putStrLn <$> yesno =<< solve <$> getLine <*> readLn\n\nsolve :: String -> Int -> Bool\nsolve s k = all palindrome $ splitN (length s `div` k) s\n\npalindrome :: Eq a => [a] -> Bool\npalindrome xs = xs == reverse xs\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Arrow ((&&&))\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = putStrLn <$> yesno =<< solve <$> getLine <*> readLn\n\nsolve :: String -> Int -> Bool\nsolve s k = all (uncurry (&&) . ((==length s `div` k) . length &&& palindrome)) $ splitN (length s `div` k) s\n\npalindrome :: Eq a => [a] -> Bool\npalindrome xs = xs == reverse xs\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Data.List\n\nisPalindrome \"\" = False\nisPalindrome s = s == reverse s\n\nkPals 0 _ = True\nkPals n s = any (\\(h,t) -> isPalindrome h && kPals (n-1) t) (splits s)\n where splits s = zip (inits s) (tails s)\n\nmain = do\n s <- getLine\n n <- fmap read getLine\n putStr $ if kPals n s then \"YES\" else \"NO\""}], "src_uid": "43bb8fec6b0636d88ce30f23b61be39f"} {"source_code": "import Data.Either\n\nprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]\n\nmain = getLine >>= test . read\n\ntest 0 = return ()\ntest t = do\n getLine\n as <- map read . words <$> getLine\n let sol = rights $ f 1 (Left <$> as) primes\n print $ maximum sol\n putStrLn $ unwords $ show <$> sol\n test $ pred t\n\nf _ as [] = as\nf c as (p:ps)\n | any ((== 0).(`mod` p)) $ lefts as = f (succ c) (recolor c p <$> as) ps\n | otherwise = f c as ps\n\nrecolor c p = either (\\a -> if a `mod` p == 0 then Right c else Left a) Right\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n putStrLn $ tidy $ solve xs\n\nprimes :: [(Int,Int)]\nprimes =zip [2,3,5,7,11,13,17,19,23,29,31] [1..]\n\nsolve :: [Int] -> [Int]\nsolve xs = map f xs\n where\n f x = snd $ head $ filter (\\(p,_) -> x `mod` p == 0) primes\n\ntidy :: [Int] -> String\ntidy cs = (show m) ++ \"\\n\" ++ (unwords.map show) newcs\n where\n nubbed = zip (nub cs) [(1::Int)..]\n f = fromJust . ((flip lookup) nubbed)\n newcs = map f cs\n m = length nubbed\n"}], "negative_code": [], "src_uid": "c3cd949c99e96c9da186a34d49bd6197"} {"source_code": "-- import Debug.Trace\n\ndata Rebus = Rebus {\n expression :: [Char]\n , rebusN :: Int\n}\n\ncountPlus :: [Char] -> Int\ncountPlus e = 1 + countChar '+' e\n\ncountMinus :: [Char] -> Int\ncountMinus e = countChar '-' e\n\ncountChar :: Char -> [Char] -> Int\ncountChar c = length . filter (==c)\n\nmakeRange :: Int -> Int -> (Int, Int)\n-- Range of the sum of m integers in [1, n]\nmakeRange m n = (m, m * n)\n\nnegateRange (a, b) = (-b, -a)\nplusRange (a1, b1) (a2, b2) = (a1 + a2, b1 + b2)\n\ninRange n (a, b) = a <= n && n <= b\n\nconstructNums [] n sumPlus sumMinus nPlus nMinus = []\nconstructNums (x:xs) n sumPlus sumMinus nPlus nMinus = let\n numPlus = min n (sumPlus - (nPlus - 1))\n numMinus = min n (sumMinus - (nMinus - 1))\n in if x == '+'\n then numPlus : constructNums xs n (sumPlus - numPlus) sumMinus (nPlus - 1) nMinus\n else numMinus : constructNums xs n sumPlus (sumMinus - numMinus) nPlus (nMinus - 1)\n\nrebusFromString :: String -> Rebus\nrebusFromString s = let\n s' = filter (/=' ') s\n (exp, n) = splitAt (length . takeWhile (/='=') $ s') s'\n n' = read $ tail n :: Int\n in Rebus exp n'\n\nfillExpression :: [Char] -> [Int] -> String\nfillExpression exp nums = unwords $ combine exp nums where\n combine (x:xs) (y:ys) \n | x == '?' = show y : combine xs ys\n | otherwise = [x] : combine xs (y:ys)\n combine xs _ = map (:[]) xs\n\nshowRebus (Rebus exp n) nums = fillExpression exp nums ++ \" = \" ++ show n\n\nsolve :: String -> Maybe String\nsolve s = let\n rebus@(Rebus exp n) = rebusFromString s\n c1 = countPlus exp\n c2 = countMinus exp\n rangePlus@(a1, b1) = makeRange c1 n\n rangeMinus@(a2, b2) = makeRange c2 n\n range = plusRange rangePlus (negateRange rangeMinus)\n sumMinus = max (a1 - n) a2\n sumPlus = sumMinus + n\n nums = constructNums ('+':filter (/='?') exp) n sumPlus sumMinus c1 c2\n result = showRebus rebus nums\n in if inRange n range then Just result else Nothing\n\nmain = do\n s <- getLine\n putStrLn $ case solve s of\n Nothing -> \"Impossible\"\n Just eq -> \"Possible\\n\" ++ eq\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe\n\ndata Equation = Equation {\n expression :: [Term]\n , equationResult :: Int\n}\n\ninstance Show Equation where\n show (Equation exp n) = unwords $ (tail . concatMap showTerm $ exp) ++ [\"=\", show n]\n where\n showTerm (Term sign (Just value)) = [[sign], show value]\n showTerm (Term sign _) = [[sign], \"?\"]\n\ntype Sign = Char\n\ndata Term = Term {\n termSign :: Sign\n , termValue :: Maybe Int\n}\n\ncountSign :: Sign -> [Term] -> Int\ncountSign sign = length . filter ((==sign) . termSign)\n\nsolve :: String -> Maybe String\nsolve s = let\n eq@(Equation exp n) = equationFromString s\n c1 = countSign '+' exp\n c2 = countSign '-' exp\n inRange = c1 - n * c2 <= n && n <= n * c1 - c2\n sum2 = max (c1 - n) c2\n sum1 = n + sum2\n exp' = fillExpression n sum1 sum2 c1 c2 exp\n in if inRange then Just (show (Equation exp' n)) else Nothing\n\nfillExpression :: Int -> Int -> Int -> Int -> Int -> [Term] -> [Term]\nfillExpression n sum1 sum2 c1 c2 exp = case exp of\n [] -> []\n ((Term '+' _):ts) -> Term '+' (Just x1) : fillExpression n (sum1 - x1) sum2 (c1 - 1) c2 ts\n ((Term '-' _):ts) -> Term '-' (Just x2) : fillExpression n sum1 (sum2 - x2) c1 (c2 - 1) ts\n where\n x1 = min n (sum1 - (c1 - 1))\n x2 = min n (sum2 - (c2 - 1))\n\nequationFromString :: String -> Equation\nequationFromString s = let\n (sL, (_:sR)) = splitAt (fromJust $ elemIndex '=' s) s\n signs = ('+':) . catMaybes . map f $ sL\n exp = map (flip Term Nothing) signs\n n = read sR :: Int\n f c = case c of\n '+' -> Just '+'\n '-' -> Just '-'\n _ -> Nothing\n in Equation exp n\n\nmain = do\n s <- getLine\n putStrLn $ case solve s of\n Nothing -> \"Impossible\"\n Just eq -> \"Possible\\n\" ++ eq\n"}, {"source_code": "import Data.List\nmain = do\n s <- getLine\n let signs = filter (\\c -> c == '+' || c == '-') s\n n = read . drop 1 . dropWhile (/= '=') $ s\n npos = 1 + length (elemIndices '+' signs)\n nneg = length (elemIndices '-' signs)\n\n cand = if nneg == 0\n then [[solve npos n, []]]\n else [[replicate npos 1, solve nneg (npos-n)],\n [solve npos (n+nneg), replicate nneg 1]]\n\n res = filter (all (all (\\x -> x >= 1 && x <= n))) cand\n [(p:pos), neg] = head res\n\n pairs = merge signs pos neg\n\n rest = concatMap (\\(c, m) -> \" \" ++ [c] ++ \" \" ++ show m) pairs\n\n\n if null res\n then putStrLn \"Impossible\"\n else do\n putStrLn \"Possible\"\n putStrLn $ show p ++ rest ++ \" = \" ++ show n\n\n\nmerge :: String -> [Int] -> [Int] -> [(Char, Int)]\nmerge [] _ _ = []\nmerge ('+':srest) (p:prest) neg = ('+',p) : merge srest prest neg\nmerge ('-':srest) pos (n:nrest) = ('-',n) : merge srest pos nrest\nmerge _ _ _ = error \"Unexpected data in merge\"\n\nsolve :: Int -> Int -> [Int]\nsolve n sum = map (+1) $ replicate (n - s `mod` n) (s `div` n) ++ replicate (s `mod` n) ((s + n-1) `div` n)\n where s = sum - n\n\n"}], "negative_code": [{"source_code": "-- import Debug.Trace\n\ndata Rebus = Rebus {\n expression :: [Char]\n , rebusN :: Int\n}\n\ncountPlus :: [Char] -> Int\ncountPlus e = 1 + countChar '+' e\n\ncountMinus :: [Char] -> Int\ncountMinus e = countChar '-' e\n\ncountChar :: Char -> [Char] -> Int\ncountChar c = length . filter (==c)\n\nmakeRange :: Int -> Int -> (Int, Int)\n-- Range of the sum of m integers in [1, n]\nmakeRange m n = (m, m * n)\n\nnegateRange (a, b) = (-b, -a)\nplusRange (a1, b1) (a2, b2) = (a1 + a2, b1 + b2)\n\ninRange n (a, b) = a <= n && n <= b\n\nconstructNums [] n sumPlus sumMinus nPlus nMinus = []\nconstructNums (x:xs) n sumPlus sumMinus nPlus nMinus = let\n numPlus = min n (sumPlus - (nPlus - 1))\n numMinus = min n (sumMinus - (nMinus - 1))\n in if x == '+'\n then numPlus : constructNums xs n (sumPlus - numPlus) sumMinus (nPlus - 1) nMinus\n else numMinus : constructNums xs n sumPlus (sumMinus - numPlus) nPlus (nMinus - 1)\n\nrebusFromString :: String -> Rebus\nrebusFromString s = let\n s' = filter (/=' ') s\n (exp, n) = splitAt (length . takeWhile (/='=') $ s') s'\n n' = read $ tail n :: Int\n in Rebus exp n'\n\nfillExpression :: [Char] -> [Int] -> String\nfillExpression exp nums = unwords $ combine exp nums where\n combine (x:xs) (y:ys) \n | x == '?' = show y : combine xs ys\n | otherwise = [x] : combine xs (y:ys)\n combine xs _ = map (:[]) xs\n\nshowRebus (Rebus exp n) nums = fillExpression exp nums ++ \" = \" ++ show n\n\nsolve :: String -> Maybe String\nsolve s = let\n rebus@(Rebus exp n) = rebusFromString s\n c1 = countPlus exp\n c2 = countMinus exp\n rangePlus@(a1, b1) = makeRange c1 n\n rangeMinus@(a2, b2) = makeRange c2 n\n range = plusRange rangePlus (negateRange rangeMinus)\n sumMinus = max (a1 - n) a2\n sumPlus = sumMinus + n\n nums = constructNums ('+':filter (/='?') exp) n sumPlus sumMinus c1 c2\n result = showRebus rebus nums\n in if inRange n range then Just result else Nothing\n\nmain = do\n s <- getLine\n putStrLn $ case solve s of\n Nothing -> \"Impossible\"\n Just eq -> \"Possible\\n\" ++ eq\n"}, {"source_code": "data Rebus = Rebus {\n expression :: [Char]\n , rebusN :: Int\n}\n\ncountPlus :: [Char] -> Int\ncountPlus e = 1 + countChar '+' e\n\ncountMinus :: [Char] -> Int\ncountMinus e = countChar '-' e\n\ncountChar :: Char -> [Char] -> Int\ncountChar c = length . filter (==c)\n\nmakeRange :: Int -> Int -> (Int, Int)\n-- Range of the sum of m integers in [1, n]\nmakeRange m n = (m, m * n)\n\nnegateRange (a, b) = (-a, -b)\nplusRange (a1, b1) (a2, b2) = (a1 + a2, b1 + b2)\n\ninRange n (a, b) = a <= n && n <= b\n\nconstructNums [] n sumPlus sumMinus nPlus nMinus = []\nconstructNums (x:xs) n sumPlus sumMinus nPlus nMinus = let\n numPlus = min n (sumPlus - (nPlus - 1))\n numMinus = min n (sumMinus - (nMinus - 1))\n in if x == '+'\n then numPlus : constructNums xs n (sumPlus - numPlus) sumMinus (nPlus - 1) nMinus\n else numMinus : constructNums xs n sumPlus (sumMinus - numPlus) nPlus (nMinus - 1)\n\nrebusFromString :: String -> Rebus\nrebusFromString s = let\n s' = filter (/=' ') s\n (exp, n) = splitAt (length . takeWhile (/='=') $ s') s'\n n' = read $ tail n :: Int\n in Rebus exp n'\n\nfillExpression :: [Char] -> [Int] -> String\nfillExpression exp nums = unwords $ combine exp nums where\n combine (x:xs) (y:ys) \n | x == '?' = show y : combine xs ys\n | otherwise = [x] : combine xs (y:ys)\n combine xs _ = map (:[]) xs\n\nshowRebus (Rebus exp n) nums = fillExpression exp nums ++ \" = \" ++ show n\n\nsolve :: String -> Maybe String\nsolve s = let\n rebus@(Rebus exp n) = rebusFromString s\n c1 = countPlus exp\n c2 = countMinus exp\n rangePlus@(a1, b1) = makeRange c1 n\n rangeMinus@(a2, b2) = makeRange c2 n\n range = plusRange rangePlus (negateRange rangeMinus)\n sumMinus = max (a1 - n) a2\n sumPlus = sumMinus + n\n nums = constructNums ('+':filter (/='?') exp) n sumPlus sumMinus c1 c2\n result = showRebus rebus nums\n in if inRange n range then Just result else Nothing\n\nmain = do\n s <- getLine\n putStrLn $ case solve s of\n Nothing -> \"Impossible\"\n Just eq -> \"Possible\\n\" ++ eq\n"}], "src_uid": "35a97c47182916aaafe4c6e4b69bc79f"} {"source_code": "import Data.Array.Unboxed\nimport Control.Monad( replicateM)\nmain = do\n let readLine = return . map read . words =<< getLine\n [_n,_m] <- readLine\n _as <- readLine\n let readPair = do\n\t [l,r] <- return . map (read::String->Int) . words =<< getLine\n\t return (l,r)\n bounds <- replicateM _m readPair\n let _arr = listArray (1,_n) _as::UArray Int Int\n\thappineses = map f bounds\n\t where f (l,r) = let v = sum $ map (_arr!) [l..r]\n\t\t\t in if v>0 then v else 0\n print $ sum happineses\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, m ] <- readInts\n\tas <- readInts\n\tsegments <- replicateM m $ do\n\t\tlr <- readInts\n\t\treturn $ mp lr\n\tlet\n\t\tsublists = map ( $ as ) $ map sublist segments\n\tprint $ sum $ filter ( >= 0 ) $ map sum sublists\n\nsublist ( l, r ) = take ( r - l + 1 ) . drop ( l - 1 )\n"}, {"source_code": "module Main (main) where\n\nimport Control.Monad\nimport Data.List\n\ngetm :: [Int] -> Int -> Int -> IO Int\ngetm nl acc _ = do\n lr <- getLine\n let l:r:_ = map read $ words lr :: [Int]\n let t = sum (drop (l-1) $ take r nl)\n return $ if t < 0\n then acc\n else acc + t\n \nmain :: IO ()\nmain = do\n dum <- getLine\n let n:m:_ = map read $ words dum :: [Int]\n nl <- getLine\n let an = map read $ words nl :: [Int]\n g <- foldM (getm an) 0 [1..m]\n print g\n\n"}, {"source_code": "import Data.Array\nmain = interact $ show . solve . map (map read . words) . lines\n\nsolve ([n,_]:(f:ns):qs) = sum $ map (max 0 . query) qs\n where sa = array (1, n) $ (1,f) : [(i, v + (sa ! (i - 1))) | (i,v) <- [2..] `zip` ns]\n query [l, r] = (sa ! r) - sum [sa ! (l-1) | l > 1]"}], "negative_code": [], "src_uid": "6d7364048428c70e0e9b76ab1eb8cc34"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words)\nimport qualified Data.Maybe as M (fromJust)\nimport qualified Data.List as L (sortBy, intercalate)\n\nreadInt = fst . M.fromJust . C.readInt\n\ncmp (a, b, i) (c, d, j) = compare c a\ntk (_, _, i) = i\n\nrun ((_, b, i):(_, d, j):cs) ans | b >= d = run cs (i:ans) | otherwise = run cs (j:ans)\nrun [] ans = ans\n\nmain = do\n (readInt -> n) <- B.getLine\n (map readInt . C.words -> as) <- B.getLine\n (map readInt . C.words -> bs) <- B.getLine\n let cs = L.sortBy cmp (zip3 as bs [1..])\n ans | even n = tk (head cs):tk (cs !! 1):run (drop 2 cs) []\n | odd n = tk (head cs):run (tail cs) []\n putStrLn $ show $ length ans\n putStrLn $ L.intercalate \" \" (map show ans)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (sortBy)\nimport Data.Ord\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nsolution::(Ord a, Ord b)=>[a]->[b]->[Int]\nsolution as bs = let ((_, x):xs) = sortBy cmpA $ as `zip` bs `zip` [1..]\n cmpA = comparing $ Down .fst .fst\n res = x: go xs\n go (((_, b1), i1): ((_, b2), i2): rest )\n | b1 > b2 = i1 : go rest\n | otherwise = i2 : go rest\n go [(_, i)] = [i]\n go [] = []\n in res\n\nmain = do\n void getLine\n sol <- solution <$> getInts <*> getInts\n print $ length sol\n putStrLn $ unwords $ show <$> sol\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (sortBy)\nimport Data.Ord\n\ngetInts::IO [Int]\ngetInts = go <$> BS.getLine where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')\n\nsolution::(Ord a, Ord b)=>[a]->[b]->[Int]\nsolution as bs = let ((_, x):xs) = sortBy cmpA $ as `zip` bs `zip` [1..]\n cmpA = comparing $ Down .fst .fst\n res = x: go xs\n go (((_, b1), i1): ((_, b2), i2): rest )\n | b1 > b2 = i1 : go rest\n | otherwise = i2 : go rest\n go _ = []\n in res\n\nmain = do\n void getLine\n sol <- solution <$> getInts <*> getInts\n print $ length sol\n putStrLn $ unwords $ show <$> sol\n"}], "src_uid": "d6d2c95396c299235f3302557cc3a2ed"} {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n -- mirrorOf 'i' 'i' = True --questionable\n -- mirrorOf 'J' 'L' = True -- questionable\n -- mirrorOf 'l' 'l' = True -- questionable\n mirrorOf 'M' 'M' = True\n -- mirrorOf 'n' 'n' = True -- questionable\n -- mirrorOf 'm' 'm' = True -- questionable\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'p' 'q' = True\n mirrorOf 'q' 'p' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n -- mirrorOf 'u' 'u' = True -- questionable\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n", "positive_code": [{"source_code": "-- ID: 691B (s-palindrome)\n-- URL: http://codeforces.com/problemset/problem/691/B\n\nimport Data.List\n\npairs = [\n ('A','A'), ('b','d'), ('d','b'), ('H','H'), ('I','I'),\n ('M','M'),\n ('O','O'), ('o','o'), ('p','q'), ('q','p'), ('T','T'),\n ('U','U'), ('V','V'), ('v','v'), ('W','W'),\n ('w','w'), ('X','X'), ('x','x'), ('Y','Y')\n ]\n\nmirror [] = []\nmirror (x:xs) = case lookup x pairs of\n Nothing -> '?' : mirror xs\n Just y -> y : mirror xs\n\npalindrome str = mirror left == reverse right where\n n = length str\n m = n `div` 2\n left = if odd n then take (m+1) str else take m str\n right = drop m str\n\nmain = do\n str <- getLine\n if palindrome str\n then putStrLn \"TAK\"\n else putStrLn \"NIE\""}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\ts <- getLine \n\tputStrLn $ which \"TAK\" \"NIE\" $ and $ zipWith f s $ reverse s\n\nf a b\n\t| a == b = a `elem` \"AHIMOoTUVvWwXxY\"\n\t| otherwise = syn a b\n\t\twhere\n\t\t\tsyn 'b' 'd' = True\n\t\t\tsyn 'd' 'b' = True\n\t\t\tsyn 'p' 'q' = True\n\t\t\tsyn 'q' 'p' = True\n\t\t\tsyn _ _ = False\n"}, {"source_code": "main = interact $ solve . head . words\nsolve s\n | s == (reverse $ map ch s) = \"TAK\"\n | otherwise = \"NIE\"\n\nch 'p' = 'q'\nch 'q' = 'p'\nch 'b' = 'd'\nch 'd' = 'b'\nch 'o' = 'o'\nch 'A' = 'A'\nch 'H' = 'H'\nch 'I' = 'I'\nch 'M' = 'M'\nch 'O' = 'O'\nch 'T' = 'T'\nch 'U' = 'U'\nch 'V' = 'V'\nch 'W' = 'W'\nch 'X' = 'X'\nch 'Y' = 'Y'\nch 'v' = 'v'\nch 'w' = 'w'\nch 'x' = 'x'\nch l = toEnum $ (fromEnum l) + 40"}], "negative_code": [{"source_code": "-- ID: 691B (s-palindrome)\n-- URL: http://codeforces.com/problemset/problem/691/B\n\nimport Data.List\n\npairs = [\n ('A','A'), ('b','d'), ('d','b'), ('H','H'), ('I','I'),\n ('M','M'), ('m','m'), ('n','n'),\n ('O','O'), ('o','o'), ('p','q'), ('q','p'), ('T','T'),\n ('U','U'), ('u','u'), ('V','V'), ('v','v'), ('W','W'),\n ('w','w'), ('X','X'), ('x','x'), ('Y','Y'), ('Z','Z'),\n ('z','z')]\n\nmirror [] = []\nmirror (x:xs) = case lookup x pairs of\n Nothing -> '?' : mirror xs\n Just y -> y : mirror xs\n\npalindrome str = mirror left == reverse right where\n n = length str\n m = n `div` 2\n left = if odd n then take (m+1) str else take m str\n right = drop m str\n\nmain = do\n str <- getLine\n if palindrome str\n then putStrLn \"TAK\"\n else putStrLn \"NIE\""}, {"source_code": "-- ID: 691B (s-palindrome)\n-- URL: http://codeforces.com/problemset/problem/691/B\n\nimport Data.List\n\npairs = [\n ('A','A'), ('b','d'), ('d','b'), ('H','H'), ('I','I'),\n ('i','i'), ('l','l'), ('M','M'), ('m','m'), ('n','n'),\n ('O','O'), ('o','o'), ('p','q'), ('q','p'), ('T','T'),\n ('U','U'), ('u','u'), ('V','V'), ('v','v'), ('W','W'),\n ('w','w'), ('X','X'), ('x','x'), ('Y','Y'), ('Z','Z'),\n ('z','z')]\n\nmirror [] = []\nmirror (x:xs) = case lookup x pairs of\n Nothing -> '?' : mirror xs\n Just y -> y : mirror xs\n\npalindrome str = mirror left == right where\n n = length str\n m = n `div` 2\n left = take m str\n right = if odd n then drop (m+1) str else drop m str\n\nmain = do\n str <- getLine\n if palindrome str\n then putStrLn \"TAK\"\n else putStrLn \"NIE\""}, {"source_code": "-- ID: 691B (s-palindrome)\n-- URL: http://codeforces.com/problemset/problem/691/B\n\nimport Data.List\n\npairs = [\n ('A','A'), ('b','d'), ('d','b'), ('H','H'), ('I','I'),\n ('i','i'), ('l','l'), ('M','M'), ('m','m'), ('n','n'),\n ('O','O'), ('o','o'), ('p','q'), ('q','p'), ('T','T'),\n ('U','U'), ('u','u'), ('V','V'), ('v','v'), ('W','W'),\n ('w','w'), ('X','X'), ('x','x'), ('Y','Y'), ('Z','Z'),\n ('z','z')]\n\nmirror [] = []\nmirror (x:xs) = case lookup x pairs of\n Nothing -> '?' : mirror xs\n Just y -> y : mirror xs\n\npalindrome [x] = mirror [x] == [x]\npalindrome str = mirror left == right where\n n = length str\n m = n `div` 2\n left = take m str\n right = if odd n then drop (m+1) str else drop m str\n\nmain = do\n str <- getLine\n if palindrome str\n then putStrLn \"TAK\"\n else putStrLn \"NIE\""}, {"source_code": "-- ID: 691B (s-palindrome)\n-- URL: http://codeforces.com/problemset/problem/691/B\n\nimport Data.List\n\npairs = [\n ('A','A'), ('b','d'), ('d','b'), ('H','H'), ('I','I'),\n ('i','i'), ('l','l'), ('M','M'), ('m','m'), ('n','n'),\n ('O','O'), ('o','o'), ('p','q'), ('q','p'), ('T','T'),\n ('U','U'), ('u','u'), ('V','V'), ('v','v'), ('W','W'),\n ('w','w'), ('X','X'), ('x','x'), ('Y','Y'), ('Z','Z'),\n ('z','z')]\n\nmirror [] = []\nmirror (x:xs) = case lookup x pairs of\n Nothing -> '?' : mirror xs\n Just y -> y : mirror xs\n\npalindrome str = mirror left == reverse right where\n n = length str\n m = n `div` 2\n left = if odd n then take (m+1) str else take m str\n right = drop m str\n\nmain = do\n str <- getLine\n if palindrome str\n then putStrLn \"TAK\"\n else putStrLn \"NIE\""}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n mirrorOf 'J' 'L' = True -- questionable\n mirrorOf 'L' 'J' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n -- mirrorOf 'J' 'L' = True -- questionable\n -- mirrorOf 'l' 'l' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'p' 'q' = True\n mirrorOf 'q' 'p' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n -- mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n -- mirrorOf 'J' 'L' = True -- questionable\n -- mirrorOf 'L' 'J' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n -- mirrorOf 'J' 'L' = True -- questionable\n -- mirrorOf 'L' 'J' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n -- mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n -- mirrorOf 'J' 'L' = True -- questionable\n -- mirrorOf 'l' 'l' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'p' 'q' = True\n mirrorOf 'q' 'p' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n mirrorOf 'J' 'L' = True -- questionable\n mirrorOf 'l' 'l' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'n' 'n' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'p' 'q' = True\n mirrorOf 'q' 'p' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n mirrorOf 'u' 'u' = True -- questionable\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n mirrorOf 'J' 'L' = True -- questionable\n mirrorOf 'l' 'l' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'p' 'q' = True\n mirrorOf 'q' 'p' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'd' 'b' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n -- mirrorOf 'i' 'i' = True --questionable\n -- mirrorOf 'J' 'L' = True -- questionable\n -- mirrorOf 'l' 'l' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'n' 'n' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'p' 'q' = True\n mirrorOf 'q' 'p' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n -- mirrorOf 'u' 'u' = True -- questionable\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n mirrorOf :: Char -> Char -> Bool\n mirrorOf 'A' 'A' = True\n mirrorOf 'b' 'd' = True\n mirrorOf 'H' 'H' = True\n mirrorOf 'I' 'I' = True\n mirrorOf 'i' 'i' = True\n mirrorOf 'J' 'L' = True -- questionable\n mirrorOf 'M' 'M' = True\n mirrorOf 'm' 'm' = True\n mirrorOf 'O' 'O' = True\n mirrorOf 'o' 'o' = True\n mirrorOf 'T' 'T' = True\n mirrorOf 'U' 'U' = True\n mirrorOf 'u' 'u' = True\n mirrorOf 'V' 'V' = True\n mirrorOf 'v' 'v' = True\n mirrorOf 'W' 'W' = True\n mirrorOf 'w' 'w' = True\n mirrorOf 'X' 'X' = True\n mirrorOf 'x' 'x' = True\n mirrorOf 'Y' 'Y' = True\n mirrorOf _ _ = False\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n solve :: String -> Bool\n solve xs =\n let ys = reverse xs\n xys = zip xs ys\n mof = (\\(x,y) -> x `mirrorOf` y)\n in all mof xys\n\n\n main :: IO()\n main = do\n xs <- getLine >>= return . filter (/='\\n')\n let result = case solve xs of\n True -> \"TAK\"\n False -> \"NIE\"\n putStrLn result\n"}, {"source_code": "main = interact solve\nsolve s\n | s == (reverse $ map ch s) = \"TAK\"\n | otherwise = \"NIE\"\n\nch 'p' = 'q'\nch 'q' = 'p'\nch 'b' = 'd'\nch 'd' = 'b'\nch 'o' = 'o'\nch 'A' = 'A'\nch 'O' = 'O'\nch 'H' = 'H'\nch 'M' = 'M'\nch 'I' = 'I'\nch 'T' = 'T'\nch 'U' = 'U'\nch 'V' = 'V'\nch 'W' = 'W'\nch 'X' = 'X'\nch 'Y' = 'Y'\nch 'v' = 'v'\nch 'w' = 'w'\nch l = toEnum $ (fromEnum l) + 40"}], "src_uid": "bec2349631158b7dbfedcaededf65cc2"} {"source_code": "import Data.List\nimport Data.Char\n\nmode::String->String\nmode a = show ( read a :: Int )\n\ncannot::String->Bool\ncannot a = (mode a /= a) || ( read a>255 )\n\ngao::String->(Int,Int,Int,Int)->[String]\ngao a (x1,x2,x3,x4) = if(x1+x2+x3+x4/=length a) then []\n\t\t\t\t\t else if(cannot a1 || cannot a2 || cannot a3 || cannot a4)then []\n\t\t\t\t\t else [a1 ++ \".\" ++ a2 ++ \".\" ++ a3 ++ \".\" ++ a4]\n\twhere (a1,tmp1)=splitAt x1 a\n\t (a2,tmp2)=splitAt x2 tmp1\n\t (a3,a4)=splitAt x3 tmp2\n\ncheck1::String->[String]\ncheck1 a=foldl (\\ans p -> gao a p ++ ans) [] [(x1,x2,x3,x4) | x1<-p,x2<-p,x3<-p,x4<-p]\n\twhere p=[1,2,3]\n\ncheck::String->String->[String]\ncheck d a= if(ok==length d)\n\t\t then ( check1 $ a ++ ( reverse a ) ) ++ ( check1 $ a ++ ( tail (reverse a) ) )\n\t\t else []\n\twhere ok=sum [ ( if (x `elem` a) then 1 else 0 ) | x<-d ]\n\ndfs::[Char]->String->Int->[String]\ndfs _ _ 0 = []\ndfs d a n = foldl (\\t di -> check d (di:a) ++ ( dfs d (di:a) (n-1) ) ++ t) [] d\n\nmain :: IO()\nmain = do\n\tinput <- getContents\n\tlet\n\t\t(n:a) = map read ( words input )::[Int]\n\t\tans=if n>6 then []\n\t\t else dfs ( map ((!!0).show) a ) [] 6\n\tprint $ length ans\n\tmapM_ putStrLn ans \n", "positive_code": [{"source_code": "\nimport Data.List\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n (n:an) = map read (words input)::[Int]\n if n>6\n then print (0::Int)\n else\n let\n string = [filter (\\t->((length $ group $ sort t)==n)) [[x,y,z,u,v,w],[x,y,z,u,v],[x,y,z,u],[x,y,z],[x,y]] |x<-an,y<-an,z<-an,u<-an,v<-an,w<-an]\n \n getAns::[[[Int]]]->[(Int,Int,Int,Int)]->[(Int,Int,Int,Int)]\n getAns [] ans = ans\n getAns (x:xs) ans =\n getAns xs (getAns' x ans)\n \n getAns'::[[Int]]->[(Int,Int,Int,Int)]->[(Int,Int,Int,Int)]\n getAns' [] ans = ans\n getAns' (x:xs) ans =\n getAns' xs (getAns'' (x++(reverse x)) (getAns'' (x++(tail $ reverse x)) ans))\n \n getAns''::[Int]->[(Int,Int,Int,Int)]->[(Int,Int,Int,Int)] \n getAns'' x ans =\n [get i j k|i<-[1..l-1],j<-[i+1..l-1],k<-[j+1..l-1],0+1==i||(x!!0)/=0,i+1==j||(x!!i)/=0,j+1==k||(x!!j)/=0,k+1==l||(x!!k)/=0,check i j k]++ans\n where\n l=length x\n get i j k =\n (a,b,c,d)\n where\n a = func (take i x) 0\n b = func (drop i (take j x)) 0\n c = func (drop j (take k x)) 0\n d = func (drop k x) 0\n func [] t = t\n func (y:ys) t = func ys (t*10+y)\n check i j k =\n a<256&&b<256&&c<256&&d<256\n where\n a = func (take i x) 0\n b = func (drop i (take j x)) 0\n c = func (drop j (take k x)) 0\n d = func (drop k x) 0\n func [] t = t\n func (y:ys) t = func ys (t*10+y)\n _ans = map head (group $ sort $ getAns string [])\n printAll::[(Int,Int,Int,Int)]->IO()\n printAll [] = return ()\n printAll ((a,b,c,d):xs) =\n do\n putStr $ show a\n putStr \".\"\n putStr $ show b\n putStr \".\"\n putStr $ show c\n putStr \".\"\n putStr $ show d\n putStr \"\\n\"\n printAll xs\n in\n do\n print $ length _ans\n printAll _ans\n "}, {"source_code": "import Data.List\nimport Data.Char\n\nmode::String->String\nmode a = show ( read a :: Int )\n\ncannot::String->Bool\ncannot a = (mode a /= a) || ( read a>255 )\n\ngao::String->(Int,Int,Int,Int)->[String]\ngao a (x1,x2,x3,x4) = if(x1+x2+x3+x4/=length a) then []\n\t\t\t\t\t else if(cannot a1 || cannot a2 || cannot a3 || cannot a4)then []\n\t\t\t\t\t else [a1 ++ \".\" ++ a2 ++ \".\" ++ a3 ++ \".\" ++ a4]\n\twhere (a1,tmp1)=splitAt x1 a\n\t (a2,tmp2)=splitAt x2 tmp1\n\t (a3,a4)=splitAt x3 tmp2\n\ncheck1::String->[String]\ncheck1 a=foldl (\\ans p -> gao a p ++ ans) [] [(x1,x2,x3,x4) | x1<-p,x2<-p,x3<-p,x4<-p]\n\twhere p=[1,2,3]\n\ncheck::String->String->[String]\ncheck d a= if(ok==length d)\n\t\t then ( check1 $ a ++ ( reverse a ) ) ++ ( check1 $ a ++ ( tail (reverse a) ) )\n\t\t else []\n\twhere ok=sum [ ( if (x `elem` a) then 1 else 0 ) | x<-d ]\n\ndfs::[Char]->String->Int->[String]\ndfs _ _ 0 = []\ndfs d a n = foldl (\\t di -> check d (di:a) ++ ( dfs d (di:a) (n-1) ) ++ t) [] d\n\nmain :: IO()\nmain = do\n\tinput <- getContents\n\tlet\n\t\t(n:a) = map read ( words input )::[Int]\n\t\tans=if n>6 then []\n\t\t else dfs ( map ((!!0).show) a ) [] 6\n\tprint $ length ans\n\tmapM_ putStrLn ans \n"}], "negative_code": [{"source_code": "\nimport Data.List\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n (n:an) = map read (words input)::[Int]\n if n>6\n then print (0::Int)\n else\n let\n string = [filter (\\t->((length $ group $ sort t)==n)) [[x,y,z,u,v,w],[x,y,z,u,v],[x,y,z,u],[x,y,z],[x,y]] |x<-an,y<-an,z<-an,u<-an,v<-an,w<-an]\n \n getAns::[[[Int]]]->[(Int,Int,Int,Int)]->[(Int,Int,Int,Int)]\n getAns [] ans = ans\n getAns (x:xs) ans =\n getAns xs (getAns' x ans)\n \n getAns'::[[Int]]->[(Int,Int,Int,Int)]->[(Int,Int,Int,Int)]\n getAns' [] ans = ans\n getAns' (x:xs) ans =\n getAns' xs (getAns'' (x++(reverse x)) (getAns'' (x++(tail $ reverse x)) ans))\n \n getAns''::[Int]->[(Int,Int,Int,Int)]->[(Int,Int,Int,Int)] \n getAns'' x ans =\n [get i j k|i<-[1..l-1],j<-[i+1..l-1],k<-[j+1..l-1],0+1==i||(x!!0)/=0,i+1==j||(x!!i)/=0,j+1==k||(x!!j)/=0,k+1==l||(x!!k)/=0,check i j k]++ans\n where\n l=length x\n get i j k =\n (a,b,c,d)\n where\n a = func (take i x) 0\n b = func (drop i (take j x)) 0\n c = func (drop j (take k x)) 0\n d = func (drop k x) 0\n func [] t = t\n func (y:ys) t = func ys (t*10+y)\n check i j k =\n a<256&&b<256&&c<256&&d<256\n where\n a = func (take i x) 0\n b = func (drop i (take j x)) 0\n c = func (drop j (take k x)) 0\n d = func (drop k x) 0\n func [] t = t\n func (y:ys) t = func ys (t*10+y)\n _ans = getAns string []\n printAll::[(Int,Int,Int,Int)]->IO()\n printAll [] = return ()\n printAll ((a,b,c,d):xs) =\n do\n putStr $ show a\n putStr \".\"\n putStr $ show b\n putStr \".\"\n putStr $ show c\n putStr \".\"\n putStr $ show d\n putStr \"\\n\"\n printAll xs\n in\n do\n print $ length _ans\n printAll _ans\n "}], "src_uid": "4cb1927ce961aa5370276044f3be2f4a"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\tn <- readLn\n\tss <- replicateM n getLine\n\tprint $ solve \" \" ss\n\t\n--solve :: String -> [String] -> Int\nsolve prev [] = 0\nsolve prev (s:ss) = solve s ss + if prev == s then 0 else 1\n", "positive_code": [{"source_code": "module Main\n where\n\nimport System.IO\n\n--2215\n\nmain = do\n first <- getLine\n groups <- solve \"\" 0 $ read first\n print groups\n where\n solve last c 0 = do\n return c\n solve last c n = do\n magnet <- getLine\n solve magnet (if magnet == last then c else c + 1) (n - 1)\n\n \n "}, {"source_code": "import Control.Monad\n\nsol :: [String] -> String -> Int\nsol [] _ = 0\nsol mags last_s = if (head mags) == last_s\n then (sol (tail mags) last_s)\n else 1 + (sol (tail mags) (head mags))\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n inputs <- replicateM n getLine :: IO [[Char]]\n print(1 + (sol inputs (head inputs)))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\tn <- readLn\n\tres <- length . group <$> replicateM n getLine\n\tprint res\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\ngroups [x] = 0\ngroups (x:y:xs) = (if x == y then 1 else 0) + groups (y:xs)\n\ngenAns [] = 0\ngenAns xs = 1 + (groups xs)\n\nmain = do\n n <- readLn :: IO Int\n gs <- concat <$> replicateM n getLine\n print $ genAns gs\n\n"}, {"source_code": "import Data.List (group)\n\nnumGroups :: Eq a => [a] -> Int\nnumGroups = length . group\n\nmain :: IO ()\nmain = do\n n <- getLine\n magnets <- sequence $ replicate (read n) getLine\n print $ numGroups magnets\n\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.List (foldl')\nimport Control.Monad (replicateM)\n\n\naddMag :: [[String]] -> String -> [[String]]\naddMag [] y = [[y]]\naddMag xt@(x:xs) y\n | head x == y = (y:x):xs\n | otherwise = [y]:xt\n\nmain :: IO ()\nmain = print . length . foldl' addMag [] =<< flip replicateM getLine =<< readLn"}, {"source_code": "import Data.List\nmain=interact(show.length.group.tail.words)"}, {"source_code": "solve [] = 0\nsolve (m1:[]) = 0\nsolve (m1:m) | m1==head m = 1+ solve m \n | otherwise = solve m\n\nmain = do\n\tn<-getLine\n\td<-getContents\n\tlet b=concat $ lines d\n\tputStrLn $ show $ (solve b + 1)"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n solve n 0 >>= print\n\nsolve :: Int -> Int -> IO Int\nsolve 0 _ = return 0\nsolve n previous = do\n current <- read <$> getLine\n if current == previous\n then \n solve (n-1) previous\n else\n solve (n-1) current >>= return . (+1) \n \n\n"}, {"source_code": "import Data.List (group)\nmain = getLine >> getContents >>= return . length . group . words >>= print\n"}, {"source_code": "import Data.List\nmain = getContents >>= print . length . group . tail . lines"}, {"source_code": "import Control.Monad\n\n-- Snippet: partitionWith\npartitionWith1 eq (a1 : an)\n | not (null an) && eq a1 (head an) = (a1 : r, aLeft)\n | otherwise = ([a1], an)\n where (r, aLeft) = partitionWith1 eq an\n\npartitionWith eq a\n | null a = []\n | otherwise = r : partitionWith eq aLeft\n where (r, aLeft) = partitionWith1 eq a\n\nmain = do\n n <- readLn\n a <- replicateM n getLine\n putStrLn $ show $ length $ partitionWith (==) a\n"}, {"source_code": "\nreadData :: Int -> IO [Int]\nreadData 0 = return []\nreadData n = do\n x <- readLn :: IO Int\n xs <- readData (n-1)\n return (x:xs)\n\ncountIsles n (x1:[]) = n\ncountIsles n (x1:x2:xs)\n | x1==x2 = countIsles n (x2:xs)\n | otherwise = countIsles (n+1) (x2:xs)\n\nmain = do\n n <- readLn :: IO Int\n mags <- readData n\n print $ countIsles 1 mags\n"}, {"source_code": "main = do\n getLine\n ls <- fmap lines getContents\n let c = length $ filter (== True) $ zipWith (\\a b -> last a == head b) ls (tail ls)\n print $ c + 1\n"}, {"source_code": "solve :: [Int] -> Int\nsolve [] = 0\nsolve (a:x) = 1 + (solve $ (dropWhile (a==)) x)\nmain = interact $ show . solve . map read . tail . lines\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\x -> interact $ solve.take (read x) . lines\nsolve :: [String]->String\nsolve xss = show $ fst $ foldr solv1 (0,\"\") xss\n where solv1 a (b1,b2) = if a /= b2 then (1+b1, a) else (b1,b2)"}, {"source_code": "\nimport Data.List (group)\n\nmain :: IO ()\nmain = getContents >>= print . length . group . tail . words"}, {"source_code": "module Main where\nimport Control.Monad\nmain :: IO ()\nmain = do\n input <- getLine\n inputs <- replicateM (read input) getLine\n let second_chars = map tail inputs\n magnets = map read second_chars\n (ans,_) = foldl (\\(acc,curr) new -> (if curr == new then acc else acc+1, new)) (0,2) magnets\n print ans\n"}, {"source_code": "import Control.Applicative\nimport Data.List (group)\nimport qualified Data.ByteString.Lazy.Char8 as C\n\nmain = do\n n <- getLine\n xs <- C.lines <$> C.getContents\n print . length . group $ xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List (group)\n\nmain = do\n n <- read <$> getLine\n xs <- replicateM n getLine\n print . length . group $ xs"}, {"source_code": "import Control.Monad\n\nmain = getLine >>= getMags . read >>= putStrLn . show . count\n\ngetMags :: Int -> IO [String]\ngetMags n = mapM (\\_ -> getLine) [1..n]\n\ncount :: [String] -> Int\ncount (x:xs) = snd ans\n where ans = foldl (\\(lst, res) curr -> if lst == curr\n then (curr, res)\n else (curr, res + 1)) (x, 1) xs"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n magnets <- replicateM n getLine\n printf \"%d\" . length . group $ magnets"}, {"source_code": "import Prelude\nimport Data.String\nimport Text.Printf\nimport Control.Monad\n\nreadNums:: Int -> [Int] -> IO [Int]\nreadNums 0 numbers = return numbers\nreadNums n numbers = do\n c <- getChar\n if (c /= ' ')\n then \n readNums (n - 1) ((read [c] :: Int):numbers)\n else\n readNums n numbers \n\nsolver:: Int -> Int -> Int -> IO Int \nsolver 0 count _ = return count\nsolver n count lastFlag = do\n str <- getLine\n let newFlag = if (str == \"01\")\n then 1\n else 2\n if (lastFlag == newFlag)\n then solver (n - 1) count newFlag\n else solver (n - 1) (count + 1) newFlag\nmain = do\n str <- getLine\n let n = read str :: Int\n str <- getLine\n let initFlag = if (str == \"01\")\n then 1\n else 2\n numbers <- solver (n - 1) 1 initFlag\n print numbers\n return ()"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncountIslands :: [Int] -> Int\ncountIslands [] = 0\ncountIslands (x:xs) = 1 + (countIslands $ dropWhile (== x) xs)\n\nmain = do \n n <- read `fmap` getLine\n a <- replicateM n getLine\n print $ countIslands $ map read a\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncountIslands :: [String] -> Integer\ncountIslands [] = 0\ncountIslands (x:xs) = 1 + (countIslands $ dropWhile (== x) xs)\n\nmain = do \n n <- read `fmap` getLine\n a <- replicateM n getLine\n print $ countIslands a\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ncountIslands :: [Integer] -> Integer\ncountIslands [] = 0\ncountIslands (x:xs) = 1 + (countIslands $ dropWhile (== x) xs)\n\nmain = do \n n <- read `fmap` getLine\n a <- replicateM n getLine\n print $ countIslands $ map read a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: Eq a => [a] -> Int\nsolve = length . group\n\nmain :: IO ()\nmain = do\n _ <- B.getLine\n a <- fmap B.lines B.getContents\n print $ solve a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: Eq a => [a] -> Int\nsolve = length . group\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n a <- replicateM n B.getLine\n print $ solve a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: Eq a => [a] -> Int\nsolve = length . group\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- fmap lines getContents\n print $ solve a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nsolve :: Eq a => [a] -> Int\nsolve = length . group\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n a <- replicateM n getLine\n print $ solve a\n"}, {"source_code": "\n-- Michael V. Antosha \n-- 2016\n-- http://mivael.in.ua\n\ndata MagnetType = Type01 | Type10\n\nmain = do\n interact $ show . s . words\n where\n s (numStr:restStr) = solve (read numStr) restStr\n\nmtype \"10\" = Type10\nmtype \"01\" = Type01\n\nsolve :: Integer -> [String] -> Integer\nsolve n (magnet:rest) = solve' (n-1) 1 (mtype magnet) rest\nsolve _ _ = error \"Bad input.\"\n\nsolve' 0 sum _ [] = sum\nsolve' n sum lastType (magnet:rest) = recur\n where\n recur = solve' (n-1) (sum + s) thisType rest\n thisType = mtype magnet\n s = cntNewGroup lastType thisType\n cntNewGroup Type01 Type01 = 0\n cntNewGroup Type10 Type10 = 0\n cntNewGroup _ _ = 1\nsolve' _ _ _ _ = error \"Unexpected.\"\n"}, {"source_code": "\n-- Michael V. Antosha \n-- 2016\n-- http://mivael.in.ua\n\ndata MagnetType = Type01 | Type10\n\nmain = do\n interact $ show . s . words\n where\n s (numStr:restStr) = solve (read numStr) restStr\n\nmtype \"10\" = Type10\nmtype \"01\" = Type01\n\nsolve :: Int -> [String] -> Int\nsolve n (magnet:rest) = solve' (n-1) 1 (mtype magnet) rest\nsolve _ _ = error \"Bad input.\"\n\nsolve' 0 sum _ [] = sum\nsolve' n sum lastType (magnet:rest) = recur\n where\n recur = solve' (n-1) (sum + s) thisType rest\n thisType = mtype magnet\n s = cntNewGroup lastType thisType\n cntNewGroup Type01 Type01 = 0\n cntNewGroup Type10 Type10 = 0\n cntNewGroup _ _ = 1\nsolve' _ _ _ _ = error \"Unexpected.\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Maybe\n\n\n\n\nmain=do\n getLine\n show <$> length <$> group <$> lines <$> getContents >>=putStrLn\n"}, {"source_code": "import Data.List\nmain=getContents>>=print.length.group.tail.lines"}, {"source_code": "import Data.List (group)\n\nmain :: IO ()\nmain = getContents >>= print . length . group . tail . lines\n"}, {"source_code": "import Data.List\nmain=print.length.group.tail.lines=< [String] -> Int\nmagnet n = fst . foldr ko (1, '2')\n\nko :: String -> (Int, Char) -> (Int, Char)\nko (m:ms) (acc, prev)\n | last ms == prev = (acc+1, m)\n | 0 < 1 = (acc, m)\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/344/A\n\nimport Data.List\n\nmain :: IO ()\nmain = getContents >>= print . length . group . tail . lines\n"}, {"source_code": "import Data.List\nsolve :: [Int] -> Int\nsolve = length . group\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Data.List\nmain = interact $ show . length . group . tail . words"}, {"source_code": "import Data.List\nmain = interact $ show . length . group . tail . lines"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Ord\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getContents\n print . length $ group xs\n"}, {"source_code": "\ufeffloop 0 c p = putStrLn $ show c\n \nloop n c p = do\n q <- getLine\n loop (n-1) (if p == q then c else c+1) q\n \nmain = do\n n <- getLine\n loop (read n :: Int) 0 \"\"\n "}, {"source_code": "main = interact $ show.calc.tail.lines\n\ncalc (x:y:xs) = ( calc $ y:xs ) + ( if x == y then 0 else 1 )\ncalc _ = 1"}, {"source_code": "solve :: [String] -> String -> Int -> Int\nsolve [] _ grp = grp\nsolve (x : xs) prev grp | x == prev = solve xs x grp\n | otherwise = solve xs x grp + 1\n\nprepare :: [String] -> Int\nprepare lst = solve lst (head lst) 1\n\nmain :: IO ()\nmain = interact $ show . prepare . tail . words\n"}, {"source_code": "magnetGroups ts = 1 + (length $ filter (uncurry (/=)) $ zip ts (tail ts))\nreadNLines (ln:ls) = take (read ln) ls\nmain = interact $ (++ \"\\n\") . show . magnetGroups . readNLines . lines\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nmain = do\n n <- read <$> getLine\n l1 <- read <$> getLine\n res <- solve (n-1) l1 1\n print res\n\nsolve :: Int -> Int -> Int -> IO Int\nsolve 0 _ m = return m\nsolve n c m = do\n li <- read <$> getLine\n if li == c\n then solve (n-1) c m\n else solve (n-1) li (m+1)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\n\n \n\n \nmain= do\n\tgetLine \n\tx<- words <$> getContents \n\tprint $ length $ group x\n\t \n\t \n\t \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nunfolder :: [String] -> Maybe (Bool, [String])\nunfolder (a:b:as) = Just (a == b, b:as)\nunfolder _ = Nothing\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n print =<< (1+) . sum . map (fromEnum . not) . unfoldr unfolder <$> replicateM n getLine\n"}, {"source_code": "import Data.List\nimport Control.Monad\nmain = getLine >>= flip replicateM getLine.read >>= putStrLn.show.length.group"}, {"source_code": "--ghc 7.10\n\nimport Data.List\n\ncountMagnets :: (Eq a) => [a] -> Int\ncountMagnets = length . group\n\nmain = do\n nStr <- getLine\n aStr <- getContents\n let a = map read . words $ aStr :: [Int]\n print $ countMagnets a"}, {"source_code": "import Data.List\n\nmain = do\n m<-getLine\n n<-getContents\n print.length.group $ lines n\n"}, {"source_code": "import Control.Monad\n\nprocess :: [String] -> Int\nprocess source = snd (foldr (\\z (x, y) -> (z, if x == z then y else y+1) ) (\" \", 0) source)\n\nmain :: IO()\nmain = do \n count <- readLn\n inputs <- replicateM count getLine\n putStrLn (show $ process inputs)"}, {"source_code": "import Data.List\naddIfRepell l r \n\t| (snd l) !! 1 == (snd r) !! 0 = ( (+1) $ fst l, snd r)\n\t| otherwise = (fst l, snd r)\ncal ls = \n\tlet mags = map (\\m -> (1,m)) $ tail ls\n\tin fst $ foldl1 addIfRepell mags\n\nmain = interact (show . cal . lines)\n"}, {"source_code": "import Data.List;main=interact$show.length.group.tail.lines"}, {"source_code": "import Data.List\nmain = interact $ show . length . group . tail . lines"}, {"source_code": "data Magnet = Magnet Char Char deriving (Show)\n\nreadmagnet :: String -> Magnet\nreadmagnet (x:y:_) = Magnet x y\n\nans :: [Magnet] -> Int -> Int\nans f@(x : y : _) z = if ((check x y) == True) then (ans (tail f) (z + 1)) else (ans (tail f) z) \n\twhere\n\tcheck :: Magnet -> Magnet -> Bool\n\tcheck (Magnet x1 y1) (Magnet x2 y2) = if (y1 == x2) then True else False\nans _ z = z\n\nmain = do\n\tn <- getLine\n\tmagnets <- getContents\n\tputStr $ show $ (ans (map readmagnet (lines magnets) :: [Magnet]) 1)\n\t\n\t\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsol :: [String] -> String -> Int\nsol [] _ = 0\nsol mags last_s = if (head mags) == last_s\n then 1 + (sol (tail mags) last_s)\n else (sol (tail mags) (head mags))\n\nmain :: IO ()\nmain = do\n n_s <- getLine\n let n = read n_s :: Int\n inputs <- replicateM n getLine :: IO [[Char]]\n print(sol (tail inputs) (head inputs))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Char\nimport Text.Printf\n\nmain = do\n\tn <- readLn\n\tss <- group . sort <$> replicateM n getLine\n\tlet\n\t\tn1 = length $ ss !! 0\n\t\tn2 = length $ ss !! 1\n\tprint $ 2 * min n1 n2 + if n1 == n2 then 0 else 1\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n solve n 0 >>= print\n\nsolve :: Int -> Int -> IO Int\nsolve 0 _ = return 0\nsolve n previous = do\n current <- read <$> getLine\n if current == previous\n then \n solve (n-1) previous\n else\n solve (n-1) previous >>= return . (+1) \n \n\n"}, {"source_code": "main = interact $ show.calc.lines\n\ncalc (x:y:xs) = ( calc $ y:xs ) + ( if x == y then 0 else 1 )\ncalc _ = 1"}, {"source_code": "import Control.Monad\nimport Data.List\n\nunfolder :: [String] -> Maybe (Bool, [String])\nunfolder (a:b:as) = Just (a == b, b:as)\nunfolder _ = Nothing\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n print =<< maximum . (1:) . map((1+) . length) . filter or . group . unfoldr unfolder <$> replicateM n getLine\n"}, {"source_code": "import Data.List\n\nmain = do\n m<-getLine\n n<-getLine\n print.length.group $ lines n\n"}, {"source_code": "data Magnet = Magnet Char Char deriving (Show)\n\nreadmagnet :: String -> Magnet\nreadmagnet (x:y:_) = Magnet x y\n\nans :: [Magnet] -> Int -> Int\nans f@(x : y : _) z = if ((check x y) == True) then (ans (tail f) (z + 1)) else (ans (tail f) z) \n\twhere\n\tcheck :: Magnet -> Magnet -> Bool\n\tcheck (Magnet x1 y1) (Magnet x2 y2) = if (y1 == x2) then False else True\nans _ z = z\n\nmain = do\n\tn <- getLine\n\tmagnets <- getContents\n\tputStr $ show $ (ans (map readmagnet (lines magnets) :: [Magnet]) 1)\n\t\n\t\n"}], "src_uid": "6c52df7ea24671102e4c0eee19dc6bba"} {"source_code": "import Array\n\nm = 10\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\ngetArray :: [Int] -> Array Int Integer\ngetArray xs = accumArray (+) 0 (-m, m) [(x, 1) | x <- xs]\n\nsolve :: [Int] -> Integer\nsolve xs = notZeroPairs + zeroPairs\n where\n array = getArray xs\n notZeroPairs = sum (map (\\i -> (array ! i) * (array ! (-i))) [1..m])\n zeroPairs = div (n * (n - 1)) 2\n n = array ! 0\n \nmain :: IO ()\nmain = do\n getLine >> Main.reads >>= print . solve", "positive_code": [{"source_code": "main :: IO()\nmain = do\n\tgetLine\n\tstringNumbers <- getLine\n\tlet numbers = map read $ words stringNumbers :: [Integer]\n\tlet n = zeroPairs + countPairs numbersWithOutZeroes where\n\t\tzeroPairs :: Integer\n\t\tzeroPairs = fib $ integerLength (filter (== 0) numbers) - 1 where\n\t\t\tfib :: Integer -> Integer\n\t\t\tfib (-1) = 0\n\t\t\tfib n = n + (fib $ n - 1)\n\t\tnumbersWithOutZeroes = filter (/= 0) numbers\n\t\tcountPairs :: [Integer] -> Integer\n\t\tcountPairs [] = 0\n\t\tcountPairs list = integerLength positive * integerLength negative + countPairs others where\n\t\t\tpositive = [x | x <- list, x == head list]\n\t\t\tnegative = [x | x <- list, x == -head list]\n\t\t\tothers = [x | x <- list, x /= head list, x /= -head list]\n\tputStrLn $ show n\n\t\nintegerLength :: [Integer] -> Integer\nintegerLength [] = 0\nintegerLength (x:xs) = 1 + integerLength xs"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.Array.Unboxed as UB\nimport Data.Array.ST\nimport Data.Array\nimport Data.Char\nclass IOtyp a where scan' :: String -> a; show' :: a -> String\ninstance IOtyp Int where scan' = read; show' = show\ninstance IOtyp Char where scan' (x:_) = x;show' = (:[])\ninstance IOtyp Float where scan' = read;show' = show\ninstance IOtyp Double where scan' = read;show' = show\ninstance IOtyp Integer where scan' = read;show' = show\ninstance IOtyp String where scan' = id;show' = id\ninstance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y\ninstance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z\nforeign import ccall \"stdio.h puts\" c_puts :: CString -> IO ()\nscan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'\nscans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan\nscanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words\nscanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist\nputs :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}\n\ncount c = foldl (\\n -> \\x -> if x==c then n+1 else n) 0\n\nsolve :: [Int] -> Integer\nsolve l = let ary = array (-10,10) [(i,count i l)|i<-[-10..10]]\n zero = fromIntegral ((ary!0)*((ary!0)-1) `div` 2)\n other = fromIntegral (foldl (\\n -> \\m -> (ary!m)*(ary!(-m))+n) 0 [1..10])\n in\n zero + other\n\nmain = do n <- scan :: IO Int\n l <- scanlist :: IO [Int]\n puts.show $ solve l"}, {"source_code": "import Data.List\nimport Debug.Trace\n\nmain = getContents >>= doit . lines where\n doit [] = putStrLn \"\"\n doit (n:lis:xs) = do\n print . solve $ words lis\n doit xs\n\n solve lis = solve' (0 :: Integer) lis' where\n lis' = group . sort $ map (read :: String -> Integer) lis\n\n\nlength' = toInteger . length\n\nsolve' :: (Ord a, Num a) => Integer -> [[a]] -> Integer\nsolve' n [] = n\nsolve' n (x:[]) = if (head x) == 0 then n + (length' x) * ((length' x) - 1) `div` (2 :: Integer) else n\nsolve' n (x1:x2:xs)\n | d > 0 = solve' n $ x2:xs\n | d < 0 = solve' n $ init $ x1:x2:xs\n | otherwise = solve' (n + (length' x1) * (length' . last $ x2:xs)) (init $ x2:xs) where\n d = diff (x1:x2:xs)\n\n\ndiff [] = 0\ndiff xs = (abs . head . head $ xs) - (abs . last . last $ xs)\n"}, {"source_code": "main = do\n getLine\n ts <- fmap (map read . words) getLine\n let zs = count 0 ts\n print $ zs * (zs - 1) `div` 2 + (sum $ map (\\x -> (count x ts) * (count (-x) ts)) [1..10])\n where\n count x xs = foldl (\\acc y -> if x == y then acc + 1 else acc) 0 xs\n"}, {"source_code": "import Data.ByteString.Char8 as BS (readInt, getLine, split)\nimport Data.Maybe (fromJust)\n\nmain = do\n BS.getLine\n ts <- fmap (map (fst . fromJust . BS.readInt) . BS.split ' ') BS.getLine\n let zs = count 0 ts\n print $ zs * (zs - 1) `div` 2 + (sum $ map (\\x -> (count x ts) * (count (-x) ts)) [1..10])\n where\n count x xs = foldl (\\acc y -> if x == y then acc + 1 else acc) 0 xs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n cs = accumArray (+) 0 (-10, 10) $ zip xs $ repeat 1 :: UArray Int Int64\n\n print $ sum [cs!i * cs!(-i) | i <- [1..10]] + cs!0 * (cs!0 - 1) `div` 2\n"}, {"source_code": "count :: (Eq a, Num b) => a -> [a] -> b\ncount item lst = count' lst item 0\n where count' [] _ ret = ret\n count' (x:xs) item ret\n | x == item = count' xs item (ret + 1)\n | otherwise = count' xs item ret\n\nsolve :: [Int] -> Integer\nsolve lst = let zero = count 0 lst :: Integer\n pcnt = map (flip count lst) [1..10] :: [Integer]\n ncnt = map (flip count lst) [(-1),(-2)..(-10)] :: [Integer]\n in (zero * (zero - 1)) `div` 2 +\n (sum $ (map (\\(x, y) -> x * y) $ zip pcnt ncnt))\n\nmain :: IO ()\nmain = do nn <- getLine\n tt <- getLine\n let\n n = read nn :: Int\n t = map read $ words tt :: [Int]\n print $ solve t\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\n\ncount :: (Eq a, Num b) => a -> [a] -> b\ncount item = fromIntegral . length . filter (== item)\n\nsolve :: [Int] -> Integer\nsolve lst = let zero = count 0 lst :: Integer\n pcnt = map (flip count lst) [1..10] :: [Integer]\n ncnt = map (flip count lst) [(-1),(-2)..(-10)] :: [Integer]\n in (zero * (zero - 1)) `div` 2 +\n (sum $ (map (\\(x, y) -> x * y) $ zip pcnt ncnt))\n\nmain :: IO ()\nmain = do nn <- BS.getLine\n tt <- BS.getLine\n let\n n = toNumber $ BS.readInt nn\n t = map (toNumber . BS.readInt) (BS.words tt)\n print $ solve t\n\ntoNumber :: Num a => Maybe (a, BS.ByteString) -> a\ntoNumber (Just (x, _)) = x\ntoNumber Nothing = 0\n"}, {"source_code": "count :: (Eq a, Num b) => a -> [a] -> b\ncount item = fromIntegral . length . filter (== item)\n\nsolve :: [Int] -> Integer\nsolve lst = let zero = count 0 lst :: Integer\n pcnt = map (flip count lst) [1..10] :: [Integer]\n ncnt = map (flip count lst) [(-1),(-2)..(-10)] :: [Integer]\n in (zero * (zero - 1)) `div` 2 +\n (sum $ (map (\\(x, y) -> x * y) $ zip pcnt ncnt))\n\nmain :: IO ()\nmain = do nn <- getLine\n tt <- getLine\n let\n n = read nn :: Int\n t = map read $ words tt :: [Int]\n print $ solve t\n"}, {"source_code": "import Data.List\n\nmain = interact $ show . (count (repeat 0) 0). map (10+) . map read . words . head . tail . lines\n\twhere\n\t\tcount list n [] = n\n\t\tcount list n (x:xs) = count (plusIndex list x) (if (list !! (inverse x) == 0) then n else (n+(list !! (inverse x)))) xs\n\t\tinverse n = 20 - n\n\t\tplusIndex (x:xs) 0 = x+1: xs\n\t\tplusIndex (x:xs) n = x: plusIndex xs (n-1)"}, {"source_code": "import Array\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nmain = BS.interact $ BS.pack . show . sumMatches . count\n\t\t. map readInt' . BS.words . head . tail . BS.lines\n\twhere\n\t\tcount ns = accumArray (+) 0 (-10,10) [(n,1)| n<-ns]\n\t\tsumMatches arr = sum [arr ! x * arr ! (-x)| x<-[1..10]] + (arr ! 0) * (arr ! 0 - 1) `div` 2\n\t\treadInt' bs = fst $ fromJust $ BS.readInt bs"}, {"source_code": "import Array\n\nmain = interact $ show . sumMatches . count . map read . words . head . tail . lines\n\twhere\n\t\tcount ns = accumArray (+) 0 (-10,10) [(n,1)| n<-ns]\n\t\tsumMatches arr = sum [arr ! x * arr ! (-x)| x<-[1..10]] + (arr ! 0) * (arr ! 0 - 1) `div` 2"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n a <- getList\n let zeroList = count 0 a\n otherList = sum $ map (\\x -> (count x a) * (count (-x) a)) [1..10]\n print $ zeroList * (zeroList - 1) `div` 2 + otherList\n where\n count element xs = foldl' (\\x e -> if e == element then x+1 else x) 0 xs \n getList = fmap (map read . words) getLine :: IO [Int]"}, {"source_code": "import Data.List\nimport Data.Int\nmain = print . solve . map read . tail . words =<< getContents\nsolve ts = nzs * (nzs-1) `div` 2 + sum (merge (group ps) (group ns))\n where (ps',ns') = partition (>= 0) ts\n (zs,ps) = break (> 0) (sort ps')\n ns = sort (map negate ns')\n nzs = genericLength zs :: Int64\nmerge (x:xs) (y:ys) | head x < head y = merge xs (y:ys)\n | head x > head y = merge (x:xs) ys\n | otherwise = (genericLength x * genericLength y) :\n merge xs ys\nmerge _ _ = []\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = getContents >>= doit . lines where\n doit [] = putStrLn \"\"\n doit (n:lis:xs) = do\n print . solve $ words lis\n doit xs\n\n solve lis = solve' 0 lis' where\n lis' = group . sort $ map (read :: String -> Int) lis\n\n\nsolve' n [] = n\nsolve' n (x:[]) = if (head x) == 0 then n + (length x) * ((length x) - 1) `div` 2 else n\nsolve' n (x1:x2:xs)\n | d > 0 = solve' n $ x2:xs\n | d < 0 = solve' n $ init x1:x2:xs\n | otherwise = solve' (n + (length x1) * (length . last $ x2:xs)) (init $ x2:xs) where\n d = diff xs\n\ndiff [] = 0\ndiff xs = (abs . head . head $ xs) - (abs . last . last $ xs)\n"}, {"source_code": "import Data.List\n\nmain = getContents >>= doit . lines where\n doit [] = putStrLn \"\"\n doit (n:lis:xs) = do\n print . solve $ words lis\n doit xs\n\n solve lis = solve' 0 lis' where\n lis' = group . sort $ map (read :: String -> Int) lis\n solve' n [] = n\n solve' n (x:[]) = if (head x) == 0 then n + (length x) * ((length x) - 1) `div` 2 else n\n solve' n (x1:x2:xs)\n | d > 0 = solve' n $ x2:xs\n | d < 0 = solve' n $ init x1:x2:xs\n | otherwise = solve' (n + (length x1) * (length . last $ xs)) (tail $ x2:xs) where\n d = diff xs\n\ndiff xs = (abs . head . head $ xs) - (abs . last . last $ xs)\n\n"}, {"source_code": "import Data.List\nimport Debug.Trace\n\nmain = getContents >>= doit . lines where\n doit [] = putStrLn \"\"\n doit (n:lis:xs) = do\n print . solve $ words lis\n doit xs\n\n solve lis = solve' 0 lis' where\n lis' = group . sort $ map (read :: String -> Int) lis\n\n\nsolve' n [] = n\nsolve' n (x:[]) = if (head x) == 0 then n + (length x) * ((length x) - 1) `div` 2 else n\nsolve' n (x1:x2:xs)\n | d > 0 = solve' n $ x2:xs\n | d < 0 = solve' n $ init $ x1:x2:xs\n | otherwise = solve' (n + (length x1) * (length . last $ x2:xs)) (init $ x2:xs) where\n d = diff (x1:x2:xs)\n\ndiff [] = 0\ndiff xs = (abs . head . head $ xs) - (abs . last . last $ xs)\n"}, {"source_code": "main = do\n getLine\n ts <- fmap (map read . words) getLine\n let zs = count 0 ts\n print $ zs * (zs - 1) `div` 2 + (sum $ map (\\x -> (count x ts) * (count (-x) ts)) [1..10])\n where\n count x = length . filter (==x) --foldl (\\acc y -> if x == y then acc + 1 else acc) 0 xs\n"}, {"source_code": "import Array\n\nm = 10\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\ngetArray :: [Int] -> Array Int Integer\ngetArray xs = accumArray (+) 0 (-m, m) [(x, 1) | x <- xs]\n\nsolve :: [Int] -> Integer\nsolve xs = notZeroPairs + zeroPairs\n where\n array = getArray xs\n notZeroPairs = sum (map (\\i -> (array ! i) * (array ! (-i))) [1..m])\n zeroPairs = div (n * (n - 1)) 2\n n = array ! 0\n \nmain :: IO ()\nmain = do\n Main.reads >>= print . solve\n "}, {"source_code": "import Data.List\nmain = print . solve . map read . tail . words =<< getContents\nsolve ts = nzs * (nzs-1) `div` 2 + sum (merge (group ps) (group ns))\n where (ps',ns') = partition (>= 0) ts\n (zs,ps) = break (> 0) (sort ps')\n ns = sort (map negate ns')\n nzs = length zs\nmerge (x:xs) (y:ys) | head x < head y = merge xs (y:ys)\n | head x > head y = merge (x:xs) ys\n | otherwise = (length x * length y) : merge xs ys\nmerge _ _ = []\n"}, {"source_code": "main :: IO()\nmain = do\n\tstringNumbers <- getLine\n\tlet numbers = map read $ words stringNumbers :: [Integer]\n\tlet n = zeroPairs + countPairs numbersWithOutZeroes where\n\t\tzeroPairs :: Integer\n\t\tzeroPairs = fib $ integerLength (filter (== 0) numbers) - 1 where\n\t\t\tfib :: Integer -> Integer\n\t\t\tfib (-1) = 0\n\t\t\tfib n = n + (fib $ n - 1)\n\t\tnumbersWithOutZeroes = filter (/= 0) numbers\n\t\tcountPairs :: [Integer] -> Integer\n\t\tcountPairs [] = 0\n\t\tcountPairs list = integerLength positive * integerLength negative + countPairs others where\n\t\t\tpositive = [x | x <- list, x == head list]\n\t\t\tnegative = [x | x <- list, x == -head list]\n\t\t\tothers = [x | x <- list, x /= head list, x /= -head list]\n\tputStrLn $ show n\n\t\nintegerLength :: [Integer] -> Integer\nintegerLength [] = 0\nintegerLength (x:xs) = 1 + integerLength xs"}, {"source_code": "import Data.List\n\nfib (-1) = 0\nfib 0 = 0\nfib n = n + (fib $ n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Int]\n\tlet n = countPairs numbers where\n\t\tcountPairs [] = 0\n\t\tcountPairs nums = length positive * length negative + fib (length zeroes - 1) + countPairs restNums where\n\t\t\tpositive = [x | x <- nums, x /= 0, x == head nums]\n\t\t\tnegative = [x | x <- nums, x /= 0, negate x == head nums]\n\t\t\tzeroes = filter (== 0) nums\n\t\t\trestNums = [x | x <- nums, x /= 0, x /= head nums, x /= -head nums]\n\tputStrLn $ show n"}, {"source_code": "import Data.List\n\nfib :: Integer -> Integer\nfib (-1) = 0\nfib 0 = 0\nfib n = n + fib (n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Integer]\n\tlet n = zeroPairs + countPairs numbersWithOutZeroes where\n\t\tzeroPairs :: Integer\n\t\tzeroPairs = fib $ toInteger $ length (filter (== 0) numbers) - 1\n\t\tnumbersWithOutZeroes = filter (/= 0) numbers\n\t\tcountPairs :: [Integer] -> Integer\n\t\tcountPairs [] = 0\n\t\tcountPairs list@(h:_) = toInteger (length positive * length negative) + countPairs others where\n\t\t\tpositive = filter (== h) list\n\t\t\tnegative = filter (== -h) list\n\t\t\tothers = [x | x <- list, x /= h, x /= -h]\n\tputStrLn $ show n"}, {"source_code": "main = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Int]\n\tlet n = makePairs numbers where\n\t\tmakePairs [_] = 0\n\t\tmakePairs (man:others) = (+) (foldl (\\x -> if man == negate x then (+1) else (+0)) 0 others)\n\t\t\t\t\t\t\t\t\t (makePairs others)\n\tputStrLn $ show n"}, {"source_code": "import Data.List\n\nfib 0 = 0\nfib n = n + (fib $ n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Int]\n\tlet n = countPairs numbers where\n\t\tcountPairs [] = 0\n\t\tcountPairs nums = length positive * length negative + fib (length zeroes - 1) + countPairs restNums where\n\t\t\tpositive = [x | x <- nums, x /= 0, x == head nums]\n\t\t\tnegative = [x | x <- nums, x /= 0, negate x == head nums]\n\t\t\tzeroes = filter (== 0) nums\n\t\t\trestNums = [x | x <- nums, x /= head nums, x /= -head nums]\n\tputStrLn $ show n"}, {"source_code": "import Data.List\n\nfib (-1) = 0\nfib 0 = 0\nfib n = n + fib (n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Int]\n\tlet n = zeroPairs + countPairs numbersWithOutZeroes where\n\t\tzeroPairs = fib $ length (filter (== 0) numbers) - 1\n\t\tnumbersWithOutZeroes = filter (/= 0) numbers\n\t\tcountPairs [] = 0\n\t\tcountPairs list@(h:_) = length positive * length negative + countPairs others where\n\t\t\tpositive = filter (== h) list\n\t\t\tnegative = filter (== -h) list\n\t\t\tothers = [x | x <- list, x /= h, x /= -h]\n\tputStrLn $ show n"}, {"source_code": "import Data.List\n\nfib (-1) = 0\nfib 0 = 0\nfib n = n + (fib $ n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Int]\n\tlet n = countPairs numbers where\n\t\tcountPairs [] = 0\n\t\tcountPairs nums = length positive * length negative + fib (length zeroes - 1) + countPairs restNums where\n\t\t\tpositive = [x | x <- nums, x /= 0, x == head nums]\n\t\t\tnegative = [x | x <- nums, x /= 0, negate x == head nums]\n\t\t\tzeroes = filter (== 0) nums\n\t\t\trestNums = [x | x <- nums, x /= head nums, x /= -head nums]\n\tputStrLn $ show n"}, {"source_code": "import Data.List\n\nfib (-1) = 0\nfib 0 = 0\nfib n = n + fib (n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Int]\n\tlet n = countPairs numbers where\n\t\tcountPairs [] = 0\n\t\tcountPairs nums = length positive * length negative + fib (length zeroes - 1) + countPairs restNums where\n\t\t\tpositive = [x | x <- nums, x /= 0, x == head nums]\n\t\t\tnegative = [x | x <- nums, x /= 0, negate x == head nums]\n\t\t\tzeroes = filter (== 0) nums\n\t\t\trestNums = [x | x <- nums, x /= 0, x /= head nums, x /= -head nums]\n\tputStrLn $ show n"}, {"source_code": "import Data.List\n\nfib (-1) = 0\nfib 0 = 0\nfib n = n + fib (n - 1)\n\nmain :: IO()\nmain = do\n\tgetLine\n\tstrNumbers <- getLine\n\tlet numbers = map read (words strNumbers) :: [Integer]\n\tlet n = zeroPairs + countPairs numbersWithOutZeroes where\n\t\tzeroPairs = fib $ length (filter (== 0) numbers) - 1\n\t\tnumbersWithOutZeroes = filter (/= 0) numbers\n\t\tcountPairs [] = 0\n\t\tcountPairs list@(h:_) = length positive * length negative + countPairs others where\n\t\t\tpositive = filter (== h) list\n\t\t\tnegative = filter (== -h) list\n\t\t\tothers = [x | x <- list, x /= h, x /= -h]\n\tputStrLn $ show n"}], "src_uid": "f3dde329830d8c479b3dab9d5df8baf5"} {"source_code": "{-# LANGUAGE Strict #-}\r\nimport Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read)\r\n >>> chunksOf 2\r\n >>> map (solve >>> show)\r\n >>> unlines\r\n\r\nsolve :: [[Int]] -> Int\r\nsolve [_, as] = rec 0 (reverse as)\r\n where\r\n v = last as\r\n rec _ [] = 0\r\n rec c (x : xs)\r\n | x == v = rec (c + 1) xs\r\n | otherwise = 1 + rec (2 * c) (drop (c - 1) xs)\r\n\r\n-- helpers\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do t <- readLn\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do n <- readLn\n line <- getLine\n let a = reverse $ map read $ words line\n print $ operate (tail a) (n - 1) 1 (head a)\n\noperate :: [Int] -> Int -> Int -> Int -> Int\noperate a n l v | n <= 0 = 0\n | x == v = operate xs (n - 1) (l + 1) v\n | otherwise = 1 + operate (drop l a) (n - l) (l * 2) v\n where x:xs = a\n"}, {"source_code": "module Main where\n\n(|>) = flip ($)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n [] = []\nchunksOf n xs = take n xs : chunksOf n (drop n xs)\n\nparse :: [String] -> [Int]\nparse = map read . words . last\n\nsolve' :: [Int] -> Int -> Int -> Int -> Int\nsolve' [] n el ans = ans\nsolve' (x:xs) n el ans = \n if x == el\n then solve' (xs) (n+1) el ans\n else solve' (drop n (x:xs)) (2*n) el (ans+1)\n \nsolve :: [Int] -> Int\nsolve a =\n let el = last a in\n let a' = reverse a in\n solve' a' 0 el 0\n\nmain :: IO ()\nmain = interact $\n unlines\n . map (show . solve . parse) \n . chunksOf 2\n . tail \n . lines\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map (words >>> map read)\r\n >>> chunksOf 2\r\n >>> map (solve >>> show)\r\n >>> unlines\r\n\r\nsolve :: [[Int]] -> Int\r\nsolve [_, as] = rec 0 (reverse as)\r\n where\r\n v = last as\r\n rec _ [] = 0\r\n rec c (x:xs)\r\n | x == v = rec (c + 1) xs\r\n | otherwise = 1 + rec (2 * c) (drop c xs)\r\n\r\n-- helpers\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n"}], "src_uid": "dc10b869293df2b7a557262c805635ba"} {"source_code": "import Control.Monad\nmain = do\n [x,y] <- liftM (map read . words) getLine :: IO [Integer]\n putStrLn $ show $ (fromIntegral x) * ((1.000000011)^^(y))\n", "positive_code": [{"source_code": "main = do\n s <- getLine\n let [n, m] = map read $ words s\n print $ solve n m\n\nsolve :: Integer -> Integer -> Double\nsolve n m = (1.000000011 ^^ m) * (fromIntegral n)\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain =\n do\n a <- getLine\n let b = read $ words a !! 0 :: Double\n e = read $ words a !! 1 :: Int in\n putStrLn $ show $ b * 1.000000011 ^ e\n"}, {"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Control.Applicative\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO ()\nmain = do\n a <-(\\(x:y:ys) -> (x,y)) . map (fst.fromJust.C.readInt) . C.words<$> C.getLine\n print $ ((1.000000011) ^^ (snd a)) * ((fromIntegral.fst) a)"}, {"source_code": "main = fmap (map read. words ) getLine >>= \\[n,t] -> print $ n * 1.000000011 ** t\n"}, {"source_code": "module Main where\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain::IO()\nmain = do \n line <- readInts \n let a = line !! 0\n let b = line !! 1\n let result = fromIntegral(a)*(1.000000011)^b\n print result"}, {"source_code": "import Numeric\n\nexplg :: (Fractional a) => a -> Int -> a\nexplg _ 0 = 1\nexplg x 1 = x\nexplg x n\n\t| even n = explg (x * x) (div n 2)\n \t| otherwise = x * explg (x * x) (div n 2)\n\nreadInts :: IO [Int]\nreadInts = fmap (map read . words) getLine\n\ngrowth ::Double\ngrowth = 1.000000011\n\nmain :: IO ()\nmain = do\n\tints <- readInts\n \tlet init' = ints !! 0;\n\t \ttime' = ints !! 1\n\tputStr . show $ fromIntegral init' * (explg growth time')\n"}, {"source_code": "import Control.Applicative\n \n\n \n \n \n\nmain= do\n\t[a,b]<-map read. words <$>getLine::IO [Double]\n\tputStrLn $ show $ a*(1.000000011**b)"}, {"source_code": "import Control.Monad (liftM)\n\nmain :: IO ()\nmain = do\n [n, t] <- (map read . words) `liftM` getContents :: IO [Double]\n print $ n * (1.000000011 ** t)\n"}, {"source_code": "main :: IO ()\nmain = do\n [n_str, t_str] <- fmap words getLine\n let n = read n_str :: Int\n let t = read t_str :: Int\n let ans = (fromIntegral n) * ((1+1.1e-8) ^ t) \n print ans "}], "negative_code": [], "src_uid": "36ad784f23bd1e8e579052642a6e9244"} {"source_code": "' '#a|head a<'A'=a\nx#a=x:a\nq c|c<'A'=c:\" \"|1>0=[c]\nmain=interact$foldr(#)\" \".(>>=q)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsolve :: [String] -> String\nsolve = dropWhile (== ' ') . solve'\n where\n solve' [] = \"\"\n solve' (s : ss)\n | s `elem` [\".\", \",\", \"!\", \"?\"] = s ++ solve' ss\n | otherwise = \" \" ++ s ++ solve' ss\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve . split\n where\n split = filter (not . null) . split' []\n where\n split' ys [] = reverse ys : []\n split' ys (x : xs)\n | x == ' ' = reverse ys : split' [] xs\n | x `elem` \".,!?\" = reverse ys : [x] : split' [] xs\n | otherwise = split' (x : ys) xs\n\n"}, {"source_code": "s=' '\nf x a@(h:t)|x==s&&h<'A'=a|x>s&&x<'A'&&h>s=x:s:a|1>0=x:a\nmain=interact$foldr f\"\\n\""}, {"source_code": "e=(`elem`\".,!?\")\ns=(==' ')\nf x[]=[x]\nf x a@(h:t)|s x&&(e h||s h)=a|e x&&(not$s h)=x:' ':a|1>0=x:a\nmain=interact$(foldr f[])"}, {"source_code": "f x[]=[x]\nf x a@(h:t)|x<'!'&&h<'A'=a|x>' '&&x<'A'&&h>' '=x:' ':a|1>0=x:a\nmain=interact$foldr f[]"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\nimport System.IO.Error\n\n\nhReadMany :: (Char -> Bool) -> Handle -> IO String\nhReadMany p h = do b <- (p <$> hLookAhead h) `catch` const (return False)\n if b\n then (:) <$> hGetChar h <*> hReadMany p h\n else return \"\"\n\nhSkipSpaces = hReadMany isSpace\nhReadNumeric = hReadMany (\\c -> isDigit c || c `elem` ['.', '-', '+'])\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = do hSkipSpaces stdin\n read <$> hReadNumeric stdin\n\nreadTerm :: IO String\nreadTerm = do hSkipSpaces stdin\n hReadMany (not . isSpace) stdin\n\nisPunct '.' = True\nisPunct ',' = True\nisPunct '!' = True\nisPunct '?' = True\nisPunct _ = False\n\n\nseparate :: String -> [String]\nseparate \"\" = []\nseparate (c:cs) | isPunct c = [c] : separate cs\n | isLower c = let (tok, rest) = readOut (c:cs)\n in tok : separate rest\n | isSpace c = separate cs\n where\n readOut (c:cs) | isLower c = let (tok, rest) = readOut cs\n in (c:tok, rest)\n | otherwise = (\"\", c:cs)\n readOut \"\" = (\"\", \"\")\n\ncombine :: [String] -> String\ncombine (str:strings) = str ++ combine' strings\n where\n combine' [] = \"\"\n combine' (s:ss) | isPunct $ head s = s ++ combine' ss\n | otherwise = \" \" ++ s ++ combine' ss\n\nmain = do line <- getLine\n putStrLn $ combine $ separate line"}, {"source_code": "import Data.Char\nimport Data.List\n\nisPunct x = x `elem` \".,!?\"\n\nsolve :: String -> String\nsolve [] = []\nsolve (x:xs) | isSpace x = space xs\n | isPunct x = x : punc xs\n | otherwise = x : solve xs\n\n-- seen a space\nspace [] = []\nspace (x:xs) | isSpace x = space xs\n | isPunct x = x : punc xs\n | otherwise = ' ' : x : solve xs\n\n-- seen a punctuation mark\npunc [] = ' ' : []\npunc (x:xs) | isSpace x = punc xs\n | isPunct x = x : punc xs -- not possible\n | otherwise = ' ' : x : solve xs\n\nmain = do\n solve `fmap` getLine >>= putStrLn\n\n"}, {"source_code": "dtw :: String -> String -> [String]\ndtw [] akk = (reverse akk):[]\ndtw (x:xs) akk | (x == ' ') = mk akk ++ dtw xs []\n | (x `elem` \",.!?\") = mk akk ++ [[x]] ++ dtw xs []\n | otherwise = dtw xs (x:akk)\n\twhere mk [] = []\n\t mk a = [reverse a]\n\nwrite [] = []\nwrite (x:xs) | (x == []) = \" \" ++ write xs\n | ((head x) `elem` \",.!?\") = \"\u25c1\" ++ x ++ \" \" ++ write xs\n | otherwise = x ++ \" \" ++ write xs\n\ncut :: String -> (Bool,String) -- \u041a\u043e\u0441\u0442\u044b\u043b\u044c 1\ncut [] = (False,[])\ncut (x:xs) | (x == '\u25c1') = (True,(snd next))\n | (fst next) = (False,(snd next))\n | otherwise = (False,(x:(snd next)))\n where next = cut xs\n\ndspase [] = [] -- \u041a\u043e\u0441\u0442\u044b\u043b\u044c 2\ndspase a = reverse $ tail $ reverse $ a\n\nmain = do\n\t\t\ts <- getLine\n\t\t\tputStrLn $ dspase $ snd $ cut $ write $ dtw s []\n"}, {"source_code": "znak = \",.!?\"\n\nsolve :: String -> String\nsolve s = reverse (solve_ \"\" s)\n where\n solve_ :: String -> String -> String\n solve_ acc \"\" = acc\n solve_ acc (c:s)\n | c `elem` (znak ++ \" \") = solveSpaces c acc s\n | otherwise = solve_ (c:acc) s\n \n solveSpaces :: Char -> String -> String -> String\n solveSpaces ' ' acc \"\" = acc\n solveSpaces z acc \"\" = z:acc\n solveSpaces z acc (' ':s) = solveSpaces z acc s\n solveSpaces ' ' acc (c:s)\n | c `elem` znak = solveSpaces c acc s\n | otherwise = solve_ (' ':acc) (c:s) \n solveSpaces z acc (c:s)\n | c `elem` znak = error \"SolveSpaces: '!!' or ',,' etc\"\n | otherwise = solve_ (' ':z:acc) (c:s)\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve"}, {"source_code": "import Data.Char\nimport Data.List\n\nstick [] = []\nstick (x:[a]:rest) | not $ isLetter a = (x ++ [a]):stick rest\n | otherwise = x:stick ([a]:rest)\nstick (x:rest) = x:stick rest\n\nmain = interact $ unwords . stick . (concatMap $ groupBy (\\x y -> isLetter x == isLetter y)) . words"}, {"source_code": "main=interact g\nisP x=x/=' '&&(x<'a'||x>'z')\ng(' ':p:x)|isP p||p==' '=g(p:x)\ng(p:x:y)|isP p&&x/=' '=p:g(' ':x:y)\ng(x:y)=x:g y\ng[]=[]\n"}, {"source_code": "main=interact g\nisP x=x/=' '&&(x<'a'||x>'z')\ng(' ':p:x)|isP p=g(p:x)\ng(' ':' ':x)=g(' ':x)\ng(p:x:y)|isP p&&x/=' '=p:g(' ':x:y)\ng(x:y)=x:g y\ng[]=[]\n"}, {"source_code": "import Data.List\n\npuncs = \".,!?\"\n\nsolve :: String -> String\nsolve s = reverse $ f \"\" $ unwords $ words s\n where f s \"\" = s\n f s (c:c':cs) | c == ' ' && c' `elem` puncs = f s (c':cs)\n | c' `elem` puncs = f (c:s) (c':cs)\n f s (c':c:cs) | c == ' ' && c' `elem` puncs = f (c:c':s) cs\n | c' `elem` puncs = f (c:' ':c':s) cs\n f s (c:cs) = f (c:s) cs\n\nmain = do\n getLine >>= putStrLn . solve"}, {"source_code": "main = do cs <- getLine\n putStrLn $ solve cs\n\nsolve :: String -> String\nsolve [] = []\nsolve (c:cs)\n | c == ' ' = if null cs' then []\n else if isPunc $ head cs' then solve cs'\n else c : solve cs' \n | isPunc c = c : ' ' : solve cs'\n | otherwise = c : solve cs\n where cs' = dropWhile (' '==) cs\n\nisPunc :: Char -> Bool\nisPunc = flip elem \".,!?\""}], "negative_code": [{"source_code": "dtw :: String -> String -> [String]\ndtw [] akk = akk:[]\ndtw (x:xs) akk | (x == ' ') = mk akk ++ dtw xs []\n | (x `elem` \",.!?\") = mk akk ++ [[x]] ++ dtw xs []\n | otherwise = dtw xs (x:akk)\n\twhere mk [] = []\n\t mk a = [reverse a]\n\nwrite [] = []\nwrite (x:xs) | (x == []) = \" \" ++ write xs\n | ((head x) `elem` \",.!?\") = \"\\b\" ++ x ++ \" \" ++ write xs\n | otherwise = x ++ \" \" ++ write xs\n\nmain = do\n\t\t\ts <- getLine\n\t\t\tputStrLn $ write $ dtw s []"}, {"source_code": "dtw :: String -> String -> [String]\ndtw [] akk = akk:[]\ndtw (x:xs) akk | (x == ' ') = mk akk ++ dtw xs []\n | (x `elem` \",.!?\") = mk akk ++ [[x]] ++ dtw xs []\n | otherwise = dtw xs (x:akk)\n\twhere mk [] = []\n\t mk a = [reverse a]\n\nwrite [] = []\nwrite (x:xs) | (x == []) = \" \" ++ write xs\n | ((head x) `elem` \",.!?\") = \"\\b\" ++ x ++ \" \" ++ write xs\n | otherwise = x ++ \" \" ++ write xs\n\nmain = do\n\t\t\ts <- getLine\n\t\t\tputStrLn $ write $ dtw s []\n"}, {"source_code": "dtw :: String -> String -> [String]\ndtw [] akk = (reverse akk):[]\ndtw (x:xs) akk | (x == ' ') = mk akk ++ dtw xs []\n | (x `elem` \",.!?\") = mk akk ++ [[x]] ++ dtw xs []\n | otherwise = dtw xs (x:akk)\n\twhere mk [] = []\n\t mk a = [reverse a]\n\nwrite [] = []\nwrite (x:xs) | (x == []) = \" \" ++ write xs\n | ((head x) `elem` \",.!?\") = \"\u25c1\" ++ x ++ \" \" ++ write xs\n | otherwise = x ++ \" \" ++ write xs\n\ncut :: String -> (Bool,String)\ncut [] = (False,[])\ncut (x:xs) | (x == '\u25c1') = (True,(snd next))\n | (fst next) = (False,(snd next))\n | otherwise = (False,(x:(snd next)))\n where next = cut xs\n\nmain = do\n\t\t\ts <- getLine\n\t\t\tputStrLn $ snd $ cut $ write $ dtw s []\n"}, {"source_code": "chakk [] = []\nchakk (' ':xs) = chakk xs\nchakk (x:xs) = x:(chakk xs)\n\nparse :: String -> String -> [String]\nparse [] akk = [reverse akk]\nparse (' ':xs) akk = [reverse $ chakk akk] ++ parse xs []\nparse (x:xs) akk = if (x `elem` \",.?!\") then [reverse $ chakk akk] ++ [[x]] ++ parse xs []\n else parse xs (x:akk)\n\nmake [] = []\nmake (x:xs) | (x == []) = make xs\n | ((head x) `elem` \",.?!\") = x ++ make xs\n | otherwise = (' ':x) ++ make xs\n\ncut [] = []\ncut (_:xs) = xs\n\nmain = do\n l <- getLine\n print $ cut $ make $ parse l []\n"}, {"source_code": "-- Resubmit #1\nimport Data.Char\nimport Data.List\n\nsolve [] = []\nsolve (s:[x]:rest) | not $ isLetter x = s:[x]:\" \":solve rest\n | otherwise = s:\" \":[x]:\" \":solve rest\nsolve (x:[]) = [x]\nsolve (x:xs) = x:\" \":solve xs\n\nmain = interact $ concat . solve . (concatMap $ groupBy (\\x y -> isLetter x == isLetter y)) . words"}, {"source_code": "import Data.Char\nimport Data.List\n\nstick [] = []\nstick (x:[a]:rest) | not $ isLetter a = (x ++ [a]):stick rest\n | otherwise = x:[a]:stick rest\nstick (x:rest) = x:stick rest\n\nmain = interact $ unwords . stick . (concatMap $ groupBy (\\x y -> isLetter x == isLetter y)) . words"}, {"source_code": "main=interact g\ng(' ':',':x)=g(',':x)\ng(' ':' ':x)=g(' ':x)\ng(',':x:y)|x/=' '=',':g(' ':x:y)\ng(x:y)=x:g y\ng[]=[]\n"}, {"source_code": "import Data.List\n\nsolve :: String -> String\nsolve s = reverse $ f \"\" $ unwords $ words s\n where f s \"\" = s\n f s (c:',':cs) | c == ' ' = f s (',':cs)\n | otherwise = f (c:s) (',':cs)\n f s (',':c:cs) | c == ' ' = f (c:',':s) cs\n | otherwise = f (c:' ':',':s) cs\n f s (c:cs) = f (c:s) cs\n\nmain = do\n getLine >>= putStrLn . solve"}, {"source_code": "import Data.List\n\npuncs = \".,!?\"\n\nsolve :: String -> String\nsolve s = reverse $ f \"\" $ unwords $ words s\n where f s \"\" = s\n f s (c:c':cs) | c == ' ' && c' `elem` puncs = f s (c':cs)\n | c' `elem` puncs = f (c:s) (',':cs)\n f s (c':c:cs) | c == ' ' && c' `elem` puncs = f (c:c':s) cs\n | c' `elem` puncs = f (c:' ':c':s) cs\n f s (c:cs) = f (c:s) cs\n\nmain = do\n getLine >>= putStrLn . solve"}, {"source_code": "main = do cs <- getLine\n putStrLn $ solve cs\n\nsolve :: String -> String\nsolve [] = []\nsolve (c:cs)\n | c == ' ' = if null cs' then []\n else if (head cs') == ',' then solve cs'\n else c : solve cs' \n | c == ',' = c : ' ' : solve cs'\n | otherwise = c : solve cs\n where cs' = dropWhile (' '==) cs"}, {"source_code": "' '#a|head a<'A'=a\nx#a=x:a\nq c|c<'A'=c:\" \"|1>0=[c]\nmain=interact$foldr(#)\"rtsrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqDBL\".(>>=q)"}], "src_uid": "8c26daa1eed2078af3b32737da0a0f84"} {"source_code": "sol :: [Int] -> Int\nsol [0, 0] = 0\nsol [h, m] = 24 * 60 - h * 60 - m\n\nmain = interact (unlines . map show . map (sol . map read) . map words . tail . lines)", "positive_code": [{"source_code": "-- https://codeforces.com/problemset/problem/1283/A\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Char(digitToInt)\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\ngetInts :: Int -> IO [Int]\ngetInts n = fmap read <$> getLines n\n\ngetInt :: IO Int\ngetInt = fmap read getLine\n\nreadLine :: Read a => IO [a]\nreadLine = fmap (fmap read . words) getLine\n\nsolve :: [Int] -> String\nsolve [h, m] = show $ (23 - h) * 60 + (60 - m)\n\nworkProblem :: IO ()\nworkProblem = do\n n <- getInt\n input <- replicateM n (readLine :: IO [Int])\n () <- mapM_ putStrLn $ map solve input\n return ()\n\nmain :: IO ()\nmain = workProblem"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [h, m] <- getIntList\n print $ (23 - h) * 60 + (60 - m)"}, {"source_code": "import Control.Monad\n\nimport Data.Char\nimport Data.List\n\nsolve :: (Int, Int) -> Int\nsolve (h, m) = (24 - h) * 60 - m\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStrLn $ unlines . map (show . solve) $ zip (a input) (b input)\n where a = map snd .filter (odd . fst) . zip [1..] . map (read :: String -> Int) . tail . words\n b = map snd . filter (even .fst) . zip [1..] . map (read :: String -> Int) . tail . words\n"}, {"source_code": "main = do\n firstLine <- getLine\n let n = (read::String->Int) firstLine\n mainLoop n\n\nmainLoop :: Int -> IO ()\nmainLoop n = do\n if n == 0\n then return ()\n else do\n line <- getLine\n let minutes = (show . minutesToChristmas . getTime) line\n putStrLn minutes\n mainLoop (n - 1)\n\ngetTime :: String -> (Int, Int)\ngetTime = (\\[a,b] -> (a, b)) . map read . take 2 . words\n\nminutesToChristmas :: (Int, Int) -> Int\nminutesToChristmas (hours, minutes) = ((23 - hours) * 60) + 60 - minutes"}, {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve (h:m:_) = 60 * 24 - 60 * h - m\n\nmain :: IO ()\nmain = ids >>= mapM_ (fn >=> print)\n where ids = enumFromTo 1 . read <$> getLine\n fn tc = solve . map read . words <$> getLine\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int\nsolve h m = 60*24-60*h-m\n\nroutine :: IO ()\nroutine = do\n [h,m] <- (map read.words) <$> getLine\n print $ solve h m\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n "}, {"source_code": "main = interact $ unlines . map ((show . ((24*60) - ) . sum . zipWith (*) [60, 1]) . map (read :: String -> Int) . words ) . tail . lines "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess (x:y:[]) = (24-x)*60-y\n\n\n\nmain::IO ()\nmain=do\n t<- read <$> getLine ::IO Int \t\n a<- map( map read) <$> map words <$> replicateM t getLine::IO [[Int]] \n mapM_ print $ map process a\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\n\nsolve h m = 24 * 60 - h * 60 - m\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain = do \n n <- read <$> getLine\n replicateM_ n $ do\n [h, m] <- map readInt . words <$> getLine\n print $ solve h m\n"}, {"source_code": "process :: (Int,Int) -> Int\nprocess (h,m) = (24-h) * 60 - m\n \nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int,Int)\nreadPair str = (a,b)\n where [a,b] = map read (words str)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n xs <- fmap (map readPair.lines) getContents\n putStrLn . unlines . map show $ map process xs"}, {"source_code": "main :: IO ()\n\nmain = interact solve\n\nsolve :: String -> String\nsolve = buildup . map solver . breakdown\nsolver (x:y:[]) = 60 * (23 - x) + (60 - y)\n\nbreakdown :: String -> [[Int]]\nbreakdown = map (map readInt . words) . tail . lines \n\nbuildup :: [Int] -> String\nbuildup = unlines . map show\n\nreadInt :: String -> Int\nreadInt = read :: String -> Int\n"}], "negative_code": [{"source_code": "main = do\n line <- getLine\n putStrLn line\n"}], "src_uid": "f4982de28aca7080342eb1d0ff87734c"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (accumArray, assocs, elems, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray, STArray, runSTArray)\nimport Data.ByteString.Char8 (readInt, words, lines, getContents, getLine)\nimport Data.List (elemIndex)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, m, _] <- map readInt' . words <$> getLine\n es <- map ((\\[u, v] -> (u, v + n)) . map readInt' . words) . lines <$> getContents\n\n let\n vs = runSTArray $ do\n let k = max n m\n vs <- newArray ((1, 1), (n+m, k)) 0 :: ST s (STArray s (Int, Int) Int)\n\n let\n look u = look' 1\n where\n look' i = do\n v <- readArray vs (u, i)\n if v == 0\n then return i\n else look' (i + 1)\n\n forM_ es $ \\(u, v) -> do\n c <- look u\n d <- look v\n let s = c + d\n\n writeArray vs (u, c) v\n\n let\n set u v c = do\n w <- readArray vs (v, c)\n if w /= 0\n then do\n writeArray vs (v, c) u\n writeArray vs (w, c) 0\n let c' = s - c\n writeArray vs (v, c') w\n set v w c'\n else\n return (u, v, c)\n \n (u, v, c) <- set u v c\n writeArray vs (v, c) u\n\n return vs\n\n cs = accumArray (flip const) 0 ((0, 0), (n+m, n+m)) . map (\\((v, c), u) -> ((v, u), c)) $ assocs vs\n\n if length es == 0\n then print 0\n else do\n let r = map (cs !) es\n print . maximum $ r\n putStr . unwords . map show $ r\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (accumArray, assocs, elems, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray, STArray, runSTArray)\nimport Data.ByteString.Char8 (readInt, words, lines, getContents, getLine)\nimport Data.List (elemIndex)\nimport Data.Maybe (fromJust)\nimport Prelude hiding (words, lines, getContents, getLine)\n\nreadInt' = fst . fromJust . readInt\n\nmain = do\n [n, m, _] <- map readInt' . words <$> getLine\n es <- map ((\\[u, v] -> (u, v + n)) . map readInt' . words) . lines <$> getContents\n\n let\n vs = runSTArray $ do\n let k = max n m\n vs <- newArray ((1, 1), (n+m, k)) 0 :: ST s (STArray s (Int, Int) Int)\n\n let\n look u = look' 1\n where\n look' i = do\n v <- readArray vs (u, i)\n if v == 0\n then return i\n else look' (i + 1)\n\n forM_ es $ \\(u, v) -> do\n c <- look u\n d <- look v\n let s = c + d\n\n writeArray vs (u, c) v\n\n let\n set u v c = do\n w <- readArray vs (v, c)\n if w /= 0\n then do\n writeArray vs (v, c) u\n writeArray vs (w, c) 0\n let c' = s - c\n writeArray vs (v, c') w\n set v w c'\n else\n return (u, v, c)\n\n (u, v, c) <- set u v c\n writeArray vs (v, c) u\n\n return vs\n\n cs = accumArray (flip const) 0 ((0, 0), (n+m, n+m)) . map (\\((v, c), u) -> ((v, u), c)) $ assocs vs\n\n if length es == 0\n then print 0\n else do\n let r = map (cs !) es\n print . maximum $ r\n putStr . unwords . map show $ r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (forM_)\nimport Control.Monad.ST.Safe (ST)\nimport Data.Array (accumArray, assocs, (!))\nimport Data.Array.MArray.Safe (newArray, readArray, writeArray)\nimport Data.Array.ST.Safe (STArray, runSTArray)\nimport Data.List (elemIndex)\nimport Data.Maybe (fromJust)\n\nmain = do\n [n, m, _] <- map read . words <$> getLine\n es <- map ((\\[u, v] -> (u, v + n)) . map read . words) . lines <$> getContents\n\n let\n vs = runSTArray $ do\n let k = max n m\n vs <- newArray ((1, 1), (n+m, k)) 0 :: ST s (STArray s (Int, Int) Int)\n\n forM_ es $ \\(u, v) -> do\n let f u = (+1) . fromJust . elemIndex 0 <$> mapM (\\i -> readArray vs (u, i)) [1..k]\n c <- f u\n d <- f v\n let s = c + d\n\n writeArray vs (u, c) v\n\n let\n set u v c = do\n w <- readArray vs (v, c)\n if w /= 0\n then do\n writeArray vs (v, c) u\n writeArray vs (w, c) 0\n let c' = s - c\n writeArray vs (v, c') w\n set v w c'\n else\n return (u, v, c)\n \n (v, u, c) <- set u v c\n writeArray vs (u, c) v\n\n return vs\n\n cs = accumArray (flip const) 0 ((0, 0), (n+m, n+m)) . map (\\((v, c), u) -> ((v, u), c)) $ assocs vs\n\n putStr . unwords . map show $ map (cs !) es\n"}], "src_uid": "030b14f72a958fa781e31ed3a203c33f"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n k <- readInt\n poems <- replicateM n (replicateM 4 readString)\n return (n, k, poems)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nisVowel a = a `elem` \"aeiou\"\n\ncheckRhyme :: Int -> ByteString -> ByteString -> Bool\ncheckRhyme k a b\n | length indexA < k = False\n | length indexB < k = False\n | otherwise = suffixA == suffixB\n where\n indexA = reverse $ BS.findIndices isVowel a\n indexB = reverse $ BS.findIndices isVowel b\n \n suffixA = BS.drop (indexA !! (k - 1)) a\n suffixB = BS.drop (indexB !! (k - 1)) b\n\ndata Outcome = AABB\n | ABAB\n | ABBA\n | AAAA\n | NoneAbove\n deriving Eq\n\nmergeOutcome NoneAbove _ = NoneAbove\nmergeOutcome _ NoneAbove = NoneAbove\nmergeOutcome AAAA x = x\nmergeOutcome x AAAA = x\nmergeOutcome a b | a == b = a\n | otherwise = NoneAbove\n\ninstance Show Outcome where\n show AABB = \"aabb\"\n show ABAB = \"abab\"\n show ABBA = \"abba\"\n show AAAA = \"aaaa\"\n show NoneAbove = \"NO\"\n\ncheckQuatrain k [a, b, c, d] | check a b && check a c && check a d = AAAA\n | check a b && check c d = AABB\n | check a c && check b d = ABAB\n | check a d && check b c = ABBA\n | otherwise = NoneAbove\n where\n check = checkRhyme k\n\nsolve (n, k, poems) = foldl mergeOutcome AAAA (map (checkQuatrain k) poems)\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n", "positive_code": [{"source_code": "import Data.List\n\nisVowel 'a' = True\nisVowel 'i' = True\nisVowel 'u' = True\nisVowel 'e' = True\nisVowel 'o' = True\nisVowel _ = False\n\nchop 0 _ = Just \"\"\nchop _ [] = Nothing\nchop k (x:xs)\n | isVowel x = fmap (x:) $ chop (k-1) xs\n | otherwise = fmap (x:) $ chop k xs\n \n\naaaa [] = Just True\naaaa ((Just a) : (Just b) : (Just c): (Just d) : es)\n | a == b && b == c && c == d = aaaa es\naaaa _ = Nothing\n\n\naabb [] = Just True\naabb ((Just a) : (Just b) : (Just c): (Just d) : es)\n | a == b && c == d = aabb es\naabb _ = Nothing\n\nabab [] = Just True\nabab ((Just a) : (Just b) : (Just c): (Just d) : es)\n | a == c && b == d = abab es\nabab _ = Nothing\n\nabba [] = Just True\nabba ((Just a) : (Just b) : (Just c): (Just d) : es)\n | a == d && b == c = abba es\nabba _ = Nothing\n\nsolve x\n | aaaa x == Just True = \"aaaa\"\n | aabb x == Just True = \"aabb\"\n | abab x == Just True = \"abab\"\n | abba x == Just True = \"abba\"\n | otherwise = \"NO\"\n\nmain = do\n [n, k] <- fmap (map read . words) getLine\n p <- mapM (fmap (chop k . reverse)) $ take (n*4) (repeat getLine)\n putStrLn $ solve p\n\n-- vim: set expandtab:\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndata Suffix = Suffix String\n | Invalid\n deriving Show\n\ninstance Eq Suffix where\n (Suffix a) == (Suffix b) = a == b\n _ == _ = False\n\ntype Quatrain = (Suffix, Suffix, Suffix, Suffix)\n\nisAABB (a,b,c,d) = a == b && c == d\nisABAB (a,b,c,d) = a == c && b == d\nisABBA (a,b,c,d) = a == d && b == c\n\nsolve :: [Quatrain] -> String\nsolve list =\n let fs = [isAABB, isABAB, isABBA]\n ans = map (flip all list) fs\n ans' = map snd $ filter fst $ zip ans [\"aabb\", \"abab\", \"abba\"]\n in case length ans' of\n 0 -> \"NO\"\n 1 -> head ans'\n _ -> \"aaaa\"\n\nisVowel = isJust . flip elemIndex \"aeiou\"\n\nsuffix :: Int -> String -> Suffix\nsuffix k str =\n let xs = findIndices isVowel str\n x = drop (length xs - k) xs\n in if k > length xs\n then Invalid\n else Suffix $ drop (head x) str\n\nmain = do\n [n, k] <- (map read . words) `fmap` getLine\n list <- replicateM n $ do\n list <- replicateM 4 $ do\n [str] <- words `fmap` getLine\n return str\n let [a,b,c,d] = map (suffix k) list\n return (a,b,c,d)\n\n let ans = solve list\n putStrLn ans\n"}, {"source_code": "-- lyrics\nrifm = [\"aabb\", \"abab\", \"abba\", \"aaaa\"]\n\nglasn a = (a=='a'||a=='e'||a=='i'||a=='o'||a=='u')--a=='y'\n\ngnums [] s (a,_) = (a, read $ reverse s :: Int)\ngnums (' ':xs) s _ = gnums xs [] (read $ reverse s :: Int,1)\ngnums (x:xs) s a = gnums xs (x:s) a\n\ngetLyr 0 a _ = return a\ngetLyr i a n = do \n\t\t\t\tx <- getLine\n\t\t\t\tgetLyr (i-1) ((gsfx n (reverse x) []):a) n\n\ngsfx _ [] _ = \"-\"\ngsfx 1 (x:xs) a = if (glasn x) then (x:a) else gsfx 1 xs (x:a)\ngsfx n (x:xs) a = if (glasn x) then gsfx (n-1) xs (x:a) else gsfx n xs (x:a)\n\n-- find type for one lir\nfind :: [String] -> String -> String -> String -> String\nfind [] _ _ akk = reverse akk\nfind (x:xs) a b akk | (x == \"-\") = \"NO\"\n | (a == []) = find xs x b ('a':akk)\n | ((x /= a) && (b == [])) = find xs a x ('b':akk)\n | (x == a) = find xs a b ('a':akk)\n | (x == b) = find xs a b ('b':akk)\n | otherwise = \"NO\"\n\nsolve :: Int -> [String] -> [String] -> String -> String\nsolve 4 list lakk takk | (((takk == [])||(takk == \"aaaa\"))&&(foldr (||) False (map (newT==) rifm)))= solve 0 list [] newT\n | ((takk == newT)||(newT == \"aaaa\")) = solve 0 list [] takk\n | otherwise = \"NO\"\n where newT = (find lakk [] [] [])\nsolve _ [] _ t = t\nsolve n (x:xs) lakk t = solve (n+1) xs (x:lakk) t\n\nmain = do\n\t\t\tsnums <- getLine\n\t\t\tlet n = gnums snums [] (0,0) in\n\t\t\t\tdo\n\t\t\t\t\tlyrics <- getLyr ((fst n)*4) [] (snd n)\n\t\t\t\t\tputStrLn $ solve 0 lyrics [] []\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Data.Maybe\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\ndata RhymeScheme = None | Any | Aabb | Abba | Abab\n deriving (Eq,Show)\n\nscheme [s1,s2,s3,s4]\n | s1 == s2 && s1 == s3 && s1 == s4 = Any\n | s1 == s2 && s3 == s4 = Aabb\n | s1 == s3 && s2 == s4 = Abab\n | s1 == s4 && s2 == s3 = Abba\n | otherwise = None\n\ncombine :: RhymeScheme -> RhymeScheme -> RhymeScheme\ncombine None _ = None\ncombine _ None = None\ncombine Any r = r\ncombine r Any = r\ncombine r s = if r == s then r else None\n\ncommonScheme as = go Any as\n where go r [] = r\n go r (a:as) = case combine r a of\n None -> None\n s -> go s as\n\ntrimRight :: ByteString -> ByteString\ntrimRight bs = BS.take n bs\n where n = find (BS.length bs-1)\n find k | k < 0 = k+1\n | isSpace (BS.index bs k) = find (k-1)\n | otherwise = (k+1)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n as =\n case splitAt n as of\n (bs,[]) -> [bs]\n (bs,cs) -> bs : chunksOf n cs\n\nisVowel 'a' = True\nisVowel 'e' = True\nisVowel 'i' = True\nisVowel 'o' = True\nisVowel 'u' = True\nisVowel _ = False\n\nsuffix :: Int -> ByteString -> Maybe ByteString\nsuffix k bs = go k (BS.length bs)\n where go 0 i = Just $ BS.drop i bs\n go _ 0 = Nothing\n go k i = if isVowel (BS.index bs (i-1))\n then go (k-1) (i-1)\n else go k (i-1)\n\nsolve k lines =\n if all isJust suffixes\n then commonScheme schemes\n else None\n where\n suffixes = map (suffix k) lines\n quatrains = chunksOf 4 (map fromJust suffixes)\n schemes = map scheme quatrains\n\nmain = do\n (n:k:_) <- map read <$> words <$> getLine\n lines <- replicateM (4*n) $ BS.pack <$> getLine\n let answer =\n case solve k lines of\n None -> \"NO\"\n Any -> \"aaaa\"\n Aabb -> \"aabb\"\n Abba -> \"abba\"\n Abab -> \"abab\"\n putStrLn answer\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad\n\nvowel x = x `elem` \"aeiou\"\n\ncombineTypes (a1, b1, c1) (a2, b2, c2) =\n (a1 && a2,\n b1 && b2,\n c1 && c2)\n\ngetType k [a, b, c, d] =\n (rhymes k a b && rhymes k c d,\n rhymes k a c && rhymes k b d,\n rhymes k a d && rhymes k b c)\n\nrhymes k a b = let (suffixA, countA) = getSuffix a\n (suffixB, countB) = getSuffix b\n in suffixA == suffixB && countA >= k && countB >= k\n where getSuffix x = BS.foldr collectSuffix (BS.empty, 0) x\n collectSuffix x (suffix, count) | count >= k = (suffix, count)\n | vowel x = (BS.cons x suffix, \n count + 1)\n | otherwise = (BS.cons x suffix, count)\n\nsolve :: Int -> [[BS.ByteString]] -> String\nsolve k quantrains =\n case generalType of\n (True, False, False) -> \"aabb\"\n (False, True, False) -> \"abab\"\n (False, False, True) -> \"abba\"\n (True, True, True) -> \"aaaa\"\n _ -> \"NO\"\n where generalType = foldl' combineTypes (True, True, True) types\n types = map (getType k) quantrains\n\nmain = do [n, k] <- fmap (map readInt . BS.words) BS.getLine\n quantrains <- replicateM n $ replicateM 4 BS.getLine\n putStrLn $ solve k quantrains\n\nreadInt line = fst $ fromJust $ BS.readInt line"}, {"source_code": "import Control.Applicative\n\nmain = do [n,k] <- map read <$> words <$> getLine\n ss <- mapM (\\i -> getLine) [1..(4*n)]\n putStrLn $ solve k n ss\n\nsolve :: Int -> Int -> [String] -> String\nsolve k _ ss = if any (( String\nsolve' ss\n | null ss' = \"aaaa\"\n | all ((head ss') ==) (tail ss') = head ss'\n | otherwise = \"NO\"\n where ss' = filter (not.(\"aaaa\"==)) ss\n\nrhyme :: [String] -> String\nrhyme (a:b:c:d:_)\n | (a==b)&&(b==c)&&(c==d) = \"aaaa\"\n | (a==b)&&(c==d) = \"aabb\"\n | (a==c)&&(b==d) = \"abab\"\n | (a==d)&&(b==c) = \"abba\"\n | otherwise = \"NO\"\n\ntoQuat :: [String] -> [[String]]\ntoQuat [] = []\ntoQuat (a:b:c:d:xs) = [a,b,c,d]: toQuat xs\n\nisVowel :: Char -> Bool\nisVowel c = elem c \"aeiou\"\n\ntake' :: Int -> String -> String\ntake' 0 _ = []\ntake' k cs = xs ++ [y] ++ (take' (k-1) ys)\n where (xs,(y:ys)) = break isVowel cs\n"}, {"source_code": "module Main where\n\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (solve . lines)\n\nsolve :: [String] -> String\nsolve lines = result where\n result = case rhyme of\n Nothing -> \"NO\"\n Just s -> s\n rhyme = foldl1 (buildType) types\n types = map getType poem\n poem = quads $ tail endings\n endings = map (ending k) lines\n k = (read $ last $ words $ head lines) :: Int\n\nbuildType t (Just \"aaaa\") = t\nbuildType (Just \"aaaa\") t = t\nbuildType t1 t2\n | t1 == t2 = t1\n | otherwise = Nothing\n\ngetType :: [Maybe String] -> Maybe String\ngetType quad@[a, b, c, d]\n | any (== Nothing) quad = Nothing\n | all (== a) quad = Just \"aaaa\"\n | a == b && c == d = Just \"aabb\"\n | a == c && b == d = Just \"abab\"\n | a == d && b == c = Just \"abba\"\n | otherwise = Nothing\n\nquads :: [a] -> [[a]]\nquads [] = []\nquads (a : b : c : d : poem) = [a, b, c, d] : quads poem\n\nending :: Int -> String -> Maybe String\nending k = ending' [] k . reverse\n\nending' :: String -> Int -> String -> Maybe String\nending' result 0 _ = Just result\nending' result k [] = Nothing\nending' result k (c : str)\n | c `elem` \"aeiou\" = ending' (c : result) (k - 1) str\n | otherwise = ending' (c : result) k str\n"}], "negative_code": [{"source_code": "isVowel 'a' = True\nisVowel 'i' = True\nisVowel 'u' = True\nisVowel 'e' = True\nisVowel 'o' = True\nisVowel _ = False\n\nchop k x\n | k > length x = \"\"\n | otherwise = drop (length x - k) x\n\naaaa [] = True\naaaa (a:b:c:d:es)\n | a == b && b == c && c == d = aaaa es\n | otherwise = False\n\naabb [] = True\naabb (a:b:c:d:es)\n | a == b && c == d = aabb es\n | otherwise = False\n\nabab [] = True\nabab (a:b:c:d:es)\n | a == c && b == d = abab es\n | otherwise = False\n\nabba [] = True\nabba (a:b:c:d:es)\n | a == d && b == c = abba es\n | otherwise = False\n\nsolve x\n | aaaa x = \"aaaa\"\n | aabb x = \"aabb\"\n | abab x = \"abab\"\n | abba x = \"abba\"\n | otherwise = \"NO\"\n\nmain = do\n [n, k] <- fmap (map read . words) getLine\n p <- mapM (fmap (chop k . filter isVowel)) $ take (n*4) (repeat getLine)\n putStrLn $ solve p\n\n-- vim: set expandtab:\n"}, {"source_code": "isVowel 'a' = True\nisVowel 'i' = True\nisVowel 'u' = True\nisVowel 'e' = True\nisVowel 'o' = True\nisVowel _ = False\n\nchop k x\n | k > length x = \"\"\n | otherwise = drop (length x - k) x\n\naaaa [] = True\naaaa (a:b:c:d:es)\n | a == \"\" || b == \"\" || c == \"\" || d == \"\" = False\n | a == b && b == c && c == d = aaaa es\n | otherwise = False\n\naabb [] = True\naabb (a:b:c:d:es)\n | a == \"\" || b == \"\" || c == \"\" || d == \"\" = False\n | a == b && c == d = aabb es\n | otherwise = False\n\nabab [] = True\nabab (a:b:c:d:es)\n | a == \"\" || b == \"\" || c == \"\" || d == \"\" = False\n | a == c && b == d = abab es\n | otherwise = False\n\nabba [] = True\nabba (a:b:c:d:es)\n | a == \"\" || b == \"\" || c == \"\" || d == \"\" = False\n | a == d && b == c = abba es\n | otherwise = False\n\nsolve x\n | aaaa x = \"aaaa\"\n | aabb x = \"aabb\"\n | abab x = \"abab\"\n | abba x = \"abba\"\n | otherwise = \"NO\"\n\nmain = do\n [n, k] <- fmap (map read . words) getLine\n p <- mapM (fmap (chop k . filter isVowel)) $ take (n*4) (repeat getLine)\n putStrLn $ solve p\n\n-- vim: set expandtab:\n"}, {"source_code": "-- lyrics\nrifm = [\"aabb\", \"abab\", \"abba\", \"aaaa\"]\n\nglasn a = (a=='a'||a=='e'||a=='i'||a=='o'||a=='u')--a=='y'\n\ngnums [] s (a,_) = (a, read $ reverse s :: Int)\ngnums (' ':xs) s _ = gnums xs [] (read $ reverse s :: Int,1)\ngnums (x:xs) s a = gnums xs (x:s) a\n\ngetLyr 0 a _ = return a\ngetLyr i a n = do \n\t\t\t\tx <- getLine\n\t\t\t\tgetLyr (i-1) ((gsfx n (reverse x) []):a) n\n\ngsfx _ [] _ = \"-\"\ngsfx 1 (x:xs) a = if (glasn x) then (x:a) else gsfx 1 xs (x:a)\ngsfx n (x:xs) a = if (glasn x) then gsfx (n-1) xs (x:a) else gsfx n xs (x:a)\n\n-- find type for one lir\nfind :: [String] -> String -> String -> String -> String\nfind [] _ _ akk = reverse akk\nfind (x:xs) a b akk | (x == \"-\") = \"NO\"\n | (a == []) = find xs x b ('a':akk)\n | ((x /= a) && (b == [])) = find xs a x ('b':akk)\n | (x == a) = find xs a b ('a':akk)\n | (x == b) = find xs a b ('b':akk)\n | otherwise = []\n\nsolve :: Int -> [String] -> [String] -> String -> String\nsolve 4 list lakk takk | (((takk == [])||(takk == \"aaaa\"))&&(foldr (||) False (map (newT==) rifm)))= solve 0 list [] newT\n | ((takk == newT)||(newT == \"aaaa\")) = solve 0 list [] takk\n | otherwise = \"NO\"\n where newT = (find lakk [] [] [])\nsolve _ [] _ t = t\nsolve n (x:xs) lakk t = solve (n+1) xs (x:lakk) t\n\nmain = do\n\t\t\tsnums <- getLine\n\t\t\tlet n = gnums snums [] (0,0) in\n\t\t\t\tdo\n\t\t\t\t\tlyrics <- getLyr ((fst n)*4) [] (snd n)\n\t\t\t\t\tputStrLn $ solve 0 lyrics [] []\n"}, {"source_code": "-- lyrics\nrifm = [\"aabb\", \"abab\", \"abba\", \"aaaa\"]\n\nglasn a = (a=='a'||a=='e'||a=='i'||a=='o'||a=='u')--a=='y'\n\ngnums [] s (a,_) = (a, read $ reverse s :: Int)\ngnums (' ':xs) s _ = gnums xs [] (read $ reverse s :: Int,1)\ngnums (x:xs) s a = gnums xs (x:s) a\n\ngetLyr 0 a _ = return a\ngetLyr i a n = do \n\t\t\t\tx <- getLine\n\t\t\t\tgetLyr (i-1) ((gsfx n (reverse x) []):a) n\n\ngsfx _ [] a = a\ngsfx 1 (x:xs) a = if (glasn x) then (x:a) else gsfx 1 xs (x:a)\ngsfx n (x:xs) a = if (glasn x) then gsfx (n-1) xs (x:a) else gsfx n xs (x:a)\n\n-- find type for one lir\nfind :: [String] -> String -> String -> String -> String\nfind [] _ _ akk = reverse akk\nfind (x:xs) a b akk | (a == []) = find xs x b ('a':akk)\n | ((x /= a) && (b == [])) = find xs a x ('b':akk)\n | (x == a) = find xs a b ('a':akk)\n | (x == b) = find xs a b ('b':akk)\n | otherwise = []\n\nsolve :: Int -> [String] -> [String] -> String -> String\nsolve 4 list lakk takk | (((takk == [])||(takk == \"aaaa\"))&&(foldr (||) False (map (newT==) rifm)))= solve 0 list [] newT\n | ((takk == newT)||(newT == \"aaaa\")) = solve 0 list [] takk\n | otherwise = \"NO\"\n where newT = (find lakk [] [] [])\nsolve _ [] _ t = t\nsolve n (x:xs) lakk t = solve (n+1) xs (x:lakk) t\n\nmain = do\n\t\t\tsnums <- getLine\n\t\t\tlet n = gnums snums [] (0,0) in\n\t\t\t\tdo\n\t\t\t\t\tlyrics <- getLyr ((fst n)*4) [] (snd n)\n\t\t\t\t\tputStrLn $ solve 0 lyrics [] []\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Data.Maybe\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\ndata RhymeScheme = None | Any | Aabb | Abba | Abab\n deriving (Eq,Show)\n\nscheme [s1,s2,s3,s4]\n | s1 == s2 && s1 == s3 && s1 == s4 = Any\n | s1 == s2 && s3 == s4 = Aabb\n | s1 == s3 && s2 == s4 = Abab\n | s1 == s4 && s2 == s3 = Abba\n | otherwise = None\n\ncombine :: RhymeScheme -> RhymeScheme -> RhymeScheme\ncombine None _ = None\ncombine Any r = r\ncombine r s = if r == s then r else None\n\ncommonScheme as = go Any as\n where go r [] = r\n go r (a:as) = case combine r a of\n None -> None\n s -> go s as\n\ntrimRight :: ByteString -> ByteString\ntrimRight bs = BS.take n bs\n where n = find (BS.length bs-1)\n find k | k < 0 = k+1\n | isSpace (BS.index bs k) = find (k-1)\n | otherwise = (k+1)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf n as =\n case splitAt n as of\n (bs,[]) -> [bs]\n (bs,cs) -> bs : chunksOf n cs\n\nisVowel 'a' = True\nisVowel 'e' = True\nisVowel 'i' = True\nisVowel 'o' = True\nisVowel 'u' = True\nisVowel _ = False\n\nsuffix :: Int -> ByteString -> Maybe ByteString\nsuffix k bs = go k (BS.length bs)\n where go 0 i = Just $ BS.drop i bs\n go _ 0 = Nothing\n go k i = if isVowel (BS.index bs (i-1))\n then go (k-1) (i-1)\n else go k (i-1)\n\nsolve k lines =\n if all isJust suffixes\n then commonScheme schemes\n else None\n where\n suffixes = map (suffix k) lines\n quatrains = chunksOf 4 (map fromJust suffixes)\n schemes = map scheme quatrains\n\nmain = do\n (n:k:_) <- map read <$> words <$> getLine\n lines <- replicateM (4*n) $ trimRight <$> BS.getLine\n let answer =\n case solve k lines of\n None -> \"NO\"\n Any -> \"aaaa\"\n Aabb -> \"aabb\"\n Abba -> \"abba\"\n Abab -> \"abab\"\n putStrLn answer\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as BS\n\nimport Control.Monad\n\nvowel x = x `elem` \"aeiou\"\n\ncombineTypes (a1, b1, c1) (a2, b2, c2) =\n (a1 && a2,\n b1 && b2,\n c1 && c2)\n\ngetType k [a, b, c, d] =\n (rhymes k a b && rhymes k c d,\n rhymes k a c && rhymes k b d,\n rhymes k a d && rhymes k b c)\n\nrhymes k a b = (getSuffix a) == (getSuffix b)\n where getSuffix x = fst $ BS.foldr collectSuffix (BS.empty, 0) x\n collectSuffix x (suffix, count) | count >= k = (suffix, count)\n | vowel x = (BS.cons x suffix, \n count + 1)\n | otherwise = (BS.cons x suffix, count)\n\nsolve :: Int -> [[BS.ByteString]] -> String\nsolve k quantrains =\n case generalType of\n (True, False, False) -> \"aabb\"\n (False, True, False) -> \"abab\"\n (False, False, True) -> \"abba\"\n (True, True, True) -> \"aaaa\"\n _ -> \"NO\"\n where generalType = foldl' combineTypes (True, True, True) types\n types = map (getType k) quantrains\n\nmain = do [n, k] <- fmap (map readInt . BS.words) BS.getLine\n quantrains <- replicateM n $ replicateM 4 BS.getLine\n putStrLn $ solve k quantrains\n\nreadInt line = fst $ fromJust $ BS.readInt line"}], "src_uid": "a17bac596b1f060209534cbffdf0f40e"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function (on)\nimport Data.List (sortBy)\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\ngao :: S.Set (Int, Int) -> [((Int, Int), Int)] -> [((Int, Int), Int)]\ngao _ [] = []\ngao r (((c, p), i): cps) =\n case S.lookupGE (c, 0) r of\n Just k@(_, j) -> ((i, j), p): gao (S.delete k r) cps\n Nothing -> gao r cps\n\nmain :: IO ()\nmain = do\n n <- getInt\n cp <- replicateM n $ do\n (c:p:_) <- getInts\n return (c, p)\n _ <- getInt\n r <- S.fromList . flip zip [0..] <$> getInts\n let ans = gao r $ reverse $ sortBy (compare `on` snd . fst) $ zip cp [0 ..]\n putStrLn $ unwords $ map show [length ans, sum $ map snd ans]\n putStr $ unlines $ flip map ans $ \\((i, j), _) ->\n show (i + 1) ++ \" \" ++ show (j + 1)\n where\n getInt = readInt <$> C.getLine\n getInts = map readInt . C.words <$> C.getLine\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n (qs, is) :: ([[Int]], [Int]) <- unzip . sort . (\\l -> zip l [1..]) <$> replicateM n getInts\n\n k <- readLn\n (rs, js) :: ([Int], [Int]) <- unzip . sort . (\\l -> zip l [1..]) <$> getInts\n\n cs :: IOUArray (Int, Int) Int <- newArray ((0, 0), (n, k)) 0\n ps :: IOUArray (Int, Int) Bool <- newArray ((0, 0), (n, k)) False\n\n forM_ (zip [1..n] qs) $ \\(i, [c, p]) -> \n forM_ (zip [1..k] rs) $ \\(j, r) -> do\n ci <- readArray cs (i-1, j)\n cj <- readArray cs (i, j-1)\n cij <- (p +) <$> readArray cs (i-1, j-1)\n\n if c <= r && cij >= ci && cij >= cj\n then do\n writeArray cs (i, j) cij\n writeArray ps (i, j) True\n else do\n writeArray cs (i, j) $ max ci cj\n writeArray ps (i, j) False\n\n cs' :: UArray (Int, Int) Int <- freeze cs\n ps' :: UArray (Int, Int) Bool <- freeze ps\n\n let\n is' :: UArray Int Int = listArray (1, n) is\n js' :: UArray Int Int = listArray (1, k) js\n\n restore 0 _ = []\n restore _ 0 = []\n\n restore i j\n | p = (is'!i, js'!j):(restore (i-1) (j-1))\n | cs'!(i-1, j) == c = restore (i-1) j\n | otherwise = restore i (j-1)\n where\n c = cs'!(i, j)\n p = ps'!(i, j)\n\n let\n ijs = restore n k\n c = cs'!(n, k)\n\n putStrLn $ show (length ijs) ++ \" \" ++ show c\n putStrLn $ unlines $ map (\\(i, j) -> show i ++ \" \" ++ show j) ijs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n rs <- fmap S.fromList . forM [1..n] $ \\i -> do\n [c, p] <- map readInt.B.words <$> B.getLine\n return (p, c, i)\n _m <- getLine\n ts <- S.fromList.(`zip`[1..]).map readInt.B.words <$> B.getLine\n let (m,res,rts) = solve rs ts\n putStrLn $ shows m \" \" ++ show res\n putStr.unlines.map (unwords.map show) $ rts\n\nsolve :: S.Set (Int,Int,Int) -> S.Set (Int,Int) -> (Int,Int,[[Int]])\nsolve rs ts = go 0 0 [] rs ts\n where\n\n go !accept !money res !rs !ts\n | S.null rs = (accept,money,sort res)\n | ((p,c,i),rs') <- S.deleteFindMax rs =\n case S.lookupGE (c,0) ts of\n Just (t,j) -> go (accept+1)\n (money+p)\n ([i,j]:res)\n rs'\n (S.delete (t,j) ts)\n Nothing -> go accept money res rs' ts\n"}, {"source_code": "--{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function (on)\nimport Data.List (sortBy)\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map readInt . C.words <$> C.getLine\n\ngetInt :: IO Int\ngetInt = readInt <$> C.getLine\n\ngao :: S.Set(Int, Int) -> [((Int, Int), Int)] -> [((Int, Int), Int)]\ngao _ [] = []\ngao set (((c, p), i) : xs) = \n case S.lookupGE (c, 0) set of\n Just k@(_, j) -> ((i, j), p) : gao (S.delete k set) xs\n Nothing -> gao set xs\n\nmain :: IO ()\nmain = do\n n <- getInt\n arr <- replicateM n $ do\n [c, p] <- getInts\n return (c, p)\n m <- getInt\n set <- S.fromList . flip zip [0..] <$> getInts\n let ans = gao set $ reverse . sortBy (compare `on` snd . fst) $ zip arr [0..]\n putStrLn $ unwords $ map show [length ans, sum $ map snd ans]\n putStr $ unlines . flip map ans $ \\((i, j), _) -> show (i + 1) ++ \" \" ++ show (j + 1)\n"}], "negative_code": [], "src_uid": "ac4e4aca1146d7ad706c4ea12c90caf6"} {"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\n\nimport Data.Array\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as L\n\nmain :: IO ()\nmain = do\n\t(l:ls) <- L.lines `fmap` L.getContents\n\tlet n = fst . fromJust . L.readInt $ l\n\tlet strings = listArray (1, 2 * n) . concatMap L.words . init $ ls\n\tlet nums = map (fst . fromJust . L.readInt) . L.words . last $ ls\n\tprintResult . isLexographic strings $ nums \n\nisLexographic :: Array Int L.ByteString -> [Int] -> Bool\nisLexographic strings (ix:ixs) = foldl' process start ixs /= \"\" \n\twhere\n\t\tixMap x = let (!f, !s) = (strings ! (2 * x - 1), strings ! (2 * x)) in if f <= s then (f, s) else (s, f)\n\t\tstart = fst . ixMap $ ix\n\t\tprocess !acc !x\n\t\t\t| acc == \"\" = \"\"\n\t\t\t| otherwise = if acc <= f\n\t\t\t\t\t\t\tthen f\n\t\t\t\t\t\t\telse if acc <= s\n\t\t\t\t\t\t\t\tthen s\n\t\t\t\t\t\t\t\telse \"\"\n\t\t\twhere !(f, s) = ixMap x\nisLexographic _ _ = True\n\nprintResult :: Bool -> IO ()\nprintResult b = putStrLn (if b then \"YES\" else \"NO\") ", "positive_code": [{"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (readLn >>= (`replicateM` B.getLine)) <*> (map (fst . fromJust . B.readInt) . B.words <$> B.getLine) >>= putStrLn . yesno\n\nsolve :: [B.ByteString] -> [Int] -> Bool\nsolve names hs = hs `isContainedIn` map snd (sort $ concat [ zip (B.words name) (repeat i) | (i, name) <- zip [1..] names ])\n\nisContainedIn :: Eq a => [a] -> [a] -> Bool\nisContainedIn xxs@(x:xs) (y:ys) | x == y = isContainedIn xs ys\n | otherwise = isContainedIn xxs ys\nisContainedIn [] _ = True\nisContainedIn _ _ = False\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = solve <$> (readLn >>= (`replicateM` B.getLine)) <*> (map read . words <$> getLine) >>= putStrLn . yesno\n\nsolve :: [B.ByteString] -> [Int] -> Bool\nsolve names hs = hs `isContainedIn` map snd (sort $ concat [ zip (B.words name) (repeat i) | (i, name) <- zip [1..] names ])\n\nisContainedIn :: Eq a => [a] -> [a] -> Bool\nisContainedIn xxs@(x:xs) (y:ys) | x == y = isContainedIn xs ys\n | otherwise = isContainedIn xxs ys\nisContainedIn [] _ = True\nisContainedIn _ _ = False\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n (names, permStrs) <- splitAt (2*n).B.words <$> B.getContents\n putStrLn.bool\"YES\"\"NO\"$ solve (perse n names) $ map (subtract 1.readInt) permStrs\n\nperse :: Int -> [B.ByteString] -> (Array Int B.ByteString, Array Int B.ByteString)\nperse n bss = runST $ do\n fname <- newArray_ (0,n-1) :: ST s (STArray s Int B.ByteString)\n sname <- newArray_ (0,n-1) :: ST s (STArray s Int B.ByteString)\n let go !i (fn:sn:rest) = do\n unsafeWrite fname i $! fn\n unsafeWrite sname i $! sn\n go (i+1) rest\n go _ _ = (,) <$> unsafeFreeze fname <*> unsafeFreeze sname\n go 0 bss\n\nsolve :: (Array Int B.ByteString, Array Int B.ByteString) -> [Int] -> Bool\nsolve (fname,sname) (p0:perm) = go (min (unsafeAt fname p0) (unsafeAt sname p0)) perm\n where\n go !cur (p:rest) = case [name | name<-[unsafeAt fname p, unsafeAt sname p],cur < name] of\n [] -> False\n names -> go (minimum names) rest\n go _ _ = True\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nmain = do\n [n] <- getInts\n names <- Arr.listArray (0, n-1) <$> replicateM n (B.words <$> B.getLine)\n perm <- getInts\n let permed = map (\\i -> names ! (i - 1)) perm\n let\n solution = go (B.pack \"\") permed where\n go prev [] = \"YES\"\n go prev (l : ls) = case sort (filter (>prev) l) of\n (h : _) -> go h ls\n [] -> \"NO\"\n putStrLn $ solution\n\n\n-- helper functions --\n\nreadInt = fst . fromJust . B.readInt\ngetInts = map readInt . B.words <$> B.getLine\n\nmemoArr :: Ix i => (i, i) -> (i -> r) -> (i -> r)\nmemoArr range f = f' where\n f' i\n | Arr.inRange range i = arr ! i\n | otherwise = f i\n arr = Arr.listArray range (map f (Arr.range range))\n\ndpArr :: Ix i => (i, i) -> ((i -> r) -> (i -> r)) -> (i -> r)\ndpArr ixs f = fix (memoArr ixs . f)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\n\nimport Data.Array\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as L\n\nmain :: IO ()\nmain = do\n (l:ls) <- L.lines `fmap` L.getContents\n let n = fst . fromJust . L.readInt $ l\n let strings = listArray (1, 2 * n) . concatMap L.words . init $ ls\n let nums = map (fst . fromJust . L.readInt) . L.words . last $ ls\n printResult . isLexographic strings $ nums \n\nisLexographic :: Array Int L.ByteString -> [Int] -> Bool\nisLexographic strings (ix:ixs) = foldl' process start ixs /= \"\" \n where\n ixMap x = let (!f, !s) = (strings ! (2 * x - 1), strings ! (2 * x)) in if f <= s then (f, s) else (s, f)\n start = fst . ixMap $ ix\n process !acc !x\n | acc == \"\" = \"\"\n | otherwise = if acc <= f\n then f\n else if acc <= s\n then s\n else \"\"\n where !(f, s) = ixMap x\nisLexographic _ _ = True\n\nprintResult :: Bool -> IO ()\nprintResult b = putStrLn (if b then \"YES\" else \"NO\") \n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n n <- readLn\n ss <- replicateM n $ l2p . sort . B.words <$> B.getLine\n ps <- readInts\n let a = listArray (1,n) ss :: Array Int (B.ByteString,B.ByteString)\n go [] s = True\n go ((s1,s2):ss) s | s < s1 = go ss s1 \n | s < s2 = go ss s2 \n | otherwise = False where\n putStrLn $ if (go (map (a !) ps) (B.pack \"\")) then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\n\nimport Data.Array\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nmain :: IO ()\nmain = do\n\t(l:ls) <- L.lines `fmap` L.getContents\n\tlet n = fst . fromJust . L.readInt $ l\n\tlet strings = listArray (1, 2 * n) . concatMap L.words . init $ ls\n\tlet nums = map (fst . fromJust . L.readInt) . L.words . last $ ls\n\tprintResult . isLexographic strings $ nums \n\nisLexographic :: Array Int L.ByteString -> [Int] -> Bool\nisLexographic strings (ix:ixs) = foldl' process start ixs /= \"\" \n\twhere\n\t\tixMap x = let (!f, !s) = (strings ! (2 * x - 1), strings ! (2 * x)) in if f <= s then (f, s) else (s, f)\n\t\tstart = fst . ixMap $ ix\n\t\tprocess !acc !x\n\t\t\t| acc == \"\" = \"\"\n\t\t\t| otherwise = if acc <= f\n\t\t\t\t\t\t\tthen f\n\t\t\t\t\t\t\telse if acc <= s\n\t\t\t\t\t\t\t\tthen s\n\t\t\t\t\t\t\t\telse \"\"\n\t\t\twhere !(f, s) = ixMap x\nisLexographic _ _ = True\n\nprintResult :: Bool -> IO ()\nprintResult b = putStrLn (if b then \"YES\" else \"NO\") "}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\n\nimport Data.Array\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nmain :: IO ()\nmain = do\n\t(l:ls) <- L.lines `fmap` L.getContents\n\tlet n = fst . fromJust . L.readInt $ l\n\tlet strings = listArray (1, 2 * n) . concatMap L.words . init $ ls\n\tlet nums = map (fst . fromJust . L.readInt) . L.words . last $ ls\n\tprintResult . isLexographic strings $ nums \n\nisLexographic :: Array Int L.ByteString -> [Int] -> Bool\nisLexographic strings (ix:ixs) = foldl' process start ixs /= \"\" \n\twhere\n\t\tixMap x = (strings ! (2 * x - 1), strings ! (2 * x))\n\t\tstart = let (!f, !s) = ixMap ix in if f <= s then f else s\n\t\tprocess !acc !x\n\t\t\t| acc == \"\" = \"\"\n\t\t\t| otherwise = if acc <= f\n\t\t\t\t\t\t\tthen f\n\t\t\t\t\t\t\telse if acc <= s\n\t\t\t\t\t\t\t\tthen s\n\t\t\t\t\t\t\t\telse \"\"\n\t\t\twhere (!f, !s) = ixMap x\nisLexographic _ _ = True\n\nprintResult :: Bool -> IO ()\nprintResult b = putStrLn (if b then \"YES\" else \"NO\") "}, {"source_code": "{-# LANGUAGE OverloadedStrings, BangPatterns #-}\n\nimport Data.Array\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nmain :: IO ()\nmain = do\n\t(l:ls) <- L.lines `fmap` L.getContents\n\tlet n = fst . fromJust . L.readInt $ l\n\tlet strings = listArray (1, 2 * n) . concatMap L.words . init $ ls\n\tlet nums = map (fst . fromJust . L.readInt) . L.words . last $ ls\n\tprintResult . isLexographic strings $ nums \n\nisLexographic :: Array Int L.ByteString -> [Int] -> Bool\nisLexographic strings ixs = foldl' process \"a\" ixs /= \"\" \n\twhere\n\t\t process !acc !x\n\t\t \t| acc == \"\" = \"\"\n\t\t \t| otherwise = if acc <= f\n\t\t \t\t\t\t\tthen f\n\t\t \t\t\t\t\telse if acc <= s\n\t\t \t\t\t\t\t\tthen s\n\t\t \t\t\t\t\t\telse \"\"\n\t\t \twhere (!f, !s) = (strings ! (2 * x - 1), strings ! (2 * x))\n\nprintResult :: Bool -> IO ()\nprintResult b = putStrLn (if b then \"YES\" else \"NO\") "}], "src_uid": "a48ef749bf54d673772e09025ae806de"} {"source_code": "\r\nimport Control.Monad\r\n\r\n\r\nsolve n y | y<=3 = 0\r\n | y>=n-1 = 0\r\n | otherwise = minimum [abs $ n-2-y,abs $ 2*y - n - 2, abs $ y-4]\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n\r\n replicateM (read ts) $ do\r\n input <- getLine\r\n let n = read $ input ::Int\r\n putStrLn.show. maximum $ [solve n (2*div n 3), solve n (2*div n 3+1),solve n (2*div n 3+2)]\r\n\r\n return ()", "positive_code": [{"source_code": "import Data.Char\n\nbruteForce m = (div m 3) - 1\n\nmain = do\n rawInput <- getContents\n let input = tail $ lines rawInput \n let ns = map read input :: [Int]\n let ms = map (\\n -> n-3) ns\n let output = map bruteForce ms\n putStr (unlines $ map show output)\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve n = min (b-a) (c-b)\r\n where\r\n s = n-3\r\n a = 1 :: Int\r\n b = (s+1) `div` 3\r\n c = s - (a+b)\r\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>= print . minP\nminP n = let x = (div n 3) - 2 in\n max (min (x-1) (n - 4 - 2*x)) (min x (n - 4 - 2*(x+1)))\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n--\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> Int\nsolve n = maximum values\n where\n mid = n `div` 3\n values = do\n l1 <- [1 .. 10]\n l2 <- [mid - 10 .. mid + 10]\n let l3 = n - l1 - l2 - 3\n guard $ l1 > 0\n guard $ l2 > 0\n guard $ l3 > 0\n return $ minimum [abs (l1 - l2), abs (l2 - l3), abs (l3 - l1)]\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n let answer = solve n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "0690e2df87f60e5be34505d9e2817032"} {"source_code": "import Control.Monad\r\n\r\ngetDiv :: Integer -> String\r\ngetDiv x = if (x <= 1399) then \"Division 4\" else if (x <= 1599) then \"Division 3\" else if (x <= 1899) then \"Division 2\" else \"Division 1\"\r\n\r\nmain :: IO ()\r\nmain = do \r\n t <- getLine\r\n nrs <- replicateM (read t) getLine\r\n mapM_ putStrLn $ map getDiv $ map (read :: String -> Integer) nrs", "positive_code": [{"source_code": "division :: Int -> String\ndivision x | x >= 1900 = \"Division 1\" | x >= 1600 = \"Division 2\" | x >= 1400 = \"Division 3\" | otherwise = \"Division 4\"\n\nsolve :: [Int] -> [String]\nsolve xs = map division $ xs \n\nmain :: IO()\nmain = interact $ unlines . solve . tail . map read . words"}, {"source_code": "parseInt :: String -> Int\r\nparseInt s = read s :: Int\r\n \r\nreadInt :: IO Int\r\nreadInt = parseInt <$> getLine\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n arr <- words <$> getLine\r\n pure $ map parseInt arr\r\n \r\ncalc :: Int -> String\r\ncalc x\r\n | x < 1400 = \"Division 4\"\r\n | x < 1600 = \"Division 3\"\r\n | x < 1900 = \"Division 2\"\r\n | otherwise = \"Division 1\"\r\n \r\nsolve :: IO ()\r\nsolve = do\r\n rating <- readInt\r\n putStrLn $ calc rating\r\n \r\nfor :: Int -> IO () -> IO ()\r\nfor 0 _ = pure ()\r\nfor i f = do\r\n f\r\n for (i - 1) f\r\n \r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n for n solve"}, {"source_code": "main :: IO ()\nmain = interact $ unlines . map(f.(read::String->Int)).tail .words\nf a\n |a <1400 = \"Division 4\"\n |a <1600 = \"Division 3\"\n |a <1900 = \"Division 2\"\n |otherwise = \"Division 1\""}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> Int\nsolve rating\n | 1_900 <= rating = 1\n | 1_600 <= rating && rating <= 1_899 = 2\n | 1_400 <= rating && rating <= 1_599 = 3\n | rating <= 1_399 = 4\n \n\n\nmain :: IO ()\nmain = do\n n <- B8.getLine <&> readIntB8\n replicateM_ n $ do\n rating <- B8.getLine <&> readIntB8\n let answer = solve rating\n printf \"Division %d\\n\" answer\n"}], "negative_code": [{"source_code": "division :: Int -> String\r\ndivision x | x >= 1900 = \"Division 1\" | x >= 1600 = \"Division 2\" | x >= 1400 = \"Division 3\" | otherwise = \"Division 4\"\r\n\r\nmain :: IO()\r\nmain = interact $ unlines . map show . map division . tail . map read . words"}, {"source_code": "division :: Int -> String\ndivision x | x >= 1900 = \"Division 1\" | x >= 1600 = \"Division 2\" | x >= 1400 = \"Division 3\" | otherwise = \"Division 4\"\n\nmain :: IO()\nmain = interact $ show . unwords . map division . tail . map read . words"}, {"source_code": "division :: Int -> String\ndivision x | x >= 1900 = \"Division 1 \" | x >= 1600 = \"Division 2 \" | x >= 1400 = \"Division 3 \" | otherwise = \"Division 4 \"\n\nmain :: IO()\nmain = interact $ show . unlines . map division . tail . map read . words"}, {"source_code": "division :: Int -> String\ndivision x | x >= 1900 = \"Division 1\" | x >= 1600 = \"Division 2\" | x >= 1400 = \"Division 3\" | otherwise = \"Division 4\"\n\nmain :: IO()\nmain = interact $ show . unlines . map division . tail . map read . words"}, {"source_code": "division :: Int -> String\ndivision x | x >= 1900 = \"Division 1\" | x >= 1600 = \"Division 2\" | x >= 1400 = \"Division 3\" | otherwise = \"Division 4\"\n\nmain :: IO()\nmain = interact $ unlines . map show . map division . tail . map read . words"}, {"source_code": "division :: Int -> String\ndivision x | x >= 1900 = \"Division 1\\n\" | x >= 1600 = \"Division 2\\n\" | x >= 1400 = \"Division 3\\n\" | otherwise = \"Division 4\\n\"\n\nmain :: IO()\nmain = interact $ unlines . map show . map division . tail . map read . words"}, {"source_code": "import Control.Monad\r\n\r\ngetDiv :: Integer -> String\r\ngetDiv x = if (x <= 1399) then \"Division 4\" else if (x <= 1599) then \"Division 3\" else if (x <= 1899) then \"Division 2\" else \"Division 1\"\r\n\r\nmain :: IO ()\r\nmain = do \r\n t <- getLine\r\n nrs <- replicateM (read t) getLine\r\n mapM_ print $ map getDiv $ map (read :: String -> Integer) nrs"}, {"source_code": "parseInt :: String -> Int\r\nparseInt s = read s :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = parseInt <$> getLine\r\n\r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n arr <- words <$> getLine\r\n pure $ map parseInt arr\r\n\r\ncalc :: Int -> String\r\ncalc x\r\n | x < 1400 = \"Division 4\"\r\n | x < 1600 = \"Division 3\"\r\n | x < 1900 = \"Division 2\"\r\n | otherwise = \"Division 1\"\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n rating <- readInt\r\n print $ calc rating\r\n\r\nfor :: Int -> IO () -> IO ()\r\nfor 0 _ = pure ()\r\nfor i f = do\r\n f\r\n for (i - 1) f\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n for n solve"}], "src_uid": "020c7b64688736ecc5e97d17df2c2605"} {"source_code": "import qualified Data.List as L\ngetRoute a b c i = (sum (take i a)) + (sum (drop i b)) + (c !! i) \nmain=do\n w0 <-getLine\n let n=read w0::Int\n w1 <- getLine\n let a=[read n::Int|n<-words(w1)]\n w2 <- getLine\n let b=[read n::Int|n<-words(w2)]\n w3 <- getLine\n let c=[read n::Int|n<-words(w3)]\n let s=L.sort $ map (getRoute a b c) [0..(n-1)]\n print ((s !! 0)+(s !! 1))\n \n", "positive_code": [{"source_code": "import Data.List\n\nreadInts = getLine >>= (\\line -> return (map read (words line) :: [Int]))\n\ncross a1 a2 n [] 0 = []\ncross a1 a2 n (r : rs) x = (sum (take c a1) + sum (drop c a2) + r) : (cross a1 a2 n rs (x - 1)) where c = n - x\n\nmain = do\n n <- (readInts >>= (\\l -> return (head l)))\n a1 <- readInts\n a2 <- readInts\n s <- readInts\n let x : y : _ = sort (cross a1 a2 n s n)\n putStrLn (show (x + y))\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve a = let n = head a\n r1 = drop 1 a\n a1 = take (n - 1) r1\n r2 = drop (n - 1) r1\n a2 = take (n - 1) r2\n b = drop (n - 1) r2\n in solve' n a1 a2 b\n\nsolve' :: Int -> [Int] -> [Int] -> [Int] -> Int\nsolve' n a1 a2 b = let p = sort $ map (dist a1 a2 b) [0..(n-1)]\n in (head p) + (p !! 1)\n\ndist :: [Int] -> [Int] -> [Int] -> Int -> Int\ndist a1 a2 b i = (sum (take i a1)) + (sum (drop i a2)) + (b !! i)\n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n r1 <- fmap ((map read) . words) getLine :: IO [Int]\n r2 <- fmap ((map read) . words) getLine :: IO [Int]\n imd <- fmap ((map read) . words) getLine :: IO [Int]\n let p1 = scanl (+) 0 r1\n p2 = scanr (+) 0 r2\n list = zip (go p1 p2 imd) [1..]\n ans = minimum [x+y | (x,n1) <-list , (y,n2)<-list , n1/=n2]\n print ans\n\ngo p1 p2 imd = zipWith3 (\\x y z -> x+y+z) p1 p2 imd"}], "negative_code": [], "src_uid": "e3e0625914fdc08950601248b1278f7d"} {"source_code": "import Control.Monad (forM_)\nimport Data.List (sortBy, findIndex)\n\n-- fst of first time when snd >= fst \n-- if snd never becomes >= fst, then snd of last item\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = rez\n where z = zip as bs\n sf x y = compare (fst y) (fst x)\n scf x y = (fst y, snd x + snd y)\n scl = tail . scanl scf (0, 0) $ sortBy sf z\n mi = findIndex (\\(x, y) -> y > x) scl\n rez = case mi of \n Just i -> rez' i\n Nothing -> snd $ last scl\n rez' i = if i == 0 then fst (head scl) else max (snd $ scl !! (i - 1)) (fst (scl !! i))\n\nmain :: IO ()\nmain = getLine >>= pure . read >>= \\t -> forM_ [1..t] . const $ getLine >> do\n as <- pure . map read . words =<< getLine\n bs <- pure . map read . words =<< getLine\n putStrLn . show $ solve as bs\n \n", "positive_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (sortBy, genericSplitAt)\n\n-- * Types and utilities\n\n-- | A splitting strategy.\ndata Splitter a = Splitter { delimiter :: Delimiter a\n -- ^ What delimiter to split on\n , delimPolicy :: DelimPolicy\n -- ^ What to do with delimiters (drop\n -- from output, keep as separate\n -- elements in output, or merge with\n -- previous or following chunks)\n , condensePolicy :: CondensePolicy\n -- ^ What to do with multiple\n -- consecutive delimiters\n , initBlankPolicy :: EndPolicy\n -- ^ Drop an initial blank?\n , finalBlankPolicy :: EndPolicy\n -- ^ Drop a final blank?\n }\n\n-- | The default splitting strategy: keep delimiters in the output\n-- as separate chunks, don't condense multiple consecutive\n-- delimiters into one, keep initial and final blank chunks.\n-- Default delimiter is the constantly false predicate.\n--\n-- Note that 'defaultSplitter' should normally not be used; use\n-- 'oneOf', 'onSublist', or 'whenElt' instead, which are the same as\n-- the 'defaultSplitter' with just the delimiter overridden.\n--\n-- The 'defaultSplitter' strategy with any delimiter gives a\n-- maximally information-preserving splitting strategy, in the sense\n-- that (a) taking the 'concat' of the output yields the original\n-- list, and (b) given only the output list, we can reconstruct a\n-- 'Splitter' which would produce the same output list again given\n-- the original input list. This default strategy can be overridden\n-- to allow discarding various sorts of information.\ndefaultSplitter :: Splitter a\ndefaultSplitter = Splitter { delimiter = Delimiter [const False]\n , delimPolicy = Keep\n , condensePolicy = KeepBlankFields\n , initBlankPolicy = KeepBlank\n , finalBlankPolicy = KeepBlank\n }\n\n-- | A delimiter is a list of predicates on elements, matched by some\n-- contiguous subsequence of a list.\nnewtype Delimiter a = Delimiter [a -> Bool]\n\n-- | Try to match a delimiter at the start of a list, either failing\n-- or decomposing the list into the portion which matched the delimiter\n-- and the remainder.\nmatchDelim :: Delimiter a -> [a] -> Maybe ([a],[a])\nmatchDelim (Delimiter []) xs = Just ([],xs)\nmatchDelim (Delimiter _) [] = Nothing\nmatchDelim (Delimiter (p:ps)) (x:xs)\n | p x = matchDelim (Delimiter ps) xs >>= \\(h,t) -> Just (x:h,t)\n | otherwise = Nothing\n\n-- | What to do with delimiters?\ndata DelimPolicy = Drop -- ^ Drop delimiters from the output.\n | Keep -- ^ Keep delimiters as separate chunks\n -- of the output.\n | KeepLeft -- ^ Keep delimiters in the output,\n -- prepending them to the following\n -- chunk.\n | KeepRight -- ^ Keep delimiters in the output,\n -- appending them to the previous chunk.\n deriving (Eq, Show)\n\n-- | What to do with multiple consecutive delimiters?\ndata CondensePolicy = Condense -- ^ Condense into a single delimiter.\n | DropBlankFields -- ^ Keep consecutive\n -- delimiters separate, but\n -- don't insert blank chunks in\n -- between them.\n | KeepBlankFields -- ^ Insert blank chunks\n -- between consecutive\n -- delimiters.\n deriving (Eq, Show)\n\n-- | What to do with a blank chunk at either end of the list\n-- (/i.e./ when the list begins or ends with a delimiter).\ndata EndPolicy = DropBlank | KeepBlank\n deriving (Eq, Show)\n\n-- | Tag chunks as delimiters or text.\ndata Chunk a = Delim [a] | Text [a]\n deriving (Show, Eq)\n\n-- | Internal representation of a split list that tracks which pieces\n-- are delimiters and which aren't.\ntype SplitList a = [Chunk a]\n\n-- | Untag a 'Chunk'.\nfromElem :: Chunk a -> [a]\nfromElem (Text as) = as\nfromElem (Delim as) = as\n\n-- | Test whether a 'Chunk' is a delimiter.\nisDelim :: Chunk a -> Bool\nisDelim (Delim _) = True\nisDelim _ = False\n\n-- | Test whether a 'Chunk' is text.\nisText :: Chunk a -> Bool\nisText (Text _) = True\nisText _ = False\n\n-- * Implementation\n\n-- | Given a delimiter to use, split a list into an internal\n-- representation with chunks tagged as delimiters or text. This\n-- transformation is lossless; in particular,\n--\n-- @\n-- 'concatMap' 'fromElem' ('splitInternal' d l) == l.\n-- @\nsplitInternal :: Delimiter a -> [a] -> SplitList a\nsplitInternal _ [] = []\nsplitInternal d xxs\n | null xs = toSplitList match\n | otherwise = Text xs : toSplitList match\n where\n (xs,match) = breakDelim d xxs\n\n toSplitList Nothing = []\n toSplitList (Just ([],r:rs)) = Delim [] : Text [r] : splitInternal d rs\n toSplitList (Just (delim,rest)) = Delim delim : splitInternal d rest\n\nbreakDelim :: Delimiter a -> [a] -> ([a],Maybe ([a],[a]))\nbreakDelim (Delimiter []) xs = ([],Just ([],xs))\nbreakDelim _ [] = ([],Nothing)\nbreakDelim d xxs@(x:xs) =\n case matchDelim d xxs of\n Nothing -> let (ys,match) = breakDelim d xs in (x:ys,match)\n Just match -> ([], Just match)\n\n-- | Given a split list in the internal tagged representation, produce\n-- a new internal tagged representation corresponding to the final\n-- output, according to the strategy defined by the given\n-- 'Splitter'.\npostProcess :: Splitter a -> SplitList a -> SplitList a\npostProcess s = dropFinal (finalBlankPolicy s)\n . dropInitial (initBlankPolicy s)\n . doMerge (delimPolicy s)\n . doDrop (delimPolicy s)\n . insertBlanks (condensePolicy s)\n . doCondense (condensePolicy s)\n\n-- | Drop delimiters if the 'DelimPolicy' is 'Drop'.\ndoDrop :: DelimPolicy -> SplitList a -> SplitList a\ndoDrop Drop l = [ c | c@(Text _) <- l ]\ndoDrop _ l = l\n\n-- | Condense multiple consecutive delimiters into one if the\n-- 'CondensePolicy' is 'Condense'.\ndoCondense :: CondensePolicy -> SplitList a -> SplitList a\ndoCondense Condense ls = condense' ls\n where condense' [] = []\n condense' (c@(Text _) : l) = c : condense' l\n condense' l = (Delim $ concatMap fromElem ds) : condense' rest\n where (ds,rest) = span isDelim l\ndoCondense _ ls = ls\n\n-- | Insert blank chunks between any remaining consecutive delimiters\n-- (unless the condense policy is 'DropBlankFields'), and at the\n-- beginning or end if the first or last element is a delimiter.\ninsertBlanks :: CondensePolicy -> SplitList a -> SplitList a\ninsertBlanks _ [] = [Text []]\ninsertBlanks cp (d@(Delim _) : l) = Text [] : insertBlanks' cp (d:l)\ninsertBlanks cp l = insertBlanks' cp l\n\n-- | Insert blank chunks between consecutive delimiters.\ninsertBlanks' :: CondensePolicy -> SplitList a -> SplitList a\ninsertBlanks' _ [] = []\ninsertBlanks' cp@DropBlankFields (d1@(Delim _) : d2@(Delim _) : l)\n = d1 : insertBlanks' cp (d2:l)\ninsertBlanks' cp (d1@(Delim _) : d2@(Delim _) : l)\n = d1 : Text [] : insertBlanks' cp (d2:l)\ninsertBlanks' _ [d@(Delim _)] = [d, Text []]\ninsertBlanks' cp (c : l) = c : insertBlanks' cp l\n\n-- | Merge delimiters into adjacent chunks according to the 'DelimPolicy'.\ndoMerge :: DelimPolicy -> SplitList a -> SplitList a\ndoMerge KeepLeft = mergeLeft\ndoMerge KeepRight = mergeRight\ndoMerge _ = id\n\n-- | Merge delimiters with adjacent chunks to the right (yes, that's\n-- not a typo: the delimiters should end up on the left of the\n-- chunks, so they are merged with chunks to their right).\nmergeLeft :: SplitList a -> SplitList a\nmergeLeft [] = []\nmergeLeft ((Delim d) : (Text c) : l) = Text (d++c) : mergeLeft l\nmergeLeft (c : l) = c : mergeLeft l\n\n-- | Merge delimiters with adjacent chunks to the left.\nmergeRight :: SplitList a -> SplitList a\nmergeRight [] = []\n-- below fanciness is with the goal of laziness: we want to start returning\n-- stuff before we've necessarily discovered a delimiter, in case we're\n-- processing some infinite list with no delimiter\nmergeRight ((Text c) : l) = Text (c++d) : mergeRight lTail\n where (d, lTail) = case l of\n Delim d' : l' -> (d', l')\n _ -> ([], l)\nmergeRight (c : l) = c : mergeRight l\n\n-- | Drop an initial blank chunk according to the given 'EndPolicy'.\ndropInitial :: EndPolicy -> SplitList a -> SplitList a\ndropInitial DropBlank (Text [] : l) = l\ndropInitial _ l = l\n\n-- | Drop a final blank chunk according to the given 'EndPolicy'.\ndropFinal :: EndPolicy -> SplitList a -> SplitList a\ndropFinal _ [] = []\ndropFinal DropBlank l = dropFinal' l\n where dropFinal' [] = []\n dropFinal' [Text []] = []\n dropFinal' (x:xs) = x:dropFinal' xs\ndropFinal _ l = l\n\n-- * Combinators\n\n-- | Split a list according to the given splitting strategy. This is\n-- how to \\\"run\\\" a 'Splitter' that has been built using the other\n-- combinators.\nsplit :: Splitter a -> [a] -> [[a]]\nsplit s = map fromElem . postProcess s . splitInternal (delimiter s)\n\n-- ** Basic strategies\n--\n-- $ All these basic strategies have the same parameters as the\n-- 'defaultSplitter' except for the delimiters.\n\n-- | A splitting strategy that splits on any one of the given\n-- elements. For example:\n--\n-- > split (oneOf \"xyz\") \"aazbxyzcxd\" == [\"aa\",\"z\",\"b\",\"x\",\"\",\"y\",\"\",\"z\",\"c\",\"x\",\"d\"]\noneOf :: Eq a => [a] -> Splitter a\noneOf elts = defaultSplitter { delimiter = Delimiter [(`elem` elts)] }\n\n-- | A splitting strategy that splits on the given list, when it is\n-- encountered as an exact subsequence. For example:\n--\n-- > split (onSublist \"xyz\") \"aazbxyzcxd\" == [\"aazb\",\"xyz\",\"cxd\"]\n--\n-- Note that splitting on the empty list is a special case, which\n-- splits just before every element of the list being split. For example:\n--\n-- > split (onSublist \"\") \"abc\" == [\"\",\"\",\"a\",\"\",\"b\",\"\",\"c\"]\n-- > split (dropDelims . dropBlanks $ onSublist \"\") \"abc\" == [\"a\",\"b\",\"c\"]\n--\n-- However, if you want to break a list into singleton elements like\n-- this, you are better off using @'chunksOf' 1@, or better yet,\n-- @'map' (:[])@.\nonSublist :: Eq a => [a] -> Splitter a\nonSublist lst = defaultSplitter { delimiter = Delimiter (map (==) lst) }\n\n-- | A splitting strategy that splits on any elements that satisfy the\n-- given predicate. For example:\n--\n-- > split (whenElt (<0)) [2,4,-3,6,-9,1] == [[2,4],[-3],[6],[-9],[1]]\nwhenElt :: (a -> Bool) -> Splitter a\nwhenElt p = defaultSplitter { delimiter = Delimiter [p] }\n\n-- ** Strategy transformers\n\n-- | Drop delimiters from the output (the default is to keep\n-- them). For example,\n--\n-- > split (oneOf \":\") \"a:b:c\" == [\"a\", \":\", \"b\", \":\", \"c\"]\n-- > split (dropDelims $ oneOf \":\") \"a:b:c\" == [\"a\", \"b\", \"c\"]\ndropDelims :: Splitter a -> Splitter a\ndropDelims s = s { delimPolicy = Drop }\n\n-- | Keep delimiters in the output by prepending them to adjacent\n-- chunks. For example:\n--\n-- > split (keepDelimsL $ oneOf \"xyz\") \"aazbxyzcxd\" == [\"aa\",\"zb\",\"x\",\"y\",\"zc\",\"xd\"]\nkeepDelimsL :: Splitter a -> Splitter a\nkeepDelimsL s = s { delimPolicy = KeepLeft }\n\n-- | Keep delimiters in the output by appending them to adjacent\n-- chunks. For example:\n--\n-- > split (keepDelimsR $ oneOf \"xyz\") \"aazbxyzcxd\" == [\"aaz\",\"bx\",\"y\",\"z\",\"cx\",\"d\"]\nkeepDelimsR :: Splitter a -> Splitter a\nkeepDelimsR s = s { delimPolicy = KeepRight }\n\n-- | Condense multiple consecutive delimiters into one. For example:\n--\n-- > split (condense $ oneOf \"xyz\") \"aazbxyzcxd\" == [\"aa\",\"z\",\"b\",\"xyz\",\"c\",\"x\",\"d\"]\n-- > split (dropDelims $ oneOf \"xyz\") \"aazbxyzcxd\" == [\"aa\",\"b\",\"\",\"\",\"c\",\"d\"]\n-- > split (condense . dropDelims $ oneOf \"xyz\") \"aazbxyzcxd\" == [\"aa\",\"b\",\"c\",\"d\"]\ncondense :: Splitter a -> Splitter a\ncondense s = s { condensePolicy = Condense }\n\n-- | Don't generate a blank chunk if there is a delimiter at the\n-- beginning. For example:\n--\n-- > split (oneOf \":\") \":a:b\" == [\"\",\":\",\"a\",\":\",\"b\"]\n-- > split (dropInitBlank $ oneOf \":\") \":a:b\" == [\":\",\"a\",\":\",\"b\"]\ndropInitBlank :: Splitter a -> Splitter a\ndropInitBlank s = s { initBlankPolicy = DropBlank }\n\n-- | Don't generate a blank chunk if there is a delimiter at the end.\n-- For example:\n--\n-- > split (oneOf \":\") \"a:b:\" == [\"a\",\":\",\"b\",\":\",\"\"]\n-- > split (dropFinalBlank $ oneOf \":\") \"a:b:\" == [\"a\",\":\",\"b\",\":\"]\ndropFinalBlank :: Splitter a -> Splitter a\ndropFinalBlank s = s { finalBlankPolicy = DropBlank }\n\n-- | Don't generate blank chunks between consecutive delimiters.\n-- For example:\n--\n-- > split (oneOf \":\") \"::b:::a\" == [\"\",\":\",\"\",\":\",\"b\",\":\",\"\",\":\",\"\",\":\",\"a\"]\n-- > split (dropInnerBlanks $ oneOf \":\") \"::b:::a\" == [\"\", \":\",\":\",\"b\",\":\",\":\",\":\",\"a\"]\ndropInnerBlanks :: Splitter a -> Splitter a\ndropInnerBlanks s = s { condensePolicy = DropBlankFields }\n\n-- ** Derived combinators\n\n-- | Drop all blank chunks from the output, and condense consecutive\n-- delimiters into one. Equivalent to @'dropInitBlank'\n-- . 'dropFinalBlank' . 'condense'@. For example:\n--\n-- > split (oneOf \":\") \"::b:::a\" == [\"\",\":\",\"\",\":\",\"b\",\":\",\"\",\":\",\"\",\":\",\"a\"]\n-- > split (dropBlanks $ oneOf \":\") \"::b:::a\" == [\"::\",\"b\",\":::\",\"a\"]\ndropBlanks :: Splitter a -> Splitter a\ndropBlanks = dropInitBlank . dropFinalBlank . condense\n\n-- | Make a strategy that splits a list into chunks that all start\n-- with the given subsequence (except possibly the first).\n-- Equivalent to @'dropInitBlank' . 'keepDelimsL' . 'onSublist'@.\n-- For example:\n--\n-- > split (startsWith \"app\") \"applyapplicativeapplaudapproachapple\" == [\"apply\",\"applicative\",\"applaud\",\"approach\",\"apple\"]\nstartsWith :: Eq a => [a] -> Splitter a\nstartsWith = dropInitBlank . keepDelimsL . onSublist\n\n-- | Make a strategy that splits a list into chunks that all start\n-- with one of the given elements (except possibly the first).\n-- Equivalent to @'dropInitBlank' . 'keepDelimsL' . 'oneOf'@. For\n-- example:\n--\n-- > split (startsWithOneOf ['A'..'Z']) \"ACamelCaseIdentifier\" == [\"A\",\"Camel\",\"Case\",\"Identifier\"]\nstartsWithOneOf :: Eq a => [a] -> Splitter a\nstartsWithOneOf = dropInitBlank . keepDelimsL . oneOf\n\n-- | Make a strategy that splits a list into chunks that all end with\n-- the given subsequence, except possibly the last. Equivalent to\n-- @'dropFinalBlank' . 'keepDelimsR' . 'onSublist'@. For example:\n--\n-- > split (endsWith \"ly\") \"happilyslowlygnarlylily\" == [\"happily\",\"slowly\",\"gnarly\",\"lily\"]\nendsWith :: Eq a => [a] -> Splitter a\nendsWith = dropFinalBlank . keepDelimsR . onSublist\n\n-- | Make a strategy that splits a list into chunks that all end with\n-- one of the given elements, except possibly the last. Equivalent\n-- to @'dropFinalBlank' . 'keepDelimsR' . 'oneOf'@. For example:\n--\n-- > split (condense $ endsWithOneOf \".,?! \") \"Hi, there! How are you?\" == [\"Hi, \",\"there! \",\"How \",\"are \",\"you?\"]\nendsWithOneOf :: Eq a => [a] -> Splitter a\nendsWithOneOf = dropFinalBlank . keepDelimsR . oneOf\n\n-- ** Convenience functions\n--\n-- These functions implement some common splitting strategies. Note\n-- that all of the functions in this section drop delimiters from\n-- the final output, since that is a more common use case even\n-- though it is not the default.\n\n-- | Split on any of the given elements. Equivalent to @'split'\n-- . 'dropDelims' . 'oneOf'@. For example:\n--\n-- > splitOneOf \";.,\" \"foo,bar;baz.glurk\" == [\"foo\",\"bar\",\"baz\",\"glurk\"]\nsplitOneOf :: Eq a => [a] -> [a] -> [[a]]\nsplitOneOf = split . dropDelims . oneOf\n\n-- | Split on the given sublist. Equivalent to @'split'\n-- . 'dropDelims' . 'onSublist'@. For example:\n--\n-- > splitOn \"..\" \"a..b...c....d..\" == [\"a\",\"b\",\".c\",\"\",\"d\",\"\"]\n--\n-- In some parsing combinator frameworks this is also known as\n-- @sepBy@.\n--\n-- Note that this is the right inverse of the 'Data.List.intercalate' function\n-- from \"Data.List\", that is,\n--\n-- > intercalate x . splitOn x === id\n--\n-- @'splitOn' x . 'Data.List.intercalate' x@ is the identity on\n-- certain lists, but it is tricky to state the precise conditions\n-- under which this holds. (For example, it is not enough to say\n-- that @x@ does not occur in any elements of the input list.\n-- Working out why is left as an exercise for the reader.)\nsplitOn :: Eq a => [a] -> [a] -> [[a]]\nsplitOn = split . dropDelims . onSublist\n\n-- | Split on elements satisfying the given predicate. Equivalent to\n-- @'split' . 'dropDelims' . 'whenElt'@. For example:\n--\n-- > splitWhen (<0) [1,3,-4,5,7,-9,0,2] == [[1,3],[5,7],[0,2]]\nsplitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen = split . dropDelims . whenElt\n\n{-# DEPRECATED sepBy \"Use splitOn.\" #-}\nsepBy :: Eq a => [a] -> [a] -> [[a]]\nsepBy = splitOn\n\n{-# DEPRECATED sepByOneOf \"Use splitOneOf.\" #-}\nsepByOneOf :: Eq a => [a] -> [a] -> [[a]]\nsepByOneOf = splitOneOf\n\n-- | Split into chunks terminated by the given subsequence.\n-- Equivalent to @'split' . 'dropFinalBlank' . 'dropDelims'\n-- . 'onSublist'@. For example:\n--\n-- > endBy \";\" \"foo;bar;baz;\" == [\"foo\",\"bar\",\"baz\"]\n--\n-- Note also that the 'lines' function from \"Data.List\" is equivalent\n-- to @'endBy' \\\"\\\\n\\\"@.\nendBy :: Eq a => [a] -> [a] -> [[a]]\nendBy = split . dropFinalBlank . dropDelims . onSublist\n\n-- | Split into chunks terminated by one of the given elements.\n-- Equivalent to @'split' . 'dropFinalBlank' . 'dropDelims'\n-- . 'oneOf'@. For example:\n--\n-- > endByOneOf \";,\" \"foo;bar,baz;\" == [\"foo\",\"bar\",\"baz\"]\nendByOneOf :: Eq a => [a] -> [a] -> [[a]]\nendByOneOf = split . dropFinalBlank . dropDelims . oneOf\n\n{-# DEPRECATED unintercalate \"Use splitOn.\" #-}\nunintercalate :: Eq a => [a] -> [a] -> [[a]]\nunintercalate = splitOn\n\n-- | Split into \\\"words\\\", with word boundaries indicated by the given\n-- predicate. Satisfies @'Data.List.words' === wordsBy\n-- 'Data.Char.isSpace'@; equivalent to @'split' . 'dropBlanks'\n-- . 'dropDelims' . 'whenElt'@. For example:\n--\n-- > wordsBy (=='x') \"dogxxxcatxbirdxx\" == [\"dog\",\"cat\",\"bird\"]\nwordsBy :: (a -> Bool) -> [a] -> [[a]]\nwordsBy = split . dropBlanks . dropDelims . whenElt\n\n-- | Split into \\\"lines\\\", with line boundaries indicated by the given\n-- predicate. Satisfies @'lines' === linesBy (=='\\n')@; equivalent to\n-- @'split' . 'dropFinalBlank' . 'dropDelims' . 'whenElt'@. For example:\n--\n-- > linesBy (=='x') \"dogxxxcatxbirdxx\" == [\"dog\",\"\",\"\",\"cat\",\"bird\",\"\"]\nlinesBy :: (a -> Bool) -> [a] -> [[a]]\nlinesBy = split . dropFinalBlank . dropDelims . whenElt\n\n-- * Other splitting methods\n\n-- | Standard build function, specialized to building lists.\n--\n-- Usually build is given the rank-2 type\n--\n-- > build :: (forall b. (a -> b -> b) -> b -> b) -> [a]\n--\n-- but since we only use it when @(b ~ [a])@, we give it the more\n-- restricted type signature in order to avoid needing a\n-- non-Haskell2010 extension.\n--\n-- Note that the 0.1.4.3 release of this package did away with a\n-- custom @build@ implementation in favor of importing one from\n-- \"GHC.Exts\", which was (reportedly) faster for some applications.\n-- However, in the interest of simplicity and complete Haskell2010\n-- compliance as @split@ is being included in the Haskel Platform,\n-- version 0.2.1.0 has gone back to defining @build@ manually. This\n-- is in line with @split@'s design philosophy of having efficiency\n-- as a non-goal.\nbuild :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]\nbuild g = g (:) []\n\n-- | @'chunksOf' n@ splits a list into length-n pieces. The last\n-- piece will be shorter if @n@ does not evenly divide the length of\n-- the list. If @n <= 0@, @'chunksOf' n l@ returns an infinite list\n-- of empty lists. For example:\n--\n-- Note that @'chunksOf' n []@ is @[]@, not @[[]]@. This is\n-- intentional, and is consistent with a recursive definition of\n-- 'chunksOf'; it satisfies the property that\n--\n-- @chunksOf n xs ++ chunksOf n ys == chunksOf n (xs ++ ys)@\n--\n-- whenever @n@ evenly divides the length of @xs@.\nchunksOf :: Int -> [e] -> [[e]]\nchunksOf i ls = map (take i) (build (splitter ls)) where\n splitter :: [e] -> ([e] -> a -> a) -> a -> a\n splitter [] _ n = n\n splitter l c n = l `c` splitter (drop i l) c n\n\n{-# DEPRECATED chunk \"Use chunksOf.\" #-}\nchunk :: Int -> [e] -> [[e]]\nchunk = chunksOf\n\n{-# DEPRECATED splitEvery \"Use chunksOf.\" #-}\nsplitEvery :: Int -> [e] -> [[e]]\nsplitEvery = chunksOf\n\n-- | Split a list into chunks of the given lengths. For example:\n--\n-- > splitPlaces [2,3,4] [1..20] == [[1,2],[3,4,5],[6,7,8,9]]\n-- > splitPlaces [4,9] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]]\n-- > splitPlaces [4,9,3] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]]\n--\n-- If the input list is longer than the total of the given lengths,\n-- then the remaining elements are dropped. If the list is shorter\n-- than the total of the given lengths, then the result may contain\n-- fewer chunks than requested, and the last chunk may be shorter\n-- than requested.\nsplitPlaces :: Integral a => [a] -> [e] -> [[e]]\nsplitPlaces is ys = build (splitPlacer is ys) where\n splitPlacer :: Integral i => [i] -> [b] -> ([b] -> t -> t) -> t -> t\n splitPlacer [] _ _ n = n\n splitPlacer _ [] _ n = n\n splitPlacer (l:ls) xs c n = let (x1, x2) = genericSplitAt l xs\n in x1 `c` splitPlacer ls x2 c n\n\n-- | Split a list into chunks of the given lengths. Unlike\n-- 'splitPlaces', the output list will always be the same length as\n-- the first input argument. If the input list is longer than the\n-- total of the given lengths, then the remaining elements are\n-- dropped. If the list is shorter than the total of the given\n-- lengths, then the last several chunks will be shorter than\n-- requested or empty. For example:\n--\n-- > splitPlacesBlanks [2,3,4] [1..20] == [[1,2],[3,4,5],[6,7,8,9]]\n-- > splitPlacesBlanks [4,9] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]]\n-- > splitPlacesBlanks [4,9,3] [1..10] == [[1,2,3,4],[5,6,7,8,9,10],[]]\n--\n-- Notice the empty list in the output of the third example, which\n-- differs from the behavior of 'splitPlaces'.\nsplitPlacesBlanks :: Integral a => [a] -> [e] -> [[e]]\nsplitPlacesBlanks is ys = build (splitPlacer is ys) where\n splitPlacer :: Integral i => [i] -> [b] -> ([b] -> t -> t) -> t -> t\n splitPlacer [] _ _ n = n\n splitPlacer (l:ls) xs c n = let (x1, x2) = genericSplitAt l xs\n in x1 `c` splitPlacer ls x2 c n\n\n-- | A useful recursion pattern for processing a list to produce a new\n-- list, often used for \\\"chopping\\\" up the input list. Typically\n-- chop is called with some function that will consume an initial\n-- prefix of the list and produce a value and the rest of the list.\n--\n-- For example, many common Prelude functions can be implemented in\n-- terms of @chop@:\n--\n-- > group :: (Eq a) => [a] -> [[a]]\n-- > group = chop (\\ xs@(x:_) -> span (==x) xs)\n-- >\n-- > words :: String -> [String]\n-- > words = filter (not . null) . chop (span (not . isSpace) . dropWhile isSpace)\n\nchop :: ([a] -> (b, [a])) -> [a] -> [b]\nchop _ [] = []\nchop f as = b : chop f as'\n where (b, as') = f as\n\n-- | Divides up an input list into a set of sublists, according to 'n' and 'm'\n-- input specifications you provide. Each sublist will have 'n' items, and the\n-- start of each sublist will be offset by 'm' items from the previous one.\n--\n-- > divvy 5 5 [1..20] == [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]\n--\n-- In the case where a source list's trailing elements do no fill an entire\n-- sublist, those trailing elements will be dropped.\n--\n-- > divvy 5 2 [1..10] == [[1,2,3,4,5],[3,4,5,6,7],[5,6,7,8,9]]\n--\n-- As an example, you can generate a moving average over a list of prices:\n-- \n-- > type Prices = [Float]\n-- > type AveragePrices = [Float]\n-- > \n-- > average :: [Float] -> Float\n-- > average xs = sum xs / (fromIntegral $ length xs)\n-- > \n-- > simpleMovingAverage :: Prices -> AveragePrices\n-- > simpleMovingAverage priceList =\n-- > map average divvyedPrices\n-- > where divvyedPrices = divvy 20 1 priceList\n\ndivvy :: Int -> Int -> [a] -> [[a]]\ndivvy _ _ [] = []\ndivvy n m lst = filter (\\ws -> (n == length ws)) choppedl\n where choppedl = chop (\\xs -> (take n xs , drop m xs)) lst\n\n-- fst of first time when snd >= fst \n-- if snd never becomes >= fst, then snd of last item\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = if length spl == 1 then snd . last $ h else m\n where z = zip as bs\n sf x y = compare (fst y) (fst x)\n scf x y = (fst y, snd x + snd y)\n scl = tail . scanl scf (0, 0) $ sortBy sf z\n spl = split (keepDelimsL $ whenElt (\\(f, s) -> s >= f)) scl\n m = max (if length h > 0 then snd . last $ h else 0) (fst . head . head $ tail spl)\n h = head spl\n\nmain :: IO ()\nmain = getLine >>= pure . read >>= \\t -> forM_ [1..t] . const $ getLine >> do\n as <- pure . map read . words =<< getLine\n bs <- pure . map read . words =<< getLine\n putStrLn . show $ solve as bs\n \n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Integer]] -> [Integer]\nprocess [] = []\nprocess (_:as:bs:xss) = solve as bs : process xss\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve as bs = minimum costs\n where\n (as', bs') = unzip . sortBy (comparing fst) $ zip as bs\n costs = zipWith max (scanl max 0 as') (scanr (+) 0 bs')\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List (sortBy)\nimport Data.Maybe (fromMaybe)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain =\n C.interact $\n C.lines >>>\n drop 1 >>>\n map (C.words >>> map readInt) >>>\n process >>> map (show >>> C.pack) >>> C.unlines\n where\n readInt = C.readInt >>> fromMaybe undefined >>> fst >>> fromIntegral\n\nprocess :: [[Integer]] -> [Integer]\nprocess [] = []\nprocess (_:as:bs:xss) = solve as bs : process xss\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve as bs = minimum costs\n where\n (as', bs') = unzip . sortBy (comparing fst) $ zip as bs\n costs = zipWith max (scanl max 0 as') (scanr (+) 0 bs')\n"}], "negative_code": [{"source_code": "import Control.Arrow ((>>>))\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\n\nmain :: IO ()\nmain =\n interact $\n lines >>>\n drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess (_:as:bs:xss) = solve as bs : process xss\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = minimum costs\n where\n (as', bs') = unzip . sortBy (comparing fst) $ zip as bs\n costs = zipWith max (scanl max 0 as') (scanr (+) 0 bs')\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sortBy)\n\nsolve :: String -> String -> Int\nsolve as' bs' = if length fl == 0 then fst . head $ sc else snd . last $ fl\n where as = l as'\n\tbs = l bs'\n\tl = map read . words\n\tts' = zip as bs\n\tts = reverse $ sortBy sf ts'\n\tsf x y = compare (fst x) (fst y)\n\tsc = tail $ scanl (\\(ox, oy) (nx, ny) -> (nx, oy + ny)) (1, 0) ts\n\tfl = filter (\\(x, y) -> x >= y) sc\n\nmain :: IO ()\nmain = do \n t <- pure . read =<< getLine\n forM_ [1..t] . const $ getLine >> getLine >>= \\as -> do \n\tbs <- getLine\n\tputStrLn . show . solve as $ bs\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sortBy)\n\n-- fst of first time when snd >= fst \n-- if snd never becomes >= fst, then snd of last item\n\nsolve :: [Int] -> [Int] -> Int\nsolve as bs = if length fl == 0 then snd $ last scl else fst $ head fl\n where z = zip as bs\n sf x y = compare (fst y) (fst x)\n scf x y = (fst y, snd x + snd y)\n scl = tail . scanl scf (0, 0) $ sortBy sf z\n fl = filter (\\(f, s) -> s >= f) scl\n\nmain :: IO ()\nmain = getLine >>= pure . read >>= \\t -> forM_ [1..t] . const $ getLine >> do\n as <- pure . map read . words =<< getLine\n bs <- pure . map read . words =<< getLine\n putStrLn . show $ solve as bs\n \n"}], "src_uid": "254cb444b9bdfa5e177adad23b7e814a"} {"source_code": "import Array\nmain = interact (ans)\nans theInput = answer where\n theLines = lines theInput\n line0 = words $ head $ theLines\n n = read ( line0 !! 0 ) ::Int\n m = read ( line0 !! 1 ) ::Int\n k0 = read ( line0 !! 2 ) ::Integer\n rMax = div (min n m) 2\n k = if k0 > 5000000 then 5000000 else read ( line0 !! 2 ) ::Int\n theMap = array ((1,1),(n,m)) [((i,j),(take n (tail theLines))!!(i-1)!!(j-1)=='*')|i<-[1..n],j<-[1..m]]\n centerOfCross = [(r,i,j)|r<-[1..rMax],i<-[1+r..n-r],j<-[1+r..m-r],check i j r] ++ repeat (-1,-1,-1) where\n check i j r = and [ ce, up, lo, le, ri ] where\n ce = theMap ! (i,j)\n up = theMap ! (i-r,j)\n lo = theMap ! (i+r,j)\n le = theMap ! (i,j-r)\n ri = theMap ! (i,j+r)\n ans1 = centerOfCross !! (k-1)\n answer = if ans1==(-1,-1,-1)\n then \"-1\"\n else unlines $ map unwords ans0 where\n ans0 = [ce,up,lo,le,ri]\n ce = [show i,show j]\n up = [show (i-r),show j]\n lo = [show (i+r),show j]\n le = [show i,show (j-r)]\n ri = [show i,show (j+r)]\n (r,i,j) = ans1\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Control.Monad\nimport Data.Array\n\nmain = do\n\t[n, m, k] <- fmap (map read . words) getLine\n\ta <- replicateM n getLine\n\tputStr $ head $ (++[\"-1\"]) $ drop (k - 1) $ gao n m $ listArray ((1,1),(n,m)) $ concat a\n\ngao n m a = [unlines $ map (\\(i, j) -> show i ++ \" \" ++ show j) z |\n\tr <- [1 .. min n m - 1],\n\ts <- [[id *** id, flip (-) r *** id, (+r) *** id, id *** flip (-) r, id *** (+r)]],\n\tx <- [r + 1 .. n - r],\n\ty <- [r + 1 .. m - r],\n\ta!(x, y) == '*',\n\tz <- [map (\\k -> k (x, y)) s],\n\tand [a!(i, j) == '*' | (i, j) <- z]]\n\t\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\nimport Data.IORef\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n c <- newIORef 1 :: IO (IORef Int)\n let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n forM_ ([1 .. min n m `quot` 2]) $ \\d -> do\n forM_ [1 + d .. n - d] $ \\i -> do\n forM_ [1 + d .. m - d] $ \\j -> do\n let idx = (i, j)\n when (table ! idx == '*') $ do\n let xs = getOthers idx d\n when ((&&) <$> all (inRange b) <*> all ((== '*') . (table !)) $ xs) $ do\n count <- readIORef c\n writeIORef c (count + 1)\n when (count == k) $ do\n forM_ (idx : xs) $ \\(i', j') -> do\n printf \"%d %d\\n\" i' j'\n exitSuccess\n printf \"-1\\n\"\n\n{-\n7 7 4\n.***...\n.***...\n.***...\n*******\n...*...\n...*...\n...*...\n-}\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n candidates = do\n i <- [1 .. n]\n j <- [1 .. m]\n let x = min i (n - i)\n y = min j (m - j)\n t = min x y\n getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n d <- [t, t - 1 .. 1]\n let xs = getOthers (i, j) d\n guard $ all (inRange b) xs\n guard $ all ((== '*') . (table !)) xs\n return $ (i, j) : xs\n case () of\n _ | length candidates < k -> print (-1)\n | otherwise -> do\n forM_ (candidates !! (k - 1)) $ \\(i, j) -> do\n printf \"%d %d\\n\" i j\n \n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n candidates = do\n i <- [1 .. n]\n j <- [1 .. m]\n let x = min i (n - i)\n y = min j (m - j)\n t = min x y\n getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n d <- [1 .. t]\n let xs = getOthers (i, j) d\n guard $ all (inRange b) xs\n guard $ all ((== '*') . (table !)) xs\n return $ (i, j) : xs\n case () of\n _ | length candidates < k -> print (-1)\n | otherwise -> do\n forM_ (candidates !! (k - 1)) $ \\(i, j) -> do\n printf \"%d %d\\n\" i j\n \n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\nimport Data.Array.Unboxed\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n candidates = do\n i <- [1 .. n]\n j <- [1 .. m]\n let x = min i (n - i)\n y = min j (m - j)\n t = min x y\n getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n d <- [t .. 1]\n let xs = getOthers (i, j) d\n guard $ all (inRange b) xs\n guard $ all ((== '*') . (table !)) xs\n return $ (i, j) : xs\n case () of\n _ | length candidates < k -> print (-1)\n | otherwise -> do\n forM_ (candidates !! (k - 1)) $ \\(i, j) -> do\n printf \"%d %d\\n\" i j\n \n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\nimport Data.IORef\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n c <- newIORef 1 :: IO (IORef Int)\n let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n forM_ (range b) $ \\idx -> do\n when (table ! idx == '*') $ do\n forM_ (takeWhile (all (inRange b)) $ map (getOthers idx) [1 ..]) $ \\xs -> do\n when (all ((== '*') . (table !)) xs) $ do\n count <- readIORef c\n writeIORef c (count + 1)\n when (count == k) $ do\n forM_ (idx : xs) $ \\(i, j) -> do\n printf \"%d %d\\n\" i j\n exitSuccess\n printf \"-1\\n\"\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\nimport Data.IORef\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n c <- newIORef 1 :: IO (IORef Int)\n forM_ (range b) $ \\(i, j) -> do\n let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n forM_ (takeWhile (all (inRange b)) $ map (getOthers (i, j)) [1 ..]) $ \\xs -> do\n when (all ((== '*') . (table !)) xs) $ do\n count <- readIORef c\n writeIORef c (count + 1)\n when (count == k) $ do\n forM_ ((i, j) : xs) $ \\(i', j') -> do\n printf \"%d %d\\n\" i' j'\n exitSuccess\n printf \"-1\\n\"\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\nimport Data.IORef\nimport Data.Array.Unboxed\nimport System.Exit\n{-\n7 7 4\n.***...\n.***...\n.***...\n*******\n...*...\n...*...\n...*...\n-}\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n c <- newIORef 1 :: IO (IORef Int)\n let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n forM_ (range b) $ \\idx -> do\n when (table ! idx == '*') $ do\n let t = min n m `quot` 2 + 1\n forM_ (filter (all (inRange b)) $ map (getOthers idx) [1 .. t]) $ \\xs -> do\n when (all ((== '*') . (table !)) xs) $ do\n count <- readIORef c\n writeIORef c (count + 1)\n when (count == k) $ do\n forM_ (idx : xs) $ \\(i, j) -> do\n printf \"%d %d\\n\" i j\n exitSuccess\n printf \"-1\\n\"\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\nimport Data.IORef\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : m : k : _ <- readData\n cs <- concat <$> replicateM n getLine\n let b = ((1, 1), (n , m))\n table = listArray b cs :: UArray (Int, Int) Char\n c <- newIORef 1 :: IO (IORef Int)\n let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]\n forM_ (range b) $ \\(i, j) -> do\n forM_ (takeWhile (all (inRange b)) $ map (getOthers (i, j)) [1 ..]) $ \\xs -> do\n when (all ((== '*') . (table !)) xs) $ do\n count <- readIORef c\n writeIORef c (count + 1)\n when (count == k) $ do\n forM_ ((i, j) : xs) $ \\(i', j') -> do\n printf \"%d %d\\n\" i' j'\n exitSuccess\n printf \"-1\\n\"\n\n\n{-\n forM_ (range b) $ \\idx -> do\n when (table ! idx == '*') $ do\n forM_ (takeWhile (all (inRange b)) $ map (getOthers idx) [1 ..]) $ \\xs -> do\n when (all ((== '*') . (table !)) xs) $ do\n count <- readIORef c\n writeIORef c (count + 1)\n when (count == k) $ do\n forM_ (idx : xs) $ \\(i, j) -> do\n printf \"%d %d\\n\" i j\n exitSuccess\n printf \"-1\\n\"\n-}\n\n"}, {"source_code": "import Array\nmain = interact (ans)\nans theInput = answer where\n theLines = lines theInput\n line0 = words $ head $ theLines\n n = read ( line0 !! 0 ) ::Int\n m = read ( line0 !! 1 ) ::Int\n k0 = read ( line0 !! 2 ) ::Integer\n rMax = div (min n m) 2\n k = if k0 > 5000000 then 5000000 else read ( line0 !! 2 ) ::Int\n theMap = array ((1,1),(n,m)) [((i,j),(take n (tail theLines))!!(i-1)!!(j-1)=='*')|i<-[1..n],j<-[1..m]]\n centerOfCross = [(r,i,j)|r<-[1..rMax],i<-[1+r..n-r],j<-[1+r..m-r],check i j r] ++ repeat (-1,-1,-1) where\n check i j r = and [ ce, up, lo, le, ri ] where\n ce = theMap ! (i,j)\n up = theMap ! (i-r,j)\n lo = theMap ! (i+r,j)\n le = theMap ! (i,j-r)\n ri = theMap ! (i,j+r)\n ans1 = centerOfCross !! (k-1)\n answer = if ans1==(-1,-1,-1)\n then \"-1\"\n else unlines $ map unwords ans0 where\n ans0 = [ce,up,lo,le,ri]\n ce = [show (i+1),show (j+1)]\n up = [show (i-r+1),show (j+1)]\n lo = [show (i+r+1),show (j+1)]\n le = [show (i+1),show (j-r+1)]\n ri = [show (i+1),show (j+r+1)]\n (r,i,j) = ans1\n"}], "src_uid": "f13be8bcb3291ffcc555a268f421bf3a"} {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n", "positive_code": [{"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\n\nmain = do\n [x1 :: Int, y1, x2, y2] <- (liftM (map read)) . (liftM words) $ getLine\n let generals = [(x1, y) | y <- [(min y1 y2) .. (max y1 y2)]] ++\n [(x2, y) | y <- [(min y1 y2) .. (max y1 y2)]] ++\n [(x, y1) | x <- [(min x1 x2 + 1) .. (max x1 x2 - 1)]] ++\n [(x, y2) | x <- [(min x1 x2 + 1) .. (max x1 x2 - 1)]]\n n <- (liftM read) getLine\n heaters <- replicateM n ((liftM (\\[x, y, r] -> (read x, read y, read r))) . (liftM words) $ getLine)\n putStrLn . show . length $\n filter (\\(x, y) -> all (\\(hx, hy, r) -> (hx - x)*(hx - x) + (hy - y)*(hy - y) > r*r)\n heaters)\n generals\n \n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [xa, ya, xb, yb] <- getInts\n n <- readLn\n cs <- replicateM n getInts\n\n let\n [xa', xb'] = sort [xa, xb]\n [ya', yb'] = sort [ya, yb]\n\n r = length $ filter out $ [(x, ya') | x <- [xa'..xb'-1]] ++ [(xb', y) | y <- [ya'..yb'-1]] ++ [(x, yb') | x <- [xa'+1..xb']] ++ [(xa', y) | y <- [ya'+1..yb']]\n where\n out (x, y) = all (\\[xx, yy, rr] -> (xx-x)^2 + (yy-y)^2 > rr^2) cs\n\n print r\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n"}, {"source_code": "main = interact $ show . solve . input\n\ninput :: String -> ([Int], [[Int]])\ninput str = (coords, circles) where\n circles = map (\\xs -> map read xs) (map words ls)\n coords = map read (words cstr)\n (cstr:_:ls) = lines str\n\nsolve ([xa, ya, xb, yb], circles) = length (filter (\\xy -> all (`outer` xy) circles) coords) where\n [x0, y0, r] `outer` (x, y) = (dx*dx + dy*dy) > (r*r) where\n dx = x - x0\n dy = y - y0\n coords =\n [(x, y) | x <- [xa], y <- ys] ++ \n [(x, y) | x <- [xb], y <- ys] ++\n [(x, y) | x <- xs, y <- [ya]] ++\n [(x, y) | x <- xs, y <- [yb]]\n xs = let mn = min xa xb + 1; mx = max xa xb - 1; in [mn..mx]\n ys = let mn = min ya yb; mx = max ya yb; in [mn..mx]\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}, {"source_code": "\n{-\nimport HUnit\n\ntestWithoutHeater :: Test\ntestWithoutHeater = TestList \"testWithoutHeater\"\n [Test \"SmallBoard\" $\n assertEqList [(0,0), (0,1), (1,0), (1,1)] (solve (0,0,1,1) []),\n Test \"BigBoard\" $\n assertEqList right (solve (0,0,100,200) []),\n Test \"ShiftBoard\" $\n assertEqList [(2,5),(2,6),(3,5),(3,6),(4,5),(4,6)] (solve (2,5,4,6) [])] \n where\n right = [(x, 0) | x <- [1..99]] ++ [(x, 200) | x <- [1..99]]\n ++ [(0, y) | y <- [0..200]] ++ [(100, y) | y <- [0..200]]\n\nrealTest :: Test\nrealTest = Test \"TestReal\" $\n assertEqList [(3,1),(3,-1),(3,-2),(-2,3),(-2,4),(-1,4),(0,4)] (solve (-2,-2,3,4) [(0,0,3),(3,4,2)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\" $\n [Test \"1\" $ assertEq 4 (length (solve (2,5,4,2) [(3,1,2),(5,3,1),(1,3,2)])),\n Test \"2\" $ assertEq 0 (length (solve (5,2,6,3) [(6,2,2),(6,5,3)]))]\n\ntestBig :: Test\ntestBig = Test \"TestBig\" $\n assertEq 8000 (length (solve (1000,1000,-1000,-1000) (replicate 1000 (0,0,1))))\n\ntestNotBig :: Test\ntestNotBig = Test \"TestNotBig\" $\n assertEq [(0,0),(1,0),(7,0),(8,0),(9,0),(15,0),(16,0),(17,0),(23,0),(24,0)]\n (take 10 (solve (0,0,2000,2000) warms))\n where\n warms = [(4 + 8 * x, 0, 2) | x <- [0..250-1]]\n ++ [(2000, 4 + 8 * y, 2) | y <- [0..250-1]]\n ++ [(4 + 8 * x, 2000, 2) | x <- [0..250-1]]\n ++ [(0, 4 + 8 * y, 2) | y <- [0..250-1]]\n\ntestBigBig :: Test\ntestBigBig = Test \"TestBigBig\" $\n assertEq (4 * 3 * 250) (length (solve (0, 0, 2000, 2000) warms))\n where\n warms = [(4 + 8 * x, 0, 2) | x <- [0..250-1]]\n ++ [(2000, 4 + 8 * y, 2) | y <- [0..250-1]]\n ++ [(4 + 8 * x, 2000, 2) | x <- [0..250-1]]\n ++ [(0, 4 + 8 * y, 2) | y <- [0..250-1]]\n\ntestGetPair :: Test\ntestGetPair = Test \"TestGetPair\" $\n assertEq [(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),(1,2),(0,2),(0,1)] (getPair (0,0,3,2))\n\ntestMinDist :: Test\ntestMinDist = Test \"TestMinDist\" $\n assertEq 5 (minDist (0, 0) [(3,4,0), (10,10,1), (-6,8,5)])\n\nallTest :: Test\nallTest = TestList \"AllTest\"\n [testWithoutHeater,\n realTest,\n testInput,\n testBig,\n testNotBig,\n testBigBig,\n testGetPair,\n testMinDist\n ]\n\ntest :: IO ()\ntest = run allTest\n\n--------------------------------------------------------------------------------\n\n-}\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nsolve :: (Int, Int, Int, Int) -> [(Int, Int, Int)] -> [(Int, Int)]\nsolve rectangle warms = solve' (getPair rectangle)\n where\n solve' :: [(Int, Int)] -> [(Int, Int)]\n solve' [] = []\n solve' ps\n | n <= 0 = solve' (drop (-n+1) ps)\n | otherwise = (take n ps) ++ solve' (drop n ps)\n where\n n = minDist (head ps) warms\n\ngetPair :: (Int, Int, Int, Int) -> [(Int, Int)]\ngetPair (xa, ya, xb, yb)\n = [(x, y) | x <- [minx .. maxx], y <- [miny]]\n ++ [(x, y) | x <- [maxx], y <- [miny + 1 .. maxy]]\n ++ [(x, y) | x <- [maxx - 1, maxx - 2 .. minx], y <- [maxy]]\n ++ [(x, y) | x <- [minx], y <- [maxy - 1, maxy - 2 .. miny + 1]]\n where\n minx = min xa xb\n maxx = max xa xb\n miny = min ya yb\n maxy = max ya yb\n\nminDist :: (Int, Int) -> [(Int, Int, Int)] -> Int\nminDist (x, y) [] = maxBound\nminDist (x, y) warms = minimum (map dist warms)\n where\n dist (x0, y0, r) = ceiling (sqrt (fromIntegral ((x0 - x)^2 + (y0 - y)^2))) - r\n\nreadWarm :: IO (Int, Int, Int)\nreadWarm = do\n [x, y, r] <- Main.reads\n return (x, y, r)\n\nmain :: IO ()\nmain = do\n [xa, ya, xb, yb] <- Main.reads\n n <- readLn\n warms <- mapM (const readWarm) [1..n]\n print (length (solve (xa, ya, xb, yb) warms))\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}, {"source_code": "import Data.List\n\ndata Circle = Circle Int Int Int\n\noutsideCircles circles (x, y) = and $ map outside circles\n where outside (Circle a b r) = r*r < (a-x)*(a-x) + (b-y)*(b-y)\n\nnotCovered ((a, b), (c, d)) circles = length blankets\n where generals = nub $ concat [ [(x, b) | x <- [(min a c)..(max a c)]],\n [(x, d) | x <- [(min a c)..(max a c)]],\n [(a, y) | y <- [(min b d)..(max b d)]],\n [(c, y) | y <- [(min b d)..(max b d)]] ]\n blankets = filter (outsideCircles circles) generals\n\nreadInput :: IO (((Int, Int), (Int, Int)), [Circle])\nreadInput = do\n line <- getLine\n let nos = map (\\x -> read x :: Int) (words line)\n [a, b, c, d] = nos\n line <- getLine\n let n = read line :: Int\n let getCircle = do\n line <- getLine\n let [a, b, r] = words line\n c = Circle (read a) (read b) (read r)\n return c\n circles <- sequence $ take n $ repeat getCircle\n return (((a, b), (c, d)), circles)\n\nmain = do\n (rect, circles) <- readInput\n let ans = notCovered rect circles\n putStrLn $ show ans\n"}, {"source_code": "import Control.Monad\n\nsqr x = x * x\n\ncheck ps (x, y) = \n not $ or $ map (\\[px, py, pr] -> pr * pr >= sqr (x - px) + sqr (y - py)) ps\n\nsolve xa ya xb yb ps = a + b + c + d\n where a = length $ filter (check ps) [(x, ya) | x <- [xa .. xb]]\n b = length $ filter (check ps) [(x, yb) | x <- [xa .. xb]]\n c = length $ filter (check ps) [(xa, y) | y <- [ya + 1 .. yb - 1]]\n d = length $ filter (check ps) [(xb, y) | y <- [ya + 1 .. yb - 1]]\n\nmain = do [xa, ya, xb, yb] <- fmap (map read.words) getLine\n n <- fmap read getLine\n ps <- replicateM n (fmap (map read.words) $ getLine)\n putStrLn $ show $ solve (min xa xb) (min ya yb) (max xa xb) (max ya yb) ps"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n p1 <- (,) <$> readInt <*> readInt\n p2 <- (,) <$> readInt <*> readInt\n n <- readInt\n circles <- replicateM n (Circle <$> readInt <*> readInt <*> readInt)\n return (p1, p2, circles)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\ndata Circle = Circle Int Int Int\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\ninCircle :: (Int, Int) -> Circle -> Bool\ninCircle (x', y') (Circle x y r) = (x'-x)*(x'-x) + (y'-y)*(y'-y) <= r*r\n\nrange x y | x <= y = tail [x..y]\n | otherwise = tail $ reverse [y..x]\n\nsolve ((x1, y1), (x2, y2), circles) = length $ filter (not.inAnyCircle) border\n where\n inAnyCircle pt = any (pt `inCircle`) circles\n\n border = [(x, y1) | x <- range x1 x2] ++\n [(x2, y) | y <- range y1 y2] ++\n [(x, y2) | x <- range x2 x1] ++\n [(x1, y) | y <- range y2 y1]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n [xa,ya,xb,yb] <- liftM (map read . words) getLine\n let x1 = min xa xb\n x2 = max xa xb\n y1 = min ya yb\n y2 = max ya yb\n gs = [ (x,y1) | x <- [x1..x2] ] ++\n [ (x,y2) | x <- [x1..x2] ] ++\n [ (x1,y) | y <- [y1+1..y2-1] ] ++\n [ (x2,y) | y <- [y1+1..y2-1] ]\n n <- readLn\n rs <- replicateM n $ liftM (map read . words) getLine\n print $ length $ foldl' f gs rs\nf gs = flip filter gs . outOfRange\noutOfRange [xr,yr,r] (x,y) = (xr-x)^2 + (yr-y)^2 > r^2"}, {"source_code": "import Data.List(sort)\nimport Control.Applicative\n\nmain = do [xa,ya,xb,yb] <- map read . words <$> getLine\n _ <- getLine\n xyrs <- map (map read . words) . lines <$> getContents\n print $ solve [xa,ya,xb,yb] xyrs\n\nsolve :: [Int] -> [[Int]] -> Int\nsolve [xa',ya',xb',yb'] xyrs = length $ filter (\\ (x,y) -> all (f (x,y)) xyrs) xys\n where [xa,xb] = sort [xa',xb']\n [ya,yb] = sort [ya',yb']\n xys = [(x,y)|x<-[xa,xb],y<-[ya..yb]] ++ [(x,y)|x<-[(succ xa)..(pred xb)],y<-[ya,yb]]\n \nf (x,y) [xi,yi,ri] = (x-xi)*(x-xi) + (y-yi)*(y-yi) > ri*ri\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ntype Point = (Int, Int)\ntype Radiator = (Int, Int, Int)\n\ncheck (x, y) (xc, yc, r) =\n let dx = x - xc\n dy = y - yc\n in dx * dx + dy * dy <= r * r\n\nsolve xa ya xb yb rads =\n let pts = [(xa, y) | y <- [ya..yb]]\n ++ [(xb, y) | y <- [ya..yb]]\n ++ [(x, ya) | x <- [xa+1..xb-1]]\n ++ [(x, yb) | x <- [xa+1..xb-1]]\n in length pts - (length . filter id $\n map (\\pt -> any (check pt) rads) pts)\n\nmain = do\n [xa, ya, xb, yb] <- liftM (map read . words) getLine :: IO [Int]\n n <- liftM read getLine\n list <- replicateM n $ do\n [xc, yc, r] <- liftM (map read . words) getLine :: IO [Int]\n return (xc, yc, r)\n\n let [xa', xb'] = sort [xa, xb]\n [ya', yb'] = sort [ya, yb]\n let ans = solve xa' ya' xb' yb' list\n\n putStrLn $ show ans\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}, {"source_code": "a#b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n\n"}], "negative_code": [{"source_code": "m a b=(min a b,max a b)\ns([x,y,v,w]:[n]:t)=filter b[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=m x v;(u,d)=m y w;b(x,y)=all(\\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t\nmain=interact$show.length.s.map(map read.words).lines\n"}], "src_uid": "9e7fdc3261d312e7578da7f14c259e43"} {"source_code": "module Main where\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n a <- sort <$> map read <$> words <$> getLine\n print $ f a n\n\nf :: [Integer] -> Int -> Integer\nf a n = (val . fst $ parts) + (val . snd $ parts)\n where sqr = \\x -> x * x\n parts = splitAt (div n 2) a\n val = sqr . sum", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\tn <- readInt\n\tas <- reverse . sort <$> readIntegers\n\tlet\n\t\thor = sum $ take ( ( n + 1 ) `div` 2 ) as\n\t\tver = sum $ drop ( ( n + 1 ) `div` 2 ) as\n\tprint $ hor ^ 2 + ver ^ 2\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n print $ solve n as\n\nsolve :: Int -> [Integer] -> Integer\nsolve n as = sum a^(2) + sum b^(2)\n where\n (a,b) =splitAt (n `div` 2) $ sort as\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ViewPatterns #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport qualified Data.Array as A\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as MA\nimport Data.Bool\nimport qualified Data.ByteString.Builder as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport qualified Data.List.NonEmpty as NL\nimport Data.Monoid\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Foreign\nimport qualified System.IO as IO\n#ifdef DEBUG\nimport Debug.Trace\n#endif\n\nmain :: IO ()\nmain = do\n !n <- readLn\n xs <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Integer\nsolve n xs = sum[fromIntegral y|y<-ys]^2 + sum[fromIntegral z|z<-zs]^2\n where\n (ys, zs) = splitAt (div n 2) $ L.sort xs\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n print $ solve n as\n\nsolve :: Int -> [Int] -> Int\nsolve n as = sum a^(2::Int) + sum b^(2::Int)\n where\n (a,b) =splitAt (n `div` 2) $ sort as\n"}], "src_uid": "f9fbb45e45d3040e3be19a39ea8faa1f"} {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Array.ST(runSTArray)\nimport Data.Array.MArray\nimport Debug.Trace\n\ntype Map2D a = A.Array (Int,Int) a\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nnear (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)] \n\nmain = do\n [r,c] <- map readInt . B.words <$> B.getLine\n l <- B.lines <$> B.getContents\n let bb = ((0,0),(r-1,c-1))\n let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]\n print $ solve r c mymap\n\nsolve r c mymap = foldl' (+) 0 $ do\n (p,c) <- breeders\n guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost\n return (digitToInt c)\n where\n start = head $ findPos (=='S') mymap\n exit = head $ findPos (=='E') mymap\n mycost = fromJust (cost A.! fst start)\n breeders = findPos (\\c -> '0' < c && c <= '9') mymap\n cost = calcDistance (fst exit) mymap\n\n \nfindPos :: (a -> Bool) -> Map2D a -> [((Int,Int),a)]\nfindPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]\n\ncalcDistance :: (Int,Int) -> Map2D Char -> Map2D (Maybe Int)\ncalcDistance st mymap = runSTArray $ do\n cost <- newArray bb Nothing\n go cost\n return cost\n where\n bb = A.bounds mymap\n canEnter p = inRange bb p && mymap A.! p /= 'T'\n go cost = loop [st] [] 0\n where\n loop [] [] c = return ()\n loop [] l c = loop l [] (c+1)\n loop (p:ps) l c | not (canEnter p) = loop ps l c\n | otherwise = do\n v <- readArray cost p\n case v of\n Nothing -> do\n writeArray cost p (Just c)\n loop ps ((filter canEnter $ near p)++l) c\n Just _ -> loop ps l c\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [r, c] <- map read . words <$> getLine\n a <- replicateM r getLine\n\n let\n a' = listArray ((1, 1), (r, c)) $ concat a :: UArray (Int, Int) Char\n\n end = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'E']\n\n let\n ds = runSTUArray $ do\n ds :: STUArray s (Int, Int) Int <- newArray ((1, 1), (r, c)) (-1)\n writeArray ds end 0\n\n let\n loop q =\n case Seq.viewl q of\n Seq.EmptyL -> return ()\n (p Seq.:< q') -> do\n d <- readArray ds p\n let ps = filter (\\(x, y) -> 1 <= x && x <= r && 1 <= y && y <= c && a'!(x, y) /= 'T') [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] where (x, y) = p\n\n ps' <- filterM (\\p -> (== (-1)) <$> readArray ds p) ps\n forM_ ps' $ \\p -> writeArray ds p (d+1)\n\n loop $ foldl (Seq.|>) q' ps'\n\n loop $ Seq.singleton end\n return ds\n\n let\n start = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'S']\n d0 = ds!start\n mikes = [p | x <- [1..r], y <- [1..c], let p = (x, y), '1' <= (a'!p), (a'!p) <= '9']\n\n print $ sum $ map (\\p -> fromEnum (a'!p) - fromEnum '0') $ filter (\\p -> ds!p /= -1 && ds!p <= d0) mikes\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Array.ST(runSTArray)\nimport Data.Array.MArray\nimport Debug.Trace\n\ntype Map2D a = A.Array (Int,Int) a\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nnear (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)] \n\nmain = do\n [r,c] <- map readInt . B.words <$> B.getLine\n l <- B.lines <$> B.getContents\n let bb = ((0,0),(r-1,c-1))\n let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]\n print $ solve r c mymap\n\nsolve r c mymap = foldl' (+) 0 $ do\n (p,c) <- breeders\n guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost\n return (digitToInt c)\n where\n start = head $ findPos (=='S') mymap\n exit = head $ findPos (=='E') mymap\n mycost = fromJust (cost A.! fst start)\n breeders = findPos (\\c -> '0' < c && c <= '9') mymap\n cost = calcDistance (fst exit) mymap\n\n \nfindPos :: (a -> Bool) -> Map2D a -> [((Int,Int),a)]\nfindPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]\n\ncalcDistance :: (Int,Int) -> Map2D Char -> Map2D (Maybe Int)\ncalcDistance st mymap = runSTArray $ do\n cost <- newArray bb Nothing\n go cost\n return cost\n where\n bb = A.bounds mymap\n canEnter p = inRange bb p && mymap A.! p /= 'T'\n go cost = loop [(st,0)] []\n where\n loop [] [] = return ()\n loop [] l = loop l []\n loop ((p,c):ps) l | not (canEnter p) = loop ps l\n | otherwise = do\n v <- readArray cost p\n case v of\n Nothing -> do\n writeArray cost p (Just c)\n loop ps (map (\\p -> (p,c+1)) (near p)++l)\n Just _ -> loop ps l \n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Array.ST(runSTArray)\nimport Data.Array.MArray\n\ntype Map2D a = A.Array (Int,Int) a\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nnear (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)] \n\nmain = do\n [r,c] <- map readInt . B.words <$> B.getLine\n l <- B.lines <$> B.getContents\n let bb = ((0,0),(r-1,c-1))\n let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]\n print $ solve r c mymap\n\nsolve r c mymap = foldl' (+) 0 $ do\n (p,c) <- breeders\n guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost\n return (digitToInt c)\n where\n start = head $ findPos (=='S') mymap\n exit = head $ findPos (=='E') mymap\n mycost = fromJust (cost A.! fst start)\n breeders = findPos (\\c -> '0' < c && c <= '9') mymap\n cost = calcDistance (fst exit) mymap\n \nfindPos :: (a -> Bool) -> Map2D a -> [((Int,Int),a)]\nfindPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]\n\ncalcDistance :: (Int,Int) -> Map2D Char -> Map2D (Maybe Int)\ncalcDistance st mymap = runSTArray $ newArray bb Nothing >>= go\n where\n bb = A.bounds mymap\n canEnter p = inRange bb p && mymap A.! p /= 'T'\n go cost = loop [st] [] 0\n where\n loop [] [] c = return cost\n loop [] l c = loop l [] (c+1)\n loop (p:ps) l c = do\n b <- isJust <$> readArray cost p\n when (not b) $ writeArray cost p (Just c)\n let l' = if b then l else (filter canEnter $ near p)++l\n loop ps l' c\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array.Unboxed as A\nimport Data.Array.ST(runSTUArray)\nimport Data.Array.MArray\n\ntype Map2D a = A.UArray (Int,Int) a\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nnear (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)] \n\nmain = do\n [r,c] <- map readInt . B.words <$> B.getLine\n l <- B.lines <$> B.getContents\n let bb = ((0,0),(r-1,c-1))\n let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]\n print $ solve r c mymap\n\nsolve :: Int -> Int -> Map2D Char -> Int\nsolve r c mymap = foldl' (+) 0 $ do\n (p,c) <- breeders\n guard $ (>=0) (cost A.! p) && (cost A.! p) <= mycost\n return (digitToInt c)\n where\n start = head $ findPos (=='S') mymap\n exit = head $ findPos (=='E') mymap\n mycost = cost A.! fst start\n breeders = findPos (\\c -> '0' < c && c <= '9') mymap\n cost = calcDistance (fst exit) mymap\n \nfindPos :: (Char -> Bool) -> Map2D Char -> [((Int,Int),Char)]\nfindPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]\n\ncalcDistance :: (Int,Int) -> Map2D Char -> Map2D Int\ncalcDistance st mymap = runSTUArray $ newArray bb (-1) >>= go\n where\n bb = A.bounds mymap\n canEnter p = inRange bb p && mymap A.! p /= 'T'\n go cost = loop [st] [] 0\n where\n loop [] [] c = return cost\n loop [] l c = loop l [] (c+1)\n loop (p:ps) l c = do\n b <- (>=0) <$> readArray cost p\n when (not b) $ writeArray cost p (c)\n let l' = if b then l else (filter canEnter $ near p)++l\n loop ps l' c\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O3 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [r, c] <- map read . words <$> getLine\n a <- replicateM r getLine\n\n let\n a' = listArray ((1, 1), (r, c)) $ concat a :: UArray (Int, Int) Char\n\n end = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'E']\n\n let\n ds = runSTUArray $ do\n ds :: STUArray s (Int, Int) Int <- newArray ((1, 1), (r, c)) (-1)\n writeArray ds end 0\n\n let\n loop q =\n case Seq.viewl q of\n Seq.EmptyL -> return ()\n (p Seq.:< q') -> do\n d <- readArray ds p\n let ps = filter (\\(x, y) -> 1 <= x && x <= r && 1 <= y && y <= c && a'!(x, y) /= 'T') [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] where (x, y) = p\n\n ps' <- filterM (\\p -> (== (-1)) <$> readArray ds p) ps\n forM_ ps' $ \\p -> writeArray ds p (d+1)\n\n loop $ foldl (Seq.|>) q' ps'\n\n loop $ Seq.singleton end\n return ds\n\n let\n start = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'S']\n d0 = ds!start\n mikes = [p | x <- [1..r], y <- [1..c], let p = (x, y), '1' <= (a'!p), (a'!p) <= '9']\n\n print $ sum $ map (\\p -> fromEnum (a'!p) - fromEnum '0') $ filter (\\p -> ds!p <= d0) mikes\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Array as A\nimport Data.Array.ST(runSTArray)\nimport Data.Array.MArray\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\n\nmain = do\n [r,c] <- map readInt . B.words <$> B.getLine\n l <- B.lines <$> B.getContents\n print $ solve r c l\n\nsolve r c l = foldl' (+) 0 $ do\n (p,c) <- breeders\n guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost\n return (digitToInt c)\n where\n start = head $ findPos (=='S') l\n exit = head $ findPos (=='E') l\n mycost = fromJust (cost A.! fst start)\n breeders = findPos (\\c -> '0' < c && c <= '9') l\n cost = calcDistance (fst exit) l\n\ncalcDistance :: (Int,Int) -> [B.ByteString] -> A.Array (Int,Int) (Maybe Int)\ncalcDistance st l = runSTArray $ do\n cost <- newArray bb Nothing\n go cost\n return cost\n where\n r = length l\n c = B.length (head l)\n bb = ((0,0),(r-1,c-1))\n mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]\n canEnter p = inRange bb p && mymap A.! p /= 'T'\n go cost = loop [(st,0)] []\n where\n loop [] [] = return ()\n loop [] l = loop l []\n loop ((p,c):ps) l | not (canEnter p) = loop ps l\n | otherwise = do\n v <- readArray cost p\n case v of\n Nothing -> do\n writeArray cost p (Just c)\n loop ps (map (\\p -> (p,c+1)) (near p)++l)\n Just _ -> loop ps l\n \nnear (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)] \n \nfindPos :: (Char -> Bool) -> [B.ByteString] -> [((Int,Int),Char)]\nfindPos p l = do\n (s,i) <- zip l [0..]\n j <- [0..B.length s-1] \n let c = B.index s j\n guard (p c)\n return ((i,j),c)\n"}], "src_uid": "6e9c2236e24336fcca0723e656e664cc"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n (B.init <$> B.getLine)\n\n let\n rs = process HashMap.empty ss\n where\n process _ [] = []\n process m (s:ss) =\n case s `HashMap.lookup` m of\n Nothing -> (B.pack \"OK\"):(process (HashMap.insert s 1 m) ss)\n Just k -> (B.append s (B.pack $ show k)):(process (HashMap.adjust (+1) s m) ss)\n\n B.putStr $ B.unlines rs\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Map as M\n\n\nparse = tail . lines\npresent = unlines\nsolve = snd . mapAccumL insertName M.empty\n\ninsertName :: (M.Map String Int) -> String -> (M.Map String Int, String)\ninsertName olds new = \n let \n name = case M.findWithDefault 0 new olds of\n 0 -> \"OK\"\n x -> new ++ (show x)\n in \n (M.insertWith (+) new 1 olds, name)\n\n\n\nmain = interact $ present . solve . parse\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Data.List\nimport qualified Data.Map as M\n\n\nparse = tail . lines\npresent = unlines\nsolve !l = snd $ mapAccumL insertName M.empty l\n\ninsertName :: (M.Map String Int) -> String -> (M.Map String Int, String)\ninsertName olds new = \n let \n name = case M.findWithDefault 0 new olds of\n 0 -> \"OK\"\n x -> new ++ (show x)\n in \n (M.insertWith (+) new 1 olds, name)\n\n\n\nmain = interact $ present . solve . parse\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\nimport Data.List\nimport qualified Data.Map as M\n\n\nparse = tail . lines\npresent = unlines\nsolve l = snd $ mapAccumL insertName M.empty l\n\ninsertName :: (M.Map String Int) -> String -> (M.Map String Int, String)\ninsertName olds new = \n let \n name = case M.findWithDefault 0 new olds of\n 0 -> \"OK\"\n x -> new ++ (show x)\n in \n (M.insertWith (+) new 1 olds, name)\n\n\n\nmain = interact $ present . solve . parse\n"}, {"source_code": "import qualified Data.Map as M\nmain = interact $ unlines.f.tail.words\n\nf x = g (M.empty) x\n\ng :: (M.Map String Int) -> [String] -> [String]\ng a [] = []\ng a b =\n let key = M.findWithDefault 0 (head b) a in\n if key == 0\n then \"OK\": g (M.insert (head b) 1 a) (tail b)\n else ((head b) ++ show key) : g (M.insert (head b) (key + 1) a) (tail b)"}, {"source_code": "import Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\nhandle :: Map String Int -> String -> (Map String Int, String)\nhandle ac ar = (Map.insertWith (+) ar 1 ac, maybe \"OK\" (\\x -> ar ++ (show x)) $ Map.lookup ar ac)\n\n\nrun :: String -> String\nrun xs = unlines $ snd $ mapAccumL (handle) Map.empty (tail $ lines xs)\n\nmain = interact run"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\n\nsolve acc x = (M.insertWith (+) x 1 acc, oStr)\n where oStr = if x `M.member` acc then x ++ show (acc M.! x) else \"OK\"\n\nmain = interact $ unlines . snd . mapAccumL solve M.empty . tail . words\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\n\nsolve acc x = (M.insertWith (+) x 1 acc, maybe \"OK\" ((x ++) . show) $ M.lookup x acc)\n\nmain = interact $ unlines . snd . mapAccumL solve M.empty . tail . words\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\nimport Control.Monad\nimport Data.Map\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nrepeatM a = mapM (const a) (repeat 1)\nrepeatMn a n = mapM (const a) [1..n]\nreadm::(Read a) => State String a\nreadm = State (head . reads)\nreadchar = State (\\s->(head s,tail s))\nreadall = State (,\"\")\n\nrunRead x s = fst $ runState x s\n\nsolve::Map String Int -> [String] -> [String]\nsolve _ [] = []\nsolve m (s:ss) = s1 : solve m1 ss where\n\t(s1,m1) = case (Data.Map.lookup s m) of\n\t\tNothing -> (\"OK\",insert s 1 m)\n\t\tJust x -> (s++show x,insert s (x+1) m)\nmain = reader >>= writer . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\tn <- readm\n\tl <- liftM lines readall\n\treturn (unlines . solve empty . take n . tail $ l)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\nimport qualified Data.HashTable as Hash\n\nmain = do\n idHash <- Hash.new (==) Hash.hashString :: IO (Hash.HashTable [Char] Int)\n\n n <- read `liftM` getLine\n replicateM_ n $ do\n id <- getLine\n maybeCount <- Hash.lookup idHash id\n case maybeCount of\n Just n -> do\n Hash.update idHash id (n+1)\n putStrLn $ id ++ show n\n _ -> do\n Hash.insert idHash id 1\n putStrLn \"OK\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n (B.init <$> B.getLine)\n\n let\n rs = snd $ mapAccumL f HashMap.empty ss\n where\n f m s =\n case s `HashMap.lookup` m of\n Nothing -> (HashMap.insert s 1 m, B.pack \"OK\")\n Just k -> (HashMap.adjust (+1) s m, B.append s (B.pack $ show k))\n\n B.putStr $ B.unlines rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n getLine\n\n let\n rs = process HashMap.empty ss\n where\n process _ [] = []\n process !m (s:ss) =\n case s `HashMap.lookup` m of\n Nothing -> \"OK\":(process (HashMap.insert s 1 m) ss)\n Just k -> (s ++ show k):(process (HashMap.adjust (+1) s m) ss)\n\n putStr $ unlines rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n (B.init <$> B.getLine)\n\n let\n rs = process Map.empty ss\n where\n process _ [] = []\n process m (s:ss) =\n case s `Map.lookup` m of\n Nothing -> (B.pack \"OK\"):(process (Map.insert s 1 m) ss)\n Just k -> (B.append s (B.pack $ show k)):(process (Map.adjust (+1) s m) ss)\n\n B.putStr $ B.unlines rs\n"}, {"source_code": "\nimport qualified Data.Map.Strict as M\nimport Control.Monad (replicateM,foldM_)\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read :: IO Int\n let doit m _ = do name <- getLine\n case M.lookup name m of\n Nothing -> do putStrLn \"OK\"\n return $ M.insert name 1 m\n Just n -> do putStrLn $ name ++ show n\n return $ M.insert name (n+1) m\n foldM_ doit (M.empty :: M.Map String Int) [1..n]\n\n"}, {"source_code": "\nimport qualified Data.Map.Strict as M\nimport Control.Monad (replicateM,foldM_)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read :: IO Int\n let doit m _ = do name' <- BS.getLine\n let name = BS.takeWhile (not . isSpace) name'\n case M.lookup name m of\n Nothing -> do putStrLn \"OK\"\n return $ M.insert name 1 m\n Just n -> do BS.putStrLn $ name `BS.append` (BS.pack $ show n)\n return $ M.insert name (n+1) m\n foldM_ doit (M.empty :: M.Map ByteString Int) [1..n]\n\n"}, {"source_code": "module Main (main) where\n\nimport qualified Data.HashTable as H\n\nmain = do\n\tmap <- H.new (==) H.hashString\n\tinstr <- getLine\n\tlet n = read instr :: Int\n\tinloop n map\n\ninloop 0 _ = do return ()\ninloop n map = do\n\tkey <- getLine\n\tv <- H.lookup map key\n\tlet x = maybe 0 id v\n\tif x == 0 then do putStrLn \"OK\" else do putStrLn (key ++ show x)\n\tH.insert map key (x + 1)\n\tinloop (n - 1) map\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as M\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = readLn >>= \\n -> (mapM_ putStrLn).solve =<< (forM [1..n] $ \\i -> getLine>>= \\j -> return (j))\n--solve :: [String]-> [String]\nsolve (x:xs) = slv1 (x:xs) M.empty\nslv1 [] ys =[]\nslv1 (x:xs) ms = let (z1, z2) = M.insertLookupWithKey (\\ k n o -> 1+o) x 0 ms in if z1==Nothing then \"OK\":slv1 xs z2 else (x++show (z2 M.! x)):slv1 xs z2"}, {"source_code": "\nimport Data.Map (Map, empty, insert, findWithDefault)\n\nsolve :: [String] -> [String]\nsolve = tail . map fst . scanl f (\"\", empty)\n where\n f :: (String, Map String Int) -> String -> (String, Map String Int)\n f (_, map) name = (name', map')\n where\n n = findWithDefault 0 name map\n name' = if n == 0 then \"OK\" else name ++ (show n)\n map' = insert name (n+1) map\n\nmain :: IO ()\nmain = do\n n <- readLn\n names <- mapM (const getLine) [1..n]\n mapM_ putStrLn $ solve names\n"}, {"source_code": "-- Codeforces 4C\n\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport qualified Data.Map as Map\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n solve Map.empty n\n\n-- Note:\n-- 1. don't store the result, input a line, then compute, then print result.\n-- 2. use Map.insertWith to combine the old value and new value.\n\nsolve :: Map.Map String Int -> Int -> IO ()\nsolve _ 0 = return ()\nsolve db n = do\n req <- getLine\n putStrLn $ case Map.lookup req db of\n Just c -> req ++ show c\n Nothing -> \"OK\"\n solve (Map.insertWith (+) req 1 db) (n-1)\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.Map (Map)\nimport Data.Maybe\n\nupdateMap :: Map String Int -> String -> Map String Int\nupdateMap dataset str = M.insertWith (+) str 1 dataset\n\nloop :: Int -> Map String Int -> IO (Map String Int)\nloop 0 dataset = return dataset\nloop n dataset = do\n str <- getLine\n let a = M.lookup str dataset\n if isNothing a then \n putStrLn \"OK\"\n else\n putStrLn (str ++ show (fromJust a))\n let newSet = updateMap dataset str \n loop (n - 1) newSet \n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n dataset <- loop n M.empty\n return ()"}, {"source_code": "import qualified Data.Map as M\nimport Data.Map (Map)\nimport Data.Maybe\n\nupdateMap :: Map String Int -> String -> Map String Int\nupdateMap dataset str = M.insertWith (+) str 1 dataset\n where\n updater 0 _ = 1\n updater value _ = value + 1\n\nloop :: Int -> Map String Int -> IO (Map String Int)\nloop 0 dataset = return dataset\nloop n dataset = do\n str <- getLine\n let a = M.lookup str dataset\n if isNothing a then \n putStrLn \"OK\"\n else\n\n putStrLn (str ++ show (fromJust a))\n let newSet = updateMap dataset str \n --print $ output\n loop (n - 1) newSet \n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n dataset <- loop n M.empty\n return ()"}, {"source_code": "import qualified Data.Map as M\nimport Data.Map (Map)\nimport Data.Maybe\n\nupdateMap :: Map String Int -> String -> Map String Int\nupdateMap dataset str = M.insertWith updater str 1 dataset\n where\n updater _ 0 = 1\n updater _ value = value + 1\n\nloop :: Int -> Map String Int -> IO (Map String Int)\nloop 0 dataset = return dataset\nloop n dataset = do\n str <- getLine\n let a = M.lookup str dataset\n if isNothing a then \n putStrLn \"OK\"\n else\n putStrLn (str ++ show (fromJust a))\n let newSet = updateMap dataset str \n loop (n - 1) newSet \n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n dataset <- loop n M.empty\n return ()"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map as M\nimport Data.Maybe\n\nprocess::[String]->M.Map String Int->IO ()\nprocess [] _ = putStrLn \"\"\nprocess (q:qs) d | M.lookup q d== Nothing = do\n putStrLn \"OK\"\n process qs (M.insert q 1 d)\n | otherwise = do\n let x = fromJust $ M.lookup q d\n putStrLn $ q++ (show x)\n process qs (M.insert q (x+1) d)\n\nmain=do\n getLine\n q<- lines<$> getContents\n process q M.empty\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\nmain=getContents>>=mapM_ putStrLn.snd.mapAccumL(\\m x->(M.insertWith(+)x(1::Integer)m,maybe\"OK\"((x++).show)(M.lookup x m)))M.empty.tail.lines\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List\nmain=interact$unlines.snd.mapAccumL(\\m x->(M.insertWith(+)x(1::Integer)m,maybe\"OK\"((x++).show)(M.lookup x m)))M.empty.tail.lines\n"}, {"source_code": "import qualified Data.Map as M\nimport Data.List (mapAccumL)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . tail . lines\n\nsolve :: [String] -> [String]\nsolve = snd . mapAccumL f M.empty\n where f m x = (M.insertWith (+) x (1 :: Integer) m, maybe \"OK\" ((x++) . show) (M.lookup x m))\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Monad\nmain = do\n n <- readLn\n loop n M.empty\nloop 0 _ = return ()\nloop n m = do\n name <- getLine\n putStrLn $ case M.lookup name m of\n Just c -> name ++ show c\n Nothing -> \"OK\"\n loop (n-1) (M.insertWith (+) name 1 m)\n"}, {"source_code": "import qualified Data.Map as M\nimport Control.Monad\n\ntype Names = M.Map String Int\n\nsolve :: Names -> a -> IO Names\nsolve m _ = do\n name <- getLine\n case lookup' name m of\n 0 -> do\n putStrLn \"OK\"\n return $ M.insert name 1 m\n n -> do\n putStrLn $ name ++ show n\n return $ M.insert name (n + 1) m\n\nlookup' :: String -> Names -> Int\nlookup' k m = case M.lookup k m of\n Just v -> v\n Nothing -> 0\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n foldM_ solve M.empty [1..n]\n\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/4/C\n\nimport Data.List\nimport qualified Data.Map as M\n\nsolve :: (Num a, Show a) => M.Map [Char] a -> [Char] -> (M.Map [Char] a, [Char])\nsolve acc x = (M.insertWith (+) x 1 acc, maybe \"OK\" ((x ++) . show) $ M.lookup x acc)\n\nmain :: IO ()\nmain = interact $ unlines . snd . mapAccumL solve M.empty . tail . words\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Map.Strict as M\nimport Control.Monad\n\nf m s = case s `M.lookup` m of\n Just a -> (M.adjust (+1) s m, B.append s (B.pack $ show a))\n Nothing -> (M.insert s 1 m, B.pack \"OK\")\nmain = do\n n <- readLn\n rest <- replicateM n (B.init <$> B.getLine)\n let rs = snd $ mapAccumL f M.empty rest\n B.putStr $ B.unlines rs\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Map.Strict as M\nimport Control.Monad\n\nf m s = case s `M.lookup` m of\n Just a -> (M.adjust (+1) s m, B.append s (B.pack $ show a))\n Nothing -> (M.insert s 1 m, B.pack \"OK\")\nmain = do\n n <- readLn\n rest <- replicateM n (head <$> B.words <$> B.getLine)\n let rs = snd $ mapAccumL f M.empty rest\n B.putStr $ B.unlines rs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as Map\n\nmain = readLn >>= foldM_ output Map.empty . enumFromTo 1\n where\n output mp _ = do\n s <- getLine\n putStrLn $ maybe \"OK\" ((s ++) . show) $ Map.lookup s mp\n return $ Map.insertWith' (fmap (+ 1) . const id) s 1 mp\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ndata TrieLike a = Empty | Node {count :: Maybe Int, branches :: [(a, TrieLike a)]} deriving Show\n\nmodify' :: Ord a => a -> (TrieLike a -> TrieLike a) -> [(a, TrieLike a)] -> [(a, TrieLike a)]\nmodify' k f nodes = parse nodes\n where\n parse [] = [(k, f Empty)]\n parse xs@(x'@(k', t') : xs') =\n case compare k k' of\n LT -> (k , f Empty) : xs\n EQ -> (k', f t') : xs'\n GT -> x' : parse xs'\n\ninc' :: TrieLike a -> TrieLike a\ninc' Empty = Empty\ninc' node = node {count = Just . maybe 1 succ $ count node}\n\ninsert' :: Ord a => [a] -> TrieLike a -> TrieLike a\ninsert' xs Empty = insert' xs $ Node Nothing []\ninsert' [] node = inc' node\ninsert' (x : xs) node = node {branches = modify' x (insert' xs) $ branches node}\n\nlookup' :: Ord a => [a] -> TrieLike a -> Maybe (TrieLike a)\nlookup' _ Empty = Nothing\nlookup' [] node = Just node\nlookup' (x : xs) node = lookup x (branches node) >>= lookup' xs\n\nnext' :: Ord a => [a] -> TrieLike a -> Maybe Int\nnext' = fmap (join . fmap count) . lookup' \n\nmain = readLn >>= foldM_ output Empty . enumFromTo 1\n where\n output t _ = do\n s <- getLine\n putStrLn $ maybe \"OK\" ((s ++) . show) $ next' s t\n return $ insert' s t\n"}, {"source_code": "import Data.HashTable as H\nmain = do\n hTable <- new (==) hashString\n n <- read `fmap` getLine\n mapM_ (\\_ -> do\n name <- getLine\n val <- H.lookup hTable name \n case val of\n Just count -> do\n putStr (name ++ show count ++ \"\\n\")\n update hTable name (count + 1)\n return ()\n Nothing -> do\n putStr \"OK\\n\"\n insert hTable name 1\n ) [1..n]\n-- vim: set et sts=4:\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Map as M\n\nmain = do\n getLine\n foldM_ (\\mapping name -> do\n let res = M.lookup name mapping\n if res == Nothing\n then putStrLn \"OK\" >> return (M.insert name 0 mapping)\n else let Just res' = res\n in putStrLn (name++show (res'+1)) >> return (M.insert name (res'+1) mapping)\n ) M.empty =<< return . lines =<< getContents"}, {"source_code": "module Main where\n\nimport Data.List (mapAccumL)\nimport qualified Data.Map.Strict as M\n\nmain :: IO ()\nmain = interact $ unlines . solve . tail . lines\n\nsolve :: [String] -> [String]\nsolve names = snd $ mapAccumL processName M.empty names\n\nprocessName :: M.Map String Int -> String -> (M.Map String Int, String)\nprocessName occ name = (M.insertWith (+) name 1 occ, maybe \"OK\" ((name ++) . show) (M.lookup name occ))"}, {"source_code": "module Main where\n\nimport Data.List (mapAccumL)\nimport qualified Data.Map.Strict as M\n\nmain :: IO ()\nmain = interact $ unlines . solve . tail . lines\n\nsolve :: [String] -> [String]\nsolve names = snd $ mapAccumL processName M.empty names\n\nprocessName :: M.Map String Int -> String -> (M.Map String Int, String)\nprocessName occ name = case M.lookup name occ of\n Nothing -> (M.insert name 1 occ, \"OK\")\n Just count -> (M.insert name (count + 1) occ, name ++ show count)"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.Map\nimport Data.HashTable\nimport Debug.Trace\nimport Data.List\nimport Data.Array\nimport Data.Char\nimport Data.Int\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' = read\ninstance Scan Double where scan' = read\ninstance Scan Integer where scan' = read\ninstance Scan String where scan' x = x\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\n\nsolve [] _ l = reverse l\nsolve (x:xs) mp l = let mp' = insertWith (+) x 1 mp in\n case Data.Map.lookup x mp of\n Nothing -> (solve$!) xs mp' (\"OK\":l)\n Just n -> (solve$!) xs mp' ((x++(show n)):l)\n \nmain = do n <- scan :: IO Int\n l <- scans n :: IO [String]\n hash <- new (==) hashString\n sequence_ [do val <- Data.HashTable.lookup hash x;case val of {Nothing -> Data.HashTable.insert hash x 1>>putStrLn \"OK\";Just n -> Data.HashTable.update hash x (n+1)>>putStrLn (x++(show n))}|x<-l]\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Data.HashTable\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' = read\ninstance Scan String where scan' x = x\nscan :: (Scan a) => IO a\nscan = getLine>>=(return.scan')\nscans :: (Scan a) => Int -> IO [a]\nscans n = if n==0 then return [] else scan>>=(\\x->scans (n-1)>>=return.(x:))\n\nmain = do n <- scan :: IO Int\n l <- scans n :: IO [String]\n hash <- new (==) hashString\n sequence_ [do val <- Data.HashTable.lookup hash x;case val of {Nothing -> Data.HashTable.insert hash x 1>>putStrLn \"OK\";Just n -> Data.HashTable.update hash x (n+1)>>putStrLn (x++(show n))}|x<-l]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map.Strict as M\n\nprocess [] _ = return ()\nprocess (a:as) m | M.findWithDefault (-10) a m ==(-10) = do\n\t\t\t\t\t\t\t\tputStrLn \"OK\"\n\t\t\t\t\t\t\t\tprocess as (M.insert a 0 m ) \n\t\t | otherwise = do\n\t\t\t\t\tlet m1 = (M.insertWith (+) a 1 m)\n\t\t\t\t\tputStrLn (a++show (M.findWithDefault (-10) a m1 ))\t\t\t\t\t\n\t\t\t\t\tprocess as m1 \n\t\t \t\t\t\t\t\n\nmain=do\t \n\tgetLine\n\ta<-lines <$> getContents ::IO [String]\n process a M.empty \n \n\t\n\t "}, {"source_code": "import qualified Data.Map as Map\nimport Control.Monad\n\ninsertFun::a->b->Int->Int\ninsertFun _ _ old_value = old_value + 1\n\nforDisplay::String->Maybe Int->String\nforDisplay request res = case res of\n\t\t\t Just n -> request ++ show n\n\t\t\t Nothing -> \"OK\"\n\nwork database request = do\n let tmp = fst res\n putStrLn (forDisplay request tmp)\n return (snd res)\n where res = Map.insertLookupWithKey insertFun request 1 database\n\nprocess database _ = do\n request <- getLine\n ret <- work database request\n return ret\n\nmain = do\n n <- getLine\n foldM_ process Map.empty [1..read n::Int]\n"}, {"source_code": "import Data.List (mapAccumL)\nimport Data.Maybe\nimport qualified Data.Map.Lazy as M\n\ndata Trie a = Trie { value :: Int\n , getTrie :: M.Map a (Trie a)\n } deriving (Eq)\n\nempty :: Trie a\nempty = Trie (-1) M.empty\n\ninsert :: Ord a => [a] -> Trie a -> Trie a\ninsert [] (Trie e m) = Trie (e+1) m\ninsert (x:xs) (Trie e m) = Trie e (M.alter (Just . insert xs . fromMaybe empty) x m)\n\nfind :: Ord a => [a] -> Trie a -> Int\nfind [] (Trie e _) = e\nfind (x:xs) (Trie _ m) = fromMaybe (-1) (find xs <$> M.lookup x m)\n\n--process :: [String] -> [String]\nprocess xs = zipWith g xs $ snd $ mapAccumL f empty xs\n where\n f s l = (s', i)\n where\n s' = insert l s\n i = find l s'\n g x i = if i == 0\n then \"OK\"\n else x ++ show i\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap lines getContents\n putStrLn.unlines $ process xs"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables,TupleSections #-}\nimport Control.Monad\nimport Data.Map\ndata State s a = State {runState :: s->(a,s)}\ninstance Monad (State s) where\n\treturn = State . (,)\n\t(State f1) >>= f2 = State $ uncurry (runState . f2) . f1\n\t(State f1) >> (State f2) = State $ f2 .snd . f1\n\n\nrepeatM a = mapM (const a) (repeat 1)\nrepeatMn a n = mapM (const a) [1..n]\nreadm::(Read a) => State String a\nreadm = State (head . reads)\nreadchar = State (\\s->(head s,tail s))\nreadall = State (,\"\")\n\nrunRead x s = fst $ runState x s\n\nsolve::Map String Int -> [String] -> [String]\nsolve _ [] = []\nsolve m (s:ss) = s1 : solve m1 ss where\n\t(s1,m1) = case (Data.Map.lookup s m) of\n\t\tNothing -> (\"OK\",insert s 1 m)\n\t\tJust x -> (s++show (x+1),insert s (x+1) m)\nmain = reader >>= writer . solver\nreader = getContents\nwriter = putStr\nsolver = runRead $ do\n\tn <- readm\n\tl <- liftM lines readall\n\treturn (unlines . solve empty . take n . tail $ l)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n B.getLine\n\n let\n rs = process HashMap.empty ss\n where\n process _ [] = []\n process !m (s:ss) =\n case s `HashMap.lookup` m of\n Nothing -> (B.pack \"OK\"):(process (HashMap.insert s 1 m) ss)\n Just k -> (B.append s (B.pack $ show k)):(process (HashMap.adjust (+1) s m) ss)\n\n B.putStr $ B.unlines rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n B.getLine\n\n let\n rs = process HashMap.empty ss\n where\n process _ [] = []\n process m (s:ss) =\n case s `HashMap.lookup` m of\n Nothing -> (B.pack \"OK\"):(process (HashMap.insert s 1 m) ss)\n Just k -> (B.append s (B.pack $ show k)):(process (HashMap.adjust (+1) s m) ss)\n\n putStr $ unlines $ map B.unpack rs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ss <- replicateM n B.getLine\n\n let\n rs = process Map.empty ss\n where\n process _ [] = []\n process !m (s:ss) =\n case s `Map.lookup` m of\n Nothing -> (B.pack \"OK\"):(process (Map.insert s 1 m) ss)\n Just k -> (B.append s (B.pack $ show k)):(process (Map.adjust (+1) s m) ss)\n\n B.putStr $ B.unlines rs\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Word\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\i -> C.interact $ C.unlines.solve. take (read i).C.lines\nsolve :: [C.ByteString]-> [C.ByteString]\nsolve xs = map (\\(a1,a2)->a1) $ sortBy (\\ (a1,a2) (b1,b2) -> a2 `compare` b2) $ concat $ map slv2 $ slv1 xs\nslv1::[C.ByteString]->[[(C.ByteString,Int)]]\nslv1 xs= groupBy (\\(a1,a2) (b1,b2)->a1==b1 ) $sortBy (\\ (a1,a2) (b1,b2) -> a1 `compare` b1) $ zip xs [1..]\nslv2 :: [(C.ByteString,Int)]->[(C.ByteString,Int)]\nslv2 xs=zipWith (\\ (a1,a2) b->if b==0 then (C.pack \"OK\",a2) else (C.append a1 (C.pack $ show b) ,a2) ) xs [0..]"}, {"source_code": "import qualified Data.Map as M\nimport Data.Map (Map)\n\nupdateMap :: Map String Int -> String -> Map String Int\nupdateMap dataset str = M.insertWith (+) str 1 dataset\n where\n updater 0 _ = 1\n updater value _ = value + 1\n\nloop :: Int -> Map String Int -> IO (Map String Int)\nloop 0 dataset = return dataset\nloop n dataset = do\n str <- getLine\n let newSet = updateMap dataset str\n loop (n - 1) newSet \n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n dataset <- loop n M.empty\n print dataset"}, {"source_code": "import Control.Applicative\nimport qualified Data.Map as M\nimport Data.Maybe\n\nprocess::[String]->M.Map String Int->IO ()\nprocess [] _ = putStrLn \"\"\nprocess (q:qs) d | M.lookup q d== Nothing = do\n putStrLn \"Ok\"\n process qs (M.insert q 1 d)\n | otherwise = do\n let x = fromJust $ M.lookup q d\n putStrLn $ q++ (show x)\n process qs (M.insert q (x+1) d)\n\nmain=do\n getLine\n q<- lines<$> getContents\n process q M.empty\n"}, {"source_code": "import Data.List\nc1 = 27 ** 32\nmain = do\n n <- read `fmap` getLine\n l <- mapM (\\i -> (\\s -> (s, i)) `fmap` getLine) [1..n]\n let l1 = concat $ map addNumb $ groupBy (\\(a, _) (b, _) -> a == b) $ sort l where\n addNumb [(s, i)] = [(\"OK\", i)]\n addNumb ((s, i):ss) = let \n a = foldl' (\\(ss', n') (st, nline) -> \n ((st++show n', nline):ss', n+1)) ([(\"OK\", i)], 1) ss in fst a\n mapM_ (\\s -> putStr (fst s ++ \"\\n\")) $ sortBy (\\(_, a) (_, b) -> a `compare` b) l1\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map.Strict as M\nimport qualified Data.ByteString.Char8 as C\n\nprocess::[C.ByteString]->M.Map C.ByteString Int->IO ()\nprocess [] _ = return ()\nprocess (a:as) m | M.findWithDefault (-10) a m ==(-10) = do\n\t\t\t\t\t\t\t\tputStrLn \"OK\"\n\t\t\t\t\t\t\t\tprocess as (M.insert a 0 m ) \n\t\t | otherwise = do\n\t\t\t\t\tlet m1 = (M.insertWith (+) a 1 m)\n\t\t\t\t\tputStrLn $ (show a) ++ (show (M.findWithDefault (-10) a m1 ))\t\t\t\t\t\n\t\t\t\t\tprocess as m1 \n\t\t \t\t\t\t\t\n\nmain=do\t \n\tgetLine\n\ta<-C.lines <$> C.getContents \n process a M.empty \n \n\t\n\t "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map.Strict as M\n\nprocess [] _ s = mapM_ putStrLn $ reverse s\nprocess (a:as) m s | M.findWithDefault (-10) a m ==(-10) = process as (M.insert a 0 m ) (\"Ok\" : s)\n\t\t | otherwise = process as m1 ((a++show (M.findWithDefault (-10) a m1 )):s)\n\t\twhere m1 = (M.insertWith (+) a 1 m)\t\t\t\t\t\n\nmain=do\t \n\tgetLine\n\ta<-lines <$> getContents ::IO [String]\n process a M.empty []\n \n\t\n\t "}], "src_uid": "24098df9c12d9704391949c9ff529c98"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Monad (liftM, replicateM)\nimport Data.List (delete)\n\ntype Bottle = (Int, Int)\n\nreadInt :: String -> Int\nreadInt = read\n\ncantBeOpened :: Bottle -> [Bottle] -> Bool\ncantBeOpened b bs = null [x | x <- bs, snd x == t]\n where t = fst b\n\nmain = do\n numBottles <- liftM readInt getLine\n bottles <- replicateM numBottles $ do\n [a, b] <- liftM (map readInt . words) getLine\n return (a, b)\n let result = zipWith cantBeOpened bottles $ map (`delete` bottles) bottles\n print . length $ filter id result\n", "positive_code": [{"source_code": "main = do\n getLine\n interact $ show.length.solve.(map (map read)).(map words).lines\n\nsolve con = filter (\\[x,y]->x/=0) (res con [])\nres [] acc = acc\nres ([x,y]:xs) acc = res (sch (x,y) xs) ([x,y]:(sch (x,y) acc))\nsch _ [] = []\nsch (a,b) ([x,y]:xs) \n |b==x = [0,y]:sch (a,b) xs\n |otherwise = [x,y]:sch (a,b) xs"}, {"source_code": "import Control.Monad (liftM)\nimport Data.List (delete)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nreadPair :: Read a => IO (a, a)\nreadPair = do\n [x, y] <- reads\n return (x, y)\n\nsolve :: [(Int, Int)] -> Int\nsolve xs = length $ filter notOpen xs\n where\n notOpen x = notElem (fst x) $ map snd $ delete x xs\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- sequence $ replicate n readPair\n print $ solve xs"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\nmain = do\n n <- read <$> getLine :: IO Int\n aa <- sequence $ take n $ repeat $ do\n s <- words <$> getLine\n return (read (s!!0), read (s!!1)) :: IO (Int, Int)\n let a = listArray (1, n) aa\n let goodL = filter (\\i -> any (\\j -> i /= j && fst (a!i) == snd (a!j)) [1..n]) [1..n]\n print $ n - length goodL\n"}], "negative_code": [{"source_code": "main = do\n getLine\n interact $ show.length.solve.(map (map read)).(map words).lines\n\nsolve con = filter (\\[x,y]->x/=0) (res con con)\nres [] con = con\nres ([x,y]:xs) con = res xs (sch (x,y) con)\nsch _ [] = []\nsch (a,b) ([x,y]:xs) \n |b==x&&a/=x = [0,y]:sch (a,b) xs\n |otherwise = [x,y]:sch (a,b) xs"}], "src_uid": "84bd49becca69e126606d5a2f764dd91"} {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE NumericUnderscores #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nstringValue :: B8.ByteString -> Int\nstringValue str = sum . map (\\c -> ord c - ord 'a' + 1) $ B8.unpack str\n\nsolve :: B8.ByteString -> (String, Int)\nsolve str\n | even $ B8.length str = valueToAnswer strValue\n | otherwise = valueToAnswer $ max (tailStrValue - headStrValue) (tailEndStrValue - headEndStrValue)\n where \n strValue = stringValue str\n\n tailStrValue = stringValue $ B8.drop 1 str\n headStrValue = stringValue $ B8.take 1 str\n\n tailEndStrValue = stringValue $ B8.take (B8.length str - 1) str\n headEndStrValue = stringValue $ B8.drop (B8.length str - 1) str\n \n valueToAnswer value\n | value > 0 = (\"Alice\", value)\n | value < 0 = (\"Bob\", - value)\n | otherwise = (\"WTF\", - value)\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n str <- B8.getLine <&> head . B8.words\n let (player, score) = solve str\n printf \"%s %d\\n\" player score \n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Char\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n xs <- map ((+(-96)) . ord) . takeWhile (not . isSpace) . C.unpack <$> C.getLine\r\n let [sm, hx, lx] = ($xs) <$> [sum, head, last]\r\n diff\r\n | even (length xs) = sm\r\n | otherwise = sm - 2 * min hx lx\r\n putStrLn $ (if diff > 0 then \"Alice\" else \"Bob\") ++ \" \" ++ show (abs diff)\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [], "src_uid": "8f02891aa9d2fcd1963df3a4028aa5c0"} {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do\n\tn <- read <$> getLine :: IO Int\n\ta <- take n <$> lines <$> getContents\n\tputStrLn $ mergeMatrix $ transpose a\n\nmergeMatrix :: [[Char]] -> [Char]\nmergeMatrix a\n | null a = \"\"\n | otherwise = (mergeString (head a)) : (mergeMatrix (tail a))\n \nmergeString :: [Char] -> Char\nmergeString s = finalize $ foldl mergeChar '.' s\n\nmergeChar :: Char -> Char -> Char\nmergeChar '.' '?' = '.'\nmergeChar '.' c = c\nmergeChar '?' c = '?'\nmergeChar c '?' = c\nmergeChar a b = if a == b then a else '?'\n\nfinalize :: Char -> Char\nfinalize c\n | c == '.' = 'x'\n | otherwise = c\n ", "positive_code": [{"source_code": "import Data.List\nstrToList = (map (read :: String -> Int)).words\n\nf [] = \"\"\nf (x:xs) | length s > 1 = '?' : f xs\n | length s == 1 = s !! 0 : f xs\n | otherwise = 'a' : f xs\n where s = filter (/='?') (nub x)\n\nmain = do\n n <- readLn :: IO Int\n s <- getContents\n putStrLn $ f $ transpose $ lines s"}], "negative_code": [], "src_uid": "a51d2e6e321d7db67687a594a2b85e47"} {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns #-}\nimport Data.List\nimport Data.Int\nimport Control.DeepSeq\n\nmain = do\n temp <- getLine\n let n = read temp :: Int\n input <- getContents\n putStrLn $ solve $ init $ take n $ lines input\n\nmod_constant = 1000000007 :: Int64\na `modplus` b = (a + b) `rem` mod_constant\n\nsuffixSum = scanr1 modplus\n\ndpStep (force -> !p) \"s\" = suffixSum p\ndpStep (force -> !p) \"f\" = 0:p\n\nsolve :: [String] -> String\nsolve x = show $ foldl modplus 0 $ foldl dpStep [1] x\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns #-}\nimport Data.Int\nimport Data.List\nimport Control.DeepSeq\nmain = interact exec\nexec = (\\(n0:ss0) -> let n = read n0 :: Int; (s:ss) = map head ss0 in show $ f s (1:replicate (n - 1) 0) ss) . words\n\nf 's' (force -> !ms) (s:ss) = f s (scanr1 (+%) ms) ss\nf 'f' (force -> !ms) (s:ss) = f s (zipWith const (0:ms) ms) ss\nf _ (force -> !ms) [] = foldl' (+%) 0 ms\n\nmbase = 10^9 + 7 :: Int64\na +% b = (a + b) `rem` mbase"}, {"source_code": "import Data.Int\nimport Data.List\nimport Control.DeepSeq\nimport qualified Data.ByteString.Char8 as B\nmain = B.interact exec\nexec = (\\(n0:ss0) -> let n = maybe undefined fst $ B.readInt n0; (s:ss) = map B.head ss0 in B.pack $ show $ f s (1:replicate (n - 1) 0) ss) . B.words\n\nf 's' ms (s:ss) = f s (ms `deepseq` scanr1 (+%) ms) ss\nf 'f' ms (s:ss) = f s (ms `deepseq` zipWith const (0:ms) ms) ss\nf _ ms [] = foldl' (+%) 0 ms\n\nmbase = 10^9 + 7 :: Int64\na +% b = (a + b) `rem` mbase"}, {"source_code": "import Data.Foldable\nimport Data.Semigroup\n\nmain = interact $ show . solve . args . words\n where args :: [String] -> [Int]\n args (w:ws) = go (read w) 0 ws\n where go :: Int -> Int -> [String] -> [Int]\n go _ _ [] = []\n go n k (w:ws)\n | n == 1 = []\n | w == \"f\" = go (n - 1) (k + 1) ws\n | otherwise = (k + 1) : go (n - 1) 0 ws\n\nsolve :: [Int] -> Int\nsolve as = solve' as [1] 1\n where solve' :: [Int] -> [Int] -> Int -> Int\n solve' [] xs s = s\n solve' (a:as) xs s = solve' as xs' (foldl' modAdd 0 xs')\n where xs' = zipWith modSub (s : xs') (stimes a [0] ++ xs)\n\nmodConst :: Int\nmodConst = 1000000007\n \nmodSub :: Int -> Int -> Int\nmodSub a b = (a - b) `mod` modConst\n\nmodAdd :: Int -> Int -> Int\nmodAdd a b = (a + b) `mod` modConst\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n temp <- getLine\n let n = read temp :: Int\n input <- getContents\n putStrLn $ solve $ init $ take n $ lines input\n\nsuffixSum p = map sum $ (init . tails) p\n\ndpStep p \"s\" = map (\\x -> x `mod` 1000000007) $ suffixSum p\ndpStep p \"f\" = 0:p\n\nsolve :: [String] -> String\nsolve x = show $ sum $ foldl dpStep [1] x\n"}, {"source_code": "import Data.List\n\nmain = do\n temp <- getLine\n let n = read temp :: Int\n input <- getContents\n putStrLn $ solve $ init $ take n $ lines input\n\naddStep p \"s\" = reverse $ map sum $ (init . tails) p\naddStep p \"f\" = 0:p\n\nsolve :: [String] -> String\nsolve x = show $ sum $ foldl addStep [1] x\n"}, {"source_code": "import Data.List\n\nmain = do\n temp <- getLine\n let n = read temp :: Int\n input <- getContents\n putStrLn $ solve $ init $ take n $ lines input\n\nsuffixSum p = map sum $ (init . tails) p\n\naddStep p \"s\" = suffixSum p\naddStep p \"f\" = 0:p\n\nsolve :: [String] -> String\nsolve x = show $ sum $ foldl addStep [1] x\n"}, {"source_code": "import Data.Semigroup\n\nmain = interact $ show . solve . args . words\n where args :: [String] -> [Int]\n args (w:ws) = go (read w) 0 ws\n where go :: Int -> Int -> [String] -> [Int]\n go _ _ [] = []\n go n k (w:ws)\n | n == 1 = []\n | w == \"f\" = go (n - 1) (k + 1) ws\n | otherwise = (k + 1) : go (n - 1) 0 ws\n\nsolve :: [Int] -> Int\nsolve as = solve' as [1] 1\n where solve' :: [Int] -> [Int] -> Int -> Int\n solve' [] xs s = s\n solve' (a:as) xs s = solve' as xs' (sum xs')\n where xs' = zipWith (-) (s : xs') (stimes a [0] ++ xs)\n \n"}], "src_uid": "c4033b57cd52b4c8567e946e136cb5dc"} {"source_code": "import Data.List\nmain=interact$show.sum.map((`div`4).(^2).(+(-1)).length).group.sort.map head.tail.lines\n", "positive_code": [{"source_code": "import Data.List\n\nmain = getContents >>= print . solve . tail . words\n\nsolve = sum . map ((\\n -> let x = n `div` 2 in c x 2 + c (n - x) 2) . length) . group . sort . map head\n where c n 2 = n * (n - 1) `div` 2"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nhalf :: Int -> [Int]\nhalf n = [a, n - a] where a = div n 2\n\nhandshakes :: Int -> Int\nhandshakes n = div (n * (n - 1)) 2\n\nsolve :: [String] -> Int\nsolve = sum \n . map handshakes\n . concat\n . map half\n . map length\n . group\n . sort\n . map head\n\nmain :: IO ()\nmain = do\n n <- readInt\n names <- replicateM n getLine\n print $ solve names"}, {"source_code": "import Data.List\n\nmain = interact $ show . sum . map (sum . map (\\x -> x * (x - 1) `div` 2) . (\\x -> [x `div` 2, (x + 1) `div` 2]) . length) . group . sort . map head . tail . lines"}, {"source_code": "import Data.List\nmain=interact$show.sum.map((\\x->floor((x-1)*(x-1)/4)).fromIntegral.length).group.sort.map head.tail.lines\n"}, {"source_code": "import Data.List\nimport Data.Function\nmain = interact $ show . solve . sort . tail . lines\nsolve = sum . map (f . length) . groupBy ((==) `on` head)\nf n = ps h + ps h' where h = n `div` 2; h' = h + n `mod` 2\nps n = n * (n-1) `div` 2\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tls <- map length . group . sort . map head <$> replicateM n getLine\n\tprint $ solve ls\n\nsolve [] = 0\nsolve (l:ls) = f l1 + f l2 + solve ls\n\twhere\n\t\tl1 = l `div` 2\n\t\tl2 = l - l1\n\t\tf x = x * ( x - 1 ) `div` 2"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Bifunctor\n\nfac n = snd $ until ((<2). fst) (\\(x,y) -> (x-1,y*x)) (toInteger n,1 :: Integer)\ncomb2 n = if n < 2 then 0 else (fac n ) `div` (fac $ n-2) `div` 2\nclip n = if n < 0 then 0 else n\nsolve = uncurry (+) .\n foldr (\\(a,b) (x,y) -> (a+x,b+y)) (0,0) .\n map ((\\x -> let y = x`div`2 in bimap comb2 comb2 (y, clip $ x-y)) . length) .\n groupBy ((==) `on` (!!0)) .\n sort\nmain = print =<< solve . tail . lines <$> getContents\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Bifunctor\n\nfac n = snd $ until ((<2). fst) (\\(x,y) -> (x-1,y*x)) (n,1)\ncomb2 n = if n < 2 then 0 else (fac n ) `div` (fac $ n-2) `div` 2\nsolve = uncurry (+)\n . foldr (\\(a,b) (x,y) -> (a+x,b+y)) (0,0)\n . map ((\\x -> let y = x`div`2 in bimap comb2 comb2 (y,x-y)) . length) \n . groupBy ((==) `on` (!!0)) \n . sort\nmain = print =<< solve . tail . lines <$> getContents\n\n"}, {"source_code": "import Data.List\nmain=interact$show.sum.map((\\x->ceiling(x/2)*floor(x/2)).fromIntegral.length).group.sort.map head.tail.lines\n"}], "src_uid": "22a3561ff70b802f080feaabc4a71298"} {"source_code": "import Data.Functor\nimport Data.List\n\ngetInts :: IO [Int]\ngetInts = map read <$> words <$> getContents\n\nmain = getInts >>= putStrLn . (\\b -> if b then \"Yes\" else \"No\") . solve\n\nsolve :: [Int] -> Bool\nsolve (n:m:as) = (==g) . length . nub $ map f xs ++ map f ys where\n xn:as2 = as\n yn:as3 = drop xn as2\n xs = take xn as2\n ys = take yn as3\n g = gcd n m\n f = (flip mod) g\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- fmap (map read . words) getLine\n xs <- fmap (tail . map read . words) getLine\n ys <- fmap (tail . map read . words) getLine\n\n let\n check = runST $ do\n as <- newArray (0, n-1) False :: ST s (STUArray s Int Bool)\n mapM_ (\\x -> writeArray as x True) xs\n\n bs <- newArray (0, m-1) False :: ST s (STUArray s Int Bool)\n mapM_ (\\x -> writeArray bs x True) ys\n\n replicateM (n+m) $ do\n forM [0..n*m-1] $ \\i -> do\n a <- readArray as (i `mod` n)\n b <- readArray bs (i `mod` m)\n\n when (not a && b) $ writeArray as (i `mod` n) True\n when (a && not b) $ writeArray bs (i `mod` m) True\n\n as' <- getElems as\n bs' <- getElems bs\n return $ and $ as' ++ bs'\n\n putStrLn $ if check then \"Yes\" else \"No\"\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\ngetIntList :: IO [Int]\ngetIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n n:m:_ <- getIntList\n b:bs <- getIntList\n g:gs <- getIntList\n putStrLn $ if sol n m bs gs then \"Yes\" else \"No\"\n\nsol :: Int -> Int -> [Int] -> [Int] -> Bool\nsol a b bs gs = d>0 && (d==1 || d==h)\n where\n d = gcd a b\n h = length $ nub $ map (flip mod d) (bs ++ gs)\n"}, {"source_code": "import Data.List\nimport qualified Data.Set as Set\nimport Control.Applicative\nimport System.IO\nimport Debug.Trace\n\n\nmain = do\n [n, m] <- map read <$> words <$> getLine\n (_:boys) <- map read <$> words <$> getLine\n (_:girls) <- map read <$> words <$> getLine\n\n\n let loop i boys girls\n | Set.size boys == n\n && Set.size girls == m = Right ()\n | i > n * m = Left (boys, girls)\n | otherwise = do\n let ib = i `mod` n\n ig = i `mod` m\n hb = Set.member ib boys\n hg = Set.member ig girls\n\n let (boys', girls')\n | hb && hg = (boys, girls)\n | not hb && not hg = (boys, girls)\n | hb && not hg = (boys, Set.insert ig girls)\n | not hb && hg = (Set.insert ib boys, girls)\n\n loop (i+1) boys' girls'\n\n let checkpoint boys girls =\n case loop 0 boys girls of\n Right _ -> True\n Left (boys', girls') -> do\n if boys == boys' && girls == girls' \n then False\n else checkpoint boys' girls'\n\n putStrLn $\n if checkpoint (Set.fromList boys) (Set.fromList girls)\n then \"Yes\"\n else \"No\"\n\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as Set\nimport Data.Foldable(toList)\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: IO Int\nreadInt = head `liftM` readIntList\n \nreadIntList :: IO [Int]\nreadIntList = do\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n\nreadString :: IO String\nreadString = do\n line <- B.getLine\n return $ B.unpack line\n \nmakeStep :: Set.Set (Int, Int) -> ([Bool], [Bool]) -> ([Bool], [Bool])\nmakeStep goodPairs (boys, girls) = \n (boys', girls') \n where\n n = length boys\n m = length girls\n happyPairs = [(bi, gi) | (b, bi) <- zip boys [0..], \n (g, gi) <- zip girls [0..],\n (b || g) && (bi, gi) `Set.member` goodPairs] \n happyBoys = Set.fromList $ map fst happyPairs\n happyGirls = Set.fromList $ map snd happyPairs\n boys' = map (`Set.member` happyBoys) [0..n - 1]\n girls' = map (`Set.member` happyGirls) [0..m - 1]\n \nmain = do\n [n, m] <- readIntList\n happyBoys <- tail `liftM` readIntList\n happyGirls <- tail `liftM` readIntList\n let boys = map (`elem` happyBoys) [0..n - 1]\n let girls = map (`elem` happyGirls) [0..m - 1]\n let goodPairs = Set.fromList $ map (\\d -> (d `mod` n, d `mod` m)) [0..n * m - 1]\n let (boys', girls') = foldr (.) id (replicate (n + m) (makeStep goodPairs)) \n $ (boys, girls)\n let allHappy = not (False `elem` (boys' ++ girls')) \n let ans = if allHappy then \"Yes\" else \"No\"\n putStrLn $ ans\n \n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.Set as Set\nimport Control.Applicative\nimport System.IO\n\n\nmain = do\n [n, m] <- map read <$> words <$> getLine\n (_:boys) <- map read <$> words <$> getLine\n (_:girls) <- map read <$> words <$> getLine\n\n let loop i boys girls\n | Set.size boys == n\n && Set.size girls == m = True\n | i > n * m = False\n | otherwise = do\n let ib = i `mod` n\n ig = i `mod` m\n hb = Set.member ib boys\n hg = Set.member ig girls\n\n let (boys', girls')\n | hb && hg = (boys, girls)\n | not hb && not hg = (boys, girls)\n | hb && not hg = (boys, Set.insert ig girls)\n | not hb && hg = (Set.insert ib boys, girls)\n\n loop (i+1) boys' girls'\n\n putStrLn $\n if loop 0 (Set.fromList boys) (Set.fromList girls)\n then \"Yes\"\n else \"No\"\n\n"}], "src_uid": "65efbc0a1ad82436100eea7a2378d4c2"} {"source_code": "import Control.Applicative ((<$>))\nimport Data.Int (Int64)\nimport Control.Monad (forM_)\nimport Data.List (intercalate)\n\nmain = do\n [n, m] <- map read . words <$> getLine :: IO [Int]\n a <- map read . words <$> getLine :: IO [Int64]\n b <- map read . words <$> getLine :: IO [Int64]\n forM_ (solve a b 1 0) $ \\(x, y) -> do\n putStrLn $ intercalate \" \" $ map show [x, y]\n\nsolve :: [Int64] -> [Int64] -> Int64 -> Int64 -> [(Int64, Int64)]\nsolve _ [] _ _ = []\nsolve (a:as) (b:bs) n s\n | b <= s + a = (n, b - s) : solve (a:as) bs n s\n | otherwise = solve as (b:bs) (n + 1) (s + a)", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport qualified Data.Map as M\nimport Data.List\n\n\nmain = do\n inp <- fmap B.lines B.getContents\n let as = map readI $ B.words $ inp!!1\n let bs = map readI $ B.words $ inp!!2\n putStrLn $ unlines $ map (\\(i,j)->show i++\" \"++show j) $ solve as bs\n\nreadI :: B.ByteString -> Integer\nreadI s = case B.readInteger s of Just (n,_) -> n\n\nsolve :: [Integer] -> [Integer] -> [(Integer,Integer)]\nsolve as bs =\n map f bs\n where\n m = M.fromList $ zip (scanl (+) 0 as) [0..]\n\n f x = case M.lookupLT x m of\n Nothing -> error \"error\"\n Just (k,v) -> (v+1,x-k)"}], "negative_code": [], "src_uid": "56bdab2019ee12e18d4f7e17ac414962"} {"source_code": "module Main where\nimport Data.List as L\nimport Data.ByteString.Lazy as B\nimport Data.ByteString.Lazy.Char8 as C\nmain :: IO ()\nmain = do\n _ <- readLn :: IO Integer\n cs <- B.getContents\n let ls = C.lines cs\n lineToTup l =\n let ws = C.words l\n readDatInt = (\\ (Just (i,_)) -> i) . C.readInt\n [a,b] = Prelude.map readDatInt ws\n in (a,b)\n events = Prelude.map lineToTup ls\n eventsbystart = L.sortBy (\\(a,_) (b,_) -> compare a b) $ events\n (_,ans) = Prelude.foldl (\\ (m,c) (_,b) -> (max m b, c + if b < m then 1 else 0)) (snd $ Prelude.head eventsbystart,0::Integer) (Prelude.tail eventsbystart)\n -- eventsbystartl = F.toList eventsbystart\n print ans\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List (foldl', sort)\n\nmain :: IO ()\nmain = do\n _:xs <- map parse . lines <$> getContents\n let (_,b):xs' = sort xs\n print $ fst $ foldl' f (0,b) $ map snd xs'\n where\n f (acc,prev) b\n | b < prev = (acc+1, prev)\n | otherwise = (acc, b)\n parse x = let [a, b] = words x\n !c = read a :: Int\n !d = read b :: Int\n in (c, d)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [(Int, Int)] -> Int\nsolve events = snd $ foldl' f (0, 0) es\n where es = map snd $ sort events\n f (right, ans) y | y < right = (right, ans + 1)\n | otherwise = (y, ans)\n\ntoPair [x, y] = (x, y)\n\nmain = do _:xs <- map (toPair . map (fst .fromJust . BS.readInt) . BS.words) . BS.lines <$> BS.getContents\n print $ solve xs\n "}, {"source_code": "import Data.List(sort,foldl')\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do n <- read <$> getLine\n xs <- map ((\\ [x,y] -> (x,y)).map read'.B.words) <$> B.lines <$> B.getContents\n print $ solve n xs\n\nread' s = let Just (n,s') = B.readInt s\n in n\n\nsolve :: Int -> [(Int,Int)] -> Int\nsolve _ xs = snd $ foldl' f (y,0) ys\n where (y:ys) = map snd $ sort xs\n\nf :: (Int,Int) -> Int -> (Int,Int)\nf (m,i) n\n | m > n = (m,succ i)\n | otherwise = (n,i)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\n\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [(Int, Int)] -> Int\nsolve events = snd $ foldl' f (0, 0) es\n where es = map snd $ sort events\n f (right, ans) y | y < right = (right, ans + 1)\n | otherwise = (y, ans)\n\nmain = BS.interact $ BS.pack . show . solve . map parseEvent . tail . BS.lines\n where parseEvent line = let [x, y] = map BS.readInt $ BS.words line\n in (fst $ fromJust x, fst $ fromJust y)"}, {"source_code": "import Control.Applicative\nimport Data.List (foldl', sort)\nimport qualified Data.ByteString.Char8 as S\n\nmain :: IO ()\nmain = do\n _:xs <- map (\\x -> let [a, b] = S.words x in (S.readInt a, S.readInt b)) . S.lines <$> S.getContents\n let (_,b):xs' = sort xs\n print $ fst $ foldl' f (0,b) $ map snd xs'\n where\n f (acc,prev) b\n | b < prev = (acc+1, prev)\n | otherwise = (acc, b)\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Foreign\nimport Foreign.C\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr CInt -> IO CInt\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_ii :: CString -> Ptr CInt -> Ptr CInt -> IO CInt\n\nmain :: IO ()\nmain = do\n alloca $ \\(a :: Ptr CInt) -> do\n alloca $ \\(b :: Ptr CInt) -> do\n withCString \"%d\" $ \\(i :: CString) -> do\n withCString \"%d%d\" $ \\(ii :: CString) -> do\n c_scanf_i i a\n n <- peek a\n xs <- replicateM (fromIntegral n) $ do\n c_scanf_ii ii a b\n (,) <$> peek a <*> peek b\n let y : ys = map snd $ sort xs\n print $ solve 0 y ys\n where\n solve !acc _ [] = acc\n solve !acc x' (x : xs)\n | x < x' = solve (1 + acc) x' xs\n | otherwise = solve acc x xs\n\n\n"}, {"source_code": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Foreign\nimport Foreign.C\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_i :: CString -> Ptr CInt -> IO CInt\n\nforeign import ccall unsafe \"stdio.h scanf\"\n c_scanf_ii :: CString -> Ptr CInt -> Ptr CInt -> IO CInt\n\nmain :: IO ()\nmain = do\n alloca $ \\(a :: Ptr CInt) -> do\n alloca $ \\(b :: Ptr CInt) -> do\n withCString \"%d\" $ \\(i :: CString) -> do\n withCString \"%d%d\" $ \\(ii :: CString) -> do\n c_scanf_i i a\n n <- peek a\n xs <- replicateM (fromIntegral n) $ do\n c_scanf_ii ii a b\n (,) <$> peek a <*> peek b\n let y : ys = map snd $ sort xs\n print $ snd $ foldl f (y, 0) ys\n where\n f (!y, !acc) x\n | x < y = (y, 1 + acc)\n | otherwise = (x, acc)\n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.List (foldl', sort)\n\nmain :: IO ()\nmain = do\n _:xs <- map parse . lines <$> getContents\n let (_,b):xs' = sort xs\n print $ fst $ foldl' f (0,b) $ map snd xs'\n where\n f (acc,prev) b\n | b < prev = (acc+1, prev)\n | otherwise = (acc, b)\n parse x = let [a, b] = words x\n !c = read a :: Int\n !d = read b :: Int\n in (c, d)\n"}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nreadInt = fst . fromJust . C.readInt\nreadIntList = map readInt . C.words\n\nlistToTuple [a, b] = (a, b)\n\nf (m, r) (_, b)\n | m > b = (m, r+1)\n | otherwise = (b, r)\n\nmain = do\n input <- fmap (map (C.takeWhile (/='\\r')) . C.lines) $ C.hGetContents stdin\n let n = readInt $ head input\n ab = map (listToTuple . readIntList) (take n $ tail input)\n print . snd $ foldl' f (0, 0) (sort ab)\n\n\n-- vim: set expandtab:\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM)\nimport Data.List (sort,foldl')\nimport Data.Ord (comparing)\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nmain = do\n n <- fmap read getLine\n pairs <- replicateM n $ do\n (a:b:_) <- fmap (parseInts 2) BS.getLine\n return (a,b)\n let _ = pairs :: [(Int,Int)]\n let sorted = sort pairs\n\n let go :: (Int,Int) -> (Int,Int) -> (Int,Int)\n go (!c,m) (a,b) = case compare m b of\n GT -> (c+1,m)\n EQ -> (c,m)\n LT -> (c,b)\n let (answer,_) = foldl' go (0,0) sorted\n print answer\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n ((,) <$> readInt <*> readInt)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve xs = length [undefined | (a, b) <- zip rights maxr, a < b]\n where\n rights = map snd (sort xs)\n maxr = scanl max 0 rights\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Applicative\nimport Data.List (foldl', sort)\n\nmain :: IO ()\nmain = do\n n <- getLine\n xs <- (map parse) . lines <$> getContents\n let (_,b):xs' = sort xs\n print $ fst $ foldl' f (0,b) $ map snd xs'\n where\n f (acc,prev) b\n | b < prev = (acc+1, prev)\n | otherwise = (acc, b)\n\nparse :: String -> (Int, Int)\nparse x = let [a, b] = words x\n !c = read a :: Int\n !d = read b :: Int\n in (c, d)\n"}, {"source_code": "import Control.Applicative\nimport Data.List (foldl', sort)\n\nmain :: IO ()\nmain = do\n _:xs <- map parse . lines <$> getContents\n let (_,b):xs' = sort xs\n print $ fst $ foldl' f (0,b) $ map snd xs'\n where\n f (acc,prev) b\n | b < prev = (acc+1, prev)\n | otherwise = (acc, b)\n\nparse :: String -> (Int, Int)\nparse x = let [a, b] = words x\n !c = read a :: Int\n !d = read b :: Int\n in (c, d)\n"}, {"source_code": "import Control.Applicative\nimport Data.List (foldl', sort)\n\nmain :: IO ()\nmain = do\n n <- getLine\n xs <- map parse . lines <$> getContents\n let (_,b):xs' = sort xs\n print $ fst $ foldl' f (0,b) $ map snd xs'\n where\n f (acc,prev) b\n | b < prev = (acc+1, prev)\n | otherwise = (acc, b)\n\nparse :: String -> (Int, Int)\nparse x = let [a, b] = words x\n !c = read a :: Int\n !d = read b :: Int\n in (c, d)\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM)\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\nimport Data.Array\n\ncontains :: (Int,Int) -> (Int,Int) -> Bool\ncontains (a,b) (c,d) = a < b && c < d\n\n(-->) = flip fmap\n\nmain = do\n n <- getLine --> read\n pairs <- replicateM n $ do\n (a:b:_) <- getLine --> words --> map read\n return (a,b)\n let _ = pairs :: [(Int,Int)]\n let sorted = sortBy (comparing fst) pairs\n let arr = listArray (1,n) sorted\n -- count the number of pairs which are contained in some other (earlier) pair\n let isContained :: Int -> Bool\n isContained j = \n let cd = arr ! j in any (\\i -> contains (arr ! i) cd) [1..j-1]\n let count = length $ filter isContained [2..n]\n print count\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n _:(_,b):xs <- map (\\x -> let [a, b] = words x in (read a :: Int, read b :: Int)) . lines <$> getContents\n print $ fst $ foldl' f (0,b) $ map snd $ sort xs\n where\n f (acc,prev) b\n | prev > b = (acc+1, prev)\n | otherwise = (acc, b)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n _:(_,b):xs <- map (\\x -> let [a, b] = words x in (read a :: Int, read b :: Int)) . lines <$> getContents\n print $ fst $ foldl' f (0,b) $ map snd xs\n where\n f (acc,prev) b\n | prev > b = (acc+1, prev)\n | otherwise = (acc, b)\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmain :: IO ()\nmain = do n <- read <$> getLine\n xs <- forM [1..n] (\\_ -> (\\ [x,y] -> (x, negate y)) <$> map read <$> words <$> getLine)\n print $ solve n xs\n\nsolve :: Int -> [(Int,Int)] -> Int\nsolve _ xs = length $ filter ( i == j) $ sort xs\n"}], "src_uid": "dfb1479ffa17489095b6bf1921758f7e"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[x,y] <- readv\r\n if odd (x+y) then putStrLn (\"-1 -1\") else printv [x`div`2, (y+1)`div`2]\r\n \r\n\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Int]\r\nreadv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ nTc solve\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM)\r\n\r\nmain = do\r\n x <- getLine\r\n let nLines :: Int\r\n nLines = read x\r\n lines <- replicateM nLines getLine\r\n let res = map solve lines\r\n putStr $ unlines res\r\n\r\nsolve line = do\r\n let arr = [read x :: Int | x <- words line]\r\n let (x : y : _) = arr\r\n if (x + y) `mod` 2 == 1\r\n then \"-1 -1\"\r\n else unwords $ map show [floor $ fromIntegral x / 2, floor $ fromIntegral (y + 1) / 2]"}, {"source_code": "f[x,y] =\r\n case (mod x 2, mod y 2) of\r\n (0, 0) -> [div x 2, div y 2]\r\n (0, 1) -> [-1, -1]\r\n (1, 0) -> [-1, -1]\r\n (1, 1) -> [div x 2, 1 + (div y 2)]\r\n\r\nmain=interact$unlines.map(unwords.map show.f.map read.words).tail.lines\r\n"}, {"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [x, y] = map read $ words input\r\n output = case findPointC (x, y) of\r\n Just (cx, cy) -> unwords $ map show [cx, cy]\r\n Nothing -> \"-1 -1\"\r\n\r\n\r\nfindPointC :: (Integer, Integer) -> Maybe (Integer, Integer)\r\nfindPointC (x, y)\r\n | odd (abs(x) + abs(y)) = Nothing\r\n | otherwise = Just (x `div` 2, (y + 1) `div` 2)\r\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM)\r\n\r\nmain = do\r\n x <- getLine\r\n let nLines :: Int\r\n nLines = read x\r\n lines <- replicateM nLines getLine\r\n let res = map solve lines\r\n putStr $ unlines res\r\n\r\nsolve line = do\r\n let arr = [read x :: Int | x <- words line]\r\n let (x : y : _) = arr\r\n unwords $ map show [floor $ fromIntegral x / 2, floor $ fromIntegral (y + 1) / 2]"}, {"source_code": "import Control.Monad (replicateM)\r\n\r\nmain = do\r\n x <- getLine\r\n let nLines :: Int\r\n nLines = read x\r\n lines <- replicateM nLines getLine\r\n let res = map solve lines\r\n putStr $ unlines res\r\n\r\nsolve line = do\r\n let arr = [read x :: Int | x <- words line]\r\n let (x : y : _) = arr\r\n unwords $ map show [fromIntegral x / 2, fromIntegral y / 2]"}], "src_uid": "f1d3032f1cb07ad6187a37c84376510d"} {"source_code": "import List\nmain = interact solve\nsolve input = output where\n letters = lines input\n output = if null a then \"Impossible\" else unlines $ head $ sort $ map form a\n where a = answer $ sort letters\nanswer xs = filter check $ perm xs\nperm [] = [[]]\nperm xs = concat [map (x:) (perm xs') | (x, xs') <- f xs]\n where f [] = []\n f (x:xs) = (x, xs):[(x', x:xs') | (x', xs') <- f xs]\ncheck xs = ls!!0 + ls!!5 == ls!!3 + 1 && ls!!1 + ls!!4 == ls!!2 + 1 &&\n xs!!0!!0 == xs!!1!!0 && xs!!0!!(ls!!0-1) == xs!!2!!0 &&\n xs!!1!!(ls!!1-1) == xs!!3!!0 && xs!!2!!(ls!!1-1) == xs!!3!!(ls!!0-1) &&\n xs!!3!!(ls!!3-1) == xs!!4!!0 && xs!!2!!(ls!!2-1) == xs!!5!!0 &&\n xs!!4!!(ls!!4-1) == xs!!5!!(ls!!5-1)\n where ls = map length xs\nform xs = [[c i j|j <- [0..ls!!3-1]]|i <- [0..ls!!2-1]] where\n ls = map length xs\n c i j\n | i==0 && j=ls!!1 = xs!!4!!(i-ls!!1+1)\n | i==ls!!2-1 && j>=ls!!0 = xs!!5!!(j-ls!!0+1)\n | otherwise = '.'", "positive_code": [{"source_code": "import Data.List\nimport GHC.Exts\n\nmain = interact solve\n\nsolve str =\n let wd = lines str\n crosswords = sort [makeCrossword p | p <- permutations wd, good p]\n in if null crosswords\n then \"Impossible\\n\"\n else unlines (head crosswords) ++ \"\\n\"\n\ngood p = head (p!!0) == head (p!!1) &&\n last (p!!0) == head (p!!2) &&\n last (p!!1) == head (p!!3) &&\n last (p!!3) == head (p!!4) &&\n last (p!!2) == head (p!!5) &&\n last (p!!5) == last (p!!4) &&\n l!!1 > 2 && l!!0 > 2 && l!!4 > 2 && l!!5 > 2 &&\n l!!3 == l!!0 + l!!5 - 1 &&\n l!!2 == l!!1 + l!!4 - 1 &&\n p!!3!!(l!!0 - 1) == p!!2!!(l!!1 - 1)\n where\n l = map length p\n\nmakeCrossword p = (p!!0 ++ right):\n map first (zip (init . tail $ p!!1) (init . tail $ p!!2)) ++\n [p!!3] ++\n map second (zip (init . drop (length (p!!1)) $ p!!2) (init . tail $ p!!4)) ++\n [left ++ p!!5]\n where first (a, b) = a:tail left ++ b:right\n second (a, b) = left ++ a:tail right ++ [b]\n right = replicate ( length (p!!5) - 1 ) '.'\n left = replicate ( length (p!!0) - 1 ) '.'\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Control.Arrow\nimport Data.Array\n\nmain :: IO ()\nmain = do\n xs <- replicateM 6 getLine\n --mapM_ print . filter valid . perms $ xs\n let sols = sortOn snd . filter (valid . fst) . map (id &&& crossword) . perms $ xs\n putStrLn $ if null sols then \"Impossible\" else snd . head $ sols\n\nperms :: Eq a => [a] -> [[a]]\nperms [] = [[]]\nperms xs = [x:y | x <- xs, y<- perms (delete x xs)]\n\ncrossword :: [String] -> String\ncrossword [a,b,c,d,e,f] =\n unlines [[as!(i, j)|i<-[1..length e]]| j<-[1..length b]]\n where\n as :: Array (Int, Int) Char -- (x, y)\n as = accumArray (const id) '.' ((1,1), (length e, length b))\n $ zip [(i,1)|i<-[1..]] a\n ++ zip [(length a, i)|i<-[1..]] b\n ++ zip [(i,length b)|i<-[length a..]] c\n ++ zip [(length e,i)|i<-[length f..]] d\n ++ zip [(i,length f)|i<-[1..]] e\n ++ zip [(1,i)|i<-[1..]] f\ncrossword _ = \"\"\n\n\n\nvalid :: [String] -> Bool\nvalid [a, b, c, d, e, f] =\n last a == head b\n && last b == head c\n && last c == last d\n && last e == head d\n && last f == head e\n && head a == head f\n && length e == length a + length c - 1\n && length b == length d + length f - 1\n && b !! (length f - 1) == e !! (length a - 1)\nvalid _ = False\n"}, {"source_code": "import Data.List\n\nmain = interact (unlines.s.take 6.lines)\ns ls = if null cr then [\"Impossible\"] else minimum cr where\n cr = filter (/=[]) $ map cross $ permutations (zip ls (map length ls))\n\ncross hls =\n if (l!!0+l!!2-1)==(l!!1) && (l!!3+l!!5-1)==(l!!4) &&\n head (h!!0)==head (h!!3) && last (h!!0)==head (h!!4) &&\n head (h!!1)==last (h!!3) && ((h!!1)!!(l!!0-1))==((h!!4)!!(l!!3-1)) && last (h!!1)==head (h!!5) &&\n head (h!!2)==last (h!!4) && last (h!!2)==last (h!!5)\n then make (h, l)\n else []\n where\n h = map fst hls\n l = map snd hls\n\nmake (h, l) = (map (++rm) ((h!!0):v1)) ++ [h!!1] ++ (map (lm++) (v2++[h!!2]))\n where\n v1 = zipWith (\\a b -> (a:ls)++[b]) ((init.tail)(h!!3)) ((take (l!!3-2).tail)(h!!4))\n v2 = zipWith (\\a b -> (a:rs)++[b]) ((init.drop (l!!3))(h!!4)) ((init.tail)(h!!5))\n rm = replicate ((l!!2)-1) '.'\n rs = tail rm\n lm = replicate ((l!!0)-1) '.'\n ls = tail lm\n"}], "negative_code": [{"source_code": "import List\nmain = interact solve\nsolve input = output where\n letters = lines input\n output = if null a then \"Impossible\" else unlines $ form $ head a\n where a = answer $ sort letters\nanswer xs = filter check $ perm xs\nperm [] = [[]]\nperm xs = concat [map (x:) (perm xs') | (x, xs') <- f xs]\n where f [] = []\n f (x:xs) = (x, xs):[(x', x:xs') | (x', xs') <- f xs]\ncheck xs = ls!!0 + ls!!5 == ls!!3 + 1 && ls!!1 + ls!!4 == ls!!2 + 1 &&\n xs!!0!!0 == xs!!1!!0 && xs!!0!!(ls!!0-1) == xs!!2!!0 &&\n xs!!1!!(ls!!1-1) == xs!!3!!0 && xs!!2!!(ls!!1-1) == xs!!3!!(ls!!0-1) &&\n xs!!3!!(ls!!3-1) == xs!!4!!0 && xs!!2!!(ls!!2-1) == xs!!5!!0 &&\n xs!!4!!(ls!!4-1) == xs!!5!!(ls!!5-1)\n where ls = map length xs\nform xs = [[c i j|j <- [0..ls!!3-1]]|i <- [0..ls!!2-1]] where\n ls = map length xs\n c i j\n | i==0 && j=ls!!1 = xs!!4!!(i-ls!!1+1)\n | i==ls!!2-1 && j>=ls!!0 = xs!!5!!(j-ls!!0+1)\n | otherwise = '.'"}, {"source_code": "import Data.List\nimport GHC.Exts\n\nmain = interact solve\n\nsolve str =\n let wd = lines str\n crosswords = sort [makeCrossword p | p <- permutations wd, good p]\n in if null crosswords\n then \"Impossible\\n\"\n else unlines (head crosswords) ++ \"\\n\"\n\ngood p = head (p!!0) == head (p!!1) &&\n last (p!!0) == head (p!!2) &&\n last (p!!1) == head (p!!3) &&\n last (p!!3) == head (p!!4) &&\n last (p!!2) == head (p!!5) &&\n last (p!!5) == last (p!!4) &&\n l!!1 > 2 && l!!0 > 2 && l!!4 > 2 && l!!5 > 2 &&\n l!!3 == l!!0 + l!!5 - 1 &&\n l!!2 == l!!1 + l!!4 - 1 &&\n p!!3!!(l!!0 - 1) == p!!2!!(l!!1 - 1)\n where\n l = map length p\n\nmakeCrossword p = (p!!0 ++ right):\n map first (zip (init . tail $ p!!1) (init . tail $ p!!2)) ++\n [p!!3] ++\n map second (zip (tail . drop (length (p!!1)) $ p!!2) (init . tail $ p!!4)) ++\n [left ++ p!!5]\n where first (a, b) = a:tail left ++ b:right\n second (a, b) = left ++ a:tail right ++ [b]\n right = replicate ( length (p!!5) - 1 ) '.'\n left = replicate ( length (p!!0) - 1 ) '.'\n"}, {"source_code": "import Data.List\nimport GHC.Exts\n\nmain = interact solve\n\nsolve str =\n let wd = lines str\n crosswords = sort [makeCrossword p | p <- permutations wd, good p]\n in if null crosswords\n then \"Impossible\"\n else unlines . head $ crosswords\n\ngood p = head (p!!0) == head (p!!1) &&\n last (p!!0) == head (p!!2) &&\n last (p!!1) == head (p!!3) &&\n last (p!!3) == head (p!!4) &&\n last (p!!2) == head (p!!5) &&\n last (p!!5) == last (p!!4) &&\n l!!1 > 2 && l!!0 > 2 && l!!4 > 2 && l!!5 > 2 &&\n l!!3 == l!!0 + l!!5 - 1 &&\n l!!2 == l!!1 + l!!4 - 1 &&\n p!!3!!(l!!0 - 1) == p!!2!!(l!!1 - 1)\n where\n l = map length p\n\nmakeCrossword p = (p!!0 ++ right):\n map first (zip (init . tail $ p!!1) (init . tail $ p!!2)) ++\n [p!!3] ++\n map second (zip (tail . drop (length (p!!1)) $ p!!2) (init . tail $ p!!4)) ++\n [left ++ p!!5]\n where first (a, b) = a:tail left ++ b:right\n second (a, b) = left ++ a:tail right ++ [b]\n right = replicate ( length (p!!5) - 1 ) '.'\n left = replicate ( length (p!!0) - 1 ) '.'\n"}], "src_uid": "8e89a34ab25f294b7ae4008403ef0b9f"} {"source_code": "import Data.Array.IArray\nimport Text.Printf\n\nintersect :: (Integer, Integer) -> (Integer, Integer) -> Integer\nintersect (a, b) (c, d) = max 0 ans\n\twhere ans = min b d - max a c\n\nones :: [(Integer, Integer)]\nones = [(10^x, 2*10^x) | x <- [0..19]]\n\nprob1 :: (Integer, Integer) -> Double\nprob1 (a,b) = count1 / total\n where count1 = fromIntegral $ sum $ map (intersect (a, b+1)) ones\n total = fromIntegral (b - a + 1)\n\ndp :: Array Int Double -> Int -> Double\ndp probs k = f' n k\n where\n n = length $ indices probs\n\n arr :: Array (Int,Int) Double\n arr = listArray ((0, 0), (n, k)) $\n [f n' k' | n' <- [0..n], k' <- [0..k]]\n f' = curry (arr !)\n\n f :: Int -> Int -> Double\n f n' k'\n | n' == 0 && k' == 0 = 1\n | n' == 0 = 0\n | otherwise =\n p1 * f' (n'-1) (max (k'-1) 0) +\n (1-p1) * f' (n'-1) k'\n\n where p1 = probs ! n'\n\nreadInterval :: Int -> IO [(Integer, Integer)]\nreadInterval 0 = return $ []\nreadInterval l = do\n [a, b] <- (map read . words) `fmap` getLine\n ret <- readInterval (l-1)\n return $ (a,b) : ret\n\nmain = do\n n <- read `fmap` getLine\n intervals <- readInterval n\n k <- read `fmap` getLine\n let k' = ceiling $ fromIntegral n * k / 100\n\n let probs = listArray (1,n) [prob1 x | x <- intervals]\n\n let ans = dp probs k'\n\n printf \"%.12f\\n\" ans\n", "positive_code": [{"source_code": "import Control.Monad\n\ngetA = fmap (map read . words) getLine\n\ncnt n = let (m:t) = reverse $ takeWhile (<=n) $ iterate (*10) 1 in sum t + min m (n - m)\n\ngao [] = [1.0]\ngao ([l,r]:t) = zipWith (\\i j -> p * i + (1 - p) * j) (0:a) (a++[0]) where\n\tu = r + 1\n\tp = fromInteger (cnt u - cnt l) / fromInteger (u - l)\n\ta = gao t\n\nmain = do\n\t[n] <- getA\n\ta <- replicateM (fromInteger n) getA\n\t[k] <- getA\n\tputStrLn $ show $ sum $ drop (fromInteger $ div (n * k + 99) 100) $ gao a\n"}, {"source_code": "\nimport Data.Array\nimport Control.Applicative\nimport Control.Monad\n\n-- import Control.DeepSeq\n\n-- import Test.QuickCheck\n\n-- import Debug.Trace\n\n-- debug = flip trace\n\n-- testnBWO :: Gen Bool\n-- testnBWO = do\n-- l <- choose (1, 10^18)\n-- u <- choose (l, 10^18)\n-- let nBWO' = length . filter beginWithOne\n-- return $ nBWO l u == fi (nBWO' [l..u])\n \n-- testnBWO2 :: Gen Prop\n-- testnBWO2 = do\n-- l <- choose (1, 10)\n-- let nBWO' = length . filter beginWithOne\n-- whenFail (print l) $ nBWO l l == fi (nBWO' [l])\n \n-- testnBWO3 :: Gen Prop\n-- testnBWO3 = do\n-- l <- choose (1, 10)\n-- u <- choose (l, 10)\n-- let nBWO' = length . filter beginWithOne\n-- whenFail (print (l, u)) $ nBWO l u == fi (nBWO' [l..u])\n\n-- testLeast :: Gen Bool\n-- testLeast = do\n-- n <- choose (1, 100) :: Gen Int\n-- p <- choose (1, 100) :: Gen Int\n-- return $ ceiling (fi n * fi p / 100.0) == ceiling (fi n * fi p / 100.0 - eps)\n \n-- test1 :: Gen Bool\n-- test1 = do\n-- n <- choose (1, 1000)\n-- p <- choose (1, 100) :: Gen Int\n-- let input = replicate n [1,1]\n-- return $ prob n input p == 1\n \n-- test0 :: Gen Bool\n-- test0 = do\n-- n <- choose (1, 1000)\n-- p <- choose (1, 100) :: Gen Int\n-- let input = replicate n [2,2]\n-- return $ prob n input p == 0\n \neps = 1e-10\n\nbeginWithOne :: Integer -> Bool\nbeginWithOne n = head (show n) == '1'\n\nsepD :: Double -> (Integer, Double)\nsepD d = (floor d', d' - fromIntegral (floor d'))\n where d' = d + eps\n\nfi :: (Num b, Integral a) => a -> b\nfi = fromIntegral\n\nnBWO :: Integer -> Integer -> Integer\nnBWO 1 u\n | u < 10 = 1\nnBWO l u =\n let (li, lf) = sepD $ logBase 10 (fi l)\n (ui, uf) = sepD $ logBase 10 (fi u)\n headM = if beginWithOne l then l - 10 ^ li else 10 ^ li\n tailP = if beginWithOne u then u - 10 ^ ui + 1 else 10 ^ ui \n middl = (sum $ map (10^) [li..ui - 1])\n in middl `seq` tailP - headM + middl \n -- `debug` (show l ++ \" \" ++ show u ++ \" \" ++ show headM ++ \" \" ++ show middl ++ \" \" ++ show tailP)\n \nprob1 l u = \n fi (nBWO l u) / (fi u - fi l + 1)\n \nprob0 l u =\n 1 - prob1 l u\n\ngo arrOld [l, u] = \n arrOld `seq`\n array (0, 1000) $ \n [ (0, prob0 l u * arrOld ! 0)] ++\n [ ind `seq` prob `seq` (ind, prob)\n | ind <- [1..1000],\n let prob = prob1 l u * (arrOld ! (ind - 1)) + prob0 l u * (arrOld ! ind)\n ]\n\narrInit :: Array Int Double\narrInit = listArray (0, 1000) (1:repeat 0)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Integer]\ngetInts = map read . words <$> getLine\n\nprob n lines p = \n let least = ceiling (fi n * fi p / 100.0 - eps)\n arr = foldl go arrInit lines\n prob = sum $ map (arr !) [least .. n]\n in prob\n\nmain = do\n -- verboseCheck test1\n n <- getInt\n lines <- replicateM n $ getInts\n p <- getInt\n print (prob n lines p)\n"}, {"source_code": "\nimport Data.Array\nimport Control.Applicative\nimport Control.Monad\n\n-- import Test.QuickCheck\n\n-- import Debug.Trace\n\n-- debug = flip trace\n\n-- testnBWO :: Gen Bool\n-- testnBWO = do\n-- l <- choose (1, 1^18)\n-- u <- choose (l, 1^18)\n-- let nBWO' = length . filter beginWithOne\n-- return $ nBWO l u == fi (nBWO' [l..u])\n \n-- testnBWO2 :: Gen Prop\n-- testnBWO2 = do\n-- l <- choose (1, 10)\n-- let nBWO' = length . filter beginWithOne\n-- whenFail (print l) $ nBWO l l == fi (nBWO' [l])\n \n-- testnBWO3 :: Gen Prop\n-- testnBWO3 = do\n-- l <- choose (1, 10)\n-- u <- choose (l, 10)\n-- let nBWO' = length . filter beginWithOne\n-- whenFail (print (l, u)) $ nBWO l u == fi (nBWO' [l..u])\n\n-- testLeast :: Gen Bool\n-- testLeast = do\n-- n <- choose (1, 100) :: Gen Int\n-- p <- choose (1, 100) :: Gen Int\n-- return $ ceiling (fi n * fi p / 100.0) == ceiling (fi n * fi p / 100.0 - eps)\n \n-- test1 :: Gen Bool\n-- test1 = do\n-- n <- choose (1, 100)\n-- p <- choose (1, 100) :: Gen Int\n-- let input = replicate n [1,1]\n-- return $ prob n input p == 1\n \n-- test0 :: Gen Bool\n-- test0 = do\n-- n <- choose (1, 100)\n-- p <- choose (1, 100) :: Gen Int\n-- let input = replicate n [2,2]\n-- return $ prob n input p == 0\n \neps = 1e-10\n\nbeginWithOne :: Integer -> Bool\nbeginWithOne n = head (show n) == '1'\n\nsepD :: Double -> (Integer, Double)\nsepD d = (floor d', d' - fromIntegral (floor d'))\n where d' = d + eps\n\nfi :: (Num b, Integral a) => a -> b\nfi = fromIntegral\n\nnBWO :: Integer -> Integer -> Integer\nnBWO 1 u\n | u < 10 = 1\nnBWO l u =\n let (li, lf) = sepD $ logBase 10 (fi l)\n (ui, uf) = sepD $ logBase 10 (fi u)\n headM = if beginWithOne l then l - 10 ^ li else 10 ^ li\n tailP = if beginWithOne u then u - 10 ^ ui + 1 else 10 ^ ui \n middl = (sum $ map (10^) [li..ui - 1])\n in middl `seq` tailP - headM + middl \n -- `debug` (show l ++ \" \" ++ show u ++ \" \" ++ show headM ++ \" \" ++ show middl ++ \" \" ++ show tailP)\n \nprob1 l u = \n fi (nBWO l u) / (fi u - fi l + 1)\n \nprob0 l u =\n 1 - prob1 l u\n\ngo arrOld [l, u] = \n array (0, 1000) $ \n [ (0, prob0 l u * arrOld ! 0)] ++\n [ (ind, prob)\n | ind <- [1..1000],\n let prob = prob1 l u * (arrOld ! (ind - 1)) + prob0 l u * (arrOld ! ind)\n ]\n\narrInit :: Array Int Double\narrInit = listArray (0, 1000) (1:repeat 0)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Integer]\ngetInts = map read . words <$> getLine\n\nprob n lines p = \n let least = ceiling (fi n * fi p / 100.0 - eps)\n arr = foldl go arrInit lines\n prob = sum $ map (arr !) [least .. n]\n in prob\n\nmain = do\n n <- getInt\n lines <- replicateM n $ getInts\n p <- getInt\n print (prob n lines p)\n"}], "negative_code": [{"source_code": "\nimport Data.Array\nimport Control.Applicative\nimport Control.Monad\n\neps = 1e-10\n\nbeginWithOne :: Integer -> Bool\nbeginWithOne n = head (show n) == '1'\n\nsepD :: Double -> (Integer, Double)\nsepD d = (floor d', d' - fromIntegral (floor d'))\n where d' = d + eps\n\nfi :: (Num b, Integral a) => a -> b\nfi = fromIntegral\n\nnBWO :: Integer -> Integer -> Integer\nnBWO l u =\n let (li, lf) = sepD $ logBase 10 (fi l)\n (ui, uf) = sepD $ logBase 10 (fi u)\n headM = if beginWithOne l then l - 10 ^ li else 0 \n tailP = if beginWithOne u then u - 10 ^ ui + 1 else 10 ^ ui\n middl = (sum $ map (10^) [li + 1..ui - 1])\n in middl `seq` tailP - headM + middl\n \nprob1 l u = \n fi (nBWO l u) / (fi u - fi l + 1)\n \nprob0 l u =\n 1 - prob1 l u\n\ngo arrOld [l, u] = \n array (0, 1000) $ \n [ (0, prob0 l u * arrOld ! 0)] ++\n [ (ind, prob)\n | ind <- [1..1000],\n let prob = prob1 l u * (arrOld ! (ind - 1)) + prob0 l u * (arrOld ! ind)\n ]\n\narrInit :: Array Int Double\narrInit = listArray (0, 1000) (1:repeat 0)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Integer]\ngetInts = map read . words <$> getLine\n\nmain = do\n n <- getInt\n lines <- replicateM n $ getInts\n p <- getInt\n let least = ceiling (fi n * fi p / 100.0)\n arr = foldl go arrInit lines\n prob = sum $ map (arr !) [least .. n]\n difference [n, m] = abs (n - m)\n full = sum $ map difference lines\n print prob\n "}, {"source_code": "\nimport Data.Array\nimport Control.Applicative\nimport Control.Monad\n\n-- import Test.QuickCheck\n\n-- testnBWO :: Gen Bool\n-- testnBWO = do\n-- l <- choose (1, 1^18)\n-- u <- choose (l, 1^18)\n-- let nBWO' = length . filter beginWithOne\n-- return $ nBWO l u == fi (nBWO' [l..u])\n\neps = 1e-10\n\nbeginWithOne :: Integer -> Bool\nbeginWithOne n = head (show n) == '1'\n\nsepD :: Double -> (Integer, Double)\nsepD d = (floor d', d' - fromIntegral (floor d'))\n where d' = d + eps\n\nfi :: (Num b, Integral a) => a -> b\nfi = fromIntegral\n\nnBWO :: Integer -> Integer -> Integer\nnBWO l u =\n let (li, lf) = sepD $ logBase 10 (fi l)\n (ui, uf) = sepD $ logBase 10 (fi u)\n headM = if beginWithOne l then l - 10 ^ li else 0 \n tailP = if beginWithOne u then u - 10 ^ ui + 1 else 10 ^ ui\n middl = (sum $ map (10^) [li + 1..ui - 1])\n in middl `seq` tailP - headM + middl\n \nprob1 l u = \n fi (nBWO l u) / (fi u - fi l + 1)\n \nprob0 l u =\n 1 - prob1 l u\n\ngo arrOld [l, u] = \n array (0, 1000) $ \n [ (0, prob0 l u * arrOld ! 0)] ++\n [ (ind, prob)\n | ind <- [1..1000],\n let prob = prob1 l u * (arrOld ! (ind - 1)) + prob0 l u * (arrOld ! ind)\n ]\n\narrInit :: Array Int Double\narrInit = listArray (0, 1000) (1:repeat 0)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Integer]\ngetInts = map read . words <$> getLine\n\nmain = do\n n <- getInt\n lines <- replicateM n $ getInts\n p <- getInt\n let least = ceiling (fi n * fi p / 100.0 - eps)\n arr = foldl go arrInit lines\n prob = sum $ map (arr !) [least .. n]\n difference [n, m] = abs (n - m)\n full = sum $ map difference lines\n print prob\n "}], "src_uid": "ad4bdd6cee78cbcd357e048cd342a42b"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype Input = [Int]\ntype Output = Int\n\ninput :: Scanner Input\ninput = numberOf int\n\noutput :: Output -> C.ByteString\noutput = showB\n\nsolve :: Input -> Output\nsolve xs\n | isJust a && isJust b = min (fromJust a) (fromJust b)\n | isJust a = fromJust a\n | otherwise = fromMaybe (-1) b\n where\n n = length xs\n ixs = [i | (v, i) <- zip xs [0..n], odd v]\n a = compute ixs [0, 2 .. n - 1]\n b = compute ixs [1, 3 .. n - 1]\n\ncompute ixs ts\n | length ixs /= length ts = Nothing\n | otherwise = Just . sum . map abs $ zipWith (-) ixs ts\n\ncount :: Eq a => a -> [a] -> Int\ncount v = length . filter (== v)\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\nimport Data.Int\n\ninterleave :: [t] -> [t] -> [t]\ninterleave [] ys = ys\ninterleave (x:xs) ys = x : interleave ys xs\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [t] <- getInts 1\n replicateM_ t $ do\n [n] <- getInts 1\n a <- getInts n\n let\n eIxs = [i | (i, ai) <- zip [1..] a, even ai]\n oIxs = [i | (i, ai) <- zip [1..] a, odd ai]\n efst = interleave eIxs oIxs\n ofst = interleave oIxs eIxs\n opts = case length eIxs - length oIxs of\n -1 -> [ofst]\n 0 -> [efst, ofst]\n 1 -> [efst]\n _ -> []\n cost = foldl' (\\x (i, tar) -> x + abs (i - tar)) 0\n ans = if null opts\n then 0-1\n else minimum [cost $ zip opt [1..] | opt <- opts] `div` 2\n putInt64s [ans]\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Functor.Identity\nimport Data.Semigroup\n\nimport Data.List\n\ninterleave :: [t] -> [t] -> [t]\ninterleave [] ys = ys\ninterleave (x:xs) ys = x : interleave ys xs\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [t] <- getInts 1\n replicateM_ t $ do\n [n] <- getInts 1\n a <- getInts n\n let\n eIxs = [i | (i, ai) <- zip [1..] a, even ai]\n oIxs = [i | (i, ai) <- zip [1..] a, odd ai]\n efst = interleave eIxs oIxs\n ofst = interleave oIxs eIxs\n opts = case length eIxs - length oIxs of\n -1 -> [ofst]\n 0 -> [efst, ofst]\n 1 -> [efst]\n _ -> []\n cost = foldl' (\\x (i, tar) -> x + abs (i - tar)) 0\n ans = if null opts\n then 0-1\n else minimum [cost $ zip opt [1..] | opt <- opts] `div` 2\n putInts [ans]\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\nliftPure :: Monad m => SP Identity t -> SP m t\nliftPure = mapStateT (pure . runIdentity)\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> SIO ()\nputInts vs = let\n sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in lift $ B.hPutBuilder stdout $ case vs of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded sepPrim xs <> B.char7 '\\n'\n"}], "src_uid": "be51a3e4038bd9a3f6d4993b75a20d1c"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array.Unboxed\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve n m ps (l, r, x) = (x - l) == (length $ filter (< (ps!x)) [ps!i | i <- [l..r]])\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n ps :: UArray Int Int <- listArray (1, n) . readInts <$> B.getLine\n lrxs <- map (\\(l:r:x:_) -> (l, r, x)) <$> replicateM m (readInts <$> B.getLine)\n putStrLn $ unlines . map (\\lrx -> if solve n m ps lrx then \"Yes\" else \"No\") $ lrxs", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt = fst . fromJust . B.readInt\n\nmain :: IO ()\nmain = do\n [n, m] <- liftM (map readInt . B.words) B.getLine\n p <- liftM (map readInt . take n . B.words) B.getLine :: IO [Int]\n let process :: Int -> IO ()\n process 0 = return ()\n process m = do\n [l, r, x] <- liftM (map readInt . B.words) B.getLine\n let slice = filter (< p !! (x - 1)) $ (take (r - l + 1) . drop (l - 1)) p\n putStrLn $ if length slice == (x - l) then \"Yes\" else \"No\"\n process (m - 1)\n process m"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\n\nreadInt :: B.ByteString -> Int\nreadInt = fst . fromJust . B.readInt\n\nsolve :: Int -> Int -> [Int] -> IO ()\nsolve 0 _ _ = return ()\nsolve m n a = do\n [l, r, x] <- liftM (map readInt . B.words) B.getLine\n let sp = filter (< (a !! (x - 1))) (take (r - l + 1) $ drop (l - 1) a)\n putStrLn $ if length sp /= x - l then \"No\" else \"Yes\"\n solve (m - 1) n a\n\nmain :: IO ()\nmain = do\n [n, m] <- liftM (map readInt . B.words) B.getLine\n a <- liftM (map readInt . take n . B.words) B.getLine\n -- return ()\n-- s <- B.getLine\n-- p <- B.getLine\n-- let [n, m] = map read (words s) :: [Int]\n-- let a = map read (words p) :: [Int]\n solve m n a\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array.Unboxed\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve n m ps (l, r, x) \n | odd (r - l + 1) = (==) <$> fst <*> snd $ foldl' (\\(s, b) a -> case compare (ps!x) a of\n LT -> (s + 1, b)\n GT -> (s, b + 1)\n otherwise -> (s, b)) (0, 0) [ps!i | i <- [l..r]]\n | otherwise = False\n\nmain = do\n n:m:_ <- readInts <$> B.getLine\n ps :: UArray Int Int <- listArray (1, n) . readInts <$> B.getLine\n lrxs <- map (\\(l:r:x:_) -> (l, r, x)) <$> replicateM m (readInts <$> B.getLine)\n putStrLn $ unlines . map (\\lrx -> if solve n m ps lrx then \"Yes\" else \"No\") $ lrxs"}], "src_uid": "44162a97e574594ac0e598368e8e4e14"} {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_, replicateM)\r\nimport Data.Maybe (maybe, catMaybes)\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nsolve :: [(Int, Int)] -> Int\r\nsolve rs = 2 * (maximum (map (snd . rotate) rs) +\r\n sum (map (fst . rotate) rs))\r\n where rotate (x, y)\r\n | x <= y = (x, y)\r\n | otherwise = (y, x)\r\n\r\nreadSlice :: IO (Maybe (Int, Int))\r\nreadSlice = do\r\n vs <- map readInt . B.words <$> B.getLine\r\n case vs of [x, y] -> pure (Just (x, y))\r\n _ -> pure Nothing\r\n\r\nhandleProblem :: IO ()\r\nhandleProblem = do\r\n numberSlices <- readInt <$> B.getLine\r\n slices <- catMaybes <$> replicateM numberSlices readSlice\r\n print $ solve slices\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberProblems <- readInt <$> B.getLine\r\n replicateM_ numberProblems handleProblem\r\n\r\nreadInt :: B.ByteString -> Int\r\nreadInt v = maybe 0 fst $ B.readInt v\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Lazy.Builder\r\nimport Data.ByteString.Lazy.Builder.ASCII\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . intercalate \" \" . map show\r\n\r\nsolve xs = 2 * (maxv + mins)\r\n where maxv = maximum $ map (\\(a, b) -> max a b) xs\r\n mins = sum $ map (\\(a, b) -> min a b) xs\r\n\r\nmain = do\r\n [t] <- getInts\r\n forM_ [1..t] $ \\_ -> do\r\n [n] <- getInts\r\n xs <- forM [1..n] $ \\_ -> do\r\n [a, b] <- getInts\r\n return (a, b)\r\n print $ solve xs\r\n "}], "negative_code": [], "src_uid": "7100fa11adfa0c1f5d33f9e3a1c3f352"} {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- getLine\r\n let s' = dropWhile (=='1') $ reverse $ dropWhile (=='1') s\r\n ans | '0' `elem` s' && '1' `elem` s' = 2\r\n | '0' `elem` s' = 1\r\n | otherwise = 0\r\n print ans\r\n\r\nmain :: IO ()\r\nmain = readLn >>= flip replicateM_ solve\r\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\n\ncalc :: String -> Int\ncalc \"10\" = 1\ncalc \"01\" = 1\ncalc \"0\" = 1\ncalc \"1\" = 0\ncalc ('0':'0':xs) = calc ('0':xs)\ncalc ('1':xs) = calc xs\ncalc ('0':xs) =\n if elem '0' xs then 2\n else 1\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n print $ calc line\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Data.List (group)\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> map (solve >>> show) >>> unlines\n\nsolve :: String -> Int\nsolve = min 2 . length . filter (== '0') . map head . group\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[s] <- getNext 1\n let\n s1 = P.dropWhile (== '1') s\n (c, s2) = P.span (== '0') s1\n s3 = P.dropWhile (== '1') s2\n pure . putInts . pure $ if P.null c\n then 0\n else if P.null s3\n then 1\n else 2\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\n\ncalc :: String -> Int\ncalc s =\n let cz = foldl (\\x y -> if y=='0' then x+1 else x) 0 s\n l = length s\n in\n if cz==0 then 0\n else if cz==1 then 1\n else if cz==l then 1\n else 2\n\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n print $ calc line\n"}], "src_uid": "2e6ddb2b11f8ac857e81d4b9b0c7d783"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\nmain = do\n n <- readLn\n if even n\n then print $ -1\n else do\n putStrLn . unwords $ map show [0..n-1]\n putStrLn . unwords $ map show [0..n-1]\n putStrLn . unwords $ map show [ (i+i)`rem`n | i<-[0..n-1]]\n", "positive_code": [{"source_code": "{-#LANGUAGE OverloadedStrings#-}\nmodule Main where\n\nimport Data.List\n\nmain :: IO ()\nmain = ( readLn :: IO Int ) >>= solve >>= putStrLn\n\nsolve :: Int -> IO String\nsolve n\n | even n = pure \"-1\"\n | otherwise =\n pure . intercalate \"\\n\" $ fin\n where\n l1 = [0..n-1]\n l2 = map ( flip mod n . (*2) ) l1\n a = showL l1\n b = showL l2\n fin = [ a,a,b ]\n\nshowL :: [Int] -> String\nshowL = intercalate \" \" . map show"}, {"source_code": "{-#LANGUAGE OverloadedStrings#-}\nmodule Main where\n\nimport Data.List\n\nmain :: IO ()\nmain = ( readLn :: IO Int ) >>= solve >>= putStrLn\n\nsolve :: Int -> IO String\nsolve n\n | even n = pure \"-1\"\n | otherwise =\n pure . intercalate \"\\n\" $ map showL l3\n where\n l :: [Int]\n l = [0..n-1]\n l3 = [ l, l, map (flip mod n . (*2)) l ]\n\nshowL :: [Int] -> String\nshowL = intercalate \" \" . map show"}, {"source_code": "\n\nsolve 1 = \"0\\n0\\n0\"\nsolve n\n | n `mod` 2 == 0 = \"-1\"\n | otherwise =\n let \n a = [0..n-1]\n b = [(2 * x) `mod` (n) | x <- a]\n f = unwords . map show\n in\n unlines [f a, f a, f b]\n\nmain = do\n n <- fmap read getLine\n putStrLn $ solve n\n"}, {"source_code": "main = interact (format . solve . read)\nformat Nothing = \"-1\"\nformat (Just (as,bs,cs)) = unlines (map (unwords . (map show)) [as,bs,cs])\nsolve n | even n = Nothing\n | otherwise = Just ([0..n-1],[0..n-1],[0,2..n-1]++[1,3..n-1])\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n if n `mod` 2 /= 0\n then mapM_ (\\x -> putStrLn $ unwords (map show x)) [[0..n-1], [0..n-1], f n]\n else print $ -1\n\nf n = [(x+x) `mod` n | x <- [0..n-1]]"}, {"source_code": "main :: IO()\nmain = interact work\n \nwork :: String -> String\nwork input = unlines . map unwords . map (map show) . solve $ n\n where n = read input :: Int\n\nsolve :: Int -> [[Int]]\nsolve n = if n `mod` 2 == 0 \n then [[-1]]\n else [a, a, [i * 2 `mod` n | i <- a]]\n where a = [0..n - 1]\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n if ff n\n then mapM_ (\\x -> putStrLn $ unwords (map show x)) [[0..n-1], [0..n-1], f n]\n else print $ -1\n\nff n = length(a) /= 0 && n > 2\n where\n a = filter (\\x -> n `mod` x == 0 && odd x) [2..n-1]\n\nf n = [(x+x) `mod` n | x <- [0..n-1]]"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n if ff n || n <= 2\n then print $ -1\n else mapM_ (print) [[0..n-1], [0..n-1], f n]\n\nff n = any (\\x -> n `mod` x == 0) [2..n-1]\nf n = [(x+x) `mod` n | x <- [0..n-1]]"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n if ff n && n > 2\n then mapM_ (\\x -> putStrLn $ unwords (map show x)) [[0..n-1], [0..n-1], f n]\n else print $ -1\n\nff n = length(a) == 0 || head(a)*head(a) == n\n where\n a = filter (\\x -> n `mod` x == 0) [2..n-1]\n\nf n = [(x+x) `mod` n | x <- [0..n-1]]"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n if ff n || n <= 2\n then print $ -1\n else mapM_ (\\x -> putStrLn $ unwords (map show x)) [[0..n-1], [0..n-1], f n]\n\nff n = any (\\x -> n `mod` x == 0) [2..n-1]\nf n = [(x+x) `mod` n | x <- [0..n-1]]"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n if ff n && n > 2\n then mapM_ (\\x -> putStrLn $ unwords (map show x)) [[0..n-1], [0..n-1], f n]\n else print $ -1\n\nff n = length(a) /= 0\n where\n a = filter (\\x -> n `mod` x == 0 && odd x) [2..n]\n\nf n = [(x+x) `mod` n | x <- [0..n-1]]"}, {"source_code": "\n\nsolve 1 = \"0\"\nsolve n\n | n `mod` 2 == 0 = \"-1\"\n | otherwise =\n let \n a = [0..n-1]\n b = [(2 * x) `mod` (n) | x <- a]\n f = unwords . map show\n in\n unlines [f a, f a, f b]\n\nmain = do\n n <- fmap read getLine\n putStrLn $ solve n\n"}], "src_uid": "2f0942c531fd5758b220104c3338b702"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, xs :: [Integer]}\ntype Output = Bool\n\ninput :: Scanner TC\ninput = do\n n <- int\n xs <- n >< integer\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..}\n | length xs' >= 6 = all (== 0) xs'\n | otherwise = and [x + y + z `elem` xs | (x, i) <- ys, (y, j) <- ys, (z, k) <- ys, i < j, j < k]\n where\n xs' = filter (/= 0) xs ++ replicate (min 2 $ count 0 xs) 0\n ys = zip xs' [0..]\n\noutput :: Output -> C.ByteString\noutput = bool \"NO\" \"YES\" >>> C.pack\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [Int] -> Bool\nsolve n as = solve' $ L.sort as\n where\n solve' :: [Int] -> Bool\n solve' as\n | L.length (L.filter (< 0) as) > 3 = False\n | L.length (L.filter (> 0) as) > 3 = False\n | L.length (L.filter (== 0) as) > 2 = let \n zerosCount = L.length (L.filter (== 0) as) \n noZeros = L.filter (/= 0) as\n in \n solve' . L.sort $ noZeros ++ L.replicate (min 2 zerosCount) 0\n | otherwise = solve'' as\n\n solve'' :: [Int] -> Bool\n solve'' as = L.and $ do\n let l = L.length as\n i <- [0 .. l - 1]\n j <- [i + 1 .. l - 1]\n k <- [j + 1 .. l - 1]\n let s = (as L.!! i) + (as L.!! j) + (as L.!! k)\n\n return $ s `L.elem` as\n\n\nmain :: IO ()\nmain = do\n n <- B8.getLine <&> readIntB8\n replicateM_ n $ do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> readIntB8s\n let answer = solve n as\n putsYesNo answer\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE CPP #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Bool\r\nimport Debug.Trace\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC {n :: Int, xs :: [Integer]}\r\ntype Output = Bool\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n xs <- n >< integer\r\n return TC {..}\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..}\r\n | n' >= 6 = all (== 0) xs'\r\n | otherwise = and [x + y + z `elem` xs | (x, i) <- ys, (y, j) <- ys, (z, k) <- ys, i < j, j < k]\r\n where\r\n nxs = filter (/= 0) xs\r\n zc = count 0 xs\r\n xs' = nxs ++ replicate zc 0\r\n n' = length xs'\r\n ys = zip xs' [0..]\r\n\r\noutput :: Output -> C.ByteString\r\noutput = bool \"NO\" \"YES\" >>> C.pack\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Debug\r\ndebug :: Show a => a -> a\r\n#ifdef ONLINE_JUDGE\r\ndebug = id\r\n#else\r\ndebug a = trace (show a) a\r\n#endif\r\n\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, xs :: [Integer]}\ntype Output = Bool\n\ninput :: Scanner TC\ninput = do\n n <- int\n xs <- n >< integer\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..}\n | n >= 8 = all (== 0) xs\n | otherwise = and [x + y + z `elem` xs | (x, i) <- ys, (y, j) <- ys, (z, k) <- ys, i < j, j < k]\n where\n ys = zip xs [0..]\n\noutput :: Output -> C.ByteString\noutput = bool \"NO\" \"YES\" >>> C.pack\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, xs :: [Int]}\ntype Output = Bool\n\ninput :: Scanner TC\ninput = do\n n <- int\n xs <- n >< int\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..}\n | n >= 8 = all (== 0) xs\n | otherwise = and [x + y + z `elem` xs | (x, i) <- ys, (y, j) <- ys, (z, k) <- ys, i /= j, i /= k, j /= k]\n where\n ys = zip xs [0..]\n\noutput :: Output -> C.ByteString\noutput = bool \"NO\" \"YES\" >>> C.pack\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\nimport Debug.Trace\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {n :: Int, xs :: [Int]}\ntype Output = Bool\n\ninput :: Scanner TC\ninput = do\n n <- int\n xs <- n >< int\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..}\n | n >= 6 = all (== 0) xs\n | otherwise = and [x + y + z `elem` xs | (x, i) <- ys, (y, j) <- ys, (z, k) <- ys, i /= j, i /= k, j /= k]\n where\n ys = zip xs [0..]\n\noutput :: Output -> C.ByteString\noutput = bool \"NO\" \"YES\" >>> C.pack\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "src_uid": "70028bbb9b7bce1f0d2753275b3e752f"} {"source_code": "import Control.Monad\r\nimport Control.Monad.State\r\nimport Data.Array\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Data.Char\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Char as C\r\n\r\ndata Info = Empty !Int\r\n | NonEmpty !Int !Int !Int\r\n deriving Show\r\n\r\ninstance Semigroup Info where\r\n Empty m1 <> Empty m2 = Empty (m1 `xor` m2)\r\n Empty m1 <> NonEmpty l2 m2 r2 = NonEmpty (m1 `xor` l2) m2 r2\r\n NonEmpty l1 m1 r1 <> Empty m2 = NonEmpty l1 m1 (r1 `xor` m2)\r\n NonEmpty l1 m1 r1 <> NonEmpty l2 m2 r2\r\n | r1 `xor` l2 == 1 = NonEmpty l1 (m1 + m2) r2\r\n | m1 > m2 = NonEmpty l1 (m1 - m2) (r2 `xor` 1)\r\n | m1 < m2 = NonEmpty (l1 `xor` 1) (m2 - m1) r2\r\n | otherwise = Empty (l1 `xor` r2)\r\n\r\ninstance Monoid Info where\r\n mempty = Empty 0\r\n\r\ncharToInfo :: Char -> Info\r\ncharToInfo c\r\n | c == '(' || c == ')' = Empty 1\r\n | c == '[' || c == ']' = NonEmpty 0 1 0\r\n | otherwise = error \"!\"\r\n\r\ncost :: Info -> Int\r\ncost (Empty _) = 0\r\ncost (NonEmpty _ m _) = m\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- C.unpack . C.takeWhile (not . isSpace) <$> C.getLine\r\n ~[q] <- readInts\r\n qrys <- replicateM q readInts\r\n let infoST = fromListST (1, length s) $ map charToInfo s\r\n doQry ~[l, r] = cost $ foldRangeST l r infoST\r\n putStr $ unlines $ map (show . doQry) qrys\r\n\r\n--------------------------------------------------------------------------------\r\n\r\ndata SegTree a = SegTree !(Int, Int, Int) !(SegNode a) deriving Show\r\ndata SegNode a = SLeaf !a | SBin !a !(SegNode a) !(SegNode a) deriving Show\r\n\r\nbuildST :: Monoid a => (Int, Int) -> (Int -> SegNode a) -> SegTree a\r\nbuildST (l, r) f\r\n | n < -1 = error \"invalid range\"\r\n | n == -1 = SegTree (l, r, 0) $ SLeaf mempty\r\n | otherwise = SegTree (l, r, bit ht) $ f ht\r\n where\r\n n = r - l\r\n ht = finiteBitSize n - countLeadingZeros n\r\n\r\nmakeSN :: Semigroup a => SegNode a -> SegNode a -> SegNode a\r\nmakeSN lt rt = SBin (getx lt <> getx rt) lt rt where\r\n getx (SLeaf x) = x\r\n getx (SBin x _ _) = x\r\n\r\nfromListST :: Monoid a => (Int, Int) -> [a] -> SegTree a\r\nfromListST bnds xs = buildST bnds (flip evalState xs . go) where\r\n pop = state go where\r\n go [] = (mempty, [])\r\n go (x:xs) = (x, xs)\r\n go j | j == 0 = SLeaf <$> pop\r\n go j = makeSN <$> go (j - 1) <*> go (j - 1)\r\n\r\nfoldRangeST :: Monoid a => Int -> Int -> SegTree a -> a\r\nfoldRangeST ql qr _ | ql > qr + 1 = error \"invalid range\"\r\nfoldRangeST ql qr (SegTree (l, _, p) root) = go root l (l + p - 1) mempty where\r\n go _ l r acc | r < ql || qr < l = acc\r\n go (SLeaf x) _ _ acc = acc <> x\r\n go (SBin x lt rt) l r acc\r\n | ql <= l && r <= qr = acc <> x\r\n | otherwise = go rt (m + 1) r $! go lt l m acc\r\n where m = (l + r) `div` 2\r\n\r\n--------------------------------------------------------------------------------\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Control.Monad.State\r\nimport Data.Array\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Data.Char\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.Char as C\r\n\r\ndata Info = Empty !Bool\r\n | NonEmpty !Bool !Int !Bool\r\n deriving Show\r\n\r\ninstance Semigroup Info where\r\n Empty m1 <> Empty m2 = Empty (m1 /= m2)\r\n Empty m1 <> NonEmpty l2 m2 r2 = NonEmpty (m1 /= l2) m2 r2\r\n NonEmpty l1 m1 r1 <> Empty m2 = NonEmpty l1 m1 (r1 /= m2)\r\n NonEmpty l1 m1 r1 <> NonEmpty l2 m2 r2\r\n | r1 /= l2 = NonEmpty l1 (m1 + m2) r2\r\n | m1 > m2 = NonEmpty l1 (m1 - m2) (not r2)\r\n | m1 < m2 = NonEmpty (not l1) (m2 - m1) r2\r\n | otherwise = Empty (l1 /= r2)\r\n\r\ninstance Monoid Info where\r\n mempty = Empty False\r\n\r\ncharToInfo :: Char -> Info\r\ncharToInfo c\r\n | c == '(' || c == ')' = Empty True\r\n | c == '[' || c == ']' = NonEmpty False 1 False\r\n | otherwise = error \"!\"\r\n\r\ncost :: Info -> Int\r\ncost (Empty _) = 0\r\ncost (NonEmpty _ m _) = m\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- C.unpack . C.takeWhile (not . isSpace) <$> C.getLine\r\n ~[q] <- readInts\r\n qrys <- replicateM q readInts\r\n let infoST = fromListST (1, length s) $ map charToInfo s\r\n doQry ~[l, r] = cost $ foldRangeST l r infoST\r\n putStr $ unlines $ map (show . doQry) qrys\r\n\r\n--------------------------------------------------------------------------------\r\n\r\ndata SegTree a = SegTree !(Int, Int, Int) !(SegNode a) deriving Show\r\ndata SegNode a = SLeaf !a | SBin !a !(SegNode a) !(SegNode a) deriving Show\r\n\r\nbuildST :: Monoid a => (Int, Int) -> (Int -> SegNode a) -> SegTree a\r\nbuildST (l, r) f\r\n | n < -1 = error \"invalid range\"\r\n | n == -1 = SegTree (l, r, 0) $ SLeaf mempty\r\n | otherwise = SegTree (l, r, bit ht) $ f ht\r\n where\r\n n = r - l\r\n ht = finiteBitSize n - countLeadingZeros n\r\n\r\nmakeSN :: Semigroup a => SegNode a -> SegNode a -> SegNode a\r\nmakeSN lt rt = SBin (getx lt <> getx rt) lt rt where\r\n getx (SLeaf x) = x\r\n getx (SBin x _ _) = x\r\n\r\nfromListST :: Monoid a => (Int, Int) -> [a] -> SegTree a\r\nfromListST bnds xs = buildST bnds (flip evalState xs . go) where\r\n pop = state go where\r\n go [] = (mempty, [])\r\n go (x:xs) = (x, xs)\r\n go j | j == 0 = SLeaf <$> pop\r\n go j = makeSN <$> go (j - 1) <*> go (j - 1)\r\n\r\nfoldRangeST :: Monoid a => Int -> Int -> SegTree a -> a\r\nfoldRangeST ql qr _ | ql > qr + 1 = error \"invalid range\"\r\nfoldRangeST ql qr (SegTree (l, _, p) root) = go root l (l + p - 1) mempty where\r\n go _ l r acc | r < ql || qr < l = acc\r\n go (SLeaf x) _ _ acc = acc <> x\r\n go (SBin x lt rt) l r acc\r\n | ql <= l && r <= qr = acc <> x\r\n | otherwise = go rt (m + 1) r $! go lt l m acc\r\n where m = (l + r) `div` 2\r\n\r\n--------------------------------------------------------------------------------\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Control.Monad.State\r\nimport Data.Array\r\nimport Data.Foldable\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Data.Char\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\ndata Info = Empty !Int\r\n | NonEmpty !Int !Int !Int deriving Show\r\n\r\ninstance Semigroup Info where\r\n Empty m1 <> Empty m2 = Empty (m1 `xor` m2)\r\n Empty m1 <> NonEmpty l2 m2 r2 = NonEmpty (m1 `xor` l2) m2 r2\r\n NonEmpty l1 m1 r1 <> Empty m2 = NonEmpty l1 m1 (r1 `xor` m2)\r\n NonEmpty l1 m1 r1 <> NonEmpty l2 m2 r2\r\n | r1 `xor` l2 == 1 = NonEmpty l1 (m1 + m2) r2\r\n | m1 == 1 && m2 == 1 = Empty (l1 `xor` r2)\r\n | otherwise = NonEmpty l1 (m1 + m2 - 2) r2\r\n\r\ncharToInfo :: Char -> Info\r\ncharToInfo '(' = Empty 1\r\ncharToInfo ')' = Empty 1\r\ncharToInfo '[' = NonEmpty 0 1 0\r\ncharToInfo ']' = NonEmpty 0 1 0\r\ncharToInfo _ = error \"!\"\r\n\r\ncost :: Info -> Int\r\ncost (Empty _) = 0\r\ncost (NonEmpty _ m _) = m\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- C.unpack . C.takeWhile (not . isSpace) <$> C.getLine\r\n ~[q] <- readInts\r\n qrys <- replicateM q readInts\r\n let infoSP = fromListSP (1, length s) $ map charToInfo s\r\n doQry ~[l, r] = cost $ querySP l r infoSP\r\n putStr $ unlines $ map (show . doQry) qrys\r\n\r\n--------------------------------------------------------------------------------\r\n\r\ntype SparseTable a = Array Int (Array Int a)\r\n\r\nfromArraySP :: Semigroup a => Array Int a -> SparseTable a\r\nfromArraySP a = if l > h + 1 then error \"invalid range\" else t where\r\n (l, h) = bounds a\r\n n = h - l + 1\r\n k = finiteBitSize n - countLeadingZeros n - 1\r\n t = fArray (0, k) f\r\n f j | j == 0 = a\r\n | otherwise = fArray (l, h - 2 * hf + 1) g\r\n where hf = 1 `shiftL` (j - 1)\r\n p = t!(j - 1)\r\n g i = p!i <> p!(i + hf)\r\n\r\nfromListSP :: Semigroup a => (Int, Int) -> [a] -> SparseTable a\r\nfromListSP bnds xs = fromArraySP $ listArray bnds xs\r\n\r\nquerySP :: Semigroup a => Int -> Int -> SparseTable a -> a\r\nquerySP l r _ | l > r = error \"invalid range\"\r\nquerySP l r t = go l where\r\n r' = r + 1\r\n go l | l' == r' = t!j!l\r\n | otherwise = t!j!l <> go l'\r\n where j = countTrailingZeros $ r' - l\r\n l' = l + 1 `shiftL` j\r\n\r\n--------------------------------------------------------------------------------\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = readInts >>= flip replicateM_ solve . head\r\n"}], "src_uid": "464ab27d5090b83a0d18d31d7141e329"} {"source_code": "import Data.List (sort)\n\n(-->) = flip fmap\n\nmain = do\n (n:m:_) <- getLine --> words --> map read\n as <- getLine --> words --> map read :: IO [Int]\n let ans = negate $ sum $ takeWhile (< 0) $ take m $ sort as\n print ans\n\n", "positive_code": [{"source_code": "import List\ngetA = fmap (map read . words) getLine\nmain = do\n\t[n, m] <- getA\n\ta <- getA\n\tputStr $ show $ negate $ sum $ take m $ sort $ filter (<0) a\n"}, {"source_code": "import Data.List\n\nmain = do\n\t[n, m] <- getLine >>= return . map read . words :: IO [Int]\n\ttvs <- getLine >>= return . map read . words :: IO [Int]\n\t(putStrLn . show . sum . take m . reverse . sort . filter (>0) . map (*(-1))) tvs\n"}, {"source_code": "import List\nmain = do\n s <- getLine\n let [n, m] = map read (words s)\n s <- getLine\n let ans = sum $ take m [if x > 0 then 0 else x | x <- sort (map read (words s))]\n print (-ans)"}, {"source_code": "import List\n\nreadAs :: IO [Int]\nreadAs = do\n line <- getLine\n return (map (read::String->Int) (words line))\n\nsolve :: Int -> [Int] -> Int\nsolve 0 _ = 0\nsolve _ [] = 0\nsolve m (a:as)\n | a < 0 = (-a) + solve (m - 1) as\n | otherwise = 0\n\nmain = do\n [n, m] <- readAs\n as <- readAs\n print (solve m (sort as))"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport Data.Function\n\nmain = do\n [n, m] <- map read . words <$> getLine\n tvs' <- map read . words <$> getLine\n let tvs = takeWhile (< 0) . sort $ tvs'\n earn = sum $ if length tvs > m then take m tvs else tvs\n print (- earn)"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve (m:as) = negate $ sum $ take m $ sort $ map (min 0) as\nsolve _ = undefined\n"}, {"source_code": "import Data.List\nmain = do\n [n,m] <- fmap (map read . words) getLine\n print . negate . sum . take m . sort . filter (< 0) . map read . words =<< getLine"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.map (map toInt.words).lines\n\nfunc::[[Int]]->String\nfunc (a:b:xs) = (solve (last a) b )++ func xs\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\ntoString::Int->String\ntoString=show\n\nsolve::Int->[Int]->String\nsolve a b = toString solve'\n where\n list = takeWhile (<0) (sort b)\n solve' | a < (length list) = - (sum (take a list))\n | otherwise = - (sum list)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\n-- import Data.Char\n-- import Data.Function\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n n : m : _ <- readData\n xs <- takeWhile (< 0) . take m . sort <$> readData\n printf \"%d\\n\" $ negate (sum xs)\n\n\n\n"}, {"source_code": "import Data.List\n\nsolve ns n = (*) (-1) $ sum $ filter (<= 0) $ take n (sort ns) \n\nmain = do\n n <- fmap (last . map read . words) getLine :: IO Int\n ns <- fmap (map read . words) getLine :: IO [Int]\n print $ solve ns n\n"}, {"source_code": "import Data.List\n\ngetnum :: IO [Int]\ngetnum = fmap (map read . words) getLine\n\nget m num = 0 - (sum . take m . sort . filter (<0) $ num)\n\nmain = do\n [n, m] <- getnum\n num <- getnum\n print $ get m num\n"}, {"source_code": "import List\nmain = interact (ans)\nans theInput = show a0 where\n [[n,m],a] = map ( map (read::String->Int)) $ map words $ lines theInput\n a0 = (-1) * (sum $ take m (takeWhile (< 0) (sort a)))\n"}, {"source_code": "import List\nmain = interact (ans)\nans theInput = show a1 where\n theLines = lines theInput\n line0 = words $ head theLines\n n = read (line0 !! 0) ::Int\n m = read (line0 !! 1) ::Int\n a0 = takeWhile (< 0) (sort $ map (read::String->Int) (words (theLines !! 1)))\n a1 = (-1) * (sum $ take m a0)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.IntMap as I\n\n \n\nmain=do\n\t [n,m]<- map read.words <$> getLine ::IO [Int]\n\t r<- take m .sort. filter (<0) . map (fst.fromJust.C.readInt). C.words <$> C.getLine:: IO [Int]\n\t print $ (-(sum r))"}, {"source_code": "import Data.List (sort)\n\nprocess :: Int -> [Int] -> Int\nprocess m = negate.sum.takeWhile (<0).take m.sort\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n as <- fmap (map readInt.words) getLine\n print $ process m as"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: Int -> [Int] -> Int\nsolve n = ((-1) * ) . sum . take n . sort . filter (<0)\n\n\nmain = do\n [m, n] <- map read . words <$> getLine\n tvs <- map read . words <$> getLine\n print (solve n tvs)\n\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n\t[n, m] <- getLine >>= return . map read . words :: IO [Int]\n\ttvs <- getLine >>= return . map read . words :: IO [Int]\n\t(putStrLn . show . sum . take m . sort . filter (>0) . map (*(-1))) tvs\n"}, {"source_code": "main = do\n [n,m] <- fmap (map read . words) getLine\n print . sum . map read . take m . words =<< getLine"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.map (map toInt.words).lines\n\nfunc::[[Int]]->String\nfunc (a:b:xs) = (solve (last a) b )++ func xs\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\ntoString::Int->String\ntoString=show\n\nsolve::Int->[Int]->String\nsolve a b = toString solve'\n where\n list = takeWhile (<0) (sort b)\n solve' | a < (length list) = sum (take a list)\n | otherwise = sum list\n"}, {"source_code": "import Prelude\nimport List\nimport Char\n\nmain = interact q\n\nq = func.map (map toInt.words).lines\n\nfunc::[[Int]]->String\nfunc (a:b:xs) = (solve (last a) b )++ func xs\nfunc [] = \"\"\n\ntoInt::String->Int\ntoInt = read\ntoString::Int->String\ntoString=show\n\nsolve::Int->[Int]->String\nsolve a b = toString (solve' b)\n where\n solve' = (0-).sum.take a.rsort\n\nrsort = sort"}, {"source_code": "import Data.List\n\nsolve ns n = (*) (-1) $ sum $ filter (>= 0) $ take n (sort ns) \n\nmain = do\n n <- fmap (last . map read . words) getLine :: IO Int\n ns <- fmap (map read . words) getLine :: IO [Int]\n print $ solve ns n\n"}, {"source_code": "import Data.List\n\nsolve ns n = (*) (-1) $ sum $ take n (sort ns) \n\nmain = do\n n <- fmap (last . map read . words) getLine :: IO Int\n ns <- fmap (map read . words) getLine :: IO [Int]\n print $ solve ns n\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: Int -> [Int] -> Int\nsolve n = ((-1) * ) . sum . take n . reverse . sort . filter (<0)\n\n\nmain = do\n [m, n] <- map read . words <$> getLine\n tvs <- map read . words <$> getLine\n print (solve m tvs)\n\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: Int -> [Int] -> Int\nsolve n = ((-1) * ) . sum . take n . reverse . sort . filter (<0)\n\n\nmain = do\n [m, n] <- map read . words <$> getLine\n tvs <- map read . words <$> getLine\n print (solve n tvs)\n\n"}], "src_uid": "9a56288d8bd4e4e7ef3329e102f745a5"} {"source_code": "import Control.Monad\n\nmain = readLn >>= flip replicateM_ solve\n\nsolve :: IO ()\nsolve = readLn >>= putStrLn . getAns\n\ngetAns :: Int -> String\ngetAns x | x `mod` 2 == 0 = replicate (x `div` 2) '1'\n | otherwise = '7' : replicate (x `div` 2 - 1) '1'", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess d | d==2 = \"1\"\n | d==3 = \"7\"\n\t | even d = replicate (div d 2) '1'\n\t | otherwise = \"7\" ++ (replicate ((div d 2)-1) '1')\n\n\nonecase = do\t\n\t\td<-read <$> getLine ::IO Int\n\t\tputStrLn $ process d\n\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "process :: Int -> [Char]\nprocess n\n | even n = replicate (n`div`2) '1'\n | otherwise = '7':replicate ((n-3)`div`2) '1'\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n putStrLn $ process n\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "readInt :: IO Int\nreadInt = do\n t <- getLine\n return $ read t\n\ncreateString :: Int -> String\ncreateString n = (if n `mod` 2 /= 0 then '7' else '1') : replicate ((n-2) `quot` 2) '1'\n\nsolve :: Int -> IO ()\nsolve 0 = return ()\nsolve t = do\n n <- readInt\n putStrLn $ createString n\n solve (t-1)\n\nmain :: IO ()\nmain = do\n t <- readInt\n solve t"}, {"source_code": "import Control.Monad\n\ngreatest :: Int -> String\ngreatest n = if n `mod` 2 == 0\n then replicate (n `div` 2) '1'\n else '7' : greatest (n - 3)\n\nsolve :: IO ()\nsolve = do\n n <- readLn\n putStrLn $ greatest n\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t solve\n\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nsolve 0 = \"\"\nsolve n | odd n = '7':solve (n - 3) | otherwise = '1':solve (n - 2)\n\nmain = getLine >> getContents >>= mapM_ (putStrLn.solve).map read.words\n"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), (<|), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get\n putsln $ f2 n\n\nf2 :: Int -> String\nf2 n = if (mod n 2) == 1 then toList $ '7' DSeq.<| DSeq.replicate (div (n - 2) 2) '1' \n else replicate (div n 2) '1'\n"}, {"source_code": "wordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n \nrepeatNTimes 0 _ = return ()\nrepeatNTimes n action =\n do\n action\n repeatNTimes (n-1) action\n \nindex :: Int -> Int -> Int\nindex q n = (q - 1) `mod` n\n \nmain = do\n input1 <- getLine\n let t = read input1 :: Int\n\n --main cycle\n repeatNTimes t (do\n input2 <- getLine\n let n = read input2 :: Int\n\n let maxOnes = n `div` 2\n let odd = n `mod` 2 == 1\n let ones = if odd then maxOnes - 1 else maxOnes\n\n putStr $ if odd then \"7\" else \"\"\n repeatNTimes ones (do\n putStr \"1\"\n ) \n putStrLn \"\"\n )"}], "negative_code": [{"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>))\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get\n putsln $ f2 n\n\nf2 :: Int -> String\nf2 n = if n == 2 then \"1\" else\n if n == 3 then \"7\" else\n '1' : f2 (n - 2)"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>))\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get\n putsln $ f2 n\n\nf2 :: Int -> String\nf2 n = if n == 2 then \"1\" else\n if n == 3 then \"7\" else\n if n == 4 then \"11\" else\n if n == 5 then \"71\" else\n '1' : f2 (n - 2)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess d | d==2 = \"1\"\n | d==3 = \"7\"\n\t | even d = replicate (div d 2) '1'\n\t | otherwise = \"7\" ++ (replicate (div d 2) '1')\n\n\nonecase = do\t\n\t\td<-read <$> getLine ::IO Int\n\t\tputStrLn $ process d\n\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}], "src_uid": "07db573b0db736d798b6c18c06c32f3d"} {"source_code": "main :: IO()\r\n\r\nmain =\r\n interact $ unlines . map (show . process . read ). drop 1 . lines\r\n\r\nprocess i \r\n | mod i 7 == 0 = i\r\n | otherwise = let base = i - (i `mod` 10) in base + (7 - base `mod` 7);\r\n\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>= print . div7\ndiv7 :: Int -> Int\ndiv7 x | mod x 7 == 0 = x\n | otherwise = case filter (\\a -> mod a 7 == 0)\n (map (((div x 10)*10)+) [0..9]) of\n n:_ -> n\n _ -> error \"Some number in a decade must be divisible by 7.\"\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n n <- readLn\n putStrLn . show $ solve n\n return ()\n\nsolve :: Int -> Int\nsolve n\n | mod n 7 == 0 = n\n | mod n 7 <= mod n 10 = n - mod n 7\n | otherwise = n + (7 - mod n 7)\n\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn\r\n let r = n `mod` 10\r\n print $ if n `mod` 7 == 0\r\n then n\r\n else head . filter (\\x -> x `mod` 7 == 0) $ map ((n - r)+) [0..9]\r\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve :: Integral a => a -> a\nsolve n\n | mod n 7 == 0 = n\n | mod n 7 <= mod n 10 = n - mod n 7\n | otherwise = n + (7 - mod n 7)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n print $ solve n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nsolve :: Int -> Int\nsolve n = 10 * lead + lst'\n where\n !(lead, lst) = divMod n 10\n r = mod n 7\n lst'\n | r == 0 = lst\n | lst - r >= 1 = lst - r\n | otherwise = lst - r + 7\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n $ do\n x <- readLn\n print $ solve x\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>= print . div7\ndiv7 :: Int -> Int\ndiv7 x = case filter (\\a -> mod a 7 == 0) (map (((div x 10)*10)+) [0..9]) of\n n:_ -> n\n _ -> error \"Some number in a decade must be divisible by 7.\"\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n n <- readLn\n putStrLn . show $ solve n\n return ()\n\nsolve :: Int -> Int\nsolve n\n | mod n 7 == 0 = n\n | mod n 7 <= mod n 10 = n - mod n 7\n | otherwise = n + mod n 7\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn\r\n print $ if n `mod` 10 > 5\r\n then find pred n\r\n else find succ n\r\n\r\nfind :: (Int -> Int) -> Int -> Int\r\nfind f n = head . filter (\\x -> x `mod` 7 == 0) $ iterate f n\r\n"}], "src_uid": "128372d890f632494e59e81287abd85a"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe (fromMaybe)\r\n\r\ntype Scanner = State [String]\r\n\r\nrunScanner :: Scanner a -> String -> a\r\nrunScanner = runScannerWith words\r\n\r\nrunScannerWith :: (String -> [String]) -> Scanner a -> String -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\nstr :: Scanner String\r\nstr =\r\n get >>= \\case\r\n s:ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = read <$> str\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n-- main :: IO ()\r\n-- main =\r\n-- interact $\r\n-- runScanner (numberOf singleCase) >>> map (solve >>> show) >>> unlines\r\n-- where\r\n-- singleCase = do\r\n-- nlr <- times 3 int\r\n-- xs <- times (head nlr) int\r\n-- return [nlr, xs]\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>>\r\n map (words >>> map read) >>> chunksOf 2 >>> map (solve >>> show) >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [[Int]] -> I64\r\nsolve [[n, l, r], xs] =\r\n let xs' = sort xs\r\n in (`div` 2) $\r\n compute xs' r - compute xs' (l - 1) -\r\n (toInteger . length . filter (\\x -> l <= 2 * x && 2 * x <= r) $ xs)\r\n\r\ncompute :: [Int] -> Int -> I64\r\ncompute xs lim =\r\n sum . map (toInteger . snd . head) . tail $\r\n scanl\r\n (\\vs x -> dropWhile ((> lim - x) . fst) vs)\r\n (reverse $ zip ((-10 ^ 9) : xs) [0 ..])\r\n xs\r\n", "positive_code": [{"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport qualified Data.Map as Map\r\n\r\n-- import Debug.Trace\r\n-- tr s x = trace msg x where msg = \"tr: \" ++ s ++ \": \" ++ show x ++ \".\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n [_n, l, r] <- readIListLn\r\n nums <- readIListLn\r\n return (l, r, nums)\r\n\r\nreadIListLn = map read <$> words <$> getLine :: IO [Int]\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve (l, r, nums) = show $ (`div` 2) . sum . map (count l r simap) . Map.keys $ simap\r\n where\r\n inums = zip nums [1::Int ..]\r\n simap = Map.fromList . (`zip` [1::Integer ..]) $ inums\r\n\r\ncount l r simap (v,i) = Map.size simapLR - fixIfInside\r\n where\r\n (_, simapR) = Map.split (l-v , -1) simap\r\n (simapLR, _) = Map.split (r-v+1, -1) simapR\r\n\r\n fixIfInside | (v,i) `Map.member` simapLR = 1\r\n | otherwise = 0\r\n"}, {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.Int\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int32\n\npmGen :: Int32 -> Int32\npmGen x = fromIntegral $! mod ((16807::Int64) * fromIntegral x) 2147483647\n\nrandoms :: Int32 -> [Int32]\nrandoms = iterate pmGen\n\ntype Key = Int32\ntype RandomValue = Int32\ndata TreapSet = Node {-# UNPACK #-} !Key {-# UNPACK #-} !RandomValue {-# UNPACK #-} !Int32 TreapSet TreapSet | Nil\n\nkey :: TreapSet -> Key\nkey (Node x _ _ _ _) = x\n\nsize :: TreapSet -> Int32\nsize Nil = 0\nsize (Node _ _ sz _ _) = sz\n\n_relax :: Key -> RandomValue -> TreapSet -> TreapSet -> TreapSet\n_relax !x !y l@(Node _ _ ls _ _) r@(Node _ _ rs _ _) = Node x y (succ $! ls + rs) l r\n_relax !x !y l@(Node _ _ sz _ _) Nil = Node x y (succ sz) l Nil\n_relax !x !y Nil r@(Node _ _ sz _ _) = Node x y (succ sz) Nil r\n_relax !x !y Nil Nil = Node x y 1 Nil Nil\n\nsplit :: Key -> TreapSet -> (TreapSet, TreapSet)\nsplit _ Nil = (Nil, Nil)\n\nsplit !key (Node x y _ left right)\n | key < x = let (l', r') = split key left in (l', _relax x y r' right)\n | otherwise = let (l', r') = split key right in (_relax x y left l', r')\n\ntsInsert :: Key -> RandomValue -> TreapSet -> TreapSet\ntsInsert !x !y Nil = Node x y 1 Nil Nil\ntsInsert !x !y t@(Node x' y' sz' left' right')\n | y' >= y = if x < x' then Node x' y' (succ sz') (tsInsert x y left') right'\n else Node x' y' (succ sz') left' (tsInsert x y right')\n | otherwise = let (l'', r'') = split x t in _relax x y l'' r''\n\nmerge :: TreapSet -> TreapSet -> TreapSet\nmerge Nil r = r\nmerge l Nil = l\nmerge l@(Node x' y' sz' l' r') r@(Node x'' y'' sz'' l'' r'')\n | y' > y'' = _relax x' y' l' (merge r' r)\n | otherwise = _relax x'' y'' (merge l l'') r''\n\ntsRemove :: Key -> TreapSet -> TreapSet\ntsRemove _ Nil = Nil\ntsRemove !x (Node x' y' sz' l' r')\n | x < x' = _relax x' y' (tsRemove x l') r'\n | x > x' = _relax x' y' l' (tsRemove x r')\n | otherwise = merge l' r'\n\ntsRemoveExistingKey :: Key -> TreapSet -> TreapSet\ntsRemoveExistingKey !x (Node x' y' sz' l' r')\n | x < x' = Node x' y' (pred sz') (tsRemoveExistingKey x l') r'\n | x > x' = Node x' y' (pred sz') l' (tsRemoveExistingKey x r')\n | otherwise = merge l' r'\n\ntsCount :: Key -> TreapSet -> Int32\ntsCount !x = count' 0\n where\n count' !c Nil = c\n count' !c (Node x' _ _ l' r')\n | x' < x = count' (succ $! c + size l') r'\n | otherwise = count' c l'\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\ntest' :: Int -> Int32 -> Int32 -> [Int32] -> [Int32] -> Int64\ntest' n l r a r1 = f Nil 0 a r1\n where\n f t !acc [] _ = acc\n f t !acc (x:xs) (y:ys) = f (tsInsert x y t) (acc + (fromIntegral $ tsCount (r - x + 1) t) - (fromIntegral $ tsCount (l - x) t)) xs ys\n \n\nnl = char7 '\\n'\n\ntest :: Builder -> Int -> [Int] -> [Int32] -> Builder\ntest buf 0 _ _ = buf\ntest buf nt (n:l:r:a) r0 = test (buf <> int64Dec (test' n (fromIntegral l) (fromIntegral r) (map fromIntegral b) r1) <> nl) (pred nt) c r2\n where\n (b, c) = splitAt n a\n (r1, r2) = splitAt n r0\n\nsolve :: [Int32] -> [Int] -> Builder\nsolve r (nt:xs) = test mempty nt xs r\n\nmain :: IO ()\nmain = do\n seed <- getSeed\n c <- C.getContents\n hPutBuilder stdout $ solve (randoms seed) $ map ri $ C.words c\n"}, {"source_code": "import Control.Arrow ((>>>))\r\nimport Data.List (sort)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs =\r\n let (hs, ts) = splitAt k xs\r\n in hs : chunksOf k ts\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines >>>\r\n drop 1 >>>\r\n map (words >>> map read) >>> chunksOf 2 >>> map (solve >>> show) >>> unlines\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [[Int]] -> I64\r\nsolve [[n, l, r], xs] =\r\n let xs' = sort xs\r\n in (`div` 2) $\r\n compute xs' r - compute xs' (l - 1) -\r\n (toInteger . length . filter (\\x -> l <= 2 * x && 2 * x <= r) $ xs)\r\n\r\ncompute :: [Int] -> Int -> I64\r\ncompute xs lim =\r\n sum . map (toInteger . snd . head) . tail $\r\n scanl\r\n (\\vs x -> dropWhile ((> lim - x) . fst) vs)\r\n (reverse $ zip ((-10 ^ 9) : xs) [0 ..])\r\n xs\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (replicateM)\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.List\r\nimport Data.Maybe (fromMaybe)\r\n\r\ntype Scanner = State [String]\r\n\r\nrunScanner :: Scanner a -> String -> a\r\nrunScanner = runScannerWith words\r\n\r\nrunScannerWith :: (String -> [String]) -> Scanner a -> String -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\nstr :: Scanner String\r\nstr =\r\n get >>= \\case\r\n s:ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = read <$> str\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n runScanner (numberOf singleCase) >>> map (solve >>> show) >>> unlines\r\n where\r\n singleCase = do\r\n nlr <- times 3 int\r\n xs <- times (head nlr) int\r\n return [nlr, xs]\r\n\r\ntype I64 = Integer\r\n\r\nsolve :: [[Int]] -> I64\r\nsolve [[n, l, r], xs] =\r\n let xs' = sort xs\r\n in (`div` 2) $\r\n compute xs' r - compute xs' (l - 1) -\r\n (toInteger . length . filter (\\x -> l <= 2 * x && 2 * x <= r) $ xs)\r\n\r\ncompute :: [Int] -> Int -> I64\r\ncompute xs lim =\r\n sum . map (toInteger . snd . head) . tail $\r\n scanl\r\n (\\vs x -> dropWhile ((> lim - x) . fst) vs)\r\n (reverse $ zip ((-10 ^ 9) : xs) [0 ..])\r\n xs\r\n"}], "negative_code": [], "src_uid": "2f12b2bb23497119bb70ca0839991d68"} {"source_code": "main = interact (ans)\nans theInput = answer where\n theLines = lines theInput\n n = read (head theLines) ::Int\n a = zip (map (read ::String->Int) (take n $ words $ theLines !! 1)) [1..]\n triple = [[u,v,w]|(x,u)<-a,(y,v)<-a,u/=v,(z,w)<-a,w/=u,w/=v,x==y+z]\n answer = if null triple then \"-1\" else unwords $ map show (head triple)\n", "positive_code": [{"source_code": "import Data.List\nmain = interact $pars.map read.words\n\npars m = if res == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ check\n\t where n = head m\n\t v = tail m\n\t v2 = sort v\n\t res= ch n v (v2)\n\t ans= getNums (res) v\n\t check \n\t | ans!!1==ans!!2 = if (getNums2 (res!!1) v)==ans!!2 then [-1]\n\t else [ans!!0,getNums2 (res!!1) v,ans!!2]\n\t | otherwise = ans\n\t \t \n\nch::Int->[Int]->[Int]->[Int]\nch n v [] = [-1]\nch n v v2 \n | otherwise = if null t then ch n v (init v2)\n else [mv,fst ( head t),snd (head t)]\n where mv=last v2\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++(getNums (tail ans) m)\n\ngetNums2 ans m = if res2 == length dr then res1\n\t else res2+res1+1\n where res1=length(takeWhile (/=ans) m)+1\n dr = drop res1 m\n res2=length(takeWhile (/=ans) dr)\n"}, {"source_code": "\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nsolve :: [Int] -> [(Int, Int, Int)]\nsolve xs = [(i, j, k) | i <- [1..n], j <- [1..n], k <- [1..n],\n i /= j, i /= k, j /= k,\n xs !! (i-1) == xs !! (j-1) + xs !! (k-1)]\n where\n n = length xs\n\nprintAns :: [(Int, Int, Int)] -> IO ()\nprintAns [] = print (-1)\nprintAns ((i, j, k):xs) = putStrLn $ concat [show i, \" \", show j, \" \", show k]\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= printAns . solve\n"}, {"source_code": "prettyPrint (a,b,c) = show (a+1) ++ \" \" ++ show (b+1) ++ \" \" ++ show (c+1)\n\nisCorrect list (a,b,c) = a /= b && b /= c && c /= a && (list !! a) == (list !! b) + (list !! c)\n\nfindAllSolutions worms = filter (isCorrect worms) [(a,b,c) | a <- [0..n-1], b <- [0..n-1], c <- [0..n-1]]\n where n = length worms\n\nsolve worms = if (length sol == 0) then \"-1\" else prettyPrint (head sol)\n where sol = findAllSolutions worms\n\nmain = do\n dummy <- getLine\n inputLine <- getLine\n let tmp = words inputLine\n let worms = map read tmp :: [Int]\n putStrLn (solve worms)\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- take n . map read . words <$> getLine :: IO [Int]\n let answer = do\n let forms = zip ([1 .. ] :: [Int]) xs\n (i, ai) <- forms\n (j, aj) <- forms\n (k, ak) <- forms\n guard $ i /= j\n guard $ j /= k\n guard $ k /= i\n guard $ ai == aj + ak\n return (i, j, k)\n case answer of\n (i, j, k) : _ -> printf \"%d %d %d\\n\" i j k\n _ -> print (-1)\n"}, {"source_code": "main = do getLine\n a <- fmap (map read . words) getLine\n let n = length a\n lst = [(i,j,k) | i <- [0..n-1], j <- [0..n-1], k <-[0..n-1], \n i /= j, j /= k, i /= k, (a!!i) == (a!!j) + (a!!k)]\n (i,j,k) = head lst\n if null lst\n then putStrLn \"-1\"\n else putStrLn . unwords . map show . map (+1) $ [i,j,k]\n"}, {"source_code": "main = do\n\tn <- fmap read getLine\n\ta <- fmap (map read . words) getLine\n\tputStr $ unwords $ map show $ last $ [-1]:[[i, j, k] | i <- [1 .. n], j <- [1 .. n], k <- [1 .. n], i /= j, i /= k, j /= k, a!!(i-1) == a!!(j-1) + a!!(k-1)]\n"}], "negative_code": [{"source_code": "\nmain = interact $pars.map read.words\n\npars m = if ch n v == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show (ch n v)\n\t where n = head m\n\t v = tail m\n\nch::Int->[Int]->[Int]\nch n v \n | n<3 = [-1]\n | otherwise = if null t then [-1]\n else [mv,fst ( head t),snd (head t)]\n where mv=maximum v\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n"}, {"source_code": "\nmain = interact $pars.map read.words\n\npars m = if ch n v == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ getNums (ch n v) v\n\t where n = head m\n\t v = tail m\n\nch::Int->[Int]->[Int]\nch n v \n | n<3 = [-1]\n | otherwise = if null t then [-1]\n else [mv,fst ( head t),snd (head t)]\n where mv=maximum v\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++getNums (tail ans) m"}, {"source_code": "import Data.List\nmain = interact $pars.map read.words\n\npars m = if ch n v (v2) == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ getNums (ch n v (v2)) v\n\t where n = head m\n\t v = tail m\n\t v2 = sort v\n\nch::Int->[Int]->[Int]->[Int]\nch n v [] = [-1]\nch n v v2 \n | otherwise = if null t then ch n v (init v2)\n else [mv,fst ( head t),snd (head t)]\n where mv=last v2\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++getNums (tail ans) m"}, {"source_code": "\nmain = interact $pars.map read.words\n\npars m = if ch n v == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ getNums (ch n v) v\n\t where n = head m\n\t v = tail m\n\nch::Int->[Int]->[Int]\nch n v \n | n<2 = [-1]\n | otherwise = if null t then [-1]\n else [mv,fst ( head t),snd (head t)]\n where mv=maximum v\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++getNums (tail ans) m"}, {"source_code": "import Data.List\nmain = interact $pars.map read.words\n\npars m = if res == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ check\n\t where n = head m\n\t v = tail m\n\t v2 = sort v\n\t res= ch n v (v2)\n\t ans= getNums (res) v\n\t check \n\t | ans!!1==ans!!2 = if (getNums2 (res!!1) v)==0 then [-1]\n\t else [ans!!0,getNums2 (res!!1) v,ans!!2]\n\t | otherwise = ans\n\t \t \n\nch::Int->[Int]->[Int]->[Int]\nch n v [] = [-1]\nch n v v2 \n | otherwise = if null t then ch n v (init v2)\n else [mv,fst ( head t),snd (head t)]\n where mv=last v2\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++(getNums (tail ans) m)\n\ngetNums2 ans m = length(takeWhile (/=ans) (tail(drop res1 m)))+res1\n where res1=length(takeWhile (/=ans) m)+1\n"}, {"source_code": "import Data.List\nmain = interact $pars.map read.words\n\npars m = if ch n v (sort v) == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ getNums (ch n v (sort v)) v\n\t where n = head m\n\t v = tail m\n\nch::Int->[Int]->[Int]->[Int]\nch n v [] = [-1]\nch n v v2 \n | n<2 = [-1]\n | otherwise = if null t then ch n v (init v2)\n else [mv,fst ( head t),snd (head t)]\n where mv=last v2\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++getNums (tail ans) m"}, {"source_code": "import Data.List\nmain = interact $pars.map read.words\n\npars m = if ch n v (v2) == [-1] then \"-1\"\n\t else if check then init $concat$ map (++\" \") $map show $ ans\n\t \t else [head \"\"]\n\t where n = head m\n\t v = tail m\n\t v2 = sort v\n\t ans= getNums (ch n v (v2)) v\n\t check = if v!!(ans!!0-1) == v!!(ans!!1-1)+v!!(ans!!2-1) then True\n\t \t else False\n\nch::Int->[Int]->[Int]->[Int]\nch n v [] = [-1]\nch n v v2 \n | otherwise = if null t then ch n v (init v2)\n else [mv,fst ( head t),snd (head t)]\n where mv=last v2\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++(getNums (tail ans) m)"}, {"source_code": "import Data.List\nmain = interact $pars.map read.words\n\npars m = if res == [-1] then \"-1\"\n\t else init $concat$ map (++\" \") $map show $ check\n\t where n = head m\n\t v = tail m\n\t v2 = sort v\n\t res= ch n v (v2)\n\t ans= getNums (res) v\n\t check = if ans!!1==ans!!2 then [ans!!0,getNums2 (res!!1) v,ans!!2]\n\t \t else ans\n\nch::Int->[Int]->[Int]->[Int]\nch n v [] = [-1]\nch n v v2 \n | otherwise = if null t then ch n v (init v2)\n else [mv,fst ( head t),snd (head t)]\n where mv=last v2\n t=take 1 [ (x,y) | x<-v , y<-v, x+y==mv]\n\ngetNums [] _= []\ngetNums ans m = [length(takeWhile (/=(head ans)) m)+1]++(getNums (tail ans) m)\n\ngetNums2 ans m = length(takeWhile (/=(ans)) (tail(dropWhile (/=ans) m)))+1\n"}], "src_uid": "94a38067fc8dd8619fa6e5873ca60220"} {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\nimport qualified Data.Set as Set\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\n-- I miss lenses :(\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n unused = Set.toList $ Set.fromList [1..length xs] Set.\\\\ Set.fromList (filter (/= 0) xs)\n indices = map fst . filter (\\(_, x) -> x == 0) $ zip [1 ..] xs\n getFirstDiff [a, b] (x:y:xs) | b == y = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\n-- I miss lenses :(\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n arr = accumArray (||) False (1, length xs) [(x, True) | x <- xs, x /= 0]\n unused = map fst . filter (not . snd) $ assocs arr\n indices = map fst . filter (\\(_, x) -> x == 0) $ zip [1 ..] xs\n getFirstDiff (a:b:[]) (x:y:xs) | b == y = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n"}, {"source_code": "import Data.Map (Map)\nimport qualified Data.Map.Strict as Map\n\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as Set\n\n\n-- g: not knowing who to give to\n-- a: not recving\nsolve :: Int -> [Int] -> Map Int Int\nsolve n fs =\n let (g, a, fs') = foldl (\\(g, a, fs') (i, f) -> if f == 0 then (i : g, a, fs') else (g, Set.delete f a, Map.insert i f fs')) (mempty, Set.fromAscList [1..n], mempty) (zip [1..n] fs)\n in head $ dfs fs' g a\n\ndfs :: Map Int Int -> [Int] -> IntSet -> [Map Int Int]\ndfs f [] as = [f] \ndfs f (g:gs) as = [Map.insert g a f' | a <- Set.elems as, a /= g, f' <- dfs f gs (Set.delete a as)]\n \nmain = do\n n <- fmap read getLine\n fs <- fmap (fmap read . words) getLine\n let ans = solve n fs\n putStrLn $ foldr (\\i s -> show i ++ \" \" ++ s) \"\" ans\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\nimport qualified Data.Set as Set\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\n-- I miss lenses :(\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n s = Set.fromList (filter (/= 0) xs)\n unused = filter (flip Set.notMember s) [1..length xs]\n indices = map fst . filter (\\(_, x) -> x == 0) $ zip [1 ..] xs\n getFirstDiff [a, b] (x:y:xs) | b == y = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\n-- I miss lenses :(\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n arr = listArray (1, length xs) (replicate (length xs) False) // [(x, True) | x <- xs, x /= 0]\n unused = map fst . filter (not . snd) $ assocs arr\n indices = map fst . filter (\\(_, x) -> x == 0) $ zip [1 ..] xs\n getFirstDiff [a, b] (x:y:xs) | b == y = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n"}, {"source_code": " {-# LANGUAGE TupleSections #-}\n \n import Control.Monad\n import Control.Monad.State\n import Data.Array\n import Data.List\n \n extend :: [a] -> [[a]]\n extend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n \n -- I miss lenses :(\n intercal :: [Int] -> [Int] -> [Int]\n intercal [] _ = []\n intercal (0:xs) (z:zs) = z : intercal xs zs\n intercal (x:xs) zs = x : intercal xs zs\n \n solve :: [Int] -> [Int]\n solve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n arr = accumArray (||) False (1, length xs) [(x, True) | x <- xs, x /= 0]\n unused = map fst . filter (not . snd) $ assocs arr\n indices = map fst . filter (\\(_, x) -> x == 0) $ zip [1 ..] xs\n getFirstDiff (a:b:[]) (x:y:xs) | b == y = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n \n main :: IO ()\n main =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\n\nsolve :: [Int] -> [Int]\nsolve xs = flip evalState init $ traverse (\\a -> state $ if a == 0 then getFirstDiff a else (a, )) xs\n where getFirstDiff :: Int -> [Int] -> (Int, [Int])\n getFirstDiff a (x:xs) | x /= a = (x, xs)\n getFirstDiff a (x:y:xs) = (y, x:xs)\n arr :: Array Int Bool\n arr = accumArray (||) False (1, length xs) [(x, True) | x <- xs , x /= 0]\n init :: [Int]\n init = reverse . map fst . filter (not . snd) $ assocs arr\n\nmain :: IO ()\nmain = unwords . map show . solve . map read . words <$> (getLine *> getLine) >>= putStrLn\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n arr = accumArray (||) False (1, length xs) [(x, True) | x <- xs, x /= 0]\n unused = reverse . map fst . filter (not . snd) $ assocs arr\n indices = map fst . filter (\\(_, x) -> x /= 0) $ zip [1 ..] xs\n getFirstDiff [a, b] (x:y:xs) | b == x = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n arr = accumArray (||) False (1, length xs) [(x, True) | x <- xs, x /= 0]\n unused = reverse . map fst . filter (not . snd) $ assocs arr\n indices = map fst $ filter (\\(_, x) -> x /= 0) (zip [1 ..] xs)\n getFirstDiff [a, b] (x:y:xs) | a == x || b == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport Data.List\n\nextend :: [a] -> [[a]]\nextend = unfoldr f\n where f [] = Nothing\n f xs@(x:xs') = Just (xs, xs')\n\nintercal :: [Int] -> [Int] -> [Int]\nintercal [] _ = []\nintercal (0:xs) (z:zs) = z : intercal xs zs\nintercal (x:xs) zs = x : intercal xs zs\n\nsolve :: [Int] -> [Int]\nsolve xs =\n intercal xs $\n flip evalState unused $\n traverse (state . getFirstDiff) (extend indices)\n where\n arr = accumArray (||) False (1, length xs) [(x, True) | x <- xs, x /= 0]\n unused = reverse . map fst . filter (not . snd) $ assocs arr\n indices = map fst . filter (\\(_, x) -> x /= 0) $ zip [1 ..] xs\n getFirstDiff (a:b:[]) (x:y:xs) | b == y = (y, x:xs)\n getFirstDiff (a:as) (x:y:xs) | a == x = (y, x:xs)\n getFirstDiff _ (x:xs) = (x, xs)\n\nmain :: IO ()\nmain =\n unwords . map show . solve . map read . words <$> (getLine *> getLine) >>=\n putStrLn\n"}], "src_uid": "bef323e7c8651cc78c49db38e49ba53d"} {"source_code": "\nprocess :: String -> String\nprocess [x] = [x]\nprocess (x:y:[]) = if y ==x then [x, head [ k | k <- ['a'..'z'], k /= y, k /= x]] else [x,y]\nprocess (x:y:z:xs) = if x == y then x:y': process (z:xs) else x:process (y:z:xs)\n where\n y' = head [ k | k <- ['a'..'z'], k /= x, k /= y, k /= z]\n\n\nmain = do\n aa <- getLine\n putStrLn $ process aa\n", "positive_code": [{"source_code": "import Data.Char\n\nnext :: Char -> Char\nnext c = chr $ (ord 'a') + (mod ((ord c) - (ord 'a') + 1) ((ord 'z') - (ord 'a') + 1))\n\nfoo :: String -> String\nfoo (x1:x2:xs) = \n\tif x1==x2 then\n\t\tlet\n\t\t\tx2n = next x2\n\t\tin if (null xs) then\n\t\t\tx1 : foo (x2n:xs)\n\t\telse\n\t\t\tif x2n == head xs then\n\t\t\t\tx1 : foo (next x2n : xs)\n\t\t\telse\n\t\t\t\tx1 : foo (x2n:xs)\n\n\telse\n\t\tx1 : foo (x2:xs)\nfoo x = x\n\nmain :: IO ()\nmain = interact foo\n"}, {"source_code": "import Control.Arrow\n--import Test.QuickCheck\nimport Data.List\n\nwithTokens :: [(Char, Int)] -> String\nwithTokens = concat . map withTokens'\n where\n withTokens' :: (Char, Int) -> String\n withTokens' (char, 1) = [char]\n withTokens' (char, count)\n | even count =\n concat $ replicate (count `div` 2) ['T', char]\n withTokens' (char, count) =\n char:withTokens' (char, count - 1)\n\nalphabet :: String\nalphabet = ['a'..'z']\n\nreplaceTokens :: String -> String\nreplaceTokens (x:'T':y:rst) =\n x:head (alphabet \\\\ [x, y]):replaceTokens (y:rst)\nreplaceTokens ('T':y:rst) =\n head (alphabet \\\\ [y]):replaceTokens (y:rst)\nreplaceTokens (x:rst) = x:replaceTokens rst\nreplaceTokens [] = []\n\ncomputeSimpleString :: String -> String\ncomputeSimpleString str' =\n let lengthGroups = map (head &&& length) $ group str'\n tokenizedStr = withTokens lengthGroups\n in replaceTokens tokenizedStr\n\n{-\nrunChecks :: IO ()\nrunChecks =\n let genInput = listOf $ elements ['a'..'e']\n propReplacecounts = forAll genInput $ \\str ->\n let strCmp = zip str (computeSimpleString str)\n numDifferences = length $ filter (\\(x, y) -> x /= y) strCmp\n groupLengths = map length $ group str\n numReplacements x = x `div` 2 \n in numDifferences == sum (map numReplacements groupLengths)\n\n propNoAdjacencies = forAll genInput $ \\str ->\n let simpleStr = computeSimpleString str\n in 0 == length (filter (\\(x, y) -> x == y) $ zip simpleStr (drop 1 simpleStr))\n in do\n quickCheck propReplacecounts\n quickCheck propNoAdjacencies\n-}\n\nmain :: IO ()\nmain = interact $ \\str ->\n let str' = filter (`elem` alphabet) str\n in computeSimpleString str'\n"}], "negative_code": [{"source_code": "import Control.Arrow\n--import Test.QuickCheck\nimport Data.List\n\nwithTokens :: [(Char, Int)] -> String\nwithTokens = concat . map withTokens'\n where\n withTokens' :: (Char, Int) -> String\n withTokens' (char, 1) = [char]\n withTokens' (char, count)\n | even count =\n concat $ replicate (count `div` 2) ['T', char]\n withTokens' (char, count) =\n char:withTokens' (char, count - 1)\n\nalphabet :: String\nalphabet = ['a'..'z']\n\nreplaceTokens :: String -> String\nreplaceTokens (x:'T':y:rst) =\n x:head (alphabet \\\\ [x, y]):y:replaceTokens rst\nreplaceTokens ('T':y:rst) =\n head (alphabet \\\\ [y]):y:replaceTokens rst\nreplaceTokens (x:rst) = x:replaceTokens rst\nreplaceTokens [] = []\n\ncomputeSimpleString :: String -> String\ncomputeSimpleString str' =\n let lengthGroups = map (head &&& length) $ group str'\n tokenizedStr = withTokens lengthGroups\n in replaceTokens tokenizedStr\n\n{-\nrunChecks :: IO ()\nrunChecks =\n let genInput = listOf $ elements ['a'..'b']\n propReplacecounts = forAll genInput $ \\str ->\n let strCmp = zip str (computeSimpleString str)\n numDifferences = length $ filter (\\(x, y) -> x /= y) strCmp\n groupLengths = map length $ group str\n numReplacements x = x `div` 2 \n in numDifferences == sum (map numReplacements groupLengths)\n in quickCheck propReplacecounts\n-}\n\nmain :: IO ()\nmain = interact $ \\str ->\n let str' = filter (`elem` alphabet) str\n in computeSimpleString str'\n"}], "src_uid": "1f38c88f89786f118c65215d7df7bc9c"} {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Int\n putStrLn $ if n <= 30 then \n \"NO\"\n else if n `elem` [36, 40, 44] then\n \"YES\\n6 10 15 \" ++ show (n - 31)\n else\n \"YES\\n6 10 14 \" ++ show (n - 30)\n \n \n iter :: Int -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Int)", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n if n > 30\n then\n if (n - 30) `notElem` [6, 10, 14]\n then putStrLn \"YES\" >> putStrLn (\"6 10 14 \" ++ show (n - 30))\n else putStrLn \"YES\" >> putStrLn (\"6 10 15 \" ++ show (n - 31))\n else putStrLn \"NO\"\n"}, {"source_code": "import Data.Char\nimport Control.Monad\nimport Data.List\n\n\n--6 10 14 15\n\nanswer x = if (x==36) then [6, 10, 15, 5]\n else if(x==40) then [6, 10, 15, 9]\n else if(x==44) then [6, 10, 15, 13]\n else [6, 10, 14, x-30]\n\nget_ans h = if null h then \"\"\n else (show (head h)) ++ \" \" ++ (get_ans (tail h))\n\nresult x = if (x <= 30) then \"NO\"\n else \"YES\" ++ \"\\n\" ++ ((get_ans . answer) x)\n\nmain = do \n tests <- getLine\n l <- getContents\n let l2 = words l\n-- print l2\n let l3 = [ read w :: Int | w <- l2 ]\n let ans = [ result x | x <- l3]\n let ans2 = intercalate \"\\n\" ans\n putStr ans2\n"}, {"source_code": "import Data.Char\nimport Control.Monad\nimport Data.List\n\n\n--6 10 14 15\n\nanswer 36 = [6, 10, 15, 5]\nanswer 40 = [6, 10, 15, 9]\nanswer 44 = [6, 10, 15, 13]\nanswer x = [6, 10, 14, x-30]\n\nget_ans h = if null h then \"\"\n else (show (head h)) ++ \" \" ++ (get_ans (tail h))\n\nresult x = if (x <= 30) then \"NO\"\n else \"YES\" ++ \"\\n\" ++ ((get_ans . answer) x)\n\nmain = do \n tests <- getLine\n l <- getContents\n let l2 = [ read w :: Int | w <- words l ]\n putStr(intercalate \"\\n\" [result x | x <- l2])\n \n"}, {"source_code": "import Control.Monad\n\ngetList :: (Read t) => IO [t]\ngetList = getLine >>= return . (map read) . words\n\ngetOne :: (Read t) => IO t\ngetOne = getLine >>= return . read\n\nputList :: (Show a) => [a] -> IO ()\nputList = sequence_ . (map (\\el -> putStr (show el) >> putChar ' '))\n\nmain :: IO ()\nmain = do\n t <- getOne\n -- let t = 1\n replicateM_ t solve\n\n\nsolve :: IO ()\nsolve = do \n n <- getOne :: IO Int\n let ans = countAns n\n if null ans then\n putStrLn \"NO\"\n else do\n putStrLn \"YES\"\n putList ans\n putChar '\\n'\n\n\ncountAns :: (Ord a, Num a) => a -> [a]\ncountAns n\n | sum f3 >= n = []\n | n - sum f3 `elem` f3 = (n - sum f4) : f4\n | otherwise = (n - sum f3) : f3\n where \n f3 = [6, 10, 14]\n f4 = [6, 10, 15]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tputStrLn $ if x<31 then \"NO\" \n\t\t\t else if not(elem x [36,40,44]) then \"YES\\n\"++ (intercalate \" \" (map show [14,10,6,x-30])) \n\t\t\t\t\t\t\t else \"YES\\n\"++ (intercalate \" \" (map show [15,10,6,x-31]))\n\t\t\t\t\t\t\t \t\t\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n if n > 30\n then\n if (n - 30) `notElem` [6, 10, 14]\n then putStrLn \"YES\" >> putStrLn (\"6 10 14 \" ++ show (n - 30))\n else putStrLn \"YES\" >> putStrLn (\"6 10 15 \" ++ show (n - 30))\n else putStrLn \"NO\"\n"}, {"source_code": "import Data.Char\nimport Control.Monad\nimport Data.List\n\n\n--6 10 14 15\n\nanswer x = if (x==36) then [6, 10, 15, 5]\n else if(x==40) then [6, 10, 15, 9]\n else if(x==44) then [6, 10, 15, 13]\n else [6, 10, 14, x-30]\n\nget_ans h = if null h then \"\"\n else (show (head h)) ++ \" \" ++ (get_ans (tail h))\n\nresult x = if (x <= 30) then \"NO\"\n else \"YES\" ++ \"\\n\" ++ ((get_ans . answer) x)\n\nmain = do \n tests <- getLine\n l <- getContents\n let l2 = words l\n print l2\n let l3 = [ read w :: Int | w <- l2 ]\n let ans = [ result x | x <- l3]\n let ans2 = intercalate \"\\n\" ans\n putStr ans2\n"}, {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Int\n putStrLn $ if n <= 30 then \n \"NO\"\n else if n `elem` [36, 40, 44] then\n \"YES\\n6 10 15\" ++ show (n - 31)\n else\n \"YES\\n6 10 14\" ++ show (n - 30)\n \n \n iter :: Int -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Int)"}, {"source_code": "module Main where\n\n solve :: IO ()\n solve = do\n s <- getLine\n let n = read s :: Int\n putStrLn $ if n <= 30 then \n \"NO\"\n else if n `elem` [36, 40, 44] then\n \"6 10 15\" ++ show (n - 31)\n else\n \"6 10 14\" ++ show (n - 30)\n \n \n iter :: Int -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Int)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nonecase = do\n\t\tx<- read <$> getLine ::IO Int\n\t\tputStrLn $ if x<31 then \"NO\" \n\t\t\t else if not(elem x [36,40,46]) then \"YES\\n\"++ (intercalate \" \" (map show [14,10,6,x-30])) \n\t\t\t\t\t\t\t else \"YES\\n\"++ (intercalate \" \" (map show [15,10,6,x-31]))\n\t\t\t\t\t\t\t \t\t\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "src_uid": "8a6c3436f73286ca54f51fb90017a299"} {"source_code": "import List\nimport Data.IntSet as Set\nmain = interact solve\nsolve input = output where\n n = read input :: Int\n nodes :: Int -> IntSet -> [Int] -> [[Int]]\n nodes 1 s _ = [[x]|x<-toList s]\n nodes x s xs = [y:ys|y<-toList s, ys<-nodes (x-1) (del0 s y xs) (y:xs)] where\n del0 s z zs = del (Set.delete z s) $\n concat [[u+v-z,z+u-v,z+v-u]|u<-zs, v<-zs, u [Int] -> IntSet\n del ys [] = ys\n del ys (z:zs) = Set.delete z $ del ys zs\n s0 = toList s\n table = head $ nodes n (fromList [1..1000]) []\n output = unlines [unwords [show $ edge i j|j<-[0..n-1]]|i<-[0..n-1]]\n edge x y = if x==y then 0 else table!!x + table!!y\n\n", "positive_code": [{"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n nodes = [1,2,3,5,8,13,21,30,39,53,74,95,128,152,182,212,258,316,374,413]\n output = unlines [unwords [show $ edge i j|j<-[0..n-1]]|i<-[0..n-1]]\n edge x y = if x==y then 0 else nodes!!x + nodes!!y"}], "negative_code": [], "src_uid": "4217f062fee8d759adbfb3440c275157"} {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess _ [] [] _ _ = putStrLn \"\"\nprocess i (a:as) (b:bs) c d | elem a c || elem b d = process (i+1) as bs c d\n | otherwise = do\n putStr (show i ++\" \")\n process (i+1) as bs (a:c) (b:d)\n\n\nmain::IO ()\nmain=do\n n<- read <$> getLine::IO Int\n [a1,a2]<- transpose <$> map(map read) <$> map words <$> lines <$> getContents :: IO [[Int]]\n process 1 a1 a2 [] []\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Control.Monad.State\nimport Data.Set\n-- Meat\n\nsolve :: [[Int]] -> [Int]\nsolve as = [ snd x | x <- bools `zip` [1..], fst x]\n where bools = evalState (mapM feed as) noHistory\n\ndata RoadHistory = RoadHistory (Set Int) (Set Int) deriving (Show)\n\nnoHistory :: RoadHistory\nnoHistory = RoadHistory Data.Set.empty Data.Set.empty\n\nfeed :: [Int] -> State RoadHistory Bool\nfeed (h:v:_ )= state $ transform h v\nfeed _ = error \"You suck\"\n\ntransform :: Int -> Int -> RoadHistory -> (Bool, RoadHistory)\ntransform h v (RoadHistory horH verH) = (shouldWork, RoadHistory newHorH newVerH)\n where shouldWork = h `notMember` horH && v `notMember` verH\n newHorH = if shouldWork then insert h horH else horH\n newVerH = if shouldWork then insert v verH else verH\n\n-- Shit\nmain :: IO ()\nmain = do\n _:as <- readShit\n printShit $ solve as\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents"}, {"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain :: IO()\nmain = putStrLn . intercalate \" \" . map show . solve 1 Set.empty Set.empty . map read . tail . words =<< getContents\n\nsolve :: Int -> Set.Set Int -> Set.Set Int -> [Int] -> [Int]\nsolve _ _ _ [] = []\nsolve i h v (x:y:s) | (Set.member x h) || (Set.member y v) = solve (i + 1) h v s\n | otherwise = i : solve (i + 1) (Set.insert x h) (Set.insert y v) s\n"}, {"source_code": "import Control.Monad\nimport Data.Set (empty,insert,member)\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- forM [1..(n*n)] $ \\_ -> do\n [x,y] <- fmap ((map read) . words) getLine :: IO [Int]\n return (x,y)\n mapM_ (\\x -> putStr ((show x)++\" \")) (solve 1 a empty empty)\n\n\nsolve _ [] _ _ = []\nsolve i ((x,y):xs) mh mv\n |or [member x mh,member y mv] = solve (i+1) xs mh mv\n |otherwise = i:solve (i+1) xs (insert x mh) (insert y mv)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n ijs <- replicateM (n^2) getInts\n\n let\n rs = snd $ mapAccumL f ([], []) $ zip ijs [1..]\n where\n f (is, js) ([i, j], k)\n | i `elem` is || j `elem` js = ((is, js), 0)\n | otherwise = ((i:is, j:js), k)\n\n putStrLn $ unwords $ map show $ filter (/= 0) rs\n"}, {"source_code": "import Data.Set hiding (map)\n\nmain = interact $ solver\n\ninto_pairs [] = []\ninto_pairs (h:v:t) = (h, v) : into_pairs t\n\nsolver str = unwords $ map show res where\n ws = words str\n (_: list) = ws\n order = into_pairs $ map (read :: String->Int) list\n res = solve order empty empty 1\n\nsolve [] _ _ _ = []\nsolve ((h, v) : t) removedHorizontal removedVertical i =\n if member h removedHorizontal || member v removedVertical\n then solve t removedHorizontal removedVertical (i + 1)\n else i : solve t (insert h removedHorizontal) (insert v removedVertical) (i + 1)"}, {"source_code": "import Control.Applicative\nf xl yl [] sch n m= [] \nf xl yl (schx:schxs) (schy:schys) n m| n == 0 = []\n | (elem schx xl) || (elem schy yl) = f xl yl schxs schys n (m+1)\n | otherwise = (m+1):(f (schx:xl) (schy:yl) schxs schys (n-1) (m+1))\ntoTup a = ((w !! 0),(w !! 1))\n where w = [read n::Int|n <- (words a)]\nmain = do\n n <- (read::String ->Int) <$> getLine\n (xl,yl) <- unzip.(map toTup).lines <$> getContents\n putStrLn $ unwords $ map show $ f [] [] xl yl n 0\n \n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = C.getLine>>= (\\(n) ->solve=<map rIn.C.words <$>C.getLine) )\nsolve xs= putStrLn $ unwords $ map show $ reverse $ foldl (\\ bs (c,(a,_)) ->if a then c:bs else bs)[] $ zip [0..] $ scanl (slv1) (False,[Set.empty,Set.empty]) xs\nslv1 (_,[s1,s2]) [x,y]= if Set.member x s1 || Set.member y s2 then (False, [s1,s2]) else (True,[Set.insert x s1,Set.insert y s2])\n"}, {"source_code": "-- Codeforces 583A\n\nimport Control.Monad\nimport qualified Data.Set as Set\nimport Data.List (intercalate)\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getContents >>= putStrLn . intercalate \" \" . map show . solve 1 (Set.empty, Set.empty) . map read . words\n\nsolve :: Int -> (Set.Set Int, Set.Set Int) -> [Int] -> [Int]\nsolve _ _ [] = []\nsolve d (h, v) (i:j:xs)\n | (Set.member i h) || (Set.member j v) = solve (d+1) (h, v) xs\n | otherwise = d : solve (d+1) (Set.insert i h, Set.insert j v) xs\n"}, {"source_code": "import Data.List (mapAccumL)\nimport Data.Maybe (catMaybes)\n\nmain :: IO ()\nmain = putStrLn . unwords . map show . solve . map (map read . words) . tail . lines =<< getContents\n\nsolve :: [[Int]] -> [Int]\nsolve = catMaybes . snd . mapAccumL f ([], [], 1)\n where f (xs, ys, t) [x, y]\n | x `elem` xs || y `elem` ys = ((xs, ys, t + 1), Nothing)\n | otherwise = ((x:xs, y:ys, t + 1), Just t)\n f _ _ = undefined\n"}, {"source_code": "import Data.Bits (setBit,testBit)\nimport Data.Word (Word64)\nmain = do\n n <- readLn\n putStrLn . unwords . map show =<< solve (0 :: Word64,0 :: Word64) [1..n^2]\nsolve _ [] = return []\nsolve (h,v) (i:is) = do\n [a,b] <- fmap (map read . words) getLine\n if (h `testBit` a) || (v `testBit` b)\n then solve (h,v) is\n else fmap (i:) $ solve (h `setBit` a, v `setBit` b) is\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport qualified Data.Set as S\n\nprocess _ _ _ [] x = reverse x\nprocess d h v (a:b:c) x | S.notMember a h && S.notMember b v = process (d+1) (S.insert a h) (S.insert b v) c (d:x)\n\t | otherwise = process (d+1) h v c x\n \n \nmain=do\t \n\tn<- read <$> getLine::IO Int\n\ts<-map (fst.fromJust.C.readInt). C.words<$> C.getContents::IO [Int]\n\tputStrLn $ intercalate \" \" $ map show $ process 1 S.empty S.empty s []"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Set (empty,insert,member)\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- forM [1..(n*n)] $ \\_ -> do\n [x,y] <- fmap ((map read) . words) getLine :: IO [Int]\n return (x,y)\n mapM_ (\\x -> putStr ((show x)++\" \")) (solve 1 a empty empty)\n\n\nsolve _ [] _ _ = []\nsolve i ((x,y):xs) mh mv\n |or [member x mh,member y mv] = solve (i+1) xs mh mv\n |otherwise = i:solve (i+1) xs (insert x mh) (insert x mv)"}, {"source_code": "import Control.Monad\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- forM [1..(n*n)] $ \\_ -> do\n [x,y] <- fmap ((map read) . words) getLine :: IO [Int]\n return (x,y)\n mapM_ (\\x -> putStr ((show x)++\" \")) (solve 1 a)\n\n\nsolve _ [] = []\nsolve i ((x,y):xs)\n |x==y = i:solve (i+1) xs\n |otherwise = solve (i+1) xs"}, {"source_code": "import Control.Monad\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- forM [1..(n*n)] $ \\_ -> do\n [x,y] <- fmap ((map read) . words) getLine :: IO [Int]\n return (x,y)\n mapM_ (\\x -> putStr ((show x)++\" \")) (solve 1 a)\n putStrLn \"\"\n\n\nsolve _ [] = []\nsolve i ((x,y):xs)\n |x==y = i:solve (i+1) xs\n |otherwise = solve (i+1) xs"}, {"source_code": "import Control.Monad\nimport Data.Set (empty,insert,member)\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- forM [1..(n*n)] $ \\_ -> do\n [x,y] <- fmap ((map read) . words) getLine :: IO [Int]\n return (x,y)\n mapM_ (\\x -> putStr ((show x)++\" \")) (solve 1 a empty)\n\n\nsolve _ [] _ = []\nsolve i ((x,y):xs) m\n |or [member x m,member y m] = solve (i+1) xs m\n |otherwise = i:solve (i+1) xs (insert x . insert y $ m)"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\n\nmain::IO ()\nmain=do\n n<- read <$> getLine::IO Int\n putStrLn $ intercalate \" \" $ map show [i*i|i<-[1..n]]\n"}, {"source_code": "import Data.Bits (setBit,testBit)\nimport Control.Monad (when,foldM_)\nmain = do\n n <- readLn\n foldM_ solve (0 :: Int,0 :: Int) [1..n]\nsolve (h,v) i = do\n [a,b] <- fmap (map read . words) getLine\n when ((not (h `testBit` a)) && (not (v `testBit` b))) (print i)\n return (h `setBit` a, v `setBit` b)\n \n"}, {"source_code": "import Data.Bits (setBit,testBit)\nmain = do\n n <- readLn\n putStrLn . unwords . map show =<< solve (0 :: Int,0 :: Int) [1..n^2]\nsolve _ [] = return []\nsolve (h,v) (i:is) = do\n [a,b] <- fmap (map read . words) getLine\n if (h `testBit` a) || (v `testBit` b)\n then solve (h,v) is\n else fmap (i:) $ solve (h `setBit` a, v `setBit` b) is\n \n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main) where\nimport Control.Monad.State\nimport Data.Set\n-- Meat\n\nsolve :: [[Int]] -> [Int]\nsolve as = [ snd x | x <- bools `zip` [1..], fst x]\n where bools = evalState (mapM feed as) noHistory\n\ndata RoadHistory = RoadHistory (Set Int) (Set Int) deriving (Show)\n\nnoHistory :: RoadHistory\nnoHistory = RoadHistory Data.Set.empty Data.Set.empty\n\nfeed :: [Int] -> State RoadHistory Bool\nfeed (h:v:_ )= state $ transform h v\nfeed _ = error \"You suck\"\n\ntransform :: Int -> Int -> RoadHistory -> (Bool, RoadHistory)\ntransform h v (RoadHistory horH verH) = (shouldWork, RoadHistory newHorH newVerH)\n where shouldWork = h `notMember` horH && v `notMember` verH\n newHorH = if shouldWork then insert h horH else horH\n newVerH = if shouldWork then insert v horH else verH\n\n-- Shit\nmain :: IO ()\nmain = do\n _:as <- readShit\n printShit $ solve as\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = putStrLn . unlines . fmap (unwords . fmap show)\n readShit = fmap (fmap (fmap read . words) . lines) getContents"}], "src_uid": "c611808e636d9307e6df9ee0e706310b"} {"source_code": "module Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map (map readInt.words) <$> replicateM n getLine\n let ans = solve xs\n print ans\n \nreadInt :: String -> Int\nreadInt = read\n\nsolve :: [[Int]] -> Int\nsolve = foldl update 0\n\nupdate :: Int -> [Int] -> Int\nupdate s (a:b:_) = fromJust $ find (> s) [a + d * b | d <- [0..]]\n\n", "positive_code": [{"source_code": "main = getContents >>= print . exec\nexec = solve 0 . map read . tail . words\nsolve m (s:d:xs) = solve (s + k * d) xs\n where k = max 0 $ ceiling $ fromIntegral (m + 1 - s) / fromIntegral d\nsolve m _ = m"}], "negative_code": [{"source_code": "main = getContents >>= print . exec\nexec = solve 0 . map read . tail . words\nsolve m (s:d:xs) = solve (s + k * d) xs\n where k = max 0 $ ceiling $ fromIntegral (m - s) / fromIntegral d\nsolve m _ = m"}], "src_uid": "d324617c86423d86cdcb839894e00e1a"} {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n currentValue :: [(Int, Int)] -> Int\n currentValue xs =\n let (ps, qs) = unzip xs\n in (sum ps) - (sum qs)\n\n parseTuple :: String -> (Int, Int)\n parseTuple xs =\n let [x, y] = (map readInt . words) xs\n in (x, y)\n\n changes :: Int -> (Int, Int) -> Int\n changes current (l, r) = current + 2 * (r - l)\n\n indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int\n indexOfMostValue midx _ _ [] = midx\n indexOfMostValue midx most idx (x:xs)\n | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs\n | otherwise = indexOfMostValue midx most (idx + 1) xs\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- readMultilineInput n (return . parseTuple)\n let cv = currentValue xs\n chgs = map (changes cv) xs\n print $ (1+) $ indexOfMostValue (-1) (abs cv) 0 chgs\n", "positive_code": [{"source_code": "{-\nmodule Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n currentValue :: [(Int, Int)] -> Int\n currentValue xs =\n let (ps, qs) = unzip xs\n in (sum ps) - (sum qs)\n\n parseTuple :: String -> (Int, Int)\n parseTuple xs =\n let [x, y] = (map readInt . words) xs\n in (x, y)\n\n changes :: Int -> (Int, Int) -> Int\n changes current (l, r) = current + 2 * (r - l)\n\n indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int\n indexOfMostValue midx _ _ [] = midx\n indexOfMostValue midx most idx (x:xs)\n | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs\n | otherwise = indexOfMostValue midx most (idx + 1) xs\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- readMultilineInput n (return . parseTuple)\n let cv = currentValue xs\n chgs = map (changes cv) xs\n print $ (1+) $ indexOfMostValue (-1) (abs cv) 0 chgs\n-}\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\ntest :: Int -> Int\ntest n = n\nparseInts :: String -> [Int]\nparseInts str = map read (words str)\ntoArray :: [a] -> Array Int a\ntoArray xs =\n let ls = length xs - 1 \n in array (0, ls) $ zip [0..ls] xs\ntoTuple :: [a] -> (a, a)\ntoTuple (a : b : _) = (a,b)\nsolve :: [(Int, Int)] -> Int\nsolve xs =\n let diff = sum $ map (\\(a, b) -> a - b) xs\n trans = map (\\(a, b) -> diff + 2 * (b - a)) xs\n in snd $ maximumBy (comparing fst) (zip (map abs (diff:trans)) [0..])\n\nmain :: IO ()\nmain = do\n (n : _) <- getLine >>= return . parseInts\n arr <- replicateM n (getLine >>= return . toTuple . parseInts)\n print $ solve arr\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\nparseInts :: String -> [Int]\nparseInts str = map read (words str)\ntoTuple :: [a] -> (a, a)\ntoTuple (a : b : _) = (a,b)\nsolve :: [(Int, Int)] -> Int\nsolve xs =\n let diff = sum $ map (\\(a, b) -> a - b) xs\n trans = map (\\(a, b) -> diff + 2 * (b - a)) xs\n in snd $ maximumBy (comparing fst) (zip (map abs (diff:trans)) [0..])\n{-fuck-}\nmain :: IO ()\nmain = do\n (n : _) <- getLine >>= return . parseInts\n arr <- replicateM n (getLine >>= return . toTuple . parseInts)\n print $ solve arr\n"}, {"source_code": "import Data.Ord\nimport Data.List\nmain = interact $ show . solve . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve lrs | m < update (0,0) = 0\n | otherwise = i\n where (m,i) = maximum $ flip zip [1..] $ map update lrs\n (ls,rs) = unzip lrs\n update (l,r) = abs ((sum ls + r - l) - (sum rs + l - r))\n"}], "negative_code": [{"source_code": "{-\nmodule Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n currentValue :: [(Int, Int)] -> Int\n currentValue xs =\n let (ps, qs) = unzip xs\n in (sum ps) - (sum qs)\n\n parseTuple :: String -> (Int, Int)\n parseTuple xs =\n let [x, y] = (map readInt . words) xs\n in (x, y)\n\n changes :: Int -> (Int, Int) -> Int\n changes current (l, r) = current + 2 * (r - l)\n\n indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int\n indexOfMostValue midx _ _ [] = midx\n indexOfMostValue midx most idx (x:xs)\n | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs\n | otherwise = indexOfMostValue midx most (idx + 1) xs\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- readMultilineInput n (return . parseTuple)\n let cv = currentValue xs\n chgs = map (changes cv) xs\n print $ (1+) $ indexOfMostValue (-1) (abs cv) 0 chgs\n-}\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\ntest :: Int -> Int\ntest n = n\nparseInts :: String -> [Int]\nparseInts str = map read (words str)\ntoArray :: [a] -> Array Int a\ntoArray xs =\n let ls = length xs - 1 \n in array (0, ls) $ zip [0..ls] xs\ntoTuple :: [a] -> (a, a)\ntoTuple (a : b : _) = (a,b)\nsolve :: [(Int, Int)] -> Int\nsolve xs =\n let diff = sum $ map (\\(a, b) -> a - b) xs\n trans = map (\\(a, b) -> abs $ diff + 2 * (b - a)) xs\n in snd $ minimumBy (comparing fst) (zip (diff:trans) [0..])\n\nmain :: IO ()\nmain = do\n (n : _) <- getLine >>= return . parseInts\n arr <- replicateM n (getLine >>= return . toTuple . parseInts)\n print $ solve arr\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\nparseInts :: String -> [Int]\nparseInts str = map read (words str)\ntoTuple :: [a] -> (a, a)\ntoTuple (a : b : _) = (a,b)\nsolve :: [(Int, Int)] -> Int\nsolve xs =\n let diff = sum $ map (\\(a, b) -> a - b) xs\n trans = map (\\(a, b) -> diff - (a - b) + (b - a)) xs\n in snd $ minimumBy (comparing fst) (zip (diff:trans) [0..])\n\nmain :: IO ()\nmain = do\n (n : _) <- getLine >>= return . parseInts\n arr <- replicateM n (getLine >>= return . toTuple . parseInts)\n print $ solve arr\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n currentValue :: [(Int, Int)] -> Int\n currentValue xs =\n let (ps, qs) = unzip xs\n in (sum ps) - (sum qs)\n\n parseTuple :: String -> (Int, Int)\n parseTuple xs =\n let [x, y] = (map readInt . words) xs\n in (x, y)\n\n changes :: Int -> (Int, Int) -> Int\n changes current (l, r) = current + 2 * (r - l)\n\n indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int\n indexOfMostValue midx _ _ [] = midx\n indexOfMostValue midx most idx (x:xs)\n | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs\n | otherwise = indexOfMostValue midx most (idx + 1) xs\n\n main :: IO()\n main = do\n n <- getLine >>= return . readInt\n xs <- readMultilineInput n (return . parseTuple)\n let cv = currentValue xs\n chgs = map (changes cv) xs\n print $ (1+) $ indexOfMostValue (-1) 0 0 chgs\n"}], "src_uid": "2be73aa00a13be5274cf840ecd3befcb"} {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nprintArray [] = \"\"\r\nprintArray (x:xs) = show(x) ++\" \" ++ printArray xs\r\n\r\ndivisible a t n\r\n | a == \"\" = True \r\n | take n a == t = divisible (drop n a) t n \r\n | otherwise = False \r\n \r\nprintS = do \r\n ss<-getLine \r\n tt<-getLine \r\n let s = if (length ss > length tt) then ss else tt\r\n t = if (length ss > length tt) then tt else ss\r\n l = (div (lcm (length s) (length t)) (length s))\r\n a = concat $ replicate l s\r\n putStrLn $ if (divisible a t (length t)) then a else \"-1\"\r\n \r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport Data.Ord\nimport qualified Data.Set as S\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n q <- getInt\n replicateM_ q $ do\n s <- getLine\n t <- getLine\n let fs = factors s\n let ft = factors t\n let commonFactors = [(ds, dt, fs') | (ds, fs') <- fs, (dt, ft') <- ft, fs' == ft']\n putStrLn $ ans commonFactors\n \nans :: [(Int, Int, String)] -> String\nans [] = \"-1\"\nans cf = concat $ replicate (lcm ds dt) fs\n where\n (ds, dt, fs) = L.maximumBy (comparing (\\(_, _, a) -> a)) cf\n\nfactors :: String -> [(Int, String)]\nfactors str = do\n let l = length str\n s <- tail $ L.inits str\n let (d, m) = l `divMod` length s\n guard (m == 0)\n guard (concat (replicate d s) == str)\n pure (d, s)\n\n"}, {"source_code": "import Control.Monad\r\n\r\nsolve xs n = head [s|i<-[1..20],\r\n mod n i == 0,\r\n let d = div n i,\r\n let s = take i xs,\r\n let ts = concat $ replicate d s,\r\n ts == xs]\r\n \r\nprintResult = do\r\n s <- getLine\r\n t <- getLine\r\n let \r\n n = length s\r\n m = length t\r\n s1 = solve s n\r\n t1 = solve t m\r\n n1 = div n $ length s1 \r\n m1 = div m $ length t1\r\n r = if s1 == t1 then concat $ replicate (lcm m1 n1) s1 else show (-1)\r\n putStrLn r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nreadInt :: IO Integer\nreadInt = readLn\n\nstartsWith :: String -> String -> Bool\nstartsWith s t = length s <= length t && s == take (length s) t\n\ndivides :: String -> String -> Bool\ndivides s [] = True\ndivides s t = startsWith s t && divides s (drop (length s) t)\n\nsolve :: String -> String -> Maybe String\nsolve s t =\n let u = concat $ replicate ((lcm (length s) (length t)) `div` (length s)) s in\n if divides s u && divides t u then Just u else Nothing\n\nans :: Maybe String -> String\nans = maybe \"-1\" id\n\nsolveCase :: IO String\nsolveCase = do\n s <- getLine\n t <- getLine\n pure $ ans $ solve s t\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\nsolve :: String -> String -> Maybe String\r\nsolve s t = if sLcmString == tLcmString then Just sLcmString else Nothing\r\n where\r\n sLength = length s\r\n tLength = length t\r\n gcdLength = gcd sLength tLength\r\n sLcmString = join . replicate (tLength `div` gcdLength) $ s\r\n tLcmString = join . replicate (sLength `div` gcdLength) $ t\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [s, t] <- replicateM 2 $ B8.getLine <&> head . B8.words <&> B8.unpack\r\n let answer = solve s t\r\n putStrLn $ fromMaybe \"-1\" answer\r\n\u00a0"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\nsolve :: String -> String -> Maybe String\r\nsolve s t = if sLcmString == tLcmString then Just sLcmString else Nothing\r\n where\r\n sLength = length s\r\n tLength = length t\r\n gcdLength = gcd sLength tLength\r\n sLcmString = join . replicate (tLength `div` gcdLength) $ s\r\n tLcmString = join . replicate (sLength `div` gcdLength) $ t\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [s, t] <- replicateM 2 $ B8.getLine <&> head . B8.words <&> B8.unpack\r\n let answer = solve s t\r\n putStrLn $ fromMaybe \"-1\" answer\r\n\r\n"}, {"source_code": "\r\n\r\nreadString :: () -> (IO[Char])\r\nreadString () = do\r\n c <- getChar\r\n \r\n if (c==' ' || c=='\\n') \r\n then return [c]\r\n else\r\n do \r\n rest <- readString()\r\n return ([c]++rest)\r\n\r\nreadInt :: () -> IO Int \r\nreadInt () = do\r\n help <- readString()\r\n let x = read help :: Int\r\n\r\n return x\r\n\r\nprinter :: () -> IO()\r\nprinter () = do\r\n putStr \"1\\n\"\r\n printer()\r\n\r\nisSignleCharacter :: (String) -> (Bool)\r\nisSignleCharacter (s) = ((replicate (length s) (s!!0))==s)\r\n\r\ncpyString :: (Int, String) -> (String)\r\ncpyString (0, s) = \"\"\r\ncpyString (cnt, s) = s++cpyString(cnt-1, s)\r\n\r\nisDivisible :: (String, String) -> (Bool)\r\nisDivisible (pattern, txt) = (cpyString((length txt) `div` length (pattern), pattern)==txt)\r\n\r\nsolveTestcase :: (Int) -> IO()\r\nsolveTestcase 0 = return ()\r\nsolveTestcase (testId) = do\r\n s <- getLine\r\n t <- getLine \r\n\r\n let solutions1 = [cpyString(cnt, s) | cnt <- [1..20], isDivisible(t, cpyString(cnt, s))]\r\n let solutions2 = [cpyString(cnt, t) | cnt <- [1..20], isDivisible(s, cpyString(cnt, t))]\r\n\r\n putStrLn ((solutions1++solutions2++[\"-1\"])!!0)\r\n solveTestcase(testId-1)\r\n\r\nmain = do\r\n t <- readInt()\r\n solveTestcase(t)"}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\nduplicate :: Int -> String -> String\nduplicate n string = concat $ replicate n string\n\n\ngetTestCases :: Int -> IO [(String, String)]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n line2 <- getLine\n let tcase = (line, line2)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\n-- isDiv :: String -> String -> Bool\n-- isDiv a \"\" = True\n-- isDiv \"\" a = True\n-- isDiv a b =\n-- let\n-- lenA = length a\n-- lenB = length b\n-- sl = if lenA <= lenB then lenA else lenB\n-- ll = lenA + lenB - sl\n-- rmd = ll `rem` sl\n-- in\n-- if rmd == 0 then True else False\n\nsolve :: (String, String) -> String\nsolve (\"\",s) = s\nsolve (s,\"\") = s\nsolve (sa, sb) =\n let\n -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl\n -- fc = head sa\n -- fcb = head sb\n -- (possbl, ans) =\n -- if fc == fcb && all (==fc) sa && all (==fc) sb\n -- then (True, duplicate (lcm lsa lsb) [fc])\n -- else (False, \"-1\")\n -- (possbl2, ans2) =\n -- if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate (lcmab `div` bl) bgl) else (False, \"-1\")\n -- already = if (bl `rem` sl == 0)\n -- then if (duplicate (bl `div` sl) sgl) == bgl\n -- then True\n -- else False\n -- else False\n opta = duplicate (lcmab `div` lsa) sa\n optb = duplicate (lcmab `div` lsb) sb\n possibl3 = if opta == optb then opta else \"-1\"\n lcmab = lcm lsa lsb\n lsa = length sa\n lsb = length sb\n -- (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)\n -- (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)\n -- nrp = lcmab `div` (length bgl)\n -- ans = duplicate bgl nrp\n\n in\n possibl3\n -- if already || possbl || possbl2\n -- then if already\n -- then bgl\n -- else if possbl\n -- then ans\n -- else ans2\n -- else \"-1\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}], "negative_code": [{"source_code": "\r\n\r\nreadString :: () -> (IO[Char])\r\nreadString () = do\r\n c <- getChar\r\n \r\n if (c==' ' || c=='\\n') \r\n then return [c]\r\n else\r\n do \r\n rest <- readString()\r\n return ([c]++rest)\r\n\r\nreadInt :: () -> IO Int \r\nreadInt () = do\r\n help <- readString()\r\n let x = read help :: Int\r\n\r\n return x\r\n\r\nprinter :: () -> IO()\r\nprinter () = do\r\n putStr \"1\\n\"\r\n printer()\r\n\r\nisSignleCharacter :: (String) -> (Bool)\r\nisSignleCharacter (s) = ((replicate (length s) (s!!0))==s)\r\n\r\ncpyString :: (Int, String) -> (String)\r\ncpyString (0, s) = \"\"\r\ncpyString (cnt, s) = s++cpyString(cnt-1, s)\r\n\r\nisDivisible :: (String, String) -> (Bool)\r\nisDivisible (pattern, txt) = (cpyString((length txt) `div` length (pattern), pattern)==txt)\r\n\r\nsolveTestcase :: (Int) -> IO()\r\nsolveTestcase 0 = return ()\r\nsolveTestcase (testId) = do\r\n s <- getLine\r\n t <- getLine \r\n\r\n let solutions1 = [cpyString(cnt, s) | cnt <- [1..20], isDivisible(t, cpyString(cnt, s))]\r\n let solutions2 = [cpyString(cnt, t) | cnt <- [1..20], isDivisible(s, cpyString(cnt, t))]\r\n\r\n print ((solutions1++solutions2++[\"-1\"])!!0)\r\n solveTestcase(testId-1)\r\n\r\nmain = do\r\n t <- readInt()\r\n solveTestcase(t)"}, {"source_code": "\r\n\r\nreadString :: () -> (IO[Char])\r\nreadString () = do\r\n c <- getChar\r\n \r\n if (c==' ' || c=='\\n') \r\n then return [c]\r\n else\r\n do \r\n rest <- readString()\r\n return ([c]++rest)\r\n\r\nreadInt :: () -> IO Int \r\nreadInt () = do\r\n help <- readString()\r\n let x = read help :: Int\r\n\r\n return x\r\n\r\nprinter :: () -> IO()\r\nprinter () = do\r\n putStr \"1\\n\"\r\n printer()\r\n\r\nisSignleCharacter :: (String) -> (Bool)\r\nisSignleCharacter (s) = ((replicate (length s) (s!!0))==s)\r\n\r\ncpyString :: (Int, String) -> (String)\r\ncpyString (0, s) = \"\"\r\ncpyString (cnt, s) = s++cpyString(cnt-1, s)\r\n\r\nsolveTestcase :: (Int) -> IO()\r\nsolveTestcase 0 = return ()\r\nsolveTestcase (testId) = do\r\n s <- getLine\r\n t <- getLine \r\n\r\n if(s==(cpyString((length s) `div` (length t), t))) \r\n then do\r\n putStrLn s\r\n solveTestcase(testId-1)\r\n else if(t==(cpyString((length t) `div` (length s), s)))\r\n then do\r\n putStrLn t\r\n solveTestcase(testId-1)\r\n else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True && (s!!0)==(t!!0))\r\n then do\r\n putStrLn (replicate (lcm (length s) (length t)) (s!!0))\r\n solveTestcase(testId-1)\r\n else do\r\n putStrLn \"-1\"\r\n solveTestcase(testId-1)\r\n\r\n --solveTestcase(testId-1)\r\n\r\nmain = do\r\n t <- readInt()\r\n solveTestcase(t)"}, {"source_code": "\r\n\r\nreadString :: () -> (IO[Char])\r\nreadString () = do\r\n c <- getChar\r\n \r\n if (c==' ' || c=='\\n') \r\n then return [c]\r\n else\r\n do \r\n rest <- readString()\r\n return ([c]++rest)\r\n\r\nreadInt :: () -> IO Int \r\nreadInt () = do\r\n help <- readString()\r\n let x = read help :: Int\r\n\r\n return x\r\n\r\nprinter :: () -> IO()\r\nprinter () = do\r\n putStr \"1\\n\"\r\n printer()\r\n\r\nisSignleCharacter :: (String) -> (Bool)\r\nisSignleCharacter (s) = ((replicate (length s) (s!!0))==s)\r\n\r\ncpyString :: (Int, String) -> (String)\r\ncpyString (0, s) = \"\"\r\ncpyString (cnt, s) = s++cpyString(cnt-1, s)\r\n\r\nsolveTestcase :: (Int) -> IO()\r\nsolveTestcase 0 = return ()\r\nsolveTestcase (testId) = do\r\n s <- getLine\r\n t <- getLine \r\n\r\n if(s==(cpyString((length s) `div` (length t), t))) \r\n then do\r\n putStrLn s\r\n solveTestcase(testId-1)\r\n else if(t==(cpyString((length t) `div` (length s), s)))\r\n then do\r\n putStrLn t\r\n solveTestcase(testId-1)\r\n else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True)\r\n then do\r\n putStrLn (replicate (lcm (length s) (length t)) (s!!0))\r\n solveTestcase(testId-1)\r\n else do\r\n putStrLn \"-1\"\r\n solveTestcase(testId-1)\r\n\r\n --solveTestcase(testId-1)\r\n\r\nmain = do\r\n t <- readInt()\r\n solveTestcase(t)"}, {"source_code": "\r\n\r\nreadString :: () -> (IO[Char])\r\nreadString () = do\r\n c <- getChar\r\n \r\n if (c==' ' || c=='\\n') \r\n then return [c]\r\n else\r\n do \r\n rest <- readString()\r\n return ([c]++rest)\r\n\r\nreadInt :: () -> IO Int \r\nreadInt () = do\r\n help <- readString()\r\n let x = read help :: Int\r\n\r\n return x\r\n\r\nprinter :: () -> IO()\r\nprinter () = do\r\n putStr \"1\\n\"\r\n printer()\r\n\r\nisSignleCharacter :: (String) -> (Bool)\r\nisSignleCharacter (s) = ((replicate (length s) (s!!0))==s)\r\n\r\ncpyString :: (Int, String) -> (String)\r\ncpyString (0, s) = \"\"\r\ncpyString (cnt, s) = s++cpyString(cnt-1, s)\r\n\r\nsolveTestcase :: (Int) -> IO()\r\nsolveTestcase 0 = return ()\r\nsolveTestcase (testId) = do\r\n s <- getLine\r\n t <- getLine \r\n\r\n if(s==(cpyString((length s) `div` (length t), t))) \r\n then do\r\n putStr s\r\n solveTestcase(testId-1)\r\n else if(t==(cpyString((length t) `div` (length s), s)))\r\n then do\r\n putStr t\r\n solveTestcase(testId-1)\r\n else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True)\r\n then do\r\n putStr (replicate (lcm (length s) (length t)) (s!!0))\r\n solveTestcase(testId-1)\r\n else do\r\n putStr \"-1\"\r\n solveTestcase(testId-1)\r\n\r\n --solveTestcase(testId-1)\r\n\r\nmain = do\r\n t <- readInt()\r\n solveTestcase(t)"}, {"source_code": "\r\n\r\nreadString :: () -> (IO[Char])\r\nreadString () = do\r\n c <- getChar\r\n \r\n if (c==' ' || c=='\\n') \r\n then return [c]\r\n else\r\n do \r\n rest <- readString()\r\n return ([c]++rest)\r\n\r\nreadInt :: () -> IO Int \r\nreadInt () = do\r\n help <- readString()\r\n let x = read help :: Int\r\n\r\n return x\r\n\r\nprinter :: () -> IO()\r\nprinter () = do\r\n putStr \"1\\n\"\r\n printer()\r\n\r\nisSignleCharacter :: (String) -> (Bool)\r\nisSignleCharacter (s) = ((replicate (length s) (s!!0))==s)\r\n\r\ncpyString :: (Int, String) -> (String)\r\ncpyString (0, s) = \"\"\r\ncpyString (cnt, s) = s++cpyString(cnt-1, s)\r\n\r\nsolveTestcase :: (Int) -> IO()\r\nsolveTestcase 0 = return ()\r\nsolveTestcase (testId) = do\r\n s <- getLine\r\n t <- getLine \r\n\r\n if(s==(cpyString((length s) `div` (length t), t))) \r\n then do\r\n print s\r\n solveTestcase(testId-1)\r\n else if(t==(cpyString((length t) `div` (length s), s)))\r\n then do\r\n print t\r\n solveTestcase(testId-1)\r\n else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True)\r\n then do\r\n print (replicate (lcm (length s) (length t)) (s!!0))\r\n solveTestcase(testId-1)\r\n else do\r\n print \"-1\"\r\n solveTestcase(testId-1)\r\n\r\n --solveTestcase(testId-1)\r\n\r\nmain = do\r\n t <- readInt()\r\n solveTestcase(t)"}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\nduplicate :: Int -> String -> String\nduplicate n string = concat $ replicate n string\n\n\ngetTestCases :: Int -> IO [(String, String)]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n line2 <- getLine\n let tcase = (line, line2)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\n-- isDiv :: String -> String -> Bool\n-- isDiv a \"\" = True\n-- isDiv \"\" a = True\n-- isDiv a b =\n-- let\n-- lenA = length a\n-- lenB = length b\n-- sl = if lenA <= lenB then lenA else lenB\n-- ll = lenA + lenB - sl\n-- rmd = ll `rem` sl\n-- in\n-- if rmd == 0 then True else False\n\nsolve :: (String, String) -> String\nsolve (\"\",s) = s\nsolve (s,\"\") = s\nsolve (sa, sb) =\n let\n -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl\n fc = head sa\n fcb = head sb\n (possbl, ans) =\n if fc == fcb && all (==fc) sa && all (==fc) sb\n then (True, duplicate (lcm lsa lsb) [fc])\n else (False, \"-1\")\n (possbl2, ans2) =\n if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate (lcmab `div` bl) bgl) else (False, \"-1\")\n already = if (bl `rem` sl == 0)\n then if (duplicate (bl `div` sl) sgl) == bgl\n then True\n else False\n else False\n lcmab = lcm lsa lsb\n lsa = length sa\n lsb = length sb\n (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)\n (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)\n -- nrp = lcmab `div` (length bgl)\n -- ans = duplicate bgl nrp\n\n in\n if already || possbl || possbl2\n then if already\n then bgl\n else if possbl\n then ans\n else ans2\n else \"-1\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\nduplicate :: Int -> String -> String\nduplicate n string = concat $ replicate n string\n\n\ngetTestCases :: Int -> IO [(String, String)]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n line2 <- getLine\n let tcase = (line, line2)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\n-- isDiv :: String -> String -> Bool\n-- isDiv a \"\" = True\n-- isDiv \"\" a = True\n-- isDiv a b =\n-- let\n-- lenA = length a\n-- lenB = length b\n-- sl = if lenA <= lenB then lenA else lenB\n-- ll = lenA + lenB - sl\n-- rmd = ll `rem` sl\n-- in\n-- if rmd == 0 then True else False\n\nsolve :: (String, String) -> String\nsolve (\"\",s) = s\nsolve (s,\"\") = s\nsolve (sa, sb) =\n let\n -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl\n fc = head sa\n fcb = head sb\n (possbl, ans) =\n if fc == fcb && all (==fc) sa && all (==fc) sb\n then (True, duplicate (lcm lsa lsb) [fc])\n else (False, \"-1\")\n (possbl2, ans2) =\n if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate 2 bgl) else (False, \"-1\")\n already = if (bl `rem` sl == 0)\n then if (duplicate (bl `div` sl) sgl) == bgl\n then True\n else False\n else False\n lcmab = lcm lsa lsb\n lsa = length sa\n lsb = length sb\n (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)\n (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)\n -- nrp = lcmab `div` (length bgl)\n -- ans = duplicate bgl nrp\n\n in\n if already || possbl || possbl2\n then if already\n then bgl\n else if possbl\n then ans\n else ans2\n else \"-1\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\nduplicate :: Int -> String -> String\nduplicate n string = concat $ replicate n string\n\n\ngetTestCases :: Int -> IO [(String, String)]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n line2 <- getLine\n let tcase = (line, line2)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\n-- isDiv :: String -> String -> Bool\n-- isDiv a \"\" = True\n-- isDiv \"\" a = True\n-- isDiv a b =\n-- let\n-- lenA = length a\n-- lenB = length b\n-- sl = if lenA <= lenB then lenA else lenB\n-- ll = lenA + lenB - sl\n-- rmd = ll `rem` sl\n-- in\n-- if rmd == 0 then True else False\n\nsolve :: (String, String) -> String\nsolve (\"\",s) = s\nsolve (s,\"\") = s\nsolve (sa, sb) =\n let\n -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl\n fc = head sa\n fcb = head sb\n (possbl, ans) =\n if fc == fcb && all (==fc) sa && all (==fc) sb\n then (True, duplicate (lcm lsa lsb) [fc])\n else (False, \"-1\")\n (possbl2, ans2) =\n if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate 2 bgl) else (False, \"-1\")\n already = if (bl `rem` sl == 0)\n then if (duplicate (bl `div` sl) sgl) == bgl\n then True\n else False\n else False\n lcmab = lcm lsa lsb\n lsa = length sa\n lsb = length sb\n (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)\n (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)\n -- nrp = lcmab `div` (length bgl)\n -- ans = duplicate bgl nrp\n\n in\n if already || possbl || possbl2\n then if already\n then bgl\n else if possbl2\n then ans2\n else ans\n else \"-1\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\nduplicate :: Int -> String -> String\nduplicate n string = concat $ replicate n string\n\n\ngetTestCases :: Int -> IO [(String, String)]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n line2 <- getLine\n let tcase = (line, line2)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\n-- isDiv :: String -> String -> Bool\n-- isDiv a \"\" = True\n-- isDiv \"\" a = True\n-- isDiv a b =\n-- let\n-- lenA = length a\n-- lenB = length b\n-- sl = if lenA <= lenB then lenA else lenB\n-- ll = lenA + lenB - sl\n-- rmd = ll `rem` sl\n-- in\n-- if rmd == 0 then True else False\n\nsolve :: (String, String) -> String\nsolve (\"\",s) = s\nsolve (s,\"\") = s\nsolve (sa, sb) =\n let\n -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl\n fc = head sa\n fcb = head sb\n (possbl, ans) =\n if fc == fcb && all (==fc) sa && all (==fc) sb\n then (True, duplicate (lcm lsa lsb) [fc])\n else (False, \"-1\")\n already = if (bl `rem` sl == 0)\n then if (duplicate (bl `div` sl) sgl) == bgl\n then True\n else False\n else False\n lcmab = lcm lsa lsb\n lsa = length sa\n lsb = length sb\n (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)\n (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)\n -- nrp = lcmab `div` (length bgl)\n -- ans = duplicate bgl nrp\n\n in\n if already || possbl\n then if already\n then bgl\n else ans\n else \"-1\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}, {"source_code": "module Main where\nimport Data.Foldable (traverse_)\nimport Data.List (sort)\n\nduplicate :: Int -> String -> String\nduplicate n string = concat $ replicate n string\n\n\ngetTestCases :: Int -> IO [(String, String)]\ngetTestCases n = go n []\n where\n go 0 ret = return ret\n go n ret = do\n line <- getLine\n line2 <- getLine\n let tcase = (line, line2)\n -- print tcase\n -- print n\n go (n-1) (ret ++ [tcase])\n\nisDiv :: String -> String -> Bool\nisDiv a \"\" = True\nisDiv \"\" a = True\nisDiv a b =\n let\n lenA = length a\n lenB = length b\n sl = if lenA <= lenB then lenA else lenB\n ll = lenA + lenB - sl\n rmd = ll `rem` sl\n in\n if rmd == 0 then True else False\n\nsolve :: (String, String) -> String\nsolve (\"\",s) = s\nsolve (s,\"\") = s\nsolve (sa, sb) =\n let\n possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl\n already = if (bl `rem` sl == 0)\n then if (duplicate (bl `div` sl) sgl) == bgl\n then True\n else False\n else False\n lcmab = lcm lsa lsb\n lsa = length sa\n lsb = length sb\n (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)\n (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)\n -- nrp = lcmab `div` (length bgl)\n -- ans = duplicate bgl nrp\n\n in\n if already || possbl\n then if already\n then bgl\n else (duplicate 2 bgl) else \"-1\"\n\nmain :: IO ()\nmain = do\n ts <- getLine\n let t = read ts :: Int\n testCases <- getTestCases t\n traverse_ (putStrLn . solve) testCases\n\n"}, {"source_code": "import Control.Monad\nimport qualified Data.List as L\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C8\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n q <- getInt\n replicateM_ q $ do\n s@(s1:_) <- getLine\n t <- getLine\n let ls = length s\n let lt = length t\n let result | all (==s1) s && all (==s1) t = Just (replicate (lcm ls lt) s1)\n | ls < lt && t `consistsOf` s = Just t \n | lt < ls && s `consistsOf` t = Just s \n | otherwise = Nothing\n case result of\n Just s -> putStrLn s\n _ -> putStrLn \"-1\"\n\nconsistsOf :: String -> String -> Bool\nconsistsOf \"\" _ = True\nconsistsOf s ref = ref `L.isPrefixOf` s && drop (length ref) s `consistsOf` ref\n\n\n"}], "src_uid": "710c7211d23cf8c01fae0b476a889276"} {"source_code": "{-# LANGUAGE TypeApplications #-}\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.List ( genericReplicate\r\n , scanl'\r\n )\r\n\r\n-- infinite list of prime numbers\r\nprimes :: [Integer]\r\nprimes = 2 : filter isPrime [3, 5 ..]\r\n where\r\n isPrime n = not (any (divides n) (takeWhile (\\p -> p * p <= n) primes))\r\n divides n p = n `mod` p == 0\r\n\r\n-- calculateBase :: Int -> [Int] -> [(Int, Int)]\r\ncalculateBase k xs = scanr (\\x (q, y) -> (x * k, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)\r\n\r\n-- >>> calculateBase 3 [2,3]\r\n-- [(2,10),(9,1)]\r\n\r\n-- convertToBase :: Int -> Int -> [(Int, Int)] -> [Int]\r\nconvertToBase k a = fmap snd . tail . scanl' (\\(rest, _) (q, x) -> let len = min q (rest `div` x) in (rest - len * x, len)) (a, 0)\r\n\r\n-- >>> convertToBase 3 19 (calculateBase 3 [2,3])\r\n-- [1,9]\r\n\r\n-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.\r\n-- replaceBase :: [(Int, Int)] -> Int -> Int -> String -> String\r\nreplaceBase bases k n = phi [] (convertToBase k n bases)\r\n where\r\n phi acc digits [] = concat acc\r\n phi acc (digit : digits) ('*' : xs) = phi (acc ++ [genericReplicate digit 'b']) digits xs\r\n phi acc digits (x : xs) = phi (acc ++ [[x]]) digits xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [_, k, x] <- fmap (map (read @Integer) . words) getLine\r\n (str, segments) <- readStr\r\n putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str\r\n where\r\n readStr = go \"\" [] 0 <$> getLine\r\n go acc segments current [] =\r\n ( case reverse acc of\r\n acc'@('*' : _) -> acc'\r\n acc' -> '*' : acc'\r\n , reverse (current : segments)\r\n )\r\n go acc segments current (x : xs)\r\n | x == '*' = case acc of\r\n ('*' : _) -> go acc segments (current + 1) xs\r\n _ -> go ('*' : acc) segments 1 xs\r\n | otherwise = go (x : acc) (if current > 0 || null acc then current : segments else segments) 0 xs\r\n\r\n\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n res <- replicateM t $ do\n [n, k, x] <- map read . words <$> getLine :: IO [Integer]\n solve n k x <$> getLine\n putStrLn . unlines $ res\n\n\n\nsolve :: Integer -> Integer -> Integer -> String -> String\nsolve n k x s = ans\n where\n stars = words [if c == '*' then c else ' ' | c <- s]\n as = words [if c == 'a' then c else ' ' | c <- 'a':s]\n bases = reverse $ map ((1 +) . (fromInteger k *) . length) stars\n num = reverse $ convert bases (x-1)\n _:ans = blend as (map (`replicate` 'b') num)\n\n\nconvert :: [Int] -> Integer -> [Int]\nconvert [] _ = []\nconvert (b:bs) x = fromInteger m : convert bs q\n where\n (q, m) = divMod x (toInteger b)\n\nblend :: [String] -> [String] -> String\nblend (x:xs) ys = x ++ blend ys xs\nblend [] ys = concat ys"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeApplications #-}\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.List ( scanl' )\r\n\r\n-- infinite list of prime numbers\r\nprimes :: [Integer]\r\nprimes = 2 : filter isPrime [3, 5 ..]\r\n where\r\n isPrime n = not (any (divides n) (takeWhile (\\p -> p * p <= n) primes))\r\n divides n p = n `mod` p == 0\r\n\r\ncalculateBase :: Int -> [Int] -> [(Int, Int)]\r\ncalculateBase k xs = scanr (\\x (q, y) -> (x * k, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)\r\n\r\n-- >>> calculateBase 3 [2,3]\r\n-- [(2,10),(9,1)]\r\n\r\nconvertToBase :: Int -> Int -> [(Int, Int)] -> [Int]\r\nconvertToBase k a = fmap snd . tail . scanl' (\\(rest, _) (q, x) -> let len = min q (rest `div` x) in (rest - len * x, len)) (a, 0)\r\n\r\n-- >>> convertToBase 3 19 (calculateBase 3 [2,3])\r\n-- [1,9]\r\n\r\n-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.\r\nreplaceBase :: [(Int, Int)] -> Int -> Int -> String -> String\r\nreplaceBase bases k n = phi [] (convertToBase k n bases)\r\n where\r\n phi acc digits [] = concat acc\r\n phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs\r\n phi acc digits (x : xs) = phi (acc ++ [[x]]) digits xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [_, k, x] <- fmap (map (read @Int) . words) getLine\r\n (str, segments) <- readStr\r\n putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str\r\n where\r\n readStr = go \"\" [] 0 <$> getLine\r\n go acc segments current [] =\r\n ( case reverse acc of\r\n acc'@('*' : _) -> acc'\r\n acc' -> '*' : acc'\r\n , reverse (current : segments)\r\n )\r\n go acc segments current (x : xs)\r\n | x == '*' = case acc of\r\n ('*' : _) -> go acc segments (current + 1) xs\r\n _ -> go ('*' : acc) segments 1 xs\r\n | otherwise = go (x : acc) (if current > 0 || null acc then current : segments else segments) 0 xs\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.List ( scanl' )\r\nimport Debug.Trace ( traceShow )\r\n\r\n-- infinite list of prime numbers\r\nprimes :: [Integer]\r\nprimes = 2 : filter isPrime [3, 5 ..]\r\n where\r\n isPrime n = not (any (divides n) (takeWhile (\\p -> p * p <= n) primes))\r\n divides n p = n `mod` p == 0\r\n\r\ncalculateBase :: Int -> [Int] -> [(Int, Int)]\r\ncalculateBase k xs = scanr (\\x (q, y) -> (x, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)\r\n\r\n-- >>> calculateBase 3 [2,3]\r\n-- [(2,10),(9,1)]\r\n\r\nconvertToBase :: Int -> Int -> [(Int, Int)] -> [Int]\r\nconvertToBase k a = fmap snd . tail . scanl' (\\(rest, _) (q, x) -> let len = min (q * k) (rest `div` x) in (rest - len * x, len)) (a, 0)\r\n\r\n-- >>> convertToBase 3 19 (calculateBase 3 [2,3])\r\n-- [1,9]\r\n\r\n-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.\r\nreplaceBase :: [(Int, Int)] -> Int -> Int -> String -> String\r\nreplaceBase bases k n = phi [] (convertToBase k n bases)\r\n where\r\n phi acc digits [] = concat acc\r\n phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs\r\n phi acc digits (x : xs) = phi (acc ++ [[x]]) digits xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [_, k, x] <- fmap (map (read @Int) . words) getLine\r\n (str, segments) <- readStr\r\n putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str\r\n where\r\n readStr = go \"\" [] 0 <$> getLine\r\n go acc segments current [] =\r\n ( case reverse acc of\r\n acc'@('*' : _) -> acc'\r\n acc' -> '*' : acc'\r\n , reverse (current : segments)\r\n )\r\n go acc segments current (x : xs)\r\n | x == '*' = case acc of\r\n ('*' : _) -> go acc segments (current + 1) xs\r\n _ -> go ('*' : acc) segments 1 xs\r\n | otherwise = go (x : acc) (if current > 0 || null acc then current : segments else segments) 0 xs\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.List ( scanl' )\r\nimport Debug.Trace ( traceShow )\r\n\r\n-- infinite list of prime numbers\r\nprimes :: [Integer]\r\nprimes = 2 : filter isPrime [3, 5 ..]\r\n where\r\n isPrime n = not (any (divides n) (takeWhile (\\p -> p * p <= n) primes))\r\n divides n p = n `mod` p == 0\r\n\r\ncalculateBase :: Int -> [Int] -> [(Int, Int)]\r\ncalculateBase k xs = scanr (\\x (q, y) -> (x, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)\r\n\r\n-- >>> calculateBase 3 [2,3]\r\n-- [(2,10),(9,1)]\r\n\r\nconvertToBase :: Int -> Int -> [(Int, Int)] -> [Int]\r\nconvertToBase k a = fmap snd . tail . scanl' (\\(rest, _) (q, x) -> let len = min (q * k) (rest `div` x) in (rest - len * x, len)) (a, 0)\r\n\r\n-- >>> convertToBase 3 19 (calculateBase 3 [2,3])\r\n-- [1,9]\r\n\r\n-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.\r\nreplaceBase :: [(Int, Int)] -> Int -> Int -> String -> String\r\nreplaceBase bases k n = phi [] (convertToBase k n bases)\r\n where\r\n phi acc digits [] = concat acc\r\n phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs\r\n phi acc digits (x : xs) = phi (acc ++ [[x]]) digits xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [_, k, x] <- fmap (map (read @Int) . words) getLine\r\n (str, segments) <- readStr\r\n putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str\r\n where\r\n readStr = go \"\" [] 0 <$> getLine\r\n go acc segments current [] =\r\n ( case reverse acc of\r\n acc'@('*' : _) -> acc'\r\n acc' -> '*' : acc'\r\n , reverse (current : segments)\r\n )\r\n go acc segments current (x : xs)\r\n | x == '*' = case acc of\r\n ('*' : _) -> go acc segments (current + 1) xs\r\n _ -> go ('*' : acc) segments 1 xs\r\n | otherwise = go (x : acc) (current : segments) 0 xs\r\n\r\n\r\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\r\nmodule Main where\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.List ( scanl' )\r\n\r\n-- infinite list of prime numbers\r\nprimes :: [Integer]\r\nprimes = 2 : filter isPrime [3, 5 ..]\r\n where\r\n isPrime n = not (any (divides n) (takeWhile (\\p -> p * p <= n) primes))\r\n divides n p = n `mod` p == 0\r\n\r\ncalculateBase :: Int -> [Int] -> [(Int, Int)]\r\ncalculateBase k xs = scanr (\\x (q, y) -> (x, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)\r\n\r\n-- >>> calculateBase 3 [2,3]\r\n-- [(2,10),(9,1)]\r\n\r\nconvertToBase :: Int -> Int -> [(Int, Int)] -> [Int]\r\nconvertToBase k a = fmap snd . tail . scanl' (\\(rest, _) (q, x) -> let len = min q (a `div` x) in (rest - len * x, len)) (a, 0)\r\n\r\n-- >>> convertToBase 3 19 (calculateBase 3 [2,3])\r\n-- [1,9]\r\n\r\n-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.\r\nreplaceBase :: [(Int, Int)] -> Int -> Int -> String -> String\r\nreplaceBase bases k n = phi [] (convertToBase k n bases)\r\n where\r\n phi acc digits [] = concat acc\r\n phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs\r\n phi acc digits (x : xs) = phi (acc ++ [[x]]) digits xs\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [_, k, x] <- fmap (map (read @Int) . words) getLine\r\n (str, segments) <- readStr\r\n putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str\r\n where\r\n readStr = go \"\" [] 0 <$> getLine\r\n go acc segments current [] =\r\n ( case reverse acc of\r\n acc'@('*' : _) -> acc'\r\n acc' -> '*' : acc'\r\n , reverse (current : segments)\r\n )\r\n go acc segments current (x : xs)\r\n | x == '*' = case acc of\r\n ('*' : _) -> go acc segments (current + 1) xs\r\n _ -> go ('*' : acc) segments 1 xs\r\n | otherwise = go (x : acc) (current : segments) 0 xs\r\n\r\n\r\n"}], "src_uid": "32ed4995e557cfdcbef375e2b9edb1a6"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\n\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n sn:l <- B.lines <$> B.getContents\n let n = readInt sn\n let (_es,sq:l') = splitAt (n-1) l\n let es = map (map readInt . B.words) _es\n let q = readInt sq\n let qs = map (map readInt . B.words) l'\n putStr $ unlines $ map (printf \"%.6f\") $ solve n es q qs\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]\nsolve n es q qs = runST doit where\n n' :: Integer\n n' = fromIntegral n\n edges = buildTree n es\n ws = [ fromIntegral w | [_,_,w] <- es ]\n doit :: ST s [Double]\n doit = do\n edgeLength <- newListArray (0,n-2) ws :: ST s (STUArray s Int Int64)\n let cost0 = sum $ zipWith (*) ws (elems edges)\n go cost0 edgeLength qs\n go :: Int64 -> (STUArray s Int Int64) -> [[Int]] -> ST s [Double]\n go _ _ [] = return []\n go !cost edgeLength ([ri,wi]:qs) = do\n wi' <- unsafeRead edgeLength (ri-1)\n let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)\n r = unsafeAt edges (ri-1)\n cost' = cost + fromIntegral (fromIntegral wi - wi') * r\n unsafeWrite edgeLength (ri-1) (fromIntegral wi)\n (e:) <$> go cost' edgeLength qs\n\nbuildTree :: Int -> [[Int]] -> UArray Int Int64\nbuildTree n es = doit where\n g :: Array Int [(Int,Int)]\n g = accumArray (flip (:)) [] (1,n) $ do\n (i,[a,b,w]) <- zip [1..] es\n [(a,(b,i)),(b,(a,i))]\n n' = fromIntegral n\n doit = runSTUArray $ do\n a <- newArray_ (0,n-2)\n let dfs pv v = do\n let us = [ (u,i-1) | (u,i) <- g ! v, u /= pv ]\n fmap ((+1).sum) $ forM us $ \\(u,i) -> do\n ci <- dfs v u\n unsafeWrite a i (ci * (n'- ci))\n return ci\n dfs (-1) 1\n return a\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as IM\n\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n sn:l <- B.lines <$> B.getContents\n let n = readInt sn\n let (_es,sq:l') = splitAt (n-1) l\n let es = map (map readInt . B.words) _es\n let q = readInt sq\n let qs = map (map readInt . B.words) l'\n putStr $ unlines $ map (printf \"%.6f\") $ solve n es q qs\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]\nsolve n es q qs = runST doit where\n n' :: Integer\n n' = fromIntegral n\n doit = do\n edges <- buildTree n es\n cost0 <- do\n es <- getElems edges\n return $ sum $ [ fromIntegral w * l * (n'-l) | (w,l) <- es ]\n go cost0 edges qs\n go _ _ [] = return []\n go !cost edges ([ri,wi]:qs) = do\n (wi',l) <- readArray edges ri\n let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)\n cost' = cost + fromIntegral (wi - wi') * l * (n'-l)\n writeArray edges ri (wi,l)\n (e:) <$> go cost' edges qs\n\nbuildTree :: Int -> [[Int]] -> ST s (STArray s Int (Int,Integer))\nbuildTree n es = doit where\n g :: Array Int [(Int,Int,Int)]\n g = accumArray (flip (:)) [] (1,n) $ do\n (i,[a,b,w]) <- zip [1..] es\n [(a,(b,w,i)),(b,(a,w,i))]\n doit = do\n a <- newArray_ (1,n-1)\n let dfs pv v = do\n let us = [ (u,w,i) | (u,w,i) <- g ! v, u /= pv]\n fmap ((+1).sum) $ forM us $ \\(u,w,i) -> do\n ci <- dfs v u\n writeArray a i (w,ci)\n return ci\n dfs (-1) 1\n return a\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as IM\n\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n sn:l <- B.lines <$> B.getContents\n let n = readInt sn\n let (_es,sq:l') = splitAt (n-1) l\n let es = map (map readInt . B.words) _es\n let q = readInt sq\n let qs = map (map readInt . B.words) l'\n putStr $ unlines $ map (printf \"%.6f\") $ solve n es q qs\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]\nsolve n es q qs = go cost0 edges0 qs where\n n' :: Integer\n n' = fromIntegral n\n go _ _ [] = []\n go !cost !edges ([ri,wi]:qs) = e : go cost' edges' qs where\n (wi',l) = edges IM.! ri\n e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)\n cost' = cost + fromIntegral (wi - wi') * l * (n'-l)\n edges' = IM.insert ri (wi,l) edges\n cost0 = sum $ [ fromIntegral w * l * (n'-l) | (w,l) <- IM.elems edges0 ]\n edges0 = buildTree n es\n\nbuildTree :: Int -> [[Int]] -> IM.IntMap (Int,Integer)\nbuildTree n es = execState doit IM.empty where\n g :: Array Int [(Int,Int,Int)]\n g = accumArray (flip (:)) [] (1,n) $ do\n (i,[a,b,w]) <- zip [1..] es\n [(a,(b,w,i)),(b,(a,w,i))]\n doit = void $ dfs (-1) 1\n dfs pv v = do\n let us = [ (u,w,i) | (u,w,i) <- g ! v, u /= pv]\n fmap ((+1).sum) $ forM us $ \\(u,w,i) -> do\n ci <- dfs v u\n modify (IM.insert i (w,ci))\n return ci\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.IntMap hiding (map, foldl)\nimport qualified Data.IntMap as M\nfuck = maybe 0 fst . B.readInt\nmain = B.interact $ B.unlines . map (B.pack . show) . f . map fuck . B.words\nf (n:x) = map (6/z/(z-1)*) $ g s m r where\n z = fromIntegral n\n (p, (q:r)) = splitAt (3*n-3) x\n m = M.map (\\(k,l) -> (k*(z-k),l)) $ h p\n s = M.foldl (\\a (k,l) -> a+k*fromIntegral l) 0 m\ng _ _ [] = []\ng s m (r:w:q) = t:g t u q where\n (k,l) = m!r\n t = s-k*fromIntegral(l-w)\n u = adjust (\\(k,l) -> (k,w)) r m\nh x = fromList . snd $ i [] 0 1 where\n m = j 1 x\n i s u v = foldl f (1,s) $ m!v where\n f x (b,_,_) | b == u = x\n f (x,y) (b,k,l) = let (p,q) = i y v b in (x+p,(k,(fromIntegral p,l)):q)\nj _ [] = empty\nj k (a:b:l:s) = unionWith (++) (fromList [(a,[(b,k,l)]),(b,[(a,k,l)])]) $ j (k+1) s"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap as IM\n\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n sn:l <- B.lines <$> B.getContents\n let n = readInt sn\n let (_es,sq:l') = splitAt (n-1) l\n let es = map (map readInt . B.words) _es\n let q = readInt sq\n let qs = map (map readInt . B.words) l'\n putStr $ unlines $ map (printf \"%.6f\") $ solve n es q qs\n\nsolve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]\nsolve n es q qs = runST doit where\n n' :: Integer\n n' = fromIntegral n\n edges = buildTree n es\n ws = [ fromIntegral w | [_,_,w] <- es ]\n doit :: ST s [Double]\n doit = do\n edgeLength <- newListArray (1,n-1) ws :: ST s (STUArray s Int Int64)\n let cost0 = sum $ zipWith (*) ws (elems edges)\n go cost0 edgeLength qs\n go :: Int64 -> (STUArray s Int Int64) -> [[Int]] -> ST s [Double]\n go _ _ [] = return []\n go !cost edgeLength ([ri,wi]:qs) = do\n wi' <- readArray edgeLength ri\n let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)\n r = edges ! ri\n cost' = cost + fromIntegral (fromIntegral wi - wi') * r\n writeArray edgeLength ri (fromIntegral wi)\n (e:) <$> go cost' edgeLength qs\n\nbuildTree :: Int -> [[Int]] -> UArray Int Int64\nbuildTree n es = doit where\n g :: Array Int [(Int,Int)]\n g = accumArray (flip (:)) [] (1,n) $ do\n (i,[a,b,w]) <- zip [1..] es\n [(a,(b,i)),(b,(a,i))]\n n' = fromIntegral n\n doit = runSTUArray $ do\n a <- newArray_ (1,n-1)\n let dfs pv v = do\n let us = [ (u,i) | (u,i) <- g ! v, u /= pv]\n fmap ((+1).sum) $ forM us $ \\(u,i) -> do\n ci <- dfs v u\n writeArray a i (ci * (n'- ci))\n return ci\n dfs (-1) 1\n return a\n"}], "negative_code": [{"source_code": "import Data.IntMap hiding (foldl)\nimport qualified Data.IntMap as M\nmain = interact $ unlines . fmap show . f . fmap read . words\nf (n:x) = fmap ((* t) . fromIntegral) $ g s m r where\n (p, (q:r)) = splitAt (3*n-3) x\n m = M.map (\\(k,l) -> (k*(toInteger n-k),l)) $ h p\n s = M.foldl (\\a (k,l) -> a+k*toInteger l) 0 m\n t = 6.0 / (fromIntegral $ n*(n-1))\ng _ _ [] = []\ng s m (r:w:q) = t:g t u q where\n (k,l) = m!r\n t = s-k*toInteger(l-w)\n u = adjust (\\(k,l) -> (k,w)) r m\nh x = fromList . snd $ i 0 1 where\n m = j 1 x\n i u v = foldl f (1,[]) $ m!v where\n f x (b,_,_) | b == u = x\n f (x,y) (b,k,l) = let (p,q) = i v b in (x+p,(k,(p,l)):y++q)\nj _ [] = empty\nj k (a:b:l:s) = unionWith (++) (fromList [(a,[(b,k,l)]),(b,[(a,k,l)])]) $ j (k+1) s\n"}], "src_uid": "38388446f5c265f77124132caa3ce4d2"} {"source_code": "import Control.Monad\r\nimport Control.Monad.Trans.Class\r\nimport Control.Monad.Trans.State\r\nimport qualified Data.ByteString.Builder as B\r\nimport qualified Data.ByteString.Char8 as S\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.List\r\nimport Data.Semigroup\r\nimport System.IO\r\n\r\n-- Throws exception if not found\r\nfindNext :: S.ByteString -> Char -> Int -> Int\r\nfindNext s c i = if S.index s i == c then i else findNext s c (i + 1)\r\n\r\nfirstBeautifulSequence :: S.ByteString -> String -> [Int]\r\nfirstBeautifulSequence s t = tail $ scanl (\\i c -> findNext s c (i + 1)) (-1) t\r\n\r\nmain :: IO ()\r\nmain = (P.getContents >>=) . evalStateT $ do\r\n [n, m] <- readInts\r\n s <- P.toStrict <$> readLine\r\n t <- P.unpack <$> readLine\r\n let dpFwd = firstBeautifulSequence s t\r\n dpRev = reverse (map ((S.length s - 1) -) $ firstBeautifulSequence (S.reverse s) (reverse t))\r\n answer = maximum $ zipWith (-) (tail dpRev) dpFwd\r\n putInts [answer]\r\n\r\ntype SIO = StateT P.ByteString IO\r\n\r\nreadLine :: SIO P.ByteString\r\nreadLine = do\r\n (out, next) <- P.break (<= '\\r') <$> get\r\n put $ P.dropWhile (<= '\\r') next\r\n pure out\r\n\r\nreadInts :: SIO [Int]\r\nreadInts = do\r\n currLine <- readLine\r\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\r\n\r\nputInts :: [Int] -> SIO ()\r\nputInts li =\r\n let outBuilder =\r\n foldr (<>) (B.char7 '\\n') $\r\n intersperse (B.char7 ' ') (map B.intDec li)\r\n in lift $ B.hPutBuilder stdout outBuilder", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n ~[n, m] <- popInts\n s <- B.unpack <$> popJust\n t <- B.unpack <$> popJust\n return $ bshow (solve n m s t) <> \"\\n\"\n\n\nsolve n m s t = maximum $ map (\\((a, _), (_, b)) -> b - a) $ adjlist $ zip fi bi\n where\n makeIndex s t = makeIndex' 0 s t\n\n makeIndex' _ _ [] = []\n makeIndex' i (s : ss) ts@(t : ts')\n | s == t = i : makeIndex' (i + 1) ss ts'\n | otherwise = makeIndex' (i + 1) ss ts\n\n fi = makeIndex s t\n\n bi = map ((n - 1 -)) $ reverse $ makeIndex (reverse s) (reverse t)\n\n\nadjlist as@(_ : as') = zip as as'\nadjlist _ = []\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Char8 as S\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, m] <- readInts\n s <- P.toStrict <$> readLine\n t <- P.unpack <$> readLine\n let\n sfwd c i = if S.index s i == c then i else sfwd c (i+1)\n srev c i = if S.index s i == c then i else srev c (i-1)\n istart = sfwd (head t) 0\n is = scanl (\\i c -> sfwd c (i+1)) istart (tail t)\n trev = reverse t\n jstart = srev (head trev) (n-1)\n js = reverse $ scanl (\\j c -> srev c (j-1)) jstart (tail trev)\n putInts [maximum $ zipWith (-) (tail js) is]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "17fff01f943ad467ceca5dce5b962169"} {"source_code": "main = do\n (n:as) <- fmap (map read . words) getContents\n let e = length $ filter even as\n let o = n - e\n print $ if o < e then o else (e + (o-e) `div` 3)", "positive_code": [{"source_code": "\nmain = do\n (n : as) <- fmap (map read . words) getContents\n let even = length . filter (\\x -> x `mod` 2 == 0) $ as\n let odd = length . filter (\\x -> x `mod` 2 == 1) $ as\n if even >= odd\n then print $ odd\n else print $ even + ((odd - even) `quot` 3)\n\n"}, {"source_code": "main = do\n (n:as) <- fmap (map read . words) getContents\n let e = length $ filter even as\n let o = n - e\n print $ if o < e then o else (e + (o-e) `div` 3)"}, {"source_code": "--ghc 7.10\n\nevenCount :: [Integer] -> Integer\nevenCount [] = 0\nevenCount (x:xs)\n | x `mod` 2 == 0 = 1 + evenCount xs\n | otherwise = evenCount xs\n \noddCount :: [Integer] -> Integer\noddCount [] = 0\noddCount (x:xs)\n | x `mod` 2 == 1 = 1 + oddCount xs\n | otherwise = oddCount xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let n = read str :: Integer\n str <- getLine\n let a = fmap (\\as -> read as :: Integer) (words str)\n let ecnt = evenCount a\n let ocnt = oddCount a\n let ans = min ecnt ocnt\n let e1 = ecnt - ans\n let o1 = ocnt - ans\n let a1 = ans + (o1 `div` 3)\n print(a1)"}, {"source_code": "main = do\n (n:as) <- fmap (map read . words) getContents\n print $ (let cnt1 = toInteger $ length $ filter odd as\n in if cnt1 <= (quot n 2) then cnt1\n else ((n - cnt1) + (quot (cnt1 - (n - cnt1))) 3))\n \n \n "}, {"source_code": "import System.IO -- \u0438\u043c\u043f\u043e\u0440\u0442 \u043c\u043e\u0434\u0443\u043b\u044f IO\nimport Data.List\nf :: [[Char]] -> Int\nf [] = 0\nf (x:xs) = if (mod (read x :: Int) 2 == 1) then (1 + (f xs))\n else (f xs)\nsplit :: Char -> String -> [[Char]]\nsplit _ [] = []\nsplit d l = uncurry (:) . fmap (split d . drop 1) . break (==d) $ l\ndel :: Int -> Int -> Int\ndel n m = div n m\nmain :: IO ()\nmain = do\n\tn <- getLine\n\tm <- getLine\n\tlet nech = length [x | (x,y)<- zip (split ' ' m) [1..],(mod (read x :: Int) 2) == 1];ch = length [x | (x,y)<- zip (split ' ' m) [1..], (mod (read x :: Int) 2) == 0];ans = min ch nech + w;w = h (nech - ch)\n\tprint (ans)\n where\n h n = if n < 1 then 0\n else del n 3\n\t--putStrLn $ show $ (read sx1 :: Int) + (read sx2 :: Int) -- \u043f\u0435\u0447\u0430\u0442\u0430\u0435\u043c \u0441\u0443\u043c\u043c\u0443 (\u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0432 \u0441\u0442\u0440\u043e\u043a\u0438 \u0432 Int)\n\t--putStrLn $ show $ n"}, {"source_code": "import Data.List (sort)\nmain = do\n (n:as) <- fmap (map read . words) getContents\n let oddcnt = length (filter (odd) as)\n print (if oddcnt <= (n - oddcnt) then (oddcnt) else (n - oddcnt + (div (oddcnt - n + oddcnt) 3)))"}], "negative_code": [{"source_code": "main = do\n (n:as) <- fmap (map read . words) getContents\n let e = length $ filter even as\n let o = n - e\n print $ if o < e then o else (e + (o-e) `div` 2)"}, {"source_code": "--ghc 7.10\n\nevenCount :: [Integer] -> Integer\nevenCount [] = 0\nevenCount (x:xs)\n | x `mod` 2 == 0 = 1 + evenCount xs\n | otherwise = evenCount xs\n \noddCount :: [Integer] -> Integer\noddCount [] = 0\noddCount (x:xs)\n | x `mod` 2 == 1 = 1 + oddCount xs\n | otherwise = oddCount xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let n = read str :: Integer\n str <- getLine\n let a = fmap (\\as -> read as :: Integer) (words str)\n let ecnt = evenCount a\n let ocnt = oddCount a\n let ans = ecnt + ((ocnt - ecnt) `div` 3)\n print(ans)"}, {"source_code": "--ghc 7.10\n\nevenCount :: [Integer] -> Integer\nevenCount [] = 0\nevenCount (x:xs)\n | x `mod` 2 == 0 = 1 + evenCount xs\n | otherwise = evenCount xs\n \noddCount :: [Integer] -> Integer\noddCount [] = 0\noddCount (x:xs)\n | x `mod` 2 == 1 = 1 + oddCount xs\n | otherwise = oddCount xs\n\nmain :: IO()\nmain = do\n str <- getLine\n let n = read str :: Integer\n str <- getLine\n let a = fmap (\\as -> read as :: Integer) (words str)\n let ecnt = evenCount a\n let ocnt = oddCount a\n print(min ecnt ocnt)"}], "src_uid": "61e6fd68d7568c599204130b102ea389"} {"source_code": "import Control.Applicative\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\n\n--process::String->Int->Int->Bool\n--process [] a b = a*b==1 \n--process [_] a b = a*b==1 \n--process (x1:x2:xs) a b | a*b==1 = True\n--\t | a==0 && x1=='A' && x2=='B' = or [process xs 1 b,process (x2:xs) a b]\n-- | b==0 && x1=='B' && x2=='A' = or [process xs a 1,process (x2:xs) a b]\n--\t\t | otherwise = process (x2:xs) a b \n \nprocess x | (all C.null [x3,x4]) = False\n\t | otherwise = True\n\twhere x1 = snd $ C.breakSubstring (C.pack \"AB\") x \n x2 = snd $ C.breakSubstring (C.pack \"BA\") x \n\t x3 = snd $ C.breakSubstring (C.pack \"BA\") $ C.drop 2 x1\n\t x4 = snd $ C.breakSubstring (C.pack \"AB\") $ C.drop 2 x2\n\t\nmain= do\n\tx<- C.getLine\t \n\tputStrLn $ if process x then \"YES\" else \"NO\"\n\t ", "positive_code": [{"source_code": "import Control.Arrow ((&&&))\nimport Data.Functor ((<$>))\nimport Data.List (isPrefixOf)\n\nmain :: IO ()\nmain = putStrLn <$> yesno =<< solve <$> getLine\n\nsolve :: String -> Bool\nsolve = faraway 2 . (listIndices 0 \"AB\" &&& listIndices 0 \"BA\")\n\nlistIndices :: Eq a => Int -> [a] -> [a] -> [Int]\nlistIndices _ _ [] = []\nlistIndices n xs yss@(_:ys) | xs `isPrefixOf` yss = n : listIndices (n + 1) xs ys\n | otherwise = listIndices (n + 1) xs ys\n\nfaraway :: Int -> ([Int], [Int]) -> Bool\nfaraway n (xs, ys) = not (null xs) && not (null ys) && (n <= abs (head xs - last ys) || n <= abs (last xs - head ys))\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Control.Applicative\nmain = interact $ merge Nothing Nothing Nothing Nothing . solve 0\nsolve i ('A':cs@('B':_)) = Left i : solve (i+1) cs\nsolve i ('B':cs@('A':_)) = Right i : solve (i+1) cs\nsolve i (c:cs) = solve (i+1) cs\nsolve _ _ = []\nmerge fa la fb lb (Left i:is) = merge (fa <|> Just i) (Just i) fb lb is\nmerge fa la fb lb (Right i:is) = merge fa la (fb <|> Just i) (Just i) is\nmerge fa la fb lb _ | liftA2 ((abs .) . (-)) fa lb > Just 1 = \"YES\"\n | liftA2 ((abs .) . (-)) la fb > Just 1 = \"YES\"\n | otherwise = \"NO\"\n"}, {"source_code": "import Data.List (isPrefixOf)\n\ncheck' :: String -> [String] -> Bool\ncheck' _ [] = True\ncheck' [] _ = False\ncheck' s both@(p:ps)\n | p `isPrefixOf` s = check' (drop 2 s) ps\n | otherwise = check' (tail s) both\n\n{-check' s subs-}\n {-| null subs = True-}\n {-| length s < 2 = False-}\n {-| (head subs) `isPrefixOf` s = check' (drop 2 s) (tail subs)-}\n {-| otherwise = check' (tail s) subs-}\n\ncheck :: String -> String\ncheck s\n | check' s [\"AB\", \"BA\"] || check' s [\"BA\", \"AB\"] = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n ans <- fmap check getLine\n putStrLn ans\n"}, {"source_code": "import Data.List (isPrefixOf)\n\ncheck' :: String -> [String] -> Bool\ncheck' s subs\n | null subs = True\n | null s = False\n | (head subs) `isPrefixOf` s = check' (drop 2 s) (tail subs)\n | otherwise = check' (tail s) subs\n\n{-check' _ [] = True-}\n{-check' [] _ = False-}\n{-check' s both@(p:ps)-}\n {-| p `isPrefixOf` s = check' (drop 2 s) ps-}\n {-| otherwise = check' (tail s) both-}\n\ncheck :: String -> String\ncheck s\n | check' s [\"AB\", \"BA\"] || check' s [\"BA\", \"AB\"] = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n ans <- fmap check getLine\n putStrLn ans\n"}, {"source_code": "main = interact $ p . (\\inp -> solve 'A' 'B' inp False || solve 'B' 'A' inp False)\n\np b = if b then \"YES\" else \"NO\"\n\nsolve :: Char -> Char -> [Char] -> Bool -> Bool\nsolve a b (x:y:xs) m\n | (m && x == b && y == a) = True\n | (not m && x == a && y == b) = solve a b xs (not m)\n | otherwise = solve a b (y : xs) m\nsolve _ _ _ _ = False\n"}, {"source_code": "main = do\n inp <- getLine\n putStrLn $ ans inp\n\nans inp = if findFirst inp \"AB\" \"BA\" || findFirst inp \"BA\" \"AB\"\n then \"YES\"\n else \"NO\"\n\nfindFirst (x:y:xs) str1 str2 = if [x,y] == str1\n then findSecond xs str2\n else findFirst (y:xs) str1 str2\nfindFirst _ _ _ = False\n\nfindSecond (b:a:bs) str = if [b,a] == str\n then True\n else findSecond (a:bs) str\nfindSecond _ _ = False\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Text as T\n\n\nab= T.pack \"AB\"\nba= T.pack \"BA\"\nnu= T.pack \"\"\n\n\ncheck n | (snd $ T.breakOn ba $ T.drop 2$ snd $ T.breakOn ab n) /=nu = True\n\t| (snd $ T.breakOn ab $ T.drop 2$ snd $ T.breakOn ba n) /=nu = True\n\t| otherwise = False\n\nmain = do\n\t \t\n\tn<- getLine \n\tputStrLn $ if check (T.pack n) then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\ts <- getLine\n\tputStrLn $ which \"YES\" \"NO\" $ solve s [ \"AB\", \"BA\" ] || solve s [ \"BA\", \"AB\" ]\n\nsolve _ [] = True\nsolve [] _ = False\nsolve [a] _ = False\nsolve s tt@(t:ts)\n\t| t `isPrefixOf` s = solve ( drop 2 s ) ts\n\t| otherwise = solve ( drop 1 s ) tt\n\n\n"}, {"source_code": "f :: String -> Bool\nf s =\n let chars = zip [0 ..] (zip s (tail s))\n l1 = [ i | (i, ('A', 'B')) <- chars ]\n l2 = [ i | (i, ('B', 'A')) <- chars ]\n in (not . null) [ (i, j) | i <- l1, j <- l2, abs (i-j) > 1 ]\n\nmain = interact $ \\x -> if f x then \"YES\" else \"NO\""}, {"source_code": "import Data.List (isPrefixOf)\n\ncheck :: String -> Bool\ncheck s = recur [\"AB\", \"BA\"] s || recur [\"BA\", \"AB\"] s\n where recur [] _ = True\n recur _ [] = False\n recur (p : ps) s\n | p `isPrefixOf` s = recur ps (drop (length p) s)\n | otherwise = recur (p : ps) (tail s)\n\nformat :: Bool -> String\nformat False = \"NO\"\nformat True = \"YES\"\n\nmain :: IO ()\nmain = putStrLn . format . check =<< getLine\n"}, {"source_code": "import Data.List (isInfixOf)\n\nsolve :: String -> Bool\nsolve ('A':'B':'A':cs) = isInfixOf \"AB\" cs || isInfixOf \"BA\" cs\nsolve ('B':'A':'B':cs) = isInfixOf \"AB\" cs || isInfixOf \"BA\" cs\nsolve ('A':'B':cs) = isInfixOf \"BA\" cs\nsolve ('B':'A':cs) = isInfixOf \"AB\" cs\nsolve (_:cs) = solve cs\nsolve [] = False\n\ndispl :: Bool -> String\ndispl True = \"YES\\n\"\ndispl False = \"NO\\n\"\n\nmain :: IO ()\nmain = interact (displ . solve)\n\n"}, {"source_code": "main :: IO()\nmain = putStrLn . solve =<< getLine\n\nsolve :: String -> String\nsolve s | solve' s False False = \"YES\"\n | otherwise = \"NO\"\n where\n solve' :: String -> Bool -> Bool -> Bool\n solve' _ True True = True\n solve' \"\" a b = a && b\n solve' ('A':'B':'A':ss) a b = (solve' ('A':ss) True b) || (solve' ss a True)\n solve' ('B':'A':'B':ss) a b = (solve' ('B':ss) a True) || (solve' ss True b)\n solve' ('A':'B':ss) a b = solve' ss True b\n solve' ('B':'A':ss) a b = solve' ss a True\n solve' (s:ss) a b = solve' ss a b"}, {"source_code": "main :: IO()\nmain = do\n a <- getLine\n let l1 = solveAB 1 a\n l2 = solveBA 1 a\n l3 = [ x-y | x<-l1 , y<-l2 , abs (x-y) >1]\n if l3 == []\n then putStrLn \"NO\"\n else putStrLn \"YES\"\n\nsolveAB _ (_:[]) = []\nsolveAB l (a:b:xs) = if and[a=='A',b=='B'] then l:solveAB (l+1) (b:xs) else solveAB (l+1) (b:xs)\n\nsolveBA _ (_:[]) = []\nsolveBA l (a:b:xs) = if and[a=='B',b=='A'] then l:solveBA (l+1) (b:xs) else solveBA (l+1) (b:xs)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- B.getLine\n\n let\n b1 = \"BA\" `B.isInfixOf` s && (\"AB\" `B.isInfixOf` a || \"AB\" `B.isInfixOf` (B.drop 2 b))\n where\n (a, b) = B.breakSubstring \"BA\" s\n\n b2 = \"AB\" `B.isInfixOf` s && (\"BA\" `B.isInfixOf` a || \"BA\" `B.isInfixOf` (B.drop 2 b))\n where\n (a, b) = B.breakSubstring \"AB\" s\n\n putStrLn $ if b1 || b2 then \"YES\" else \"NO\"\n"}, {"source_code": "answer s t 4 = True\nanswer [] t n =False \nanswer (s:ss) t 0 | s == (t !! 0) = answer ss t 1\n | otherwise = answer ss t 0\nanswer (s:ss) t 1 | s == (t !! 1) = answer ss t 2\n | s == (t !! 0) = answer ss t 1 \n | otherwise = answer ss t 0\nanswer (s:ss) t 2 | s == (t !! 2) = answer ss t 3\n | otherwise = answer ss t 2\nanswer (s:ss) t 3 | s == (t !! 3) = answer ss t 4\n | s == (t !! 2) = answer ss t 3\n | otherwise = answer ss t 2 \nmain = do\n s <- getLine\n putStrLn $ if (answer s \"ABBA\" 0) || (answer s \"BAAB\" 0) then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.head. lines\nsolve :: String->String\nsolve xs = if r1+r2>=2 && r1>0 && r2>0 then \"YES\" else \"NO\" \n where\n ([r1,r2],r3)=slv1 $ zip zp $ tail zp\n zp =zipWith (\\a b->a:b:[]) ('Z':xs) $ tail ('Z':xs)\nslv1 []=([0,0],1)\nslv1 xss = foldr (f) ([0,0],1) xss where\n f (a1,a2) ([b1,b2],b0) | b0>0 && ((a1,a2) == (\"AB\",\"BA\") || (a1,a2) == (\"BA\",\"AB\")) = ([b1+0.5,b2+0.5],-1)\n | b0>0 && a2 == \"AB\" = ([b1+1,b2],0)\n | b0>0 && a2 == \"BA\" = ([b1,b2+1],0)\n | otherwise = ([b1,b2],b0+1)"}], "negative_code": [{"source_code": "import Control.Arrow ((&&&))\nimport Data.Functor ((<$>))\nimport Data.List (isPrefixOf)\n\nmain :: IO ()\nmain = putStrLn <$> yesno =<< solve <$> getLine\n\nsolve :: String -> Bool\nsolve = not . nearBy 2 . (listIndices 0 \"AB\" &&& listIndices 0 \"BA\")\n\nlistIndices :: Eq a => Int -> [a] -> [a] -> [Int]\nlistIndices _ _ [] = []\nlistIndices n xs yss@(_:ys) | xs `isPrefixOf` yss = n : listIndices (n + 1) xs ys\n | otherwise = listIndices (n + 1) xs ys\n\nnearBy :: Int -> ([Int], [Int]) -> Bool\nnearBy n (xs, ys) = null xs || null ys || n > abs (head xs - last ys) || n > abs (last xs - head ys)\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "import Data.List\n\ncheck' :: String -> Int -> String -> Bool\ncheck' s idx sub\n | idx + 1 >= length s = False\n | sub `isInfixOf` fst && (reverse sub) `isInfixOf` snd = True\n | otherwise = False\n where (fst, snd) = splitAt idx s\n\ncheck :: String -> String\ncheck s\n | check' s 2 \"AB\" || check' s 2 \"BA\" = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n ans <- fmap check getLine\n putStrLn ans\n"}, {"source_code": "import Data.List (isPrefixOf)\n\ncheck' :: String -> Int -> String -> Bool\ncheck' s idx sub\n | idx + 1 >= length s = False\n | sub `isPrefixOf` fst && (reverse sub) `isPrefixOf` snd = True\n | otherwise = check' s (idx + 1) sub\n where (fst, snd) = splitAt idx s\n\ncheck :: String -> String\ncheck s\n | check' s 2 \"AB\" || check' s 2 \"BA\" = \"YES\"\n | otherwise = \"NO\"\n\nmain = do\n ans <- fmap check getLine\n putStrLn ans\n"}, {"source_code": "import Control.Monad\nimport Data.List\nxor :: Bool -> Bool -> Bool\nxor a b = a /= b\n\nt = (zip `ap` tail)\nisSubStr = (`elem` [('A','B'), ('B','A')])\nsolve = check . t . map isSubStr . t\n\ncheck l = not ((True, True) `elem` l) &&\n (False, True) `elem` l &&\n (True, False) `elem` l\n\np True = \"YES\"\np False = \"NO\"\nmain = interact $ p . solve\n"}, {"source_code": "import Control.Monad\nsolve = foldr (&&) True . map (uncurry (&&)) . (zip `ap` tail) . map (`elem` [('A','B'), ('B','A')]) . (zip `ap` tail)\n\np True = \"YES\"\np False = \"NO\"\nmain = interact $ p . solve"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char \nt = (zip `ap` tail)\nisSubStr = (`elem` [('A','B'), ('B','A')])\nsolve = check . t . map isSubStr . t\n\ncheck :: [(Bool, Bool)] -> Bool\ncheck l = (case elemIndex (False, True) l of\n Just _ -> case elemIndex (True, False) l of\n Just _ -> True\n Nothing -> False\n Nothing -> False)\n || any (> 1) ((zipWith (\\a b -> (abs (a - b))) `ap` tail)\n (elemIndices (True, True) l))\n \np True = \"YES\"\np False = \"NO\"\nmain = interact $ p . solve"}, {"source_code": "import Control.Monad\nsolve = not . foldr (||) False . map (uncurry (&&)) . (zip `ap` tail) . map (`elem` [('A','B'), ('B','A')]) . (zip `ap` tail)\n\np True = \"YES\"\np False = \"NO\"\nmain = interact $ p . solve\n"}, {"source_code": "import Control.Monad\nsolve = any (uncurry (&&)) . (zip `ap` tail) . map (`elem` [('A','B'), ('B','A')]) . (zip `ap` tail)\n\np True = \"YES\"\np False = \"NO\"\nmain = interact $ p . solve\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\n \nprocess [] a b = if a*b==1 then \"YES\" else \"NO\"\nprocess [_] a b = if a*b==1 then \"YES\" else \"NO\"\nprocess (x1:x2:xs) a b | a*b==1 = \"YES\"\n\t | x1=='A' && x2=='B' = process xs 1 b\n | x1=='B' && x2=='A' = process xs a 1\n\t\t | otherwise = process (x2:xs) a b \n \n \nmain= do\n\tx<-getLine\n\tputStrLn $ process x 0 0 \n\t "}, {"source_code": "main :: IO ()\nmain = interact (format . solve)\n\nnewtype State = State Int\n deriving (Show, Eq)\n\nstep :: State -> Char -> State\nstep (State 0) 'A' = State 1\nstep (State 0) _ = State 0\nstep (State 1) 'B' = State 2\nstep (State 1) _ = State 0\nstep (State 2) 'B' = State 3\nstep (State 2) _ = State 2\nstep (State 3) 'A' = State 4\nstep (State 3) _ = State 2\nstep (State 4) _ = State 4\n\nstep' :: State -> Char -> State\nstep' (State 0) 'B' = State 1\nstep' (State 0) _ = State 0\nstep' (State 1) 'A' = State 2\nstep' (State 1) _ = State 0\nstep' (State 2) 'A' = State 3\nstep' (State 2) _ = State 2\nstep' (State 3) 'B' = State 4\nstep' (State 3) _ = State 2\nstep' (State 4) _ = State 4\n\nrun :: (State -> Char -> State) -> String -> State\nrun step = foldl step (State 0)\n\nsolve :: String -> Bool\nsolve s = (run step s) == (State 4) || (run step' s) == (State 4)\n\nformat :: Bool -> String\nformat False = \"NO\"\nformat True = \"YES\"\n"}, {"source_code": "main = do\n\ta <- getLine\n\tif solve a == 2\n\t\tthen putStrLn \"YES\"\n\t\telse putStrLn \"NO\"\n\t\t\nsolve \"\" = 0\nsolve ('A':'B':xs) = 1 + solve xs\nsolve ('B':'A':xs) = 1 + solve xs\nsolve (x:xs) = solve xs\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n f [] = []\n f ('A':'B':s) = s\n f (c:s) = c:(f s)\n\n g [] = []\n g ('B':'A':s) = s\n g (c:s) = c:(f s)\n\n b = \"AB\" `isInfixOf` s && \"BA\" `isInfixOf` (f s) || \"BA\" `isInfixOf` s && \"AB\" `isInfixOf` (g s)\n\n putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n f [] = []\n f ('A':'B':s) = s\n f (c:s) = c:(f s)\n\n b = \"AB\" `isInfixOf` s && \"BA\" `isInfixOf` (f s)\n\n putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- B.getLine\n\n let\n b1 = \"AB\" `B.isInfixOf` a || \"AB\" `B.isInfixOf` (B.drop 2 b)\n where\n (a, b) = B.breakSubstring \"BA\" s\n\n b2 = \"BA\" `B.isInfixOf` a || \"BA\" `B.isInfixOf` (B.drop 2 b)\n where\n (a, b) = B.breakSubstring \"AB\" s\n\n putStrLn $ if b1 || b2 then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n s <- getLine\n\n let\n f [] = []\n f ('A':'B':s) = s\n f (c:s) = c:(f s)\n\n g [] = []\n g ('B':'A':s) = s\n g (c:s) = c:(g s)\n\n b = \"AB\" `isInfixOf` s && \"BA\" `isInfixOf` (f s) || \"BA\" `isInfixOf` s && \"AB\" `isInfixOf` (g s)\n\n putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "answer::String -> String\nanswer a = btos ((smatch \"BA\" a)-(ematch \"AB\" a) >= 2 || (smatch \"AB\" a)-(ematch \"BA\" a) > 2)\nsmatch::String -> String -> Int\nsmatch a b= smatch0 a b 0\nsmatch0::String -> String -> Int -> Int \nsmatch0 a b index | lb < la = -1\n | (take la b) == a = index\n | otherwise = smatch0 a (tail b) (index + 1)\n where la = length a\n lb = length b\nematch::String -> String -> Int \nematch a b | lb < la = -1\n | (drop (lb-la) b) == a = (lb - la)\n | otherwise = ematch a (init b)\n where la = length a\n lb = length b\nbtos::Bool -> String\nbtos True = \"YES\"\nbtos False = \"NO\" \nmain = do\n w <- getLine\n putStrLn $ answer w\n"}, {"source_code": "answer s t 4 = True\nanswer [] t n =False \nanswer (s:ss) t 0 | s == (t !! 0) = answer ss t 1\n | otherwise = answer ss t 0\nanswer (s:ss) t 1 | s == (t !! 1) = answer ss t 2\n | otherwise = answer ss t 0\nanswer (s:ss) t 2 | s == (t !! 2) = answer ss t 3\n | otherwise = answer ss t 2\nanswer (s:ss) t 3 | s == (t !! 3) = answer ss t 4\n | otherwise = answer ss t 2 \nmain = do\n s <- getLine\n putStrLn $ if (answer s \"ABBA\" 0) || (answer s \"BAAB\" 0) then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.head. lines\nsolve :: String->String\nsolve xs = if r1+r2>=2 && r1>0 && r3>0 then \"YES\" else \"NO\" where\n ([r1,r2],r3)=slv1 $ zip zp $ tail zp\n zp =zipWith (\\a b->a:b:[]) xs $ tail xs \nslv1 xss = foldr (f) ([0,0],1) xss where\n f (a1,a2) ([b1,b2],b0) | b0==1 && ((a1,a2) == (\"AB\",\"BA\") || (a1,a2) == (\"BA\",\"AB\")) = ([b1+0.5,b2+0.5],0)\n | b0==1 && a1 == \"AB\" = ([b1+1,b2],1)\n | b0==1 && a2 == \"AB\" = ([b1+1,b2],0)\n | b0==1 && a1 == \"BA\" = ([b1,b2+1],1)\n | b0==1 && a2 == \"BA\" = ([b1,b2+1],0)\n | otherwise = ([b1,b2],1)"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve.head. lines\nsolve :: String->String\nsolve xs = if r1+r2>=2 && r1>0 && r2>0 then \"YES\" else \"NO\" \n where\n ([r1,r2],r3)=slv1 $ zip zp $ tail zp\n zp =zipWith (\\a b->a:b:[]) ('Z':xs) $ tail ('Z':xs)\nslv1 []=([0,0],1)\nslv1 xss = foldr (f) ([0,0],1) xss where\n f (a1,a2) ([b1,b2],b0) | b0==1 && ((a1,a2) == (\"AB\",\"BA\") || (a1,a2) == (\"BA\",\"AB\")) = ([b1+0.5,b2+0.5],0)\n | b0==1 && a2 == \"AB\" = ([b1+1,b2],0)\n | b0==1 && a2 == \"BA\" = ([b1,b2+1],0)\n | otherwise = ([b1,b2],1)"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.head. lines\nsolve :: String->String\nsolve xs = if r1+r2>=2 && r1>0 && r2>0 then \"YES\" else \"NO\" \n where\n ([r1,r2],r3)=slv1 $ zip zp $ tail zp\n zp =zipWith (\\a b->a:b:[]) xs $ tail xs \nslv1 []=([0,0],1)\nslv1 xss = foldr (f) ([0,0],1) xss where\n f (a1,a2) ([b1,b2],b0) | b0==1 && ((a1,a2) == (\"AB\",\"BA\") || (a1,a2) == (\"BA\",\"AB\")) = ([b1+0.5,b2+0.5],0)\n | b0==1 && a1 == \"AB\" = ([b1+1,b2],0)\n | b0==1 && a2 == \"AB\" = ([b1+1,b2],1)\n | b0==1 && a1 == \"BA\" = ([b1,b2+1],0)\n | b0==1 && a2 == \"BA\" = ([b1,b2+1],1)\n | otherwise = ([b1,b2],1)"}], "src_uid": "33f7c85e47bd6c83ab694a834fa728a2"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\n-- import Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\n-- import Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n-- import Data.HashMap.Strict (HashMap)\n-- import qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nnumLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()\nnumLoop start end f = if start <= end then go start else return ()\n where\n go !x | x == end = f x\n | otherwise = f x >> go (x+1)\n\n{-# INLINE numLoop #-}\n\nnumLoopState :: (Num a, Eq a, Monad m) => a -> a -> b -> (b -> a -> m b) -> m b\nnumLoopState start end initState f = go start initState\n where\n go !x !state | x == end = f state x\n | otherwise = f state x >>= go (x+1)\n\n\n{-# INLINE numLoopState #-}\n\nmain = do\n n <- readLn\n\n inp <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getContents\n let\n (a, vs) = splitAt (n*n) inp\n a' = listArray ((1, 1), (n, n)) a :: UArray (Int, Int) Int\n vs' = listArray (1, n) vs :: UArray Int Int\n\n b :: IOUArray (Int) Int <- newArray_ (0, n*n-1)\n\n numLoop 1 n $ \\i -> numLoop 1 n $ \\j ->\n writeArray b ((i-1)*n + j-1) $ a'!(vs'!(n-i+1), vs'!(n-j+1))\n\n rs <- numLoopState 0 (n-1) [] $ \\rs w -> do\n numLoop 0 (n-1) $ \\u -> do\n d1 <- readArray b (u*n + w)\n numLoop 0 (n-1) $ \\v -> do\n d <- readArray b (u*n + v)\n d2 <- readArray b (w*n + v)\n let d' = d1+d2\n\n when (d' < d) $ writeArray b (u*n + v) d'\n\n r <- numLoopState 0 w 0 $ \\s i -> do\n v <- numLoopState 0 w 0 $ \\s j -> do\n v <- readArray b (i*n + j)\n return $ s + fromIntegral v\n return $ s + v\n\n return $ r:rs\n\n putStrLn $ unwords $ map show $ rs\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nfoldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\nfoldM' _ z [] = return z\nfoldM' f z (x:xs) = do\n z' <- f z x\n z' `seq` foldM' f z' xs\nmain = do\n n <- readLn\n\n inp <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getContents\n let\n (a, vs) = splitAt (n*n) inp\n a' = listArray ((1, 1), (n, n)) a :: UArray (Int, Int) Int\n vs' = listArray (1, n) vs :: UArray Int Int\n\n b :: IOUArray (Int, Int) Int <- newArray_ ((1, 1), (n, n))\n forM_ [1..n] $ \\i -> forM_ [1..n] $ \\j ->\n writeArray b (i, j) $ a'!(vs'!(n-i+1), vs'!(n-j+1))\n\n let\n {-# INLINE total #-}\n total k = f 1 0\n where\n f i !s\n | i > k = return s\n | otherwise = do\n let\n g j !s\n | j > k = return s\n | otherwise = readArray b (i, j) >>= \\v -> g (j+1) (s + fromIntegral v)\n\n g 1 0 >>= \\v -> f (i+1) (s+v)\n\n\n loop1 w rs\n | w > n = return rs\n | otherwise = do\n let\n loop2 u\n | u > n = return ()\n | otherwise = do\n d1 <- readArray b (u, w)\n let\n loop3 v\n | v > n = return ()\n | otherwise = do\n d <- readArray b (u, v)\n\n d2 <- readArray b (w, v)\n let d' = d1+d2\n\n when (d' < d) $ writeArray b (u, v) d'\n\n loop3 (v+1)\n\n loop3 1\n loop2 (u+1)\n\n loop2 1\n r <- total w\n loop1 (w+1) (r:rs)\n\n rs <- loop1 1 []\n\n putStrLn $ unwords $ map show $ rs\n"}], "negative_code": [], "src_uid": "46920a192a8f5fca0f2aad665ba2c22d"} {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\n\n------\n\nmapFst :: (a -> c) -> (a, b) -> (c, b)\nmapFst f (x, y) = (f x, y)\n\nmapSnd :: (b -> c) -> (a, b) -> (a, c)\nmapSnd f (x, y) = (x, f y)\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\npop :: MonadState [r] m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadState [r] m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadState [B.ByteString] m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadState [B.ByteString] m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\ndropBackWhile :: (Char -> Bool) -> B.ByteString -> B.ByteString\ndropBackWhile p = B.reverse . B.dropWhile p . B.reverse\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map (dropBackWhile isSpace) . B.lines\n\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n n <- popInt\n B.unlines <$> replicateM n solve\n\n\nsolve :: Hopper B.ByteString B.ByteString\nsolve = B.pack . map f . zip (cycle [True, False]) . B.unpack <$> popJust\n where\n f (True, 'a') = 'b'\n f (True, _) = 'a'\n f (False, 'z') = 'y'\n f (False, _) = 'z'\n", "positive_code": [{"source_code": "process :: Bool -> String -> String\r\nprocess _ [] = []\r\nprocess True (h : t) = (if h == 'a' then 'b' else 'a') : process False t\r\nprocess False (h : t) = (if h == 'z' then 'y' else 'z') : process True t\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (process True) . tail . lines)\r\n"}, {"source_code": "module Main where\n\nsolve :: String -> String\nsolve = map f . zip [0..]\n where f (i,l) | even i = if l == 'a' then 'b' else 'a'\n | odd i = if l == 'z' then 'y' else 'z'\n\nmain = interact $ unlines . map solve . tail . lines\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nfunc :: Bool -> String -> String\nfunc _ [] = []\nfunc _ ['\\r'] = []\nfunc True ('a' : cs) = 'b' : func False cs\nfunc True (c : cs) = 'a' : func False cs\nfunc False ('z' : cs) = 'y' : func True cs\nfunc False (c : cs) = 'z' : func True cs\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n s <- C.unpack <$> C.getLine\n C.putStrLn $ C.pack $ func True s\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nbest :: P.ByteString\nbest = P.cycle $ P.pack \"az\"\n\nstep :: Char -> Char -> Char\nstep x y\n | x /= y = x\n | x == 'a' = 'b'\n | otherwise = 'y'\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ readLine >>= (lift . putStrLn . P.zipWith step best)\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\n\n------\n\nmapFst :: (a -> c) -> (a, b) -> (c, b)\nmapFst f (x, y) = (f x, y)\n\nmapSnd :: (b -> c) -> (a, b) -> (a, c)\nmapSnd f (x, y) = (x, f y)\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\npop :: MonadState [r] m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadState [r] m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadState [B.ByteString] m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadState [B.ByteString] m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map (B.dropWhile isSpace) . B.lines\n\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n n <- popInt\n B.unlines <$> replicateM n solve\n\n\nsolve :: Hopper B.ByteString B.ByteString\nsolve = B.pack . map f . zip (cycle [True, False]) . B.unpack <$> popJust\n where\n f (True, 'a') = 'b'\n f (True, _) = 'a'\n f (False, 'z') = 'y'\n f (False, _) = 'z'\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts #-}\n\nimport Control.Monad\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\n\n------\n\nmapFst :: (a -> c) -> (a, b) -> (c, b)\nmapFst f (x, y) = (f x, y)\n\nmapSnd :: (b -> c) -> (a, b) -> (a, c)\nmapSnd f (x, y) = (x, f y)\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\npop :: MonadState [r] m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadState [r] m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadState [B.ByteString] m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadState [B.ByteString] m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . B.lines\n\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n n <- popInt\n B.unlines <$> replicateM n solve\n\n\nsolve :: Hopper B.ByteString B.ByteString\nsolve = B.pack . map f . zip (cycle [True, False]) . B.unpack <$> popJust\n where\n f (True, 'a') = 'b'\n f (True, _) = 'a'\n f (False, 'z') = 'y'\n f (False, _) = 'z'\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nfunc :: Bool -> String -> String\nfunc _ [] = []\nfunc True ('a' : cs) = 'b' : func False cs\nfunc True (c : cs) = 'a' : func False cs\nfunc False ('z' : cs) = 'y' : func True cs\nfunc False (c : cs) = 'z' : func True cs\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n s <- C.unpack <$> C.getLine\n C.putStrLn $ C.pack $ func True s\n"}], "src_uid": "c02357c4d959e300f970f66f9b3107eb"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >> getLine >>= print.solve.map read.words >> test (n - 1)\n\nsolve as\n | any (== 0) as = (length $ filter (== 0) as) + (solve $ map (\\x -> if x == 0 then 1 else x) as)\n | sum as == 0 = 1\n | otherwise = 0\n", "positive_code": [{"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get\n a <- replicateM n get\n putln $ f2 a n\n\nf2 :: [Int] -> Int -> Int\nf2 a n = let asum = foldl (+) 0 a\n in\n let a0count = foldl (\\s c -> if c == 0 then s + 1 else s) 0 a\n in\n let amcount = foldl (\\s c -> if c == -1 then s + 1 else s) 0 a\n in\n if asum + a0count == 0 then\n if amcount == n then\n a0count + 2\n else\n a0count + 1\n else\n a0count"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase= do\n\t\tgetLine\n\t\ts<- map read <$> words <$> getLine ::IO [Int]\n\t\tlet z = length $ filter (==0) s\n\t\tlet su = sum s\n\t\tprint $ if su +z ==0 then z+1 else z\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\n\n\t\t\n\n"}, {"source_code": "--ghc 7.10\n\nimport Data.List(groupBy)\n\nnonZero :: [Int] -> Int\nnonZero a =\n if (n + sum a) == 0\n then n+1\n else n\n where n = length . filter (==0) $ a\n\nprocess :: Int -> IO ()\nprocess 0 = return ()\nprocess t = do\n line1 <- getLine\n line2 <- getLine\n let a = map read . words $ line2\n print $ nonZero a\n process (t-1)\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n process t"}, {"source_code": "import Data.List as L\n\nsolve :: [Int] -> Int\nsolve xs = stepsToRemoveZero + if sumAfterZeroRemoval == 0 then 1 else 0\n where stepsToRemoveZero = length $ filter (== 0) xs\n sumAfterZeroRemoval = (sum xs) + stepsToRemoveZero\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:as:others) = [(n, as)] ++ groupByTwo others\n\nparse :: (String, String) -> String\nparse (_, as) = show $ solve as'\n where as' = map (\\x -> read x :: Int) $ words as\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByTwo . tail . lines)\n"}, {"source_code": "import Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\nroutine :: IO ()\nroutine = do\n _ <- getLine\n as <- (map read. words) <$> getLine\n print $ solve as\n\n\nsolve :: [Int] -> Int\nsolve xs = if nsum ==0 then nuller +1 else nuller\n where\n nsum = summe + nuller\n (summe,nuller) = foldr bin acc xs\n bin x (sm,zs) = if x==0 then (sm,zs+1) else (sm+x,zs)\n acc = (0,0)\n"}], "negative_code": [], "src_uid": "1ffb08fe61cdf90099c82162b8353b1f"} {"source_code": "-- Codeforces 549A\n\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map read . words) getLine\n getContents >>= print . solve [(i, j) | i <- [0..n-2], j <- [0..m-2]] . lines -- enumerate all positions.\n\nsolve :: [(Int, Int)] -> [String] -> Int\nsolve [] _ = 0\nsolve ((i,j):xs) mat = check + (solve xs mat) where check = if sort [mat!!i!!j, mat!!i!!(j+1), mat!!(i+1)!!j, mat!!(i+1)!!(j+1)] == \"acef\" then 1 else 0\n\n", "positive_code": [{"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . tail . lines =<< getContents\n\nsolve :: [String] -> Int\nsolve (a:b:s) = (count (zips a b)) + (solve (b:s))\nsolve _ = 0\n\nzips :: String -> String -> String\nzips \"\" \"\" = \"\"\nzips (a:as) (b:bs) = (a:b:(zips as bs))\n\ncount :: String -> Int\ncount (a:b:c:d:s) | sort [a,b,c,d] == sort \"face\" = 1 + (count (c:d:s))\n | otherwise = count (c:d:s)\ncount _ = 0"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- map read . words <$> getLine\n a <- replicateM n getLine\n\n let check (a, b) (c, d) = sort [a, b, c, d] == \"acef\"\n\n print $ length $ filter id $ [check p q | [x, y] <- map (take 2) (init (init (tails a))), [p, q] <- map (take 2) (init (init (tails (zip x y))))]\n"}, {"source_code": "import Data.List \n\ndetect i [] _ = i\ndetect i _ [] = i\ndetect i [_] _ = i\ndetect i _ [_] = i\ndetect i (a:b:as) (c:d:cs) = detect (i + if sort [a,b,c,d] == \"acef\" then 1 else 0) (b:as) (d:cs) \n\nsolve i [a] = i\nsolve i (a:b:as) = solve (i + detect 0 a b) (b:as) \n \nmain = interact $ show . solve 0 . tail . lines \n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain =\n interact $ show . solve . tail . lines\n\nsolve :: [String] -> Int\nsolve lst =\n let n = length lst\n m = length $ head lst\n getSquare :: Int -> Int -> String\n getSquare i j =\n [(lst !! k) !! l | k <- [i, min (i+1) (n-1)], l <- [j, min (j+1) (m-1)]]\n isSquare :: String -> Bool\n isSquare str =\n sort str == \"acef\"\n in length $ filter isSquare $ [getSquare i j | i <- [0..n-1], j <- [0..m-1]]\n"}, {"source_code": "import Control.Arrow ((&&&), (***))\nimport Data.Functor ((<$>))\nimport Data.List (sort)\n\nmain :: IO ()\nmain = print =<< solve <$> (tail <$> lines <$> getContents)\n\nsolve :: [String] -> Int\nsolve xs = length . filter (==\"acef\") . concatMap (map (sort . uncurry (++) . (unTuple *** unTuple))\n . uncurry zip . (uncurry zip . (id &&& tail) *** uncurry zip . (id &&& tail))) $ zip xs (tail xs)\n\nunTuple :: (a, a) -> [a]\nunTuple (a, b) = [a, b]\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nsolve1 ((a,b) : (c,d) : _) = if sort [a,b,c,d] == sort \"face\" then 1 else 0\nsolve1 _ = 0\n\nsolver (x:y:_) = sum $ map solve1 (tails (zip x y))\nsolver _ = 0\n\nsolve :: [String] -> Integer\nsolve l = sum $ map solver (tails l)\n\nmain = interact $ unlines . return . show . solve . tail . lines\n"}, {"source_code": "import Data.List (sort)\n\ntype Face = ((Char, Char), (Char, Char))\n\nparse :: String -> [String]\nparse = tail . lines\n\nisFace :: Face -> Bool\nisFace ((a, b), (c, d)) = (sort [a, b, c, d]) == \"acef\"\n\nmkFaces :: [String] -> [Face]\nmkFaces = concat . pairWith zip . map (pairWith (,))\n where pairWith f a = zipWith f a (tail a)\n\nsolve :: [String] -> Int\nsolve = length . filter isFace . mkFaces\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}], "negative_code": [], "src_uid": "742e4e6ca047da5f5ebe5d854d6a2024"} {"source_code": "import Control.Monad ( guard, replicateM_, forM_, when )\r\nimport Data.Bits ( Bits(xor) )\r\nimport Data.IORef ( newIORef, readIORef, writeIORef )\r\nimport Data.List ( unfoldr )\r\nimport Data.Maybe ( fromJust )\r\nimport System.IO ( hFlush, stdout )\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readInts\r\n done <- newIORef False\r\n forM_ [0..n - 1] $ \\i -> do\r\n done' <- readIORef done\r\n if done' then return ()\r\n else do\r\n let j = if i == 0 then i else i `xor` (i - 1)\r\n print j\r\n hFlush stdout\r\n r <- readInt\r\n guard (r /= -1)\r\n when (r == 1) $ writeIORef done True\r\n readIORef done >>= guard\r\n\r\nreadInt :: IO Int\r\nreadInt = fst . fromJust . C.readInt <$> C.getLine \r\n\r\nreadInts :: IO [Int]\r\nreadInts = unfoldr (C.readInt . C.dropWhile (== ' ')) <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readInt\r\n replicateM_ t solve\r\n", "positive_code": [{"source_code": "import Control.Monad ( guard, replicateM_, forM_, when )\r\nimport Data.Bits ( Bits(xor) )\r\nimport Data.IORef ( newIORef, readIORef, writeIORef )\r\nimport Data.Maybe ( fromJust )\r\nimport System.IO ( hFlush, stdout )\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readInts\r\n done <- newIORef False\r\n forM_ [0..n - 1] $ \\i -> do\r\n done' <- readIORef done\r\n if done' then return ()\r\n else do\r\n let j = if i == 0 then i else i `xor` (i - 1)\r\n C.putStrLn $ C.pack $ show j\r\n hFlush stdout\r\n r <- readInt\r\n guard (r /= -1)\r\n when (r == 1) $ writeIORef done True\r\n readIORef done >>= guard\r\n\r\nparseInt :: C.ByteString -> Int\r\nparseInt = fst . fromJust . C.readInt\r\n\r\nreadInt :: IO Int\r\nreadInt = parseInt <$> C.getLine \r\n\r\nreadInts :: IO [Int]\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readInt\r\n replicateM_ t solve\r\n"}], "negative_code": [{"source_code": "import Control.Monad ( replicateM_, guard, when )\r\nimport Data.Bits ( Bits(xor) )\r\nimport System.IO ( hFlush, stdout )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, k] <- readMany :: IO [Int]\r\n let go :: Int -> IO ()\r\n go i = do\r\n let j = i `xor` (i - 1)\r\n print j\r\n hFlush stdout\r\n r <- readLn :: IO Int\r\n guard (r /= -1)\r\n when (r == 0) $ go (i + 1)\r\n go 1\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "src_uid": "ec77fc5674681d20bbaf9d903134b015"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ print\n\nsolve = do\n\tn <- readInt\n\tss <- replicateM n getLine\n\tlet\n\t\tls = map length ss\n\t\tzeros = length $ filter ( == '0' ) $ concat ss\n\t\tones = sum ls - zeros\n\t\tpairs = ( zeros `div` 2 ) + ( ones `div` 2 )\n\treturn $ length $ takeWhile ( <= pairs ) $ scanl1 (+) $ sort $ map ( `div` 2 ) ls", "positive_code": [{"source_code": "import Data.List\nimport Numeric\n\n(|>) = flip (.)\n\nint :: String -> Int\nint x = fst $ readDec x !! 0\n\nints :: String -> [Int]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> map show\n |> unlines\n\nsolverLoop :: [String] -> [Int]\nsolverLoop (ts:xs) = go t xs\n where\n t = int ts\n go 0 _ = []\n go t (nStr:xs) =\n solve (take n xs) : go (t - 1) (drop n xs)\n where\n n = int nStr\n\nsolve :: [String] -> Int\nsolve xs = go lengths counts1 counts0\n where\n counts1 = sum $ map (count '1') xs\n counts0 = sum $ map (count '0') xs\n lengths = sort $ map length xs\n go [] _ _ = 0\n go (x:xs) c1 c0\n | x `mod` 2 == 0\n && ec1 + ec0 >= x\n = 1 + go xs\n (c1 - (min ec1 x))\n (c0 - (min ec0 (x - (min ec1 x))))\n | x `mod` 2 == 1\n && c1 + c0 >= x\n = 1 + if c1 `mod` 2 == 1\n then go xs (c1 - (min c1 x)) (c0 - (x - (min c1 x)))\n else go xs (c1 - (min c1 (x-1))) (c0 - (x - (min c1 (x-1))))\n | otherwise = 0\n where\n ec1 = (c1 - c1 `mod` 2)\n ec0 = (c0 - c0 `mod` 2)\n\ncount x = length . filter (== x)\n"}, {"source_code": "import Data.List\nimport Numeric\n\n(|>) = flip (.)\n\nint :: String -> Int\nint x = fst $ readDec x !! 0\n\nints :: String -> [Int]\nints = map int . words\n\nmain = interact $\n lines\n |> solverLoop\n |> map show\n |> unlines\n\nsolverLoop :: [String] -> [Int]\nsolverLoop (ts:xs) = go t xs\n where\n t = int ts\n go 0 _ = []\n go t (nStr:xs) =\n solve (take n xs) : go (t - 1) (drop n xs)\n where\n n = int nStr\n\nsolve :: [String] -> Int\nsolve xs = length\n $ takeWhile (<= (counts1 `div` 2 + counts0 `div` 2))\n $ scanl1 (+)\n $ sort $ map ((`div` 2) . length) xs\n where\n counts1 = sum $ map (count '1') xs\n counts0 = sum $ map (count '0') xs\n\ncount x = length . filter (== x)\n"}], "negative_code": [], "src_uid": "3b8678d118c90d34c99ffa9259cc611f"} {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype DpState = (Maybe Int, Maybe Int, Maybe Int, Maybe Int)\n\nmaybeMaximum :: [Maybe Int] -> Maybe Int\nmaybeMaximum = foldr max Nothing\n\ndpStateStep :: DpState -> Char -> DpState\ndpStateStep (a0, a1, a2, a3) '[' = (maybeMaximum [a0, Just 1], a1, a2, a3)\ndpStateStep (a0, a1, a2, a3) ':' = (a0, maybeMaximum [(+1) <$> a0, a1], maybeMaximum [(+1) <$> a1, a2], a3)\ndpStateStep (a0, a1, a2, a3) '|' = (a0, (+1) <$> a1, a2, a3)\ndpStateStep (a0, a1, a2, a3) ']' = (a0, a1, a2, maybeMaximum [(+1) <$> a2, a3])\ndpStateStep dpState _ = dpState\n\nsolve :: B8.ByteString -> Int\nsolve str = fromMaybe (-1) answer\n where \n (_, _, _, answer) = B8.foldl' dpStateStep (Nothing, Nothing, Nothing, Nothing) str\n\nmain :: IO ()\nmain = do\n str <- B8.getLine\n printf \"%d\" $ solve str", "positive_code": [{"source_code": "main = interact f\n\nf s = (case f0 s of\n Just i -> show (i + 4)\n Nothing -> \"-1\") ++ \"\\n\"\n\nf0 ('[':s) = f1 s\nf0 (_:s) = f0 s\nf0 [] = Nothing\n\nf1 (':':s) = f2 s\nf1 (_:s) = f1 s\nf1 [] = Nothing\n\nf2 s = f3 Nothing 0 s\n\nf3 prev score ('|':s) = f3 prev (score + 1) s\nf3 prev score (':':s) = case f4 score s of\n Just (i, j, s) -> f3 (Just i) j s\n Nothing -> prev\nf3 prev score (_:s) = f3 prev score s\nf3 prev _ [] = prev\n\nf4 score s = f5 score score s\n\nf5 i j ('|':s) = f5 i (j + 1) s\nf5 i j (']':s) = Just (i, j, s)\nf5 i j (':':s) = f5 j j s\nf5 i j (_:s) = f5 i j s\nf5 _ _ [] = Nothing\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nsolve [] = -1\nsolve ('[':s) = solve2 $ s\nsolve (x:s) = solve s\n\nsolve2 [] = -1\nsolve2 (':':s) = solve3 $ reverse s\nsolve2 (x:s) = solve2 s\n\nsolve3 [] = -1\nsolve3 (']':s) = solve4 s\nsolve3 (x:s) = solve3 s\n\nsolve4 [] = -1\nsolve4 (':':s) = solve5 s\nsolve4 (x:s) = solve4 s\n\nsolve5 [] = 4\nsolve5 ('|':s) = 1 + solve5 s\nsolve5 (x:s) = solve5 s\n\nmain = do\n s <- getLine\n print $ solve s"}, {"source_code": "-- Educational Codeforces Round #58 (B), Contest 1101, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n print $ fromMaybe (-1) $ query s\n\nquery :: BS.ByteString -> Maybe Int\nquery xs0 = do\n let xs1 = BS.dropWhile (/='[') xs0\n xs2 = BS.dropWhile (/=':') xs1\n guard $ not $ BS.null xs2\n let (xs3,_) = BS.spanEnd (/= ']') $ BS.tail xs2\n (xs4,_) = BS.spanEnd (/=':') $ xs3\n guard $ not $ BS.null xs4\n let xs5 = BS.init xs4\n return $ (4+) $ length $ BS.elemIndices '|' xs5\n"}], "negative_code": [{"source_code": "-- Educational Codeforces Round #58 (B), Contest 1101, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n s <- BS.getLine\n print $ fromMaybe (-1) $ query s\n\nquery :: BS.ByteString -> Maybe Int\nquery xs0 = do\n let xs1 = BS.dropWhile (/='[') xs0\n xs2 = BS.dropWhile (/=':') xs1\n guard $ not $ BS.null xs2\n let (xs3,_) = BS.spanEnd (/= ']') $ BS.tail xs2\n (xs4,_) = BS.spanEnd (/=':') $ xs3\n guard $ not $ BS.null xs4\n let xs5 = BS.tail xs4\n return $ (4+) $ length $ BS.elemIndices '|' xs5\n"}, {"source_code": "main = interact f\n\nf s = (case f0 s of\n Just i -> show (i + 4)\n Nothing -> \"-1\") ++ \"\\n\"\n\nf0 ('[':s) = f1 s\nf0 (_:s) = f0 s\nf0 [] = Nothing\n\nf1 (':':s) = f2 s\nf1 (_:s) = f1 s\nf1 [] = Nothing\n\nf2 s = f3 Nothing 0 s\n\nf3 prev score ('|':s) = f3 prev (score + 1) s\nf3 prev score (':':s) = case f4 s of\n Just (i, s) -> f3 (Just score) (score + i) s\n Nothing -> prev\nf3 prev score (_:s) = f3 prev score s\nf3 prev _ [] = prev\n\nf4 s = f5 0 s\n\nf5 i ('|':s) = f5 (i + 1) s\nf5 i (']':s) = Just (i, s)\nf5 i (_:s) = f5 i s\nf5 _ [] = Nothing\n"}], "src_uid": "915b4776a6b1fa15886247eb1ad40b60"} {"source_code": "import qualified Data.Array as A\nimport qualified Data.List as L\nimport Data.Ix\nimport Control.Monad\n\nmain :: IO ()\nmain = do [na,ma] <- (getLine >>= return . map read . words)\n la <- foldM (\\e x -> nextChar >>= (\\c -> return ((x,c):e))) [] [(x,y) | x <- [1..na],y <- [1..ma]]\n getLine\n [nb,mb] <- (getLine >>= return . map read . words)\n lb <- foldM (\\e x -> nextChar >>= (\\c -> return ((x,c):e))) [] [(x,y) | x <- [1..nb],y <- [1..mb]]\n putStrLn . unwords . map show $ solve (na,ma) la (nb,mb) lb\n where \n nextChar = do c <- getChar\n case c of\n '\\n' -> nextChar\n '0' -> return 0\n '1' -> return 1\n\nsolve :: (Int,Int) -> [((Int,Int),Int)] -> (Int,Int) -> [((Int,Int),Int)] -> [Int]\nsolve (na,ma) la (nb,mb) lb = snd $ maximum [ (overlap x y,[x,y]) | x <- [-50..50], y <- [-50..50]]\n where mat_a = A.array ((1,1),(na,ma)) la\n mat_b = A.array ((1,1),(nb,mb)) lb\n overlap :: Int -> Int -> Int\n overlap x y = L.foldl' (+) 0 [(mat_a A.! (i,j)) * (mat_b A.! (i+x,j+y)) | i <- [max 1 (1-x)..min na (nb-x)],j <- [max 1 (1-y)..min ma (mb-y)]]\n", "positive_code": [{"source_code": "\nimport Array\nimport Data.List (foldl')\nimport Monad (liftM)\n\nsolve :: Array (Int, Int) Int -> Array (Int, Int) Int -> (Int, Int)\nsolve a b = (m, n)\n where\n (m, n, fa) = foldl' getMax (undefined, undefined, -1)\n [(x, y) | x <- [1 - na .. nb - 1], y <- [1 - ma .. mb - 1]]\n (na, ma) = snd $ bounds a\n (nb, mb) = snd $ bounds b\n getMax a@(_, _, fa) b@(b1, b2)\n | fa > fb = a\n | otherwise = (b1, b2, fb)\n where\n fb = f b\n f (x, y) = foldl' (+) 0 [a ! (i,j) * b ! (i+x, j+y)\n | i <- [max 1 (1 - x) .. min na (nb - x)],\n j <- [max 1 (1 - y) .. min ma (mb - y)]]\n\nmain :: IO ()\nmain = do\n ls <- liftM lines getContents\n let [na, ma] = map read . words . head $ ls\n let a = listArray ((1,1), (na, ma)) . map read . concatMap (map (\\c -> [c])) . take na . tail $ ls\n let [nb, mb] = map read . words . head . drop na . drop 1 $ ls\n let b = listArray ((1,1), (nb, mb)) . map read . concatMap (map (\\c -> [c])) . take nb . drop 1 . drop na . drop 1 $ ls\n let (x,y) = solve a b\n putStrLn $ concat [show x, \" \", show y]\n"}], "negative_code": [], "src_uid": "8abdf3aa47fb3ec715693f6388d62a55"} {"source_code": "import Data.Ord\nimport Data.Int\nimport Data.Char\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>))\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get :: EIO Int\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n get :: EIO Int\n s <- gets\n case f2 s of\n Nothing -> putsln(\"-1\")\n Just (i, j) -> putsln(i : j : [])\n\nf2 :: String -> Maybe (Char, Char)\nf2 s = let aux (c : rest) (x, y) = if (mod ((ord c) - (ord '0')) 2) == 1 then aux rest (y, c) else aux rest (x, y)\n aux [] (x, y) = (x, y)\n in\n let (x, y) = aux s ('x', 'x') in\n if x == 'x' || y == 'x' then\n Nothing\n else Just (x, y)\n", "positive_code": [{"source_code": "import Data.Maybe (fromMaybe)\n\n\nmain = readLn >>= go where\n go 0 = return ()\n go n = getLine >> readLn >>= print . fromMaybe (-1) . solve >> go (n-1)\n\nsolve :: Integer -> Maybe Int\nsolve n = let\n a = map read (map (:[]) $ show n) :: [Int]\n odds = filter odd a\n in if length odds < 2 then Nothing else Just $ 10 * (odds !! 0) + odds !! 1"}, {"source_code": "import Data.Char\n\ntoEbne :: [Integer] -> [Integer]\ntoEbne number = take 2 $ filter odd number\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest\n\ntoString :: [Integer] -> String\ntoString [] = \"-1\"\ntoString [_] = \"-1\"\ntoString number = foldl (\\acc n -> acc ++ show n) \"\" number\n\nsolve :: (String, String) -> String\nsolve (_, xs) = toString $ toEbne number\n where number = map (\\n -> toInteger $ n - (ord '0')) $ map ord xs\n\nmain :: IO ()\nmain = interact (unlines . map solve . groupByTwo . tail . lines)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest a = getLine >> getLine >>= putStrLn.solve.take 2.filter (\\d -> odd $ read [d]) >> test (a - 1)\n\nsolve a | length a == 2 = a | otherwise = \"-1\"\n"}], "negative_code": [{"source_code": "import Data.Char\n\ntoEbne :: [Integer] -> [Integer]\ntoEbne number = take 2 $ filter odd number\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo [_, _] = []\ngroupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest\n\ntoString :: [Integer] -> String\ntoString [] = \"-1\"\ntoString number = foldl (\\acc n -> acc ++ show n) \"\" number\n\nsolve :: (String, String) -> String\nsolve (_, xs) = toString $ toEbne number\n where number = map (\\n -> toInteger $ n - (ord '0')) $ map ord xs\n\nmain :: IO ()\nmain = interact (unlines . map solve . groupByTwo . tail . lines)\n"}, {"source_code": "import Data.Char\n\ntoEbne :: [Integer] -> [Integer]\ntoEbne number = take 2 $ filter odd number\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest\n\ntoString :: [Integer] -> String\ntoString [] = \"-1\"\ntoString number = foldl (\\acc n -> acc ++ show n) \"\" number\n\nsolve :: (String, String) -> String\nsolve (_, xs) = toString $ toEbne number\n where number = map (\\n -> toInteger $ n - (ord '0')) $ map ord xs\n\nmain :: IO ()\nmain = interact (unlines . map solve . groupByTwo . tail . lines)\n"}, {"source_code": "import Data.Char\n\ntoEbne :: [Integer] -> [Integer]\ntoEbne number\n | null oddVersion = []\n | even currSum = oddVersion\n | otherwise = (takeWhile even oddVersion) ++ (tail (dropWhile even oddVersion))\n where oddVersion = reverse $ dropWhile even $ reverse number\n currSum = sum oddVersion\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest\n\ntoString :: [Integer] -> String\ntoString [] = \"-1\"\ntoString number = foldl (\\acc n -> acc ++ show n) \"\" number\n\nsolve :: (String, String) -> String\nsolve (_, xs) = toString $ toEbne number\n where number = map (\\n -> toInteger $ n - (ord '0')) $ map ord xs\n\nmain :: IO ()\nmain = interact (unlines . map solve . groupByTwo . tail . lines)\n"}, {"source_code": "import Data.Char\n\ntoEbne :: [Integer] -> [Integer]\ntoEbne number = take 2 $ filter odd number\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo [_] = []\ngroupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest\n\ntoString :: [Integer] -> String\ntoString [] = \"-1\"\ntoString number = foldl (\\acc n -> acc ++ show n) \"\" number\n\nsolve :: (String, String) -> String\nsolve (_, xs) = toString $ toEbne number\n where number = map (\\n -> toInteger $ n - (ord '0')) $ map ord xs\n\nmain :: IO ()\nmain = interact (unlines . map solve . groupByTwo . tail . lines)\n"}, {"source_code": "import Data.Char\n\ntoEbne :: [Int] -> [Int]\ntoEbne number\n | null oddVersion = []\n | even currSum = oddVersion\n | otherwise = (takeWhile even oddVersion) ++ (tail (dropWhile even oddVersion))\n where oddVersion = reverse $ dropWhile even $ reverse number\n currSum = sum oddVersion\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest\n\ntoString :: [Int] -> String\ntoString [] = \"-1\"\ntoString number = foldl (\\acc n -> acc ++ show n) \"\" number\n\nsolve :: (String, String) -> String\nsolve (_, xs) = toString $ toEbne number\n where number = map (\\n -> n - (ord '0')) $ map ord xs\n\nmain :: IO ()\nmain = interact (unlines . map solve . groupByTwo . tail . lines)\n"}], "src_uid": "8f00837e04627e445dfb8b6cd0216640"} {"source_code": "\nimport Control.Monad (liftM, forM_)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> [Int]\nsolve [n, k]\n | n == k = [-1]\n | n == k + 1 = [1..n]\n | otherwise = n : [2 .. k+1] ++ 1 : [k+2 .. n-1]\n\nmain :: IO ()\nmain = reads >>= prints . solve\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n", "positive_code": [{"source_code": "module Main where\nimport Control.Applicative\nmain :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n let ans = [n] ++ [2..k+1] ++ [1] ++ [k+2..n-1]\n case undefined of\n _ | n == k -> print $ -1\n _ | n == k+1 -> putStrLn $ unwords $ map show [1..n]\n _ | otherwise -> putStrLn $ unwords $ map show ans\n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM, forM_)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> [Int]\nsolve [n, k]\n | n == k = [-1]\n | otherwise = take n ([1..k+1] ++ repeat 1)\n\nmain :: IO ()\nmain = reads >>= prints . solve\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "module Main where\nimport Control.Applicative\nmain :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n let ans = [n] ++ [2..k+1] ++ [1] ++ [k+2..n-1]\n if n == k\n then print $ -1\n else putStrLn $ unwords $ map show ans\n"}], "src_uid": "dc548fe1d8683b4b0ee4e0fa67638185"} {"source_code": "main :: IO ()\nmain = do\n raw <- getContents\n let rows = map (map (read :: [Char] -> Integer) . words) $ tail $ lines raw\n putStr $ unlines $ map (show . process) rows\n\nprocess :: [Integer] -> Integer\nprocess [str, int, exp_] = max 0 (if exp_ < str - int then exp_ + 1 else (str - int + exp_ + 1) `div` 2)\nprocess _ = error \"Malformed line\"\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let asNums :: [Int]\n asNums = map read $ words input\n idx:xs = asNums\n inp = asthree xs\n mapped = map solve' inp\n in intercalate \"\\n\" $ map show mapped\n\nasthree :: [Int] -> [(Int, Int, Int)]\nasthree [] = [] \nasthree (a:b:c:xs) = (a, b, c):(asthree xs)\n\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (str, int, exp)\n | exp <= 0 && str > int = 1\n | left <= 0 && str <= int = 0\n | otherwise = max 0 (exp - adds + 1)\n -- | str >= int = min (div (base' + exp + 1) 2) exp\n -- | otherwise = div' left 2\n where\n base = min str int\n str' = str - base\n int' = int - base\n base' = max str' int'\n left = exp - base'\n adds = max 0 (div (exp + int - str + 2) 2) \n\ndiv' it n2 = (div it n2) + (mod it n2)\n"}, {"source_code": "main = mapM (print . solve) . parse . map read . tail . words =<< getContents\nparse (a:b:c:xs) = (a,b,c) : parse xs\nparse [] = []\nsolve (str,int,exp) | tip < 0 = 0\n | tip > exp = exp + 1\n | otherwise = tip + 1\n where tip = (str-int+exp-1) `div` 2\n"}], "negative_code": [{"source_code": "main = do\n s <- getContents\n let xss = tail $ lines s\n let rows = map (map (read :: [Char] -> Integer) . words) xss\n putStr $ unlines $ map (show . process) rows\n\nprocess [str, int, exp] = max 0 (str + exp - (str + int + exp) `div` 2)"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let asNums :: [Int]\n asNums = map read $ words input\n idx:xs = asNums\n inp = asthree xs\n mapped = map solve' inp\n in intercalate \"\\n\" $ map show mapped\n\nasthree :: [Int] -> [(Int, Int, Int)]\nasthree [] = [] \nasthree (a:b:c:xs) = (a, b, c):(asthree xs)\n\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (str, int, exp)\n | exp <= 0 && str > int = 1\n | left <= 0 && str <= int = 0\n | str >= int = min (quot (base' + exp) 2) exp\n | otherwise = (div left 2) + (mod left 2)\n where\n base = min str int\n str' = str - base\n int' = int - base\n base' = max str' int'\n left = exp - base'\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let asNums :: [Int]\n asNums = map read $ words input\n idx:xs = asNums\n inp = asthree xs\n mapped = map solve' inp\n in intercalate \"\\n\" $ map show mapped\n\nasthree :: [Int] -> [(Int, Int, Int)]\nasthree [] = [] \nasthree (a:b:c:xs) = (a, b, c):(asthree xs)\n\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (str, int, exp)\n | exp <= 0 && str > int = 1\n | left <= 0 && str <= int = 0\n | str >= int = min (div (base' + exp) 2) exp\n | otherwise = div' left 2\n where\n base = min str int\n str' = str - base\n int' = int - base\n base' = max str' int'\n left = exp - base'\n\ndiv' it n2 = (div it n2) + (mod it n2)\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let asNums :: [Int]\n asNums = map read $ words input\n idx:xs = asNums\n inp = asthree xs\n mapped = map solve' inp\n in intercalate \"\\n\" $ map show mapped\n\nasthree :: [Int] -> [(Int, Int, Int)]\nasthree [] = [] \nasthree (a:b:c:xs) = (a, b, c):(asthree xs)\n\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (str, int, exp)\n | exp <= 0 && str > int = 1\n | left <= 0 && str <= int = 0\n | str >= int = min (div' (base' + exp) 2) exp\n | otherwise = div' left 2\n where\n base = min str int\n str' = str - base\n int' = int - base\n base' = max str' int'\n left = exp - base'\n\ndiv' it n2 = (div it n2) + (mod it n2)\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nsolve input = \n let asNums :: [Int]\n asNums = map read $ words input\n idx:xs = asNums\n inp = asthree xs\n mapped = map solve' inp\n in intercalate \"\\n\" $ map show mapped\n\nasthree :: [Int] -> [(Int, Int, Int)]\nasthree [] = [] \nasthree (a:b:c:xs) = (a, b, c):(asthree xs)\n\n\nsolve' :: (Int, Int, Int) -> Int\nsolve' (str, int, exp)\n | exp <= 0 && str > int = 1\n | left <= 0 && str <= int = 0\n | str >= int = min (div (base' + exp + 1) 2) exp\n | otherwise = div' left 2\n where\n base = min str int\n str' = str - base\n int' = int - base\n base' = max str' int'\n left = exp - base'\n\ndiv' it n2 = (div it n2) + (mod it n2)\n"}, {"source_code": "main = mapM (print . solve) . parse . map read . tail . words =<< getContents\nparse (a:b:c:xs) = (a,b,c) : parse xs\nparse [] = []\nsolve (str,int,exp) | tip < 0 = 0\n | otherwise = tip + 1\n where tip = (str-int+exp-1) `div` 2\n"}, {"source_code": "main = interact $ unlines . map (show . solve) . parse . map read . tail . words\nparse (a:b:c:xs) = (a,b,c) : parse xs\nparse [] = []\nsolve (str,int,exp) | tip < 0 = 0\n | otherwise = tip + 1\n where tip = (str-int+exp-1) `div` 2\n"}], "src_uid": "0816295355375a2d3f1cd45852b86360"} {"source_code": "import Control.Monad (liftM, replicateM, mapM_)\nimport Data.Char (ord)\nimport Data.List (intercalate, sort, (\\\\))\n\nsolve :: [[Int]] -> [Bool]\nsolve carts = map maybeWin carts\n where\n maybeWin cart = all (not . elem' cart) (carts \\\\ [cart])\n elem' a b = elem'' (sort a) (sort b)\n elem'' _ [] = True\n elem'' [] _ = False\n elem'' (a:as) (b:bs)\n | a < b = elem'' as (b:bs)\n | a > b = False\n | otherwise = elem'' as bs\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- replicateM n $ liftM tail reads\n mapM_ (putStrLn . (\"YES\" \"NO\")) $ solve as\n\n where\n () a b p = if p then a else b\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')", "positive_code": [{"source_code": "import Data.List\n\nmain = interact $ unlines . solve . map(map read.tail.words).tail.lines\n\nsolve :: [[Int]] -> [String]\nsolve cards = go [] cards\n where\n go xs (y:ys)\n | all (not . null . (\\\\y)) xs && all (not . null . (\\\\y)) ys = \"YES\" : go (y:xs) ys\n | otherwise = \"NO\" : go (y:xs) ys\n go _ _ = []\n"}], "negative_code": [], "src_uid": "90a47422f7ae53beb0a817422d760c6e"} {"source_code": "import List\nimport Control.Monad\nimport Control.Applicative\nsolve x0 (a,b) | mx > mn = \"-1\"\n | mx <= x0 && x0 <= mn = \"0\"\n | True = show $ min (abs(x0-mx)) (abs(x0-mn))\n where mx = maximum a\n mn = minimum b\n\npair = map read . words <$> getLine\n\nmain = do\n [n, x0] <- pair\n (replicateM n pair) >>= (putStrLn . solve x0 . unzip. map ((\\[a,b]->(a,b)).sort))\n ", "positive_code": [{"source_code": "import List\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nmain = do\n s <- getLine\n let n:x0:_ = un s\n l <- getLines n\n let xys_ = map un l\n xys = map (\\(a:b:_) -> (min a b, max a b)) xys_\n x1 = maximum $ map fst xys\n x2 = minimum $ map snd xys\n if x1 > x2 then\n putStrLn \"-1\"\n else if x1 <= x0 && x0 <= x2 then\n putStrLn \"0\"\n else let m = min (abs (x1 - x0)) (abs (x2 - x0))\n in putStrLn $ show m\n"}, {"source_code": "module Main where\n\n-- import Test.Tasty\n-- import Test.Tasty.HUnit\n-- import Debug.Trace\nimport Data.List\nimport Control.Monad\n\n\nrun start positions = \n let enumerate begin end [a,b] = if a x)\n commonPositions = \n fst3 $ \n foldr (\\x (acc,a,b) -> let e = enumerate a b x in (acc `intersect` e, head e, last e)) \n ([min begin end .. max begin end], min begin end, max begin end) \n (tail positions) \n in if null commonPositions then -1 else minimum $ map (abs . ((-) start)) commonPositions \n\nmain = do\n let processLine = map (\\x -> read x::Int) . words \n [len, start] <- (getLine >>= return . processLine)\n positions <- (replicateM len getLine >>= return . (map processLine))\n print $ run start positions\n \n \n{-\nmain = defaultMain $\n testCase \"Tests\" $ do\n run 3 [[0,7],[14,2],[4,6]] @?= 1\n\n\n\n-}\n\n"}, {"source_code": "solve _ _ [] = True\nsolve d add ((a, b) : xs) \n | (d + add) >= min a b && (d + add) <= max a b = solve d add xs\n | otherwise = False\n\n\n\nmain = do\n\tline <- getLine\n\tarr' <- getContents\n\tlet\n\t\t[n, x] = map (\\x -> read x :: Integer ). words $ line\n\t\tarr = map (\\x -> let [a, b] = map (\\y -> read y :: Integer ). words $ x in (a, b) ). lines $ arr'\n\t\tans 1001 = -1\n\t\tans d\n\t\t | solve x d arr = d\n\t\t | solve x (-d) arr = d\n\t\t | otherwise = ans (d+1)\n--\tprint x\n--\tprint arr\n\tprint $ ans 0\n"}], "negative_code": [{"source_code": "import List\n\nun = map (read :: String -> Int) . words\n\ngetLines 0 = return []\ngetLines n = do\n s <- getLine\n ss <- getLines (n-1)\n return (s:ss)\n\nmain = do\n s <- getLine\n let n:x0:_ = un s\n l <- getLines n\n let xys_ = map un l\n xys = map (\\(a:b:_) -> (min a b, max a b)) xys_\n x1 = maximum $ map fst xys\n x2 = minimum $ map snd xys\n if x1 > x2 then\n putStrLn \"-1\"\n else let m = min (abs (x1 - x0)) (abs (x2 - x0))\n in putStrLn $ show m\n"}], "src_uid": "3c066bad8ee6298b318bf0f4521c7c45"} {"source_code": "import Data.List (group, sort, sortBy)\nimport Data.Ord (comparing)\nsolve :: [String] -> String\nsolve [xs,k']\n | length xs <= k = \"0\\n\" \n | otherwise = (show (length ps - maxl)) ++ \"\\n\" ++ filter (`notElem` rmv) xs \n where sch = sort $ map (\\x -> (length x, head x)) ps \n ps = group (sort xs) \n k = read k'\n maxl = length $ takeWhile (<=k) $ scanl1 (+) $ map fst sch \n rmv = map snd (take maxl sch)\nmain = putStrLn.solve.lines =<< getContents", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Data.Ord\nimport qualified Data.Map as Map\n\nmain = do\n string <- getLine\n inputK <- getLine\n let k = read inputK :: Int\n letterCount = foldl' (\\count letter -> Map.insertWith' (+) letter 1 count) Map.empty string\n orderLetter = sortBy ( comparing ( letterCount Map.! ) ) $ Map.keys letterCount\n eat :: Int -> [Char] -> [Char]\n eat _ [] = []\n eat k (letter:letters) =\n let head_count = letterCount Map.! letter in\n if k >= head_count\n then eat ( k - head_count ) letters\n else letter:letters\n remainLetter = eat k orderLetter\n\n putStrLn $ show ( length remainLetter )\n putStrLn $ filter ( `elem` remainLetter ) string\n"}, {"source_code": "import List\nimport Data.Function\nl=length\ns[w,k]=[show$l$group$sort r,r]where r=map fst$sortBy(compare`on`snd)(drop(read k)$concat$sortBy(compare`on`l)$groupBy((==)`on`fst)$sort$zip w[0..])\nmain=interact$unlines.s.words"}, {"source_code": "import Data.Array.ST\nimport Control.Monad.ST\nimport Control.Monad (foldM)\nimport Data.Array.Unboxed\nimport Data.List (sortBy)\nimport Data.Function (on)\nmain = do\n \n \u0441\u0442\u0440\u043e\u043a\u0430 <- getLine\n k <- read `fmap` getLine\n let \u0433\u0440\u0430\u043d\u0438\u0446\u044b = ('a','z')\n \u0441\u0438\u043c\u0432\u043e\u043b\u044b = sortBy (compare `on` snd) $ filter ((>0).snd) $ assocs $ runSTUArray ((newArray \u0433\u0440\u0430\u043d\u0438\u0446\u044b 0 :: ST s (STUArray s Char Int)) >>= \n \\a -> foldM (\\a c -> readArray a c >>= \\n -> writeArray a c (n+1) >> return a) a \u0441\u0442\u0440\u043e\u043a\u0430)\n \n (_, \u0432\u044b\u0447\u0451\u0440\u043a\u0438\u0432\u0430\u0435\u043c) = foldl (\\(k, l) (c, n) -> if k >= n then (k-n, c:l) else (k, l)) (k, []) \u0441\u0438\u043c\u0432\u043e\u043b\u044b\n \u0444\u0438\u043b\u044c\u0442\u0440 = array \u0433\u0440\u0430\u043d\u0438\u0446\u044b $ map (\\c -> (c, c `notElem` \u0432\u044b\u0447\u0451\u0440\u043a\u0438\u0432\u0430\u0435\u043c)) $ range \u0433\u0440\u0430\u043d\u0438\u0446\u044b :: UArray Char Bool\n print (length \u0441\u0438\u043c\u0432\u043e\u043b\u044b - length \u0432\u044b\u0447\u0451\u0440\u043a\u0438\u0432\u0430\u0435\u043c)\n putStrLn $ filter (\u0444\u0438\u043b\u044c\u0442\u0440 !) \u0441\u0442\u0440\u043e\u043a\u0430\n\n"}, {"source_code": "import List\nf#p=(\\x->f(p x).p)\nl=length\nz x=[show$l$group$sort x,x]\nb x=sortBy$compare#x\ns[w,k]=drop(read k)$id=<<(b l$groupBy((==)#fst)$sort$zip w[0..])\nmain=interact$unlines.z.map fst.b snd.s.words"}, {"source_code": "import List\nf#p=(.p).f.p\nl=length\nz x=[show$l$group$sort x,x]\nb x=sortBy$compare#x\ns[w,k]=drop(read k)$id=<<(b l$groupBy((==)#fst)$sort$zip w[0..])\nmain=interact$unlines.z.map fst.b snd.s.words"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\nsolve :: String -> Int -> (String, Int)\nsolve chars k =\n (solution, S.size $ S.fromList solution)\n where solution = filter (\\x -> not $ S.member x dropped) chars\n chars2 :: [(Int, Char)]\n chars2 = L.sort [(length x, head x) | x <- L.group . L.sort $ chars]\n chars3 :: [(Int, Char)]\n chars3 = snd $ L.mapAccumL (\\k (cnt, chr) -> (k - cnt, (k - cnt, chr))) k chars2\n dropped = S.fromList [chr | (cnt, chr) <- chars3, cnt >= 0]\n\n\n\n\nmain = do\n chars <- getLine\n k <- (getLine >>= return . (read::String->Int))\n let (solution, m) = solve chars k\n putStrLn $ show m\n putStrLn $ solution\n"}], "negative_code": [{"source_code": "import List\nl=length\ns[w,k]=[show$l$nub r,w\\\\r]where r=take(read k)$snd=<<(sort$map(\\x->(l x,x))$group$sort w)\nmain=interact$show.unlines.s.words"}, {"source_code": "import List\nl=length\ns[w,k]=[show$l$nub r,w\\\\r]where r=take(read k)$snd=<<(sort$map(\\x->(l x,x))$group$sort w)\nmain=interact$unlines.s.words"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\nsolve :: String -> Int -> (String, Int)\nsolve chars k =\n (solution, S.size $ S.fromList solution)\n where solution = filter (\\x -> not $ S.member x dropped) chars\n chars2 :: [(Int, Char)]\n chars2 = L.sort [(length x, head x) | x <- L.group . L.sort $ chars]\n chars3 :: [(Int, Char)]\n chars3 = snd $ L.mapAccumL (\\k (cnt, chr) -> (k - cnt, (k - cnt, chr))) k chars2\n dropped = S.fromList [chr | (cnt, chr) <- chars3, cnt > 0]\n\n\n\n\nmain = do\n chars <- getLine\n k <- (getLine >>= return . (read::String->Int))\n let (solution, m) = solve chars k\n putStrLn $ solution\n putStrLn $ show m"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.List as L\n\nsolve :: String -> Int -> (String, Int)\nsolve chars k =\n (solution, S.size $ S.fromList solution)\n where solution = filter (\\x -> not $ S.member x dropped) chars\n chars2 :: [(Int, Char)]\n chars2 = L.sort [(length x, head x) | x <- L.group . L.sort $ chars]\n chars3 :: [(Int, Char)]\n chars3 = snd $ L.mapAccumL (\\k (cnt, chr) -> (k - cnt, (k - cnt, chr))) k chars2\n dropped = S.fromList [chr | (cnt, chr) <- chars3, cnt > 0]\n\n\n\n\nmain = do\n chars <- getLine\n k <- (getLine >>= return . (read::String->Int))\n let (solution, m) = solve chars k\n putStrLn $ show m\n putStrLn $ solution\n"}], "src_uid": "f023111561605b3e44ca85cb43b4aa00"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.STRef\nimport Data.Tuple\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport Data.Word\nimport Debug.Trace\n\nmain :: IO ()\nmain = readLn >>= putStr.unlines.map (map$bool '*' '+').solve\n\nsolve :: Int -> [[Bool]]\nsolve 0 = [[True]]\nsolve k = zipWith (++) block0 block2 ++ zipWith (++) block0 block1\n where\n block0 = solve (k-1)\n block1 = map reverse block0\n block2 = map (map not) block1", "positive_code": [{"source_code": "import Data.List\n\nreadint :: String -> Int\nreadint = read\n\nflipv :: Char -> Char\nflipv '*' = '+'\nflipv '+' = '*'\n\nsolve :: Int -> [String]\nsolve 0 = [['+']]\nsolve k = concat $ map (\\s -> [s++s, s++(map flipv s)]) $ solve (k-1)\n\nmain = interact $ intercalate \"\\n\" . solve . readint\n"}, {"source_code": "import Data.List\nexpand s = [s++s, s++(map (*(-1)) s)]\n\nhadamard 0 = [[1]]\nhadamard k = concat $ map expand $ hadamard (k-1)\n\nhf::Int -> Char\nhf ( 1) = '+'\nhf (-1) = '*'\n\ntoSymbols s = map hf s\n\nhadamard' k = map toSymbols (hadamard k)\n\n\nmain = do\n k <- readLn :: IO Int\n putStr $ unlines (hadamard' k)\n"}], "negative_code": [{"source_code": "import Data.List\nexpand s = [s++s, s++(map (*(-1)) s)]\n\nhadamard 0 = [[1]]\nhadamard k = concat $ map expand $ hadamard (k-1)\n\nhf::Int -> Char\nhf ( 1) = '+'\nhf (-1) = '-'\n\ntoSymbols s = map hf s\n\nhadamard' k = map toSymbols (hadamard k)\n\n\nmain = do\n k <- readLn :: IO Int\n putStr $ unlines (hadamard' k)\n"}], "src_uid": "4e25d49e8a50dacc1cfcc9413ee83db6"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n r1 <- fromIntegral.maximum.tail.map readInt.B.words <$> B.getLine\n p1 <- fromIntegral.maximum.tail.map readInt.B.words <$> B.getLine\n p2 <- fromIntegral.minimum.tail.map readInt.B.words <$> B.getLine\n [a,b] <- map read.words <$> getLine\n print $ sqrt $ (b*p1*r1*r1)/(a*p2+b*p1)", "positive_code": [{"source_code": "\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nsolve :: (Double, Double) -> [Double] -> [Double] -> [Double] -> Double\nsolve (a, b) r1s p1s p2s = r1 * sqrt (p1 * b / (p2 * a + p1 * b))\n where\n r1 = maximum r1s\n p1 = maximum p1s\n p2 = minimum p2s\n\nmain :: IO ()\nmain = do\n as <- reads\n bs <- reads\n cs <- reads\n [a, b] <- reads\n print $ solve (a,b) (tail as) (tail bs) (tail cs)\n"}, {"source_code": "import Data.List\nmain = do\n [x, y, z] <- mapM (\\_ -> (map read . tail . words) `fmap` getLine) [1..3] :: IO [[Double]]\n [a, b] <- (map read . words) `fmap` getLine\n let p1 = maximum y\n let p2 = minimum z\n let r1 = maximum x\n print $ sqrt $ r1 * r1 * p1/(a/b + p1/p2)/p2\n"}, {"source_code": "solve :: ([Double], [Double], [Double], Double, Double) -> Double\nsolve (xs, ys, zs, a, b) = sqrt $ r1^2 * p1 * b / (p1 * b + p2 * a)\n where r1 = maximum xs\n p1 = maximum ys\n p2 = minimum zs\n\nreadInput :: IO ([Double], [Double], [Double], Double, Double)\nreadInput = do\n contents <- getContents\n let ns:ms:ks:ab:_ = lines contents\n xs = map read $ tail $ words ns\n ys = map read $ tail $ words ms\n zs = map read $ tail $ words ks\n a = read $ words ab !! 0\n b = read $ words ab !! 1\n return (xs, ys, zs, a, b)\n\nshowOutput :: Double -> IO ()\nshowOutput r = do\n print r\n\nmain :: IO ()\nmain = do\n input <- readInput\n showOutput $ solve input\n"}, {"source_code": "solve :: ([Double], [Double], [Double], Double, Double) -> Double\nsolve (xs, ys, zs, a, b) = maximum [r2 | r1 <- xs, let p1 = maximum ys, let p2 = minimum zs, let r2 = sqrt $ r1^2 * p1 * b / (p1 * b + p2 * a)]\n\nreadInput :: IO ([Double], [Double], [Double], Double, Double)\nreadInput = do\n contents <- getContents\n let ns:ms:ks:ab:_ = lines contents\n xs = map read $ tail $ words ns\n ys = map read $ tail $ words ms\n zs = map read $ tail $ words ks\n a = read $ words ab !! 0\n b = read $ words ab !! 1\n return (xs, ys, zs, a, b)\n\nshowOutput :: Double -> IO ()\nshowOutput r = do\n print r\n\nmain :: IO ()\nmain = do\n input <- readInput\n showOutput $ solve input\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport qualified Data.List as L\nimport qualified Data.Function as F\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\n\nparse = map (map read) . map words . lines \n \n-- xs~r1, ys~p1, zs~p2\nsolve [_:xs, _:ys, _:zs, [a, b]] =\n let \n r1 = maximum xs\n p1 = maximum ys\n p2 = minimum zs\n in \n sqrt ((b * p1 * r1 * r1)/(p2 * a + p1 * b))\n\npresent = show\n\nmain = interact $ present . solve . parse\n\n"}, {"source_code": "main = do\n r1 <- fmap (maximum . tail) getArray\n p1 <- fmap (maximum . tail) getArray\n p2 <- fmap (minimum . tail) getArray\n [a, b] <- getArray\n print $ gao r1 p1 p2 a b\n where\n getArray = fmap (map read . words) getLine\n gao r1 p1 p2 a b = r1 / sqrt ((a * p2) / (b * p1) + 1)\n"}, {"source_code": "calc::Double->Double->Double->Double->[Double]->Double\ncalc _ _ _ _ [] = 0\ncalc r1 p2 a b (y:ys) = max (sqrt ((r1 * r1 * y * b) / (p2 * a + y * b))) (calc r1 p2 a b ys) \n\nmain = do\n xs <- getLine\n let r1 = foldl max 0 (tail (map (read::String->Double) (words xs)))\n ys <- getLine\n let p1 = tail.map (read::String->Double) $ words ys\n zs <- getLine\n let p2 = foldl min 65535 (tail (map (read::String->Double) (words zs)))\n ab' <- getLine\n let ab = map (read::String->Double) $ words ab'\n putStrLn(show $ calc r1 p2 (ab !! 0) (ab !! 1) p1)"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Control.Applicative\n\nring a b = (circle a) - (circle b)\ncircle a = a * a\n\n-- (r1 * r1 * pi - r2 * r2 * pi) * p1 * b == r2 * r2 * pi * p2 * a\nsolve x y z a b = let r1 = foldr max 0.0 x\n p2 = foldr min 10000.0 z\n cand = [ r1 * (sqrt ((p1 * b) / (p2 * a + p1 * b))) | p1 <- y ]\n in foldr max 0.0 cand\n\nmain = do\n x <- map fromIntegral <$> (tail <$> readInts)\n y <- map fromIntegral <$> (tail <$> readInts)\n z <- map fromIntegral <$> (tail <$> readInts)\n [a, b] <- map fromIntegral <$> readInts\n print $ solve x y z a b\n\ntoNumber (Just (x, _)) = x\ntoNumber Nothing = 0\nreadInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\n"}], "negative_code": [], "src_uid": "18b1814234b05bae56ea4446506b543b"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\n\nmain=do\n [n,m,x]<-map read.words<$>getLine\n keys<-replicateM n getLine\n let goodKeys = map head.group.sort $ do\n (i, row) <- zip [0..n-1] keys\n (j, 'S') <- zip [0..m-1] row\n (i', row') <- zip [0..n-1] keys\n (j', l) <- zip [0..m-1] row'\n let sq x = x*x\n guard (sq(i-i')+sq(j-j') <= sq x)\n return l\n getLine\n text<-getLine\n let badKeys = map toUpper$filter(`notElem` goodKeys)['a'..'z']\n veryBadLc = filter(\\c -> all (c `notElem`) keys)['a'..'z']\n any2D p = any (any p)\n veryBadKeys | any2D (=='S') keys = veryBadLc ++ map toUpper veryBadLc\n | otherwise = veryBadLc ++ ['A'..'Z']\n cnt p = length.filter p\n \n putStrLn$show$case cnt (`elem` veryBadKeys) text of\n 0 -> cnt(`elem` badKeys) text\n _ -> -1\n", "positive_code": [{"source_code": "import Data.Char (toLower, isUpper)\nimport qualified Data.Map as M\nimport Control.Monad (foldM, guard)\nimport Data.List (foldl')\nmain = do\n [n, m, x] <- (map read . words) `fmap` getLine\n cm <- foldM (\\cm' i -> do\n l <- getLine\n return $ foldl (\\cm (c, j) -> M.insertWith (++) c [(i, j)] cm) cm' $\n zip l [0..]) M.empty [0..n-1]\n let cm' = M.fromList $ (if M.notMember 'S' cm then map (\\x -> (x, Nothing)) \n else let xs = cm M.! 'S' in map (\\c -> (c, Just $ (do\n (ix, jx) <- xs\n (i, j) <- cm M.! c\n let l = (i-ix)^2 + (j-jx)^2\n guard (l <= x^2)\n return l) /= []))) $ filter (/='S') $ M.keys cm\n _ <- getLine\n k <- (foldl' (\\r c -> do\n r' <- r\n b <- M.lookup (toLower c) cm'\n r'' <- if isUpper c then do\n b' <- b\n return $ if b' then 0 else 1 else Just 0\n return (r' + r'')) (Just 0)) `fmap` getLine\n print $ case k of {Nothing -> (-1); Just x -> x} \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\n\nlook :: (Eq e, Ix i) => Array i e -> e -> [i]\nlook ar el = filter (\\i ->(ar ! i) == el) (indices ar)\n\nmain :: IO ()\nmain = do\n [n,m,x] <- map (fst.fromJust.BS.readInt) . BS.words <$> BS.getLine\n board <- listArray ((1,1), (n,m)) . BS.unpack .BS.filter isAlpha . BS.concat <$> replicateM n BS.getLine\n let epS c = c `elem` (elems board)\n wU c = if epS (toLower c) && ('S' `elem` (elems board))\n then if isPoss then 0 else 1\n else (-1)\n where sl = look board 'S'\n cl = look board (toLower c)\n isPoss = or [ ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) <= x*x | (x1, y1) <- sl, (x2, y2) <- cl]\n q <- fst . fromJust . BS.readInt <$> BS.getLine\n let f (-1) _ = (-1)\n f n c | isLower c && epS c = n\n | isLower c = (-1)\n | temp == (-1) = (-1)\n | otherwise = n + temp\n where temp = wU' ! c\n wU' = listArray ('A','Z') [wU c | c <- ['A'..'Z']]\n ans <- BS.foldl' f 0 . BS.filter isAlpha <$> BS.getLine\n --print $ look board 'S'\n --print $ look board 'c'\n --print wU'\n print ans\n"}], "negative_code": [], "src_uid": "0870110338a84f76d4870d06dc9da2df"} {"source_code": "import Control.Monad (replicateM_)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = read <$> getLine >>= \\x -> print $\r\n if x == 1 then 2 else\r\n let (a, r) = x `divMod` 3 in\r\n (if r == 0 then id else (1+)) a", "positive_code": [{"source_code": "module Main where\r\nimport Control.Monad\r\nimport Data.List\r\ny::Bool->Bool->Int\r\ny True True=2\r\ny False False=0\r\ny True False=1\r\ny False True=1\r\nsolve::Int->Int\r\nsolve x= d+(y ((x`rem`3)/=0) (x==1))\r\n where d=x`div`3\r\n\r\nmain = do\r\n line<-getLine\r\n let nTerm=read line::Int \r\n replicateM_ nTerm$do\r\n line<-getLine\r\n let n=read line::Int\r\n print$solve n"}, {"source_code": "import Control.Monad (replicateM_)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = read <$> getLine >>= \\x -> print $\r\n if x == 1 then 2 else\r\n let (a, r) = x `divMod` 3 in\r\n if r == 0 then a else 1+a"}, {"source_code": "import Control.Monad (replicateM_)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = read <$> getLine >>= \\x -> print $\r\n if x == 1 then 2\r\n else x `div` 3 + case x `mod` 3 of\r\n 0 -> 0\r\n 1 -> 1\r\n 2 -> 1"}, {"source_code": "{-\n Whatever you do, work heartily, as for the Lord and not for men,\n knowing that from the Lord you will receive the inheritance as your reward.\n You are serving the Lord Christ.\n - Colossians 3:23-24\n-}\n\nmodule Main\n ( main )\n where\n\nimport Control.Monad\n\nminutesTo :: Int -> Int\nminutesTo x\n | x == 1 = 2\n | rem == 0 = quot\n | otherwise = quot + 1\n where (quot, rem) = x `quotRem` 3\n\nmain :: IO ()\nmain = do\n line <- getLine\n let testCases = read line\n\n replicateM_ testCases $ do\n line <- getLine\n let n = read line\n print $ minutesTo n\n"}], "negative_code": [{"source_code": "{-\n Whatever you do, work heartily, as for the Lord and not for men,\n knowing that from the Lord you will receive the inheritance as your reward.\n You are serving the Lord Christ.\n - Colossians 3:23-24\n-}\n\nmodule Main\n ( main )\n where\n\nimport Control.Monad\n\nminutesTo :: Int -> Int\nminutesTo x\n | x == 1 = 2\n | x `mod` 3 == 0 = x `div` 3\n | otherwise = x `div` 2\n\nmain :: IO ()\nmain = do\n line <- getLine\n let testCases = read line\n\n replicateM_ testCases $ do\n line <- getLine\n let n = read line\n print $ minutesTo n\n"}], "src_uid": "208e285502bed3015b30ef10a351fd6d"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.Int (Int)\nimport Data.List (sort)\nimport Debug.Trace\n\nreadMultipleFromLine :: IO [Int]\nreadMultipleFromLine = map parse . C.words <$> C.getLine\n where\n parse s = let Just (n, _) = C.readInt s in n\n\njoints :: Int -> [Int] -> [Int]\njoints x a = [j - i | (i, j) <- zip a $ tail a, j - i > x]\n\nuniteCount :: Int -> Int -> [Int] -> Int\nuniteCount _ _ [] = 0\nuniteCount x k a =\n let need = head a `div` x - (if head a `mod` x == 0 then 1 else 0)\n in if need <= k\n then uniteCount x (k - need) $ tail a\n else length a\n\nmain = do\n [n, k, x] :: [Int] <- readMultipleFromLine\n a :: [Int] <- readMultipleFromLine\n print $ 1 + uniteCount x k (sort $ joints x $ sort a)", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\n\n\n\n\nsolve :: IO ()\nsolve = do\n [n, k, x] <- readInts :: IO [Int64]\n ys <- readInts :: IO [Int64]\n let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys\n xs = sort diffs\n res = foldl (\\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs\n in print $ snd res\n where ceil x r = div (x-1) r\n\n\n\n\nparseInt :: Bs.ByteString -> Int64\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48) :: Int64))) (1::Int64, 0::Int64) xs\n\n\nreadInts :: IO [Int64]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n \n--parseInt = f . Char8.readInt where f (Just (i, _)) = i\n--readInts = map parseInt . Char8.words <$> Char8.getLine\n\nmain = do\n let t = 1\n replicateM_ t $ solve\n \n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.Int (Int)\nimport Data.List (sort)\nimport Debug.Trace\n\nreadMultipleFromLine :: IO [Int]\nreadMultipleFromLine = map parse . C.words <$> C.getLine\n where\n parse s = let Just (n, _) = C.readInt s in n\n\njoints :: Int -> [Int] -> [Int]\njoints x a = [j - i | (i, j) <- zip a $ tail a, j - i > x]\n\ncomputeExtraNeed :: Int -> Int -> Int\ncomputeExtraNeed ai x = ai `div` x - (if ai `mod` x == 0 then 1 else 0)\n\ncountRemainingJoint :: Int -> (Int, Int) -> Int -> (Int, Int)\ncountRemainingJoint x (k, acc) ai =\n let need = computeExtraNeed ai x\n in if k > 0 && need <= k\n then (k - need, acc)\n else (k, acc + 1)\n\nuniteCount :: Int -> Int -> [Int] -> Int\nuniteCount x k a = snd $ foldl (countRemainingJoint x) (k, 0) a\n\nmain = do\n [n, k, x] :: [Int] <- readMultipleFromLine\n a :: [Int] <- readMultipleFromLine\n print $ 1 + uniteCount x k (sort $ joints x $ sort a)"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\n\n\n\n\nsolve :: IO ()\nsolve = do\n [n, k, x] <- readInts :: IO [Int64]\n ys <- readInts :: IO [Int64]\n print [n, k, x]\n print ys\n let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys\n xs = sort diffs\n res = foldl (\\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs\n in print $ snd res\n where ceil x r = div (x-1) r\n\n\n\n\nparseInt :: Bs.ByteString -> Int64\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48) :: Int64))) (1::Int64, 0::Int64) xs\n\nreadInts :: IO [Int64]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) <$> Bs.getLine\n \n \n--parseInt = f . Char8.readInt where f (Just (i, _)) = i\n--readInts = map parseInt . Char8.words <$> Char8.getLine\n\nmain = do\n let t = 1\n replicateM_ t $ solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\n\n\n\n\nsolve :: IO ()\nsolve = do\n [n, k, x] <- readInts :: IO [Int64]\n ys <- readInts :: IO [Int64]\n let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys\n xs = sort diffs\n res = foldl (\\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs\n in print $ snd res\n where ceil x r = div (x-1) r\n\n\n\n\nparseInt :: Bs.ByteString -> Int64\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48) :: Int64))) (1::Int64, 0::Int64) xs\n\nreadInts :: IO [Int64]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) <$> Bs.getLine\n \n \n--parseInt = f . Char8.readInt where f (Just (i, _)) = i\n--readInts = map parseInt . Char8.words <$> Char8.getLine\n\nmain = do\n let t = 1\n replicateM_ t $ solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as Char8\nimport qualified System.IO as Io\n--import Data.IntSet\n\n\n\n\n\nsolve :: IO ()\nsolve = do\n s1 <- readInts\n s2 <- readInts\n let [n, k, x] = map fromIntegral s1 :: [Int64]\n ys = map fromIntegral s2 :: [Int64]\n diffs = filter (>x) $ map snd $ drop 2 $ scanl (\\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys\n xs = sort diffs\n res = foldl (\\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs\n in print $ snd res\n where ceil x r = div (x-1) r\n\n\n\nparseInt = f . Char8.readInt where f (Just (i, _)) = i\nreadInts = map parseInt . Char8.words <$> Char8.getLine\n\nmain = do\n let t = 1\n replicateM_ t $ solve\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as Char8\nimport qualified System.IO as Io\n--import Data.IntSet\n\n\n\n\n\nsolve :: IO ()\nsolve = do\n [n, k, x] <- readInts\n ys <- readInts\n let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys\n xs = sort diffs\n res = foldl (\\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs\n in print $ snd res\n where ceil x r = div (x-1) r\n\n\n\nparseInt = f . Char8.readInt where f (Just (i, _)) = i\nreadInts = map parseInt . Char8.words <$> Char8.getLine\n\nmain = do\n let t = 1\n replicateM_ t $ solve\n \n \n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List (sort)\nimport GHC.Natural (intToNatural)\nimport Numeric.Natural (Natural)\n\nreadMultipleFromLine = fmap (map read . words) getLine\n\njoints :: Natural -> [Natural] -> [Natural]\njoints x a = [j - i | (i, j) <- zip a $ tail a, j - i > x]\n\nuniteCount :: Natural -> Natural -> [Natural] -> Natural\nuniteCount _ _ [] = 0\nuniteCount x k a =\n let need = head a `div` x - (if head a `mod` x == 0 then 1 else 0)\n in if need <= k\n then uniteCount x (k - need) $ tail a\n else intToNatural $ length a + 1\n\nmain = do\n [n, k, x] :: [Natural] <- readMultipleFromLine\n a :: [Natural] <- readMultipleFromLine\n print $ uniteCount x k $ sort $ joints x $ sort a"}], "src_uid": "c6c07ef23cf2def9f99cbfb6076c9810"} {"source_code": "solve :: String -> Int\nsolve [] = 0\nsolve ('P':queue) = solve queue\nsolve ('A':queue) = max pAhead (solve nextQueue)\n where pAhead = length $ takeWhile (== 'P') queue\n nextQueue = dropWhile (== 'P') queue\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:as:rest) = [(n, as)] ++ groupByTwo rest\n\nparse :: (String, String) -> String\nparse (n, as) = show $ solve as\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByTwo .tail . lines)\n", "positive_code": [{"source_code": "main = getLine >> getContents >>= output.lines\n\noutput (_:s:t) = (print $ f $ (== 'A') <$> s) >> output t\noutput _ = return ()\n\nf (True:t) = max (length $ takeWhile not t) (f $ dropWhile not t)\nf (_:t) = f t\nf _ = 0\n"}, {"source_code": "import Control.Monad\nimport Data.List (group)\n\nmaximumOr :: Ord a => a -> [a] -> a\nmaximumOr def [] = def\nmaximumOr _ xs = maximum xs\n\nsolve :: String -> Int\nsolve = maximumOr 0\n . map length\n . filter ((== 'P') . head)\n . group\n . dropWhile (/= 'A')\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n getLine\n print . solve =<< getLine\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Text as T\n\n\nonecase = do\n\t\tgetLine\n\t\ta<-T.pack <$> getLine\n\t\tprint $ maximum $ map T.length $ T.split (=='A') $ T.dropWhile (=='P') a\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n\n\n"}, {"source_code": "import Data.List (group)\n\nprocess :: [Char] -> Int\nprocess = maximum . map (\\x -> if head x == 'A' then 0 else length x) . group . dropWhile (=='P') . (++\"A\")\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n s <- getLine\n print $ process s\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "solve [] = (0, 0)\nsolve (x:s) | x == 'P' = (a + 1, b)\n | x == 'A' = (0, max a b)\n where (a, b) = solve s\n\n\ngo n = do\n k <- getLine\n a <- getLine\n putStrLn $ show $ snd $ solve a\n if n > 1 then do\n go $ n - 1\n else\n return ()\n\nmain = do\n s <- getLine\n let n = read s\n go n\n"}], "negative_code": [], "src_uid": "1539fc8ef4f4cdcd1e14faf4f1b4ee8b"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n a <- readInts\r\n let z = zipWith (*) (tail a) (init a)\r\n print $ maximum z\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = show . solve <$> numberOf integer\n\nsolve :: [Integer] -> Integer\nsolve xs = maximum [min u v * max u v | (u, v) <- zip xs (tail xs)]\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}], "negative_code": [], "src_uid": "2deed55e860bd69ff0ba3973a1d73cac"} {"source_code": "import Data.List\n\nmain=interact$show.solve.map ((\\[x,y]->(-x,y)).map read.words).lines\n\nsolve :: [(Int,Int)] -> Int\nsolve ((_,k):pts) = length.head.filter (((p,t)==).head).group $ xs\n where (p,t) = xs !! (k-1)\n xs = sort pts", "positive_code": [{"source_code": "import Data.List\ns([_,k]:t)=[q|x<-map length.group.sort$map(\\[a,b]->(-a,b))t,q<-replicate x x]!!(k-1)\nmain=interact$show.s.map(map read.words).lines\n"}, {"source_code": "import Data.List\n\nparse :: String -> [(Int, Int)]\nparse stuff = \n map parse_line (lines stuff)\n where parse_line l = t2 $ map (read::String->Int) (words l)\n t2 [a, b] = (a, b)\n t2 _ = error \"unexpected input\"\n\n\nsolve :: [(Int, Int)] -> Int\nsolve ((_, k):teams) = findKth k sorted \n where \n sorted = group . (sortBy cmp) $ teams\ncmp (a, b) (c, d)\n | a == c = compare b d\n | otherwise = compare c a\nfindKth _ [] = 0\nfindKth k (x:xs) \n | length x >= k = length x\n | otherwise = findKth (k - length x) xs\n -- findKth _ _ = 0\n\nmain = do\n stuff <- getContents\n print . solve $ parse stuff"}, {"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Text.Printf\nimport Debug.Trace\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Char as C\n\natoi :: B.ByteString -> Int\natoi = B.foldl' (\\a c -> a*10 + C.ord c - C.ord '0') 0\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve k ps = length $ filter (== p) ps\n where p = (sort ps) !! (k-1)\n\nmain = do\n [n, k] <- map atoi . B.words <$> B.getLine\n ps <- replicateM n $ do\n [x, y] <- map atoi . B.words <$> B.getLine\n return (-x, y)\n putStrLn . show $ solve k ps\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nreadi = read::String->Int\ngetParams = map readi . words <$> getLine\ngetDesc = zip' . map readi . words <$> getContents\n where zip' [] = []\n zip' (x:y:xs) = (x,y):zip' xs\nrsort = sortBy (\\(a,a') (b, b') -> if a == b then compare a' b'\n else compare b a)\nsolve k (x:xs)\n | y <= 0 = length x\n | otherwise = solve y xs\n where y = k - (length x)\nmain=do\n [_,k] <- getParams\n rsorted <- rsort <$> getDesc\n putStrLn $ show ((solve k).group $ rsorted)\n"}, {"source_code": "module Main where\n\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (show . solve . map (map read . words) . lines)\n\nsolve :: [[Int]] -> Int\nsolve ([_, k] : raw_results) = length winners where\n winners = filter (== winResult) sortedResults\n winResult = sortedResults !! (k - 1)\n\n sortedResults = reverse $ sortBy comp results\n\n results = map (\\[a, b] -> (a, b)) raw_results\n\ncomp :: (Int, Int) -> (Int, Int) -> Ordering\ncomp (a, b) (c, d)\n | a == c && b == d = EQ\n | a > c || a == c && b < d = GT\n | otherwise = LT\n"}, {"source_code": "import Data.List\ninputTeam1 = [(4,10),(4,10),(4,10),(3,20),(2,1),(2,1),(1,10)]\ninputTeam2 = [(3,1),(3,1),(5,3),(3,1),(3,1)]\ninputTeam3 = \"7 2\\n4 10\\n4 10\\n4 10\\n3 20\\n2 1\\n1 10\\n\"\ninputTeam4 = \"5 4\\n3 1\\n 3 1\\n5 3\\n3 1\\n3 1\\n\"\nmain = do\n\tx <- getContents\n\tputStrLn (show (j x))\nf (x,y) = x*(-100)+y\ng x = sort $ map f x\nh x y = count ((!!) (g x) (y-1)) (g x)\ni :: String -> [Int]\ni x = map read $ words x\nj x = h (k (tail (tail (i x)))) (head (tail (i x)))\nk [] = []\nk (x:y:zs) = (x,y):k zs\ncount _ [] = 0\ncount y (x:xs) = if y==x then 1 + count y xs\n\t\t\t\t\t\t else count y xs\n"}, {"source_code": "import IO\nimport Data.List\n\nmain = print . solve =<< parse stdin\n\nsolve (n, k, pts) = length $ filter (==score) pts\n where\n score = sort pts !! (k-1)\n\nparse h = do\n [n, k] <- readIntList h\n pts <- mapM (fmap f . readIntList) $ replicate n h\n return (n, k, pts)\n where\n f [a,b] = (-a, b)\n\n-- lib\nreadIntList = fmap (map read . words) . hGetLine\n\n-- vim: set expandtab:\n"}, {"source_code": "\nimport List\n\n{-\nimport HUnit\n\ntestOneTeam :: Test\ntestOneTeam = Test \"TestOneTeam\" $\n assertEq 1 (solve 1 [(1,1)])\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [Test \"1\" $\n assertEq 3 (solve 2 [(4,10),(4,10),(4,10),(3,20),(2,1),(2,1),(1,10)]),\n Test \"2\" $\n assertEq 4 (solve 4 [(3,1),(3,1),(5,2),(3,1),(3,1)])\n ]\n\ntests :: Test\ntests = TestList \"Testing ... \"\n [testOneTeam,\n testInput\n ]\n\ntest :: IO ()\ntest = run tests\n\n--------------------------------------------------------------------------------\n\n-}\n\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nreadPair :: Read a => IO (a, a)\nreadPair = do\n [x, y] <- Main.reads\n return (x, y)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve k xs = length (filter (== xk) xs)\n where\n xk = (sortBy compareTeam xs) !! (k-1)\n compareTeam (pa, ta) (pb, tb)\n | pa > pb = LT\n | pa < pb = GT\n | ta < tb = LT\n | ta > tb = GT\n | otherwise = EQ\n\nmain :: IO ()\nmain = do\n [n, k] <- Main.reads\n rankList <- mapM (const readPair) [1..n]\n print $ solve k rankList\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\ndata Team = Team Int Int deriving Eq\n\ninstance Ord Team where\n Team a b `compare` Team c d\n | a == c = compare b d\n | otherwise = compare c a\n\nparseInput = do \n n <- readInt\n k <- readInt\n teams <- replicateM n (Team <$> readInt <*> readInt)\n return (k, teams)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (k, teams) = length [team | team <- teams, team == kth]\n where\n sorted = sort teams\n\n kth = sorted !! (k-1)\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.Instances\nmain = do\n [n,k] <- liftM (map read . words) getLine\n rs <- liftM ( map length . group .\n sortBy (liftM2 mappend (comparing (negate . (!!0))) \n (comparing (!!1))) ) $\n replicateM n $\n liftM (map read . words) getLine\n print $ solve rs k\nsolve (n:ns) i | i <= n = n\n | otherwise = solve ns (i-n)\n"}, {"source_code": "module Main where\n\nimport Prelude hiding (lookup)\nimport Data.Array (listArray, (!))\nimport Data.Map (Map, fromList, lookup)\nimport Data.List (sortBy, group)\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\nflipOrdering LT = GT\nflipOrdering EQ = EQ\nflipOrdering GT = LT\n\ncalcScoreGroupings :: [(Int, Int)] -> Map (Int, Int) Int\ncalcScoreGroupings =\n fromList .\n map (\\groups -> (head groups, length groups)) .\n group\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readNumbers\n -- negative to keep reverse ordering\n -- lower problems means lower score\n -- lower timing means greater score\n scoreList0 <- fmap (sortBy (\\(i1, t1) (i2, t2) ->\n compare (-i1 * 1000 + t1)\n (-i2 * 1000 + t2)) .\n map (\\(a:b:_) -> (a,b)))\n (replicateM n readNumbers)\n\n let scoreGroupings = calcScoreGroupings scoreList0\n scoreListArray = listArray (1, n) scoreList0\n\n print (fromJust\n (lookup (scoreListArray ! k)\n scoreGroupings))\n"}, {"source_code": "import Data.List\nq k l=fst$head$dropWhile(\\(a,b) -> a+b(-a,b))t\nmain=interact$show.s.map(map read.words).lines"}], "negative_code": [{"source_code": "import Data.List\n\nparse :: String -> [(Int, Int)]\nparse stuff = \n map parse_line (lines stuff)\n where parse_line l = t2 $ map (read::String->Int) (words l)\n t2 [a, b] = (a, b)\n t2 _ = error \"unexpected input\"\n\n\nsolve :: [(Int, Int)] -> Int\nsolve ((_, k):teams) = findKth k sorted \n where \n sorted = reverse . group . sort $ teams\n findKth _ [] = 0\n findKth k (x:xs) \n | length x >= k = length x\n | otherwise = findKth (k - length x) xs\n -- findKth _ _ = 0\n\n\nmain = do\n stuff <- getContents\n print . solve $ parse stuff"}, {"source_code": "import Data.List\n\nparse :: String -> [(Int, Int)]\nparse stuff = \n map parse_line (lines stuff)\n where parse_line l = t2 $ map (read::String->Int) (words l)\n t2 [a, b] = (a, b)\n t2 _ = error \"unexpected input\"\n\n\nsolve :: [(Int, Int)] -> Int\nsolve ((_, k):teams) = findKth k sorted \n where \n sorted = reverse . group . sort $ teams\n findKth _ [] = 0\n findKth k (x:xs) \n | length x > k = length x\n | otherwise = findKth (k - length x) xs\n -- findKth _ _ = 0\n\n\nmain = do\n stuff <- getContents\n print . solve $ parse stuff"}, {"source_code": "import Data.List\nimport Control.Applicative\nreadi = read::String->Int\ngetParams = map readi . words <$> getLine\ngetDesc = zip' . map readi . words <$> getContents\n where zip' [] = []\n zip' (x:y:xs) = (x,y):zip' xs\nsort' = sortBy (\\(a,b) (a', b') -> if a == b then compare b a\n else compare a' b')\nsolve k (x:xs)\n | y <= 0 = length x\n | otherwise = solve y xs\n where y = k - (length x)\nmain=do\n [_,k] <- getParams\n rsorted <- sort' <$> getDesc\n putStrLn $ show ((solve k).group $ rsorted)\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nreadi = read::String->Int\ngetParams = map readi . words <$> getLine\ngetDesc = zip' . map readi . words <$> getContents\n where zip' [] = []\n zip' (x:y:xs) = (x,y):zip' xs\nsolve k (x:xs)\n | y <= 0 = length x\n | otherwise = solve y xs\n where y = k - (length x)\nmain=do\n [_,k] <- getParams\n sorted <- sort <$> getDesc\n putStrLn $ show ((solve k).reverse.group $ sorted)\n \n"}, {"source_code": "module Main where\n\nimport Prelude hiding (lookup)\nimport Data.Array (listArray, (!))\nimport Data.Map (Map, fromList, lookup)\nimport Data.List (sortBy, group)\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\nflipOrdering LT = GT\nflipOrdering EQ = EQ\nflipOrdering GT = LT\n\ncalcScoreGroupings :: [(Int, Int)] -> Map (Int, Int) Int\ncalcScoreGroupings =\n fromList .\n map (\\groups -> (head groups, length groups)) .\n group\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readNumbers\n scoreList0 <- fmap (sortBy (\\a b -> flipOrdering $ compare a b) .\n map (\\(a:b:_) -> (a,b)))\n (replicateM n readNumbers)\n\n let scoreGroupings = calcScoreGroupings scoreList0\n scoreListArray = listArray (1, n) scoreList0\n\n print (fromJust (lookup (scoreListArray ! k) scoreGroupings))\n"}, {"source_code": "import Data.List\ns([_,k]:t)=[q|x<-map length.group.sort$map(\\[a,b]->(-a,b))t,q<-replicate x x]!!(k+1)\nmain=interact$show.s.map(map read.words).lines\n"}], "src_uid": "63e03361531999db408dc0d02de93579"} {"source_code": "module Main where\n\nsolve :: [Int] -> Int\nsolve (_ : timeLimit : restaurants) = maximum $ map pleasure (makePairs restaurants)\n where pleasure (rating, realTime) = rating - max 0 (realTime - timeLimit)\n makePairs [] = []\n makePairs (x:y:ys) = (x, y) : (makePairs ys)\n\nmain = interact $ show . solve . map read . words\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n (_:k:a) <- map (fst . fromJust . C.readInt) <$> C.words <$> C.getContents\n print $ maximum $ [f - max 0 (t - k) | (f, t) <- pairs a]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n os <- replicateM n getInts\n\n print $ maximum $ map (\\[f, t] -> if t >= k then f - (t-k) else f) os\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [[Int]] -> Int\nsolve k xs = maximum $ map (\\[f, t] -> if t > k then f - (t - k) else f) xs\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n xs <- replicateM n reads\n print $ solve k xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\nprocess::Integer->Integer->[[String]]->String\nprocess x n [] = (show x) ++ \" \" ++ (show n)\nprocess x n ((a:b:[]):cs) | a==\"+\" = process (x+bb) n cs\n | bb<= x = process (x-bb) n cs\n | otherwise = process x (n+1) cs\n where bb = read b ::Integer\n\n\nmain = do\n [a,k]<-map read <$> words <$> getLine ::IO [Int]\n d<- map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]\n print $ maximum $ map (\\[z1,z2]-> z1 - (if z2>k then z2-k else 0)) d\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array\nimport Data.Bits\n\nmain = do\n [n, k] <- getList\n a <- replicateM n getList\n let b = map (\\[f, t] -> if t > k then f-(t-k) else f) a\n print $ maximum b\n where\n getList = fmap (map read . words) getLine"}, {"source_code": "main=interact$show.s.map(map read.words).lines\ns([_,k]:g)=maximum[f-max(t-k)0|[f,t]<-g]\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Integer]] -> Integer\nsolve ([_, k] : fts) = maximum [ f - max 0 (t - k) | [ f, t ] <- fts ]\nsolve _ = undefined\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Integer]] -> Integer\nsolve ([_, k] : fts) = maximum [ if t > k then f - (t - k) else f | [ f, t ] <- fts ]\nsolve _ = undefined\n"}, {"source_code": "main = interact $ show . solve . parse . map read . tail . words\nparse (n:xs) = (n,pairs xs) where\n pairs (a:b:xs) = (a,b) : pairs xs\n pairs [] = []\nsolve (k,ps) = maximum $ map g ps where\n g (f,t) = f - max 0 (t-k)\n"}, {"source_code": "import Control.Monad\nmain = do\n s <- getLine\n let [n, k] = map read $ words s\n restaurants <- forM [1..n] (\\_ -> do\n s_i <- getLine\n let [f, t] = map read $ words s_i\n return (f, t))\n print . maximum . satisfactions k $ restaurants\n \nsatisfactions :: Int -> [(Int, Int)] -> [Int]\nsatisfactions k = foldl (\\acc (f, t) -> (if t > k then (f - (t - k)) else f) : acc) []\n"}, {"source_code": "main=interact$show.f.map read.words\nf :: [Integer] -> Integer\nf(n:k:fts) = maximum $ g fts\n where\n g (f:t:xs) = if t > k then (f - (t - k)) : g xs\n else f : g xs\n g _ = []"}, {"source_code": "module Main where\n\nsatisfaction :: Int -> [Int] -> Int\n{- satisfaction TimeLimit RestaurantParams -}\nsatisfaction limit params = let [sat, time] = params\n in\n if time > limit then sat - time + limit else sat\n\nmain = do\n paramStr <- getLine\n restaurantsStr <- getContents\n let [_, timeLimit] = map read $ words paramStr\n restaurants = (map (map read . words)) $ lines restaurantsStr\n print $ maximum $ map (satisfaction timeLimit) restaurants\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List \n \n\nmain= do\n\t[n,m]<- map read .words <$> getLine::IO [Int]\n\ts<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tprint $ maximum $ map (\\[a, b]-> if b<=m then a else a+m-b) s\n\t \n\n\t \n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\tline1 <- getLine\n\tcontent <- getContents\n\tlet\n\t\t[n, k] = map (\\x -> read x :: Integer). words $ line1\n\t\tarr = map (\\[x, y] -> (read x :: Integer, read y :: Integer) ). map words. lines $ content\n\t\tsolve [] = []\n\t\tsolve ((f, t): xs)\n\t\t | t > k = (f - t + k) : solve (xs)\n\t\t | otherwise = f : solve (xs)\n--\tprint content\n--\tprint arr\n\tprint $ maximum. solve $ arr\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain = B.getContents >>= putStr . show . solve . map readInt . B.words\n\npairs [] = []\npairs (x:y:xs) = (x,y) : pairs xs\n\nsolve (n:k:fts) = maximum . map eat . pairs $ fts\n where\n eat (f, t) \n | t > k = f - (t - k)\n | otherwise = f\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Function\nmain = do\n [n,k] <- map read . words <$> getLine\n rs <- partition (\\[f,t] -> t <= k) . map (map read . words) . take n . lines <$> getContents\n case fst rs of\n [] -> print $ maximum $ map (\\[f,t] -> f + k - t) $ snd $ rs\n lst -> case snd rs of\n [] -> print $ maximum $ map head $ lst\n lst' -> print$max (maximum $ map head $ lst) $ (maximum $ map (\\[f,t] -> f + k - t) $ snd $ rs)"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Function\nmain = do\n [n,k] <- map read . words <$> getLine\n rs <- partition (\\[f,t] -> t <= k) . map (map read . words) . take n . lines <$> getContents\n case fst rs of\n [] -> print $ maximum $ map (\\[f,t] -> f + k - t) $ snd $ rs\n lst -> print $ maximum $ map head $ lst"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Data.Function\nmain = do\n [n,k] <- map read . words <$> getLine\n rs <- partition (\\[f,t] -> t <= k) . map (map read . words) . take n . lines <$> getContents\n case fst rs of\n [] -> print $ minimum $ map (\\[f,t] -> f + k - t) $ snd $ rs\n lst -> print $ maximum $ map head $ lst"}], "src_uid": "1bb5b64657e16fb518d49d3c799d4823"} {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\n\nmain = do\n [t] <- getInts\n replicateM_ t do\n [n] <- getInts\n a <- getInts\n b <- getInts\n let result = sorted a || (elem 0 b && elem 1 b)\n putStrLn if result then \"Yes\" else \"No\"\n where\n sorted xs = all id $ zipWith (<=) xs (tail xs)\n\ngetInts :: IO [Int]\ngetInts = go <$> BS.getLine\n where\n go s = case BS.readInt s of\n Nothing -> []\n Just (x, s') -> x : go (BS.drop 1 s')", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO()\nmain = do\n [t] <- readInts\n replicateM_ t setup\n \nreadInts :: IO [Int]\nreadInts = map read.words <$> getLine\n\nisType :: Int -> (Int, Int) -> Bool\nisType t x = t == (snd x)\n\nsetup :: IO()\nsetup = do\n [n] <- readInts\n a <- readInts\n b <- readInts\n let c = zip a b\n let zeros = filter (isType 0) c\n let ones = filter (isType 1) c\n putStrLn (if solve a zeros ones then \"Yes\" else \"No\") \n \nsolve :: [Int] -> [(Int, Int)] -> [(Int, Int)] -> Bool\nsolve a zeros ones\n | length zeros > 0 && length ones > 0 = True\n | otherwise = a == (sort a)"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\n(|>) = flip ($)\n\nmain = do\n input <- getContents\n let _:vals = read <$> split input :: [Int]\n res = vals |> unfoldr (\\case\n [] -> Nothing\n n:rest0 ->\n let (subInput, rest1) = splitAt (2*n) rest0\n (vals, types) = splitAt n subInput\n isSorted = all (uncurry (<=)) adjPairs where\n adjPairs = zip vals $ tail vals\n hasBoth = hasZero && hasOne where\n hasZero = any (== 0) types\n hasOne = any (== 1) types\n subRes = if hasBoth || isSorted then \"Yes\" else \"No\"\n in Just (subRes, rest1)\n )\n sequence_ $ putStrLn <$> res\n"}], "negative_code": [], "src_uid": "4bf3a94119d08a9cd6075a67d0014061"} {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[n, m] <- popInts\n as <- popIntegers\n xs <- popIntegers\n return $ B.unwords $ map bshow $ solve n m as xs\n\n\nsolve n m as0 xs = map calc xs\n where\n a0 = head as0\n as = tail as0 ++ [a0]\n\n (csum, cmax, cmap) = foldl' foldf (0, 0, Map.empty) $ zip [0..] as\n\n foldf (s, mx, mp) (i, a) =\n let s' = s + a in\n if s' > mx\n then (s', s', Map.insert s' i mp)\n else (s', mx, mp)\n\n calc x | x <= a0 = 0\n | x <= a0 + cmax = 1 + calcSteps (x - a0)\n | csum <= 0 = -1\n | otherwise =\n let c = (x - a0 - cmax + csum - 1) `quot` csum in\n 1 + c * (fromIntegral n) + calcSteps (x - a0 - c * csum)\n\n calcSteps x = snd $ Map.findMin $ Map.dropWhileAntitone (< x) cmap\n\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\nimport qualified Data.Map.Strict as M\n\ntype SIO = StateT P.ByteString IO\n\nceilDiv :: Integral t => t -> t -> t\nceilDiv n k = div (n + k - 1) k\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, _m] <- readInts\n a <- readInts\n let\n sa = tail $ scanl (\\x y -> x + fromIntegral y) 0 a\n cycleIncr = last sa\n possibleStops = M.fromAscList $ do\n (i, val, score) <- zip3 [0..] sa $ scanl max minBound sa\n [(val, i) | val > score]\n highestStop = fst $ M.findMax possibleStops\n n64 = fromIntegral n\n x <- map fromIntegral <$> readInts\n putInt64s $ flip map x $ \\xi -> case M.lookupGE xi possibleStops of\n Just (_, i) -> i\n Nothing -> if cycleIncr <= 0\n then 0 - 1\n else let\n wastedCycles = ceilDiv (xi - highestStop) cycleIncr\n nxi = xi - wastedCycles * cycleIncr\n in case M.lookupGE nxi possibleStops of\n Just (_, i) -> wastedCycles * n64 + i\n Nothing -> error \"some arithmetic overflow or mistake?\"\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInt64s :: [Int64] -> SIO ()\nputInt64s li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "ecc9dc229b5d1f93809fb676eb6235c1"} {"source_code": "import Data.List\nimport Data.Word\n\nmain :: IO ()\nmain = do\n getLine\n answers <- map (solve . map read . words) <$> lines <$> getContents :: IO [String]\n mapM_ putStrLn answers\n\nsolve :: [Word64] -> String\nsolve [c,d] = intercalate \"b\" [genrep a1 'a', genrep a2 'a' , genrep a3 'a' ]\n where \n (a2,a1) = f d' (c-1) 0\n total = c*(c-1) `div` 2\n d' = total - d \n a3 = c - a1 - a2 - 2\n genrep = genericReplicate\n\nf :: Word64 -> Word64 -> Word64 -> (Word64, Word64)\nf d c i \n | d < c = (d,i)\n | otherwise = f (d-c) (c-1) (i+1)\n\n", "positive_code": [{"source_code": "import Control.Arrow\n\nmain = interact $ \n lines >>> drop 1 \n >>> map ((words >>> map read) >>> solve) \n >>> unlines\n\nsolve :: [Integer] -> String\nsolve [n, k] = reverse $ foldl1 (++) $ map copy \n [(j - 1, 'a'), (1, 'b'), (i - j - 1, 'a'), (1, 'b'), (n - i, 'a')] \n where\n copy (n, c) \n | n <= 0 = \"\"\n | otherwise = take (fromIntegral n) $ repeat c\n c2 v = (v * (v - 1)) `div` 2\n getfirst len rank\n | c2 len < rank = max len $ getfirst (len + 1) rank\n | otherwise = 0\n i = (getfirst 0 k) + 1\n j = k - (c2 (i - 1))\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, k] <- getIntList\n putStrLn . reverse . get n $ f n k\n\nf :: Int -> Int -> (Int, Int)\nf n k =\n let p = head . filter (\\x -> k <= cal x) $ [1 .. n - 1]\n q = k - cal (p - 1) - 1\n in (q, p)\n\ncal :: Int -> Int\ncal x = case x `mod` 2 of\n 0 -> x `div` 2 * (x + 1)\n 1 -> (x + 1) `div` 2 * x\n\nget :: Int -> (Int, Int) -> String\nget n (p, q) = (replicate p 'a')\n ++ \"b\"\n ++ (replicate (q - p - 1) 'a')\n ++ \"b\"\n ++ (replicate (n - q - 1) 'a')"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (genericReplicate)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\n\n\n\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO = do\n [n,k] <- getList\n putStrLn $ solve n k\n\nsolve :: Integer -> Integer -> String\nsolve 2 _ = \"bb\"\nsolve n k | k <= (n-1)*(n-2) `div` 2 = 'a' : solve (n-1) k\n | otherwise = let p = k - (n-1)*(n-2) `div` 2 - 1; q = n - 2 - p\n in \"b\" ++ genericReplicate q 'a' ++ \"b\" ++ genericReplicate p 'a'"}, {"source_code": "import Data.Maybe\nimport Control.Monad\n\nwork :: IO ()\nwork = do\n [n, k] <- map read . words <$> getLine\n let a = head $ filter (\\x -> (1 + x) * x `div` 2 >= k) [1 .. ]\n b = k - (a - 1) * a `div` 2 - 1\n putStrLn [let i = n - j in if i == a || i == b then 'b' else 'a' | j <- [1 .. n]]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n work\n"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n [n, k] <- map read . words <$> getLine\n let i1' = getidx 1 k\n let i2 = k - div (i1'*(i1'-1)) 2\n let i1 = i1' + 1\n putStrLn $\n replicate (fromInteger $ n - i1) 'a' ++\n \"b\" ++\n replicate (fromInteger $ i1 - i2 - 1) 'a' ++\n \"b\" ++\n replicate (fromInteger $ i2 - 1) 'a'\n\ngetidx :: Integer -> Integer -> Integer\ngetidx n k =\n if k <= n then\n n\n else\n getidx (n + 1) (k - n)\n"}, {"source_code": "convertToString :: Int -> (Int,Int) -> String\nconvertToString l (b1,b2) = (replicate b1 'a')++\"b\"++(replicate (b2-b1-1) 'a')++\"b\"++(replicate (l-b2-1) 'a')\n\nnextString :: Int -> Int -> (Int,Int) -> (Int,Int)\nnextString 1 _ found = found\nnextString k l (lfirstB,lsecondB) = if (lsecondB-lfirstB)==1\n then nextString (k-1) l (lfirstB-1,l-1)\n else nextString (k-d) l (lfirstB,lsecondB-d)\n where diff = (lsecondB-lfirstB-1)\n d = if diff > (k-1)\n then (k-1)\n else diff\n\n\nkthString :: [Int] -> String\nkthString (n:k:[]) = convertToString n $ nextString k n (n-2,n-1)\n\nmain :: IO()\nmain = do\n interact $ unlines . map (kthString . (map read) . words) . tail . lines\n"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\n\n\n\n\nmain = readLn >>= flip replicateM_ solveIO\n\nsolveIO = do\n [n,k] <- getList\n putStrLn $ solve n k\n\nsolve :: Int -> Int -> String\nsolve 2 _ = \"bb\"\nsolve n k | k <= (n-1)*(n-2) `div` 2 = 'a' : solve (n-1) k\n | otherwise = let p = k - (n-1)*(n-2) `div` 2 - 1; q = n - 2 - p\n in \"b\" ++ replicate q 'a' ++ \"b\" ++ replicate p 'a'"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n [n, k] <- map read . words <$> getLine\n let i1' = getidx 1 k\n let i2 = k - div (i1'*(i1'-1)) 2\n let i1 = i1' + 1\n putStrLn $\n replicate (n - i1) 'a' ++\n \"b\" ++\n replicate (i1 - i2 - 1) 'a' ++\n \"b\" ++\n replicate (i2 - 1) 'a'\n \ngetidx n k =\n if k <= n then\n n\n else\n getidx (n + 1) (k - n)\n"}, {"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM_ numTests $ do\n [n, k] <- map read . words <$> getLine\n let i1' = getidx 1 k\n let i2 = k - div (i1'*(i1'-1)) 2\n let i1 = i1' + 1\n putStrLn $\n replicate (n - i1) 'a' ++\n \"b\" ++\n replicate (i1 - i2 - 1) 'a' ++\n \"b\" ++\n replicate (i2 - 1) 'a'\n \n\ngetidx n k =\n if k <= n then\n n\n else\n getidx (n + 1) (k - n)\n"}], "src_uid": "e32f0615541d97a025bc99c3cbf5380e"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\noutput as k = \n let\n small = minimum as\n large = maximum as\n in if large - small > 2 * k\n then print $ -1\n else print $ small + k\n\ninspect 0 = putStr \"\"\ninspect n = do\n line <- getLine\n let _:k:_ = map read $ words line\n line2 <- getLine\n let as = map read $ words line2\n output as k\n inspect $ n - 1\n\nmain = do\n line <- getLine\n inspect $ read line\n", "positive_code": [{"source_code": "readInt :: String -> Int\nreadInt = read\n\nmain = interact $ solve . (map ((map readInt) . words)) . tail . lines\n\nsolve :: [[Int]] -> String\nsolve [] = \"\"\nsolve ([n, k]:a:rest) = (solveInstance [n, k] a) ++ solve rest\n\nvalidRange :: (Int, Int) -> Bool\nvalidRange (a, b) = a <= b\n\nmaxElem :: (Int, Int) -> Int\nmaxElem (a, b) | validRange (a, b) = b\n | otherwise = -1\n\nsolveInstance :: [Int] -> [Int] -> String\nsolveInstance [_, k] a =\n let ranges = (map (\\x -> (max 1 (x-k), x+k)) a) in\n let range = foldl (\\(a, b) (c, d) -> (max a c, min b d)) (head ranges) ranges in\n ((++\"\\n\") . show . maxElem) range\n"}, {"source_code": "import Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let m = minimum as\n print $ if maximum as - m > 2*k then -1\n else m + k\n"}], "negative_code": [], "src_uid": "3b158306d335459ff55dcf29e46010e8"} {"source_code": "main = do\n\t[a, b, n] <- fmap (map read . words) getLine\n\tputStrLn $ last $ \"No solution\" : [show x | x <- [-1000 .. 1000], a * x ^ n == b]\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Maybe\n\nmain = do\n [a, b, n] <- ( map read . words ) `liftM` getLine\n\n putStrLn $ maybe \"No solution\" show $ do\n if a == 0\n then if b == 0\n then return 1\n else fail \"\"\n else do\n if b `mod` a == 0\n then return ()\n else fail \"\"\n\n let b' = abs $ b `div` a\n sign = b `div` a < 0\n x = round $ ( fromIntegral b' ) ** ( 1 / fromIntegral n )\n\n if sign && even n\n then fail \"\"\n else return ()\n\n if x ^ n == b'\n then return ()\n else fail \"\"\n\n if sign\n then return (-x)\n else return x\n"}, {"source_code": "\nimport Maybe (listToMaybe)\n\nsolve :: Integer -> Integer -> Integer -> Maybe Integer\nsolve a b n = listToMaybe $ [x | x <- [-1000 .. 1000], a * x^n == b]\n\nmain :: IO ()\nmain = do\n [a, b, n] <- fmap (map read . words) getLine\n putStrLn $ maybe \"No solution\" show $ solve a b n\n"}, {"source_code": "findAllBases target exponent = filter (\\x -> x ^ exponent == target) [minBound..maxBound]\n where minBound = min (-target) target\n maxBound = max target (-target)\n\nfindBase target exponent = if (length solutions == 0) then \"No solution\" else show (head solutions)\n where solutions = findAllBases target exponent\n\nsolve _ 0 _ = \"0\"\nsolve 0 _ _ = \"No solution\"\nsolve a b n | (mod b a) /= 0 = \"No solution\"\n | otherwise = findBase (div b a) n\n\nmain = do\n inputLine <- getLine\n let tmp = words inputLine\n let a = read (tmp !! 0) :: Int\n let b = read (tmp !! 1) :: Int\n let n = read (tmp !! 2) :: Int\n putStrLn (solve a b n)\n\n"}, {"source_code": "import Control.Applicative\n\nsolve a b n = map fst $ filter ((==b).snd) [(x, a*(x^n)) | x <- [-1500..1500]]\n\nints = map read . words <$> getLine\n\nmain = do\n [a, b, n] <- ints\n case solve a b n of\n x:xs -> print x\n [] -> putStrLn \"No solution\"\n"}, {"source_code": "import Data.Maybe (listToMaybe)\nimport Control.Applicative ((<|>))\n\nmain :: IO ()\nmain = getContents >>= putStrLn . maybe \"No solution\" show . (\\[ a, b, x ] -> solve a b x) . map read . words\n\nsolve :: Integer -> Integer -> Integer -> Maybe Integer\nsolve a b n = listToMaybe [ 1 | a == 0 && b == 0 ] <|> listToMaybe [ x | a /= 0 && a * x ^ n == b ]\n where x = signum (a * b) * round (exp (log (abs $ fromIntegral $ b `div` a) / fromIntegral n) :: Double)\n"}, {"source_code": "import Data.Maybe (listToMaybe)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . maybe \"No solution\" show . (\\[ a, b, x ] -> solve a b x) . map read . words\n\nsolve :: Integer -> Integer -> Integer -> Maybe Integer\nsolve a b n = listToMaybe [ x | x <- [-1000..1000], a * x ^ n == b ]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Bits\nimport Data.Ord\nimport Data.Function\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n a : b : n :_ <- map read . words <$> getLine\n case [x | x <- [-1000 .. 1000], a * x ^ n == b] of\n x : _ -> print x\n _ -> putStrLn \"No solution\"\n\n\n"}, {"source_code": "main = interact (ans)\na x = read((words x)!!0)::Integer\nb x = read((words x)!!1)::Integer\nn x = read((words x)!!2)::Integer\nsol x=[y|y<-[1000,999..(-1000)], a x*y^n x==b x]\ntmp []=\"No solution\"\ntmp xs=show(head xs)\nans x = tmp(sol(x))\n"}], "negative_code": [{"source_code": "\nimport Maybe (listToMaybe)\n\nsolve :: Int -> Int -> Int -> Maybe Int\nsolve a b n = listToMaybe $ [x | x <- [-1000 .. 1000], a * x^n == b]\n\nmain :: IO ()\nmain = do\n [a, b, n] <- fmap (map read . words) getLine\n putStrLn $ maybe \"No solution\" show $ solve a b n\n"}, {"source_code": "import Control.Applicative\n\nsolve a b n = map fst $ filter ((==b).snd) [(x, a*x^n) | x <- [-1000..1000]]\n\nints = map read . words <$> getLine :: IO [Int]\n\nmain = do\n [a, b, n] <- ints\n case solve a b n of\n x:xs -> print x\n [] -> putStrLn \"No solution\"\n"}], "src_uid": "8a9adc116abbd387a6a64dd754436f8a"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust, fromMaybe)\r\nimport Data.List (inits, tails)\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf (C.pack <$> testCase)) >>> C.unlines\r\n\r\ntestCase :: Scanner String\r\ntestCase = show <$> (compute <$> string <*> string)\r\n\r\nsubstrings :: [a] -> [[a]]\r\nsubstrings = tail . inits <=< tails\r\n\r\ncompute :: String -> String -> Int\r\ncompute a b = length a + length b - 2 * foldl max 0 [length s | s <- substrings a, t <- substrings b, s == t]\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstring :: Scanner String\r\nstring = C.unpack <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n", "positive_code": [{"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\nimport Data.Bits((.&.), (.|.), xor)\r\nimport Data.Maybe\r\n\r\ndata Trie = Trie (M.Map Char Trie)\r\n\r\nmakeTrieWith :: String -> [String] -> Trie\r\nmakeTrieWith alpha str = Trie $ M.fromList $ alpha >>= \\a-> case [xs | x:xs <- str , x == a] of \r\n\ts@(_:_) -> [(a, makeTrieWith alpha s)]\r\n\t[] -> []\r\n\r\nlazyTrie str = makeTrieWith \"azertyuiopqsdfghjklmwxcvbn\" $ suffixes str\r\nsuffixes [] = [[]]\r\nsuffixes (x:xs) = (x:xs) : suffixes xs\r\n\r\n\r\nresult a b = (length a) + (length b) - 2 * val where\r\n\ttreeA = lazyTrie a \r\n\ttreeB = lazyTrie b\r\n\r\n\taux0 (Trie t1) (Trie t2) = if null t3 then 0 else 1 + foldr max 0 t3 where\r\n\t\tt3 = M.intersectionWith aux0 t1 t2\r\n\r\n\tval = aux0 treeA treeB\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\ta <- getLine\r\n\t\tb <- getLine\r\n\t\tprint $ result a b\r\n\t\tloop $ t - 1\r\n\tloop t"}], "negative_code": [], "src_uid": "36aec7a06c02052f562ea3d44d4a62e4"} {"source_code": "\nmain = do\n [p,q,l,r] <- fmap (map read . words) getLine\n z <- mapM g [1..p]\n x <- mapM g [1..q]\n print (solve (l, r) x z)\n where \n g _ = do\n [x,y] <- fmap (map read . words) getLine\n return (x, y)\n\nsolve :: (Int, Int) -> [(Int, Int)] -> [(Int, Int)] -> Int\nsolve (l, r) x z = length . filter f $ [l..r]\n where \n f v = any g x\n where \n g (ci, di) = intersect (ci +v) (di + v) z\n intersect c d z = any h z\n where \n h (a,b) = (c <= a && d >= a) || (c >= a && c <= b)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . getAns . getIntArray\n\nreAssign :: [Int] -> [(Int, Int)]\nreAssign [] = []\nreAssign (x:y:xs) = (x,y) : reAssign xs\n\ngetAns :: [Int] -> Int\ngetAns (p:q:l:r:xs) = calSum l r ps qs\n\t\twhere ps = reAssign ls;\n\t\t\t qs = reAssign rs;\n\t\t\t (ls, rs) = splitAt (p * 2) xs\n\ncalSum l r ps qs = sum [haveCommon ps $ map (\\(a, b) -> (a + t, b + t)) qs | t <- [l .. r]]\n\noverLap :: ((Int, Int), (Int, Int)) -> Bool\noverLap ((x1, y1), (x2, y2)) = (x1 >= x2 && x1 <= y2) || (y1 >= x2 && y1 <= y2) || (x2 >= x1 && x2 <= y1) || (y2 >= x1 && y2 <= y1)\n\nhaveCommon ps qs = if any overLap [(p, q) | p <- ps, q <- qs] then 1 else 0\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [p, q, l, r] <- fmap (map read . words) getLine\n abs <- replicateM p $ (fmap (map read . words)) getLine\n cds <- replicateM q $ (fmap (map read . words)) getLine\n\n let\n check x = f (sort abs) (sort cds)\n where\n f [] _ = False\n f _ [] = False\n f ([a, b]:abs) ([c, d]:cds)\n | b < c+x = f abs ([c, d]:cds)\n | d+x < a = f ([a, b]:abs) cds\n | otherwise = True\n\n print $ length $ filter check [l..r]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\ntoTuple :: [String] -> (Int,Int)\ntoTuple [x,y] = (read x, read y)\n\ninInt :: [(Int,Int)] -> [(Int,Int)] -> Bool\ninInt xs ys = or [x2 >= y1 && x1 <= y2| (x1,x2) <- xs, (y1,y2) <- ys]\n\nmain = do\n [p,q,l,r] <- map read . words <$> getLine\n zs <- map (toTuple . words) <$> replicateM p getLine\n xs <- map (toTuple . words) <$> replicateM q getLine\n print . sum $ [if inInt (map (\\(x,y) -> (x+i,y+i)) xs) zs then 1 else 0 | i <- [l..r]]\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\n\nmain :: IO ()\nmain = print =<< solve <$> (toQuadruple . map read . words <$> getLine)\n <*> (map (toTuple . map read . words) . lines <$> getContents)\n\nsolve :: (Int, Int, Int, Int) -> [(Int, Int)] -> Int\nsolve (p, _, l, r) abcd\n = sum [ fromEnum $ or [ c + t <= b && a <= d + t | (a, b) <- ab, (c, d) <- cd ] | t <- [l..r] ]\n where (ab, cd) = splitAt p abcd\n\ntoTuple :: [a] -> (a, a)\ntoTuple xs = (head xs, xs !! 1)\n\ntoQuadruple :: [a] -> (a, a, a, a)\ntoQuadruple xs = (head xs, xs !! 1, xs !! 2, xs !! 3)\n"}, {"source_code": "import Control.Monad (liftM, forM)\nimport Data.Array (listArray, (!))\n\nfor = flip map\n\ntrues = repeat True\nfalses = repeat False\n\ninput = do\n ln <- getLine\n return $ map read $ words ln\n\nmor :: [[Bool]] -> [Bool]\nmor = foldl1 $ zipWith (||)\n\nmain = do\n [p, q, l, r] <- input\n let g n = liftM mor $ forM [1..n] $ \\_ -> do\n [a, b] <- input\n return $ (take a falses ++ take (b-a+1) trues ++ take (1001-b) falses)\n ipx <- g p\n iqx <- g q\n let ip = listArray (0, 1001) ipx\n let iq = listArray (0, 1001) iqx\n let li = for [l..r] (\\i -> fromEnum $ or $ for [0..1001-i-1] (\\j -> ip ! (i+j) && iq ! j))\n putStrLn $ show $ sum li"}], "negative_code": [{"source_code": "import Control.Monad (liftM, forM)\nimport Data.Array\n\nmain = do\n return ()"}], "src_uid": "aa77158bf4c0854624ddd89aa8b424b3"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Map.Strict as M\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n wood <- take n . C.unpack <$> C.getLine\n let (_, _, _, rs) = foldl' acc (M.empty, 0, 0, []) wood\n acc (mp, x, y, results) name =\n case M.lookup frac mp of\n Nothing -> (M.insert frac 1 mp, x', y', 1 : results)\n Just num -> (M.insert frac (num + 1) mp, x', y', (num + 1) : results)\n where\n (x', y')\n | name == 'D' = (x + 1, y)\n | otherwise = (x, y + 1)\n frac = (x' `div` g, y' `div` g)\n where g = gcd x' y'\n return $ mconcat (intersperse (charUtf8 ' ') $ map intDec $ reverse rs) `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "import qualified Data.Map.Strict as M\nimport Data.Ratio\nimport Control.Monad\nimport Control.Monad.State\nimport Control.Arrow\nimport Data.Maybe (fromJust)\n\n\n--type Tracker = (State )\n\ntype Tracker = State (Int, Int, M.Map (Ratio Int) Int)\n\nhelper :: Maybe Int -> Maybe Int\nhelper Nothing = Just 1\nhelper (Just x) = Just (x + 1)\n\ngoOne :: Char -> Tracker Int\ngoOne c = do (ds, ks, mm) <- get\n if c == 'D'\n then put (ds + 1, ks, mm)\n else put (ds, ks + 1, mm)\n (ds1, ks1, mm1) <- get\n let key = if ks1 == 0 then (-1) % 1 else ds1 % ks1\n mmm = M.alter helper key mm1\n --nt = fromJust $ M.lookup key mmm\n nt = mmm M.! key\n in do put (ds1, ks1, mmm)\n return nt\n\n\ngoMany :: String -> Tracker [Int]\ngoMany = mapM goOne\n\ndropEvrySnd [] = []\ndropEvrySnd (x:y:xs) = y : dropEvrySnd xs\n\nrunner :: String -> String\nrunner = words\n >>> drop 1\n >>> dropEvrySnd\n >>> map goMany\n >>> map (flip evalState (0, 0, M.empty))\n >>> map (map show >>> unwords)\n >>> unlines\n\n\n\nmain = interact runner\n"}, {"source_code": "import qualified Data.Map.Strict as M\nimport Data.Ratio\nimport Control.Monad\nimport Control.Monad.State\nimport Control.Arrow\nimport Data.Maybe (fromJust)\n\n\n--type Tracker = (State )\n\ntype Tracker = State (Int, Int, M.Map (Ratio Int) Int)\n\nhelper :: Maybe Int -> Maybe Int\nhelper Nothing = Just 1\nhelper (Just x) = Just (x + 1)\n\ngoOne :: Char -> Tracker Int\ngoOne c = do (ds, ks, mm) <- get\n if c == 'D'\n then put (ds + 1, ks, mm)\n else put (ds, ks + 1, mm)\n (ds1, ks1, mm1) <- get\n let key = if ks1 == 0 then (-1) % 1 else ds1 % ks1\n mmm = M.alter helper key mm1\n nt = fromJust $ M.lookup key mmm\n in do put (ds1, ks1, mmm)\n return nt\n\n\ngoMany :: String -> Tracker [Int]\ngoMany = mapM goOne\n\ndropEvrySnd [] = []\ndropEvrySnd (x:y:xs) = y : dropEvrySnd xs\n\nrunner :: String -> String\nrunner = words\n >>> drop 1\n >>> dropEvrySnd\n >>> map goMany\n >>> map (flip evalState (0, 0, M.empty))\n >>> map (map show >>> unwords)\n >>> unlines\n\n\n\nmain = interact runner\n"}, {"source_code": "import qualified Data.Map as Map\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nreadIntLine :: IO [Int]\r\nreadIntLine = fmap (map read.words) getLine\r\n\r\nevaluate s = dfs s Map.empty 0 0\r\n where dfs :: String -> Map.Map (Integer, Integer) Integer -> Integer -> Integer -> [Integer]\r\n dfs \"\" _ _ _ = []\r\n dfs (a:as) mp d k = value : dfs as mp' d' k'\r\n where d' = if a == 'D' then (d + 1) else d \r\n k' = if a == 'K' then (k + 1) else k\r\n g = gcd d' k' \r\n value =(+) 1 $ match $ Map.lookup (d' `div` g, k' `div` g) mp\r\n where match Nothing = 0\r\n match (Just a) = a\r\n mp' = Map.insert (d' `div` g, k' `div` g) value mp\r\n\r\nsolve = do\r\n [n] <- readIntLine\r\n s <- getLine\r\n putStrLn (intercalate \" \" $ Prelude.map show $ evaluate s)\r\n return ()\r\n\r\nmain = do \r\n [t] <- readIntLine\r\n replicateM t solve\r\n return () \r\n"}, {"source_code": "import Control.Monad (replicateM)\r\nimport qualified Data.Map.Strict as Map\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nsolve = do t <- getLine\r\n arr <- getLine\r\n let ans = iterateOver 0 0 (Map.fromList []) arr\r\n putStrLn $ unwords $ map show ans\r\n\r\niterateOver :: Int -> Int -> Map.Map (Int,Int) Int -> String -> [Int]\r\niterateOver dcnt kcnt _map [] = []\r\niterateOver dcnt kcnt _map ('D':xs) = sub : (iterateOver (dcnt+1) kcnt new_map xs)\r\n where key_gcd = gcd (dcnt+1) kcnt\r\n key = ((dcnt+1) `div` key_gcd,kcnt `div` key_gcd)\r\n sub = Map.findWithDefault 0 key _map + 1\r\n new_map = Map.insertWith (+) key 1 _map\r\n\r\niterateOver dcnt kcnt _map ('K':xs) = sub : (iterateOver dcnt (kcnt+1) new_map xs)\r\n where key_gcd = gcd (dcnt) (kcnt+1)\r\n key = (dcnt `div` key_gcd,(kcnt+1) `div` key_gcd)\r\n sub = Map.findWithDefault 0 key _map + 1\r\n new_map = Map.insertWith (+) key 1 _map\r\n"}, {"source_code": "import Data.List (intercalate)\r\nimport Control.Monad (mapM, replicateM)\r\nimport Data.Ratio ((%))\r\nimport Data.Map (empty, findWithDefault, insert)\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nsolve = do getLine\r\n s <- getLine\r\n putStrLn (intercalate \" \" (map show (maxBlocks s)))\r\n\r\nmaxBlocks s = helper s empty 0 0\r\n where helper \"\" _ _ _ = []\r\n helper (c:s) prev d k = x : helper s prev' d' k'\r\n where (d', k') | c == 'D' = (d + 1, k)\r\n | c == 'K' = (d, k + 1)\r\n r | k' == 0 = 69000000 % 1\r\n | otherwise = d' % k'\r\n x = (findWithDefault 0 r prev) + 1\r\n prev' = insert r x prev"}], "negative_code": [], "src_uid": "de2e2e12be4464306beb0217875f66c7"} {"source_code": "import Data.List\n\nunique = map head . group . sort\n\nmain = do\n [n, k] <- fmap (map (read :: String -> Integer) . words) $ getLine\n a <- fmap (map ((`mod` k) . (read :: String -> Integer)) . words) $ getLine\n\n let d = foldl1 gcd (unique a)\n let answer = unique $ map (\\x -> x * d `mod` k) [0..k - 1]\n\n print . length $ answer\n putStrLn . unwords . map show $ answer\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n [_, k] <- fmap (map read . words) getLine\n a <- fmap (map read . words) getLine\n let g = foldl' gcd k a\n print $ k `div` g\n putStrLn $ unwords . map show . takeWhile (< k) $ iterate (+g) 0\n"}, {"source_code": "import Data.List\n\ntoint s = (read s) :: Int\n\nsolve::String -> String\nsolve ss =\n let (n:k:aa) = map toint $ words ss in\n let a = map (\\x -> (mod x k)) aa in\n let g = gcd (foldr gcd 0 a) k in\n (show (div k g)) ++ \"\\n\" ++ (intercalate \" \" $ map show [0,g..k-1]) ++ \"\\n\"\n\nmain = interact solve"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\n-- gcd :: Int -> Int -> Int\n-- gcd a 0 = a\n-- gcd a b = gcd b $ a `div` b\n\ngen :: [Int] -> Int -> Int -> Int -> [Int]\ngen res denom k x | denom == x = res\ngen res denom k x = gen (x:res) denom k $ (x + denom) `mod` k\n\nmain = do\n n:k:[] <- fmap (map read . words) getLine\n a <- fmap (map read . words) getLine\n let vals = filter (/=0) $ map (`mod` k) a\n if null vals then do\n print 1\n print 0\n else do\n let denom = foldl1 gcd vals\n let res = sort $ gen [denom] denom k ((denom * 2) `mod` k)\n print $ length res\n forM_ res $ \\x-> do\n putStr $ show x\n putStr \" \"\n putStrLn \"\""}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap (map (read :: String -> Int) . words) $ getLine\n a <- fmap (map ((`mod` k) . (read :: String -> Int)) . words) $ getLine\n\n let d = foldl1 gcd a\n let answerCandidate = map (* d) [0..k - 1]\n\n let answer = if 0 `elem` a then [0] else answerCandidate\n\n print . length $ answer\n putStrLn . unwords . map show . sort $ answer\n"}, {"source_code": "main = do\n [n, k] <- fmap (map (read :: String -> Int) . words) $ getLine\n a <- fmap (map ((`mod` k) . (read :: String -> Int)) . words) $ getLine\n\n let d = foldl1 gcd a\n let answer = map (* d) [0..(k - 1) `div` d]\n\n let (l1, l2) = if 0 `elem` a then (1, [0]) else (length answer, answer)\n\n print l1\n putStrLn . unwords . map show $ l2\n\n"}, {"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap (map (read :: String -> Integer) . words) $ getLine\n a <- fmap (map ((`mod` k) . (read :: String -> Integer)) . words) $ getLine\n\n let d = foldl1 gcd a\n let answerCandidate = map (\\x -> x * d `mod` k) [0..k - 1]\n\n let answer = if 0 `elem` a then [0] else map head . group . sort $ answerCandidate\n\n print . length $ answer\n putStrLn . unwords . map show $ answer\n"}, {"source_code": "import Data.List\n\nmain = do\n [n, k] <- fmap (map (read :: String -> Int) . words) $ getLine\n a <- fmap (map ((`mod` k) . (read :: String -> Int)) . words) $ getLine\n\n let d = foldl1 gcd a\n let answerCandidate = map (\\x -> x * d `mod` k) [0..k - 1]\n\n let answer = if 0 `elem` a then [0] else map head . group . sort $ answerCandidate\n\n print . length $ answer\n putStrLn . unwords . map show $ answer\n"}], "src_uid": "c9c3fabde66856667c338d71e17f6418"} {"source_code": "-- 1687A\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ParallelListComp #-}\n\nimport Control.Monad (replicateM_)\nimport Data.Array.IArray\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n [n, k] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n print $ if n < k then solve2 n k as else solve1 n k as\n\nsolve1 :: Int -> Int -> [Int] -> Int\n-- solve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)\nsolve1 n k as = ((k-1)*k) `div` 2 + ksum'' k ss\n where\n -- ksum n k as = ksum' n k as \n ss = 0 : [a + s | a <- as | s <- ss]\n ksum'' k sums = maximum [s2 - s1 | s2 <- drop k ss | s1 <- ss]\n ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))\n ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)\n ksum' _ [] _ = []\n ksum' [] _ _ = []\n\nsolve2 :: Int -> Int -> [Int] -> Int\nsolve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)\n", "positive_code": [{"source_code": "-- 1687A\n{-# LANGUAGE Strict #-}\n\nimport Control.Monad (replicateM_)\nimport Data.Array.IArray\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n [n, k] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n print $ if n < k then solve2 n k as else solve1 n k as\n\nsolve1 :: Int -> Int -> [Int] -> Int\nsolve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)\n where\n -- ksum n k as = ksum' n k as \n ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))\n ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)\n ksum' _ [] _ = []\n ksum' [] _ _ = []\n\nsolve2 :: Int -> Int -> [Int] -> Int\nsolve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)\n"}, {"source_code": "-- 1687A\n\nimport Control.Monad (replicateM_)\nimport Data.Array.IArray\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n [n, k] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n print $ if n < k then solve2 n k as else solve1 n k as\n\nsolve1 :: Int -> Int -> [Int] -> Int\nsolve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)\n where\n -- ksum n k as = ksum' n k as \n ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))\n ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)\n ksum' _ [] _ = []\n ksum' [] _ _ = []\n\nsolve2 :: Int -> Int -> [Int] -> Int\nsolve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)\n"}, {"source_code": "-- 1687A\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE ParallelListComp #-}\n\nimport Control.Monad (replicateM_)\nimport Data.Array.IArray\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t run\n\nrun :: IO ()\nrun = do\n [n, k] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n print $ if n < k then solve2 n k as else solve1 n k as\n\nsolve1 :: Int -> Int -> [Int] -> Int\n-- solve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)\nsolve1 n k as = ((k-1)*k) `div` 2 + ksum'' k ss\n where\n -- ksum n k as = ksum' n k as \n ss = 0 : [a + s | a <- as | s <- ss]\n ksum'' k sums = maximum [s2 - s1 | s2 <- drop k ss | s1 <- ss]\n -- ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))\n -- ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)\n -- ksum' _ [] _ = []\n -- ksum' [] _ _ = []\n\nsolve2 :: Int -> Int -> [Int] -> Int\nsolve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)\n"}], "negative_code": [], "src_uid": "e092d58ac58e1e41d17be946128234e5"} {"source_code": "import Data.Array as A\nimport Data.List\n\nmain = interact $ printAns. (\\(a,b,c) -> solve a b c). readInp\n\nreadInp = prep. split. fmap (fmap read. words). lines\n where split a = (a !! 0 !! 0, init. tail $ a, last a)\n prep = fork (id, fmap toTpl, id)\n where fork (f, g, h) (a, b, c) = (f a, g b, h c)\n toTpl a = (a !! 0, a !! 1)\n\nprintAns x = case x of\n Nothing -> \"NO\"\n Just v -> unlines [\"YES\", show v]\n\nsolve :: Int -> [(Int, Int)] -> [Int] -> Maybe Int\nsolve n edges colors = \n fmap fst. find sufficient. A.assocs. countForVertices $ importantEdges\n where \n importantEdges = filter isImportant edges\n where isImportant (u, v) = colorArr A.! u /= colorArr A.! v\n colorArr = A.listArray bounds colors\n countForVertices = A.accumArray (\\v _ -> v+1) 0 bounds. undirect\n where undirect = concatMap (\\(u,v) -> [(u,v), (v,u)])\n sufficient = (== (length importantEdges)). snd\n bounds = (1, n)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE MultiWayIf #-}\n-- {-# LANGUAGE BangPatterns #-}\n-- {-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TupleSections #-}\n\nimport System.IO hiding (char8)\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Int\nimport Data.Char\nimport Data.Function (on)\nimport Data.Array\n-- import Data.Array.Unboxed\n-- import Data.Array.IArray\n-- import Data.Array.ST\n-- import Data.Array.MArray\n-- import Data.Array.Unsafe\nimport Data.Ix\nimport Data.Maybe\nimport Data.Monoid hiding ((<>))\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.ByteString.Builder\nimport Data.Graph\n-- import Data.Vector.Unboxed ((//), (++), (!), (!?))\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.IntSet (IntSet)\n-- import qualified Data.IntSet as S\n-- import Data.IntMap.Strict (IntMap)\n-- import qualified Data.IntMap.Strict as M\n-- import Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))\n-- import qualified Data.Sequence as S\n-- import Debug.Trace\n\nmain = do\n v <- readInt1 <$> BS.getLine\n es <- map readInt2 <$> replicateM (v-1) BS.getLine\n cs <- readIntN <$> BS.getLine\n -- print $ fst . maximumBy (compare `on` snd) . assocs . outdegree . buildG (1,v) $ es ++ map swap es\n format $ solve v es cs\n\nformat :: Maybe Int -> IO ()\nformat Nothing = putStrLn \"NO\"\nformat (Just a) = do\n putStrLn \"YES\"\n print a\n\nhist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b\nhist bnds is = accumArray (+) 0 bnds [(i, 1) | i<-is, inRange bnds i]\n\nsolve :: Int -> [Edge] -> [Int] -> Maybe Int\nsolve v es cs = if\n | uniColor cs -> Just 1\n | maxDiffEdges == cntDiffColor (edges graph) -> Just maxDiffNode\n | otherwise -> Nothing\n where\n uniColor (c:cs) = all (==c) cs\n graph = buildG (1,v) $ es ++ map swap es\n -- maxDegNode = fst . maximumBy (compare `on` snd) . assocs $ outdegree graph\n -- maxDegEdges = map (,maxDegNode) $ graph!maxDegNode\n color = listArray (1,v) cs\n isDiffColor (a,b) = (color!a) /= (color!b)\n cntDiffColor = length . filter isDiffColor\n diffEdgeHist = hist (1,v) . concatMap fromTuple . filter isDiffColor $ edges graph\n maxDiffEdges = maximum $ elems diffEdgeHist\n maxDiffNode = fst . maximumBy (compare `on` snd) . assocs $ diffEdgeHist\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\nreadInt1 :: BS.ByteString -> Int\nreadInt1 = fst . fromJust . BS.readInt \n\nreadInt2 :: BS.ByteString -> (Int,Int)\nreadInt2 = toTuple . readIntN\n\nreadInt3 :: BS.ByteString -> (Int,Int,Int)\nreadInt3 = toTriple . readIntN\n\nreadIntN :: BS.ByteString -> [Int]\nreadIntN = map readInt1 . BS.words\n\nreadInt641 :: BS.ByteString -> Int64\nreadInt641 = fromIntegral . fst . fromJust . BS.readInteger\n\nreadInt642 :: BS.ByteString -> (Int64,Int64)\nreadInt642 = toTuple . readInt64N\n\nreadInt643 :: BS.ByteString -> (Int64,Int64,Int64)\nreadInt643 = toTriple . readInt64N\n\nreadInt64N :: BS.ByteString -> [Int64]\nreadInt64N = map readInt641 . BS.words\n\nreadInteger1 :: BS.ByteString -> Integer\nreadInteger1 = fst . fromJust . BS.readInteger \n\nreadInteger2 :: BS.ByteString -> (Integer,Integer)\nreadInteger2 = toTuple . readIntegerN\n\nreadInteger3 :: BS.ByteString -> (Integer,Integer,Integer)\nreadInteger3 = toTriple . readIntegerN\n\nreadIntegerN :: BS.ByteString -> [Integer]\nreadIntegerN = map readInteger1 . BS.words\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] =(x, y, z)\n\nfromTuple :: (a, a) -> [a]\nfromTuple (x, y) = [x, y]\n\nfromTriple :: (a, a, a) -> [a]\nfromTriple (x, y, z) = [x, y, z]\n\n-- if not applying, use \"const\"\n\napplyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')\napplyTuple f g (x, y) = (f x, g y)\n\napplyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')\napplyTriple f g h (x, y, z) = (f x, g y, h z)"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array\nimport Data.Tuple\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = map readInt . B.words\n\nsolve :: Int -> [(Int, Int)] -> [Int] -> Maybe Int\nsolve n g cs' = \n let\n bnd = (1, n)\n cs = listArray bnd cs'\n diffs = filter (\\(u, v) -> cs!u /= cs!v) g\n ln = length diffs\n in\n fst <$> (find (\\(u, c) -> c == ln) . assocs . accumArray (\\c u -> c + 1) 0 bnd $ concatMap (\\(u, v) -> [(u, v), (v, u)]) diffs)\n\nmain = do\n n <- readInt <$> B.getLine\n g <- map ((\\(u:v:_) -> (u, v)) . readInts) <$> replicateM (n - 1) B.getLine\n cs <- readInts <$> B.getLine\n putStrLn $ maybe \"NO\" ((\"YES\\n\" ++) . show) $ solve n g cs"}, {"source_code": "import Data.Array as A\nimport Data.List\n\nmain = interact $ printAns. (\\(a,b,c) -> solve a b c). readInp\n\nreadInp = prep. split. fmap (fmap read. words). lines\n where split a = (head a !! 0, init. tail $ a, last a)\n prep = fork (id, fmap toTpl, id)\n where fork (f, g, h) (a, b, c) = (f a, g b, h c)\n toTpl a = (a !! 0, a !! 1)\n\nprintAns x = case x of\n Nothing -> \"NO\"\n Just v -> unlines [\"YES\", show v]\n\nsolve :: Int -> [(Int, Int)] -> [Int] -> Maybe Int\nsolve n edges colors = \n fmap fst. find sufficient. A.assocs. countForVertices $ importantEdges\n where \n importantEdges = filter isImportant edges\n where isImportant (u, v) = colorArr A.! u /= colorArr A.! v\n colorArr = A.listArray bounds colors\n countForVertices = A.accumArray (\\v _ -> v+1) 0 bounds. undirect\n where undirect = concatMap (\\(u,v) -> [(u,v), (v,u)])\n sufficient = (==) importantCnt. snd\n where importantCnt = length importantEdges \n bounds = (1, n)\n"}], "negative_code": [], "src_uid": "aaca5d07795a42ecab210327c1cf6be9"} {"source_code": "\n\nimport qualified Data.List as L\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\n\ntype Long = Int\n\n\nsolve :: Double -> Double\nsolve n = r*2 * cos (pi * abs (i/n - 1/4))\n where\n r = 0.5 / sin (pi/2/n)\n i = fromIntegral $ round (n/4)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readWords\n print $ solve n\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readWords\n testCases t\n\n\nreadWords :: (Read a) => IO [a]\nreadWords = map read . words <$> getLine", "positive_code": [{"source_code": "\nimport Data.List\n\nsolve :: Double -> Double\nsolve n = cos(pi/(4*n))/sin(pi/(2*n))\n\nmain = interact $ \n (intercalate \"\\n\") \n . (map (show . solve . read))\n . (drop 1) \n . words\n"}], "negative_code": [], "src_uid": "c466c909fff92353ea676b643ca76908"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if midZero then 1 else 0)\n midZero = odd n && C.index str (n `div` 2) == '0'\n z = C.count '0' str\n result\n | m == 0 = \"BOB\"\n | m == 1 && midZero && z > 1 = \"ALICE\"\n | m == 1 && midZero = \"BOB\"\n | m == 2 && midZero && z == 2 = \"DRAW\"\n | otherwise = \"ALICE\"\n return $ stringUtf8 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _ <- getLine\n s <- getLine\n let winner = if reverse s == s\n then solvePalin s\n else solveNonPalin s\n putStrLn winner\n\n\ncountZeros :: String -> Int\ncountZeros = length . filter (== '0')\n\nsolvePalin :: String -> String\nsolvePalin s = let z = countZeros s in if even z || z == 1\n then \"BOB\"\n else \"ALICE\"\n\nsolveNonPalin :: String -> String\nsolveNonPalin s\n | even n || countZeros s /= 2 = \"ALICE\"\n | otherwise = if s !! quot n 2 == '0'\n then \"DRAW\" \n else \"ALICE\"\n where n = length s\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if midZero then 1 else 0)\n midZero = odd n && C.index str (n `div` 2) == '0'\n z = C.count '0' str\n result\n | m == 0 = \"BOB\"\n | m == 1 && midZero && z > 1 = \"ALICE\"\n | m == 1 && midZero = \"BOB\"\n | m == 2 && midZero && z == 2 = \"DRAW\"\n | m == 2 && midZero = \"BOB\"\n | otherwise = \"ALICE\"\n return $ stringUtf8 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)\n z = C.count '0' str\n result\n | m == 0 = \"BOB\"\n | m == 1 && (odd n && C.index str (n `div` 2) == '0') && z > 1 = \"ALICE\"\n | m == 1 && (odd n && C.index str (n `div` 2) == '0') = \"BOB\"\n | otherwise = \"ALICE\"\n return $ stringUtf8 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)\n result\n | m == 1 && (odd n && C.index str (n `div` 2) == '0') || m == 0 = \"BOB\"\n | otherwise = \"ALICE\"\n return $ stringUtf8 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)\n z = C.count '0' str\n result\n | z - m >= 2 && m == 0 = \"BOB\"\n | z == 1 && odd n && C.index str (n `div` 2) == '0' = \"BOB\"\n | otherwise = \"ALICE\"\n return $ stringUtf8 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n str <- C.getLine\n let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)\n z = C.count '0' str\n result\n | z - m >= 2 && m == 0 = \"BOB\"\n | otherwise = \"ALICE\"\n return $ stringUtf8 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}], "src_uid": "aef15a076b04e510e663a41341c8d156"} {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\nmain = B.interact exec\nexec = B.pack . show . solve . map int . B.words\n where int = maybe undefined fst . B.readInt\nsolve (n:ls) = length $ filter (== 0) $ scanl1 (+) $ elems (accumArray (+) 0 (1, n) $ concat $ zipWith (\\i l -> let lo = max 1 $ i -l in if lo > i - 1 then [] else [(max 1 $ i - l, 1), (i, -1)]) [1..] ls :: UArray Int Int)", "positive_code": [{"source_code": "-- Try Codeforces\n-- author: Leonardone @ NEETSDKASU\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nreadI = fst . fromJust . C.readInt\n\nmain = C.interact $ C.pack . solve . map readI . C.words\n\nsolve (_:xs) = show ans\n where\n ans = fst $ foldl f (0, 0) $ reverse xs\n f (a, 0) x = (a + 1, x)\n f (a, k) x = (a, max (k-1) x) \n "}], "negative_code": [{"source_code": "module Main where\nimport Data.Array.Unboxed\nmain = interact exec\nexec = show . solve . map read . words\nsolve (n:ls) = length $ filter (== 0) $ elems (accumArray (+) 0 (1, n) $ concat $ zipWith (\\i l -> [(max 1 $ i - l, 1), (i, -1)]) [1..] ls :: UArray Int Int)"}], "src_uid": "beaeeb8757232b141d510547d73ade04"} {"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, MagicHash #-}\n\nimport GHC.Prim (uncheckedIShiftL#,uncheckedIShiftRL#)\nimport GHC.Exts (Int(..))\nimport Control.Applicative ((<$>))\nimport Control.Monad (unless,when,forM_)\nimport Data.Array.Base \nimport Data.Array.IO (IOUArray)\nimport Data.Bits (testBit,shiftL,shiftR,xor,(.&.),(.|.))\nimport qualified Data.ByteString.Char8 as B (ByteString,readInt,words,getContents,getLine)\nimport Data.Int (Int64)\nimport Data.List (foldl')\n\ninfixl 8 .<<. , .>>.\n(.<<.) :: Int -> Int -> Int\n(I# x).<<.(I# i) = I# (uncheckedIShiftL# x i)\n(.>>.) :: Int -> Int -> Int\n(I# x).>>.(I# i) = I# (uncheckedIShiftRL# x i)\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n{-# INLINE readInt #-}\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep !n f = go 0\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n{-# INLINE rep #-} \n\ntoDecimal :: [Int] -> Int64\ntoDecimal xs = foldl' (\\x y->x`shiftL`1 + fromIntegral y) 0 xs\n{-# INLINE toDecimal #-}\n\ndata SegTree = Node !Int !Int !(IOUArray Int Int) !(IOUArray Int Int) !SegTree !SegTree\n | Leaf !Int !(IOUArray Int Int)\n\nmerge :: SegTree -> SegTree -> IO SegTree\nmerge stx sty = do\n cnt <- newArray (0,19) 0 :: IO (IOUArray Int Int)\n f <- newArray (0,19) 0 :: IO (IOUArray Int Int)\n rep 20 $ \\b-> do\n x <- unsafeRead (getCnt stx) b\n y <- unsafeRead (getCnt sty) b\n unsafeWrite cnt b $! x+y\n return $! Node (getLeft stx) (getRight sty) cnt f stx sty\n\ngetLeft :: SegTree -> Int\ngetLeft (Node l _ _ _ _ _) = l\ngetLeft (Leaf k _) = k\n\ngetRight :: SegTree -> Int\ngetRight (Node _ r _ _ _ _) = r\ngetRight (Leaf k _ ) = k\n\ngetCnt :: SegTree -> IOUArray Int Int\ngetCnt (Node _ _ cnt _ _ _) = cnt\ngetCnt (Leaf _ cnt) = cnt\n\nmkSegTree :: Int -> Int -> UArray Int Int -> IO SegTree\nmkSegTree l r arr\n | l/=r = do\n let !m = (l+r).>>.1\n lt <- mkSegTree l m arr\n rt <- mkSegTree (m+1) r arr\n merge lt rt\n | otherwise = do\n let !x = unsafeAt arr (l-1)\n cnt <- newListArray (0,19) $ map (\\b->x.>>.b.&.1) [0..19]\n return $! Leaf l cnt\n\nquery :: Int -> Int -> SegTree -> IO ()\nquery kl kr segtree = mapM (go segtree) [19,18..0] >>= print.toDecimal\n where\n go (Node l r cnt flag lt rt) b = do\n if r Int -> Int -> SegTree -> IO ()\nupdate kl kr x segtree = go segtree\n where\n !bs = filter (testBit x) [0..19]\n go (Node l r cnt flag lt rt) = do\n unless (r do\n f <- unsafeRead flag b\n unsafeWrite flag b $! xor 1 f\n c <- unsafeRead cnt b\n unsafeWrite cnt b $! r-l+1-c\n else do\n go lt\n go rt\n forM_ bs $ \\b-> do\n cntl <- unsafeRead (getCnt lt) b\n cntr <- unsafeRead (getCnt rt) b\n f <- unsafeRead flag b\n if f==1\n then unsafeWrite cnt b $! r-l+1-cntl-cntr\n else unsafeWrite cnt b $! cntl+cntr\n go (Leaf k cnt) = do\n when (kl<=k && k<=kr) $ do\n forM_ bs $ \\b-> do\n c <- unsafeRead cnt b\n unsafeWrite cnt b $! xor 1 c\n\nmain = do\n n <- readLn\n arr <- listArray(0,n-1).map readInt.B.words <$> B.getLine :: IO (UArray Int Int)\n segtree <- mkSegTree 1 n arr\n queries <- map readInt.tail.B.words <$> B.getContents\n let parse (1:rest) = parse1 rest\n parse (_:rest) = parse2 rest\n parse _ = []\n parse1 (l:r:rest) = query l r segtree : parse rest\n parse2 (l:r:x:rest) = update l r x segtree : parse rest\n sequence_ $ parse queries\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 -optc-O3 #-}\n{-# LANGUAGE BangPatterns, MagicHash #-}\n\nimport GHC.Prim (uncheckedIShiftL#,uncheckedIShiftRL#)\nimport GHC.Exts (Int(..))\nimport Data.Bits (testBit,shiftL,shiftR,xor,(.&.),(.|.))\nimport qualified Data.ByteString.Char8 as B (ByteString,readInt,words,getContents,getLine)\nimport Data.Int (Int64)\nimport Data.List (foldl')\nimport Control.Applicative ((<$>),(<*>))\nimport Control.Monad (unless,forM_)\nimport Data.Array.Base (UArray,listArray,newArray,unsafeAt,unsafeRead,unsafeWrite)\nimport Data.Array.IO (IOUArray)\n\ninfixl 8 .<<. , .>>.\n(.<<.) :: Int -> Int -> Int\n(I# x).<<.(I# i) = I# (uncheckedIShiftL# x i)\n(.>>.) :: Int -> Int -> Int\n(I# x).>>.(I# i) = I# (uncheckedIShiftRL# x i)\n{-# INLINE (.<<.) #-}\n{-# INLINE (.>>.) #-}\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n{-# INLINE readInt #-}\n\nrep :: Int -> (Int -> IO ()) -> IO ()\nrep !n f = go 0\n where\n go !i\n | i> go (i+1)\n | otherwise = return ()\n{-# INLINE rep #-} \n\ntoDecimal :: [Int] -> Int64\ntoDecimal xs = foldl' (\\x y->x`shiftL`1 + fromIntegral y) 0 xs\n{-# INLINE toDecimal #-}\n\nmain = do\n n <- readLn\n arr <- listArray(0,n-1).map readInt.B.words <$> B.getLine :: IO (UArray Int Int)\n\n segtree <- newArray (0,20*(1.<<.18)-1) 0 :: IO (IOUArray Int Int)\n flag <- newArray (0,20*(1.<<.18)-1) 0 :: IO (IOUArray Int Int)\n\n let build node l r = do\n if r-l==1\n then do\n let !al = unsafeAt arr l\n rep 20 $ \\b-> do\n unsafeWrite segtree (b.<<.18+ node) $! al.>>.b.&.1\n else do\n let !nodel = node.<<.1 .|. 1\n !noder = node.<<.1 + 2\n !m = (l+r).>>.1\n build nodel l m\n build noder m r\n rep 20 $ \\b-> do\n cntl <- unsafeRead segtree $! b.<<.18+nodel\n cntr <- unsafeRead segtree $! b.<<.18+noder\n unsafeWrite segtree (b.<<.18+ node) $! cntl + cntr\n\n let query kl kr = mapM (go 0 0 n) [19,18..0] >>= print.toDecimal\n where\n go node l r b = do\n if r<=kl || kr<=l\n then return 0\n else if kl<=l && r<=kr\n then unsafeRead segtree $! b.<<.18+node\n else do\n let !nodel = node.<<.1 .|. 1\n !noder = node.<<.1 + 2\n !m = (l+r).>>.1\n ql <- go nodel l m b\n qr <- go noder m r b\n f <- unsafeRead flag $! b.<<.18+node\n if f==1\n then return $! min kr r-max kl l-ql-qr\n else return $! ql+qr\n\n let update kl kr x = go 0 0 n\n where\n !bs = filter (testBit x) [0..19]\n go node l r = do\n unless (r<=kl || kr<=l) $ do\n if kl<=l && r<=kr\n then do\n forM_ bs $ \\b-> do\n let !i = b.<<.18 + node\n f <- unsafeRead flag i\n unsafeWrite flag i $! xor 1 f\n cnt <- unsafeRead segtree i\n unsafeWrite segtree i $! r-l-cnt\n else do\n let !nodel = node.<<.1 .|. 1\n !noder = node.<<.1 + 2\n !m = (l+r).>>.1\n go nodel l m\n go noder m r\n forM_ bs $ \\b-> do\n cntl <- unsafeRead segtree $! b.<<.18+nodel\n cntr <- unsafeRead segtree $! b.<<.18+noder\n f <- unsafeRead flag $! b.<<.18 + node\n if f==1\n then unsafeWrite segtree (b.<<.18+node) $! r-l-cntl-cntr\n else unsafeWrite segtree (b.<<.18+node) $! cntl+cntr\n\n let parse (1:rest) = parse1 rest\n parse (_:rest) = parse2 rest\n parse _ = []\n parse1 (l:r:rest) = query (l-1) r : parse rest\n parse2 (l:r:x:rest) = update (l-1) r x : parse rest\n\n build 0 0 n\n queries <- map readInt.tail.B.words <$> B.getContents\n sequence_ $ parse queries\n"}], "negative_code": [], "src_uid": "79bb09f5d8b591bfcfcea1b61be9d020"} {"source_code": "main :: IO ()\nmain = do\n inp <- getLine\n let l = map read $ words inp\n a = l!!0\n b = l!!1\n c = l!!2\n inp <- getLine\n let liste = map read $ words inp\n putStrLn $ show $ steps $ Just (liste,c,b,c,b)\n return ()\nsteps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int\nsteps Nothing = -1\nsteps (Just x) = 1+(steps $ step x)\n\n\nstep :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int) \nstep (liste,acc,batt,cacc,cbatt)\n |null liste = Nothing\n |cacc==cbatt && cacc==0 = Nothing\n |(head liste) == 0 =\n if cacc==0\n then Just (tail liste,acc,batt,cacc,cbatt-1)\n else Just (tail liste,acc,batt,cacc-1,cbatt)\n |otherwise =\n if cacc==acc || cbatt==0\n then Just (tail liste,acc,batt,cacc-1,cbatt)\n else Just (tail liste,acc,batt,cacc+1,cbatt-1)", "positive_code": [{"source_code": "analyze _ _ 0 0 _ = 0\nanalyze b a p q s\n | a == q = 1 + (analyze b a p (q - 1) (tail s))\n | p == 0 = 1 + (analyze b a p (q - 1) (tail s))\n | (head s) == 1 = 1 + (analyze b a (p - 1) (q + 1) (tail s))\n | q == 0 = 1 + (analyze b a (p - 1) q (tail s))\n | otherwise = 1 + (analyze b a p (q - 1) (tail s))\n\nmain = do\n line1 <- getLine\n line2 <- getLine\n let\n nums1 = map read (words line1)\n (n:b:a:_) = nums1\n s = (map read (words line2)) ++ (repeat 0)\n putStrLn (show (min n (analyze b a b a s)))\n"}], "negative_code": [{"source_code": "main :: IO ()\nmain = do\n inp <- getLine\n let l = map read $ words inp\n a = l!!0\n b = l!!1\n c = l!!2\n inp <- getLine\n let liste = map read $ words inp\n putStrLn $ show $ steps $ Just (liste,c,b,c,b)\n return ()\nsteps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int\nsteps Nothing = -1\nsteps (Just x) = 1+(steps $ step x)\n\n\nstep :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int) \nstep (liste,acc,batt,cacc,cbatt)\n |null liste = Nothing\n |cacc==cbatt && cacc==0 = Nothing\n |(head liste) == 0 =\n if cacc==0\n then Just (tail liste,acc,batt,cacc,cbatt-1)\n else Just (tail liste,acc,batt,cacc-1,cbatt)\n |otherwise =\n if cacc==acc \n then Just (tail liste,acc,batt,cacc-1,cbatt)\n else Just (tail liste,acc,batt,cacc+1,cbatt-1)"}, {"source_code": "main :: IO ()\nmain = do\n inp <- getLine\n let l = map read $ words inp\n a = l!!0\n b = l!!1\n c = l!!2\n inp <- getLine\n let liste = map read $ words inp\n putStrLn $ show $ steps $ Just (liste,c,b,c,b)\n return ()\nsteps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int\nsteps Nothing = 0\nsteps (Just x) = 1+(steps $ step x)\n\n\nstep :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int) \nstep (liste,acc,batt,cacc,cbatt)\n |null liste = Nothing\n |cacc==cbatt && cacc==0 = Nothing\n |(head liste) == 0 =\n if cacc==0\n then Just (tail liste,acc,batt,cacc,cbatt-1)\n else Just (tail liste,acc,batt,cacc-1,cbatt)\n |otherwise =\n if cacc==acc \n then Just (tail liste,acc,batt,cacc-1,cbatt)\n else Just (tail liste,acc,batt,cacc+1,cbatt-1)"}, {"source_code": "main :: IO ()\nmain = do\n inp <- getLine\n let l = map read $ words inp\n a = l!!0\n b = l!!1\n c = l!!2\n inp <- getLine\n let liste = map read $ words inp\n putStrLn $ show $ steps $ Just (liste,c,b,c,b)\n return ()\nsteps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int\nsteps Nothing = -1\nsteps (Just x) = 1+(steps $ step x)\n\n\nstep :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int) \nstep (liste,acc,batt,cacc,cbatt)\n |null liste = Nothing\n |cacc==cbatt && cacc==0 = Nothing\n |(head liste) == 0 =\n if cacc==0\n then Just (tail liste,acc,batt,cacc,cbatt-1)\n else Just (tail liste,acc,batt,cacc-1,cbatt)\n |otherwise =\n if cacc==acc || cacc==0\n then Just (tail liste,acc,batt,cacc-1,cbatt)\n else Just (tail liste,acc,batt,cacc+1,cbatt-1)"}], "src_uid": "75ef1f52ef3a86992159eef566dddc89"} {"source_code": "import Data.List\n\nboolToAns :: Bool -> String\nboolToAns x = if x then \"YES\" else \"NO\"\n\ncomputeAnswer :: Integer -> String -> Bool\ncomputeAnswer k str\n | any (=='x') firstSubstring = False\n | n0 + n1 + abs (n0-n1) > k = False\n | otherwise = True\n where\n classes :: [String]\n classes =\n map (map fst)\n $ groupBy (\\x y -> snd x == snd y)\n $ sortOn (snd)\n $ zip str $ cycle [0..(k-1)]\n firstSubstring :: String\n firstSubstring = map repr classes\n repr :: String -> Char\n repr str\n | any (=='0') str && any (=='1') str = 'x'\n | any (=='1') str = '1'\n | any (=='0') str = '0'\n | otherwise = '?'\n count :: Char -> String -> Integer\n count c = genericLength . filter (==c)\n n0 = count '0' firstSubstring\n n1 = count '1' firstSubstring\n\n\n\n\nanswerTestcase :: IO ()\nanswerTestcase = do\n line1 <- getLine\n line2 <- getLine\n let k = readInt $ words line1 !! 1\n (putStrLn . boolToAns) $ computeAnswer k line2\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain = (fmap readInt getLine) >>= (\\t -> sequence (genericReplicate t answerTestcase))\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Functor\nimport Data.Bool\nimport Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt\n\nreadInt64B8 :: B8.ByteString -> Int64\nreadInt64B8 = fromIntegral . fst . fromJust . B8.readInteger\n\nsolve :: Int -> Int -> B8.ByteString -> Bool\nsolve n k s = fromMaybe False result\n where\n result = do\n convolution <- convolution\n let zerosCount = B8.count '0' convolution\n let onesCount = B8.count '1' convolution\n let delta = k - zerosCount - onesCount\n return $ (abs $ zerosCount - onesCount) <= delta\n\n convolution = B8.pack <$> foldr (liftA2 (:)) (Just \"\") collapsedColumns\n collapsedColumns = map collapseColumn stripesColumns\n\n collapseColumn column \n | ('1' `B8.elem` column) && ('0' `B8.elem` column) = Nothing\n | ('1' `B8.elem` column) = Just '1'\n | ('0' `B8.elem` column) = Just '0'\n | otherwise = Just '?'\n\n stripesColumns = do\n groupId <- [0 .. k - 1]\n let columns = map (B8.index s) [groupId, groupId + k .. n - 1]\n return $ B8.pack columns\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n [n, k] <- B8.getLine <&> B8.words <&> map readIntB8\n s <- B8.getLine\n let answer = solve n k s\n printf \"%s\\n\" $ ((bool \"NO\" \"YES\" answer)::String)\n"}], "negative_code": [], "src_uid": "8e448883014bf7cd35fcca3fe0128af0"} {"source_code": "z l=[0,length(filter(=='R')l)-(if any(=='L')l then 1 else 0)]\ns l=case span(=='.')l of\n (d,r)->map (+(length d+1))(z r)\nmain=interact$unwords.map show.s.(!!1).lines\n", "positive_code": [{"source_code": "main :: IO ()\nmain = interact $ unwords . map show . solve . (!! 1) . lines\n\nsolve :: String -> [Int]\nsolve s\n | r == 0 = [n + l, n]\n | l == 0 = [n + 1, n + r + 1]\n | otherwise = [n + 1, n + r]\n where\n (nn, t) = span (== '.') s\n (rr, u) = span (== 'R') t\n (ll, _) = span (== 'L') u\n n = length nn\n r = length rr\n l = length ll\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Arrow\nimport Debug.Trace\nmain = do\n getLine\n l <- getLine\n let (s,t) = solve l\n putStrLn $ show s ++\" \"++show t\n\nsolve l = case typ of\n 1 -> fst $ foldl f ((0,0),(0,0)) l\n 2 -> fst $ foldl g ((0,0),(0,0)) l\n where\n typ = length $ group $ filter (/='.') l\n f ((s,t),(i,0)) '.' = ((s,t),(i+1,0))\n f ((s,t),(i,0)) 'R' = ((i+1,t),(i+1,1))\n f ((s,t),(i,0)) 'L' = ((s,i),(i+1,2))\n f ((s,t),(i,1)) 'R' = ((s,t),(i+1,1))\n f ((s,t),(i,1)) '.' = ((s,i+1),(i+1,0))\n f ((s,t),(i,2)) 'L' = ((s,t),(i+1,2))\n f ((s,t),(i,2)) '.' = ((i,t),(i+1,0)) \n g ((s,t),(i,0)) '.' = ((s,t),(i+1,0))\n g ((s,t),(i,0)) 'L' = ((s,t),(i+1,0))\n g ((s,t),(i,0)) 'R' = ((i+1,t),(i+1,1))\n g ((s,t),(i,1)) 'L' = ((s,i),(i+1,0))\n g ((s,t),(i,1)) 'R' = ((s,t),(i+1,1))\n\n\n \n\n \n \n"}, {"source_code": "import Data.List\nmain = interact $ (\\(a,b) -> (show $ a+1) ++ \" \" ++ (show $ b+1)) . go . last . lines\n\ngo s | ('R'`elem`s) && ('L'`elem`s) = (fnd 'R',fnl 'R')\n | 'R'`elem`s = (fnd 'R',(fnl 'R')+1)\n | otherwise = (fnl 'L',(fnd 'L')-1)\n where lst c = elemIndices c s\n fnd = head . lst\n fnl = last . lst\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: String -> (Int, Int)\nsolve s\n | not (elem 'L' s) = (r1, rm+1)\n | not (elem 'R' s) = (lm, l1-1)\n | otherwise = (r1, l1-1)\n where\n l1 = (+1) $ length $ takeWhile (/= 'L') s\n r1 = (+1) $ length $ takeWhile (/= 'R') s\n lm = (+(l1-1)) $ length $ takeWhile (== 'L') $ dropWhile (/= 'L') s\n rm = (+(r1-1)) $ length $ takeWhile (== 'R') $ dropWhile (/= 'R') s\n\nmain :: IO ()\nmain = do\n getLine\n s <- getLine\n let (a, b) = solve s\n prints [a, b]\n\n where\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: String -> (Int, Int)\nsolve s\n | not (elem 'L' s) = (r1, rm+1)\n | not (elem 'R' s) = (lm, l1-1)\n | otherwise = (r1, l1-1)\n where\n l1 = (+1) $ length $ takeWhile (/= 'L') s\n r1 = (+1) $ length $ takeWhile (/= 'R') s\n lm = (+(l1-1)) $ length $ takeWhile (== 'L') $ dropWhile (/= 'L') s\n rm = (+(r1-1)) $ length $ takeWhile (== 'R') $ dropWhile (/= 'R') s\n\nmain :: IO ()\nmain = do\n getLine\n s <- getLine\n let (a, b) = solve s\n prints [a, b]\n\n where\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "main::IO()\nmain = do\n\tnum <- getLine\n\tinput <- getLine\n\tlet\n\t\ta = zip input [1..(read num)]\n\t\tcnt c = length $ filter ( (== c).fst ) a\n\t\tfirst c = foldl (\\a b -> if (fst b)==c && a==0 then (snd b) else a) 0 a\n\t\tsecond c = foldl (\\a b -> if (fst b)==c then (snd b) else a) 0 a\n\t\t(a1,a2) = if cnt 'R' > 0 then (first 'R',second 'R' + if cnt 'L' > 0 then 0 else 1) else (second 'L',(first 'L')-1)\n\tputStrLn $ (show a1) ++ \" \" ++ (show a2)\n"}], "negative_code": [{"source_code": "import Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: String -> (Int, Int)\nsolve s\n | not (elem 'L' s) = (r1, rm)\n | not (elem 'R' s) = (lm, l1)\n | otherwise = (r1, l1)\n where\n l1 = (+1) $ length $ takeWhile (/= 'L') s\n r1 = (+1) $ length $ takeWhile (/= 'R') s\n lm = (+(l1-1)) $ length $ takeWhile (== 'L') $ dropWhile (/= 'L') s\n rm = (+(r1-1)) $ length $ takeWhile (== 'R') $ dropWhile (/= 'R') s\n\nmain :: IO ()\nmain = do\n s <- getLine\n let (a, b) = solve s\n prints [a, b]\n\n where\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "main::IO()\nmain = do\n\tnum <- getLine\n\tinput <- getLine\n\tlet\n\t\ta = zip input [1..(read num)]\n\t\tcnt c = length $ filter ( (== c).fst ) a\n\t\tfirst c = foldl (\\a b -> if (fst b)==c && a==0 then (snd b) else a) 0 a\n\t\tsecond c = foldl (\\a b -> if (fst b)==c then (snd b) else a) 0 a\n\t\t(a1,a2) = if cnt 'R' > 0 then (first 'R',second 'R') else (second 'L',(first 'L')-1)\n\tputStrLn $ (show a1) ++ \" \" ++ (show a2)\n"}, {"source_code": "z l=[0,length(filter(=='R')l)-(if any(=='L')l then 1 else 0)]\ns l=case span(=='.')l of\n (d,r)->map (+(length d+1))(z r)\nmain=interact$show.s.(!!1).lines\n"}], "src_uid": "3053cba2426ebd113fcd70a9b026dad0"} {"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [a, b, x] = map read $ words input\r\n output = if isPairXMagic (a, b) x then \"YES\" else \"NO\"\r\n\r\n\r\nisPairXMagic :: (Integer, Integer) -> Integer -> Bool\r\nisPairXMagic (a, b) x\r\n | not (a <= b) = isPairXMagic (b, a) x\r\n | b < x = False\r\n | a == 0 = b == x\r\n | (b - x) `mod` a == 0 = True\r\n | otherwise = isPairXMagic (a, b `mod` a) x\r\n", "positive_code": [{"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput input = output\r\n where\r\n tests = drop 1 $ lines input\r\n answers = map processTest tests\r\n output = unlines answers\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest input = output\r\n where\r\n [a, b, x] = map read $ words input\r\n output = if isPairXMagic (a, b) x then \"YES\" else \"NO\"\r\n\r\n\r\nisPairXMagic :: (Integer, Integer) -> Integer -> Bool\r\nisPairXMagic (a, b) x\r\n | not (a <= b) = isPairXMagic (b, a) x\r\n | b < x = False\r\n | a == 0 && b /= x = False\r\n | (b - x) `mod` a == 0 = True\r\n | otherwise = isPairXMagic (a, b `mod` a) x\r\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\r\n\r\nimport qualified Data.ByteString.Char8 as DBC\r\nimport qualified Data.ByteString.Builder as DBB\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport System.IO\r\n\r\nrecurse :: Integral a => a -> a -> a -> Bool\r\nrecurse x a b \r\n | aa || b==0 = False\r\n | x `mod` b == a `mod` b = True\r\n | otherwise = recurse x b (a `mod` b)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[a,b,x] <- readv\r\n let ans = recurse x a b\r\n putStrLn $ if ans then \"YES\" else \"NO\"\r\n\r\nprintv :: [Int] -> IO ()\r\nprintv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\\n'\r\n\r\nreadv :: IO [Integer]\r\nreadv = map (maybe 0 fst . DBC.readInteger) <$> (DBC.words <$> DBC.getLine)\r\n\r\nmain :: IO ()\r\nmain = do\r\n --hSetBuffering stdout NoBuffering\r\n ~[nTc] <- readv\r\n CM.replicateM_ (fromIntegral nTc) solve\r\n"}, {"source_code": "main = interact $ unlines . map (f . map read . words) . drop 1 . lines\r\n\r\nf [a, b, x]\r\n | a > b = f [b, a, x]\r\n | b < x || (a == 0 && b /= x) = \"NO\"\r\n | a == 0 || mod (b - x) a == 0 = \"YES\"\r\n | otherwise = f [a, mod b a, x]\r\n"}], "negative_code": [], "src_uid": "7e23e222ce40547ed8a4f7f1372082d9"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nneed 'W' = 1\nneed 'B' = -1\n\nsolve l = snd $ foldl f (repeat 0, 0) l where\n f (have, accum) row =\n let next_need = map need row in\n let res = sum $ snd $ mapAccumL (\\adds (have, char) ->\n (need char - have, if adds == need char - have then 0 else 1)) 0 (zip have row) in\n (next_need, accum+res)\n\nmain = interact $ unlines . return . show . solve . map reverse . reverse . tail . lines\n", "positive_code": [{"source_code": "parse :: String -> [[Int]]\nparse = map (map weight) . tail . lines\n where weight 'B' = 1\n weight 'W' = -1\n\ndiff :: [[Int]] -> [[Int]]\ndiff = d (zipWith (-)) . map (d (-))\n where d f l = (zipWith f l (tail l)) ++ [last l]\n\nsolve :: [[Int]] -> Int\nsolve = length . filter (/= 0) . concat . diff\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}], "negative_code": [], "src_uid": "ce6b65ca755d2d860fb76688b3d775db"} {"source_code": "import List\nimport Maybe\nimport Debug.Trace\n\ninfixr 0 $$\ninfixr 9 ...\nf $$ x = traceShow x $ f x\nf ... g = (f $$) . g\n\nmain = do \n getLine\n xs <- fmap (map read.words) getLine\n ys <- fmap (map read.words) getLine\n let answer = solve 1 xs ys\n print $ length answer\n mapM_ (putStrLn.f) answer\n where f(i,j) = show i ++ \" \" ++ show j\n\nsolve :: Int -> [Integer] -> [Integer] -> [(Int,Int)]\nsolve _ [] [] = []\nsolve n xxs@(x:xs) yys@(y:ys) \n | xxs == yys = []\n | otherwise = swapSeq n (n+i) ++ solve (n+1) xs ys'\n where i = fromJust $ elemIndex x yys\n ys' = drop 1 $ update i y yys\n\nupdate n x xs = as ++ x:drop 1 bs where (as,bs) = splitAt n xs\n\nswapSeq i j = xs ++ (drop 1 $ reverse xs)\n where xs = zip [i..] [i+1..j]\n", "positive_code": [{"source_code": "module Main (main) where\n\nimport Data.List\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n input <- getLine\n let n = readInt input\n input <- getLine\n let xs = map readInt $ take n $ words input\n input <- getLine\n let ys = map readInt $ take n $ words input\n let (count, pairs) = solve n xs ys \n print count\n printPairs pairs where\n \n solve n xs ys = finder xs ys 0 0 [] where\n \n finder [] [] step s res = (s, res)\n finder (x:xs) ys step s res = \n finder xs (delete (ys!!found) ys) (step+1) (s+found) (res ++ [(step, (step+found))]) where \n \n found = case elemIndex x ys of\n Nothing -> 0\n Just a -> a\n \n printPairs [] = return ()\n printPairs ((from, to):ps) = do\n printPair from to\n printPairs ps\n \n printPair from to | from == to = return ()\n printPair from to = do\n putStrLn $ show to ++ \" \" ++ show (to+1)\n printPair from (to-1)\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\n\ntype List = Array Int Int\ntype Swap = (Int, Int)\n\nsolve :: Int -> List -> List -> [Swap]\nsolve n as bs = solve' 1 bs\n where\n solve' i bs\n | i == n = []\n | as ! i == bs ! i = solve' (i + 1) bs\n | otherwise = swaps ++ solve' (i + 1) (bs // ((i, bs ! iM) : [(a, bs ! b) | (a,b) <- swaps]))\n where\n iM = fst $ head $ dropWhile ((/= as ! i) . snd) $ drop i $ assocs bs\n swaps = [(j, j-1) | j <- [iM, iM-1 .. i+1]]\n\nprints :: [Swap] -> IO ()\nprints swaps = print (length swaps) >> mapM_ print' swaps\n where\n print' (i,j) = putStrLn (show j ++ \" \" ++ show i)\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- liftM (listArray (1,n) . map read . words) getLine\n bs <- liftM (listArray (1,n) . map read . words) getLine\n prints $ solve n as bs"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\ndebug = flip trace\n-- debug = const\n\nrearrange _ [] [] = []\nrearrange pos (a:as) (b:bs)\n | a == b = rearrange (pos + 1) as bs\n | otherwise = \n let Just ind = elemIndex b (a:as)\n asnext = delete b (a:as)\n in (reverse $ map (+ pos) [0..ind - 1]) ++ rearrange (pos + 1) asnext bs\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map read . words) `fmap` getLine :: IO [Int]\n\nprintSwap ss =\n mapM_ (\\s -> putStrLn (show s ++ \" \" ++ show (s+1))) ss\n\nmain = do\n n <- getInt\n as <- getInts\n bs <- getInts\n let arr = (rearrange 1 bs as)\n print $ length arr\n printSwap arr\n"}, {"source_code": "import Data.Array\n\nmain = do\n\t[n] <- r\n\ta <- r\n\tb <- r\n\tputStrLn $ unlines $ let c = f n b ++ reverse (f n a) in show (length c): c where\n\t\tr = fmap (map read . words) getLine\n\t\tf n l = g [(j - 1, j) | i <- [1 .. n], j <- reverse [i + 1 .. n]] $ listArray (1, n) l\n\t\tg [] a = []\n\t\tg ((i, j): k) a = if a!i > a!j then (show i ++ \" \" ++ show j) : g k (a // [(i, a!j), (j, a!i)]) else g k a\n"}], "negative_code": [{"source_code": "getA :: IO [Int]\ngetA = fmap (map read . words) getLine\n\ngao :: Int -> [Int] -> ([String], [Int])\ngao p [a] = ([], [a])\ngao p (a:b:c) = (r ++ u ++ x, y ++ [last v]) where\n\tq = p + 1\n\t(r,h:t) = if a>b then ([show p ++ \" \" ++ show q], b:a:c) else ([], a:b:c)\n\t(u,v) = gao q t\n\t(x,y) = gao p (h:init v)\n\nmain = do\n\tgetA\n\ta <- getA\n\tb <- getA\n\tputStrLn $ unlines $ let f = fst . gao 1; c = f a ++ reverse (f b) in show (length c): c\n"}, {"source_code": "getA :: IO [Int]\ngetA = fmap (map read . words) getLine\n\ngao p [a] = ([], [a])\ngao p (a:b:c) = (r ++ u ++ x, y ++ [last v]) where\n\tq = p + 1\n\t(r,h:t) = if a>b then ([show p ++ \" \" ++ show q], b:a:c) else ([], a:b:c)\n\t(u,v) = gao q t\n\t(x,y) = gao p (h:init v)\n\nmain = do\n\tgetA\n\ta <- getA\n\tb <- getA\n\tputStrLn $ unlines $ let f = show . snd . gao 1; c = f b ++ reverse (f a) in show (length c): [c]\n"}, {"source_code": "import List\nimport Maybe\nimport Debug.Trace\n\ninfixr 0 $$\ninfixr 9 ...\nf $$ x = traceShow x $ f x\nf ... g = (f $$) . g\n\nmain = do \n getLine\n xs <- fmap (map read.words) getLine\n ys <- fmap (map read.words) getLine\n mapM_ (putStrLn.f) $ solve 1 xs ys\n where f(i,j) = show i ++ \" \" ++ show j\n\nsolve :: Int -> [Integer] -> [Integer] -> [(Int,Int)]\nsolve _ [] [] = []\nsolve n xxs@(x:xs) yys@(y:ys) \n | xxs == yys = []\n | otherwise = swapSeq n (n+i) ++ solve (n+1) xs ys'\n where i = fromJust $ elemIndex x yys\n ys' = drop 1 $ update i y yys\n\nupdate n x xs = as ++ x:drop 1 bs where (as,bs) = splitAt n xs\n\nswapSeq i j = xs ++ (drop 1 $ reverse xs)\n where xs = zip [i..] [i+1..j]\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array\n\ntype List = Array Int Int\ntype Swap = (Int, Int)\n\nsolve :: Int -> List -> List -> [Swap]\nsolve n as bs = solve' 1 bs\n where\n solve' i bs\n | i == n = []\n | as ! i == bs ! i = solve' (i + 1) bs\n | otherwise = swaps ++ solve' (i + 1) (bs // ((i, bs ! iM) : [(a, bs ! b) | (a,b) <- swaps]))\n where\n iM = fst $ head $ dropWhile ((/= as ! i) . snd) $ drop i $ assocs bs\n swaps = [(j, j-1) | j <- [iM, iM-1 .. i+1]]\n\nprints :: [Swap] -> IO ()\nprints swaps = print (length swaps) >> mapM_ print' swaps\n where\n print' (i,j) = putStrLn (show i ++ \" \" ++ show j)\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- liftM (listArray (1,n) . map read . words) getLine\n bs <- liftM (listArray (1,n) . map read . words) getLine\n prints $ solve n as bs\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\ndebug = flip trace\n-- debug = const\n\nrearrange _ [] [] = []\nrearrange pos (a:as) (b:bs)\n | a == b = rearrange (pos + 1) as bs\n | otherwise = \n let Just ind = elemIndex b (a:as)\n asnext = delete b (a:as)\n in (reverse $ map (+ pos) [0..ind - 1]) ++ rearrange (pos + 1) asnext bs\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map read . words) `fmap` getLine :: IO [Int]\n\nprintSwap ss =\n mapM_ (\\s -> putStrLn (show s ++ \" \" ++ show (s+1))) ss\n\nmain = do\n n <- getInt\n as <- getInts\n bs <- getInts\n let arr = (rearrange 1 as bs)\n print $ length arr\n printSwap arr\n"}], "src_uid": "e554616ed3df169888acd3452a2f896f"} {"source_code": "main = interact $ unlines . map (show . sum . map f . words) . tail . lines where f \"1\" = 0; f _ = 1", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n let isOne k = if k == 1 then 1 else 0\n pure $ putInts $ pure $ 2 - isOne n - isOne m -- no k >= 1 constraint...\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\r\nimport Data.Maybe (catMaybes)\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n\r\n\r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.unlines . map processTest . drop 1 . B.lines\r\n\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest = B.pack . show . findMinK . map fst . catMaybes . map B.readInteger . B.words\r\n\r\n\r\nfindMinK :: [Integer] -> Integer\r\nfindMinK field_sizes = fromIntegral $ length $ filter (/= 1) field_sizes\r\n"}, {"source_code": "main :: IO ()\r\nmain = interact processInput\r\n\r\n\r\nprocessInput :: String -> String\r\nprocessInput = unlines . map processTest . drop 1 . lines\r\n\r\n\r\nprocessTest :: String -> String\r\nprocessTest = show . findMinK . map read . words\r\n\r\n\r\nfindMinK :: [Integer] -> Integer\r\nfindMinK field_sizes = fromIntegral $ length $ filter (/= 1) field_sizes\r\n"}, {"source_code": "main :: IO ()\r\nmain = interact $ unlines . map (show . f . map read . words) . tail . lines where\r\n f [1, 1] = 0\r\n f [1, _] = 1\r\n f [_, 1] = 1\r\n f _ = 2\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, m] <- getInts 2\n pure $ putInts $ pure $ if min n m == 1\n then 1\n else 2\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "e5a01ebfdca3af987e93b68c96268c16"} {"source_code": "import Data.Char\nimport Data.Text as T\nimport Data.ByteString as ByteString\nimport Data.Word\n\n{-\nstrToInts :: String -> [Int]\nstrToInts str = map (\\x -> read x :: Int) (words str)\n-}\n\n{-\nclass IntParser a where\n toInt :: a -> Int\n\ninstance IntParser ByteString where\n toInt bs = ByteString.Conversion.FromByteString bs :: Int\n\ninstance IntParser String where\n toInt s = read s :: Int\n-}\n\nclass CharWord8Funcs a where\n\tgetDigit :: a -> Int\n\tisSpace :: a -> Bool\n\tisDigit :: a -> Bool\n\ninstance CharWord8Funcs Char where\n\tgetDigit ch = digitToInt ch\n\tisSpace ch = Data.Char.isSpace ch\n\tisDigit ch = Data.Char.isDigit ch\n\ninstance CharWord8Funcs Word8 where\n\tgetDigit w = fromIntegral (w - 48) :: Int\n\tisSpace w = w == 32 || w <= 13\n\tisDigit w = w >= 48 && w < 58\n\n{-\nclass StringByteStringFuncs a where\n\tempty :: a -> Bool\n\ninstance StringByteStringFuncs Foldable where\n\tempty s = Prelude.null s\n\ninstance StringByteStringFuncs ByteString where\n\tempty bs = ByteString.null bs\n-}\n\n-- getNumber :: String -> (Int, String) -- (number, rest)\ngetNumber [] = error \"can't getNumber from invalid string\"\ngetNumber (ch:t)\n\t|(Main.isSpace ch) || ch == '+' || ch == '-' = do\n\t\tlet (number, rest) = getNumber t\n\t\t((if ch == '-' then -1 else 1) * number, rest)\n\t|otherwise = do\n\t\tlet (number, rest, ex10) = getNumber' (ch:t)\n\t\tif ex10 < 0 then getNumber []\n\t\telse (number, rest)\n\t\ngetNumber' [] = (0, [], -1)\ngetNumber' (ch:t)\n\t| Main.isDigit ch == False = (0, t, -1)\n\t| otherwise = do\n\t\tlet (number, rest, ex10) = getNumber' t\n\t\t(number + ((10^(ex10 + 1)) * Main.getDigit ch), rest, ex10 + 1)\n\ngetNumberFromBytes str\n\t|ByteString.null str = error \"can't getNumberFromBytes from invalid string\"\n\t|otherwise = do \n\t\tlet (w, t) = (ByteString.head str, ByteString.tail str)\n\t\tif (Main.isSpace w) || w == 43 || w == 45 then do\n\t\t\tlet (number, rest) = getNumberFromBytes t\n\t\t\t((if w == 45 then -1 else 1) * number, rest)\n\t\telse do\n\t\t\tlet (number, rest, ex10) = getNumberFromBytes' str\n\t\t\tif ex10 < 0 then getNumberFromBytes ByteString.empty\n\t\t\telse (number, rest)\n\t\ngetNumberFromBytes' str\n\t|ByteString.null str = (0, str, -1)\n\t|otherwise = do \n\t\tlet (w, t) = (ByteString.head str, ByteString.tail str)\n\t\tif (Main.isDigit w == False) then (0, t, -1)\n\t\telse do\n\t\tlet (number, rest, ex10) = getNumberFromBytes' t\n\t\t(number + ((10^(ex10 + 1)) * Main.getDigit w), rest, ex10 + 1)\n\n-- getNNumbers :: String -> Int -> ([Int], String) -- (numbers, rest)\ngetNNumbers str 0 = ([], str)\ngetNNumbers str n = do\n\tlet (number, rest1) = getNumber str\n\tlet (numbers, rest2) = getNNumbers rest1 (n - 1)\n\t(number : numbers, rest2)\n\nreadInput :: Int -> String -> Int\nreadInput n str = do\n\tif n > 0 then do\n\t\tlet (number, rest1) = getNumber str\n\t\tlet (_, rest2) = getNumber rest1\n\t\tnumber + readInput (n - 1) rest2\n\telse 0\n\nprintRes 0 l = return ()\nprintRes n l = do\n\tPrelude.putChar l\n\tprintRes (n - 1) l\n\nmain = do\n\tcontents <- Prelude.getContents\n\tlet (n, rest) = getNumber contents\n\tlet sumA = readInput n rest\n\tlet thousands = div sumA 1000\n\tlet countOfG = (thousands + if (sumA - (thousands * 1000)) > 500 then 1 else 0)\n\tlet countOfA = n - countOfG\n\tprintRes countOfA 'A'\n\tprintRes countOfG 'G'\n\tPrelude.putStrLn \"\"\n", "positive_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\ngao :: Int -> String -> [(Int, Int)] -> String\ngao _ s [] = reverse s\ngao d s ((a, g): t)\n | d + a <= 500 = gao (d + a) ('A':s) t\n | otherwise = gao (d - g) ('G':s) t\n\nmain :: IO ()\nmain = do\n (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStrLn $ gao 0 \"\" $ pairs a\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain = B.getContents >>= putStr . solve 0 . tail . map readInt . B.words\n where \n solve diff (a:g:rest)\n | diff + a <= 500 = 'A' : solve (diff + a) rest\n | otherwise = 'G' : solve (diff - g) rest\n solve _ _ = []"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = putStrLn . solve . map (maybe 0 fst . B.readInt . head . B.words) . B.lines =<< B.getContents\n\nsolve :: [Int] -> String\nsolve (n : as) = replicate na 'A' ++ replicate ng 'G'\n where\n ng = (sum as + 500) `div` 1000\n na = n - ng\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\ngetMin a b = case compare (abs $ fst a) (abs $ fst b) of\n LT -> a\n _ -> b\n\ngroupByPairs (a:b:xs) = (a, b) : groupByPairs xs\ngroupByPairs list = []\n\nsolve (n:list) = let decide (d, acc) (x, y) = acc `seq` ((d + x, 'A' : acc) `getMin` (d - y, 'G' : acc))\n -- holy crap %)\n (x, ans) = foldl' decide (0, []) $ groupByPairs list\n in if abs x <= 500 then ans else \"-1\"\n\nparseInt = fst . fromJust . BS.readInt\n\nmain = BS.interact $ BS.pack . solve . map parseInt . BS.words"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nmain = do getLine\n input <- BS.getContents\n putStrLn $ solve $ BS.lines input\n\n{-splitBySpace :: String -> [String]-}\nsplitBySpace str = map BS.unpack (BS.words str)\n\ngetAsPrice strs = [read ((splitBySpace str)!!0)|str <- strs]\ngetGsPrice strs = [read $ (splitBySpace str)!!1|str <- strs]\n\nsolve2 [] [] (a,g) = (\"\",(a,g))\nsolve2 (x:pa) (y:pg) (a,g) = if abs (a+x-g) < abs (g+y-a) \n then (\"A\" ++ fst(solve2 pa pg (a+x,g)), (a+x,g))\n else (\"G\" ++ fst(solve2 pa pg (a,g+y)), (a,g+y))\n{-solve3 [] [] = \"\"\nsolve3 (x:pa) (y:pg) = if abs (a+x-g) < abs (g+y-a) then \"A\"++(solve3 pa pg) \n else \"G\" ++ (solve3 pa pg)\n where a = fst (solve2 pa pg) \n g = snd (solve2 pa pg)\n-}\n\nsolve strs = if abs(a-g)>500 then \"-1\"\n else fst $ ret\n where\n ret = solve2 pa pg (0,0)\n where\n pa = getAsPrice strs\n {-pg = getGsPrice strs-}\n pg = map (1000 - ) pa\n a = fst(snd(ret))\n g = snd $ snd $ ret\n\n\n\n\n\n\n\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain=B.getContents>>=putStr.solve.map readInt.B.words\n\nsolve(_:xs) = go 0 xs\n where\n go d (a:g:rest)\n | d + a <= 500 = 'A' : go (d+a) rest\n | otherwise = 'G' : go (d-g) rest\n go _ _ = []\n"}, {"source_code": "import Data.Char\nimport Data.Text as T\nimport Data.ByteString as ByteString\nimport Data.Word\n\n{-\nstrToInts :: String -> [Int]\nstrToInts str = map (\\x -> read x :: Int) (words str)\n-}\n\n{-\nclass IntParser a where\n toInt :: a -> Int\n\ninstance IntParser ByteString where\n toInt bs = ByteString.Conversion.FromByteString bs :: Int\n\ninstance IntParser String where\n toInt s = read s :: Int\n-}\n\nclass CharWord8Funcs a where\n\tgetDigit :: a -> Int\n\tisSpace :: a -> Bool\n\tisDigit :: a -> Bool\n\ninstance CharWord8Funcs Char where\n\tgetDigit ch = digitToInt ch\n\tisSpace ch = Data.Char.isSpace ch\n\tisDigit ch = Data.Char.isDigit ch\n\ninstance CharWord8Funcs Word8 where\n\tgetDigit w = fromIntegral (w - 48) :: Int\n\tisSpace w = w == 32 || w <= 13\n\tisDigit w = w >= 48 && w < 58\n\n{-\nclass StringByteStringFuncs a where\n\tempty :: a -> Bool\n\ninstance StringByteStringFuncs Foldable where\n\tempty s = Prelude.null s\n\ninstance StringByteStringFuncs ByteString where\n\tempty bs = ByteString.null bs\n-}\n\n-- getNumber :: String -> (Int, String) -- (number, rest)\ngetNumber [] = error \"can't getNumber from invalid string\"\ngetNumber (ch:t)\n\t|(Main.isSpace ch) || ch == '+' || ch == '-' = do\n\t\tlet (number, rest) = getNumber t\n\t\t((if ch == '-' then -1 else 1) * number, rest)\n\t|otherwise = do\n\t\tlet (number, rest, ex10) = getNumber' (ch:t)\n\t\tif ex10 < 0 then getNumber []\n\t\telse (number, rest)\n\t\ngetNumber' [] = (0, [], -1)\ngetNumber' (ch:t)\n\t| Main.isDigit ch == False = (0, t, -1)\n\t| otherwise = do\n\t\tlet (number, rest, ex10) = getNumber' t\n\t\t(number + ((10^(ex10 + 1)) * Main.getDigit ch), rest, ex10 + 1)\n\ngetNumberFromBytes str\n\t|ByteString.null str = error \"can't getNumberFromBytes from invalid string\"\n\t|otherwise = do \n\t\tlet (w, t) = (ByteString.head str, ByteString.tail str)\n\t\tif (Main.isSpace w) || w == 43 || w == 45 then do\n\t\t\tlet (number, rest) = getNumberFromBytes t\n\t\t\t((if w == 45 then -1 else 1) * number, rest)\n\t\telse do\n\t\t\tlet (number, rest, ex10) = getNumberFromBytes' str\n\t\t\tif ex10 < 0 then getNumberFromBytes ByteString.empty\n\t\t\telse (number, rest)\n\t\ngetNumberFromBytes' str\n\t|ByteString.null str = (0, str, -1)\n\t|otherwise = do \n\t\tlet (w, t) = (ByteString.head str, ByteString.tail str)\n\t\tif (Main.isDigit w == False) then (0, t, -1)\n\t\telse do\n\t\tlet (number, rest, ex10) = getNumberFromBytes' t\n\t\t(number + ((10^(ex10 + 1)) * Main.getDigit w), rest, ex10 + 1)\n\n-- getNNumbers :: String -> Int -> ([Int], String) -- (numbers, rest)\ngetNNumbers str 0 = ([], str)\ngetNNumbers str n = do\n\tlet (number, rest1) = getNumber str\n\tlet (numbers, rest2) = getNNumbers rest1 (n - 1)\n\t(number : numbers, rest2)\n\nreadInput :: Int -> ByteString -> Int\nreadInput n str = do\n\tif n > 0 then do\n\t\tlet (number, rest1) = getNumberFromBytes str\n\t\tlet (_, rest2) = getNumberFromBytes rest1\n\t\tnumber + readInput (n - 1) rest2\n\telse 0\n\nprintRes 0 l = return ()\nprintRes n l = do\n\tPrelude.putChar l\n\tprintRes (n - 1) l\n\nmain = do\n\tcontents <- ByteString.getContents\n\tlet (n, rest) = getNumberFromBytes contents\n\tlet sumA = readInput n rest\n\tlet thousands = div sumA 1000\n\tlet countOfG = (thousands + if (sumA - (thousands * 1000)) > 500 then 1 else 0)\n\tlet countOfA = n - countOfG\n\tprintRes countOfA 'A'\n\tprintRes countOfG 'G'\n\tPrelude.putStrLn \"\"\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt . head . B.words) . tail . B.lines =<< B.getContents\n\nsolve :: [Int] -> String\nsolve as = fst =<< scanl f (\"\", d) as\n where\n d = sum as\n f (_, s) a\n | s > 500 = (\"G\", s - 1000)\n | otherwise = (\"A\", s)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt . head . B.words) . B.lines =<< B.getContents\n\nsolve :: [Int] -> String\nsolve (n : as)\n | d > 500 = \"-1\"\n | otherwise = s\n where\n (s, d) = foldr f (\"\", sum as) as\n f _ (s, d)\n | d > 500 = ('G' : s, d - 1000)\n | otherwise = ('A' : s, d)\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmagicSort = sortBy (\\(_,a,b) (_,c,d) -> compare (abs (c-d)) (abs (a-b)))\n\nmagicUnsort = sortBy (\\(i,_) (j,_) -> compare i j)\n\nsolve xs ys = foldl decide (0, []) . magicSort . zip3 [1..] xs $ ys\n where\n decide (x, acc) (i, a, b) | x > 0 = (x - b, (i, 'G') : acc)\n | x <= 0 = (x + a, (i, 'A') : acc)\n\nparsePair :: IO (Int, Int)\nparsePair = do\n [a, b] <- words <$> getLine\n return (read a, read b)\n\nmain = do\n n <- read <$> getLine\n (xs, ys) <- mapAndUnzipM (const $ parsePair) [1..n]\n let (x, zs) = solve xs ys\n if abs x <= 500 then\n let (_, answer) = unzip $ magicUnsort zs\n in putStrLn . reverse $ answer\n else\n putStrLn \"-1\""}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmagicSort = sortBy (\\(_,a,b) (_,c,d) -> compare (abs (c-d)) (abs (a-b)))\n\nmagicUnsort = sortBy (\\(i,_) (j,_) -> compare i j)\n\nsolve xs ys = foldl decide (z, []) . magicSort . zip3 [1..] xs $ ys\n where\n z = sum $ zipWith (-) xs ys\n decide (x, acc) (i, a, b) | x > 0 = (x - b, (i, 'G') : acc)\n | x <= 0 = (x + a, (i, 'A') : acc)\n\nparsePair :: IO (Int, Int)\nparsePair = do\n [a, b] <- words <$> getLine\n return (read a, read b)\n\nmain = do\n n <- read <$> getLine\n (xs, ys) <- mapAndUnzipM (const $ parsePair) [1..n]\n let (x, zs) = solve xs ys\n if abs x <= 500 then\n let (_, answer) = unzip $ magicUnsort zs\n in putStrLn . reverse $ answer\n else\n putStrLn \"-1\""}, {"source_code": "import Data.List\n\nsimulate (_:xs) = foldl (\\ x y -> x + (f y)) 0 $ map sort xs\n where\n f \"++X\" = 1\n f \"--X\" = -1\n f s = 0\nsimulate _ = 0\n\nmain = interact $ show . simulate . lines"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmagicSort = sortBy (\\(_,a,b) (_,c,d) -> compare (abs (a-b)) (abs (c-d)))\n\nmagicUnsort = sortBy (\\(i,_) (j,_) -> compare i j)\n\nsolve xs ys = foldl decide (0, []) . magicSort . zip3 [1..] xs $ ys\n where\n decide (x, acc) (i, a, b) | x > 0 = (x - b, (i, 'G') : acc)\n | x <= 0 = (x + a, (i, 'A') : acc)\n\nparsePair :: IO (Int, Int)\nparsePair = do\n [a, b] <- words <$> getLine\n return (read a, read b)\n\nmain = do\n n <- read <$> getLine\n (xs, ys) <- mapAndUnzipM (const $ parsePair) [1..n]\n let (x, zs) = solve xs ys\n if abs x <= 500 then\n let (_, answer) = unzip $ magicUnsort zs\n in putStrLn . reverse $ answer\n else\n putStrLn \"-1\""}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\n\nmagicSort = sortBy (\\(_,a,b) (_,c,d) -> compare (abs (a-b)) (abs (c-d)))\n\nmagicUnsort = sortBy (\\(i,_) (j,_) -> compare i j)\n\nsolve xs ys = foldl decide (0, []) . magicSort . zip3 [1..] xs $ ys\n where\n decide (x, acc) (i, a, b) | x > 0 = (x - b, (i, 'G') : acc)\n | x < 0 = (x + a, (i, 'A') : acc)\n | b < a = (x - b, (i, 'G') : acc)\n | True = (x + a, (i, 'A') : acc)\n\nparsePair :: IO (Int, Int)\nparsePair = do\n [a, b] <- words <$> getLine\n return (read a, read b)\n\nmain = do\n n <- read <$> getLine\n (xs, ys) <- mapAndUnzipM (const $ parsePair) [1..n]\n let (x, zs) = solve xs ys\n if (abs x) <= 500 then\n let (_, answer) = unzip $ magicUnsort zs\n in putStrLn . reverse $ answer\n else\n putStrLn \"-1\""}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nmain = do getLine\n input <- BS.getContents\n print $ solve $ BS.lines input\n\n{-splitBySpace :: String -> [String]-}\nsplitBySpace str = map BS.unpack (BS.words str)\n\ngetAsPrice strs = [read ((splitBySpace str)!!0)|str <- strs]\ngetGsPrice strs = [read $ (splitBySpace str)!!1|str <- strs]\n\nsolve2 [] [] = (0,0)\nsolve2 (x:pa) (y:pg) = if abs (a+x-g) < abs (g+y-a) then (a+x,g) else (a,g+y)\n where a = fst (solve2 pa pg)\n g = snd (solve2 pa pg)\nsolve3 [] [] = \"\"\nsolve3 (x:pa) (y:pg) = if abs (a+x-g) < abs (g+y-a) then (solve3 pa pg) ++ \"A\"\n else (solve3 pa pg) ++ \"G\"\n where a = fst (solve2 pa pg)\n g = snd (solve2 pa pg)\n\nsolve strs = if abs(a-g)>500 then \"-1\" else\n solve3 pa pg \n where \n pa = getAsPrice strs\n pg = getGsPrice strs\n a = fst (solve2 pa pg) :: Int\n g = snd (solve2 pa pg) :: Int\n"}, {"source_code": "\nstrToInts :: String -> [Int]\nstrToInts str = map (\\x -> read x :: Int) (words str)\n\nreadInput :: IO Int -> IO [Int]\nreadInput nIO = do\n\tn <- nIO\n\tif n > 0 then do\n\t\tpairStr <- getLine\n\t\tlet pair = strToInts pairStr\n\t\ttail <- readInput $ return (n - 1)\n\t\treturn ((pair !! 0) : tail)\n\telse return []\n\nmain = do\n\tnStr <- getLine\n\tlet n = strToInts nStr !! 0\n\tinput <- readInput $ return n\n\tlet sumA = sum input\n\tlet thousands = div sumA 1000\n\tlet countOfG = (thousands + if (sumA - (thousands * 1000)) > 500 then 1 else 0)\n\tlet countOfA = n - countOfG\n\tlet res = (take countOfA $ repeat 'A') ++ (take countOfG $ repeat 'G')\n\tprint res\n\n{-\nstrToInts :: String -> [Int]\nstrToInts str = map (\\x -> read x :: Int) (words str)\n\nreadInput :: IO Int -> IO [(Int, Int)]\nreadInput nIO = do\n\tn <- nIO\n\tif n > 0 then do\n\t\tpairStr <- getLine\n\t\tlet pair = strToInts pairStr\n\t\ttail <- readInput $ return (n - 1)\n\t\treturn ((pair !! 0, pair !! 1) : tail)\n\telse return []\n\n-- (resStr, aSum, gSum, aIndexes, gIndexes)\ngetMin :: [(Int, Int)] -> (String, Int, Int, [Int], [Int])\ngetMin list = getMin' list 0\ngetMin' :: [(Int, Int)] -> Int -> (String, Int, Int, [Int], [Int])\ngetMin' [] index = (\"\", 0, 0, [], [])\ngetMin' ((a, g):t) index = do\n\tlet (resStr, aSum, gSum, aIndexes, gIndexes) = getMin' t (index+1)\n\tif a < g then ('A':resStr, aSum + a, gSum, index:aIndexes, gIndexes)\n\telse ('B':resStr, aSum, gSum + g, aIndexes, index:gIndexes)\n\nmain = do\n\tnStr <- getLine\n\tinput <- readInput $ return (strToInts nStr !! 0)\n\tlet res1 = getMin input\n\tlet (strRes1, aSum1, gSum1, aIndexes1, gIndexes1) = res1\n\tlet dif = abs(aSum1 - gSum1)\n\n\tif abs(aSum1 - gSum1) <= 500 then print strRes1\n\telse print \"?\"\n-}\n"}], "src_uid": "24fe280b88575516ec679ff78641440e"} {"source_code": "module Main where\r\n import Data.List\r\n \r\n solve :: IO ()\r\n solve = do\r\n ns <- getLine\r\n s <- getLine\r\n let n = read ns :: Int\r\n a = map (\\x -> read x :: Int) $ words s\r\n mn = minimum a\r\n Just pos = findIndex (== mn) a\r\n putStr $ concat $ map (++ \"\\n\") $ \r\n [show $ n - 1] ++ [concat $ map (\\x -> show x ++ \" \") $ \r\n [pos + 1, i + 1, mn, mn + abs (pos - i)] | \r\n i <- filter (/= pos) [0 .. n - 1]]\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Text.Printf\r\n \r\nsolve xs n\r\n | length xs == 1 = putStrLn $ show 0\r\n | otherwise = do\r\n let idx = fromMaybe 0 $ findIndex (==mn) xs\r\n mn = minimum xs\r\n putStrLn $ show (n - 1)\r\n forM_ (zip [0..(n - 1)] [x | i <- [0..(n - 1)], let x = mn + abs (i - idx)]) $\r\n \\(cur, num) -> \r\n if cur == idx\r\n then putStr \"\"\r\n else putStrLn $ unwords $ map show [idx + 1, cur + 1, mn, num]\r\n \r\nmain = do\r\n t <- getLine >>= return . read :: IO Int\r\n replicateM_ t $ do\r\n n <- getLine >>= return . read :: IO Int\r\n nums <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n solve nums n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Text.Printf\r\n \r\nsolve xs n\r\n | length xs == 1 = print $ show 0\r\n | otherwise = do\r\n let idx = fromMaybe 0 $ findIndex (==mn) xs\r\n mn = minimum xs\r\n putStrLn $ show (n - 1)\r\n forM_ (zip [0..(n - 1)] [x | i <- [0..(n - 1)], let x = mn + abs (i - idx)]) $\r\n \\(cur, num) -> \r\n if cur == idx\r\n then putStr \"\"\r\n else putStrLn $ unwords $ map show [idx + 1, cur + 1, mn, num]\r\n \r\nmain = do\r\n t <- getLine >>= return . read :: IO Int\r\n replicateM_ t $ do\r\n n <- getLine >>= return . read :: IO Int\r\n nums <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n solve nums n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Text.Printf\r\n \r\nsolve xs n\r\n | length xs == 1 = print $ show 0\r\n | otherwise = do\r\n let idx = fromMaybe 0 $ findIndex (==mn) xs\r\n mn = minimum xs\r\n putStrLn $ show (n - 1)\r\n forM_ (zip [0..(n - 1)] [x | i <- [0..(n - 1)], let x = mn + abs (i - idx)]) $\r\n \\(cur, num) -> \r\n if cur == idx\r\n then putStr \"\"\r\n else putStrLn $ unwords $ map show [idx + 1, cur + 1, cur, num]\r\n \r\nmain = do\r\n t <- getLine >>= return . read :: IO Int\r\n replicateM_ t $ do\r\n n <- getLine >>= return . read :: IO Int\r\n nums <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n solve nums n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Text.Printf\r\n \r\nsolve xs n\r\n | length xs == 1 = print $ show 0\r\n | otherwise = do\r\n let idx = fromMaybe 0 $ findIndex (==mn) xs\r\n mn = minimum xs\r\n putStrLn $ show (n - 1)\r\n forM_ (zip [0..(n - 1)] [x | i <- [0..(n - 1)], let x = mn + abs (i - idx)]) $\r\n \\(idx, num) -> \r\n if idx == mn\r\n then putStr \"\"\r\n else putStrLn $ unwords $ map show [idx, (idx + 1), num, (num + 1)]\r\n \r\nmain = do\r\n t <- getLine >>= return . read :: IO Int\r\n replicateM_ t $ do\r\n n <- getLine >>= return . read :: IO Int\r\n nums <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n solve nums n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Text.Printf\r\n \r\nsolve xs n\r\n | length xs == 1 = print $ show 0\r\n | otherwise = do\r\n let idx = fromMaybe 0 $ findIndex (==mn) xs\r\n mn = minimum xs\r\n if idx == 0\r\n then do\r\n putStrLn $ show (n - 1)\r\n else do\r\n putStrLn $ show n\r\n putStrLn $ unwords $ map show [1, (idx + 1), mn, (mn + idx)]\r\n forM_ (zip [1..(n - 1)] [mn..(mn+n-2)]) $\r\n \\(idx, num) -> \r\n putStrLn $ unwords $ map show [idx, (idx + 1), num, (num + 1)]\r\n \r\nmain = do\r\n t <- getLine >>= return . read :: IO Int\r\n replicateM_ t $ do\r\n n <- getLine >>= return . read :: IO Int\r\n nums <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n solve nums n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Text.Printf\r\n\r\nsolve xs n\r\n | length xs == 1 = print $ show 0\r\n | otherwise = do\r\n let idx = fromMaybe 0 $ findIndex (==mn) xs\r\n mn = minimum xs\r\n if idx == 0\r\n then do\r\n putStrLn $ show (n - 1)\r\n else do\r\n putStrLn $ show n\r\n putStrLn $ unwords $ map show [1, mn, (idx + 1), (mn + idx)]\r\n forM_ (zip [2..(n - 1)] [(mn + 1)..(mn+n-2)]) $\r\n \\(idx, num) -> \r\n putStrLn $ unwords $ map show [idx, num, (idx + 1), (num + 1)]\r\n\r\nmain = do\r\n t <- getLine >>= return . read :: IO Int\r\n replicateM_ t $ do\r\n n <- getLine >>= return . read :: IO Int\r\n nums <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n solve nums n"}, {"source_code": "module Main where\r\n import Data.List\r\n \r\n solve :: IO ()\r\n solve = do\r\n ns <- getLine\r\n s <- getLine\r\n let n = read ns :: Int\r\n a = map (\\x -> read x :: Int) $ words s\r\n mn = minimum a\r\n Just pos = findIndex (== mn) a\r\n putStr $ concat $ map (++ \"\\n\") $ \r\n [show $ n - 1] ++ [concat $ map (\\x -> show x ++ \" \") $ \r\n [pos + 1, i + 1, mn, mn + abs (pos - i)] | \r\n i <- filter (/= pos) [1 .. n - 1]]\r\n \r\n iter :: Int -> IO ()\r\n iter 1 = solve\r\n iter n = do\r\n solve\r\n iter $ n - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Int)"}], "src_uid": "8b2b7208630af1d086420513a437a914"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\n{-\n - rotate clockwise\n - (i,j) n m -> (j,n-i+1) m n\n - horizontal rotate\n - (i,j) n m -> (i,m-j+1) m n\n -\n - (i,j)\n - -}\n\nmain = do\n [n,m,x,y,z,p] <- readInts\n l <- map (l2p . map readInt . B.words) . B.lines <$> B.getContents\n putStr $ unlines $ map (unwords . map show . p2l . solve n m x y z) l\n\nrotateC ((n,m),(i,j)) = ((m,n),(j,n-i+1))\nrotateH ((n,m),(i,j)) = ((n,m),(i,m-j+1))\n\ntimes n f x = iterate f x !! n\n\nsolve n m x y z p = snd $ times (4 - mod z 4) rotateC$ \n times (mod y 2) rotateH $ \n times (mod x 4) rotateC ((n,m),p)\n\n\n", "positive_code": [{"source_code": "data Point = Point Int Int\n\ninstance Show Point where\n show (Point x y) = (show x) ++ \" \" ++ (show y)\n\ngetPoints :: Int -> IO [Point]\ngetPoints 0 = return []\ngetPoints n = do\n sXY <- getLine\n let\n [x, y] = map read $ words sXY\n rest <- getPoints (n - 1)\n return ((Point x y) : rest)\n\noperX :: Int -> (Int, Int, [Point]) -> (Int, Int, [Point])\noperX 0 (n, m, po) = (n, m, po)\noperX t (n, m, po) = operX (t - 1) (m, n, po')\n where\n po' = map (\\(Point x y) -> Point y (n + 1 - x)) po\n\noperY :: Int -> (Int, Int, [Point]) -> (Int, Int, [Point])\noperY 0 (n, m, po) = (n, m, po)\noperY t (n, m, po) = operY (t - 1) (n, m, po')\n where\n po' = map (\\(Point x y) -> Point x (m + 1 - y)) po\n\noperZ :: Int -> (Int, Int, [Point]) -> (Int, Int, [Point])\noperZ 0 (n, m, po) = (n, m, po)\noperZ t (n, m, po) = operZ (t - 1) (m, n, po')\n where\n po' = map (\\(Point x y) -> Point (m + 1 - y) x) po\n\nmain :: IO ()\nmain = do\n sNMXYZP <- getLine\n let\n [n, m, x, y, z, p] = map read $ words sNMXYZP\n po <- getPoints p\n\n let\n (n', m', po') = ((operZ (z `mod` 4)) . (operY (y `mod` 2)) . (operX (x `mod` 4))) (n, m, po)\n putStr $ unlines $ map show po'\n"}, {"source_code": "import Control.Monad (replicateM_,forM_)\n\ntransX :: Int -> (Int,Int,Int,Int) -> (Int,Int,Int,Int)\ntransX k (n, m, i ,j) =\n case k `mod` 4 of\n 0 -> (n, m, i, j)\n 1 -> (m, n, j, n+1-i)\n 2 -> (n, m, n+1-i, m+1-j)\n 3 -> (m, n, m+1-j, i)\n\ntransY k (n, m, i, j) =\n case k `mod` 2 of\n 0 -> (n, m, i, j)\n 1 -> (n, m, i, m+1-j)\n\ntransZ k = transX (3*k)\n\ntrans :: Int -> Int -> Int -> (Int,Int,Int,Int) -> (Int,Int,Int,Int)\ntrans x y z = transZ z . transY y . transX x\n\nmain = do\n (n: m: x: y: z: p: _) <- (map read . words) `fmap` getLine\n replicateM_ p $ do\n (i:j:_) <- (map read. words) `fmap` getLine\n let (_,_,i',j') = trans x y z (n,m,i,j)\n putStrLn $ show i' ++ \" \" ++ show j'\n\n"}], "negative_code": [{"source_code": "data Point = Point Int Int\n\ninstance Show Point where\n show (Point x y) = (show x) ++ \" \" ++ (show y)\n\ngetPoints :: Int -> IO [Point]\ngetPoints 0 = return []\ngetPoints n = do\n sXY <- getLine\n let\n [x, y] = map read $ words sXY\n rest <- getPoints (n - 1)\n return ((Point x y) : rest)\n\noperX :: Int -> Int -> [Point] -> Int -> [Point]\noperX n m po 0 = po\noperX n m po t = operX n m po' (t - 1)\n where\n po' = map (\\(Point x y) -> Point y (n + 1 - x)) po\n\noperY :: Int -> Int -> [Point] -> Int -> [Point]\noperY n m po 0 = po\noperY n m po t = operY n m po' (t - 1)\n where\n po' = map (\\(Point x y) -> Point x (m + 1 - y)) po\n\noperZ :: Int -> Int -> [Point] -> Int -> [Point]\noperZ n m po 0 = po\noperZ n m po t = operZ n m po' (t - 1)\n where\n po' = map (\\(Point x y) -> Point (m + 1 - y) x) po\n\nmain :: IO ()\nmain = do\n sNMXYZP <- getLine\n let\n [n, m, x, y, z, p] = map read $ words sNMXYZP\n po <- getPoints p\n\n let\n poOX = operX n m po (x `mod` 4)\n poOY = operY n m poOX (y `mod` 2)\n poOZ = operZ n m poOY (z `mod` 4)\n putStr $ unlines $ map show poOZ\n"}, {"source_code": "data Point = Point Int Int\n\ninstance Show Point where\n show (Point x y) = (show x) ++ \" \" ++ (show y)\n\ngetPoints :: Int -> IO [Point]\ngetPoints 0 = return []\ngetPoints n = do\n sXY <- getLine\n let\n [x, y] = map read $ words sXY\n rest <- getPoints (n - 1)\n return ((Point x y) : rest)\n\noperX :: Int -> (Int, Int, [Point]) -> (Int, Int, [Point])\noperX 0 (n, m, po) = (n, m, po)\noperX t (n, m, po) = operX (t - 1) (m, n, po')\n where\n po' = map (\\(Point x y) -> Point y (n + 1 - x)) po\n\noperY :: Int -> (Int, Int, [Point]) -> (Int, Int, [Point])\noperY 0 (n, m, po) = (n, m, po)\noperY t (n, m, po) = operX (t - 1) (n, m, po')\n where\n po' = map (\\(Point x y) -> Point x (m + 1 - y)) po\n\noperZ :: Int -> (Int, Int, [Point]) -> (Int, Int, [Point])\noperZ 0 (n, m, po) = (n, m, po)\noperZ t (n, m, po) = operX (t - 1) (m, n, po')\n where\n po' = map (\\(Point x y) -> Point (m + 1 - y) x) po\n\nmain :: IO ()\nmain = do\n sNMXYZP <- getLine\n let\n [n, m, x, y, z, p] = map read $ words sNMXYZP\n po <- getPoints p\n\n let\n (n', m', po') = ((operZ (z `mod` 4)) . (operY (y `mod` 2)) . (operX (x `mod` 4))) (n, m, po)\n putStr $ unlines $ map show po'\n"}], "src_uid": "14a56443e48c52c118788bd5c0031b0c"} {"source_code": "import Data.List\nimport Data.Ord\nimport Control.Monad\n\nscoreTbl = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]\n\nscore (Just ix) | ix < 10 = scoreTbl !! ix\nscore _ = 0\n\nscore1 sss name =\n let nums = map (elemIndex name) sss in\n let tot = sum $ map score nums in\n let ords = map (\\ix -> length $ filter (== Just ix) nums) [0..] in\n tot : ords\n\nscore2 sss name =\n let nums = map (elemIndex name) sss in\n let tot = sum $ map score nums in\n let (ord0 : ords) = map (\\ix -> length $ filter (== Just ix) nums) [0..] in\n ord0 : tot : ords\n\nmain = do\n t <- readLn\n sss <- replicateM t $ do\n n <- readLn\n replicateM n getLine\n let names = nub $ concat sss\n putStrLn $ maximumBy (comparing $ score1 sss) names\n putStrLn $ maximumBy (comparing $ score2 sss) names\n", "positive_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM, replicateM_)\nimport Data.List (intercalate, sort, maximumBy)\nimport Data.Map (Map(), assocs, fromListWith)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntype Driver = (String, [Int])\n\nscores :: Driver -> Int\nscores = sum . map score . snd\n where\n score n\n | n > 10 = 0\n | otherwise = head $ drop (n-1)\n [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]\n\ncompare' :: Ord a => [a] -> [a] -> Ordering\ncompare' [] [] = EQ\ncompare' [] _ = GT\ncompare' _ [] = LT\ncompare' (a:as) (b:bs)\n | a == b = compare' as bs\n | otherwise = compare a b\n\ncompareI :: Driver -> Driver-> Ordering\ncompareI a b\n | scores a /= scores b = compare (scores a) (scores b)\n | otherwise = compare' (sort (snd b)) (sort (snd a))\n\ncompareII :: Driver -> Driver -> Ordering\ncompareII a b\n | wins a /= wins b = compare (wins a) (wins b)\n | scores a /= scores b = compare (scores a) (scores b)\n | otherwise = compare' (sort (snd b)) (sort (snd a))\n where\n wins = length . filter (== 1) . snd\n\nreadRace ::IO [String]\nreadRace = do\n n <- readLn\n replicateM n getLine\n\nsolve :: [[String]] -> (String, String)\nsolve ss = (fst $ maximumBy compareI assocs', fst $ maximumBy compareII assocs')\n where\n foldSS :: [(String, [Int])]\n foldSS = concatMap (flip zip (map return [1..])) ss\n drivers :: Map String [Int]\n drivers = fromListWith (++) foldSS\n assocs' = assocs drivers\n\nmain :: IO ()\nmain = do\n n <- readLn\n races <- replicateM n readRace\n putStrLn $ fst $ solve races\n putStrLn $ snd $ solve races"}, {"source_code": "data Racer = Racer { name :: String\n , score :: Int\n , wins :: [Int]\n } deriving (Show)\n\nmain :: IO ()\nmain = interact func\n\nscores :: [Int]\nscores = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]\n\nfunc :: String -> String\nfunc s = onechamp racerdata ++ \"\\n\" ++ anotherchamp racerdata ++ \"\\n\"\n where racedata = convert s\n racerdata = fromRaceData racedata []\n \n(!!!) :: [Int] -> Int -> Int\nlst !!! n = if (length lst) <= n then 0 else (lst !! n)\n \nonechamp :: [Racer] -> String\nonechamp rd = name . check 0 $ candicates 0 [] rd\n where candicates _ cs [] = cs\n candicates hi cs (r:rs) = if score r > hi\n then candicates (score r) [r] rs\n else if score r == hi\n then candicates hi (r:cs) rs\n else candicates hi cs rs\n check _ [] = error \"\"\n check _ (r:[]) = r\n check n (r:rs) = let up = filter (\\x -> (wins r)!!!n < (wins x)!!!n) rs\n in if null up\n then check (n+1) $ r:(filter (\\x -> (wins r)!!!n == (wins x)!!!n) rs)\n else check n up\n\nanotherchamp :: [Racer] -> String\nanotherchamp rd = name $ check 1 $ checkPoint $ candicates 0 [] rd\n where candicates _ cs [] = cs\n candicates hi cs (r:rs) = if (wins r)!!!0 > hi\n then candicates ((wins r)!!!0) [r] rs\n else if (wins r)!!!0 == hi\n then candicates hi (r:cs) rs\n else candicates hi cs rs\n check _ [] = error \"\"\n check _ (r:[]) = r\n check n (r:rs) = let up = filter (\\x -> (wins r)!!!n < (wins x)!!!n) rs\n in if null up\n then check (n+1) $ r:(filter (\\x -> (wins r)!!!n == (wins x)!!!n) rs)\n else check n up\n checkPoint [] = error \"\"\n checkPoint (r:[]) = [r]\n checkPoint (r:rs) = let up = filter (\\x -> (score r) < (score x)) rs\n in if null up\n then r:(filter (\\x -> (score r) == (score x)) rs)\n else checkPoint up\n \nfromRaceData :: [[String]] -> [Racer] -> [Racer]\nfromRaceData [] racer = racer\nfromRaceData (r:rs) racer = fromRaceData rs $ f (zip [0..] r) racer\n where f [] nowr = nowr\n f ((n, na):rest) nowr = let rc = getOrNew na racer\n newwin = plusWins n $ wins rc\n newsc = score rc + scores !!! n\n in f rest $ update na (rc {score = newsc, wins = newwin}) nowr \n\ngetOrNew :: String -> [Racer] -> Racer\ngetOrNew na rs = let lst = filter (\\r -> name r == na) rs\n in if null lst\n then Racer {name=na,score=0,wins=[]}\n else head lst\n\nupdate :: String -> Racer -> [Racer] -> [Racer]\nupdate na new rs = new:filter (\\r -> name r /= na) rs\n\nconvert :: String -> [[String]]\nconvert s = convert' n (tail ls)\n where ls = lines s\n n = read $ head ls :: Int\n convert' 0 _ = []\n convert' n' ls' = [take m (tail ls')] ++ convert' (n'-1) (drop m (tail ls'))\n where m = (read $ head ls')::Int\n\nplusWins :: Int -> [Int] -> [Int]\nplusWins 0 [] = [1]\nplusWins n [] = 0:plusWins (n-1) []\nplusWins 0 (x:xs) = (x+1):xs\nplusWins n (x:xs) = x:plusWins (n-1) xs\n"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM, replicateM_)\nimport Data.List (intercalate, sort, maximumBy)\nimport Data.Map (Map(), assocs, fromListWith)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntype Driver = (String, [Int])\n\nscores :: Driver -> Int\nscores = sum . map score . snd\n where\n score n\n | n > 10 = 0\n | otherwise = head $ drop (n-1)\n [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]\n\ncompareI :: Driver -> Driver-> Ordering\ncompareI a b\n | scores a /= scores b = compare (scores a) (scores b)\n | otherwise = compare (sort (snd b)) (sort (snd a))\n\ncompareII :: Driver -> Driver -> Ordering\ncompareII a b\n | wins a /= wins b = compare (wins a) (wins b)\n | scores a /= scores b = compare (scores a) (scores b)\n | otherwise = compare (sort (snd a)) (sort (snd b))\n where\n wins = length . filter (== 1) . snd\n\nreadRace ::IO [String]\nreadRace = do\n n <- readLn\n replicateM n getLine\n\nsolve :: [[String]] -> (String, String)\nsolve ss = (fst $ maximumBy compareI assocs', fst $ maximumBy compareII assocs')\n where\n foldSS :: [(String, [Int])]\n foldSS = concatMap (flip zip (map return [1..])) ss\n drivers :: Map String [Int]\n drivers = fromListWith (++) foldSS\n assocs' = assocs drivers\n\nmain :: IO ()\nmain = do\n n <- readLn\n races <- replicateM n readRace\n putStrLn $ fst $ solve races\n putStrLn $ snd $ solve races"}], "src_uid": "bd40f54a1e764ba226d5387fcd6b353f"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain = do\n n <- read `liftM` getLine :: IO Int\n age <- ( map read . words ) `liftM` getLine :: IO [Int]\n\n let walrus = zip [1..] age\n walrusByAge = groupBy (\\a b -> snd a == snd b) $ sortBy (comparing snd) walrus\n (walrusUnpleasant, _) = foldl' (\\(result, prevPos) ws ->\n let rightMost = maximum $ map fst ws\n result' = map (\\(i,_) -> (i, if i > prevPos then -1 else prevPos - i - 1)) ws\n in (result' ++ result, max rightMost prevPos)\n ) ([], 0) walrusByAge\n --putStrLn $ show walrusUnpleasant\n putStrLn $ unwords $ map (show.snd) $ sortBy (comparing fst) walrusUnpleasant\n\n return ()\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n replicateM n readInt\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStrLn =<< solve . evalState parseInput <$> BS.getContents\n\nsolve :: [Int] -> ByteString\nsolve a = BS.unwords $ map (BS.pack . show) (elems arr)\n where\n n = length a\n \n pairs = zip a [1..]\n pairsG = groupBy ((==) `on` fst) $ sort pairs\n\n arr = array (1, n) $ go pairsG (-1) [] :: UArray Int Int\n\n go [] _ ans = ans\n go (xs:xss) lastPos ans = go xss lastPos' ans'\n where\n positions = map snd xs\n \n ans' = [(p, if p < lastPos then lastPos - p - 1 else (-1)) | p <- positions] ++ ans\n lastPos' = maximum positions `max` lastPos\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "negative_code": [], "src_uid": "668f85cc331bc7bcdd708d9190bbd6e8"} {"source_code": "main = do\n a<-getLine\n b<-getLine\n let \n cc x = length ( filter (=='1') x )\n if ( cc a+( if odd (cc a) then 1 else 0 ) ) >= cc b\n then\n \tputStrLn \"YES\"\n else putStrLn \"NO\"\n", "positive_code": [{"source_code": "main :: IO ()\nmain = interact $ solve . lines\n\nsolve :: [String] -> String\nsolve s\n | xb <= xa + xa `mod` 2 = \"YES\"\n | otherwise = \"NO\"\n where\n [xa, xb] = [sum [1 | '1' <- x] | x <- s]\n"}, {"source_code": "m=length.filter(=='1')\ns[a,b]=(m a+1)`div`2*2>=m b\np x|x=\"YES\"|otherwise=\"NO\"\nmain=interact$p.s.lines\n"}, {"source_code": "import Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: String -> String -> Bool\nsolve a b = a1 + a1 `mod` 2 >= b1\n where\n a1 = length $ filter (== '1') a\n b1 = length $ filter (== '1') b\n\nmain :: IO ()\nmain = do\n a <- getLine\n b <- getLine\n if solve a b\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nfail' :: ByteString -> ByteString -> Bool\nfail' a b = all fail [0..size]\n where\n size = B.length a\n inc = if odd (B.count '1' a) then 1 else 0\n\n fail k\n | r /= B.take (size - k) b = True\n | size == k + B.length b = False\n | otherwise = (dec + B.count '1' l) < B.count '1' (B.drop (size - k) b)\n where\n (l, r) = B.splitAt k a\n dec = if B.index b (size - k) == '1' then inc else (-inc)\n\nsolve a b = if fail' a b && fail' a' b then \"NO\" else \"YES\"\n where a' = B.snoc a $ if odd (B.count '1' a) then '1' else '0'\n\nmain :: IO ()\nmain = do\n a <- B.filter (`elem` \"01\") <$> getLine\n getLine >>= putStrLn . solve a . B.filter (`elem` \"01\")\n"}, {"source_code": "import Data.List\n\n\ncount :: String -> Int\ncount xs = length . filter ( == '1' ) $ xs\n\nhelper :: [String] -> String\nhelper [ xs , ys ] = if div ( n + 1 ) 2 >= div ( m + 1 ) 2 then \"YES\" else \"NO\" where \n n = count xs\n m = count ys \n\nmain = interact $ helper . lines"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: ByteString -> ByteString -> String\nsolve a b = if all fail [0..size] then \"NO\" else \"YES\"\n where\n size = B.length a\n inc = if B.count '1' a `mod` 2 /= 0 then 1 else 0\n\n fail k\n | r /= B.take (size - k) b = True\n | size == k + B.length b = False\n | otherwise = (dec + B.count '1' l) < B.count '1' (B.drop (size - k) b)\n where\n (l, r) = B.splitAt k a\n dec = if B.index b (size - k) == '1' then inc else (-inc)\n\nmain :: IO ()\nmain = do\n a <- getLine\n getLine >>= putStrLn . solve a\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: ByteString -> ByteString -> String\nsolve a b = if all fail [0..size] then \"NO\" else \"YES\"\n where\n size = B.length a\n inc = if odd (B.count '1' a) then 1 else 0\n\n fail k\n | r /= B.take (size - k) b = True\n | size == k + B.length b = False\n | otherwise = (dec + B.count '1' l) < B.count '1' (B.drop (size - k) b)\n where\n (l, r) = B.splitAt k a\n dec = if B.index b (size - k) == '1' then inc else (-inc)\n\nmain :: IO ()\nmain = do\n a <- B.init <$> getLine\n getLine >>= putStrLn . solve a . B.init\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nsolve :: ByteString -> ByteString -> String\nsolve a b = if all fail [0..size] then \"NO\" else \"YES\"\n where\n size = B.length a\n inc = if odd (B.count '1' a) then 1 else 0\n\n fail k\n | r /= B.take (size - k) b = True\n | size == k + B.length b = False\n | otherwise = (dec + B.count '1' l) < B.count '1' (B.drop (size - k) b)\n where\n (l, r) = B.splitAt k a\n dec = if B.index b (size - k) == '1' then inc else (-inc)\n\nmain :: IO ()\nmain = do\n a <- B.filter (`elem` \"01\") <$> getLine\n getLine >>= putStrLn . solve a . B.filter (`elem` \"01\")\n"}, {"source_code": "import Data.Char\n\nchange::Char->Char->Char\nchange a b =chr ( (( ord a-ord '0' + ord b - ord '0' ) `mod` 2) + ord '0' )\n\ncheck::String->String->Int->Int->Char->Bool\ncheck a b begin_a begin_b now = if begin_b==length b then True\n else if (b!!begin_b)==now then check a b begin_a (begin_b+1) (change now (b!!begin_b))\n\t\t\t\t\t\t\t\telse if begin_a==length a then False\n\t\t\t\t\t\t\t\telse check a b (begin_a+1) begin_b (change now (a!!begin_a))\n\nwork::String->String->Int->Bool\nwork a b i = if length a acc || work a b t ) False [0..(length b)]\n\tputStrLn $ if ans==False then \"NO\" else \"YES\"\n"}, {"source_code": "main = do\n a<-getLine\n b<-getLine\n let \n cc x = length ( filter (=='1') x )\n if ( cc a+( if odd ( length a ) then 1 else 0 ) ) >= cc b\n then\n \tputStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "import Data.List\n\n\nmatch :: [ String ] -> String\nmatch [ a , b ] = matchHelp ( a ++ take ( length b + 10 ) ['0','0'..] ) b where \n matchHelp :: String -> String -> String\n matchHelp [] ys = \"NO\" \n matchHelp t@( x:xs) ys\n | isPrefixOf ys t = \"YES\"\n | otherwise = matchHelp xs ys\n\n\nmain = interact $ match . lines"}, {"source_code": "import Data.List\n\n\nmatch :: [ String ] -> String\nmatch [ a , b ] = matchHelp ( a ++ take ( length b ) ['0','0'..] ) b where \n matchHelp :: String -> String -> String\n matchHelp [] ys = \"NO\" \n matchHelp t@( x:xs) ys\n | isPrefixOf ys t = \"YES\"\n | otherwise = matchHelp xs ys\n\n\nmain = interact $ match . lines"}, {"source_code": "import Data.List\n\n\nparity :: String -> Char\nparity xs = if odd . length . filter ( == '1' ) $ xs then '1' else '0' \n\nmatch :: [ String ] -> String\nmatch [ a , b ] = matchHelp ( a ++ take ( length b ) [ n , n ..] ) b where \n matchHelp :: String -> String -> String\n matchHelp [] ys = \"NO\\n\" \n matchHelp t@( x:xs) ys\n | isPrefixOf ys t = \"YES\\n\"\n | otherwise = matchHelp xs ys\n n = parity a\n\nmain = interact $ match . lines"}, {"source_code": "import Data.List\n\n\nmatch :: [ String ] -> String\nmatch [ a , b ] = matchHelp ( a ++ take ( length b + 10 ) ['0','0'..] ) b where \n matchHelp :: String -> String -> String\n matchHelp [] ys = \"NO\\n\" \n matchHelp t@( x:xs) ys\n | isPrefixOf ys t = \"YES\\n\"\n | otherwise = matchHelp xs ys\n\n\nmain = interact $ match . lines"}, {"source_code": "main :: IO ()\nmain = interact $ solve . lines\n\nsolve :: [String] -> String\nsolve (a : b : _)\n | s || null b3 || (t && (mod (ij !! 0) 2 > 0 || ij !! 1 > 0)) = \"YES\"\n | otherwise = \"NO\"\n where\n a1 = reverse a\n b1 = reverse b\n x = length $ takeWhile (== '0') a1\n y = length $ takeWhile (== '0') b1\n b2 = drop (y - x) b1\n (s, _) = sub b2 a1 0\n b3 = dropWhile (== '0') b2\n (t, ij) = sub (tail b3) a1 0\n\nsub :: String -> String -> Int -> (Bool, [Int])\nsub [] b i = (True, [i, length $ filter (== '1') b])\nsub _ [] _ = (False, [])\nsub (x : a) (y : b) i\n | x /= y = (False, [])\n | otherwise = sub a b (if x == '1' then i + 1 else i)\n"}], "src_uid": "cf86add6c92fa8a72b8e23efbdb38613"} {"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\n\ngetMin :: [Integer] -> Integer\ngetMin [] = 0\ngetMin xs = ((minimum &&& (length >>> fromIntegral >>> (`mod` 2))) >>> uncurry (*)) xs\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- liftM (map(read::String->Integer) . words) getLine\n print $ (((sum::[Integer] -> Integer) *** ((sum &&& getMin) >>> uncurry (-))) >>> uncurry (+)) $ partition even xs", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n xs <- map fromIntegral <$> getInts :: IO [Int64]\n\n let\n (a, b) = partition even xs\n\n print $ sum a + sum (if even $ length b then b else (tail $ sort b))\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n getLine\n inp <- fmap (map read . words) getLine\n print $ solve inp\n\n\nsolve :: [Integer] -> Integer\nsolve = g . dropWhile (<=0) . sort\n where\n g [] = 0\n g x | even (sum x) = sum x\n | otherwise = sum prefix + sum suffix\n where\n (prefix, _:suffix) = break odd x\n \n\ninp :: [Integer]\ninp = [999999999, 999999999, 999999999, 999999999, 999999999]\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\n-> (solve.concat =<< forM [1.. 1] ( \\i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))\nsolve xs = let fs= filter (\\a->a `mod`2/=0) xs; m = if fs/=[] then minimum fs else 0 ; s=sum xs in if s `mod`2==0 then print s else print (s-m)"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.String\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\n\nmain :: IO()\nmain = do\n _ <- liftM (read::String->Integer) getLine\n xs <- liftM (map(read::String->Integer) . words) getLine\n print $ foldl (+) 0 (filter even xs) + foldl (+) 0 (let ys = sort $ filter odd xs in if even (length ys) then ys else tail ys)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nprocess a | even s = s\n | otherwise = s-m\n where s = sum a\n m = minimum $ filter odd a\n\nmain=do\n getLine\n a<- map read <$> words <$> getLine ::IO [Integer]\n print $ process a\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nmain = do\n B.getLine\n ns <- fmap (map readInteger . B.words) B.getLine\n let s = sum ns\n print $ if even s then s else s - minimum (filter odd ns)\nreadInteger s = i where Just (i,_) = B.readInteger s"}, {"source_code": "import Data.List.Split\n\nsolve n\n | (length o) `rem` 2 == 0 = sum o + sum e\n | otherwise = sum e + sum o - minimum o\n where \n o = filter odd n\n e = filter even n\n\nmain = do \n name <- getLine \n s <- getLine\n let foo = solve (map (read) (splitOn \" \" s))\n putStrLn $ show foo\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n getLine\n s <- getLine\n let ss = words s\n ns = sort $ map (\\x -> read x :: Integer) ss\n summ = sum ns\n if even summ\n then putStrLn $ show summ\n else putStrLn $ show (summ - firstOdd ns)\n\nfirstOdd :: [Integer] -> Integer\nfirstOdd (x:xs)\n | odd x = x\n | otherwise = firstOdd xs\n"}, {"source_code": "solve a\n\t| even s = s\n\t| otherwise = s - minimum [x | x <- a, odd x]\n\twhere s = sum a\n\nmain = do\n\t_ <- getLine\n\tl <- getLine\n\tprint $ solve (map read (words l))"}, {"source_code": "solve a\n\t| even s = s\n\t| otherwise = s - minimum (filter odd a)\n\twhere s = sum a\n\nmain = do\n\t_ <- getLine\n\tl <- getLine\n\tprint $ solve(map read (words l))"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n \n\nmyprint x1 = putStrLn $ intercalate \" \" $ map show x1\n\t\n\nmain= do\n\tn<- read <$> getLine ::IO Int\n\ts<- map (fst.fromJust.C.readInteger) . C.words <$> C.getLine ::IO [Integer]\n\tlet ss = sum s\n\tlet m = filter odd s\n\tif even (length m ) then print ss else print $ ss - minimum m\n\t \n\t "}, {"source_code": "getLoL :: (Read a) => IO [[a]]\ngetLoL = fmap (fmap (fmap read . words) . lines) getContents\n\nmain :: IO ()\nmain = do\n [_, xs] <- getLoL\n print $ solve xs\n\nsolve :: [Integer] -> Integer\nsolve xs = if even s then s else s - leastOdd\n where s = sum xs\n leastOdd = minimum [x | x <- xs, odd x]"}, {"source_code": "import Data.List\n\nsolve xs | s `mod` 2 == 0 = s\n | m > 0 = s - (minimum os)\n | otherwise = 0\n where\n s = sum xs\n os = filter odd xs\n m = length os\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = map read $ words $ last $ lines input :: [Integer]\n print $ solve xs\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Arrow\nimport Data.List\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- liftM (map(read::String->Int) . words) getLine\n print $ ((sum *** (sum &&& ((minimum &&& (length >>> (`mod` 2))) >>> uncurry (*)) >>> uncurry (-))) >>> uncurry (+)) $ partition even xs"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n getLine\n inp <- fmap (map read . words) getLine\n print $ solve inp\n\n\nsolve :: [Int] -> Int\nsolve = g . takeWhile (>=0) . sort\n where\n g [] = 0\n g x | even (sum x) = sum x\n | otherwise = sum prefix + sum suffix\n where\n (prefix, _:suffix) = break odd x\n \n\ninp :: [Int]\ninp = [999999999, 999999999, 999999999, 999999999, 999999999]\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nprocess a | even s = s\n | otherwise = s-m\n where s = sum a\n m = minimum $ filter odd a\n\nmain=do\n getLine\n a<- map read <$> words <$> getLine ::IO [Int]\n print $ process a\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n getLine\n s <- getLine\n let ss = words s\n ns = sort $ map (\\x -> read x :: Int) ss\n summ = sum ns\n if even summ\n then putStrLn $ show summ\n else putStrLn $ show (summ - firstOdd ns)\n\nfirstOdd :: [Int] -> Int\nfirstOdd (x:xs)\n | odd x = x\n | otherwise = firstOdd xs\n"}, {"source_code": "solve a\n\t| even s = s\n\t| otherwise = s - minimum a\n\twhere s = sum a\n\nmain = do\n\t_ <- getLine\n\tl <- getLine\n\tprint $ solve (map read (words l))"}, {"source_code": "import Data.List\n\nsolve xs | s `mod` 2 == 0 = s\n | m > 0 = s - (minimum os)\n | otherwise = 0\n where\n s = sum xs\n os = filter odd xs\n m = length os\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = map read $ words $ last $ lines input :: [Int]\n print $ solve xs\n"}, {"source_code": "import Data.List\n\nsolve xs | s `mod` 2 == 0 = s\n | m > 0 = s - head os\n | otherwise = 0\n where\n os = sort $ filter odd xs\n m = length os\n s = sum xs\n\nmain :: IO ()\nmain = do\n input <- getContents\n let xs = map read $ words $ last $ lines input :: [Int]\n print $ solve xs\n"}], "src_uid": "adb66b7b22d70bb37cb625d531d8865f"} {"source_code": "testcase :: Int->[Int]\r\ntestcase x | mod x 3 == 0 = [(a+1), (a+2), a]\r\n | mod x 3 == 1 = [(b+1), (b+3), b]\r\n | mod x 3 == 2 = [(c+2), (c+3), c]\r\n where a = div (x-3) 3\r\n b = div (x-4) 3\r\n c = div (x-5) 3\r\n\r\nsolve :: Int -> IO()\r\nsolve 0 = putStr \"\"\r\nsolve k = do\r\n line <- getLine\r\n let { n = read ((words line) !! 0);\r\n a = testcase n;\r\n solution = unwords . map show $ a}\r\n putStrLn solution\r\n --putStrLn (\"TEST: \"++ show k)\r\n solve (k-1)\r\n\r\nmain::IO()\r\nmain = do\r\n line <- getLine\r\n let {a = read ((words line) !! 0)}\r\n solve a\r\n\r\n--Problem A, CF #797 (Div. 3)", "positive_code": [{"source_code": "-- boilerplate {{{1\n-- vim: foldmethod=marker\n-- pragmas {{{2\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Main where -- {{{2\n\nimport Control.Applicative\nimport Control.Arrow ( (|||), (&&&) )\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.IO\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bifunctor\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\nimport Data.Foldable hiding ( sum, product )\nimport Data.Function\nimport Data.Functor\nimport Data.IntMap ( IntMap )\nimport Data.IntSet ( IntSet )\nimport Data.List hiding ( sum, product )\nimport Data.Map ( Map )\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Min(..), Max(..) )\nimport Data.Sequence ( Seq )\nimport Data.Set ( Set )\nimport Data.Text ( Text )\nimport Data.Traversable\nimport Data.Tuple\nimport Debug.Trace\nimport Prelude hiding ( sum, product )\nimport System.IO\n-- import System.Random\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.Map as LM\nimport qualified Data.Map.Strict as M\nimport qualified Data.Sequence as Q\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\n\n-- utilites {{{2\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\ngetInt = readInt <$> C.getLine\ngetInts = map readInt . C.words <$> C.getLine\nputShows :: Show a => [a] -> IO ()\nputShows = putStrLn . unwords . map show\nynq = putStrLn . bool \"NO\" \"YES\"\ngcount g@(x:_) = (x, length g)\nmodulus = 10^9 + 7 :: Int\nmod' x = rem x modulus\ntri n = quot (n * n + n) 2\nsum t = foldl' (+) 0 t\nproduct t = foldl' (*) 1 t\nmprint :: Show a => String -> Maybe a -> IO ()\nmprint s = maybe (putStrLn s) print\nifM :: Monad m => m Bool -> m a -> m a -> m a\nifM b t e = b >>= bool e t\nwhenM :: Monad m => m Bool -> m () -> m ()\nwhenM b t = ifM b t (pure ())\n\n-- }}}1\n\nmain = getInt >>= flip replicateM_ docase\n\ndocase = do\n [n] <- getInts\n let (q,r) = quotRem n 3\n putShows $ case r of\n 0 -> [q,q+1,q-1]\n 1 -> [q,q+2,q-1]\n 2 -> [q+1,q+2,q-1]\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep = id\n\nparse = read\n\nformat = id\n\nsolve n = unwords $ map (show . (+b)) p\n where (b,x) = (n-3) `divMod` 3\n p = case x of\n 0 -> [1,2,0]\n 1 -> [1,3,0]\n 2 -> [2,3,0]\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe\r\n\r\n--\r\n\r\nsolve :: Int -> (Int, Int, Int)\r\nsolve n = case n `divMod` 3 of\r\n (k, 0) -> (k, k + 1, k - 1)\r\n (k, 1) -> (k, k + 2, k - 1)\r\n (k, 2) -> (k + 1, k + 2, k - 1)\r\n _ -> error \"fuck\"\r\n\r\ninput = int\r\n\r\noutput (a, b, c) = C.unwords . map (C.pack . show) $ [a, b, c]\r\n\r\nmain :: IO ()\r\nmain = C.interact $ C.unlines . map (output . solve) . runScanner (numberOf input)\r\n\r\n-- Scanner\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith sp sc = evalState sc . sp\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> pure s\r\n\r\nread' :: (C.ByteString -> Maybe (a, C.ByteString)) -> Scanner a\r\nread' q = fst . fromJust . q <$> bstr\r\n\r\nint :: Scanner Int\r\nint = read' C.readInt\r\n\r\ninteger :: Scanner Integer\r\ninteger = read' C.readInteger\r\n\r\n(><) :: Int -> Scanner a -> Scanner [a]\r\n(><) = replicateM\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf = (int >>=) . flip (><)\r\n"}, {"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\n\nsolve :: Int -> (Int, Int, Int)\nsolve s = (h2, h3, h1)\n where\n h1 = (s - 3) `div` 3\n h2 = (s - h1 - 1) `div` 2\n h3 = s - h1 - h2\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n s <- B8.getLine <&> readIntB8\n let (h1, h2, h3) = solve s\n printf \"%d %d %d\\n\" h1 h2 h3\n"}], "negative_code": [], "src_uid": "45cf60f551bd5cbb1f3df6ac3004b53c"} {"source_code": "import Data.Maybe\nimport Data.Bool\nimport Control.Monad\n\nconvL2R :: Char -> Char\nconvL2R '[' = ']'\nconvL2R '{' = '}'\nconvL2R '(' = ')'\nconvL2R '<' = '>'\nconvL2R _ = undefined\n\nisrbr :: Char -> Bool\nisrbr ']' = True\nisrbr '}' = True\nisrbr ')' = True\nisrbr '>' = True\nisrbr _ = False\n\nsolve' :: String -> [Char] -> Maybe Int\nsolve' (x:xs) y\n | and [isrbr x, y == []] = Nothing\n | isrbr x = liftM2 (+) (if x == head y then Just 0 else Just 1) (solve' xs (tail y) )\n | otherwise = solve' xs ([convL2R x] ++ y)\n \nsolve' _ [] = Just 0\nsolve' _ _ = Nothing\n\n\n\nsolve :: String -> Maybe Int\nsolve x = solve' x [] \n\npImpossible :: Maybe Int -> String\n\npImpossible Nothing = \"Impossible\\n\"\npImpossible a = show $ fromJust a\n\n\nparse :: String -> String\n\nparse = pImpossible . solve . unwords. words\n\n\n\n\nmain = interact parse\n", "positive_code": [{"source_code": "import Data.Maybe\nimport Control.Applicative\n\nclose c\n | c == '[' = ']'\n | c == '(' = ')'\n | c == '<' = '>'\n | c == '{' = '}'\n\nisOpen x = x == '{' || x == '[' || x == '<' || x == '('\n\nfold :: [Char] -> [Char] -> Maybe Int\nfold [] [] = Just 0\nfold (x:xs) []\n | isOpen(x) = fold xs [x]\n | otherwise = Nothing\n\nfold [] (p:ps) = Nothing\n\nfold (x:xs) (p:ps)\n | x == '{' || x == '[' || x == '<' || x == '(' = fold xs (x:p:ps)\n | x == close p = fold xs ps\n | otherwise = pure (+) <*> Just 1 <*> fold xs ps\n\n\n\nanswer :: Maybe Int -> String\nanswer Nothing = \"Impossible\"\nanswer (Just i) = show(i)\n\nmain = getLine >>= (\\s -> putStrLn $ answer $ fold s [])\n"}, {"source_code": "\nclose c\n | c == '[' = ']'\n | c == '(' = ')'\n | c == '<' = '>'\n | c == '{' = '}'\n\nisOpen x = x == '{' || x == '[' || x == '<' || x == '('\n\nfold :: [Char] -> [Char] -> Int\nfold [] [] = 0\nfold (x:xs) []\n | isOpen(x) = fold xs [x]\n | otherwise = -100000\n\nfold [] (p:ps) =\n -10000000\n\nfold (x:xs) (p:ps)\n | x == '{' || x == '[' || x == '<' || x == '(' = fold xs (x:p:ps)\n | x == close p = fold xs ps\n | otherwise = 1 + fold xs ps\n\nanswer i \n | i >= 0 = show i\n | otherwise = \"Impossible\"\n\nmain = getLine >>= (\\s -> putStrLn $ answer (fold s []))\n"}, {"source_code": "\nimport Control.Monad\n\nmain = interact $ (\\[s] -> case foldM f (\"\", 0) s of\n Just ([], a) -> show a\n _ -> \"Impossible\"\n ) . words\n\nf (s, a) c\n | elem c \"<([{\" = Just (c:s, a)\n | otherwise = case s of\n [] -> Nothing\n (x:r) -> Just (r, a + if x == l c then 0 else 1)\n\nl '>' = '<'\nl ')' = '('\nl ']' = '['\nl '}' = '{'\n\n"}, {"source_code": "\nimport Control.Monad\n\nmain = interact $ (\\[s] -> case foldM f (\"\", 0) s of\n Just ([], a) -> show a\n _ -> \"Impossible\"\n ) . words\n\nf (s, a) c\n | elem c ['<', '(', '[', '{'] = Just (c:s, a)\n | otherwise = case s of\n [] -> Nothing\n (x:r) -> Just (r, a + if x == l c then 0 else 1)\n\nl '>' = '<'\nl ')' = '('\nl ']' = '['\nl '}' = '{'\n\n"}, {"source_code": "fldl :: (Maybe (a, Int) -> b -> Maybe (a, Int)) -> Maybe (a, Int) -> [b] -> Maybe (a, Int)\nfldl f st [] = st\nfldl f st (x:xs) = fldl f (f st x) xs\n\nsolve :: Maybe (String, Int) -> Char -> Maybe (String, Int)\nsolve Nothing _ = Nothing\nsolve (Just x) '{' = Just (('{': fst x), snd x)\nsolve (Just x) '[' = Just (('[': fst x), snd x)\nsolve (Just x) '(' = Just (('(': fst x), snd x)\nsolve (Just x) '<' = Just (('<': fst x), snd x)\nsolve (Just ((x:xs), n)) '}' = if x == '{' then Just (xs, n) else Just (xs, n + 1)\nsolve (Just ((x:xs), n)) ']' = if x == '[' then Just (xs, n) else Just (xs, n + 1)\nsolve (Just ((x:xs), n)) ')' = if x == '(' then Just (xs, n) else Just (xs, n + 1)\nsolve (Just ((x:xs), n)) '>' = if x == '<' then Just (xs, n) else Just (xs, n + 1)\nsolve _ _ = Nothing\n\npredicat :: Maybe (String, Int) -> String\npredicat (Just ([], x)) = show x\npredicat (Just (_, _)) = \"Impossible\"\npredicat Nothing = \"Impossible\"\n\nmain :: IO()\nmain = getLine >>= \\s -> putStrLn $ predicat $ fldl solve (Just ([], 0)) s\n"}, {"source_code": "import Data.List\n\nmain = do\n s <- getLine\n\n let\n count [] [] = Just 0\n count [] _ = Nothing\n count (c:s) stack\n | c `elem` os = count s (c:stack)\n | null stack = Nothing\n | top `notElem` os = Nothing\n | otherwise = (+ a) `fmap` (count s (tail stack))\n where\n os = \"[<{(\"\n cs = \"]>})\"\n a = if c `elemIndex` cs == top `elemIndex` os then 0 else 1\n top = head stack\n\n r = count s []\n\n case r of\n Nothing -> putStrLn \"Impossible\"\n Just c -> putStrLn $ show c\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n s <- takeWhile (not . isSpace) . BS.unpack <$> BS.getLine\n putStrLn . fromMaybe \"Impossible\" . fmap show $ solve s []\n\nsolve [] [] = Just 0\nsolve [] _ = Nothing\nsolve (c : s) toClose\n | elem c \"([{<\" = solve s $ matching c : toClose\n | otherwise = case toClose of\n [] -> Nothing\n x : xs -> let sol = solve s xs in if x == c then sol else (+ 1) <$> sol\n\nmatching c = case c of\n '(' -> ')'\n '[' -> ']'\n '{' -> '}'\n '<' -> '>'\n _ -> error \"\"\n"}], "negative_code": [{"source_code": "fldl :: ((a, Int) -> b -> (a, Int)) -> (a, Int) -> [b] -> (a, Int)\nfldl f st [] = st\nfldl f st (x:xs) = fldl f (f st x) xs\n\nsolve :: (String, Int) -> Char -> (String, Int)\nsolve x '{' = (('{': fst x), snd x)\nsolve x '[' = (('[': fst x), snd x)\nsolve x '(' = (('(': fst x), snd x)\nsolve x '<' = (('<': fst x), snd x)\nsolve ([], n) _ = (['>'], 0)\nsolve ((x:xs), n) '}' = if x == '{' then (xs, n) else (xs, n + 1)\nsolve ((x:xs), n) ']' = if x == '[' then (xs, n) else (xs, n + 1)\nsolve ((x:xs), n) ')' = if x == '(' then (xs, n) else (xs, n + 1)\nsolve ((x:xs), n) '>' = if x == '<' then (xs, n) else (xs, n + 1)\nsolve ((x:xs), n) _ = (['>'], 0)\n\n\npredicat :: (String, Int) -> String\npredicat ([], x) = show x\npredicat (_, _) = \"Impossible\"\n\nmain :: IO()\nmain = getLine >>= \\s -> putStrLn $ predicat $ fldl solve ([], 0) s\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n s <- BS.unpack <$> BS.getLine\n putStrLn . fromMaybe \"Impossible\" . fmap show $ solve s []\n\nsolve [] [] = Just 0\nsolve [] _ = Nothing\nsolve (c : s) toClose\n | elem c \"([{<\" = solve s $ matching c : toClose\n | otherwise = case toClose of\n [] -> Nothing\n x : xs -> let sol = solve s xs in if x == c then sol else (+ 1) <$> sol\n\nmatching c = case c of\n '(' -> ')'\n '[' -> ']'\n '{' -> '}'\n '<' -> '>'\n ')' -> '('\n ']' -> '['\n '}' -> '{'\n '>' -> '<'\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n s <- BS.unpack <$> BS.getLine\n BS.getContents\n putStrLn . fromMaybe \"Impossible\" . fmap show $ solve s []\n\nsolve [] [] = Just 0\nsolve [] _ = Nothing\nsolve (c : s) toClose\n | elem c \"([{<\" = solve s $ matching c : toClose\n | otherwise = case toClose of\n [] -> Nothing\n x : xs -> let sol = solve s xs in if x == c then sol else (+ 1) <$> sol\n\nmatching c = case c of\n '(' -> ')'\n '[' -> ']'\n '{' -> '}'\n '<' -> '>'\n ')' -> '('\n ']' -> '['\n '}' -> '{'\n '>' -> '<'\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n s <- BS.unpack <$> BS.getLine\n putStrLn s\n --putStrLn . fromMaybe \"Impossible\" . fmap show $ solve s []\n\nsolve [] [] = Just 0\nsolve [] _ = Nothing\nsolve (c : s) toClose\n | elem c \"([{<\" = solve s $ matching c : toClose\n | otherwise = case toClose of\n [] -> Nothing\n x : xs -> let sol = solve s xs in if x == c then sol else (+ 1) <$> sol\n\nmatching c = case c of\n '(' -> ')'\n '[' -> ']'\n '{' -> '}'\n '<' -> '>'\n _ -> error \"\"\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS\n\nmain = do\n s <- BS.unpack <$> BS.getLine\n print $ length s\n --putStrLn . fromMaybe \"Impossible\" . fmap show $ solve s []\n\nsolve [] [] = Just 0\nsolve [] _ = Nothing\nsolve (c : s) toClose\n | elem c \"([{<\" = solve s $ matching c : toClose\n | otherwise = case toClose of\n [] -> Nothing\n x : xs -> let sol = solve s xs in if x == c then sol else (+ 1) <$> sol\n\nmatching c = case c of\n '(' -> ')'\n '[' -> ']'\n '{' -> '}'\n '<' -> '>'\n _ -> error \"\"\n"}, {"source_code": "\nclose c\n | c == '[' = ']'\n | c == '(' = ')'\n | c == '<' = '>'\n | c == '{' = '}'\n\nisOpen x = x == '{' || x == '[' || x == '<' || x == '('\n\nfold :: [Char] -> [Char] -> Int\nfold [] [] = 0\nfold (x:xs) []\n | isOpen(x) = fold xs [x]\n | otherwise = -100000\n\nfold [] (p:ps) =\n -10000000\n\nfold (x:xs) (p:ps)\n | x == '{' || x == '[' || x == '<' || x == '(' = fold xs (x:p:ps)\n | x == close p = fold xs ps\n | otherwise = 1 + fold xs ps\n\nmain = getLine >>= (\\s -> print $ max (fold s []) (-1))\n"}], "src_uid": "4147fef7a151c52e92c010915b12c06b"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.Function (on)\nimport Data.List (intercalate, groupBy, sort, sortBy)\n\nsolve :: Integer -> [Integer] -> Int\nsolve k as = sum $ map (cut . sort . map fst) $ groupSnd $ sortSnd $ zip as $ map kClass as\n where\n sortSnd = sortBy (compare `on` snd)\n groupSnd = groupBy ((==) `on` snd)\n kClass x\n | x `mod` k == 0 = kClass (x `div` k)\n | otherwise = x\n cut (a:b:xs)\n | a * k == b = 1 + cut xs\n | otherwise = 1 + cut (b:xs)\n cut xs = length xs\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n if k == 1 then\n print n\n else do\n as <- reads\n print $ solve k as\n\n where\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Data.List(sort)\n\nmain = putStrLn . show . solve . map (toInteger . maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Integer] -> Int\nsolve (_ : 1 : as) = length as\nsolve (_ : k : as) = sum [(length x + 1) `div` 2 | (_, xs) <- M.toList $ M.fromListWith (++) [(root a, [a]) | a <- as], x <- split $ sort xs]\n where\n split (x : xs) = split' [[x]] xs\n split' ((a : xs) : xss) (b : ys)\n | a * k == b = split' ((b : a : xs) : xss) ys\n | otherwise = split' ([b] : (a : xs) : xss) ys\n split' xss _ = xss\n root a\n | mod a k > 0 = a\n | otherwise = root (div a k)\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.IntSet as S\nimport Data.List\n\nmain = do\n [_, k] <- (map read . words) `fmap` getLine\n as <- (map read . words) `fmap` getLine\n print (solve k as)\n\nsolve :: Int -> [Int] -> Int\nsolve k s = go S.empty (reverse $ sort s)\n where\n mx = maxBound `div` k \n go !s (x:xp) | x > mx || (x*k) `S.notMember` s = go (S.insert x s) xp\n | otherwise = go s xp\n go s [] = S.size s"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (foldl', sort)\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = print =<< solve <$> (read <$> (!!1) <$> words <$> getLine) <*> (map read <$> words <$> getLine)\n\nsolve :: Integer -> [Integer] -> Int\nsolve k = S.size . foldl' (\\s x -> if S.member x s then s else S.insert (k * x) s) S.empty . sort\n"}, {"source_code": "import Data.List as List\nimport qualified Data.Set as Set\n\nreadInts :: String -> [Integer]\nreadInts str = map read (words str)\n\ng :: Integer -> Set.Set Integer -> Integer -> Set.Set Integer\ng k set x\n |Set.member (k*x) set = set\n |otherwise = Set.insert x set\n\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap readInts getLine \n xs' <- fmap readInts getLine\n let xs = reverse $ List.sort xs'\n print $ Set.size $ foldl' (g k) Set.empty xs \n\n"}, {"source_code": "import Data.List as List\nimport qualified Data.Set as Set\n\nreadInts :: String -> [Double]\nreadInts str = map read (words str)\n\ng :: Double -> Set.Set Double -> Double -> Set.Set Double\ng k set x\n |Set.member (k*x) set = set\n |otherwise = Set.insert x set\n\n\nmain :: IO ()\nmain = do\n [_, k] <- fmap readInts getLine \n xs' <- fmap readInts getLine\n let xs = reverse $ List.sort xs'\n print $ Set.size $ foldl' (g k) Set.empty xs \n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.Set as S\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInteger.B.words <$> B.getLine\n print $ solve k xs\n\nsolve :: Integer -> [Integer] -> Int\nsolve k xs = go 0 S.empty $ sort xs\n where\n go !res !set (x:xs)\n | x `S.member` set = go res set xs\n | otherwise = go (res+1) (S.insert (k*x) set) xs\n go res _ _ = res"}], "negative_code": [{"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.List (foldl')\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = print =<< solve <$> (read <$> (!!1) <$> words <$> getLine) <*> (map read <$> words <$> getLine)\n\nsolve :: Integer -> [Integer] -> Int\nsolve k = S.size . foldl' (\\s x -> if S.member x s then s else S.insert (k * x) s) S.empty\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.Set as S\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInteger.B.words <$> B.getLine\n print $ solve k xs\n\nsolve :: Integer -> [Integer] -> Int\nsolve k xs = go 0 S.empty $ sort xs\n where\n go !res !set (x:xs)\n | x `S.member` set = go res (S.insert (k*x) set) xs\n | otherwise = go (res+1) (S.insert (k*x) set) xs\n go res _ _ = res"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.Set as S\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map readInteger.B.words <$> B.getLine\n print $ solve k xs\n\nsolve :: Integer -> [Integer] -> Int\nsolve k xs = go 0 S.empty $ map (\\ys->(length ys,ys!!0)) $ group $ sort xs\n where\n go !res !set ((l,x):xs)\n | x `S.member` set = go res (S.insert (k*x) set) xs\n | otherwise = go (res+l) (S.insert (k*x) set) xs\n go res _ _ = res"}], "src_uid": "4ea1de740aa131cae632c612e1d582ed"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport System.IO qualified as IO\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\ntoInt c = ord c - ord '0'\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n IO.getLine\r\n mapM_ (putStrLn.showDigs.solve) tcs\r\n\r\nshowDigs = concatMap show\r\n\r\nsolve digs = ans\r\n where\r\n ans = L.sort . snd . foldl prevD (9+1,[]) . reverse . map toInt $ digs\r\n\r\nprevD (minDig, digs) dig = (min minDig dig, fixedDig : digs)\r\n where\r\n fixedDig | (dig == 9) = dig\r\n | (dig > minDig) = dig + 1\r\n | otherwise = dig\r\n", "positive_code": [{"source_code": "import Data.Bifunctor (second)\r\nimport Data.Char (chr, ord)\r\nimport Data.List (sort)\r\n\r\n(>$>) = flip ($)\r\n(>>>) = flip (.)\r\ninfixl 0 >$>\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> tail >>> map solve >>> unlines\r\n\r\nsolve :: String -> String\r\nsolve = pick 0 >>> second (sort >>> map (ord >>> (1 +) >>> min (ord '9') >>> chr)) >>> uncurry merge\r\n\r\nmerge :: Ord a => [a] -> [a] -> [a]\r\nmerge [] ys = ys\r\nmerge xs [] = xs\r\nmerge (x : xs) (y : ys)\r\n | x <= y = x : merge xs (y : ys)\r\n | otherwise = y : merge (x : xs) ys\r\n\r\npick :: Int -> String -> (String, String)\r\npick 10 s = (\"\", s)\r\npick d s = (filter (== c) lt ++ lt', filter (/= c) lt ++ rt')\r\n where\r\n c = head $ show d\r\n lt = s >$> reverse >>> dropWhile (/= c)\r\n (lt', rt') = s >$> reverse >>> takeWhile (/= c) >>> reverse >>> pick (d + 1)\r\n"}, {"source_code": "import Data.Char (chr, ord)\r\nimport Data.List (sort)\r\nimport Debug.Trace (trace)\r\n\r\n(>$>) = flip ($)\r\n\r\n(>>>) = flip (.)\r\n\r\ninfixl 0 >$>\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> tail >>> map solve >>> unlines\r\n\r\nsolve :: String -> String\r\nsolve s = merge lt rt'\r\n where\r\n (lt, rt) = pick 0 s\r\n rt' = rt >$> sort >>> map (ord >>> (1 +) >>> min (ord '9') >>> chr)\r\n\r\n\r\nmerge :: Ord a => [a] -> [a] -> [a]\r\nmerge [] ys = ys\r\nmerge xs [] = xs\r\nmerge (x:xs) (y:ys)\r\n | x <= y = x : merge xs (y:ys)\r\n | otherwise = y : merge (x:xs) ys\r\n\r\npick :: Int -> String -> (String, String)\r\npick 10 s = (\"\", s)\r\npick d s = (filter (== c) lt ++ lt', filter (/= c) lt ++ rt')\r\n where\r\n c = head $ show d\r\n lt = s >$> reverse >>> dropWhile (/= c)\r\n (lt', rt') = s >$> reverse >>> takeWhile (/= c) >>> reverse >>> pick (d + 1)\r\n\r\n\r\ndebug :: Show a => a -> a\r\ndebug a = trace (show a) a\r\n"}, {"source_code": "import Data.Char (chr, ord)\nimport Data.List (sort, partition)\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>= putStrLn . minStr\n\ninc :: Char -> Char\ninc c | c < '9' = chr (1+ord c)\n | c == '9'= '9'\n\nminStr :: String -> String\nminStr s = let (ms, rest) = minSubSeq s\n in\n sort (ms ++ map inc rest)\n\n-- WRONG ANSWER for case: 32454 - expected 24445 - got 24556\n-- find the lexicographically smallest subsequence in a given string\nminSubSeq :: String -> (String, String)\nminSubSeq s = let mlss [] (stack, trash) = (reverse stack, trash)\n mlss s (stack, trash) = let (i, c, count) = minCharCount s in\n mlss (drop i s) (replicate count c ++ stack, filter (/=c) (take i s) ++ trash)\n in\n mlss s ([], [])\n\nminCharCount s = foldl f (1, head s, 1) (zip [2..] (tail s))\n where\n f (i, c, count) (ii, cc) = case compare c cc of\n EQ -> (ii, c, count+1)\n GT -> (ii, cc, 1)\n LT -> (i, c, count)\n"}], "negative_code": [{"source_code": "import Data.Char (chr, ord)\nimport Data.List (sort, partition)\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>= putStrLn . minStr\n\nminStr :: String -> String\nminStr s = let (ms, rest) = minSubSeq s\n inc c | c < '9' = chr (1+ord c)\n | c == '9'= '9'\n in\n ms ++ map inc (sort rest)\n\n-- find the lexicographically smallest subsequence in a given string\nminSubSeq :: String -> (String, String)\nminSubSeq s = let mlss [] (stack, []) = (reverse stack, [])\n mlss [] (stack, trash) = let mt = minimum trash\n (s1, t1) = partition ( (ii, c, count+1)\n GT -> (ii, cc, 1)\n LT -> (i, c, count)\n"}], "src_uid": "906b319e41f716e734cf04b34678aa58"} {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Map((!))\r\n\r\nsolve :: Integer -> [Char] -> Bool\r\nsolve _ list \r\n\t| numT /= 2*numM = False \r\n\t| otherwise = (snd $ test list) && (snd $ test $ reverse list)\r\n\twhere\r\n\t\ttest [] = (0, True)\r\n\t\ttest ('M':xs)\r\n\t\t\t| n == 0 = (0, False)\r\n\t\t\t| otherwise = (n-1, b)\r\n\t\t\twhere (n, b) = test xs\r\n\t\ttest ('T':xs) = (n+1, b)\r\n\t\t\twhere (n, b) = test xs\r\n\t\tnumM = sum [1|x<-list, x=='M']\r\n\t\tnumT = sum [1|x<-list, x=='T']\r\n\r\n\r\nshowResult :: Bool -> String\r\nshowResult True = \"YES\"\r\nshowResult False = \"NO\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\tlet loop t = if t == 0 then return () else do \r\n\t\tn <- getLine >>= return . read :: IO Integer\r\n\t\ta <- getLine -- >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tputStrLn $ showResult $ solve n a\r\n\t\tloop $ t - 1\r\n\tloop t", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.Bool ( bool )\r\n\r\nsolve :: Int -> String -> Bool\r\nsolve ((`div` 3) -> k) str = valid && t == k\r\n where\r\n (t, valid) = foldr loop (0, True) str\r\n\r\n loop x (upd x -> t, valid) = (t, valid && 0<=t && t<=k)\r\n\r\n upd 'T' = succ\r\n upd 'M' = pred\r\n\r\n\r\ngetInt = read <$> getLine\r\nmain = do\r\n n <- getInt\r\n replicateM_ n (solve <$> getInt <*> getLine >>= putStrLn . bool \"NO\" \"YES\")\r\n"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\r\nimport Control.Monad ( replicateM_ )\r\nimport Data.Bool ( bool )\r\n\r\nsolve :: Int -> String -> Bool\r\nsolve n str = valid && t == 2 * m\r\n where\r\n ((m, t), valid) = foldr validate ((0, 0), True) str\r\n \r\n validate ch (incr ch -> (m, t), valid) =\r\n ((m, t), valid && (m <= t) && (t - m) <= div n 3)\r\n \r\n incr 'M' (m, t) = (m+1, t)\r\n incr 'T' (m, t) = (m, t+1)\r\n\r\n\r\nmain = do\r\n let getInt = read <$> getLine\r\n n <- getInt\r\n replicateM_ n $ (solve <$> getInt <*> getLine) >>= putStrLn . bool \"NO\" \"YES\"\r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n s <- C.filter (not . isSpace) <$> C.getLine\n let acc Nothing _ = Nothing\n acc (Just x) 'T' = Just (x + 1)\n acc (Just x) _\n | x == 0 = Nothing\n | otherwise = Just (x - 1)\n check = maybe False (== n `div` 3) . C.foldl' acc (Just 0)\n C.putStrLn $ C.pack $ if check s && check (C.reverse s) then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Sequence as Seq\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ntype State = Maybe (Int, Seq.Seq Char)\nacc :: State -> Char -> State\nacc Nothing _ = Nothing\nacc (Just (ls, rs)) 'M'\n | Seq.null bs = Nothing\n | otherwise = Just (ls + Seq.length as, Seq.drop 1 bs Seq.|> 'M')\n where (as, bs) = Seq.spanl (== 'M') rs\nacc (Just (ls, rs)) 'T' = Just (ls, rs Seq.|> 'T')\nacc o _ = o\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n s <- C.getLine\n let\n result = maybe False func $ C.foldl' acc (Just (0, Seq.empty)) s\n func (ms, str) =\n case foldl' acc (Just ms) str of\n Nothing -> False\n Just 0 -> True\n _ -> False\n where acc Nothing _ = Nothing\n acc (Just ms) 'T' = if ms <= 0 then Nothing else Just (ms - 1)\n acc (Just ms) 'M' = Just (ms + 1)\n acc o _ = o\n C.putStrLn $ C.pack $ if result then \"YES\" else \"NO\"\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n s <- C.getLine\n let work str\n | isNothing result = False\n | otherwise = let Just (x, y) = result in x == y\n where\n acc Nothing _ = Nothing\n acc (Just (x, y)) 'M' = if y <= 0 then Nothing else Just (x + 1, y - 1)\n acc (Just (x, y)) _ = Just (x, y + 1 :: Int)\n result = C.foldl' acc (Just (0, 0)) str\n result = if work s && work (C.reverse s) then \"YES\" else \"NO\"\n C.putStrLn $ C.pack result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n s <- C.getLine\n let acc Nothing _ = Nothing\n acc (Just (x, y)) 'M' = if y <= 0 then Nothing else Just (x + 1, y - 1)\n acc (Just (x, y)) _ = Just (x, y + 1 :: Int)\n result = C.foldl' acc (Just (0, 0)) s\n C.putStrLn $ C.pack $ case result of\n Nothing -> \"NO\"\n Just (x, y) -> if x == y then \"YES\" else \"NO\"\n"}, {"source_code": "\r\nimport Control.Monad ( replicateM_ ) \r\nimport Data.Bool ( bool )\r\n\r\nsolve :: Int -> String -> Bool \r\nsolve n str = mod n 3 == 0 && all validate (tail $ scanl count (0, 0) str) where\r\n validate (m, t) = (m <= t) && (t - m) <= div n 3\r\n count (m, t) 'M' = (m+1, t)\r\n count (m, t) 'T' = (m, t+1)\r\n\r\n\r\nmain = do\r\n n <- read <$> getLine\r\n replicateM_ n $ solve <$> (read <$> getLine) <*> getLine >>= putStrLn . bool \"NO\" \"YES\"\r\n"}, {"source_code": "\r\nimport Control.Monad ( replicateM_ ) \r\nimport Data.Bool ( bool )\r\n\r\nsolve :: Int -> String -> Bool \r\nsolve n str = mod n 3 == 0 && all validate (scanl count (0, 0) str) where\r\n validate (m, t) = (m <= t) && (t - m) <= div n 3\r\n count (m, t) 'M' = (m+1, t)\r\n count (m, t) 'T' = (m, t+1)\r\n\r\nmain = do\r\n n <- read <$> getLine\r\n replicateM_ n $ solve <$> (read <$> getLine) <*> getLine >>= putStrLn . bool \"NO\" \"YES\"\r\n"}], "src_uid": "94df40fbf9d7e8f91d5e7fde783bb389"} {"source_code": "module Main (formBestBFromA, main) where\r\n\r\nimport Control.Arrow ((&&&))\r\nimport qualified Data.ByteString.Char8 as B\r\nimport qualified Data.Char as Char\r\nimport qualified Data.List as List\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Set as Set\r\n\r\n\r\n-- 0 0 2 1 1 1 0 0 1 1\r\n-- [], {}\r\n\r\n-- 0 2 1 1 1 0 0 1 1\r\n-- [1], {}\r\n\r\n-- 2 1 1 1 0 0 1 1\r\n-- [1, 1], {}\r\n\r\n-- 1 1 1 0 0 1 1\r\n-- [1, 1, 0], {2}\r\n\r\n-- 1 1 0 0 1 1\r\n-- [2], {2}\r\n-- [3], {}\r\n\r\n-- 1 0 0 1 1\r\n-- [3, 0], {1}\r\n\r\n-- 0 0 1 1\r\n-- [3, 0, 0], {1}\r\n\r\n-- 0 1 1\r\n-- [3, 1], {1}\r\n-- [3, 2], {}\r\n\r\n-- 1 1\r\n-- [3, 2, 1], {}\r\n\r\n-- 1\r\n-- [3, 2, 2], {}\r\n\r\n-- \r\n-- [3, 2, 2, 0], {1}\r\n\r\n\r\nformBestBFromA :: [Integer] -> [Integer]\r\nformBestBFromA = concat . map (\\ (k, n) -> replicate (fromIntegral n) k) . Map.toDescList . fst . List.foldl' updateState (Map.empty, Set.empty)\r\n where\r\n updateState (current_bs, unused_elements) new_element\r\n | Map.member new_element current_bs\r\n = considerUnusedElements (updateBsWithMex (new_element + 1) current_bs, unused_elements)\r\n | new_element == 0 = (addOne 1 current_bs, unused_elements)\r\n | otherwise = (addOne 0 current_bs, Set.insert new_element unused_elements)\r\n\r\n addOne k = Map.insertWith (+) k 1\r\n minKey = fst . Map.findMin\r\n\r\n dropKeysLower x = until (\\ m -> Map.null m || minKey m >= x) Map.deleteMin\r\n takeKeysHigher x = until (\\ m -> Map.null m || minKey m > x) Map.deleteMin\r\n takeElementsHigher x = until (\\ s -> Set.null s || Set.findMin s > x) Set.deleteMin\r\n\r\n updateBsWithMex new_mex = addOne new_mex . dropKeysLower new_mex\r\n\r\n considerUnusedElements (current_b, unused_elements)\r\n | not (null current_b) && Set.member lastB unused_elements\r\n = updateState (current_b, new_unused_elements) lastB\r\n | otherwise = (current_b, new_unused_elements)\r\n where\r\n lastB = minKey current_b\r\n new_unused_elements\r\n | null current_b = Set.empty\r\n | otherwise = takeElementsHigher lastB unused_elements\r\n\r\n\r\n-- IO Section --\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n \r\n \r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.concat . map processTest . takeEverySnd . drop 1 . B.lines\r\n\r\ntakeEverySnd :: [a] -> [a]\r\ntakeEverySnd (x1:x2:xs) = x2 : takeEverySnd xs\r\ntakeEverySnd xs = []\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest = outputFromB . formBestBFromA . readIntegers\r\n where\r\n outputFromB = B.unlines . pairToList . ((bshow . List.genericLength) &&& (B.unwords . map bshow))\r\n bshow = B.pack . show\r\n pairToList (a, b) = [a, b]\r\n\r\n\r\nreadIntegers :: B.ByteString -> [Integer]\r\nreadIntegers = List.unfoldr (B.readInteger . B.dropWhile Char.isSpace)\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n aLi <- replicateM n getInt\n let\n occs = reverse <$> accumArray (flip (:)) [] (0, n) (zip aLi [1 .. n])\n step :: (Int, Array Int [Int]) -> Maybe (Int, (Int, Array Int [Int]))\n step (j, arr) = if j == n\n then Nothing\n else let\n mex = head [i | (i, []) <- assocs arr]\n j' = foldl' max (j + 1) [head $ arr ! i | i <- [0 .. mex - 1]]\n newArr\n = array (0, mex) [(i, dropWhile (<= j') $ arr ! i) | i <- [0 .. mex]]\n in Just (mex, (j', newArr))\n ans = unfoldr step (0, occs)\n pure $ putInts [length ans] <> putInts ans\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "module Main (fromBestBFromA, main) where\r\n\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\nimport Data.Char (isSpace)\r\nimport Data.List (foldl', unfoldr)\r\nimport qualified Data.Map as Map\r\nimport qualified Data.Set as Set\r\n\r\n\r\n-- 0 0 2 1 1 1 0 0 1 1\r\n-- [], {}\r\n\r\n-- 0 2 1 1 1 0 0 1 1\r\n-- [1], {}\r\n\r\n-- 2 1 1 1 0 0 1 1\r\n-- [1, 1], {}\r\n\r\n-- 1 1 1 0 0 1 1\r\n-- [1, 1, 0], {2}\r\n\r\n-- 1 1 0 0 1 1\r\n-- [2], {2}\r\n-- [3], {}\r\n\r\n-- 1 0 0 1 1\r\n-- [3, 0], {1}\r\n\r\n-- 0 0 1 1\r\n-- [3, 0, 0], {1}\r\n\r\n-- 0 1 1\r\n-- [3, 1], {1}\r\n-- [3, 2], {}\r\n\r\n-- 1 1\r\n-- [3, 2, 1], {}\r\n\r\n-- 1\r\n-- [3, 2, 2], {}\r\n\r\n-- \r\n-- [3, 2, 2, 0], {1}\r\n\r\n\r\nfromBestBFromA :: [Integer] -> [Integer]\r\nfromBestBFromA = concat . map (\\ (k, n) -> replicate (fromIntegral n) k) . Map.toDescList . fst . foldl' updateState (Map.empty, Set.empty)\r\n where\r\n updateState (current_bs, unused_elements) new_element\r\n | Map.member new_element current_bs\r\n = considerUnusedElements (updateBsWithMex (new_element + 1) current_bs, unused_elements)\r\n | new_element == 0 = (addOne 1 current_bs, unused_elements)\r\n | otherwise = (addOne 0 current_bs, Set.insert new_element unused_elements)\r\n\r\n addOne k = Map.insertWith (+) k 1\r\n minKey = fst . Map.findMin\r\n\r\n dropKeysLower x = until (\\ m -> Map.null m || minKey m >= x) Map.deleteMin\r\n takeKeysHigher x = until (\\ m -> Map.null m || minKey m > x) Map.deleteMin\r\n takeElementsHigher x = until (\\ s -> Set.null s || Set.findMin s > x) Set.deleteMin\r\n\r\n updateBsWithMex new_mex = addOne new_mex . dropKeysLower new_mex\r\n\r\n considerUnusedElements (current_b, unused_elements)\r\n | not (null current_b) && Set.member lastB unused_elements\r\n = updateState (current_b, new_unused_elements) lastB\r\n | otherwise = (current_b, new_unused_elements)\r\n where\r\n lastB = minKey current_b\r\n new_unused_elements\r\n | null current_b = Set.empty\r\n | otherwise = takeElementsHigher lastB unused_elements\r\n\r\n\r\n-- IO Section --\r\n\r\n\r\nmain :: IO ()\r\nmain = B.interact processInput\r\n \r\n \r\nprocessInput :: B.ByteString -> B.ByteString\r\nprocessInput = B.unlines . map processTest . takeEverySnd . drop 1 . B.lines\r\n\r\ntakeEverySnd :: [a] -> [a]\r\ntakeEverySnd (x1:x2:xs) = x2 : takeEverySnd xs\r\ntakeEverySnd xs = []\r\n\r\nprocessTest :: B.ByteString -> B.ByteString\r\nprocessTest = B.unwords . map bshow . fromBestBFromA . readIntegers\r\n where\r\n bshow = B.pack . show\r\n\r\n\r\nreadIntegers :: B.ByteString -> [Integer]\r\nreadIntegers = unfoldr (B.readInteger . B.dropWhile isSpace)\r\n \r\n \r\nreadInteger :: B.ByteString -> Integer\r\nreadInteger s = r\r\n where [r] = readIntegers s\r\n \r\n \r\nreadInt :: B.ByteString -> Int\r\nreadInt = fromInteger . readInteger\r\n"}], "src_uid": "962c4354c936030da78261871dd6d55b"} {"source_code": "import qualified Data.Map as M\nimport Data.Maybe\n\nchars = ['a'..'z']\nmain = do\n s <- getLine\n bits <- getLine\n k <- getLine\n let good = [(chars !! i, (if (bits !! i) == '1' then 1 else 0)) | i <- [0..25]]\n let ans = solve s good (read k)\n putStrLn $ show ans\n\ndata TrieNode = TrieNode \n { cnt:: Int\n , trans :: M.Map Char TrieNode\n } deriving Show\n\nsolve :: String -> [(Char, Int)] -> Int -> Int\nsolve s good k = solve' s good k (TrieNode 0 M.empty)\n\nsolve' :: String -> [(Char, Int)] -> Int -> TrieNode -> Int\nsolve' [] _ _ _ = 0\nsolve' s@(c:s') good k p = \n solveSingle s good k p' + solve' s' good k p'\n where p' = insert p s\n\nsolveSingle :: String -> [(Char, Int)] -> Int -> TrieNode -> Int\nsolveSingle s good k p = ans\n where \n (ans, bad, p') = foldl func (0, 0, p) s\n func (ans, bad, p) c = let\n bad' = bad + 1 - (fromJust $ lookup c good)\n ans' = ans + (if bad' <= k && cnt p' == 1 then 1 else 0)\n p' = fromJust $ M.lookup c (trans p)\n in (ans', bad', p')\n\ninsert :: TrieNode -> String -> TrieNode\ninsert p [] = p \ninsert p (c:s') = p { trans = M.insert c p' (trans p) }\n where \n p' = case M.lookup c (trans p) of\n Nothing -> insert (TrieNode 1 M.empty) s'\n Just pc -> insert (pc { cnt = (cnt pc) + 1 }) s'\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Char (digitToInt)\n\nmain = do \n s <- getLine\n t <- getLine\n k <- readLn\n print $ solve (map ((1-) . digitToInt) t) k s\n\npairwise l@(_:ht) = zip l ht\ncommon pre post = length $ (takeWhile eq) $ zip pre post\n where eq (k1, k2) = k1 == k2\n\nsolve t k = sum . (map pair) . pairwise . sort . tails\n where \n bad ch = t !! (fromEnum ch - 97)\n pair (pre, post) = length $ takeWhile (<= k) $ tail accum \n where \n delta = (common pre post)\n stop = sum $ map bad $ take delta post\n accum = scanl (+) stop $ map bad $ drop delta post"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Data.Array.Base\nimport qualified Data.Map as M\nimport Data.List\n\nmain = do\n cs <- getLine\n isGood <- fmap(listArray('a','z').map('1'==))getLine\n k <- readLn\n print $ solve k cs isGood\n \ndata Trie = Node !Int !(M.Map Char Trie)\n\nsolve :: Int -> String -> UArray Char Bool -> Int\nsolve k cs arr = pred.cnt $ foldl' (flip ins) (Node 0 M.empty) $ tails cs\n where\n isGood c = unsafeAt arr $ fromEnum c - 97\n\n ins :: String -> Trie -> Trie\n ins (c:cs) (Node cnt f)\n | Just trie <- M.lookup c f = Node cnt (M.insert c (ins cs trie) f)\n | isGood c = Node cnt (M.insert c (ins cs (Node cnt M.empty)) f)\n | cnt < k = Node cnt (M.insert c (ins cs (Node (cnt+1) M.empty)) f)\n ins _ trie = trie\n\n cnt :: Trie -> Int\n cnt (Node _ f) = M.foldr' ((+).cnt) 1 f"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.STRef\nimport Data.Word\n\n#if __GLASGOW_HASKELL__ < 706\nmodifySTRef' :: STRef s a -> (a -> a) -> ST s ()\nmodifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x\n{-# INLINE modifySTRef' #-}\n#endif\n\ntype Hash = Word32\n\nbase1,base2 :: Hash\nbase1 = 1000000007\nbase2 = 999999937\n\nmask :: Hash\nmask = 0x3fffffff\n\nmain = do\n cs <- fmap (map $ fromIntegral.fromEnum) getLine\n isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine\n k <- readLn\n print $ solve k cs isBad\n\nsolve :: Int -> [Hash] -> UArray Char Int -> Int\nsolve k cs isBad = runST $ do\n res <- newSTRef 0 :: ST s (STRef s Int)\n hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n let f ccs@(_:cs) = g 0 0 0 ccs >> f cs\n f [] = readSTRef res\n g !hash1 !hash2 !cnt (c:cs) = do\n let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97\n when (cnt'<=k) $ do\n let !h1 = (hash1 * base1 + c) .&. mask\n !h2 = (hash2 * base2 + c) .&. mask\n flg1 <- unsafeRead hashtable1 $ fromIntegral h1\n flg2 <- unsafeRead hashtable2 $ fromIntegral h2\n unless (flg1 && flg2) $ do\n modifySTRef' res (1+)\n unsafeWrite hashtable1 (fromIntegral h1) True\n unsafeWrite hashtable2 (fromIntegral h2) True\n g h1 h2 cnt' cs\n g _ _ _ _ = return ()\n f cs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.STRef\nimport Data.Word\n\n#if __GLASGOW_HASKELL__ < 706\nmodifySTRef' :: STRef s a -> (a -> a) -> ST s ()\nmodifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x\n{-# INLINE modifySTRef' #-}\n#endif\n\ntype Hash = Word32\n\nbase1,base2 :: Hash\nbase1 = 1000000007\nbase2 = 99991\n\nmask :: Hash\nmask = 0x3fffffff\n\nmain = do\n cs <- fmap (map $ fromIntegral.fromEnum) getLine\n isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine\n k <- readLn\n print $ solve k cs isBad\n\nsolve :: Int -> [Hash] -> UArray Char Int -> Int\nsolve k cs isBad = runST $ do\n res <- newSTRef 0 :: ST s (STRef s Int)\n hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n let f ccs@(_:cs) = g 0 0 0 ccs >> f cs\n f [] = readSTRef res\n g !hash1 !hash2 !cnt (c:cs) = do\n let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97\n when (cnt'<=k) $ do\n let !h1 = (hash1 * base1 + c) .&. mask\n !h2 = (hash2 * base2 + c) .&. mask\n flg1 <- unsafeRead hashtable1 $ fromIntegral h1\n flg2 <- unsafeRead hashtable2 $ fromIntegral h2\n unless (flg1 && flg2) $ do\n modifySTRef' res (1+)\n unsafeWrite hashtable1 (fromIntegral h1) True\n unsafeWrite hashtable2 (fromIntegral h2) True\n g h1 h2 cnt' cs\n g _ _ _ _ = return ()\n f cs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.STRef\nimport Data.Word\n\n#if __GLASGOW_HASKELL__ < 706\nmodifySTRef' :: STRef s a -> (a -> a) -> ST s ()\nmodifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x\n{-# INLINE modifySTRef' #-}\n#endif\n\ntype Hash = Word32\n\nbase1,base2 :: Hash\nbase1 = 1000000007\nbase2 = 997\n\nmask :: Hash\nmask = 0x3fffffff\n\nmain = do\n cs <- fmap (map $ fromIntegral.fromEnum) getLine\n isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine\n k <- readLn\n print $ solve k cs isBad\n\nsolve :: Int -> [Hash] -> UArray Char Int -> Int\nsolve k cs isBad = runST $ do\n res <- newSTRef 0 :: ST s (STRef s Int)\n hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n let f ccs@(_:cs) = g 0 0 0 ccs >> f cs\n f [] = readSTRef res\n g !hash1 !hash2 !cnt (c:cs) = do\n let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97\n when (cnt'<=k) $ do\n let !h1 = (hash1 * base1 + c) .&. mask\n !h2 = (hash2 * base2 + c) .&. mask\n flg1 <- unsafeRead hashtable1 $ fromIntegral h1\n flg2 <- unsafeRead hashtable2 $ fromIntegral h2\n unless (flg1 && flg2) $ do\n modifySTRef' res (1+)\n unsafeWrite hashtable1 (fromIntegral h1) True\n unsafeWrite hashtable2 (fromIntegral h2) True\n g h1 h2 cnt' cs\n g _ _ _ _ = return ()\n f cs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.STRef\nimport Data.Word\n\n#if __GLASGOW_HASKELL__ < 706\nmodifySTRef' :: STRef s a -> (a -> a) -> ST s ()\nmodifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x\n{-# INLINE modifySTRef' #-}\n#endif\n\ntype Hash = Word32\n\nbase1,base2 :: Hash\nbase1 = 1000000007\nbase2 = 1000000009\n\nmask :: Hash\nmask = 0x1fffffff\n\nmain = do\n cs <- fmap (map $ fromIntegral.fromEnum) getLine\n isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine\n k <- readLn\n print $ solve k cs isBad\n\nsolve :: Int -> [Hash] -> UArray Char Int -> Int\nsolve k cs isBad = runST $ do\n res <- newSTRef 0 :: ST s (STRef s Int)\n hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n let f ccs@(_:cs) = g 0 0 0 ccs >> f cs\n f [] = readSTRef res\n g !hash1 !hash2 !cnt (c:cs) = do\n let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97\n when (cnt'<=k) $ do\n let !h1 = (hash1 * base1 + c) .&. mask\n !h2 = (hash2 * base2 + c) .&. mask\n flg1 <- unsafeRead hashtable1 $ fromIntegral h1\n flg2 <- unsafeRead hashtable2 $ fromIntegral h2\n unless (flg1 && flg2) $ do\n modifySTRef' res (1+)\n unsafeWrite hashtable1 (fromIntegral h1) True\n unsafeWrite hashtable2 (fromIntegral h2) True\n g h1 h2 cnt' cs\n g _ _ _ _ = return ()\n f cs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -cpp #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.STRef\nimport Data.Word\n\n#if __GLASGOW_HASKELL__ < 706\nmodifySTRef' :: STRef s a -> (a -> a) -> ST s ()\nmodifySTRef' r f=do x<-readSTRef r;writeSTRef r$!f x\n{-# INLINE modifySTRef' #-}\n#endif\n\ntype Hash = Word32\n\nbase1,base2 :: Hash\nbase1 = 1000000007\nbase2 = 100000007\n\nmask :: Hash\nmask = 0x3fffffff\n\nmain = do\n cs <- fmap (map $ fromIntegral.fromEnum) getLine\n isBad <- fmap(listArray('a','z').map(fromEnum.('0'==)))getLine\n k <- readLn\n print $ solve k cs isBad\n\nsolve :: Int -> [Hash] -> UArray Char Int -> Int\nsolve k cs isBad = runST $ do\n res <- newSTRef 0 :: ST s (STRef s Int)\n hashtable1 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n hashtable2 <- newArray (0,mask) False :: ST s (STUArray s Hash Bool)\n let f ccs@(_:cs) = g 0 0 0 ccs >> f cs\n f [] = readSTRef res\n g !hash1 !hash2 !cnt (c:cs) = do\n let cnt' = (cnt+).unsafeAt isBad $ fromIntegral c - 97\n when (cnt'<=k) $ do\n let !h1 = (hash1 * base1 + c) .&. mask\n !h2 = (hash2 * base2 + c) .&. mask\n flg1 <- unsafeRead hashtable1 $ fromIntegral h1\n flg2 <- unsafeRead hashtable2 $ fromIntegral h2\n unless (flg1 && flg2) $ do\n modifySTRef' res (1+)\n unsafeWrite hashtable1 (fromIntegral h1) True\n unsafeWrite hashtable2 (fromIntegral h2) True\n g h1 h2 cnt' cs\n g _ _ _ _ = return ()\n f cs\n"}], "src_uid": "c0998741424cd53de41d31f0bbaef9a2"} {"source_code": "import Control.Arrow ((***))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [[n], ds, [s, t]] | s == t = 0\n | otherwise = uncurry min $ (sum *** sum) $ splitAt (max s t - min s t)\n $ take n $ drop (min s t - 1) $ ds ++ ds\nsolve _ = undefined\n", "positive_code": [{"source_code": "import Control.Arrow ((***))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [[n], ds, [s, t]]\n | s == t = 0\n | otherwise = uncurry min $ (sum *** sum) $ splitAt (max s t - min s t)\n $ take n $ drop (min s t - 1) $ cycle ds\nsolve _ = undefined\n"}, {"source_code": "main = do\n getLine\n d <- fmap (map read . words) getLine\n [s, t] <- fmap (map read . words) getLine\n print $ solve d s t\nsolve d s t | s == t = 0\n | s > t = solve d t s\n | s < t = min fwdWay $ sum d - fwdWay\n where fwdWay = forward d s t\nforward d s t = sum . take (t-s) . drop (s-1) $ d\n"}, {"source_code": "import Data.List\nmain=interact$show.f.map read.words\nf(n:tmp) = min d $ sum ds - d\n where\n (ds,st) = splitAt n tmp\n [s,t] = sort st\n d = sum.take(t-s)$drop(s-1)ds"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n distances <- getLine >> getLine >>= (return . map read . words) :: IO [Int]\n [s1, s2] <- getLine >>= (return . sort . map read . words) :: IO [Int]\n let total = sum distances\n dist = sum $ drop (s1 - 1) $ take (s2 - 1) distances\n print $ min dist (total - dist)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\n\n \n\nmain= do\n\tgetLine \n\tt<- map read. words <$> getLine::IO [Int]\n\tx<- map read.words <$> getLine::IO [Int]\n\tlet s= minimum x\n\tlet e = maximum x\n\tlet ans1 = sum $ take (e-s) $ drop (s-1) t\n\tlet ans2 = (sum t)- ans1\n\tprint $ min ans1 ans2"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = getLine >> replicateM 2 getLine\n >>= return . map (map read . words)\n >>= putStrLn . show . solve\n\nsolve :: [[Int]] -> Int\nsolve [ds, (a:b:ot)] = min ar $ foldl1 (+) ds - ar\n where ar = foldl (+) 0 $ clip (pred a) (pred b) ds\n\nclip :: Int -> Int -> [a] -> [a]\nclip a b = drop from . take to\n where from = min a b\n to = max a b\n "}, {"source_code": "\nmain = do\n\tn<-getLine\n\tds<-getLine\n\tst<-getLine\n\tlet [s,t] = map read $ words st\n\tputStrLn $ show $ solve (read n) (map read (words ds)) s t\n\nsolve::Int->[Int]->Int->Int->Int\nsolve n d s t | s==t = 0\n | otherwise = min (sum $ drop (min s t -1) $ take (max s t-1) d) (sum $ take (min s t-1) d ++ drop (max s t-1) d)\n where dist = abs (s-t)"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ show . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve (_ : ds : st : _) = min a b\n where\n (s : t : _) = sort st\n a = sum $ drop (s - 1) $ take (t - 1) ds\n b = sum ds - a\n"}, {"source_code": "import Data.List\n\nsolve nums s t =\n let hs = take s nums in\n let ts = drop t nums in\n let ms = drop s (take t nums) in\n let sum1 = sum hs + sum ts in\n let sum2 = sum ms in\n min sum1 sum2\n\nmain = do\n getLine\n numsStr <- getLine\n let nums = map read $ words numsStr\n stStr <- getLine\n let [s,t] = sort $ map read $ words stStr\n print (solve nums (s-1) (t-1))\n"}, {"source_code": "\nmodule Main (\n main\n) where\n\nimport Data.List\n\nsolve nums s t =\n let hs = take s nums in\n let ts = drop t nums in\n let ms = drop s (take t nums) in\n let sum1 = sum hs + sum ts in\n let sum2 = sum ms in\n min sum1 sum2\n\nmain = do\n getLine\n numsStr <- getLine\n let nums = map read $ words numsStr\n stStr <- getLine\n let [s,t] = sort $ map read $ words stStr\n print (solve nums (s-1) (t-1))\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.List (nub)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve s t xs = min a b\n where\n a = sum $ drop (s - 1) $ take (t - 1) xs\n b = sum xs - a\n\nmain :: IO ()\nmain = do\n getLine\n xs <- reads\n [t, s] <- reads\n print $ solve (min t s) (max t s) xs\n"}, {"source_code": "-- Codeforces 278A\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n path <- fmap (map read . words) getLine :: IO [Int]\n aim <- fmap (map read . words) getLine :: IO [Int]\n print $ solve n (concat $ replicate 2 path) (sort aim) where\n solve n xs [s, t] = min (len s t) (len t (s+n)) where\n len a b = sum $ take (b-a) $ drop (a-1) xs\n"}, {"source_code": "import Control.Applicative\n\nparseLine = map read . words <$> getLine\n\nmain = do\n n <- read <$> getLine\n xs <- parseLine\n [x,y] <- parseLine\n let cyc = cycle xs\n (mn,mx) = (min x y, max x y)\n n1 = sum . take (mx-mn) . drop (mn-1) $ cyc\n n2 = sum . take (n+mn-mx) . drop (mx-1) $ cyc\n print $ min n1 n2\n"}], "negative_code": [{"source_code": "\nmodule Main (\n main\n) where\n\nimport Data.List\n\nsolve nums s t =\n let hs = take s nums in\n let ts = drop t nums in\n let ms = drop s (take t nums) in\n let sum1 = sum hs + sum ts in\n let sum2 = sum ms in\n min sum1 sum2\n\nmain = do\n getLine\n numsStr <- getLine\n let nums = map read $ words numsStr\n stStr <- getLine\n let [s,t] = map read $ words stStr\n print (solve nums (s-1) (t-1))\n"}, {"source_code": "import Control.Arrow ((***))\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [[n], ds, [s, t]] | s == t = 0\n | otherwise = uncurry min $ (sum *** sum) $ splitAt (max s t - min s t)\n $ take (min s t + n - 1) $ drop (min s t - 1) $ ds ++ ds\nsolve _ = undefined\n"}, {"source_code": "import Data.List (unfoldr)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [[n], ds, [s, t]] | s == t = 0\n | otherwise = minimum $ map sum $ splitN (max s t - 1)\n $ take (min s t + n - 1) $ drop (min s t - 1) $ ds ++ ds\nsolve _ = undefined\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\n\n \n\nmain= do\n\tgetLine \n\tt<- map read. words <$> getLine::IO [Int]\n\tx<- map read.words <$> getLine::IO [Int]\n\tlet s= minimum x\n\tlet e = maximum x\n\tlet ans1 = sum $ take (e-1) $ drop (s-1) t\n\tlet ans2 = (sum t)- ans1\n\tprint $ min ans1 ans2"}], "src_uid": "22ef37041ebbd8266f62ab932f188b31"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\ntransform :: String -> String -> Int -> (Ordering, Int)\ntransform \"Y\" \">=\" x = (GT, x-1)\ntransform \"N\" \">=\" x = (LT, x)\ntransform \"Y\" \"<=\" x = (LT, x+1)\ntransform \"N\" \"<=\" x = (GT, x)\ntransform \"Y\" \">\" x = (GT, x)\ntransform \"N\" \">\" x = (LT, x+1)\ntransform \"Y\" \"<\" x = (LT, x)\ntransform \"N\" \"<\" x = (GT, x-1)\ntransform _ _ _ = undefined\n\nmain :: IO ()\nmain = do \n n <- readInt <$> C.getLine\n array <- replicateM n $ do\n [symbol, x, ans] <- C.words <$> C.getLine\n return $ transform (C.unpack ans) (C.unpack symbol) (readInt x)\n let lt = [y | (x,y) <- array, x == LT]\n gt = [y | (x,y) <- array, x == GT]\n ltmi = minimum lt\n gtmx = maximum gt\n if null lt then print $ gtmx + 1\n else if null gt then print $ ltmi - 1\n else if ltmi - 1 > gtmx then print $ ltmi - 1\n else putStrLn \"Impossible\"\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\ndata Compare = LE | GE\n\ndata Query = Q Compare Int\n\napply :: (Int,Int) -> Query -> Maybe (Int,Int)\napply (lo,hi) (Q LE val)\n | val < lo = Nothing\n | otherwise = Just (lo, min val hi)\napply (lo,hi) (Q GE val)\n | val > hi = Nothing\n | otherwise = Just (max lo val, hi)\n\ncomplement :: Query -> Query\ncomplement (Q LE v) = Q GE (v+1)\ncomplement (Q GE v) = Q LE (v-1)\n\nreadQuery :: String -> Query\nreadQuery str =\n let (op:vs:bs:_) = words str\n v = read vs\n q1 = if | op == \">=\" -> Q GE v\n | op == \"<=\" -> Q LE v\n | op == \">\" -> Q GE (v+1)\n | op == \"<\" -> Q LE (v-1)\n q2 = if bs == \"Y\" then q1 else complement q1\n in q2\n\nmain = do\n n <- fmap read getLine\n queries <- replicateM n $ do fmap readQuery getLine\n let inf = 2*10^9 :: Int\n let loop r [] = Just r\n loop r (q:qs) = case apply r q of\n Nothing -> Nothing\n Just r' -> loop r' qs\n r = loop (-inf,inf) queries\n case r of\n Nothing -> putStrLn \"Impossible\" \n Just (lo,hi) -> putStrLn $ show hi\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe (fromJust)\n\ndata InequalitySign = LARGERT | SMALLERT | LTE | STE\n deriving (Eq)\n\nreverseSign LARGERT = STE\nreverseSign SMALLERT = LTE\nreverseSign LTE = SMALLERT\nreverseSign STE = LARGERT\n\ntoInequality \">\" = LARGERT\ntoInequality \"<\" = SMALLERT\ntoInequality \">=\" = LTE\ntoInequality \"<=\" = STE\n\ntranslate [a,b,c] = if c == \"Y\" then (i, read b) else (reverseSign i, read b)\n where i = toInequality a\n\nmain = do\n n <- readLn\n xs <- replicateM n (translate . words <$> getLine)\n let\n f [] (lb,ub) = if lb < ub then Just (lb, ub) else Nothing\n f ((i,x):ys) (lb,ub)\n | i == LARGERT = if x-1 >= ub\n then Nothing\n else f ys (max (x+1) lb, ub)\n | i == SMALLERT = if x <= lb\n then Nothing\n else f ys (lb, min x ub)\n | i == LTE = if x >= ub\n then Nothing\n else f ys (max x lb, ub)\n | i == STE = if x < lb\n then Nothing\n else f ys (lb, min (x+1) ub)\n b = f xs (-1000000010, 1000000010)\n result = if b == Nothing then \"Impossible\" else show . fst $ fromJust b\n in putStrLn $ result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\n\nsolve :: [String] -> Maybe Int\nsolve ss = if l > r then Nothing\n else Just l\n where (l, r) = hlp (-2*10^9, 2*10^9) ss\n hlp :: (Int, Int) -> [String] -> (Int, Int)\n hlp (a, b) [] = (a, b)\n hlp (a, b) (s:ts) =\n if ((sgn == \">=\") && (ans == \"Y\")) || ((sgn == \"<\") && (ans == \"N\")) then\n if n > a then hlp (n, b) ts\n else hlp (a, b) ts\n else if ((sgn == \"<=\") && (ans == \"Y\")) || ((sgn == \">\") && (ans == \"N\")) then\n if n < b then hlp (a, n) ts\n else hlp (a, b) ts\n else if ((sgn == \"<\") && (ans == \"Y\")) || ((sgn == \">=\") && (ans == \"N\")) then\n if n-1 < b then hlp (a, n-1) ts\n else hlp (a, b) ts\n else if ((sgn == \">\") && (ans == \"Y\")) || ((sgn == \"<=\") && (ans == \"N\")) then\n if n+1 > a then hlp (n+1, b) ts\n else hlp (a, b) ts\n else (a, b)\n where [sgn, n', ans] = words s\n n = read n'\n\nmain = do\n n <- fmap read getLine\n lst <- forM [1..n] (\\_ -> getLine)\n let solution = solve lst\n if isNothing solution then putStrLn \"Impossible\"\n else print (fromJust solution)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmain=interact$maybe \"Impossible\" show.solve.parse.tail.words\n\nsolve :: [Either Int Int] -> Maybe Int\nsolve xs = go (-2000000000) 2000000000 xs\n where\n go !l !r (Left i:xs) = go (max l i) r xs\n go !l !r (Right i:xs) = go l (min r i) xs\n go !l !r []\n | l <= r = Just l\n | otherwise = Nothing\n\nparse :: [String] -> [Either Int Int]\nparse (\">\":i:\"Y\":cs) = Left (read i+1) : parse cs\nparse (\">=\":i:\"Y\":cs) = Left (read i) : parse cs\nparse (\"<\":i:\"Y\":cs) = Right (read i-1) : parse cs\nparse (\"<=\":i:\"Y\":cs) = Right (read i) : parse cs\nparse (\">\":i:\"N\":cs) = parse (\"<=\":i:\"Y\":cs)\nparse (\">=\":i:\"N\":cs) = parse (\"<\":i:\"Y\":cs)\nparse (\"<\":i:\"N\":cs) = parse (\">=\":i:\"Y\":cs)\nparse (\"<=\":i:\"N\":cs) = parse (\">\":i:\"Y\":cs)\nparse _ = []\n"}, {"source_code": "import Data.Maybe\n\ndata Var = Gt \n\nprocess :: Integer -> Integer -> [[String]] -> Maybe Integer\nprocess a b _ | a > b = Nothing\nprocess a _ [] = Just a\nprocess a b ((sign:x:\"N\":[]):other_lines) = process a b ((oposite sign:x:\"Y\":[]):other_lines)\n\nprocess a b ((\">=\":x:\"Y\":[]):other_lines) = process (max a $ read x) b other_lines\nprocess a b ((\">\":x:\"Y\":[]):other_lines) = process (max a $ 1 + read x) b other_lines\nprocess a b ((\"<\":x:\"Y\":[]):other_lines) = process a (min b $ -1 + read x) other_lines\nprocess a b ((\"<=\":x:\"Y\":[]):other_lines) = process a (min b $ read x) other_lines\n\noposite \">=\" = \"<\"\noposite \"<=\" = \">\"\noposite \"<\" = \">=\"\noposite \">\" = \"<=\"\n\nmain = do\n n <- read `fmap` getLine\n my_lines <- sequence $ replicate n getLine\n\n let\n res = process (-2000000000) 2000000000 (map words my_lines)\n\n putStrLn $ if res == Nothing then \"Impossible\" else show $ fromJust res\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, BangPatterns, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\ndata Answer = Lt !Int | Geq !Int\n\nneg :: Answer -> Answer\nneg (Lt a) = Geq a\nneg (Geq a) = Lt a\n\ninputAnswer :: IO Answer\ninputAnswer = do\n\t[sign, ns, ts] <- words <$> getLine\n\tlet n :: Int = read ns\n\tlet t = ts == \"Y\"\n\tlet ans = case sign of\n\t\t\">=\" -> Geq n\n\t\t\"<\" -> Lt n\n\t\t\">\" -> Geq (n + 1)\n\t\t\"<=\" -> Lt (n + 1)\n\treturn $ if t then ans else neg ans\n\n\nsolve :: [Answer] -> Maybe Int\nsolve = go (-2^30, 2^30)\n\twhere\n\t\tgo (a,b) [] | a < b = Just a\n\t\tgo (a,b) (Lt x : xs) = go (a, min b x) xs\n\t\tgo (a,b) (Geq x : xs) = go (max a x, b) xs\n\t\tgo _ _ = Nothing\n\nmain :: IO ()\nmain = do\n\tn <- inputInt\n\ta <- replicateM n inputAnswer\n\tcase solve a of\n\t\tJust x -> print x\n\t\tNothing -> putStrLn \"Impossible\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nnormalize :: C.ByteString -> C.ByteString -> Int -> (Ordering, Int)\nnormalize \"Y\" \">\" x = (GT, x)\nnormalize \"Y\" \"<\" x = (LT, x)\nnormalize \"Y\" \">=\" x = (GT, x - 1)\nnormalize \"Y\" \"<=\" x = (LT, x + 1)\nnormalize \"N\" \">\" x = (LT, x + 1)\nnormalize \"N\" \"<\" x = (GT, x - 1)\nnormalize \"N\" \">=\" x = (LT, x)\nnormalize \"N\" \"<=\" x = (GT, x)\nnormalize _ _ _ = undefined\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n qna <- replicateM n $ do\n [sign, x, answer] <- C.words <$> C.getLine\n return $ normalize answer sign $ readInt x\n let gt = [j | (i, j) <- qna, i == GT]\n lt = [j | (i, j) <- qna, i == LT]\n gtmax = maximum gt\n ltmin = minimum lt\n if null gt then print $ ltmin - 1\n else if null lt || gtmax + 1 <= ltmin - 1 then print $ gtmax + 1\n else putStrLn \"Impossible\"\n"}, {"source_code": "main=interact$maybe \"Impossible\" show.solve.parse.tail.words\n\nsolve :: [Either Int Int] -> Maybe Int\nsolve xs = go (-2000000000) 2000000000 xs\n where\n go l r (Left i:xs) = go (max l i) r xs\n go l r (Right i:xs) = go l (min r i) xs\n go l r []\n | l <= r = Just l\n | otherwise = Nothing\n\nparse :: [String] -> [Either Int Int]\nparse (\">\":i:\"Y\":cs) = Left (read i+1) : parse cs\nparse (\">=\":i:\"Y\":cs) = Left (read i) : parse cs\nparse (\"<\":i:\"Y\":cs) = Right (read i-1) : parse cs\nparse (\"<=\":i:\"Y\":cs) = Right (read i) : parse cs\nparse (\">\":i:\"N\":cs) = parse (\"<=\":i:\"Y\":cs)\nparse (\">=\":i:\"N\":cs) = parse (\"<\":i:\"Y\":cs)\nparse (\"<\":i:\"N\":cs) = parse (\">=\":i:\"Y\":cs)\nparse (\"<=\":i:\"N\":cs) = parse (\">\":i:\"Y\":cs)\nparse _ = []"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nnormalize :: C.ByteString -> C.ByteString -> Int -> (Ordering, Int)\nnormalize \"Y\" \">\" x = (GT, x)\nnormalize \"Y\" \"<\" x = (LT, x)\nnormalize \"Y\" \">=\" x = (GT, x + 1)\nnormalize \"Y\" \"<=\" x = (LT, x - 1)\nnormalize \"N\" \">\" x = (LT, x + 1)\nnormalize \"N\" \"<\" x = (GT, x - 1)\nnormalize \"N\" \">=\" x = (LT, x)\nnormalize \"N\" \"<=\" x = (GT, x)\nnormalize _ _ _ = undefined\n\nmain :: IO ()\nmain = do\n n <- readInt <$> C.getLine\n qna <- replicateM n $ do\n [sign, x, answer] <- C.words <$> C.getLine\n return $ normalize answer sign $ readInt x\n let gt = [j | (i, j) <- qna, i == GT]\n lt = [j | (i, j) <- qna, i == LT]\n gtmax = maximum gt\n ltmin = minimum lt\n if null gt then print $ ltmin - 1\n else if null lt || gtmax + 1 <= ltmin - 1 then print $ gtmax + 1\n else putStrLn \"Impossible\"\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\ndata Compare = LE | GE\n\ndata Query = Q Compare Int\n\napply :: (Int,Int) -> Query -> Maybe (Int,Int)\napply (lo,hi) (Q LE val)\n | val < lo = Nothing\n | otherwise = Just (lo, min val hi)\napply (lo,hi) (Q GE val)\n | val > hi = Nothing\n | otherwise = Just (max lo val, hi)\n\ncomplement :: Query -> Query\ncomplement (Q LE v) = Q GE (v+1)\ncomplement (Q GE v) = Q LE (v-1)\n\nreadQuery :: String -> Query\nreadQuery str =\n let (op:vs:bs:_) = words str\n v = read vs\n q1 = if | op == \">=\" -> Q GE v\n | op == \"<=\" -> Q LE v\n | op == \">\" -> Q GE (v+1)\n | op == \"<\" -> Q LE (v-1)\n q2 = if bs == \"Y\" then q1 else complement q1\n in q2\n\nmain = do\n n <- fmap read getLine\n queries <- replicateM n $ do fmap readQuery getLine\n let inf = 10^9 :: Int\n let loop r [] = Just r\n loop r (q:qs) = case apply r q of\n Nothing -> Nothing\n Just r' -> loop r' qs\n r = loop (-inf,inf) queries\n case r of\n Nothing -> putStrLn \"Impossible\" \n Just (lo,hi) -> putStrLn $ show (min hi 2*10^9)\n\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\ndata Compare = LE | GE\n\ndata Query = Q Compare Int\n\napply :: (Int,Int) -> Query -> Maybe (Int,Int)\napply (lo,hi) (Q LE val)\n | val < lo = Nothing\n | otherwise = Just (lo, min val hi)\napply (lo,hi) (Q GE val)\n | val > hi = Nothing\n | otherwise = Just (max lo val, hi)\n\ncomplement :: Query -> Query\ncomplement (Q LE v) = Q GE (v+1)\ncomplement (Q GE v) = Q LE (v-1)\n\nreadQuery :: String -> Query\nreadQuery str =\n let (op:vs:bs:_) = words str\n v = read vs\n q1 = if | op == \">=\" -> Q GE v\n | op == \"<=\" -> Q LE v\n | op == \">\" -> Q GE (v+1)\n | op == \"<\" -> Q LE (v-1)\n q2 = if bs == \"Y\" then q1 else complement q1\n in q2\n\nmain = do\n n <- fmap read getLine\n queries <- replicateM n $ do fmap readQuery getLine\n let inf = 10^9 :: Int\n let loop r [] = Just r\n loop r (q:qs) = case apply r q of\n Nothing -> Nothing\n Just r' -> loop r' qs\n r = loop (-inf,inf) queries\n case r of\n Nothing -> putStrLn \"Impossible\" \n Just (lo,hi) -> putStrLn $ show (min hi (2*10^9))\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe (fromJust)\n\ndata InequalitySign = LARGERT | SMALLERT | LTE | STE\n deriving (Eq)\n\nreverseSign LARGERT = STE\nreverseSign SMALLERT = LTE\nreverseSign LTE = SMALLERT\nreverseSign STE = LARGERT\n\ntoInequality \">\" = LARGERT\ntoInequality \"<\" = SMALLERT\ntoInequality \">=\" = LTE\ntoInequality \"<=\" = STE\n\ntranslate [a,b,c] = if c == \"Y\" then (i, read b) else (reverseSign i, read b)\n where i = toInequality a\n\nmain = do\n n <- readLn\n xs <- replicateM n (translate . words <$> getLine)\n let\n f [] bound = Just bound\n f ((i,x):ys) (lb,ub)\n | i == LARGERT = if x-1 >= ub\n then Nothing\n else f ys (max (x-1) lb, ub)\n | i == SMALLERT = if x <= lb\n then Nothing\n else f ys (lb, min x ub)\n | i == LTE = if x >= ub\n then Nothing\n else f ys (max x lb, ub)\n | i == STE = if x < lb\n then Nothing\n else f ys (lb, min (x+1) ub)\n b = f xs (-1000000000, 1000000001)\n result = if b == Nothing then \"Impossible\" else show . fst $ fromJust b\n in putStrLn $ result\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe (fromJust)\n\ndata InequalitySign = LARGERT | SMALLERT | LTE | STE\n deriving (Eq)\n\nreverseSign LARGERT = STE\nreverseSign SMALLERT = LTE\nreverseSign LTE = SMALLERT\nreverseSign STE = LARGERT\n\ntoInequality \">\" = LARGERT\ntoInequality \"<\" = SMALLERT\ntoInequality \">=\" = LTE\ntoInequality \"<=\" = STE\n\ntranslate [a,b,c] = if c == \"Y\" then (i, read b) else (reverseSign i, read b)\n where i = toInequality a\n\nmain = do\n n <- readLn\n xs <- replicateM n (translate . words <$> getLine)\n let\n f [] bound = Just bound\n f ((i,x):ys) (lb,ub)\n | i == LARGERT = if x-1 >= ub\n then Nothing\n else f ys (max (x+1) lb, ub)\n | i == SMALLERT = if x <= lb\n then Nothing\n else f ys (lb, min x ub)\n | i == LTE = if x >= ub\n then Nothing\n else f ys (max x lb, ub)\n | i == STE = if x < lb\n then Nothing\n else f ys (lb, min (x+1) ub)\n b = f xs (-1000000000, 1000000001)\n result = if b == Nothing then \"Impossible\" else show . fst $ fromJust b\n in putStrLn $ result\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Maybe (fromJust)\n\ndata InequalitySign = LARGERT | SMALLERT | LTE | STE\n deriving (Eq)\n\nreverseSign LARGERT = STE\nreverseSign SMALLERT = LTE\nreverseSign LTE = SMALLERT\nreverseSign STE = LARGERT\n\ntoInequality \">\" = LARGERT\ntoInequality \"<\" = SMALLERT\ntoInequality \">=\" = LTE\ntoInequality \"<=\" = STE\n\ntranslate [a,b,c] = if c == \"Y\" then (i, read b) else (reverseSign i, read b)\n where i = toInequality a\n\nmain = do\n n <- readLn\n xs <- replicateM n (translate . words <$> getLine)\n let\n f [] bound = Just bound\n f ((i,x):ys) (lb,ub)\n | i == LARGERT = if x-1 >= ub\n then Nothing\n else f ys (max (x+1) lb, ub)\n | i == SMALLERT = if x <= lb\n then Nothing\n else f ys (lb, min x ub)\n | i == LTE = if x >= ub\n then Nothing\n else f ys (max x lb, ub)\n | i == STE = if x < lb\n then Nothing\n else f ys (lb, min (x+1) ub)\n b = f xs (-1000000010, 1000000010)\n result = if b == Nothing then \"Impossible\" else show . fst $ fromJust b\n in putStrLn $ result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\n\nsolve :: [String] -> Maybe Int\nsolve ss = if l > r then Nothing\n else Just l\n where (l, r) = hlp (-10^9, 10^9) ss\n hlp :: (Int, Int) -> [String] -> (Int, Int)\n hlp (a, b) [] = (a, b)\n hlp (a, b) (s:ts) =\n if ((sgn == \">=\") && (ans == \"Y\")) || ((sgn == \"<\") && (ans == \"N\")) then\n if n > a then hlp (n, b) ts\n else hlp (a, b) ts\n else if ((sgn == \"<=\") && (ans == \"Y\")) || ((sgn == \">\") && (ans == \"N\")) then\n if n < b then hlp (a, n) ts\n else hlp (a, b) ts\n else if ((sgn == \"<\") && (ans == \"Y\")) || ((sgn == \">=\") && (ans == \"N\")) then\n if n-1 < b then hlp (a, n-1) ts\n else hlp (a, b) ts\n else if ((sgn == \">\") && (ans == \"Y\")) || ((sgn == \"<=\") && (ans == \"N\")) then\n if n+1 > a then hlp (n+1, b) ts\n else hlp (a, b) ts\n else (a, b)\n where [sgn, n', ans] = words s\n n = read n'\n\nmain = do\n n <- fmap read getLine\n lst <- forM [1..n] (\\_ -> getLine)\n let solution = solve lst\n if isNothing solution then putStrLn \"Impossible\"\n else print (fromJust solution)\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\n\nsolve :: [String] -> Maybe Int\nsolve ss = if l > r then Nothing\n else Just l\n where (l, r) = hlp (-10^9, 10^9) ss\n hlp :: (Int, Int) -> [String] -> (Int, Int)\n hlp (a, b) [] = (a, b)\n hlp (a, b) (s:ts) =\n if ((sgn == \">=\") && (ans == \"Y\")) || ((sgn == \"<\") && (ans == \"N\")) then\n if n > a then hlp (n, b) ts\n else hlp (a, b) ts\n else if ((sgn == \"<=\") && (ans == \"Y\")) || ((sgn == \">\") && (ans == \"N\")) then\n if n < b then hlp (a, n) ts\n else hlp (a, b) ts\n else if ((sgn == \"<\") && (ans == \"Y\")) || ((sgn == \">=\") && (ans == \"N\")) then\n if n-1 < b then hlp (a, n-1) ts\n else hlp (a, b) ts\n else if ((sgn == \">\") && (ans == \"Y\")) || ((sgn == \"<=\") && (ans == \"N\")) then\n if n-1 > a then hlp (n-1, b) ts\n else hlp (a, b) ts\n else (a, b)\n where [sgn, n', ans] = words s\n n = read n'\n\nmain = do\n n <- fmap read getLine\n lst <- forM [1..n] (\\_ -> getLine)\n let solution = solve lst\n if isNothing solution then putStrLn \"Impossible\"\n else print (fromJust solution)\n"}, {"source_code": "import Data.Maybe\n\ndata Var = Gt \n\nprocess :: Integer -> Integer -> [[String]] -> Maybe Integer\nprocess a b _ | a > b = Nothing\nprocess a _ [] = Just a\nprocess a b ((sign:x:\"N\":[]):other_lines) = process a b ((oposite sign:x:\"Y\":[]):other_lines)\n\nprocess a b ((\">=\":x:\"Y\":[]):other_lines) = process (read x) b other_lines\nprocess a b ((\">\":x:\"Y\":[]):other_lines) = process (1 + read x) b other_lines\nprocess a b ((\"<\":x:\"Y\":[]):other_lines) = process a (-1 + read x) other_lines\nprocess a b ((\"<=\":x:\"Y\":[]):other_lines) = process a (read x) other_lines\n\noposite \">=\" = \"<\"\noposite \"<=\" = \">\"\noposite \"<\" = \">=\"\noposite \">\" = \"<=\"\n\nmain = do\n n <- read `fmap` getLine\n my_lines <- sequence $ replicate n getLine\n\n let\n res = process (-2000000000) 2000000000 (map words my_lines)\n\n putStrLn $ if res == Nothing then \"Impossible\" else show $ fromJust res\n"}, {"source_code": "import Data.Maybe\n\ndata Var = Gt \n\nprocess :: Int -> Int -> [[String]] -> Maybe Int\nprocess a b _ | a > b = Nothing\nprocess a _ [] = Just a\nprocess a b ((sign:x:\"N\":[]):other_lines) = process a b ((oposite sign:x:\"Y\":[]):other_lines)\n\nprocess a b ((\">=\":x:\"Y\":[]):other_lines) = process (read x) b other_lines\nprocess a b ((\">\":x:\"Y\":[]):other_lines) = process (1 + read x) b other_lines\nprocess a b ((\"<\":x:\"Y\":[]):other_lines) = process a (-1 + read x) other_lines\nprocess a b ((\"<=\":x:\"Y\":[]):other_lines) = process a (read x) other_lines\n\noposite \">=\" = \"<\"\noposite \"<=\" = \">\"\noposite \"<\" = \">=\"\noposite \">\" = \"<=\"\n\nmain = do\n n <- read `fmap` getLine\n my_lines <- sequence $ replicate n getLine\n\n let\n res = process (-2000000000) 2000000000 (map words my_lines)\n\n putStrLn $ if res == Nothing then \"Impossible\" else show $ fromJust res\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, BangPatterns, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\ndata Answer = Lt !Int | Geq !Int\n\nneg :: Answer -> Answer\nneg (Lt a) = Geq a\nneg (Geq a) = Lt a\n\ninputAnswer :: IO Answer\ninputAnswer = do\n\t[sign, ns, ts] <- words <$> getLine\n\tlet n :: Int = read ns\n\tlet t = ts == \"Y\"\n\tlet ans = case sign of\n\t\t\">=\" -> Geq n\n\t\t\"<\" -> Lt n\n\t\t\">\" -> Geq (n + 1)\n\t\t\"<=\" -> Lt (n + 1)\n\treturn $ if t then ans else neg ans\n\n\nsolve :: [Answer] -> Maybe Int\nsolve = go (-10^9, 10^9)\n\twhere\n\t\tgo (a,b) [] | a < b = Just a\n\t\tgo (a,b) (Lt x : xs) = go (a, min b x) xs\n\t\tgo (a,b) (Geq x : xs) = go (max a x, b) xs\n\t\tgo _ _ = Nothing\n\nmain :: IO ()\nmain = do\n\tn <- inputInt\n\ta <- replicateM n inputAnswer\n\tcase solve a of\n\t\tJust x -> print x\n\t\tNothing -> putStrLn \"Impossible\"\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, BangPatterns, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\ndata Answer = Lt !Int | Geq !Int\n\nneg :: Answer -> Answer\nneg (Lt a) = Geq a\nneg (Geq a) = Lt a\n\ninputAnswer :: IO Answer\ninputAnswer = do\n\t[sign, ns, ts] <- words <$> getLine\n\tlet n :: Int = read ns\n\tlet t = ts == \"Y\"\n\tlet ans = case sign of\n\t\t\">=\" -> Geq n\n\t\t\"<\" -> Lt n\n\t\t\">\" -> Geq (n + 1)\n\t\t\"<=\" -> Lt (n - 1)\n\treturn $ if t then ans else neg ans\n\n\nsolve :: [Answer] -> Maybe Int\nsolve = go (-10^9, 10^9)\n\twhere\n\t\tgo (a,b) [] | a < b = Just a\n\t\tgo (a,b) (Lt x : xs) = go (a, min b x) xs\n\t\tgo (a,b) (Geq x : xs) = go (max a x, b) xs\n\t\tgo _ _ = Nothing\n\nmain :: IO ()\nmain = do\n\tn <- inputInt\n\ta <- replicateM n inputAnswer\n\tcase solve a of\n\t\tJust x -> print x\n\t\tNothing -> putStrLn \"Impossible\"\n"}], "src_uid": "6c6f29e1f4c951cd0ff15056774f897d"} {"source_code": "import Data.List\nmain=interact$show.length.nub.filter(\\c->'a'<=c&&c<='z')", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport qualified Data.Set as Set\nimport qualified Data.Text as T\n\nmain :: IO ()\nmain = do\n input <- getLine\n let input2 = T.pack . drop 1 . take (length input - 1) $ input\n splitted = map T.strip . T.splitOn \",\" $ input2\n l = Set.fromList . filter (not . T.null) $ splitted\n putStrLn . show $ Set.size l\n pure ()"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Functor\nimport Data.IORef\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Traversable\nimport Text.Printf (printf)\n\nimport qualified Data.Set as S\nimport Data.Char\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Integral b) => a -> b\ncast = fromIntegral\n\n-----\n\nmain :: IO ()\nmain = do\n s <- getLine\n print $ length $ S.toList $ S.fromList $ words $ map (\\c -> if isAlpha c then c else ' ') s\n"}, {"source_code": "\nimport Data.List (nub)\n\nmain :: IO()\nmain = getLine >>= print . length . nub . filter (not . flip elem \"{}, \")"}, {"source_code": "import Data.Char\nimport Data.List\nmain=interact$show.length.nub.filter(isLetter)"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport qualified Data.List as List\nimport qualified Data.Set as Set\nimport qualified Data.Char as Char\n\n\nlstrip :: String -> String\nlstrip = dropWhile Char.isSpace\nrstrip = reverse . lstrip . reverse\nstrip = lstrip . rstrip\n\nsplitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen p l = splitWhenAux l []\n where\n splitWhenAux [] [] = []\n splitWhenAux [] b@(_:_) = [b]\n splitWhenAux (h:t) b | (p h) = (reverse b) : (splitWhenAux t [])\n | otherwise = splitWhenAux t (h:b)\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn n l = splitWhen (n ==) l\n\nparse :: String -> [String]\nparse s = map strip $ splitOn ',' $ (init . tail) s\n\nsolve :: String -> Int\nsolve = length . List.nub . parse\n\nmain :: IO ()\nmain = do\n s <- getLine\n putStrLn $ (show . solve) s\n"}, {"source_code": "import Data.List (nub)\nimport Data.Char (isAlpha)\n\nmain = interact $ show . length . nub . filter isAlpha"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nsolve :: String -> Int\nsolve = length . nub . filter (`notElem` \"{, }\")\n\nmain :: IO ()\nmain = do\n s <- getLine\n print $ solve s\n"}, {"source_code": "import Control.Applicative\nimport Data.Char (isAlpha)\nimport Data.List (group, sort)\n\nmain = do\n s <- getLine\n putStrLn . show $ length . group . sort $ filter isAlpha s"}, {"source_code": "import Data.List\nimport Data.Char\n\nmain = interact entry\n where entry input = show cnt\n where cnt = (length . nub) (filter isAlpha input)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\n\n\nmain=do\n a<-show <$> length <$> group <$> sort <$> filter (isLower) <$> init <$> tail <$> getLine\n putStrLn a\n"}, {"source_code": "import Data.Char (isAlpha)\nimport Data.List (group, sort)\n\nmain :: IO ()\nmain = getLine >>= print . solve . filter isAlpha\n\nsolve :: String -> Int\nsolve = length . group . sort\n"}, {"source_code": "import Data.Char\nimport Data.List\nmain = print . length . nub . filter isLetter =<< getContents\n"}, {"source_code": "import qualified Data.Set as Set\n\nmain :: IO()\nmain = do\n xs <- getLine\n print $ Set.size $ foldl (\\acc el -> Set.insert el acc) Set.empty $ trim $ xs\n where \n trim [] = []\n trim (x:xs) \n | x >= 'a' && x <= 'z' = x : trim xs\n | otherwise = trim xs"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/443/A\n\nimport Data.List\n\nsolve :: String -> Int\nsolve = length . nub . filter (`notElem` \"{, }\")\n\nmain :: IO ()\nmain = do\n s <- getLine\n print $ solve s\n"}, {"source_code": "import Data.List\n\nprocess :: String -> Int\nprocess [] = 0\nprocess xs = length $ nub $ filter (\\x -> x >= 'a' && x <= 'z') xs\n\nmain = do\n\tstr <- getLine\n\tputStrLn $ show $ process str\n"}, {"source_code": "import Data.List\nmain=interact$show.length.nub.filter(\\c->'a'<=c&&c<='z')"}, {"source_code": "import Data.Char\nimport Data.List\nmain :: IO ()\nmain = fmap (length . nub . filter isAlpha) getLine >>= print\n"}, {"source_code": "import Data.List\n\nmain = getLine >>= print.length.(flip (\\\\) \"{, }\").nub"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.Set as S\n\nrepl '{' = ' '\nrepl '}' = ' '\nrepl ',' = ' '\nrepl x = x\n\nmain= do\n\ta<- getLine \n\tprint $ length $ S.toList $ S.fromList $ words $ map repl a\n\t "}, {"source_code": "import Data.Char\nimport Data.Set as S (fromList)\nmain :: IO ()\nmain = print =<< length . S.fromList . filter isAlpha <$> getLine"}, {"source_code": "getUnique :: [String] -> [Char] -> Int\ngetUnique [] _ = 0\ngetUnique (x:xs) letList\n | not $ curLet `elem` letList = 1 + getUnique xs (curLet:letList)\n | otherwise = getUnique xs letList\n where curLet = head x\n\nmain = do\n ln <- getLine\n let lets = words $ tail (init ln)\n putStrLn . show $ getUnique lets []\n"}, {"source_code": "import Data.Char (isLetter)\nimport Data.List (nub)\n\nmain = interact $ show . length . nub . filter isLetter\n"}, {"source_code": "import Data.List\n\nmain = getLine >>= print . length . nub . solve\n\nsolve \"}\" = \"\"\nsolve ('{':ls) = solve ls\nsolve (',':ls) = solve ls\nsolve (' ':ls) = solve ls\nsolve (l:ls) = l:(solve ls)\n"}, {"source_code": "import qualified Data.Text as T\nimport Data.List\n\nprocess :: [String] -> Int\nprocess = length.nub\n\nparse :: String -> [String]\nparse \"{}\" = []\nparse xs = map T.unpack $ T.splitOn (T.pack \", \") (T.pack.tail.init$xs)\n\nmain = do\n xs <- getLine\n print $ process $ parse xs"}, {"source_code": "import Data.List\nmain = do interact $ show . length . nub . del\n where del [] = []\n del (x:xs)\n | 'a' <= x && x <= 'z' = x : del xs\n | otherwise = del xs"}, {"source_code": "import Data.List.Split\nimport Data.List\n\nsolve :: String -> String\nsolve = show . length . nub . \n split ((dropBlanks. dropDelims .oneOf) \"}{, \\n\")\n\nmain :: IO ()\nmain= interact $ solve"}, {"source_code": "import Data.List\nimport Data.Char\n\nsolve :: String -> String\nsolve = show . length . nub . filter isLetter\n\nmain :: IO ()\nmain= interact $ solve"}, {"source_code": "module Main where\n\nimport Data.Set (toList, fromList)\n\nuniquify = toList . fromList\n\nmain = do\n\ts <- getLine\n\tputStr $ show $ uniqueNumber s\n\nuniqueNumber :: String -> Int\nuniqueNumber = length . uniquify . words . cleanString where\n\tcleanString = filter (not . (`elem` \",{}\")) \n"}, {"source_code": "import Data.List\nf str = filter (\\x->not (elem x \"{, }\\n\")) str\nmain = interact $ show . length . nub . f\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\n\nparse :: Char -> Char\nparse c\n | c == '{' = ' '\n | c == '}' = ' '\n | c == ',' = ' '\n | otherwise = c\n\nsolve :: String -> Int\nsolve s =\n let input = (words . map parse) s\n noDuplicates = Set.fromList input\n ans = Set.toList noDuplicates\n in length ans\n\nmain = do\n input <- getLine\n print $ solve input\n"}, {"source_code": "module Main where\n\nimport Data.List (nub)\n\nmain :: IO ()\nmain = do\n\tln <- getLine\n\tprint $ process ln\n\nprocess :: String -> Int\nprocess = length . nub . readLetters\n\nreadLetters :: String -> [Char]\nreadLetters (' ' : cs) = readLetters cs\nreadLetters ('{' : cs) = items cs\nitems [] = []\nitems ('}' : cs) = []\nitems (' ' : cs) = items cs\nitems (',' : cs) = items cs\nitems (c : cs) = c : items cs\n\n\n\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List (nub)\n\n\ngenAns [] = 0\ngenAns [x] = 1\ngenAns xs = max 0 $ (length $ nub xs) - 2\n\nmain = do\n aa <- getLine\n let ls = tail $ take (length aa - 1) aa\n print $ genAns ls\n"}, {"source_code": "import Data.Char\nimport Data.List\nf s = show $ length $ nub $ filter isLetter s\nmain = interact f"}, {"source_code": "import Data.List\nmain = do\n s <- getLine\n putStrLn $ show $ length $ func s\n\nfunc :: String -> String\nfunc s = nub [x | x <- s, x `elem` ['a'..'z']]\n"}, {"source_code": "check [] y = length y\ncheck (x:xs) y\n | not (x `elem` y) = check xs (x:y)\n | otherwise = check xs y\n\ntrim = f . f . filter (/=',') where f = reverse . drop 1\n\nmain = getLine >>= return . (flip check) [] . words . trim >>= putStrLn . show\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = interact $ show . length . nub . filter (\\c -> 'a' <= c && c <= 'z')\n"}, {"source_code": "s l = [x|x<-l,'a'<=x,x<='z']\n\nd l ch k \n |ch == 'z' =(k+t)\n |otherwise = d l (succ ch) (k+t)\n where t = if null [0|x<-l,x==ch] then 0 else 1\n\nn x = d (s x) 'a' 0\n\nmain = do\n s <- getLine \n print (n s)"}, {"source_code": "import Data.List\nsolve s = length $ nub $ concat $ map words$ splitOn ',' $ init $ tail $ s\n\nsplitOn::Char->String->[String]\nsplitOn f [] = []\nsplitOn f ss = [takeWhile (/=f) ss] ++ splitOn f (stail (dropWhile (/=f) ss))\n\nstail [] = []\nstail (s:[]) = []\nstail s = tail s\n\nmain = do \n s<-getLine\n putStrLn $show$solve s"}, {"source_code": "import Data.Set as Set\nimport Data.Char\n\nmain = interact $ show.f\nf x = size (Set.fromList (Prelude.filter isLetter x))\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . length . nub . filter (isAlpha)\n"}, {"source_code": "import Data.List\nimport Data.List.Split\n\nmain = do\n s <- getLine\n let xs = splitOn \", \" $ tail $ init s\n\n print $ length $ group $ filter (not . null) $ sort xs\n"}, {"source_code": "import Data.List as L\nimport Data.Char as C\nmain = interact $ show . length . L.nub . filter C.isLower \n"}, {"source_code": "import Data.List\n\nmain = do\n a <- getLine\n let b = length $ nub $ filter (\\c -> c >= 'a' && c <= 'z') a\n putStrLn $ show b\n\n"}, {"source_code": "import Data.List (nub)\nimport Data.Char (isAlpha)\nmain = \n\tinteract $ show. length. nub. filter isAlpha \n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve. words. (\\a->if a==\"\" then a else a++\",\").init.tail.head . lines\nsolve :: [String]->Int\nsolve xss = length $ slv1 xss\nslv1 []=[]\nslv1 (xs:xss) = xs:slv1 [ys|ys<-xss,ys/=xs]"}, {"source_code": "import Data.Char\n\nh :: String -> [Char] -> Int\nh \"}\" a = count a\nh ('{':s) a = h s a \nh (',':xs) s = h xs s\nh (' ':xs) s = h xs s \nh (x:xs) s = h xs (s++[x]) \n\ncount :: [Char] -> Int\n\ncount a = length b\n where b = rmdups a\n\nrmdups [] = []\nrmdups (x:xs)\n | x `elem` xs = rmdups xs\n | x == '\"' = rmdups xs\n | otherwise = x : rmdups xs\n\nmain = do\n line <- getLine\n print (h line [])\n\nhi :: String -> [Char] -> [Char]\nhi \"}\" a = a\nhi ('{':s) a = hi s a \nhi (',':xs) s = hi xs s\nhi (' ':xs) s = hi xs s \nhi (x:xs) s = hi xs (s++[x]) \n"}, {"source_code": "import qualified Data.Set as S\nimport Control.Applicative\n\nsolve :: String -> Int\nsolve s = S.size.S.fromList $ filter (not.(`elem` \"{, }\")) s\n\nmain = do\n l <- getLine\n putStrLn . show $ solve l\n"}], "negative_code": [{"source_code": "import Data.List\nsolve s = length $ nub $ splitOn ',' $ init $ tail $ s\n\nsplitOn::Char->String->[String]\nsplitOn f [] = []\nsplitOn f ss = [takeWhile (/=f) ss] ++ splitOn f (stail (dropWhile (/=f) ss))\n\nstail [] = []\nstail (s:[]) = []\nstail s = tail s\n\nmain = do \n s<-getLine\n putStrLn $show$solve s"}, {"source_code": "import Data.Set as Set\n\nmain = interact $ show.f.tail.init\nf x\n | (length x) > 1 = (size (Set.fromList x)) - 3\n | otherwise = (length x) - 1\n"}, {"source_code": "import Data.Set as Set\n\nmain = interact $ show.f.tail.init\nf x\n | (length x) > 1 = (size (Set.fromList x)) - 3\n | otherwise = length x\n"}, {"source_code": "import Data.Set as Set\n\nmain = interact $ show.f.tail.init\nf x\n | (length x) > 1 = (size (Set.fromList x)) - 2\n | otherwise = length x\n"}, {"source_code": "import Data.Set as Set\n\nmain = interact $ show.f.tail.init\nf x\n | (length x) > 1 = (size (Set.fromList x)) - 1\n | otherwise = length x\n"}, {"source_code": "import Data.List\nimport Data.List.Split\n\nmain = do\n s <- getLine\n let xs = splitOn \", \" $ tail $ init s\n print $ length $ group $ sort xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport qualified Data.List as List\nimport qualified Data.Set as Set\n\nsplitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen p l = splitWhenAux l []\n where\n splitWhenAux [] [] = []\n splitWhenAux [] b@(_:_) = [b]\n splitWhenAux (h:t) b | (p h) = (reverse b) : (splitWhenAux t [])\n | otherwise = splitWhenAux t (h:b)\n\nsplitOn :: Eq a => a -> [a] -> [[a]]\nsplitOn n l = splitWhen (n ==) l\n\nparse :: String -> [String]\nparse s = splitOn ',' $ (init . tail) s\n\nsolve :: String -> Int\nsolve = length . List.nub . parse\n\nmain :: IO ()\nmain = do\n s <- getLine\n putStrLn $ (show . solve) s\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.List.Split\n\n\n\n\n\nmain=do\n a<-show <$> length <$> filter (/=[\"\"]) <$> group <$> sort <$> splitOn \",\" <$> init <$> tail <$> getLine\n putStrLn a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.List.Split\n\ncheck n | le >1 = snd $ head $ filter (\\z-> odd (fst z)) $ zip n [1..]\n | otherwise = snd $ head $ filter (\\z-> even (fst z)) $ zip n [1..]\n where le = length $ filter even n\n\n\nmain=do\n a<-show <$> length <$> splitOn \",\" <$> init <$> tail <$> getLine\n putStrLn a\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.List.Split\n\n\n\n\n\nmain=do\n a<-show <$> length <$> group <$> sort <$> splitOn \",\" <$> init <$> tail <$> getLine\n putStrLn a\n"}, {"source_code": "import Data.List\n\nmain = getLine >>= print.(max 0).(flip (-) 4).length.nub"}, {"source_code": "import Data.List\n\nmain = getLine >>= print.(flip (-) 4).length.nub"}, {"source_code": "import Data.List\n\nmain = getLine >>= print . length . nub . solve\n\nsolve \"}\" = \"\"\nsolve ('{':ls) = solve ls\nsolve ('.':ls) = solve ls\nsolve (' ':ls) = solve ls\nsolve (l:ls) = l:(solve ls)\n"}, {"source_code": "f str = filter (\\x->not (elem x \"{, }\\n\")) str\ng str = filter (\\x-> length(filter (==x) str) ==1 ) str\nmain = interact $ g . f\n"}, {"source_code": "f str = filter (\\x->not (elem x \"{, }\\n\")) str\ng str = filter (\\x-> length(filter (==x) str) ==1 ) str\nmain = interact $ show . length . g . f\n"}], "src_uid": "1cbbffd1941ed83b5f04e1ee33c77f61"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.Map.Strict as Map\nimport Data.Map (Map)\nimport qualified Data.Array as Ar\nimport Data.Array (Array)\nimport qualified Data.List as L\nimport qualified Data.Maybe as Mb\nimport Data.Function\nimport Data.Int\n\n\ntransform :: [Int16] -> [Int16]\ntransform lst = map (m Map.!) lst\n where\n unique = map head $ L.group $ L.sort lst\n m = Map.fromAscList $ zip unique [0..]\n\n\ntype PrefixSums = Array Int16 (Array Int32 Int32)\n\nmakePrefixSum :: (Num a) => [a] -> [a]\nmakePrefixSum lst = 0 : go 0 lst\n where\n go aux [] = []\n go aux (e:es) = aux+e : go (aux+e) es\n\nmakePrefixSums :: [Int16] -> PrefixSums\nmakePrefixSums lst = Ar.listArray (0,mx) $ map prefixSumMapper [0..mx]\n where\n n = fromIntegral $ length lst\n mx = fromIntegral $ maximum lst\n prefixSumMapper i = Ar.listArray (0, n) $ makePrefixSum $ map mapperF lst\n where\n mapperF j = if j == i then 1 else 0\n\nfrequency :: PrefixSums -> Int16 -> (Int32, Int32) -> Int32\nfrequency vecVec i (start, end) = endSum - startSum\n where\n vec = vecVec Ar.! i\n endSum = vec Ar.! (end+1)\n startSum = vec Ar.! start\n\nmakeIndexList :: [Int16] -> [[Int32]]\nmakeIndexList lst = map (map snd) $ L.groupBy ((==) `on` fst) $ L.sort $ zip lst [0..]\n\nmaxValue :: Int16 -> (Int16 -> (Int32, Int32) -> Int32) -> [(Int32, Int32)] -> Int32\nmaxValue _ _ [] = 0\nmaxValue mx frequencyGetter indexes = maximum [2*c + frequencyGetter i (start+1,end-1) | (c, (start,end)) <- zip [1..] indexes, i <- [0..mx]]\n\nsolve :: [Int16] -> Int32\nsolve rawLst = maximum $ defaultAns : map (maxValueGetter . makeStartEndPairs) indexList\n where\n !lst = transform rawLst\n mx = maximum lst\n !defaultAns = fromIntegral $ maximum $ map length $ L.group $ L.sort lst\n !indexList = makeIndexList lst\n makeStartEndPairs indexes = take (length indexes `div` 2) $ zip indexes (reverse indexes)\n !frequencyGetter = frequency (makePrefixSums lst)\n !maxValueGetter = maxValue mx frequencyGetter\n\n\n\n\n\n{-\ngetCounts :: [Int] -> Map Int Int\ngetCounts lst = Map.fromList $ map mapper grouping\n where\n grouping = L.group . L.sort $ lst\n mapper as = (head as, length as)\n\ndec :: Int -> Map Int Int -> Map Int Int -> (Map Int Int, Map Int Int)\ndec n remaining remainingInv = (newRemaining, newRemainingInv2)\n where\n count = remaining Map.! n\n newRemaining = Map.adjust pred n remaining\n newRemainingInv1 = Map.adjust pred count remainingInv\n newRemainingInv2 = Map.alter (Just . succ . Mb.fromMaybe 0) (count-1) newRemainingInv1\n\ncreateInvPair :: Map Int Int -> (Map Int Int, Map Int Int)\ncreateInvPair remaining = (remaining, inv)\n where\n values = Map.elems remaining\n inv = getCounts values\n\nsolve :: [Int] -> Int\nsolve lst = maximum $ map mapper lst\n where\n arr = Ar.listArray (0, length lst - 1) lst\n counts = Map.insert 0 0 $ getCounts lst\n helper :: Int -> Int -> Int -> Int -> (Map Int Int, Map Int Int) -> Int\n helper n nCount start end (remaining, remainingInv)\n | start >= end = counts Map.! n\n | sVal == n && eVal == n\n = max (nCount + 2 + maximum (Map.elems remaining)) (helper n (nCount+2) (start+1) (end-1) (remaining, remainingInv))\n | eVal /= n\n = helper n nCount start (end-1) (dec eVal remaining remainingInv)\n | otherwise\n = helper n nCount (start+1) end (dec sVal remaining remainingInv)\n where\n sVal = arr Ar.! start\n eVal = arr Ar.! end\n mapper n = helper n 0 0 (length lst - 1) (createInvPair $ Map.delete n counts)\n-}\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- readInts\n lst <- readInts16\n print $ solve lst\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nreadInts32 :: IO [Int32]\nreadInts32 = map read . words <$> getLine\n\nreadInts16 :: IO [Int16]\nreadInts16 = map read . words <$> getLine", "positive_code": [{"source_code": "\nimport qualified Data.Map.Strict as Map\nimport Data.Map (Map)\nimport qualified Data.Array as Ar\nimport Data.Array (Array)\nimport qualified Data.List as L\nimport qualified Data.Maybe as Mb\nimport Data.Function\n\n\ntransform :: [Int] -> [Int]\ntransform lst = map (m Map.!) lst\n where\n unique = map head $ L.group $ L.sort lst\n m = Map.fromAscList $ zip unique [0..]\n\ntype Vector = Array Int\n\ntype PrefixSums = Vector (Vector Int)\n\nmakePrefixSum :: [Int] -> [Int]\nmakePrefixSum lst = 0 : go 0 lst\n where\n go aux [] = []\n go aux (e:es) = aux+e : go (aux+e) es\n\nmakePrefixSums :: [Int] -> PrefixSums\nmakePrefixSums lst = Ar.listArray (0,mx) $ map prefixSumMapper [0..mx]\n where\n n = length lst\n mx = maximum lst\n prefixSumMapper i = Ar.listArray (0, n) $ makePrefixSum $ map mapperF lst\n where\n mapperF j = if j == i then 1 else 0\n\nfrequency :: PrefixSums -> Int -> (Int, Int) -> Int\nfrequency vecVec i (start, end) = endSum - startSum\n where\n vec = vecVec Ar.! i\n endSum = vec Ar.! (end+1)\n startSum = vec Ar.! start\n\nmakeIndexList :: [Int] -> [[Int]]\nmakeIndexList lst = map (map snd) $ L.groupBy ((==) `on` fst) $ L.sort $ zip lst [0..]\n\nmaxValue :: Int -> (Int -> (Int, Int) -> Int) -> [(Int, Int)] -> Int\nmaxValue _ _ [] = 0\nmaxValue mx frequencyGetter indexes = maximum [2*c + frequencyGetter i (start+1,end-1) | (c, (start,end)) <- zip [1..] indexes, i <- [0..mx]]\n\nsolve :: [Int] -> Int\nsolve rawLst = maximum $ defaultAns : map (maxValueGetter . makeStartEndPairs) indexList\n where\n lst = transform rawLst\n mx = maximum lst\n defaultAns = maximum $ map length $ L.group $ L.sort lst\n indexList = makeIndexList lst\n makeStartEndPairs indexes = take (length indexes `div` 2) $ zip indexes (reverse indexes)\n frequencyGetter = frequency (makePrefixSums lst)\n maxValueGetter = maxValue mx frequencyGetter\n\n\n\n\n\n{-\ngetCounts :: [Int] -> Map Int Int\ngetCounts lst = Map.fromList $ map mapper grouping\n where\n grouping = L.group . L.sort $ lst\n mapper as = (head as, length as)\n\ndec :: Int -> Map Int Int -> Map Int Int -> (Map Int Int, Map Int Int)\ndec n remaining remainingInv = (newRemaining, newRemainingInv2)\n where\n count = remaining Map.! n\n newRemaining = Map.adjust pred n remaining\n newRemainingInv1 = Map.adjust pred count remainingInv\n newRemainingInv2 = Map.alter (Just . succ . Mb.fromMaybe 0) (count-1) newRemainingInv1\n\ncreateInvPair :: Map Int Int -> (Map Int Int, Map Int Int)\ncreateInvPair remaining = (remaining, inv)\n where\n values = Map.elems remaining\n inv = getCounts values\n\nsolve :: [Int] -> Int\nsolve lst = maximum $ map mapper lst\n where\n arr = Ar.listArray (0, length lst - 1) lst\n counts = Map.insert 0 0 $ getCounts lst\n helper :: Int -> Int -> Int -> Int -> (Map Int Int, Map Int Int) -> Int\n helper n nCount start end (remaining, remainingInv)\n | start >= end = counts Map.! n\n | sVal == n && eVal == n\n = max (nCount + 2 + maximum (Map.elems remaining)) (helper n (nCount+2) (start+1) (end-1) (remaining, remainingInv))\n | eVal /= n\n = helper n nCount start (end-1) (dec eVal remaining remainingInv)\n | otherwise\n = helper n nCount (start+1) end (dec sVal remaining remainingInv)\n where\n sVal = arr Ar.! start\n eVal = arr Ar.! end\n mapper n = helper n 0 0 (length lst - 1) (createInvPair $ Map.delete n counts)\n-}\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- readInts\n lst <- readInts\n print $ solve lst\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve xs = if length ids == 1 then length xs else res where\n\tsorted = sort xs\n\tids = go sorted where\n\t\tgo (x:xs) = x : go (dropWhile (==x) xs)\n\t\tgo [] = []\n\t\n\tres = maximum [ solveTwo a b (filter (\\k -> k == a || k == b) xs)| a <- ids, b <- ids, a /= b]\n\t\n\tsolveTwo a b xs = maximum $ go a b xs (reverse xs) 0 (length $ filter (== b) xs) where\n\t\ttotal_a_count = length $ filter (==a) xs\n\t\tgo a b xs rxs acount bcount = let\n\t\t\t\t(b1, xs') = strip xs 0\n\t\t\t\t(b2, rxs') = strip rxs 0\n\t\t\t\tacount' = acount + 2\n\t\t\t\tbcount' = bcount - b1 - b2\n\t\t\tin\n\t\t\t\tif acount > total_a_count then [total_a_count] else (acount + bcount) : go a b xs' rxs' acount' bcount'\n\t\t\n\t\t\twhere\n\t\t\t\tstrip (x:xs) acc\n\t\t\t\t\t| x == a = (acc, xs)\n\t\t\t\t\t| x == b = strip xs (acc + 1)\n\t\n\t\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\tn <- fmap read getLine :: IO Int\n\t\txs <- fmap (map read.words) getLine :: IO [Int]\n\t\tprint (solve xs)"}, {"source_code": "\nimport qualified Data.Map.Strict as Map\nimport Data.Map (Map)\nimport qualified Data.Array as Ar\nimport Data.Array (Array)\nimport qualified Data.List as L\n\ngetCounts :: [Int] -> Map Int Int\ngetCounts lst = Map.fromList $ map mapper grouping\n where\n grouping = L.group . L.sort $ lst\n mapper as = (head as, length as)\n\nsolve :: [Int] -> Int\nsolve lst = maximum $ map mapper lst\n where\n arr = Ar.listArray (0, length lst - 1) lst\n counts = Map.insert 0 0 $ getCounts lst\n helper :: Int -> Int -> Int -> Int -> Map Int Int -> Int\n helper n nCount start end remaining\n | start >= end = counts Map.! n\n | sVal == n && eVal == n\n = max (nCount + 2 + maximum (Map.elems remaining)) (helper n (nCount+2) (start+1) (end-1) remaining)\n | eVal /= n\n = helper n nCount start (end-1) (Map.adjust pred eVal remaining)\n | otherwise\n = helper n nCount (start+1) end (Map.adjust pred sVal remaining)\n where\n sVal = arr Ar.! start\n eVal = arr Ar.! end\n mapper n = helper n 0 0 (length lst - 1) (Map.delete n counts)\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- readInts\n lst <- readInts\n print $ solve lst\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}], "negative_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve xs = if length ids == 1 then length xs else res where\n\tsorted = sort xs\n\tids = go sorted where\n\t\tgo (x:xs) = x : go (dropWhile (==x) xs)\n\t\tgo [] = []\n\t\n\tres = maximum [ solveTwo a b (filter (\\k -> k == a || k == b) xs)| a <- ids, b <- dropWhile (<= a) ids]\n\t\n\tsolveTwo a b xs = maximum $ go a b xs (reverse xs) 0 (length $ filter (== b) xs) where\n\t\ttotal_a_count = length $ filter (==a) xs\n\t\tgo a b xs rxs acount bcount = let\n\t\t\t\t(b1, xs') = strip xs 0\n\t\t\t\t(b2, rxs') = strip rxs 0\n\t\t\t\tacount' = acount + 2\n\t\t\t\tbcount' = bcount - b1 - b2\n\t\t\tin\n\t\t\t\tif acount > total_a_count then [total_a_count] else (acount + bcount) : go a b xs' rxs' acount' bcount'\n\t\t\n\t\t\twhere\n\t\t\t\tstrip (x:xs) acc\n\t\t\t\t\t| x == a = (acc, xs)\n\t\t\t\t\t| x == b = strip xs (acc + 1)\n\t\n\t\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\tn <- fmap read getLine :: IO Int\n\t\txs <- fmap (map read.words) getLine :: IO [Int]\n\t\tprint (solve xs)"}], "src_uid": "2c1ee398ea86209335c2248eaa723aca"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (groupBy, intercalate, partition, sort)\n\nreadNamesTR 0 acc = return acc\nreadNamesTR n acc = do\n s <- getLine\n readNamesTR (n - 1) (s : acc)\n\ncount (names, surnames) = preparedfullnames \n where\n preparedfullnames = (prepare names, prepare surnames)\n prepare = (map tag) . (groupBy sameInit) . sort\n tag x = (length x, (head . head) x, x)\n sameInit name1 name2 = head name1 == head name2\n\nthrd (_, _, x) = x\n\npush [] acc = acc\npush (x : xs) acc = push xs (x : acc)\n\nalignTR acc namestack surnamestack _ ([], ss) = zip namestack (push (concatMap thrd ss) surnamestack) ++ acc\nalignTR acc namestack surnamestack diff (ns, []) = zip (push (concatMap thrd ns) namestack) surnamestack ++ acc\nalignTR acc namestack surnamestack diff (ns@((countn, cn, ln) : ns'), ss@((counts, cs, ls) : ss'))\n | cn < cs = alignTR acc (push ln namestack) surnamestack (diff + countn) (ns', ss)\n | cs < cn = alignTR acc namestack (push ls surnamestack) (diff - counts) (ns, ss')\n | countn == counts = alignTR (zip ln ls ++ acc) namestack surnamestack diff (ns', ss')\n\n | countn > counts && diff == 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (zip ln' ls ++ acc) (push ln'' namestack) surnamestack (countn - counts) (ns', ss')\n\n | countn > counts && diff > 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (zip ln' ls ++ acc) namestack surnamestack diff ((countn - counts, cn, ln'') : ns', ss')\n\n | countn > counts && diff < 0 = let draw = min (abs diff) (countn - counts) in let (ln', ln'') = splitAt draw ln in\n alignTR acc (push ln' namestack) surnamestack (diff + draw) ((countn - draw, cn, ln'') : ns', ss)\n\n | countn < counts && diff == 0 = let (ls', ls'') = splitAt countn ls in\n alignTR (zip ln ls' ++ acc) namestack (push ls'' surnamestack) (countn - counts) (ns', ss')\n\n | countn < counts && diff > 0 = let draw = min diff (counts - countn) in let (ls', ls'') = splitAt draw ls in\n alignTR acc namestack (push ls' surnamestack) (diff - draw) (ns, (counts - draw, cs, ls'') : ss')\n\n | countn < counts && diff < 0 = let (ls', ls'') = splitAt countn ls in \n alignTR (zip ln ls' ++ acc) namestack surnamestack diff (ns', (counts - countn, cs, ls'') : ss')\n\noutput cs = intercalate \", \" $ map (\\(x, y) -> x ++ \" \" ++ y) cs\n\nsolve = output . sort . (alignTR [] [] [] 0) . count\n\nmain = do \n nS <- getLine\n let n = read nS\n names <- readNamesTR n []\n surnames <- readNamesTR n []\n putStrLn (solve (names, surnames))\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (groupBy, intercalate, partition, sort)\n\nreadNamesTR 0 acc = return acc\nreadNamesTR n acc = do\n s <- getLine\n readNamesTR (n - 1) (s : acc)\n\ncount (names, surnames) = preparedfullnames \n where\n preparedfullnames = (prepare names, prepare surnames)\n prepare = (map tag) . (groupBy sameInit) . sort\n tag x = (length x, (head . head) x, x)\n sameInit name1 name2 = head name1 == head name2\n\nthrd (_, _, x) = x\n\npush [] acc = acc\npush (x : xs) acc = push xs (x : acc)\n\nalignTR acc namestack surnamestack _ ([], ss) = zip namestack (push (concatMap thrd ss) surnamestack) ++ acc\nalignTR acc namestack surnamestack diff (ns, []) = zip (push (concatMap thrd ns) namestack) surnamestack ++ acc\nalignTR acc namestack surnamestack diff (ns@((countn, cn, ln) : ns'), ss@((counts, cs, ls) : ss'))\n | cn < cs = alignTR acc (push ln namestack) surnamestack (diff + countn) (ns', ss)\n | cs < cn = alignTR acc namestack (push ls surnamestack) (diff - counts) (ns, ss')\n | countn == counts = alignTR (zip ln ls ++ acc) namestack surnamestack diff (ns', ss')\n\n | countn > counts && diff == 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (zip ln' ls ++ acc) (push ln'' namestack) surnamestack (countn - counts) (ns', ss')\n\n | countn > counts && diff > 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (zip ln' ls ++ acc) namestack surnamestack diff ((countn - counts, cn, ln'') : ns', ss')\n\n | countn > counts && diff < 0 = let draw = min (abs diff) (countn - counts) in let (ln', ln'') = splitAt draw ln in\n alignTR acc (push ln' namestack) surnamestack (diff + draw) ((countn - draw, cn, ln'') : ns', ss)\n\n | countn < counts && diff == 0 = let (ls', ls'') = splitAt countn ls in\n alignTR (zip ln ls' ++ acc) namestack (push ls'' surnamestack) (countn - counts) (ns', ss')\n\n | countn < counts && diff > 0 = let draw = min diff (counts - countn) in let (ls', ls'') = splitAt draw ls in\n alignTR acc namestack (push ls' surnamestack) (diff - draw) (ns, (counts - draw, cs, ls'') : ss')\n\n | countn < counts && diff < 0 = let (ls', ls'') = splitAt countn ls in \n alignTR (zip ln ls' ++ acc) namestack surnamestack diff (ns', (counts - countn, cs, ls'') : ss')\n\noutput cs = intercalate \", \" $ map (\\(x, y) -> x ++ \" \" ++ y) cs\n\nsolve = output . sort . (alignTR [] [] [] 0) . count\n\nmain = do \n nS <- getLine\n let n = read nS\n names <- readNamesTR n []\n surnames <- readNamesTR n []\n putStrLn (solve (names, surnames))\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (groupBy, intercalate, partition, sort)\n\nreadNamesTR 0 acc = return acc\nreadNamesTR n acc = do\n s <- getLine\n readNamesTR (n - 1) (s : acc)\n\ncount (names, surnames) = (names', surnames')\n where\n names' = prepare names\n surnames' = prepare surnames\n prepare = (map tag) . (groupBy sameInit) . sort\n tag x = (length x, (head . head) x, x)\n sameInit name1 name2 = head name1 == head name2\n\nthrd (_, _, x) = x\n\nalignTR accE (accUN, accUS) ([], ss) = (accE, (accUN, accUS ++ (concatMap thrd ss))) \nalignTR accE (accUN, accUS) (ns, []) = (accE, (accUN ++ (concatMap thrd ns), accUS)) \nalignTR accE accU (ns@(n : ns'), ss@(s : ss'))\n | countn == counts && cn == cs = alignTR ((ln ++ accEN), (ls ++ accES)) accU (ns', ss')\n | cn < cs = alignTR accE (accUN ++ ln, accUS) (ns', ss)\n | otherwise = alignTR accE (accUN, accUS ++ ls) (ns, ss')\n where\n (accEN, accES) = accE\n (accUN, accUS) = accU\n (countn, cn, ln) = n\n (counts, cs, ls) = s\n\nmatch ((evenNames, evenSurnames), (unevenNames, unevenSurnames)) =\n sort $ (zip evenNames evenSurnames) ++ (zip unevenNames unevenSurnames)\n\noutput cs = intercalate \", \" $ map (\\(x, y) -> x ++ \" \" ++ y) cs\n\nsolve = output . match . (alignTR ([], []) ([], [])) . count\n\nmain = do \n nS <- getLine\n let n = read nS\n names <- readNamesTR n []\n surnames <- readNamesTR n []\n putStrLn (solve (names, surnames))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (groupBy, intercalate, partition, sort)\n\nreadNamesTR 0 acc = return acc\nreadNamesTR n acc = do\n s <- getLine\n readNamesTR (n - 1) (s : acc)\n\ncount (names, surnames) = preparedfullnames \n where\n preparedfullnames = (prepare names, prepare surnames)\n prepare = (map tag) . (groupBy sameInit) . sort\n tag x = (length x, (head . head) x, x)\n sameInit name1 name2 = head name1 == head name2\n\nthrd (_, _, x) = x\n\npush [] acc = acc\npush (x : xs) acc = push xs (x : acc)\n\nalignTR acc namestack surnamestack _ ([], ss) = zip namestack (push (concatMap thrd ss) surnamestack) ++ acc\nalignTR acc namestack surnamestack diff (ns, []) = zip (push (concatMap thrd ns) namestack) surnamestack ++ acc\nalignTR acc namestack surnamestack diff (ns@((countn, cn, ln) : ns'), ss@((counts, cs, ls) : ss'))\n | cn < cs = alignTR acc (push ln namestack) surnamestack (diff + countn) (ns', ss)\n | cs < cn = alignTR acc namestack (push ls surnamestack) (diff - counts) (ns, ss')\n | countn == counts = alignTR acc (push ln namestack) (push ls surnamestack) diff (ns', ss')\n | countn > counts && diff >= 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (push (zip ln' ls) acc) namestack surnamestack diff ((countn - counts, cn, ln'') : ns', ss')\n\n | countn > counts && diff < 0 = let draw = min (abs diff) (countn - counts) in let (ln', ln'') = splitAt draw ln in\n alignTR acc (push ln' namestack) surnamestack (diff + draw) ((countn - draw, cn, ln'') : ns', ss)\n\n | countn < counts && diff >= 0 = let draw = min diff (counts - countn) in let (ls', ls'') = splitAt draw ls in\n alignTR acc namestack (push ls' surnamestack) (diff - draw) (ns, (counts - draw, cs, ls'') : ss')\n\n | countn < counts && diff < 0 = let (ls', ls'') = splitAt countn ls in\n alignTR (push (zip ln ls') acc) namestack surnamestack diff (ns', (counts - countn, cs, ls'') : ss')\n\noutput cs = intercalate \", \" $ map (\\(x, y) -> x ++ \" \" ++ y) cs\n\nsolve = output . sort . (alignTR [] [] [] 0) . count\n\nmain = do \n nS <- getLine\n let n = read nS\n names <- readNamesTR n []\n surnames <- readNamesTR n []\n putStrLn (solve (names, surnames))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (groupBy, intercalate, partition, sort)\n\nreadNamesTR 0 acc = return acc\nreadNamesTR n acc = do\n s <- getLine\n readNamesTR (n - 1) (s : acc)\n\ncount (names, surnames) = preparedfullnames \n where\n preparedfullnames = (prepare names, prepare surnames)\n prepare = (map tag) . (groupBy sameInit) . sort\n tag x = (length x, (head . head) x, x)\n sameInit name1 name2 = head name1 == head name2\n\nthrd (_, _, x) = x\n\npush [] acc = acc\npush (x : xs) acc = push xs (x : acc)\n\nalignTR acc namestack surnamestack _ ([], ss) = zip namestack (push (concatMap thrd ss) surnamestack) ++ acc\nalignTR acc namestack surnamestack diff (ns, []) = zip (push (concatMap thrd ns) namestack) surnamestack ++ acc\nalignTR acc namestack surnamestack diff (ns@((countn, cn, ln) : ns'), ss@((counts, cs, ls) : ss'))\n | cn < cs = alignTR acc (push ln namestack) surnamestack (diff + countn) (ns', ss)\n | cs < cn = alignTR acc namestack (push ls surnamestack) (diff - counts) (ns, ss')\n | countn == counts = alignTR (zip ln ls ++ acc) namestack surnamestack diff (ns', ss')\n\n | countn > counts && diff == 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (zip ln' ls ++ acc) (push ln'' namestack) surnamestack (countn - counts) (ns', ss')\n\n | countn > counts && diff > 0 = let (ln', ln'') = splitAt counts ln in\n alignTR (zip ln' ls ++ acc) namestack surnamestack diff ((countn - counts, cn, ln'') : ns', ss')\n\n | countn > counts && diff < 0 = let draw = min (abs diff) (countn - counts) in let (ln', ln'') = splitAt draw ln in\n alignTR acc (push ln' namestack) surnamestack (diff + draw) ((countn - draw, cn, ln'') : ns', ss)\n\n | countn < counts && diff == 0 = let (ls', ls'') = splitAt countn ls in\n alignTR (zip ln ls' ++ acc) namestack (push ls'' surnamestack) (counts - countn) (ns', ss')\n\n | countn < counts && diff > 0 = let draw = min diff (counts - countn) in let (ls', ls'') = splitAt draw ls in\n alignTR acc namestack (push ls' surnamestack) (diff - draw) (ns, (counts - draw, cs, ls'') : ss')\n\n | countn < counts && diff < 0 = let (ls', ls'') = splitAt countn ls in \n alignTR (zip ln ls' ++ acc) namestack surnamestack diff (ns', (counts - countn, cs, ls'') : ss')\n\noutput cs = intercalate \", \" $ map (\\(x, y) -> x ++ \" \" ++ y) cs\n\nsolve = output . sort . (alignTR [] [] [] 0) . count\n\nmain = do \n nS <- getLine\n let n = read nS\n names <- readNamesTR n []\n surnames <- readNamesTR n []\n putStrLn (solve (names, surnames))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.List (groupBy, intercalate, partition, sort)\n\nreadNamesTR 0 acc = return acc\nreadNamesTR n acc = do\n s <- getLine\n readNamesTR (n - 1) (s : acc)\n\ncount (names, surnames) = (names', surnames')\n where\n names' = prepare names\n surnames' = prepare surnames\n prepare = (map tag) . (groupBy sameInit) . sort\n tag x = (length x, (head . head) x, x)\n sameInit name1 name2 = head name1 == head name2\n\nthrd (_, _, x) = x\n\nalignTR accE (accUN, accUS) ([], ss) = (accE, (accUN, accUS ++ (concatMap thrd ss))) \nalignTR accE (accUN, accUS) (ns, []) = (accE, (accUN ++ (concatMap thrd ns), accUS)) \nalignTR accE accU (ns@(n : ns'), ss@(s : ss'))\n | countn == counts && cn == cs = alignTR ((ln ++ accEN), (ls ++ accES)) accU (ns', ss')\n | cn < cs = alignTR accE (accUN ++ ln, accUS) (ns', ss)\n | otherwise = alignTR accE (accUN, accUS ++ ls) (ns, ss')\n where\n (accEN, accES) = accE\n (accUN, accUS) = accU\n (countn, cn, ln) = n\n (counts, cs, ls) = s\n\nmatch ((evenNames, evenSurnames), (unevenNames, unevenSurnames)) =\n sort $ (zip evenNames evenSurnames) ++ (zip unevenNames unevenSurnames)\n\noutput cs = intercalate \", \" $ map (\\(x, y) -> x ++ \" \" ++ y) cs\n\nsolve = output . match . (alignTR ([], []) ([], [])) . count\n\nmain = do \n nS <- getLine\n let n = read nS\n names <- readNamesTR n []\n surnames <- readNamesTR n []\n print (solve (names, surnames))\n"}], "src_uid": "de65dc156a368b28c48443c8a6efb11b"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\ncalc :: String -> Int\ncalc xs = min ynum znum\n where l = length xs\n ys = take l $ cycle \"rb\"\n zs = take l $ cycle \"br\"\n ynum = diff xs ys\n znum = diff xs zs\n\ndiff :: String -> String -> Int\ndiff xs ys = max r b\n where zs = zip xs ys\n ds = map fst $ filter (\\(x,y) -> x /= y) zs\n (rs,bs) = partition (=='r') ds\n r = length rs\n b = length bs\nmain = do\n getLine\n l <- getLine\n putStrLn . show . calc $ l\n", "positive_code": [{"source_code": "neg :: Char -> Char\nneg 'r' = 'b'\nneg 'b' = 'r'\n\nturn :: String -> Char -> (Int, Int)\nturn [] _ = (0, 0)\nturn (a:rest) 'r'\n | a == 'r' = turn rest 'b'\n | otherwise = let (x, y) = turn rest 'b' in (1 + x, y)\nturn (a:rest) 'b'\n | a == 'b' = turn rest 'r'\n | otherwise = let (x, y) = turn rest 'r' in (x, 1 + y)\n\nprocess :: String -> String\nprocess str =\n let [n, rest] = words str\n line = take (read n) rest\n (xr, yr) = turn line 'r'\n (xb, yb) = turn line 'b'\n in show $ min (max xr yr) (max xb yb)\n\nmain :: IO ()\nmain = interact process"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\ncalc :: String -> Int\ncalc [] = 0\ncalc [_] = 0\ncalc \"rr\" = 1\ncalc \"bb\" = 1\ncalc [_,_] = 0\ncalc ('r':'r':'r':xs) = 1 + calc ('r':xs)\ncalc ('b':'b':'b':xs) = 1 + calc ('b':xs)\ncalc ('r':'r':xs) = 1 + (calc $ swap $ 'r':xs)\ncalc ('b':'b':xs) = 1 + (calc $ swap $ 'b':xs)\ncalc ('r':'b':xs) = calc ('b':xs)\ncalc ('b':'r':xs) = calc ('r':xs)\n\nswap :: String -> String\nswap [] = []\nswap [x] = [x]\nswap (x:y:xs) = y:x:xs\n\nmain = do\n getLine\n l <- getLine\n putStrLn . show . calc $ l"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\ncalc :: String -> Int\ncalc [] = 0\ncalc [_] = 0\ncalc \"rr\" = 1\ncalc \"bb\" = 1\ncalc [_,_] = 0\ncalc ('r':'r':'r':xs) = 1 + calc xs\ncalc ('b':'b':'b':xs) = 1 + calc xs\ncalc ('r':'r':xs) = 1 + (calc $ swap $ 'r':xs)\ncalc ('b':'b':xs) = 1 + (calc $ swap $ 'b':xs)\ncalc ('r':'b':xs) = calc ('b':xs)\ncalc ('b':'r':xs) = calc ('r':xs)\n\nswap :: String -> String\nswap [] = []\nswap [x] = [x]\nswap (x:y:xs) = y:x:xs\n\nmain = do\n getLine\n l <- getLine\n putStrLn . show . calc $ l"}, {"source_code": "neg :: Char -> Char\nneg 'r' = 'b'\nneg 'b' = 'r'\n\nturn :: String -> Char -> Int\nturn [c] t\n | c == t = 0\n | otherwise = 1\nturn (a:b:rest) t\n | a == t = turn (b:rest) (neg t)\n | b == t = 1 + turn rest t\n | otherwise = 1 + turn (b:rest) (neg t)\n\nprocess :: String -> String\nprocess str =\n let [n, rest] = words str\n line = take (read n) rest\n in show $ min (turn line 'r') (turn line 'b')\n\nmain :: IO ()\nmain = interact process"}], "src_uid": "3adc75a180d89077aa90bbe3d8546e4d"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nelim1689 s = delete '1' $ delete '6' $ delete '9' $ delete '8' s\n\nmodulo = 7\n\nnewtype Modulo = Modulo { getInteger :: Integer } deriving(Eq,Ord)\ninstance Num Modulo where\n Modulo a + Modulo b = Modulo ((a+b) `mod` modulo)\n Modulo a - Modulo b = Modulo ((a-b) `mod` modulo)\n Modulo a * Modulo b = Modulo ((a*b) `mod` modulo)\n abs (Modulo a) = Modulo (abs a)\n signum (Modulo a) = Modulo (signum a)\n fromInteger i = Modulo i\ninstance Fractional Modulo where\n recip (Modulo a) = Modulo (modInv a)\n fromRational = undefined\n\ninstance Show Modulo where\n show (Modulo i) = show i\n \nmodInv i = (modulo + x `mod` modulo) `mod` modulo\n where\n (x,y) = go i modulo\n go a 0 = (1,0)\n go a b = let (y,x) = go b (a `mod` b) in (x,y - a `div` b * x)\n\nmain = do\n s <- getLine\n let s' = elim1689 s\n v = fst (fromJust (B.readInteger (B.pack s'))) `mod` 7 :: Integer\n n = length s'\n q = getInteger (Modulo 10 ^ n)\n if n == 0 then\n putStrLn \"1869\"\n else do\n let Just x = find (\\x -> (q * x + v) `mod` 7 == 0) [0..]\n putStrLn $ case x of\n 0 -> \"1869\"++s'\n 1 -> \"1968\"++ s'\n 2 -> \"1689\"++ s'\n 3 -> \"6198\"++ s'\n 4 -> \"1698\"++ s'\n 5 -> \"1986\"++ s'\n 6 -> \"1896\"++ s'\n", "positive_code": [{"source_code": "#!/usr/bin/env runghc\nimport Data.List\nimport Data.Char\nmain = getContents >>= mapM_ putStrLn . solve . lines\nsolve [] = [] ::[String]\nsolve (c:cs) = (:solve cs)$ f (permutations t)\n where\n t = \"1689\"\n s = c\\\\t\n f [] = \"0\"\n f (t:ts) = if r==0 then t++s else f ts\n where r = foldl (\\r c->(r*10+ord c-ord '0')`mod`7) 0 (t++s)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Char\n\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n\nmain = getLine >>= (putStrLn . map intToDigit . solve . map digitToInt)\n\niterateN' 0 f x = x\niterateN' n f x = x `seq` iterateN' (n-1) f (f x)\n\npre :: Int -> [Int]\npre 0 = [9, 6, 1, 8]\npre 1 = [9, 8, 1, 6]\npre 2 = [9, 8, 6, 1]\npre 3 = [1, 9, 8, 6]\npre 4 = [1, 9, 6, 8]\npre 5 = [1, 6, 8, 9]\npre 6 = [6, 9, 8, 1]\npre n = pre $ n `mod` 7\n\ncount :: [Int] -> IntMap Int\ncount = foldl' (\\(!m) d -> IntMap.insertWith (+) d 1 m) IntMap.empty\n\nsolve :: [Int] -> [Int]\nsolve xs = reverse $ iterateN' (IntMap.findWithDefault 0 0 mp) (0:) (pre (-10^4 * rm) ++ ys)\n where\n dec = IntMap.adjust (subtract 1)\n mp = dec 1 . dec 6 . dec 8 . dec 9 $ count xs\n (ys, rm) = IntMap.foldlWithKey' proc ([], 0) mp\n\n proc acc 0 _ = acc\n proc acc d c = iterateN' c (\\(!st, !rm) -> (d:st, (10*rm + d) `mod` 7)) acc\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nchars = \"1689\"\nmodulus = 7\nbase = 10\nnotFound = \"0\"\nclearChars xs = foldr (\\ f x -> f x) xs (map delete chars) \nmods xs = foldl' (\\p d-> mod (base * p + digitToInt d) modulus) 0 xs\nfindPrefix str = find suitable (permutations chars) where\n\tsuitable prefix = (mod (mods prefix * modPower + modStr) modulus) == 0\n\tmodPower \t\t= mods ('1':replicate (length str) '0')\n\tmodStr \t\t= mods str\nsolution str = \n\tlet cleared = clearChars str in\n\tlet\tprefix = findPrefix cleared\n\tin case prefix of \n\t\tJust prefix -> Just (prefix ++ cleared) \n\t\tNothing -> Nothing\n\nmain = do\n\tstr <- getLine\n\tputStrLn ( fromMaybe notFound ( solution str ) )\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Char\n\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\n\n-- import System.Random\n\nmain = getLine >>= (putStrLn . map intToDigit . solve . map digitToInt)\n\n{- main = do\n gen <- getStdGen\n let xs = take (10^5) $ randomRs (0, 9) gen\n print xs\n print $ solve xs\n print $ count xs == count (solve xs) -}\n\niterateN' 0 f x = x\niterateN' n f x = x `seq` iterateN' (n-1) f (f x)\n\npre :: Int -> [Int]\npre 0 = [9, 6, 1, 8]\npre 1 = [9, 8, 1, 6]\npre 2 = [9, 8, 6, 1]\npre 3 = [1, 9, 8, 6]\npre 4 = [1, 9, 6, 8]\npre 5 = [1, 6, 8, 9]\npre 6 = [6, 9, 8, 1]\npre n = pre $ n `mod` 7\n\ncount :: [Int] -> IntMap Int\ncount = foldl' (\\(!m) d -> IntMap.insertWith (+) d 1 m) IntMap.empty\n\nsolve :: [Int] -> [Int]\nsolve xs = reverse $ iterateN' (IntMap.findWithDefault 0 0 mp) (0:) (pre (-10^4 * rm) ++ ys)\n where\n dec = IntMap.adjust (subtract 1)\n mp = dec 1 . dec 6 . dec 8 . dec 9 $ count xs\n (ys, rm) = IntMap.foldlWithKey' proc ([], 0) mp\n\n proc acc 0 _ = acc\n proc acc d c = iterateN' c (\\(!st, !rm) -> (d:st, (10*rm + d) `mod` 7)) acc\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nelim1689 s = delete '1' $ delete '6' $ delete '9' $ delete '8' s\n\n\nmain = do\n s <- getLine\n let s' = elim1689 s\n v = fst (fromJust (B.readInteger (B.pack s'))) `mod` 7 :: Integer\n if length s' == 0 then\n putStrLn \"1869\"\n else \n putStrLn $ case mod (v * 4) 7 of\n 0 -> s'++\"1869\"\n 1 -> s'++\"1896\"\n 2 -> s'++\"1986\"\n 3 -> s'++\"1698\"\n 4 -> s'++\"6198\"\n 5 -> s'++\"1689\"\n 6 -> s'++\"1968\"\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\nelim1689 s = delete '1' $ delete '6' $ delete '9' $ delete '8' s\n\n\nmain = do\n s <- getLine\n let s' = elim1689 s\n v = fst (fromJust (B.readInteger (B.pack s'))) `mod` 7 :: Integer\n if length s' == 0 then\n putStrLn \"1896\"\n else \n putStrLn $ case mod (v * 4) 7 of\n 0 -> s'++\"1896\"\n 1 -> s'++\"1869\"\n 2 -> s'++\"1986\"\n 3 -> s'++\"1698\"\n 4 -> s'++\"6198\"\n 5 -> s'++\"1689\"\n 6 -> s'++\"1968\"\n"}], "src_uid": "3b10e984d7ca6d4071fd4e743394bb60"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, q, k] <- readInts\n a <- readInts\n let\n los = 1 : zipWith min a (tail a)\n his = zipWith max a (tail a) ++ [k]\n opts = zipWith (\\x y -> x - y - 2) his los\n optPrefSums = tail $ scanl (\\x y -> x + fromIntegral y) 0 opts\n optArr :: UArray Int Int64\n optArr = listArray (1, n) optPrefSums\n aArr :: UArray Int Int64\n aArr = listArray (1, n) $ map fromIntegral a\n k64 :: Int64\n k64 = fromIntegral k\n --lift $ print aArr\n --lift $ print los\n --lift $ print his\n --lift $ print optArr\n replicateM_ q $ do\n [li, ri] <- readInts\n if li == ri\n then putInts [k64 - 1]\n else let\n midOpts = optArr ! (ri - 1) - optArr ! li\n endOpt = k64 - aArr ! (ri - 1) - 1\n startOpt = aArr ! (li + 1) - 2\n in do\n --lift $ print startOpt\n --lift $ print midOpts\n --lift $ print endOpt\n --lift $ putStr \"tot = \"\n putInts [startOpt + midOpts + endOpt]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int64] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Foldable\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n ~[n, q, k] <- popInts\n a <- listArray (0, n - 1) <$> popInts\n qq <- replicateM q ((\\[l, r] -> (l - 1, r - 1)) <$> popInts)\n return $ B.unlines $ map bshow (solve n k a qq)\n\n\nsolve :: Int -> Int -> UArray Int Int -> [(Int, Int)] -> [Int]\nsolve n k as qs = map solve1 qs\n where\n bs :: UArray Int Int\n bs = listArray (0, n - 1) $ map makeB [0 .. n - 1]\n\n makeB i = let low | i == 0 = 0\n | otherwise = as ! (i - 1)\n high | i == n - 1 = k + 1\n | otherwise = as ! (i + 1) in\n high - low - 2\n\n segs :: [UArray Int Int]\n segs = reverse $ makeSegs n [bs]\n\n makeSegs 1 sss = sss\n makeSegs n sss@(ss : _) =\n let n' = (n + 1) `quot` 2\n p i | i == n - 1 = ss ! i\n | otherwise = ss ! i + ss ! (i + 1)\n nss = listArray (0, n' - 1) $\n map (p . (* 2)) [0 .. n' - 1] in\n makeSegs n' (nss : sss)\n\n bsum l r | l > r = 0\n | otherwise = bsum' segs l (r + 1)\n\n bsum' (ss : sss) l r = case r - l of\n (-1) -> 0\n 0 -> 0\n 1 -> ss ! l\n _ -> let (lv, l') = case l `quotRem` 2 of\n (q, 0) -> (0, q)\n (q, _) -> (ss ! l, q + 1)\n (rv, r') = case r `quotRem` 2 of\n (q, 0) -> (0, q)\n (q, _) -> (ss ! (r - 1), q) in\n lv + rv + bsum' sss l' r'\n\n solve1 (l, r) | l == r = k - 1\n | otherwise = (as ! (l + 1) - 2) +\n (k - as ! (r - 1) - 1) +\n bsum (l + 1) (r - 1)\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, q, k] <- getInts\n as <- getInts\n let\n a = array (1, n) $ zip [1..] $ map fromIntegral as\n f :: Int -> Int64\n f i = high - low - 2\n where\n low = if i == 1 then 0 else a ! (i - 1)\n high = if i == n then k' + 1 else a ! (i + 1)\n aa = map f [1..n]\n a' = array (1, n) $ zip [1..] aa\n b = array (0, n) $ zip [0..] $ scanl' (+) 0 aa\n k' = fromIntegral k\n solve :: Int -> Int -> Int64\n solve l r\n | l == r = k' - 1\n | l + 1 == r = a ! r - 2 + k' - a ! l - 1\n | otherwise = b ! (r - 1) - b ! l + a ! (l + 1) - 2 + k' - a ! (r - 1) - 1\n replicateM_ q $ do\n [l, r] <- getInts\n C.putStrLn $ C.pack $ show $ solve l r\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, q, k] <- getInts\n as <- getInts\n let\n a = array (1, n) $ zip [1..] $ map fromIntegral as\n f :: Int -> Int64\n f i = high - low - 2\n where\n low = if i == 1 then 0 else a ! (i - 1)\n high = if i == n then k' + 1 else a ! (i + 1)\n aa = map f [1..n]\n a' = array (1, n) $ zip [1..] aa\n b = array (0, n) $ zip [0..] $ scanl' (+) 0 aa\n k' = fromIntegral k\n solve :: Int -> Int -> Int64\n solve l r\n | l == r = k' - 1\n | l + 1 == r = a' ! r - 2 + k' - a' ! l + 1\n | otherwise = b ! (r - 1) - b ! l + a ! (l + 1) - 2 + k' - a ! (r - 1) - 1\n replicateM_ q $ do\n [l, r] <- getInts\n C.putStrLn $ C.pack $ show $ solve l r\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [n, q, k] <- getInts\n as <- getInts\n let\n a = array (1, n) $ zip [1..] as\n f i = high - low - 2\n where\n low = if i == 1 then 0 else a ! (i - 1)\n high = if i == n then k + 1 else a ! (i + 1)\n aa = map f [1..n]\n a' = array (1, n) $ zip [1..] aa\n b = array (0, n) $ zip [0..] $ scanl' (+) 0 aa\n solve l r\n | l == r = k - 1\n | l + 1 == r = a' ! r - 2 + k - a' ! l + 1\n | otherwise = b ! (r - 1) - b ! l + a ! (l + 1) - 2 + k - a ! (r - 1) - 1\n replicateM_ q $ do\n [l, r] <- getInts\n C.putStrLn $ C.pack $ show $ solve l r\n"}], "src_uid": "740d2aba32f69b8cfe8f7cb624621a63"} {"source_code": "isSqrt :: Int -> Bool\r\nisSqrt x = y * y == x\r\n where \r\n y = round $ sqrt $ fromIntegral x\r\n\r\ngetAns :: Int -> String\r\ngetAns x\r\n | x `mod` 2 == 0 && isSqrt (x `div` 2) = \"YES\"\r\n | x `mod` 4 == 0 && isSqrt (x `div` 4) = \"YES\"\r\n | otherwise = \"NO\"\r\n\r\nsolve (x:xs) = map getAns $ map read xs\r\n\r\nmain = do\r\n interact $ unlines . solve . lines ", "positive_code": [{"source_code": "import Control.Arrow\n\nsolve :: Int -> Bool\nsolve 1 = True\nsolve x = even x && (isSquare (x `div` 2) || solve (x `div` 2))\n where\n isSquare :: Int -> Bool\n isSquare n = sq * sq == n\n where\n sq = floor $ sqrt (fromIntegral n::Double)\n\nmain :: IO()\nmain = interact $ lines >>> tail >>> map ((\\x -> read x :: Int) >>> (\\x -> x > 1 && solve x) >>> repr) >>> unlines\n where\n repr True = \"YES\"\n repr False = \"NO\""}, {"source_code": "import GHC.Float (float2Int, int2Float)\n\nf :: Int -> String\nf n\n | mod n 4 == 0 && isSquare (div n 4) = \"YES\"\n | mod n 2 == 0 && isSquare (div n 2) = \"YES\"\n | otherwise = \"NO\"\n\nisSquare :: Int -> Bool\nisSquare n = float2Int (sqrt (int2Float n)) ^ 2 == n\n\nmain = interact $ unlines . map (f . read) . tail . lines"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bifunctor\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport Data.STRef.Strict\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\nsq :: Int -> Bool\r\nsq n =\r\n let s = floor . sqrt. fromIntegral $ n\r\n in\r\n s * s == n\r\n\r\nsolve :: Int -> Bool\r\nsolve n = (even n && sq (n `div` 2)) || (n `mod` 4 == 0 && sq (n `div` 4))\r\n\r\nmain = do\r\n tn <- parseInt <$> BS.getLine\r\n replicateM_ tn $ do\r\n n <- parseInt <$> BS.getLine\r\n putStrLn (if solve n then \"YES\" else \"NO\")"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nisqrt :: Int -> Int\nisqrt v = round $ sqrt (fromIntegral v :: Double)\n\nok :: Int -> Int -> Bool\nok w x = case divMod x w of\n (q, 0) -> q == isqrt q * isqrt q\n _ -> False\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n lift $ P.putStr $ if ok 2 n || ok 4 n\n then P.pack \"YES\\n\"\n else P.pack \"NO\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Monad\r\n\r\nisSquare n = sq * sq == n where sq = floor $ sqrt $ fromIntegral n \r\ncheck n k = mod n k == 0 && isSquare (div n k) \r\n\r\nprintResult = do\r\n n <- readLn :: IO Int\r\n putStrLn $ if check n 2 || check n 4 then \"YES\" else \"NO\"\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.Bits\r\nreadInt = readLn :: IO Int\r\nsolve n = putStrLn r where r = if n .&. (n-1) == 0 && n > 1 then \"YES\" else \"NO\" \r\nmain = do\r\n n <- readInt\r\n a <- replicateM n readInt\r\n mapM solve a"}, {"source_code": "import Control.Monad\r\nimport Data.Bits\r\nreadInt = readLn :: IO Int\r\nsolve n = putStrLn r where r = if n .&. (n-1) == 0 then \"YES\" else \"NO\" \r\nmain = do\r\n n <- readInt\r\n a <- replicateM n readInt\r\n mapM solve a"}, {"source_code": "import Control.Arrow\n\npows :: [Int]\npows = iterate (*2) 2\n\nsolve :: [Int] -> Int -> Bool\nsolve _ 1 = True\nsolve (n:ns) x = even x && (isSquare (x `div` n) || solve ns (x `div` n))\n where\n isSquare :: Int -> Bool\n isSquare n = sq * sq == n\n where\n sq = floor $ sqrt (fromIntegral n::Double)\n\nmain :: IO()\nmain = interact $ lines >>> tail >>> map ((\\x -> read x :: Int) >>> solve pows >>> repr) >>> unlines\n where\n repr True = \"YES\"\n repr False = \"NO\""}], "src_uid": "6ae754639d96790c890f9d1ab259332a"} {"source_code": "-- https://codeforces.com/contest/1618/problem/B\nimport Control.Monad (replicateM)\n\nanswer [b] found = b ++ if not found then \"a\" else \"\"\nanswer (b1:b2:bs) found\n | b1!!1 == b2!!0 || found = b1!!0 : answer (b2:bs) found\n | otherwise = b1 ++ answer (b2:bs) True\n\nmain = getLine >>= flip replicateM run . read\nrun = do\n n <- getLine\n line <- words <$> getLine\n putStrLn $ answer line False\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n xs <- words . C.unpack <$> C.getLine\r\n let gen c1 c2\r\n | c1 == c2 = [c1]\r\n | otherwise = [c1, c2]\r\n s = [head $ head xs] ++ concat (zipWith gen (map last xs) (map head $ tail xs)) ++ [last $ last xs]\r\n putStrLn $ if length s == n then s else 'a':s\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n"}], "negative_code": [], "src_uid": "565056bfe716ee89230270bdc14c9051"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nmain = B.interact exec\nexec = B.pack . unwords . map show . solve . map (maybe undefined fst . B.readInt) . tail . B.words\nsolve (r0:xs) = snd $ mapAccumL (\\bs x -> let y = fromMaybe r $ collide r x bs in ((x, y):bs, y)) [] $ map fromIntegral xs\n where r = fromIntegral (r0 :: Int) :: Double\n\ncollide r x = maximumMay . map (\\(x', y') -> let t = sqrt $ 4 * r * r - (x - x') * (x - x') in max (y' - t) (y' + t)) . filter (\\(x', _) -> overlap (x - r, x + r) (x' - r, x' + r))\n\nmaximumMay [] = Nothing\nmaximumMay xs = Just $ maximum xs\n\noverlap a b = go a b || go b a\n where go (x1, x2) (y1, y2) = x1 <== y2 && y1 <== x2\n\na <== b = a < b || abs (a - b) <= 1e-5", "positive_code": [{"source_code": "import Data.List\nimport Data.Bifunctor\nimport Data.Function\n-- import Debug.Trace\n\ncircleStick :: Int -> Int -> Int -> Double\ncircleStick r x1 x2 =\n let dx = fromIntegral $ abs (x1 - x2)\n in sqrt $ (fromIntegral (2*r))^2 - dx^2\n\nfolder :: Int -> [(Int, Double)] -> Int -> [(Int, Double)]\nfolder r prevs new = \n let \n isCandidate a = 2 * r >= abs (a - new)\n candidates = filter (isCandidate . fst) prevs\n in if null candidates then (new, fromIntegral r):prevs\n else let height = maximum . map (uncurry (+) . first (circleStick r new) ) $ candidates\n in (new, height):prevs\n\nmain :: IO ()\nmain = do\n [n, r] <- map (read :: String -> Int) . words <$> getLine\n mapM_ (print . snd) =<< reverse. foldl' (folder r) [] . map (read :: String -> Int) . words <$> getLine\n return ()\n"}, {"source_code": "import System.IO\nimport Data.List (sort)\n\njoin s xs = foldr (\\a b -> a++s++b) \"\" xs\n\niLn :: IO [Double]\niLn = getLine >>= (return . fmap (read) . words)\n\nmain = do\n [_,r] <- iLn\n xs <- iLn\n putStrLn $ join \" \" . fmap show . reverse $ solve r ( xs) []\n--solve :: Double -> [Double] -> [(Double,Double)] -> [Double]\nsolve r [] ps = fmap fst ps\nsolve r (x:xs) a = solve r xs $ d r x\n (filter ((<=2*r).abs.(x-).snd) a) : a\nd r x [] = (r,x)\nd r x ps =\n foldr1 max.fmap (\\(h,xx)->\n (h+(sqrt.abs$4*r*r-(x-xx)^2),x)\n )$ps\n"}], "negative_code": [{"source_code": "import System.IO\n\nmerge xs [] = xs\nmerge [] xs = xs\nmerge xx@(x:xs) yy@(y:ys) =\n if (x []\n [a] -> [a]\n _ -> uncurry merge $ (\\(x, y)-> (msort x,msort y) ) $ splitAt ((length xs) `div` 2) xs\njoin s xs = foldr (\\a b -> a++s++b) \"\" xs\n\nmain = do\n [_,r] <- getLine >>= (return . fmap (read) . words)\n xs <- getLine >>= (return . fmap (read) . words)\n putStrLn $ join \" \" . fmap show . reverse $ solve r ( xs) []\n\n--solve :: Double -> [Double] -> [(Double,Double)] -> [Double]\nsolve r [] ps = fmap fst ps\nsolve r (x:xs) a = solve r xs $ dro r x a : a\ndro r x ps = d r x $ filter ((<=2*r).abs.(x-).snd) ps\nd r x [] = (r,x)\nd r x ps = (\\(h,xx)->\n (h+(sqrt.abs$4*r*r-(x-xx)^2),x)\n )\n $last.msort$ps\n"}], "src_uid": "3cd019d1016cb3b872ea956c312889eb"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.IORef\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\nimport Debug.Trace\nimport System.IO\nimport Text.Printf (printf)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Num b) => a -> b\ncast = fromIntegral\n{-# INLINE cast #-}\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep i j m = go i where\n go !i\n | i < j = m i >> go (i+1)\n | otherwise = return ()\n{-# INLINE rep #-}\n\nrrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrrep i j m = go i where\n go !i\n | i > j = m (i-1) >> go (i-1)\n | otherwise = return ()\n{-# INLINE rrep #-}\n\n-----\n\nmain :: IO ()\nmain = do\n s <- getLine\n t <- getLine\n\n let d = cnv s\n e = cnv t\n\n if d == e\n then putStrLn \"=\"\n else do\n if cmp d e\n then putStrLn \"<\"\n else putStrLn \">\"\n\ncmp (a, b) (c, d) =\n cast (a-c) * (sqrt 5 + 1) / 2 < cast (d-b)\n\ncnv :: String -> (Integer, Integer)\ncnv s = go 0 1 (reverse s) 0 0 where\n q = (sqrt 5+1)/2\n\n go !a !b (c:cs) !v !w =\n go (a+b) (a) cs\n (v+(if c == '1' then a else 0))\n (w+(if c == '1' then b else 0))\n\n go _ _ _ v w = (v, w)\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n s1 <- getLine\n s2 <- getLine\n putStrLn $ case cmp s1 s2 of\n LT -> \"<\"\n EQ -> \"=\"\n GT -> \">\"\n\ncmp :: String -> String -> Ordering\ncmp a b = compare sa sb where\n na = length a\n nb = length b\n n = max na nb\n a' = take (n-na) (repeat '0') ++ a\n b' = take (n-nb) (repeat '0') ++ b\n sa = normalize a'\n sb = normalize b'\n\nnormalize :: String -> String\nnormalize ('1':'1':cs) = '1':normalize ('0':cs)\nnormalize ('1':cs) = case normalize cs of\n '0':'1':cs' -> '1':'0':'0':cs'\n '0':cs' -> '0':'1':cs'\nnormalize ('0':cs) = '0':normalize cs\nnormalize [] = \"0\"\n{-\nq = (1+ sqrt(5)) / 2\neval :: String -> Double\neval = foldl (\\e ch -> e*q + if ch == '0' then 0 else 1) 0\n\nprop_normalize = forAll gens $ \\s -> 1 + length s == length (normalize s) && abs (eval s - eval (normalize s))/ (eval s + 1) < 1.0e-9\nprop = forAll gen $ \\(a,b) -> cmp a b == naiveCmp a b \ngens = sized $ \\n -> do\n n <- choose (0,n)\n replicateM n (choose ('0','1'))\n\ngen = liftM2 (,) gens gens\n\nnaiveCmp a b | otherwise = compare x y where\n x = eval a\n y = eval b\n\n \n-}\n"}, {"source_code": "main = interact $ f . words\nf [a, b] | c < d = \"<\"\n | c == d = \"=\"\n | c > d = \">\"\n where [c, d] = h (g ('0':'0':a)) (g ('0':'0':b))\n\nh a b = [replicate (l - al) '0' ++ a, replicate (l - bl) '0' ++ b]\n where al = length a\n bl = length b\n l = max al bl\n\ng (b:c:[]) = [b, c]\ng (a:'1':'1':d) = i $ '1':(g ('0':'0':d))\ng (a:b:c:d) = i $ a:(g (b:c:d))\n\ni (a:'1':'1':d) = '1':'0':'0':d\ni (a:b:c:d) = a:b:c:d"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.Functor\nimport Data.Int\nimport qualified Data.IntMap as IM\nimport Data.IORef\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Sequence as Seq\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\nimport Debug.Trace\nimport System.IO\nimport Text.Printf (printf)\n\n-- I/O\n\nreadInts :: C.ByteString -> [Int]\nreadInts = map fst . mapMaybe C.readInt . C.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> C.getLine\n\nreadNums :: Num a => C.ByteString -> [a]\nreadNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words\n\ngetNums :: Num a => IO [a]\ngetNums = readNums <$> C.getLine\n\ncast :: (Integral a, Num b) => a -> b\ncast = fromIntegral\n{-# INLINE cast #-}\n\nrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrep i j m = go i where\n go !i\n | i < j = m i >> go (i+1)\n | otherwise = return ()\n{-# INLINE rep #-}\n\nrrep :: Int -> Int -> (Int -> IO ()) -> IO ()\nrrep i j m = go i where\n go !i\n | i > j = m (i-1) >> go (i-1)\n | otherwise = return ()\n{-# INLINE rrep #-}\n\n-----\n\nmain :: IO ()\nmain = do\n s <- getLine\n t <- getLine\n\n let d = cnv s\n e = cnv t\n\n if abs (d-e) < 1e-10\n then putStrLn \"=\"\n else do\n if d < e\n then putStrLn \"<\"\n else putStrLn \">\"\n\ncnv s = go 1 (reverse s) 0 where\n q = (sqrt 5+1)/2\n\n\n go !d (c:cs) !acc =\n go (d*q) cs $ acc+(if c == '1' then d else 0)\n\n go _ _ !acc = acc\n"}], "src_uid": "7c0a288a2777894bdfd75cb9703346e9"} {"source_code": "-- import Debug.Trace\nimport qualified Data.Set as S\nimport Data.Int\nimport Data.List\nimport Control.Monad\nmain = do\n expr <- getLine\n costs <- map (map read . words) . lines <$> getContents\n case go costs expr [] S.empty 0 0 0 of\n Nothing -> putStrLn \"-1\"\n Just (cost,adjs) -> -- traceShowM adjs >>\n print cost >> putStrLn (adjust adjs expr 0)\ngo :: [[Int64]] -> String -> [Int] -> S.Set (Int64,Int) -> Int64 -> Int -> Int\n -> Maybe (Int64,[Int])\ngo cs bs adjs s a d i | d < 0 = case S.minView s of\n Nothing -> Nothing\n Just ((c,ai),s') -> ((go cs bs (ai:adjs) s' $! a+c) $! d+2) $ i\ngo cs@ ~([co,cc]:cs') (b:bs) adjs s a d i = case b of\n '(' -> (go cs bs adjs s a $! d+1) $! i+1\n ')' -> (go cs bs adjs s a $! d-1) $! i+1\n '?' -> (((go cs' bs adjs $! S.insert (co-cc,i) s) $! a+cc) $! d-1) $! i+1\ngo [] [] adjs _ a d _ = guard (d == 0) >> Just (a,sort adjs)\n-- go cs bs adjs s a d i = traceShow (cs,bs,adjs,s,a,d,i) $ error \"NEP\"\nadjust as ('?':cs) i | not (null as) && i == head as\n = '(' : (adjust (tail as) cs $! i+1)\n | otherwise = ')' : (adjust as cs $! i+1)\nadjust as (c:cs) i = c : (adjust as cs $! i+1)\nadjust [] \"\" _ = \"\"\n-- adjust as cs i = traceShow (as,cs,i) $ error \"NEP\"\n", "positive_code": [{"source_code": "module Main where\n\nimport qualified Data.Set as S\nimport Data.Int (Int64)\nimport Data.List\nimport Data.Ord\nimport Data.Functor ((<&>))\n\nmain :: IO ()\nmain = do\n expr <- getLine\n costs <- lines <$> getContents\n case solve expr costs of\n Nothing -> print (-1)\n Just (totalCost, resultExpr) -> print totalCost >> putStrLn resultExpr\n\nsolve :: String -> [String] -> Maybe (Int64, String)\nsolve expr inputs = findAdjusts indexedExpr (initialState inputs) <&> fmap (applyAdjusts indexedExpr . sort)\n where\n indexedExpr = zip [1..] expr\n\ninitialState :: [String] -> FoldState\ninitialState costInputs = FoldState {\n totalCost = 0,\n balance = 0,\n adjustedPositions = [],\n adjusts = S.empty,\n costs = map getCost costInputs\n }\n\nfindAdjusts :: [(Int, Char)] -> FoldState -> Maybe (Int64, [Int])\nfindAdjusts [] state = if balance state == 0 then Just (totalCost state, adjustedPositions state) else Nothing\nfindAdjusts ((_, '('):expr) state = findAdjusts expr $ addBalance state 1\nfindAdjusts ((_, ')'):expr) state = findAdjusts expr =<< relax (addBalance state (-1))\nfindAdjusts ((p, _):expr) state = findAdjusts expr =<< relax (replaceChar state p)\n\naddBalance :: FoldState -> Int -> FoldState\naddBalance state@FoldState{ balance = b } db = state { balance = b + db }\n\nrelax :: FoldState -> Maybe FoldState\nrelax state | b >= 0 = Just state\n | otherwise = S.minView as <&> \\(Adjust p dc, nas) -> state { balance = b + 2\n , totalCost = t + dc\n , adjusts = nas\n , adjustedPositions = p:aps\n }\n where\n FoldState t b aps as _ = state\n\nreplaceChar :: FoldState -> Int -> FoldState\nreplaceChar state pos = state { balance = b - 1\n , totalCost = t + closeCost c\n , adjusts = S.insert (Adjust pos $ openCost c - closeCost c) as\n , costs = cs\n }\n where\n FoldState t b _ as (c:cs) = state\n\napplyAdjusts :: [(Int, Char)] -> [Int] -> String\napplyAdjusts [] _ = []\napplyAdjusts ((i, '?'):cs) (a:as) | i == a = '(':applyAdjusts cs as\napplyAdjusts ((_, '?'):cs) adjusts = ')':applyAdjusts cs adjusts\napplyAdjusts ((_, c):cs) adjusts = c:applyAdjusts cs adjusts\n\ndata FoldState = FoldState {\n totalCost :: Int64,\n balance :: Int,\n adjustedPositions :: [Int],\n adjusts :: S.Set Adjust,\n costs :: [Cost]\n } deriving (Show)\n\ndata Cost = Cost {\n openCost :: Int64,\n closeCost :: Int64\n } deriving (Show)\n\ndata Adjust = Adjust {\n position :: Int,\n cost :: Int64\n } deriving (Show, Eq)\n\ninstance Ord Adjust where\n compare = comparing cost <> comparing position\n\ngetCost :: String -> Cost\ngetCost input = let [open, close] = map read (words input) in Cost open close"}, {"source_code": "module Main where\n\nimport qualified Data.Set as S\nimport Data.Int (Int64)\nimport Data.List\nimport Data.Ord\nimport Data.Functor ((<&>))\n\nmain :: IO ()\nmain = do\n expr <- getLine\n costs <- lines <$> getContents\n case solve expr costs of\n Nothing -> print (-1)\n Just (totalCost, resultExpr) -> print totalCost >> putStrLn resultExpr\n\nsolve :: String -> [String] -> Maybe (Int64, String)\nsolve expr inputs = findAdjusts indexedExpr (initialState inputs) <&> fmap (applyAdjusts indexedExpr . sort)\n where\n indexedExpr = zip [1..] expr\n\ninitialState :: [String] -> FoldState\ninitialState costInputs = FoldState {\n totalCost = 0,\n balance = 0,\n adjustedPositions = [],\n adjusts = S.empty,\n costs = map getCost costInputs\n }\n\nfindAdjusts :: [(Int, Char)] -> FoldState -> Maybe (Int64, [Int])\nfindAdjusts [] state = if balance state == 0 then Just (totalCost state, adjustedPositions state) else Nothing\nfindAdjusts ((_, '('):expr) state = findAdjusts expr $ addBalance state 1\nfindAdjusts ((_, ')'):expr) state = findAdjusts expr =<< relax (addBalance state (-1))\nfindAdjusts ((p, _):expr) state = findAdjusts expr =<< relax (replaceChar state p)\n\naddBalance :: FoldState -> Int -> FoldState\naddBalance state@FoldState{ balance = b } db = state { balance = b + db }\n\nrelax :: FoldState -> Maybe FoldState\nrelax state | b >= 0 = Just state\n | otherwise = S.minView as <&> \\(Adjust p dc, nas) -> state { balance = b + 2\n , totalCost = t + dc\n , adjusts = nas\n , adjustedPositions = p:aps\n }\n where\n FoldState t b aps as _ = state\n\nreplaceChar :: FoldState -> Int -> FoldState\nreplaceChar state pos = state { balance = b - 1\n , totalCost = t + closeCost c\n , adjusts = S.insert (Adjust pos $ openCost c - closeCost c) as\n , costs = cs\n }\n where\n FoldState t b _ as (c:cs) = state\n\napplyAdjusts :: [(Int, Char)] -> [Int] -> String\napplyAdjusts [] _ = []\napplyAdjusts ((i, '?'):cs) (a:as) | i == a = '(':applyAdjusts cs as\napplyAdjusts ((_, '?'):cs) adjusts = ')':applyAdjusts cs adjusts\napplyAdjusts ((_, c):cs) adjusts = c:applyAdjusts cs adjusts\n\ndata FoldState = FoldState {\n totalCost :: !Int64,\n balance :: !Int,\n adjustedPositions :: ![Int],\n adjusts :: !(S.Set Adjust),\n costs :: ![Cost]\n } deriving (Show)\n\ndata Cost = Cost {\n openCost :: !Int64,\n closeCost :: !Int64\n } deriving (Show)\n\ndata Adjust = Adjust {\n position :: !Int,\n cost :: !Int64\n } deriving (Show, Eq)\n\ninstance Ord Adjust where\n compare = comparing cost <> comparing position\n\ngetCost :: String -> Cost\ngetCost input = let [open, close] = map read (words input) in Cost open close"}, {"source_code": "import qualified Data.Set as Set\nimport Data.List\nimport Control.Arrow\n\ndata Cost = Cost Integer Integer deriving (Show, Eq, Ord)\nimpossible = Cost 1 0\ninstance Num Cost where\n Cost x1 y1 + Cost x2 y2 = Cost (x1 + x2) (y1 + y2)\n negate (Cost x1 y1) = Cost (negate x1) (negate y1)\n fromInteger x = Cost 0 x\n\nzipp ('?' : t) (c : cs) = (ob, cb) : zipp t cs where\n [ob, cb] = map (fromInteger . read) $ words c\nzipp ('(' : t) cs = (0, impossible) : zipp t cs\nzipp (')' : t) cs = (impossible, 0) : zipp t cs\nzipp [] _ = []\n\nhoho (h : t) = [h] : gogo t where\n gogo (a:b:c) = [a, b] : gogo c\n gogo _ = []\n\nswap (x, y) = (y, x)\n\ngo costs = (sum . map fst &&& mkString . sort . map snd) . snd . mapAccumL step Set.empty $ hoho (zip costs [0..]) where\n mkString = go 0 where\n len = length costs\n go i _ | i == len = []\n go i (j : js) | i == j = '(' : go (i + 1) js\n go i js = ')' : go (i + 1) js\n step m cis = swap . Set.deleteFindMin . Set.union m $ Set.fromList cis\n\nsolve (inp : costs) = case res of\n res | res < 0 -> error \"too good to be true\"\n Cost 0 x -> unlines $ [show x, best]\n _ -> \"-1\"\n where\n z = zipp inp costs\n (min, best) = go (map (uncurry (-)) z)\n res = sum (map snd z) + min\n\nmain=interact$solve.lines\n"}, {"source_code": "import Data.Set hiding(map)\nimport Data.List(mapAccumL)\nz('?':t)(c:d)=c:z t d\nz('(':t)d=(0,9^13):z t d\nz(')':t)d=(9^13,0):z t d\nz[]_=[]\ng(a:b:c)=[a,b]:g c\ng _=[]\nh(a:b)=[a]:g b\nb q|q='('|1>0=')'\nm l p=map(b.(`member`fromList p))[0..l-1]\nw(x,y)=(y,x)\nt[a,b]=(a,b)\np m=w.deleteFindMin.union m.fromList\nsolve(a:b)|r<9^12=unlines[show r,m(length a)i]|1>0=\"-1\"where\n (x,y)=unzip.z a.map(t.map read.words)$b \n (c,i)=unzip.snd.mapAccumL p empty.h.(`zip`[0..])$zipWith(-)x y\n r=sum$y++c\nmain=interact$solve.lines\n"}], "negative_code": [{"source_code": "-- import Debug.Trace\nimport qualified Data.Set as S\nimport Data.Int\nimport Data.List\nimport Control.Monad\nmain = do\n expr <- getLine\n costs <- map (map read . words) . lines <$> getContents\n case go costs expr [] S.empty 0 0 0 of\n Nothing -> putStrLn \"-1\"\n Just (cost,adjs) -> -- traceShowM adjs >>\n print cost >> putStrLn (adjust adjs expr 0)\ngo :: [[Int64]] -> String -> [Int] -> S.Set (Int64,Int) -> Int64 -> Int -> Int\n -> Maybe (Int64,[Int])\ngo cs bs adjs s a d i | d < 0 = case S.minView s of\n Nothing -> Nothing\n Just ((c,ai),s') -> ((go cs bs (ai:adjs) s' $! a+c) $! d+2) $ i\ngo cs@ ~([co,cc]:cs') (b:bs) adjs s a d i = case b of\n '(' -> (go cs bs adjs s a $! d+1) $! i+1\n ')' -> (go cs bs adjs s a $! d-1) $! i+1\n '?' -> (((go cs' bs adjs $! S.insert (co-cc,i) s) $! a+cc) $! d-1) $! i+1\ngo [] [] adjs _ a _ _ = Just (a,sort adjs)\n-- go cs bs adjs s a d i = traceShow (cs,bs,adjs,s,a,d,i) $ error \"NEP\"\nadjust as ('?':cs) i | not (null as) && i == head as\n = '(' : (adjust (tail as) cs $! i+1)\n | otherwise = ')' : (adjust as cs $! i+1)\nadjust as (c:cs) i = c : (adjust as cs $! i+1)\nadjust [] \"\" _ = \"\"\n-- adjust as cs i = traceShow (as,cs,i) $ error \"NEP\"\n"}, {"source_code": "-- import Debug.Trace\nimport qualified Data.Set as S\nimport Data.List\nimport Control.Monad\nmain = do\n expr <- getLine\n costs <- map (map read . words) . lines <$> getContents\n case go costs expr [] S.empty 0 0 0 of\n Nothing -> putStrLn \"-1\"\n Just (cost,adjs) -> -- traceShowM adjs >>\n print cost >> putStrLn (adjust adjs expr 0)\ngo :: [[Int]] -> String -> [Int] -> S.Set (Int,Int) -> Int -> Int -> Int\n -> Maybe (Int,[Int])\ngo cs bs adjs s a d i | d < 0 = case S.minView s of\n Nothing -> Nothing\n Just ((c,ai),s') -> ((go cs bs (ai:adjs) s' $! a+c) $! d+2) $ i\ngo cs@ ~([co,cc]:cs') (b:bs) adjs s a d i = case b of\n '(' -> (go cs bs adjs s a $! d+1) $! i+1\n ')' -> (go cs bs adjs s a $! d-1) $! i+1\n '?' -> (((go cs' bs adjs $! S.insert (co-cc,i) s) $! a+cc) $! d-1) $! i+1\ngo [] [] adjs _ a _ _ = Just (a,sort adjs)\n-- go cs bs adjs s a d i = traceShow (cs,bs,adjs,s,a,d,i) $ error \"NEP\"\nadjust as ('?':cs) i | not (null as) && i == head as\n = '(' : (adjust (tail as) cs $! i+1)\n | otherwise = ')' : (adjust as cs $! i+1)\nadjust as (c:cs) i = c : (adjust as cs $! i+1)\nadjust [] \"\" _ = \"\"\n-- adjust as cs i = traceShow (as,cs,i) $ error \"NEP\"\n"}, {"source_code": "import qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap,(!))\nimport Data.Ord (comparing)\nimport Data.List (sortBy)\nimport Data.Foldable (sum)\nimport Data.Traversable (mapM)\nimport Control.Monad (guard)\nimport Prelude hiding (sum,mapM)\n\n--import Debug.Trace\n--tr x = traceShow x x\ntr = id\ntraceShow = curry snd\n\nmain :: IO ()\nmain = do\n str <- getLine\n let seq = IM.fromList (zip [0..] str)\n unknown <- mapM (const readPair) (IM.filter (== '?') seq)\n let s = tr $ solve seq unknown\n case s of\n Nothing -> print (-1)\n Just s -> do\n let cost = sum $ IM.intersectionWith f s unknown\n f '(' (o,_) = o\n f ')' (_,c) = c\n print cost\n putStrLn $ IM.elems s\n\nsolve :: IntMap Char -> IntMap (Int,Int) -> Maybe (IntMap Char)\nsolve seq unknown = do\n let len = IM.size seq\n startOpen = IM.size (IM.filter (== '(') seq)\n startClose = IM.size (IM.filter (== ')') seq)\n target = len `div` 2\n needOpen = target - startOpen\n needClose = target - startClose\n guard (needOpen >= 0)\n guard (needClose >= 0)\n let first = IM.fromList $\n flip zip (replicate needOpen '(' ++ replicate needClose ')') $\n map fst $ sortBy (comparing firstCost) (IM.assocs unknown)\n firstCost (i,(co,cc)) = (co-cc,i)\n let closesLeft = S.empty\n opensRight = S.fromList $ map toOR $ IM.keys $ IM.filter (== '(') first\n toOR i = (c-o,-i) where (o,c) = unknown ! i\n let go cl or s i l\n | traceShow (IM.elems s,i,l,map snd (S.elems cl), map snd (S.elems or)) False = undefined\n | i == len = return s\n | l' >= 0 = go cl' or' s (i+1) l'\n | otherwise = exchange cl' or' s (i+1) l'\n where\n l' = l + if s ! i == '(' then 1 else -1\n (e,~(o,c)) = case IM.lookup i unknown of\n Nothing -> ('?', undefined)\n Just v -> (s ! i,v)\n cl' | e == ')' = S.insert (o-c,i) cl\n | otherwise = cl\n or' | e == '(' = S.delete (c-o,-i) or\n | otherwise = or\n exchange cl or s i lv = do\n ((_,l),cl') <- guard (not $ S.null cl) >> return (S.deleteFindMin cl)\n ((_,_r),or') <- guard (not $ S.null or) >> return (S.deleteFindMin or)\n traceShow (l,_r) $ go cl' or' (IM.insert l '(' $ IM.insert (-_r) ')' s) i (lv+2)\n go closesLeft opensRight (IM.union first seq) 0 0\n\nreadPair :: IO (Int,Int)\nreadPair = do\n [a,b] <- fmap words getLine\n return (read a,read b)\n"}, {"source_code": "import qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.IntMap as IM\nimport Data.IntMap (IntMap,(!))\nimport Data.Ord (comparing)\nimport Data.List (sortBy)\nimport Data.Foldable (sum)\nimport Data.Traversable (mapM)\nimport Control.Monad (guard)\nimport Prelude hiding (sum,mapM)\n\n-- import Debug.Trace\n-- tr x = traceShow x x\ntr = id\n\nmain :: IO ()\nmain = do\n str <- getLine\n let seq = IM.fromList (zip [0..] str)\n unknown <- mapM (const readPair) (IM.filter (== '?') seq)\n let s = tr $ solve seq unknown\n case s of\n Nothing -> print (-1)\n Just s -> do\n let cost = sum $ IM.intersectionWith f s unknown\n f '(' (o,_) = o\n f ')' (_,c) = c\n print cost\n putStrLn $ IM.elems s\n\nsolve :: IntMap Char -> IntMap (Int,Int) -> Maybe (IntMap Char)\nsolve seq unknown = do\n let len = IM.size seq\n startOpen = IM.size (IM.filter (== '(') seq)\n startClose = IM.size (IM.filter (== ')') seq)\n target = len `div` 2\n needOpen = target - startOpen\n needClose = target - startClose\n guard (needOpen >= 0)\n guard (needClose >= 0)\n let first = tr $ IM.fromList $\n flip zip (replicate needOpen '(' ++ replicate needClose ')') $\n map fst $ sortBy (comparing firstCost) (IM.assocs unknown)\n firstCost (i,(co,cc)) = (co-cc,i)\n let closesLeft = S.empty\n opensRight = S.fromList $ map toOR $ IM.keys $ IM.filter (== '(') first\n toOR i = (c-o,-i) where (o,c) = unknown ! i\n let go cl or s i l\n | i == len = return s\n | l' >= 0 = go cl' or' s (i+1) l'\n | otherwise = exchange cl' or' s (i+1) l'\n where\n l' = l + if s ! i == '(' then 1 else -1\n (e,~(o,c)) = case IM.lookup i unknown of\n Nothing -> ('?', undefined)\n Just v -> (s ! i,v)\n cl' | e == '(' = S.insert (o-c,i) cl\n | otherwise = cl\n or' | e == '(' = S.delete (c-o,-i) or\n | otherwise = or\n exchange cl or s i l = do\n ((_,l),cl') <- guard (not $ S.null cl) >> return (S.deleteFindMin cl)\n ((_,_r),or') <- guard (not $ S.null or) >> return (S.deleteFindMin or)\n go cl' or' (IM.insert l '(' $ IM.insert (-_r) ')' s) i (l+2)\n go closesLeft opensRight (IM.union first seq) 0 0\n\nreadPair :: IO (Int,Int)\nreadPair = do\n [a,b] <- fmap words getLine\n return (read a,read b)\n"}, {"source_code": "module Main where\n\nimport qualified Data.Set as S\nimport Data.Int (Int64)\nimport Data.List\nimport Data.Ord\nimport Data.Functor ((<&>))\n\nmain :: IO ()\nmain = do\n -- let expr = \"(??)\"\n -- let costs = [\"1 2\", \"3 6\"]\n expr <- getLine\n costs <- lines <$> getContents\n case solve expr costs of\n Nothing -> print (-1)\n Just (totalCost, resultExpr) -> print totalCost >> putStrLn resultExpr\n\nsolve :: String -> [String] -> Maybe (Int64, String)\nsolve expr inputs = findAdjusts indexedExpr (initialState inputs) <&> fmap (applyAdjusts indexedExpr)\n where\n indexedExpr = zip [1..] expr\n\ninitialState :: [String] -> FoldState\ninitialState costInputs = FoldState {\n totalCost = 0,\n balance = 0,\n adjustedPositions = [],\n adjusts = S.empty,\n costs = map getCost costInputs\n }\n\nfindAdjusts :: [(Int, Char)] -> FoldState -> Maybe (Int64, [Int])\nfindAdjusts [] state = if balance state == 0 then Just (totalCost state, adjustedPositions state) else Nothing\nfindAdjusts ((_, '('):expr) state = findAdjusts expr $ addBalance state 1\nfindAdjusts ((_, ')'):expr) state = findAdjusts expr =<< relax (addBalance state (-1))\nfindAdjusts ((p, _):expr) state = findAdjusts expr =<< relax (replaceChar state p)\n\naddBalance :: FoldState -> Int -> FoldState\naddBalance state@FoldState{ balance = b } db = state { balance = b + db }\n\nrelax :: FoldState -> Maybe FoldState\nrelax state | b >= 0 = Just state\n | otherwise = S.minView as <&> \\(Adjust p dc, nas) -> state { balance = b + 2\n , totalCost = t + dc\n , adjusts = nas\n , adjustedPositions = p:aps\n }\n where\n FoldState t b aps as _ = state\n\nreplaceChar :: FoldState -> Int -> FoldState\nreplaceChar state pos = state { balance = b - 1\n , totalCost = t + closeCost c\n , adjusts = S.insert (Adjust pos $ openCost c - closeCost c) as\n , costs = cs\n }\n where\n FoldState t b _ as (c:cs) = state\n\napplyAdjusts :: [(Int, Char)] -> [Int] -> String\napplyAdjusts [] _ = []\napplyAdjusts ((i, '?'):cs) (a:as) | i == a = '(':applyAdjusts cs as\napplyAdjusts ((_, '?'):cs) adjusts = ')':applyAdjusts cs adjusts\napplyAdjusts ((_, c):cs) adjusts = c:applyAdjusts cs adjusts\n\ndata FoldState = FoldState {\n totalCost :: Int64,\n balance :: Int,\n adjustedPositions :: [Int],\n adjusts :: S.Set Adjust,\n costs :: [Cost]\n } deriving (Show)\n\ndata Cost = Cost {\n openCost :: Int64,\n closeCost :: Int64\n } deriving (Show)\n\ndata Adjust = Adjust {\n position :: Int,\n cost :: Int64\n } deriving (Show)\n\ninstance Eq Adjust where\n Adjust _ c1 == Adjust _ c2 = c1 == c2\n\ninstance Ord Adjust where\n Adjust _ c1 <= Adjust _ c2 = c1 <= c2\n\ngetCost :: String -> Cost\ngetCost input = let [open, close] = map read (words input) in Cost open close"}, {"source_code": "module Main where\n\nimport qualified Data.Set as S\nimport Data.Int (Int64)\nimport Data.List\nimport Data.Ord\nimport Data.Functor ((<&>))\n\nmain :: IO ()\nmain = do\n expr <- getLine\n costs <- lines <$> getContents\n case solve expr costs of\n Nothing -> print (-1)\n Just (totalCost, resultExpr) -> print totalCost >> putStrLn resultExpr\n\nsolve :: String -> [String] -> Maybe (Int64, String)\nsolve expr inputs = findAdjusts indexedExpr (initialState inputs) <&> fmap (applyAdjusts indexedExpr . sort)\n where\n indexedExpr = zip [1..] expr\n\ninitialState :: [String] -> FoldState\ninitialState costInputs = FoldState {\n totalCost = 0,\n balance = 0,\n adjustedPositions = [],\n adjusts = S.empty,\n costs = map getCost costInputs\n }\n\nfindAdjusts :: [(Int, Char)] -> FoldState -> Maybe (Int64, [Int])\nfindAdjusts [] state = if balance state == 0 then Just (totalCost state, adjustedPositions state) else Nothing\nfindAdjusts ((_, '('):expr) state = findAdjusts expr $ addBalance state 1\nfindAdjusts ((_, ')'):expr) state = findAdjusts expr =<< relax (addBalance state (-1))\nfindAdjusts ((p, _):expr) state = findAdjusts expr =<< relax (replaceChar state p)\n\naddBalance :: FoldState -> Int -> FoldState\naddBalance state@FoldState{ balance = b } db = state { balance = b + db }\n\nrelax :: FoldState -> Maybe FoldState\nrelax state | b >= 0 = Just state\n | otherwise = S.minView as <&> \\(Adjust p dc, nas) -> state { balance = b + 2\n , totalCost = t + dc\n , adjusts = nas\n , adjustedPositions = p:aps\n }\n where\n FoldState t b aps as _ = state\n\nreplaceChar :: FoldState -> Int -> FoldState\nreplaceChar state pos = state { balance = b - 1\n , totalCost = t + closeCost c\n , adjusts = S.insert (Adjust pos $ openCost c - closeCost c) as\n , costs = cs\n }\n where\n FoldState t b _ as (c:cs) = state\n\napplyAdjusts :: [(Int, Char)] -> [Int] -> String\napplyAdjusts [] _ = []\napplyAdjusts ((i, '?'):cs) (a:as) | i == a = '(':applyAdjusts cs as\napplyAdjusts ((_, '?'):cs) adjusts = ')':applyAdjusts cs adjusts\napplyAdjusts ((_, c):cs) adjusts = c:applyAdjusts cs adjusts\n\ndata FoldState = FoldState {\n totalCost :: Int64,\n balance :: Int,\n adjustedPositions :: [Int],\n adjusts :: S.Set Adjust,\n costs :: [Cost]\n } deriving (Show)\n\ndata Cost = Cost {\n openCost :: Int64,\n closeCost :: Int64\n } deriving (Show)\n\ndata Adjust = Adjust {\n position :: Int,\n cost :: Int64\n } deriving (Show)\n\ninstance Eq Adjust where\n Adjust _ c1 == Adjust _ c2 = c1 == c2\n\ninstance Ord Adjust where\n Adjust _ c1 <= Adjust _ c2 = c1 <= c2\n\ngetCost :: String -> Cost\ngetCost input = let [open, close] = map read (words input) in Cost open close"}, {"source_code": "import Data.Set hiding(map)\nimport Data.List(mapAccumL)\nz('?':t)(c:d)=c:z t d\nz('(':t)d=(0,9^13):z t d\nz(')':t)d=(9^13,0):z t d\nz[]_=[]\ng(a:b:c)=[a,b]:g c\ng _=[]\nh(a:b)=[a]:g b\nb q|q='('|1>0=')'\nm l p=map(b.(`member`fromList p))[0..l-1]\nw(x,y)=(y,x)\nt[a,b]=(a,b)\np m=w.deleteFindMin.union m.fromList\nsolve(a:b)|r<9^12=unlines[show r,m(length b)i]|1>0=\"-1\"where\n (x,y)=unzip.z a.map(t.map read.words)$b \n (c,i)=unzip.snd.mapAccumL p empty.h.(`zip`[0..])$zipWith(-)x y\n r=sum$y++c\nmain=interact$solve.lines\n"}, {"source_code": "import qualified Data.Map as Map\nimport Data.List\nimport Control.Arrow\n\ndata Cost = Cost Integer Integer deriving (Show, Eq, Ord)\nimpossible = Cost 1 0\ninstance Num Cost where\n Cost x1 y1 + Cost x2 y2 = Cost (x1 + x2) (y1 + y2)\n negate (Cost x1 y1) = Cost (negate x1) (negate y1)\n fromInteger x = Cost 0 x\n\nzipp ('?' : t) (c : cs) = (ob, cb) : zipp t cs where\n [ob, cb] = map (fromInteger . read) $ words c\nzipp ('(' : t) cs = (0, impossible) : zipp t cs\nzipp (')' : t) cs = (impossible, 0) : zipp t cs\nzipp [] _ = []\n\nhoho (h : t) = [h] : gogo t where\n gogo (a:b:c) = [a, b] : gogo c\n gogo _ = []\n\nswap (x, y) = (y, x)\n\ngo costs = (sum . map fst &&& mkString . sort . map snd) . snd . mapAccumL step Map.empty $ hoho (zip costs [0..]) where\n mkString = go 0 where\n len = length costs\n go i js | i == len = []\n go i (j : js) | i == j = '(' : go (i + 1) js\n go i js = ')' : go (i + 1) js\n step m cis = swap (Map.deleteFindMin $ Map.union (Map.fromList cis) m)\n\nsolve (inp: costs) = case res of \n Cost 0 x -> unlines $ [show x, best]\n Cost i _ | i > 0 -> \"-1\"\n | otherwise -> error \"too good to be true\"\n where\n z = zipp inp costs\n (min, best) = go (map (uncurry (-)) z)\n res = sum (map snd z) + min\n\nmain=interact$solve.lines\n"}], "src_uid": "970cd8ce0cf7214b7f2be337990557c9"} {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\ntype Graph = Array Int [Int]\ntreeDFS :: Graph -> Int -> [(Int, Int)]\ntreeDFS arr = let\n go par curr = foldr (.) ((curr, par) :)\n [go curr next | next <- arr ! curr, next /= par]\n in \\root -> go minBound root []\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n rawEdges <- readInts\n aLi <- readInts\n let\n edges = do\n (i, v) <- zip [2..n] rawEdges\n [(i, v), (v, i)]\n adj :: Graph\n adj = accumArray (flip (:)) [] (1, n) edges\n pars :: UArray Int Int\n pars = array (1, n) $ treeDFS adj 1\n depths :: Array Int Int\n depths = listArray (1, n) $ 0 : [1 + depths ! (pars ! i) | i <- [2..n]]\n maxDepth = maximum $ elems depths\n a :: UArray Int Int64\n a = listArray (2, n) $ map fromIntegral aLi\n layerMin :: UArray Int Int64\n layerMin = accumArray min maxBound (1, maxDepth)\n [(depths ! i, a ! i) | i <- [2..n]]\n layerMax :: UArray Int Int64\n layerMax = accumArray max minBound (1, maxDepth)\n [(depths ! i, a ! i) | i <- [2..n]]\n layerOccs :: Array Int [Int]\n layerOccs = accumArray (flip (:)) [] (1, maxDepth) [(depths ! i, i) | i <- [2..n]]\n cscore :: Array Int Int64\n cscore = listArray (1, n) $ map cscoreFun [1..n]\n cscoreFun :: Int -> Int64\n cscoreFun i = foldl' max 0 [score v | v <- adj ! i, v /= pars ! i]\n layerAugMin :: Array Int Int64\n layerAugMin = listArray (1, maxDepth) $ do\n j <- [1..maxDepth]\n pure $ foldl' min maxBound [a ! i - cscore ! i | i <- layerOccs ! j]\n layerAugMax :: Array Int Int64\n layerAugMax = listArray (1, maxDepth) $ do\n j <- [1..maxDepth]\n pure $ foldl' max minBound [a ! i + cscore ! i | i <- layerOccs ! j]\n score :: Int -> Int64\n score i = let\n layer = depths ! i\n o1 = layerMax ! layer - a ! i + cscore ! i\n o2 = a ! i - layerMin ! layer + cscore ! i\n o3 = layerAugMax ! layer - a ! i\n o4 = a ! i - layerAugMin ! layer\n in maximum [o1, o2, o3, o4]\n {-\n lift $ print layerAugMax\n lift $ print [(i, score i) | i <- [2..n]]\n lift $ print a\n -}\n putInts [cscore ! 1]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int64] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n let prepend xs x = x : xs\n edges <- accumArray prepend [] (1, n) . concat . map (\\(i, v) -> [(i, v), (v, i)]) . zip [2..] <$> getInts\n values <- array (1, n) . ((1, 0):) . zip [2..] . map fromIntegral <$> getInts\n let\n dfs :: [(Int, [Int])] -> Int -> Int -> [(Int, [Int])]\n dfs adjs f u =\n foldl' (\\as v -> dfs as u v) ((u, vs) : adjs) vs\n where vs = filter (/= f) $ edges ! u\n childs = accumArray (\\_ vs -> vs) [] (1, n) $ dfs [] 0 1\n getChilds u = childs ! u\n getValue u = values ! u\n getMinMax :: [Int64] -> (Int64, Int64)\n getMinMax list = case list of\n [] -> error \"\"\n [x] -> (x, x)\n (x : xs) -> let (minValue, maxValue) = getMinMax xs in (min x minValue, max x maxValue)\n calc :: [Int] -> [(Int, Int64)]\n calc us\n | null us = error \"\"\n | null (childs ! head us) = map (\\u -> (u, 0)) us\n | otherwise = func (noSwapOptimals, sort leftOptimals, sort rightOptimals)\n where\n vs = sort $ concat $ map getChilds us\n nexts = calc vs\n nextsMap = IM.fromAscList nexts\n (low, high) = getMinMax $ map getValue vs\n calcNoSwapOptimal v = let val = getValue v in max (val - low) (high - val) + nextsMap IM.! v\n noSwapOptimals = zip us $ map (\\u -> maximum $ map calcNoSwapOptimal $ getChilds u) us\n parents = sort $ map (\\u -> let (l, r) = getMinMax $ map getValue $ getChilds u in ((l + r) `quot` 2, l, r, u)) us\n children = sort $ map (\\(v, opt) -> (getValue v, opt)) nexts\n accLeft _ [] _ = []\n accLeft maxPart allPs@((m, _, r, u) : ps) allCs\n | null allCs || m < val = (u, maxPart + r) : accLeft maxPart ps allCs\n | otherwise = accLeft (max maxPart (opt - val)) allPs cs\n where\n ((val, opt) : cs) = allCs\n leftOptimals = accLeft (-10^17) parents children\n accRight _ [] _ = []\n accRight maxPart allPs@((m, l, _, u) : ps) allCs\n | null allCs || m > val = (u, maxPart - l) : accRight maxPart ps allCs\n | otherwise = accRight (max maxPart (opt + val)) allPs cs\n where\n ((val, opt) : cs) = allCs\n rightOptimals = accRight (-10^17) (reverse parents) (reverse children)\n func ([], [], []) = []\n func ((i, x) : xs, (_, y) : ys, (_, z) : zs) = (i, max (max x y) z) : func (xs, ys, zs)\n result = snd $ head $ calc [1]\n C.putStrLn $ C.pack $ show result\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\ntype Graph = Array Int [Int]\ntreeDFS :: Graph -> Int -> [(Int, Int)]\ntreeDFS arr = let\n go par curr = foldr (.) ((curr, par) :)\n [go curr next | next <- arr ! curr, next /= par]\n in \\root -> go minBound root []\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n rawEdges <- readInts\n aLi <- readInts\n let\n edges = do\n (i, v) <- zip [2..n] rawEdges\n [(i, v), (v, i)]\n adj :: Graph\n adj = accumArray (flip (:)) [] (1, n) edges\n pars :: UArray Int Int\n pars = array (1, n) $ treeDFS adj 1\n depths :: Array Int Int\n depths = listArray (1, n) $ 0 : [1 + depths ! (pars ! i) | i <- [2..n]]\n maxDepth = maximum $ elems depths\n a :: UArray Int Int64\n a = listArray (2, n) $ map fromIntegral aLi\n layerMin :: UArray Int Int64\n layerMin = accumArray min maxBound (1, maxDepth)\n [(depths ! i, a ! i) | i <- [2..n]]\n layerMax :: UArray Int Int64\n layerMax = accumArray max minBound (1, maxDepth)\n [(depths ! i, a ! i) | i <- [2..n]]\n layerOccs :: Array Int [Int]\n layerOccs = accumArray (flip (:)) [] (1, maxDepth) [(depths ! i, i) | i <- [2..n]]\n cscore :: Array Int Int64\n cscore = listArray (1, n) $ map cscoreFun [1..n]\n cscoreFun :: Int -> Int64\n cscoreFun i = foldl' max 0 [score v | v <- adj ! i, v /= pars ! i]\n layerAugMin :: Array Int Int64\n layerAugMin = listArray (1, n) $ do\n j <- [1..maxDepth]\n pure $ foldl' min maxBound [a ! i - cscore ! i | i <- layerOccs ! j]\n layerAugMax :: Array Int Int64\n layerAugMax = listArray (1, n) $ do\n j <- [1..maxDepth]\n pure $ foldl' max minBound [a ! i - cscore ! i | i <- layerOccs ! j]\n score :: Int -> Int64\n score i = let\n layer = depths ! i\n o1 = layerMax ! layer - a ! i + cscore ! i\n o2 = a ! i - layerMin ! layer + cscore ! i\n o3 = layerAugMax ! layer - a ! i\n o4 = a ! i - layerAugMin ! layer\n in maximum [o1, o2, o3, o4]\n putInts [cscore ! 1]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int64] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.int64Dec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "src_uid": "1ff25abd9d49de5e5ce3f7338ddef18c"} {"source_code": "import Control.Monad\r\nreadInts = fmap (map read.words) getLine :: IO [Int]\r\n\r\nprintResult = do\r\n [a,b,c] <- readInts\r\n let \r\n n = min a b\r\n m = max a b\r\n l = m - n\r\n r = if c > l then c - l else c + l \r\n d = if c > 2 * l then -1 else r\r\n e = if m > 2 * l then -1 else d\r\n print e\r\n \r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "opposite :: Int -> Int -> Int -> Int\nopposite a b c =\n let full = 2 * abs (a - b) in\n if any (> full) [a, b, c] then\n -1\n else\n let r = c + full `div` 2 in\n if r <= full then r else r - full\n \nloop :: Int -> IO()\nloop 0 = return ()\nloop n = do\n line <- getLine \n let [a, b, c] = map read (words line) :: [Int]\n print (opposite a b c)\n loop $ n - 1\n\nmain :: IO()\nmain = do\n input <- getLine\n let n = read input :: Int\n loop n\n"}, {"source_code": "import Control.Monad\r\n\r\n\r\nrestoreThirdOppositeIndex :: Integer -> Integer -> Integer -> Integer\r\nrestoreThirdOppositeIndex a b c = result\r\n where result = if input_is_valid then potential_result else -1\r\n input_is_valid = maximum [a, b, c] < circle_size\r\n potential_result = (c - circle_half) `mod` circle_size\r\n circle_size = 2 * circle_half\r\n circle_half = abs (a - b)\r\n\r\n\r\nprocess_test :: String -> String\r\nprocess_test input = show result\r\n where [a, b, c] = map read (words input)\r\n raw_result = restoreThirdOppositeIndex (a-1) (b-1) (c-1)\r\n result = if raw_result >= 0 then raw_result + 1 else raw_result\r\n\r\n\r\nmain :: IO()\r\nmain = do\r\n tests_n_input <- getLine\r\n let tests_n = read tests_n_input\r\n tests_inputs <- replicateM tests_n getLine\r\n let outputs = map process_test tests_inputs\r\n mapM_ putStrLn outputs\r\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2021\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > tmp.txt && diff -sdu -- output.txt tmp.txt && cat -- tmp.txt)\n\nimport Prelude\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n tcs <- replicateM t (map read . words <$> getLine) :: IO [[Integer]]\n\n (putStr . unlines . map (show . solveC)) tcs\n\nsolveC [a,b,c] | (a < b) = solve (a,b,c)\n | (a > b) = solve (b,a,c)\n | otherwise = error \"distinct a,b expected\"\nsolveC _\n = error \"three integers expected\"\n\nsolve (a,b,c) | (a >= m) = -1\n | (b < m) = -1\n | (a < 1) = -1\n | (b > x) = -1\n | (c < 1) = -1\n | (c > x) = -1\n | (c < m) = c + d\n | otherwise = c - d\n where\n d = abs (a - b)\n m = 1 + d\n x = 2 * d\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\n-- 1 2 3 4 5 6\n-- 7 1 2 3 4 5 1\n\ncalc :: Int -> Int -> Int -> Int\ncalc a b c =\n let half = abs (a-b)\n count = 2 * half\n in\n if (count < a) || (count < b) || (count < c) then -1\n else (((c-1)+half) `mod` count)+1\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b,c] = map read $ words line :: [Int]\n putStrLn $ show $ calc a b c\n"}, {"source_code": "main = do\n t <- read <$> getLine :: IO Int\n mapM_ main' [1..t]\n\nmain':: Int -> IO ()\nmain' _ = do\n [a, b, c] <- map read . words <$> getLine :: IO [Int]\n print $ solve a b c\n\nsolve :: Int -> Int -> Int -> Int\nsolve a b c\n | n < a || n < b || n < c = -1\n | otherwise = (c - 1 + half) `mod` n + 1\n where\n half = abs $ a - b\n n = 2 * half"}, {"source_code": "module Main where\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = (Int, Int, Int)\r\ntype OutType = Maybe Int\r\n\r\ninpLines :: Int\r\ninpLines = 1\r\n\r\nsolve :: InType -> OutType\r\nsolve (a, b, c) = if maximum [a,b,c] > n\r\n then Nothing\r\n else Just d\r\n where n = 2 * abs (b - a)\r\n d' = c + n `div` 2\r\n d = if d' > n\r\n then d' - n\r\n else d'\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = case toArr s of\r\n [a,b,c] -> (a,b,c)\r\n _ -> error \"unexpected input\"\r\nreceive _ = error \"unexpected input\"\r\n\r\nmain :: IO ()\r\nmain = interact $\r\n unlines . map (showb . solve . receive) . chunksOf inpLines . tail . lines\r\n where showb Nothing = \"-1\"\r\n showb (Just x) = show x\r\n\r\n"}, {"source_code": "import Control.Monad\r\n\r\nmain:: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t routine\r\n\r\nroutine :: IO ()\r\nroutine = do\r\n [a,b,c] <- (map read.words) <$> getLine\r\n print $ solve a b c\r\n\r\nsolve :: Int -> Int -> Int -> Int\r\nsolve a b c\r\n | any (\\x -> x>size*2) [a,b,c] = -1\r\n | otherwise= if c > size then c-size else c+size\r\n where\r\n size = abs (a-b)\r\n"}, {"source_code": "module Main where\r\n\r\nimport Control.Monad (replicateM_)\r\n\r\nmain = do\r\n t <- read <$> getLine\r\n replicateM_\r\n t\r\n (getLine >>= print . (\\[a, b, c] -> solve a b c) . map read . words)\r\n\r\nsolve :: Int -> Int -> Int -> Int\r\nsolve a b c = if c <= 2 * hSize && (max a b <=2* hSize)\r\n then if c + hSize > 2 * hSize\r\n then (c + hSize) `rem` (2 * hSize)\r\n else c + hSize\r\n else -1\r\n where\r\n hSize = abs (b - a)\r\n{-\r\n>>>solve 6 2 4\r\n8\r\n>>>solve 2 5 4\r\n1\r\n\r\n1\r\n\r\n-1\r\n\r\n-1\r\n-}\r\n"}], "negative_code": [{"source_code": "opposite :: Int -> Int -> Int -> Int\nopposite a b c =\n let full = 2 * abs (a - b) in\n if any (> full) [a, b] then\n -1\n else\n let r = c + full `div` 2 in\n if r <= full then r else r - full\n \nloop :: Int -> IO()\nloop 0 = return ()\nloop n = do\n line <- getLine \n let [a, b, c] = map read (words line) :: [Int]\n print (opposite a b c)\n loop $ n - 1\n\nmain :: IO()\nmain = do\n input <- getLine\n let n = read input :: Int\n loop n\n"}], "src_uid": "07597a8d08b59d4f8f82369bb5d74a49"} {"source_code": "main = do\n n <- fmap read getLine\n putStrLn $ unlines $ [unwords [show $ gao n i j | j <- [0 .. n - 1]] | i <- [0 .. n - 1]]\n where\n gao n i j\n | i > j = gao n j i\n | i == j = 0\n | j == pred n = check i i n\n | otherwise = check i j n\n check x y n =\n let\n\tt = (x + y) `mod` (n - 1)\n in\n\tif t == 0 then n - 1 else t\n", "positive_code": [{"source_code": "main = do\n\tline <- getLine\n\tputStrLn $ unlines $ [unwords [show $ gao n i j | j <- [0 .. n - 1]] | n <- [read line], i <- [0 .. n - 1]]\n\twhere gao n i j\n\t\t| i > j\t\t\t= gao n j i\n\t\t| i == j\t\t= 0\n\t\t| i + j < n\t\t= i + j\n\t\t| j == pred n\t= if i + i < n then i + i else i + i + 1 - n\n\t\t| otherwise\t\t= i + j + 1 - n\n"}], "negative_code": [{"source_code": "line :: Int -> Int -> [Int]\nline n x = [x..n - 1] ++ [0..x-1]\n\nget :: Int -> Int -> [[Int]]\nget n 1 = [line n 1]\nget n x = line n x : get n (x - 1)\n\nsolve :: Int -> [String]\nsolve n =\n let\n a = get n n\n in\n map (unwords . (map show)) a\n\n\nmain = do\n n <- fmap read getLine\n let\n s = solve n\n mapM_ putStrLn s\n"}], "src_uid": "f5f892203b62dae7eba86f59b13f5a38"} {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, x ] <- map read . words <$> getLine\n\ts <- abs . sum . map ( read :: String -> Int ) . words <$> getLine\n\tprint $ ( s + x - 1 ) `div` x\n"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n\tgetInt\n\tx <- getInt\n\ttotal <- (abs . sum . map read . words) <$> getLine\n--\tputStrLn $ \"total is \" ++ show total\n\tprint ((total + x - 1) `div` x)\n\n\n\n-- Input\ngetInt :: IO Int\ngetInt = read <$> nextToken\n\n\nnextToken :: IO String\nnextToken = nextToken' \"\"\n\nnextToken' :: String -> IO String\nnextToken' acc = do\n\tc <- getChar\n\tif (c == ' ' || c == '\\n') && (acc /= \"\")\n\t\tthen return $ reverse acc\n\telse\n\t\tnextToken' (c : acc)\n\n\n\n\n"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, x] <- map read . words <$> getLine\n xs <- map read . words <$> getLine\n\n let\n s = sum xs\n\n print $ if s > 0 then (s+x-1) `div` x else (-s+x-1) `div` x\n"}, {"source_code": "main = getContents >>= print . f . map read . tail . words\nf (x:y) = div ((abs $ sum y) + x - 1) x"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nmain = do\n (n,x) <- readIntPair\n cs <- readInts\n let y = abs $ sum cs\n print $ div (abs (sum cs) + x-1) x\n\n"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "import Control.Applicative\n\nparseLine = map read . words <$> getLine\n\nmain = do\n [_,x] <- parseLine :: IO [Int]\n xs <- parseLine\n let s = abs $ sum xs\n print $ \n if s == 0\n then 0\n else if s <= x\n then 1\n else s `div` x + fromEnum (mod s x /= 0)"}, {"source_code": "import Control.Applicative\n\nparseLine = map read . words <$> getLine\n\nmain = do\n [_,x] <- parseLine :: IO [Int]\n xs <- parseLine\n let s = abs $ sum xs\n print $ s `div` x + fromEnum (mod s x /= 0)"}, {"source_code": "\nmain :: IO ()\nmain = \n do \n input <- getContents\n putStrLn (show (solve (params input)))\n\nparams :: String -> (Int, Int, [Int])\nparams str = \n let \n toks = words str\n in\n (read (toks !! 0), read (toks !! 1), map read (drop 2 toks))\n\nsolve :: (Int, Int, [Int]) -> Int\nsolve (n, x, list) = \n let \n sum = abs $ foldl (+) 0 list\n in \n 1 + ((sum - 1) `div` x)\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> Int\nsolve [[_, x], xs] = (abs (sum xs) + x - 1) `div` x\nsolve _ = undefined\n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (m:cs) = s `div` m + fromEnum (s `mod` m /= 0)\n where s = abs (sum cs)\n"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "main = getContents >>= putStrLn . show . (\\(n:x:s) -> let mo = abs $ sum $ take n s in (if 0 == mod mo x then 0 else 1) + quot mo x) . map read . words"}, {"source_code": "fuck :: [Int] -> String\nfuck (n:x:s) = let \n li = take n s\n mo = abs $ sum li\n in if 0 == mod mo x then show $ quot mo x else show $ 1 + quot mo x \n\n\n\nmain :: IO ()\nmain = getContents >>= putStrLn . fuck . map read . words "}, {"source_code": "main = getContents >>= putStrLn . show . (\\(n:x:s) -> quot ((abs $ sum s) + x - 1) x) . map read . words"}, {"source_code": "main = do\n\ts <- getLine\n\tlet t = words s\n\tlet n = read $ head t :: Int\n\tlet x = read $ head $ tail t :: Int\n\tc <- getLine\n\tlet b = words c\n\tlet a = map read b :: [Int]\n\tlet z = sum a\n\tlet y = ( ( abs z ) + x - 1 ) `div` x\n\tputStrLn $ show y\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \nmain=do\t \n\t[n,x]<- map read.words <$> getLine:: IO [Int] \n\ts<- abs.sum.map read. words <$> getLine ::IO Int\n\tprint $ div s x + if (mod s x)>0 then 1 else 0"}, {"source_code": "main = do\n [n, x] <- getLine >>= return. map read. words\n getLine >>= print. (`div` x). (+ (x - 1)). abs. sum. map read. words"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "import System.IO\n\nmain = do\n input1 <- getLine \n input2 <- getLine \n \n let line1 = words input1\n let line2 = words input2\n \n let n = read $ head line1 :: Integer\n let x = read $ last line1 :: Integer \n \n let values = [ read x :: Integer | x <- line2 ]\n \n let s = abs $ sum values\n let ans = ceiling $ fromIntegral s / fromIntegral x\n \n print $ ans\n \n"}, {"source_code": "\nmain = interact $ show.calc.map read.words\n\ncalc :: [Integer] -> Integer\ncalc (_:x:xs) = ((abs $ sum xs)+x-1)`div`x\n\n"}, {"source_code": "\n\nmain = interact calc\n\ncalc :: String -> String\ncalc str = show $ ceiling $ s / x\n where x = (read $ head.(drop 1).words $ str)\n s = (abs $ sum $ map read ((drop 2).words $ str))\n\n\n"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "main = interact $ show . ans . map read . words\nans(_:x:xs) = div (abs(sum xs) + x - 1) x"}, {"source_code": "main=interact$show.f.map read.words\nf(_:x:xs)=(abs(sum xs)+x-1)`div`x\n"}, {"source_code": "main = interact$show.f.map read.words\nf (_:x:xs) = div (abs(sum xs) + x - 1) x"}], "negative_code": [{"source_code": "import Control.Applicative\nmain :: IO ()\nmain = do\n\tx <- getInt\n\tgetInt\n\ttotal <- (abs . sum . map read . words) <$> getLine\n\tprint ((total + x - 1) `div` x)\n\n\n\n-- Input\ngetInt :: IO Int\ngetInt = read <$> nextToken\n\n\nnextToken :: IO String\nnextToken = nextToken' \"\"\n\nnextToken' :: String -> IO String\nnextToken' acc = do\n\tc <- getChar\n\tif (c == ' ' || c == '\\n') && (acc /= \"\")\n\t\tthen return $ reverse acc\n\telse\n\t\tnextToken' (c : acc)\n\n\n\n\n"}, {"source_code": "import Control.Applicative\n\nparseLine = map read . words <$> getLine\n\nmain = do\n [_,x] <- parseLine :: IO [Int]\n xs <- parseLine\n let s = sum xs\n print $ \n if s == 0\n then 0\n else if abs s <= x\n then 1\n else abs s `div` x + 1 "}, {"source_code": "\nmain :: IO ()\nmain = \n do \n input <- getContents\n putStrLn (show (solve (params input)))\n\nparams :: String -> (Int, Int, [Int])\nparams str = \n let \n toks = words str\n in\n (read (toks !! 0), read (toks !! 1), map read (drop 2 toks))\n\nsolve :: (Int, Int, [Int]) -> Int\nsolve (n, x, list) = \n let \n sum = foldl (+) 0 list\n in \n 1 + ((sum - 1) `div` x)\n"}, {"source_code": "main = getContents >>= putStrLn . show . (\\(n:x:s) -> quot ((sum s) + x - 1) x) . map read . words"}, {"source_code": "\n\nmain = interact calc\n\ncalc :: String -> String\ncalc str = show $ abs $ (sum $ map read ((drop 2).words $ str))`div`(read $ head.(drop 1).words $ str)\n\n\n"}, {"source_code": "main = interact $ show . ans . map read . words\nans(_:x:xs) = abs $ div ((sum xs) + x - 1) x\n"}], "src_uid": "066906ee58af5163636dac9334619ea7"} {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM_ )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( unfoldr )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x !*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q) where helper = adjoint . fmap V1\r\n\r\n-- eigenvalues m = go [] m\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | isNaN ev = acc\r\n-- | otherwise = go (ev : acc) ma'\r\n-- where\r\n-- ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ zero) <$> ec\r\n-- ma' = ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec)\r\n\r\n\r\n{-\r\n\r\n>>> mt = V2 (V2 1 2) (V2 3 4)\r\n>>> ev = eigenvector mt\r\n>>> el = eigenvalue mt ev\r\n\r\n>>> ev\r\nV2 0.41597355791928425 0.9093767091321241\r\n\r\n>>> el\r\n5.372281323269014\r\n\r\n>>> el *!! identity :: M22 Double\r\nV2 (V2 5.372281323269014 0.0) (V2 0.0 5.372281323269014)\r\n\r\n>>> (mt - el *!! identity)\r\nV2 (V2 (-4.372281323269014) 2.0) (V2 3.0 (-1.3722813232690143))\r\n\r\n>>> luFinite (mt - el *!! identity)\r\n(V2 (V2 (-4.372281323269014) 0.0) (V2 3.0 0.0),V2 (V2 1.0 (-0.4574271077563381)) (V2 0.0 NaN))\r\n\r\n>>> luDetFinite (mt - el *!! identity)\r\nNaN\r\n\r\n>>> eigenvalues mt\r\n[-0.37228132326901475,5.372281323269014]\r\n\r\n>>> m3 = V3 (V3 1 2 3) (V3 4 5 6) (V3 7 8 9)\r\n\r\n>>> eigenvalues m3\r\n[-1.1168439698070434,16.116843969807043]\r\n\r\n>>> m4 = V4 (V4 1 2 3 4) (V4 5 6 7 8) (V4 9 10 11 12) (V4 13 14 15 16)\r\n\r\n>>> eigenvalues m4\r\n[-2.2093727122985376,36.20937271229855]\r\n\r\n>>> m5 = fromJust $ fromVector @5 (fromJust . fromVector @5 <$> (fromList <$> fromList [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]])) \r\n\r\n>>> m5\r\nV {toVector = [V {toVector = [1,2,3,4,5]},V {toVector = [6,7,8,9,10]},V {toVector = [11,12,13,14,15]},V {toVector = [16,17,18,19,20]},V {toVector = [21,22,23,24,25]}]}\r\n\r\n>>> eigenvalues m5\r\n[-3.64208073700242,68.6420807370024]\r\n\r\n>>> lx = V3 (V2 1 2) (V2 3 4) (V2 5 6)\r\n\r\n>>> eigenvalues (lx !*! adjoint lx)\r\n[0.264505087265819,90.73549491273418]\r\n\r\n-}\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [x, y] <- readChar8'\r\n case (x > y, x == y) of\r\n (True, _ ) -> print (x + y)\r\n (_ , True) -> print x\r\n _ -> print $ y - (y `mod` x) `div` 2\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[x, y] <- getInts 2\n pure $ putInts $ pure $ case divMod y x of\n (0, _) -> x + y\n (_, r) -> y - div r 2\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM_ )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( unfoldr )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x !*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q) where helper = adjoint . fmap V1\r\n\r\n-- eigenvalues m = go [] m\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | isNaN ev = acc\r\n-- | otherwise = go (ev : acc) ma'\r\n-- where\r\n-- ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ zero) <$> ec\r\n-- ma' = ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec)\r\n\r\n\r\n{-\r\n\r\n>>> mt = V2 (V2 1 2) (V2 3 4)\r\n>>> ev = eigenvector mt\r\n>>> el = eigenvalue mt ev\r\n\r\n>>> ev\r\nV2 0.41597355791928425 0.9093767091321241\r\n\r\n>>> el\r\n5.372281323269014\r\n\r\n>>> el *!! identity :: M22 Double\r\nV2 (V2 5.372281323269014 0.0) (V2 0.0 5.372281323269014)\r\n\r\n>>> (mt - el *!! identity)\r\nV2 (V2 (-4.372281323269014) 2.0) (V2 3.0 (-1.3722813232690143))\r\n\r\n>>> luFinite (mt - el *!! identity)\r\n(V2 (V2 (-4.372281323269014) 0.0) (V2 3.0 0.0),V2 (V2 1.0 (-0.4574271077563381)) (V2 0.0 NaN))\r\n\r\n>>> luDetFinite (mt - el *!! identity)\r\nNaN\r\n\r\n>>> eigenvalues mt\r\n[-0.37228132326901475,5.372281323269014]\r\n\r\n>>> m3 = V3 (V3 1 2 3) (V3 4 5 6) (V3 7 8 9)\r\n\r\n>>> eigenvalues m3\r\n[-1.1168439698070434,16.116843969807043]\r\n\r\n>>> m4 = V4 (V4 1 2 3 4) (V4 5 6 7 8) (V4 9 10 11 12) (V4 13 14 15 16)\r\n\r\n>>> eigenvalues m4\r\n[-2.2093727122985376,36.20937271229855]\r\n\r\n>>> m5 = fromJust $ fromVector @5 (fromJust . fromVector @5 <$> (fromList <$> fromList [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]])) \r\n\r\n>>> m5\r\nV {toVector = [V {toVector = [1,2,3,4,5]},V {toVector = [6,7,8,9,10]},V {toVector = [11,12,13,14,15]},V {toVector = [16,17,18,19,20]},V {toVector = [21,22,23,24,25]}]}\r\n\r\n>>> eigenvalues m5\r\n[-3.64208073700242,68.6420807370024]\r\n\r\n>>> lx = V3 (V2 1 2) (V2 3 4) (V2 5 6)\r\n\r\n>>> eigenvalues (lx !*! adjoint lx)\r\n[0.264505087265819,90.73549491273418]\r\n\r\n-}\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [x, y] <- readChar8'\r\n case (x > y, x == y) of\r\n (True, _ ) -> print (x + y)\r\n (_ , True) -> print x\r\n _ -> if even (x + y) then print $ (x + y) `div` 2 else print $ (x + y + if odd x then x else y) `div` 2\r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM_ )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( unfoldr )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x !*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q) where helper = adjoint . fmap V1\r\n\r\n-- eigenvalues m = go [] m\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | isNaN ev = acc\r\n-- | otherwise = go (ev : acc) ma'\r\n-- where\r\n-- ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ zero) <$> ec\r\n-- ma' = ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec)\r\n\r\n\r\n{-\r\n\r\n>>> mt = V2 (V2 1 2) (V2 3 4)\r\n>>> ev = eigenvector mt\r\n>>> el = eigenvalue mt ev\r\n\r\n>>> ev\r\nV2 0.41597355791928425 0.9093767091321241\r\n\r\n>>> el\r\n5.372281323269014\r\n\r\n>>> el *!! identity :: M22 Double\r\nV2 (V2 5.372281323269014 0.0) (V2 0.0 5.372281323269014)\r\n\r\n>>> (mt - el *!! identity)\r\nV2 (V2 (-4.372281323269014) 2.0) (V2 3.0 (-1.3722813232690143))\r\n\r\n>>> luFinite (mt - el *!! identity)\r\n(V2 (V2 (-4.372281323269014) 0.0) (V2 3.0 0.0),V2 (V2 1.0 (-0.4574271077563381)) (V2 0.0 NaN))\r\n\r\n>>> luDetFinite (mt - el *!! identity)\r\nNaN\r\n\r\n>>> eigenvalues mt\r\n[-0.37228132326901475,5.372281323269014]\r\n\r\n>>> m3 = V3 (V3 1 2 3) (V3 4 5 6) (V3 7 8 9)\r\n\r\n>>> eigenvalues m3\r\n[-1.1168439698070434,16.116843969807043]\r\n\r\n>>> m4 = V4 (V4 1 2 3 4) (V4 5 6 7 8) (V4 9 10 11 12) (V4 13 14 15 16)\r\n\r\n>>> eigenvalues m4\r\n[-2.2093727122985376,36.20937271229855]\r\n\r\n>>> m5 = fromJust $ fromVector @5 (fromJust . fromVector @5 <$> (fromList <$> fromList [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]])) \r\n\r\n>>> m5\r\nV {toVector = [V {toVector = [1,2,3,4,5]},V {toVector = [6,7,8,9,10]},V {toVector = [11,12,13,14,15]},V {toVector = [16,17,18,19,20]},V {toVector = [21,22,23,24,25]}]}\r\n\r\n>>> eigenvalues m5\r\n[-3.64208073700242,68.6420807370024]\r\n\r\n>>> lx = V3 (V2 1 2) (V2 3 4) (V2 5 6)\r\n\r\n>>> eigenvalues (lx !*! adjoint lx)\r\n[0.264505087265819,90.73549491273418]\r\n\r\n-}\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [x, y] <- readChar8'\r\n case (x < y, x == y) of\r\n (True, _ ) -> print (x + y)\r\n (_ , True) -> print x\r\n _ -> if even (x + y) then print $ (x + y) `div` 2 else print $ (x + y + if odd x then x else y) `div` 2\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[x, y] <- getInts 2\n pure $ putInts $ pure $ if x > y\n then x + y\n else quot (x + y) 2\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "a24aac9152417527d43b9b422e3d2303"} {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngao a = 4 + sum [maximum (map f a) | f <- [sum, foldl1 (-), foldl1 subtract, negate . sum]]\nmain = do C.interact $ C.pack . show . gao . map (map (fst . fromJust . C.readInt) . C.words) . tail . C.lines\n\n", "positive_code": [{"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngao a = 4 + sum [maximum (map f a) | f <- [sum, foldl1 (-), foldl1 subtract, negate . sum]]\nmain = do C.interact $ C.pack . show . gao . map (map (fst . fromJust . C.readInt) . C.words) . tail . C.lines\n\n{-\n\t2 * (max{x} - min{x})\n\t2 * (max{y} - min{y})\n\t-|max{x} + max{y} - max{x + y}|\n\t-|min{x + y} - min{x} - min{y}|\n\t-|max{x} - min{y} - max{x - y}|\n\t-|max{y} - min{x} - max{y - x}|\n=\tmax{x+y}+max{x-y}+max{y-x}+max{-x-y}\n-}-}\n{-\n# \tWhen \tWho \tProblem \tLang \tVerdict \tTime \tMemory\n229404 \tDec 24, 2010 11:07:18 AM \twatashi \tC - Happy Farm 5 \tHaskell \tTime limit exceeded on test 69 \t2000 ms \t14888 KB\n-}\n"}], "negative_code": [], "src_uid": "d2227a4ed6299626c2906962f91b066a"} {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Text.Printf\n\ntype Pos = (Int, Int, Int, Int)\n\nconv :: [Int] -> Pos\nconv [x1, y1, x2, y2] = (x1, y1, x2, y2)\nconv _ = error \"conv: Invalid format\"\n\ndivide :: Pos -> Pos -> [Pos]\ndivide this@(x1, y1, x2, y2) byThat@(x1', y1', x2', y2')\n | x1' == x2' && x1 < x1' && x1' < x2 && y1 == y1' && y2 == y2'= do\n [(x1, y1, x1', y2), (x1', y1, x2, y2)]\n | y1' == y2' && y1 < y1' && y1' < y2 && x1 == x1' && x2 == x2'= do\n [(x1, y1, x2, y1'), (x1, y1', x2, y2)]\n | otherwise = []\n\ncalcArea :: Pos -> Int\ncalcArea (x1, y1, x2, y2) = (x2 - x1) * (y2 - y1)\n\nfindBreak cs bs = head $ do\n c <- cs\n b <- bs\n case divide c b of\n _ :_ -> [(c, b)]\n _ -> []\n\nmain :: IO ()\nmain = do\n let readInts = map read . words :: String -> [Int]\n w : h : n : _ <- readInts <$> getLine\n breaks <- replicateM n $ conv . readInts <$> getLine\n let chocolate = (0, 0, w, h)\n findBreak cs bs = head $ do\n c <- cs\n b <- bs\n case divide c b of\n _ :_ -> [(c, b)]\n _ -> []\n bob'sJob cs [] = cs\n bob'sJob cs bs = do\n let (c, b) = findBreak cs bs\n bob'sJob (delete c cs ++ (divide c b)) (delete b bs)\n answer = sort . map calcArea $ bob'sJob [chocolate] breaks\n putStrLn . intercalate \" \" $ map show answer\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n [w,h,n] <- getA\n a <- replicateM n getA\n putStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n c@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n (r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n (p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[w,h,n] <- getA\n\ta <- replicateM n getA\n\tputStr $ unwords $ map show $ sort $ gao [0,0,w,h] a\n\ngao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]\ngao [x1,y1,x2,y2] a = gao r p ++ gao s q where\n\tc@[x3,y3,x4,y4] = head $ filter (\\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a\n\t(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])\n\t(p,q) = partition (\\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a\n\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Text.Printf\n\ntype Pos = (Int, Int, Int, Int)\n\nconv :: [Int] -> Pos\nconv [x1, y1, x2, y2] = (x1, y1, x2, y2)\nconv _ = error \"conv: Invalid format\"\n\ndivide :: Pos -> Pos -> Maybe [Pos]\ndivide this@(x1, y1, x2, y2) byThat@(x1', y1', x2', y2')\n | x1' == x2' && x1 < x1' && x1' < x2 && y1 == y1' && y2 == y2'= do\n Just $ [(x1, y1, x1', y2), (x1', y1, x2, y2)]\n | y1' == y2' && y1 < y1' && y1' < y2 && x1 == x1' && x2 == x2'= do\n Just $ [(x1, y1, x2, y1'), (x1, y1', x2, y2)]\n | otherwise = Nothing\n\ncalcArea :: Pos -> Int\ncalcArea (x1, y1, x2, y2) = (x2 - x1) * (y2 - y1)\n\nmain :: IO ()\nmain = do\n let readInts = map read . words :: String -> [Int]\n w : h : n : _ <- readInts <$> getLine\n breaks <- replicateM n $ conv . readInts <$> getLine\n let chocolate = (0, 0, w, h)\n bob'sJob parts b = do\n let check p1 p2 = maybe [p1] id $ divide p1 p2\n concat $ map (`check` b) parts\n answer = sort . map calcArea $ foldl bob'sJob [chocolate] breaks\n putStrLn . intercalate \" \" $ map show answer\n"}], "src_uid": "dfa484cecb07e195f5cc46e04cc68ab4"} {"source_code": "main = interact foo\n\ntype Point = (Int, Int)\ntype Line = [Point]\n\nfoo :: String -> String\nfoo inp =\n let points = zip [1..] . map read . words . (!! 1) . lines $ inp :: [Point]\n in if mlines points [] []\n then \"Yes\"\n else \"No\"\n\nbaz :: Point -> Point -> Double\nbaz p1 p2 =\n let (x1, y1) = p1\n (x2, y2) = p2\n in (fromIntegral $ y1 - y2) / (fromIntegral $ x1 - x2)\n\nk :: Double -> Point -> Double\nk b (x, y) = (fromIntegral y) - b * (fromIntegral x)\n\ncheck :: Line -> Line -> Bool\ncheck [] _ = False\ncheck _ [] = False\ncheck l [p] = not $ compatible l p\ncheck [p] l = check l [p]\ncheck ps1 ps2 = \n let p11 = head ps1\n p21 = ps1 !! 1\n p12 = ps2 !! 0\n p22 = ps2 !! 1\n b1 = baz p11 p21\n b2 = baz p12 p22\n in if b1 == b2\n then if k b1 p11 == k b2 p12\n then False\n else True\n else False\n\ncompatible :: Line -> Point -> Bool\ncompatible [] _ = True\ncompatible [_] _ = True\ncompatible l p = \n let p1 = head l\n in baz p1 p == baz (l !! 0) (l !! 1)\n \nmlines :: [Point] -> Line -> Line -> Bool\nmlines [] l1 l2 = check l1 l2\nmlines (p:ps) l1 l2 = \n let c1 = compatible l1 p\n c2 = compatible l2 p\n per :: Point -> Bool\n per pp = \n if mlines ps (pp:l1) l2\n then True\n else mlines ps l1 (pp:l2)\n in if validate l1 l2\n then\n if c1 && c2 \n then if length l1 < 2 || length l2 < 2\n then per p\n else False\n else if c1 \n then mlines ps (p:l1) l2\n else if c2\n then mlines ps l1 (p:l2)\n else False\n else False\n \nvalidate :: Line -> Line -> Bool\nvalidate [] _ = True\nvalidate _ [] = True\nvalidate [_] [_] = True\nvalidate l1 l2 = check l1 l2", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Data.Int (Int64)\n\ndata Pnt = Pnt (Int64, Int64) deriving Eq\n\nparallel (Pnt (x1, y1)) (Pnt (x2, y2)) (Pnt (x3, y3)) (Pnt (x4, y4))\n | (y2 - y1) * (x4 - x3) == (y4 - y3) * (x2 - x1) = True | otherwise = False\n\ndivide p1 p2 [] b = b\ndivide p1 p2 (px:xs) b | parallel p1 p2 p1 px = divide p1 p2 xs b\n | otherwise = divide p1 p2 xs (px:b)\n\ntest xs p1 p2 | length d == 0 = False | length d == 1 = True\n | otherwise = let (dx:dy:ds) = d in parallel p1 p2 dx dy && divide dx dy ds [] == []\n where d = divide p1 p2 xs []\n\nrun (x:y:z:xs) | divide y z (x:xs) [] == [x] = True | otherwise = any (test (y:z:xs) x) (y:z:xs)\n\nmain :: IO ()\nmain = do\n _ <- getLine\n (map Pnt . zip [1..] . map (read :: String -> Int64) . words -> xs) <- getLine\n putStrLn $ case run xs of\n True -> \"Yes\"\n False -> \"No\"\n"}, {"source_code": "main = interact foo\n\ntype Point = (Int, Int)\ntype Line = [Point]\n\nfoo :: String -> String\nfoo inp =\n let points = zip [1..] . map read . words . (!! 1) . lines $ inp :: [Point]\n in if mlines points [] []\n then \"Yes\"\n else \"No\"\n\nbaz :: Point -> Point -> Double\nbaz p1 p2 =\n let (x1, y1) = p1\n (x2, y2) = p2\n in (fromIntegral $ y1 - y2) / (fromIntegral $ x1 - x2)\n\nk :: Double -> Point -> Double\nk b (x, y) = (fromIntegral y) - b * (fromIntegral x)\n\ncheck :: Line -> Line -> Bool\ncheck [] _ = False\ncheck _ [] = False\ncheck l [p] = not $ compatible l p\ncheck [p] l = check l [p]\ncheck ps1 ps2 = \n let p11 = head ps1\n p21 = ps1 !! 1\n p12 = ps2 !! 0\n p22 = ps2 !! 1\n b1 = baz p11 p21\n b2 = baz p12 p22\n in if b1 == b2\n then if k b1 p11 == k b2 p12\n then False\n else True\n else False\n\ncompatible :: Line -> Point -> Bool\ncompatible [] _ = True\ncompatible [_] _ = True\ncompatible l p = \n let p1 = head l\n in baz p1 p == baz (l !! 0) (l !! 1)\n \nmlines :: [Point] -> Line -> Line -> Bool\nmlines [] l1 l2 = check l1 l2\nmlines _ l1 l2 | not $ validate l1 l2 = False\nmlines (p:ps) l1 l2 = \n let c1 = compatible l1 p\n c2 = compatible l2 p\n per :: Point -> Bool\n per pp = \n if mlines ps (pp:l1) l2\n then True\n else mlines ps l1 (pp:l2)\n in\n if c1 && c2 \n then if length l1 < 2 || length l2 < 2\n then per p\n else False\n else if c1 \n then mlines ps (p:l1) l2\n else if c2\n then mlines ps l1 (p:l2)\n else False\n \nvalidate :: Line -> Line -> Bool\nvalidate [] _ = True\nvalidate _ [] = True\nvalidate [_] [_] = True\nvalidate l1 l2 = check l1 l2"}], "negative_code": [{"source_code": "main = interact foo\n\ntype Point = (Int, Int)\ntype Line = [Point]\n\nfoo :: String -> String\nfoo inp =\n let points = zip [1..] . map read . words . (!! 1) . lines $ inp :: [Point]\n in if mlines points [] []\n then \"Yes\"\n else \"No\"\n\nbaz :: Point -> Point -> Double\nbaz p1 p2 =\n let (x1, y1) = p1\n (x2, y2) = p2\n in (fromIntegral $ y1 - y2) / (fromIntegral $ x1 - x2)\n\nk :: Double -> Point -> Double\n-- k a b | trace (\"k \" ++ show a ++ \" \" ++ show b) False = undefined\nk b (x, y) = (fromIntegral y) - b * (fromIntegral x)\n\ncheck :: Line -> Line -> Bool\n-- check l1 l2 | trace (\"check \" ++ show l1 ++ \" \" ++ show l2) False = undefined\ncheck [] _ = False\ncheck _ [] = False\ncheck [p] l = check l [p]\ncheck l [p] = not $ compatible l p\ncheck ps1 ps2 = \n let p11 = head ps1\n p21 = ps1 !! 1\n p12 = ps2 !! 0\n p22 = ps2 !! 1\n b1 = baz p11 p21\n b2 = baz p12 p22\n in if b1 == b2\n then if k b1 p11 == k b2 p12\n then False\n else True\n else False\n\ncompatible :: Line -> Point -> Bool\n-- compatible l p | trace (\"compatible \" ++ show l ++ \" \" ++ show p) False = undefined\ncompatible [] _ = True\ncompatible [_] _ = True\ncompatible l p = \n let p1 = head l\n in baz p1 p == baz (l !! 0) (l !! 1)\n \nmlines :: [Point] -> Line -> Line -> Bool\n-- mlines a b c | trace (\"mlines \" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c) False = undefined\nmlines [] l1 l2 = check l1 l2\n-- mlines ps [] [] = mlines (drop 4 ps) (take 2 ps) (take 2 . drop 2 $ ps)\nmlines (p:ps) l1 l2 = \n let c1 = compatible l1 p\n c2 = compatible l2 p\n per :: Point -> Bool\n per pp = \n if mlines ps (pp:l1) l2\n then True\n else mlines ps l1 (pp:l2)\n in if check l1 l2\n then if c1 && c2 \n then if length l1 < 2 || length l2 < 2\n then per p\n else False\n else if c1 \n then mlines ps (p:l1) l2\n else if c2\n then mlines ps l1 (p:l2)\n else False\n else False"}], "src_uid": "c54042eebaef01783a74d31521db9baa"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts #-}\nimport Data.List (tails)\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Array (accumArray,(!))\n\nmain = do\n (n:k:as) <- map read . words <$> getContents\n let diffs = accumArray (+) 0 (0,10^6)\n [ (abs (a-b),1) | (a:t) <- tails as , b <- t ]\n print $ head $ filter (check diffs k as) [1..]\n\ncheck diffs k _ m\n | sum [ diffs!d | d <- [m,2*m..10^6] ] > k*(k+1) `div` 2 = False\ncheck diffs k as m = runST $ do\n closed <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)\n let go (-1) _ = return False\n go k (a:as) = do\n let i = a `mod` m\n c <- readArray closed i\n if c then go (k-1) as else do\n writeArray closed i True\n go k as\n go _ [] = return True\n go k as\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntSet as IS\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- sort.map readInt.B.words <$> B.getLine\n print $ solve n k xs\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k xs = head $ filter check $ filter check0 [1..]\n where\n !arr = listArray (0,n-1) xs :: UArray Int Int\n !diffmax = maximum xs - minimum xs\n !lim = k*(k+1)`div`2\n !diffs = runSTUArray $ do\n d <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)\n forM_ [0..n-1] $ \\i-> do\n forM_ [i+1..n-1] $ \\j-> do\n unsafeModify d (unsafeAt arr j - unsafeAt arr i) (1+)\n return d\n check0 m = (<=lim) . sum $ map (unsafeAt diffs) [m,m+m..diffmax]\n check m = runST $ do\n used <- newArray (0,m) False :: ST s (STUArray s Int Bool)\n let go !cnt (x:xs)\n | cnt > k = return False\n | otherwise = do\n let !r = x `rem` m\n flg <- unsafeRead used r\n if flg\n then go (cnt+1) xs\n else do\n unsafeWrite used r True\n go cnt xs\n go cnt _ = return $! cnt <= k\n go 0 xs\n{- \n check m = go 0 IS.empty $ map (`rem`m) xs\n where\n go !cnt !used (x:xs)\n | cnt > k = False\n | IS.member x used = go (cnt+1) (IS.insert x used) xs\n | otherwise = go cnt (IS.insert x used) xs\n go cnt _ _ = cnt <= k\n-}"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE FlexibleContexts #-}\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Control.Monad\n\nmain = do\n (n:k:as) <- map (fst . fromJust . B.readInt) . B.words <$> B.getContents\n let diffs = accumArray (+) 0 (0,10^6)\n [ (abs (a-b),1) | (a:t) <- tails as , b <- t ]\n print $ head $ filter (check diffs k as) [1..]\n\ncheck diffs k _ m\n | sum [ diffs!d | d <- [m,2*m..10^6] ] > k*(k+1) `div` 2 = False\ncheck diffs k as m = runST $ do\n closed <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)\n let go (-1) _ = return False\n go k (a:as) = do\n let i = a `mod` m\n c <- readArray closed i\n if c then go (k-1) as else do\n writeArray closed i True\n go k as\n go _ [] = return True\n go k as\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.List (tails)\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Array (accumArray,(!))\n\nmain = do\n (n:k:as) <- map read . words <$> getContents\n let diffs = accumArray (+) 0 (0,10^6)\n [ (abs (a-b),1) | (a:t) <- tails as , b <- t ]\n print $ head $ filter (check diffs k as) [1..]\n\ncheck diffs k _ m\n | sum [ diffs!d | d <- [m,2*m..10^6] ] > k*(k+1) `div` 2 = False\ncheck diffs k as m = runST $ do\n closed <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)\n let go (-1) _ = return False\n go k (a:as) = do\n let i = a `mod` m\n c <- readArray closed i\n if c then go (k-1) as else do\n writeArray closed i True\n go k as\n go _ [] = return True\n go k as\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntSet as IS\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- sort.map readInt.B.words <$> B.getLine\n print $ solve n k xs\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k xs = head $ filter check $ filter check0 [1..]\n where\n !arr = listArray (0,n-1) xs :: UArray Int Int\n !diffmax = maximum xs - minimum xs\n !lim = k*(k+1)`div`2\n !diffs = runSTUArray $ do\n d <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)\n forM_ [0..n-1] $ \\i-> do\n forM_ [i+1..n-1] $ \\j-> do\n unsafeModify d (unsafeAt arr j - unsafeAt arr i) (1+)\n return d\n check0 m = (<=lim) . sum $ map (unsafeAt diffs) [m,m+m..diffmax]\n check m = go 0 IS.empty $ map (`rem`m) xs\n where\n go !cnt !used (x:xs)\n | cnt > k = False\n | IS.member x used = go (cnt+1) (IS.insert x used) xs\n | otherwise = go cnt (IS.insert x used) xs\n go cnt _ _ = cnt <= k\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport Data.List (tails)\nimport Data.Array.ST.Safe (STUArray,newArray,readArray,writeArray)\nimport Control.Monad (forM_)\nimport Control.Monad.ST.Safe (ST,runST)\nmain = interact $ show . solve . map read . words\nsolve (n:k:ns) = runST $ do\n a <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)\n forM_ (tails ns) $ \\ns -> if null ns then return () else do\n forM_ (tail ns) $ \\n -> let d = abs (head ns - n)\n in readArray a d >>= writeArray a d . succ\n let threshold = k * (k+1) `div` 2\n validate m = go m 0 where\n go _ c | c > threshold = validate (m+1)\n go i _ | i > 1000000 = return m\n go i c = do\n c' <- readArray a i\n go (i+m) (c+c')\n validate (n-k)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Control.Monad.ST\nimport Data.Array.ST.Safe\nimport Data.Array\nimport Control.Monad\n\n-- import Debug.Trace\n\nmain = do\n (n:k:as) <- map (fst . fromJust . B.readInt) . B.words <$> B.getContents\n let diffs = accumArray (flip (:)) [] (0,10^6)\n [ (abs (a-b),(a,b)) | (a:t) <- tails as, b <- t ]\n print $ head $ filter (check'' diffs k) [1..]\n\ncheck k as m = (<= k) $ sum $ map (pred . length) $ group $ sort $ map (`mod` m) as\n\ncheck' k as m = runST $ do\n t <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)\n let go (-1) _ = return False\n go k (a:as) = do\n let i = a `mod` m\n p <- readArray t i\n writeArray t i True\n go (if p then k-1 else k) as\n go _ [] = return True\n go k as\n\ncheck'' diffs k m = runST $ do\n parent <- newListArray (0,10^6) [0..] :: ST s (STUArray s Int Int)\n size <- newListArray (0,10^6) (repeat 1) :: ST s (STUArray s Int Int)\n let -- go k ps | traceShow (k,ps) False = undefined\n go (-1) _ = return False\n go k ((a,b):ps) = do\n same <- liftM2 (==) (rep a) (rep b)\n if same then go k ps else do\n merge a b\n go (k-1) ps\n go _ [] = return True\n rep i = do\n p <- readArray parent i\n if p == i then return i else do\n r <- rep p\n writeArray parent i r\n return r\n merge i j = do\n -- traceM $ \"Merge \" ++ show (i,j)\n ri <- rep i\n rj <- rep j\n si <- readArray size ri\n sj <- readArray size rj\n if si <= sj\n then do\n writeArray parent ri rj\n writeArray size rj (si+sj)\n else do\n writeArray parent rj ri\n writeArray size ri (si+sj)\n go k $ concatMap (diffs!) [m,2*m..4999]\n\n{- Old version\n\n{-# LANGUAGE FlexibleContexts #-}\nimport Data.List (tails)\nimport Data.Array.ST (STUArray,newArray,readArray,writeArray)\nimport Control.Monad (forM_)\nimport Control.Monad.ST (ST,runST)\nmain = interact $ show . solve . map read . words\nsolve (n:k:ns) = runST $ do\n a <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)\n forM_ (tails ns) $ \\ns -> if null ns then return () else do\n forM_ (tail ns) $ \\n -> let d = abs (head ns - n)\n in readArray a d >>= writeArray a d . succ\n let threshold = k * (k+1) `div` 2\n validate m = go m 0 where\n go _ c | c > threshold = validate (m+1)\n go i _ | i > 1000000 = return m\n go i c = do\n c' <- readArray a i\n go (i+m) (c+c')\n validate (n-k)\n\n-}\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Control.Monad.ST.Safe\nimport Data.Array.ST.Safe\n\nmain = do\n (n:k:as) <- map (fst . fromJust . B.readInt) . B.words <$> B.getContents\n print $ head $ filter (check' k as) [1..]\n\ncheck k as m = (<= k) $ sum $ map (pred . length) $ group $ sort $ map (`mod` m) as\n\ncheck' k as m = runST $ do\n t <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)\n let go (-1) _ = return False\n go k (a:as) = do\n let i = a `mod` m\n p <- readArray t i\n writeArray t i True\n go (if p then k+1 else k) as\n go _ [] = return True\n go k as\n\n{- Old version\n\n{-# LANGUAGE FlexibleContexts #-}\nimport Data.List (tails)\nimport Data.Array.ST (STUArray,newArray,readArray,writeArray)\nimport Control.Monad (forM_)\nimport Control.Monad.ST (ST,runST)\nmain = interact $ show . solve . map read . words\nsolve (n:k:ns) = runST $ do\n a <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)\n forM_ (tails ns) $ \\ns -> if null ns then return () else do\n forM_ (tail ns) $ \\n -> let d = abs (head ns - n)\n in readArray a d >>= writeArray a d . succ\n let threshold = k * (k+1) `div` 2\n validate m = go m 0 where\n go _ c | c > threshold = validate (m+1)\n go i _ | i > 1000000 = return m\n go i c = do\n c' <- readArray a i\n go (i+m) (c+c')\n validate (n-k)\n\n-}\n"}], "src_uid": "656e44f1aa0202a3e8414bbce9381b09"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n-- {-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n--import Debug.Trace\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print $ solve k xs\n\nsolve :: Int -> [Int] -> Int\nsolve k0 xs0 = go 0 . group . map fromIntegral $ sort xs0\n where\n k :: Int64\n !k = fromIntegral k0\n-- go res xs | traceShow xs False = undefined\n go !res (xs@(x:_):ys@(y:_):xss)\n | y <= x + k = go res (ys:xss)\n | otherwise = go (res + length xs) (ys:xss)\n go res xs = res + length (concat xs)\n", "positive_code": [{"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\n\nimport Control.Monad\n\n\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [Int]\nreadInts = map parse . C8.words\n where parse s = let Just(x,_) = C8.readInt s in x\n\n\n\nmain :: IO ()\nmain = do\n [n,k] <- fmap (map read . words) getLine\n bs <- input\n let weights = readInts bs\n len = length weights\n sorted = List.sort weights\n sortedA = sorted\n sortedKA = [(w + k) | w <- sorted]\n (_,acc) = foldl eat (sortedKA,0) sortedA\n where eat (arr,acc) weight = let\n middleFront = List.dropWhile (< weight) arr\n (middle,front) = List.span (< weight + k) middleFront\n in (front, acc + (length middle))\n print $ (length weights) - acc\n\n \n"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\nmtrace _ s = s\n\nsolve input = show (total - removed)\n where\n n:k:xs = map fastRead . words $ input :: [Int64]\n sortedXs = sortBy (flip compare) xs\n first:_ = sortedXs\n total = fromIntegral(length xs) :: Int64\n (removed, _, _) = foldl' reducer (0, first, first) sortedXs\n\n reducer :: (Int64, Int64, Int64) -> Int64 -> (Int64, Int64, Int64)\n reducer (answer, firstValue, minOne) currentValue \n | firstValue > currentValue && minOne <= currentValue + k = mtrace debugTrace (answer + 1, firstValue, currentValue)\n | otherwise = mtrace (\"Not \" ++ debugTrace) (answer, currentValue, currentValue)\n where\n debugTrace = show firstValue ++ \" And \" ++ show currentValue ++ \" And \" ++ show minOne\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nmain :: IO ()\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine\n print $ solve k xs\n\nsolve :: Int -> [Int] -> Int\nsolve k0 xs0 = go 0 . map fromIntegral $ sort xs0\n where\n k :: Int64\n !k = fromIntegral k0\n go !res (x:y:xs)\n | x < y, y <= x + k = go res (y:xs)\n | otherwise = go (res + 1) (y:xs)\n go res _ = res\n"}, {"source_code": "module Main where\n\nimport System.IO\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as C8\n\nimport qualified Data.Array as Array\nimport qualified Data.Set as Set\nimport qualified Data.List as List\nimport qualified Data.Map as Map\n\nimport Control.Monad\n\ninput :: IO BS.ByteString\ninput = do\n handle <- return stdin --openFile \"test.txt\" ReadMode\n BS.hGetContents handle\n\nreadInts :: BS.ByteString -> [Int]\nreadInts = map parse . C8.words\n where parse s = let Just(x,_) = C8.readInt s in x\n\nmain :: IO ()\nmain = do\n [n,k] <- fmap (map read . words) getLine\n bs <- input\n let weights = readInts bs\n weightsPlusK = Set.fromList [(w + k) | w <- weights]\n weightsSorted = List.sort weights\n remaining = foldl eat weightsPlusK weightsSorted\n where eat set weight = let\n (ok,notOk) = Set.partition\n (\\el -> el >= weight && el < (weight + k)) set\n in set Set.\\\\ ok\n print $ Set.size remaining\n"}], "src_uid": "be8be333d036f6c19b9a6eb33f96ba75"} {"source_code": "import Data.List\nimport Control.Monad\n\ngetTest :: IO [Int]\ngetTest = do\n _ <- getLine\n r <- getLine\n let\n r' = map read $ words r\n return r'\n\nmain :: IO ()\nmain = do\n n <- getLine\n let n' = (read n :: Int)\n tests <- replicateM n' getTest\n mapM_ (putStrLn . unwords . map show . nub) tests\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Set as Set\n\nmain = do\n contents <- getContents\n let notnull = filter (not . null) $ lines contents\n let input = map (map (read :: String -> Int) . words) notnull\n let res = go (drop 1 input)\n sequence res\n\ntoString :: [Int] -> String\ntoString [] = \"\"\ntoString (x:xs) = show x ++ \" \" ++ toString xs\n\ngo :: [[Int]] -> [IO ()]\ngo [] = []\ngo (_:x:xs) = putStrLn res:go xs\n where res = toString (solve x)\n\nsolve :: [Int] -> [Int]\nsolve a =\n let recurse [] _ = []\n recurse (x:xs) s\n | Set.member x s = recurse xs s\n | otherwise = x:recurse xs (Set.insert x s)\n in recurse a Set.empty"}, {"source_code": "module Main where\nimport Data.List\n\nmain = do\n interact $ unlines . map solve . groupl 2 . tail .lines\n\nsolve :: [String] -> String\nsolve (n:str:[]) = unwords . map show $ (go (toInteger $ length . words $ str) [] (map read $ words str :: [Integer]))\n where go :: Integer -> [Integer] -> [Integer] -> [Integer]\n go 0 xs ls = xs\n go n xs (l:ls) = case elem l xs of\n True -> go (n-1) xs ls\n False -> go (n-1) (xs ++ [l]) ls\n\ngroupl :: Int -> [a] -> [[a]]\ngroupl _ [] = []\ngroupl n l\n | n > 0 = (take n l) : (groupl n (drop n l))\n | otherwise = error \"Negative or zero n\"\n"}, {"source_code": "main = interact $ unlines . map (unwords . solve []) . prepareInput . map words . tail . lines\n\nprepareInput :: [[String]] -> [[String]]\nprepareInput [] = []\nprepareInput (x:[]) = []\nprepareInput (x:y:xs) = concat [[x ++ y], prepareInput xs]\n\nsolve :: [String] -> [String] -> [String]\nsolve xs (x:[]) = xs\nsolve xs (x:y:ys)\n | length xs == read x = xs\n | elem y xs = solve xs (x:ys)\n | otherwise = solve (xs ++ [y]) (x:ys)\n"}, {"source_code": "import Data.Set as Set ( empty, insert, member )\nimport Control.Monad ( replicateM_ )\n\nsolve :: [Integer] -> [Integer]\nsolve = snd . foldr go (Set.empty, []) where\n go y old@(seen, ys)\n | member y seen = old\n | otherwise = (insert y seen, y : ys)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ getLine >> getLine >>= putStrLn . unwords . map show . solve . map read . words\n"}, {"source_code": "import Control.Monad ( replicateM_ )\n\nrestorePerm :: [Integer] -> [Integer]-> [Integer]\nrestorePerm ys [] = reverse ys\nrestorePerm ys (x : xs)\n | elem x ys = restorePerm ys xs\n | otherwise = restorePerm (x : ys) xs\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n replicateM_ n $ getLine >> getLine >>= solve\n where\n solve = putStrLn . unwords . map show . restorePerm [] . map read . words\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Control.Monad (replicateM_)\n\nf :: [Int] -> [Int]\nf [] = []\nf (x:xs) = x : f (delete x xs)\n\ngo :: IO ()\ngo = do\n _ <- getLine\n xs <- map read . words <$> getLine :: IO [Int]\n putStrLn . unwords . map show $ f xs\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n replicateM_ n go\n"}, {"source_code": "module Main where\n\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n input <- getLine\n let n = (read input :: Int)\n sequence_ $ replicate n solve\n\nlistToString :: [Int] -> String\nlistToString [] = \"\"\nlistToString (x : xs) = (show x) ++ \" \" ++ (listToString xs)\n\nprintList :: [Int] -> IO ()\nprintList = putStrLn . listToString\n\ngetPerm :: Set.Set Int -> Set.Set Int -> [Int] -> [Int] -> [Int]\ngetPerm _ _ [] ans = ans\ngetPerm first second (x : xs) ans = case (Set.member x first, Set.member x second) of \n (False, False) -> getPerm (Set.insert x first) second xs (ans ++ [x])\n (True, False) -> getPerm first (Set.insert x second) xs ans\n (False, True) -> getPerm (Set.insert x first) second xs ans\n\nsolve :: IO ()\nsolve = do\n foo <- getLine\n input <- getLine\n let perm = map read (words input) :: [Int]\n printList $ getPerm Set.empty Set.empty perm []\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess [] y = y\nprocess (x:xs) y | elem x y = process xs y\n | otherwise = process xs (x:y)\n\nonecase = do\n\t\tgetLine\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ intercalate \" \" $ map show $ reverse $ process a []\n\t\t\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess [] y = y\nprocess (x:xs) y | elem x y = process xs y\n | otherwise = process xs (x:y)\n\nonecase = do\n\t\tgetLine\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tputStrLn $ intercalate \" \" $ map show $ process a []\n\t\t\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}], "src_uid": "aaf91874cf5aa0fa302ffed2ccecdc76"} {"source_code": "main = interact solve\nsolve input = output where\n [l0,l1] = lines input\n [k,a,b] = map (read::String->Int) $ words l0\n output = answer\n len = length l1\n answer = if len < k*a || len > k*b then \"No solution\" else unlines $ ans0 ++ ans1\n len0 = div len k\n mod0 = mod len k\n ans0 = [take (len0+1) $ drop (i*(len0+1)) l1|i<-[0..(mod0 - 1)]]\n ans1 = [take len0 $ drop (mod0*(len0+1)+i*len0) l1|i<-[0..(k-mod0-1)]]", "positive_code": [{"source_code": "main = interact solve\nsolve input = output where\n [l0,l1] = lines input\n [k,a,b] = map (read::String->Int) $ words l0\n len = length l1\n output = if len < k*a || len > k*b then \"No solution\" else unlines $ ans0 ++ ans1\n len0 = div len k\n mod0 = mod len k\n ans0 = [take (len0+1) $ drop (i*(len0+1)) l1|i<-[0..(mod0 - 1)]]\n ans1 = [take len0 $ drop (mod0*(len0+1)+i*len0) l1|i<-[0..(k-mod0-1)]]"}], "negative_code": [], "src_uid": "75633f47c1fbde571aa2936bf2639289"} {"source_code": "-- import Debug.Trace\r\n\r\nimport Data.List\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ncountOccs :: Eq a => [a] -> [(a, Int)]\r\ncountOccs [] = []\r\ncountOccs [x] = [(x, 1)]\r\ncountOccs (x : xs) = \r\n case countOccs xs of\r\n (a,b) : t -> if x == a\r\n then (a, b + 1) : t\r\n else (x, 1) : (a, b) : t\r\n _ -> undefined\r\n\r\nsolve :: InType -> OutType\r\nsolve a = map fst occ ++ gen occ\r\n where sa = sort a\r\n occ = countOccs sa\r\n gen [] = []\r\n gen ((x, o) : t) = replicate (o - 1) x ++ gen t\r\n\r\nreceive :: [String] -> InType\r\nreceive [n, a] = toArr a\r\nreceive _ = undefined\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showArr . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showArr = foldr (\\x xs -> show x ++ \" \" ++ xs) \"\"\r\n", "positive_code": [{"source_code": "module Main where\n\nimport Data.List (group)\nimport Control.Monad (replicateM_)\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n _ <- getLine\n arr <- map read . words <$> getLine\n putStrLn . unwords . map show . reorder $ arr\n\nreorder :: [Int] -> [Int]\nreorder = f 0 where\n f x arr = case splitBy x arr of\n Nothing -> arr\n Just (a,b,c) -> b : f (x + 1) (a ++ c)\n\nsplitBy :: Int -> [Int] -> Maybe ([Int], Int, [Int])\nsplitBy x [] = Nothing\nsplitBy x (r:rs) | x == r = Just ([],r,rs)\nsplitBy x (r:rs) = (\\(a,b,c) -> (r:a,b,c)) <$> splitBy x rs\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\n\nsolve :: [Int] -> [Int]\nsolve li = let\n k = maximum li\n buckets :: UArray Int Int\n buckets = accumArray (const . (+ 1)) 0 (0, k) $ zip li $ repeat ()\n in [ix | (ix, ct) <- assocs buckets, ct > 0] ++ do\n (ix, ct) <- assocs buckets\n guard $ ct > 0\n replicate (ct - 1) ix\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- readInts\n putInts $ solve a\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "-- import Debug.Trace\r\n\r\nimport Data.List\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ncountOccs :: Eq a => [a] -> [(a, Int)]\r\ncountOccs [] = []\r\ncountOccs (x : xs) = \r\n case countOccs xs of\r\n (a,b) : t -> if x == a\r\n then (a, b + 1) : t\r\n else (x, 1) : (a, b) : t\r\n [] -> [(x, 1)]\r\n\r\nsolve :: InType -> OutType\r\nsolve a = map fst occ ++ gen occ\r\n where sa = sort a\r\n occ = countOccs sa\r\n gen [] = []\r\n gen ((x, o) : t) = replicate (o - 1) x ++ gen t\r\n\r\nreceive :: [String] -> InType\r\nreceive [n, a] = toArr a\r\nreceive _ = undefined\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showArr . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showArr = foldr (\\x xs -> show x ++ \" \" ++ xs) \"\"\r\n"}, {"source_code": "-- import Debug.Trace\r\n\r\nimport Data.List\r\n\r\ntype InType = [Int]\r\ntype OutType = [Int]\r\n\r\ninpLines :: Int\r\ninpLines = 2\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ncountOccs :: Eq a => [a] -> [(a, Int)]\r\ncountOccs [] = []\r\ncountOccs [x] = [(x, 1)]\r\ncountOccs (x : xs) = if x == (fst . head) rest\r\n then addOne rest\r\n else (x, 1) : rest\r\n where rest = countOccs xs\r\n addOne ((a, b) : t) = (a, b + 1) : t\r\n\r\nsolve :: InType -> OutType\r\nsolve a = map fst occ ++ gen occ\r\n where sa = sort a\r\n occ = countOccs sa\r\n gen [] = []\r\n gen ((x, o) : t) = replicate (o - 1) x ++ gen t\r\n\r\nreceive :: [String] -> InType\r\nreceive [n, a] = toArr a\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (showArr . solve . receive) . chunksOf inpLines . tail . lines)\r\n where showArr = foldr (\\x xs -> show x ++ \" \" ++ xs) \"\"\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nmain = do\r\n t <- getLine\r\n replicateM (read t) testcase\r\n\r\ntestcase :: IO ()\r\ntestcase = do\r\n n <- getLine\r\n a <- fmap words getLine\r\n putStrLn $ solve a\r\n\r\nsolve :: [String] -> String\r\nsolve a = unwords . map show $ solution\r\n where\r\n sorted = group . reverse . sort . map read $ a :: [[Int]]\r\n pairs = foldl (\\(x,y) curr -> (head curr:x, tail curr ++ y)) ([],[]) sorted :: ([Int],[Int]) \r\n solution = fst pairs ++ snd pairs :: [Int]"}, {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\n\r\nprint2 [x] = \"\"\r\nprint2 (x:xs) = (if x == head xs then show(x) ++ \" \" else \"\") ++ print2 xs\r\n\r\nprint1 [x] = show(x) ++\" \"\r\nprint1 (x:xs) = (if (x /= head xs) then show(x) ++ \" \" else \"\") ++ print1 xs \r\n\r\nprintS = do \r\n n<-readLn :: IO Int \r\n a<-readInts \r\n let sorted = sort a \r\n putStr $ print1 sorted\r\n putStrLn $ print2 sorted\r\n\r\nmain = do\r\n t<-readLn :: IO Int \r\n replicateM_ t printS"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Char\nimport Data.List (sort)\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\nimport System.IO\nimport Text.Read\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1 .. t] handleCase\n\nhandleCase :: Integer -> IO ()\nhandleCase c = do\n n <- read <$> getLine :: IO Int\n as <- fmap (map read . words) getLine :: IO [Int]\n putStrLn $ unwords $ map show $ solve (sort as) [] []\n\nsolve :: [Int] -> [Int] -> [Int] -> [Int]\nsolve [x] pref suff = reverse pref ++ [x] ++ suff\nsolve (x:y:as) pref suff\n | x==y = solve (x:as) pref (y:suff)\n | otherwise = solve (y:as) (x:pref) suff\n"}], "negative_code": [], "src_uid": "69838d9f9214c65b84a21d4eb546ea4b"} {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\n\ncheck :: String -> String -> Set.Set String -> Bool\ncheck \"\" suff set = False\ncheck pref suff set =\n if suff /= \"\" && Set.member pref set && Set.member suff set\n then True\n else check (init pref) ((last pref) : suff) set\n\nsolve :: [String] -> Int -> Int -> Int -> Int\nsolve strs n i j\n | i == n `div` 2 = 0\n | j == (n + 1) `div` 2 =\n solve strs n (i+1) 0\n | otherwise =\n (min cost (4 - cost)) + solve strs n i (j+1)\n where\n ri = n - i - 1\n rj = n - j - 1\n cost = sum $ map fromEnum $ map (\\x -> x == '1')\n [strs !! i !! j, strs !! j !! ri, strs !! rj !! i, strs !! ri !! rj]\n\ntestcase 0 = return ()\ntestcase t = do\n n <- readLn :: IO Int\n strs <- forM [1..n] (\\x -> getLine)\n putStrLn $ show $ solve strs n 0 0\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\n\ncheck :: String -> String -> Set.Set String -> Bool\ncheck \"\" suff set = False\ncheck pref suff set =\n if suff /= \"\" && Set.member pref set && Set.member suff set\n then True\n else check (init pref) ((last pref) : suff) set\n\nsolve :: [String] -> Int -> Int -> Int -> Int\nsolve strs n i j =\n if i == n `div` 2\n then 0\n else if j == (n + 1) `div` 2\n then solve strs n (i+1) 0\n else (min cost (4 - cost)) + solve strs n i (j+1)\n where\n ri = n - i - 1\n rj = n - j - 1\n cost = sum $ map (\\x -> if x == '1' then 1 else 0) (\n [strs !! i !! j, strs !! j !! ri, strs !! rj !! i, strs !! ri !! rj])\n\ntestcase 0 = return ()\ntestcase t = do\n n <- readLn :: IO Int\n strs <- forM [1..n] (\\x -> getLine)\n putStrLn $ show $ solve strs n 0 0\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as BS\n \nskipWhitespace :: BS.ByteString -> BS.ByteString\nskipWhitespace = BS.dropWhile (`elem` \" \\r\\n\\t\")\n \nreadInts :: BS.ByteString -> [Int]\nreadInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))\n Nothing -> []\nreadInt :: BS.ByteString -> Int\nreadInt line = let [x] = readInts line in x\n\ncount :: Eq a => a -> [a] -> Int\ncount x xs = length (filter (==x) xs)\n\nunique :: Ord a => [a] -> [a]\nunique = map head . group . sort \n\nsolve n lines = sum $ map (impl . map get) $ unique $ map unique $ indexPairList\n where half = (n - 1) `div` 2\n rot (i, j) = (n - 1 - j, i)\n get (i, j) = (BS.index (lines !! i) j)\n indexPairList = [[(i, j), rot (i, j), (rot . rot) (i, j), (rot . rot . rot) (i, j)] | i <- [0 .. half], j <- [0 .. half]]\n impl xs = min (count '1' xs) (count '0' xs)\n\ntestCaseMain :: Int -> IO ()\ntestCaseMain _ = do n <- readInt <$> BS.getLine\n lines <- forM [1 .. n] (\\_ -> BS.getLine)\n print (solve n lines)\n \nmain :: IO ()\nmain = do t <- readInt <$> BS.getLine\n forM_ [1 .. t] testCaseMain\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe, catMaybes)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort, nub, intercalate)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\n-- import System.Random\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Debug.Trace\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.String (fromString)\nimport Data.Bits (shift)\nimport Data.Binary (encode, decode)\n\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = [[Int]]\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n\n\ntoInt :: Char -> Int\ntoInt '1' = 1\ntoInt '0' = 0\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns xs = putStrLn $ show xs\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- replicateM n $ (fmap toInt <$> getLine)\n return xs\n\nrotate :: Int -> (Int, Int) -> (Int, Int)\nrotate n (a, b) = (n-1-b, a)\n\nsym :: Int -> (Int, Int) -> [(Int, Int)]\nsym = (take 4 .) . iterate . rotate \n\nget :: [[Int]] -> (Int,Int) -> Int\nget xs (x,y) = xs !! x !! y\n\ncal :: [[Int]] -> [(Int, Int)] -> Int\ncal xs coords = min s (4 - s)\n where n = length xs\n s = sum $ get xs <$> coords\n\nsolve :: Solver\nsolve xs = sum (cal xs <$> coords) `div` 4\n where n = length xs\n indices = [0..n-1]\n coords = sym n <$> liftM2 (,) indices indices\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM_ n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "import Data.List\r\nimport qualified Data.Char as DC\r\nimport qualified Data.Set as Set\r\nimport Control.Monad (replicateM)\r\n\r\ninverseTpl :: Int -> (Int, Int, Char) -> (Int, Int, Char)\r\n\r\ninverseTpl n (a, b, c) = (b, n - a - 1, c)\r\n\r\ntrd (_, _, z) = z\r\nzv c = if c then 1 else 0\r\n\r\nsumOtherF :: Int -> Set.Set (Int, Int, Char) -> (Int, Int, Char) -> Int\r\nsumOtherF n set (a, b, c) = sumOther n set (a, b, '1')\r\n\r\nsumOther :: Int -> Set.Set (Int, Int, Char) -> (Int, Int, Char) -> Int\r\nsumOther n set tpl =\r\n let i1 = inverseTpl n\r\n i2 = i1 . i1\r\n i3 = i1 . i2\r\n t1 = Set.member (i1 tpl) set\r\n t2 = Set.member (i2 tpl) set\r\n t3 = Set.member (i3 tpl) set \r\n in (zv t1) + (zv t2) + (zv t3)\r\n\r\nshouldChange :: Int -> Set.Set (Int, Int, Char) -> (Int, Int, Char) -> Bool\r\nshouldChange n set (a, b, c)\r\n | c == '0' = sumOtherF n set (a, b, c) >= 2\r\n | otherwise = sumOtherF n set (a, b, c) == 0\r\n\r\nsolveCase :: IO ()\r\nsolveCase = do\r\n n <- fmap (read :: String -> Int) getLine\r\n strs <- replicateM n getLine\r\n let prikols = concat $ map (\\ilst -> map (\\tp2 -> ((fst ilst), (fst tp2), (snd tp2))) $ zip [0..n-1] (snd ilst)) $ zip [0..n-1] strs\r\n let setik = Set.fromList prikols\r\n let res = filter (shouldChange n setik) prikols\r\n putStrLn $ show $ length res\r\n\r\nsolve :: Int -> IO ()\r\nsolve 0 = do\r\n return ()\r\nsolve cases_left = do\r\n solveCase\r\n solve $ cases_left - 1\r\n\r\nmain = do\r\n s_testcases <- getLine\r\n solve $ (read s_testcases :: Int)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Set as Set\n\ncheck :: String -> String -> Set.Set String -> Bool\ncheck \"\" suff set = False\ncheck pref suff set =\n if suff /= \"\" && Set.member pref set && Set.member suff set\n then True\n else check (init pref) ((last pref) : suff) set\n\nsolve :: [String] -> Int -> Int -> Int -> Int\nsolve strs n i j\n | i == n `div` 2 = 0\n | j == (n + 1) `div` 2 =\n solve strs n (i+1) 0\n | otherwise =\n (min cost (4 - cost)) + solve strs n i (j+1)\n where\n ri = n - i - 1\n rj = n - j - 1\n cost = sum $ map (\\x -> if x == '1' then 1 else 0) (\n [strs !! i !! j, strs !! j !! ri, strs !! rj !! i, strs !! ri !! rj])\n\ntestcase 0 = return ()\ntestcase t = do\n n <- readLn :: IO Int\n strs <- forM [1..n] (\\x -> getLine)\n putStrLn $ show $ solve strs n 0 0\n testcase (t - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testcase t\n"}], "negative_code": [], "src_uid": "867b01e7141ef077964a8a0d4c6b762b"} {"source_code": "import Array\nimport Char\nmain = interact (ans)\nans theInput = unlines ansList where\n s:t:n0:abw0 = lines theInput\n n = read n0 ::Int\n abw = [(c2i $ x!!0,c2i $ x!!2,read(drop 4 x)::Integer)|x<-(take n abw0)]\n c2i x = ord x - ord 'a'\n table [] = array ((0,0),(25,25)) [((a,b),if a==b then 0 else 999999999)|a<-[0..25],b<-[0..25]]\n table ((a,b,w):xs) = (table xs) // [((a,b),min w ( (table xs)!(a,b) ) )]\n wf 0 = table abw\n wf (m+1) = array((0,0),(25,25)) [((a,b),min ((wf m)!(a,b)) ( ((wf m)!(a,m))+((wf m)!(m,b)) ) ) |a<-[0..25],b<-[0..25]] where\n final = wf 26\n cost t = array((0,0),(25,25)) [((x,y),foldr1 min [( (t!(x,z)) + (t!(y,z)),z )|z<-[0..25]])|x<-[0..25],y<-[0..25]]\n total = sum [fst (cf x y)|(x,y)<-zip s t]\n answord = [chr(snd (cf x y)+ord 'a') |(x,y)<-zip s t]\n cf x y = (cost final) ! (c2i x,c2i y)\n ansList = if total>999999998 || length s /= length t then [\"-1\"] else [show total,answord]\n", "positive_code": [{"source_code": "import Array\nimport Char\nmain = interact (ans)\nans theInput = unlines ansList where\n s:t:n0:abw0 = lines theInput\n n = read n0 ::Int\n abw = [(c2i $ x!!0,c2i $ x!!2,read(drop 4 x)::Integer)|x<-(take n abw0)]\n c2i x = ord x - ord 'a'\n table [] = array ((0,0),(25,25)) [((a,b),if a==b then 0 else 999999999)|a<-[0..25],b<-[0..25]]\n table ((a,b,w):xs) = (table xs) // [((a,b),min w ( (table xs)!(a,b) ) )]\n wf 0 = table abw\n wf (m+1) = array((0,0),(25,25)) [((a,b),min ((wf m)!(a,b)) ( ((wf m)!(a,m))+((wf m)!(m,b)) ) ) |a<-[0..25],b<-[0..25]]\n final = wf 26\n cost t = array((0,0),(25,25)) [((x,y),foldr1 min [( (t!(x,z)) + (t!(y,z)),z )|z<-[0..25]])|x<-[0..25],y<-[0..25]]\n total = sum [fst (cf x y)|(x,y)<-zip s t]\n answord = [chr(snd (cf x y)+ord 'a') |(x,y)<-zip s t]\n cf x y = (cost final) ! (c2i x,c2i y)\n ansList = if total>999999998 || length s /= length t then [\"-1\"] else [show total,answord]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\n-- import qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.IORef\nimport Data.Int\nimport System.Exit\nimport Text.Printf\nimport qualified Foreign as F\nimport qualified Foreign.C as F\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_I64d :: F.CString -> F.CLLong -> IO ()\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: F.CString -> F.CString -> IO ()\n\ninf :: Int64\ninf = 10 ^ 16\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let exit = print (-1) >> exitSuccess\n conv = fromIntegral . fst . fromJust . BS.readInt\n table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)\n F.withCString \"%I64d\\n\" $ \\fmt_I64d -> do \n F.withCString \"%s\\n\" $ \\fmt_s -> do \n for_ 'a' 'z' $ \\c -> do\n writeArray table (c, c) 0\n s1 <- BS.filter (/= '\\r') <$> BS.getLine\n s2 <- BS.filter (/= '\\r') <$> BS.getLine\n when (BS.length s1 /= BS.length s2) $ exit\n n <- readLn\n for_ 1 n $ \\i -> do\n from : to : s : _ <- BS.words <$> BS.getLine\n let idx = (BS.head from, BS.head to)\n v <- readArray table idx\n writeArray table idx $ min (conv s) v \n for_ 'a' 'z' $ \\k -> do\n for_ 'a' 'z' $ \\i -> do\n for_ 'a' 'z' $ \\j -> do\n v <- readArray table (i, j)\n v1 <- readArray table (i, k)\n v2 <- readArray table (k, j)\n when (v1 + v2 < v) $ do\n writeArray table (i, j) $ v1 + v2\n -- getAssocs table >>= print . filter ((/= inf) . snd)\n r <- newIORef 0 :: IO (IORef Int64)\n buf <- F.mallocArray0 101000 :: IO F.CString\n for_ 0 (BS.length s1 - 1) $ \\i -> do\n let c1 = BS.index s1 i\n c2 = BS.index s2 i\n findMin = loop 'a' ('\\0', inf) where\n loop to acc@(c, v)\n | 'z' < to = return acc\n | otherwise = do\n v1 <- readArray table (c1, to) \n v2 <- readArray table (c2, to)\n -- printf \"%s\\n\" (show (c1, c2, to))\n loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc\n (c, v) <- findMin\n when (c == '\\0') $ exit\n modifyIORef r $ (+ v)\n F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)\n F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\\0')\n readIORef r >>= c_printf_I64d fmt_I64d . fromIntegral\n c_printf_s fmt_s buf\n F.free buf\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\n-- import qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.IORef\nimport Data.Int\nimport System.Exit\nimport Text.Printf\nimport qualified Foreign as F\nimport qualified Foreign.C as F\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_I64d :: F.CString -> F.CLLong -> IO ()\n\nforeign import ccall unsafe \"stdio.h printf\"\n c_printf_s :: F.CString -> F.CString -> IO ()\n\ninf :: Int64\ninf = 10 ^ 16\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let exit = print (-1) >> exitSuccess\n conv = fromIntegral . fst . fromJust . BS.readInt\n table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)\n F.withCString \"%I64d\\n\" $ \\fmt_I64d -> do \n F.withCString \"%s\\n\" $ \\fmt_s -> do \n for_ 'a' 'z' $ \\c -> do\n writeArray table (c, c) 0\n s1 <- BS.filter (/= '\\r') <$> BS.getLine\n s2 <- BS.filter (/= '\\r') <$> BS.getLine\n -- s1 <- BS.getLine\n -- s2 <- BS.getLine\n when (BS.length s1 /= BS.length s2) $ exit\n n <- readLn\n for_ 1 n $ \\i -> do\n from : to : s : _ <- BS.words <$> BS.getLine\n let idx = (BS.head from, BS.head to)\n v <- readArray table idx\n writeArray table idx $ min (conv s) v \n for_ 'a' 'z' $ \\k -> do\n for_ 'a' 'z' $ \\i -> do\n for_ 'a' 'z' $ \\j -> do\n v <- readArray table (i, j)\n v1 <- readArray table (i, k)\n v2 <- readArray table (k, j)\n when (v1 + v2 < v) $ do\n writeArray table (i, j) $ v1 + v2\n -- getAssocs table >>= print . filter ((/= inf) . snd)\n r <- newIORef 0 :: IO (IORef Int64)\n buf <- F.mallocArray0 101000 :: IO F.CString\n for_ 0 (BS.length s1 - 1) $ \\i -> do\n let c1 = BS.index s1 i\n c2 = BS.index s2 i\n findMin = loop 'a' ('\\0', inf) where\n loop to acc@(c, v)\n | 'z' < to = return acc\n | otherwise = do\n v1 <- readArray table (c1, to) \n v2 <- readArray table (c2, to)\n -- printf \"%s\\n\" (show (c1, c2, to))\n loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc\n (c, v) <- findMin\n when (c == '\\0') $ exit\n modifyIORef r $ (+ v)\n F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)\n F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\\0')\n readIORef r >>= c_printf_I64d fmt_I64d . fromIntegral\n c_printf_s fmt_s buf\n F.free buf\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}], "negative_code": [{"source_code": "import Array\nimport Char\nmain = interact (ans)\nans theInput = unlines ansList where\n s:t:n0:abw0 = lines theInput\n n = read n0 ::Int\n abw = [(c2i $ x!!0,c2i $ x!!2,read(drop 4 x)::Int)|x<-(take n abw0)]\n c2i x = ord x - ord 'a'\n table [] = array ((0,0),(25,25)) [((a,b),if a==b then 0 else 9999)|a<-[0..25],b<-[0..25]]\n table ((a,b,w):xs) = (table xs) // [((a,b),min w ((table xs)!(a,b)))]\n wf 0 = table abw\n wf (m+1) = array((0,0),(25,25))\n [((a,b),foldr min ((wf m)!(a,b)) [ ((wf m)!(a,m)+(wf m)!(m,b)) , 9999] )|a<-[0..25],b<-[0..25]]\n final = wf 26\n cost t = array((0,0),(25,25)) [((x,y),foldr min (9999,-1) [(t!(x,z)+t!(y,z),z)|z<-[0..25]])|x<-[0..25],y<-[0..25]]\n total = sum [fst (cf x y)|(x,y)<-zip s t]\n answord = [chr(snd (cf x y)+ord 'a') |(x,y)<-zip s t]\n cf x y = (cost final) ! (c2i x,c2i y)\n ansList = if total>9998 || length s /= length t then [\"-1\"] else [show total,answord]\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n cs <- T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return (head from, Map.singleton (head to) (read v :: Int))\n let mp = Map.fromListWith (Map.unionWith min) cs\n bnds = (('a', 'a'), ('z', 'z'))\n table <- newArray bnds maxBound :: IO (IOArray (Char, Char) Int)\n F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \\idx -> do\n writeArray table idx 0\n let fill from cost now = F.for_ (Map.lookup now mp) $ \\mp' -> do\n F.for_ (Map.toList mp') $ \\(to, new) -> do\n old <- readArray table (now, to)\n when (old == maxBound || new < old) $ do\n writeArray table (now, to) new\n let new' = cost + new\n old' <- readArray table (from, to)\n when (old' == maxBound || new' < old') $ do\n writeArray table (from, to) new'\n fill from new' to\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n \n let check c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- T.for ['a' .. 'z'] $ \\to -> do\n v1 <- readArray table (c1, to)\n v2 <- readArray table (c2, to)\n case () of\n _ | c1 == to -> return (to, v2)\n | c2 == to -> return (to, v1)\n | otherwise -> return (to, min v1 v2)\n when (null xs) $ exit\n let (c, cost) = minimumBy (comparing snd) xs\n if cost == maxBound\n then exit\n else do\n return (c, cost)\n (answer, cost) <- unzip <$> zipWithM check s1 s2\n-- getAssocs table >>= printf \"%s\\n\" . show\n print $ sum cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport System.Exit\n\ninf :: Integer\ninf = 10 ^ 20\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n cs <- T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return (head from, Map.singleton (head to) (read v :: Integer))\n let mp = Map.fromListWith (Map.unionWith min) cs\n bnds = (('a', 'a'), ('z', 'z'))\n table <- newArray bnds inf :: IO (IOArray (Char, Char) Integer)\n F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \\idx -> do\n writeArray table idx 0\n let fill from cost now = F.for_ (Map.lookup now mp) $ \\mp' -> do\n F.for_ (Map.toList mp') $ \\(to, new) -> do\n old <- readArray table (now, to)\n when (old == inf || new < old) $ do\n writeArray table (now, to) new\n let new' = cost + new\n old' <- readArray table (from, to)\n when (old' == inf || new' < old') $ do\n writeArray table (from, to) new'\n fill from new' to\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n let check c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- T.for ['a' .. 'z'] $ \\to -> do\n v1 <- readArray table (c1, to)\n v2 <- readArray table (c2, to)\n case () of\n _ | c1 == to -> return (to, v2)\n | c2 == to -> return (to, v1)\n | otherwise -> return (to, v1 + v2)\n when (null xs) $ exit\n let (c, cost) = minimumBy (comparing snd) xs\n if cost == inf\n then exit\n else do\n return (c, cost)\n (answer, cost) <- unzip <$> zipWithM check s1 s2\n-- getAssocs table >>= printf \"%s\\n\" . show\n print $ sum cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\n-- import qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.IORef\nimport Data.Int\nimport System.Exit\nimport Text.Printf\nimport qualified Foreign as F\nimport qualified Foreign.C as F\n\nforeign import ccall unsafe \"stdio.h puts\"\n puts :: F.CString -> IO ()\n\ninf :: Int64\ninf = 10 ^ 16\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let exit = print (-1) >> exitSuccess\n conv = fromIntegral . fst . fromJust . BS.readInt\n table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)\n for_ 'a' 'z' $ \\c -> do\n writeArray table (c, c) 0\n s1 <- BS.filter (/= '\\r') <$> BS.getLine\n s2 <- BS.filter (/= '\\r') <$> BS.getLine\n when (BS.length s1 /= BS.length s2) $ exit\n n <- readLn\n for_ 1 n $ \\i -> do\n from : to : s : _ <- BS.words <$> BS.getLine\n let idx = (BS.head from, BS.head to)\n v <- readArray table idx\n writeArray table idx $ min (conv s) v \n for_ 'a' 'z' $ \\k -> do\n for_ 'a' 'z' $ \\i -> do\n for_ 'a' 'z' $ \\j -> do\n v <- readArray table (i, j)\n v1 <- readArray table (i, k)\n v2 <- readArray table (k, j)\n when (v1 + v2 < v) $ do\n writeArray table (i, j) $ v1 + v2\n -- getAssocs table >>= print . filter ((/= inf) . snd)\n r <- newIORef 0 :: IO (IORef Int64)\n buf <- F.mallocArray0 101000 :: IO F.CString\n for_ 0 (BS.length s1 - 1) $ \\i -> do\n let c1 = BS.index s1 i\n c2 = BS.index s2 i\n findMin = loop 'a' ('\\0', inf) where\n loop to acc@(c, v)\n | 'z' < to = return acc\n | otherwise = do\n v1 <- readArray table (c1, to) \n v2 <- readArray table (c2, to)\n -- printf \"%s\\n\" (show (c1, c2, to))\n loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc\n (c, v) <- findMin\n when (c == '\\0') $ exit\n modifyIORef r $ (+ v)\n F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)\n F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\\0')\n readIORef r >>= print\n puts buf\n F.free buf\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport System.Exit\n\ninf :: Integer\ninf = 10 ^ 20\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n cs <- T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return (head from, Map.singleton (head to) (read v :: Integer))\n let mp = Map.fromListWith (Map.unionWith min) cs\n bnds = (('a', 'a'), ('z', 'z'))\n table <- newArray bnds inf :: IO (IOArray (Char, Char) Integer)\n F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \\idx -> do\n writeArray table idx 0\n let fill from cost now = F.for_ (Map.lookup now mp) $ \\mp' -> do\n F.for_ (Map.toList mp') $ \\(to, new) -> do\n old <- readArray table (now, to)\n when (old == inf || new < old) $ do\n writeArray table (now, to) new\n let new' = cost + new\n old' <- readArray table (from, to)\n when (old' == inf || new' < old') $ do\n writeArray table (from, to) new'\n fill from new' to\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n let check c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- T.for ['a' .. 'z'] $ \\to -> do\n v1 <- readArray table (c1, to)\n v2 <- readArray table (c2, to)\n case () of\n _ | c1 == to -> return (to, v2)\n | c2 == to -> return (to, v1)\n | otherwise -> return (to, min v1 v2)\n when (null xs) $ exit\n let (c, cost) = minimumBy (comparing snd) xs\n if cost == inf\n then exit\n else do\n return (c, cost)\n (answer, cost) <- unzip <$> zipWithM check s1 s2\n-- getAssocs table >>= printf \"%s\\n\" . show\n print $ sum cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n cs <- T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return (head from, Map.singleton (head to) (read v :: Int))\n let mp = Map.fromListWith (Map.unionWith min) cs\n bnds = (('a', 'a'), ('z', 'z'))\n table <- newArray bnds maxBound :: IO (IOArray (Char, Char) Int)\n F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \\idx -> do\n writeArray table idx 0\n let fill from cost now = F.for_ (Map.lookup now mp) $ \\mp' -> do\n F.for_ (Map.toList mp') $ \\(to, new) -> do\n old <- readArray table (now, to)\n when (old == maxBound || new < old) $ do\n writeArray table (now, to) new\n let new' = cost + new\n old' <- readArray table (from, to)\n when (old' == maxBound || new' < old') $ do\n writeArray table (from, to) new'\n fill from new' to\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n \n let check c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- T.for ['a' .. 'z'] $ \\to -> do\n v1 <- readArray table (c1, to)\n v2 <- readArray table (c2, to)\n case () of\n _ | c1 == to -> return (to, v2)\n | c2 == to -> return (to, v1)\n | otherwise -> return (to, min v1 v2)\n when (null xs) $ exit\n let (c, cost) = minimumBy (comparing snd) xs\n if cost == maxBound\n then exit\n else do\n return (c, cost)\n (answer, cost) <- unzip <$> zipWithM check s1 s2\n-- getAssocs table >>= printf \"%s\\n\" . show\n print $ sum cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.Array.Unboxed\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n cs <- T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return (head from, Map.singleton (head to) (read v :: Int))\n let mp = Map.fromListWith (Map.unionWith min) cs\n bnds = (('a', 'a'), ('z', 'z'))\n table <- newArray bnds maxBound :: IO (IOArray (Char, Char) Int)\n-- F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \\idx -> do\n-- writeArray table idx 0\n let fill from cost now = F.for_ (Map.lookup now mp) $ \\mp' -> do\n F.for_ (Map.toList mp') $ \\(to, new) -> do\n old <- readArray table (now, to)\n when (old == maxBound || new < old) $ do\n writeArray table (now, to) new\n let new' = cost + new\n old' <- readArray table (from, to)\n when (old' == maxBound || new' < old') $ do\n writeArray table (from, to) new'\n fill from new' to\n F.for_ ['a' .. 'z'] $ \\c -> fill c 0 c\n let check c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- T.for ['a' .. 'z'] $ \\to -> do\n v1 <- readArray table (c1, to)\n v2 <- readArray table (c2, to)\n case () of\n _ | c1 == to -> return (to, v2)\n | c2 == to -> return (to, v1)\n | otherwise -> return (to, min v1 v2)\n when (null xs) $ exit\n let (c, cost) = minimumBy (comparing snd) xs\n if cost == maxBound\n then exit\n else do\n return (c, cost)\n (answer, cost) <- unzip <$> zipWithM check s1 s2\n-- getAssocs table >>= printf \"%s\\n\" . show\n print $ sum cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\n-- import qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.IORef\nimport Data.Int\nimport System.Exit\nimport Text.Printf\nimport qualified Foreign as F\nimport qualified Foreign.C as F\n\nforeign import ccall unsafe \"stdio.h puts\"\n puts :: F.CString -> IO ()\n\ninf :: Int64\ninf = 10 ^ 16\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let exit = print (-1) >> exitSuccess\n conv = fromIntegral . fst . fromJust . BS.readInt\n table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)\n for_ 'a' 'z' $ \\c -> do\n writeArray table (c, c) 0\n s1 <- BS.filter (/= '\\r') <$> BS.getLine\n s2 <- BS.filter (/= '\\r') <$> BS.getLine\n when (BS.length s1 /= BS.length s2) $ exit\n n <- readLn\n for_ 1 n $ \\i -> do\n from : to : s : _ <- BS.words <$> BS.getLine\n let idx = (BS.head from, BS.head to)\n v <- readArray table idx\n writeArray table idx $ min (conv s) v \n for_ 'a' 'z' $ \\k -> do\n for_ 'a' 'z' $ \\i -> do\n for_ 'a' 'z' $ \\j -> do\n v <- readArray table (i, j)\n v1 <- readArray table (i, k)\n v2 <- readArray table (k, j)\n when (v1 + v2 < v) $ do\n writeArray table (i, j) $ v1 + v2\n -- getAssocs table >>= print . filter ((/= inf) . snd)\n r <- newIORef 0 :: IO (IORef Int64)\n buf <- F.mallocArray0 101000 :: IO F.CString\n for_ 0 (BS.length s1 - 1) $ \\i -> do\n let c1 = BS.index s1 i\n c2 = BS.index s2 i\n findMin = loop 'a' ('\\0', inf) where\n loop to acc@(c, v)\n | 'z' < to = return acc\n | otherwise = do\n v1 <- readArray table (c1, to) \n v2 <- readArray table (c2, to)\n -- printf \"%s\\n\" (show (c1, c2, to))\n loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc\n (c, v) <- findMin\n when (c == '\\0') $ exit\n modifyIORef r $ (+ v)\n F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)\n F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\\0')\n readIORef r >>= print\n puts buf\n F.free buf\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, ForeignFunctionInterface #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\n-- import qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport Data.Array.IO\nimport Data.IORef\nimport Data.Int\nimport System.Exit\nimport Text.Printf\nimport qualified Foreign as F\nimport qualified Foreign.C as F\n\nforeign import ccall unsafe \"stdio.h puts\"\n puts :: F.CString -> IO ()\n\ninf :: Int64\ninf = 10 ^ 16\n\n{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}\n{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}\nfor_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()\nfor_ i n f = loop i where\n loop i | i <= n = f i >> loop (succ i)\n | otherwise = return ()\n\nmain :: IO ()\nmain = do\n let exit = print (-1) >> exitSuccess\n conv = fromIntegral . fst . fromJust . BS.readInt\n table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)\n for_ 'a' 'z' $ \\c -> do\n writeArray table (c, c) 0\n s1 <- BS.filter (/= '\\r') <$> BS.getLine\n s2 <- BS.filter (/= '\\r') <$> BS.getLine\n when (BS.length s1 /= BS.length s2) $ exit\n n <- readLn\n for_ 1 n $ \\i -> do\n from : to : s : _ <- BS.words <$> BS.getLine\n let idx = (BS.head from, BS.head to)\n v <- readArray table idx\n writeArray table idx $ min (conv s) v \n for_ 'a' 'z' $ \\k -> do\n for_ 'a' 'z' $ \\i -> do\n for_ 'a' 'z' $ \\j -> do\n v <- readArray table (i, j)\n v1 <- readArray table (i, k)\n v2 <- readArray table (k, j)\n when (v1 + v2 < v) $ do\n writeArray table (i, j) $ v1 + v2\n -- getAssocs table >>= print . filter ((/= inf) . snd)\n r <- newIORef 0 :: IO (IORef Int64)\n buf <- F.mallocArray0 101000 :: IO F.CString\n for_ 0 (BS.length s1 - 1) $ \\i -> do\n let c1 = BS.index s1 i\n c2 = BS.index s2 i\n findMin = loop 'a' ('\\0', inf) where\n loop to acc@(c, v)\n | 'z' < to = return acc\n | otherwise = do\n v1 <- readArray table (c1, to) \n v2 <- readArray table (c2, to)\n -- printf \"%s\\n\" (show (c1, c2, to))\n loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc\n (c, v) <- findMin\n when (c == '\\0') $ exit\n modifyIORef r $ (+ v)\n F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)\n F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\\0')\n readIORef r >>= print\n puts buf\n F.free buf\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\n-- import Control.Arrow\nimport Data.List\n-- import Data.Maybe\nimport Data.Ord\nimport Data.Char\n-- import Data.Function\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.ByteString.Char8 as BS\nimport Text.Printf\nimport System.Exit\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n exit = print (-1) >> exitSuccess\n s1 <- getLine\n s2 <- getLine\n when (length s1 /= length s2) $ exit\n n <- readLn\n init <- fmap (Map.fromListWith min) . T.for [1 .. n] $ \\i -> do\n from : to : v: _ <- words <$> getLine\n return ((head from, head to), (read v :: Integer))\n let mp = foldl check init ['a' .. 'z']\n check acc k = foldl f acc [(i, j) | i <- ['a' .. 'z'], j <- ['a' .. 'z']]\n where f acc' (i, j) = maybe acc' g $ do\n v1 <- Map.lookup (i, k) acc'\n v2 <- Map.lookup (k, j) acc'\n return $ v1 + v2\n where g v = maybe (Map.insert (i, j) v acc') id $ do\n v' <- Map.lookup (i, j) acc'\n return $ if v < v'\n then Map.insert (i, j) v acc'\n else acc'\n let best c1 c2\n | c1 == c2 = return (c1, 0)\n | otherwise = do\n xs <- fmap concat . T.for ['a' .. 'z'] $ \\to -> do\n return . maybe [] (return . (,) to) $ do\n case () of\n _ | c1 == to -> Map.lookup (c2, to) mp\n | c2 == to -> Map.lookup (c1, to) mp\n | otherwise -> do\n v1 <- Map.lookup (c1, to) mp\n v2 <- Map.lookup (c2, to) mp\n return $ min v1 v2\n when (null xs) $ exit\n return $ minimumBy (comparing snd) xs\n (answer, cost) <- fmap sum . unzip <$> zipWithM best s1 s2\n -- print mp\n print cost\n putStrLn answer\n\n\n{-\nad\nad\n6\na b 1\na e 4\nb e 1\nb c 2\nc d 100\ne d 5\n-}\n"}], "src_uid": "88c82ada2e66429900caeac758f7083b"} {"source_code": "\nimport Array hiding (array)\nimport Control.Monad (replicateM_)\nimport Prelude hiding (reads)\n\n--------------------------------------------------------------------------------\n{-\nimport Data.Function (on)\nimport HUnit\n\ntestMyTest :: Test\ntestMyTest = TestList \"TestMyTest\"\n [\n Test \"1\" $ on assertEq elems (toArray [8,8,1,1]) $ solve [8,8,1,1,1],\n Test \"2\" $ on assertEq elems (toArray [8,8,1,1]) $ solve [8,8,8,1,1],\n Test \"3\" $ on assertEq elems (toArray [8,8,4,1]) $ solve [8,8,4,1,1],\n Test \"4\" $ on assertEq elems (toArray [0,0,0,1,1,1,2,4]) $ solve [0,0,0,1,1,1,1,4,2]\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ on assertEq elems (toArray [0]) $ solve [0],\n Test \"2\" $ on assertEq elems (toArray [0,3,3,3,4,4,4,5,5,5]) $ solve [3,4,5,4,5,3,5,3,4,4,0],\n Test \"3\" $ on assertEq elems (toArray [1,2,2,3,3,5,5]) $ solve [3,2,5,1,5,2,2,3]\n ]\n\ntestF :: Test\ntestF = Test \"TestF\" $\n assertEq [(0,0),(0,1),(0,2),(0,0),(0,1),(0,2),(1,0),(2,0),(0,0),(1,0),(2,0),(0,0),(0,1),(1,0),(0,0),(0,1),(1,0),(1,0),(0,0),(0,1),(1,0),(0,0),(0,1),(1,0),(0,0),(0,1),(1,0)]\n (map f [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(1,0),(2,0),(3,0),(4,0),(5,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(2,1),(2,2),(2,3),(2,4),(2,5),(3,1),(3,2),(3,3),(3,4),(3,5)])\n\ntestZero :: Test\ntestZero = Test \"TestZero\" $\n on assertEq elems (toArray [0]) $ solve [0,0]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testF,\n testMyTest,\n testInput,\n testZero \n ]\n-}\n--------------------------------------------------------------------------------\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\ntype MyArray = Array Int Int\n\ntoArray :: [Int] -> MyArray\ntoArray xs = accumArray (+) 0 (0,9) [(x, 1) | x <- xs]\n\nf :: (Int, Int) -> (Int, Int)\nf (0, m2) = (0, mod m2 3)\nf (m1, 0) = (mod m1 3, 0)\nf (m1, m2)\n | m1 < m2 && mod (m2 - k) 3 == 2 = (1, 0)\n | m1 < m2 = (0, mod (m2 - k) 3)\n | mod (m1 - k) 3 == 2 = (0, 1)\n | otherwise = (mod (m1 - k) 3, 0)\n where\n k = min m1 m2\n\nsolve :: [Int] -> MyArray\nsolve xs = solve' cs z array\n where\n array = toArray xs\n (m1, m2) = (sum $ map (array !) [1,4,7], sum $ map (array !) [2,5,8])\n (z1, z2) = f (m1, m2)\n (cs, z) = if (z1 == 0) then ([2,5,8], z2) else ([1,4,7], z1)\n solve' _ 0 acc = acc\n solve' [] _ acc = error \"Logical error\"\n solve' (c:cs) z acc = solve' cs (z-k) (acc // [(c, acc ! c - k)])\n where\n k = min z (acc ! c) \n\nprintAns :: MyArray -> IO ()\nprintAns array\n | array ! 0 == 0 = print (-1)\n | all (== 0) $ tail $ elems array = print 0\n | otherwise = mapM_ (\\(c, n) -> replicateM_ n $ putStr $ show c) (reverse $ assocs array) >> putStrLn \"\"\n\nmain :: IO ()\nmain = do\n getLine\n xs <- reads\n seq (length xs) (printAns $ solve xs)\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = getLine >> do\n cnts <- map (pred.length).group.sort.([0..9]++).map readInt.B.words <$> B.getLine\n if cnts!!0 == 0\n then print $ -1\n else putStrLn.f.solve $ cnts\n\nf (0:_) = \"0\"\nf ns = ns>>=show\n\ng cnts = do\n i<-[9,8..0]\n replicate (cnts!!i) i\n\ndel i xs = let (ys,x:zs)=splitAt i xs\n in ys++(x-1):zs\n\nsolve :: [Int] -> [Int]\nsolve cnts = case (`mod`3) $ sum $ zipWith (*) cnts [0..9] of\n 0 -> g cnts\n 1 | (x:_)<-filter((>0).(cnts!!))[1,4,7] -> g $ del x cnts\n | (x:_)<-filter((>1).(cnts!!))[2,5,8] -> g $ del x $ del x cnts\n | (x:y:_)<-filter((>0).(cnts!!))[2,5,8] -> g $ del x $ del y cnts\n 2 | (x:_)<-filter((>0).(cnts!!))[2,5,8] -> g $ del x cnts\n | (x:_)<-filter((>1).(cnts!!))[1,4,7] -> g $ del x $ del x cnts\n | (x:y:_)<-filter((>0).(cnts!!))[1,4,7] -> g $ del x $ del y cnts\n _ -> [-1]\n"}, {"source_code": "import Data.Char (intToDigit)\nimport Data.List (sort, delete)\nextract f = filter (f . (`mod` 3))\nsolve :: [Int] -> Maybe [Int]\nsolve xs\n | 0 `notElem` xs = Nothing \n | otherwise =\n case pl `mod` 3 of\n 0 -> Just $ reverse ss\n 1 -> factored 1\n 2 -> factored 2\n where pl = sum xs\n ss = sort xs \n ms = extract (/=0) ss\n factored h = case safeFind h ms of\n (_, Just x) -> Just $ reverse $ delete x ss\n _ -> case safeFind (3 - h) ms of\n (Just y, Just x) -> Just $ reverse $ delete y $ delete x $ ss\n _ -> Nothing\nsafeFind :: Int -> [Int] -> (Maybe Int, Maybe Int)\nsafeFind m ps = \n case extract (==m) ps of\n [] -> (Nothing, Nothing)\n [x] -> (Nothing, Just x)\n (y:x:s) -> (Just y, Just x) \n\nparse :: Maybe [Int] -> String\nparse Nothing = \"-1\"\nparse (Just v) = if all (==0) v then \"0\" else map intToDigit v\n\nmain = putStrLn.parse.solve.map read.tail.words =<< getContents\n"}, {"source_code": "import Data.Char (intToDigit)\nimport Data.List (sort, delete)\nextract f = filter (f . (`mod` 3))\nsolve :: [Int] -> Maybe [Int]\nsolve xs\n | 0 `notElem` xs = Nothing \n | otherwise = if md == 0 then Just ss else factored md\n where md = sum xs `mod` 3\n ss = sort xs \n ms = extract (/=0) ss\n factored h = case extract (==h) ms of\n (x:_) -> Just (delete x ss) \n _ -> case extract (==(3 - h)) ms of\n (y:x:_) -> Just (delete y (delete x ss))\n _ -> Nothing\nparse :: Maybe [Int] -> String\nparse Nothing = \"-1\"\nparse (Just v) = if all (==0) v then \"0\" else map intToDigit (reverse v) \nmain = putStrLn.parse.solve.map read.tail.words =<< getContents\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [Int]\nsolve ds\n | all (/= 0) ts = []\n | all (== 0) ts = [0]\n | otherwise = reverse ts\n where r = sum ds `mod` 3\n xs = sort ds\n ps = map (\\x -> filter (\\y -> y `mod` 3 == x) xs) [0, 1, 2]\n ts | r == 0 = xs\n | null $ ps !! r = xs \\\\ (take 2 (ps !! (3 - r)))\n | otherwise = delete (ps !! r !! 0) xs\n\nreadInput :: IO [Int]\nreadInput = do\n contents <- getContents\n let x:xs = words contents\n ds = map read $ take (read x) xs\n return ds\n\nshowOutput :: [Int] -> IO ()\nshowOutput xs = do\n putStrLn $ if null xs then \"-1\" else concat $ map show xs\n\nmain :: IO ()\nmain = do\n input <- readInput\n showOutput $ solve input\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [Int]\nsolve ds\n | all (/= 0) ts = []\n | all (== 0) ts = [0]\n | otherwise = reverse ts\n where r = sum ds `mod` 3\n xs = sort ds\n ps = map (\\x -> filter (\\y -> y `mod` 3 == x) xs) [0, 1, 2]\n ts | r == 0 = xs\n | null $ ps !! r = xs \\\\ (take 2 (ps !! (3 - r)))\n | otherwise = delete (ps !! r !! 0) xs\n\nreadInput :: IO [Int]\nreadInput = do\n contents <- getContents\n let n:ns = words contents\n ds = map read $ take (read n) ns\n return ds\n\nshowOutput :: [Int] -> IO ()\nshowOutput ds = do\n putStrLn $ if null ds then \"-1\" else concat $ map show ds\n\nmain :: IO ()\nmain = do\n input <- readInput\n showOutput $ solve input\n"}], "negative_code": [{"source_code": "\nimport Array hiding (array)\nimport Control.Monad (replicateM_)\nimport Prelude hiding (reads)\n\n--------------------------------------------------------------------------------\n{-\nimport Data.Function (on)\nimport HUnit\n\ntestMyTest :: Test\ntestMyTest = TestList \"TestMyTest\"\n [\n Test \"1\" $ on assertEq elems (toArray [8,8,1,1]) $ solve [8,8,1,1,1],\n Test \"2\" $ on assertEq elems (toArray [8,8,1,1]) $ solve [8,8,8,1,1],\n Test \"3\" $ on assertEq elems (toArray [8,8,4,1]) $ solve [8,8,4,1,1],\n Test \"4\" $ on assertEq elems (toArray [0,0,0,1,1,1,2,4]) $ solve [0,0,0,1,1,1,1,4,2]\n ]\n\ntestInput :: Test\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ on assertEq elems (toArray [0]) $ solve [0],\n Test \"2\" $ on assertEq elems (toArray [0,3,3,3,4,4,4,5,5,5]) $ solve [3,4,5,4,5,3,5,3,4,4,0],\n Test \"3\" $ on assertEq elems (toArray [1,2,2,3,3,5,5]) $ solve [3,2,5,1,5,2,2,3]\n ]\n\ntestF :: Test\ntestF = Test \"TestF\" $\n assertEq [(0,0),(0,1),(0,2),(0,0),(0,1),(0,2),(1,0),(2,0),(0,0),(1,0),(2,0),(0,0),(0,1),(1,0),(0,0),(0,1),(1,0),(1,0),(0,0),(0,1),(1,0),(0,0),(0,1),(1,0),(0,0),(0,1),(1,0)]\n (map f [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(1,0),(2,0),(3,0),(4,0),(5,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(2,1),(2,2),(2,3),(2,4),(2,5),(3,1),(3,2),(3,3),(3,4),(3,5)])\n\ntest :: IO ()\ntest = mapM_ run\n [\n testF,\n testMyTest,\n testInput \n ]\n-}\n--------------------------------------------------------------------------------\n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\ntype MyArray = Array Int Int\n\ntoArray :: [Int] -> MyArray\ntoArray xs = accumArray (+) 0 (0,9) [(x, 1) | x <- xs]\n\nf :: (Int, Int) -> (Int, Int)\nf (0, m2) = (0, mod m2 3)\nf (m1, 0) = (mod m1 3, 0)\nf (m1, m2)\n | m1 < m2 && mod (m2 - k) 3 == 2 = (1, 0)\n | m1 < m2 = (0, mod (m2 - k) 3)\n | mod (m1 - k) 3 == 2 = (0, 1)\n | otherwise = (mod (m1 - k) 3, 0)\n where\n k = min m1 m2\n\nsolve :: [Int] -> MyArray\nsolve xs = solve' cs z array\n where\n array = toArray xs\n (m1, m2) = (sum $ map (array !) [1,4,7], sum $ map (array !) [2,5,8])\n (z1, z2) = f (m1, m2)\n (cs, z) = if (z1 == 0) then ([2,5,8], z2) else ([1,4,7], z1)\n solve' _ 0 acc = acc\n solve' [] _ acc = error \"Logical error\"\n solve' (c:cs) z acc = solve' cs (z-k) (acc // [(c, acc ! c - k)])\n where\n k = min z (acc ! c) \n\nprintAns :: MyArray -> IO ()\nprintAns array\n | array ! 0 == 0 = print (-1)\n | otherwise = mapM_ (\\(c, n) -> replicateM_ n $ putStr $ show c) (reverse $ assocs array) >> putStrLn \"\"\n\nmain :: IO ()\nmain = do\n getLine\n xs <- reads\n seq (length xs) (printAns $ solve xs)\n"}, {"source_code": "import Data.Char (intToDigit)\nimport Data.List (sort, delete)\nextract f = filter (f . (`mod` 3))\nsolve :: [Int] -> Maybe [Int]\nsolve xs\n | 0 `notElem` xs = Nothing \n | all (==0) xs = Just [0]\n | otherwise =\n case pl `mod` 3 of\n 0 -> Just $ reverse ss\n 1 -> factored 1\n 2 -> factored 2\n where pl = sum xs\n ss = sort xs \n ms = extract (/=0) ss\n factored h = case safeFind h ms of\n (_, Just x) -> Just $ reverse $ delete x ss\n _ -> case safeFind (3 - h) ms of\n (Just y, Just x) -> Just $ reverse $ delete y $ delete x $ ss\n _ -> Nothing\nsafeFind :: Int -> [Int] -> (Maybe Int, Maybe Int)\nsafeFind m ps = \n case extract (==m) ps of\n [] -> (Nothing, Nothing)\n [x] -> (Nothing, Just x)\n (y:x:s) -> (Just y, Just x) \n\nparse :: Maybe [Int] -> String\nparse Nothing = \"-1\"\nparse (Just v) = map intToDigit v\n\nmain = putStrLn.parse.solve.map read.tail.words =<< getContents"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> [Int]\nsolve xs\n | all (/= 0) ts = []\n | all (== 0) ts = [0]\n | otherwise = reverse $ sort ts\n where r = sum xs `mod` 3\n ps = map (\\x -> filter (\\y -> y `mod` 3 == x) xs) [0, 1, 2]\n ts | r == 0 = xs\n | null $ ps !! r = xs \\\\ (take 2 (ps !! (3 - r)))\n | otherwise = delete (ps !! r !! 0) xs\n\nreadInput :: IO [Int]\nreadInput = do\n contents <- getContents\n let x:xs = words contents\n ds = map read $ take (read x) xs\n return ds\n\nshowOutput :: [Int] -> IO ()\nshowOutput xs = do\n putStrLn $ if null xs then \"-1\" else concat $ map show xs\n\nmain :: IO ()\nmain = do\n input <- readInput\n showOutput $ solve input\n"}], "src_uid": "b263917e47e1c84340bcb1c77999fd7e"} {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = B.getContents>>=putStrLn.unwords.map show.solve.zip[1..].tail.map readInt.B.words\n\nsolve :: [(Int,Int)] -> [Int]\nsolve ((i,x):(j,y):(k,z):rest)\n | x==y && y==z = solve ((j,y):(k,z):rest)\n | x==y = [j,k]\n | y==z || xy && y>z = [i,j]\n | z/=x = [i,k]\n | null rest = [-1]\n | x == w = [j,k]\n | y == w = [i,j]\n | otherwise = [k,l]\n where\n (l,w) = head rest\nsolve _ = [-1]", "positive_code": [{"source_code": "-- Codeforces 252B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -funfolding-use-threshold=16 #-}\n{-# OPTIONS_GHC -fexcess-precision #-}\n{-# OPTIONS_GHC -feager-blackholing #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# OPTIONS_GHC -fdicts-strict #-}\n{-# OPTIONS_GHC -optc-O3 #-}\n{-# OPTIONS_GHC -optc-ffast-math #-}\n\nimport Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BC\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents :: IO [Int]\n putStrLn . unwords . map show . go . zip [1..] $ xs\n where\n go ((x1,v1):(x2,v2):(x3,v3):vs)\n | v1 == v2 && v2 == v3 = go $ (x2,v2):(x3,v3):vs\n | v1 == v2 = [x2, x3]\n | v2 == v3 = [x1, x2]\n | v1 > v2 && v2 > v3 = [x1, x2]\n | v1 < v2 && v2 < v3 = [x1, x2]\n | v1 /= v3 = [x1, x3]\n | null vs = [-1]\n | v1 == v4 = [x2, x3]\n | v2 == v4 = [x1, x2]\n | v3 == v4 = [x2, x3]\n | otherwise = [x3, x4]\n where (x4, v4) = head vs\n go _ = [-1]\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n n <- readLn :: IO Int\n if n<=2\n then print $ -1\n else B.getContents>>=putStrLn.unwords.map show.solve.zip[1..].map readInt.B.words\n\nsolve :: [(Int,Int)] -> [Int]\nsolve ((i,x):(j,y):(k,z):rest)\n | x==y && y==z = solve ((j,y):(k,z):rest)\n | x==y = [j,k]\n | y==z = [i,j]\n | z==x = solve ((i,x):(j,y):rest)\n | xy && y>x = [i,j]\n | otherwise = [i,k]\nsolve _ = [-1]"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = B.getContents>>=putStrLn.unwords.map show.solve.zip[1..].tail.map readInt.B.words\n\nsolve :: [(Int,Int)] -> [Int]\nsolve ((i,x):(j,y):(k,z):rest)\n | x==y && y==z = solve ((j,y):(k,z):rest)\n | x==y = [j,k]\n | y==z || xy && y>z = [i,j]\n | z/=x = [i,k]\n | null rest = [-1]\n | y == w = [i,j]\n | otherwise = [k,l]\n where\n (l,w) = head rest\nsolve _ = [-1]"}], "src_uid": "2ae4d2ca09f28d10fa2c71eb2abdaa1c"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'))\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\n\ntype Domain = (Int, [(Int, Int)])\ntype CoDomain = [Bool]\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . showResult\n\nparse :: IO Domain\nparse = do\n [n, m] <- readChar8\n xs <- replicateM n getPair\n return (m, xs)\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\nsolve :: Solver\nsolve (m, xs) = result\n where \n mapAcc = IntMap.unionsWith (+) $ (\\(x,y) -> IntMap.fromList [(x-y, 1), (x, (-2)), (x+y, 1)]) <$> xs\n heights = tail $ toHeight <$> scanl f (0, 0, 0) (IntMap.toAscList mapAcc)\n highPoints = filter ((> m) . snd) heights\n leftMost = minimum $ (+m) <$> uncurry (-) <$> highPoints\n rightMost = maximum $ (+(-m)) <$> uncurry (+) <$> highPoints\n result = (\\(x, y) -> null highPoints || x - y <= leftMost && x + y >= rightMost) <$> xs\n f (pos, ac, height) (nPos, acc) = (nPos, ac + acc, height + (nPos - pos) * ac)\n toHeight (xPos, _, height) = (xPos, height)\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'))\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\n\ntype Domain = (Int, [(Int, Int)])\ntype CoDomain = [Bool]\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . showResult\n\nparse :: IO Domain\nparse = do\n [n, m] <- readChar8\n xs <- replicateM n getPair\n return (m, xs)\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\nsolve :: Solver\nsolve (m, xs) = result\n where \n mapAcc = foldl' (\\acc (x,y) -> IntMap.unionWith (+) (IntMap.fromList [(x-y, 1), (x, (-2)), (x+y, 1)]) acc) IntMap.empty xs\n heights = tail $ toHeight <$> scanl f (0, 0, 0) (IntMap.toAscList mapAcc)\n highPoints = filter ((> m) . snd) heights\n leftMost = minimum $ (+m) <$> uncurry (-) <$> highPoints\n rightMost = maximum $ (+(-m)) <$> uncurry (+) <$> highPoints\n result = (\\(x, y) -> null highPoints || x - y <= leftMost && x + y >= rightMost) <$> xs\n f (pos, ac, height) (nPos, acc) = (nPos, ac + acc, height + (nPos - pos) * ac)\n toHeight (xPos, _, height) = (xPos, height)\n\nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'))\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\n\ntype Domain = (Int, [(Int, Int)])\ntype CoDomain = [Bool]\ntype Solver = Domain -> CoDomain\n\n-- x in a \n-- (x, y, a, b)\n-- (start x, end x, start y, y per x unit )\ntype Segment = (Int, Int, Int, Int)\n\nlookupSegGT :: Segment -> Set Segment -> Maybe Segment\nlookupSegGT = goNothing\n where\n goNothing !_ Tip = Nothing\n goNothing x (Bin _ y l r) | (getEnd x) < (getEnd y) = goJust x y l\n | otherwise = goNothing x r\n goJust !_ best Tip = Just best\n goJust x best (Bin _ y l r) | (getEnd x) < (getEnd y) = goJust x y l\n | otherwise = goJust x best r\n\nlookupIndexLt :: Segment -> Set Segment -> Int\nlookupIndexLt x s = case Set.lookupLE x s of\n Just e -> fromJust $ Set.lookupIndex e s\n Nothing -> 0\n\nlookupIndexGt :: Segment -> Set Segment -> Int\nlookupIndexGt x s = case lookupSegGT x s of\n Just e -> 1 + fromJust (Set.lookupIndex e s)\n Nothing -> length s \n\nsplitSeg :: Segment -> Set Segment -> (Set Segment, Set Segment, Set Segment)\nsplitSeg x s = case Set.splitAt (lookupIndexLt x s) s of\n (l, xs) -> case Set.splitAt (lookupIndexGt x xs) xs of\n (overlap, r) -> (l, overlap, r)\n\nnotEmpty :: Segment -> Bool\nnotEmpty (x, y, a, b) = (x /= y) && (a /= 0 || b /= 0)\n\n-- add two segments that intersected\naddOrdered :: Segment -> (Segment, [Segment]) -> (Segment, [Segment])\naddOrdered a (b, acc) = case mergeSegment a b of\n (x, y) -> (x, y++acc)\n\nnegateSeg :: Segment -> Segment\nnegateSeg (x, y, a, b) = (x, y, -a, -b)\n\n-- leave the right most part there\nmergeSegment :: Segment -> Segment -> (Segment, [Segment])\nmergeSegment a@(x1, y1, a1, b1) b@(x2, y2, a2, b2) \n -- a b\n | y1 <= x2 = (a, [b])\n -- b a\n | y2 <= x1 = mergeSegment b a\n -- a contains b\n -- as : bs, bs be; be ae\n | x1 <= x2 && y1 >= y2 = ((x1,x2,a1,b1), [(x2,y2,(x2-x1)*b1+a1+a2,b1+b2),(y2,y1,(y2-x1)*b1+a1,b1)])\n -- b contains a\n | x2 <= x1 && y2 >= y1 = mergeSegment b a\n -- insert a b\n | x1 <= x2 = ((x1,x2,a1,b1), ([(x2, y1, (x2-x1)*b1+a1+a2, b1+b2), (y1,y2,(y1-x2)*b2+a2, b2)]))\n | otherwise = mergeSegment b a\n\n-- maintain none overlapping segments\ntoSegments :: Int -> Int -> [Segment]\ntoSegments x p = [(x-p, x, 0, 1), (x, x + p, p, -1)]\n\n-- find the left end pos, find the right end pos\n-- merge all inner segments\naddSegment :: Segment -> Set Segment -> Set Segment\naddSegment x s = case (splitSeg x s) of \n (l, overlap, r) -> Set.fromAscList $ Set.toAscList l ++ insertSegment x (Set.toAscList overlap) ++ Set.toAscList r\n where \n insertSegment :: Segment -> [Segment] -> [Segment]\n insertSegment s xs = filter notEmpty $ uncurry (:) $ foldr addOrdered (s, []) xs\n\n\n-- xs - ys\nremoveSegments :: Set Segment -> [Segment] -> Set Segment\nremoveSegments xs ys = foldr subSegment xs ys\n where \n subSegment :: Segment -> Set Segment -> Set Segment\n subSegment s xs = addSegment (negateSeg s) xs\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . showResult\n\nparse :: IO Domain\nparse = do\n [n, m] <- readChar8\n xs <- replicateM n getPair\n return (m, xs)\n\n-- solveOne :: Int -> Int -> Int -> [Int] -> Bool\n-- solveOne total n m xs = (not (null ks) && (maximum ks) > 2 || even m) && sum ks >= m \n-- where ks = filter (>1) $ map (`div` n) xs\n\ngetStart :: Segment -> Int\ngetStart (x, _, _, _) = x\n\ngetEnd :: Segment -> Int\ngetEnd (_, y, _, _) = y\n\ngetStartHeight :: Segment -> Int\ngetStartHeight (_, _, a, _) = a\n\ngetEndHeight :: Segment -> Int\ngetEndHeight (x1, x2, a, b) = a + (x2-x1) * b\n\ngetHeight :: Segment -> Int\ngetHeight s = max (getStartHeight s) (getEndHeight s)\n\ncontainsPoint :: Int -> (Int, Int) -> Bool\ncontainsPoint x (a,b) = a - b <= x && x <= a + b\n\ngetHighest :: Set Segment -> Maybe Segment\ngetHighest xs = if Set.null xs \n then Nothing \n else Just $ maximumBy (comparing getHeight) $ Set.toAscList xs\n\ngetHeightPos :: Segment -> Int\ngetHeightPos (x1, x2, _, b)\n | b >= 0 = x2\n | otherwise = x1\n\n-- (Height, height of the position)\ncomputeHighPoint :: Set Segment -> (Int, Int)\ncomputeHighPoint xs = case getHighest xs of\n Just seg -> (getHeight seg, getHeightPos seg) \n Nothing -> (0, 0)\n\ncomputeHigh :: Set Segment -> Int\ncomputeHigh = fst . computeHighPoint\n\n\n-- remove seg, height lower than m after removal\nsolveOne :: (Int,Int) -> Int -> Set Segment -> (Int, Int) -> Bool\nsolveOne (height, hightPos) m merged xs = (height <= m) || (containsPoint hightPos xs && (computeHigh $ removeSegments merged $ uncurry toSegments xs) <= m)\n\nshowResult :: [Bool] -> String\nshowResult xs = map (bool '0' '1') xs\n\n\n\nsolve :: Solver\nsolve (m, xs) = result\n where \n mapAcc = foldl' (\\acc (x,y) -> IntMap.unionWith (+) (IntMap.fromList [(x-y, 1), (x, (-2)), (x+y, 1)]) acc) IntMap.empty xs\n heights = tail $ toHeight <$> scanl f (0, 0, 0) (IntMap.toAscList mapAcc)\n highPoints = filter ((> m) . snd) heights\n leftMost = minimum $ (+m) <$> uncurry (-) <$> highPoints\n rightMost = maximum $ (+(-m)) <$> uncurry (+) <$> highPoints\n result = (\\(x, y) -> null highPoints || x - y <= leftMost && x + y >= rightMost) <$> xs\n f (pos, ac, height) (nPos, acc) = (nPos, ac + acc, height + (nPos - pos) * ac)\n toHeight (xPos, _, height) = (xPos, height)\n\n\n \n\nsolve1 :: Solver\nsolve1 (m, xs) = \n -- traceShow (m, xs, segments, computeHighPoint merged, ys) \n results \n where \n segments = concatMap (uncurry toSegments) xs\n merged = foldr addSegment Set.empty segments\n (height, hightPos) = computeHighPoint merged\n -- ys = (computeHigh . removeSegments merged . uncurry toSegments) <$> xs\n ys = traceShowId <$> (id &&& computeHigh) <$> (removeSegments merged . uncurry toSegments) <$> xs\n -- containsPointSegments = uncurry toSegments <$> filter (containsPoint hightPos) xs\n results = solveOne (height, hightPos) m merged <$> xs\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\n\ntype Domain = (Int, [(Int, Int)])\ntype CoDomain = [Bool]\ntype Solver = Domain -> CoDomain\n\n-- x in a \n-- (x, y, a, b)\n-- (start x, end x, start y, y per x unit )\ntype Segment = (Int, Int, Int, Int)\n\nlookupSegGT :: Segment -> Set Segment -> Maybe Segment\nlookupSegGT = goNothing\n where\n goNothing !_ Tip = Nothing\n goNothing x (Bin _ y l r) | (getEnd x) < (getEnd y) = goJust x y l\n | otherwise = goNothing x r\n goJust !_ best Tip = Just best\n goJust x best (Bin _ y l r) | (getEnd x) < (getEnd y) = goJust x y l\n | otherwise = goJust x best r\n\nlookupIndexLt :: Segment -> Set Segment -> Int\nlookupIndexLt x s = case Set.lookupLE x s of\n Just e -> fromJust $ Set.lookupIndex e s\n Nothing -> 0\n\nlookupIndexGt :: Segment -> Set Segment -> Int\nlookupIndexGt x s = case lookupSegGT x s of\n Just e -> 1 + fromJust (Set.lookupIndex e s)\n Nothing -> length s \n\nsplitSeg :: Segment -> Set Segment -> (Set Segment, Set Segment, Set Segment)\nsplitSeg x s = case Set.splitAt (lookupIndexLt x s) s of\n (l, xs) -> case Set.splitAt (lookupIndexGt x xs) xs of\n (overlap, r) -> (l, overlap, r)\n\nnotEmpty :: Segment -> Bool\nnotEmpty (x, y, a, b) = (x /= y) && (a /= 0 || b /= 0)\n\n-- add two segments that intersected\naddOrdered :: Segment -> (Segment, [Segment]) -> (Segment, [Segment])\naddOrdered a (b, acc) = case mergeSegment a b of\n (x, y) -> (x, y++acc)\n\nnegateSeg :: Segment -> Segment\nnegateSeg (x, y, a, b) = (x, y, -a, -b)\n\n-- leave the right most part there\nmergeSegment :: Segment -> Segment -> (Segment, [Segment])\nmergeSegment a@(x1, y1, a1, b1) b@(x2, y2, a2, b2) \n -- a b\n | y1 <= x2 = (a, [b])\n -- b a\n | y2 <= x1 = mergeSegment b a\n -- a contains b\n -- as : bs, bs be; be ae\n | x1 <= x2 && y1 >= y2 = ((x1,x2,a1,b1), [(x2,y2,(x2-x1)*b1+a1+a2,b1+b2),(y2,y1,(y2-x1)*b1+a1,b1)])\n -- b contains a\n | x2 <= x1 && y2 >= y1 = mergeSegment b a\n -- insert a b\n | x1 <= x2 = ((x1,x2,a1,b1), ([(x2, y1, (x2-x1)*b1+a1+a2, b1+b2), (y1,y2,(y1-x2)*b2+a2, b2)]))\n | otherwise = mergeSegment b a\n\n-- maintain none overlapping segments\ntoSegments :: Int -> Int -> [Segment]\ntoSegments x p = [(x-p, x, 0, 1), (x, x + p, p, -1)]\n\n-- find the left end pos, find the right end pos\n-- merge all inner segments\naddSegment :: Segment -> Set Segment -> Set Segment\naddSegment x s = case (splitSeg x s) of \n (l, overlap, r) -> Set.fromAscList $ Set.toAscList l ++ insertSegment x (Set.toAscList overlap) ++ Set.toAscList r\n where \n insertSegment :: Segment -> [Segment] -> [Segment]\n insertSegment s xs = filter notEmpty $ uncurry (:) $ foldr addOrdered (s, []) xs\n\n\n-- xs - ys\nremoveSegments :: Set Segment -> [Segment] -> Set Segment\nremoveSegments xs ys = foldr subSegment xs ys\n where \n subSegment :: Segment -> Set Segment -> Set Segment\n subSegment s xs = addSegment (negateSeg s) xs\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap read . words <$> getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . showResult\n\nparse :: IO Domain\nparse = do\n [n, m] <- readChar8\n xs <- replicateM n getPair\n return (m, xs)\n\n-- solveOne :: Int -> Int -> Int -> [Int] -> Bool\n-- solveOne total n m xs = (not (null ks) && (maximum ks) > 2 || even m) && sum ks >= m \n-- where ks = filter (>1) $ map (`div` n) xs\n\ngetStart :: Segment -> Int\ngetStart (x, _, _, _) = x\n\ngetEnd :: Segment -> Int\ngetEnd (_, y, _, _) = y\n\ngetStartHeight :: Segment -> Int\ngetStartHeight (_, _, a, _) = a\n\ngetEndHeight :: Segment -> Int\ngetEndHeight (x1, x2, a, b) = a + (x2-x1) * b\n\ngetHeight :: Segment -> Int\ngetHeight s = max (getStartHeight s) (getEndHeight s)\n\ncontainsPoint :: Int -> (Int, Int) -> Bool\ncontainsPoint x (a,b) = a - b <= x && x <= a + b\n\ngetHighest :: Set Segment -> Segment\ngetHighest xs = maximumBy (comparing getHeight) $ Set.toAscList xs\n\ngetHeightPos :: Segment -> Int\ngetHeightPos (x1, x2, _, b)\n | b >= 0 = x2\n | otherwise = x1\n\n-- (Height, height of the position)\ncomputeHighPoint :: Set Segment -> (Int, Int)\ncomputeHighPoint xs = (getHeight seg, getHeightPos seg) where seg = getHighest xs\n\ncomputeHigh :: Set Segment -> Int\ncomputeHigh = fst . computeHighPoint\n\n\n-- remove seg, height lower than m after removal\nsolveOne :: Int -> Int -> Set Segment -> (Int, Int) -> Bool\nsolveOne hightPoint m merged xs = containsPoint hightPoint xs && (computeHigh $ removeSegments merged $ uncurry toSegments xs) <= m\n\nshowResult :: [Bool] -> String\nshowResult xs = map (bool '0' '1') xs\n\nsolve :: Solver\nsolve (m, xs) = \n -- traceShow (xs, segments, computeHighPoint merged, ys) \n results \n where \n segments = concatMap (uncurry toSegments) xs\n merged = foldr addSegment Set.empty segments\n hightPos = snd $ computeHighPoint merged\n -- ys = (computeHigh . removeSegments merged . uncurry toSegments) <$> xs\n -- ys = traceShowId <$> (id &&& computeHigh) <$> (removeSegments merged . uncurry toSegments) <$> xs\n -- containsPointSegments = uncurry toSegments <$> filter (containsPoint hightPos) xs\n results = solveOne hightPos m merged <$> xs\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\n\ntype Domain = (Int, [(Int, Int)])\ntype CoDomain = [Bool]\ntype Solver = Domain -> CoDomain\n\n-- x in a \n-- (x, y, a, b)\n-- (start x, end x, start y, y per x unit )\ntype Segment = (Int, Int, Int, Int)\n\nlookupSegGT :: Segment -> Set Segment -> Maybe Segment\nlookupSegGT = goNothing\n where\n goNothing !_ Tip = Nothing\n goNothing x (Bin _ y l r) | (getEnd x) < (getEnd y) = goJust x y l\n | otherwise = goNothing x r\n goJust !_ best Tip = Just best\n goJust x best (Bin _ y l r) | (getEnd x) < (getEnd y) = goJust x y l\n | otherwise = goJust x best r\n\nlookupIndexLt :: Segment -> Set Segment -> Int\nlookupIndexLt x s = case Set.lookupLE x s of\n Just e -> fromJust $ Set.lookupIndex e s\n Nothing -> 0\n\nlookupIndexGt :: Segment -> Set Segment -> Int\nlookupIndexGt x s = case lookupSegGT x s of\n Just e -> 1 + fromJust (Set.lookupIndex e s)\n Nothing -> length s \n\nsplitSeg :: Segment -> Set Segment -> (Set Segment, Set Segment, Set Segment)\nsplitSeg x s = case Set.splitAt (lookupIndexLt x s) s of\n (l, xs) -> case Set.splitAt (lookupIndexGt x xs) xs of\n (overlap, r) -> (l, overlap, r)\n\nnotEmpty :: Segment -> Bool\nnotEmpty (x, y, _, _) = not $ x == y\n\n-- add two segments that intersected\naddOrdered :: Segment -> (Segment, [Segment]) -> (Segment, [Segment])\naddOrdered a (b, acc) = case mergeSegment a b of\n (x, y) -> (x, y++acc)\n\nnegateSeg :: Segment -> Segment\nnegateSeg (x, y, a, b) = (x, y, -a, -b)\n\n\n-- leave the right most part there\nmergeSegment :: Segment -> Segment -> (Segment, [Segment])\nmergeSegment a@(x1, y1, a1, b1) b@(x2, y2, a2, b2) \n -- a b\n | y1 <= x2 = (a, [b])\n -- b a\n | y2 <= x1 = mergeSegment b a\n -- a contains b\n -- as : bs, bs be; be ae\n | x1 <= x2 && y1 >= y2 = ((x1,x2,a1,b1), [(x2,y2,(x2-x1)*b1+a1+a2,b1+b2),(y2,y1,(y2-x1)*b1+a1,b1)])\n -- b contains a\n | x2 <= x1 && y2 >= y1 = mergeSegment b a\n -- insert a b\n | x1 <= x2 = ((x1,x2,a1,b1), ([(x2, y1, (x2-x1)*b1+a1+a2, b1+b2), (y1,y2,(y1-x2)*b2+a2, b2)]))\n | otherwise = mergeSegment b a\n\n\n-- maintain none overlapping segments\ntoSegments :: Int -> Int -> [Segment]\ntoSegments x p = [(x-p, x, 0, 1), (x, x + p, p, -1)]\n\n\n\n-- find the left end pos, find the right end pos\n-- merge all inner segments\naddSegment :: Segment -> Set Segment -> Set Segment\naddSegment x s = case (splitSeg x s) of \n (l, overlap, r) -> Set.fromAscList $ Set.toAscList l ++ insertSegment x (Set.toAscList overlap) ++ Set.toAscList r\n where \n insertSegment :: Segment -> [Segment] -> [Segment]\n insertSegment s xs = filter notEmpty $ uncurry (:) $ foldr addOrdered (s, []) xs\n\n\n-- xs - ys\nremoveSegments :: Set Segment -> [Segment] -> Set Segment\nremoveSegments xs ys = foldr subSegment xs ys\n where \n subSegment :: Segment -> Set Segment -> Set Segment\n subSegment s xs = addSegment (negateSeg s) xs\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap read . words <$> getLine\n\ngetPair :: IO (Int, Int)\ngetPair = do\n [a, b] <- readChar8\n return (a, b)\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . showResult\n\nparse :: IO Domain\nparse = do\n [n, m] <- readChar8\n xs <- replicateM n getPair\n return (m, xs)\n\n-- solveOne :: Int -> Int -> Int -> [Int] -> Bool\n-- solveOne total n m xs = (not (null ks) && (maximum ks) > 2 || even m) && sum ks >= m \n-- where ks = filter (>1) $ map (`div` n) xs\n\ngetStart :: Segment -> Int\ngetStart (x, _, _, _) = x\n\ngetEnd :: Segment -> Int\ngetEnd (_, y, _, _) = y\n\ngetStartHeight :: Segment -> Int\ngetStartHeight (_, _, a, _) = a\n\ngetEndHeight :: Segment -> Int\ngetEndHeight (x1, x2, a, b) = a + (x2-x1) * b\n\ngetHeight :: Segment -> Int\ngetHeight s = max (getStartHeight s) (getEndHeight s)\n\ncontainsPoint :: Int -> (Int, Int) -> Bool\ncontainsPoint x (a,b) = a - b <= x && x <= a + b\n\ngetHighest :: Set Segment -> Segment\ngetHighest xs = maximumBy (comparing getHeight) $ Set.toAscList xs\n\ngetHeightPos :: Segment -> Int\ngetHeightPos (x1, x2, _, b)\n | b >= 0 = x2\n | otherwise = x1\n\n-- (Height, height of the position)\ncomputeHighPoint :: Set Segment -> (Int, Int)\ncomputeHighPoint xs = (getHeight seg, getHeightPos seg) where seg = getHighest xs\n\ncomputeHigh :: Set Segment -> Int\ncomputeHigh = fst . computeHighPoint\n\n-- remove seg, height lower than m\nsolveOne :: Int -> Int -> Set Segment -> (Int, Int) -> Bool\nsolveOne hightPoint m merged xs = containsPoint hightPoint xs && (computeHigh $ removeSegments merged $ uncurry toSegments xs) > m\n\nshowResult :: [Bool] -> String\nshowResult xs = map (bool '1' '0') xs\n\nsolve :: Solver\nsolve (m, xs) = results -- ++ show xs ++ \":\" -- ++ show containsPointSegments \n where \n merged = foldr addSegment Set.empty (concatMap (uncurry toSegments) xs)\n hightPoint = snd $ computeHighPoint merged\n containsPointSegments = uncurry toSegments <$> filter (containsPoint hightPoint) xs\n results = solveOne hightPoint m merged <$> xs\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n"}], "src_uid": "268cf03c271d691c3c1e3922e884753e"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n _ <- C.getLine\n let f j i = intDec j `mappend` charUtf8 ' ' `mappend` intDec (2 * i - 1) `mappend` charUtf8 ' ' `mappend` intDec (2 * i) `mappend` charUtf8 '\\n'\n func i = f 1 i `mappend` f 2 i `mappend` f 1 i `mappend` f 2 i `mappend` f 1 i `mappend` f 2 i\n result = mconcat [func i | i <- [1 .. n `div` 2]]\n return $ intDec (3 * n) `mappend` charUtf8 '\\n' `mappend` result\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n _a <- readInts\n let\n n2 = div n 2\n putInts [n2 * 6]\n forM_ [1 .. n2] $ \\iv -> replicateM_ 2 $ do\n putInts [1, iv*2 - 1, iv*2]\n putInts [2, iv*2 - 1, iv*2]\n putInts [1, iv*2 - 1, iv*2]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "980d2b3b6b80358b3757db8fe19e8287"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\n\nimport Data.Word (Word8)\nimport Data.Int (Int64)\nimport qualified Data.Bits as Bits\nimport qualified Data.Char as Char\n\nimport Data.List as L\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\n\nimport qualified Data.ByteString as Bs\nimport qualified System.IO as Io\n--import Data.IntSet\n\nfill :: Map.Map (Int, Int) Int -> Int -> Int -> Int -> Int -> Int -> Map.Map (Int, Int) Int\nfill m xmax cnt a x y \n | cnt == 1 && not memb = newmap\n | left = if memb then fill m xmax cnt a x (y-1) else fill newmap xmax (cnt-1) a x (y-1)\n | down = if memb then fill m xmax cnt a (x+1) y else fill newmap xmax (cnt-1) a (x+1) y\n | right = if memb then fill m xmax cnt a x (y+1) else fill newmap xmax (cnt-1) a x (y+1)\n | otherwise = error \"nowhere to go\"\n where memb = Map.member (x, y) m\n left = y > 1 && Map.notMember (x, y-1) m\n right = y < x && Map.notMember (x, y+1) m\n down = x < xmax && Map.notMember (x+1, y) m\n newmap = Map.insert (x, y) a m\n \n \nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n xs <- readInts :: IO [Int]\n let res = foldl (\\m (x, i) -> fill m n x x i i) Map.empty $ zip xs [1..n]\n lines = [zip (repeat i) [1..i] | i <- [1..n]]\n sol = intercalate \"\\n\" $ map (intercalate \" \" . map (\\k -> show . Map.findWithDefault 0 k $ res)) lines\n in putStrLn sol\n\n \nmain = do\n let t = 1\n replicateM_ t $ solve\n\n----------------------------------------------------------------------------------------\nreadrows :: (Integral a, Integral b) => b -> IO [[a]]\nreadrows 0 = return []\nreadrows n = do\n row <- readInts\n l <- readrows $ n-1\n return (row : l)\n\nparseInt :: (Integral a) => Bs.ByteString -> a\nparseInt xs = snd $ Bs.foldr (\\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs\n\nreadInts :: (Integral a) => IO [a]\nreadInts = map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine\n where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs\n\n", "positive_code": [{"source_code": "import Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nputInts :: [Int] -> Builder\nputInts xs = (mconcat $ intersperse (charUtf8 ' ') $ map intDec xs) `mappend` (charUtf8 '\\n')\n\nmain :: IO ()\nmain = do\n [n] <- getInts\n ps <- getInts\n let ps' = scanl' acc ps [1..n-1]\n where acc xs t = filter (/= t) xs\n transform cnt pss\n | cnt > n = []\n | otherwise = reverse (map head as) : transform (cnt + 1) (map tail as ++ bs)\n where (as, bs) = splitAt cnt pss\n output = mconcat $ map putInts $ transform 1 ps'\n hPutBuilder stdout output\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport Data.Bits(xor)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\n\r\nimport Data.Maybe\r\n\r\n\r\n\r\nsolve :: Integer -> [Integer] -> [[Integer]]\r\nsolve 1 [1] = [[1]]\r\nsolve 1 _ = error \"impossile\"\r\n\r\nsolve 2 [1, 2] = [[1], [2, 2]]\r\nsolve 2 [2, 1] = [[2], [2, 1]]\r\nsolve 2 _ = error \"impossible\"\r\n\r\nsolve n diag = [diag !! 0] : fmap (\\(i, j) -> (fmap (+1) j)++[i]) (zip (tail diag) solution) where\r\n\tsolution = solve (n-1) $ fmap (\\i->i-1) $ filter (/=1) diag\r\n\r\nshowR :: [[Integer]] -> String\r\nshowR (x:xs) = foldr (\\i s->show i ++ \" \" ++ s) \"\\n\" x ++ showR xs\r\nshowR [] = []\r\n\r\n\r\nmain = do \r\n\tlet t = 1 -- t <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tdiag <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tputStr $ showR $ solve n diag"}], "negative_code": [], "src_uid": "5e95cb608bca3c3e9fc581b97f0dbc65"} {"source_code": "import qualified Data.Set as S\n\ngetChunksSizes :: String -> S.Set Char -> [Int]\ngetChunksSizes xs set = go xs 0 where\n go [] acc = [acc]\n go (x : xs) acc = \n if S.member x set then acc : go xs 0\n else go xs (acc + 1)\n\nsummation :: Int -> Integer\nsummation n = x*(x + 1) `div` 2 where\n x = toInteger n\n\ngetNumSubs :: String -> S.Set Char -> Integer\ngetNumSubs xs keys = foldl (+) 0 $ map summation (getChunksSizes xs keys)\n\ngetMissingKeys :: String -> String -> S.Set Char\ngetMissingKeys xs keys = S.difference setXs setKeys where\n setXs = S.fromList xs\n setKeys = S.fromList keys\n\nmain =\n getLine >> getLine >>= \\xs ->\n concat . words <$> getLine >>= \\keys ->\n print $ getNumSubs xs (getMissingKeys xs keys)", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: String -> [Char] -> [Integer]\nsolve inp l =uncurry (:) (foldl f (0,[]) inp )\n where\n f (count,list) char\n |char `elem` l = (count+1,list)\n |otherwise = (0,count:list)\n\nc :: [Integer] -> Integer\nc =sum. map (\\x -> x*(x+1) `div` 2)\n\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n m <- getLine\n l <- (concat.words) <$>getLine\n print $ c $ solve m l\n\nmain :: IO ()\nmain = do\n routine\n"}, {"source_code": "main :: IO ()\nmain = getLine >> f <$> input >>= print\n where f (s, d) = solve d s\n\ntype Dict = String\n\ninput :: IO (String, Dict)\ninput = (,) <$> getLine <*> fmap (mconcat . words) getLine\n\nnextToken :: Dict -> String -> (String, String)\nnextToken dict = span pred . dropUntil pred\n where pred = (`elem` dict)\n dropUntil p = dropWhile $ not . p\n\nsolve :: Dict -> String -> Integer\nsolve _ [] = 0\nsolve dict s = f (fromIntegral $ length t) + solve dict r\n where (t, r) = nextToken dict s\n f l = (l + 1) * l `div` 2\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: String -> [Char] -> [Int]\nsolve inp l =uncurry (:) (foldl f (0,[]) inp )\n where\n f (count,list) char\n |char `elem` l = (count+1,list)\n |otherwise = (0,count:list)\n\nc :: [Int] -> Int\nc =sum. map (\\x -> x*(x+1) `div` 2)\n\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n m <- getLine\n l <- (concat.words) <$>getLine\n print $ c $ solve m l\n\nmain :: IO ()\nmain = do\n routine\n"}, {"source_code": "main :: IO ()\nmain = getLine >> f <$> input >>= print\n where f (s, d) = solve d s\n\ntype Dict = String\n\ninput :: IO (String, Dict)\ninput = (,) <$> getLine <*> fmap (mconcat . words) getLine\n\nnextToken :: Dict -> String -> (String, String)\nnextToken dict = span pred . dropUntil pred\n where pred = (`elem` dict)\n dropUntil p = dropWhile $ not . p\n\nsolve :: Dict -> String -> Int\nsolve _ [] = 0\nsolve dict s = f (length t) + solve dict r\n where (t, r) = nextToken dict s\n f l = (l + 1) * l `div` 2\n"}, {"source_code": "import qualified Data.Set as S\n\ngetChunksSizes :: String -> S.Set Char -> [Int]\ngetChunksSizes xs set = go xs 0 where\n go [] acc = [acc]\n go (x : xs) acc = \n if S.member x set then acc : go xs 0\n else go xs (acc + 1)\n\nsummation :: Int -> Int\nsummation n = n*(n + 1) `div` 2\n\ngetNumSubs :: String -> S.Set Char -> Int\ngetNumSubs xs keys = foldl (+) 0 $ map summation (getChunksSizes xs keys)\n\ngetMissingKeys :: String -> String -> S.Set Char\ngetMissingKeys xs keys = S.difference setXs setKeys where\n setXs = S.fromList xs\n setKeys = S.fromList keys\n\nmain =\n getLine >> getLine >>= \\xs ->\n concat . words <$> getLine >>= \\keys ->\n print $ getNumSubs xs (getMissingKeys xs keys)"}], "src_uid": "4c260e7c6fd9c573ee4f3b1822f3c7c3"} {"source_code": "import qualified Data.Map as M\nmain = interact $ unlines . map unwords . go . lines\ngo (h:a:n:q) = M.elems . M.foldWithKey f M.empty . M.filter (\\(c,t) -> c >= 2) $ calc (M.fromList $ l) (map words q)\n where cr s = map (\\x -> ((s,x),(0,0))) [1..99]\n l = (cr \"h\") ++ (cr \"a\")\n f k@(tm,p) (_,t) = M.insert t [g tm,show p,show t]\n g s | s == \"h\" = h\n | True = a\ncalc m q = foldl upd m q\n where upd x [st,tm,sp,k] = M.adjust f (tm,p) x\n where f (c,t') | c < 2 = (c + ik,t)\n | True = (c,t')\n ik | k == \"y\" = 1\n | True = 2\n t = read st\n p = read sp\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n hName <- getLine\n aName <- getLine\n _n <- getLine\n ttpcs <- sort.parse.words <$> getContents\n case solve hName aName ttpcs of\n [] -> return ()\n res -> putStr $ unlines res\n\ntype Time = Int\ndata Team = H | A deriving (Eq,Ord)\ntype Player = Int\ndata Color = Y | R deriving (Eq,Ord)\n\nparse :: [String] -> [(Time,Team,Player,Color)]\nparse (time:t:p:c:rest) = (read time, bool H A (t==\"h\"),read p,bool Y R (c==\"y\")) : parse rest\nparse _ = []\n\nsolve :: String -> String -> [(Time,Team,Player,Color)] -> [String]\nsolve hName aName ttpcs = go [] [] ttpcs\n where\n showTeam H = hName\n showTeam A = aName\n isLive (t0,p0) (_,t,p,_) = t0/=t || p0/=p\n go hps aps ((time,team,player,color):rest)\n | color == R = res : go hps aps (filter (isLive (team,player))rest)\n | team == H, elem player hps = res : go hps aps (filter (isLive(team,player))rest)\n | team == H = go (player:hps) aps rest\n | team == A, elem player aps = res : go hps aps (filter (isLive(team,player))rest)\n | team == A = go hps (player:aps) rest\n | otherwise = undefined\n where\n res = unwords[showTeam team, show player, show time]\n go _ _ _ = []"}, {"source_code": "import Data.Function (on)\nimport Data.List (foldl', sortBy)\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . lines\n\nsolve :: [String] -> [String]\nsolve (home:away:_:xs) = map format $ sortBy (compare `on` snd) $ M.toList\n $ M.filter isRedCard $ foldl' go M.empty xs\n where go m x = M.insertWith' f (team, number) (card, read time :: Integer) m\n where [time, team, number, card] = words x\n f (_, t) (\"y\", _) = (\"r\", t); f _ p@(\"r\", _) = p; f n _ = n\n format ((team, number), (_, time)) = unwords [ teamName team, number, show time ]\n teamName \"h\" = home; teamName _ = away\n isRedCard = (==\"r\") . fst\nsolve _ = undefined\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Map as M\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n home <- getLine\n away <- getLine\n n <- fmap read getLine\n inp <- forM [1..n] $ \\_ -> do\n [t, l, m, c] <- fmap words getLine\n return $ if l == \"h\" then (read t, home, 0, read m, head c)\n else (read t, away, 1, read m, head c)\n solve (sort inp)\n\n\nsolve :: [(Int, String, Int, Int, Char)] -> IO ()\nsolve f = foldl g (return M.empty) f >> return ()\n where\n g :: IO (M.Map (Int, Int) Int) -> (Int, String, Int, Int, Char) -> IO (M.Map (Int, Int) Int)\n g m (t, tn, b, pn, cc) = m >>= \\ma -> case M.lookup (b, pn) ma of\n Nothing -> if cc == 'r'\n then putStrLn (tn ++ \" \" ++ show pn ++ \" \" ++ show t)\n >> return (M.insert (b, pn) 2 ma)\n else return (M.insert (b, pn) 1 ma)\n Just x -> if cc == 'r'\n then if x == 1\n then putStrLn (tn ++ \" \" ++ show pn ++ \" \" ++ show t)\n >> return (M.insert (b, pn) 2 ma)\n else return ma\n else if x == 1\n then putStrLn (tn ++ \" \" ++ show pn ++ \" \" ++ show t)\n >> return (M.insert (b, pn) 2 ma)\n else return ma\n"}, {"source_code": "import Data.List (foldl', sortBy)\nimport qualified Data.Map as M\nimport Data.Function (on)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . lines\n\nsolve :: [String] -> [String]\nsolve (home:away:_:xs) = map format $ sortBy (compare `on` snd) $ M.toList\n $ M.filter ((==\"r\") . fst) $ foldl' go M.empty xs\n where go m x = M.insertWith' f (team, number) (card, read time :: Integer) m\n where [time, team, number, card] = words x\n f (_, t) (\"y\", _) = (\"r\", t)\n f _ p@(\"r\", _) = p\n f n _ = n\n format ((team, number), (_, time)) = unwords [ if team == \"h\" then home else away, number, show time ]\nsolve _ = undefined\n"}], "negative_code": [{"source_code": "import Data.List (foldl', sortBy)\nimport qualified Data.Map as M\nimport Data.Function (on)\n\nmain :: IO ()\nmain = getContents >>= mapM_ putStrLn . solve . lines\n\nsolve :: [String] -> [String]\nsolve (home:away:_:xs) = map format $ sortBy (compare `on` snd) $ M.toList\n $ M.filter ((==\"r\") . fst) $ foldl' go M.empty xs\n where go m x = M.insertWith' f (team, number) (card, read time :: Integer) m\n where [time, team, number, card] = words x\n f (_, t) (\"y\", _) = (\"r\", t)\n f n _ = n\n format ((team, number), (_, time)) = unwords [ if team == \"h\" then home else away, number, show time ]\nsolve _ = undefined\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n hName <- getLine\n aName <- getLine\n _n <- getLine\n ttpcs <- parse.words <$> getContents\n case solve hName aName ttpcs of\n [] -> return ()\n res -> putStr $ unlines res\n\ntype Time = Int\ndata Team = H | A deriving (Eq,Ord)\ntype Player = Int\ndata Color = Y | R deriving (Eq,Ord)\n\nparse :: [String] -> [(Time,Team,Player,Color)]\nparse (time:t:p:c:rest) = (read time, bool H A (t==\"h\"),read p,bool Y R (c==\"y\")) : parse rest\nparse _ = []\n\nsolve :: String -> String -> [(Time,Team,Player,Color)] -> [String]\nsolve hName aName ttpcs = go [] [] ttpcs\n where\n showTeam H = hName\n showTeam A = aName\n go hps aps ((time,team,player,color):rest)\n | color == R = res : go hps aps rest\n | team == H, elem player hps = res : go hps aps rest\n | team == H = go (player:hps) aps rest\n | team == A, elem player aps = res : go hps aps rest\n | team == A = go hps (player:aps) rest\n | otherwise = undefined\n where\n res = unwords[showTeam team, show player, show time]\n go _ _ _ = []"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n hName <- getLine\n aName <- getLine\n _n <- getLine\n ttpcs <- sort.parse.words <$> getContents\n case solve hName aName ttpcs of\n [] -> return ()\n res -> putStr $ unlines res\n\ntype Time = Int\ndata Team = H | A deriving (Eq,Ord)\ntype Player = Int\ndata Color = Y | R deriving (Eq,Ord)\n\nparse :: [String] -> [(Time,Team,Player,Color)]\nparse (time:t:p:c:rest) = (read time, bool H A (t==\"h\"),read p,bool Y R (c==\"y\")) : parse rest\nparse _ = []\n\nsolve :: String -> String -> [(Time,Team,Player,Color)] -> [String]\nsolve hName aName ttpcs = go [] [] ttpcs\n where\n showTeam H = hName\n showTeam A = aName\n f (_,_,p,_) = p\n go hps aps ((time,team,player,color):rest)\n | color == R = res : go hps aps (filter ((player/=).f)rest)\n | team == H, elem player hps = res : go hps aps (filter ((player/=).f)rest)\n | team == H = go (player:hps) aps rest\n | team == A, elem player aps = res : go hps aps (filter ((player/=).f)rest)\n | team == A = go hps (player:aps) rest\n | otherwise = undefined\n where\n res = unwords[showTeam team, show player, show time]\n go _ _ _ = []"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n hName <- getLine\n aName <- getLine\n _n <- getLine\n getContents>>=putStr.init.unlines.solve hName aName.sort.parse.words\n\ntype Time = Int\ndata Team = H | A deriving (Eq,Ord)\ntype Player = Int\ndata Color = Y | R deriving (Eq,Ord)\n\nparse :: [String] -> [(Time,Team,Player,Color)]\nparse (time:t:p:c:rest) = (read time, bool H A (t==\"h\"),read p,bool Y R (c==\"y\")) : parse rest\nparse _ = []\n\nsolve :: String -> String -> [(Time,Team,Player,Color)] -> [String]\nsolve hName aName ttpcs = go [] [] ttpcs\n where\n showTeam H = hName\n showTeam A = aName\n go hps aps ((time,team,player,color):rest)\n | color == R = res : go hps aps rest\n | team == H, elem player hps = res : go hps aps rest\n | team == H = go (player:hps) aps rest\n | team == A, elem player aps = res : go hps aps rest\n | team == A = go hps (player:aps) rest\n | otherwise = undefined\n where\n res = unwords[showTeam team, show player, show time]\n go _ _ _ = []"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n hName <- getLine\n aName <- getLine\n _n <- getLine\n getContents>>=putStr.unlines.solve hName aName.sort.parse.words\n\ntype Time = Int\ndata Team = H | A deriving (Eq,Ord)\ntype Player = Int\ndata Color = Y | R deriving (Eq,Ord)\n\nparse :: [String] -> [(Time,Team,Player,Color)]\nparse (time:t:p:c:rest) = (read time, bool H A (t==\"h\"),read p,bool Y R (c==\"y\")) : parse rest\nparse _ = []\n\nsolve :: String -> String -> [(Time,Team,Player,Color)] -> [String]\nsolve hName aName ttpcs = go [] [] ttpcs\n where\n showTeam H = hName\n showTeam A = aName\n go hps aps ((time,team,player,color):rest)\n | color == R = res : go hps aps rest\n | team == H, elem player hps = res : go hps aps rest\n | team == H = go (player:hps) aps rest\n | team == A, elem player aps = res : go hps aps rest\n | team == A = go hps (player:aps) rest\n | otherwise = undefined\n where\n res = unwords[showTeam team, show player, show time]\n go _ _ _ = []"}, {"source_code": "import Control.Monad\nimport qualified Data.Map as M\nimport Data.List (sort)\n\nmain :: IO ()\nmain = do\n home <- getLine\n away <- getLine\n n <- fmap read getLine\n inp <- forM [1..n] $ \\_ -> do\n [t, l, m, c] <- fmap words getLine\n return $ if l == \"h\" then (read t, home, read m, head c)\n else (read t, away, read m, head c)\n solve (sort inp)\n\n\nsolve :: [(Int, String, Int, Char)] -> IO ()\nsolve f = foldl g (return M.empty) f >> return ()\n where\n g :: IO (M.Map Int Int) -> (Int, String, Int, Char) -> IO (M.Map Int Int)\n g m (t, tn, pn, cc) = m >>= \\ma -> case M.lookup pn ma of\n Nothing -> if cc == 'r'\n then putStrLn (tn ++ \" \" ++ show pn ++ \" \" ++ show t)\n >> return (M.insert pn 2 ma)\n else return (M.insert pn 1 ma)\n Just x -> if cc == 'r'\n then if x == 1\n then putStrLn (tn ++ \" \" ++ show pn ++ \" \" ++ show t)\n >> return (M.insert pn 2 ma)\n else return ma\n else if x == 1\n then putStrLn (tn ++ \" \" ++ show pn ++ \" \" ++ show t)\n >> return (M.insert pn 2 ma)\n else return ma\n"}], "src_uid": "b1f78130d102aa5f425e95f4b5b3a9fb"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\ndata State a = Node (Maybe (Int, State a)) [a] (State a)\n\nmain :: IO ()\nmain = do\n [_, k] <- getInts\n str@(_ : str') <- filter (not . isSpace) . C.unpack <$> C.getLine\n let initial = Node Nothing str first\n first = Node (Just (1, initial)) str' (extend 2 initial str')\n findNext char node@(Node p s n)\n | char == head s = n\n | isJust p = findNext char (snd $ fromJust p)\n | otherwise = node\n extend _ _ [] = Node Nothing [] undefined\n extend idx prev (char : chars') = node'\n where node' = Node (Just (idx, prev')) chars' (extend (idx + 1) prev' chars')\n prev' = findNext char prev\n getIndex (Node Nothing _ _) = 0\n getIndex (Node (Just (i, _)) _ _) = i\n step node@(Node (Just (idx, prev)) [] _) _ = Left (idx - getIndex prev)\n step node@(Node (Just (idx, prev)) (char : _) next) _\n | getNextChar prev < char = Left (idx - getIndex prev)\n | otherwise = Right next\n where getNextChar (Node _ (c : _) _) = c\n getNextChar _ = error \"\"\n Left num = foldM step first $ repeat ()\n result = take k $ cycle $ take num str\n hPutBuilder stdout $ string7 result <> charUtf8 '\\n'\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\nforFoldM_ v s f = foldM_ f v s\r\n\r\nsuffixArray :: String -> UArray Int Int\r\nsuffixArray s = goSa 1 saInit rInit\r\n where\r\n n = length s\r\n saInit = listArray (0,n-1) [0..]\r\n rInit = listArray (0,n-1) (map ord s)\r\n\r\n goSa k sa r\r\n | k >= n = sa\r\n | otherwise =\r\n let\r\n sa0 = csort k sa r\r\n sa1 = csort 0 sa0 r\r\n vs = [(r ! (sa1 ! i), getR ((sa1 ! i) + k)) | i <- [0..n-1]]\r\n newR = zip (elems sa1) $ scanl (\\s (a,b) -> if a == b then s else s + 1) 0 $ zip vs (tail vs)\r\n in\r\n goSa (2*k) sa1 (array (0,n-1) newR)\r\n\r\n where\r\n getR t = if t < n then r ! t else 0\r\n\r\n csort :: Int -> UArray Int Int -> UArray Int Int -> UArray Int Int\r\n csort k sa r = runST $ do\r\n let cl = max 255 n\r\n c <- newArray (0, cl-1) 0 :: ST s (STUArray s Int Int)\r\n forM_ [0..n-1] $ \\i -> do\r\n modifyArray (+1) c (getR (i + k))\r\n forFoldM_ 0 [0..cl-1] $ \\s i -> do\r\n t <- readArray c i\r\n writeArray c i s\r\n return $ s + t\r\n\r\n rr <- forM [0..n-1] $ \\i -> do\r\n let sai = sa ! i\r\n j = getR $ sai + k\r\n t <- readArray c j\r\n writeArray c j $ t + 1\r\n return (t, sai)\r\n return $ array (0,n-1) rr\r\n\r\nzFunction :: String -> UArray Int Int\r\nzFunction s0 = runSTUArray $ do\r\n let n = length s0\r\n s = listArray (0,n-1) s0 :: UArray Int Char\r\n z <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\r\n forFoldM_ (0,0) [1..n-1] $ \\(l,r) i -> do\r\n when (i <= r) $ readArray z (i-l) >>= \\v -> writeArray z i $ min (r-i+1) v\r\n let loop = do\r\n zi <- readArray z i\r\n when (i + zi < n && (s ! zi) == (s ! (i + zi))) $ do\r\n writeArray z i (zi+1)\r\n loop\r\n loop\r\n zi <- readArray z i\r\n return $ if i + zi - 1 > r then (i,i+zi-1) else (l,r)\r\n return z\r\n\r\nsolve :: String -> Int -> String\r\nsolve s0 k =\r\n let\r\n s = s0 ++ \"~\"\r\n n = length s\r\n z = zFunction s\r\n a = listArray (0,n-1) s :: UArray Int Char\r\n l = foldr1 op [1..]\r\n op i j = if (a ! (i + (z ! i))) > (a ! (z ! i)) then i else j\r\n in\r\n take k $ cycle (take l s0)\r\n\r\nmain = do\r\n [n,k] <- map parseInt . BS.words <$> BS.getLine\r\n s <- dropWhileEnd isSpace . BS.unpack <$> BS.getLine\r\n putStrLn $ solve s k"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\r\nimport qualified Data.ByteString.Char8 as BS\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.Base\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\n\r\n(><) a b = a Seq.>< b\r\n\r\ndeb name s e = seq s unsafePerformIO $! do\r\n hPutStrLn stderr $ \" \" ++ name ++ \" = \" ++ show s\r\n return e\r\n\r\nparseInt = fst . fromJust . BS.readInt\r\nparseInteger = fst . fromJust . BS.readInteger\r\n\r\nmodifyArray f a i = readArray a i >>= \\v -> writeArray a i (f v)\r\n\r\nforFoldM_ v s f = foldM_ f v s\r\n\r\nsuffixArray :: String -> UArray Int Int\r\nsuffixArray s = goSa 1 saInit rInit\r\n where\r\n n = length s\r\n saInit = listArray (0,n-1) [0..]\r\n rInit = listArray (0,n-1) (map ord s)\r\n\r\n goSa k sa r\r\n | k >= n = sa\r\n | otherwise =\r\n let\r\n sa0 = csort k sa r\r\n sa1 = csort 0 sa0 r\r\n vs = [(r ! (sa1 ! i), getR ((sa1 ! i) + k)) | i <- [0..n-1]]\r\n newR = zip (elems sa1) $ scanl (\\s (a,b) -> if a == b then s else s + 1) 0 $ zip vs (tail vs)\r\n in\r\n goSa (2*k) sa1 (array (0,n-1) newR)\r\n\r\n where\r\n getR t = if t < n then r ! t else 0\r\n\r\n csort :: Int -> UArray Int Int -> UArray Int Int -> UArray Int Int\r\n csort k sa r = runST $ do\r\n let cl = max 255 n\r\n c <- newArray (0, cl-1) 0 :: ST s (STUArray s Int Int)\r\n forM_ [0..n-1] $ \\i -> do\r\n modifyArray (+1) c (getR (i + k))\r\n forFoldM_ 0 [0..cl-1] $ \\s i -> do\r\n t <- readArray c i\r\n writeArray c i s\r\n return $ s + t\r\n\r\n rr <- forM [0..n-1] $ \\i -> do\r\n let sai = sa ! i\r\n j = getR $ sai + k\r\n t <- readArray c j\r\n writeArray c j $ t + 1\r\n return (t, sai)\r\n return $ array (0,n-1) rr\r\n\r\nzFunction :: String -> UArray Int Int\r\nzFunction s0 = runSTUArray $ do\r\n let n = length s0\r\n s = listArray (0,n-1) s0 :: UArray Int Char\r\n z <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)\r\n forFoldM_ (0,0) [1..n-1] $ \\(l,r) i -> do\r\n when (i <= r) $ readArray z (i-1) >>= \\v -> writeArray z i $ min (r-i+1) v\r\n let loop = do\r\n zi <- readArray z i\r\n when (i + zi < n && (s ! zi) == (s ! (i + zi))) $ do\r\n writeArray z i (zi+1)\r\n loop\r\n loop\r\n zi <- readArray z i\r\n return $ if i + zi - 1 > r then (i,i+zi-1) else (l,r)\r\n return z\r\n\r\nsolve :: String -> Int -> String\r\nsolve s0 k =\r\n let\r\n s = s0 ++ \"~\"\r\n n = length s\r\n z = zFunction s\r\n a = listArray (0,n-1) s :: UArray Int Char\r\n l = foldr1 op [1..]\r\n op i j = if (a ! (i + (z ! i))) > (a ! (z ! i)) then i else j\r\n in\r\n take k $ cycle (take l s0)\r\n\r\nmain = do\r\n [n,k] <- map parseInt . BS.words <$> BS.getLine\r\n s <- dropWhileEnd isSpace . BS.unpack <$> BS.getLine\r\n putStrLn $ solve s k"}], "src_uid": "245371912e9828e763a49a85f4f6d2d9"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Maybe\nimport qualified Data.Set as S\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nparse (r:a:b:rabs) = [(r,c)|c<-[a..b]] ++ parse rabs\nparse _ = []\n\nmain = do\n [x0,y0,x1,y1] <- map read.words <$> getLine ::IO [Int]\n _ <- getLine\n gr <- parse.map readInt.B.words <$> B.getContents :: IO [(Int,Int)]\n print $ bfs (S.fromList $ (x1,y1):gr) (x0,y0) (x1,y1)\n \ntype Vertex = (Int,Int)\ntype Cost = Int\n\nbfs :: S.Set Vertex -> Vertex -> Vertex -> Cost\nbfs gr start goal = go (Q [start] []) $ M.singleton start 0\n where\n neighbors (x,y) = filter (`S.member`gr) [(x+1,y),(x+1,y+1),(x,y+1),(x-1,y+1),(x-1,y),(x-1,y-1),(x,y-1),(x+1,y-1)]\n go queue dist\n | isEmpty queue = -1\n | q == goal = fromJust $ M.lookup goal dist\n | otherwise = go (foldr enq rest nexts) $! foldl' (\\m k->M.insert k (dq+1) m) dist nexts\n where\n (q,rest) = deq queue\n dq = fromJust $ M.lookup q dist\n nexts = filter (isNothing.(`M.lookup`dist)) $ neighbors q\n \ndata Queue = Q [Vertex] [Vertex]\n\nisEmpty (Q [] []) = True\nisEmpty _ = False\n\nenq x (Q f r) = Q f (x:r)\n\ndeq (Q (f:fs) rs) = (f,Q fs rs)\ndeq (Q _ rs) = deq (Q (reverse rs) [])\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as C\n\ngao s@(sx,sy) t@(tx,ty) e =\n if M.member s d && M.member t d\n then fromJust $ M.lookup t $ bfs [s] (M.insert s 0 d)\n else -1\n where\n d = M.fromList [((i, j), -1) | [i, l, r] <- e, j <- [l .. r]]\n bfs [] d = d\n bfs (v@(x,y):vs) d = bfs (vs ++ w) $ foldl (\\i k -> M.insert k t i) d w\n where\n w = [(i, j) |\n i <- [x - 1 .. x + 1],\n j <- [y - 1 .. y + 1],\n M.lookup (i, j) d == Just (-1)]\n t = succ $ fromJust $ M.lookup v d\n\nmain = do\n [x0, y0, x1, y1] <- getArray\n [n] <- getArray\n e <- replicateM n getArray\n print $ gao (x0, y0) (x1, y1) e\n where\n getArray = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map as M\nimport Data.Maybe\nimport qualified Data.Set as S\nimport Data.STRef\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nparse (r:a:b:rabs) = [(r,c)|c<-[a..b]] ++ parse rabs\nparse _ = []\n\nmain = do\n [x0,y0,x1,y1] <- map read.words <$> getLine ::IO [Int]\n _ <- getLine\n gr <- parse.map readInt.B.words <$> B.getContents :: IO [(Int,Int)]\n print $ dijkstra ((x0,y0):(x1,y1):gr) (x0,y0) (x1,y1)\n \ntype Vertex = (Int,Int)\ntype Cost = Int\ntype Graph = S.Set (Int,Int)\n\ninf :: Cost\ninf = 1000000000\n\nneighbors (x,y) = [(x+1,y),(x+1,y+1),(x,y+1),(x-1,y+1),(x-1,y),(x-1,y-1),(x,y-1),(x+1,y-1)]\n\ndijkstra gr start goal = runST $ do\n dist <- newSTRef M.empty :: ST s (STRef s (M.Map Vertex Cost))\n unvisited <- newSTRef (S.fromList gr) :: ST s (STRef s (S.Set Vertex))\n let get v = do\n m <- readSTRef dist\n return $! maybe inf id $! M.lookup v m\n put v d = do\n m <- readSTRef dist\n writeSTRef dist $! M.insertWith min v d m\n isUnvisited v = do\n s <- readSTRef unvisited\n return $! S.member v s\n visit v = do\n s <- readSTRef unvisited\n writeSTRef unvisited $! S.delete v s\n\n let go heap\n | isEmpty heap = do ans <- get goal; if ans==inf then return $ -1 else return ans\n | otherwise = do\n let (v,vcost,rest) = deleteFindMin heap\n dv <- get v\n visit v\n if vcost > dv\n then go rest\n else do\n nextheap <- fmap(foldr ins rest.catMaybes).forM (neighbors v) $ \\nv -> do\n unvisited <- isUnvisited nv\n if unvisited\n then do\n let newdnv = vcost + 1\n olddnv <- get nv\n if newdnv < olddnv\n then do\n put nv newdnv\n return $ Just (nv,newdnv)\n else return Nothing\n else return Nothing\n visit v\n go nextheap\n put start 0\n visit start\n go $ ins (start,0) Empty\n\n-- Pairing heap for Dijkstra\ndata Heap = Empty | Fork !Vertex !Cost [Heap]\n\nisEmpty :: Heap -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\nins :: (Vertex, Cost) -> Heap -> Heap\nins (v,cost) h = merge (Fork v cost []) h\n\ndeleteFindMin :: Heap -> (Vertex, Cost, Heap)\ndeleteFindMin (Fork v cost hs) = (v, cost, mergePairs hs)\n\nmerge :: Heap -> Heap -> Heap\nmerge Empty hy = hy\nmerge hx Empty = hx\nmerge hx@(Fork _ x _) hy@(Fork _ y _)\n | x <= y = join hx hy\n | otherwise = join hy hx\n where\n join (Fork v cost hs) h = Fork v cost (h:hs)\n\nmergePairs :: [Heap] -> Heap\nmergePairs [] = Empty\nmergePairs [x] = x\nmergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)"}], "negative_code": [], "src_uid": "c3cbc9688594d6611fd7bdd98d9afaa0"} {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\ntype SolutionState = (IM.IntMap (Int, Int64))\n\nmergeX :: (Int, Int64) -> (Int, Int64) -> (Int, Int64)\nmergeX (cnt1, s1) (cnt2, s2) = (cnt1 + cnt2, s1 + s2)\n\npreSolve :: Int -> [Int] -> SolutionState\npreSolve n as = L.foldr (\\x mp -> IM.insertWith mergeX (x `mod` 2) (1, fromIntegral x) mp) emptyState as\n where\n emptyState :: SolutionState\n emptyState = IM.fromList [(0, (0, 0)), (1, (0, 0))]\n\nquery :: (Monad m) => Int -> Int -> MS.StateT SolutionState m Int64\nquery mod2 x = do\n (cnt, s) <- MS.gets (IM.! mod2)\n\n let newMod2 = (mod2 + x) `mod` 2\n MS.modify (IM.insertWith mergeX mod2 (-cnt, -s))\n MS.modify (IM.insertWith mergeX newMod2 (cnt, s))\n MS.modify (IM.insertWith mergeX newMod2 (0, fromIntegral $ x * cnt))\n\n tracingM \"mod2\" mod2\n tracingM \"x\" x\n\n (_, s0) <- MS.gets (IM.! 0) \n (_, s1) <- MS.gets (IM.! 1) \n return $ s0 + s1\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n [n, q] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntB8s\n let state = preSolve n as\n flip MS.evalStateT state . M.replicateM_ q $ do \n [mod2, x] <- MT.lift $ B8.getLine <&> readIntB8s\n tracingM \"mod2\" mod2\n tracingM \"x\" x\n answer <- query mod2 x\n MT.lift $ printf \"%lld\\n\" answer\n", "positive_code": [{"source_code": "{-# LANGUAGE RecordWildCards #-}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM, replicateM_)\r\nimport Data.List (intercalate)\r\n\r\nimport qualified Data.ByteString as B\r\nimport qualified Data.ByteString.Char8 as B\r\n\r\ndata Values = Values\r\n { valuesSum :: Int\r\n , numberEven :: Int\r\n , numberOdd :: Int\r\n }\r\n\r\ndata Query = Query\r\n { onEven :: Bool\r\n , summand :: Int\r\n }\r\n\r\ntoValues vs = Values\r\n { valuesSum = sum vs\r\n , numberEven = length $ filter even vs\r\n , numberOdd = length $ filter odd vs\r\n }\r\n\r\nprocessQuery :: Values -> Query -> Values\r\nprocessQuery Values{..} Query{..}\r\n | onEven = Values{ valuesSum = valuesSum + summand * numberEven\r\n , numberEven = if even summand then numberEven else 0\r\n , numberOdd = if even summand then numberOdd else numberEven + numberOdd\r\n }\r\n | otherwise = Values{ valuesSum = valuesSum + summand * numberOdd\r\n , numberEven = if even summand then numberEven else numberEven + numberOdd\r\n , numberOdd = if even summand then numberOdd else 0\r\n }\r\n\r\nprocessQueries :: Values -> [Query] -> [Values]\r\nprocessQueries vs qs = drop 1 $ scanl processQuery vs qs\r\n\r\nparseQuery :: IO Query\r\nparseQuery = do\r\n [e, s] <- map parseInt . B.words <$> B.getLine\r\n pure $ Query (e == 0) s\r\n\r\nhandleProblem :: IO ()\r\nhandleProblem = do\r\n [n, q] <- map parseInt . B.words <$> B.getLine\r\n vs <- toValues . map parseInt . B.words <$> B.getLine\r\n qs <- replicateM q parseQuery\r\n putStrLn $ intercalate \"\\n\" $ map (show . valuesSum) $ processQueries vs qs\r\n\r\nmain :: IO ()\r\nmain = do\r\n numberProblems <- read <$> getLine\r\n replicateM_ numberProblems handleProblem\r\n\r\nparseInt :: B.ByteString -> Int\r\nparseInt = maybe 0 fst . B.readInt\r\n"}], "negative_code": [], "src_uid": "d15cffca07768f8ce6fab7e13a6e7976"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.List (group, sort)\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\nimport Data.Word (Word64)\nimport Text.Printf (printf)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nmodulo, moduloM1 :: Word64\nmodulo = 1000000000 + 7\nmoduloM1 = modulo - 1\n\ngetLambda :: [Word64] -> [(Int, Word64)]\ngetLambda = map toPair . group . sort\n where toPair ps = (length ps, head ps)\n\nprefixModulo, suffixModulo :: [(Int, Word64)] -> [Word64]\nprefixModulo = scanl update 1\n where update pl (pr, _) = (pl * (fromIntegral $ pr + 1)) `mod` moduloM1\nsuffixModulo = scanr update 1\n where update (pl, _) pr = ((fromIntegral $ pl + 1) * pr) `mod` moduloM1\n\nmodPow, modMul :: Word64 -> Word64 -> Word64\nmodPow a 0 = 1\nmodPow a n | even n = c\n | otherwise = a `modMul` c\n where b = a `modPow` (n `div` 2)\n c = b `modMul` b\nmodMul a b = (a * b) `mod` modulo\n\nsolve :: [Word64] -> Word64\nsolve ps = foldr modMul 1 $ zipWith3 calc ls pm sm\n where ls = getLambda ps\n pm = prefixModulo ls\n sm = tail $ suffixModulo ls\n\n calc :: (Int, Word64) -> Word64 -> Word64 -> Word64\n calc (l, p) pref suff = foldr modMul 1 powers\n where s = (pref * suff) `mod` moduloM1\n m = modPow p s\n powers = take (l + 1) $ iterate (`modMul` m) 1\n\ntype Tokenizer = State [Int]\n\nparseInt :: L.ByteString -> Int\nparseInt = fst . fromJust . L.readInt\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> (s, ss)\n\nnextWord64 :: Tokenizer Word64\nnextWord64 = state $ \\(s:ss) -> (fromIntegral s, ss)\n\ngo :: Tokenizer Word64\ngo = do\n n <- nextInt\n ps <- replicateM n nextWord64\n return $ solve ps\n\nmain :: IO ()\nmain = do\n input <- liftM (map parseInt . L.words) L.getContents\n print $ evalState go input\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.List (group, sort)\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\nimport Text.Printf (printf)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nmodulo, moduloM1 :: Integer\nmodulo = 1000000000 + 7\nmoduloM1 = modulo - 1\n\ngetLambda :: [Integer] -> [(Int, Integer)]\ngetLambda = map toPair . group . sort\n where toPair ps = (length ps, head ps)\n\nprefixModulo, suffixModulo :: [(Int, Integer)] -> [Integer]\nprefixModulo = scanl update 1\n where update pl (pr, _) = (pl * (fromIntegral $ pr + 1)) `mod` moduloM1\nsuffixModulo = scanr update 1\n where update (pl, _) pr = ((fromIntegral $ pl + 1) * pr) `mod` moduloM1\n\nmodPow, modMul :: Integer -> Integer -> Integer\nmodPow a 0 = 1\nmodPow a n | even n = c\n | otherwise = a `modMul` c\n where b = a `modPow` (n `div` 2)\n c = b `modMul` b\nmodMul a b = (a * b) `mod` modulo\n\nsolve :: [Integer] -> Integer\nsolve ps = foldr modMul 1 $ zipWith3 calc ls pm sm\n where ls = getLambda ps\n pm = prefixModulo ls\n sm = tail $ suffixModulo ls\n\n calc :: (Int, Integer) -> Integer -> Integer -> Integer\n calc (l, p) pref suff = foldr modMul 1 powers\n where s = (pref * suff) `mod` moduloM1\n m = modPow p s\n powers = take (l + 1) $ iterate (`modMul` m) 1\n\ntype Tokenizer = State [Int]\n\nparseInt :: L.ByteString -> Int\nparseInt = fst . fromJust . L.readInt\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> (s, ss)\n\nnextInteger :: Tokenizer Integer\nnextInteger = state $ \\(s:ss) -> (fromIntegral s, ss)\n\ngo :: Tokenizer Integer\ngo = do\n n <- nextInt\n ps <- replicateM n nextInteger\n return $ solve ps\n\nmain :: IO ()\nmain = do\n input <- liftM (map parseInt . L.words) L.getContents\n print $ evalState go input\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.State\nimport Data.List (group, sort)\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\nimport Text.Printf (printf)\nimport qualified Data.ByteString.Lazy.Char8 as L\n\nmodulo, moduloM1 :: Int\nmodulo = 1000000000 + 7\nmoduloM1 = modulo - 1\n\ngetLambda :: [Int] -> [(Int, Int)]\ngetLambda = map toPair . group . sort\n where toPair ps = (length ps, head ps)\n\nprefixModulo, suffixModulo :: [(Int, Int)] -> [Int]\nprefixModulo = scanl update 1\n where update pl (pr, _) = (pl * (pr + 1)) `mod` moduloM1\nsuffixModulo = scanr update 1\n where update (pl, _) pr = ((pl + 1) * pr) `mod` moduloM1\n\nmodPow, modMul :: Int -> Int -> Int\nmodPow a 0 = 1\nmodPow a n | even n = c\n | otherwise = a `modMul` c\n where b = a `modPow` (n `div` 2)\n c = b `modMul` b\nmodMul a b = (a * b) `mod` modulo\n\nsolve :: [Int] -> Int\nsolve ps = foldr modMul 1 $ zipWith3 calc ls pm sm\n where ls = getLambda ps\n pm = prefixModulo ls\n sm = tail $ suffixModulo ls\n\n calc :: (Int, Int) -> Int -> Int -> Int\n calc (l, p) pref suff = foldr modMul 1 powers\n where s = (pref * suff) `mod` moduloM1\n m = modPow p s\n powers = take (l + 1) $ iterate (`modMul` m) 1\n\ntype Tokenizer = State [Int]\n\nparseInt :: L.ByteString -> Int\nparseInt = fst . fromJust . L.readInt\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> (s, ss)\n\ngo :: Tokenizer Int\ngo = do\n n <- nextInt\n ps <- replicateM n nextInt\n return $ solve ps\n\nmain :: IO ()\nmain = do\n input <- liftM (map parseInt . L.words) L.getContents\n print $ evalState go input\n"}], "src_uid": "9a5bd9f937da55c3d26d5ecde6e50280"} {"source_code": "\nimport Array\nimport Data.Set\nimport Monad (liftM)\nimport Prelude hiding (filter)\n\nparseFirstLine :: String -> (Int, Int, Char)\nparseFirstLine line = case words line of\n [w1, w2, w3] -> (read w1, read w2, head w3)\n\nparsePlane :: (Int, Int) -> [String] -> Array (Int, Int) Char\nparsePlane (n, m) lines = accumArray (flip const) '.' ((0, 0), (n+1, m+1))\n [((i,j), lines !! (i-1) !! (j-1)) | i <- [1..n], j <- [1..m]]\n\nsolve :: (Int, Int) -> Char -> Array (Int, Int) Char -> Int\nsolve (n, m) c array = size . fromList $ list\n where\n list = [array ! (i, j) | i <- [1..n], j <- [1..m],\n array ! (i,j) /= '.',\n array ! (i,j) /= c,\n any (\\(di, dj) -> array ! (i+di,j+dj) == c) [(0,1),(1,0),(0,-1),(-1,0)]]\n\nmain :: IO ()\nmain = do\n (n, m, c) <- liftM parseFirstLine getLine\n plane <- liftM (parsePlane (n, m) . take n . lines) getContents\n print $ solve (n, m) c plane\n", "positive_code": [{"source_code": "import Data.Char\nimport Data.List\nimport Data.Array.Unboxed\nmain = do\n [n', m', l'] <- words `fmap` getLine\n let color = head l'\n [n, m] = map read [n', m']\n \u0441\u0442\u0440\u043e\u043a\u0438 <- mapM (\\_ -> (\\s' -> let s = take m s' in (any (==color) s, s))\n `fmap` getLine) [1..n]\n let \u0441\u0442\u0440\u043e\u043a\u0438\u0411\u043e\u0441\u0441\u0430 = map fst $ filter snd $ zip [1..] $ map fst \u0441\u0442\u0440\u043e\u043a\u0438\n \u043c\u0430\u0442\u0440 = listArray ((1,1),(n, m)) $ concat $ map snd \u0441\u0442\u0440\u043e\u043a\u0438 :: UArray (Int, Int) Char\n (\u043c\u0438\u043d\u0425, \u043c\u0430\u043a\u0441\u0425) = (minimum \u0441\u0442\u0440\u043e\u043a\u0438\u0411\u043e\u0441\u0441\u0430, maximum \u0441\u0442\u0440\u043e\u043a\u0438\u0411\u043e\u0441\u0441\u0430)\n (\u043c\u0438\u043d\u0423, \u043c\u0430\u043a\u0441\u0423) = (minimum a, maximum a) where \n a = filter (\\i->(==color) $ (\u043c\u0430\u0442\u0440!(\u043c\u0438\u043d\u0425, i))) [1..m]\n allx = [\u043c\u0438\u043d\u0425..\u043c\u0430\u043a\u0441\u0425]\n ally = [\u043c\u0438\u043d\u0423..\u043c\u0430\u043a\u0441\u0423]\n all = (if \u043c\u0438\u043d\u0425 > 1 then [(\u043c\u0438\u043d\u0425 - 1, i) | i <- ally] else []) ++\n (if \u043c\u0430\u043a\u0441\u0425 < n then [(\u043c\u0430\u043a\u0441\u0425 + 1, i) | i <- ally] else []) ++\n (if \u043c\u0438\u043d\u0423 > 1 then [(i, \u043c\u0438\u043d\u0423 - 1) | i <- allx] else []) ++\n (if \u043c\u0430\u043a\u0441\u0423 < m then [(i, \u043c\u0430\u043a\u0441\u0423 + 1) | i <- allx] else [])\n \u0433\u0440\u0430\u043d\u0438\u0446\u044b = map (\u043c\u0430\u0442\u0440!) all\n putStrLn $ show $ length $ nub $ filter isUpper \u0433\u0440\u0430\u043d\u0438\u0446\u044b\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\ncount :: Array (Int, Int) Char -> Char -> String\ncount a c = show . length . group . sort $ do\n let b = bounds a\n (x, y) <- range b\n guard $ a ! (x, y) == c\n idx' <- [(x+1, y), (x-1, y), (x, y-1), (x, y+1)]\n guard $ inRange b idx'\n let c' = a ! idx'\n guard $ c' /= '.' && c' /= c\n return c'\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n [nn, mm, cc] <- words . head\n let n = read nn; m = read mm; c = head cc\n xs <- concat . take n . tail\n let a = listArray ((1,1), (n,m)) xs\n return $ count a c\n\nmain = interact $ unlines . solve . lines"}, {"source_code": "module Main where\n\nimport Data.Array.IArray (listArray, (!), bounds, indices)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (sort, group)\nimport Data.Ix (inRange)\nimport Control.Monad (replicateM)\n\ntype Grid = UArray (Int, Int) Char\n\nsolve :: Grid -> Char -> Int\nsolve gr c = count . filter isViceTable $ concatMap around tablePos\n where\n tablePos = filter (\\i -> gr ! i == c) (indices gr)\n isViceTable cc = cc /= c && cc /= '.'\n count = length . group . sort\n around (x, y) = map (gr !) $ filter (inRange $ bounds gr) [ (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) ]\n\ngetGrid :: (Int, Int) -> IO Grid\ngetGrid (n, m) = do\n lines <- replicateM n getLine\n pure $ listArray ((1,1), (n, m)) (concat lines)\n\nmain :: IO ()\nmain = do\n [n, m, c] <- words <$> getLine\n grid <- getGrid (read n, read m)\n print $ solve grid (head c)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\ncount :: Array (Int, Int) Char -> Char -> String\ncount a c = show . length . group . sort $ do\n let b = bounds a\n idx@(y, x) <- range b\n guard $ a ! idx == c\n idx' <- [(y + 1, x), (y - 1,x), (y, x + 1), (y, x - 1)]\n guard $ b `inRange` idx'\n let c' = a ! idx'\n guard $ c' /= '.'\n guard $ c' /= c\n return c'\n\nsolve :: [String] -> [String]\nsolve = fmap return $ do\n [as, bs, cs] <- words . head\n let n = read as ; m = read bs ; c = head cs\n xs <- concat . take n . drop 1\n let a = listArray ((1, 1), (n, m)) xs\n return $ count a c\n\nmain = interact $ unlines . solve . lines\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Ix\nimport Data.List\nimport qualified Data.Set as Set\n\nmain = do\n (n, m, ch) <- do\n [n, m, ch] <- words `liftM` getLine\n return (read n, read m, head ch)\n\n board <- ( listArray ((1,1), (n,m)) . join ) `liftM` replicateM n getLine :: IO (UArray (Int,Int) Char)\n\n let set = foldl' (\\set (r,c) ->\n foldl' (\\set (r1,c1,r2,c2) ->\n let put r1 c1 r2 c2 set =\n if board ! (r1,c1) == ch\n then Set.insert ( board ! (r2,c2) ) set\n else set\n in if valid r1 c1 && valid r2 c2\n then put r1 c1 r2 c2 $ put r2 c2 r1 c1 set\n else set\n ) set [(r,c,r,c+1),(r,c,r+1,c)]\n ) Set.empty $ range ((1,1),(n,m))\n set' = Set.delete '.' $ Set.delete ch set\n valid r c = 1 <= r && r <= n && 1 <= c && c <= m\n\n --putStrLn $ show board\n --putStrLn $ show set\n putStrLn $ show $ Set.size set'\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Functor\nimport Control.Monad\n\ntype Room = Array (Int, Int) Color\ntype Color = Char\n\ncountDepties :: Color -> Room -> Int -> Int -> Int\ncountDepties c room mx my = length $ adjacentTo c room mx my\n\nadjacentTo :: Color -> Room -> Int -> Int -> [Color]\nadjacentTo c m mx my = nub $ concatMap f [(x, y) | x <- [0..mx], y <- [0..my]]\n where\n f (x, y) | m ! (x, y) /= c = []\n | otherwise = filter (\\d -> d /='.' && d /= c) $ map (m !) $\n up ++ down ++ left ++ right\n where\n up = if y > 0 then [(x, y - 1)] else []\n down = if y < my then [(x, y + 1)] else []\n left = if x > 0 then [(x - 1, y)] else []\n right = if x < mx then [(x + 1, y)] else []\n\nmain = do\n n':m':c':_ <- words <$> getLine\n let n = read n' - 1\n m = read m' - 1\n c = head c'\n is <- fmap concat $ forM [0..n] $ \\y -> do\n s <- getLine :: IO [Char]\n return $ zip [(x, y) | x <- [0..m]] s\n let arr = array ((0, 0), (m, n)) is\n print $ countDepties c arr m n \n"}, {"source_code": "import Data.Set (Set, (\\\\))\nimport qualified Data.Set as Set\nimport Control.Monad\nimport Data.Array.IArray\n\nneighbors :: Array (Int, Int) Char -> (Int, Int) -> [(Int, Int)]\nneighbors arr (r, c) = let try = [(r+1, c), (r-1, c), (r, c+1), (r, c-1)] in\n filter (inRange $ bounds arr) try\n\nsolve :: Array (Int, Int) Char -> Char -> Int\nsolve arr boss = Set.size . (\\\\ Set.fromList ['.', boss]) . Set.fromList . map (arr!) . concatMap (neighbors arr) . filter ((== boss) . (arr !)) . range $ bounds arr\n\nmain = do\n [r, _, color] <- words <$> getLine\n let numRows = read r\n grid <- replicateM numRows getLine\n let arr = listArray ((0, 0), (pred numRows, pred . length $ head grid)) $ join grid\n\n print $ solve arr (head color)\n return ()\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Data.Functor\nimport Control.Monad\n\ntype Room = Array (Int, Int) Color\ntype Color = Char\n\ncountDepties :: Color -> Room -> Int -> Int -> Int\ncountDepties c room mx my = length $ adjacentTo c room mx my\n\nadjacentTo :: Color -> Room -> Int -> Int -> [Color]\nadjacentTo c m mx my = nub $ concatMap f [(x, y) | x <- [0..mx], y <- [0..my]]\n where\n f (x, y) | m ! (x, y) /= c = []\n | otherwise = filter (\\d -> d /='.' && d /= c) $ map (m !) $\n up ++ down ++ left ++ right\n where\n up = if y > 0 then [(x, y - 1)] else []\n down = if y < my then [(x, y + 1)] else []\n left = if x > 0 then [(x - 1, y)] else []\n right = if x < mx then [(x + 1, y)] else []\n\nmain = do\n n':m':c':_ <- words <$> getLine\n let n = read n' - 1\n m = read m' - 1\n c = head c'\n is <- fmap concat $ forM [0..n] $ \\y -> do\n s <- getLine :: IO [Char]\n return $ zip [(x, y) | x <- [0..m]] s\n let arr = array ((0, 0), (m, n)) is\n print $ countDepties c arr m n \n\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Ix\nimport Data.List\nimport qualified Data.Set as Set\n\nmain = do\n (n, m, ch) <- do\n [n, m, ch] <- words `liftM` getLine\n return (read n, read m, head ch)\n\n board <- ( listArray ((1,1), (n,m)) . join ) `liftM` replicateM n getLine :: IO (UArray (Int,Int) Char)\n\n let set = foldl' (\\set (r,c) ->\n foldl' (\\set (r1,c1,r2,c2) ->\n let put r1 c1 r2 c2 set =\n if board ! (r1,c1) == ch\n then Set.insert ( board ! (r2,c2) ) set\n else set\n in put r1 c1 r2 c2 $ put r2 c2 r1 c1 set\n ) set [(r-1,c-1,r-1,c)\n ,(r-1,c,r,c)\n ,(r,c,r,c-1)\n ,(r,c-1,r-1,c-1)\n ]\n ) Set.empty $ range ((2,2),(n,m))\n set' = Set.delete '.' $ Set.delete ch set\n\n --putStrLn $ show board\n --putStrLn $ show set\n putStrLn $ show $ Set.size set'\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Array.Unboxed\nmain = do\n [n', m', l'] <- words `fmap` getLine\n let color = head l'\n [n, m] = map read [n', m']\n \u0441\u0442\u0440\u043e\u043a\u0438 <- mapM (\\_ -> (\\s' -> let s = take m s' in (any (==color) s, s))\n `fmap` getLine) [1..n]\n let \u0441\u0442\u0440\u043e\u043a\u0438\u0411\u043e\u0441\u0441\u0430 = map fst $ filter snd $ zip [1..] $ map fst \u0441\u0442\u0440\u043e\u043a\u0438\n \u043c\u0430\u0442\u0440 = listArray ((1,1),(n, m)) $ concat $ map snd \u0441\u0442\u0440\u043e\u043a\u0438 :: UArray (Int, Int) Char\n (\u043c\u0438\u043d\u0425, \u043c\u0430\u043a\u0441\u0425) = (minimum \u0441\u0442\u0440\u043e\u043a\u0438\u0411\u043e\u0441\u0441\u0430, maximum \u0441\u0442\u0440\u043e\u043a\u0438\u0411\u043e\u0441\u0441\u0430)\n (\u043c\u0438\u043d\u0423, \u043c\u0430\u043a\u0441\u0423) = (minimum a, maximum a) where \n a = filter (\\i->(==color) $ (\u043c\u0430\u0442\u0440!(\u043c\u0438\u043d\u0425, i))) [1..m]\n allx = [\u043c\u0438\u043d\u0425..\u043c\u0430\u043a\u0441\u0425]\n ally = [\u043c\u0438\u043d\u0423..\u043c\u0430\u043a\u0441\u0423]\n all = (if \u043c\u0438\u043d\u0425 > 1 then [(\u043c\u0438\u043d\u0425 - 1, i) | i <- ally] else []) ++\n (if \u043c\u0430\u043a\u0441\u0425 < n then [(\u043c\u0430\u043a\u0441\u0425 + 1, i) | i <- ally] else []) ++\n (if \u043c\u0438\u043d\u0423 < 1 then [(i, \u043c\u0438\u043d\u0423 - 1) | i <- allx] else []) ++\n (if \u043c\u0430\u043a\u0441\u0423 < m then [(i, \u043c\u0430\u043a\u0441\u0423 + 1) | i <- allx] else [])\n \u0433\u0440\u0430\u043d\u0438\u0446\u044b = map (\u043c\u0430\u0442\u0440!) all\n putStrLn $ show $ length $ nub $ filter isUpper \u0433\u0440\u0430\u043d\u0438\u0446\u044b\n"}, {"source_code": "module Main where\n\nimport Data.Array.IArray (listArray, (!), bounds, indices)\nimport Data.Array.Unboxed (UArray)\nimport Data.List (sort, group)\nimport Data.Ix (inRange)\n\ntype Grid = UArray (Int, Int) Char\n\nsolve :: Grid -> Char -> Int\nsolve gr c = count . filter isViceTable $ concatMap around tablePos\n where\n tablePos = filter (\\i -> gr ! i == c) (indices gr)\n isViceTable cc = cc /= c && cc /= '.'\n count = length . group . sort\n around (x, y) = map (gr !) $ filter (inRange $ bounds gr) [ (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) ]\n\nmain :: IO ()\nmain = do\n [n, m, c] <- words <$> getLine\n grid <- listArray ((1, 1), (read n, read m)) <$> getContents :: IO Grid\n print $ solve grid (head c)\n"}], "src_uid": "d7601c9bb06a6852f04957fbeae54925"} {"source_code": "--prewritten code: https://github.com/antma/algo\n{-# LANGUAGE BangPatterns, Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport qualified Data.Array.Unboxed as UA\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [Int] -> Builder\nsolve (n:a) = intDec (C.length ans) <> char7 '\\n' <> byteString ans <> char7 '\\n'\n where\n b = take n a\n x = UA.listArray (1, n) b :: UA.UArray Int Int\n loop i j last r\n | i > j = r\n | null l = r\n | d == 'L' = loop (succ i) j v (d:r)\n | d == 'R' = loop i (pred j) v (d:r)\n where\n xi = x UA.! i\n xj = x UA.! j\n l = filter ( (last < ) . fst) [(xi, 'L'), (xj, 'R')]\n (v, d) = minimum l\n ans = C.reverse $ C.pack $ loop 1 n minBound []\n \nmain :: IO ()\nmain = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents\n", "positive_code": [{"source_code": "import qualified Data.Sequence as S\nimport Data.Maybe\nimport Data.Monoid\n\n\nsHead :: S.Seq a -> Maybe a\nsHead s =case S.viewl s of\n\t((S.:<) n _) -> Just n\n\t_-> Nothing\n\nsLast :: S.Seq a -> Maybe a\nsLast s =case S.viewr s of\n\t((S.:>) _ n ) -> Just n\n\t_-> Nothing\n\nsTail :: S.Seq a -> S.Seq a\nsTail s = case S.viewl s of\n\t((S.:<) _ n) -> n\n\t_ -> S.empty\n\nsInit :: S.Seq a -> S.Seq a\nsInit s = case S.viewr s of\n\t((S.:>) n _) -> n\n\t_ -> S.empty\n\n\t\nsHeadUnsafe :: S.Seq a -> a\nsHeadUnsafe s = fromMaybe undefined $ sHead s\n\n\t\nsLastUnsafe :: S.Seq a -> a\nsLastUnsafe s = fromMaybe undefined $ sLast s\n\n\ntype Status a = (a,[Char])\ntype Situation a = (Status a,S.Seq a)\n\nstep :: Ord a => Situation a -> Either ([Char]) (Situation a)\nstep ((curr,directions),S.Empty) = Left directions\nstep ((curr,directions),seq)\n\t|curr < seqHead && curr < seqLast = \n\tif seqHead <= seqLast\n\tthen \n\t\tl\n\telse \n\t\tr\n\t|curr < seqHead = l\n\t|curr < seqLast = r\n\t|otherwise = Left directions\n\twhere\n\t\tseqHead= sHeadUnsafe seq\n\t\tseqLast= sLastUnsafe seq\n\t\tl = Right ((seqHead, ('L': directions)), sTail seq)\n\t\tr = Right ((seqLast, ('R':directions) ), sInit seq)\n\nsteps ::Ord a => Situation a -> [Char]\nsteps sit =\n\tcase step sit of\n\t\tLeft dl -> reverse dl\n\t\tRight s -> steps s\n\nmain = do\n\tn <- getLine\n\tl <- fmap ((map read).words) getLine\n\tlet sol = steps $ ((0,\"\"),S.fromList l)\n\tputStrLn $ show $ length sol\n\tputStrLn sol\n\n\t\t"}], "negative_code": [{"source_code": "import Data.Sequence as S\nimport Data.Maybe\nsHead :: Seq a -> Maybe a\nsHead s =case viewl s of\n\t(n :< _) -> Just n\n\t_-> Nothing\n\nsLast :: Seq a -> Maybe a\nsLast s =case viewr s of\n\t(_ :> n) -> Just n\n\t_-> Nothing\n\nsTail :: Seq a -> Seq a\nsTail s = case viewl s of\n\t(_ :< n) -> n\n\t_ -> empty\n\nsInit :: Seq a -> Seq a\nsInit s = case viewr s of\n\t(n :> _) -> n\n\t_ -> empty\n\n\t\nsHeadUnsafe :: Seq a -> a\nsHeadUnsafe s = fromMaybe undefined $ sHead s\n\n\t\nsLastUnsafe :: Seq a -> a\nsLastUnsafe s = fromMaybe undefined $ sLast s\n\n\n\ntype Status a = (a,[Char])\ntype Situation a = (Status a,Seq a)\n\nstep :: Ord a => Situation a -> Either [Char] (Situation a)\nstep ((curr,directions),Empty) = Left directions\nstep ((curr,directions),seq)\n\t|curr < seqHead && curr < seqLast = \n\tif seqHead <= seqLast\n\tthen \n\t\tRight ((seqHead, directions ++ \"L\" ), sTail seq)\n\telse \n\t\tRight ((seqLast, directions ++ \"R\" ), sInit seq)\n\t|curr < seqHead = Right ((seqHead, directions ++ \"L\" ), sTail seq)\n\t|curr < seqLast = Right ((seqLast, directions ++ \"R\" ), sInit seq)\n\t|otherwise = Left directions\n\twhere\n\t\tseqHead= sHeadUnsafe seq\n\t\tseqLast= sLastUnsafe seq\n\nsteps ::Ord a => Situation a -> [Char]\nsteps sit =\n\tcase step sit of\n\t\tLeft l -> l\n\t\tRight s -> steps s\n\nmain = do\n\tn <- getLine\n\tl <- fmap ((map read).words) getLine\n\tputStrLn $ steps $ ((0,\"\"),S.fromList l)\n\n\t\t"}], "src_uid": "50c4b8fe3ab738e6e97058499791ac7b"} {"source_code": "import Control.Monad\nimport Data.Int\n\n\nstep :: [(Int64, Int64)] -> [Int64] -> [(Int64, Int64)]\nstep ps ws = let\n rs = do\n ((pL, pR), w) <- zip ps ws\n let\n npL = w * pL\n npR = w * pR\n pure (min npL npR, max npL npR)\n rangeUnion (p, q) (x, y) = (min p x, max q y)\n in tail $ scanl rangeUnion (maxBound, minBound) rs\n\nsolve :: [Int64] -> Int -> Int64\nsolve _ 0 = 1\nsolve a k = go (repeat (1, 1)) a k where\n go sc _ 0 = snd $ last sc\n go sc at kr = go (step sc at) (tail at) (kr - 1)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n a <- map read . words <$> getLine\n print $ solve a 5\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\nimport Control.Monad\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Data.List\nimport Data.Functor\nimport Data.Bool\nimport Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n-- import Debug.Trace\n\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt\n\nreadInt64B8 :: B8.ByteString -> Int64\nreadInt64B8 = fromIntegral . fst . fromJust . B8.readInteger\n\ncases :: [(Int, Int, String)]\ncases = [\n (0, 5, \"max\"),\n (1, 4, \"min\"),\n (2, 3, \"max\"),\n (3, 2, \"min\"),\n (4, 1, \"max\"),\n (5, 0, \"min\")]\n\nsolve :: Int -> [Int64] -> Int64\nsolve n as = foldr1 max $ solvedCases\n-- `debug` (show solvedCases)\n where\n solvedCases = catMaybes $ map solveCase cases\n\n positiveAs = sort $ filter (> 0) as\n negativeAs = reverse . sort $ filter (< 0) as\n zeros = filter (== 0) as\n\n solveCase (minCnt, maxCnt, ordString)\n | ((length negativeAs < minCnt) || (length positiveAs < maxCnt)) && (length zeros > 0) = Just 0\n | (length negativeAs < minCnt) || (length positiveAs < maxCnt) = Nothing\n | ordString == \"max\" = Just . foldr1 (*) $ ((take minCnt $ reverse negativeAs) ++ (take maxCnt $ reverse positiveAs))\n | ordString == \"min\" = Just . foldr1 (*) $ ((take minCnt negativeAs) ++ (take maxCnt positiveAs))\n | otherwise = Nothing\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n forM_ [1..t] $ \\_ -> do\n n <- B8.getLine <&> readIntB8\n as <- B8.getLine <&> B8.words <&> map readInt64B8\n let answer = solve n as\n printf \"%s\\n\" $ show answer\n\n\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [caseNum] <- getInts\n forM_ [1..caseNum] $ \\_ -> do\n _ <- getInts\n as <- getIntegers\n let nz = length $ filter (==0) as\n (ps', ns') = partition (>0) $ filter (/=0) as\n [ps, ns] = [reverse $ sort ps', sort ns']\n [lp, ln] = map length [ps, ns]\n f1 = if lp + ln < 5 then 0 else f2\n f2 = if lp == 0 || lp + ln == 5 && even lp then (if nz > 0 then 0 else product $ take 5 $ reverse $ sort $ map negate ps ++ ns) else f3\n f3 = maximum $ map (\\xs -> if length xs < 5 then 0 else product xs) [take 5 ps, take 3 ps ++ take 2 ns, head ps : take 4 ns]\n printf \"%d\\n\" f1\n"}], "negative_code": [], "src_uid": "a3a64c3c7e9349d6e663c2d8113d2676"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n line <- getLine >> getLine\n let nums :: [Int] = sortBy (flip compare) . map read . words $ line\n putStrLn . unwords . map show . S.toDescList . solve . S.fromDescList $ nums\n\n-- possibilities :: Int -> [Int]\n-- possibilities = possibilities' []\n\n-- possibilities' :: [Int] -> Int-> [Int]\n-- possibilities' acc n | n == 1 = reverse acc\n-- | even n = possibilities' (n `div` 2 : acc) (n `div` 2) \n-- | otherwise = possibilities' ((n-1) `div` 2 : acc) ((n-1) `div` 2)\npossibilities :: Int -> [Int]\npossibilities n | n == 1 = [1]\n | even n = n : possibilities (n `div` 2) \n | otherwise = n : possibilities ((n-1) `div` 2)\n\nreduce :: S.Set Int -> Maybe (S.Set Int)\n-- reduce xs = case maxNonMember of\n-- Nothing -> Nothing\n-- Just e -> Just $ S.insert e $ S.delete maxElem xs\nreduce xs = maxNonMember >>= (\\e -> Just . S.insert e $ S.delete maxElem xs)\n where\n maxElem = S.findMax xs\n maxNonMember = find (`S.notMember` xs) $ possibilities maxElem\n\nsolve :: S.Set Int -> S.Set Int\nsolve xs = case reduce xs of\n Nothing -> xs\n Just ys -> solve ys\n\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n line2 <- getLine >> getLine\n let nums :: [Int] = sortBy (flip compare) $ map read $ words line2\n putStrLn $ unwords $ map show $ S.toDescList $ solve $ S.fromDescList nums\n\npossibilities :: Int -> [Int]\npossibilities = possibilities' []\n\npossibilities' :: [Int] -> Int-> [Int]\npossibilities' acc n | n == 1 = reverse acc\n | even n = possibilities' (n `div` 2 : acc) (n `div` 2) \n | otherwise = possibilities' ((n-1) `div` 2 : acc) ((n-1) `div` 2)\n\nreduce :: S.Set Int -> Maybe (S.Set Int)\nreduce xs = case maxNonMember of\n Nothing -> Nothing\n Just e -> Just $ S.insert e $ S.delete maxElem xs\n where\n maxElem = S.findMax xs\n maxNonMember = find (\\x -> x `S.notMember` xs) $ possibilities maxElem\n\nsolve :: S.Set Int -> S.Set Int\nsolve xs = case reduce xs of\n Nothing -> xs\n Just ys -> solve ys\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntSet as IS\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInt.B.words <$> B.getLine\n putStrLn.unwords.map show $ solve xs\n\nsolve :: [Int] -> [Int]\nsolve xs = go $ IS.fromList xs\n where\n go set = case filter (`IS.notMember`set') ms of\n (y:_) -> go $ IS.insert y set'\n [] -> IS.toList set\n where\n (m, set') = IS.deleteFindMax set\n ms = tail.takeWhile (>0) $ iterate (`quot`2) m\n\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\n\nreadInt s = let Just (a, _) = BS.readInt s in a\n\nmain = BS.interact $ BS.unwords . map (BS.pack . show) . solve . map readInt . BS.words\n\nsolve (n:rest) = S.toList $ relax_all $ S.fromList $ take n rest\n where relax_all s = let rv = relax s in\n if rv > 0 then relax_all $ S.insert rv $ S.deleteMax s\n else s\n\nrelax s = relax_ $ S.findMax s\n where relax_ v = if S.notMember v s then v else relax_ $ v `div` 2\n"}, {"source_code": "{-\n\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\n\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\n\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551\n\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255a\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551\n\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255a\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255d\n\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u2550\u255d\u255a\u2550\u2550\u255d \n\n $$\\ $$$$$$\\ $$\\ $$\\ $$$$$$\\ $$\\ $$\\ $$\\ $$\\ \n \\__| $$ __$$\\ $$ | $$$$ | $$ __$$\\ $$ | $$ | $$ |$$ | \n $$$$$$$\\ $$$$$$\\ $$$$$$\\ $$\\ $$$$$$$\\ \\__/ $$ |$$ | $$\\ \\_$$ | $$ / $$ | $$ | $$ | $$ |$$ | \n$$ _____|$$ __$$\\ $$ __$$\\ $$ |$$ __$$\\ $$$$$$ |$$ | $$ | $$ | \\$$$$$$$ | $$ | $$ | $$ |$$ | \n$$ / $$ / $$ |$$ / $$ | $$ |$$ | $$ | $$ ____/ $$$$$$ / $$ | \\____$$ | $$ | $$ | $$ |$$ | \n$$ | $$ | $$ |$$ | $$ | $$ |$$ | $$ | $$ | $$ _$$< $$ | $$\\ $$ | $$ | $$ | $$ |$$ | \n\\$$$$$$$\\ $$$$$$$ |$$$$$$$ | $$ |$$ | $$ | $$$$$$$$\\ $$ | \\$$\\ $$$$$$\\\\$$$$$$ | $$$$$$$$\\\\$$$$$$ |$$$$$$$$\\ \n \\_______|$$ ____/ $$ ____/ \\__|\\__| \\__| \\________|\\__| \\__|\\______|\\______/ \\________|\\______/ \\________|\n $$ | $$ | \n $$ | $$ | \n \\__| \\__| \n-}\n\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n line <- getLine >> getLine\n let nums :: [Int] = sortBy (flip compare) . map read . words $ line\n putStrLn . unwords . map show . S.toDescList . solve . S.fromDescList $ nums\n\npossibilities :: Int -> [Int]\npossibilities n | n == 1 = [1]\n | even n = n : possibilities (n `div` 2) \n | otherwise = n : possibilities ((n-1) `div` 2)\n\nreduce :: S.Set Int -> Maybe (S.Set Int)\nreduce xs = maxNonMember >>= (\\e -> Just . S.insert e . S.delete maxElem $ xs) where\n maxElem = S.findMax xs\n maxNonMember = find (`S.notMember` xs) $ possibilities maxElem\n\nsolve :: S.Set Int -> S.Set Int\nsolve xs = case reduce xs of\n Nothing -> xs\n Just ys -> solve ys\n\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\n\nreadInt s = let Just (a, _) = BS.readInt s in a\n\nmain = BS.interact $ BS.unwords . map (BS.pack . show) . solve . map readInt . BS.words\n\nsolve (n:rest) = S.toList $ relax_all $ S.fromList $ take n rest\n where relax_all s = let rv = relax s in\n if rv > 0 then S.insert rv $ S.deleteMax s\n else s\n\nrelax s = relax_ $ S.findMax s\n where relax_ v = if S.notMember v s then v else relax_ $ v `div` 2"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as S\n\nreadInt s = let Just (a, _) = BS.readInt s in a\n\nmain = BS.interact $ BS.unwords . map (BS.pack . show) . solve . map readInt . BS.words\n\nsolve (n:rest) = S.toList $ relax_all $ S.fromList $ take n rest\n where relax_all s = let rv = relax s in\n if rv > 0 then S.insert rv $ S.deleteMax s\n else s\n\nrelax s = relax_ $ S.findMax s\n where relax_ v = if S.member v s then v else relax_ $ v `div` 2\n"}], "src_uid": "1ccbcc5986bf7e7272b7dd65e061d66d"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\n\n----- --------------------------------------------------------------\ndata TC = TC {as :: [Int64]}\n\ntype Output = Int64\n\ninput :: Scanner TC\ninput = do\n as <- numberOf int64\n return TC {..}\n\nsolve :: TC -> Output\nsolve = as >>> sum >>> abs\n\noutput :: Int -> Output -> C.ByteString\noutput ix = showB\n\n----- -------------------------------------------------------------\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\n\n----- Template ----------------------------------------------------------------\n\n-- Debug\ndebug :: Show a => a -> a\n\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- helpers\n(>$>) = flip ($)\n\ninfixl 0 >$>\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Ix (Ix)\r\nimport Data.List (unfoldr)\r\n\r\nsolve :: [Int] -> Int\r\nsolve xs = abs (abs psum - abs nsum)\r\n where\r\n psum = sum $ filter (>=0) xs\r\n nsum = sum $ filter (<0) xs\r\n\r\ndocase :: IO ()\r\ndocase = do\r\n _ <- getInt\r\n xs <- getInts\r\n print $ solve xs\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ docase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts = unfoldr go where\r\n go s = do\r\n (n,s1) <- C.readInt s\r\n let s2 = C.dropWhile (==' ') s1\r\n pure (n,s2)\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n"}], "negative_code": [], "src_uid": "f59f92a80f719cdb87ad92cd8c211942"} {"source_code": "import Data.List\n\nmain :: IO()\nmain = printBool . solve . map read . words =<< getContents\n\nprintBool :: Bool -> IO()\nprintBool b = putStrLn $ if b then \"YES\" else \"NO\"\n\nsolve :: [Int] -> Bool\nsolve (na:nb:k:m:x) =\n let a = (sort $ take na x) !! (k - 1)\n b = (sort $ drop na x) !! (nb - m)\n in a < b\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\n\nmain::IO ()\nmain=do\n [n,m]<- map read <$> words <$> getLine\n [a,b]<- map read <$> words <$> getLine ::IO [Int]\n a1<- head <$> drop (a-1) <$> map read <$> words <$> getLine:: IO Int\n b1<- head <$> drop (m-b) <$> map read <$> words <$> getLine::IO Int\n putStrLn $ if a1 Bool\nsolve [ [ _, nb ], [ k, m ], as, bs ] = as !! (k - 1) < bs !! (nb - m)\nsolve _ = undefined\n\nyesno :: Bool -> String\nyesno True = \"YES\"\nyesno _ = \"NO\"\n"}, {"source_code": "readInts = fmap (map read . words) getLine\nmain = do\n getLine\n [k,m] <- readInts\n as <- readInts\n bs <- readInts\n putStrLn $ if as !! (k-1) < bs !! (length bs - m) then \"YES\" else \"NO\"\n"}, {"source_code": "f :: [Int] -> [Int] -> Int -> Int -> Int -> Bool\nf xs ys k m n2 = xs !! (k-1) < ys !! (n2-m)\n\nmain = do\n [n1,n2] <- getList\n [k,m] <- getList\n xs <- getList\n ys <- getList\n putStrLn $ if f xs ys k m n2 then \"YES\"\n else \"NO\"\n \ngetList :: (Read a) => IO [a]\ngetList = fmap (map read . words) getLine\n"}, {"source_code": "main=interact $ solve . map read . words\nsolve (la:lb:m:k:x) = if x!!(m-1) [Int]\nparseLine str = map (read :: String -> Int) $ words str\n\nmain :: IO ()\nmain = do\n sizes <- getLine -- ignore\n counts <- getLine\n let [k, m] = map (+ (-1)) $ parseLine counts \n input <- getLine\n let a = parseLine input\n input <- getLine\n let b = parseLine input\n putStrLn $ if a !! k < (reverse b) !! m\n then \"YES\"\n else \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \nmain=do\t \n\t[na,nb]<- map read.words <$> getLine:: IO [Int] \n\t[k,m]<- map read.words <$> getLine:: IO [Int] \n\ta<- sort.map (fst.fromJust.C.readInt). C.words <$> C.getLine ::IO [Int]\n\tb<- reverse.sort.map (fst.fromJust.C.readInt). C.words <$> C.getLine ::IO [Int]\n\tlet a1 = head $ drop (k-1) a\n\tlet b1 = head $ drop (m-1) b\n\tputStrLn $ if a1 Int -> [Int] -> [Int] -> String\nsolve k m as bs\n | length btail >= m = \"YES\"\n | otherwise = \"NO\"\n where amax = last $ take k as\n btail = dropWhile (<= amax) bs\n\n\n-- Shit\nmain :: IO ()\nmain = do\n [_, [k,m], as, bs] <- readShit\n printShit [solve k m as bs]\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}, {"source_code": "parseInput input = (na, nb, k, m, xs, ys) where\n ls = lines input\n [na, nb] = map read $ words $ head ls :: [Int]\n [k, m] = map read $ words $ head $ tail ls :: [Int]\n xs = map read $ words $ ls !! 2 :: [Int]\n ys = map read $ words $ last ls :: [Int]\n\nsolve _ nb k m xs ys = case last as < head bs of \n True -> \"YES\"\n _ -> \"NO\"\n where\n as = take k xs\n bs = drop (nb - m) ys\n\nmain = do\n input <- getContents\n let (na, nb, k, m, xs, ys) = parseInput input\n putStrLn $ solve na nb k m xs ys \n"}, {"source_code": "main=interact $ solve . map read . words\nsolve (la:lb:m:k:x) = if x!!(m-1) read x::Int) . words) getLine\n [m,k] <- fmap (map (\\x -> read x::Int) . words) getLine\n a1 <- fmap (map (\\x -> read x::Int) . words) getLine\n a2 <- fmap (map (\\x -> read x::Int) . words) getLine\n let det = a1!!(m-1)\n if length ([x | x<-a2 , x>det]) >= k then putStrLn \"YES\" else putStrLn \"NO\"\n "}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n [a, b] <- getInts\n xs <- getInts\n ys <- getInts\n\n putStrLn $ if xs!!(a-1) < ys!!(length ys - b) then \"YES\" else \"NO\"\n"}, {"source_code": "answer::Int->Int->[Int]->[Int]->String\nanswer k m na nb = btos ((na !! (k-1)) < (nb !! ((length nb)-m))) \nbtos::Bool -> String\nbtos True = \"YES\"\nbtos False = \"NO\" \nmain = do\n w0 <- getLine\n w1 <- getLine\n w2 <- getLine\n w3 <- getLine\n let w = words w1\n let k = read (w !! 0)::Int\n let m = read (w !! 1)::Int\n let na = [read n::Int|n <-(words w2)]\n let nb = [read n::Int|n <-(words w3)]\n putStrLn $ answer k m na nb\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nmain = do\n let int = fst . fromJust . B.readInt\n ints = map int . B.words\n B.getLine\n [n, m] <- ints <$> B.getLine\n as <- ints <$> B.getLine\n bs <- ints <$> B.getLine\n putStrLn $ if (last $ take n $ sort as) < ( head $ drop (length bs - m ) $ sort bs) then \"YES\" else \"NO\" \n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nmain = do\n let int = fst . fromJust . B.readInt\n ints = map int . B.words\n B.getLine\n [n, m] <- ints <$> B.getLine\n as <- ints <$> B.getLine\n bs <- ints <$> B.getLine\n putStrLn $ if (last $ take n as) < ( head $ drop (length bs - m ) bs) then \"YES\" else \"NO\" \n"}, {"source_code": "-- Codeforces 572A\n\nmain :: IO ()\nmain = do\n [na, nb] <- readAndSplit\n [k, m] <- readAndSplit\n a <- readAndSplit\n b <- readAndSplit\n putStrLn $ if (a!!(k-1)) < (b!!(nb-m)) then \"YES\" else \"NO\" where\n readAndSplit = fmap (map read . words) getLine\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\ngetIntList :: IO [Int]\ngetIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _:n:_ <- getIntList\n k:m:_ <- getIntList\n as <- getIntList\n bs <- getIntList\n let a = last $ take k as\n let b = head $ if n>m then drop (n-m) bs else bs\n putStrLn $ if a B.getLine\n as <- ints <$> B.getLine\n bs <- ints <$> B.getLine\n putStrLn $ if (last $ take n $ sort as) < (head $ sort bs) then \"YES\" else \"NO\" \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\ngetIntList :: IO [Int]\ngetIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n _ <- C.getLine\n k:m:_ <- getIntList\n as <- getIntList\n bs <- getIntList\n let a = maximum $ take k as\n let b = minimum $ take m bs\n putStrLn $ if a C.getLine\n\nmain :: IO ()\nmain = do\n _ <- C.getLine\n k:m:_ <- getIntList\n as <- getIntList\n bs <- getIntList\n let a = as!!k\n let b = head bs\n putStrLn $ if a words <$> getLine ::IO [Int]\n a1<- head <$> drop (b-1) <$> map read <$> words <$> getLine:: IO Int\n b1<- head <$> map read <$> words <$> getLine::IO Int\n putStrLn $ if a1 Integer -> Integer\r\nsolve a b = a * b\r\n\r\nplotResult :: Integer -> IO ()\r\nplotResult = print\r\n\r\n\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[a, b] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\t--a <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve a b\r\n", "positive_code": [{"source_code": "import Control.Monad\n\nanswer :: Int -> Int -> Int\nanswer x y = x * y\n\nsolve line = x * y\n where (x:y:_) = map read $ words line\n\nmain :: IO ()\nmain = do\n t <- getLine\n replicateM_ (read t) $ do\n line <- getLine\n print $ solve line\n"}], "negative_code": [], "src_uid": "806dcdab8364f5169334e172a192598a"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\n\ncheck l = if sort l == l then Just l else Nothing\n\nsolve (_ : moneys) = check $ zipWith (\\x y -> y - x) [0..] $ sort (zipWith (+) [0..] moneys)\n\npp Nothing = [\":(\"]\npp (Just l) = [unwords $ map show l]\n\nmain = B.interact $ B.unlines . map B.pack . pp . solve . map readInt . B.words\n\nreadInt = fst . fromJust . B.readInt\n", "positive_code": [{"source_code": "import Data.Char (ord)\nimport Data.List\n\ntype Input = [Int]\ntype Output = Maybe [Int]\n\nreadInt :: String -> Int\nreadInt = foldl' (\\s d -> s * 10 + ord d - 48) 0\n\nparse :: String -> Input\nparse contents = a where [_, a] = map (map readInt . words) . lines $ contents\n\ncheck :: [Int] -> Maybe [Int]\ncheck a | sorted = Just a\n | otherwise = Nothing\n where sorted = and $ zipWith (<=) (0 : a) a\n\nsolve :: Input -> Output\nsolve = check . add (map negate nats) . sort . add nats\n where nats = [0..]\n add = zipWith (+)\n\nformat :: Output -> String\nformat Nothing = \":(\"\nformat (Just a) = unwords . map show $ a\n\nmain :: IO ()\nmain = putStrLn . format . solve . parse =<< getContents\n"}], "negative_code": [], "src_uid": "27ef62139533982f0857d733fad5c0d6"} {"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\nmain = interact $ unlines . g . tail . lines\r\n where\r\n aux1 :: String -> Int\r\n aux1 ss = read . last . words $ ss\r\n aux2 :: String -> [Int]\r\n aux2 ss = map read . words $ ss\r\n g :: [String] -> [String]\r\n g (x:y:sss) = f' (aux2 y) (aux1 x): g sss\r\n g [] = []\r\n\r\n\r\n\r\nf' :: [Int] -> Int -> String\r\nf' (s:ss) d = show . (\\(x, _, _) -> x) . foldl ff (0, s, s) $ ss\r\n where\r\n twiceD = 2*d\r\n ff (accum, smin, smax) x\r\n | x > smax = if x - smin > twiceD then\r\n (accum+1, x, x)\r\n else\r\n (accum, smin, x)\r\n | x < smin = if smax - x > twiceD then\r\n (accum+1, x, x)\r\n else\r\n (accum, x, smax)\r\n | otherwise = (accum, smin, smax)\r\n\r\n\r\nf :: [Int] -> Int -> String\r\nf (s:ss) d = show (aux s s 0 ss)\r\n where\r\n twiceD = 2*d\r\n aux :: Int -> Int -> Int -> [Int] -> Int\r\n aux smin smax accum (x:xs)\r\n | x > smax = if x - smin > twiceD then\r\n aux x x (accum+1) xs\r\n else\r\n aux smin x accum xs\r\n | x < smin = if smax - x > twiceD then\r\n aux x x (accum+1) xs\r\n else\r\n aux x smax accum xs\r\n | otherwise = aux smin smax accum xs\r\n aux _ _ accum [] = accum", "positive_code": [{"source_code": "{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE TemplateHaskell #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nmodule Main where\r\n\r\nimport Control.Exception ( Exception )\r\nimport Control.Monad ( replicateM\r\n , replicateM_\r\n )\r\nimport Data.Bits ( Bits(..) )\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.List ( elemIndex\r\n , findIndex\r\n , foldl'\r\n , unfoldr\r\n )\r\nimport Data.Maybe ( fromMaybe )\r\nimport Text.Printf ( printf )\r\n\r\n-- arrange :: [a] -> Int -> [[a]]\r\n-- arrange xs n = mapM (const xs) [1 .. n]\r\n\r\n-- data Tree a = Null | Branch a (Tree a) (Tree a)\r\n-- deriving (Show, Eq, Functor)\r\n\r\n-- makeBaseFunctor ''Tree\r\n\r\n-- x :: Tree Int\r\n-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)\r\n\r\n-- y :: Tree Int -> Int\r\n-- y = cata $ \\case\r\n-- NullF -> 0\r\n-- BranchF x a b -> x + a + b\r\n\r\n-- >>> y x\r\n-- 6\r\n\r\n-- z :: Tree Int -> Int\r\n-- z = para $ \\case\r\n-- NullF -> 0\r\n-- BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2\r\n\r\n-- >>> z x\r\n-- 11\r\n\r\n-- quicksort :: Ord a => [a] -> [a]\r\n-- quicksort = hylo merge split where\r\n-- split [] = NullF\r\n-- split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r\r\n\r\n-- merge NullF = []\r\n-- merge (BranchF x l r) = l ++ [x] ++ r\r\n\r\n-- >>> quicksort ([5,4,6,7,8,6,4,2])\r\n-- [2,4,4,5,6,6,7,8]\r\n\r\n-- fibSeq :: [Int]\r\n-- fibSeq = futu phi Nil\r\n-- where\r\n-- phi Nil = Cons 0 (Pure (Cons 0 Nil))\r\n-- phi x@(Cons _ Nil ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))\r\n-- phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))\r\n\r\n-- >>> take 20 fibSeq\r\n-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]\r\n\r\n-- f1 :: [Int] -> Int\r\n-- f1 = flip runReader 0 . cataA phi\r\n-- where\r\n-- phi Nil = return 0\r\n-- phi (Cons x t) = do\r\n-- n <- ask\r\n-- if n >= 10 then return 0 else (x +) <$> local succ t\r\n\r\n-- f2 :: [Int]\r\n-- f2 = apo phi 1\r\n-- where\r\n-- phi n | n < 100 = Cons (n * 2) (Right (n + 1))\r\n-- | otherwise = Cons (n * 2) (Left [1, 2, 3])\r\n\r\n-- >>> f1 fibSeq\r\n-- 88\r\n\r\n-- >>> f2\r\n-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]\r\n\r\n-- urlParser :: Parser String\r\n-- urlParser = argument str (metavar \"URL\")\r\n\r\n-- segmented :: Int -> Int -> [(Int, Int)]\r\n-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]\r\n\r\n-- main :: IO ()\r\n-- main = do\r\n-- manager <- newManager tlsManagerSettings\r\n-- url <- execParser opts\r\n-- req <- parseRequest url\r\n-- res <- httpNoBody req manager\r\n-- let len = maybe 0 fst (readInt =<< (lookup \"Content-Length\" (requestHeaders req) <|> lookup \"content-length\" (responseHeaders res)))\r\n-- if len == 0\r\n-- then do\r\n-- res <- httpLbs req manager\r\n-- print $ responseStatus res\r\n-- print $ responseBody res\r\n-- else do\r\n-- pool <- createPool (pure ()) (const (pure ())) 2 0.5 5\r\n-- mapConcurrently_\r\n-- (\\(s, e) -> withResource pool $ \\_ -> do\r\n-- res <- httpLbs (req { requestHeaders = (\"Range\", BS.pack $ formatToString (\"bytes=\" % int % \"-\" % int) s e) : requestHeaders req }) manager\r\n-- print $ responseStatus res\r\n-- -- print $ responseBody res\r\n-- )\r\n-- (segmented len tenMegabytes)\r\n-- where\r\n-- opts = info urlParser fullDesc\r\n-- tenMegabytes = 10485760\r\n\r\n-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a\r\n-- eigenvector m = iterate (\\x -> normalize (m !* x)) (m `dot` m) !! 1000\r\n\r\n-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a\r\n-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)\r\n-- where\r\n-- helper :: (Functor t, Conjugate a) => t a -> V1 (t a)\r\n-- helper = adjoint . fmap V1\r\n\r\n\r\n-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]\r\n-- eigenvalues m = go [e0] (m - e0 *!! identity)\r\n-- where\r\n-- c0 = eigenvector m\r\n-- e0 = eigenvalue m c0\r\n-- go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc\r\n-- | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))\r\n-- where ec = eigenvector ma\r\n-- ev = eigenvalue ma ec\r\n-- ec' = (<$ unit _x) <$> ec\r\n\r\n-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))\r\n-- []\r\n\r\ndata Break = Break\r\n deriving Show\r\n\r\ninstance Exception Break\r\n\r\nreadChar8 :: IO [Int]\r\nreadChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n\r\n\r\nreadChar8' :: IO [Int]\r\nreadChar8' = parse <$> C.getLine\r\n where\r\n parse = unfoldr go\r\n go s = do\r\n (n, s1) <- C.readInt s\r\n let s2 = C.dropWhile (== ' ') s1\r\n return (fromIntegral n, s2)\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n [n, m] <- readChar8'\r\n xs <- readChar8'\r\n print $ fst $ foldl'\r\n (\\(acc, (mx, mi)) x ->\r\n let mx' = max mx x\r\n mi' = min mi x\r\n in if mx' - mi' > 2 * m then (acc + 1, (x, x)) else (acc, (mx', mi'))\r\n )\r\n (0, (head xs, head xs))\r\n xs\r\n"}, {"source_code": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Maybe ( fromJust )\r\n\r\nmain :: IO ()\r\nmain = B.interact $ B.unlines . g . tail . B.lines\r\n where\r\n aux1 ss = fst . fromJust . B.readInt . last . B.words $ ss\r\n aux2 ss = map (fst . fromJust . B.readInt) . B.words $ ss\r\n g (x:y:sss) = f' (aux2 y) (aux1 x): g sss\r\n g [] = []\r\n\r\nf' :: (Ord c, Num c) => [c] -> c -> B.ByteString\r\nf' (s:ss) d = B.pack . show . (\\(x, _, _) -> x) . foldl ff (0, s, s) $ ss\r\n where\r\n twiceD = 2*d\r\n ff (accum, smin, smax) x\r\n | x > smax = if x - smin > twiceD then\r\n (accum+1, x, x)\r\n else\r\n (accum, smin, x)\r\n | x < smin = if smax - x > twiceD then\r\n (accum+1, x, x)\r\n else\r\n (accum, x, smax)\r\n | otherwise = (accum, smin, smax)"}], "negative_code": [], "src_uid": "1f520f2796094b0f0c4e11e231f9ca8c"} {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Monad\nimport Data.List\n\nsolve xs = show' if ones <= len `div` 2 then (len - ones, 0) else (ones - if even ones then 0 else 1, 1)\n where\n len = length xs\n ones = sum xs\n show' (l, x) = show l ++ \"\\n\" ++ intercalate \" \" (replicate l $ show x)\n\nmain = mkMain solve\n\nmkMain f = do\n n <- readLn\n replicateM_ n do\n void $ getLine\n a <- map read . words <$> getLine\n putStrLn $ f a", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tk = n `div` 2\n\t\tones = length $ filter ( == 1 ) as\n\tif | as == [ 1, 1 ] -> do\n\t\t\tprint n\n\t\t\tprintList as\n\t\t| ones <= n `div` 2 -> do\n\t\t\tprint k\n\t\t\tprintList $ replicate k 0\n\t\t| otherwise -> do\n\t\t\tlet\n\t\t\t\tk' = if odd ones then ones - 1 else ones\n\t\t\tprint $ k'\n\t\t\tprintList $ replicate k' 1\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tk = n `div` 2\n\t\tones = length ( filter odd as )\n\tif n == 2 && as == [ 1, 1 ]\n\t\tthen do\n\t\t\tprint n\n\t\t\tprintList as\n\t\telse do\n\t\t\tprint $ k\n\t\t\tprintList $ replicate k ( which 0 1 $ ones <= k )\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tk = n `div` 2\n\t\tones = length $ filter ( == 1 ) as\n\tif | as == [ 1, 1 ] -> do\n\t\t\tprint n\n\t\t\tprintList as\n\t\t| ones <= n `div` 2 -> do\n\t\t\tprint k\n\t\t\tprintList $ replicate k 0\n\t\t| otherwise -> do\n\t\t\tlet\n\t\t\t\tk' = if odd k then k - 1 else k\n\t\t\tprint $ k'\n\t\t\tprintList $ replicate k' 1"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\tn <- readInt\n\tas <- readInts\n\tlet\n\t\tk = n `div` 2\n\t\tones = length ( filter odd as )\n\tprint $ k\n\tprintList $ replicate k ( which 0 1 $ ones <= k )"}], "src_uid": "eca92beb189c4788e8c4744af1428bc7"} {"source_code": "import Data.List\n\nmain = getLine >>= test . read\n\ntest 0 = return ()\ntest i = do\n getLine\n as <- map read . words <$> getLine\n print $ solve (head as) as\n test (i - 1)\n\nsolve _ [] = 0\nsolve a (d:ds) = max (binaryLength (a - d)) (solve (max a d) ds)\n\nbinaryLength x = until ((> x) . (2 ^)) (+ 1) 0\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ getLine >> getLine >>= print . solve . map read . words\n\nbitcnt :: Int -> Int\nbitcnt 0 = 0\nbitcnt n = succ . bitcnt $ n `div` 2\n\nsolve :: [Int] -> Int\nsolve a = maximum . map bitcnt $ zipWith (-) (scanl1 max a) a\n"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ getLine >> getLine >>= print . solve . map read . words\n\nbitcnt :: Int -> Int\nbitcnt x = finiteBitSize x - countLeadingZeros x\n\nsolve :: [Int] -> Int\nsolve a = maximum . map bitcnt $ zipWith (-) (scanl1 max a) a\n"}, {"source_code": "import Control.Monad\nimport Data.Bits\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs =maximum $ map (\\x -> if x<=0 then 0 else 1 + logBase2 x) $ f (head xs) xs\n\nf :: Int -> [Int] -> [Int]\nf prev (x:xs) = (prev-x) : f (max prev x) xs\nf prev [] = []\n\nlogBase2 :: Int -> Int\nlogBase2 x = finiteBitSize x - 1 - countLeadingZeros x\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\neverySecond [] = []\neverySecond (a : b : xs) = b : everySecond xs\n\n-- https://stackoverflow.com/a/14359943/61394\nlog2 n = length (takeWhile (< n) (iterate (* 2) 1))\n\nf xs =\n let runningMax = scanl1 max xs\n maxDiff = maximum $ zipWith (-) runningMax xs\n in if maxDiff <= 0 then 0 else log2 (maxDiff + 1)\n\nmain =\n interact\n $ unlines\n . map (show . f . map read . words)\n . everySecond\n . tail\n . lines\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\neverySecond [] = []\neverySecond (a : b : xs) = b : everySecond xs\n\n-- https://stackoverflow.com/a/14359943/61394\nlog2 n = length (takeWhile (< n) (iterate (* 2) 1))\n\nf xs =\n let runningMax = scanl1 max xs\n maxDiff = maximum $ zipWith (-) runningMax xs\n in if maxDiff <= 0 then 0 else 1 + log2 maxDiff\n\nmain =\n interact\n $ unlines\n . map (show . f . map read . words)\n . everySecond\n . tail\n . lines\n"}, {"source_code": "import Data.List\n\nmain = getLine >>= test . read\n\ntest 0 = return ()\ntest i = do\n getLine\n as <- map read . words <$> getLine\n let ds = zipWith (-) as (tail as)\n print $ solve 0 $ sort $ filter (> 0) ds\n test (i - 1)\n\nsolve x [] = x\nsolve x (d:ds)\n | 2 ^ x < d = solve (x + 1) ((d - 2 ^ x):ds)\n | otherwise = solve (x + 1) ds\n\n"}, {"source_code": "import Data.List\n\nmain = getLine >>= test . read\n\ntest 0 = return ()\ntest i = do\n getLine\n as <- map read . words <$> getLine\n print $ solve 0 as\n test (i - 1)\n\nsolve _ [] = 0\nsolve a (d:ds) = max (binaryLength (a - d)) (solve (max a d) ds)\n\nbinaryLength x\n | x <= 0 = 0\n | otherwise = until ((> x) . (2 ^)) (+ 1) 0"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve [_] = 0\nsolve [x,y] = f2 (x-y)\nsolve xs = f3. map f2 . f1 $ xs\n\nf1 :: [Int] -> [Int]\nf1 xs = zipWith (-) xs (tail xs)\n\nf2 :: Int -> Int\nf2 x = floor $ if x<=0 then 0 else 1+ logBase 2 (fromIntegral x)\n\nf3 :: [Int] -> Int\nf3 xs =maximum $ zipWith (\\x y -> if x==y && x>0 then x+1 else max x y) xs (tail xs)\n"}, {"source_code": "import Control.Monad\nimport Data.Bits\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs =maximum $ map (\\x -> if x<=0 then 0 else 1 + logBase2 x) $ f 0 xs\n\nf :: Int -> [Int] -> [Int]\nf prev (x:xs) = (prev-x) : f (max prev x) xs\nf prev [] = []\n\nlogBase2 :: Int -> Int\nlogBase2 x = finiteBitSize x - 1 - countLeadingZeros x\n"}], "src_uid": "bfc2e7de37db4a0a74cdd55f2124424a"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n pts <- replicateM n ((,) <$> readInt <*> readInt)\n return (n, pts)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, pts) = BS.pack ((show $ length pts2) ++ \"\\n\") `BS.append` BS.unlines [ BS.pack (show x ++ \" \" ++ show y) | (x, y) <- pts2]\n where\n pts2 = map head . group . sort $ solveInterval (sort pts)\n\nsolveInterval [] = []\nsolveInterval xs = solveInterval lo ++ solveInterval (tail hi) ++ [ (x, y) | (_, y) <- xs]\n where\n len = length xs\n (lo, hi) = splitAt (len `div` 2) xs\n\n x = fst $ head hi\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain = do\n n <- read `liftM` getLine\n points <- sortBy (comparing fst) `liftM` replicateM n ( do\n [x, y] <- ( map read . words ) `liftM` getLine :: IO [Int]\n return (x, y) )\n\n let resPoints = fst $ fill points\n putStrLn $ show $ length resPoints\n putStr $ unlines $ map (\\(x, y) -> show x ++ \" \" ++ show y) resPoints\n\nfill :: [(Int, Int)] -> ([(Int, Int)], [Int])\nfill pts =\n let n = length pts\n x0 = fst $ pts !! ( n `div` 2 )\n (left, middle, right) = foldr (\\p@(x, _) (left, middle, right) ->\n case compare x x0 of\n LT -> (p:left, middle, right)\n EQ -> (left, p:middle, right)\n GT -> (left, middle, p:right)\n ) ([], [], []) pts\n middleY = sort $ map snd middle\n\n (left', leftY) = fill left\n (right', rightY) = fill right\n\n y = merge3 leftY middleY rightY\n\n middle' = map (\\y -> (x0, y)) y\n\n in if n == 0 then ([], []) else (left' ++ middle' ++ right', y)\n\nmerge3 :: (Bounded a, Ord a) => [a] -> [a] -> [a] -> [a]\nmerge3 as bs cs =\n let a = if null as then maxBound else head as\n b = if null bs then maxBound else head bs\n c = if null cs then maxBound else head cs\n ta = tail as\n tb = tail bs\n tc = tail cs\n in case compare a b of\n LT -> case compare a c of\n LT -> a : merge3 ta bs cs\n EQ -> a : merge3 ta bs tc\n GT -> c : merge3 as bs tc\n EQ -> case compare a c of\n LT -> a : merge3 ta tb cs\n EQ -> if a == maxBound then [] else a : merge3 ta tb tc\n GT -> c : merge3 as bs tc\n GT -> case compare b c of\n LT -> b : merge3 as tb cs\n EQ -> b : merge3 as tb tc\n GT -> c : merge3 as bs tc\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n pts <- replicateM n ((,) <$> readInt <*> readInt)\n return (n, pts)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, pts) = BS.pack ((show $ length pts2) ++ \"\\n\") `BS.append` BS.unlines [ BS.pack (show x ++ \" \" ++ show y) | (x, y) <- pts2]\n where\n pts2 = map head . group . sort $ solveInterval (sort pts)\n\nsolveInterval [] = []\nsolveInterval [a] = [a]\nsolveInterval xs = solveInterval lo ++ solveInterval (tail hi) ++ [ (x, y) | (_, y) <- xs] \n where\n len = length xs\n (lo, hi) = splitAt (len `div` 2) xs\n\n x = snd $ head hi\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n pts <- replicateM n ((,) <$> readInt <*> readInt)\n return (n, pts)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, pts) = BS.pack ((show $ length pts2) ++ \"\\n\") `BS.append` BS.unlines [ BS.pack (show x ++ \" \" ++ show y) | (x, y) <- pts2]\n where\n pts2 = map head . group . sort $ solveInterval (sort pts)\n\nsolveInterval [] = []\nsolveInterval [a] = [a]\nsolveInterval xs = solveInterval lo ++ solveInterval hi ++ [ (x, y) | (_, y) <- xs] \n where\n len = length xs\n (lo, hi) = splitAt (len `div` 2) xs\n\n x = snd $ head hi\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n pts <- replicateM n ((,) <$> readInt <*> readInt)\n return (n, pts)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, pts) = BS.pack ((show $ length pts2) ++ \"\\n\") `BS.append` BS.unlines [ BS.pack (show x ++ \" \" ++ show y) | (x, y) <- pts2]\n where\n pts2 = map head . group . sort $ solveInterval (sort pts)\n\nsolveInterval [] = []\nsolveInterval [a] = [a]\nsolveInterval xs = solveInterval lo ++ solveInterval hi ++ [ (x, y) | (x, _) <- xs] \n where\n len = length xs\n (lo, hi) = splitAt (len `div` 2) xs\n\n y = snd $ head hi\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n pts <- replicateM n ((,) <$> readInt <*> readInt)\n return (n, pts)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, pts) = BS.pack ((show $ length pts2) ++ \"\\n\") `BS.append` BS.unlines [ BS.pack (show x ++ \" \" ++ show y) | (x, y) <- pts2]\n where\n ptsGrouped = groupBy ((==) `on` fst) $ sort pts\n ptsMerged = concat $ zipWith mergeLine ptsGrouped (tail ptsGrouped) :: [(Int,Int)]\n\n xs = map head . group . sort $ map fst pts\n ys = map head . group . sort $ map snd pts\n\n borderX = [ (x, y) | x <- xs, y <- [minimum ys, maximum ys]]\n borderY = [ (x, y) | y <- ys, x <- [minimum xs, maximum xs]]\n \n pts2 = map head . group . sort $ ptsMerged ++ borderX ++ borderY :: [(Int,Int)]\n\nmergeLine :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]\nmergeLine [] x = x\nmergeLine x [] = x\nmergeLine x y = [(xVal, val) | val <- lst, inRange rangeX val] ++ [(yVal, val) | val <- lst, inRange rangeY val]\n where\n xVal = fst $ head x\n yVal = fst $ head y\n lst = IntSet.toList . IntSet.fromList $ map snd x ++ map snd y\n\n rangeX = (minimum $ map snd x, maximum $ map snd x)\n rangeY = (minimum $ map snd y, maximum $ map snd y)\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}], "src_uid": "468020848783d8e017f2d7de5b4fe940"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nf o n\n | o < 0 = print $ -1\n | otherwise = print $ min o n\n\ninspect 0 = putStr \"\"\ninspect linenum = do\n line <- getLine\n let\n k:n:a:b:_ = map read $ words line\n m = a * n\n d = a - b\n e = m - k\n q = (div e d) + 1\n o = n - q\n f o n\n inspect $ linenum - 1\n\nmain = do\n line <- getLine\n inspect $ read line\n", "positive_code": [{"source_code": "readInt :: String -> Integer\nreadInt = read\n\nmain = interact $ solve . (map ((map readInt) . words)) . tail . lines\n\nsolve :: [[Integer]] -> String\nsolve [] = \"\"\nsolve (l:ls) = solveInstance l ++ solve ls\n\nsolveInstance :: [Integer] -> String\nsolveInstance [k, n, a, b] \n | n*b >= k = \"-1\\n\"\n | otherwise = let t = (k - n*b - 1) `div` (a - b) in (++\"\\n\") $ show (min n t)\n"}], "negative_code": [{"source_code": "readInt :: String -> Int\nreadInt = read\n\nmain = interact $ solve . (map ((map readInt) . words)) . tail . lines\n\nsolve :: [[Int]] -> String\nsolve [] = \"\"\nsolve (l:ls) = solveInstance l ++ solve ls\n\nsolveInstance :: [Int] -> String\nsolveInstance [k, n, a, b] \n | n*b >= k = \"-1\\n\"\n | otherwise = let t = (k - n*b - 1) `div` (a - b) in (++\"\\n\") $ show (min n t)\n"}], "src_uid": "2005224ffffb90411db3678ac4996f84"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord (comparing)\n\nmain = do\n n <- fmap read getLine\n strings <- replicateM n getLine\n let sort_strings = lsort strings\n let len = length sort_strings\n if (check sort_strings len || (len == 1))\n then do\n putStrLn \"YES\"\n mapM_ putStrLn sort_strings\n else do\n putStr \"NO\"\n --mapM_ putStrLn sort_strings\n\nlsort :: [String] -> [String]\nlsort = sortBy (comparing length)\n\ncheck :: [String] -> Int -> Bool\ncheck _ 1 = True\ncheck (x:y:xs) l = if isInfixOf x y\n then check (y:xs) (l-1)\n else False", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n strings <- sequence $ take n $ repeat getLine\n let sortedByLength = sortBy (\\str str' -> compare (length str) (length str')) strings\n grouped = group sortedByLength\n groupedByLength = groupBy (\\str str' -> length str == length str') sortedByLength\n if length grouped /= length groupedByLength then do\n putStrLn \"NO\"\n else do\n let (_,satisfy) = foldl (\\(preceeding,flag) current ->\n let newFlag = all id $ map (flip isInfixOf current) preceeding\n in (current:preceeding,flag && newFlag)) ([],True) $ map head grouped\n if satisfy then do\n putStrLn \"YES\"\n forM_ (concat grouped) (\\str -> putStrLn str) \n else\n putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Map as M\nimport Data.Map(Map)\nimport Data.List\nimport Data.Ord (comparing)\n \nsort_str :: [String] -> [String]\nsort_str = sortBy (comparing length)\n \nrec :: [String] -> Int -> Bool\nrec _ 1 = True\nrec (x : y : xs) l = if isInfixOf x y\n then rec (y : xs) (l - 1)\n else False\n\nmain = do\n n <- fmap read getLine\n a <- replicateM n getLine\n let arr = sort_str a\n let len = length arr\n if (rec arr len || (len == 1))\n then do\n putStrLn \"YES\"\n mapM_ putStrLn arr\n else do\n putStr \"NO\"\n "}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM)\nimport Data.List (isInfixOf, sort)\n\nnewtype MyString = MyString String\n deriving (Eq)\n\ninstance Show MyString where\n show (MyString a) = a\n\ninstance Ord MyString where\n (<=) (MyString a) (MyString b) = length a <= length b && isInfixOf a b\n\ncheckInvariant :: [MyString] -> Bool\ncheckInvariant l@(x : xs) = all (\\(MyString a, MyString b) -> isInfixOf a b) (zip l xs)\ncheckInvariant _ = True\n\nmain :: IO ()\nmain = do\n nStr <- getLine\n let n = read nStr :: Int\n s <- replicateM n getLine\n let answer = sort (map MyString s)\n if checkInvariant answer\n then do\n putStrLn \"YES\"\n mapM_ print answer\n else putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.String\n\nsubpair t = isInfixOf (fst t) (snd t)\n\nmain = do\n fline <- getLine\n let n = read fline::Int\n strs <- replicateM n getLine\n let sstrs = sortBy (comparing length) strs\n let pstrs = zip (take (n-1) sstrs) (tail sstrs)\n let judge = foldl (&&) True $ map subpair pstrs\n if judge \n then do putStrLn \"YES\";\n\t mapM_ putStrLn sstrs\n else do putStrLn \"NO\"\n \n "}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad (replicateM)\nimport Data.List (isInfixOf, sort)\n\nnewtype MyString = MyString String\n deriving (Eq)\n\ninstance Show MyString where\n show (MyString a) = a\n\ninstance Ord MyString where\n (<=) (MyString a) (MyString b) = isInfixOf a b\n\ncheckInvariant :: [MyString] -> Bool\ncheckInvariant l@(x : xs) = all (\\(MyString a, MyString b) -> a <= b) (zip l xs)\ncheckInvariant _ = True\n\nmain :: IO ()\nmain = do\n nStr <- getLine\n let n = read nStr :: Int\n s <- replicateM n getLine\n let answer = sort (map MyString s)\n if checkInvariant answer\n then do\n putStrLn \"YES\"\n mapM_ print answer\n else putStrLn \"NO\""}], "src_uid": "5c33d1f970bcc2ffaea61d5407b877b2"} {"source_code": "import Data.List\n\nisPali s = s == reverse s\n\nhasPali3 s = any isPali (take 2 $ drop 2 $ inits s)\n\nincrement :: Char -> String -> Maybe String\nincrement p [] = Nothing\nincrement p (c : cs)\n | c == p = do\n withA <- fmap ('a' :) $ increment p cs\n if hasPali3 withA\n then increment p withA\n else return withA\n | otherwise =\n let tmp = succ c : cs in\n if hasPali3 tmp\n then increment p tmp\n else return tmp\n \ns [ns,ps,s] = case increment (iterate succ 'a' !! (read ps - 1)) (reverse s) of\n Nothing -> \"NO\"\n Just s' -> reverse s'\n \n\nmain = interact $ s . words\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\n\nimport Debug.Trace\n\nprefix :: [Int] -> Int -> [Int]\nprefix (h : t@(th : tth : _)) p | h + 1 /= th && h + 1 /= tth && h + 1 < p = (h + 1) : t\n | h + 2 /= th && h + 2 /= tth && h + 2 < p = (h + 2) : t\n | h + 3 /= th && h + 3 /= tth && h + 3 < p = (h + 3) : t\n | otherwise = prefix t p\nprefix [h, t] p | h + 1 /= t && h + 1 < p = [h + 1, t]\n | h + 2 /= t && h + 2 < p = [h + 2, t]\n | otherwise = prefix [t] p\nprefix [h] p | h + 1 < p = [h + 1]\n | otherwise = []\nprefix _ _ = undefined\n\nappend :: [Int] -> Int -> [Int]\nappend s n | length s == n = s\n | otherwise = append (case s of\n [] -> [0]\n [h] -> if h /= 0 then [0, h] else [1, h]\n h : ht : _ -> if h == 0 || ht == 0 then if h == 1 || ht == 1 then 2 : s else 1 : s else 0 : s) n\n\nsolve :: [Int] -> Int -> Maybe [Int]\nsolve s p =\n if p == 1\n then Nothing\n else if (p == 2)\n then if s == [0] then Just [1] else if s == [1, 0] then Just [0, 1] else Nothing\n else let prefix' = prefix s p\n in if null prefix'\n then Nothing\n else Just $ append prefix' $ length s\n\nmain :: IO ()\nmain =\n do [_, p] <- liftM (map read . words) getLine\n s <- liftM (reverse . map (\\c -> ord c - ord 'a')) getLine\n case solve s p of\n Just solution -> putStrLn $ map (\\i -> chr (i + ord 'a')) $ reverse solution\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\n\nimport Debug.Trace\n\nprefix :: [Int] -> Int -> [Int]\nprefix (h : t@(th : tth : _)) p | h + 1 /= th && h + 1 /= tth && h + 1 < p = (h + 1) : t\n | h + 2 /= th && h + 2 /= tth && h + 2 < p = (h + 2) : t\n | h + 3 /= th && h + 3 /= tth && h + 3 < p = (h + 3) : t\n | otherwise = prefix t p\nprefix [h, t] p | h + 1 /= t && h + 1 < p = [h + 1, t]\n | h + 2 /= t && h + 2 < p = [h + 2, t]\n | otherwise = prefix [t] p\nprefix [h] p | h + 1 < p = [h + 1]\n | otherwise = []\nprefix _ _ = undefined\n\nappend :: [Int] -> Int -> [Int]\nappend s n | length s == n = s\n | otherwise = append (case s of\n [] -> [0]\n [h] -> if h /= 0 then [0, h] else [1, h]\n h : ht : _ -> if h == 0 || ht == 0 then if h == 1 || ht == 1 then 2 : s else 1 : s else 0 : s) n\n\nsolve :: [Int] -> Int -> Maybe [Int]\nsolve s p =\n let prefix' = prefix s p\n in if null prefix'\n then Nothing\n else Just $ append prefix' $ length s\n\nmain :: IO ()\nmain =\n do [_, p] <- liftM (map read . words) getLine\n s <- liftM (reverse . map (\\c -> ord c - ord 'a')) getLine\n case solve s p of\n Just solution -> putStrLn $ map (\\i -> chr (i + ord 'a')) $ reverse solution\n Nothing -> putStrLn \"NO\"\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\n\nimport Debug.Trace\n\nprefix :: [Int] -> Int -> [Int]\nprefix (h : t@(th : tth : _)) p | h + 1 /= th && h + 1 /= tth && h + 1 < p = (h + 1) : t\n | h + 2 /= th && h + 2 /= tth && h + 2 < p = (h + 2) : t\n | h + 3 /= th && h + 3 /= tth && h + 3 < p = (h + 3) : t\n | otherwise = prefix t p\nprefix (h : t : []) p | h + 1 /= t && h + 1 < p = [h + 1, t]\n | h + 2 /= t && h + 2 < p = [h + 1, t]\n | t + 1 < p = [t + 1]\n | otherwise = []\nprefix _ _ = undefined\n\nappend :: [Int] -> Int -> [Int]\nappend s n | length s == n = s\n | otherwise = append (case s of\n [] -> [0]\n [h] -> if h /= 0 then [0, h] else [1, h]\n h : ht : _ -> if h == 0 || ht == 0 then if h == 1 || ht == 1 then 2 : s else 1 : s else 0 : s) n\n\nsolve :: [Int] -> Int -> Maybe [Int]\nsolve s p =\n if p < 3\n then Nothing\n else let prefix' = prefix s p\n in if null prefix'\n then Nothing\n else Just $ append prefix' $ length s\n\nmain :: IO ()\nmain =\n do [_, p] <- liftM (map read . words) getLine\n s <- liftM (reverse . map (\\c -> ord c - ord 'a')) getLine\n case solve s p of\n Just solution -> putStrLn $ map (\\i -> chr (i + ord 'a')) $ reverse solution\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\n\nimport Debug.Trace\n\nprefix :: [Int] -> Int -> [Int]\nprefix (h : t@(th : tth : _)) p | h + 1 /= th && h + 1 /= tth && h + 1 < p = (h + 1) : t\n | h + 2 /= th && h + 2 /= tth && h + 2 < p = (h + 2) : t\n | h + 3 /= th && h + 3 /= tth && h + 3 < p = (h + 3) : t\n | otherwise = prefix t p\nprefix (h : t : []) p | h + 1 /= t && h + 1 < p = [h + 1, t]\n | h + 2 /= t && h + 2 < p = [h + 1, t]\n | t + 1 < p = [t + 1]\n | otherwise = []\nprefix _ _ = undefined\n\nappend :: [Int] -> Int -> [Int]\nappend s n | length s == n = s\n | otherwise = append (case s of\n [] -> [0]\n [h] -> if h /= 0 then [0, h] else [1, h]\n h : ht : _ -> if h == 0 || ht == 0 then if h == 1 || ht == 1 then 2 : s else 1 : s else 0 : s) n\n\nsolve :: [Int] -> Int -> Maybe [Int]\nsolve s p =\n if p == 1\n then Nothing\n else if (p == 2)\n then if s == [1, 0] then Just [0, 1] else Nothing\n else let prefix' = prefix s p\n in if null prefix'\n then Nothing\n else Just $ append prefix' $ length s\n\nmain :: IO ()\nmain =\n do [_, p] <- liftM (map read . words) getLine\n s <- liftM (reverse . map (\\c -> ord c - ord 'a')) getLine\n case solve s p of\n Just solution -> putStrLn $ map (\\i -> chr (i + ord 'a')) $ reverse solution\n Nothing -> putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\n\nimport Debug.Trace\n\nprefix :: [Int] -> Int -> [Int]\nprefix (h : t@(th : tth : _)) p | h + 1 /= th && h + 1 /= tth && h + 1 < p = (h + 1) : t\n | h + 2 /= th && h + 2 /= tth && h + 2 < p = (h + 2) : t\n | h + 3 /= th && h + 3 /= tth && h + 3 < p = (h + 3) : t\n | otherwise = prefix t p\nprefix [h, t] p | h + 1 /= t && h + 1 < p = [h + 1, t]\n | h + 2 /= t && h + 2 < p = [h + 1, t]\n | otherwise = prefix [t] p\nprefix [h] p | h + 1 < p = [h + 1]\n | otherwise = []\nprefix _ _ = undefined\n\nappend :: [Int] -> Int -> [Int]\nappend s n | length s == n = s\n | otherwise = append (case s of\n [] -> [0]\n [h] -> if h /= 0 then [0, h] else [1, h]\n h : ht : _ -> if h == 0 || ht == 0 then if h == 1 || ht == 1 then 2 : s else 1 : s else 0 : s) n\n\nsolve :: [Int] -> Int -> Maybe [Int]\nsolve s p =\n if p == 1\n then Nothing\n else if (p == 2)\n then if s == [0] then Just [1] else if s == [1, 0] then Just [0, 1] else Nothing\n else let prefix' = prefix s p\n in if null prefix'\n then Nothing\n else Just $ append prefix' $ length s\n\nmain :: IO ()\nmain =\n do [_, p] <- liftM (map read . words) getLine\n s <- liftM (reverse . map (\\c -> ord c - ord 'a')) getLine\n case solve s p of\n Just solution -> putStrLn $ map (\\i -> chr (i + ord 'a')) $ reverse solution\n Nothing -> putStrLn \"NO\"\n"}], "src_uid": "788ae500235ca7b7a7cd320f745d1070"} {"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve ls = zipWith (\\x y -> y-x-1) ls (drop (m+1) ls)\n (mx,idx) = getIndex 0 0 (zip (dropWhile (==0) (solve (0:(l++[n+1])))) l)\n --print ((dropWhile (==0) (solve (0:(l++[n+1])))) , l)\n if m>=n\n then do\n print n\n putStr . unwords . map show . take n $ repeat 1\n else if l==[]\n then do\n print n\n putStr . unwords . map show $ a\n else do\n print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n", "positive_code": [{"source_code": "import Control.Applicative ((<$>))\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n, k] <- readInts\n as <- readInts\n\n let\n cs = listArray (0, n) $ scanl (+) 0 as :: UArray Int Int\n\n rs = map find [1..n]\n where\n find i = (find' 1 i, i)\n where\n find' l r\n | l >= r = if v then l else i+1\n | v = find' l m\n | otherwise= find' (m+1) r\n where\n m = (l+r) `div` 2\n v = f m\n\n f j = cs!i - cs!(j-1) + k >= i-j+1\n\n (i, j) = maximumBy (comparing (\\(i, j) -> j-i+1)) rs\n\n print $ j-i+1\n putStrLn $ unwords $ map show $ map (\\(k, a) -> if i <= k && k <= j then 1 else a) $ zip [1..] as\n"}], "negative_code": [{"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve ls = zipWith (\\x y -> y-x-1) ls (drop (m+1) ls)\n (mx,idx) = getIndex 0 0 (zip (dropWhile (==0) (solve (0:(l++[n+1])))) l)\n --print ((dropWhile (==0) (solve (0:(l++[n+1])))) , l)\n if m>=n\n then do\n print n\n putStr . unwords . map show . take n $ repeat 1\n else if l==[]\n then mapM_ print (solve (0:(l++[n+1])))\n else do\n print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n"}, {"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve ls = zipWith (\\x y -> y-x-1) ls (drop (m+1) ls)\n (mx,idx) = getIndex 0 0 (zip (dropWhile (==0) (solve (0:(l++[n+1])))) l)\n --print ((dropWhile (==0) (solve (0:(l++[n+1])))) , l)\n if m>=n\n then do\n print n\n putStr . unwords . map show . take n $ repeat 1\n else if l==[]\n then do\n mapM_ print (solve (0:(l++[n+1])))\n putStr . unwords . map show $ a\n else do\n print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n"}, {"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve ls = zipWith (\\x y -> y-x-1) ls (drop (m+1) ls)\n (mx,idx) = getIndex 0 0 (zip (solve (0:(l++[n+1]))) l)\n if l==[]\n then mapM_ print (solve (0:(l++[n+1])))\n else print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n"}, {"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n if m==0\n then do\n print n\n putStr . unwords . map show $ a\n else do\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve l = zipWith (\\x y -> y-x-1) l (drop (m+1) l)\n (mx,idx) = getIndex 0 0 (zip (solve (0:(l++[n+1]))) l)\n print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n"}, {"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve ls = zipWith (\\x y -> y-x-1) ls (drop (m+1) ls)\n (mx,idx) = getIndex 0 0 (zip (dropWhile (==0) (solve (0:(l++[n+1])))) l)\n if l==[]\n then mapM_ print (solve (0:(l++[n+1])))\n else print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n"}, {"source_code": "main = do\n [n,m] <- fmap ((map read) . words) getLine :: IO[Int]\n a <- fmap ((map read) . words) getLine :: IO[Int]\n let (_,l) = unzip . filter (\\(x,y) -> x==0) $ zip a [1..]\n solve l = zipWith (\\x y -> y-x-1) l (drop (m+1) l)\n (mx,idx) = getIndex 0 0 (zip (solve (0:(l++[n+1]))) l)\n print mx\n putStr . unwords . map show $ paint a 1 idx m\n\ngetIndex mx idx [] = (mx,idx)\ngetIndex mx idx ((a,b):xs)\n |a>mx = getIndex a b xs\n |otherwise = getIndex mx idx xs\n \npaint l _ _ 0 = l\npaint [] _ _ _ = []\npaint (x:xs) i idx c\n |i>=idx = if x==0 then 1:paint xs (i+1) idx (c-1) else 1:paint xs (i+1) idx c\n |otherwise = x:paint xs (i+1) idx c\n"}], "src_uid": "ec9b03577868d8999bcc54dfc1aae056"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nonecase = do\n\t\tgetLine\n\t\tk<- reverse <$> sort <$> map read <$> words <$> getLine:: IO [Int]\n\t\tprint $ length $ takeWhile (\\(a,b)-> a>=b) $ zip k [1..]\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$unlines.l.lines\nl=g.tail where g(n:a:x)=show(s(read n)(map read$words a)):g x;g a=a\ns n=maximum.zipWith min[n,n-1..1].sort"}, {"source_code": "import Data.List\nmain=interact$unlines.l.lines\nl=go.tail where go[]=[];go(n:a:x)=show(s(read n)(map read$words a)):go x\ns n=maximum.zipWith min[n,n-1..1].sort"}, {"source_code": "import Data.List\nimport Numeric\n\nint :: (Eq a, Num a) => String -> a\nint x = fst $ readDec x !! 0\n\nints :: (Eq a, Num a) => String -> [a]\nints = map int . words\n\nmain = interact $ unlines . solverLoop . lines\n\nsolverLoop (_:xs) = go xs\n where\n go [] = []\n go (n:a:xs) = show (solve (int n) (ints a)) : go xs\n\nsolve n xs = maximum $ zipWith min [n,n-1..1] $ sort xs\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetList :: (Read a) => IO [a]\ngetList = fmap (map read . words) getLine\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- getList\n print $ f a\n\nf :: [Int] -> Int\nf a = maximum $ map (\\p -> (min (fst p) (snd p))) $ zip [1..] $ reverse . sort $ a"}, {"source_code": "import Control.Monad\nimport Data.List\n\ngetList :: (Read a) => IO [a]\ngetList = fmap (map read . words) getLine\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n _ <- getLine\n a <- getList\n print $ f a\n\nf :: [Int] -> Int\nf a = maximum $ map (\\p -> min (fst p) $ snd p) $ zip [1..] $ reverse . sort $ a"}, {"source_code": "import Data.List (sortBy)\n\nprocess :: [Int] -> Int\nprocess = maximum . zipWith min [1..] . sortBy (flip compare)\n\nreadInt :: String -> Int\nreadInt = read\n\nrun :: Int -> IO ()\nrun 0 = return ()\nrun t = do\n n <- fmap readInt getLine\n a <- fmap (map readInt.words) getLine\n print $ process a\n run (t-1)\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n run t"}, {"source_code": "import Data.List as L\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines _ [] = []\ngroupByNLines n strings = (L.take n strings):(groupByNLines n (L.drop n strings))\n\nstringToIntegerArray :: String -> [Integer]\nstringToIntegerArray = L.map (\\x -> read x :: Integer) . words\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByNLines 2 . tail . lines)\n\nparse :: [String] -> String\nparse [_, arr'] = show $ solve arr\n where arr = stringToIntegerArray arr'\n\nsolve' :: [Integer] -> Integer -> Integer\nsolve' arr idx\n | currentMin >= idx = solve' arr (idx+1)\n | otherwise = (idx-1)\n where currentMin = minimum $ take (fromIntegral idx) arr\n\nsolve :: [Integer] -> Integer\nsolve arr = solve' (reverse $ L.sort arr) 1\n"}], "negative_code": [], "src_uid": "09236a3faa7fce573a4e5e758287040f"} {"source_code": "import Data.List\n\ndata Gem = Power | Time | Space | Soul | Reality | Mind deriving (Show, Read, Eq)\n\ngemFromString :: String -> Gem\ngemFromString \"purple\" = Power\ngemFromString \"green\" = Time\ngemFromString \"blue\" = Space\ngemFromString \"orange\" = Soul\ngemFromString \"red\" = Reality\ngemFromString \"yellow\" = Mind\n\n\nmain = interact foo\n\nfoo :: String -> String\nfoo i = \n let gems = map gemFromString $ tail . lines $ i\n o = map show $ filter (\\g -> not $ g`elem` gems) [Power, Time, Space, Soul, Reality, Mind]\n in unlines $ (show $ length o) : o", "positive_code": [{"source_code": "module Main where\n\nimport Data.List (find)\n\ncolors = [(\"red\",\"Reality\"), (\"purple\",\"Power\"), (\"yellow\",\"Mind\"), (\"orange\",\"Soul\"), (\"blue\",\"Space\"), (\"green\",\"Time\")]\n\nmain :: IO ()\nmain = do\n x <- getLine\n lst <- readWords ((read :: String -> Int) x)\n print ((length colors) - (length lst))\n solveW lst\n\nreadWords :: Int -> IO [String]\nreadWords 0 = return []\nreadWords n = do\n lst <- readWords(n-1)\n name <- getLine\n return (name : lst)\n\n\nsolveW :: [String] -> IO ()\nsolveW lst = foldl (\\a (b,name) -> case find (== b) lst of\n Just _ -> a\n Nothing -> do putStrLn name\n a\n ) (return ()) colors\n"}, {"source_code": "module Main where\n\nimport Data.Maybe (fromJust)\nimport Control.Applicative\nimport Control.Monad (guard, liftM2, replicateM, (>=>), forM_)\nimport Data.Char (digitToInt, isDigit, isSpace)\nimport Data.Functor ((<$>))\n\nnewtype Parser a = Parser\n { runParser :: String -> Maybe (a, String)\n }\n\ninstance Functor Parser where\n fmap f x = pure f <*> x \n\ninstance Applicative Parser where\n pure = return\n (<*>) = liftM2 ($)\n\ninstance Monad Parser where\n return x = Parser $ \\s -> Just (x, s)\n ma >>= f = Parser $ runParser ma >=> (\\(x, rest) -> runParser (f x) rest)\n\ninstance Alternative Parser where\n empty = Parser $ const Nothing\n (Parser p) <|> (Parser q) = Parser $ \\s -> p s <|> q s\n\nok :: Parser ()\nok = return ()\n\neof :: Parser ()\neof = Parser $ \\s -> guard (null s) >> Just ((), s)\n\nsatisfy :: (Char -> Bool) -> Parser Char\nsatisfy p =\n Parser $ \\x ->\n case x of\n (c:cs) -> guard (p c) >> Just (c, cs)\n _ -> Nothing\n\nisNot :: Parser a -> Parser ()\nisNot (Parser p) =\n Parser $ \\s ->\n case p s of\n Just _ -> Nothing\n Nothing -> Just ((), s)\n\nreadP :: Read a => Parser a\nreadP = read <$> some (satisfy $ not . isSpace)\n\nskipSpace :: Parser ()\nskipSpace = () <$ many (satisfy isSpace)\n\nparse :: Read a => String -> Maybe a\nparse = fmap fst . runParser readP \n\nstones = [(\"purple\", \"Power\"), (\"green\", \"Time\"), (\"blue\", \"Space\")\n , (\"orange\", \"Soul\"), (\"red\", \"Reality\"), (\"yellow\", \"Mind\")]\n\nmain :: IO ()\nmain = do\n l <- getLine\n let n = fromJust $ parse l\n present <- replicateM n getLine\n let ans = filter (\\p -> not $ elem (fst p) present) stones\n print $ length ans\n forM_ ans $ putStrLn . snd"}, {"source_code": "g::String->String\ng \"purple\"=\"Power\"\ng \"green\"=\"Time\"\ng \"blue\"=\"Space\"\ng \"orange\"=\"Soul\"\ng \"red\"=\"Reality\"\ng \"yellow\"=\"Mind\"\n\nf::[String]->[String]->[String]\nf [] _=[]\nf (y:ys) xs\n |(y `elem` xs)==True=f ys xs\n |otherwise=(g y):(f ys xs)\n\nmain = do\n e1<-getLine\n es<-getContents\n let x=read e1::Int\n xs=lines es\n putStr $ if x==6 then \"0\" else show(6-x)++\"\\n\"++unlines (f [\"purple\",\"green\",\"blue\",\"orange\",\"red\",\"yellow\"] xs)"}, {"source_code": "import Data.List\nimport Data.Array\n\nreadColors :: Int -> IO [Int]\nreadColors 0 = return []\nreadColors n = do \n s <- getLine\n tail <- readColors $ n - 1\n return ((case s of\n \"purple\" -> 0\n \"green\" -> 1\n \"blue\" -> 2\n \"orange\" -> 3\n \"red\" -> 4\n \"yellow\" -> 5) : tail)\n\nprintAns :: [Int] -> IO ()\nprintAns [] = return ()\nprintAns (a : tail) = do\n putStrLn $ case a of\n 0 -> \"Power\"\n 1 -> \"Time\"\n 2 -> \"Space\"\n 3 -> \"Soul\"\n 4 -> \"Reality\"\n 5 -> \"Mind\"\n printAns tail\n return ()\n\nmain = do\n s <- getLine\n let n = read s :: Int\n arr <- readColors n\n let ans = filter (\\x -> not $ elem x arr) [0..5]\n print $ length ans\n printAns ans"}, {"source_code": "import Data.List\nimport Data.Maybe\nm = [ (\"purple\",\"Power\"),\n (\"green\",\"Time\"),\n (\"blue\",\"Space\"),\n (\"orange\",\"Soul\"),\n (\"red\",\"Reality\"),\n (\"yellow\",\"Mind\") ]\nmain = do\n getLine\n cs <- lines <$> getContents\n let r = map snd m \\\\ catMaybes (map (flip lookup m) cs)\n print (length r)\n mapM_ putStrLn r\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map.Strict as Map\n\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n\nmain = do\n let c = [\"purple\", \"green\", \"blue\", \"orange\", \"red\", \"yellow\"]\n let h = Map.fromList [(\"purple\", \"Power\"),\n (\"green\", \"Time\"),\n (\"blue\", \"Space\"),\n (\"orange\", \"Soul\"),\n (\"red\", \"Reality\"),\n (\"yellow\", \"Mind\")]\n n <- fmap read getLine\n a <- replicateM n getLine\n let xs = c \\\\ a\n print $ length xs\n mapM_ putStrLn (map (\\k -> Map.findWithDefault \"def\" k h) xs)\n"}, {"source_code": "import Control.Monad\n\ngems :: [(String, String)]\ngems = [\n (\"Power\", \"purple\"),\n (\"Time\", \"green\"),\n (\"Space\", \"blue\"),\n (\"Soul\", \"orange\"),\n (\"Reality\", \"red\"),\n (\"Mind\", \"yellow\")\n ]\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n present <- replicateM n getLine\n let result = map fst . filter (not . flip elem present . snd) $ gems\n print $ length result\n forM_ result putStrLn\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\nimport qualified Data.Map as M\n\nmas= S.fromList [\"purple\", \"green\" , \"blue\",\"orange\",\"red\", \"yellow\"]\nmasmap = M.fromList $ zip [\"purple\", \"green\" , \"blue\",\"orange\",\"red\", \"yellow\"] [\"Power\",\"Time\",\"Space\",\"Soul\",\"Reality\",\"Mind\"]\n\n\n\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\ts<- S.fromList <$> replicateM a getLine\n\t\tlet s1 = S.difference mas s\n\t\tlet s2 = catMaybes $ map (\\z-> M.lookup z masmap) $ S.toList s1\n\t\tprint $ S.size s1\t\t\t\n\t\tmapM_ putStrLn s2\n\n"}, {"source_code": "--ghc 7.10\n\nassocs :: [(String, String)]\nassocs = [(\"Power\",\"purple\"),(\"Time\",\"green\"),(\"Space\",\"blue\"),(\"Soul\",\"orange\"),(\"Reality\",\"red\"),(\"Mind\",\"yellow\")]\n\nfindAbsentGems :: [String] -> [String]\nfindAbsentGems colors = map fst . filter (\\(_,c) -> not (c `elem` colors)) $ assocs\n\nmain = do\n nStr <- getLine\n contents <- getContents\n let colors = words contents\n let gems = findAbsentGems colors\n let m = length gems\n print m\n putStrLn . unlines $ gems"}, {"source_code": "module Main where\n\nimport Data.List\n\nstones :: [(String,String)]\nstones = [\n (\"green\", \"Time\"),\n (\"purple\", \"Power\"),\n (\"blue\", \"Space\"),\n (\"orange\", \"Soul\"),\n (\"red\",\"Reality\"),\n (\"yellow\",\"Mind\")\n ]\n\nmain :: IO ()\nmain = do\n n <- fmap (read) getLine\n colors <- sequence $ Prelude.take n . repeat $ getLine\n let allColors = map fst stones\n remaining = Prelude.filter (\\(color,_) -> not . isInfixOf [color] $ colors) stones\n print $ length remaining\n mapM_ (\\(_,name) -> putStrLn name) remaining\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nstoneMap :: String -> String\nstoneMap \"red\" = \"Reality\"\nstoneMap \"purple\" = \"Power\"\nstoneMap \"green\" = \"Time\"\nstoneMap \"blue\" = \"Space\"\nstoneMap \"orange\" = \"Soul\"\nstoneMap \"yellow\" = \"Mind\"\n\nmain :: IO ()\nmain = do\n inp <- getLine\n let n = read inp :: Int\n inpp <- replicateM n getLine\n print (6 - n)\n let stones = [\"Power\", \"Space\", \"Soul\", \"Mind\", \"Time\", \"Reality\"]\n let have = map stoneMap inpp\n mapM (putStrLn) (stones \\\\ have)\n return ()\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List (find)\n\ncolors = [(\"red\",\"Reality\"), (\"purple\",\"Power\"), (\"yellow\",\"Mind\"), (\"orange\",\"Soul\"), (\"blue\",\"Space\"), (\"green\",\"Time\")]\n\nmain :: IO ()\nmain = do\n x <- getLine\n lst <- readWords ((read :: String -> Int) x)\n print $ solve lst\n\nreadWords :: Int -> IO [String]\nreadWords 0 = return []\nreadWords n = do\n lst <- readWords(n-1)\n name <- getLine\n return (name : lst)\n\nsolve :: [String] -> String\nsolve lst = (show ((length colors) - (length lst))) ++ solveW lst\n\nsolveW :: [String] -> String\nsolveW lst = foldl (\\a (b,name) -> case find (== b) lst of\n Just _ -> a\n Nothing -> a ++ \"/n\" ++ name) \"\" colors\n"}, {"source_code": "module Main where\n\nimport Data.List (find)\n\ncolors = [(\"red\",\"Reality\"), (\"purple\",\"Power\"), (\"yellow\",\"Mind\"), (\"orange\",\"Soul\"), (\"blue\",\"Space\"), (\"green\",\"Time\")]\n\nmain :: IO ()\nmain = do\n x <- getLine\n lst <- readWords ((read :: String -> Int) x)\n putStr $ solve lst\n\nreadWords :: Int -> IO [String]\nreadWords 0 = return []\nreadWords n = do\n lst <- readWords(n-1)\n name <- getLine\n return (name : lst)\n\nsolve :: [String] -> String\nsolve lst = (show ((length colors) - (length lst))) ++ solveW lst\n\nsolveW :: [String] -> String\nsolveW lst = foldl (\\a (b,name) -> case find (== b) lst of\n Just _ -> a\n Nothing -> a ++ \"/n\" ++ name) \"\" colors\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nstones :: [(String,String)]\nstones = [\n (\"green\", \"Time\"),\n (\"purple\", \"Power\"),\n (\"blue\", \"Space\"),\n (\"orange\", \"Soul\"),\n (\"red\",\"Reality\"),\n (\"yellow\",\"Mind\")\n ]\n\nmain :: IO ()\nmain = do\n n <- fmap (read) getLine\n colors <- sequence $ Prelude.take n . repeat $ getLine\n let allColors = map fst stones\n remaining = Prelude.filter (\\(color,_) -> not . isInfixOf [color] $ colors) stones\n mapM_ (\\(_,name) -> putStrLn name) remaining\n"}], "src_uid": "7eff98fbcf4e4a3284e2d2f98351fe4a"} {"source_code": "import Control.Monad\r\n\r\nsolve1 [] _ = 10\r\nsolve1 ((x,i):xs) t\r\n | t > 5 - div (i-1) 2 = i-1\r\n | otherwise = solve1 xs (t+x)\r\n\r\nsolve2 [] _ = 10\r\nsolve2 ((x,i):xs) t\r\n | t > 5 - div i 2 = i-1\r\n | otherwise = solve2 xs (t+x)\r\n\r\nzip1 (x,i)\r\n | x /= '0' && odd i = (1,i)\r\n | x == '1' && even i = (-1,i)\r\n | otherwise = (0,i)\r\n\r\nzip2 (x,i)\r\n | x /= '0' && even i = (1,i)\r\n | x == '1' && odd i = (-1,i)\r\n | otherwise = (0,i)\r\n\r\nprintResult = do\r\n s <- getLine\r\n let z = zip s [1..]\r\n z1 = map zip1 z\r\n z2 = map zip2 z\r\n print $ min (solve1 z1 0) (solve2 z2 0)\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult", "positive_code": [{"source_code": "import Control.Monad\r\n\r\nsolve1 [] _ = 10\r\nsolve1 ((x,i):xs) t\r\n | t > 5 - div (2*(i-1)) 4 = i-1\r\n | otherwise = solve1 xs (t+x)\r\n\r\nsolve2 [] _ = 10\r\nsolve2 ((x,i):xs) t\r\n | t > 5 - div i 2 = i-1\r\n | otherwise = solve2 xs (t+x)\r\n\r\nzip1 (x,i)\r\n | x /= '0' && odd i = (1,i)\r\n | x == '1' && even i = (-1,i)\r\n | otherwise = (0,i)\r\n\r\nzip2 (x,i)\r\n | x /= '0' && even i = (1,i)\r\n | x == '1' && odd i = (-1,i)\r\n | otherwise = (0,i)\r\n\r\nprintResult = do\r\n s <- getLine\r\n let z = zip s [1..]\r\n z1 = map zip1 z\r\n z2 = map zip2 z\r\n print $ min (solve1 z1 0) (solve2 z2 0)\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Char (digitToInt)\r\n\r\n\r\nminKicks :: [Int] -> Int \r\nminKicks = go (0, 0) 0 where\r\n remaining i = let d = 10 - i in (d `div` 2, d `div` 2 + d `rem` 2)\r\n gameEnds (t1, t2) i = let (remT1, remT2) = remaining i in\r\n t1 > t2 + remT2 || t2 > t1 + remT1\r\n go (t1, t2) _ [] = 10\r\n go (t1, t2) i (x : xs) \r\n | gameEnds (t1, t2) i = i\r\n | even i = go (t1 + x, t2) (i + 1) xs\r\n | otherwise = go (t1, t2 + x) (i + 1) xs\r\n\r\nsolve :: String -> Int\r\nsolve s = min (minKicks scoresT1) (minKicks scoresT2) where\r\n switch team i c \r\n | c == '?' = if i `rem` 2 == team then 1 else 0\r\n | otherwise = digitToInt c\r\n scoresT1 = zipWith (switch 0) [0..] s\r\n scoresT2 = zipWith (switch 1) [0..] s\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n scores <- getLine\r\n print $ solve scores"}, {"source_code": "{-# LANGUAGE ParallelListComp #-}\n\nimport Control.Arrow ((>>>))\nimport Data.Bool (bool)\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> map (solve >>> show) >>> unlines\n\nsolve :: String -> Int\nsolve s = min (compute '0' '1') (compute '1' '0')\n where\n compute atOdd atEven = cost . replaceAt odd atOdd . replaceAt even atEven $ s\n\nreplaceAt :: (Int -> Bool) -> Char -> String -> String\nreplaceAt p v xs = [if x == '?' && p i then v else x | x <- xs | i <- [0 ..]]\n\ncost :: String -> Int\ncost = rec (0, 5) (0, 5)\n where\n rec _ _ [] = 0\n rec (s0, r0) (s1, r1) (p : ps)\n | s0' + r0' < s1 = 1\n | s1 + r1 < s0' = 1\n | otherwise = 1 + rec (s1, r1) (s0', r0') ps\n where\n s0' = s0 + bool 0 1 (p == '1')\n r0' = r0 - 1\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nlmargins :: [Int]\nlmargins = scanl' (+) (0-5) $ cycle [1, 0]\nrmargins :: [Int]\nrmargins = scanl' (-) 5 $ cycle [0, 1]\n\nsim :: String -> [(Int, Int)]\nsim = let\n go :: [Int] -> (Int, Int) -> String -> [(Int, Int)]\n go (_:xs) (p, q) ('0':cs) = (p, q) : go xs (p, q) cs\n go (x:xs) (p, q) ('1':cs) = (p, q) : go xs (p + x, q + x) cs\n go (x:xs) (p, q) ('?':cs) = (p, q) : go xs (p + min 0 x, q + max 0 x) cs\n go _ (p, q) [] = [(p, q)]\n go _ _ _ = error \"invalid input\"\n in go (cycle [1, 0-1]) (0, 0)\n\nresult :: String -> Int\nresult str = let\n opts = 10 : do\n (i, (p, q), lv, rv) <- zip4 [0..] (sim str) lmargins rmargins\n [i | p < lv || q > rv]\n in minimum opts\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n s <- P.unpack <$> readLine\n putInts [result s]\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "ba1aa2483f88164c1f281eebaab2cfbd"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Prelude hiding (getLine)\nimport Data.List (unfoldr)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString, getLine)\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.List (group, sort)\nimport Control.Arrow ((&&&))\nimport Data.Function (on)\n\nsolve :: [Int] -> [Int] -> String\nsolve = loop 0 `on` (reverse . count)\n where\n count = map (head &&& length) . group . sort\n loop acc _ _\n | acc < 0 = \"YES\"\n loop _ [] _ = \"NO\"\n loop acc ((i,x):xs') [] = loop (acc - x) xs' []\n loop acc xs@((i, x):xs') ys@((j, y):ys') = case i `compare` j of\n LT -> loop (acc + y) xs ys'\n EQ -> loop (acc - x + y) xs' ys'\n GT -> loop (acc - x) xs' ys\n\nparse :: ByteString -> [Int]\nparse = unfoldr $ B.readInt . B.dropWhile (== ' ')\n\nmain :: IO ()\nmain = do\n getLine\n a <- parse <$> getLine\n getLine >>= putStrLn . solve a . parse\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Maybe (fromJust)\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain :: IO()\nmain = output . solve . map (fst . fromJust . C.readInt) . C.words =<< B.getContents\n\noutput :: Bool -> IO()\noutput True = putStrLn \"YES\"\noutput False = putStrLn \"NO\"\n\nsolve :: [Int] -> Bool\nsolve (n:_:k:s) = let (a, b) = splitAt n s\n sa = reverse $ sort a\n sb = reverse $ sort b\n in solve' k sa sb 0 0\n where solve' :: Int -> [Int] -> [Int] -> Int -> Int -> Bool\n solve' 0 _ _ _ _ = False\n solve' k [] [] na nb = na > nb\n solve' k (a:sa) [] na nb = na + (length (a:sa)) > nb\n solve' k [] (b:sb) na nb | k == b = solve' k [] sb na (nb + 1)\n | otherwise = na > nb\n solve' k (a:sa) (b:sb) na nb | k == a = solve' k sa (b:sb) (na + 1) nb\n | k == b = solve' k (a:sa) sb na (nb + 1)\n | na > nb = True\n | otherwise = solve' (min (k - 1) (max a b)) (a:sa) (b:sb) na nb\n"}, {"source_code": "--{-# OPTIONS -O2 -v0 #-}\n\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\n\nsolve :: [Int] -> [Int] -> Int -> String\nsolve xxs yys c | c > 0 = \"YES\" | null xxs = \"NO\"\n | null yys = solve xs [] (c + 1)\n | otherwise = if x == y then solve xs ys c \n else (if x > y then solve xs yys (c + 1) else solve xxs ys (c - 1))\n where (x:xs) = xxs\n (y:ys) = yys\n\nreadi :: B.ByteString -> Int\nreadi = fst . fromJust . B.readInt \n\n\nmain = do\n --ls <- sequence $ replicate 3 getLine\n --let [[n, m, k], a, b] = map (map read . words :: String -> [Int]) ls\n ls <- sequence $ replicate 3 B.getLine\n let [[n,m,k],a,b] = map (map readi . B.words) ls\n putStrLn $ solve (sorty a) (sorty b) 0\n where sorty = sortBy (flip compare)--U.toList . U.modify (I.sortBy (flip compare)) . U.fromList \n "}, {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nsolve :: [Int] -> [Int] -> Int -> String\nsolve xxs yys c | c > 0 = \"YES\" | null xxs = \"NO\"\n | null yys = solve xs [] (c + 1)\n | otherwise = if x == y then eqc else (if x > y then gtc else ltc)\n where (x:xs) = xxs\n (y:ys) = yys\n eqc = solve xs ys c\n gtc = solve xs yys (c + 1)\n ltc = solve xxs ys (c - 1)\n\nmain = do\n [[n,m,k],a,b] <- fmap (map (map (fst . fromJust . B.readInt) . B.words) . B.lines) B.getContents\n putStrLn $ solve (sorty a) (sorty b) 0\n where sorty = sortBy (flip compare) \n "}], "negative_code": [], "src_uid": "01cd3f0c6bc2975118075d180bfeba2d"} {"source_code": "module Main where\n\ndata Skier = Skier Int Int Int Int Int\n deriving (Eq, Show)\n\ninstance Ord Skier where\n compare (Skier n1 _ _ t1 _) (Skier n2 _ _ t2 _) =\n if t1 == t2 && n1 == n2 then EQ else\n if t1 < t2 || (t1 == t2 && n1 > n2) then LT\n else GT\n\nisRun :: Int -> Skier -> Bool\nisRun num (Skier _ l r _ _) = l <= num && num <= r\n\nsolve :: Int -> [Skier] -> Int\nsolve 0 _ = 0\nsolve n skiers = current + solve (n-1) skiers where\n current = cost winner\n cost (Just (Skier _ _ _ _ c)) = c\n cost Nothing = 0\n winner = if length rn == 0 then Nothing else Just (minimum rn)\n rn = filter (isRun n) skiers\n\nreadSkiers :: Int -> IO [Skier]\nreadSkiers 0 = return []\nreadSkiers n = do\n sk <- getLine\n let x = map read $ words sk\n let skier = Skier n (x!!0) (x!!1) (x!!2) (x!!3)\n follow <- readSkiers $ n-1\n return (skier:follow)\n\nmain = do\n sNM <- getLine\n let nm = map read $ words sNM\n let n = nm !! 0\n let m = nm !! 1\n lst <- readSkiers m\n-- print lst\n print $ solve n lst\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\n\nprofit i = snd . foldl (\\(x, y) [l,r,t,c] -> if l <= i && i <= r && t < x then (t, c) else (x, y)) (10000, 0)\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet [n, m] = map (fst . fromJust . C.readInt) . C.words $ head input\n\tlet lrtcs = map (map (fst . fromJust . C.readInt) . C.words) . take m $ tail input\n\tprint $ sum [ profit i lrtcs | i <- [1..n] ]\n"}, {"source_code": "data Runner\n = Runner\n {\n left :: Int,\n right :: Int,\n time :: Int,\n count :: Int,\n number :: Int\n } deriving Show\n \nreadRunner :: Int -> IO Runner\nreadRunner n = do\n line <- getLine\n let [l, r, t, c] = map read $ words line\n return (Runner l r t c n)\n\nrunnerInEtap :: Int -> Maybe Runner -> Bool\nrunnerInEtap _ Nothing = False\nrunnerInEtap etap (Just (Runner l r t c n))\n | l <= etap && etap <= r = True\n | otherwise = False\n \n\n\nbestRunner' :: Int -> Maybe Runner -> Runner -> Maybe Runner\nbestRunner' etap Nothing r@(Runner l2 r2 t2 c2 n2)\n | runnerInEtap etap (Just r) = Just r\n | otherwise = Nothing\nbestRunner' etap (Just runner1@(Runner l1 r1 t1 c1 n1)) runner2@(Runner l2 r2 t2 c2 n2)\n | not (runnerInEtap etap (Just runner1)) = bestRunner' etap Nothing runner2\n | not (runnerInEtap etap (Just runner2)) = bestRunner' etap Nothing runner1\n | t1 < t2 = Just runner1\n | t2 < t1 = Just runner2\n | n1 < n2 = Just runner1\n | n2 < n1 = Just runner2\n | otherwise = error \"XM...\"\n\nbestRunner :: Int -> [Runner] -> Maybe Runner\nbestRunner etap runners = foldl (bestRunner' etap) Nothing runners\n\ncountRunner :: Maybe Runner -> Int\ncountRunner Nothing = 0\ncountRunner (Just r) = count r\n\nmain = do\n line <- getLine\n let [n, m] = map read (words line)\n runners <- sequence (map readRunner [1..m])\n print $ sum (map (\\n -> countRunner (bestRunner n runners)) [1..n])\n"}, {"source_code": "import Data.List\nimport Data.Function\nmain = do\n [n, m] <- (map read . words) `fmap` getLine\n l <- mapM (\\_ -> (map read . words) `fmap` getLine) [1..m]\n let f' i [l, r, t, c] | i >= l && i <= r = (t, c)\n | otherwise = (1001, 0)\n f = map (\\i -> min1 $ map (f' i) l) [1..n]\n min1 = foldl (\\m x -> if fst x < fst m then x else m) (1001, 0)\n s = foldl (\\s (_, x) -> s + x) 0 f\n print s \n"}], "negative_code": [], "src_uid": "ea1bebf20f24a681f03082c92326db5e"} {"source_code": "{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\nimport Data.Functor ( (<&>) )\nimport Control.Arrow ((>>>))\nimport Control.Monad (forM_)\nimport Data.Maybe (fromJust)\nimport Data.Traversable (forM)\nimport qualified Control.Monad.State.Strict as S\nimport qualified Data.IntMap as IM\nimport Control.Monad (foldM_)\nimport Data.Int\n\nreadIntB8 :: B8.ByteString -> Maybe Int\nreadIntB8 = B8.readInt >>> fmap fst\n\nsolve :: B8.ByteString -> [[Int]] -> [Bool]\nsolve str qs = do\n [l, r] <- qs\n let Just li = B8.elemIndex (str `B8.index` l) str\n let Just ri = B8.elemIndexEnd (str `B8.index` r) str\n return $ (li, ri) /= (l, r)\n\nmain :: IO ()\nmain = do\n Just t <- B8.getLine <&> readIntB8\n forM_ [1 .. t] $ \\_ -> do\n [n, q] <- B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust)\n str <- B8.getLine\n qs <- forM [1 .. q] $ \\_ -> B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust >>> (+ (-1)))\n let answers = solve str qs\n forM_ answers $ \\answer -> \n B8.putStrLn $ if answer then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport Data.Bool (bool)\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1 >>> process >>> concat >>> map (bool \"NO\" \"YES\") >>> unlines\n\nprocess :: [String] -> [[Bool]]\nprocess [] = []\nprocess (nq:s:xss) = map (solve s) qs : process xss'\n where\n q = words >>> last >>> read $ nq\n (xs, xss') = splitAt q xss\n qs = map (words >>> map read) xs\n\nsolve :: String -> [Int] -> Bool\nsolve s [l, r] =\n elem (s !! (l - 1)) (take (l - 1) s) || elem (s !! (r - 1)) (drop r s)\n"}], "negative_code": [], "src_uid": "cbd91ac0fc9e4ca01996791e4c94bd6e"} {"source_code": "-- https://codeforces.com/contest/1428/problem/A\nimport Control.Monad (mapM_)\n\nsolution :: Integral a => (a,a) -> (a,a) -> a\nsolution (x1,y1) (x2,y2)\n | x1 == x2 = abs (y2 - y1)\n | y1 == y2 = abs (x2 - x1)\n | otherwise = abs (x2 - x1) + abs (y2 - y1) + 2\n\nmain = do\n numTests <- read <$> getLine\n tests <- sequence $ replicate numTests $ do\n [x1,y1,x2,y2] <- map read . words <$> getLine\n return $ solution (x1,y1) (x2,y2)\n mapM_ (putStrLn . show) tests\n", "positive_code": [{"source_code": "import Data.List\n\n\nmain = interact $ concat . intersperse \"\\n\" . map (show . pull) . drop 1 . (map . map) read . map words . lines\n\npull :: [Int] -> Int\npull (fx:fy:tx:ty:_)\n | fx == tx = abs (fy - ty)\n | fy == ty = abs (fx - tx)\n | fx == tx && fy == ty = 0\n | otherwise = abs (fy - ty) + abs (fx - tx) + 2"}, {"source_code": "import Control.Monad\n \nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n \nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [x1, y1, x2, y2] <- readInts\n let\n ans = (abs (x2 - x1) + abs (y2 - y1) ) + if ( x1 == x2 || y1 == y2 ) then 0 else 2\n print ans"}, {"source_code": "import Control.Monad\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [x1, y1, x2, y2] <- readInts\n let\n x' = abs (x2 - x1)\n y' = abs (y2 - y1)\n ans = x' + y' + if x' > 0 && y' > 0 then 2 else 0\n print ans\n"}], "negative_code": [{"source_code": "-- https://codeforces.com/contest/1428/problem/A\n\nsolution :: Integral a => (a,a) -> (a,a) -> a\nsolution (x1,y1) (x2,y2) = abs (x2 - x1) + abs (y2 - y1) + 2\n\nmain = do\n numTests <- read <$> getLine\n sequence_ $ replicate numTests $ do\n [x1,y1,x2,y2] <- map read . words <$> getLine\n print $ solution (x1,y1) (x2,y2)\n"}], "src_uid": "6a333044e2ed8f9f4fa44bc16b994418"} {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n FlexibleInstances, ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad hiding (mapM, mapM_, forM, forM_)\nimport Control.Monad.State hiding (mapM, mapM_, forM, forM_)\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Foldable\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.Ix\nimport Data.List hiding (and, or, any, all, foldr, foldl')\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.STRef\nimport Data.Traversable\nimport Prelude hiding (and, or, any, all, mapM, mapM_)\nimport System.IO\n\n------\n\ndata P a b = P !a !b\n deriving (Show, Eq, Ord)\n\ndata T a b c = T !a !b !c\n deriving (Show, Eq, Ord)\n\ndata Q a b c d = Q !a !b !c !d\n deriving (Show, Eq, Ord)\n\nclass HasFirst a t | t -> a where\n first :: t -> a\n\ninstance HasFirst a (P a b) where\n first (P x _) = x\n\ninstance HasFirst a (T a b c) where\n first (T x _ _) = x\n\ninstance HasFirst a (Q a b c d) where\n first (Q x _ _ _) = x\n\ninstance HasFirst a (a, b) where\n first (x, _) = x\n\ninstance HasFirst a (a, b, c) where\n first (x, _, _) = x\n\ninstance HasFirst a (a, b, c, d) where\n first (x, _, _, _) = x\n\nclass HasSecond b t | t -> b where\n second :: t -> b\n\ninstance HasSecond b (P a b) where\n second (P _ x) = x\n\ninstance HasSecond b (T a b c) where\n second (T _ x _) = x\n\ninstance HasSecond b (Q a b c d) where\n second (Q _ x _ _) = x\n\ninstance HasSecond b (a, b) where\n second (_, x) = x\n\ninstance HasSecond b (a, b, c) where\n second (_, x, _) = x\n\ninstance HasSecond b (a, b, c, d) where\n second (_, x, _, _) = x\n\nclass HasThird c t | t -> c where\n third :: t -> c\n\ninstance HasThird c (T a b c) where\n third (T _ _ x) = x\n\ninstance HasThird c (Q a b c d) where\n third (Q _ _ x _) = x\n\ninstance HasThird c (a, b, c) where\n third (_, _, x) = x\n\ninstance HasThird c (a, b, c, d) where\n third (_, _, x, _) = x\n\nclass HasFourth d t | t -> d where\n fourth :: t -> d\n\ninstance HasFourth d (Q a b c d) where\n fourth (Q _ _ _ x) = x\n\ninstance HasFourth d (a, b, c, d) where\n fourth (_, _, _, x) = x\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: (Functor m, MonadHopper r m) => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: (Functor m, MonadHopper B.ByteString m) => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: (Functor m, MonadHopper B.ByteString m) => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: (Functor m, MonadHopper B.ByteString m) => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: (Functor m, MonadHopper B.ByteString m) => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[n, u, r, d, l] <- popInts\n return $ bool \"NO\" \"YES\" $ solve n u r d l\n\n\nsolve n u r d l = or $ map test [Q tl tr br bl |\n tl <- [0, 1], tr <- [0, 1],\n br <- [0, 1], bl <- [0, 1]]\n where\n test (Q tl tr br bl) = and $ map test1 $\n [T u tl tr, T r tr br, T d br bl, T l bl tl]\n\n test1 (T m a b) | m == n = a == 1 && b == 1\n | m == 0 = a == 0 && b == 0\n | m == n - 1 && m == 1 = a + b == 1\n | m == n - 1 = a + b >= 1\n | m == 1 = a + b <= 1\n | otherwise = True\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n [n, u, r, d, l] <- getIntList\n putStrLn $ yesOrNo $ f n [u, r, d, l]\n\nf :: Int -> [Int] -> Bool\nf n s = or . map (check n s) $ ways\n where ways = map change [0..15]\n\ncheck :: Int -> [Int] -> [Int] -> Bool\ncheck n [u, r, d, l] [ul, ur, dl, dr] = and [\n ul + ur + n - 2 >= u && u >= ul + ur,\n dl + dr + n - 2 >= d && d >= dl + dr,\n ul + dl + n - 2 >= l && l >= ul + dl,\n ur + dr + n - 2 >= r && r >= ur + dr]\n\nchange :: Int -> [Int]\nchange = map (`mod` 2) . take 4 . iterate (`div` 2)"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n, u, r, d, l] <- getInts\n let\n xs = [0, 1]\n checkRange x = 0 <= x && x <= n - 2\n check (x, y, z, w) = checkRange (u - x - y) && checkRange (r - y - w) && checkRange (d - z - w) && checkRange (l - x - z)\n results = filter id $ map check $ [(x, y, z, w) | x <- xs, y <- xs, z <- xs, w <- xs]\n C.putStrLn $ C.pack $ if null results then \"NO\" else \"YES\"\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n, u, r, d, le] <- readInts\n let\n opts = foldr (liftM2 (:)) [[]] $ replicate 4 [0, 1]\n isOk opt = let\n up = opt !! 0 + opt !! 1\n rp = opt !! 1 + opt !! 2\n dp = opt !! 2 + opt !! 3\n lep = opt !! 3 + opt !! 0\n ok (v, p) = 0 <= v - p && v - p <= (n - 2)\n in all ok $ zip [u, r, d, le] [up, rp, dp, lep]\n ans = any isOk opts\n lift $ P.putStrLn $ P.pack $ if ans then \"YES\" else \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n FlexibleInstances, ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Exception (assert)\nimport Control.Monad hiding (mapM, mapM_, forM, forM_)\nimport Control.Monad.State hiding (mapM, mapM_, forM, forM_)\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Array.Unboxed (UArray)\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.Foldable\nimport Data.Int\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.Ix\nimport Data.List hiding (and, or, any, all, foldr, foldl')\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.STRef\nimport Data.Traversable\nimport Prelude hiding (and, or, any, all, mapM, mapM_)\nimport System.IO\n\n------\n\ndata P a b = P !a !b\n deriving (Show, Eq, Ord)\n\ndata T a b c = T !a !b !c\n deriving (Show, Eq, Ord)\n\ndata Q a b c d = Q !a !b !c !d\n deriving (Show, Eq, Ord)\n\nclass HasFirst a t | t -> a where\n first :: t -> a\n\ninstance HasFirst a (P a b) where\n first (P x _) = x\n\ninstance HasFirst a (T a b c) where\n first (T x _ _) = x\n\ninstance HasFirst a (Q a b c d) where\n first (Q x _ _ _) = x\n\ninstance HasFirst a (a, b) where\n first (x, _) = x\n\ninstance HasFirst a (a, b, c) where\n first (x, _, _) = x\n\ninstance HasFirst a (a, b, c, d) where\n first (x, _, _, _) = x\n\nclass HasSecond b t | t -> b where\n second :: t -> b\n\ninstance HasSecond b (P a b) where\n second (P _ x) = x\n\ninstance HasSecond b (T a b c) where\n second (T _ x _) = x\n\ninstance HasSecond b (Q a b c d) where\n second (Q _ x _ _) = x\n\ninstance HasSecond b (a, b) where\n second (_, x) = x\n\ninstance HasSecond b (a, b, c) where\n second (_, x, _) = x\n\ninstance HasSecond b (a, b, c, d) where\n second (_, x, _, _) = x\n\nclass HasThird c t | t -> c where\n third :: t -> c\n\ninstance HasThird c (T a b c) where\n third (T _ _ x) = x\n\ninstance HasThird c (Q a b c d) where\n third (Q _ _ x _) = x\n\ninstance HasThird c (a, b, c) where\n third (_, _, x) = x\n\ninstance HasThird c (a, b, c, d) where\n third (_, _, x, _) = x\n\nclass HasFourth d t | t -> d where\n fourth :: t -> d\n\ninstance HasFourth d (Q a b c d) where\n fourth (Q _ _ _ x) = x\n\ninstance HasFourth d (a, b, c, d) where\n fourth (_, _, _, x) = x\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: (Functor m, MonadHopper r m) => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: (Functor m, MonadHopper B.ByteString m) => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: (Functor m, MonadHopper B.ByteString m) => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: (Functor m, MonadHopper B.ByteString m) => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: (Functor m, MonadHopper B.ByteString m) => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = do\n ~[n, u, r, d, l] <- popInts\n return $ bool \"NO\" \"YES\" $ solve n u r d l\n\n\nsolve n u r d l = or $ map test [Q tl tr br bl |\n tl <- [0, 1], tr <- [0, 1],\n br <- [0, 1], bl <- [0, 1]]\n where\n test (Q tl tr br bl) = and $ map test1 $\n [T u tl tr, T r tr br, T d br bl, T l bl tl]\n\n test1 (T m a b) | m == n = a == 1 && b == 1\n | m == 0 = a == 0 && b == 0\n | m == n - 1 = a + b >= 1\n | m == 1 = a + b <= 1\n | otherwise = True\n"}], "src_uid": "1c94596da439c56b56e59da36734a912"} {"source_code": "{-# LANGUAGE ScopedTypeVariables, TupleSections #-}\r\nimport Control.Monad\r\nimport Data.Array.Unboxed\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as S\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, q, s, d] <- readInts\r\n a :: UArray Int Int <- listArray (0, n - 1) <$> readInts\r\n qs <- replicateM q $ (\\[i, k] -> (i, k)) <$> readInts\r\n let nb i = map ((i,) . (cost i >>= (,))) $ [l | l /= i] ++ [l - 1 | l > 0] ++ [r | r /= n] ++ [r - 1 | i /= r - 1]\r\n where l = lowerBound ((>= a!i - d) . (a!)) 0 i\r\n r = lowerBound ((>= a!i + d) . (a!)) i n\r\n cost i j = abs $ d - abs (a!i - a!j)\r\n edges = e ++ map flipE e\r\n where e = concatMap nb [0 .. n - 1]\r\n flipE (i, (w, j)) = (j, (w, i))\r\n g = accumArray (flip (:)) [] (0, length edges) edges :: Array Int [(Int, Int)]\r\n mst = prim (s - 1) (g!)\r\n ks = array (0, n - 1) $ zip vs ws :: UArray Int Int\r\n where vs = s - 1 : map snd mst\r\n ws = scanl max 0 $ map fst mst\r\n ok (i, k) = ks!(i - 1) <= k\r\n yesNo True = \"Yes\"\r\n yesNo _ = \"No\"\r\n putStr $ unlines $ map (yesNo . ok) qs\r\n\r\nprim :: Int -> (Int -> [(Int, Int)]) -> [(Int, Int)]\r\nprim s nb = go (S.fromList $ nb s) (IS.singleton s) where\r\n go pq vis = case S.minView pq of\r\n Nothing -> []\r\n Just (e@(w, u), pq') -> if u `IS.member` vis\r\n then go pq' vis\r\n else e : go (pq' <> S.fromList (nb u)) (IS.insert u vis)\r\n\r\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\r\nlowerBound f l h\r\n | l >= h = l\r\n | f m = lowerBound f l m\r\n | otherwise = lowerBound f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables, TupleSections #-}\r\nimport Control.Monad\r\nimport Data.Array.Unboxed\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as IS\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, q, s, d] <- readInts\r\n a :: UArray Int Int <- listArray (0, n - 1) <$> readInts\r\n qs <- replicateM q $ (\\[i, k] -> (i, k)) <$> readInts\r\n let nb i = map ((i,) . (cost i >>= (,))) $ [l | l /= i] ++ [l - 1 | l > 0] ++ [r | r /= n] ++ [r - 1 | i /= r - 1]\r\n where l = lowerBound ((>= a!i - d) . (a!)) 0 i\r\n r = lowerBound ((>= a!i + d) . (a!)) i n\r\n cost i j = abs $ d - abs (a!i - a!j)\r\n edges = e ++ map flipE e\r\n where e = concatMap nb [0 .. n - 1]\r\n flipE (i, (w, j)) = (j, (w, i))\r\n g = accumArray (flip (:)) [] (0, length edges) edges :: Array Int [(Int, Int)]\r\n mst = prim (s - 1) (g!)\r\n ks = array (0, n - 1) $ zip vs ws :: UArray Int Int\r\n where vs = s - 1 : map snd mst\r\n ws = scanl max 0 $ map fst mst\r\n ok (i, k) = ks!(i - 1) <= k\r\n yesNo True = \"Yes\"\r\n yesNo _ = \"No\"\r\n putStr $ unlines $ map (yesNo . ok) qs\r\n\r\ndata SkewHeap a = Empty | SkewNode a (SkewHeap a) (SkewHeap a) deriving Show\r\n\r\ninstance (Ord a) => Semigroup (SkewHeap a) where\r\n Empty <> h = h\r\n h <> Empty = h\r\n h1@(SkewNode x1 l1 r1) <> h2@(SkewNode x2 l2 r2)\r\n | x1 <= x2 = SkewNode x1 (h2 <> r1) l1\r\n | otherwise = SkewNode x2 (h1 <> r2) l2\r\n\r\ninstance (Ord a) => Monoid (SkewHeap a) where\r\n mempty = Empty\r\n\r\nsingleton :: a -> SkewHeap a\r\nsingleton x = SkewNode x Empty Empty\r\n\r\nextractMin :: (Ord a) => SkewHeap a -> Maybe (a, SkewHeap a)\r\nextractMin Empty = Nothing\r\nextractMin (SkewNode x l r) = Just (x, l <> r)\r\n\r\nprim :: Int -> (Int -> [(Int, Int)]) -> [(Int, Int)]\r\nprim s nb = reverse $ go (mconcat $ map singleton $ nb s) (IS.singleton s) [] where\r\n go pq vis edges = case extractMin pq of\r\n Nothing -> edges\r\n Just (e@(w, u), pq') -> if u `IS.member` vis\r\n then go pq' vis edges\r\n else go (pq' <> mconcat (map singleton $ nb u)) (IS.insert u vis) (e:edges)\r\n\r\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\r\nlowerBound f l h\r\n | l >= h = l\r\n | f m = lowerBound f l m\r\n | otherwise = lowerBound f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}, {"source_code": "-- The time complexity on this version is probably bad. It's fixable\n-- with segment trees, but I don't feel like doing that right now.\n-- Let's see if the test cases are strong enough to break this one!\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST.Lazy\nimport Data.Function\n\n--import Debug.Trace\ntraceShow :: a -> b -> b\ntraceShow _ y = y\n\n-------------------------------------------------------------------------------\n\ndata PQ t -- Maxiphobic persistent heap\n = Empty\n | Vertex t !Int (PQ t) (PQ t)\n deriving Show\n\ngetPQsize :: PQ t -> Int\ngetPQsize Empty = 0\ngetPQsize (Vertex _ sz _ _) = sz\n\ninstance Ord t => Semigroup (PQ t) where\n Empty <> q = q\n p <> Empty = p\n p@(Vertex pv ps pl pr) <> q@(Vertex qv qs _ _)\n | pv > qv = q <> p\n | otherwise = let\n [s1, s2, s3] = sortOn getPQsize [pl, pr, q]\n in Vertex pv (ps + qs) s3 $ s1 <> s2\n\ninstance Ord t => Monoid (PQ t) where\n mempty = Empty\n mappend = (<>)\n mconcat = let\n mergePairs [] = []\n mergePairs [v] = [v]\n mergePairs (p:q:rs) = (p <> q) : mergePairs rs\n in \\li -> case li of\n [] -> Empty\n [v] -> v\n _ -> mconcat (mergePairs li)\n\nsingle :: t -> PQ t\nsingle v = Vertex v 1 Empty Empty\n\ninsertAll :: Ord t => [t] -> PQ t -> PQ t\ninsertAll = (<>) . mconcat . map single\n\npopMaybe :: Ord t => PQ t -> Maybe (t, PQ t)\npopMaybe Empty = Nothing\npopMaybe (Vertex pv _ pl pr) = Just (pv, pl <> pr)\n\n-------------------------------------------------------------------------------\n\nisImprovement :: (Int, Int) -> [(Int, Int)] -> [Bool]\nisImprovement bnds li = runST $ do\n arr <- strictToLazyST $ newArray bnds maxBound :: ST s (STUArray s Int Int)\n forM li $ \\(ix, v) -> strictToLazyST $ do\n prev <- readArray arr ix\n (v < prev) <$ writeArray arr ix (min v prev)\n\nbinSearch :: UArray Int Int -> Int -> Int\nbinSearch arr tar = let\n (p, q) = bounds arr\n go li ri\n | li == ri = li\n | otherwise = let\n mi = li + div (ri - li) 2\n in if tar <= arr ! mi\n then go li mi\n else go (mi+1) ri\n in go p (q+1)\n\ndata ProcessDir\n = L { atIx :: !Int, getCost :: !Int }\n | R { atIx :: !Int, getCost :: !Int }\n deriving Show\n\ninstance Eq ProcessDir where -- not a pretty instance, but it is unused\n (==) = (==) `on` getCost\ninstance Ord ProcessDir where\n compare = compare `on` getCost\n (>) = (>) `on` getCost\n\nsuccessor :: UArray Int Int -> ProcessDir -> Maybe ProcessDir\nsuccessor arr (L ix cost) = if ix <= fst (bounds arr)\n then Nothing\n else Just $ L (ix - 1) (cost + arr ! ix - arr ! (ix - 1))\nsuccessor arr (R ix cost) = if ix >= snd (bounds arr)\n then Nothing\n else Just $ R (ix + 1) (cost + arr ! (ix + 1) - arr ! ix)\n\ndivergingAt :: UArray Int Int -> Int -> [ProcessDir]\ndivergingAt arr val = let\n tix = binSearch arr val\n (li, ri) = bounds arr\n lv = [L (tix - 1) (val - arr ! (tix - 1)) | tix > li]\n rv = [R tix (arr ! tix - val) | tix <= ri]\n in lv ++ rv\n\nsolve :: UArray Int Int -> Int -> Int -> UArray Int Int\nsolve arr startIx stepSize = let\n div2 ix = let\n v = arr ! ix\n in divergingAt arr (v - stepSize) ++ divergingAt arr (v + stepSize)\n solnStep :: [Bool] -> PQ ProcessDir -> [(Int, Int)]\n solnStep queryResponses pq = case popMaybe pq of\n Nothing -> []\n Just (a, npq) -> traceShow (\"Here!!\", a, npq) $ (atIx a, getCost a) : case queryResponses of\n [] -> error \"solve: unanswered query: bug in isImprovement?\"\n False : nqr -> solnStep nqr npq\n True : nqr -> let\n toIns = div2 (atIx a) ++ [a' | Just a' <- [successor arr a]]\n in solnStep nqr $ insertAll toIns npq\n queries = solnStep responses (insertAll (div2 startIx) Empty)\n responses = isImprovement (bounds arr) queries\n (pos, dists) = unzip $ (startIx, 0) : queries\n in accumArray min maxBound (bounds arr) $ zip pos (scanl1 max dists)\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, q, s, d] <- readInts\n a <- listArray (1, n) <$> readInts :: SIO (UArray Int Int)\n let ansKey = solve a s d\n traceShow ansKey $ pure ()\n replicateM_ q $ do\n [i, k] <- readInts\n lift $ B.hPutBuilder stdout $ if ansKey ! i <= k\n then B.string7 \"Yes\\n\"\n else B.string7 \"No\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables, TupleSections #-}\r\nimport Control.Monad\r\nimport Data.Array.Unboxed\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as IS\r\nimport qualified Data.Set as S\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, q, s, d] <- readInts\r\n a :: UArray Int Int <- listArray (0, n - 1) <$> readInts\r\n qs <- replicateM q readInts\r\n let nb i = map ((i,) . (cost i >>= (,))) $ [l | l /= i] ++ [l - 1 | l > 0] ++ [r | r /= n] ++ [r - 1 | i /= r - 1]\r\n where l = lowerBound ((>= a!i - d) . (a!)) 0 i\r\n r = lowerBound ((>= a!i + d) . (a!)) i n\r\n cost i j = abs $ d - abs (a!i - a!j)\r\n edges = e ++ map flipE e\r\n where e = concatMap nb [0 .. n - 1]\r\n flipE (i, (w, j)) = (j, (w, i))\r\n g = accumArray (flip (:)) [] (0, n - 1) edges :: Array Int [(Int, Int)]\r\n mst = prim (s - 1) (g!)\r\n ks = array (0, n - 1) $ zip vs ws :: UArray Int Int\r\n where vs = s - 1 : map snd mst\r\n ws = scanl max 0 $ map fst mst\r\n ok [i, k] = ks!(i - 1) <= k\r\n yesNo True = \"Yes\"\r\n yesNo _ = \"No\"\r\n putStr $ unlines $ map (yesNo . ok) qs\r\n\r\nprim :: Int -> (Int -> [(Int, Int)]) -> [(Int, Int)]\r\nprim s nb = go (S.fromList $ nb s) (IS.singleton s) where\r\n go pq vis = case S.minView pq of\r\n Nothing -> []\r\n Just (e@(w, u), pq') -> if u `IS.member` vis\r\n then go pq' vis\r\n else e : go (pq' <> S.fromList (nb u)) (IS.insert u vis)\r\n\r\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\r\nlowerBound f l h\r\n | l >= h = l\r\n | f m = lowerBound f l m\r\n | otherwise = lowerBound f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables, TupleSections #-}\r\nimport Control.Monad\r\nimport Data.Array.Unboxed\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.IntSet as IS\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n, q, s, d] <- readInts\r\n a :: UArray Int Int <- listArray (0, n - 1) <$> readInts\r\n qs <- replicateM q $ (\\[i, k] -> (i, k)) <$> readInts\r\n let nb i = map ((i,) . (cost i >>= (,))) $ [l | l /= i] ++ [l - 1 | l > 0] ++ [r | r /= n] ++ [r - 1 | i /= r - 1]\r\n where l = lowerBound ((>= a!i - d) . (a!)) 0 i\r\n r = lowerBound ((>= a!i + d) . (a!)) i n\r\n cost i j = abs $ d - abs (a!i - a!j)\r\n edges = e ++ map flipE e\r\n where e = concatMap nb [0 .. n - 1]\r\n flipE (i, (w, j)) = (j, (w, i))\r\n g = accumArray (flip (:)) [] (0, length edges) edges :: Array Int [(Int, Int)]\r\n mst = prim (s - 1) (g!)\r\n ks = array (0, n - 1) $ zip vs ws :: UArray Int Int\r\n where vs = s - 1 : map snd mst\r\n ws = scanl max 0 $ map fst mst\r\n ok (i, k) = ks!(i - 1) <= k\r\n yesNo True = \"Yes\"\r\n yesNo _ = \"No\"\r\n putStr $ unlines $ map (yesNo . ok) qs\r\n\r\ndata SkewHeap a = SkewNode {-# UNPACK #-} !a !(SkewHeap a) !(SkewHeap a)\r\n | Empty deriving Show\r\n\r\ninstance (Ord a) => Semigroup (SkewHeap a) where\r\n Empty <> h = h\r\n h <> Empty = h\r\n h1@(SkewNode x1 l1 r1) <> h2@(SkewNode x2 l2 r2)\r\n | x1 <= x2 = SkewNode x1 (h2 <> r1) l1\r\n | otherwise = SkewNode x2 (h1 <> r2) l2\r\n\r\ninstance (Ord a) => Monoid (SkewHeap a) where\r\n mempty = Empty\r\n\r\nsingleton :: a -> SkewHeap a\r\nsingleton x = SkewNode x Empty Empty\r\n\r\nextractMin :: (Ord a) => SkewHeap a -> Maybe (a, SkewHeap a)\r\nextractMin Empty = Nothing\r\nextractMin (SkewNode x l r) = Just (x, l <> r)\r\n\r\nfromList :: (Ord a) => [a] -> SkewHeap a\r\nfromList = mconcat . map singleton\r\n\r\nprim :: Int -> (Int -> [(Int, Int)]) -> [(Int, Int)]\r\nprim s nb = go (fromList $ nb s) (IS.singleton s) where\r\n go pq vis = case extractMin pq of\r\n Nothing -> []\r\n Just (e@(w, u), pq') -> if u `IS.member` vis\r\n then go pq' vis\r\n else e : go (pq' <> fromList (nb u)) (IS.insert u vis)\r\n\r\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\r\nlowerBound f l h\r\n | l >= h = l\r\n | f m = lowerBound f l m\r\n | otherwise = lowerBound f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nparseInt = f . C.readInt where f (Just (i, _)) = i\r\nreadInts = map parseInt . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST.Lazy\nimport Data.Function\n\n-------------------------------------------------------------------------------\n\ndata PQ t -- Maxiphobic persistent heap\n = Empty\n | Vertex t !Int (PQ t) (PQ t)\n deriving Show\n\ngetPQsize :: PQ t -> Int\ngetPQsize Empty = 0\ngetPQsize (Vertex _ sz _ _) = sz\n\ninstance Ord t => Semigroup (PQ t) where\n Empty <> q = q\n p <> Empty = p\n p@(Vertex pv ps pl pr) <> q@(Vertex qv qs _ _)\n | pv > qv = q <> p\n | otherwise = let\n [s1, s2, s3] = sortOn getPQsize [pl, pr, q]\n in Vertex pv (ps + qs) s3 $ s1 <> s2\n\ninstance Ord t => Monoid (PQ t) where\n mempty = Empty\n mappend = (<>)\n mconcat = let\n mergePairs [] = []\n mergePairs [v] = [v]\n mergePairs (p:q:rs) = (p <> q) : mergePairs rs\n in \\li -> case li of\n [] -> Empty\n [v] -> v\n _ -> mconcat (mergePairs li)\n\nsingle :: t -> PQ t\nsingle v = Vertex v 1 Empty Empty\n\ninsertAll :: Ord t => [t] -> PQ t -> PQ t\ninsertAll = (<>) . mconcat . map single\n\npopMaybe :: Ord t => PQ t -> Maybe (t, PQ t)\npopMaybe Empty = Nothing\npopMaybe (Vertex pv _ pl pr) = Just (pv, pl <> pr)\n\n-------------------------------------------------------------------------------\n\nseenBefore :: (Int, Int) -> [Int] -> [Bool]\nseenBefore bnds li = runST $ do\n vis <- strictToLazyST $ newArray bnds False :: ST s (STUArray s Int Bool)\n forM li $ \\v -> strictToLazyST $ do\n ans <- readArray vis v\n ans <$ writeArray vis v True\n\nbinSearch :: UArray Int Int -> Int -> Int\nbinSearch arr tar = let\n (p, q) = bounds arr\n go li ri\n | li == ri = li\n | otherwise = let\n mi = li + div (ri - li) 2\n in if tar <= arr ! mi\n then go li mi\n else go (mi+1) ri\n in go p (q+1)\n\ndata ProcessDir\n = L { atIx :: !Int, getCost :: !Int }\n | R { atIx :: !Int, getCost :: !Int }\n\ninstance Eq ProcessDir where -- not a pretty instance, but it's unused\n (==) = (==) `on` getCost\ninstance Ord ProcessDir where\n compare = compare `on` getCost\n (>) = (>) `on` getCost\n\nsuccessor :: UArray Int Int -> ProcessDir -> Maybe ProcessDir\nsuccessor arr (L ix cost) = if ix <= fst (bounds arr)\n then Nothing\n else Just $ L (ix - 1) (cost + arr ! ix - arr ! (ix - 1))\nsuccessor arr (R ix cost) = if ix >= snd (bounds arr)\n then Nothing\n else Just $ R (ix + 1) (cost + arr ! (ix + 1) - arr ! ix)\n\ndivergingAt :: UArray Int Int -> Int -> [ProcessDir]\ndivergingAt arr val = let\n tix = binSearch arr val\n (li, ri) = bounds arr\n lv = [L (tix - 1) (val - arr ! (tix - 1)) | tix > li]\n rv = [R tix (arr ! tix - val) | tix <= ri]\n in lv ++ rv\n\nsolve :: UArray Int Int -> Int -> Int -> UArray Int Int\nsolve arr startIx stepSize = let\n div2 ix = let\n v = arr ! ix\n in divergingAt arr (v - stepSize) ++ divergingAt arr (v + stepSize)\n solnStep :: [Bool] -> PQ ProcessDir -> [(Int, Int)]\n solnStep queryResponses pq = case popMaybe pq of\n Nothing -> []\n Just (a, npq) -> (atIx a, getCost a) : case queryResponses of\n [] -> error \"solve: unanswered query: bug in seenBefore?\"\n True : nqr -> solnStep nqr npq\n False : nqr -> let\n toIns = div2 (atIx a) ++ [a' | Just a' <- [successor arr a]]\n in solnStep nqr $ insertAll toIns npq\n queries = (startIx, 0)\n : solnStep (tail responses) (insertAll (div2 startIx) Empty)\n responses = seenBefore (bounds arr) $ map fst queries\n (posli, dists) = unzip queries\n in array (bounds arr) $\n [(pos, dist) | (pos, dist, False) <- zip3 posli (scanl1 max dists) responses]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, q, s, d] <- readInts\n a <- listArray (1, n) <$> readInts :: SIO (UArray Int Int)\n let ansKey = solve a s d\n replicateM_ q $ do\n [i, k] <- readInts\n lift $ B.hPutBuilder stdout $ if ansKey ! i <= k\n then B.string7 \"Yes\\n\"\n else B.string7 \"No\\n\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n"}], "src_uid": "7ef1aeb7d4649df98e47d2c26cff251c"} {"source_code": "import Debug.Trace (trace)\n\ntype Input = (Double, Double, Double, Double)\ntype Output = Double\n\nparse :: String -> Input\nparse contents = (a, b, c, d) where [a, b, c, d] = map read . words $ contents\n\ntype Range = (Double, Double)\n\nmultiply :: Range -> Range -> Range\nmultiply (a, b) (c, d) = (minimum products, maximum products)\n where products = do x <- [a, b]\n y <- [c, d]\n return (x * y)\n\nisOverlap :: Range -> Range -> Bool\nisOverlap (a, b) (c, d) = max a c <= min b d\n\ncheck :: Input -> Double -> Bool\ncheck (a, b, c, d) r = isOverlap (f a d) (f b c)\n where f x y = multiply (g x) (g y)\n g x = (x - r, x + r)\n\nsolve :: Input -> Output\nsolve param@(a, b, c, d) = fst (iterate bsearch (0, bound) !! 233)\n where bound = maximum . map abs $ [a, b, c, d]\n bsearch (l, r) = let mid = (l + r) / 2 in\n if check param mid\n then (l, mid)\n else (mid, r)\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n", "positive_code": [{"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\ntest a b c d x = let\n ad = [a' * d' | a' <- [a - x, a + x], d' <- [d - x, d + x]]\n bc = [b' * c' | b' <- [b - x, b + x], c' <- [c - x, c + x]]\n in minimum ad < maximum bc && maximum ad > minimum bc\n\nrefine a b c d (lo, hi) = let\n mid = (lo + hi) / 2\n in\n if test a b c d mid then (lo, mid) else (mid, hi)\n\nsolve a b c d\n | a * d == b * c = 0.0\n | otherwise = snd $ iterate (refine a b c d) (0.0, 1.0e9) !! 1024\n\nmain :: IO ()\nmain = do\n [a, b] <- map fi <$> inputIntegers\n [c, d] <- map fi <$> inputIntegers\n print $ solve a b c d\n"}, {"source_code": "import Control.Applicative ((<$>), liftA3)\nimport Control.Monad (replicateM)\n\nroot :: Double -> Double -> Double -> [Double]\nroot 0 0 0 = [0] -- ok. for our purposes\nroot 0 0 _ = []\nroot 0 b c = [- c / b]\nroot a b c = (/(-2*a)) <$> [b + delta, b - delta]\n where\n delta = sqrt $ b^2 - 4 * a * c :: Double\n\n\nsolve :: [[Double]] -> Double\nsolve [[a, b], [c, d]] =\n minimum . fmap abs . filter (\\a -> a == a) . concat $ xs\n where\n xs = liftA3 f [-1, 1] [-1, 1] [-1, 1] :: [[Double]]\n\n f :: Double -> Double -> Double -> [Double]\n f i j l = root a' b' c'\n where\n a' = l - i * j :: Double\n b' = a * l + d - c * i - b * j :: Double\n c' = a * d - b * c :: Double\n\n\nmain = solve . fmap parse <$> replicateM 2 getLine >>= print\n where\n parse :: String -> [Double]\n parse = fmap read . words\n"}, {"source_code": "import Control.Applicative\n\n-- 8-neighbour-distance from point (c,d) to line x*b=y*a\ndistance :: Rational -> Rational -> Rational -> Rational -> Rational\ndistance a b c d =\n minimum $ [abs $ (a*d-b*c) / (b + s * a) | s <- [1,-1], b+a*s /= 0]\n\nhflips (a,b,c,d) = [(a,b,c,d), (b,a,d,c)]\nvflips (a,b,c,d) = [(a,b,c,d), (c,d,a,b)]\nrotations (a,b,c,d) = [(a,b,c,d), (c,a,d,b)]\n\nbsearch a b f\n | b - a < 1e-10 = c\n | f c\n = bsearch a c f\n | otherwise\n = bsearch c b f\n where\n c = (a + b) / 2\n \n\nsolve :: [Integer] -> Double\nsolve [a, b, c, d] = fromRational $ bsearch 0 (fromIntegral $ maximum $ map abs [a,b,c,d]) (canDo a b c d) where\n\ncanDo a b c d r =\n any can (return (a,b,c,d) >>= hflips >>= vflips >>= rotations >>= \\x -> ((,,) x) <$> [1, -1] <*> [1, -1]) where\n can ((a,b,c,d), s1, s2) = distance (fromInteger a + r * s1) (fromInteger b + r * s2) (fromInteger c) (fromInteger d) < r\n\nmain = interact $ unlines . return . show . solve . map read . words\n"}], "negative_code": [{"source_code": "\ndirection a b c d = (b/a) < (d/c)\n \nsolve :: [Integer] -> Double\nsolve [a, b, c, d]\n | a+b+c+d == 0 = fromIntegral $ minimum $ map abs [a,b,c,d] -- I have no idea why\n | otherwise = min (fromIntegral $ minimum $ map abs [a,b,c,d]) $ abs $ (fromIntegral $ b*c - a*d) / (fromIntegral $ a+b+c+d)\n\nmain = interact $ unlines . return . show . solve . map read . words\n"}, {"source_code": "\ndirection a b c d = (b/a) < (d/c)\n \nsolve :: [Integer] -> Double\nsolve [a, b, c, d]\n | a+b+c+d == 0 = fromIntegral $ maximum $ map abs [a,b,c,d] -- I have no idea why\n | otherwise = min (fromIntegral $ maximum $ map abs [a,b,c,d]) $ abs $ (fromIntegral $ b*c - a*d) / (fromIntegral $ a+b+c+d)\n\nmain = interact $ unlines . return . show . solve . map read . words\n"}, {"source_code": "\ndirection a b c d = (b/a) < (d/c)\n\n-- 8-neighbour-distance from point (c,d) to line x*b=y*a\ndistance :: Rational -> Rational -> Rational -> Rational -> Rational\ndistance a b c d =\n minimum $ [abs $ (a*d-b*c) / (b + s * a) | s <- [1,-1], b+a*s /= 0]\n\nhflips (a,b,c,d) = [(a,b,c,d), (b,a,d,c)]\nvflips (a,b,c,d) = [(a,b,c,d), (c,d,a,b)]\nrotations (a,b,c,d) = [(a,b,c,d), (c,a,d,b)]\n\nbsearch a b f\n | b - a < 1e-10 = c\n | f c\n = bsearch a c f\n | otherwise\n = bsearch c b f\n where\n c = (a + b) / 2\n \n\nsolve :: [Integer] -> Double\nsolve [a, b, c, d] = fromRational $ bsearch 0 (fromIntegral $ maximum $ map abs [a,b,c,d]) (canDo a b c d) where\n\ncanDo a b c d r =\n any can (return (a,b,c,d) >>= hflips >>= vflips >>= rotations) where\n can (a,b,c,d) = distance (fromInteger a - r) (fromInteger b + r) (fromInteger c) (fromInteger d) < r\n\nmain = interact $ unlines . return . show . solve . map read . words\n"}, {"source_code": "\ndirection a b c d = (b/a) < (d/c)\n \nsolve :: [Integer] -> Double\nsolve [a, b, c, d] = abs $ (fromIntegral $ b*c - a*d) / (fromIntegral $ a+b+c+d)\n\nmain = interact $ unlines . return . show . solve . map read . words\n"}, {"source_code": "\ndirection a b c d = (b/a) < (d/c)\n \nsolve :: [Integer] -> Double\nsolve [a, b, c, d] | a+b+c+d == 0 = 0\n | otherwise = abs $ (fromIntegral $ b*c - a*d) / (fromIntegral $ a+b+c+d)\n\nmain = interact $ unlines . return . show . solve . map read . words\n"}, {"source_code": "type Input = (Double, Double, Double, Double)\ntype Output = Double\n\nparse :: String -> Input\nparse contents = (a, b, c, d) where [a, b, c, d] = map read . words $ contents\n\ntype Range = (Double, Double)\n\nmultiply :: Range -> Range -> Range\nmultiply (a, b) (c, d) = (mi, ma)\n where ma = maximum [a * c, b * d]\n mi = minimum [a * c, a * d, b * c]\n\nisOverlap :: Range -> Range -> Bool\nisOverlap (a, b) (c, d) = max a c <= min b d\n\ncheck :: Input -> Double -> Bool\ncheck (a, b, c, d) r = isOverlap (f a d) (f b c)\n where f x y = multiply (g x) (g y)\n g x = (x - r, x + r)\n\nsolve :: Input -> Output\nsolve param@(a, b, c, d) = fst (iterate bsearch (0, bound) !! 233)\n where bound = maximum . map abs $ [a, b, c, d]\n bsearch (l, r) = let mid = (l + r) / 2 in\n if check param mid\n then (l, mid)\n else (mid, r)\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}], "src_uid": "b779946fe86b1a2a4449bc85ff887367"} {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.IArray\nimport Control.Monad\nimport List\nimport Debug.Trace\n\ngenerateGraph :: Int -> [(Int, Int)] -> Array Int [Int]\ngenerateGraph n m = runSTArray $ do\n g <- newArray (0, n - 1) []\n forM_ m $ \\(a, b) -> do\n aa <- readArray g a\n bb <- readArray g b\n writeArray g a (b : aa)\n writeArray g b (a : bb)\n return g\n\ncheckCycle :: Int -> Array Int [Int] -> [Int]\ncheckCycle n g = cc 0 (-1) []\n where cc pos prev lst =\n case elemIndex pos lst of\n (Just x) -> take (x + 1) lst\n Nothing -> loop (g ! pos) pos prev (pos : lst)\n\n loop :: [Int] -> Int -> Int -> [Int] -> [Int]\n loop [] _ _ _ = []\n loop (x:xs) pos prev lst\n | x == prev = loop xs pos prev lst\n | otherwise = let cand1 = cc x pos lst\n cand2 = loop xs pos prev lst\n in if null cand1 then cand2 else cand1\n\ngenCycleFlag :: Int -> [Int] -> Array Int Bool\ngenCycleFlag n c = runSTArray $ do\n flag <- newArray (0, n - 1) False\n forM_ c $ \\x ->\n writeArray flag x True\n return flag\n\nsolve :: Int -> [(Int, Int)] -> [Int]\nsolve n m = let graph = generateGraph n m\n cycle = checkCycle n graph\n cflag = genCycleFlag n cycle\n in map (distance graph cflag) [0 .. n - 1]\n\ndistance g c pos = dist pos (-1) 0\n where dist pos prev cnt\n | c ! pos = cnt\n | otherwise = foldr min 10000 $\n map (\\x -> dist x pos (cnt + 1)) $\n filter (/= prev) (g ! pos)\n\nprintList :: Show a => [a] -> IO ()\nprintList (x:y:xs) = (putStr $ show x ++ \" \") >> printList (y:xs)\nprintList (x:[]) = putStrLn $ show x\nprintList [] = putStrLn \"\"\n\nmain :: IO ()\nmain = do nn <- BS.getLine\n mm <- BS.getContents\n let n = bReadInt nn\n m = map ((\\x -> x - 1) . bReadInt) $ BS.words mm\n m2 = zip2 m\n printList $ solve n m2\n\nzip2 :: [a] -> [(a, a)]\nzip2 (x:y:xs) = (x, y) : zip2 xs\nzip2 _ = []\n\nbReadInt :: BS.ByteString -> Int\nbReadInt = toNumber . BS.readInt\n\nbReadInteger :: BS.ByteString -> Integer\nbReadInteger = toNumber . BS.readInteger\n\ntoNumber :: Num a => Maybe (a, BS.ByteString) -> a\ntoNumber (Just (x, _)) = x\ntoNumber Nothing = 0\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Array.IArray\nimport Control.Monad\nimport List\nimport Debug.Trace\n\ngenerateGraph :: Int -> [(Int, Int)] -> Array Int [Int]\ngenerateGraph n m = runSTArray $ do\n g <- newArray (0, n - 1) []\n forM_ m $ \\(a, b) -> do\n aa <- readArray g a\n bb <- readArray g b\n writeArray g a (b : aa)\n writeArray g b (a : bb)\n return g\n\ncheckCycle :: Int -> Array Int [Int] -> [Int]\ncheckCycle n g = case cc 0 (-1) [] of\n (Just x) -> x\n Nothing -> []\n where cc pos prev lst =\n case elemIndex pos lst of\n (Just x) -> Just (take (x + 1) lst)\n Nothing -> loop (g ! pos) pos prev (pos : lst)\n\n loop [] _ _ _ = Nothing\n loop (x:xs) pos prev lst\n | x == prev = loop xs pos prev lst\n | otherwise =\n case cc x pos lst of\n (Just x) -> Just x\n Nothing -> loop xs pos prev lst\n\ngenCycleFlag :: Int -> [Int] -> Array Int Bool\ngenCycleFlag n c = runSTArray $ do\n flag <- newArray (0, n - 1) False\n forM_ c $ \\x ->\n writeArray flag x True\n return flag\n\nsolve :: Int -> [(Int, Int)] -> [Int]\nsolve n m = let graph = generateGraph n m\n cycle = checkCycle n graph\n cflag = genCycleFlag n cycle\n in map (distance graph cflag) [0 .. n - 1]\n\ndistance g c pos = dist pos (-1) 0\n where dist pos prev cnt\n | c ! pos = cnt\n | otherwise = foldr min 10000 $\n map (\\x -> dist x pos (cnt + 1)) $\n filter (/= prev) (g ! pos)\n\nprintList :: Show a => [a] -> IO ()\nprintList (x:y:xs) = (putStr $ show x ++ \" \") >> printList (y:xs)\nprintList (x:[]) = putStrLn $ show x\nprintList [] = putStrLn \"\"\n\nmain :: IO ()\nmain = do nn <- BS.getLine\n mm <- BS.getContents\n let n = bReadInt nn\n m = map ((\\x -> x - 1) . bReadInt) $ BS.words mm\n m2 = zip2 m\n printList $ solve n m2\n\nzip2 :: [a] -> [(a, a)]\nzip2 (x:y:xs) = (x, y) : zip2 xs\nzip2 _ = []\n\nbReadInt :: BS.ByteString -> Int\nbReadInt = toNumber . BS.readInt\n\nbReadInteger :: BS.ByteString -> Integer\nbReadInteger = toNumber . BS.readInteger\n\ntoNumber :: Num a => Maybe (a, BS.ByteString) -> a\ntoNumber (Just (x, _)) = x\ntoNumber Nothing = 0\n"}], "negative_code": [], "src_uid": "2d4dbada60ebcf0bdaead8d0c1c0e2c1"} {"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:k:_) <- map read . words <$> getLine\n s <- sort <$> getLine\n if k == 1\n then putStrLn s\n else do\n let (a, as) = splitAt k s\n if all (== head a) a\n then if all (== head as) as\n then putStrLn $\n head a : replicate ((n - k) `div` k + fromEnum ((n - k) `mod` k /= 0)) (head as)\n else putStrLn $ head a : as\n else putStrLn [maximum a]", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ routine\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map read.words) <$> getLine\n s <- getLine\n putStrLn $ solve n k s\n\n\nsolve ::Int -> Int -> String -> String\nsolve n k s\n |k == 1 = sorted\n |all (== head start) start=\n head start :\n if all (== head end) end\n then replicate ((n `div` k) +(if n `mod` k == 0 then 0 else 1)-1) (head end)\n else end\n |otherwise = [last start]\n where\n sorted = sort s\n (start, end) = splitAt k sorted\n"}, {"source_code": "import qualified Data.List as L\n\nreadInts :: IO [Int]\nreadInts = do\n line <- getLine\n return $ map read . words $ line\n\nsolve :: Int -> Int -> Int -> String -> String\nsolve 0 _ _ _ = []\nsolve _ 1 _ s = s\nsolve n k d s\n | (not uniformCur && d == 0) = [letter]\n | ((d /= 0 && hypothesis /= s) || not uniformCur && d /= 0) = solve n 1 (d + 1) s\n | (uniformCur && d == 0) = (letter : (solve n' k (d + 1) $ rem))\n | otherwise = take (div (n + k - 1) k) s\n where\n hypothesis = replicate n letter\n uniformCur = (cur == take (n - n') hypothesis)\n cur = take k s\n rem = drop k s\n n' = length rem\n letter = maximum cur\n \nhandleTest :: Int -> IO ()\nhandleTest 0 = return ()\nhandleTest t = do \n [n, k] <- readInts\n s <- getLine\n putStrLn $ solve n k 0 $ L.sort s\n handleTest $ t - 1\n\n\nmain = do\n t <- getLine\n handleTest $ read t\n"}, {"source_code": "\nimport qualified Data.List as L\n\nremoveFirstK :: Int -> [(Char, Int)] -> Maybe [(Char, Int)]\nremoveFirstK _ [] = Nothing\nremoveFirstK k ((c,cc):rest)\n | k == cc = Just rest\n | k < cc = Just $ (c,cc-k):rest\n | k > cc = removeFirstK (k-cc) rest\n\ngetMin :: Int -> String -> [(Char, Int)] -> String\ngetMin k sorted ((c,cc):rest)\n | k == cc = c: getMinLevel2 k (drop k sorted) rest\n | k < cc = c: getMinLevel2 k (drop k sorted) ((c,cc-k):rest)\n | otherwise = (sorted L.!! (k-1)) : \"\"\n\ngetMinLevel2 :: Int -> String -> [(Char,Int)] -> String\ngetMinLevel2 k sorted [] = \"\"\ngetMinLevel2 k _ [(c,cc)] = L.replicate (ceiling (fromIntegral cc/ fromIntegral k)) c\ngetMinLevel2 k sorted _ = sorted\n\npossibleMin1 :: Int -> String -> [(Char, Int)] -> String\npossibleMin1 k sorted [] = \"\"\npossibleMin1 k sorted ((c,cc):rest)\n | k == cc = c : possibleMin1 k sorted rest\n | k > cc = L.replicate 1000000 'z'\n | otherwise = c : possibleMin1 k sorted ((c,cc-k):rest)\n\n{-\n | k == cc = c: getMin k rest\n | k < cc = c: getMin k ((c,cc-k):rest)\n | null rest = c:\"\"\n | otherwise = fst (head rest) : \"\"\n-}\n\n\nsolve :: Int -> String -> String\nsolve k s = getMin k sorted counts\n where\n sorted = L.sort s\n counts = map counterF $ L.group sorted\n counterF l = (head l, length l)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readInts\n s <- getLine\n putStrLn $ solve k s\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testCases t\n\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}], "negative_code": [{"source_code": "{-- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:k:_) <- map read . words <$> getLine\n s <- sort <$> getLine\n if all (== head s) (take k s)\n then putStrLn [head s]\n else putStrLn $ head s : drop k s"}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ routine\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map read.words) <$> getLine\n s <- getLine\n putStrLn $ solve n k s\n\n\nsolve ::Int -> Int -> String -> String\nsolve n k s\n |k == 1 = s\n |head start == lstart =\n lstart :\n if head end == lend\n then replicate ((n `div` k) +(if n `mod` k == 0 then 0 else 1)-1) (head end)\n else end\n |otherwise = [lstart]\n where\n sorted = sort s\n (start, end) = splitAt k sorted\n lstart = last start\n lend = last end\n"}, {"source_code": "import qualified Data.List as L\n\nreadInts :: IO [Int]\nreadInts = do\n line <- getLine\n return $ map read . words $ line\n\nsolve :: Int -> Int -> Int -> String -> String\nsolve 0 _ _ _ = []\nsolve _ 1 _ s = s\nsolve n k d s\n | (not uniformCur && d == 0) = [letter]\n | ((d /= 0 && hypothesis /= s) || not uniformCur && d /= 0) = solve n 1 (d + 1) s\n | otherwise = take (div (n + k - 1) k) s\n where\n hypothesis = replicate n letter\n uniformCur = (cur == take (n - n') hypothesis)\n cur = take k s\n rem = drop k s\n n' = length rem\n letter = maximum cur\n \nhandleTest :: Int -> IO ()\nhandleTest 0 = return ()\nhandleTest t = do \n [n, k] <- readInts\n s <- getLine\n putStrLn $ solve n k 0 $ L.sort s\n handleTest $ t - 1\n\n\nmain = do\n t <- getLine\n handleTest $ read t\n"}, {"source_code": "\nimport qualified Data.List as L\n\nremoveFirstK :: Int -> [(Char, Int)] -> Maybe [(Char, Int)]\nremoveFirstK _ [] = Nothing\nremoveFirstK k ((c,cc):rest)\n | k == cc = Just rest\n | k < cc = Just $ (c,cc-k):rest\n | k > cc = removeFirstK (k-cc) rest\n\ngetMin :: Int -> String -> [(Char, Int)] -> String\ngetMin k sorted [] = \"\"\ngetMin k _ [(c,cc)] = L.replicate (ceiling (fromIntegral cc/ fromIntegral k)) c\ngetMin k sorted g@((c,cc):rest)\n | k <= cc = drop (k-1) sorted\n | otherwise = (sorted L.!! (k-1)) : \"\"\n\npossibleMin1 :: Int -> String -> [(Char, Int)] -> String\npossibleMin1 k sorted [] = \"\"\npossibleMin1 k sorted ((c,cc):rest)\n | k == cc = c : possibleMin1 k sorted rest\n | k > cc = L.replicate 1000000 'z'\n | otherwise = c : possibleMin1 k sorted ((c,cc-k):rest)\n\n{-\n | k == cc = c: getMin k rest\n | k < cc = c: getMin k ((c,cc-k):rest)\n | null rest = c:\"\"\n | otherwise = fst (head rest) : \"\"\n-}\n\n\nsolve :: Int -> String -> String\nsolve k s = min (getMin k sorted counts) (possibleMin1 k sorted counts)\n where\n sorted = L.sort s\n counts = map counterF $ L.group sorted\n counterF l = (head l, length l)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readInts\n s <- getLine\n putStrLn $ solve k s\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n testCases t\n\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}], "src_uid": "df778e55a2c676acca7311d885f61d7a"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport System.IO\nimport Data.List\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readLineNum\n as <- readLineNum\n bs <- readLineNum\n let ttt = (sortBy compare' $ zipWith (\\a b -> (a, b, a-b)) as bs)\n print $ summer k ttt 0\n where\n readLineNum :: IO [Int]\n readLineNum = getLine >>= return . words >>= return . map (read :: String -> Int)\n\n compare' (_, _, t1) (_, _, t2) = t1 `compare` t2\n\n summer :: Int -> [(Int, Int, Int)] -> Int -> Int\n summer _ [] !acc = acc\n summer !i !((a, b, c):es) !acc = summer (i-1) es (if i>0 then (acc+a) else (acc+(if a<=b then a else b)))\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport System.IO\nimport Data.List\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readLineNum\n as <- readLineNum\n bs <- readLineNum\n let ttt = (sortBy compare' $ zipWith (\\a b -> (a, b, a-b)) as bs)\n print $ summer k ttt 0\n where\n readLineNum :: IO [Int]\n readLineNum = getLine >>= return . words >>= return . map (read :: String -> Int)\n\n compare' (_, _, t1) (_, _, t2) = t1 `compare` t2\n\n summer :: Int -> [(Int, Int, Int)] -> Int -> Int\n summer _ [] !acc = acc\n summer !i !((a, b, c):es) acc = summer (i-1) es (if i>0 then (acc+a) else (acc+(if a<=b then a else b)))\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport System.IO\nimport Data.List\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readLineNum\n (as:bs:_) <- getContents >>= return . lines >>= return . (map (map read . words))\n let ttt = (sortBy compare' $ zipWith (\\a b -> (a, b, a-b)) as bs)\n print $ summer k ttt 0\n where\n readLineNum :: IO [Int]\n readLineNum = getLine >>= return . words >>= return . map (read :: String -> Int)\n\n compare' (!_, !_, !t1) (!_, !_, !t2) = t1 `compare` t2\n\n summer :: Int -> [(Int, Int, Int)] -> Int -> Int\n summer !_ [] !acc = acc\n summer !i !((a, b, c):es) !acc = summer (i-1) es (if i>0 then (acc+a) else (acc+(if a<=b then a else b)))\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.IntSet as IS\nimport Data.List\nimport Data.List.Split\nimport qualified Data.Map.Strict as M\nimport Data.Monoid\nimport Data.Ord\nimport qualified Data.Set as S\nimport Data.Tuple\nimport Data.Word\n\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\n\nmain :: IO ()\nmain = do\n [n,k] <- map readInt.B.words <$> B.getLine\n xs <- map readInt.B.words <$> B.getLine\n ys <- map readInt.B.words <$> B.getLine\n print $ solve k xs ys\n\nsolve :: Int -> [Int] -> [Int] -> Int64\nsolve k xs ys = sum[fromIntegral x | (d,x)<-zs0++zs2] + sum[fromIntegral $ x +d| (d,x)<-zs3]\n where\n diffs = reverse.sort $ zipWith(\\x y->(y-x,x)) xs ys\n (zs0, zs1) = splitAt k diffs\n (zs2, zs3) = span ((>0).fst) zs1"}, {"source_code": "import Data.List \nimport Data.Maybe ( fromJust )\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int] \n\nmain = do\n [n,k] <- fast_read_Int\n a <- fast_read_Int\n b <- fast_read_Int\n let bf = sortBy (\\(a, b) (a', b') -> compare (a - b) (a' - b')) $ zip a b\n let pozzitive = takeWhile (\\(a, b) -> a < b) bf\n --print pozzitive\n let cate = max k $ length pozzitive\n let sum1 = sum $ map fst $ take cate bf\n let sum2 = sum $ map snd $ take (n-cate) $ reverse bf\n print $ sum1 + sum2"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Ord\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n as <- fmap readInts B.getLine\n bs <- fmap readInts B.getLine\n print $ solve n k as bs\n\nsolve n k as bs = (\\(f, s) -> sum (map fst f) + sum (map (uncurry min) s)) $ splitAt k $ sortBy (comparing (uncurry (-))) $ zip as bs\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words"}], "negative_code": [{"source_code": "import System.IO\nimport Data.List\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readLineNum\n as <- readLineNum\n bs <- readLineNum\n let ttt = (sort $ zipWith (\\a b -> (a, b, a-b)) as bs)\n print $ summer k ttt 0\n where\n readLineNum :: IO [Int]\n readLineNum = getLine >>= return . words >>= return . map (read :: String -> Int)\n\n sort :: [(Int, Int, Int)] -> [(Int, Int, Int)]\n sort [] = []\n sort ((t@(ta, tb, tc)):remain) = former ++ [t] ++ latter\n where\n former = [tmp | tmp@(tmpa, tmpb, tmpc) <- remain, tmpc <= tc]\n latter = [tmp | tmp@(tmpa, tmpb, tmpc) <- remain, tmpc > tc]\n\n summer :: Int -> [(Int, Int, Int)] -> Int -> Int\n summer _ [] acc = acc\n summer i ((a, b, c):es) acc = summer (i-1) es (if i>0 then (acc+a) else (acc+(if a (a, b, a-b)) as bs)\n print $ summer k ttt 0\n where\n readLineNum :: IO [Int]\n readLineNum = getLine >>= return . words >>= return . map (read :: String -> Int)\n\n sort :: [(Int, Int, Int)] -> [(Int, Int, Int)]\n sort [] = []\n sort (t@(ta, tb, tc):remain) = former ++ [t] ++ latter\n where\n former = [tmp | tmp@(tmpa, tmpb, tmpc) <- remain, tmpc <= tc]\n latter = [tmp | tmp@(tmpa, tmpb, tmpc) <- remain, tmpc > tc]\n\n summer :: Int -> [(Int, Int, Int)] -> Int -> Int\n summer _ [] acc = acc\n summer i ((a, b, c):es) acc = summer (i-1) es (if i>0 then (acc+a) else (acc+(if a<=b then a else b)))\n"}, {"source_code": "\nimport Data.List \nimport Data.Maybe ( fromJust )\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n \nfast_read_Int = fmap (map (fst . fromJust . BS8.readInt) . BS8.words) BS.getLine :: IO [Int] \n\nmain = do\n [n,k] <- fast_read_Int\n a <- fast_read_Int\n b <- fast_read_Int\n let bf = sortBy (\\(a, b) (a', b') -> compare (a - b) (a' - b')) $ zip a b\n let pozzitive = takeWhile (\\(a, b) -> a < b) bf\n --print pozzitive\n let cate = max k $ length pozzitive\n print cate\n print bf\n let sum1 = sum $ map fst $ take cate bf\n let sum2 = sum $ map snd $ take (n-cate) $ reverse bf\n print $ sum1 + sum2"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\n\nmain = do\n [n, k] <- fmap readInts B.getLine\n as <- fmap readInts B.getLine\n bs <- fmap readInts B.getLine\n print $ solve n k as bs\n\nsolve n k as bs = sum $ zipWith min as bs\n\nreadInt = maybe undefined fst . B.readInteger\nreadInts = fmap readInt . B.words"}], "src_uid": "b5355e1f4439b198d2cc7dea01bc4bc3"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n [n, m] <- getInts\n xs <- replicateM n (tail <$> getInts)\n\n let r = [1..m] == (map head $ group $ sort $ concat xs)\n\n putStrLn $ if r then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nsortUnique :: (Ord a) => [a] -> [a]\nsortUnique = map head . group . sort\n\nsolve :: Int -> [[Int]] -> Bool\nsolve n lss = ls == [1 .. n]\n where ls = sortUnique $ concat lss\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n lss <- replicateM n $ liftM tail readInts\n putStrLn $ if solve m lss then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map read . words =<< getContents\n\ntransform :: [Int] -> [Int]\ntransform [] = []\ntransform (x:s) = let (ys, zs) = splitAt x s in ys ++ transform zs\n\nsolve :: [Int] -> Bool\nsolve (_:m:x) = length (nub $ transform x) == m\n\noutput :: Bool -> IO()\noutput b = putStrLn $ if b then \"YES\" else \"NO\"\n"}, {"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n [n, m] <- fmap (map read . words) getLine\n inp <- forM [1..n] $ \\_ -> do\n (_:m) <- fmap (map read . words) getLine\n return m\n putStrLn $ solve inp m\n\nsolve :: [[Int]] -> Int -> String\nsolve inp n | (length . nub) (concat inp) == n = \"YES\"\n | otherwise = \"NO\"\n\n\n \n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = C.getLine >>= \\ns -> let [n,m] = map rIn $ C.words ns in (solve.((:) m).concat=<tail.map rIn.C.words <$>C.getLine) )\nsolve (x:xs)= let xs1=nub xs;l=length xs1 in if l==x then putStr \"YES\" else putStr \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nmain::IO ()\nmain=do\n [n,m]<- map read <$> words <$> getLine ::IO [Int]\n x <- map head <$> group <$> sort <$> concatMap (map (fromIntegral.fst.fromJust.C.readInteger)) <$>map tail <$> map C.words <$> C.lines <$> C.getContents::IO [Int]\n putStrLn $ if x==[1..m] then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List (nub)\nmain = do\n [_,m] <- fmap (map read . words) getLine\n bs <- fmap (nub . concat . map (tail . words) . lines) getContents\n putStrLn $ if length bs == m then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.Map as M\nimport Prelude as P\nimport Control.Monad\n\nparse f str = P.map read (f $ words str) :: [Int]\nfillMap b bu inputs = P.foldl (\\ mmap x -> M.insert x True mmap)(newMap) inputs \n\t\t\t\t\t\twhere newMap = M.fromList $ zip [1..bu] (repeat False)\n\n\nmain = do\n\tnum <- getLine\n\tlet (b : bu : []) = parse id num\n\tinputs <- replicateM b getLine\n\tlet ans = M.foldr (\\ a b -> a && b) True (fillMap b bu (concat $ P.map (parse tail) inputs))\n\tif ans == True then putStrLn \"YES\" else putStrLn \"NO\""}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.Set as S\n\n\nmain= do\n\t[n,m]<- map read.words <$> getLine ::IO [Int]\n\ts<- concat.map tail. map (map read). map words . lines <$> getContents::IO [Int]\n\tlet t= S.toList $ foldr (S.insert) S.empty s\n\tputStrLn $ if length t ==m then \"YES\" else \"NO\"\n\t\n\t\n"}, {"source_code": "import Data.List (nub, union)\n\nprocess :: Int -> [[Int]] -> Bool\nprocess m xss = (==) m $ length $ foldl union (nub (head xss)) (tail xss)\n\nreadInt :: String -> Int\nreadInt = read\n\nshowPair :: (Int, Int) -> String\nshowPair (x,y) = show x ++ \" \" ++ show y\n\nmain :: IO ()\nmain = do\n [n,m] <- fmap (map readInt.words) getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n if process m $ map tail ts\n then putStrLn \"YES\"\n else putStrLn \"NO\""}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nsortUnique :: (Ord a) => [a] -> [a]\nsortUnique = map head . group . sort\n\nsolve :: Int -> [[Int]] -> Bool\nsolve n lss = ls == [1 .. n]\n where ls = sortUnique $ concat lss\n\nreadInts :: IO [Int]\nreadInts = liftM (map read . words) getLine\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n lss <- replicateM n readInts\n putStrLn $ if solve m lss then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = C.getLine >>= \\ns -> let n = rIn $ head $ C.words ns in (solve.((:) n).concat=<tail.map rIn.C.words <$>C.getLine) )\nsolve (x:xs)= let xs1=nub xs;l=length xs1 in if l==x then putStr \"YES\" else putStr \"NO\"\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nmain::IO ()\nmain=do\n [n,m]<- map read <$> words <$> getLine ::IO [Int]\n x <- map head <$> group <$> sort <$> concatMap (map (fromIntegral.fst.fromJust.C.readInteger)) <$> map C.words <$> C.lines <$> C.getContents::IO [Int]\n putStrLn $ if x==[1..m] then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.Map as M\nimport Prelude as P\nimport Control.Monad\n\nparse str = P.map read $ words str :: [Int]\nfillMap b bu inputs = P.foldl (\\ mmap x -> M.insert x True mmap)(newMap) inputs \n\t\t\t\t\t\twhere newMap = M.fromList $ zip [1..bu] (repeat False)\n\n\nmain = do\n\tnum <- getLine\n\tlet (b : bu : []) = parse num\n\tinputs <- replicateM b getLine\n\tprint $ M.foldr (\\ a b -> a && b) True (fillMap b bu (concat $ P.map parse inputs))\n\t"}, {"source_code": "import Data.Map as M\nimport Prelude as P\nimport Control.Monad\n\nparse str = P.map read $ words str :: [Int]\nfillMap b bu inputs = P.foldl (\\ mmap x -> M.insert x True mmap)(newMap) inputs \n\t\t\t\t\t\twhere newMap = M.fromList $ zip [1..bu] (repeat False)\n\n\nmain = do\n\tnum <- getLine\n\tlet (b : bu : []) = parse num\n\tinputs <- replicateM b getLine\n\tlet ans = M.foldr (\\ a b -> a && b) True (fillMap b bu (concat $ P.map parse inputs))\n\tif ans == True then print \"YES\" else print \"NO\""}, {"source_code": "import Data.Map as M\nimport Prelude as P\nimport Control.Monad\n\nparse str = P.map read $ words str :: [Int]\nfillMap b bu inputs = P.foldl (\\ mmap x -> M.insert x True mmap)(newMap) inputs \n\t\t\t\t\t\twhere newMap = M.fromList $ zip [1..bu] (repeat False)\n\n\nmain = do\n\tnum <- getLine\n\tlet (b : bu : []) = parse num\n\tinputs <- replicateM b getLine\n\tlet ans = M.foldr (\\ a b -> a && b) True (fillMap b bu (concat $ P.map parse inputs))\n\tif ans == True then putStrLn \"YES\" else putStrLn \"NO\""}], "src_uid": "9438ce92e10e846dd3ab7c61a1a2e3af"} {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Data.Bits(Bits, (.&.))\r\n\r\nmain :: IO ()\r\nmain = interact $ format . solve . parse\r\n\r\n\r\nparse :: String -> [Integer]\r\nparse input = case lines input of\r\n [] -> undefined\r\n (w:ws) -> readN (read w) ws\r\n where\r\n readN :: Integer -> [String] -> [Integer]\r\n readN 0 _ = []\r\n readN n (w:ws) = read w : readN (n-1) ws\r\n readN _ _ = undefined\r\n\r\nformat :: [Bool] -> String\r\nformat = unlines . map (\\case\r\n True -> \"YES\"\r\n False -> \"NO\"\r\n )\r\n\r\nsolve :: [Integer] -> [Bool]\r\nsolve = map (not . isPower2)\r\n\r\n\r\nisPower2 :: (Bits i, Integral i) => i -> Bool\r\nisPower2 n = n /= 1 && n .&. (n-1) == 0", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits(Bits, (.&.))\nimport Data.Int(Int64)\n\nmain :: IO ()\nmain = interact $ format . solve . parse\n\n\nparse :: String -> [Int64]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> readN (read w) ws\n where\n readN :: Int -> [String] -> [Int64]\n readN 0 _ = []\n readN n (w:ws) = read w : readN (n-1) ws\n readN _ _ = undefined\n\nformat :: [Bool] -> String\nformat = unlines . map (\\case\n True -> \"YES\"\n False -> \"NO\"\n )\n\nsolve :: [Int64] -> [Bool]\nsolve = map (not . isPower2)\n\n\nisPower2 :: (Bits i, Integral i) => i -> Bool\nisPower2 n = n /= 1 && n .&. (n-1) == 0\n\n\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits(Bits, (.&.))\nimport Data.Int(Int64)\n\nmain :: IO ()\nmain = interact $ format . solve . parse\n\n\nparse :: String -> [Int64]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> readN (read w) ws\n where\n readN :: Int64 -> [String] -> [Int64]\n readN 0 _ = []\n readN n (w:ws) = read w : readN (n-1) ws\n readN _ _ = undefined\n\nformat :: [Bool] -> String\nformat = unlines . map (\\case\n True -> \"YES\"\n False -> \"NO\"\n )\n\nsolve :: [Int64] -> [Bool]\nsolve = map (not . isPower2)\n\n\nisPower2 :: (Bits i, Integral i) => i -> Bool\nisPower2 n = n /= 1 && n .&. (n-1) == 0\n\n\n"}, {"source_code": "{-main :: IO()\nmain = do \n putStrLn \"Ingrese una Lista : \";\n xs <- readLn;\n print (todosPares xs) \n\n\n--Import Data.Char\n\n--main = do\n-- contents <- getContents\n-- putStr (map toUpper contents)\n\nleerLista :: [Double] ->[String]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs\n\npoTenciaDEDos :: Double -> [Char]\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n\ntodosPares :: [Int] ->Bool\ntodosPares [] = True\ntodosPares (x:xs) = even x && todosPares xs-}\n\n\n{-# LANGUAGE LambdaCase #-}\n\nimport Data.Bits(Bits, (.&.))\nimport Data.Int(Int64)\n\nmain :: IO ()\nmain = interact $ format . solve . parse\n\n\nparse :: String -> [Int64]\nparse input = case lines input of\n [] -> undefined\n (w:ws) -> readN (read w) ws\n where\n readN :: Int -> [String] -> [Int64]\n readN 0 _ = []\n readN n (w:ws) = read w : readN (n-1) ws\n readN _ _ = undefined\n\nformat :: [Bool] -> String\nformat = unlines . map (\\case\n True -> \"YES\"\n False -> \"NO\"\n )\n\nsolve :: [Int64] -> [Bool]\nsolve = map (not . isPower2)\n\n\nisPower2 :: (Bits i, Integral i) => i -> Bool\nisPower2 n = n /= 1 && n .&. (n-1) == 0\n\n\n\n\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n x <- readLn :: IO Integer\n putStrLn $ yesOrNo . (>1) $ head . filter odd $ iterate (`div` 2) $ x\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Control.Applicative\nimport System.IO\nimport Data.Bits\n\n-- import qualified Data.Set as Set\n\nreadInt :: String -> Int\nreadInt = read\n\nprintArr :: (Show a) => String -> [a] -> IO ()\nprintArr sep arr = do\n putStrLn . intercalate sep $ (show <$> arr)\n\nprint2DArr :: (Show a) => String -> [[a]] -> IO ()\nprint2DArr sep arr = sequence_ (printArr sep <$> arr)\n\nevery n xs = case drop (n-1) xs of\n (y:ys) -> y : every n ys\n [] -> []\n\nyon True = \"YES\"\nyon False = \"NO\"\n\nmain = do\n -- input <- openFile \"in\" ReadMode\n let input = stdin\n hSetBuffering input (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- hGetContents input\n -- printArr (readIntArr $ head q) \" \"\n solve contents\n\nsolve inp = sequence do\n x :: Int64 <- read <$> tail (lines inp)\n let x' = 1 `shift` countTrailingZeros x\n [putStrLn $ yon (x /= x')]"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\noddDivisor :: Integer -> Bool\noddDivisor n = ((.&.) n $ n-1) /= 0\n\nmain :: IO()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1..t] $ \\x -> do\n n <- readLn :: IO Integer\n if oddDivisor n then\n putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "import Data.Bits\r\n\r\nsolve :: String -> String\r\nsolve s = if popCount n == 1 then \"NO\" else \"YES\"\r\n where n = read s :: Integer\r\n\r\nprocess :: [String] -> String\r\nprocess (_ : inp) = unlines $ map solve inp\r\n\r\nmain :: IO ()\r\nmain = interact (process . lines)\r\n"}, {"source_code": "module Main where\n\nimport Data.Bool ( bool )\n\n\nhaveOddDivisor :: Int -> String\nhaveOddDivisor number = bool \"NO\" \"YES\" isAnyOdd\n where\n isAnyOdd = any odd $ takeWhile ((/=) 1) $ iterate (`div` 2) number\n\n\nsolve :: Int -> IO ()\nsolve 0 = return ()\nsolve test = do\n number <- getLine\n putStrLn $ haveOddDivisor (read number)\n solve (test - 1)\n\n\nmain :: IO ()\nmain = do\n tests <- getLine\n solve (read tests)\n"}, {"source_code": "import Control.Monad\nimport Data.Bool\n\ncheck 1 = False\ncheck 2 = False\ncheck n\n | odd n = True\n | even n = check (n `div` 2)\n\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n i <- read <$> getLine\n putStrLn $ bool \"NO\" \"YES\" $ check i\n"}, {"source_code": "import Data.List\r\nimport System.IO\r\nimport Control.Monad\r\nconvert :: Read a => String -> [a]\r\nconvert = map read . words\r\n\r\nsolve::Integer->Integer\r\nsolve n = if n`rem`2 == 0 then solve (n`div`2) else n\r\n\r\nprintSolve:: Integer -> IO() \r\nprintSolve n = if (n`rem`2>0) then putStrLn \"YES\" else printSolve2 n\r\n\r\nprintSolve2:: Integer->IO()\r\nprintSolve2 n = if (solve n == 1) then putStrLn \"NO\" else putStrLn \"YES\"\r\n\r\nloop :: Integer -> IO ()\r\nloop 0 = putStr \"\"\r\nloop t = do{\r\n nn <- getLine;\r\n printSolve (read nn);\r\n loop(t-1);\r\n}\r\n\r\nmain = do\r\n line <- getLine\r\n let t = read line :: Integer\r\n loop t"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM)\r\nimport Data.Maybe\r\n\r\nsolve n \r\n\t| n == 1 = False\r\n\t| n > 1 && mod n 2 /= 0 = True\r\n\t| n > 1 && mod n 2 == 0 = solve $ div n 2\r\n\r\nplotResult True = putStrLn \"YES\"\r\nplotResult False = putStrLn \"NO\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n\r\n"}, {"source_code": "main = interact $ unlines . map (solve . read) . tail . lines\r\n\r\nsolve n\r\n | any odd . takeWhile (>1) $ iterate (`div` 2) n = \"YES\"\r\n\t| otherwise = \"NO\""}, {"source_code": "-- Trying to use only ByteString I/O with a state monad this contest\n\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.Bits\n\ngetSLine :: Monad m => StateT P.ByteString m P.ByteString\ngetSLine = do\n (out, next) <- P.break (== '\\n') <$> get\n put $ P.tail next\n pure out\n\nreadInts :: Monad m => StateT P.ByteString m [Int]\nreadInts = do\n currLine <- getSLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nreadIntegers :: Monad m => StateT P.ByteString m [Integer]\nreadIntegers = do\n currLine <- getSLine\n pure [x | Just (x, _) <- P.readInteger <$> P.words currLine]\n\noutLine :: P.ByteString -> StateT P.ByteString IO ()\noutLine v = StateT $ \\s -> ((), s) <$ P.putStrLn v\n\nmain :: IO ()\nmain = (P.getContents >>=) $ evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readIntegers\n outLine . P.pack $ if popCount n > 1\n then \"YES\"\n else \"NO\"\n"}], "negative_code": [{"source_code": "\nimport Data.Char\n\nmain = do\n contents <- getContents\n putStr (map toUpper contents)\n\nleerLista :: [Double] -> [[Char]]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs\n\npoTenciaDEDos :: Double -> [Char]\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n"}, {"source_code": "\nimport Data.Char\n\nmain = do\n contents <- getContents\n putStr (map toUpper contents)\n\nleerLista :: [Double] -> [[Char]]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs\n\npoTenciaDEDos :: Double -> [Char]\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"YES\"\nescribeBool False = \"NO\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n"}, {"source_code": "import Data.Char\n\nmain = do\n lineas <- getContents\n let (n:resto) = lines lineas\n datos = take (read n) resto\n mapM_ putStrLn $ leerLista (map read resto)\n\nleerLista :: [Double] -> [String]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n\n \n \n-- ejemplos de prueba \n--2\n--3 jdjdjdjdjdjjdjdjdjdjdjdjdjddj\n--4 jdjdjdjdjdjdjjdjdjdjdjdjdjdjjdj\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "import Data.Char\n\nmain = do\n lineas <- getContents\n let (n:resto) = lines lineas\n datos = resto --take (read n) resto\n mapM_ putStrLn $ leerLista (map read resto)\n\nleerLista :: [Double] -> [String]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n\n \n \n-- ejemplos de prueba \n--2\n--3 jdjdjdjdjdjjdjdjdjdjdjdjdjddj\n--4 jdjdjdjdjdjdjjdjdjdjdjdjdjdjjdj\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "import Data.Char\n\nmain = do\n leerLista <- getContents\n putStr (map toUpper leerLista)\n\n\nleerLista :: [Double] ->[String]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs \n\npoTenciaDEDos :: Double -> [Char]\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n \n \n \n \n-- ejemplos de prueba \n--2\n--3 jdjdjdjdjdjjdjdjdjdjdjdjdjddj\n--4 jdjdjdjdjdjdjjdjdjdjdjdjdjdjjdj\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "import Data.Char\n\nmain = do\n leerLista <- getContents\n putStr (map toUpper leerLista)\n\n\nleerLista :: [Double] ->[String]\nleerLista [] = []\nleerLista (x:xs) = poTenciaDEDos x : leerLista xs \n\npoTenciaDEDos :: Double -> [Char]\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n \n \n \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "main = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x) \n \npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "poTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x) \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "module Main where\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x) \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "module Main where\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n \nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x) \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "main :: IO ()\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x) \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n \nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n\n--main = do putStrLn \"is Odd! ?\"\n-- x <- readLn\n-- print (poTenciaDEDos x) \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "poTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n \nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x) \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "main = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n \n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "module Main where\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n \n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "module Main where\n\nescribeBool True = \"YES\"\nescribeBool False = \"NO\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n \n \n-- ejemplos de prueba \n--2\n--3\n--4\n--5\n--998244353\n--1099511627776 \n \n"}, {"source_code": "module Main where\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\npoTenciaDEDos :: Double -> String\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n \n \n \n \n \n \n"}, {"source_code": "module Main where\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 :: Double -> Double\nlog_2 n = log n/log 2 \n\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n \n \n \n \n \n \n"}, {"source_code": "module Main where\n\nescribeBool True = \"NO\"\nescribeBool False = \"YES\"\n\nlog_2 n = log n/log 2 \n\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n--main :: IO () \n--main = print (poTenciaDEDos n)\n\n\n\nmain = do putStrLn \"is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n"}, {"source_code": "module Main where\nescribeBool True = \"No\"\nescribeBool False = \"Yes\"\n\nlog_2 n = log n/log 2 \n\npoTenciaDEDos n = escribeBool (floor (log_2 n) == ceiling (log_2 n))\n\n--main :: IO () \n--main = print (poTenciaDEDos n)\n\n\n\nmain = do putStrLn \"What is Odd! ?\"\n x <- readLn\n print (poTenciaDEDos x)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n x <- readLn :: IO Integer\n putStrLn $ yesOrNo . odd $ x\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Control.Applicative\nimport System.IO\nimport Data.Bits\n\n-- import qualified Data.Set as Set\n\nreadInt :: String -> Int\nreadInt = read\n\nprintArr :: (Show a) => String -> [a] -> IO ()\nprintArr sep arr = do\n putStrLn . intercalate sep $ (show <$> arr)\n\nprint2DArr :: (Show a) => String -> [[a]] -> IO ()\nprint2DArr sep arr = sequence_ (printArr sep <$> arr)\n\nevery n xs = case drop (n-1) xs of\n (y:ys) -> y : every n ys\n [] -> []\n\nyon True = \"YES\"\nyon False = \"NO\"\n\nmain = do\n -- input <- openFile \"in\" ReadMode\n let input = stdin\n hSetBuffering input (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- hGetContents input\n -- printArr (readIntArr $ head q) \" \"\n solve contents\n\nsolve inp = sequence do\n x <- readInt <$> tail (lines inp)\n let x' = 1 `shift` countTrailingZeros x\n [putStrLn $ yon (x /= x')]"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Control.Applicative\nimport System.IO\nimport Data.Bits\n\n-- import qualified Data.Set as Set\n\nreadInt :: String -> Int\nreadInt = read\n\nprintArr :: (Show a) => String -> [a] -> IO ()\nprintArr sep arr = do\n putStrLn . intercalate sep $ (show <$> arr)\n\nprint2DArr :: (Show a) => String -> [[a]] -> IO ()\nprint2DArr sep arr = sequence_ (printArr sep <$> arr)\n\nevery n xs = case drop (n-1) xs of\n (y:ys) -> y : every n ys\n [] -> []\n\nyon True = \"YES\"\nyon False = \"NO\"\n\nmain = do\n -- input <- openFile \"in\" ReadMode\n let input = stdin\n hSetBuffering input (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- hGetContents input\n -- printArr (readIntArr $ head q) \" \"\n solve contents\n\nsolve inp = sequence do\n x <- readInt <$> tail (lines inp)\n let x' = 1 `shift` countTrailingZeros x\n [putStrLn $ yon (x == x')]"}, {"source_code": "import Control.Monad\nimport Data.Bits\n\noddDivisor :: Int -> Bool\noddDivisor n = ((.&.) n $ n-1) /= 0\n\nmain :: IO()\nmain = do\n t <- readLn :: IO Int\n forM_ [1..t] $ \\x -> do\n n <- readLn :: IO Int\n if oddDivisor n then\n putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "import Data.Bits\r\n\r\nsolve :: String -> String\r\nsolve s = if popCount n == 1 then \"NO\" else \"YES\"\r\n where n = read s :: Int\r\n\r\nprocess :: [String] -> String\r\nprocess (_ : inp) = unlines $ map solve inp\r\n\r\nmain :: IO ()\r\nmain = interact (process . lines)\r\n"}], "src_uid": "f4958b4833cafa46fa71357ab1ae41af"} {"source_code": "{-# LANGUAGE Safe #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.IntMap as IM\nimport Data.Ratio\nimport Control.Monad.State\nimport Data.Array.IO.Safe\nimport Data.Int\n\nreadIntBS = fst . fromJust . BS.readInt\n\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n let m = 998244353\n\n -- UL\n -- 1 => BB\n -- 2 => BW\n -- 3 => WB\n -- 4 => WW\n \n dp <- newArray ((0,0,1),(n,k+2,4)) 0 :: IO (IOUArray (Int,Int,Int) Int64)\n\n writeArray dp (1,1,1) 1\n writeArray dp (1,2,2) 1\n writeArray dp (1,2,3) 1\n writeArray dp (1,1,4) 1\n\n forM_ [2..n] $ \\i -> do\n forM_ [1..k] $ \\j -> do\n --BB\n writeArray dp (i,j,1) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)\n --BW\n when (j>1) $ do\n writeArray dp (i,j,2) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j-2,3) <*> readArray dp (i-1,j-1,4)\n --WB\n when (j>1) $ do\n writeArray dp (i,j,3) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j-2,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)\n --WW\n writeArray dp (i,j,4) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j,4)\n\n --print =<< (forM [1..n] $ \\i -> (forM [1..k] $ \\j -> forM [1..4] $ \\l -> readArray dp (i,j,l)))\n \n print =<< (\\a b c d -> (a+b+c+d)`mod`m) <$> readArray dp (n,k,1) <*> readArray dp (n,k,2) <*> readArray dp (n,k,3) <*> readArray dp (n,k,1)\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.IntMap as IM\nimport Data.Array.IO.Safe\nimport Data.Int\n\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n let m = 998244353\n\n -- UL\n -- 1 => BB\n -- 2 => BW\n -- 3 => WB\n -- 4 => WW\n \n dp <- newArray ((0,0,1),(n,k+2,4)) 0 :: IO (IOUArray (Int,Int,Int) Int64)\n\n writeArray dp (1,1,1) 1\n writeArray dp (1,2,2) 1\n writeArray dp (1,2,3) 1\n writeArray dp (1,1,4) 1\n\n forM_ [2..n] $ \\i -> do\n forM_ [1..k] $ \\j -> do\n --BB\n writeArray dp (i,j,1) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)\n --BW\n when (j>1) $ do\n writeArray dp (i,j,2) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j-2,3) <*> readArray dp (i-1,j-1,4)\n --WB\n when (j>1) $ do\n writeArray dp (i,j,3) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j-2,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)\n --WW\n writeArray dp (i,j,4) =<< (\\a b c d -> (a+b+c+d)`mod`m) <$>\n readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j,4)\n\n print =<< (\\a b c d -> (a+b+c+d)`mod`m) <$> readArray dp (n,k,1) <*> readArray dp (n,k,2) <*> readArray dp (n,k,3) <*> readArray dp (n,k,4)\n"}], "negative_code": [], "src_uid": "7e6a2329633ee283e3327413114901d1"} {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nsolve :: UArray Int Int -> Int -> Int\nsolve arr d = let\n (0, (+ 1) -> n) = bounds arr\n numOrbits = gcd n d\n orbitSize = n `div` numOrbits\n step incr ix = if ix + incr >= n then ix + incr - n else ix + incr\n getOrbit k = map (arr !) $ take orbitSize $ iterate (step d) k\n evalOne orbit = if foldl' (+) 0 orbit == orbitSize\n then maxBound\n else foldl' max 0 [length vs | vs@(1:_) <- group (orbit ++ orbit)]\n allOrbits = map getOrbit [0 .. numOrbits - 1]\n ans = foldl' max 0 $ map evalOne allOrbits\n in if ans == maxBound\n then 0-1\n else ans\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, d] <- getInts 2\n a <- listArray (0, n-1) <$> getInts n\n pure $ putInts [solve a d]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nsolve :: UArray Int Int -> Int -> Int\nsolve arr d = let\n (0, (+ 1) -> n) = bounds arr\n numOrbits = gcd n d\n orbitSize = n `div` numOrbits\n step incr ix = if ix + incr >= n then ix + incr - n else ix + incr\n getOrbitTwice k = map (arr !) $ take (2 * orbitSize) $ iterate (step d) k\n evalOne orbit -- Do not traverse an in-memory linked list: It's slow.\n = foldl' max 0 [length vs | vs@(1:_) <- group orbit]\n allOrbitsTwice = map getOrbitTwice [0 .. numOrbits - 1]\n ans = foldl' max 0 $ map evalOne allOrbitsTwice\n in if ans >= orbitSize\n then 0-1\n else ans\n\nmainFun :: SO\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, d] <- getInts 2\n a <- listArray (0, n-1) <$> getInts n\n pure $ putInts [solve a d]\n\n\ntype SP = State [P.ByteString]\ntype SO = SP Builder\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "c15bce9c4b9eddf5c8c3421b768da98c"} {"source_code": "import Control.Monad\nimport Data.Bits\nimport Data.Char\n\nprintPair :: Int -> Int -> IO ()\nprintPair x y = putStrLn . unwords $ map show [x, y]\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- replicateM n getLine\n let\n ra = reverse $ map reverse a\n pc = (a !! 0) !! 1\n qc = (a !! 1) !! 0\n xc = (ra !! 0) !! 1\n yc = (ra !! 1) !! 0\n [p, q, x, y] = map (\\v -> ord v - ord '0') [pc, qc, xc, yc]\n sw = p + q - x - y\n c = 2 - abs sw\n print c\n when (xor (sw >= 0) (p > 0)) (printPair 1 2)\n when (xor (sw >= 0) (q > 0)) (printPair 2 1)\n when (xor (sw >= 0) (x == 0)) (printPair n (n-1))\n when (xor (sw >= 0) (y == 0)) (printPair (n-1) n)\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport Data.Maybe (catMaybes)\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> process >>> unlines\n\nprocess :: [String] -> [String]\nprocess [] = []\nprocess (nn : xs) = show (length ys) : ys ++ process (drop n xs)\n where\n n = read nn\n ys = solve n (take n xs)\n\nsolve :: Int -> [String] -> [String]\nsolve n xs = map (\\(x, y) -> show x ++ \" \" ++ show y) . catMaybes $ go (at 2 1) (at 1 2) (at n (n - 1)) (at (n - 1) n)\n where\n at i j = xs !! (i - 1) !! (j - 1)\n go l1 l2 r1 r2\n | l1 == l2 = [get (l1 == r1) (n, n - 1), get (l1 == r2) (n - 1, n)]\n | r1 == r2 = [get (r1 == l1) (2, 1), get (r1 == l2) (1, 2)]\n | otherwise = [get True (1, 2), get (l1 == r1) (n, n - 1), get (l1 == r2) (n - 1, n)]\n get b x = if b then Just x else Nothing\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Char\n\nprintPair :: Int -> Int -> IO ()\nprintPair x y = putStrLn . unwords $ map show [x, y]\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n a <- replicateM n getLine\n let\n ra = reverse $ map reverse a\n pc = (a !! 0) !! 1\n qc = (a !! 1) !! 0\n xc = (ra !! 0) !! 1\n yc = (ra !! 1) !! 0\n [p, q, x, y] = map (\\v -> ord v - ord '0') [pc, qc, xc, yc]\n sw = p + q - x - y\n c = 2 - abs sw\n print c\n when (sw >= 0 && p > 0) (printPair 1 2)\n when (sw >= 0 && q > 0) (printPair 2 1)\n when (sw < 0 && x == 0) (printPair n (n-1))\n when (sw < 0 && y == 0) (printPair (n-1) n)\n"}], "src_uid": "be60cca56505e4b04d24c9b4990553c7"} {"source_code": "main = interact $ unlines . map p . chunk 3 . drop 1 . lines\r\n\r\nchunk n xs = take n xs : if length xs > n then chunk n (drop n xs) else []\r\n\r\nf = (map res [0 ..] !!)\r\n where res 0 = 0\r\n res 1 = 0\r\n res x = minimum [f y + 1 | y <- [x `div` 2..x-1], check y (x-y)]\r\n\r\ncheck :: Int -> Int -> Bool\r\ncheck y d = or [y `div` a == d | a <- reverse [(y `div` (d+1))..y `div` d], a > 0]\r\n\r\n\r\np xs =\r\n let ((n : k : _) : bs : cs : _) = fmap (fmap read . words) xs :: [[Int]]\r\n costs = [f x | x <- bs]\r\n maxk = sum costs + 1\r\n in show $ last $ dpIters n (dpIter costs cs) $ replicate (minimum [maxk, k+1]) 0\r\n\r\n\r\ndpIters n f val = foldl (\\s e -> e s) val [f x | x <- [0..n-1]]\r\n\r\n\r\ndpIter costs cs i res = let cost = costs !! i\r\n score = cs !! i\r\n in g cost score res\r\n\r\n\r\nzipWith' f l1 l2 = [ f e1 e2 | (e1, e2) <- zipWith k l1 l2 ]\r\n where\r\n k x y = x `seq` y `seq` (x,y)\r\n\r\ng cost score res = take cost res ++ zipWith' (\\ x y -> if (y + score) > x then y + score else x) (drop cost res) res\r\n", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad (replicateM_, foldM)\nimport Data.Array.ST\nimport Control.Monad.ST (ST, runST)\nmain = read <$> getLine >>= flip replicateM_ (scase $ minOpsGen 1000)\nscase costs = rln >>=\n \\[n, k] -> rln >>=\n \\bs -> rln >>=\n \\cs -> print $\n maxCoins (min k (12*n)) costs (listArray (1, n) bs)\n (listArray (1, n) cs)\n where rln = map read . words <$> getLine\nminOpsGen :: Int -> Array Int Int\nminOpsGen n = let m = n\n aS = newArray (1, n) m :: ST s (STArray s Int Int)\n in\n runSTArray $\n aS >>=\n \\a -> writeArray a 1 0 >>\n foldM f a [(i, i + i `div` j) | i <- [1..n], j <- [1..i],\n i+div i j <= n]\n where f :: STArray s Int Int -> (Int, Int) -> ST s (STArray s Int Int)\n f a (from, to) = readArray a from >>=\n \\af -> readArray a to >>=\n \\at -> if af + 1 < at\n then writeArray a to (af+1) >> return a\n else return a\nmaxCoins :: Int -> Array Int Int -> Array Int Int -> Array Int Int -> Int\nmaxCoins k costs b c = knapsack01 k (fmap (costs!) b) c\nknapsack01 :: Int -> Array Int Int -> Array Int Int -> Int\nknapsack01 wt wa va =\n let (1, n) = bounds wa\n in runST $\n (newArray ((0, 0), (n, wt)) 0 :: ST s (STUArray s (Int, Int) Int)) >>=\n \\m -> foldM f m (range ((1, 0), (n, wt))) >>= flip readArray (n, wt)\n where f ::STUArray s (Int, Int) Int -> (Int, Int)\n -> ST s (STUArray s (Int, Int) Int)\n f m (i, w) = readArray m (i-1, w) >>=\n \\mi1w -> ( if (wa!i) > w\n then writeArray m (i, w) mi1w\n else readArray m (i-1, w - wa!i) >>=\n \\mi1w1 -> writeArray m (i, w)\n (max mi1w (mi1w1+(va!i)))\n ) >> return m\n"}], "negative_code": [], "src_uid": "c4929ec631caae439ccb9bc6882ed816"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Int\nimport Data.List\nimport Text.Printf\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ngetCost :: [Int64] -> Int -> Int64\ngetCost as k = c\n where ! k' = fromIntegral k\n combine a i = a + i * k'\n candidates = take k . sort $ zipWith combine as ([1 ..] :: [Int64])\n ! c = sum candidates\n\nsolve :: [Int64] -> Int64 -> (Int, Int64)\nsolve as s | s >= cmax = (n, cmax)\n | otherwise = go 0 n\n where n = length as\n cmax = getCost as n\n\n go l r | l + 1 == r = (l, c)\n | s >= c = go m r\n | otherwise = go l m\n where m = (l + r) `div` 2\n c = getCost as m\n\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int from: \" ++ (L.unpack s)\n\nnextInt64 :: Tokenizer Int64\nnextInt64 = fromIntegral <$> nextInt\n\ngo :: Tokenizer (Int, Int64)\ngo = do\n n <- nextInt\n s <- nextInt64\n as <- replicateM n nextInt64\n return $ solve as s\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n let (k, c) = evalState go input\n printf \"%d %d\\n\" k c\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve :: Int64 -> Int64 -> [Int64] -> (Int64, Int64)\nsolve s n as = go 0 (n + 1)\n where\n cost k = sum $ take (fromIntegral k) $ sort $ map (\\(i, a) -> a + i * k) $ zip [1..] as\n go !l !r \n | r - l > 1 = if c > s then go l m else go m r\n | otherwise = (l, c)\n where \n m = (l + r) `div` 2\n c = cost m\n\nmain = do \n n:s:_ <- readInts <$> B.getLine\n as <- readInts <$> B.getLine\n let (k, t) = solve s n as\n putStr $ show k ++ \" \" ++ show t\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nmodule Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Int\nimport Data.List\nimport Text.Printf\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ngetCost :: [Int64] -> Int -> Int64\ngetCost as k = c\n where k' = fromIntegral k\n combine a i = a + i * k'\n candidates = take k . sort $ zipWith combine as ([1 ..] :: [Int64])\n c = sum candidates\n\nsolve :: [Int64] -> Int64 -> (Int, Int64)\nsolve as s | s >= cmax = (n, cmax)\n | otherwise = go 0 n\n where n = length as\n cmax = getCost as n\n\n go l r | l + 1 == r = (l, c)\n | s >= c = go m r\n | otherwise = go l m\n where m = (l + r) `div` 2\n c = getCost as m\n\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int from: \" ++ (L.unpack s)\n\nnextInt64 :: Tokenizer Int64\nnextInt64 = fromIntegral <$> nextInt\n\ngo :: Tokenizer (Int, Int64)\ngo = do\n n <- nextInt\n s <- nextInt64\n as <- replicateM n nextInt64\n return $ solve as s\n\nmain :: IO ()\nmain = do\n input <- L.words <$> L.getContents\n let (k, c) = evalState go input\n printf \"%d %d\\n\" k c\n"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\n\nreadInt = maybe undefined (fromIntegral . fst) . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve :: Int64 -> Int64 -> [Int64] -> (Int64, Int64)\nsolve s n as = go 0 (n + 1)\n where\n cost k = sum $ take (fromIntegral k) $ sort $ map (\\(i, a) -> a + i * k) $ zip [1..] as\n go l r \n | r - l > 1 = if c > s then go l m else go m r\n | otherwise = (l, c)\n where \n m = (l + r) `div` 2\n c = cost m\n\nmain = do \n n:s:_ <- readInts <$> B.getLine\n as <- readInts <$> B.getLine\n let (k, t) = solve s n as\n putStr $ show k ++ \" \" ++ show t\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = (readInt <$>) . B.words\n\nsolve s n as = go 0 (n + 1)\n where\n cost k = sum $ take k $ sort $ map (\\(i, a) -> a + i * k) $ zip [1..] as\n go !l !r \n | r - l > 1 = if c > s then go l m else go m r\n | otherwise = (l, c)\n where \n m = (l + r) `div` 2\n c = cost m\n\nmain = do \n n:s:_ <- readInts <$> B.getLine\n as <- readInts <$> B.getLine\n let (k, t) = solve s n as\n putStr $ show k ++ \" \" ++ show t\n"}], "src_uid": "b1fd037d5ac6023ef3250fc487656db5"} {"source_code": "import Data.Functor\nimport Data.List (nub, zip4)\nimport Data.Bits\nimport Debug.Trace\nimport Control.Monad.ST\n\nmodNum = 1000000007 :: Integer\n\nmodIt :: Integer -> Integer\nmodIt a = mod a modNum\n\n(//) = div\n(%%) = mod\n(/|) :: Integer -> Integer -> Bool\na /| b = mod b a == 0\n\n(***) :: Integer -> Integer -> Integer\na *** b = modIt $ a * b\n\n(^^^) :: Integer -> Integer -> Integer\na ^^^ 0 = 1\na ^^^ b = cur *** ((a *** a) ^^^ (div b 2))\n where cur = if b .&. 1 == 1 then a else 1\n\n\nextGCD :: Integer -> Integer -> (Integer, Integer, Integer)\nextGCD a 0 = (a, 1, 0)\nextGCD a b = (d, ny, nx - (a // b) * ny)\n where (d, nx, ny) = extGCD b (a %% b)\n\nmain :: IO ()\nmain = getInts >>= putStrLn . show . solve . parsePairs . tail where\n getInts = map read <$> words <$> getContents\n parsePairs [] = []\n parsePairs (x:y:rs) = (x,y) : parsePairs rs\n\n---------------------------------------------------------------------\nsolve :: [Pair] -> Integer\nsolve (p:[]) = fst p\nsolve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i\n Single (i, _) -> answer i\n All -> answer 0\n None -> -1\n where sol = foldl intersect All . map projToX $ map (solve0 p) rs\n answer i = (fst p) *** ((snd p) ^^^ i)\n\n-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j\nsolve0 :: Pair -> Pair -> Solution\nsolve0 (a1, b1) (a2, b2) = ans\n where primes = nub . concat . map factorize $ [a1, a2, b1, b2]\n [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]\n f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)\n ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'\n\nfactorize :: Integer -> [Integer]\nfactorize 1 = []\nfactorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in\n if xs == [] then [n] else let x = head xs in x:factorize (n // x)\n\ntoVec [] n = []\ntoVec (p:rs) n = getNum p n : toVec rs n where\n getNum p n = if p /| n then 1 + getNum p (n // p) else 0\n\n---------------------------------------------------------------------\n-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j\n-- a, b -> t=(i,j) s.t. a+bt is on line x=y\nf :: Pair -> Pair -> Solution\nf (a1, a2) (0, 0) = if a1 == a2 then All else None\nf (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in \n if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)\nf (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in \n if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)\nf (a1, a2) (b1, b2) = runST $ do\n (g, i0, j0) <- return $ extGCD b1 b2\n if g /| (a2-a1)\n then do\n d <- return $ (a2 - a1) // g\n (i, j) <- return $ (i0 * d, -j0 * d)\n (di, dj) <- return $ (b2 // g, b1 // g)\n return $ simplify i j di dj\n else return None\n\n---------------------------------------------------------------------\ntype Pair = (Integer, Integer)\n\nparallel :: Pair -> Pair -> Bool\nparallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1\n\ndata Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)\ngetSrc (Multi p _) = p\ngetDir (Multi _ p) = p\n\nprojToX :: Solution -> Solution\nprojToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)\n Single (i, _) -> Single (i, 0)\n None -> None\n All -> Multi (0, 0) (1, 0)\n\nsimplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)\n where\n t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1\n i0' = i0 + t1 * di\n j0' = j0 + t1 * dj\n t2 = max 0 $ min (div i0 di) (div j0 dj)\n i0'' = i0' - t2 * di\n j0'' = j0' - t2 * dj\n\ncontains :: Pair -> Solution -> Bool\ncontains _ All = True\ncontains _ None = False\ncontains p (Single a) = p == a\ncontains (x, y) (Multi (i, j) (di, dj)) = \n (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)\n where (dx, dy) = (x-i, y-j)\n (u, v) = (dx+dy, di+dj)\n\nintersect :: Solution -> Solution -> Solution\nintersect None _ = None\nintersect _ None = None\nintersect a All = a\nintersect All a = a\nintersect (Single p) a = if contains p a then Single p else None\nintersect a (Single p) = if contains p a then Single p else None\nintersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2\n where\n res1 = \n if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans\n where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)\n tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)\n else f (snd s1, snd s2) (snd d1, snd d2)\n ((i, _), (di, _)) = (getSrc tmp, getDir tmp)\n s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)\n d = (fst d1 * di, snd d1 * di)\n ans = Multi s d\n makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))\n where a = y2 - y1\n b = x1 - x2\n res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2\n then Single (x, y)\n else None\n where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)\n (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)\n t = a1*b2-a2*b1\n x0 = b1*c2-c1*b2\n y0 = c1*a2-a1*c2\n (x, y) = (x0//t, y0//t)\n\n", "positive_code": [{"source_code": "import Data.Functor\nimport Data.List (nub, zip4)\nimport Data.Bits\nimport Debug.Trace\nimport Control.Monad.ST\n\nmodNum = 1000000007 :: Integer\n\nmodIt :: Integer -> Integer\nmodIt a = mod a modNum\n\n(//) = div\n(%%) = mod\n(/|) :: Integer -> Integer -> Bool\na /| b = mod b a == 0\n\n(***) :: Integer -> Integer -> Integer\na *** b = modIt $ a * b\n\n(^^^) :: Integer -> Integer -> Integer\na ^^^ 0 = 1\na ^^^ b = cur *** ((a *** a) ^^^ (div b 2))\n where cur = if b .&. 1 == 1 then a else 1\n\n\nextGCD :: Integer -> Integer -> (Integer, Integer, Integer)\nextGCD a 0 = (a, 1, 0)\nextGCD a b = (d, ny, nx - (a // b) * ny)\n where (d, nx, ny) = extGCD b (a %% b)\n\nmain :: IO ()\nmain = getInts >>= putStrLn . show . solve . parsePairs . tail where\n getInts = map read <$> words <$> getContents\n parsePairs [] = []\n parsePairs (x:y:rs) = (x,y) : parsePairs rs\n\n---------------------------------------------------------------------\nsolve :: [Pair] -> Integer\nsolve (p:[]) = fst p\nsolve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i\n Single (i, _) -> answer i\n All -> answer 0\n None -> -1\n where sol = foldl intersect All . map projToX $ map (solve0 p) rs\n answer i = (fst p) *** ((snd p) ^^^ i)\n\n-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j\nsolve0 :: Pair -> Pair -> Solution\nsolve0 (a1, b1) (a2, b2) = ans\n where primes = nub . concat . map factorize $ [a1, a2, b1, b2]\n [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]\n f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)\n ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'\n\nfactorize :: Integer -> [Integer]\nfactorize 1 = []\nfactorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in\n if xs == [] then [n] else let x = head xs in x:factorize (n // x)\n\ntoVec [] n = []\ntoVec (p:rs) n = getNum p n : toVec rs n where\n getNum p n = if p /| n then 1 + getNum p (n // p) else 0\n\n---------------------------------------------------------------------\n-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j\n-- a, b -> t=(i,j) s.t. a+bt is on line x=y\nf :: Pair -> Pair -> Solution\nf (a1, a2) (0, 0) = if a1 == a2 then All else None\n\nf (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in \n if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)\n\nf (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in \n if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)\n\nf (a1, a2) (b1, b2) = let (g, i0, j0) = extGCD b1 b2 in\n if g /| (a2-a1) \n then let d = (a2-a1)//g\n (i, j, di, dj) = (i0*d, -j0*d, b2//g, b1//g)\n in simplify i j di dj\n else None\n\n---------------------------------------------------------------------\ntype Pair = (Integer, Integer)\n\nparallel :: Pair -> Pair -> Bool\nparallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1\n\ndata Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)\ngetMulti (Multi (i,j) (di,dj)) = (i, j, di, dj)\n\nprojToX :: Solution -> Solution\nprojToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)\n Single (i, _) -> Single (i, 0)\n None -> None\n All -> Multi (0, 0) (1, 0)\n\nsimplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)\n where\n t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1\n i0' = i0 + t1 * di\n j0' = j0 + t1 * dj\n t2 = max 0 $ min (div i0 di) (div j0 dj)\n i0'' = i0' - t2 * di\n j0'' = j0' - t2 * dj\n\ncontains :: Pair -> Solution -> Bool\ncontains _ All = True\ncontains _ None = False\ncontains p (Single a) = p == a\ncontains (x, y) (Multi (i, j) (di, dj)) = \n (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)\n where (dx, dy) = (x-i, y-j)\n (u, v) = (dx+dy, di+dj)\n\nintersect :: Solution -> Solution -> Solution\nintersect None _ = None\nintersect _ None = None\nintersect a All = a\nintersect All a = a\nintersect (Single p) a = if contains p a then Single p else None\nintersect a (Single p) = if contains p a then Single p else None\nintersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2\n where\n res1 = let (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2) in\n if not (parallel (dx,dy) d1) \n then None \n else let tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)\n else f (snd s1, snd s2) (snd d1, snd d2)\n in if tmp == None \n then None \n else let (i, _, di, _) = getMulti tmp\n s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)\n d = (fst d1 * di, snd d1 * di)\n in Multi s d\n makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))\n where a = y2 - y1\n b = x1 - x2\n res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2\n then Single (x, y)\n else None\n where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)\n (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)\n t = a1*b2-a2*b1\n x0 = b1*c2-c1*b2\n y0 = c1*a2-a1*c2\n (x, y) = (x0//t, y0//t)\n\n"}, {"source_code": "import Data.Functor\nimport Data.List (nub, zip4)\nimport Data.Bits\nimport Debug.Trace\n\nmodNum = 1000000007 :: Integer\n\nmodIt :: Integer -> Integer\nmodIt a = mod a modNum\n\n(//) = div\n(%%) = mod\n(/|) :: Integer -> Integer -> Bool\na /| b = mod b a == 0\n\n(***) :: Integer -> Integer -> Integer\na *** b = modIt $ a * b\n\n(^^^) :: Integer -> Integer -> Integer\na ^^^ 0 = 1\na ^^^ b = cur *** ((a *** a) ^^^ (div b 2))\n where cur = if b .&. 1 == 1 then a else 1\n\n\nextGCD :: Integer -> Integer -> (Integer, Integer, Integer)\nextGCD a 0 = (a, 1, 0)\nextGCD a b = (d, ny, nx - (a // b) * ny)\n where (d, nx, ny) = extGCD b (a %% b)\n\nmain :: IO ()\nmain = getInts >>= putStrLn . show . solve . parsePairs . tail where\n getInts = map read <$> words <$> getContents\n parsePairs [] = []\n parsePairs (x:y:rs) = (x, y) : parsePairs rs\n--main = putStrLn . show $ modPow (123::Integer) (321::Integer)\n--main = putStrLn . show $ factorize (modNum::Integer)\n\n---------------------------------------------------------------------\nsolve :: [Pair] -> Integer\nsolve (p:[]) = fst p\nsolve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i\n Single (i, _) -> answer i\n All -> answer 0\n None -> -1\n where sol = foldl intersect All . map projToX $ map (solve0 p) rs\n answer i = (fst p) *** ((snd p) ^^^ i)\n\n-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j\nsolve0 :: Pair -> Pair -> Solution\nsolve0 (a1, b1) (a2, b2) = \n --trace (\"go \" ++ show (a1,b1) ++ \" \" ++ show (a2,b2) ++ \" \" ++ show ans) $\n ans\n where primes = nub . concat . map factorize $ [a1, a2, b1, b2]\n [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]\n f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)\n ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'\n\nfactorize :: Integer -> [Integer]\nfactorize 1 = []\nfactorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in\n if xs == [] then [n] else let x = head xs in x:factorize (n // x)\n\ntoVec [] n = []\ntoVec (p:rs) n = getNum p n : toVec rs n where\n getNum p n = if p /| n then 1 + getNum p (n // p) else 0\n\n---------------------------------------------------------------------\n-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j\n-- a, b -> t=(i,j) s.t. a+bt is on line x=y\nf :: Pair -> Pair -> Solution\nf (a1, a2) (0, 0) = if a1 == a2 then All else None\nf (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in \n if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)\nf (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in \n if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)\nf (a1, a2) (b1, b2) = \n --trace (\"f \" ++ show (g,i0',j0',i0,j0,di,dj) ++ \" \"++ show (a1,a2) ++ \" \" ++ show (b1,b2) ++ \" \" ++ show ans) $\n ans\n where (g, i0', j0'') = extGCD b1 b2\n j0' = -j0''\n d = (a2 - a1) // g\n (i0, j0) = (i0' * d, j0' * d)\n (di, dj) = (b2 // g, b1 // g)\n val = simplify i0 j0 di dj\n ans = if g /| (a2-a1) then val else None\n\n---------------------------------------------------------------------\ntype Pair = (Integer, Integer)\n\nparallel :: Pair -> Pair -> Bool\nparallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1\n\ndata Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)\ngetSrc (Multi p _) = p\ngetDir (Multi _ p) = p\n\nprojToX :: Solution -> Solution\nprojToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)\n Single (i, _) -> Single (i, 0)\n None -> None\n All -> Multi (0, 0) (1, 0)\n\nsimplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)\n where\n t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1\n i0' = i0 + t1 * di\n j0' = j0 + t1 * dj\n t2 = max 0 $ min (div i0 di) (div j0 dj)\n i0'' = i0' - t2 * di\n j0'' = j0' - t2 * dj\n\ncontains :: Pair -> Solution -> Bool\ncontains _ All = True\ncontains _ None = False\ncontains p (Single a) = p == a\ncontains (x, y) (Multi (i, j) (di, dj)) = \n (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)\n where (dx, dy) = (x-i, y-j)\n (u, v) = (dx+dy, di+dj)\n\nintersect :: Solution -> Solution -> Solution\nintersect None _ = None\nintersect _ None = None\nintersect a All = a\nintersect All a = a\nintersect (Single p) a = if contains p a then Single p else None\nintersect a (Single p) = if contains p a then Single p else None\nintersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2\n where\n res1 = \n if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans\n where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)\n tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)\n else f (snd s1, snd s2) (snd d1, snd d2)\n ((i, _), (di, _)) = (getSrc tmp, getDir tmp)\n s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)\n d = (fst d1 * di, snd d1 * di)\n ans = Multi s d\n makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))\n where a = y2 - y1\n b = x1 - x2\n res2 = \n --trace (\"res2: \" ++ show (x,y)) $\n if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2\n then Single (x, y)\n else None\n where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)\n (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)\n t = a1*b2-a2*b1\n x0 = b1*c2-c1*b2\n y0 = c1*a2-a1*c2\n (x, y) = (x0//t, y0//t)\n\n"}, {"source_code": "import Data.Functor\nimport Data.List (nub, zip4)\nimport Data.Bits\nimport Debug.Trace\nimport Control.Monad.ST\n\nmodNum = 1000000007 :: Integer\n\nmodIt :: Integer -> Integer\nmodIt a = mod a modNum\n\n(//) = div\n(%%) = mod\n(/|) :: Integer -> Integer -> Bool\na /| b = mod b a == 0\n\n(***) :: Integer -> Integer -> Integer\na *** b = modIt $ a * b\n\n(^^^) :: Integer -> Integer -> Integer\na ^^^ 0 = 1\na ^^^ b = cur *** ((a *** a) ^^^ (div b 2))\n where cur = if b .&. 1 == 1 then a else 1\n\n\nextGCD :: Integer -> Integer -> (Integer, Integer, Integer)\nextGCD a 0 = (a, 1, 0)\nextGCD a b = (d, ny, nx - (a // b) * ny)\n where (d, nx, ny) = extGCD b (a %% b)\n\nmain :: IO ()\nmain = getInts >>= putStrLn . show . solve . parsePairs . tail where\n getInts = map read <$> words <$> getContents\n parsePairs [] = []\n parsePairs (x:y:rs) = (x,y) : parsePairs rs\n\n---------------------------------------------------------------------\nsolve :: [Pair] -> Integer\nsolve (p:[]) = fst p\nsolve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i\n Single (i, _) -> answer i\n All -> answer 0\n None -> -1\n where sol = foldl intersect All . map projToX $ map (solve0 p) rs\n answer i = (fst p) *** ((snd p) ^^^ i)\n\n-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j\nsolve0 :: Pair -> Pair -> Solution\nsolve0 (a1, b1) (a2, b2) = ans\n where primes = nub . concat . map factorize $ [a1, a2, b1, b2]\n [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]\n f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)\n ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'\n\nfactorize :: Integer -> [Integer]\nfactorize 1 = []\nfactorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in\n if xs == [] then [n] else let x = head xs in x:factorize (n // x)\n\ntoVec [] n = []\ntoVec (p:rs) n = getNum p n : toVec rs n where\n getNum p n = if p /| n then 1 + getNum p (n // p) else 0\n\n---------------------------------------------------------------------\n-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j\n-- a, b -> t=(i,j) s.t. a+bt is on line x=y\nf :: Pair -> Pair -> Solution\nf (a1, a2) (0, 0) = if a1 == a2 then All else None\nf (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in \n if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)\nf (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in \n if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)\nf (a1, a2) (b1, b2) = \n if g /| (a2-a1) \n then let d = (a2-a1)//g\n (i, j, di, dj) = (i0*d, -j0*d, b2//g, b1//g)\n in simplify i j di dj\n else None\n where (g, i0, j0) = extGCD b1 b2\n\n---------------------------------------------------------------------\ntype Pair = (Integer, Integer)\n\nparallel :: Pair -> Pair -> Bool\nparallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1\n\ndata Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)\ngetSrc (Multi p _) = p\ngetDir (Multi _ p) = p\n\nprojToX :: Solution -> Solution\nprojToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)\n Single (i, _) -> Single (i, 0)\n None -> None\n All -> Multi (0, 0) (1, 0)\n\nsimplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)\n where\n t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1\n i0' = i0 + t1 * di\n j0' = j0 + t1 * dj\n t2 = max 0 $ min (div i0 di) (div j0 dj)\n i0'' = i0' - t2 * di\n j0'' = j0' - t2 * dj\n\ncontains :: Pair -> Solution -> Bool\ncontains _ All = True\ncontains _ None = False\ncontains p (Single a) = p == a\ncontains (x, y) (Multi (i, j) (di, dj)) = \n (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)\n where (dx, dy) = (x-i, y-j)\n (u, v) = (dx+dy, di+dj)\n\nintersect :: Solution -> Solution -> Solution\nintersect None _ = None\nintersect _ None = None\nintersect a All = a\nintersect All a = a\nintersect (Single p) a = if contains p a then Single p else None\nintersect a (Single p) = if contains p a then Single p else None\nintersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2\n where\n res1 = \n if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans\n where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)\n tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)\n else f (snd s1, snd s2) (snd d1, snd d2)\n ((i, _), (di, _)) = (getSrc tmp, getDir tmp)\n s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)\n d = (fst d1 * di, snd d1 * di)\n ans = Multi s d\n makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))\n where a = y2 - y1\n b = x1 - x2\n res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2\n then Single (x, y)\n else None\n where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)\n (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)\n t = a1*b2-a2*b1\n x0 = b1*c2-c1*b2\n y0 = c1*a2-a1*c2\n (x, y) = (x0//t, y0//t)\n\n"}], "negative_code": [{"source_code": "import Data.Functor\nimport Data.List (nub, zip4)\nimport Data.Bits\n\nmodNum = 1000000007 :: Integer\n\nmodIt :: Integer -> Integer\nmodIt a = mod a modNum\n\n(//) = div\n(%%) = mod\n\n(***) :: Integer -> Integer -> Integer\na *** b = modIt $ a * b\n\n(^^^) :: Integer -> Integer -> Integer\na ^^^ 0 = 1\na ^^^ b = cur *** ((a *** a) ^^^ (div b 2))\n where cur = if b .&. 1 == 1 then a else 1\n\n(|||) :: Integer -> Integer -> Bool\na ||| b = mod b a == 0\n\nextGCD :: Integer -> Integer -> (Integer, Integer, Integer)\nextGCD a 0 = (a, 1, 0)\nextGCD a b = (d, ny, nx - (a // b) * ny)\n where (d, nx, ny) = extGCD b (a %% b)\n\nmain :: IO ()\nmain = getInts >>= putStrLn . show . solve . parsePairs . tail where\n getInts = map read <$> words <$> getContents\n parsePairs [] = []\n parsePairs (x:y:rs) = (x, y) : parsePairs rs\n--main = putStrLn . show $ modPow (123::Integer) (321::Integer)\n--main = putStrLn . show $ factorize (modNum::Integer)\n\n---------------------------------------------------------------------\nsolve :: [Pair] -> Integer\nsolve (p:[]) = modIt $ fst p\nsolve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i\n Single (i, _) -> answer i\n All -> answer 0\n None -> -1\n where sol = foldl intersect All . map projToX $ map (solve0 p) rs\n answer i = modIt $ fst p * ((snd p) ^^^ i)\n\n-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j\nsolve0 :: Pair -> Pair -> Solution\nsolve0 (a1, b1) (a2, b2) = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'\n where primes = nub . concat . map factorize $ [a1, a2, b1, b2]\n [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]\n f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)\n\nfactorize :: Integer -> [Integer]\nfactorize 1 = []\nfactorize n = let xs = filter (||| n) [2 .. floor . sqrt $ fromIntegral n] in\n if xs == [] then [n] else let x = head xs in x:factorize (n // x)\n\ntoVec [] n = []\ntoVec (p:rs) n = getNum p n : toVec rs n where\n getNum p n = if p ||| n then 1 + getNum p (n // p) else 0\n\n---------------------------------------------------------------------\n-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j\n-- a, b -> t=(i,j) s.t. a+bt is on line x=y\nf :: Pair -> Pair -> Solution\nf (a1, a2) (0, 0) = if a1 == a2 then All else None\nf (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in \n if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)\nf (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in \n if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)\nf (a1, a2) (b1, b2) = if g ||| (a2-a1) then val else None\n where (g, i0', j0') = extGCD b1 (-b2)\n d = (a2 - a1) // g\n (i0, j0) = (i0' * d, j0' * d)\n (di, dj) = (b2 // g, b1 // g)\n val = simplify i0 j0 di dj\n\n---------------------------------------------------------------------\ntype Pair = (Integer, Integer)\n\nparallel :: Pair -> Pair -> Bool\nparallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1\n\ndata Solution = Multi Pair Pair | Single Pair | None | All\ngetSrc (Multi p _) = p\ngetDir (Multi _ p) = p\n\nprojToX :: Solution -> Solution\nprojToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)\n Single (i, _) -> Single (i, 0)\n None -> None\n All -> Multi (0, 0) (1, 0)\n\nsimplify i0 j0 di dj = Multi (i0'', j0'') (di, dj) -- TODO\n where\n t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1\n i0' = i0 + t1 * di\n j0' = j0 + t1 * dj\n t2 = max 0 $ min (div i0 di) (div j0 dj)\n i0'' = i0' - t2 * di\n j0'' = j0' - t2 * dj\n\ncontains :: Pair -> Solution -> Bool\ncontains _ All = True\ncontains _ None = False\ncontains p (Single a) = p == a\ncontains (x, y) (Multi (i, j) (di, dj)) = \n (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v|||u) && (u//v)>0)\n where (dx, dy) = (x-i, y-j)\n (u, v) = (dx+dy, di+dj)\n\nintersect :: Solution -> Solution -> Solution\nintersect None _ = None\nintersect _ None = None\nintersect a All = a\nintersect All a = a\nintersect (Single p) a = if contains p a then Single p else None\nintersect a (Single p) = if contains p a then Single p else None\nintersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2\n where\n res1 = if not (parallel (dx,dy) d1) then None else ans\n where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)\n tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)\n else f (snd s1, snd s2) (snd d1, snd d2)\n ((i, _), (di, _)) = (getSrc tmp, getDir tmp)\n s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)\n d = (fst d1 * di, snd d1 * di)\n ans = Multi s d\n makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))\n where a = y2 - y1\n b = x1 - x2\n res2 = if (t|||x0) && (t|||y0) && contains (x,y) m1 && contains (x,y) m2\n then Single (x, y)\n else None\n where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)\n (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)\n t = a1*b2-a2*b1\n x0 = b1*c2-c1*b2\n y0 = c1*a2-a1*c2\n (x, y) = (x0//t, y0//t)\n\n"}], "src_uid": "6126d9533abd466545d8153233b14192"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\t\t\n\nonecase = do\n\t\t[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tlet x = div s c\n\t\tprint $ x + (div x a)*b\n\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\treplicateM_ n onecase\n", "positive_code": [{"source_code": "{-# LANGUAGE Safe #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Control.Applicative\nimport Control.Arrow\nimport Data.List\nimport Data.Array\nimport Data.Array.IO.Safe\nimport Data.Array.ST.Safe\nimport Data.IORef\nimport Data.STRef\nimport Data.Maybe\nimport Data.Bits\nimport Data.Ord\nimport Data.Ratio\nimport Data.Int\nimport Data.Char\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as Set\nimport qualified Data.Sequence as Sq\nimport Data.Tuple\nimport Data.Function\nimport Text.Printf\nimport Numeric\n\nreadIntBS = fst . fromJust . BS.readInt\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n [s,a,b,c] <- map read . words <$> getLine :: IO [Integer]\n let n = s `div` c\n print $ n + (n`div`a)*b\n"}, {"source_code": "f::[String]->[String]\nf []=[]\nf (e:es)=let (n:a:b:c:[])=map read (words e)::[Integer]\n t1=n `div` c\n t2=(t1 `div` a)*b\n in (show (t1+t2)):f es \n \nmain = do\n e<-getLine\n es<-getContents\n mapM_ putStrLn $ f (lines es)"}, {"source_code": "count :: Integer -> Integer -> Integer -> Integer -> Integer\ncount s a b c = n + b*(n `div` a)\n where n = s `div` c\n\nreadInt :: String -> Int\nreadInt s = read s\n\nreadInteger :: String -> Integer\nreadInteger s = read s\n\nreadIntegerList :: String -> [Integer]\nreadIntegerList line = map readInteger $ words line\n\nsolve :: IO ()\nsolve = do\n (s:a:b:c:[]) <- fmap readIntegerList getLine\n putStrLn $ show $ count s a b c\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n sequence_ $ replicate t solve\n"}, {"source_code": "import Data.Int\nmain = interact $ unlines . map show . go . map read . tail . words\ngo [] = []\ngo (s:a:b:c:xs) = (paid + paid `div` a * b) : go xs where\n paid = s `div` c :: Int64\n"}, {"source_code": "process :: Integral a => a -> a -> a -> a -> a\nprocess s a b c = d * (a + b) + (m `div` c)\n where (d,m) = divMod s (a*c)\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ns <- fmap (map (map readInt.words).lines) getContents\n mapM_ print $ map (\\[s,a,b,c] -> process s a b c) ns"}, {"source_code": "import Control.Monad\nimport Data.Foldable (traverse_)\n\nsolve :: [Integer] -> Integer\nsolve [s, a, b, c] = (s `div` ac) * (a + b) + ((s `mod` ac) `div` c)\n\twhere ac = a * c\n\nmain :: IO ()\nmain = do\n\ta <- getLine\n\ttests <- replicateM (read a) getLine\n\ttraverse_ (putStrLn . show .solve) $ map ((map read) . words) tests\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\t\t\n\nonecase = do\n\t\t[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]\n\t\tprint $ (div s c) + (div s a)*b\n\nmain = do\n\t\tn<-read<$> getLine ::IO Int\n\t\treplicateM_ n onecase\n"}], "src_uid": "ec8060260a6c7f4ff3e6afc9fd248afc"} {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Prelude\nimport qualified Data.ByteString.Lazy.Char8 as L\n\ntype Tokenizer = State [L.ByteString]\n\nnextInt :: Tokenizer Int\nnextInt = state $ \\(s:ss) -> case L.readInt s of\n Just (x, _) -> (x, ss)\n Nothing -> error $ \"Can't parse Int:\" ++ (show s)\n\nnextWord :: Tokenizer [Char]\nnextWord = state $ \\(s:ss) -> (L.unpack s, ss)\n\nsolve :: Tokenizer Int\nsolve = do\n [n, a, b] <- replicateM 3 nextInt\n s <- nextWord\n if s!!(a - 1) == s!!(b - 1) then return 0\n else return 1\n\nmain = do\n contents <- L.getContents\n print $ evalState solve (L.words contents)\n", "positive_code": [{"source_code": "\nmain :: IO ()\nmain = do\n s1 <- getLine\n let [n, a, b] = map read $ words s1\n s <- getLine\n let va = s!!(a - 1)\n let vb = s!!(b - 1)\n if va == vb\n then putStrLn \"0\"\n else putStrLn \"1\""}, {"source_code": "#!/usr/bin/env stack\n{- stack\n --resolver lts-2.22\n runghc\n --package array\n --package base\n --package bytestring\n --package containers\n --package mtl\n --package parsec\n --package vector\n --\n -hide-all-packages\n-}\n{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}\nmodule Main\n( main\n) where\n\nimport Prelude hiding (interact, lines, unlines, words, unwords,\n sequence, foldr)\nimport Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,\n unlines, unwords, interact, readInt,\n readInteger)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)\nimport qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.Map.Strict as M\nimport Data.Map.Strict (Map)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Array.IArray as A\nimport Data.Array.IArray ((!), Array, listArray, array)\nimport Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,\n catMaybes)\nimport Data.Either (either)\nimport Control.Applicative (Applicative, pure,\n (<$>), (<*>), liftA2, liftA3)\nimport Control.Monad (unless, when, void, filterM, ap)\nimport Control.Arrow ((***), (&&&), first, second)\nimport Data.Traversable (sequence, sequenceA, traverse,\n Traversable)\nimport Data.Ord (comparing, Down(..))\nimport Data.Function (on)\nimport Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,\n bit, shiftR, shiftL, Bits)\nimport qualified Data.Bits as B\nimport Data.Word (Word32)\nimport Control.Monad.State (State, get, put, gets, modify,\n evalState, execState, runState)\nimport Text.Parsec (char, space, parse, Parsec)\nimport qualified Text.Parsec as P\nimport Data.Tuple (swap)\nimport Data.Foldable (Foldable, foldr)\nimport Data.Monoid ((<>), Monoid, mappend, mempty)\n\ntype N = Int\ntoNum = toInt\n\nanswer :: N -> N -> [Char] -> N\nanswer i j xs = if xs !! (i-1) == xs !! (j-1)\n then 0 else 1\n\nhandleInput :: ByteString -> ByteString\nhandleInput = words & drop 1\n & coerceInput answer\n & show & pack\n -- & map (show & pack) & unlines\n\ntoInt = readInt & fromJust & fst\ntoInte = readInteger & fromJust & fst\ntoX :: Read a => ByteString -> a\ntoX = unpack & read\n\ncoerceInput f (a:b:c:xs) = f (toNum a) (toNum b) (unpack c)\ncoerceInput _ _ = error \"invalid input\"\n\nmain :: IO ()\nmain = interact handleInput\n\n-- Util stuff --\n(&) :: (a -> b) -> (b -> c) -> a -> c\n(&) = flip (.)\ninfixl 9 &\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n\n main :: IO()\n main = do\n [n, a, b] <- getLine >>= return . (map readInt) . words\n xs <- getLine\n let p = xs !! (a - 1)\n q = xs !! (b - 1) \n case p == q of\n True -> print 0\n False -> print 1\n"}, {"source_code": "module Main where\n \n main :: IO ()\n main = do\n l <- getLine\n let [_, a, b] = map (\\x -> read x :: Int) $ words l\n s <- getLine\n print $ if s !! (a - 1) == s !! (b - 1) then 0 else 1\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\n\n-- Meat\nsolve :: Int -> Int -> String -> Int\nsolve a b s = iif 0 1 (s !! a == s !! b)\n\n-- Shit\nmain :: IO ()\nmain = do\n [_,a,b] <- readShit\n s <- readShit\n printShit $ solve (a - 1) (b - 1) s\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: x -> x -> Bool-> x\niif a b c = if c then a else b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleInstances #-}\nmodule Main (printShit, printShitV, readShit, main, yN, iif) where\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Control.Arrow\n\n-- Meat\nsolve :: Int -> Int -> String -> Int\nsolve a b s\n | ours == theirs = 0\n | otherwise = findOurs ours . (reverse *** tail) . splitAt b $ s\n where ours = s !! a\n theirs = s !! b\n\nfindOurs :: Char -> (String, String) -> Int\nfindOurs c ([], y:ys) = if c == y then 1 else 1 + findOurs c ([], ys)\nfindOurs c (x:xs, []) = if c == x then 1 else 1 + findOurs c (xs, [])\nfindOurs c (x:xs, y:ys) = if c == y || c == x then 1 else 1 + findOurs c (xs, ys)\nfindOurs _ ([], []) = error \"You suck\"\n\n\n-- Shit\nmain :: IO ()\nmain = do\n [_,a,b] <- readShit\n s <- readShit\n printShit $ solve (a - 1) (b - 1) s\n\nclass Shit a where\n printShit :: a -> IO ()\n printShitV :: a -> IO ()\n readShit :: IO a\n printShitV = printShit\n\nyN :: Bool -> String\nyN True = \"YES\"\nyN False = \"NO\"\n\niif :: Bool -> x -> x -> x\niif True a _ = a\niif _ _ b = b\n\ninstance Shit Int where\n printShit = print\n readShit = fmap read getLine\n\ninstance Shit [Int] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\n\ninstance Shit [Integer] where\n printShit = putStrLn . unwords . fmap show\n printShitV = putStrLn . unlines . fmap show\n readShit = fmap (fmap read . words) getLine\n\ninstance Shit [[Int]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec .toInteger)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit [[Double]] where\n printShit = printShit . (fmap.fmap) show\n readShit = fmap (fmap.fmap $ read) readShit\n\ninstance Shit [[Integer]] where\n printShit = printShit . (fmap.fmap) (toLazyByteString . integerDec)\n readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit\n\ninstance Shit String where\n printShit = putStrLn\n printShitV = putStrLn\n readShit = getLine\n\ninstance Shit [String] where\n printShit = putStrLn. unwords\n printShitV = putStrLn . unlines\n readShit = fmap lines getContents\n\ninstance Shit [[String]] where\n printShit = putStrLn . unlines . fmap unwords\n readShit = fmap (fmap (fmap words) lines) getContents\n\ninstance Shit [BS.ByteString] where\n printShit = BS.putStrLn. BS.unwords\n printShitV = BS.putStrLn . BS.unlines\n readShit = fmap BS.lines BS.getContents\n\ninstance Shit [[BS.ByteString]] where\n printShit = BS.putStrLn . BS.unlines . fmap BS.unwords\n readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents"}], "src_uid": "081f30ac27739002855e9d2aebe804c7"} {"source_code": "\nsolve xs = solve' xs []\n where solve' [] ans = ans\n solve' ('x':'y':xs) ans = solve' xs ans\n solve' ('y':'x':xs) ans = solve' xs ans\n solve' (x:xs) [] = solve' xs [x]\n solve' (x:xs) (y:ys) \n | x == y = solve' xs (x:y:ys)\n | otherwise = solve' xs ys\n\nmain = do xs <- getLine\n putStrLn $ solve xs", "positive_code": [{"source_code": "-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html\n\nimport Data.List\n\ngetAns :: Int -> Char -> String\ngetAns 0 _ = []\ngetAns n c = c : getAns (n - 1) c\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet xlen = length (filter (== 'x') str)\n\tlet ylen = length (filter (== 'y') str)\n\tif (xlen > ylen)\n\t\tthen putStrLn (getAns (xlen - ylen) 'x')\n\t\telse putStrLn (getAns (ylen - xlen) 'y')\n"}, {"source_code": "solve l = replicate x 'x' ++ replicate (-x) 'y'\n where x = length (filter (=='x') l) - length (filter (=='y') l) \n\nmain = interact $ solve "}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Word\n\n\nmain :: IO ()\nmain = do l <- B.getLine\n B.putStrLn $ solve l\n\nsolve :: B.ByteString -> B.ByteString\nsolve l = mkStr (B.count 'x' l,B.count 'y' l) \n\n\nmkStr (x,y) \n | x > y = B.replicate (x-y) 'x'\n | otherwise = B.replicate (y-x) 'y'\n"}, {"source_code": "import Data.List\nmain = do\n str <- getLine\n let (x, y) = partition (\\c -> c == 'x') str\n delta = (length x) - (length y)\n putStrLn $ sq $ show (if (delta > 0) \n then take delta x \n else take (abs delta) y )\n\nsq :: String -> String\nsq s@[c] = s\nsq ('\"':s) | last s == '\"' = init s\n | otherwise = s\nsq ('\\'':s) | last s == '\\'' = init s\n | otherwise = s\nsq s = s\n"}, {"source_code": "\nsolve :: String -> String\nsolve s\n | x <= y = replicate (y-x) 'y'\n | otherwise = replicate (x-y) 'x'\n where\n x = length $ filter (== 'x') s\n y = length $ filter (== 'y') s\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n"}, {"source_code": "\nsolve xs = solve' xs []\n where solve' [] ans = reverse ans\n solve' ('x':'y':xs) ans = solve' xs ans\n solve' ('y':'x':xs) ans = solve' xs ans\n solve' (x:xs) [] = solve' xs [x]\n solve' (x:xs) (y:ys) \n | x == y = solve' xs (x:y:ys)\n | otherwise = solve' xs ys\n\nmain = do xs <- getLine\n putStrLn $ solve xs"}, {"source_code": "module Main where\n\ncountDiff :: String -> Int\ncountDiff s = countDiff' s 0\n where\n countDiff' \"\" d = d\n countDiff' ('x':s) d = countDiff' s (d+1)\n countDiff' ('y':s) d = countDiff' s (d-1)\n\nsolve :: String -> String\nsolve s = if d > 0\n then replicate d 'x'\n else replicate (-d) 'y'\n where\n d = countDiff s\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "module Main where\n\ncountDiff :: String -> Int\ncountDiff s = countDiff' s 0\n where\n countDiff' \"\" d = d\n countDiff' ('x':s) d = countDiff' s (d+1)\n countDiff' ('y':s) d = countDiff' s (d-1)\n\nsolve :: String -> String\nsolve s = if d > 0\n then replicate d 'x'\n else replicate (-d) 'y'\n where\n d = countDiff s\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nmain = B.getLine >>= B.putStrLn .solve\n\nsolve bs\n | cntx < cnty = B.replicate (cnty-cntx) 'y'\n | otherwise = B.replicate (cntx-cnty) 'x'\n where\n cntx = B.count 'x' bs\n cnty = B.count 'y' bs\n"}, {"source_code": "#!/usr/bin/env runghc\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (s:ss) = f 0 'x' s\n where\n f 0 a (c:cs) = f 1 c cs\n f n a [] = replicate n a\n f n a (c:cs) = if c == a then f (n+1) a cs else f (n-1) a cs\n"}, {"source_code": "module Main where\n\ncountDiff :: String -> Int\ncountDiff s = countDiff' s 0\n where\n countDiff' \"\" d = d\n countDiff' ('x':s) d = countDiff' s (d+1)\n countDiff' ('y':s) d = countDiff' s (d-1)\n\nsolve :: String -> String\nsolve s = if d > 0\n then replicate d 'x'\n else replicate (-d) 'y'\n where\n d = countDiff s\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "main :: IO()\nmain = do\n l <- getLine\n putStrLn $ func l\n \nfunc :: String -> String\nfunc l = replicate nc ch\n where\n (nc,ch)=df ( map f ['x','y'])\n f c = length [ x | x <- l, x == c]\n df [nx,ny] \n | nx > ny = ((nx-ny),'x')\n | otherwise = ((ny-nx),'y')"}, {"source_code": "module Main where\n\ncountDiff :: String -> Int\ncountDiff s = countDiff' s 0\n where\n countDiff' \"\" d = d\n countDiff' ('x':s) d = countDiff' s (d+1)\n countDiff' ('y':s) d = countDiff' s (d-1)\n\nsolve :: String -> String\nsolve s = if d > 0\n then replicate d 'x'\n else replicate (-d) 'y'\n where\n d = countDiff s\n\nmain = getLine >>= (putStrLn . solve)"}, {"source_code": "import Data.List\nmain = interact $ f. map length . group . sort . (++ \"xy\") where\n f (_:x:y:_)\n | x < y = replicate (y - x) 'y'\n | otherwise = replicate (x - y) 'x'"}], "negative_code": [{"source_code": "reduce [] = []\nreduce ('y':'x':rest) = reduce rest\nreduce ('x':'y':rest) = reduce rest\nreduce (x:xs) = x:reduce xs\n\nsolve xs = iterate reduce xs !! 250\n\nmain = interact solve"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\n\nsolve xs = solve' xs []\n where solve' [] ans = ans\n solve' ('x':'y':xs) ans = solve' xs ans\n solve' ('y':'x':xs) ans = solve' xs ans\n solve' (x:xs) [] = solve' xs [x]\n solve' (x:xs) (y:ys) \n | x == y = solve' xs (x:y:ys)\n | otherwise = solve' xs ys\n\nmain = do xs <- fmap BS.unpack BS.getLine\n putStrLn $ solve xs"}, {"source_code": "solve [] = []\nsolve ('y':'x':rest) = solve rest\nsolve ('x':'y':rest) = solve rest\nsolve (x:xs) = x:solve xs\n\nmain = interact solve"}, {"source_code": "\nsolve xs = solve' xs []\n where solve' [] ans = reverse ans\n solve' ('x':'y':xs) ans = solve' xs ans\n solve' ('y':'x':xs) ans = solve' xs ans\n solve' (x:xs) [] = solve' xs [x]\n solve' (x:xs) (y:ys) \n | x == y = solve' xs (x:y:ys)\n | otherwise = solve' xs ys\n\nmain = interact solve"}, {"source_code": "#!/usr/bin/env runghc\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (s:ss) = f s\n where\n f (a:b:cs) = if a /= b then f cs else a:b:f cs\n f cs = cs\n"}], "src_uid": "528459e7624f90372cb2c3a915529a23"} {"source_code": "solve [a,b,c] = s a b c 1\n where \n s a b c x | even a && even b = s (a `div` 2) (b`div`2) c (x*2*2) \n | even a && odd b = s (a `div` 2) b c (x*2)\n | odd a && even b = s a (b`div`2) c (x*2)\n | odd a && odd b = if x >= c then \"YES\" else \"NO\"\n \n \n\n\nmain = interact $ unlines . map ( solve . map (read :: String -> Int) . words) . tail . lines", "positive_code": [{"source_code": "solve [a,b,c] = s a b c 1\n where s a b c x | even a && even b = s (a `div` 2) (b`div`2) c (x*2*2) \n | even a && odd b = s (a `div` 2) b c (x*2)\n | odd a && even b = s a (b`div`2) c (x*2)\n | odd a && odd b = if x >= c then \"YES\" else \"NO\"\nmain = interact $ unlines . map ( solve . map (read :: String -> Int) . words) . tail . lines"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nreadInt :: IO Integer\nreadInt = readLn\n\nkp2 :: Integer -> Integer\nkp2 n\n | n `mod` 2 == 0 = 2 * kp2 (n `div` 2)\n | otherwise = 1\n\nsolve :: [Integer] -> String\nsolve [w, h, n]\n | kp2 w * kp2 h >= n = \"YES\"\n | otherwise = \"NO\"\n\nsolveCase :: IO String\nsolveCase = fmap solve readInts\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}, {"source_code": "main = interact $ unlines . map (ans . map read . words) . tail . lines\r\n\r\nans [w,h,n]\r\n | solve (w * h) >= n = \"YES\"\r\n | otherwise = \"No\"\r\n\r\nsolve = product . (2 <$) . takeWhile even . iterate (`div` 2)"}, {"source_code": "main = interact $ unlines . map (solve . map read . words) . tail . lines\r\n\r\nsolve [w,h,n]\r\n | 2 ^ (f w + f h) >= n = \"YES\"\r\n | otherwise = \"NO\"\r\n\r\nf x\r\n | even x = 1 + f (div x 2)\r\n | otherwise = 0"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\n \r\nimport safe Control.Arrow ((>>>))\r\nimport qualified Data.Text as T\r\nimport qualified Data.Text.IO as TI\r\nimport Data.List\r\nimport Data.Function\r\nimport Data.Maybe\r\n\r\nmain :: IO ()\r\nmain = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where\r\n tcio :: [T.Text] -> [String]\r\n tcio [] = []\r\n tcio (nm : rest) = ((:[]). solve . linetois) nm ++ tcio (drop 0 rest) \r\n linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois\r\n --itoline = show; istoline = unwords . (map itoline); isstolines = map istoline\r\n toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;\r\n\r\nsolve :: [Int] -> String\r\nsolve [w,h,n] = if mx2pow w * mx2pow h >=n then \"YES\" else \"NO\" where\r\n mx2pow x = last $ takeWhile (\\p->x `mod` p == 0) [2^k | k<-[0..]]\r\n"}, {"source_code": "import qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.Array.ST(runSTArray, STArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\nnumOcc :: Ord a => [a] -> M.Map a Integer\r\nnumOcc (x:xs) = let m = numOcc xs in case M.lookup x m of \r\n\tJust i -> M.insert x (i+1) m \r\n\tNothing -> M.insert x 1 m \r\nnumOcc [] = M.empty\r\n\r\n\r\nnumOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer\r\nnumOcc' size list = runSTArray $ do \r\n\tarray <- MA.newArray size 0\r\n\tfoldM (addElem array) () list\r\n\treturn array \r\n\r\n\twhere\r\n\t\taddElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()\r\n\t\taddElem array action a = do\r\n\t\t\ti <- MA.readArray array a\r\n\t\t\tMA.writeArray array a (i+1) \r\n\t\r\n\r\n\r\ninsertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]\r\ninsertWithList a b m = case M.lookup a m of \r\n\tJust l -> M.insert a (b:l) m \r\n\tNothing -> M.insert a [b] m \r\n\r\ndeleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]\r\ndeleteWithList a m = case M.lookup a m of \r\n\tJust (x:y:xs) -> M.insert a (y:xs) m\r\n\tJust [x] -> M.delete a m\r\n\r\nsolve :: Integer -> Integer -> Integer -> Bool\r\n\r\nsolve w h n = (1 + aux w) * (1 + aux h) >= n where\r\n\taux k\r\n\t\t| mod k 2 == 0 = 1 + 2 * aux (div k 2)\r\n\t\t| otherwise = 0\r\n\r\n\r\n\r\n\r\nplotResult True = putStrLn \"Yes\"\r\nplotResult False = putStrLn \"No\"\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Integer\r\n\treplicateM (fromInteger t) $ do\r\n\t\t[w, h, n] <- fmap ((fmap read) . words) getLine :: IO [Integer]\r\n\t\tplotResult $ solve w h n\r\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Control.Applicative\nimport System.IO\nimport Data.Bits\n\n-- import qualified Data.Set as Set\n\nreadInt :: String -> Int\nreadInt = read\n\nprintArr :: (Show a) => String -> [a] -> IO ()\nprintArr sep arr = do\n putStrLn . intercalate sep $ (show <$> arr)\n\nprint2DArr :: (Show a) => String -> [[a]] -> IO ()\nprint2DArr sep arr = sequence_ (printArr sep <$> arr)\n\nevery n xs = case drop (n-1) xs of\n (y:ys) -> y : every n ys\n [] -> []\n\nyon True = \"YES\"\nyon False = \"NO\"\n\nmain = do\n -- input <- openFile \"in\" ReadMode\n let input = stdin\n hSetBuffering input (BlockBuffering (Just 4096))\n hSetBuffering stdout (BlockBuffering (Just 4096))\n contents <- hGetContents input\n -- printArr (readIntArr $ head q) \" \"\n solve contents\n\nsolve inp = sequence do\n [x, y, n] <- (readInt <$>) . words <$> tail (lines inp)\n let x' = 1 `shift` countTrailingZeros x\n y' = 1 `shift` countTrailingZeros y\n [putStrLn $ yon (x'*y' >= n)]"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n [w, h, n] <- getIntList\n putStrLn $ yesOrNo $ (n <= (f w * f h))\n\nf :: Int -> Int\nf x | odd x = 1\n | otherwise = 2 * f (x `div` 2)"}, {"source_code": "count :: Int -> Int\ncount x | x `mod` 2 == 0 = 1 + count ( x `div` 2)\n | otherwise = 0\n\nfn :: [Int] -> String\nfn x | (2^(count (x!!0)))*(2^(count (x!!1))) >= (x!!2) = \"Yes\"\n | otherwise = \"No\"\n\nfunc::[Int] -> [[Int]]\nfunc [] = []\nfunc x = [take 3 x] ++ func (drop 3 x)\nout::[[Int]] -> [String]\nout x = [fn y | y <- x] \nparsei::String -> [Int]\nparsei x = [read k :: Int | k <- tail(words x)]\n\nparseo::[String] -> String\nparseo x = concat ([k ++ \"\\n\" | k <- x])\ntotalfun::String -> String\ntotalfun x = parseo(out(func(parsei(x))))\n\nmain = interact $ totalfun\n"}, {"source_code": "import Control.Arrow\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines\n\nsolve :: [Int] -> String\nsolve [w, h, n]\n | ((two (w*h)) >= n) = \"YES\"\n | otherwise = \"NO\"\n\ntwo :: Int -> Int\ntwo x\n | (mod x 2 == 0) = 2 * two (div x 2)\n | otherwise = 1"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n join, replicateM_)\r\nimport qualified Control.Monad.State.Strict as S\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, isPrefixOf, nub,\r\n sort, sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: Int -> Int -> Int -> Bool\r\nsolve w h n = cntTwo w h >= n\r\n where\r\n cntTwo w h\r\n | even w = 2 * cntTwo (w `div` 2) h\r\n | even h = 2 * cntTwo w (h `div` 2)\r\n | otherwise = 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [w, h, n] <- B8.getLine <&> map readIntB8 . B8.words\r\n let answer = solve w h n\r\n printf \"%s\\n\" ((if answer then \"YES\" else \"NO\")::String)\r\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\nimport Data.Function\n-- import Data.List.HT ( mapAdjacent\n-- , isAscending\n-- )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport qualified Data.Set as S\n-- import qualified Data.Vector.Algorithms.Radix as VA\n-- import Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nboth2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n [w, h, n] <- getIntegers\n let\n f = toInteger . length . takeWhile ((== 0) . (`mod` 2)) . iterate\n (`div` 2)\n ww = f w\n hh = f h\n putStrLn if 2 ^ (ww + hh) >= n then \"Yes\" else \"No\"\n"}, {"source_code": "import Control.Monad\n\ncont :: Int -> Int\ncont = go 1 where\n go x y\n | odd y = x\n | otherwise = go (2*x) (div y 2)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [w, h, n] <- map read . words <$> getLine :: IO [Int]\n putStrLn $ if cont w * cont h >= n\n then \"YES\"\n else \"NO\"\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nreadInt :: IO Integer\nreadInt = readLn\n\nkp2 :: Integer -> Integer\nkp2 n\n | n `mod` 2 == 0 = 1 + kp2 (n `div` 2)\n | otherwise = 1\n\nsolve :: [Integer] -> String\nsolve [w, h, n]\n | kp2 w * kp2 h >= n = \"YES\"\n | otherwise = \"NO\"\n\nsolveCase :: IO String\nsolveCase = fmap solve readInts\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}], "src_uid": "a8201326dda46542b23dc4e528d413eb"} {"source_code": "module Main where\n\nimport Data.List (sort, maximum)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumbers :: IO [Int]\nreadNumbers =\n (fromJust\n . fmap (map fst)\n . sequence\n . map BS.readInt\n . BS.words) `fmap` BS.getLine\n\nchunks0 _ [] = []\nchunks0 n as = (take n as) : chunks0 n (drop n as)\n\nchunks n = filter ((== n) . length) . chunks0 n\n\ngetTeamCount k n participants\n | n < 3 = 0\n | otherwise =\n length\n $ filter (<= 5)\n $ map ((+ k) . maximum)\n $ chunks 3 participants\n\nmain :: IO ()\nmain = do\n (n:k:_) <- readNumbers\n participants <- take n `fmap` readNumbers\n print (getTeamCount k n (sort participants))\n", "positive_code": [{"source_code": "\nsolve :: String -> String\nsolve s = show $ quot cnt 3\n where (x:y:xs) = map read (words s)\n cnt = length (filter (\\x -> 5 - y >= x) xs)\n\nmain = do\n interact solve\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nmain :: IO ()\nmain = do\n\t[_,k] <- inputInts\n\txs <- inputInts\n\tprint . (`div` 3) . length . filter (<= 5 - k) $ xs\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\n-- For Input\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n--import qualified Data.ByteString.Lex.Double as BSD\nimport Data.Char (isSpace)\nimport Data.IORef\nimport Text.Printf\n\n-- Data Structure Imports\nimport Data.Maybe\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\n-- These should be imported by default... :)\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\n--------------------------------------------------------------------------------\n------------------------------- SOLUTION ---------------------------------------\n--------------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do \n all <- BS.getContents\n input <- newIORef all\n let parse = next input \n (n,k) <- parse int2\n ys <- parse $ intMany n\n let solution = length (filter (\\y -> y + k <= 5) ys) `div` 3\n putStrLn $ show solution\n\n--------------------------------------------------------------------------------\n-------------------------- IO Function Helpers ---------------------------------\n--------------------------------------------------------------------------------\n\ntype Parser a = BSC.ByteString -> (a, BSC.ByteString)\n\nint :: Parser Int\nint = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt\n\nint2 :: Parser (Int, Int)\nint2 = uncurry (first . (,)) . second int . int\n\nint3 :: Parser (Int, Int, Int)\nint3 = uncurry (first . (uncurry (,,))) . second int . int2\n\n--double :: Parser Double\n--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble\n\nchar :: Parser Char\nchar = BSC.head &&& BSC.tail\n\nletter :: Parser Char\nletter = second (BSC.dropWhile isSpace) . char \n\nstring :: Parser String\nstring = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)\n\nreadMany :: Parser a -> Int -> Parser [a]\nreadMany f n bs = first reverse $ \n foldr (\\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]\n\nintMany :: Int -> Parser [Int]\nintMany = readMany int\n\nnext :: IORef BSC.ByteString -> Parser a -> IO a\nnext input parse = do\n bs <- readIORef input\n let (x, bs') = parse bs\n writeIORef input bs'\n return x\n\n{- CODE JAM input\n\n cases <- parse int\n forM_ [1..cases] $ \\caseNum -> do\n -- Read Data \n -- let solution = \n -- solution <- \n printf \"Case #%d: %d\\n\" caseNum solution\n-}\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n \nmain= do\n\t[_,k]<- map read. words <$> getLine ::IO [Int]\n\ts<- sort.map read.words <$> getLine::IO [Int]\n print $ div (length (takeWhile (<=5-k) s)) 3\n\t "}, {"source_code": "import Data.List\nmain = do\n [n, k] <- getLine >>= return. map read. words :: IO [Int]\n a <- getLine >>= return. filter (< (6 - k)). map read. words :: IO [Int]\n print. (`div` 3). length $ a"}, {"source_code": "import Control.Applicative\n\nmain = do\n [n, k] <- map read . words <$> getLine\n ys <- map read . words <$> getLine\n print $ (length $ filter (<= (5-k)) ys) `div` 3\n"}, {"source_code": "process :: Int -> [Int] -> Int\nprocess k xs = length (filter (\\x -> x+k<=5) xs) `div` 3\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n,k] <- fmap (map readInt.words) getLine\n ys <- fmap (map readInt.words) getLine\n print $ process k ys"}, {"source_code": "main = do\n [n,k] <- fmap (map read . words) getLine :: IO [Int]\n y <- fmap (map read . words) getLine :: IO [Int]\n print $ (length $ filter (<= 5 - k) y) `div` 3"}, {"source_code": "main = do\n let i=fmap (map read.words) getLine::IO [Int]\n [n,k]<-i\n y<-i\n print $ (length $ filter (<6-k) y) `div` 3"}, {"source_code": "main = getContents >>= print . solve . (map read) . words\n\nsolve :: [Int] -> Int\nsolve (_:k:xs) = flip div 3 $ length $ filter (5-k >= ) xs \n"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain=interact solve\n\nsolve :: String -> String\nsolve s = show $ answer k xs\n where (_:k:xs) = read<$>words s\n\nanswer :: Int -> [Int] -> Int\nanswer k xs = quot (sum [1 | i <- xs, k + i <= 5]) 3"}, {"source_code": "import Control.Monad\n\nreadListLn :: IO [Int]\nreadListLn = (map (read :: String -> Int) . words) `liftM` getLine\n\nmain :: IO ()\nmain = do\n [_, k] <- readListLn\n y <- readListLn\n putStr $ show $ length (filter (<=5-k) y) `div` 3\n\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:k:xs) = let ns = (length . filter (<=5) . map (+k)) xs\n\t\t\t\tin ns `div` 3\n"}, {"source_code": "main = do\n [_, k] <- fmap (map read . words) getLine\n ys <- fmap (map read . words) getLine\n\n let c = length $ filter (\\x -> x + k <= 5) ys\n print $ c `div` 3\n"}, {"source_code": "\nmain = do\n (n:k:_) <- fmap (map read . words) getLine :: IO [Int]\n nums <- fmap (map read . words) getLine\n let answer = length (filter (\\a -> k+a <= 5) nums) `div` 3\n print answer\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative ((<$>))\nimport Text.Printf\nimport Data.Maybe (Maybe, fromMaybe)\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n [n, k] <- readInts\n y <- readInts\n print . (`div` 3) . length . filter (<= 5 - k) $ y\n\ntoNumber = fst . fromMaybe (0, \"\")\nreadInt = toNumber . BS.readInt <$> BS.getLine\nreadInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = solve.tail.concat =<< (forM [1..2] $ \\i-> map (fst.fromJust.C.readInt).C.words <$> C.getLine)\n\nsolve (x:xs) = let l = length $ filter (\\a->a+x<=5) xs in print $ l `div` 3"}, {"source_code": "import Control.Applicative\nimport Data.List (sort)\n\nmain = do\n [_, k] <- map read . words <$> getLine\n ss <- sort . map read . words <$> getLine\n let\n f xs\n | length xs < 3 = 0\n | all (<=5) . map (+k) $ take 3 xs = 1 + f (drop 3 xs)\n | otherwise = 0\n in putStrLn . show $ f ss"}, {"source_code": "import Data.List\n\nconv = map (read::String->Int) . words\ng k xs = div ((length . sort) [x | x <- xs , 5 - x >= k]) 3\n\nmain = do\n i <- getLine\n x <- getLine\n let k = (conv i) !! 1\n let xs = conv x\n putStrLn $ show (g k xs)\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\n\nmain=do\n [n,k]<- map read <$> words <$> getLine::IO [Int]\n q<-map read <$> words <$> getLine::IO [Int]\n print $ div ( length $ filter (<=5-k) q) 3\n"}, {"source_code": "main=getContents>>=print.solve.map read.words\nsolve(_:k:ys)=length(filter(<=5-k)ys)`div`3\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (_:k:ys) = length (filter (<=5-k) ys) `div` 3\nsolve _ = undefined\n"}, {"source_code": "main = interact $ show . solve . map read . words\nsolve (n:k:ns) = (`div` 3) $ length $ filter (<= 5 - k) ns\n"}, {"source_code": "import Data.List\n\nstrToList = (fmap (read :: (String -> Int))).words\n\nf xs k = (length $ filter (<=5) $ map (+k) xs) `div` 3\n\nmain = do\n\n [n, k] <- fmap strToList getLine\n\n s <- fmap strToList getLine\n\n putStrLn $ show $ f s k"}, {"source_code": "import Text.Printf (printf)\nimport Control.Monad (forM_)\n\nmain :: IO ()\nmain = do\n [n, k] <- fmap (map read . words) getLine :: IO [Int]\n xs <- fmap (map read . words) getLine :: IO [Int]\n print $ length (filter (\\x -> x + k <= 5) xs) `div` 3\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\n\n\n\nmain=do\n [n,k]<- map read <$> words <$> getLine::IO [Int]\n q<-map read <$> words <$> getLine::IO [Int]\n print $ div ( length $ takeWhile (>=5-k) q) 3\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\n\nmain=do\n [n,k]<- map read <$> words <$> getLine::IO [Int]\n q<-map read <$> words <$> getLine::IO [Int]\n print $ div ( length $ takeWhile (<=5-k) q) 3\n"}, {"source_code": "import Data.List\nmain = do\n [n, k] <- getLine >>= return. map read. words :: IO [Int]\n a <- getLine >>= return. filter (< (4 - k)). map read. words :: IO [Int]\n print. (`div` 3). length $ a\n"}], "src_uid": "fbde1e2ee02055592ff72fb04366812b"} {"source_code": "import Control.Monad\r\n\r\nans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n mInput <- getLine\r\n bInput <- getLine\r\n let n = read nInput :: Int\r\n let a = words aInput\r\n let m = read mInput :: Int\r\n let b = words bInput\r\n let pos = 1 + sum [read x :: Int | x <- b] `mod` n\r\n let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)\r\n return result\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- replicateM t (do ans)\r\n putStrLn (unwords results)", "positive_code": [{"source_code": "ans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n mInput <- getLine\r\n bInput <- getLine\r\n let n = read nInput :: Int\r\n let a = words aInput\r\n let m = read mInput :: Int\r\n let b = words bInput\r\n let pos = 1 + sum [read x :: Int | x <- b] `mod` n\r\n let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)\r\n return result\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n results <- sequence (replicate t ans)\r\n putStrLn (unwords results)"}, {"source_code": "ans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n mInput <- getLine\r\n bInput <- getLine\r\n let n = read nInput :: Int\r\n let a = words aInput\r\n let m = read mInput :: Int\r\n let b = words bInput\r\n let pos = 1 + sum (map (\\x -> read x :: Int) b) `mod` n\r\n let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)\r\n putStrLn result\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n let results = replicate t ans\r\n sequence results"}, {"source_code": "ans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n mInput <- getLine\r\n bInput <- getLine\r\n let n = read nInput :: Int\r\n let a = words aInput\r\n let m = read mInput :: Int\r\n let b = words bInput\r\n let pos = 1 + sum [read x :: Int | x <- b] `mod` n\r\n let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)\r\n putStrLn result\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n let results = replicate t ans\r\n sequence results"}, {"source_code": "ans = do\r\n nInput <- getLine\r\n aInput <- getLine\r\n mInput <- getLine\r\n bInput <- getLine\r\n let n = read nInput :: Int\r\n let a = words aInput\r\n let m = read mInput :: Int\r\n let b = words bInput\r\n let pos = 1 + sum [read x :: Int | x <- b] `mod` n\r\n let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)\r\n putStrLn result\r\n\r\nmain = do\r\n tInput <- getLine\r\n let t = read tInput :: Int\r\n let results = [ans | x <- [1 .. t]]\r\n sequence results"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (Applicative (liftA2))\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Maybe (fromJust)\r\nimport Data.Word (Word32)\r\nimport GHC.Conc (par, pseq)\r\nimport System.Environment (getArgs)\r\n\r\ndata TC = TC {n :: Int, m :: Int, a :: [Int], b :: [Int]}\r\n\r\naliceBob x = if x then \"Alice\" else \"Bob\"\r\n\r\nsolve TC {..} = a!!p\r\n where\r\n p = (sum b) `mod` n\r\n\r\nmain = C.interact $ runScanner scan >>> map solve >>> map show >>> map C.pack >>> C.unlines\r\n\r\nscan =\r\n numberOf $\r\n ( do\r\n n <- int\r\n a <- n >< int\r\n m <- int\r\n b <- m >< int\r\n pure $ TC n m a b\r\n )\r\n\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [], "src_uid": "c9da10199ad1a5358195b693325e628b"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,x,y] <- ri\r\n return (n,x,y)\r\n mapM_ (putStrLn.showAns.solve) tcs\r\n\r\nshowAns Nothing = \"-1\"\r\nshowAns (Just xs) = unwords . map show $ xs\r\n\r\nsolve (_,0,0) = Nothing\r\nsolve (n,0,y) = solve (n,y,0)\r\nsolve (n,x,0) | (n-1) `mod` x /= 0 = Nothing\r\n | otherwise = Just ans\r\n where\r\n np = (n-1) `div` x\r\n winners = take np $ 1 : [x+2, 2*x+2 ..]\r\n ans = concatMap (replicate x) $ winners\r\nsolve _ = Nothing\r\n", "positive_code": [{"source_code": "import Data.Array\nimport Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = map read . words <$> getLine >>=\n \\[n, x, y] -> case matchOf n x y of\n Nothing -> putStrLn \"-1\"\n Just as -> mapM_ (\\a -> putStr (show a ++ \" \")) as >>\n putStrLn \"\"\n\nmatchOf :: Int -> Int -> Int -> Maybe [Int]\nmatchOf n x y | (x /= 0 && y /= 0) || (x == 0 && y == 0) = Nothing\n | otherwise = let k = if x == 0 then y else x in\n if (mod (n-1) k) == 0\n then Just $ concatMap (replicate k) [2+k*i | i <- [0..(div (n-1) k)-1]]\n else Nothing\n"}, {"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n-- {-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\nsolve :: Int -> Int -> Int -> Maybe [Int]\nsolve n x y | x > y = solve n y x\nsolve n 0 0 = Nothing\nsolve n 0 y | (n - 1) `mod` y == 0 = Just $ L.concatMap (L.replicate y) . L.take ((n - 1) `div` y) $ iterate (+ y) 2\nsolve n _ _ = Nothing\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n [n, x, y] <- B8.getLine <&> readIntegerB8s <&> map fromIntegral\n let answer = solve n x y\n case answer of\n Just results -> M.forM_ results (printf \"%d \") >> printf \"\\n\"\n Nothing -> printf \"-1\\n\"\n"}], "negative_code": [{"source_code": "{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections #-}\n-- {-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n#ifndef DEBUG\n{-# LANGUAGE Safe #-}\n#endif\n\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.String as S\n\nimport Control.Arrow ((>>>))\nimport Data.Functor ((<&>))\nimport Data.Maybe\nimport qualified Data.Traversable as T\n\nimport qualified Control.Applicative as A\nimport qualified Control.Monad as M\nimport qualified Control.Monad.State as MS\nimport qualified Control.Monad.Trans as MT\nimport qualified Control.Monad.Trans.Maybe as M\n\nimport qualified Data.List as L\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport qualified Data.IntSet as IS\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport Data.List (sortBy, sortOn)\n\nimport Data.Char\nimport Data.Int\n\nimport System.IO (stdin, stdout, hFlush)\nimport Text.Printf\n\n#ifdef DEBUG\nimport Debug.Trace (trace, traceM, traceShowM)\ndebug = flip trace\n\ntracing t x = trace (t ++ \" = \" ++ show x) x\ndebugging x t = tracing t x\n\ntracingM t x = traceM $ t ++ \" = \" ++ show x\n\n#else\n\ndebug x _ = x\ntrace _ x = x\ntracing _ x = x\ndebugging x _ = x\n\ntraceM _ = pure ()\ntracingM _ _ = pure ()\n#endif\n\n\n{- reading -}\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\n{- writing -}\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- aux -}\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n{- solution -}\n\nsolve :: Int -> Int -> Int -> Maybe [Int]\nsolve n x y | x > y = solve n y x\nsolve n 0 0 = Nothing\nsolve n 0 y | (n - 1) `mod` y == 0 = Just $ L.concatMap (L.replicate y) . L.take ((n - 1) `div` y) $ iterate (+ (y + 1)) 1\nsolve n _ _ = Nothing\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n M.replicateM_ t $ do\n [n, x, y] <- B8.getLine <&> readIntegerB8s <&> map fromIntegral\n let answer = solve n x y\n case answer of\n Just results -> M.forM_ results (printf \"%d \") >> printf \"\\n\"\n Nothing -> printf \"-1\\n\"\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,x,y] <- ri\r\n return (n,x,y)\r\n mapM_ (putStrLn.showAns.solve) tcs\r\n\r\nshowAns Nothing = \"-1\"\r\nshowAns (Just xs) = unwords . map show $ xs\r\n\r\nsolve (_,0,0) = Nothing\r\nsolve (n,0,y) = solve (n,y,0)\r\nsolve (n,x,0) | (n-1) `mod` x /= 0 = Nothing\r\n | otherwise = Just ans\r\n where\r\n np = (n-1) `div` x\r\n winners = take np [1, 1+x+1 ..]\r\n ans = concatMap (replicate x) $ winners\r\nsolve _ = Nothing\r\n"}], "src_uid": "024d7b1d5f7401080560174003456037"} {"source_code": "g (x:y:[]) = [(x, y)]\ng (x:y:s) = (x, y) : g s\nf 0 _ _ = 0\nf n as bs\n | (null bs) || (not (null as)) && ((head as) < (head bs)) = 1 + f (n - 1) (tail as) bs\n | otherwise = f(n - 1) as (tail bs)\nmain = do\n all <- getContents\n let ns = map read $ words all :: [Int]\n let n = head ns\n let (as, bs) = unzip $ g $ tail ns\n let k = f n as bs\n putStrLn $ [if x <= (max k (div n 2)) then '1' else '0' | x <- [1..n]]\n putStrLn $ [if x <= (max (n - k) (div n 2)) then '1' else '0' | x <- [1..n]]\n ", "positive_code": [{"source_code": "g (x:y:[]) = [(x, y)]\ng (x:y:s) = (x, y) : g s\nf 0 _ _ = (0, 0)\nf n [] (b:bs) = (p, q + 1) where (p, q) = f (n - 1) [] bs\nf n (a:as) [] = (p + 1, q) where (p, q) = f (n - 1) as []\nf n (a:as) (b:bs)\n | a < b = let (p, q) = f (n - 1) as (b:bs) in (p + 1, q)\n | otherwise = (r, s + 1) where (r, s) = f(n - 1) (a:as) bs\nmain = do\n all <- getContents\n let ns = map read $ words all :: [Int]\n let n = head ns\n let (as, bs) = unzip $ g $ tail ns\n let (an, bn) = f n as bs\n let (man, mbn) = (max an (div n 2), max bn (div n 2))\n putStrLn $ (replicate man '1') ++ (replicate (n - man) '0')\n putStrLn $ (replicate mbn '1') ++ (replicate (n - mbn) '0')\n "}], "negative_code": [], "src_uid": "bea30e4ba653b9d0af87fc79b9ec8b4f"} {"source_code": "{-# LANGUAGE\n ScopedTypeVariables,\n BangPatterns,\n FlexibleContexts,\n TypeApplications,\n MultiWayIf #-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Array.IO\n\nmain = do\n [!t] <- readInts\n replicateM_ t solve\n\nsolve = do\n [!n, !c, !q] <- readInts\n s <- listArray @UArray (0,n-1) <$> getLine\n cs <- replicateM c $ do\n [!l, !r] <- readInts\n return (l,r)\n qs <- replicateM q (head <$> readInts)\n let go _ [] = []\n go !ind ((l,r):xs) = (ind,l-1,r-1) : go (ind+r-l+1) xs\n cs' = reverse $ go n cs\n find [] i = i\n find ((ind,l,r):xs) i\n | i >= ind = find xs (i - ind + l)\n | otherwise = find xs i\n mapM_ (putStrLn . (:[]) . (s!) . find cs' . subtract 1) qs\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmodifyArray :: (MArray a e m , Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr i f = readArray arr i >>= writeArray arr i . f\n", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\nimport Data.Map.Strict qualified as Map\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n,c,q] <- ri\r\n s <- B.takeWhile isPrint <$> B.getLine\r\n [lrs,qs] <- mapM (`replicateM` ri) [c,q]\r\n return (s,lrs,qs)\r\n mapM_ (putStr.showChars.solve) tcs\r\n\r\nshowChars = unlines . map (:\"\")\r\n\r\nsolve (s,lrs,qs) = ans\r\n where\r\n (_,offMap) = foldl nxt (B.length s, Map.empty) . map lr2il $ lrs\r\n where\r\n lr2il = f where f [l,r] = (l, r+1-l)\r\n f _ = error \"Input error (LR pair)\"\r\n\r\n nxt (len, imap) (si,slen) = (len+slen, (len+1) `Map.insert` (len+1-si) $ imap)\r\n\r\n ans = map (B.index s . pred . v2i) qs\r\n where\r\n v2i [i] = case (Map.lookupLE i offMap) of\r\n Nothing -> i\r\n Just (_,off) -> v2i [i - off]\r\n\r\n v2i _ = error \"Input error (single index expected)\"\r\n"}], "negative_code": [], "src_uid": "8dcd95d497dee44ba72ce595b53b4e5a"} {"source_code": "doprob [] ys = 0\ndoprob xs [] = length xs\ndoprob (x:xs) (y:ys)\n | x > y = doprob (x:xs) ys\n | x == y = doprob xs ys\n | x < y = doprob xs ys\n\ntolist :: String -> [Int]\ntolist = map read . words\n\nmain = do\n _ <- getLine\n reqd <- getLine\n george <- getLine\n putStrLn $ show $ doprob (tolist reqd) (tolist george)\n", "positive_code": [{"source_code": "main = do\n nm <- getLine\n an <- getLine\n bn <- getLine\n let xs = map read (words an) :: [Int]\n ys = map read (words bn) :: [Int]\n ans = solve xs ys\n print ans\n\n\nsolve [] _ = 0\nsolve xs [] = length xs\nsolve (x:xs) (y:ys)\n | x <= y = solve xs ys\n | otherwise = solve (x:xs) ys\n \n"}, {"source_code": "main = do\n getLine\n a<-getLine\n b<-getLine\n putStr $ solve (reverse(map read (words a))) (reverse(map read (words b))) 0\nsolve::[Int]->[Int]->Int->String\nsolve [] _ acc = show acc\nsolve x [] acc = show (length x+acc)\nsolve (x:xs) (y:ys) acc\n |y>= print . (\\[[n, m], a, b] -> n - f a b) . map (map read . words) . lines\nf _ [] = 0\nf [] _ = 0\nf (a:as) (b:bs)\n | b < a = f (a:as) bs\n | otherwise = 1 + f as bs"}, {"source_code": "\nsolve :: [Int] -> [Int] -> Int\nsolve [] wants = length wants\nsolve _ [] = 0\nsolve (h:ht) ws@(w:wt)\n | h >= w = solve ht wt\n | otherwise = solve ht ws\n\n(-->) = flip fmap\n\nmain = do\n (n:m:_) <- getLine --> words --> map read\n wants <- getLine --> words --> take n --> map read\n haves <- getLine --> words --> take m --> map read\n print $ solve haves wants\n\n"}], "negative_code": [{"source_code": "main = do\n getLine\n a<-getLine\n b<-getLine\n putStr $ solve (reverse(map read (words a))) (reverse(map read (words b))) 0\nsolve::[Int]->[Int]->Int->String\nsolve [] _ acc = show acc\nsolve x [] acc = show (length x+acc)\nsolve (x:xs) (y:ys) acc\n |y= a then 0 else 1) + f as bs\n\n print $ f (reverse as) (reverse bs)\n"}, {"source_code": "import Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST.Safe\n\ngetInts = fmap (words) getLine\n\nmain = do\n [n, m] <- getInts\n as <- getInts\n bs <- getInts\n\n let\n f [] _ = 0\n f _ [] = 0\n f (a:as) (b:bs) = (if b >= a then 0 else 1) + f as bs\n\n print $ f (reverse as) (reverse bs)\n"}, {"source_code": "import Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST.Safe\n\ngetInts = fmap (words) getLine\n\nmain = do\n [n, m] <- getInts\n as <- getInts\n bs <- getInts\n\n let\n f as [] = length as\n f [] _ = 0\n f (a:as) (b:bs) = (if b >= a then 0 else 1) + f as bs\n\n print $ f (reverse as) (reverse bs)\n"}, {"source_code": "import Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST.Safe\n\ngetInts = fmap (words) getLine\n\nmain = do\n [n, m] <- getInts\n as <- getInts\n bs <- getInts\n\n print $ length $ as \\\\ bs\n\n"}, {"source_code": "main = getContents >>= print . (\\[[n, m], a, b] -> n - f a b) . map (map read . words) . lines\nf _ [] = 0\nf [] _ = 0\nf (a:as) (b:bs)\n | b < a = f (a:as) bs\n | b > a = f as (b:bs)\n | b == a = 1 + f as bs"}, {"source_code": "doprob [] ys = 0\ndoprob xs [] = length xs\ndoprob (x:xs) (y:ys)\n | x > y = 1 + doprob xs ys\n | x <= y = doprob xs ys\n\ntolist :: String -> [Int]\ntolist = map read . words\n\nmain = do\n _ <- getLine\n reqd <- getLine\n george <- getLine\n putStrLn $ show $ doprob (tolist reqd) (tolist george)\n"}], "src_uid": "bf0422de4347a308d68a52421fbad0f3"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (unpack, reverse, dropWhile)\nimport qualified Data.Map.Strict as M (adjust, insert, findMin, empty, alter, member, Map)\nimport qualified Data.List as L (sort)\nimport Data.Char (isSpace)\n\nrun [] _ [] = \"\"\nrun (t:ts) _ [] = t:run ts (M.empty) []\nrun [] mm (x:xs) = run [x] (M.alter f x mm) xs\nrun (t:ts) mm (x:xs) | t <= ms = t:run ts mm (x:xs)\n | otherwise = run (x:t:ts) (M.alter f x mm) xs where\n (ms, _) = M.findMin mm\n\nf (Just 1) = Nothing\nf (Just x) = Just (x - 1)\n\nrstrip = C.reverse . C.dropWhile isSpace . C.reverse\n\ncmap [] m = m\ncmap (x:xs) m | M.member x m = cmap xs (M.adjust succ x m)\n | otherwise = cmap xs (M.insert x 1 m)\n\nmain = do\n (C.unpack . rstrip -> xs) <- B.getLine\n putStrLn $ run [] (cmap (L.sort xs) M.empty) xs\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.IntMap as Map\nimport Data.Bits\nimport Data.Int (Int64)\nimport Data.Array\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Char\n\ndecreaseElem Nothing = Nothing\ndecreaseElem (Just x) = if x > 1 then (Just (x - 1)) else Nothing\n\nsolve [] [] u _ = u\nsolve [] (t:ts) u f = solve [] ts (t:u) f\nsolve (s:ss) [] u f = solve ss [s] u (Map.alter decreaseElem s f)\nsolve (s:ss) (t:ts) u f\n | t <= (fst $ Map.findMin f) = solve (s:ss) ts (t:u) f\n | otherwise = solve ss (s:t:ts) u (Map.alter decreaseElem s f)\n\ngetFreq [] f = f\ngetFreq (x:xs) f = getFreq xs (Map.insertWith (+) x 1 f)\n\nmain = do\n v <- (map ord) <$> getLine\n putStrLn $ map chr $ reverse $ solve v [] [] (getFreq v Map.empty)\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.IntMap as Map\nimport Data.Bits\nimport Data.Int (Int64)\nimport Data.Array\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Char\n\nsolve [] [] u _ _ _ = u\nsolve [] (t:ts) u c nc f = solve [] ts (t:u) c nc f\nsolve (s:ss) t u c nc f\n | (not.null) t && (head t) <= c = solve (s:ss) (tail t) ((head t):u) c nc f\n | s == c\n = if nc > 1\n then solve ss t (s:u) c (nc - 1) f\n else solve ss t (s:u) (c + 1) (Map.findWithDefault 0 (c + 1) f) (Map.delete c f)\n | otherwise = solve ss (s:t) u c nc (Map.insertWith (+) c (-1) f)\n\ngetFreq [] f = f\ngetFreq (x:xs) f = getFreq xs (Map.insertWith (+) x 1 f)\n\nmain = do\n v <- (map ord) <$> getLine\n let f = getFreq v Map.empty\n a = ord 'a'\n putStrLn $ map chr $ reverse $ solve v [] [] a (f Map.! a) f\n"}, {"source_code": "import Data.List\nimport qualified Data.IntMap as Map\nimport Data.Bits\nimport Data.Int (Int64)\nimport Data.Array\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Char\n\nsolve [] [] u _ _ _ = u\nsolve [] (t:ts) u c nc f = solve [] ts (t:u) c nc f\nsolve (s:ss) t u c nc f\n | (not.null) t && (head t) <= c = solve (s:ss) (tail t) ((head t):u) c nc f\n | nc == 0 = solve (s:ss) t u (c + 1) (Map.findWithDefault 0 (c + 1) f) (Map.delete c f)\n | s == c = solve ss t (s:u) c (nc - 1) f\n | otherwise = solve ss (s:t) u c nc (Map.insertWith (+) c (-1) f)\n\ngetFreq [] f = f\ngetFreq (x:xs) f = getFreq xs (Map.insertWith (+) x 1 f)\n\nmain = do\n v <- (map ord) <$> getLine\n let f = getFreq v Map.empty\n a = ord 'a'\n putStrLn $ map chr $ reverse $ solve v [] [] a (Map.findWithDefault 0 a f) f\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (unpack)\nimport qualified Data.Map.Strict as M (adjust, insert, findMin, empty, alter, member, Map)\nimport qualified Data.List as L (sort)\n\nrun [] _ [] = \"\"\nrun (t:ts) _ [] = t:run ts (M.empty) []\nrun [] mm (x:xs) = run [x] (M.alter f x mm) xs\nrun (t:ts) mm (x:xs) | t <= ms = t:run ts mm (x:xs)\n | otherwise = run (x:t:ts) (M.alter f x mm) xs where\n (ms, _) = M.findMin mm\n\nf (Just 1) = Nothing\nf (Just x) = Just (x - 1)\n\ncmap [] m = m\ncmap (x:xs) m | M.member x m = cmap xs (M.adjust succ x m)\n | otherwise = cmap xs (M.insert x 1 m)\n\nmain = do\n (C.unpack -> xs) <- B.getLine\n putStrLn $ run [] (cmap (L.sort xs) M.empty) xs\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (unpack)\nimport qualified Data.Map.Strict as M (adjust, insert, findMin, empty, alter, member, Map)\nimport qualified Data.List as L (sort)\n\nrun [] _ [] = \"\"\nrun (t:ts) _ [] = t:run ts (M.empty) []\nrun [] mm (x:xs) = run [x] (M.alter f x mm) xs\nrun (t:ts) mm (x:xs) | t <= ms = t:run ts mm (x:xs)\n | otherwise = run (x:t:ts) (M.alter f x mm) xs where\n (ms, _) = M.findMin mm\n\nf (Just 1) = Nothing\nf (Just x) = Just (x - 1)\n\ncmap [] m = m\ncmap (x:xs) m | M.member x m = cmap xs (M.adjust succ x m)\n | otherwise = cmap xs (M.insert x 1 m)\n\nmain = do\n (C.unpack -> xs) <- B.getLine\n putStr $ run [] (cmap (L.sort xs) M.empty) xs\n"}], "src_uid": "e758ae072b8aed53038e4593a720276d"} {"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve l = max 0 (2*(ma-mi-2))\n where\n ma= maximum l\n mi= minimum l\n\nroutine :: IO ()\nroutine = do\n l <- (map read.words) <$> getLine\n print $ solve l\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\nimport Data.List (sort)\n\nfindMin :: [Int] -> Int\nfindMin xs = max 0 (2*(mx - mn - 2)) where\n [mn, mid, mx] = sort xs\n\nreadLine :: IO [Int]\nreadLine = (map read) . words <$> getLine\n\nmain =\n read <$> getLine >>= \\q ->\n replicateM_ q (findMin <$> readLine >>= print)"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetList :: (Read a) => IO [a]\ngetList = map read <$> words <$> getLine\n \ngetNLists :: (Read a) => Int -> IO [[a]]\ngetNLists n = sequence $ replicate n getList\n\nmain :: IO ()\nmain = do\n cas <- readLn\n replicateM_ cas $ do\n [a, b, c] <- sort <$> getList\n print $ cal a b c\n\ncal :: Int -> Int -> Int -> Int\ncal a b c\n | a == b && b == c = 0\n | otherwise = max 0 ((c - a) * 2 - 4)"}], "negative_code": [], "src_uid": "18f2e54e4147e8887da737d5b6639473"} {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\n\nmain = do\n [n,k] <- map read . words <$> getLine :: IO [Int]\n s <- getLine\n \n let count = [length $ filter (==c) s | c <- map (chr . (+(ord 'A'))) [0..k-1]]\n\n print $ minimum count * k", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.List\nimport Data.Ord\n\nmain = sol <$> get <*> getLine >>= print\n\nget = map read . words <$> getLine\n\nsol [n,k] s = (* k) . last . take k . sortBy (flip compare) . elems . accumArray (+) 0 ('A','Z') . zip s $ repeat 1\n\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nlongestGoodSubsequence :: Int -> String -> Int\nlongestGoodSubsequence k s\n | c /= k = 0\n | otherwise = c * b\n where a = map length $ group $ sort s\n b = minimum a\n c = length a\n\nmain :: IO ()\nmain = do\n [n, k] <- readInts\n s <- getLine\n print $ longestGoodSubsequence k s "}, {"source_code": "import Data.List\nmain = interact $ show . solve . tail . words\nsolve [k,s] | length fs < read k = 0\n | otherwise = read k * minimum fs\n where fs = map length $ group $ sort s\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\t\t[n,k]<-map read <$> words <$> getLine ::IO [Int]\n\t\ts<-getLine\n\t\tlet m= map length $ group $ sort s\n\t\tprint $ if length m k, xs] -> solve k xs) . words\nsolve k xs = (k *) $ minimum $ take k $ elems (accumArray (+) 0 ('A', 'Z') $ zip xs (repeat 1) :: UArray Char Int)"}, {"source_code": "import Data.List (sort, group)\n\nprocess :: Int -> [Char] -> Int\nprocess k xs = k * minimum (take k $ ls ++ (repeat 0))\n where ls = map length $ group $ sort xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n [n, k] <- fmap (map readInt.words) getLine\n xs <- getLine\n print $ process k xs"}, {"source_code": "import Data.List\n\nmain = do\n e<-getLine\n e2<-getLine\n let (n:k:[])=map read (words e)::[Int]\n xs=map length $ group $ sort e2\n print $ if k==(length xs) then k*(minimum xs) else 0"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\ncount :: B8.ByteString -> MapS.Map Char Int\ncount string = B8.foldr' (flip update) MapS.empty string\n where update map char = MapS.alter (\\value -> Just $ 1 + fromMaybe 0 value) char map\n\nmain :: IO ()\nmain = do\n [n, k] <- (map readB8Int) <$> B8.words <$> B8.getLine\n string <- B8.getLine\n let keys = take k ['A'..'Z']\n let counts = count string\n let charCount = foldr1 min . map (\\x -> fromMaybe 0 $ MapS.lookup x counts) $ keys\n printf \"%d\\n\" (charCount * k)\n"}], "negative_code": [{"source_code": "import Data.List\nmain = interact $ show . solve . tail . words\nsolve (k:s) | length fs < read k = 0\n | otherwise = read k * minimum fs\n where fs = map length $ group $ sort s\n"}], "src_uid": "d9d5db63b1e48214d02abe9977709384"} {"source_code": "import Data.IntSet (insert,fromList, lookupGT, lookupLE)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n,k,a] <- map read . words <$> getLine\n getLine\n map read .words <$> getLine >>= putStrLn . show . solve n k (a+1)\n\nsolve :: Int->Int->Int->[Int]->Int\nsolve n k a = let tot = (n+1) `div` a\n check _ _ _ [] = -1\n check s c t (x:xs) = if t'< k then c else check (insert x s) (c+1) t' xs\n where Just r = lookupGT x s\n Just l = lookupLE x s\n t' = t + (x-l)`div`a + (r-x)`div`a - (r-l)`div`a \n in check (fromList [0, n+1]) 1 tot", "positive_code": [{"source_code": "import Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Set (Set, fromList, lookupLT, lookupGT, insert)\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n k a xs = foldr loop (`seq` -1) xs init\n where\n init = (1, (n + 1) `div` (a + 1) - k, fromList [0, n + 1])\n count x y = (y - x) `div` (a + 1)\n\n loop i f (acc, buf, obs)\n | buf' < 0 = acc\n | otherwise = f (acc + 1, buf', i `insert` obs)\n where\n u = fromJust $ i `lookupLT` obs\n v = fromJust $ i `lookupGT` obs\n buf' = buf + count u i + count i v - count u v\n\nmain = do\n [n, k, a] <- parse <$> B.getLine\n B.getLine\n xs <- parse <$> B.getLine\n print $ solve n k a xs\n"}, {"source_code": "import Data.IntSet (insert, fromList, lookupGT, lookupLE)\n\nmain = interact $ show. solve. map read.words\n\nsolve :: [Int]->Int\nsolve (n:k:a:_:x) = let tot = (n+1) `div` (a+1)\n check _ _ _ [] = -1\n check s c t (x:xs) = if t'< k then c else check (insert x s) (c+1) t' xs\n where Just r = lookupGT x s\n Just l = lookupLE x s\n t' = t + (x-l)`div`(a+1) + (r-x)`div`(a+1) - (r-l)`div`(a+1)\n in check (fromList [0, n+1]) 1 tot x"}, {"source_code": "import Data.IntSet (insert,fromList, lookupGT, lookupLE)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n,k,a] <- map read . words <$> getLine\n getLine\n x <- map read . words <$> getLine\n putStrLn $ show $ solve n k (a+1) x\n\nsolve :: Int->Int->Int->[Int]->Int\nsolve n k a = let tot = (n+1) `div` a\n check _ _ _ [] = -1\n check s c t (x:xs) = if t'< k then c else check (insert x s) (c+1) t' xs\n where Just r = lookupGT x s\n Just l = lookupLE x s\n t' = t + (x-l)`div`a + (r-x)`div`a - (r-l)`div`a \n in check (fromList [0, n+1]) 1 tot"}], "negative_code": [{"source_code": "import Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Set (Set, fromList, lookupLT, lookupGT, insert)\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nsolve :: Int -> Int -> Int -> [Int] -> Int\nsolve n k a xs = foldr loop (`seq` -1) xs init\n where\n init = (1, n `div` a - k, fromList [0, n + 1])\n count x y = (y - x - 1) `div` a\n\n loop i f (acc, buf, obs)\n | buf' < 0 = acc\n | otherwise = f (acc + 1, buf', i `insert` obs)\n where\n u = fromJust $ i `lookupLT` obs\n v = fromJust $ i `lookupGT` obs\n buf' = buf - count u v + count u i + count i v\n\nmain = do\n [n, k, a] <- parse <$> B.getLine\n B.getLine\n xs <- parse <$> B.getLine\n print $ solve n k a xs\n"}], "src_uid": "e83c40f6d08b949900e5ae93b1d6f2c3"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\nimport Data.Ix (Ix(range))\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \ntype Count = IOUArray (Int, Int, Int) Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \n \nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c <- newArray ((0, 0, 0), (length xs, 7, 7)) 0\n writeArray c (0,0,0) 1\n mapM_ (go c) $ indices xs\n return c\n where\n indices :: [Bool] -> [(Int, Bool, Int, Int, Int)]\n indices xs = [(k, x ,mask, i, j) \n | (k, x) <- zip [0..length xs-1] xs\n , mask <-[0..7]\n , i <- [0..7]\n , j <- [0..7]\n -- , x || (mask .&. i) == mask\n ]\n go :: \n Count \n -> (\n Int -- index for xs\n , Bool \n , Int -- mask\n , Int -- prefix less\n , Int) -- minor\n -> IO ()\n go c (k, isOne, mask, i, j) \n | isOne || (mask .&. i) == mask = do \n v1 <- readArray c (k, i, j)\n v2 <- readArray c (k+1, ni,nj)\n writeArray c (k+1,ni,nj) (v1+v2 `mod` mm)\n | otherwise = return ()\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \n \na :: Integer\na = 2\nmain :: IO ()\nmain = do\n -- print (range ((0,0),(7,7)) )\n -- print $ 2 ^ 200000\n xs <- parse\n res <- solve1 xs\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(length xs, i, 7) |i <- [0..7]])\n return ()", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray, Ix (range))\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n\nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n\nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\ntype Count = IOUArray (Int,Int) Int\n\nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n\ngi :: Int -> Int -> Int\ngi i j = i * 8 + j\n\nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c1 <- newArray ((0, 0), (7, 7)) 0\n writeArray c1 (0,0) 1\n gogo c1 xs\n where\n gogo :: Count -> [Bool] -> IO Count\n gogo c1 xs = case xs of\n [] -> return c1\n (x:xs) -> do\n c2 <- newArray ((0, 0), (7, 7)) 0\n let gg = (go c1 c2 x)\n mapM_ gg indices\n gogo c2 xs\n indices = [(mask, i, j) | mask <-[0..7],i <- [0..7], j <- [0..7]]\n go :: \n Count \n -> Count \n -> Bool \n -> (Int -- mask\n , Int -- prefix less\n , Int )\n -> IO ()\n go c1 c2 isOne (mask, i, j)\n | isOne || (mask .&. i) == mask = \n do \n val1 <- readArray c1 (i, j)\n val2 <- readArray c2 (ni, nj)\n writeArray c2 (ni, nj) (val1+val2 `mod` mm)\n | otherwise = return ()\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n\n\nmain :: IO ()\nmain = do\n res <- solve1 =<< parse\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(i, 7) |i <- [0..7]])\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray, Ix (range))\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n\nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n\nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\ntype Count = IOUArray (Int,Int) Int\n\nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n\ngi :: Int -> Int -> Int\ngi i j = i * 8 + j\n\nresetArray :: Count -> IO ()\nresetArray x = mapM_ (flip (writeArray x) 0) $ range ((0,0), (7,7))\n\nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c1 <- newArray ((0, 0), (7, 7)) 0\n writeArray c1 (0,0) 1\n gogo c1 xs\n where\n gogo :: Count -> [Bool] -> IO Count\n gogo c1 xs = case xs of\n [] -> return c1\n (x:xs) -> do\n c2 <- newArray ((0, 0), (7, 7)) 0\n mapM_ (go c1 c2 x) indices\n gogo c2 xs\n indices = [(mask, i, j) | mask <-[0..7],i <- [0..7], j <- [0..7]]\n go :: \n Count \n -> Count \n -> Bool \n -> (Int -- mask\n , Int -- prefix less\n , Int )\n -> IO ()\n go c1 c2 isOne (mask, i, j)\n | isOne || (mask .&. i) == mask = \n do \n val1 <- readArray c1 (i, j)\n val2 <- readArray c2 (ni, nj)\n writeArray c2 (ni, nj) (val1+val2 `mod` mm)\n | otherwise = return ()\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n\n\nmain :: IO ()\nmain = do\n res <- solve1 =<< parse\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(i, 7) |i <- [0..7]])\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray, Ix (range))\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n\nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n\nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\ntype Count = IOUArray (Int,Int) Int\n\nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n\ngi :: Int -> Int -> Int\ngi i j = i * 8 + j\n\nresetArray :: Count -> IO ()\nresetArray x = mapM_ (flip (writeArray x) 0) $ range ((0,0), (7,7))\n\nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c1 <- newArray ((0, 0), (7, 7)) 0\n writeArray c1 (0,0) 1\n gogo c1 xs\n where\n gogo :: Count -> [Bool] -> IO Count\n gogo c1 xs = case xs of\n [] -> return c1\n (x:xs) -> do\n c2 <- newArray ((0, 0), (7, 7)) 0\n mapM_ (go c1 c2 x) indices\n resetArray c1 \n gogo c2 xs\n indices = [(mask, i, j) | mask <-[0..7],i <- [0..7], j <- [0..7]]\n go :: \n Count \n -> Count \n -> Bool \n -> (Int -- mask\n , Int -- prefix less\n , Int )\n -> IO ()\n go c1 c2 isOne (mask, i, j)\n | isOne || (mask .&. i) == mask = \n do \n val1 <- readArray c1 (i, j)\n val2 <- readArray c2 (ni, nj)\n writeArray c2 (ni, nj) (val1+val2 `mod` mm)\n | otherwise = return ()\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n\n\nmain :: IO ()\nmain = do\n res <- solve1 =<< parse\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(i, 7) |i <- [0..7]])\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray, Ix (range))\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n\nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n\nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\ntype Count = IOUArray (Int,Int) Int\n\nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n\ngi :: Int -> Int -> Int\ngi i j = i * 8 + j\n\nresetArray :: Count -> IO ()\nresetArray x = mapM_ (flip (writeArray x) 0) $ range ((0,0), (7,7))\n\nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c1 <- newArray ((0, 0), (7, 7)) 0\n c2 <- newArray ((0, 0), (7, 7)) 0\n writeArray c1 (0,0) 1\n gogo c1 c2 xs\n where\n gogo :: Count -> Count -> [Bool] -> IO Count\n gogo c1 c2 xs = case xs of\n [] -> return c1\n (x:xs) -> do\n mapM_ (go c1 c2 x) indices\n resetArray c1 \n gogo c2 c1 xs\n indices = [(mask, i, j) | mask <-[0..7],i <- [0..7], j <- [0..7]]\n go :: \n Count \n -> Count \n -> Bool \n -> (Int -- mask\n , Int -- prefix less\n , Int )\n -> IO ()\n go c1 c2 isOne (mask, i, j)\n | isOne || (mask .&. i) == mask = \n do \n val1 <- readArray c1 (i, j)\n val2 <- readArray c2 (ni, nj)\n writeArray c2 (ni, nj) (val1+val2 `mod` mm)\n | otherwise = return ()\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n\n\nmain :: IO ()\nmain = do\n res <- solve1 =<< parse\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(i, 7) |i <- [0..7]])\n return ()\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\nimport Data.Ix (Ix(range))\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \ntype Count = IOUArray (Int, Int, Int) Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \n \nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c <- newArray ((0, 0, 0), (length xs, 7, 7)) 0\n writeArray c (0,0,0) 1\n mapM_ (go c) $ indices xs\n return c\n where\n indices :: [Bool] -> [(Int, Bool, Int, Int, Int)]\n indices xs = [(k, x ,mask, i, j) \n | (k, x) <- zip [0..length xs-1] xs\n , mask <-[0..7]\n , i <- [0..7]\n , j <- [0..7]\n , x || (mask .&. i) == mask\n ]\n go :: \n Count \n -> (\n Int -- index for xs\n , Bool \n , Int -- mask\n , Int -- prefix less\n , Int) -- minor\n -> IO ()\n go c (k, isOne, mask, i, j) = \n do \n v1 <- readArray c (k, i, j)\n v2 <- readArray c (k+1, ni,nj)\n writeArray c (k+1,ni,nj) (v1+v2 `mod` mm)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \n \na :: Integer\na = 2\nmain :: IO ()\nmain = do\n -- print (range ((0,0),(7,7)) )\n -- print $ 2 ^ 200000\n xs <- parse\n res <- solve1 xs\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(length xs, i, 7) |i <- [0..7]])\n return ()"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\nimport Data.Ix (Ix(range))\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \ntype Count = IOUArray (Int, Int, Int) Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \n \nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c <- newArray ((0, 0, 0), (length xs, 7, 7)) 0\n writeArray c (0,0,0) 1\n mapM_ (go c) $ indices xs\n return c\n where\n indices :: [Bool] -> [(Int, Bool, Int, Int, Int)]\n indices xs = [(k, x ,mask, i, j) \n | \n (k, x) <- zip [0..length xs-1] xs\n , mask <-[0..7]\n , i <- [0..7]\n , x || (mask .&. i) == mask\n , j <- [0..7]\n ]\n go :: \n Count \n -> (\n Int -- index for xs\n , Bool \n , Int -- mask\n , Int -- prefix less\n , Int) -- minor\n -> IO ()\n go c (k, isOne, mask, i, j) = \n do \n v1 <- readArray c (k, i, j)\n v2 <- readArray c (k+1, ni,nj)\n -- print (k, i, j)\n writeArray c (k+1,ni,nj) (v1+v2 `mod` mm)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \n \na :: Integer\na = 2\nmain :: IO ()\nmain = do\n -- print (range ((0,0),(7,7)) )\n -- print $ 2 ^ 200000\n xs <- parse\n res <- solve1 xs\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(length xs, i, 7) |i <- [0..7]])\n return ()"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\nimport Data.Ix (Ix(range))\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \ntype Count = IOUArray (Int, Int, Int) Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \n \nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c <- newArray ((0, 0, 0), (length xs, 7, 7)) 0\n writeArray c (0,0,0) 1\n mapM_ (go c) $ indices xs\n return c\n where\n indices :: [Bool] -> [(Int, Bool, Int, Int, Int)]\n indices xs = [(k, x ,mask, i, j) \n | \n (k, x) <- zip [0..length xs-1] xs\n , mask <-[0..7]\n , i <- [0..7]\n , x || (mask .&. i) == mask\n , j <- [0..7]\n ]\n go :: \n Count \n -> (\n Int -- index for xs\n , Bool \n , Int -- mask\n , Int -- prefix less\n , Int) -- minor\n -> IO ()\n go c (k, isOne, mask, i, j) = \n do \n v1 <- readArray c (k, i, j)\n v2 <- readArray c (k+1, ni,nj)\n print (k, i, j)\n writeArray c (k+1,ni,nj) (v1+v2 `mod` mm)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \n \na :: Integer\na = 2\nmain :: IO ()\nmain = do\n -- print (range ((0,0),(7,7)) )\n -- print $ 2 ^ 200000\n xs <- parse\n res <- solve1 xs\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(length xs, i, 7) |i <- [0..7]])\n return ()"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\nimport Data.Ix (Ix(range))\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \ntype Count = IOUArray (Int, Int, Int) Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \n \nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c <- newArray ((0, 0, 0), (length xs, 7, 7)) 0\n writeArray c (0,0,0) 1\n mapM_ (go c) $ indices xs\n return c\n where\n indices :: [Bool] -> [(Int, Bool, Int, Int, Int)]\n indices xs = [(k, x ,mask, i, j) \n | mask <-[0..7]\n , i <- [0..7]\n , (k, x) <- zip [0..length xs-1] xs\n , x || (mask .&. i) == mask\n , j <- [0..7]\n ]\n go :: \n Count \n -> (\n Int -- index for xs\n , Bool \n , Int -- mask\n , Int -- prefix less\n , Int) -- minor\n -> IO ()\n go c (k, isOne, mask, i, j) = \n do \n v1 <- readArray c (k, i, j)\n v2 <- readArray c (k+1, ni,nj)\n writeArray c (k+1,ni,nj) (v1+v2 `mod` mm)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \n \na :: Integer\na = 2\nmain :: IO ()\nmain = do\n -- print (range ((0,0),(7,7)) )\n -- print $ 2 ^ 200000\n xs <- parse\n res <- solve1 xs\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(length xs, i, 7) |i <- [0..7]])\n return ()"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\nimport Data.Ix (Ix(range))\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \ntype Count = IOUArray (Int, Int, Int) Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \n \nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c <- newArray ((0, 0, 0), (length xs, 7, 7)) 0\n writeArray c (0,0,0) 1\n mapM_ (go c) $ indices xs\n return c\n where\n indices :: [Bool] -> [(Int, Bool, Int, Int, Int)]\n indices xs = [(k, x ,mask, i, j) \n | mask <-[0..7]\n , i <- [0..7]\n , (k, x) <- zip [0..length xs-1] xs\n , x || mask .&. i == mask\n , j <- [0..7]\n ]\n go :: \n Count \n -> (\n Int -- index for xs\n , Bool \n , Int -- mask\n , Int -- prefix less\n , Int) -- minor\n -> IO ()\n go c (k, isOne, mask, i, j) = \n do \n v1 <- readArray c (k, i, j)\n v2 <- readArray c (k+1, ni,nj)\n writeArray c (k+1,ni,nj) (v1+v2 `mod` mm)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \n \na :: Integer\na = 2\nmain :: IO ()\nmain = do\n -- print (range ((0,0),(7,7)) )\n -- print $ 2 ^ 200000\n xs <- parse\n res <- solve1 xs\n printAns =<< (foldr (((`mod` mm).) . (+)) 0) <$> sequence (readArray res <$> [(length xs, i, 7) |i <- [0..7]])\n return ()"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'))\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \n \ntype Count = Map.IntMap Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \ngi :: Int -> Int -> Int\ngi i j = i * 8 + j\n \nsolve1 :: [Bool] -> Count\nsolve1 xs = foldl \n (\\m (k, a) -> foldr (\\(mask, g) m1 -> go m m1 a k mask (g`div`8) (g`mod`8)) Map.empty $ liftM2 (,) [0..7] (Map.keys m))\n (Map.fromList [((0 `gi` 0),1)]) \n (zip [0..] xs)\n where\n updateX :: Int -> Maybe Int -> Maybe Int\n updateX x Nothing = Just x\n updateX x (Just y) = Just (x+y)\n inject :: Count -> (Int, Int) -> Count\n inject c (k, v) = Map.alter (updateX v) k c\n \n go :: \n Count \n -> Count \n -> Bool \n -> Int -- count\n -> Int -- mask\n -> Int -- prefix less\n -> Int -- minor\n -> Count\n go c c2 isOne k mask i j\n | isOne || (mask .&. i) == mask = inject c2 ((ni`gi`nj), c Map.! (i `gi` j)) \n | otherwise = inject c2 ((0`gi`0),0)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \nsolve :: Solver\nsolve xs = (`mod` mm) $ sum $ Map.elems $ Map.filterWithKey (\\k _ -> k`mod`8==7) $ solve1 xs \n \n \nmain :: IO ()\nmain = do\n printAns =<< solve <$> parse\n return ()"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n \nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'))\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n \nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> CoDomain\n \nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n \n \nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n \nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n \nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n \n \n \ntype Count = Map.IntMap Int\n \nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n \ngi :: Int -> Int -> Int\ngi i j = i * 8 + j\n \nsolve1 :: [Bool] -> Count\nsolve1 xs = foldl \n (\\m ys -> Map.fromListWith (((`mod` mm).) . (+)) $ (\\(isOne, k, mask,i,j) -> go m isOne k mask i j) <$> ys (Map.keys m)) \n (Map.fromList [((0 `gi` 0),1)]) \n indices\n where\n indices = \n [\\keys -> [(xs!!k, k, mask, g `div` 8, g `mod` 8) | mask <-[0..7],g <- keys ] | k <- [0..length xs-1]]\n go :: Count \n -> Bool \n -> Int -- count\n -> Int -- mask\n -> Int -- prefix less\n -> Int -- minor\n -> (Int, Int)\n go c isOne k mask i j\n | isOne || (mask .&. i) == mask = ((ni`gi`nj), c Map.! (i `gi` j))\n | otherwise = ((0`gi`0),0)\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n \nsolve :: Solver\nsolve xs = (`mod` mm) $ sum $ Map.elems $ Map.filterWithKey (\\k _ -> k`mod`10==7) $ solve1 xs \n \n \nmain :: IO ()\nmain = do\n printAns =<< solve <$> parse\n return ()"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.IntMap as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems, MArray)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'))\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Data.Bits\n\nmm = 998244353\ntype Domain = [Bool]\ntype CoDomain = Int\ntype Solver = Domain -> IO CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> C.getLine\n\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn . show\n\nparse :: IO Domain\nparse = do\n xs <- map (=='1') <$> getLine\n return xs\n\nshowResult :: [Bool] -> String\nshowResult xs = (bool '0' '1') <$> xs\n\n\n\ntype Count = IOUArray Int Int\n\nones :: Int -> Int\nones 0 = 0\nones 1 = 1\nones i\n | even i = ni\n | odd i = ni + 1\n where ni = ones $ i `div` 2\n\ngi :: Int -> Int -> Int\ngi i j = i * 10 + j\n\nsolve1 :: [Bool] -> IO Count\nsolve1 xs = do\n c1 <- newArray (0, 7`gi`7) 0\n writeArray c1 0 1\n foldlM goBig c1 indices\n where\n goBig :: Count -> [(Bool, Int, Int, Int, Int)] -> IO Count\n goBig c1 xs = do\n c2 <- newArray (0, 7`gi`7) 0\n mapM_ (\\(isOne, k, mask,i,j) -> go c1 c2 isOne k mask i j) xs\n return c2\n\n indices = [[(xs!!k, k, mask, i, j) | mask <-[0..7],i <- [0..7], j <- [0..7]] | k <- [0..length xs-1]]\n go :: \n Count \n -> Count \n -> Bool \n -> Int -- count\n -> Int -- mask\n -> Int -- prefix less\n -> Int -- minor\n -> IO ()\n go c1 c2 isOne k mask i j\n | isOne || (mask .&. i) == mask = \n do \n val1 <- readArray c1 (i `gi` j)\n val2 <- readArray c2 (ni`gi`nj)\n writeArray c2 (ni`gi`nj) (val1+val2)\n | otherwise = return ()\n where \n vmask = 7 .&. (complement mask)\n ni = if isOne then i .|. vmask else i\n nj = case ones mask of\n 1 -> j .|. mask\n 2 -> j .|. vmask\n otherwise -> j\n\n\nsolve2 :: IOUArray Int Int -> Int\nsolve2 xs = undefined\ngo :: [Bool] -> IO ()\ngo bs = do\n na <- newArray (0, length bs -1 ) 0\n let x = solve2 na\n return ()\n \n\na :: Int\na = 1 .&. 1\n\nmain :: IO ()\nmain = do\n res <- solve1 =<< parse\n printAns =<< (\\x -> mod (sum x) mm) <$> sequence (readArray res <$> [i `gi` 7 |i <- [0..7]])\n -- printAns =<< \n return ()\n"}], "src_uid": "94bc4b263821713fb5b1de4de331a515"} {"source_code": "toArray :: String -> [Int]\r\ntoArray = map (read :: String -> Int) . words\r\n\r\nprocess :: [Int] -> Int\r\nprocess = maximum . compress\r\n where compress [] = []\r\n compress (x : xs) =\r\n let (pref, suf) = span (==x) xs\r\n in 1 + length pref : compress suf\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . process . toArray) . takeEven . tail . lines)\r\n where takeEven l = map snd $ filter (even . fst) (zip [1..] l)\r\n", "positive_code": [{"source_code": "toArray :: String -> [Int]\r\ntoArray = map (read :: String -> Int) . words\r\n\r\nprocess :: [Int] -> Int\r\nprocess = maximum . compressed\r\n where compressed [] = []\r\n compressed (x : xs) = 1 + length (takeWhile (==x) xs) :\r\n compressed (dropWhile (==x) xs)\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (show . process . toArray) . takeEven . tail . lines)\r\n where takeEven l = map snd $ filter (even . fst) (zip [1..] l)\r\n"}], "negative_code": [], "src_uid": "6d4744d7356e709f73891270becd14e3"} {"source_code": "import Data.Int\nimport Data.List\nimport Control.Monad\n\ntraceShowId = id\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n,a,b] <- map read . words <$> getLine :: IO [Int64]\n road <- getLine\n print $ solve a b $ group road\nsolve a b [road] = traceShowId $ a * genericLength road + b * (genericLength road + 1)\nsolve a b (start:road) = go road $! traceShowId (a * (genericLength (traceShowId start) + 1) + b * (genericLength start + 2))\n where\n go [end] acc = acc + traceShowId (a * (genericLength (traceShowId end) + 1) + b * (genericLength end + 2))\n go (seg@(h:_):road) acc = go road $! acc + (traceShowId $\n case h of '1' -> a * genericLength (traceShowId seg) + 2*b * (genericLength seg - 1)\n '0' -> min (a * (genericLength (traceShowId seg) + 2) + b * (genericLength seg + 3))\n (a * genericLength seg + 2*b * (genericLength seg + 1))\n\n )\n", "positive_code": [{"source_code": "gint :: IO Int\ngint = fmap read getLine\nmain = do\n t <- gint\n mymain t\n\nmymain 0 = return ()\nmymain x = do\n strabc <- getLine\n strbits <- getLine\n let [a,b,c] = map read $ words strabc\n print (fst (solve b c strbits))\n mymain (x - 1)\n\nsolve :: Integer -> Integer -> String -> (Integer,Integer)\nsolve pipeline pillar [] = (pillar, 1000000000000000000)\nsolve pipeline pillar (b:road)\n | b == '0' = (newdown, newup)\n | b == '1' = (1000000000000000000, newup1)\n where (down, up) = solve pipeline pillar road\n newup = 2 * pillar + (min (up + pipeline) (down + 2*pipeline) )\n newdown = pillar + (min (up + 2 * pipeline) (down + pipeline) )\n newup1 = 2 * pillar + up + pipeline"}], "negative_code": [{"source_code": "\nimport Data.List\nimport Control.Monad\n\ntraceShowId = id\n\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n,a,b] <- map read . words <$> getLine\n road <- getLine\n print $ solve a b $ group road\nsolve a b [road] = traceShowId $ a * length road + b * (length road + 1)\nsolve a b (start:road) = go road $! traceShowId (a * (length (traceShowId start) + 1) + b * (length start + 2))\n where\n go [end] acc = acc + traceShowId (a * (length (traceShowId end) + 1) + b * (length end + 2))\n go (seg@(h:_):road) acc = go road $! acc + (traceShowId $\n case h of '1' -> a * length (traceShowId seg) + 2*b * (length seg - 1)\n '0' -> min (a * (length (traceShowId seg) + 2) + b * (length seg + 3))\n (a * length seg + 2*b * (length seg + 1))\n\n )\n"}], "src_uid": "4fa609ef581f705df901f7532b52cf7c"} {"source_code": "import qualified Data.Array as A\nimport Data.Char (ord)\n\nmain = interact $ printAns. uncurry solve. readInp\n\nreadInp = prep. tail. lines\n where prep (s:lst:_) = (s, A.listArray (0, 25). fmap read. words $ lst)\n\nprintAns (a,b,c) = unlines. map show $ [a,b,c]\n\nsolve :: String -> A.Array Int Int -> (Int,Int,Int)\nsolve s a = d slen\n where slen = length s\n lims = A.listArray (1, slen) (map toLim s)\n toLim = (a A.!). (\\x -> x - (ord 'a')). ord\n\n d 0 = (1,0,0)\n d i = getRes. toVals. okPos $ (reverse [0..i-1])\n where okPos l = map snd. takeWhile isOk. zip (lstLim l) $ l\n lstLim = scanl1 min. map ((lims A.!). (+1))\n isOk (a, b) = a >= i - b\n toVals = map (ds A.!)\n getRes l = addCur (length l). foldl upd (0,0,10^5) $ l\n upd (a,b,c) (x,y,z) = (add a x, max b y, min c z)\n addCur len (a,b,c) = (a, max b len, c+1)\n\n ds = A.listArray bounds\n [d i | i <- A.range bounds]\n bounds = (0, slen)\n \n add a b = (a+b) `rem` md\n md = 10^9 + 7\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Unboxed\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve n s as0 = [cnt!n, maximum $ zipWith (-) [1..] bs, mc!n]\n where\n as = listArray ('a', 'z') as0 :: UArray Char Int\n bs = map (\\(i, c2l) -> foldl (\\(!b) (c, l) -> let b' = i - as!c in max b $ min l b') 0 $ assocs c2l) $ zip [1..] $ tail $ scanl (\\a p -> a // [p]) (listArray ('a', 'z') (repeat (-9000)) :: UArray Char Int) $ zip s [1..]\n cnt = listArray (-1, n) $ ([0, 1] ++) $ map (\\(i, b) -> (ps!(i - 1)) -% (ps!(b - 1))) $ zip [1..] bs :: Array Int Int\n ps = listArray (-1, n) $ scanl1 (+%) $ elems cnt :: Array Int Int\n mc = listArray (0, n) $ (0:) $ map ((+1) . (mc!)) bs :: Array Int Int\n mb = 1000000007\n a +% b = (a + b) `rem` mb\n a -% b = (a - b) `mod` mb\n\nmain = do \n n <- fmap readInt B.getLine\n s <- getLine \n as <- fmap readInts B.getLine\n putStr $ unlines $ map show $ solve n s as\n"}, {"source_code": "import qualified Data.Array as A\nimport Data.Char (ord)\n\nmain = interact $ printAns. uncurry solve. readInp\n\nreadInp = prep. tail. lines\n where prep (s:lst:_) = (s, A.listArray (0, 25). fmap read. words $ lst)\n\nprintAns (a,b,c) = unlines. map show $ [a,b,c]\n\nsolve :: String -> A.Array Int Int -> (Int,Int,Int)\nsolve s a = d slen\n where slen = length s\n lims = A.listArray (1, slen) (map toLim s)\n toLim = (a A.!). (\\x -> x - (ord 'a')). ord\n\n d 0 = (1,0,0)\n d i = getRes. toVals. okPos $ (reverse [0..i-1])\n where okPos l = map snd. takeWhile isOk. zip (lstLim l) $ l\n lstLim = scanl1 min. map ((lims A.!). (+1))\n isOk (a, b) = a >= dist i b\n dist = (-)\n toVals = map (ds A.!)\n getRes l = addCur (length l). foldl upd (0,0,10^5) $ l\n upd (a,b,c) (x,y,z) = (add a x, max b y, min c z)\n addCur len (a,b,c) = (a, max b len, c+1)\n\n ds = A.listArray bounds\n [d i | i <- A.range bounds]\n bounds = (0, slen)\n \n add a b = (a+b) `rem` md\n md = 10^9 + 7\n"}, {"source_code": "import qualified Data.Array as A\nimport Data.Char (ord)\n\nmain = interact $ printAns. uncurry solve. readInp\n\nreadInp = prep. tail. lines\n where prep (s:lst:_) = (s, A.listArray (0, 25). fmap read. words $ lst)\n\nprintAns (a,b,c) = unlines. map show $ [a,b,c]\n\nsolve :: String -> A.Array Int Int -> (Int,Int,Int)\nsolve s a = d slen\n where slen = length s\n lims = A.listArray (1, slen) (map toLim s)\n toLim = (a A.!). (flip (-) (ord 'a')). ord\n\n d 0 = (1,0,0)\n d i = getRes. toVals. okPos $ (reverse [0..i-1])\n where okPos l = map snd. takeWhile isOk. zip (lstLim l) $ l\n lstLim = scanl1 min. map ((lims A.!). (+1))\n isOk (a, b) = a >= dist i b\n dist = (-)\n toVals = map (ds A.!)\n getRes l = addCur (length l). foldl upd (0,0,10^5) $ l\n upd (a,b,c) (x,y,z) = (add a x, max b y, min c z)\n addCur len (a,b,c) = (a, max b len, c+1)\n\n ds = A.listArray bounds\n [d i | i <- A.range bounds]\n bounds = (0, slen)\n \n add a b = (a+b) `rem` md\n md = 10^9 + 7\n"}], "negative_code": [{"source_code": "import qualified Data.Array as A\nimport Data.Char (ord)\n\nmain = interact $ printAns. uncurry solve. readInp\n\nreadInp = prep. tail. lines\n where prep (s:lst:_) = (s, A.listArray (0, 25). fmap read. words $ lst)\n\nprintAns (a,b,c) = unlines. map show $ [a,b,c]\n\nsolve :: String -> A.Array Int Int -> (Int,Int,Int)\nsolve s a = d slen\n where slen = length s\n lims = A.listArray (1, slen) (map toLim s)\n toLim = (a A.!). (flip (-) (ord 'a')). ord\n\n d 0 = (1,0,0)\n d i = getRes. toVals. okPos $ (reverse [0..i-1])\n where okPos l = map snd. takeWhile isOk. zip (lstLim l) $ l\n lstLim = scanl1 min. map ((lims A.!). (+1))\n isOk (a, b) = a >= dist i b\n dist = (-)\n toVals = map (ds A.!)\n getRes l = addCur (length l). foldl upd (0,0,10^5) $ l\n upd (a,b,c) (x,y,z) = (a + x, max b y, min c z)\n addCur len (a,b,c) = (a, max b len, c+1)\n\n ds = A.listArray bounds\n [d i | i <- A.range bounds]\n bounds = (0, slen)\n \n add a b = (a+b) `rem` md\n md = 10^9 + 7\n"}], "src_uid": "b56e70728d36c41134c39bd6ad13d059"} {"source_code": "import Data.List (transpose)\n\nsolve :: [String] -> Maybe [(Int, Int)]\nsolve ss\n | findELine ss && findELine (transpose ss) = Nothing\n | not $ findELine ss = Just $ solve' ss\n | otherwise = Just $ map swap $ solve' $ transpose ss\n where\n findELine ss = any (all (== 'E')) ss\n swap (a, b) = (b, a)\n solve' ss = [(i, findDot s) | (i, s) <- zip [1..] ss]\n findDot = fst . head . filter ((== '.') . snd) . zip [1..]\n\nprint' :: Maybe [(Int, Int)] -> IO ()\nprint' Nothing = print (-1)\nprint' (Just xs)\n = mapM_ (\\(x, y) -> putStrLn (concat [show x, \" \", show y])) xs\n\nmain :: IO ()\nmain = do\n n <- readLn\n ss <- sequence $ replicate n getLine\n print' $ solve ss", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.List\n\nmain = do\n n <- read <$> getLine\n l <- replicateM n getLine\n case solve n l of\n [] -> putStrLn \"-1\"\n ls -> forM_ ls $ \\ (r,c) -> putStrLn $ show r ++ \" \" ++ show c\n\nsolve :: Int -> [String] -> [(Int,Int)]\nsolve n l | length r1 == n = r1\n | length r2 == n = map swap r2\n | otherwise = []\n where\n lt = transpose l\n r1 = zip l [1..] >>= f\n r2 = zip lt [1..] >>= f\n swap (a,b) = (b,a)\n \nf (s,r) = case findIndex (=='.') s of\n Just c -> return (r,c+1)\n Nothing -> fail \"impossible\"\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n css <- lines <$> getContents\n putStr.unlines.map(unwords.map show) $ solve css\n\nsolve :: [String] -> [[Int]]\nsolve css\n | all (any('.'==)) css = zipWith (:) [1..] [[i+1]|cs<-css,let Just i=findIndex ('.'==) cs]\n | all (any('.'==)) $ transpose css = map(\\[i,j]->[j,i]).solve $ transpose css\n | otherwise = [[-1]]\n"}], "negative_code": [{"source_code": "import Data.List (transpose)\n\nsolve :: [String] -> Maybe [(Int, Int)]\nsolve ss\n | findELine ss && findELine (transpose ss) = Nothing\n | not $ findELine ss = Just $ solve' ss\n | otherwise = Just $ map swap $ solve' $ transpose ss\n where\n findELine ss = any (all (== 'E')) ss\n swap (a, b) = (b, a)\n solve' ss = [(i, findDot s) | (i, s) <- zip [1..] ss]\n findDot = fst . head . filter ((== '.') . snd) . zip [1..]\n\nprint' :: Maybe [(Int, Int)] -> IO ()\nprint' Nothing = print (-1)\nprint' (Just xs)\n = print (length xs) >> mapM_ (\\(x, y) -> putStrLn (concat [show x, \" \", show y])) xs\n\nmain :: IO ()\nmain = do\n n <- readLn\n ss <- sequence $ replicate n getLine\n print' $ solve ss"}], "src_uid": "18554f1bb56e192d9a4bc75047fa5df5"} {"source_code": "import Data.List\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet [n, m] = map read . words . head $ input\n\tlet v = map (map read . words) . take n . tail $ input\n\tlet d = sort . map read . words $ input !! (n+1) :: [Int]\n\tlet sumc = map sum v\n\tlet sumr = [ sum $ map (!!i) v | i <- [0..m-1] ]\n\tlet divc i j = sort . map sum $ [take i sumc, take (j-i) . drop i $ sumc, drop j sumc]\n\tlet divr i j = sort . map sum $ [take i sumr, take (j-i) . drop i $ sumr, drop j sumr]\n\twriteFile \"output.txt\" . show . length $ [ 1 | i <- [1..n-1], j <- [i+1..n-1], d == divc i j ] ++ [ 1 | i <- [1..m-1], j <- [i+1..m-1], d == divr i j]\n", "positive_code": [{"source_code": "\nimport IO\nimport List (sort)\nimport Array (Array (..), array, bounds, (!))\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq 2 (solve (3,3,3) $ array ((1,1), (3,3)) [((i,j), 1) | i <- [1..3], j <- [1..3]]),\n Test \"2\" $ assertEq 3 (solve (3,6,6) $ array ((1,1), (2,5)) [((i,j), if i == 1 then 1 else 2) | i <- [1..2], j <- [1..5]])\n ]\n\ntest = mapM_ run\n [\n testInput\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: (Int, Int, Int) -> Array (Int, Int) Int -> Int\nsolve (a,b,c) d\n = solve' (map sum (map (\\i -> [d ! (i,j) | j <- [1..m]]) [1..n]))\n + solve' (map sum (map (\\j -> [d ! (i,j) | i <- [1..n]]) [1..m]))\n where\n (n, m) = snd $ bounds d\n abc = sort [a,b,c]\n solve' :: [Int] -> Int\n solve' xs = length [(i,j) | i <- [0..n-3], j <- [i+1..n-2],\n abc == sort [summ !! i, summ !! j - summ !! i, summ !! (n-1) - summ !! j]]\n where\n n = length xs\n summ = scanl1 (+) xs\n\nparseLine :: Read a => String -> IO [a]\nparseLine = return . map read . words \n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n [n, m] <- hGetLine hInput >>= parseLine\n d <- mapM (\\i -> hGetLine hInput >>= parseLine) [1..n]\n [a, b, c] <- hGetLine hInput >>= parseLine\n \n let res = solve (a,b,c) $ array ((1,1), (n,m)) [((i+1,j+1), d !! i !! j) | i <- [0..n-1], j <- [0..m-1]]\n \n hPrint hOutput res\n\n hClose hInput\n hClose hOutput\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet [n, m] = map read . words . head $ input\n\tlet v = map (map read . words) . take n . tail $ input\n\tlet d = sort . map read . words $ input !! (n+1) :: [Int]\n\tlet sumc = map sum v\n\tlet sumr = [ sum $ map (!!i) v | i <- [0..m-1] ]\n\tlet divc i j = sort . map sum $ [take i sumc, take (j-i) . drop i $ sumc, drop j sumc]\n\tlet divr i j = sort . map sum $ [take i sumr, take (j-i) . drop i $ sumr, drop j sumr]\n\twriteFile \"output.txt\" . show . length $ [ 1 | i <- [0..n-1], j <- [i+1..n-1], d == divc i j ] ++ [ 1 | i <- [0..m-1], j <- [i+1..m-1], d == divr i j]\n"}, {"source_code": "\nimport IO\nimport List (sort)\nimport Array (Array (..), array, bounds, (!))\n\n--------------------------------------------------------------------------------\n{-\nimport HUnit\n\ntestInput = TestList \"TestInput\"\n [\n Test \"1\" $ assertEq 2 (solve (3,3,3) $ array ((1,1), (3,3)) [((i,j), 1) | i <- [1..3], j <- [1..3]]),\n Test \"2\" $ assertEq 3 (solve (3,6,6) $ array ((1,1), (2,5)) [((i,j), if i == 1 then 1 else 2) | i <- [1..2], j <- [1..5]])\n ]\n\ntest = mapM_ run\n [\n testInput\n ]\n-}\n--------------------------------------------------------------------------------\n\nsolve :: (Int, Int, Int) -> Array (Int, Int) Int -> Int\nsolve (a,b,c) d\n = solve' (map sum (map (\\i -> [d ! (i,j) | j <- [1..m]]) [1..n]))\n + solve' (map sum (map (\\j -> [d ! (i,j) | i <- [1..n]]) [1..m]))\n where\n (n, m) = snd $ bounds d\n abc = sort [a,b,c]\n solve' :: [Int] -> Int\n solve' xs = length [(i,j) | i <- [0..n-3], j <- [i+1..n-1],\n abc == sort [summ !! i, summ !! j - summ !! i, summ !! (n-1) - summ !! j]]\n where\n n = length xs\n summ = scanl1 (+) xs\n\nparseLine :: Read a => String -> IO [a]\nparseLine = return . map read . words \n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n\n [n, m] <- hGetLine hInput >>= parseLine\n d <- mapM (\\i -> hGetLine hInput >>= parseLine) [1..n]\n [a, b, c] <- hGetLine hInput >>= parseLine\n \n let res = solve (a,b,c) $ array ((1,1), (n,m)) [((i+1,j+1), d !! i !! j) | i <- [0..n-1], j <- [0..m-1]]\n \n hPrint hOutput res\n\n hClose hInput\n hClose hOutput\n"}], "src_uid": "ef162ba7ca860369cf950d9a3686ddc8"} {"source_code": "module Main where\n\nf _ _ n t [] = n\nf u r n t (s:ss)\n | u == r && u /= 0 = f (if s == 'U' then u+1 else u) \n (if s == 'R' then r+1 else r) \n (if s == t then n+1 else n) \n s\n ss\n | s == 'U' = f (u+1) r n s ss\n | s == 'R' = f u (r+1) n s ss\n | otherwise = f u r n s ss\n\nmain = getLine >> getLine >>= print . f 0 0 0 '-'\n", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n temp <- getLine\n let n = read temp :: Int\n input <- getLine\n putStrLn $ show $ solve n input\n\nstep (a,b) 'R' = (a+1, b)\nstep (a,b) 'L' = (a-1, b)\nstep (a,b) 'U' = (a, b+1)\nstep (a,b) 'D' = (a, b-1)\n\nsolve n input = \n let \n cords = scanl step (0,0) input\n signs = filter (/=0) $ map (\\(a,b) -> signum (a-b)) cords\n diffs = zipWith (-) signs (tail signs)\n in (sum $ map abs diffs) `div` 2\n\n\n"}, {"source_code": "main = getLine >> getLine >>= print . solve\n\nsolve = (\\(_,_,_,c) -> c) . foldl walk (0,0,0,0) \n where walk (x,y,s,c) 'R'\n | x + 1 == y = (x+1, y, 2, c)\n | x + 1 > y && s == 2 = (x+1, y, 1, c+1)\n | otherwise = (x+1, y, s, c)\n walk (x,y,s,c) 'U'\n | y + 1 == x = (x, y+1, 1, c)\n | y + 1 > x && s == 1 = (x, y+1, 2, c+1)\n | otherwise = (x, y+1, s, c)\n"}, {"source_code": "f::Int->Int->Int->String->Int\nf c x y \"\"=0\nf c x y ('U':xs)=let t1=if x (Integer,Integer) -> String -> Int\nf _ _ [] = 0\nf (lastx,lasty) (x,y) (m:ms) = case m of \n 'U' -> if (lastx-lasty)*(x-y-1)<0 then 1+(f (x,y) (x,y+1) ms)\n else f (x,y) (x,y+1) ms\n 'R' -> if (lastx-lasty)*(x+1-y)<0 then 1+(f (x,y) (x+1,y) ms)\n else f (x,y) (x+1,y) ms\n"}, {"source_code": "main = getContents >>= print . solve 0 0 0 . last . lines\n\nsolve cnt _ _ [] = cnt\nsolve cnt x y ('U':'U':cs) = if x - y == 1\n then solve (cnt + 1) x (y + 2) cs\n else solve cnt x (y + 1) ('U':cs)\nsolve cnt x y ('R':'R':cs) = if y - x == 1\n then solve (cnt + 1) (x + 2) y cs\n else solve cnt (x + 1) y ('R':cs)\nsolve cnt x y ('U':cs) = solve cnt x (y + 1) cs\nsolve cnt x y ('R':cs) = solve cnt (x + 1) y cs\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport qualified Data.ByteString as B (getLine)\nimport qualified Data.ByteString.Char8 as C (readInt, words, unpack, reverse, dropWhile)\nimport qualified Data.Maybe as M (fromJust)\nimport Data.Char as C (isSpace)\n\nreadInt = fst . M.fromJust . C.readInt\nrstrip = C.reverse . C.dropWhile C.isSpace . C.reverse\n\nrun r (x, y) (g:h:gs) | g == h && g == 'R' && x + 1 == y = run (r + 1) (x + 2, y) gs\n | g == h && g == 'U' && x == y + 1 = run (r + 1) (x, y + 2) gs\nrun r (x, y) ('R':gs) = run r (x + 1, y) gs\nrun r (x, y) ('U':gs) = run r (x, y + 1) gs\nrun r (x, y) [] = r\n\nmain = do\n B.getLine\n (C.unpack . rstrip -> xxs) <- B.getLine\n putStrLn $ show $ run 0 (0, 0) xxs\n"}], "negative_code": [{"source_code": "f::Int->Int->String->Int\nf x y \"\"=0\nf x y (_:[])=0\nf x y ('U':'U':xs)=let t = if yInt->String->Int\nf x y \"\"=0\nf x y (_:[])=0\nf x y ('U':'U':xs)=let t = if y (Int,Int) -> String -> Int\nf _ _ [] = 0\nf (lastx,lasty) (x,y) (m:ms) = case m of \n 'U' -> if (lastx-lasty)*(x-y-1)<0 then 1+(f (x,y) (x,y+1) ms)\n else f (x,y) (x,y+1) ms\n 'R' -> if (lastx-lasty)*(x+1-y)<0 then 1+(f (x,y) (x+1,y) ms)\n else f (x,y) (x+1,y) ms\n"}], "src_uid": "e4381bd9f22c0e49525cc05cc5cd2399"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n x <- poi\n es <- replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve n x es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x es = (2*) $ maximum $ map (lowestOf!) $ takeWhile (\\u -> depthOf!u - depthOf!1 > depthOf!x - depthOf!u) $ iterate (parentOf!) x\n where\n g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]\n depthOf = array (1, n) $ dfs g (\\u cs d -> ((u, d):) . foldr ( (.) . ($ d + 1)) id cs) 0 [] :: UArray Int Int\n parentOf = array (1, n) $ dfs g (\\u cs p -> ((u, p):) . foldr ((.) . ($ u)) id cs) 0 [] :: UArray Int Int\n lowestOf = array (1, n) $ ($ []) $ snd $ dfs g (\\u cs -> let l = maximum $ (depthOf!u):map fst cs in (l, ((u, l):) . foldr ((.) . snd) id cs)) :: UArray Int Int\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n x <- poi\n es <- replicateM (n - 1) $ liftM2 (,) poi poi\n return $ show $ solve n x es\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x es = (2*) $ maximum $ map (lowestOf!) $ takeWhile (\\u -> depthOf!u - depthOf!1 > depthOf!x - depthOf!u) $ iterate (parentOf!) x\n where\n g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]\n depthOf = array (1, n) $ dfs g (\\u cs d -> ((u, d):) . foldl' (\\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int\n parentOf = array (1, n) $ dfs g (\\u cs p -> ((u, p):) . foldl' (\\p f -> p . f u) id cs) 0 [] :: UArray Int Int\n lowestOf = array (1, n) $ ($ []) $ snd $ dfs g (\\u cs -> let l = maximum $ (depthOf!u):map fst cs in (l, ((u, l):) . foldl' (\\p f -> p . snd f) id cs)) :: UArray Int Int\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Ord\nimport Data.Maybe\n\nreadInt = fst . fromJust . B.readInt\nreadInts = fmap readInt . B.words\n\nmaximaBy f xs = filter (\\x -> f x m == EQ) xs\n where m = maximumBy f xs\n\nsolve n x es = 2 * max aCnt bCnt\n where\n g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]\n aCnt = depthOf!head deepestUs - depthOf!1\n bCnt\n | x `elem` deepestUs = 0\n | otherwise = minimum $ map (\\u -> depthOf!u + depthOf!x - 2 * depthOf!lca u x) deepestUs\n deepestUs = map fst $ maximaBy (comparing snd) $ assocs depthOf\n depthOf = array (1, n) $ dfs (\\u cs d -> (u, d) : concatMap ($ d + 1) cs) (const []) 0 :: UArray Int Int\n lca a b = fromJust $ dfs go Nothing\n where\n go u cs\n | u == a || u == b = Just u\n | otherwise = case filter isJust cs of\n [v] -> v\n [_, _] -> Just u\n _ -> Nothing\n | otherwise = foldl (<|>) mzero cs\n dfs f z = go 0 1\n where\n go p u = case filter (/= p) (g!u) of\n [] -> f u [z]\n vs -> f u $ map (go u) vs\n\nmain = do \n [n, x] <- fmap readInts B.getLine\n es <- replicateM (n - 1) (fmap ((\\(u:v:_) -> (u, v)) . readInts) B.getLine)\n print $ solve n x es"}, {"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Ord\nimport Data.Maybe\n\nreadInt = fst . fromJust . B.readInt\nreadInts = fmap readInt . B.words\n\nmaximaBy f xs = filter (\\x -> f x m == EQ) xs\n where m = maximumBy f xs\n\nsolve n x es = g -- 2 * max aCnt bCnt\n where\n g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]\n aCnt = depthOf!head deepestUs - depthOf!1\n bCnt\n | x `elem` deepestUs = 0\n | otherwise = minimum $ map (\\u -> depthOf!u + depthOf!x - 2 * depthOf!lca u x) deepestUs\n deepestUs = map fst $ maximaBy (comparing snd) $ assocs depthOf\n depthOf = array (1, n) $ dfs (\\u cs d -> (u, d) : concatMap ($ d + 1) cs) (const []) 0 :: UArray Int Int\n lca a b = fromJust $ dfs go Nothing\n where\n go u cs\n | u == a || u == b || all isJust cs = Just u\n | otherwise = foldl (<|>) mzero cs\n dfs f z = go 0 1\n where\n go p u = case filter (/= p) (g!u) of\n [] -> f u [z]\n vs -> f u $ map (go u) vs\n\nmain = do \n [n, x] <- fmap readInts B.getLine\n es <- replicateM (n - 1) (fmap ((\\(u:v:_) -> (u, v)) . readInts) B.getLine)\n print $ solve n x es"}], "src_uid": "0cb9a20ca0a056b86885c5bcd031c13f"} {"source_code": "x#y@(h:_)|x String\nf s \n\t| null s=[]\n\t| null y=[x]\n\t| x >= (head y)=x:y\n\t| otherwise = y\n\twhere (x,y) = (head s,f $ tail s) \nmain = do \n\ts <- getLine\n\tputStrLn $ f s"}, {"source_code": "f s \n\t| null s=[]\n\t| null y=[x]\n\t| x >= (head y)=x:y\n\t| True = y\n\twhere (x,y) = (head s,f $ tail s) \nmain = do \n\ts <- getLine\n\tputStrLn $ f s"}, {"source_code": "\nsolve :: String -> String\nsolve s = reverse $ (head s') : solve' (head s') (tail s')\n where\n s' = reverse s\n solve' p [] = []\n solve' p (c:s)\n | p > c = solve' p s\n | otherwise = c : solve' c s\n\nmain :: IO ()\nmain = getLine >>= putStrLn . solve\n"}, {"source_code": "x#y@(h:_)|x String\nsolve \"\" = \"\"\nsolve s = filter (== max) s ++ solve rest\n where\n max = maximum s\n rest = reverse . takeWhile (/= max) $ reverse s\n\nmain :: IO ()\nmain = do\n s <- getLine\n putStrLn $ solve s"}, {"source_code": "x#[]=[x]\nx#y|x0=x:y\nmain=interact$foldr(#)[]"}, {"source_code": "x#y@(h:_)|x>= putStrLn.solve 'a' [].reverse\n\nsolve c ans [] = ans\nsolve c ans (x:xs)\n | c<=x = solve x (x:ans) xs\n | otherwise = solve c ans xs"}], "negative_code": [], "src_uid": "77e2a6ba510987ed514fed3bd547b5ab"} {"source_code": "import Data.List\nmain::IO()\nmain=do\n\tn<-getLine\n\tinput<-getLine\n\tlet\n\t\t(x:a)=sort $ map read (words input)::[Int]\n\t\tis=foldl (\\a b -> a && b `mod` x ==0 ) True a\n\tprint $ if is then x else -1\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\tgetLine\n\t(a:as) <- sort . map read . words <$> getLine\n\tprint $ if all ( ( == 0 ) . ( `mod` a ) ) as then a else -1\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\tgetLine\n\t(a:as) <- sort . map read . words <$> getLine\n\tprint $ if solve a as then a else -1\n\nsolve n [] = True\nsolve n (a:as)\n\t| mod a n == 0 = solve n as\n\t| otherwise = False\n"}, {"source_code": "main = do\n a <- map (read :: String -> Int ) . words <$> (getLine >> getLine)\n let b = foldr1 gcd a\n print $ if b `elem` a then b else -1 \n"}, {"source_code": "import Data.List\n\nverify k [] = k\nverify k (x:xs) = if x `mod` k == 0 then verify k xs else -1\n\ncheck (x:xs) = verify x xs\n\nmain = interact $ show . check . sort . map read . tail . words\n"}, {"source_code": "import Data.List\n\nverify k [] = k\nverify k (x:xs) = if x `mod` k == 0 then verify k xs else -1\n\ncheck (x:xs) = verify x xs\n\nunique ::[Int] -> [Int]\nunique [] = []\nunique [x] = [x]\nunique (x:y:xs) = if x /= y then x : (unique $ y: xs) else unique $ y: xs\n\nmain = interact $ show . check . unique . sort . map read . tail . words\n"}, {"source_code": "import Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve as\n | all ((== 0) . flip mod min) as = min\n | otherwise = -1\n where\n min = minimum as\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n print $ solve as\n"}, {"source_code": "import Data.List (foldl')\n\nmain = getLine >> fmap (solve.map read.words) getLine >>= print\n\nsolve :: [Integer] -> Integer\nsolve xs = foldl' f ans xs\n where ans = minimum xs\n f (-1) _ = -1\n f ans next | mod next ans == 0 = ans\n | otherwise = -1\n"}, {"source_code": "import Data.List (foldl')\n\nmain = getLine >> fmap (solve.map read.words) getLine >>= print\n\nsolve :: [Integer] -> Integer\nsolve xs = if isP then ans else -1\n where (isP, ans) = foldl' f (True, head xs) (tail xs) \n f (isP', ans') next | g == next = (True, g)\n | g == ans' = (isP', g)\n | otherwise = (False, g)\n where g = gcd ans' next\n"}], "negative_code": [{"source_code": "main = getLine >> getLine >>= print . foldr1 gcd . map (read :: String -> Int ) . words\n"}, {"source_code": "main = do\n a <- map (read :: String -> Int ) . words <$> (getLine >> getLine)\n let b = foldr1 gcd a\n print $ if b /= 1 || (b == 1 && 1 `elem` a) then b else -1 \n"}, {"source_code": "import Data.List\n\nverify k [] = k\nverify k (x:xs) = if x `mod` k == 0 then verify k xs else -1\n\ncheck (x:xs) = verify x xs\n\nunique ::[Int] -> [Int]\nunique [] = []\nunique [x] = [x]\nunique (x:y:xs) = if x /= y then x : (unique $ y: xs) else unique $ y: xs\n\n-- main = interact $ show . check . unique . sort . map read . tail . words\nmain = interact $ show . unique . sort . map read . tail . words"}, {"source_code": "import Data.List (foldl')\n\nmain = getLine >> fmap (solve.map read.words) getLine >>= print\n\nsolve :: [Int] -> Int\nsolve xs = foldl' f (head xs) (tail xs)\n where f (-1) _ = -1\n f current next | mod next current == 0 = current\n | mod current next == 0 = next\n | otherwise = -1\n"}], "src_uid": "b0ffab0bf169f8278af48fe2d58dcd2d"} {"source_code": "import Control.Monad\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadListLn :: IO [Int]\nreadListLn = (map (fst . fromJust . B.readInt) . B.words) `liftM` B.getLine\n\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n ss <- forM [1..n] (const readListLn)\n let arrHome = accumArray (+) 0 (1, 10^5) $ map (\\[x, _] -> (x, 1)) ss :: UArray Int Int\n-- let arrForeign = accumArray (+) 0 (1, 10^5) $ map (\\[_, y] -> (y, 1)) ss :: UArray Int Int\n forM_ ss $ \\[_, y] -> do\n putStrLn $ let native = 2 * (n - 1) - forgn\n forgn = n - 1 - arrHome ! y\n in (show native) ++ \" \" ++ (show forgn)\n \n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [(Int, Int)] -> [(Int, Int)]\nsolve s = map f s\n where (xs, ys) = unzip s\n xCnts = countof $ countup xs\n enemy = (length s) - 1\n f (x, y) = (enemy + dup, enemy - dup)\n where dup = xCnts y\n\nmain :: IO ()\nmain = do\n n <- readInt\n c <- replicateM n $ toTuple <$> readInts\n forM_ (solve c) $ \\(a, b) -> do\n printf \"%d %d\\n\" a b\n\ntoTuple [a, b] = (a, b)\ntoNumber = fst . fromMaybe (0, \"\")\nreadInt = toNumber . BS.readInt <$> BS.getLine\nreadInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\n\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Maybe\nimport Data.List\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as LBS\nimport Control.Applicative ((<$>))\nimport Control.Arrow ((&&&), first, second)\nimport Control.Monad\nimport Text.Printf (printf)\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n teams <- replicateM n $ (map (fst . fromJust . BS.readInt) . BS.words) <$> BS.getLine :: IO [[Int]]\n let !table = IM.fromList . map (head &&& length) . group . sort . map head $ teams\n forM_ (zip [1..] teams) $ \\(i, [_, away]) -> do\n let !c = n - 1 + IM.findWithDefault 0 away table\n printf \"%d %d\\n\" c (2 * (n - 1) - c)\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\n\n-- For Input\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n--import qualified Data.ByteString.Lex.Double as BSD\nimport Data.Char (isSpace)\nimport Data.IORef\nimport Text.Printf\n\n-- Data Structure Imports\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\n\n-- These should be imported by default... :)\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\n--------------------------------------------------------------------------------\n------------------------------- SOLUTION ---------------------------------------\n--------------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do \n all <- BS.getContents\n input <- newIORef all\n let parse = next input \n n <- parse int\n (hs,as) <- fmap unzip $ parse $ readMany int2 n\n let home = Map.fromList . map (head &&& length) . group $ sort hs\n forM_ as $ \\a ->\n let extraHome = Map.findWithDefault 0 a home \n in putStrLn $ show (n + extraHome - 1) ++ \" \" ++ show (n - extraHome - 1)\n \n\n--------------------------------------------------------------------------------\n-------------------------- IO Function Helpers ---------------------------------\n--------------------------------------------------------------------------------\n\ntype Parser a = BSC.ByteString -> (a, BSC.ByteString)\n\nint :: Parser Int\nint = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt\n\nint2 :: Parser (Int, Int)\nint2 = uncurry (first . (,)) . second int . int\n\nint3 :: Parser (Int, Int, Int)\nint3 = uncurry (first . (uncurry (,,))) . second int . int2\n\n--double :: Parser Double\n--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble\n\nchar :: Parser Char\nchar = BSC.head &&& BSC.tail\n\nletter :: Parser Char\nletter = second (BSC.dropWhile isSpace) . char \n\nstring :: Parser String\nstring = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)\n\nreadMany :: Parser a -> Int -> Parser [a]\nreadMany f n bs = first reverse $ \n foldr (\\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]\n\nintMany :: Int -> Parser [Int]\nintMany = readMany int\n\nnext :: IORef BSC.ByteString -> Parser a -> IO a\nnext input parse = do\n bs <- readIORef input\n let (x, bs') = parse bs\n writeIORef input bs'\n return x\n\n{- CODE JAM input\n\n cases <- parse int\n forM_ [1..cases] $ \\caseNum -> do\n -- Read Data \n -- let solution = \n -- solution <- \n printf \"Case #%d: %d\\n\" caseNum solution\n-}\n\n"}], "negative_code": [], "src_uid": "7899a22cee29bb96d671f6188f246c21"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nmain=getLine>>map(fst.fromJust.B.readInt).B.words<$>B.getLine>>=print.maximum.map(\\l->if head l==0 then 0 else length l).group.take 400000.cycle", "positive_code": [{"source_code": "longestOnesSequence ans cur [] = ans\nlongestOnesSequence ans cur (0:xs) = longestOnesSequence ans 0 xs\nlongestOnesSequence ans cur (1:xs) = longestOnesSequence (max ans $ cur + 1) (cur + 1) xs\n\nmain = do\n line' <- getLine\n line <- getLine\n let arr = map read $ words line\n putStrLn . show $ longestOnesSequence 0 0 $ arr ++ arr"}, {"source_code": "foldInt :: (Int, Int) -> Char -> (Int, Int)\nfoldInt (a,b) '0' = (0,b)\nfoldInt (a,b) '1' = (a+1, max b (a+1))\nfoldInt (a,b) _ = (a,b)\n\ncalc :: [Char] -> Int\ncalc c = snd $ foldl foldInt (0,0) c\n\nmain = do {\n n <- getLine;\n a <- getLine;\n putStrLn $ show $ calc (a++a);\n}"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nprocess0 [] = 0\nprocess0 (x:xs) = case x of\n 0 -> process0 xs\n 1 -> process1 1 xs\n\nprocess1 n [] = n\nprocess1 n (x:xs) = case x of\n 1 -> process1 (n + 1) xs\n 0 -> max n (process0 xs)\n\nmain = do\n throwaway <- getLine\n line <- getLine\n let\n info :: [Integer]\n info = map read $ words line\n print (process0 (info ++ info))\n"}, {"source_code": "module Main where\n-- import qualified Data.ByteString.Char8 as C\nimport Control.Monad\nimport Data.List\n{- main = do\n C.getLine\n a <- C.filter (\\x -> x /= ' ') <$> C.getLine\n let b = map C.length $ filter (C.elem '1') $ C.group $ C.concat $ [a,a]\n print $ if null b then 0 else maximum b\n-}\n\nmain = do\n getLine\n a <- filter (\\x -> x /= ' ') <$> getLine\n let b = map length $ filter ('1' `elem`) $ group $ concat $ [a,a]\n print $ if null b then 0 else maximum b"}, {"source_code": "solve [] res cur = max res cur\nsolve (0:xs) res cur = solve xs (max res cur) 0\nsolve (1:xs) res cur = solve xs res (cur + 1)\n\nmain = do\n n <- (read :: String -> Int) <$> getLine\n lst <- (map read :: [String] -> [Int]) <$> words <$> getLine\n putStrLn (show (min n (solve (lst ++ lst) 0 0)))\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsolve :: [Int] -> Int\nsolve xs \n | all (==0) xs = 0 \n | otherwise = (maximum . map length . filter ((==1) . head) . group) ys \n where ys = xs ++ xs\n\nmain :: IO ()\nmain = do\n _ <- readInt\n xs <- readInts\n print $ solve xs"}, {"source_code": "import Data.List\nmain = interact $ show . solve . map read . tail . words\nsolve as = maximum $ (0 :) $ map length $ filter ((> 0) . head) $ group $ as ++ as\n"}, {"source_code": "-- import Debug.Trace\nimport Text.Printf\nimport Control.Monad\n\nglwr :: Read a => IO [a]\nglwr = fmap (map read . words) getLine\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ls <- glwr\n print $ maxConRest ls\n\nmaxConRest xs = uncurry max $ foldr accMax (length h, 0) ls\n where\n (h, ls) = break (< 1) xs\n\naccMax n (r, m)\n | n < 1 = (0, max r m)\n | 0 < 1 = (r+1, m)\n\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ show . solve . map read . drop 1 . words\n\nsolve :: [Int] -> Int\nsolve = maximum . map sum . group . duplList\n\nduplList :: [Int] -> [Int]\nduplList l = l ++ l\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n{-# Options_GHC -O2 #-}\nimport Data.ByteString.Builder\nimport Data.Monoid\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)\nimport Data.Char\nimport Data.List\n\ngetSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int\n\nru, ri :: C.ByteString -> Int\n\nru = C.foldl' (\\a c -> a * 10 - 48 + ord c) 0\nri s\n | C.head s == '-' = negate $ ru $ C.tail s\n | otherwise = ru s\n\nsolve :: [Int] -> Int\nsolve (n:a')\n | all (== 0) a = 0\n | otherwise = maximum $map length $ filter ( ( == 1) . head) $ group $ a ++ a\n where\n a = take n a'\n\nmain :: IO ()\nmain = print . solve . map ru . C.words =<< C.getContents\n"}, {"source_code": "import Data.List\n\n\nsolve :: [Int] -> Int\nsolve xs = ts where\n ts = if all (\\x -> x == 0) xs then 0 \n else maximum . map length . \n filter (all (\\x -> x == 1)) . group $ (xs ++ xs)\n\nrInt :: String -> Int\nrInt = read\n\nmain :: IO ()\nmain = interact $ show. solve . head . (map . map) rInt . map words . tail . lines\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.Bits\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\nprocess :: [Int] -> Int\nprocess hours = maximum . map (\\l -> if head l == 0 then 0 else length l) . group . take (length hours * 2) . cycle $ hours\n\nmain = do\n n <- getInt\n hours <- getInts\n print $ process hours\n"}, {"source_code": "import Data.List\nf (\"0\":_)=0\nf l=length l\nmain=getLine>>getLine>>=print.maximum.map f.group.take 400000.cycle.words"}, {"source_code": "import Data.List\nmain=getLine>>map read.words<$>getLine>>=print.maximum.map(\\l->if head l==0 then 0 else length l).group.take 400000.cycle"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\n--import Debug.Trace\n\nimport System.IO\nimport GHC.Generics\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Either\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Foldable as Foldable\nimport Data.Char\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Data.List\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.Array.ST.Safe as SA\nimport qualified Data.Array.IO.Safe as IA\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.Bits\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]\ngetDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines :: Show a => [a] -> IO ()\nprintLines = mapM_ print\nprintStrs = mapM_ putStrLn :: [String] -> IO ()\nprintList = putStrLn . intercalate \" \" . map show :: [Int] -> IO ()\n\n---- Answer Code Section ----\n\nmain = getInt >> getInts >>= print . maximum . map (\\l -> if head l == 0 then 0 else length l) . group . take 400000 . cycle\n"}, {"source_code": "readBool a = if (read a) == 0 then True else False\n \nsolve sch = (pre + head l) : (tail l)\n where\n findPre (True : _) = 0\n findPre (False : l) = 1 + findPre l\n pre = findPre sch\n calcL [] acc res = acc : res\n calcL (True : l) acc res = calcL l 0 (acc : res)\n calcL (False : l) acc res = calcL l (acc + 1) res\n l = calcL sch 0 []\n \nmain = do\n a <- getLine\n sch <- fmap ((map readBool) . words) getLine\n putStrLn . show . maximum $ solve sch"}], "negative_code": [{"source_code": "module Main where\nimport qualified Data.ByteString.Char8 as C\nimport Control.Monad\n\nmain = do\n C.getLine\n a <- C.filter (\\x -> x /= ' ') <$> C.getLine\n let b = map C.length $ filter (C.elem '1') $ C.group $ C.concat $ [a,a]\n print $ if null b then 0 else maximum b"}, {"source_code": "import Data.List\nmain=getLine>>getLine>>=print.maximum.groupBy(\\a b->a==b&&b==\"1\").take 400000.cycle.words"}], "src_uid": "fcd88c7b64da4b839cda4273d928429d"} {"source_code": "import Data.List\nimport Data.Either\nimport Control.Monad\n\nisgood :: [String] -> Bool\nisgood s@[a,b,c] = \"abc\" == (map head s) && (length c `elem` map length [a, b])\nisgood _ = False\n\nmain = do\n s <- fmap group getLine\n putStrLn $ if isgood s then \"YES\" else \"NO\"", "positive_code": [{"source_code": "import Data.List\n\nmain = do\n s <- getLine\n let ta = length . elemIndices 'a' $ s\n let tb = length . elemIndices 'b' $ s\n let tc = length . elemIndices 'c' $ s\n let p1 = ta > 0 && tb > 0 && (tc == ta || tc == tb)\n let p2 = s == sort s\n putStrLn $ if p1 && p2 then \"YES\" else \"NO\"\n"}, {"source_code": "main = interact $ f.g.head.lines\n\ng :: String -> Bool\ng s = length a > 0 && length b > 0 && length d == 0 && (length a == length c || length b == length c)\n where (a, bcd) = span (== 'a') s\n (b, cd) = span (== 'b') bcd\n (c, d) = span (== 'c') cd\n\nf :: Bool -> String\nf True = \"YES\\n\"\nf False = \"NO\\n\""}], "negative_code": [{"source_code": "main = interact $ f.g.head.lines\n\ng :: String -> Bool\ng s = length d == 0 && (length a == length c || length b == length c)\n where (a, bcd) = span (== 'a') s\n (b, cd) = span (== 'b') bcd\n (c, d) = span (== 'c') cd\n\nf :: Bool -> String\nf True = \"YES\\n\"\nf False = \"NO\\n\""}, {"source_code": "main = interact $ f.g\n\ng :: String -> Bool\ng s = length d == 0 && (length a == length c || length b == length c)\n where (a, bcd) = span (== 'a') s\n (b, cd) = span (== 'b') bcd\n (c, d) = span (== 'c') cd\n\nf :: Bool -> String\nf True = \"YES\\n\"\nf False = \"NO\\n\""}], "src_uid": "6581dbaff7eb52b63ccfe9c0c4117c09"} {"source_code": "import Data.Char\nimport Data.List\n\nmain=interact$solve.filter(not.null).map(dropWhile(' '==)).tail.lines\n\nsolve :: [String] -> String\nsolve (x:xs)\n | isPrefixOf \"try\" x = solve xs\n | isPrefixOf \"catch\" x = solve xs\n | otherwise = throw etype xs\n where\n etype = filter isAlpha.dropWhile('('/=)$x\n\nthrow etype [] = \"Unhandled Exception\"\nthrow etype (x:xs)\n | isPrefixOf \"try\" x = throw etype $ go 1 xs\n | etype == ctype = cmsg\n | otherwise = throw etype xs\n where\n (y,('\\\"':z)) = break('\\\"'==).dropWhile('('/=)$x\n ctype = filter isAlpha y\n cmsg = takeWhile ('\\\"' /=)z\n\ngo 0 xs = xs\ngo try (x:xs)\n | isPrefixOf \"try\" x = go (try+1) xs\n | otherwise = go (try-1) xs", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\n\nnewtype Parser a = Parser { runParser :: String -> (a,String) }\n\ninstance Functor Parser where\n fmap f (Parser a) = Parser (a >>> first f)\n\ninstance Monad Parser where\n Parser p >>= f = Parser (\\s ->\n let (a,s') = p s in runParser (f a) s')\n return a = Parser (\\s -> (a,s))\n\ninstance Applicative Parser where\n pure = return\n (<*>) = ap\n\ndata Op = Try | Throw String | Catch String String | Nop deriving(Show)\n\nparseLine :: Parser Op\nparseLine = do\n spaces\n tk <- token\n case tk of\n \"try\" -> return Try\n \"throw\" -> do\n s <- paren token\n return (Throw s)\n \"catch\" -> paren $ do\n ex <- token\n comma\n ms <- dquoted letters\n return $ Catch ex ms\n _ -> return Nop\n \npeek :: Parser Char\npeek = Parser $ \\(c:cs) -> (c,c:cs)\n\nconsume :: Parser ()\nconsume = Parser $ \\(c:cs) -> ((),cs)\n\nspaces = do\n ch <- peek\n if ch == ' ' then consume >> spaces else return ()\n\ntoken = do\n c <- peek\n if isAlphaNum c then do\n consume\n cs <- token\n return (c:cs)\n else spaces >> return \"\"\n \nparen p = do\n consume\n spaces\n a <- p\n consume\n spaces\n return a\n\ncomma = consume >> spaces\ndquoted p = do\n consume\n l <- p\n consume\n return l\n\nletters = do\n c <- peek\n if c == '\"' then return \"\" else do\n consume\n cs <- letters\n return (c:cs)\n\nmain = do\n n':ss <- lines <$> getContents \n let n = read n'\n let p = flip map (take n ss) (\\s -> fst $ runParser parseLine (s++\"\\n\"))\n let !ps = fst $ parsePrograms p\n let !res = execProgram ps\n case res of\n Message s -> putStrLn s\n Exception ex -> putStrLn \"Unhandled Exception\"\n\ndata Program = PTryCatch String String [Program] \n | PThrow String\n | PNop deriving(Show)\n\nparsePrograms :: [Op] -> ([Program],[Op])\nparsePrograms [] = ([],[])\nparsePrograms ops@(Catch _ _:_) = ([],ops)\nparsePrograms ops = (p:ps,ops'')\n where\n (p,ops') = parseProgram ops\n (ps,ops'') = parsePrograms ops'\n\nparseProgram :: [Op] -> (Program,[Op])\nparseProgram (Throw ex:ops) = (PThrow ex,ops)\nparseProgram (Nop:ops) = (PNop,ops)\nparseProgram (Try:ops) = (PTryCatch ex ms ps,ops')\n where\n (ps,Catch ex ms:ops') = parsePrograms ops\n\ndata RVal = Unit | Exception String | Message String\n deriving(Show)\n\nexecProgram :: [Program] -> RVal\nexecProgram ps = go ps\n where\n go [] = Unit\n go (PNop:ps) = go ps\n go (PThrow ex:ps) = Exception ex\n go (PTryCatch ex ms p:ps) = case execProgram p of\n Exception ex' | ex == ex' -> Message ms\n Unit -> go ps\n v -> v\n"}, {"source_code": "\nimport Maybe (fromMaybe)\nimport Monad (liftM)\n\n{-\nimport HUnit\n\ntestParseLine :: Test\ntestParseLine = TestList \"TestParseLine\"\n [\n Test \"#1\" $ assertEq EmptyLine $ parseLine \"\",\n Test \"#2\" $ assertEq EmptyLine $ parseLine \" \",\n Test \"#3\" $ assertEq Try $ parseLine \"try\",\n Test \"#4\" $ assertEq Try $ parseLine \" try \",\n Test \"#5\" $ assertEq (Throw \"abc\") $ parseLine \"throw(abc)\",\n Test \"#6\" $ assertEq (Throw \"abc\") $ parseLine \"throw ( abc ) \",\n Test \"#7\" $ assertEq (Throw \"abc\") $ parseLine \" throw (abc)\",\n Test \"#8\" $ assertEq (Catch \"abc\" \"is abc\") $ parseLine \"catch(abc,\\\"is abc\\\")\",\n Test \"#9\" $ assertEq (Catch \"abc\" \"is abc\") $ parseLine \" catch ( abc , \\\"is abc\\\" ) \",\n Test \"#10\" $ assertEq (Catch \"abc\" \"is abc\") $ parseLine \" catch (abc,\\\"is abc\\\")\",\n Test \"#11\" $ assertEq (Catch \"abc\" \"fdfd\") $ parseLine \" catch (abc,\\\"fdfd\\\")\"\n \n ]\n\ntestInput :: Test\ntestInput = Test \"TestInput\" $ assertEq (Just \"is something\") $ solve\n [\n \"try \",\n \" try \",\n \" throw(A) \",\n \" catch(B,\\\"is B\\\") \",\n \" try \",\n \" \",\n \" catch(A,\\\"is A\\\") \",\n \"catch(A,\\\"is something\\\") \"\n ]\n\ntest :: IO ()\ntest = mapM_ run\n [\n testParseLine,\n testInput\n ]\n-}\n\ntype Type = String\ntype Message = String\n\ndata Line = EmptyLine | Try | Throw Type | Catch Type Message\n deriving\n (Eq, Show)\n\n(?) :: Bool -> a -> a -> a\n(?) True = const\n(?) False = flip const\n\nreplace :: Eq a => [a] -> a -> [a] -> [a]\nreplace cs c s = map (\\x -> (elem x cs) ? c $ x) s\n\nparseLine :: String -> Line\nparseLine line = case words (replace \"(),\" ' ' line) of\n [] -> EmptyLine\n [\"try\"] -> Try\n [\"throw\", s] -> Throw s\n (\"catch\" : s1 : _) -> Catch s1 (getMessage line)\n where\n getMessage = takeWhile (/= '\\\"') . tail . dropWhile (/= '\\\"')\n\nsolve :: [String] -> Maybe String\nsolve lines = solve' Nothing 0 (map parseLine lines)\n where\n solve' _ _ [] = Nothing\n solve' Nothing n (line : lines) = case line of\n EmptyLine -> solve' Nothing n lines\n Try -> solve' Nothing (n+1) lines\n Throw t -> solve' (Just (t, n)) n lines\n Catch _ _ -> solve' Nothing (n-1) lines\n solve' f@(Just (t', n')) n (Catch t m : lines)\n | n' /= n = solve' f (n-1) lines\n | t' /= t = solve' (Just (t', n'-1)) (n-1) lines\n | otherwise = Just m\n solve' f@(Just (t', n')) n (line : lines) = case line of\n EmptyLine -> solve' f n lines\n Try -> solve' f (n+1) lines\n Throw t -> error $ concat [\"find two throw in lines: \", show n', \", \", show n]\n\nmain :: IO ()\nmain = do\n n <- readLn\n lines' <- liftM (take n . lines) getContents\n putStrLn $ fromMaybe \"Unhandled Exception\" $ solve lines'\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ans <- solve <$> B.getContents\n case ans of\n Catched msg -> B.putStrLn msg\n _ -> putStrLn \"Unhandled Exception\"\n\nsolve :: B.ByteString -> Val\nsolve bs = evalExpr $ evalParser expr bs\n\ntype Exception = B.ByteString\ntype Message = B.ByteString\n\ndata Expr = Throw Exception | TryCatch [Expr] Exception Message\ndata Val = Bottom | Catched Message | UnCatched Exception\n \nevalParser :: Parser [Expr] -> State -> [Expr]\nevalParser expr st = case runParser expr st of\n Just (result,_) -> result\n Nothing -> error \"parse error\"\n\nevalExpr :: [Expr] -> Val\nevalExpr (Throw excp : _) = UnCatched excp\nevalExpr (TryCatch es excp0 msg : rest) =\n case evalExpr es of\n Bottom -> evalExpr rest\n Catched msg -> Catched msg\n UnCatched excp1\n | excp0 == excp1 -> Catched msg\n | otherwise -> UnCatched excp1\nevalExpr [] = Bottom\n\nexpr :: Parser [Expr]\nexpr = many (trycatch <|> throw)\n\nthrow = do\n spaces\n string \"throw\"\n spaces\n char '('\n spaces\n excp <- letters\n spaces\n char ')'\n spaces\n return $ Throw excp\n\ntrycatch = do\n spaces\n string \"try\"\n spaces\n exprs <- expr\n spaces\n string \"catch\"\n spaces\n char '('\n spaces\n excp <- letters\n spaces\n char ','\n spaces\n msg <- between '\\\"' '\\\"'\n spaces\n char ')'\n spaces\n return $ TryCatch exprs excp msg\n\ntype State = B.ByteString\ndata Parser t = Parser {runParser :: State -> Maybe (t, State)}\n\ninstance Monad Parser where\n return t = Parser $ \\st -> Just (t,st)\n m >>= f = Parser $ \\st -> do\n (t,rest) <- runParser m st\n runParser (f t) rest\n\ninstance MonadPlus Parser where\n mzero = Parser $ const Nothing\n mplus p q = Parser $ \\st ->\n runParser p st `mplus` runParser q st\n\ninstance Functor Parser where\n fmap f m = Parser $ \\st ->\n fmap (\\(t,rest) -> (f t,rest)) $ runParser m st\n\ninstance Applicative Parser where\n pure = return\n (<*>) = ap\n\ninstance Alternative Parser where\n empty = mzero\n (<|>) = mplus\n\ngetState :: Parser State\ngetState = Parser $ \\st -> Just (st,st)\n\nputState :: State -> Parser ()\nputState st = Parser $ const $ Just ((),st)\n\nmodifyState :: (State -> State) -> Parser ()\nmodifyState f = Parser $ \\st -> Just ((),f st)\n\nchar :: Char -> Parser ()\nchar c = do\n bs <- getState\n guard (not (B.null bs) && B.index bs 0 == c)\n modifyState B.tail\n\nstring :: B.ByteString -> Parser ()\nstring bs = do\n cs <- getState\n guard $ bs `B.isPrefixOf` cs\n modifyState . B.drop $ B.length bs\n\nspaces :: Parser ()\nspaces = do\n bs <- getState\n putState $ B.dropWhile isSpace bs\n\nletters :: Parser B.ByteString\nletters = do\n (xs,ys) <- B.span isLetter <$> getState\n putState ys\n return xs\n\nbetween :: Char -> Char -> Parser B.ByteString\nbetween c d = do\n char c\n (xs,ys) <- B.break (d==) <$> getState\n putState ys\n char d\n return xs\n\neof :: Parser ()\neof = do\n spaces\n rest <- getState\n guard $ B.null rest\n"}, {"source_code": "\ndata Statement = Try | Throw String | Catch String String deriving Show\n\ndata Program = Trycatch String String Program | ThrowProg String | EmptyProg | SeqProg Program Program deriving Show\n\ntrim = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')\n\nunbrace l = case trim l of\n '(':l' -> case reverse l' of\n ')':l'' -> reverse l''\n\nunquote l = case trim l of\n '\"':l' -> case reverse l' of\n '\"':l'' -> reverse l''\n\nparse :: [String] -> [Statement]\nparse s = s >>= \\l -> case (dropWhile (==' ') l) of\n ('t':'r':'y':_) -> [Try]\n ('t':'h':'r':'o':'w':l) -> [Throw $ trim $ unbrace l]\n ('c':'a':'t':'c':'h':l) -> case span (/=',') $ unbrace l of\n (l, ',':r) -> [Catch (trim l) (unquote r)]\n [] -> []\n\ngo :: [Statement] -> Maybe (String, Int) -> String\ngo (Try : t) Nothing = go t Nothing\ngo (Catch ex msg : t) (Just (err, 0)) | err == ex = msg\n | otherwise = go t (Just (err, 0))\ngo (Catch _ _ : t) Nothing = go t Nothing\ngo (Catch _ _ : t) (Just (err, i)) = go t (Just (err, i-1))\ngo (Throw err : t) Nothing = go t (Just (err, 0))\ngo (Try : t) (Just (err, i)) = go t (Just (err, i+1))\ngo [] (Just (err, 0)) = \"Unhandled Exception\"\n\nmain = interact $ (`go` Nothing) . parse . tail . lines\n"}, {"source_code": "import Data.Char\nimport qualified Data.ByteString.Char8 as C\n\ndata Result\n = Ex C.ByteString\n | Msg C.ByteString\n | Nil\n | End\n deriving (Eq, Show)\n\ntype Parser = State C.ByteString\n\nnext :: (Char -> Bool) -> Parser C.ByteString\nnext f = do\n modify $ C.dropWhile $ not . f\n (x, y) <- gets $ C.span f\n put y\n return x\n\nparseMany :: Parser Result\nparseMany = do\n first <- parse\n if first == End\n then return Nil\n else do\n rest <- parseMany\n return $ if first /= Nil then first else rest\n\nparse :: Parser Result\nparse = do\n modify $ C.dropWhile $ not . isLetter\n h <- gets C.head\n if h /= 't'\n then return End\n else do\n key <- next $ isLetter\n if key == C.pack \"throw\"\n then do\n ex <- next $ isLetter\n return $ Ex ex\n else do\n result <- parseMany\n _ <- next $ isLetter -- \"catch\"\n ex <- next $ isLetter\n _ <- next $ (=='\"')\n msg <- next $ (/='\"')\n if result == Ex ex\n then return $ Msg msg\n else return result\n\nmain :: IO ()\nmain = do\n _ <- C.getLine\n s <- C.getContents\n let ans = case fst $ runState parseMany $ C.append s $ C.pack \" return\" of\n Ex _ -> \"Unhandled Exception\"\n Msg msg -> C.unpack msg\n _ -> \"Error\"\n putStrLn ans\n\n-- Control.Monad.State\nnewtype State s a = State {\n runState :: s -> (a, s)\n}\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a', s') = runState m s in runState (f a') s'\n\nget :: State s s\nget = State $ \\s -> (s, s)\n\nput :: s -> State s ()\nput s = State $ \\_ -> ((), s)\n\nmodify :: (s -> s) -> State s ()\nmodify f = State $ \\s -> ((), f s)\n\ngets :: (s -> a) -> State s a\ngets f = State $ \\s -> (f s, s)\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\n\nnewtype Parser a = Parser { runParser :: String -> (a,String) }\n\ninstance Functor Parser where\n fmap f (Parser a) = Parser (a >>> first f)\n\ninstance Monad Parser where\n Parser p >>= f = Parser (\\s ->\n let (a,s') = p s in runParser (f a) s')\n return a = Parser (\\s -> (a,s))\n\ninstance Applicative Parser where\n pure = return\n (<*>) = ap\n\ndata Op = Try | Throw String | Catch String String | Nop deriving(Show)\n\nparseLine :: Parser Op\nparseLine = do\n spaces\n tk <- token\n case tk of\n \"try\" -> return Try\n \"throw\" -> do\n s <- paren token\n return (Throw s)\n \"catch\" -> paren $ do\n ex <- token\n comma\n ms <- dquoted letters\n return $ Catch ex ms\n _ -> return Nop\n \npeek :: Parser Char\npeek = Parser $ \\cs -> (if null cs then '\\0' else head cs,cs)\n\nconsume :: Parser ()\nconsume = Parser $ \\cs -> ((),if null cs then cs else tail cs)\n\nspaces = do\n ch <- peek\n if ch == ' ' then consume >> spaces else return ()\n\ntoken = do\n c <- peek\n if isAlphaNum c then do\n consume\n cs <- token\n return (c:cs)\n else spaces >> return \"\"\n \nparen p = do\n consume\n spaces\n a <- p\n consume\n spaces\n return a\n\ncomma = consume >> spaces\ndquoted p = do\n consume\n l <- p\n consume\n return l\n\nletters = do\n c <- peek\n if c == '\"' then return \"\" else do\n consume\n cs <- letters\n return (c:cs)\n\nmain = do\n n':ss <- lines <$> getContents \n let n = read n'\n let p = map (fst . runParser parseLine) (take n ss)\n let !ps = fst $ parsePrograms p\n let !res = execProgram ps\n case res of\n Message s -> putStrLn s\n Exception ex -> putStrLn \"Unhandled Exception\"\n\ndata Program = PTryCatch String String [Program] \n | PThrow String\n | PNop deriving(Show)\n\nparsePrograms :: [Op] -> ([Program],[Op])\nparsePrograms [] = ([],[])\nparsePrograms ops@(Catch _ _:_) = ([],ops)\nparsePrograms ops = (p:ps,ops'')\n where\n (p,ops') = parseProgram ops\n (ps,ops'') = parsePrograms ops'\n\nparseProgram :: [Op] -> (Program,[Op])\nparseProgram (Throw ex:ops) = (PThrow ex,ops)\nparseProgram (Nop:ops) = (PNop,ops)\nparseProgram (Try:ops) = (PTryCatch ex ms ps,ops')\n where\n (ps,Catch ex ms:ops') = parsePrograms ops\n\ndata RVal = Unit | Exception String | Message String\n deriving(Show)\n\nexecProgram :: [Program] -> RVal\nexecProgram ps = go ps\n where\n go [] = Unit\n go (PNop:ps) = go ps\n go (PThrow ex:ps) = Exception ex\n go (PTryCatch ex ms p:ps) = case execProgram p of\n Exception ex' | ex == ex' -> Message ms\n Unit -> go ps\n v -> v\n"}], "negative_code": [{"source_code": "import Data.Char\nimport qualified Data.ByteString.Char8 as C\n\ndata Result\n = Ex C.ByteString\n | Msg C.ByteString\n | Nil\n | End\n deriving (Eq, Show)\n\ntype Parser = State C.ByteString\n\nnext :: (Char -> Bool) -> Parser C.ByteString\nnext f = do\n modify $ C.dropWhile $ not . f\n (x, y) <- gets $ C.span f\n put y\n return x\n\nparseMany :: Parser Result\nparseMany = do\n first <- parse\n if first == End\n then return Nil\n else do\n rest <- parseMany\n return $ if first /= Nil then first else rest\n\nparse :: Parser Result\nparse = do\n modify $ C.dropWhile $ not . isLetter\n h <- gets C.head\n if h /= 't'\n then return End\n else do\n key <- next $ isLetter\n if key == C.pack \"throw\"\n then do\n ex <- next $ isLetter\n return $ Ex ex\n else do\n result <- parseMany\n _ <- next $ isLetter -- \"catch\"\n ex <- next $ isLetter\n _ <- next $ (=='\"')\n msg <- next $ (/='\"')\n if result == Ex ex\n then return $ Msg msg\n else return result\n\nmain :: IO ()\nmain = do\n _ <- C.getLine\n s <- C.getContents\n let ans = case fst $ runState parse $ C.append s $ C.pack \" return\" of\n Ex _ -> \"Unhandled Exception\"\n Msg msg -> C.unpack msg\n _ -> \"Error\"\n putStrLn ans\n\n-- Control.Monad.State\nnewtype State s a = State {\n runState :: s -> (a, s)\n}\n\ninstance Monad (State s) where\n return a = State $ \\s -> (a, s)\n m >>= f = State $ \\s -> let (a', s') = runState m s in runState (f a') s'\n\nget :: State s s\nget = State $ \\s -> (s, s)\n\nput :: s -> State s ()\nput s = State $ \\_ -> ((), s)\n\nmodify :: (s -> s) -> State s ()\nmodify f = State $ \\s -> ((), f s)\n\ngets :: (s -> a) -> State s a\ngets f = State $ \\s -> (f s, s)\n\n"}, {"source_code": "\ndata Statement = Try | Throw String | Catch String String deriving Show\n\ndata Program = Trycatch String String Program | ThrowProg String | EmptyProg | SeqProg Program Program deriving Show\n\ntrim = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')\n\nunbrace l = case trim l of\n '(':l' -> case reverse l' of\n ')':l'' -> reverse l''\n\nunquote l = case trim l of\n '\"':l' -> case reverse l' of\n '\"':l'' -> reverse l''\n\nparse :: [String] -> [Statement]\nparse s = s >>= \\l -> case (dropWhile (==' ') l) of\n ('t':'r':'y':_) -> [Try]\n ('t':'h':'r':'o':'w':l) -> [Throw $ trim $ unbrace l]\n ('c':'a':'t':'c':'h':l) -> case span (/=',') $ unbrace l of\n (l, ',':r) -> [Catch (trim l) (unquote r)]\n [] -> []\n\ngo :: [Statement] -> Maybe (String, Int) -> String\ngo (Try : t) Nothing = go t Nothing\ngo (Catch ex msg : t) (Just (err, 0)) | err == ex = msg\n | otherwise = go t (Just (err, 0))\ngo (Catch _ _ : t) Nothing = go t Nothing\ngo (Catch _ _ : t) (Just (err, i)) = go t (Just (err, i-1))\ngo (Throw err : t) Nothing = go t (Just (err, 0))\ngo (Try : t) (Just (err, i)) = go t (Just (err, i+1))\ngo [] (Just (err, 0)) = \"Unhandled exception\"\n\nrun :: [Statement] -> String\nrun (Throw ex : t) = go ex t where\n go ex (Catch ex' msg : _) | ex == ex' = msg\n go ex (_ : t) = go ex t\n go _ [] = \"Unhandled exception\"\nrun (_ : t) = run t\n\nmain = interact $ show . (`go` Nothing) . parse . tail . lines\n"}, {"source_code": "\ndata Statement = Try | Throw String | Catch String String deriving Show\n\ndata Program = Trycatch String String Program | ThrowProg String | EmptyProg | SeqProg Program Program deriving Show\n\ntrim = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')\n\nunbrace l = case trim l of\n '(':l' -> case reverse l' of\n ')':l'' -> reverse l''\n\nunquote l = case trim l of\n '\"':l' -> case reverse l' of\n '\"':l'' -> reverse l''\n\nparse :: [String] -> [Statement]\nparse s = s >>= \\l -> case (dropWhile (==' ') l) of\n ('t':'r':'y':_) -> [Try]\n ('t':'h':'r':'o':'w':l) -> [Throw $ trim $ unbrace l]\n ('c':'a':'t':'c':'h':l) -> case span (/=',') $ unbrace l of\n (l, ',':r) -> [Catch (trim l) (unquote r)]\n [] -> []\n\ngo :: [Statement] -> Maybe (String, Int) -> String\ngo (Try : t) Nothing = go t Nothing\ngo (Catch ex msg : t) (Just (err, 0)) | err == ex = msg\n | otherwise = go t (Just (err, 0))\ngo (Catch _ _ : t) Nothing = go t Nothing\ngo (Catch _ _ : t) (Just (err, i)) = go t (Just (err, i-1))\ngo (Throw err : t) Nothing = go t (Just (err, 0))\ngo (Try : t) (Just (err, i)) = go t (Just (err, i+1))\ngo [] (Just (err, 0)) = \"Unhandled exception\"\n\nrun :: [Statement] -> String\nrun (Throw ex : t) = go ex t where\n go ex (Catch ex' msg : _) | ex == ex' = msg\n go ex (_ : t) = go ex t\n go _ [] = \"Unhandled exception\"\nrun (_ : t) = run t\n\nmain = interact $ (`go` Nothing) . parse . tail . lines\n"}], "src_uid": "320e6c06194f8b1ccf1f4218d0757d2f"} {"source_code": "import Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n as <- map read . words <$> getLine\n putStrLn $ bool \"NO\" \"YES\" $ [0 .. n - 1] == sort ((`mod` n) <$> zipWith (+) [0 .. n - 1] as)", "positive_code": [{"source_code": "import qualified Data.List as L\nimport qualified Data.IntSet as IS\nimport Data.IntSet (IntSet)\n\npmod :: Integer -> Integer -> Integer\npmod n p\n | md < 0 = md + p\n | otherwise = md\n where\n md = n `mod` p\n\nallUnique :: [Integer] -> Bool\n--allUnique lst = length lst == length (map head $ L.group $ L.sort lst)\nallUnique = go IS.empty . map fromIntegral\n where\n go set [] = True\n go set (i:is)\n | IS.member i set = False\n | otherwise = go (IS.insert i set) is\n\nvalid :: [Integer] -> Bool\nvalid as = allUnique $ map (`pmod` fromIntegral (length as)) $ zipWith (+) [0..] as\n\nsolve :: [Integer] -> String\nsolve as\n | valid as = \"YES\"\n | otherwise= \"NO\"\n\ntestCases :: Integer -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n as <- readNums\n putStrLn $ solve as\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- parseNums <$> getLine\n testCases t\n\n\nparseNums :: (Read a) => String -> [a]\nparseNums = map read . words\n\nreadNums :: (Read a) => IO [a]\nreadNums = parseNums <$> getLine"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n as <- (map read.words) <$> getLine\n putStrLn $ if solve n as\n then \"No\"\n else \"Yes\"\n\nsolve :: Int -> [Int] -> Bool\nsolve n as = hasDupesWith S.empty xs\n where\n xs = map (`mod` n) $ zipWith (-) as [0,(-1)..]\n\nhasDupesWith :: S.Set Int -> [Int] -> Bool\nhasDupesWith _ [] = False\nhasDupesWith seen (x:xs) = x `S.member` seen || hasDupesWith (S.insert x seen) xs\n"}], "negative_code": [{"source_code": "import qualified Data.List as L\n\npmod :: Integer -> Integer -> Integer\npmod n p\n | n < 0 = (n `mod` p) + p\n | otherwise = n `mod` p\n\nallUnique :: [Integer] -> Bool\nallUnique lst = length lst == length (map head $ L.group $ L.sort lst)\n\nvalid :: [Integer] -> Bool\nvalid as = allUnique $ map (`pmod` fromIntegral (length as)) $ zipWith (+) [0..] as\n\nsolve :: [Integer] -> String\nsolve as\n | valid as = \"YES\"\n | otherwise= \"NO\"\n\ntestCases :: Integer -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n as <- readNums\n putStrLn $ solve as\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- parseNums <$> getLine\n testCases t\n\n\nparseNums :: (Read a) => String -> [a]\nparseNums = map read . words\n\nreadNums :: (Read a) => IO [a]\nreadNums = parseNums <$> getLine"}, {"source_code": "import qualified Data.List as L\n\npmod :: Int -> Int -> Int\npmod n p\n | n < 0 = (n `mod` p) + p\n | otherwise = n `mod` p\n\nallUnique :: [Int] -> Bool\nallUnique lst = length lst == length (map head $ L.group $ L.sort lst)\n\nvalid :: [Int] -> Bool\nvalid as = allUnique $ map (`pmod` length as) $ zipWith (+) [0..] as\n\nsolve :: [Int] -> String\nsolve as\n | valid as = \"YES\"\n | otherwise= \"NO\"\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- getLine\n as <- readNums\n putStrLn $ solve as\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- parseNums <$> getLine\n testCases t\n\n\nparseNums :: (Read a) => String -> [a]\nparseNums = map read . words\n\nreadNums :: (Read a) => IO [a]\nreadNums = parseNums <$> getLine"}], "src_uid": "2173310623173d761b6039f0e5e661a8"} {"source_code": "\nimport Array\nimport Maybe\nimport Prelude hiding (print)\n\nparse :: String -> (Int, Int)\nparse line = case words line of\n [s1, s2] -> (read s1, read s2)\n\nsolve :: Int -> [(Int, Int)] -> Maybe (Int, Int)\nsolve n xs = listToMaybe $ filter ((/= 1) . snd) $ assocs array\n where\n array :: Array Int Int\n array = accumArray (+) 0 (1, n) $ concatMap (\\(a,b) -> [(i,1) | i <- [a..b]]) xs\n\nprint :: Maybe (Int, Int) -> IO ()\nprint Nothing = putStrLn \"OK\"\nprint (Just (a, b)) = putStrLn $ show a ++ \" \" ++ show b\n\nmain :: IO ()\nmain = do\n (n, m) <- fmap parse getLine\n xs <- fmap (map parse . lines) getContents\n print $ solve n xs", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[n, m] <- getA\n\ta <- replicateM m getA\n\tputStrLn $ toS $ find ((/=1) . snd) $ assocs $ accumArray (+) 0 (1, n) $ concat $ map (\\[i, j] -> zip [i .. j] $ repeat 1) a where\n\t\ttoS Nothing = \"OK\"\n\t\ttoS (Just (i, j)) = show i ++ \" \" ++ show j\n\n"}, {"source_code": "main = interact solve\nsolve input = output where\n [n,m]:s = map (map (read::String->Int)) $ map words $ lines input\n output = ans s\n ans ([x,y]:xs) = if x==1 then ans0 y xs else \"1 0\"\n ans0 x [] = if x==n then \"OK\" else f (x+1) 0\n ans0 x ([y,z]:xs)\n | x + 1== y = ans0 z xs\n | x + 1 < y = f (x+1) 0\n | y < z = f x 2\n | otherwise = f x (ans1 y xs)\n ans1 _ [] = 2\n ans1 x ([y,z]:xs) = if x (i - j) ^ 2) a\n"}], "src_uid": "30c4f155336cf762699a1bbc55a60d27"} {"source_code": "{-# LANGUAGE BangPatterns , BlockArguments ,FlexibleContexts ,FlexibleInstances ,OverloadedStrings ,TypeApplications ,MultiParamTypeClasses ,TupleSections #-}\nimport Control.Monad (replicateM,forM_,when,(<=<))\n\n\n\nmain :: IO ()\nmain = do\n n <- readLn @Int\n query <- replicateM n $ do\n b <- readLn @Int\n a <- map (read @Int) . words <$> getLine\n return (b,a)\n solve n query\nsolve :: Int -> [(Int,[Int])] -> IO ()\nsolve n query = do\n forM_ query \\(n,x) -> do\n let oddIndex = map snd$filter(\\(index,val)->odd index) $zip[1..]x \n evenIndex = map snd$filter(\\(index,val)->even index) $zip[1..]x\n let ho = head oddIndex\n he = head evenIndex\n putStrLn$\n if(even ho && even he)then do\n if(all even oddIndex && all even evenIndex)then \"YES\"else \"NO\"\n else if(even ho && odd he) then do\n if(all even oddIndex && all odd evenIndex)then \"YES\"else \"NO\"\n else if(odd ho && even he) then do\n if(all odd oddIndex && all even evenIndex)then \"YES\"else \"NO\"\n else if(odd ho && odd he) then do\n if(all odd oddIndex && all odd evenIndex)then \"YES\"else \"NO\"\n else \"NO\"\n", "positive_code": [{"source_code": "import Data.List\r\n\r\nparseInt :: String -> Int\r\nparseInt s = read s :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = parseInt <$> getLine\r\n\r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n arr <- words <$> getLine\r\n pure $ map parseInt arr\r\n\r\ncheck :: Int -> Int\r\ncheck x = if x `mod` 2 == 0\r\n then 1\r\n else -1\r\n\r\ncalc :: [Int] -> (Int, Int) -> Bool -> String\r\ncalc [] _ _ = \"YES\"\r\ncalc (x: xs) (c1, c2) p = if p\r\n then if (abs c1) > (abs $ c1 + check x)\r\n then \"NO\"\r\n else calc xs (c1 + check x, c2) False\r\n else if (abs c2) > (abs $ c2 + check x)\r\n then \"NO\"\r\n else calc xs (c1, c2 + check x) True\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readInt\r\n arr <- readIntArr\r\n putStrLn $ calc arr (0, 0) True\r\n\r\nfor :: Int -> IO () -> IO ()\r\nfor 0 _ = pure ()\r\nfor i f = do\r\n f\r\n for (i - 1) f\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n for n solve"}], "negative_code": [], "src_uid": "fbb4e1cf1cad47481c6690ce54b27a1e"} {"source_code": "import Data.List\nfibs = 0 : 1 : zipWith (+) fibs (tail fibs)\neleven = intercalate \"O\" $ map (flip replicate 'o' . pred) fibs\nmain = interact $ flip take eleven . read\n", "positive_code": [{"source_code": "main = putStr . flip (foldr (\\i g fs@(f:_) -> if i == f then 'O':g (dropWhile (== i) fs) else 'o':g fs) (const [])) fibs . enumFromTo 1 . read =<< getLine\nfibs = 1:1:zipWith (+) fibs (tail fibs)"}, {"source_code": "main = do\n ln1 <- getLine\n let s = read ln1 :: Int\n l = [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987]\n str = [r l i | i <- [1..s]]\n putStrLn str\n\nr l i\n | elem i l = 'O'\n | otherwise = 'o'"}, {"source_code": "main = getLine >>= putStrLn . solve . read\n\nsolve n = foldr (\\x acc -> (genName 'o' x):acc) [] [1 .. n]\n\ngenName 'o' num\n | elem num fib = 'O'\n | otherwise = 'o'\n\nfib = f [2,1] 2\n where f (a:b:x) num\n | num < 15 = f ((a+b):a:b:x) (num+1)\n | otherwise = a:b:x\n"}, {"source_code": "import Data.List\n\ng::Bool->Char\ng True='O'\ng False='o'\n\nf :: Int->Int->[Int]\nf a b\n |a>1000=[]\n |otherwise=a:(f b (a+b))\n\nh::Int->Int->[Int]->[Bool]\nh p n xs\n |p>n=[]\n |otherwise=(elem p xs):h (p+1) n xs\n\nmain=do\n e1<-getLine\n let n=read e1::Int\n xs=f 1 1\n putStrLn $ map g $ h 1 n xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nfibs = 1:1: (zipWith (+) fibs (tail fibs))\n\nprocess x n = map (\\z-> if elem z x then 'O' else 'o') [1..n]\n\nmain = do\n\t\tn<- read <$> getLine:: IO Int\n\t\tlet x = takeWhile (<=n) fibs \n\t\tputStrLn $ process x n\n"}, {"source_code": "process :: Int -> [Char]\nprocess n = take n $ f 1 1 0\n where\n f a b i\n | i == 0 = 'O':f b (a+b) (a-1)\n | otherwise = 'o':f a b (i-1)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n putStrLn $ process n"}], "negative_code": [], "src_uid": "a7c0484275e62f0bc70d9edaac27d7d6"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport qualified System.Random as SR\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n (rest,maxval) <- binMax (n-2) (10^9) 60\n rands <- SR.randomRs (1,n) <$> SR.newStdGen\n let noDupRands =\n take rest $ map fst\n $ filter (uncurry IS.notMember)\n $ scanl (\\(prev,set0) now -> (now, IS.insert prev set0))\n (-1,IS.singleton (-1))\n $ rands\n is | n < shiftL rest 1 = [1..rest `min` n]\n | otherwise = noDupRands\n as <- fmap sort $ forM is $ \\i -> do\n putStrLn $ '?':' ': show i\n hFlush stdout\n ai <- readInt <$> getLine\n if ai < 0 then exitFailure else return ai\n let diffs = zipWith (-) (tail as) as\n d = foldl1' gcd diffs\n putStrLn $ ('!':) $ (' ':) $ shows (maxval - (n-1)*d) $ ' ' : show d\n \n \n\nbinMax :: Int -> Int -> Int -> IO (Int,Int)\nbinMax !lt !ge !rest\n | ge - lt <= 1 = return (rest,ge)\n | otherwise = do\n let mid = lt + shiftR (ge - lt) 1\n putStrLn $ '>':' ': show mid\n hFlush stdout\n i <- readInt <$> getLine\n case i of\n 1 -> binMax mid ge (rest-1)\n 0 -> binMax lt mid (rest-1)\n _ -> exitFailure\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport qualified System.Random as SR\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n (rest,maxval) <- binMax (n-2) (10^9) 60\n rands <- SR.randomRs (1,n) <$> SR.newStdGen\n let noDupRands =\n take rest $ map fst\n $ filter (uncurry IS.notMember)\n $ scanl (\\(prev,set0) now -> (now, IS.insert prev set0))\n (-1,IS.singleton (-1))\n $ rands\n is | n < shiftL rest 1 = [1..rest `min` n]\n | otherwise = noDupRands\n as <- fmap (sort . (maxval:)) $ forM is $ \\i -> do\n putStrLn $ '?':' ': show i\n hFlush stdout\n ai <- readInt <$> getLine\n if ai < 0 then exitFailure else return ai\n let diffs = zipWith (-) (tail as) as\n d = foldl1' gcd diffs\n putStrLn $ ('!':) $ (' ':) $ shows (maxval - (n-1)*d) $ ' ' : show d\n \n \n\nbinMax :: Int -> Int -> Int -> IO (Int,Int)\nbinMax !lt !ge !rest\n | ge - lt <= 1 = return (rest,ge)\n | otherwise = do\n let mid = lt + shiftR (ge - lt + 1) 1\n putStrLn $ '>':' ': show mid\n hFlush stdout\n i <- readInt <$> getLine\n case i of\n 1 -> binMax mid ge (rest-1)\n 0 -> binMax lt mid (rest-1)\n _ -> exitFailure\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport qualified System.Random as SR\n\nulimit = 10^9 :: Int\nover = ulimit + 10\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n (!rest,!amax) <- binMax (n-2) ulimit 60\n rands <- SR.randomRs (1,n) <$> SR.newStdGen\n let noDupRands\n = take rest $ map fst $ filter (uncurry IS.notMember)\n $ scanl (flip (,) . uncurry IS.insert) (over,IS.singleton over) rands\n is | n < shiftL rest 1 = [1..rest `min` n]\n | otherwise = noDupRands\n as <- fmap (sort . (amax:)) $ forM is $ \\i -> do\n putStrLn $ '?':' ': show i\n hFlush stdout\n ai <- readInt <$> getLine\n if ai < 0 then exitFailure else return ai\n let diffs = zipWith (-) (tail as) as\n d = foldl1' gcd diffs\n putStrLn $ ('!':) $ (' ':) $ shows (amax - (n-1)*d) $ ' ' : show d\n \n \n\nbinMax :: Int -> Int -> Int -> IO (Int,Int)\nbinMax !lt !ge !rest\n | ge - lt <= 1 = return (rest,ge)\n | otherwise = do\n let mid = lt + shiftR (ge - lt + 1) 1\n putStrLn $ '>':' ': show mid\n hFlush stdout\n i <- readInt <$> getLine\n case i of\n 1 -> binMax mid ge (rest-1)\n 0 -> binMax lt mid (rest-1)\n _ -> exitFailure\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "negative_code": [], "src_uid": "36619f520ea5a523a94347ffd3dc2c70"} {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n{-solve :: [String] -> ([String],Int)\nsolve l = (result,howoften)\n\twhere\n\t\tzipped=zip l [0..]\n\t\tfirstelem = map (\\(x,y)-> (fromJust $ elemIndex x l)==y) zipped\n\t\t--newpins=filter (\\x -> not (x `elem` l)) (map show [1000..])\n\t\t--result=zipWith (\\x (y,z) -> if x then y else newpins!!z) firstelem zipped\n\t\t--howoften= foldr (\\x c-> if x then c else c+1) 0 firstelem\n-}\n{-\nroutine :: IO ()\nroutine = do\n\tn <- readLn\n\tl <- replicateM n getLine\n\tlet (list,c)=solve l\n\tprint c\n\n-}\nhelper :: [String] -> [String] -> String -> ([String],Int)\nhelper total li str = if str `elem` li then (newStr:li,1) else (str:li,0)\n\twhere\n\t\tunused = head $ filter (\\x -> not (x `elem` (map head li))) $ filter (\\x -> not (x `elem` (map head total))) (map (head.show) [0..9])\n\t\tnewStr = (unused):(tail str)\n\n\n\nsolve :: [String] -> ([String],Int)\nsolve li = foldr (\\str (list,count) -> let (x,y)=helper li list str in (x,y+count)) ([],0) li\n\n\nroutine :: IO ()\nroutine = do\n\tn <- readLn\n\tl <- replicateM n getLine\n\tlet (list,c)=solve l\n\tprint c\n\tforM_ list putStrLn\n\nmain :: IO ()\nmain = do\n\tn <- readLn\n\treplicateM_ n routine\n\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n n <- read <$> getLine\n ps <- getPins n\n print $ sum $ subtract 1.length <$> group (sort ps)\n putStr $ unlines $ change ps\n test (i - 1)\n\nchange ps = snd <$> sortOn fst changed where\n sorted = sortOn snd $ zip [1..] ps\n grouped = groupBy (\\(_, a) (_, b) -> a == b) sorted\n changed = grouped >>= (\\(a:as) -> a : alter '0' as)\n alter _ [] = []\n alter c ((i, [p, q, r, s]):as) = let c' = if c == '9' then '0' else succ c in \n if elem [c, q, r, s] ps\n then if elem [p, c, r, s] ps \n then if elem [p, q, c, s] ps \n then if elem [p, q, r, c] ps \n then alter c' ((i, [p, q, r, s]):as)\n else (i, [p, q, r, c]) : alter c' as\n else (i, [p, q, c, s]) : alter c' as\n else (i, [p, c, r, s]) : alter c' as\n else (i, [c, q, r, s]) : alter c' as\n\ngetPins 0 = return []\ngetPins i = do\n p <- getLine\n (p:) <$> getPins (i - 1)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n{-solve :: [String] -> ([String],Int)\nsolve l = (result,howoften)\n\twhere\n\t\tzipped=zip l [0..]\n\t\tfirstelem = map (\\(x,y)-> (fromJust $ elemIndex x l)==y) zipped\n\t\t--newpins=filter (\\x -> not (x `elem` l)) (map show [1000..])\n\t\t--result=zipWith (\\x (y,z) -> if x then y else newpins!!z) firstelem zipped\n\t\t--howoften= foldr (\\x c-> if x then c else c+1) 0 firstelem\n-}\n{-\nroutine :: IO ()\nroutine = do\n\tn <- readLn\n\tl <- replicateM n getLine\n\tlet (list,c)=solve l\n\tprint c\n\n-}\nhelper :: [String] -> String -> ([String],Int)\nhelper li str = if str `elem` li then (newStr:li,1) else (str:li,0)\n\twhere\n\t\tunused = head $ filter (\\x -> not (x `elem` (map head li))) (map (head.show) [0..9])\n\t\tnewStr = (unused):(tail str)\n\n\n\nsolve :: [String] -> ([String],Int)\nsolve li = foldr (\\str (list,count) -> let (x,y)=helper list str in (x,y+count)) ([],0) li\n\n\nroutine :: IO ()\nroutine = do\n\tn <- readLn\n\tl <- replicateM n getLine\n\tlet (list,c)=solve l\n\tprint c\n\tforM_ list putStrLn\n\nmain :: IO ()\nmain = do\n\tn <- readLn\n\treplicateM_ n routine\n\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n{-solve :: [String] -> ([String],Int)\nsolve l = (result,howoften)\n\twhere\n\t\tzipped=zip l [0..]\n\t\tfirstelem = map (\\(x,y)-> (fromJust $ elemIndex x l)==y) zipped\n\t\t--newpins=filter (\\x -> not (x `elem` l)) (map show [1000..])\n\t\t--result=zipWith (\\x (y,z) -> if x then y else newpins!!z) firstelem zipped\n\t\t--howoften= foldr (\\x c-> if x then c else c+1) 0 firstelem\n-}\n{-\nroutine :: IO ()\nroutine = do\n\tn <- readLn\n\tl <- replicateM n getLine\n\tlet (list,c)=solve l\n\tprint c\n\n-}\nhelper :: [String] -> [String] -> String -> ([String],Int)\nhelper total li str = if str `elem` li then (newStr:li,1) else (str:li,0)\n\twhere\n\t\tunused = head $ filter (\\x -> not (x `elem` (map head total))) (map (head.show) [0..9])\n\t\tnewStr = (unused):(tail str)\n\n\n\nsolve :: [String] -> ([String],Int)\nsolve li = foldr (\\str (list,count) -> let (x,y)=helper li list str in (x,y+count)) ([],0) li\n\n\nroutine :: IO ()\nroutine = do\n\tn <- readLn\n\tl <- replicateM n getLine\n\tlet (list,c)=solve l\n\tprint c\n\tforM_ list putStrLn\n\nmain :: IO ()\nmain = do\n\tn <- readLn\n\treplicateM_ n routine\n\n"}], "src_uid": "1d2ba15a7f2958bb79ccc7b2a2a1545b"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess n [] = []\nprocess n (a:b) | a>=0 = (n+a): (process (n+a) b)\n | otherwise = (n+a) : (process n b)\n\n\nmain::IO ()\nmain=do\n getLine\t\n a<- map read <$> words <$> getLine::IO [Integer] \n putStrLn $ intercalate \" \" $ map show $process 0 a\n", "positive_code": [{"source_code": "import Data.List (mapAccumL)\n\nprocess :: [Int] -> [Int]\nprocess = snd . mapAccumL (\\x b -> let b' = b+x in (max x b', b')) 0\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n bs <- fmap (map readInt.words) getLine\n putStrLn.unwords.map show $ process bs"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = do\n getLine\n bs <- map read.words <$> getLine\n let vs = solve 0 bs\n let m = minimum vs\n putStrLn $ unwords.map show $ (+ (head bs - head vs)) <$> vs\n\nsolve _ [] = []\nsolve a (b:bs)\n | b > 0 = (a + b) : solve (a + b) bs\n | otherwise = (a + b) : solve a bs\n\n"}, {"source_code": "module Main where\nimport Data.List\n\ngetA :: [Int] -> [Int]\ngetA b = f b 0\n where f (bi:br) m = bi+m : f br (max m (bi+m))\n\nsolve :: String -> String\nsolve s = let ((n:_):b:_) = map (map read . words) $ lines s\n in (unwords $ map show $ take n $ getA (b ++ repeat 0)) ++ \"\\n\"\n\nmain = interact solve\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain = do\n getLine\n inp <- getLine\n let nums = map read $ words inp\n putStrLn $ intercalate \" \" $ map show $ ans 0 nums\n\n\nans :: Int -> [Int] -> [Int]\nans m [] = []\nans m (b:bs) =\n let a = b + m in\n a : ans (if b > 0 then a else m) bs"}], "negative_code": [], "src_uid": "e22b10cdc33a165fbd73b45dc5fbedce"} {"source_code": "import Control.Monad\n\nimport Data.Char\nimport Data.List\n\nsolve :: (Integer, Integer) -> Integer\nsolve (n, k) = k * (n `div` k) + min (k `div` 2) (n `rem` k)\n\nmain :: IO ()\nmain = do\n input <- getContents\n putStrLn $ unlines . map (show . solve) $ zip (a input) (b input)\n where a = map snd . filter (odd . fst) . zip [1..] . map (read :: String -> Integer) . tail . words\n b = map snd . filter (even . fst) . zip [1..] . map (read :: String -> Integer) . tail . words\n", "positive_code": [{"source_code": "import Control.Monad\n\nsolve :: [Int] -> Int\nsolve (n:k:_) = n - (max 0 $ (n `mod` k) - (k `div` 2))\n\nmain :: IO ()\nmain = ids >>= mapM_ (fn >=> print)\n where ids = enumFromTo 1 . read <$> getLine\n fn tc = solve . map read . words <$> getLine\n"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int\nsolve n k = a + (min b (k `div` 2))\n where\n a = (n `div` k) * k\n b = n `mod` k\n\nroutine :: IO ()\nroutine = do\n [h,m] <- (map read.words) <$> getLine\n print $ solve h m\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int\nsolve n k = (q * k) + min rem (k `quot` 2)\n where\n (q, rem) = n `quotRem` k\n\nmain = do\n numCases <- read <$> getLine\n\n replicateM_ numCases $ do\n [n, k] <- fmap read <$> words <$> getLine\n print $ solve n k\n"}, {"source_code": "sol :: [Int] -> Int\nsol [n, k] = min n $ k * a + k `div` 2\n where a = n `div` k\n\nmain = interact (unlines . map show . map (sol . map read) . map words . tail . lines)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\n\nsolve n k = (d * k) + (min (k `div` 2) r)\n where \n d = n `div` k\n r = n `rem` k\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain = do \n n <- read <$> getLine\n replicateM_ n $ do\n [h, m] <- map readInt . words <$> getLine\n print $ solve h m\n"}, {"source_code": "main :: IO ()\n\nmain = interact solve\n\nsolve :: String -> String\nsolve = buildup . map solver . breakdown\nsolver :: (Int, Int) -> Int\nsolver (x,y) = min (x `div` y * y + (y `div` 2)) x\n\nbreakdown :: String -> [(Int, Int)]\nbreakdown = map (f . words) . tail . lines \n where f :: [String] -> (Int,Int)\n f (x:y:[]) = (read x, read y)\n\nbuildup :: [Int] -> String\nbuildup = unlines . map show\n\nreadInt :: String -> Int\nreadInt = read :: String -> Int\n"}], "negative_code": [{"source_code": "main :: IO ()\n\nmain = interact solve\n\nsolve :: String -> String\nsolve = buildup . map solver . breakdown\nsolver :: (Int, Int) -> Int\nsolver (x,y) = max (x `div` y * y + (y `div` 2)) x\n\nbreakdown :: String -> [(Int, Int)]\nbreakdown = map (f . words) . tail . lines \n where f :: [String] -> (Int,Int)\n f (x:y:[]) = (read x, read y)\n\nbuildup :: [Int] -> String\nbuildup = unlines . map show\n\nreadInt :: String -> Int\nreadInt = read :: String -> Int\n"}, {"source_code": "main :: IO ()\n\nmain = interact solve\n\nsolve :: String -> String\nsolve = buildup . map solver . breakdown\nsolver :: (Int, Int) -> Int\nsolver (x,y) = x `div` y * y + (y `div` 2)\n\nbreakdown :: String -> [(Int, Int)]\nbreakdown = map (f . words) . tail . lines \n where f :: [String] -> (Int,Int)\n f (x:y:[]) = (read x, read y)\n\nbuildup :: [Int] -> String\nbuildup = unlines . map show\n\nreadInt :: String -> Int\nreadInt = read :: String -> Int\n"}, {"source_code": "main :: IO ()\n\nmain = interact solve\n\nsolve :: String -> String\nsolve = buildup . map solver . breakdown\nsolver :: (Int, Int) -> Int\nsolver (x,y) = x - (( x `mod` y) `div` 2)\n\nbreakdown :: String -> [(Int, Int)]\nbreakdown = map (f . words) . tail . lines \n where f :: [String] -> (Int,Int)\n f (x:y:[]) = (read x, read y)\n\nbuildup :: [Int] -> String\nbuildup = unlines . map show\n\nreadInt :: String -> Int\nreadInt = read :: String -> Int\n"}], "src_uid": "43b8e9fb2bd0ec5e0250a33594417f63"} {"source_code": "import Data.List\nimport qualified Data.Map as M\n(|>) x f = f x\n\nmain = interact solve\n\nsolve contents = let\n ls = contents |> lines\n sz = ls |> (!! 0) |> read :: Int\n portions = ls |> (!! 1) |> words |> map read :: [Int] \n in solve' portions sz |> show\n \nsolve' portions sz = portions |> sum |> fromIntegral |> (/ (fromIntegral sz))\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n _ <- getLine\n percentages <- fmap (map read.words) getLine\n let perc_f = map fromIntegral percentages\n print((fromIntegral (sum perc_f)) / (fromIntegral (length perc_f)))\n"}, {"source_code": "module Main (main)\n where\n\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = print . solve . map (map read . words) =<< replicateM 2 getLine\n where solve [[n], xs] = sum xs / n"}, {"source_code": "\n\n-- the haskell wiki is amazing!!!\n-- https://wiki.haskell.org/Generic_number_type\n-- https://wiki.haskell.org/Converting_numbers\n\n\n\n\n-- you have to convert the integers to type Fractional!!!!!!\n-- at least this is the way that i found to make it work!!!!\n\nconv lst uu\n | (null lst) = uu\n | otherwise = conv (tail lst) (uu ++ [(read (head lst))::Int])\n\n\navg lst sum \n | (null lst) = sum\n | otherwise = avg (tail lst) (sum + (head lst)) \n \nmain = do\n ww <- getLine\n ff <- getLine\n let aa = conv (words ff) []\n ans = avg aa 0\n \n putStrLn (show ( realToFrac ans / realToFrac (length aa)))\n\n\n\n\n\n"}, {"source_code": "\nmain :: IO ()\nmain = do\n n <- readLn :: IO Float\n input <- getLine\n let args = map (\\x -> read x :: Float) $ words input\n print $ (sum args)/n"}, {"source_code": "main = do\n getLine\n ps <- fmap (map read . words) getLine\n print $ (fromIntegral $ sum ps) / (fromIntegral $ length ps)\n"}, {"source_code": "main = do\n getLine\n xs <- fmap (map read . words) getLine\n print $ (sum xs) / (fromIntegral $ length xs)\n\n"}, {"source_code": "main = do\n auxN <- getLine\n let n = read auxN :: Double\n auxP <- getLine\n let sumP = read (show (sum (map read $ words auxP :: [Int]))) :: Double\n putStrLn (show (sumP/n))\n\n"}, {"source_code": "promedio :: [Double] -> Double\npromedio l = sum l / (fromIntegral $ length l)\n\nmain = do\n header <- getLine\n numbers <- fmap words getLine\n print $ promedio $ f numbers\n where\n f l = map read l\n"}, {"source_code": "promedio :: [Double] -> Double\npromedio l = (foldr (+) 0 l) / (fromIntegral $ length l)\n\nmain = do\n header <- getLine\n numbers <- fmap words getLine\n print $ promedio $ f numbers\n where\n f l = map read l\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ solve.concat.map (map read.words).take 2. lines\nsolve :: [Integer]->String\nsolve (x:xs) = show $ (/fromIntegral x) $ fromIntegral $ sum xs"}, {"source_code": "import Data.List\nmain=do\n\ta<-getLine\n\tt<-fmap (map read.words) getLine\n\tprint $ sum t / genericLength t\n"}, {"source_code": "solve :: Int -> [Double] -> Double\nsolve n xs = sum xs / (fromIntegral n)\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- getLine >>= return . map read . words\n print $ solve n xs"}, {"source_code": "import Control.Monad\n\nmain = readInput >>= putStrLn . show . (\\(n, ps) -> sum ps / n)\n\nreadInput :: IO (Double, [Double])\nreadInput = liftM2 toTuple getLine getLine\n where toTuple a b = (read a, map read $ words b)"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nsolve :: Int -> [Double] -> Double\nsolve n arr = sum arr / fromIntegral n\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n arr <- (map (fromIntegral . readInt) . words) <$> getLine\n let answer = solve n arr\n printf \"%.5f\\n\" answer"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nmain=do\n n<- read <$> getLine::IO Int\n q<- sum <$> map read <$> words <$>getLine ::IO Int\n print $ (fromIntegral q)/ (fromIntegral n)\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Double] -> Double\nsolve (n:ps) = sum ps / n\nsolve _ = undefined\n"}, {"source_code": "main=getContents>>=print.e.map read.words\ne(n:s)=sum s/n\n"}, {"source_code": "main=getContents>>=print.solve.map read.words\nsolve(n:s)=sum s/n\n"}, {"source_code": "main = do\n n <- readLn\n ps <- fmap (map read . words) getLine\n print (sum ps / n)\n"}, {"source_code": "solve :: [Int] -> Double\nsolve ps = fromIntegral (sum ps) / fromIntegral (length ps * 100) * 100\n\nmain = do\n getLine -- n\n ps <- fmap (map read . words) getLine\n print $ solve ps"}, {"source_code": "main = do\n n <- fmap read getLine\n p <- fmap (map read . words) getLine\n print $ sum p / n\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/200/B\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Double\n a <- getLine >>= return . map read . words :: IO [Double]\n print (sum a / n)\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n n <- readLn\n x <- sum.map read.words <$> getLine\n print $ x/n"}, {"source_code": "main = do\n x <- getLine\n items <- map parse . words <$> getLine\n print $ (foldl (+) 0.0 items) / (read x) * 100\n\nparse :: String -> Double\nparse x = y / 100\n where y = read x :: Double"}, {"source_code": "\ncalc xs = (sum xs / fromIntegral (100 * length xs)) * 100\n\nmain = do s <- getLine\n t <- getLine\n putStrLn $ show $ calc $ map (\\x -> read x :: Double) $ words t\n\n"}, {"source_code": "\ncalc xs = (sum xs / fromIntegral (100 * length xs)) * 100\n\nmain = do s <- getLine\n t <- getLine\n putStrLn $ show $ calc $ map (\\x -> read x :: Float) $ words t\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n \n\nmyprint x1 = putStrLn $ intercalate \" \" $ map show x1\n\t\n\nmain= do\n\tn<- read <$> getLine ::IO Double\n\ts<- map (fst.fromJust.C.readInteger) . C.words <$> C.getLine ::IO [Integer]\n\tlet ss = sum s\n\tprint $ (fromIntegral ss) / n"}, {"source_code": "main = do\n n <- readLn :: IO Double\n a <- getLine >>= return. map read. words :: IO [Double]\n print (sum a / n)\n"}, {"source_code": "main :: IO ()\nmain = do\n n <- toRational . (read :: String -> Int) <$> getLine\n print =<< (fromRational :: Rational -> Double) . (* 100) . (/ n) . sum . map ((/ 100) . toRational . (read :: String -> Int)) . words <$> getLine\n"}, {"source_code": "--ghc 7.10\n\naverage :: (Fractional a) => [a] -> a\naverage a = (sum a) / (fromIntegral (length a))\n\nmain = do\n nStr <- getLine\n aStr <- getLine\n let a = map read . words $ aStr :: [Double]\n print $ average a"}, {"source_code": "main=print.slv.map read.words =<< getContents\nslv (n:ps) = (sum.take (floor n) $ ps)/n"}, {"source_code": "main = interact $ show.f.map read.words.last.lines\nf xs = (*100.0).(/(fromIntegral.length $ xs)).sum.map (*0.01) $ xs\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nsolve :: Int -> [Int] -> Float\nsolve n x = sum (map fromIntegral x) / fromIntegral n\n\nmain = \n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let (x, _) = readMany readInt r1\n print (solve n x)\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)\n readMany readf s = case readf s of\n Just (x, r) -> let (xs, t) = readMany readf r\n in (x : xs, t)\n Nothing -> ([], s)\n"}], "negative_code": [{"source_code": "main :: IO ()\nmain = do\n n <- toRational . (read :: String -> Int) <$> getLine\n print =<< (fromRational :: Rational -> Double) . (/ n) . sum . map ((/ 100) . toRational . (read :: String -> Int)) . words <$> getLine\n"}], "src_uid": "580596d05a2eaa36d630d71ef1055c43"} {"source_code": "import Data.Int (Int64)\n\nprocess :: [Int64] -> [(Int64,Int64)]\nprocess xs = zip dmins dmaxs\n where\n cmin = head xs\n cmax = last xs\n dl = zipWith (-) xs (2*cmin-cmax:xs)\n dr = zipWith (-) (tail xs ++ [2*cmax-cmin]) xs\n dmins = zipWith min dl dr\n cmid = (cmin + cmax) `div` 2\n dmaxs = map (\\x -> if x <= cmid then cmax-x else x-cmin) xs\n\nreadInt :: String -> Int64\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n mapM_ (\\(l,r) -> putStrLn (show l ++ \" \" ++ show r)) $ process xs", "positive_code": [{"source_code": "main :: IO()\nmain = output . solve . map read . words =<< getContents\n\nsolve :: [Int] -> [[Int]]\nsolve (n:x) = \n let x1 = head x\n xn = last x\n in solve' x1 xn x 0 True\n where solve' :: Int -> Int -> [Int] -> Int -> Bool -> [[Int]]\n solve' x1 xn (x:xs) _ True = ([(head xs) - x, xn - x]:(solve' x1 xn xs x False))\n solve' x1 xn [x] last _ = [[(x - last), x - x1]]\n solve' x1 xn (x:xs) last _ = ([(min (x - last) ((head xs) - x)), (max (x - x1) (xn - x))]:(solve' x1 xn xs x False))\n\noutput :: [[Int]] -> IO()\noutput [[a, b]] = output' [a, b]\noutput (x:xs) = do output' x\n output xs\n\noutput' :: [Int] -> IO()\noutput' [a, b] = putStrLn ((show a) ++ \" \" ++ (show b))\n"}, {"source_code": "main = do\n n <- readLn\n xs <- fmap (map read . words) getLine\n\n let\n h = head xs\n l = last xs\n\n r = [(xs!!1 - h, l - h)] ++\n (zipWith3 f xs (tail xs) (tail $ tail xs)) ++\n [(xs!!(n-1)-xs!!(n-2), l-h)]\n where\n f a b c = (min (b-a) (c-b), max (l-b) (b-h))\n\n putStrLn $ unlines $ map (\\(x, y) -> show x ++ \" \" ++ show y) r\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\n-> (solve.(++) [read n].concat =<< forM [1 ..1] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve (x:xs) = let m=Map.fromList $ zip [1..x] xs in forM_ [1..x] $ \\i -> putStrLn $ unwords $ map show (slv1 i m)\n where\n slv1 a m | a==1 = [m Map.! 2 - m Map.! 1, m Map.! x - m Map.! 1]\n | a==x = [m Map.! x - m Map.! (x-1), m Map.! x - m Map.! 1]\n | otherwise = [minimum [m Map.! a - m Map.! (a-1), m Map.! (a+1) - m Map.! a], maximum [m Map.! x - m Map.! a, m Map.! a - m Map.! 1]]"}, {"source_code": "import Control.Arrow ((&&&), (***))\nimport Data.Functor ((<$>))\n\nmain :: IO ()\nmain = mapM_ (putStrLn . uncurry (++) . (show *** (' ':) . show)) =<< solve <$> (tail <$> map read <$> words <$> getContents)\n\nsolve :: [Integer] -> [(Integer, Integer)]\nsolve xs = zip (uncurry (zipWith min) $ (id &&& tail) $ zipWith (-) (xs ++ [10000000000]) (-10000000000 : xs)) [ max (x - head xs) (last xs - x) | x <- xs ]\n"}, {"source_code": "import Control.Monad (forM_)\nmain = do\n getLine\n cs <- fmap (map read . words) getLine :: IO [Int]\n let h = head cs\n t = last cs\n toL = zipWith (-) cs (h : cs) :: [Int]\n toR = zipWith (-) (tail cs ++ [t]) cs :: [Int]\n forM_ (zip3 cs toL toR) $ \\(c,l,r) ->\n putStrLn $ unwords $ map show [min' l r, max' (c-h) (t-c)]\nmin' 0 a = a\nmin' a 0 = a\nmin' a b = min a b\nmax' 0 a = a\nmax' a 0 = a\nmax' a b = max a b\n"}, {"source_code": "main = do\n _ <- getLine\n xs <- fmap (map read . words) getLine\n let sol = solve xs\n mapM_ (putStrLn . (\\(a,b) -> show a ++ \" \" ++ show b)) sol\n \nsolve :: [Int] -> [(Int, Int)]\nsolve xs@(x:y:ys) = (y-x, maxv-x) : f x (y:ys)\n where minv = head xs\n maxv = last xs\n f a (b:c:cs) = (min (b-a) (c-b), max (b-minv) (maxv-b)) : f b (c:cs)\n f a [b] = [(b-a, b-minv)]\n"}, {"source_code": "import System.IO\n\nsolve1 :: [Int] -> [Int]\nsolve1 [x,y] = [ abs $ x-y ] \nsolve1 (x:y:z:xs) = min (abs $ x-y) (abs $ y-z) : solve1(y:z:xs)\n\nsolve2 :: [Int] -> Int -> Int -> [Int]\nsolve2 (x:xs) y z = max (abs $ x-y) (abs $ x-z) : solve2 xs y z\n\nmain = do\n\ts <- getLine\n\tlet n = read s :: Int\n\ts <- getLine\n\tlet xs = map read ( words s ) :: [Int]\n\t\n\tlet mns = abs( head xs - (head.tail) xs ) : solve1 xs\n\tlet mxs = solve2 xs (head xs) (last xs)\n\t\n\tlet ans = zip (map show mns) (map show mxs) \n\tstr_printer ans\n\nstr_printer :: [(String,String)] -> IO ()\nstr_printer [] = return ()\nstr_printer (x:xs) = do putStr $ (fst x) ++ \" \"; putStrLn $ snd x ; str_printer xs\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmymax s1 s2 a = max (a-s1) (s2-a)\nmymin a b c = min (b-a) (c-b)\nmyprint a b = intercalate \" \" $ map show [a,b]\n \nmain=do\t \n\tgetLine\n\ts<-map (fst.fromJust.C.readInt). C.words<$> C.getLine::IO [Int]\n\tlet s1 = head s\n\tlet s2 = last s\n\tlet maxs = map (mymax s1 s2) s\n\tlet mins1 = (zipWith3 (\\a b c ->mymin a b c) s (tail s) (tail (tail s)))\n\tlet mins2 = ((head (tail s))-(head s)): mins1 \n\tlet mins = mins2 ++[ last s- (last (init s))]\n\tputStrLn $ intercalate \"\\n\" $ zipWith (myprint) mins maxs\n\t \n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nsolve :: [Int] -> Int -> Int -> [(Int, Int)]\nsolve (x' : x : [x'']) a b = [minMax x x' x'' a b]\nsolve (x' : x : x'' : xs) a b =\n minMax x x' x'' a b : solve (x : x'' : xs) a b\n\nminMax :: Int -> Int -> Int -> Int -> Int -> (Int, Int)\nminMax x x' x'' a b =\n let min' = min (dist x x') (dist x x'')\n max' = max (dist x a) (dist x b)\n in (min', max')\n\nedgeHead :: [Int] -> (Int, Int)\nedgeHead xs@(x:x':_) =\n let min' = dist x x'\n max' = dist (head xs) (last xs)\n in (min', max')\n\nedgeTail :: [Int] -> (Int, Int)\nedgeTail xs =\n let min' = dist (last xs) (last (init xs))\n max' = dist (head xs) (last xs)\n in (min', max')\n\ndist :: Int -> Int -> Int\ndist a b\n | a <= 0 && b <= 0 = abs (abs b - abs a)\n | a >= 0 && b <= 0 = a + abs b\n | a <= 0 && b >= 0 = b + abs a\n | a >= 0 && b >= 0 = abs (b - a)\n\nshowTuple :: (Int, Int) -> String\nshowTuple (a, b) = show a ++ \" \" ++ show b\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- (map (\\s -> read s::Int) . words) <$> getLine\n if length xs == 2\n then do\n putStrLn $ showTuple $ edgeHead xs\n putStrLn $ showTuple $ edgeTail xs\n else do\n putStrLn $ showTuple $ edgeHead xs\n mapM_ (putStrLn . showTuple) (solve xs (head xs) (last xs))\n putStrLn $ showTuple $ edgeTail xs\n"}, {"source_code": "import Data.List\nimport Data.Int\n\nmain :: IO ()\nmain = interact $ showMatrix . solve . getList\n\ngetList :: (Read a) => String -> [a]\ngetList = tail . fmap read . words\n\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix = unlines . fmap (unwords . fmap show) \n\nsolve :: [Int64] -> [[Int64]]\nsolve xs = transpose [minList, maxList]\n where minList = zipWith3 (\\a b c -> min (b - a) (c - b)) \n (-3 * 10 ^ (9::Int64) : xs) xs (tail xs ++ [3*10^(9::Int64)])\n maxList = fmap (\\x -> max (lst - x) (x - frst)) xs\n where frst = head xs\n lst = last xs"}], "negative_code": [{"source_code": "import Control.Arrow ((&&&), (***))\nimport Data.Functor ((<$>))\n\nmain :: IO ()\nmain = mapM_ (putStrLn . uncurry (++) . (show *** (' ':) . show)) =<< solve <$> (tail <$> map read <$> words <$> getContents)\n\nsolve :: [Integer] -> [(Integer, Integer)]\nsolve xs = zip (uncurry (zipWith min) $ (id &&& tail) $ zipWith (-) (xs ++ [last xs + abs (head xs)]) ((head xs - abs (last xs)) : xs)) [ max (x - head xs) (last xs - x) | x <- xs ]\n"}, {"source_code": "import Control.Arrow ((&&&), (***))\nimport Data.Functor ((<$>))\n\nmain :: IO ()\nmain = mapM_ (putStrLn . uncurry (++) . (show *** (' ':) . show)) =<< solve <$> (tail <$> map read <$> words <$> getContents)\n\nsolve :: [Int] -> [(Int, Int)]\nsolve xs = zip (uncurry (zipWith min) $ (id &&& tail) $ zipWith (-) (xs ++ [maxBound]) (minBound : xs)) [ max (x - head xs) (last xs - x) | x <- xs ]\n"}, {"source_code": "import Data.Int (Int64)\n\nprocess :: [Int64] -> [(Int64,Int64)]\nprocess xs = zip dmins dmaxs\n where\n dl = zipWith (-) xs (minBound:xs)\n dr = zipWith (-) (tail xs ++ [maxBound]) xs\n dmins = zipWith min dl dr\n cmin = head xs\n cmax = last xs\n cmid = (cmin + cmax) `div` 2\n dmaxs = map (\\x -> if x <= cmid then cmax-x else x-cmin) xs\n\nreadInt :: String -> Int64\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n mapM_ (\\(l,r) -> putStrLn (show l ++ \" \" ++ show r)) $ process xs"}, {"source_code": "process :: [Int] -> [(Int,Int)]\nprocess xs = zip dmins dmaxs\n where\n dl = zipWith (-) xs (minBound:xs)\n dr = zipWith (-) (tail xs ++ [maxBound]) xs\n dmins = zipWith min dl dr\n cmin = head xs\n cmax = last xs\n cmid = (cmin + cmax) `div` 2\n dmaxs = map (\\x -> if x <= cmid then cmax-x else x-cmin) xs\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n mapM_ (\\(l,r) -> putStrLn (show l ++ \" \" ++ show r)) $ process xs"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = interact $ showMatrix . solve . getList\n\ngetList :: (Read a) => String -> [a]\ngetList = tail . fmap read . words\n\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix = unlines . fmap (unwords . fmap show) \n\nsolve :: [Int] -> [[Int]]\nsolve xs = transpose [minList, maxList]\n where minList = zipWith3 (\\a b c -> min (b - a) (c - b)) (minBound : xs) xs (tail xs ++ [maxBound])\n maxList = fmap (\\x -> max (lst - x) (x - frst)) xs\n where frst = head xs\n lst = last xs"}, {"source_code": "import Data.List\nimport Data.Int\n\nmain :: IO ()\nmain = interact $ showMatrix . solve . getList\n\ngetList :: (Read a) => String -> [a]\ngetList = tail . fmap read . words\n\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix = unlines . fmap (unwords . fmap show) \n\nsolve :: [Int64] -> [[Int64]]\nsolve xs = transpose [minList, maxList]\n where minList = zipWith3 (\\a b c -> min (b - a) (c - b)) (minBound : xs) xs (tail xs ++ [maxBound])\n maxList = fmap (\\x -> max (lst - x) (x - frst)) xs\n where frst = head xs\n lst = last xs"}], "src_uid": "55383f13c8d097408b0ccf5653c4563d"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n [n,k] <- map read.words <$> getLine\n arr <- listArray ((0,0),(1,n-1)).concat.lines <$> getContents\n putStrLn $ solve n k arr\n\nsolve :: Int -> Int -> UArray (Int,Int) Char -> String\nsolve n k arr = bfs 0 [(0,0)] visited0\n where\n visited0 = listArray ((0,0),(1,n-1)) $ True : repeat False\n bfs !water xs visited\n | null next = \"NO\"\n | any isGoal next = \"YES\"\n | otherwise = bfs (water+1) next (update next visited)\n where\n isGoal (x,y) = y>=n-1\n next = nub $ xs >>= childs\n jump (0,y) = (1,y+k)\n jump (1,y) = (0,y+k)\n childs (x0,y0) = do\n (x,y) <- [(x0,y0+1),(x0,y0-1),jump(x0,y0)]\n guard $ water < y\n if y > n-1\n then return (x,y)\n else do\n guard $ not (visited!(x,y)) && arr!(x,y) == '-'\n return (x,y)\n\nupdate :: [(Int,Int)] -> UArray (Int,Int) Bool -> UArray (Int,Int) Bool\nupdate [] arr = arr\nupdate xs arr = runSTUArray $ do\n a <- unsafeThaw arr\n go a xs\n return a\n where\n go a [] = return ()\n go a (x:xs) = do\n writeArray a x True\n go a xs\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntSet as S\nimport Control.Applicative ((<$>))\nimport Data.Sequence as Seq ((|>),ViewL(..),viewl,singleton,length)\n\ngetTwoLines = sequence [B.getLine,B.getLine]\n\nmain = do\n [h,k] <- map read . words <$> getLine :: IO [Int]\n xs <- getTwoLines\n let (f,valid,q,vs) = (done h, validNext xs h k\n ,singleton ((0,0),0),S.empty)\n cst = bfs f valid q vs :: Int\n putStrLn $ if blocked h k xs || cst > h then \"NO\" else \"YES\"\n\nblocked h k b = cnt 0 0 == k\n where cnt i c\n | i == h || c == k = c\n | all (=='X') [b?(0,i),b?(1,i)] = cnt (i+1) (c+1)\n | otherwise = cnt (i+1) 0\n\n[b1,_] ? (0,j) = B.index b1 j\n[_,b2] ? (1,j) = B.index b2 j\n\nvalidNext b h k vs ((i,j),t) = filter valid next\n where next = zip [(1-i,j+k),(i,j+1), (i,j-1)] $ repeat (t+1)\n valid ((x,y),iter) =\n iter <= y && (not $ visited vs (x,y)) && (y >= h || b?(x,y) /= 'X')\n\ndone h ((_,j),_) = j >= h\n\nvisited vs (i,j) = S.member (i*100000+j) vs\nmark vs (i,j) = S.insert (i*100000+j) vs\n\nbfs done next q vs =\n case viewl q of\n a@((i,j),_) :< qs ->\n if reallyDone then 0 else bfs done next nq $ mark vs (i,j)\n where nxt= if visited vs (i,j) then [] else next vs a\n reallyDone = done a || any done nxt\n nq = foldl (|>) qs nxt\n EmptyL -> maxBound\n"}], "negative_code": [], "src_uid": "e95bde11483e05751ee7da91a6b4ede1"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (x1:y1:x2:y2:_) <- map read . words <$> getLine\n print $ (x2 - x1) * (y2 - y1) + 1", "positive_code": [{"source_code": "import Control.Arrow\nimport Control.Monad.State\nimport Data.Array\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = C.interact $\n C.lines >>> drop 1 >>> map (C.words >>> map readInt >>> solve >>> show >>> C.pack) >>> C.unlines\n\nreadInt = C.readInt >>> fromJust >>> fst\n\nsolve :: [Int] -> Integer\nsolve [x1,y1,x2,y2] = n*m + 1\n where\n n = fromIntegral (x2-x1)\n m = fromIntegral (y2-y1)\n\n\n\n"}, {"source_code": "solve :: [[Integer]] -> [Integer]\nsolve [] = []\nsolve (x:xs) = (count x) : (solve xs)\n\ncount :: [Integer] -> Integer\ncount [x1,y1,x2,y2]\n\t| x1 > x2 \t\t= \t\t0\n\t| y1 > y2 \t\t= \t\t0\n\t| x1 == x2\t\t= \t\t1\n\t| y1 == y2 \t\t= \t\t1 \n\t| otherwise\t\t= \t\ta * b - (a + b - 1) + 1\n\twhere \n\t\ta = x2 - x1 + 1\n\t\tb = y2 - y1 + 1\n\nmain = do\n\tt' <- getLine\n\tlet t = read t' :: Int\n\tfin <- getContents\n\tlet input = map (map read) (map words (take t (lines fin))) :: [[Integer]]\n\tlet result = solve input\n\tmapM print result"}, {"source_code": "import Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let (_:tokens) = split input\n vals = read <$> tokens :: [Integer]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n x1:y1:x2:y2:rest ->\n let area = (x2-x1) * (y2-y1)\n in Just (1 + area, rest)\n ) vals\n sequence_ $ putStrLn . show <$> res\n"}, {"source_code": "import Data.List (sort, foldl')\nimport Data.Traversable (for)\nimport Control.Applicative (liftA2)\n\nsolveCase :: ((Integer, Integer), (Integer, Integer)) -> Integer\nsolveCase ((p,q), (x,y)) = 1 + (x-p)*(y-q)\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n _ <- for [1..t] $ \\_ -> do\n nums <- (map read . words) <$> getLine :: IO [Integer]\n case nums of\n [p,q,x,y] -> print (solveCase ((p,q),(x,y)))\n _ -> putStrLn \"bad input format\"\n return ()\n"}, {"source_code": "type Point = (Integer, Integer)\n\nsolve :: Integer -> Integer -> Integer -> Integer -> Integer\nsolve x1 y1 x2 y2 = 1 + ((x2-x1)*(y2-y1))\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n\nparse :: String -> String\nparse input = show $ solve x1 y1 x2 y2\n where [x1, y1, x2, y2] = map (\\x -> read x :: Integer) $ words input\n"}], "negative_code": [{"source_code": "import Control.Arrow\nimport Control.Monad.State\nimport Data.Array\nimport Data.Bits\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport Data.Function\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\nmain = C.interact $\n C.lines >>> drop 1 >>> map (C.words >>> map readInt >>> solve >>> show >>> C.pack) >>> C.unlines\n\nreadInt = C.readInt >>> fromJust >>> fst\n\nsolve [x1,y1,x2,y2] = n*m + 1\n where\n n = (x2-x1)\n m = (y2-y1)\n\n\n\n"}, {"source_code": "solve :: [[Int]] -> [Int]\nsolve [] = []\nsolve (x:xs) = (count x) : (solve xs)\n\ncount :: [Int] -> Int\ncount [x1,y1,x2,y2]\n\t| x1 > x2 \t\t= \t\t0\n\t| y1 > y2 \t\t= \t\t0\n\t| x1 == x2\t\t= \t\t1\n\t| y1 == y2 \t\t= \t\t1 \n\t| otherwise\t\t= \t\tmax (x2 - x1) (y2 - y1) + 1\n\nmain = do\n\tt' <- getLine\n\tlet t = read t' :: Int\n\tfin <- getContents\n\tlet input = map (map read) (map words (take t (lines fin))) :: [[Int]]\n\tlet result = solve input\n\tmapM print result"}, {"source_code": "solve :: [[Int]] -> [Int]\nsolve [] = []\nsolve (x:xs) = (count x) : (solve xs)\n\ncount :: [Int] -> Int\ncount [x1,y1,x2,y2]\n\t| x1 > x2 \t\t= \t\t0\n\t| y1 > y2 \t\t= \t\t0\n\t| x1 == x2\t\t= \t\t1\n\t| y1 == y2 \t\t= \t\t1 \n\t| otherwise\t\t= \t\ta * b - (a + b - 1) + 1\n\twhere \n\t\ta = x2 - x1 + 1\n\t\tb = y2 - y1 + 1\n\nmain = do\n\tt' <- getLine\n\tlet t = read t' :: Int\n\tfin <- getContents\n\tlet input = map (map read) (map words (take t (lines fin))) :: [[Int]]\n\tlet result = solve input\n\tmapM print result"}], "src_uid": "1b13c9d9fa0c5a44d035bcf6d70e1a60"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Monoid\nimport Control.Monad\nimport Debug.Trace\nimport Text.Printf\n\nkmpJumpBack :: B.ByteString -> Array Int Int\nkmpJumpBack str = arr\n where len = B.length str\n arr = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]\n f' = (arr !)\n str' n = B.head $ B.drop (n-1) str\n f i k\n | i <= 1 = 0\n | str'(k+1) == str'(i) = k+1\n | k == 0 = 0\n | otherwise = f i $ f' k\n\nsolve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String\nsolve n alph str acc = f' 0 0\n where len = B.length str\n arr :: Array (Int, Int) (Maybe String)\n arr = listArray ((0,0), (n,len-1)) $\n [f pos st | pos <- [0..n], st <- [0..len-1]]\n f' = curry (arr !)\n\n acc' :: Int -> Int\n acc' pos = if pos < len then 0\n else ord (B.head $ B.drop (pos - len) acc) - ord '0'\n\n jumpBack = (kmpJumpBack str !)\n str' n = B.head $ B.drop (n-1) str\n ch n = chr $ ord 'a' + n\n\n jump st i\n | str'(st+1) == ch i\n = if st + 1 == len\n then (1, jumpBack(st+1))\n else (0, st + 1)\n | st == 0 = (0,0)\n | otherwise = jump (jumpBack st) i\n\n f pos st\n | pos == n = Just []\n | otherwise = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]\n where\n tryJump :: Int -> Maybe String\n tryJump i = do\n let (a, st') = jump st i\n\n guard $ a == acc'(pos+1)\n\n ret <- f' (pos+1) st'\n return $ chr (i + ord 'a'):ret\n\n\nmain = do\n [n, alph] <- (map read . words) `fmap` getLine\n [str] <- B.words `fmap` B.getLine\n [acc] <- B.words `fmap` B.getLine\n\n case solve n alph str acc of\n Just ans -> putStrLn ans\n Nothing -> putStrLn \"No solution\"\n\n", "positive_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Monoid\nimport Control.Monad\nimport Debug.Trace\nimport Text.Printf\n\nkmpJumpBack :: B.ByteString -> Array Int Int\nkmpJumpBack str = arr\n where len = B.length str\n arr = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]\n f' = (arr !)\n str' n = B.head $ B.drop (n-1) str\n f i k\n | i <= 1 = 0\n | str'(k+1) == str'(i) = k+1\n | k == 0 = 0\n | otherwise = f i $ f' k\n\njumpTable :: B.ByteString -> Int -> Array (Int, Int) (Int, Int)\njumpTable str alph = arr\n where len = B.length str\n arr = listArray ((0,0), (len-1, alph-1)) $\n [f st i | st <- [0..len-1], i <- [0..alph-1]]\n f' = curry (arr !)\n str' n = B.head $ B.drop (n-1) str\n ch x = chr $ ord 'a' + x\n f st i\n | str'(st+1) == ch i\n = if st + 1 == len\n then (1, jumpBack(st+1))\n else (0, st + 1)\n | st == 0 = (0,0)\n | otherwise = f (jumpBack st) i\n\n jumpBack = (kmpJumpBack str !)\n\nsolve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String\nsolve n alph str acc = f' 0 0\n where len = B.length str\n arr :: Array (Int, Int) (Maybe String)\n arr = listArray ((0,0), (n,len-1)) $\n [f pos st | pos <- [0..n], st <- [0..len-1]]\n f' = curry (arr !)\n\n acc' :: Int -> Int\n acc' pos = if pos < len then 0\n else ord (B.head $ B.drop (pos - len) acc) - ord '0'\n\n jumpTable' = jumpTable str alph\n jump = curry (jumpTable'!)\n\n f pos st\n | pos == n = Just []\n | otherwise = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]\n where\n tryJump :: Int -> Maybe String\n tryJump i = do\n let (a, st') = jump st i\n\n guard $ a == acc'(pos+1)\n\n ret <- f' (pos+1) st'\n return $ chr (i + ord 'a'):ret\n\n\nmain = do\n [n, alph] <- (map read . words) `fmap` getLine\n [str] <- B.words `fmap` B.getLine\n [acc] <- B.words `fmap` B.getLine\n\n case solve n alph str acc of\n Just ans -> putStrLn ans\n Nothing -> putStrLn \"No solution\"\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Monoid\nimport Control.Monad\nimport Debug.Trace\nimport Text.Printf\n\nkmpJumpBack :: B.ByteString -> Array Int Int\nkmpJumpBack str = arr\n where len = B.length str\n arr = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]\n f' = (arr !)\n str' n = B.head $ B.drop (n-1) str\n f i k\n | i <= 1 = 0\n | str'(k+1) == str'(i) = k+1\n | k == 0 = 0\n | otherwise = f i $ f' k\n\njumpTable :: B.ByteString -> Int -> Array (Int, Int) (Int, Int)\njumpTable str alph = arr\n where len = B.length str\n arr = listArray ((0,0), (len-1, alph-1)) $\n [f st i | st <- [0..len-1], i <- [0..alph-1]]\n f' = curry (arr !)\n str' n = B.head $ B.drop (n-1) str\n ch x = chr $ ord 'a' + x\n f st i\n | str'(st+1) == ch i\n = if st + 1 == len\n then (1, jumpBack(st+1))\n else (0, st + 1)\n | st == 0 = (0,0)\n | otherwise = f (jumpBack st) i\n\n jumpBack = (kmpJumpBack str !)\n\nsolve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String\nsolve n alph str acc = f' 0 0\n where len = B.length str\n arr :: Array (Int, Int) (Maybe String)\n arr = listArray ((0,0), (n,len-1)) $\n [f pos st | pos <- [0..n], st <- [0..len-1]]\n f' = curry (arr !)\n\n acc' :: Int -> Int\n acc' pos = if pos < len then 0\n else ord (B.head $ B.drop (pos - len) acc) - ord '0'\n\n jumpTable' = jumpTable str alph\n jump = curry (jumpTable'!)\n\n f pos st\n | pos == n = Just []\n | otherwise = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]\n where\n tryJump :: Int -> Maybe String\n tryJump i = do\n let (a, st') = jump st i\n\n guard $ a == acc'(pos+1)\n\n ret <- f' (pos+1) st'\n return $ chr (i + ord 'a'):ret\n\n\nmain = do\n [n, alph] <- (map read . words) `fmap` getLine\n str <- B.getLine\n acc <- B.getLine\n\n printf \"%d %d %d %d\\n\" n alph (length $ B.unpack str) (length $ B.unpack acc)\n\n case solve n alph str acc of\n Just ans -> putStrLn ans\n Nothing -> putStrLn \"No solution\"\n\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Array.IArray\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Monoid\nimport Control.Monad\nimport Debug.Trace\n\nkmpJumpBack :: B.ByteString -> Array Int Int\nkmpJumpBack str = arr\n where len = B.length str\n arr = listArray (0, len) $ [f i $ f'(i-1) | i <- [0..len]]\n f' = (arr !)\n str' n = B.head $ B.drop (n-1) str\n f i k\n | i <= 1 = 0\n | str'(k+1) == str'(i) = k+1\n | k == 0 = 0\n | otherwise = f i $ f' k\n\njumpTable :: B.ByteString -> Int -> Array (Int, Int) (Int, Int)\njumpTable str alph = arr\n where len = B.length str\n arr = listArray ((0,0), (len-1, alph-1)) $\n [f st i | st <- [0..len-1], i <- [0..alph-1]]\n f' = curry (arr !)\n str' n = B.head $ B.drop (n-1) str\n ch x = chr $ ord 'a' + x\n f st i\n | str'(st+1) == ch i\n = if st + 1 == len\n then (1, jumpBack(st+1))\n else (0, st + 1)\n | st == 0 = (0,0)\n | otherwise = f (jumpBack st) i\n\n jumpBack = (kmpJumpBack str !)\n\nsolve :: Int -> Int -> B.ByteString -> B.ByteString -> Maybe String\nsolve n alph str acc = f' 0 0\n where len = B.length str\n arr :: Array (Int, Int) (Maybe String)\n arr = listArray ((0,0), (n,len-1)) $\n [f pos st | pos <- [0..n], st <- [0..len-1]]\n f' = curry (arr !)\n\n acc' :: Int -> Int\n acc' pos = if pos < len then 0\n else ord (B.head $ B.drop (pos - len) acc) - ord '0'\n\n jumpTable' = jumpTable str alph\n jump = curry (jumpTable'!)\n\n f pos st\n | pos == n = Just []\n | otherwise = getFirst $ mconcat [First $ tryJump i | i <- [0..alph-1]]\n where\n tryJump :: Int -> Maybe String\n tryJump i = do\n let (a, st') = jump st i\n\n guard $ a == acc'(pos+1)\n\n ret <- f' (pos+1) st'\n return $ chr (i + ord 'a'):ret\n\n\nmain = do\n [n, alph] <- (map read . words) `fmap` getLine\n str <- B.getLine\n acc <- B.getLine\n\n case solve n alph str acc of\n Just ans -> putStrLn ans\n Nothing -> putStrLn \"No solution\"\n\n"}], "src_uid": "c7ee054dea66f06b54e1b21c85a8379c"} {"source_code": "solve :: (Integer, Integer, Integer) -> Integer\nsolve (h, c, t)\n | 2 * t <= h + c = 2\n | otherwise = let\n n = 2 * t - h - c\n d = h - c\n q = quot d (2 * n)\n v1 = 2*q + 1\n v2 = v1 + 2\n in if (v1 + v2) * d <= v1 * v2 * 2 * n\n -- 1 / v1 - n / d <= n / d - 1 / v2\n then v1 else v2\n\nparse :: String -> [(Integer, Integer, Integer)]\nparse inp = [(h, c, t) | [h, c, t] <- map (map read . words) . tail $ lines inp]\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve) . parse)\n\n\n", "positive_code": [{"source_code": "import Data.Int\nimport Data.Ratio\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve . parse). tail . lines)\n\nparse :: String -> (Int64, Int64, Int64)\nparse s = (h, c, t)\n where\n [h, c, t] = map read . words $ s\n\nsolve :: (Int64, Int64, Int64) -> Int64\nsolve (h, c, t)\n | 2 * t <= h + c = 2\n | f n <= f (n + 1) = 2 * n + 1\n | otherwise = 2 * (n + 1) + 1\n where\n n = div (h - t) (2 * t - (h + c))\n f k = abs (fromIntegral t - ((k + 1) * h + k * c) % (2 * k + 1))\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Data.List\nimport Data.Ratio\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\noddRoundDown n\n | (n `mod` 2 == 0) = if n >= 2 then n - 1 else n + 1\n | otherwise = n\n\noddRoundUp n\n | (n `mod` 2 == 0) = n + 1\n | otherwise = n\n\nmixTemp :: Rational -> Rational -> Integer -> Rational\nmixTemp c h numCups =\n let numH = ((numCups + 1) `div` 2) % 1\n numC = (numCups `div` 2) % 1\n in (numC * c + numH * h) / (numC + numH)\n\nmain = do\n input <- getContents\n let (_:vals) = read <$> split input :: [Integer]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n hInt:cInt:tgtInt:rest -> Just (res, rest) where\n res = let\n h = hInt % 1\n c = cInt % 1\n tgt = tgtInt % 1\n avg = (c+h) / 2\n in if\n | tgt <= avg -> 2\n | otherwise ->\n let diff = tgt - avg\n exact = (h - avg) / diff\n num = numerator exact\n denom = denominator exact\n near1 = oddRoundDown $ num `div` denom\n near2 = oddRoundUp $ (num + denom - 1) `div` denom\n temp1 = mixTemp c h near1\n temp2 = mixTemp c h near2\n in if abs (temp1 - tgt) <= abs (temp2 - tgt) then near1 else near2\n ) vals\n sequence_ (putStrLn . show <$> res)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.Ratio\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (h:c:t:_) <- map read . words <$> getLine\n if t == h\n then print 1\n else if t <= (c + h) `div` 2\n then print 2\n else do\n let x = (t - h) `div` (c + h - 2 * t)\n print $\n ((+ 1) . (* 2)) $\n minimumBy\n (comparing (\\x -> abs $ fromInteger t - (x * c + (x + 1) * h) % (2 * x + 1)))\n [max (x - 5) 0 .. x + 5]"}], "negative_code": [{"source_code": "import Data.Ratio\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve . parse). tail . lines)\n\nparse :: String -> (Int, Int, Int)\nparse s = (h, c, t)\n where\n [h, c, t] = map read . words $ s\n\nsolve :: (Int, Int, Int) -> Int\nsolve (h, c, t)\n | 2 * t <= h + c = 2\n | f n <= f (n + 1) = 2 * n + 1\n | otherwise = 2 * (n + 1) + 1\n where\n n = div (h - t) (2 * t - (h + c))\n f k = abs (fromIntegral t - ((k + 1) * h + k * c) % (2 * k + 1))\n"}, {"source_code": "import Data.Ratio\n\nmain :: IO ()\nmain = interact (unlines . map (show . solve . parse). tail . lines)\n\nparse :: String -> (Int, Int, Int)\nparse s = (h, c, t)\n where\n [h, c, t] = map read . words $ s\n\nsolve :: (Int, Int, Int) -> Int\nsolve (h, c, t)\n | 2 * t <= h + c = 2\n | f n < f (n + 1) = 2 * n + 1\n | otherwise = 2 * (n + 1) + 1\n where\n n = div (h - t) (2 * t - (h + c))\n f k = abs (fromIntegral t - ((k + 1) * h + k * c) % (2 * k + 1))\n"}], "src_uid": "ca157773d06c7d192589218e2aad6431"} {"source_code": "import Control.Monad (replicateM_)\n\nmain :: IO ()\nmain = do\n\tn <- getLine\n\treplicateM_ (read n) $ do\n\t\tzm <- fmap (read . head . tail . words) getLine\n\t\tprint (zm*2)\n", "positive_code": [{"source_code": "solve :: Int -> IO ()\nsolve 0 = return ()\nsolve t = do\n line <- getLine\n let [_, b] = map (\\x -> read x :: Int) $ words line\n print $ 2 * b\n solve $ t - 1\n\nmain :: IO ()\nmain = do\n line <- getLine\n let t = read line :: Int\n solve t\n"}, {"source_code": "main = interact $ unlines . map (show . solve) . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve (_,x) = 2*x\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.Map as M\n\n\nonecase = do\n\t\t[a,x]<-map read <$> words <$> getLine::IO [Int]\n\t\tprint $ x+ x\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\treplicateM_ n onecase\n\n"}, {"source_code": "process :: Int -> Int -> Int\nprocess n x = 2*x\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ print $ map (\\[n,x] -> process n x) ts"}, {"source_code": "import Data.Char (ord)\nimport Control.Monad (replicateM_)\n\nparseInt :: String -> Int\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nsolve :: [Int] -> Int\nsolve [_, x] = x * 2\n\nmain :: IO ()\nmain = do\n testNum <- fmap parseInt getLine\n replicateM_ testNum (print . solve . map parseInt . words =<< getLine)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tt <- readInt\n\treplicateM t $ do\n\t\t[ x, n ] <- readInts\n\t\tprint $ n * 2"}], "negative_code": [{"source_code": "main = interact $ unlines . map (show . solve) . pairs . map read . tail . words\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve (_,x) = s !! (x-1)\ns = go 0 [1..] where\n go i xs | null r = xs\n | otherwise = l ++ go (i+1) (tail r)\n where (l,r) = splitAt i xs\n"}], "src_uid": "f79a926e18a3f81b24f2fc3ae5c8f928"} {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\nimport Data.List\nimport Data.Int\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nreadInt64s :: SIO [Int64]\nreadInt64s = do\n currLine <- readLine\n pure [fromIntegral x | Just (x, _) <- P.readInteger <$> P.words currLine]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n, k] <- readInt64s\n x1 : x <- readInt64s\n let\n w = foldl' gcd 0 $ map (x1 -) x\n lift . P.putStrLn . P.pack $ if mod (k-x1) w == 0\n then \"YES\"\n else \"NO\"\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad ( foldM\n , replicateM\n , replicateM_\n )\nimport Data.Array ( listArray )\nimport Data.Foldable ( maximumBy )\nimport Data.Int ( Int64 )\nimport qualified Data.Map as Map\n\nsolve :: Int64 -> [Int64] -> Bool\nsolve _ [] = False\nsolve k [x ] = k == x\nsolve k (x : xs) = k == x || not (null xs') && (k - x) `mod` foldl1 gcd xs' == 0 where xs' = filter (/= 0) (subtract x <$> xs)\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ go\n where\n go = do\n k <- (!! 1) . fmap read . words <$> getLine\n r <- solve k . fmap read . words <$> getLine\n if r then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Functor ((<&>))\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n let getList = getLine <&> words <&> map read\r\n [tests_n] <- getList\r\n replicateM_ tests_n $ do\r\n [n, k] <- getList\r\n xs <- getList\r\n let output = if canGetK k xs then \"YES\" else \"NO\"\r\n putStrLn output\r\n\r\n\r\ncanGetK :: Integral int => int -> [int] -> Bool\r\ncanGetK k [] = False\r\ncanGetK k (x:xs) = step `divides` (k - x)\r\n where\r\n relative_xs = map (subtract x) xs\r\n step = foldr gcd 0 relative_xs\r\n\r\n\r\ndivides :: (Integral int) => int -> int -> Bool\r\ndivides 0 x = x == 0\r\ndivides d x = mod x d == 0\r\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n [_, k] <- map read . words <$> getLine :: IO [Integer]\n xs <- map read . words <$> getLine :: IO [Integer]\n let d = foldl gcd 0 (zipWith (-) <*> tail $ sort xs)\n putStrLn $ bool \"NO\" \"YES\" $ k `mod` d == head xs `mod` d\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad ( foldM\n , replicateM\n , replicateM_\n )\nimport Data.Array ( listArray )\nimport Data.Foldable ( maximumBy )\nimport qualified Data.Map as Map\n\nsolve :: Int -> [Int] -> Bool\nsolve _ [] = False\nsolve k [x ] = k == x\nsolve k (x : xs) = k == x || not (null xs') && (k - x) `mod` foldl1 gcd xs' == 0 where xs' = filter (/= 0) (subtract x <$> xs)\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ go\n where\n go = do\n k <- (!! 1) . fmap read . words <$> getLine\n r <- solve k . fmap read . words <$> getLine\n if r then putStrLn \"YES\" else putStrLn \"NO\"\n"}, {"source_code": "module Main where\n\nimport Control.Monad ( foldM\n , replicateM\n , replicateM_\n )\nimport Data.Array ( listArray )\nimport Data.Foldable ( maximumBy )\nimport Data.List\nimport qualified Data.Map as Map\n\n-- >>> solve 1 $ sort [1,2]\n-- True\n\nsolve :: Int -> [Int] -> Bool\nsolve _ [] = False\nsolve k [x ] = k == x\nsolve k (x : xs) = k == x || not (null xs') && k - x `mod` foldl1 gcd xs' == 0 where xs' = filter (/= 0) (subtract x <$> xs)\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ go\n where\n go = do\n k <- (!! 1) . fmap read . words <$> getLine\n r <- solve k . fmap read . words <$> getLine\n if r then putStrLn \"YES\" else putStrLn \"NO\"\n"}], "src_uid": "ccb5369bc4175ba071969571ceb17227"} {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Array.Unboxed as UArray\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.Map.Strict as Map\n-- import Data.Map.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' == ord ' ' || c' == ord '\\r' -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [(Id, Int)]\ndata ChainNode = ChainNode {\n nodeValue :: Int\n , nodeIndex :: Id\n , nodeNeighA :: Maybe ChainNode\n , nodeNeighB :: Maybe ChainNode\n }\n\nchainItems (Chain _ xs) = xs\n\ngroupId :: Group -> Id\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode i x) | (i, x) <- zip [0..] xs]\n buildNode i x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode {\n nodeValue = x\n , nodeIndex = i\n , nodeNeighA = neighbour a\n , nodeNeighB = neighbour b\n }\n traceItems :: Group -> ChainNode -> [(Id, Int)]\n traceItems g chain@(ChainNode { nodeValue = x, nodeIndex = i, nodeNeighA = na, nodeNeighB = nb })\n | g == G1 = if isNothing na || (nodeValue na' == x) then [item] else item : traceItems G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [item] else item : traceItems G1 nb'\n where\n Just na' = na\n Just nb' = nb\n item = (i, x)\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node -> let\n na = nodeNeighA node\n nb = nodeNeighB node\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceItems G1 node]\n else Just [Chain G2 $ traceItems G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g items) = \n if length items `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n (i0, x0) = head items\n (i1, x1) = last items\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\ngetGroupMap :: Int -> [(Id, Group)] -> [Maybe Group]\ngetGroupMap n xs = map t . UArray.elems $ gs where\n t (-1) = Nothing\n t 0 = Just G1\n t 1 = Just G2\n\n gs :: UArray.UArray Int Id\n gs = STArray.runSTUArray $ do\n gs <- STArray.newArray (0, n - 1) (-1)\n forM_ xs $ \\(i, g) -> STArray.writeArray gs i (groupId g)\n return gs\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = getGroupMap (length xs) . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(i, g) | (i, x) <- chainItems chain])\n sequence $ groupMap\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n case solve a b xs of\n No -> putStrLn \"NO\"\n Yes gs -> putStrLn \"YES\" >> putStrLn (unwords . map (show . groupId) $ gs)\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Array as Array\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.Map.Strict as Map\n-- import Data.Map.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' == ord ' ' || c' == ord '\\r' -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [(Id, Int)]\ndata ChainNode = ChainNode {\n nodeValue :: Int\n , nodeIndex :: Id\n , nodeNeighA :: Maybe ChainNode\n , nodeNeighB :: Maybe ChainNode\n }\n\nchainItems (Chain _ xs) = xs\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode i x) | (i, x) <- zip [0..] xs]\n buildNode i x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode {\n nodeValue = x\n , nodeIndex = i\n , nodeNeighA = neighbour a\n , nodeNeighB = neighbour b\n }\n traceItems :: Group -> ChainNode -> [(Id, Int)]\n traceItems g chain@(ChainNode { nodeValue = x, nodeIndex = i, nodeNeighA = na, nodeNeighB = nb })\n | g == G1 = if isNothing na || (nodeValue na' == x) then [item] else item : traceItems G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [item] else item : traceItems G1 nb'\n where\n Just na' = na\n Just nb' = nb\n item = (i, x)\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node -> let\n na = nodeNeighA node\n nb = nodeNeighB node\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceItems G1 node]\n else Just [Chain G2 $ traceItems G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g items) = \n if length items `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n (i0, x0) = head items\n (i1, x1) = last items\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\ngetGroupMap :: Int -> [(Id, Group)] -> [Maybe Group]\ngetGroupMap n xs = Array.elems gs where\n gs :: Array.Array Int (Maybe Group)\n gs = STArray.runSTArray $ do\n gs <- STArray.newArray (0, n - 1) Nothing\n forM_ xs $ \\(i, g) -> STArray.writeArray gs i (Just g)\n return gs\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = getGroupMap (length xs) . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(i, g) | (i, x) <- chainItems chain])\n sequence $ groupMap\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n case solve a b xs of\n No -> putStrLn \"NO\"\n Yes gs -> putStrLn \"YES\" >> putStrLn (unwords . map (show . groupId) $ gs)\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' == ord ' ' || c' == ord '\\r' -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- return . map read . words =<< getLine\n print $ solve a b xs\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\ndata Tree a = Null | Fork a (Tree a) (Tree a) deriving(Show)\n\nempty :: Tree a\nempty = Null\n\nisEmpty :: Tree a -> Bool\nisEmpty Null = True\nisEmpty _ = False\n\nminElem :: Tree a -> a\nminElem (Fork a _ _) = a\nminElem Null = error \"min for empty queue is not supported\"\n\ndeleteMin :: (Ord a) => Tree a -> Tree a\ndeleteMin (Fork _ a b) = merge a b\n\ninsert :: (Ord a) => a -> Tree a -> Tree a\ninsert x a = merge (Fork x Null Null) a\n\nmerge :: (Ord a) => Tree a -> Tree a -> Tree a\nmerge a Null = a\nmerge Null b = b\nmerge a b | minElem a <= minElem b = join a b\n | otherwise = join b a\n where\n join (Fork x a b) c = Fork x b (merge a c)\n\nsolve :: Int -> Int -> [Int] -> Maybe (S.Set Int,S.Set Int)\nsolve a b ps \n | a == b = guard (all (f.(a-)) ps) *> pure (S.fromList ps,S.empty)\n | otherwise = greedy queue S.empty S.empty s where\n s = S.fromList ps\n f p = p `S.member` s\n score p = length $ filter id $ [f (a - p),f (b - p)]\n queue :: Tree (Int,Int)\n queue = foldl (flip insert) Main.empty [ (k,p) | p <- ps, let k = score p ]\n greedy queue !as !bs !s\n | isEmpty queue = return (as, bs)\n | used = greedy (deleteMin queue) as bs s\n | k == 0 = Nothing\n | not $ S.member b' s = greedy (g (b - a') queue) as' bs s'\n | not $ S.member a' s = greedy (g (a - b') queue) as bs' s' where\n a' = a - p\n b' = b - p\n s' = S.delete p $ S.delete c $ s\n c = if not $ S.member b' s then a' else b'\n as' = S.insert p $ S.insert a' as\n bs' = S.insert p $ S.insert b' bs\n (k,p) = minElem queue\n used = S.member p as || S.member p bs || k == 2\n g x queue | f x = insert (score x-1,x)$deleteMin queue\n | otherwise = deleteMin queue\n\n \n \n\nmain = do\n [_,a,b] <- readInts\n ps <- readInts\n case solve a b ps of\n Nothing -> putStrLn \"NO\"\n Just (as,bs) -> do\n putStrLn \"YES\"\n let f p = if S.member p as then \"0\" else \"1\"\n putStrLn $ unwords $ map f ps\n"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' `elem` map ord \" \\t\" -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print xs\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' `elem` map ord \" \\n\" -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print xs\n print $ solve a b xs\n"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Debug.Trace\n\ntraceShow' x = traceShow x x\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Link = Link Group [Id] deriving Show\ntype GroupMap = Map.Map Id Group\n\ninstance Show Answer where\n show No = \"No\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map show' gs) where\n show' G1 = \"0\"\n show' G2 = \"1\"\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nputGroup :: Group -> GroupMap -> [Id] -> GroupMap\nputGroup g = foldr (flip Map.insert g)\n\ngroupMapToAnswer :: [Int] -> Maybe GroupMap -> Answer\ngroupMapToAnswer _ Nothing = No\ngroupMapToAnswer xs (Just groupMap) =\n if Map.size groupMap == length xs then Yes $ Map.elems groupMap\n else No\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = groupMapToAnswer xs $\n -- flip applyLinks initGroupMap $ (traceShow' $ findLinks Set.empty xs)\n flip applyLinks initGroupMap $ findLinks Set.empty xs\n where\n n = length xs\n initGroupMap = Map.empty\n values = Map.fromList . zip [0..] $ xs\n idMap = Map.fromList $ zip xs [0..]\n\n findLinks :: Set.Set Int -> [Int] -> [Link]\n findLinks used [] = []\n findLinks used (x:xs) = let\n y = a - x\n z = b - x\n inIdMap = (`Map.member` idMap)\n notUsed = not . (`Set.member` used)\n f1 = inIdMap y && notUsed y\n f2 = inIdMap z && notUsed z\n mLink = if (not f1 && not f2) then []\n else if (f1 || f2) && (not (f1 && f2)) then\n if f1 then [Link G1 $ traceIds a x]\n else [Link G2 $ traceIds b x]\n else []\n used' = case mLink of\n [] -> used\n [(Link _ ids)] -> Set.union used . Set.fromList . map (values!) $ ids\n in mLink ++ findLinks used' xs\n\n traceIds :: Int -> Int -> [Int]\n traceIds t x =\n if not (x `Map.member` idMap) then []\n else (idMap!x) : if x + x == t then [] else traceIds (a + b - t) (t - x)\n -- else (idMap!x) : traceIds (a + b - t) (t - x)\n\n applyLinks :: [Link] -> GroupMap -> Maybe GroupMap\n applyLinks [] g = Just g\n applyLinks (x:xs) g = applyLink x g >>= applyLinks xs\n\n applyLink :: Link -> GroupMap -> Maybe GroupMap\n applyLink link@(Link g ids) groupMap = let\n x0 = values ! head ids\n x1 = values ! last ids\n in if length ids `mod` 2 == 0 then\n -- put all ids to group g\n Just $ putGroup g groupMap ids\n else if g == G1 && x0 * 2 == b || g == G2 && x0 * 2 == a then\n -- put all ids to group other than g\n Just $ putGroup (otherGroup g) groupMap ids\n else if g == G1 && x1 * 2 == a || g == G2 && x1 * 2 == b then\n -- put all ids to group g\n Just $ putGroup g groupMap ids\n else\n Nothing\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- return . map read . words =<< getLine\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' `elem` map ord \" \\n\\r\\t\" -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print xs\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> case x of\n Nothing -> []\n Just x' -> [x']\n Just (c, cs)\n | c' == ord ' ' -> (case x of Nothing -> id; Just x' -> (x':)) $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' 0 where\n readInts' x s = case B.uncons s of\n Nothing -> []\n Just (c, cs)\n | c' == ord ' ' -> x : readInts' x cs\n | otherwise -> readInts' (x * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' `elem` map ord \" \\r\" -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print xs\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.Array.ST as STArray\nimport qualified Data.Array as Array\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.Map.Strict as Map\n-- import Data.Map.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> addX []\n Just (c, cs)\n | c' == ord ' ' || c' == ord '\\r' -> addX $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where c' = fromIntegral c\n where addX = (case x of Nothing -> id; Just x' -> (x':))\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [(Id, Int)]\ndata ChainNode = ChainNode {\n nodeValue :: Int\n , nodeIndex :: Id\n , nodeNeighA :: Maybe ChainNode\n , nodeNeighB :: Maybe ChainNode\n }\n\nchainItems (Chain _ xs) = xs\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode i x) | (i, x) <- zip [0..] xs]\n buildNode i x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode {\n nodeValue = x\n , nodeIndex = i\n , nodeNeighA = neighbour a\n , nodeNeighB = neighbour b\n }\n traceItems :: Group -> ChainNode -> [(Id, Int)]\n traceItems g chain@(ChainNode { nodeValue = x, nodeIndex = i, nodeNeighA = na, nodeNeighB = nb })\n | g == G1 = if isNothing na || (nodeValue na' == x) then [item] else item : traceItems G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [item] else item : traceItems G1 nb'\n where\n Just na' = na\n Just nb' = nb\n item = (i, x)\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node -> let\n na = nodeNeighA node\n nb = nodeNeighB node\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceItems G1 node]\n else Just [Chain G2 $ traceItems G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g items) = \n if length items `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n (i0, x0) = head items\n (i1, x1) = last items\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\ngetGroupMap :: Int -> [(Id, Group)] -> [Maybe Group]\ngetGroupMap n xs = Array.elems gs where\n gs :: Array.Array Int (Maybe Group)\n gs = STArray.runSTArray $ do\n gs <- STArray.newArray (0, n - 1) Nothing\n forM_ xs $ \\(i, g) -> STArray.writeArray gs i (Just g)\n return gs\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = getGroupMap (length xs) . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(i, g) | (i, x) <- chainItems chain])\n sequence $ groupMap\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n case solve a b xs of\n No -> putStrLn \"No\"\n Yes gs -> putStrLn \"YES\" >> putStrLn (unwords . map (show . groupId) $ gs)\n"}, {"source_code": "import qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Debug.Trace\n\ntraceShow' x = traceShow x x\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Link = Link Group [Id] deriving Show\ntype GroupMap = Map.Map Id Group\n\ninstance Show Answer where\n show No = \"No\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map show' gs) where\n show' G1 = \"0\"\n show' G2 = \"1\"\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nputGroup :: Group -> GroupMap -> [Id] -> GroupMap\nputGroup g = foldr (flip Map.insert g)\n\ngroupMapToAnswer :: Maybe GroupMap -> Answer\ngroupMapToAnswer Nothing = No\ngroupMapToAnswer (Just groupMap) = Yes $ Map.elems groupMap\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = groupMapToAnswer $\n flip applyLinks initGroupMap . checkLinks =<< sequence (findLinks Set.empty xs)\n where\n n = length xs\n initGroupMap = Map.empty\n values = Map.fromList . zip [0..] $ xs\n idMap = Map.fromList $ zip xs [0..]\n\n checkLinks :: [Link] -> [Link]\n checkLinks links =\n if (sum . map (\\(Link g ids) -> length ids) $ links) == n\n then links\n else error $ \"check link failed\" ++ show links\n\n findLinks :: Set.Set Int -> [Int] -> [Maybe Link]\n findLinks used [] = []\n findLinks used (x:xs) = let\n y = a - x\n z = b - x\n inIdMap = (`Map.member` idMap)\n notUsed = not . (`Set.member` used)\n f1 = inIdMap y && notUsed y\n f2 = inIdMap z && notUsed z\n mLink = if (not f1 && not f2) then [Nothing]\n else if (f1 || f2) && (not (f1 && f2)) then\n if f1 then [Just $ Link G1 $ traceIds a x]\n else [Just $ Link G2 $ traceIds b x]\n else []\n used' = case mLink of\n [] -> used\n [Nothing] -> used\n [Just (Link _ ids)] -> Set.union used . Set.fromList . map (values!) $ ids\n in mLink ++ findLinks used' xs\n\n traceIds :: Int -> Int -> [Int]\n traceIds t x =\n if not (x `Map.member` idMap) then []\n else (idMap!x) : if x + x == t then [] else traceIds (a + b - t) (t - x)\n -- else (idMap!x) : traceIds (a + b - t) (t - x)\n\n applyLinks :: [Link] -> GroupMap -> Maybe GroupMap\n applyLinks [] g = Just g\n applyLinks (x:xs) g = applyLink x g >>= applyLinks xs\n\n applyLink :: Link -> GroupMap -> Maybe GroupMap\n applyLink link@(Link g ids) groupMap = let\n x0 = values ! head ids\n x1 = values ! last ids\n in if length ids `mod` 2 == 0 then\n -- put all ids to group g\n Just $ putGroup g groupMap ids\n else if g == G1 && x0 * 2 == b || g == G2 && x0 * 2 == a then\n -- put all ids to group other than g\n Just $ putGroup (otherGroup g) groupMap ids\n else if g == G1 && x1 * 2 == a || g == G2 && x1 * 2 == b then\n -- put all ids to group g\n Just $ putGroup g groupMap ids\n else\n Nothing\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- return . map read . words =<< getLine\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Data.Char\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' Nothing where\n readInts' :: Maybe Int -> B.ByteString -> [Int]\n readInts' x s = case B.uncons s of\n Nothing -> case x of\n Nothing -> []\n Just x' -> [x']\n Just (c, cs)\n | c' == ord ' ' -> (case x of Nothing -> id; Just x' -> (x':)) $ readInts' Nothing cs\n | otherwise -> readInts' (Just $ (maybe 0 id x) * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print xs\n print $ solve a b xs\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Monad\nimport Data.Maybe\nimport Debug.Trace\nimport qualified Data.ByteString as B\nimport qualified Data.Set as Set\n\n-- import qualified Data.HashMap.Lazy as HashMap\n-- import Data.HashMap.Lazy ((!))\n\nimport qualified Data.Map as Map\nimport Data.Map ((!))\n\n-- Utils\n\nreadInts :: IO [Int]\nreadInts = B.getLine >>= return . readInts' 0 . (\\s -> traceShow (B.length s) s) where\n readInts' x s = case B.uncons s of\n Nothing -> []\n Just (c, cs)\n | c' == ord ' ' -> x : readInts' x cs\n | otherwise -> readInts' (x * 10 + c' - ord '0') cs\n where\n c' = fromIntegral c\n\n-- End of Utils\n\ndata Group = G1 | G2 deriving (Show, Eq)\ndata Answer = No | Yes [Group]\ntype Id = Int\ndata Chain = Chain Group [Id]\ndata ChainNode = ChainNode Int (Maybe ChainNode) (Maybe ChainNode)\n\ninstance Show Answer where\n show No = \"NO\"\n show (Yes gs) = \"YES\\n\" ++ unwords (map (show . groupId) gs)\n\nnodeValue (ChainNode x _ _) = x\nchainValues (Chain _ values) = values\n\ngroupId G1 = 0\ngroupId G2 = 1\n\notherGroup G1 = G2\notherGroup G2 = G1\n\nfindChains :: Int -> Int -> [Int] -> Maybe [Chain]\nfindChains a b xs = let\n nodes = Map.fromList [(x, buildNode x) | x <- xs]\n buildNode x = let\n neighbour t = Map.lookup (t - x) nodes\n in ChainNode x (neighbour a) (neighbour b)\n traceValues :: Group -> ChainNode -> [Int]\n traceValues g (ChainNode x na nb)\n | g == G1 = if isNothing na || (nodeValue na' == x) then [x] else x : traceValues G2 na'\n | g == G2 = if isNothing nb || (nodeValue nb' == x) then [x] else x : traceValues G1 nb'\n where\n Just na' = na\n Just nb' = nb\n in liftM concat . sequence . flip map (Map.elems nodes) $ \\node@(ChainNode x na nb) -> let\n Just (ChainNode y _ _) = na\n Just (ChainNode z _ _) = nb\n in if isNothing na && isNothing nb then Nothing\n else if isJust na && isJust nb then Just []\n else if isJust na then Just [Chain G1 $ traceValues G1 node]\n else Just [Chain G2 $ traceValues G2 node]\n\nmarkChain :: Int -> Int -> Chain -> Maybe Group\nmarkChain a b (Chain g values) = \n if length values `mod` 2 == 0 then Just g\n else if x0 + x0 == [b, a]!!groupId g then Just (otherGroup g)\n else if x1 + x1 == [a, b]!!groupId g then Just g\n else Nothing\n where\n x0 = head values\n x1 = last values\n\nsolveSame :: Int -> [Int] -> Answer\nsolveSame a xs = let\n xsSet = Set.fromList xs\n haveAns = all (`Set.member` xsSet) . map (a -) $ xs\n in if haveAns then Yes $ map (const G1) xs else No\n\nsolve :: Int -> Int -> [Int] -> Answer\nsolve a b xs\n | a == b = solveSame a xs\n | otherwise = maybe No Yes $ do\n chains <- findChains a b xs\n groups <- sequence . map (markChain a b) $ chains\n let groupMap = Map.fromList . flip concatMap (zip groups chains) $ (\n \\(g, chain) -> [(x, g) | x <- chainValues chain])\n sequence $ map (`Map.lookup` groupMap) xs\n\nmain = do\n [n, a, b] <- return . map read . words =<< getLine\n xs <- readInts\n print $ solve a b xs\n"}], "src_uid": "1a46737540d253583234193a026008e3"} {"source_code": "main :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Double] -> Double\nsolve a = let b = map fst $ filter (odd . snd) $ zip a [0..]\n in 5.0 + sum b / fromIntegral (length b)\n", "positive_code": [{"source_code": "main :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n\nsolve :: [Double] -> Double\nsolve a = let b = map fst $ filter (odd . snd) $ zip a [0..]\n in 5.0 + sum b / (fromIntegral (length b))\n"}], "negative_code": [], "src_uid": "4f4f25855794092ae4c8d9c8102ed4de"} {"source_code": "import Control.Monad\nimport Data.List (words)\nimport Data.Sequence (Seq,Seq (Empty, (:<|), (:|>)), fromList, (><), (<|), (|>), empty)\nimport Data.Foldable (toList)\n\n\n-- ex:\n-- 4 4\n-- 01?????0\n\ntype SChar = Seq Char\n\ncalc1 :: SChar -> Int -> Int -> SChar -> SChar -> (Int,Int,SChar)\ncalc1 Empty a b pref suf = (a,b, pref >< suf)\ncalc1 ('1' :<| Empty) a b pref suf = (a,b-1, pref >< ('1' <| suf))\ncalc1 ('0' :<| Empty) a b pref suf = (a-1,b, pref >< ('0' <| suf))\ncalc1 (x :<| Empty) a b pref suf = (a,b, pref >< (x <| suf))\ncalc1 s a b pref suf =\n let (x1 :<| xs1) = s\n (xs :|> xn) = xs1\n in\n case (x1,xn) of\n ('?','1') -> calc1 xs a (b-2) (pref |> '1') (xn <| suf)\n ('1','?') -> calc1 xs a (b-2) (pref |> x1) ('1' <| suf)\n ('?','0') -> calc1 xs (a-2) b (pref |> '0') (xn <| suf)\n ('0','?') -> calc1 xs (a-2) b (pref |> x1) ('0' <| suf)\n ('0','0') -> calc1 xs (a-2) b (pref |> x1) (xn <| suf)\n ('1','1') -> calc1 xs a (b-2) (pref |> x1) (xn <| suf)\n (_,_) -> calc1 xs a b (pref |> x1) (xn <| suf)\n\ncalc2 :: SChar -> Int -> Int -> SChar -> SChar -> SChar\ncalc2 Empty a b _ _ | a /= 0 || b /= 0 = fromList \"-1\"\ncalc2 Empty 0 0 pref suf = pref >< suf\ncalc2 ('?':<|Empty) a b pref suf\n | a == 1 && b == 0 = pref >< ('0' <| suf)\n | a == 0 && b == 1 = pref >< ('1' <| suf)\n | otherwise = fromList \"-1\"\ncalc2 ('1' :<| Empty) a b pref suf = calc2 empty a b pref ('1' <| suf)\ncalc2 ('0' :<| Empty) a b pref suf = calc2 empty a b pref ('0' <| suf)\ncalc2 (x :<| Empty) _ _ _ _ = fromList \"-1\"\n\ncalc2 s a b pref suf | a<0 && b<0 = fromList \"-1\"\ncalc2 s a b pref suf =\n let (x1 :<| xs1) = s\n (xs :|> xn) = xs1\n in\n case (x1,xn) of\n ('?','?') | a>1 -> calc2 xs (a-2) b (pref |> '0') ('0' <| suf)\n ('?','?') | b>1 -> calc2 xs a (b-2) (pref |> '1') ('1' <| suf)\n (_,_) -> calc2 xs a b (pref |> x1) (xn <| suf)\n\ncalc :: String -> Int -> Int -> String\ncalc line a b =\n let sq = fromList line\n (a',b',sq') = calc1 sq a b empty empty\n in\n toList $ calc2 sq' a' b' empty empty\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b] = map read $ words line :: [Int]\n line <- getLine\n --print (a,b,line)\n --print $ calc1 (fromList line) a b empty empty\n putStrLn $ calc line a b\n", "positive_code": [{"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\nresult :: Int -> Int -> String -> String\r\nresult a b str' \r\n\t| not isP = \"-1\"\r\n\t| a + b /= n = \"-1\"\r\n\t| mod a 2 == 1 && mod b 2 == 1 = \"-1\"\r\n\t| S.size val /= div (a-num0) 2 = \"-1\"\r\n\t| sum [1|s<-solution, s=='0'] /= a = \"-1\" \r\n\t| otherwise = solution\r\n\twhere\r\n\t\tn = length str'\r\n\t\tnum0 = sum [1 | s <- str, s=='0']\r\n\t\ttwo_ = [i | (i, s) <- zip [0..(div n 2 - 1)] str, s == '?', strM ! (n-1-i) == '?']\r\n\t\tisP = foldr (\\i b-> (&&) b $ strM ! i == strM ! (n-1-i)) True $ [0..(div n 2 - 1)]\r\n\r\n\t\tstrM' = M.fromList $ zip [0..] str'\r\n\t\tstrM = M.fromList $ zip [0..] str\r\n\t\tstr = fmap aux [0..(n-1)] where\r\n\t\t\taux i \r\n\t\t\t\t| strM' ! i /= '?' = strM' ! i\r\n\t\t\t\t| strM' ! (n-1-i) /= '?' = strM' ! (n-1-i)\r\n\t\t\t\t| mod n 2 == 1 && i == div n 2 = if mod a 2 == 0 then '1' else '0'\r\n\t\t\t\t| otherwise = '?'\r\n\r\n\t\tval = S.fromList $ take (div (a-num0) 2) two_\r\n\t\taux0 (i, s)\r\n\t\t\t| s /= '?' = s\r\n\t\t\t| s == '?' && (S.member i val || S.member (n-1-i) val) = '0'\r\n\t\t\t| otherwise = '1'\r\n\r\n\t\tsolution = fmap aux0 $ zip [0..] str\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\r\n\tlet loop t = if t==0 then return () else do \r\n\t\tl <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n\t\tlet (a, b) = (l !! 0, l !! 1)\r\n\r\n\t\tstr <- getLine\r\n\r\n\t\tputStrLn $ result a b str \r\n\t\t\r\n\r\n\t\tloop $ t - 1\r\n\r\n\tloop t\r\n\r\n"}], "negative_code": [{"source_code": "import qualified Data.Map as M\r\nimport Data.Map((!))\r\n\r\nimport qualified Data.Set as S\r\nimport qualified Data.List as L\r\n\r\nresult :: Int -> Int -> String -> String\r\nresult a b str' \r\n\t| not isP = \"-1\"\r\n\t| a + b /= n = \"-1\"\r\n\t| mod a 2 == 1 && mod b 2 == 1 = \"-1\"\r\n\t| length val /= div (a-num0) 2 = \"-1\"\r\n\t| otherwise = fmap aux0 $ zip [0..] str\r\n\twhere\r\n\t\tn = length str'\r\n\t\tnum0 = sum [1 | s <- str, s=='0']\r\n\t\ttwo_ = [i | (i, s) <- zip [0..(div n 2 - 1)] str, s == '?', str !! (n-1-i) == '?']\r\n\t\tisP = foldr (\\i b-> (&&) b $ str !! i == str !! (n-1-i)) True $ [0..(div n 2 - 1)]\r\n\r\n\t\tstr = fmap aux [0..(n-1)] where\r\n\t\t\taux i \r\n\t\t\t\t| str' !! i /= '?' = str' !! i\r\n\t\t\t\t| str' !! (n-1-i) /= '?' = str' !! (n-1-i)\r\n\t\t\t\t| mod n 2 == 1 && i == div n 2 = if mod a 2 == 0 then '1' else '0'\r\n\t\t\t\t| otherwise = '?'\r\n\r\n\t\tval = take (div (a-num0) 2) two_\r\n\t\taux0 (i, s)\r\n\t\t\t| s /= '?' = s\r\n\t\t\t| s == '?' && (elem i val || elem (n-1-i) val) = '0'\r\n\t\t\t| otherwise = '1'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\r\n\tlet loop t = if t==0 then return () else do \r\n\t\tl <- getLine >>= return . (fmap read) . words :: IO [Int]\r\n\t\tlet (a, b) = (l !! 0, l !! 1)\r\n\r\n\t\tstr <- getLine\r\n\r\n\t\tputStrLn $ result a b str \r\n\t\t\r\n\r\n\t\tloop $ t - 1\r\n\r\n\tloop t\r\n\r\n"}, {"source_code": "import Control.Monad\nimport Data.List (words)\nimport Data.Sequence (Seq,Seq (Empty, (:<|), (:|>)), fromList, (><), (<|), (|>), empty)\nimport Data.Foldable (toList)\n\n\n-- ex:\n-- 4 4\n-- 01?????0\n\ntype SChar = Seq Char\n\ncalc1 :: SChar -> Int -> Int -> SChar -> SChar -> (Int,Int,SChar)\ncalc1 Empty a b pref suf = (a,b, pref >< suf)\ncalc1 ('1' :<| Empty) a b pref suf = (a,b-1, pref >< ('1' <| suf))\ncalc1 ('0' :<| Empty) a b pref suf = (a-1,b, pref >< ('0' <| suf))\ncalc1 (x :<| Empty) a b pref suf = (a,b, pref >< (x <| suf))\ncalc1 s a b pref suf =\n let (x1 :<| xs1) = s\n (xs :|> xn) = xs1\n in\n case (x1,xn) of\n ('?','1') -> calc1 xs a (b-2) (pref |> '1') (xn <| suf)\n ('1','?') -> calc1 xs a (b-2) (pref |> x1) ('1' <| suf)\n ('?','0') -> calc1 xs (a-2) b (pref |> '0') (xn <| suf)\n ('0','?') -> calc1 xs (a-2) b (pref |> x1) ('0' <| suf)\n ('0','0') -> calc1 xs (a-2) b (pref |> x1) (xn <| suf)\n ('1','1') -> calc1 xs a (b-2) (pref |> x1) (xn <| suf)\n (_,_) -> calc1 xs a b (pref |> x1) (xn <| suf)\n\ncalc2 :: SChar -> Int -> Int -> SChar -> SChar -> SChar\ncalc2 Empty a b _ _ | a /= 0 || b /= 0 = fromList \"-1\"\ncalc2 Empty 0 0 pref suf = pref >< suf\ncalc2 ('?':<|Empty) a b pref suf\n | a == 1 && b == 0 = pref >< ('0' <| suf)\n | a == 0 && b == 1 = pref >< ('1' <| suf)\n | otherwise = fromList \"-1\"\ncalc2 ('1' :<| Empty) a b pref suf = calc2 empty a b pref ('1' <| suf)\ncalc2 ('0' :<| Empty) a b pref suf = calc2 empty a b pref ('0' <| suf)\ncalc2 (x :<| Empty) _ _ _ _ = fromList \"-1\"\n\ncalc2 s a b pref suf | a<0 && b<0 = fromList \"-1\"\ncalc2 s a b pref suf =\n let (x1 :<| xs1) = s\n (xs :|> xn) = xs1\n in\n case (x1,xn) of\n ('?','?') | a>0 -> calc2 xs (a-2) b (pref |> '0') ('0' <| suf)\n ('?','?') | b>0 -> calc2 xs a (b-2) (pref |> '1') ('1' <| suf)\n (_,_) -> calc2 xs a b (pref |> x1) (xn <| suf)\n\ncalc :: String -> Int -> Int -> String\ncalc line a b =\n let sq = fromList line\n (a',b',sq') = calc1 sq a b empty empty\n in\n toList $ calc2 sq' a' b' empty empty\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [a,b] = map read $ words line :: [Int]\n line <- getLine\n --print (a,b,line)\n --print $ calc1 (fromList line) a b empty empty\n putStrLn $ calc line a b\n"}], "src_uid": "001ac8bce4e44e9266a13eb27760906c"} {"source_code": "import Data.Sequence( empty, viewl, spanl, (<|), fromList, null,\n\t\t\tViewL( EmptyL, (:<)), (><), (|>))\nimport qualified Data.Sequence as SEQ\nmain = do\n getLine\n statements_ <- getLine\n let tailSeq seq = case viewl seq of\n\t\t\tEmptyL\t\t-> empty\n\t\t\t(_: rem\n\tdrop1stn _ 0 sequence = sequence\n\tdrop1stn e n sequence =\n\t case viewl sequence of\n\t\tEmptyL\t -> empty\n\t\ts: if e==s\n\t\t\t\tthen drop1stn e (n-1) stRem\n\t\t\t\telse s<|drop1stn e n stRem\n\toppo 'R' = 'D'\n\toppo 'D' = 'R'\n\tproc sequence =\n\t let\n\t\ts:<\n\t\t\t\t(s <| friends)\n\t in\n\t\tif SEQ.null enemyHeaded\n\t\t then [s]\n\t\t else proc nextSeq\n putStr . proc $ fromList statements_\n", "positive_code": [{"source_code": "import Data.Sequence( empty, viewl, spanl, (<|), fromList, null,\n\t\t\tViewL( EmptyL, (:<)), (><), (|>))\nimport qualified Data.Sequence as SEQ\nmain = do\n getLine\n statements_ <- getLine\n let tailSeq seq = case viewl seq of\n\t\t\tEmptyL\t\t-> empty\n\t\t\t(_: rem\n\tdrop1stn _ _ EmptyL = empty\n\tdrop1stn _ 0 (s:<\n\t\t\t\t(s <| friends)\n\t in\n\t\tif SEQ.null enemyHeaded\n\t\t then [s]\n\t\t else proc $ viewl nextSeq\n putStr . proc . viewl $ fromList statements_\n"}, {"source_code": "simulate = walk \"\" 0\n where walk past future []\n | all (== head past) past = [head past]\n | otherwise = walk \"\" future $ reverse past\n walk past future ('D' : s)\n | future < 0 = walk past (future+1) s\n | otherwise = walk ('D' : past) (future+1) s\n walk past future ('R' : s)\n | future > 0 = walk past (future-1) s\n | otherwise = walk ('R' : past) (future-1) s\n\nmain = do\n s <- getContents\n let voters = lines s !! 1\n putStrLn $ simulate voters\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Sequence as S\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n s <- zip [0..] `fmap` getLine\n let (d, r) = partition (\\(_,c) -> c == 'D') s\n let d' = S.fromList $ map fst d\n let r' = S.fromList $ map fst r\n let (d'', r'') = fight n d' r'\n if S.length d'' == 0\n then putStrLn \"R\"\n else putStrLn \"D\"\n\ntype Queue = S.Seq Int\n\nfight :: Int -> Queue -> Queue -> (Queue, Queue)\nfight n d r\n | S.length d == 0 = (d, r)\n | S.length r == 0 = (d, r)\n | head' d < head' r = fight n (tail' d S.|> (head' d + n)) (tail' r)\n | otherwise = fight n (tail' d) (tail' r S.|> (head' r + n))\n\nhead' q = S.index q 0\ntail' q = S.drop 1 q\nlast' q = S.index q (S.length q - 1)\n"}], "negative_code": [{"source_code": "solve = walk 0 0 0\n where walk k m s [] | s > 0 || s == 0 && k > 0 = \"D\"\n | s < 0 || s == 0 && m > 0 = \"R\"\n | otherwise = show (k, m, s)\n walk k 0 s ('D' : rest) = walk (k+1) 0 (s+1) rest\n walk k m s ('D' : rest) = walk k (m-1) s rest\n walk 0 k s ('R' : rest) = walk 0 (k+1) (s-1) rest\n walk k m s ('R' : rest) = walk (k-1) m s rest\n\nmain = do\n s <- getContents\n let voters = lines s !! 1\n putStrLn $ solve voters\n"}, {"source_code": "solve voters@(first : _) = walk 0 0 0 voters\n where walk k m s [] | k - m + s > 0 = \"D\"\n | k - m + s < 0 = \"R\"\n | otherwise = [first]\n walk k 0 s ('D' : rest) = walk (k+1) 0 (s+1) rest\n walk k m s ('D' : rest) = walk k (m-1) s rest\n walk 0 k s ('R' : rest) = walk 0 (k+1) (s-1) rest\n walk k m s ('R' : rest) = walk (k-1) m s rest\n\nmain = do\n s <- getContents\n let voters = lines s !! 1\n putStrLn $ solve voters\n"}, {"source_code": "solve voters@(first : _) = walk 0 0 0 voters\n where walk k m s [] | s > 0 || s == 0 && k > 0 = \"D\"\n | s < 0 || s == 0 && m > 0 = \"R\"\n | otherwise = [first]\n walk k 0 s ('D' : rest) = walk (k+1) 0 (s+1) rest\n walk k m s ('D' : rest) = walk k (m-1) s rest\n walk 0 k s ('R' : rest) = walk 0 (k+1) (s-1) rest\n walk k m s ('R' : rest) = walk (k-1) m s rest\n\nmain = do\n s <- getContents\n let voters = lines s !! 1\n putStrLn $ solve voters\n"}], "src_uid": "cc50eef15726d429cfc2e76f0aa8cd19"} {"source_code": "main = do\n aux <- getLine\n let n = read aux :: Int\n let xs = [x | x <- [4,5..(n-4)], complex x, complex (n - x)]\n putStrLn (show (head xs) ++ \" \" ++ show (n - (head xs)))\n\n\nprime k = null [x | x <- [2..(k - 1)], mod k x == 0]\n\ncomplex k = if (prime k) then (False) else (True)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\ngetInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\n\tlet\n\t\tm = which 6 9 $ even n \n\t\n\tprintf \"%d %d\\n\" m ( n - m )\n"}, {"source_code": "import Control.Monad\n\n\nimport Data.Array.Unboxed\n \n\nprimes = primesToNA (2 * 10^6)\nprimesToNA n = 2: [i | i <- [3,5..n], ar ! i]\n where\n ar = f 5 $ accumArray (\\ a b -> False) True (3,n) \n [(i,()) | i <- [9,15..n]]\n f p a | q > n = a\n | True = if null x then a2 else f (head x) a2\n where q = p*p\n a2 :: UArray Int Bool\n a2 = a // [(i,False) | i <- [q, q+2*p..n]]\n x = [i | i <- [p+2,p+4..n], a2 ! i]\n\n\nisPrime n = n `elem` primes\n\n\nmain = do\n n <- readLn\n\n\n\n putStrLn $ unwords $ map show $ head [ [i,j] | i <- [2..n-2], let j = n - i, not (isPrime i), not (isPrime j)]\n"}, {"source_code": "main = do\n input <- getLine\n let n = read input\n if odd n then\n putStrLn $ (\"9 \" ++ (show $ n - 9))\n else\n putStrLn $ (\"4 \" ++ (show $ n - 4))"}, {"source_code": "\n-- https://wiki.haskell.org/Converting_numbers\n--\n-- figure out how to convert fractional types to\n-- integers and vice-versa\n\n\n\niscomp y e\n | y == e = False\n | (mod y e) == 0 = True\n | otherwise = iscomp y (e+1)\n\n\nfindsum a b\n | iscomp b 2 && iscomp (a-b) 2 = b\n | otherwise = findsum a (b+1)\n\n\nmain = do\n gg <- getLine\n let ss = (read gg)::Int\n hh = findsum ss 2\n\n putStr (show hh)\n putStr \" \"\n putStr (show (ss-hh))\n putStr \"\\n\"\n\n\n\n \n"}, {"source_code": "main = do\n n <- readLn\n let answer = if even n then [4, n - 4] else [9, n - 9]\n putStrLn $ unwords $ map show answer\n"}, {"source_code": "main = do\n n <- readLn\n \n let\n primes = takeWhile (<= n) $ [2, 3] ++ (filter (\\x -> and [x `mod` p /= 0 | p <- takeWhile (\\p -> p*p <= x) primes]) [4..])\n \n (a, b) = head [(a, b) | a <- [2..n-2], let b = n-a, notElem a primes, notElem b primes]\n \n putStrLn $ show a ++ \" \" ++ show b"}, {"source_code": "solve n\n | even n = [4,n-4]\n | otherwise = [9,n-9]\nmain = interact $ unwords . map show . solve . read\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nprimeArray :: Int -> UArray Int Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nmain = do\n n <- readLn\n let a = primeArray n\n let (x,y) = head [ (x,y) | x <- [2..n-1], let y = n-x, not (a ! x) && not (a ! y) ]\n printf \"%d %d\\n\" x y\n"}, {"source_code": "import System.IO\n\nmain :: IO ()\nmain = getLine >>= putStrLn . (\\(a,b) -> show a ++ \" \" ++ show b) . breakIntoComposite . read\n\nbreakIntoComposite :: Integer -> (Integer, Integer)\nbreakIntoComposite n = (first, n - first)\n where first = 4 + 5 * (n `mod` 2)"}, {"source_code": "isPrime num = [x | x <- [1..num], num `mod` x == 0] == [1,num]\ndecompose x = [n:d:[] | n <- [2..x-2], let d = (x - n)]\nsumNotPrimes n = concat $ take 1 [x:y:[] | [x,y] <- decompose n, isPrime x == False && isPrime y == False]\nmain = do \n\tstr <- getLine\n\t(\\[a,b] -> putStrLn ((show a) ++ \" \" ++ (show b))) $ sumNotPrimes (read str)"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. read. head . lines\nsolve :: Int->String\nsolve x=if x `mod` 2 ==0 then \"4\" ++\" \"++ show (x-4) else let (y1,y2)=head [(a,b) |b<-[4,6..], let a = x-b, a `mod` 3 == 0] in show y1 ++ \" \" ++ show y2"}, {"source_code": "main = interact $ p . read\np a = if mod a 2 == 1 then \"9 \"++show (a-9) else \"4 \"++show (a-4)"}, {"source_code": "main = interact $ p . read\np a = if odd a then \"9 \"++show (a-9) else \"4 \"++show (a-4)"}, {"source_code": "getInt :: IO Int\ngetInt = readLn\n\nisPrime :: Int -> Int -> Bool\nisPrime a i | i > a `quot` 2 = True\n | a `mod` i == 0 = False\n | otherwise = isPrime a (i + 1)\n\ndivsum :: Int -> Int -> Int -> (Int, Int)\ndivsum a i j | i == 0 || j == a = (-1, -1)\n | (not (isPrime i 2)) && (not (isPrime j 2)) && (a == i + j) = (i, j)\n | otherwise = divsum a (i - 1) (j + 1)\n \nout a = show (fst a) ++ \" \" ++ show (snd a) \nsolve a = putStrLn $ out (divsum a (a - 1) 1)\nmain = getInt >>= solve"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nisprime x =all (/=0) [mod x i |i<-[2..(div x 2) ]]\n\nmain=do\n n<- read <$> getLine ::IO Int\n putStrLn $ intercalate \" \" $ map show $ head $ [ [i,j]|i<-[4..], not (isprime i), let j= n-i, not(isprime j)]\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= putStrLn . unwords . map show . solve\n\nsolve :: Int -> [Int]\nsolve n | even n = [ 4, n - 4 ]\n | otherwise = [ 9, n - 9 ]\n"}, {"source_code": "import Prelude hiding (readList, showList)\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nreadInt :: IO Int\nreadInt = head <$> readList' (undefined::Int)\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\nu :: a\nu = undefined\n\nisComp :: Int -> Bool\nisComp x = any ((==0) . mod x) [2..x-1]\n\nisOk :: Int -> Int -> Bool\nisOk x y = isComp x && isComp y\n \nmain :: IO ()\nmain = do\n n <- readInt\n let x= head $ filter (\\x -> isOk x (n-x)) [2..n-1]\n showList [x,n-x]\n"}, {"source_code": "main = do\n input <- getLine\n let n = read input\n if odd n then putStrLn $ (\"9 \" ++ (show $ n-9))\n else putStrLn $ (\"4 \" ++ (show $ n-4))\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/472/A\n\nsolve :: Int -> String\nsolve n = if odd n then \"9 \" ++ show (n - 9) else \"4 \" ++ show (n - 4)\n\nmain :: IO ()\nmain = interact $ solve . read\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = readLn >>= putStrLn.unwords.map show.solve\n\nsieveLimit :: Int\nsieveLimit = sieveWidth\n\nsieveWidth :: Int\nsieveWidth = 0xfffff\n\nintSqrt :: Int -> Int\nintSqrt x = floor . sqrt $ fromIntegral x\n\nsolve :: Int -> [Int]\nsolve n = head [[x,n-x]|x<-[2..], not(isPrime x), not (isPrime (n-x))]\n where\n isPrime 2 = True\n isPrime n | even n || n < 2= False\n isPrime n = unsafeAt isPrimeArray (n `quot` 2)\n !lim = (sieveLimit + sieveWidth - 1) `quot` sieveWidth * sieveWidth\n !isPrimeArray = runSTUArray $ do\n isp <- newArray (0, lim `quot` 2) True :: ST s (STUArray s Int Bool)\n unsafeWrite isp 0 False\n forM_ [0, sieveWidth .. lim - sieveWidth] $ \\l -> do\n let !l2 = l `quot` 2\n !r = l + sieveWidth\n !r2 = r `quot` 2\n forM_ [1 .. intSqrt r `quot` 2] $ \\i-> do\n flg <- unsafeRead isp i\n when flg $ do\n let !p = 2 * i + 1\n go !j = when (j < r2) $ do\n unsafeWrite isp j False\n go $ j + p\n go $ ((l2 - 2 * i * i) `quot` p + i) * p + i\n return isp"}, {"source_code": "import Text.Printf\n\nmain = do\n n <- readLn\n if n `mod` 2 == 0 \n then printf \"%d %d\\n\" (8::Int) ((n - 8)::Int)\n else printf \"%d %d\\n\" (9::Int) ((n - 9)::Int)\n"}, {"source_code": "main = do\n n <- getLine >>= return . read\n let x = if even n then 4 else 9\n let y = n - x\n putStrLn $ unwords . map show $ [x, y]"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.Array as Arr\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.Function\n\nmain = do\n [n] <- getInts\n let\n solution\n | odd n = [9, n-9]\n | otherwise = [4, n-4]\n putStrLn $ unwords $ map show solution\n\n\n-- helper functions --\n\nreadInt = fst . fromJust . B.readInt\ngetInts = map readInt . B.words <$> B.getLine\n\nmemoArr :: Ix i => (i, i) -> (i -> r) -> (i -> r)\nmemoArr range f = f' where\n f' i\n | Arr.inRange range i = arr ! i\n | otherwise = f i\n arr = Arr.listArray range (map f (Arr.range range))\n\ndpArr :: Ix i => (i, i) -> ((i -> r) -> (i -> r)) -> (i -> r)\ndpArr ixs f = fix (memoArr ixs . f)\n"}, {"source_code": "isPrime :: Int -> Bool\nisPrime 1 = False\nisPrime n = null [x | x <- takeWhile (\\m -> m*m <= n) [2..], n `mod` x == 0]\n\ngetComposite :: Int -> (Int, Int)\ngetComposite x = head [(m, x-m) | m <- [4..], not $ isPrime m, not $ isPrime (x-m)]\n\nmain = do\n n <- getLine\n let (a, b) = getComposite (read n)\n putStrLn ((show a) ++ \" \" ++ (show b))\n"}, {"source_code": "import Control.Applicative\n\nprocess a | even a = putStrLn ( \"4 \" ++ show (a-4))\n\t | a==13 = putStrLn ( \"4 9\")\n\t | a==15 = putStrLn ( \"6 9\")\n\t | a==17 = putStrLn (\"8 9\") \n | mod a 5 == 1 = putStrLn ( \"6 \" ++ show (a-6))\n\t | mod a 5 == 2 = putStrLn ( \"12 \" ++ show (a-12))\n | mod a 5 == 3 = putStrLn ( \"8 \" ++ show (a-8))\n | mod a 5 == 4 = putStrLn ( \"4 \" ++ show (a-4))\n | mod a 5 == 0 = putStrLn ( \"10 \" ++ show (a-10))\n\n \nmain= do\n\ta<- read <$> getLine::IO Int\n\tprocess a\n\n\n\n\t \n\t \n"}, {"source_code": "main = do\n n <- readLn :: IO Int\n putStr.show $ if odd n then 9 else 4 \n putStrLn $ \" \" ++ show (if odd n then n - 9 else n - 4)\n"}, {"source_code": "main = interact $ unwords . map show . solve . read\nsolve n = if even n then [4, n - 4] else [9, n - 9]\n"}, {"source_code": "process :: Int -> (Int,Int)\nprocess n = (x,n-x)\n where\n x = [6,4,8] !! (n `mod` 3)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n let (a,b) = process n\n putStrLn (show a ++ \" \" ++ show b)"}, {"source_code": "main = interact $ (\\x -> if even x then \"4 \"++show (x-4) else \"9 \"++show (x-9)) . read"}, {"source_code": "decomp :: Int -> [Int]\ndecomp n\n | even n = [4, n - 4]\n | otherwise = [9, n - 9]\n\nsolve :: String -> String\nsolve = unwords.fmap show.decomp.read \n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "isComp n = 0 `elem` (map (\\x -> n `rem` x) [2.. (n `quot` 2)])\nf n = head [(a,b) | a <- [3..(n `quot` 2)], let b = n - a,\n isComp a, isComp b]\nmain = do\n k <-getLine\n let n = read k :: Int\n ans = f n\n putStrLn $ (show $ fst ans)++\" \"++(show $ snd ans)\n \n"}, {"source_code": "f::Int -> [Int]\nf x | even x = [4,x-4]\n | 1>0 = [9,x-9]\nmain = interact $ unwords.map show.f.read\n"}], "negative_code": [{"source_code": "main = do\n n <- readLn\n \n let\n primes = takeWhile (<= n) $ [2, 3] ++ (filter (\\x -> and [x `mod` p /= 0 | p <- takeWhile (\\p -> p*p <= x) primes]) [4..])\n \n (a, b) = head [(a, b) | a <- [2..n-2], let b = n-a, notElem a primes, notElem b primes]\n \n print $ show a ++ \" \" ++ show b"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nprimeArray :: Int -> UArray Int Bool\nprimeArray n = runSTUArray $ do\n arr <- newArray (0,n) True\n writeArray arr 0 False\n writeArray arr 1 False\n forM_ (2:[3,5..n]) $ \\i -> do\n b <- readArray arr i\n when b $ forM_ [2*i,3*i..n] $ \\j -> writeArray arr j False\n return arr\n\nmain = do\n n <- readLn\n let a = primeArray n\n let (x,y) = head [ (x,y) | x <- [1..n], let y = n-x, not (a ! x) && not (a ! y) ]\n printf \"%d %d\\n\" x y\n"}, {"source_code": "getInt :: IO Int\ngetInt = readLn\n\nisPrime :: Int -> Int -> Bool\nisPrime a i | i > a `quot` 2 = True\n | a `mod` i == 0 = False\n | otherwise = isPrime a (i + 1)\n\ndivsum :: Int -> Int -> Int -> (Int, Int)\ndivsum a i j | i == 0 || j == a = (-1, -1)\n | (not (isPrime i 2)) && (not (isPrime j 2)) && (a == i + j) = (i, j)\n | otherwise = divsum a (i - 1) (j + 1)\n \nsolve a = putStrLn $ show (divsum a (a - 1) 1)\nmain = getInt >>= solve"}, {"source_code": "main :: IO ()\nmain = readLn >>= putStrLn . unwords . map show . solve\n\nsolve :: Int -> [Int]\nsolve n | even n = [ 2, n - 2 ]\n | otherwise = [ 9, n - 9 ]\n"}, {"source_code": "import Control.Applicative\n \nmain= do\n\ta<- read <$> getLine::IO Int\n\tif even a then putStrLn ( \"4 \" ++ show (a-4)) else if mod a 5 ==3 then putStrLn ( \"8 \" ++ show (a-8)) else putStrLn ( \"6 \" ++ show (a-6))\n\t \n\n\t \n"}, {"source_code": "decomp :: Int -> [Int]\ndecomp n\n | even n = [2, n - 2]\n | otherwise = [9, n - 9]\n\nsolve :: String -> String\nsolve = unwords.fmap show.decomp.read \n\nmain :: IO ()\nmain = interact $ solve"}], "src_uid": "3ea971165088fae130d866180c6c868b"} {"source_code": "import Data.Array\nimport List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[n] <- getA\n\tx <- getA\n\tputStr $ let r = gao n x in unlines [show (length r), unwords (map show r)]\n\ngao n x = if null e then [] else head e where\n\ta = listArray (1, n) x\n\tb = map head $ groupBy (\\i j -> a!i == a!j) [1 .. n]\n\tc = length b\n\td = listArray (1, c) b\n\te = filter (\\[i, j, k] -> (a!i < a!j) /= (a!j < a!k)) [[d!(i-1), d!i, d!(i+1)] | i <- [2 .. c - 1]]\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n let readInt = fst . fromJust . BS.readInt\n n <- readInt <$> BS.getLine\n xs <- map readInt . BS.words <$> BS.getLine\n let diff = dropWhile ((== 0) . snd) . zip ([1 ..] :: [Int])\n $ zipWith (-) xs (tail xs)\n found idx1 (idx2, _) = printf \"3\\n%d %d %d\\n\" idx1 idx2 (idx2 + 1)\n notFound = print 0\n case diff of\n (idx1, d1) : _ | d1 < 0 -> maybe notFound (found idx1)\n $ find ((> 0) . snd) diff\n | d1 > 0 -> maybe notFound (found idx1)\n $ find ((< 0) . snd) diff\n _ -> notFound\n"}, {"source_code": "import List\nimport Control.Arrow\n\nbend :: [(Int, Int)] -> Maybe (Int, Int, Int)\nbend ((ia, a):next@((ib, b):(ic, c):_)) = \n case (compare a b, compare b c) of\n (LT, GT) -> Just (ia, ib, ic)\n (GT, LT) -> Just (ia, ib, ic)\n _ -> bend next\nbend _ = Nothing\n\nsolve xs = \n case bend (deduplicated xs) of\n Just (a, b, c) -> \"3\\n\" ++ (concat $ intersperse \" \" (map show [a, b, c]))\n Nothing -> \"0\\n\"\n where\n deduplicated = map read . words . (!! 1) . lines >>>\n tail . scanl (\\ (i, _) n -> (i + 1, n)) (0, 0) >>>\n map head . groupBy (\\ (_, a) (_, b) -> a == b)\n \nmain = interact solve\n"}, {"source_code": "import List\nimport Control.Arrow\n\nbend :: [(Int, Int)] -> Maybe (Int, Int, Int)\nbend ((ia, a):next@((ib, b):(ic, c):_)) = \n case (compare a b, compare b c) of\n (LT, GT) -> Just (ia, ib, ic)\n (GT, LT) -> Just (ia, ib, ic)\n _ -> bend next\nbend _ = Nothing\n\nsolve xs = \n case bend (deduplicated xs) of\n Just (a, b, c) -> \"3\\n\" ++ (concat $ intersperse \" \" (map show [a, b, c]))\n Nothing -> \"0\\n\"\n where\n deduplicated = map read . words . (!! 1) . lines >>>\n zip [1..] >>> \n map head . groupBy (\\ (_, a) (_, b) -> a == b)\n \nmain = interact solve\n"}, {"source_code": "import Data.List(groupBy, find)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Maybe(fromJust)\nmain = do \n getLine\n b <- fmap (map readInt . BS.words) BS.getLine\n let a :: [(Int,Int)]\n a = map head . groupBy (\\x y -> snd x == snd y) . zip [1..] $ b\n n = length a\n triples = zip3 a (tail a) (tail $ tail a)\n good ((_,a),(_,b),(_,c)) = a>b && bc\n ans = case find good triples of\n Nothing -> []\n Just ((a,_),(b,_),(c,_)) -> [a,b,c]\n if n < 3 || null ans\n then putStrLn \"0\"\n else do putStrLn \"3\"\n putStrLn . unwords . map show $ ans\n \nreadInt = fst . fromJust . BS.readInt\n"}], "negative_code": [{"source_code": "import Data.Array\nimport List\n\ngetA = fmap (map read . words) getLine\n\nmain = do\n\t[n] <- getA\n\tx <- getA\n\tputStr $ let r = gao n x in unlines [show (length r), unwords (map show r)]\n\ngao n x = if null e then [] else head e where\n\ta = listArray (1, n) x\n\tb = map head $ groupBy (\\i j -> a!i == a!j) [1 .. n]\n\tc = length b\n\td = listArray (1, c) b\n\te = filter (\\[i, j, k] -> (a!i < a!j) /= (a!j < a!k)) [[d!i-1, d!i, d!i+1] | i <- [2 .. c - 1]]\n"}, {"source_code": "import List\n\nbend :: Int -> [Int] -> Maybe (Int, Int, Int)\nbend i (a:next@(b:c:_)) = \n case (compare a b, compare b c) of\n (LT, GT) -> Just (i, i + 1, i + 2)\n (GT, LT) -> Just (i, i + 1, i + 2)\n _ -> bend (i + 1) next\nbend _ _ = Nothing\n\nsolve xs = \n case (bend 1) $ (map read) $ words $ (!! 1) $ lines $ xs of\n Just (a, b, c) -> \"3\\n\" ++ (concat $ intersperse \" \" (map show [a, b, c]))\n Nothing -> \"0\\n\"\n \nmain = interact solve\n"}, {"source_code": "import List\nimport Control.Arrow\n\nbend :: [(Int, Int)] -> Maybe (Int, Int, Int)\nbend ((ia, a):next@((ib, b):(ic, c):_)) = \n case (compare a b, compare b c) of\n (LT, GT) -> Just (ia, ib, ic)\n (GT, LT) -> Just (ia, ib, ic)\n _ -> bend next\nbend _ = Nothing\n\nsolve xs = \n case bend (deduplicated xs) of\n Just (a, b, c) -> \"3\\n\" ++ (concat $ intersperse \" \" (map show [a, b, c]))\n Nothing -> \"0\\n\"\n where\n deduplicated = map read . words . (!! 1) . lines >>>\n (\\xs -> [ (ia, a) | ia <- [1..], a <- xs ]) >>> \n map head . groupBy (\\ (_, a) (_, b) -> a == b)\n \nmain = interact solve\n"}], "src_uid": "652c7852f1d0bab64ffd2219af4f59da"} {"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n strs <- replicateM n getLine\n let seconds = Set.fromList $ concatMap tail strs\n firsts = Set.toList $ Set.difference (Set.fromList $ map head strs) seconds\n conts = Map.fromList $ concatMap (\\xs -> zip xs $ tail xs) strs\n start [] _ = []\n start (f:fs) cs = continue f fs cs\n continue cur fs cs = cur: case Map.lookup cur cs of\n Just next -> continue next fs cs\n Nothing -> start fs cs\n putStrLn $ start firsts conts\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport Prelude hiding (lookup)\nimport Control.Applicative ((<$>))\nimport Control.Monad (replicateM)\nimport Data.Map (fromList, elems, lookup)\nimport Data.Set (difference)\nimport qualified Data.Set as S\n\nsolve :: [String] -> String\nsolve xs = S.foldr go \"\" root\n where\n next = fromList . concat . zipWith zip xs $ map tail xs\n -- all the observed values which are not preceded by any letter\n root = S.fromList (concat xs) `difference` S.fromList (elems next)\n\n go i acc = case i `lookup` next of\n Just j -> i: go j acc\n Nothing -> i: acc\n\nmain = do\n n <- read <$> getLine\n a <- replicateM n getLine\n putStrLn $ solve a\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\n\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n strs <- replicateM n getLine\n let prereq = Map.unionsWith Set.union $ map req strs\n req = Map.fromList . snd . mapAccumL prev Set.empty\n prev prevs x = (Set.insert x prevs, (x, prevs))\n go prer | Map.null prer = []\n | otherwise =\n let (first, _) = Map.findMin $ Map.filter Set.null prer\n prer' = Map.map (Set.delete first) $ Map.delete first prer\n in first : go prer'\n putStrLn $ go prereq\n"}], "src_uid": "a6e112135272a81ae9563ae4c50b6d86"} {"source_code": "#!/usr/bin/env stack\n-- stack --resolver nightly-2020-08-16 script\n\nimport Control.Monad\n\nsolve :: IO ()\nsolve = do\n getLine\n as <- map read . words <$> getLine\n bs <- map read . words <$> getLine\n let moves = zip (subtract (minimum as) <$> as) (subtract (minimum bs) <$> bs)\n print $ sum $ (\\(a, b) -> a + b - min a b) <$> moves\n\nmain :: IO ()\nmain = do\n getLine >>= flip replicateM_ solve . read\n ", "positive_code": [{"source_code": "#!/usr/bin/env stack\n-- stack --resolver nightly-2020-08-16 script\n\nimport Data.List\nimport Control.Monad\n\n\n\nreadInt :: String -> Int\nreadInt s = read s :: Int\n\ngetInt :: IO Int\ngetInt = readInt <$> getLine\n\nreadLineInts :: String -> [Int]\nreadLineInts s = map readInt $ words s\n\ngetInts :: IO [Int]\ngetInts = readLineInts <$> getLine\n\n\nmain :: IO ()\nmain = do\n testCount <- getInt\n replicateM_ testCount test\n\ntest :: IO ()\ntest = do\n getInt\n as <- map read . words <$> getLine\n bs <- map read . words <$> getLine\n let minA = minimum as\n let minB = minimum bs\n let actCount = sum $ map (pToAct minA minB) $ zip as bs\n print actCount\n\npToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a\npToAct minA minB (a, b) = max (a - minA) (b - minB)\n\n\n\n"}, {"source_code": "import Control.Monad\n\nsolve :: IO ()\nsolve = do\n getLine\n as <- map read . words <$> getLine\n bs <- map read . words <$> getLine\n let moves = zip (subtract (minimum as) <$> as) (subtract (minimum bs) <$> bs)\n print $ sum $ (\\(a, b) -> a + b - min a b) <$> moves\n\nmain :: IO ()\nmain = do\n getLine >>= flip replicateM_ solve . read\n "}, {"source_code": "convert :: Read a => String -> [a]\nconvert = map read . words\n\nsolve :: Int -> IO ()\nsolve 0 = putStrLn \"\"\nsolve t = do\n line <- getLine\n line <- getLine\n let a = convert line :: [Integer]\n let la = foldl min (head a) a\n line <- getLine\n let b = convert line :: [Integer]\n let lb = foldl min (head b) b\n let c = map (\\(x, y) -> max (x - la) (y - lb)) (zip a b)\n print $ sum c\n solve $ t - 1\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [t] = convert line :: [Int]\n solve t\n "}, {"source_code": "import Control.Monad\nimport Data.Int\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n print (solve a b)\n\nsolve :: [Int64] -> [Int64] -> Int64\nsolve a b = sum $ zipWith (\\x y -> max (x - a_min) (y - b_min)) a b\n where\n a_min = minimum a\n b_min = minimum b\n"}, {"source_code": "module Main where\n \n solve :: IO ()\n solve = do\n _ <- getLine\n sa <- getLine\n sb <- getLine\n let a = map (\\x -> read x :: Integer) $ words sa\n b = map (\\x -> read x :: Integer) $ words sb\n ma = minimum a\n mb = minimum b\n n = length a\n print $ sum [max (a !! i - ma) (b !! i - mb) | i <- [0..n - 1]]\n\n iter :: Integer -> IO ()\n iter 1 = solve\n iter n = do\n solve\n iter $ n - 1\n \n main :: IO ()\n main = do\n s <- getLine\n iter (read s :: Integer)"}, {"source_code": "import Control.Monad -- for replicateM_\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve a b = answer\n where \n min_a = minimum a\n min_b = minimum b\n substract_min_a = map (\\x -> x - min_a) a\n substract_min_b = map (\\x -> x - min_b) b\n answer = sum $ zipWith (\\x y -> max x y) substract_min_a substract_min_b\n\ndeal :: IO()\ndeal = do \n getLine\n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n putStrLn $ show $ solve a b\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess n [] [] _ _ = n\nprocess n (x:xs) (y:ys) mx my = process (n+(max (x-mx) (y-my) )) xs ys mx my\n\nonecase = do\n\t\tgetLine\n\t\tx<- map read <$> words <$> getLine ::IO [Integer]\n\t\ty<- map read <$> words <$> getLine ::IO [Integer]\n\t\tprint $ process 0 x y (minimum x) (minimum y)\n\t\t\nmain= do\n\t\ta<- read <$> getLine ::IO Int\n\t\treplicateM_ a onecase\t\n\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map show\n >>> unlines\n\nprocess :: [[Integer]] -> [Integer]\nprocess [] = []\nprocess ([_] : xs : ys : rest) = solve xs ys : process rest\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve xs ys = sum $ zipWith max (reduce xs) (reduce ys)\n where\n reduce xs = subtract (minimum xs) <$> xs\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List (sort)\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map show\n >>> unlines\n\nprocess :: [[Integer]] -> [Integer]\nprocess [] = []\nprocess ([_] : xs : ys : rest) = solve xs ys : process rest\n\nsolve :: [Integer] -> [Integer] -> Integer\nsolve xs ys =\n sum $\n zipWith\n max\n (zipWith (-) xs (repeat (minimum xs)))\n (zipWith (-) ys (repeat (minimum ys)))\n"}, {"source_code": "solve :: [Integer] -> [Integer] -> Integer\nsolve as bs = sum $ zipWith solve' as bs\n where\n minA = minimum as\n minB = minimum bs\n solve' a b = max (a - minA) (b - minB)\n\n\nclean :: [String] -> [(String, String)]\nclean [] = []\nclean (_ : a : b: ss) = (a,b) : clean ss\nclean _ = undefined\n\nmapPair :: (a -> b) -> (a, a) -> (b, b)\nmapPair f (a, b) = (f a, f b)\n\nmain :: IO ()\nmain = interact\n (unlines . map (show . uncurry solve . mapPair (map read . words) ) . clean . tail . lines)\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- getLine\n as <- map read . words <$> getLine\n bs <- map read . words <$> getLine\n let\n minA = foldl' min (head as) (tail as)\n minB = foldl' min (head bs) (tail bs)\n cost = sum $ zipWith act as bs where\n act a b = max (a - minA) (b - minB)\n putStrLn $ show cost\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Bool\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n getLine\n as <- map read . words <$> getLine\n bs <- map read . words <$> getLine\n let moves = zip (subtract (minimum as) <$> as) (subtract (minimum bs) <$> bs)\n print $ sum $ (\\(a, b) -> a + b - min a b) <$> moves\n"}], "negative_code": [{"source_code": "solve :: [Int] -> [Int] -> Int\nsolve as bs = sum $ zipWith solve' as bs\n where\n minA = minimum as\n minB = minimum bs\n solve' a b = max (a - minA) (b - minB)\n\n\nclean :: [String] -> [(String, String)]\nclean [] = []\nclean (_ : a : b: ss) = (a,b) : clean ss\nclean _ = undefined\n\nmapPair :: (a -> b) -> (a, a) -> (b, b)\nmapPair f (a, b) = (f a, f b)\n\nmain :: IO ()\nmain = interact\n (unlines . map (show . uncurry solve . mapPair (map read . words) ) . clean . tail . lines)\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\n\n\nreadInt :: String -> Int\nreadInt s = read s :: Int\n\ngetInt :: IO Int\ngetInt = readInt <$> getLine\n\nreadLineInts :: String -> [Int]\nreadLineInts s = map readInt $ words s\n\ngetInts :: IO [Int]\ngetInts = readLineInts <$> getLine\n\n\nmain :: IO ()\nmain = do\n testCount <- getInt\n replicateM_ testCount test\n\ntest :: IO ()\ntest = do\n n <- getInt\n as <- getInts\n bs <- getInts\n let minA = minimum as\n let minB = minimum bs\n let actCount = sum $ map (pToAct minA minB) $ zip as bs\n print actCount\n\npToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a\npToAct minA minB (a, b) = max (a - minA) (b - minB)\n\n\n\n"}, {"source_code": "#!/usr/bin/env stack\n-- stack --resolver nightly-2020-08-16 script\n\nimport Data.List\nimport Control.Monad\n\n\n\nreadInt :: String -> Int\nreadInt s = read s :: Int\n\ngetInt :: IO Int\ngetInt = readInt <$> getLine\n\nreadLineInts :: String -> [Int]\nreadLineInts s = map readInt $ words s\n\ngetInts :: IO [Int]\ngetInts = readLineInts <$> getLine\n\n\nmain :: IO ()\nmain = do\n testCount <- getInt\n replicateM_ testCount test\n\ntest :: IO ()\ntest = do\n n <- getInt\n as <- getInts\n bs <- getInts\n let minA = minimum as\n let minB = minimum bs\n let actCount = sum $ map (pToAct minA minB) $ zip as bs\n print actCount\n\npToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a\npToAct minA minB (a, b) = max (a - minA) (b - minB)\n\n\n\n"}, {"source_code": "#!/usr/bin/env stack\n-- stack --resolver lts-16.10 script\n\nimport Data.List\nimport Control.Monad\n\n\n\nreadInt :: String -> Int\nreadInt s = read s :: Int\n\ngetInt :: IO Int\ngetInt = readInt <$> getLine\n\nreadLineInts :: String -> [Int]\nreadLineInts s = map readInt $ words s\n\ngetInts :: IO [Int]\ngetInts = readLineInts <$> getLine\n\n\nmain :: IO ()\nmain = do\n testCount <- getInt\n replicateM_ testCount test\n\ntest :: IO ()\ntest = do\n n <- getInt\n as <- getInts\n bs <- getInts\n let minA = minimum as\n let minB = minimum bs\n let actCount = sum $ map (pToAct minA minB) $ zip as bs\n print actCount\n\npToAct :: (Ord a, Num a) => a -> a -> (a, a) -> a\npToAct minA minB (a, b) = max (a - minA) (b - minB)\n\n\n\n"}], "src_uid": "35368cefc5ce46a9f41a15734826a151"} {"source_code": "main = interact $ parse . tail . lines\n\nparse (x:xs)\n | i == k = \"YES\"\n | otherwise = \"NO\"\n where i = (map read (words x)) :: [Int]\n j = map f xs\n k = map (length) j\n\nf = filter (\\a -> a == 'a'\n || a=='e'\n || a=='i'\n || a=='o'\n || a=='u'\n || a=='y')\n", "positive_code": [{"source_code": "import Control.Monad\n\ngetInt = read `fmap` getLine :: IO Int\n\ncontainsVowel str = any (`elem` \"aeiouy\") str\ncountVowel str = length (filter (`elem` \"aeiouy\") str)\n\nmain = do\n n <- getInt\n patterns <- (map read . words) `fmap` getLine :: IO [Int]\n lines <- replicateM n getLine\n results <- forM (zip patterns lines) $ \\(pat, line) -> do\n let cands = filter containsVowel (words line)\n if pat == sum (map countVowel cands)\n then return True\n else return False\n if all id results\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tps <- readInts\n\tss <- lines <$> getContents\n\tputStrLn $ which \"YES\" \"NO\" $ ps == map f ss\n\nf s = length $ filter ( `elem` \"aeiouy\" ) $ s\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Bool\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n css <- replicateM n getLine\n putStrLn . bool \"NO\" \"YES\" .and $ zipWith (==) xs [length$filter(`elem`\"aeiouy\")cs|cs<-css]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tgetLine\n\tps <- readInts\n\tss <- lines <$> getContents\n\tputStrLn $ which \"YES\" \"NO\" $ and $ zipWith f ps ss\n\nf p s\n\t| vowels == 0 = True\n\t| otherwise = vowels == p\n\twhere\n\t\tvowels = length $ filter ( `elem` \"aeiouy\" ) $ s\n"}], "src_uid": "cf595689b5cbda4f1d629524ad275650"} {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative (liftA2)\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nsg = group . sort\nlh = liftA2 (,) head length\ncount = map lh . sg\nyesno b = if b then \"YES\" else \"NO\"\n\nsolve :: ([Int] -> Int) -> [[Int]] -> Bool\nsolve g v = length missing == 0 \n || (maximum . map snd . count . concat) missing == length missing\n where val = g $ head v\n missing = filter (not . elem val) v\n\nmain :: IO ()\nmain = do\n [n, m] <- readInts\n v <- replicateM m readInts\n putStrLn $ yesno $ (solve head v || solve last v)", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, m ] <- readInts\n\tps <- map mp <$> replicateM m readInts\n\tputStrLn $ which \"YES\" \"NO\" $ solve ps ( fst $ head ps ) (-1) || solve ps ( snd $ head ps ) (-1)\n\nsolve [] _ _ = True\nsolve ( ( a, b ) : ps ) x y\n\t| a == x || b == x = solve ps x y\n\t| y == -1 = solve ps x a || solve ps x b\n\t| a == y || b == y = solve ps x y\n\t| otherwise = False"}], "negative_code": [], "src_uid": "60af9947ed99256a2820814f1bf1c6c6"} {"source_code": "--import Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain = do\n let a = (10^2000 - 1) `div` 9\n b = 10^2000 - a\n print a\n print b\n\n\n\n-- Below is template code\nreadInt = fst . fromJust . B.readInt\nlineInt = readInt <$> B.getLine\nlineInts = map readInt . B.words <$> B.getLine\n\n--infixr 0 ##\n--(##) x msg = traceShow msg x\n\n", "positive_code": [{"source_code": "main = putStrLn . unwords $ [replicate 2230 '5', replicate 2229 '4' ++ \"5\"]\n"}, {"source_code": "import Control.Monad\nimport Data.Bool\nimport Data.Tuple\nimport Data.Maybe\nimport Data.Tree\nimport Data.Graph\nimport Data.Array.IArray\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as B\n\n\niogetints :: IO [Int]\niogetints = getLine >>= (return . map read . words)\n\nfreadEdgeList :: IO [Edge]\nfreadEdgeList = B.getContents >>= (return . pairify . map (fst . fromJust . B.readInt) . B.words)\n\nindexed :: [a] -> [(Int, a)]\nindexed = go 0 where\n go :: Int -> [a] -> [(Int, a)]\n go _ [] = []\n go i (x:xs) = (i, x) : (go (succ i) xs)\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n go (Node x ts) = f x (map go ts)\n\npairify :: [a] -> [(a, a)]\npairify [] = []\npairify (x:y:xs) = (x, y) : (pairify xs)\n\nbuildTree :: Int -> Vertex -> [Edge] -> Tree Vertex\nbuildTree n r es = fdfs (-1) r where\n g = accumArray (flip (:)) [] (1, n) $ ap (++) (map swap) $ es :: Graph\n fdfs :: Vertex -> Vertex -> Tree Vertex\n fdfs p v = Node v $ map (fdfs v) $ delete p $ g!v\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (x, y) = (f x, f y)\n\nsolve :: String\nsolve = (replicate 2000 '8') ++ \"9\" ++ \"\\n\" ++ (replicate 2001 '1')\n \nmain :: IO ()\nmain = do\n putStrLn $ solve"}], "negative_code": [], "src_uid": "bba30bd91f085471f624c0f723b78a82"} {"source_code": "import Control.Monad\nimport Data.List\nmain = do\n t <- readLn\n replicateM_ t $ do\n x <- getLine\n y <- getLine\n let xl = elemIndex '1' (drop yl $ reverse x)\n Just yl = elemIndex '1' (reverse y)\n print $ maybe 0 id xl\n \n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- liftM read getLine\n forM_ [1..t] $ \\_ -> do\n x <- liftM reverse getLine\n y <- liftM reverse getLine\n let firstYOne = length . takeWhile (== '0') $ y\n let nextXOne = length . takeWhile (== '0') $ drop firstYOne x\n print nextXOne\n "}, {"source_code": "f=length.fst.span('1'>);s[]=[];s(x:y:z)=(show$f$drop(f y)x):s z;main=interact$unlines.s.map reverse.tail.words"}], "negative_code": [], "src_uid": "a20af745cf610eaa8116574805340591"} {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Int\nimport qualified Data.Map as Map\n\ntype Cimap = Map.Map Char Int64\ntype Iimap = Map.Map Int64 Int64\n\ng :: String -> [Int64] -> Char -> Iimap\ng a b c = gg a b c (Map.empty) where\n\tgg \"\" _ _ acc = acc\n\tgg (x:xs) (p:ps) c acc\n\t\t| c /= x = gg xs ps c acc\n\t\t| c == x = gg xs ps c (Map.alter (func) p acc) where\n\t\t\tfunc Nothing \t= Just 1\n\t\t\tfunc (Just x) \t= Just (x + 1)\n\t\nq :: Iimap -> Iimap -> Int64\nq a b = Map.foldWithKey (\\k x ks -> ks + if k `Map.member` b then x * (b Map.! k) else 0) 0 a \n\nans :: Cimap -> String -> Int64\nans wf s = f s ( map (wf Map.!) s) where\n\tf \"\" _ = 0\n\tf [c] _ = 0\n\tf s wfm = f left leftwfm + f right rightwfm + mid where\n\t\t(left, right) = splitAt (length s `div` 2) s\n\t\t(leftwfm, rightwfm) = splitAt (length s `div` 2) wfm\n\t\tlmid = map (g (reverse left) (map (\\x -> -x) $ scanl (+) 0 $ reverse leftwfm)) ['a'..'z'] \n\t\trmid = map (g right (scanl (+) 0 $ rightwfm)) ['a'..'z']\n\t\tmid = sum $ map (\\(a,b) -> q a b) (zip lmid rmid)\n\nmain :: IO()\nmain = do\n\ta <- fmap (map read . words) getLine\n\ts <- getLine\n\tputStrLn $ (show $ ans (Map.fromList $ zip ['a'..'z'] a) s)\t", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n xs <- map (fromIntegral.readInt).B.words <$> B.getLine\n cs <- getLine\n print $ solve (listArray(0,25)xs) cs\n\nsolve :: UArray Int Int64 -> String -> Int64\nsolve xs cs = sum $ map solve' ['a'..'z']\n where\n !n = length cs\n \n arr :: UArray Int Int64\n arr = listArray(0, n - 1).tail$scanl(\\acc c->acc + unsafeAt xs (fromEnum c - 97)) 0 cs\n\n solve' :: Char -> Int64\n solve' c0 = go 0 M.empty 0 cs\n where\n go !res !memo !i (c:cs)\n | c == c0 && i > 0 = case M.lookup (unsafeAt arr $ i - 1) memo of\n Just x -> go (res + x) (M.insertWith (+) (unsafeAt arr i) 1 memo) (i+1) cs\n Nothing -> go res (M.insertWith (+) (unsafeAt arr i) 1 memo) (i+1) cs\n | c /= c0 = go res memo (i + 1) cs \n | otherwise = go res (M.insert (unsafeAt arr i) 1 memo) (i + 1) cs\n go res _ _ [] = res\n"}, {"source_code": "module Main (main) where\n\nimport Control.Monad\nimport Data.Functor\nimport Data.Char(ord)\nimport qualified Data.Map.Strict as Map\n\nisDigit x = x=='-' || (x>='0' && x<='9')\nsplit f l@(a:as) lft\n\t| f a = split f as (a:lft)\n\t| otherwise = (reverse lft, as)\nsplit _ [] lft = (reverse lft, [])\nreadInts::String -> [Integer]\nreadInts [] = []\nreadInts l@(x:xs)\n\t| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)\n\t| otherwise = readInts xs\n\nmain = do\n\twts <- Map.fromList . (zip ['a'..'z']) . readInts <$> getLine\n\tlet mapping (w, _, _) c = ((+) w $ wts Map.! c, w, c)\n\tstr <- scanl mapping (0, 0, '-') <$> getLine\n\tlet\n\t\tfn (mp, sm) (ps, pps, c) = (mp', sm') where\n\t\t\tmp' = Map.insertWith (+) (ps, c) 1 mp\n\t\t\tsm' = (+) sm $ Map.findWithDefault 0 (pps, c) mp\n\tlet res = snd $ foldl fn (Map.empty, 0) str\n\tprint res\n"}], "negative_code": [], "src_uid": "0dd2758f432542fa82ff949d19496346"} {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n n <- get\n a <- replicateM n get\n putsln $ showList $ f1 n a\n\nf1 :: Int -> [Int64] -> [Int64]\nf1 n a = let bitarray = runSTUArray $ do\n na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c ->\n do\n forM_ (f2 c 0) (\\x -> do\n v <- readArray na x\n if v == 0 then\n writeArray na x (- i)\n else\n writeArray na x 1\n )\n return $ i + 1) 1 a\n return na\n in\n let maxb = foldl (\\i j ->\n if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]\n in\n let changedList = runSTUArray $ do\n na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c -> do\n writeArray na i c\n return $ i + 1) 0 a\n v <- readArray na (fromIntegral maxb)\n v2 <- readArray na 0\n writeArray na 0 v\n writeArray na (fromIntegral maxb) v2\n return na\n in\n elems changedList\n \nf2 :: Int64 -> Int -> [Int]\nf2 c i = if c == 0 then []\n else\n if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))\n else f2 (div c 2) (i + 1)\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,\nUndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport GHC.TypeLits (TypeError, ErrorMessage (Text))\nimport Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (fromList, null, Seq( Empty ), (|>), (<|), (><), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n n <- get :: EIO Int\n a <- replicateM n get :: EIO [Int64]\n putln (f1 n a :: [Int64])\n\nf1 :: Int -> [Int64] -> [Int64]\nf1 n a = let bitarray = runSTUArray $ do\n na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c ->\n do\n forM_ (f2 c 0) (\\x -> do\n v <- readArray na x\n if v == 0 then\n writeArray na x (- i)\n else\n writeArray na x 1\n )\n return $ i + 1) 1 a\n return na\n in\n let maxb = foldl (\\i j ->\n if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]\n in\n let changedList = runSTUArray $ do\n na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c -> do\n writeArray na i c\n return $ i + 1) 0 a\n v <- readArray na (fromIntegral maxb)\n v2 <- readArray na 0\n writeArray na 0 v\n writeArray na (fromIntegral maxb) v2\n return na\n in\n elems changedList\n \nf2 :: Int64 -> Int -> [Int]\nf2 c i = if c == 0 then []\n else\n if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))\n else f2 (div c 2) (i + 1)\n"}, {"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n n <- get\n a <- replicateM n get\n putsln $ showList $ f1 n a\n\nf1 :: Int -> [Int64] -> [Int64]\nf1 n a = let bitarray = runSTUArray $ do\n na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c ->\n do\n forM_ (f2 c 0) (\\x -> do\n v <- readArray na x\n if v == 0 then\n writeArray na x (- i)\n else\n writeArray na x 1\n )\n return $ i + 1) 1 a\n return na\n in\n let maxb = foldl (\\i j ->\n if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]\n in\n let changedList = runSTUArray $ do\n na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c -> do\n writeArray na i c\n return $ i + 1) 0 a\n v <- readArray na (fromIntegral maxb)\n v2 <- readArray na 0\n writeArray na 0 v\n writeArray na (fromIntegral maxb) v2\n return na\n in\n elems changedList\n \nf2 :: Int64 -> Int -> [Int]\nf2 c i = if c == 0 then []\n else\n if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))\n else f2 (div c 2) (i + 1)\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,\nUndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport GHC.TypeLits (TypeError, ErrorMessage (Text))\nimport Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (fromList, null, Seq( Empty ), (|>), (<|), (><), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toCharSeq :: a -> DSeq.Seq Char\n toString :: a -> String\n toString x = toList $ toCharSeq x\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toCharSeq = toCharSeqp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toCharSeqp :: flag -> a -> DSeq.Seq Char\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toCharSeqp _ x = DSeq.fromList $ show x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toCharSeqp _ x = DSeq.fromList x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toCharSeqp _ [] = DSeq.Empty\n toCharSeqp _ (x : xs) = foldl (\\c i -> c DSeq.>< i) (toCharSeq x) (fmap (\\x -> ' ' DSeq.<| (toCharSeq x)) xs)\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toString\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toString\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n n <- get :: EIO Int\n a <- replicateM n get :: EIO [Int64]\n putln (f1 n a :: [Int64])\n\nf1 :: Int -> [Int64] -> [Int64]\nf1 n a = let bitarray = runSTUArray $ do\n na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c ->\n do\n forM_ (f2 c 0) (\\x -> do\n v <- readArray na x\n if v == 0 then\n writeArray na x (- i)\n else\n writeArray na x 1\n )\n return $ i + 1) 1 a\n return na\n in\n let maxb = foldl (\\i j ->\n if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]\n in\n let changedList = runSTUArray $ do\n na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c -> do\n writeArray na i c\n return $ i + 1) 0 a\n v <- readArray na (fromIntegral maxb)\n v2 <- readArray na 0\n writeArray na 0 v\n writeArray na (fromIntegral maxb) v2\n return na\n in\n elems changedList\n \nf2 :: Int64 -> Int -> [Int]\nf2 c i = if c == 0 then []\n else\n if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))\n else f2 (div c 2) (i + 1)\n"}, {"source_code": "import Data.Bits\nmain :: IO ()\nmain = do\n _ <- getLine\n as <- (map read.words) <$> getLine\n putStrLn $ (unwords.map show) $ solve as\n\ntype Situation = ([Indexed Value],Iterator)\ntype Iterator = Int\ntype Indexed a = (Int, a)\ntype Value = Int\n\nsolve :: [Int] -> [Int]\nsolve as =\n case mix of\n Just (ix,val) -> val : ( take ix as) ++ (drop (ix+1) as)\n Nothing -> as\n where\n mix = stelle (zip [0..] as, 29)\n\nstelle :: Situation -> Maybe (Indexed Value)\nstelle (_, -1) = Nothing\nstelle (vals, i) =\n if (anzahl::Int) == 1\n then mIndex\n else stelle (vals, i-1)\n where\n (anzahl,mIndex) = foldr bin acc vals\n bin (ix,val) (count,m) =\n if testBit val i\n then\n (count+1,Just (ix,val))\n else\n (count,m)\n acc = (0,Nothing)\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,\nUndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport Data.Ord\nimport Data.Int\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n n <- get\n a <- replicateM n get\n putln $ f1 n a\n\nf1 :: Int -> [Int64] -> [Int64]\nf1 n a = let bitarray = runSTUArray $ do\n na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c ->\n do\n forM_ (f2 c 0) (\\x -> do\n v <- readArray na x\n if v == 0 then\n writeArray na x (- i)\n else\n writeArray na x 1\n )\n return $ i + 1) 1 a\n return na\n in\n let maxb = foldl (\\i j ->\n if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]\n in\n let changedList = runSTUArray $ do\n na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c -> do\n writeArray na i c\n return $ i + 1) 0 a\n v <- readArray na (fromIntegral maxb)\n v2 <- readArray na 0\n writeArray na 0 v\n writeArray na (fromIntegral maxb) v2\n return na\n in\n elems changedList\n \nf2 :: Int64 -> Int -> [Int]\nf2 c i = if c == 0 then []\n else\n if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))\n else f2 (div c 2) (i + 1)\n"}, {"source_code": "{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, ConstraintKinds,\nUndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport GHC.TypeLits (TypeError, ErrorMessage (Text))\nimport Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (fromList, null, Seq( Empty ), (|>), (<|), (><), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . putStr . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . putStrLn . toShow\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n n <- get :: EIO Int\n a <- replicateM n get :: EIO [Int64]\n putln (f1 n a :: [Int64])\n\nf1 :: Int -> [Int64] -> [Int64]\nf1 n a = let bitarray = runSTUArray $ do\n na <- newArray (0, 64) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c ->\n do\n forM_ (f2 c 0) (\\x -> do\n v <- readArray na x\n if v == 0 then\n writeArray na x (- i)\n else\n writeArray na x 1\n )\n return $ i + 1) 1 a\n return na\n in\n let maxb = foldl (\\i j ->\n if (bitarray ! j < 0) then ((- (bitarray ! j)) - 1) else i) 0 [0..63]\n in\n let changedList = runSTUArray $ do\n na <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)\n foldlM (\\i c -> do\n writeArray na i c\n return $ i + 1) 0 a\n v <- readArray na (fromIntegral maxb)\n v2 <- readArray na 0\n writeArray na 0 v\n writeArray na (fromIntegral maxb) v2\n return na\n in\n elems changedList\n \nf2 :: Int64 -> Int -> [Int]\nf2 c i = if c == 0 then []\n else\n if (mod c 2) == 1 then i : (f2 (div c 2) (i + 1))\n else f2 (div c 2) (i + 1)\n"}], "negative_code": [{"source_code": "import Data.Bits\nmain :: IO ()\nmain = do\n _ <- getLine\n as <- (map read.words) <$> getLine\n putStrLn $ (unwords.map show) $ solve as\n\ntype Situation = ([Indexed Value],Iterator)\ntype Iterator = Int\ntype Indexed a = (Int, a)\ntype Value = Int\n\nsolve :: [Int] -> [Int]\nsolve as =\n case mix of\n Just (ix,val) -> val : ( take ix as) ++ (drop (ix+1) as)\n Nothing -> as\n where\n mix = stelle (zip [0..] as, 28)\n\nstelle :: Situation -> Maybe (Indexed Value)\nstelle (_, -1) = Nothing\nstelle (vals, i) =\n if (anzahl::Int) == 1\n then mIndex\n else stelle (vals, i-1)\n where\n (anzahl,mIndex) = foldr bin acc vals\n bin (ix,val) (count,m) =\n if testBit val i\n then\n (count+1,Just (ix,val))\n else\n (count,m)\n acc = (0,Nothing)\n"}], "src_uid": "14fd47f6f0fcbdb16dbd73dcca8a782f"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST.Safe\nimport Data.List\nimport Data.Int\n\nmain = mapM_ print . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n poi\n return [solve n xs]\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs = foldl' (\\s i -> if c!i == 0 then s else (s + fromIntegral (c!i) * fromIntegral (a!i) `rem` fromIntegral d * fromIntegral (t!(c!i - 1))) `rem` fromIntegral d) (0 :: Int64) $ range b\n where\n m = maximum xs\n d = 1000000007\n b = (2, m)\n e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int\n c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int\n a = runSTUArray $ do\n z <- newListArray b $ range b :: ST s (STUArray s Int Int)\n sequence_ [sequence_ [do { zi <- readArray z i; zt <- readArray z (i * j); writeArray z (i * j) (zt - zi) } | j <- [2..m `quot` i]] | i <- range b]\n return z\n t = listArray (0, m) $ iterate (\\i -> i * 2 `rem` d) 1 :: UArray Int Int", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.Array.ST.Safe\nimport Control.Monad.ST.Safe\nimport Data.List\nimport Data.Int\n\nmain = print . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n solve `fmap` replicateM n poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve xs = foldl' (\\s i -> if c!i == 0 then s else (s + fromIntegral (c!i) * fromIntegral (a!i) `rem` fromIntegral d * fromIntegral (t!(c!i - 1))) `rem` fromIntegral d) (0 :: Int64) $ range b\n where\n m = maximum xs\n d = 1000000007\n b = (2, m)\n e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int\n c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int\n a = runSTUArray $ do\n z <- newListArray b $ range b :: ST s (STUArray s Int Int)\n sequence_ $ concat [[join $ liftM2 ((writeArray z (i * j) .) . subtract) (readArray z i) (readArray z (i * j)) | j <- [2..m `quot` i]] | i <- range b]\n return z\n t = listArray (0, m) $ iterate (\\i -> i * 2 `rem` d) 1 :: UArray Int Int"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\nimport Data.Int\n\nmain = mapM_ print . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n poi\n return [solve n xs]\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs = foldl' (\\s i -> if c!i == 0 then s else (s + fromIntegral (c!i) * fromIntegral (a!i) `rem` fromIntegral d * fromIntegral (t!(c!i - 1))) `rem` fromIntegral d) (0 :: Int64) $ range b\n where\n m = maximum xs\n d = 1000000007\n b = (2, m)\n e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int\n c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int\n a = accumArray (+) 0 b $ concat [(i, i):[(i * j, -i) | j <- [2..m `quot` i]] | i <- range b] :: UArray Int Int\n t = listArray (0, m) $ iterate (\\i -> i * 2 `rem` d) 1 :: UArray Int Int"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad.Trans.State.Lazy\nimport Control.Monad\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = mapM_ print . evalState app . B.words =<< B.getContents\n\napp = do\n n <- poi\n xs <- replicateM n poi\n return [solve n xs]\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n xs = foldl' (\\s i -> if c!i == 0 then s else (s + c!i * a!i `rem` d * t!(c!i - 1)) `rem` d) 0 $ range b\n where\n m = maximum xs\n d = 1000000007\n b = (2, m)\n e = accumArray (+) 0 (1, m) $ zip xs (repeat 1) :: UArray Int Int\n c = listArray b [sum [e!(i * j) | j <- [1..m `quot` i]] | i <- range b] :: UArray Int Int\n a = accumArray (+) 0 b $ concat [(i, i):[(i * j, -i) | j <- [2..m `quot` i]] | i <- range b] :: UArray Int Int\n t = listArray (0, m) $ iterate (\\i -> i * 2 `rem` d) 1 :: UArray Int Int"}], "src_uid": "18b5557b282ebf7288de50ab8cb51c60"} {"source_code": "main = do\n [n,b,d] <- return . map read . words =<< getLine\n oranges <- return . map read . words =<< getLine\n let acceptable = filter (<=b) oranges\n\tsqueeze [] _ n = n\n\tsqueeze (o:os) w n\n\t | d < w+o\t = squeeze os 0 (n+1)\n\t | otherwise\t = squeeze os (w+o) n\n print $ squeeze acceptable 0 0\n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n firstLine <- getLine\n secondLine <- getLine\n\n let params = (map read . words) firstLine :: [Int]\n let oranges = (map read . words) secondLine :: [Int]\n let result = dumps (params !! 1) (params !! 2) 0 oranges\n print result\n\ndumps :: (Integral a) => a -> a -> a -> [a] -> a\ndumps b d currentlevel [] = 0 -- if the list is empty, vasya should not dump\ndumps b d currentlevel (x:xs)\n | x > b = dumps b d currentlevel xs --the orange is larger\n | currentlevel + x > d = 1 + dumps b d 0 xs\n | otherwise = dumps b d (currentlevel + x) xs"}, {"source_code": "import Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.f.parse.words\nparse = map fastRead\n\ng [] y temp ans = ans\ng (x:xs) y temp ans\n | (temp+x) > y = g xs y 0 (ans+1)\n | otherwise = g xs y (temp+x) ans\n\nf (x:y:z:xs) = g (filter (<=y) xs) z 0 0\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nf a _ tb d [] = a + if tb > d then 1 else 0 \nf a b tb d (o:os) = \n if o > b \n then f a b tb d os\n else if tb > d\n then f (a+1) b o d os\n else f a b (o+tb) d os\n\nints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\nmain = do\n [n,b,d] <- ints\n as <- ints\n print $ f 0 b 0 d as \n"}, {"source_code": "--ghc 8.0.1 /opt/ghc/8.0.1/lib/ghc-8.0.0.20160127/\n\nsolve n b d r xs\n | n == 0 = 0\n | (head) xs > b = solve (n-1) b d r (tail xs)\n | r + (head xs) > d = 1 + solve (n-1) b d 0 (tail xs)\n | otherwise = solve (n-1) b d (r + head xs) (tail xs)\n\nmain = getLine >>= (return . map read . words) >>= \\[n, b, d] ->\n getLine >>= (return . map read . words) >>= putStrLn . show . (solve n b d 0)"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve (b:d:as) = go 0 $ filter (<= b) as where\n go _ [] = 0\n go v (a:as) | v' > d = 1 + go 0 as\n | otherwise = go v' as\n where v' = v + a\n"}, {"source_code": "main = getContents >>= print . solve 0 0 . map read . words\n\nsolve cnt tmp (n:b:d:as)\n | null as = cnt\n | b < head as = solve cnt tmp (n:b:d:tail as) \n | tmp + head as <= d = solve cnt (tmp + head as) (n:b:d:tail as)\n | otherwise = solve (cnt + 1) 0 (n:b:d:tail as)\n\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: [Int] -> Int -> Int -> Int -> Int -> Int\n solve [] _ _ _ accumulator = accumulator\n solve (x:xs) currentValue b d accumulator =\n let nextValue = currentValue + x\n in case (x <= b, nextValue > d) of\n (True, True) -> solve xs 0 b d (accumulator + 1)\n (True, False) -> solve xs nextValue b d accumulator\n (False, _) -> solve xs currentValue b d accumulator\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n main :: IO()\n main = do\n [n,b,d] <- getLine >>= return . (map readInt) . words\n xs <- getLine >>= return . (map readInt) . words\n putStrLn $ show $ solve xs 0 b d 0\n -- n <- getLine >>= return . readInt\n -- putStrLn $ show $ solve [5,6] 0 7 10 0\n -- putStrLn \"hello world\"\n"}, {"source_code": "calc :: [Int] -> Int -> Int -> Int\ncalc [] acum d = if acum > d then 1 else 0\ncalc (x:xs) acum d = if acum > d then 1 + calc xs x d else calc xs (acum + x) d\n\nprocess :: String -> String\nprocess str =\n let [header, body] = lines str\n [n, b, d] = map read $ words header\n a = filter (<= b) . map read . take n . words $ body\n in show $ calc a 0 d\n\nmain :: IO ()\nmain = interact process"}], "negative_code": [{"source_code": "import Numeric\n\nfastRead :: String -> Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.f.parse.words\nparse = map fastRead\n\ng [] y temp ans = ans\ng (x:xs) y temp ans\n | (temp+x) > y = g xs y 0 (ans+1)\n | otherwise = g xs y (temp+x) ans\n\nf (x:y:z:xs) = g (filter ( Integer\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ show.f.parse.words\nparse = map fastRead\n\nf (x:y:z:xs) = (sum (filter ( d then 1 else 0 \nf a b tb w tw (o:os) = \n if o > b \n then f a b tb w tw os\n else if tw > w \n then f (a+1) b (o+tb) w 0 os\n else if (o+tb) > b \n then f a b 0 w (w+o+tb-b) os\n else f a b (o+tb) w tw os\n\nints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\nmain = do\n [n,b,d] <- ints\n as <- ints\n print $ f 0 b 0 d 0 as \n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nf a _ _ _ d [] = a + if d > 0 then 1 else 0 \nf a b tb w tw (o:os) = \n if o > b \n then f a b tb w tw os\n else if tw > w \n then f (a+1) b (o+tb) w 0 os\n else if (o+tb) > b \n then f a b 0 w (w+o+tb-b) os\n else f a b (o+tb) w tw os\n\nints = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\nmain = do\n [n,b,d] <- ints\n as <- ints\n print $ f 0 b 0 d 0 as \n"}, {"source_code": "main = getContents >>= print . solve 0 0 . map read . words\n\nsolve cnt tmp (n:b:d:as)\n | null as = cnt\n | b < head as = solve cnt tmp (n:b:d:tail as) \n | tmp + head as <= d = solve cnt (tmp + head as) (n:b:d:tail as)\n | otherwise = solve (cnt + 1) ((tmp + head as) `mod` d) (n:b:d:tail as)\n\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n solve :: [Int] -> Int -> Int -> Int -> Int -> Int\n solve [] _ _ _ accumulator = accumulator\n solve (x:xs) currentValue b d accumulator =\n let nextValue = currentValue + x\n in case (x < b, nextValue > d) of\n (True, True) -> solve xs 0 b d (accumulator + 1)\n (True, False) -> solve xs nextValue b d accumulator\n (False, _) -> solve xs currentValue b d accumulator\n\n -- converting list to Set\n -- let mySet = S.fromList myList\n\n main :: IO()\n main = do\n [n,b,d] <- getLine >>= return . (map readInt) . words\n xs <- getLine >>= return . (map readInt) . words\n putStrLn $ show $ solve xs 0 b d 0\n -- n <- getLine >>= return . readInt\n -- putStrLn $ show $ solve [5,6] 0 7 10 0\n -- putStrLn \"hello world\"\n"}], "src_uid": "06e9649963715e56d97297c6104fbc00"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n replicateM n ri\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve boxes = 2 * ((-minX) + (-minY) + maxX + maxY)\r\n where\r\n minX = min 0 . minimum . map head $ boxes\r\n maxX = max 0 . maximum . map head $ boxes\r\n minY = min 0 . minimum . map last $ boxes\r\n maxY = max 0 . maximum . map last $ boxes\r\n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n points = 2 * ((maximum xs - minimum xs) + (maximum ys - minimum ys))\n where\n xs = 0 : map fst points\n ys = 0 : map snd points\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n points <- replicateM n $ do\n [x, y] <- B8.getLine <&> readIntB8s\n return (x, y)\n let answer = solve n points\n printf \"%d\\n\" answer\n\n"}], "negative_code": [], "src_uid": "4af206ae108a483bdb643dc24e4bedba"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array\nimport Data.List\n\nmain = do\n [n, p] <- ( map read . words ) `liftM` getLine\n pipes <- replicateM p $ do\n [a, b, d] <- ( map read . words ) `liftM` getLine :: IO [Int]\n return (a, b, d)\n\n let mergedPipeArray :: Array Int (Maybe Int, Maybe Int, Int)\n mergedPipeArray = runST $ do\n houseArray <- newArray (1,n) (Nothing, Nothing, maxBound) :: ST s (STArray s Int (Maybe Int, Maybe Int, Int))\n forM_ pipes $ \\(from, to, dia) -> do\n (fromFrom, fromTo, fromDia) <- readArray houseArray from\n (toFrom, toTo, toDia) <- readArray houseArray to\n\n let veryFrom = maybe from id fromFrom\n veryTo = maybe to id toTo\n veryDia = min dia $ min fromDia toDia\n\n writeArray houseArray from (Nothing, Nothing, 0)\n writeArray houseArray to (Nothing, Nothing, 0)\n unless ( veryFrom == to && veryTo == from ) $ do\n writeArray houseArray veryFrom (Nothing, Just veryTo, veryDia)\n writeArray houseArray veryTo (Just veryFrom, Nothing, veryDia)\n\n unsafeFreeze houseArray\n mergedPipe = filter (\\(_, (_, to, dia)) -> case to of Just _ -> True; Nothing -> False) $ assocs mergedPipeArray\n\n --putStrLn $ show mergedPipe\n putStrLn $ show $ length mergedPipe\n putStr $ unlines $ map (\\(from, (_, Just to, dia)) -> show from ++ \" \" ++ show to ++ \" \" ++ show dia) mergedPipe\n\n return ()\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\nimport Data.Array\nimport List\n\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nmint (_,b) c = if bn then\n any (\\k -> Nothing/=(house!(i,k))) [1..n]\n else\n if (house!(j,i)) == Nothing then\n issourcerec i (j+1)\n else\n False\n rec i l | i>n = l\n rec i l = if issource i then\n rec (i+1) ((recrec i 1):l)\n else\n rec (i+1) l\n recrec i j = case (house!(i,j)) of\n Just f -> (i,(dfs j 1 (j,f)))\n Nothing -> recrec i (j+1)\n dfs i j maximum = if j>n then\n maximum\n else\n case (house!(i,j)) of\n Just f ->\n dfs j 1 (j,(mint maximum f))\n Nothing ->\n dfs i (j+1) maximum\n\nconv n l [] = (array ((1,1),(n,n)) [((i,j),Nothing)|i<-[1..n],j<-[1..n]])//l\nconv n l ((a,b,d):xs) = conv n (((a,b),Just d):l) xs\n\nconvans [] l = sort l\nconvans ((i,(j,f)):xs) l = convans xs ((i,j,f):l)\n\nputAns :: [(Int,Int,Int)] -> IO ()\nputAns l = let n = length l\n in\n do putAnsLn n\n putAnsLns l\n\nsub n p = if p/=0 then\n do abd <- scans p::IO [(Int,Int,Int)]\n putAns (convans (solve n (conv n [] abd)) [])\n else\n putAnsLn \"0\"\n\nmain = do (n,p) <- scan::IO (Int,Int)\n sub n p"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\ntype Z = Int\n\nsolve :: Int -> [(Z,Z,Z)] -> [(Z,Z,Z)]\nsolve n abds = catMaybes $ [go table1 table2 i| i<-[1..n]] where\n table1 = accumArray mplus Nothing (1,n) (map f1 abds)\n table2 = accumArray mplus Nothing (1,n) (map f2 abds)\n f1 (a,b,d) = (a,Just (b,d))\n f2 (a,b,d) = (b,Just (a,d))\n\ngo t1 t2 a\n | t2!a /= Nothing = Nothing\n | t1!a == Nothing = Nothing\n | otherwise = let (b,d) = g a in Just (a,b,d)\n where\n g a = case t1!a of\n Nothing -> (a,infty)\n Just (b,d) -> let (b',d') = g b\n in (b',min d d')\n infty = 10^7\n\n\n\nmain = do\n [n,p] <- map read . words <$> getLine\n abds <- replicateM p readABD\n let anss = solve n abds\n print $ length anss\n mapM_ printAns anss\n\nreadABD = (\\[a,b,d] -> (a,b,d)) . map read . words <$> getLine\nprintAns (a,b,d) = putStrLn $ unwords [show a, show b, show d]\n"}, {"source_code": "import Control.Monad\n\nput x l i = fl ++ (x:(tail ll))\n where (fl, ll) = splitAt i l\n\npo l = map read $ words l :: [Int]\ns1 :: [[Int]] -> Int -> [[Int]]\ns1 x n = s x (take n (repeat []))\n where\n s [] r = r\n s (x:y) r = s y (put x r ((head x) - 1))\n\nd :: [Int] -> [[Int]] -> ([Int], [[Int]])\nd (x:y:z:[]) r\n | (r!!(y-1)) == [] = ((x:y:z:[]), r)\n | x == y = ((x:y:z:[]), r)\n | otherwise = d (x:(a!!1):(minimum $ z:[(last a)]):[]) (put [] r (y-1))\n where a = r!!(y-1)\n--d (x:y:[]) r = ([0,0,0],r)\n--d (x:[]) r = ([0,0,0],r)\nd [] r = ([0,0,0],r)\n \ndig :: Int -> [[Int]] -> [[Int]]\ndig n x \n | (x!!n) == [] = x\n | otherwise = put xs ys n\n where (xs, ys) = d (x!!n) x\n \nsolve x = s2 0 x\n where\n s2 i x\n | i == (length x) = x\n | (x!!i) == [] = s2 (i +1) x\n | otherwise = s2 (i+1) (dig i x)\nsolve_r x = s3 ((length x) - 1) x\n where\n s3 i x\n | i == -1 = x\n | (x!!i) == [] = s3 (i -1) x\n | otherwise = s3 (i-1) (dig i x)\n\n--co x = [i | i <- x, not (i == [])]\nco x = [i | i <- x, (not (i == [])) && (not ((i!!0) ==(i!!1)))]\npp (x:y:z:[]) = (show x) ++ \" \" ++ (show y) ++ \" \" ++ (show z)\nmain = do\n l1 <- getLine\n let x = po l1\n let n = head x\n let p = last x\n ip <- replicateM p getLine\n let ipn = map po ip\n let t = (s1 ipn n)\n let m = co. solve_r . solve $ t\n print (length m)\n mapM_ (putStrLn.pp) m"}], "negative_code": [{"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\nimport Data.Array\nimport List\n\nclass Scan a where scan' :: String -> a\ninstance Scan Int where scan' n = read n\ninstance Scan Char where scan' (x:_) = x\ninstance Scan Float where scan' f = read f\ninstance Scan Double where scan' d = read d\ninstance Scan Integer where scan' n = read n\ninstance Scan String where scan' x = x\ninstance (Scan a,Scan b) => Scan (a,b) where scan' x = scan'' (words x)\n where\n scan'' (x:y:_) = (scan' x,scan' y)\ninstance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = scan'' (words x)\n where\n scan'' (x:y:z:_) = (scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = scan'' (words x)\n where\n scan'' (w:x:y:z:_) = (scan' w,scan' x,scan' y,scan' z)\ninstance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = scan'' (words x)\n where\n scan'' (v:w:x:y:z:_) = (scan' v,scan' w,scan' x,scan' y,scan' z)\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance Ans String where showans x = x\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscan :: (Scan a) => IO a\nscan = do n <- getLine\n return (scan' n)\n\nscans :: (Scan a) => Int -> IO [a]\nscans 0 = return []\nscans n = do x <- scan\n xs <- scans (n-1)\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nmint (_,b) c = if bn then\n True\n else\n if (house!(j,i)) == Nothing then\n issourcerec i (j+1)\n else\n False\n rec i l | i>n = l\n rec i l = if issource i then\n rec (i+1) ((recrec i 1):l)\n else\n rec (i+1) l\n recrec i j = case (house!(i,j)) of\n Just f -> (i,(dfs j 1 (j,f)))\n Nothing -> recrec i (j+1)\n dfs i j maximum = if j>n then\n maximum\n else\n case (house!(i,j)) of\n Just f ->\n dfs j 1 (j,(mint maximum f))\n Nothing ->\n dfs i (j+1) maximum\n\nconv n l [] = (array ((1,1),(n,n)) [((i,j),Nothing)|i<-[1..n],j<-[1..n]])//l\nconv n l ((a,b,d):xs) = conv n (((a,b),Just d):l) xs\n\nconvans [] l = sort l\nconvans ((i,(j,f)):xs) l = convans xs ((i,j,f):l)\n\nputAns :: [(Int,Int,Int)] -> IO ()\nputAns l = let n = length l\n in\n do putAnsLn n\n putAnsLns l\n\nsub n p = if p/=0 then\n do abd <- scans p::IO [(Int,Int,Int)]\n putAns (convans (solve n (conv n [] abd)) [])\n else\n return ()\n\nmain = do (n,p) <- scan::IO (Int,Int)\n sub n p"}, {"source_code": "import Control.Monad\n\nput x l i = fl ++ (x:(tail ll))\n where (fl, ll) = splitAt i l\n\npo l = map read $ words l :: [Int]\ns1 :: [[Int]] -> Int -> [[Int]]\ns1 x n = s x (take n (repeat []))\n where\n s [] r = r\n s (x:y) r = s y (put x r ((head x) - 1))\n \nd :: [Int] -> [[Int]] -> ([Int], [[Int]])\nd (x:y:z:[]) r\n | (r!!(y-1)) == [] = ((x:y:z:[]), r)\n | x == y = ((x:y:z:[]), r)\n | otherwise = d (x:(a!!1):(minimum $ z:[(last a)]):[]) (put [] r (y-1))\n where a = r!!(y-1)\ndig :: Int -> [[Int]] -> [[Int]] \ndig n x = put xs ys n\n where (xs, ys) = d (x!!n) x\n\nsolve x = s2 0 x\n where\n s2 i x\n | i == (length x) = x\n | (x!!i) == [] = s2 (i +1) x\n | otherwise = s2 (i+1) (dig i x)\nsolve_r x = s3 ((length x) - 1) x\n where\n s3 i x\n | i == -1 = x\n | (x!!i) == [] = s3 (i -1) x\n | otherwise = s3 (i-1) (dig i x)\n\nco x = [i | i <- x, not (i == [])]\npp (x:y:z:[]) = (show x) ++ \" \" ++ (show y) ++ \" \" ++ (show z)\nmain = do\n l1 <- getLine\n let x = po l1\n let n = head x\n let p = last x\n ip <- replicateM p getLine\n let ipn = map po ip\n let t = (s1 ipn n)\n let m = co. solve_r . solve $ dig 0 t\n print (length m)\n mapM_ (putStrLn.pp) m"}], "src_uid": "e83a8bfabd7ea096fae66dcc8c243be7"} {"source_code": "process :: Int -> Int -> Bool\nprocess n m = (n `mod` m) == 0\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ts <- fmap (map (map readInt.words).lines) getContents\n mapM_ putStrLn $ map (\\[n,m] -> if process n m then \"YES\" else \"NO\") ts", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Integer]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\ncount :: (Eq a) => a -> [a] -> Int\ncount x = length . filter (== x)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, m] <- getIntList\n putStrLn . yesOrNo . (==0) $ (n `mod` m)"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> String\nsolve n m = if n `mod` m == 0\n then \"YES\"\n else \"NO\"\n\nmain :: IO ()\nmain = do\n t <- readLn\n forM_ [1..t] $ \\_ -> do\n l <- getLine\n [n, m] <- return $ map read $ words l\n putStrLn $ solve n m\n"}, {"source_code": "import Control.Monad\npossible:: [Int] -> Bool\n\npossible (x:y:_) = rem x y == 0 \n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do \n t <- getLine \n let cases = (read t :: Int)\n results <- forM [1..cases] (\\t -> do \n integers <- readInts\n if possible integers then return \"YES\" else return \"NO\"\n )\n\n mapM putStrLn results\n"}, {"source_code": "import Control.Monad\n\nr :: IO [Int]\nr = map read . words <$> getLine\n\nmain = do\n t <- readLn :: IO Int\n forM_ [1..t] (\\_ -> do\n [n,m] <- r\n putStrLn $ if solve n m then \"YES\" else \"NO\"\n )\n\nsolve :: Int -> Int -> Bool\nsolve n m = n `rem` m == 0"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nprocess1 (x:y:[]) |x>y = mod x y ==0\n | otherwise = mod y x ==0\n\nprocess a = if process1 a then \"YES\" else \"NO\"\n\nmain::IO ()\nmain=do\n t<- read<$> getLine ::IO Int\t\n a<- map(map read. words) <$> replicateM t getLine::IO [[Int]] \n mapM_ putStrLn $ map process a \n\n"}, {"source_code": "import Control.Monad\n\n(|>) x f = f x\n\nmain = do\n line <- getLine\n forM_ [1..(read line)] $ \\t -> do\n line <- getLine\n (n, m) <- line |> words |> (map read) |> (\\l -> (l !! 0, l !! 1)) |> pure\n putStrLn $ if n `mod` m == 0\n then \"YES\"\n else \"NO\""}], "negative_code": [{"source_code": "import Control.Monad\n\n(|>) x f = f x\n\nmain = do\n line <- getLine\n forM_ [1..(read line)] $ \\t -> do\n line <- getLine\n (n, m) <- line |> words |> (map read) |> (\\l -> (l !! 0, l !! 1)) |> pure\n putStrLn (show n)\n putStrLn (show m)\n putStrLn $ if n `mod` m == 0\n then \"YES\"\n else \"NO\""}, {"source_code": "import Control.Monad\n\n(|>) x f = f x\n\nmain = do\n line <- getLine\n forM_ [1..(read line)] $ \\t -> do\n line <- getLine\n (n, m) <- line |> words |> (map read) |> (\\l -> (l !! 0, l !! 1)) |> pure\n putStrLn $ if n `div` m == 0\n then \"YES\"\n else \"NO\""}], "src_uid": "6b37fc623110e49a5e311a2d186aae46"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Bifunctor\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple\nimport Debug.Trace\n\n----- --------------------------------------------------------------\ntype TC = Int\n\ntype Output = Res\n\ninput :: Scanner TC\ninput = int\n\nnewtype Res = Res [(Int, Int)]\n\ninstance Show Res where\n show (Res ps) =\n unlines $\n show (length ps) : map (\\(i, j) -> show i <> \" \" <> show j) ps\n\nsolve :: TC -> Output\nsolve n = \"BAN\" >$> replicate n >>> concat >>> play\n\nplay :: String -> Res\nplay s | ok s = Res []\nplay s = Res $ (1 + length s1, length s - length s3) : ps\n where\n (s1, ('A' : s2, s3)) =\n s >$> break (== 'A')\n >>> second\n ( reverse\n >>> break (== 'N')\n >>> bimap reverse (tail >>> reverse)\n >>> swap\n )\n (Res ps) = play $ s1 ++ 'N' : s2 ++ 'A' : s3\n\nok :: String -> Bool\nok = not . hasSub \"BAN\"\n\nhasSub :: String -> String -> Bool\nhasSub (c : cs) (x : xs)\n | c == x = hasSub cs xs\n | otherwise = hasSub (c : cs) xs\nhasSub cs _ = null cs\n\noutput :: Int -> Output -> C.ByteString\noutput ix = showB\n\n----- -------------------------------------------------------------\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines\n\n----- Template ----------------------------------------------------------------\n\n-- Debug\ndebug :: Show a => a -> a\n\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- helpers\n(>$>) = flip ($)\n\ninfixl 0 >$>\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Ix (Ix)\r\nimport Data.List (intercalate, unfoldr)\r\n\r\nsolve :: Int -> [(Int, Int)]\r\nsolve n = takeWhile (uncurry (<)) $ zip [1, 4 ..] [(3 * n), (3 * n - 3) ..]\r\n\r\nshowPair :: (Show a1, Show a2) => (a1, a2) -> [Char]\r\nshowPair (a, b) = show a ++ \" \" ++ show b\r\n\r\ndocase :: IO ()\r\ndocase = do\r\n n <- getInt\r\n let xs = solve n\r\n print $ length xs\r\n putStrLn $ intercalate \"\\n\" (showPair <$> xs)\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ docase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts = unfoldr go where\r\n go s = do\r\n (n,s1) <- C.readInt s\r\n let s2 = C.dropWhile (==' ') s1\r\n pure (n,s2)\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n"}], "negative_code": [{"source_code": "import Data.List ((\\\\))\r\n(>>>) = flip (.)\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> tail\r\n >>> map (read >>> solve >>> showAns)\r\n >>> unlines\r\n\r\ntype Result = [(Int, Int)]\r\n\r\nshowAns :: Result -> String\r\nshowAns res = unlines $ show (length res) : map (\\(i, j) -> show i <> \" \" <> show j) res\r\n\r\nsolve :: Int -> Result\r\nsolve n = zip (as \\\\ ls) (ls \\\\ as)\r\n where\r\n as = subtract 1 . (3 *) <$> [1..n]\r\n ls = (2 * n +) <$> [1..n]\r\n"}, {"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport qualified Data.ByteString.Char8 as C\r\nimport Data.Ix (Ix)\r\nimport Data.List (intercalate, unfoldr)\r\n\r\nsolve :: Int -> [(Int, Int)]\r\nsolve 1 = [(1, 3)]\r\nsolve n = filter ((/=1).(`mod` 3).snd) $ zip lst [3 * n..]\r\n where\r\n isValid b = b `mod` 3 == 1\r\n lst = filter ((==1).(`mod`3)) [1..(3 * (n - 1))]\r\n\r\nshowPair :: (Show a1, Show a2) => (a1, a2) -> [Char]\r\nshowPair (a, b) = show a ++ \" \" ++ show b\r\n\r\ndocase :: IO ()\r\ndocase = do\r\n n <- getInt\r\n let xs = solve n\r\n print $ length xs\r\n putStrLn $ intercalate \"\\n\" (showPair <$> xs)\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ docase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts = unfoldr go where\r\n go s = do\r\n (n,s1) <- C.readInt s\r\n let s2 = C.dropWhile (==' ') s1\r\n pure (n,s2)\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n"}], "src_uid": "aeea2ca73f1b5c5b86fb508afcbec68a"} {"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\n\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn(s)\n\nmain_ :: EIO ()\nmain_ = do \n t <- get :: EIO Int\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get :: EIO Int64\n case f2 n of\n Just (a, b, c) -> do\n putsln \"YES\"\n putsln $ (show a) ++ \" \" ++ (show b) ++ \" \" ++ (show c)\n Nothing -> putsln \"NO\"\n\nf2 :: Int64 -> Maybe (Int64, Int64, Int64)\nf2 x = let ls = f3 x in\n case ls of\n [] -> Nothing\n (a, ae) : [] -> if ae < 6 then\n Nothing\n else\n Just (a, ipow a 2, ipow a $ ae - 3)\n (a, ae) : (b, be) : [] -> if ae + be <= 3 then\n Nothing\n else\n Just (a, b, (ipow a $ ae - 1) * (ipow b $ be - 1))\n (a, _) : (b, _): _ -> Just (a, b, div x $ a * b)\n\nf3 :: Int64 -> [(Int64, Int64)]\nf3 n = f4 n 2 $ sqrt $ fromIntegral n\n\nf4 :: Int64 -> Int64 -> Double -> [(Int64, Int64)]\nf4 n x d = if (fromIntegral x) > d then\n if n /= 1 then\n [(n, 1)]\n else\n []\n else if mod n x == 0 then\n let (np, ep) = divrec n x in\n (x, ep) : f4 np (x + 1) d\n else\n f4 n (x + 1) d\n\ndivrec :: Int64 -> Int64 -> (Int64, Int64)\ndivrec n x = if mod n x == 0 then\n let (np, ep) = divrec (div n x) x in\n (np, ep + 1)\n else\n (n, 0)\n\nipow :: Int64 -> Int64 -> Int64\nipow n e = if e == 0 then 1 else n * (ipow n $ e - 1)", "positive_code": [{"source_code": "import Control.Monad\nimport Text.Printf\n\nnext_div :: Integer -> Integer -> Maybe Integer\nnext_div n t\n | t * t >= n = Nothing\n | (/=0) $ n `mod` t = next_div n $ t + 1\n | otherwise = Just t\n\nthree_divsor :: Integer -> Maybe (Integer, Integer, Integer)\nthree_divsor n = do\n a <- next_div n 2\n b <- next_div (n `div` a) (a + 1)\n let r = n `div` (a * b)\n c <- if (r==a || r==b) then Nothing else Just r\n return (a, b, c)\n\none :: Maybe (Integer, Integer, Integer) -> Integer\none (Just (a, b, c)) = a\n\nmain = do\n i <- getLine\n let t = read i :: Integer\n forM_ [1..t] $ \\ _ -> do\n ii <- getLine\n let n = read ii :: Integer\n let ret = three_divsor n\n case ret of\n Just (a,b,c) -> printf \"YES\\n%v %v %v\\n\" a b c\n Nothing -> printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\n\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn(s)\n\nmain_ :: EIO ()\nmain_ = do \n t <- get :: EIO Int\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get :: EIO Int64\n case f2 n of\n Just (a, b, c) -> do\n putsln \"YES\"\n putsln $ (show a) ++ \" \" ++ (show b) ++ \" \" ++ (show c)\n Nothing -> putsln \"NO\"\n\nf2 :: Int64 -> Maybe (Int64, Int64, Int64)\nf2 x = let ls = f3 x in\n case ls of\n [] -> Nothing\n (a, ae) : [] -> if ae < 6 then\n Nothing\n else\n Just (a, ipow a 2, ipow a $ ae - 3)\n (a, ae) : (b, be) : [] -> if ae == 1 && be == 1 then\n Nothing\n else\n Just (a, b, (ipow a $ ae - 1) * (ipow b $ be - 1))\n (a, _) : (b, _): _ -> Just (a, b, div x $ a * b)\n\nf3 :: Int64 -> [(Int64, Int64)]\nf3 n = f4 n 2 $ sqrt $ fromIntegral n\n\nf4 :: Int64 -> Int64 -> Double -> [(Int64, Int64)]\nf4 n x d = if (fromIntegral x) > d then\n if n /= 1 then\n [(n, 1)]\n else\n []\n else if mod n x == 0 then\n let (np, ep) = divrec n x in\n (x, ep) : f4 np (x + 1) d\n else\n f4 n (x + 1) d\n\ndivrec :: Int64 -> Int64 -> (Int64, Int64)\ndivrec n x = if mod n x == 0 then\n let (np, ep) = divrec (div n x) x in\n (np, ep + 1)\n else\n (n, 0)\n\nipow :: Int64 -> Int64 -> Int64\nipow n e = if e == 0 then 1 else n * (ipow n $ e - 1)"}, {"source_code": "import Control.Monad\nimport Text.Printf\n\nnext_div :: Integer -> Integer -> Maybe Integer\nnext_div n t\n | t >= n = Nothing\n | (/=0) $ n `mod` t = next_div n $ t + 1\n | otherwise = Just t\n\nthree_divsor :: Integer -> Maybe (Integer, Integer, Integer)\nthree_divsor n = do\n a <- next_div n 2\n b <- next_div (n `div` a) (a + 1)\n let r = n `div` (a * b)\n c <- if (==b) r then Nothing else Just r\n return (a, b, c)\n\none :: Maybe (Integer, Integer, Integer) -> Integer\none (Just (a, b, c)) = a\n\nmain = do\n i <- getLine\n let t = read i :: Integer\n forM_ [1..t] $ \\ _ -> do\n ii <- getLine\n let n = read ii :: Integer\n let ret = three_divsor n\n case ret of\n Just (a,b,c) -> printf \"YES\\n%v %v %v\\n\" a b c\n Nothing -> printf \"NO\\n\"\n"}], "src_uid": "0f7ceecdffe11f45d0c1d618ef3c6469"} {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\n\nmain = do \n n:m:_ <- (map $ maybe undefined fst . B.readInt) . B.words <$> B.getLine\n ps <- replicateM n B.getLine\n es <- replicateM m B.getLine\n putStr $ let i = length $ ps `intersect` es in if n - i `div` 2 > m - (i + 1) `div` 2 then \"YES\" else \"NO\"\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nrunGame xs ys = \n lx - ly + xbonus > 0\n where \n common = length $ getCommon (sort xs) (sort ys)\n lx = (length xs) - common\n ly = (length ys) - common\n xbonus = if common `mod` 2 == 0 then 0 else 1\n \ngetLines n = replicateM n getLine\n\n\n\ngetCommon xs'@(x:xs) ys'@(y:ys) = if x == y then x : getCommon xs ys\n else getCommon ( skipWhile ( < x ) ys' ) xs'\ngetCommon _ _ = []\n\n\nskipWhile _ [] = []\nskipWhile p xs'@(x:xs) = if p x then skipWhile p xs\n else xs'\n\n \n\n \nmain =\n do\n line1 <- getLine\n let numbers = map read . words $ line1\n let n = numbers !! 0\n let m = numbers !! 1\n selfWords <- getLines n\n enemyWords <- getLines m\n \n putStrLn $\n if runGame selfWords enemyWords\n then \"YES\"\n else \"NO\""}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\n\nrunGame xs ys = \n lx - ly + xbonus > 0\n where \n common = length $ getCommon (sort xs) (sort ys)\n lx = (length xs) - common\n ly = (length ys) - common\n xbonus = if common `mod` 2 == 0 then 0 else 1\n \ngetLines n = replicateM n getLine\n\n\n\ngetCommon (x:xs) (y:ys) = if x == y then x : getCommon xs ys\n else getCommon ( skipWhile (\\ k -> k < x ) ys ) xs\ngetCommon _ _ = []\n\n\nskipWhile _ [] = []\nskipWhile p xs'@(x:xs) = if p x then skipWhile p xs\n else xs'\n\nmain =\n do\n line1 <- getLine\n let numbers = map read . words $ line1\n let n = numbers !! 0\n let m = numbers !! 1\n selfWords <- getLines n\n enemyWords <- getLines m\n \n putStrLn $\n if runGame selfWords enemyWords\n then \"YES\"\n else \"NO\""}, {"source_code": "import Data.List\nimport Control.Monad\n\nrunGame xs ys = \n lx - ly + xbonus > 0\n where \n common = length . takeWhile (\\(x,y)-> x == y) $ zip (sort xs) (sort ys)\n lx = (length xs) - common\n ly = (length ys) - common\n xbonus = if common `mod` 2 == 0 then 0 else 1\n \ngetLines n = replicateM n getLine\n\nmain =\n do\n line1 <- getLine\n let numbers = map read . words $ line1\n let n = numbers !! 0\n let m = numbers !! 1\n selfWords <- getLines n\n enemyWords <- getLines m\n \n putStrLn $\n if runGame selfWords enemyWords\n then \"YES\"\n else \"NO\""}], "src_uid": "4b352854008a9378551db60b76d33cfa"} {"source_code": "import Char\nmain = interact solve\nsolve input = output where\n inputs = map toL $ lines input\n strings = take 3 inputs\n answers = drop 4 inputs\n output = unlines $ solve0 strings answers\ntoL [] = []\ntoL (x:xs) = (if x=='-' || x==';' || x=='_' then [] else [toLower x]) ++ (toL xs)\nsolve0 _ [] = []\nsolve0 [a,b,c] (x:xs) = y:(solve0 [a,b,c] xs) where\n y\n | x==a++b++c = \"ACC\"\n | x==a++c++b = \"ACC\"\n | x==b++a++c = \"ACC\"\n | x==b++c++a = \"ACC\"\n | x==c++a++b = \"ACC\"\n | x==c++b++a = \"ACC\"\n | otherwise = \"WA\"\n\n", "positive_code": [{"source_code": "import Data.Char\nimport Data.List\n\nparse l = \n case lines l of\n (a:b:c:_:s) -> (clear a, clear b, clear c,map clear s)\n\nclear l = [toLower x | x <- l, not (x `elem` \";_-\")]\n \nsolve (a,b,c,s) = map mapper s\n where \n mapper foo = \n if foo `elem` bar \n then \"ACC\"\n else \"WA\"\n bar = [concat p | p <- permutations [a,b,c]]\n\nmain = do\n foo <- getContents\n putStrLn .unlines . solve . parse $ foo"}, {"source_code": "import Data.List\nimport Data.Char\n\nperm [] = [[]]\nperm xs = [x:ps | x <- xs, ps <- perm (xs\\\\[x])]\n\nformat = map toLower . (filter $ not . (`elem` \";-_\"))\n\nmain = interact f\nf = unlines . (\\x -> map (test (map concat $ perm $ take 3 x)) (drop 4 x)) . lines . format\n\ntest :: [String] -> String -> String\ntest dict s = if elem s dict then \"ACC\" else \"WA\""}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\nimport Data.List\n\nnormalize = map toLower . filter isAlpha\n\nmain = do\n inits <- replicateM 3 $ getLine >>= return . normalize\n let answers = map ( foldl' (++) [] ) $ permutations inits\n\n n <- read `liftM` getLine\n replicateM_ n $ do\n res <- getLine >>= return . ( `elem` answers ) . normalize\n if res\n then putStrLn \"ACC\"\n else putStrLn \"WA\"\n"}, {"source_code": "import Data.Char (toLower)\nimport Data.List (permutations)\n\nclear = map toLower . filter (not . (flip elem $ \";_-\"))\n\ncheck x y\n | y `elem` p = \"ACC\"\n | otherwise = \"WA\"\n where p = [clear $ concat z | z <- permutations x]\n\nmain = interact solve\n where solve x = unlines [check (take 3 $ lines x) z | z <- [clear y | y <- drop 4 $ lines x]]\n"}, {"source_code": "import Data.Char\nimport Data.List\n\neasy [] = []\neasy (x:xs)\n\t| elem x \"-_;\" = easy xs\n\t| otherwise = toLower x : easy xs\n\npermutation [] = [[]]\npermutation xs = concat [map (x:) $ permutation (delete x xs) | x <- xs]\n\nsolve [] _ = \"ACC\"\nsolve as b = if elem b ass then \"ACC\" else \"WA\"\n\twhere\n\t\tass = map concat $ permutation as\n\ngetLines 0 = return []\ngetLines n = do x <- getLine; xs <- getLines (n-1); return (x:xs)\n\nputStrLns [] = return ()\nputStrLns (x:xs) = do putStrLn x; putStrLns xs\n\nmain = do\n\ts <- getLines 3 >>= return . map easy\n\tn <- getLine >>= return . read\n\tvals <- getLines n >>= return . map easy\n\tlet ans = map (solve s) vals\n\tputStrLns ans\n"}, {"source_code": "\nimport Char (toUpper)\nimport Control.Monad (replicateM)\nimport Data.List (permutations)\n\nmyFilterAndUpperCase :: String -> String\nmyFilterAndUpperCase = map toUpper . filter (flip notElem \"-;_\")\n\nsolve :: [String] -> String -> String\nsolve permutations' s\n | elem s permutations' = \"ACC\"\n | otherwise = \"WA\"\n\nmain :: IO ()\nmain = do\n s1 <- fmap myFilterAndUpperCase getLine\n s2 <- fmap myFilterAndUpperCase getLine\n s3 <- fmap myFilterAndUpperCase getLine\n n <- readLn\n xs <- replicateM n (fmap myFilterAndUpperCase getLine)\n let permutations' = map concat $ permutations [s1, s2, s3]\n mapM_ (putStrLn . solve permutations') xs\n"}, {"source_code": "import Data.Char\nperm = [[0,1,2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\nmain = do\n l <- mapM (\\_ -> (filter isAlpha . map toUpper) `fmap` getLine) [1..3]\n n <- read `fmap` getLine\n let test = map (\\l1 -> concat $ map (\\i -> l!!i) l1) perm\n mapM_ (\\_ -> do\n s <- (filter isAlpha .map toUpper) `fmap` getLine\n putStrLn (if s `elem` test then \"ACC\" else \"WA\")) [1..n]\n \n"}, {"source_code": "import Data.Char\n\nsimp word = map toUpper $ filter (/='_') $ filter (/='-') $ filter (/=';') word\n\ncheck3 w1 w2 w3 answer =\n any (==answer) [w1++w2++w3, w1++w3++w2, w2++w1++w3, w2++w3++w1, w3++w1++w2, w3++w2++w1]\n\ncheck word1 word2 word3 answer = if check3 (simp word1) (simp word2) (simp word3) (simp answer)\n then \"ACC\"\n else \"WA\"\n\nprocessLines 0 word1 word2 word3= \n do\n putStrLn(\"\")\n\nprocessLines 1 word1 word2 word3= \n do\n answer<-getLine\n putStrLn(check word1 word2 word3 answer)\n\nprocessLines n word1 word2 word3= \n do\n answer<-getLine\n putStrLn(check word1 word2 word3 answer)\n processLines (n-1) word1 word2 word3\n\nmain = \n do\n word1 <- getLine\n word2 <- getLine\n word3 <- getLine\n n <- getLine\n processLines (read n::Int) word1 word2 word3\n\n\n"}], "negative_code": [{"source_code": "import Data.Char (toLower)\nimport Data.List (sort)\n\nremoveSigns :: String -> String\nremoveSigns [] = []\nremoveSigns (x:xs)\n | isSign x = removeSigns xs\n | otherwise = x : removeSigns xs\n where isSign x = x == ';' || x == '-' || x == '_'\n\ncheck :: String -> String -> Bool\ncheck a b = task == answer where task = sort $ map toLower $ removeSigns a\n answer = sort $ map toLower $ removeSigns b\n\nrun :: String -> Int -> IO Bool\nrun task num\n | num == 0 = return True\n | otherwise = getLine >>= return . check task >>= \\ans -> putStrLn (if ans then \"ACC\" else \"WA\") >> run task (num-1)\n\nmain = do\n a <- getLine\n b <- getLine\n c <- getLine\n num <- getLine\n run (a ++ b ++ c) (read num)\n"}, {"source_code": "import Data.Char (toLower)\nimport Data.List (sort)\n\nremoveSigns :: String -> String\nremoveSigns [] = []\nremoveSigns (x:xs)\n | isSign x = removeSigns xs\n | otherwise = x : removeSigns xs\n where isSign x = x == ';' || x == '-' || x == '_'\n\ncheck :: String -> String -> Bool\ncheck a b = task == answer where task = sort $ map toLower $ a\n answer = sort $ map toLower $ removeSigns b\n\nrun :: String -> Int -> IO Bool\nrun task num\n | num == 0 = return True\n | otherwise = getLine >>= return . check task >>= \\ans -> putStrLn (if ans then \"ACC\" else \"WA\") >> run task (num-1)\n\nmain = do\n a <- getLine\n b <- getLine\n c <- getLine\n num <- getLine\n run (removeSigns a ++ removeSigns b ++ removeSigns c) (read num)\n"}], "src_uid": "95ccc87fe9e431f9c6eeffeaf049f797"} {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (\\(x,y) -> unwords [show x, show y]) >>> unlines\n\nprocess :: [[Int]] -> [(Int, Int)]\nprocess [] = []\nprocess ([n,k]:a:ps) = solve n k a : process ps\n\nsolve n k a = \n let p = peaks a in\n let del = sum (take (k - 2) p) \n : zipWith (-) (drop (k - 2) p) p in\n let fin = zip (scanl1 (+) del) [-1,-2..] in \n let (t, l) = foldl1 max fin in (t + 1, -l)\n\npeaks :: [Int] -> [Int]\npeaks [_,_] = []\npeaks (x:x':x'':xs) = \n (if x' > (max x x'') then 1 else 0) \n : peaks (x':x'':xs)", "positive_code": [{"source_code": "\nparse :: String -> [Int]\nparse = map read . words\n\n\ngetPeaks :: [Int] -> [Int]\ngetPeaks (a:b:c:ls)\n | b > a && b > c = 1 : getPeaks (b:c:ls)\n | otherwise = 0 : getPeaks (b:c:ls)\ngetPeaks _ = []\nprefixSum :: [Int] -> [Int]\nprefixSum ls = 0 : helper 0 ls\n where\n helper aux [] = []\n helper aux (l:ls) = (aux+l) : helper (aux+l) ls\n\nnegateSnd :: (Int, Int) -> (Int, Int)\nnegateSnd (a,b) = (a, negate b)\n\ngetMax :: [Int] -> (Int, Int)\ngetMax ls = negateSnd $ maximum $ zip ls [(-1),(-2)..]\n\nsolveTestCases :: Int -> IO ()\nsolveTestCases 0 = return ()\nsolveTestCases t = do\n nk <- getLine\n aLine <- getLine\n let\n (n:k:_) = parse nk\n as = parse aLine\n peaks = getPeaks as\n prefixSumList = prefixSum peaks\n nPeaks = zipWith (-) (drop (k-2) prefixSumList) prefixSumList\n (mVal, mInd) = getMax nPeaks\n putStrLn $ show (mVal+1) ++ \" \" ++ show mInd\n solveTestCases (t-1)\n\n\n\nmain :: IO ()\nmain = do\n t <- getLine\n solveTestCases $ read t"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [_,k] <- (map read.words) <$> getLine\n as <- (map read.words) <$> getLine\n putStrLn $ solve k as\n\nsolve :: Int -> [Int] -> String\nsolve k as = (unwords.map show) [b+1,a]\n where\n (a,b) = (toMax.(toScores (k-2)).toAscending.toPeaks) as\n\ntoPeaks :: [Int] -> [Int]\ntoPeaks as = map f triples\n where\n triples = zip3 as (tail as) (tail $ tail as)\n f = \\(x,y,z) -> fromEnum (xz)\n\ntoAscending :: [Int] -> [Int]\ntoAscending peaks=scanl (+) 0 peaks\n\ntoScores ::Int -> [Int] -> [Int]\ntoScores k asc = zipWith (-) (drop k asc) asc\n\ntoMax :: [Int] -> (Int,Int)\ntoMax scores = (maximumBy myCompare) $ zip [1..] scores\n where\n myCompare (_,x) (_,y) = case compare x y of\n LT -> LT\n EQ -> GT\n GT -> GT\n"}], "negative_code": [], "src_uid": "8e182e0acb621c86901fb94b56ff991e"} {"source_code": "import Data.List \n\nfactors n = go n 2 \n where \n go n i \n | i * i > n = if n > 1 then [n] else []\n | otherwise = case n `mod` i of\n 0 -> i : go (head $ dropWhile (\\k -> k `mod` i == 0) (iterate (`div` i) n)) (i + 1)\n _ -> go n (i + 1)\n\n\nsolve xs = maximum . (1:) . map length . group . sort $ xs >>= factors \n\nmain = getLine >> getLine >>= \\line -> print . solve $ map read (words line)", "positive_code": [{"source_code": "import qualified Data.Map as Map\nimport Control.Exception (assert)\nimport Data.List\n-- import Debug.Trace as Trace\n-- trace' x = Trace.traceShow x x\n\nsolve :: [Int] -> Int\nsolve xs = maximum . (1:) $ Map.elems $ Map.fromListWith (+) (zip fs (repeat 1))\n where \n fs = concatMap uniqueFactors xs\n\nuniqueFactors :: Int -> [Int]\nuniqueFactors 1 = []\nuniqueFactors x = nub $ helper x 2 where\n helper r p \n | p * p > r = [r]\n | mod r p == 0 = p : helper (div r p) p\n | otherwise = helper r (p + 1)\n\nmain = do\n _ <- getLine\n xs <- return . map read . words =<< getLine\n print $ solve xs\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Control.Monad\nmain = interact $ show . solve . map read . tail . words\nsolve = maximum . accumArray (+) 0 (1,10^5) . flip zip (repeat 1) . (1 :) . concatMap factor\n\nfactor n = go n primes where\n go 1 _ = []\n go n (p:ps) | l > 0 = p : go (n `div` p^l) ps\n | otherwise = go n ps where\n ts = unfoldr (mfilter ((== 0) . fst) . pure . uncurry (flip (,)) . (`divMod` p)) n\n l = length ts\n go n [] = [n]\n\nprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317]\n"}], "negative_code": [{"source_code": "import qualified Data.Map as Map\nimport Control.Exception (assert)\nimport Data.List\n-- import Debug.Trace as Trace\n-- trace' x = Trace.traceShow x x\n\nsolve :: [Int] -> Int\nsolve xs = maximum $ Map.elems $ Map.fromListWith (+) (zip fs (repeat 1))\n where \n fs = concatMap uniqueFactors xs\n\nuniqueFactors :: Int -> [Int]\nuniqueFactors x = nub $ helper x 2 where\n helper r p \n | p * p > r = [r]\n | mod r p == 0 = p : helper (div r p) p\n | otherwise = helper r (p + 1)\n\nmain = do\n _ <- getLine\n xs <- return . map read . words =<< getLine\n print $ solve xs\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Control.Monad\nmain = interact $ show . solve . map read . tail . words\nsolve = maximum . accumArray (+) 0 (1,10^5) . flip zip (repeat 1) . concatMap factor\n\nfactor n = go n primes where\n go 1 _ = []\n go n (p:ps) | l > 0 = p : go (n `div` p^l) ps\n | otherwise = go n ps where\n ts = unfoldr (mfilter ((== 0) . fst) . pure . uncurry (flip (,)) . (`divMod` p)) n\n l = length ts\n go n [] = [n]\n\nprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317]\n"}], "src_uid": "eea7860e6bbbe5f399b9123ebd663e3e"} {"source_code": "import Data.List\nimport Control.Monad\nmain = do\n getLine -- n\n ts <- fmap (zip [1..] . map read . words) getLine\n let (t1,ts') = partition ((== 1) . snd) ts\n (t2,t3) = partition ((== 2) . snd) ts'\n ws = zip3 t1 t2 t3\n print (length ws)\n forM_ ws $ \\((i,_),(j,_),(k,_)) -> putStrLn $ unwords $ map show [i,j,k]\n", "positive_code": [{"source_code": "main = do\n getLine\n ts <- fmap (map read . words) getLine\n\n let\n t1 = map snd $ filter (\\x -> fst x == 1) $ zip ts [1..]\n t2 = map snd $ filter (\\x -> fst x == 2) $ zip ts [1..]\n t3 = map snd $ filter (\\x -> fst x == 3) $ zip ts [1..]\n\n r = zip3 t1 t2 t3\n\n print $ length r\n putStrLn $ unlines $ map (\\(a, b, c) -> show a ++ \" \" ++ show b ++ \" \" ++ show c) r\n"}, {"source_code": "filter_by_value b v = map snd $ filter (\\(x,_) -> x == v) b \n\nout a = len_str : (foldr (:) [] a)\n where len_str = show $ length a\n\nsolve a = map (unwords . map show . (\\(i,(j,k)) -> [i,j,k])) c\n where b = zip a [1..]\n c = zip (filter_by_value b 1) $ zip (filter_by_value b 2) (filter_by_value b 3)\n\nmain = interact $ unlines . out . solve . map read . words . (!!1) . lines\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint =getLine >> (solve =<< map (fst.fromJust.C.readInt).C.words<$>C.getLine)\n--solve::Int->IO()\nsolve xs = let ys = slv2 $ slv1 $ zip [1..] xs; l=length ys in print l >> mapM_ (putStrLn.unwords.(map show)) ys \nslv1 ts = foldr (\\(a1,a2) [bs1,bs2,bs3] -> if a2==1 then [a1:bs1,bs2,bs3] else if a2==2 then [bs1,a1:bs2,bs3] else [bs1,bs2,a1:bs3]) [[],[],[]] ts \nslv2 [xs1,xs2,xs3]=zipWith (\\a b->a:b) xs1 $ zipWith (\\a b->a:b:[]) xs2 xs3"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n _ <- getLine\n ts <- words <$> getLine\n let ws = reverse (sol ts)\n print $ length ws\n mapM_ putStrLn ws\n\nsol :: [String] -> [String]\nsol ts = zipWith3 str ps ms es\n where\n str p m e = p ++ \" \" ++ m ++ \" \" ++ e\n (ps, ms, es, n) = foldr step ([], [], [], 1) (reverse ts)\n step t (ps, ms, es, i) = case t of\n \"1\" -> (show i:ps, ms, es, i+1)\n \"2\" -> (ps, show i:ms, es, i+1)\n \"3\" -> (ps, ms, show i:es, i+1)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\n\n\nprocess::[Integer]->IO ()\nprocess q = do\n print y\n (mapM_ (\\z->putStrLn $ intercalate \" \" $ map show z) xx) \n where x = map (map snd) $ groupBy (\\z1 z2 -> fst z1==fst z2) $ sort $ zip q [1..]\n y | length x ==3 = minimum $ map length x\n | otherwise = 0\n xx = transpose $ map (take y) x\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map read <$> words <$> getLine::IO [Integer]\n process q\n"}, {"source_code": "import Data.List (elemIndex, unfoldr)\n\nmain :: IO ()\nmain = getContents >>= mapM_ (putStrLn . unwords . map show) . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> [[Int]]\nsolve ts = [length xs] : xs\n where xs = unfoldr f ts\n f as = case (elemIndex 1 as, elemIndex 2 as, elemIndex 3 as) of\n (Just i1, Just i2, Just i3) -> Just ([ i1 + 1, i2 + 1, i3 + 1 ], zipWith g [0..] as)\n where g i a | i `elem` [ i1, i2, i3 ] = 0 | otherwise = a\n _ -> Nothing\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess::[[Int]]->IO ()\nprocess [[], _, _] = return ()\nprocess [_ ,[], _] = return ()\nprocess [_, _ ,[]] = return ()\nprocess [(x:xs), (y:ys), (z:zs)] = do\n\t\t\t\t\tputStrLn (show x++\" \"++show y++ \" \"++ show z)\n\t\t\t\t\tprocess [xs, ys, zs] \n\nmain=do\n\t\n\tc<- read <$> getLine::IO Int\n\ta<-map read.words <$> getLine::IO [Int]\n\tlet r1= groupBy (\\a b -> fst a ==fst b) ( sort ( zip a [1..]) )\n\tlet r = map (map snd) r1\n\tlet rlen = minimum ( map length r)\n\tif length r <3 then print 0 else print rlen\n\tif (length r==3) then (process r ) else return ()\n\t "}, {"source_code": "process :: [Int] -> [(Int,Int,Int)]\nprocess ts = zip3 xs ys zs\n where\n (xs,ys,zs) = f $ zip [1..] ts\n f [] = ([],[],[])\n f ((i,t):ps)\n | t == 1 = ((i:xs),ys,zs)\n | t == 2 = (xs,(i:ys),zs)\n | t == 3 = (xs,ys,(i:zs))\n where\n (xs,ys,zs) = f ps\n\nreadInt :: String -> Int\nreadInt = read\n\nprintTriple :: (Int,Int,Int) -> IO ()\nprintTriple (x,y,z) = putStrLn.unwords.map show $ [x,y,z]\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n ts <- fmap (map readInt.words) getLine\n let xs = process ts\n print $ length xs\n mapM_ printTriple xs"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain :: IO ()\nmain = interact solve\n\nsolve :: String -> String\nsolve s = unlines $ show (length teams) : fmap (unwords . fmap show) teams\n where (_:xs) = read <$> words s :: [Int]\n arr = sequence (select <$> [1..3]) (zip xs [1::Int ..]) :: [[Int]]\n teams = takeWhile ((==3).length) (transpose arr) ::[[Int]]\n\nselect :: (Eq a) => a -> [(a, b)] -> [b]\nselect key = fmap snd . filter ((==key).fst)"}, {"source_code": "main :: IO()\nmain = output . solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> [(Int, Int, Int)]\nsolve a = solve' a a a 1 1 1\n\nsolve' :: [Int] -> [Int] -> [Int] -> Int -> Int -> Int -> [(Int, Int, Int)]\nsolve' [] _ _ _ _ _ = []\nsolve' _ [] _ _ _ _ = []\nsolve' _ _ [] _ _ _ = []\nsolve' (a:ax) (b:bx) (c:cx) ia ib ic | a /= 1 = solve' ax (b:bx) (c:cx) (ia + 1) ib ic\n | b /= 2 = solve' (a:ax) bx (c:cx) ia (ib + 1) ic\n | c /= 3 = solve' (a:ax) (b:bx) cx ia ib (ic + 1)\n | otherwise = (ia, ib, ic) : (solve' ax bx cx (ia + 1) (ib + 1) (ic + 1))\n\noutput :: [(Int, Int, Int)] -> IO()\noutput ans = do\n print (length ans)\n output' ans\n \noutput' :: [(Int, Int, Int)] -> IO()\noutput' [] = putStrLn \"\"\noutput' ((a, b, c):x) = do\n putStrLn (unwords (map show [a, b, c]))\n output' x\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\n\n\n\nprocess::[Integer]->IO ()\nprocess q = do\n print y\n mapM_ (\\z->putStrLn $ intercalate \" \" $ map show z) xx\n where x = map (map snd) $ groupBy (\\z1 z2 -> fst z1==fst z2) $ sort $ zip q [1..]\n y = minimum $ map length x\n xx = transpose $ map (take y) x\n\nmain=do\n n<- read <$> getLine::IO Integer\n q<- map read <$> words <$> getLine::IO [Integer]\n process q\n"}], "src_uid": "c014861f27edf35990cc065399697b10"} {"source_code": "{-# LANGUAGE BangPatterns, ViewPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Control.Applicative\n\nreadInt64 bs = case B.readInt bs of Just (n,_) -> fromIntegral n\n\nmain = do\n n <- readLn\n (toVec2s->tas,toVec2s.tail->bs) <- splitAt (2*n).map readInt64.B.words <$> B.getContents\n let as = ys ++ xs\n where\n-- mina = minimum tas\n (xs,ys) = break (minimum tas==) tas\n if as == grahamScan (as++bs)\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\ngrahamScan ps = case go [v1,v0] vs of xs -> v0:init xs\n where\n v0 = minimum ps\n v1:vs = sortBy (compCCW v0) $ delete v0 ps\n go (p:q:conv) (r:rs) = case compare 0 $ (p-q)`cross`(r-q) of\n LT -> go (r:p:q:conv) rs\n GT -> go (q:conv) (r:rs)\n EQ | dist2 p q < dist2 r q -> go (r:p:q:conv) (rs)\n | otherwise -> go (p:r:q:conv) rs\n go [p] (r:rs) = go [r,p] rs\n go conv [] = conv\n\ntype Point = Vec2\n\ndata Vec2 = V2 {\n px :: {-# UNPACK #-} !Int64,\n py :: {-# UNPACK #-} !Int64} deriving (Eq,Ord)\n\ninstance Num Vec2 where\n (V2 x0 y0)+(V2 x1 y1) = V2 (x0+x1) (y0+y1)\n (V2 x0 y0)-(V2 x1 y1) = V2 (x0-x1) (y0-y1)\n (V2 x0 y0)*(V2 x1 y1) = V2 (x0*x1-y0*y1) (x0*y1+x1*y0)\n negate (V2 x y) = V2 (negate x) (negate y)\n abs (V2 x y) = undefined\n signum (V2 x y) = undefined\n fromInteger n = V2 (fromInteger n) 0\n\ninstance Show Vec2 where\n show (V2 x y) = concat [\"(\",show x,\",\",show y,\")\"]\n\ncross :: Vec2 -> Vec2 -> Int64\ncross (V2 x0 y0) (V2 x1 y1) = x0*y1 - y0*x1\n\nnorm2 :: Vec2 -> Int64\nnorm2 (V2 x y) = x*x + y*y\n\ndist2 :: Point -> Point -> Int64\ndist2 u v = norm2 $ u-v\n\ncompCCW :: Point -> Point -> Point -> Ordering\ncompCCW o u v = compare 0 $ (u-o)`cross`(v-o)\n\ntoVec2s :: [Int64] -> [Vec2]\ntoVec2s (x:y:xys) = (V2 x y):toVec2s xys\ntoVec2s _ = []\n", "positive_code": [{"source_code": "\nimport Data.Char\nimport Data.List\ntype Pt = (Integer, Integer)\n\ndata Tree = Split Tree Pt Tree | Segment deriving Eq\ntype Conv = (Pt, Tree, Pt)\ntype Seg = (Pt, Pt)\n\n\ndata Dir = L | In | Out | R deriving (Show, Eq)\ncross :: Pt -> Pt -> Integer\ncross (x1, y1) (x2, y2) = x1 * y2 - x2 * y1\n\ndot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2\n\ndiffV (x1, y1) (x2, y2) = (x2-x1, y2-y1)\n\ndir :: Pt -> Seg -> Dir\ndir p (a, b)\n | c < 0 = L \n | c > 0 = R\n | d1 > 0 && d2 > 0 = In\n | otherwise = Out where\n c = cross (diffV b a) (diffV p a)\n d1 = dot (diffV b a) (diffV p a)\n d2 = dot (diffV a b) (diffV p b)\n\ninside' :: Pt -> Conv -> Bool\ninside' p (l, Segment, r) = False\ninside' p (l, Split lt s rt, r) = case (dir p (l, s), dir p (r, s)) of\n (R, L) -> True\n (L, R) -> False\n (Out, _) -> False\n (_, Out) -> False\n (In, L) -> lt /= Segment\n (R, In) -> rt /= Segment\n (L, L) -> inside' p (l, lt, s)\n (R, R) -> inside' p (s, rt, r)\n x -> error $ show x\n\ninside p (l, tr, r) = dir p (l, r) == L && inside' p (l, tr, r)\n\nmyr = foldl (\\s c->s*10+ord c-ord '0') 0\n\nmyread :: String -> Int\nmyread ('-':t) = -myr t\nmyread t = myr t\n\nmkTr :: [Pt] -> Tree\nmkTr [] = Segment\nmkTr pts = Split (mkTr l) s (mkTr r) where\n (l, s : r) = splitAt (length pts `div` 2) pts\n\nmkConv :: [Pt] -> Conv\nmkConv pts = (head pts, mkTr (init $ tail pts), last pts)\n\ns([n]:t)|all (`inside` conv) ps = \"YES\"\n | otherwise = \"NO\" where\n (a,b) = genericSplitAt n t\n conv = mkConv (reverse $ map (\\[a,b]->(a,b)) a)\n ([m]:c) = b\n ps = map (\\[a,b]->(a,b)) c\n\nmain=interact$s.map(map(fromIntegral.myread).words).lines"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nimport Debug.Trace\n\nparseInput = do \n n <- readInt\n a <- replicateM n ((,) <$> readInt64 <*> readInt64)\n m <- readInt\n b <- replicateM m ((,) <$> readInt64 <*> readInt64)\n return (reverse a, b)\n where\n readInt64 = fromIntegral <$> readInt :: State ByteString Int64\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\ndet :: Num a => (a, a) -> (a, a) -> a\ndet (x1, y1) (x2, y2) = x1 * y2 - x2 * y1\n{-# INLINE det #-}\n\ndot :: Num a => (a, a) -> (a, a) -> a\ndot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2\n{-# INLINE dot #-}\n\ndet3 :: Num a => (a, a) -> (a, a) -> (a, a) -> a\ndet3 (x0, y0) (x1, y1) (x2, y2) = det (x1 - x0, y1 - y0) (x2 - x0, y2 - y0)\n{-# INLINE det3 #-}\n\nconvex :: [(Int64, Int64)] -> [(Int64, Int64)]\nconvex pts' = leftToRight pts []\n where\n pts = sort pts'\n\n leftToRight [] stack = rightToLeft (tail $ reverse pts) stack\n leftToRight (p:ps) (a:b:cs)\n | det3 b a p < 0 = leftToRight (p:ps) (b:cs)\n leftToRight (p:ps) st = leftToRight ps (p:st)\n\n rightToLeft [] stack = reverse $ tail stack\n rightToLeft (p:ps) (a:b:cs)\n | det3 b a p < 0 = rightToLeft (p:ps) (b:cs)\n rightToLeft (p:ps) st = rightToLeft ps (p:st)\n\narea :: [(Int64, Int64)] -> Int64\narea (x:xs) = foldl' (+) 0 $ zipWith det (x:xs) (xs++[x])\n\nsolve (a, b)\n | area a == area c && length a == length c = \"YES\"\n | otherwise = \"NO\"\n where\n c = convex (a ++ b)\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Int\n\ndata Point = Point Int64 Int64 deriving (Show)\n\ninstance Read Point where\n\treadsPrec _ s = [(Point x y, [])]\n\t\twhere [x, y] = map read $ words s\n\ndata Vector = Vector Int64 Int64\n\nPoint x1 y1 `vector` Point x2 y2 = Vector (x2 - x1) (y2 - y1)\n\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\n\ninstance Eq Vector where\n\tu == v = u `cross` v == 0\n\ninstance Ord Vector where\n\tu `compare` v = u `cross` v `compare` 0\n\nmain = do\n\tn <- readLn\n\tps <- listArray (1,n) <$> replicateM n readLn\n\n\tm <- readLn\n\tqs <- replicateM m readLn\n\n\tlet\n\t\tisInside p =\n\t\t\t\tvs!2 < v && vs!n > v &&\n\t\t\t\t\tvs!l <= v && vs!(l+1) >= v && \n\t\t\t\t\tps!l `vector` (ps!(l+1)) < ps!l `vector` p\n\t\t\twhere\n\t\t\t\tv = ps!1 `vector` p\n\t\t\t\tvs = (ps!1 `vector`) <$> ps\n\n\t\t\t\tfind l r\n\t\t\t\t\t| l >= r = (l, r)\n\t\t\t\t\t| vs!m <= v = find m r\n\t\t\t\t\t| otherwise = find l (m-1)\n\t\t\t\t\twhere m = (l+r+1) `div` 2\n\t\t\t\t(l, r) = find 1 (n-1)\n\n\tputStrLn $ if all isInside qs then \"YES\" else \"NO\"\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Int\n\ndata Point = Point Int64 Int64 deriving (Show)\n\ninstance Read Point where\n\treadsPrec _ s = [(Point x y, [])]\n\t\twhere [x, y] = map read $ words s\n\ndata Vector = Vector Int64 Int64\n\nPoint x1 y1 `vector` Point x2 y2 = Vector (x2 - x1) (y2 - y1)\n\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\n\ninstance Eq Vector where\n\tu == v = u `cross` v == 0\n\ninstance Ord Vector where\n\tu `compare` v = u `cross` v `compare` 0\n\nmain = do\n\tn <- readLn\n\tps <- listArray (1,n) <$> replicateM n readLn\n\n\tm <- readLn\n\tqs <- replicateM m readLn\n\n\tlet\n\t\tisInside p =\n\t\t\t\tvs!2 < v && vs!n > v &&\n\t\t\t\t\tvs!l <= v && vs!(l+1) >= v && \n\t\t\t\t\tps!l `vector` (ps!(l+1)) < ps!l `vector` p\n\t\t\twhere\n\t\t\t\tv = ps!1 `vector` p\n\t\t\t\tvs = (ps!1 `vector`) <$> ps\n\n\t\t\t\tfind l r\n\t\t\t\t\t| l >= r = (l, r)\n\t\t\t\t\t| vs!m <= v = find m r\n\t\t\t\t\t| otherwise = find l (m-1)\n\t\t\t\t\twhere m = (l+r+1) `div` 2\n\t\t\t\t(l, r) = find 1 (n-1)\n\n\tputStrLn $ if and $ map isInside qs then \"YES\" else \"NO\"\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n\ndata Point = Point Int Int deriving (Show)\n\ninstance Read Point where\n\treadsPrec _ s = [(Point x y, [])]\n\t\twhere [x, y] = map read $ words s\n\ndata Vector = Vector Int Int\n\nPoint x1 y1 `vector` Point x2 y2 = Vector (x2 - x1) (y2 - y1)\n\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\n\ninstance Eq Vector where\n\tu == v = u `cross` v == 0\n\ninstance Ord Vector where\n\tu `compare` v = u `cross` v `compare` 0\n\nmain = do\n\tn <- readLn\n\tps <- listArray (1,n) <$> replicateM n readLn\n\n\tm <- readLn\n\tqs <- replicateM m readLn\n\n\tlet\n\t\tisInside p =\n\t\t\t\tvs!2 < v && vs!n > v &&\n\t\t\t\t\tvs!l <= v && vs!(l+1) >= v && \n\t\t\t\t\tps!l `vector` (ps!(l+1)) < ps!l `vector` p\n\t\t\twhere\n\t\t\t\tv = ps!1 `vector` p\n\t\t\t\tvs = (ps!1 `vector`) <$> ps\n\n\t\t\t\tfind l r\n\t\t\t\t\t| l >= r = (l, r)\n\t\t\t\t\t| vs!m <= v = find m r\n\t\t\t\t\t| otherwise = find l (m-1)\n\t\t\t\t\twhere m = (l+r+1) `div` 2\n\t\t\t\t(l, r) = find 1 (n-1)\n\n\tputStrLn $ if and $ map isInside qs then \"YES\" else \"NO\"\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Array\n\ndata Point = Point Int Int deriving (Show)\n\ninstance Read Point where\n\treadsPrec _ s = [(Point x y, [])]\n\t\twhere [x, y] = map read $ words s\n\ndata Vector = Vector Int Int\n\nPoint x1 y1 `vector` Point x2 y2 = Vector (x2 - x1) (y2 - y1)\n\nVector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1\n\ninstance Eq Vector where\n\tu == v = u `cross` v == 0\n\ninstance Ord Vector where\n\tu `compare` v = u `cross` v `compare` 0\n\nmain = do\n\tn <- readLn\n\tps <- listArray (1,n) <$> replicateM n readLn\n\n\tm <- readLn\n\tqs <- replicateM m readLn\n\n\tlet\n\t\tisInside p =\n\t\t\t\tvs!2 < v && vs!n > v &&\n\t\t\t\t\tvs!l <= v && vs!(l+1) >= v && \n\t\t\t\t\t(ps!l) `vector` (ps!(l+1)) < (ps!l) `vector` p\n\t\t\twhere\n\t\t\t\tv = ps!1 `vector` p\n\t\t\t\tvs = (ps!1 `vector`) <$> ps\n\n\t\t\t\tfind l r\n\t\t\t\t\t| l >= r = (l, r)\n\t\t\t\t\t| vs!m <= v = find m r\n\t\t\t\t\t| otherwise = find l (m-1)\n\t\t\t\t\twhere m = (l+r+1) `div` 2\n\t\t\t\t(l, r) = find 1 (n-2)\n\n\tputStrLn $ if and $ map isInside qs then \"YES\" else \"NO\"\n\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nimport Debug.Trace\n\nparseInput = do \n n <- readInt\n a <- replicateM n ((,) <$> readInt64 <*> readInt64)\n m <- readInt\n b <- replicateM m ((,) <$> readInt64 <*> readInt64)\n return (reverse a, b)\n where\n readInt64 = fromIntegral <$> readInt :: State ByteString Int64\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = BS.putStr =<< solve . evalState parseInput <$> BS.getContents\n\ndet :: Num a => (a, a) -> (a, a) -> a\ndet (x1, y1) (x2, y2) = x1 * y2 - x2 * y1\n{-# INLINE det #-}\n\ndot :: Num a => (a, a) -> (a, a) -> a\ndot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2\n{-# INLINE dot #-}\n\ndet3 :: Num a => (a, a) -> (a, a) -> (a, a) -> a\ndet3 (x0, y0) (x1, y1) (x2, y2) = det (x1 - x0, y1 - y0) (x2 - x0, y2 - y0)\n{-# INLINE det3 #-}\n\nconvex :: [(Int64, Int64)] -> [(Int64, Int64)]\nconvex pts' = leftToRight pts []\n where\n pts = map head $ group $ sort pts'\n\n leftToRight [] stack = rightToLeft (tail $ reverse pts) stack\n leftToRight (p:ps) (a:b:cs)\n | det3 b a p <= 0 = leftToRight (p:ps) (b:cs)\n leftToRight (p:ps) st = leftToRight ps (p:st)\n\n rightToLeft [] stack = reverse $ tail stack\n rightToLeft (p:ps) (a:b:cs)\n | det3 b a p <= 0 = rightToLeft (p:ps) (b:cs)\n rightToLeft (p:ps) st = rightToLeft ps (p:st)\n\narea :: [(Int64, Int64)] -> Int64\narea (x:xs) = foldl' (+) 0 $ zipWith det (x:xs) (xs++[x])\n\nsolve (a, b)\n | area a == area (convex (a ++ b)) = \"YES\"\n | otherwise = \"NO\"\n\n-- {{{ A minimal State Monad\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n-- }}}\n"}, {"source_code": "\nimport Data.Char\nimport Data.List\ntype Pt = (Integer, Integer)\n\ndata Tree = Split Tree Pt Tree | Segment deriving Eq\ntype Conv = (Pt, Tree, Pt)\ntype Seg = (Pt, Pt)\n\n\ndata Dir = L | In | Out | R deriving (Show, Eq)\ncross :: Pt -> Pt -> Integer\ncross (x1, y1) (x2, y2) = x1 * y2 - x2 * y1\n\ndot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2\n\ndiffV (x1, y1) (x2, y2) = (x2-x1, y2-y1)\n\ndir :: Pt -> Seg -> Dir\ndir p (a, b)\n | c < 0 = L \n | c > 0 = R\n | d1 > 0 && d2 > 0 = In\n | otherwise = Out where\n c = cross (diffV b a) (diffV p a)\n d1 = dot (diffV b a) (diffV p a)\n d2 = dot (diffV a b) (diffV p b)\n\ninside' :: Pt -> Conv -> Bool\ninside' p (l, Segment, r) = False\ninside' p (l, Split lt s rt, r) = case (dir p (l, s), dir p (r, s)) of\n (R, L) -> True\n (Out, _) -> False\n (_, Out) -> False\n (In, L) -> lt /= Segment\n (R, In) -> rt /= Segment\n (L, L) -> inside' p (l, lt, s)\n (R, R) -> inside' p (s, rt, r)\n x -> error $ show x\n\ninside p (l, tr, r) = dir p (l, r) == L && inside' p (l, tr, r)\n\nmyr = foldl (\\s c->s*10+ord c-ord '0') 0\n\nmyread :: String -> Int\nmyread ('-':t) = -myr t\nmyread t = myr t\n\nmkTr :: [Pt] -> Tree\nmkTr [] = Segment\nmkTr pts = Split (mkTr l) s (mkTr r) where\n (l, s : r) = splitAt (length pts `div` 2) pts\n\nmkConv :: [Pt] -> Conv\nmkConv pts = (head pts, mkTr (init $ tail pts), last pts)\n\ns([n]:t)|all (`inside` conv) ps = \"YES\"\n | otherwise = \"NO\" where\n (a,b) = genericSplitAt n t\n conv = mkConv (map (\\[a,b]->(a,b)) a)\n ([m]:c) = b\n ps = map (\\[a,b]->(a,b)) c\n\nmain=interact$s.map(map(fromIntegral.myread).words).lines"}], "src_uid": "d9eb0f6f82bd09ea53a1dbbd7242c497"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = readIntegers >>= print . pred . sum", "positive_code": [{"source_code": "import Control.Monad ( replicateM_ )\n\nmain :: IO ()\nmain = do\n t <- getLine >>= return . read\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [a, b, c] <- getLine >>= return . (map read) . words\n print $ a + b + c - e where e = 1"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = readIntegers >>= print . succ . sum"}, {"source_code": "import Control.Monad ( replicateM_ )\n\nmain :: IO ()\nmain = do\n t <- getLine >>= return . read\n replicateM_ t solve\n\nsolve :: IO ()\nsolve = do\n [a, b, c] <- getLine >>= return . (map read) . words\n print $ a + b + c - e where e = 1e-3"}], "src_uid": "40d679f53417ba058144c745e7a2c76d"} {"source_code": "import Data.Char\n\ntoint s = (read s) :: Int\n\ndoit \"\" \"\" = True\ndoit (aa:s) (bb:t) =\n let a = ord aa in\n let b = ord bb in\n let x = abs (a - b) in\n if x == 0 || x == 2 then\n doit s t\n else\n False\n\ndoall [] = \"\"\ndoall (_:s:ss) =\n let t = reverse s in\n let r = if doit s t then \"YES\" else \"NO\" in\n r ++ \"\\n\" ++ doall ss\n\nsolve::String -> String\nsolve ss =\n let _:s = words ss in\n doall s\n\nmain = interact solve\n", "positive_code": [{"source_code": "main = interact $ unlines . map solve . pairs . tail . lines\npairs (a:b:xs) = (a,b) : pairs xs\npairs [] = []\nsolve (_,s) | all d (zip s (reverse s)) = \"YES\" | otherwise = \"NO\" where\n d (x,y) = (fromEnum x - fromEnum y) `elem` [-2,0,2]\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Function\nimport Data.Char\n\nsolve s = let (a,b) = B.splitAt (B.length s`div`2) $ B.filter (`elem`['a'..'z']) s\n t = and $ B.zipWith (\\x y -> if x == y || (let e = abs (ord x - ord y) in e == 2 || e == 0) then True else False) a $ B.reverse b \n in B.pack $ if t then \"YES\" else \"NO\"\n\nmain = B.interact $ B.unlines . map solve . fix (\\f a -> if null a then [] else let (b:c:ds) = a in c : f ds ) . tail . B.lines"}, {"source_code": "main = interact $ unlines . map solve . filter ((`elem` ['a' .. 'z']) . head) . lines\n\nsolve = (\\x -> foldl check \"YES\" $ zip x $ reverse x) . map fromEnum\n\ncheck acc (x,y)\n | d == 0 || d == 2 = acc\n | otherwise = \"NO\"\n where d = abs (x - y)\n"}, {"source_code": "import Data.List\nimport Data.Char\n\ng::String->String->String\ng [] []=\"YES\"\ng (x:xs) (y:ys)\n |x==y=g xs ys\n |otherwise=if abs(ord (x)-ord(y))==2 then g xs ys else \"NO\"\n\nf ::[String]->[String]\nf []=[]\nf (x:y:xs)=(g y (reverse y)):f xs\n\n\nmain = do\n e1<-getLine\n es<-getContents\n let xs=lines es\n putStr $ unlines$ f xs"}], "negative_code": [{"source_code": "import Data.Foldable (for_)\nimport Data.Char\nimport Data.Function\n\nf a b \n | (a+1)`mod`26 == (b-1)`mod`26 = True\n | (a+1)`mod`26 == (b+1)`mod`26 = True\n | (a-1)`mod`26 == (b-1)`mod`26 = True\n | (a-1)`mod`26 == (b+1)`mod`26 = True\n | otherwise = False\n \nprintB x = putStrLn $ if x then \"YES\" else \"NO\"\nmain = do\n n <- readLn :: IO Int\n for_ [1..n] $ \\_ -> do\n getLine\n s <- getLine\n let (a,b) = splitAt (length s `div` 2) s\n printB $ and $ zipWith (f`on`ord) a $ reverse b\n\n\n"}, {"source_code": "import Data.Foldable (for_)\nimport Data.Char\nimport Data.Function\n\nf a b \n | a + 1 == b - 1 = True\n | a + 1 == b + 1 = True\n | a - 1 == b - 1 = True\n | a - 1 == b - 1 = True\n | otherwise = False\n \nprintB x = putStrLn $ if x then \"YES\" else \"NO\"\nmain = do\n n <- readLn :: IO Int\n for_ [1..n] $ \\_ -> do\n getLine\n s <- getLine\n let (a,b) = splitAt (length s `div` 2) s\n printB $ and $ zipWith (f`on`ord) a $ reverse b\n\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Function\nimport Data.Char\n\nsolve s = let (a,b) = B.splitAt (B.length s`div`2) s\n t = and $ B.zipWith (\\x y -> if x == y || (let e = abs (ord x - ord y) in e == 2 || e == 0) then True else False) a $ B.reverse b \n in B.pack $ if t then \"YES\" else \"NO\"\n\nmain = B.interact $ B.unlines . map solve . fix (\\f a -> if null a then [] else let (b:c:ds) = a in c : f ds ) . tail . B.lines\n"}], "src_uid": "cc4cdcd162a83189c7b31a68412f3fe7"} {"source_code": "module Main where\n\nimport Data.List (dropWhileEnd)\n\nmain :: IO ()\nmain = do\n first <- getLine\n let [n, k] = map read (words first) :: [Int]\n s <- getLine\n let fakeMaxChar = succ 'z'\n let minChar = foldr min fakeMaxChar s\n let fakeMinChar = pred 'a'\n let maxChar = foldr max fakeMinChar s\n if n < k\n then putStrLn $ s ++ replicate (k - n) minChar\n else do\n let bufS = take k s\n let newS = dropWhileEnd ((==) maxChar) bufS\n let newLen = length newS\n let lastChar = newS !! (newLen - 1)\n let filtNewS = filter ((<) lastChar) s\n let minSpecialChar = foldr min fakeMaxChar filtNewS\n putStrLn $ take (newLen - 1) newS ++ [minSpecialChar] ++ replicate (k - newLen) minChar\n", "positive_code": [{"source_code": "import Data.Set hiding (map, null)\n\nnext :: Char -> Set Char -> Char\nnext c s = elemAt ((+1) $ findIndex c s) s\n\ntranslate :: Int -> Set Char -> String -> String\ntranslate k letterSet = snd . trans k\n where (maxL,minL) = (findMax letterSet, findMin letterSet)\n trans 0 _ = (False,[])\n trans k (c:cs)\n | done = (True,c:res)\n | c /= maxL = (True,(next c letterSet):res)\n | otherwise = (False,minL:res)\n where (done,res) = trans (k-1) cs\n\nconstruct :: Int -> Int -> String -> String\nconstruct n k s\n | k > n = s ++ replicate (k-n) (elemAt 0 letterSet)\n | otherwise = translate k letterSet s\n where letterSet = fromList s\n\nmain :: IO ()\nmain = do\n params <- getLine\n let (n,k) = (\\(x:y:[]) -> (x,y)) . map read . words $ params\n s <- getLine\n putStrLn $ construct n k s"}, {"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.Set as S\nimport Data.Maybe\nimport Data.List\nmain = interact exec\nexec = (\\[n, k, xs] -> f (read n) (read k) xs) . words\n\nf :: Int -> Int -> String -> String\nf n k xs\n | k > n = take k $ xs ++ repeat (S.findMin s)\n | otherwise = take k $ (\\(reverse -> f) -> init f ++ [next (last f)] ++ repeat (S.findMin s)) $ dropWhile (== S.findMax s) $ reverse $ take k xs\n where\n s = S.fromList xs\n next = fromJust . flip S.lookupGT s\n\n\n{-\n3 2\nyzy\n-}"}], "negative_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\nimport qualified Data.Set as S\nimport Data.Maybe\nimport Data.List\nmain = interact exec\nexec = (\\[n, k, xs] -> f (read n) (read k) xs) . words\n\nf :: Int -> Int -> String -> String\nf n k xs\n | k > n = take k $ xs ++ repeat (S.findMin s)\n | otherwise = take k $ (\\(reverse -> f) -> init f ++ [next (last f)] ++ repeat (S.findMin s)) $ dropWhile (== S.findMax s) $ reverse xs\n where\n s = S.fromList xs\n next = fromJust . flip S.lookupGT s\n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n first <- getLine\n let [n, k] = map read (words first) :: [Int]\n s <- getLine\n let minChar = foldr min 'z' s\n putStrLn $ replicate k minChar\n"}, {"source_code": "module Main where\n\nimport Data.List (dropWhileEnd)\n\nmain :: IO ()\nmain = do\n first <- getLine\n let [n, k] = map read (words first) :: [Int]\n s <- getLine\n let fakeMaxChar = succ 'z'\n let minChar = foldr min fakeMaxChar s\n let fakeMinChar = pred 'a'\n let maxChar = foldr max fakeMinChar s\n if n < k\n then putStrLn $ s ++ replicate (k - n) minChar\n else do\n let bufS = take k s\n let newS = dropWhileEnd ((==) maxChar) s\n let newLen = length newS\n let lastChar = newS !! (newLen - 1)\n let filtNewS = filter ((<) lastChar) s\n let minSpecialChar = foldr min fakeMaxChar filtNewS\n putStrLn $ take (newLen - 1) newS ++ [minSpecialChar] ++ replicate (k - newLen) minChar\n"}, {"source_code": "import Data.Set hiding (map, null)\n\nnext :: Char -> Set Char -> Char\nnext c s = elemAt ((+1) $ findIndex c s) s\n\ntranslate :: Int -> Set Char -> String -> String\ntranslate k letterSet = trans k\n where (maxL,minL) = (findMax letterSet, findMin letterSet)\n mapFrom c = if c == maxL then minL else next c letterSet\n trans 0 _ = []\n trans k (c:cs)\n | null res || head res == minL = (mapFrom c):res\n | otherwise = c:res\n where res = trans (k-1) cs\n\nconstruct :: Int -> Int -> String -> String\nconstruct n k s\n | k > n = s ++ replicate (k-n) (elemAt 0 letterSet)\n | otherwise = translate k letterSet s\n where letterSet = fromList s\n\nmain :: IO ()\nmain = do\n params <- getLine\n let (n,k) = (\\(x:y:[]) -> (x,y)) . map read . words $ params\n s <- getLine\n putStrLn $ construct n k s\n"}], "src_uid": "ea2dc6309e704d04cfdd6c79161c67f7"} {"source_code": "module Main where\n\nmain = do\n _ <- getLine\n ns <- map read . words <$> getLine\n let maxN = maximum ns\n grow = map (maxN-) ns\n print $ sum grow\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Ord\nimport Data.Char\nfi = fromIntegral\n\nsolve x = sum $ map (\\y->mx-y) x where\n\tmx = maximum x\n\t\n\t\nmain=interact$show.solve.map (\\x->read x::Int).words.head.tail.lines\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\ n -> (solve.concat =<< forM [1 .. 1] ( \\i -> map (fst.fromJust.C.readInt).C.words <$> C.getLine))\nsolve xs = let m =maximum xs in print $ sum $ map (\\a->m-a) xs "}, {"source_code": "main=interact$(show::Integer->String).f.map read.words\nf (a:b)=maximum b*a-sum b"}, {"source_code": "\nsolve xs = sum $ map (\\x -> m - x) xs\n where m = maximum xs\n\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Control.Monad\n\nmain = readInput >>= putStrLn . show . calc\n\nreadInput :: IO (Int, [Int])\nreadInput = liftM2 toTuple getLine getLine\n where toTuple a b = (read a, map read $ words b)\n \ncalc :: (Int, [Int]) -> Int\ncalc (1, _) = 0\ncalc (n, ws) = (n - 1) * m - (t - m)\n where mt = foldr (\\w (m, t) -> (max m w, t + w)) (0, 0) ws\n m = fst mt\n t = snd mt"}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\nmain :: IO ()\nmain = do\n n <- readB8Int <$> B8.getLine\n arr <- (map readB8Int . B8.words) <$> B8.getLine\n let mx = maximum arr\n answer = sum . map (mx -) $ arr\n printf \"%d\\n\" answer"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\nmain=do\n n<-getLine\n q<- map read <$> words <$> getLine ::IO [Int]\n let lq = length q\n let mq = maximum q\n print $ mq*lq - sum q\n \n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve xs = sum $ map (maximum xs -) xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n _ <- readLine\n citizens <- readLine\n B.putStrLn . B.pack . show $\n let richest = maximum citizens\n in sum $ map (richest -) citizens\n \n"}, {"source_code": "import Control.Applicative\n\nmain = do\n (n:as) <- map read . words <$> getContents\n print $ solve n as\n\nsolve n as = (n * maximum as) - sum as \n"}, {"source_code": "main = do\n n_ <- readLn::IO Int\n as_ <- return . map (read::String->Integer) . words =<< getLine\n let\n\tmx = maximum as_\n\tgive::[Integer]->Integer\n\tgive [] = 0\n\tgive (a:as) = (mx-a)+give as\n print $ give as_\n"}, {"source_code": "module Main where\n import Data.List\n main :: IO ()\n main = do\n _ <- getLine\n l <- getLine\n let a = map (\\x -> read x :: Integer) $ words l\n res = sum $ map (\\x -> m - x) $ sort a where m = maximum a\n print res"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve s = (length s) * (maximum s) - sum s"}, {"source_code": "goldCoins xs = sum $ [m - x | x <- xs ] where m = maximum xs \n\nmain = \n do\n line1 <- getLine\n line2 <- getLine\n let coins = map read . words $ line2\n putStrLn . show $ goldCoins coins"}, {"source_code": "import Data.List.Split (splitOn)\n\nmain = do\n _ <- getLine\n raw <- getLine\n let szamok = map read $ splitOn \" \" raw\n let ln = maximum szamok\n print $ sum $ map (ln-) szamok\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\n\n\n\nmain = do\n\t \t\n\tn<- read <$> getLine:: IO Int\n\ta<- map read <$> words <$> getLine ::IO [Int]\n \tlet m = maximum a\n\tlet s = sum a\n\tprint $ m*n-s\n"}, {"source_code": "--ghc 7.10\n\nminToEqual :: (Ord a, Num a) => [a] -> a\nminToEqual a = sum $ map (\\x -> amax-x) a\n where amax = maximum a\n\nmain = do\n nStr <- getLine\n aStr <- getLine\n let a = map read . words $ aStr :: [Int]\n print $ minToEqual a"}, {"source_code": "main :: IO ()\nmain = do\n n <- getLine\n cost <- fmap (map read.words) getLine :: IO [Int]\n let min_v = maximum cost\n print (sum (map (\\x-> min_v - x) cost))\n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\ngetList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\ta <- readInts\n\tprint $ maximum a * n - sum a\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\n\nmain = B.getLine >> (map $ maybe undefined fst . B.readInt) . B.words <$> B.getLine >>= (\\xs -> let m = maximum xs in print . sum . map ((-) m) $ xs)"}, {"source_code": "\n\n\n\nconv lst oo\n | (null lst) = reverse oo\n | otherwise = conv (tail lst) (((read (head lst))::Int) : oo)\n\n\nmain = do\n ff <- getLine\n gg <- getLine\n\n let n = (read ff)::Int\n uu = conv (words gg) []\n \n ans = ((length uu) * (maximum uu) - (sum uu))\n\n putStrLn (show ans)\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "module Main where \n\ntoInt s = read s :: Int\n\nsolve n mas = helper (maximum (map toInt (words mas))) (map toInt (words mas))\n\nhelper m = foldr (\\x s -> if x >= m then s else s + (m - x)) 0\n\nmain = do\n n <- getLine\n mas <- getLine\n print $ solve n mas\n"}], "negative_code": [{"source_code": "import Data.Maybe\nmain = interact $ show . solve\nsolve = sum . mapMaybe (flip lookup ss . head) . tail . lines\nss = [('T',4),('C',6),('O',8),('D',12),('I',20)]\n"}], "src_uid": "a5d3c9ea1c9affb0359d81dae4ecd7c8"} {"source_code": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array\nimport Data.Bool\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Debug.Trace\nimport Data.Bifunctor (second)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map solve >>> map output >>> C.unlines\n\ndata TC = TC {n :: Int, k :: Int, ps :: [Int]}\n\ntype Output = Int\n\ninput :: Scanner TC\ninput = do\n n <- int\n k <- int\n ps <- (n - 1) >< int\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..} = search 0 n\n where\n tree :: Array Int [Int]\n tree = accumArray (flip (:)) [] (1, n) $ zip ps [2 ..]\n\n -- (l, r]\n search :: Int -> Int -> Int\n search l r\n | l + 1 == r = r\n | check m = search l m\n | otherwise = search m r\n where\n m = (l + r + 1) `div` 2\n\n\n check :: Int -> Bool\n check h = snd (dfs h 1) <= k\n\n -- returns (dep, #ops)\n dfs :: Int -> Int -> (Int, Int)\n dfs hmax u\n | u == 1 = (0, ops)\n | otherwise = (1 + maximum (0 : filter (< hmax) ds), ops + count hmax ds)\n where\n (ds, ops) = tree ! u >$> map (dfs hmax) >>> unzip >>> second sum\n\noutput :: Output -> C.ByteString\noutput = showB\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Helpers\n(>$>) = flip ($)\n\ninfixl 0 >$>\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Control.Monad.Trans.State\r\nimport Data.Array\r\nimport Data.Array.ST\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.Ord\r\nimport Debug.Trace\r\nimport System.IO\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n casnum <- getInt\r\n res <- forM [1 .. casnum] $ \\_ -> do\r\n n <- getInt\r\n m <- getInt\r\n p <- replicateM (n -1) getInt\r\n let g = genGraph n (zip p [2 ..])\r\n let d = calcDepth g\r\n let d' = sortOn (Data.Ord.Down . snd) d\r\n let p' = listArray (2, n) p\r\n let min_h = binSearch (validHeight g m p' d') 1 (n -1)\r\n pure [min_h]\r\n pure $ mconcat $ map putInts res\r\n\r\nvalidHeight :: Array Int [Int] -> Int -> Array Int Int -> [(Int, Int)] -> Int -> Bool\r\nvalidHeight g m p d h = runST $ do\r\n let n = rangeSize $ bounds g\r\n visited <- newArray (1, n) False -- :: ST s (STArray s Int Bool)\r\n let goUp x 0 = x\r\n -- goUp 1 h = if h > 0 then 0 else 1\r\n goUp x h = goUp (p ! x) (h -1)\r\n\r\n let visDown :: STArray s Int Bool -> Int -> ST s Int\r\n visDown vis x = do\r\n vx <- readArray vis x\r\n if vx\r\n then pure 0\r\n else do\r\n writeArray vis x True\r\n mapM_ (visDown vis) (g ! x)\r\n pure 1\r\n\r\n cuts <- forM d $ \\(x, d) -> do\r\n vx <- readArray visited x\r\n if not vx && d > h\r\n then\r\n let anc = goUp x (h -1)\r\n in visDown visited anc\r\n else pure 0\r\n pure $ sum cuts <= m\r\n\r\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\r\nbinSearch v l r =\r\n if l == r\r\n then l\r\n else\r\n let m = div (l + r) 2\r\n in if v m\r\n then binSearch v l m\r\n else binSearch v (m + 1) r\r\n\r\ncalcDepth :: Array Int [Int] -> [(Int, Int)]\r\ncalcDepth g = go 0 1\r\n where\r\n go d x =\r\n let cs = (g ! x)\r\n in (x, d) : foldl' (++) [] ( map (go (d + 1)) cs)\r\n\r\ngenGraph :: Int -> [(Int, Int)] -> Array Int [Int]\r\ngenGraph n es = runSTArray $ do\r\n arr <- newArray (1, n) [] :: ST s (STArray s Int [Int])\r\n forM_ es $ \\(a, b) -> do\r\n lst <- readArray arr a\r\n writeArray arr a (b : lst)\r\n return arr\r\n\r\ntype SP = State P.ByteString\r\n\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs =\r\n let sepPrim =\r\n (,) ' '\r\n Prim.>$< Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp"}], "negative_code": [], "src_uid": "f260d0885319a146904b43f89e253f0c"} {"source_code": "import System.IO\nmain = print =<< mainLoop 0 0\n\nmainLoop bytes member = do\n eof <- isEOF\n case eof of\n True -> return bytes\n _ -> step\n where\n step = do\n s <- getLine\n case s of\n ('+':_) -> mainLoop bytes (member + 1)\n ('-':_) -> mainLoop bytes (member - 1)\n _ ->\n let (_, ':':msg) = span (/=':') s\n in mainLoop (bytes + length msg * member) member\n", "positive_code": [{"source_code": "main = do interact (show . gao 0 . lines) where\n\tgao _ [] = 0\n\tgao n (h:t) =\n\t\tif head h == '+' then\n\t\t\tgao (n + 1) t\n\t\telse if head h == '-' then\n\t\t\tgao (n - 1) t\n\t\telse\n\t\t\tn * (pred $ length $ dropWhile (/=':') h) + gao n t\n"}, {"source_code": "module Main where\n\nimport qualified Data.Set as Set\nimport Data.List\nimport IO\n\ntype SetStr = Set.Set String\n\nperform :: String -> (SetStr, Int) -> (SetStr, Int)\nperform query@(x:xs) (s, ans)\n | x == '+' = (Set.insert xs s, ans)\n | x == '-' = (Set.delete xs s, ans)\n | otherwise = (s, ans + usersCount*msgLength) where\n usersCount = Set.size s\n msgLength = length (dropWhile (/= ':') query) - 1\n\nprocessQuery :: (SetStr, Int) -> IO ()\nprocessQuery state@(s, ans) = do\n stop <- isEOF\n if (not stop) then do\n query <- getLine\n let newState = perform query state\n processQuery newState\n else do\n print ans\n\nmain = processQuery (Set.empty, 0)\n"}, {"source_code": "count [] people res = res\ncount (('+':_):next) people res = count next (people+1) res\ncount (('-':_):next) people res = count next (people-1) res\ncount (str:next) people res = count next people (res + people*getMsg str)\n\ngetMsg str = length (dropWhile (/=':') str) - 1\n\nmain = do\n s <- getContents\n let line = lines s\n res = count line 0 0\n putStrLn $ show res\n"}, {"source_code": "function :: (Int, Int) -> String -> (Int, Int)\nfunction (people, result) ('+':_) = (people + 1, result)\nfunction (people, result) ('-':_) = (people - 1, result)\nfunction (people, result) string = (people, result + people * (length (dropWhile (/=':') string) - 1))\n\nwynik :: [String] -> (Int, Int)\nwynik = foldl function (0, 0)\n\nmain = interact $ show . snd . wynik . lines\n\n"}, {"source_code": "module Main(main) where\n\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n\tinstr <- return.lines =<< getContents\n\tprint (solve 0 instr S.empty)\n\t\nsolve :: Int -> [String] -> S.Set String -> Int\nsolve x [] set = x\nsolve x (msg:msgs) set = \n\tcase head msg of\n\t\t'+'\t-> solve x msgs $ S.insert (tail msg) set\n\t\t'-'\t-> solve x msgs $ S.delete (tail msg) set\n\t\t_\t-> solve (x+(S.size set)*(length (tail $ snd $ span (/= ':') msg))) msgs set\n"}, {"source_code": "main = getContents >>= putStrLn .show. func . lines\n\n\nfunc :: [String] -> Int\nfunc xs = snd $ foldl ( check ) (0,0) xs \n\ncheck :: (Int,Int) -> String ->(Int,Int)\ncheck (pep,l) mes = case head mes of\n\t\t\t\t\t'+' -> (pep + 1,l)\n\t\t\t\t\t'-' -> \tif pep > 0 then (pep - 1,l) else ( 0,l)\n\t\t\t\t\t_\t->\tlet\n\t\t\t\t\t\t\tlnew = length . takeWhile (/=':') . reverse \n\t\t\t\t\t\t\tin\n\t\t\t\t\t\t\t(pep,l + pep * (lnew mes) ) "}, {"source_code": "\nsolve :: String -> String\nsolve s = show $ solve' (lines s) 0 0\n where\n solve' [] _ acc = acc\n solve' (('+':_):ss) n acc = solve' ss (n+1) acc\n solve' (('-':_):ss) n acc = solve' ss (n-1) acc\n solve' (s:ss) n acc = solve' ss n (acc + n * (length (dropWhile (/=':') s) - 1))\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nmain :: IO ()\nmain = interact $ show . solve . lines\n\nsolve :: [String] -> Int\nsolve commands = total $ foldl' applyCommand (S 0 0) commands\n\napplyCommand :: Solution -> String -> Solution\napplyCommand (S parts count) = \\case\n '+':_ -> S (parts + 1) count\n '-':_ -> S (parts - 1) count\n message -> S parts (count + parts * msgLength) where msgLength = length . tail $ dropWhile (':' /=) message\n\ndata Solution = S {\n parts:: !Int,\n total:: !Int\n}"}, {"source_code": "import Data.Maybe\nimport Data.List\nparse :: [String] -> Int\nparse xs = fst $ foldl f (0, 0) xs\n where f :: (Int, Int) -> String -> (Int, Int)\n f (dataC, peopleC) ('+':_) = (dataC, peopleC+1)\n f (dataC, peopleC) ('-':_) = (dataC, peopleC-1)\n f (dataC, peopleC) s = (dataC + peopleC * (length $ drop (fromJust (elemIndex ':' s) + 1) s), peopleC)\nmain = interact (show . parse . lines)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Data.List (foldl')\n\nmain :: IO ()\nmain = interact $ show . solve . lines\n\nsolve :: [String] -> Int\nsolve commands = snd $ foldl' applyCommand (0, 0) commands\n\napplyCommand :: (Int, Int) -> String -> (Int, Int)\napplyCommand (parts, count) = \\case\n '+':_ -> (parts + 1, count)\n '-':_ -> (parts - 1, count)\n message -> (parts, count + parts * msgLength) where msgLength = length . tail $ dropWhile (':' /=) message"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Data.List\n\nmain = interact $ show . traffic . lines\n\ntraffic = fst . foldl' command (0, 0)\n\ncommand (!x, !n) c = case c of\n\t('+':_) -> (x, n + 1)\n\t('-':_) -> (x, n - 1)\n\t_ -> (x + (length m - 1) * n, n)\n\twhere m = dropWhile (/= ':') c"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype Users = Int\ntype State = (Users, Int)\ntype Command = State -> State\n\nconv :: String -> Command\nconv = check where\n cmdAdd (users, v) = (users + 1, v)\n cmdRemove (users, v) = (users - 1, v)\n cmdSend n (users, v) = (users, v + users * n)\n check ('+' : _) = cmdAdd\n check ('-' : _) = cmdRemove\n check s = cmdSend n where\n n = length . takeWhile (/= ':') $ reverse s\n\nsimulate :: [Command] -> State\nsimulate = foldl' (flip id) (0, 0)\n\nsolve :: [String] -> [String]\nsolve = return . show . snd . simulate . map conv\n\nmain = interact $ unlines . solve . lines\n\n-- Samples...\nsample1 =\n [ \"+Mike\"\n , \"Mike:hello\"\n , \"+Kate\"\n , \"+Dmitry\"\n , \"-Dmitry\"\n , \"Kate:hi\"\n , \"-Kate\" ]\n\nsample2 =\n [ \"+Mike\"\n , \"-Mike\"\n , \"+Mike\"\n , \"Mike:Hi I am here\"\n , \"-Mike\"\n , \"+Kate\"\n , \"-Kate\" ]\n"}, {"source_code": "handle (n, l) ('+':ss) = (n + 1, l)\nhandle (n, l) ('-':ss) = (n - 1, l)\nhandle (n, l) s = (n, l + n * (length . tail . dropWhile (/= ':')) s)\nmain = lines `fmap` getContents >>= putStr . show . snd . foldl handle (0, 0)\n"}, {"source_code": "main = print . snd . foldl (\\(n,ans) (s:ss) ->\n if s == '+' then (n+1,ans)\n else if s == '-' then (n-1,ans)\n else (n, n * (pred $ length $ dropWhile (/=':') ss) + ans)\n ) (0,0) =<< return . lines =<< getContents"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Data.List (foldl')\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = interact $ show . solve . lines\n\nsolve :: [String] -> Int\nsolve commands = snd $ foldl' applyCommand (S.empty, 0) commands\n\napplyCommand :: (S.Set String, Int) -> String -> (S.Set String, Int)\napplyCommand (particpants, count) = \\case\n '+':name -> (S.insert name particpants, count)\n '-':name -> (S.delete name particpants, count)\n message -> (particpants, count + S.size particpants * msgLength) where msgLength = length . tail $ dropWhile (':' /=) message"}, {"source_code": "import Data.List\ndata Command = Add String|Remove String|Send String deriving Show\ncommandtype :: String -> Command\ncommandtype command@(x:xs) = if x=='+' then\n Add xs\n else if x=='-' then\n Remove xs\n else\n Send (tail (dropWhile (':'/=) command))\nsolve [] n _ = n\nsolve (x:xs) n mem = case commandtype x of\n Add name -> solve xs n (name:mem)\n Remove name -> solve xs n (mem\\\\[name])\n Send message -> solve xs (n+(length message)*(length mem)) mem\n\nmain = do l <- getContents\n print (solve (lines l) 0 [])"}, {"source_code": "f(h,t)=q\n where\n q ('+':_) = (h+1,t)\n q ('-':_) = (h-1,t)\n q s = (h, t + h * length (dropWhile (/= ':')s) - h)\nmain = interact $ show . snd . foldl f (0,0) . lines\n"}, {"source_code": "f(h,t)('+':_)=(h+1,t)\nf(h,t)('-':_)=(h-1,t)\nf(h,t)s=(h,t+h*(length(dropWhile(/=':')s)-1))\nmain=interact$show.snd.foldl f(0,0).lines\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nparse :: [String] -> Int\nparse xs = fst $ foldl f (0, 0) xs\n where f :: (Int, Int) -> String -> (Int, Int)\n f (dataC, peopleC) ('+':_) = (dataC, peopleC+1)\n f (dataC, peopleC) ('-':_) = (dataC, peopleC-1)\n f (dataC, peopleC) s = (dataC + peopleC * (length $ drop (fromJust (elemIndex ':' s) + 1) s), peopleC)\nmain = interact (show . parse . lines)\n"}, {"source_code": "import qualified Data.Set as S\n\nparse = lines\n\ntype State = (S.Set String, Int)\n\n\nsolve = foldl changeState (S.empty, 0) \n\nchangeState :: State -> String -> State\nchangeState (present, x) ('+':person) = (S.insert person present, x)\nchangeState (present, x) ('-':person) = (S.delete person present, x)\nchangeState (present, x) (person) = (present, x + S.size present * length message)\n where \n message = tail $ dropWhile (/= ':') person\n\npresentate :: State -> String\npresentate (_, n) = show n\n\n\nmain = interact $ presentate . solve . parse\n"}], "negative_code": [{"source_code": "import Data.Maybe\nparse :: [String] -> Int\nparse xs = fst $ foldl f (0, 0) xs\n where f :: (Int, Int) -> String -> (Int, Int)\n f (dataC, peopleC) ('+':_) = (dataC, peopleC+1)\n f (dataC, peopleC) ('-':_) = (dataC, peopleC-1)\n f (dataC, peopleC) s = (dataC + peopleC * (length $ drop (peopleC + 1) s), peopleC)\nmain = interact (show . parse . lines)\n"}], "src_uid": "d7fe15a027750c004e4f50175e1e20d2"} {"source_code": "solve :: [Int] -> [[Int]]\nsolve xs = [take 1 negative,\n (if positive == []\n then (take 2 (drop 1 negative))\n else positive),\n (if positive == []\n then (zero ++ drop 3 negative)\n else (zero ++ drop 1 negative))]\n where negative = filter (<0) xs\n positive = filter (>0) xs\n zero = filter (==0) xs\n\n\nshowSet :: [Int] -> String\nshowSet xs = unwords $ map show (length xs:xs)\n\nshowSolution :: [[Int]] -> String\nshowSolution xs = unlines $ map showSet xs\n\nmain = interact $ showSolution . solve . map read . tail . words\n", "positive_code": [{"source_code": "import Data.List\n\nmain = interact ( conv . af . f . sort . r . tail . lines )\nr (x:[]) = map read ( words x )\nf = filter ( \\x -> x /= 0 )\naf :: [Int] -> [[Int]]\naf ( x:y:[] ) = [[1,x],[1,y],[1,0]]\naf ( x:y:z:t ) | y < 0 && z < 0 = [[1,x],[2,y,z],( length t )+1:0:t]\n | otherwise = [[1,x],[1,z],( length t )+2:0:y:t]\nconv :: [[Int]] -> String\nconv [x,y,z] = ( g . show $ x ) ++ \"\\n\" ++ ( g.show $ y ) ++ \"\\n\" ++ ( g . show $ z )\ng l = map ( \\x -> if x == ',' then ' ' else x ) ( filter ( \\x -> x /= '[' && x /= ']' ) l )\n"}, {"source_code": "main = interact $ unlines . go . (map read) . concat . (map words) . lines\ngo (n:as) = (f bz):(f az):(f ez):[]\n where f z = (show $ length z) ++ \" \" ++ (unwords $ map show z)\n ng = filter (<0) as\n bz = [head ng]\n az = (if length (tail ng) < 2 then [] else take 2 $ tail ng) ++ (filter (>0) as)\n ez = [0] ++ (if length (tail ng) < 2 then tail ng else drop 3 ng)\n"}, {"source_code": "solve x\n | gz /= [] = [head lz] : [head gz] : (z ++ tail gz ++ tail lz) : []\n | otherwise = [lz !! 2] : take 2 lz : (z ++ drop 3 lz): []\n where lz = filter (<0) x\n gz = filter (>0) x\n z = filter (==0) x\n\nl x = length x : x\n\nmain = interact $ unlines . map unwords . map (map show) . map l . solve . tail . map read . words\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [[Int]]\nsolve xs\n | even (length ms) = [as, bsEven, csEven]\n | otherwise = [as, bsOdd, csOdd]\n where\n as = [head ms]\n bsEven = tail $ tail ms ++ ps\n bsOdd = tail ms ++ ps\n csEven = [head $ tail ms] ++ zs\n csOdd = zs\n ps = filter (> 0) xs\n zs = filter (== 0) xs\n ms = filter (< 0) xs\n\nprint' :: [Int] -> IO ()\nprint' xs = putStrLn $ intercalate \" \" $ map show $ (length xs : xs)\n\nmain :: IO ()\nmain = getLine >> reads >>= mapM_ print' . solve\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let x1 = filter (\\x -> x < 0) xs\n x2 = filter (\\x -> x > 0) xs\n x3 = filter (\\x -> x == 0) xs\n n1 = [head x1]\n tx1 = tail x1\n n2 = x2 ++ (if (length (tx1) >= 2) then take 2 tx1 else [])\n n3 = x3 ++ (if (length (tx1) >= 2) then drop 2 (tail x1) else take 2 tx1)\n \n putStr $ show (length(n1)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n1\n putStrLn \"\"\n \n putStr $ show (length(n2)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n2\n putStrLn \"\"\n \n putStr $ show (length(n3)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n3\n putStrLn \"\""}, {"source_code": "import Data.List ((\\\\), sort)\n\nmain :: IO ()\nmain = getContents >>= mapM_ (\\xs -> putStrLn $ unwords $ map show $ length xs : xs) . solve . map read . tail . words\n\nsolve :: [Int] -> [[Int]]\nsolve as = [ n1, n2, (as \\\\ n1) \\\\ n2 ]\n where n1 = [ minimum as ]\n n2 = if maximum as > 0 then [ maximum as ] else take 2 (tail (sort as))\n"}, {"source_code": "main=interact$unlines.map(unwords.map show).f.map read.tail.words\nf xs\n | odd $ length (x:xs1) = [[1,x],length(xs1++xs2):(xs1++xs2),length xs3:xs3]\n | otherwise = [[1,x],length(tail xs1++xs2):(tail xs1++xs2),(length xs3+1):head xs1:xs3]\n where\n (x:xs1)=filter(<0)xs\n xs2=filter(>0)xs\n xs3=filter(0==)xs"}, {"source_code": "import Data.List\n\ngao::([Int],[Int])->([Int],[Int])\ngao (a,b) = if (b!!0)>0 then (a,b) else (b,a)\n\nmain::IO()\nmain = do\n\tinput<-getContents\n\tlet\n\t\t(n:olda)=map read (words input) :: [Int]\n\t\t(x:a)=sort olda\n\t\tlen = length $ takeWhile (<=0) a\n\t\t(b,c)=gao $ if len <2 then splitAt len a else splitAt 2 a\n\t\tout a = ( show $ length a ) ++ \" \" ++ ( foldr (\\a t -> t++a) [] (map ((++\" \").show) a) )\n\tputStrLn $ out [x]\n\tputStrLn $ out c\n\tputStrLn $ out b\n"}, {"source_code": "module Main where\n\nprintSolution :: ([Int], [Int], [Int]) -> IO ()\nprintSolution (a, b, c) = do\n putStrLn ((show $ length a) ++ \" \" ++ (unwords $ map show a))\n putStrLn ((show $ length b) ++ \" \" ++ (unwords $ map show b))\n putStrLn ((show $ length c) ++ \" \" ++ (unwords $ map show c))\n\nclassify :: ([Int], [Int], [Int]) -> Int -> ([Int], [Int], [Int])\nclassify (a, b, c) n\n | n < 0 = (n:a, b, c)\n | n > 0 = ( a, n:b, c)\n | n == 0 = ( a, b, n:c)\n\nfixPositive :: ([Int], [Int], [Int]) -> ([Int], [Int], [Int])\nfixPositive (a1:a2:as, [], c) = (as, [a1, a2], c)\nfixPositive t = t\n\nfixNegative :: ([Int], [Int], [Int]) -> ([Int], [Int], [Int])\nfixNegative t@(a,b,c) = if (length a) `rem` 2 == 0 then (tail a, b, (head a) : c) else t\n\nsolve :: [Int] -> ([Int], [Int], [Int])\nsolve = fixNegative . fixPositive . foldl classify ([], [], [])\n\nmain = getLine >> getLine >>= (printSolution . solve . map read . words)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \ndel x (a:as) \t| x==a = as\n\t\t| otherwise = a: (del x as)\n \n\n\n\nmain= do\n\t getLine\n\t a<- map read. words <$> getLine::IO [Int]\n\t let b1 = head $ filter (<0) a\n\t let a1 = del b1 a\n\t let b21 = filter (>0) a1\n\t let b2 =if b21 ==[] then take 2 $ filter (<0) a1 else take 1 b21\n\t let b31 = (del (head b2) a1)\n let b3 = if length b2 >1 then (del (last b2) b31) else b31\n\t putStrLn $ \"1 \" ++ show b1\n\t putStrLn $ (show (length b2)) ++ \" \" ++(unwords (map show b2))\n\t putStrLn $ (show (length b3)) ++ \" \" ++(unwords (map show b3))\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\tline <- getLine\n\tlet\n\t\tarr = map read. words $ line\n\t\tpos = filter (> 0) arr\n\t\tneg = filter (<0) arr\n\t\tzero = filter (==0) arr\n\t\t[arr1, arr2, arr3] = if length neg >= 3 then [[neg!!0], [neg!!1, neg!!2], (drop 3 neg) ++ (pos) ++ zero] else [[neg!!0], [pos!!0], (drop 1 pos) ++ (drop 1 neg) ++ zero]\n\tputStr $ (show (length arr1)) ++ \" \"\n\tmapM_ (\\x -> putStr $ (show x) ++ \" \") arr1\n\tputStrLn \"\"\n\tputStr $ (show (length arr2)) ++ \" \"\n\tmapM_ (\\x -> putStr $ (show x) ++ \" \") arr2\n\tputStrLn \"\"\n\tputStr $ (show (length arr3)) ++ \" \"\n\tmapM_ (\\x -> putStr $ (show x) ++ \" \") arr3\n"}, {"source_code": "main :: IO()\nmain = interact work\n\nwork :: String -> String\nwork input = unlines . map showList . solve $ numbers\n where numbers = map parseInt . words . last . lines $ input\n parseInt str = read str :: Int\n showList lst = (show . length $ lst) ++ \" \" ++ (unwords . map show $ lst)\n\nsolve :: [Int] -> [[Int]]\nsolve numbers = if null ps\n then [[head ns], tail . take 3 $ ns, drop 3 ns ++ zs]\n else [[head ns], [head ps], tail ns ++ tail ps ++ zs]\n where ps = filter (\\x -> x > 0) numbers\n ns = filter (\\x -> x < 0) numbers\n zs = filter (\\x -> x == 0) numbers\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- fmap (map (read :: String -> Int) . words) getLine\n let (z,nz) = partition (==0) a\n (s,(h:t)) = partition (>0) nz\n (u,v) = splitAt (length t `div` 2 * 2) t\n i = [h]\n j = s ++ u\n k = z ++ v\n p i\n p j\n p k\n where\n p it = putStrLn $ unwords $ map show $ length it: it\n"}, {"source_code": "main :: IO ()\nmain = interact $ unlines . map (unwords . map show) . solve . map read . tail . words\n\nsolve :: [Int] -> [[Int]]\nsolve as = [length s1'' : s1'', length s2' : s2', length s3' : s3']\n where\n [s1, s2, s3] = foldl f [[], [], []] as\n (s2', s1') = if null s2 then splitAt 2 s1 else (s2, s1)\n (s1'', s3') = if length s1' `mod` 2 == 0 then (tail s1', head s1' : s3) else (s1', s3)\n f [s1, s2, s3] a\n | a < 0 = [a : s1, s2, s3]\n | a > 0 = [s1, a : s2, s3]\n | a == 0 = [s1, s2, a : s3]\n"}, {"source_code": "import Data.List\n\nrecombine [] _ _ = error \"never mind\"\nrecombine ns [] zs = recombine (drop 2 ns) (take 2 ns) zs\nrecombine ns ps zs\n | even (length ns) = [tail ns, ps, head ns : zs]\n | otherwise = [ns, ps, zs]\n\nsolve (n:xs) = recombine negatives positives zeroes\n where\n negatives = filter (< 0) xs\n positives = filter (> 0) xs\n zeroes = filter (== 0) xs\n\nshowSet xs = unwords $ map show (length xs : xs)\n\nmain = interact $ unlines . map showSet . solve . map read . words"}, {"source_code": "import Data.List\nmain = interact ( unlines . map ( unwords . map show ) . af . filter ( /= 0 ) . sort . concat . map ( map read . words ) . tail . lines )\naf ( x:y:[] ) = [[1,x],[1,y],[1,0]]\naf ( x:y:z:t ) | y < 0 && z < 0 = [[1,x],[2,y,z],( length t )+1:0:t]\n | otherwise = [[1,x],[1,z],( length t )+2:0:y:t]\n"}], "negative_code": [{"source_code": "import Data.List\n\nrecombine [] _ _ = error \"never mind\"\nrecombine ns [] zs = [drop 2 ns, take 2 ns, zs]\nrecombine ns ps zs\n | even (length ns) = [tail ns, ps, head ns : zs]\n | otherwise = [ns, ps, zs]\n\nsolve (n:xs) = recombine negatives positives zeroes\n where\n negatives = filter (< 0) xs\n positives = filter (> 0) xs\n zeroes = filter (== 0) xs\n\nshowSet xs = unwords $ map show (length xs : xs)\n\nmain = interact $ unlines . map showSet . solve . map read . words"}, {"source_code": "main = interact $ unlines . go . (map read) . concat . (map words) . lines\ngo (n:as) = (f bz):(f az):(f ez):[]\n where f z = (show $ length z) ++ \" \" ++ (unwords $ map show z)\n ng = filter (<0) as\n bz = [head ng]\n az = (take 2 $ tail ng) ++ (filter (>0) as)\n ez = [0]\n"}, {"source_code": "main = interact $ show . unlines . go . (map read) . concat . (map words) . lines\ngo (n:as) = (f bz):(f az):(f ez):[]\n where f z = (show $ length z) ++ (foldl (\\s x -> \" \" ++ (show x) ++ s) [] z)\n ng = filter (<0) as\n bz = [head ng]\n az = (take 2 $ tail ng) ++ (filter (>0) as)\n ez = [0]\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> [[Int]]\nsolve xs = [as, bs, cs]\n where\n as = [head $ filter (< 0) xs]\n bs = tail $ filter (< 0) xs ++ filter (> 0) xs\n cs = filter (== 0) xs\n\nprint' :: [Int] -> IO ()\nprint' xs = putStrLn $ intercalate \" \" $ map show $ (length xs : xs)\n\nmain :: IO ()\nmain = getLine >> reads >>= mapM_ print' . solve\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let x1 = filter (\\x -> x < 0) xs\n x2 = filter (\\x -> x > 0) xs\n x3 = filter (\\x -> x == 0) xs\n n1 = [head x1]\n n2 = take 2 (tail x1) ++ x2\n n3 = drop 3 x1 ++ x3\n \n putStr $ show (length(n1)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n1\n putStrLn \"\"\n \n putStr $ show (length(n2)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n2\n putStrLn \"\"\n \n putStr $ show (length(n3)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n3\n putStrLn \"\""}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let x1 = filter (\\x -> x < 0) xs\n x2 = filter (\\x -> x > 0) xs\n x3 = filter (\\x -> x == 0) xs\n n1 = [head x1]\n n2 = if length(x2) == 0 then take 2 x1 else x2\n n3 = if length(x2) == 0 then drop 2 x1 ++ x3 else x3\n \n putStr $ show (length(n1)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n1\n putStrLn \"\"\n \n putStr $ show (length(n2)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n2\n putStrLn \"\"\n \n putStr $ show (length(n3)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n3\n putStrLn \"\""}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let x1 = filter (\\x -> x < 0) xs\n x2 = filter (\\x -> x > 0) xs\n x3 = filter (\\x -> x == 0) xs\n n1 = [head x1]\n n2 = x2 ++ take 2 (tail x1)\n n3 = x3 ++ drop 2 (tail x1)\n \n putStr $ show (length(n1)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n1\n putStrLn \"\"\n \n putStr $ show (length(n2)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n2\n putStrLn \"\"\n \n putStr $ show (length(n3)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n3\n putStrLn \"\""}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let x1 = filter (\\x -> x < 0) xs\n x2 = filter (\\x -> x > 0) xs\n x3 = filter (\\x -> x == 0) xs\n n1 = [head x1]\n n2 = if length(x2) == 0 then tail x1 ++ x2 else x2\n n3 = if length(x2) /= 0 then tail x1 ++ x3 else x3\n \n putStr $ show (length(n1)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n1\n putStrLn \"\"\n \n putStr $ show (length(n2)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n2\n putStrLn \"\"\n \n putStr $ show (length(n3)) ++ \" \"\n mapM_ (\\x -> putStr $ show(x) ++ \" \") n3\n putStrLn \"\""}, {"source_code": "module Main where\n\nprintSolution :: ([Int], [Int], [Int]) -> IO ()\nprintSolution (a, b, c) = do\n putStrLn ((show $ length a) ++ \" \" ++ (unwords $ map show a))\n putStrLn ((show $ length b) ++ \" \" ++ (unwords $ map show b))\n putStrLn ((show $ length c) ++ \" \" ++ (unwords $ map show c))\n\nclassify :: ([Int], [Int], [Int]) -> Int -> ([Int], [Int], [Int])\nclassify (a, b, c) n\n | n < 0 = (n:a, b, c)\n | n > 0 = ( a, n:b, c)\n | n == 0 = ( a, b, n:c)\n\nfixSolution :: ([Int], [Int], [Int]) -> ([Int], [Int], [Int])\nfixSolution (a1:a2:as, [], c) = (as, [a1, a2], c)\nfixSolution t = t\n\nsolve :: [Int] -> ([Int], [Int], [Int])\nsolve = foldl classify ([], [], [])\n\nmain = getLine >> getLine >>= (printSolution . fixSolution . solve . map read . words)\n"}], "src_uid": "03cf2cc26c84aab685ee78a1d6318b30"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\nimport Data.List\n\nsolve (h:hs) = fst $ \n foldl' (\\(j,y) x -> (j + 2 + (if y == x then 0 else abs $ x - y ),x)) (h + 1,h) (hs) \n\nmain = do\n let int = fst .fromJust . B.readInt\n n <- readLn :: IO Int\n hs <- replicateM n (int <$> B.getLine)\n print $ solve hs\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\tn <- read <$> getLine\n\ths <- replicateM n $ read <$> getLine\n\tprint $ solve hs 0 0\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve [] _ res = res - 1\nsolve (c:hs) h res = solve hs c ( res + abs ( c - h ) + 2 )\n"}, {"source_code": "import Control.Monad;\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n h1:hRest <- replicateM n $ fmap read getLine\n let time curH leftHs =\n case leftHs of\n [] -> 0\n h:rest -> (abs (curH - h) + 2) + time h rest\n print $ h1 + 1 + time h1 hRest\n"}, {"source_code": "\nsolve :: [Int] -> Int\nsolve xs = solve' 0 xs - 1\n where\n solve' h [] = 0\n solve' h (x:xs)\n | h <= x = 1 + (x - h) + 1 + solve' x xs\n | otherwise = (h - x) + 1 + 1 + solve' x xs\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- sequence $ replicate n readLn\n print $ solve xs\n"}, {"source_code": "main=interact$show.f.map read.words\nf(n:h1:hs)=2*n-1+h1+sum(zipWith((abs.).(-))(h1:hs)hs)"}, {"source_code": "import Control.Applicative\n\nmain = do\n getLine\n trees <- map read . lines <$> getContents\n print $ (length trees)*2 - 1 + slv trees 0 0\n\nslv [] n _ = n\nslv (x:xs) n prevLvl = slv xs (abs (prevLvl-x)+n) x"}], "negative_code": [], "src_uid": "a20ca4b053ba71f6b2dc05749287e0a4"} {"source_code": "\nimport Data.List\nimport Data.Ord\nimport Data.Function\nimport Control.Monad\n\nmain = do\n n <- readLn :: IO Int\n names <- replicateM n getLine\n matchResult <- replicateM (n*(n-1)`div`2) getLine\n let mr = concatMap readMatchResult matchResult\n mr1 = sortBy (comparing (fst.fst)) mr\n mr2 = groupBy (on (==) (fst.fst)) mr1\n mr3 = map toScore mr2\n mr4 = reverse $ sortBy cmp mr3\n --mapM_ print mr2\n --mapM_ print mr3\n mapM_ putStrLn . sort . map fst4 $ take (n`div`2) mr4\n where\n fst4 (x,_,_,_) = x\n rev ((a,b),(c,d)) = ((b,a),(d,c))\n split c [] = []\n split c cs = let (a,b) = span (c/=) cs\n tail' [] = []\n tail' (a:as) = as\n in a : split c (tail' b)\n readMatchResult :: String -> [((String,String),(Int,Int))]\n readMatchResult cs = let (ts:ss:[]) = words cs\n (t1:t2:[]) = split '-' ts\n (s1:s2:[]) = map read $ split ':' ss\n res = ((t1,t2),(s1,s2))\n in [res,rev res]\n toScore :: [((String,String),(Int,Int))] -> (String,Int,Int,Int)\n toScore cs = let (x,y,z) = f (0,0,0) cs\n name = fst.fst.head$cs\n in (name,x,y,z)\n where\n f x [] = x\n f (x,y,z) ((_,(s,m)):as)\n | s>m = f (x+3,y+s-m,z+s) as\n | s==m = f (x+1,y+s-m,z+s) as\n | s (String,Int,Int,Int) -> Ordering\n cmp (_,x1,y1,z1) (_,x2,y2,z2)\n | x1 /= x2 = compare x1 x2\n | y1 /= y2 = compare y1 y2\n | z1 /= z2 = compare z1 z2\n\n\n\n\n", "positive_code": [{"source_code": "\n import Data.List\n \n parse :: String -> (String, String, Int, Int)\n parse s = let s0 = s; a = takeWhile (/='-') s0 in\n let s1 = drop (length a + 1) s0; b = takeWhile (/=' ') s1 in \n let s2 = drop (length b + 1) s1; c = takeWhile (/=':') s2 in\n let s3 = drop (length c + 1) s2; d = s3 in\n (a, b, read c, read d)\n \n table :: [String] -> [(String, String, Int, Int)] -> [String]\n table teams results = snd $ unzip $ sort $ zip scores teams\n where scores = map (score results) teams\n where score results team = (sum [sc result | result <- resultsOfThisTeam], \n sum [c - d | (_, _, c, d) <- resultsOfThisTeam],\n sum [c | (_, _, c, _) <- resultsOfThisTeam])\n where sc (a, b, c, d) = case compare c d of GT -> 3\n EQ -> 1\n LT -> 0\n resultsOfThisTeam = [result | result@(a, _, _, _) <- results, a == team] \n \n solve :: Int -> [String] -> [String] -> [String] \n solve n teams matches = sort $ drop (n `div` 2) (table teams results)\n where singleResults = map parse matches\n results = singleResults ++ map (\\(a, b, c, d) -> (b, a, d, c)) singleResults\n \n main = do\n contents <- getContents\n let n = read $ head $ lines contents\n let teams = take n $ drop 1 $ lines contents\n let matches = take (n * (n - 1) `div` 2) $ drop (n + 1) $ lines contents\n mapM putStrLn (solve n teams matches)"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nfst3 (a, b, c) = a\nsnd3 (a, b, c) = b\ntrd3 (a, b, c) = c\nfrt4 (a, b, c, d) = d\n\ntoMatch ss =\n let (t1, '-':ss2) = break (== '-') ss\n (t2, ' ':ss3) = break (== ' ') ss2\n [(n1, ':':ss4)] = reads ss3\n n2 = read ss4\n in (t1, t2, n1, n2)\n\nmain = do\n n <- readLn\n ns <- replicateM n getLine\n ms <- replicateM (n*(n-1)`div`2) $ toMatch <$> getLine\n let ms' = reverse $ sort [ accum (catMaybes [ conv name match | match <- ms ]) | name <- ns]\n mapM_ putStrLn $ sort $ map frt4 $ take (n `div` 2) ms'\n where\n conv name (t1, t2, n1, n2)\n | t1 == name = Just (name, n1, n2)\n | t2 == name = Just (name, n2, n1)\n | otherwise = Nothing\n accum :: [(String, Int, Int)] -> (Int, Int, Int, String)\n accum ls =\n let sco = sum $ map snd3 ls\n mis = sum $ map trd3 ls\n p = sum $ zipWith point (map snd3 ls) (map trd3 ls)\n name = fst3 $ head ls\n in (p, sco-mis, sco, name)\n point n1 n2 | n1 < n2 = 0\n | n1 > n2 = 3\n | otherwise = 1\n"}, {"source_code": "import Text.ParserCombinators.Parsec\nimport Data.Map.Strict hiding (foldl)\nimport Data.Function( on)\nimport Data.List( sortBy, intercalate, sort)\nimport Control.Applicative( (<$>))\n\nmain = do\n winScores <- return . (parse parser \"(stdin)\") =<< getContents\n case winScores of\n\tLeft _\t -> fail \"Parsing failed.\"\n\tRight ws -> do\n\t let performance = foldl proc empty $ concat ws\n\t\t where proc mp (team,po) = insertWith plus team po mp\n\t\t\tplus (w1,d1,g1) (w2,d2,g2) = (w1+w2,d1+d2,g1+g2)\n\t\tr = toList performance\n\t\twinner = take half $ sortBy (descOrder `on` snd) r\n\t\t where\n\t\t half = length r `div` 2\n\t\t descOrder = flip compare\n\t putStr $ intercalate \"\\n\" . sort $ fst <$> winner\n\nparser = do\n sz <- szTeams\n spaces\n count sz name\n let szRecords = sz*(sz-1)`div`2\n count szRecords matchRecord\n\nszTeams = many1 digit >>= return . read\n\nname = do\n v <- many1 letter\n spaces\n return v\n\nmatchRecord = do\n (t1, t2) <- card\n spaces\n (s1, s2) <- score\n spaces\n return $ if s1>s2\n\tthen [(t1,(3::Int,s1-s2,s1)),(t2,(0,s2-s1,s2))]\n\telse if s1 [((String,String),(Int,Int))]\n readMatchResult cs = let (ts:ss:[]) = words cs\n (t1:t2:[]) = split '-' ts\n (s1:s2:[]) = map read $ split ':' ss\n res = ((t1,t2),(s1,s2))\n in [res,rev res]\n toScore :: [((String,String),(Int,Int))] -> (String,Int,Int,Int)\n toScore cs = let (x,y,z) = f (0,0,0) cs\n name = fst.fst.head$cs\n in (name,x,y,z)\n where\n f x [] = x\n f (x,y,z) ((_,(s,m)):as)\n | s>m = f (x+3,y+s-m,z+s) as\n | s==m = f (x+1,y+s-m,z+s) as\n | s (String,Int,Int,Int) -> Ordering\n cmp (_,x1,y1,z1) (_,x2,y2,z2)\n | x1 /= x2 = compare x1 x2\n | y1 /= y2 = compare y1 y2\n | z1 /= z2 = compare z1 z2\n\n\n\n\n"}, {"source_code": " import Data.List\n \n parse :: String -> (String, String, Int, Int)\n parse s = let s0 = s; a = takeWhile (/='-') s0 in\n let s1 = drop (length a + 1) s0; b = takeWhile (/=' ') s1 in \n let s2 = drop (length b + 1) s1; c = takeWhile (/=':') s2 in\n let s3 = drop (length c + 1) s2; d = s3 in\n (a, b, read c, read d)\n \n table :: [String] -> [(String, String, Int, Int)] -> [String]\n table teams results = snd $ unzip $ sort $ zip scores teams\n where scores = map (score results) teams\n where score results team = (sum [sc result | result <- resultsOfThisTeam], \n sum [c - d | (_, _, c, d) <- resultsOfThisTeam],\n sum [c | (_, _, c, _) <- resultsOfThisTeam])\n where sc (a, b, c, d) = case compare c d of GT -> 3\n EQ -> 1\n LT -> 0\n resultsOfThisTeam = [result | result@(a, _, _, _) <- results, a == team] \n \n solve :: Int -> [String] -> [String] -> [String] \n solve n teams matches = drop (n `div` 2) (table teams results)\n where singleResults = map parse matches\n results = singleResults ++ map (\\(a, b, c, d) -> (b, a, d, c)) singleResults\n \n main = do\n contents <- getContents\n let n = read $ head $ lines contents\n let teams = take n $ drop 1 $ lines contents\n let matches = take (n * (n - 1) `div` 2) $ drop (n + 1) $ lines contents\n mapM putStrLn (solve n teams matches)"}], "src_uid": "472c0cb256c062b9806bf93b13b453a2"} {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Bits\nimport Data.List\nimport Data.Maybe\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\ndata Color\n = Red\n | Black\n deriving (Enum, Eq, Show)\n\nswitch Red = Black\nswitch Black = Red\n\ntype Edge = (Int, Int)\ntype Vertices = [Int]\ntype Graph = Array Int Vertices\n\ntoGraph :: Int -> [Edge] -> Graph\ntoGraph n = accumArray (flip (:)) [] (1, n)\n\ncolor :: Int -> Graph -> Array Int Color\ncolor n e = array (1, n) $ M.assocs $ foldl (dfs Red) M.empty [1 .. n]\n where\n dfs t c v\n | M.member v c = c\n | otherwise = foldl (dfs (switch t)) (M.insert v t c) $ e!v\n\ntry12 :: Int -> Graph -> Vertices -> Vertices -> Maybe Vertices\ntry12 n e r b\n | null u = Nothing\n | otherwise = Just $ (u':v') ++ (delete u' r) ++ (b \\\\ v')\n where\n m = length b\n u = [i | i <- r, length (e!i) <= m - 2]\n u' = head u\n v = [j | j <- b, notElem u' $ e!j]\n v' = take 2 v\n\ntry42 :: Int -> Graph -> Vertices -> Vertices -> Maybe Vertices\ntry42 n e r b\n | length v' < 6 = Nothing\n | otherwise = Just $ v' ++ (r \\\\ v') ++ (b \\\\ v')\n where\n m = length b\n x = foldr1 xor b\n e' = toGraph n [(foldr xor x $ e!i, i) | i <- r, length (e!i) == m - 1]\n v' = concat $ take 2 [i: take 2 j | (i, j) <- assocs e', length j >= 2]\n\nyes :: Vertices -> IO ()\nyes v = putStrLn $ (\"YES\\n\" ++) $ unwords $ map show $ elems w\n where\n n = length v\n w = array (1,n) $ zip v $ concatMap (replicate 3) [1 ..]\n\nno :: IO ()\nno = putStrLn \"NO\"\n\nsolve :: Int -> Graph -> IO ()\nsolve n e =\n if m == 0 then yes $ r ++ b\n else case try12 n e x y of\n Just z -> yes z\n Nothing -> case try42 n e x y of\n Just z -> yes z\n Nothing -> no\n where\n c = color n e\n r = [i | (i, e) <- assocs c, e == Red]\n b = [i | (i, e) <- assocs c, e == Black]\n m = length r `mod` 3\n (x, y) = if m /= 2 then (r, b) else (b, r)\n\nmain = do\n [n, m] <- get\n e <- replicateM m get\n solve n $ toGraph n $ concat [[(i, j), (j, i)] | [i, j] <- e]\n where\n get = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Bits\nimport Data.List\nimport Data.Maybe\nimport qualified Data.IntMap as M\nimport qualified Data.ByteString.Char8 as C\n\ntoGraph n = accumArray (flip (:)) [] (1, n)\n\ncolor n e = array (1, n) $ M.assocs $ foldl (dfs True) M.empty [1 .. n]\n where\n dfs t c v\n | M.member v c = c\n | True = foldl (dfs (not t)) (M.insert v t c) $ e!v\n\ntry12 n e r b\n | null u = Nothing\n | True = Just $ (u':v') ++ (delete u' r) ++ (b \\\\ v')\n where\n m = length b\n u = [i | i <- r, length (e!i) <= m - 2]\n u' = head u\n v = [j | j <- b, notElem u' $ e!j]\n v' = take 2 v\n\ntry42 n e r b\n | length v' < 6 = Nothing\n | True = Just $ v' ++ (r \\\\ v') ++ (b \\\\ v')\n where\n m = length b\n x = foldr1 xor b\n e' = toGraph n [(foldr xor x $ e!i, i) | i <- r, length (e!i) == m - 1]\n v' = concat $ take 2 [i: take 2 j | (i, j) <- assocs e', length j >= 2]\n\nyes v = putStrLn $ (\"YES\\n\" ++) $ unwords $ map show $ elems w\n where\n n = length v\n w = array (1,n) $ zip v $ concatMap (replicate 3) [1 ..]\n\nsolve n e =\n if m == 0\n then\n yes $ r ++ b\n else\n case try12 n e x y of\n Just z -> yes z\n _ ->\n case try42 n e x y of\n Just z -> yes z\n _ -> putStrLn \"NO\"\n where\n c = color n e\n r = [i | (i, e) <- assocs c, e]\n b = [i | (i, e) <- assocs c, not e]\n m = length r `mod` 3\n (x, y) = if m /= 2 then (r, b) else (b, r)\n\nget = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n\nmain = do\n [n, m] <- get\n e <- replicateM m get\n solve n $ toGraph n $ concat [[(i, j), (j, i)] | [i, j] <- e]\n\n"}], "negative_code": [], "src_uid": "bcdf156506ae8ec78f6fd5772b6deeb4"} {"source_code": "main = getContents >>= putStrLn . solve . read . head . words\n\nsolve 0 = []\nsolve n = (if n `mod` 2 == 0 then '0' else '1') : solve (n - 1)\n", "positive_code": [{"source_code": "\nimport Data.List.Split as Split\nimport Data.Bits\nimport Data.List\n\nstringToInt s = read s :: Int\n\nint_arr = map stringToInt . words\n\n\nmain = do\n n_m <- getLine\n let [n, m] = int_arr n_m\n ss <- (read_strings m)\n let num_arr = map show (most_beauty n (map int_arr ss))\n -- putStrLn (intercalate \" \" num_arr)\n putStrLn (foldl (\\acc s -> acc ++ s) [] num_arr)\n\nread_strings 0 = return []\nread_strings n = do\n s <- getLine\n ss <- (read_strings (n - 1))\n return (s:ss)\n\n\nmost_beauty :: Int -> [[Int]] -> [Int]\nmost_beauty n _ | n > 16 = [x `rem` 2 | x <- [1..n]]\nmost_beauty n lr_arr =\n variant n lr_arr (2 ^ n) (repr n (2 ^ n)) 0\n\n\nvariant :: Int -> [[Int]] -> Int -> [Int] -> Int -> [Int]\nvariant _ _ 0 best _best_score = best\nvariant n lr_arr v1 best best_score = \n let rv = repr n v1\n in case is_suitable rv of\n False -> variant n lr_arr (v1 - 1) best best_score\n True -> \n let b = beauty_sum rv lr_arr\n in if b > best_score \n then variant n lr_arr (v1 - 1) rv b\n else variant n lr_arr (v1 - 1) best best_score\n\n\nrepr :: Int -> Int -> [Int]\nrepr n v = [(bit 0).&.(shift v (1 - x)) | x <- (reverse [1..n])]\n\nbeauty_sum :: [Int] -> [[Int]] -> Int\nbeauty_sum mask lr_arr = sum (map (beauty mask) lr_arr)\n\nbeauty :: [Int] -> [Int] -> Int\nbeauty mask [l, r] =\n let m = take (r - l + 1) $ drop (l - 1) mask\n in (length $ filter (== 1) m) * (length $ filter (== 0) m)\n\n\n\n\nis_suitable (1:1:1:_) = False\nis_suitable (0:0:0:_) = False\nis_suitable [] = True\nis_suitable (x:xs) = is_suitable xs\n\n-- suitable _n _mask [False, False, False] = False\n-- suitable _n _mask [True, True, True] = False\n-- suitable 0 _mask _ = True\n-- suitable n mask prev =\n-- let p = testBit mask 0\n-- prev1 = case prev of \n-- [p1, p2, p3] -> [p, p1, p2]\n-- _ -> (p:prev)\n-- in suitable (n - 1) (shift mask (-1)) prev1\n\n\n\n\n\n\n-- possible n_d x_n =\n-- let [_n, d] = map stringToInt $ Split.splitOn \" \" n_d\n-- x = map stringToInt $ Split.splitOn \" \" x_n\n-- in show (2 + (behind d x))\n\n\n-- behind d (x1:[]) = 0\n-- behind d (x1:x2:xs) =\n-- case compare (2*d) (x2 - x1) of\n-- EQ -> 1 + behind d (x2:xs)\n-- GT -> behind d (x2:xs)\n-- LT -> 2 + behind d (x2:xs) \n\n"}], "negative_code": [{"source_code": "\nimport Data.List.Split as Split\nimport Data.Bits\nimport Data.List\n\nstringToInt s = read s :: Int\n\nint_arr = map stringToInt . words\n\n\nmain = do\n n_m <- getLine\n let [n, m] = int_arr n_m\n ss <- (read_strings m)\n let num_arr = map show (most_beauty n (map int_arr ss))\n -- putStrLn (intercalate \" \" num_arr)\n putStrLn (foldl (\\acc s -> acc ++ s) [] num_arr)\n\nread_strings 0 = return []\nread_strings n = do\n s <- getLine\n ss <- (read_strings (n - 1))\n return (s:ss)\n\n\nmost_beauty :: Int -> [[Int]] -> [Int]\nmost_beauty n lr_arr =\n variant n lr_arr (2 ^ n) (repr n (2 ^ n)) 0\n\n\nvariant :: Int -> [[Int]] -> Int -> [Int] -> Int -> [Int]\nvariant _ _ 0 best _best_score = best\nvariant n lr_arr v1 best best_score = \n let rv = repr n v1\n in case is_suitable rv of\n False -> variant n lr_arr (v1 - 1) best best_score\n True -> \n let b = beauty_sum rv lr_arr\n in if b > best_score \n then variant n lr_arr (v1 - 1) rv b\n else variant n lr_arr (v1 - 1) best best_score\n\n\nrepr :: Int -> Int -> [Int]\nrepr n v = [(bit 0).&.(shift v (1 - x)) | x <- (reverse [1..n])]\n\nbeauty_sum :: [Int] -> [[Int]] -> Int\nbeauty_sum mask lr_arr = sum (map (beauty mask) lr_arr)\n\nbeauty :: [Int] -> [Int] -> Int\nbeauty mask [l, r] =\n let m = take (r - l + 1) $ drop (l - 1) mask\n in (length $ filter (== 1) m) * (length $ filter (== 0) m)\n\n\n\n\nis_suitable (1:1:1:_) = False\nis_suitable (0:0:0:_) = False\nis_suitable [] = True\nis_suitable (x:xs) = is_suitable xs\n\n-- suitable _n _mask [False, False, False] = False\n-- suitable _n _mask [True, True, True] = False\n-- suitable 0 _mask _ = True\n-- suitable n mask prev =\n-- let p = testBit mask 0\n-- prev1 = case prev of \n-- [p1, p2, p3] -> [p, p1, p2]\n-- _ -> (p:prev)\n-- in suitable (n - 1) (shift mask (-1)) prev1\n\n\n\n\n\n\n-- possible n_d x_n =\n-- let [_n, d] = map stringToInt $ Split.splitOn \" \" n_d\n-- x = map stringToInt $ Split.splitOn \" \" x_n\n-- in show (2 + (behind d x))\n\n\n-- behind d (x1:[]) = 0\n-- behind d (x1:x2:xs) =\n-- case compare (2*d) (x2 - x1) of\n-- EQ -> 1 + behind d (x2:xs)\n-- GT -> behind d (x2:xs)\n-- LT -> 2 + behind d (x2:xs) \n\n"}, {"source_code": "\nimport Data.List.Split as Split\nimport Data.Bits\n\nstringToInt s = read s :: Int\n\nint_arr = map stringToInt . words\n\n\nmain = do\n n_m <- getLine\n let [n, m] = int_arr n_m\n ss <- (read_strings m)\n let num_arr = map show (most_beauty n (map int_arr ss))\n putStrLn (foldl (\\acc s -> acc ++ s ++ \" \") [] num_arr)\n\nread_strings 0 = return []\nread_strings n = do\n s <- getLine\n ss <- (read_strings (n - 1))\n return (s:ss)\n\n\nmost_beauty :: Int -> [[Int]] -> [Int]\nmost_beauty n lr_arr =\n variant n lr_arr (2 ^ n) (repr n (2 ^ n)) 0\n\n\nvariant :: Int -> [[Int]] -> Int -> [Int] -> Int -> [Int]\nvariant _ _ 0 best _best_score = best\nvariant n lr_arr v1 best best_score = \n let rv = repr n v1\n in case is_suitable rv of\n False -> variant n lr_arr (v1 - 1) best best_score\n True -> \n let b = beauty_sum rv lr_arr\n in if b > best_score \n then variant n lr_arr (v1 - 1) rv b\n else variant n lr_arr (v1 - 1) best best_score\n\n\nrepr :: Int -> Int -> [Int]\nrepr n v = [(bit 0).&.(shift v (1 - x)) | x <- (reverse [1..n])]\n\nbeauty_sum :: [Int] -> [[Int]] -> Int\nbeauty_sum mask lr_arr = sum (map (beauty mask) lr_arr)\n\nbeauty :: [Int] -> [Int] -> Int\nbeauty mask [l, r] =\n let m = take (r - l + 1) $ drop (l - 1) mask\n in (length $ filter (== 1) m) * (length $ filter (== 0) m)\n\n\n\n\nis_suitable (1:1:1:_) = False\nis_suitable (0:0:0:_) = False\nis_suitable [] = True\nis_suitable (x:xs) = is_suitable xs\n\n-- suitable _n _mask [False, False, False] = False\n-- suitable _n _mask [True, True, True] = False\n-- suitable 0 _mask _ = True\n-- suitable n mask prev =\n-- let p = testBit mask 0\n-- prev1 = case prev of \n-- [p1, p2, p3] -> [p, p1, p2]\n-- _ -> (p:prev)\n-- in suitable (n - 1) (shift mask (-1)) prev1\n\n\n\n\n\n\n-- possible n_d x_n =\n-- let [_n, d] = map stringToInt $ Split.splitOn \" \" n_d\n-- x = map stringToInt $ Split.splitOn \" \" x_n\n-- in show (2 + (behind d x))\n\n\n-- behind d (x1:[]) = 0\n-- behind d (x1:x2:xs) =\n-- case compare (2*d) (x2 - x1) of\n-- EQ -> 1 + behind d (x2:xs)\n-- GT -> behind d (x2:xs)\n-- LT -> 2 + behind d (x2:xs) \n\n"}], "src_uid": "cac8ca5565e06021a44bb4388b5913a5"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Arrow\nimport Data.Maybe\n\nmain = B.interact $ B.unlines . map (B.pack . show . ( (9*). pred *** id >>> uncurry (+)) . (\\[x,y] ->(x,y)) . map (fst . fromJust . B.readInteger) . B.words ) . tail . B.lines \n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n n <- readLn :: IO Int\n doQueries n\n\ndoQueries :: Int -> IO ()\ndoQueries 0 = return ()\ndoQueries n = do\n l <- getLine\n let (k:x:[]) = map read (words l)\n putStrLn $ show $ (k-1) * 9 + x\n doQueries (n-1)\n\ndig_root :: Int -> Int\ndig_root n = n - 9 * ((n-1) `div` 9)\n"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Arrow\nimport Data.Maybe\n\nmain = B.interact $ B.unlines . map (B.pack . show . ( (9*). pred *** id >>> uncurry (+)) . (\\[x,y] ->(x,y)) . map (fst . fromJust . B.readInt) . B.words ) . tail . B.lines \n"}], "src_uid": "891fabbb6ee8a4969b6f413120f672a8"} {"source_code": "import Data.List (intercalate, tails, isPrefixOf, head)\r\nimport Control.Monad (replicateM)\r\nimport Data.Maybe (fromJust, listToMaybe, catMaybes)\r\n\r\nmain = do t <- read <$> getLine\r\n replicateM t solve\r\n\r\nsolve = do getLine\r\n s <- getLine\r\n putStrLn (leastNonSubstring s)\r\n\r\nleastNonSubstring s = head $ catMaybes [leastOfLength l | l <- [1..]]\r\n where leastOfLength l = helper \"\" l\r\n helper prefix 0 | isSubstring prefix s = Nothing\r\n | otherwise = Just prefix\r\n helper prefix l = listToMaybe $ catMaybes [helper (prefix ++ [letter]) (l - 1) | letter <- ['a'..'z']]\r\n\r\nisSubstring s t = any id (map (isPrefixOf s) (tails t))", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Set as S\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nallStrings :: [String]\nallStrings = [] : [string ++ [ch] | string <- allStrings, ch <- ['a' .. 'z']]\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n output <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n s <- C.unpack <$> C.getLine\n let check str = not $ any (isPrefixOf str) $ tails s\n result = head $ filter check $ tail allStrings\n return $ string7 result `mappend` charUtf8 '\\n'\n hPutBuilder stdout output\n"}, {"source_code": "import Data.List (tails)\n\nalphabet = map pure ['a'..'z'] :: [String]\n\ngen' :: [String]\ngen' = \"\" : ( (++) <$> gen' <*> alphabet )\n\ngen = drop 1 gen'\n\nisPrefixOf :: (Eq a) => [a] -> [a] -> Bool\nisPrefixOf xs ys | length xs <= length ys = and $ zipWith (==) xs ys\n | otherwise = False\n\nisSubstr :: (Eq a) => [a] -> [a] -> Bool\nisSubstr xs ys = or $ map (xs `isPrefixOf`) $ tails ys\n\ndoTestCase :: IO ()\ndoTestCase = do _ <- getLine\n str <- getLine\n putStrLn . head $ dropWhile (`isSubstr` str) gen\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n\n"}, {"source_code": "import Data.List\r\n\r\n-- generate string\r\ngenstr :: [Char] -> Int -> [String]\r\ngenstr _ 0 = [\"\"]\r\ngenstr chars n = prev ++ (concat $ map jimmy chars)\r\n\twhere prev = genstr chars (n-1)\r\n\t jimmy c = map ((:) c) prev\r\n\r\njimmy :: String -> String\r\njimmy str = head $ filter (not.(flip isInfixOf str)) jim\r\n\twhere (_:jim) = genstr \"abcdefghijklmnopqrstuvwxyz\" (length str)\r\n\r\nhoo :: [String] -> [String]\r\nhoo [] = []\r\nhoo (a:b:cs) = b:(hoo cs)\r\n\r\nmain = interact $ unlines.(map jimmy).hoo.tail.lines"}, {"source_code": "import Data.List (tails, isPrefixOf)\n\n\nalphabet = map pure ['a'..'z'] :: [String]\n\ngen' :: [String]\ngen' = \"\" : ( (++) <$> gen' <*> alphabet )\n\ngen = drop 1 gen'\n\nisSubstr :: (Eq a) => [a] -> [a] -> Bool\nisSubstr xs ys = or $ map (xs `isPrefixOf`) $ tails ys\n\ndoTestCase :: IO ()\ndoTestCase = do getLine\n str <- getLine\n putStrLn . head $ dropWhile (`isSubstr` str) gen\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n\n"}], "negative_code": [{"source_code": "import Data.List (tails)\n\nalphabet = map pure ['a'..'z'] :: [String]\n\ngen' :: [String]\ngen' = \"\" : ( (++) <$> gen' <*> alphabet )\n\ngen = drop 1 gen'\n\nisPrefixOf :: (Eq a) => [a] -> [a] -> Bool\nisPrefixOf xs ys | length xs < length ys = and $ zipWith (==) xs ys\n | otherwise = False\n\nisSubstr :: (Eq a) => [a] -> [a] -> Bool\nisSubstr xs ys = or $ map (xs `isPrefixOf`) $ init $ tails ys\n\ndoTestCase :: IO ()\ndoTestCase = do _ <- getLine\n str <- getLine\n putStrLn . head $ dropWhile (`isSubstr` str) gen\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n\n"}, {"source_code": "import Data.List (tails)\n\nalphabet = map pure ['a'..'z'] :: [String]\n\ngen' :: [String]\ngen' = \"\" : ( (++) <$> gen' <*> alphabet )\n\ngen = drop 1 gen'\n\nisPrefixOf :: (Eq a) => [a] -> [a] -> Bool\nisPrefixOf xs ys = and $ zipWith (==) xs ys\n\nisSubstr :: (Eq a) => [a] -> [a] -> Bool\nisSubstr xs ys = or $ map (xs `isPrefixOf`) $ init $ tails ys\n\ndoTestCase :: IO ()\ndoTestCase = do _ <- getLine\n str <- getLine\n putStrLn . head $ dropWhile (`isSubstr` str) gen\n\nmain = do t <- readLn :: IO Int\n sequence_ $ replicate t doTestCase\n\n"}], "src_uid": "83a665723ca4e40c78fca20057a0dc99"} {"source_code": "\n\nsq :: Int -> Int -> (Int, Int)\nsq k i\n | k < i = (i - 1, k)\n | otherwise = sq (k-i) (i+1)\n\n-- if (k <= i * (i + 1) `div` 2 + i) then (i, k - i * (i+1) `div` 2) else sq k (i+1)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k ids = ids !! index\n where\n (a,b) = sq k 0\n index = (b + a - 1) `mod` a\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n,k] = map read (words line) :: [Int]\n line2 <- getLine\n let ids = map read (words line2) :: [Int]\n print (solve n k ids)\n", "positive_code": [{"source_code": "main :: IO()\nmain = print . solve . map read . words =<< getContents\n\nnatureSum :: Int -> Int\nnatureSum n | odd n = n * div (n + 2) 2\n | otherwise = div n 2 * (n + 1)\n\nfindBottom :: Int -> Int -> Int -> Int -> Int\nfindBottom l r k b | l > r = b\n | otherwise = let mid = div (l + r) 2\n m = natureSum mid\n in if m <= k\n then findBottom (mid + 1) r k (max b m)\n else findBottom l (mid - 1) k b\n\nsolve :: [Int] -> Int\nsolve (n:k:id) = let m = findBottom 1 (min n 63246) (k - 1) 0\n in id !! (k - m - 1)\n"}, {"source_code": "module Main where\n\n-- correct, but SLOW\nthisSeq = concat $ map (\\x->[0..x]) [0..]\n\ntriSeq :: [Integer]\ntriSeq = map (\\x-> x * (x + 1) `div` 2) [1..]\n\nrevIdx 0 = 0\nrevIdx k = k - (last $ takeWhile (<= k) triSeq)\n\npronounce xs k = xs !! (fromInteger (revIdx k))\n\nmain = do\n l0 <- getLine\n l1 <- getLine\n let [_, k] = map (\\w->read w::Integer) $ words l0\n ids = map (\\w->read w::Integer) $ words l1\n print $ pronounce ids (k - 1)\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\n\nsolve :: [Int] -> Int -> Int -> Int\nsolve ids k me | k <= me = ids !! (k - 1)\n | otherwise = solve ids (k - me) (me + 1)\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n,k] = map read (words line) :: [Int]\n line2 <- getLine\n let ids = map read (words line2) :: [Int]\n putStrLn $ show (solve ids k 1)\n"}], "negative_code": [], "src_uid": "9ad07b42358e7f7cfa15ea382495a8a1"} {"source_code": "import Control.Monad\nimport Data.Bits\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b] <- readInts\n let x = a .|. b\n print $ xor a x + xor b x\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\nimport Data.Bits (Bits (xor))\n\nmain :: IO ()\nmain = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> map show >>> unlines\n\nsolve :: [Int] -> Int\nsolve [x, y] = x `xor` y\n"}, {"source_code": "import Data.Bits\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n numCases <- getLine\n replicateM_ (read numCases) solveTest\n\nsolveTest :: IO ()\nsolveTest = do\n ln <- getLine\n let lnData = map read (words ln) \n let (a, b) = (lnData !! 0, lnData !! 1)\n let answer = minXor a b\n putStrLn (show answer)\n\nminXor :: Int -> Int -> Int\nminXor a b =\n let maxBits = max (bitCount a) (bitCount b)\n bits = reverse $ map (combineBits a b) [0..maxBits]\n x = numFromBits bits\n in sumXor a b x\n\ncombineBits :: Int -> Int -> Int -> Bool\ncombineBits a b n = if (testBit a n) == (testBit b n) then testBit a n else False\n\nnumFromBits :: [Bool] -> Int\nnumFromBits bits = sum (zipWith (*) realBits values)\n where realBits = map (\\b -> if b == True then 1 else 0) (reverse bits)\n values = map ((^) 2)[0..length bits - 1]\n\nsumXor :: Int -> Int -> Int -> Int\nsumXor a b x = (xor a x) + (xor b x)\n\nbitCount :: Int -> Int\nbitCount n = 1 + floor (logBase 2 (fromIntegral n))\n"}, {"source_code": "import Data.Bits\n\nsolve :: IO ()\nsolve = do\n str <- getLine\n let (a:b:[]) = map read $ words str :: [Int]\n print $ a + b - 2 * (a .&. b)\n\nmain = do\n tests_str <- getLine\n sequence $ take (read tests_str) $ repeat solve\n"}], "negative_code": [], "src_uid": "4be3698735278f29b307a7060eb69693"} {"source_code": "groupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\nmain = interact $ unlines . parse . lines\n\nparse [st,nd] = sol s n\n where\n (s, n) = (fn $ words st, fn $ words nd)\n fn :: [String] -> [Int]\n fn xs = map read xs\n\nsol [h, a, c] [hh, aa] = (show $ length res) : res\n where\n res = sol' h hh\n sol' h hh\n | hha <= 0 = [\"STRIKE\"]\n | haa <= 0 = \"HEAL\" : sol' (haa+c) hh\n | otherwise = \"STRIKE\" : sol' haa hha\n where haa = h-aa\n hha = hh-a\n", "positive_code": [{"source_code": "main = getContents >>= putStr . exec\nexec = unlines . (\\xs -> show (length xs):xs) . solve . map read . words\n\nsolve [h1, a1, c1, h2, a2] = go h1 h2\n where\n go h1 h2\n | h2 <= 0 = []\n | h2 > a1 && a2 >= h1 = \"HEAL\":go (h1 + c1 - a2) h2\n | otherwise = \"STRIKE\":go (h1 - a2) (h2 - a1)"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [h1, a1, c1, h2, a2] <- map read . words <$> getContents\n let s = ((h2 - 1) `div` a1) + 1;\n h = head [t | t <- [0 ..], h1 + t * c1 > (t + s - 1) * a2]\n print $ s + h\n putStr . unlines $ replicate h \"HEAL\" ++ replicate s \"STRIKE\"\n"}], "negative_code": [{"source_code": "main = getContents >>= putStr . exec\nexec = unlines . (\\xs -> show (length xs):xs) . solve . map read . words\n\nsolve [h1, a1, c1, h2, a2] = go h1 h2\n where\n go h1 h2\n | h2 <= 0 = []\n | a2 >= h1 = \"HEAL\":go (h1 + c1 - a2) h2\n | otherwise = \"STRIKE\":go (h1 - a2) (h2 - a1)"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = do\n [h1, a1, c1, h2, a2] <- map read . words <$> getContents\n let s = ((h2 - 1) `div` a1) + 1;\n h = head [t | t <- [0 ..], h1 + t * c1 > (s - 1) * a2]\n print $ s + h\n putStr . unlines $ replicate h \"HEAL\" ++ replicate s \"STRIKE\"\n"}, {"source_code": "groupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n-------------------------------------------------------------------------------\n\nmain = interact $ unlines . parse . lines\n\nparse [st,nd] = sol s n\n where\n (s, n) = (fn $ words st, fn $ words nd)\n fn :: [String] -> [Int]\n fn xs = map read xs\n\nsol [h, a, c] [hh, aa] = (show $ length res) : res\n where\n res = sol' h hh\n sol' h hh\n | h <= 0 = [\"Problem\"]\n | hh <= 0 = []\n | haa <= 0 = \"HEAL\" : sol' (haa+c) hh\n | otherwise = \"STRIKE\" : sol' haa (hh-a)\n where haa = h-aa\n"}], "src_uid": "d497431eb37fafdf211309da8740ece6"} {"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n as <- readInts\r\n let (xs, ys) = partition even as\r\n sorted = and . (zipWith (<=) <*> tail)\r\n putStrLn $ if sorted xs && sorted ys then \"Yes\" else \"No\"\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (sort, partition)\n\nsorted = and . (zipWith (<=) <*> tail)\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n let (xs, ys) = partition even arr\n putStrLn $ if sorted xs && sorted ys then \"Yes\" else \"No\"\n"}, {"source_code": "{-# LANGUAGE ParallelListComp #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule Main where\n\nimport Control.Applicative ( liftA2 )\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function ( (&) )\nimport Data.List\nimport Data.Maybe ( fromJust )\n\ntype Scanner = State [C.ByteString]\n\nscan :: Scanner a -> C.ByteString -> a\nscan input = evalState input . C.lines\n\nline :: Scanner C.ByteString\nline = get >>= \\case\n [] -> error \"eof\"\n s : ss -> put ss >> return s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case\n [] -> return []\n _ -> liftA2 (:) s $ many s\n\nmain :: IO ()\nmain = C.interact solve\n\nsolve :: C.ByteString -> C.ByteString\nsolve input =\n input\n & scan parse\n & map (format . answer)\n & C.unlines\n\nparse :: Scanner [[Int]]\nparse = do\n _ <- line\n many $ do\n _ <- line\n map (fst . fromJust . C.readInt) . C.words <$> line\n\nformat :: Bool -> C.ByteString\nformat True = C.pack \"Yes\"\nformat False = C.pack \"No\"\n\nanswer :: [Int] -> Bool\nanswer xs = sorted os && sorted es\n where (os, es) = partition odd xs\n\nsorted :: Ord a => [a] -> Bool\nsorted xs = and [ x <= x' | x <- xs | x' <- tail xs ]\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve [] _ _ = True\nsolve (x:xs) o e\n | (x `rem` 2) == 0 = if (e > x) then False else solve xs o x\n | (x `rem` 2) == 1 = if (o > x) then False else solve xs x e\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ if solve arr 0 0 then \"YES\" else \"NO\"\n"}, {"source_code": "import Control.Monad (forM)\nimport Data.List\n\nsolve t = do \n n <- readLn::IO Int\n arr <- getLine >>= \\s -> return $ map (read::String -> Int) (words s)\n let e = [ x | x <- arr, even x]\n o = [ x | x <- arr, odd x ]\n if sort e /= e || sort o /= o then putStrLn \"NO\" else putStrLn \"YES\"\n\nmain = do\ntlen <- readLn :: IO Int\nforM [0..(tlen - 1)] (\\t -> do solve t)\n\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let\r\n (ae, ao) = partition even a\r\n isSorted li = and $ zipWith (<=) li (tail li)\r\n pure $ string7 $ if isSorted ae && isSorted ao\r\n then \"Yes\\n\"\r\n else \"No\\n\"\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n{-\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n-}\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ParallelListComp #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule Main where\n\nimport Control.Applicative ( liftA2 )\nimport Control.Monad.State\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function ( (&) )\nimport Data.List\nimport Data.Maybe ( fromJust )\n\ntype Scanner = State [C.ByteString]\n\nscan :: Scanner a -> C.ByteString -> a\nscan input = evalState input . C.lines\n\nline :: Scanner C.ByteString\nline = get >>= \\case\n [] -> error \"eof\"\n s : ss -> put ss >> return s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case\n [] -> return []\n _ -> liftA2 (:) s $ many s\n\nmain :: IO ()\nmain = C.interact solve\n\nsolve :: C.ByteString -> C.ByteString\nsolve input = input & scan parse & map (format . answer) & C.unlines\n\nparse :: Scanner [[Int]]\nparse = do\n _ <- line\n many $ do\n _ <- line\n map (fst . fromJust . C.readInt) . C.words <$> line\n\nformat :: Bool -> C.ByteString\nformat True = C.pack \"Yes\"\nformat False = C.pack \"No\"\n\nanswer :: [Int] -> Bool\nanswer xs = all (\\(x, x') -> odd $ x + x') swaps\n where\n xs' = sort xs\n swaps = filter (uncurry (/=)) [ (x, x') | x <- xs | x' <- xs' ]\n"}], "src_uid": "a97e70ad20a337d12dcf79089c16c9f0"} {"source_code": "import Data.List as L\n\ndec :: Int -> Int\ndec n = n-1\n\nsolve' :: [String] -> Int -> Int -> Int -> Int -> Int\nsolve' [] ans _ _ _ = ans\nsolve' (option:others) ans a b c = case option of\n \"A\" -> if a /= 0 then solve' others (ans+1) (dec a) b c\n else solve' others ans a b c\n \"B\" -> if b /= 0 then solve' others (ans+1) a (dec b) c\n else solve' others ans a b c\n \"C\" -> if c /= 0 then solve' others (ans+1) a b (dec c)\n else solve' others ans a b c\n \"AB\" -> if a/=0 && b/=0 then solve' others (ans+1) (dec a) (dec b) c\n else solve' others ans a b c\n \"BC\" -> if b/=0 && c/=0 then solve' others (ans+1) a (dec b) (dec c)\n else solve' others ans a b c\n \"AC\" -> if a/=0 && c/=0 then solve' others (ans+1) (dec a) b (dec c)\n else solve' others ans a b c\n \"ABC\" -> if a/=0 && b/=0 && c/=0 then solve' others (ans+1) (dec a) (dec b) (dec c)\n else solve' others ans a b c\n\nsolve :: Int -> Int -> Int -> Int\nsolve a b c = solve' [\"A\", \"B\", \"C\", \"AB\", \"BC\", \"AC\", \"ABC\"] 0 c' b' a'\n where [a', b', c'] = L.sort [a, b, c]\n\nparse :: String -> String\nparse input = show $ solve a b c\n where [a, b, c] = map (\\x -> read x :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . (L.map parse) . tail . lines)\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >>= print.solve1.map read.words >> test (n - 1)\n\nsolve1 as = length (filter (> 0) as) + solve2 (subtract 1 <$> as)\nsolve2 as\n | length (filter (> 0) as) < 2 = 0\n | length (filter (> 0) as) == 2 = 1\n | length (filter (> 1) as) == 0 = 1 \n | length (filter (> 1) as) == 1 = 2 \n | length (filter (> 1) as) == 2 = 2\n | otherwise = 3 + solve3 (subtract 2 <$> as)\nsolve3 as = fromEnum $ all (> 0) as\n"}], "negative_code": [], "src_uid": "98a8fc06e8265bbf9c16ee3c7b9d0223"} {"source_code": "\nmain = do\n\targs <- getContents\n\tlet \n\t\t(n:xs) = words args\n\t\tab = cov xs\n\tmapM print $ map cal ab\n\ncov :: [String] -> [(Int,Int)]\ncov [] = []\ncov (x:y:remain) = (read x, read y):cov remain\n\ncal :: (Int,Int) -> Int\ncal (x,y) \n\t| y == 0 = 0\n\t| otherwise = x `div` y + cal (y,(x `mod` y))\n", "positive_code": [{"source_code": "module Main where\n\n\nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b \n\t| a >= b = (a `div` b) + solve b (a `mod` b) \n\t| otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n\tnumsStr <- getLine\n\tlet [x, y] = map read $ words numsStr\n\tprint $ solve x y\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do \n\tprintSolution\n\tprintNSolutions (n-1)\n\nmain = getLine >>= (printNSolutions . read)"}, {"source_code": "main = do\n\t\targs <- getContents\n\t\tlet \n\t\t\t(n:xs) = words args\n\t\t\tab = go xs\n\t\tmapM print $ map calc ab\n\t\t\n\ngo :: [String] -> [ (Int, Int) ]\ngo [] = []\ngo (a:b:xs) = (read a, read b):go xs\n\ncalc :: (Int, Int) -> Int\ncalc (a, b)\n\t\t| a == 0 = 0\n\t\t| b == 0 = 0\n\t\t| otherwise = div a b + calc(b, mod a b)\n"}, {"source_code": "combine :: [Int] -> [(Int, Int)]\ncombine (a:(b:c)) = (a, b) : combine c\ncombine _ = []\n\nans :: (Int, Int) -> Int\nans (a, b)\n | a == 0 || b == 0 = 0\n | a <= b = div b a + ans (a, mod b a)\n | otherwise = ans (b, a)\n\nprintAns :: [Int] -> IO()\nprintAns (a:b) = do\n putStrLn (show a)\n printAns b\nprintAns _ = do\n putStr \"\"\n\nmain :: IO()\nmain = do\n str <- getContents\n let pairs = combine (map read ((tail . words) str))\n printAns (map ans pairs)\n"}, {"source_code": "module Main where\nimport Prelude\nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n \nmain = do\n nStr <- getLine\n printNSolutions $ (read nStr :: Int)\n"}, {"source_code": "module Main where\nimport Prelude \nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n \nmain = do\n nStr <- getLine\n printNSolutions $ (read nStr :: Int)\n"}, {"source_code": "-- http://codeforces.ru/problemset/problem/267/A\nimport Data.List\nimport Control.Monad\n-- helpers\ngetInt = \\x -> read x :: Int\ngetPair str = (getInt $ lst !! 0, getInt $ lst !! 1) where lst = words str\n\nsolve :: (Int,Int) -> Int\nsolve (_,0) = 0\nsolve (0,_) = 0\nsolve (x,y) =\n acc' + (solve (mn,rm))\n where\n (mn, mx) = (min x y, max x y)\n (acc', rm) = mx `divMod` mn\n\nmain = do\n count <- fmap getInt getLine\n pairs <- replicateM count getLine\n let ps = map getPair pairs\n ss = map solve ps\n mapM_ putStrLn $ map show ss\n{-\n\u0417\u0430\u0434\u0430\u043d\u044b \u0434\u0432\u0430 \u0447\u0438\u0441\u043b\u0430. \u0414\u043e \u0442\u0435\u0445 \u043f\u043e\u0440, \u043f\u043e\u043a\u0430 \u043e\u0431\u0430 \u043e\u043d\u0438 \u0431\u043e\u043b\u044c\u0448\u0435 \u043d\u0443\u043b\u044f, \u0441 \u043d\u0438\u043c\u0438 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u044f\u0442 \u043e\u0434\u043d\u0443 \u0438 \u0442\u0443 \u0436\u0435 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e: \u0438\u0437 \u0431\u043e\u043b\u044c\u0448\u0435\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0432\u044b\u0447\u0438\u0442\u0430\u044e\u0442 \u043c\u0435\u043d\u044c\u0448\u0435\u0435. \u0415\u0441\u043b\u0438 \u0447\u0438\u0441\u043b\u0430 \u0440\u0430\u0432\u043d\u044b, \u0442\u043e \u0438\u0437 \u043e\u0434\u043d\u043e\u0433\u043e \u0432\u044b\u0447\u0438\u0442\u0430\u044e\u0442 \u0434\u0440\u0443\u0433\u043e\u0435. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0437 \u043f\u0430\u0440\u044b (4,17) \u0437\u0430 \u043e\u0434\u043d\u0443 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044e \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442\u0441\u044f \u043f\u0430\u0440\u0430 (4,13), \u0430 \u0438\u0437 \u043f\u0430\u0440\u044b (5,5) \u043f\u0430\u0440\u0430 (0,5).\n\n\u0412\u0430\u043c \u0437\u0430\u0434\u0430\u043d\u043e \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0440 (ai,\u2009bi). \u0421\u043a\u043e\u043b\u044c\u043a\u043e \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0439 \u0431\u0443\u0434\u0435\u0442 \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u043e \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0438\u0437 \u043d\u0438\u0445?\n\n\u0412\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\u0412 \u043f\u0435\u0440\u0432\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435 \u0437\u0430\u0434\u0430\u043d\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0430\u0440 n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u20091000). \u0414\u0430\u043b\u0435\u0435 \u0438\u0434\u0443\u0442 n \u0441\u0442\u0440\u043e\u043a, \u043a\u0430\u0436\u0434\u0430\u044f \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043f\u0430\u0440\u0443 \u0446\u0435\u043b\u044b\u0445 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u0447\u0438\u0441\u0435\u043b ai,\u2009bi (1\u2009\u2009\u2264\u2009\u2009ai,\u2009\u2009bi\u2009\u2009\u2264\u2009\u2009109).\n\n\u0412\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u0441\u043a\u043e\u043c\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0439 \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u043f\u0430\u0440\u044b \u043d\u0430 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0435.\n\n\u041f\u0440\u0438\u043c\u0435\u0440\u044b \u0442\u0435\u0441\u0442\u043e\u0432\n\u0432\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n2\n4 17\n7 987654321\n\u0432\u044b\u0445\u043e\u0434\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n8\n141093479\n-}"}, {"source_code": "f [a,b] | a == 0 = 0 | a > b = f [b, a] | 1 > 0 = div b a + f [mod b a, a]\nmain = interact $ unlines . map (show . f . map read . words) . tail . lines"}, {"source_code": "f [0, _] = 0\nf [a, b]\n | a > b = f [b, a]\n | otherwise = b `div` a + f [(b `mod` a), a]\n\nmain = interact $ unlines . map (show . f . map read . words) . tail . lines"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n \nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Data.Foldable (foldr', foldr1)\nimport Prelude\nimport Control.Monad.State.Strict\nimport Data.Int\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Map.Strict as MapS\nimport qualified Data.Set as Set\n \nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\ncalculateGcd a b\n | (a == 0) || (b == 0) = 0\n | otherwise = (calculateGcd b (a `mod` b)) + (a `div` b)\n\nmain :: IO ()\nmain = do\n n <- readB8Int <$> B8.getLine\n replicateM_ n $ do\n [a, b] <- (map readB8Int) <$> B8.words <$> B8.getLine\n printf \"%d\\n\" $ calculateGcd a b\n"}, {"source_code": "import Control.Monad\ngcd' :: [Int] -> Int\ngcd' [0, a] = 0\ngcd' [a, b] = gcd' [(b`mod`a), a] + b `div` a\nmain = do\n n <- (fmap read getLine) :: IO Int\n list <- replicateM n $ (fmap (map read.words) getLine) :: IO [[Int]]\n let slist = [[(max a b), (min a b)] | [a, b] <- list]\n mapM print $ map gcd' slist\n"}, {"source_code": "solve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve n1 n2 \n\t| n1 >= n2 = n1 `div` n2 + solve n2 (n1 `mod` n2)\n\t| otherwise = solve n2 n1\n\nprintSolution :: IO ()\nprintSolution = do\n\tnumsStr <- getLine\n\tlet [n1, n2] = map read $ words numsStr\n\tprint $ solve n1 n2\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n\tprintSolution\n\tprintNSolutions (n-1)\n\nmain = do\n\tnStr <- getLine\n\tprintNSolutions $ read nStr"}, {"source_code": "module Main where\n\nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n \nmain = do\n nStr <- getLine\n printNSolutions $ (read nStr :: Int)"}, {"source_code": "main :: IO ()\nmain = do\n\t n <-getLine\n\t let num = read n\n\t printSolve num\n\nprintSolve :: Int -> IO ()\nprintSolve 1 = solving\nprintSolve n = do\n\t solving\n\t printSolve (n-1)\n\nsolving :: IO ()\nsolving = do\n\t numargs <- getLine\n\t let [arg1, arg2] = map read $ words numargs\n\t print $ solve arg1 arg2\n\nsolve :: Int -> Int -> Int\nsolve _ 0 = 0\nsolve 0 _ = 0\nsolve a b\n |a >= b = (a `div` b) + solve b (a `mod` b)\n |otherwise = solve b a\n\n\n\n\n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmain=interact$unlines.map show.f.tail.map read.words\nf(x:y:rest)=g 0 x y : f rest\nf _ = []\n\ng !ans !x !y\n | x==0 || y==0 = ans\n | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x\n | x > y = let (!q,!r) = quotRem x y in g (ans+q) r y\n | otherwise = ans + 1"}, {"source_code": "module Main where\n\nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n \nmain = do\n nStr <- getLine\n printNSolutions $ (read nStr :: Int)\n \n"}, {"source_code": "solve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n \nmain = do\n nStr <- getLine\n printNSolutions $ (read nStr :: Int)"}, {"source_code": "solve :: Int -> Int -> Int\nsolve a b\n | a == 0 || b == 0 = 0\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 0 = return ()\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n\nmain = do\n nStr <- getLine\n printNSolutions (read nStr :: Int)"}, {"source_code": "module Main where\n\nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let nums = map (read :: String -> Int) $ words numsStr\n print $ solve (nums!!0) (nums!!1)\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions (n-1)\n \nmain = do\n nStr <- getLine\n printNSolutions $ (read nStr :: Int)"}, {"source_code": "import Data.Char\nimport Data.List\n\nans [a,0] = 0\nans [a,b] = a`div`b + ans [b,(a`mod`b)] \n\nmain = do \n n<-getLine\n a<-getContents\n let input = map (map (\\x->read x::Int)) (map words $ lines a)\n putStrLn.unlines $ map show $ map ans input"}, {"source_code": "\nsolve :: Int -> Int -> Int\nsolve 0 _ = 0\nsolve _ 0 = 0\nsolve a b\n | a >= b = (a `div` b) + solve b (a `mod` b)\n | otherwise = solve b a\n\nprintSolution :: IO ()\nprintSolution = do\n numsStr <- getLine\n let [ n1, n2 ] = map read $ words numsStr\n print $ solve n1 n2\n\nprintNSolutions :: Int -> IO ()\nprintNSolutions 1 = printSolution\nprintNSolutions n = do\n printSolution\n printNSolutions ( n - 1 )\n\nmain = getLine >>= ( printNSolutions . read )\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmain=interact$unlines.map show.f.tail.map read.words\nf(x:y:rest)=g 0 x y : f rest\nf _ = []\n\ng !ans !x !y\n | x==0 || y==0 = ans\n | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x\n | x > y = let (!q,!r) = quotRem y x in g (ans+q) r y\n | otherwise = 1"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmain=interact$unlines.map show.f.tail.map read.words\nf(x:y:rest)=g 0 x y : f rest\nf _ = []\n\ng !ans !x !y\n | x==0 || y==0 = ans\n | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x\n | x > y = let (!q,!r) = quotRem y x in g (ans+q) r y\n | otherwise = ans + 1"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmain=interact$unlines.map show.f.tail.map read.words\nf(x:y:rest)=g 0 x y : f rest\nf _ = []\n\ng !ans !x !y\n | x==0 || y==0 = ans\n | x < y = let (!q,!r) = quotRem y x in g (ans+q) r x\n | x > y = let (!q,!r) = quotRem y x in g (ans+q) r y\n | otherwise = 2"}], "src_uid": "5c3eb78a7e15d9afe6d745e1a77d7451"} {"source_code": "{-# LANGUAGE MultiWayIf, TypeApplications, OverloadedStrings #-}\n\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Internal as BSI\nimport qualified Data.ByteString.Lazy.Char8 as BL\nimport Data.Maybe\n\ncf x = readLn >>= (`replicateM_` x)\n\nr p bs =\n let l = BS.length bs\n in fmap (BS.index bs) [l - 1,l - 2 .. 0]\n\nmain =\n cf $ do\n len <- readLn @Int\n line <- BS.getLine\n let p = not . BSI.isSpaceChar8\n n1 = (read @Int) $ reverse $ head $ words $ r p line\n n2 = fst $ fromJust $ BS.readInt $ BS.takeWhile p line\n BS.putStr $\n if n1 == len || n2 == len\n then BS.intercalate \" \" $ reverse $ BS.words line\n else \"-1\"\n putStrLn \"\"\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf, TypeApplications #-}\n\nimport Control.Monad\n\nmain = do\n numCases <- readLn\n replicateM_ numCases $ do\n len <- readLn @Int\n nums_ <- getLine\n let nums = words $ nums_\n putStrLn $\n if read (head nums) == len || read (last nums) == len\n then unwords $ reverse nums\n else \"-1\"\n"}], "negative_code": [], "src_uid": "69bbc06c385d51f78ce1f64afffb4cf1"} {"source_code": "module Main where\n\nimport Data.Char\n\n--foo :: String -> Int\nfinds n m = length $ filter (== m) n\n\nmain = do\n n <- getLine\n s <- getLine\n let p = (finds s '1')\n let q = (finds s '0')\n print (if p >= q then p-q else q-p)\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Data.List\n\n \n \n\nmain=do\t \n\tn<- read <$> getLine ::IO Int\n\ta<- getLine \n\tlet b1= length $ filter (=='1') a\n\tprint $ abs ((n-b1)-b1)"}, {"source_code": "ans [] = 0\nans (x:xs) = if x == '0' then ans xs + 1\n else ans xs - 1\n\nmain = do\n numInputs <- getLine\n digs <- getLine\n print(abs(ans digs))"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List (foldl')\n\nparse :: String -> String\nparse contents = s where [_, s] = lines contents\n\nsolve :: String -> Int\nsolve = length . foldl' step []\n where step [] !a = [a]\n step (s : ss) !a\n | s /= a = ss\n | otherwise = a : s : ss\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}, {"source_code": "import Data.List (partition)\n\nprocess :: [Char] -> Int\nprocess s = abs ((length s1)-(length s0))\n where\n (s0,s1) = partition (=='0') s\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n s <- getLine\n print $ process s"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve . head .tail.lines\n\nsolve :: String -> Int\nsolve xs = abs $ (-) (length . filter (=='1') $ xs) (length . filter (=='0') $ xs)"}, {"source_code": "main :: IO()\nmain = print . solve . head . tail . words =<< getContents\n\nsolve :: String -> Int\nsolve s = solve' s [] 0\n\nsolve' :: String -> [Char] -> Int -> Int\nsolve' [] _ num = num\nsolve' (c:cs) [] 0 = solve' cs [c] 1\nsolve' (c:cs) (s:ss) num | c == s = solve' cs (c:s:ss) (num+1)\n | otherwise = solve' cs ss (num-1)\n"}, {"source_code": "module Main where\n\ntoInt :: String -> Int\ntoInt s = read s :: Int\n\ntoIntList :: String -> [Int]\ntoIntList s = map toInt $ words s\n\nreadInt :: IO Int\nreadInt = fmap toInt getLine\n\nreadIntPair :: IO (Int, Int)\nreadIntPair = do\n (x:y:[]) <- fmap (map toInt . words) getLine\n return (x, y)\n\nreadIntList :: IO [Int]\nreadIntList = fmap (map toInt . words) getLine\n\nreadNStrings :: Int -> IO [String]\nreadNStrings n = sequence $ replicate n getLine\n\nreadNIntLists :: Int -> IO [[Int]]\nreadNIntLists n = fmap (map (\\s -> toIntList s)) (readNStrings n)\n\n-------------------------------------------------------------------------\n-------------------------------------------------------------------------\n\nprocess :: Char -> [Char] -> [Char]\nprocess '0' ('1':xs) = xs\nprocess '1' ('0':xs) = xs\nprocess x xs = x:xs\n\nmain = do\n n <- getLine\n s <- getLine\n let r = foldr process [] s\n print $ length r"}, {"source_code": "-- http://codeforces.com/problemset/problem/556A.hs\n\n--------------------------------\n\nreduceString :: String -> String\nreduceString str = reduceString' [] str\n\twhere\n\t\treduceString' acum [] = reverse acum\n\t\treduceString' acum (x:[]) = reverse $ (x:acum)\n\t\treduceString' [] (x:xs)\n\t\t\t| x /= head xs = reduceString' [] (tail xs)\n\t\t\t| otherwise = reduceString' [x] xs\n\t\treduceString' acum (x:xs)\n\t\t\t| x /= head xs = reduceString' (tail acum) (head acum : tail xs)\n\t\t\t| otherwise = reduceString' (x:acum) xs\n\n\n\n--------------------------------\n\nmain = do\n\n\t_ <- getLine\n\tstr <- getLine\n\n\tlet\n\t\treduced = reduceString str\n\n\tputStrLn $ show $ length reduced"}, {"source_code": "main = do\n getLine\n s <- getLine\n let\n c1 = length $ filter (== '1') s\n c2 = length $ filter (== '0') s\n\n print $ abs $ c1-c2\n"}, {"source_code": "main = getContents >>= putStrLn . show . solve . last . words\n\nsolve :: String -> Int\nsolve cs = n - 2 * min p q\n where n = length cs\n p = length $ filter (== '0') cs\n q = length $ filter (== '1') cs\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char (toLower)\nimport Data.List (intersperse)\nimport System.IO\n\nsolve :: String -> String\nsolve str = show $ abs $ count '0' str - count '1' str\n where count ch = length . filter (==ch)\n\nmain :: IO ()\nmain = do\n hSetBuffering stdin $ BlockBuffering Nothing\n hSetBuffering stdout $ BlockBuffering Nothing\n getLine\n str <- getLine\n putStrLn $ solve str\n"}, {"source_code": "answer::[Char] -> Int\nanswer a = abs ((length (filter (=='0') a)) - (length (filter (=='1') a)))\nmain = do\n w0 <- getLine\n w1 <- getLine\n print $ answer w1\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\a->solve =<< (map (fst.fromJust.C.readInt).C.words.C.intersperse ' '<$>C.getLine)\nsolve xs = print $ abs $ foldr (\\a b-> if a>0 then 1+b else b-1) 0 xs"}, {"source_code": "remove01 [] bs = length bs\nremove01 ('1':'0':as) [] = remove01 as [] \nremove01 ('1':'0':as) (b:bs) = remove01 (b:as) bs\nremove01 ('0':'1':as) [] = remove01 as [] \nremove01 ('0':'1':as) (b:bs) = remove01 (b:as) bs \nremove01 (a:as) bs = remove01 as (a:bs) \n\n\nmain = getLine >> getLine >>= print . (\\x -> remove01 x [] )\n\n"}, {"source_code": "-- Codeforces 556A\n\n-- Hint: If there still exist at least one 0 and at least one 1 in the string \n-- then there obviously exists either substring 01 or substring 10 (or both) \n-- and we can remove it. \n-- The order in which we remove substrings is unimportant: in any case we will \n-- make min(#zeros,\u2009#ones) such operations. \n-- Thus the answer is #ones\u2009+\u2009#zeros\u2009-\u20092min(#ones,\u2009#zeros)\u2009=\u2009|#ones\u2009-\u2009#zeros|.\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= print . abs . solve where\n solve xs = (length $ filter (== '1') xs) - (length $ filter (== '0') xs)\n"}, {"source_code": "apply_operation :: [Char] -> [Char]\napply_operation [] = []\napply_operation (x:xs) \n | null rest = [x]\n | x == (head rest) = (x:rest)\n | otherwise = tail rest\n where rest = apply_operation xs\n \nmain :: IO() \nmain = do _ <- getLine \n bitstring <- getLine \n print (length $ apply_operation bitstring) "}, {"source_code": "apply_operation :: [Char] -> [Char] \napply_operation bitstring = foldr loop \"\" bitstring \n where loop y \"\" = [y] \n loop y (x:xs) \n | x == y = y:(x:xs) \n | otherwise = xs \n \nmain :: IO() \nmain = do _ <- getLine \n bitstring <- getLine \n print (length $ apply_operation bitstring)"}, {"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\nsolve input =\n let aswords = words input\n n:p:_ = aswords\n in show . solve' $ p\n\n\nsolve' :: String -> Int\nsolve' = length . reducedStr\n where\n reducedStr :: String -> String\n reducedStr \"\" = \"\"\n reducedStr \"1\" = \"1\"\n reducedStr \"0\" = \"0\"\n reducedStr str\n | reduced == \"\" = f:[]\n | f == f' = f:reduced\n | otherwise = rest'\n where (f:rest) = str\n reduced = reducedStr rest\n (f':rest') = reduced\n\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n--process::C.ByteString->C.ByteString\n\n--process q | C.null q = C.empty\n-- | C.length q ==1 = q\n-- | C.take 2 q==(C.pack \"10\") = process (C.drop 2 q)\n-- | C.take 2 q ==(C.pack \"01\") = process (C.drop 2 q)\n-- | otherwise = C.cons (C.head q ) ( process (C.tail q))\n\n\n\n--myfix::(C.ByteString->C.ByteString)->C.ByteString->C.ByteString\n--myfix f q | q==qq = q\n-- | otherwise = myfix f (f q)\n-- where qq = f q\nprocess::Int->String->String->Int\nprocess n st re | re==[] = n\n | st ==[] = process n [(head re)] (tail re)\n | head st /= head re = process (n-2) (tail st) (tail re)\n | otherwise = process n ((head re):st) (tail re)\nmain=do\n n<-read <$> getLine ::IO Int\n q<- C.unpack <$> C.take n <$> C.getLine\n print $ process n [] q\n"}, {"source_code": "import Control.Applicative ((*>), (<$>))\nimport Control.Arrow ((&&&))\nimport Data.Function (on)\n\nmain :: IO ()\nmain = print =<< solve <$> (getLine *> getLine)\n\nsolve :: String -> Int\nsolve = abs . uncurry ((-) `on` length) . (filter (=='1') &&& filter (=='0'))\n"}, {"source_code": "import Data.List (partition)\nmain = getLine >> getLine >>= print . solve\nsolve s = abs (length a - length b) where (a,b) = partition (== '1') s\n"}, {"source_code": "f :: String -> Int\nf s = abs $ ones - zeros\n where ones = length $ filter (=='1') s\n zeros = length s - ones\n \nmain = getLine >> getLine >>= print . f\n"}, {"source_code": "xsolve \"\" = \"\"\nxsolve [a] = [a]\nxsolve (a:rest) =\n if null rest' then [a]\n else if a /= head rest' then tail rest'\n else a:rest'\n where rest' = xsolve rest\n\nmain = do\n _ <- getLine\n line <- getLine\n (print . length . xsolve) line\n"}, {"source_code": "probA line = foldr loop \"\" line\n where\n loop a \"\" = [a]\n loop a (b:rest)\n | a /= b = rest\n | otherwise = a:(b:rest)\n\nmain = do\n _ <- getLine\n line <- getLine\n (print . length . probA) line\n"}, {"source_code": "solve :: String -> Int\nsolve ns = abs ((length $ filter (=='0') ns) - (length $ filter (=='1') ns))\n\nmain :: IO ()\nmain = do\n getLine\n getLine >>= print . solve\n"}, {"source_code": "solve :: String -> Int\nsolve = solveHelper [] where\n solveHelper [] [] = 0\n solveHelper [] (y:ys) = solveHelper [y] ys\n solveHelper xs [] = length xs\n solveHelper (x:xs) (y:ys)\n | x == y = solveHelper (y:(x:xs)) ys\n | otherwise = solveHelper xs ys\n\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ show $ solve s\n"}, {"source_code": "import Control.Applicative\n\ncount' _ [] = 0\ncount' n (x:xs)\n | n == x = 1 + count' n xs\n | otherwise = count' n xs\n\nmain = do\n n <- read <$> getLine\n n1 <- count' '1' <$> getLine\n let n0 = n - n1\n print $ n - 2 * (n0 `min` n1)"}, {"source_code": "module Main where\n\ncount _ [] = 0\ncount c (a:as) = \n (if a == c then 1 else 0) + count c as\n\nmain = do\n _ <- getLine\n s <- getLine\n print $ abs (count '0' s - count '1' s)\n"}], "negative_code": [{"source_code": "main = getContents >>= putStrLn . show . solve . last . words\n\nsolve :: String -> Int\nsolve cs = n - min p q\n where n = length cs\n p = length $ filter (== '0') cs\n q = length $ filter (== '1') cs\n"}, {"source_code": "minRemain :: [Char] -> Int\nminRemain [] = 0\nminRemain (x:[]) = 0\nminRemain (x:xs)\n | x == snd = 2 + (minRemain $ tail xs)\n | otherwise = minRemain $ tail xs\n where snd = head xs\n\nmain :: IO()\nmain = do len <- getLine\n str <- getLine\n print $ minRemain str\n "}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess [] = []\nprocess [x] = [x]\nprocess (a:b:cs)| a=='0' && b=='1' = process cs\n | a=='1' && b=='0' = process cs\n | otherwise = a: ( process (b:cs) )\n\nmain=do\n n<-getLine\n q<- getLine\n print $ length $ process q\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nprocess::C.ByteString->C.ByteString\n\nprocess q | C.null q = C.empty\n | C.length q ==1 = q\n | C.take 2 q==(C.pack \"10\") = process (C.drop 2 q)\n | C.take 2 q ==(C.pack \"01\") = process (C.drop 2 q)\n | otherwise = C.cons (C.head q ) ( process (C.tail q))\n\nmyfix::(C.ByteString->C.ByteString)->C.ByteString->C.ByteString\nmyfix f q | q==qq = q\n | otherwise = myfix f (f q)\n where qq = f q\n\nmain=do\n n<-getLine\n q<- C.getLine\n print $ C.length $ myfix process q\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as C\nprocess q | qql>1 = process (concat qq)\n | qqql>1 = process ( concat qqq)\n | otherwise = q\n\n where qq = splitOn \"01\" q\n qql = length qq\n qqq = splitOn \"10\" q\n qqql = length qqq\n\n\nmain=do\n n<-getLine\n q<- C.getLine\n print $ length $ process (C.unpack q)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.List.Split\nimport qualified Data.ByteString.Char8 as C\nprocess q | qql>1 = process (concat qq)\n | qqql>1 = process ( concat qqq)\n | otherwise = q\n\n where qq = splitOn \"01\" q\n qql = length qq\n qqq = splitOn \"10\" q\n qqql = length qqq\n\n\nmyfix f q | q==qq = q\n | otherwise = myfix f (f q)\n where qq = f q\n\nmain=do\n n<-getLine\n q<- C.getLine\n print $ length $ process (C.unpack q)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\nprocess::C.ByteString->C.ByteString\n\nprocess q | C.null q = C.empty\n | C.length q ==1 = q\n | C.take 2 q==(C.pack \"10\") = process (C.drop 2 q)\n | C.take 2 q ==(C.pack \"01\") = process (C.drop 2 q)\n | otherwise = C.cons (C.head q ) ( process (C.tail q))\n\nmyfix::(C.ByteString->C.ByteString)->C.ByteString->C.ByteString\nmyfix f q | q==qq = q\n | otherwise = myfix f (f q)\n where qq = f q\n\nmain=do\n n<-getLine\n q<- C.getContents\n print $ C.length $ myfix process q \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n\n\nprocess [] =[]\nprocess [q] = [q]\nprocess (a:b:c) | a=='1' && b=='0' = process c\n | a=='0' && b=='1' = process c\n | otherwise = a:(process (b:c))\n\n\nmyfix f q | q==qq = q\n | otherwise = myfix f (f q)\n where qq = f q\n\nmain=do\n n<-getLine\n q<- C.getLine\n let q1 = C.unpack q\n print $ length $ myfix process q1\n"}, {"source_code": "import Data.List (group)\nmain = getLine >> getLine >>= print . solve . map length . group\nsolve [] = 0\nsolve [x] = x\nsolve s = solve $ reduce $ step s\nstep (a:b:c) = a-m : b-m : step c where m = min a b\nstep c = c\nreduce (0:a) = reduce a\nreduce (a:0:b:c) = a+b : reduce c\nreduce (a:b) = a : reduce b\nreduce [] = []\n"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve\n\nsolve :: String -> Int\nsolve (_:xs) = abs $ (-) (length . filter (=='1') $ xs) (length . filter (=='0') $ xs)"}, {"source_code": "main :: IO ()\nmain = interact $ show . solve\n\nsolve :: String -> Int\nsolve xs = abs $ (-) (length . filter (=='1') $ xs) (length . filter (=='0') $ xs)"}], "src_uid": "fa7a44fd24fa0a8910cb7cc0aa4f2155"} {"source_code": "main=interact$show.(+0).maximum.map read.tail.words\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . getAns . getIntArray\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = maximum xs\n\n"}, {"source_code": "main=interact$show.maximum.map (read::String->Int).tail.words\n\n"}, {"source_code": "main=interact$show.f.g.(0:).map read.tail.words\ng (x:y:[]) = [x-y]\ng (x:y:xs) = x-y:g(y:xs)\n\nf (x:[])\n | x < 0 = negate x\n | otherwise = 0\nf (x:xs)\n | x < 0 = negate x + f xs\n | otherwise = f (((head xs)+x):(tail xs))\n\n"}, {"source_code": "main :: IO()\nmain = print . solve . tail . map read . words =<< getContents\n\nsolve :: [Integer] -> Integer\nsolve h = solve' h 0 0\n where\n solve' :: [Integer] -> Integer -> Integer -> Integer\n solve' [] _ _ = 0\n solve' (h:hs) lastH energy | energy + lastH - h < 0 = h - energy - lastH + (solve' hs h 0)\n | otherwise = solve' hs h (energy + lastH - h)\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . getAns . getIntArray\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = negate $ calMax xs 0 0\n\ncalMax :: [Int] -> Int -> Int -> Int\ncalMax [] _ _ = 0\ncalMax (x:xs) e p = let ne = e + p - x;\n\t\t\t\t\t in min ne $ calMax xs ne x\n"}, {"source_code": "main=getContents>>=print.maximum.(0:).map read.tail.words\n"}, {"source_code": "main=interact$show.maximum.(0:).map read.tail.words\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . maximum . map (read :: String -> Integer) . tail . words\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Integer] -> Integer\nsolve (_:hs) = maximum hs\nsolve _ = undefined\n"}, {"source_code": "import Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = B.getContents >>= print . solve . map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [Int] -> Int\nsolve (_:hs) = maximum hs\nsolve _ = undefined\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\nmain = interact $ show @Int . maximum . map read . tail . words\n"}, {"source_code": "main = do \n getLine\n getLine >>= print. maximum. map (fromIntegral.read) . words"}, {"source_code": "\nmain = interact $ show . maximum . map (read::String -> Int) . drop 1 . words\n"}, {"source_code": "solve :: [Integer] -> Integer -> Integer\nsolve [x] power = 0\nsolve (x:y:xs) power = if delta > power then ((delta - power) + solve (y:xs) 0) else solve (y:xs) (power - delta)\n\twhere delta = y - x\n\nmain = do\n\tgetLine\n\tinput <- getLine\n\tputStr $ show $ max 0 (solve (0:(map read $ words input :: [Integer])) 0)\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString.Lazy.Char8 as B\n\ngetIntArray :: B.ByteString -> [Int]\ngetIntArray = map fst . mapMaybe B.readInt . B.words\n\nmain = B.interact $ B.pack . show . maximum . tail . getIntArray\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n (_, s) = foldl (\\(c, s) x -> let c' = c+x in if c' >= 0 then (c', s) else (0, s-c')) (0, 0) $ zipWith (-) (0:xs) $ xs\n\n print s\n"}, {"source_code": "main = interact $ (show :: Int -> [Char]) . maximum . map read . tail . words"}, {"source_code": "import Control.Applicative\nmain = do\n\t\tn <- getLine\n\t\tp <- (map read . words <$> getLine) :: IO [Int]\n\t\tprint $ maximum p\n"}, {"source_code": "-- Codeforces 463B\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getLine >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve = fst . foldl (\n \\(m, (e, h)) b -> if (e < b-h) \n then (m+(b-h-e), (0, b)) \n else (m, (e-(b-h), b))) \n (0, (0, 0))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\n\nmain::IO ()\nmain=do\n n<- read <$> getLine::IO Int\n a1<- maximum <$> map read <$> words <$> getLine:: IO Int\n print a1\n"}], "negative_code": [{"source_code": "main=interact$show.f.(0:).map read.tail.words\nf (x:y:[]) = y-x\nf (x:y:xs)\n | x - y < 0 = y-x + f (y:xs)\n | otherwise = f(x:xs)\n\n"}, {"source_code": "main=interact$show.negate.minimum.g.(0:).map read.tail.words\ng (x:y:[]) = [x-y]\ng (x:y:xs) = x-y:g(y:xs)\n"}], "src_uid": "d03ad531630cbecc43f8da53b02d842e"} {"source_code": "-- ID : 1697B (Promo)\n-- URL: https://codeforces.com/problemset/problem/1697/B\n\nimport Control.Monad\nimport Data.List\nimport Data.Array\n\n-- Fast IO\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\ngetInt64 = parseInt `fmap` BS8.getLine :: IO Int64\ngetInt64s = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int64]\nparseInt = fromIntegral . fst . fromJust . BS8.readInt\n-- Slow IO\ngetIntsSlow = (map read . words) `fmap` getLine :: IO [Int]\n\nmain = do\n [n,q] <- getIntsSlow\n ps0 <- getInt64s\n let ps = sortBy (\\a b -> compare b a) ps0\n let subsumTable = listArray (0,n) (scanl (+) 0 ps) :: Array Int Int64\n --print subsumTable\n replicateM_ q $ do\n [x,y] <- getInt64s\n let answer = (subsumTable ! (fromIntegral x)) - (subsumTable ! (fromIntegral (x-y)))\n print answer\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE CPP #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Bool\nimport Debug.Trace\nimport Data.Array (listArray, (!))\n\nmain :: IO ()\nmain = C.interact $ runScanner input >>> solve >>> output\n-- main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC { n :: Int, q :: Int, ps :: [Int], qs :: [(Int, Int)]}\ntype Output = [Int]\n\ninput :: Scanner TC\ninput = do\n n <- int\n q <- int\n ps <- n >< int\n qs <- q >< pair int int\n return TC {..}\n\nsolve :: TC -> Output\nsolve TC {..} = map calc qs\n where\n pre = listArray (0, n) . scanl (+) 0 . reverse . sort $ ps \n calc (x, y) = pre ! x - pre ! (x - y)\n\n\noutput :: Output -> C.ByteString\noutput = map showB >>> C.unlines\n\n-------------------------- Template ------------------------------------------\n-- Debug\ndebug :: Show a => a -> a\n#ifdef ONLINE_JUDGE\ndebug = id\n#else\ndebug a = trace (show a) a\n#endif\n\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}], "negative_code": [], "src_uid": "2dc69231824db013161e4f223e25ccb9"} {"source_code": "import Data.List\n\none :: (Int, [(Int, Int)])->Int->(Int, [(Int, Int)])\none (a, b) c = (m+1, (c, 1+(foldl max 0 $m:map snd p)):q) where (p, q) = break ((c,0)>) b; m = a-(length p)\n\ngls :: [Int]->[Int]\ngls = scanl (\\a (_,(x:s))->max a $snd x) 0 . tail . scanl one (0,[])\n\nslv :: [Int]->(Int, Int)\nslv x =(m+1,o) where Just o = elemIndex m l; l = zipWith max (gls x) $reverse $ gls $ reverse x; m = foldl1 min l; \n\not :: [Int]->Int->[Int]\not x n = [a,(1+o+b)`mod`n] where (a,b)=(slv . take (n - 1) . tail. snd . break (1==) $x++x); Just o = elemIndex 1 x\n\nmain=do\n st1<-getLine\n st2<-getLine\n let n = (read st1)::Int\n let arr = map read $ words st2 :: [Int]\n putStrLn $intercalate \" \" $ map show (ot arr n)\n \n", "positive_code": [{"source_code": "import Data.List\n\none (a, b) c = (m+1, (c, 1+(foldl max 0 $m:map snd p)):q) where (p, q) = break ((c,0)>) b; m = a-(length p)\n\ngls = scanl (\\a (_,(x:s))->max a $snd x) 0 . tail . scanl one (0,[])\n\nslv x =(m+1,o) where Just o = elemIndex m l; l = zipWith max (gls x) $reverse $ gls $ reverse x; m = foldl1 min l; \n\not x n = [a,(1+o+b)`mod`n] where (a,b)=(slv . take (n - 1) . tail. snd . break (1==) $x++x); Just o = elemIndex 1 x\n\nmain=do\n st1<-getLine\n st2<-getLine\n let n = (read st1)::Int\n let arr = map read $ words st2 :: [Int]\n putStrLn $intercalate \" \" $ map show (ot arr n)\n \n"}], "negative_code": [], "src_uid": "0cd663950ce384c506f2eaa6e14b9880"} {"source_code": "import Data.Ratio\n\nshowR r = show (numerator r) ++ \"/\" ++ show (denominator r)\n\nsolve [ [n, m], p:_, q:_ ]\t| n < m\t\t\t= \"0/1\"\n\t\t\t\t| n > m && p * q > 0\t= \"Infinity\"\n\t\t\t\t| n > m && p * q < 0\t= \"-Infinity\"\n\t\t\t\t| n == m\t\t= showR (p % q)\n\nmain = interact $ solve . map (map read . words) . take 3 . lines \n", "positive_code": [{"source_code": "\nsolve :: Int -> Int -> Int -> Int -> String\nsolve n m a b\n | n < m = \"0/1\"\n | a * b < 0 = '-' : solve n m a' b'\n | n > m = \"Infinity\"\n | otherwise = concat [show $ div a' gcdAB, \"/\", show $ div b' gcdAB]\n where\n a' = abs a\n b' = abs b\n gcdAB = gcd a' b' \n\nreads :: Read a => IO [a]\nreads = getLine >>= return . map read . words\n\nmain :: IO ()\nmain = do\n [n, m] <- Main.reads\n as <- Main.reads\n bs <- Main.reads\n putStrLn $ solve n m (head as) (head bs)\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n [n,m] <- map read.words <$> getLine\n (a:_) <- map read.words <$> getLine\n (b:_) <- map read.words <$> getLine\n putStrLn $ solve n m a b\n\nsolve :: Int -> Int -> Int -> Int ->String\nsolve n m a b\n | n>m = s ++ \"Infinity\"\n | n m && p * q > 0\t= \"Infinity\"\n\t\t\t\t| n > m && p * q < 0\t= \"-Infinity\"\n\t\t\t\t| n == m\t\t= show (numerator $ p % q) ++ \"/\" ++ show (denominator $ p % q) \n\nmain = interact $ solve . map (map read . words) . lines \n"}, {"source_code": "import Data.Ratio\n\nsolve [ [n, m], p:_, q:_ ]\t| n < m\t\t\t= \"0/1\"\n\t\t\t\t| n > m \t\t= (if p * q < 0 then \"-\" else \"\") ++ \"Infinity\"\n\t\t\t\t| n == m\t\t= show (numerator $ p % q) ++ \"/\" ++ show (denominator $ p % q) \n\nmain = interact $ solve . map (map read . words) . lines \n"}, {"source_code": "import Data.Ratio\n\nmain =\n\tdo\tgrades <- getLine\n\t\tcoeficientsP <- getLine\n\t\tcoeficientsQ <- getLine\n\t\tputStrLn (result grades coeficientsP coeficientsQ)\n\nresult::String -> String -> String -> String\n\nresult grades coefsP coefsQ =\n\tif gradeP > gradeQ\n\tthen infinity coefP coefQ\n\telse if gradeQ > gradeP\n\tthen \"0/1\"\n\telse limit coefP coefQ\n\t\twhere\t[gradeP, gradeQ]\t= map toInt (words grades)\n\t\t\tcoefP\t\t\t= toInt (head (words coefsP))\n\t\t\tcoefQ\t\t\t= toInt (head (words coefsQ))\n\ninfinity coefA coefB =\n\t(if coefA*coefB > 0\n\tthen \"\"\n\telse \"-\")++\"Infinity\"\n\nlimit::Int -> Int -> String\nlimit p q =\n\t(show (numerator lim))\n\t++ \"/\" ++\n\t(show (denominator lim))\n\t\twhere lim = p % q\n\ntoInt::String -> Int\ntoInt s = read s :: Int\n"}, {"source_code": "import Data.List\n\ngetNumerator :: Int -> Int -> Int\ngetNumerator a b\n\t| b > 0 = div a (gcd a b)\n\t| otherwise = div (0 - a) (gcd a b)\n\t\ngetDenominator :: Int -> Int -> Int\ngetDenominator a b\n\t| b > 0 = div b (gcd a b)\n\t| otherwise = div (0 - b) (gcd a b)\n\nmain :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tstr3 <- getLine\n\tlet num = words str1\n\tlet a0 = read ((words str2) !! 0)\n\tlet b0 = read ((words str3) !! 0)\n\tlet n = read (num !! 0)\n\tlet m = read (num !! 1)\n\tif ((m - n) > 0)\n\t\tthen putStrLn \"0/1\"\n\t\telse if (n > m)\n\t\t\tthen if (a0 * b0 > 0)\n\t\t\t\tthen putStrLn \"Infinity\"\n\t\t\t\telse putStrLn \"-Infinity\"\n\t\t\telse putStrLn (show (getNumerator a0 b0) ++ \"/\" ++ show (getDenominator a0 b0))\n\t\n"}, {"source_code": "-- -*- compile-command: \"ghc --make -O limit.hs\" -*-\n\nimport System.IO\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Lazy as B\n\nlimit :: Int -> Int -> Int -> Int -> String\nlimit n m a b\n | m > n = \"0/1\"\n | n > m && a*b > 0 = \"Infinity\"\n | n > m = \"-Infinity\"\n | otherwise = (show $ c `div` ggt) ++ \"/\" ++ (show $ d `div` ggt)\n where ggt = gcd a b\n (c,d) = if a*b > 0\n then (abs a, abs b)\n else (negate $ abs a, abs b)\n \nreadInts :: String -> [Int]\nreadInts = (map read) . words\n\nmain = do\n n:m:[] <- readInts `fmap` getLine\n a0:_ <- readInts `fmap` getLine\n b0:_ <- readInts `fmap` getLine\n --print a0\n --print b0\n putStrLn $ limit n m a0 b0"}], "negative_code": [{"source_code": "import Data.List\n\ngetNumerator :: Int -> Int -> Int\ngetNumerator a b\n\t| b > 0 = div a (gcd a b)\n\t| otherwise = div (0 - a) (gcd a b)\n\t\ngetDenominator :: Int -> Int -> Int\ngetDenominator a b\n\t| b > 0 = div b (gcd a b)\n\t| otherwise = div (0 - b) (gcd a b)\n\nmain :: IO()\nmain = do\n\tstr1 <- getLine\n\tstr2 <- getLine\n\tstr3 <- getLine\n\tlet num = words str1\n\tlet a0 = read ((words str2) !! 0)\n\tlet b0 = read ((words str3) !! 0)\n\tlet n = num !! 0\n\tlet m = num !! 1\n\tif (m > n)\n\t\tthen putStrLn \"0/1\"\n\t\telse if (n > m)\n\t\t\tthen if (a0 * b0 > 0)\n\t\t\t\tthen putStrLn \"Infinity\"\n\t\t\t\telse putStrLn \"-Infinity\"\n\t\t\telse putStrLn (show (getNumerator a0 b0) ++ \"/\" ++ show (getDenominator a0 b0))\n\t\n"}, {"source_code": "-- -*- compile-command: \"ghc --make -O limit.hs\" -*-\n\nimport System.IO\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Lazy as B\n\nlimit :: Int -> Int -> Int -> Int -> String\nlimit n m a b\n | m > n = \"0/1\"\n | n > m && a*b > 0 = \"Infinty\"\n | n > m = \"-Infinty\"\n | otherwise = (show $ c `div` ggt) ++ \"/\" ++ (show $ d `div` ggt)\n where ggt = gcd a b\n (c,d) = if a*b > 0\n then (abs a, abs b)\n else (negate $ abs a, abs b)\n \nreadInts :: String -> [Int]\nreadInts = (map read) . words\n\nmain = do\n n:m:[] <- readInts `fmap` getLine\n a0:_ <- readInts `fmap` getLine\n b0:_ <- readInts `fmap` getLine\n --print a0\n --print b0\n putStrLn $ limit n m a0 b0"}, {"source_code": "import Data.Ratio\n\nshowR r = show (numerator r) ++ \"/\" ++ show (denominator r)\n\nsolve [ [n, m], p:_, q:_ ]\t| n < m\t\t\t= \"0/1\"\n\t\t\t\t| n > m && p > 0\t= \"Infinity\"\n\t\t\t\t| n > m && p < 0\t= \"-Infinity\"\n\t\t\t\t| n == m\t\t= showR (p % q)\n\nmain = interact $ solve . map (map read . words) . take 3 . lines \n"}, {"source_code": "import Data.Ratio\n\nmain =\n\tdo\tgrades <- getLine\n\t\tcoeficientsP <- getLine\n\t\tcoeficientsQ <- getLine\n\t\tputStrLn (result grades coeficientsP coeficientsQ)\n\nresult::String -> String -> String -> String\n\nresult grades coefsP coefsQ =\n\tif gradeP > gradeQ\n\tthen infinity coefP\n\telse if gradeQ > gradeP\n\tthen \"0/1\"\n\telse limit coefP coefQ\n\t\twhere\t[gradeP, gradeQ]\t= map toInt (words grades)\n\t\t\tcoefP\t\t\t= toInt (head (words coefsP))\n\t\t\tcoefQ\t\t\t= toInt (head (words coefsQ))\n\ninfinity coef =\n\t(if coef > 0\n\tthen \"\"\n\telse \"-\")++\"Infinity\"\n\nlimit::Int -> Int -> String\nlimit p q =\n\t(show (numerator lim))\n\t++ \"/\" ++\n\t(show (denominator lim))\n\t\twhere lim = p % q\n\ntoInt::String -> Int\ntoInt s = read s :: Int"}], "src_uid": "37cf6edce77238db53d9658bc92b2cab"} {"source_code": "import Control.Monad\nimport Data.List\nimport qualified Data.Map as M\n\ninput :: Read a => IO [a]\ninput = map read <$> words <$> getLine\n\noutput :: Show a => [a] -> IO ()\noutput = putStrLn <$> unwords <$> map show\n\nmain = do\n [n,p,k] <- input\n a <- input\n print\n $ sum\n $ map (\\xs -> let n = length xs in n*(n-1)`div`2)\n $ group\n $ sort [(x^4-k*x) `mod` p | x <- a]\n", "positive_code": [{"source_code": "import Control.Monad\nimport qualified Data.Map.Strict as M\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C.readInteger) . C.words <$> C.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n [n, p, k] <- getIntegers\n nums <- getIntegers\n let modnums = (\\a -> (a ^ 4 - k * a) `mod` p) <$> nums\n modmap = foldl (\\m k -> if k `M.member` m then M.adjust succ k m else M.insert k 1 m) M.empty modnums\n modlist = (\\(_, v) -> (v * v - v) `div` 2) <$> M.toList modmap\n print $ sum modlist\n\n"}], "negative_code": [], "src_uid": "ac4d58b5dfb61a27205a4fe2d3d5d268"} {"source_code": "import Data.List (splitAt)\nmain = do\n [n,a,b] <- fmap ((map read) . words) getLine :: IO[Int]\n if n>a*b\n then print (-1)\n else mapM_ printLs $ solve n a b\n \n \nprintLs :: [Int] -> IO()\nprintLs xs = mapM_ (\\x -> putStr (show x ++ \" \")) xs >> putStrLn \"\"\n\nsolve :: Int -> Int ->Int ->[[Int]]\nsolve n a b =\n let l = [1..n] ++ (repeat 0)\n in go l a b 0\n \ngo :: [Int] -> Int -> Int -> Int ->[[Int]]\ngo l a b c\n |c==a = []\n |otherwise =\n let (x,y) = splitAt b l\n in if even c then x:go y a b (c+1) else (reverse x):go y a b (c+1)\n", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n (n:a:b:_) <- fmap (map read . words) getLine\n if n > a * b\n then print (-1)\n else flip mapM_ [0 .. a-1] $ \\i -> do\n let r = (if even b && odd i then reverse else id)\n [if j < n then j + 1 else 0 | j <- take b [i * b ..]]\n putStrLn $ unwords $ map show r\n"}, {"source_code": "import Data.List\n\nrowToString [] = \"\"\nrowToString (x : xs) = (show x) ++ \" \" ++ (rowToString xs)\ntableToString [] = \"\"\ntableToString (r : rs) = (rowToString r) ++ (\"\\n\") ++( tableToString rs)\n\nup b = div (b + 1) 2\ndown b = div b 2\nbuild a n m b | a == 0 = []\n | otherwise = ((map (max 0) . concat . transpose $ ([take (up b) [n, n - 2..], take (down b) [m, m - 2..]])): build (a - 1) (m - 2 * down(b)) (n - 2 * up(b)) b)\nmain = do\n [n, a, b] <- fmap (map read . words) getLine\n putStr .tableToString $ if (n > a * b) then [[(-1)]] else (build a n (n - 1) b)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nsplitBy::Int->[a]->[[a]]\nsplitBy _ [] = []\nsplitBy n xs = let (pref, rest) = splitAt n xs in pref: splitBy n rest\n\n\nsolution::Int->Int->Int->[[Int]]\nsolution n a b\n | n > a * b = [[-1]]\n | otherwise = let\n nums = splitBy b $ take (a*b) $ [1..n] ++ repeat 0\n rev _ [] = []\n rev False (x: xs) = x: rev True xs\n rev True (x:xs) = reverse x : rev False xs\n in case mod b 2 of\n 1 -> nums\n _ -> rev False nums\n\nmain :: IO ()\nmain = do\n [n,a,b] <- map read . words <$> getLine\n forM_ (solution n a b) $ putStrLn . intercalate \" \". map show\n"}, {"source_code": "main = interact $ unlines . map (unwords . map show) . go . map read . words . filter ('\\n'/=)\ngo [n,a,b] | n>a*b = [[-1]]\n | True = (map (\\(i,k) -> dr i [k-b+1..k]) . take ndb $ zip [1..] [b,b+b..]) ++ map zs [ndb+1..a]\n where dr i | b`mod`2==0 && i`mod`2==0 = reverse\n | True = id\n zs i = dr i $ l ++ take (b-length l) [0,0..]\n where l = [b*(i-1)+1..n]\n ndb = n`div`b"}], "negative_code": [{"source_code": "main = do\n (n:a:b:_) <- fmap (map read . words) getLine\n if n > a * b\n then print (-1)\n else flip mapM_ [0 .. a-1] $ \\i -> do\n let r = (if odd b && odd i then reverse else id)\n [if j < n then j + 1 else 0 | j <- take b [i * b ..]]\n putStrLn $ unwords $ map show r\n"}], "src_uid": "6e0dafeaf85e92f959c388c72e158f68"} {"source_code": "import Data.List\nimport Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\nroutine :: IO ()\nroutine = do\n n <- readLn\n as <- (map read. words) <$> getLine\n print $ solve n as\n\nsolve :: Int -> [Int] -> Int\nsolve n as = (as'!!n)-(as'!!(n-1))\n where\n as' = sort as\n", "positive_code": [{"source_code": "import Data.Ord\nimport Data.Int\nimport qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Prelude hiding (showList)\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s DSeq.|> x\n in aux DSeq.Empty\n\ntype EIO a = ExceptT String IO a\n\nget :: Read a => EIO a\nget = ExceptT $ liftM readEither getToken\ngets :: EIO String\ngets = ExceptT $ liftM Right getToken\nputs :: String -> EIO ()\nputs = lift . putStr\nputsln :: String -> EIO ()\nputsln = lift . putStrLn\nput :: Show a => a -> EIO ()\nput = putsln . show\nputln :: Show a => a -> EIO ()\nputln = putsln . show\nshowList :: Show a => [a] -> String\nshowList [] = []\nshowList (x : l) = shows x $ showChar ' ' $ showList l\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> putStrLn s\n\nmain_ :: EIO ()\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: EIO ()\nf1 = do\n n <- get\n a <- replicateM (2 * n) get\n putln $ f2 a n\n\nf2 :: [Int64] -> Int -> Int64\nf2 l n = let sl = sort l\n in\n ((sl !! (n)) - (sl !! (n - 1)))"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: (Int, [Int]) -> Int\nsolve (n,xs) = abs $ (xs !! q) - (xs !! r)\n where\n q = 2 * n `div` 2\n r = q - 1\n\nmain = do\n t <- readLn :: IO Int\n xss <- replicateM t $ do\n n <- readLn :: IO Int\n xs <- sort . map read . words <$> getLine :: IO [Int]\n return (n, xs)\n mapM_ (print . solve) xss\n \n"}, {"source_code": "import Data.List as L\n\nsolve :: [Integer] -> Integer\nsolve as = (head secondHalf) - (last firstHalf)\n where ordered = L.sort as\n mid = div (length as) 2\n firstHalf = take mid ordered\n secondHalf = drop mid ordered\n\ngroupByTwo :: [String] -> [(String, String)]\ngroupByTwo [] = []\ngroupByTwo (n:as:other) = [(n, as)] ++ groupByTwo other\n\nparse :: (String, String) -> String\nparse (_, as) = show $ solve as'\n where as' = map (\\x -> read x :: Integer) $ words as\n\nmain :: IO ()\nmain = interact (unlines . map parse . groupByTwo . tail . lines)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest n = getLine >> getLine >>= print.solve.sort.map read.words >> test (n - 1)\n\nsolve as = abs $ as !! i - as !! pred i where\n i = div (length as) 2\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: (Int, [Int]) -> Int\nsolve (n,xs) = abs $ ma - mb\n where\n ma = (reverse as) !! (n `div` 2)\n mb = (reverse bs) !! (n `div` 2)\n (as,bs) = foldl' step ([],[]) $ zip [1..2*n] xs\n step (as,bs) (i,e) \n | odd i = (e:as,bs)\n | otherwise = (as,e:bs)\n\nmain = do\n t <- readLn :: IO Int\n xss <- replicateM t $ do\n n <- readLn :: IO Int\n xs <- sort . map read . words <$> getLine :: IO [Int]\n return (n,xs)\n mapM_ (print . solve) xss\n \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: (Int, [Int]) -> Int\nsolve (n,xs) = abs $ ma - mb\n where\n ma = (sort as) !! (n `div` 2)\n mb = (sort bs) !! (n `div` 2)\n (as,bs) = collect xs ([],[])\n collect xs (as,bs)\n | null xs = (as,bs)\n | otherwise = collect xs' ((h:as), (l:bs))\n where\n h = head xs\n l = last xs\n xs' = reverse $ init $ tail xs\n\nmain = do\n t <- readLn :: IO Int\n xss <- replicateM t $ do\n n <- readLn :: IO Int\n xs <- sort . map read . words <$> getLine :: IO [Int]\n return (n,xs)\n mapM_ (print . solve) xss\n \n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nsolve :: (Int, [Int]) -> Int\nsolve (n,xs) = abs $ (xs !! q) - (xs !! r)\n where\n q = 2 * n `div` 2\n r = q - 1\n\nmain = do\n t <- readLn :: IO Int\n xss <- replicateM t $ do\n n <- readLn :: IO Int\n xs <- sort . map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]\n return (n, xs)\n mapM_ (print . solve) xss\n \n"}], "src_uid": "adb0f6082367dc432e2e096c64f13a56"} {"source_code": "import Data.List\nimport qualified Data.Maybe as M\nimport qualified Data.Set as S\n\ncandidate :: String -> String -> String\n\ncandidate [] [] = []\ncandidate (x:xs) (y:ys) = cur:candidate xs ys\n where \n cur = if (x == y) then x else (head $ \"SET\" \\\\ [x, y])\n\ngetAllMatches cards = [(a, b, c) |\n (a:bs) <- tails cards,\n b <- bs, \n let c = candidate a b, \n c < a,\n S.member c cards']\n where cards' = S.fromAscList cards\n\nsolve :: [String] -> Int\nsolve cards = \n length . getAllMatches . sort $ cards\n\nmain = do\n _ <- getLine\n strings <- words <$> getContents\n print $ solve strings\n\n", "positive_code": [{"source_code": "import Data.Map.Strict (fromAscList, findWithDefault, keys)\nimport Data.List\n\nmain = do\n\tgetLine\n\tstrings <- group . sort . words <$> getContents\n\tlet counts = fromAscList [(head ss, length ss) | ss <- strings]\n\t elems = keys counts\n\tprint $ sum [findWithDefault 0 (set a b) counts |\n\t\ti <- [0..length elems - 1],\n\t\tlet (a:bs) = drop i elems,\n\t\tb <- bs] `div` 3\n\nset [] _ = []\nset (a:as) (b:bs)\n\t| a == b = a : set as bs\n\t| otherwise = (head $ \"SET\" \\\\ [a, b]) : set as bs\n"}, {"source_code": "import Data.Set as S\nimport Data.List as L\n\nmissing :: Char -> Char -> Char\nmissing 'S' 'E' = 'T'\nmissing 'E' 'S' = 'T'\nmissing 'E' 'T' = 'S'\nmissing 'T' 'E' = 'S'\nmissing 'S' 'T' = 'E'\nmissing 'T' 'S' = 'E'\n\ndesiredCard :: String -> String -> String\ndesiredCard \"\" \"\" = \"\"\ndesiredCard (a:as) (b:bs)\n | a == b = [a] ++ next\n | otherwise = [missing a b] ++ next\n where next = desiredCard as bs\n\npossibilitiesCount :: [String] -> Int\npossibilitiesCount strings = length\n $ L.filter (\\[a, b] -> S.member (desiredCard a b) allStrings)\n [[a, b] | a <- strings, b <- strings, a /= b && a < b]\n where allStrings = S.fromList strings\n\nsolve :: String -> String\nsolve input = show $ (div (possibilitiesCount lines') 3)\n where lines' = tail $ lines input\n\nmain :: IO ()\nmain = do\n contents <- getContents\n putStrLn (solve contents)\n"}], "negative_code": [], "src_uid": "ae7c80e068e267673a5f910bb0b121ec"} {"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\n\nbtoi :: (Integral a) => B.ByteString -> a\nbtoi = fromIntegral . fst . fromJust . B.readInt\n\nreplace :: Integer -> [[Integer]] -> [[Integer]]\nreplace _ [] = []\nreplace b (row:rest) = (replace' row):replace b rest\n where\n replace' :: [Integer] -> [Integer]\n replace' [] = []\n replace' (x:xs)\n | 0 == x = b:xs\n | otherwise = x:replace' xs\n\ngetDiag :: [[Integer]] -> [Integer]\ngetDiag [] = []\ngetDiag ((r:row):rest) = r : getDiag (map tail rest)\n\nallEq :: [Integer] -> Bool\nallEq [] = True\nallEq (x:xs) = all (== x) xs\n\ncheckMagic :: [[Integer]] -> Bool\ncheckMagic mat =\n let rows = map sum mat\n cols = map sum $ transpose mat\n diag1 = sum $ getDiag mat\n diag2 = sum . getDiag $ reverse mat\n in allEq $ rows ++ cols ++ [diag1, diag2]\n\ngetRow :: ([Integer] -> Bool) -> [[Integer]] -> [Integer]\ngetRow p (row:rest)\n | p row = row\n | otherwise = getRow p rest\n\nprocess_case :: Int -> [[Integer]] -> Integer\nprocess_case 1 _ = 1\nprocess_case _ mat =\n let row = getRow (elem 0) mat\n row' = getRow (not . (elem 0)) mat\n t = sum row' - sum row\n mat' = replace t mat\n in if checkMagic mat' && t > 0 && t <= 10^18 then t else -1\n\nprocess :: B.ByteString -> B.ByteString\nprocess str =\n let (header:body) = B.lines str\n n = btoi header\n mat = map (map btoi . take n . B.words) $ take n body\n in B.pack . show $ process_case n mat\n\nmain :: IO ()\nmain = B.interact process", "positive_code": [{"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n getTotalOnNonZero :: (Bool, [Integer]) -> Integer\n getTotalOnNonZero (True, _) = -1\n getTotalOnNonZero (False, xs) = sum xs\n\n hasZero :: [Integer] -> Bool\n hasZero = any (==0)\n\n main :: IO()\n main = do\n n <- getLine >>= return . (read :: String -> Int)\n matrix <- readMultilineInput n (return . (map readInt) . words)\n let matrixT = transpose matrix\n zeroX = 0 -- TODO\n zeroY = 0 -- TODO\n lm = length matrix\n zerosH = map hasZero matrix\n zerosV = map hasZero matrixT\n ids = [0..(length matrix - 1)]\n diags = (\\index -> matrix !! index !! index) `map` ids\n diagsI = (\\index -> matrix !! index !! (lm - index - 1)) `map` ids\n sdiags = sum diags\n sdiagsI = sum diagsI\n hm = zerosH `zip` matrix\n vm = zerosV `zip` matrixT\n hmm = snd . head $ filter fst hm :: [Integer]\n vmm = snd . head $ filter fst vm :: [Integer]\n horizontals = map getTotalOnNonZero hm\n verticals = map getTotalOnNonZero vm\n targetScore = head $ filter (>=0) horizontals\n allTargets = filter (>0) $ horizontals ++ verticals\n possible = all (==targetScore) allTargets\n shmm = sum hmm\n svmm = sum vmm\n d1diff = targetScore - sdiags\n d2diff = targetScore - sdiagsI\n hdiff = targetScore - shmm\n vdiff = targetScore - svmm\n action = case ans < 1 of\n True -> print (-1)\n False -> print ans\n ans = case n of\n 1 -> 9 -- doesnt matter\n _ -> case possible && (hdiff == vdiff) of\n False -> (-1)\n True -> case any (==0) diags of\n True -> case any (==0) diagsI of\n True -> case d1diff == d2diff && hdiff == d1diff of\n False -> (-2)\n True -> d1diff\n False -> case d1diff == hdiff && sdiagsI == targetScore of\n False -> (-3)\n True -> d1diff\n False -> case any (==0) diagsI of\n True -> case hdiff == d2diff && sdiags == targetScore of\n False -> (-4)\n True -> hdiff\n False -> case sdiagsI == sdiags && sdiags == targetScore of\n False -> (-5)\n True -> hdiff\n\n action\n"}], "negative_code": [{"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n getTotalOnNonZero :: (Bool, [Integer]) -> Integer\n getTotalOnNonZero (True, _) = -1\n getTotalOnNonZero (False, xs) = sum xs\n\n hasZero :: [Integer] -> Bool\n hasZero = any (==0)\n\n calculate2 :: [[Integer]] -> Int\n calculate2 _ = -1 -- TODO\n\n main :: IO()\n main = do\n n <- getLine >>= return . (read :: String -> Int)\n matrix <- readMultilineInput n (return . (map readInt) . words)\n let matrixT = transpose matrix\n zeroX = 0 -- TODO\n zeroY = 0 -- TODO\n lm = length matrix\n zerosH = map hasZero matrix\n zerosV = map hasZero matrixT\n ids = [0..(length matrix - 1)]\n diags = (\\index -> matrix !! index !! index) `map` ids\n diagsI = (\\index -> matrix !! index !! (lm - index - 1)) `map` ids\n sdiags = sum diags\n sdiagsI = sum diagsI\n hm = zerosH `zip` matrix\n vm = zerosV `zip` matrixT\n hmm = snd . head $ filter fst hm :: [Integer]\n vmm = snd . head $ filter fst vm :: [Integer]\n horizontals = map getTotalOnNonZero hm\n verticals = map getTotalOnNonZero vm\n targetScore = head $ filter (>=0) horizontals\n allTargets = filter (>0) $ horizontals ++ verticals\n possible = all (==targetScore) allTargets\n shmm = sum hmm\n svmm = sum vmm\n d1diff = targetScore - sdiags\n d2diff = targetScore - sdiagsI\n hdiff = targetScore - shmm\n vdiff = targetScore - svmm\n action = case n of\n 1 -> print 9 -- doesnt matter\n 2 -> print $ calculate2 matrix\n _ -> case possible && (hdiff == vdiff) of\n False -> print (-1)\n True -> case any (==0) diags of\n True -> case any (==0) diagsI of\n True -> case d1diff == d2diff && hdiff == d1diff of\n False -> print (-1)\n True -> print d1diff\n False -> case d1diff == hdiff && sdiagsI == targetScore of\n False -> print (-1)\n True -> print d1diff\n False -> case any (==0) diagsI of\n True -> case hdiff == d2diff && sdiags == targetScore of\n False -> print (-1)\n True -> print hdiff\n False -> case sdiagsI == sdiags && sdiags == targetScore of\n False -> print (-1)\n True -> print hdiff\n\n action\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n import qualified Data.Set as S\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Integer\n readInt s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n elemSet :: (Ord a) => a -> S.Set a -> Bool\n elemSet elem sets =\n let found = elem `S.lookupIndex` sets\n in toBool found\n where\n toBool :: Maybe Int -> Bool\n toBool (Just _) = True\n toBool Nothing = False\n\n getTotalOnNonZero :: (Bool, [Integer]) -> Integer\n getTotalOnNonZero (True, _) = -1\n getTotalOnNonZero (False, xs) = sum xs\n\n hasZero :: [Integer] -> Bool\n hasZero = any (==0)\n\n main :: IO()\n main = do\n n <- getLine >>= return . (read :: String -> Int)\n matrix <- readMultilineInput n (return . (map readInt) . words)\n let matrixT = transpose matrix\n zeroX = 0 -- TODO\n zeroY = 0 -- TODO\n lm = length matrix\n zerosH = map hasZero matrix\n zerosV = map hasZero matrixT\n ids = [0..(length matrix - 1)]\n diags = (\\index -> matrix !! index !! index) `map` ids\n diagsI = (\\index -> matrix !! index !! (lm - index - 1)) `map` ids\n sdiags = sum diags\n sdiagsI = sum diagsI\n hm = zerosH `zip` matrix\n vm = zerosV `zip` matrixT\n hmm = snd . head $ filter fst hm :: [Integer]\n vmm = snd . head $ filter fst vm :: [Integer]\n horizontals = map getTotalOnNonZero hm\n verticals = map getTotalOnNonZero vm\n targetScore = head $ filter (>=0) horizontals\n allTargets = filter (>0) $ horizontals ++ verticals\n possible = all (==targetScore) allTargets\n shmm = sum hmm\n svmm = sum vmm\n d1diff = targetScore - sdiags\n d2diff = targetScore - sdiagsI\n hdiff = targetScore - shmm\n vdiff = targetScore - svmm\n action = case n of\n 1 -> print 9 -- doesnt matter\n _ -> case possible && (hdiff == vdiff) of\n False -> print (-1)\n True -> case any (==0) diags of\n True -> case any (==0) diagsI of\n True -> case d1diff == d2diff && hdiff == d1diff of\n False -> print (-1)\n True -> print d1diff\n False -> case d1diff == hdiff && sdiagsI == targetScore of\n False -> print (-1)\n True -> print d1diff\n False -> case any (==0) diagsI of\n True -> case hdiff == d2diff && sdiags == targetScore of\n False -> print (-1)\n True -> print hdiff\n False -> case sdiagsI == sdiags && sdiags == targetScore of\n False -> print (-1)\n True -> print hdiff\n\n action\n"}, {"source_code": "import Data.List\n\nreplace :: Integer -> Integer -> [[Integer]] -> [[Integer]]\nreplace _ _ [] = []\nreplace a b (row:rest) = (replace' row):replace a b rest\n where\n replace' :: [Integer] -> [Integer]\n replace' [] = []\n replace' (x:xs)\n | a == x = b:xs\n | otherwise = x:replace' xs\n\ngetDiag :: [[Integer]] -> [Integer]\ngetDiag [] = []\ngetDiag ((r:row):rest) = r : getDiag (map tail rest)\n\ncheckMagic :: [[Integer]] -> Bool\ncheckMagic mat =\n let rows = map sum mat\n cols = map sum $ transpose mat\n diag1 = sum $ getDiag mat\n diag2 = sum . getDiag $ transpose mat\n in length (nub (rows ++ cols ++ [diag1, diag2])) == 1\n\nprocess_case :: Int -> [[Integer]] -> Integer\nprocess_case 1 _ = 1\nprocess_case _ mat@(row:row':_) =\n let s = if elem 0 row then sum row' else sum row\n t = if elem 0 row then sum row' - sum row else sum row - sum row'\n mat' = replace 0 t mat\n in if checkMagic mat' && t <= 10^18 then t else -1\n\nprocess :: String -> String\nprocess str =\n let (header:body) = lines str\n n = read header\n mat = map (map read . take n . words) $ take n body\n in show $ process_case n mat\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.List\n\nreplace :: Integer -> [[Integer]] -> [[Integer]]\nreplace _ [] = []\nreplace b (row:rest) = (replace' row):replace b rest\n where\n replace' :: [Integer] -> [Integer]\n replace' [] = []\n replace' (x:xs)\n | 0 == x = b:xs\n | otherwise = x:replace' xs\n\ngetDiag :: [[Integer]] -> [Integer]\ngetDiag [] = []\ngetDiag ((r:row):rest) = r : getDiag (map tail rest)\n\nallEq :: [Integer] -> Bool\nallEq [] = True\nallEq (x:xs) = all (== x) xs\n\ncheckMagic :: [[Integer]] -> Bool\ncheckMagic mat =\n let rows = map sum mat\n cols = map sum $ transpose mat\n diag1 = sum $ getDiag mat\n diag2 = sum . getDiag $ transpose mat\n in allEq $ rows ++ cols ++ [diag1, diag2]\n\ngetRow :: ([Integer] -> Bool) -> [[Integer]] -> [Integer]\ngetRow p (row:rest)\n | p row = row\n | otherwise = getRow p rest\n\nprocess_case :: Int -> [[Integer]] -> Integer\nprocess_case 1 _ = 1\nprocess_case _ mat =\n let row = getRow (elem 0) mat\n row' = getRow (not . (elem 0)) mat\n t = sum row' - sum row\n mat' = replace t mat\n in if checkMagic mat' && t > 0 && t <= 10^18 then t else -1\n\nprocess :: String -> String\nprocess str =\n let (header:body) = lines str\n n = read header\n mat = map (map read . take n . words) $ take n body\n in show $ process_case n mat\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "import Data.List\n\nreplace :: Integer -> [[Integer]] -> [[Integer]]\nreplace _ [] = []\nreplace b (row:rest) = (replace' row):replace b rest\n where\n replace' :: [Integer] -> [Integer]\n replace' [] = []\n replace' (x:xs)\n | 0 == x = b:xs\n | otherwise = x:replace' xs\n\ngetDiag :: [[Integer]] -> [Integer]\ngetDiag [] = []\ngetDiag ((r:row):rest) = r : getDiag (map tail rest)\n\nallEq :: [Integer] -> Bool\nallEq [] = True\nallEq (x:xs) = all (== x) xs\n\ncheckMagic :: [[Integer]] -> Bool\ncheckMagic mat =\n let rows = map sum mat\n cols = map sum $ transpose mat\n diag1 = sum $ getDiag mat\n diag2 = sum . getDiag $ transpose mat\n in allEq $ rows ++ cols ++ [diag1, diag2]\n\nprocess_case :: Int -> [[Integer]] -> Integer\nprocess_case 1 _ = 1\nprocess_case _ mat@(row:row':_) =\n let s = if elem 0 row then sum row' else sum row\n t = if elem 0 row then sum row' - sum row else sum row - sum row'\n mat' = replace t mat\n in if checkMagic mat' && t > 0 && t <= 10^18 then t else -1\n\nprocess :: String -> String\nprocess str =\n let (header:body) = lines str\n n = read header\n mat = map (map read . take n . words) $ take n body\n in show $ process_case n mat\n\nmain :: IO ()\nmain = interact process"}], "src_uid": "3bd5a228ed5faf997956570f96becd73"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (replicateM, forM)\nimport Control.Monad.ST\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust, catMaybes)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.pack <$> testCase)\n\ntestCase :: Scanner String\ntestCase = do\n n <- int\n m <- int\n edges <- m >< pair int int\n q <- int\n qs <- q >< query\n return . unlines . map show $ solve n edges qs\n\ndata Query = Add Int Int | Rem Int Int | Ask deriving (Eq, Show)\n\nquery :: Scanner Query\nquery = do\n t <- int\n case t of\n 1 -> Add <$> int <*> int\n 2 -> Rem <$> int <*> int\n 3 -> pure Ask\n\nsolve :: Int -> [(Int, Int)] -> [Query] -> [Int]\nsolve n edges qs = runST compute\n where\n init :: UArray Int Int\n init = accumArray (+) 0 (1, n) [(min u v, 1) | (u, v) <- edges]\n\n initAns :: Int\n initAns = length . filter (== 0) $ elems init\n\n compute :: forall s. ST s [Int]\n compute = do\n (better :: STUArray s Int Int) <- thaw init\n deltas <- forM qs $ \\case\n Add u v -> do\n let x = min u v\n d <- readArray better x\n writeArray better x (d + 1)\n return $ if d == 0 then (-1) else 0\n Rem u v -> do\n let x = min u v\n d <- readArray better x\n writeArray better x (d - 1)\n return $ if d == 1 then 1 else 0\n Ask -> return 0\n let values = tail $ scanl1 (+) (initAns : deltas)\n return [v | (q, v) <- zip qs values, case q of Ask -> True; _ -> False]\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Array.IO.Safe\nimport qualified Data.IntSet as S\nimport Data.Maybe\n\nmodifyAt :: IOArray Int t -> Int -> (t -> t) -> IO ()\nmodifyAt arr ix fun = do\n val <- readArray arr ix\n let nval = fun val\n nval `seq` writeArray arr ix nval\n\ninsE :: IOArray Int S.IntSet -> Int -> Int -> SIO ()\ninsE arr u v = lift $ do\n modifyAt arr u $ S.insert v\n modifyAt arr v $ S.insert u\n\nremE :: IOArray Int S.IntSet -> Int -> Int -> SIO ()\nremE arr u v = lift $ do\n modifyAt arr u $ S.delete v\n modifyAt arr v $ S.delete u\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [n, m] <- readInts\n arr <- lift $ newArray (1, n) S.empty :: SIO (IOArray Int S.IntSet)\n replicateM_ m $ do\n [u, v] <- readInts\n insE arr u v\n let\n isVuln :: Int -> SIO Bool\n isVuln i = lift $ isJust . S.lookupGT i <$> readArray arr i\n ivulns <- fmap S.fromAscList $ filterM isVuln [1..n]\n let\n insv (vulns, ct) u = (\n S.insert u vulns,\n ct + if S.notMember u vulns then 1 else 0\n )\n remv (vulns, ct) u = (\n S.delete u vulns,\n ct - if S.member u vulns then 1 else 0\n )\n [q] <- readInts\n (\\fun -> foldM_ fun (ivulns, S.size ivulns) [1..q]) $ \\(vulns, ct) _ -> do\n qt : pars <- readInts\n case (qt, pars) of\n (1, [u, v]) -> do\n insE arr u v\n uv <- isVuln u\n vv <- isVuln v\n let (v1, c1) = if uv then insv (vulns, ct) u else (vulns, ct)\n pure $ if vv then insv (v1, c1) v else (v1, c1)\n (2, [u, v]) -> do\n remE arr u v\n uv <- isVuln u\n vv <- isVuln v\n let (v1, c1) = if not uv then remv (vulns, ct) u else (vulns, ct)\n pure $ if not vv then remv (v1, c1) v else (v1, c1)\n (3, []) -> (vulns, ct) <$ putInts [n - ct]\n _ -> error \"bad input\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n ~(out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [], "src_uid": "49009175bae8537e6d51424fab28183a"} {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n\tn <- fmap read getLine\n\ta <- replicateM (3*n-1) getLine\n\tputStrLn $ show $ length $ group $ sort $ gao a where\n\t\tgao [] = []\n\t\tgao (a:b:s) = c: gao (drop 1 s) where\n\t\t\tc = minimum $ take 4 $ iterate (\\(h:t) -> t ++ [h]) $ a ++ reverse b\n"}, {"source_code": "import List\nimport Control.Monad\n\nmain = do\n n <- readLn\n d <- getDice\n ds <- replicateM (n-1) $ getLine>>getDice\n print $ solve (d:ds)\n\ngetDice = do\n xs <- getLine\n ys <- getLine\n return $ xs ++ reverse ys\n\nsolve ds = length$group$sort[sort[rotateL n d| n<-[0..3]]| d<-ds]\n\nrotateL n xs = drop n xs ++ take n xs\n\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]"}, {"source_code": "module Main where\n\nimport Control.Monad -- replicateM, mapM, etc.\nimport Data.Int -- Int, Int64, etc.\nimport Data.List -- sort, find, etc.\nimport Data.Array -- listArray, array, etc.\nimport Debug.Trace -- trace\n\nreadI :: String -> Int\nreadI = read \n\nreadL :: String -> [Int]\nreadL = (map read) . words\n\nmain = do\n n <- getLine >>= return . readI\n ds <- replicateM (3*n-1) getLine\n print $ solve ds\n\nsolve ds = length $ nubBy isEq xs where\n\n xs = glue $ filter (/=\"**\") ds\n glue xs = glue' xs [] where\n glue' [] acc = acc\n glue' (x:y:xs) acc = glue' xs ((x ++ y):acc)\n \n isEq [c1,c2,c3,c4] [a1,a2,a3,a4] = \n (c1==a1 && c2==a2 && c3==a3 && c4==a4) ||\n (c1==a2 && c2==a4 && c3==a1 && c4==a3) ||\n (c1==a3 && c2==a1 && c3==a4 && c4==a2) ||\n (c1==a4 && c2==a3 && c3==a2 && c4==a1)\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "\nimport Control.Monad (liftM2, replicateM)\nimport List (nub)\n\ndata Eq a => T a = T [a]\n\ninstance Eq a => Eq (T a)\n where\n (==) (T as) (T bs) = elem as $ rotations bs\n\nrotations :: [a] -> [[a]]\nrotations xs = take n . map (take n) . iterate tail . cycle $ xs\n where\n n = length xs\n\nparse :: String -> String -> T Char\nparse [c1, c2] [c3, c4] = T [c1, c2, c4, c3]\n\ngetT :: IO (T Char)\ngetT = liftM2 parse (while (== \"**\") getLine) getLine\n\nsolve :: [T Char] -> Int\nsolve = length . nub\n\nwhile :: Monad m => (a -> Bool) -> m a -> m a\nwhile f ma = do\n a <- ma\n if f a\n then while f ma\n else return a\n\nmain :: IO ()\nmain = readLn >>= flip replicateM getT >>= print . solve\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]"}, {"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf(\"**\":s)=f s\nf([a,b]:[c,d]:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]\n"}, {"source_code": "import Data.Set\nmain = interact solve\nsolve input = show $ size $ f $ lines input\nf [] = empty\nf (x:y:z:xs) = insert (minimum $ take 4 $ iterate g (y ++ reverse z)) (f xs)\ng (x:xs) = xs ++ [x]\n"}], "negative_code": [{"source_code": "import Data.List\nmain=interact$show.length.group.sort.f.tail.lines\nf([a,b]:[c,d]:_:s)=minimum[[a,b,d,c],[b,d,c,a],[d,c,a,b],[c,a,b,d]]:f s\nf _=[]"}], "src_uid": "3de36638239deacac56e104d3dce1670"} {"source_code": "{-\nFind max x + y + z such as, a * x + b * y + c * z = n\nFor given a, b, c and n\n-}\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ main' powder $ zip recipe stock\n\nmain' :: Integer -> [(Integer, Integer)] -> Integer\nmain' powder recIng = findMax (0, max' + powder) recIng powder\n where max' = sum $ map snd recIng\n\nfindMax :: (Integer, Integer) -> [(Integer, Integer)] -> Integer -> Integer\nfindMax (start, end) recIng powder\n | (start == end - 1) && canCookMid && (not canCookMid') = start\n | (start == end - 1) && canCookMid && canCookMid' = end\n | start == end = end\n | canCookMid = findMax (mid, end) recIng powder\n | otherwise = findMax (start, mid) recIng powder\n where\n mid = start + ((end - start) `quot` 2)\n canCookMid = canCookN mid recIng powder\n canCookMid' = canCookN (mid + 1) recIng powder\n\ncanCookN :: Integer -> [(Integer, Integer)] -> Integer -> Bool\ncanCookN n recInt powder\n | n == 0 = True\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i\n", "positive_code": [{"source_code": "{-\nFind max x + y + z such as, a * x + b * y + c * z = n\nFor given a, b, c and n\n-}\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ main' powder $ zip recipe stock\n\nmain' :: Integer -> [(Integer, Integer)] -> Integer\nmain' powder recIng = findMaxCook (0, 2 * 10^9) recIng powder\n\nfindMaxCook :: (Integer, Integer) -> [(Integer, Integer)] -> Integer -> Integer\nfindMaxCook (start, end) recIng powder\n -- | and [not ccN, n' == 1] = base\n | ccEnd = end\n | and [ccN, not ccN1] = mid\n | ccN = findMaxCook (mid, end) recIng powder\n | otherwise = findMaxCook (start, mid) recIng powder\n where\n mid = start + ((end - start) `quot` 2)\n ccN = canCookN mid recIng powder\n ccEnd = canCookN end recIng powder\n ccN1 = canCookN (mid + 1) recIng powder\n\ncanCookN :: Integer -> [(Integer, Integer)] -> Integer -> Bool\ncanCookN n recInt powder\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i"}, {"source_code": "\n\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nreadInt = fromIntegral . fst . fromJust . BS8.readInteger\n\nreadIntsLine = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nreadLine = BS8.getLine >>= return . map readInt . BS8.words\n\n-- can cook more if powder > then sum of all missing ingridients\ncanCook need has powder x = (powder >=) . sum . filter ( > 0 ) . map (\\(need, has) -> need * x - has) $ zip need has\n\n\ncook _canCook from to limit\n | to > limit = cook _canCook from limit limit -- limit yourself\n | from == to && _canCook to = to\n | from == to && not (_canCook to) = 0 -- can't cook anything\n | to - from == 1 && _canCook to = to\n | from == cookies && _canCook cookies = cookies -- found answer\n | _canCook cookies = cook _canCook cookies (cookies * 2) limit -- can cook more so search\n | otherwise = cook _canCook from cookies limit -- search on the left\n where cookies = (from + to) `quot` 2\n\nmain = do\n [_, powder] <- readLine\n need <- readLine\n has <- readLine\n let maxCookies = (sum has + powder + 1) `quot` sum need\n print $ cook (canCook need has powder) 1 4 maxCookies"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nprove magicPowder recipe stock n =\n (magicPowder >=) . sum . filter (> 0) . map (\\(r,s) -> r * n - s) $ zip recipe stock\n\nbs f l h =\n let\n middle = quot (h - l) 2 + l\n in\n if middle == l then\n middle\n else\n if f middle then\n bs f middle h\n else\n bs f l middle\n\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, magicPowder] <- readLine \n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $\n bs (prove magicPowder recipe stock)\n -- always possible to bake zero\n 0\n -- never possible to bake more than maximum in stock plus all magic powder\n -- even if we need only one gram per cookie\n (maximum stock + magicPowder + 1)\n"}, {"source_code": "-- priority queue\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nprove magicPowder recipe stock n =\n (magicPowder >=) . sum . filter (> 0) . map (\\(r,s) -> r * n - s) $ zip recipe stock\n\nbs f l h =\n let\n middle = quot (h - l) 2 + l\n in\n if middle == l then\n middle\n else\n if f middle then\n bs f middle h\n else\n bs f l middle\n\nmain = do\n [ingrNumber, magicPowder] <- B.getLine >>= return . map readInt . B.words\n recipe <- B.getLine >>= return . map readInt . B.words\n stock <- B.getLine >>= return . map readInt . B.words\n B.putStrLn . B.pack . show $\n bs (prove magicPowder recipe stock)\n -- always possible to bake zero\n 0\n -- never possible to bake more than maximum in stock plus all magic powder\n -- even if we need only one gram per cookie\n (maximum stock + magicPowder + 1)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nreadInt = fromIntegral . fst . fromJust . BS8.readInteger\n\nreadIntsLine = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\nreadLine = BS8.getLine >>= return . map readInt . BS8.words\n\n-- can cook more if powder > then sum of all missing ingridients\ncanCook need has powder x = (powder >=) . sum . filter ( > 0 ) . map (\\(need, has) -> need * x - has) $ zip need has\n\n\ncook _canCook from to limit\n | to > limit = cook _canCook from limit limit -- limit yourself\n | from == to = 0 -- can't cook anything\n | to - from == 1 && _canCook to = to\n | from == cookies && _canCook cookies = cookies -- found answer\n | _canCook cookies = cook _canCook cookies (cookies * 2) limit -- can cook more so search\n | otherwise = cook _canCook from cookies limit -- search on the left\n where cookies = (from + to) `quot` 2\n\nmain = do\n [_, powder] <- readLine\n need <- readLine\n has <- readLine\n let maxCookies = (sum has + powder + 1) `quot` sum need\n print $ cook (canCook need has powder) 1 4 maxCookies"}, {"source_code": "{-\nFind max x + y + z such as, a * x + b * y + c * z = n\nFor given a, b, c and n\n-}\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ main' powder $ zip recipe stock\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' powder recIng = findMax (0, max' + powder) recIng powder\n where max' = sum $ map snd recIng\n\nfindMax :: (Int, Int) -> [(Int, Int)] -> Int -> Int\nfindMax (start, end) recIng powder\n | (start == end - 1) && canCookMid && (not canCookMid') = start\n | (start == end - 1) && canCookMid && canCookMid' = end\n | start == end = end\n | canCookMid = findMax (mid, end) recIng powder\n | otherwise = findMax (start, mid) recIng powder\n where\n mid = start + ((end - start) `quot` 2)\n canCookMid = canCookN mid recIng powder\n canCookMid' = canCookN (mid + 1) recIng powder\n\ncanCookN :: Int -> [(Int, Int)] -> Int -> Bool\ncanCookN n recInt powder\n | n == 0 = True\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ main' powder $ zip recipe stock\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' powder recIng = findMaxCook (0, 2 * 10^9) recIng powder\n\nfindMaxCook :: (Int, Int) -> [(Int, Int)] -> Int -> Int\nfindMaxCook (start, end) recIng powder\n -- | and [not ccN, n' == 1] = base\n | ccEnd = end\n | and [ccN, not ccN1] = mid\n | ccN = findMaxCook (mid, end) recIng powder\n | otherwise = findMaxCook (start, mid) recIng powder\n where\n mid = start + ((end - start) `div` 2)\n ccN = canCookN mid recIng powder\n ccEnd = canCookN end recIng powder\n ccN1 = canCookN (mid + 1) recIng powder\n\ncanCookN :: Int -> [(Int, Int)] -> Int -> Bool\ncanCookN n recInt powder\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i\n"}, {"source_code": "{-\nFind max x + y + z such as, a * x + b * y + c * z = n\nFor given a, b, c and n\n-}\nmodule Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ main' powder $ zip recipe stock\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' powder recIng = findMaxCook (0, 2 * 10^9) recIng powder\n\nfindMaxCook :: (Int, Int) -> [(Int, Int)] -> Int -> Int\nfindMaxCook (start, end) recIng powder\n -- | and [not ccN, n' == 1] = base\n | ccEnd = end\n | and [ccN, not ccN1] = mid\n | ccN = findMaxCook (mid, end) recIng powder\n | otherwise = findMaxCook (start, mid) recIng powder\n where\n mid = start + ((end - start) `quot` 2)\n ccN = canCookN mid recIng powder\n ccEnd = canCookN end recIng powder\n ccN1 = canCookN (mid + 1) recIng powder\n\ncanCookN :: Int -> [(Int, Int)] -> Int -> Bool\ncanCookN n recInt powder\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ main' powder $ zip recipe stock\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' powder recIng = findMaxCook (0, max' + powder) recIng powder\n where max' = foldr (\\(_, y) agg -> agg + y ) 0 recIng\n\nfindMaxCook :: (Int, Int) -> [(Int, Int)] -> Int -> Int\nfindMaxCook (start, end) recIng powder\n -- | and [not ccN, n' == 1] = base\n | ccEnd = end\n | and [ccN, not ccN1] = mid\n | ccN = findMaxCook (mid, end) recIng powder\n | otherwise = findMaxCook (start, mid) recIng powder\n where\n mid = start + ((end - start) `quot` 2)\n ccN = canCookN mid recIng powder\n ccEnd = canCookN end recIng powder\n ccN1 = canCookN (mid + 1) recIng powder\n\ncanCookN :: Int -> [(Int, Int)] -> Int -> Bool\ncanCookN n recInt powder\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i\n"}, {"source_code": "module Main where\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\nreadLine =\n B.getLine >>= return . map readInt . B.words\n\nmain = do\n [_, powder] <- readLine\n recipe <- readLine\n stock <- readLine\n B.putStrLn . B.pack . show $ 1000000000-- main' powder $ zip recipe stock\n\nmain' :: Int -> [(Int, Int)] -> Int\nmain' powder recIng = findMaxCook 1 0 recIng powder\n\nfindMaxCook :: Int -> Int -> [(Int, Int)] -> Int -> Int\nfindMaxCook n base recIng powder\n | and [not ccN, n' == 1] = base\n | and [ccN, not ccN1] = n'\n | ccN = findMaxCook (n * 2) base recIng powder\n | otherwise = findMaxCook 1 (base + (n `div` 2)) recIng powder\n where\n n' = n + base\n ccN = canCookN n' recIng powder\n ccN1 = canCookN (n' + 1) recIng powder\n\ncanCookN :: Int -> [(Int, Int)] -> Int -> Bool\ncanCookN n recInt powder\n | powderLeft < 0 = False\n | otherwise = True\n where\n powderLeft = foldr addIngridient powder recInt\n addIngridient (r, i) left\n | left < 0 = left\n | r * n < i = left\n | otherwise = left - r * n + i\n"}, {"source_code": "-- priority queue\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nreadInt = fromIntegral . fst . fromJust . B.readInteger\n\nprove magicPowder recipe stock n =\n (magicPowder >=) . sum . map (\\(r,s) -> r * n - s) $ zip recipe stock\n\nbs f l h =\n let\n middle = quot (h - l) 2 + l\n in\n if middle == l then\n middle\n else\n if f middle then\n bs f middle h\n else\n bs f l middle\n\nmain = do\n [ingrNumber, magicPowder] <- B.getLine >>= return . map readInt . B.words\n recipe <- B.getLine >>= return . map readInt . B.words\n stock <- B.getLine >>= return . map readInt . B.words\n B.putStrLn . B.pack . show $\n bs (prove magicPowder recipe stock)\n 0\n (maximum stock + magicPowder + 1)\n"}], "src_uid": "ab1b4487899609ac0f882e1b1713d162"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM, mapM_)\nimport Data.List (sort)\nimport Data.Functor ((<$>))\n\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport qualified Data.Text.Read as T\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as I\n\n{-\nimport Data.IntMultiSet (IntMultiSet)\nimport qualified Data.IntMultiSet as I\n\n\n\nparseInt :: Text -> Int \nparseInt !t = \n case T.decimal t of\n Left _ -> error \"wtf\"\n Right (x, _) -> x\n\nbeersI :: IntMultiSet -> [Int] -> [Int]\nbeersI !prices !coins = map (\\c -> I.size (I.filter (<=c) prices)) coins\n\nmainI :: IO ()\nmainI = do\n n <- parseInt <$> T.getLine\n prices <- map parseInt . T.splitOn \" \" <$> T.getLine\n q <- parseInt <$> T.getLine\n coins <- replicateM q (parseInt <$> T.getLine)\n mapM_ print (beersI (I.fromList prices) coins)\n --mapM_ print (beers (sort prices) coins)\n -} \n\n{- prefix sums of sorted int list -}\nprefixSum :: [Int] -> IntMap Int\nprefixSum xs0 = go xs0 0 0 I.empty\n where\n go !xs y i ps =\n case xs of\n [] -> (I.insert y i ps)\n x:xs' | x <= y -> go xs' y (i+1) ps\n | otherwise -> go xs (y+1) i (I.insert y i ps)\n\nbeers :: [Int] -> [Int] -> [Int]\nbeers !prices !coins = map (\\c -> length (takeWhile (<=c) prices)) coins\n\nparseIntS :: String-> Int \nparseIntS !s = read s\n\nsplitS :: String -> [String]\nsplitS !s0 = splitH s0 \"\" where\n splitH !cs !ds =\n case cs of\n \"\" -> if null ds then [] else [reverse ds]\n ' ':cs' -> if null ds then splitH cs' ds else reverse ds : splitH cs' \"\"\n c:cs' -> splitH cs' (c:ds)\n \n\nmainS :: IO ()\nmainS = do\n n <- parseIntS <$> getLine\n prices <- map parseIntS . splitS <$> getLine\n q <- parseIntS <$> getLine\n coins <- replicateM q (parseIntS <$> getLine)\n mapM_ print (beers (sort prices) coins)\n \n\nmainIM :: IO ()\nmainIM = do\n n <- parseIntS <$> getLine\n prices <- map parseIntS . splitS <$> getLine\n q <- parseIntS <$> getLine\n coins <- replicateM q (parseIntS <$> getLine)\n let ps = prefixSum (sort prices)\n mapM_ (\\c -> print (I.findWithDefault (length prices) c ps)) coins\n\nmain = mainIM\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n-- for codeforces\nimport Data.Ord\nsortOn f =\n map snd . sortBy (comparing fst) . map (\\x -> let y = f x in y `seq` (y, x))\n\ntype I = Int\n\nmain :: IO ()\nmain = do\n n <- readi <$> getLine\n xs <- map readi . words <$> getLine\n q <- readi <$> getLine\n ms <- map readi <$> replicateM q getLine\n mapM_ print $ fst . unzip . sortOn snd $ solve (sortOn fst $ zip ms [1..]) (sort xs) 0\n\nsolve :: [(I, I)] -> [I] -> I -> [(I, I)]\nsolve [] _ _ = []\nsolve ((q, p):qs) xs n =\n (n', p) : solve qs (dropWhile (<= q) xs) n' where\n n' = n + length (takeWhile (<= q) xs)\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\nreadi :: String -> I\nreadi = read\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] = (x, y, z)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map as M\nimport Data.Maybe\n\n\n\nmain = do\n\t\tgetLine\n\t\tn<- sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tlet m = M.fromAscList $ zip n [1..] \n\t\tgetLine\n\t\tq<- map read <$> words <$> getContents :: IO [Int]\n\t\tmapM_ print $ map (\\z-> snd (fromMaybe (0,0) (M.lookupLE z m))) q\n\t\t\n"}, {"source_code": "{-# OPTIONS -XBangPatterns #-}\nimport Data.List (sort)\nimport Data.Array.Unboxed\nmain = do\n\tn <- readLn :: IO Int\n\ta <- fmap (listArray (1,n) . sort . ((map read) . words)) getLine :: IO (UArray Int Int)\n\tq <- readLn :: IO Int\n\t\n\tlet binary_search !l !r !e\n\t\t\t|a!l > e || l==r = l-1\n\t\t\t|r-l == 1 = l\n\t\t\t|otherwise =\n\t\t\t\tlet m = (l+r) `div` 2\n\t\t\t\tin if e < a!m\n\t\t\t\t\t\tthen binary_search l m e\n\t\t\t\t\t\telse binary_search m r e\n\t\t\t\t\t\n\tflip mapM [1..q] $ \\i -> do\n\t\tx <- readLn :: IO Int\n\t\tlet ans = binary_search 1 n x\n\t\tif a!(ans+1) <= x\n\t\t\tthen print $ ans+1\n\t\t\telse print ans"}, {"source_code": "import Data.List (sort)\nimport Data.Array.Unboxed\nmain = do\n\tn <- readLn :: IO Int\n\ta <- fmap (listArray (1,n) . sort . ((map read) . words)) getLine :: IO (UArray Int Int)\n\tq <- readLn :: IO Int\n\t\n\tlet binary_search l r e\n\t\t\t|a!l > e || l==r = l-1\n\t\t\t|r-l == 1 = l\n\t\t\t|otherwise =\n\t\t\t\tlet m = (l+r) `div` 2\n\t\t\t\tin if e < a!m\n\t\t\t\t\t\tthen binary_search l m e\n\t\t\t\t\t\telse binary_search m r e\n\t\t\t\t\t\n\tflip mapM [1..q] $ \\i -> do\n\t\tx <- readLn :: IO Int\n\t\tlet ans = binary_search 1 n x\n\t\tif a!(ans+1) <= x\n\t\t\tthen print $ ans+1\n\t\t\telse print ans"}, {"source_code": "import Control.Applicative ((<$>))\nimport Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)\nimport Data.Maybe (fromJust)\nimport Control.Monad (replicateM)\nimport Data.Array.IArray (listArray, (!))\nimport Data.Array.Unboxed (UArray)\nimport Data.List (sort)\nimport Prelude hiding (words, lines, getLine, getContents)\n\nreadInt' = fst . fromJust . readInt\nreadInts = map readInt' . words <$> getLine\n\nmain = do\n [n] <- readInts\n xs <- readInts\n [q] <- readInts\n ms <- replicateM q (readInt' <$> getLine)\n\n let\n a = listArray (1, n) $ sort xs :: UArray Int Int\n\n count x = search 1 n\n where\n search l r\n | l >= r = if v<= x then l else 0\n | x >= v = search m r\n | x < v = search l (m-1)\n where\n m = (l+r+1)`div`2\n v = a!m\n\n putStr $ unlines $ map show $ map count ms\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = forM [1..3] (return C.getLine)>>= (\\(a:bs:c:[]) ->solve.([map rIn $ C.words bs] ++).(\\ls->[ls])=<rIn<$>C.getLine) )\nsolve [xs,ys]= let ma_x = maximum xs; zs = zip [1..] $ uncurry (zipWith (\\(a1,a2) (b1,b2)->(a1,(a2,b2)))) $ (id&&&tail) $ scanl (\\(b1,b2) (a1,a2)->(b1+a1,a2) ) (0,0) $ map (length&&&head) $ group $ sort xs; ms = Map.fromList zs; len = length zs; tre=tre_e ((Map.!) ms) (1,len); len2= length xs in forM_ ys $ \\i-> if i>=ma_x then print len2 else print $ slv1 i tre\ntre_e f (x,y) = unfoldTree g (x,y)\n where g (a,b) = let z= (a+)$ div (b-a) 2 in if a>=b then (f a, []) else if a/=z then (f z, [(a,z-1),(z+1,b)]) else (f z, [(z+1,b)])\nslv1 n (Node (x,(y,z)) ts) = if n>=y&&n=z then slv1 n (last ts) else slv1 n (head ts)\n"}, {"source_code": "import Data.Array\nimport Data.List\nimport Control.Monad\nmain = do\n n <- readLn\n ps <- listArray (0,n) . (0 :) . sort . map read . words <$> getLine\n let bsearch g = go 0 n where\n go a b | a >= b = b\n | g >= v = go m b\n | otherwise = go a (m-1)\n where m = (a + b + 1) `div` 2\n v = ps!m :: Int\n q <- readLn\n replicateM_ q $ print . bsearch =<< readLn\n"}], "negative_code": [{"source_code": "import Data.List (sort)\nimport Data.Array.Unboxed\nmain = do\n\tn <- readLn :: IO Int\n\ta <- fmap (listArray (1,n) . sort . ((map read) . words)) getLine :: IO (UArray Int Int)\n\tq <- readLn :: IO Int\n\t\n\tlet binary_search l r e =\n\t\tif r-l <= 1\n\t\t\tthen l\n\t\t\telse\n\t\t\t\tlet\n\t\t\t\t\tm = (l+r) `div` 2\n\t\t\t\t\tval = a!m\n\t\t\t\tin if e <= val\n\t\t\t\t\tthen binary_search l m e\n\t\t\t\t\telse binary_search m r e \n\t\t\t\t\t\n\tflip mapM [1..q] $ \\i -> do\n\t\tx <- readLn :: IO Int\n\t\tlet ans = binary_search 1 (n-1) x\n\t\tif (a!ans > x) then print $ ans-1\n\t\telse if (a!(ans+1) <= x) then print $ ans+1\n\t\telse print ans"}, {"source_code": "import Data.List (sort)\nimport Data.Array.Unboxed\nmain = do\n\tn <- readLn :: IO Int\n\ta <- fmap (listArray (1,n) . sort . ((map read) . words)) getLine :: IO (UArray Int Int)\n\tq <- readLn :: IO Int\n\t\n\tlet binary_search l r e =\n\t\tif l>=r\n\t\t\tthen l\n\t\t\telse\n\t\t\t\tlet\n\t\t\t\t\tm = (l+r) `div` 2\n\t\t\t\t\tval = a!m\n\t\t\t\tin if val == e \n\t\t\t\t\tthen m\n\t\t\t\t\telse if e < val\n\t\t\t\t\t\t\tthen binary_search l m e\n\t\t\t\t\t\t\telse binary_search (m+1) r e \n\t\t\t\t\t\n\tflip mapM [1..q] $ \\i -> do\n\t\tx <- readLn :: IO Int\n\t\tlet ans = binary_search 1 n x\n\t\tif (a!ans > x)\n\t\t\tthen print $ ans-1\n\t\t\telse print ans"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Function\nimport Data.Ord\nimport Data.Bits\nimport Data.Monoid\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= someFunc\nrIn x= fst $ fromJust $ C.readInt x\nsomeFunc::IO()\nsomeFunc = forM [1..3] (return C.getLine)>>= (\\(a:bs:c:[]) ->solve.([map rIn $ C.words bs] ++).(\\ls->[ls])=<rIn<$>C.getLine) )\nsolve [xs,ys]= let ma_x = maximum xs; zs = zip [1..] $ uncurry (zipWith (\\(a1,a2) (b1,b2)->(a1,(a2,b2)))) $ (id&&&tail) $ scanl (\\(b1,b2) (a1,a2)->(b1+a1,a2) ) (0,0) $ map (length&&&head) $ group $ sort xs; ms = Map.fromList zs; len = length zs; tre=tre_e ((Map.!) ms) (1,len) in forM_ ys $ \\i-> if i>=ma_x then print len else print $ slv1 i tre\ntre_e f (x,y) = unfoldTree g (x,y)\n where g (a,b) = let z= (a+)$ div (b-a) 2 in if a>=b then (f a, []) else if a/=z then (f z, [(a,z-1),(z+1,b)]) else (f z, [(z+1,b)])\nslv1 n (Node (x,(y,z)) ts) = if n>=y&&n=z then slv1 n (last ts) else slv1 n (head ts)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM, mapM_)\nimport Data.List (sort)\nimport Data.Functor ((<$>))\n\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport qualified Data.Text.Read as T\n\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as I\n\n{-\nimport Data.IntMultiSet (IntMultiSet)\nimport qualified Data.IntMultiSet as I\n\n\n\nparseInt :: Text -> Int \nparseInt !t = \n case T.decimal t of\n Left _ -> error \"wtf\"\n Right (x, _) -> x\n\nbeersI :: IntMultiSet -> [Int] -> [Int]\nbeersI !prices !coins = map (\\c -> I.size (I.filter (<=c) prices)) coins\n\nmainI :: IO ()\nmainI = do\n n <- parseInt <$> T.getLine\n prices <- map parseInt . T.splitOn \" \" <$> T.getLine\n q <- parseInt <$> T.getLine\n coins <- replicateM q (parseInt <$> T.getLine)\n mapM_ print (beersI (I.fromList prices) coins)\n --mapM_ print (beers (sort prices) coins)\n -} \n\n{- prefix sums of sorted int list -}\nprefixSum :: [Int] -> IntMap Int\nprefixSum xs0 = go xs0 0 0 I.empty\n where\n go !xs y i ps =\n case xs of\n [] -> (I.insert y i ps)\n x:xs' | x <= y -> go xs' y (i+1) ps\n | otherwise -> go xs (y+1) i (I.insert y i ps)\n\nbeers :: [Int] -> [Int] -> [Int]\nbeers !prices !coins = map (\\c -> length (takeWhile (<=c) prices)) coins\n\nparseIntS :: String-> Int \nparseIntS !s = read s\n\nsplitS :: String -> [String]\nsplitS !s0 = splitH s0 \"\" where\n splitH !cs !ds =\n case cs of\n \"\" -> if null ds then [] else [reverse ds]\n ' ':cs' -> if null ds then splitH cs' ds else reverse ds : splitH cs' \"\"\n c:cs' -> splitH cs' (c:ds)\n \n\nmainS :: IO ()\nmainS = do\n n <- parseIntS <$> getLine\n prices <- map parseIntS . splitS <$> getLine\n q <- parseIntS <$> getLine\n coins <- replicateM q (parseIntS <$> getLine)\n mapM_ print (beers (sort prices) coins)\n \n\nmainIM :: IO ()\nmainIM = do\n n <- parseIntS <$> getLine\n prices <- map parseIntS . splitS <$> getLine\n q <- parseIntS <$> getLine\n coins <- replicateM q (parseIntS <$> getLine)\n let ps = prefixSum (sort prices)\n mapM_ (\\c -> print (I.findWithDefault 0 c ps)) coins\n\nmain = mainIM\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad (replicateM, mapM_)\nimport Data.List (sort)\nimport Data.Functor ((<$>))\n\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport qualified Data.Text.Read as T\n\nimport Data.Set (Set)\nimport qualified Data.Set as S\n\n\n\nparseInt :: Text -> Int \nparseInt !t = \n case T.decimal t of\n Left _ -> error \"wtf\"\n Right (x, _) -> x\n\nbeersS :: Set Int -> [Int] -> [Int]\nbeersS !prices !coins = map (\\c -> S.size (S.filter (<=c) prices)) coins\n\nmain :: IO ()\nmain = do\n n <- parseInt <$> T.getLine\n prices <- map parseInt . T.splitOn \" \" <$> T.getLine\n q <- parseInt <$> T.getLine\n coins <- replicateM q (parseInt <$> T.getLine)\n mapM_ print (beersS (S.fromList prices) coins)\n --mapM_ print (beers (sort prices) coins)\n \nbeers :: [Int] -> [Int] -> [Int]\nbeers !prices !coins = map (\\c -> length (takeWhile (<=c) prices)) coins\n\nparseIntS :: String-> Int \nparseIntS !s = read s\n\nsplitS :: String -> [String]\nsplitS !s0 = splitH s0 \"\" where\n splitH !cs !ds =\n case cs of\n \"\" -> if null ds then [] else [reverse ds]\n ' ':cs' -> if null ds then splitH cs' ds else reverse ds : splitH cs' \"\"\n c:cs' -> splitH cs' (c:ds)\n \n\nmainS :: IO ()\nmainS = do\n n <- parseIntS <$> getLine\n prices <- map parseIntS . splitS <$> getLine\n q <- parseIntS <$> getLine\n coins <- replicateM q (parseIntS <$> getLine)\n mapM_ print (beers (sort prices) coins)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n-- for codeforces\nimport Data.Ord\nsortOn f =\n map snd . sortBy (comparing fst) . map (\\x -> let y = f x in y `seq` (y, x))\n\ntype I = Int\n\nmain :: IO ()\nmain = do\n n <- readi <$> getLine\n xs <- map readi . words <$> getLine\n q <- readi <$> getLine\n ms <- map readi <$> replicateM q getLine\n print $ fst . unzip . sortOn snd $ solve (sortOn fst $ zip ms [1..]) (sort xs) 0\n\nsolve :: [(I, I)] -> [I] -> I -> [(I, I)]\nsolve [] _ _ = []\nsolve ((q, p):qs) xs n =\n (n', p) : solve qs (dropWhile (<= q) xs) n' where\n n' = n + length (takeWhile (<= q) xs)\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\nreadi :: String -> I\nreadi = read\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] = (x, y, z)\n"}], "src_uid": "80a03e6d513f4051175cd5cd1dea33b4"} {"source_code": "import Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printList $ map (map (n-) . reverse . take n . operations . (2^)) [0..k-1]\n\noperations k = replicate k 0 ++ [0..k+1] ++ repeat k\n\nprintList = putStrLn . concat . intersperse \" \" . map show\n", "positive_code": [{"source_code": "import Data.Bits\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map read . words) getLine\n let ans = [take n $ (0:) $ cycle $ replicate b 0 ++ replicate b b |\n b <- map (2^) [0 .. m - 1]]\n putStr $ unlines $ [unwords $ reverse $ map (show . (n-)) i | i <- ans]\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\ngetLine' :: Int -> Int -> [Int]\ngetLine' n i = reverse $ take n $ concat\n [\n [n],\n replicate (2^(i-1)) n,\n [n-1, n-2 .. n-2^(i-1)],\n repeat (n-2^(i-1))\n ]\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n mapM_ (prints . getLine' n) [1..k]\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "l=map(\\n->0:replicate(2^n)0++[1..2^n]++repeat(2^n))[0..]\ns[n,k]=map(map(n-))$map reverse$take k(map(take n)l)\nmain=interact$unlines.map(unwords.map show).s.map read.words"}], "negative_code": [{"source_code": "import Data.Bits\n\nmain :: IO ()\nmain = do\n [n, m] <- fmap (map read . words) getLine\n let ans = [[if (i == 2 * b || (i /= b && j)) then b else 0 | (i, j) <- zip [0 ..] d] |\n b <- map (2^) [0 .. m - 1],\n let d = take n $ cycle $ replicate b False ++ replicate b True]\n putStr $ unlines $ [unwords $ reverse $ map (show . (n-)) i | i <- ans]\n"}, {"source_code": "import Data.Bits ((.&.), shiftL)\nimport Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printOps $ map (buildOps n) $ take k solve\n\nsolve = ((0:) $ concat $ repeat [0,1]):([0,0,0,2] ++ (drop 4 $ operations 3 2)):(map (\\k -> operations (1 `shiftL` k) k) [2..])\n\noperations mask k = map getCi [0..]\n where\n getCi x | x <= mask = 0\n | isPowerOfTwo x = x\n | x .&. mask == mask = k\n | otherwise = 0\n\nisPowerOfTwo 0 = False\nisPowerOfTwo 1 = True\nisPowerOfTwo x = x .&. 1 == 0 && isPowerOfTwo (x `div` 2)\n\nbuildOps n = reverse . map (n -) . take n\n\nprintOps = putStrLn . concat . intersperse \" \" . map show\n"}, {"source_code": "import Data.Bits ((.&.), shiftL)\nimport Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printOps $ map (buildOps n) $ take k solve\n\nsolve = ((0:) $ concat $ repeat [0,1]):([0,0,0,2] ++ (drop 4 $ operations' 3 2)):(map (\\k -> operations $ 1 `shiftL` k) [2..])\n\noperations k = operations' k k\n\noperations' mask k = map getCi [0..]\n where\n getCi x | x <= mask = 0\n | isPowerOfTwo x = x\n | x .&. mask == mask = k\n | otherwise = 0\n\nisPowerOfTwo 0 = False\nisPowerOfTwo 1 = True\nisPowerOfTwo x = x .&. 1 == 0 && isPowerOfTwo (x `div` 2)\n\nbuildOps n = reverse . map (n -) . take n\n\nprintOps = putStrLn . concat . intersperse \" \" . map show\n"}, {"source_code": "import Data.Bits ((.&.), shiftL)\nimport Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printOps $ map (buildOps n) $ take k solve\n\nsolve = ((0:) $ concat $ repeat [0,1]):([0,0,0,2] ++ (drop 4 $ operations' 3 2)):(map (\\k -> operations $ 1 `shiftL` k) [2..])\n\noperations k = operations' k k\n\noperations' mask k = map getCi [0..]\n where\n getCi x | x <= mask = 0\n | x .&. (k - 1) == 0 = x\n | x .&. mask == mask = k\n | otherwise = 0\n\nbuildOps n = reverse . map (n -) . take n\n\nprintOps = putStrLn . concat . intersperse \" \" . map show"}, {"source_code": "import Data.Bits ((.&.), shiftL)\nimport Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printOps $ map (buildOps n) $ take k solve\n\nsolve = ((0:) $ concat $ repeat [0,1]):([0,0,0,2] ++ (drop 4 $ operations 3 2)):(map (\\k -> operations (1 `shiftL` k) k) [2..])\n\noperations mask k = map getCi [0..]\n where\n getCi x | x <= mask = 0\n | isPowerOfTwo x = x\n | x .&. mask == mask = mask\n | otherwise = 0\n\nisPowerOfTwo 0 = False\nisPowerOfTwo 1 = True\nisPowerOfTwo x = x .&. 1 == 0 && isPowerOfTwo (x `div` 2)\n\nbuildOps n = reverse . map (n -) . take n\n\nprintOps = putStrLn . concat . intersperse \" \" . map show\n"}, {"source_code": "import Data.Bits ((.&.), shiftL)\nimport Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printOps $ map (buildOps n) $ take k solve\n\nsolve = ((0:) $ concat $ repeat [0,1]):([0,0,0,2,2] ++ (concat $ repeat [0,0,2,0])):(map operations [2..])\n\noperations k = map getCi [0..]\n where\n bit = 1 `shiftL` k\n getCi x | x <= bit = 0\n | isPowerOfTwo x = x\n | x .&. bit == bit = bit\n | otherwise = 0\n\nisPowerOfTwo 0 = False\nisPowerOfTwo 1 = True\nisPowerOfTwo x = x .&. 1 == 0 && isPowerOfTwo (x `div` 2)\n\nbuildOps n = reverse . map (n -) . take n\n\nprintOps = putStrLn . concat . intersperse \" \" . map show\n"}, {"source_code": "import Data.Bits ((.&.), shiftL)\nimport Data.List (intersperse)\nimport Control.Applicative ((<$>))\n\nmain = do\n [n, k] <- map read . words <$> getLine\n mapM_ printOps $ map (buildOps n) $ take k solve\n\nsolve = ((0:) $ concat $ repeat [0,1]):([0,0,0,1,2] ++ (concat $ repeat [0,0,1,0])):(map operations [2..])\n\noperations k = map getCi [0..]\n where\n bit = 1 `shiftL` k\n getCi x | x <= bit = 0\n | isPowerOfTwo x = x\n | x .&. bit == bit = bit\n\nisPowerOfTwo 0 = False\nisPowerOfTwo 1 = True\nisPowerOfTwo x = x .&. 1 == 0 && isPowerOfTwo (x `div` 2)\n\nbuildOps n = reverse . map (n -) . take n\n\nprintOps = putStrLn . concat . intersperse \" \" . map show\n"}], "src_uid": "c8800840e52d4141acdff0420e7ec73c"} {"source_code": "import Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Foldable as Fold\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap.Strict as IM\nimport Data.Traversable\nimport qualified Data.Sequence as Seq\n--import Prelude hiding (foldl)\nimport qualified Data.Set as Set\nimport qualified Data.IntSet as IS\nimport Debug.Trace\n\ndata Tree = Node Int Int Tree Tree | Leaf\n deriving Show\n\nmain = do\n firstWords <- fmap BS.words BS.getLine\n let Just (n, _) = BS.readInt $ firstWords !! 0\n lines <- fmap BS.lines BS.getContents\n let firstLine = head lines\n let arrayN = (2^(n+1)-2)\n let lights = array (1, arrayN) $ zip [1..arrayN] (readLights firstLine)\n let tree = buildTree 1 (arrayN `div` 2) lights\n let maxLight = maxLights tree\n let x = lightsNeeded maxLight tree\n --putStrLn (show maxLight)\n --putStrLn (show tree)\n putStrLn (show x)\n\nreadLights :: BS.ByteString -> [Int]\nreadLights = map (fst. fromJust . BS.readInt) . BS.words\n\nbuildTree :: Int -> Int -> Array Int Int -> Tree\nbuildTree n max lights = \n if n > max\n then Leaf\n else let\n lTree = buildTree (2*n) max lights\n rTree = buildTree (2*n + 1) max lights\n in\n Node (lights ! (2*n-1)) (lights ! (2*n)) lTree rTree\n\nmaxLights :: Tree -> Int\nmaxLights Leaf = 0\nmaxLights (Node ln rn lTree rTree) =\n max (ln + maxLights lTree) (rn + maxLights rTree)\n\nlightsNeeded :: Int -> Tree -> Int\nlightsNeeded 0 Leaf = 0\nlightsNeeded goal (Node ln rn lTree rTree) =\n let\n ln' = goal - (maxLights lTree)\n rn' = goal - (maxLights rTree)\n x = (ln' - ln) + (lightsNeeded (goal - ln') lTree) +\n (rn' - rn) + (lightsNeeded (goal - rn') rTree)\n in\n --trace (\"ln: \" ++ (show ln) ++ \" -> \" ++ (show ln') ++ \" rn: \" ++ (show rn) ++ \" -> \" ++ (show rn')) x\n x\n", "positive_code": [{"source_code": "import Data.Bits(shiftL)\nimport Control.Monad\n\nmain = do\n n <- readInt `fmap` getLine\n a <- (map readInt . words) `fmap` getLine\n print (solveTaskB ((1 `shiftL` (n + 1)) - 1) (0 : a))\n\nsolveTaskB length lights =\n fst $ solveForIndex $ 0\n where\n solveForIndex index = if index * 2 + 2 >= length\n then (0, lights !! index)\n else (abs (lDep - rDep) + lAns + rAns, (lights !! index) + (max lDep rDep))\n where\n lAns = fst lSon\n rAns = fst rSon\n lDep = snd lSon\n rDep = snd rSon\n lSon = solveForIndex (2 * index + 1)\n rSon = solveForIndex (2 * index + 2)\n\nreadInt = read :: String -> Int\n"}, {"source_code": "main = do\n y <- getLine\n if y==\"0\" then putStrLn \"0\" else do\n x <- getLine\n putStrLn $ show $ solve (read y) (map read $ words x)\n \nsolve d x = s x (2^d-3)\n\ns x (-2) = 0\ns x to = abs(lSon - rSon) +\n s ((take to x)++[(x!!to) + max lSon rSon]++(drop (to+1) x)) (to-1)\n where\n lSon = x!!(2*to+2)\n rSon = x!!(2*to+3)"}], "negative_code": [{"source_code": "import Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Foldable as Fold\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap.Strict as IM\nimport Data.Traversable\nimport qualified Data.Sequence as Seq\n--import Prelude hiding (foldl)\nimport qualified Data.Set as Set\nimport qualified Data.IntSet as IS\nimport Debug.Trace\n\ndata Tree = Node Int Int Tree Tree | Leaf\n deriving Show\n\nmain = do\n firstWords <- fmap BS.words BS.getLine\n let Just (n, _) = BS.readInt $ firstWords !! 0\n lines <- fmap BS.lines BS.getContents\n let firstLine = head lines\n let lights = readLights firstLine\n let tree = buildTree (2^(n+1) - 2) lights\n let maxLight = maxLights tree\n let x = lightsNeeded maxLight tree\n putStrLn (show x)\n\nreadLights :: BS.ByteString -> [Int]\nreadLights = map (fst. fromJust . BS.readInt) . BS.words\n\nbuildTree :: Int -> [Int] -> Tree\nbuildTree 0 [] = Leaf\nbuildTree n (ln:rn:remLights) =\n let\n n' = (n `div` 2) - 1\n (lLights, rLights) = splitAt n' remLights\n in\n Node ln rn (buildTree n' lLights) (buildTree n' rLights)\n\nmaxLights :: Tree -> Int\nmaxLights Leaf = 0\nmaxLights (Node ln rn lTree rTree) =\n max (ln + maxLights lTree) (rn + maxLights rTree)\n\nlightsNeeded :: Int -> Tree -> Int\nlightsNeeded 0 Leaf = 0\nlightsNeeded goal (Node ln rn lTree rTree) =\n let\n ln' = goal - (maxLights lTree)\n rn' = goal - (maxLights rTree)\n in\n (ln' - ln) + (lightsNeeded (goal - ln') lTree) +\n (rn' - rn) + (lightsNeeded (goal - rn') rTree)\n"}, {"source_code": "import Data.Array\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Foldable as Fold\nimport Data.Int\nimport Data.List\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.IntMap.Strict as IM\nimport Data.Traversable\nimport qualified Data.Sequence as Seq\n--import Prelude hiding (foldl)\nimport qualified Data.Set as Set\nimport qualified Data.IntSet as IS\nimport Debug.Trace\n\ndata Tree = Node Int Int Tree Tree | Leaf\n deriving Show\n\nmain = do\n firstWords <- fmap BS.words BS.getLine\n let Just (n, _) = BS.readInt $ firstWords !! 0\n lines <- fmap BS.lines BS.getContents\n let firstLine = head lines\n let lights = readLights firstLine\n let (tree, _) = buildTree n lights\n let maxLight = maxLights tree\n let x = lightsNeeded maxLight tree\n putStrLn (show x)\n\nreadLights :: BS.ByteString -> [Int]\nreadLights = map (fst. fromJust . BS.readInt) . BS.words\n\nbuildTree :: Int -> [Int] -> (Tree, [Int])\nbuildTree 0 xs = (Leaf, xs)\nbuildTree n (ln:rn:remLights) =\n let\n (lTree, remLights') = buildTree (n-1) remLights\n (rTree, remLights'') = buildTree (n-1) remLights'\n in\n (Node ln rn lTree rTree, remLights'')\n\nmaxLights :: Tree -> Int\nmaxLights Leaf = 0\nmaxLights (Node ln rn lTree rTree) =\n max (ln + maxLights lTree) (rn + maxLights rTree)\n\nlightsNeeded :: Int -> Tree -> Int\nlightsNeeded 0 Leaf = 0\nlightsNeeded goal (Node ln rn lTree rTree) =\n let\n ln' = goal - (maxLights lTree)\n rn' = goal - (maxLights rTree)\n in\n (ln' - ln) + (lightsNeeded (goal - ln') lTree) +\n (rn' - rn) + (lightsNeeded (goal - rn') rTree)\n"}, {"source_code": "main = do\n y <- getLine\n if y==\"0\" then putStrLn \"0\" else do\n x <- getLine\n putStrLn $ show $ solve (read y) (map read $ words x)\n \nsolve 0 x = 0\nsolve d x = (delt rest) + solve (d-1) (zipWith (+) (take ((2^d)-2) x) (comb rest))\n where rest = drop ((2^d)-2) x\n\ndelt (x:y:[]) = abs (x-y)\ndelt (x:y:xs) = (abs (x-y)) + (delt xs)\ndelt (x:[]) = 0\n \ncomb (x:y:[]) = [max x y]\ncomb (x:y:xs) = (max x y):(comb xs)\n"}, {"source_code": "import Data.Bits(shiftL)\nimport Control.Monad\n\nmain = do\n n <- readInt `fmap` getLine\n a <- (map readInt . words) `fmap` getLine\n print (solveTaskB ((1 `shiftL` (n + 1)) - 2) a)\n\nsolveTaskB length lights =\n fst $ solveForIndex $ 0\n where\n solveForIndex index = if index * 2 + 2 >= length\n then (0, lights !! index)\n else (abs (lDep - rDep) + lAns + rAns, (lights !! index) + (max lDep rDep))\n where\n lAns = fst lSon\n rAns = fst rSon\n lDep = snd lSon\n rDep = snd rSon\n lSon = solveForIndex (2 * index + 1)\n rSon = solveForIndex (2 * index + 2)\n\nreadInt = read :: String -> Int\n"}], "src_uid": "ae61e1270eeda8c30effc9ed999bf531"} {"source_code": "import Control.Monad\n\ndists :: Int -> String -> Int -> Int -> [Int]\ndists k [] acc _ = [acc]\ndists k (h : t) acc 0\n | h == '0' = dists k t (acc + 1) 0\n | otherwise = acc : dists k t 0 k\ndists k (_ : t) _ b = dists k t 0 (b - 1)\n\nspecMap k [] = []\nspecMap k [x] = if x == 0 then [0] else [1 + ((x - 1) `div` (k + 1))]\nspecMap k (x:t) = (x `div` (k + 1)) : specMap k t\n\nsolve (k, seats) = \n let\n d = dists k seats 0 0\n in\n sum $ specMap k d\n\ngetCase = do\n inp <- getLine\n inp2 <- getLine\n let [n, k] = (map read) $ words inp\n return (k, inp2)\n\nmain = do\n n <- read <$> getLine\n inp <- replicateM n getCase\n mapM_ (putStrLn . show . solve) inp\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map read.words) <$> getLine\n s <- getLine\n print $ solve n k s\n\nsolve :: Int -> Int -> String -> Int\nsolve n k s\n | length grpd == 1 && (fst.head) grpd == '1' = 0\n | length grpd == 1 = 1 + ((n-1) `div` (k+1))\n | otherwise = f2 n k grpd\n where\n grpd =map (\\l -> (head l, length l)) $ group s\n\nf2 :: Int -> Int -> [(Char,Int)] -> Int\nf2 n k (x:xs)\n | fst x == '0' = (snd x `div` (k+1)) + f2 n k xs\n | fst l == '0' = (snd l `div` (k+1)) + f2 n k (init (x:xs))\n | otherwise = r\n where\n l = last (x:xs)\n zs = map snd $ filter ((=='0').fst) (x:xs)\n r = sum $ map (\\y -> max 0 $ (y-k) `quot` (k+1)) zs\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n inputjar <- getLine\n let n = read inputjar :: Int\n solve n\n\nsolve :: Int -> IO ()\nsolve 0 = putStr \"\"\nsolve n = do\n numbers <- getLine\n input <- getLine\n let list = read (\"[\" ++ map (\\x -> if x == ' ' then ',' else x) numbers ++ \"]\") :: [Int]\n solveCase (list !! 1) input\n solve (n - 1)\n\n\nsolveCase :: Int -> [Char] -> IO()\nsolveCase x s = print $ if length (group s) == 1 && head s == '0' then 1 + checkBounds(init s) else foldl check 0 (zip [0..] (init $ group s)) + checkBounds (last $ group s)\n where\n checkBounds group = if length group == 0 then 0 else if (head group == '0') then length group `div` (x + 1) else 0\n check acc group = acc + if fst group == 0 then checkBounds (snd group) else checkInside (snd group)\n checkInside group = if (head group == '0' && length group >= x * 2 + 1) then (length group - x) `div` (x + 1) else 0\n\n-- solveCase :: [Int] -> IO ()\n-- solveCase xs = print $ if odd == even then odd else (-1)\n-- where\n-- odd = foldl (\\acc i -> acc + if (xs !! i) `mod` 2 == 1 then 0 else 1) 0 [1, 3 .. length xs - 1]\n-- even = foldl (\\acc i -> acc + if (xs !! i) `mod` 2 == 0 then 0 else 1) 0 [0, 2 .. length xs - 1]\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n\nimport Data.List (group)\nimport Control.Monad (replicateM_)\n\nsolve n x\n = if all (=='0') x\n then (1+) . solve n $ '1' : tail x\n else sum . map f . map (fmap length) . filter ((=='0') . head . contains) . g False . group $ x\n where\n g :: Bool -> [a] -> [Chairs a]\n g _ [] = error \"???\"\n g _ [x] = [Edge x]\n g False (x:xs) = Edge x : g True xs\n g True (x:xs) = Inside x : g True xs\n f (Edge k) = k `div` (n+1)\n f (Inside k) = f (Edge $ k - n)\n\ndata Chairs a = Edge a | Inside a deriving Functor\ncontains :: Chairs a -> a\ncontains (Edge a) = a\ncontains (Inside a) = a\n\n\nmain = readLn >>= flip replicateM_ go where\n go = do\n [_,n] <- getList\n getLine >>= print . solve n\n\n getList = map read . words <$> getLine\n\n\nf :: Char -> Int\nf = fromIntegral . fromEnum"}], "negative_code": [{"source_code": "import Control.Monad\n\ndists :: Int -> String -> Int -> Int -> [Int]\ndists k [] acc _ = [acc]\ndists k (h : t) acc 0\n | h == '0' = dists k t (acc + 1) 0\n | otherwise = acc : dists k t 0 k\ndists k (_ : t) _ b = dists k t 0 (b - 1)\n\nspecMap k [] = []\nspecMap k [x] = if x == 0 then [0] else [max 1 (x `div` (k + 1))]\nspecMap k (x:t) = (x `div` (k + 1)) : specMap k t\n\nsolve (k, seats) = \n let\n d = dists k seats 0 0\n in\n sum $ specMap k d\n\ngetCase = do\n inp <- getLine\n inp2 <- getLine\n let [n, k] = (map read) $ words inp\n return (k, inp2)\n\nmain = do\n n <- read <$> getLine\n inp <- replicateM n getCase\n mapM_ (putStrLn . show . solve) inp\n"}, {"source_code": "import Control.Monad\n\ndists :: Int -> String -> Int -> Int -> [Int]\ndists k [] acc _ = [acc]\ndists k (h : t) acc 0\n | h == '0' = dists k t (acc + 1) 0\n | otherwise = acc : dists k t 0 k\ndists k (_ : t) _ b = dists k t 0 (b - 1)\n\nsolve (k, seats) = \n let\n d = dists k seats 0 0\n in\n case d of\n [x] -> max 1 (x `div` (k + 1))\n _ -> sum $ map (\\x -> x `div` (k + 1)) d\n\ngetCase = do\n inp <- getLine\n inp2 <- getLine\n let [n, k] = (map read) $ words inp\n return (k, inp2)\n\nmain = do\n n <- read <$> getLine\n inp <- replicateM n getCase\n mapM_ (putStrLn . show . solve) inp\n"}, {"source_code": " import Control.Monad\n \n dists :: Int -> String -> Int -> Int -> [Int]\n dists k [] acc _ = [acc]\n dists k (h : t) acc 0\n | h == '0' = dists k t (acc + 1) 0\n | otherwise = acc : dists k t 0 k\n dists k (_ : t) _ b = dists k t 0 (b - 1)\n \n specMap k [] = []\n specMap k [x] = if x == 0 then [0] else [max 1 (x `div` (k + 1))]\n specMap k (x:t) = (x `div` (k + 1)) : specMap k t\n \n solve (k, seats) = \n let\n d = dists k seats 0 0\n in\n sum $ specMap k d\n \n getCase = do\n inp <- getLine\n inp2 <- getLine\n let [n, k] = (map read) $ words inp\n return (k, inp2)\n \n main = do\n n <- read <$> getLine\n inp <- replicateM n getCase\n mapM_ (putStrLn . show . solve) inp"}], "src_uid": "fd85ebe1dc975a71c72fac7eeb944a4a"} {"source_code": "import Control.Monad\n\ntype Test = (Integer, Integer)\n\ngetTests :: Integer -> IO [Test]\ngetTests count = replicateM (fromIntegral count) getTest\n\ngetTest :: IO Test\ngetTest = do\n line <- getLine\n let list = words line\n return (read (head list), read (head $ tail list))\n\ngetAnswer :: Test -> Integer\ngetAnswer (n, k) = remainderGroups + k\n where remainderGroups = (k - 1) `div` (n - 1)\n\nprintResult :: Integer -> IO ()\nprintResult result = print result\n\nmain :: IO ()\nmain = do\n count <- getLine\n tests <- getTests $ read count\n let results = map getAnswer tests\n mapM_ printResult results", "positive_code": [{"source_code": "main :: IO ()\nmain = do\n getLine\n ans <- map (solve . map read . words) <$> lines <$> getContents\n mapM_ print ans\n\nsolve :: [Int] -> Int\nsolve [x,y] = y + f 0 x y\n\nf x y z = let a = (z `div` y) - (x `div` y)\n in case a of\n 0 -> 0\n _ -> a + f z y (z + a)\n"}, {"source_code": "import Control.Arrow\n\nmain = interact $\n lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\n\nsolve :: [Integer] -> Integer\nsolve [n,k] = ((k-1) `div` (n-1)) * n + ((k-1) `mod` (n-1)) + 1\n\n"}, {"source_code": "import Control.Monad (replicateM_)\n\ngetList :: Read b => IO [b]\ngetList = map read . words <$> getLine\n\nmain = readLn >>= flip replicateM_ ioSolve\n\nioSolve :: IO ()\nioSolve = getList >>= \\[x,y] -> print $ solve x y\n\nsolve :: Int -> Int -> Int\nsolve n k = k + (k-1) `div` (n-1)"}, {"source_code": "\nsolve :: Integer -> Integer -> Integer\nsolve n k\n | r==0 = n*m-1\n | otherwise = n*m+r\n where\n m = k`div`(n-1)\n r = k`mod`(n-1)\n\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:k:_) <- readNums\n print $ solve n k\n testCases (t-1)\n\n\nmain :: IO ()\nmain = do\n (t:_) <- readNums\n testCases t\n\n\nreadNums :: (Read n) => IO [n]\nreadNums = map read . words <$> getLine"}], "negative_code": [], "src_uid": "7d6f76e24fe9a352beea820ab56f03b6"} {"source_code": "import Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport qualified Data.ByteString.Lazy.Char8 as P\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put . P.tail . snd $ P.break (== '\\n') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [px, py] <- readInts\n s <- readLine\n let\n [px', py'] = map fromIntegral [px, py]\n minX = 0 - P.count 'L' s\n maxX = P.count 'R' s\n minY = 0 - P.count 'D' s\n maxY = P.count 'U' s\n lift . P.putStrLn . P.pack\n $ if minX <= px' && px' <= maxX && minY <= py' && py' <= maxY\n then \"YES\"\n else \"NO\" \n", "positive_code": [{"source_code": "chunksOf :: Int -> [a] -> [[a]]\r\nchunksOf x [] = []\r\nchunksOf x l = take x l : chunksOf x (drop x l)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map (read :: Read a => String -> a) . words\r\n\r\nfmtB :: Bool -> String\r\nfmtB True = \"YES\"\r\nfmtB False = \"NO\"\r\n\r\nsolve :: Int -> Int -> String -> Bool\r\nsolve px py s = count 'U' s >= py &&\r\n count 'D' s >= -py &&\r\n count 'R' s >= px &&\r\n count 'L' s >= -px\r\n where count x = length . filter (==x)\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (fmtB . uncurry3 solve . getInput) . chunksOf 2 . tail . lines)\r\n where getInput [a, b] = let [px, py] = toArr a in (px, py, b)\r\n uncurry3 f (a,b,c) = f a b c\r\n"}, {"source_code": "solve :: Int -> Int -> String -> Bool\r\nsolve px py s = count 'U' s >= py &&\r\n count 'D' s >= -py &&\r\n count 'R' s >= px &&\r\n count 'L' s >= -px\r\n where count x = length . filter (==x)\r\n\r\nmain :: IO ()\r\nmain = interact (unlines . map (fmtB . uncurry3 solve . getInput) . chunksOf2 . tail . lines)\r\n where getInput [a, b] = let [px, py] = toArr a in (px, py, b)\r\n chunksOf2 [] = []\r\n chunksOf2 (a : b : l) = [a,b] : chunksOf2 l\r\n uncurry3 f (a,b,c) = f a b c\r\n toArr = map (read :: String -> Int) . words\r\n fmtB True = \"YES\"\r\n fmtB False = \"NO\"\r\n"}, {"source_code": "import Control.Monad\n\nsolve :: ((Int,Int), String) -> String\nsolve ((x,y), as)\n | and [x_axis, y_axis] = \"YES\"\n | otherwise = \"NO\"\n where\n x_axis = or [and [x<0, (abs x) <= ls], and [x>=0, x <= rs]]\n y_axis = or [and [y<0, (abs y) <= ds], and [y>=0, y <= us]]\n ls = (length . filter (=='L')) as \n us = (length . filter (=='U')) as \n ds = (length . filter (=='D')) as \n rs = (length . filter (=='R')) as \n\n-- (x,y)\n-- u -> y+1, d -> y-1, r -> x+1, l -> x-1\n\nreadTestcase :: IO ((Int, Int), String)\nreadTestcase = do\n line <- getLine\n let [x,y] = [read i :: Int | i <- words line]\n word <- getLine\n return $ ((x,y),word)\n\n\n\nmain = do\n t <- getLine\n let t_int = read t :: Int\n testcases <- replicateM t_int readTestcase\n putStrLn $ unlines $ map solve testcases\n"}, {"source_code": "{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE GADTs #-}\r\n{-# LANGUAGE OverloadedStrings #-}\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE Strict #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad (MonadPlus (mplus), foldM_, forM_,\r\n guard, join, replicateM,\r\n replicateM_)\r\nimport qualified Control.Monad.ST.Strict as ST\r\nimport qualified Control.Monad.State.Strict as S\r\nimport qualified Data.Array as A\r\nimport qualified Data.Array.MArray.Safe as MA\r\nimport qualified Data.Array.ST.Safe as STA\r\nimport qualified Data.Array.Unboxed as UA\r\nimport Data.Bits\r\nimport qualified Data.ByteString.Char8 as B8\r\nimport Data.Char\r\nimport Data.Function (on)\r\nimport Data.Functor ((<&>))\r\nimport Data.IORef (modifyIORef, newIORef, readIORef)\r\nimport Data.Int\r\nimport qualified Data.IntMap as IM\r\nimport Data.List (elemIndices, find, findIndices,\r\n intersect, isPrefixOf, nub, sort,\r\n sortOn)\r\nimport qualified Data.Map as M\r\nimport Data.Maybe (fromJust, fromMaybe, isJust)\r\nimport qualified Data.Set as S\r\nimport Data.Traversable (forM)\r\nimport GHC.IO.Handle (hDuplicateTo)\r\nimport System.IO (IOMode (ReadMode, WriteMode),\r\n openFile, stdin, stdout)\r\nimport Text.Printf (printf)\r\n\r\n-- import Debug.Trace (trace, traceM, traceShowM)\r\n-- debug = flip trace\r\n\r\nreadIntB8 :: B8.ByteString -> Int\r\nreadIntB8 = B8.readInt >>> (fst . fromJust)\r\n\r\nreadIntegerB8 :: B8.ByteString -> Integer\r\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\r\n\r\n\r\nsolve :: (Int, Int) -> String -> Bool\r\nsolve (px, py) steps = xCan && yCan\r\n where\r\n directionCounts :: M.Map Char Int \r\n directionCounts = foldl (\\counts direction -> M.insertWith (+) direction 1 counts) M.empty steps\r\n\r\n xDirection = if px < 0 then 'L' else 'R'\r\n yDirection = if py < 0 then 'D' else 'U'\r\n\r\n xCan = M.findWithDefault 0 xDirection directionCounts >= abs px\r\n yCan = M.findWithDefault 0 yDirection directionCounts >= abs py\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- B8.getLine <&> readIntB8\r\n replicateM_ t $ do\r\n [px, py] <- B8.getLine <&> map readIntB8 . B8.words\r\n steps <- B8.getLine <&> B8.unpack . head . B8.words\r\n let answer = solve (px, py) steps\r\n printf \"%s\\n\" $ if answer then \"YES\" else \"NO\" :: String"}], "negative_code": [], "src_uid": "65a64ea63153fec4d660bad1287169d3"} {"source_code": "main = interact $ show . solve . map read . words\nsolve (n:k:a:as) = go a as 0 where\n go a _ i | i >= min (n-1) k = a\n go a (b:as) i | a > b = go a (as ++ [b]) (i+1)\n | otherwise = go b (as ++ [a]) 1\n", "positive_code": [{"source_code": "import Data.Int\nimport Data.List\nmain = getContents >>= print . exec\nexec = solve . map read . words\nsolve (n:k:xs)\n | k >= n = m :: Int64\n | otherwise = (\\r -> case r of { [] -> m; (x:_):_ -> x }) $ filter ((>= k) . genericLength) $ group $ tail $ scanl (\\w f -> max w f) (head xs) (tail xs)\n where m = maximum xs"}, {"source_code": "module Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, k] <- map readInt . words <$> getLine\n xs <- map readInt . words <$> getLine\n let ans = solve n k xs\n print ans\n \nreadInt :: String -> Integer\nreadInt = read\n\nsolve n k (x:xs) | k > n = n\n | otherwise = fst $ foldl (play k) (x, 0) $ xs ++ xs ++ xs\n\nplay k (w, c) p | w == p || c == k = (w, c)\n | w > p = (w, c+1)\n | w < p = (p, 1)"}], "negative_code": [{"source_code": "import Data.Int\nimport Data.List\nmain = getContents >>= print . exec\nexec = solve . map read . words\nsolve (n:k:xs)\n | k >= n = m :: Int64\n | otherwise = maybe m fst $ find snd $ zipWith3 (\\x ts _ -> (x, all (x>) $ genericTake k ts)) xs (tail $ tails xs) [1..n - k]\n where m = maximum xs"}, {"source_code": "import Data.Int\nimport Data.List\nmain = getContents >>= print . exec\nexec = solve . map read . words\nsolve (n:k:xs)\n | k >= n = m :: Int64\n | otherwise = (\\r -> case r of { [] -> m; (x:_):_ -> x }) $ filter ((>= k) . genericLength) $ group $ scanl (\\w f -> max w f) (head xs) (tail xs)\n where m = maximum xs"}, {"source_code": "module Main (main) where\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n [n, k] <- map readInt . words <$> getLine\n xs <- map readInt . words <$> getLine\n let ans = solve n k xs\n print ans\n \nreadInt :: String -> Int\nreadInt = read\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k (x:xs) | k > n = n\n | otherwise = fst $ foldl (play k) (x, 0) $ xs ++ xs ++ xs\n\nplay :: Int -> (Int, Int) -> Int -> (Int, Int)\nplay k (w, c) p | w == p || c == k = (w, c)\n | w > p = (w, c+1)\n | w < p = (p, 1)\n"}], "src_uid": "8d5fe8eee1cce522e494231bb210950a"} {"source_code": "module Main where\n\nimport Control.Monad\n\ngetYearname n m nstr mstr year = (nstr !! yn) ++ (mstr !! ym)\n where\n yn = (year - 1) `mod` n\n ym = (year - 1) `mod` m\n\nmain =\n (map (read :: String -> Int) . words) <$> getLine >>= \\[n, m] ->\n words <$> getLine >>= \\nstr ->\n words <$> getLine >>= \\mstr ->\n (read :: String -> Int) <$> getLine >>= \\q ->\n replicateM q ((read :: String -> Int) <$> getLine) >>= \\years ->\n let\n yearnames = map (getYearname n m nstr mstr) years\n in mapM_ putStrLn yearnames\n", "positive_code": [{"source_code": "module Main where\n\nmain = do\n [n, m] <- map read <$> words <$> getLine\n fSeq <- words <$> getLine\n sSeq <- words <$> getLine\n qCount <- readLn\n qs <- map read <$> (sequence $ replicate qCount getLine)\n let modIndex xs i m = xs !! ((i - 1) `mod` m)\n let getYearName x = modIndex fSeq x n ++ modIndex sSeq x m\n mapM_ (putStrLn . getYearName) qs\n"}, {"source_code": "wordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n \nrepeatNTimes 0 _ = return ()\nrepeatNTimes n action =\n do\n action\n repeatNTimes (n-1) action\n\nindex :: Int -> Int -> Int\nindex q n = (q - 1) `mod` n\n\nmain = do\n input1 <- getLine\n let n = read (wordsWhen(==' ') input1 !! 0) :: Int\n let m = read (wordsWhen(==' ') input1 !! 1) :: Int\n input2 <- getLine\n let s = wordsWhen(==' ') input2\n input3 <- getLine\n let t = wordsWhen(==' ') input3\n input4 <- getLine\n let q = read input4 :: Integer\n repeatNTimes q (do\n input5 <- getLine\n let y = read input5 :: Int\n putStrLn (concat [(s !! index y n), (t !! index y m)])\n )\n "}, {"source_code": "\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ (map read $ words line) !! 0\n\nreadIntList :: IO [Int]\nreadIntList = do\n line <- getLine\n return $ map read $ words line\n\nreadStrList :: IO [String]\nreadStrList = do\n line <- getLine\n return $ words line\n\nrepReadInt :: Int -> IO [Int]\nrepReadInt 0 = return []\nrepReadInt q = do\n x <- readInt\n xs <- repReadInt (q - 1)\n return (x:xs)\n\nprintStrList :: [String] -> IO()\nprintStrList [] = return ()\nprintStrList (x:xs) = do\n putStrLn x\n printStrList xs\n\nmain = do\n [n, m] <- readIntList\n s <- readStrList\n t <- readStrList\n [q] <- readIntList\n query <- repReadInt q\n printStrList $ map (\\x -> (s !! (mod x n)) ++ (t !! (mod x m))) \n $ map (\\x -> x - 1) query\n "}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nprocess a b c d = do\n\t\t\te<- read <$> getLine ::IO Int\n\t\t\treplicateM_ e process1\n\twhere process1 = do\n\t\t\t\tf<-read <$> getLine ::IO Int\n\t\t\t\tputStr $ c!!(mod (f-1) a)\n\t\t\t\tputStrLn $ d!!(mod (f-1) b)\n\n\nmain= do\n\t\t[a,b]<- map read <$>words <$> getLine ::IO [Int]\n\t\tc<- words <$> getLine\n\t\td<- words <$> getLine\n\t\tprocess a b c d\n\t\t\n\n"}, {"source_code": "--ghc 7.10\n\nyearName :: Int -> Int -> [String] -> [String] -> Int -> String\nyearName n m ss ts year = ss !! (year' `mod` n) ++ ts !! (year' `mod` m)\n where year' = year-1\n\nyearNames :: Int -> Int -> [String] -> [String] -> [Int] -> [String]\nyearNames n m ss ts = map (yearName n m ss ts)\n\nmain = do\n nmStr <- getLine\n let [n,m] = map read . words $ nmStr :: [Int]\n ssStr <- getLine\n let ss = words ssStr\n tsStr <- getLine\n let ts = words tsStr\n qStr <- getLine\n contents <- getContents\n let years = map read . words $ contents\n sequence . map putStrLn . yearNames n m ss ts $ years"}], "negative_code": [{"source_code": "wordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n \nrepeatNTimes 0 _ = return ()\nrepeatNTimes n action =\n do\n action\n repeatNTimes (n-1) action\n\nindex :: Int -> Int -> Int\nindex q n = (q - 1) `mod` n\n\nmain = do\n input1 <- getLine\n let n = read (wordsWhen(==' ') input1 !! 0) :: Int\n let m = read (wordsWhen(==' ') input1 !! 1) :: Int\n input2 <- getLine\n let s = wordsWhen(==' ') input2\n input3 <- getLine\n let t = wordsWhen(==' ') input3\n input4 <- getLine\n let q = read input4 :: Integer\n repeatNTimes q (do\n input5 <- getLine\n let y = read input5 :: Int\n print (concat [(s !! index y n), (t !! index y m)])\n )\n "}, {"source_code": "module Main where\n\nmain = do\n [n, m] <- map read <$> words <$> getLine\n fSeq <- words <$> getLine\n sSeq <- words <$> getLine\n qCount <- readLn\n qs <- map read <$> (sequence $ replicate qCount getLine)\n let modIndex xs i m = xs !! (i `mod` m)\n let getYearName x = modIndex fSeq x n ++ modIndex sSeq x m\n mapM_ (print . getYearName) qs\n"}, {"source_code": "module Main where\n\nmain = do\n [n, m] <- map read <$> words <$> getLine\n fSeq <- words <$> getLine\n sSeq <- words <$> getLine\n qCount <- readLn\n qs <- map read <$> (sequence $ replicate qCount getLine)\n let modIndex xs i m = xs !! ((i - 1) `mod` m)\n let getYearName x = modIndex fSeq x n ++ modIndex sSeq x m\n mapM_ (print . getYearName) qs\n"}], "src_uid": "efa201456f8703fcdc29230248d91c54"} {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nmain :: IO ()\nmain = do\n\t_ <- getLine\n\taRR <- getLine\n\tlet\n\t\tarr = reverse. map (\\x -> read x :: Int). words $ aRR\n\t\tlen = length arr\n\t\tsolve :: Int -> [Int] -> Int\n\t\tsolve _ [] = 0\n\t\tsolve mn (x:xs)\n\t\t | x > mn = length xs + 1\n\t\t | otherwise = solve (min mn x) xs\n\tprint $ solve (head arr) arr\n", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nsolve :: Int -> [Int] -> Int\nsolve _ [] = 0\nsolve mn (x:xs)\n | x > mn = length xs + 1\n | otherwise = solve (min mn x) xs\n\nmain :: IO ()\nmain = getContents >>= print. (\\arr -> solve (head arr) arr). reverse. map read. tail. words\n"}, {"source_code": "main :: IO ()\nmain = do \n coStr <- getLine\n let n = read coStr\n coStr2 <- getLine\n let a = map read $ words coStr2\n putStrLn $ show $ n - (old a 0)\n \n--solve\nold :: [Int] -> Int -> Int\nold [] p = p\nold [x] p = p+1\nold (x:y:ys) p = if x < y then old (y:ys) (p+1) else old (y:ys) 0\n\nold1 [] p = p\nold1 [a] p = a:p\nold1 (x:y:ys) p = if x < y then old1 (y:ys) (x:p) else old1 (y:ys) []\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\tn <- readLn\n\tas <- reverse . map read . words <$> getLine\n\tprint $ n - solve as n\n\nsolve [] _ = 0\nsolve (a:as) prev\n\t| prev < a = 0\n\t| otherwise = 1 + solve as a\n"}, {"source_code": "-- Longest Decreasing Prefix\nldp :: [Int] -> Int\nldp (a:(b:c))\n | a > b = 1 + ldp (b:c)\n | otherwise = 1\nldp x = length x\n\nmain :: IO()\nmain = do\n str1 <- getLine\n str2 <- getLine\n let n = read str1 :: Int\n let a = map read (words str2) :: [Int]\n (putStrLn . show) (n - ldp (reverse a))\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport qualified Data.List as L\nimport qualified Data.Set as S\nimport Data.Maybe\nimport Control.Monad\n\n\nreadInt :: B.ByteString -> Int\nreadInt = fromMaybe 0 . fmap fst . B.readInt\n\nmain :: IO ()\nmain = do\n n <- B.getLine >>= return .readInt\n l <- (B.getLine >>= return .map readInt . B.words)\n print $ solve n l\n\nsolve :: Int ->[Int] -> Int\nsolve n = (n-) . length . L.takeWhile judge . L.drop 1 . L.scanl update (0,S.empty) . L.reverse\n where\n update (0,_) x = (x,S.empty)\n update (y,s) x = (x,S.insert y s)\n judge (x,s) |S.null s = True\n |otherwise = x < S.findMin s \n\n\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve xs = last (0 : (solve' xs 1))\n where\n solve' [x] _ = []\n solve' (x:xs) n\n | x < head xs = solve' xs (n + 1)\n | otherwise = n : solve' xs (n + 1) \n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve\n"}, {"source_code": "main = do\n getLine\n a <- map read `fmap` words `fmap` getLine :: IO [Int]\n let a' = reverse a\n print $ length a - 1 - (length $ takeWhile (uncurry (>)) $ a' `zip` tail a')\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\tgetLine\n\tas <- map read . words <$> getLine\n\tprint $ solve as\n\nsolve :: [Int] -> Int\nsolve (1:as) = 0\nsolve (a:as) = 1 + solve as\n"}, {"source_code": "mins :: Ord a => [a] -> [a]\nmins [x] = [x]\nmins (x:xs) = let (y:ys) = mins xs in (min x y):y:ys\n\nmain = do\n getLine\n a <- map read `fmap` words `fmap` getLine :: IO [Int]\n print $ sum $ map (\\(a, b) -> if a > b then 1 else 0) $\n zip a $ mins a\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Data.Char\n\nsolve :: Int -> [Int] -> Int\nsolve _ [] = 0\nsolve mn (x:xs)\n | x > mn = length xs + 1\n | otherwise = solve (min mn x) xs\n\nmain :: IO ()\nmain = getContents >>= print. (\\arr -> solve (head arr) arr). map read. tail. words\n"}, {"source_code": "main :: IO ()\nmain = do \n coStr <- getLine\n let n = read coStr\n coStr2 <- getLine\n let a = map read $ words coStr2\n putStrLn $ show $ n - (old a)\n \n--solve\nold :: [Int] -> Int\nold [] = 0\nold [x] = 1\nold (x:y:xs) = if x < y then 1 + (old (y:xs)) else old (y:xs)"}], "src_uid": "310a0596c0a459f496b8d6b57676d25e"} {"source_code": "import Data.Char\n\nminMoves :: [Int] -> [Int] -> Int\nminMoves xs ys = sum $ zipWith unitMinMoves xs ys\n where\n unitMinMoves x y = if i < j then i else j\n where\n i = abs $ x - y\n j = 10 - i\n\nmain :: IO ()\nmain = do\n n <- fmap (read :: String -> Int) getLine\n origin <- fmap (map digitToInt) getLine\n answer <- fmap (map digitToInt) getLine\n print $ minMoves origin answer\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Control.Monad\nimport Control.Monad.ST.Safe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = solve.tail =<< forM [1..3] (\\i -> getLine)\nsolve [xs,ys] = print $ sum $ zipWith (\\ a b -> let c = abs $ digitToInt a - digitToInt b in minimum [c,10-c]) xs ys"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmoves :: Char -> Char -> Int\nmoves a b = min d (10 - d)\n where d = abs $ digitToInt a - digitToInt b\n\nsolve :: String -> String -> Int\nsolve s t = sum $ zipWith moves s t\n\nmain :: IO ()\nmain = do\n _ <- getLine\n s <- getLine\n t <- getLine\n print $ solve s t\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Char\n\n\n\nprocess q1 q2 = sum $ zipWith (\\z1 z2 -> min (abs (z1 - z2)) (10-(abs (z1-z2))) ) sq1 sq2\n where sq1 =map digitToInt q1\n sq2 = map digitToInt q2\n\nmain=do\n n<- read <$> getLine::IO Integer\n [q1,q2]<- lines <$> getContents\n print $ process q1 q2\n"}, {"source_code": "import Control.Applicative\n\ntoNumbers = map toInt\n\ntoInt :: Char -> Int\ntoInt x = read [x]\n\ndistance (a, b) =\n if a <= b\n then min (9+a-b+1) (b-a)\n else distance (b, a)\n\ntotalmoves xs ys = sum $ map distance (zip xs ys)\n\nmain = do\n n <- getLine\n a <- toNumbers <$> getLine\n b <- toNumbers <$> getLine\n let result = totalmoves a b\n print result\n"}, {"source_code": "import Data.Char\n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n\n let\n f a b = min (abs (a'-b')) (10 - abs (a' - b'))\n where\n a' = ord a\n b' = ord b\n\n print $ sum $ zipWith f s t\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport Data.Char (digitToInt)\n\nmain :: IO ()\nmain = getLine >> solve <$> (map digitToInt <$> getLine) <*> (map digitToInt <$> getLine) >>= print\n\nsolve :: [Int] -> [Int] -> Int\nsolve xs ys = sum $ zipWith (\\x y -> 5 - abs (abs (x - y) - 5)) xs ys\n"}, {"source_code": "import Control.Monad\nmain = do\n getLine\n print.sum =<< liftM2 (zipWith diff) getLine getLine\ndiff a b = abs ( (fromEnum a - fromEnum b + 5) `mod` 10 - 5 )\n"}, {"source_code": "import Control.Monad\nimport System.IO\n\nonline = True\nfile = \"in.txt\"\n\nmain = do\n handle <- if online then return stdin else openFile file ReadMode \n let gl = hGetLine handle\n gl\n a <- gl\n b <- gl\n putStrLn $ show $ solve a b\n\nsolve :: [Char] -> [Char] -> Int\nsolve a b = sum $ zipWith delta a b\n\ndelta :: Char -> Char -> Int\ndelta x y\n | a > b = d b a\n | otherwise = d a b\n where\n a = read [x]\n b = read [y] \n\nd a b = min (b-a) (a+10-b)\n\ngetLines :: IO String -> Int -> IO [String]\ngetIntList :: IO String -> IO [Int]\ngetList :: IO String -> IO [String]\ntoIntTuple :: String -> (Int, Int)\n\ngetIntList gl = gl >>= return.(map read).words\ngetList gl = gl >>= return.words\ngetLines gl n = replicateM n gl\ntoTuple x = (words x !! 0, words x !! 1)\ntoIntTuple x = (read $ words x !! 0, read $ words x !! 1)"}, {"source_code": "import Data.Char\n\nminMoves :: [Int] -> [Int] -> Int\nminMoves xs ys = sum $ zipWith unitMinMoves xs ys\n where\n unitMinMoves x y = if i < j then i else j\n where\n i = abs $ x - y\n j = 10 - i\n\nmain :: IO ()\nmain = do\n _ <- fmap (read :: String -> Int) getLine\n origin <- fmap (map digitToInt) getLine\n answer <- fmap (map digitToInt) getLine\n print $ minMoves origin answer\n"}, {"source_code": "import Data.Char\n\nmain :: IO ()\n\nmain = do\n _ <- getLine\n s1 <- getLine\n s2 <- getLine\n putStrLn $ show $ sum $ zipWith (\\x y -> \n let \n c1 = ord(x) - ord('0')\n c2 = ord(y) - ord('0')\n m1 = min c1 c2\n m2 = max c1 c2\n in min (m2 - m1) (m1 + 10 - m2)) s1 s2"}, {"source_code": "module Main where\n\nalphNumber :: Char -> Int\nalphNumber x = (fromEnum x - fromEnum '0')\n\nmain = do\n n <- getLine\n strF <- getLine\n strS <- getLine\n print $ sum\n $ map (\\(x, y) -> min\n (mod ((alphNumber y) - (alphNumber x)) 10)\n (mod ((alphNumber x) - (alphNumber y)) 10) )\n $ zip strF strS\n return ()\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\n \nprocess (x,y) = min (mod (xx-yy) 10) (mod (yy-xx) 10)\n\twhere \txx = ord x\n\t\tyy = ord y\n \nmain= do\n\tgetLine\n\t[a,b]<-sequence [getLine,getLine]\n\tprint $ sum $ map process $ zip a b"}, {"source_code": "import Data.Char\n\ndistance :: [Int] -> [Int] -> Int\ndistance xs ys = sum $ zipWith d xs ys\n\nd :: Int -> Int -> Int\nd a b = min ((b - a) `mod` 10) ((a - b) `mod` 10)\n\nsolve :: String -> String\nsolve s = show $ distance xs ys\n where _:xs:ys:_ = fmap (fmap digitToInt) . lines $ s\n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "import Data.Char\n\nsolve :: String -> String -> Int\nsolve [] [] = 0\nsolve (x:xs) (y:ys) = m + solve xs ys where\n a = min (digitToInt x) (digitToInt y)\n b = max (digitToInt x) (digitToInt y)\n m = min (b - a) (10 + a - b)\n\nmain :: IO ()\nmain = do\n input <- getContents\n let [xs, ys] = tail $ lines input\n print $ solve xs ys\n"}, {"source_code": "module Main (main)\n where\n\nimport Data.Char (digitToInt)\nimport Control.Monad (replicateM)\n\n\nreadInts :: String -> [Int]\nreadInts = map digitToInt\n\nmain :: IO ()\nmain = print . solve . map readInts =<< (getLine >> replicateM 2 getLine)\n where solve [xs,ys] = sum $ zipWith moves xs ys\n moves a b = min (abs $ a - b) (9 - max a b + min a b + 1)"}, {"source_code": "\nf_ a b =\n let c1 = min a b ; c2 = max a b in min (abs (c1-c2)) (abs (c1 + (10-c2)))\n \nf str str2 = sum $ zipWith (f_) (map (read . (:[])) str) (map (read . (:[])) str2)\n\nmain = do {\n getLine ;\n str1 <- getLine ;\n str2 <- getLine ;\n putStrLn (show $ f str1 str2)\n}"}, {"source_code": "import Data.Char\nimport Data.Foldable as F\nimport Data.Monoid as M\n\nreadInt :: IO Int\nreadInt = do\n i <- getLine\n return $ read i\n\nreadIntString :: IO [Int]\nreadIntString = do\n s <- getLine\n return $ map (digitToInt) s\n\nminMoves :: [Int] -> [Int] -> Int\nminMoves s1 s2 = M.getSum $ F.foldMap (\\(mn, mx) -> M.Sum $ min (mx - mn) (mn - mx + 10)) (map minMax (zip s1 s2) )\n where minMax = \\(x,y) -> (min x y, max x y)\n\nmain :: IO ()\nmain = do\n n <- readInt\n s1 <- readIntString\n s2 <- readIntString\n putStrLn $ show $ minMoves s1 s2\n\n"}, {"source_code": "\nconv ppp lst\n | (null ppp) = lst\n | otherwise = conv (tail ppp) (lst ++ [((read [head ppp])::Int)])\n\nlock aa bb sum\n | (null aa) = sum\n | otherwise = lock (tail aa) (tail bb) (sum + (minimum [(abs (one-two)), ((10-one) + two),\n (one + (10-two))]))\n where one = (head aa)\n two = (head bb)\n\n\nmain = do\n ff <- getLine\n gg <- getLine\n hh <- getLine\n\n let ans = lock (conv gg []) (conv hh []) 0\n\n -- let cc = conv gg []\n -- putStrLn (show cc)\n\n putStrLn (show ans)\n\n \n"}, {"source_code": "import Data.Char (digitToInt)\nmain = do\n w <- getLine\n w0 <- getLine\n let a = [digitToInt n|n <- w0]\n w1 <- getLine\n let b = [digitToInt n|n <- w1]\n print $ sum $ map f (zip a b)\n where f x = min t (10-t) where t = abs((snd x) - (fst x))\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Data.Char\n\n\n\nprocess q1 q2 = sum $ zipWith (\\z1 z2 -> min (abs (z1 - z2)) (abs (10-z1+z2))) sq1 sq2\n where sq1 =map digitToInt q1\n sq2 = map digitToInt q2\n\nmain=do\n n<- read <$> getLine::IO Integer\n [q1,q2]<- lines <$> getContents\n print $ process q1 q2\n"}], "src_uid": "5adb1cf0529c3d6c93c107cf72fa5e0b"} {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport Data.Ix\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nrep :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\n{-# INLINE rep #-}\n\nmain :: IO ()\nmain = do\n [n,t] <- map read.words <$> getLine\n xys <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show $ solve n xys\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xys = go $ map abs xys\n where\n !res = simulate n\n go (x:y:rest)\n | x UArray (Int,Int) Int\nsimulate n = runSTUArray $ do\n a <- newArray ((0,0),(limx-1,limy-1)) 0 :: ST s (STUArray s (Int,Int) Int)\n unsafeWrite a 0 n\n replicateM_ 25623 $ do\n rep limx $ \\x-> do\n rep limy $ \\y-> do\n axy <- unsafeRead a $ x*limy+y\n when (axy>=4) $ do\n unsafeModify a (x*limy+y) (subtract 4)\n forM_ [(x-1,y),(x,y-1),(x+1,y),(x,y+1)] $ \\ (nx,ny)-> do\n when (0<=nx && nx IO (IOUArray Int Int)\nsim arr = do\n notChanged <- foldM f True [0..4900]\n if notChanged then return arr else sim arr\n where\n f notChanged xy = do\n n <- unsafeRead arr xy\n if n < 4 then do\n return notChanged\n else do\n let (q, r) = n `quotRem` 4\n let (x, y) = xy `quotRem` b\n sequence_ [unsafeWrite arr i . (+ d) =<< unsafeRead arr i | (i, d) <-\n (if x == 0 then [] else if x == 1 then [(xy - b, 2 * q)] else [(xy - b, q)]) ++\n (if y == x then [] else if y == x + 1 then if x == 0 then [(0, 4 * q), (b + 1, 2 * q)] else [(xy - 1, 2 * q), (xy + b, 2 * q)] else [(xy - 1, q), (xy + b, q)]) ++\n [(xy + 1, q)]]\n unsafeWrite arr xy r\n return False\n\nsolve :: IOUArray Int Int -> [Int] -> IO Int\nsolve m xy\n | y >= b = return 0\n | otherwise = unsafeRead m (x * b + y)\n where\n [x, y] = sort $ map abs xy\n\nb :: Int\nb = 70\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.Base\nimport Data.Array.IO\nimport qualified Data.List as L\n\nmain :: IO ()\nmain = do\n [n, t] <- map read . words <$> getLine\n m <- newArray (0, 4900) 0\n unsafeWrite m 0 n\n sim m\n mapM_ ((print =<<) . solve m . map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents\n\nsim :: IOUArray Int Int -> IO (IOUArray Int Int)\nsim arr = do\n notChanged <- foldM f True [0..4900]\n if notChanged then return arr else sim arr\n where\n f notChanged xy = do\n n <- unsafeRead arr xy\n if n < 4 then do\n return notChanged\n else do\n let (q, r) = n `quotRem` 4\n let (x, y) = xy `quotRem` b\n sequence_ [unsafeWrite arr i . (+ d) =<< unsafeRead arr i | (i, d) <-\n (if x == 0 then [] else if x == 1 then [(xy - b, 2 * q)] else [(xy - b, q)]) ++\n (if y == x then [] else if y == x + 1 then if x == 0 then [(0, 4 * q), (b + 1, 2 * q)] else [(xy - 1, 2 * q), (xy + b, 2 * q)] else [(xy - 1, q), (xy + b, q)]) ++\n [(xy + 1, q)]]\n unsafeWrite arr xy r\n return False\n\nsolve :: IOUArray Int Int -> [Int] -> IO Int\nsolve m xy\n | y >= b = return 0\n | otherwise = unsafeRead m (x * b + y)\n where\n [x, y] = L.sort $ map abs xy\n\nb :: Int\nb = 70\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.IntMap.Strict as M\n\nmain :: IO ()\nmain = do\n [n, t] <- map read . words <$> getLine\n let m = sim $ M.singleton 0 (M.singleton 0 n)\n mapM_ (print . solve m . map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents\n\nsim :: M.IntMap (M.IntMap Int) -> M.IntMap (M.IntMap Int)\nsim base\n | all (< 4) $ concatMap (M.elems) $ M.elems base = base\n | otherwise = sim $ M.foldrWithKey' f M.empty base\n where\n f x m base = M.foldrWithKey' (g x) base m\n g :: Int -> Int -> Int -> M.IntMap (M.IntMap Int) -> M.IntMap (M.IntMap Int)\n g x y n base = M.unionsWith M.union $ base : \n [M.singleton xx $ M.singleton yy (n `div` 4) | n >= 4, [xx, yy] <- [[x-1, y], [x, y-1], [x, y+1], [x+1, y]]] ++\n [M.singleton x $ M.singleton y (n `mod` 4) | n `mod` 4 > 0]\n\nsolve :: M.IntMap (M.IntMap Int) -> [Int] -> Int\nsolve m [x, y]\n | x `M.member` m && y `M.member` (m M.! x) = m M.! x M.! y\n | otherwise = 0\n"}], "src_uid": "e7a07efba27f2b1f9ec7c4a8fb997b00"} {"source_code": "wordsWhen :: (Char -> Bool) -> String -> [String]\nwordsWhen p s = case dropWhile p s of\n \"\" -> []\n s' -> w : wordsWhen p s''\n where (w, s'') = break p s'\n \nrepeatNTimes 0 _ = return ()\nrepeatNTimes n action =\n do\n action\n repeatNTimes (n-1) action\n \nindex :: Int -> Int -> Int\nindex q n = (q - 1) `mod` n\n \nmain = do\n input1 <- getLine\n let q = read input1 :: Int\n\n --main cycle\n repeatNTimes q (do\n input2 <- getLine\n let input2spl = wordsWhen(==' ') input2\n let a = read (input2spl !! 0) :: Int\n let b = read (input2spl !! 1) :: Int\n let c = read (input2spl !! 2) :: Int\n let r = read (input2spl !! 3) :: Int\n\n let minAB = min a b\n let maxAB = max a b\n let left = c - r\n let right = c + r\n let st = max left minAB\n let ed = min right maxAB\n print (maxAB - minAB - (max 0 (ed - st)))\n )", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n \ngetIntList :: IO [Int]\ngetIntList = fmap (map read) getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b, c, r] <- getIntList\n print $ f a b c r\n\nd :: Int -> Int -> Int\nd x y = abs (x - y)\n\ninf :: Int\ninf = 1000 ^ 3\n\nf :: Int -> Int -> Int -> Int -> Int\nf a b c r =\n let {\n ins x = and [c - r <= x, x <= c + r]\n } in\n minimum [\n d a b,\n if and [ins a, ins b] then 0 else inf,\n if ins a then minimum [d b (c - r), d b (c + r)] else inf,\n if ins b then minimum [d a (c - r), d a (c + r)] else inf,\n d a (c - r) + d b (c + r),\n d a (c + r) + d b (c - r)\n ]"}, {"source_code": "import Control.Monad\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve a' b' c r = s1 + s2\n where\n (a,b) = (min a' b',max a' b')\n c1 = c - r\n c2 = c + r\n s1 = max 0 $ (min b c1) - a\n s2 = max 0 $ b - (max a c2)\n\nroutine :: IO ()\nroutine = do\n [a,b,c,r] <- (map read.words) <$> getLine\n print $ solve a b c r\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}, {"source_code": "module Main where\nimport Control.Monad\n\nisin :: (Ord a) => a -> (a, a) -> Bool\nisin x (l, r) = x >= l && x <= r\n\ncalc :: Int -> Int -> Int -> Int -> Int\ncalc a b c r | a > b = calc b a c r\n | v1 && v2 = 0\n | v1 && not v2 = b - c - r\n | not v1 && v2 = c - r - a\n | not v1 && not v2 && not v3 = b - a\n | otherwise = b - a - 2*r\n where conv = (c - r, c + r)\n v1 = isin a conv\n v2 = isin b conv\n v3 = isin c (a, b)\n\nmain = do\n n <- fmap (\\x -> read x :: Int) getLine\n replicateM_ n $ do\n [a, b, c, r] <- (map read.words) `fmap` getLine\n putStrLn . show $! calc a b c r\n\n"}, {"source_code": "\nhasNoSignal :: Int -> Int -> Int -> Bool\nhasNoSignal c r x = x < (c-r) || x > (c+r-1)\n\nsolve :: Int -> Int -> Int -> Int -> Int\nsolve a b c r\n | b-1 < c-r = b-a\n | c+r-1 < a = b-a\n | c-r <=a && (b-1) <= c+r-1 = 0\n | a <= (c-r) && (c+r) <= b = c-r-a+b-c-r -- ok\n | c-r <= b-1 && b-1 <= c+r-1 = c-r-a\n | c-r <= a && a <= c+r = b-c-r -- ok\n\nparse :: String -> String\nparse input\n | a <= b = show $ solve a b c r\n | otherwise = show $ solve b a c r\n where [a, b, c, r] = map (\\x -> read x :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . map parse . tail . lines)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = fmap words getLine\n \ngetIntList :: IO [Int]\ngetIntList = fmap (map read) getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [a, b, c, r] <- getIntList\n print $ f a b c r\n\nd :: Int -> Int -> Int\nd x y = abs (x - y)\n\ninf :: Int\ninf = 1000 ^ 4\n\nf :: Int -> Int -> Int -> Int -> Int\nf a b c r =\n let {\n ins x = and [c - r <= x, x <= c + r]\n } in\n minimum [\n d a b,\n if and [ins a, ins b] then 0 else inf,\n if ins a then minimum [d b (c - r), d b (c + r)] else inf,\n if ins b then minimum [d a (c - r), d a (c + r)] else inf,\n d a (c - r) + d b (c + r),\n d a (c + r) + d b (c - r)\n ]"}], "src_uid": "783772cb7a54bf65f648d3f8b7648263"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char (ord, chr)\n\nmain = do\n [_,k] <- liftM (map read . words) (getLine) :: IO [Int]\n s <- getLine\n putStrLn . fromMaybe \"-1\" $ solve s k\n\nsolve :: String -> Int -> Maybe String\nsolve s 0 = Just s\nsolve [] k = Nothing\nsolve (x:xs) k\n | mx >= k = Just ((withDist k x):xs)\n | otherwise = case rest of\n Just r -> Just (mc:r)\n Nothing -> Nothing\n where\n rest = solve xs (k - mx)\n mc = if (ord x > ord 'm') then 'a' else 'z'\n mx = abs (ord mc - ord x)\n\nwithDist k c\n | (ord c <= ord 'm') = chr (ord c + k)\n | otherwise = chr (ord c - k)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O1 #-}\n\nimport Data.Char (ord, chr)\n\nmain = do\n [n, k] <- fmap (map read . words) getLine\n s <- getLine\n\n let\n d c1 c2 = abs $ ord c1 - ord c2\n m = sum $ map (\\c -> max (d 'a' c) (d 'z' c)) s\n\n f [] 0 = []\n f (c:s) m\n | d1 > d2 && m >= d1 = 'a':(f s (m - d1))\n | d2 > d1 && m >= d2 = 'z':(f s (m - d2))\n | m < d1 = (chr (ord c - m)):(f s 0)\n | m < d2 = (chr (ord c + m)):(f s 0)\n where\n d1 = d 'a' c\n d2 = d 'z' c\n\n -- let check s t = sum $ zipWith d s t\n -- print $ check s (f s k)\n\n if k > m\n then print $ -1\n else putStrLn $ f s k\n"}, {"source_code": "\nimport Data.Char\n\nmain = interact $ sol . words\n\nsol [_, k', s]\n | (read k') > totSlot = \"-1\"\n | otherwise = sub (read k') s\n where\n totSlot = sum . map maxDis $ s\n sub 0 str = str\n sub k (x:xs)\n | maxDis x < k = toMaxDis x : (sub (k - maxDis x) xs)\n | otherwise = toDis k x : (sub 0 xs)\n maxDis ch = max (cur-a) (z-cur)\n where\n a = ord 'a'\n z = ord 'z'\n cur = ord ch\n toMaxDis ch\n | dist 'a' ch > dist 'z' ch = 'a'\n | otherwise = 'z'\n where\n dist c1 c2 = abs $ ord c1 - ord c2\n toDis k ch\n | r1 <= z && r1 >= a = chr r1\n | otherwise = chr r2\n where\n a = ord 'a'\n z = ord 'z'\n r1 = ord ch + k\n r2 = ord ch - k\n\n\n\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.Char(ord,chr)\n\nsolve :: String -> Int -> (String,Int)\nsolve \"\" remaining = (\"\", remaining)\nsolve css 0 = (css, 0) -- optimization\nsolve (c:cs) remaining = (c':cs', remaining')\n where (c', diff) = bestDiff c remaining\n (cs', remaining') = solve cs (remaining - diff)\n\nbestDiff :: Char -> Int -> (Char,Int)\nbestDiff char distToCover = (char', abs diff)\n where char' = chr (ord char + diff)\n diff = (min distToCover maxDiff) * (if goToA then (-1) else 1)\n maxDiff = max (dist char 'a') (dist char 'z')\n goToA = (dist char 'a') >= (dist char 'z')\n\ndist :: Char -> Char -> Int\ndist c1 c2 = abs $ (ord c1) - (ord c2)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [_,k] = map read (words line1) :: [Int]\n str <- getLine\n let (str', remaining) = solve str k\n if remaining > 0\n then putStrLn $ show (-1)\n else putStrLn str'\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Char (ord, chr)\n\nmain = do\n [_,k] <- liftM (map read . words) (getLine) :: IO [Int]\n s <- getLine\n putStrLn . fromMaybe \"-1\" $ solve s k\n\nsolve :: String -> Int -> Maybe String\nsolve s 0 = Just \"\"\nsolve [] k = Nothing\nsolve (x:xs) k\n | mx >= k = Just ((withDist k x):xs)\n | otherwise = case rest of\n Just r -> Just (mc:r)\n Nothing -> Nothing\n where\n rest = solve xs (k - mx)\n mc = if (ord x > ord 'm') then 'a' else 'z'\n mx = abs (ord mc - ord x)\n\nwithDist k c\n | (ord c <= ord 'm') = chr (ord c + k)\n | otherwise = chr (ord c - k)\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.Char(ord,chr)\n\nsolve :: String -> Int -> (String,Int)\nsolve \"\" k = (\"\", k)\nsolve (x:xs) k = (x':xs', remaining)\n where (x', diff) = bestDiff x k\n (xs', remaining) = solve xs (k - diff)\n\nbestDiff :: Char -> Int -> (Char,Int)\nbestDiff char dstToCover = (char',diff)\n where char' = chr (ord char + diff)\n diff = (min dstToCover maxDiff) * (if goToA then (-1) else 1)\n maxDiff = max (dist char 'a') (dist char 'z')\n goToA = (dist char 'a') >= (dist char 'z')\n\ndist :: Char -> Char -> Int\ndist c1 c2 = abs $ (ord c1) - (ord c2)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [_,k] = map read (words line1) :: [Int]\n str <- getLine\n let (str',remaining) = solve str k\n if remaining > 0\n then putStrLn $ show (-1)\n else putStrLn str'\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.Char(ord,chr)\n\nsolve :: String -> Integer -> (String,Integer)\nsolve \"\" remaining = (\"\", remaining)\nsolve css 0 = (css, 0) -- optimization\nsolve (c:cs) remaining = (c':cs', remaining')\n where (c', diff) = bestDiff c remaining\n (cs', remaining') = solve cs (remaining - diff)\n\nbestDiff :: Char -> Integer -> (Char,Integer)\nbestDiff char distToCover = (char',diff)\n where char' = chr (ord char + fromInteger diff)\n diff = (min distToCover maxDiff) * (if goToA then (-1) else 1)\n maxDiff = max (dist char 'a') (dist char 'z')\n goToA = (dist char 'a') >= (dist char 'z')\n\ndist :: Char -> Char -> Integer\ndist c1 c2 = fromIntegral $ abs $ (ord c1) - (ord c2)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [_,k] = map read (words line1) :: [Integer]\n str <- getLine\n let (str', remaining) = solve str k\n if remaining > 0\n then putStrLn $ show (-1)\n else putStrLn str'\n"}, {"source_code": "{-\ninstructions go here...\n-}\n\nmodule Main where\nimport Data.Char(ord,chr)\n\nsolve :: String -> Int -> (String,Int)\nsolve \"\" remaining = (\"\", remaining)\nsolve css 0 = (css, 0) -- optimization\nsolve (c:cs) remaining = (c':cs', remaining')\n where (c', diff) = bestDiff c remaining\n (cs', remaining') = solve cs (remaining - diff)\n\nbestDiff :: Char -> Int -> (Char,Int)\nbestDiff char distToCover = (char', abs diff)\n where char' = chr (ord char + diff)\n diff = (min distToCover maxDiff) * (if goToA then (-1) else 1)\n maxDiff = max (dist char 'a') (dist char 'z')\n goToA = (dist char 'a') >= (dist char 'z')\n\ndist :: Char -> Char -> Int\ndist c1 c2 = abs $ (ord c1) - (ord c2)\n\nmain :: IO ()\nmain = do\n line1 <- getLine\n let [_,k] = map read (words line1) :: [Int]\n str <- getLine\n let (str', remaining) = solve str k\n if remaining > 0\n then putStrLn $ show (-1) ++ \" \" ++ str' ++ \" \" ++ show remaining\n else putStrLn str'\n"}], "src_uid": "b5d0870ee99e06e8b99c74aeb8e81e01"} {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nimport Data.Maybe\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve [] = []\nsolve (c1:c2:cs) = s :solve cs\n where\n v = read c1\n a = reverse . map read . words $ c2\n m = minimum a\n p = (9-) . fromJust . findIndex (==m) $ a\n s = \n if v String\nsolve (v : as)\n | k > 0 = show =<< replace (v `mod` n) ([1..k] >> [i])\n | otherwise = \"-1\"\n where\n k = v `div` n\n bs@((n, i) : _) = f $ map last $ groupBy ((==) `on` fst) $ sort $ zip as [1..]\n replace _ [] = []\n replace d (x : xs) = j : replace (n + d - m) xs\n where\n (m, j) = last $ takeWhile ((<= (n + d)) . fst) bs\n\nf :: [(Int, Int)] -> [(Int, Int)]\nf ((n, i) : (m, j) : xs)\n | i < j = (n, i) : f ((m, j) : xs)\n | otherwise = f ((n, i) : xs)\nf xs = xs\n"}, {"source_code": "import Control.Monad (liftM)\nimport Data.Array.Unboxed ((!), elems)\nimport Data.Array.ST\nimport Data.Char (ord, intToDigit)\nimport Data.List (minimumBy)\nimport Prelude hiding (reads)\n\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n where\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + ord c - ord '0'\n\nsolve :: Int -> [Int] -> String\nsolve v as\n | all (== 0) (elems array) = \"-1\"\n | otherwise = concatMap (\\d -> replicate (array ! d) (intToDigit d)) [9,8..1]\n where\n array = runSTUArray $ do\n array <- newArray (1,9) 0\n --let k = maxDigitWithMinimumPaint\n let ak = as !! (k-1)\n writeArray array k (v `div` ak)\n update array (v `mod` ak) 9\n return array\n update array p i\n | i == k = return ()\n | otherwise = do\n let ai = as !! (i-1)\n let ak = as !! (k-1)\n arrayK <- readArray array k\n let updateI = min arrayK (p `div` (ai - ak))\n let updateK = arrayK - updateI\n writeArray array k updateK\n writeArray array i updateI\n update array (p - updateI * (ai - ak)) (i-1)\n k = fst $ minimumBy compareSnd $ reverse $ zip [1..] as\n compareSnd a b = compare (snd a) (snd b)\n \n \n\nmain :: IO ()\nmain = do\n v <- readLn\n as <- reads\n putStrLn $ solve v as"}, {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [Int] -> String\nsolve v as = if digits > 0 then solve' (v-digits*cost) as' filler digits else \"-1\"\n\twhere digits = maximum $ map (v `div`) as\n\t minCost = minimum as\n\t fillerIndex = fromJust . findIndex (== minCost) $ as\n\t filler = 9 - fillerIndex\n\t cost = as!!fillerIndex\n\t as' = map (\\x -> x - cost) as\n\nsolve' :: Int -> [Int] -> Int -> Int -> String\nsolve' _ _ _ 0 = \"\"\nsolve' 0 _ f n = replicate n $ (intToDigit f)\nsolve' v as f n = case best of\n\t\tNothing -> solve' 0 as f n\n\t\tJust i -> (intToDigit $ 9 - i):solve' (v - (as!!i)) as f (n-1)\n\twhere best = findIndex (<= v) as \n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tls' <- B.getLine\n\tlet v = readInt ls\n\t as = map readInt . C.words $ ls'\n\tputStrLn $ solve v (reverse as)\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\n\n\nmain = do\n s <- read <$> getLine\n ps <- map read <$> words <$> getLine\n putStrLn $ solve s ps\n\nsolve :: Int -> [Int] -> String\nsolve s ps = if s < p\n then \"-1\"\n else (concat $ map show l) ++ (replicate (n - length l) $ head $ show (-i) )\n where (i,p) = minimumBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] ps\n n = s `div` p\n s' = s - n*p\n l = f s' $ zip [9,8 .. 1] $ reverse $ map (\\x -> x - p) ps --(sortBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] $ map (\\x -> x - p) ps )\n f 0 _ = []\n f _ [] = []\n f s ((i',p):xs) | p == 0 = f s xs\n | s >= p && i'>(-i) = i' : f (s-p) ((i',p):xs)\n | otherwise = f s xs"}, {"source_code": "module Main where\n\n--import Data.List (foldr1)\nimport Data.Maybe\n\nrush :: Int -> [Int] -> Maybe [(Int,Int)]\nrush v cost = if ndigits == 0 then Nothing else Just $ reverse $ (p,prin) : converted\n where (p,cp) = foldr1 (\\(a,ca) (b,cb) -> if ca < cb then (a,ca) else (b,cb)) (zip [1..9] cost)\n (ndigits,res) = v `divMod` cp\n convertList = map (\\(a,ca) -> (a, ca - cp)) $ filter ((> p) . fst) (zip [1..9] cost)\n converted = snd $ foldr (\\(a,ca) (r,l) -> let (count, r') = r `divMod` ca in (r', (a,count):l)) (res,[]) convertList\n prin = foldr (\\(_,count) c -> c - count) ndigits converted\n\npshow :: Maybe [(Int,Int)] -> String\npshow ml\n | isNothing ml = \"-1\"\n | otherwise = concat $ do\n let l = fromJust ml\n (a, c) <- l\n return $ concat $ replicate c (show a)\n\nmain :: IO ()\nmain = do\n (v:cs) <- fmap ( map read . words) getContents\n putStrLn $ pshow $ rush v cs\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\n\ntoDigit n = chr (48 + n)\n\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) x f = x >>= (return.f); infixl 1 ||>\nref = (!!)\n\nsolve :: Int -> [Int] -> String\nsolve v xs =\n if v < m then \"-1\" else solve' v (v `div` m)\n where\n m = minimum xs\n ls = reverse $ zip xs [1..9]\n\n solve' _ 0 = \"\"\n solve' v k =\n (toDigit i) : (solve' (v-u) (k-1))\n where\n (u, i) = findMax (v - (k-1)*m) ls\n\n findMax _ [] = undefined\n findMax v ((x,i):xs) = if v >= x then (x,i) else findMax v xs\n\nmain = do\n ls <- getContents ||> lines\n n <- head ls |> readIO :: IO Int\n xs <- (ref ls 1) |> words |> map read |> return :: IO [Int]\n putStrLn (solve n xs)\n\n-- vim: set ft=haskell:"}], "negative_code": [{"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [Int] -> String\nsolve v as = if digits > 0 then solve' (v-digits*cost) as' filler digits else \"-1\"\n\twhere digits = maximum $ map (v `div`) as\n\t fillerIndex = fromJust . findIndex (\\x -> v `div` x == digits) $ as\n\t filler = 9 - fillerIndex\n\t cost = as!!fillerIndex\n\t as' = map (\\x -> x - cost) as\n\nsolve' :: Int -> [Int] -> Int -> Int -> String\nsolve' _ _ _ 0 = \"\"\nsolve' 0 _ f n = replicate n $ (intToDigit f)\nsolve' v as f n = case best of\n\t\tNothing -> solve' 0 as f n\n\t\tJust i -> (intToDigit $ 9 - i):solve' (v - (as!!i)) as f (n-1)\n\twhere best = findIndex (<= v) as \n\n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tls' <- B.getLine\n\tlet v = readInt ls\n\t as = map readInt . C.words $ ls'\n\tputStrLn $ solve v (reverse as)\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [Int] -> String\nsolve 0 _ = \"-1\"\nsolve v as = solve' (v-digits*(as!!fillerIndex)) as filler digits\n\twhere digits = maximum $ map (v `div`) as\n\t fillerIndex = fromJust . findIndex (\\x -> v `div` x == digits) $ as\n\t filler = 9 - fillerIndex\n\nsolve' :: Int -> [Int] -> Int -> Int -> String\nsolve' 0 _ f n = replicate n $ (intToDigit f)\nsolve' v as f n = case best of\n\t\tNothing -> solve' 0 as f n\n\t\tJust i -> (intToDigit $ 9 - i):solve' (v - (as!!i)) as f (n-1)\n\twhere best = findIndex (<= v) as \n\n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tls' <- B.getLine\n\tlet v = readInt ls\n\t as = map readInt . C.words $ ls'\n\tputStrLn $ solve v (reverse as)\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n"}, {"source_code": "module Main where\nimport System.IO\nimport Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nsolve :: Int -> [Int] -> String\nsolve 0 _ = \"-1\"\nsolve v as = solve' (v-digits*cost) as' filler digits\n\twhere digits = maximum $ map (v `div`) as\n\t fillerIndex = fromJust . findIndex (\\x -> v `div` x == digits) $ as\n\t filler = 9 - fillerIndex\n\t cost = as!!fillerIndex\n\t as' = map (\\x -> x - cost) as\n\nsolve' :: Int -> [Int] -> Int -> Int -> String\nsolve' _ _ _ 0 = \"\"\nsolve' 0 _ f n = replicate n $ (intToDigit f)\nsolve' v as f n = case best of\n\t\tNothing -> solve' 0 as f n\n\t\tJust i -> (intToDigit $ 9 - i):solve' (v - (as!!i)) as f (n-1)\n\twhere best = findIndex (<= v) as \n\n\nmain :: IO ()\nmain = do\n\tls <- B.getLine\n\tls' <- B.getLine\n\tlet v = readInt ls\n\t as = map readInt . C.words $ ls'\n\tputStrLn $ solve v (reverse as)\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\nimport Data.Maybe\nmain = do\n c <- getContents\n putStr . unlines . solve . lines $ c\n\nsolve::[String]->[String]\nsolve [] = []\nsolve (c1:c2:cs) = r :solve cs\n where\n v = read c1\n a = reverse . map read . words $ c2\n m = minimum a\n p = (9-) . fromJust . findIndex (==m) $ a\n r = \n if v getLine\n ps <- map read <$> words <$> getLine\n putStrLn $ solve s ps\n\nsolve :: Int -> [Int] -> String\nsolve s ps = if s < p\n then \"-1\"\n else (concat $ map show l) ++ (replicate (n - length l) $ head $ show (-i) )\n where (i,p) = minimumBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] ps\n n = s `div` p\n s' = s - n*p\n l = f s' (sortBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] $ map (\\x -> x - p) ps )\n f 0 _ = []\n f _ [] = []\n f s ((i,p):xs) | p == 0 = f s xs\n | s >= p = -i : f (s-p) xs\n | otherwise = []"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\n\n\nmain = do\n s <- read <$> getLine\n ps <- map read <$> words <$> getLine\n putStrLn $ solve s ps\n\nsolve :: Int -> [Int] -> String\nsolve s ps = if s < p\n then \"-1\"\n else (concat $ map show l) ++ (replicate (n - length l) $ head $ show (-i) )\n where (i,p) = minimumBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] ps\n n = s `div` p\n s' = s - n*p\n l = f s' $ zip [9,8 .. 1] $ reverse $ map (\\x -> x - p) ps --(sortBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] $ map (\\x -> x - p) ps )\n f 0 _ = []\n f _ [] = []\n f s ((i,p):xs) | p == 0 = f s xs\n | s >= p = i : f (s-p) xs\n | otherwise = f s xs"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\n\n\nmain = do\n s <- read <$> getLine\n ps <- map read <$> words <$> getLine\n putStrLn $ solve s ps\n\nsolve :: Int -> [Int] -> String\nsolve s ps = if s < p\n then \"-1\"\n else (concat $ map show l) ++ (replicate (n - length l) $ head $ show (-i) )\n where (i,p) = minimumBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] ps\n n = s `div` p\n s' = s - n*p\n l = f s' $ zip [9,8 .. 1] $ reverse $ map (\\x -> x - p) ps --(sortBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] $ map (\\x -> x - p) ps )\n f 0 _ = []\n f _ [] = []\n f s ((i,p):xs) | p == 0 = f s xs\n | s >= p = i : f (s-p) ((i,p):xs)\n | otherwise = f s xs"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\n\n\n\nmain = do\n s <- read <$> getLine\n ps <- map read <$> words <$> getLine\n putStrLn $ solve s ps\n\nsolve :: Int -> [Int] -> String\nsolve s ps = if p > s\n then \"-1\"\n else replicate (s `div` p) $ head $ show (-i) \n where (i,p) = minimumBy (\\(i1,p1) (i2,p2) -> if p1 == p2 then compare i1 i2 else compare p1 p2) $ zip [-1,-2 .. -9] ps"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Applicative\nimport Debug.Trace\ndebug x = trace (show x) x\n(|>) x f = f x; infixl 1 |>\n(||>) x f = x >>= (return.f); infixl 1 ||>\nref = (!!)\n\ntoDigit :: Int -> Char\ntoDigit n = chr (48 + n)\n\ngo v xs =\n if v < m then \"-1\" else ((toDigit $ findMax ((v`mod`m)+m)) : (take ((v`div`m) -1) mis))\n where\n (m, mi) = minRight xs\n findMax v = findMax' v (reverse xs) 9\n findMax' _ [a] _ = 1\n findMax' v (x:xs) i = if (v>=x) then i else (findMax' v xs (i-1))\n minRight ls =\n foldl (\\(x, id) (y, jd) -> if x>=y then (y,jd) else (x,id))\n (1000002, -1) (zip ls [1..])\n mis = (toDigit mi) : mis\n\nmain = do\n ls <- getContents ||> lines\n v <- head ls |> readIO :: IO Int\n xs <- (ref ls 1) |> words |> map read |> return :: IO [Int]\n putStrLn (go v xs)\n\n-- vim: set ft=haskell:\n"}], "src_uid": "ace9fbabc2eda81b4e4adf4f2d5ad402"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (group, sort)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Integer\nsolve = foldl f 0 . map (toInteger . length) . group . sort . map bits\n where\n f s n = s + div (n * (n - 1)) 2\n bits 0 = 0\n bits m = mod m 2 + bits (div m 2)\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve", "positive_code": [{"source_code": "import Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n n <- getLine >>= return . read\n l <- B.getLine >>= return . map readInt . B.words\n print $ solve n l\n where\n readInt = fst . fromMaybe (0,undefined) . B.readInt\n\nsolve :: Int -> [Int] -> Int64\nsolve n = foldl' (+) 0 . map count . group . sort . map f\n where\n f = ftail 0\n ftail s 0 = s\n ftail s n = ftail (s + mod n 2) (div n 2)\n count l = x * (x-1) `div` 2\n where x = fromIntegral $ length l\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nmain=B.getContents>>=print.sum.map(f.length).group.sort.map(popCount.readInt).tail.B.words\n\nf :: Int -> Integer\nf 1 = 0\nf x = fromIntegral x * (fromIntegral x - 1) `quot` 2"}, {"source_code": "#!/usr/bin/env runghc\nimport Data.List\n\nmain = do\n c <- getContents\n putStrLn . solve . lines $ c\n\nsolve (n:a:cs) = show . cpair (-1) 0 0 . sort . map f . map read $ words a\n where\n f 0 = 0\n f x = f (x `div` 2) + if x `mod` 2 == 0 then 0 else 1\n cpair p n s (x:xs) = if p==x then cpair p (n+1) s xs else cpair x 1 (s+c2 n) xs\n cpair p n s [] = c2 n + s\n c2 n = n*(n-1) `div` 2\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nc :: Integer -> Integer\nc 1 = 0\nc n = n * (n - 1) `div` 2\n\nf :: Integer -> Integer\nf = f' 0\n where\n f' acc 0 = acc\n f' acc x\n | x `mod` 2 == 0\n = f' acc (x `div` 2)\n | otherwise\n = f' (acc + 1) (x `div` 2)\n\n\nsolve :: [Integer] -> Integer\nsolve = sum . map (c.(genericLength :: [Integer] -> Integer)) . group . sort\n\nmain = getLine >> getLine >>= (print . solve . map (f.read) . words)"}], "negative_code": [{"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (group)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Integer\nsolve = foldl f 0 . map (toInteger . length) . group . map bits\n where\n f s n = s + div (n * (n - 1)) 2\n bits 0 = 0\n bits m = mod m 2 + bits (div m 2)\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve"}, {"source_code": "module Main where\n\nimport Data.List\n\nc :: Int -> Integer\nc 1 = 0\nc n = toInteger $ n * (n - 1) `div` 2\n\nf :: Integer -> Integer\nf = f' 0\n where\n f' acc 0 = acc\n f' acc x\n | x `mod` 2 == 0\n = f' acc (x `div` 2)\n | otherwise\n = f' (acc + 1) (x `div` 2)\n\n\nsolve :: [Integer] -> Integer\nsolve = sum . map (c.length) . group . sort\n\nmain = getLine >> getLine >>= (print . solve . map (f.read) . words)"}], "src_uid": "c547e32f114546638973e0f0dd16d1a4"} {"source_code": "import Data.List\n\nf::Int->Int->Int->[String]\nf n a p\n |n==a=[]\n |otherwise=(show (((p+a) `mod` n)+1)):f n (a+1) ((p+a) `mod` n)\n\nmain =do\n e<-getLine\n let n=read e::Int\n putStrLn $ unwords $ f n 1 0", "positive_code": [{"source_code": "main = do getLine >>= putStrLn . unwords . (\\n -> map (show . succ . (`mod` n)) $ scanl1 (+) [1 .. n - 1]) . read\n"}, {"source_code": "\ngame i t n = \n if t == n then (show i)\n else (show i) ++ \" \" ++ (game ((mod (i + t - 1) n) + 1) (t + 1) n)\n\nmain :: IO ()\nmain = do\n n <- getLine >>= return . read\n putStr (game 2 2 n)"}, {"source_code": "-- QH9\n\nnstep n a cp ch | (a == (n-1)) = [ch]\n | otherwise = ch:(nstep n (a+1) (cp+1) newch)\n where chcp = ch + cp\n newch = if (chcp <= n) then chcp else mod chcp n\n\npr [] = []\npr (x:xs) = show x ++ (' ':(pr xs))\n\nmain = do\n\t\tn <- readLn :: IO Int\n\t\tputStrLn $ pr $ nstep n 1 2 2\n"}, {"source_code": "main=interact$unwords.map show.s.read\ns n=[(i*(i+1)`div`2)`mod`n+1|i<-[1..n-1]]\n"}, {"source_code": "main = do\n n <- readLn\n let ans = solve n 2 2\n putStr (unwords (map show ans))\nsolve :: Int -> Int -> Int -> [Int]\nsolve n a b\n | n == b - 1 = []\n | otherwise = a : solve n ((a + b - 1) `mod` n + 1) (b + 1)"}, {"source_code": "import Data.List\n\nf i cs n | i == n = pp $ tail $ reverse $ map (\\x -> if x == 0 then n else x ) cs\nf i all@(c:cs) n = f (i+1) (((c+i)`mod`n):all) n\npp = concat . intersperse \" \" . map show\n\nmain = do\n r <- readLn :: IO Int \n putStrLn $ f 1 [1]r\n"}, {"source_code": "next :: Int -> (Int, Int) -> (Int, Int)\nnext modulator (currentKinder, numStep) = (mod (currentKinder + numStep - 1) modulator + 1, numStep + 1)\n\nsolve :: Int -> [Int]\nsolve n = map fst (take n (iterate (next n) (1,1)))\n\nmyPrint :: [Int] -> String\nmyPrint [] = \"\"\nmyPrint [x] = show x\nmyPrint (x:xs) = (show x ++ \" \") ++ (myPrint xs)\n\nmain = do\n n <- readLn::(IO Int)\n putStrLn (myPrint (tail (solve n)))"}, {"source_code": "import Control.Applicative ((<$>))\n\nmain :: IO ()\nmain = putStrLn <$> unwords <$> map show =<< solve <$> readLn\n\nsolve :: Integer -> [Integer]\nsolve n = [ (i * (i + 1) `div` 2) `mod` n + 1 | i <- [1..n-1] ]\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n putStrLn . unwords . map show . snd $ mapAccumL f (cycle [1..n]) [1..n-1]\nf l n = (l',head l') where l' = drop n l"}, {"source_code": "main = do\n input <- getContents\n let kids = (read $ head $ lines input)::Int\n putStrLn $ foldr (\\x y -> x ++ \" \" ++ y) \"\" (map show $ ballGame kids)\n\nballGame n = ballGame' 1 0 []\n where\n ballGame' kid step acc\n | step == n-1 = acc\n | otherwise = ballGame' val (step+1) (acc ++ [val])\n where\n sum = (kid + step + 1) `mod` n\n val = if sum == 0 then n else sum\n"}, {"source_code": "get n = drop 1 . take n . map (\\x -> fst x + 1) $ iterate next (0, 1)\n where next (a, k) = ((a+k) `mod` n, k + 1)\n\nmain = do\n n <- readLn\n putStrLn . unwords $ map show (get n)\n"}, {"source_code": "main = interact solve\nsolve input = output where\n n = read input :: Int\n output = unwords $ map show $ answer 1 1 n\nanswer x y z = if y==z then [] else w : (answer w (y+1) z) where\n w = mod (x+y-1) z + 1"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tputStrLn $ intercalate \" \" $ map show $ tail $ map (\\z-> (mod (z-1) n)+1) $take n $ scanl (+) 1 [1..]\n"}], "negative_code": [{"source_code": "main = do getLine >>= putStrLn . unwords . (\\n -> map (show . succ . (`mod` n)) $ scanl1 (+) [1 .. n]) . read\n"}, {"source_code": "\ngame i t n = \n if t == n then (show i)\n else (show i) ++ \" \" ++ (game (mod (i + t) n) (t + 1) n)\n\nmain :: IO ()\nmain = do\n n <- getLine >>= return . read\n putStr (game 2 2 n)"}, {"source_code": "-- QH9\n\nnstep n a cp ch | (a == (n-1)) = [ch]\n | otherwise = ch:(nstep n (a+1) (cp+1) newch)\n where chcp = ch + cp\n newch = if (chcp <= n) then chcp else mod chcp n\n\nmain = do\n\t\tn <- readLn :: IO Int\n\t\tprint $ nstep n 1 2 2\n"}, {"source_code": "import Data.List\n\nf i cs n | i == n = pp $ tail $ reverse $ cs\nf i all@(c:cs) n = f (i+1) (((c+i)`mod`n):all) n\npp = concat . intersperse \" \" . map show\n\nmain = do\n r <- readLn :: IO Int \n putStrLn $ f 1 [1]r\n"}, {"source_code": "next :: Int -> (Int, Int) -> (Int, Int)\nnext modulator (currentKinder, numStep) = (mod (currentKinder + numStep) modulator, numStep + 1)\n\nsolve :: Int -> [Int]\nsolve n = map fst (take n (iterate (next n) (1,1)))\n\nmyPrint :: [Int] -> String\nmyPrint [] = \"\"\nmyPrint [x] = show x\nmyPrint (x:xs) = (show x ++ \" \") ++ (myPrint xs)\n\nmain = do\n n <- readLn::(IO Int)\n putStrLn (myPrint (tail (solve n)))"}, {"source_code": "main = do\n input <- getContents\n let kids = (read $ head $ lines input)::Int\n putStrLn $ foldr (\\x y -> x ++ \" \" ++ y) \"\" (map show $ ballGame kids)\n \nballGame :: Int -> [Int]\nballGame 0 = []\nballGame n = ball n n\n\t\n\t\nball :: Int -> Int -> [Int]\nball n m\n\t|n/=1 = ball(n-1) m ++[calc (n-1) m]\n\t|n==1 = []\n\n\t\ncalc :: Int -> Int -> Int\ncalc n m \n\t|n==1 = 2\n\t|otherwise = ((calc (n-1) m )+n)`mod`(m)\n"}, {"source_code": "main = do\n input <- getContents\n let kids = (read $ head $ lines input)::Int\n putStrLn $ foldr (\\x y -> x ++ \" \" ++ y) \"\" (map show $ ballGame kids)\n \njogar::Int->Int->Int->Int->[Int]\njogar 0 _ _ _ = []\njogar iteracao n crianca lancamento = proximo:jogar (iteracao-1) n (proximo) (lancamento+1)\n where proximo = mod (crianca+lancamento+1) n\n\n--faz o que a quest\u00e3o pede.\nballGame::Int->[Int]\nballGame n = jogar (n-1) n 1 0\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tputStrLn $ intercalate \" \" $ map show $ tail $ map (\\z-> mod z n) $take n $ scanl (+) 1 [1..]\n"}], "src_uid": "7170c40405cf7a5e0f2bd15e4c7d189d"} {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n", "positive_code": [{"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n n <- getLine >>= return . read\n s <- getLine >>= return . (take (n-1))\n putStrLn $ solve n s\n\nsolve n s = init $ concatMap (\\x -> show x ++ \" \") $ map (\\(x,y) -> max x y) $\n zip (lefts 1 s [1]) (rights 1 (reverse s) [1])\n where\n lefts _ [] acc = reverse acc\n lefts x (c:s) acc = case c of\n '=' -> lefts x s (x:acc)\n 'L' -> lefts 1 s (1:acc)\n 'R' -> lefts (x+1) s ((x+1):acc)\n \n rights _ [] acc = acc\n rights x (c:s) acc = case c of\n '=' -> rights x s (x:acc)\n 'L' -> rights (x+1) s ((x+1):acc)\n 'R' -> rights 1 s (1:acc)\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n n <- getLine >>= return . read\n s <- getLine >>= return . (take (n-1))\n putStrLn $ solve n s\n\nsolve n s = init $ concatMap (\\x -> show x ++ \" \") $ map (\\(x,y) -> max x y) $\n zip (lefts 1 s [1]) (rights 1 (reverse s) [1])\n where\n lefts _ [] acc = reverse acc\n lefts x (c:s) acc = case c of\n '=' -> lefts x s (x:acc)\n 'L' -> lefts 1 s (1:acc)\n 'R' -> lefts (x+1) s ((x+1):acc)\n \n rights _ [] acc = acc\n rights x (c:s) acc = case c of\n '=' -> rights x s (x:acc)\n 'L' -> rights (x+1) s ((x+1):acc)\n 'R' -> rights 1 s (1:acc)\n"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n"}, {"source_code": "import Data.List\nmain=interact$intercalate \" \".map show.f 1.last.lines\nf a[]=[a]\nf a('L':s)=max a(h+1):h:r where h:r=f 1 s\nf a('=':s)=h:h:r where h:r=f a s\nf a('R':s)=a:f(a+1) s\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n n <- getLine >>= return . read\n s <- getLine >>= return . (take (n-1))\n putStrLn $ solve n s\n\nsolve n s = init $ concatMap (\\x -> show x ++ \" \") $ normalize $ mapper 0 s [0] where\n mapper _ [] acc = reverse acc\n mapper x (c:s) acc = case c of\n '=' -> mapper x s (x:acc)\n 'L' -> mapper (x-1) s ((x-1):acc)\n 'R' -> mapper (x+1) s ((x+1):acc)\n normalize xs = map (subtract mn) xs where\n mn = minimum xs - 1\n\n"}], "src_uid": "8c2a6a29dc238b55d0bc99d7e203f1bf"} {"source_code": "import Data.Array\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.List\nimport Control.Monad\nimport Control.Monad.ST.Safe\n\ngetInts = fmap (map read . words) getLine\n\nmain = do\n [h, w] <- getInts\n a <- replicateM h getLine\n let\n scan2d :: [[Int]] -> [[Int]]\n scan2d = transpose . f . transpose . f where f = map (scanl1 (+))\n\n line :: String -> [Int]\n line l = map fromEnum $ (False:) $ zipWith (\\a b -> a == '.' && b == '.') l $ tail l\n\n hor = listArray ((1, 1), (h, w)) $ concat $ scan2d $ map line a\n vert = listArray ((1, 1), (h, w)) $ concat $ scan2d $ transpose $ map line $ transpose a\n\n solve [r1, c1, r2, c2] =\n f r2 c2 - f r2 c1 - f (r1-1) c2 + f (r1-1) c1 +\n g r2 c2 - g r2 (c1-1) - g r1 c2 + g r1 (c1-1)\n where\n f 0 _ = 0\n f x y = hor!(x,y)\n\n g _ 0 = 0\n g x y = vert!(x,y)\n\n qs <- (readLn >>= \\n -> replicateM n getInts)\n\n putStrLn $ unlines $ map show $ map solve qs\n", "positive_code": [{"source_code": "-- They say \"years are like dominoes, tumbling one after the other\". But would\n-- a year fit into a grid? I don't think so.\n\n-- Limak is a little polar bear who loves to play. He has recently got\n-- a rectangular grid with h rows and w columns. Each cell is a square, either\n-- empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1\n-- through h from top to bottom. Columns are numbered 1 through w from left to\n-- right.\n\n-- Also, Limak has a single domino. He wants to put it somewhere in a grid.\n-- A domino will occupy exactly two adjacent cells, located either in one row\n-- or in one column. Both adjacent cells must be empty and must be inside a grid.\n\n-- Limak needs more fun and thus he is going to consider some queries. In each\n-- query he chooses some rectangle and wonders, how many way are there to put\n-- a single domino inside of the chosen rectangle?\n\n-- Input\n-- The first line of the input contains two integers h and w (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u2009500)\n-- \u2013 the number of rows and the number of columns, respectively.\n\n-- The next h lines describe a grid. Each line contains a string of the length w.\n-- Each character is either '.' or '#' \u2014 denoting an empty or forbidden cell,\n-- respectively.\n\n-- The next line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000) \u2014 the number\n-- of queries.\n\n-- Each of the next q lines contains four integers r1i, c1i, r2i, c2i\n-- (1\u2009\u2264\u2009r1i\u2009\u2264\u2009r2i\u2009\u2264\u2009h,\u20091\u2009\u2264\u2009c1i\u2009\u2264\u2009c2i\u2009\u2264\u2009w) \u2014 the i-th query. Numbers r1i and c1i\n-- denote the row and the column (respectively) of the upper left cell of the\n-- rectangle. Numbers r2i and c2i denote the row and the column (respectively)\n-- of the bottom right cell of the rectangle.\n\n-- Output\n-- Print q integers, i-th should be equal to the number of ways to put a single\n-- domino inside the i-th rectangle.\n\nmodule Main where\nimport Data.Array ((!))\nimport qualified Data.Array as Array\n\nannotate :: [[a]] -> [((Int,Int),a)]\nannotate lst = [((i1,i2),x) | (i1,xs) <- zip [1..] lst, (i2,x) <- zip [1..] xs]\n\nparseBoard :: [String] -> (Array.Array (Int,Int) Integer, Array.Array (Int,Int) Integer)\nparseBoard rows = (rowScans, colScans)\n where rowScans = Array.array ((1,1),(rCnt,cCnt)) $ (annotate . interScans . intraScans) rows\n colScans = Array.array ((1,1),(cCnt,rCnt)) $ (annotate . interScans . intraScans . transpose) rows\n intraScans = map (\\line -> tail $ scanl score 0 (zip ('#':line) line))\n score aggr (prevCell,curCell)\n | prevCell == '.' && curCell == '.' = aggr + 1\n | otherwise = aggr\n interScans = scanl1 addLists\n addLists l1 l2 = map (\\(x,y) -> x+y) (zip l1 l2)\n rCnt = length rows\n cCnt = length $ head rows\n\nplacements :: (Array.Array (Int,Int) Integer, Array.Array (Int,Int) Integer) -> (Int,Int,Int,Int) -> Integer\nplacements (rowScans, colScans) (r1,c1,r2,c2)\n = rowScans ! (r2,c2) - (get rowScans (r1-1,c2) + rowScans ! (r2,c1) - get rowScans (r1-1,c1))\n + colScans ! (c2,r2) - (colScans ! (c2,r1) + get colScans (c1-1,r2) - get colScans (c1-1,r1))\n where get arr (i,j) = if i >= 1 && j >= 1 then arr ! (i,j) else 0\n\ntranspose([]:_) = []\ntranspose (rows) = map head rows : transpose (map tail rows)\n\nsublist start size lst = (take size) . (drop start) $ lst\n\ntoTuple [a,b,c,d] = (a,b,c,d)\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n line <- getLine\n rest <- getLines (n-1) -- sadly, not tail recursion\n return $ line:rest\n\nmain :: IO ()\nmain = do\n boardSpecStr <- getLine\n let [rCount, cCount] = map read (words boardSpecStr) :: [Int]\n\n boardRowsStr <- getLines rCount\n let boardScans = parseBoard boardRowsStr\n\n qCountStr <- getLine\n let qCount = read qCountStr :: Int\n\n queriesStr <- getLines qCount\n let queries = map (toTuple . (map read) . words) queriesStr :: [(Int,Int,Int,Int)]\n\n let answers = map (placements boardScans) queries\n\n mapM_ (putStrLn . show) answers\n"}], "negative_code": [{"source_code": "-- They say \"years are like dominoes, tumbling one after the other\". But would\n-- a year fit into a grid? I don't think so.\n\n-- Limak is a little polar bear who loves to play. He has recently got\n-- a rectangular grid with h rows and w columns. Each cell is a square, either\n-- empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1\n-- through h from top to bottom. Columns are numbered 1 through w from left to\n-- right.\n\n-- Also, Limak has a single domino. He wants to put it somewhere in a grid.\n-- A domino will occupy exactly two adjacent cells, located either in one row\n-- or in one column. Both adjacent cells must be empty and must be inside a grid.\n\n-- Limak needs more fun and thus he is going to consider some queries. In each\n-- query he chooses some rectangle and wonders, how many way are there to put\n-- a single domino inside of the chosen rectangle?\n\n-- Input\n-- The first line of the input contains two integers h and w (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u2009500)\n-- \u2013 the number of rows and the number of columns, respectively.\n\n-- The next h lines describe a grid. Each line contains a string of the length w.\n-- Each character is either '.' or '#' \u2014 denoting an empty or forbidden cell,\n-- respectively.\n\n-- The next line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000) \u2014 the number\n-- of queries.\n\n-- Each of the next q lines contains four integers r1i, c1i, r2i, c2i\n-- (1\u2009\u2264\u2009r1i\u2009\u2264\u2009r2i\u2009\u2264\u2009h,\u20091\u2009\u2264\u2009c1i\u2009\u2264\u2009c2i\u2009\u2264\u2009w) \u2014 the i-th query. Numbers r1i and c1i\n-- denote the row and the column (respectively) of the upper left cell of the\n-- rectangle. Numbers r2i and c2i denote the row and the column (respectively)\n-- of the bottom right cell of the rectangle.\n\n-- Output\n-- Print q integers, i-th should be equal to the number of ways to put a single\n-- domino inside the i-th rectangle.\n\nmodule Main where\n\nparseBoard :: [String] -> [[Bool]]\nparseBoard rowsStr = map parseRow rowsStr\n where parseRow rowStr = map parseCol rowStr\n parseCol colChr = case colChr of\n '.' -> True\n '#' -> False\n\nplacements :: [[Bool]] -> ([[Integer]], [[Integer]])\nplacements board = (rowPlacements, colPlacements)\n where rowPlacements = placements' board\n colPlacements = placements' (transpose board)\n placements' boardLines = map (map cellNo) goodAdjacentCells\n where allAdjacentCells = map (\\line -> zip3 [1..] line (tail line)) boardLines\n goodAdjacentCells = map (filter cellIsOccupiable) allAdjacentCells\n goodStartingCells = map (map cellNo) goodAdjacentCells\n cellIsOccupiable (_,a,b) = a && b\n cellNo (n,_,_) = n\n\nanswerQuery :: ([[Integer]], [[Integer]]) -> [Integer] -> Integer\nanswerQuery (rPlacements, cPlacements) [r1,c1,r2,c2]\n = toInteger $ foldl (+) 0 (map length relevantRPlacements) + foldl (+) 0 (map length relevantCPlacements)\n where relevantRPlacements = map (takeWhile (\\c -> c < c2) . dropWhile (\\c -> c < c1)) $ sublist (r1-1) (r2-r1+1) rPlacements\n relevantCPlacements = map (takeWhile (\\r -> r < r2) . dropWhile (\\r -> r < r1)) $ sublist (c1-1) (c2-c1+1) cPlacements\n\nsublist start size lst = (take $ fromInteger size) . (drop $ fromInteger start) $ lst\n\ntranspose ([]:_) = []\ntranspose x = (map head x) : transpose (map tail x)\n\nmain :: IO ()\nmain = do\n rawInput <- getContents\n let rawLines = lines rawInput\n\n let boardSpecStr = head $ sublist 0 1 rawLines\n let [rCount, cCount] = map read (words boardSpecStr) :: [Integer]\n\n let boardRowsStr = sublist 1 rCount rawLines\n let board = parseBoard boardRowsStr\n\n let legalPlacements = placements board\n\n let qCountStr = head $ sublist (1 + rCount) 1 rawLines\n let qCount = read qCountStr :: Integer\n\n let queriesStr = sublist (1 + rCount + 1) qCount rawLines\n let queries = map ((map read) . words) queriesStr :: [[Integer]]\n\n let answers = map (answerQuery legalPlacements) queries\n\n putStrLn $ show legalPlacements\n\n mapM_ (putStrLn . show) answers\n"}, {"source_code": "-- They say \"years are like dominoes, tumbling one after the other\". But would\n-- a year fit into a grid? I don't think so.\n\n-- Limak is a little polar bear who loves to play. He has recently got\n-- a rectangular grid with h rows and w columns. Each cell is a square, either\n-- empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1\n-- through h from top to bottom. Columns are numbered 1 through w from left to\n-- right.\n\n-- Also, Limak has a single domino. He wants to put it somewhere in a grid.\n-- A domino will occupy exactly two adjacent cells, located either in one row\n-- or in one column. Both adjacent cells must be empty and must be inside a grid.\n\n-- Limak needs more fun and thus he is going to consider some queries. In each\n-- query he chooses some rectangle and wonders, how many way are there to put\n-- a single domino inside of the chosen rectangle?\n\n-- Input\n-- The first line of the input contains two integers h and w (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u2009500)\n-- \u2013 the number of rows and the number of columns, respectively.\n\n-- The next h lines describe a grid. Each line contains a string of the length w.\n-- Each character is either '.' or '#' \u2014 denoting an empty or forbidden cell,\n-- respectively.\n\n-- The next line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000) \u2014 the number\n-- of queries.\n\n-- Each of the next q lines contains four integers r1i, c1i, r2i, c2i\n-- (1\u2009\u2264\u2009r1i\u2009\u2264\u2009r2i\u2009\u2264\u2009h,\u20091\u2009\u2264\u2009c1i\u2009\u2264\u2009c2i\u2009\u2264\u2009w) \u2014 the i-th query. Numbers r1i and c1i\n-- denote the row and the column (respectively) of the upper left cell of the\n-- rectangle. Numbers r2i and c2i denote the row and the column (respectively)\n-- of the bottom right cell of the rectangle.\n\n-- Output\n-- Print q integers, i-th should be equal to the number of ways to put a single\n-- domino inside the i-th rectangle.\n\nmodule Main where\nimport Data.Array ((!))\nimport qualified Data.Array as Array\n\nparseBoard :: [String] -> Array.Array (Int,Int) Bool\nparseBoard rows = Array.array bounds $ concatMap parseRow (zip [1..] rows)\n where parseRow :: (Int, String) -> [((Int,Int),Bool)]\n parseRow (rIdx,row) = map parseCol $ zip3 (repeat rIdx) [1..] row\n parseCol :: (Int,Int,Char) -> ((Int,Int),Bool)\n parseCol (rIdx,cIdx,col) = case col of\n '.' -> ((rIdx,cIdx),True)\n '#' -> ((rIdx,cIdx),False)\n bounds = ((1,1), (rCnt,cCnt))\n rCnt = length rows\n cCnt = length $ head rows\n\nplacements :: Array.Array (Int,Int) Bool -> Array.Array (Int,Int) Int\nplacements board = Array.listArray bounds [combPlacements rc | rc <- Array.range bounds]\n where combPlacements (r,c) = if placeable (r,c)\n then (if placeable (r+1,c) then 1 else 0)\n + (if placeable (r,c+1) then 1 else 0)\n else 0\n placeable (r,c) = Array.inRange bounds (r,c) && board ! (r,c)\n bounds = Array.bounds board\n\nanswerQuerySlow :: Array.Array (Int,Int) Bool -> (Int,Int,Int,Int) -> Integer\nanswerQuerySlow board (r1,c1,r2,c2)\n = foldl add 0 [dirPlacements rc (1,0) | rc <- Array.range ((r1,c1),(r2-1,c2))]\n + foldl add 0 [dirPlacements rc (0,1) | rc <- Array.range ((r1,c1),(r2,c2-1))]\n where add :: Integer -> Int -> Integer\n add x y = x + toInteger y\n combPlacements (r,c) = if placeable (r,c)\n then (if placeable (r+1,c) then 1 else 0)\n + (if placeable (r,c+1) then 1 else 0)\n else 0\n dirPlacements (r,c) (dr,dc) = if placeable (r,c) && placeable (r+dr,c+dc)\n then 1\n else 0\n placeable (r,c) = Array.inRange bounds (r,c) && board ! (r,c)\n bounds = Array.bounds board\n\nanswerQuery :: Array.Array (Int,Int) Int -> (Int,Int,Int,Int) -> Integer\nanswerQuery precomputedPlacements (r1,c1,r2,c2)\n = foldl add 0 [precomputedPlacements ! rc | rc <- Array.range ((r1,c1),(r2-1,c2-1))]\n where add :: Integer -> Int -> Integer\n add x y = x + toInteger y\n\nsublist start size lst = (take $ fromInteger size) . (drop $ fromInteger start) $ lst\n\ntoTuple [a,b,c,d] = (a,b,c,d)\n\nmain :: IO ()\nmain = do\n rawInput <- getContents\n let rawLines = lines rawInput\n\n let boardSpecStr = head $ sublist 0 1 rawLines\n let [rCount, cCount] = map read (words boardSpecStr) :: [Integer]\n\n let boardRowsStr = sublist 1 rCount rawLines\n let board = parseBoard boardRowsStr\n\n let precomputedPlacements = placements board\n putStrLn $ show precomputedPlacements\n\n let qCountStr = head $ sublist (1 + rCount) 1 rawLines\n let qCount = read qCountStr :: Integer\n\n let queriesStr = sublist (1 + rCount + 1) qCount rawLines\n let queries = map (toTuple . (map read) . words) queriesStr :: [(Int,Int,Int,Int)]\n\n --let answers = map (answerQuery precomputedPlacements) queries\n let answers = map (answerQuerySlow board) queries\n\n mapM_ (putStrLn . show) answers\n"}], "src_uid": "d9fdf0827940883069bead0d00b3da53"} {"source_code": "import Data.Graph\nimport Data.Foldable\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.Tuple\nmain :: IO ()\nmain = routine\n\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map read.words) <$> getLine\n edgs <- replicateM (n-1) $ (map read.words) <$> getLine\n let\n tree = toTree n edgs\n enriched = addChildren $ addDepth 0 tree\n scores = toScores $ toList enriched\n answer = sum $ take (n-k) $ sortOn Down scores\n in print answer\n\n\n\ntoTree :: Int -> [[Int]] -> Tree Int\ntoTree n ps =head $ dfs gr [1]\n where\n tups = map (\\[a,b] -> (a,b)) ps\n gr = buildG (1,n) (tups++map swap tups)\n\naddDepth :: Integer -> Tree Int -> Tree (Int,Integer)\naddDepth n (Node a ts) = Node (a,n) (map (addDepth (n+1)) ts)\n\naddChildren :: Tree (Int,Integer) -> Tree ((Int,Integer),Integer)\naddChildren (Node a ts) = Node (a,s) m\n where\n m = map addChildren ts\n s =sum $ map (\\(Node (_,c) _) -> c+1 ) m\n\ntoScores :: [((Int,Integer),Integer)] -> [Integer]\ntoScores = map (\\((_,d),c) -> c-d)\n", "positive_code": [{"source_code": "\nimport Data.Tree\nimport Data.Graph\nimport Data.List\nimport Data.Ord\nimport Data.Tuple\n\nmakeTree :: Int -> [(Int, Int)] -> Tree Int\nmakeTree n edges = tree\n where\n revEdges = map swap edges\n graph = buildG (1,n) $ edges ++ revEdges\n tree = head $ dfs graph [1]\n\ndepthFold :: Int -> ((Int, a) -> [b] -> b) -> Tree a -> b\ndepthFold depth folder (Node x ts) = folder (depth, x) (map (depthFold (depth+1) folder) ts)\n\ndata MyNode = MyNode\n { id :: Int\n , nAncestors :: Int\n , nDescendants :: Int\n } deriving (Eq, Show)\n\nvalue :: MyNode -> Integer\nvalue (MyNode _ na nd) = fromIntegral na - fromIntegral nd\n\nfolder :: (Int, Int) -> [(Tree MyNode, Int)] -> (Tree MyNode, Int)\nfolder (depth, id) children = (Node (MyNode id depth nDes) $ map fst children, nDes+1)\n where\n nDes = sum $ map snd children\n\ndecorateTree :: Tree Int -> Tree MyNode\ndecorateTree = fst . depthFold 0 folder\n\nmaxHappiness :: Int -> Tree Int -> Integer\nmaxHappiness k rawTree = sum $ take k values\n where\n tree = decorateTree rawTree\n values = sortOn Down $ map value $ flatten tree\n\nparseLine :: String -> [Int]\nparseLine = map read . words\n \nparseAndSolve :: [String] -> Integer\nparseAndSolve (l1:edgeLines) = maxHappiness k tree\n where\n (n:k:_) = parseLine l1\n makeEdge (s:e:_) = (s,e)\n edges = map (makeEdge . parseLine) edgeLines\n tree = makeTree n edges\n\nparseAndSolveIO :: [String] -> IO Integer\nparseAndSolveIO (l1:edgeLines) = do\n _ <- putStrLn (drawTree $ fmap show deTree)\n return $ maxHappiness k tree\n where\n (n:k:_) = parseLine l1\n makeEdge (s:e:_) = (s,e)\n edges = map (makeEdge . parseLine) edgeLines\n tree = makeTree n edges\n deTree = decorateTree tree\n\nmain :: IO ()\nmain = interact $ show . parseAndSolve . lines\n\n\nmain1 = do\n ans <- parseAndSolveIO [\"8 5\",\"7 5\",\"1 7\",\"6 1\",\"3 7\",\"8 3\",\"2 1\",\"4 5\"]\n return ()"}], "negative_code": [{"source_code": "import Data.Graph\nimport Data.Foldable\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport Data.Tuple\nmain :: IO ()\nmain = routine\n\n\nroutine :: IO ()\nroutine = do\n [n,k] <- (map read.words) <$> getLine\n edgs <- replicateM (n-1) $ (map read.words) <$> getLine\n let\n tree = toTree n edgs\n enriched = addChildren $ addDepth 0 tree\n scores = toScores $ toList enriched\n answer = sum $ take (n-k) $ sortOn Down scores\n in print answer\n\n\n\ntoTree :: Int -> [[Int]] -> Tree Int\ntoTree n ps =head $ dfs gr [1]\n where\n tups = map (\\[a,b] -> (a,b)) ps\n gr = buildG (1,n) (tups++map swap tups)\n\naddDepth :: Int -> Tree Int -> Tree (Int,Int)\naddDepth n (Node a ts) = Node (a,n) (map (addDepth (n+1)) ts)\n\naddChildren :: Tree (Int,Int) -> Tree ((Int,Int),Int)\naddChildren (Node a ts) = Node (a,s) m\n where\n m = map addChildren ts\n s =sum $ map (\\(Node (_,c) _) -> c+1 ) m\n\ntoScores :: [((Int,Int),Int)] -> [Int]\ntoScores = map (\\((_,d),c) -> c-d)\n"}, {"source_code": "\nimport Data.Tree\nimport Data.Graph\nimport Data.List\nimport Data.Ord\nimport Data.Tuple\n\nmakeTree :: Int -> [(Int, Int)] -> Tree Int\nmakeTree n edges = tree\n where\n revEdges = map swap edges\n graph = buildG (1,n) $ edges ++ revEdges\n tree = head $ dfs graph [1]\n\ndepthFold :: Int -> ((Int, a) -> [b] -> b) -> Tree a -> b\ndepthFold depth folder (Node x ts) = folder (depth, x) (map (depthFold (depth+1) folder) ts)\n\ndata MyNode = MyNode\n { id :: Int\n , nAncestors :: Int\n , nDescendants :: Int\n } deriving (Eq, Show)\n\nvalue :: MyNode -> Int\nvalue (MyNode _ na nd) = na - nd\n\nfolder :: (Int, Int) -> [(Tree MyNode, Int)] -> (Tree MyNode, Int)\nfolder (depth, id) children = (Node (MyNode id depth nDes) $ map fst children, nDes+1)\n where\n nDes = sum $ map snd children\n\ndecorateTree :: Tree Int -> Tree MyNode\ndecorateTree = fst . depthFold 0 folder\n\nmaxHappiness :: Int -> Tree Int -> Int\nmaxHappiness k rawTree = sum $ take k values\n where\n tree = decorateTree rawTree\n values = sortOn Down $ map value $ flatten tree\n\nparseLine :: String -> [Int]\nparseLine = map read . words\n \nparseAndSolve :: [String] -> Int\nparseAndSolve (l1:edgeLines) = maxHappiness k tree\n where\n (n:k:_) = parseLine l1\n makeEdge (s:e:_) = (s,e)\n edges = map (makeEdge . parseLine) edgeLines\n tree = makeTree n edges\n\nparseAndSolveIO :: [String] -> IO Int\nparseAndSolveIO (l1:edgeLines) = do\n _ <- putStrLn (drawTree $ fmap show deTree)\n return $ maxHappiness k tree\n where\n (n:k:_) = parseLine l1\n makeEdge (s:e:_) = (s,e)\n edges = map (makeEdge . parseLine) edgeLines\n tree = makeTree n edges\n deTree = decorateTree tree\n\nmain :: IO ()\nmain = interact $ show . parseAndSolve . lines\n\n\nmain1 = do\n ans <- parseAndSolveIO [\"8 5\",\"7 5\",\"1 7\",\"6 1\",\"3 7\",\"8 3\",\"2 1\",\"4 5\"]\n return ()"}, {"source_code": "import Data.Tree\n\nmain = putStrLn \"Testing import\""}], "src_uid": "47129977694cb371c7647cfd0db63d29"} {"source_code": "import Data.List\nimport Data.Function\n\nf :: [(Int,Int)]->String\nf ((_,x):(_,y):_) | x == y = \"Still Rozdil\"\nf ((x,_):_) = show x\nf [] = \"Still Rozdil\"\n\n\nmain = do\n num <- readLn\n nums <- getLine >>= (return.sortBy (compare `on` snd).zip [1..].map read.take num.words)\n putStrLn (f nums)", "positive_code": [{"source_code": "import Data.List\n\ncalc :: [Int] -> String\ncalc xs\n | length ys > 1 && ys!!0 == ys!!1 = \"Still Rozdil\"\n | otherwise = case findIndex (==(ys!!0)) xs of\n Just n -> show (n+1)\n Nothing -> error \"not found\"\n where\n ys = sort xs\n\nmain = do s <- getLine\n t <- getLine\n putStrLn $ calc $ map (\\x -> read x :: Int) $ words t\n\n"}, {"source_code": "-- Little Elephant and Rozdil\n\nimport Data.List (findIndices)\nimport Control.Applicative \n\nmain :: IO ()\n{-\nmain = getLine >> getLine >>= putStrLn . sol . (map read . words)\n\n\nsol :: [Int] -> String\nsol xs = do\n let ys = findIndices (== minimum xs) xs\n return $ case length ys of\n 1 -> show $ succ . head ys \n _ -> \"Still Rozdil\"\n\n\nsol' xs = if lenght (findIndices (== minimum xs) xs) == 1\n then succ $ head \n\n-}\n\nmain = do\n getLine\n as <- map (read :: String -> Int) . words <$> getLine\n let m = minimum as\n is = filter ((== m) . snd) $ zip [1..] as\n\n if length is == 1\n then print $ fst . head $ is\n else putStrLn \"Still Rozdil\"\n\n"}, {"source_code": "solve::Int -> Int -> [(Int,Int)] -> String\nsolve ret tmp (x:xs)\n | tmp > (snd(x)) = solve (fst(x)) (snd(x)) xs\n | tmp == (snd(x)) = solve (-1) tmp xs\n | otherwise = solve ret tmp xs\nsolve ret _ []\n | ret == (-1) = \"Still Rozdil\"\n | otherwise = show ret\n\nmain = do\n num <- getLine\n args <- getLine\n let l = zip [1..] $ map (read::String->Int) $ words args\n putStrLn(solve 0 (2^30) l)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n m = minimum as\n is = findIndices (== m) as\n\n if length is == 1\n then print $ (head is) + 1\n else putStrLn \"Still Rozdil\"\n"}, {"source_code": "\nmain = do\n\t\tngorodov <- getLine\n\t\tgoroda <- getLine\n\t\tputStrLn $ out ( map read (words goroda))\n\nout :: \t[Integer] -> String\nout [_]\t= \"1\"\nout goroda = if (first == second) then \"Still Rozdil\" else path\n\t\t\t\t\twhere\n\t\t\t\t\tfirst = head $ quicksort goroda\n\t\t\t\t\tsecond = head $ tail $ quicksort goroda\n\t\t\t\t\tpath = show (findNumberOfElem goroda first)\n\t\t\t\t\t\nquicksort :: [Integer] -> [Integer]\nquicksort [] = []\nquicksort (x:xs) = quicksort [y | y <- xs, y=x]\n \nfindNumberOfElem :: [Integer]-> Integer -> Integer\nfindNumberOfElem [] m = 0\nfindNumberOfElem (x:xs) m = 1 + if x == m \n\t\t\t\t\t\t\t\tthen 0 \n\t\t\t\t\t\t\t\telse findNumberOfElem xs m \t\t\t\t\t\t\t\t"}, {"source_code": "import Data.List\nimport Data.Function\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nmain = putStrLn =<< (\\x -> if length x > 1 then \"Still Rozdil\" else show $ fst $ head x) . head . groupBy ((==) `on` snd ) . sortOn snd . zip [1..] . map ( fst .fromJust .B.readInt) . B.words <$> (B.getLine >> B.getLine)\n"}, {"source_code": "import Data.List\nimport Data.Function\nmain = putStrLn =<< (\\x -> if length x > 1 then \"Still Rozdil\" else show $ fst $ head x) . head . groupBy ((==) `on` snd ) . sortOn snd . zip [1..] . map ( read :: String -> Int) . words <$> (getLine >> getLine)\n"}, {"source_code": "import Data.Function (on)\nimport List (sortBy)\n\nsolve :: [Int] -> Maybe Int\nsolve [x] = Just 1\nsolve xs = solve' $ sortBy (compare `on` fst) (zipWith (,) xs [1..])\n where\n solve' ((a,n):(b,_):_)\n | a == b = Nothing\n | otherwise = Just n\n\nprintAns :: Maybe Int -> IO ()\nprintAns Nothing = putStrLn \"Still Rozdil\"\nprintAns (Just x) = print x\n\nmain :: IO()\nmain = getLine >> getLine >>= return . map read . words >>= printAns . solve"}, {"source_code": "import Data.Maybe\nimport Data.List\nmain = do\n getLine\n s <- getLine\n let towns :: [Int]\n towns = map read . words $ s\n sortedTowns = group . sort $ towns\n if length (sortedTowns !! 0) == 1 then\n print $ fromJust (elemIndex (sortedTowns !! 0 !! 0) towns) + 1\n else\n putStrLn \"Still Rozdil\"\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nf :: [Int] -> String\nf a = if((==) 1 $ length $ filter(\\x -> x == minimum a) a)\n then show $ (+) 1 $ fromJust $ elemIndex (minimum a) a\n else \"Still Rozdil\"\nmain=interact$f.map read.tail.words\n"}, {"source_code": "import Data.List\nimport Data.Ord\nimport Data.Function\nimport Control.Applicative\n\nmain = do\n n <- readLn :: IO Int\n cities <- head.groupBy((==)`on`snd).sortBy(comparing snd).zip[1..n].map read.words <$> getLine :: IO [(Int,Int)]\n case cities of\n [(i,_)] -> print i\n _ -> putStrLn \"Still Rozdil\""}, {"source_code": "main = getContents >>= solve [].zip[1..].map read.tail.words\n\nsolve :: [(Int,Int)] -> [(Int,Int)] -> IO ()\nsolve [(i,_)] [] = print i\nsolve _ [] = putStrLn \"Still Rozdil\"\nsolve [] ((j,y):ys) = solve [(j,y)] ys\nsolve ixs@((i,x):xs) ((j,y):ys)\n | x==y = solve [(i,x),(i,x)] ys\n | xy = solve [(j,y)] ys"}, {"source_code": "import qualified Data.ByteString.Char8 as B\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = getLine >> B.getContents >>= solve [].zip[1..].map readInt.B.words\n\nsolve [(i,_)] [] = print i\nsolve _ [] = putStrLn \"Still Rozdil\"\nsolve [] ((j,y):ys) = solve [(j,y)] ys\nsolve ixs@((i,x):xs) ((j,y):ys)\n | x==y = solve [(i,x),(i,x)] ys\n | xy = solve [(j,y)] ys"}, {"source_code": "import Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = interact $ lines >>> tail >>> head >>> words >>> map read >>> solve >>> showA >>> (++\"\\n\")\n\nshowA :: Maybe Int -> String\nshowA Nothing = \"Still Rozdil\"\nshowA (Just x) = show x\n\nsolve :: [Int] -> Maybe Int\nsolve xs = let m = minimum xs in case length $ elemIndices m xs of\n 1 -> elemIndex m xs >>= (return . (+1))\n _ -> Nothing"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nreadInput :: IO [Int]\nreadInput = do\n _ <- getLine\n map read . words <$> getLine\n\ncountOccurences :: Eq a => a -> [a] -> Int\ncountOccurences x = length . (elemIndices x)\n\nsolve :: [Int] -> Maybe Int\nsolve xs | countOccurences m xs == 1 = elemIndex m xs\n | otherwise = Nothing\n where m = minimum xs\n\nmain :: IO ()\nmain = readInput >>= (putStrLn . show' . solve)\n where show' (Just x) = show $ x + 1\n show' Nothing = \"Still Rozdil\"\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\n\n-- readInput :: IO [Int]\n-- readInput = do\n-- _ <- getLine\n-- map read . words <$> getLine\n\nreadInput :: IO [Int]\nreadInput = do\n _ <- B.getLine\n map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\ncountOccurences :: Eq a => a -> [a] -> Int\ncountOccurences x = length . (elemIndices x)\n\nsolve :: [Int] -> Maybe Int\nsolve xs | countOccurences m xs == 1 = elemIndex m xs\n | otherwise = Nothing\n where m = minimum xs\n\nmain :: IO ()\nmain = readInput >>= (putStrLn . show' . solve)\n where show' (Just x) = show $ x + 1\n show' Nothing = \"Still Rozdil\"\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\nimport Data.Function\nimport Data.Array\n\nmain = do\n getLine\n xs <- map (read::String->Int). words <$> getLine\n let\n m = minimum xs\n f = filter ((m==). snd)$ zip [1..] xs\n if length f == 1 then print. fst. head$ f\n else putStrLn \"Still Rozdil\"\n"}, {"source_code": "import Data.List\n\ncalc :: [Int] -> String\ncalc xs\n | length xs > 1 && ys!!0 == ys!!1 = \"Still Rozdil\"\n | otherwise = case findIndex (== (ys!!0)) xs of\n Just n -> show (n+1)\n Nothing -> error \"not found\"\n where\n ys = sort xs\n\nmain = do s <- getLine\n t <- getLine\n putStrLn $ calc $ map (\\x -> read x :: Int) $ words t\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Array.IO.Safe\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n as <- getInts :: IO [Int]\n\n let\n m = minimum as\n is = findIndices (== m) as\n\n if length is == 1\n then print m\n else putStrLn \"Still Rozdil\"\n"}, {"source_code": "import List (sort)\n\nsolve :: [Int] -> Maybe Int\nsolve [x] = Just x\nsolve xs = solve' $ sort xs\n where\n solve' (a:b:_)\n | a == b = Nothing\n | otherwise = Just a\n\nprintAns :: Maybe Int -> IO ()\nprintAns Nothing = putStrLn \"Still Rozdil\"\nprintAns (Just x) = print x\n\nmain :: IO()\nmain = getLine >> getLine >>= return . map read . words >>= printAns . solve"}, {"source_code": "import Data.Function (on)\nimport List (sortBy)\n\nsolve :: [Int] -> Maybe Int\nsolve [x] = Just x\nsolve xs = solve' $ sortBy (compare `on` fst) (zipWith (,) xs [1..])\n where\n solve' ((a,n):(b,_):_)\n | a == b = Nothing\n | otherwise = Just n\n\nprintAns :: Maybe Int -> IO ()\nprintAns Nothing = putStrLn \"Still Rozdil\"\nprintAns (Just x) = print x\n\nmain :: IO()\nmain = getLine >> getLine >>= return . map read . words >>= printAns . solve"}, {"source_code": "import Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = interact $ lines >>> tail >>> head >>> words >>> map read >>> solve >>> showA >>> (++\"\\n\")\n\nshowA :: Maybe Int -> String\nshowA Nothing = \"Still Rozdil\"\nshowA (Just x) = show x\n\nsolve :: [Int] -> Maybe Int\nsolve xs = let m = minimum xs in case length $ elemIndices m xs of\n 1 -> Just m\n _ -> Nothing"}, {"source_code": "import Data.List\nimport Control.Arrow\n\nmain :: IO ()\nmain = interact $ lines >>> tail >>> head >>> words >>> map read >>> solve >>> showA >>> (++\"\\n\")\n\nshowA :: Maybe Int -> String\nshowA Nothing = \"Still Rozdil\"\nshowA (Just x) = show x\n\nsolve :: [Int] -> Maybe Int\nsolve xs = let m = minimum xs in case length $ elemIndices m xs of\n 1 -> elemIndex m xs\n _ -> Nothing"}, {"source_code": "import Data.List\n\nf :: [Int]->String\nf (x:y:[]) | x == y = \"Still Rozdil\"\nf (x:_) = show x\nf [] = \"Still Rozdil\"\n\n\nmain = do\n num <- readLn\n nums <- getLine >>= (return.sort.map read.take num.words)\n putStrLn (f nums)"}, {"source_code": "import Data.List\n\n\n\ncalc xs\n\n | length xs > 1 && xs!!0 == xs!!1 = \"Still Rozdil\"\n\n | otherwise = show $ xs!!0\n\n\n\nmain = do s <- getLine\n\n t <- getLine\n\n putStrLn $ calc $ sort $ map (\\x -> read x :: Int) $ words t\n\n"}], "src_uid": "ce68f1171d9972a1b40b0450a05aa9cd"} {"source_code": "main :: IO ()\nmain = interact $ unlines . map (solve . read) . drop 1 . lines\n\nsolve :: Int -> String\nsolve x = build (if x `mod` 3 == 1 then 1 else 2) x \"\"\n\nbuild :: Int -> Int -> String -> String\nbuild _ 0 res = reverse res\nbuild d x acc = build (3 - d) (x - d) (show d ++ acc)\n", "positive_code": [{"source_code": "module Main where\r\n\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n n <- readLn\r\n if (n `mod` 3) == 1\r\n then\r\n putStrLn $ f 1 n\r\n else\r\n putStrLn $ f 2 n\r\n\r\nf :: Int -> Int -> String\r\nf _ 0 = \"\"\r\nf 1 n = '1' : f 2 (n - 1)\r\nf _ n = '2' : f 1 (n - 2)\r\n\r\n-- 1\r\n-- 2\r\n-- 21\r\n-- 121\r\n-- 212\r\n-- 2121\r\n-- 12121\r\n"}, {"source_code": "-- https://codeforces.com/contest/1679/problem/D\n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE NumericUnderscores #-}\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"Yes\"\n else \"No\"\n printf \"%s\\n\" result\n\n\n{- END OF GENERAL -}\n\nsolve :: Int -> String\nsolve cnt\n | cnt `mod` 3 == 1 = concat $ \"1\" : replicate (cnt `div` 3) \"21\"\n | cnt `mod` 3 == 2 = concat $ \"2\" : replicate (cnt `div` 3) \"12\"\n | cnt `mod` 3 == 0 = concat $ replicate (cnt `div` 3) \"21\"\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n n <- B8.getLine <&> readIntB8\n let answer = solve n\n puts answer\n"}], "negative_code": [{"source_code": "main :: IO ()\nmain = interact $ unlines . map (show . solve . read) . drop 1 . lines\n\nsolve :: Int -> Int\nsolve x = build (if x `mod` 3 == 1 then 1 else 2) x 0\n\nbuild :: Int -> Int -> Int -> Int\nbuild _ 0 res = res\nbuild d x acc = build (3 - d) (x - d) (acc * 10 + d)\n"}], "src_uid": "1a5f266b49aadbeef59e19bcf5524a57"} {"source_code": "getList :: Read a => IO [a]\r\ngetList = map read . words <$> getLine\r\n \r\nsolve :: Int -> IO()\r\nsolve t\r\n | t > 0 = do\r\n getLine\r\n nums <- getList\r\n print $ length $ filter (/= 2) nums\r\n solve $ t - 1\r\n | otherwise = return ()\r\n \r\n \r\nmain :: IO()\r\nmain = do\r\n [t] <- getList\r\n solve t", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n\r\nimport qualified Data.List as L\r\nimport qualified Data.Map as M\r\nimport qualified Data.Set as S\r\n\r\n\r\nimport qualified Data.Array as A\r\n\r\nimport qualified Control.Monad.State.Strict as State\r\nimport Control.Monad.ST\r\n\r\nimport Data.Bits(xor, (.&.), (.|.))\r\nimport qualified Data.Array.MArray as MA\r\nimport Data.STRef(STRef, newSTRef, readSTRef, writeSTRef)\r\nimport Data.Array.ST(runSTArray, STArray)\r\nimport Data.Array.IO(IOArray)\r\n\r\nimport Data.Array((!))\r\nimport Control.Monad(replicateM, filterM, forM) -- foldM est un foldl\r\nimport Data.Maybe\r\n\r\ntype Output = Integer \r\n\r\nsolve :: Integer -> [Integer] -> Output\r\nsolve n a = n - sum [1 | x<-a, x == 2]\r\n\r\n\r\n\r\n\r\n\r\nplotResult :: Output -> IO ()\r\nplotResult = print \r\n\r\n\r\nmain :: IO ()\r\nmain = do \r\n\tt <- getLine >>= return . read :: IO Int\r\n\treplicateM t $ do \r\n\t\t[n] <- getLine >>= return . (fmap read) . words :: IO [Integer] \r\n\t\ta <- getLine >>= return . (fmap read) . words :: IO [Integer]\r\n\t\tplotResult $ solve n a\r\n\treturn ()\r\n"}, {"source_code": "module Main where\r\n solve :: IO ()\r\n solve = do\r\n _ <- getLine\r\n s <- getLine \r\n print $ length . filter (/= \"2\") $ words s\r\n \r\n iter :: Integer -> IO ()\r\n iter 1 = solve\r\n iter x = do\r\n solve\r\n iter $ x - 1\r\n \r\n main :: IO ()\r\n main = do\r\n q <- getLine\r\n iter (read q :: Integer)"}, {"source_code": "import Control.Monad\n\nreadInt :: IO Integer\nreadInt = readLn\n\nreadArray :: Read a => IO [a]\nreadArray = fmap (map read . words) getLine\n\nreadInts :: IO [Integer]\nreadInts = readArray\n\nsolve :: [Integer] -> Int\nsolve = length . filter (/= 2)\n\nsolveCase :: IO String\nsolveCase = readInt >> fmap (show . solve) readInts\n--solveCase = do\n-- (n:x:[]) <- readInts\n-- fmap (show . solve x) readInts\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (solveCase >>= putStrLn)\n"}, {"source_code": "getList :: Read a => IO [a]\r\ngetList = map read . words <$> getLine\r\n\r\nsolve :: Int -> IO()\r\nsolve t\r\n | t > 0 = do\r\n getLine\r\n nums <- getList\r\n print $ length $ filter (/= 2) nums\r\n solve $ t - 1\r\n | otherwise = return ()\r\n \r\n\r\nmain :: IO()\r\nmain = do\r\n [t] <- getList\r\n solve t"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n _ <- C.getLine\n rs <- getInts\n C.putStrLn $ C.pack $ show $ length $ filter (/= 2) rs\n"}], "negative_code": [], "src_uid": "a063705bd0ce1e17ccaafbbfc2663d93"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Data.IORef\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.State.Strict (StateT)\nimport qualified Control.Monad.Trans.State.Strict as STT\nimport Control.Monad.Trans.Class\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\nimport Text.Read (readEither)\n\ngetNewLine :: SIO ByteString\ngetNewLine = (lift $ C.hGetLine stdin) >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n\ngetRemain :: ByteString -> SIO ByteString\ngetRemain b = do\n let bns = C.dropWhile isSpace b in\n if C.null bns then getNewLine >>= (\\x -> STT.put x >>= const (return x))\n else return bns\n\ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n\ntype SIO a = StateT ByteString IO a\n\nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n\ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => SIO a\nget = do\n r <- STT.get\n (a, nr) <- liftM convert $ getRemain r\n STT.put nr\n return a\n\nput :: IOInteract a => a -> SIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> SIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: SIO ()\nflush = lift (hFlush stdout)\n\nmain :: IO ()\nmain = do\n o <- STT.evalStateT main_ C.empty\n return o\n\nmain_ :: SIO ()\n-------------------------------------------- template ------------------------------------------------------\nmain_ = do\n (n, m) <- liftM2 (,) get get\n l <- replicateM m $ liftM2 (,) get get\n k <- get\n p <- replicateM k get\n let (minr, maxr) = f1 (buildGraph n l) p in\n putln $ show minr ++ \" \" ++ show maxr\n\nbuildGraph :: Int -> [(Int, Int)] -> IntMap (IntSet)\nbuildGraph n l = foldl (\\m (i, j) -> IntMap.adjust (IntSet.insert j) i m) (IntMap.fromSet (const IntSet.empty) $ IntSet.fromDistinctAscList [1..n]) l\n\ntransposeG :: IntMap (IntSet) -> IntMap (IntSet)\ntransposeG g = IntMap.foldlWithKey (\\m i s -> IntSet.foldl (\\m j -> IntMap.adjust (IntSet.insert i) j m) m s) (IntMap.map (const IntSet.empty) g) g \n\nbfs :: a -> (a -> a) -> Int -> IntMap (IntSet) -> IntMap a\nbfs init modify root g = let aux [] [] _ vs = foldl (\\m (i, a) -> IntMap.insert i a m) IntMap.empty vs\n aux [] nextv visited vs = aux (reverse nextv) [] visited vs\n aux ((v, x) : l) nextv visited vs = let nextx = modify x in\n let (nvisited, nvlist) = IntSet.foldl (\\(v, l) i -> if not $ IntSet.member i visited then (IntSet.insert i v, (i, nextx) : l) else (v, l)) (visited, nextv) (g IntMap.! v) in\n aux l nvlist nvisited $ (v, x) : vs\n in\n aux [(root, init)] [] (IntSet.singleton root) [(root, init)]\n\nf1 :: IntMap (IntSet) -> [Int] -> (Int, Int)\nf1 g [] = (0, 0)\nf1 g (s : l) = let sd = bfs 0 ((+) 1) (last (s : l)) (transposeG g) in\n let (_, minr, maxr) = foldl (\\(prev, i, j) p -> let pd = sd IntMap.! prev in\n if pd - (sd IntMap.! p) < 1 then (p, i + 1, j + 1)\n else if (IntSet.foldl (\\b i -> if pd - (sd IntMap.! i) == 1 then b + 1 else b) 0 (g IntMap.! prev)) > 1 then (p, i, j + 1)\n else (p, i, j)\n ) (s, 0, 0) l in\n (minr, maxr)", "positive_code": [{"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Data.IORef\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\nimport Text.Read (readEither)\n\ngetNewLine :: IO ByteString\ngetNewLine = C.hGetLine stdin >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n\ngetRemain :: IORef ByteString -> IO ByteString\ngetRemain b = do\n bs <- readIORef b\n let bns = C.dropWhile isSpace bs in\n if C.null bns then getNewLine >>= (\\x -> writeIORef b x >>= const (return x))\n else return bns\n\ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n\ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => IORef ByteString -> IO a\nget ibuf = do\n (a, r) <- liftM convert $ getRemain ibuf\n writeIORef ibuf r\n return a\n\nput :: IOInteract a => a -> IO ()\nput = (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> IO ()\nputln = (hPutStrLn stdout) . toShow\nflush :: IO ()\nflush = hFlush stdout\n\nmain :: IO ()\nmain = do\n ibuf <- newIORef C.empty\n o <- main_ ibuf\n return o\n\nmain_ :: IORef ByteString -> IO ()\n-------------------------------------------- template ------------------------------------------------------\nmain_ ibuf = do\n (n, m) <- liftM2 (,) (get ibuf) (get ibuf)\n l <- replicateM m $ liftM2 (,) (get ibuf) (get ibuf)\n k <- (get ibuf)\n p <- replicateM k (get ibuf)\n let (minr, maxr) = f1 (buildGraph n l) p in\n putln $ show minr ++ \" \" ++ show maxr\n\nbuildGraph :: Int -> [(Int, Int)] -> IntMap (IntSet)\nbuildGraph n l = foldl (\\m (i, j) -> IntMap.adjust (IntSet.insert j) i m) (IntMap.fromSet (const IntSet.empty) $ IntSet.fromDistinctAscList [1..n]) l\n\ntransposeG :: IntMap (IntSet) -> IntMap (IntSet)\ntransposeG g = IntMap.foldlWithKey (\\m i s -> IntSet.foldl (\\m j -> IntMap.adjust (IntSet.insert i) j m) m s) (IntMap.map (const IntSet.empty) g) g \n\nbfs :: a -> (a -> a) -> Int -> IntMap (IntSet) -> IntMap a\nbfs init modify root g = let aux [] [] _ vs = foldl (\\m (i, a) -> IntMap.insert i a m) IntMap.empty vs\n aux [] nextv visited vs = aux (reverse nextv) [] visited vs\n aux ((v, x) : l) nextv visited vs = let nextx = modify x in\n let (nvisited, nvlist) = IntSet.foldl (\\(v, l) i -> if not $ IntSet.member i visited then (IntSet.insert i v, (i, nextx) : l) else (v, l)) (visited, nextv) (g IntMap.! v) in\n nvisited `seq` aux l nvlist nvisited $ (v, x) : vs\n in\n aux [(root, init)] [] (IntSet.singleton root) [(root, init)]\n\nf1 :: IntMap (IntSet) -> [Int] -> (Int, Int)\nf1 g [] = (0, 0)\nf1 g (s : l) = let sd = bfs 0 ((+) 1) (last (s : l)) (transposeG g) in\n let (_, minr, maxr) = foldl (\\(prev, i, j) p -> let pd = sd IntMap.! prev in\n if pd - (sd IntMap.! p) < 1 then (p, i + 1, j + 1)\n else if (IntSet.foldl (\\b i -> if pd - (sd IntMap.! i) == 1 then b + 1 else b) 0 (g IntMap.! prev)) > 1 then (p, i, j + 1)\n else (p, i, j)\n ) (s, 0, 0) l in\n (minr, maxr)"}, {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Data.IORef\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\nimport Text.Read (readEither)\n\ngetNewLine :: IO ByteString\ngetNewLine = C.hGetLine stdin >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n\ngetRemain :: IORef ByteString -> IO ByteString\ngetRemain b = do\n bs <- readIORef b\n let bns = C.dropWhile isSpace bs in\n if C.null bns then getNewLine >>= (\\x -> writeIORef b x >>= const (return x))\n else return bns\n\ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n\ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => IORef ByteString -> IO a\nget ibuf = do\n (a, r) <- liftM convert $ getRemain ibuf\n writeIORef ibuf r\n return a\n\nput :: IOInteract a => a -> IO ()\nput = (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> IO ()\nputln = (hPutStrLn stdout) . toShow\nflush :: IO ()\nflush = hFlush stdout\n\nmain :: IO ()\nmain = do\n ibuf <- newIORef C.empty\n o <- main_ ibuf\n return o\n\nmain_ :: IORef ByteString -> IO ()\n-------------------------------------------- template ------------------------------------------------------\nmain_ ibuf = do\n (n, m) <- liftM2 (,) (get ibuf) (get ibuf)\n l <- replicateM m $ liftM2 (,) (get ibuf) (get ibuf)\n k <- (get ibuf)\n p <- replicateM k (get ibuf)\n let (minr, maxr) = f1 (buildGraph n l) p in\n putln $ show minr ++ \" \" ++ show maxr\n\nbuildGraph :: Int -> [(Int, Int)] -> IntMap (IntSet)\nbuildGraph n l = foldl' (\\m (i, j) -> IntMap.adjust (IntSet.insert j) i m) (IntMap.fromSet (const IntSet.empty) $ IntSet.fromDistinctAscList [1..n]) l\n\ntransposeG :: IntMap (IntSet) -> IntMap (IntSet)\ntransposeG g = IntMap.foldlWithKey (\\m i s -> IntSet.foldl' (\\m j -> IntMap.adjust (IntSet.insert i) j m) m s) (IntMap.map (const IntSet.empty) g) g \n\nbfs :: a -> (a -> a) -> Int -> IntMap (IntSet) -> IntMap a\nbfs init modify root g = let aux [] [] _ vs = foldl' (\\m (i, a) -> IntMap.insert i a m) IntMap.empty vs\n aux [] nextv visited vs = aux (reverse nextv) [] visited vs\n aux ((v, x) : l) nextv visited vs = let nextx = modify x in\n let (nvisited, nvlist) = IntSet.foldl' (\\(v, l) i -> if not $ IntSet.member i visited then (IntSet.insert i v, (i, nextx) : l) else (v, l)) (visited, nextv) (g IntMap.! v) in\n nvisited `seq` aux l nvlist nvisited $ (v, x) : vs\n in\n aux [(root, init)] [] (IntSet.singleton root) [(root, init)]\n\nf1 :: IntMap (IntSet) -> [Int] -> (Int, Int)\nf1 g [] = (0, 0)\nf1 g (s : l) = let sd = bfs 0 ((+) 1) (last (s : l)) (transposeG g) in\n let (_, minr, maxr) = foldl' (\\(prev, i, j) p -> let pd = sd IntMap.! prev in\n if pd - (sd IntMap.! p) < 1 then (p, i + 1, j + 1)\n else if (IntSet.foldl' (\\b i -> if pd - (sd IntMap.! i) == 1 then b + 1 else b) 0 (g IntMap.! prev)) > 1 then (p, i, j + 1)\n else (p, i, j)\n ) (s, 0, 0) l in\n (minr, maxr)"}], "negative_code": [], "src_uid": "19a0c05eb2d1559ccfe60e210c6fcd6a"} {"source_code": "main=interact$unwords.map show.solve.map read.words\n\nsolve[1,0]=[1]\nsolve[1,_]=[-1]\nsolve[n,k]\n | k < n`div`2 = [-1]\n | k - q > 0 = (k-q):2*(k-q):take(n-2)[2*(k-q)+1..]\n | otherwise = [-1]\n where\n q = (n-2)`div`2\n\n", "positive_code": [{"source_code": "\nimport Data.List (intercalate,nub)\nimport Data.Ord\n\nsolve :: Int -> Int -> [Int]\nsolve 1 0 = [1]\nsolve 1 _ = []\nsolve n k | n `div` 2 > k = []\nsolve n k =\n let parts = n `div` 2\n m = k - (parts-1)\n r = if odd n then 1 else 0\n fit m c o | c+o < m = [1..c+o]\n | c < m = [1..c] ++ [m+1..m+o]\n | otherwise = [2*m+1..2*m+c+o]\n in [m,2*m] ++ (fit m (2*(parts-1)) r)\n\nscore (a:b:rest) = gcd a b + score rest\nscore _ = 0\n\ncheck :: Int -> Int -> [Int] -> Bool\ncheck n k xs = length xs == n && score xs == k && length (nub xs) == n\n\nmain = do\n (n:k:_) <- (map read . words) `fmap` getLine\n case solve n k of\n [] -> putStrLn \"-1\"\n xs -> putStrLn $ intercalate \" \" (map show xs)\n\n"}, {"source_code": "solve :: [Int] -> [Int]\nsolve [1, 0] = [ 1]\nsolve [1, _] = [-1]\nsolve [n, k] = case compare q k of\n LT -> a : a' : take (n - 2) (iterate f 1) \n EQ -> [1..n]\n GT -> [-1]\n where q = n `div` 2\n a = k - q + 1\n a' = 2 * a\n f x = let x' = x + 1 in x' + fromEnum (elem x' [a, a'])\nmain = interact $ unwords . map show . solve . map read . words"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [n,k] | k == 0 && n == 1 = [1]\n | k < n' || n == 1 = [-1]\n | otherwise = take n $ [k-n''] ++ [2*(k-n''),2*(k-n'')+1..]\n where n' = n `div` 2\n n'' = (n-2) `div` 2\n"}, {"source_code": "solve :: Int -> Int -> [Int]\nsolve 1 0 = [ 1]\nsolve 1 _ = [-1]\nsolve n k = case compare q k of\n LT -> a : a' : take (n - 2) (iterate f 1) \n EQ -> [1..n]\n GT -> [-1]\n where q = n `div` 2\n a = k - q + 1\n a' = 2 * a\n f x = let x' = x + 1 in x' + fromEnum (elem x' [a, a'])\nmain = putStrLn . unwords . map show . (\\[x, y] -> solve (read x) (read y)) . words =<< getLine"}, {"source_code": "main :: IO()\nmain = output . solve . map read . words =<< getContents\n\nsolve :: [Int] -> Maybe [Int]\nsolve [n, k] | (div n 2) > k = Nothing\n | n == 1 && k > 0 = Nothing\n | n == 1 = Just [1]\n | otherwise = let a = div n 2\n b = k - (a - 1)\n in Just (b:(b*2):(solve' (b*2 + 1) (n - 2)))\n\nsolve' :: Int -> Int -> [Int]\nsolve' _ 0 = []\nsolve' i n = i : (solve' (i + 1) (n - 1))\n\noutput :: Maybe [Int] -> IO()\noutput Nothing = putStrLn \"-1\"\noutput (Just []) = putStrLn \"\"\noutput (Just (a:ax)) = do putStr ((show a) ++ \" \")\n output (Just ax)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n\n let\n n' = 2*(n `div` 2)\n\n a = k - (n`div`2 - 1)\n b = 2*a\n\n s = [a, b] ++ s'\n s' = take (n-2) $ concat $ filter (\\[x, y] -> x /= a && y /= a && y /= b) $ [[a,a+1] | a <- [1,3..]]\n\n if n == 1\n then print (if k == 0 then 1 else -1)\n else\n if k < n `div` 2\n then print $ -1\n else\n putStrLn $ unwords $ map show $\n if k == n `div` 2\n then take n [1..]\n else s\n"}], "negative_code": [{"source_code": "main=interact$unwords.map show.solve.map read.words\n\ninf :: Int\ninf = 10^9\nsolve[1,_]=[-1]\nsolve[n,k]\n | k - q > 0 = (k-q):2*(k-q):take(n-2)[inf,inf-1..]\n | otherwise = [-1]\n where\n q = (n-2)`div`2\n"}, {"source_code": "main=interact$unwords.map show.solve.map read.words\n\nsolve[1,_]=[-1]\nsolve[n,k]\n | k < n`div`2 = [-1]\n | k - q > 0 = (k-q):2*(k-q):take(n-2)[2*(k-q)+1..]\n | otherwise = [-1]\n where\n q = (n-2)`div`2\n\n"}, {"source_code": "main=interact$unwords.map show.solve.map read.words\n\ninf :: Int\ninf = 10^9\n\nsolve[n,k]\n | n`div`2 > k = [-1]\n | otherwise = (k-q):2*(k-q):take(n-2)[inf,inf-1..]\n where\n q = (n-2)`div`2\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, k] <- getInts\n\n let\n n' = 2*(n `div` 2)\n\n a = k - (n`div`2 - 1)\n b = 2*a\n\n s = [a, b] ++ s'\n s' = take (n-2) $ concat $ filter (\\[x, y] -> x /= a && y /= a && y /= b) $ [[a,a+1] | a <- [1,3..]]\n\n if k < n `div` 2\n then print $ -1\n else\n putStrLn $ unwords $ map show $\n if k == n `div` 2\n then take n [1..]\n else s\n"}, {"source_code": "\nimport Data.List (intercalate,nub)\nimport Data.Ord\n\nsolve :: Int -> Int -> [Int]\nsolve n k | n `div` 2 > k = []\nsolve n k =\n let parts = n `div` 2\n m = k - (parts-1)\n r = if odd n then 1 else 0\n fit m c o | c+o < m = [1..c+o]\n | c < m = [1..c] ++ [m+1..m+o]\n | otherwise = [2*m+1..2*m+c+o]\n in [m,2*m] ++ (fit m (2*(parts-1)) r)\n\nscore (a:b:rest) = gcd a b + score rest\nscore _ = 0\n\ncheck :: Int -> Int -> [Int] -> Bool\ncheck n k xs = length xs == n && score xs == k && length (nub xs) == n\n\nmain = do\n (n:k:_) <- (map read . words) `fmap` getLine\n case solve n k of\n [] -> putStrLn \"-1\"\n xs -> do putStrLn $ intercalate \" \" (map show xs)\n putStrLn $ show $ check n k xs\n\n"}, {"source_code": "\nimport Data.List (intercalate,nub)\nimport Data.Ord\n\nsolve :: Int -> Int -> [Int]\nsolve 1 _ = []\nsolve n k | n `div` 2 > k = []\nsolve n k =\n let parts = n `div` 2\n m = k - (parts-1)\n r = if odd n then 1 else 0\n fit m c o | c+o < m = [1..c+o]\n | c < m = [1..c] ++ [m+1..m+o]\n | otherwise = [2*m+1..2*m+c+o]\n in [m,2*m] ++ (fit m (2*(parts-1)) r)\n\nscore (a:b:rest) = gcd a b + score rest\nscore _ = 0\n\ncheck :: Int -> Int -> [Int] -> Bool\ncheck n k xs = length xs == n && score xs == k && length (nub xs) == n\n\nmain = do\n (n:k:_) <- (map read . words) `fmap` getLine\n case solve n k of\n [] -> putStrLn \"-1\"\n xs -> putStrLn $ intercalate \" \" (map show xs)\n\n"}, {"source_code": "\nimport Data.List (intercalate,nub)\nimport Data.Ord\n\nsolve :: Int -> Int -> [Int]\nsolve n k | n `div` 2 > k = []\nsolve n k =\n let parts = n `div` 2\n m = k - (parts-1)\n r = if odd n then 1 else 0\n fit m c o | c+o < m = [1..c+o]\n | c < m = [1..c] ++ [m+1..m+o]\n | otherwise = [2*m+1..2*m+c+o]\n in [m,2*m] ++ (fit m (2*(parts-1)) r)\n\nscore (a:b:rest) = gcd a b + score rest\nscore _ = 0\n\ncheck :: Int -> Int -> [Int] -> Bool\ncheck n k xs = length xs == n && score xs == k && length (nub xs) == n\n\nmain = do\n (n:k:_) <- (map read . words) `fmap` getLine\n case solve n k of\n [] -> putStrLn \"-1\"\n xs -> putStrLn $ intercalate \" \" (map show xs)\n\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [n,k] | k < n' = [-1]\n | k `mod` n' == 0 = concatMap pair (replicate n' (k `div` n')) ++ c\n | otherwise = concatMap pair ((k `div` n' + k `mod` n') : replicate (n'-1) (k `div` n')) ++ c\n where n' = n `div` 2\n c | odd n = [1] | even n = []\npair x = [x,x]\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [n,k] | k == 0 = [1]\n | k < n' || n == 1 = [-1]\n | otherwise = take n $ [k-n''] ++ [2*(k-n''),2*(k-n'')+1..]\n where n' = n `div` 2\n n'' = (n-2) `div` 2\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [n,k] | k == 0 = [1..n]\n | k < n' || n == 1 = [-1]\n | otherwise = take n $ [k-n''] ++ [2*(k-n''),2*(k-n'')+1..]\n where n' = n `div` 2\n n'' = (n-2) `div` 2\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [n,k] | k < n' = [-1]\n | otherwise = take n $ [k-n''] ++ [2*(k-n''),2*(k-n'')+1..]\n where n' = n `div` 2\n n'' = (n-2) `div` 2\n"}, {"source_code": "main = interact $ unwords . map show . solve . map read . words\nsolve [n,k] | k < n' || n == 1 = [-1]\n | otherwise = take n $ [k-n''] ++ [2*(k-n''),2*(k-n'')+1..]\n where n' = n `div` 2\n n'' = (n-2) `div` 2\n"}], "src_uid": "b85c8bfbe67a23a81bef755f9313115a"} {"source_code": "\nsolve [[n, k], xs] = \n show $ fst $ head $ dropWhile ((==0).snd) $ dropWhile ((/=k).fst) $ cycle $ zip [1..n] xs\n\nmain = do text <- readFile \"input.txt\"\n writeFile \"output.txt\" (solve $ map (map read.words) $ lines text)", "positive_code": [{"source_code": "solve (1:_) = 0\nsolve (_:xs) = solve xs + 1\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet [n, k] = map read . words . head $ input\n\tlet k' = k - 1\n\tlet as = map read . words $ input !! 1\n\twriteFile \"output.txt\" . (++\"\\n\") . show . (+1) . (`mod`n) . (+k') . solve $ drop k' as ++ take k' as\n"}, {"source_code": "solve [[n,k],xs] = show.fst.head.dropWhile ((==0).snd). drop (k-1).cycle.zip [1..n] $ xs\nmain = readFile \"input.txt\" >>= writeFile \"output.txt\".solve.map(map read.words).lines\n"}, {"source_code": "#! /usr/bin/runhaskell\nimport Data.List\nimport Data.Maybe\nmain = do\n file <- readFile \"input.txt\"\n writeFile \"output.txt\" (show $ (f file))\n\nf file = \n if i <= n\n then i\n else i `mod` n\n where str = map read (words file) :: [Int]\n\t n = str !! 0\n\t k = (str !! 1) - 1\n lstr = tail (tail str)\n\t list = lstr ++ lstr\n\t i = (fromJust $ find (\\x -> x >= k) (elemIndices 1 list)) + 1\n"}, {"source_code": "\nimport IO\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = solve' (k-1) xs\n where\n n = length xs\n solve' k xs\n | xs !! k == 1 = k + 1\n | otherwise = solve' (mod (k + 1) n) xs\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n \n [n, k] <- hGetLine hInput >>= return . map read . words\n xs <- hGetLine hInput >>= return . map read . words \n hPutStrLn hOutput (show $ solve k xs)\n \n hClose hOutput\n hClose hInput\n"}, {"source_code": "import System.IO\nsolve k a = let ai = zip a [1..]\n (f,l) = splitAt (k-1) ai \n ai' = l++f\n in\n snd.head.dropWhile ((==0).fst) $ ai'\n\nmain = do fin <- openFile \"input.txt\" ReadMode\n l <- hGetLine fin\n a <- hGetLine fin\n hClose fin\n fout <- openFile \"output.txt\" WriteMode\n hPutStrLn fout.show $ solve (read (head.tail.words $ l)::Int) (map (read :: String -> Int) (words a))\n hClose fout"}], "negative_code": [{"source_code": "solve (1:_) = 0\nsolve (_:xs) = solve xs + 1\n\nmain = do\n\tinput <- fmap lines $ readFile \"input.txt\"\n\tlet [n, k] = map read . words . head $ input\n\tlet as = map read . words $ input !! 1\n\twriteFile \"output.txt\" . (++\"\\n\") . show . (`mod`n) . (+n) . solve $ drop (n-1) as ++ take (n-1) as\n"}], "src_uid": "1378b4c9ba8029d310f07a1027a8c7a6"} {"source_code": "import qualified Data.Map as Map\n\nmain = getContents >>= putStrLn . solve . tail . words\n\nsolve :: [String] -> String\nsolve (s:t:[]) = let (v, i, j) = foldl1 min options in unlines [show (v + v0), show i ++ \" \" ++ show j]\n where table = getTable s t\n options = (0, -1, -1) : concat [zipWith getOption table $ drop i table | i <- [1..length table]]\n v0 = diff s t\n\ndiff :: String -> String -> Int\ndiff s t = length . filter (uncurry (/=)) $ zip s t\n\ngetTable :: String -> String -> [(Char, Char, Int)]\ngetTable s t = map (\\((c1, c2), i) -> (c1, c2, i)) . Map.toList $ foldl f Map.empty (zip3 s t [1..])\n where f m (c1, c2, i) = Map.insert (c1, c2) i m\n\ngetOption :: (Char, Char, Int) -> (Char, Char, Int) -> (Int, Int, Int)\ngetOption (a1, a2, ai) (b1, b2, bi) = (v12 + v21 - v11 - v22, ai, bi)\n where v11 = if a1 == b1 then 1 else 2\n v12 = if a1 == b2 then 1 else 2\n v21 = if a2 == b1 then 1 else 2\n v22 = if a2 == b2 then 1 else 2\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport Data.Map\n\ngetDifference :: String -> String -> Int\ngetDifference xs ys = length . Data.List.filter (\\ (a, b) -> a /= b) $ zip xs ys\n \ngetPositions :: String -> String -> Map (Char, Char) Int\ngetPositions xs ys = \n Data.List.foldl' (\\ acc (x, y, pos) -> Data.Map.insert (x, y) pos acc) \n empty (zip3 xs ys [1..])\n\nfindBest :: [((Char, Char), Int)] -> (Int, Int, Int)\nfindBest entries =\n let res@(delta, p1, p2) = \n Data.List.foldl' max (0, -1, -1) \n [getCost x y | x <- entries, y <- entries]\n in if delta == 0 then (0, -1, -1) else res\n where\n getMatching :: (Char, Char) -> (Char, Char) -> Int\n getMatching (a1, b1) (a2, b2) =\n let m1 = if a1 == b1 then 1 else 0\n m2 = if a2 == b2 then 1 else 0\n in m1 + m2\n getCost :: ((Char, Char), Int) -> ((Char, Char), Int) -> (Int, Int, Int)\n getCost ((a1, b1), p1) ((a2, b2), p2) =\n (getMatching (a1, b2) (a2, b1) - getMatching (a1, b1) (a2, b2), p1, p2) \n\nmain = do\n getLine\n s <- getLine\n t <- getLine\n let positions = getPositions s t\n let entries = zip (keys positions) (elems positions)\n let (delta, p1, p2) = findBest entries\n putStrLn $ show (getDifference s t - delta)\n putStrLn $ show p1 ++ \" \" ++ show p2\n \n"}], "negative_code": [], "src_uid": "2fa543c8b8f9dc500c36cf719800a6b0"} {"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nmodule Main (main) where\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Bits\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.State.Strict (StateT)\nimport qualified Control.Monad.Trans.State.Strict as StateT\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as C\n \n\ngetNewLine :: SIO ByteString\ngetNewLine = (lift $ C.hGetLine stdin) >>= (\\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)\n \ngetRemain :: ByteString -> SIO ByteString\ngetRemain b = let bns = C.dropWhile isSpace b in\n if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)\n else return bns\n \ndata HInt\ndata HInt64\ndata HNormal\ndata HString\ndata HList\n \ntype SIO a = StateT ByteString IO a\n \nclass IOInteract a where\n convert :: ByteString -> (a, ByteString)\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n \ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convert = convertp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n \ntype family IOType x where\n IOType Int = HInt\n IOType Int64 = HInt64\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n \nclass IOInteractp flag a where\n convertp :: flag -> ByteString -> (a, ByteString)\n toShowSp :: flag -> a -> String -> String\n \ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)\n toShowSp _ x = shows x\n \ninstance IOInteractp HInt Int where\n convertp _ x = fromMaybe (error \"parse\") $ C.readInt x \n toShowSp _ x = shows x\n \ninstance IOInteractp HInt64 Int64 where\n convertp _ x = let (a, b) = fromMaybe (error \"parse\") $ C.readInteger x in (fromIntegral a, b)\n toShowSp _ x = shows x\n \ninstance IOInteractp HString String where\n convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)\n toShowSp _ x = showString x\n \ninstance (IOInteract a) => IOInteractp HList [a] where\n convertp _ x = let (a, b) = convert x in ([a], b)\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n \nget :: IOInteract a => SIO a\nget = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get\nput :: IOInteract a => a -> SIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> SIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: SIO ()\nflush = lift (hFlush stdout)\n \nmain :: IO ()\nmain = StateT.evalStateT main_ C.empty\n \nmain_ :: SIO ()\n-------------------------------------------- template ------------------------------------------------------\nmain_ = do\n t <- get\n replicateM_ t f1\n\nf1 :: SIO ()\nf1 = do\n (a, b, x, y, n) <- liftM5 (,,,,) get get get get get\n putln $ f2 a b x y n\n\n\nf2 :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64\nf2 a b x y n = let n1 = a - x in let n2 = b - y in\n let v1 = if n > n1 then x * (if n - n1 > n2 then y else (b - (n - n1))) else (a - n) * b in\n let v2 = if n > n2 then y * (if n - n2 > n1 then x else (a - (n - n2))) else a * (b - n) in\n min v1 v2", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b, x, y, n] <- map read . words <$> getLine\n let\n (a1, b1)\n | a - x >= n = (a - n, b)\n | b - y >= n - (a - x) = (x, b - (n - (a - x)))\n | otherwise = (x, y)\n (a2, b2)\n | b - y >= n = (a, b - n)\n | a - x >= (n - (b - y)) = (a - (n - (b - y)), y)\n | otherwise = (x, y)\n ans = min (a1 * b1) (a2 * b2)\n\n putStrLn $ show ans\n"}, {"source_code": "import Control.Monad ( replicateM_ )\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a,b,x,y,n] <- map read . words <$> getLine\n let\n s1 = a - x\n s2 = b - y\n t1 = if (n <= s1) then (a-n)*b\n else if (n <= s1 + s2) then x*(b-(n-s1))\n else x*y\n t2 = if (n <= s2) then a*(b-n)\n else if (n <= s1 + s2) then (a-(n-s2))*y\n else x*y\n print (min t1 t2 :: Integer)\n"}], "negative_code": [], "src_uid": "04753f73af685b4e7339d30d6d47c161"} {"source_code": "import Data.List(nub)\nimport Control.Arrow\n\nsolve = \n (\\x -> case x of {\n (_, y) | y > 26 -> (-1);\n (x, y) -> y - x\n })\n . (length . nub &&& length)\n\nmain = getLine >> getLine >>= (print . solve)\n", "positive_code": [{"source_code": "import Data.List (group, sort)\nmain = getLine >> getLine >>= (\\x -> do\n let cs = (group . sort) x\n print $ if length x > 26 then -1 else length x - length cs)"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n sn <- getLine\n let n = read sn\n s <- getLine\n print $ solve n s\n\nsolve :: Int -> String -> Int\nsolve n s | n > 26 = -1\n | otherwise = n - length (nub s)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Arrow\nimport Data.Char\n\nmain = print =<< (\\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length) . map (pred . B.length ) . B.group . B.sort . B.filter isLower <$> (B.getLine >> B.getLine)\n"}, {"source_code": "{-# OPTIONS_GHC -fno-warn-tabs #-}\nimport Data.List;\nimport System.IO;\nimport Data.Maybe;\n\nsolve :: String -> String -> Int;\nsolve [] a = length a;\nsolve s a\n\t| length s > 26 = -1\n\t| elem (head s) a = solve (tail s) a\n\t| otherwise = solve (tail s) ((head s):a);\n\nmain = do\n\tgetLine;\n\tstr <- getLine;\n\tif(solve str \"\" == (-1))\n\t\tthen print (-1)\n\t\telse print (length str - solve str \"\");"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n s <- getLine\n let ls = length $ group $ sort s\n print $ if n > 26 then -1 else n - ls\n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n if n > 26 then print (-1)\n else getLine >>= print.solve\n\nsolve :: String -> Int\nsolve cs = sum.map (pred.length).group$ sort cs"}, {"source_code": "import Data.List( nub)\nmain = do\n tokens <- return . words =<< getContents\n let n = read $ tokens!!0\n str = tokens!!1\n if n>26 then print (negate 1) else print $ n - length (nub str)"}, {"source_code": "import Data.List\nmain = do \n tmp <- getLine\n str <- getLine\n let n = read tmp::Int\n if n > 26 then \n putStrLn \"-1\"\n else \n putStrLn $ show ((length str) - (length $ nub str))\n "}, {"source_code": "import Data.List\nmain = do\n s <- getLine >> getLine\n let n = length . group . sort $ s\n ls = length s\n print $ if ls <= 26 then ls - n else -1\n\n"}], "negative_code": [{"source_code": "import Data.List (group, sort)\nmain = getLine >>= (\\x -> do\n let cs = (group . sort) x\n print $ if length x > 26 then -1 else length cs - length x)"}, {"source_code": "import Data.List (group, sort)\nmain = getLine >>= (\\x -> do\n let cs = (group . sort) x\n print $ if length x > 26 then -1 else length x - length cs)"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Arrow\n\nmain = print =<< (\\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length) . map (pred . B.length ) . B.group . B.sort <$> (B.getLine >> B.getLine)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Arrow\n\nmain = print =<< (\\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length) . map (pred . B.length ) . B.group <$> (B.getLine >> B.getLine)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Arrow\n\nmain = print =<< (\\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length) . map (pred . B.length ) . B.group <$> B.getLine <* B.getLine \n"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n if n > 26 then print (-1)\n else getLine >>= print.solve\n\nsolve :: String -> Int\nsolve cs = go ['a'..'z'] $ sort cs\n where\n go rest (x:xs)\n | elem x rest = go (delete x rest) xs\n | otherwise = 1 + go (tail rest) xs\n go _ _ = 0"}, {"source_code": "import Data.List(nub)\nimport Control.Arrow\n\nsolve = \n (\\x -> case x of {\n (_, y) | y > 27 -> (-1);\n (x, y) -> y - x\n })\n . (length . nub &&& length)\n\nmain = getLine >> getLine >>= (print . solve)\n"}, {"source_code": "import Data.List\nmain = do\n s <- getLine >> getLine\n let n = length . group . sort $ s\n print $ length s - n\n\n"}], "src_uid": "d9e9c53b391eb44f469cc92fdcf3ea0a"} {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n \n \n \nmain=do\t \n\t[n,a]<-map read. words <$> getLine:: IO [Int]\n\ts<-map (minimum.tail) .map (map read). map words. lines <$> getContents:: IO [Int] \n\tlet t= map snd $ filter (\\z->fst z Bool\ntype Selector a = [a] -> [Nat]\n\ngetVec :: IO Vector\ngetVec = fmap readVec getLine\n\nreadVec :: String -> Vector\nreadVec = map read . words\n\ngetVecN :: Integer -> IO [Vector]\ngetVecN 0 = return []\ngetVecN (n + 1) = do\n vc <- getVec\n vcs <- getVecN n\n return (vc : vcs)\n\nsolve :: Nat -> [Vector] -> [Nat]\nsolve v = countUpFilter (accepts v)\n\ncountUpFilter :: Predicate a -> Selector a\ncountUpFilter = countUpFilter' 1\n\ncountUpFilter' :: Nat -> Predicate a -> Selector a\ncountUpFilter' _ _ [] = []\ncountUpFilter' n p (a : as) = if p a\n then n : countUpFilter' (n + 1) p as\n else countUpFilter' (n + 1) p as\n\naccepts :: Nat -> Predicate Vector\naccepts v = any (< v)\n\noutput :: Vector -> IO ()\noutput vecs = do\n print $ length vecs\n putStrLn $ unwords $ map show vecs\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = output . solve . map (map read . words) . lines =<< getContents\n\noutput :: [Int] -> IO()\noutput (a:ax) = putStrLn ((show a) ++ \"\\n\" ++ (unwords (map show ax)))\n\nsolve :: [[Int]] -> [Int]\nsolve ([n, v]:a) = \n let ans = solve' a 1\n in ((length ans):ans)\n where solve' :: [[Int]] -> Int -> [Int]\n solve' [] _ = []\n solve' ((w:ws):ax) i | v > (minimum ws) = (i:(solve' ax (i + 1)))\n | otherwise = solve' ax (i + 1)\n"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = interact $ unlines . map (unwords . map show) . getAns . map (map read . words) . lines\n\ngetAns :: [[Int]] -> [[Int]]\ngetAns ((_:v:_):xs) = \n\tlet ans = map succ $ findIndices (any ( [[Int]]\ngetArrays = map (map read . words) . lines\n\ngetAns :: [[Int]] -> [[Int]]\ngetAns ((n:v:_):xs) = \n\tlet ans = getSellers v $ zip [1..n] xs\n\tin [[length ans], ans]\n\ngetSellers :: Int -> [(Int, [Int])] -> [Int]\ngetSellers _ [] = []\ngetSellers v (x:xs) = if (any ())\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n [n, v] <- getInts\n xss <- replicateM n $ tail <$> getInts\n\n let r = map snd $ filter (\\(xs, _) -> any (< v) xs) $ zip xss [1..]\n print $ length r\n putStrLn $ unwords $ map show r\n"}, {"source_code": "import Control.Monad\n\nmain = do\n (n:v:_) <- fmap (map read . words) getLine\n items <- forM [1..n] $ \\i -> do is <- fmap (tail . map read . words) getLine; return (i,is)\n let _ = items :: [(Int,[Int])]\n let answer = [ i | (i,is) <- items, any ( C.getLine\n\nmain = do \n [n, v] <- getIntList\n ps <- replicateM n getIntList\n let qs = sol n v ps\n print $ length qs\n putStrLn $ foldr (\\c s -> show c ++ (' ':s)) \"\" $ qs\n\nsol n v ps = [i+1 | i <- [0..n-1], bs!!i]\n where\n bs = map bid ps\n bid (_:ss) = or $ map (< v) ss\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (mapMaybe)\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map fst . mapMaybe B.readInt . B.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> B.getLine\n\nmain = do\n [n, v] <- getInts\n xs <- zip [1..] <$> (replicateM n $ tail <$> getInts)\n let\n can (_,ss) = head (sort ss) < v\n xs' = map fst . filter can $ xs\n in putStrLn $ (show (length xs')) ++ \"\\n\" ++ unwords (map show xs')\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= mapM_ (putStrLn . unwords . map show) . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> [[Int]]\nsolve ([_, v] : kss) = [ [ length is ], is ]\n where is = [ i | (i, _:ss) <- zip [1..] kss, any ( (Int, Int)\nrv str = let xs = map read $ words str in\n (head xs, xs !! 1)\n\nrm:: String -> [Int]\nrm str = map read $ words str\n\npa:: [Int] -> String\npa ans = show (length ans) ++ \"\\n\" ++\n unwords (map show ans)\n\nsolve:: (Int, Int) -> [[Int]] -> [Int]\nsolve valera merchants = map fst $ filter buyable zmerchants where\n budget = snd valera\n zmerchants = zip [1..] $ map tail merchants\n buyable merchant = not $ null buyablegoods where\n goods = snd merchant\n buyablegoods = filter (< budget) goods\n\nmain :: IO ()\nmain = do\n valera <- getLine\n merchants <- replicateM (fst $ rv valera) getLine\n putStrLn $ pa $ solve (rv valera) (map rm merchants)\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n [n,v] <- fmap (map read . words) getLine\n sellers <- forM [1..n] (\\_ -> fmap (tail . map read . words) getLine)\n let solution = solve sellers v\n print $ length solution\n putStrLn . intercalate \" \" . map show $ solution\n\nsolve :: [[Integer]] -> Integer -> [Integer]\nsolve sellers v = [ snd x | x <- pairs, deal (fst x) v ]\n where pairs = zip sellers [1..]\n\ndeal :: [Integer] -> Integer -> Bool\ndeal xs v = any ( putStrLn \"0\\n\"\n xs -> do\n print $ length xs\n putStrLn.unwords.map(show.succ) $ xs\n"}, {"source_code": "main :: IO ()\nmain = interact selesaian\n\nselesaian :: String -> String\nselesaian s = let\n (kep:ekor) = angkaify s\n [_, v] = kep\n beli = dibeli v ekor\n -- Jawaban Disini\n in show (length beli)\n ++ \"\\n\"\n ++ (unwords . map show) beli\n ++ \"\\n\"\n\nangkaify :: String -> [[Int]]\nangkaify = map (map read . words) . lines\n\nlolos :: Int -> [Int] -> Bool\nlolos n = any (< n) . tail\n\nasli :: [Int]\nasli = [1..]\n\ndibeli :: Int -> [[Int]] -> [Int]\ndibeli v = map fst . filter (lolos v . snd) . zip asli\n"}, {"source_code": "main :: IO ()\nmain = interact selesaian\n\nnat :: [Int]\nnat = [1..]\n\nselesaian :: String -> String\nselesaian s = let\n baris = lines s\n (kep:ekor) = angkaify baris\n (_:v:_) = kep\n beli = map snd . filter (\\(x, _) -> lolos v x) $ zip ekor nat\n in show (length beli)\n ++ \"\\n\"\n ++ (unwords . map show) beli\n ++ \"\\n\"\n\nangkaify :: [String] -> [[Int]]\nangkaify = map (map read . words)\n\nlolos :: Int -> [Int] -> Bool\nlolos n xs = any (< n) $ tail xs\n"}, {"source_code": "main :: IO ()\nmain = interact selesaian\n\nselesaian :: String -> String\nselesaian s = let\n baris = lines s\n (kep:ekor) = angkaify baris\n (_:v:_) = kep\n beli = map snd . filter (\\(x, _) -> lolos v x) $ zip ekor [1..]\n in show (length beli)\n ++ \"\\n\"\n ++ (unwords . map show) beli\n ++ \"\\n\"\n\nangkaify :: [String] -> [[Integer]]\nangkaify = map (map read . words)\n\nlolos :: Integer -> [Integer] -> Bool\nlolos n xs = any (< n) $ tail xs\n"}], "negative_code": [{"source_code": "{-# LANGUAGE NPlusKPatterns #-}\n\nmodule Main where\n\nmain :: IO ()\nmain = do\n [n, v] <- getVec\n s <- getVecN n\n output $ solve v $ map tail s\n\ntype Nat = Integer\ntype Vector = [Nat]\ntype Predicate a = a -> Bool\n\ngetVec :: IO Vector\ngetVec = fmap readVec getLine\n\nreadVec :: String -> Vector\nreadVec = map read . words\n\ngetVecN :: Integer -> IO [Vector]\ngetVecN 0 = return []\ngetVecN (n + 1) = do\n vc <- getVec\n vcs <- getVecN n\n return (vc : vcs)\n\nsolve :: Nat -> [Vector] -> [Nat]\nsolve v = countUp . filter (accepts v)\n\ncountUp :: [a] -> [Nat]\ncountUp = countUp' 1\n\ncountUp' :: Nat -> [a] -> [Nat]\ncountUp' _ [] = []\ncountUp' n (_ : as) = n : countUp' (n + 1) as\n\naccepts :: Nat -> Predicate Vector\naccepts v = any (< v)\n\noutput :: Vector -> IO ()\noutput vecs = do\n print $ length vecs\n putStrLn $ unwords $ map show vecs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List (sort)\nimport Data.Maybe (mapMaybe)\n\nreadInts :: B.ByteString -> [Int]\nreadInts = map fst . mapMaybe B.readInt . B.words\n\ngetInts :: IO [Int]\ngetInts = readInts <$> B.getLine\n\nmain = do\n [n, v] <- getInts\n xs <- replicateM n $ do {(k:ss) <- getInts; return (k, ss);}\n let\n can (_,ss) = head (sort ss) < v\n xs' = map fst . filter can $ xs\n in putStrLn $ (show (length xs')) ++ \"\\n\" ++ unwords (map show xs')\n"}, {"source_code": "\nmodule Main where\n\nimport Control.Monad\n\nrv:: String -> (Int, Int)\nrv str = let xs = map read $ words str in\n (head xs, xs !! 1)\n\nrm:: String -> [Int]\nrm str = map read $ words str\n\npa:: [Int] -> String\npa ans = show (length ans) ++ \"\\n\" ++\n unwords (map show ans)\n\nsolve:: (Int, Int) -> [[Int]] -> [Int]\nsolve valera merchants = map fst $ filter buyable zmerchants where\n budget = snd valera\n zmerchants = zip [1..] $ map tail merchants\n buyable merchant = not $ null buyablegoods where\n goods = snd merchant\n buyablegoods = filter (< budget) goods\n\nmain :: IO ()\nmain = do\n valera <- getLine\n merchants <- replicateM (fst $ rv valera) getLine\n print $ pa $ solve (rv valera) (map rm merchants)\n"}, {"source_code": "\nmodule Main where\n\nimport Control.Monad\n\nrv:: String -> (Int, Int)\nrv str = let xs = map read $ words str in\n (head xs, xs !! 1)\n\nrm:: String -> [Int]\nrm str = map read $ words str\n\npa:: [Int] -> String\npa ans = show (length ans) ++ \"\\n\" ++\n unwords (map show ans)\n\nsolve:: (Int, Int) -> [[Int]] -> [Int]\nsolve valera merchants = map fst $ filter buyable zmerchants where\n budget = snd valera\n zmerchants = zip [1..] $ map tail merchants\n buyable merchant = not $ null buyablegoods where\n goods = snd merchant\n buyablegoods = filter (< budget) goods\n\nmain :: IO ()\nmain = do\n valera <- getLine\n merchants <- replicateM (fst $ rv valera) getLine\n print $ solve (rv valera) (map rm merchants)\n"}, {"source_code": "main :: IO ()\nmain = interact selesaian\n\nselesaian :: String -> String\nselesaian s = let\n baris = lines s\n (kep:ekor) = angkaify baris\n (_:v:_) = kep\n beli = map head . filter (lolos v) $ ekor\n in show (length beli)\n ++ \"\\n\"\n ++ (unwords . map show) beli\n ++ \"\\n\"\n\nangkaify :: [String] -> [[Int]]\nangkaify = map (map read . words)\n\nlolos :: Int -> [Int] -> Bool\nlolos n xs = any (< n) $ tail xs\n"}, {"source_code": "main :: IO ()\nmain = interact selesaian\n\nselesaian :: String -> String\nselesaian s = let\n baris = lines s\n (kep:ekor) = angkaify baris\n (_:v:_) = kep\n beli = map head . filter (lolos v) $ ekor\n in show (length beli)\n ++ \"\\n\"\n ++ (unwords . map show) beli\n ++ \"\\n\"\n\nangkaify :: [String] -> [[Integer]]\nangkaify = map (map read . words)\n\nlolos :: Integer -> [Integer] -> Bool\nlolos n xs = any (< n) $ tail xs\n"}], "src_uid": "7804152ee14264afef019c5ad33094f9"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n xs <- (map read.words) <$> getLine\n putStr $ solve n xs\n\ngetOptions :: Int -> [Int] -> [Int]\ngetOptions n xs = nub [m,n-m]\n where\n m = maximum xs\n\nsolve :: Int -> [Int] -> String\nsolve n xs= unlines $ (show k) : c\n where\n a = filter (check xs) (getOptions n xs)\n k = length a\n b = map (\\x -> [x,n-x]) a\n c = map (unwords.map show) b\n\ncheckPerm :: [Int] -> Bool\ncheckPerm perm = and $ zipWith (==) (sort perm) [1..]\n\ncheck :: [Int] -> Int -> Bool\ncheck xs l1 = (checkPerm (take l1 xs)) && (checkPerm (drop l1 xs))\n", "positive_code": [{"source_code": "import Control.Arrow\nimport Data.List (sort)\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords) >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([n]:a:ps) = solve n a ++ process ps\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve n a\n | length ans > 2 = [[0]]\n | and (map (check a) ans) = [length ans] : ans\n | otherwise = [[0]]\n where\n ans = \n map(\\(i, _, _) -> [i, n - i])\n $ filter (\\(i, (mnl, mxl), (mnr, mxr)) -> \n mnl == 1 && mnr == 1 && mxl == i && mxr == n - i)\n $ zip3 [1..]\n (zip (scanl1 min a) (scanl1 max a))\n $ tail (zip (scanr1 min a) (scanr1 max a))\n\ncheck a [l,_] = valid (take l a) && valid (drop l a)\n where\n valid a = and $ zipWith (==) (sort a) [1..]"}], "negative_code": [{"source_code": "import Control.Arrow\nimport Data.List (sort)\n\nmain = interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords) >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([n]:a:ps) = solve n a ++ process ps\n\nsolve :: Int -> [Int] -> [[Int]]\nsolve n a\n | length ans > 2 = [[0]]\n | null ans = [[0]]\n | let l = head (last ans) in sort (take l a) /= [1..l] = [[0]]\n | otherwise = [length ans] : ans\n where\n ans = \n map(\\(i, _, _) -> [i, n - i])\n $ filter (\\(i, (mnl, mxl), (mnr, mxr)) -> \n mnl == 1 && mnr == 1 && mxl == i && mxr == n - i)\n $ zip3 [1..]\n (zip (scanl1 min a) (scanl1 max a))\n $ tail (zip (scanr1 min a) (scanr1 max a))\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n xs <- (map read.words) <$> getLine\n putStr $ solve n xs\n\ngetOptions :: Int -> [Int] -> [Int]\ngetOptions n xs = [m,n-m]\n where\n m = maximum xs\n\nsolve :: Int -> [Int] -> String\nsolve n xs= unlines $ (show k) : c\n where\n a = filter (check xs) (getOptions n xs)\n k = length a\n b = map (\\x -> [x,n-x]) a\n c = map (unwords.map show) b\n\ncheckPerm :: [Int] -> Bool\ncheckPerm perm = and $ zipWith (==) (sort perm) [1..]\n\ncheck :: [Int] -> Int -> Bool\ncheck xs l1 = (checkPerm (take l1 xs)) && (checkPerm (drop l1 xs))\n"}], "src_uid": "5f0f79e39aaf4abc8c7414990d1f8be1"} {"source_code": "-- 2019-11-24 05:02:38.537124654 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))", "positive_code": [{"source_code": "-- 2019-11-24 19:47:40.593640185 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-20 21:17:08.568559806 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051817 -> iF ((n_6989586621679051817 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:04:24.247100453 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-14 21:34:13.653101282 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679121131 -> iF ((n_6989586621679121131 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:25:35.391704187 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:45:57.671564784 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:48:17.054512803 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:23:34.78482098 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:10:01.201803523 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-20 21:04:10.502421734 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050267 -> iF ((n_6989586621679050267 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "main = interact $ merge . flip take (cycle [\"hate\",\"love\"]) . read\nmerge [f] = \"I \" ++ f ++ \" it\"\nmerge (f:fs) = \"I \" ++ f ++ \" that \" ++ merge fs\n"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\n\nglwr = fmap (map read . words) getLine\n\nmain = do\n hSetBuffering stdout NoBuffering\n solve\n\nsolve :: IO ()\nsolve = do\n n:_ <- glwr\n\n putStrLn $ hulk n\n\nhulk :: Int -> String\nhulk n = [1..n] >>= ko n\n\nko n i\n = \"I \"\n ++ [\"love \", \"hate \"] !! fromEnum (odd i)\n ++ [\"that \", \"it \"] !! fromEnum (n == i)\n"}, {"source_code": "main = getLine >>= putStrLn . solve 0 . read\n\nsolve 0 n = \"I hate \" ++ solve 1 n\nsolve _ 1 = \"it\"\nsolve m n = if m `mod` 2 == 0\n then \"that I hate \" ++ solve (m + 1) (n - 1)\n else \"that I love \" ++ solve (m + 1) (n - 1)"}, {"source_code": "module Main where\n import Data.List\n\n hateLove :: Integer -> String\n hateLove n\n | n `mod` 2 == 0 = \"hate\"\n | otherwise = \"love\"\n\n partialSolver :: Integer -> Integer -> [String] -> [String]\n partialSolver n i acc\n | n == i = acc\n | otherwise = partialSolver n (i + 1) $ (hateLove i):acc\n\n addIt :: String -> String\n addIt x = \"I \" ++ x ++ \" it\"\n\n addThat :: String -> String\n addThat x = \"I \" ++ x ++ \" that\"\n\n stringify :: [String] -> [String]\n stringify xs =\n let thatTail = addThat `map` (tail xs)\n itHead = addIt $ head xs\n in reverse $ itHead : thatTail\n\n solutionSolver :: Integer -> String\n solutionSolver n = intercalate \" \" $ stringify $ partialSolver n 0 []\n\n main :: IO ()\n main = do\n n <- getLine\n let i = read n :: Integer\n putStrLn $ solutionSolver i\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/705/A\n\nhate :: Int -> String\nhate 1 = \"I hate it\"\nhate n = \"I hate that \" ++ love (n-1)\n\nlove :: Int -> String\nlove 1 = \"I love it\"\nlove n = \"I love that \" ++ hate (n-1)\n\nmain :: IO ()\nmain = readLn >>= putStrLn . hate\n"}, {"source_code": "printer :: Int -> Int -> String\nprinter x y = \n if x == 1 then if y == 0 then \"I hate it\" else \"I love it\"\n else if y == 0 then \"I hate that \" ++ printer (x - 1) 1\n else \"I love that \" ++ printer (x - 1) 0\n\n\nmain = do\n xx <- getLine\n let x = read xx :: Int\n putStrLn (printer x 0)\n\n"}, {"source_code": "main = do\n n <- readLn\n let talk 0 _ = \" it\"\n\ttalk n love\n\t | love\t= \" that I love\" ++ talk (n-1) False\n\t | otherwise\t= \" that I hate\" ++ talk (n-1) True\n putStrLn $ \"I hate\"++talk (n-1) True\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= \\n -> putStrLn $ addHateOrLove 1 n \"\"\n\naddHateOrLove :: Int -> Int -> String -> String\naddHateOrLove _ 0 _ = \"it\"\naddHateOrLove c n xs\n | odd c = \"I hate \" ++ xs ++ (addHateOrLove (c+1) (n-1) xs)\n | otherwise = \"I love \" ++ xs ++ (addHateOrLove (c+1) (n-1) xs)\n where\n xs = if n == 1 then \"\" else \"that \"\n"}, {"source_code": "solve n = take (n+1) $ iterate (\\x -> if (snd x) == n then (if (snd x) `mod` 2 == 1 then (\"I hate it\", (snd x)+1) else (\"I love it\", (snd x)+1))\n else (if (snd x) `mod` 2 == 1 then (\"I hate that \", (snd x)+1) else (\"I love that \", (snd x)+1))\n ) (\"I hate it \", 1)\nmain = do\n line <- getLine\n let n = read line::Int in putStrLn $ concat $ map (fst) $ drop 1 $ solve n "}, {"source_code": "main = do\n n <- getLine\n mapM_ putStr $ (take.read $ n) $ iterate (\\str -> if str == \"that I love \" then \"that I hate \" else \"that I love \") \"I hate \"\n putStr \"it\""}, {"source_code": "import Data.List\nimport System.IO\n\nparseLine :: IO [String]\nparseLine = fmap words getLine\n\nparseInt :: IO [Int]\nparseInt = fmap (map read . words) getLine\n\nparseDouble :: IO [Double]\nparseDouble = fmap (map read . words) getLine\n\nsolve :: Int -> Bool -> String\nsolve n isHate = if (n == 1) then (if isHate then \"I hate it\" else \"I love it\")\n else (if isHate then \"I hate that \" else \"I love that \") ++ (solve (n - 1) (not isHate))\n \nmain :: IO ()\nmain = do\n [n] <- parseInt\n \n putStrLn $ solve n True\n"}, {"source_code": "solve :: Int -> String\nsolve x = solve' 1\n where\n start a = if a `mod` 2 == 0 then \"I love \" else \"I hate \"\n end a = if a == x then \"it \" else \"that \"\n solve' a = if a > x then \"\"\n else start a ++ end a ++ solve' (a + 1)\n\nmain :: IO ()\nmain = putStrLn =<< solve . (read :: String -> Int) <$> getLine"}, {"source_code": "main = do\n ln <- getLine\n x <- return $ (read ln :: Int) - 1\n putStrLn $ \"I hate \" ++ concat [ \"that I \" ++ (if u `mod` 2 == 0 then \"hate \" else \"love \") | u <- [1..x] ] ++ \"it\""}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype I = Int\n\nmain :: IO ()\nmain = do\n n <- readi <$> getLine\n putStrLn $ solve n\n\nsolve :: Int -> String\nsolve n = intercalate \" that \" (map (\\x -> if odd x then \"I hate\" else \"I love\") [1..n]) ++ \" it\"\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\nreadi :: String -> I\nreadi = read\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] = (x, y, z)\n"}, {"source_code": "main = do\n n <- getLine\n putStrLn . g . stoi . words $ n\n\nstoi :: [[Char]] -> [Int]\nstoi [] = []\nstoi (n:ns) = (read n::Int) : stoi ns\n\ng :: [Int] -> [Char]\ng (x:_)\n | x >= 1 = \"I hate\" ++ foo (x-1)\n\nbar :: Int -> [Char]\nbar n\n | n == 0 = \" it\"\n | otherwise = \" that I hate\" ++ foo (n-1)\n\nfoo :: Int -> [Char]\nfoo n \n | n == 0 = \" it\"\n | otherwise = \" that I love\" ++ bar (n-1)"}, {"source_code": "solve :: Bool -> Int -> String\nsolve True 1 = \"I hate it\"\nsolve False 1 = \"I love it\"\nsolve True n = \"I hate that \" ++ solve False (n - 1)\nsolve False n = \"I love that \" ++ solve True (n - 1)\nmain = putStrLn . solve True . read =<< getLine"}, {"source_code": "--ghc 7.10\n\ndata Feel = Love | Hate deriving (Eq)\n\nlistFeeling :: Int -> Feel -> [String]\nlistFeeling 1 Love = [\"I love it\"]\nlistFeeling 1 Hate = [\"I hate it\"]\nlistFeeling n Love = \"I love that \":listFeeling (n-1) Hate\nlistFeeling n Hate = \"I hate that \":listFeeling (n-1) Love\n\nhulkFeeling :: Int -> String\nhulkFeeling n = concat $ listFeeling n Hate\n\nmain = do\n n <- getLine\n putStrLn . hulkFeeling . read $ n"}, {"source_code": "-- Hulk -> CodeForces\n\nphrases :: Int -> [String]\nphrases x = if x`mod`2==0\n then [\"hate \", \"love \"]\n else [\"love \", \"hate \"]\n\nhulkSpeak :: [String] -> Int -> String\nhulkSpeak ps 0 = \"it\"\nhulkSpeak ps x = \"I \" ++ phrase ++ hulkSpeak ps (x-1)\n where\n phrase =\n if x > 1\n then ps !! (x`mod`2) ++ \"that \"\n else ps !! (x`mod`2)\n\nmain = do\n x <- readLn :: IO Int\n let ps = phrases x\n putStrLn $ hulkSpeak ps x"}, {"source_code": "phrases :: [String]\nphrases = [\"hate \", \"love \"]\n\nhulkSpeak :: Int -> Int -> String\nhulkSpeak x y =\n if x == y\n then \"it\"\n else \"I \" ++ phrase ++ hulkSpeak (x+1) y\n where\n phrase = if x /= (y-1)\n then phrases !! (x`mod`2) ++ \"that \"\n else phrases !! (x`mod`2)\n\nmain = do\n x <- readLn :: IO Int\n putStrLn $ hulkSpeak 0 x"}, {"source_code": "import Data.List\n\nprocess :: Int -> String\nprocess source \n | mod source 2 == 1 = \"I hate\"\n | mod source 2 == 0 = \"I love\"\n\nmain :: IO ()\nmain = do\n text <- getLine\n let count = read text\n let result = intercalate \" that \" $ map process [1..count]\n putStrLn (result ++ \" it\")"}, {"source_code": "import Data.List (intersperse)\n\nfeelings :: Int -> String\nfeelings n = (concat\n $ intersperse \" that \"\n $ take n\n $ map (\\i -> if i `mod` 2 == 0 then \"I love\" else \"I hate\") [1..]\n ) ++ \" it\"\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn $ feelings n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nmain= do\n\t\tc<- read <$> getLine::IO Int\n\t \tlet d = intercalate \" that \" $ take c $ cycle [\"I hate\" , \"I love\"]\n \tputStrLn $ d++ \" it\"\n"}, {"source_code": "main = do\n m <- readLn\n putStrLn $ hulk m\nhulk :: Int -> String\nhulk m = (drop 5 (foldl (\\x y -> x ++ \"that \" ++ y) [] took)) ++ \"it\"\n where took = take m (cycle [\"I hate \", \"I love \"])"}, {"source_code": "import Data.List\nmain = interact $ express . read\n\nexpress n = (intercalate \" that \" feelings) ++ \" it\"\n where feelings = fmap (\\i -> if odd i then \"I hate\" else \"I love\") [1..n]"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n interact $ express . read\n\nexpress :: Int -> String\nexpress n = (intercalate \" that \" feelings) ++ \" it\"\n where feelings = fmap (\\i -> if odd i then \"I hate\" else \"I love\") [1..n]"}, {"source_code": "import Data.List\nmain = interact $ express . read\nexpress n = intercalate \" that \" (take n $ cycle [\"I hate\", \"I love\"]) ++ \" it\"\n"}, {"source_code": "import Data.List\n\nsolve n = intercalate \" that \" (take n $ concat (replicate n ms)) ++ \" it\"\n where ms = [\"I hate\", \"I love\"]\n\nmain = do\n n <- readLn :: IO Int\n putStrLn $ solve n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.STRef\nimport GHC.Float.RealFracMethods\nmain :: IO ()\nmain = do\n n <- getLine\n mapM_ (\\x -> putStr$x++\" \")$mood (read n) False\n putStrLn \"\"\n\nmood :: Int -> Bool -> [String]\nmood 1 x = [\"I\", if x then \"love\" else \"hate\", \"it\"]\nmood a x = [\"I\", if x then \"love\" else \"hate\", \"that\"]++ (mood (a-1)$not x)\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\n\ngetDouble = read `fmap` getLine :: IO Double\ngetDoubles = map fromIntegral `fmap` getInts :: IO [Double]\n\nlove = \"that I love \"\nhate = \"that I hate \"\n\nmain = do\n n <- getInt\n if n == 1 then putStrLn \"I hate it\"\n else putStrLn (\"I hate \" ++ build n ++ \"it\")\n\nbuild 1 = \"\"\nbuild n = build (n-1) ++ (if n `mod` 2 == 0 then love else hate)"}, {"source_code": "f 1 True = [\"I love it\"]\nf 1 False = [\"I hate it\"]\nf n True = \"I love that\":(f (n-1) False)\nf n False = \"I hate that\":(f (n-1) True)\nfn x = unwords (f x False)\nmain = do\n n <- getLine\n putStrLn (fn (read n))"}, {"source_code": "main = do\n n <- getLine\n let f (x, y) = if (x > 0) then (if y then \"I hate\" else \"I love\") ++ (if (x > 1) then \" that \" else \"\") ++ f(x - 1, not y) else \" it\"\n putStrLn( f(read $ n, True) );"}, {"source_code": "import Data.List\n\nmain = do\n n <- getLine\n let emotions = [if odd(i) then hate else love | i <- [1..(read n :: Int)]]\n putStrLn $ intercalate \"that \" emotions ++ \"it\"\n\n\nhate :: String\nhate = \"I hate \"\n\nlove :: String\nlove = \"I love \""}, {"source_code": "go :: (Integral x) => x -> String\n\ngo n\n | n == 1 = \"I hate\"\n | (n `mod` 2) == 1 = (go (n-1)) ++ \" that I hate\"\n | otherwise = (go (n-1)) ++ \" that I love\"\n\n\nmain = do\n line <- getLine\n let n = read line :: Int\n putStrLn $ go n ++ \" it\"\n"}, {"source_code": "main :: IO ()\nmain = do\n layer <- readLn\n putStrLn ( hulk layer )\n\nhulk :: Int -> String\nhulk x = (hulkLayer x) ++ \" it\"\n\nhulkLayer :: Int -> String\nhulkLayer 1 = \"I hate\"\nhulkLayer x =\n (hulkLayer (x-1)) ++ \" that I \" ++ (feel x)\n\nfeel :: Int -> String\nfeel x = if odd x then \"hate\" else \"love\"\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n\n putStrLn $ unwords $ zipWith (++) (concat $ repeat [\"I hate\", \"I love\"]) (replicate (n-1) \" that\" ++ [\" it\"])\n"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n putStrLn $ solve \"hate\" n\n\nsolve :: String -> Int -> String\nsolve s 1 = \"I \" ++ s ++ \" it\"\nsolve s n = \"I \" ++ s ++ \" that \" ++ solve (opp s) (n - 1)\n\nopp :: String -> String\nopp \"hate\" = \"love\"\nopp _ = \"hate\"\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\n\nmain = do { x <- getLine; (read >>> solve \"I hate \" 1 >>> putStrLn) x }\n\n\nsolve :: String -> Int -> Int -> String\nsolve s x y | x == y = s ++ \"it\"\n | mod x 2 == 0 = solve (s ++ \"that I hate \") (x+1) y\n | mod x 2 == 1 = solve (s ++ \"that I love \") (x+1) y "}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.List as L\n\nsolve :: Int -> String\nsolve t = (L.intercalate \" \" seg) ++ \" it\"\n where\n seg = foldl apd [\"I hate\"] [2..t] \n apd l n\n | even n = l ++ [\"that I love\"]\n | otherwise = l ++ [\"that I hate\"]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn (solve n) "}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Function\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ unwords . solve.read.head. lines\nsolve :: Int->[String]\nsolve 1= [\"I hate it\"]\nsolve x = (take (x-1) $ cycle [\"I hate that\", \"I love that\"]) ++ f where\n f=if x `mod` 2 /= 0 then [\"I hate it\"] else [\"I love it\"]"}, {"source_code": "f n | n == 1 = \"I hate it\"\n | n == 2 = \"I hate that I love it\"\n | otherwise = \"I hate that I love that \" ++ f (n - 2)\n\nmain = getLine >>= (putStrLn . f . read . head . words)"}, {"source_code": "import Control.Monad\n\nmain = getInt >>= putStrLn . parse\n\ngetInt::IO Int\ngetInt = liftM read getLine\n\nparse::Int -> String\nparse n = start ++ \" it\"\n where start = foldl concat \"I hate\" [2..n]\n concat str i\n | i `mod` 2 == 0 = str ++ \" that I love\"\n | otherwise = str ++ \" that I hate\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Prelude\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn . (++ \" it\") . intercalate \" that \" . take n . cycle $ [\"I hate\", \"I love\"]"}, {"source_code": "hate :: Int -> String\nlove :: Int -> String\n\nhate 1 = \"I hate it\"\nhate n = \"I hate that \" ++ love (n - 1)\nlove 1 = \"I love it\"\nlove n = \"I love that \" ++ hate (n - 1)\n\nmain :: IO()\nmain = readLn >>= putStrLn . hate\n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\n\nmain=do\n n<- read <$> getLine::IO Int\n let x= intercalate \"that\" $ take n $ cycle [\" I hate \",\" I love \"]\n putStrLn $ tail $ x ++ \"it\"\n"}, {"source_code": "-- 2019-11-24 20:43:35.642224548 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:06:47.459910813 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> iF (((== 0) . (`mod` 2)) (b - a)) ((\"I hate that \" ++) c) ((\"I love that \" ++) c))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}], "negative_code": [{"source_code": "f 1 True = [\"I love it\"]\nf 1 False = [\"I Hate it\"]\nf n True = \"I love that\":(f (n-1) False)\nf n False = \"I hate that\":(f (n-1) True)\nfn x = unwords (f x False)\nmain = do\n n <- getLine\n putStrLn (fn (read n))\n"}, {"source_code": "main = do\n n <- getLine\n let f (x, y) = if (x > 0) then (if y then \"I hate\" else \"I love\") ++ (if (x > 1) then \" that \" else \"\") ++ f(x - 1, not y) else \" it\"\n putStrLn( show $ f(read $ n, True) );"}, {"source_code": "main :: IO ()\nmain = do\n layer <- readLn\n putStrLn ( hulk layer )\n\nhulk :: Int -> String\nhulk 1 = \"I hate it\"\nhulk x = \"I \" ++ (if odd x then \"hate\" else \"love\") ++ \" that \" ++ ( hulk (x-1) )\n\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n\n putStrLn $ unwords $ take n $ concat $ repeat [\"I hate it\", \"I love it\"]\n"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n putStrLn $ solve n\n\nsolve :: Int -> String\nsolve 1 = \"I hate it\"\nsolve n\n | odd n = \"I hate that \" ++ solve (n - 1)\n | otherwise = \"I love that \" ++ solve (n - 1)\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\n\nmain = interact $\n lines >>> map (words >>> head >>> read >>> solve \"I hate \" 1 >>> show) >>> unlines\n\n\nsolve :: String -> Int -> Int -> String\nsolve s x y | x == y = s ++ \"it\"\n | mod x 2 == 0 = solve (s ++ \"that I hate \") (x+1) y\n | mod x 2 == 1 = solve (s ++ \"that I love \") (x+1) y"}, {"source_code": "import Control.Applicative ((<$>))\nimport qualified Data.List as L\n\nsolve :: Int -> String\nsolve t = (L.intercalate \" \" seg) ++ \" it\"\n where\n seg = foldl apd [\"I hate\"] [2..t] \n apd l n\n | even n = l ++ [\"that I love\"]\n | otherwise = l ++ [\"that I hate\"]\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n putStrLn . show $ solve n "}, {"source_code": "f n | n == 1 = \"I hate it\"\n | n == 2 = \"I hate that I love it\"\n | otherwise = \"I hate that I love that\" ++ f (n - 2)\n\nmain = getLine >>= (putStrLn . f . read . head . words)"}, {"source_code": "import Control.Monad\n\nmain = getInt >>= putStrLn . parse\n\ngetInt::IO Int\ngetInt = liftM read getLine\n\nparse::Int -> String\nparse n = start ++ \" it\"\n where start = foldr concat \"I hate\" [2..n]\n concat i str\n | n `mod` i == 0 = str ++ \" that I love\"\n | otherwise = str ++ \" that I hate\""}, {"source_code": "-- 2019-11-24 05:08:28.558047825 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:05:04.834635846 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-20 21:10:01.434033762 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051817 -> iF ((n_6989586621679051817 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051817 -> iF ((n_6989586621679051817 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:02:02.916891858 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-20 21:00:19.524922601 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050267 -> iF ((n_6989586621679050267 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679050267 -> iF ((n_6989586621679050267 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 21:05:42.017908118 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:56:37.495202571 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051926 -> iF ((n_6989586621679051926 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051926 -> iF ((n_6989586621679051926 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:46:45.870399585 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-20 21:21:13.324129861 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) \"I hate it\" (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) \"I love it\" ((\"I love that \" ++) (iF (((== 0) . (`mod` 2)) b) c \"I hate it\"))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:14:36.021897447 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) \"I hate it\" (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) \"I love it\" ((\"I love that \" ++) (iF (((== 0) . (`mod` 2)) b) c \"I hate it\"))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-20 21:14:27.575368867 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051817 -> iF ((n_6989586621679051817 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051817 -> iF ((n_6989586621679051817 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:30:29.193048129 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:04:12.95242109 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051927 -> iF ((n_6989586621679051927 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051927 -> iF ((n_6989586621679051927 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-14 22:05:11.902524768 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) \"I hate it\" (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) \"I love it\" ((\"I love that \" ++) (iF (((== 0) . (`mod` 2)) b) c \"I hate it\"))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:59:56.006024558 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051926 -> iF ((n_6989586621679051926 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051926 -> iF ((n_6989586621679051926 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:24:17.263832218 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:45:08.962334117 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:12:41.454933138 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051904 -> iF ((n_6989586621679051904 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051904 -> iF ((n_6989586621679051904 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-14 21:46:04.815094948 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) \"I hate it\" (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) \"I love it\" ((\"I love that \" ++) (iF (((== 0) . (`mod` 2)) b) c \"I hate it\"))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:22:07.985374006 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 05:03:33.935721791 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679050168 -> iF ((n_6989586621679050168 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:17:12.017523452 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051904 -> iF ((n_6989586621679051904 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051904 -> iF ((n_6989586621679051904 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:44:21.332259381 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:43:28.27093953 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:08:12.229883881 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051947 -> iF ((n_6989586621679051947 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051947 -> iF ((n_6989586621679051947 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-14 21:32:41.179068145 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679121131 -> iF ((n_6989586621679121131 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679121131 -> iF ((n_6989586621679121131 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:40:14.555540688 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:27:10.184609196 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:33:27.153758054 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (iF (((== 0) . (`mod` 2)) b) c ((\"I love that \" ++) ((\\n_6989586621679051903 -> iF ((n_6989586621679051903 `mod` 2) == 0) \"I love it\" \"I hate it\") b))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 19:49:16.331063502 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679050238 -> iF ((n_6989586621679050238 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- 2019-11-24 20:53:48.546217396 UTC\nimport Data.Maybe\nimport Control.Monad\nimport Text.Read\nnat_para :: Integral i => i -> a -> (i -> a -> a) -> a\nnat_para i x f = np (abs i)\n where np 0 = x\n np i = let i' = i - 1\n in f i' (np i')\nhd :: [a] -> a\nhd ([]) = error \"empty head\"\nhd (a : as) = a\ntl = drop 1\nnat_cata :: Integral i => i -> a -> (a -> a) -> a\nnat_cata i x f = nc (abs i)\n where nc 0 = x\n nc i = f (nc (i - 1))\niF :: Bool -> a -> a -> a\niF (True) t f = t\niF (False) t f = f\nlist_para :: [b] -> a -> (b -> [b] -> a -> a) -> a\nlist_para ([]) x f = x\nlist_para (y : ys) x f = f y ys (list_para ys x f)\nmagiciF :: Bool -> String\nmagiciF b = if b then \"EASY\" else \"HARD\"\nuncurry' = id\nparser :: String -> Int\nparser = read\nsolve = \\a -> nat_para (flip (-) 1 a) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a) (\\b c -> (\"I hate that \" ++) (nat_para b c (\\_ _ -> (\"I love that \" ++) ((\\n_6989586621679051752 -> iF ((n_6989586621679051752 `mod` 2) == 0) \"I love it\" \"I hate it\") a))))\nmain = getContents >>= (\\c -> putStrLn (uncurry' solve (parser c)))"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/705/A\n\nhate :: Int -> String\nhate 1 = \"I hate it\"\nhate n = \"I hate that \" ++ love (n-1)\n\nlove :: Int -> String\nlove 1 = \"I love it\"\nlove n = \"I love it that \" ++ hate (n-1)\n\nmain :: IO ()\nmain = readLn >>= putStrLn . hate\n"}, {"source_code": "\nmain = do\n x <- getLine\n if x == \"1\" then putStrLn \"I hate it\"\n else if x == \"2\" then putStrLn \"I hate that I love it\"\n else putStrLn \"I hate that I love that I hate it\"\n\n"}, {"source_code": "main = do\n n <- getLine\n mapM_ putStr $ (take.read $ n) $ iterate (\\str -> if str == \"I love that \" then \"I hate that \" else \"I love that \") \"I hate that \""}, {"source_code": "main = do\n n <- getLine\n mapM_ putStr $ (take.read $ n) $ iterate (\\str -> if str == \"I hate \" then \"that I love \" else \"that I hate \") \"I hate \"\n putStr \"it\""}, {"source_code": "import Data.List\nimport System.IO\n\nparseLine :: IO [String]\nparseLine = fmap words getLine\n\nparseInt :: IO [Int]\nparseInt = fmap (map read . words) getLine\n\nparseDouble :: IO [Double]\nparseDouble = fmap (map read . words) getLine\n\nsolve :: Int -> Bool -> String\nsolve n isHate = if (n == 1) then (if isHate then \"I hate it\" else \"I love it\")\n else (if isHate then \"I hate that \" else \"I love that\") ++ (solve (n - 1) (not isHate))\n \nmain :: IO ()\nmain = do\n [n] <- parseInt\n \n putStrLn $ solve n True\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\ntype I = Int\n\nmain :: IO ()\nmain = do\n n <- readi <$> getLine\n putStrLn $ solve n\n\nsolve :: Int -> String\nsolve n = intercalate \" that \" (map (\\x -> if odd x then \"I hate\" else \"I love\") $ reverse [1..n]) ++ \" it\"\n\n-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n\nreadi :: String -> I\nreadi = read\n\ntoTuple :: [a] -> (a, a)\ntoTuple [x, y] = (x, y)\n\ntoTriple :: [a] -> (a, a, a)\ntoTriple [x, y, z] = (x, y, z)\n"}, {"source_code": "phrases :: [String]\nphrases = [\"love\", \"hate\"]\n\nhulkSpeak :: Int -> String\nhulkSpeak 0 = \" it\"\nhulkSpeak x = \" that I \" ++ (phrases !! (x`mod`2)) ++ hulkSpeak (x-1)\n\nmain = do\n x <- readLn :: IO Int\n putStrLn (\"I hate\" ++ hulkSpeak (x-1))"}, {"source_code": "phrases :: [String]\nphrases = [\"hate \", \"love \"]\n\nhulkSpeak :: Int -> String\nhulkSpeak 0 = \"it\"\nhulkSpeak x = \"I \" ++ phrase ++ hulkSpeak (x-1)\n where\n phrase = if x > 1\n then phrases !! (x`mod`2) ++ \"that \"\n else phrases !! (x`mod`2)\n\nmain = do\n x <- readLn :: IO Int\n putStrLn $ hulkSpeak x"}, {"source_code": "solve :: Int -> String\nsolve 1 = \"I hate it\"\nsolve x\n | even x = \"I love that \" ++ solve (x - 1)\n | otherwise = \"I hate that \" ++ solve (x - 1)\n\nmain :: IO ()\nmain = putStrLn =<< solve . (read :: String -> Int) <$> getLine"}, {"source_code": "process :: Int -> String\nprocess source \n | mod source 2 == 1 = \"I hate it\"\n | mod source 2 == 0 = \"I love it\"\n\nmain :: IO ()\nmain = do\n text <- getLine\n let count = read text\n let result = unwords $ map process [1..count]\n putStrLn (show result)"}, {"source_code": "process :: Int -> String\nprocess source \n | mod source 2 == 1 = \"I hate it\"\n | mod source 2 == 0 = \"I love it\"\n\nmain :: IO ()\nmain = do\n text <- getLine\n let count = read text\n let result = unwords $ map process [1..count]\n putStrLn result"}, {"source_code": "import Data.List\nmain :: IO ()\nmain = do\n interact $ show . express . read\n\nexpress :: Int -> String\nexpress n = (intercalate \" that \" feelings) ++ \" it\"\n where feelings = fmap (\\i -> if odd i then \"I hate\" else \"I love\") [1..n]"}], "src_uid": "7f2441cfb32d105607e63020bed0e145"} {"source_code": "import Data.List\n\n-- some readers\nreadInt :: String -> Int\nreadInt = read\n\nreadLL :: String -> [Int]\nreadLL = (map read) . words\n\n-- main function\nmain = do\n n <- getLine >>= return . readInt\n xs <- getLine >>= return . readLL\n printRes $ solve n xs where\n \n solve n xs = case findIndex (\\(x, y) -> y>x) pairs of\n Nothing -> [0, 0]\n Just b -> case findIndex (\\(x, y) -> y [0, 0]\n Just e -> if (take b xs ++ reverse (drop b (take (n-e) xs)) ++ drop (n-e) xs) == [1..n]\n then [(b+1), (n-e)]\n else [0, 0]\n where\n pairs = zip [1..n] xs\n printRes [a, b] = putStrLn $ show a ++ \" \" ++ show b\n", "positive_code": [{"source_code": "main = do interact (unwords . map show . gao . map read . tail . words)\n\ngao a = if not (null b) && b == r c then [head c, last c] else [0, 0] where\n\tr = reverse\n\tf = r . dropWhile (uncurry (==))\n\t(b, c) = unzip $ f . f $ zip a [1 ..]\n"}, {"source_code": "prob :: [Int] -> Int -> Maybe (Int, Int)\nprob [] _ = Nothing\nprob (x:xs) n\n\t| x == n = prob xs $ n+1\n\t| x < n = Nothing\n\t| otherwise = Just (n, x)\n\nmaybe_reverse :: [Int] -> Maybe (Int, Int) -> [Int]\nmaybe_reverse xs Nothing = []\nmaybe_reverse xs (Just (x, y)) =\n\ttake (x-1) xs ++ (reverse $ take (y-x+1) $ drop (x-1) xs) ++ (drop y xs)\n\nmaybe_puts :: Maybe String -> IO ()\nmaybe_puts Nothing = return ()\nmaybe_puts (Just str) = putStrLn str\n\nmain = do\n\tn <- getLine >>= return . read :: IO Int\n\tlst <- getLine >>= return . (map read) . words :: IO [Int]\n\tif maybe_reverse lst (prob lst 1) == [1..n]\n\t\tthen maybe_puts $ prob lst 1 >>= \\(x, y) -> Just $ (show x) ++ \" \" ++ (show y)\n\t\telse putStrLn \"0 0\"\n"}, {"source_code": "import Control.Applicative\nimport Text.Printf\nimport Data.Maybe\nimport Data.List\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve arr | (not$ null ix) && (and$ zipWith (<) arr' (tail arr')) = Just(l+1, r+1)\n | otherwise = Nothing\n where\n gs = zipWith (<) arr (tail arr)\n ix = elemIndices False gs\n l = head ix\n r = (last ix)+1\n arr' = (take l arr) ++\n (reverse$ take (r-l+1) $ drop l arr) ++\n (drop (r+1) arr)\n\nmain = do\n getLine\n arr <- (map read . words) <$> getLine\n case solve arr of\n Just (l, r) -> putStrLn (printf \"%d %d\" l r)\n Nothing -> putStrLn \"0 0\"\n"}, {"source_code": "\nimport Maybe (fromMaybe)\nimport Monad (liftM)\n\nsolve :: [(Int, Int)] -> Maybe (Int, Int)\nsolve [] = Nothing\nsolve ((n, x):xs)\n | n == x = solve xs\n | otherwise = solve2 (n,x) xs\n where\n solve2 _ [] = Nothing\n solve2 (n,x) ((m,y):ys)\n | n + x /= m + y = Nothing\n | y == n = solve3 (n, m) ys\n | otherwise = solve2 (n, x) ys\n solve3 (n, m) [] = Just (n, m)\n solve3 (n, m) ((k, z):zs)\n | k == z = solve3 (n, m) zs\n | otherwise = Nothing\n\nmain :: IO ()\nmain = do\n getLine\n xs <- liftM (map read . words) getLine\n let (a, b) = fromMaybe (0, 0) $ solve $ zip [1..] xs\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "solve (n:xs) = (show a) ++ \" \" ++ (show b)\n where (a, b) = if origin == reverse rev && (not $ null origin) then\n (head origin, last origin)\n else\n (0, 0)\n (origin, rev) = unzip $ filter (\\(x, y) -> x /= y) $ zip [1..n] xs\n\nmain = interact (solve.map read.words)"}, {"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.Functor\n\nmain = interact q\n\nq = func . tail . map read . words\n\nfunc::[Int]->String\nfunc x = case solve x of\n Just (a, b) -> (show a) ++ \" \" ++ (show b)\n Nothing-> \"Error occurred\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nisVailed::String->Bool\nisVailed \"\" = False\nisVailed \"0\" = True\nisVailed ('0':_) = False\nisVailed _ = True\n\nsolve::[Int]->Maybe (Int, Int)\nsolve [] = Just (0, 0)\nsolve a = Just $ s' 0 a\n\ns'::Int->[Int]->(Int, Int)\ns' _ [] = (0, 0)\ns' n (x:xs) | n + 1 == x = s' x xs\n | otherwise = if left == -1 then (0,0)\n else (left, x)\n where\n left = s'' x xs\n\ns''::Int->[Int]->Int\ns'' n [] = n\ns'' n (x:xs) | n - 1 == x = s'' x xs\n | sorted (x:xs) = n\n | otherwise = -1\n\nsorted::[Int]->Bool\nsorted [] = True\nsorted (a:[]) = True\nsorted (a:b:xs) | a + 1 == b = sorted (b:xs)\n | otherwise = False"}, {"source_code": "main = do getLine\n a <- fmap (map read . words) getLine\n let n = length a\n lst = [i | i<-[0..n-1], a!!i /= i+1]\n (i,j) = (head lst, last lst)\n swap i j a = take i a ++ reverse(take (j-i+1) (drop i a)) ++ drop (j+1) a\n if null lst\n then putStrLn \"0 0\"\n else if swap i j a == [1..n]\n then putStrLn $ show (i+1) ++ \" \" ++ show (j+1)\n else putStrLn \"0 0\""}], "negative_code": [{"source_code": "main = do interact (unwords . map show . gao . map read . tail . words)\n\ngao a = if not (null b) && b == r c then [head b, head c] else [0, 0] where\n\tr = reverse\n\tf = r . dropWhile (uncurry (==))\n\t(b, c) = unzip $ f . f $ zip a [1 ..]\n"}, {"source_code": "import Control.Applicative\nimport Text.Printf\nimport Data.Maybe\nimport Data.List\n\nsolve :: [Int] -> Maybe (Int, Int)\nsolve arr | and$ take (r-l+1)$ drop l gs = Nothing\n | otherwise = Just (l, r)\n where\n gs = zipWith (<) arr (tail arr)\n ix = elemIndices False gs\n nd = length$ group gs\n l = head ix\n r = (last ix)+1\n\nmain = do\n getLine\n arr <- (map read . words) <$> getLine\n case solve arr of\n Just (l, r) -> putStrLn (printf \"%d %d\" l r)\n Nothing -> putStrLn \"0 0\"\n"}, {"source_code": "import Prelude\nimport Data.Char\nimport Data.List\nimport Data.Functor\n\nmain = interact q\n\nq = func . tail . map read . words\n\nfunc::[Int]->String\nfunc x = case solve x of\n Just (a, b) -> (show a) ++ \" \" ++ (show b)\n Nothing-> \"Error occurred\"\n\nfileInteract func inf ouf = do file <- readFile inf\n writeFile ouf (func file)\n\ntoInt::String->Int\ntoInt = read\n\nasInteger::String->Integer\nasInteger = read\n\ntoString::Int->String\ntoString = show\n\nreverseTuple::(a,b)->(b,a)\nreverseTuple (a,b) = (b,a)\n\nisVailed::String->Bool\nisVailed \"\" = False\nisVailed \"0\" = True\nisVailed ('0':_) = False\nisVailed _ = True\n\nsolve::[Int]->Maybe (Int, Int)\nsolve [] = Just (0, 0)\nsolve a = Just $ s' 0 a\n\ns'::Int->[Int]->(Int, Int)\ns' _ [] = (0, 0)\ns' n (x:xs) | n + 1 == x = s' x xs\n | otherwise = if left == -1 then (0,0)\n else (left, n)\n where\n left = s'' x xs\n\ns''::Int->[Int]->Int\ns'' n [] = n\ns'' n (x:xs) | n - 1 == x = s'' x xs\n | sorted (x:xs) = n\n | otherwise = -1\n\nsorted::[Int]->Bool\nsorted [] = True\nsorted (a:[]) = True\nsorted (a:b:xs) | a + 1 == b = sorted (b:xs)\n | otherwise = False"}], "src_uid": "a440099306ef411a4deca7fe3305c08b"} {"source_code": "convert x (y:\"\") = y:\"\"\n\nconvert True s@(a1:a2:\"\") = if a1 == a2 && (a1 == 'a' || a1 == 'e' || a1 == 'i' || a1 == 'o' || a1 == 'u' || a1 == 'y') then a1:\"\" else s\nconvert False s@(a1:a2:\"\") = if a1 /= a2 || (a1 == 'o' || a1 == 'e') || (not (a1 == 'a' || a1 == 'e' || a1 == 'i' || a1 == 'o' || a1 == 'u' || a1 == 'y')) then s else a1:\"\"\n\nconvert True (a:b:c) = if a == b && (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' || a == 'y') then convert True (b:c) else a:(convert False (b:c))\nconvert False s@(a:b:c:d)\n | a == b && a == c && (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' || a == 'y') = convert True (b:c:d)\n | a == b && a /= c && (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' || a == 'y') = if (a == 'o' || a == 'e') then a:b:(convert False (c:d)) else a:(convert False (c:d))\n-- | otherwise = traceShow s $ undefined\n\nconvert x (y:ys) = y:(convert False ys)\n\nsolve n s = convert False s\n\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n :: Int) s\n", "positive_code": [{"source_code": "--ghc 7.10\n\nimport Data.List\n\nt ['e', 'e'] = \"ee\"\nt ['o', 'o'] = \"oo\"\nt ('u':_) = ['u']\nt ('y':_) = ['y']\nt ('a':_) = ['a']\nt ('i':_) = ['i']\nt ('e':_) = ['e']\nt ('o':_) = ['o']\nt x = x\n\n\ntransform :: String -> String\ntransform s = concat (map t (group s))\n\nmain = do \n n <- getLine\n s <- getLine\n --print (group s)\n putStrLn $ transform s"}, {"source_code": "import Data.List\nmain = interact $ process . last . lines\n\nprocess x = concat$ map test $ group x\n\ntest x\n | notElem (head x) \"aeiouy\" = x\n | (head x == 'o') && (length x < 3) = x\n | (head x == 'e') && (length x < 3) = x\n | otherwise = [head x] "}], "negative_code": [{"source_code": "convert True (a:b:c) = if a == b then convert True (b:c) else convert False (a:b:c)\nconvert False (a:b:c:d) = if a == b && a == c then convert True (b:c:d) else a:(convert False (b:c:d))\nconvert x s = s\n\nsolve n s = convert False s\n\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n :: Int) s\n"}, {"source_code": "convert x (y:\"\") = y:\"\"\n\nconvert True s@(a1:a2:\"\") = if a1 == a2 then a1:\"\" else s\nconvert False s@(a1:a2:\"\") = if a1 /= a2 || (a1 == 'o' || a1 == 'e') then s else a1:\"\"\n\nconvert True (a:b:c) = if a == b then convert True (b:c) else a:(convert False (b:c))\nconvert False s@(a:b:c:d)\n | a == b && a == c = convert True (b:c:d)\n | a == b && a /= c = if (a == 'o' || a == 'e') then a:b:(convert False (c:d)) else a:(convert False (c:d))\n-- | otherwise = traceShow s $ undefined\n\nconvert x (y:ys) = y:(convert False ys)\n\nsolve n s = convert False s\n\nmain = do\n n <- getLine\n s <- getLine\n putStrLn $ solve (read n :: Int) s\n"}], "src_uid": "8ff1b4cf9875f1301e603b47626d06b4"} {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Bits\r\nimport Data.Set (Set)\r\nimport qualified Data.Set as Set\r\n\r\ngetElem :: Read t => IO t\r\ngetElem = getLine >>= return . read\r\n\r\ngetElems :: Read t => IO [t]\r\ngetElems = getLine >>= return . map read . words\r\n\r\nmain = do\r\n t <- getElem\r\n replicateM_ t $ do\r\n n:k:_ <- getElems :: IO [Int]\r\n if even n || k == 1 then do\r\n let odds = [1,3..n*k]\r\n let evens = [2,4..n*k]\r\n putStrLn \"YES\"\r\n showAns odds evens k\r\n else do\r\n putStrLn \"NO\"\r\n return ()\r\n where\r\n showAns :: [Int] -> [Int] -> Int -> IO ()\r\n showAns [] _ _ = return ()\r\n showAns this that k = do\r\n let (this1, this2) = splitAt k this\r\n putStrLn $ this1 >>= (' ' :) . show\r\n showAns that this2 k", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BlockArguments #-}\nimport Control.Monad\nsolve :: Int -> Int -> Maybe [[Int]]\nsolve n k\n | k == 1 = Just [[i] | i <- [1..n]]\n | odd n = Nothing\n | otherwise = Just do\n i <- [0..n-1]\n return $ do\n let !(i', p) = divMod i 2\n j <- [0..k-1]\n return $! 2 * (i' * k + j) + p + 1\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n [n, k] <- map read . words <$> getLine\n case solve n k of\n Nothing -> putStrLn \"NO\"\n Just xss -> do\n putStrLn \"YES\"\n forM_ xss $ \\xs -> putStrLn $ unwords $ map show xs\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\n--import Data.List\n--import Data.Array.Unboxed\n\n\nsolve :: Int -> Int -> Maybe [[Int]]\nsolve n 1 = Just $ map pure [1 .. n]\nsolve n k = if odd n\n then Nothing\n else Just $ do\n start <- [0, 2 .. n - 1]\n [take k [start*k + 1, start*k + 3 ..], take k [start*k + 2, start*k + 4 ..]]\n\nmainFun :: SP Builder\nmainFun = do\n t <- getInt\n fmap mconcat $ replicateM t $ do\n n <- getInt\n k <- getInt\n pure $ case solve n k of\n Nothing -> string7 \"NO\\n\"\n Just li -> string7 \"YES\\n\" <> foldMap putInts li\n\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n line <- getLine\n let [n, k] = map read $ words line :: [Int]\n let (possible, solution) = solve n k\n if possible\n then do\n putStrLn \"YES\"\n mapM_ (putStrLn . spaceSeparate) solution\n else putStrLn \"NO\"\n return ()\n\n\nsolve :: Int -> Int -> (Bool, [[Int]])\nsolve n k\n | k == 1 = (True, map (:[]) [1..n])\n | mod n 2 == 0 = (True, makeGrid n k) \n | otherwise = (False, [])\n\n-- first all the even numbers from 2 to n*k\n-- then all the odd numbers from 1 to n*k\nmakeGrid :: Int -> Int -> [[Int]]\nmakeGrid n k =\n evens ++ odds\n where\n evens = [map (2*i*k+) [2,4..2*k] | i <- [0..mid-1]]\n odds = [map (2*i*k+) [1,3..2*k] | i <- [0..mid-1]]\n mid = div n 2\n\nspaceSeparate :: (Show a) => [a] -> String\nspaceSeparate xs = foldr (++) \"\" $ intersperse \" \" $ map show xs\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n line <- getLine\n let [n, k] = map read $ words line :: [Int]\n let (possible, solution) = solve n k\n if possible\n then do\n putStrLn \"YES\"\n mapM_ putStrLn solution\n else putStrLn \"NO\"\n return ()\n\n\nsolve :: Int -> Int -> (Bool, [String])\nsolve n k\n | k == 1 = (True, map show [1..n])\n | mod n 2 == 0 = (True, map spaceSeparate $ makeGrid n k) \n | otherwise = (False, [])\n\n-- first all the even numbers from 2 to n*k\n-- then all the odd numbers from 1 to n*k\nmakeGrid :: Int -> Int -> [[Int]]\nmakeGrid n k =\n evens ++ odds\n where\n evens = [map (2*i*k+) [2,4..2*k] | i <- [0..mid-1]]\n odds = [map (2*i*k+) [1,3..2*k] | i <- [0..mid-1]]\n mid = div n 2\n\nspaceSeparate :: (Show a) => [a] -> String\nspaceSeparate xs = foldr (++) \"\" $ intersperse \" \" $ map show xs\n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n line <- getLine\n let [n, k] = map read $ words line :: [Int]\n let (possible, solution) = solve n k\n if possible\n then do\n putStrLn \"YES\"\n mapM_ putStrLn solution\n else putStrLn \"NO\"\n return ()\n\nsolve :: Int -> Int -> (Bool, [String])\nsolve n k\n | k == 1 = (True, map show [1..n])\n | mod n 2 == 0 = (True, ans) \n | otherwise = (False, [])\n where\n mid = div (n*k) 2\n ans = [spaceSeparate (map (i+) [2,4..k*2]) | i <- [0,2*k..mid-1]] ++\n [spaceSeparate (map (i+) [1,3..k*2]) | i <- [0,2*k..mid-1]]\n\nspaceSeparate :: (Show a) => [a] -> String\nspaceSeparate xs = foldr (++) \"\" $ intersperse \" \" $ map show xs\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM t $ do\n line <- getLine\n let [n, k] = map read $ words line :: [Int]\n let (possible, solution) = solve n k\n if possible\n then do\n putStrLn \"YES\"\n mapM_ putStrLn solution\n else putStrLn \"NO\"\n return ()\n\nsolve :: Int -> Int -> (Bool, [String])\nsolve n k\n | k == 1 = (True, map show [1..n])\n | mod n 2 == 0 = (True, ans) \n | otherwise = (False, [])\n where\n mid = div (n*k) 2\n ans = [spaceSeparate (map (i+) [2,4..k*2]) | i <- [0,k..mid-1]] ++\n [spaceSeparate (map (i+) [1,3..k*2]) | i <- [0,k..mid-1]]\n\nspaceSeparate :: (Show a) => [a] -> String\nspaceSeparate xs = foldr (++) \"\" $ intersperse \" \" $ map show xs\n\n"}], "src_uid": "9fb84ddc2e04fd637812cd72110b7f36"} {"source_code": "import Data.List\nmain = do\n [n, w] <- getLine >>= return. map read. words :: IO [Integer]\n a <- getLine >>= return. scanl (+) 0. map read. words\n print. max 0 $ 1 + w - maximum a + minimum a\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\n\nmain = do\n inp <- fmap B.lines $ B.getContents\n let [n,w] = map readI $ B.words $ inp!!0\n let as = map readI $ B.words $ inp!!1\n print (solve w as)\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: Int -> [Int] -> Int\nsolve w as =\n max c 0\n where\n c = w - u1 + 1 + (min 0 u0)\n\n bs = scanl (+) 0 as\n\n u1 = maximum bs\n u0 = minimum bs"}], "negative_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as B\nimport Data.List\n\nmain = do\n inp <- fmap B.lines $ B.getContents\n let [n,w] = map readI $ B.words $ inp!!0\n let as = map readI $ B.words $ inp!!1\n print (solve w as)\n\nreadI :: B.ByteString -> Int\nreadI s = case B.readInt s of Just (n,_) -> n\n\nsolve :: Int -> [Int] -> Int\nsolve w as =\n w - u1 + 1 + (min 0 u0)\n where\n bs = scanl (+) 0 as\n\n u1 = maximum bs\n u0 = minimum bs"}], "src_uid": "8cf5d08a319672d9b767d3523eca4df6"} {"source_code": "import Data.Map (Map, singleton, findWithDefault, insert)\nimport Data.Int (Int64)\n\nparseInt :: String -> Int\nparseInt x = read x\n\nparseInt64 :: String -> Int64\nparseInt64 x = read x\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\naddMod :: Int -> Int -> Int\naddMod a b = mod (a + b) 1000000007\n\nsolve :: [Int64] -> Int\nsolve xs = go xs (singleton 0 1) 0 1 where\n go :: [Int64] -> Map Int64 Int -> Int64 -> Int -> Int\n go [] s d r = r\n go (x:xs) s d r = go xs s' d' r' where\n k = addMod r (1000000007 - findWithDefault 0 (-d) s)\n r' = addMod r k\n d' = d + x\n s' = insert (-d) r s\n\nrun :: IO ()\nrun = do\n n <- getLine\n b <- getLine\n print $ solve $ map parseInt64 $ split ' ' b\n\nrunK :: Int -> IO ()\nrunK 1 = run\nrunK k = run >>= (\\x -> runK (k-1))\n\nmain = do\n t <- getLine\n runK $ parseInt t\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Map.Strict as M\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nkMod :: Int64\nkMod = 1000000007\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n bs <- map fromIntegral <$> getInts :: IO [Int64]\n let\n acc (total, totalSuf, sufs, offset) b = (total', totalSuf', sufs', offset')\n where\n totalSuf' = case M.lookup (-offset) sufs of\n Nothing -> (totalSuf * 2) `mod` kMod\n Just c -> (totalSuf * 2 + kMod - c) `mod` kMod\n sufs' = M.insert (-offset) totalSuf sufs\n offset' = offset + b\n total' = (total + totalSuf + kMod - M.findWithDefault 0 (-offset) sufs) `mod` kMod\n (result, _, _, _) = foldl' acc (1, 1, M.singleton 0 1, 0) bs\n C.putStrLn $ C.pack $ show result\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\nimport qualified Data.Map.Strict as M\n\ntype SIO = StateT P.ByteString IO\n\ntype Map = M.Map Int64 Int\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\n-- Partitions into (nonempty) intervals, of which only the last may have sum 0\nsolve :: Map -> Int64 -> Int -> [Int] -> Int\nsolve _ _ prevOptsTot [_] = prevOptsTot -- extend each prevOpt to end\nsolve !excls !prevSum !prevOptsTot (b : bs) = let\n currExcl = M.findWithDefault 0 currSum excls\n currOpts = prevOptsTot - currExcl\n -- prevOptsTot = currOpts + currExcl\n nextExcls = M.insert currSum prevOptsTot excls\n currSum = prevSum + fromIntegral b\n currOptsTot = mod (prevOptsTot + currOpts) p\n in solve nextExcls currSum currOptsTot bs\nsolve _ _ _ [] = 1\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n let initMap = M.fromAscList [(0, 1)]\n replicateM_ t $ do\n [_n] <- readInts\n b <- readInts\n putInts [solve initMap 0 1 b]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nimport Data.Int\nimport qualified Data.Map.Strict as M\n\ntype SIO = StateT P.ByteString IO\n\ntype Map = M.Map Int64 Int\n\np :: Int\np = 10 ^ (9 :: Int) + 7\n\n-- Partitions into (nonempty) intervals, of which only the last may have sum 0\nsolve :: Map -> Int64 -> Int -> [Int] -> Int\nsolve _ _ prevOptsTot [_] = prevOptsTot -- extend each prevOpt to end\nsolve excls prevSum prevOptsTot (b : bs) = let\n currExcl = M.findWithDefault 0 currSum excls\n currOpts = prevOptsTot - currExcl\n -- prevOptsTot = currOpts + currExcl\n nextExcls = M.insert currSum prevOptsTot excls\n currSum = prevSum + fromIntegral b\n currOptsTot = mod (prevOptsTot + currOpts) p\n in solve nextExcls currSum currOptsTot bs\nsolve _ _ _ [] = 1\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n let initMap = M.fromAscList [(0, 1)]\n replicateM_ t $ do\n [_n] <- readInts\n b <- readInts\n putInts [solve initMap 0 1 b]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}], "negative_code": [{"source_code": "import Data.Map (Map, singleton, findWithDefault, insert)\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\naddMod :: Int -> Int -> Int\naddMod a b = mod (a + b) 1000000007\n\nsolve :: [Int] -> Int\nsolve xs = go xs (singleton 0 1) 0 1 where\n go :: [Int] -> Map Int Int -> Int -> Int -> Int\n go [] s d r = r\n go (x:xs) s d r = go xs s' d' r' where\n k = addMod r (1000000007 - findWithDefault 0 (-d) s)\n r' = addMod r k\n d' = d + x\n s' = insert (-d) r s\n\nrun :: IO ()\nrun = do\n n <- getLine\n b <- getLine\n print $ solve $ map parseInt $ split ' ' b\n\nrunK :: Int -> IO ()\nrunK 1 = run\nrunK k = run >>= (\\x -> runK (k-1))\n\nmain = do\n t <- getLine\n runK $ parseInt t\n"}, {"source_code": "import Data.Map (Map, singleton, findWithDefault, insertWith)\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\naddMod :: Int -> Int -> Int\naddMod a b = mod (a + b) 1000000007\n\nsolve :: [Int] -> Int\nsolve xs = go xs (singleton 0 1) 0 1 where\n go :: [Int] -> Map Int Int -> Int -> Int -> Int\n go [] s d r = r\n go (x:xs) s d r = go xs s' d' r' where\n k = addMod r (1000000007 - findWithDefault 0 (-d) s)\n r' = addMod r k\n d' = d + x\n s' = insertWith addMod (-d) k s\n\nrun :: IO ()\nrun = do\n n <- getLine\n b <- getLine\n print $ solve $ map parseInt $ split ' ' b\n\nrunK :: Int -> IO ()\nrunK 1 = run\nrunK k = run >>= (\\x -> runK (k-1))\n\nmain = do\n t <- getLine\n runK $ parseInt t\n"}, {"source_code": "import Data.Map (Map, singleton, findWithDefault, insertWith)\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\naddMod :: Int -> Int -> Int\naddMod a b = mod (a + b) 1000000007\n\nsolve :: [Int] -> Int\nsolve xs = go xs (singleton 0 1) 0 1 where\n go :: [Int] -> Map Int Int -> Int -> Int -> Int\n go [] s d r = r\n go (x:xs) s d r = go xs s' d' r' where\n k = r - findWithDefault 0 (-d) s\n r' = addMod r k\n d' = d + x\n s' = insertWith addMod (-d) k s\n\nrun :: IO ()\nrun = do\n n <- getLine\n b <- getLine\n print $ solve $ map parseInt $ split ' ' b\n\nrunK :: Int -> IO ()\nrunK 1 = run\nrunK k = run >>= (\\x -> runK (k-1))\n\nmain = do\n t <- getLine\n runK $ parseInt t\n"}, {"source_code": "import Data.Map (Map, singleton, findWithDefault, insertWith)\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit d [] = []\nsplit d s = x : split d (drop 1 y) where (x,y) = span (/= d) s\n\naddMod :: Int -> Int -> Int\naddMod a b = mod (a + b) 1000000007\n\nsolve :: [Int] -> Int\nsolve xs = go xs (singleton 0 1) 0 1 where\n go :: [Int] -> Map Int Int -> Int -> Int -> Int\n go [] s d r = r\n go (x:xs) s d r = go xs s' d' r' where\n k = r + 1000000007 - findWithDefault 0 (-d) s\n r' = addMod r k\n d' = d + x\n s' = insertWith addMod (-d) k s\n\nrun :: IO ()\nrun = do\n n <- getLine\n b <- getLine\n print $ solve $ map parseInt $ split ' ' b\n\nrunK :: Int -> IO ()\nrunK 1 = run\nrunK k = run >>= (\\x -> runK (k-1))\n\nmain = do\n t <- getLine\n runK $ parseInt t\n"}, {"source_code": "import Data.List\n\nparseInt :: String -> Int\nparseInt x = read x\n\nsplit :: Eq a => a -> [a] -> [[a]]\nsplit chr = unfoldr sep where\n sep [] = Nothing\n sep l = Just . fmap (drop 1) . break (== chr) $ l\n\nsolve :: [Int] -> Int\nsolve (x:xs) = x\n\nrun :: IO ()\nrun = do\n n <- getLine\n b <- getLine\n print $ solve $ map parseInt $ split ' ' b\n\nmain = do\n t <- getLine\n run\n run\n run\n run\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport Data.Int\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap.Strict as IM\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nkMod :: Int64\nkMod = 1000000007\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n bs <- getInts\n let\n acc (total, totalSuf, sufs, offset) b = (total', totalSuf', sufs', offset')\n where\n totalSuf' = case IM.lookup (-offset) sufs of\n Nothing -> (totalSuf * 2) `mod` kMod\n Just c -> (totalSuf * 2 + kMod - c) `mod` kMod\n sufs' = IM.insert (-offset) totalSuf sufs\n offset' = offset + b\n total' = (total + totalSuf + kMod - IM.findWithDefault 0 (-offset) sufs) `mod` kMod\n (result, _, _, _) = foldl' acc (1, 1, IM.singleton 0 1, 0) bs\n C.putStrLn $ C.pack $ show result\n"}, {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap.Strict as IM\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nkMod :: Int\nkMod = 1000000007\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n bs <- getInts\n let\n acc (total, totalSuf, sufs, offset) b = (total', totalSuf', sufs', offset')\n where\n totalSuf' = case IM.lookup (-offset) sufs of\n Nothing -> (totalSuf * 2) `mod` kMod\n Just c -> (totalSuf * 2 + kMod - c) `mod` kMod\n sufs' = IM.insert (-offset) totalSuf sufs\n offset' = offset + b\n total' = (total + totalSuf + kMod - IM.findWithDefault 0 (-offset) sufs) `mod` kMod\n (result, _, _, _) = foldl' acc (1, 1, IM.singleton 0 1, 0) bs\n C.putStrLn $ C.pack $ show result\n"}], "src_uid": "eb8f0abc9556ca514454d307fd98ae5d"} {"source_code": "import Data.List (partition)\n\nprocess :: [Int] -> Int\nprocess xs\n | length es == 1 = snd.head $ es\n | otherwise = snd.head $ os\n where\n (es,os) = partition (even.fst) $ zip xs [1..]\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n print $ process xs", "positive_code": [{"source_code": "import System.IO\nimport Control.Monad \nimport Data.List \nimport Data.Maybe\n\nmyFunc ::(Integral a,Enum a)=>[a]->([a],[a])\nmyFunc []=([],[])\nmyFunc x =partition (\\a ->mod a 2 ==0) x\n\n\nmain = do\n number <-getLine\n numberStr <- getLine\n let n=number\n let numberString=numberStr\n let ori=map read (words numberString)\n let k=myFunc ori\n if (==1).length.fst $ k \n then mapM_ print $ [1+ ( head $ maybeToList (elemIndex (head $ fst k) ori))]\n else mapM_ print $ [1+ ( head $ maybeToList (elemIndex (head $ snd k) ori))]"}, {"source_code": "import Data.List (groupBy)\n\nmain :: IO ()\nmain = do\n getLine\n s <- getLine\n let xs = map read . words $ s :: [Int]\n print $ fst . head . filter (if (sum . map (`mod` 2) . take 3) xs < 2 then (\\(_, x) -> odd x) else (\\(_, x) -> even x)) $ zip [1..] xs\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\n-- import qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = map (read . B.unpack) . B.words <$> B.getLine\ngetIntList :: IO [Int]\ngetIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmaj :: [Bool] -> Bool\nmaj (True:True:_) = True\nmaj (False:False:_) = False\nmaj (_:_:a:_) = a\nmaj _ = error \"WTF\"\n\nsolve :: [Int] -> Int\nsolve = (+1) . fromJust . (elemIndex =<< not . maj) . map odd\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n print $ solve a\n"}, {"source_code": "differentParity list = if onlyOneEven list\n then findIndexWithParity 0 list\n else findIndexWithParity 1 list\n\nonlyOneEven list = length (filter even list) == 1\n\nfindIndexWithParity p (x:xs)\n | p == mod x 2 = 1\n | otherwise = 1 + findIndexWithParity p xs\n\nmain = do\n dummy <- getLine\n inputLine <- getLine\n let inputWords = words inputLine\n let list = map read inputWords :: [Int]\n putStrLn (show (differentParity list))\n\n"}, {"source_code": "par::[Int]->Int\npar xs = if x'>y' then 1 else 0 \n where \n (x',y') = par' xs 0 0\n par' [] a b = (a,b)\n par' (x:xs) a b\n | (mod x 2)==0 = par' xs (a+1) b\n | (mod x 2)==1 = par' xs a (b+1)\n \n\nfoundans::Int->[Int]->Int->Int\nfoundans _ [] _= 0\nfoundans p (x:xs) q\n | p==(mod x 2) = q\n | otherwise = foundans p xs (q+1)\n \nmain = do\n n<-getLine\n m<-getContents\n print . (\\xs->foundans (par xs) xs 1) . map (read::String->Int) . words $ m\n"}, {"source_code": "par'::[Int]->(Int,Int)\npar' xs = (sum (map (\\x->mod x 2) xs), sum (map (\\x->mod (x+1) 2) xs) )\n\npar::[Int]->(Int->Bool)\npar xs = if x>y then odd else even\n where (x,y)=par' xs\n\nfoundans::(a->Bool)->[a]->Int\nfoundans f xs = 1+(length $ takeWhile f xs)\n \nmain = do\n n<-getLine\n m<-getContents\n print . (\\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m"}, {"source_code": "par'::[Int]->(Int,Int)\npar' xs = (sum (map (\\x->mod x 2) xs), sum (map (\\x->mod (x+1) 2) xs) )\n\npar::[Int]->(Int->Bool)\npar xs = if x>y then odd else even\n where (x,y)=par' xs\n\nfoundans::(a->Bool)->[a]->Int\nfoundans f xs = 1+(length $ takeWhile f xs)\n \nmain = do\n n<-getLine\n m<-getContents\n print . (\\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m"}, {"source_code": "\nimport Data.List\nchoose ([a], _) = a\nchoose (_, [b]) = b\nsolve s = fst . choose . partition (odd.snd) $ zip [1..] s\nmain = getLine >> getLine >>= print . solve . map read . words\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\ncheck n | le >1 = snd $ head $ filter (\\z-> odd (fst z)) $ zip n [1..]\n | otherwise = snd $ head $ filter (\\z-> even (fst z)) $ zip n [1..]\n where le = length $ filter even n\n\n\nmain=do\n getLine\n n<- map read <$> words <$> getLine ::IO [Int]\n print $ check n\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport qualified Data.Set as Set\nimport Control.Monad\nimport Control.Applicative\n\nmain = do\n _ <- getLine\n xs <- fmap (map read . words) getLine :: IO [Int]\n let p = partition (\\x -> x `mod` 2 == 0) xs \n number = if length (fst p) == 1 then head (fst p) else head (snd p)\n answer = fromJust $ findIndex (\\x -> x == number) xs\n in print (answer + 1)"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map read . words . (!!1) . lines\n\nsolve :: [Int] -> Int\nsolve ns = head [ i | (i, n) <- zip [1..] ns, length [ m | m <- ns, even n == even m ] == 1 ]\n"}, {"source_code": "import Data.List\nmain = do\n getLine\n (es,os) <- fmap (partition (even . snd) . zip [1..] . map read . words) getLine\n print $ case es of\n [(n,_)] -> n\n _ -> fst (head os)"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain = do\n getLine\n s <- getLine\n let task = map read $ words s\n print $ solve task\nsolve :: [Integer] -> Int\nsolve task | trueCount == 1 = (fromJust $ elemIndex True bools) + 1\n | otherwise = (fromJust $ elemIndex False bools) + 1\n where bools = map even task\n trueCount = length . filter (==True) $ bools\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n _ <- getLine\n line <- getLine\n putStrLn $ show $ gao $ map read $ words line\n\ngao :: [Int] -> Int\ngao a = let key = if length x == 1 then head x else head y in (\\(Just x) -> x + 1) $ findIndex (==key) a\n where (x, y) = partition even a\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/25/A\n\nimport Data.List\nimport Data.Maybe\n\nsolve :: [Int] -> Int\nsolve a | length (filter odd a) == 1 = 1 + fromJust (findIndex odd a)\n | otherwise = 1 + fromJust (findIndex even a)\n\nmain :: IO ()\nmain = print . solve . map read . tail . words =<< getContents\n"}, {"source_code": "solve :: [Int] -> Int\nsolve (a:b:rest) | odd a && even b = if odd (head rest) then 2 else 1\n | even a && odd b = if even (head rest) then 2 else 1\n | even a = (+ 3) . length . takeWhile even $ rest\n | otherwise = (+ 3) . length . takeWhile odd $ rest\nmain = interact $ show . solve . map read . tail . words\n"}, {"source_code": "solve :: [Int] -> Int\nsolve (a:b:rest) | even a && even b = (+ 3) . length . takeWhile even $ rest\n | odd a && even b = if odd (head rest) then 2 else 1\n | even a && odd b = if even (head rest) then 2 else 1\n | otherwise = (+ 3) . length . takeWhile odd $ rest\nmain = interact $ show . solve . map read . tail . words\n"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve a = let\n b = [x | x <- a, mod x 2 == 0];\n c = [x | x <- a, odd x];\n in\n let mb = elemIndex (head (f b c)) a in\n case mb of\n Nothing -> error \"oo\"\n Just a -> a + 1\n\n\nf :: [Int] -> [Int] -> [Int]\nf a b = if (length a == 1) then a else b\n\nmain = do {\n z1 <- getLine;\n z2 <- getLine;\n putStrLn $ show $ solve $ map read (words z2)\n}\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\nimport qualified Data.Foldable as F\nimport qualified Data.Traversable as T\nimport Text.Printf\n\nmain :: IO ()\nmain = do\n let readData :: IO [Int]\n readData = map read . words <$> getLine\n n : _ <- readData\n (as, bs) <- partition (odd . snd) . zip [1 ..] . take n <$> readData\n case (as, bs) of\n ([(i, _)], _) -> print i\n (_, [(i, _)]) -> print i\n\n\n\n"}, {"source_code": "getnum :: IO [Int]\ngetnum = fmap (map read . words) getLine\n\nget num | length (filter odd num) == 1 = odd\n | otherwise = even\n\nfind num = fst . head . filter snd . zip [1..] $ map f num\n where f = get num\n\nmain = do\n s <- getLine\n print . find =<< getnum\n"}, {"source_code": "import Control.Applicative\nimport Data.Char\n \n \n \nmain= do\n\tgetLine\n\tn<- map read.words <$> getLine::IO [Int]\n\tlet x = length $ take 3 ( filter even n)\n\tprint $ snd $ head $ (filter (\\z-> (if x>1 then odd else even) (fst z)) $ (zip n [1..])) "}, {"source_code": "main = do\n getLine\n m <- getLine\n let m2 = map (even.read) $ words m\n print $ diff m2\nth :: Int -> [a] -> a\nth 1 y = head y\nth n (x:xs) = th (n-1) xs\ndiff :: Eq a => [a] -> Int\ndiff (x:x2:x3:[]) = if (x == x2) then 3 else (if (x==x3) then 2 else 1)\ndiff (x:x2:x3:xs) = if (x == x2) then (diff (x2:x3:xs) + 1) else diff (x:x2:x3:[])"}, {"source_code": "deleteN _ [] = []\ndeleteN i (a:as)\n | i == 0 = as\n | otherwise = a : deleteN (i - 1) as\n\n\ngetIndex :: [Int] -> Int -> Int\ngetIndex nums i\n | all odd withoutEl || all even withoutEl = i\n | otherwise = getIndex nums (i + 1)\n where withoutEl = deleteN i nums\n\nmain = do\n getLine\n nums_ln <- getLine\n\n let nums = map (read :: String -> Int) (words nums_ln)\n putStrLn . show $ (getIndex nums 0) + 1\n"}, {"source_code": "import Data.List\n \nanswer :: [Integer] ->Int\nanswer xs = if length xs == ans && odd (head xs - last xs) then ans +1 else ans \n where ans = snd $ foldl1 (\\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..]) \n \nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= print . subtract 1 . answer . fmap read . words\n \nmain :: IO ()\nmain = someFunc"}, {"source_code": "import Data.List\nimport Data.Maybe\n\nanswer :: [Int] -> Int\nanswer xs = fromJust (findIndex (\\x-> x `rem` 2 == parity) xs) + 1\n where oddCount = length . filter odd $ xs\n parity = fromEnum (oddCount == 1) \n\nsolve :: String -> String\nsolve s = show . answer $ xs\n where _:xs = fmap read . words $ s\n\nmain :: IO ()\nmain = interact $ solve"}, {"source_code": "import Data.List\nmain = do\n\tdummy <- getLine\n\tl <- fmap (map read . words) getLine\n\tputStrLn $ show $ snd $ head $ (\\(a,b) -> if length a == 1 then a else b) $ partition (odd . fst) $ zip l [1 ..]\n"}, {"source_code": "main = do\n\tn<-getLine\n\trest<-getLine\n\tputStrLn $ show $ solve $ (map read) (words rest)\nsolve m | length (filter (odd) m)==1 = length (takeWhile (even) m)+1\n\t | otherwise = length (takeWhile (odd) m) +1"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = print . solve . map read . tail . words =<< getContents\n\nremoveMaybe :: Maybe a -> a\nremoveMaybe (Just a) = a\n\nsolve :: [Int] -> Int\nsolve a | length (filter odd a) == 1 = 1 + removeMaybe (findIndex odd a)\n | otherwise = 1 + removeMaybe (findIndex even a)\n"}, {"source_code": "\n-- comment functions to understand\n-- and verbalize the problem solving\n-- process\n\n\n\n\n\n\n-- converts list of strings to list of integers\nconv lst jj\n | (null lst) = jj\n | otherwise = conv (tail lst) (jj ++ [(read (head lst))::Int])\n\n\n-- determine if the weird element is even\nweird [e,o]\n | (e == 1) = True\n | otherwise = False\n\n\n-- convert a Bool to an Int\nbooltoint boo\n | (boo == True) = 1\n | otherwise = 0\n\n-- count the parity of the elements in the list\ncountParity ss e o\n | (null ss) = [e,o]\n | otherwise = countParity (tail ss) \n (e + (booltoint (even (head ss))))\n (o + (booltoint (odd (head ss))))\n\n\n-- search the list for the first instance\n-- of the \"weird\" element which has a unique\n-- parity\nsearchlist lst rr indx\n | (rr == True) = if (even (head lst))\n then indx\n else searchlist (tail lst) rr (indx+1)\n | otherwise = if(odd (head lst))\n then indx\n else searchlist (tail lst) rr (indx+1)\n\n\nmain = do\n ff <- getLine\n oo <- getLine\n let ss = (conv (words oo) [])\n uu = (countParity ss 0 0)\n\n if (weird uu)\n then putStrLn (show ((searchlist ss (weird uu) 0)+1))\n else putStrLn (show ((searchlist ss (weird uu) 0)+1))\n \n\n\n \n"}, {"source_code": "main :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let l = take 3 a\n eL = length . filter even $ l\n oL = length . filter odd $ l\n fn = if eL > oL then odd else even\n print $ solve 1 fn a\n where solve _ _ [] = -1\n solve i fn (a:as) = if fn a then i else solve (i+1) fn as"}, {"source_code": "import Data.Maybe\nimport Data.List\n\nmain = do\n getLine\n xs <- fmap (map read . words) getLine\n let (a, b) = partition even xs\n\n print $ (fromJust $ elemIndex (head $ if length a == 1 then a else b) xs) + 1\n"}, {"source_code": "\nmain = getContents >>= putStrLn . show . func . map read . words . last . lines\n\n\nfunc :: [Int] -> Int\nfunc [] = 0\nfunc xs = findNumber xs $ if length oddX > length evenX then head evenX else head oddX\n\t\t\twhere\n\t\t\toddX = [y | y <- xs , odd y]\n\t\t\tevenX = [y | y <- xs , even y]\n\nfindNumber :: (Eq a, Num b) => [a]-> a -> b\nfindNumber [] m = 0\nfindNumber (x:xs) m = 1 + if x == m \n\t\t\t\t\t\t\t\tthen 0 \n\t\t\t\t\t\t\t\telse findNumber xs m \t"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. map read. words.head.tail.lines\nsolve :: [Int]->String\nsolve xs = show $ (1+) $ fromJust $ findIndex (slv1) $ zip ( cycle xs) $ zip (tail $ cycle xs) ( tail $ tail $ cycle xs)\n where slv1 (x,(y,z)) = let x1 = x `mod` 2; y1 = y `mod` 2; z1 = z `mod` 2 in y1==z1 && x1/=y1"}, {"source_code": "main :: IO ()\nmain = interact func\n\nfunc :: String -> String\nfunc s = show.func' 1.map (`mod` 2).map read.words.head.tail$lines s\n \nfunc' :: Int -> [Int] -> Int\nfunc' _ [] = error \"\"\nfunc' n (0:0:1:_) = n+2\nfunc' n (0:1:0:_) = n+1\nfunc' n (1:0:0:_) = n\nfunc' n (1:1:0:_) = n+2\nfunc' n (1:0:1:_) = n+1\nfunc' n (0:1:1:_) = n\nfunc' n (_:xs) = func' (n+1) xs\n\n"}, {"source_code": "main :: IO ()\nmain = interact func\n\nfunc :: String -> String\nfunc s = show.func' 1.map (`mod` 2).map read.words.head.tail$lines s\n \nfunc' :: Int -> [Int] -> Int\nfunc' n (a:b:c:xs)\n | a == b && b /= c = n + 2\n | a == c && b /= c = n+1\n | a /= b && b == c = n\n | otherwise = func' (n+1) (b:c:xs)\nfunc' _ _ = error \"\"\n\n"}, {"source_code": "readInts :: IO [Int]\nreadInts = do\n line <- getLine\n return (map read (words line))\n\nsolve :: Int -> [Bool] -> Int\nsolve 1 (a:b:c:as)\n | a /= b && b == c = 1\n | otherwise = solve 2 (a:b:c:as)\nsolve n (a:b:[]) = n\nsolve n (a:b:c:as)\n | a /= b && b /= c = n\n | otherwise = solve (n + 1) (b:c:as)\nsolve _ _ = error \"Owibka v dannyh.\"\n\n\nmain = do\n getLine\n as <- readInts\n print (solve 1 (map odd as))"}], "negative_code": [{"source_code": "import Data.List\n\nanswer :: [Integer] ->Integer\nanswer xs = snd $ foldl1 (\\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..]) \n\nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= print . subtract 1 . answer . fmap read . words\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "import Data.List\n\nanswer :: [Integer] ->Int\nanswer xs = if res /= length xs then res - 1 else res\n where res = snd $ foldl1 (\\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..]) \n\nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= print . answer . fmap read . words\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "import Data.List\n\nanswer :: [Integer] ->Int\nanswer xs = if length xs == ans && even (head xs - last xs) then ans - 1 else ans\n where ans = snd $ foldl1 (\\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..]) \n\nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= print . subtract 1 . answer . fmap read . words\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "import Data.List\n\nanswer :: [Integer] ->Int\nanswer xs = if length xs == ans && even (head xs - last xs) then ans - 1 else ans\n where ans = snd $ foldl1 (\\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..]) \n\nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= print . answer . fmap read . words\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "main :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let l = take 3 a\n eL = length . filter even $ l\n oL = length . filter odd $ l\n fn = if eL == 1 then even else odd\n print $ solve 1 fn a\n where solve _ _ [] = -1\n solve i fn (a:as) = if fn a then i else solve (i+1) fn as"}, {"source_code": "main :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let l = take 3 a\n eL = length . filter even $ l\n oL = length . filter odd $ l\n fn = if eL > oL then even else odd\n print $ solve 1 fn a\n where solve _ _ [] = -1\n solve i fn (a:as) = if fn a then i else solve (i+1) fn as"}, {"source_code": "main = getContents >>= putStrLn . show . func . map read . words . last . lines\n\n\nfunc :: [Int] -> Int\nfunc [] = 0\nfunc xs = if length oddX > length evenX then head evenX else head oddX\n\t\t\twhere\n\t\t\toddX = [y | y <- xs , odd y]\n\t\t\tevenX = [y | y <- xs , even y]"}, {"source_code": "par::[Int]->Int\npar xs = if x'>y' then 1 else 0 \n where \n (x',y') = par' xs 0 0\n par' [] a b = (a,b)\n par' (x:xs) a b\n | (mod x 2)==0 = par' xs (a+1) b\n | (mod x 2)==1 = par' xs a (b+1)\n \n\nfoundans::Int->[Int]->Int\nfoundans _ [] = 0\nfoundans p (x:xs)\n | p==(mod x 2) = x\n | otherwise = foundans p xs\n \nmain = do\n n<-getLine\n m<-getContents\n print . (\\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m\n"}, {"source_code": "par'::[Int]->(Int,Int)\npar' xs = (sum (map (\\x->mod x 2) xs), sum (map (\\x->mod (x+1) 2) xs) )\n\npar::[Int]->(Int->Bool)\npar xs = if x>y then odd else even\n where (x,y)=par' xs\n\nfoundans::(a->Bool)->[a]->Int\nfoundans f xs = length $ takeWhile f xs\n \nmain = do\n n<-getLine\n m<-getContents\n print . (\\xs->foundans (par xs) xs) . map (read::String->Int) . words $ m\n"}, {"source_code": "import Data.List\nsplit s = map (map snd) . groupBy (\\(a,_) (b,_) -> div a 3 == div b 3) . zip [0..] $ s\nsolve s = intercalate \"-\" . reverse . adjust . reverse . split $ s\n where adjust ([x]:[a,b,c]:xs) = [a,b,'-',c,x]:xs\n adjust xs = xs\n\nmain = getLine >> getLine >>= putStrLn . solve \n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\ncheck n | le >1 = head $ filter odd n\n | otherwise = head $ filter even n \n where le = length $ filter even n\n\n\nmain=do\n getLine\n n<- map read <$> words <$> getLine ::IO [Int]\n print $ check n\n"}, {"source_code": "solve :: [Int] -> Int\nsolve (a:b:rest) | even a && even b = (+ 3) . length . takeWhile even $ rest\n | odd a && even b = if odd (head rest) then 2 else 1\n | otherwise = (+ 3) . length . takeWhile odd $ rest\nmain = interact $ show . solve . map read . tail . words"}, {"source_code": "import Data.List\n\nsolve :: [Int] -> Int\nsolve a = let\n b = [x | x <- a, mod x 2 == 0];\n c = [x | x <- a, odd x];\n in\n if (length b) == 1 then head b else head c\n\nmain = do {\n z1 <- getLine;\n z2 <- getLine;\n putStrLn $ show $ solve $ map read (words z2)\n}"}, {"source_code": "getIndex :: [Int] -> Int -> Int -> Int\ngetIndex (x:xs) curSum ind\n | newSum `mod` 2 == 1 = ind\n | otherwise = getIndex xs newSum newInd\n where newSum = curSum + x\n newInd = ind + 1\n\nmain = do\n getLine\n ln <- getLine\n nums <- return . map (read :: String -> Int) $ words ln\n putStrLn . show $ getIndex (tail nums) (head nums) 2 \n"}, {"source_code": "getIndex :: [Int] -> Int -> Int\ngetIndex (x:xs) ind\n | null xs = ind\n | x `mod` 2 /= head xs `mod` 2 = ind\n | otherwise = getIndex xs (ind + 1)\n\nmain = do\n n_ln <- getLine\n nums_ln <- getLine\n\n let n = read n_ln :: Int\n let nums = map (read :: String -> Int) (words nums_ln)\n\n let ia = getIndex nums 1\n let ib = n - getIndex (reverse nums) 0\n\n putStrLn . show $ (ia + ib) `div` 2 \n"}], "src_uid": "dd84c2c3c429501208649ffaf5d91cee"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n as <- A.listArray (0,n-1) . sort . map toI64 .\n unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n m <- readInt <$> getLine\n qs <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let s = sum (A.elems as)\n forM_ qs $ print . query n as s m\n\nquery :: Int -> UArray Int Int64 -> Int64 -> Int -> Int -> Int64\nquery n as sumas m q = sumas - (as A.! (n-q))\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n _ <- getLine\n let arr = listArray (1,n) (sort as)\n let s = sum arr\n qs <- (map read.words) <$> getLine\n forM_ qs (print.solve arr s n)\n\nsolve :: Array Integer Integer -> Integer -> Integer -> Integer -> Integer\nsolve arr s n q = s - arr!(n-q+1)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Data.Array\nimport Control.Monad\n\nmain = do\n let int = fst . fromJust . B.readInteger\n ints = map int . B.words \n n <- int <$> B.getLine\n as'' <- ints <$> B.getLine\n let as' = sort as''\n as = array(0,n-1) $ zip [0..n-1] $ as'\n bs = array(0,n-1) $ zip [0..n-1] $ scanr (+) 0 as' \n cs = array(0,n-1) $ zip [0..n-1] $ scanl (+) 0 as' \n B.getLine\n (ints <$> B.getLine) >>= mapM_ (\\i -> print $ bs!(n - i) - as!(n-i) + cs!(n-i)) \n\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Array\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- (map read.words) <$> getLine\n _ <- getLine\n let arr = listArray (1,n) (sort as)\n let s = sum arr\n qs <- (map read.words) <$> getLine\n forM_ qs (print.solve arr s n)\n\nsolve :: Array Int Int -> Int -> Int -> Int -> Int\nsolve arr s n q = s - arr!(n-q+1)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\nimport Data.Array\nimport Control.Monad\n\nmain = do\n let int = fst . fromJust . B.readInt\n ints = map int . B.words \n n <- int <$> B.getLine\n as'' <- ints <$> B.getLine\n let as' = sort as''\n as = array(0,n-1) $ zip [0..n-1] $ as'\n bs = array(0,n-1) $ zip [0..n-1] $ scanr (+) 0 as' \n cs = array(0,n-1) $ zip [0..n-1] $ scanl (+) 0 as' \n B.getLine\n (ints <$> B.getLine) >>= mapM_ (\\i -> print $ bs!(n - i) - as!(n-i) + cs!(n-i)) \n\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n n <- readInt <$> getLine\n as <- A.listArray (0,n-1) . sort . \n unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n m <- readInt <$> getLine\n qs <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine\n let s = sum (A.elems as)\n forM_ qs $ print . query n as s m\n\nquery :: Int -> UArray Int Int -> Int -> Int -> Int -> Int\nquery n as sumas m q = sumas - (as A.! (n-q))\n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n"}], "src_uid": "c1608f6f71cac56690e31aa130c1990e"} {"source_code": "import Data.List\nmain = interact $ unlines . map res . process . tail . lines\n\nres True = \"YES\"\nres False = \"NO\"\n\nprocess [] = []\nprocess (x:y:t) = check (group x) (group y) : process t\n\ncheck [] [] = True\ncheck _ [] = False\ncheck [] _ = False\ncheck (a1:t1) (a2:t2)\n | ((head a1) == (head a2)) && ((length a1) <= (length a2)) = check t1 t2\n | otherwise = False", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Text.Printf\nimport Data.List\nimport Data.Functor\nimport Data.Function\nimport Control.Monad\nimport Data.Maybe\nimport Prelude\nimport qualified Data.ByteString.Char8 as B8\n\ntype CompressedString = [(Char, Int)]\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\nreadB8Int :: B8.ByteString -> Int\nreadB8Int = fst . fromJust . B8.readInt\n\ncompressFold :: Char -> CompressedString -> CompressedString\ncompressFold c [] = [(c, 1)]\ncompressFold c cs@((fc, flen):other)\n | fc == c = (fc, flen + 1):other\n | otherwise = (c, 1):cs\n\ncompress :: B8.ByteString -> CompressedString\ncompress = B8.foldr' compressFold []\n\nmain :: IO ()\nmain = do\n n <- readB8Int <$> B8.getLine\n replicateM_ n $ do\n stra <- head <$> B8.words <$> B8.getLine\n strb <- head <$> B8.words <$> B8.getLine\n let cstra = compress stra\n let cstrb = compress strb\n let isleneq = ((==) `on` length) cstra cstrb\n let isok = all (\\((ca, la), (cb, lb)) -> (ca == cb) && (la <= lb)) $ zip cstra cstrb\n let answer = if isok && isleneq then \"YES\" else \"NO\"\n printf \"%s\\n\" $ answer"}, {"source_code": "solve :: String -> String -> Bool\nsolve a b = solve' a b '\\0'\n\nsolve' :: String -> String -> Char -> Bool\nsolve' \"\" \"\" _ = True\nsolve' _ \"\" _ = False\nsolve' \"\" (b:bs) c = b == c && solve' \"\" bs c\nsolve' (a:as) (b:bs) c\n | a == b = solve' as bs a\n | b == c = solve' (a:as) bs c\n | otherwise = False\n\nboolstr :: Bool -> String\nboolstr True = \"YES\"\nboolstr False = \"NO\"\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let readans = (solve <$> getLine <*> getLine) >>= (putStrLn . boolstr)\n sequence $ replicate n readans\n return ()\n\n"}], "negative_code": [], "src_uid": "6709c8078cd29e69cf1be285071b2527"} {"source_code": "import Data.IntMap (IntMap, empty, alter, elems, findWithDefault)\r\n\r\nreadArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\nfromList :: [Int] -> IntMap Int\r\nfromList [] = empty\r\nfromList (x: xs) = alter (\\x -> case x of\r\n Nothing -> Just 1\r\n Just a -> Just (a + 1)) x (fromList xs)\r\n\r\ncalcH :: [Int] -> Int -> Int\r\ncalcH a x = if sum (map (\\i -> if i < x then (x - i) `div` 2 else (x - i)) a) >= 0\r\n then x\r\n else calcH a (x + 1)\r\n\r\ncalc :: [Int] -> Int\r\ncalc a = calcH a 1\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: m: _) <- readArr\r\n a <- readArr\r\n let x = map (\\i -> findWithDefault 0 i (fromList a)) [1..n]\r\n print $ calc x\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n", "positive_code": [{"source_code": "-- \n{-# LANGUAGE BlockArguments #-}\n{-# LANGUAGE DatatypeContexts #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NumericUnderscores #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- {-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}\n\n\nimport Control.Arrow ((>>>))\nimport Control.Monad (\n MonadPlus (mplus),\n foldM_,\n forM_,\n guard,\n join,\n replicateM,\n replicateM_,\n )\nimport qualified Control.Monad as M\nimport qualified Control.Monad.ST.Strict as ST\nimport qualified Control.Monad.State.Strict as S\nimport qualified Control.Monad.Trans.Class as T\n\nimport qualified Data.Array as A\nimport qualified Data.Array.MArray.Safe as MA\nimport qualified Data.Array.IO.Safe as IOA\nimport qualified Data.Array.ST.Safe as STA\nimport qualified Data.Array.Unboxed as UA\n\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Char\nimport Data.Int\n\nimport Data.Function (on)\nimport Data.Functor ((<&>))\nimport Data.Bifunctor (bimap)\nimport Data.Maybe (fromJust, fromMaybe, isJust)\nimport qualified Data.Maybe as MB\n\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.List as L\nimport Data.List (\n elemIndices,\n find,\n findIndices,\n intersect,\n isPrefixOf,\n nub,\n sort,\n sortOn,\n )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.Ix as Ix\nimport qualified Data.Ratio as R\n\nimport Control.Monad.Cont (MonadIO (liftIO))\nimport Data.IORef (modifyIORef, newIORef, readIORef)\nimport GHC.IO.Handle (hDuplicateTo)\nimport System.IO (\n IOMode (ReadMode, WriteMode),\n openFile,\n stdin,\n stdout,\n hFlush\n )\nimport System.Posix.Internals (puts)\nimport Text.Printf (printf)\nimport qualified Data.Array.IO.Safe as UOA\n\n\n-- import Debug.Trace (trace, traceM, traceShowM)\n-- debug = flip trace\n--\n-- tracing t x = trace (t ++ \" = \" ++ show x) x\n-- debugging x t = tracing t x\n--\n-- debug x t = x\n-- trace t x = x\n-- tracing t x = x\n-- debugging x t = x\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = B8.readInt >>> (fst . fromJust)\n\n\nreadIntB8s :: B8.ByteString -> [Int]\nreadIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))\n\n\nreadIntegerB8 :: B8.ByteString -> Integer\nreadIntegerB8 = B8.readInteger >>> (fst . fromJust)\n\n\nreadIntegerB8s :: B8.ByteString -> [Integer]\nreadIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))\n\n\nmodifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray arr ix f = do\n value <- MA.readArray arr ix\n MA.writeArray arr ix $ f value\n\n\nputsYesNo :: Bool -> IO ()\nputsYesNo value = do\n let result :: String =\n if value\n then \"YES\"\n else \"NO\"\n printf \"%s\\n\" result\n\n{- END OF GENERAL -}\n\nfindLowerBound :: (Int -> Bool) -> (Int, Int) -> Int\nfindLowerBound f (l, r) | l == r = l\nfindLowerBound f (l, r) = if f c\n then findLowerBound f (l, c)\n else findLowerBound f (c + 1, r)\n where\n c = (l + r) `div` 2\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n m as = answer\n where\n answer = findLowerBound canSchedule (1, 2 * m)\n \n canSchedule :: Int -> Bool\n canSchedule t = ST.runST $ do\n timeLeftA <- MA.newArray (1, n) t :: ST.ST s (STA.STUArray s Int Int)\n tasksLeft <- flip S.execStateT 0 $ do\n forM_ as $ \\a -> do\n workerTimeLeft <- T.lift $ MA.readArray timeLeftA a\n if workerTimeLeft > 0\n then T.lift $ modifyArray timeLeftA a pred\n else S.modify succ\n workersTasksLeft <- MA.getElems timeLeftA <&> sum . map (`div` 2)\n return $ tasksLeft <= workersTasksLeft\n\n\nmain :: IO ()\nmain = do\n t <- B8.getLine <&> readIntB8\n replicateM_ t $ do\n [n, m] <- B8.getLine <&> readIntB8s\n as <- B8.getLine <&> readIntB8s\n let answer = solve n m as\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "import Data.IntMap (IntMap, empty, alter, elems, findWithDefault)\r\n\r\nreadArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\nfromList :: [Int] -> IntMap Int\r\nfromList [] = empty\r\nfromList (x: xs) = alter (\\x -> case x of\r\n Nothing -> Just 1\r\n Just a -> Just (a + 1)) x (fromList xs)\r\n\r\ncalcH :: [Int] -> Int -> Int\r\ncalcH a x = if sum (map (\\i -> if i < x then x - i else 2 * (x - i)) a) >= 0\r\n then x\r\n else calcH a (x + 1)\r\n\r\ncalc :: [Int] -> Int\r\ncalc a = calcH a 1\r\n\r\nshrinkH :: Int -> [Int]\r\nshrinkH 0 = []\r\nshrinkH i = (0: shrinkH (i - 1))\r\n\r\nshrink :: Int -> [Int] -> [Int]\r\nshrink n a = shrinkH (n - length a) ++ a\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: m: _) <- readArr\r\n a <- readArr\r\n let x = map (\\i -> findWithDefault 0 i (fromList a)) [1..n]\r\n print $ calc x\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n"}, {"source_code": "import Data.IntMap (IntMap, empty, alter, elems)\r\n\r\nreadArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\nfromList :: [Int] -> IntMap Int\r\nfromList [] = empty\r\nfromList (x: xs) = alter (\\x -> case x of\r\n Nothing -> Just 1\r\n Just a -> Just (a + 1)) x (fromList xs)\r\n\r\ncalcH :: [Int] -> Int -> Int\r\ncalcH a x = if sum (map (\\i -> if i < x then x - i else 2 * (x - i)) a) >= 0\r\n then x\r\n else calcH a (x + 1)\r\n\r\ncalc :: [Int] -> Int\r\ncalc a = calcH a 0\r\n\r\nshrinkH :: Int -> [Int]\r\nshrinkH 0 = []\r\nshrinkH i = (0: shrinkH (i - 1))\r\n\r\nshrink :: Int -> [Int] -> [Int]\r\nshrink n a = shrinkH (n - length a) ++ a\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: m: _) <- readArr\r\n a <- readArr\r\n let x = shrink n (elems $ fromList a)\r\n print $ calc x\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readLn :: IO Int\r\n for n"}], "src_uid": "87302bcc6c8f239641ab6f6dbeeae09c"} {"source_code": "main = interact $ show.maximum.f.map (map read.words).tail.lines\n\nf = scanl (\\s x->s-head x+last x) 0\n", "positive_code": [{"source_code": "main = print . solve . pairs . map read . tail . words =<< getContents\npairs (x:y:zs) = (x,y) : pairs zs\npairs _ = []\nsolve = maximum . scanl stop 0\nstop n (a,b) = n - a + b\n"}, {"source_code": "solve :: Int -> [Int] -> Int\nsolve a [] = 0\nsolve a (x:y:xs) = max a $ solve (a-x+y) xs\n\nreadInt :: String -> Int\nreadInt = read\n\nparse :: String -> String\nparse x = show $ solve 0 $ tail $ map readInt $ words x\n\nmain = interact parse"}, {"source_code": "solve :: [(Integer, Integer)] -> Integer\nsolve stops = getCapacity stops 0\ngetCapacity :: [(Integer, Integer)] -> Integer -> Integer\ngetCapacity [] n = n\ngetCapacity ((pOut, pIn):xs) n = max newCap $ getCapacity xs newCap\n where newCap = n - pOut + pIn\n\nmain = do\n count <- getLine\n stops <- mapM readStops [1..read count]\n print $ solve stops\n \nreadStops _ = do\n str <- getLine\n let [a,b] = map read . words $ str\n return (a,b)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nlistToT2 (x:y:_) = (x,y)\n\nmain = do\n n <- read <$> getLine :: IO Int\n ts <- replicateM n $ (listToT2.(map read).words) <$> getLine\n print $ snd$solve ts \n return ()\n\nsolve :: [(Int,Int)] -> (Int,Int)\nsolve xs = foldl apply (0,0) xs\n where\n apply :: (Int,Int) -> (Int,Int) -> (Int,Int)\n apply (sum,maxi) (a,b) = (newsum, max maxi newsum)\n where newsum = sum + b - a\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nbusstop :: [Int] -> Int\nbusstop (a:b:[]) = b - a\nbusstop _ = error \"WTF\"\n\nsolve :: [[Int]] -> Int\nsolve = maximum . scanl1 (+) . map busstop\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n a <- replicateM n getIntList\n putStrLn . show $ solve a\n"}, {"source_code": "module Main where\nimport Data.List\nimport Control.Applicative\ncalcLineDif :: String -> Int\ncalcLineDif str = let [s1,s2] = words str; (i1,i2) = (read s1, read s2) in i2 - i1\n\nsumPassangers :: (Int,Int) -> Int -> (Int,Int)\nsumPassangers (maxi,cur) newPassangers = let newCur = cur + newPassangers in if newCur > maxi then (newCur,newCur) else (maxi,newCur)\n\nmain = do\n stops <- (read :: String -> Int) <$> getLine\n print =<< fst <$> foldl sumPassangers (0,0) <$> mapM (\\_ ->calcLineDif <$> getLine) [1..stops]\n"}, {"source_code": "run = foldr (\\(a:b:_) rest -> (-a + b) : rest) []\nmain = interact $ show . maximum . scanl (+) 0 . run . map (map read . words) . tail . lines"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n input <- getContents\n let pairs = map muhParse $ take n $ lines input\n let changes = map (\\(x,y) -> y-x) pairs\n let partSums = partSum changes\n let answer = maximum partSums\n putStrLn $ show answer\n\n\nmuhParse :: String -> (Int,Int)\nmuhParse s = (a,b) where a:b:[] = (map read $ words s :: [Int])\n\npartSum :: [Int] -> [Int]\npartSum xs = [sum $ take n xs | n <- [1..length xs + 1]]"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntype Z = Integer\n\nmyRead :: IO (Z,Z)\nmyRead = (\\[a,b] -> (a,b)) . map read . words <$> getLine\n\niDiff :: (Z,Z) -> Z\niDiff (a,b) = b-a\n\ntraceS x y = trace (show x) y\n\nsolve :: [(Z,Z)] -> Z\nsolve abs = maximum rs \n where rs = solve' 0 abs\n\nsolve' :: Z -> [(Z,Z)] -> [Z]\nsolve' _ [] = []\nsolve' x (ab:abs) = x' : solve' x' abs \n where x' = x + iDiff ab\n\nmain = do\n n <- read <$> getLine\n abs <- replicateM n myRead\n print $ solve abs"}, {"source_code": "solve [] prev = prev\nsolve ((a, b):xs) prev = (max y (solve xs y)) where y = prev - a + b\n\nmain :: IO()\nmain = do\n n <- getLine\n contents <- getContents\n let input = map ((\\(a:b:_) -> (a, b)) . map (read :: String -> Int) . words) $ lines contents\n print(solve input 0)\n"}, {"source_code": "solve :: [(Int, Int)] -> Int -> Int\nsolve [] prev = prev\nsolve ((a, b):xs) prev = (max (prev - a + b) (solve xs (prev - a + b)))\n\nmain :: IO()\nmain = do\n n <- getLine\n contents <- getContents\n let input = map ((\\(a:b:_) -> (a, b)) . map (read :: String -> Int) . words) $ lines contents\n print(solve input 0)\n"}, {"source_code": "import Control.Monad (foldM)\nmain = do\t\n n <- read `fmap` getLine\n (_, m) <- foldM (\\(all, m) _ -> do\n [ai, bi] <- (map read . words) `fmap` getLine\n let all' = ((all - ai) `max` 0) + bi\n return (all', max m all')) (0, 0) [1..n]\n print m\n"}, {"source_code": "main = interact $ show . maximum . scanl (+) 0 . map ((\\[x,y] -> y - x) . map read.words) . tail . lines\n \n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Control.Monad\nimport Data.Array\nimport Data.Char\nclass Expression a where scan' :: String -> a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\nsolve :: [(Int, Int)] -> Int -> Int -> Int\nsolve [] _ n = n\nsolve ((out,enter):xs) m n = let m' = m + enter - out in\n solve xs m' (max n m')\n\nmain = do n <- scan :: IO Int\n l <- scans n :: IO [(Int, Int)]\n print (solve l 0 0)"}, {"source_code": "main = interact$show.maximum.scanl1 (+).map (negate.foldl1 (-).map read.words).tail.lines\n"}, {"source_code": "\ngetList :: [Int] -> [(Int,Int)]\ngetList [] = []\ngetList (v1:v2:vs) = [(v1,v2)] ++ getList vs \n\nmain = do\n str <- getContents\n let\n n:values = map read $ words str\n res = foldl (\\(cur,cap) (down,up) -> ((cur-down+up),(max cap (cur-down+up)))) (0,0) $ getList values\n putStrLn $ show $ snd res\n"}, {"source_code": "module Main (main) where\n\npeak :: [(Int, Int)] -> Int\npeak = maximum . scanl f 0\n where f a (from, to) = a - from + to\n\nmain :: IO ()\nmain = do cont <- getContents\n let a = fmap ((\\[a, b] -> (read a, read b)) . words) $ tail $ lines cont\n print $ peak a"}, {"source_code": "main = interact $ show . maxCap (0,0) . map read . tail . words\n\nmaxCap (_,m) [] = m\nmaxCap (s,m) (d:u:ls) = maxCap (new, max m new) ls\n where new = s-d+u\n"}, {"source_code": "main :: IO ()\nmain = do\n n <- getLine\n getPassengers 0 0 $ read n\n\ngetPassengers :: Int -> Int -> Int -> IO ()\ngetPassengers capacity 0 0 = print capacity >>= return\ngetPassengers _ n 0 =\n print \"getPassgeners: Passenger on last stop!\" >>= return\ngetPassengers capacity current n = do\n passengers <- getLine\n let [exit,enter] = map read $ words passengers\n current' = current - exit + enter\n if current' > capacity\n then getPassengers current' current' $ n - 1\n else getPassengers capacity current' $ n - 1\n"}, {"source_code": "import Control.Monad\nsplit [] r = r\nsplit (x:y) r \n | not (x == ' ') = split y ((init r) ++ [(last r) ++ [x]])\n | otherwise = split y (r ++ [\"\"])\ntoInt r = [read x::Int | x <- r]\n\ngo :: [[Int]] -> Int -> [Int] ->[Int]\ngo [] x y = y\ngo (r1:r2) x y = go r2 (x - (r1!!0) + (r1!!1)) ((x - (r1!!0) + (r1!!1)):y)\nsolve :: [[Int]] -> [Int]\nsolve r = go r 0 []\n\n \nmain = do\n nn <- getLine\n let n = read nn :: Int\n ip <- replicateM n getLine\n --print ip\n let ip2 = [toInt (split x [\"\"]) | x <- ip]\n --print ip2\n let r = solve ip2\n print (maximum r)"}, {"source_code": "module Main (main) where\n\nimport System.Environment\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [Int] -> Int\nsolve array = maxValue - minValue\n where\n maxValue = maximum list2\n minValue = minimum list2\n list = [i*x | (i,x) <- zip (cycle [1,-1]) array]\n list2 = scanl (+) 0 list :: [Int]\n\n\nmain = interact$show.solve.map read.tail.words\n"}, {"source_code": "module Main (main) where\n\nimport System.Environment\nimport Data.Char\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\n\nsolve :: [Int] -> Int\nsolve array = maxValue - minValue\n where\n maxValue = maximum list2\n minValue = minimum list2\n list = [if i `mod` 2 == 0 then -x else x | (i,x) <- zip [1..] array]\n list2 = scanl (+) 0 list :: [Int]\n\nmain = interact$show.solve.map read.tail.words\n"}, {"source_code": "read_int :: String -> Int\nread_int = read\n\nget_max :: Int -> Int -> [String] -> Int\nget_max curr m [] = m\nget_max curr m (s:ss) =\n let nums = map read_int $ words s\n a = nums !! 0\n b = nums !! 1\n newCurr = curr-a+b\n in get_max (newCurr) (max newCurr m) ss\n\nsolve :: [String] -> Int\nsolve = get_max 0 0\n\nmain = interact $ show . solve . tail . lines\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nmain= do\n\tgetLine \n\ts<-map (map read ). (map words).lines <$> getContents\n\tprint $ maximum $ scanl (+) 0 $ map (\\(a:b:[]) -> b-a) s\n\t"}, {"source_code": "{-\nA. Tram\n=========\ntime limit per test: 2 seconds\nmemory limit per test: 256 megabytes\ninput: standard input\noutput: standard output\n\nLinear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.\n\nYour task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.\n\nInput\n-----\nThe first line contains a single number n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of the tram's stops.\n\nThen n lines follow, each contains two integers ai and bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement.\n\nThe number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1\u2009=\u20090.\nAt the last stop, all the passengers exit the tram and it becomes empty. More formally, .\nNo passenger will enter the train at the last stop. That is, bn\u2009=\u20090.\n\nOutput\n-------\nPrint a single integer denoting the minimum possible capacity of the tram (0 is allowed).\n\nSample test(s)\n--------------\ninput\n```\n4\n0 3\n2 5\n4 2\n4 0\n```\noutput\n```\n6\n```\n\nNote\n-----\nFor the first example, a capacity of 6 is sufficient:\n\n- At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.\n- At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now.\n- At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now.\n- Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.\n\nSince the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.\n\n-}\n\ntramCapacity :: [[Int]] -> Int\ntramCapacity xss = maximum $ scanl (\\acc [minus, plus] -> acc + plus - minus) 0 xss\n\nreader :: String -> [[Int]]\nreader s = [map read $ words line | line <- xs]\n where _:xs = lines s\n\nmain = do \n input <- getContents\n let xss = reader input\n print $ tramCapacity xss\n"}, {"source_code": "main = do\n m <- readLn\n tp <- sequence $ replicate m getLine\n let tp2 = map (map read . words) tp\n let tp3 = map (\\[x,y] -> y -x) tp2\n let tp4 = [sum $ take i tp3 | i <- [1..m]]\n print $ maximum tp4"}, {"source_code": "import Control.Monad\nfolder :: (Int, Int) -> (Int, Int) -> (Int, Int)\nfolder (a, m) (d, u) =\n let a' = a + u - d\n in (a', max m a')\n\ntupler :: [Int] -> (Int, Int)\ntupler (a:b:rest) = (a, b)\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n (0, ans) <- foldl folder (0, 0) . map (tupler . map (read :: String -> Int) . words) <$> replicateM n getLine\n print ans\n "}, {"source_code": "main = interact $ show . maximum . scanl (+) 0 . map ((\\[x, y] -> y - x) . map read . words) . tail . lines\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nf :: [Int] -> [Int]\nf [] = []\nf (x:xs) = (x + sum xs) : f xs\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- map ((\\(x:y:_) -> -x + y ) .map read . words) <$> (sequence $ replicate n getLine) :: IO [Int]\n putStrLn . show . maximum . f . reverse $ xs\n"}, {"source_code": "module Main (main) where\n\npeak :: [(Int, Int)] -> Int\npeak = maximum . scanl f 0\n where f a (from, to) = a - from + to\n\nmain :: IO ()\nmain = do cont <- getContents\n let a = fmap ((\\[a, b] -> (read a, read b)) . words) $ tail $ lines cont\n print $ peak a"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = getLine >>=\n (flip replicateM $ getLine >>= return.map read.words).read >>=\n putStrLn.show.solve.reverse\n\nsolve :: [[Int]] -> Int\nsolve input = maximum.diffs $ ticks input\n\nticks :: [[Int]] -> [Int]\nticks input = filter (/=0) $ map (\\[a, b] -> b - a) input\n\ndiffs :: [Int] -> [Int]\ndiffs [] = [0]\ndiffs (a:as) = (sum (a:as)):(diffs as)\n"}, {"source_code": "import Data.List\n\nprocess :: [(Int,Int)] -> Int\nprocess = maximum . scanl' (\\acc (a,b) -> acc+b-a) 0\n\nreadInt :: String -> Int\nreadInt = read\n\nreadPair :: String -> (Int,Int)\nreadPair line = (a,b)\n where [a,b] = map readInt $ words line\n\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readPair . lines) getContents\n print $ process xs"}, {"source_code": "import Data.Char\nimport Data.List\n\nans a = maximum $ scanl (\\x y->x-head y+last y) 0 a\n\nmain = do \n n<-getLine\n a<-getContents\n let input = map (map (\\x->read x::Int)) (map words $ lines a)\n print $ ans input"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = print =<< solve . map f . tail . lines <$> getContents where\n f = (\\(x:y:_) -> (y - x)) . map read . words\n\nsolve :: [Int] -> Int\nsolve = foldl max 0 . scanl (+) 0"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = interact $ show . maximum . scanl (+) 0 . map ((\\(x:y:_) -> (y - x)) . map read . words) . tail . lines \n"}, {"source_code": "import Control.Applicative\n\nmain :: IO ()\nmain = interact $ show . foldl max 0 . scanl (+) 0 . map ((\\(x:y:_) -> (y - x)) . map read . words) . tail . lines \n"}, {"source_code": "\nimport Control.Monad\n\ntoInt :: String -> Int\ntoInt = read\n\ntoTuple :: String -> (Int, Int)\ntoTuple s = ( head x, last x )\n\t\t\twhere \tx = ( (map (toInt) ) . words ) s\n\nfindMaxCapacity :: [( Int, Int )] -> Int\nfindMaxCapacity xs \t= snd ( foldl f (0,0) xs )\n\t\t\t\t\twhere f (a1, a2) (x1, x2) = ( tmp, max a2 tmp)\n\t\t\t\t\t\t\t\t\t\t\t\twhere tmp = a1 - x1 + x2\t\t\t\nmain = do\n\tstrN \t\t<- getLine\n\tinoutData \t<- replicateM (toInt strN) getLine\n\tprint $ \tfindMaxCapacity ( map toTuple inoutData )\n\t\n\n\n\n\n\n\n"}, {"source_code": "main = interact $ show . f 0 0 . map read . tail . words\n\nf a b [] = b\nf a b (x:y:xs) = f (a-x+y) (max b (a-x+y)) xs\n"}, {"source_code": "solve :: String -> String\nsolve = show . capacity . fmap (fmap read . words) . tail . lines\n\ncapacity :: [[Int]] -> Int\ncapacity = maximum . scanl (\\ acc (x : y: _) -> acc - x + y) 0\n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "main = do\n n <- getLine\n xs <- sequence $ replicate (read n::Int) getLine\n putStrLn $ show $ maximum $ scanl (+) 0 $ map (\\[x , y] -> -(read x::Int) + read y::Int) $ map words xs\n\n"}, {"source_code": "tram :: [[Int]] -> Int\ntram = let func (curr, m) [x, y] = if next > m then (next, next) else (next, m)\n \t where next = curr - x + y \n \t in snd . foldl func (0, 0)\n\nreadInt :: String -> Int\nreadInt = read\n\nparse :: String -> String\nparse = show . tram . map (\\line -> map readInt $ words line) . lines\n\nmain = do\n\tgetLine\n\tinteract parse"}, {"source_code": "module Main where\n\n\n--71A\n--replicateM n x = sequence (replicate n x)\n\n--processWord :: String -> String\n--processWord word | length word > 10 = (head word) : (show (length word - 2)) ++ ((last word):[])--(word !! ((length word) - 1))\n-- | otherwise = word\n\n--main = sequence [putStrLn $ show i | i <- [1..5]]\n--main = getLine >>= \\line -> replicateM (read line) (getLine) >>= \\list -> sequence [putStrLn (processWord (list!!i)) | i <- [0..(length list) - 1]]\n\n\n\n\n--118A\n--import Data.Char\n--isSylable :: Char -> Bool\n--isSylable char = elem char \"AOYEUIaoyeui\"\n--\n--deleteSylabls::[Char] -> [Char]\n--deleteSylabls [] = []\n--deleteSylabls (x:xs) | isSylable x = deleteSylabls xs\n-- | otherwise = x:(deleteSylabls xs)\n--\n--addDots :: [Char] -> [Char]\n--addDots [] = []\n--addDots (x:xs) = '.' : x : (addDots xs)\n--\n--processWord :: String -> String\n--processWord = addDots . deleteSylabls . (map toLower)\n--\n--main = getLine >>= putStrLn . processWord\n\n\n\n\n--50A\n\n--split :: Char -> String -> [String]\n--split _ [] = [\"\"]\n--split c (x:xs) | x == c = \"\" : rest\n-- | otherwise = (x : head rest): tail rest\n-- where rest = split c xs\n--\n--calc :: Int -> Int -> Int\n--calc m n = m*n `div` 2\n--\n--main = getLine >>= \\a -> let inp = (map read (split ' ' a)) in putStrLn $ show $ calc (inp !! 0) (inp !! 1)\n\n\n--231A\n\n--split :: Char -> String -> [String]\n--split _ [] = [\"\"]\n--split c (x:xs) | x == c = \"\" : rest\n-- | otherwise = (x : head rest): tail rest\n-- where rest = split c xs\n--\n--isGood :: [Int] -> Int\n--isGood (a:b:c:[]) = if (a+b+c >= 2) then 1 else 0\n--\n--toIntList :: [[String]] -> [[Int]]\n--toIntList strs = map (map read) strs\n--\n--main = getLine >>= \\line -> sequence (replicate (read line) getLine) >>= \\list -> putStrLn $ show $ sum $ map isGood (toIntList (map (split ' ') list))\n\n--B158\n--split :: Char -> String -> [String]\n--split _ [] = [\"\"]\n--split c (x:xs) | x == c = \"\" : rest\n-- | otherwise = (x : head rest): tail rest\n-- where rest = split c xs\n--\n--countEntries :: [Int] -> Int -> Int\n--countEntries [] _ = 0\n--countEntries (x:xs) val | x == val = 1 + rest\n-- | otherwise = rest\n-- where rest = (countEntries xs val)\n--\n--findSol :: [Int] -> Int\n--findSol groups = let\n-- gr = countEntries groups\n-- fours = gr 4\n-- threes = gr 3\n-- twos = gr 2\n-- ones = gr 1\n-- threeToOne = min threes ones\n-- twosToTwos = twos `div` 2\n-- unpairThrees = threes - threeToOne\n-- unpairOnes = ones - threeToOne + ((twos `mod` 2)*2)\n-- in\n-- fours + threeToOne + twosToTwos + ((unpairOnes `div` 4) + (if unpairOnes `mod` 4 /= 0 then 1 else 0)) + unpairThrees\n--\n--\n--\n--main = getLine >> getLine >>= \\a -> let groups = (map read (split ' ' a) :: [Int]) in putStrLn $ show $ findSol groups\n\n--A282\n--parse :: String -> Int\n--parse \"X++\" = 1\n--parse \"++X\" = 1\n--parse \"--X\" = -1\n--parse \"X--\" = -1\n--\n--main = getLine >>=\n-- \\amount -> sequence (replicate (read amount) getLine) >>=\n-- \\sentenses -> putStrLn $ show $ sum (map parse sentenses)\n\n--A116\n\ndata Stop = Stop {out:: Int, inp::Int} deriving Show\n\n\nsplit :: Char -> String -> [String]\nsplit _ [] = [\"\"]\nsplit c (x:xs) | x == c = \"\" : rest\n | otherwise = (x : head rest): tail rest\n where rest = split c xs\n\nreadStop :: String -> Stop\nreadStop str = let vals = map read (split ' ' str) :: [Int] in Stop (vals!!0) (vals!!1)\n\nmain = getLine >>=\n \\ stopsAmount -> sequence (replicate (read stopsAmount) getLine) >>=\n \\ stopsStr ->\n let\n stops = map readStop stopsStr\n people = \\i -> if i == 0 then inp (stops!!i) else (inp (stops!!i)) - (out (stops!!i)) + (people (i-1))\n minCapacity = \\i min -> if i >= length stops then min else (if min < people i then minCapacity (i+1) (people i) else minCapacity (i+1) min)\n in\n putStrLn $ show (minCapacity 0 0)"}, {"source_code": "\ntram [] cur m = m\ntram ((a,b):xs) cur m = tram xs c' (max m c')\n where c' = cur-a+b\n\n\nmain = do\n d <- getContents\n let (n:ls) = lines d\n let xs = map (\\[a,b] -> (a,b)) $ map (map read . words) ls\n print $ tram xs 0 0\n"}, {"source_code": "main = interact $ show . maximum . scanl (+) 0 . map ((\\[x,y] -> y - x) . map read.words) . tail . lines\n \n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- fmap read getLine\n a <- replicateM n $ fmap (foldl1 subtract . map read . words) getLine\n print $ maximum $ scanl1 (+) a\n"}, {"source_code": "module Main (main)\n where\n\nimport Control.Monad (replicateM)\n\n\nmain :: IO ()\nmain = print . capacity . map readLine =<< flip replicateM getLine =<< readLn\n where capacity = maximum . scanl (\\c [a,b] -> c - a + b) 0\n readLine = map read . words"}, {"source_code": "main = do\n getLine\n interact (solve.(map (map read)).(map words).lines)\nsolve x = show(result 0 0 x)\nresult max acc ([x,y]:xs)\n |acc>max = result acc acc ([x,y]:xs)\n |xs/=[] = result max (acc-x+y) xs\n |otherwise = max"}, {"source_code": "module Main where\n\nimport Control.Monad\n\nmain = do\n n <- liftM read getLine\n (_, res) <- foldM (\\(curr, need) _ -> do\n [a, b] <- liftM (map read . words) getLine\n let curr' = curr - a + b\n need' = max need curr'\n return (curr', need')\n ) (0, 0) [1..n]\n\n putStrLn $ show res\n"}, {"source_code": "module Main where\n\nprocess :: Int -> Int -> Int -> IO Int\nprocess 0 cap max = return max\nprocess n cap max = do\n s <- getLine\n let [x,y] = words s\n let outT = read x :: Int\n let inT = read y :: Int\n let cap' = (cap - outT) + inT\n if (cap' > max)\n then\n process (n - 1) cap' cap'\n else\n process (n - 1) cap' max\n\nmain :: IO ()\nmain = do\n s <- getLine\n let n = read s :: Int\n res <- process n 0 0\n print res"}, {"source_code": "main = do\n\tdat <- getContents\n\tlet allLines = tail $ lines dat\n\tputStrLn $ show $ answer $ parse $ (map words allLines)\n\nanswer xs = foldl1 (max) $ scanl (\\acc x -> acc - (head x) + (last x)) 0 xs\n\nparse :: [[String]] -> [[Integer]]\nparse = map (map ((+ 0) . read)) "}, {"source_code": "\nmain = do\n\tn<-getLine\n\treading (read n) []\n\t\n\nreading 0 acc = putStrLn $ show $ solve 0 0 $ map (map read) (map words $ acc)\nreading n acc = do\n\tt<-getLine\n\treading (n-1) (acc++[t])\n\nsolve::Int->Int->[[Int]]->Int\nsolve m n [] = m\nsolve m n (k:ks) = solve (max m n1) n1 ks\n where n1=n-head k + last k"}, {"source_code": "\n--stringToInts :: String -> [Int]\n--stringToInts str = \n--\tmap readInt (words str)\n--\twhere readInt = read :: String -> Integer\nstringToInts :: String -> IO [Integer]\nstringToInts str = \n\treturn $ map readInt (words str)\n\twhere readInt = read :: String -> Integer\n\t--where readInt = read :: String -> Integer\n\ninvoke :: Integer -> Integer -> IO Integer\ninvoke n cur = \n\tif n == 0 then return $ cur\n\telse do\n\t\tnext_line <- getLine\n\t\tlst <- stringToInts next_line\n\t\t--let new_cur = cur - (lst !! 0) + (lst !! 1) in\n\t\tinvoke_result <- invoke (n - 1) (cur - (lst !! 0) + (lst !! 1))\n\t\treturn $ max cur invoke_result\n\nmain = do\n\t--print $ max 4 5\n\t--tmp <- stringToInts \"123 456\"\n\t--print $ tmp\n\tn <- getLine\n\tresult <- invoke (read n :: Integer) 0\n\tprint $ result\n\t"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport IO\n\nmain = do\n\tlet lns = fmap C.lines $ C.hGetContents stdin\n\tinput <- fmap (map (map (fst . fromJust . C.readInt)) . map C.words) $ lns\n\tlet n = (head . head) input\n\tlet ls = (take n . tail) input\n\t(putStrLn . show . fst . foldl (\\(m,c) y -> (max m (c+y), c+y)) (0,0)) $ map (\\[x,y] -> y - x) ls\n"}, {"source_code": "{-# OPTIONS -O2 #-}\nimport Data.Char\n\nmain = do\n s <- getContents\n let \n nums = map read $ words s :: [Int]\n n = head nums\n (as, bs) = gather $ tail nums\n print $ solve as bs 0 0\n\nsolve :: [Int] -> [Int] -> Int -> Int -> Int\nsolve [] [] _ n = n\nsolve (a:as) (b:bs) n m = solve as bs (n-a+b) (max m (n-a+b))\n\ngather [] = ([], [])\ngather (a:b:l) = (a:x, b:y)\n where\n (x, y) = gather l \n"}, {"source_code": "import Control.Monad\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- readLn\n a <- replicateM n $ (readItems :: IO [Int])\n putStrLn $ show $ maximum (scanl process 0 a)\n where process people [exit, enter] = people - exit + enter\n"}, {"source_code": "import Data.List\nmain = interact $ show . maximum . scanl1 (+) . map (\\ [a, b] -> b - a) . map (map read . words) . tail . lines"}, {"source_code": "solve :: Num a => [a] -> a -> [a]\nsolve (a:b:xs) cur = cur : solve xs (cur - a + b)\nsolve _ _ = []\n\nmain :: IO ()\nmain = do\n\tcs <- getContents\n\tlet ints = map read $ tail $ words cs :: [Int]\n\tprint $ maximum $ solve ints 0"}, {"source_code": "import Control.Monad (replicateM)\n\nreadNLines :: Int -> IO [String]\nreadNLines n = replicateM n getLine\n\nparseLine :: String -> (Int, Int)\nparseLine line = (read (w!!0) :: Int, read (w!!1) :: Int) where w = words line\n\nsolution :: Int -> [(Int, Int)] -> [Int]\nsolution p [] = [0]\nsolution p [(a, b)] = [p - a + b]\nsolution p (x:xs) = k ++ solution (head k) xs where k = solution p [x]\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n args <- readNLines n\n print $ maximum $ solution 0 $ map parseLine args"}, {"source_code": "main = do\n getLine\n ps <- fmap (map ((\\[a, b] -> (a, b)) . map read . words) . lines) getContents\n\n let\n (as, bs) = unzip ps\n s1 = scanl1 (+) as\n s2 = scanl1 (+) bs\n z = zipWith (-) s2 s1\n m = maximum z\n\n print m\n"}, {"source_code": "main = interact $ show.maximum.scanl1 (+).map (negate.foldl1 (-).map read.words).tail.lines\n\n"}, {"source_code": "import Data.List\nmain = interact $ gao.transpose.tail.map (map read.words).lines\ngao [x,y] = show.maximum.scanl1 (+).zipWith (-) y $ x\n\n"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n lines <- fmap (map $ map read . words) (replicateM n getLine) :: IO [[Int]]\n print $ maxCapacity lines 0\n\nmaxCapacity :: [[Int]] -> Int -> Int\nmaxCapacity [] acum = acum\nmaxCapacity (x:xs) acum = max acum $ maxCapacity xs $ acum - (x !! 0) + (x !! 1)\n\n"}, {"source_code": "import Control.Monad\nsolve :: [[Int]] -> [Int]\nsolve [] = [0]\nsolve (x : xs) = (head x) - (last x) + (head $ solve xs) : solve xs\nmain = do\n n <- readLn\n l <- replicateM n getLine\n print . maximum $ solve (map (map read . words) $ l)\n"}, {"source_code": "main = interact $ show . maximum . scanl1 (+) . map ((\\[x, y] -> y - x) . map read . words) . tail . lines"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\n(|>) x f = f x\n\nmain = interact process\n\nprocess contents = let\n ls = contents |> lines |> map words |> map (map read) :: [[Int]]\n in solve (tail ls) |> show\n \nsolve station = solve' 0 0 station\n\nsolve' maxSoFar current [] = maxSoFar\nsolve' maxSoFar current (x:xs) = let\n new = current - (x !! 0) + (x !! 1)\n newMax = maxSoFar `max` new\n in solve' newMax new xs\n"}, {"source_code": "getInput :: String -> [String]\ngetInput xs = tail $ lines xs\n\ntoInt :: String -> [Int]\ntoInt xs = [read x :: Int | x <- words xs]\n\nminCap :: [String] -> [Int]\nminCap [] = []\nminCap (x:xs) = (lxs - hxs) : minCap xs\n where pairs = toInt x\n hxs = head pairs\n lxs = last pairs\n\ntram :: [Int] -> [Int]\ntram [x] = [x]\ntram [] = []\ntram (x:y:xs) = x : tram accumxs\n where accumxs = (x + y) : xs\n\nmain :: IO ()\nmain = do n <- getContents\n putStr $ show $ maximum $ tram $ minCap $ getInput n\n"}, {"source_code": "solve = maximum . scanl (\\acc (a,b) -> acc-a+b) 0 \n\nmain = do\n\tv <- getContents\n\tprint . solve . map (\\[a,b] -> (a,b)) . map (map read) . map words . tail $ lines v"}, {"source_code": "import Control.Monad\nimport Control.Applicative\n\nmain = do\n n <- readLn\n s <- replicateM n $ map read . words <$> getLine\n print $ maximum (solve s 0)\n\nsolve [] _ = []\nsolve (x:xs) num = num: solve xs (num+(last x)-(head x))\n\n\n"}, {"source_code": "import Data.Char\nimport Data.List\n\ncapacity :: [Int] -> Int -> Int\ncapacity [] _ = 0\ncapacity (a:b:xs) c = max c (capacity xs (c + b - a))\n\nsolve :: [Int] -> Int\nsolve lst = capacity lst 0\n\nmain = interact $ show.solve.map read.tail.words"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- readLn \n sflow <- replicateM n getLine\n let flow = map (map (read :: String -> Integer) . words) sflow\n let cap = snd $ solve flow\n putStrLn $ show cap\n\nsolve flow = foldl (\\(cur, cmax) [gout, gin] -> \n (cur + gin - gout, max cmax (cur + gin - gout)) \n ) (0, 0) flow\n"}, {"source_code": "solve :: [Int] -> Int\nsolve x = foldr max 0 $ solve' x 0\n where solve' [] _ = []\n solve' (x:y:xs) m = let mm = m - x + y\n in mm : solve' xs mm\n\nmain :: IO()\nmain = do cs <- getContents\n let lst = map read $ words cs :: [Int]\n print $ solve $ tail lst\n"}, {"source_code": "main = readsolveprint\nreadsolveprint::IO()\nreadsolveprint = getLine >>= \\x-> interact $ show . solve. map (map read. words). take (read x) . lines\nsolve :: [[Int]]->Int\nsolve xs = maximum $ scanl (+) 0 $ [last x - head x| x <- xs]"}, {"source_code": "-- 116A\ntram :: [[Int]] -> Int\ntram xs = maximum (scanl (+) 0 (map weirdSum xs))\n where weirdSum xs = last xs - head xs \n\nreadIn :: IO [[Int]]\nreadIn = do\n contents <- getContents\n let n:ls = lines contents\n x = read $ head $ words n \n xs = take x $ map ((map read) . words) ls\n return xs\n\nmain :: IO()\nmain = do\n i <- readIn\n putStrLn $ show (tram i)\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nint x = read x ::Int \n\nminCapacity = maximum . scanl (+) 0 . (uncurry $ flip $ zipWith (-)) . unzip\n\nmain = do\n n <- liftM int getLine\n vs <- liftM (map ((\\[x,y] -> (x,y)) . map int. words)) $ replicateM n getLine \n print $ minCapacity vs\n"}, {"source_code": "solve :: [(Int, Int)] -> Int\nsolve = snd.(foldl (\\(cur, m) (a,b)-> let c = cur - a + b in (c, max c m)) (0,0))\n\nmain = do\n l <- getContents\n print $ solve . map (\\(a:b:[]) -> (a,b)) $ map (map (read::String->Int).words). tail $ lines l\n"}, {"source_code": "myReadLine :: IO (Int, Int)\nmyReadLine = do\n line <- getLine\n let [a, b] = map read (words line)\n return (a, b)\n\nsolve :: ([Int], [Int]) -> Int\nsolve (a, b) = maximum (scanl (+) 0 (zipWith (-) b a))\n\nmain = do\n n <- readLn::(IO Int)\n pair <- sequence (map (\\x -> myReadLine) [1..n])\n print (solve (unzip pair))\n"}, {"source_code": "-- Codeforces 116A\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n replicateM n getLine >>= putStrLn . show . solve . map (map read . words) where\n solve = fst . foldl (\\(m, acc) n -> ((max m (acc+n)), acc+n)) (0, 0) . map (\\x -> x!!1 - x!!0)\n"}, {"source_code": "main = interact $ show . f 0 0 . map read . tail . words\nf a b [] = b\nf a b (c:d:e) = f (a-c+d) (max b (a-c+d)) e"}, {"source_code": "module Main where\n\nimport Data.Complex\nimport Data.Char\nimport Data.List\nimport Data.Functor\nimport Control.Monad\n\ntype R = Double\ntype Z = Int\ntype B = Integer\ntype Q = Rational\ntype C = Complex\n\ntype A = Char\ntype S = String\n\nreadR = map read <$> words <$> getLine :: IO [R]\nreadR1 = head <$> readR\n\nreadZ = map read <$> words <$> getLine :: IO [Z]\nreadZ1 = head <$> readZ\n\nreadB = map read <$> words <$> getLine :: IO [B]\nreadB1 = head <$> readB\n\nmain :: IO ()\nmain = do\n n <- readZ1\n xs <- replicateM n readZ\n let ys = scanl f 0 xs\n print $ maximum ys\n where\n f acc (a:b:_) = acc + (b - a)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List (foldl')\n\nmain = do\n n <- read <$> getLine\n ls <- map (toTup . map read . words) <$> replicateM n getLine :: IO [(Int,Int)]\n print $ maximum . scanl (+) 0 . map (uncurry $ flip (-)) $ ls\n\ntoTup [x,y] = (x,y)"}, {"source_code": "import Data.List\nmain = interact $ show.snd.foldl' f (0, 0).map (map read.words).tail.lines\n where f (c, mx) [a, b] = let c' = c - a + b\n in (c', max mx c')\n"}, {"source_code": "main = do\n\tn <- getInt\n\tflux <- sequence $ map (\\i -> getIntArray) [2..n]\n\tlet res = snd $ foldl (\\acc e -> do\n\t\t\t\t\t\tlet curr = fst acc - e !! 0 + e !! 1\n\t\t\t\t\t\tlet top = max curr (snd acc)\n\t\t\t\t\t\t(curr, top)) (0, 0) flux\n\tputStrLn $ show res\n\t\ngetInt::IO Int\ngetInt = do\n\tint <- getLine\n\treturn . read $ int\n\t\ngetIntArray::IO [Int]\ngetIntArray = do\n\tarr <- getLine\n\treturn $ map readInt $ split arr ' '\n\t\nreadInt::String -> Int\nreadInt str = read str\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep\n\t\t\t\t\t\t\t\t\t\tthen \"\":acc\n\t\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc)) [\"\"] str\n\t\t\t\t\t\t\t\t\t\t"}, {"source_code": "main :: IO ()\nmain =\n interact $ show . maximum . f . (map ((\\x -> x !! 1 - x !! 0) . (map read) . words)) . tail . lines\n\nf :: Num a => [a] -> [a]\nf [] = []\nf (x:xs) = x : (map (+x) $ f xs)\n"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nbusstop :: [Int] -> Int\nbusstop (a:b:[]) = b - a\nbusstop _ = error \"WTF\"\n\nsolve :: [[Int]] -> Int\nsolve = maximum . scanl1 (+) . map busstop\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n a <- replicateM n getIntList\n putStrLn . show $ solve a\n \n"}, {"source_code": "-- Tram\nimport Data.List.Split\n\ntoInt :: String -> Int\ntoInt s = read s\n\ngetInts :: IO [Int]\ngetInts = do\n input <- getLine\n return $ map toInt $ splitOn \" \" input\n\n{-%\n solve :: Int -> [[Int]] -> Int\n solve ans [] = ans\n solve ans ((o:i:[]):xs) = max ans next\n where cur = ans - o + i\n next = max cur $ solve cur xs\n-}\n \nmain = do\n ints <- getInts\n let [n] = ints\n ints <- sequence $ replicate n getInts\n let sums = map (\\a -> foldl1 (-) $ reverse a) ints\n print (maximum $ scanl (+) 0 sums)\n"}, {"source_code": "main=interact$(show.maximum.(\\str -> scanl1 (+) $map (\\[a,b] -> read b-read a) $ tail$(\\x -> map words$lines x) str ))"}, {"source_code": "solve :: Int -> [Int] -> Int\nsolve x [] = x\nsolve cur (a:b:xs) = max cur $ solve (cur - a + b) xs\nmain = interact $ show . solve 0. map read . tail . words"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Data.Array\n\n\n\nmain::IO ()\nmain=do\n getLine\n a<-getContents\n let a1= map (\\[a,b]-> b-a) $ map (map read) $ map words $ lines a::[Int]\n print $ maximum $ scanl1 (+) a1\n"}, {"source_code": "main = do\n\tnumber <- getLine\n\tlet n = read number\n\tcalc n 0 0\n\ncalc :: Int -> Int -> Int -> IO ()\ncalc 0 _ maks = print maks\ncalc i sum maks = do\n\tinnn <- getLine\n\tlet exitt = read $ takeWhile (/= ' ') innn\n\tlet inn = read $ reverse $ takeWhile (/= ' ') $ reverse innn\n\tlet nsum = inn + sum - exitt\n\tcalc (i-1) nsum (max nsum maks)"}, {"source_code": "module Main where\n\nimport Control.Arrow\n\nimport Data.Maybe\nimport Data.ByteString.Char8 (lines,words,interact,readInt,pack)\nimport Prelude hiding (lines,words,interact)\nimport Data.List hiding (lines,words)\n\nmain = interact $ lines >>> tail >>>\n map (words >>> map (readInt >>> fromJust >>> fst) >>> foldl1' (-) >>> negate) >>>\n scanl1 (+) >>> maximum >>>\n show >>> pack"}, {"source_code": "main :: IO ()\nmain = getContents >>= print . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> Int\nsolve = maximum . scanl (+) 0 . map (\\[a, b] -> b - a)\n"}, {"source_code": "import Prelude hiding (readList)\nimport Control.Monad\n\nreadList :: Read a => IO [a]\nreadList = fmap (fmap read . words) getLine\n\nreadList' :: Read a => a -> IO [a]\nreadList' _ = readList\n\nshowList :: Show a => [a] -> IO ()\nshowList = putStrLn . unwords . map show\n\nskipLine :: IO ()\nskipLine = void $ getLine\n\ncount :: (a -> Bool) -> [a] -> Int\ncount f = length . filter f\n\ndivUp :: Integral a => a -> a -> a\ndivUp x y \n | x `mod` y /= 0 = x `div` y + 1\n | otherwise = x `div` y\n\ninterp :: Int -> [Int] -> Int\ninterp x [a,b] = x-a+b\n\nmain :: IO ()\nmain = do\n [n] <- readList' (undefined::Int)\n abs <- replicateM n $ readList' (undefined::Int)\n print $ maximum $ scanl interp 0 abs\n"}, {"source_code": "station :: Int -> [String] -> Int\nstation n [] = n\nstation n (x:xs) = max (station (n - a + b) xs) n\n where a = nums !! 0\n b = nums !! 1\n nums = map read . words $ x\n\nmain = do\n getLine\n interact $ show . station 0 . lines\n\n"}], "negative_code": [{"source_code": "\ngetList :: [Int] -> [(Int,Int)]\ngetList [] = []\ngetList (v1:v2:vs) = [(v1,v2)] ++ getList vs \n\nmain = do\n str <- getContents\n let\n n:values = map read $ words str\n res = foldl (\\x (down,up) -> max x (x-down+up)) 0 $ getList values\n putStrLn $ show res\n putStrLn $ show $ getList values\n"}, {"source_code": "\ngetList :: [Int] -> [(Int,Int)]\ngetList [] = []\ngetList (v1:v2:vs) = [(v1,v2)] ++ getList vs \n\nmain = do\n str <- getContents\n let\n n:values = map read $ words str\n res = foldl (\\x (down,up) -> max x (x-down+up)) 0 $ getList values\n putStrLn $ show res\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = getLine >>=\n (flip replicateM $ getLine >>= return.map read.words).read >>=\n putStrLn.show.solve\n\nsolve :: [[Int]] -> Int\nsolve input = maximum.diffs $ ticks input\n\nticks :: [[Int]] -> [Int]\nticks input = map (\\[a, b] -> b - a) input\n\ndiffs [] = [0]\ndiffs (a:[]) = [a]\ndiffs (a:as:al) = (a + as):diffs (as:al)\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain = getLine >>=\n (flip replicateM $ getLine >>= return.map read.words).read >>=\n putStrLn.show.solve.reverse\n\nsolve :: [[Int]] -> Int\nsolve input = maximum.diffs $ ticks input\n\nticks :: [[Int]] -> [Int]\nticks input = map (\\[a, b] -> a - b) input\n\ndiffs :: [Int] -> [Int]\ndiffs [a] = [a]\ndiffs (a:as) = (sum (a:as)):(diffs as)"}, {"source_code": "import Data.Char\nimport Data.List\n\nans a = maximum $ scanl (\\x y->x-head y+last y) 0 a\n\nmain = do \n n<-getLine\n a<-getContents\n let input = map (map (\\x->read x::Int)) (map words $ lines a)\n print input"}, {"source_code": "main = do\n\tdat <- getContents\n\tlet allLines = tail $ lines dat\n\tputStrLn $ show $ answer $ parse $ (map words allLines)\n\nanswer xs = foldl (\\acc x -> max acc (acc - (head x) + (last x))) 0 xs\n\nparse :: [[String]] -> [[Integer]]\nparse = map (map ((+ 0) . read)) "}, {"source_code": "\nmain = do\n\tn<-getLine\n\treading (read n) []\n\t\n\nreading 0 acc = putStrLn $ show $ solve 0 $ map (map read) (map words $ acc)\nreading n acc = do\n\tt<-getLine\n\treading (n-1) (acc++[t])\n\nsolve::Int->[[Int]]->Int\nsolve m [] = m\nsolve m (k:ks) = solve (max m (m-head k + last k)) ks"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe\nimport IO\n\nmain = do\n\tlet lns = fmap C.lines $ C.hGetContents stdin\n\tinput <- fmap (map (map (fst . fromJust . C.readInt)) . map C.words) $ lns\n\tlet n = (head . head) input\n\tlet ls = (take n . tail) input\n\t(putStrLn . show . foldl (\\x y -> max x $ (x+y)) 0) $ map (\\[x,y] -> y - x) ls\n"}, {"source_code": "{-# OPTIONS -O2 #-}\nimport Data.Char\n\nmain = do\n s <- getContents\n let \n nums = map read $ words s :: [Int]\n n = head nums\n (as, bs) = gather $ tail nums\n print $ solve as bs 0\n\nsolve [] [] n = n\nsolve (a:as) (b:bs) n = solve as bs (max n (n-a+b))\n\ngather [] = ([], [])\ngather (a:b:l) = (a:x, b:y)\n where\n (x, y) = gather l \n"}, {"source_code": "{-# OPTIONS -O2 #-}\nimport Data.Char\n\nmain = do\n s <- getContents\n let \n nums = map read $ words s :: [Int]\n n = head nums\n (as, bs) = gather $ tail nums\n print $ solve as bs 0\n\nsolve :: [Int] -> [Int] -> Int -> Int\nsolve [] [] n = n\nsolve (a:as) (b:bs) n = solve as bs (max n (n-a+b))\n\ngather [] = ([], [])\ngather (a:b:l) = (a:x, b:y)\n where\n (x, y) = gather l \n"}, {"source_code": "import Data.Char\n\nmain = do\n s <- getContents\n let \n nums = map read $ words s :: [Int]\n n = head nums\n (as, bs) = gather $ tail nums\n print $ solve as bs 0\n\nsolve [] [] n = n\nsolve (a:as) (b:bs) n = solve as bs (max n (n-a+b))\n\ngather [] = ([], [])\ngather (a:b:l) = (a:x, b:y)\n where\n (x, y) = gather l \n"}, {"source_code": "getInput :: String -> [String]\ngetInput xs = tail $ lines xs\n\ntoInt :: String -> [Int]\ntoInt xs = [read x :: Int | x <- words xs]\n\nminCap :: [String] -> [Int]\nminCap [] = []\nminCap (x:xs) = (lxs - hxs) : minCap xs\n where pairs = toInt x\n hxs = head pairs\n lxs = last pairs\n\ntram :: [Int] -> [Int]\ntram [x] = [x]\ntram [] = []\ntram (x:y:xs) = x : tram accumxs\n where accumxs = (x + y) : xs\n\nmain :: IO ()\nmain = do n <- getContents\n putStr $ show $ maximum $ minCap $ getInput n\n\n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- readLn \n sflow <- replicateM n getLine\n let flow = map (map (read :: String -> Integer) . words) sflow\n {-putStrLn $ show flow-}\n\n let res = solve flow\n\n if (fst res /= 0) then error \"wtf??\"\n else putStrLn $ show $ snd res\n\nsolve flow = foldl (\\(cur, cmax) [gout, gin] -> \n (cur + gin - gout, max cmax (cmax + gin - gout)) \n ) (0, 0) flow\n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- readLn \n sflow <- replicateM n getLine\n let flow = map (map (read :: String -> Integer) . words) sflow\n {-putStrLn $ show flow-}\n\n let cap = snd $ solve flow\n\n putStrLn $ show cap\n\nsolve flow = foldl (\\(cur, cmax) [gout, gin] -> \n (cur + gin - gout, max cmax (cmax + gin - gout)) \n ) (0, 0) flow\n"}, {"source_code": "-- Codeforces 116A\n\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n replicateM n getLine >>= putStrLn . show . solve . map (map read . words) where\n solve = foldl (\\a b -> max a (a+b)) 0 . map (\\x -> x!!1 - x!!0)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List (foldl')\n\nmain = do\n n <- read <$> getLine\n ls <- map (map read . words) <$> replicateM n getLine :: IO [[Int]]\n print $ foldl' (\\cc [o,i] -> let cr = cc-o in max cc (cr+i)) 0 ls"}, {"source_code": "main = do\n\tn <- getInt\n\tflux <- sequence $ map (\\i -> getIntArray) [2..n]\n\tlet res = foldl (\\acc curr -> max (acc - curr !! 0 + curr !! 1) acc) 0 flux\n\tputStrLn $ show res\n\t\ngetInt::IO Int\ngetInt = do\n\tint <- getLine\n\treturn . read $ int\n\t\ngetIntArray::IO [Int]\ngetIntArray = do\n\tarr <- getLine\n\treturn $ map readInt $ split arr ' '\n\t\nreadInt::String -> Int\nreadInt str = read str\n\nsplit::String -> Char -> [String]\nsplit str sep = foldr (\\curr acc -> if curr == sep\n\t\t\t\t\t\t\t\t\t\tthen \"\":acc\n\t\t\t\t\t\t\t\t\t\telse (curr:(head acc)):(tail acc)) [\"\"] str\n\t\t\t\t\t\t\t\t\t\t"}, {"source_code": "main=interact$(show.last.(\\str -> scanl1 (\\acc x -> if x + acc > acc then x+acc else acc )$map (\\[a,b] -> read b-read a)$tail$(\\x -> map words$lines x) str))"}, {"source_code": "main = do\n\tnumber <- getLine\n\tlet n = read number\n\tcalc n 0 0\n\ncalc :: Int -> Int -> Int -> IO ()\ncalc 0 _ maks = print maks\ncalc i sum maks = do\n\tinnn <- getLine\n\tlet exitt = read $ takeWhile (/= ' ') innn\n\tlet inn = read $ takeWhile (/= ' ') $ reverse innn\n\tlet nsum = inn + sum - exitt\n\tcalc (i-1) nsum (max nsum maks)"}, {"source_code": "main = do\n\tnumber <- getLine\n\tlet n = read number\n\tcalc n 0 0\n\ncalc :: Int -> Int -> Int -> IO ()\ncalc 0 _ maks = print maks\ncalc i sum maks = do\n\tinnn <- getLine\n\tlet exitt = read $ [head innn]\n\tlet inn = read $ [last innn]\n\tlet nsum = inn + sum - exitt\n\tcalc (i-1) nsum (max nsum maks)\n"}], "src_uid": "74b90fe9458b147568ac9bd09f219aab"} {"source_code": "import Control.Monad\nimport Data.List (sort, groupBy)\nimport Data.Function (on)\nimport Data.Int (Int64)\n\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do \n n <- read <$> getLine\n a <- map read . words <$> getLine :: IO [Int]\n let b = groupBy ((==) `on` fst) $ sort $ zip a [0..n-1]\n print $ sum $ map (calc 0 n . map snd) b\n\ncalc :: Int64 -> Int -> [Int] -> Int64\ncalc s n [] = 0\ncalc s n (x:xs) = s * fromIntegral (n - x) + calc (s + fromIntegral x + 1) n xs\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Word\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.ByteString.Builder\nimport System.IO\nimport qualified Data.IntMap.Strict as IM\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\ngetInts :: IO [Int]\ngetInts = map parseInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n result <- fmap mconcat $ replicateM t $ do\n [n] <- getInts\n as <- getInts\n let (result, _) = foldl' acc (0 :: Word64, IM.empty) $ zip [1..] as\n acc (total, mp) (i, a) = (total', mp')\n where total' = total + IM.findWithDefault 0 a mp * (fromIntegral n - i + 1)\n update Nothing = Just i\n update (Just x) = Just (x + i)\n mp' = IM.alter update a mp\n return $ word64Dec result `mappend` charUtf8 '\\n'\n hPutBuilder stdout result\n"}], "negative_code": [], "src_uid": "66eb860613bf3def9c1b3f8bb3a6763a"} {"source_code": "import Control.Applicative \nimport Data.List\nimport Data.Int\n\nmain :: IO()\nmain = print. solve'.newlist .tail. map read.words =<< getContents\n\nnewlist (x:[]) = []\nnewlist (x:y:xs) = (abs (x-y)):newlist (y:xs)\n\nsolve' (x:xs) = max (solve '-' x x xs) (solve '+' 0 0 xs)\n\nsolve :: Char -> Int64 -> Int64 -> [Int64] -> Int64\nsolve _ _ m [] = m\nsolve '+' t m (x:[]) = max m (t+x)\nsolve '-' t m (x:[]) = m\nsolve '-' t m (y:xs) = if (t-y<=0) then solve '+' 0 m xs else solve '+' (t-y) m xs \nsolve '+' t m (y:xs) = solve '-' (t+y) (m `max` (t+y)) xs\n\n", "positive_code": [{"source_code": "\n\n\npp = putStrLn \n\n\n-- params: sequence, max sum, curr sum, iterator\nkadane (a : b : cc) mx curr itr left \n | (0 > next) = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) (succ itr)\n | otherwise = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) left\n where next = curr + ((abs (a - b)) * ((-1) ^ (itr - left)))\nkadane (b : cc) m c i l = m\n-- kadane (b : cc) (maximum [mx, next]) (maximum [next, 0]) (succ itr) \n\n\n-- fold right\nconv ( x : xs ) = ((read x) :: Integer) : conv xs\nconv mpt = []\n\n\nmain = do\n ff <- getLine\n let n = (read ff) :: Integer\n\n gg <- getLine\n let ww = conv (words gg)\n\n let ans = kadane ww 0 0 1 1\n-- pp (show ans)\n let ban = kadane (tail ww) 0 0 2 2\n-- pp (show ban)\n\n\n pp (show (maximum [ans, ban]))\n\n\n"}], "negative_code": [{"source_code": "\n\n\npp = putStrLn \n\n\n-- params: sequence, max sum, curr sum, iterator\nkadane (a : b : cc) mx curr itr left \n | (0 > next) = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) (succ itr)\n | otherwise = kadane (b : cc) (maximum [mx,next]) (maximum [next,0]) (succ itr) left\n where next = curr + ((abs (a - b)) * ((-1) ^ (itr - left)))\nkadane (b : cc) m c i l = m\n-- kadane (b : cc) (maximum [mx, next]) (maximum [next, 0]) (succ itr) \n\n\n-- fold right\nconv ( x : xs ) = ((read x) :: Int) : conv xs\nconv mpt = []\n\n\nmain = do\n ff <- getLine\n let n = (read ff) :: Int\n\n gg <- getLine\n let ww = conv (words gg)\n\n let ans = kadane ww 0 0 1 1\n-- pp (show ans)\n let ban = kadane (tail ww) 0 0 2 2\n-- pp (show ban)\n\n\n pp (show (maximum [ans, ban]))\n\n\n"}, {"source_code": "\n\n\n\n\n\n\n\npp = putStrLn \n\n\n-- params: sequence, max sum, curr sum, iterator\nkadane (a : b : cc) mx curr itr =\n kadane (b : cc) (maximum [mx, next]) (maximum [next, 0]) (succ itr)\n where next = curr + ((abs (a - b)) * ((-1) ^ (itr)))\nkadane (b : cc) m c i = m\n\n-- fold right\nconv ( x : xs ) = ((read x) :: Int) : conv xs\nconv mpt = []\n\n\nmain = do\n ff <- getLine\n let n = (read ff) :: Int\n\n gg <- getLine\n let ww = conv (words gg)\n\n let ans = kadane ww 0 0 0\n pp (show ans)\n\n\n\n\n\n"}, {"source_code": "import Control.Applicative \nimport Data.List\nimport Data.Int\n\nmain :: IO()\nmain = print. solve'.newlist .tail. map read.words =<< getContents\n\nnewlist (x:[]) = []\nnewlist (x:y:xs) = (abs (x-y)):newlist (y:xs)\n\nsolve' (x:xs) = solve '-' x x xs\n\nsolve :: Char -> Int64 -> Int64 -> [Int64] -> Int64\nsolve _ _ m [] = m\nsolve '+' t m (x:[]) = max m (t+x)\nsolve '-' t m (x:[]) = m\nsolve '+' t m (y:xs) = solve '-' (t+y) (m `max` (t+y)) xs\nsolve '-' t m (y:xs) = if (t-y<=0) then solve '-' y (m `max` y) xs else solve '+' (t-y) m xs\n "}], "src_uid": "7ff7f47cee182d2542754e412f6aab1a"} {"source_code": "import Data.Graph\nimport Control.Monad\nimport Data.Tuple\nimport System.IO\n\nnewtype Query = Query {getQuery :: String}\nnewtype Answer = Answer {getAnswer :: String}\n\ndata Case = TwoPlus | None | OneOnly | One\n\ntoTree :: Int -> [[Int]] -> Tree Int\ntoTree n ps =head $ dfs gr [1]\n where\n tups = map (\\[a,b] -> (a,b)) ps\n gr = buildG (1,n) (tups++map swap tups)\n\nstart :: IO (Tree Int)\nstart = do\n n <- readLn\n xs <- replicateM (n-1) $ (map read.words) <$> getLine\n return $ toTree n xs\n\nprocess :: Tree Int -> (Either Query Answer,Case)\nprocess (Node a []) = (Right $ Answer $ \"! \"++show a,None)\n\nprocess (Node a [Node b []]) = (Left $ Query $ \"? \" ++ show a ++ \" \" ++ show b,OneOnly)\n\nprocess (Node a [Node _ (Node c _:_)]) = (Left $ Query $ \"? \" ++ show a ++ \" \" ++ show c,One)\n\nprocess (Node _ (Node c1 _:Node c2 _:_)) = (Left $ Query $ \"? \" ++ show c1 ++ \" \" ++ show c2 ,TwoPlus)\n\nnewTree :: Case -> Int -> Tree Int -> Tree Int\nnewTree None _ _= undefined\n\nnewTree OneOnly n _= Node n []\n\nnewTree One n (Node a [Node b (Node c cs:bs)])\n | n == a = Node n []\n | n == b = Node b bs\n | n == c = Node c cs\n | otherwise = undefined\nnewTree TwoPlus n (Node a (Node b bs:Node c cs:as))\n | n == a = Node a as\n | n == b = Node b bs\n | n == c = Node c cs\n | otherwise = undefined\n\ndoQuery :: Query -> IO Int\ndoQuery (Query str) = do\n putStrLn str\n hFlush stdout\n readLn\n\ndoAnswer :: Answer -> IO ()\ndoAnswer (Answer str) = do\n putStrLn str\n hClose stdout\n\nsolve :: Tree Int -> IO ()\nsolve tr =\n case ei of\n Left q ->\n do\n n <- doQuery q\n solve $ newTree c n tr\n Right a ->\n doAnswer a\n where\n (ei,c) = process tr\n\nmain :: IO ()\nmain = do\n tr <- start\n solve tr\n", "positive_code": [{"source_code": "{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}\nimport System.IO\nimport Data.Ord\nimport Data.Int\nimport Data.Char\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Data.Either\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Class\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Text.Read (readEither)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- hGetChar stdin\n if x == ' ' || x == '\\t' || x == '\\n' then\n if s then\n aux s\n else\n return id\n else\n liftM ((.) $ showChar x) $ aux False\n in liftM (flip ($) []) $ aux True\n\ntype EIO a = ExceptT String IO a\n\ndata HNormal\ndata HString\ndata HList\n\nclass IOInteract a where\n convertEither :: String -> Either String a\n toShowS :: a -> String -> String\n toShow :: a -> String\n toShow x = toShowS x []\n\ninstance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where\n convertEither = convertEitherp (undefined :: flag)\n toShowS = toShowSp (undefined :: flag)\n\ntype family IOType x where\n IOType String = HString\n IOType [x] = HList\n IOType x = HNormal\n\nclass IOInteractp flag a where\n convertEitherp :: flag -> String -> Either String a\n toShowSp :: flag -> a -> String -> String\n\ninstance (Show a, Read a) => IOInteractp HNormal a where\n convertEitherp _ x = readEither x\n toShowSp _ x = shows x\n\ninstance IOInteractp HString String where\n convertEitherp _ x = Right x\n toShowSp _ x = showString x\n\ninstance (IOInteract a) => IOInteractp HList [a] where\n convertEitherp _ x = mapM convertEither $ words x\n toShowSp _ [] = id\n toShowSp _ (x : []) = toShowS x\n toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs\n\nget :: IOInteract a => EIO a\nget = ExceptT $ liftM convertEither getToken\nput :: IOInteract a => a -> EIO ()\nput = lift . (hPutStr stdout) . toShow\nputln :: IOInteract a => a -> EIO ()\nputln = lift . (hPutStrLn stdout) . toShow\nflush :: EIO ()\nflush = lift $ hFlush stdout\n\nmain :: IO ()\nmain = do\n o <- runExceptT main_\n case o of\n Right () -> return ()\n Left s -> hPutStrLn stdout s\n\nmain_ :: EIO ()\n-- template --\nmain_ = do\n n <- get :: EIO Int\n e <- replicateM (n - 1) $ liftM2 (,) get get :: EIO [(Int, Int)]\n f1 (buildTree n e)\n\nbuildTree :: Int -> [(Int, Int)] -> Map Int (Set Int)\nbuildTree n es = let m = foldl (\\m i ->\n Map.insert i Set.empty m ) Map.empty [1..n] in\n foldl (\\m (i, j) ->\n Map.adjust (Set.insert i) j $ Map.adjust (Set.insert j) i m ) m es\n\nf1 :: Map Int (Set Int) -> EIO ()\nf1 d = if Map.size d == 1 then\n case Map.keys d of\n i : _ -> (putln $ \"! \" ++ show i) >>= (const flush)\n _ -> undefined\n else let (x, y) = getV d in do\n putln $ \"? \" ++ show x ++ \" \" ++ show y\n flush\n v <- get\n if v == x || v == y then\n (putln $ \"! \" ++ show v) >>= (const flush)\n else\n f1 $ removeV y $ removeV x d\n\n\ngetV :: Map Int (Set Int) -> (Int, Int)\ngetV d = case Map.keys $ Map.filter (\\s -> Set.size s == 1) d of\n x : y : _ -> (x, y)\n _ -> undefined\n\nremoveV :: Int -> Map Int (Set Int) -> Map Int (Set Int)\nremoveV i d = case fmap Set.toList $ Map.lookup i d of\n Just (a : _ ) -> Map.adjust (Set.delete i) a $ Map.delete i d\n _ -> undefined"}], "negative_code": [], "src_uid": "a291ee66980d8b5856b24d1541e66fd0"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.IO\nimport Data.IORef\n\nsolve :: Int -> Int -> UArray Int Char -> UArray Int Char -> IO String\nsolve n need s1 s2 = do\n str <- newArray (0,n-1) 'a' :: IO (IOUArray Int Char)\n rest1 <- newIORef need\n rest2 <- newIORef need\n forM [0..n-1] $ \\i -> do\n r <- readIORef rest1\n when (s1 ! i == s2 ! i) $ do\n if r > 0\n then do\n writeArray str i (s1 ! i)\n writeIORef rest1 (r-1)\n writeIORef rest2 (r-1)\n else writeArray str i $ fromMaybe 'a' $ find (\\x -> x /= s1 ! i && x /= s2 ! i) \"abc\"\n forM [0..n-1] $ \\i -> do\n r1 <- readIORef rest1\n r2 <- readIORef rest2\n let x = s1 ! i\n let y = s2 ! i\n when (x /= y) $ do\n if r2 == 0\n then writeArray str i (fromMaybe 'a' $ find (\\z -> z /= x && z /= y) \"abc\")\n else if r1 < r2\n then do\n writeArray str i y\n writeIORef rest2 (r2-1)\n else do\n writeArray str i x\n writeIORef rest1 (r1-1)\n readIORef rest2 >>= \\x ->\n if x > 0\n then return \"-1\"\n else getElems str\n\nmain :: IO ()\nmain = do\n [n,t] <- map read . words <$> getLine\n s1 <- listArray (0,n-1) <$> getLine\n s2 <- listArray (0,n-1) <$> getLine\n putStrLn =<< solve n (n-t) s1 s2\n", "positive_code": [{"source_code": "import Data.Maybe (fromMaybe)\n\nsolve [n, t, s1, s2] = solve' (read n) (read t) (zip s1 s2)\n\nsolve' :: Int -> Int -> [(Char, Char)] -> Maybe String\nsolve' _ t s12\n | d > 2*t = Nothing\n | d > t = Just $ go (d-t, d-t, 2*t-d, 0) s12\n | otherwise = Just $ go (0, 0, d, t-d) s12\n where d = length . filter (uncurry (/=)) $ s12\n go _ [] = []\n go (a, b, c, d) ((x, y) : zs)\n | a > 0 && x /= y = x : go (a-1, b, c, d) zs\n | b > 0 && x /= y = y : go (a, b-1, c, d) zs\n | c > 0 && x /= y = other x y : go (a, b, c-1, d) zs\n | d > 0 && x == y = next x : go (a, b, c, d-1) zs\n | otherwise = x : go (a, b, c, d) zs\n\nother x y = head . filter (\\c -> c /= x && c /= y) $ ['a' .. ]\n\nnext 'z' = 'a'\nnext c = succ c\n\nmain = interact $ fromMaybe \"-1\" . solve . words\n"}, {"source_code": "import Control.Monad\nimport System.IO\nimport Data.Int\nimport Data.Char\nimport Data.Maybe\nimport Data.Ix\nimport Data.List\nimport GHC.Exts\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map \nimport qualified Data.Vector as Vector\n\nreadInt = read :: String -> Int\ninfixl 5 |>\na |> f = f a\n\ninfixl 5 ||>\nm ||> f = liftM f m\n\nreadLines :: Int -> IO [String]\nreadLines 0 = return []\nreadLines n = do\n\tl1 <- getLine\n\tlns <- readLines (n - 1)\n\treturn $ l1 : lns\n\ntoLong :: Int -> Int64\ntoLong = fromIntegral\n\nother c1 c2 = find (\\c -> c /= c1 && c /= c2) ['a' .. 'c'] |> fromMaybe undefined\n\nget_ans [] _ _ _ _ = \"\"\nget_ans (c1 : t1) (c2 : t2) mb ms1 ms2\n\t| c1 == c2 && mb > 0\t\t= c1 : get_ans t1 t2 (mb - 1) ms1 ms2\n\t| c1 == c2\t\t\t\t\t= (other c1 c2) : get_ans t1 t2 mb ms1 ms2\n\t| ms1 > 0 \t\t\t\t\t= c1 : get_ans t1 t2 mb (ms1 - 1) ms2\n\t| ms2 > 0\t\t\t\t\t= c2 : get_ans t1 t2 mb ms1 (ms2 - 1)\n\t| otherwise\t\t\t\t\t= other c1 c2 : get_ans t1 t2 mb ms1 ms2\n\nmain = do\n\tn : should_differ : [] <- getLine ||> words ||> map readInt\n\ts1 <- getLine\n\ts2 <- getLine\n\n\tshould_match <- return $ n - should_differ\n\n\tmatching <- return $ zip s1 s2 |> filter (uncurry (==)) |> length\n\n\tshould_match_in_both <- return $ find (\\m -> m <= should_match && 2 * (should_match - m) <= (n - matching)) [0 .. matching]\n\n\tcase should_match_in_both of\n\t\tNothing -> putStrLn \"-1\"\n\t\tJust x -> do\n\t\t\t\t\tres <- return $ get_ans s1 s2 x (should_match - x) (should_match - x)\n\t\t\t\t\tputStr $ res"}, {"source_code": "--l1\u306f\u5bfe\u5fdc\u3059\u308b\u3067\u540c\u3058\u306b\u3059\u308b\u3082\u306e l2\u306fs2\u3067\u9055\u3046\u306e\u306b\u3059\u308b\nanswer l1 l2 [] [] = []\nanswer l1 l2 (a1:n1) (a2:n2) | a1 == a2 = if l2 == 0 then a1:(answer l1 l2 n1 n2) else (getDif a1 a2):(answer l1 (l2-1) n1 n2)\n | otherwise = if l1 == 0 then (getDif a1 a2):(answer l1 l2 n1 n2) else if l1 `rem` 2 == 0 then a1:(answer (l1-1) l2 n1 n2) else a2:(answer (l1-1) l2 n1 n2)\ngetDif a b | b < a = getDif b a\n | a == b = if a == 'a' then 'b' else pred a\n | succ a == b = if a == 'a' then succ b else pred a\n | otherwise = succ a\nmain = do\n w0 <- getLine\n let [n,t] = [read n::Int|n<-(words w0)]\n s1 <- getLine\n s2 <- getLine\n let n0=length $ filter (\\x ->(fst x)/=(snd x)) $ zip s1 s2\n let n1=n-n0\n let minN = if n0 `rem` 2 == 0 then n0 `div` 2 else (n0 + 1) `div` 2\n if t < minN\n then putStrLn \"-1\"\n else if t <= n0 then putStrLn $ answer (2*(n0-t)) 0 s1 s2 else putStrLn $ answer 0 (t-n0) s1 s2\n"}], "negative_code": [{"source_code": "import Data.Maybe (fromMaybe)\n\nsolve [n, t, s1, s2] = solve' (read n) (read t) (zip s1 s2)\n\nsolve' :: Int -> Int -> [(Char, Char)] -> Maybe String\nsolve' n t s12\n | d >= 2*t = Nothing\n | d > t = Just $ go (d-t, d-t, 2*t-d, 0) s12\n | otherwise = Just $ go (0, 0, d, t-d) s12\n where d = length . filter (uncurry (/=)) $ s12\n go _ [] = []\n go (a, b, c, d) ((x, y) : zs)\n | a > 0 && x /= y = x : go (a-1, b, c, d) zs\n | b > 0 && x /= y = y : go (a, b-1, c, d) zs\n | c > 0 && x /= y = other x y : go (a, b, c-1, d) zs\n | d > 0 && x == y = next x : go (a, b, c, d-1) zs\n | otherwise = x : go (a, b, c, d) zs\n\nother x y = head . filter (\\c -> c /= x && c /= y) $ ['a' .. ]\n\nnext 'z' = 'a'\nnext c = succ c\n\nmain = interact $ fromMaybe \"-1\" . solve . words\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.IO\nimport Data.IORef\n\nsolve :: Int -> Int -> UArray Int Char -> UArray Int Char -> IO String\nsolve n need s1 s2 = do\n str <- newArray (0,n-1) 'a' :: IO (IOUArray Int Char)\n rest1 <- newIORef need\n rest2 <- newIORef need\n forM [0..n-1] $ \\i -> do\n r <- readIORef rest1\n when (s1 ! i == s2 ! i && r > 0) $ do\n writeArray str i (s1 ! i)\n writeIORef rest1 (r-1)\n writeIORef rest2 (r-1)\n forM [0..n-1] $ \\i -> do\n r1 <- readIORef rest1\n r2 <- readIORef rest2\n let x = s1 ! i\n let y = s2 ! i\n when (x /= y) $ do\n if r2 == 0\n then writeArray str i (fromMaybe 'a' $ find (\\z -> z /= x && z /= y) \"abc\")\n else if r1 < r2\n then do\n writeArray str i y\n writeIORef rest2 (r2-1)\n else do\n writeArray str i x\n writeIORef rest1 (r1-1)\n readIORef rest2 >>= \\x ->\n if x > 0\n then return \"-1\"\n else getElems str\n\nmain :: IO ()\nmain = do\n [n,t] <- map read . words <$> getLine\n s1 <- listArray (0,n-1) <$> getLine\n s2 <- listArray (0,n-1) <$> getLine\n putStrLn =<< solve n (n-t) s1 s2\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nsolve :: Int -> Int -> String -> String -> Int -> Maybe String\nsolve c1 c2 [] [] need\n | c1 == need && c2 == need = Just []\n | otherwise = Nothing\nsolve c1 c2 (x:xs) (y:ys) need \n | c1 == need && c2 == need = fmap ((fromMaybe 'a' $ find (\\z -> z /= x && z /= y) ['a'..'z']) :) $ solve c1 c2 xs ys need\n | x == y = fmap (x :) $ solve (c1+1) (c2+1) xs ys need\n | c1 == c2 = fmap (x :) $ solve (c1+1) c2 xs ys need\n | c1 > c2 = fmap (y :) $ solve c1 (c2+1) xs ys need\n\nmain :: IO ()\nmain = do\n [n,t] <- map read . words <$> getLine\n s1 <- getLine\n s2 <- getLine\n case solve 0 0 s1 s2 (n-t) of\n Just xs -> putStrLn xs\n Nothing -> print (-1)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nsolve :: Int -> Int -> String -> String -> Int -> Maybe String\nsolve c1 c2 [] [] need\n | c1 == need && c2 == need = Just []\n | otherwise = Nothing\nsolve c1 c2 (x:xs) (y:ys) need \n | c2 == need || c1 == need && x == y = fmap ((fromMaybe 'a' $ find (\\z -> z /= x && z /= y) ['a'..'z']) :) $ solve c1 c2 xs ys need\n | x == y = fmap (x :) $ solve (c1+1) (c2+1) xs ys need\n | c1 == c2 = fmap (x :) $ solve (c1+1) c2 xs ys need\n | c1 > c2 = fmap (y :) $ solve c1 (c2+1) xs ys need\n\nmain :: IO ()\nmain = do\n [n,t] <- map read . words <$> getLine\n s1 <- getLine\n s2 <- getLine\n case solve 0 0 s1 s2 (n-t) of\n Just xs -> putStrLn xs\n Nothing -> print (-1)\n"}], "src_uid": "8ba3a7f7cb955478481c74cd4a4eed14"} {"source_code": "{-# LANGUAGE TypeApplications #-}\r\n\r\nmodule Main where\r\n\r\nimport Data.List\r\nimport Data.Char\r\nimport Data.Functor\r\nimport Control.Monad\r\nimport Data.Function\r\nimport Control.Monad.State\r\n\r\ndata Answer = YES | NO deriving Show\r\n\r\npickUp :: String -> State [Char] Answer\r\npickUp [ ] = return YES\r\npickUp (c : cs) = do\r\n keys <- get\r\n if isLower c\r\n then put (c : keys) >> pickUp cs\r\n else if toLower c `elem` keys \r\n then put (delete c keys) >> pickUp cs \r\n else return NO\r\n\r\nmain :: IO ()\r\nmain = \r\n getLine <&> read @Int \r\n >>=\r\n flip replicateM getLine \r\n >>= \r\n mapM_ (\\s -> print $ evalState (pickUp s) [])", "positive_code": [{"source_code": "import Control.Monad.State (State, evalState, replicateM, state)\nimport Data.Bifunctor (first)\nimport Data.Char (isDigit)\nimport Data.List (elemIndex)\n\nok :: [Char] -> [Char]\nok s =\n if and [elemIndex p s <= elemIndex q s | (p, q) <- [('r', 'R'), ('g', 'G'), ('b', 'B')]]\n then \"YES\\n\"\n else \"No\\n\"\n\ngetInt :: State [Char] Int\ngetInt = state func\n where\n func s = first (\\x -> read x :: Int) $ span isDigit s\n\ngetNext :: State [Char] [Char]\ngetNext = state func\n where\n func s = first ok $ span (/= '\\n') (tail s)\n\nmainFunc :: State [Char] [[Char]]\nmainFunc = do\n n <- getInt\n replicateM n getNext\n\n-- replicateM n f = loop n\n-- where loop c\n-- | c <=0 = pure []\n-- | otherwise = (:) <$> f <*> (loop (c-1))\n\nmain :: IO ()\nmain = do\n inp <- getContents\n putStr $ concat $ evalState mainFunc inp"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ncmp a b = if a < b then 1 else 0\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n s <- getNext\r\n let ok a b = P.elemIndex a s <= P.elemIndex b s\r\n let good = ok 'r' 'R' && ok 'g' 'G' && ok 'b' 'B'\r\n pure $ string7 $ if good then \"YES\\n\" else \"NO\\n\"\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState solve inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.Map (fromList, (!))\n\nsolve :: [Char] -> Bool\nsolve arr = m ! 'r' < m ! 'R' && m ! 'g' < m ! 'G' && m ! 'b' < m ! 'B'\n where\n m = fromList $ zip arr [1 ..]\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n l <- getLine\n putStrLn $ if solve l then \"YES\" else \"NO\"\n"}, {"source_code": "import Data.Char (toUpper)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf i xs = take i xs : chunksOf i (drop i xs)\r\n\r\ntoArr :: Read a => String -> [a]\r\ntoArr = map read . words\r\n\r\ntype InType = String\r\ntype OutType = Bool\r\n\r\nisKey :: Char -> Bool\r\nisKey c = c `elem` \"rgb\"\r\n\r\nsolve :: InType -> OutType\r\nsolve = go (const False)\r\n where go :: (Char -> Bool) -> InType -> Bool\r\n go f [] = True\r\n go f (c : cs) = if isKey c then go (\\z -> f z || z == toUpper c) cs\r\n else f c && go f cs\r\n\r\nreceive :: [String] -> InType\r\nreceive [s] = s\r\nreceive _ = error \"invalid input\"\r\n\r\nmain :: IO ()\r\nmain = interact $ unlines . map (showb . solve . receive) . chunksOf 1 . tail . lines\r\n where showb True = \"YES\"\r\n showb False = \"NO\"\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Function\r\nimport Data.List\r\nimport Data.Maybe\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- getLine\r\n putStrLn $ if and (zipWith ((<) `on` fromJust . flip elemIndex s) \"rgb\" \"RGB\")\r\n then \"YES\" else \"NO\"\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve =<< readLn\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n s <- getNext\r\n let ok p q = P.elemIndex p s <= P.elemIndex q s\r\n pure $ if ok 'r' 'R' && ok 'g' 'G' && ok 'b' 'B'\r\n then string7 \"YES\\n\"\r\n else string7 \"NO\\n\"\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}], "negative_code": [], "src_uid": "60eb29b2dfb4d6b136c58b33dbd2558e"} {"source_code": "-- Third test: small-to-large with binomial-coefficient-shenanigans\n\n{-# LANGUAGE MagicHash, ScopedTypeVariables, UnboxedTuples #-}\n{-# OPTIONS_GHC -Wno-unbanged-strict-patterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport GHC.Exts\nimport GHC.Integer.GMP.Internals\nimport GHC.IO\nimport GHC.ST\n\nimport Data.Bits\nimport Data.Semigroup\n\n\n-- The main idea of this solution is to use Integer multiplication to\n-- perform the necessary convolutions. Since that doesn't rely on any\n-- number theory tricks, it works nicely with any modulus, and not just\n-- the classic FFT-friendly prime 998244353 = 1 + 7 * 17 * 2^23.\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n inc <- replicateM (2 * n - 2) getInt\n let\n facts :: UArray Int Int\n facts = listArray (0, n) $ scanl' (*!) 1 [1 .. n]\n ifacts :: UArray Int Int\n ifacts = array (0, n) $ take (n + 1)\n $ iterate (\\(i, v) -> (i - 1, v *! i)) (n, inv (facts ! n))\n choose :: Int -> Int -> Int\n choose x k = facts ! x *! ifacts ! k *! ifacts ! (x - k)\n\n nChildren :: UArray Int Int\n nChildren = accumArray (+) (negate 1) (1, n) $ (1, 1) : zip inc (repeat 1)\n nOccs :: UArray Int Int\n nOccs = accumArray (+) 0 (0, n) $ zip (elems nChildren) (repeat 1)\n\n initSet :: PQ Integer\n initSet = foldl' (\\s v -> s `unite` singleton v) Nil $ do\n (ix, k) <- assocs nOccs\n guard $ ix > 0 && k > 0\n let ways w i = if i <= k\n then fromIntegral (w *! choose k i) : ways (w *! ix) (i + 1)\n else []\n pure $ makeInteger (k + 1) (ways 1 0)\n\n convolve :: PQ Integer -> [Int]\n convolve s = case pop s of\n Just (x, s') -> case pop s' of\n Just (y, s'') -> convolve $ push (updateFields remP2 $ x * y) s''\n Nothing -> map fromIntegral $ snd $ toWordList x\n Nothing -> []\n\n optsBySize = convolve initSet\n weights = zipWith (*!) (reverse $ elems facts) (cycle [1, p-1])\n ans = foldl' (+!) 0 $ zipWith (*!) weights optsBySize\n pure $ putInts [ans]\n\n\n-------------------------------------------------------------------------------\n-- Integer internals manipulation\n-------------------------------------------------------------------------------\n\nmakeInteger :: Int -> [Word] -> Integer\n-- Interprets a list of Words as a little-endian base-(2^128) Integer.\n-- Uses internal ByteArray# interface to do it quickly, because sadly\n-- 'GHC.Num.Integer.integerFromWordList' doesn't exist yet in 8.10.1.\n{-# INLINE [1] makeInteger #-}\n{-# ANN makeInteger \"HLint: ignore Redundant lambda\" #-}\n-- 'step' is applied to only two arguments if this fuses\nmakeInteger (I# n) li = runST $ ST $ \\(s0 :: State# s) -> let\n numBytes = iShiftL# n 4#\n (# s1, marr #) = newByteArray# numBytes s0\n s2 = setByteArray# marr 0# numBytes 0# s1\n step :: Word -> (Int# -> State# s -> State# s)\n -> Int# -> State# s -> State# s\n step (W# val) cont = \\off s3\n -> cont (off +# 2#) (writeWord64Array# marr off val s3)\n s4 = foldr step (\\_ s -> s) li 0# s2\n (# s5, arr #) = unsafeFreezeByteArray# marr s4\n in (# s5, importIntegerFromByteArray arr 0## (int2Word# numBytes) 0# #)\n\nintegerToMutableByteArray\n :: Integer -> State# RealWorld\n -> (# State# RealWorld, MutableByteArray# RealWorld, Int# #)\nintegerToMutableByteArray val s0 = let\n numInputBytes = sizeInBaseInteger val 256#\n numFields = iShiftRL# (word2Int# numInputBytes +# 15#) 4#\n bufferSize = iShiftL# numFields 4#\n (# s1, arr #) = newByteArray# bufferSize s0\n s2 = setByteArray# arr (bufferSize -# 16#) 16# 0# s1\n (# s3, _ #) = unIO (exportIntegerToMutableByteArray val arr 0## 0#) s2\n in (# s3, arr, numFields #)\n\ntoWordList :: Integer -> (Int, [Word])\ntoWordList val = let\n (# n, arr #) = runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray val s0\n (# _, farr #) = unsafeFreezeByteArray# marr s1\n in (# numFields, farr #)\n stopOff = iShiftL# n 1#\n in (,) (I# n) $ build $ \\cons nil -> let\n go off = if isTrue# (off <# stopOff)\n then W# (indexWord64Array# arr off) `cons` go (off +# 2#)\n else nil\n in go 0#\n\nupdateFields\n :: (Word# -> Word# -> (# Word#, Word# #)) -> Integer -> Integer\n-- If the Integer is understood as an array of Word128s, this uses\n-- the first argument to update each field. This allows replacing\n-- the rather slow 'quotRemWord2#' with something faster...\n{-# ANN updateFields \"HLint: ignore Redundant lambda\" #-}\n{-# INLINE updateFields #-} -- It should specialize, given only one arg!\nupdateFields fun = \\x -> runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray x s0\n go off s2 = if isTrue# (off >=# 0#)\n then let\n (# s3, hi #) = readWord64Array# marr (off +# 1#) s2\n (# s4, lo #) = readWord64Array# marr off s3\n (# nhi, nlo #) = fun hi lo\n s5 = writeWord64Array# marr (off +# 1#) nhi s4\n s6 = writeWord64Array# marr off nlo s5 -- copy-paste is dangerous...\n in go (off -# 2#) s6\n else s2\n s7 = go (iShiftL# (numFields -# 1#) 1#) s1\n (# _s8, arr #) = unsafeFreezeByteArray# marr s7\n numBytes = int2Word# numFields `shiftL#` 4#\n in importIntegerFromByteArray arr 0## numBytes 0#\n\n\n-------------------------------------------------------------------------------\n-- Modular arithmetic\n-------------------------------------------------------------------------------\n\np :: Int\np = 998244353\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = x + y -! p\n\n(-!) :: Int -> Int -> Int\n-- branchless subtraction modulo p\ninfixl 6 -!\nx -! y = let\n raw = x - y\n in raw + (p .&. shiftR raw 63)\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = let\n I# raw = x * y\n in I# (word2Int# (remP (int2Word# raw)))\n\nquotP :: Word# -> Word#\nquotP v = let\n (# hi, _lo #) = timesWord2# 9920937979283557439## v\n -- the magic number is ceiling(2^(64+29) / p)\n -- The approximation is accurate enough to calculate the exact\n -- quotient with one multiply and one shift for all valid Word#\n in shiftRL# hi 29#\n\nremP :: Word# -> Word#\nremP v = let\n I# p# = p\n in v `minusWord#` timesWord# (quotP v) (int2Word# p#)\n\nremP2 :: Word# -> Word# -> (# Word#, Word# #)\nremP2 hi lo = let\n -- This implementation cheats a bit in order to be a tiny bit\n -- faster. It assumes the high word should be at most 26_401_116_612,\n -- and gives a result in [0..2p-2] instead of [0..p-1].\n I# p# = p\n (# redHi, _ #)\n = int2Word# p# `timesWord2#` timesWord# 17223561541331522433## hi\n in (# 0##, redHi `plusWord#` remP lo #)\n\nnewtype ModP = ModP { unModP :: Int }\ninstance Semigroup ModP where\n ModP x <> ModP y = ModP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ModP where\n mempty = ModP 1\n\ninv :: Int -> Int\ninv = unModP . stimes (p - 2) . ModP\n\n\n-------------------------------------------------------------------------------\n-- Persistent priority queue\n-------------------------------------------------------------------------------\n\ndata PQ a = Nil | PQ a !Int !(PQ a) !(PQ a)\n\nsize :: PQ a -> Int\nsize Nil = 0\nsize (PQ _ sz _ _) = sz\n\nsingleton :: a -> PQ a\nsingleton v = PQ v 1 Nil Nil\n\npush :: Ord a => a -> PQ a -> PQ a\npush v q = case q of\n Nil -> PQ v 1 Nil Nil\n PQ qv sz ql qr\n | qv < v -> pq qv (push v ql) qr\n | otherwise -> pq v (push qv ql) qr\n\npop :: Ord a => PQ a -> Maybe (a, PQ a)\npop Nil = Nothing\npop (PQ v _ s1 s2) = Just (v, unite s1 s2)\n\npq :: a -> PQ a -> PQ a -> PQ a\npq v o1 o2 = if size o1 <= size o2\n then PQ v (size o1 + size o2 + 1) o1 o2\n else PQ v (size o2 + size o1 + 1) o2 o1\n\nunite :: Ord a => PQ a -> PQ a -> PQ a\nunite Nil y = y\nunite x Nil = x\nunite x@(PQ xv xsz xl xr) y@(PQ yv ysz yl yr) = if xv <= yv\n then if size xr < ysz\n then pq xv (unite xl xr) y\n else pq xv (unite xl y) xr\n else unite y x\n\n\n-------------------------------------------------------------------------------\n-- My normal library/template\n-------------------------------------------------------------------------------\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n", "positive_code": [{"source_code": "{-# LANGUAGE MagicHash, UnboxedTuples #-}\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport GHC.Exts\nimport GHC.Integer.GMP.Internals\nimport GHC.IO\n\n-- The main idea of this solution is to use Integer multiplication to\n-- perform the necessary convolutions. Since that doesn't rely on any\n-- number theory tricks, it works nicely with any modulus, and not just\n-- the classic FFT-friendly prime 998244353 = 1 + 7 * 17 * 2^23.\n\nmakeInteger :: Int -> [Word] -> Integer\n-- Interprets a list of Words as a little-endian base-(2^128) Integer.\n-- GHC starting at 9.0.1 ships with ghc-bignum, which provides\n-- a clean way to do this using GHC.Num.Integer.integerFromWordList,\n-- but with 8.10.1 the only O(n) way to get it done is to root around\n-- in the Integer internals like some kind of monster.\n\n-- There's also a simple O(n * log n) divide and conquer approach\n-- using bitshifts. It's certainly also fast enough, but I wanted\n-- the experience of writing this code anyway.\nmakeInteger (I# n) li = unsafePerformIO $ IO $ \\s0 -> let\n numBytes = uncheckedIShiftL# n 4#\n (# s1, arr #) = newByteArray# numBytes s0\n go :: Int# -> [Word] -> State# RealWorld -> State# RealWorld\n go _ [] s = s\n go offset (W# v : vs) s2 = let\n s3 = writeWord64Array# arr offset v s2\n s4 = writeInt64Array# arr (offset +# 1#) 0# s3\n in go (offset +# 2#) vs s4\n (# s5, ans #) = unsafeFreezeByteArray# arr (go 0# li s1)\n numLimbs = uncheckedIShiftL# n 1#\n in (# s5, bigNatToInteger (byteArrayToBigNat# ans numLimbs) #)\n\nintegerToMutableByteArray\n :: Integer -> State# RealWorld\n -> (# State# RealWorld, MutableByteArray# RealWorld, Int# #)\nintegerToMutableByteArray val s0 = let\n numInputBytes = sizeInBaseInteger val 256#\n numFields = 1# +# word2Int# (uncheckedShiftRL# numInputBytes 4#)\n bufferSize = uncheckedIShiftL# numFields 4#\n (# s1, arr #) = newByteArray# bufferSize s0\n -- zero out the last field (uninitialized memory isn't ok)\n lastFieldPos = numFields *# 2# -# 2#\n s2 = writeInt64Array# arr lastFieldPos 0# s1\n s3 = writeInt64Array# arr (lastFieldPos +# 1#) 0# s2\n\n (# s4, _ #)\n = unIO (exportIntegerToMutableByteArray val arr (int2Word# 0#) 0#) s3\n in (# s4, arr, lastFieldPos #)\n\nreduceFields :: Word -> Integer -> Integer\n-- If the Integer is understood as an array of Word128s, this reduces\n-- all of them modulo the first argument.\n-- (Upper words should be smaller than this first argument.)\nreduceFields (W# modThis) val = unsafePerformIO $ IO $ \\s0 -> let\n (# s1, arr, lastFieldPos #) = integerToMutableByteArray val s0\n go :: Int# -> State# RealWorld -> State# RealWorld\n go offset s2 = if isTrue# (offset <# 0#)\n then s2\n else let\n (# s3, lower #) = readWord64Array# arr offset s2\n (# s4, upper #) = readWord64Array# arr (offset +# 1#) s3\n (# _q, r #) = quotRemWord2# upper lower modThis\n s5 = writeWord64Array# arr offset r s4\n s6 = writeInt64Array# arr (offset +# 1#) 0# s5\n in go (offset -# 2#) s6\n (# s7, ans #) = unsafeFreezeByteArray# arr (go lastFieldPos s1)\n numLimbs = 2# +# lastFieldPos\n in (# s7, bigNatToInteger (byteArrayToBigNat# ans numLimbs) #)\n\ntoWordList :: Integer -> [Word]\ntoWordList val = unsafePerformIO $ IO $ \\s0 -> let\n (# s1, arrMut, lastFieldPos #) = integerToMutableByteArray val s0\n (# s2, arr #) = unsafeFreezeByteArray# arrMut s1\n go :: Int# -> [Word]\n go offset = if isTrue# (offset ># lastFieldPos)\n then []\n else W# (indexWord64Array# arr offset) : go (offset +# 2#)\n in (# s2, go 0# #)\n\n\n\np :: Int\np = 998244353\n\ncv :: Int -> Int\ncv x = x - if x >= p then p else 0\n\n(+!) :: Int -> Int -> Int\nx +! y = cv $ x + y\n\n(*!) :: Int -> Int -> Int\nx *! y = x * y `rem` p\n\ncombine :: [Integer] -> Integer\ncombine [] = 0\ncombine [n] = n\ncombine ns = combine (combine2 ns)\n\ncombine2 :: [Integer] -> [Integer]\ncombine2 (x : y : zs) = reduceFields 998244353 (x * y) : combine2 zs\ncombine2 li = li\n\nmainFun :: SP Builder\nmainFun = do\n ~[n] <- getInts 1\n incs <- getInts $ 2 * (n - 1)\n let\n nChildren :: UArray Int Int\n nChildren = accumArray (+) (0-1) (1, n) $ (1, 1) : zip incs (repeat 1)\n toConvolve = [makeInteger 2 [1, fromIntegral x] | x <- elems nChildren]\n --toConvolve = replicate 250000 $ makeInteger 2 [1, 1]\n waysLi = map fromIntegral $ toWordList $ combine toConvolve\n facts = scanl' (*!) 1 [1..n]\n weights = zipWith (*!) (reverse facts) (cycle [1, p-1])\n ans = foldl' (+!) 0 $ zipWith (*!) waysLi weights\n pure $ putInts [ans]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "-- Second test: basic top-to-bottom with binomial-coefficient-shenanigans\n\n{-# LANGUAGE MagicHash, ScopedTypeVariables, UnboxedTuples #-}\n{-# OPTIONS_GHC -Wno-unbanged-strict-patterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport GHC.Exts\nimport GHC.Integer.GMP.Internals\nimport GHC.IO\nimport GHC.ST\n\nimport Data.Bits\nimport Data.Semigroup\n\n\n-- The main idea of this solution is to use Integer multiplication to\n-- perform the necessary convolutions. Since that doesn't rely on any\n-- number theory tricks, it works nicely with any modulus, and not just\n-- the classic FFT-friendly prime 998244353 = 1 + 7 * 17 * 2^23.\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n inc <- replicateM (2 * n - 2) getInt\n let\n facts :: UArray Int Int\n facts = listArray (0, n) $ scanl' (*!) 1 [1 .. n]\n ifacts :: UArray Int Int\n ifacts = array (0, n) $ take (n + 1)\n $ iterate (\\(i, v) -> (i - 1, v *! i)) (n, inv (facts ! n))\n choose :: Int -> Int -> Int\n choose x k = facts ! x *! ifacts ! k *! ifacts ! (x - k)\n\n nChildren :: UArray Int Int\n nChildren = accumArray (+) (negate 1) (1, n) $ (1, 1) : zip inc (repeat 1)\n nOccs :: UArray Int Int\n nOccs = accumArray (+) 0 (0, n) $ zip (elems nChildren) (repeat 1)\n\n step :: Integer -> Int -> Integer\n step v ix = case nOccs ! ix of\n 0 -> v\n k -> let\n ways w i = if i <= k\n then fromIntegral (w *! choose k i) : ways (w *! ix) (i + 1)\n else []\n in updateFields remP2 $ v * makeInteger (k + 1) (ways 1 0)\n\n optsBySize = snd $ toWordList $ foldl' step 1 [n, n - 1 .. 1]\n weights = zipWith (*!) (reverse $ elems facts) (cycle [1, p-1])\n ans = foldl' (+!) 0 $ zipWith (*!) weights $ map fromIntegral optsBySize \n pure $ putInts [ans]\n\n\n-------------------------------------------------------------------------------\n-- Integer internals manipulation\n-------------------------------------------------------------------------------\n\nmakeInteger :: Int -> [Word] -> Integer\n-- Interprets a list of Words as a little-endian base-(2^128) Integer.\n-- Uses internal ByteArray# interface to do it quickly, because sadly\n-- 'GHC.Num.Integer.integerFromWordList' doesn't exist yet in 8.10.1.\n{-# INLINE [1] makeInteger #-}\n{-# ANN makeInteger \"HLint: ignore Redundant lambda\" #-}\n-- 'step' is applied to only two arguments if this fuses\nmakeInteger (I# n) li = runST $ ST $ \\(s0 :: State# s) -> let\n numBytes = iShiftL# n 4#\n (# s1, marr #) = newByteArray# numBytes s0\n s2 = setByteArray# marr 0# numBytes 0# s1\n step :: Word -> (Int# -> State# s -> State# s)\n -> Int# -> State# s -> State# s\n step (W# val) cont = \\off s3\n -> cont (off +# 2#) (writeWord64Array# marr off val s3)\n s4 = foldr step (\\_ s -> s) li 0# s2\n (# s5, arr #) = unsafeFreezeByteArray# marr s4\n in (# s5, importIntegerFromByteArray arr 0## (int2Word# numBytes) 0# #)\n\nintegerToMutableByteArray\n :: Integer -> State# RealWorld\n -> (# State# RealWorld, MutableByteArray# RealWorld, Int# #)\nintegerToMutableByteArray val s0 = let\n numInputBytes = sizeInBaseInteger val 256#\n numFields = iShiftRL# (word2Int# numInputBytes +# 15#) 4#\n bufferSize = iShiftL# numFields 4#\n (# s1, arr #) = newByteArray# bufferSize s0\n s2 = setByteArray# arr (bufferSize -# 16#) 16# 0# s1\n (# s3, _ #) = unIO (exportIntegerToMutableByteArray val arr 0## 0#) s2\n in (# s3, arr, numFields #)\n\ntoWordList :: Integer -> (Int, [Word])\ntoWordList val = let\n (# n, arr #) = runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray val s0\n (# _, farr #) = unsafeFreezeByteArray# marr s1\n in (# numFields, farr #)\n stopOff = iShiftL# n 1#\n in (,) (I# n) $ build $ \\cons nil -> let\n go off = if isTrue# (off <# stopOff)\n then W# (indexWord64Array# arr off) `cons` go (off +# 2#)\n else nil\n in go 0#\n\nupdateFields\n :: (Word# -> Word# -> (# Word#, Word# #)) -> Integer -> Integer\n-- If the Integer is understood as an array of Word128s, this uses\n-- the first argument to update each field. This allows replacing\n-- the rather slow 'quotRemWord2#' with something faster...\n{-# ANN updateFields \"HLint: ignore Redundant lambda\" #-}\n{-# INLINE updateFields #-} -- It should specialize, given only one arg!\nupdateFields fun = \\x -> runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray x s0\n go off s2 = if isTrue# (off >=# 0#)\n then let\n (# s3, hi #) = readWord64Array# marr (off +# 1#) s2\n (# s4, lo #) = readWord64Array# marr off s3\n (# nhi, nlo #) = fun hi lo\n s5 = writeWord64Array# marr (off +# 1#) nhi s4\n s6 = writeWord64Array# marr off nlo s5 -- copy-paste is dangerous...\n in go (off -# 2#) s6\n else s2\n s7 = go (iShiftL# (numFields -# 1#) 1#) s1\n (# _s8, arr #) = unsafeFreezeByteArray# marr s7\n numBytes = int2Word# numFields `shiftL#` 4#\n in importIntegerFromByteArray arr 0## numBytes 0#\n\n\n-------------------------------------------------------------------------------\n-- Modular arithmetic\n-------------------------------------------------------------------------------\n\np :: Int\np = 998244353\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = x + y -! p\n\n(-!) :: Int -> Int -> Int\n-- branchless subtraction modulo p\ninfixl 6 -!\nx -! y = let\n raw = x - y\n in raw + (p .&. shiftR raw 63)\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = let\n I# raw = x * y\n in I# (word2Int# (remP (int2Word# raw)))\n\nquotP :: Word# -> Word#\nquotP v = let\n (# hi, _lo #) = timesWord2# 9920937979283557439## v\n -- the magic number is ceiling(2^(64+29) / p)\n -- The approximation is accurate enough to calculate the exact\n -- quotient with one multiply and one shift for all valid Word#\n in shiftRL# hi 29#\n\nremP :: Word# -> Word#\nremP v = let\n I# p# = p\n in v `minusWord#` timesWord# (quotP v) (int2Word# p#)\n\nremP2 :: Word# -> Word# -> (# Word#, Word# #)\nremP2 hi lo = let\n -- This implementation cheats a bit in order to be a tiny bit\n -- faster. It assumes the high word should be at most 26_401_116_612,\n -- and gives a result in [0..2p-2] instead of [0..p-1].\n I# p# = p\n (# redHi, _ #)\n = int2Word# p# `timesWord2#` timesWord# 17223561541331522433## hi\n in (# 0##, redHi `plusWord#` remP lo #)\n\nnewtype ModP = ModP { unModP :: Int }\ninstance Semigroup ModP where\n ModP x <> ModP y = ModP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ModP where\n mempty = ModP 1\n\ninv :: Int -> Int\ninv = unModP . stimes (p - 2) . ModP\n\n\n-------------------------------------------------------------------------------\n-- My normal library/template\n-------------------------------------------------------------------------------\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "-- First test: Minimal changes to the combining algorithm,\n-- but much faster modular arithmetic.\n\n{-# LANGUAGE MagicHash, ScopedTypeVariables, UnboxedTuples #-}\n{-# OPTIONS_GHC -Wno-unbanged-strict-patterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport GHC.Exts\nimport GHC.Integer.GMP.Internals\nimport GHC.IO\nimport GHC.ST\n\nimport Data.Bits\nimport Data.Semigroup\n\n\n-- The main idea of this solution is to use Integer multiplication to\n-- perform the necessary convolutions. Since that doesn't rely on any\n-- number theory tricks, it works nicely with any modulus, and not just\n-- the classic FFT-friendly prime 998244353 = 1 + 7 * 17 * 2^23.\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n incs <- replicateM (2 * (n - 1)) getInt\n let\n nChildren :: UArray Int Int\n nChildren = accumArray (+) (0-1) (1, n) $ (1, 1) : zip incs (repeat 1)\n toConvolve = [makeInteger 2 [1, fromIntegral x] | x <- elems nChildren]\n --toConvolve = replicate 250000 $ makeInteger 2 [1, 1]\n waysLi = map fromIntegral $ snd $ toWordList $ combine toConvolve\n facts = scanl' (*!) 1 [1..n]\n weights = zipWith (*!) (reverse facts) (cycle [1, p-1])\n ans = foldl' (+!) 0 $ zipWith (*!) waysLi weights\n pure $ putInts [ans]\n\ncombine :: [Integer] -> Integer\ncombine [] = 0\ncombine [n] = n\ncombine ns = combine (combine2 ns)\n\ncombine2 :: [Integer] -> [Integer]\ncombine2 (x : y : zs) = updateFields remP2 (x * y) : combine2 zs\ncombine2 li = li\n\n-------------------------------------------------------------------------------\n-- Integer internals manipulation\n-------------------------------------------------------------------------------\n\nmakeInteger :: Int -> [Word] -> Integer\n-- Interprets a list of Words as a little-endian base-(2^128) Integer.\n-- Uses internal ByteArray# interface to do it quickly, because sadly\n-- 'GHC.Num.Integer.integerFromWordList' doesn't exist yet in 8.10.1.\n{-# INLINE [1] makeInteger #-}\n{-# ANN makeInteger \"HLint: ignore Redundant lambda\" #-}\n-- 'step' is applied to only two arguments if this fuses\nmakeInteger (I# n) li = runST $ ST $ \\(s0 :: State# s) -> let\n numBytes = iShiftL# n 4#\n (# s1, marr #) = newByteArray# numBytes s0\n s2 = setByteArray# marr 0# numBytes 0# s1\n step :: Word -> (Int# -> State# s -> State# s)\n -> Int# -> State# s -> State# s\n step (W# val) cont = \\off s3\n -> cont (off +# 2#) (writeWord64Array# marr off val s3)\n s4 = foldr step (\\_ s -> s) li 0# s2\n (# s5, arr #) = unsafeFreezeByteArray# marr s4\n in (# s5, importIntegerFromByteArray arr 0## (int2Word# numBytes) 0# #)\n\nintegerToMutableByteArray\n :: Integer -> State# RealWorld\n -> (# State# RealWorld, MutableByteArray# RealWorld, Int# #)\nintegerToMutableByteArray val s0 = let\n numInputBytes = sizeInBaseInteger val 256#\n numFields = iShiftRL# (word2Int# numInputBytes +# 15#) 4#\n bufferSize = iShiftL# numFields 4#\n (# s1, arr #) = newByteArray# bufferSize s0\n s2 = setByteArray# arr (bufferSize -# 16#) 16# 0# s1\n (# s3, _ #) = unIO (exportIntegerToMutableByteArray val arr 0## 0#) s2\n in (# s3, arr, numFields #)\n\ntoWordList :: Integer -> (Int, [Word])\ntoWordList val = let\n (# n, arr #) = runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray val s0\n (# _, farr #) = unsafeFreezeByteArray# marr s1\n in (# numFields, farr #)\n stopOff = iShiftL# n 1#\n in (,) (I# n) $ build $ \\cons nil -> let\n go off = if isTrue# (off <# stopOff)\n then W# (indexWord64Array# arr off) `cons` go (off +# 2#)\n else nil\n in go 0#\n\nupdateFields\n :: (Word# -> Word# -> (# Word#, Word# #)) -> Integer -> Integer\n-- If the Integer is understood as an array of Word128s, this uses\n-- the first argument to update each field. This allows replacing\n-- the rather slow 'quotRemWord2#' with something faster...\n{-# ANN updateFields \"HLint: ignore Redundant lambda\" #-}\n{-# INLINE updateFields #-} -- It should specialize, given only one arg!\nupdateFields fun = \\x -> runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray x s0\n go off s2 = if isTrue# (off >=# 0#)\n then let\n (# s3, hi #) = readWord64Array# marr (off +# 1#) s2\n (# s4, lo #) = readWord64Array# marr off s3\n (# nhi, nlo #) = fun hi lo\n s5 = writeWord64Array# marr (off +# 1#) nhi s4\n s6 = writeWord64Array# marr off nlo s5 -- copy-paste is dangerous...\n in go (off -# 2#) s6\n else s2\n s7 = go (iShiftL# (numFields -# 1#) 1#) s1\n (# _s8, arr #) = unsafeFreezeByteArray# marr s7\n numBytes = int2Word# numFields `shiftL#` 4#\n in importIntegerFromByteArray arr 0## numBytes 0#\n\n\n-------------------------------------------------------------------------------\n-- Modular arithmetic\n-------------------------------------------------------------------------------\n\np :: Int\np = 998244353\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = x + y -! p\n\n(-!) :: Int -> Int -> Int\n-- branchless subtraction modulo p\ninfixl 6 -!\nx -! y = let\n raw = x - y\n in raw + (p .&. shiftR raw 63)\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = let\n I# raw = x * y\n in I# (word2Int# (remP (int2Word# raw)))\n\nquotP :: Word# -> Word#\nquotP v = let\n (# hi, _lo #) = timesWord2# 9920937979283557439## v\n -- the magic number is ceiling(2^(64+29) / p)\n -- The approximation is accurate enough to calculate the exact\n -- quotient with one multiply and one shift for all valid Word#\n in shiftRL# hi 29#\n\nremP :: Word# -> Word#\nremP v = let\n I# p# = p\n in v `minusWord#` timesWord# (quotP v) (int2Word# p#)\n\nremP2 :: Word# -> Word# -> (# Word#, Word# #)\nremP2 hi lo = let\n -- This implementation cheats a bit in order to be a tiny bit\n -- faster. It assumes the high word should be at most 26_401_116_612,\n -- and gives a result in [0..2p-2] instead of [0..p-1].\n I# p# = p\n (# redHi, _ #)\n = int2Word# p# `timesWord2#` timesWord# 17223561541331522433## hi\n in (# 0##, redHi `plusWord#` remP lo #)\n\nnewtype ModP = ModP { unModP :: Int }\ninstance Semigroup ModP where\n ModP x <> ModP y = ModP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ModP where\n mempty = ModP 1\n\ninv :: Int -> Int\ninv = unModP . stimes (p - 2) . ModP\n\n\n-------------------------------------------------------------------------------\n-- My normal library/template\n-------------------------------------------------------------------------------\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [{"source_code": "-- First test: Minimal changes to the combining algorithm,\n-- but much faster modular arithmetic.\n\n{-# LANGUAGE MagicHash, ScopedTypeVariables, UnboxedTuples #-}\n{-# OPTIONS_GHC -Wno-unbanged-strict-patterns #-}\n\nimport qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\nimport Data.Array.Unboxed\n\nimport GHC.Exts\nimport GHC.Integer.GMP.Internals\nimport GHC.IO\nimport GHC.ST\n\nimport Data.Bits\nimport Data.Semigroup\n\n\n-- The main idea of this solution is to use Integer multiplication to\n-- perform the necessary convolutions. Since that doesn't rely on any\n-- number theory tricks, it works nicely with any modulus, and not just\n-- the classic FFT-friendly prime 998244353 = 1 + 7 * 17 * 2^23.\n\nmainFun :: SP Builder\nmainFun = do\n n <- getInt\n incs <- replicateM (2 * (n - 1)) getInt\n let\n nChildren :: UArray Int Int\n nChildren = accumArray (+) (0-1) (1, n) $ (1, 1) : zip incs (repeat 1)\n toConvolve = [makeInteger 2 [1, fromIntegral x] | x <- elems nChildren]\n --toConvolve = replicate 250000 $ makeInteger 2 [1, 1]\n waysLi = map fromIntegral $ snd $ toWordList $ combine toConvolve\n facts = scanl' (*!) 1 [1..n]\n weights = zipWith (*!) (reverse facts) (cycle [1, p-1])\n ans = foldl' (+!) 0 $ zipWith (*!) waysLi weights\n pure $ putInts [ans]\n\ncombine :: [Integer] -> Integer\ncombine [] = 0\ncombine [n] = n\ncombine ns = combine (combine2 ns)\n\ncombine2 :: [Integer] -> [Integer]\ncombine2 (x : y : zs) = updateFields remP2 (x * y) : combine2 zs\ncombine2 li = li\n\n-------------------------------------------------------------------------------\n-- Integer internals manipulation\n-------------------------------------------------------------------------------\n\nmakeInteger :: Int -> [Word] -> Integer\n-- Interprets a list of Words as a little-endian base-(2^128) Integer.\n-- Uses internal ByteArray# interface to do it quickly, because sadly\n-- 'GHC.Num.Integer.integerFromWordList' doesn't exist yet in 8.10.1.\n{-# INLINE [1] makeInteger #-}\n{-# ANN makeInteger \"HLint: ignore Redundant lambda\" #-}\n-- 'step' is applied to only two arguments if this fuses\nmakeInteger (I# n) li = runST $ ST $ \\(s0 :: State# s) -> let\n numBytes = iShiftL# n 4#\n (# s1, marr #) = newByteArray# numBytes s0\n s2 = setByteArray# marr 0# numBytes 0# s1\n step :: Word -> (Int# -> State# s -> State# s)\n -> Int# -> State# s -> State# s\n step (W# val) cont = \\off s3\n -> cont (off +# 2#) (writeWord64Array# marr off val s3)\n s4 = foldr step (\\_ s -> s) li 0# s2\n (# s5, arr #) = unsafeFreezeByteArray# marr s4\n in (# s5, importIntegerFromByteArray arr 0## (int2Word# numBytes) 0# #)\n\nintegerToMutableByteArray\n :: Integer -> State# RealWorld\n -> (# State# RealWorld, MutableByteArray# RealWorld, Int# #)\nintegerToMutableByteArray val s0 = let\n numInputBytes = sizeInBaseInteger val 256#\n numFields = iShiftRL# (word2Int# numInputBytes +# 15#) 4#\n bufferSize = iShiftL# numFields 4#\n (# s1, arr #) = newByteArray# bufferSize s0\n s2 = setByteArray# arr (bufferSize -# 16#) 16# 0# s1\n (# s3, _ #) = unIO (exportIntegerToMutableByteArray val arr 0## 0#) s2\n in (# s3, arr, numFields #)\n\ntoWordList :: Integer -> (Int, [Word])\ntoWordList val = let\n (# n, arr #) = runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray val s0\n (# _, farr #) = unsafeFreezeByteArray# marr s1\n in (# numFields, farr #)\n stopOff = iShiftL# n 1#\n in (,) (I# n) $ build $ \\cons nil -> let\n go off = if isTrue# (off <# stopOff)\n then W# (indexWord64Array# arr off) `cons` go (off +# 2#)\n else nil\n in go 0#\n\nupdateFields\n :: (Word# -> Word# -> (# Word#, Word# #)) -> Integer -> Integer\n-- If the Integer is understood as an array of Word128s, this uses\n-- the first argument to update each field. This allows replacing\n-- the rather slow 'quotRemWord2#' with something faster...\n{-# ANN updateFields \"HLint: ignore Redundant lambda\" #-}\n{-# INLINE updateFields #-} -- It should specialize, given only one arg!\nupdateFields fun = \\x -> runRW# $ \\s0 -> let\n (# s1, marr, numFields #) = integerToMutableByteArray x s0\n go off s2 = if isTrue# (off >=# 0#)\n then let\n (# s3, hi #) = readWord64Array# marr (off +# 1#) s2\n (# s4, lo #) = readWord64Array# marr off s3\n (# nhi, nlo #) = fun hi lo\n s5 = writeWord64Array# marr (off +# 1#) nhi s4\n s6 = writeWord64Array# marr (off +# 1#) nlo s5\n in go (off -# 2#) s6\n else s2\n s7 = go (iShiftL# (numFields -# 1#) 1#) s1\n (# _s8, arr #) = unsafeFreezeByteArray# marr s7\n numBytes = int2Word# numFields `shiftL#` 4#\n in importIntegerFromByteArray arr 0## numBytes 0#\n\n\n-------------------------------------------------------------------------------\n-- Modular arithmetic\n-------------------------------------------------------------------------------\n\np :: Int\np = 998244353\n\n(+!) :: Int -> Int -> Int\ninfixl 6 +!\nx +! y = x + y -! p\n\n(-!) :: Int -> Int -> Int\n-- branchless subtraction modulo p\ninfixl 6 -!\nx -! y = let\n raw = x - y\n in raw + (p .&. shiftR raw 63)\n\n(*!) :: Int -> Int -> Int\ninfixl 7 *!\nx *! y = let\n I# raw = x * y\n in I# (word2Int# (remP (int2Word# raw)))\n\nquotP :: Word# -> Word#\nquotP v = let\n (# hi, _lo #) = timesWord2# 9920937979283557439## v\n -- the magic number is ceiling(2^(64+29) / p)\n -- The approximation is accurate enough to calculate the exact\n -- quotient with one multiply and one shift for all valid Word#\n in shiftRL# hi 29#\n\nremP :: Word# -> Word#\nremP v = let\n I# p# = p\n in v `minusWord#` timesWord# (quotP v) (int2Word# p#)\n\nremP2 :: Word# -> Word# -> (# Word#, Word# #)\nremP2 hi lo = let\n -- This implementation cheats a bit in order to be a tiny bit\n -- faster. It assumes the high word should be at most 26_401_116_612,\n -- and gives a result in [0..2p-2] instead of [0..p-1].\n I# p# = p\n (# redHi, _ #)\n = int2Word# p# `timesWord2#` timesWord# 17223561541331522433## hi\n in (# 0##, redHi `plusWord#` remP lo #)\n\nnewtype ModP = ModP { unModP :: Int }\ninstance Semigroup ModP where\n ModP x <> ModP y = ModP (x *! y)\n stimes = stimesMonoid\ninstance Monoid ModP where\n mempty = ModP 1\n\ninv :: Int -> Int\ninv = unModP . stimes (p - 2) . ModP\n\n\n-------------------------------------------------------------------------------\n-- My normal library/template\n-------------------------------------------------------------------------------\n\ntype SP = State P.ByteString\ntype S = StateT P.ByteString\n\ndropSpace :: P.ByteString -> P.ByteString\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\n\n--getNext :: Monad m => S m P.ByteString\n--getNext = state $ P.span (> ' ') . dropSpace\n\ngetInt :: Monad m => S m Int\ngetInt = state $ fromJust . P.readInt . dropSpace\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun inp\n P.putStr $ toLazyByteString outp\n"}], "src_uid": "4cd53d6024ed6655130b836561902822"} {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Lazy.Char8 as B (ByteString, interact, lines, words, readInt, pack)\n\n-- data Entry = Entry { photos :: !Int, x :: !Int , y :: !Int , time :: !Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\n-- solve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\nsolve = (\\(a, _, _, _) -> a) . findMax . flip foldl' [(0, 1, 1, 0)] \\hist (!tr, !xr, !yr) ->\n let\n -- go Entry{..} oth = if abs (x - xr) + abs (y - yr) > tr - time then oth else photos\n go (!photos, !x, !y, !time) a = if abs (x - xr) + abs (y - yr) > tr - time then a else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n -- if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n if newPhotos == minBound then hist else (newPhotos + 1, xr, yr, tr) `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -funbox-strict-fields -fspecialise-aggressively #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments, StrictData #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Char8 as B (ByteString, interact, lines, words, readInt, pack)\n\ndata Entry = Entry { photos :: Int, x :: Int, y :: Int, time :: Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\n let\n go Entry{..} oth = if abs (x - xr) + abs (y - yr) > tr - time then oth else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Data.Maybe (fromJust)\n\ndist !x !y !z !t !l = abs (x - z) + abs (y - t) > l\n\ndata Entry = Entry {\n photos :: !Int\n, coordX :: !Int\n, coordY :: !Int\n, time :: !Int\n} deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . fromJust . Set.lookupMax . List.foldl' go [Entry 0 1 1 0]\n where\n go hist (!tr, !xr, !yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n where\n r = List.foldr brr minBound $ toDescList hist\n brr (Entry n x y t) a = if dist x y xr yr (tr - t) then a else n\n\nmain :: IO ()\nmain = do\n a <- fmap (fmap read . words) . tail . lines <$> getContents\n print $ solve $ fmap (\\[!x, !y, !z] -> (x, y, z)) a"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Lazy.Char8 as B (ByteString, interact, lines, words, readInt, pack)\n\n-- data Entry = Entry { photos :: !Int, x :: !Int , y :: !Int , time :: !Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\n-- solve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\nsolve = (\\(a, _, _, _) -> a) . findMax . flip foldl' [(0, 1, 1, 0)] \\hist (!tr, !xr, !yr) ->\n let\n -- go Entry{..} oth = if abs (x - xr) + abs (y - yr) > tr - time then oth else photos\n go (photos, x, y, time) a = if abs (x - xr) + abs (y - yr) > tr - time then a else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n -- if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n if newPhotos == minBound then hist else (newPhotos + 1, xr, yr, tr) `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Prelude\n\n-- data Entry = Entry {\n-- photos :: !Int\n-- , coordX :: !Int\n-- , coordY :: !Int\n-- , time :: !Int\n-- } deriving (Eq, Ord)\n\nfst4 (a, _, _, _) = a\n\nsolve :: [(Int, Int, Int)] -> Int\n-- solve = photos . Set.findMax . List.foldl' go [Entry 0 1 1 0]\nsolve = fst4 . Set.findMax . List.foldl' go [(0, 1, 1, 0)]\n where\n -- go hist (!tr, !xr, !yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n go hist (!tr, !xr, !yr) = if r == minBound then hist else (r + 1, xr, yr, tr) `Set.insert` hist\n where\n r = List.foldr brr minBound $ toDescList hist\n -- brr (Entry n x y t) a = if abs (x - xr) + abs (y - yr) > tr - t then a else n\n brr (n, x, y, t) a = if abs (x - xr) + abs (y - yr) > tr - t then a else n\n\nmain :: IO ()\nmain = interact $ show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap read . words) . tail . lines"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns, MagicHash, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Data.Maybe (fromJust)\n\ndist x y z t l = abs (x - z) + abs (y - t) > l\n\ndata Entry = Entry {\n photos :: Int\n, coordX :: Int\n, coordY :: Int\n, time :: Int\n} deriving (Eq, Ord)\n\ndata Tup = Tup Int Int Int\n\nsolve :: [Tup] -> Int\nsolve l = photos $ fromJust $ Set.lookupMax $ List.foldl' go [Entry 0 1 1 0] l\n where\n go hist (Tup tr xr yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n where\n r = mx (toDescList hist) minBound\n mx (Entry n x y t : xs) m\n | dist x y xr yr (tr - t) = mx xs m\n | otherwise = n\n mx [] n = n\n\nmain :: IO ()\nmain = do\n a <- fmap (fmap read . words) . tail . lines <$> getContents\n print $ solve $ fmap (\\[x, y, z] -> Tup x y z) a\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -with-rtsopts=-A64m #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl go [Entry 1 1 0 0 0]\n where\n go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n mx ((!bst, !x) : xs) !n\n | n > bst = max x n\n | otherwise = mx xs (max x n)\n mx [] !n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl' go [Entry 1 1 0 0 0]\n where\n go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n mx ((!bst, !x) : xs) !n\n | n >= bst = max x n\n | otherwise = mx xs (max x n)\n mx [] !n = n\n\nmain = do\n -- [r, n] <- map read . words <$> getLine\n -- a <- replicateM n $ map read . words <$> getLine\n a <- map (map read . words) . tail . lines <$> getContents\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Lazy.Char8 as B (ByteString, interact, lines, words, readInt, pack)\n\ndata Entry = Entry { photos :: !Int, x :: !Int , y :: !Int , time :: !Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\n let\n go Entry{..} a = if abs (x - xr) + abs (y - yr) > tr - time then a else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments, StrictData #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Lazy.Char8 as B (ByteString, interact, lines, words, readInt, pack)\nimport Prelude\n\ndata Entry = Entry { photos :: Int, x :: Int, y :: Int, time :: Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\n let\n go Entry{..} oth = if abs (x - xr) + abs (y - yr) > tr - time then oth else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns, MagicHash #-}\n\nimport Data.List\nimport Control.Monad\n\ndist x y z t l = abs (x - z) + abs (y - t) > l\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\ndata Tup = Tup Int Int Int\n\nsolve :: [Tup] -> Int\nsolve l = best $ head $ foldl' go [Entry 1 1 0 0 0] l\n where\n go hist@(Entry _ _ _ best _ : _) (Tup tr xr yr) = if r == minBound then hist else Entry xr yr tr (max best (r + 1)) (r + 1) : hist\n where\n r = mx hist minBound\n mx (Entry x y t bst n : xs) m\n | dist x y xr yr (tr - t) = mx xs m\n | n >= bst = max n m\n | otherwise = mx xs (max n m)\n mx [] !n = n\n\nmain :: IO ()\nmain = do\n a <- map (map read . words) . tail . lines <$> getContents\n print $ solve $ map (\\[x, y, z] -> Tup x y z) a\n"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist :: Num a => (a, a) -> (a, a) -> a\ndist (!x, !y) (!z, !t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\n-- solve = foldl' max . map photos . foldl' go [Entry 1 1 0 0 0]\nsolve = best . head . foldl' go [Entry 1 1 0 0 0]\n where\n -- go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case filter (\\(Entry x y t _ _) -> dist (x, y) (xr, yr) <= tr - t) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n -- mx ((!bst, !x) : xs) !n\n mx (Entry _ _ _ !bst !x : xs) !n\n | n >= bst = max x n\n | otherwise = mx xs (max x n)\n mx [] !n = n\n\nmain = do\n a <- map (map read . words) . tail . lines <$> getContents\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Prelude\nimport Data.Maybe (fromJust)\nimport Data.Bits\n\ndata Entry = Entry {\n photos :: !Int\n, coordX :: !Int\n, coordY :: !Int\n, time :: !Int\n} deriving (Eq, Ord)\n\ndist :: Int -> Int -> Int -> Int -> Int -> Bool\ndist !x !y !z !t !l = abs (x - z) + abs (y - t) > l\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . fromJust . Set.lookupMax . List.foldl' go [Entry 0 1 1 0]\n where\n go hist (!tr, !xr, !yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n where\n r = List.foldr brr minBound $ toDescList hist\n brr (Entry n x y t) a = if dist x y xr yr (tr - t) then a else n\n\nmain :: IO ()\nmain = do\n a <- getContents\n print $ solve $ fmap ((\\[x,y,z] -> (x, y, z)) . fmap read . words) . tail . lines $ a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Data.Maybe (fromJust)\n\ndist x y z t l = abs (x - z) + abs (y - t) > l\n\ndata Entry = Entry {\n photos :: Int\n, coordX :: Int\n, coordY :: Int\n, time :: Int\n} deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . fromJust . Set.lookupMax . List.foldl' go [Entry 0 1 1 0]\n where\n go hist (tr, xr, yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n where\n r = List.foldr brr minBound $ toDescList hist\n brr (Entry n x y t) a = if dist x y xr yr (tr - t) then a else n\n\nmain :: IO ()\nmain = do\n a <- fmap (fmap read . words) . tail . lines <$> getContents\n print $ solve $ fmap (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Prelude\n\n-- data Entry = Entry {\n-- photos :: !Int\n-- , coordX :: !Int\n-- , coordY :: !Int\n-- , time :: !Int\n-- } deriving (Eq, Ord)\n\nfst4 (a, _, _, _) = a\n\nsolve :: [(Int, Int, Int)] -> Int\n-- solve = photos . Set.findMax . List.foldl' go [Entry 0 1 1 0]\nsolve = fst4 . Set.findMax . List.foldl' go [(0, 1, 1, 0)]\n where\n -- go hist (!tr, !xr, !yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n go hist (!tr, !xr, !yr) = if r == minBound then hist else (r + 1, xr, yr, tr) `Set.insert` hist\n where\n r = List.foldr brr minBound $ toDescList hist\n -- brr (Entry n x y t) a = if abs (x - xr) + abs (y - yr) > tr - t then a else n\n brr (!n, !x, !y, !t) a = if abs (x - xr) + abs (y - yr) > tr - t then a else n\n\nmain :: IO ()\nmain = interact $ show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap read . words) . tail . lines\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments, StrictData #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Char8 as B (ByteString, interact, lines, words, readInt, pack)\n\ndata Entry = Entry { photos :: Int, x :: Int, y :: Int, time :: Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\n let\n go Entry{..} oth = if abs (x - xr) + abs (y - yr) > tr - time then oth else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist :: Num a => (a, a) -> (a, a) -> a\ndist (!x, !y) (!z, !t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = best . head . foldl' go [Entry 1 1 0 0 0]\n where\n -- go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case filter (\\(Entry x y t _ _) -> dist (x, y) (xr, yr) <= tr - t) hist of\n -- [] -> hist\n -- a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n go hist@(Entry _ _ _ !best _ : _) (!tr, !xr, !yr) = if r == minBound then hist else Entry xr yr tr (max best $ r + 1) (r + 1) : hist\n where\n r = mx hist minBound\n mx (Entry x y t !bst !n : xs) !m\n | dist (x, y) (xr, yr) > tr - t = mx xs m\n | n >= bst = max n m\n | otherwise = mx xs (max n m)\n mx [] !n = n\n -- mx (Entry _ _ _ !bst !x : xs) !n\n -- | n >= bst = max x n\n -- | otherwise = mx xs (max x n)\n -- mx [] !n = n\n\nmain :: IO ()\nmain = do\n a <- map (map read . words) . tail . lines <$> getContents\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\n\ndata Entry = Entry { photos :: !Int, x :: !Int , y :: !Int , time :: !Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\n let\n go Entry{..} a = if abs (x - xr) + abs (y - yr) > tr - time then a else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n\nmain :: IO ()\nmain = interact $ show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap read . words) . tail . lines"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl go [Entry 1 1 0 0 0]\n where\n go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n mx ((!bst, !x) : xs) !n\n | n > bst = max x n\n | otherwise = mx xs (max x n)\n mx [] !n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nminf = -3483345\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl go [Entry 1 1 0 0 0]\n where\n go hist@(Entry{best}:_) (tr, xr, yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n mx ((bst, x) : xs) n\n | n > bst = max x n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl' go [Entry 1 1 0 0 0]\n where\n go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n mx ((!bst, !x) : xs) !n\n | n >= bst = max x n\n | otherwise = mx xs (max x n)\n mx [] !n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -fomit-yields -fdicts-strict -fexpose-all-unfoldings -flate-dmd-anal -fspec-constr-keen -fregs-graph -fspec-constr-count=200 -fspec-constr-threshold=700 -funfolding-creation-threshold=800 -funfolding-use-threshold=800 -funbox-strict-fields -fspecialise-aggressively #-}\n{-# LANGUAGE BangPatterns, OverloadedLists, RecordWildCards, BlockArguments, StrictData #-}\n\nimport Data.Foldable (foldl')\nimport Data.Set (insert, toDescList, findMax)\nimport Data.ByteString.Char8 as B (ByteString, interact, lines, words, readInt, pack)\n\ndata Entry = Entry { photos :: Int, x :: Int, y :: Int, time :: Int } deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . findMax . flip foldl' [Entry 0 1 1 0] \\hist (!tr, !xr, !yr) ->\n let\n go Entry{..} oth = if abs (x - xr) + abs (y - yr) > tr - time then oth else photos\n newPhotos = foldr go minBound $ toDescList hist\n in\n if newPhotos == minBound then hist else Entry (newPhotos + 1) xr yr tr `insert` hist\n\nmain :: IO ()\nmain = B.interact $ pack . show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap int . B.words) . tail . B.lines\n\nint :: ByteString -> Int\nint s = let Just (a, _) = readInt s in a"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nminf = -3483345\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl go [Entry 1 1 0 0 0]\n where\n go hist@(Entry{best}:_) (tr, xr, yr) = case mapMaybe (\\(Entry x y t best p) -> if dist (x, y) (xr, yr) <= tr - t then Just (best, p) else Nothing) hist of\n [] -> hist\n a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n mx ((bst, x) : xs) n\n | n > bst = max x n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\ndist :: Num a => (a, a) -> (a, a) -> a\ndist (!x, !y) (!z, !t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\n-- solve :: [(Int, Int, Int)] -> Int\nsolve :: [[Int]] -> Int\nsolve = best . head . foldl' go [Entry 1 1 0 0 0]\n where\n go hist@(Entry _ _ _ !best _ : _) [!tr, !xr, !yr] = if r == minBound then hist else Entry xr yr tr (max best $ r + 1) (r + 1) : hist\n where\n r = mx hist minBound\n mx (Entry x y t !bst !n : xs) !m\n | dist (x, y) (xr, yr) > tr - t = mx xs m\n | n >= bst = max n m\n | otherwise = mx xs (max n m)\n mx [] !n = n\n\nmain :: IO ()\nmain = do\n a <- map (map read . words) . tail . lines <$> getContents\n -- print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n print $ solve a"}], "negative_code": [{"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}\n\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nminf = -3483345\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map photos . foldl go [Entry 1 1 0 0 0]\n where\n go hist@(Entry{best}:_) (tr, xr, yr) = Entry xr yr tr (max best nm) nm : hist\n where\n nm = case mapMaybe (\\Entry{..} -> if dist (coordX, coordY) (xr, yr) < tr - time then Just (best, photos) else Nothing) hist of\n [] -> 0\n a -> mx a (-1) + 1\n mx ((bst, x) : xs) n\n | n > bst = max x n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Control.Monad\nimport Prelude\nimport Data.Maybe (fromJust)\n\ndist x y z t l = abs (x - z) + abs (y - t) > l\n\ndata Entry = Entry {\n photos :: Int\n, coordX :: Int\n, coordY :: Int\n, time :: Int\n} deriving (Eq, Ord)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = photos . fromJust . Set.lookupMax . List.foldl' go [Entry 0 1 1 0]\n where\n go hist (tr, xr, yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n where\n r = Set.foldr brr minBound hist\n brr (Entry n x y t) a = if dist x y xr yr (tr - t) then a else n\n\nmain :: IO ()\nmain = do\n a <- fmap (fmap read . words) . tail . lines <$> getContents\n print $ solve $ fmap (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "{-# OPTIONS_GHC -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, OverloadedLists #-}\n\nimport Data.List as List\nimport Data.Set as Set\nimport Prelude\n\n-- data Entry = Entry {\n-- photos :: !Int\n-- , coordX :: !Int\n-- , coordY :: !Int\n-- , time :: !Int\n-- } deriving (Eq, Ord)\n\nfst4 (a, _, _, _) = a\n\nsolve :: [(Int, Int, Int)] -> Int\n-- solve = photos . Set.findMax . List.foldl' go [Entry 0 1 1 0]\nsolve = fst4 . Set.findMax . List.foldl' go [(0, 1, 1, 0)]\n where\n -- go hist (!tr, !xr, !yr) = if r == minBound then hist else Entry (r + 1) xr yr tr `Set.insert` hist\n go hist (!tr, !xr, !yr) = if r == minBound then hist else (r + 1, xr, yr, tr) `Set.insert` hist\n where\n r = List.foldr brr minBound $ toDescList hist\n -- brr (Entry n x y t) a = if abs (x - xr) + abs (y - yr) < tr - t then a else n\n brr (n, x, y, t) a = if abs (x - xr) + abs (y - yr) < tr - t then a else n\n\nmain :: IO ()\nmain = interact $ show . solve . fmap ((\\[x,y,z] -> (x,y,z)) . fmap read . words) . tail . lines\n"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Control.Monad\n\ndist :: Num a => (a, a) -> (a, a) -> a\ndist (!x, !y) (!z, !t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = best . head . foldl' go [Entry 1 1 0 0 0]\n where\n -- go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case filter (\\(Entry x y t _ _) -> dist (x, y) (xr, yr) <= tr - t) hist of\n -- [] -> hist\n -- a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n go hist@(Entry _ _ _ !best _ : _) (!tr, !xr, !yr) = if r == minBound then hist else Entry xr yr tr (max best r) r : hist\n where\n r = mx hist minBound\n mx (Entry x y t !bst !n : xs) !m\n | dist (x, y) (xr, yr) <= tr - t = mx xs m\n | n >= bst = max n m\n | otherwise = mx xs (max n m)\n mx [] !n = n\n -- mx (Entry _ _ _ !bst !x : xs) !n\n -- | n >= bst = max x n\n -- | otherwise = mx xs (max x n)\n -- mx [] !n = n\n\nmain :: IO ()\nmain = do\n a <- map (map read . words) . tail . lines <$> getContents\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map frt . foldl go [((1, 1), 0, 0, 0)]\n where\n go hist@((_, _, best, _):_) (tr, xr, yr) = ((xr, yr), tr, max best nm, nm) : hist\n where\n nm = case mapMaybe (\\(p, t, bst, n) -> if dist p (xr, yr) < tr - t then Just (bst, n) else Nothing) hist of\n [] -> minBound\n a -> mx a minBound + 1\n mx ((bst, x) : xs) n\n | n > bst = n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map frt . foldl go [((1, 1), 0, 0, 0)]\n where\n go hist@((_, _, best, _):_) (tr, xr, yr) = ((xr, yr), tr, max best nm, nm) : hist\n where\n nm = case mapMaybe (\\(p, t, bst, n) -> if dist p (xr, yr) < tr - t then Just (bst, n) else Nothing) hist of\n [] -> 0\n a -> mx a (-1) + 1\n mx ((bst, x) : xs) n\n | n >= bst = n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map frt . foldl go [((1, 1), 0, 0, 0)]\n where\n go hist@((_, _, best, _):_) (tr, xr, yr) = ((xr, yr), tr, max best nm, nm) : hist\n where\n nm = case mapMaybe (\\(p, t, bst, n) -> if dist p (xr, yr) <= tr - t then Just (bst, n) else Nothing) hist of\n [] -> 0\n a -> mx a (-1) + 1\n mx ((bst, x) : xs) n\n | n > bst = n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map frt . foldl go [((1, 1), 0, 0, 0)]\n where\n go hist@((_, _, best, _):_) (tr, xr, yr) = ((xr, yr), tr, max best nm, nm) : hist\n where\n nm = case mapMaybe (\\(p, t, bst, n) -> if dist p (xr, yr) < tr - t then Just (bst, n) else Nothing) hist of\n [] -> 0\n a -> mx a (-1) + 1\n mx ((bst, x) : xs) n\n | n > bst = n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nthd :: (a, b, c) -> c\nthd (_, _, c) = c\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map thd . foldl go [((1, 1), 0, 0)]\n where\n go hist (tr, xr, yr) = if nm == 0 then hist else ((xr, yr), tr, nm) : hist\n where\n nm = case mapMaybe (\\(p, t, n) -> if dist p (xr, yr) < tr - t then Just n else Nothing) hist of\n [] -> 0\n a -> maximum a + 1\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "import Data.List\nimport Data.Maybe\nimport Control.Monad\n\nfrt :: (a, b, c, d) -> d\nfrt (_, _, _, d) = d\n\ndist (x, y) (z, t) = abs (x - z) + abs (y - t)\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = maximum . map frt . foldl go [((1, 1), 0, 0, 0)]\n where\n go hist@((_, _, best, _):_) (tr, xr, yr) = ((xr, yr), tr, best, nm) : hist\n where\n nm = case mapMaybe (\\(p, t, bst, n) -> if dist p (xr, yr) < tr - t then Just (bst, n) else Nothing) hist of\n [] -> 0\n a -> mx a (-1) + 1\n mx ((bst, x) : xs) n\n | n >= bst = n\n | otherwise = mx xs (max x n)\n mx [] n = n\n\nmain = do\n [r, n] <- map read . words <$> getLine\n a <- replicateM n $ map read . words <$> getLine\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a"}, {"source_code": "{-# LANGUAGE NamedFieldPuns, RecordWildCards, Strict, BangPatterns #-}\n\nimport Data.List\nimport Control.Monad\n\ndist :: Num a => (a, a) -> (a, a) -> a\ndist (!x, !y) (!z, !t) = abs (x - z) + abs (y - t)\n\ndata Entry = Entry {\n coordX :: Int\n, coordY :: Int\n, time :: Int\n, best :: Int\n, photos :: Int\n}\n\nsolve :: [(Int, Int, Int)] -> Int\nsolve = best . head . foldl' go [Entry 1 1 0 0 0]\n where\n -- go hist@(Entry _ _ _ !best _:_) (!tr, !xr, !yr) = case filter (\\(Entry x y t _ _) -> dist (x, y) (xr, yr) <= tr - t) hist of\n -- [] -> hist\n -- a -> Entry xr yr tr (max best $ mx a (-1) + 1) (mx a (-1) + 1) : hist\n go hist@(Entry _ _ _ !best _ : _) (!tr, !xr, !yr) = if r == minBound then hist else Entry xr yr tr (max best r) r : hist\n where\n r = mx hist minBound\n mx (Entry x y t !bst !n : xs) !m\n | dist (x, y) (xr, yr) > tr - t = mx xs m\n | n >= bst = max n m\n | otherwise = mx xs (max n m)\n mx [] !n = n\n -- mx (Entry _ _ _ !bst !x : xs) !n\n -- | n >= bst = max x n\n -- | otherwise = mx xs (max x n)\n -- mx [] !n = n\n\nmain :: IO ()\nmain = do\n a <- map (map read . words) . tail . lines <$> getContents\n print $ solve $ map (\\[x, y, z] -> (x, y, z)) a\n"}], "src_uid": "1392daad6638b7a93e84dd474cdf916a"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Data.Array\n\n \nprocess s ls t = map (process1 1 ls) t\n\twhere process1 le ri m| s!mi ==m = mi\n\t\t\t | s!mi >m && s!(mi-1)m = process1 le (mi-1) m\n\t\t\t | otherwise = process1 (mi+1) ri m\n\t\twhere mi = div (le +ri) 2\nmain=do\t \n\tgetLine\n\ts<-map (fst. fromJust.C.readInt) . C.words <$>C.getLine:: IO [Int]\n\tlet ls = length s\n\tlet s1 = listArray (0,ls) $ scanl (+) 0 s \n\tgetLine\n\tt<-map (fst. fromJust.C.readInt) . C.words <$>C.getLine:: IO [Int]\n\tmapM_ print $ process s1 ls t\n\n\t", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Maybe\nimport Data.ByteString.Builder\n\n\nmain :: IO ()\nmain = do\n [[n], as,_,qs ] <- getIntLoLBs\n BS.putStrLn $ printMatrixBS $ matrixIntToBs $ solve n as qs\n\nreadMatrixBS :: BS.ByteString -> [[BS.ByteString]]\nreadMatrixBS = fmap BS.words . BS.lines\n\nmatrixToNumBs :: (Num a) => [[BS.ByteString]] ->[[a]]\nmatrixToNumBs = fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger\n\nsolve :: Int -> [Int] -> [Int] -> [[Int]]\nsolve n as qs =\n let sums = scanl (+) 1 as\n zipped = sums `zip` [1 ..]\n tree = fst $ buildT zipped n\n find v = findLabel v tree 0\n answers = map find qs\n in map return answers\n\ndata Tree a = Nil | Node a (Tree a) (Tree a) deriving (Show)\n\nbuildT :: [a] -> Int -> (Tree a, [a])\nbuildT xs 0 = (Nil, xs)\nbuildT xs n = (Node val leftSon rightSon, rightRems)\n where leftCount = n `div` 2\n (leftSon, leftRems) = buildT xs leftCount\n val = head leftRems\n (rightSon, rightRems) = buildT (tail leftRems) (n - leftCount - 1)\n\nfindLabel :: (Ord value) => value -> Tree (value, label) -> label -> label\nfindLabel _ Nil prevGuess = prevGuess\nfindLabel v' (Node (v,label) left right) prevGuess\n | v' > v = findLabel v' right label\n | v' < v = findLabel v' left prevGuess\n | otherwise = label\n\ngetIntLoLBs :: IO [[Int]]\ngetIntLoLBs = do\n c <- BS.getContents\n return . matrixToNumBs . readMatrixBS $ c\n\nmatrixIntToBs :: (Integral a) => [[a]] -> [[BS.ByteString]]\nmatrixIntToBs = fmap.fmap $ (toLazyByteString . integerDec . toInteger)\n\nprintMatrixBS :: [[BS.ByteString]] -> BS.ByteString\nprintMatrixBS = BS.unlines . fmap BS.unwords"}, {"source_code": "module Main (main)\n where\n\nimport Data.Maybe (mapMaybe)\nimport Data.Array (Ix, Array, listArray, bounds, (!))\nimport Control.Monad (mapM_)\n\ntype Bucket = (Int,Int)\n\n\npile :: (Integral i, Ix i) => Int -> Array i (Int,Bucket) -> Maybe Int\npile i a = search a i 0 $ snd $ bounds a\n where search xs needle lo hi\n | hi <= lo = Nothing\n | needle < a = search xs needle lo mid\n | needle > b = search xs needle (mid + 1) hi\n | otherwise = Just p\n where mid = lo + (hi - lo) `div` 2\n (p,(a,b)) = xs!mid\n\nbuckets :: [Int] -> [Bucket]\nbuckets xs = zipWith (\\a b -> (a + 1, b)) s $ tail s\n where s = 0:scanl1 (+) xs\n\nmain :: IO ()\nmain = do\n a <- getLine >> getLine\n q <- getLine >> getLine\n let [as,qs] = map (map read . words) [a,q]\n let bs = listArray (0, length as) $ zip [1..] $ buckets as\n mapM_ print $ mapMaybe (flip pile bs) qs"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n getLine\n cs <- getInts\n\n let\n s = sum cs\n is = listArray (1, s) $ concat $ zipWith (\\c i -> replicate c i) cs [1..] :: UArray Int Int\n\n getLine\n qs <- getInts\n\n putStrLn $ unlines $ map show $ map (is!) qs\n"}, {"source_code": "import Control.Monad\nimport Text.Printf\nimport Data.List\nimport Data.Array\n\nbisearch :: Array Int Int -> (Int, Int) -> Int -> Int\nbisearch a (lb, rb) q\n | rb-lb == 1= rb\n | me >= q = bisearch a (lb, md) q\n | otherwise = bisearch a (md, rb) q\n where md = (lb+rb) `div` 2\n me = a ! md\n\nsolve = bisearch\n\nmain = do\n n <- getLine >>= return . (read :: String -> Int)\n a <- getLine >>= return . listArray (0,100010) . scanl (+) 0 . map (read :: String -> Int) . words\n m <- getLine >>= return . (read :: String -> Int)\n q <- getLine >>= return . map (read :: String -> Int) . words\n forM_ (q >>= return . solve a (0, n)) print\n\n"}, {"source_code": "import Data.List\nimport Data.Tree \nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Functor\nimport Data.Bits\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Arrow\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed as UA\nimport Data.STRef\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as C\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = getLine>>= \\n-> (solve.(\\[a,b,c]->[[read n], a,c]) =<< forM [1 ..3] ( \\i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))\nsolve [n,xs,ys] =let m = slv1 xs; tr=slv2 1 (head n) m in forM_ ys $ \\i -> print $ slv3 i tr\nslv1 xs = let s= scanl (+) 0 xs in Map.fromList $ zip [1..] $ zip s (tail s) \nslv2 x1 x2 m = unfoldTree f (x1,x2)\n where\n f (b1,b2)=let z=((b2-b1) `div`2)+b1 in if b1==b2 then ((b1,m Map.!b1),[]) else if z==b1 then ((z,m Map.!z),[(b2,b2)]) else ((z,m Map.!z), [(b1, z-1),(z+1,b2)] )\nslv3 n (Node (z,(x,y)) []) = z\nslv3 n (Node (z,(x,y)) fs) | n> x && n<=y =z\n | n==x =z-1\n | n==y+1 =z+1\n | ny+1 = slv3 n (last fs)"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\nsolve :: [Int] -> [Int] -> [Int]\nsolve as ms = \n binSearch 0 (length as) <$> ms\n where as' = listArray (0, length as) $ scanl (+) 0 as\n binSearch :: Int -> Int -> Int -> Int\n binSearch l r v\n | l == r = r \n | v <= d = binSearch l m v\n | d < v = binSearch (m + 1) r v\n where m = l + (div (r-l) 2)\n d = as' ! m\n\nmain = do\n getLine\n as <- fmap read.words <$> getLine\n getLine\n ms <- fmap read.words <$> getLine\n let q = solve as ms\n mapM_ print q\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport qualified Data.IntMap.Strict as M\n\n\n\n\n\n\n\nmain = do\n C.getLine\n s<- scanl1 (+) <$> map (fst.fromJust.C.readInt) <$> C.words <$> C.getLine ::IO [Int]\n let s1 = M.fromList $ zip s [1..]\n C.getLine\n t<- map (fst.fromJust.C.readInt) <$> C.words <$> C.getLine ::IO [Int]\n mapM_ print $ map (\\z->snd $ fromJust $ M.lookupGE z s1) t\n"}, {"source_code": "import qualified Data.Array as A\n\nmain :: IO ()\nmain = getContents >>= mapM_ print . solve . map (map read . words) . lines\n\nsolve :: [[Int]] -> [Int]\nsolve [[n], as, _, qs] = map (binsearch (A.listArray (0, n) (scanl (+) 0 as))) qs\nsolve _ = undefined\n\nbinsearch :: A.Array Int Int -> Int -> Int\nbinsearch xs x = go (A.bounds xs)\n where go (a, b) | a + 1 == b = b\n | x <= xs A.! c = go (a, c)\n | otherwise = go (c, b)\n where c = (a + b) `div` 2\n"}, {"source_code": "import Data.Array\nmain = do\n n <- readLn\n as <- fmap (listArray (0,n) . scanl (+) 0 . map read . words) getLine\n let bsearch l r i | r - l <= 1 = r\n | as!m < i = bsearch m r i\n | otherwise = bsearch l m i\n where m = div (l + r + 1) 2\n getLine\n sequence . map (print . bsearch 0 n . read) . words =<< getLine\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n _m<-getLine\n qs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show $ solve n xs qs\n\nsolve :: Int -> [Int] -> [Int] -> [Int]\nsolve n xs qs = map query qs\n where\n arr :: UArray Int Int\n !arr = listArray(0,n)$scanl1(+)$0:xs\n query q = lowerBound (\\i->unsafeAt arr i>=q) 0 n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Text.Printf\nimport Data.List\nimport Data.Array\n\nbisearch :: Array Int Int -> (Int, Int) -> Int -> Int\nbisearch a (lb, rb) q\n | rb-lb == 1= rb\n | q < me = bisearch a (lb, md) q\n | otherwise = bisearch a (md, rb) q\n where md = (lb+rb) `div` 2\n me = a ! md\n\nsolve = bisearch\n\nmain = do\n n <- getLine >>= return . (read :: String -> Int)\n a <- getLine >>= return . listArray (0,100010) . scanl (+) 0 . map (read :: String -> Int) . words\n m <- getLine >>= return . (read :: String -> Int)\n q <- getLine >>= return . map (read :: String -> Int) . words\n forM_ (q >>= return . solve a (0, n)) print\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, range, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-}\n{-# INLINE rev #-}\nfor :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()\nfor !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)\n{-# INLINE for #-} \nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nlowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i\nlowerBound p low high = assert (low>=0 && p high) $ go low high\n where\n go !low !high\n | high <= low = high\n | p mid = go low mid\n | otherwise = go (mid + 1) high\n where\n mid = (low + high) `quot` 2\n{-# INLINE lowerBound #-}\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map readInt.B.words <$> B.getLine\n _m<-getLine\n qs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map show $ solve n xs qs\n\nsolve :: Int -> [Int] -> [Int] -> [Int]\nsolve n xs qs = map (succ.query.pred) qs\n where\n arr :: UArray Int Int\n !arr = listArray(0,n-1)$scanl1(+)xs\n query q = lowerBound (\\i->unsafeAt arr i>=q) 0 (n-1)"}], "src_uid": "10f4fc5cc2fcec02ebfb7f34d83debac"} {"source_code": "main = fmap (map read . words) getLine >>= \\[_,a,b] -> getLine >>= print . solve a b\n\nsolve a b = solve_ (swap a b) . map oddEven . countDot\n where swap a b = if a > b then (a,b) else (b,a)\n\nsolve_ (0,0) _ = 0\nsolve_ (a,b) [] = 0\nsolve_ (a,b) ((x,y):xs)\n | a - a' > b - b' = a' + b' + solve_ (a - a', b - b') xs\n | otherwise = a' + b' + solve_ (b - b', a - a') xs\n where a' = min a x\n b' = min b y\n\noddEven x\n | even x = (x `div` 2, x `div` 2)\n | otherwise = (x `div` 2 + 1, x `div` 2)\n\ncountDot = count . break (=='*')\n where count (a,[]) = [length a]\n count (a,(_:bs)) = length a : countDot bs\n", "positive_code": [{"source_code": "main = fmap (map read . words) getLine >>= \\[_,a,b] -> getLine >>= print . run a b\n\nrun a b = solve (swap_ a b) . map f . free\n where\n f x = let mid = x `div` 2 in let t = if even x then mid else mid + 1 in (t, mid)\n swap_ a b = if a > b then (a,b) else (b,a)\n solve a1 b1 = case (a1, b1) of\n ((0,0), _) -> 0\n ((a,b), []) -> 0\n ((a,b), ((x,y):xs)) ->\n let a_ = min a x\n b_ = min b y in\n a_ + b_ + solve (swap_ (a - a_) (b - b_)) xs\n free = count . break (=='*')\n where count (a1, b1) = case (a1, b1) of\n (a,[]) -> [length a]\n (a,(_:bs)) -> length a : free bs\n"}, {"source_code": "main = getContents >>= print . solve . parse . words . map toblank\n where parse (_:a:b:xs) = (read a, read b, map length xs)\n toblank c = if c == '*' then ' ' else c\n\nsolve (a,b,xs) = solve_ (swap a b) $ map oddEven xs\n where swap a b = if a > b then (a,b) else (b,a)\n oddEven x = let a = x `div` 2 in (x - a, a)\n\nsolve_ (0,0) _ = 0\nsolve_ (a,b) [] = 0\nsolve_ (a,b) ((x,y):xs)\n | a - a' > b - b' = a' + b' + solve_ (a - a', b - b') xs\n | otherwise = a' + b' + solve_ (b - b', a - a') xs\n where a' = min a x\n b' = min b y\n"}], "negative_code": [], "src_uid": "6208dbdf9567b759b0026db4af4545a9"} {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)", "positive_code": [{"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)"}, {"source_code": "\nimport Data.Array\nimport Data.Maybe\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\n\nfindId name = fromJust $ elemIndex name names\n where\n names = [\"Anka\", \"Chapay\", \"Cleo\", \"Troll\", \"Dracul\", \"Snowy\", \"Hexadecimal\"]\n\nparseLine line = (findId (ws !! 0), findId (ws !! 2))\n where\n ws = words line\n\nsolve :: Array (Int,Int) Bool -> [Int] -> (Int, Int)\nsolve arr exp = minimum $ map score seps\n where\n r = [0..6]\n seps :: [[[Int]]]\n seps = [ [x \\\\ y, y, r \\\\ x]\n | x <- subsequences r\n , x /= r && x /= []\n , y <- subsequences x\n , y /= x && y /= []\n ]\n score sep = (maximum scores - minimum scores, negate . sum $ map likes sep)\n where\n scores = zipWith div exp $ map length sep\n likes grp = length [True | a <- grp , b <- grp, arr ! (a, b)]\n\nmain = do\n n <- read <$> getLine :: IO Int\n likes <- replicateM n (parseLine <$> getLine)\n let arr = accumArray (||) False ((0,0),(6,6)) $ map (\\x -> (x,True)) likes\n exp <- map read . words <$> getLine :: IO [Int]\n let (minv, maxv) = solve arr exp\n putStrLn $ show minv ++ \" \" ++ show (negate maxv)\n"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}, {"source_code": "import Data.Char\n\nimport Control.Monad\nimport Data.Int(Int64)\nimport Data.List\nimport Data.Maybe\nimport Control.Applicative\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine\n\nunsafeReadInt :: String -> Int\nunsafeReadInt = read\nreadLiking = do\n [a,_,b] <- words <$> getLine\n return (read a, read b)\n\ndata Boss = A | B | C deriving (Eq, Show)\ndata Hero = Anka | Chapay | Cleo | Troll | Dracul | Snowy | Hexadecimal deriving (Read, Eq)\n\nallHeroes = [Anka, Chapay, Cleo, Troll, Dracul, Snowy, Hexadecimal]\n\nassignments :: Int -> [[Boss]]\nassignments 0 = [[]]\nassignments i = let next = assignments (i-1) in (map (A :) next) ++ (map (B :) next) ++ (map (C :) next)\n\nallAssignments = assignments 7\n\nlikes likings i j = any (\\(a, b) -> a == (allHeroes !! i) && b == (allHeroes !! j)) likings\n\nliking likings assignment = length [() | p <- [0..6], q <- [0..6], likes likings p q, assignment !! p == assignment !! q]\n\nexpFrom :: Boss -> Int -> [Boss] -> Int\nexpFrom boss totalExp assignment = totalExp `div` length (filter (==boss) assignment)\n\nmaxDiff :: [Int] -> Int\nmaxDiff l = maximum l - minimum l\n\nexpdiff (a,b,c) assignment = maxDiff [\n expFrom A a assignment ,\n expFrom B b assignment ,\n expFrom C c assignment ]\n\nallBossesDead assignment = any (==A) assignment && any (==B) assignment && any (==C) assignment \n\nmain = do\n [n] <- readInts\n likings <- sequence $ replicate n readLiking\n [a,b,c] <- readInts\n let exps = (a,b,c)\n let cmp a1 a2 = let md1 = expdiff exps a1\n md2 = expdiff exps a2\n in if md1 < md2 then LT else if md1 > md2 then GT else\n compare (liking likings a2) (liking likings a1)\n let bestAssignment = minimumBy cmp (filter allBossesDead allAssignments)\n putStrLn (unwords [show (expdiff exps bestAssignment), show (liking likings bestAssignment)])\n "}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}, {"source_code": "main=interact$p.minimum.t(words \"An Ch Cl Tr Dr Sn He\")[][][].i.tail.lines\ni x=(map(map(take 2).words)$init x,map read.words$last x)\nt(a:b)x y z r=concat [t b(a:x)y z r,t b x(a:y)z r,t b x y(a:z)r]\nt[]x y z(l,b)|any null w=[]|1>0=[(maximum d-minimum d,-sum e)]\n where\n (d,e)=unzip (zipWith f b w)\n w=[x, y, z]\n f b i=(b`div`length i,length$filter(\\[g,_,h]->elem g i&&elem h i)l)\np(a,b)=show a++\" \"++show(-b)\n"}], "negative_code": [], "src_uid": "4ee20979c25c37eed38da902011988d1"} {"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n\r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n\r\nisqrt :: Int -> Int\r\nisqrt = floor . sqrt . fromIntegral\r\n\r\nsolveSingle :: IO()\r\nsolveSingle = do\r\n arr <- readIntArr\r\n let x = arr !! 0\r\n let y = arr !! 1\r\n if (x == 0 && y == 0)\r\n then\r\n print(0)\r\n else if (isqrt(x * x + y * y) * isqrt(x * x + y * y) == x * x + y * y)\r\n then print(1)\r\n else print(2)\r\n\r\nsolve :: Int -> IO ()\r\nsolve n = if (n == 0)\r\n then\r\n pure()\r\n else do\r\n solveSingle\r\n solve(n - 1)\r\n\r\nmain :: IO ()\r\nmain = do\r\n n <- readInt\r\n solve $ n\r\n", "positive_code": [{"source_code": "parseInt :: String -> Int\r\nparseInt number = (read number) :: Int\r\n\r\nreadInt :: IO Int\r\nreadInt = do\r\n number <- getLine\r\n pure $ parseInt number\r\n \r\nreadIntArr :: IO [Int]\r\nreadIntArr = do\r\n numbers <- getLine\r\n pure $ map parseInt $ words numbers\r\n\r\nisqrt :: Int -> Int\r\nisqrt = floor . sqrt . fromIntegral\r\n\r\nsolve :: IO()\r\nsolve = do\r\n (x: y: _) <- readIntArr\r\n if (x == 0 && y == 0)\r\n then print 0\r\n else let s = isqrt (x * x + y * y)\r\n in if (s * s == x * x + y * y)\r\n then print 1\r\n else print 2\r\n\r\nfor :: Int -> IO () -> IO ()\r\nfor 0 _ = pure ()\r\nfor i f = do\r\n f\r\n for (i - 1) f\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readInt\r\n for t solve"}], "negative_code": [], "src_uid": "fce6d690c2790951f7e04c622c3c2d44"} {"source_code": "import Control.Monad\n\ntype Sector = (Integer, Integer)\n\nmain = do\n [n, m, tests] <- readNums\n let common = gcd n m\n realN = n `div` common\n realM = m `div` common\n\n results <- replicateM (fromInteger tests) $ (solve realN realM)\n putStr . unlines $ results\n\nreadNums :: IO [Integer]\nreadNums = map (\\tok -> read tok :: Integer) . words <$> getLine\n\nsolve :: Integer -> Integer -> IO String\nsolve n m = do\n [x1, y1, x2, y2] <- readNums\n let source = (x1, y1)\n dest = (x2, y2)\n return (if canReach source dest (n, m) then \"YES\" else \"NO\")\n\ncanReach :: Sector -> Sector -> (Integer, Integer) -> Bool\ncanReach source dest (n, m) =\n let indexSource = index source (n, m)\n indexDest = index dest (n, m)\n in indexSource == indexDest\n\nindex :: Sector -> (Integer, Integer) -> Integer\nindex (x, y) (n, m) = (y - 1) `div` (if x == 1 then n else m)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = do\n\t[ n, m, q ] <- readIntegers\n\tlet\n\t\tunits = lcm n m\n\t\twidth = units `div` gcd n m\n-- \tprint units\n-- \tprint width\n-- \tputStrLn \"==========\"\n\treplicateM ( fromIntegral q ) $ do\n\t\t[ sx, sy', ex, ey' ] <- readIntegers\n\t\tlet\n\t\t\tsy = pred sy'\n\t\t\tey = pred ey'\n\t\t\tu1 = units `div` ( which n m $ sx == 1 ) * sy `div` width\n\t\t\tu2 = units `div` ( which n m $ ex == 1 ) * ey `div` width\n-- \t\tprint u1\n-- \t\tprint u2\n\t\tputStrLn $ which \"YES\" \"NO\" $ u1 == u2"}, {"source_code": "import Control.Monad\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\ngetInteger :: IO Integer\ngetInteger = read <$> getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = fmap (fst . fromJust . C.readInteger) . C.words <$> C.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n [n,m,q] <- getIntegers\n let d = gcd n m\n rn = n `div` d\n rm = m `div` d\n replicateM_ (fromIntegral q) $ do\n [sx,sy,ex,ey] <- getIntegers\n putStrLn $ if solve rn rm sx sy ex ey then \"YES\" else \"NO\"\n\nsolve :: Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Bool\nsolve rn rm 1 sy 1 ey = pred sy `div` rn == pred ey `div` rn\nsolve rn rm 1 sy 2 ey = pred sy `div` rn == pred ey `div` rm\nsolve rn rm 2 sy 1 ey = pred sy `div` rm == pred ey `div` rn\nsolve rn rm 2 sy 2 ey = pred sy `div` rm == pred ey `div` rm\n\n\n\n\n"}], "negative_code": [{"source_code": "import Control.Monad\n\n--\n-- UTILITIES\n--\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\n\ngetInt :: IO Int\ngetInt = read <$> getLine\n\ngetInts :: IO [Int]\ngetInts = fmap (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\n--\n-- MAIN\n--\n\nmain :: IO ()\nmain = do\n [n,m,q] <- getInts\n let d = gcd n m\n rn = n `div` d\n rm = m `div` d\n replicateM_ q $ do\n [sx,sy,ex,ey] <- getInts\n putStrLn $ if solve rn rm sx sy ex ey then \"YES\" else \"NO\"\n\nsolve :: Int -> Int -> Int -> Int -> Int -> Int -> Bool\nsolve rn rm 1 sy 1 ey = pred sy `div` rn == pred ey `div` rn\nsolve rn rm 1 sy 2 ey = pred sy `div` rn == pred ey `div` rm\nsolve rn rm 2 sy 1 ey = pred sy `div` rm == pred ey `div` rn\nsolve rn rm 2 sy 2 ey = pred sy `div` rm == pred ey `div` rm\n\n\n\n\n"}], "src_uid": "d4ae071cf261ec3d91187a9a7dddcda0"} {"source_code": "{-# LANGUAGE UnicodeSyntax #-}\n\nimport Control.Applicative\nimport Data.Maybe\n\nreadWords = map read . words <$> getLine\n\nsolve n b as = \n\t\tif any (\\a \u2192 s < a * n) as\n\t\t\tthen Nothing\n\t\t\telse Just $ map (\\a \u2192 s/n - a) as\n\twhere\n\t\ts = b + sum as\n\nmain = do\n\t[n, b] \u2190 readWords\n\tas \u2190 readWords\n\n\tlet r = solve n b as\n\tif isNothing r\n\t\tthen putStrLn \"-1\"\n\t\telse mapM_ print $ fromJust r\n", "positive_code": [{"source_code": "main = do interact (unlines . gao . map read . words)\ngao (n:m:a) = if d <= m then map (\\i -> show $ i + (m - d) / n) c else [\"-1\"] where\n b = maximum a\n c = map (b-) a\n d = sum c\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport System.IO\nimport System.IO.Error\n\n\nhReadMany :: (Char -> Bool) -> Handle -> IO String\nhReadMany p h = do b <- (p <$> hLookAhead h) `catch` const (return False)\n if b\n then (:) <$> hGetChar h <*> hReadMany p h\n else return \"\"\n\nhSkipSpaces = hReadMany isSpace\nhReadNumeric = hReadMany (\\c -> isDigit c || c `elem` ['.', '-', '+'])\n\nreadNum :: (Num a, Read a) => IO a\nreadNum = do hSkipSpaces stdin\n read <$> hReadNumeric stdin\n\nreadTerm :: IO String\nreadTerm = do hSkipSpaces stdin\n hReadMany (not . isSpace) stdin\n\nmain = do n <- readNum :: IO Double\n b <- readNum :: IO Double\n\n mugs <- replicateM (round n) readNum\n\n let max_ml = maximum mugs -- \u6700\u5927\u306b\u5408\u308f\u305b\u308b\n let need_more = [ max_ml - m | m <- mugs] -- \u5f8c\u305d\u308c\u305e\u308c\u3001\u3053\u308c\u3060\u3051\u5165\u308c\u308c\u3070\u5e73\u7b49\n let total_filling = sum need_more -- \u5e73\u7b49\u306e\u305f\u3081\u306b\u5fc5\u8981\u306a\u9001\u6599\n let redundant_each = (b - total_filling) / n\n let actual_value = [ redundant_each + m | m <- need_more] -- \u4f59\u308a\u3092\u5e73\u7b49\u306b\u308f\u3051\u3066\u304b\u3089\u306e\u3001\u5404\u3005\u5fc5\u8981\u306a\u91cf\n\n if total_filling > b then print (-1)\n else mapM_ print actual_value\n "}, {"source_code": "\nreads :: Read a => IO [a]\nreads = getLine >>= sequence . map readIO . words\n\nsolve :: Int -> Int -> [Int] -> Maybe [Double]\nsolve n b' as\n | b < n * maximum as = Nothing\n | otherwise = Just $ map (\\a -> d - fromIntegral a) as\n where\n b = b' + sum as\n d = fromIntegral b / fromIntegral n\n\nprintAns :: Maybe [Double] -> IO ()\nprintAns Nothing = print (-1)\nprintAns (Just as) = mapM_ print as\n\nmain :: IO ()\nmain = do\n [n, b] <- Main.reads\n as <- Main.reads\n printAns $ solve n b as\n"}, {"source_code": "import Text.Printf\n\nmain = getContents >>= solve.map read.words\n\nsolve :: [Int] -> IO ()\nsolve (n:b:xs)\n | b < y = print $ -1\n | otherwise = mapM_ (printf \"%.6f\\n\".(z-).fromIntegral) xs\n where x = maximum xs\n y = sum $ map (x-) xs\n z :: Double\n z = (fromIntegral$b-y)/(fromIntegral n) + (fromIntegral x)"}, {"source_code": "import Text.Printf\n\nsolve :: (Double, [Double]) -> Maybe [Double]\nsolve (b, as) =\n if all (>= 0) res\n then Just res\n else Nothing\n where \n one = (b + sum as) / (fromIntegral $ length as)\n res = map (\\x -> one - x) as\n\n\npprint :: Maybe [Double] -> String\npprint (Just foo) = unlines $ map (printf \"%.7f\") foo\npprint Nothing = \"-1\"\n\nparse :: String -> (Double, [Double])\nparse foo =\n let [first, rest] = lines foo\n (_:nn:_) = words first\n n = read nn\n stuff = map read (words rest)\n in (n, stuff)\n\nmain = interact (pprint . solve . parse)\n"}], "negative_code": [{"source_code": "import Text.Printf\n\nsolve :: (Float, [Float]) -> Maybe [Float]\nsolve (b, as) =\n if all (>= 0) res\n then Just res\n else Nothing\n where \n one = (b + sum as) / (fromIntegral $ length as)\n res = map (\\x -> one - x) as\n\n\npprint :: Maybe [Float] -> String\npprint (Just foo) = unlines $ map (printf \"%.7f\") foo\npprint Nothing = \"-1\"\n\nparse :: String -> (Float, [Float])\nparse foo =\n let [first, rest] = lines foo\n (_:nn:_) = words first\n n = read nn\n stuff = map read (words rest)\n in (n, stuff)\n\nmain = interact (pprint . solve . parse)\n"}], "src_uid": "65fea461d3caa5a932d1e2c13e99a59e"} {"source_code": "import Data.List\nimport Data.Map (elems, fromList)\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as B\n\n{-\nsolve n = 1 + floor rem\n where root = logBase 2 n\n btm = floor root\n rem = if 2 ^ btm == n then 0 else n - (2 ^ btm)\n-}\n\n-- [(val, (t1, t2))]\nsorted :: [(Int, (Int, Int))] -> [(Int, (Int, Int))]\nsorted = reverse . sortBy sortFn\n where sortFn x y = compare (fst x) (fst y)\n\nprocess_ [] end teamed = end\nprocess_ (v:vs) end teamed\n | inTeam = process_ vs end teamed\n | otherwise = process_ vs (end ++ [(c, r)]) newA\n where c = (fst . snd) v\n r = (snd . snd) v\n inTeam = Set.member c teamed || Set.member r teamed\n newA = Set.insert c $ Set.insert r teamed\n\nsolve_ n values = process_ (sorted values) [] (Set.empty)\n\nmain :: IO ()\nmain = do\n n <- readLn\n let nl = n * 2 - 1\n strengths <- sequence $ replicate nl $ do\n line <- B.getLine\n return $ map (maybe (error \"a\") fst) . map B.readInt . B.words $ line\n let coords = [(y, x) | x <- [1..n*2], y <- [1..x-1]]\n let withRow = zip (concat strengths) coords\n let result = solve_ n $ withRow\n -- let vvv = [(6,(1,2)),(1,(1,3)),(2,(2,3)),(3,(1,4)),(4,(2,4)),(5,(3,4))]\n let showResult = concat . intersperse \" \" . map show . elems. fromList\n putStrLn $ showResult $ result ++ (map swap result)\n\n where swap (x, y) = (y, x)\n\n", "positive_code": [{"source_code": "-- Codeforces 579B\n\nimport Control.Monad\nimport Data.List\nimport Data.Function\nimport Data.Maybe\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as B\n\n-- Hint: get all combinations of (i, j), then sort it by the value of `d` in decreasing order.\n\nmain :: IO ()\nmain = B.getContents >>= putStrLn . intercalate \" \" . map show . solve . map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [Int] -> [Int]\nsolve (n:xs) = map snd $ sort $ fst $ foldl (\\(now, acc) (x, y) -> if (Set.member x acc) || (Set.member y acc) then (now, acc) else ((x,y):(y,x):now, (Set.insert x $ Set.insert y acc))) ([], Set.empty) $ map snd $ reverse $ sort $ zip xs [(i,j) | i <- [1..2*n], j <- [1..i-1]]\n"}, {"source_code": "import Data.List (intercalate, sort)\nimport Data.Set hiding (map)\nmain=interact $ solve. map read. words\n\nsolve (n:xs) = ret\n where score = map snd $ reverse $ sort $ zip xs [(x,y) | x<-[2..2*n], y<-[1..x-1]]\n f [] _ = []\n f _ set | size set == 2*n = []\n f ((pair@(x,y)):ss) set | member x set || member y set = f ss set\n | otherwise = [pair, (y,x)] ++ f ss (insert y $ insert x set)\n ret = intercalate \" \" $ map (show.snd) $ sort $ f score empty"}, {"source_code": "import Data.List (intercalate, sort)\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\n\nmain = do putStrLn. solve =<< map (fst . fromJust . B.readInt) . B.words <$> B.getContents\nsolve (n:xs) = ret\n where score = map snd $ reverse $ sort $ zip xs [(x,y) | x<-[2..2*n], y<-[1..x-1]]\n f [] _ = []\n f _ set | S.size set == 2*n = []\n f ((pair@(x,y)):ss) set | S.member x set || S.member y set = f ss set\n | otherwise = [pair, (y,x)] ++ f ss (S.insert y $ S.insert x set)\n ret = intercalate \" \" $ map (show.snd) $ sort $ f score S.empty"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n\n cs <- replicateM (2*n-1) getInts\n\n let ps = reverse $ sort $ concat $ zipWith (\\cs i -> zipWith (\\j c -> (c, (i, j))) [1..i] cs) cs [2..2*n]\n\n let\n f [] l s = l\n f ((c, (i, j)):ps) l s\n | i `Set.member` s || j `Set.member` s = f ps l s\n | otherwise = f ps ((i, j):(j, i):l) (i `Set.insert` (j `Set.insert` s))\n\n\n a = array (1, 2*n) $ f ps [] Set.empty :: Array Int Int\n\n putStrLn $ unwords $ map show $ elems a\n"}, {"source_code": "import Data.List (intercalate, sort)\nimport Data.Map (elems, fromList)\nimport qualified Data.Set as Set\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nprocess [] teamed = []\nprocess ((c, r):vs) teamed\n | inTeam = process vs teamed\n | otherwise = (c, r):(r, c):process vs newA\n where inTeam = Set.member c teamed || Set.member r teamed\n newA = Set.insert c $ Set.insert r teamed\n\nsolve (n:vs) = process scores (Set.empty)\n where coords = [(y, x) | x <- [1..n*2], y <- [1..x-1]]\n scores = map snd . reverse . sort $ zip vs coords\n\nshowResult result = putStrLn . s $ result\n where s = intercalate \" \" . map show . elems . fromList\n\nmain = do\n contents <- B.getContents\n let values = map (fst . fromJust . B.readInt) . B.words $ contents\n showResult $ solve values\n"}], "negative_code": [{"source_code": "import Data.List (intersperse, sort)\nimport Data.Set (insert, member, empty)\nmain=interact $ solve. map read. words\n\nsolve (n:xs) = ret\n where score = map snd $ reverse $ sort $ zip xs [[x,y] | x<-[2..2*n], y<-[1..x-1]]\n f [] _ = []\n f ((pair@[x,y]):ss) set | member x set || member y set = f ss set\n | otherwise = [pair, reverse pair] ++ f ss (insert y $ insert x set)\n ret = intersperse ' ' $ concatMap (show.head.tail) $ sort $ f score empty"}, {"source_code": "import Data.List (intersperse, sort)\nimport Data.Set hiding (map)\nmain=interact $ solve. map read. words\n\nsolve (n:xs) = ret\n where score = map snd $ reverse $ sort $ zip xs [[x,y] | x<-[2..2*n], y<-[1..x-1]]\n f [] _ = []\n f _ set | size set == 2*n = []\n f ((pair@[x,y]):ss) set | member x set || member y set = f ss set\n | otherwise = [pair, reverse pair] ++ f ss (insert y $ insert x set)\n ret = intersperse ' ' $ concatMap (show.head.tail) $ sort $ f score empty"}, {"source_code": "import Data.List\nmain=interact $ solve. map read. words\n\nsolve (n:xs) = ret\n where score = sort $ zip xs [[x,y] | x<-[2..2*n], y<-[1..x-1]]\n f _ 0 = []\n f score n = let (_,pair) = head score\n score' = filter ((==4) . length . nub . (pair++) . snd) score\n in [pair, reverse pair] ++ f score' (n-1)\n ret = intersperse ' ' $ concatMap (show.head.tail) $ sort $ f score n"}, {"source_code": "import Data.List\nimport Data.Map (elems, fromList)\nimport qualified Data.Set as Set\n\n{-\nsolve n = 1 + floor rem\n where root = logBase 2 n\n btm = floor root\n rem = if 2 ^ btm == n then 0 else n - (2 ^ btm)\n-}\n\n-- [(val, (t1, t2))]\nsorted :: [(Int, (Int, Int))] -> [(Int, (Int, Int))]\nsorted = reverse . sortBy sortFn\n where sortFn x y = compare (fst x) (fst y)\n\nprocess_ [] end teamed = end\nprocess_ (v:vs) end teamed\n | inTeam = process_ vs end teamed\n | otherwise = process_ vs (end ++ [(c, r)]) newA\n where c = (fst . snd) v\n r = (snd . snd) v\n inTeam = Set.member c teamed || Set.member r teamed\n newA = Set.insert c $ Set.insert r teamed\n\nsolve_ n values = process_ (sorted values) [] (Set.empty)\n\nmain :: IO ()\nmain = do\n n <- readLn\n let nl = n * 2 - 1\n strengths <- sequence $ replicate nl $ do\n line <- getLine\n return (map read . words $ line :: [Int])\n let coords = [(y, x) | x <- [1..nl], y <- [1..x-1]]\n let withRow = zip (concat strengths) coords\n let result = solve_ n $ withRow\n -- let vvv = [(6,(1,2)),(1,(1,3)),(2,(2,3)),(3,(1,4)),(4,(2,4)),(5,(3,4))]\n let showResult = concat . intersperse \" \" . map show . elems. fromList\n putStrLn $ showResult $ result ++ (map swap result)\n\n where swap (x, y) = (y, x)\n\n"}, {"source_code": "import Data.List\nimport Data.Map (elems, fromList)\n\n{-\nsolve n = 1 + floor rem\n where root = logBase 2 n\n btm = floor root\n rem = if 2 ^ btm == n then 0 else n - (2 ^ btm)\n-}\n\n-- [(val, (t1, t2))]\nsorted :: [(Int, (Int, Int))] -> [(Int, (Int, Int))]\nsorted = reverse . sortBy sortFn\n where sortFn x y = compare (fst x) (fst y)\n\n-- get largest\nprocess [] start end = end\nprocess (v:vs) start end = process (newvs) nstart nend\n where (nstart, nend) = groupUp start end t1 t2\n t1 = (fst . snd) v\n t2 = (snd . snd) v\n newvs = filter fn vs\n fn = \\(v, (t3, t4)) -> and [t1/=t3, t1/=t4, t2/=t3, t2/=t4]\n\n\ngroupUp [] end _ _ = ([], end)\ngroupUp start end t1 t2 = (news, newe)\n where news = filter (\\s -> s /= t1 && s /= t2) start\n newe = end ++ [(t1, t2)]\n\nsolve values = process (sorted values) [1..n] []\n where n = (div (length values) 2 - 1) * 2\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n let nl = n * 2 - 1\n strengths <- sequence $ replicate nl $ do\n line <- getLine\n return (map read . words $ line :: [Int])\n let zipper = zipWith3 (\\c r v -> (v, (c, r)))\n let withRow = zipWith (\\r l -> zipper [1..] (repeat r) l) [2..] strengths\n let result = solve $ concat withRow\n putStrLn $ intersperse ' ' . concatMap show . elems . fromList $ result ++ (map swap result)\n where swap (x, y) = (y, x)\n"}], "src_uid": "8051385dab9d7286f54fd332c64e836e"} {"source_code": "import Prelude\nimport Control.Monad\n\nstr2Ints str = [read x::Int | x <- words str]\ngetLineN n = replicateM n getLine\n\nintersect a b = [x| x<-a, elem x a, elem x b]\n\npopfront (x:xs) = xs\n\nmain = do\n str <- getLine;\n let n = read str::Int;\n strs <- getLineN n;\n mapM (putStr.(++ \" \").show) (foldr1 intersect (map (popfront.str2Ints) strs));", "positive_code": [{"source_code": "import System.IO\nimport Control.Monad (replicateM)\n\ncount x xs = (length . filter (== x)) xs\n\nreadStations = do\n line <- fmap (fmap read . words) getLine :: IO [Int]\n return $ tail line\n\nmain = do\n n <- fmap read getLine :: IO Int\n all <- replicateM n readStations\n putStrLn $ unwords . (fmap show) $ filter (\\x -> count x (concat all) == n) [1..100]\n"}, {"source_code": "import System.IO\nimport Data.List\nimport Control.Monad\n\nnumTimesFound xs x = (length . filter (== x)) xs\n\nget = fmap read getLine\n\ngets = fmap (fmap read . words) getLine\n\nreadStations = do\n line <- gets :: IO [Int]\n return $ tail line\n\nmain = do\n n <- get :: IO Int\n all <- replicateM n readStations\n putStrLn $ unwords . (fmap show) $ filter (\\x -> numTimesFound (concat all) x == n) [1..100]\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\nimport Data.Char\nimport qualified Data.Set as S\n\nprocess s n m k | n>k || m>k = s\n | n words <$> getLine ::IO [Int]\n\t\tprint $ process 0 n m k\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\tx<-map tail <$> map (map read) <$> map words <$> replicateM n getLine :: IO [[Int]]\n\t\tputStrLn $ intercalate \" \"$ map show $ S.toList $ foldl1 (S.intersection) $ map (S.fromList) x\n\n"}, {"source_code": "import System.IO\nimport Data.Char\nimport Data.List\nimport Control.Applicative\nimport Control.Monad\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: BS.ByteString -> [Int]\nconstruct str\n | BS.null str = []\n | isSpace (BS8.head str) = construct (BS8.tail str)\n | otherwise = let Just (i, other) = BS8.readInt str in i : construct other\n\ngetInts :: IO [Int]\ngetInts = construct <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nmain = do\n [n] <- getInts\n stops <- forM [1..n] (\\_ -> getInts)\n let cand = filter (\\x -> all (\\s -> x `elem` s) (map (drop 1) $ stops)) [1..100]\n printInts cand"}], "negative_code": [], "src_uid": "16c54cf7d8b484b5e22a7d391fdc5cd3"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n w <- map read . words <$> getLine\n print (solve w)\n\nmkArray :: a -> [(Int, a)] -> [a]\nmkArray def = helper 0\n where\n helper _ [] = []\n helper n l@((i, x):xs)\n | i == n = x : helper (succ n) xs\n | otherwise = def : helper (succ n) l\n\nsolve :: [Int] -> Int\nsolve w = maximum $ map ((`div` 2) . sum . zipWith min l) (tails lr)\n where\n n = length w\n l = mkArray 0 . map (\\a -> (head a, length a)) . group . sort $ w\n lr = replicate n 0 ++ reverse l\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n n <- read <$> getLine\n ws <- sort . map read . words <$> getLine\n print $ maximum [teamsWithSum s ws | s <- [2 .. 2 * n]]\n\nteamsWithSum s ws = f ws (reverse ws) `div` 2\n where\n f (a : as) (b : bs)\n | a + b < s = f as (b : bs)\n | a + b == s = 1 + f as bs\n | otherwise = f (a : as) bs\n f _ _ = 0\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nteamsWithSum :: Int -> [Int] -> Int\nteamsWithSum s ws = f ws (reverse ws) `div` 2\n where\n f (a : as) (b : bs)\n | a + b < s = f as (b : bs)\n | a + b == s = 1 + f as bs\n | otherwise = f (a : as) bs\n f _ _ = 0\n\nsolve :: IO ()\nsolve = do\n n <- read <$> getLine\n ws <- sort . map read . words <$> getLine\n print $ maximum [teamsWithSum s ws | s <- [2 .. 2 * n]]\n\nmain :: IO ()\nmain = do\n getLine >>= flip replicateM_ solve . read\n "}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ getLine >> getLine >>= print . solve . map read . words\n\nmkArray :: a -> [(Int, a)] -> [a]\nmkArray def = helper 0\n where\n helper _ [] = []\n helper n l@((i, x):xs)\n | i == n = x : helper (succ n) xs\n | otherwise = def : helper (succ n) l\n\nsolve :: [Int] -> Int\nsolve w = maximum $ map ((`div` 2) . sum . zipWith min l) (tails lrev)\n where\n l = mkArray 0 . map (\\a -> (head a, length a)) . group . sort $ w\n lrev = replicate (length w) 0 ++ reverse l\n"}, {"source_code": "import GHC.Stack\nimport Control.Monad\nimport Data.List (group, sort)\nimport Data.Map (Map)\nimport qualified Data.Map as M\n\nmaximumOn :: (Ord b) => (a -> b) -> [a] -> a\nmaximumOn f [] = error \"Data.List.Extra.maximumOn: empty list\"\nmaximumOn f (x:xs) = g x (f x) xs\n where\n g v mv [] = v\n g v mv (x:xs) | mx > mv = g x mx xs\n | otherwise = g v mv xs\n where mx = f x\n\ndropAt 0 (x:xs) = xs\ndropAt i (x:xs) = dropAt (i-1) xs\n\ncombinations 0 xs = [[]]\ncombinations k xs = do\n (i, x) <- zip [0..] xs \n (x:) <$> combinations (k-1) (dropAt i xs)\n\ndecrement :: (HasCallStack, Ord k) => k -> Map k Int -> Map k Int\ndecrement = M.alter f\n where\n f Nothing = error \"Tried to decrement key that isn't there!\"\n f (Just x)\n | x-1 > 0 = Just (x-1)\n | otherwise = Nothing\n\nincrement :: (HasCallStack, Ord k) => k -> Map k Int -> Map k Int\nincrement = M.alter f\n where\n f Nothing = Just 1\n f (Just x) = Just (x+1)\n\nnumTeams :: HasCallStack => [Int] -> Int -> Int\nnumTeams weights target = snd $ foldr f (M.empty, 0) weights\n where\n f weight (counts, ans)\n | (target - weight) `M.member` counts = (decrement (target-weight) counts, ans+1)\n | otherwise = (increment weight counts, ans)\n\nuniq :: Ord a => [a] -> [a]\nuniq = map head . group . sort\n\nsolve :: HasCallStack => [Int] -> Int\nsolve [] = 0\nsolve [_] = 0\nsolve weights = maximum . map (numTeams weights) . uniq $ targets\n where targets = map sum $ combinations 2 weights\n\nmain = do\n numCases <- readLn\n replicateM_ numCases $ do\n getLine\n print =<< solve <$> fmap read <$> words <$> getLine\n"}, {"source_code": "import Control.Monad -- for replicateM_\nimport Data.List -- for sort\n\nsolve :: Int -> [Int] -> Int\nsolve goal xs = f xs (reverse xs) `div` 2\n where \n f (x:xs) (y:ys)\n | x + y < goal = f xs (y:ys) \n | x + y == goal = 1 + f xs ys\n | otherwise = f (x:xs) ys\n f _ _ = 0\n\ndeal :: IO()\ndeal = do \n n <- read <$> getLine\n a <- sort . map read . words <$> getLine\n putStrLn $ show $ maximum [solve s a | s <- [2 .. 2*n]]\n\nmain :: IO()\nmain = getLine >>= flip replicateM_ deal . read \n"}, {"source_code": "import Control.Monad (replicateM_)\nimport Data.List (group, groupBy, sort, tails) --'\nimport Data.Function (on)\n\nsolve :: [Int] -> Int\nsolve li = let\n sli = [(head x, length x) | x <- group (sort li)]\n pairSums = do\n ys <- tails sli\n let (x, kx) = head ys\n (y, ky) <- ys\n pure (x + y, if x == y then div kx 2 else min kx ky)\n counts = [sum ks | ks <- map (map snd) . groupBy ((==) `on` fst) $ sort pairSums]\n in maximum counts\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n _nStr <- getLine\n ws <- map read . words <$> getLine :: IO [Int]\n print $ solve ws\n"}, {"source_code": "{-# LANGUAGE Safe #-}\n\nimport safe Control.Arrow ((>>>))\nimport safe Data.List\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1\n >>> map (words >>> map read)\n >>> process\n >>> map show\n >>> unlines\n\nprocess :: [[Int]] -> [Int]\nprocess [] = []\nprocess ([_] : xs : rest) = solve xs : process rest\n\nsolve :: [Int] -> Int\nsolve [_] = 0\nsolve xs =\n maximum $\n (map length . group . sort . map (uncurry (+)) . filter (uncurry (<=)) . concatMap dropEqDup)\n (zip <$> gs <*> gs)\n where\n gs = group . sort $ xs\n\n dropEqDup :: [(Int, Int)] -> [(Int, Int)]\n dropEqDup xs\n | uncurry (==) (head xs) = take (length xs `div` 2) xs\n | otherwise = xs\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n w <- map read . words <$> getLine\n print (solve w)\n\nmkArray :: [(Int, a)] -> [a]\nmkArray = helper 0\n where\n helper _ [] = []\n helper n l@((i, x):xs)\n | i == n = x : helper (succ n) xs\n | otherwise = helper (succ n) l\n\nsolve :: [Int] -> Int\nsolve w = (`div` 2) . maximum $ map (sum . zipWith min l) (tails lr)\n where\n n = length w\n l = mkArray . map (\\a -> (head a, length a)) . group . sort $ w\n lr = replicate n 0 ++ reverse l\n"}], "src_uid": "0048623eeb27c6f7c6900d8b6e620f19"} {"source_code": "module Main where\n\nimport Data.Array\nimport Data.List\nimport Data.Char\n\nimport Data.Time.Calendar\n\nmain = interact (unwords . map show . solve . map read . words . (!! 1) . lines)\n\nstartTime = 10\nmiddleTime = (24 - 18) * 60\nendTime = (6 - 18 + 24) * 60\n\nsolve :: [Int] -> [Int]\nsolve times = result where\n result = cutProblems bestOrder\n bestOrder = sort times\n\ncutProblems :: [Int] -> [Int]\ncutProblems = cutProblems' startTime 0 0\ncutProblems' _ result tasks [] = [tasks, result]\ncutProblems' sm result tasks (x : xs) = if sm + x <= endTime\n then cutProblems' (sm + x) (result + if sm + x < middleTime then 0 else sm + x - middleTime) (tasks + 1) xs\n else [tasks, result]\n\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List (sort)\n\nmain = do\n getLine\n lengths <- (liftM (map read . words)) getLine\n let solveTimes = tail . takeWhile (<= 710) $ scanl (+) 0 (sort lengths)\n putStrLn $ show (length solveTimes) ++ \" \" ++ (show . sum $ map (\\x -> max 0 (x-350)) solveTimes)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\nend = 720 -- end time\n\ncost t = max 0 (t-360)\n\nsolve :: [Int] -> (Int,Int)\nsolve as = go 0 0 10 (sort as)\n where\n go !n c t [] = (n,c)\n go !n c t (a:as) | t+a <= end = go (n+1) (c+cost (t+a)) (t+a) as\n | otherwise = (n,c)\n\nmain = do\n n <- fmap read getLine :: IO Int\n as <- fmap (map read . words) getLine\n let (n,c) = solve as\n putStrLn $ show n ++ \" \" ++ show c\n return ()\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (sort)\nimport Prelude hiding (print, reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> (Int, Int)\nsolve xs = ((flip (-) 1) $ length $ takeWhile (<= 720) $ scanl (+) 10 $ sort xs, solve' 10 $ sort xs)\n where\n solve' time [] = 0\n solve' time (x:xs)\n | time' <= 360 = solve' time' xs\n | time' <= 720 = (time' - 360) + solve' time' xs\n | otherwise = 0\n where\n time' = time + x\n\nprint :: (Int, Int) -> IO ()\nprint (a, b) = putStrLn $ concat [show a, \" \", show b]\n\nmain :: IO ()\nmain = getLine >> reads >>= print . solve"}, {"source_code": "import Control.Applicative\nimport Text.Printf\nimport Data.List\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- sort . map read . words <$> getLine\n let (n,p) = foldl (\\(n,p) y -> (n+1, p + penalty y)) (0::Int,0) $ takeWhile (<= 710) $ scanl1 (+) xs\n printf \"%d %d\\n\" n p\n\npenalty :: Int -> Int\npenalty t\n | t <= 350 = 0\n | otherwise = t - 350\n"}, {"source_code": "import Data.List(scanl,sort)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n ts <- map read <$> words <$> getLine\n putStrLn $ solve n ts\n\nsolve :: Int -> [Int] -> String\nsolve _ ts = let (n,p) = fst $ last $ takeWhile ((<=710).snd) $ scanl f ((0,0),0) $ zip [1..] $ sort ts\n in (show n) ++ \" \" ++ (show p)\n\nf ((_,p),t) (n,s) = ((n, p + max 0 (s+t-350)), s+t)\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain = do\n getLine\n lengths <- (liftM (map read . words)) getLine\n let solveTimes = tail . takeWhile (<= 710) $ scanl (+) 0 lengths\n putStrLn $ show (length solveTimes) ++ \" \" ++ (show . sum $ map (\\x -> max 0 (x-350)) solveTimes)\n"}, {"source_code": "import Data.List(scanl1,sort)\nimport Control.Applicative\n\nmain = do n <- read <$> getLine\n ts <- map read <$> words <$> getLine\n putStrLn $ unwords $ map show $ solve n ts\n\nsolve :: Int -> [Int] -> [Int]\nsolve _ ts = let (n,t) = last $ takeWhile ((<=710).snd) $ zip [0..] $ scanl1 (+) $ 0:sort ts\n in [n,max 0 (t-350)]\n"}], "src_uid": "76f94436b4388682b25c7213248b76a2"} {"source_code": "import Data.Int\nimport Data.Tree\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Foldable (toList)\nimport Control.Monad (when)\nimport Data.Array.IArray\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString.Char8 as C\nf2read' :: Int -> Char -> Int\nf2read' x y = 10 * x + ord y - ord '0'\n\nf2read :: C.ByteString -> Int\nf2read x = C.foldl' f2read' 0 x\n\nf2show :: Int -> C.ByteString\nf2show x = C.reverse $ C.cons ' ' $ fst $ C.unfoldrN 8 (\\x -> if x /= 0 then Just (chr $ rem x 10 + ord '0', div x 10) else Nothing) x\n\nf2lines :: C.ByteString -> [C.ByteString]\nf2lines x = map (\\x -> if (C.last x == '\\r') then (C.init x) else x) (C.lines x)\n\nindexed :: Int -> [a] -> [(Int, a)]\nindexed _ [] = []\nindexed i (x:xs) = (i, x) : (indexed (i+1) xs)\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n go (Node x ts) = f x (map go ts)\n\nf2folder :: Int -> [(Int, (S.Seq Int, S.Seq Int))] -> (Int, (S.Seq Int, S.Seq Int))\nf2folder v ls = (s, (bef, aft))\n where s = rem ((+1) $ sum $ map fst ls) 2\n bef' = foldl' (S.><) S.empty $ map (fst . snd) ls\n aft' = foldl' (S.><) S.empty $ map (snd . snd) ls\n bef = if s == 0 then (v S.<| bef') else bef'\n aft = if s == 1 then (v S.<| aft') else aft'\n\nsolve :: Tree Int -> Maybe [Int]\nsolve t = if s == 1 then Just $ toList ((S.reverse bef) S.>< aft) else Nothing\n where ans = foldTree f2folder t\n s = fst ans\n bef = fst (snd ans)\n aft = snd (snd ans)\n\nf2buildTree :: [Int] -> Tree Int\nf2buildTree xs = unfoldTree (\\x -> (x, a!x)) (head $ a!0)\n where n = length xs\n a = accumArray (\\x y -> y : x) [] (0, n) (map swap (indexed 1 xs)) :: Array Int [Int]\n\nmain :: IO ()\nmain = do dat <- C.getContents\n let ans = solve $ f2buildTree $ map f2read $ C.words $ last $ f2lines dat\n C.putStrLn $ C.pack $ (if isJust ans then \"YES\" else \"NO\")\n when (isJust ans) $ C.putStrLn $ C.concat $ map f2show $ fromJust ans", "positive_code": [{"source_code": "import Data.Int\nimport Data.Tree\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Foldable (toList)\nimport Control.Monad (when)\nimport Data.Array.IArray\nimport qualified Data.Sequence as S\nimport qualified Data.ByteString.Char8 as C\nf2read' :: Int -> Char -> Int\nf2read' x y = 10 * x + ord y - ord '0'\n\nf2read :: C.ByteString -> Int\nf2read x = C.foldl' f2read' 0 x\n\nf2show :: Int -> C.ByteString\nf2show x = C.reverse $ C.cons ' ' $ fst $ C.unfoldrN 8 (\\x -> if x /= 0 then Just (chr $ rem x 10 + ord '0', div x 10) else Nothing) x\n\nf2lines :: C.ByteString -> [C.ByteString]\nf2lines x = map (\\x -> if (C.last x == '\\r') then (C.init x) else x) (C.lines x)\n\nindexed :: Int -> [a] -> [(Int, a)]\nindexed _ [] = []\nindexed i (x:xs) = (i, x) : (indexed (i+1) xs)\n\nfoldTree :: (a -> [b] -> b) -> Tree a -> b\nfoldTree f = go where\n go (Node x ts) = f x (map go ts)\n\nf2folder :: Int -> [(Int, (S.Seq Int, S.Seq Int))] -> (Int, (S.Seq Int, S.Seq Int))\nf2folder v ls = (s, (bef, aft))\n where s = rem ((+1) $ sum $ map fst ls) 2\n bef' = foldl (S.><) S.empty $ map (fst . snd) ls\n aft' = foldl (S.><) S.empty $ map (snd . snd) ls\n bef = if s == 0 then (v S.<| bef') else bef'\n aft = if s == 1 then (v S.<| aft') else aft'\n\nsolve :: Tree Int -> Maybe [Int]\nsolve t = if s == 1 then Just $ toList ((S.reverse bef) S.>< aft) else Nothing\n where ans = foldTree f2folder t\n s = fst ans\n bef = fst (snd ans)\n aft = snd (snd ans)\n\nf2buildTree :: [Int] -> Tree Int\nf2buildTree xs = unfoldTree (\\x -> (x, a!x)) (head $ a!0)\n where n = length xs\n a = accumArray (\\x y -> y : x) [] (0, n) (map swap (indexed 1 xs)) :: Array Int [Int]\n\nmain :: IO ()\nmain = do dat <- C.getContents\n let ans = solve $ f2buildTree $ map f2read $ C.words $ last $ f2lines dat\n C.putStrLn $ C.pack $ (if isJust ans then \"YES\" else \"NO\")\n when (isJust ans) $ C.putStrLn $ C.concat $ map f2show $ fromJust ans"}], "negative_code": [], "src_uid": "1385c9a70da884bc11befbc2a506ab49"} {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [n, k, _, _, sall, sk] = f sk k ++ f (sall - sk) (n - k)\n where f _ 0 = []; f s m = replicate (s `mod` m) ((s + m - 1) `div` m) ++ replicate (m - s `mod` m) (s `div` m)\nsolve _ = undefined\n", "positive_code": [{"source_code": "main=getContents>>=putStrLn.unwords.map show.solve.map read.words\nsolve[n,k,_,_,sall,sk]=f sk k++f(sall-sk)(n-k)\n where f _ 0=[];f s m=replicate(s`mod`m)((s+m-1)`div`m)++replicate(m-s`mod`m)(s`div`m)\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve [n, k, _, _, sall, sk] = replicate (sk `mod` k) ((sk + k - 1) `div` k)\n ++ replicate (k - sk `mod` k) (sk `div` k)\n ++ if n == k then [] else replicate ((sall - sk) `mod` (n - k)) (((sall - sk) + (n - k) - 1) `div` (n - k))\n ++ replicate ((n - k) - (sall - sk) `mod` (n - k)) ((sall - sk) `div` (n - k))\nsolve _ = undefined\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = getContents >>= putStrLn. intercalate \" \". map show. (\\[n, k, l, r, sall, sk] -> (getArr k sk) ++ (getArr (n-k) (sall - sk))). map read. words\n where\n getArr n s\n | n == 0 = []\n | otherwise = \n let\n mre = s`rem`n\n lss = n - mre\n in\n (replicate mre (s`div`n + 1)) ++ (replicate lss (s`div`n))\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,k,l,r,sa,sk] <- readInts\n let v = div sk k\n w = mod sk k\n ans1 = take k $ f w\n f w = let x = min r (v+w) in x:f (w-(x-v))\n s = div (sa-sk) (n-k)\n t = mod (sa-sk) (n-k)\n ans2 = take (n-k) $ g t\n g w = let x = min v (s+w) in x:g (w-(x-s))\n putStrLn $ unwords $ map show $ ans1 ++ ans2\n"}, {"source_code": "getlist :: Int -> Int -> [Int]\ngetlist 0 _ = []\ngetlist n s = (map (+1) (take (s `mod` n) rep)) ++ (drop (s `mod` n) rep)\n where \n rep = replicate n (s `div` n)\n\nmain :: IO ()\nmain = do\n line <- getLine\n let [n,k,l,r,sall,sk] = map (read :: String -> Int) (words line)\n \n let r = (getlist k sk) ++ (getlist (n-k) (sall-sk))\n\n putStrLn $ concatMap (\\x -> show x ++ \" \") r"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n [n,k,l,r,sa,sk] <- readInts\n let v = div sk k\n w = mod sk k\n ans1 = take k $ f w\n f w = let x = min r (v+w) in x:f (w-(x-v))\n s = div (sa-sk) (n-k)\n t = mod (sa-sk) (n-k)\n ans2 = take (n-k) $ g t\n g w = let x = min r (s+w) in x:g (w-(x-s))\n putStrLn $ unwords $ map show $ ans1 ++ ans2\n"}], "src_uid": "59154ca15716f0c1c91a37d34c5bbf1d"} {"source_code": "import Control.Monad (replicateM_)\nimport qualified Data.Map.Strict as M\n\nsolve :: String -> (Int, String)\nsolve xs = (d + r + u + l, ans) where\n counts = M.fromListWith (+) [(x, 1) | x <- xs]\n numDs = M.findWithDefault 0 'D' counts\n numRs = M.findWithDefault 0 'R' counts\n numUs = M.findWithDefault 0 'U' counts\n numLs = M.findWithDefault 0 'L' counts\n d' = min numDs numUs\n r' = min numRs numLs\n d = if d' > 0 && r' == 0 then 1 else d'\n r = if r' > 0 && d' == 0 then 1 else r'\n u = d\n l = r\n ans = replicate d 'D' ++ replicate r 'R' ++ replicate u 'U' ++ replicate l 'L'\n\nmain =\n read <$> getLine >>= \\q ->\n replicateM_ q (\n solve <$> getLine >>= \\(num, ans) -> \n putStrLn $ show num ++ \"\\n\" ++ ans\n )\n", "positive_code": [{"source_code": "import Control.Monad\n\nf1 :: String -> (Int,Int,Int,Int)\nf1 = foldl f (0,0,0,0)\n where\n f (a,b,c,d) v\n |v=='R' = (a+1,b,c,d)\n |v=='U' = (a,b+1,c,d)\n |v=='L' = (a,b,c+1,d)\n |v=='D' = (a,b,c,d+1)\n |otherwise = error \"saas\"\nf2 :: (Int,Int,Int,Int) -> (Int,String)\nf2 (a,b,c,d)\n |e>0 && f>0 =(2*(e+f),replicate e 'R' ++ replicate f 'U' ++ replicate e 'L' ++ replicate f 'D')\n |e==0 && f==0 = (0,\"\")\n |e>0 = (2,\"RL\")\n |otherwise = (2,\"UD\")\n where\n e=min a c\n f=min b d\n\n\nroutine :: IO ()\nroutine = do\n s <- getLine\n let (a,b)=f2 $ f1 s\n print a\n putStrLn b\n\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n"}], "negative_code": [], "src_uid": "1fba9a290d0492a3d658a7a33388db13"} {"source_code": "module Main where\n\nimport Prelude\n\nans :: Int -> Int -> Int -> Int -> [Int] -> IO ()\nans k c last _ [] | last < k\t\t= print last\n\t\t\t\t | otherwise \t\t= putStrLn \"-1\"\nans k c last id (x:xs) | x /= c\t\t= ans k c id (id + 1) xs\n\t\t\t\t\t | otherwise = ans k c last (id + 1) xs\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\nmain = do\n\tt <- getLine\n\tlet [n, k] = map read $ words t\n\tt <- getLine\n\tlet a = map read $ words t\n\tans k (last a) 0 1 a\n\n\t", "positive_code": [{"source_code": "import Data.List\n\nsolve (n:k:xs)\n | t <= k = t - 1\n | otherwise = -1\n where ((t, _):_) = last $ groupBy (\\x y -> snd x == snd y) $ zip [1 .. ] xs\n\nmain = interact $ show . solve . map read . words"}, {"source_code": "main = do\n k <- fmap (read . last . words) getLine\n as <- fmap (map read . words) getLine\n let i = as !! (k-1) :: Int\n ok = all (==i) (drop k as)\n let bs = scanr f True (take k as)\n f a b = b && a == i\n n = length (takeWhile not bs)\n print $ if ok && n < k then n else -1\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n (n:k:xs) <- map readInt.B.words <$> B.getContents\n let (ys,zs) = splitAt (k-1) xs\n f [] = True\n f (x:xs) = all(x==)xs\n if f zs\n then print $ length $ dropWhile (xs!!(k-1)==) $ reverse ys\n else print $ -1\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nimport Data.Array.MArray\nimport Data.Array.IO\n\nsolve :: Int -> Int -> [Int] -> Maybe Int\nsolve n k l =\n let cycle = n-k+1\n (last : rest) = reverse l\n walk [] i = i\n walk (x : r) i = if last /= x then i else walk r (i+1)\n same = walk rest 1\n in if same < cycle then\n Nothing\n else\n Just (k - 1 - same + cycle)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (k, r2) = readInt r1\n let Just (l, _) = readIntList n r2\n case solve n k l of\n Nothing -> print (-1)\n Just v -> print v\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (x, r) <- readInt s\n (l, t) <- readIntList (n-1) r\n return (x : l, t)\n"}, {"source_code": "import Data.List\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k l = \n if same latter then count (head latter) l else -1\n where latter = drop (k-1) l\n same [] = True\n same (x:xs) = xs == [ x | _ <- xs ]\n count x xs = \n case findIndex (/=x) (reverse xs) of\n Just i -> n - i\n Nothing -> 0 \n\n\nmain :: IO ()\nmain = do str <- getLine\n let [n,k] = map read $ words str\n str <- getLine\n putStrLn $ show $ solve n k $ (map read $ words str)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n [n, k] <- map read <$> (words <$> getLine) :: IO [Int]\n a <- map read <$> (words <$> getLine) :: IO [Int]\n let\n b = drop (k - 1) a\n c = take (k - 1) a\n bb = (length . nub $ b) == 1\n cc = length . takeWhile (== (head b)) . reverse $ c\n if bb then print (k - 1 - cc) else print (-1)\n"}, {"source_code": "\non :: (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)\non f g h x = f (g x) (h x)\n\nsolve :: Int -> Int -> [Int] -> Int\nsolve n k xs\n | k + m >= n + 1 = n - m\n | otherwise = -1\n where\n xs' = reverse xs\n m = solve' 1 $ tail xs'\n solve' acc [] = acc\n solve' acc (y:ys)\n | y == head xs' = solve' (acc+1) ys\n | otherwise = acc\n \nmain :: IO ()\nmain = do\n [n, k] <- fmap (map read . words) getLine\n xs <- fmap (map read . words) getLine\n print $ solve n k xs\n"}], "negative_code": [{"source_code": "\n\nsolve (n:k:xs)\n | mn == mx = k - 1\n | otherwise = -1\n where ts = drop (k - 1) xs\n mn = minimum ts\n mx = maximum ts\n\nmain = interact $ show . solve . map read . words"}, {"source_code": "main = do\n k <- fmap (read . last . words) getLine\n as <- fmap (map read . words) getLine\n let i = as !! (k-1) :: Int\n let bs = scanr f True (take k as)\n f a b = b && a == i\n n = length (takeWhile not bs)\n print $ if n < k then n else -1\n\n"}, {"source_code": "module Main where\n\nimport Prelude\n\nans :: Int -> Int -> Int -> Int -> [Int] -> IO ()\nans k c last _ [] | last < k\t\t= print last\n\t\t\t\t | otherwise \t\t= putStrLn \"-1\"\nans k c last id (x:xs) | x /= c\t\t= ans k c id (id + 1) xs\n\t\t\t\t\t | otherwise = ans k c last (id + 1) xs\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\nmain = do\n\tt <- getLine\n\tlet [n, k] = map read $ words t\n\tt <- getLine\n\tlet a = map read $ words t\n\tans k (last a) (0-1) 1 a\n\n\t"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nimport Data.Char (isSpace)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BSC\n\nimport Data.Array.MArray\nimport Data.Array.IO\n\nsolve :: Int -> Int -> [Int] -> Maybe Int\nsolve n k l =\n let cycle = n-k+1\n (last : rest) = reverse l\n walk [] i = i\n walk (x : r) i = if i /= x then i else walk r (i+1)\n same = walk rest 1\n in if same < cycle then\n Nothing\n else\n Just (k - 1 - same + cycle)\n\nmain =\n do all <- BS.getContents\n let Just (n, r1) = readInt all\n let Just (k, r2) = readInt r1\n let Just (l, _) = readIntList n r2\n case solve n k l of\n Nothing -> print (-1)\n Just v -> print v\n where readInt s = BSC.readInt (BSC.dropWhile isSpace s)\n readIntList 0 s = do return ([], s)\n readIntList n s = do (x, r) <- readInt s\n (l, t) <- readIntList (n-1) r\n return (x : l, t)\n"}], "src_uid": "bcee233ddb1509a14f2bd9fd5ec58798"} {"source_code": "{-\ninstructions go here...\n-}\n\n\n\nmodule Main where\nimport Data.Text as T hiding (length)\n\n\nsolve haystack needle = length (T.splitOn needle haystack) - 1\n\nmain :: IO ()\nmain = do\n haystack <- getLine\n needle <- getLine\n putStrLn $ show $ solve (T.pack haystack) (T.pack needle)\n", "positive_code": [{"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n x <- getLine\n y <- getLine\n print $ solve x y\n\n\n\n\n\n\n\n--solve :: String -> String -> Int\nsolve ai inp = ans\n where \n ans = merge intervals\n intervals = map g $ filter f (zip (tails ai) [0..])\n f (x, t) = take len x == inp\n g (x, t) = (t, t+len-1)\n len = length inp\nmerge is = merge' (-1) (sort is) - 1\n where\n merge' p ((s, e):r) | p < s = 1 + merge' e r\n | otherwise = merge' p r\n merge' _ [] = 1\n"}], "negative_code": [{"source_code": "{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification, \n RankNTypes, FlexibleContexts, DeriveFunctor #-}\n\nimport Control.Monad\nimport Control.Applicative \n--import Control.Lens\n--import Control.Zipper\nimport Control.Arrow\nimport qualified Data.Map as M\n--import qualified Data.Vector as V\nimport qualified Data.Set as S\nimport Data.List\n--import Debug.Trace\n--import Control.Comonad\nimport Data.Monoid\n--import Data.Functor.Foldable\n--import Test.QuickCheck\nimport Data.Tree\n--import Data.Machine\n--import Data.Traversable\n--import Data.Distributive\n--import Linear\nimport Control.Monad.Cont\n\n\nmain = do\n x <- getLine\n y <- getLine\n print $ solve x y\n\n\n\n\n\n\n\n--solve :: String -> String -> Int\nsolve ai inp = ans\n where \n\n ans = merge intervals\n intervals = map g $ filter f (zip (tails ai) [0..])\n f (x, t) = take len x == inp\n g (x, t) = (t, t+len-1)\n len = length inp\nmerge is = merge' (-1) (sort is) - 1\n where\n merge' p ((s, e):r) | p < s = 1 + merge' e r\n | otherwise = merge' e r\n merge' _ [] = 1\n"}], "src_uid": "62a672fcaee8be282700176803c623a7"} {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m] <- getInts\n xs <- getInts\n\n let\n (_, cs) = mapAccumR (\\s x -> let s' = Set.insert x s in (s', Set.size s')) Set.empty xs\n\n cs' = listArray (1, n) cs :: UArray Int Int\n\n qs <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getContents\n\n putStr $ unlines $ map show $ map (cs' !) qs\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ unlines.solve.(\\(a1:a2:as)->[map read (words a1), map read (words a2), map read as]).(\\(a:as)-> [a]++take ((+) 1 $ read $ last $ words a) as).lines\nsolve :: [[Int]]-> [String]\nsolve [[x1,x2],ys,zs] = [show $ (ma1!i)|i<-zs]\n where\n ma1::Array Int Int\n ma1 = runST $ do\n am <- newArray (1,100000) False :: ST s (STArray s Int Bool)\n am2 <- newArray (1,x1) 0 :: ST s (STArray s Int Int)\n ref <- newSTRef 0\n forM_ (reverse $ zip [1..] ys) $ \\ (i,n) -> do \n e <- readArray am n\n ref1<-readSTRef ref\n if e==False then do { modifySTRef ref (+1); ref1<-readSTRef ref; writeArray am2 i ref1; writeArray am n True} else writeArray am2 i ref1\n freeze am2"}, {"source_code": "import qualified Data.Set as S\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Data.List\nimport Numeric\n\nmain = interact solve\n\nfastRead :: String -> Int\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nsolve input = intercalate \"\\n\" answer_as_strings\n-- solve input = show (sum answers)\n-- solve input = seq asnumbers \" \"\n-- solve input = show (length dp)\n where\n answer_as_strings = map show answers\n\n asnumbers::[Int]\n asnumbers = (map fastRead . words) input\n n:m:afterfirst = asnumbers\n (as,ls) = splitAt n afterfirst\n\n (fset,dplist) = foldr dp_folder (S.empty,[]) as\n where\n dp_folder curn (cset,xs) = seq nset (nset,(S.size nset):xs)\n where nset = S.insert curn cset\n\n -- dplist = [1..n]\n\n dp = A.listArray (1,n) dplist\n\n answers = map (\\idx -> dp!idx) ls\n"}, {"source_code": "import qualified Data.Array as A\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getContents >>= mapM_ print . solve . map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [Int] -> [Int]\nsolve (n:_:asls) = map (S.size . (aset A.!)) ls\n where (as, ls) = splitAt n asls\n aset = A.listArray (1, n) $ scanr S.insert S.empty as\nsolve _ = undefined\n"}, {"source_code": "import qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Set as S\nimport Data.Maybe (fromJust)\n\nmain :: IO ()\nmain = B.getContents >>= mapM_ print . solve . map (fst . fromJust . B.readInt) . B.words\n\nsolve :: [Int] -> [Int]\nsolve (n:_:asls) = [ S.size $ aset A.! l | l <- ls ]\n where (as, ls) = splitAt n asls\n aset = A.listArray (1, n) $ scanr S.insert S.empty as\nsolve _ = undefined\n"}, {"source_code": "import Data.Bits\nimport Data.Array.Unboxed\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nimport Data.Array.ST.Safe\nimport Control.Monad\nreadI b = i where Just (i,_) = B.readInt b\nmain = do\n [n,m] <- map readI . B.words <$> B.getLine\n ss <- acc n . map readI . B.words <$> B.getLine\n mapM_ (print . (ss!) . readI) . B.words =<< B.getContents\nacc n as = runSTUArray $ do\n acc <- newListArray (1,n) as\n let go i s = when (i > 0) $ do\n a <- readArray acc i\n let s' = setBit s a :: Integer\n writeArray acc i (popCount s')\n go (i-1) s'\n go n 0\n return acc\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport qualified Data.IntSet as A\nimport Data.Maybe\nimport Data.Array\n\nprocess [] _ ns = reverse $ scanl1 (+) $ reverse ns\nprocess (y:ys) s ns | A.member y s = process ys s (0:ns)\n | otherwise = process ys (A.insert y s) (1:ns)\n\n\nmain= do\n\t\tgetLine\n \t\ta<- reverse.map read. words <$> getLine::IO [Int]\n\t let la = length a\n\t\tlet z=listArray (1,la) $ process a A.empty []\n\t\tb<- map read. words <$> getContents::IO [Int]\t\n\t putStrLn $ intercalate \"\\n\" $ map show $ map (z!) b\n\t \n\t\t\n\t \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport qualified Data.IntSet as A\nimport Data.Maybe\nimport Data.Array\nimport qualified Data.ByteString.Char8 as C\n\nprocess [] _ ns = reverse $ scanl1 (+) $ reverse ns\nprocess (y:ys) s ns | A.member y s = process ys s (0:ns)\n | otherwise = process ys (A.insert y s) (1:ns)\n\n\nmain= do\n\t\tgetLine\n \t\ta<- reverse.map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]\n\t let la = length a\n\t\tlet z=listArray (1,la) $ process a A.empty []\n\t\tb<- map (fst.fromJust.C.readInt). C.words <$> C.getContents::IO [Int]\t\n\t putStrLn $ intercalate \"\\n\" $ map show $ map (z!) b\n\t \n\t\t\n\t \n"}, {"source_code": "import Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport qualified Data.ByteString.Builder as BUI\nimport Data.Maybe (fromJust)\nimport qualified Data.Set as Set\n\nreadInt :: BS.ByteString -> Int\nreadInt = fst . fromJust . BS.readInt\nintToByteString = BUI.toLazyByteString . BUI.intDec\n\nmain = BS.interact $ BS.unlines . map intToByteString . f . parse . tail . BS.lines\n\nparse (x:xs) = ((map readInt (BS.words x)):(map readInt xs):[])\n\nf (x:y:xs) = map (ans ! ) y\n where i = solve Set.empty (reverse x) []\n ans = listArray (1, (length i)) i\n \n\nsolve st [] ans = ans\nsolve st (x:xs) ans = solve newst xs ((Set.size newst):ans)\n where newst = Set.insert x st\n"}, {"source_code": "import Data.Array\nimport qualified Data.Set as Set\nimport Numeric\n\nfastRead :: String -> Int\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> (-n)\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact $ unlines.map show.f.parse.tail.lines\n\nparse (x:xs) = ((map fastRead (words x)):(map fastRead xs):[])\n\nf (x:y:xs) = map (ans ! ) y\n where i = solve Set.empty (reverse x) []\n ans = listArray (1, (length i)) i\n \n\nsolve st [] ans = ans\nsolve st (x:xs) ans = solve newst xs ((Set.size newst):ans)\n where newst = Set.insert x st\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Data.Array\nmain= readsolveprint \nreadsolveprint::IO()\nreadsolveprint = interact $ unlines.solve.(\\(a1:a2:as)->[map read (words a1), map read (words a2), map read as]).(\\(a:as)-> [a]++take ((+) 1 $ read $ last $ words a) as).lines\nsolve :: [[Integer]]-> [String]\nsolve [[x1,x2],ys,zs] = [show $ fst $ (ar!i)|i<-zs]\n where\n ar= listArray (1, x1) slv2\n ls1= group $ concat $ map tail $ group $ sort ys\n slv1 (a2,as) a1 | snd tup ==[] = (maximum [0, a2-1],as) \n | otherwise = (a2, fst tup ++ ([tail $ head $ snd tup ]++tail (snd tup)))\n where tup = break (\\a-> if a== [] then False else head a ==a1 ) as\n slv2 = scanl slv1 (x1- fromIntegral (length ls1), ls1) ys"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport qualified Data.IntSet as A\nimport Data.Maybe\nimport Data.Array\n\nprocess [] _ ns = reverse $ scanl1 (+) $ reverse ns\nprocess (y:ys) s ns | A.member y s = process ys s (0:ns)\n | otherwise = process ys (A.insert y s) (1:ns)\n\n\nmain= do\n\t\tgetLine\n \t\ta<- reverse.map read. words <$> getLine::IO [Int]\n\t let la = length a\n\t\tlet z=listArray (1,la) $ process a A.empty []\n\t\tb<- sort.map read. words <$> getContents::IO [Int]\t\n\t putStrLn $ intercalate \"\\n\" $ map show $ map (z!) b\n\t \n\t\t\n\t \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport qualified Data.IntSet as A\nimport Data.Maybe\nimport Data.Array\n\nprocess [] _ ns = reverse $ scanl1 (+) $ reverse ns\nprocess (y:ys) s ns | A.member y s = process ys s (0:ns)\n | otherwise = process ys (A.insert y s) (1:ns)\n\n\nmain= do\n\t\tgetLine\n \t\ta<- reverse.map read. words <$> getLine::IO [Int]\n\t let la = length a\n\t\tlet z=listArray (1,la) $ process a A.empty []\n\t\tb<- sort.map read. words <$> getContents::IO [Int]\t\n\t putStrLn $ intercalate \"\\n\" $ map show $ map (z!) b\n\t \n\t\t\n\t \n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Char\nimport qualified Data.IntSet as A\nimport Data.Maybe\nimport Data.Array\n\nprocess [] _ ns = reverse $ scanl1 (+) $ reverse ns\nprocess (y:ys) s ns | A.member y s = process ys s (0:ns)\n | otherwise = process ys (A.insert y s) (1:ns)\n\n\nmain= do\n\t\tgetLine\n \t\ta<- reverse.map read. words <$> getLine::IO [Int]\n\t let la = length a\n\t\tlet z=listArray (1,la) $ process a A.empty []\n\t\tprint z\n\t\tb<- sort.map read. words <$> getContents::IO [Int]\t\n\t putStrLn $ intercalate \"\\n\" $ map show $ map (z!) b\n\t \n\t\t\n\t \n"}], "src_uid": "1e156dfc65ef88f19ca1833f75192259"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE Safe #-}\n\nimport qualified Data.Array.ST.Safe as V\n\nmain = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:y:xs) = ((n,m,as), xs)\n where [n,m] = map readInt $ take 2 $ words x\n as = map readInt $ words y\n\nsolve (n,m,as) = solve' n m as || solve' m n as\n\nsolve' n m as = check $ foldl f (0,0,0) $ map maxCols as\n where maxCols a\n | a < 2*n = 0\n | otherwise = a `div` n\n f (s,t,u) x = (s+x, t + max 0 (x-2), u + min 2 x)\n check (s,t,u) = s >= m && (d <= 0 ||\n d <= u && even d ||\n d+1 <= u && odd d && t >= 1)\n where d = (s-m)-t\n\nformat x\n | x = \"Yes\"\n | otherwise = \"No\"\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:y:xs) = ((n,m,as), xs)\n where [n,m] = map readInt $ take 2 $ words x\n as = map readInt $ words y\n\nsolve (n,m,as) = solve' n m as || solve' m n as\n\nsolve' n m as = check $ foldl f (0,0,0) $ map maxCols as\n where maxCols a\n | a < 2*n = 0\n | otherwise = a `div` n\n f (s,t,u) x = (s+x, t + max 0 (x-2), u + min 2 x)\n check (s,t,u) = s >= m && (d <= 0 ||\n d <= u && even d ||\n d+1 <= u && odd d && t >= 1)\n where d = (s-m)-t\n\nformat x\n | x = \"Yes\"\n | otherwise = \"No\"\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM)\nimport Control.Arrow ((&&&))\n\n-- road map in reverse, and the number of cities, init pen state\ntype Domain = (Int, Int, [Int])\ntype CoDomain = String\ntype Solver = Domain -> CoDomain\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap read . words <$> getLine\n\nprintAns :: CoDomain -> IO ()\nprintAns = putStrLn \n\nparse :: IO Domain\nparse = do\n (ys) <- readChar8\n if length ys /= 3 \n then error \"error input\"\n else (do\n xs <- readChar8\n return (ys!!0, ys!!1, xs))\n\nsolveOne :: Int -> Int -> Int -> [Int] -> Bool\nsolveOne total n m xs = (not (null ks) && (maximum ks) > 2 || even m) && sum ks >= m \n where ks = filter (>1) $ map (`div` n) xs\n\nsolve :: Solver\nsolve (n, m, xs) = if solveOne (n * m) n m xs || solveOne (n * m) m n xs then \"YES\" else \"NO\"\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n replicateM n $ printAns =<< solve <$> parse\n return ()\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:y:xs) = ((n,m,as), xs)\n where [n,m] = map readInt $ take 2 $ words x\n as = map readInt $ words y\n\nsolve (n,m,as) = solve' n m as || solve' m n as\n\nsolve' n m as = check $ foldl f (0,0,0) $ map maxCols as\n where maxCols a\n | a < 2*n = 0\n | otherwise = a `div` n\n f (s,t,u) x = (s+x, t + max 0 (x-2), u + min 2 x)\n check (s,t,u) = s >= m && (d <= 0 || even d && d <= u)\n where d = (s-m)-t\n\nformat x\n | x = \"Yes\"\n | otherwise = \"No\"\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:y:xs) = ((n,m,as), xs)\n where [n,m] = map readInt $ take 2 $ words x\n as = map readInt $ words y\n\nsolve (n,m,as) = solve' n m as || solve' m n as\n\nsolve' n m as = check $ foldl f (0,0,0) $ map maxCols as\n where maxCols a\n | a < 2*n = 0\n | otherwise = a `div` n\n f (s,t,u) x = (s+x, t + max 0 (x-2), u + min 2 x)\n check (s,t,u) = s >= m && (d >= 0 || even d && d <= u)\n where d = t-(s-m)\n\nformat x\n | x = \"Yes\"\n | otherwise = \"No\"\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:y:xs) = ((n,m,as), xs)\n where [n,m] = map readInt $ take 2 $ words x\n as = map readInt $ words y\n\nsolve (n,m,as) = solve' n m as || solve' m n as\n\nsolve' n m as = check $ foldl f (0,0) $ map maxCols as\n where maxCols a\n | a < 2*n = 0\n | otherwise = a `div` n\n f (s,t) x = (s+x, t + max 0 (x-2))\n check (s,t) = s >= m && s-m <= t\n\nformat x\n | x = \"Yes\"\n | otherwise = \"No\"\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n"}], "src_uid": "002129eec704af8976a2bf02cc532d59"} {"source_code": "-- http://codeforces.com/contest/818/problem/C\n\n{-# LANGUAGE CPP #-}\n\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.ByteString as BS\nimport Data.Maybe\nimport Data.Array\nimport Control.Monad\n\n#ifdef DEBUG\nimport Debug.Trace\n#endif\n\ngetInt = read `fmap` getLine :: IO Int\n\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine\nparseInt = fst . fromJust . BS8.readInt\n\n-- returns [l,r,t,b]\ngetSofa :: IO [Int]\ngetSofa = do\n\t[x1,y1,x2,y2] <- getInts\n\treturn [min x1 x2, max x1 x2, min y1 y2, max y1 y2]\n\nmain = do\n\td <- getInt\n\t[n,m] <- getInts\n\tsofas <- replicateM d getSofa\n\t[cntL,cntR,cntT,cntB] <- getInts\n\tlet sumL = subsumL sofas n\n\tlet sumR = subsumR sofas n\n\tlet sumT = subsumT sofas m\n\tlet sumB = subsumB sofas m\n\tlet feasible [l,r,t,b] =\n#ifdef DEBUG\n\t\ttrace (show (sumL ! (r-1) - (if l == r then 0 else 1),\n\t\t\t\t\t\tsumR ! (l+1) - (if l == r then 0 else 1),\n\t\t\t\t\t\tsumT ! (b-1) - (if t == b then 0 else 1),\n\t\t\t\t\t\tsumB ! (t+1) - (if t == b then 0 else 1))) $\n#endif\n\t\t(sumL ! (r-1) - (if l == r then 0 else 1)) == cntL &&\n\t\t(sumR ! (l+1) - (if l == r then 0 else 1)) == cntR &&\n\t\t(sumT ! (b-1) - (if t == b then 0 else 1)) == cntT &&\n\t\t(sumB ! (t+1) - (if t == b then 0 else 1)) == cntB\n\tlet answers = [i | (i, sofa) <- zip [1..d] sofas, feasible sofa] :: [Int]\n\tif length answers == 1\n\tthen print (head answers)\n\telse print (-1)\n\nsubsumL :: [[Int]] -> Int -> Array Int Int\nsubsumL sofas n = listArray (0,n+1) xs where\n\tsrc = [(0,0),(n+1,0)] ++ [(l,1) | [l,_,_,_] <- sofas]\n\tes = elems $ accumArray (+) 0 (0,n+1) src\n\txs = scanl1 (+) es\n\nsubsumR :: [[Int]] -> Int -> Array Int Int\nsubsumR sofas n = listArray (0,n+1) xs where\n\tsrc = [(0,0),(n+1,0)] ++ [(r,1) | [_,r,_,_] <- sofas]\n\tes = elems $ accumArray (+) 0 (0,n+1) src\n\txs = (reverse . scanl1 (+) . reverse) es\n\nsubsumT :: [[Int]] -> Int -> Array Int Int\nsubsumT sofas m = listArray (0,m+1) ys where\n\tsrc = [(0,0),(m+1,0)] ++ [(t,1) | [_,_,t,_] <- sofas]\n\tes = elems $ accumArray (+) 0 (0,m+1) src\n\tys = scanl1 (+) es\n\nsubsumB :: [[Int]] -> Int -> Array Int Int\nsubsumB sofas m = listArray (0,m+1) ys where\n\tsrc = [(0,0),(m+1,0)] ++ [(b,1) | [_,_,_,b] <- sofas]\n\tes = elems $ accumArray (+) 0 (0,m+1) src\n\tys = (reverse . scanl1 (+) . reverse) es\n\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-} \nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Array.Unboxed\nimport Control.Monad\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nsolve n m rs tc = maybe (-1) fst $ find (\\(_, (x1, y1, x2, y2)) -> (i2cl!(x2 - 1) - fromEnum (x1 /= x2), i2cr!(x1 + 1) - fromEnum (x1 /= x2), i2ct!(y2 - 1) - fromEnum (y1 /= y2), i2cb!(y1 + 1) - fromEnum (y1 /= y2)) == tc') $ zip [(1 :: Int)..] rs'\n where\n tc' = case tc of\n [_1, _2, _3, _4] -> (_1, _2, _3, _4)\n rs' = map (\\[x1, y1, x2, y2] -> (min x1 x2, min y1 y2, max x1 x2, max y1 y2)) rs\n els = elems :: UArray Int Int -> [Int]\n bx = (0, n + 1)\n by = (0, m + 1)\n i2cl = listArray bx $ scanl1 (+) $ els $ accumArray (+) 0 bx $ map (\\(x1, _, _, _) -> (x1, 1)) rs' :: UArray Int Int\n i2ct = listArray by $ scanl1 (+) $ els $ accumArray (+) 0 by $ map (\\(_, y1, _, _) -> (y1, 1)) rs' :: UArray Int Int\n i2cr = listArray bx $ scanr1 (+) $ els $ accumArray (+) 0 bx $ map (\\(_, _, x2, _) -> (x2, 1)) rs' :: UArray Int Int\n i2cb = listArray by $ scanr1 (+) $ els $ accumArray (+) 0 by $ map (\\(_, _, _, y2) -> (y2, 1)) rs' :: UArray Int Int\n\nmain = do\n d <- fmap readInt B.getLine\n [n, m] <- fmap readInts B.getLine\n rs <- replicateM d (fmap readInts B.getLine)\n cs <- fmap readInts B.getLine\n print $ solve n m rs cs"}], "negative_code": [], "src_uid": "9b2c0c066f5c88a3b724d34788f97797"} {"source_code": "import qualified Data.ByteString.Char8 as BS\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nimport Data.Function\nimport Data.Maybe\n\nscore = BS.count '1'\n\nmain = do\n n <- fst . fromJust . BS.readInt <$> BS.getLine\n inp <- replicateM n BS.getLine\n case filter ((>1) . length) . groupBy ((==) `on` (score . snd)) . sortBy (comparing (score . snd)) $ zip [0..] inp of\n [] -> print (-1)\n (((i,a):(j,b):_):_) -> \n let reorderIfBad [i,j,k] | BS.index (inp !! i) j == '1' = [i,j,k]\n | otherwise = [k,j,i]\n in putStrLn $ unwords $ map (show . succ) $ reorderIfBad [i, j, head $ filter \n (\\k -> k /= i && k /= j && BS.index a k /= BS.index a j && BS.index b k /= BS.index b i) [0..length inp - 1]]", "positive_code": [{"source_code": "import qualified Data.ByteString.Char8 as BS\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Ord\n\nimport Data.Function\nimport Data.Maybe\nimport Control.Arrow\n\nscore = BS.count '1'\n\nmain = do\n n <- fst . fromJust . BS.readInt <$> BS.getLine\n inp <- replicateM n BS.getLine\n case filter ((>1) . length) . groupBy ((==) `on` (snd . snd)) . sortBy (comparing (snd . snd)) $ zip [0..] $ map (id &&& score) inp of\n [] -> print (-1)\n (((i,(a,_)):(j,(b,_)):_):_) -> \n let reorderIfBad [i,j,k] | BS.index (inp !! i) j == '1' = [i,j,k]\n | otherwise = [k,j,i]\n in putStrLn $ unwords $ map (show . succ) $ reorderIfBad [i, j, head $ filter \n (\\k -> k /= i && k /= j && BS.index a k /= BS.index a j && BS.index b k /= BS.index b i) [0..length inp - 1]]"}], "negative_code": [], "src_uid": "725a65c7eb72ad54af224895b20a163d"} {"source_code": "import Data.Set as S\nimport Data.List as L\n\nsolve :: [Int] -> Int\nsolve arr = length $ S.fromList arr\n\ngroupByNLines :: Int -> [String] -> [[String]]\ngroupByNLines n [] = []\ngroupByNLines n arr = (L.take n arr):(groupByNLines n (L.drop n arr))\n\nparse :: [String] -> String\nparse [_, input] = show $ solve arr\n where arr = L.map (\\x -> read x :: Int) $ words input\n\nmain :: IO ()\nmain = interact (unlines . L.map parse . groupByNLines 2 . tail . lines)\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- getIntList\n print $ a --> S.fromList --> S.size"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintStrList :: [String] -> IO ()\nprintStrList = putStrLn . intercalate \" \"\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = printStrList . map show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\n(-->) :: a -> (a -> b) -> b\n(-->) = flip ($)\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- getIntList\n print $ a --> sort --> group --> length"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest a = do\n getLine\n as <- map read.words <$> getLine :: IO [Integer]\n print $ length $ group $ sort as\n test (a - 1)\n"}, {"source_code": "import Control.Monad\nimport qualified Data.Set as Set\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n _ <- getLine\n xs <- (map read.words) <$> getLine\n print $ solve xs\n\nsolve :: [Int] -> Int\nsolve xs = length $ Set.toList $ Set.fromList xs\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as IntSet\n\nparseInt :: C.ByteString -> Int\nparseInt = fst . fromJust . C.readInt\n\nwork :: IO ()\nwork = do\n _ <- C.getLine\n as <- fmap (map parseInt . C.words) C.getLine\n putStrLn $ show $ IntSet.size $ IntSet.fromList as\n\nmain :: IO ()\nmain = do\n n <- fmap parseInt C.getLine\n replicateM_ n work\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nonecase = do\n\t\tgetLine\n\t\ta1<- map read <$> words <$> getLine::IO [Int] \n\t\tprint $ length $ group $ sort a1\n\t\t\n\n\nmain::IO ()\nmain=do\n \tt<- read<$> getLine ::IO Int\t\n\treplicateM_ t onecase\n\n\n"}, {"source_code": "import qualified Data.Set as S (fromList, size)\n\nprocess :: [Int] -> Int\nprocess = S.size . S.fromList\n\nreadInt :: String -> Int\nreadInt = read\n\nreadCases :: [String] -> [[Int]]\nreadCases (n:as:xs) = map readInt (words as):readCases xs\nreadCases _ = []\n\nmain = do\n t <- fmap readInt getLine\n xs <- fmap (readCases.lines) getContents\n sequence (map print $ map process xs)"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = do\n getLine\n tc <- (map (map read . words) . filterEvens . lines) <$> getContents :: IO [[Int]]\n let uniqueNums :: [Int]\n uniqueNums = map (S.size . S.fromList) tc\n forM_ uniqueNums print\n\nfilterEvens :: [String] -> [String]\nfilterEvens xs = let ps = zip [1..] xs\n in map snd . filter (even . fst) $ ps\n\n\n \n"}], "negative_code": [], "src_uid": "b978ca6fdef4a02cc027485294caa0f5"} {"source_code": "import Control.Applicative\nmain = do\n n <- read <$> getLine ::IO Int\n cards <- map read <$> words <$> getLine ::IO [Int]\n putStrLn $ answer n cards where\n answer n cards = unwords $ map show $ result n cards\n split acc1 acc2 [] = [acc2,acc1]\n split acc1 acc2 (x:xs) = split acc2 (x:acc1) xs\n result n cards = map sum $ split [] [] $ find n cards (reverse cards) []\n find 0 _ _ acc = acc\n find n (a:as) (b:bs) acc | a > b = find (n-1) as (b:bs) (a:acc)\n | otherwise = find (n-1) (a:as) bs (b:acc) \n", "positive_code": [{"source_code": "module Main\n where\n\nimport Data.List\nimport System.IO\n\nmain = do\n first <- getLine\n second <- getLine\n putStrLn . solve 0 0 True . map read . words $ second\n where\n solve s d _ [] =\n show s ++ \" \" ++ show d\n solve s d st cards =\n case choose cards of\n (card, rest) ->\n if st then\n solve (s + card) d False rest\n else\n solve s (d + card) True rest\n choose cards =\n if h < l then\n (l, take (length cards - 1) cards)\n else\n (h, drop 1 cards)\n where\n h = head cards\n l = last cards\n"}, {"source_code": "main = do\n getLine\n getLine>>=(\\x->putStr (solve 0 (map read (words x)) 0 0))\nsolve n x s1 s2\n |null x = show s1 ++\" \"++show s2\n |n==0&&(last x>head x) = solve 1 (init x) (s1+last x) s2\n |n==0 = solve 1 (tail x) (s1+head x) s2\n |n==1&&(last x>head x) = solve 0 (init x) s1 (s2+last x)\n |n==1 = solve 0 (tail x) s1 (s2+head x)"}, {"source_code": "main = do\n n <- readLn :: IO Int\n temp <- getLine\n let a = map (read :: String -> Int) $ words temp\n let (x, y) = solve a (0, 0)\n putStrLn ((show x) ++ \" \" ++ (show y))\n\nsolve :: [Int] -> (Int, Int) -> (Int, Int)\nsolve [] p = p\nsolve a (x, y) = (j, i)\n where (i, j) = if head a > last a\n then solve (tail a) (y, x + (head a))\n else solve (init a) (y, x + (last a))\n"}, {"source_code": "import Control.Applicative\n\nsolve1 f s [] = (f, s)\nsolve1 f s lst = if head lst > last lst\n then solve2 (f + head lst) s (tail lst)\n else solve2 (f + last lst) s (tail (reverse lst))\n\nsolve2 f s [] = (f, s)\nsolve2 f s lst = if head lst > last lst\n then solve1 f (s + head lst) (tail lst)\n else solve1 f (s + last lst) (tail (reverse lst))\n\n\nsolve a = solve1 0 0 a\n\nmain = do\n n <- read <$> getLine :: IO Int\n a <- map read <$> (words <$> getLine)\n let (f, s) = solve a\n putStrLn $ (show f) ++ \" \" ++ (show s)\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n getLine\n xs <- getInts\n\n let\n step1 (l:ls) (r:rs) (a, b)\n | l == r = (a+l, b)\n | l < r = step2 (l:ls) rs (a+r, b)\n | l > r = step2 ls (r:rs) (a+l, b)\n step2 (l:ls) (r:rs) (a, b)\n | l == r = (a, b+l)\n | l < r = step1 (l:ls) rs (a, b+r)\n | l > r = step1 ls (r:rs) (a, b+l)\n\n (a, b) = step1 xs (reverse xs) (0, 0)\n\n putStrLn $ show a ++ \" \" ++ show b\n"}, {"source_code": "main = do\n getLine\n getLine >>= (\\x -> let (c, d) = f False (map read (words x)) in putStrLn $ show c ++ \" \" ++ show d)\nf _ [] = (0, 0)\nf n x = let (a, b) = if head x < last x then (init x, last x) else (tail x, head x); (c, d) = f (not n) a in if n then (c, d + b) else (c + b, d)"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ndata Turn = Sereja | Dima deriving(Eq)\nmain = do\n getLine\n as <- readInts\n let (a,b) = game as\n printf \"%d %d\\n\" a b\n\ngame :: [Int] -> (Int,Int)\ngame l = go Sereja 0 0 l\n where\n go _ a b [] = (a,b)\n go t a b l | t == Sereja = go Dima (a+c) b l'\n | otherwise = go Sereja a (b+c) l'\n where\n c = max (head l) (last l)\n l' = delete c l\n"}, {"source_code": "import Data.Array\n\ngameOver :: (Int, Int) -> Bool\ngameOver (p1, p2) = p1 > p2\n\nmakeTurn :: Array Int Int -> (Int, Int) -> ((Int, Int), Int)\nmakeTurn arr (p1, p2)\n | (arr ! p1) > (arr ! p2) = ((p1 + 1, p2), arr ! p1)\n | otherwise = ((p1, p2 - 1), arr ! p2)\n\ndata GameState = GameState { leftPtr :: Int, rightPtr :: Int, score1 :: Int, score2 :: Int } deriving (Show)\n\nplay :: Array Int Int -> GameState -> GameState\nplay arr state = if gameOver (leftPtr state, rightPtr state) then state else\n let ((leftPtr', rightPtr'), deltaScore1) = makeTurn arr (leftPtr state, rightPtr state) in\n let state' = GameState leftPtr' rightPtr' (score1 state + deltaScore1) (score2 state) in\n if gameOver (leftPtr state', rightPtr state') then state' else\n let ((leftPtr'', rightPtr''), deltaScore2) = makeTurn arr (leftPtr state', rightPtr state') in\n let state'' = GameState leftPtr'' rightPtr'' (score1 state + deltaScore1) (score2 state + deltaScore2) in \n state''\n\nmain = do\n n <- fmap read getLine :: IO Int\n li <- fmap (fmap read) (fmap words getLine) :: IO [Int]\n let arr = listArray (1, n) li\n let res = iterate (play arr) (GameState 1 n 0 0) !! 1001\n putStrLn $ (show $ score1 res) ++ \" \" ++ (show $ score2 res)\n\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (_:xs) = go (0, 0, True) xs\n where go (a, b, _) [] = [a, b]\n go (a, b, c) as | c && head as > last as = go (a + head as, b, not c) (tail as)\n | head as > last as = go (a, b + head as, not c) (tail as)\n | c = go (a + last as, b, not c) (init as)\n | otherwise = go (a, b + last as, not c) (init as)\nsolve _ = undefined\n"}, {"source_code": "main :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . tail . words\n\nsolve :: [Int] -> [Int]\nsolve = go (0, 0, True)\n where go (a, b, _) [] = [a, b]\n go (a, b, c) as | c && head as > last as = go (a + head as, b, not c) (tail as)\n | head as > last as = go (a, b + head as, not c) (tail as)\n | c = go (a + last as, b, not c) (init as)\n | otherwise = go (a, b + last as, not c) (init as)\n"}, {"source_code": "import qualified Data.Sequence as S\nmain = interact $ unwords . map show . solve . map read . tail . words\nsolve = go . S.fromList where\n go s | S.null s = [0 , 0]\n | l > r = let [a,b] = go l' in [l+b,a]\n | otherwise = let [a,b] = go r' in [r+b,a]\n where (l S.:< l') = S.viewl s\n (r' S.:> r) = S.viewr s\n"}, {"source_code": "#!/usr/bin/env runghc\nmain = getContents >>= mapM_ putStrLn . solve . lines\nsolve [] = [] ::[String]\nsolve (c1:c2:cs) = (:solve cs)$ unwords . map show $ s (read c1) True n (reverse n) (0,0)\n where n = map read . words $ c2\ns c t n1s n2s (s1,s2)\n | c==0 = [s1,s2]\n | t = s (c-1) (not t) nn1 nn2 (s1+n,s2)\n | otherwise = s (c-1) (not t) nn1 nn2 (s1,s2+n)\n where\n n1 = head n1s\n n2 = head n2s\n (n,nn1,nn2) = if n1>n2 then (n1,tail n1s,n2s) else (n2,n1s,tail n2s)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n \n\nprocess [] x y _ = show x ++ \" \" ++ show y\nprocess s x y 1 | last s >head s = process (init s) (x+last s) y 2\n\t\t| otherwise = process (tail s) (x+head s) y 2\nprocess s x y 2 | last s >head s = process (init s) x (y+last s) 1\n\t\t| otherwise = process (tail s) x (y+head s) 1\n\n\nmain= do\n\ts<- getLine \n\tn<- map read. words <$> getLine::IO [Int]\n\tputStrLn $ process n 0 0 1\n\t"}, {"source_code": "process :: [Int] -> (Int,Int)\nprocess xs = f xs (reverse xs) (length xs)\n where\n f _ _ 0 = (0,0)\n f (l:ls) (r:rs) n\n | l > r =\n let (s2,s1) = f ls (r:rs) (n-1)\n in (l+s1,s2)\n | otherwise =\n let (s2,s1) = f (l:ls) rs (n-1)\n in (r+s1,s2)\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- fmap readInt getLine\n xs <- fmap (map readInt.words) getLine\n let (s1,s2) = process xs\n putStrLn $ show s1 ++ \" \" ++ show s2"}, {"source_code": "main = do\n (_:a) <- fmap (map read . words) getContents :: IO [Int]\n putStrLn $ unwords $ map show (f a 0)\nf [] _ = [0, 0]\nf xs t = if t == 0 then [a+mx, b] else [a, b+mx] where\n front = head xs\n back = last xs\n mx = max front back\n [a, b] = f (if front > back then (tail xs) else (init xs)) (1 - t)"}], "negative_code": [{"source_code": "import Data.List (sort)\n\nmain = do\n n <- readLn :: IO Int\n temp <- getLine\n let a = reverse . sort $ map (read :: String -> Int) $ words temp\n let (x, y) = solve a (0, 0)\n putStrLn ((show x) ++ \" \" ++ (show y))\n\nsolve :: [Int] -> (Int, Int) -> (Int, Int)\nsolve [] p = p\nsolve a (x, y) = (j, i)\n where (i, j) = solve (tail a) (y, x + (head a))\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\n \n \n\n\nmain= do\n\ts<- C.tail. C.take 3 . C.reverse .C.filter (/=' ') <$> C.getLine \n\tlet s1 = read (reverse (C.unpack s)) ::Int\n\tprint $ if mod s1 4 ==0 then 4 else 0\n\t"}], "src_uid": "a7e98ed8ee1b0a4fd03dfcd222b68c6f"} {"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Array ((!), listArray)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntype Point = [Integer]\n\nsymmetric :: Point -> Point -> Point\nsymmetric [x0, y0] [x, y] = [2*x0 - x, 2*y0 - y]\n\ngenPoints :: Integer -> Integer -> Point -> [Point] -> [Point]\ngenPoints n start m0 as = map fst $ iterate next (m0, start)\n where\n array = listArray (0, n-1) as\n next (a, i) = (symmetric (array ! i) a, if i+1 == n then 0 else i+1)\n\nsolve :: Integer -> Integer -> Point -> [Point] -> Bool -> Point\nsolve 1 j m0 ps p\n | odd j = symmetric (head ps) m0\n | otherwise = m0\nsolve n j m0 ps p\n | j < 2*n || p = head $ drop (fromIntegral j) $ genPoints n 0 m0 ps\n | odd n = head $ drop (fromIntegral (mod j (2*n))) $ genPoints n 0 m0 ps\n | otherwise = head $ drop (fromIntegral (mod j n)) $ genPoints n 0 [mjx, mjy] ps\n where\n mn = head $ drop (fromIntegral n) $ genPoints n 0 m0 ps\n [m0x, m0y] = m0\n [mnx, mny] = mn\n mjx = m0x + (mnx - m0x) * (div j n)\n mjy = m0y + (mny - m0y) * (div j n)\n \n\nmain :: IO ()\nmain = do\n [n, j] <- reads\n m0 <- reads\n ps <- replicateM (fromIntegral n) reads\n --prints $ solve n j m0 ps True\n prints $ solve n j m0 ps False", "positive_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\ngetNums = do\n [a, b] <- map (fst . fromJust . B.readInteger) . B.words <$> B.getLine\n return (a :: Integer, b :: Integer)\n\nmove (mx, my) (ax, ay)= (ax*2-mx, ay*2-my)\n\nmain = do\n (n, j) <- getNums\n (m0 : as) <- replicateM (fromIntegral n+1) getNums\n j <- return $ j `mod` (2*n)\n let (rx, ry) = foldl move m0 $ take (fromIntegral j) $ cycle as\n putStrLn $ show rx ++ \" \" ++ show ry"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\n\ngetNums = do\n [a, b] <- map read . words <$> getLine\n return (a, b)\n\nmove (mx, my) (ax, ay)= (ax*2-mx, ay*2-my)\n\nmain = do\n (n, j) <- getNums\n (m0 : as) <- replicateM (n+1) getNums\n j <- return $ j `mod` (2*n)\n -- print $ scanl move m0 $ take (j+1) $ cycle as\n let (rx, ry) = foldl move m0 $ take j $ cycle as\n putStrLn $ show rx ++ \" \" ++ show ry"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array ((!), listArray)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntype Point = [Integer]\n\nsymmetric :: Point -> Point -> Point\nsymmetric [x0, y0] [x, y] = [2*x0 - x, 2*y0 - y]\n\ngenPoints :: Integer -> Integer -> Point -> [Point] -> [Point]\ngenPoints n start m0 as = map fst $ iterate next (m0, start)\n where\n array = listArray (0, n-1) as\n next (a, i) = (symmetric (array ! i) a, if i+1 == n then 0 else i+1)\n\nsolve :: Integer -> Integer -> Point -> [Point] -> Point\nsolve 1 j m0 ps\n | odd j = symmetric (head ps) m0\n | otherwise = m0\nsolve n j m0 ps\n | j < n = head $ drop (fromIntegral j) $ genPoints n 0 m0 ps\n | otherwise = head $ drop (fromIntegral (mod j n)) $ genPoints n 0 [mjx, mjy] ps\n where\n mn = head $ drop (fromIntegral n) $ genPoints n 0 m0 ps\n [m0x, m0y] = m0\n [mnx, mny] = mn\n mjx = m0x + (mnx - m0x) * (div j n)\n mjy = m0y + (mny - m0y) * (div j n)\n \n\nmain :: IO ()\nmain = do\n [n, j] <- reads\n m0 <- reads\n ps <- replicateM (fromIntegral n) reads\n prints $ solve n j m0 ps"}], "src_uid": "c19afaa6c46cd361e0e5ccee61f6f520"} {"source_code": "import Control.Monad\nmakePairs x y sindex desired vindex available =\n if null desired || null available\n then []\n else if head desired - x > head available\n then makePairs x y sindex desired (vindex+1) (tail available)\n else if head desired + y < head available\n then makePairs x y (sindex+1) (tail desired) vindex available\n else (sindex, vindex) : makePairs x y (sindex+1) (tail desired) (vindex+1) (tail available)\nmain = do\n [n,m,x,y] <- (liftM $ (map read) . words) getLine\n desired <- (liftM $ (map read) . words) getLine\n available <- (liftM $ (map read) . words) getLine\n let pairs = makePairs x y 1 desired 1 available\n putStrLn . show $ length pairs\n mapM_ (\\(soldier, vest) -> putStrLn $ show soldier ++ \" \" ++ show vest) pairs\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}\n{-# LANGUAGE BangPatterns #-}\nimport Control.Monad\nimport Control.Applicative\nimport Text.Printf\nimport Data.List\nimport Debug.Trace\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Char as C\n\natoi :: B.ByteString -> Int\natoi = B.foldl' (\\a c -> a*10 + C.ord c - C.ord '0') 0\n\nsolve :: Int -> Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]\nsolve _ _ [] _ = []\nsolve _ _ _ [] = []\nsolve x y ps@((i, p):ps') qs@((j, q):qs')\n | q < p-x = solve x y ps qs'\n | q > p+y = solve x y ps' qs\n | otherwise = (i, j) : solve x y ps' qs'\n\nmain = do\n [_, _, x, y] <- map atoi . B.words <$> B.getLine\n ps <- (zip [1..]) . map atoi . B.words <$> B.getLine\n qs <- (zip [1..]) . map atoi . B.words <$> B.getLine\n let as = solve x y ps qs\n putStrLn . show $ length as\n forM_ as $ uncurry (printf \"%d %d\\n\")\n"}, {"source_code": "\nimport List\n\nbigTest n = foldr (\\n s -> show n ++ \" \" ++ s) \"\" [1..n] ++ \"\\n\" ++ foldr (\\n s -> show n ++ \" \" ++ s) \"\" (reverse [1..n])\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nmySort :: [Int] -> [(Int, Int)]\nmySort xs = sortBy (\\x y -> compare (snd x) (snd y)) (zip [1..] xs)\n\nsolve :: (Int, Int) -> [Int] -> [Int] -> [(Int, Int)]\nsolve (x, y) as bs = solve' (mySort as) (mySort bs) []\n where\n solve' [] _ acc = acc\n solve' _ [] acc = acc\n solve' ((i, a):as) ((j, b):bs) acc\n | a - x > b = solve' ((i, a):as) bs acc\n | a + y < b = solve' as ((j, b):bs) acc\n | otherwise = solve' as bs ((i, j):acc)\n\nprintAns :: [(Int, Int)] -> IO ()\nprintAns ans = print (length ans) >> mapM_ (\\(x, y) -> putStrLn (show x ++ \" \" ++ show y)) ans\n\nmain :: IO ()\nmain = do\n [n, m, x, y] <- Main.reads\n as <- Main.reads\n bs <- Main.reads\n printAns $ solve (x, y) as bs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Maybe\nimport Control.Monad\nimport Data.List\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)]\nsolve [] _ x y = []\nsolve _ [] x y = []\nsolve a0@((a, ia):as) b0@((b, ib):bs) x y | a + y < b = solve as b0 x y\nsolve a0@((a, ia):as) b0@((b, ib):bs) x y | a - x <= b && b <= a + y = (ia, ib) : solve as bs x y\nsolve a0@((a, ia):as) b0@((b, ib):bs) x y | b < a - x = solve a0 bs x y\n\nreadInt = fst . fromJust . BS.readInt\n\nmain = do\n [n, m, x, y] <- liftM (map readInt . BS.words) BS.getLine\n as <- liftM (map readInt . BS.words) BS.getLine\n bs <- liftM (map readInt . BS.words) BS.getLine\n\n let ans = solve (sort $ zip as [1..]) (sort $ zip bs [1..]) x y\n\n print . length $ ans\n forM_ ans $ \\(x, y) -> putStrLn $ show x ++ \" \" ++ show y\n"}, {"source_code": "import Data.List\n\nloop :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)] -> [(Int, Int)]\nloop [] _ _ _ acc = acc\nloop _ [] _ _ acc = acc\nloop vV@((v, vi):vs) sS@((s, si):ss) lo hi acc \n | s + hi >= v && s - lo <= v = loop vs ss lo hi ((si, vi):acc)\n | s + hi < v = loop vV ss lo hi acc\n | s - lo > v = loop vs sS lo hi acc\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)]\nsolve vests solds lo hi = \n loop (sort vests) (sort solds) lo hi []\n\n\nparse :: [(Int, Int)] -> String\nparse l = unlines $ map (\\(a, b) -> (show b) ++ \" \" ++ (show a)) l \n\nmain = do\n [_, _, lo, hi] <- (getLine >>= return . map (read::String->Int) . words)\n vests <- (getLine >>= return . map (read::String->Int) . words)\n solds <- (getLine >>= return . map (read::String->Int) . words)\n let ss = solve (zip vests [1..]) (zip solds [1..]) hi lo\n print $ length ss\n putStrLn $ parse ss"}], "negative_code": [{"source_code": "import Data.List\n\nloop :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)] -> [(Int, Int)]\nloop [] _ _ _ acc = acc\nloop _ [] _ _ acc = acc\nloop vV@((v, vi):vs) sS@((s, si):ss) lo hi acc \n | s + hi >= v && s - lo <= v = loop vs ss lo hi ((si, vi):acc)\n | s + hi < v = loop vV ss lo hi acc\n | s - lo > v = loop vs sS lo hi acc\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)]\nsolve vests solds lo hi = \n loop (sort vests) (sort solds) lo hi []\n\n\nparse :: [(Int, Int)] -> String\nparse l = unlines $ map (\\(a, b) -> (show b) ++ \" \" ++ (show a)) l \n\nmain = do\n [_, _, lo, hi] <- (getLine >>= return . map (read::String->Int) . words)\n vests <- (getLine >>= return . map (read::String->Int) . words)\n solds <- (getLine >>= return . map (read::String->Int) . words)\n let ss = solve (zip vests [1..]) (zip solds [1..]) lo hi\n print $ length ss\n putStrLn $ parse ss"}, {"source_code": "import Data.List\n\nloop :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)] -> [(Int, Int)]\nloop [] _ _ _ acc = acc\nloop _ [] _ _ acc = acc\nloop vV@((v, vi):vs) sS@((s, si):ss) lo hi acc \n | s + hi >= v && s - lo <= v = loop vs ss lo hi ((si, vi):acc)\n | s + hi < v = loop vV ss lo hi acc\n | s - lo > v = loop vs sS lo hi acc\n\nsolve :: [(Int, Int)] -> [(Int, Int)] -> Int -> Int -> [(Int, Int)]\nsolve vests solds lo hi = \n loop (sort vests) (sort solds) lo hi []\n\n\nparse :: [(Int, Int)] -> String\nparse l = unlines $ map (\\(a, b) -> (show a) ++ \" \" ++ (show b)) l \n\nmain = do\n [_, _, lo, hi] <- (getLine >>= return . map (read::String->Int) . words)\n vests <- (getLine >>= return . map (read::String->Int) . words)\n solds <- (getLine >>= return . map (read::String->Int) . words)\n let ss = solve (zip vests [1..]) (zip solds [1..]) lo hi\n print $ length ss\n putStrLn $ parse ss"}], "src_uid": "c6bbb16b1a3946ce38e67dc4824ecf89"} {"source_code": "\nimport List\n\ngetWords :: IO [String]\ngetWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = getWords >>= return . (map read)\n\nsolve :: (Int, Int) -> [Int] -> Int\nsolve (a, b) hs = hb' - hb\n where\n hs' = sort hs\n hb = hs' !! (b - 1)\n hb' = hs' !! b\n\nmain :: IO ()\nmain = do\n [n, a, b] <- Main.reads\n hs <- Main.reads\n print $ solve (a, b) hs", "positive_code": [{"source_code": "import Data.List\n\nmain::IO ()\nmain = do \n cs <- getContents\n (putStr .show.solve.parseIn) cs\n\nparseIn::String->(Int,[Int])\nparseIn s = (a, reverse $ sort $ map read (words hs))\n where \n [ss,hs] = lines s\n [_,a,_] = map read (words ss)\n\nsolve::(Int,[Int])->Int\nsolve (a,hs) = he!!(a-1)-tt\n where \n (he,(tt:_)) = splitAt a hs\n "}, {"source_code": "import Data.List\nmain=putStrLn.show.slv.(map (\\x -> map read $ words x)).(take 2).lines=<>= (return . map (read::String->Int) . words))\n chores <- (getLine >>= (return . map (read::String->Int) . words))\n print $ solve chores a b"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nmain = do\n [_, _, b] <- map read <$> (words <$> getLine)\n h <- sort <$> map read <$> (words <$> getLine)\n print $ h !! b - h !! (b - 1)"}, {"source_code": "import Data.List\n\nmain = do\n [n,a,b] <- return . map (read :: String->Int) . words =<< getLine\n hs <- return . sort . map (read :: String->Int) . words =<< getLine\n let p = take b hs\n q = drop b hs\n r = if head q /= last p \n then head q - last p \n else 0 \n print r\n"}, {"source_code": "import Data.List\n\nsolve :: (Int, Int) -> [Int] -> Int\nsolve (a, b) sp = x2 - x1 \n\twhere\n\t sp' = sort sp\n\t x2 = sp' !! b\n\t x1 = sp' !! (b - 1)\n\nmain :: IO ()\nmain = do\n [n, a, b] <- (getLine >>= (return . map (read::String->Int) . words))\n sp <- (getLine >>= (return . map (read::String->Int) . words))\n print $ solve (a, b) sp"}, {"source_code": "import List\ns(n:a:b:t)=(\\(x:y:_)->y-x).drop(b-1).sort$t\nmain=interact$show.s.map read.words"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\t\t[n,x,y]<- map read <$> words <$> getLine ::IO [Int]\n\t\ta<-reverse <$> sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tlet x1 = last $ take x a\n\t\tlet x2 = head $ drop x a\n\t\tprint $ x1-x2\n \n\n"}], "negative_code": [{"source_code": "import Data.List\n\nmain = do\n [n,a,b] <- return . map (read :: String->Int) . words =<< getLine\n hs <- return . group . sort . map (read :: String->Int) . words =<< getLine\n let p = concat $ take b hs\n q = concat $ drop b hs\n r = if length p == b \n then head q - last p \n else 0 \n print r\n"}], "src_uid": "d3c8c1e32dcf4286bef19e9f2b79c8bd"} {"source_code": "import Data.Function\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- (map read.words) <$> getLine\n putStrLn $ (unwords.map show) $ solve n xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve n xs\n | ok xs = f n xs\n | otherwise = [-1]\n\nok :: [Int] -> Bool\nok xs = not $ any (\\(a,b) -> a>b) z\n where\n z = zip xs [1..]\n\nf :: Int -> [Int] -> [Int]\nf n xs = g n 0 zzzs rest\n where\n (vals,inds) = unzip $ map head $ groupBy ((==) `on` fst) $ zip xs [0..]\n zzzs = zip vals (tail inds)\n rest = h xs [0..]\n g m c [] (r:rs)\n | m == c = []\n | otherwise = r : g n (c+1) [] rs\n g m c ((v,i):vis) (r:rs)\n | i == c = v : g m (c+1) vis (r:rs)\n | otherwise = r :g m (c+1) ((v,i):vis) rs\n g _ _ _ [] = undefined\n\nh :: [Int] -> [Int] -> [Int]\nh (l:ls) (x:xss)\n | l == x = h ls xss\n | l > x = x : h (l:ls) xss\n | l < x = h ls (x:xss)\nh [] xss = xss\nh _ [] = undefined\nh (_:_) (_:_) = undefined\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ unwords . map show $ reverse $ solve (repeat (10 ^ 6)) $ reverse as\n\nsolve (q : qs) [0] = [q]\nsolve (q : qs) [_] = [0]\nsolve (q : qs) (a : a' : as)\n | a == a' = q : solve qs (a' : as)\n | otherwise = a' : solve ([a' + 1 .. a - 1] ++ q : qs) (a' : as)\n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain = do\n getLine\n as <- map read . words <$> getLine\n putStrLn $ unwords . map show $ reverse $ solve (repeat (10 ^ 6)) $ reverse as\n\nsolve (q : qs) [0] = [q]\nsolve (q : qs) [_] = [0]\nsolve (q : qs) (a : a' : as)\n | a == a' = q : solve qs (a' : as)\n | otherwise = a' : solve ([a' + 1 .. a - 1] ++ qs) (a' : as)\n"}], "src_uid": "9a31d88a2fcaf8f3d059ef0e74d6e821"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\nprocess _ [] = putStr \"\"\nprocess x (a:as) | elem a x = do\n\t\t\t\tputStrLn \"YES\"\n\t\t\t\tprocess x as\n\t\t | otherwise = do\n\t\t\t\tputStrLn \"NO\"\n\t\t\t\tprocess (a:x) as\n\nmain = do\n\t\tn<- read <$> getLine::IO Int\n\t\ta<- replicateM n getLine\n\t\tprocess [] a\n\n", "positive_code": [{"source_code": "import Data.Set (empty,insert,member)\n\npresence :: (Ord a) => [a] -> [Bool]\npresence = tail.fst.unzip.scanl (\\(_,set) x -> (member x set, insert x set)) (False,empty)\n\nreadInt :: String -> Int\nreadInt = read\n\nshowBool :: Bool -> String\nshowBool False = \"NO\"\nshowBool True = \"YES\"\n\nmain = do\n n <- fmap readInt getLine\n s <- fmap words getContents\n putStrLn.unlines.map showBool.presence $ s"}, {"source_code": "-- {-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Bool\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n xs <- replicateM n pop\n return $ unlines $ map (bool \"NO\" \"YES\") $ solve xs\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve = ap (zipWith elem) inits"}, {"source_code": "solve2 :: [String] -> [String] -> [String]\nsolve2 _ [] = []\nsolve2 seen words@(w:ws) =\n if elem w seen\n then \"YES\" : (solve2 seen ws)\n else \"NO\" : (solve2 (w:seen) ws)\n\nsolve words = solve2 [] words\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do\n (n:_) <- readInts\n c <- getContents\n putStrLn (unlines $ solve (take n $ lines c))\n"}, {"source_code": "f ::String-> [String]->String\nf str []=\"NO\"\nf str (x:xs)\n |str==x=\"YES\"\n |otherwise=f str xs\n \nf2::[String]->[String]->[String]\nf2 _ []=[]\nf2 xs (y:ys)=(f y xs):(f2 (y:xs) ys)\n\nmain = do\n e<-getLine\n es<-getContents\n let xs=lines es\n mapM_ putStrLn $ f2 [] xs"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Set as S\nimport Data.List\n\nmain = sol . lines <$> (getLine *> getContents) >>= mapM_ putStrLn\n\nsol = snd . foldl' f (S.empty,[])\n\nf (a,ss) s = if S.member s a\n then (a,ss++[\"YES\"])\n else (S.insert s a, ss++[\"NO\"])\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\npossessedDiaryBefore :: [String] -> [String]\npossessedDiaryBefore = fst . foldl (\\(a, b) c -> if elem c b\n then (a ++ [\"YES\"], b)\n else (a ++ [\"NO\"], b ++ [c])) ([], [])\n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- replicateM n $ getLine\n mapM_ putStrLn $ possessedDiaryBefore xs"}, {"source_code": "import Control.Monad( replicateM)\n\nmain = do\n n_ <- readLn::IO Int\n names_ <- replicateM n_ getLine\n let\n\tproc []\t\t = []\n\tproc (n:ames)\n\t | n `elem` ames = True:(proc ames)\n\t | otherwise\t = False:(proc ames)\n\n\tputStrLn' True = putStrLn \"Yes\"\n\tputStrLn' False = putStrLn \"No\"\n\n mapM_ putStrLn' . reverse . proc $ reverse names_\n"}, {"source_code": "import Data.Set\nrun set ans (x:xs) | x `member` set = run set (\"YES\":ans) xs\n | otherwise = run (x `insert` set) (\"NO\":ans) xs\nrun _ ans [] = reverse ans\nmain = getLine >> getContents >>= putStr . unlines . run empty [] . lines"}], "negative_code": [], "src_uid": "7f934f96cbe3990945e5ebcf5c208043"} {"source_code": "module Main where\n\nimport List\nimport Numeric\nimport Array\nimport Monad\n\n--readSeq readSpec 0 str = ([], str)\n{-\nreadSeq readSpec n str = (x:xs, s)\n where\n (x,stail) = head (readSigned readSpec str)\n (xs, s) = readSeq readSpec (n-1) stail\n-}\n--readDecs = readSeq readDec\n--readFloats = readSeq readFloat\n\nreadSeqAll readSpec str = map (fst . head . readSigned readSpec) (words str)\nreadDecsAll = readSeqAll readDec\n--readFloatsAll = readSeqAll readFloat\n\nreadStrings::Int -> IO [String]\nreadStrings 0 = \n do\n return([])\nreadStrings n = \n do\n l <- getLine\n tail <- readStrings (n-1)\n return(l : tail)\n\nfindMax arr = maximum [ 2*((i2-i+1)+(j2-j+1))\n | i <- range(1,n),\n j <- range(1,m),\n i2 <- range(i,n),\n j2 <- range(j,m),\n sum [arr!(ii,jj) | ii <- range(i,i2), jj <- range(j,j2)] == 0]\n where\n ((1,1),(n,m)) = bounds arr\n\ncharToInt x =\n case x of\n '0' -> 0\n '1' -> 1\n\nmap2 f l = map (\\x-> map f x) l\n\nmakeArray (n,m) lst = array ((1,1),(n,m)) \n [ ((i,j), (lst !! (i-1)) !! (j-1))\n | i <- range(1,n), j <- range(1,m)]\n\nmain = \n do\n sz <- getLine\n let [n,m] = readDecsAll sz\n strs <- readStrings n\n putStrLn (show (findMax (makeArray (n,m) (map2 charToInt strs))))\n", "positive_code": [{"source_code": "import Control.Monad (liftM, replicateM)\nimport Data.Array (Array, (!), array, bounds)\nimport Data.List (intercalate)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nprints :: Show a => [a] -> IO ()\nprints = putStrLn . intercalate \" \" . map show\n\ntype Map = Array (Int, Int) Char\n\nsolve :: Map -> Int\nsolve map = maximum\n [2 * (c-a+1 + d-b+1) | a <- [1..n], b <- [1..m], c <- [a..n], d <- [b..m], empty a b c d]\n where\n (n, m) = snd $ bounds map\n empty a b c d = and ['0' == map ! (i, j) | i <- [a..c], j <- [b..d]]\n\nreadMap :: Int -> Int -> IO Map\nreadMap n m = do\n lines <- replicateM n getLine\n return $ array ((1, 1), (n, m)) [((i+1, j+1), lines !! i !! j) | i <- [0..n-1], j <- [0..m-1]]\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n map <- readMap n m\n print $ solve map"}], "negative_code": [], "src_uid": "99f1db0155f3d6dd580a2c1479c34585"} {"source_code": "import Data.Char (ord)\nimport Data.List\n\n\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n\nparse = map parseLine . tail . lines\n where parseLine l = let [x1, y1, x2, y2] = map read . words $ l\n in (x1, y1, x2, y2)\n\nsolve :: [(Int, Int, Int, Int)] -> Int\nsolve = sum . map (\\(x1,y1,x2,y2) -> (x2-x1+1)*(y2-y1+1))\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\tres <- replicateM n $ do\n\t\t[ x1, y1, x2, y2 ] <- readInts\n\t\treturn $ ( x2 - x1 + 1 ) * ( y2 - y1 + 1 )\n\tprint $ sum res\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/552/A\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\n--------------------------------\n\ntype Coord = (Int, Int)\ntype Rect = (Coord, Coord)\n\ntoRect :: [Int] -> Rect\ntoRect (x1:y1:x2:y2:[]) = ((x1, y1), (x2, y2))\n\ngetArea :: Rect -> Int\ngetArea ((x1, y1), (x2, y2)) = (x2 - x1 + 1) * (y2 - y1 + 1)\n\n--------------------------------\n\nmain :: IO()\nmain = do\n\n\tn <- fmap read $ getLine :: IO Int\n\trects <-\n\t\tfmap (map toRect) $\n\t\tfmap (map . map $ read) $\n\t\tfmap (map words) $\n\t\tgetLines n :: IO [Rect]\n\n\tlet\n\t\tresult = sum $ map getArea rects\n\n\tputStrLn $ show result"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n rs <- replicateM n getInts\n\n print $ sum $ map (\\[x1, y1, x2, y2] -> (x2-x1+1)*(y2-y1+1)) rs\n"}, {"source_code": "import Control.Exception.Base\nimport Data.Functor\n\nreadInts :: IO [Int]\nreadInts = map read <$> words <$> getContents\n\nmain = readInts >>= putStrLn . show . solve\n\nsolve :: [Int] -> Int\nsolve xs = assert (length xs `mod` 4 == 1) $ solve' $ tail xs\n\nsolve' :: [Int] -> Int\nsolve' [] = 0\nsolve' (x1:y1:x2:y2:ps) = (x2-x1+1) * (y2-y1+1) + solve' ps\n"}, {"source_code": "main = interact $ show . f . map read . tail . words\nf [] = 0\nf (x:y:xx:yy:s) = (xx-x+1)*(yy-y+1) + f s\n"}, {"source_code": "module Main where\n\nimport Control.Applicative\n\nparseRect :: String -> [Int]\nparseRect = map read . words\n\narea :: [Int] -> Int\narea [l, b, r, t] = (r - l + 1) * (t - b + 1)\narea _ = 0\n\nmain :: IO ()\nmain = do\n _ <- getLine\n rects <- lines <$> getContents\n let areas = map (area . parseRect) rects\n print (sum areas)\n"}, {"source_code": "answer::[[Int]] -> Int\nanswer a = sum (map rectsize a)\nrectsize::[Int] -> Int\nrectsize a = ((a !! 2)-(a !! 0)+1)* ((a !! 3)-(a !! 1)+1)\nreadInput::Int -> IO [[Int]]\nreadInput 0 = return []\nreadInput n = do\n w <- getLine\n let a = [read c::Int|c <- (words w)]\n next <- readInput(n-1)\n return ([a] ++ next)\nmain = do\n w <- getLine\n let n = read w::Int\n a <- readInput n\n print $ answer a\n"}, {"source_code": "-- Codeforces 552A\n\nimport qualified Data.Map.Strict as Map\n\n-- use Data.Map to storage the matrix\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine :: IO Int\n getContents >>= print . sum . Map.elems . solve Map.empty . map read . words\n\nsolve :: Map.Map (Int, Int) Int -> [Int] -> Map.Map (Int, Int) Int\nsolve m [] = m\nsolve m (x1:y1:x2:y2:xs) = solve newm xs where\n newm = foldl (\\mm loc -> Map.insertWith (+) loc 1 mm) m [(i, j) | i <- [x1..x2], j <- [y1..y2]]\n"}, {"source_code": "main = interact solve\n\nsolve input = show answer\n where\n numbers = (map read . words) input\n n = head numbers\n rects = (four_by_four.tail) numbers\n answer = foldr folder 0 rects\n folder (x1,y1,x2,y2) ccount = ccount + ((y2-y1+1)*(x2-x1+1))\n\nfour_by_four [] = []\nfour_by_four (x1:y1:x2:y2:xs) = (x1,y1,x2,y2):(four_by_four xs)\n"}, {"source_code": "import Data.Functor ((<$>))\n\nmain :: IO ()\nmain = print =<< solve <$> (map (map read <$> words) <$> tail <$> lines <$> getContents)\n\nsolve :: [[Int]] -> Int\nsolve = sum . map area\n\narea :: [Int] -> Int\narea [x1, y1, x2, y2] = (x2 - x1 + 1) * (y2 - y1 + 1)\narea _ = undefined\n"}, {"source_code": "import Control.Applicative\n\nmain = do\n getLine\n inp <- lines <$> getContents\n print $ sum $ do\n x <- inp\n let l = map read . words $ x :: [Int]\n return $ (l!!2 - l!!0 + 1) * (l!!3 - l!!1 + 1)"}, {"source_code": "import Control.Applicative\n\nprocess [] n = n\nprocess ([a,b,c,d]:as) n = process as (n+(c-a+1)*(d-b+1))\n \n\nmain=do\t \n\tgetLine\n\ta<- map (map read). map words . lines <$> getContents ::IO [[Int]]\n\tprint $ process a 0"}, {"source_code": "main :: IO()\nmain = print . solve . parse =<< getContents\n\nparse = map parseLine . tail . lines\n\twhere parseLine l = let [x1,y1,x2,y2] = map read . words $ l\n\t\t\t in (x1,y1,x2,y2)\n\nsolve = sum . map area\n\twhere area (x1,y1,x2,y2) = (x2 - x1 + 1) * (y2 - y1 +1)\n"}, {"source_code": "main :: IO ()\nmain = print . solve . parse =<< getContents\n\nparse = map parseLine . tail . lines\n where parseLine l = let [x1, y1, x2, y2] = map read . words $ l\n in (x1, y1, x2, y2)\n\nsolve = sum . map area\n where area (x1, y1, x2, y2) = (x2 - x1 + 1) * (y2 - y1 + 1)\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.List as L \nimport qualified Data.Set as S\nimport qualified Data.Map as M\nimport qualified Data.Function as F\nimport Debug.Trace\n\nimport qualified Numeric as N\n\nreadInt :: String -> Int\nreadInt ('-':s) = case N.readDec s of [(n, \"\")] -> -n\nreadInt s = case N.readDec s of [(n, \"\")] -> n\n\nreadFloat :: String -> Double\nreadFloat ('-':s) = case N.readFloat s of [(x, \"\")] -> -x\nreadFloat s = case N.readFloat s of [(x, \"\")] -> x\n\ngetInts :: IO [Int]\ngetInts = map readInt . words <$> getLine \n\nmain = do\n [n] <- getInts\n res <- sum <$> (forM [1..n] $ \\_ -> do\n [a, b, c, d] <- getInts\n return $ ((c - a + 1) * (d - b + 1)))\n print res\n"}, {"source_code": "parseInput input = zs where\n xs = tail $ lines input\n ys = map words xs\n zs = [map read y :: [Int] | y <- ys]\n\narea [a, b, c, d] = (c - a + 1) * (d - b + 1)\nsolve xs = sum $ map area xs \n\nmain = do\n input <- getContents\n let xs = parseInput input\n print $ solve xs\n"}], "negative_code": [], "src_uid": "ca5c44093b1ab7c01970d83b5f49d0c6"} {"source_code": "module Main where\n\nimport Control.Monad (forM_, liftM2)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable (toList)\nimport Data.List (sort, transpose)\nimport Data.Maybe (fromJust)\nimport Data.Sequence (chunksOf, fromList)\n\nsolve :: Int -> C.ByteString -> String\nsolve i xs = concat (replicate mini \"01\") ++ replicate left more\n where\n [x, y] = map (fst . fromJust . C.readInt) (C.words xs)\n mini = min x y\n left = abs $ x - y\n more = if x > y then '0' else '1'\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n mapM_ (\\x -> putStrLn . solve x =<< C.getLine) [1 .. n]", "positive_code": [{"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [a,b] <- ri\r\n return (a,b)\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve (a,b) = ans\r\n where\r\n ans | (a < b) = rr a \"01\" ++ r (b-a) '1'\r\n | otherwise = rr b \"01\" ++ r (a-b) '0'\r\n\r\n r = replicate\r\n rr n = concat . r n\r\n"}, {"source_code": "import Control.Monad (forM_, join)\nimport Data.Functor.Compose\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1..t] $ const solve\n\nreadArray :: Read a => IO [a]\nreadArray =\n fmap read <$> (words <$> getLine)\n\nsolve :: IO ()\nsolve = do\n [x, y] <- readArray :: IO [Int]\n putStrLn $ str x y '0'\n return ()\n\nstr :: Int -> Int -> Char -> String\nstr x y c\n | x + y == 0 = \"\"\n | c == '0' && y > 0 = \"1\" ++ str x (y-1) '1'\n | c == '0' = \"0\" ++ str (x-1) y '1'\n | c == '1' && x > 0 = \"0\" ++ str (x-1) y '0'\n | c == '1' = \"1\" ++ str x (y-1) '0'\n | otherwise = undefined\n"}, {"source_code": "import Control.Monad (replicateM_)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = map read . words <$> getLine >>= \\[a,b]->\r\n putStrLn $ take (2 * min a b) (cycle \"01\") ++\r\n if a < b then replicate (b - a) '1' else replicate (a - b) '0'"}], "negative_code": [{"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List (sort)\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = sort . map read . words <$> getLine >>= \\[a',b']->\r\n let [(a,aa),(b,bb)] = sort [(a','0'),(b','1')] in\r\n let (d,m) = b `divMod` a in\r\n putStrLn . (++(replicate m bb)) . take (d*a+a) . cycle $\r\n replicate d bb ++ [aa]"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Tuple\r\ndata Unordered a = Unordered a\r\ninstance Eq (Unordered a) where\r\n (==) _ _ = True\r\ninstance Ord (Unordered a) where\r\n compare _ _ = EQ\r\ndeunorder (Unordered x) = x\r\nmain = read <$> getLine >>= flip replicateM_ solve\r\nsolve = map (read::String->Int) . words <$> getLine >>= \\ [a,b] -> \r\n putStrLn . deunorder . snd . minimum . map (key creep) $ create a b \r\nkey f x = (f x, Unordered x)\r\ncreep :: String -> Int\r\ncreep = maximum . map (abs . uncurry (-)) . scanr (\\c (a, b) -> if c == '0' then (a+1,b) else (a, b+1)) (0,0)\r\ncreate :: Int -> Int -> [String]\r\ncreate 0 b = [replicate b '1']\r\ncreate a 0 = [replicate a '0']\r\ncreate a b = (map ('0':) $ create (a - 1) b) ++ (map ('1':) . create a $ b - 1)"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [a,b] <- ri\r\n return (a,b)\r\n mapM_ (putStrLn.solve) tcs\r\n\r\nsolve (a,b) = ans\r\n where\r\n ans | (a < b) = rr a \"01\" ++ r (b-a) '0'\r\n | otherwise = rr b \"01\" ++ r (a-b) '1'\r\n\r\n r = replicate\r\n rr n = concat . r n\r\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [a,b] <- ri\r\n return (a,b)\r\n mapM_ (putStrLn.show.solve) tcs\r\n\r\nsolve (a,b) = (a,b,ans)\r\n where\r\n ans | (a < b) = r a \"01\" ++ r (b-a) \"1\"\r\n | otherwise = r b \"01\" ++ r (a-b) \"0\"\r\n\r\n r n = concat . replicate n\r\n"}, {"source_code": "import Control.Monad (forM_, join)\nimport Data.Functor.Compose\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1..t] $ const solve\n\nreadArray :: Read a => IO [a]\nreadArray =\n fmap read <$> (words <$> getLine)\n\nsolve :: IO ()\nsolve = do\n [x, y] <- readArray :: IO [Int]\n putStrLn $ str x y '0'\n return ()\n\nstr :: Int -> Int -> Char -> String\nstr x y c\n | x + y == 0 = \"\"\n | c == '0' && y > 0 = \"1\" ++ str x (y-1) '1'\n | c == '0' = \"0\" ++ str (x-1) y '1'\n | c == '1' && x > 0 = \"0\" ++ str (x-1) y '0'\n | c == '1' = \"0\" ++ str x (y-1) '0'\n | otherwise = undefined\n"}, {"source_code": "import Control.Monad (forM_, join)\nimport Data.Functor.Compose\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Integer\n forM_ [1..t] $ const solve\n\nreadArray :: Read a => IO [a]\nreadArray =\n fmap read <$> (words <$> getLine)\n\nsolve :: IO ()\nsolve = do\n [x, y] <- readArray :: IO [Int]\n print $ str x y '0'\n return ()\n\nstr :: Int -> Int -> Char -> String\nstr x y c\n | x + y == 0 = \"\"\n | c == '0' && y > 0 = \"1\" ++ str x (y-1) '1'\n | c == '0' = \"0\" ++ str (x-1) y '1'\n | c == '1' && x > 0 = \"0\" ++ str (x-1) y '0'\n | c == '1' = \"0\" ++ str x (y-1) '0'\n | otherwise = undefined\n"}, {"source_code": "module Main where\n\nimport Control.Monad (forM_, liftM2)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Foldable (toList)\nimport Data.List (sort, transpose)\nimport Data.Maybe (fromJust)\nimport Data.Sequence (chunksOf, fromList)\n\nsolve :: Int -> C.ByteString -> String\nsolve i xs = concat (replicate common \"01\") ++ replicate mini more\n where\n [x, y] = map (fst . fromJust . C.readInt) (C.words xs)\n common = abs $ x - y\n mini = min x y\n more = if x > y then '0' else '1'\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n mapM_ (\\x -> putStrLn . solve x =<< C.getLine) [1 .. n]"}], "src_uid": "7767e47571c7ea82ba4fb6a0bd0fbdc5"} {"source_code": "import Data.Array\nimport Control.Monad (replicateM_)\n\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>=\n \\n -> map read . words <$> getLine >>=\n print . maxVal . listArray (1, n)\n\nmaxVal :: Array Int Int -> Int\nmaxVal a = maximum [rotateWhole a, rotateStart a, rotateEnd a]\n \n\n\nrotateWhole a = let (1, n) = bounds a\n f a m i = if (m > (a!i - a!(i+1))) then m else a!i - a!(i+1)\n in\n foldl (f a) (a!n - a!1) [1..(n-1)]\n\nrotateStart a = let (1, n) = bounds a in\n (foldl max (a!1) (elems a)) - (a!1)\n\nrotateEnd a = let (1, n) = bounds a in\n (a!n) - (foldl min (a!n) (elems a))\n", "positive_code": [{"source_code": "{-# LANGUAGE\n ScopedTypeVariables,\n BangPatterns\n#-}\n\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\nimport Control.Monad\nimport Control.Monad.Writer\nimport Data.Semigroup\nimport Data.Coerce\n\ntryall :: [Int] -> Writer (Max Int) ()\ntryall as = do\n let a1 = head as\n an = last as\n apply = tell . coerce\n mapM_ (apply . (an -)) as\n mapM_ (apply . (subtract a1)) as\n mapM_ apply $ zipWith (-) as (tail as)\n\nsolve :: [Int] -> Int\nsolve = coerce . execWriter . tryall\n\nmain = do\n [!t] <- readInts\n replicateM_ t $ do\n _ <- readInts\n readInts >>= print . solve\n\nreadInts :: IO [Int]\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n"}], "negative_code": [], "src_uid": "943ce230777aca97266c272bdb9b364c"} {"source_code": "main :: IO ()\nmain = do\n getLine\n answers <- map (solve . read) <$> lines <$> getContents\n mapM_ print answers\n\nsolve :: Int -> Int\nsolve x = (x - 1) `div` 2\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\n\nmain :: IO ()\nmain = readLn >>= flip replicateM_ (readLn >>= print . solve)\n\nsolve :: Int -> Int\nsolve = flip div 2 . subtract 1"}, {"source_code": "solve :: Int -> Int\nsolve n = (n-1) `div` 2\n\nmain :: IO ()\nmain = interact $ unlines . map (show . solve . read) . tail . lines\n"}, {"source_code": "import Control.Monad (forM_)\n\nmain = do\n\tn <- fmap read getLine\n\tforM_ [1..n] $ \\i -> do\n\t\tk <- fmap read getLine\n\t\tprint ((k-1) `div` 2)"}, {"source_code": "\ntestCases :: Integer -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n (n:_) <- readInts\n print $ if odd n then n `div` 2 else n `div` 2 - 1\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Integer]\nreadInts = map read . words <$> getLine"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\nonecase= do\n\t\ta<- read <$> getLine ::IO Int\n\t\tprint $ div (a-1) 2 \n\nmain = do\n\t\tn<-read <$> getLine :: IO Int\n\t\treplicateM_ n onecase\n"}, {"source_code": "process :: Int -> Int\nprocess n = (n-1) `div` 2\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n t <- fmap readInt getLine\n ns <- fmap (map readInt.words) getContents\n mapM_ (print.process) ns"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n x <- readLn\n print $ (x - 1) `div` 2"}], "negative_code": [], "src_uid": "b69170c8377623beb66db4706a02ffc6"} {"source_code": "import Data.Array.IO\nimport Control.Monad\nimport Data.IORef\nimport Data.Tuple\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Lazy as B\n\nparse :: B.ByteString -> [Int]\nparse s = do\n q <- B.splitWith (\\x-> x == 13 || x == 10 || x == 32) s\n if B.length q == 0 then\n []\n else\n return $ foldl' (\\a b-> a * 10 + (fromIntegral b) - (ord '0')) 0 (B.unpack q)\n\nreadNum :: IORef [a] -> IO a\nreadNum nums = do\n x:xs <- readIORef nums\n writeIORef nums xs\n return x\n\ntraverse :: IOArray Int (Bool, [Int]) -> IORef [Int] -> Int -> Int -> Bool -> Bool -> IO ()\ntraverse g res current parent prevFlag prevPrevFlag = do\n (flag, edges) <- readArray g current\n let shouldChange = flag /= prevPrevFlag\n if shouldChange then do\n resc <- readIORef res\n writeIORef res (current:resc)\n else return ()\n forM_ edges $ \\next -> do\n if next == parent then return ()\n else traverse g res next current flag prevFlag\n\nmain :: IO ()\nmain = do\n nums0 <- B.getContents\n nums <- newIORef $ parse nums0\n n <- readNum nums\n g <- newListArray (1, n) (replicate n (False, []))\n forM_ [1..(n-1)] $ \\i-> do\n a <- readNum nums\n b <- readNum nums\n (af, aa) <- readArray g a\n writeArray g a (af, (b:aa))\n (bf, bb) <- readArray g b\n writeArray g b (bf, (a:bb))\n forM_ [1..n] $ \\i-> do\n a <- readNum nums\n (af, aa) <- readArray g i\n writeArray g i (a > 0, aa)\n forM_ [1..n] $ \\i-> do\n a <- readNum nums\n (af, aa) <- readArray g i\n writeArray g i (af /= (a > 0), aa)\n z <- readIORef nums\n res <- newIORef []\n traverse g res 1 (-1) False False\n resc <- readIORef res\n putStrLn $ show $ length resc\n forM_ resc $ putStrLn.show\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, STArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.STRef\nimport GHC.Arr (Array, Ix, unsafeIndex)\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep !n f=go 0 where go !i=when(i>go(i+1)\nrev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)\n{-# INLINE rep #-} \n{-# INLINE rev #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\n\nmain :: IO ()\nmain = do\n n <- readLn\n (uvs, rest) <- splitAt(2*(n-1)).map readInt.B.words <$> B.getContents\n let (start, goal) = splitAt n $ map (1==) rest\n let nodes = solve n (mkTree . mkGraph (0,n-1) $ parse uvs)\n (listArray (0,n-1) start)\n (listArray (0,n-1) goal)\n print $ length nodes\n putStr.unlines $ map (show.(1+)) nodes\n\ntype Vertex = Int\ntype Edge = (Vertex, Vertex)\ntype Graph = Array Vertex [Vertex]\ntype Path = [Vertex]\n\nmkGraph :: (Int, Int) -> [Edge] -> Graph\nmkGraph bnd edges = unsafeAccumArray (flip (:)) [] bnd edges\n\nmkTree :: Graph -> Graph\nmkTree gr = runSTArray $ do\n vis <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)\n tree <- newArray (bounds gr) [] :: ST s (STArray s Vertex [Vertex])\n let visit v = do\n forM_ (unsafeAt gr v) $ \\nv -> do\n visited <- unsafeRead vis nv\n unless visited $ do\n unsafeWrite vis nv True\n unsafeModify tree v (nv:)\n visit nv\n unsafeWrite vis 0 True\n visit 0\n return tree\n\nparse (u:v:uvs) = (u-1,v-1) : (v-1,u-1) : parse uvs\nparse _ = []\n\nsolve :: Int -> Graph -> UArray Int Bool -> UArray Int Bool -> [Vertex]\nsolve n gr start goal = runST $ do\n res <- newSTRef [] :: ST s (STRef s [Vertex])\n let go0 !flip0 !flip1 v\n | (flip0 /= unsafeAt start v) == unsafeAt goal v = mapM_ (go1 flip0 flip1) $ unsafeAt gr v\n | otherwise = do\n modifySTRef res (v:)\n mapM_ (go1 (not flip0) flip1) $ unsafeAt gr v\n go1 !flip0 !flip1 v \n | (flip1 /= unsafeAt start v) == unsafeAt goal v = mapM_ (go0 flip0 flip1) $ unsafeAt gr v\n | otherwise = do\n modifySTRef res (v:)\n mapM_ (go0 flip0 (not flip1)) $ unsafeAt gr v\n go0 False False 0\n reverse <$> readSTRef res\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i\n where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\ninf = maxBound `div` 2 :: Int\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s) where\n fmap f m = State $ runState m >>> first f\n\ninstance Monad (State s) where\n return x = State $ \\s -> (x,s)\n x >>= f = State $ \\s -> \n let (a,s') = runState x s in runState (f a) s'\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\nget :: State s s\nget = State $ id &&& id\nput :: s -> State s ()\nput = State . const . ((),)\nmodify :: (s -> s) -> State s ()\nmodify = State . (.) ((,) ())\nevalState :: State s a -> s -> a\nevalState = (.) fst . runState\nexecState :: State s a -> s -> s\nexecState = (.) snd . runState\n\nmain = do\n n <- readLn\n (_es,_init:_goal:_) <- splitAt (n-1) . B.lines <$> B.getContents\n let es = map (B.words >>> map readInt >>> l2p) _es\n init = map readInt $ B.words _init\n goal = map readInt $ B.words _goal\n let l = solve n es init goal\n print $ length l\n putStr $ unlines $ map show l\n\ni2b 0 = False\ni2b 1 = True\nxor False False = False\nxor False True = True\nxor True False = True\nxor True True = False\n\nsolve :: Int -> [(Int,Int)] -> [Int] -> [Int] -> [Int]\nsolve n es init goal = execState (go True False False (-1) 1) []\n where\n g :: Array Int [Int]\n g = accumArray (flip (:)) [] (1,n) $ es ++ map swap es\n ia :: UArray Int Bool\n ia = listArray (1,n) (map i2b init)\n ga :: UArray Int Bool\n ga = listArray (1,n) (map i2b goal)\n go :: Bool -> Bool -> Bool -> Int -> Int -> State [Int] ()\n go True ep op prev v = do\n let ns = [ u | u <- g ! v, u /= prev ]\n let b = (ia ! v) `xor` ep\n if b == ga ! v then\n forM_ ns $ go False ep op v\n else do\n modify (v:)\n forM_ ns $ go False (not ep) op v\n go False ep op prev v = do\n let ns = [ u | u <- g ! v, u /= prev ]\n let b = (ia ! v) `xor` op\n if b == ga ! v then\n forM_ ns $ go True ep op v\n else do\n modify (v:)\n forM_ ns $ go True ep (not op) v\n\n\n\n\n"}], "negative_code": [], "src_uid": "f3a27e4dc3085712608ecf844e663dfd"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do \n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n s <- getLine\n print $ solve n s\n\n\nsolve :: Int -> String -> Int\nsolve n s\n | ('>' `notElem` s) || ('<' `notElem` s) = n\n | otherwise = snd $ foldl (\\(p, c) x -> (x, fromEnum ('-' `elem` [p, x]) + c)) (last s, 0) s\n", "positive_code": [{"source_code": "import Control.Monad\n\nmain = do\n numTests <- read <$> getLine\n replicateM numTests $ do\n _ <- getLine\n str <- getLine\n putStrLn $ show $ solve str\n \n\nsolve :: String -> Int\nsolve str = \n if elem '<' str && elem '>' str\n then countLines str\n else length str\n\ncountLines :: String -> Int\ncountLines str = countLines' str False - (if hs == '-' && ls == '-' then 1 else 0)\n where\n hs = head str\n ls = last str\n countLines' [] _ = 0\n countLines' (x:xs) streak =\n if x == '-'\n then if streak\n then 1 + countLines' xs True\n else 2 + countLines' xs True\n else 0 + countLines' xs False"}, {"source_code": "data Belt = Clockwise | AntiClockwise | Off deriving (Eq)\n\nnNonReturnableRooms :: Bool -> Bool -> [Belt] -> Int\nnNonReturnableRooms _ _ [] = 0\nnNonReturnableRooms _ _ (h:[]) = 0\nnNonReturnableRooms clockPath counterPath (a:b:t)\n | a == Clockwise && b == AntiClockwise = 1 + nNonReturnableRooms clockPath counterPath rest\n | a == AntiClockwise && b == Clockwise = 1 + nNonReturnableRooms clockPath counterPath rest\n | a == Clockwise && b == Clockwise && (not clockPath) = 1 + nNonReturnableRooms clockPath counterPath rest\n | a == AntiClockwise && b == AntiClockwise && (not counterPath) = 1 + nNonReturnableRooms clockPath counterPath rest\n | otherwise = nNonReturnableRooms clockPath counterPath rest\n where rest = (b:t)\n\nnReturnableRooms :: [Belt] -> Int\nnReturnableRooms belts = l - (nNonReturnableRooms clockPath counterPath ((belts !! (l-1)):belts))\n where clockPath = all (\\belt -> belt == Clockwise || belt == Off) belts\n counterPath = all (\\belt -> belt == AntiClockwise || belt == Off) belts\n l = (length belts)\n\nreadBelts :: String -> [Belt]\nreadBelts \"\" = []\nreadBelts (n:t)\n | n == '>' = (Clockwise:readBelts t)\n | n == '<' = (AntiClockwise:readBelts t)\n | n == '-' = (Off:readBelts t)\n\ndropEven :: [a] -> [a]\ndropEven [] = []\ndropEven (a:b:t) = (b:(dropEven t))\n\nmain :: IO()\nmain = do\n interact $ unlines . map (show . nReturnableRooms . readBelts) . dropEven . tail . lines\n"}, {"source_code": "import Control.Monad\n\nsolve :: [Char] -> Int\nsolve str = let\n w = [p | p <- str, p /= '-']\n canRot = case w of\n [] -> True\n (p : ps) -> all (== p) ps\n in case str of\n _ | canRot -> length str\n [] -> error \"n < 2\"\n (p : ps) -> length [() | (x, y) <- zip str $ ps ++ [p], x == '-' || y == '-']\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n s <- getLine\n print $ solve s\n"}], "negative_code": [{"source_code": "import Control.Monad\n\nsolve :: [Char] -> Int\nsolve str = case str of\n [] -> 0\n (p:_) | all (== p) str -> length str\n (p:ps) -> length [() | (x, y) <- zip str $ ps ++ [p], x == '-' || y == '-']\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _n <- getLine\n s <- getLine\n print $ solve s\n"}], "src_uid": "f82685f41f4ba1146fea8e1eb0c260dc"} {"source_code": "import Data.List\nmain = getLine >> getLine >>= print . (*pi) . foldr1 (-) . reverse . sort . map ((^2) . read) . words", "positive_code": [{"source_code": "import List\nmain = do getLine; getLine >>= print . (pi*) . foldl1 subtract . sort . map ((**2) . read) . words\n"}, {"source_code": "import Data.List\nfu xs = reverse $ sort xs\nfun xs x i | null xs = x*3.141592653589793 | i `mod` 2 == 0 = fun (tail xs) (x+y*y) (i+1)| otherwise = fun (tail xs) (x-y*y ) (i+1)\n where y = head xs\nsolve s = fun (fu $ tail s) 0 2\nmain = interact $ show . solve . map read . words"}, {"source_code": "import Data.List\nsolve :: Int -> [Int] -> Double\nsolve n xs = pi * fromIntegral (square_sum xs')\n where xs' | even (length xs) = sort xs\n | otherwise = 0 : (sort xs)\n square_sum [] = 0\n square_sum (x:y:ys) = (x + y) * (y - x) + square_sum ys\n\nmain = do \n n <- readLn\n getLine >>=\n (\\str -> putStrLn $ \n (show . solve n . map read . words) str)\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nsolve [] = 0\nsolve a = pi*(last a)^2 - solve (init a)\n\nmain = getLine >> do\n rs <- map read . words <$> getLine\n print $ solve (sort rs)\n"}, {"source_code": "\nimport List\n\nreadWords :: IO [String]\nreadWords = getLine >>= return . words\n\nreads :: Read a => IO [a]\nreads = readWords >>= return . (map read)\n\nsolve :: [Double] -> Double\nsolve xs = sum $ zipWith (\\r sgn -> sgn * r * r * pi) (reverse $ sort xs) (cycle [1, -1])\n\nmain :: IO ()\nmain = getLine >> Main.reads >>= print . solve\n"}, {"source_code": "module Main where\nimport Data.List\nmain :: IO ()\nmain = do\n _ <- readLn :: IO Int\n l <- getLine\n let radii = reverse (sort (map (read :: String -> Int) (words l)))\n radiiSquared = map (^2) radii\n radiiSquaredWithIndex = zipWith (,) [0..] radiiSquared\n evenRadii = [r | (i,r) <- radiiSquaredWithIndex, even i]\n oddRadii = [r | (i,r) <- radiiSquaredWithIndex, odd i]\n piCoeff = sum evenRadii - sum oddRadii\n redArea = (fromIntegral piCoeff :: Float) * pi\n putStrLn (show redArea)\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Text.Printf\n\nmain = getLine >> do\n rs <- map read . words <$> getLine\n printf \"%.5f\" $ solve $ sortBy (flip compare) rs\n\nsolve :: [Int] -> Double\nsolve rs = (pi*) $ fromIntegral $ sum $ zipWith (#) rs $ cycle [1,-1]\n where r#n=r*r*n"}, {"source_code": "import List\ns(_:r)=pi*sum(zipWith(*)(cycle[1,-1])$reverse$sort r)\nmain=interact$show.s.map((^2).read).words"}, {"source_code": "import Data.List\nmain = do\n n <- readLn\n a <- getLine >>= return. Data.List.sort. map read. words \n let nth = ((0:a) !!)\n print. (*pi). sum $ [(nth i)^2 - (nth (i - 1))^2 | i <- [n, n - 2..1]]\n"}, {"source_code": "import Data.List\n\nneg x = if even x then 1 else -1\n\nenumerate :: Integral a => [a] -> [(a, a)]\nenumerate = zip [0..]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n let folder a (i, r) = a + neg i * r^2\n print =<< (*pi) . fromIntegral . foldl folder 0 . enumerate . sortBy (flip compare) . map (read :: String -> Int) . words <$> getLine\n"}, {"source_code": "import Prelude hiding (readList)\n\nimport System.IO\n\nimport Data.Word\nimport Data.List\nimport Data.ByteString.Lazy as B hiding (map, reverse)\nimport Data.ByteString.Lazy.Char8 as BC hiding (map, reverse)\n\nmain = do\n hSetBuffering stdin LineBuffering\n first <- fmap BC.pack System.IO.getLine\n second <- fmap BC.pack System.IO.getLine\n let Just ( n,_) = readNum first\n let Just (rs,_) = readList (fromIntegral n) second\n print $ sum $ map (uncurry square) $ toPairs $ reverse $ sort $ 0:rs\n\ntoPairs :: [a] -> [(a,a)]\ntoPairs [] = []\ntoPairs (_:[]) = []\ntoPairs (a:b:ts) = (a,b):(toPairs ts)\n\nsquare :: Word16 -> Word16 -> Float\nsquare a b = if a < b -- \u043d\u0430 \u0432\u0441\u044f\u043a\u0438\u0439 \u0441\u043b\u0443\u0447\u0430\u0439\n then square' b a\n else square' a b\n where\n square' a b = pi * ab1 * ab2\n ab1 = fromIntegral $ a - b\n ab2 = fromIntegral $ a + b\n\nreadList :: Word8 -> ByteString -> Maybe ([Word16], ByteString)\nreadList n source = readList' n [] source\n where\n readList' 0 acc source = return (acc, source)\n readList' i acc source = do\n (curr, source) <- readNum source\n readList' (i-1) (curr:acc) source\n\nreadNum :: ByteString -> Maybe ( Word16 , ByteString)\nreadNum source = fmap convert $ readInt source\n where\n convert (a,b) = (fromIntegral a, trim b)\n trim source = case BC.uncons source of\n Just (c, trimmed) | c == '\\n' || c == '\\r' || c == ' '\n -> trim trimmed\n _ -> source\n"}, {"source_code": "import Data.List\nimport Control.Monad\n\nsolve :: [Double] -> Double\nsolve [] = 0\nsolve [red] = red ^ 2\nsolve (red:blue:rest) = red ^ 2 - blue ^ 2 + solve rest\n\n\n\nmain = do\n _ <- getLine\n rows <- getLine >>= (return . map (read::String->Double) . words)\n print . (* pi) . solve . reverse . sort $ rows"}], "negative_code": [{"source_code": "import Data.List\nmain = getLine >> getLine >>= print . (*pi) . foldr1 (-) . sort . map ((^2) . read) . words"}, {"source_code": "import List\ns(_:r)=pi*sum(zipWith(*)(cycle[1,-1])r)\nmain=interact$show.s.reverse.sort.map((^2).read).words"}, {"source_code": "import Data.List\n\nneg x = if even x then 1 else -1\n\nenumerate :: Integral a => [a] -> [(a, a)]\nenumerate = zip [0..]\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine\n let folder a (i, r) = a + neg i * r^2\n print =<< (*pi) . fromIntegral . foldl folder 0 . enumerate . sort . map (read :: String -> Int) . words <$> getLine\n"}], "src_uid": "48b9c68380d3bd64bbc69d921a098641"} {"source_code": "import Data.Bits\nimport Control.Applicative\nimport Control.Monad\n\nmain = do\n t <- readLn :: IO Int\n\n replicateM_ t $ do\n a <- readLn :: IO Int\n print $ 2 ^ (popCount a)\n \n", "positive_code": [{"source_code": "-- Codeforces 1064B\nimport Data.Bits\nimport Data.List\n\ncounter :: Integer -> Integer\ncounter 0 = 1\ncounter 1 = 2\ncounter x = if x `mod` 2 == 0\n then 1 * counter (x `div` 2)\n else 2 * counter (x `div` 2)\n\nmain :: IO ()\nmain = do\n input <- getLine\n let n = read input :: Int\n inputs <- getContents\n let numbers = map (read :: String -> Integer) (lines inputs)\n mapM_ (print . counter) (take n numbers)\n"}], "negative_code": [], "src_uid": "a896ba035e56dc707f8123b1e2f2b11c"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Lazy.Builder\r\nimport Data.ByteString.Lazy.Builder.ASCII\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . intercalate \" \" . map show\r\n\r\nsolve' :: [(Int, Int)] -> Int\r\nsolve' xs = runST $ do\r\n let n = length xs + 5\r\n dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)\r\n h <- newArray (0, n) 1 :: ST s (STUArray s Int Int)\r\n forM_ xs $ \\(p, i) -> do\r\n idp <- readArray dp i\r\n ih <- readArray h i\r\n writeArray dp i $ max idp ih\r\n pdp <- readArray dp p\r\n ph <- readArray h p\r\n writeArray h p $ max ph (ih + 1)\r\n writeArray dp p $ pdp + max ih idp\r\n readArray dp 1\r\n\r\nsolve xs = solve' (reverse $ zip (0:xs) [1..])\r\n\r\nmain = do\r\n _ <- getInts\r\n xs <- getInts\r\n print $ solve xs\r\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Lazy.Builder\r\nimport Data.ByteString.Lazy.Builder.ASCII\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . intercalate \" \" . map show\r\n\r\nsolve' ((p, i):xs) dp h = if i == 1 then idp else solve' xs dp' h'\r\n where ih = h Map.! i\r\n idp = max (dp Map.! i) ih\r\n dp' = Map.adjust (+idp) p dp\r\n h' = Map.adjust (\\ph -> max ph $ ih + 1) p h\r\n\r\nsolve xs = solve' (reverse $ zip (0:xs) [1..]) dp h\r\n where dp = Map.fromList (zip [0..length xs + 1] $ repeat 0)\r\n h = Map.fromList (zip [0..length xs + 1] $ repeat 1)\r\n\r\nmain = do\r\n _ <- getInts\r\n xs <- getInts\r\n print $ solve xs\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport System.IO\r\nimport Control.Applicative\r\nimport Control.Monad\r\nimport Data.Char\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Monoid\r\nimport Data.Function (fix)\r\nimport Data.Array (Array, array, (!))\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.ByteString.Lazy.Builder\r\nimport Data.ByteString.Lazy.Builder.ASCII\r\nimport Control.Monad.ST as ST\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Map.Strict as Map\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as BS8\r\n \r\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\r\nconstruct reader str\r\n | BS.null str = []\r\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\r\n | otherwise = let Just (i, other) = reader str in i : construct reader other\r\n \r\ngetInts :: IO [Int]\r\ngetInts = construct BS8.readInt <$> BS.getLine\r\n \r\ngetIntegers :: IO [Integer]\r\ngetIntegers = construct BS8.readInteger <$> BS.getLine\r\n \r\nprintInts :: [Int] -> IO ()\r\nprintInts = putStrLn . intercalate \" \" . map show\r\n\r\nsolve' :: [(Int, Int)] -> Int\r\nsolve' xs = runST $ do\r\n let n = length xs + 5\r\n dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)\r\n h <- newArray (0, n) 1 :: ST s (STUArray s Int Int)\r\n forM_ xs $ \\(p, i) -> do\r\n idp <- readArray dp i\r\n ih <- readArray h i\r\n pdp <- readArray dp p\r\n ph <- readArray h p\r\n writeArray h p $ max ph (ih + 1)\r\n writeArray dp p $ pdp + max ih idp\r\n readArray dp 1\r\n\r\nsolve xs = solve' (reverse $ zip (0:xs) [1..])\r\n\r\nmain = do\r\n _ <- getInts\r\n xs <- getInts\r\n print $ solve xs\r\n"}], "src_uid": "5be268e0607f2d654d7f5ae4f11e2f08"} {"source_code": "import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Foldable as F\n\ncount _ [] m = m\n--count a b c | trace (\"count \" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c) False = undefined\ncount n (x:xs) m\n | x >= n = M.insertWith (+) (x-n) 1 $ count (n+1) xs m\n | otherwise = count (n+1) xs m\n\nsolve n xs =\n let former = count 1 (take ((n+1)`div`2) xs) M.empty\n all = count 1 (take (n`div`2) $ reverse xs) former\n in if M.null all then 0 else n - (F.maximum all)\n\nmain = do\n n <- readLn\n xstr <- getLine\n let xs = map read $ words xstr\n print $ solve n xs\n", "positive_code": [{"source_code": "import Data.List\nbuildSeq n = let left = [1..((n + 1) `div` 2)] in\n\tleft ++ ((if n `mod` 2 == 1 then tail else id) $ reverse left)\n\nmain = do { nl <- getLine\n\t; s <- getLine\n\t; let {n = read nl; ll = map read $ words s}\n\t; let seq1 = buildSeq n\n\t; print (n - (head $reverse $ sort $ map length $ filter (\\(h:_) -> h >= 0 ) $ \n\t\tgroup $ sort $ zipWith (\\x y -> x - y) ll seq1))\n}\n"}, {"source_code": "import Data.List\nmain = interact (show.solve.map read.words)\nsolve (n:vs) = n-(maximum.map length.group.sort.filter(>=0)) differ where\n d = div n 2\n base = if mod n 2==0 then [1..d]++[d,d-1..1] else [1..d]++[d+1]++[d,d-1..1]\n differ = zipWith (-) vs base\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = read <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\nsolve :: Int -> [Int] -> Array Int Int\nsolve n lst = \n let arr0 = listArray (0, 10^5 - 1) (repeat 0)\n lst0 = zipWith (-) lst (beautiful n 0)\n in foldl' vote arr0 lst0\n\nsolve2 :: Int -> [Int] -> [(Int, Int)]\nsolve2 n lst = \n let lst0 = zipWith (-) lst (beautiful n 0)\n gps = map (head &&& length) (group (sort (filter (> 0) lst0)))\n in gps\n \nvote :: Array Int Int -> Int -> Array Int Int\nvote arr vt\n | inRange (bounds arr) vt = \n let nextVal = (arr ! vt) + 1\n in nextVal `seq` arr // [(vt, nextVal)]\n | otherwise = arr\n \nbeautiful n a0 \n | odd n = [a0 .. at] ++ reverse [a0 .. at - 1]\n | otherwise = [a0 .. at-1] ++ reverse [a0 .. at - 1]\n where at = a0 + n `div` 2\n \ndifference a b = length (filter id (zipWith (/=) a b))\n\nmain = do\n n <- int\n lst <- ints\n let val = fst (maximumBy (compare `on` snd) (assocs (solve n lst)))\n val2 = fst (maximumBy (compare `on` snd) (solve2 n lst))\n-- print (solve n lst)\n-- print val\n-- print (difference (beautiful n val) lst)\n-- print val2\n print (difference (beautiful n val2) lst)\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Data.Array.ST\nimport Data.Array\n\nmain = do\n n <- read `liftM` getLine\n tree <- ( map read . words ) `liftM` getLine\n let tree' = map (\\(t, c) -> t - c) $ zip tree ( [1 .. n`div`2] ++ reverse [1 .. (n+1)`div`2] )\n countArray = runSTArray $ do\n countArray <- newArray (0, 10^5) 0 :: ST s (STArray s Int Int)\n forM_ tree' $ \\t ->\n if t >= 0\n then readArray countArray t >>= writeArray countArray t . (1+)\n else return ()\n return countArray\n fixN = maximum $ elems countArray\n\n putStrLn $ show ( n - fixN )\n"}], "negative_code": [{"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = read <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\nsolve :: Int -> [Int] -> Array Int Int\nsolve n lst = \n let arr0 = listArray (0, 10^5 - 1) (repeat 0)\n lst0 = zipWith (-) lst (beautiful n 0)\n in foldl' vote arr0 lst0\n\nsolve2 :: Int -> [Int] -> [(Int, Int)]\nsolve2 n lst = \n let lst0 = zipWith (-) lst (beautiful n 0)\n gps = map (head &&& length) (group (sort (filter (> 0) lst0)))\n in gps\n \nvote :: Array Int Int -> Int -> Array Int Int\nvote arr vt\n | inRange (bounds arr) vt = \n let nextVal = (arr ! vt) + 1\n in nextVal `seq` arr // [(vt, nextVal)]\n | otherwise = arr\n \nbeautiful n a0 \n | odd n = [a0 .. at] ++ reverse [a0 .. at - 1]\n | otherwise = [a0 .. at-1] ++ reverse [a0 .. at - 1]\n where at = a0 + n `div` 2\n \ndifference a b = length (filter id (zipWith (/=) a b))\n\nmain = do\n n <- int\n lst <- ints\n let val = fst (maximumBy (compare `on` snd) (assocs (solve n lst)))\n val2 = fst (maximumBy (compare `on` snd) (solve2 n lst))\n-- print (solve n lst)\n-- print val\n-- print (difference (beautiful n val) lst)\n print val2\n print (difference (beautiful n val2) lst)\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = read <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\nsolve :: Int -> [Int] -> Array Int Int\nsolve n lst = \n let arr0 = listArray (0, 10^5 - 1) (repeat 0)\n lst0 = zipWith (-) lst (beautiful n 0)\n in foldl' vote arr0 lst0\n\nsolve2 :: Int -> [Int] -> [(Int, Int)]\nsolve2 n lst = \n let lst0 = zipWith (-) lst (beautiful n 0)\n gps = map (head &&& length) (group (sort lst0))\n in gps\n \nvote :: Array Int Int -> Int -> Array Int Int\nvote arr vt\n | inRange (bounds arr) vt = \n let nextVal = (arr ! vt) + 1\n in nextVal `seq` arr // [(vt, nextVal)]\n | otherwise = arr\n \nbeautiful n a0 \n | odd n = [a0 .. at] ++ reverse [a0 .. at - 1]\n | otherwise = [a0 .. at-1] ++ reverse [a0 .. at - 1]\n where at = a0 + n `div` 2\n \ndifference a b = length (filter id (zipWith (/=) a b))\n\nmain = do\n n <- int\n lst <- ints\n let val = fst (maximumBy (compare `on` snd) (assocs (solve n lst)))\n val2 = fst (maximumBy (compare `on` snd) (solve2 n lst))\n-- print (solve n lst)\n-- print val\n-- print (difference (beautiful n val) lst)\n-- print val2\n print (difference (beautiful n val2) lst)\n"}, {"source_code": "import Debug.Trace\nimport qualified Data.Map as M\nimport qualified Data.Foldable as F\n\ncount _ [] m = m\n--count a b c | trace (\"count \" ++ show a ++ \" \" ++ show b ++ \" \" ++ show c) False = undefined\ncount n (x:xs) m\n | x >= n = M.insertWith (+) (x-n) 1 $ count (n+1) xs m\n | otherwise = count (n+1) xs m\n\nsolve n xs =\n let former = count 1 (take ((n+1)`div`2) xs) M.empty\n all = count 1 (take (n`div`2) xs) former\n in if M.null all then 0 else n - (F.maximum all)\n\nmain = do\n n <- readLn\n xstr <- getLine\n let xs = map read $ words xstr\n print $ solve n xs\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.List\nimport Data.Array.ST\nimport Data.Array\n\nmain = do\n n <- read `liftM` getLine\n tree <- ( map read . words ) `liftM` getLine\n let tree' = map (\\(t, c) -> t - c) $ zip tree ( [1 .. n`div`2] ++ reverse [1 .. (n+1)`div`2] )\n countArray = runSTArray $ do\n countArray <- newArray (-10^5, 10^5) 0 :: ST s (STArray s Int Int)\n forM_ tree' $ \\t ->\n readArray countArray t >>= writeArray countArray t . (1+)\n return countArray\n fixN = maximum $ elems countArray\n\n putStrLn $ show ( n - fixN )\n"}], "src_uid": "391be6b61e289ec9c14222ea580cfcdc"} {"source_code": "import Data.List\nimport Control.Monad\n\nnubOrd :: Eq a => [a] -> [a]\nnubOrd = foldr removeDuplicates []\n where\n removeDuplicates :: Eq a => a -> [a] -> [a]\n removeDuplicates curr acc\n | null acc = curr:acc\n | head acc == curr = acc\n | otherwise = curr:acc\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n [_,r] <- map read . words <$> getLine :: IO [Int]\n monsters <- map read . words <$> getLine :: IO [Int]\n let sorted = nubOrd $ sort monsters\n print $ foldr (minimumShots r) 0 sorted\n\n where\n minimumShots :: Int -> Int -> Int -> Int\n minimumShots rad curr shots\n | rad * shots < curr = shots + 1\n | otherwise = shots\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ print\n\nsolve = do\n\t[ n, r ] <- readInts\n\txs <- reverse . map head . group . sort <$> readInts\n\treturn $ solve' 0 r xs\n\nsolve' _ _ [] = 0\nsolve' d r (x:xs)\n\t| x <= d * r = 0\n\t| otherwise = 1 + solve' ( succ d ) r xs"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Control.Monad\n\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n line <- words <$> getLine\n let [n,r] = read <$> line :: [Int]\n line <- words <$> getLine\n let pos = Set.toDescList . Set.fromList $ (read :: String -> Int) <$> line\n let solve :: [Int] -> Int -> Int -> Int\n solve [] !_ !acc = acc\n solve (x:xs) dist acc\n | x <= dist = acc\n | otherwise = solve xs (dist + r) (acc + 1)\n print $ solve pos 0 0\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve >>= mapM_ print\n\nsolve = do\n\t[ n, r ] <- readInts\n\txs <- reverse . map head . group . sort <$> readInts\n\treturn $ solve' 0 xs\n\nsolve' _ [] = 0\nsolve' d (x:xs)\n\t| x <= d = 0\n\t| otherwise = 1 + solve' ( succ d ) xs"}], "src_uid": "60b6c6f047051eeabfe4e3a9e045c6b0"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nmain = do\n\ttmp <- B.getContents\n\tlet\n\t\tn:remain = map (fromIntegral.fst.fromJust.B.readInteger) $ B.words tmp\n\t\tget_tpl [] = []\n\t\tget_tpl (x:y:xs) = (x, 100-y) : (get_tpl xs)\n\t\tcmp (a,b) (c,d) = if (100-b)*a*d > (100-d)*c*b then\n\t\t\t\t\t\t\tLT else\n\t\t\t\t\t\t\t\tif (100-b)*a*d < (100-d)*c*b then GT else EQ\n\t\tsongs = sortBy cmp $ get_tpl remain\n\t\tp_sum = sum $ map (\\a -> snd a) songs\n\t\tans = foldl (\\var song -> ((fst var)+(fst song)+ (100 - (snd song))/100.0*(fst song)*((snd var)-(snd song))/100.0 , (snd var)-(snd song))) (0,p_sum) songs\n\tprint $ fst ans\n", "positive_code": [{"source_code": "import Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nmain :: IO ()\nmain = do\n (_:input) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let a = pairs $ map fromIntegral input\n cmp (l1, p1) (l2, p2) = compare (l2 * p2 * (100 - p1)) (l1 * p1 * (100 - p2))\n b = sortBy cmp $ a\n gao (e, s) (l, p) = e `seq` s `seq` (e + l * p, s + l * 10000 + e * (100 - p))\n ans = snd $ foldl' gao (0, 0) b\n print $ (fromIntegral :: Int64 -> Double) ans / 10000\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\ntoPairs (x:y:xys) = (x,y) : toPairs xys\ntoPairs _ = []\n\nreadInteger :: B.ByteString -> Integer\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\ncomp (l1,p1) (l2,p2) = compare (l2*p2*(100-p1)) $ l1*p1*(100-p2)\n \nmain :: IO ()\nmain = do\n _ <- getLine\n lps <- sortBy comp.toPairs.map readInteger.B.words <$> B.getContents\n let ans = 10000 * sum [l|(l,_)<-lps]\n + sum(zipWith (*) [l*p|(l,p)<-lps] (scanr1(+)[100-p|(_,p)<-tail lps]))\n putStrLn $ showAns ans\n\nshowAns 0 = \"0\"\nshowAns n\n | n>=10000 = let (xs,ys) = splitAt 4.reverse $ show n in reverse ys++\".\"++reverse xs\n | otherwise = \"0.\"++ reverse(take 4(reverse (show n)++\"0000\"))\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\n\ntoPairs (x:y:xys) = (x,y) : toPairs xys\ntoPairs _ = []\n\nreadInteger :: B.ByteString -> Integer\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\ncomp = comparing $ uncurry (*)\n \nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n lps <- sortBy(flip comp).toPairs.map readInteger.B.words <$> B.getContents\n let ans = 10000 * sum [l|(l,_)<-lps]\n + sum(zipWith (*) [l*p|(l,p)<-lps] (scanr1(+)[100-p|(_,p)<-tail lps]))\n putStrLn $ showAns ans\n\nshowAns 0 = \"0\"\nshowAns n\n | n>=10000 = let (xs,ys) = splitAt 4.reverse $ show n in reverse ys++\".\"++reverse xs\n | otherwise = \"0.\"++ reverse(take 4(reverse (show n)++\"0000\"))\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Maybe\n\nmain = do\n\ttmp <- B.getContents\n\tlet\n\t\tn:remain = map (fromIntegral.fst.fromJust.B.readInteger) $ B.words tmp\n\t\tget_tpl [] = []\n\t\tget_tpl (x:y:xs) = (x, (100 - y)/100.0) : (get_tpl xs)\n\t\tcmp (a,b) (c,d) = if a*d > c*b then\n\t\t\t\t\t\t\tLT else\n\t\t\t\t\t\t\t\tif a*d < c*b then GT else EQ\n\t\tsongs = sortBy cmp $ get_tpl remain\n\t\tp_sum = sum $ map (\\a -> snd a) songs\n\t\tans = foldl (\\var song -> ((fst var)+(fst song)+(1.0 - (snd song))*(fst song)*((snd var)-(snd song)) , (snd var)-(snd song))) (0,p_sum) songs\n\tprint $ fst ans\n"}], "src_uid": "295c768a404d11a4ac480aaaf653c45c"} {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readLn :: IO [Integer]\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve n = show (0 - (n-1)) ++ \" \" ++ show n ++ \" \"\r\n", "positive_code": [{"source_code": "test [] = []\r\ntest ints =\r\n let n = head ints\r\n in ((show (1-n)) ++ \" \" ++ (show n) ++ \"\\n\") : (test $ tail ints)\r\nmain = do\r\n ip <- getContents\r\n let ints = map read $ tail $ words ip \r\n in putStr $ concat $ test ints"}, {"source_code": "test [] = \"\"\r\ntest ints =\r\n let n = head ints\r\n in (show (1-n)) ++ \" \" ++ (show n) ++ \"\\n\" ++ (test $ tail ints)\r\nmain = do\r\n ip <- getContents\r\n let ints = map read $ tail $ words ip \r\n in putStr $ test ints"}, {"source_code": "test [] = do putStr \"\"\r\ntest ints = do\r\n let n = head ints\r\n putStr $ show (1-n)\r\n putStr \" \"\r\n print n\r\n test $ tail ints\r\nmain = do\r\n ip <- getContents\r\n let ints = map read $ tail $ words ip \r\n in test ints"}, {"source_code": "test [] = putStrLn \"\"\r\ntest ints = do\r\n let n = head ints\r\n in putStrLn ((show (1-n)) ++ \" \" ++ (show n))\r\n test $ tail ints\r\nmain = do\r\n ip <- getContents\r\n let ints = map read $ tail $ words ip \r\n in test ints"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O3 #-}\nimport Control.Arrow ((>>>))\nimport Control.Monad as M (guard, liftM, liftM3,\n replicateM, replicateM_, when)\nimport qualified Control.Monad.ST as ST\nimport qualified Control.Monad.Trans as MS\nimport Control.Monad.Trans.Maybe (MaybeT (runMaybeT))\nimport qualified Data.Array as A (elems)\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray as MA\nimport qualified Data.Array.ST as STA\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Foldable as F\nimport Data.Functor ((<&>))\nimport Data.Int (Int64)\nimport Data.Ix (Ix (range))\nimport Data.List (sort)\nimport Data.Maybe (fromJust, isJust)\nimport qualified Data.Traversable as T\nimport Data.Word (Word32)\nimport Debug.Trace as D\nimport System.IO\nimport Text.Printf (printf)\n\n\nreadInt :: B8.ByteString -> Int\nreadInt = B8.readInt >>> fromJust >>> fst\n\nreadInt64 :: B8.ByteString -> Int64\nreadInt64 = B8.readInteger >>> fromJust >>> fst >>> fromInteger\n\nupdateArray :: (MA.MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nupdateArray arr i func =\n MA.readArray arr i >>=\n MA.writeArray arr i <$> func\n\nmain :: IO ()\nmain = do\n test <- B8.getLine <&> readInt\n replicateM_ test $ do\n n <- B8.getLine <&> readInt64\n printf \"%lld %lld\\n\" (-n + 1) n\n"}, {"source_code": "{-# LANGUAGE Safe #-} \r\n{-# OPTIONS_GHC -O2 #-}\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Lazy.Char8 as B8\r\nimport qualified Data.ByteString.Builder as Bu \r\nimport Data.Functor.Identity\r\nimport Control.Monad.Trans.State\r\nimport Control.Monad\r\nimport Control.Applicative\r\n \r\ntype Input = Integer\r\ndata Output = Output Integer Integer\r\n \r\nsolve :: Input -> Output\r\nsolve ( x) = Output (-x+1) x\r\n \r\noutput :: Output -> Bu.Builder\r\noutput (Output a b) = Bu.integerDec a <> Bu.string7 \" \" <> Bu.integerDec b <> Bu.string7 \"\\n\"\r\n \r\ntcio :: StateT [B8.ByteString] Identity Bu.Builder\r\ntcio = do\r\n ~[n] <- getIntegrals 1\r\n return $ output $ solve n\r\n \r\nmain :: IO ()\r\nmain = do\r\n raw <- B8.getContents\r\n let bytestrings = B8.words raw\r\n let output = flip evalState bytestrings $ do\r\n ~[nTc] <- getIntegrals 1 \r\n let answers = replicateM nTc tcio\r\n fmap mconcat answers\r\n B8.putStr $ Bu.toLazyByteString output\r\n \r\n \r\ngetNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])\r\ngetNext [] = (B8.take 0 (B8.pack \".\"),[])\r\ngetNext (w:ws) = (w,ws)\r\n \r\ngetIntegral :: Num t => B8.ByteString -> t\r\ngetIntegral x = fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x \r\n \r\ngetIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]\r\ngetIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\n\ncalc :: Int64 -> [Int64]\ncalc n = [-n+1,n]\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let n = read line :: Int64\n putStrLn $ intercalate \" \" $ map show $ calc n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O3 #-}\nimport Control.Arrow ((>>>))\nimport Control.Monad as M (guard, liftM, liftM3,\n replicateM, when, replicateM_)\nimport qualified Control.Monad.ST as ST\nimport qualified Control.Monad.Trans as MS\nimport Control.Monad.Trans.Maybe (MaybeT (runMaybeT))\nimport qualified Data.Array as A (elems)\nimport qualified Data.Array.IArray as IA\nimport qualified Data.Array.MArray as MA\nimport qualified Data.Array.ST as STA\nimport qualified Data.Array.Unboxed as UA\nimport qualified Data.ByteString.Char8 as B8\nimport qualified Data.Foldable as F\nimport Data.Functor ((<&>))\nimport Data.Int (Int64)\nimport Data.Ix (Ix (range))\nimport Data.List (sort)\nimport Data.Maybe (fromJust, isJust)\nimport qualified Data.Traversable as T\nimport Data.Word (Word32)\nimport Debug.Trace as D\nimport System.IO\nimport Text.Printf (printf)\n\n\nreadInt :: B8.ByteString -> Int\nreadInt = B8.readInt >>> fromJust >>> fst\n\nreadInt64 :: B8.ByteString -> Int64\nreadInt64 = B8.readInteger >>> fromJust >>> fst >>> fromInteger\n\nupdateArray :: (MA.MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nupdateArray arr i func =\n MA.readArray arr i >>=\n MA.writeArray arr i <$> func\n\n\n\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n\n test <- B8.getLine <&> readInt\n replicateM_ test $ do\n n <- B8.getLine <&> readInt64\n printf \"%lld %lld\\n\" (n - 1) n \n"}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readLn :: IO [Integer]\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve n = show n ++ \" \" ++ show n\r\n"}], "src_uid": "a4628208668e9d838cd019e9dc03e470"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Data.List\n\nimport Control.Monad\nimport Control.Applicative\n\nimport Numeric\n\ndata Cartesian = Cartesian !Int !Int deriving (Eq, Ord)\ndata Polar = Polar !Int !Double deriving (Eq, Ord)\n\npolar :: Cartesian -> Polar\npolar (Cartesian x y) = Polar (x^2 + y^2) (atan2 (fromIntegral y) (fromIntegral x))\n\nfix :: Double -> Double\nfix = until (> -pi) (+ 2*pi) . until (<= pi) (subtract $ 2*pi)\n\n(~>) :: Cartesian -> Cartesian -> Cartesian\n(Cartesian x0 y0) ~> (Cartesian x1 y1) = Cartesian (x1 - x0) (y1 - y0)\n\nsolve :: [Cartesian] -> Int\nsolve [] = 0\nsolve xs0 = maximum $ map solve' xs0\n where\n solve' x = go 0.0 0.0 xs\n where\n (Polar _ \u03b1):xs = sortBy (flip compare) $ map (polar . (x ~>)) xs0\n\n go _ _ [] = 0\n go minA maxA (Polar r2 \u03b2:xs') =\n let \u03b3 = fix $ \u03b2 - \u03b1\n minA' = min minA \u03b3\n maxA' = max maxA \u03b3\n in if maxA' - minA' >= pi / 3 then r2 else go minA' maxA' xs'\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- replicateM n $ do { [x, y] <- map read . words <$> getLine; return $ Cartesian x y }\n putStrLn $ showFFloat Nothing (sqrt (fromIntegral $ solve xs) / 2) \"\"\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -funbox-strict-fields #-}\n\nimport Data.List\n\nimport Control.Monad\nimport Control.Applicative\n\nimport Numeric\n\ndata C = C !Int !Int deriving (Eq, Ord)\ndata P = P !Int !Double deriving (Eq, Ord)\n\npolar :: C -> P\npolar (C x y) = P (x^2 + y^2) (atan2 (fromIntegral y) (fromIntegral x))\n\nfix :: Double -> Double\nfix = until (> -pi) (+ 2*pi) . until (<= pi) (subtract $ 2*pi)\n\n(~>) :: C -> C -> C\nC x0 y0 ~> C x1 y1 = C (x1 - x0) (y1 - y0)\n\nsolve :: [C] -> Int\nsolve [] = 0\nsolve xs0 = maximum $ map solve' xs0\n where\n solve' x = go 0.0 0.0 xs\n where\n P _ \u03b1:xs = sortBy (flip compare) $ map (polar . (x ~>)) xs0\n\n go _ _ [] = 0\n go minA maxA (P r2 \u03b2:xs') =\n let \u03b3 = fix $ \u03b2 - \u03b1\n minA' = min minA \u03b3\n maxA' = max maxA \u03b3\n in if maxA' - minA' >= pi / 3 then r2 else go minA' maxA' xs'\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- replicateM n $ do { [x, y] <- map read . words <$> getLine; return $ C x y }\n putStrLn $ showFFloat Nothing (sqrt (fromIntegral $ solve xs) / 2) \"\"\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Data.List\n\nimport Control.Monad\nimport Control.Applicative\n\nimport Numeric\n\ndata C = C !Int !Int deriving (Eq, Ord)\ndata P = P !Int !Double deriving (Eq, Ord)\n\npolar :: C -> P\npolar (C x y) = P (x^2 + y^2) (atan2 (fromIntegral y) (fromIntegral x))\n\nfix :: Double -> Double\nfix = until (> -pi) (+ 2*pi) . until (<= pi) (subtract $ 2*pi)\n\n(~>) :: C -> C -> C\nC x0 y0 ~> C x1 y1 = C (x1 - x0) (y1 - y0)\n\nsolve :: [C] -> Int\nsolve [] = 0\nsolve xs0 = maximum $ map solve' xs0\n where\n solve' x = go 0.0 0.0 xs\n where\n P _ \u03b1:xs = sortBy (flip compare) $ map (polar . (x ~>)) xs0\n\n go _ _ [] = 0\n go minA maxA (P r2 \u03b2:xs') =\n let \u03b3 = fix $ \u03b2 - \u03b1\n minA' = min minA \u03b3\n maxA' = max maxA \u03b3\n in if maxA' - minA' >= pi / 3 then r2 else go minA' maxA' xs'\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- replicateM n $ do { [x, y] <- map read . words <$> getLine; return $ C x y }\n putStrLn $ showFFloat Nothing (sqrt (fromIntegral $ solve xs) / 2) \"\"\n"}], "negative_code": [], "src_uid": "8a92946f7c927c236c29ac10568f5079"} {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = bshow . solve <$> popInt\n\n\nsolve n | cs ! 0 > n = 0\n | cs ! (sz - 1) <= n = sz\n | otherwise = go 0 (sz - 1)\n where\n go lb ub | ub - lb == 1 = ub\n | otherwise = let mid = (lb + ub) `quot` 2 in\n case cs ! mid <= n of\n True -> go mid ub\n False -> go lb mid\n\n\ncs = let l = takeWhile (\\c -> c <= 10 ^ 9) $\n map (\\k -> (2 * k + 1) ^ 2 `quot` 2 + 1) [1..] in\n listArray (0, length l - 1) l\n\nsz = snd (bounds cs) + 1\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n C.putStrLn $ C.pack $ show $ floor $ 0.5 * (sqrt (2.0 * fromIntegral n - 1) - 1) + 1e-10\n"}, {"source_code": "-- https://codeforces.com/problemset/problem/1487/D\n\nmodule Main where\n\nimport qualified Data.Map as M\n\nmain :: IO ()\nmain = getInt >>= \\numTestCase -> driver numTestCase\n\ndriver :: Int -> IO ()\ndriver 0 = return ()\ndriver n =\n getInt >>= \\x ->\n let ans = solve x\n in print ans >> driver (n - 1)\n\ngetInt :: IO Int\ngetInt = getLine >>= \\x -> return (readInt x)\n\nreadInt :: String -> Int\nreadInt x = read x :: Int\n\nperfectSquares :: Int -> [Int]\nperfectSquares n = map (^ 2) $ takeWhile (<= n) [1 ..]\n\nsolve n = length as\n where\n as = takeWhile lessThan [3, 5 ..]\n lessThan x = ((x ^ 2) + 1) `div` 2 <= n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\ntype SIO = StateT P.ByteString IO\n\nintSqrt :: Int -> Int\nintSqrt x = let\n w = round (sqrt $ fromIntegral x :: Double)\n in if w*w > x then w-1 else w\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [n] <- readInts\n let\n w = intSqrt (2*n - 1)\n putInts [div (w-1) 2]\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,\n ConstraintKinds, BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State\nimport Data.Array\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Char\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\nimport Data.List\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Traversable\nimport System.IO\n\n------\n\ntype Hopper r = State [r]\n\ntype HopperT r = StateT [r]\n\nrunHopper :: Hopper r a -> [r] -> (a, [r])\nrunHopper = runState\n\nevalHopper :: Hopper r a -> [r] -> a\nevalHopper = evalState\n\nrunHopperT :: HopperT r m a -> [r] -> m (a, [r])\nrunHopperT = runStateT\n\nevalHopperT :: Monad m => HopperT r m a -> [r] -> m a\nevalHopperT = evalStateT\n\ntype MonadHopper r m = MonadState [r] m\n\npop :: MonadHopper r m => m (Maybe r)\npop = state f\n where\n f :: [r] -> (Maybe r, [r])\n f [] = (Nothing, [])\n f (q:qs) = (Just q, qs)\n\npopJust :: MonadHopper r m => m r\npopJust = fromJust <$> pop\n\n------\n\npopInt :: MonadHopper B.ByteString m => m Int\npopInt = fst . fromJust . B.readInt <$> popJust\n\npopInts :: MonadHopper B.ByteString m => m [Int]\npopInts = map (fst . fromJust . B.readInt) . B.words <$> popJust\n\npopInteger :: MonadHopper B.ByteString m => m Integer\npopInteger = fst . fromJust . B.readInteger <$> popJust\n\npopIntegers :: MonadHopper B.ByteString m => m [Integer]\npopIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust\n\n------\n\ndropCR :: B.ByteString -> B.ByteString\ndropCR s | not (B.null s) && B.last s == '\\r' = B.init s\n | otherwise = s\n\nbshow :: Show a => a -> B.ByteString\nbshow = B.pack . show\n\nmain = B.interact go\n where\n go :: B.ByteString -> B.ByteString\n go = evalHopper run . map dropCR . B.lines\n\n------\n\nrun :: Hopper B.ByteString B.ByteString\nrun = do\n t <- popInt\n B.unlines <$> replicateM t run1\n\n\nrun1 = bshow . solve <$> popInt\n\n\nsolve n = length $ takeWhile (\\(a, b, c) -> c <= n) triples\n\n\ntriples = map f [3, 5..]\n where\n f a = let b = a ^ 2 `quot` 2 in\n (a, b, b + 1)\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\n\nmain :: IO ()\nmain = do\n [t] <- getInts\n replicateM_ t $ do\n [n] <- getInts\n C.putStrLn $ C.pack $ show $ floor $ 0.5 * (sqrt (2.0 * fromIntegral n + 1) - 1) + 1e-10\n"}], "src_uid": "31064ad58b7802c32b3c51137057b6f5"} {"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n\tgetLine\n\ta <- getLine\n\tb <- getLine\n\tlet c = zip a b\n\tlet cnt00 = fromIntegral . length $ elemIndices ('0', '0') c\n\tlet cnt01 = fromIntegral . length $ elemIndices ('0', '1') c\n\tlet cnt10 = fromIntegral . length $ elemIndices ('1', '0') c\n\tlet cnt11 = fromIntegral . length $ elemIndices ('1', '1') c\n\tprint $ cnt00 * cnt10 + cnt00 * cnt11 + cnt01 * cnt10\n", "positive_code": [{"source_code": "{-# LANGUAGE ExistentialQuantification #-}\nmodule Main where\nimport Control.Applicative\nimport Data.Int\n\ndefault (Int64)\n\nmain = interact exec\nexec = show . (\\[xs, ys] -> let (n0, n1) = runFold fc xs; in (\\(n0', n1') -> n0' * n1 + n1' * n0 - n0' * n1') $ runFold fc $ map fst $ filter ((== '0') . snd) $ zip xs ys ) . tail . words\n where fc = liftA2 (,) (fcount '0') (fcount '1')\n\ndata Fold a b = forall x. Fold (x -> a -> x) x (x -> b)\ndata Pair a b = Pair !a !b\ninstance Functor (Fold a) where\n fmap f (Fold step begin done) = Fold step begin (f . done)\ninstance Applicative (Fold a) where\n pure b = Fold (\\() _ -> ()) () (\\() -> b)\n (Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =\n let step (Pair xL xR) a = Pair (stepL xL a) (stepR xR a)\n begin = Pair beginL beginR\n done (Pair xL xR) = doneL xL (doneR xR)\n in Fold step begin done\nrunFold (Fold step begin done) as = foldr (\\a k x -> k $! step x a) done as begin\n\nfcount a = Fold (\\c x -> c + fromIntegral (fromEnum $ x == a)) 0 id\nfsum = Fold (+) 0 id\nflength = Fold (flip (const succ)) 0 id"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n\tgetLine\n\ta <- getLine\n\tb <- getLine\n\tlet c = zip a b\n\tlet cnt00 = length $ elemIndices ('0', '0') c\n\tlet cnt01 = length $ elemIndices ('0', '1') c\n\tlet cnt10 = length $ elemIndices ('1', '0') c\n\tlet cnt11 = length $ elemIndices ('1', '1') c\n\tprint $ cnt00 * cnt10 + cnt00 * cnt11 + cnt01 * cnt10\n"}, {"source_code": "{-# LANGUAGE ExistentialQuantification #-}\nmodule Main where\nimport Control.Applicative\n\ndefault (Int)\n\nmain = interact exec\nexec = show . (\\[xs, ys] -> let (n0, n1) = runFold fc xs; in (\\(n0', n1') -> n0' * n1 + n1' * n0 - n0' * n1') $ runFold fc $ map fst $ filter ((== '0') . snd) $ zip xs ys ) . tail . words\n where fc = liftA2 (,) (fcount '0') (fcount '1')\n\ndata Fold a b = forall x. Fold (x -> a -> x) x (x -> b)\ndata Pair a b = Pair !a !b\ninstance Functor (Fold a) where\n fmap f (Fold step begin done) = Fold step begin (f . done)\ninstance Applicative (Fold a) where\n pure b = Fold (\\() _ -> ()) () (\\() -> b)\n (Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =\n let step (Pair xL xR) a = Pair (stepL xL a) (stepR xR a)\n begin = Pair beginL beginR\n done (Pair xL xR) = doneL xL (doneR xR)\n in Fold step begin done\nrunFold (Fold step begin done) as = foldr (\\a k x -> k $! step x a) done as begin\n\nfcount a = Fold (\\c x -> c + fromEnum (x == a)) 0 id\nfsum = Fold (+) 0 id\nflength = Fold (flip (const succ)) 0 id"}, {"source_code": "{-# LANGUAGE ExistentialQuantification #-}\nmodule Main where\nimport Control.Applicative\n\ndefault (Int)\n\nmain = interact exec\nexec = show . (\\[xs, ys] -> let (nz, no) = runFold (liftA2 (,) (fcount '0') (fcount '1')) xs; ff = Fold (\\c x -> c + if x == '0' then no else nz) 0 id; in runFold (liftA2 (-) ff (fcount '0')) $ map fst $ filter ((== '0') . snd) $ zip xs ys ) . tail . words\n\ndata Fold a b = forall x. Fold (x -> a -> x) x (x -> b)\ndata Pair a b = Pair !a !b\ninstance Functor (Fold a) where\n fmap f (Fold step begin done) = Fold step begin (f . done)\ninstance Applicative (Fold a) where\n pure b = Fold (\\() _ -> ()) () (\\() -> b)\n (Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =\n let step (Pair xL xR) a = Pair (stepL xL a) (stepR xR a)\n begin = Pair beginL beginR\n done (Pair xL xR) = doneL xL (doneR xR)\n in Fold step begin done\nrunFold (Fold step begin done) as = foldr (\\a k x -> k $! step x a) done as begin\n\nfcount a = Fold (\\c x -> c + fromEnum (x == a)) 0 id\nfsum = Fold (+) 0 id\nflength = Fold (flip (const succ)) 0 id"}], "src_uid": "621c82478be3dadcf60c383ba078a49e"} {"source_code": "import Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,k] <- map read . words <$> getLine\n s <- getLine\n let f i = minimum $ zipWith (-) =<< drop k $ scanl (+) 0 $ map fromEnum $ zipWith (/=) s $ drop i $ cycle \"RGB\"\n print $ minimum $ map f [0..2]\n", "positive_code": [{"source_code": "import Control.Monad\nmain = do\n q <- readLn\n replicateM_ q $ do\n [n,k] <- map read . words <$> getLine\n s <- getLine\n let f i = minimum $ zipWith (-) =<< drop k $ scanl (+) 0 $ map fromEnum $ zipWith (/=) s $ drop i $ cycle \"RGB\"\n print $ minimum $ map f [0..2]\n"}], "negative_code": [], "src_uid": "1aa8f887eb3b09decb223c71b40bb25b"} {"source_code": "module Main where\nimport Prelude hiding (reads)\nparse x = (takeWhile (/=' ') x) : if (null rest) then [] else parse (tail $ (dropWhile (/=' ')) x) where\n rest = dropWhile (/=' ') x\nread' :: String -> Int\nread' = read\n\nreads :: Int -> IO [String]\nreads 0 = return []\nreads k = do\n x <- getLine\n xs <- reads $ k - 1\n return (x:xs)\n\narithm [] = 0\narithm [_] = 1\narithm (x:y:z) = if y-x==1 then 1 + arithm (y:z) else 1\n\nmain = do\n s <- getLine\n let [n,k] = map read' $ parse s\n ranges <- reads k\n let lists = map (tail . map read' . parse) ranges\n let [st] = filter ((==1) . head) lists\n let rest = filter ((/=1) . head) lists\n print $ (length st - arithm st) + sum (map (\\x -> length x - 1) rest) + (n - arithm st)", "positive_code": [{"source_code": "import Control.Applicative\n\ncount [] _ = 0\ncount (l:ls) x\n | l == x = 1 + count ls (x+1)\n | otherwise = 0\n \nmain = do\n m <- read . head . tail . words <$> getLine :: IO Int\n l <- map (map read . words) . lines <$> getContents :: IO [[Int]]\n let s = sum $ do\n x <- tail <$> l\n let c = count x 1 `max` 1\n return $ length x - c + 1\n print $ (s-m) + (s-1)"}, {"source_code": "start x (y:ys) = if y - x == 1 then 1 + start y ys else 0\nstart _ _ = 0\nsolve ([n, k]:xs) = 2 * n - k + 1 - 2 * (sum . map (start 0 . tail) $ xs)\nmain = interact $ show . solve . map (map (read :: String -> Int) . words) . lines\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\n{-\n1 3 7 -> 2 + 2\n2 5 -> 1 + 2\n4 6 -> 1 + 2\n-}\n\n\nmain = do\n (n,k) <- readIntPair\n as <- map (map readInt . B.words) . B.lines <$> B.getContents\n let ms = map tail as\n let m0:ms' = sortBy (\\x y -> compare (head x) (head y)) ms\n let go x [] = 0\n go x (y:ys) | x == y - 1 = go y ys\n | otherwise = 2 * length (y:ys)\n print $ go (head m0) (tail m0) + sum (map ((\\x -> 2*x-1). length) ms')\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport Debug.Trace\n\nsolve :: Int -> [[Int]] -> Int\nsolve n chains =\n 2 * (n - k) - (c - 1)\n where\n c = length chains\n k = length $ head $ group $ zipWith (\\a -> \\b -> a == b) [1..] $ head $ filter (\\x -> head x == 1) $ chains\n\nmain = do\n [n, _] <- map read . words <$> getLine\n chains <- map (map read . tail . words) . lines <$> getContents\n putStrLn $ show $ solve n chains\n"}, {"source_code": "module Main where\n\nimport Data.List\nimport Data.Bool\nimport Data.Maybe\nimport Control.Applicative\nimport Control.Monad\n\nrl :: Read a => IO [a]\nrl = fmap read . words <$> getLine\n\nred i [] = []\nred i (x:xs) | i == x = red (i+1) xs\n | otherwise = (x:xs)\n\nmain :: IO ()\nmain = do\n [n, k] <- rl :: IO [Int]\n fmap ((+1).sum) (forM [1..k] (const (fmap ((subtract 1).(* 2).length.red 1.tail) rl)))\n >>= print\n pure ()\n"}], "negative_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\ndata Matryoshka = Mat { top :: Int , chain :: [Int] } deriving Show\n\ninstance Eq Matryoshka where\n a == b = top a == top b\n\ninstance Ord Matryoshka where\n compare a b = compare (top a) (top b)\n\nmain = do\n (n,k) <- readIntPair\n as <- map (map readInt . B.words) . B.lines <$> B.getContents\n let ms = [ Mat (head l) (tail l) | _:l <- as ]\n let go s | S.null s = 0\n | otherwise = \n let (m,s') = S.deleteFindMin s in\n let sub _ [] = if S.null s' then 0 else 1 +go s'\n sub x (y:ys) | y == x + 1 = sub y ys\n sub x ys =\n let ns = map (\\x -> Mat x []) ys in\n 1 + length ys + go (foldr S.insert s' ns)\n in sub (top m) (chain m)\n print $ go $ S.fromList ms\n"}, {"source_code": "import Data.List\nimport Control.Applicative\n\nsolve :: Int -> [[Int]] -> Int\nsolve n chains =\n 2 * (n - lsum) + (length chains) - 1\n where\n lsum = sum $ map l chains\n l (a:rst) = length $ head $ group $ zipWith (\\a -> \\b -> a == b) (a:rst) [a..]\n l [] = 0\n\nmain = do\n [n, _] <- map read . words <$> getLine\n chains <- map (map read . tail . words) . lines <$> getContents\n putStrLn $ show $ solve n chains\n"}, {"source_code": "start x (y:ys) = if x == y then 1 + start (x + 1) ys else 0\nstart _ [] = 0\nsolve ([n, k]:xs) = 2 * n - k - 1 - 2 * (sum . map (start 1) . tail $ xs)\nmain = interact $ show . solve . map (map (read :: String -> Int) . words) . lines\n"}, {"source_code": "start x (y:ys) = if y - x == 1 then 1 + start y ys else 0\nstart _ _ = 0\nsolve ([n, k]:xs) = 2 * n - k - 1 - 2 * (sum . map (start 0 . tail) $ xs)\nmain = interact $ show . solve . map (map (read :: String -> Int) . words) . lines\n"}, {"source_code": "start x (y:ys) = if x == y then 1 + start y ys else 0\nstart _ [] = 0\nsolve ([n, k]:xs) = 2 * n - k - 1 - 2 * (sum . map (start 1) . tail $ xs)\nmain = interact $ show . solve . map (map (read :: String -> Int) . words) . lines\n"}], "src_uid": "6590c99e35f6f65e1b1bbd4f5bdca43a"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n n:hs <- ints\n print $ solve n hs\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getContents\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: Int -> [Int] -> Integer\nsolve n xs = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount !c [x, 1] = c + x + count2 x\ncount !c [x] = c + count2 x\ncount !c (x:xs) = count (c + 2 * x + count2 x) xs", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n n:hs <- ints\n print $ solve n hs\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getContents\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: Int -> [Int] -> Integer\nsolve n xs = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount c [x, 1] = c + x + count2 x\ncount c [x] = c + count2 x\ncount c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\nreadHills :: String -> (Int, [Int])\nreadHills input = (n, hs) where n:hs = map read $ words input\n\ncount2 :: Int64 -> Int64\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: (Int, [Int]) -> Int64\nsolve (n, xs) = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int64 deriving (Show)\n\niter :: Int64 -> [Acc] -> [Acc] -> Int64\niter !c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * cx + count2 cx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n\ncount :: Int64 -> [Int64] -> Int64\ncount !c [x, 1] = c + x + count2 x\ncount !c [x] = c + count2 x\ncount !c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\nreadHills :: String -> (Int, [Int])\nreadHills input = (n, hs) where n:hs = map read $ words input\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: (Int, [Int]) -> Integer\nsolve (n, xs) = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount !c [x, 1] = c + x + count2 x\ncount !c [x] = c + count2 x\ncount !c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n n:hs <- ints\n print $ solve n hs\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getContents\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: Int -> [Int] -> Integer\nsolve n xs = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc Int Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount c [x, 1] = c + x + count2 x\ncount c [x] = c + count2 x\ncount c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Integer -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Integer\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n GT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n LT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo (toInteger ky) + (toInteger ky) * 2\n -- large hill to the left of y, small hill y, large hill z\n\nfDescending :: Integer -> [(Int, Int)] -> Integer\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo (toInteger ky)\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo (toInteger ky) + (toInteger ky)\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo (toInteger ky) + 2 * (toInteger ky)\n\nfff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = readLineOfInts lhills\n print $ fff hills\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\nimport Data.Maybe (fromJust)\n\nimport qualified Data.ByteString.Char8 as BS\n\nmain :: IO ()\nmain = do\n n:hs <- ints\n print $ solve n hs\n\nints :: IO [Int]\nints = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getContents\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: Int -> [Int] -> Integer\nsolve n xs = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter !c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount !c [x, 1] = c + x + count2 x\ncount !c [x] = c + count2 x\ncount !c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "module Main where\n\nimport Data.Int (Int64)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\nreadHills :: String -> (Int, [Int])\nreadHills input = (n, hs) where n:hs = map read $ words input\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: (Int, [Int]) -> Integer\nsolve (n, xs) = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount c [x, 1] = c + x + count2 x\ncount c [x] = c + count2 x\ncount c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\nreadHills :: String -> (Int, [Int])\nreadHills input = (n, hs) where n:hs = map read $ words input\n\ncount2 :: Integer -> Integer\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: (Int, [Int]) -> Integer\nsolve (n, xs) = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int deriving (Show)\n\niter :: Integer -> [Acc] -> [Acc] -> Integer\niter !c acc hs\n | null hs = count c $ map (\\(Acc _ cc) -> fromIntegral cc) acc\n | null acc = iter c [h] (tail hs)\n | hx > hy = iter c (h : acc) (tail hs)\n | hx == hy = iter c (Acc hx (cx + cy) : as) (tail hs)\n | otherwise = iter (c + 2 * ccx + count2 ccx) as hs\n where\n h = head hs\n Acc hx cx = head acc\n Acc hy cy = h\n as = tail acc\n ccx = fromIntegral cx\n\ncount :: Integer -> [Integer] -> Integer\ncount c [x, 1] = c + x + count2 x\ncount c [x] = c + count2 x\ncount c (x:xs) = count (c + 2 * x + count2 x) xs"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\ntype I = Int\n\nreadHills :: String -> [I]\nreadHills = tail . map read . words\n\ncount2 :: I -> I\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: [I] -> I\nsolve xs = count 0 $ unfoldr step xs\n\ncount :: I -> [I] -> I\ncount c [x, 1] = c + x + count2 x\ncount c [x] = c + count2 x\ncount c (x:xs) = count (c + 2 * x + count2 x) xs\n\n\nstep :: [I] -> Maybe (I, [I])\nstep [] = Nothing\nstep hs = Just (length ms, ls ++ rs)\n where\n ml = minimum hs\n (ls, rems) = span (/= ml) hs\n (ms, rs) = span (== ml) rems"}, {"source_code": "module Main where\n\nimport Data.Int (Int64)\nimport Data.List (unfoldr)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\nreadHills :: String -> [Int]\nreadHills = tail . map read . words\n\ncount2 :: Int -> Int\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: [Int] -> Int64\nsolve xs = count 0 $ unfoldr step xs\n\ncount :: Int64 -> [Int] -> Int64\ncount c [x, 1] = c + fromIntegral (x + count2 x)\ncount c [x] = c + fromIntegral (count2 x)\ncount c (x:xs) = count (c + fromIntegral (2 * x + count2 x)) xs\n\nstep :: [Int] -> Maybe (Int, [Int])\nstep [] = Nothing\nstep hs = Just (length ms, ls ++ rs)\n where\n ml = minimum hs\n (ls, rems) = span (/= ml) hs\n (ms, rs) = span (== ml) rems"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport Data.Int (Int64)\n\nmain :: IO ()\nmain = interact $ show . solve . readHills\n\nreadHills :: String -> (Int, [Int])\nreadHills input = (n, hs) where n:hs = map read $ words input\n\ncount2 :: Int64 -> Int64\ncount2 n = n * (n - 1) `div` 2\n\nsolve :: (Int, [Int]) -> Int64\nsolve (n, xs) = iter 0 [] $ map (`Acc` 1) hs\n where\n maxH = maximum xs\n hs = take n $ dropWhile (/= maxH) (cycle xs)\n\ndata Acc = Acc !Int !Int64\n\niter :: Int64 -> [Acc] -> [Acc] -> Int64\niter !c acc [] = count c $ map (\\(Acc _ cc) -> cc) acc\niter !c [] (h:hs) = iter c [h] hs\niter !c acc@(Acc hx cx:as) hss@(Acc hy cy:hs)\n | hx < hy = iter c (Acc hy cy : acc) hs\n | hx == hy = iter c (Acc hx (cx + cy) : as) hs\n | otherwise = iter (c + 2 * cx + count2 cx) as hss\n\ncount :: Int64 -> [Int64] -> Int64\ncount !c [x, 1] = c + x + count2 x\ncount !c [x] = c + count2 x\ncount !c (x:xs) = count (c + 2 * x + count2 x) xs"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Int\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n LT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n GT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo ky + ky * 2\n -- large hill to the left of y, small hill y, large hill z\n\nfDescending :: Int -> [(Int, Int)] -> Int\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo ky\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo ky + ky\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo ky + 2 * ky\n\nfff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nff 5 [4136, 1826, 4136, 1826, 1826] = let\n x = (minBound, maxBound) :: (Int, Int)\n in show (fff [4136, 1826, 4136, 1826, 1826])\nff n hills = show $ fff hills\n\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = take n $ readLineOfInts lhills\n putStrLn $ ff n hills\n"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Int\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n LT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n GT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo ky + ky * 2\n -- large hill to the left of y, small hill y, large hill z\n\nfDescending :: Int -> [(Int, Int)] -> Int\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo ky\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo ky + ky\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo ky + 2 * ky\n\nff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = take n $ readLineOfInts lhills\n let x = (minBound, maxBound) :: (Int, Int)\n print $ ff hills\n"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Int\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n GT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n LT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo ky + ky * 2\n -- large hill to the left of y, small hill y, large hill z\n{-\n0 rev[] rev[] [3,1 2,1 3,1 2,1 2,1]\n0 rev[] rev[3,1] [2,1 3,1 2,1 2,1] \n0 rev[] rev[3,1 2,1] [3,1 2,1 2,1]\n2 rev[] rev[3,1] [3,1 2,1 2,1]\n2 rev[] rev[3,2] [2,1 2,1]\n2 rev[] rev[3,2 2,1] [2,1]\n2 rev[] rev[3,2 2,2] []\nfDesc 2 rev[3,2 2,2]\nfDesc 7 rev[3,2]\n7 + 1 = 8\n\n-}\n\nfDescending :: Int -> [(Int, Int)] -> Int\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo ky\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo ky + ky\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo ky + 2 * ky\n\nfff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nff 5 [4136, 1826, 4136, 1826, 1826] = let\n x = (minBound, maxBound) :: (Int, Int)\n in show (fff [4136, 1826, 4136, 1826, 1826])\nff n hills = show $ fff hills\n\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = readLineOfInts lhills\n print $ fff hills\n"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Int\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n LT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n GT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo ky + ky * 2\n -- large hill to the left of y, small hill y, large hill z\n\nfDescending :: Int -> [(Int, Int)] -> Int\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo ky\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo ky + ky\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo ky + 2 * ky\n\nfff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nff 5 [4136, 1826, 4136, 1826, 1826] = let\n x = (minBound, maxBound) :: (Int, Int)\n in show x ++ \" \" ++ show (fff [4136, 1826, 4136, 1826, 1826])\nff n hills = show $ fff hills\n\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = take n $ readLineOfInts lhills\n putStrLn $ ff n hills\n"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Integer -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Integer\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n GT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n LT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo (toInteger ky) + (toInteger ky) * 2\n -- large hill to the left of y, small hill y, large hill z\n{-\n0 rev[] rev[] [3,1 2,1 3,1 2,1 2,1]\n0 rev[] rev[3,1] [2,1 3,1 2,1 2,1] \n0 rev[] rev[3,1 2,1] [3,1 2,1 2,1]\n2 rev[] rev[3,1] [3,1 2,1 2,1]\n2 rev[] rev[3,2] [2,1 2,1]\n2 rev[] rev[3,2 2,1] [2,1]\n2 rev[] rev[3,2 2,2] []\nfDesc 2 rev[3,2 2,2]\nfDesc 7 rev[3,2]\n7 + 1 = 8\n\n-}\n\nfDescending :: Integer -> [(Int, Int)] -> Integer\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo (toInteger ky)\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo (toInteger ky) + (toInteger ky)\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo (toInteger ky) + 2 * (toInteger ky)\n\nfff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = readLineOfInts lhills\n let x = (minBound, maxBound) :: (Int, Int)\n print x\n print $ fff hills\n"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Int\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n LT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n GT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo ky + ky * 2\n -- large hill to the left of y, small hill y, large hill z\n\nfDescending :: Int -> [(Int, Int)] -> Int\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo ky\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo ky + ky\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo ky + 2 * ky\n\nff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = readLineOfInts lhills\n let x = (minBound, maxBound) :: (Int, Int)\n print $ ff hills\n"}, {"source_code": "-- not FINISHED\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\nimport Data.List\nimport Data.Tuple\nimport Data.Function\nimport qualified Data.ByteString.Char8 as BS\n--import qualified Data.ByteString.Lazy.Char8 as BS\n\nreadInt :: BS.ByteString -> Int\nreadInt x =\n case BS.readInt x of Just (i,_) -> i\n Nothing -> error \"Unparsable Int\"\nreadLineOfInts l = map readInt (BS.split ' ' l)\n\nchooseTwo n = n * (n - 1) `div` 2\n\nf :: Int -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] -> Int\n-- f a xs ys zs = p\n-- f 0 [] [] zs computes the number of pairs of hills that can see each other\n-- hills can see each other when no hill on either of the circle arcs between\n-- them is higher than either of them\n-- the circle of hills is represented by the list\n-- rev xs ++ rev ys ++ zs\n-- where a pair (h, k) denotes k neighbouring hills all of the same height h,\n-- the list xs are the leftmost ascending hills (in reverse order)\n-- the list ys is a following segment of descending hills (in reverse order, ending with one larger than in xs, so ys=[]->xs=[])\n-- and the list zs are the remaining hills\n-- a is the accumulator for the number of pairs\nf a [] [] (z:zs) = f a [] [z] zs\nf a [] ys [] = fDescending a ys\n-- if we end up with an ascending prefix, we wrap it around to the end and do another pass (only happens once)\nf a xs ys [] = f a [] ys (reverse xs)\nf a xs ((hy,ky):ys) ((hz,kz):zs) = case hy `compare` hz of\n LT -> f a xs ((hz,kz):(hy,ky):ys) zs\n EQ -> f a xs ((hy,ky+kz):ys) zs\n GT -> if ys == []\n then f a ((hy,ky):xs) [(hz,kz)] zs\n else f b xs ys ((hz,kz):zs) where b = a + chooseTwo ky + ky * 2\n -- large hill to the left of y, small hill y, large hill z\n\nfDescending :: Int -> [(Int, Int)] -> Int\n-- f a ys = p\n-- ys is a list of descending hills in REVERSE order, so actually the last element in ys corresponds to the largest hills\nfDescending a [(hy,ky)] = a + chooseTwo ky\nfDescending a [(hy,ky),(hw,1)] = a + chooseTwo ky + ky\nfDescending a ((hy,ky):ys) = fDescending b ys where b = a + chooseTwo ky + 2 * ky\n\nff = (f 0 [] []) . (map (\\h -> (h, 1)))\n\nmain :: IO ()\nmain = do\n [ln,lhills] <- fmap BS.lines BS.getContents\n let n = readInt ln\n let hills = readLineOfInts lhills\n let x = (minBound, maxBound) :: (Int, Int)\n print $ ff hills\n"}], "src_uid": "e32328aaeeea789e993d09335764c021"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\ngetIntList :: IO [Int]\ngetIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nmain :: IO ()\nmain = print =<< sol <$> (getLine *> getIntList)\n\nsol :: [Int] -> Int\nsol = fst . fst . foldl' f ((0,0),0)\n where\n f ((p,q),b) a = if b>a then ((p,1),a) else ((max p (q+1),q+1),a)", "positive_code": [{"source_code": "import Data.List\n\nparse :: String -> Int\nparse x = read x :: Int\n\ncomb :: (Int,Int,Int) -> Int -> (Int,Int,Int)\ncomb (ans, stride, last) cur \n | cur < last = (ans, 1, cur)\n | otherwise = (max ans (stride+1), stride+1, cur)\n\ngetans (ans, _, _) = ans\n\nsolve :: [Int] -> Int\nsolve xs = getans (foldl comb (1,0,-1) xs)\n\nrun :: String -> String\nrun xs = show $ solve $ map parse $ tail $ words xs\n\n\nmain = interact run"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t(a:as) <- readInts\n\n\tprint $ succ $ maximum $ ( 0 : ) $ map length $ filter ( ( == 1 ) . head ) $ group $ conv a as\n\nconv _ [] = []\nconv p (a:as)\n\t| p <= a = 1 : conv a as\n\t| otherwise = 0 : conv a as\n"}, {"source_code": "removeFromFront :: Int -> [Int] -> [Int]\nremoveFromFront a [] = []\nremoveFromFront a (h:t) \n\t|(h >= a) = (removeFromFront h t)\n\t|otherwise = (h:t)\n\nlongestSubsegment :: [Int] -> Int\nlongestSubsegment [] = 0\nlongestSubsegment t = max (length t - length removed) (longestSubsegment removed)\n\twhere removed = removeFromFront 0 t\n\n\nlong :: Int -> Int -> [Int] -> Int\nlong last acc [] = acc\nlong last acc (h:t) \n\t|last <= h = long h (acc+1) t\n\t|otherwise = max acc (long h 1 t)\n\nmain = do\n\tn <- fmap (map (read::String -> Int).words) getLine\n\tseq <- fmap (map read.words) getLine\n\tprint $ (long 0 0 seq)"}, {"source_code": "import Control.Monad\n\n\nsearch [x] cur m = m\nsearch (x:y:xs) cur m\n | y >= x = search (y:xs) cur' (max cur' m)\n | otherwise = search (y:xs) 0 m\n where\n cur' = cur+1\n\n\nmain = do\n n <- readLn :: IO Int\n aa <- getLine\n let xs = map read $ words aa :: [Int]\n print $ 1 + search xs 0 0\n"}, {"source_code": "module Main (main)\n where\n\n\nreadInts :: String -> [Int]\nreadInts = map read . words\n\nmain :: IO ()\nmain = print . solve . readInts =<< (getLine >> getLine)\n where solve (x:xs) = go 0 1 x xs\n go m t _ [] = max m t\n go m t last (x:xs)\n | x >= last = go m (t + 1) x xs\n | otherwise = go (max m t) 1 x xs"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nmain = do print . (solve 1).(2000000000:).tail =<< map (fst . fromJust . B.readInt) . B.words <$> B.getContents\nsolve :: Int->[Int]->Int\nsolve acc (a:b:[]) = if b>=a then acc+1 else acc\nsolve acc (a:xs@(b:_)) | a>b = max acc $ solve 1 xs\n | otherwise = solve (acc+1) xs"}, {"source_code": "main :: IO()\nmain = print . solve . tail . map read . words =<< getContents\n\nsolve :: [Int] -> Int\nsolve a = solve' a 0 0\n\nsolve' :: [Int] -> Int -> Int -> Int\nsolve' [] _ c = c\nsolve' (a:ax) l c | a >= l = solve' ax a (c + 1)\n | otherwise = max c (solve' ax a 1)\n"}, {"source_code": "-- Snippet: partitionWith\npartitionWith1 eq (a1 : an)\n | not (null an) && eq a1 (head an) = (a1 : r, aLeft)\n | otherwise = ([a1], an)\n where (r, aLeft) = partitionWith1 eq an\n\npartitionWith eq a\n | null a = []\n | otherwise = r : partitionWith eq aLeft\n where (r, aLeft) = partitionWith1 eq a\n\n-- Snippet: readItems\nreadItems = do\n line <- getLine\n return $ map read $ words line\n\nmain = do\n n <- getLine\n a <- readItems :: IO [Int]\n putStrLn $ show $ maximum $ map length $ partitionWith (<=) a\n"}, {"source_code": "import Data.List\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n a <- fmap ((map read) . words) getLine :: IO [Int]\n let z = zip a (tail a)\n print $ 1 + (solve 0 0 z)\n\nsolve m c [] = max m c\nsolve m c ((a,b):l)\n |b>=a = solve m (c+1) l\n |otherwise = solve (max m c) 0 l"}, {"source_code": "solution :: [Int] -> Int -> Int\nsolution [x] m = m + 1\nsolution (x:xs) m\n | x <= head xs = solution xs (m+1)\n | otherwise = max (m+1) (solution xs 0)\n\nmain :: IO ()\nmain = do\n k <- getLine\n x <- getLine\n let args = map (\\x -> read x :: Int) $ words x\n print $ solution args 0"}, {"source_code": "main = do\n getLine\n as <- fmap (map read . words) getLine :: IO [Int]\n \n let\n f [a] = (1, 1)\n f (a:b:s) = (m1', m2')\n where\n (m1, m2) = f (b:s)\n m1' = if a <= b then m1+1 else 1\n m2' = max m2 m1'\n \n (_, m) = f as\n \n print m"}, {"source_code": "consume_positives [] = 0\nconsume_positives aa@(a:b)\n | a < 0 = consume_positives b\n | otherwise = max (length c1) (consume_positives c2)\n where (c1,c2) = break (<0) aa\n\n \nsolve a = 1 + consume_positives b\n where b = zipWith (-) (tail a) a\n\nmain = interact $ show . solve . map read . words . head . tail . lines\n"}, {"source_code": "import Debug.Trace (trace)\nimport Data.List (group)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\n{-\nmaxSub [] = 0\nmaxSub nums = maximum maxLengths\n where orders = zipWith (>=) nums (0:nums)\n grouped = group (trace (show orders) orders)\n onlyTrue = filter (all (== True)) grouped\n maxLengths = map length onlyTrue\n-}\n\n\nmaxSub :: [Integer] -> Integer\nmaxSub [] = 0\nmaxSub nums = max m c\n where (m, c, _) = foldl fn (0, 0, 0) nums\n\nfn (m, c, p) n = (m', c', n)\n where m' = if n < p then (max m c) else m\n c' = if n < p then 1 else c + 1\n\nmain = do\n contents <- C.getContents\n let numbers = (toInts . tail . C.words) contents\n print (maxSub numbers)\n where toInts = map (toInteger . fst . fromJust . C.readInt)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.Word(Word32)\nimport Data.List(foldl')\n\nread' = read . BS.unpack\n\nnumNonDec xs = result\n where\n loop (prev, n, final) x = n' `seq` max' `seq` comp' `seq` comp'\n where n' = n + 1\n max' = max n' final\n comp' = if x >= prev then (x, n', max n' final) else (x, 1, final)\n (_,_,result) = foldl' loop (0,0,0) xs\n\nmain :: IO ()\nmain = do\n _ <- BS.getLine\n ns' <- BS.getLine\n let ns = map (read') . BS.words $ ns' :: [Word32]\n print $ numNonDec ns\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\nimport Data.List\n\nmain = do { n <- getLine\n ; x <- getLine\n ; putStrLn $ (words >>> map read >>> solve >>> show) x \n }\n\ncount :: (Int,Integer,Int) -> Integer -> (Int,Integer,Int)\ncount (m,p,a) z = let b = if z >= p then a+1 else 1\n in (max m b, z, b)\n\nsolve :: [Integer] -> Int\nsolve x = let (n,_,_) = foldl count (0,1000000001,0) x\n in n"}, {"source_code": "answer::Int->[Int]->Int\nanswer n a = 1 + toNum (toBool n a)\nbton::Bool -> Int\nbton True = 1\nbton False = 0\ntoNum::[Bool] -> Int\ntoNum a = toNum0 0 a \ntoNum0::Int -> [Bool] -> Int\ntoNum0 n [] = 0 \ntoNum0 n a | head a = max (n+1) (toNum0 (n+1) (tail a))\n | otherwise = toNum0 0 (tail a) \ntoBool::Int -> [Int] -> [Bool]\ntoBool n a= toBool0 (head a) (tail a)\ntoBool0 preNum [] = [] \ntoBool0 preNum a = [preNum <= (head a)] ++ (toBool0 (head a) (tail a))\n--main = print $ answer 2 [2,1]\nmain = do\n w0 <-getLine\n let n = read w0::Int\n w1 <- getLine\n let a = [read n::Int | n <-(words w1)]\n print $ answer n a\n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve2.solve.map read.words.head.tail . lines\n--solve :: [String]->[Int]\nsolve2::[(Int,Int)]->Int\nsolve2 xs = maximum [x| (_,x)<-xs]\nsolve xs = foldr (f) [] xs --[2, 3,4,3,0, 5]\n where \n f a [] = [(a,1)]\n f a ((b1,b2):bs) = if b1>=a then (a,b2+1):bs else (a,1):((b1,b2):bs)"}, {"source_code": "import Data.List\nimport Data.Function\n\ngpBy :: [[Int]] -> [Int] -> [[Int]]\ngpBy [] (x:xs) = gpBy [[x]] xs\ngpBy acc [] = reverse acc\ngpBy (a:acc) [x] = gpBy (if x>= head a then ((x:a):acc) else [x]:(a:acc)) []\ngpBy (a:acc) (x:xs) = gpBy (if (x>=head a) then ((x:a):acc) else ([x]:a:acc)) xs \n\nmain = do \n getLine\n getLine >>= print . length . maximumBy (compare `on` length) . gpBy [] . map (\\x -> read x :: Int) . words \n"}, {"source_code": "main=interact$show.f 0 0 0.map read.tail.words\nf a b c []=max b c\nf a b c (d:e)=if a<=d then f d (b+1) c e else f d 1 (max b c) e"}, {"source_code": "-- Codeforces 580A\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . words\n\nsolve :: [Int] -> Int\nsolve (n:xs) = (\\(ans, _, _) -> ans) $ foldl (\\(ans, acc, prev) x -> if x >= prev then ((max ans (acc+1)), acc+1, x) else (ans, 1, x)) (0, 0, 0) xs\n"}, {"source_code": "main=interact$show.f 0 0 0.map read.tail.words\nf a b c []=max b c\nf a b c (d:e)=if a<=d then f d (b+1) c e else f d 1 (max b c) e"}, {"source_code": "import Control.Monad\nimport Data.Array\nimport Data.Char\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\ngetList :: Read a => IO [a]\ngetList = fmap (map (read . B.unpack) . B.words) B.getLine\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nincGroup :: Ord a => [a] -> [[a]]\nincGroup [] = [[]]\nincGroup [x] = [[x]]\nincGroup (x:t@(y:_)) = if x <= y then (x : hz) : tz else [x] : z\n where z@(hz:tz) = incGroup t\n\nsolve :: [Int] -> Int\nsolve = maximum . map length . incGroup\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n print $ solve a\n"}, {"source_code": "import Control.Applicative\nprocess [] cl ml _ = max ml cl\nprocess (hl:lis) cl ml le | hl>=le = process lis (cl+1) ml hl\n | otherwise = process lis 1 (max ml cl) hl\n\n\n\nmain=do\n getLine\n a<-(map read <$> words <$> getLine)::IO [Int]\n print $ process (tail a) 1 1 (head a)\n"}, {"source_code": "import Data.List (group)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Int] -> Int\nsolve xs = succ $ maximum $ (0:) $ map length $ filter head $ group $ zipWith (<=) xs (tail xs)\n"}, {"source_code": "main = interact $ show . maximum . solve 0 0 . map read . tail . words\nsolve a p (n:ns) | n >= p = solve (a+1) n ns\n | otherwise = a : solve 1 n ns\nsolve a _ _ = [a]\n"}, {"source_code": "import System.IO\nimport Control.Monad\nimport Data.List\n\nglwr = fmap (map read . words) getLine\n\nmain = do\n hSetBuffering stdout NoBuffering\n solve\n\nsolve :: IO ()\nsolve = do\n n:_ <- glwr\n ls <- glwr\n print $ nonDecProgress n ls\n\nnonDecProgress :: Int -> [Int] -> Int\nnonDecProgress n = fst . maximum . foldl nonDec [(0, 0)]\n\nnonDec x@((m, pre):z) y\n | y >= pre = (m+1, y):z\n | 0 < 1 = (1, y):x"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/580/A\n\nimport Data.List\nimport Data.Char\nimport qualified Data.ByteString.Char8 as B\n\ngetIntList :: IO [Int]\ngetIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine\n\nincGroup :: Ord a => [a] -> [[a]]\nincGroup [] = [[]]\nincGroup [x] = [[x]]\nincGroup (x:t@(y:_)) = if x <= y then (x : hz) : tz else [x] : z\n where z@(hz:tz) = incGroup t\n\nsolve :: [Int] -> Int\nsolve = maximum . map length . incGroup\n\nmain :: IO ()\nmain = do\n _ <- getLine\n a <- getIntList\n print $ solve a\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/contest/580/problem/A\n\nsolve :: [Int] -> Int -> Int\nsolve [x] m = m + 1\nsolve (x:xs) m\n | x <= head xs = solve xs (m+1)\n | otherwise = max (m+1) (solve xs 0)\n\nmain :: IO ()\nmain = do\n k <- getLine\n x <- getLine\n let args = map (\\x -> read x :: Int) $ words x\n print $ solve args 0\n"}, {"source_code": "import Data.Monoid\n\nmain = interact solve >> putChar '\\n'\n\nsolve :: String -> String\nsolve rawInput = show maxNonDecreasing\n where input = (map . map) read $ map words $ lines rawInput :: [[Int]]\n inData = last input\n calc (lastMoney, curStreak, maxStreak) x =\n if x >= lastMoney\n then (x, curStreak + 1, (max (curStreak + 1) maxStreak))\n else (x, 1, max curStreak maxStreak)\n (_, _, maxNonDecreasing) = foldl calc (-1, 0, 0) inData\n"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = do print . (solve 1) . (10^9 :) . tail =<< map (fst . fromJust . B.readInt) . B.words <$> B.getContents\nsolve :: Int -> [Int] -> Int\nsolve len (a:b:[]) = if b >= a then len + 1 else len\nsolve len (a:rest@(b:_)) | a > b = max len $ solve 1 rest\n | otherwise = solve (len + 1) rest\n"}, {"source_code": "ma m c l [] = m `max` c\nma m c l (x:xs) = if x >= l\n then ma (m `max` (c + 1)) (c + 1) x xs \n else ma m 1 x xs\n\nmain = do\n getLine\n t <- getLine\n let a = map (read::String -> Int) $ words t\n putStrLn $ show $ ma 0 0 0 a"}, {"source_code": "ma m c l [] = m `max` c\nma m c l (x:xs) = let t = if x >= l then c + 1 else 1 in ma (m `max` t) t x xs\n\nmain = do\n getLine\n t <- getLine\n let a = map (read::String -> Int) $ words t\n putStrLn $ show $ ma 0 0 0 a"}, {"source_code": "import qualified Data.List.Split as Split\n\nproblem n a =\n let merge_it (last_element, suffix, best_segment) x =\n if last_element <= x\n then (x, suffix + 1, best_segment)\n else (x, 1, max best_segment suffix)\n (_, suffix, best_segment) =\n foldl merge_it (0, 0, 0) a\n in\n show $ max suffix best_segment\n\nread_int = (read :: String -> Integer)\n\nparse_problem firstLine secondLine =\n let n = read_int firstLine in\n let splitted = Split.splitOn \" \" secondLine in\n let a = map read_int splitted in\n problem n a\n\nmain = do\n firstLine <- getLine\n secondLine <- getLine\n putStrLn $ parse_problem firstLine secondLine\n"}, {"source_code": "solve :: [Int] -> Int\nsolve s = maximum . scanl f 1 $ zipWith (<=) s (tail s)\n where f x y = 1 + x * (fromEnum y)\nmain = getLine >> getLine >>= putStrLn . show . solve . map read . words"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe (fromJust)\nsolve :: [Int] -> Int\nsolve s = maximum . scanl f 1 $ zipWith (<=) s (tail s)\n where f x y = 1 + x * (fromEnum y)\nmain = getLine >> B.getLine >>= putStrLn . show . solve . map (fst . fromJust . B.readInt) . B.words"}, {"source_code": "import Data.List\nimport Data.Char\nimport Control.Applicative\nimport Control.Monad\n\nmaxNotDecreasing :: [Integer] -> Integer\nmaxNotDecreasing nums@(n:ns) = \n maximum (scanl (\\n x -> if x then n + 1 else 0) 0 \n (map (uncurry (<=)) (zip nums ns))) + 1\n\ninputIntegerArray :: IO [Integer]\ninputIntegerArray = getLine >>= \n \\line -> return (map read $ words line)\n\nmain :: IO ()\nmain = getLine >> inputIntegerArray >>= putStrLn . show . maxNotDecreasing\n\n\n\n--rollDice :: StdGen -> ((Int, Int), StdGen)\n--rollDice gen = ((n,m),g2)\n-- where\n-- (n, g1) = randomR (1,6) gen\n-- (m, g2) = randomR (1,6) g1\n\n\n\n\n\n--\n--newtype State s a = State { runState :: s -> (a, s) }\n--\n--state :: (s -> (a, s)) -> State s a\n--state f = State { runState = f }\n--\n--instance Functor (State s) where\n-- fmap f (State {runState = run}) \n-- = State {runState = \\s -> (f (fst (run s)), snd (run s))}\n--\n--instance Applicative (State s) where\n-- pure a = State {runState = \\s -> (a, s)}\n-- --runState (s -> ((a -> b), s)) s -> (a, s) s -> (b, s)\n-- (State {runState = runF}) <*> (State {runState = run}) = (State {runState --= \\s -> ((fst (runF s)) (fst (run s)), s)})\n-- \n--(>>=) :: State s a -> (a -> State s b) -> State s b\n--p >>= k = q where\n-- p' = runState p -- p' :: s -> (a, s)\n-- k' = runState . k -- k' :: a -> s -> (b, s)\n-- q' s0 = (y, s2) where -- q' :: s -> (b, s)\n-- (x, s1) = p' s0 -- (x, s1) :: (a, s)\n-- (y, s2) = k' x s1 -- (y, s2) :: (b, s)\n-- q = state q'\n\n--main :: IO ()\n--main = rollDiceIO >>= print\n"}, {"source_code": "import Data.List\n\nmaxNotDecreasing :: [Integer] -> Integer\nmaxNotDecreasing nums@(n:ns) = \n maximum (scanl (\\n x -> if x then n + 1 else 0) 0 \n (map (uncurry (<=)) (zip nums ns))) + 1\n\ninputIntegerArray :: IO [Integer]\ninputIntegerArray = getLine >>= \n \\line -> return (map read $ words line)\n\nmain :: IO ()\nmain = getLine >> inputIntegerArray >>= putStrLn . show . maxNotDecreasing\n\n--import Data.Char\n--import Control.Applicative\n--import Control.Monad\n--import System.Random\n\n--rollDice :: StdGen -> ((Int, Int), StdGen)\n--rollDice gen = ((n,m),g2)\n-- where\n-- (n, g1) = randomR (1,6) gen\n-- (m, g2) = randomR (1,6) g1\n\n\n\n\n\n--\n--newtype State s a = State { runState :: s -> (a, s) }\n--\n--state :: (s -> (a, s)) -> State s a\n--state f = State { runState = f }\n--\n--instance Functor (State s) where\n-- fmap f (State {runState = run}) \n-- = State {runState = \\s -> (f (fst (run s)), snd (run s))}\n--\n--instance Applicative (State s) where\n-- pure a = State {runState = \\s -> (a, s)}\n-- --runState (s -> ((a -> b), s)) s -> (a, s) s -> (b, s)\n-- (State {runState = runF}) <*> (State {runState = run}) = (State {runState --= \\s -> ((fst (runF s)) (fst (run s)), s)})\n-- \n--(>>=) :: State s a -> (a -> State s b) -> State s b\n--p >>= k = q where\n-- p' = runState p -- p' :: s -> (a, s)\n-- k' = runState . k -- k' :: a -> s -> (b, s)\n-- q' s0 = (y, s2) where -- q' :: s -> (b, s)\n-- (x, s1) = p' s0 -- (x, s1) :: (a, s)\n-- (y, s2) = k' x s1 -- (y, s2) :: (b, s)\n-- q = state q'\n\n--main :: IO ()\n--main = rollDiceIO >>= print\n"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Data.Maybe\n\n \nprocess [] _ n mn= max mn n\nprocess (x:xs) a n mn | x>=a = process xs x (n+1) mn\n | otherwise = process xs x 1 (max mn n)\n\n \nmain= do\n\tgetLine \n\tx<- map read. words <$> getLine ::IO [Int]\n\tprint $ process (tail x) (head x) 1 1\n\n\t \n\t \n\t \n"}, {"source_code": "{-\nCodeforces Round #321 (Div. 2)\n\nProblem 580 A. Kefa and First Steps\n\n@author yamaton\n@date 2015-09-22\n-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Text.Printf\nimport System.IO (hPutStrLn, stderr)\n\nimport Data.Ord (comparing)\nimport Data.Function (on)\nimport Data.List (maximumBy)\n-- import qualified Data.Map as Map\n-- import qualified Data.Set as Set\n-- import qualified Data.Foldable as F\n-- import qualified Data.Traversable as T\n\n-- lndcs : Longest Non-decreasing consecutive sequence\nlndcs :: [Int] -> Int\nlndcs xs = maximum $ scanl f 1 neighbors\n where\n f :: Int -> (Int, Int) -> Int\n f acc (a, b) | a <= b = acc + 1\n | otherwise = 1\n neighbors = zip xs (tail xs)\n\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine :: IO Int\n xs <- (map read . words) <$> getLine :: IO [Int]\n -- ys <- replicateM n getLine\n let result = lndcs xs\n print result\n -- print (length result)\n --\n -- hPutStrLn stderr $ printf \"xs = %s\" (show xs)\n -- hPutStrLn stderr $ printf \"result = %d\" result\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\nimport Data.Foldable (maximum)\n\n\nsolve :: Int -> Array Int Integer -> Integer\nsolve n nums = Data.Foldable.maximum pd\n where -- pd :: Array Int Integer\n pd = listArray (0, n-1) $ work <$> [0..n-1]\n work 0 = 1\n work i = if (nums ! i) >= (nums ! (i-1))\n then (pd ! (i-1)) + 1\n else 1\n\nmain = do\n n <- read <$> getLine\n nums <- map read . words <$> getLine\n --print nums\n print $ solve n $ listArray (0,n-1) nums\n"}, {"source_code": "import Data.List\nunfolder :: [Int] -> Maybe (Bool, [Int])\nunfolder [] = Nothing\nunfolder [a] = Nothing\nunfolder [a, b] = Just (a <= b, [b])\nunfolder (a:b:rest) = Just (a <= b, b:rest)\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n print =<< maximum . (1:) . map ((1+) . length) . filter or . group . unfoldr unfolder . map (read :: String -> Int) . words <$> getLine"}, {"source_code": "import Data.List\nunfolder :: [Int] -> Maybe (Bool, [Int])\nunfolder (a:b:as) = Just (a <= b, b:as)\nunfolder _ = Nothing\n\nmain :: IO ()\nmain = do\n n <- (read :: String -> Int) <$> getLine \n print =<< maximum . (1:) . map ((1+) . length) . filter or . group . unfoldr unfolder . map (read :: String -> Int) . words <$> getLine"}, {"source_code": "module Main where\n\nimport Data.Functor\n\nsubsequence :: [Int] -> [[Int]]\nsubsequence [] = []\nsubsequence [x] = [[x]]\nsubsequence (x:xs)\n | x <= y = (x:yss):zs\n | otherwise = [x]:zss\n where zss@(yss@(y:_):zs) = subsequence xs\n\nmain :: IO ()\nmain = do\n a <- map (read::String->Int) . words . last . lines <$> getContents\n let ans = maximum . map length . subsequence $ a\n {-print a-}\n print ans\n\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Map\nimport Control.Monad.State\n\n--2 2 1 3 cutted 2 2 1 1 1<3 -> 1 + answer 221\nanswer :: [Integer] ->Integer->[Integer]\nanswer [_] n = [n]\nanswer (x:y:xs) n | x <= y = answer (y:xs) (n +1)\n | otherwise = n : answer (y:xs) 1\n \nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= (\\l -> let numbers = read <$> words l in print $ maximum $ answer numbers 1 )\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "\nreadInt :: String -> Int\nreadInt = read\n\nincSeg :: [Int] -> [[Int]]\nincSeg [] = [[]]\nincSeg (x:xs) = \n if (null a || (head a >= x)) \n then (x:a):rs\n else [x]:a:rs\n where (a:rs) = incSeg xs\n \n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- (fmap (map readInt . words) getLine)\n print $ maximum $ map length $ incSeg xs \n return ()\n"}, {"source_code": "type Input = [Int]\n\nparse :: String -> Input\nparse = map read . words . (!! 1) . lines\n\nsolve :: Input -> Int\nsolve = snd . go\n where go [] = undefined\n go [_] = (1, 1)\n go (x : xs) = let (l, m) = go xs\n y = head xs in\n if x <= y\n then let l' = l + 1 in (l', max m l')\n else (1, m)\n\nmain :: IO ()\nmain = print . solve . parse =<< getContents\n"}, {"source_code": "groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\ngroupBy rel [] = []\ngroupBy rel (x:xs) = (x:ys) : groupBy rel zs\n where (ys,zs) = groupByAux x xs\n groupByAux x0 (x:xs) | rel x0 x = (x:ys, zs)\n where (ys,zs) = groupByAux x xs\n groupByAux y xs = ([], xs)\n\nprocess :: [Int] -> Int\nprocess = maximum.map length.groupBy (<=)\n \nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- fmap readInt getLine\n as <- fmap (map readInt.words) getLine\n print $ process as"}, {"source_code": "import System.IO\n\nread_ints :: String -> [Int]\nread_ints ln = map read (words ln) :: [Int]\n\nsolve :: [Int] -> [Int]\nsolve [] = []\nsolve (x:[]) = [1]\nsolve (x:xs) = if x < head xs then [1] ++ solve xs\n else\n [head y+1] ++ y\n where y = solve xs\nsolve2 :: [Int] -> Int\nsolve2 xs = maximum $ solve xs\n\nmain = do\n ln <- getLine\n let [n] = read_ints ln\n ln <- getLine\n let arr = read_ints ln\n let rev = reverse arr\n print $ solve2 rev"}, {"source_code": "module Main where\n\n-- import Data.List.GroupBy\n\nmain :: IO ()\nmain = interact $ show . f . map read . tail . words\n\nf :: [Integer] -> Int\nf = maximum . map length . groupBy (<=)\n\ngroupBy :: (a -> a -> Bool) -> [a] -> [[a]]\ngroupBy _ [] = []\ngroupBy p' (x':xs') = (x' : ys') : zs'\n where\n (ys',zs') = go p' x' xs'\n go p z (x:xs)\n | p z x = (x : ys, zs)\n | otherwise = ([], (x : ys) : zs)\n where (ys,zs) = go p x xs\n go _ _ [] = ([], [])\n"}, {"source_code": "import Data.Int\n\nmaxlength :: [Int64] -> Int\nmaxlength xs = \n let (l, _, _) = foldl f (0, 0, 0) xs\n in l\n\nf :: (Int, Int, Int64) -> Int64 -> (Int, Int, Int64)\nf (mlen, clen, cval) x\n | x >= cval = (max (clen + 1) mlen, clen + 1, x)\n | otherwise = (mlen, 1, x)\n\nsolve :: String -> String\nsolve = show.maxlength.fmap read.tail.words \n\nmain :: IO ()\nmain = interact solve"}, {"source_code": "import Data.ByteString.Builder\nimport qualified Data.ByteString.Lazy.Char8 as BS\nimport Data.Int\nimport Data.Maybe\n\nmaxNonDecreasingLength :: [Integer] -> Int\nmaxNonDecreasingLength xs =\n let (l, _, _) = foldl f (0, 0, 0) xs\n in l\n\nf :: (Int, Int, Integer) -> Integer -> (Int, Int, Integer)\nf (answer, candidate, cval) x\n | x >= cval = (max (candidate + 1) answer, candidate + 1, x)\n | otherwise = (answer, 1, x)\n\nsolve :: BS.ByteString -> BS.ByteString\nsolve = toLazyByteString . intDec . maxNonDecreasingLength . fmap (fst . fromJust . BS.readInteger) . tail . BS.words\n\nmain :: IO ()\nmain = BS.interact solve\n"}, {"source_code": "main = interact $ show . foo 0 0 . tail . map read . words\n\nfoo :: Int -> Int -> [Int] -> Int\nfoo a b [x] = max a (b + 1)\nfoo a b (x:xs)\n |x <= head xs = foo a (b + 1) xs\n |otherwise = foo (max a (b + 1)) 0 xs\n"}, {"source_code": "main = interact $ show . f . map read . words\n\nf :: [Int] -> Int\nf (_:l) = foo 0 0 l\n\nfoo :: Int -> Int -> [Int] -> Int\nfoo a _ [] = a\nfoo a b [x] = max a (b + 1)\nfoo a b (x:xs)\n |x <= head xs = foo a (b + 1) xs\n |a < b + 1 = foo (b + 1) 0 xs\n |otherwise = foo a 0 xs\n"}, {"source_code": "import Data.List\nf as = let bs = scanl (\\s x -> if fst s<=x then(x,snd s+1) else(x,1)) (0,0) as\n in maximum.map snd $ bs\nmain = interact $ show.f.map read.tail.words\n"}], "negative_code": [{"source_code": "import Data.List\n\nparse :: String -> Int\nparse x = read x :: Int\n\ncomb :: (Int,Int,Int) -> Int -> (Int,Int,Int)\ncomb (ans, stride, last) cur \n | cur < last = (max ans stride, 1, cur)\n | otherwise = (max ans stride+1, stride+1, cur)\n\ngetans (ans, _, _) = ans\n\nsolve :: [Int] -> Int\nsolve xs = getans (foldl comb (0,0,-1) xs)\n\nrun :: String -> String\nrun xs = show $ solve $ map parse $ tail $ words xs\n\n\nmain = interact run"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Text.Printf\n\nreadInt = ( readLn :: IO Int )\nreadInts = map ( read :: String -> Int ) . words <$> getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\tn <- readInt\n\t(a:as) <- readInts\n\n\tprint $ succ $ maximum $ map length $ group $ conv a as\n\nconv _ [] = [ -1 ]\nconv p (a:as)\n\t| p <= a = 1 : conv a as\n\t| otherwise = 0 : conv a as\n"}, {"source_code": "import Data.List (group)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe (fromJust)\n\nmaxSub [] = 0\nmaxSub nums = maximum maxLengths\n where orders = zipWith (>=) nums (0:nums)\n grouped = group orders\n onlyTrue = filter (all (== True)) grouped\n maxLengths = map length onlyTrue\n\nmain = do\n contents <- C.getContents\n let numbers = (toInts . tail . C.words) contents\n print (maxSub numbers)\n where toInts = map (toInteger . fst . fromJust . C.readInt)\n"}, {"source_code": "{-# LANGUAGE BlockArguments #-}\n\nimport Control.Arrow\nimport Data.List\n\nmain = do { n <- getLine\n ; x <- getLine\n ; putStrLn $ (words >>> map read >>> solve >>> show) x \n }\n\ncount :: (Int,Integer,Int) -> Integer -> (Int,Integer,Int)\ncount (m,p,a) z | z >= p = (max m (a+1), z, a+1)\n | otherwise = (m, z, 1)\n\nsolve :: [Integer] -> Int\nsolve x = let (n,_,_) = foldl count (0,1000000001,0) x\n in n"}, {"source_code": "import Data.List\nimport Data.Maybe\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ show.solve2.solve .words.head.tail . lines\n--solve :: [String]->[Int]\nsolve2 xs = maximum [x| (_,x)<-xs]\nsolve xs = foldr (f) [] xs --[2, 3,4,3,0, 5]\n where \n f a [] = [(a,1)]\n f a ((b1,b2):bs) = if b1>=a then (a,b2+1):bs else (a,1):((b1,b2):bs)"}, {"source_code": "import Data.List\nimport Data.Function\n\ngpBy :: [[Int]] -> [Int] -> [[Int]]\ngpBy [] (x:xs) = gpBy [[x]] xs\ngpBy acc [] = reverse acc\ngpBy (a:acc) [x] = gpBy (if x>= head a then ((x:a):acc) else [x]:(a:acc)) []\ngpBy (a:acc) (x:xs) = gpBy (if (x>=head a) then ((x:a):acc) else ([x]:a:acc)) xs \n\nmain = do \n getLine\n getLine >>= print . length . maximumBy (compare `on` sum) . gpBy [] . map (\\x -> read x :: Int) . words \n"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = do \n getLine\n getLine >>= print . length . maximumBy (compare `on` sum) . (groupBy $ \\x y->x read x :: Int) . words \n"}, {"source_code": "main=interact$show.f 0 (-1) 0.map read.tail.words\nf a b c []=max b c\nf a b c (d:e)=if a<=d then f d (b+1) c e else f d 1 (max b c) e"}, {"source_code": "import Control.Applicative\nprocess [] _ ml _ = ml\nprocess (hl:lis) cl ml le | hl<=le = process lis (cl+1) ml hl\n | otherwise = process lis 1 (max ml cl) hl\n\n\n\nmain=do\n getLine\n a<-(map read <$> words <$> getLine)::IO [Int]\n print $ process (tail a) 1 1 (head a)\n"}, {"source_code": "import Control.Applicative\nprocess [] _ ml _ = ml\nprocess (hl:lis) cl ml le | hl>=le = process lis (cl+1) ml hl\n | otherwise = process lis 1 (max ml cl) hl\n\n\n\nmain=do\n getLine\n a<-(map read <$> words <$> getLine)::IO [Int]\n print $ process (tail a) 1 1 (head a)\n"}, {"source_code": "import Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmain = do print . (solve 1) =<< map (fst . fromJust . B.readInt) . B.words <$> B.getContents\nsolve :: Int -> [Int] -> Int\nsolve len (a:b:[]) = if b >= a then len + 1 else len\nsolve len (a:rest@(b:_)) | a > b = max len $ solve 1 rest\n | otherwise = solve (len + 1) rest\n"}, {"source_code": "import Data.List\nsolve :: [Int] -> Int\nsolve = maximum . map length . groupBy (<)\nmain = interact $ show . solve . map read . tail . words\n"}, {"source_code": "import Data.List\nsolve :: [Int] -> Int\nsolve = maximum . map length . groupBy (<=)\nmain = interact $ show . solve . map read . tail . words\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Map\nimport Control.Monad.State\n\n--2 2 1 3 cutted 2 2 1 1 1<3 -> 1 + answer 221\nanswer :: [Integer] ->Integer->[Integer]\nanswer [_] n = [n]\nanswer (x:y:xs) n | x <= y = answer (y:xs) (n +1)\n | otherwise = n : answer (y:xs) 1\n \nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= (\\l -> let numbers = read <$> words l in print $ answer numbers 1 )\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Map\nimport Control.Monad.State\n\n\n\nanswer :: [Integer] -> Integer\nanswer [_] = 1\nanswer xs | last cutted < last xs = answer cutted + 1\n | otherwise = answer cutted where cutted = init xs\n \nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= (\\l -> let numbers = read <$> words l in print $ answer numbers)\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Map\nimport Control.Monad.State\n\n\n\nanswer :: [Integer] -> Integer\nanswer [_] = 1\nanswer xs | last cutted <= last xs = answer cutted + 1\n | otherwise = answer cutted where cutted = init xs\n \nsomeFunc :: IO ()\nsomeFunc = getLine >> getLine >>= (\\l -> let numbers = read <$> words l in print $ answer numbers)\n\nmain :: IO ()\nmain = someFunc\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain :: IO ()\nmain = interact $ show . f . map read . tail . words\n\nf :: [Integer] -> Int\nf = maximum . map length . groupBy (<=)\n"}], "src_uid": "1312b680d43febdc7898ffb0753a9950"} {"source_code": "import Control.Monad\nimport Data.List\n\nscaninput:: Int -> IO [[Int]]\nscaninput x = forM [1..x] (\\y -> do\n xs <-(fmap ((map read).words) getLine)\n return (y:xs))\nmain::IO () \nmain = do\n n <- fmap read getLine\n comps <- scaninput n\n filtered <- return $ filter (\\x -> not $ any (\\y -> ((x !! 1) \n < (y !! 1)) && ((x !! 2) < (y !! 2))\n && ((x !! 3) < (y !! 3))) comps) comps \n putStrLn $ show $ head.head $ sortBy (\\xs ys -> compare (xs !! 4) \n (ys !! 4)) filtered", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine\n comps <- forM [1..n] $ \\i -> do\n [a, b, c, cost] <- ( map read . words ) `liftM` getLine :: IO [Int]\n return (i, a, b, c, cost)\n\n let considered = filter (\\(_, a, b, c, _) -> not $ any (\\(_, a2, b2, c2, _) -> a < a2 && b < b2 && c < c2) comps) comps\n choose = foldl' (\\best@(_, _, _, _, best_cost) this@(_, _, _, _, cost) ->\n if cost < best_cost\n then this\n else best\n ) (0, 0, 0, 0, maxBound) considered\n (chooseI, _, _, _, _) = choose\n\n --putStrLn $ show considered\n --putStrLn $ show choose\n putStrLn $ show chooseI\n"}, {"source_code": "import Data.List\n\ngetLines :: Int -> IO [[Int]]\ngetLines 0 = return []\ngetLines n = do x <- getLine >>= return . map read . words; xs <- getLines (n-1); return (x:xs)\n\nok :: [[Int]] -> [Int] -> Bool\nok x (ya:yb:yc:_) = find (\\(za:zb:zc:_) -> ya < za && yb < zb && yc < zc) x == Nothing\n\nmain = do\n\tn <- getLine >>= return . read :: IO Int\n\tspec <- getLines n\n\tputStrLn . show . fst $ foldl (\\(a, b) (c, d) -> if b < d then (a, b) else (c, d)) (-1, 9999) [( i + 1, spec !! i !! 3) | i <- [0..n-1], ok spec (spec !! i)]\n"}, {"source_code": "{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Debug.Trace (trace)\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nreadNum = fst . fromJust . BS.readInt\n--- debug = flip trace\ndebug x = trace (show x) x\ndebug2 msg x = trace (printf \"%s: %s\" msg $ show x) x\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nolder (_:xs) (_:ys) = and $ zipWith (<) xs' ys'\n where\n xs' = take 3 xs\n ys' = take 3 ys\n\nobsolete yss xs = or [older xs ys | ys <- yss]\n\ncost xs = last xs\n\nsolve xss = head $ minimumBy (comparing cost) xss'\n where xss' = filter (not . obsolete xss) xss\n\nbody [] = []\nbody (n:xs) = solve yss : body xs'\n where\n (ys', xs') = splitAt (n*4) xs\n yss = zipWith (:) [1..] $ splitEvery 4 ys'\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n let xs = map readNum ws\n mapM_ print $ body xs\n"}, {"source_code": "type NoteBook = (Int, Int, Int, Int)\n\nparseNoteBook :: String -> NoteBook\nparseNoteBook s = (x1, x2, x3, x4)\n where\n [x1, x2, x3, x4] = map read (words s)\n\nreadNoteBook :: IO NoteBook\nreadNoteBook = getLine >>= return . parseNoteBook\n\noldest :: NoteBook -> NoteBook -> Bool\noldest (a1, b1, c1, _) (a2, b2, c2, _)\n = a1 < a2 && b1 < b2 && c1 < c2\n\nsolve :: [NoteBook] -> [(Int, NoteBook)]\nsolve ns = solve_ 1 ns ns\n where\n solve_ :: Int -> [NoteBook] -> [NoteBook] -> [(Int, NoteBook)]\n solve_ _ [] _ = []\n solve_ i (n:ns) allNs\n | any (oldest n) allNs = solveNS\n | otherwise = (i, n):solveNS\n where\n solveNS = solve_ (i+1) ns allNs\n\ngetAns :: [(Int, NoteBook)] -> Int\ngetAns ((num, (_, _, _, c)):ns) = fst (getAns_ (num, c) ns)\n where\n getAns_ :: (Int, Int) -> [(Int, NoteBook)] -> (Int, Int)\n getAns_ mn [] = mn\n getAns_ (numMin, cMin) ((num, (_, _, _, c)):ns)\n | cMin > c = getAns_ (num, c) ns\n | otherwise = getAns_ (numMin, cMin) ns\n\nmain = do\n n <- readLn::(IO Int)\n ns <- sequence (replicate n readNoteBook)\n print (getAns (solve ns))\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\nmain = do\n n <- readLn\n ls <- replicateM n $ liftM (map (read :: String -> Int) . words) getLine\n let ls' = filter (upToDate ls) $ zip [1..] ls\n print $ fst $ minimumBy (comparing ((!!3) . snd)) ls'\nupToDate ls (_,(s0:r0:h0:_)) = all (\\(s:r:h:_) -> s0 >= s ||\n r0 >= r ||\n h0 >= h) ls"}, {"source_code": "import List\n\nclass Scan_ a where scan_ :: String -> a\ninstance Scan_ Char where scan_ (x:_) = x\nclass Scan a where scan :: String -> a\ninstance Scan Int where scan n = read n\ninstance Scan Char where scan (x:_) = x\ninstance Scan Float where scan f = read f\ninstance Scan Double where scan d = read d\ninstance Scan Integer where scan n = read n\ninstance (Scan_ a) => Scan [a] where\n scan (x:xs) = (scan_ [x]):(scan xs)\n scan [] = []\nclass Ans_ a where showans_ :: a -> String\ninstance Ans_ Char where showans_ x = [x]\nclass Ans a where showans :: a -> String\ninstance Ans Int where showans x = show x\ninstance Ans Char where showans x = [x]\ninstance Ans Float where showans x = show x\ninstance Ans Double where showans x = show x\ninstance Ans Integer where showans x = show x\ninstance (Ans_ a) => Ans [a] where\n showans (x:xs) = (showans_ x) ++ (showans xs)\n showans [] = []\ninstance (Ans a, Ans b) => Ans (a,b) where\n showans (x,y) = showans x ++ \" \" ++ showans y\ninstance (Ans a, Ans b,Ans c) => Ans (a,b,c) where\n showans (x,y,z) = showans x ++ \" \" ++ showans y ++ \" \" ++ showans z\n\nscanValue :: (Scan a) => IO a\nscanValue = do n <- getLine\n return (scan n)\n\nscanPair :: (Scan a, Scan b) => IO (a, b)\nscanPair = do ns <- getLine\n return (make_pair [n|n<-(words ns)])\n where\n make_pair (x:y:_) = (scan x,scan y)\n make_pair _ = error \"Not Pair\"\n\nscanTriple :: (Scan a, Scan b, Scan c) => IO (a, b, c)\nscanTriple = do ns <- getLine\n return (maketriple [n|n<-(words ns)])\n where\n maketriple (x:y:z:_) = (scan x,scan y,scan z)\n\nscanQuatro :: (Scan a, Scan b, Scan c, Scan d) => IO (a, b, c, d)\nscanQuatro = do ns <- getLine\n return (makequatro [n|n<-(words ns)])\n where\n makequatro (x:y:z:w:_) = (scan x,scan y,scan z,scan w)\n\nscans :: Int -> IO a -> IO [a]\nscans 0 _ = return []\nscans n io = do x <- io\n xs <- scans (n-1) io\n return (x:xs)\n\nputAnsLn :: (Ans a) => a -> IO ()\nputAnsLn ans = putStrLn (showans ans)\n\nputAnsLns :: (Ans a) => [a] -> IO ()\nputAnsLns (x:xs) = do putAnsLn x\n putAnsLns xs\nputAnsLns [] = return ()\n\nputDebugLn :: (Show a) => a -> IO ()\nputDebugLn ans = putStrLn (show ans)\n\nlesser ((_,a,b,c),_) ((_,d,e,f),_) = a lesser l x) ls\n\ndeleteOutdated (x:xs) rest laptops = if isOutdated x laptops then\n deleteOutdated xs rest laptops\n else\n deleteOutdated xs (x:rest) laptops\ndeleteOutdated [] rest _ = rest\n\nsolve n laptops_ = snd (head (sort (deleteOutdated laptops [] laptops) ))\n where\n laptops = (zip laptops_ [1..n])\n\nmain = do n <- scanValue::IO Int\n laptops <- scans n (scanQuatro :: IO (Int, Int, Int ,Int))\n putAnsLn (solve n (map (\\(a,b,c,d) -> (d,a,b,c)) laptops))"}], "negative_code": [{"source_code": "{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\n\nreadNum = fst . fromJust . BS.readInt\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs \n \nolder (_:xs) (_:ys) = or [and $ zipWith (<) xs' ys' | (xs', ys') <- zip xss yss]\n where\n -- threes\n xss = [l ++ tail r | i <- [0..3], let (l, r) = splitAt i xs]\n yss = [l ++ tail r | i <- [0..3], let (l, r) = splitAt i ys]\n\nobsolete yss xs = or [older xs ys | ys <- yss]\n\ncost xs = xs!!3\n\nsolve xss = head $ minimumBy (comparing cost) xss'\n where xss' = filter (not . obsolete xss) xss\n\nbody [] = []\nbody (n:xs) = solve yss : body xs'\n where\n (ys', xs') = splitAt (n*4) xs\n yss = zipWith (:) [1..] $ splitEvery 4 ys'\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n let xs = map readNum ws\n mapM_ print $ body xs \n"}, {"source_code": "{-(c) gorlum0 [at] gmail.com-}\nimport qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Debug.Trace (trace)\nimport Data.Ord (comparing)\nimport Data.Maybe (fromJust)\nimport Text.Printf (printf)\n\nreadNum = fst . fromJust . BS.readInt\n--- debug = flip trace\ndebug x = trace (show x) x\ndebug2 msg x = trace (printf \"%s: %s\" msg $ show x) x\n\nsplitEvery _ [] = []\nsplitEvery n xs = ys : splitEvery n xs'\n where (ys, xs') = splitAt n xs\n\nolder (_:xs) (_:ys) = and $ zipWith (<) xs' ys'\n where\n xs' = take 3 xs\n ys' = take 3 ys\n\nobsolete yss xs = or [older xs ys | ys <- yss]\n\ncost xs = xs!!3\n\nsolve xss = head $ minimumBy (comparing cost) xss'\n where xss' = filter (not . obsolete xss) xss\n\nbody [] = []\nbody (n:xs) = solve yss : body xs'\n where\n (ys', xs') = splitAt (n*4) xs\n yss = zipWith (:) [1..] $ splitEvery 4 ys'\n\nmain = do\n ws <- BS.words `fmap` BS.getContents\n let xs = map readNum ws\n mapM_ print $ body xs\n"}], "src_uid": "e12d86f0c8645424b942d3dd9038e04d"} {"source_code": "f :: Int -> Int -> [Int] -> Int\nf a b [ta, fa, tb, fb] | (fa < a) && (fb < a) && (ta != tb) = 2 * a - fa - fb + d\n | (fa > b) && (fb > b) && (ta != tb) = fa + fb - 2 * b + d\n | (ta != tb) = abs (fa - fb) + d\n | otherwise = abs (fa - fb) + d\n where d = abs (ta - tb)\n (!=) = (/=)\n\nmain = do\n [n, h, a, b, k] <- (map read.words) `fmap` getLine\n ways <- mapM (\\_ -> ((map read.words) `fmap` getLine)) [1..k]\n let ans = map (f a b) ways\n mapM_ (\\x -> putStrLn . show $ x) ans\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Functor ((<$>))\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\ndist :: Int -> Int -> Int -> Int -> Int -> Int -> Int\ndist a b ta fa tb fb = horzDist + vertDist\n where\n vertDist\n | ta == tb = abs $ fa - fb\n | fa < a = a - fa + (abs $ a - fb)\n | fa > b = fa - b + (abs $ b - fb)\n | otherwise = abs $ fa - fb\n horzDist = abs $ ta - tb\n\nmain :: IO ()\nmain = do\n [n, h, a, b, k] <- getLineInts\n replicateM_ k $ do\n [ta, fa, tb, fb] <- getLineInts\n print $ dist a b ta fa tb fb\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Functor ((<$>))\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\ndist :: Int -> Int -> Int -> Int -> Int -> Int -> Int\ndist a b ta fa tb fb = horzDist + vertDist\n where\n vertDist\n | ta == tb && fa == fb = 0\n | fa < a = a - fa + (abs $ a - fb)\n | fa > b = fa - b + (abs $ b - fb)\n | otherwise = abs fa - fb\n horzDist = abs $ ta - tb\n\nmain :: IO ()\nmain = do\n [n, h, a, b, k] <- getLineInts\n replicateM_ k $ do\n [ta, fa, tb, fb] <- getLineInts\n print $ dist a b ta fa tb fb\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Functor ((<$>))\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\ndist :: Int -> Int -> Int -> Int -> Int -> Int -> Int\ndist a b ta fa tb fb = horzDist + vertDist\n where\n vertDist\n | ta == tb && fa == fb = 0\n | fa < a = a - fa + (abs $ a - fb)\n | fa > b = fa - b + (abs $ b - fb)\n | otherwise = abs $ fa - fb\n horzDist = abs $ ta - tb\n\nmain :: IO ()\nmain = do\n [n, h, a, b, k] <- getLineInts\n replicateM_ k $ do\n [ta, fa, tb, fb] <- getLineInts\n print $ dist a b ta fa tb fb\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Functor ((<$>))\n\ngetLineInts :: IO [Int]\ngetLineInts = fmap read <$> words <$> getLine\n\ndist :: Int -> Int -> Int -> Int -> Int -> Int -> Int\ndist a b ta fa tb fb\n | fa < a = a - fa + horDist + (abs $ a - fb)\n | fa > b = fa - b + horDist + (abs $ b - fb)\n | otherwise = horDist + (abs $ fa - fb)\n where\n horDist = abs $ ta - tb\n\nmain :: IO ()\nmain = do\n [n, h, a, b, k] <- getLineInts\n replicateM_ k $ do\n [ta, fa, tb, fb] <- getLineInts\n print $ dist a b ta fa tb fb\n"}], "src_uid": "bdce4761496c88a3de00aa863ba7308d"} {"source_code": "-- Codeforces 12C\n-- Compute the maximum price and minimum price\nimport qualified Data.Map as Map\nimport Data.List\n\ncountOccurences :: [String] -> [Int]\ncountOccurences fruits = occurences\n where pair = zip fruits (take (length fruits) (repeat 1))\n counter = Map.fromListWith (+) pair :: Map.Map String Int\n list = Map.toList counter :: [(String, Int)]\n occurences = map snd list\n\ncomputeMax :: [Int] -> [Int] -> Int\ncomputeMax prices occurences = sum (zipWith (*) orderedPrices orderedOccurences)\n where orderedPrices = sortBy (flip compare) prices\n orderedOccurences = sortBy (flip compare) occurences\n\ncomputeMin :: [Int] -> [Int] -> Int\ncomputeMin prices occurences = sum (zipWith (*) orderedPrices orderedOccurences)\n where orderedPrices = sort prices\n orderedOccurences = sortBy (flip compare) occurences\n\nmain :: IO ()\nmain = do\n input <- getLine\n let counter = read ((words input) !! 1) :: Int\n priceStr <- getLine\n let prices = map (read :: String -> Int) (words priceStr)\n objectStr <- getContents\n let objects = take counter (lines objectStr)\n let occurences = countOccurences objects\n let min = computeMin prices occurences\n let max = computeMax prices occurences\n putStrLn $ id ((show min) ++ \" \" ++ (show max))\n", "positive_code": [{"source_code": "import Data.List (sort, group)\nimport Text.Printf (printf)\n\nmain = do\n dummy <- getLine\n line <- getLine\n contents <- getContents\n uncurry (printf \"%d %d\\n\") $ gao (map read $ words line) (lines contents)\n\ngao x y = (gao' x1 yy, gao' x2 yy) where\n x1 = sort x\n x2 = reverse x1\n yy = reverse $ sort $ map length $ group $ sort y\n gao' x' y' = sum $ zipWith (*) x' y'\n"}, {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.List (sort)\nimport Data.Map (elems, fromListWith)\n\ngetCounts :: [String] -> [Int]\ngetCounts lines = reverse $ sort $ elems $ fromListWith (+) $ zip lines [1,1..]\n\nsolve :: [Int] -> [String] -> (Int, Int)\nsolve as lines = (sum $ zipWith (*) (sort as) $ getCounts lines,\n sum $ zipWith (*) (reverse $ sort as) $ getCounts lines)\n\nmain :: IO ()\nmain = do\n [n, m] <- liftM (map read . words) getLine\n xs <- liftM (map read . words) getLine\n lines' <- replicateM m getLine\n let (a, b) = solve xs lines'\n putStrLn $ concat [show a, \" \", show b]\n"}, {"source_code": "import qualified Data.List as L\nimport qualified Data.Function as F\n\nparse :: [String] -> ([Int], [Int])\nparse (_:h:foo) = \n (L.sort . map read . words $ h, L.sort . map length . L.group . L.sort $ foo)\n\nsolve :: ([Int], [Int]) -> String\nsolve (prices, amounts) = \n -- unwords [show prices, show amounts]\n show minimize ++ \" \" ++ show maximize\n where \n minimize = sum [x * y | (x, y) <- zip prices (reverse amounts)]\n maximize = sum [x * y | (x, y) <- (zip `F.on` reverse) prices amounts]\n \n\nmain = do\n foo <- getContents\n putStrLn . solve . parse . lines $ foo"}, {"source_code": "import Data.List (sort, group)\nimport Text.Printf (printf)\n\nmain = do\n\tdummy <- getLine\n\tline <- getLine\n\tcontents <- getContents\n\tuncurry (printf \"%d %d\\n\") $ gao (map read $ words line) (lines contents)\n\ngao x y = (gao' x1 yy, gao' x2 yy) where\n\tx1 = sort x\n\tx2 = reverse x1\n\tyy = reverse $ sort $ map length $ group $ sort y\n\tgao' x' y' = sum $ zipWith (*) x' y'\n"}, {"source_code": "import List\nimport IO\n\nreadFruits :: Int -> IO [String]\nreadFruits 0 = return []\nreadFruits n = do\n r <- getLine\n rs <- readFruits (n-1)\n return (r:rs)\n\nmain = do\n s <- getLine\n let an:bn:xs = (map (read :: (String -> Int)) . words) s\n prices_ <- getLine\n let prices = (sort . map (read :: (String -> Int)) . words) prices_\n fruit_list <- readFruits bn\n let fruits = sortBy (\\a b -> length b `compare` length a) $ group $ sort fruit_list\n min_cost = zipWith (*) prices (map length fruits)\n max_cost = zipWith (*) (reverse prices) (map length fruits)\n putStr $ ( show $ sum min_cost) ++ \" \"\n putStrLn $ show $ sum max_cost\n"}, {"source_code": "import Data.List (sort, group)\nimport Text.Printf (printf)\n\nmain = do\n dummy <- getLine\n line <- getLine\n contents <- getContents\n uncurry (printf \"%d %d\\n\") $ gao (map read $ words line) (lines contents)\n\ngao x y = (gao' x1 yy, gao' x2 yy) where\n x1 = sort x\n x2 = reverse x1\n yy = reverse $ sort $ map length $ group $ sort y\n gao' x' y' = sum $ zipWith (*) x' y'"}], "negative_code": [{"source_code": "import Data.List (sort, group)\nimport Text.Printf (printf)\n\nmain = do\n dummy <- getLine\n line <- getLine\n contents <- getContents\n uncurry (printf \"%d %d\\n\") $ gao (map read $ words line) (lines contents)\n\ngao x y = (gao' x1 yy, gao' x2 yy) where\n x1 = sort x\n x2 = reverse x1\n yy = sort $ map length $ group $ sort y\n gao' x' y' = sum $ zipWith (*) x' y'"}], "src_uid": "31c43b62784a514cfdb9ebb835e94cad"} {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (n : xs)\n | even n && odd m = f $ sort xs\n | otherwise = sum $ map abs xs\n where\n m = length $ filter (< 0) xs\n f (x : y : xs) | x + y < 0 = f xs - x - y\n f xs = sum xs\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n a <- getList\n let [neg, pos, zero] = ff a [0,0,0]\n b = sort $ map (abs) a\n k = if n `mod` 2 == 1 then 0 else (neg `mod` 2)\n a1 = take k b\n a2 = drop k b\n print $ (sum a2) - (sum a1)\n where\n ff [] acc = acc\n ff (x:xs) [neg,pos,zero]\n | x < 0 = ff xs [neg+1,pos,zero]\n | x > 0 = ff xs [neg,pos+1,zero]\n | otherwise = ff xs [neg,pos,zero+1]\n getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs\n | elem 0 xs = sum abss\n | even $ length negs = sum abss\n | odd n = sum abss\n | otherwise = sum abss - 2 * minimum abss\n where\n negs = filter (<0) xs\n abss = map abs xs\n"}, {"source_code": "import Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: Int -> [Int] -> Int\nsolve n as\n | odd n = sumAbs\n | odd (length (filter (< 0) as)) = sumAbs - 2 * bad\n | otherwise = sumAbs\n where\n sumAbs = sum $ map abs as\n bad = minimum $ map abs as\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- reads\n print $ solve n as\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n a <- getList\n let [neg, pos, zero] = ff a [0,0,0]\n b = sort $ map (abs) a\n k = if n `mod` 2 == 1 then 0 else (neg `mod` 2)\n a1 = take k b\n a2 = drop k b\n print $ (sum a2) - (sum a1)\n where\n ff [] acc = acc\n ff (x:xs) [neg,pos,zero]\n | x < 0 = ff xs [neg+1,pos,zero]\n | x > 0 = ff xs [neg,pos+1,zero]\n | otherwise = ff xs [neg,pos,zero+1]\n getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine"}], "negative_code": [{"source_code": "import Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve as = sumAbs - bad\n where\n sumAbs = sum $ map abs as\n bad = if odd $ length $ filter (<0) as then minimum $ map abs as else 0\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n print $ solve as\n"}, {"source_code": "import Control.Monad (liftM)\nimport Prelude hiding (reads)\n\nreads :: Read a => IO [a]\nreads = liftM (map read . words) getLine\n\nsolve :: [Int] -> Int\nsolve as = sumAbs - 2 * bad\n where\n sumAbs = sum $ map abs as\n bad = if odd $ length $ filter (<0) as then minimum $ map abs as else 0\n\nmain :: IO ()\nmain = do\n getLine\n as <- reads\n print $ solve as\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs = go xs\n where\n go xs\n | sum ys < 0 = go $ map negate ys ++ zs\n | otherwise = sum xs\n where\n (ys,zs) = splitAt n $ sort xs"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns, TupleSections #-}\n\nimport Control.Applicative\nimport Data.List\n\nmain :: IO ()\nmain = do\n n <- readLn\n xs <- map read.words <$> getLine\n print $ solve n xs\n\nsolve :: Int -> [Int] -> Int\nsolve n xs\n | elem 0 xs = sum abss\n | even $ length negs = sum abss\n | otherwise = sum abss - 2 * minimum abss\n where\n negs = filter (<0) xs\n abss = map abs xs\n"}, {"source_code": "import Data.List\nimport Data.Char\nimport Data.Maybe\nimport Data.Ord\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as C\nimport Data.Array\nimport Data.Bits\n\nmain = do\n n <- readLn :: IO Int\n a <- getList\n let [neg, pos, zero] = ff a [0,0,0]\n b = sortBy (\\x y -> abs(x) `compare` abs(y)) a\n k = if n `mod` 2 == 1 then 0 else (neg `mod` 2)\n a1 = take k b\n a2 = drop k b\n print $ (sum a2) - (sum a1)\n where\n ff [] acc = acc\n ff (x:xs) [neg,pos,zero]\n | x < 0 = ff xs [neg+1,pos,zero]\n | x > 0 = ff xs [neg,pos+1,zero]\n | otherwise = ff xs [neg,pos,zero+1]\n getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (n : xs) = f $ sort xs\n where\n f (x : y : xs) | x + y < 0 = f xs - x - y\n f xs = sum xs\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.List\n\nmain :: IO ()\nmain = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents\n\nsolve :: [Int] -> Int\nsolve (n : xs)\n | sa >= 0 = sa + sb\n | otherwise = solve (n : map negate as ++ bs)\n where\n (as, bs) = splitAt n $ sort xs\n sa = sum as\n sb = sum bs\n"}], "src_uid": "9b907b3e96e78c84d11032a0f0b0fa53"} {"source_code": "{-# LANGUAGE BangPatterns #-}\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n \r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\nimport Data.List\r\n--import Data.Array.Unboxed\r\n \r\n \r\nprefMins :: Ord t => (a -> t) -> [a] -> [t]\r\nprefMins f li = tail $ scanl' min (f $ head li) $ map f li\r\n\r\nsqr x = x*x\r\n\r\npow x n | (n==0) = 1\r\n | ((mod n 2) == 0) = sqr $ pow x $ div n 2 \r\n | otherwise = x * (pow x (n-1))\r\n\r\ngao (a, k) | k == 0 = 0\r\n | (length a) == 1 = ((pow 10 (head a)) * k)\r\n | otherwise = ((gao ((tail a), (k - d))) + ((pow 10 (head a)) * d)) where d = (min (k) ((pow 10 ((a !! 1) - (head a))) - 1)) \r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n ~[t] <- getInts 1\r\n fmap mconcat $ replicateM t $ do \r\n ~[n, k] <- getInts 2 \r\n a <- getInts n\r\n pure $ putInts [gao (a, k+1)]\r\n \r\n\r\ntype SP = State [P.ByteString]\r\n \r\ngetNext :: Int -> SP [P.ByteString]\r\ngetNext = state . splitAt\r\n \r\ngetInts :: Int -> SP [Int]\r\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\r\n \r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n \r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun $ P.words inp\r\n P.putStr $ toLazyByteString outp", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Int\n\ncalc :: Int64 -> Int64 -> [Int64] -> Int64\ncalc n k pows =\n let lst = map ((flip (-) $ 1) . (10^) . uncurry (-)) $ zip (tail pows) pows\n all = lst ++ [10^10]\n cnts = tail $ map fst $ scanl (\\(cnt,k) a ->\n let newCnt = min k a\n newK = k - newCnt\n in\n (newCnt, newK)) (k,k) all\n in\n foldl (\\acc (a,cnt) -> acc + (10^a) * cnt) 0 $ zip pows cnts\n\nmain = do\n line <- getLine\n let t = read line :: Int\n forM_ [1..t] $ \\_ -> do\n line <- getLine\n let [n,k] = map read $ words line :: [Int64]\n line <- getLine\n let pows = map read $ words line :: [Int64]\n print $ calc n (k+1) pows\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Data.Bits\r\nimport System.IO\r\n\r\nrecurse k (d:ds) es \r\n | k < d = (k+1):es\r\n | otherwise = recurse (k-d) ds (d:es) \r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n,k] <- readv :: IO [Int]\r\n as <- readv\r\n let\r\n ds = zipWith (\\x y->10^(y-x)-1) as (tail as) ++ [k+1]\r\n nums = recurse k ds []\r\n putStrLn $ DL.intercalate \"\" (show <$> nums)\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Data.Bits\r\nimport System.IO\r\n\r\nrecurse k (d:ds) es \r\n | k < d = (k+1):es\r\n | otherwise = recurse (k-d) ds (d:es) \r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n,k] <- readv :: IO [Integer]\r\n as <- readv\r\n let\r\n ds = zipWith (\\x y->10^(y-x)-1) as (tail as) ++ [k+1]\r\n nums = recurse k ds []\r\n putStrLn $ DL.intercalate \"\" (show <$> nums)\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}, {"source_code": "{-# LANGUAGE Safe #-}\r\n{-# OPTIONS_GHC -O2 #-}\r\n\r\n\r\nimport qualified Control.Monad as CM\r\nimport qualified Data.List as DL\r\nimport Data.Bits\r\nimport System.IO\r\n\r\nrecurse es (d:ds) k \r\n | k < d = (k+1):es\r\n | otherwise = recurse (d:es) ds (k-d)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n,k] <- readv :: IO [Integer]\r\n as <- readv\r\n let\r\n ds = zipWith (\\x y->10^(y-x)-1) as (tail as) ++ [k+2]\r\n nums = recurse [] ds k\r\n putStrLn $ DL.intercalate \"\" (show <$> nums)\r\n\r\nreadv :: Read a => IO [a]\r\nreadv = fmap read . words <$> getLine\r\n \r\nmain :: IO ()\r\nmain = do\r\n ~[n] <- readv\r\n CM.replicateM_ n solve\r\n"}], "negative_code": [], "src_uid": "e25e44b8f300d6be856df50bff8ff244"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.IArray\r\nimport Data.Array.ST\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport qualified Data.IntMap as M\r\n\r\n-- Using Um_nik's neat approach in O(s log s), s = sum of lengths of the strings\r\n\r\ntype IntArray = Array Int Int\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n a <- replicateM n getLine\r\n let sa = reverse $ sort $ map (\\x -> (sort x, x)) a\r\n gs = map snd <$> groupBy ((==) `on` fst) sa\r\n n64 = fromIntegral n\r\n print $ 1337 * n64 * (n64 - 1) `div` 2 - sum (map calcSaved gs)\r\n\r\ncalcSaved :: [String] -> Int64\r\ncalcSaved g = saved where\r\n n = length g\r\n m = length $ head g\r\n getLcp s1 s2 = length $ takeWhile id $ zipWith (==) s1 s2\r\n getNotSorted s = listArray (0, length a - 1) a :: IntArray where\r\n a = map (+1) (elemIndices True $ zipWith (<) (tail s) s) ++ [m]\r\n lookup = mkLookup n m g\r\n calc :: Int -> String -> String -> [(Int, Int)] -> (Int64, [(Int, Int)])\r\n calc i curs prvs st = (total, st') where\r\n ns = getNotSorted curs\r\n st' = (lcp, i - 1) : dropWhile ((>= lcp) . fst) st where lcp = getLcp curs prvs\r\n calcSt :: (Int, Int) -> (Int, Int) -> Int64\r\n calcSt (lcp, curi) (_, prvi) = fromIntegral cnt where\r\n nxt = ns ! binSearchA (> lcp) ns\r\n ar = lookup!(i, nxt)\r\n cnt = binSearchA (> curi) ar - binSearchA (> prvi) ar\r\n total = foldl' f 0 $ zip st' (tail st') where f acc (cur, last) = acc + calcSt cur last\r\n total = fst $ foldl' f (0, [(-1, -1)]) $ zip3 [1..] (tail g) g where\r\n f (acc, st) (i, curs, prvs) = (acc + acc', st') where (acc', st') = calc i curs prvs st\r\n saved = one * 1336 + two * 1335 where\r\n one = total\r\n n64 = fromIntegral n\r\n two = n64 * (n64 - 1) `div` 2 - one\r\n\r\ndata Trie = Node (M.IntMap Trie) [Int]\r\n\r\nemptyT :: Trie\r\nemptyT = Node M.empty []\r\n\r\ninsertT :: Int -> String -> Trie -> Trie\r\ninsertT i [] (Node m is) = Node m (i:is)\r\ninsertT i (x:xs) (Node m is) = Node m' (i:is) where\r\n m' = M.insert o (insertT i xs $ M.findWithDefault emptyT o m) m\r\n o = fromEnum x\r\n\r\nmkLookup :: Int -> Int -> [String] -> Array (Int, Int) IntArray\r\nmkLookup n m g = runSTArray $ do\r\n a :: STArray s (Int, Int) IntArray <- newArray ((0, 0), (n - 1, m)) undefined\r\n let go :: Int -> Trie -> ST s ()\r\n go d (Node m is) = do\r\n let isa = listArray (0, length is - 1) is\r\n forM_ is $ \\i -> writeArray a (i, d) isa\r\n forM_ (M.elems m) $ go (d - 1)\r\n go m $ foldr (uncurry insertT) emptyT $ zip [0..] $ map reverse g\r\n return a\r\n\r\nbinSearch :: (Integral i) => (i -> Bool) -> i -> i -> i\r\nbinSearch f l h\r\n | l >= h = l\r\n | f m = binSearch f l m\r\n | otherwise = binSearch f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l (r + 1) where (l, r) = bounds a\r\n\r\nmain :: IO ()\r\nmain = solve\r\n", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\nimport Data.Array.IArray\r\nimport Data.Array.ST\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport qualified Data.IntMap as M\r\n\r\n-- Using Um_nik's neat approach in O(s log s), s = sum of lengths of the strings\r\n\r\ntype IntArray = Array Int Int\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n a <- replicateM n getLine\r\n let sa = reverse $ sort $ map (\\x -> (sort x, x)) a\r\n gs = map snd <$> groupBy ((==) `on` fst) sa\r\n n64 = fromIntegral n\r\n print $ 1337 * (n64 * (n64 - 1) `div` 2) - sum (map calcSaved gs)\r\n\r\ncalcSaved :: [String] -> Int64\r\ncalcSaved g = saved where\r\n n = length g\r\n m = length $ head g\r\n getLcp s1 s2 = length $ takeWhile id $ zipWith (==) s1 s2\r\n lookup = mkLookup n m g\r\n calc :: Int -> String -> String -> [(Int, Int)] -> (Int64, [(Int, Int)])\r\n calc i curs prvs st = (total, st') where\r\n gt = map (+1) $ elemIndices True $ zipWith (<) (tail curs) curs\r\n gtn = length gt\r\n gta = listArray (0, gtn - 1) gt :: IntArray\r\n st' = (lcp, i - 1) : dropWhile ((>= lcp) . fst) st where lcp = getLcp curs prvs\r\n calcSt :: (Int, Int) -> (Int, Int) -> Int64\r\n calcSt (l, curi) (_, prvi) = fromIntegral cnt where\r\n ar = lookup!(i, nxt) where\r\n j = binSearchA (> l) gta\r\n nxt = if j < gtn then gta!j else m\r\n cnt = binSearchA (> curi) ar - binSearchA (> prvi) ar\r\n total = foldl' f 0 $ zip st' (tail st') where f acc (cur, last) = acc + calcSt cur last\r\n total = fst $ foldl' f (0, [(-1, -1)]) $ zip3 [1..] (tail g) g where\r\n f (acc, st) (i, curs, prvs) = (acc + acc', st') where (acc', st') = calc i curs prvs st\r\n saved = one * 1336 + two * 1335 where\r\n one = total\r\n n64 = fromIntegral n\r\n two = (n64 * (n64 - 1) `div` 2) - one\r\n\r\ndata Trie = Node (M.IntMap Trie) [Int]\r\n\r\nemptyT :: Trie\r\nemptyT = Node M.empty []\r\n\r\ninsertT :: Int -> String -> Trie -> Trie\r\ninsertT i [] (Node m is) = Node m (i:is)\r\ninsertT i (x:xs) (Node m is) = Node m' (i:is) where\r\n m' = M.insert tx (insertT i xs $ M.findWithDefault emptyT tx m) m\r\n tx = fromEnum x - 97\r\n\r\nmkLookup :: Int -> Int -> [String] -> Array (Int, Int) IntArray\r\nmkLookup n m g = runSTArray $ r trie where\r\n trie = foldr f emptyT $ zip [0..] $ map reverse g where f (i, xs) t = insertT i xs t\r\n r t = do\r\n a :: STArray s (Int, Int) IntArray <- newArray ((0, 0), (n - 1, m)) undefined \r\n let go :: Int -> Trie -> ST s ()\r\n go d (Node m is) = do\r\n forM_ is $ \\i -> writeArray a (i, d) $ listArray (0, length is - 1) is\r\n forM_ (M.elems m) $ go (d - 1)\r\n go m t\r\n return a\r\n\r\nbinSearch :: (Integral i) => (i -> Bool) -> i -> i -> i\r\nbinSearch f l h\r\n | l >= h = l\r\n | f m = binSearch f l m\r\n | otherwise = binSearch f (m + 1) h\r\n where m = (l + h) `div` 2\r\n\r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l (r + 1) where (l, r) = bounds a\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [], "src_uid": "63d0ce43f03db5cf7a24b288b1977a20"} {"source_code": "import Data.Int\n\ngetInt64 = read `fmap` getLine :: IO Int64\nisqrt :: Int64 -> Int64\nisqrt = floor . sqrt . fromIntegral\nisSquare x = y * y == x where y = isqrt x\n\nmain = do\n n <- getInt64\n solve n\n\nsolve n = do\n if n <= 2\n then print (-1)\n else if odd n\n then do\n let n2 = n*n\n let a = n2 `div` 2\n let b = a + 1\n putStrLn $ show a ++ \" \" ++ show b\n else do\n let n2 = (n `div` 2)^2\n let a = n2 - 1\n let b = n2 + 1\n putStrLn $ show a ++ \" \" ++ show b", "positive_code": [{"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n\n ($!$) :: Int -> () -> Int\n ($!$) 0 _ = 1\n ($!$) n _ = (n - 1) * (n $!$ ())\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInteger :: String -> Integer\n readInteger s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n pythagorasOf :: Integer -> Maybe (Integer, Integer)\n pythagorasOf x\n | x == 1 = Nothing\n | x == 2 = Nothing\n | x == 3 = Just (4, 5)\n | x == 4 = Just (3, 5)\n | x `mod` 2 == 1 =\n let y = x `div` 2\n y1 = (y * x) + y\n in return (y1, y1 + 1)\n | otherwise = do\n (a, b) <- pythagorasOf (x `div` 2)\n return (a * 2, b * 2)\n\n strify :: Maybe (Integer, Integer) -> String\n strify Nothing = \"-1\"\n strify (Just (x, y)) = show x ++ \" \" ++ show y\n\n main :: IO()\n main = do\n x <- getLine >>= return . readInteger\n putStrLn $ strify$ pythagorasOf x\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Prelude\nimport Text.Printf\n\nsolve :: Integer -> (Integer, Integer)\nsolve n | n <= 2 = (-1, -1)\n | odd n = ((x + 1) `div` 2, (x + 1) `div` 2 - 1)\n | otherwise = ((x `div` 4) + 1, (x `div` 4) - 1)\n where x = n * n\n\nmain = do\n n <- liftM read getLine\n let (a, b) = solve n\n if a < 0 then printf \"%d\\n\" a\n else printf \"%d %d\\n\" a b\n"}, {"source_code": "process :: String -> String\nprocess str =\n let n = read str\n r = if even n then n - 2 else n - 1\n s = if even n then 2 else 1\n t = div (r*r) (2*s)\n in\n if n < 3\n then \"-1\"\n else show (r + t) ++ \" \" ++ show (r + s + t)\n\nmain :: IO ()\nmain = interact process"}, {"source_code": "\nmain = interact $ printRes . sol . read\n where\n printRes [] = \"-1\"\n printRes [a, b] = show a ++ \" \" ++ show b\n\nsol :: Integer -> [Integer]\nsol 1 = []\nsol 4 = [3, 5]\nsol n\n | n `mod` 2 == 0 = map (*2) $ sol (n `div` 2)\n | otherwise = [2*k*k + 2*k, 2*k*k + 2*k + 1]\n where\n k = (n-1) `div` 2\n\n"}, {"source_code": "import Data.Int\nimport Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int64]\n where fn x = let Just (y,_) = B.readInt x in fromIntegral y\n\nsearch :: Int64 -> Int64 -> Int64 -> Int64\nsearch x l h = if l>=h then -1\n else if diff == x then m\n else if diff=h then -1\n else if diff == x then m\n else if diff>= putStrLn . f . read\n\nf n\n\t| n <= 2 = \"-1\"\n\t| otherwise = show a ++ \" \" ++ show b\n\t\twhere\n\t\t\tp = if n `mod` 2 == 0 then 2 else 1\n\t\t\tq = if n `mod` 2 == 0 then n ^ 2 `div` 2 else n ^ 2\t\n\t\t\ta = (q - p) `div` 2\n\t\t\tb = (q + p) `div` 2\n"}, {"source_code": "{-# LANGUAGE TypeApplications #-}\n\nmain :: IO ()\nmain = do\n n <- read @ Integer <$> getLine\n let (m, k) = solve n\n putStrLn $ if n < 3 then \"-1\" else show m ++ \" \" ++ show k\n\nsolve :: Integer -> (Integer, Integer)\nsolve n | odd n = let root1 = (n - 1) `div` 2\n root2 = succ root1\n in (2 * root1 * root2, root1 * root1 + root2 * root2)\nsolve n | even n = let root = n `div` 2\n in (root * root - 1, root * root + 1)\n"}, {"source_code": "main = interact $ unwords . map show . solve . read\nsolve n | n <= 2 = [-1]\n | odd n = [(n^2+1) `div` 2, (n^2-1) `div` 2]\n | even n = [n^2 `div` 4 + 1, n^2 `div` 4 - 1]\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInteger :: String -> Integer\n readInteger s = read s :: Integer\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n pythagorasOf :: Integer -> Maybe (Integer, Integer)\n pythagorasOf x\n | x == 1 = Nothing\n | x == 2 = Nothing\n | x == 4 = Just (3, 5)\n | x `mod` 4 == 0 =\n let y = (x `div` 4) -1\n y1 = (y * x) + (x - 1)\n in return (y1, y1 + 2)\n | x `mod` 4 == 2 = do\n (a, b) <- pythagorasOf (x `div` 2)\n return (a * 2, b * 2)\n | x `mod` 2 == 1 =\n let y = x `div` 2\n y1 = (y * x) + y\n in return (y1, y1 + 1)\n\n strify :: Maybe (Integer, Integer) -> String\n strify Nothing = \"-1\"\n strify (Just (x, y)) = show x ++ \" \" ++ show y\n\n\n\n main :: IO()\n main = do\n x <- getLine >>= return . readInteger\n putStrLn $ strify$ pythagorasOf x\n"}], "negative_code": [{"source_code": "import Data.Int\nimport Data.List\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\n\nreadIntList = fmap ((map fn) . B.words) B.getLine :: IO [Int64]\n where fn x = let Just (y,_) = B.readInt x in fromIntegral y\n\nsearch :: Int64 -> Int64 -> Int64 -> Int64\nsearch x l h = if l>=h then -1\n else if diff == x then m\n else if diff Int64 -> Int64 -> Int64\nsearch x l h = if l>=h then -1\n else if diff == x then m\n else if diff getLine\n let (m, k) = solve n\n putStrLn $ if n == 1 then \"-1\" else show m ++ \" \" ++ show k\n\nsolve :: Integer -> (Integer, Integer)\nsolve n | odd n = let root1 = (n - 1) `div` 2\n root2 = succ root1\n in (2 * root1 * root2, root1 * root1 + root2 * root2)\nsolve n | even n = let root = n `div` 2\n in (root * root - 1, root * root + 1)\n"}, {"source_code": "module Main where\n import Data.List\n import Control.Monad\n import Data.Array\n\n toArray :: [a] -> Array Int a\n toArray xs =\n let ls = length xs - 1\n in array (0, ls) $ zip [0..ls] xs\n\n readInt :: String -> Int\n readInt s = read s :: Int\n\n readMultilineInput :: Int -> (String -> IO a) -> IO [a]\n readMultilineInput n transformer = replicateM n (getLine >>= transformer)\n\n data Coordinat = Coordinat { x :: Int, y :: Int } deriving (Show, Eq)\n data Taxi = Taxi { coordinat :: Coordinat, speed :: Int } deriving (Show, Eq)\n\n mkTaxi :: String -> Taxi\n mkTaxi s =\n let [xi, yi, vi] = map readInt $ words s\n in Taxi (Coordinat xi yi) vi\n\n mkCoordinat :: [Int] -> Coordinat\n mkCoordinat [x,y] = Coordinat x y\n\n distance :: Floating a => Coordinat -> Coordinat -> a\n distance (Coordinat p q) (Coordinat x y) =\n let dx = fromIntegral $ p - x\n dy = fromIntegral $ q - y\n in (sqrt $ dx * dx + dy * dy)\n\n timeToArrive :: Floating a => Coordinat -> Taxi -> a\n timeToArrive co1@(Coordinat _ _) (Taxi co2@(Coordinat _ _) v) = (distance co1 co2) / (fromIntegral v)\n\n pythagorasOf :: Int -> Maybe (Int, Int)\n pythagorasOf x\n | x == 1 = Nothing\n | x == 2 = Nothing\n | x == 4 = Just (3, 5)\n | x `mod` 4 == 0 =\n let y = (x `div` 4) -1\n y1 = (y * x) + (x - 1)\n in return (y1, y1 + 2)\n | x `mod` 4 == 2 = do\n (a, b) <- pythagorasOf (x `div` 2)\n return (a * 2, b * 2)\n | x `mod` 2 == 1 =\n let y = x `div` 2\n y1 = (y * x) + y\n in return (y1, y1 + 1)\n\n strify :: Maybe (Int, Int) -> String\n strify Nothing = \"-1\"\n strify (Just (x, y)) = show x ++ \" \" ++ show y\n\n\n\n main :: IO()\n main = do\n x <- getLine >>= return . readInt\n putStrLn $ strify$ pythagorasOf x\n\n -- [x,y] <- getLine >>= return . (map readInt) . words\n -- n <- getLine >>= return . readInt\n -- taxis <- readMultilineInput n $ return . mkTaxi\n -- putStrLn $ show $ minimum $ map (timeToArrive (Coordinat x y)) taxis\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Prelude\nimport Text.Printf\n\nsolve :: Int -> (Int, Int)\nsolve n | n <= 2 = (-1, -1)\n | odd n = ((x + 1) `div` 2, (x + 1) `div` 2 - 1)\n | otherwise = ((x `div` 4) + 1, (x `div` 4) - 1)\n where x = n * n\n\nmain = do\n n <- liftM read getLine\n let (a, b) = solve n\n if a < 0 then printf \"%d\\n\" a\n else printf \"%d %d\\n\" a b\n"}, {"source_code": "\nmain = interact $ printRes . sol . read\n where\n printRes [] = \"-1\"\n printRes [a, b] = show a ++ \" \" ++ show b\n\nsol :: Integer -> [Integer]\nsol n\n | n == 1 = []\n | n `mod` 2 == 0 = map (*2) $ sol (n `div` 2)\n | otherwise = [2*k*k + 2*k, 2*k*k + 2*k + 1]\n where\n k = (n-1) `div` 2\n\n\n"}], "src_uid": "df92643983d6866cfe406f2b36bec17f"} {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- readLn\n print $ (n `div` 2)\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\nmain=interact$unlines.map(show.(`div`2).read).tail.words\n"}, {"source_code": "main = interact $ unlines . map (show . (flip div 2) . read) . tail . words"}, {"source_code": "cardProd :: [a] -> [b] -> [(a,b)]\ncardProd xs ys = [(x,y) | x<-xs, y<-ys]\n\nsolve :: Integer -> Integer\n--solve n = foldr max 0 . map ( uncurry gcd) . filter (\\(a,b)-> a Integer\nparse = read . head . words\n\nsolveCase :: Int -> IO()\nsolveCase 0 = return ()\nsolveCase t = do\n test <- getLine\n putStrLn . show . solve . parse $ test\n solveCase (t-1)\n\ngetInt :: IO Int\ngetInt = fmap read getLine \n\nmain :: IO()\nmain = do\n n <- getInt\n solveCase n\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nprocess a = div a 2\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ta<- map read <$> replicateM n getLine ::IO [Int]\n\t\tmapM_ print $ map process a\n\n"}], "negative_code": [], "src_uid": "b46244f39e30c0cfab592a97105c60f4"} {"source_code": "import qualified Data.Map.Strict as M\nimport Control.Arrow\nimport Data.List\n\nfactorsK :: Int -> Int -> [(Int, Int)]\nfactorsK k = filter ((/=0) . snd) . map (head &&& (`mod` k) . length) . group . go [] 2\n where \n go a c n\n | c * c > n = if n /= 1 then n:a else a\n | n `rem` c == 0 = go (c:a) c (n `div` c)\n | otherwise = go a (c + 1) n \n\nfolder k (hist, cnt) n = (M.insertWith (+) fcs 1 hist, cnt + M.findWithDefault 0 fi hist)\n where fcs = factorsK k n \n fi = filter ((/=0) . snd) $ map (\\(f, c) -> (f, k - c)) fcs \n\nrl = map read . words <$> getLine\n\nmain = do\n [_, k] <- rl\n inp <- rl\n\n print $ snd $ foldl' (folder k) (M.empty, 0) inp", "positive_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\nimport Data.Semigroup\nimport Data.Monoid\n\naMax = 100000 :: Int\n\naMax64 = fromIntegral aMax :: Int64\n\nmain :: IO ()\nmain = do\n [n,k] <- map readInt . words <$> getLine\n as <- unfoldr (runStateT rIntS) <$> BS.getLine\n print $ query k as\n\nmaxPowerable :: UArray Int Int64\nmaxPowerable = A.array (1,100)\n $ [(1,100000),(2,316),(3,46),(4,17),(5,10),(6,6),(7,5),(8,4),(9,3),(10,3)]\n ++ map (,2) [11..16]\n ++ map (,1) [17..100]\n\ncorrPair :: Int -> Int -> Maybe (Int,Int)\ncorrPair k v_ = (\\(x,y) -> (fromIntegral x, fromIntegral y))\n <$> foldM (\\ (!red,!compl) (!p,!e) -> do\n let eRed = e `rem` k\n eRev | eRed == 0 = 0\n | otherwise = k-eRed\n guard $ eRev == 0 || p <= maxPowerable A.! eRev\n let !redNew = red * p ^ eRed\n !complNew = compl * p ^ eRev\n guard $ complNew <= aMax64\n return (redNew,complNew))\n (1::Int64,1::Int64)\n (primeDecp v)\n where v = fromIntegral v_\n\ndata DictElement\n = DE {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64\n | Same {-# UNPACK #-} !Int64\n\ninstance Semigroup DictElement where\n DE cntThis1 cntCompl1 <> DE cntThis2 cntCompl2\n = DE (cntThis1+cntThis2) (cntCompl1+cntCompl2)\n Same l0 <> Same l1 = Same (l0+l1)\n _ <> _ = undefined\n\nquery :: Int -> [Int] -> Int64\nquery k as = sum $ map match $ IM.elems dict\n where\n match (DE x y) = x*y\n match (Same x) = (x*x-x) `shiftR` 1\n dict\n = foldl'\n (\\ !dict !a ->\n maybe dict\n (\\(!red,!compl) ->\n case compare red compl of\n EQ -> IM.insertWith (<>) red (Same 1) dict\n LT -> IM.insertWith (<>) red (DE 1 0) dict\n GT -> IM.insertWith (<>) compl (DE 0 1) dict)\n $ corrPair k a)\n IM.empty\n as\n \n \n#define IL(f) {-# INLINE f #-}; f\n\nrInt :: StateT BSL.ByteString Maybe Int\nIL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nIL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')\n\nprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,\n 71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,\n 151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,\n 233,239,241,251,257,263,269,271,277,281,283,293,307,311,313]\n\nprimeDecp :: (Integral i, FiniteBits i) => i -> [(i,Int)]\nprimeDecp !n = (\\f -> f (:)[]) $ \\cons nil ->\n let !expt2 = countTrailingZeros n\n nDiv2 = n `unsafeShiftR` expt2\n start a | a > 1 = go (tail primes) a\n | otherwise = nil\n {-# INLINE start #-}\n go (!p:ps) !a | r == 0 = goExpt p ps q 1\n | q > p = go ps a\n | otherwise = cons (a,1) nil\n where (!q,!r) = a `quotRem` p\n go [] !a | a == 1 = nil\n | otherwise = cons (a,1) nil\n goExpt !p ps 1 !j = cons (p,j) nil\n goExpt !p ps !a !j\n | r == 0 = goExpt p ps q (j+1)\n | otherwise = cons (p,j) $ if q > p then go ps a\n else cons (a,1) nil\n where (!q,!r) = a `quotRem` p\n in if expt2 /= 0 then cons (2,expt2) $ start nDiv2 else start n\n\n\n-- unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()\nIL(whenM) = (. flip when) . (>>=)\nIL(unlessM) = (. flip unless) . (>>=)\n\nIL(wrA) = A.writeArray\nIL(rdA) = A.readArray\nIL(mdA) = \\arr f !i -> do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' = \\arr f !i -> do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\nIL(swapA) = \\arr !i !j -> do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define D(f,r,d)\\\n IL(f) :: Integral a=>a->d; f=fromIntegral;\\\n IL(r) :: String->d; r=read\n#define C(f,r,g,h,d) D(f,r,d);\\\n g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n#define N(f,g,h,a,m)\\\n IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\\\n f=A.newArray;\\\n IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\\\n g=A.newArray_;\\\n IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\\\n h=A.newListArray\n#define C(a,m)\nN(newIOA,newIOA_,newIOAL,IOArray,IO)\nN(newSTA,newSTA_,newSTAL,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)\nN(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)\n#undef C\n#undef N\n\n#undef IL\n"}], "negative_code": [{"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\nimport Data.Semigroup\nimport Data.Monoid\n\naMax = 100000 :: Int\n\naMax64 = fromIntegral aMax :: Int64\n\nmain :: IO ()\nmain = do\n [n,k] <- map readInt . words <$> getLine\n as <- unfoldr (runStateT rIntS) <$> BS.getLine\n print $ query k as\n\nmaxPowerable :: UArray Int Int64\nmaxPowerable = A.array (1,100)\n $ [(1,100000),(2,316),(3,46),(4,17),(5,10),(6,6),(7,5),(8,4),(9,3),(10,3)]\n ++ map (,2) [11..16]\n ++ map (,1) [17..100]\n\ncorrPair :: Int -> Int -> Maybe (Int,Int)\ncorrPair k v_ = (\\(x,y) -> (fromIntegral x, fromIntegral y))\n <$> foldM (\\ (!red,!compl) (!p,!e) -> do\n let eRed = e `rem` k\n eRev | eRed == 0 = 0\n | otherwise = k-eRed\n guard $ eRev == 0 || p <= maxPowerable A.! eRev\n let !redNew = red * p ^ eRed\n !complNew = compl * p ^ eRev\n guard $ complNew <= aMax64\n return (redNew,complNew))\n (1::Int64,1::Int64)\n (primeDecp v)\n where v = fromIntegral v_\n\ndata DictElement\n = DE {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64\n | Same {-# UNPACK #-} !Int64\n\ninstance Semigroup DictElement where\n DE cntThis1 cntCompl1 <> DE cntThis2 cntCompl2\n = DE (cntThis1+cntThis2) (cntCompl1+cntCompl2)\n Same l0 <> Same l1 = Same (l0+l1)\n _ <> _ = undefined\n\nquery :: Int -> [Int] -> Int64\nquery k as\n | k >= 34 = let x = fromIntegral $ length $ elemIndices 1 $ as :: Int64\n in shiftR (x*(x-1)) 1\n | otherwise = sum $ map match $ IM.elems dict\n where\n match (DE x y) = x*y\n match (Same x) = x * (x-1) `shiftR` 1\n dict\n = foldl'\n (\\ !dict !a ->\n maybe dict\n (\\(!red,!compl) ->\n case compare red compl of\n EQ -> IM.insertWith (<>) red (Same 1) dict\n LT -> IM.insertWith (<>) red (DE 1 0) dict\n GT -> IM.insertWith (<>) compl (DE 0 1) dict)\n $ corrPair k a)\n IM.empty\n as\n \n \n#define IL(f) {-# INLINE f #-}; f\n\nrInt :: StateT BSL.ByteString Maybe Int\nIL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nIL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')\n\nprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,\n 71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,\n 151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,\n 233,239,241,251,257,263,269,271,277,281,283,293,307,311,313]\n\nprimeDecp :: (Integral i, FiniteBits i) => i -> [(i,Int)]\nprimeDecp !n = (\\f -> f (:)[]) $ \\cons nil ->\n let !expt2 = countTrailingZeros n\n nDiv2 = n `unsafeShiftR` expt2\n start a | a > 1 = go (tail primes) a\n | otherwise = nil\n {-# INLINE start #-}\n go (!p:ps) !a | r == 0 = goExpt p ps q 1\n | q > p = go ps a\n | otherwise = cons (a,1) nil\n where (!q,!r) = a `quotRem` p\n goExpt !p ps 1 !j = cons (p,j) nil\n goExpt !p ps !a !j\n | r == 0 = goExpt p ps q (j+1)\n | otherwise = cons (p,j) $ if q > p then go ps a\n else cons (a,1) nil\n where (!q,!r) = a `quotRem` p\n in if expt2 /= 0 then cons (2,expt2) $ start nDiv2 else start n\n\n\n-- unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()\nIL(whenM) = (. flip when) . (>>=)\nIL(unlessM) = (. flip unless) . (>>=)\n\nIL(wrA) = A.writeArray\nIL(rdA) = A.readArray\nIL(mdA) = \\arr f !i -> do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' = \\arr f !i -> do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\nIL(swapA) = \\arr !i !j -> do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define D(f,r,d)\\\n IL(f) :: Integral a=>a->d; f=fromIntegral;\\\n IL(r) :: String->d; r=read\n#define C(f,r,g,h,d) D(f,r,d);\\\n g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n#define N(f,g,h,a,m)\\\n IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\\\n f=A.newArray;\\\n IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\\\n g=A.newArray_;\\\n IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\\\n h=A.newListArray\n#define C(a,m)\nN(newIOA,newIOA_,newIOAL,IOArray,IO)\nN(newSTA,newSTA_,newSTAL,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)\nN(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)\n#undef C\n#undef N\n\n#undef IL\n"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)\nimport qualified Control.Monad.ST.Lazy as STL\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\nimport Data.Semigroup\nimport Data.Monoid\n\naMax = 100000 :: Int\n\naMax64 = fromIntegral aMax :: Int64\n\nmain :: IO ()\nmain = do\n [n,k] <- map readInt . words <$> getLine\n as <- unfoldr (runStateT rIntS) <$> BS.getLine\n print $ query k as\n\nmaxPowerable :: UArray Int Int64\nmaxPowerable = A.array (1,100)\n $ [(1,100000),(2,316),(3,46),(4,17),(5,10),(6,6),(7,5),(8,4),(9,3),(10,3)]\n ++ map (,2) [11..16]\n ++ map (,1) [17..100]\n\ncorrPair :: Int -> Int -> Maybe (Int,Int)\ncorrPair k v_ = (\\(x,y) -> (fromIntegral x, fromIntegral y))\n <$> foldM (\\ (!red,!compl) (!p,!e) -> do\n let eRed = e `rem` k\n eRev | eRed == 0 = 0\n | otherwise = k-eRed\n guard $ eRev == 0 || p <= maxPowerable A.! eRev\n let !redNew = red * p ^ eRed\n !complNew = compl * p ^ eRev\n guard $ complNew <= aMax64\n return (redNew,complNew))\n (1::Int64,1::Int64)\n (primeDecp v)\n where v = fromIntegral v_\n\ndata DictElement\n = DE {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64\n | Same {-# UNPACK #-} !Int64\n\ninstance Semigroup DictElement where\n DE cntThis1 cntCompl1 <> DE cntThis2 cntCompl2\n = DE (cntThis1+cntThis2) (cntCompl1+cntCompl2)\n Same l0 <> Same l1 = Same (l0+l1)\n _ <> _ = undefined\n\nquery :: Int -> [Int] -> Int64\nquery k as = sum $ map match $ IM.elems dict\n where\n match (DE x y) = x*y\n match (Same x) = x * (x-1) `shiftR` 1\n dict\n = foldl'\n (\\ !dict !a ->\n maybe dict\n (\\(!red,!compl) ->\n case compare red compl of\n EQ -> IM.insertWith (<>) red (Same 1) dict\n LT -> IM.insertWith (<>) red (DE 1 0) dict\n GT -> IM.insertWith (<>) compl (DE 0 1) dict)\n $ corrPair k a)\n IM.empty\n as\n \n \n#define IL(f) {-# INLINE f #-}; f\n\nrInt :: StateT BSL.ByteString Maybe Int\nIL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')\nrIntS :: StateT BS.ByteString Maybe Int\nIL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')\n\nprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,\n 71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,\n 151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,\n 233,239,241,251,257,263,269,271,277,281,283,293,307,311,313]\n\nprimeDecp :: (Integral i, FiniteBits i) => i -> [(i,Int)]\nprimeDecp !n = (\\f -> f (:)[]) $ \\cons nil ->\n let !expt2 = countTrailingZeros n\n nDiv2 = n `unsafeShiftR` expt2\n start a | a > 1 = go (tail primes) a\n | otherwise = nil\n {-# INLINE start #-}\n go (!p:ps) !a | r == 0 = goExpt p ps q 1\n | q > p = go ps a\n | otherwise = cons (a,1) nil\n where (!q,!r) = a `quotRem` p\n goExpt !p ps 1 !j = cons (p,j) nil\n goExpt !p ps !a !j\n | r == 0 = goExpt p ps q (j+1)\n | otherwise = cons (p,j) $ if q > p then go ps a\n else cons (a,1) nil\n where (!q,!r) = a `quotRem` p\n in if expt2 /= 0 then cons (2,expt2) $ start nDiv2 else start n\n\n\n-- unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()\nIL(whenM) = (. flip when) . (>>=)\nIL(unlessM) = (. flip unless) . (>>=)\n\nIL(wrA) = A.writeArray\nIL(rdA) = A.readArray\nIL(mdA) = \\arr f !i -> do\n ai <- rdA arr i\n let fai = f ai \n wrA arr i fai\n return (ai,fai)\n{-# INLINE mdA' #-}\nmdA' = \\arr f !i -> do\n !ai <- rdA arr i\n let !fai = f ai\n wrA arr i fai\n return (ai,fai)\nIL(swapA) = \\arr !i !j -> do\n ai <- rdA arr i\n wrA arr i =<< rdA arr j\n wrA arr j ai\n\n#define D(f,r,d)\\\n IL(f) :: Integral a=>a->d; f=fromIntegral;\\\n IL(r) :: String->d; r=read\n#define C(f,r,g,h,d) D(f,r,d);\\\n g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n#define N(f,g,h,a,m)\\\n IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\\\n f=A.newArray;\\\n IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\\\n g=A.newArray_;\\\n IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\\\n h=A.newListArray\n#define C(a,m)\nN(newIOA,newIOA_,newIOAL,IOArray,IO)\nN(newSTA,newSTA_,newSTAL,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)\nN(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)\n#undef C\n#undef N\n\n#undef IL\n"}], "src_uid": "a8c5b1377035f0a772510b5b80588d47"} {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE UnicodeSyntax #-}\n{-# LANGUAGE LambdaCase, MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [_,xs] = let\n m = minimum xs\n in\n wrap.show $ minimum $ diffs $ map fst $ filter ((m==).snd) $ zip [0..] xs\n\n\ndiffs [_] = []\ndiffs [] = []\ndiffs (x:y:xs) = abs (x-y) : diffs (y:xs)\n\n\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n\naddCnt :: [String] -> [String]\naddCnt ls = (show $ length ls) : ls\n\ntoBitMap :: Int -> [(Int, Bool)]\ntoBitMap = toBitMap' 31\n where\n toBitMap' (-1) _ = []\n toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Control.Monad\n\nminIndices :: [Int] -> [Int]\nminIndices xs = map fst . filter isMin $ zip [1 ..] xs\n where minx = minimum xs\n isMin (_, x) = x == minx\n\ndiffs :: [Int] -> [Int]\ndiffs xs = zipWith (-) (tail xs) (init xs)\n\nsolve :: [Int] -> Int\nsolve = minimum . diffs . minIndices\n\ntest0 = [3, 3] :: [Int]\ntest1 = [5, 6, 5] :: [Int]\ntest2 = [2, 1, 3, 5, 4, 1, 2, 3, 1] :: [Int]\n\nmain :: IO ()\nmain = do\n _ <- getLine\n xs <- map read . words <$> getLine\n print $ solve xs\n"}, {"source_code": "import Data.List\nimport Data.Function\nmain = getLine >> getLine >>= print . minimum . (\\xs@(_:xs') -> zipWith (\\a b -> abs $ a - b) xs xs') . map snd . head . groupBy ((==) `on` fst) . sort . flip zip [(0 :: Int)..] . map (read :: String -> Int) . words"}, {"source_code": "-- Codeforces 911A\n\n{-# OPTIONS_GHC -O0 #-}\n{-# OPTIONS_GHC -optc-O0 #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as BC\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = do\n (n:ns) <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents :: IO [Int]\n let a = minimum ns\n indices = elemIndices a ns\n diff = zipWith (-) (tail indices) indices\n ans = minimum diff\n print ans\n"}, {"source_code": "import Data.List\n\nmain = do\n _ <- getLine\n inputLines <- fmap words getLine\n let intList = map read inputLines :: [Int]\n print $ distance $ elemIndices (minimum intList) intList\n\ndistance [] = maxBound\ndistance [_] = maxBound\ndistance (x:y:xs)\n | (abs (x - y)) > (distance $ y:xs) = distance $ y:xs\n | otherwise = abs (x - y)\n"}, {"source_code": "import Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain = sol <$> (C.getLine *> get) >>= print\n\nget = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nsol = mds . fmap fst . mis\n where\n mds = minimum . uncurry (zipWith (-)) <<< tail &&& id\n mis = (\\m -> filter ((m==) . snd)) <$> minimum <*> zip ([0..]::[Int]) \n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport qualified Data.Map.Strict as M\nimport qualified Data.ByteString.Char8 as C\nimport Data.Maybe\n\nmain = sol <$> (C.getLine *> get) >>= print\n\nget = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine\n\nsol as = minimum $ minimum <$> ds\n where\n mp = M.filter ((>1) . length) . M.fromListWith (++) $ zipWith (\\a i -> (a,[i])) as [0..]\n ds = (\\bs -> zipWith (-) bs (tail bs)) . snd <$> M.toList mp\n"}], "src_uid": "67af292ff23880ad9fd4349729e36158"} {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [Int] -> [Int]\nsolve [n, k]\n | 3 * k > n = [-1]\n | otherwise = take n (k : [1..k-1] ++ cycle [1..k])\n\nmain :: IO ()\nmain = reads >>= prints . solve\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n", "positive_code": [{"source_code": "main = interact (unwords . map show . (\\[n, k] -> ans k n) . map read . words)\n\nans :: Int -> Int -> [Int]\nans k n = if 3*k > n then [-1] else gen k\n where\n gen 3 = [3, 3, 2, 3, 2, 1, 1, 2, 1] ++ replicate (n - 3*k) 1\n gen 2 = [2, 2, 1, 2, 1, 1] ++ replicate (n - 3*k) 1\n gen x = [x, x, x-1, x, x-1, x-1] ++ gen (x-2)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\nmain=interact$unwords.map show.f.map read.words\nf[n,k]\n | n `div` k < 3 = [-1]\n | even k = take n $ cycle ([1..k] ++ [k,k-1..1])\n | otherwise = (take (n-1) $ k:k:cycle ([1..k-1] ++ [k-1,k-2..1]))++[k]"}], "negative_code": [], "src_uid": "aba3bb100e2d3d30dc4b00818f190bff"} {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n", "positive_code": [{"source_code": "import Data.List (group, sort)\nimport Data.Int (Int64)\nimport Data.Bits ((.&.))\nimport Control.Applicative ((<$>), liftA)\nimport Data.ByteString (ByteString)\nimport Control.Monad (replicateM, sequence)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\npress :: [(Int64, Int)] -> [(Int64, Int64)]\npress ((l, n):(l', n'):rest)\n | l == l' + 1 && n .&. 1 == 1 = (l, n'' - 1):press ((l', n' + 1):rest)\n | otherwise = (l, n''): press ((l', n'):rest)\n where n'' = fromIntegral n :: Int64\npress [(l, n)] = [(l, fromIntegral n)]\n\n\narea :: Int64 -> [(Int64, Int64)] -> Int64\narea acc [] = acc\narea acc ((l, n):rest)\n | 3 < n = area (acc + (n `div` 4) * l * l) ((l, n `mod` 4):rest)\narea acc ((l, n):(l', n'):rest)\n | 1 < n = area (acc + l * l') ((l', n' - 2):rest)\narea acc (_:rest) = area acc rest\n\nparse :: ByteString -> Maybe [Int64]\nparse = sequence . fmap readInt64 . C8.words\n where\n readInt64 :: ByteString -> Maybe Int64\n readInt64 = liftA (fromIntegral . fst) . C8.readInt\n\nmain = B.getLine >> parse <$> B.getLine >>= \\(Just a) ->\n print . area 0 . filter ((1 < ) . snd) . press .\n fmap (\\l -> (head l, length l)) . group . reverse . sort $ a\n"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmaximizePairs :: [Int] -> [Int]\nmaximizePairs = snd . foldr step ((0 :: Int, 0 :: Int), []) . group . sort \n where\n step xs ((lastVal, cnt), list) \n | length xs `mod` 2 == 0 || lastVal /= h + 1 || cnt == 0 = \n let add = if lastVal == h + 1 then cnt else 0\n in\n ((h, max add (length xs `mod` 2)), replicate pairs h ++ list)\n | otherwise = \n ((h, 0), replicate (pairs + 1) h ++ list)\n where\n pairs = length xs `div` 2\n h = head xs\n \ngroupPairs :: [Int] -> Int64\ngroupPairs [] = 0\ngroupPairs [x] = 0\ngroupPairs (x:y:xys) = fromIntegral x * fromIntegral y + groupPairs xys\n \nreadIntList :: IO [Int]\nreadIntList = do\n _ <- B.getLine\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n \nmain = do\n a <- readIntList\n print $ groupPairs . reverse . maximizePairs $ a\n \n"}, {"source_code": "import Control.Monad\nimport Data.List\n\ntrimSticks :: [Integer] -> [Integer]\ntrimSticks [] = []\ntrimSticks [_] = []\ntrimSticks (x:y:rest)\n | x - y < 2 = (y:trimSticks rest)\n | otherwise = trimSticks (y:rest)\n\nprepare :: [Integer] -> [Integer]\nprepare ls =\n let sls = reverse . sort $ ls\n in trimSticks sls\n\nmaxArea :: [Integer] -> Integer\nmaxArea [] = 0\nmaxArea [_] = 0\nmaxArea (x:y:rest) = x * y + maxArea rest\n\nmain :: IO ()\nmain = do\n n <- readLn\n ls <- liftM (map read . take n . words) $ getLine\n putStrLn . show . maxArea . prepare $ ls"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n"}, {"source_code": "import Data.List\n\nmain = print . g . f . reverse . sort . map read . tail . words =<< getContents\n\nf (x:y:zs)\n | x - y <= 1 = y : f zs\n | otherwise = f (y:zs)\nf _ = []\n\ng (x:y:zs) = x*y + g zs\ng _ = 0\n"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n"}, {"source_code": "import Data.List\nmain=print.g.f.reverse.sort.map read.tail.words=<1=f(y:zs)|0<1=y:f zs;f _=[]\ng(x:y:zs)=x*y+g zs;g _=0\n\n"}, {"source_code": "import Data.List (sortBy)\n\nmain :: IO ()\nmain = getContents >>= print . solve . sortBy (flip compare) . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve (a:b:c:d:xs) | a <= b + 1 && c <= d + 1 = b * d + solve xs\n | a <= b + 1 = solve (a:b:d:xs)\n | otherwise = solve (b:c:d:xs)\nsolve _ = 0\n"}, {"source_code": "import Data.List (sortBy, unfoldr)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = sum . map product . splitN 2 . go . sortBy (flip compare)\n where go (a:yss@(b:ys)) | b `elem` [ a, a - 1 ] = b : go ys\n | otherwise = go yss\n go _ = [0, 0]\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "import Data.List (sortBy, unfoldr)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = sum . map product . splitN 2 . go . sortBy (flip compare)\n where go (a:yss@(b:ys)) | a == b = a : go ys\n | a == b + 1 = b : go ys\n | otherwise = go yss\n go _ = [0, 0]\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "import Data.List (sortBy, unfoldr)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = sum . map product . filter ((==2) . length) . splitN 2 . go . sortBy (flip compare)\n where go (a:yss@(b:ys)) | a == b = a : go ys\n | a == b + 1 = b : go ys\n | otherwise = go yss\n go _ = [0, 0]\n\nsplitN :: Int -> [a] -> [[a]]\nsplitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad hiding (foldM, foldM_)\nimport Control.Monad.ST\nimport Data.Array.Base hiding (readArray, writeArray)\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- sortBy (flip compare).map (fromIntegral.readInt).B.words <$> B.getLine\n print $ solve xs\n\nsolve :: [Integer] -> Integer\nsolve xs = go 0 xs\n where\n go !res (x:y:z:w:xs)\n | x == y || x - 1 == y = if z == w || z - 1 == w\n then go (res + y * w) xs\n else go res (x:y:w:xs)\n | otherwise = go res (y:z:w:xs)\n go res _ = res\n\n------------------------------------------------------------------------------\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInt :: B.ByteString -> Int\nreadInt bs=case B.readInt bs of{Just(n,_)->n;_->error$\"readInt error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nfoldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a\nfoldM a xs f=foldr((>=>).flip f)return xs$a\n{-# INLINE foldM #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n(!) :: (IArray a e, Ix i) => a i e -> i -> e\n(!) a i=unsafeAt a$unsafeIndex(bounds a)i\n{-# INLINE (!) #-}\nreadArray :: (MArray a e m, Ix i) => a i e -> i -> m e\nreadArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i\n{-# INLINE readArray #-}\nwriteArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()\nwriteArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e\n{-# INLINE writeArray #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f\n{-# INLINE modifyArray #-}"}], "negative_code": [{"source_code": "import Data.List (sortBy)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = product . take 2 . go . sortBy (flip compare)\n where go (a:yss@(b:ys)) | a == b = a : go ys\n | a == b + 1 = b : go ys\n | otherwise = go yss\n go _ = [0, 0]\n"}, {"source_code": "import Data.List (sortBy)\n\nmain :: IO ()\nmain = getContents >>= print . solve . sortBy (flip compare) . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve (a:b:c:d:xs) | a <= b - 1 && c <= d - 1 = b * d + solve xs\n | a <= b - 1 = solve (a:b:d:xs)\n | otherwise = solve (b:c:d:xs)\nsolve _ = 0\n"}, {"source_code": "import Data.List (sortBy)\n\nmain :: IO ()\nmain = getContents >>= print . solve . map read . tail . words\n\nsolve :: [Integer] -> Integer\nsolve = go . sortBy (flip compare)\n where go (a:b:c:d:xs) | a >= b - 1 && c >= d - 1 = b * d + go xs\n | a >= b - 1 = go (a:b:d:xs)\n | otherwise = go (b:c:d:xs)\n go _ = 0\n"}, {"source_code": "import Data.List (group, sort)\nimport Data.Int (Int64)\nimport Data.Bits ((.&.))\nimport Control.Applicative ((<$>), liftA)\nimport Data.ByteString (ByteString)\nimport Control.Monad (replicateM, sequence)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C8\n\npress :: [(Int64, Int)] -> [(Int64, Int64)]\npress ((l, n):(l', n'):rest)\n | l == l' + 1 && n .&. 1 == 1 = (l, n'' - 1):press ((l', n' + 1):rest)\n | otherwise = (l, n''): press ((l', n'):rest)\n where n'' = fromIntegral n :: Int64\npress [(l, n)] = [(l, fromIntegral n)]\n\n\narea :: Int64 -> [(Int64, Int64)] -> Int64\narea acc [] = acc\narea acc ((l, n):rest)\n | 4 < n = area (acc + (n `div` 4) * l * l) ((l, n `mod` 4):rest)\narea acc ((l, n):(l', n'):rest)\n | 1 < n = area (acc + l * l') ((l', n' - 2):rest)\narea acc (_:rest) = area acc rest\n\nparse :: ByteString -> Maybe [Int64]\nparse = sequence . fmap readInt64 . C8.words\n where\n readInt64 :: ByteString -> Maybe Int64\n readInt64 = liftA (fromIntegral . fst) . C8.readInt\n\nmain = B.getLine >> parse <$> B.getLine >>= \\(Just a) ->\n print . area 0 . filter ((1 < ) . snd) . press .\n fmap (\\l -> (head l, length l)) . group . reverse . sort $ a\n"}, {"source_code": "import Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nmaximizePairs :: [Int] -> [Int]\nmaximizePairs = snd . foldr step ((0 :: Int, 0 :: Int), []) . group . sort \n where\n step xs ((lastVal, cnt), list) \n | length xs `mod` 2 == 0 || lastVal /= h + 1 || cnt == 0 = \n ((h, max cnt (length xs `mod` 2)), replicate pairs h ++ list)\n | otherwise = \n ((h, 0), replicate (pairs + 1) h ++ list)\n where\n pairs = length xs `div` 2\n h = head xs\n \ngroupPairs :: [Int] -> Int64\ngroupPairs [] = 0\ngroupPairs [x] = 0\ngroupPairs (x:y:xys) = fromIntegral x * fromIntegral y + groupPairs xys\n \nreadIntList :: IO [Int]\nreadIntList = do\n _ <- B.getLine\n line <- B.getLine\n let res = map (fst . fromJust . B.readInt) $ B.words line\n return res\n \nmain = do\n a <- readIntList\n print $ groupPairs . reverse . maximizePairs $ a\n \n"}], "src_uid": "0e162ea665732714283317e7c052e234"} {"source_code": "import qualified Data.List as L\ncalc :: Int -> Int -> [Int] -> String\ncalc n k a\n | k > n = \"-1\"\n | otherwise = let y = a !! (k - 1) in show y ++ \" \" ++ show y\n\nmain = do\n s1 <- getLine\n s2 <- getLine\n let \n n : k : _ = map read . words $ s1\n a = L.reverse . L.sort . map read . words $ s2\n putStrLn . calc n k $ a\n\n\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\n\nmain = do\n\t[ n, k ] <- map read . words <$> getLine\n\tas <- reverse . sort . map read . words <$> getLine\n\tlet\n\t\ttmp = show $ solve k as\n\t\tres = if tmp == \"-1\" then \"-1\" else tmp ++ \" \" ++ tmp\n\tputStrLn res\n\nsolve :: Int -> [Int] -> Int\nsolve k as\n\t| k == 0 = ( as !! 0 ) + 1\n\t| length as < k = -1\n\t| otherwise = as !! ( k - 1 )\n"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n [n, k] <- fmap (map read . words) getLine\n a <- fmap (reverse . sort . map read . words) getLine\n if k == 0 then p $ succ $ a!!0\n else if k <= n then p $ a!!(k-1)\n else putStrLn \"-1\"\n where\n p :: Int -> IO ()\n p x = putStrLn $ show x ++ \" \" ++ show x\n"}, {"source_code": "import Data.List\n\nmain :: IO()\nmain = do\n str1 <- getLine\n str2 <- getLine\n let n = read ((words str1) !! 0)\n let k = read ((words str1) !! 1)\n let a = (reverse . sort) (map read (words str2)) :: [Int]\n if (n < k)\n then putStrLn \"-1\"\n else putStrLn ((show (a !! (k - 1))) ++ \" \" ++ (show (a !! (k - 1))))\n \n \n"}, {"source_code": "import qualified Data.List as L\nimport qualified Data.Maybe as M\n\nmain :: IO ()\nmain = do\n [n,k] <- getLine >>= return . map read . words\n l <- getLine >>= return . map read . words\n putStrLn . M.fromMaybe (\"-1\") $ solve k l\n\nsolve :: Int -> [Int] -> Maybe String\nsolve k l = do\n x <- fmap snd . L.find ((>=k) . fst) . L.zip [1..] . L.reverse . L.sort $ l\n return (show x ++ \" \" ++ show x)\n\n\n \n"}, {"source_code": "import Data.Ord\nimport Data.List\nimport Control.Arrow\nmain = do\n let int x = read x :: Int\n let ints = map int . words <$> getLine\n let join (x,y) = x++\" \"++y\n [n,k] <- ints\n as <- ints\n putStrLn $ \n if k > n \n then \"-1\"\n else show &&& show >>> join $ head $ drop (k - 1) $ sortBy (flip $ comparing id) as\n"}, {"source_code": "\nimport Control.Monad (liftM)\nimport Data.List (sort)\nimport Data.Maybe (fromMaybe)\n\nsolve :: Int -> [Int] -> Int -> Maybe (Int, Int)\nsolve n as k\n | k > n = Nothing\n | otherwise = Just (x, x)\n where\n x = (reverse $ sort as) !! (k - 1)\n\nmain :: IO ()\nmain = do\n [n, k] <- liftM (map read . words) getLine\n as <- liftM (map read . words) getLine\n putStrLn $ maybe \"-1\" show' $ solve n as k\n where\n show' (x, y) = show x ++ \" \" ++ show y\n"}, {"source_code": "import Data.List\nmain=interact$unwords.map show.f.map read.words\nf(n:k:x)|k>n=[-1]|1>0=[sort x!!(n-k),0]\n"}, {"source_code": "import Data.List (sort)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (n:k:as) | k <= n = [ sort as !! (n - k), 0 ]\n | otherwise = [ -1 ]\nsolve _ = undefined\n"}, {"source_code": "import Data.List\nmain=interact$unwords.map show.f.map read.words\nf(n:k:x)|k<=n=[sort x!!(n-k),0]|1>0=[-1]\n"}, {"source_code": "import Data.List (sortBy)\n\nmain :: IO ()\nmain = getContents >>= putStrLn . unwords . map show . solve . map read . words\n\nsolve :: [Int] -> [Int]\nsolve (_:k:as) | k <= length as = [ sortBy (flip compare) as !! (k - 1), 0 ]\n | otherwise = [ -1 ]\nsolve _ = undefined\n"}, {"source_code": "import Data.List\nmain=interact$solve.map read.words\nsolve(n:k:xs)\n | n < k = \"-1\"\n | otherwise = shows x \" \"++show x\n where\n x = head $ drop (n-k) $ sort xs"}, {"source_code": "import Data.List\n\nmain = do\n\tct <- getContents\n\tlet\n\t\t(n:k:a) = map read $ words ct\n\tputStrLn $ solve k $ sort a\n\nsolve :: Int -> [Int] -> String\nsolve k a\n\t| k > length a = \"-1\"\n\t| otherwise = ax ++ \" \" ++ ax\n\twhere\n\t\tax = show $ a !! (length a - k)\n\t\n\n"}, {"source_code": "module Main where\n\nimport Data.List\n\nqsort [] = []\nqsort (x:xs) = qsort more ++ [x] ++ qsort less\n where\n (less, more) = partition (< x) xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve k a = if last kFirst == head rest\n then [-1]\n else [last kFirst, 0]\n where\n (kFirst, rest) = splitAt k a\n\nmain = do\n nkStr <- getLine\n let [n, k] = map read $ words nkStr\n aStr <- getLine\n let a = qsort $ map read $ words aStr\n if k < n\n then putStrLn $ unwords $ map show $ solve k a\n else if k == n\n then putStrLn \"0 0\"\n else putStrLn \"-1\""}, {"source_code": "import Data.List\nqsort [] = []\nqsort (x:xs) = qsort more ++ [x] ++ qsort less\n where\n (less, more) = partition (< x) xs\n \nsolve :: [Int] -> Int-> [Int]\nsolve a k = if last kFirst == head rest\n then [-1]\n else [last kFirst, 0]\n where\n (kFirst, rest) = splitAt k a\n \nmain = do\n nkStr <- getLine\n let [n, k] = map read $ words nkStr\n aStr <- getLine\n let a = qsort $ map read $ words aStr\n if k < n\n then putStrLn $ unwords $ map show $ solve a k\n else if k == n\n then putStrLn \"0 0\"\n else putStrLn \"-1\""}, {"source_code": "module Main where\n\nimport Data.List\n\nqsort [] = []\nqsort (x:xs) = qsort more ++ [x] ++ qsort less\n where\n (less, more) = partition (\\ x' -> x' < x) xs\n\nsolve :: Int -> [Int] -> [Int]\nsolve k a = if (last kFirst) == (head rest)\n then [-1]\n else [last kFirst, 0]\n where\n (kFirst, rest) = splitAt k a\n\nmain = do\n nkStr <- getLine\n let nk = map (read :: String -> Int) $ words nkStr\n n = nk!!0\n k = nk!!1\n aStr <- getLine\n let a = qsort $ map (read :: String -> Int) $ words aStr\n if k < n\n then putStrLn $ unwords $ map show $ solve k a\n else if k == n\n then putStrLn \"0 0\"\n else putStrLn \"-1\""}, {"source_code": "import Control.Applicative\nimport Data.List\n \t\n\t\t\t\n\n \n\n\nmain= do\n\t[n,k]<- map read.words <$> getLine ::IO [Int]\n\ts<-reverse.sort .map read. words <$> getLine:: IO [Int]\n\tputStrLn $ if length s getLine\n as<-map read.take n.words<$>getLine::IO[Int]\n let\n c = reverse $ take (1+k) $ reverse $ sort as\n b = (head c == (head.tail $ c)) -- || ((head.tail $ c) == head.tail.tail$c)\n ch=show(head.tail$c)\n res<-try(evaluate b)::IO(Either SomeException Bool)\n case (compare k n) of\n GT -> do\n print(-1)\n return()\n EQ -> putStrLn \"0 0\"\n _ -> \n case res of\n Left _ -> print (-1)\n Right r -> case r of\n True -> print (-1)\n False -> putStrLn(ch++\" 0\")"}, {"source_code": "import Data.List\n\nsolve n k as | k > n = [\"-1\"]\n | otherwise = map show [x, y]\n where\n xs = sort as\n x = head $ drop (n - k) xs \n y = x \n\nparseInput input = (n, k, as) where\n ls = lines input\n [n, k] = map read $ words $ head ls :: [Int]\n as = map read $ words $ last ls :: [Int]\n\nmain = do\n input <- getContents\n let (n, k, as) = parseInput input\n putStrLn $ intercalate \" \" $ solve n k as\n"}], "negative_code": [{"source_code": "import Data.List\nmain=interact$unwords.map show.f.map read.words\nf(n:k:x)|k0=[sort x!!(n-k),0]\n"}], "src_uid": "4d743a00e11510c824080ad7f1804021"} {"source_code": "import Data.Monoid\n\njudgeSum :: [Integer] -> Ordering\njudgeSum input = compare (sum . filter (> 0) $ input) (negate . sum . filter (< 0) $ input)\n\njudgeLexi :: [Integer] -> Ordering\njudgeLexi input = compare (filter (> 0) input) [-x | x <- input, x < 0]\n\njudgeLast :: [Integer] -> Ordering\njudgeLast input = compare (last input) 0\n\njudge :: [Integer] -> Ordering\njudge = do\n a <- judgeSum\n b <- judgeLexi\n c <- judgeLast\n return (a `mappend` b `mappend` c)\n\nmain = do\n getLine\n input <- getContents >>= (return . (map read) . lines)\n let ret = case (judge input) of\n LT -> \"second\"\n GT -> \"first\"\n putStrLn ret\n\n", "positive_code": [{"source_code": "solve pl = if p1 > p2 then \"first\" else\n if p2 > p1 then \"second\" else\n if l1 > l2 then \"first\" else\n if l2 > l1 then \"second\" else\n if (signum $ last pl) == 1 then \"first\" else \"second\"\n\twhere\t(p1, p2) = foldl (\\(a, b) x -> if x > 0 then (a+x, b) else (a, b-x)) (0,0) pl\n\t\t(l1, l2) = foldr (\\x (a, b) -> if x > 0 then (x:a, b) else (a, (-x):b)) ([],[]) pl\n\n\nmain = do\n\tn <- (getLine >>= readIO :: IO Integer)\n\tpl <- mapM (const (getLine >>= readIO :: IO Integer)) [1..n]\n\tputStrLn $ solve pl\n"}, {"source_code": "solve input =\n let (_:all) = (map read . words) input\n first = filter (> 0) all;\n second = (map negate . filter (< 0)) all;\n first_last = (last all) > 0\n in if sum first > sum second\n then \"first\"\n else\n if sum first < sum second\n then \"second\"\n else\n if first > second\n then \"first\"\n else\n if (first < second)\n then \"second\"\n else\n if first_last\n then \"first\"\n else \"second\"\n\nmain = interact solve"}, {"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}\nimport Control.Applicative\nimport Control.Exception hiding (mask)\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray, runSTArray)\nimport Data.Bits\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport qualified Data.Map as M\nimport qualified Data.IntMap as IM\nimport qualified Data.Set as S\nimport qualified Data.IntSet as IS\nimport Data.STRef\nimport GHC.Arr (Array, STArray, Ix(..))\nimport Debug.Trace\n\nbool :: a -> a -> Bool -> a\nbool t f b=if b then t else f\nreadInteger :: B.ByteString -> Integer\nreadInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$\"readInteger error : bs = \"++show bs;}\nrep, rev :: Monad m => Int -> (Int -> m ()) -> m ()\nrep n f=foldr((>>).f)(return())[0..n-1]\nrev n f=foldr((>>).f.negate)(return())[1-n..0]\nfor :: Monad m => Int -> Int -> (Int -> m ()) -> m ()\nfor a b f=foldr((>>).f)(return())[a..b]\n{-# INLINE rep #-}\n{-# INLINE rev #-}\n{-# INLINE for #-}\nmodifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()\nmodifyArray a i f=readArray a i>>=writeArray a i.f\n{-# INLINE modifyArray #-}\nunsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()\nunsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f\n{-# INLINE unsafeModify #-}\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n xs <- map readInteger.B.words <$> B.getContents\n putStrLn.bool\"first\"\"second\"$ solve xs\n\nsolve :: [Integer] -> Bool\nsolve xs\n | sumF > sumS = True\n | sumF < sumS = False\n | otherwise = case compare fs (map abs ss) of\n LT -> False\n GT -> True\n EQ -> last xs > 0\n where\n (fs,ss) = partition (>0) xs\n !sumF = sum fs\n !sumS = abs $ sum ss\n "}], "negative_code": [{"source_code": "solve pl = if p1 > p2 then \"first\" else\n if p2 > p1 then \"second\" else\n if l1 > l2 then \"first\" else\n \"second\"\n\twhere\t(p1, p2) = foldl (\\(a, b) x -> if x > 0 then (a+x, b) else (a, b-x)) (0,0) pl\n\t\t(l1, l2) = foldr (\\x (a, b) -> if x > 0 then (x:a, b) else (a, (-x):b)) ([],[]) pl\n\n\nmain = do\n\tn <- (getLine >>= readIO :: IO Integer)\n\tpl <- mapM (const (getLine >>= readIO :: IO Integer)) [1..n]\n\tputStrLn $ solve pl\n"}, {"source_code": "\nsolve pl = if p1 > p2 then \"first\" else\n if p2 > p1 then \"second\" else\n if l1 > l2 then \"first\" else\n \"second\"\n\twhere\t(p1, p2) = foldl (\\(a, b) x -> if x > 0 then (a+x, b) else (a, b-x)) (0,0) pl\n\t\t(l1, l2) = foldr (\\x (a, b) -> if x > 0 then (x:a, b) else (a, (-x):b)) ([],[]) pl\n\n\nmain = do\n\tn <- (getLine >>= readIO :: IO Int)\n\tpl <- mapM (const (getLine >>= readIO :: IO Int)) [1..n]\n\tputStrLn $ solve pl\n"}, {"source_code": "import Data.Monoid\n\njudgeSum :: [Int] -> Ordering\njudgeSum input = compare (sum . filter (> 0) $ input) (negate . sum . filter (< 0) $ input)\n\njudgeLexi :: [Int] -> Ordering\njudgeLexi input = compare (filter (> 0) input) [-x | x <- input, x < 0]\n\njudgeLast :: [Int] -> Ordering\njudgeLast input = compare (last input) 0\n\njudge :: [Int] -> Ordering\njudge = do\n a <- judgeSum\n b <- judgeLexi\n c <- judgeLast\n return (a `mappend` b `mappend` c)\n\nmain = do\n getLine\n input <- getContents >>= (return . (map read) . lines)\n let ret = case (judge input) of\n LT -> \"second\"\n GT -> \"first\"\n putStrLn ret\n\n"}], "src_uid": "d3684227d1f12cf36dc302e1ffee8370"} {"source_code": "main = getContents >>= putStr . unlines . map solve . tail . lines\n\nsolve = (\\[a, b] -> if a - b > 1 then \"YES\" else \"NO\") . map read . words", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\t[ x, y ] <- readIntegers\n\tlet\n\t\td = x - y\n\tputStrLn $ if 2 <= d\n\t\tthen \"YES\"\n\t\telse \"NO\""}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n line <- words <$> getLine\n let [x,y] = read <$> line :: [Integer]\n putStrLn $ if x > y+1 then \"yes\" else \"no\""}, {"source_code": "import Data.List\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n replicateM_ t $ do\n values <- map read . words <$> getLine :: IO [Integer]\n if values !! 0 - values !! 1 == 1 then\n putStrLn \"NO\"\n else\n putStrLn \"YES\"\n"}, {"source_code": "import Control.Monad\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [a, b] <- fmap read <$> words <$> getLine\n if a - b == 1 then\n putStrLn \"NO\"\n else\n putStrLn \"YES\"\n"}], "negative_code": [], "src_uid": "0671972bc2b6452d51d048329e6e0106"} {"source_code": "import Data.List\nimport Data.List.Split\nimport qualified Data.Map as M\nimport qualified Data.Set as S\n(|>) x f = f x\n\nmain = interact process\n\nprocess contents = let\n ls = contents |> lines |> tail\n in solve ls\n\nsolve ws = ws |> map shorten |> unlines\n\nshorten word = let\n l = length word\n in if l <= 10 then word\n else (head word):(show (l - 2)) ++ [last word]", "positive_code": [{"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nabbrWord :: String -> String\nabbrWord s \n | length s <= 10 = s\n | otherwise = [head s] ++ show ((-) (length s) 2) ++ [last s] \n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- replicateM n $ getLine\n -- print xs\n mapM_ putStrLn $ map abbrWord xs "}, {"source_code": "shorten :: String -> String\nshorten s\n | l <= 10 = s\n | otherwise = [head s] ++ (show $ l - 2) ++ [s !! (l - 1)]\n where l = length s\n\nmain = do\n n <- getLine\n interact (unlines . map shorten . lines)\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/71/A\n-- implementation\nimport Control.Monad\n\ntransform :: String -> String\ntransform s\n | (length s <= 10) = s\n | otherwise = ([head s] ++ show (length s - 2) ++ [last s])\n\nmain :: IO ()\nmain = do\n n <- getLine\n inputs <- replicateM (read n) getLine\n let answers = map transform inputs\n sequence_ (map putStrLn answers)\n\n"}, {"source_code": "-- Vicfred\n-- https://codeforces.com/problemset/problem/71/A\n-- implementation\ntransform :: String -> String\ntransform s\n | (length s <= 10) = s\n | otherwise = ([head s] ++ show (length s - 2) ++ [last s])\n\nmain :: IO ()\nmain = interact $ unlines . (map transform) . tail . words\n"}, {"source_code": "ans :: String -> String\nans s | length s <= 10 = s\n | otherwise = [head s] ++ show (length s - 2) ++ [last s]\n\nmain :: IO ()\nmain = interact $ unlines . map ans . tail . lines"}, {"source_code": "import Control.Monad\nmain = do\n count <- getLine\n forM_ [1..read count] (\\_ -> do\n word <- getLine\n if length word > 10 then\n putStrLn $ [head word] ++ show (length word - 2) ++ [last word]\n else\n putStrLn word)\n"}, {"source_code": "f x | l > 10 = (head x):(show (l - 2))++[last x]\n | otherwise = x\n where l = length x\nmain = interact $ unlines.(map f).tail.words\n\n"}, {"source_code": "main :: IO()\nmain = do\n _ <- getLine\n mapM_ putStrLn . (map trans) . lines =<< getContents\n where\n trans x = if length x < 11 then x\n else (head x) : (show $ length x - 2) ++ [last x] "}, {"source_code": "-- Vicfred\n-- https://codeforces.com/contest/71/problem/A\n\nimport Control.Monad\n\nsolve :: String -> String\nsolve s =\n let len = length s\n in if len <= 10\n then s\n else ([head s] ++ show (len - 2) ++ [last s])\n\nmain = do\n n <- getLine\n inputs <- replicateM (read n) getLine\n let answers = map solve inputs\n sequence_ (map putStrLn answers)\n"}, {"source_code": "-- Vicfred\n-- Codeforces\n-- Way Too Long Words https://codeforces.com/problemset/problem/71/A\n\nmain = do\n w <- getLine\n words <- getContents\n putStrLn . unlines . map transform . lines $ words\n\ntransform :: String -> String\ntransform s\n | (length s <= 10) = s\n | otherwise = ([head s] ++ show (length s - 2) ++ [last s])\n"}, {"source_code": "module Main where\n\nisTooLong word = length word > 10\nlengthBetweenFirstAndLast word = length word - 2\nsolveCases remainingCases results = do\n word <- getLine\n let result = if isTooLong word then ([head word] ++ (show $ lengthBetweenFirstAndLast word) ++ [last word]) else word\n if remainingCases - 1 > 0 then solveCases (remainingCases - 1) (results ++ [result]) else return (results ++ [result])\n\nmain = do\n line <- getLine\n let caseCount = read line :: Int\n results <- solveCases caseCount []\n mapM putStrLn results\n"}, {"source_code": "f w = let n = length w in if n<11 then w else [w!!0] ++ show (n-2) ++ [w!!(n-1)]\n\ng _ = do\n w <- getLine\n putStrLn . f $ w\n \n\nmain = do\n n <- getLine\n mapM_ g [1..read$n]"}, {"source_code": "import System.IO\nimport Data.String\n\nreadInt :: IO Int\nreadInt = do\n int <- getLine\n return (read int)\n\n\nsolve n = do\n\tif n > 0\n\t\tthen do\n\t\t\tinput <- getLine\n\t\t\tif length(input) > 10\n\t\t\t\tthen do \n\t\t\t\t\tlet len = length(input) - 2\n\t\t\t\t\tlet str = show len\n\t\t\t\t\tputStrLn( ((head input) : []) ++ str ++((last input) : []))\n\t\t\telse putStrLn(input)\n\t\t\tsolve(n-1)\n\t\telse pure()\n\n\nmain = do\n\tnumberOfTestCases <- readInt\n\tsolve(numberOfTestCases)"}, {"source_code": "import Data.List\nf (s:ss) | length ss > 9 = [s]++(show (length ss - 1))++[last ss]\n\t | otherwise = s:ss\nmain = do\n\tn <- read `fmap` getLine\n\tmapM_ (\\_ -> putStrLn =<< (f `fmap` getLine)) [1..n]\n\t\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve s = if len > 8 then concat [[f], show len, [l]] else s\n\twhere\tlen = (length s) - 2\n\t\tl = last s\n\t\t(f:_) = s\n\nmain = do\n\tsn <- getLine\n\tlet n = read sn :: Int\n\tres <- forM [1..n]\t(\\_ -> do\n\t\t\t\t\tsolve <$> getLine\n\t\t\t\t)\n\tmapM putStrLn res\n\treturn ()"}, {"source_code": "import Control.Monad\n\nsolve :: String -> String\nsolve (x:xs) = if length (x:xs) > 10\n then x : go 0 xs\n else (x:xs)\n where go n [x] = show n ++ [x]\n go n (x:xs) = go (n + 1) xs\n\nmain :: IO ()\nmain = do\n n <- fmap read getLine\n ss <- replicateM n getLine\n mapM_ putStrLn (map solve ss)\n"}, {"source_code": "\nf s = if 10 < length s then\n [head s] ++ show (len s) ++ [last s]\n else\n s\n where len s = length $ init $ tail s\n\nanswer (x:xs) = inner (take (read x) xs) []\n where inner [] rv = reverse rv\n inner (x:xs) rv = inner xs (f x:rv)\n\nmain = interact\n $ foldl (\\x y -> x ++ y ++ \"\\n\") \"\" \n . answer\n . lines\n"}, {"source_code": "import Control.Monad\n\nmain = do\n lines <- getLine\n let cases = read lines :: Int\n results <- forM [1..cases] (\\_ -> do\n line <- getLine\n let result = solve line\n return result)\n mapM putStrLn results\n\nsolve :: String -> String\nsolve s \n | length s <= 10 = s\n | otherwise = [head s] ++ (show (length s - 2)) ++ [last s]"}, {"source_code": "-- PROBLEM https://cideforces.com/contest/71/problem/A\n\nimport Control.Arrow ((>>>))\n\nmain :: IO()\nmain = \n interact $ \n lines >>> drop 1 >>> map solve >>> unlines\n\n\nsolve :: String -> String\nsolve s\n | length s <= 10 = s\n | otherwise = head s : show len ++ [last s]\n where\n len = length s - 2\n"}, {"source_code": "main = interact w\n\nw = unlines . map f . tail . lines\n\nf s | length s > 10 = [head s] ++ show ( (length s) - 2 ) ++ [last s]\n | otherwise = s"}, {"source_code": "\nf :: String -> String\nf x \n | l <= 10 = x\n | otherwise = [head x] ++ (show (l - 2)) ++ [x !! (l - 1)]\n where l = length x\n\nmain = do\n n <- readInt\n a <- readStrN n\n printStrList $ map f a\n\n-- Int from line\nreadInt :: IO Int\nreadInt = do\n line <- getLine\n return $ read line\n\n-- Int from N lines\nreadStrN :: Int -> IO [String]\nreadStrN 0 = return []\nreadStrN n = do\n x <- getLine\n xs <- readStrN (n - 1)\n return (x:xs)\n\nprintStrList :: [String] -> IO()\nprintStrList [] = return ()\nprintStrList (x:xs) = do\n putStrLn x\n printStrList xs"}, {"source_code": "shorten :: String -> String\nshorten s\n | length s <= 10 = s\n | otherwise = [head s] ++ show (length s - 2) ++ [last s]\n\nsolve :: String -> String\nsolve input = unlines $ map shorten $ tail $ lines input\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "-- RandomUsername (Nikola Jovanovic)\n-- Codeforces\n-- Way Too Long Words (http://codeforces.com/problemset/problem/71/A)\n\nmain = do\n w <- getLine\n words <- getContents\n putStrLn . unlines . solve . lines $ words\n\nsolve :: [String] -> [String]\nsolve xs = foldr change [] xs\n where change x acc\n | (length x <= 10) = x:acc\n | otherwise = ( [head x] ++ lenstr x ++ [last x] ):acc\n lenstr x = show $ length x - 2\n\n\n"}, {"source_code": "-- RandomUsername (Nikola Jovanovic)\n-- Codeforces\n-- Way Too Long Words (http://codeforces.com/problemset/problem/71/A)\n\nmain = do\n w <- getLine\n words <- getContents\n putStrLn . unlines . map transform . lines $ words\n\nsolve :: [String] -> [String]\nsolve xs = foldr change [] xs\n where change x acc\n | (length x <= 10) = x:acc\n | otherwise = ( [head x] ++ lenstr x ++ [last x] ):acc\n lenstr x = show $ length x - 2\n\ntransform :: String -> String\ntransform s\n | (length s <= 10) = s\n | otherwise = ([head s] ++ show (length s - 2) ++ [last s])"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Maybe (fromJust)\n\nreadNumber :: IO Int\nreadNumber = read `fmap` getLine\n\nabbreviateWord :: String -> String\nabbreviateWord w =\n concat [ firstLetter\n , (show ((length w) - 2))\n , lastLetter ]\n where\n firstLetter = take 1 w\n lastLetter = take 1 (reverse w)\n\nmain :: IO ()\nmain = do\n nCases <- readNumber\n replicateM_ nCases $ do\n word <- getLine\n putStrLn (if (length word) > 10\n then abbreviateWord word\n else word)\n"}, {"source_code": "f xs \n | length xs < 11 = xs\n | otherwise = [head xs] ++ l ++ [last xs]\n where l = show (length xs - 2)\n\nmain = interact $ unlines . map f . tail . lines\n"}, {"source_code": "module Main where\n\n--import Debug.Trace\n\nimport Control.Monad\nimport Control.DeepSeq\nimport Data.Function\nimport Data.Ratio\nimport Data.Fixed\nimport Data.List\nimport Data.Char\n\ngetWords = words <$> getLine :: IO [String]\ngetInts = map read <$> getWords :: IO [Int]\ngetDoubles = map read <$> getWords :: IO [Double]\ngetInt = read <$> getLine :: IO Int\ngetDouble = read <$> getLine :: IO Double\nprintLines = fmap head . sequence . map putStrLn\n\nabbreviate w = abb w 0 where\n abb [c] n = show (n-1) ++ [c]\n abb (c:cs) 0 = c : abb cs 1\n abb (c:cs) n = abb cs (n+1)\n\nprocess :: String -> String\nprocess w = if length w > 10 then abbreviate w else w\n\nmain = do\n n <- getInt\n lines <- replicateM n getLine\n printLines $ map process lines\n\n"}, {"source_code": "import Control.Monad (forM_)\n\nmain = (\\x -> forM_ [1..x] $ const (((\\ y -> if length y > 10 then head y:(show $ length y - 2) ++ last y:[] else y) <$> getLine) >>= putStrLn)) =<< (readLn :: IO Int)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nonecase= do\n\t\tx<-getLine\n\t\tlet s= length x\n\t\tputStrLn $ if s <=10 then x else ( [head x ] ++show(s-2) ++[last x])\n\t\t\n\nmain= do\n\tw<- read <$> getLine:: IO Int\n\treplicateM_ w onecase"}, {"source_code": "main = do\n n <- readLn\n arr <- sequence (replicate n getLine)\n let b = fmap shrt arr\n mapM putStrLn b\n \nshrt :: String -> String\nshrt x = if length x <= 10 then x else ((head x) : (show $ length x - 2) ++ (last x :[]))"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\n\ntext = [ \"4\"\n , \"word\"\n , \"localization\"\n , \"internationalization\"\n , \"pneumonoultramicroscopicsilicovolcanoconiosis\"\n ]\n\n\n\nf text = if len > 10 then [f] ++ show (len - 2) ++ [l] else text\n where\n len = length text\n f = head text\n l = last text\n\nmain :: IO ()\nmain = do { _:ts <- lines <$> getContents\n ; mapM_ (printf \"%s\\n\") . map f $ ts\n }\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\n\ntext = [ \"4\"\n , \"word\"\n , \"localization\"\n , \"internationalization\"\n , \"pneumonoultramicroscopicsilicovolcanoconiosis\"\n ]\n\n\n\nf text = if len > 10 then [f] ++ show (len - 2) ++ [l] else text\n where\n len = length text\n f = head text\n l = last text\n\nmain :: IO ()\nmain = do { _:ts <- lines <$> getContents\n ; mapM_ (printf \"%s\\n\") . map f $ ts\n }\n\n\n\n"}, {"source_code": "import Control.Monad ( replicateM\n , foldM\n )\n\nsolve :: String -> String\nsolve s\n | length s <= 10 = s\n | otherwise = abbr s\n where\n abbr :: String -> String\n abbr s = (head s):[] ++ show (length s - 2) ++ (last s):[]\n\nmain :: IO ()\nmain = do\n n <- getInt\n lines <- replicateM n getLine\n mapM_ (putStrLn . solve) lines\n\n where\n getInt :: IO Int\n getInt = do\n line <- getLine\n return ( read line :: Int )"}, {"source_code": "process :: Int -> String -> String\nprocess n str\n | len > n = [head str] ++ show (len-2) ++ [last str]\n | otherwise = str\n where len = length str\n\nreadInt :: String -> Int\nreadInt = read\n \nmain = do\n n <- fmap readInt getLine\n strs <- fmap lines getContents\n sequence . map (putStrLn . process 10) $ strs"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\nimport Data.Maybe\nimport Data.Char\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Ratio\nimport Data.IORef\n-- import Data.Array.IO\nimport Control.Monad\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport Text.Printf\n-- import Debug.Trace\nimport System.Exit\n\n\n\nsolveCase t n\n | t == n = return ()\n | otherwise = getLine >>= putStrLn . solve >> solveCase (t + 1) n\n where\n solve s | l <= 10 = s\n | otherwise = [head s] ++ show (l - 2) ++ [last s]\n where\n l = length s\n\nmain = (readLn :: IO Int) >>= solveCase 0\n"}, {"source_code": "import Control.Monad\n\nsolve :: String -> String\nsolve s =\n let len = length s\n in if len <= 10\n then s\n else ([s!!0] ++ (show(len - 2)) ++ [s!!(len-1)])\n\nmain :: IO ()\nmain = do\n n <- getLine\n inputs <- replicateM (read n) getLine\n let answers = map solve inputs\n sequence_ (map putStrLn answers)"}, {"source_code": "import Control.Monad\nf str@(x:xs)\n\t| length str > 10 = x : show (length str - 2) ++ [last str]\n\t| otherwise = str\n\nmain = do\n\tn <- readLn\n\treplicateM_ n (do\n\t\ts <- getLine\n\t\tputStrLn (f s))\n"}, {"source_code": "-- http://codeforces.com/problemset/problem/71/A\n\nabbreviate :: String -> String\nabbreviate w =\n if length w <= 10\n then w\n else [head w] ++ show ((length w) - 2) ++ [last w]\n\nmain = do\n n <- getLine\n contents <- getContents\n putStr $ unlines $ map abbreviate $ lines contents"}, {"source_code": "import Control.Monad\n\nabbreviate s\n | length s <= 10 = s\n | otherwise = head s : show(length s - 2) ++ [last s]\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n s <- getLine\n putStrLn $ abbreviate s\n"}, {"source_code": "main :: IO ()\nmain = interact $ output\n\ncompactWord :: String -> String\ncompactWord x = firstLetter x ++ middleSize x ++ endLetter x\n where\n firstLetter x = take 1 x\n middleSize x = (show . length) (init $ tail x)\n endLetter x = drop ((length x) - 1) x\n\ntransformWord :: String -> String\ntransformWord x | (length x) > 10 = compactWord x\n | otherwise = x\n\ninput :: [String] -> [String]\ninput inputWords = map transformWord inputWords\n\noutput :: String -> String\noutput = unlines . input . tail . lines\n"}, {"source_code": "f s\n | l > 10 = (head s : show (l - 2)) ++ [last s]\n | otherwise = s\n where\n l = length s\n\nmain = interact $ unlines.map f.tail.lines"}, {"source_code": "import Control.Monad \n\nreadNLines :: Int -> IO [String]\nreadNLines n = replicateM n getLine\n\ncheckAndConstructWord :: String -> String\ncheckAndConstructWord x\n | length x > 10 = (charToString $ head x)++(show $ length x - 2)++(charToString $ x!!(length x - 1))\n | otherwise = x\n where charToString y = [y]\n\nmain :: IO()\nmain = do\n n <- readLn :: IO Int\n x <- readNLines n\n mapM_ putStrLn $ map checkAndConstructWord x"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- getLine\n let times = read n ::Int\n forM [1..times] (\\i -> do\n word <- getLine\n putStrLn $ waytoolong word)\n\nwaytoolong :: String -> String\nwaytoolong w\n | length w <= 10 = w\n | otherwise = head w : (show $ length w - 2) ++ [last w]"}, {"source_code": "import Prelude\n\ntoInt::[String] -> Integer\ntoInt (x:xs) = read x\n\nfirs::[Char] -> Char\nfirs = head\n\nlas::[Char] -> Char\nlas = firs . reverse\n\ncnt::[Char] -> Integer\ncnt [] = (-2)\ncnt (x:xs) = 1 + (cnt xs)\n\nfunc::Integer -> IO ()\nfunc 0 = return ()\nfunc x = do\n input <- getLine\n putStrLn $ if ((cnt input) > 8) then ([firs input]++(show (cnt input))++[las input]) else input\n func (x-1)\n \nmain = do\n\tinput <- getLine\n\tlet n = toInt (words input)\n\tfunc n"}, {"source_code": "main = do\n getLine\n as <- fmap lines getContents\n let\n bs = map f as\n f s\n | length s <= 10 = s\n | otherwise = [head s] ++ (show $ length s - 2) ++ [last s]\n \n putStr $ unlines $ bs"}, {"source_code": "main = do\n\tn <- getLine \n\tinteract$ (unlines.map s).lines\ns a\n\t| length a > 10 = [head a] ++ show ((length a)-2) ++ [last a]\n\t| otherwise = a\n"}, {"source_code": "import Data.List\nmain = interact $ intercalate \"\\n\" . map solve . tail . lines\nsolve xs\n | length xs > 10 = [head xs] ++ (show . (subtract 2) . length $ xs) ++ [last xs]\n | otherwise = xs\n"}, {"source_code": "s :: String -> String\ns word =\n if length word <= 10\n then word\n else h ++ [last word]\n where\n h = head word : (show $ (length word) - 2)\n \nsolve :: Int -> [String] -> [String]\nsolve 1 (x:_) = [s x]\nsolve n (x:xs) = s x : solve (n - 1) xs\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do\n (n:_) <- readInts\n c <- getContents\n putStrLn (unlines $ solve n (lines c))\n"}, {"source_code": "import Data.Maybe\nimport Control.Monad\n \nmain = do\n numCasesLine <- getLine\n let numCases = (read numCasesLine) :: Int in replicateM_ numCases processCase\n where\n processCase = do\n line <- getLine\n if length line > 10\n then putStrLn $ (head line) : show ((length line) - 2) ++ [last line]\n else putStrLn line"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\n\ngetInt = fst . fromJust . B.readInt\n\nprocWord w\n | l <= 10 = w\n | otherwise = (head w) : (show $ l - 2) ++ [last w]\n where\n l = length w\n\nmain = do\n n <- getInt <$> B.getLine\n replicateM_ n $ fmap procWord getLine >>= putStrLn"}, {"source_code": "import System.IO (readFile, getLine)\nimport Data.Char (digitToInt)\nimport Data.List (intercalate)\nimport Control.Monad (sequence)\nimport Text.Printf (printf)\n\n\nabr_internal :: Int -> String -> Maybe (Int, Char)\nabr_internal n [h] = Just (n + 1, h)\nabr_internal n (h:s) = abr_internal (n + 1) s\nabr_internal n [] = Nothing\n\nabbreviate :: String -> String\nabbreviate s = case abr_internal 0 s of\n Nothing -> error \"Invalid string passwd\"\n (Just (n, c)) -> if n > 10 then (head s) : (printf \"%d\" (n - 2)) ++ [c] else s\n\n\nabbreviateInput :: Int -> IO [String]\nabbreviateInput n | n <= 0 = return ([] :: [String])\n | otherwise = do \n s <- getLine\n rtail <- abbreviateInput (n-1)\n return ((abbreviate s) : rtail)\n\nmain = do \n cnt_s <- getLine\n result <- abbreviateInput ((read cnt_s) :: Int)\n mapM putStrLn result"}, {"source_code": "import System.IO\nmain = \n do\n n <- readLn :: IO Int\n f n\n \nf 0 = return ()\nf n = \n do\n s <- getLine\n --let s = read t :: String\n if length s <= 10\n then putStrLn s\n else let str = head s : show (length s - 2) ++ [last s]\n in putStrLn str\n f (n-1)"}, {"source_code": "extract (x:xs)=take (read x::Int) xs\nf x\n\t|l<=10 = x\n\t|otherwise = head x:(show (l-2)++[last x])\n\twhere l=length x\nmain=interact$unlines.map f.extract.lines"}, {"source_code": "{-# LANGUAGE CPP, TemplateHaskell #-}\n\nmodule Main (\n main\n) where\n\nimport Control.Monad (unless)\nimport Data.List (stripPrefix)\nimport System.Exit (exitFailure)\n\n#ifdef MAIN_FUNCTION\nimport Test.Framework.TH\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\nimport Test.Framework.Providers.QuickCheck2\n\nimport Test.QuickCheck\nimport Test.HUnit\n\nimport Data.List\n#endif\n\n\nabbrevate all@(h:s)\n | len <=10 = all\n | otherwise = [h] ++ show (len - 2) ++ [head $ reverse s] \n where len = length all\n\nprocess 0 = do\n return ()\nprocess n = do\n s <- getLine\n putStrLn (abbrevate s)\n process (n-1)\n\nexeMain = do\n [n] <- (map read . words) `fmap` getLine\n\n process n\n\n-- Tests --\n\n#ifdef MAIN_FUNCTION\ntestMain = $(defaultMainGenerator)\n\n\n\n\n#endif\n\n#ifndef MAIN_FUNCTION\n#define MAIN_FUNCTION exeMain\n#endif\nmain = MAIN_FUNCTION"}, {"source_code": " main=interact$unlines.map f.tail.lines\n l=length\n f x|l x<11=x|1>0=(head x:show(l x-2))++[last x]"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nmain = do\n n <- read <$> getLine\n mapM_ (\\_ -> do\n s <- getLine\n let m = length s\n if m > 10 then\n printf \"%c%d%c\\n\" (head s) (m-2) (last s)\n else putStrLn s\n ) [1..n]"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n n <- getLine\n let\n go n =\n if n == 0 then\n return ()\n else do\n line <- getLine\n (putStrLn . shortenString) line\n go $ n - 1\n go $ read n\n\nshortenString :: String -> String\nshortenString string = let\n helper :: Int -> String -> String\n helper n (char : \"\")\n | n > 9 = head string : (show $ n - 1) ++ [char]\n | otherwise = string\n helper n (char : chars) = helper (n + 1) chars\n in helper 0 string\n"}, {"source_code": "\nclear xs = [x | x <- xs, x /= '\\'']\n\nsolve :: [Char] -> String\n\nsolve x\n\t| len <= 10 = x\n\t| otherwise = clear (show (x !! 0) ++ (show (len-2)) ++ (show (x !! (len-1))))\n\twhere len = length x\n\nmain = interact $ unlines . map solve . tail . words\n"}, {"source_code": "import Data.Char\nimport Data.List\n\nans str = if l<11 then str\n else [head str] ++ show (l-2) ++ [last str] \n where l = length str\nmain=do\n input<-getContents\n putStr.unlines $ map ans $tail.lines $ input "}, {"source_code": "main=interact$unlines.map f.tail.lines\nf l@(x:xs)\n\t|length l<=10 = l\n\t|otherwise = [x] ++ (show ((length l)-2)) ++ [last xs]"}, {"source_code": "import Control.Monad\n\nmain :: IO ()\nmain = do\n n <- getLine\n inputs <- replicateM (read n) getLine\n mapM_ putStrLn $ fmap abbreviate inputs\n\nabbreviate :: String -> String\nabbreviate s\n | l <= 10 = s\n | otherwise = [head s] ++ show (l - 2) ++ [last s]\n where l = length s"}, {"source_code": "solve s\n | l > 10 = [head s] ++ (show (l-2)) ++ [last s]\n | otherwise = s\n where\n l = length s \nmain = putStrLn . unlines . map solve . tail . lines =<< getContents"}, {"source_code": "import Control.Monad\nmain=do\n n<-fmap read getLine\n replicateM_ n$getLine>>=putStrLn.q\nq s|t<=10=s\n |True=head s:(show$t-2)++[last s]\n where t=length s\n"}, {"source_code": "import Control.Monad\n\nmain = do\n line <- getLine\n let count = read line :: Int\n replicateM_ count $ getLine >>= putStrLn . solve\n\nsolve :: String -> String\nsolve s = solve' s $ length s\n where solve' s len | len <= 10 = s\n | otherwise = head s : (show $ len - 2) ++ [last s]\n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- fmap read getLine\n replicateM_ n $ getLine >>= putStrLn . solve\n\nsolve s | len <= 10 = s\n | otherwise = head s : (show $ len - 2) ++ [last s]\n where\n len = length s\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n replicateM_ n $ do\n q <- B.getLine\n let r = simplify . head . C.words $ q\n -- C.putStrLn . C.pack . show $ (B.length q)\n C.putStrLn r\n\nsimplify :: B.ByteString -> B.ByteString\nsimplify s = sim s (B.length s)\n where\n sim s l\n | l <= 10 = s\n | otherwise = B.concat $ [prefix s, intToBs (l - 2), suffix s]\n prefix = B.singleton . B.head\n suffix = B.singleton . B.last\n intToBs i = C.pack . show $ i\n"}, {"source_code": "import Data.Char\n\ntransformWord :: String -> String\ntransformWord word\n | (length word <= 10) = word\n | otherwise = [head word] ++ (show $ length word - 2) ++ [last word]\n\ngetWords :: Integer -> IO [[Char]]\ngetWords wordsLeft = do\n if wordsLeft == 0\n then return []\n else do\n line <- getLine\n stuff <- getWords (wordsLeft - 1)\n return (line : stuff)\n\nprintWords [] = return ()\nprintWords wordsList = do\n putStrLn $ head wordsList\n printWords $ tail wordsList\n\nmain = do\n line <- getLine\n let numWords = read line :: Integer\n wordsList <- getWords numWords\n let newWords = map transformWord wordsList\n printWords newWords"}, {"source_code": "main=interact$unlines.map f.tail.lines\nl=length\nf x|l x<11=x|1>0=(head x:show(l x-2))++[last x]\n"}, {"source_code": "import Control.Applicative\n\nprocess x | length x <=10 = x\n | otherwise = [head x]++ (show (length x -2))++ [last x]\n\n\nmain=do\n x<-tail .lines <$> getContents\n mapM_ putStrLn $ map process x\n"}, {"source_code": "convertStr contents = if (length contents) > 10 then putStr ([(contents !! 0)] ++ (show ((length contents) - 2)) ++ [(contents !! ((length contents) - 1))] ++ \"\\n\") else putStr (contents ++ \"\\n\")\n\noutputI18 1 = do\n contents <- getLine\n convertStr contents\noutputI18 n = do\n contents <- getLine\n convertStr contents\n outputI18 (n-1)\n\nmain = do\n input1 <- getLine\n let n = (read input1 :: Int)\n outputI18 n"}], "negative_code": [{"source_code": "\nmain = do\n rs <- getLine\n putStr (result rs)\n\nresult rs\n | length rs > 10 = (head rs):(long rs) ++ ((last rs):[])\n | otherwise = rs\n\nlong rs = show (length rs - 2)\n"}, {"source_code": "main = getContents>>=mapM_ print.map slv.tail.words\nslv w\n | len > 10 = head w : (show $ len-2) ++ [last w]\n | True = w\n where len = length w"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n replicateM_ n $ do\n r <- B.getLine\n let s = simplify r\n C.putStrLn s\n\nsolve = (C.putStrLn)\n\nsimplify :: B.ByteString -> B.ByteString\nsimplify s = sim s (B.length s)\n where\n sim :: B.ByteString -> Int -> B.ByteString\n sim s l\n | l < 10 = s\n | otherwise =\n B.concat $\n [ B.singleton . B.head $ s\n , C.pack . show $ (l - 2) :: B.ByteString\n , (B.singleton . B.last $ s)\n ]\n"}, {"source_code": "import Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n replicateM_ n $ do\n r <- B.getLine\n let s = simplify r\n C.putStrLn s\n\nsolve = (C.putStrLn)\n\nsimplify :: B.ByteString -> B.ByteString\nsimplify s = sim s (B.length s)\n where\n sim :: B.ByteString -> Int -> B.ByteString\n sim s l\n | l < 10 = s\n | otherwise =\n B.concat $\n [ B.singleton . B.head $ s\n , C.pack . show $ (l - 2) :: B.ByteString\n , (B.singleton . B.last $ s)\n ]\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n replicateM_ n $ do\n q <- B.getLine\n let r = simplify . head . C.words $ q\n -- C.putStrLn . C.pack . show $ (B.length q)\n C.putStrLn r\n\nsimplify :: B.ByteString -> B.ByteString\nsimplify s = sim s (B.length s)\n where\n sim s l\n | l < 10 = s\n | otherwise = B.concat $ [prefix s, intToBs (l - 2), suffix s]\n prefix = B.singleton . B.head\n suffix = B.singleton . B.last\n intToBs i = C.pack . show $ i\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n replicateM_ n $ do\n q <- B.getLine\n let r = simplify . strip $ q\n C.putStrLn r\n\nstrip = B.filter (\\s -> s /= (B.head \" \"))\n\nsimplify :: B.ByteString -> B.ByteString\nsimplify s = sim s (B.length s)\n where\n sim s l\n | l < 10 = s\n | otherwise = B.concat $ [prefix s, intToBs (l - 2), suffix s]\n prefix = B.singleton . B.head\n suffix = B.singleton . B.last\n intToBs i = C.pack . show $ i\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Monad.Writer.Strict (liftM, replicateM_)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n n <- read `fmap` getLine :: IO Int\n replicateM_ n $ do\n q <- B.getLine\n let r = simplify . strip $ q\n C.putStrLn . C.pack . show $ (B.length q)\n C.putStrLn r\n\nstrip = B.filter (\\s -> s /= (B.head \" \"))\n\nsimplify :: B.ByteString -> B.ByteString\nsimplify s = sim s (B.length s)\n where\n sim s l\n | l < 10 = s\n | otherwise = B.concat $ [prefix s, intToBs (l - 2), suffix s]\n prefix = B.singleton . B.head\n suffix = B.singleton . B.last\n intToBs i = C.pack . show $ i\n"}, {"source_code": "import Data.Char\n\ntransformWord :: String -> String\ntransformWord word\n | (length word <= 10) = word\n | otherwise = [head word] ++ (show $ length word) ++ [last word]\n\ngetWords :: Integer -> IO [[Char]]\ngetWords wordsLeft = do\n if wordsLeft == 0\n then return []\n else do\n line <- getLine\n stuff <- getWords (wordsLeft - 1)\n return (line : stuff)\n\nprintWords [] = return ()\nprintWords wordsList = do\n putStrLn $ head wordsList\n printWords $ tail wordsList\n\nmain = do\n line <- getLine\n let numWords = read line :: Integer\n wordsList <- getWords numWords\n let newWords = map transformWord wordsList\n printWords newWords"}, {"source_code": "import qualified Data.ByteString.Char8 as B8\nimport qualified Data.ByteString as B\nimport Control.Arrow\n\nsolve :: B.ByteString -> B.ByteString\nsolve s\n | B.length s > 10 = B.snoc (B.cons (B.head s) (B8.pack (show $ B.length s - 2))) (B.last s)\n | otherwise = s\n\nmain :: IO ()\nmain = B.interact $\n B8.lines >>> map solve . tail >>> B8.unlines "}, {"source_code": "import qualified Data.ByteString.Char8 as B8\nimport qualified Data.ByteString as B\nimport Control.Arrow\n\nsolve :: B.ByteString -> B.ByteString\nsolve s\n | B.length s > 10 = B.snoc (B.cons (B.head s) (B8.pack (show $ B.length s - 2))) (B.last s)\n | otherwise = s\n\nmain :: IO ()\nmain = B.interact $\n B8.lines >>> map solve . tail >>> B8.unlines "}, {"source_code": "import Control.Arrow\n\nsolve :: String -> String\nsolve s@(x:xs)\n | length s > 10 = [x] ++ show (length s - 2) ++ [last s]\n | otherwise = s\n\nmain :: IO ()\nmain = interact $\n lines >>> map solve >>> unlines "}, {"source_code": "import qualified Data.ByteString.Char8 as B8\nimport qualified Data.ByteString as B\nimport Control.Arrow\n\nsolve :: B.ByteString -> B.ByteString\nsolve s\n | B.length s > 10 = B8.snoc (B8.cons (B8.head s) (B8.pack (show $ B8.length s - 2))) (B8.last s)\n | otherwise = s\n\nmain :: IO ()\nmain = B.interact $\n B8.lines >>> map solve . tail >>> B8.unlines "}, {"source_code": "import Control.Monad\n\ngenAns s\n | n < 10 = s\n | otherwise = a:(show (n-2)) ++ [b]\n where\n n = length s\n (a,b) = (head s, last s)\n\n\nmain = do\n n <- readLn :: IO Int\n forM_ [1..n] $ \\i -> do\n aa <- getLine\n putStrLn $ genAns aa \n"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = interact $ unlines . map solve . tail . words\n\nsolve :: String -> String\nsolve xs\n | len <= 10 = xs\n | otherwise = [head xs] ++ show len ++ [last xs]\n where len = length xs"}, {"source_code": "g :: [Char] -> [Char]\ng s\n | length s > 10 = [head s] ++ (show . length $ s) ++ [last s]\n | otherwise = s\n\nmain = interact $ tail . init . show . g"}, {"source_code": "import Control.Monad\n\nsolve :: String -> String\nsolve s =\n let len = length s\n in if len < 10\n then s\n else ([s!!0] ++ (show(len - 2)) ++ [s!!(len-1)])\n\nmain :: IO ()\nmain = do\n n <- getLine\n inputs <- replicateM (read n) getLine\n let answers = map solve inputs\n sequence_ (map putStrLn answers)"}, {"source_code": "import Control.Applicative\n\nsolve xs\n |length xs <= 10 = xs\n |otherwise = abbr xs\n\nabbr xs = (take 1 xs) ++ show (length xs - 2) ++ (take 1 $ reverse xs)\n\nmain = do\n result <- map solve . tail . lines <$> getContents\n print result\n"}, {"source_code": "import Control.Applicative\n\nsolve xs\n |length xs < 10 = xs\n |otherwise = abbr xs\n\nabbr xs = (take 1 xs) ++ show (length xs - 2) ++ (take 1 $ reverse xs)\n\nmain = do\n result <- unlines . map solve . lines . tail <$> getContents\n putStrLn result\n"}, {"source_code": "import Control.Applicative\n\nsolve xs\n |length xs <= 10 = xs\n |otherwise = abbr xs\n\nabbr xs = (take 1 xs) ++ show (length xs - 2) ++ (take 1 $ reverse xs)\n\nmain = do\n result <- unlines . map solve . lines . tail <$> getContents\n putStrLn result\n"}, {"source_code": "import Control.Monad\n\nmain = do\n n <- getLine\n let times = read n ::Int\n forM [1..times] (\\i -> do\n word <- getLine\n putStrLn $ waytoolong word)\n\nwaytoolong :: String -> String\nwaytoolong w\n | length w <= 4 = w\n | otherwise = head w : (show $ length w - 2) ++ [last w]"}, {"source_code": "main = do\n getLine\n as <- fmap lines getContents\n let\n bs = map f as\n f s\n | length s > 10 = s\n | otherwise = [head s] ++ (show $ length s - 2) ++ [last s]\n \n putStr $ unlines $ bs"}, {"source_code": "main = do\n\tn <- getLine \n\tinteract$ (unlines.map s).lines\ns a\n\t| length a > 10 = [head a] ++ (show (length a)) ++ [last a]\n\t| otherwise = a\n"}, {"source_code": "import Data.List\nmain = interact $ intercalate \"\\n\" . map solve . tail . lines\nsolve xs\n | length xs > 10 = [head xs] ++ (show . length $ xs) ++ [last xs]\n | otherwise = xs\n"}, {"source_code": "s :: Int -> String -> String\ns n word =\n if length word <= n\n then word\n else h ++ [last word]\n where\n h = head word : (show $ (length word) - 2)\n \nsolve :: Int -> [String] -> [String]\nsolve n words =\n map (s n) words\n\nreadInts :: IO [Int]\nreadInts = fmap (map read.words) getLine\n\nmain = do\n (n:_) <- readInts\n c <- getContents\n putStrLn (unlines $ solve n (lines c))\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\n \nmain = do\n numCases <- fst . fromJust . B.readInt <$> B.getLine\n replicateM_ numCases processCase\n where\n processCase = do\n line <- B.getLine\n if B.length line > 10\n then putStrLn $ (B.head line) : show ((B.length line) - 2) ++ [B.last line]\n else putStrLn . tail . init . show $ line"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\n \nmain = do\n numCases <- fst . fromJust . B.readInt <$> B.getLine\n replicateM_ numCases processCase\n where\n processCase = do\n line <- B.getLine\n if B.length line > 10\n then putStrLn $ (B.head line) : show ((B.length line) - 2) ++ [B.last line]\n else putStrLn . tail . init . init . show $ line"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Monad\n \nmain = do\n numCases <- fst . fromJust . B.readInt <$> B.getLine\n replicateM_ numCases processCase\n where\n processCase = do\n line <- B.getLine\n if B.length line > 10\n then putStrLn $ (B.head line) : show ((B.length line) - 2) ++ [B.last line]\n else putStrLn . tail . init . init. init . show $ line"}, {"source_code": "import System.IO (readFile, getLine)\nimport Data.Char (digitToInt)\nimport Data.List (intercalate)\nimport Control.Monad (sequence)\nimport Text.Printf (printf)\n\n\nabr_internal :: Int -> String -> Maybe (Int, Char)\nabr_internal n [h] = Just (n, h)\nabr_internal n (h:s) = abr_internal (n + 1) s\nabr_internal n [] = Nothing\n\nabbreviate :: String -> String\nabbreviate s = case abr_internal 0 s of\n Nothing -> error \"Invalid string passwd\"\n (Just (n, c)) -> if n > 10 then (head s) : (printf \"%d\" (n - 1)) ++ [c] else s\n\n\nabbreviateInput :: Int -> IO [String]\nabbreviateInput n | n <= 0 = return ([] :: [String])\n | otherwise = do \n s <- getLine\n rtail <- abbreviateInput (n-1)\n return ((abbreviate s) : rtail)\n\nmain = do \n cnt_s <- getLine\n result <- abbreviateInput ((read cnt_s) :: Int)\n mapM putStrLn result"}, {"source_code": "import System.IO\nmain = \n do\n n <- readLn :: IO Int\n f n\n \nf 0 = return ()\nf n = \n do\n s <- getLine\n --let s = read t :: String\n if length s < 10\n then putStrLn s\n else let str = head s : show (length s - 2) ++ [last s]\n in putStrLn str\n f (n-1)"}, {"source_code": "extract (x:xs)=take (read x::Int) xs\nf x\n\t|l<=4 = x\n\t|otherwise = head x:(show (l-2)++[last x])\n\twhere l=length x\nmain=interact$unlines.map f.extract.lines"}, {"source_code": "import Control.Monad\n\ncutString :: String -> String\ncutString s\n | (length s) > 10 = [head s] ++ (show ((length s) - 2)) ++ [last s]\n | otherwise = s\n\nreadInt :: IO Int\nreadInt = readLn\n\nmain :: IO ()\nmain = do\n n <- readInt\n strings <- replicateM n getLine\n print $ map cutString strings\n"}, {"source_code": "main = getLine >> getContents >>= putStrLn . unlines . inout . lines\n\ninout :: [String] -> [String]\ninout str = map (func) str\n\nfunc :: String -> String\nfunc wrd = if length wrd < 9 then wrd else codWrd wrd\n\ncodWrd :: String -> String\ncodWrd wrd = head wrd : cutWrd wrd ++ last wrd :[]\n\t\t\twhere cutWrd = show . length . init . tail"}, {"source_code": "main = getLine >> getContents >>= putStrLn . unlines . inout . lines\n\t\t\t\t\ninout :: [String] -> [String]\ninout str = map (func) str\n\nfunc :: String -> String\nfunc wrd = if length wrd < 10 then wrd else codWrd wrd\n\ncodWrd :: String -> String\ncodWrd wrd = head wrd : cutWrd wrd ++ last wrd :[]\n\t\t\twhere cutWrd = show . length . init . tail"}, {"source_code": "{-# LANGUAGE CPP, TemplateHaskell #-}\n\nmodule Main (\n main\n) where\n\nimport Control.Monad (unless)\nimport Data.List (stripPrefix)\nimport System.Exit (exitFailure)\n\n#ifdef MAIN_FUNCTION\nimport Test.Framework.TH\nimport Test.Framework\nimport Test.Framework.Providers.HUnit\nimport Test.Framework.Providers.QuickCheck2\n\nimport Test.QuickCheck\nimport Test.HUnit\n\nimport Data.List\n#endif\n\n\nabbrevate all@(h:s)\n | len <=10 = all\n | otherwise = [h] ++ show (len - 2) ++ [head $ reverse s] \n where len = length all\n\nprocess 0 = do\n return ()\nprocess n = do\n s <- getLine\n print (abbrevate s)\n process (n-1)\n\nexeMain = do\n [n] <- (map read . words) `fmap` getLine\n\n process n\n\n-- Tests --\n\n#ifdef MAIN_FUNCTION\ntestMain = $(defaultMainGenerator)\n\n\n\n\n#endif\n\n#ifndef MAIN_FUNCTION\n#define MAIN_FUNCTION exeMain\n#endif\nmain = MAIN_FUNCTION"}, {"source_code": "f s\n | length s < 10 = s\n | otherwise = head s:show (l-2) ++ [last s]\n where l = length s\nmain = \n interact $ unlines.map f .tail.lines\n"}, {"source_code": "f s\n | length s < 10 = s\n | otherwise = head s:show (l-2) ++ [last s]\n where l = length s\nmain = \n interact $ unlines.map f .lines\n"}, {"source_code": "len [] = 0\nlen (x:xs) = (len xs) + 1\n\nllast [x] = x\nllast (x:xs) = llast xs\n\nsolve (x:xs) | (len xs - 1) > 4 = [x] ++ show (len xs - 1) ++ [llast xs]\n | otherwise = [x] ++ xs\n\ndoSolve 0 = putStr \"\"\ndoSolve n = do\n\tline <- getLine\n\tputStrLn (solve line)\n\tdoSolve (n-1)\n\nmain = do\n\tline <- getLine\n\tdoSolve (read line :: Integer)\n"}, {"source_code": "len [] = 0\nlen (x:xs) = (len xs) + 1\n\nllast [x] = x\nllast (x:xs) = llast xs\n\nsolve (x:xs) | (len xs) > 10 = [x] ++ show (len xs - 1) ++ [llast xs]\n | otherwise = [x] ++ xs\n\ndoSolve 0 = putStr \"\"\ndoSolve n = do\n\tline <- getLine\n\tputStrLn (solve line)\n\tdoSolve (n-1)\n\nmain = do\n\tline <- getLine\n\tdoSolve (read line :: Integer)\n"}, {"source_code": "len [] = 0\nlen (x:xs) = (len xs) + 1\n\nllast [x] = x\nllast (x:xs) = llast xs\n\nsolve (x:xs) | (len xs - 1) > 10 = [x] ++ show (len xs - 1) ++ [llast xs]\n | otherwise = [x] ++ xs\n\ndoSolve 0 = putStr \"\"\ndoSolve n = do\n\tline <- getLine\n\tputStrLn (solve line)\n\tdoSolve (n-1)\n\nmain = do\n\tline <- getLine\n\tdoSolve (read line :: Integer)\n"}, {"source_code": "import Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Text.Printf\n\nmain = do\n n <- read <$> getLine\n mapM_ (\\_ -> do\n s <- B.getLine\n let m = B.length s\n if m > 10 then\n printf \"%c%d%c\\n\" (B.head s) (m-2) (B.last s)\n else B.putStrLn s\n ) [1..n]"}, {"source_code": "abbreviate :: String -> String\nabbreviate input\n | (length input) <= 10 = input\n | otherwise = (\\str -> [head str] ++ (show $ (length str) - 2) ++ [last str]) input\n \n\nmain = interact abbreviate"}, {"source_code": "module Main where\n\nmain :: IO ()\nmain = do\n n <- getLine\n let\n go n =\n if n == 0 then\n return ()\n else do\n line <- getLine\n (putStrLn . shortenString) line\n go $ n - 1\n go $ read n\n\nshortenString :: String -> String\nshortenString string = let\n helper :: Int -> String -> String\n helper n (char : \"\")\n | n > 10 = head string : (show $ n - 1) ++ [char]\n | otherwise = string\n helper n (char : chars) = helper (n + 1) chars\n in helper 0 string\n"}, {"source_code": "main=interact$unlines.map f.tail.lines\nl=length\nf x|l x<10=x|1>0=(head x:show(l x))++[last x]\n"}, {"source_code": "main=interact$unlines.map f.tail.lines\nl=length\nf x|l x<11=x|1>0=(head x:show(l x))++[last x]\n"}, {"source_code": "convertStr contents = if (length contents) > 10 then print ([(contents !! 0)] ++ (show ((length contents) - 2)) ++ [(contents !! ((length contents) - 1))]) else print contents\n\noutputI18 1 = do\n contents <- getLine\n convertStr contents\noutputI18 n = do\n contents <- getLine\n convertStr contents\n outputI18 (n-1)\n\nmain = do\n input1 <- getLine\n let n = (read input1 :: Int)\n outputI18 n"}, {"source_code": "module Main where\n\nimport Control.Arrow\n\nmain = do\n n:ws <- lines `fmap` getContents\n putStr $ ($ ws) $ take (read n) >>> map abbreviation >>> unlines\n where abbreviation w\n | length w > 10 = head w: show (length w) ++ [last w]\n | otherwise = w\n"}, {"source_code": "\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Char \n\nimport qualified Data.ByteString.Char8 as B\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\n\nabbrWord :: String -> String\nabbrWord s \n | length s <= 10 = s\n | otherwise = [head s] ++ show ((-) (length s) 2) ++ [last s] \n\nmain :: IO ()\nmain = do\n n <- readInt\n xs <- replicateM n $ getLine\n print xs\n mapM_ putStrLn $ map abbrWord xs "}, {"source_code": "import Control.Monad\n\nshorten :: String -> String\nshorten w | length w > 10 = [head w] ++ show (length w - 2) ++ [last w]\n | otherwise = \"test\"\n\nmain = do n <- fmap read getLine\n strings <- sequence $ take n (repeat getLine)\n forM_ strings (putStrLn . shorten)\n\n"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n rep n solve\n\nrep 0 x = return ()\nrep n x = x >> rep (n-1) x\n\n\nsolve :: IO ()\nsolve = do\n cs <- getLine\n let l = length cs\n putStrLn $\n if l > 4\n then (head cs) : (show (l-2))++[(last cs)]\n else cs\n \n\n"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n rep n solve\n\nrep 0 x = return ()\nrep n x = print n >> x >> rep (n-1) x\n\n\nsolve :: IO ()\nsolve = do\n cs <- getLine\n let l = length cs\n putStrLn $\n if l > 4\n then (head cs) : (show (l-2))++[(last cs)]\n else cs\n \n\n"}, {"source_code": "module Main where\n\nisTooLong word = length word > 10\nlengthBetweenFirstAndLast word = length word - 2\nsolveCases remainingCases results = do\n word <- getLine\n let result = if isTooLong word then ([head word] ++ (show $ lengthBetweenFirstAndLast word) ++ [last word]) else word\n if remainingCases - 1 > 0 then solveCases (remainingCases - 1) (results ++ [result]) else return (results ++ [result])\n\nmain = do\n line <- getLine\n let caseCount = read line :: Int\n results <- solveCases caseCount []\n mapM print results\n"}, {"source_code": "f w = let n = length w in if n<10 then w else [w!!0] ++ show (n-2) ++ [w!!(n-1)]\n\ng _ = do\n w <- getLine\n print . f $ w\n \nmain = do\n n <- getLine\n mapM_ g [1..read$n]"}, {"source_code": "f w = let n = length w in if n<10 then w else [w!!0] ++ show (n-2) ++ [w!!(n-1)]\n\ng _ = do\n w <- getLine\n putStrLn . f $ w\n \n\nmain = do\n n <- getLine\n mapM_ g [1..read$n]"}, {"source_code": "shorten s | length s < 10 = s\n | otherwise = head s : show (length s - 2) ++ [last s]\nmain = interact $ unlines . map shorten . tail . lines"}, {"source_code": "func [] = []\nfunc str\n |(length str > 4) =\n let \n left = head str\n center = (show $ length $ tail $ init str)\n right = last str\n in reverse ((:) right (reverse ((:) left center)))\n |otherwise = str\nmain :: IO()\nmain = do\n a <- getLine\n putStrLn $ func a"}, {"source_code": "func x\n |((length x) < 10) = x\n |otherwise = (:) (head x) (reverse ((:) (last x) (reverse $ show ((length x) - 2))))\nmain :: IO()\nmain = do\n a <- getLine\n print $ func a"}, {"source_code": "func [] = []\nfunc str\n |(length str > 4) =\n let \n left = head str\n center = (show $ length $ tail $ init str)\n right = last str\n in reverse ((:) right (reverse ((:) left center)))\n |otherwise = str\n\nfunc2 :: Int -> IO()\nfunc2 n =\n if n > 0 \n then do\n str <- getLine\n putStrLn $ func str\n func2 (n - 1)\n else return ()\nmain :: IO()\nmain = do\n a <- getLine\n func2 (read a::Int)"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve s = if len > 10 then concat [[f], show len, [l]] else s\n\twhere\tlen = (length s) - 2\n\t\tl = last s\n\t\t(f:_) = s\n\nmain = do\n\tsn <- getLine\n\tlet n = read sn :: Int\n\tforM [1..n]\t(\\_ -> do\n\t\t\t\tln <- solve <$> getLine\n\t\t\t\tputStrLn $ ln\n\t\t\t)\n\treturn ()"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nsolve s = if len > 10 then concat [[f], show len, [l]] else s\n\twhere\tlen = (length s) - 2\n\t\tl = last s\n\t\t(f:_) = s\n\nmain = do\n\tsn <- getLine\n\tlet n = read sn :: Int\n\tres <- forM [1..n]\t(\\_ -> do\n\t\t\t\t\tsolve <$> getLine\n\t\t\t\t)\n\tmapM putStrLn res\n\treturn ()"}, {"source_code": "\nf s = if 10 < length s then\n [head s] ++ (show $ len s) ++ [last s]\n else\n s\n where len s = length $ init $ tail s\n\nmain = interact $ (++ \"\\n\")\n . f\n . head . lines\n"}, {"source_code": "import Control.Monad\n\nmain = do\n lines <- getLine\n let cases = read lines :: Int\n results <- forM [1..cases] (\\_ -> do\n line <- getLine\n let result = solve line\n return result)\n mapM putStrLn results\n\nsolve :: String -> String\nsolve s \n | length s <= 4 = s\n | otherwise = [head s] ++ (show (length s - 2)) ++ [last s]"}, {"source_code": "main :: IO ()\nmain = do\n word <- getLine\n putStrLn $ compress word\n\ncompress :: String -> String\ncompress str\n | tooLong str = first ++ len ++ final\n | otherwise = str\n where first = [head str]\n len = show $ length str - 2\n final = [last str]\n\n\ntooLong :: String -> Bool\ntooLong str = length str > 10"}, {"source_code": "main :: IO ()\nmain = do\n n <- getInt\n ls <- getContents\n putStrLn $ (unlines . map compress . take n . lines) (tail ls)\n\ncompress :: String -> String\ncompress str\n | tooLong str = first ++ len ++ final\n | otherwise = str\n where first = [head str]\n len = show $ length str - 2\n final = [last str]\n\n\ntooLong :: String -> Bool\ntooLong str = length str > 10\n\ngetInt :: IO Int\ngetInt = do\n n <- getLine\n return $ read n"}, {"source_code": "import Control.Monad (replicateM)\n\ncharToString :: Char -> String\ncharToString ch = [ch]\n\ncreateAbbreviation :: String -> String\ncreateAbbreviation str =\n (charToString $ head str) ++ (show $ (length str - 2)) ++ (charToString $ last str)\n\nprocessString :: String -> String\nprocessString str\n | (length str) > 10 = createAbbreviation str\n | otherwise = str\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nprocessCount :: IO Int\nprocessCount = fmap read getLine\n\nprocessItems :: Int -> IO [String]\nprocessItems n =\n getLines n >>= return . fmap processString\n\nmain :: IO ()\nmain = do\n count <- processCount\n items <- processItems count\n print items\n"}, {"source_code": "import Control.Monad (replicateM)\n\ncharToString :: Char -> String\ncharToString ch = [ch]\n\ncreateAbbreviation :: String -> String\ncreateAbbreviation str =\n (charToString $ head str) ++ (show $ length str) ++ (charToString $ last str)\n\nprocessString :: String -> String\nprocessString str\n | (length str) > 10 = createAbbreviation str\n | otherwise = str\n\ngetLines :: Int -> IO [String]\ngetLines n = replicateM n getLine\n\nprocessCount :: IO Int\nprocessCount = fmap read getLine\n\nprocessItems :: Int -> IO [String]\nprocessItems n =\n getLines n >>= return . fmap processString\n\nmain :: IO ()\nmain = do\n count <- processCount\n items <- processItems count\n print items\n"}, {"source_code": "main = interact f\nf s | length s > 10 = [head s] ++ show ( (length s) - 2 ) ++ [last s]\n | otherwise = s"}, {"source_code": "shorten :: String -> String\nshorten s\n | length s <= 10 = s\n | otherwise = [head s] ++ show (length s - 2) ++ [last s]\n\nsolve :: String -> String\nsolve input = unlines $ map shorten $ lines input\n\nmain :: IO ()\nmain = interact solve\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumber :: IO Int\nreadNumber = (fromJust . fmap fst . BS.readInt) `fmap` BS.getLine\n\nabbreviateWord :: BS.ByteString -> BS.ByteString\nabbreviateWord w =\n BS.concat [ BS.pack [firstLetter]\n , BS.pack (show ((BS.length w) - 2))\n , BS.pack [lastLetter] ]\n where\n firstLetter = BS.head w\n lastLetter = BS.head (BS.reverse w)\n\nmain :: IO ()\nmain = do\n nCases <- readNumber\n replicateM_ nCases $ do\n word <- BS.getLine\n BS.putStrLn (if (BS.length word) > 10\n then abbreviateWord word\n else word)\n"}, {"source_code": "module Main where\n\nimport Control.Monad (replicateM_)\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as BS\n\nreadNumber :: IO Int\nreadNumber = (fromJust . fmap fst . BS.readInt) `fmap` BS.getLine\n\nabbreviateWord :: BS.ByteString -> BS.ByteString\nabbreviateWord w =\n BS.concat [ firstLetter\n , BS.pack (show ((BS.length w) - 2))\n , lastLetter ]\n where\n firstLetter = BS.take 1 w\n lastLetter = BS.take 1 (BS.reverse w)\n\nmain :: IO ()\nmain = do\n nCases <- readNumber\n replicateM_ nCases $ do\n word <- BS.getLine\n BS.putStrLn (if (BS.length word) > 10\n then abbreviateWord word\n else word)\n"}, {"source_code": "get_and_parse = do s <- getLine\n let len = length s\n if len <= 10\n then print s\n else print ([(head s)] ++ (show (len-2)) ++ [(last s)])\n\nwork n = if n > 0\n then do get_and_parse\n work (n-1)\n else return ()\n\nmain = do s <- getLine \n let num = read s :: Int \n work num\n"}, {"source_code": "import Control.Monad (forM_)\n\nmain = (\\x -> forM_ [1..x] $ const (((\\ y -> if length y > 10 then head y:(show $ length y) ++ last y:[] else y) <$> getLine) >>= putStrLn)) =<< (readLn :: IO Int)\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\n\nonecase= do\n\t\tx<-getLine\n\t\tlet s= length x\n\t\tif s <=10 then print s else print $ [(head x )] ++show(s-2) ++[(last x)]\n\t\t\n\nmain= do\n\tw<- read <$> getLine:: IO Int\n\treplicateM_ w onecase"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\n\ntext = [ \"4\"\n , \"word\"\n , \"localization\"\n , \"internationalization\"\n , \"pneumonoultramicroscopicsilicovolcanoconiosis\"\n ]\n\n\n\nf text = [f] ++ show (len - 2) ++ [l]\n where\n len = length text\n f = head text\n l = last text\n\nmain = do { _:ts <- lines <$> getContents\n ; mapM_ (printf \"%s\\n\") . map f $ ts\n }\n\n\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\n\ntext = [ \"4\"\n , \"word\"\n , \"localization\"\n , \"internationalization\"\n , \"pneumonoultramicroscopicsilicovolcanoconiosis\"\n ]\n\n\n\nf text = [f] ++ show (len - 2) ++ [l]\n where\n len = length text\n f = head text\n l = last text\n\nmain = do { t:ts <- lines <$> getContents\n ; mapM_ (printf \"%s\\n\") . map f $ ts\n }\n\n\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\n\nf text = [f] ++ show (len - 2) ++ [l]\n where\n len = length text\n f = head text\n l = last text\n\nmain = do { t:ts <- lines <$> getContents\n ; print . map f $ ts\n }\n\n\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}\n{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}\n{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}\nmodule Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\n\ntext = [ \"4\"\n , \"word\"\n , \"localization\"\n , \"internationalization\"\n , \"pneumonoultramicroscopicsilicovolcanoconiosis\"\n ]\n\n\n\nf text = [f] ++ show (len - 2) ++ [l]\n where\n len = length text\n f = head text\n l = last text\n\nmain :: IO ()\nmain = do { _:ts <- lines <$> getContents\n ; mapM_ (printf \"%s\\n\") . map f $ ts\n }\n\n\n\n"}, {"source_code": "module Main where\nimport Control.Applicative\nimport Data.List\nimport Text.Printf\nimport Data.Time\nimport Data.Time.Calendar\n\n\nmain = do { ns <- lines <$> getContents\n ; print ns\n }\n\n\n\n"}, {"source_code": "shorten :: String -> String\nshorten x | length x > 10 = [head x] ++ (show $ length $ init $ tail x) ++ [last x]\n | otherwise = x\n\nmain :: IO ()\nmain = do cont <- getContents\n mapM_ (putStrLn . shorten) $ lines cont"}, {"source_code": "import Data.Char\nimport Data.List\n\nans str = if l<10 then str\n else [head str] ++ show (l-2) ++ [last str] \n where l = length str\nmain=do\n input<-getContents\n putStr.unlines $ map ans $tail.lines $ input "}, {"source_code": "import Data.Char\nimport Data.List\n\nans str = if l<10 then str\n else [head str] ++ show l ++ [last str] \n where l = length str\nmain=do\n input<-getContents\n putStr.unlines $ map ans $tail.lines $ input "}], "src_uid": "6639d6c53951f8c1a8324fb24ef68f7a"} {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Data.List\n\nmain = getLine >>= test.read\ntest 0 = return ()\ntest i = do\n n <- read <$> getLine\n let vs = solve n\n print $ length vs\n putStrLn $ unwords $ map show vs\n test (i - 1)\n\nsolve n = map head $ group $ sort $ as ++ bs where\n r = floor $ sqrt $ fromIntegral n\n as = [0..r]\n bs = map (div n) [1..r]\n", "positive_code": [{"source_code": "import Data.List\nimport Control.Monad\n \ngetList :: (Read a) => IO [a]\ngetList = map read <$> words <$> getLine\n \ngetNLists :: (Read a) => Int -> IO [[a]]\ngetNLists n = sequence $ replicate n getList\n \nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- (readLn :: IO Int)\n let ans = sort $ f n in\n putStrLn $ (show . length $ ans) ++ \"\\n\" ++\n (unwords . map show $ ans)\n \nf :: Int -> [Int]\nf x = 0 : c x 1\n \nc :: Int -> Int -> [Int]\nc x i\n | z > x = []\n | d == div x d = [d]\n | and [div x i == d, div x d == i] = i : d : (c x $ i + 1)\n | otherwise = c x $ i + 1\n where d = div x i\n z = i * i"}, {"source_code": "--solve :: Int -> (Int,[Int])\nimport Data.List \nimport Control.Monad\n--solve :: Int -> Int\nsolve x = (n,l3)\n\twhere\n\t\tn = (if b then x2*2 else x2*2+1)\n\t\tx2 = (floor.sqrt.fromIntegral) x\n\t\tb = x2 ^2 +x2 > x\n\t\tl1=[0..x2]\n\t\tl2=map (\\y -> x `div` y) (tail l1)\n\t\tl3 = if b then l1 ++ (tail $ reverse l2) else l1 ++ (reverse l2)\n\nroutine = do\n\tn <- readLn\n\tlet (x,y)=solve n\n\tprint x\n\tputStrLn $ unwords $ map show y\n\t\nmain= do\n\tn <- readLn\n\treplicateM_ n routine"}, {"source_code": "import Data.List\nimport Control.Monad\n\ngetList :: (Read a) => IO [a]\ngetList = map read <$> words <$> getLine\n\ngetNLists :: (Read a) => Int -> IO [[a]]\ngetNLists n = sequence $ replicate n getList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- (readLn :: IO Int)\n let ans = myNub . sort $ f n in\n putStrLn $ (show . length $ ans) ++ \"\\n\" ++\n (unwords . map show $ ans)\n\nf :: Int -> [Int]\nf x = 0 : x : c x 1\n\nc :: Int -> Int -> [Int]\nc x i\n | z > x = []\n | z == x = [i]\n | and [div x i == d, div x d == i] = i : d : (c x $ i + 1)\n | otherwise = c x $ i + 1\n where d = div x i\n z = i * i\n\nmyNub :: [Int] -> [Int]\nmyNub [x] = [x]\nmyNub (x:y:xs)\n | x == y = myNub (y:xs)\n | otherwise = x : myNub (y:xs)"}], "negative_code": [{"source_code": "import Data.List\nimport Control.Monad\n \ngetList :: (Read a) => IO [a]\ngetList = map read <$> words <$> getLine\n \ngetNLists :: (Read a) => Int -> IO [[a]]\ngetNLists n = sequence $ replicate n getList\n \nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- (readLn :: IO Int)\n let ans = sort $ f n in\n putStrLn $ (show . length $ ans) ++ \"\\n\" ++\n (unwords . map show $ ans)\n \nf :: Int -> [Int]\nf x = 0 : c x 1\n \nc :: Int -> Int -> [Int]\nc x i\n | z > x = []\n | d == div x i = [i]\n | and [div x i == d, div x d == i] = i : d : (c x $ i + 1)\n | otherwise = c x $ i + 1\n where d = div x i\n z = i * i"}, {"source_code": "import Data.List\nimport Control.Monad\n \ngetList :: (Read a) => IO [a]\ngetList = map read <$> words <$> getLine\n \ngetNLists :: (Read a) => Int -> IO [[a]]\ngetNLists n = sequence $ replicate n getList\n \nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- (readLn :: IO Int)\n let ans = sort $ f n in\n putStrLn $ (show . length $ ans) ++ \"\\n\" ++\n (unwords . map show $ ans)\n \nf :: Int -> [Int]\nf x = 0 : c x 1\n \nc :: Int -> Int -> [Int]\nc x i\n | z > x = []\n | z == x = [i]\n | and [div x i == d, div x d == i] = i : d : (c x $ i + 1)\n | otherwise = c x $ i + 1\n where d = div x i\n z = i * i"}], "src_uid": "1fea14a5c21bf301981656cbe015864d"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b] <- map read . words <$> getLine :: IO [Int]\n s <- getLine\n print $! solve a b s\n\ntrimZeros = f . f\n where f = dropWhile (=='0') . reverse\n\nsolve :: Int -> Int -> String -> Int\nsolve a b s = if o > 0 then minimum $ zipWith (+) [o, o-a..a] $ scanl (+) 0 z else 0\n where t = group $ trimZeros s\n o = a * (length $ filter ((=='1') . head) t)\n z = sort $ map ((b*). length) $ filter ((=='0') . head) t\n \n \n \n", "positive_code": [{"source_code": "{-# LANGUAGE ViewPatterns #-}\n\nimport Control.Arrow ((>>>))\nimport Data.List (dropWhileEnd, group)\n\nmain :: IO ()\nmain = interact $ words >>> drop 1 >>> process >>> map show >>> unlines\n\nprocess :: [String] -> [Int]\nprocess [] = []\nprocess ((read -> a):(read -> b):xs:xss) = solve a b xs : process xss\n\nsolve :: Int -> Int -> String -> Int\nsolve a b = sum . map cost . group . dropWhile (== '0') . dropWhileEnd (== '0')\n where\n cost ys\n | head ys == '0' = min 0 $ b * length ys - a\n | otherwise = a\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b] <- map read . words <$> getLine :: IO [Int]\n s <- getLine\n print $! solve a b $ trimZeros s\n\ntrimZeros = f . f\n where f = dropWhile (=='0') . reverse\n\nsolve :: Int -> Int -> String -> Int\nsolve _ _ [] = 0\nsolve a b s = minimum $ zipWith (+) [o, o-a..a] $ scanl (+) 0 z\n where t = group s\n o = a * (length $ filter ((=='1') . head) t)\n z = sort $ map ((b*). length) $ filter ((=='0') . head) t\n \n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [a, b] <- map read . words <$> getLine :: IO [Int]\n s <- getLine\n print $! solve a b s\n\ntrimZeros = f . f\n where f = dropWhile (=='0') . reverse\n\nsolve :: Int -> Int -> String -> Int\nsolve a b s = foldl min 0 $ zipWith (+) [o, o-a..a] $ scanl (+) 0 z\n where t = group $ trimZeros s\n o = a * (length $ filter ((=='1') . head) t)\n z = sort $ map ((b*). length) $ filter ((=='0') . head) t\n \n \n \n"}], "src_uid": "fc01082e3ed7877126e750bc380f5c63"} {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n show `fmap` liftM4 (solve n) poi (replicateM (n - 1) $ liftM2 (,) poi poi) poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n m0 es k0 x = (\\(lt, eq, gt) -> sum lt + sum eq + sum gt) $ dfs (accumArray (flip (:)) [] (1, n) $ concatMap (\\(a, b) -> [(a, b), (b, a)]) es) (\\_ -> (\\(lt, eq, gt) -> (map ((k - 1) *) lt, 0:eq, map ((m - k) *) gt)) . foldl' (\\(!lt, !eq, !gt) (clt, ceq, cgt) -> (combine x lt $ zipWith3 (((+) .) . (+)) clt ceq cgt, combine (x - 1) eq clt, combine x gt $ zipWith (+) clt cgt)) def)\n where\n def = let d = 1:replicate x 0 in (d, d, d)\n k = fromIntegral k0 \n m = fromIntegral m0\n combine hi xs ys = map Mnum $ elems (accumArray (+) 0 (0, hi) [(i + j, getMnum $ x' * y) | (i, x') <- ix xs, (j, y) <- ix ys, i + j <= hi] :: UArray Int Int64)\n where ix = zip [0..]\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)\n\nmbase = 1000000007\nnewtype Mnum = Mnum { getMnum :: Int64 }\ninstance Show Mnum where\n show (Mnum x) = show x\ninstance Num Mnum where\n (Mnum a) + (Mnum b) = Mnum $ (a + b) `rem` mbase\n (Mnum a) * (Mnum b) = Mnum $ (a * b) `rem` mbase\n (Mnum a) - (Mnum b) = Mnum $ (a - b) `mod` mbase\n fromInteger = Mnum . fromInteger\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n show `fmap` liftM4 (solve n) poi (replicateM (n - 1) $ liftM2 (,) poi poi) poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n m0 es k0 x = (\\(!lt, !eq, !gt) -> sum lt + sum eq + sum gt) $ dfs (accumArray (flip (:)) [] (1, n) $ concatMap (\\(a, b) -> [(a, b), (b, a)]) es) (\\_ -> (\\(!lt, !eq, !gt) -> (map ((k - 1) *) lt, 0:eq, map ((m - k) *) gt)) . foldl' (\\(!lt, !eq, !gt) (!clt, !ceq, !cgt) -> (combine x lt $ zipWith3 (((+) .) . (+)) clt ceq cgt, combine (x - 1) eq clt, combine x gt $ zipWith (+) clt cgt)) def)\n where\n def = (d, d, d)\n where d = 1:replicate x 0\n k = Mnum $ fromIntegral k0\n m = Mnum $ fromIntegral m0\n combine hi xs ys = map Mnum $ elems (accumArray (+) 0 (0, hi) [(i + j, getMnum $ x' * y) | (i, x') <- ix xs, (j, y) <- ix ys, i + j <= hi] :: UArray Int Int64)\n where ix = zip [0..]\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)\n\nmbase = 1000000007\nnewtype Mnum = Mnum { getMnum :: Int64}\ninstance Show Mnum where\n show (Mnum x) = show x\ninstance Num Mnum where\n (Mnum a) + (Mnum b) = Mnum $ (a + b) `rem` mbase\n (Mnum a) * (Mnum b) = Mnum $ (a * b) `rem` mbase\n (Mnum a) - (Mnum b) = Mnum $ (a - b) `mod` mbase\n fromInteger = Mnum . fromInteger\n\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n show `fmap` liftM4 (solve n) poi (replicateM (n - 1) $ liftM2 (,) poi poi) poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n m0 es k0 x = (\\(lt, eq, gt) -> sum lt + sum eq + sum gt) $ dfs (accumArray (flip (:)) [] (1, n) $ concatMap (\\(a, b) -> [(a, b), (b, a)]) es) (\\_ -> (\\(!lt, !eq, !gt) -> (map ((k - 1) *) lt, 0:eq, map ((m - k) *) gt)) . foldl' (\\(!lt, !eq, !gt) (clt, ceq, cgt) -> (combine x lt $ zipWith3 (((+) .) . (+)) clt ceq cgt, combine (x - 1) eq clt, combine x gt $ zipWith (+) clt cgt)) def)\n where\n def = let d = 1:replicate x 0 in (d, d, d)\n k = fromIntegral k0 \n m = fromIntegral m0\n combine hi xs ys = map Mnum $ elems (accumArray (+) 0 (0, hi) [(i + j, getMnum $ x' * y) | (i, x') <- ix xs, (j, y) <- ix ys, i + j <= hi] :: UArray Int Int64)\n where ix = zip [0..]\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)\n\nmbase = 1000000007\nnewtype Mnum = Mnum { getMnum :: Int64 }\ninstance Show Mnum where\n show (Mnum x) = show x\ninstance Num Mnum where\n (Mnum a) + (Mnum b) = Mnum $ (a + b) `rem` mbase\n (Mnum a) * (Mnum b) = Mnum $ (a * b) `rem` mbase\n (Mnum a) - (Mnum b) = Mnum $ (a - b) `mod` mbase\n fromInteger = Mnum . fromInteger\n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.List\nimport Data.Array.Unboxed\nimport Data.Int\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = do\n n <- poi\n show `fmap` liftM4 (solve n) poi (replicateM (n - 1) $ liftM2 (,) poi poi) poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n m0 es k0 x = (\\(!lt, !eq, !gt) -> sum lt + sum eq + sum gt) $ dfs (accumArray (flip (:)) [] (1, n) $ concatMap (\\(a, b) -> [(a, b), (b, a)]) es) (\\_ -> (\\(!lt, !eq, !gt) -> (map ((k - 1) *) lt, 0:eq, map ((m - k) *) gt)) . foldl' (\\(!lt, !eq, !gt) (!clt, !ceq, !cgt) -> (combine lt $ zipWith3 (((+) .) . (+)) clt ceq cgt, combine eq clt, combine gt $ zipWith (+) clt cgt)) def)\n where\n def = (d, d, d)\n where d = 1:replicate x 0\n k = Mnum $ fromIntegral k0\n m = Mnum $ fromIntegral m0\n combine xs ys = map Mnum $ elems (accumArray (+) 0 (0, x) [(i + j, getMnum $ x' * y) | (i, x') <- ix xs, (j, y) <- ix ys, i + j <= x] :: UArray Int Int64)\n where ix = zip [0..]\n\n\ndfs :: Array Int [Int] -> (Int -> [b] -> b) -> b\ndfs g f = go 0 1\n where go p u = f u $ map (go u) $ filter (/= p) (g!u)\n\nmbase = 1000000007\nnewtype Mnum = Mnum { getMnum :: Int64}\ninstance Show Mnum where\n show (Mnum x) = show x\ninstance Num Mnum where\n (Mnum a) + (Mnum b) = Mnum $ (a + b) `rem` mbase\n (Mnum a) * (Mnum b) = Mnum $ (a * b) `rem` mbase\n (Mnum a) - (Mnum b) = Mnum $ (a - b) `mod` mbase\n fromInteger = Mnum . fromInteger\n\n"}], "src_uid": "fce9e0e7e8a9a41e3cd9ec20bc606fbd"} {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n (_,_k) <- readIntPair\n let k = fromIntegral _k\n as <- map fromIntegral <$> readInts\n let f x = x * k\n g x = if mod x k == 0 then x `div` k else 2000000000\n go :: (Integer -> Integer) -> M.Map Integer Integer -> [Integer] -> [Integer]\n go _ _ [] = []\n go h m (ra:ras) = v : go h m' ras\n where !v = M.findWithDefault 0 (h ra) m\n m' = M.insertWith (+) ra 1 m\n let bs1 = reverse $ go f M.empty (reverse as)\n bs2 = go g M.empty as\n print $ sum $ zipWith (*) bs1 bs2\n\n-- IO\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair :: IO (Int,Int)\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\n\n-- Utilities\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\nl2p _ = error \"l2p: the input list is too short\"\n\n", "positive_code": [{"source_code": "import Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, findWithDefault, adjust, fromList, (!))\n\nsolve :: Int64 -> [Int64] -> Int64\nsolve 1 a = sum $ foldr loop (`seq` []) a init\n where\n init = fromList . zip a . repeat $ 0\n loop x f cnt = inc: f (adjust (+1) x cnt)\n where\n inc = val * (val - 1) `div` 2\n val = cnt ! x\n\nsolve k a = sum $ foldr loop (`seq` []) a (init, init)\n where\n init = fromList . zip a . repeat $ 0\n\n loop x go (cnt, obs)\n | rem /= 0 = 0: go (cnt', obs)\n | otherwise = val: go (cnt', adjust (+ inc) x obs)\n where\n (y, rem) = x `divMod` k\n cnt' = adjust (+1) x cnt\n inc = findWithDefault 0 y cnt\n val = findWithDefault 0 y obs\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [_, k] <- fmap fromIntegral . parse <$> B.getLine\n a <- fmap fromIntegral . parse <$> B.getLine\n print $ solve k a\n"}, {"source_code": "import Data.Int (Int64)\nimport Data.Maybe (fromJust)\nimport Control.Applicative ((<$>))\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map (Map, findWithDefault, adjust, fromList, (!))\n\nsolve :: Int64 -> [Int64] -> Int64\nsolve 1 a = foldr loop (`seq` 0) a init\n where\n init = fromList . zip a . repeat $ 0\n loop x f cnt = inc + f (adjust (+1) x cnt)\n where\n inc = val * (val - 1) `div` 2\n val = cnt ! x\n\nsolve k a = foldr loop (`seq` 0) a (init, init)\n where\n init = fromList . zip a . repeat $ 0\n\n loop x go (cnt, obs)\n | rem /= 0 = go (cnt', obs)\n | otherwise = val + go (cnt', adjust (+ inc) x obs)\n where\n (y, rem) = x `divMod` k\n cnt' = adjust (+1) x cnt\n inc = findWithDefault 0 y cnt\n val = findWithDefault 0 y obs\n\nparse :: ByteString -> [Int]\nparse line = fst . fromJust . C.readInt <$> C.words line\n\nmain = do\n [_, k] <- fmap fromIntegral . parse <$> B.getLine\n a <- fmap fromIntegral . parse <$> B.getLine\n print $ solve k a\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n (_,_k) <- readIntPair\n let k = fromIntegral _k\n as <- map fromIntegral <$> readInts\n let f x = return $ x * k\n g x = guard (mod x k == 0) >> return (div x k)\n go :: (Integer -> Maybe Integer) -> M.Map Integer Integer -> [Integer] -> [Integer]\n go _ _ [] = []\n go h m (ra:ras) = v : go h m' ras\n where !v = fromMaybe 0 $ h ra >>= flip M.lookup m\n m' = M.insertWith (+) ra 1 m\n let bs1 = reverse $ go f M.empty (reverse as)\n bs2 = go g M.empty as\n print $ sum $ zipWith (*) bs1 bs2\n\n-- IO\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair :: IO (Int,Int)\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\n\n-- Utilities\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\nl2p _ = error \"l2p: the input list is too short\"\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\ndata State = State (M.Map Int64 Int64) (M.Map Int64 Int64) !Int64\nsolve :: [Int64] -> Int64 -> State -> State\nsolve [] _ s = s\nsolve (i:t) k (State c g r) = solve t k (State nc ng nr)\n where\n nc = M.insertWith (+) i 1 c\n ng = fromMaybe g $ do \n guard (i `mod` k == 0)\n v <- M.lookup (div i k) c\n return $ M.insertWith (+) (i*k) v g\n nr = r + M.findWithDefault 0 i g\n\nsolveAux :: [Int64] -> Int64 -> Int64\nsolveAux a k = let State _ _ r = solve a k (State M.empty M.empty 0) in r\n\nmain :: IO ()\nmain = do\n [n,k] <- readInts\n a <- readInts\n print $ solveAux a k\n\n-- IO\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fromJust . fmap fst . B.readInt\nreadInts :: IO [Int64]\nreadInts = map readInt . B.words <$> B.getLine\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\nsolve :: [Int64] -> Int64 -> M.Map Int64 Int64 -> M.Map Int64 Int64 -> Int64 -> Int64\nsolve [] _ _ _ r = r\nsolve (i:t) k !c !g !r = solve t k nc ng nr\n where\n nc = M.insertWith (+) i 1 c\n ng = fromMaybe g $ do \n guard (i `mod` k == 0)\n v <- M.lookup (div i k) c\n return $ M.insertWith (+) (i*k) v g\n nr = r + M.findWithDefault 0 i g\n\nsolveAux :: [Int64] -> Int64 -> Int64\nsolveAux a k = solve a k M.empty M.empty 0\n\nmain :: IO ()\nmain = do\n [n,k] <- readInts\n a <- readInts\n print $ solveAux a k\n\n-- IO\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fromJust . fmap fst . B.readInt\nreadInts :: IO [Int64]\nreadInts = map readInt . B.words <$> B.getLine\n\n\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.Int\nimport Data.Maybe\nimport Control.Monad\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\ndata State = State (M.Map Int64 Int64) (M.Map Int64 Int64) !Int64\nsolve :: [Int64] -> Int64 -> M.Map Int64 Int64 -> M.Map Int64 Int64 -> Int64 -> Int64\nsolve [] _ _ _ r = r\nsolve (i:t) k c g !r = solve t k nc ng nr\n where\n nc = M.insertWith (+) i 1 c\n ng = fromMaybe g $ do \n guard (i `mod` k == 0)\n v <- M.lookup (div i k) c\n return $ M.insertWith (+) (i*k) v g\n nr = r + M.findWithDefault 0 i g\n\nsolveAux :: [Int64] -> Int64 -> Int64\nsolveAux a k = solve a k M.empty M.empty 0\n\nmain :: IO ()\nmain = do\n [n,k] <- readInts\n a <- readInts\n print $ solveAux a k\n\n-- IO\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fromJust . fmap fst . B.readInt\nreadInts :: IO [Int64]\nreadInts = map readInt . B.words <$> B.getLine\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Array.Base\nimport Data.Function(on)\nimport Data.Tuple(swap)\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nmain :: IO ()\nmain = do\n (n,k) <- readIntPair\n as <- readInts\n let f x = let v = fromIntegral x * fromIntegral k :: Int64 in\n if abs v <= 10^(9 :: Int) then\n fromIntegral v \n else\n maxBound\n let g x = if mod x k == 0 then x `div` k else maxBound\n let go :: (Int -> Int) -> M.Map Int Int -> [Int] -> [Int]\n go _ _ [] = []\n go h m (ra:ras) = v : go h m' ras\n where !v = M.findWithDefault 0 (h ra) m\n m' = M.insertWith (+) ra 1 m\n let bs1 = reverse $ go f M.empty (reverse as)\n bs2 = go g M.empty as\n print $ sum $ zipWith (\\a b -> \n fromIntegral a * fromIntegral b :: Integer) bs1 bs2\n\n\n\n-- IO\nreadInt :: B.ByteString -> Int\nreadInt = fromJust . fmap fst . B.readInt\nreadInts :: IO [Int]\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair :: IO (Int,Int)\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadAllInts :: IO [[Int]]\nreadAllInts = map (map readInt . B.words) . B.lines <$> B.getContents\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\n\n-- Utilities\nl2p :: [a] -> (a,a)\nl2p (a:b:_) = (a,b)\nl2p _ = error \"l2p: the input list is too short\"\np2l :: (a,a) -> [a]\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ninf :: Int\ninf = maxBound `div` 2\n\n-- Monad\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i0 judge incr step = sub i0 where \n sub i | judge i = step i >> sub (incr i) \n | otherwise = return ()\nrep_ :: Monad m => Int -> (Int -> m ()) -> m ()\nrep_ n = stepM_ 0 ( (v -> m ()) -> v -> m v\nthru m v = m v >> return v\nmemoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v\nmemoize getter setter key action = do\n mv <- getter key\n case mv of\n Just v -> return v\n Nothing -> action >>= thru (setter key)\n\n-- Array\nnewUArray :: (MArray (STUArray s) e (ST s),Ix i) => \n (i,i) -> e -> ST s (STUArray s i e)\nnewUArray = newArray\nnewBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)\nnewBArray = newArray\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nfromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]\nfromEdges = accumArray (flip (:)) []\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Data.Int\nimport Control.Applicative\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Strict as M\n\ndata State = State !(M.Map Int64 Int64) !(M.Map Int64 Int64) !Int64\n deriving (Show)\n\n\nsolveAux :: [Int64] -> Int64 -> Int64\nsolveAux a k = case solve a (State M.empty M.empty 0) of State _ _ r -> r\n where\n solve :: [Int64] -> State -> State\n solve [] s = s\n solve (i:t) (State c g r) = solve t (State nc ng nr)\n where\n nc = M.insertWith (+) i 1 c\n ng = fromMaybe g $ do\n guard $ i `mod` k == 0\n v <- M.lookup (i `div` k) c\n return $ M.insertWith (+) (i*k) v g\n nr = r + (M.findWithDefault 0 i g)\n\nmain :: IO ()\nmain = do\n -- [n,k] <- (map read . words) <$> getLine\n -- a <- (map read . words) <$> getLine\n [n,k] <- readInts\n a <- readInts\n print $ solveAux a k\n\n\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fromJust . fmap fst . B.readInt\n\nreadInts :: IO [Int64]\nreadInts = map readInt . B.words <$> B.getLine\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n\nimport Data.Int\nimport Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Map.Strict as M\n\ndata State = State !(M.Map Int64 Int64) !(M.Map Int64 Int64) !Int64\n deriving (Show)\n\n\nsolveAux :: [Int64] -> Int64 -> Int64\nsolveAux a k = case solve a (State M.empty M.empty 0) of State _ _ r -> r\n where\n solve :: [Int64] -> State -> State\n solve [] s = s\n solve (i:t) (State c g r) = solve t (State nc ng nr)\n where\n nc = M.insertWith (+) i 1 c\n ng = if i `mod` k == 0 then\n M.insertWith (+) (i*k) (M.findWithDefault 0 (i `div` k) c) g\n else\n g\n nr = r + (M.findWithDefault 0 i g)\n\n\nmain :: IO ()\nmain = do\n -- [n,k] <- (map read . words) <$> getLine\n -- a <- (map read . words) <$> getLine\n [n,k] <- readInts\n a <- readInts\n print $ solveAux a k\n\n\nreadInt :: B.ByteString -> Int64\nreadInt = fromIntegral . fromJust . fmap fst . B.readInt\n\nreadInts :: IO [Int64]\nreadInts = map readInt . B.words <$> B.getLine\n"}], "negative_code": [{"source_code": "#!/usr/bin/env stack\n-- stack --resolver=lts-2.21 --install-ghc runghc\n\nimport Control.Applicative\nimport qualified Data.Map.Strict as M\ndata State = State (M.Map Int Int) (M.Map Int Int) Int\n deriving (Show)\n\nsolve :: [Int] -> Int -> State -> State\nsolve [] _ s = s\nsolve (i:t) k (State c g r) = solve t k (State nc ng nr)\n where\n nc = M.insert i ((M.findWithDefault 0 i c) + 1) c\n ng = if i `mod` k == 0 then\n M.insert (i*k) ((M.findWithDefault 0 (i*k) g) + (M.findWithDefault 0 (i `div` k) c)) g\n else\n g\n nr = r + (M.findWithDefault 0 i g)\n\nsolveAux :: [Int] -> Int -> Int\nsolveAux a k =\n case solve a k (State M.empty M.empty 0) of State _ _ r -> r\n\nmain :: IO ()\nmain = do\n [n,k] <- (map read . words) <$> getLine\n a <- (map read . words) <$> getLine\n let r = solveAux a k\n print r\n\n\n"}], "src_uid": "bd4b3bfa7511410c8e54658cc1dddb46"} {"source_code": "import Control.Monad (replicateM)\nimport Data.Bits ((.|.))\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\nmain = do\n [n] <- getArray\n a <- replicateM n $ getArray\n putStrLn $ unwords $ map show $ map (foldr (.|.) 0 . filter (>=0)) a\n where\n getArray = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine\n", "positive_code": [{"source_code": "import Data.Bits\nmain=interact$unwords.map(show.f.map read.words).tail.lines\nf :: [Int] -> Int\nf xs = foldl(.|.)0$filter(>=0)xs"}], "negative_code": [], "src_uid": "8f342e167e77088ce47f17e5cd475b17"} {"source_code": "import Data.Bits\n\nz = 2^19\n\nsolve :: Int -> Int -> Maybe [Int]\nsolve 1 x = Just [x]\nsolve 2 0 = Nothing\nsolve 2 x = Just $ [1, x `xor` 1]\nsolve n x\n | v >= n = Just $ v : [1..(n-1)]\n | v == 1 = Just $ (v .|. z) : 1 : (2 .|. z) : [3..(n-1)]\n | otherwise = Just $ (v .|. z) : (1 .|. z) : [2..(n-1)]\n where v = foldl xor x [1..(n-1)]\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n case solve n x of\n Nothing -> putStrLn \"NO\"\n Just xs -> putStrLn \"YES\" >> putStrLn (unwords . map show $ xs)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && n == 2 = Nothing\n | n == 1 = Just [x]\n | n == 2 = Just [x, 0]\n | otherwise = Just $ ([262144, 393216] ++) $ (:) =<< (xor 131072 . foldl' xor x) $ take (n - 3) [1..]"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && n > 1 = Nothing\n | odd n = Just $ (:) =<< foldl' xor x $ take (n - 1) [2^17..]\n | otherwise = Just $ (0:) $ (:) =<< foldl' xor x $ take (n - 2) [2^17..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && even n = Nothing\n | odd n = Just $ go n (2^17) x\n | otherwise = Just $ (++) =<< (go 3 (2^18) . foldl' xor x) $ take (n - 3) [2^17..]\n\ngo n lo x = (:) =<< foldl' xor x $ take (n - 1) [lo..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x = (:) =<< foldl' xor x $ take (n - 1) [10^5+1..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && even n = Nothing\n | odd n = Just $ (:) =<< foldl' xor x $ take (n - 1) [2^17..]\n | otherwise = Just $ (0:) $ (:) =<< foldl' xor x $ take (n - 2) [2^17..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && even n = Nothing\n | odd n = Just $ go n (2^17) x\n | otherwise = Just $ (++) =<< (go 3 (2^19) . foldl' xor x) $ take (n - 3) [2^17..]\n\ngo n lo x = (:) =<< foldl' xor x $ take (n - 1) [lo..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && even n = Nothing\n | otherwise = Just $ ([262144, 393216] ++) $ (:) =<< (xor 131072 . foldl' xor x) $ take (n - 3) [1..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && even n = Nothing\n | odd n = Just $ (:) =<< foldl' xor x $ take (n - 1) [2^17..] -- 0....\n | otherwise = Just $ ([0, 2^17]++) $ (:) =<< (flip clearBit 17 . foldl' xor x) $ take (n - 3) [2^17 + 1..] --1......"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | odd n = (:) =<< foldl' xor x $ take (n - 1) [2^17..]\n | otherwise = (0:) $ (:) =<< foldl' xor x $ take (n - 2) [2^17..]"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}\nmodule Main where\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Control.Monad\nimport Control.Monad.Trans.State.Lazy\nimport Data.Bits\nimport Data.List\n\nmain = putStr . evalState app . B.words =<< B.getContents \n\napp = maybe \"NO\" ((\"YES\\n\" ++) . unwords . map show) `fmap` liftM2 solve poi poi\n where\n pop = state $ \\(x:xs) -> (x, xs)\n poi = fmap int pop\n int = maybe undefined fst . B.readInt\n\nsolve n x \n | x == 0 && even n = Nothing\n | n == 1 = Just [x]\n | n == 2 = Just [x, 0]\n | otherwise = Just $ ([262144, 393216] ++) $ (:) =<< (xor 131072 . foldl' xor x) $ take (n - 3) [1..]"}, {"source_code": "import Data.Bits\n\nz = 2^19\n\nsolve :: Int -> Int -> Maybe [Int]\nsolve 2 0 = Nothing\nsolve 2 x = Just $ [1, x `xor` 1]\nsolve n x\n | v >= n = Just $ v : [1..(n-1)]\n | v == 1 = Just $ (v .|. z) : 1 : (2 .|. z) : [3..(n-1)]\n | otherwise = Just $ (v .|. z) : (1 .|. z) : [2..(n-1)]\n where v = foldl xor x [1..(n-1)]\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n case solve n x of\n Nothing -> putStrLn \"NO\"\n Just xs -> putStrLn \"YES\" >> putStrLn (unwords . map show $ xs)\n"}, {"source_code": "import Data.Bits\n\nz = 2^19\n\nsolve :: Int -> Int -> Maybe [Int]\nsolve 2 0 = Nothing\nsolve n x\n | v >= n = Just $ v : [1..(n-1)]\n | v == 1 = Just $ (v .|. z) : 1 : (2 .|. z) : [3..(n-1)]\n | otherwise = Just $ (v .|. z) : (1 .|. z) : [2..(n-1)]\n where v = foldl xor x [1..(n-1)]\n\nmain = do\n [n, x] <- fmap (map read . words) getLine\n case solve n x of\n Nothing -> putStrLn \"NO\"\n Just xs -> putStrLn \"YES\" >> putStrLn (unwords . map show $ xs)\n"}], "src_uid": "a559171e858d9a63c49fc9e0fecb44c7"} {"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1 -- t\n >>> map (words >>> map read)\n >>> process\n >>> map (map show >>> unwords)\n >>> unlines\n\nprocess :: [[Int]] -> [[Int]]\nprocess [] = []\nprocess ([_, t] : a : rest) = solve t a : process rest\n\nsolve :: Int -> [Int] -> [Int]\nsolve t a =\n fst $\n foldr\n ( \\x (ans, col) ->\n case compare t (2 * x) of\n EQ -> (col:ans, 1 - col)\n LT -> (0:ans, col)\n GT -> (1:ans, col)\n )\n ([], 0)\n a\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.Bool\n\nsolve :: Int -> [Int] -> [Bool]\nsolve u a = let\n ct = length [() | x <- a, x + x == u]\n go 0 [] = []\n go 0 (s : t) = (s + s <= u) : go 0 t\n go k (s : t) = case compare (s + s) u of\n LT -> True : go k t\n EQ -> False : go (k - 1) t\n GT -> False : go k t\n go _ _ = error \"...\"\n in go (div ct 2) a\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [_n, u] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n putStrLn . unwords . map (bool \"0\" \"1\") $ solve u a\n"}], "negative_code": [], "src_uid": "6458ad752e019ffb87573c8bfb712c18"} {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [(Int, Int)] -> String -> Maybe String\nsolve [_] acc = Just acc\nsolve ((x1,y1):(x2,y2):xs) acc\n | x1 <= x2 && y1 <= y2 = solve ((x2,y2):xs) (acc ++ path)\n | otherwise = Nothing \n where\n path = (replicate (x2-x1) 'R') ++ replicate (y2-y1) 'U'\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n n <- readLn :: IO Int\n xys <- replicateM n $ do\n [a,b] <- map read . words <$> getLine :: IO [Int]\n return (a,b)\n case solve ((0,0):(sort xys)) \"\" of\n Just res -> do\n putStrLn \"YES\"\n putStrLn res\n Nothing -> do\n putStrLn \"NO\"\n \n ", "positive_code": [{"source_code": "import Data.Char\nimport Data.List\nimport Control.Monad\n\ncheckYs :: [Int] -> Bool\ncheckYs ys = -1 == (foldr (\\a b -> if a <= b then a else -1) 1001) ys\n \nisImpossible :: Int -> [(Int, Int)] -> Bool\nisImpossible n = checkYs . map snd\n\ngetPath :: (Int, Int) -> Int -> [(Int, Int)] -> String\ngetPath _ 0 _ = []\ngetPath (x1, y1) n ((x2, y2):xys) = (rs) ++ (us) ++ (getPath (x2, y2) (n - 1) xys)\n where rTimes = x2 - x1\n uTimes = y2 - y1\n rs = replicate rTimes 'R'\n us = replicate uTimes 'U'\n\nsolve :: Int -> [(Int, Int)] -> String\nsolve n xy\n | invalid = \"NO\"\n | otherwise = \"YES\\n\" ++ (getPath (0, 0) n xys)\n where xys = sort xy\n invalid = isImpossible n xys\n\nmakePair :: String -> (Int, Int)\nmakePair s = (a, b)\n where wds = words s\n a = read (wds !! 0)\n b = read (wds !! 1)\n\ntestCase :: IO ()\ntestCase = do\n n <- read <$> getLine\n inputs <- replicateM n (makePair <$> getLine)\n putStrLn $ solve n inputs\n \nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM t testCase \n return ()\n"}, {"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Control.Monad.Trans.Maybe\nimport Control.Monad.Trans.Class\n\nimport Text.Read (readMaybe)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\nget :: Read a => MaybeT IO a\nget = MaybeT $ liftM readMaybe getToken\n\nputs :: String -> MaybeT IO ()\nputs = lift . putStr\n\nputsln :: String -> MaybeT IO ()\nputsln = lift . putStrLn\n\nput :: Show a => a -> MaybeT IO ()\nput = putsln . show\n\nputln :: Show a => a -> MaybeT IO ()\nputln = putsln . show\n\nmain :: IO ()\nmain = do\n o <- runMaybeT sub\n return ()\n\nsub :: MaybeT IO ()\nsub = do \n t <- get :: MaybeT IO Int\n replicateM_ t f1\n\nf1 :: MaybeT IO ()\nf1 = do { n <- get :: MaybeT IO Int\n ; a <- replicateM n $ liftM2 (,) get get :: MaybeT IO [(Int, Int)]\n ; case f2 a of\n Just s -> do\n putsln \"YES\"\n putsln s\n Nothing -> putsln \"NO\" }\n\nf2 :: [(Int, Int)] -> Maybe String\nf2 a = let aux (a, b) (c, d) = case compare a c of\n EQ -> compare b d\n x -> x\n in toList <$> (f3 (0, 0) $ sortBy aux a)\n\nf3 :: (Int, Int) -> [(Int, Int)] -> Maybe (Seq Char)\nf3 _ [] = Just DSeq.Empty\nf3 (a, b) ((c, d) : l) = if b > d then Nothing else\n (\\x -> (DSeq.replicate (c - a) 'R' >< DSeq.replicate (d - b) 'U') >< x ) <$> f3 (c, d) l\n"}, {"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\nimport Data.Maybe\nimport Text.Read (readMaybe)\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\nget :: Read a => IO (Maybe a)\nget = liftM readMaybe getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\ntry :: Maybe (IO ()) -> IO ()\ntry = fromMaybe . return $ ()\n\nmain :: IO ()\nmain = do {\n t' <- get :: IO (Maybe Int)\n ; try $ do {\n t <- t'\n ; Just $ do {\n replicateM_ t f1 }}}\n\nf1 :: IO ()\nf1 = do { n' <- get :: IO (Maybe Int)\n ; try $ do {\n n <- n'\n ; Just $ do {\n a' <- replicateM n $ liftM2 (,) get get :: IO [(Maybe Int, Maybe Int)]\n ; try $ do {\n a <- toList <$> foldl (liftM2 (|>)) (Just DSeq.Empty) ((\\ (x, y) -> liftM2 (,) x y) <$> a')\n ; Just $ case f2 a of\n Just s -> do\n putStrLn \"YES\"\n putStrLn s\n Nothing -> putStrLn \"NO\" }}}}\n\nf2 :: [(Int, Int)] -> Maybe String\nf2 a = let aux (a, b) (c, d) = case compare a c of\n EQ -> compare b d\n x -> x\n in toList <$> (f3 (0, 0) $ sortBy aux a)\n\nf3 :: (Int, Int) -> [(Int, Int)] -> Maybe (Seq Char)\nf3 _ [] = Just DSeq.Empty\nf3 (a, b) ((c, d) : l) = if b > d then Nothing else\n (\\x -> (DSeq.replicate (c - a) 'R' >< DSeq.replicate (d - b) 'U') >< x ) <$> f3 (c, d) l\n"}, {"source_code": "import Control.Monad\nimport Data.Ord\nimport Data.Int\nimport Data.Sequence as DSeq (null, Seq( Empty ), (|>), (><), replicate)\nimport Data.Foldable\nimport Data.List\n\ngetToken :: IO String\ngetToken =\n let aux s = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n' then\n if DSeq.null s then\n aux s\n else\n return $ toList s\n else\n aux $ s |> x\n in aux DSeq.Empty\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n t <- get :: IO Int\n replicateM_ t f1\n\nf1 :: IO ()\nf1 = do\n n <- get :: IO Int\n a <- replicateM n $ liftM2 (,) get get :: IO [(Int, Int)]\n case f2 a of\n Just s -> do\n putStrLn \"YES\"\n putStrLn s\n Nothing -> putStrLn \"NO\"\n\nf2 :: [(Int, Int)] -> Maybe String\nf2 a = let aux (a, b) (c, d) = case compare a c of\n EQ -> compare b d\n x -> x\n in toList <$> (f3 (0, 0) $ sortBy aux a)\n\nf3 :: (Int, Int) -> [(Int, Int)] -> Maybe (Seq Char)\nf3 _ [] = Just DSeq.Empty\nf3 (a, b) ((c, d) : l) = if b > d then Nothing else\n (\\x -> (DSeq.replicate (c - a) 'R' >< DSeq.replicate (d - b) 'U') >< x ) <$> f3 (c, d) l\n"}], "negative_code": [], "src_uid": "b01c627abc00f97767c237e304f8c17f"} {"source_code": "import Data.Array (Array, assocs, listArray, (!))\nimport Data.Array.Unboxed (UArray, accumArray, array, elems)\nimport Data.Maybe (fromJust)\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as C\n\npalindrome n s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1], r <= n]\n where\n a = listArray (1, n) $ C.unpack s\n go l r = if 1 <= l && r <= n && a!l == a!r then succ $ go (pred l) (succ r) else 0\n\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a ! l U.! r: go t\n n = C.length s\n a = listArray (1,n) $ map gao $ zip [1 .. n] $ iterate (drop 2) $ palindrome n s\n gao :: (Int, [(Int, Int, Int)]) -> UArray Int Int\n gao (s, p) = U.listArray (s,n) $ scanl1 (+) $ scanl1 (+) $ elems d\n where\n d :: UArray Int Int\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0]\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStr $ unlines $ map show $ solve s q\n", "positive_code": [{"source_code": "import Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as C\n\ntype U = UArray Int Int\n\npal n s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1]]\n\twhere\n\t\ta = A.listArray (1, n) $ C.unpack s\n\t\tgo l r = if 1 <= l && r <= n && a!l == a!r then go (l - 1) (r + 1) + 1 else 0\n\nsolve s q = go q\n\twhere\n\t\tgo [] = []\n\t\tgo (l:r:t) = ' ': show (a A.! l ! r) ++ go t\n\t\tn = C.length s\n\t\tp = pal n s\n\t\ta = listArray (1,n) $ map gao [1 .. n]\n\t\tgao s = listArray (s,n) $ scanl1 (+) $ scanl1 (+) $ elems d :: U\n\t\t\twhere\n\t\t\t\td = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n\t\t\t\t\t(l,r,m) <- p,\n\t\t\t\t\tlet m' = min m $ l - s + 1,\n\t\t\t\t\tm' > 0] :: U\n\nmain = do\n\ts <- C.getLine\n\tC.getLine\n\tq <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n\tputStr $ solve s q\n"}, {"source_code": "{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}\nimport Data.Array (Array, assocs, listArray, (!))\nimport Data.Array.Unboxed (UArray, accumArray, array, elems)\nimport Data.Maybe (fromJust)\nimport Debug.Trace (trace)\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as C\n\n-- parsum = scanl1 (+)\n-- parsum2 = parsum . parsum\nparsum2 a = go 0 0 a\n where\n go s x [] = []\n go s x (h:t) = x': go s' x' t\n where\n s' = s + h\n x' = x + s'\n\n-- O(n^2): 0.36s\npalindrome s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1], r <= n]\n where\n n = C.length s\n a = listArray (1, n) $ C.unpack s\n go l r\n | l < 1 || r > n = 0\n | a!l /= a!r = 0\n | otherwise = succ $ go (pred l) (succ r)\n\n-- O(n): 0.02s\nmanacher s = [(div i 2, div (i + 1) 2, e) | (i, e) <- assocs b]\n where\n n = C.length s\n a = listArray (1, n) $ C.unpack s\n pal l r\n | l < 1 || r > n = 0\n | a!l /= a!r = 0\n | otherwise = succ $ pal (pred l) (succ r)\n b = listArray (2, 2*n) $ go 2 (0, 0)\n go k (e, c) = if l > n then [] else t: go (k + 1) (e', c')\n where\n l = div k 2\n r = k - l\n s = if k <= e then min (b!(2*c-k)) $ 1 + div (e-k) 2 else 0\n t = s + pal (l - s) (r + s)\n (e', c') = max (e, c) (2 * (r + t - 1), k)\n\nsolve :: C.ByteString -> [Int] -> [Int]\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a ! l U.! r: go t\n n = C.length s\n p = manacher s\n a = listArray (1,n) $ map gao $ zip [1 .. n] $ iterate (drop 2) p\n gao :: (Int, [(Int, Int, Int)]) -> UArray Int Int\n gao (s, p) = U.listArray (s,n) $ parsum2 $ elems d\n where\n d :: UArray Int Int\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0]\n\n-- 4562ms\ncustomTest = do\n let s = C.pack $ replicate 5000 'a'\n q = concat [[i, i + 1, i * 5, j * 5] | i <- [1 .. 1000], j <- [i .. 1000]]\n putStr $ unlines $ map show $ solve s q\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStr $ unlines $ map show $ solve s q\n"}, {"source_code": "import Data.Array (Array, assocs, listArray, (!))\nimport Data.Array.Unboxed (UArray, accumArray, array, elems)\nimport Data.Maybe (fromJust)\nimport qualified Data.Array.Unboxed as U\nimport qualified Data.ByteString.Char8 as C\n\nparsum2 a = go 0 0 a\n where\n go s x [] = []\n go s x (h:t) = x': go s' x' t\n where\n s' = s + h\n x' = x + s'\n\nmanacher s = [(div i 2, div (i + 1) 2, e) | (i, e) <- assocs b]\n where\n n = C.length s\n a = listArray (1, n) $ C.unpack s\n pal l r = if 1 <= l && r <= n && a!l == a!r then succ $ pal (pred l) (succ r) else 0\n b = listArray (2, 2*n) $ go 2 (0, 0)\n go k (e, c) = if l > n then [] else t: go (k + 1) (e', c')\n where\n l = div k 2\n r = k - l\n s = if k <= e then min (b!(2*c-k)) $ 1 + div (e-k) 2 else 0\n t = s + pal (l - s) (r + s)\n (e', c') = max (e, c) (2 * (r + t - 1), k)\n\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a ! l U.! r: go t\n n = C.length s\n p = manacher s\n a = listArray (1,n) $ map gao $ zip [1 .. n] $ iterate (drop 2) p\n gao :: (Int, [(Int, Int, Int)]) -> UArray Int Int\n gao (s, p) = U.listArray (s,n) $ parsum2 $ elems d\n where\n d :: UArray Int Int\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0]\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStr $ unlines $ map show $ solve s q\n"}, {"source_code": "import Data.Array.Unboxed\nimport Data.Maybe\nimport qualified Data.Array as A\nimport qualified Data.ByteString.Char8 as C\n\npalindrome n s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1], r <= n]\n where\n a = A.listArray (1, n) $ C.unpack s\n go l r = if 1 <= l && r <= n && a!l == a!r then succ $ go (pred l) (succ r) else 0\n\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a A.! l ! r: go t\n n = C.length s\n a = listArray (1,n) $ map gao $ zip [1 .. n] $ iterate (drop 2) $ palindrome n s\n gao (s, p) = listArray (s,n) $ scanl1 (+) $ scanl1 (+) $ elems d :: UArray Int Int\n where\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0] :: UArray Int Int\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n putStr $ unlines $ map show $ solve s q\n"}], "negative_code": [{"source_code": "import Data.Array.Unboxed (UArray, accumArray, array, elems, listArray, (!))\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\npalindrome s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1], r <= n]\n where\n n = C.length s\n a = listArray (1, n) $ C.unpack s :: UArray Int Char\n go l r\n | l < 1 || r > n = 0\n | a!l /= a!r = 0\n | otherwise = succ $ go (pred l) (succ r)\n\nsolve :: C.ByteString -> [Int] -> [Int]\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a!(l,r): go t\n n = C.length s\n p = palindrome s\n a :: UArray (Int, Int) Int\n a = array ((1,1),(n,n)) $ concatMap gao [1 .. n]\n gao :: Int -> [((Int, Int), Int)]\n gao s = zip [(s, i) | i <- [s .. n]] $ scanl1 (+) $ scanl1 (+) $ elems d\n where\n d :: UArray Int Int\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0]\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n if length q < 1000\n then putStr $ unlines $ map show $ solve s q\n else print $ sum $ solve s q\n"}, {"source_code": "import Data.Array.Unboxed (UArray, accumArray, array, elems, listArray, (!))\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\npalindrome s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1], r <= n]\n where\n n = C.length s\n a = listArray (1, n) $ C.unpack s :: UArray Int Char\n go l r\n | l < 1 || r > n = 0\n | a!l /= a!r = 0\n | otherwise = succ $ go (pred l) (succ r)\n\nsolve :: C.ByteString -> [Int] -> [Int]\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a!(l,r): go t\n n = C.length s\n p = palindrome s\n a :: UArray (Int, Int) Int\n a = array ((1,1),(n,n)) $ concatMap gao [1 .. n]\n gao :: Int -> [((Int, Int), Int)]\n gao s = zip [(s, i) | i <- [s .. n]] $ scanl1 (+) $ scanl1 (+) $ elems d\n where\n d :: UArray Int Int\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0]\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n if C.pack \"aaaa\" `C.isPrefixOf` s\n then print $ sum $ solve s q\n else putStr $ unlines $ map show $ solve s q\n"}, {"source_code": "import Data.Array.Unboxed (UArray, accumArray, array, elems, listArray, (!))\nimport Data.Maybe (fromJust)\nimport qualified Data.ByteString.Char8 as C\n\npalindrome s = [(l, r, go l r) | l <- [1 .. n], r <- [l, l + 1], r <= n]\n where\n n = C.length s\n a = listArray (1, n) $ C.unpack s :: UArray Int Char\n go l r\n | l < 1 || r > n = 0\n | a!l /= a!r = 0\n | otherwise = succ $ go (pred l) (succ r)\n\nsolve :: C.ByteString -> [Int] -> [Int]\nsolve s q = go q\n where\n go [] = []\n go (l:r:t) = a!(l,r): go t\n n = C.length s\n p = palindrome s\n a :: UArray (Int, Int) Int\n a = array ((1,1),(n,n)) $ concatMap gao [1 .. n]\n gao :: Int -> [((Int, Int), Int)]\n gao s = zip [(s, i) | i <- [s .. n]] $ scanl1 (+) $ scanl1 (+) $ elems d\n where\n d :: UArray Int Int\n d = accumArray (+) 0 (s,n+1) $ concat [[(r, 1), (r + m', -1)] |\n (l,r,m) <- p,\n let m' = min m $ l - s + 1,\n m' > 0]\n\nmain = do\n s <- C.getLine\n C.getLine\n q <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n if length q < 100000\n then putStr $ unlines $ map show $ solve s q\n else print $ sum $ solve s q\n"}], "src_uid": "1d8937ab729edad07b3b23b1927f7e11"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.Traversable (for)\n\ncost :: Integer -> Integer -> Integer -> [Char] -> Integer\ncost _ _ acc [] = acc\ncost x y acc ('.':'.':cs)\n = cost x y (acc + min (2*x) y) cs\ncost x y acc ('.':cs) = cost x y (acc + x) cs\ncost x y acc (_:cs) = cost x y acc cs\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine :: IO Int\n _ <- for [1..t] $ \\_ -> do\n [n, _m, x, y] <- map read . words <$> getLine :: IO [Integer]\n rows <- for [1..n] $ const getLine\n print . sum $ map (cost x y 0) rows\n return ()\n\n\n", "positive_code": [{"source_code": "import Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let (_:tokens) = split input\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n':m':x':y':rest ->\n let n = read n' :: Int\n m = read m' :: Int\n x = read x' :: Int\n y = min (2*x) (read y' :: Int)\n (rows, rest') = splitAt n rest\n rowVals =\n let rowSum = (\\acc row ->\n case row of\n [] -> acc\n '*':rest -> rowSum acc rest\n '.':'.':rest -> rowSum (acc + y) rest\n '.':rest -> rowSum (acc + x) rest\n )\n in rowSum 0 <$> rows\n total = foldl (+) 0 rowVals\n in Just (total, rest')\n ) tokens\n sequence (putStrLn . show <$> res)\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.List\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:m:x:y:_) <- map read . words <$> getLine\n square <- replicateM n getLine\n let rs = square >>= (map length . filter ((/= False) . head) . group . map (== '.'))\n print $ min (sum $ (\\a -> (a `div` 2) * y + (a `mod` 2) * x) <$> rs) (sum $ (* x) <$> rs)"}], "negative_code": [], "src_uid": "69ef9492fcdcc979cb31fa95c3e76db9"} {"source_code": "import Data.Int\nimport Data.List\nimport Data.Array.Unboxed\nmain = do\n [n,m] <- map read . words <$> getLine\n xs <- listArray (1,n) . map read . words <$> getLine :: IO (UArray Int Int64)\n ps <- listArray (1,m) . map read . words <$> getLine :: IO (UArray Int Int64)\n if n == 1 then do\n putStrLn \"YES\"\n putStrLn (show (xs!1) ++ \" \" ++ show (ps!1))\n else do\n let g = foldl1' gcd $ zipWith (-) (tail (elems xs)) (elems xs)\n case find ((== 0) . (g `mod`) . (ps !)) (indices ps) of\n Nothing -> putStrLn \"NO\"\n Just j -> putStrLn \"YES\" >> putStrLn (show (xs!1) ++ \" \" ++ show j)\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, m ] <- readInts\n\txs <- readIntegers\n\tps <- readIntegers\n\tlet\n\t\tg = foldl1 gcd $ map ( subtract $ head xs ) xs\n\t\tres = find ( \\( p, _ ) -> g `mod` p == 0 ) $ zip ps ( [ 1.. ] :: [Int] )\n\tcase res of\n\t\tNothing -> putStrLn \"NO\"\n\t\tJust ( _, idx ) -> do\n\t\t\tputStrLn $ \"YES\"\n\t\t\tprintf \"%d %d\\n\" ( head xs ) idx"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadNInts = readInt >>= flip replicateM readInt\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmain = do\n\t[ n, m ] <- readInts\n\txs <- readInts\n\tps <- readInts\n\tlet\n\t\tg = foldl1 gcd $ map ( subtract $ head xs ) xs\n\t\tres = find ( \\( p, _ ) -> g `mod` p == 0 ) $ zip ps ( [ 1.. ] :: [Int] )\n\tcase res of\n\t\tNothing -> putStrLn \"NO\"\n\t\tJust ( _, idx ) -> do\n\t\t\tputStrLn $ \"YES\"\n\t\t\tprintf \"%d %d\\n\" ( head xs ) idx"}, {"source_code": "import Data.Int\nmain = do\n [n,m] <- map read . words <$> getLine\n xs <- map read . words <$> getLine\n ps <- map read . words <$> getLine :: IO [Int64]\n if n == 1 then putStrLn \"YES\" >> putStrLn (show (head xs) ++ \" \" ++ show (head ps)) else do\n let xd = foldl1 gcd $ zipWith (-) (tail xs) xs\n case filter ((== 0) . (xd `mod`)) ps of\n [] -> putStrLn \"NO\"\n (p:_) -> putStrLn \"YES\" >> putStrLn (show (head xs) ++ \" \" ++ show p)\n"}, {"source_code": "import Data.Int\nimport Data.List\nimport Data.Array.Unboxed\nmain = do\n [n,m] <- map read . words <$> getLine\n xs <- listArray (1,n) . map read . words <$> getLine :: IO (UArray Int Int64)\n ps <- listArray (1,m) . map read . words <$> getLine :: IO (UArray Int Int64)\n if n == 1 then do\n putStrLn \"YES\"\n putStrLn (show (xs!1) ++ \" \" ++ show (ps!1))\n else do\n let g = foldl1' gcd $ zipWith (-) (tail (elems xs)) (elems xs)\n case find ((== 0) . (g `mod`) . (ps !)) (indices ps) of\n Nothing -> putStrLn \"NO\"\n Just j -> putStrLn \"YES\" >> putStrLn (show (xs!1) ++ \" \" ++ show (j+1))\n"}, {"source_code": "import Data.Int\nmain = do\n [n,m] <- map read . words <$> getLine\n xs <- map read . words <$> getLine\n ps <- map read . words <$> getLine\n if n == 1 then putStrLn \"YES\" >> putStrLn (show (head xs) ++ \" \" ++ show (head ps)) else do\n let xd = minimum $ zipWith (-) (tail xs) xs\n case filter ((== 0) . (xd `mod`)) ps of\n [] -> putStrLn \"NO\"\n (p:_) -> putStrLn \"YES\" >> putStrLn (show (head xs) ++ \" \" ++ show p)\n"}], "src_uid": "6493e146ea8d931582d77bb1b0f06e53"} {"source_code": "import Control.Applicative\nimport Data.List\n\nreadWords = map read . words <$> getLine\n\nsolve a b marks\n\t| a == b = nums\n\t| a < b = map snd $ sort $ zip (map snd $ sort $ zip (map negate marks) [1..]) nums\n\t| a > b = map snd $ sort $ zip (map snd $ sort $ zip marks [1..]) nums\n\twhere\n\t\tnums = replicate a 1 ++ replicate b 2\n\nmain = do\n\t_ <- getLine\n\t[a, b] <- readWords\n\tmarks <- readWords\n\tputStrLn $ unwords $ map show $ solve a b marks\n", "positive_code": [{"source_code": "\n\nimport Control.Applicative\nimport Data.List\n\nreadWords = map read . words <$> getLine\n\nsolve a b marks\n\t| a == b = nums\n\t| a < b = map snd $ sort $ zip (map snd $ sort $ zip (map negate marks) [1..]) $ nums\n\t| a > b = map snd $ sort $ zip (map snd $ sort $ zip marks [1..]) $ nums\n\twhere\n\t\tnums = replicate a 1 ++ replicate b 2\n\nmain = do\n\t_ <- getLine\n\t[a, b] <- readWords\n\tmarks <- readWords\n\tputStrLn $ unwords $ map show $ solve a b marks\n"}, {"source_code": "import List\n\ndata Pair\n = Pair\n {\n mark :: Int,\n number :: Int\n } deriving Show\n \ninstance Eq Pair where\n (==) (Pair x1 y1) (Pair x2 y2) = x1 == x2 && y1 == y2\n \ninstance Ord Pair where\n compare (Pair x1 y1) (Pair x2 y2)\n | x1 == x2 && y1 == y2 = EQ\n | x1 > x2 || x1 == x2 && y1 < y2 = GT\n | otherwise = LT\n\nmySort :: [Int] -> [Pair]\nmySort as = reverse $ sort $ tail (scanl (\\(Pair _ m) a -> Pair a (m + 1)) (Pair 0 0) as)\n\nsolve :: Int -> Int -> [Int] -> [Pair]\nsolve a b ds\n | b > a = map (\\(Pair d n) -> (Pair 1 n)) (take a sortedDs) ++ map (\\(Pair d n) -> (Pair 2 n)) (drop a sortedDs)\n | a > b = map (\\(Pair d n) -> (Pair 1 n)) (take a sortedDsR) ++ map (\\(Pair d n) -> (Pair 2 n)) (drop a sortedDsR)\n | otherwise = (replicate a (Pair 1 1)) ++ (replicate b (Pair 2 2))\n where\n sortedDs = mySort ds\n sortedDsR = reverse $ mySort $ reverse ds\n\nmyPrint :: Bool -> [Pair] -> [Int]\nmyPrint False ds = map number (sort (map (\\(Pair x y) -> Pair y x) ds))\nmyPrint True ds = reverse (myPrint False ds)\n\nintsToString :: [Int] -> String\nintsToString ds = foldr (\\n s -> (show n) ++ \" \" ++ s) (show $ last ds) (init ds)\n\nmain = do\n n <- readLn::IO Int\n line <- getLine\n let [a,b] = map read (words line)\n line <- getLine\n let ds = map read $ words line\n putStrLn $ intsToString $ myPrint (a > b) (solve a b ds)"}, {"source_code": "import Control.Applicative\nimport Data.List\nimport Array\n\nrep = replicate . fromIntegral -- genericReplicate\ntype Z = Integer\n\nmain = do\n n <- readLn\n [a,b] <- map read . words <$> getLine\n f <- map read . words <$> getLine\n putStrLn . unwords . map show $ solve n a b f\n\nsolve :: Z -> Z -> Z -> [Z] -> [Z]\nsolve n a b f\n | a==b = rep a 1 ++ rep b 2\n | a>b = let fi = zip (rep a 1 ++ rep b 2) . sort $ zip f [0..]\n in elems $ array (0,n-1) [(i,t)| (t,(_,i))<-fi]\n{-\n | a compare b2 b1 `mappend` compare a1 a2)\n | a > b = sortBy (\\(a1, b1) (a2, b2) -> compare b1 b2 `mappend` compare a1 a2)\n | a == b = id\n t = (srt . zip [1..] . map read . words) t' :: [(Int, Int)]\n f = ([\"1\"] <* [1..a]) ++ ([\"2\"] <* [1..b])\n putStrLn $ unwords $ if a == b then f else \n map snd $ sort $ zipWith (\\(a,b) c -> (a, c)) t f\n"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.Monoid\nimport Data.List\nimport Data.Ord\n\ngetInts = map read . words <$> getLine\n\nmerge [] [] = []\nmerge (h1:t1) [] = \"1\" : merge t1 []\nmerge [] (h2:t2) = \"2\" : merge [] t2\n\n\nmain = do\n [n] <- getInts\n [a,b] <- getInts\n marks <- getInts\n let marks' = zip [0..] marks\n cmp (i1, a1) (i2, a2) = \n let mod = \n case compare a b of\n EQ -> 0\n GT -> 1\n LT -> -1\n in compare (a1*mod) (a2*mod) `mappend` compare i1 i2\n marks'' = sortBy cmp marks'\n (marks1, marks2) = splitAt a marks''\n res = map snd $ sortBy (comparing fst) $ map (\\(i,_) -> (i, \"1\")) marks1 ++ map (\\(i,_) -> (i, \"2\")) marks2 :: [String ]\n putStrLn $ concat $ intersperse \" \" $ res"}], "negative_code": [{"source_code": "\n\nimport Control.Applicative\nimport Data.List\n\nreadWords = map read . words <$> getLine\n\nsolve a b marks\n\t| a == b = nums\n\t| a < b = order $ reverse nums\n\t| a > b = order nums\n\twhere\n\t\tnums = replicate a 1 ++ replicate b 2\n\t\torder = map snd . sort . zip (map snd $ sort $ zip marks [1..]) \n\nmain = do\n\t_ <- getLine\n\t[a, b] <- readWords\n\tmarks <- readWords\n\tputStrLn $ unwords $ map show $ solve a b marks\n"}, {"source_code": "import List\n\nmySort :: [Int] -> [(Int, Int)]\nmySort as = reverse $ sort $ tail (scanl (\\(_, m) a -> (a, m + 1)) (0, 0) as)\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)]\nsolve a b ds\n | b > a = map (\\(d, n) -> (1, n)) (take a sortedDs) ++ map (\\(d, n) -> (2, n)) (drop a sortedDs)\n | otherwise = map (\\(d, n) -> (2, n)) (take b sortedDs) ++ map (\\(d, n) -> (1, n)) (drop b sortedDs)\n where\n sortedDs = mySort ds\n\nmyPrint :: [(Int, Int)] -> [Int]\nmyPrint ds = map snd (sort (map (\\(x, y) -> (y, x)) ds))\n\nintsToString :: [Int] -> String\nintsToString ds = foldl (\\s n -> s ++ \" \" ++ (show n)) (show $ head ds) (tail ds)\n\nmain = do\n n <- readLn::IO Int\n line <- getLine\n let [a,b] = map read (words line)\n line <- getLine\n let ds = map read $ words line\n putStrLn $ intsToString $ myPrint $ solve a b ds"}, {"source_code": "import List\n\nmySort :: [Int] -> [(Int, Int)]\nmySort as = reverse $ sort $ tail (scanl (\\(_, m) a -> (a, m + 1)) (0, 0) as)\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)]\nsolve a b ds\n | b > a = map (\\(d, n) -> (1, n)) (take a sortedDs) ++ map (\\(d, n) -> (2, n)) (drop a sortedDs)\n | a > b = map (\\(d, n) -> (2, n)) (take b sortedDs) ++ map (\\(d, n) -> (1, n)) (drop b sortedDs)\n | otherwise = (replicate a (1, 1)) ++ (replicate b (2, 2))\n where\n sortedDs = mySort ds\n\nmyPrint :: [(Int, Int)] -> [Int]\nmyPrint ds = map snd (sort (map (\\(x, y) -> (y, x)) ds))\n\nintsToString :: [Int] -> String\nintsToString ds = foldl (\\s n -> s ++ \" \" ++ (show n)) (show $ head ds) (tail ds)\n\nmain = do\n n <- readLn::IO Int\n line <- getLine\n let [a,b] = map read (words line)\n line <- getLine\n let ds = map read $ words line\n putStrLn $ intsToString $ myPrint $ solve a b ds"}, {"source_code": "import List\n\nmySort :: [Int] -> [(Int, Int)]\nmySort as = reverse $ sort $ tail (scanl (\\(_, m) a -> (a, m + 1)) (0, 0) as)\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)]\nsolve a b ds\n | b > a = map (\\(d, n) -> (1, n)) (take a sortedDs) ++ map (\\(d, n) -> (2, n)) (drop a sortedDs)\n | a < b = map (\\(d, n) -> (2, n)) (take b sortedDs) ++ map (\\(d, n) -> (1, n)) (drop b sortedDs)\n | otherwise = (replicate a (1, 1)) ++ (replicate b (2, 2))\n where\n sortedDs = mySort ds\n\nmyPrint :: [(Int, Int)] -> [Int]\nmyPrint ds = map snd (sort (map (\\(x, y) -> (y, x)) ds))\n\nintsToString :: [Int] -> String\nintsToString ds = foldl (\\s n -> s ++ \" \" ++ (show n)) (show $ head ds) (tail ds)\n\nmain = do\n n <- readLn::IO Int\n line <- getLine\n let [a,b] = map read (words line)\n line <- getLine\n let ds = map read $ words line\n putStrLn $ intsToString $ myPrint $ solve a b ds"}, {"source_code": "import List\n\nmySort :: [Int] -> [(Int, Int)]\nmySort as = reverse $ sort $ tail (scanl (\\(_, m) a -> (a, m + 1)) (0, 0) as)\n\nsolve :: Int -> Int -> [Int] -> [(Int, Int)]\nsolve a b ds\n | b > a = map (\\(d, n) -> (1, n)) (take a sortedDs) ++ map (\\(d, n) -> (2, n)) (drop a sortedDs)\n | a > b = map (\\(d, n) -> (1, n)) (take a (reverse sortedDs)) ++ map (\\(d, n) -> (2, n)) (drop a (reverse sortedDs))\n | otherwise = (replicate a (1, 1)) ++ (replicate b (2, 2))\n where\n sortedDs = mySort ds\n\nmyPrint :: [(Int, Int)] -> [Int]\nmyPrint ds = map snd (sort (map (\\(x, y) -> (y, x)) ds))\n\nintsToString :: [Int] -> String\nintsToString ds = foldl (\\s n -> s ++ \" \" ++ (show n)) (show $ head ds) (tail ds)\n\nmain = do\n n <- readLn::IO Int\n line <- getLine\n let [a,b] = map read (words line)\n line <- getLine\n let ds = map read $ words line\n putStrLn $ intsToString $ myPrint $ solve a b ds"}, {"source_code": "import List\n\ndata Pair\n = Pair\n {\n mark :: Int,\n number :: Int\n } deriving Show\n \ninstance Eq Pair where\n (==) (Pair x1 y1) (Pair x2 y2) = x1 == x2 && y1 == y2\n \ninstance Ord Pair where\n compare (Pair x1 y1) (Pair x2 y2)\n | x1 == x2 && y1 == y2 = EQ\n | x1 > x2 || x1 == x2 && y1 < y2 = GT\n | otherwise = LT\n\nmySort :: [Int] -> [Pair]\nmySort as = reverse $ sort $ tail (scanl (\\(Pair _ m) a -> Pair a (m + 1)) (Pair 0 0) as)\n\nsolve :: Int -> Int -> [Int] -> [Pair]\nsolve a b ds\n | b > a = map (\\(Pair d n) -> (Pair 1 n)) (take a sortedDs) ++ map (\\(Pair d n) -> (Pair 2 n)) (drop a sortedDs)\n | a > b = map (\\(Pair d n) -> (Pair 1 n)) (take a sortedDsR) ++ map (\\(Pair d n) -> (Pair 2 n)) (drop a sortedDsR)\n | otherwise = (replicate a (Pair 1 1)) ++ (replicate b (Pair 2 2))\n where\n sortedDs = mySort ds\n sortedDsR = reverse $ mySort $ reverse ds\n\nmyPrint :: Bool -> [Pair] -> [Int]\nmyPrint False ds = map number (sort (map (\\(Pair x y) -> Pair y x) ds))\nmyPrint True ds = reverse (myPrint False ds)\n\nintsToString :: [Int] -> String\nintsToString ds = foldr (\\n s -> (show n) ++ \" \" ++ s) (show $ head ds) (tail ds)\n\nmain = do\n n <- readLn::IO Int\n line <- getLine\n let [a,b] = map read (words line)\n line <- getLine\n let ds = map read $ words line\n putStrLn $ intsToString $ myPrint (a > b) (solve a b ds)"}], "src_uid": "867facaa8bcdfcb53ec3647387f7d23f"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let _:tokens = read <$> split input :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n:x:rest0 ->\n let (vals, rest1) = splitAt (2*(n-1)) rest0\n count = sum $ (\\a -> if a == x then 1 else 0) <$> vals\n subres = if count <= 1 || n `mod` 2 == 0 then \"Ayush\" else \"Ashish\"\n in Just (subres, rest1)\n ) tokens\n sequence_ $ putStrLn <$> res\n", "positive_code": [{"source_code": "import Data.Graph\nimport Data.Tuple\nimport Control.Monad\nmain :: IO ()\nmain = do\n n <- readLn\n replicateM_ n routine\n\nroutine :: IO ()\nroutine = do\n [n,x] <- (map read.words) <$> getLine\n es <- replicateM (n-1) $ ((map read.words) <$> getLine)\n putStrLn $ if solve n x es then \"Ayush\" else \"Ashish\"\n\nsolve :: Int -> Int -> [[Int]] -> Bool\nsolve n x es = (trivial tr) || (even n)\n where\n tr = toTree x n es\n\ntrivial :: Tree Int -> Bool\ntrivial (Node _ trs) = (length trs) < 2\n\ntoTree :: Int -> Int -> [[Int]] -> Tree Int\ntoTree x n ps =head $ dfs gr [x]\n where\n tups = map (\\[a,b] -> (a,b)) ps\n gr = buildG (1,n) (tups++map swap tups)\n"}, {"source_code": "import Control.Monad\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t solve\n\nsolve :: IO()\nsolve = do\n [n,x] <- map read.words <$> getLine\n es <- replicateM (n-1) $ (map read.words <$> getLine)\n putStrLn (winner n x es)\n\nwinner :: Int -> Int -> [[Int]] -> String\nwinner n x es = do\n let degreeX = length (filter (isXEdge x) es)\n if degreeX <= 1 || even n then \"Ayush\" else \"Ashish\"\n\nisXEdge :: Int -> [Int] -> Bool\nisXEdge x [u,v] = u == x || v == x \n"}], "negative_code": [{"source_code": "import Control.Monad\n\nmain :: IO()\nmain = do\n t <- readLn\n replicateM_ t solve\n\nsolve :: IO()\nsolve = do\n [n,x] <- map read.words <$> getLine\n es <- replicateM (n-1) $ (map read.words <$> getLine)\n putStrLn (winner n x es)\n\nwinner :: Int -> Int -> [[Int]] -> String\nwinner n x es = do\n let degreeX = length (filter (isXEdge x) es)\n if degreeX <= 1 || odd degreeX then \"Ayush\" else \"Ashish\"\n\nisXEdge :: Int -> [Int] -> Bool\nisXEdge x [u,v] = u == x || v == x \n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\n_split acc \"\" [] = reverse acc\n_split acc curr [] = reverse $ reverse curr : acc\n_split acc curr (ch:rest)\n | (any (== ch) [' ', '\\n']) = _split (reverse curr : acc) \"\" rest\n | otherwise = _split acc (ch:curr) rest\n\nsplit = _split [] \"\"\n\nmain = do\n input <- getContents\n let _:tokens = read <$> split input :: [Int]\n res = unfoldr (\\ls ->\n case ls of\n [] -> Nothing\n n:x:rest0 ->\n let (vals, rest1) = splitAt (2*(n-1)) rest0\n count = sum $ (\\a -> if a == x then 1 else 0) <$> vals\n subres = if count == 1 || n `mod` 2 == 0 then \"Ayush\" else \"Ashish\"\n in Just (subres, rest1)\n ) tokens\n sequence_ $ putStrLn <$> res\n"}], "src_uid": "1a93a35395436f9e15760400f991f1ce"} {"source_code": "{-# LANGUAGE ParallelListComp #-}\nmain = getLine >>= putStr . (\\(a, bs) -> show a ++ \"\\n\" ++ unwords (map show $ length bs:bs)) . solve . read\nsolve :: Int -> (Int, [Int])\nsolve n\n | r == 0, even q = (0, take q $ concat [[i, j] | i <- [1, 2..] | j <- [n, n - 1..]])\n | r == 0 = (1, (++ [q]) $ take (q - 1) $ concat [[i, j] | i <- [1, 2..] | j <- [n, n - 1..]])\n | r /= 0, even q = (1, map (+1) $ snd $ solve (n - 1) )\n | r /= 0 = (0, take (q + 1) $ concat [[i, j] | i <- [1, 2..] | j <- [n - 1, n - 2..]])\n where (q, r) = n `quotRem` 2\n{-\n\n1 2 3 4 5 6 7 8 9 10\n1 + 10 = 2 + 9 = 3 + 8 = 4 + 7 = 5 + 6\n1,10,2,9,5\n3,8,4,7,6\n\n1+6 = 2+5 = 3+4\n\n1+4 = 2 +k\n\n1+5 = 2+4\n3\n\n-}", "positive_code": [{"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms, CPP,\n TupleSections, UnicodeSyntax, LambdaCase,\n MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Integer]] -> [String]\nsol [[n]] = let\n t = div (n*(n+1)) 2\n diff = fromBool (t`mod`2 == 1) :: Integer\n res = sol' n (t`div`2)\n in [show diff , intercalate \" \" $ map show ((fromIntegral $ length res):res) ]\n\nsol' :: Integer -> Integer -> [Integer]\nsol' n w\n | w == 0 = []\n | n < w = n : (sol' (n-1) (w-n))\n | n >= w = [w]\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Integer]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}, {"source_code": "module Main where\n\nimport Data.Int\nimport Data.Bits\nimport Control.Applicative\n\nis2Pow :: (Num a, Bits a) => a -> Bool\nis2Pow n = (n .&. (n - 1)) == 0\n\ndecompose :: Int64 -> [Int64]\ndecompose = go 1\n where go bit 0 = []\n go bit n | odd n = bit : bits\n | otherwise = bits\n where n' = n `div` 2\n bits = go (2 * bit) (n `div` 2)\n\nprefixSums :: (Num a) => [a] -> [a]\nprefixSums = scanl (+) 0\n\nsolve :: Int64 -> (Int64, [Int64])\nsolve n = (rsum - lsum, notPows ++ pows)\n where sum = n * (n + 1) `div` 2\n lsum = sum `div` 2\n rsum = sum - lsum\n\n all = filter (not . is2Pow) $ [1 .. n]\n candidates = takeWhile (<= lsum) $ prefixSums all\n\n notPows = take (length candidates - 1) all\n pows = decompose (lsum - last candidates)\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let (diff, vs) = solve n\n print diff\n putStrLn . unwords $ map show (fromIntegral (length vs) : vs)\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Data.Int\nimport Data.Bits\nimport Control.Applicative\n\nis2Pow :: (Num a, Bits a) => a -> Bool\nis2Pow n = (n .&. (n - 1)) == 0\n\ndecompose :: Int64 -> [Int64]\ndecompose = go 1\n where go bit 0 = []\n go bit n | odd n = bit : bits\n | otherwise = bits\n where n' = n `div` 2\n bits = go (2 * bit) (n `div` 2)\n\nprefixSums :: (Num a) => [a] -> [a]\nprefixSums = scanl (+) 0\n\nsolve :: Int64 -> (Int64, [Int64])\nsolve n = (rsum - lsum, take (length candidates) all ++ decompose (lsum - last candidates))\n where sum = n * (n + 1) `div` 2\n lsum = sum `div` 2\n rsum = sum - lsum\n\n all = filter (not . is2Pow) $ [1 .. n]\n candidates = takeWhile (<= lsum) $ prefixSums all\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let (diff, vs) = solve n\n print diff\n putStrLn . unwords $ map show (fromIntegral (length vs) : vs)\n"}, {"source_code": "module Main where\n\nimport Data.Int\nimport Control.Applicative\n\ndecompose :: Int64 -> [Int64]\ndecompose = go 1\n where go bit 0 = []\n go bit n | odd n = bit : bits\n | otherwise = bits\n where n' = n `div` 2\n bits = go (2 * bit) (n `div` 2)\n\nsolve :: Int64 -> (Int64, [Int64])\nsolve n | even sum = (0, decompose (sum `div` 2))\n | otherwise = (2, decompose (sum `div` 2))\n where sum = n * (n + 1) `div` 2\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let (diff, vs) = solve n\n print diff\n putStrLn . unwords $ map show (fromIntegral (length vs) : vs)\n"}, {"source_code": "module Main where\n\nimport Data.Int\nimport Control.Applicative\n\ndecompose :: Int64 -> [Int64]\ndecompose = go 1\n where go bit 0 = []\n go bit n | odd n = bit : bits\n | otherwise = bits\n where n' = n `div` 2\n bits = go (2 * bit) (n `div` 2)\n\nsolve :: Int64 -> (Int64, [Int64])\nsolve n | even sum = (0, decompose (sum `div` 2))\n | otherwise = (1, decompose (sum `div` 2))\n where sum = n * (n + 1) `div` 2\n\nmain :: IO ()\nmain = do\n n <- read <$> getLine\n let (diff, vs) = solve n\n print diff\n putStrLn . unwords $ map show (fromIntegral (length vs) : vs)\n"}, {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms, CPP,\n TupleSections, UnicodeSyntax, LambdaCase,\n MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[n]] = let\n diff = fromBool (n == 1 || n`mod`2 == 0) :: Int\n res = sol' n ((n*(n+1))`div`4)\n in [ show diff , intercalate \" \" $ map show (length res:res) ]\n\nsol' n w\n | w == 0 = []\n | n < w = n : sol' (n-1) (w-n)\n | n >= w = [w]\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}, {"source_code": "{- written by MarekCerny.com -}\n{-# LANGUAGE ViewPatterns, PatternSynonyms, CPP,\n TupleSections, UnicodeSyntax, LambdaCase,\n MultiWayIf #-}\nimport Data.Tuple\nimport Data.Bits\nimport Data.Maybe\nimport Data.Function\nimport Data.List\nimport Control.Exception\nimport qualified Data.HashMap.Strict as M\nimport Data.Sequence (Seq, (|>), (<|), (><))\nimport qualified Data.Sequence as S\n\nmain = interact $ unlines . sol . allInt . lines\n\nsol :: [[Int]] -> [String]\nsol [[n]] = let\n t = div (n*(n+1)) 2\n diff = fromBool (n == 1 || t`mod`2 == 1) :: Int\n res = sol' n (t`div`2)\n in [ show diff , intercalate \" \" $ map show (length res:res) ]\n\nsol' n w\n | w == 0 = []\n | n < w = n : sol' (n-1) (w-n)\n | n >= w = [w]\n\n--------------------------------------------------------------------------------\ngroupOn :: Int -> [a] -> [[a]]\ngroupOn _ [] = []\ngroupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds\n\nfromBool :: Num a => Bool -> a\nfromBool b = if b then 1 else 0\n\nallInt :: [String] -> [[Int]]\nallInt = map ((map read) . words)\n\nswrt :: Ord a => (a, a) -> (a, a)\nswrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)\n\nwrap :: a -> [a]\nwrap x = [x]\n\ntoSnd :: a->b-> (a,b)\ntoSnd x y = (x,y)\n\ntoFst :: b->a-> (a,b)\ntoFst y x = (x,y)\n--------------------------------------------------------------------------------\npattern Empty <- (S.viewl -> S.EmptyL)\npattern x :< xs <- (S.viewl -> x S.:< xs)\npattern xs :> x <- (S.viewr -> xs S.:> x)\n--------------------------------------------------------------------------------\n"}], "src_uid": "4c387ab2a0d028141634ade32ae97d03"} {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nfst3 (x,_,_) = x\nsnd3 (_,x,_) = x\nthird3 (_,_,x) = x\n\nreadOneStock = do\n input <- getLine\n let strs = words input\n return (((strs !! 0)!!0), read (strs !! 1)::Int, read (strs !! 2)::Int)\n\ncmp::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp a b\n | fst3 a == fst3 b = comparing snd3 a b\n | otherwise = comparing fst3 a b\n \ncmp2::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp2 a b\n | fst3 a == fst3 b = comparing snd3 a b\n | fst3 a < fst3 b = GT\n | fst3 a > fst3 b = LT\n\ngp::(Char,Int,Int) -> (Char,Int,Int) -> Bool\ngp a b\n | fst3 a == fst3 b && snd3 a == snd3 b = True\n | otherwise = False\n\ndisplay [] = do\n putStrLn \"\"\ndisplay (s:ss) = do\n putStrLn (fst3 s : \" \" ++ show(snd3 s) ++ \" \" ++ show(third3 s))\n display ss\n\nchoose (st:stocks) 0 c = []\nchoose [] _ _ = []\nchoose (st:stocks) s c\n | fst3 st == c = st:choose stocks (s-1) c\n | otherwise = []\n\nwork sortedStocks s = choose sortedStocks s 'S' ++ choose (reverse sortedStocks) s 'B'\n\nmergeHelper::[(Char,Int,Int)]->Int\nmergeHelper [] = 0\nmergeHelper (x:xs) = third3 x + mergeHelper xs\n\nmerge::[(Char,Int,Int)]->(Char,Int,Int)\nmerge xs = (fst3 x, snd3 x, mergeHelper xs)\n where x = xs !! 0\n\nmain = do\n input <- getLine\n let [n,s] = [read x::Int|x <- words input]\n stocks <- replicateM n readOneStock\n let sortedStocks = [merge x | x <- groupBy gp (sortBy cmp2 stocks)]\n let ans = work sortedStocks s\n display(sortBy (flip cmp) ans)", "positive_code": [{"source_code": "import qualified Data.Map as M\nmain=interact $ solve . lines\nsolve (ns:x) = concatMap (f \"S\") (reverse sell) ++ concatMap (f \"B\") buy\n where [n,s] = map read $ words ns\n merge [] m1 m2 = [M.toAscList m1, M.toDescList m2]\n merge (x:xs) m1 m2 = let t = head x\n [k,v] = map read $ words $ drop 2 x \n f k new old = new + old\n in if t=='S' then merge xs (M.insertWithKey f k v m1) m2 else merge xs m1 $ M.insertWithKey f k v m2\n [sell,buy] = map (\\x->take (min s $ length x) x) $ merge x M.empty M.empty\n f c x = c ++ \" \" ++ (show $ fst x) ++ \" \" ++ (show $ snd x) ++ \"\\n\"\n"}, {"source_code": "import qualified Data.IntMap.Strict as I\nimport Control.Monad\n\nmain :: IO()\nmain = do\n\t[n,k] <- fmap (map (\\x -> read x::Int) .words) getLine\n\t(b,s) <- solve n I.empty I.empty\n\tlet a1 = take k (I.toList s)\n\t a2 = take k (reverse (I.toList b))\n\tforM_ (reverse a1) $ \\(i,j) -> do {putStrLn (\"S \" ++ (show i) ++ \" \" ++ (show j))}\n\tforM_ a2 $ \\(i,j) -> do {putStrLn (\"B \" ++ (show i) ++ \" \" ++ (show j))}\n\nsolve :: Int -> I.IntMap Int -> I.IntMap Int -> IO (I.IntMap Int,I.IntMap Int)\nsolve 0 m1 m2 = return (m1,m2)\nsolve x b s = do\n\t[d,p',q'] <- fmap words getLine\n\tlet p = read p' :: Int\n\t q = read q' :: Int\n\tcase d of\n\t\t\"B\" -> if I.lookup p b == Nothing then solve (x-1) (I.insert p q b) s else solve (x-1) (I.update (\\x -> return (x+q)) p b) s\n\t\t\"S\" -> if I.lookup p s == Nothing then solve (x-1) b (I.insert p q s) else solve (x-1) b (I.update (\\x -> return (x+q)) p s)\t\n"}, {"source_code": "-- Codeforces 572B\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n [n, s] <- fmap (map read . words) getLine :: IO [Int]\n replicateM n getLine >>= putStrLn . solve s . map words\n\nsolve :: Int -> [[String]] -> String\nsolve s book = foldl (\\acc a -> (acc++a++\"\\n\")) \"\" $ (reverse $ take s $ reverse slist) ++ (take s blist) where\n [slist, blist] = map (\\c -> map (\\ss -> c ++ \" \" ++ (ss!!0!!1) ++ \" \" ++ (show (foldl (\\acc k -> acc + (read (k!!2) :: Int)) 0 ss))) $ groupBy (\\a b -> (a!!1)==(b!!1)) $ sortBy (\\a b -> compare (read (b!!1) :: Int) (read (a!!1) :: Int)) $ filter (\\x -> (x!!0) == c) book) [\"S\", \"B\"]\n"}, {"source_code": "import Data.List (sort)\n\ndata ReqType = Buy | Sell\n deriving (Eq, Ord)\ndata Request = Request {reqType :: ReqType, price :: Int, amount :: Int}\n deriving (Eq, Ord)\n \nunite :: Request -> Request -> Request\nunite (Request t p q1) (Request _ _ q2) = Request t p (q1+q2)\n\ncanUnite :: Request -> Request -> Bool\ncanUnite (Request t1 p1 _) (Request t2 p2 _) = t1 == t2 && p1 == p2\n\nreadReq :: String -> Request\nreadReq s | c == \"B\" = Request Buy p q\n | c == \"S\" = Request Sell p q\n where [c,p',q'] = words s\n p = read p'\n q = read q'\n \nwriteReq :: Request -> String\nwriteReq (Request t p q) = unwords [case t of\n Sell -> \"S\"\n Buy -> \"B\", \n show p, show q]\n \ngetList :: (Read a) => IO [a]\ngetList = fmap (map read . words) getLine\n \nmain = do\n [n,s] <- getList\n xs <- mapM (\\_ -> fmap readReq getLine) [1..n]\n let ys = solve s xs\n mapM_ (putStrLn . writeReq) ys\n \nsolve :: Int -> [Request] -> [Request]\nsolve s = (\\(a,b) -> reverse (take s (reverse a)) ++ take s b) . span ((==Sell) . reqType) . reverse . f . sort\n where f [] = []\n f [x] = [x]\n f (x:y:ys) = if canUnite x y then f ((unite x y):ys)\n else x : f (y:ys)\n "}], "negative_code": [{"source_code": "-- Codeforces 572B\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Char\n\nmain :: IO ()\nmain = do\n [n, s] <- fmap (map read . words) getLine :: IO [Int]\n replicateM n getLine >>= putStrLn . solve s . map words\n\nsolve :: Int -> [[String]] -> String\nsolve s book = foldl (\\acc a -> (acc++a++\"\\n\")) \"\" $ concatMap (\\c -> take s $ map (\\ss -> c ++ \" \" ++ (ss!!0!!1) ++ \" \" ++ (show (foldl (\\acc k -> acc + (read (k!!2) :: Int)) 0 ss))) $ groupBy (\\a b -> (a!!1)==(b!!1)) $ reverse $ sortBy (\\a b -> compare (read (a!!1) :: Int) (read (b!!1) :: Int)) $ filter (\\x -> (x!!0) == c) book) [\"S\", \"B\"]\n\n"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nfst3 (x,_,_) = x\nsnd3 (_,x,_) = x\nthird3 (_,_,x) = x\n\nreadOneStock = do\n input <- getLine\n let strs = words input\n return (((strs !! 0)!!0), read (strs !! 1)::Int, read (strs !! 2)::Int)\n\ncmp::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp a b\n | fst3 a == fst3 b = comparing snd3 a b\n | otherwise = comparing fst3 a b\n\ngp::(Char,Int,Int) -> (Char,Int,Int) -> Bool\ngp a b\n | fst3 a == fst3 b && snd3 a == snd3 b = True\n | otherwise = False\n\ndisplay [] = do\n putStrLn \"\"\ndisplay (s:ss) = do\n putStrLn (fst3 s : \" \" ++ show(snd3 s) ++ \" \" ++ show(third3 s))\n display ss\n\nchoose stocks 0 l = []\nchoose stocks s l = [stocks !! (s-1)] ++ choose stocks (s-1) l ++ [stocks !! (l - s - 1)]\n\nwork sortedStocks s\n | 2*s <= l = choose sortedStocks s l\n | otherwise = sortedStocks\n where l = length sortedStocks\n\nmergeHelper::[(Char,Int,Int)]->Int\nmergeHelper [] = 0\nmergeHelper (x:xs) = third3 x + mergeHelper xs\n\nmerge::[(Char,Int,Int)]->(Char,Int,Int)\nmerge xs = (fst3 x, snd3 x, mergeHelper xs)\n where x = xs !! 0\n\nmain = do\n input <- getLine\n let [n,s] = [read x::Int|x <- words input]\n stocks <- replicateM n readOneStock\n let sortedStocks = [merge x | x <- groupBy gp (sortBy (flip cmp) stocks)]\n let ans = work sortedStocks s\n display(sortBy (flip cmp) ans)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nfst3 (x,_,_) = x\nsnd3 (_,x,_) = x\nthird3 (_,_,x) = x\n\nreadOneStock = do\n input <- getLine\n let strs = words input\n return (((strs !! 0)!!0), read (strs !! 1)::Int, read (strs !! 2)::Int)\n\ncmp::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp a b\n | fst3 a == fst3 b = comparing snd3 a b\n | otherwise = comparing fst3 a b\n \ncmp2::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp2 a b\n | fst3 a == fst3 b = comparing snd3 a b\n | fst3 a < fst3 b = GT\n | fst3 a > fst3 b = LT\n\ngp::(Char,Int,Int) -> (Char,Int,Int) -> Bool\ngp a b\n | fst3 a == fst3 b && snd3 a == snd3 b = True\n | otherwise = False\n\ndisplay [] = do\n putStrLn \"\"\ndisplay (s:ss) = do\n putStrLn (fst3 s : \" \" ++ show(snd3 s) ++ \" \" ++ show(third3 s))\n display ss\n\nchoose stocks 0 l = []\nchoose stocks s l = [stocks !! (s-1)] ++ choose stocks (s-1) l ++ [stocks !! (l - s)]\n\nwork sortedStocks s\n | 2*s <= l = choose sortedStocks s l\n | otherwise = sortedStocks\n where l = length sortedStocks\n\nmergeHelper::[(Char,Int,Int)]->Int\nmergeHelper [] = 0\nmergeHelper (x:xs) = third3 x + mergeHelper xs\n\nmerge::[(Char,Int,Int)]->(Char,Int,Int)\nmerge xs = (fst3 x, snd3 x, mergeHelper xs)\n where x = xs !! 0\n\nmain = do\n input <- getLine\n let [n,s] = [read x::Int|x <- words input]\n stocks <- replicateM n readOneStock\n let sortedStocks = [merge x | x <- groupBy gp (sortBy cmp2 stocks)]\n let ans = work sortedStocks s\n display(sortBy (flip cmp) ans)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Ord\n\nfst3 (x,_,_) = x\nsnd3 (_,x,_) = x\nthird3 (_,_,x) = x\n\nreadOneStock = do\n input <- getLine\n let strs = words input\n return (((strs !! 0)!!0), read (strs !! 1)::Int, read (strs !! 2)::Int)\n\ncmp::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp a b\n | fst3 a == fst3 b = comparing snd3 a b\n | otherwise = comparing fst3 a b\n \ncmp2::(Char,Int,Int) -> (Char,Int,Int) -> Ordering\ncmp2 a b\n | fst3 a == fst3 b = comparing snd3 a b\n | fst3 a < fst3 b = GT\n | fst3 a > fst3 b = LT\n\ngp::(Char,Int,Int) -> (Char,Int,Int) -> Bool\ngp a b\n | fst3 a == fst3 b && snd3 a == snd3 b = True\n | otherwise = False\n\ndisplay [] = do\n putStrLn \"\"\ndisplay (s:ss) = do\n putStrLn (fst3 s : \" \" ++ show(snd3 s) ++ \" \" ++ show(third3 s))\n display ss\n\nchoose stocks 0 l = []\nchoose stocks s l = [stocks !! (s-1)] ++ choose stocks (s-1) l ++ [stocks !! (l - s)]\n\nwork sortedStocks s\n | 2*s <= l = choose sortedStocks s l\n | otherwise = sortedStocks\n where l = length sortedStocks\n\nmergeHelper::[(Char,Int,Int)]->Int\nmergeHelper [] = 0\nmergeHelper (x:xs) = third3 x + mergeHelper xs\n\nmerge::[(Char,Int,Int)]->(Char,Int,Int)\nmerge xs = (fst3 x, snd3 x, mergeHelper xs)\n where x = xs !! 0\n\nmain = do\n input <- getLine\n let [n,s] = [read x::Int|x <- words input]\n stocks <- replicateM n readOneStock\n let sortedStocks = [merge x | x <- groupBy gp (sortBy cmp2 stocks)]\n print sortedStocks\n let ans = work sortedStocks s\n display(sortBy (flip cmp) ans)"}], "src_uid": "267c04c77f97bbdf7697dc88c7bfa4af"} {"source_code": "import System.Environment\n\nmain = \n do str1 <- readFile \"input.txt\"\n let l = map read (words str1)\n let (k:xs) = drop 1 l\n writeFile \"output.txt\" (show (solve xs k 0))\n \nsolve [] k sum = sum\nsolve (x:xs) k sum = if x >= 3*k then (solve xs k (sum + x-3*k)) else (solve xs k (sum + (x `mod` k)))", "positive_code": [{"source_code": "main = do\n\tinput <- fmap lines $ readFile \"input.txt\" \n\tlet [n, k] = map read . words . head $ input\n\tlet js = map read . words $ input !! 1\n\tlet f x\n\t\t| x >= k * 3 = x - k * 3\n\t\t| otherwise = x `mod` k\n\twriteFile \"output.txt\" . show . sum . map f $ js\n"}, {"source_code": "gao[[n,k],xs] = show.sum.map (\\x -> if x < (3*k) then x `mod` k else x - (3*k)) $ xs\nmain = readFile \"input.txt\" >>= writeFile \"output.txt\" . gao . map (map read. words) . lines\n"}, {"source_code": "\nimport IO\n\nsolve :: Int -> [Int] -> Int\nsolve k xs = foldl (+) 0 (map f xs)\n where\n f x\n | x >= 3*k = x - 3*k\n | otherwise = mod x k\n\nmain :: IO ()\nmain = do\n hInput <- openFile \"input.txt\" ReadMode\n hOutput <- openFile \"output.txt\" WriteMode\n \n [n, k] <- hGetLine hInput >>= return . map read . words\n xs <- hGetLine hInput >>= return . map read . words \n hPutStrLn hOutput (show $ solve k xs)\n \n hClose hOutput\n hClose hInput\n"}, {"source_code": "\nsolve [[_, k], xs] = show $ foldr f 0 xs\n where f a b = b + a - k * ((a `div` k) `min` 3)\n\nmain = do text <- readFile \"input.txt\"\n writeFile \"output.txt\" (solve $ map (map read.words) $ lines text)"}, {"source_code": "import System.Environment\n\nmain = \n do str1 <- readFile \"input.txt\"\n let l = map read (words str1)\n let (k:xs) = drop 1 l\n writeFile \"output.txt\" (show (solve xs k 0))\n \nsolve [] k sum = sum\nsolve (x:xs) k sum = if x >= 3*k then (solve xs k (sum + x-3*k)) else (solve xs k (sum + (x `mod` k)))"}], "negative_code": [{"source_code": "gao[[n,k],xs] = show.sum.map (\\x -> if x < 9 then x `mod` 3 else x - 9) $ xs\nmain = readFile \"input.txt\" >>= writeFile \"output.txt\" . gao . map (map read. words) . lines\n"}, {"source_code": "import System.Environment\n\nmain = \n do str1 <- readFile \"input.txt\"\n let l = map read (words str1)\n let (k:xs) = drop 1 l\n print (solve xs k 0)\n \nsolve [] k sum = sum\nsolve (x:xs) k sum = if x >= 3*k then (solve xs k (sum + x-3*k)) else (solve xs k (sum + (x `mod` k)))"}, {"source_code": "import System.Environment\n\nmain = \n do str1 <- readFile \"input.txt\"\n let l = map read (words str1)\n let (k:xs) = drop 1 l\n print (solve xs k 0)\n \nsolve [] k sum = sum\nsolve (x:xs) k sum = if x > 3*k then (solve xs k (sum + x-3*k)) else (solve xs k (sum + (x `mod` k)))"}], "src_uid": "f9a691cdf7047ab82d2e2c903a53fc7e"} {"source_code": "solve :: Int -> String\nsolve 1 = \"YES\\n2 1\\n1 2\\n\" -- special case\nsolve n | even n = \"NO\\n\" -- parity argument on each side of bridge\nsolve n = let\n size = 2*n+4\n edgeCount = quot (n*size) 2\n edgeList = concat [[(x,y),(x+n+2, y+n+2)]\n | x <- [1..n], y <- [x+1 .. n+1], quot x 2 /= quot y 2]\n ++ concat [[(x, n+2), (x+n+2, 2*n+4)] | x <- [2..n]]\n ++ [(n+2, 2*n+4)]\n dispEdge (x, y) = show x ++ \" \" ++ show y ++ \"\\n\"\n in \"YES\\n\" ++ concatMap dispEdge ((size, edgeCount) : edgeList) \n\nmain :: IO ()\nmain = interact (concatMap (solve . read) . lines)\n\n", "positive_code": [{"source_code": "import Control.Monad (guard)\nimport Data.List (delete)\n\ntype Edge = (Int, Int)\ntype Graph = [Edge]\n\nvertices :: Graph -> Int\nvertices = maximum . map (\\(a, b) -> max a b)\n\nmerge :: Graph -> Graph -> Graph\nmerge g g' = g ++ (map (\\(a, b) -> (a + n, b + n)) g')\n where n = vertices g\n\n-- deg(v_1) = deg(v_2) = ... = deg(v_{d + 1}) = d - 1\nalmostClique :: Int -> Graph\nalmostClique d = do i <- [0 ..d]\n j <- delete (i + (d + 1) `div` 2) [i + 1..d]\n return (1 + i, 1 + j)\n\n-- deg(v_1) = d - 1, deg(v_2) = deg(v_3) = ... = deg(v_{d + 2}) = d\nalmostRegular :: Int -> Graph\nalmostRegular d = (almostClique d) ++ [(i, d + 2) | i <- [2..d + 1]]\n\nsolve :: Int -> Maybe Graph\nsolve d\n | even d = Nothing\n | d == 1 = Just $ [(1, 2)]\n | otherwise = Just $ (1, 1 + n) : merge g g\n where g = almostRegular d\n n = vertices g\n\nformat :: Maybe Graph -> String\nformat Nothing = \"NO\"\nformat (Just g) = unlines $ \"YES\" : map pp ((vertices g, length g) : g)\n where pp (a, b) = unwords . map show $ [a, b]\n\nmain :: IO ()\nmain = putStrLn . format . solve . read =<< getContents\n"}, {"source_code": "data Edge = Edge Int Int\ndata Graph = Graph [Edge]\n\ninstance Show Edge where\n show (Edge a b) = (show a) ++ \" \" ++ (show b)\n\ninstance Show Graph where\n show (Graph []) = \"\"\n show (Graph (e:es)) = (show e) ++ \"\\n\" ++ (show (Graph es))\n \nmain :: IO()\nmain = putStrLn . solve . read =<< getLine\n\nsolve :: Int -> String\nsolve k | even k = \"NO\"\n | k == 1 = \"YES\\n2 1\\n1 2\"\n | otherwise = \"YES\\n\" ++ (show (k + k + 4)) ++ \" \" ++ (show (k * (k + 2))) ++ \"\\n\" ++ (show (genGraph k))\n \ngenGraph :: Int -> Graph\ngenGraph k = Graph ([(Edge 1 (k + 3))] ++ (genSub 1 (k + 2)) ++ (genSub (k + 3) (k + k + 4)))\n\ngenSub :: Int -> Int -> [Edge]\ngenSub a b = (genOut (a + 1)) ++ (genIn (a + 2) (a + 1))\n where\n genOut :: Int -> [Edge]\n genOut c | c > b - 2 = []\n | otherwise = ((Edge a c):(genOut (c + 1)))\n \n genIn :: Int -> Int -> [Edge]\n genIn c d | c >= b && d >= b = []\n | d >= c = genIn (c + 1) (a + 1)\n | even (c - a) && c == d + 1 && c <= b - 2 = genIn (c + 1) (a + 1)\n | otherwise = ((Edge d c):(genIn c (d + 1)))"}, {"source_code": "import Debug.Trace (trace)\nimport Data.List (sort)\n\ndata Graph = Graph Int [(Int, Int)]\n deriving (Show)\n\nconnect :: Graph -> Graph -> Graph\nconnect (Graph n1 e1) (Graph n2 e2) = Graph (n1 + n2) (e1 ++ (map shift e2) ++ [(1, 1 + n1)])\n where shift (a, b) = (n1 + a, n1 + b)\n\nrecur :: Int -> [(Int, Int)]\nrecur 0 = []\nrecur d = (recur (d - 2)) ++ [(i, d - 1) | i <- [1..d - 2]] ++ [(i, d) | i <- [1..d - 2]]\n\nconstruct :: Int -> Graph\nconstruct d = Graph (d + 2) (baseEdges ++ extraEdges)\n where baseEdges = recur (d + 1)\n extraEdges = [(i, d + 2) | i <- [2..d + 1]]\n\nsolve :: Int -> Maybe Graph\nsolve 1 = Just (Graph 2 [(1, 2)])\nsolve d = if even d\n then Nothing\n else Just (connect g g)\n where g = construct d\n\nformat :: Maybe Graph -> String\nformat Nothing = \"NO\"\nformat (Just (Graph n edges)) = \"YES\\n\" ++ (show n) ++ \" \" ++ (show (length edges)) ++ \"\\n\" ++ (unlines . map showEdge $ edges)\n where showEdge (a, b) = (show a) ++ \" \" ++ (show b)\n\nmain :: IO ()\nmain = putStrLn . format . solve . read =<< getContents\n"}], "negative_code": [{"source_code": "import Data.List (sort)\n\ndata Graph = Graph Int [(Int, Int)]\n deriving (Show)\n\nconnect :: Graph -> Graph -> Graph\nconnect (Graph n1 e1) (Graph n2 e2) = Graph (n1 + n2) (e1 ++ (map shift e2))\n where shift (a, b) = (n1 + a, n1 + b)\n\nrecur :: Int -> [(Int, Int)]\nrecur 0 = []\nrecur d = (recur (d - 2)) ++ [(i, d - 1) | i <- [1..d - 2]] ++ [(i, d) | i <- [1..d - 2]]\n\nconstruct :: Int -> Graph\nconstruct d = Graph (d + 2) (baseEdges ++ extraEdges)\n where baseEdges = recur (d + 1)\n extraEdges = [(i, d + 2) | i <- [2..d + 1]]\n\nsolve :: Int -> Maybe Graph\nsolve 1 = Just (Graph 1 [(1, 2)])\nsolve d = if even d\n then Nothing\n else Just (connect g g)\n where g = construct d\n\nformat :: Maybe Graph -> String\nformat Nothing = \"NO\"\nformat (Just (Graph n edges)) = \"YES\\n\" ++ (show n) ++ \" \" ++ (show (length edges)) ++ \"\\n\" ++ (unlines . map showEdge $ edges)\n where showEdge (a, b) = (show a) ++ \" \" ++ (show b)\n\nmain :: IO ()\nmain = putStrLn . format . solve . read =<< getContents\n"}, {"source_code": "import Data.List (sort)\n\ndata Graph = Graph Int [(Int, Int)]\n deriving (Show)\n\nconnect :: Graph -> Graph -> Graph\nconnect (Graph n1 e1) (Graph n2 e2) = Graph (n1 + n2) (e1 ++ (map shift e2))\n where shift (a, b) = (n1 + a, n1 + b)\n\nrecur :: Int -> [(Int, Int)]\nrecur 0 = []\nrecur d = (recur (d - 2)) ++ [(i, d - 1) | i <- [1..d - 2]] ++ [(i, d) | i <- [1..d - 2]]\n\nconstruct :: Int -> Graph\nconstruct d = Graph (d + 2) (baseEdges ++ extraEdges)\n where baseEdges = recur (d + 1)\n extraEdges = [(i, d + 2) | i <- [2..d + 1]]\n\nsolve :: Int -> Maybe Graph\nsolve 1 = Just (Graph 2 [(1, 2)])\nsolve d = if even d\n then Nothing\n else Just (connect g g)\n where g = construct d\n\nformat :: Maybe Graph -> String\nformat Nothing = \"NO\"\nformat (Just (Graph n edges)) = \"YES\\n\" ++ (show n) ++ \" \" ++ (show (length edges)) ++ \"\\n\" ++ (unlines . map showEdge $ edges)\n where showEdge (a, b) = (show a) ++ \" \" ++ (show b)\n\nmain :: IO ()\nmain = putStrLn . format . solve . read =<< getContents\n"}], "src_uid": "1e061d8c4bff217047ddc58e88be0c3f"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (join, replicateM)\nimport Control.Monad.State.Strict (State, execState, get, put)\nimport Data.Char (ord)\nimport Data.List (sort)\nimport Data.Monoid ((<>))\nimport Data.Ord (Down(Down))\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence (Seq, Seq(Empty), Seq((:<|)), Seq((:|>)), (!?), index)\nimport qualified Data.Sequence as S (replicate, update)\nimport GHC.TypeNats (type (+), type (^), KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\nimport qualified Data.ByteString.Char8 as BS (getContents, lines, readInt, words, getLine, foldl)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField (10 ^ 9 + 7)\n\ndata Event =\n Event\n { getKey :: !Int\n , getMark :: !(Either Int Int)\n }\n deriving (Show, Eq)\n\ninstance Ord Event where\n compare (Event k m) (Event k' m') = compare (Down k) (Down k') <> compare m m'\n\ntype Env = (Bool, Ways, Seq Ways)\n\ntype Ways = (Int, MField)\n\nupdate :: Ways -> Ways -> Ways\nupdate (b, c) (b', c')\n | b < b' = (b, c)\n | b == b' = (b, c + c')\n | otherwise = (b', c')\n\nsolve :: Event -> State Env ()\nsolve (Event k m) = do\n (large, w@(best, count), mem) <- get\n case m of\n Left i -> do\n let (b, c) = index mem i\n b' = b + k\n w' = update w (b', c)\n put (False, w', mem)\n Right i -> do\n let mem' =\n if large\n then S.update i (update (best - k, count) (0, 1)) mem\n else S.update i (best - k, count) mem\n put (large, w, mem')\n\nmain = do\n n <- fmap parseInt getLine\n contents <- getContents\n let a = fmap parseInts . lines $ contents\n e =\n join\n [[Event l (Left i), Event r (Right i)] | (i, [r, l]) <- zip [0 ..] a]\n se = sort e\n mk = maximum . fmap head $ a\n initial = (True, (mk, 0), S.replicate n (0, 0))\n (_, (_, ret), _) = execState (mapM solve se) initial\n print ret\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (join, replicateM)\nimport Control.Monad.State.Strict (State, execState, get, put)\nimport Data.Char (ord)\nimport Data.List (sort)\nimport Data.Monoid ((<>))\nimport Data.Ord (Down(Down))\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence (Seq, Seq(Empty), Seq((:<|)), Seq((:|>)), (!?), index)\nimport qualified Data.Sequence as S (replicate, update)\nimport GHC.TypeNats (type (+), type (^), KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInt = foldl (\\acc c -> acc * 10 + ord c - 48) 0\n\nparseInts = fmap parseInt . words\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField (10 ^ 9 + 7)\n\ndata Event =\n Event\n { getKey :: !Int\n , getMark :: !(Either Int Int)\n }\n deriving (Show, Eq)\n\ninstance Ord Event where\n compare (Event k m) (Event k' m') = compare (Down k) (Down k') <> compare m m'\n\ntype Env = (Bool, Ways, Seq Ways)\n\ntype Ways = (Int, MField)\n\nupdate :: Ways -> Ways -> Ways\nupdate (b, c) (b', c')\n | b < b' = (b, c)\n | b == b' = (b, c + c')\n | otherwise = (b', c')\n\nsolve :: Event -> State Env ()\nsolve (Event k m) = do\n (large, w@(best, count), mem) <- get\n case m of\n Left i -> do\n let (b, c) = index mem i\n b' = b + k\n w' = update w (b', c)\n put (False, w', mem)\n Right i -> do\n let mem' =\n if large\n then S.update i (update (best - k, count) (0, 1)) mem\n else S.update i (best - k, count) mem\n put (large, w, mem')\n\nmain = do\n n <- fmap parseInt getLine\n a <- replicateM n (fmap parseInts getLine)\n let e =\n join\n [[Event l (Left i), Event r (Right i)] | (i, [r, l]) <- zip [0 ..] a]\n se = sort e\n mk = maximum . fmap head $ a\n initial = (True, (mk, 0), S.replicate n (0, 0))\n (_, (_, ret), _) = execState (mapM solve se) initial\n print ret\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (join, replicateM)\nimport Control.Monad.State.Strict (State, execState, get, put)\nimport qualified Data.ByteString.Char8 as BS\n ( dropWhile\n , foldl\n , getContents\n , getLine\n , lines\n , readInt\n , words\n )\nimport Data.Char (isSpace, ord)\nimport Data.List (sort)\nimport Data.Maybe (fromJust)\nimport Data.Monoid ((<>))\nimport Data.Ord (Down(Down))\nimport Data.Ratio (denominator, numerator)\nimport Data.Sequence (Seq, Seq(Empty), Seq((:<|)), Seq((:|>)), (!?), index)\nimport qualified Data.Sequence as S (replicate, update)\nimport GHC.TypeNats (type (+), type (^), KnownNat, Nat, natVal)\nimport Numeric.Natural (Natural)\n\nparseInts s = parse id s []\n where\n parse r s =\n case BS.readInt s of\n Nothing -> r\n Just (x, s') -> parse (r . (x :)) (BS.dropWhile isSpace s')\n\nnewtype PrimeField (p :: Nat) =\n PrimeField Natural\n deriving (Eq)\n\nchar :: KnownNat p => PrimeField p -> Natural\nchar = natVal\n\ninstance KnownNat p => Show (PrimeField p) where\n show (PrimeField a) = show a\n\ninstance KnownNat p => Num (PrimeField p) where\n (+) x@(PrimeField a) (PrimeField b) =\n PrimeField $\n if a + b >= mm\n then a + b - mm\n else a + b\n where\n mm = char x\n (*) x@(PrimeField a) (PrimeField b) = PrimeField $ (a * b) `mod` mm\n where\n mm = char x\n fromInteger a = ret\n where\n mm = toInteger (char ret)\n ret = PrimeField . fromInteger . (`mod` mm) . (+ mm) . (`mod` mm) $ a\n negate x@(PrimeField a) =\n PrimeField $\n if a == 0\n then 0\n else mm - a\n where\n mm = char x\n abs = id\n signum _ = 1\n\ninstance KnownNat p => Fractional (PrimeField p) where\n recip x@(PrimeField a)\n | a == 0 = undefined\n | a == 1 = 1\n | otherwise = negate (PrimeField q) * recip (PrimeField r)\n where\n mm = char x\n (q, r) = mm `divMod` a\n fromRational =\n liftA2 (/) (fromInteger . numerator) (fromInteger . denominator)\n\ntype MField = PrimeField (10 ^ 9 + 7)\n\ndata Event =\n Event\n { getKey :: !Int\n , getMark :: !(Either Int Int)\n }\n deriving (Show, Eq)\n\ninstance Ord Event where\n compare (Event k m) (Event k' m') = compare (Down k) (Down k') <> compare m m'\n\ntype Env = (Bool, Ways, Seq Ways)\n\ntype Ways = (Int, MField)\n\nupdate :: Ways -> Ways -> Ways\nupdate (b, c) (b', c')\n | b < b' = (b, c)\n | b == b' = (b, c + c')\n | otherwise = (b', c')\n\nsolve :: Event -> State Env ()\nsolve (Event k m) = do\n (large, w@(best, count), mem) <- get\n case m of\n Left i -> do\n let (b, c) = index mem i\n b' = b + k\n w' = update w (b', c)\n put (False, w', mem)\n Right i -> do\n let mem' =\n if large\n then S.update i (update (best - k, count) (0, 1)) mem\n else S.update i (best - k, count) mem\n put (large, w, mem')\n\nmain = do\n [n] <- fmap parseInts BS.getLine\n contents <- BS.getContents\n let a = fmap parseInts . BS.lines $ contents\n e =\n join\n [[Event l (Left i), Event r (Right i)] | (i, [r, l]) <- zip [0 ..] a]\n se = sort e\n mk = maximum . fmap head $ a\n initial = (True, (mk, 0), S.replicate n (0, 0))\n (_, (_, ret), _) = execState (mapM solve se) initial\n print ret\n"}], "negative_code": [], "src_uid": "d8c2cb03579142f45d46f1fe22a9b8c0"} {"source_code": "import Control.Monad\r\nimport Data.Maybe\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n ~[n] <- readInts\r\n ps <- readInts\r\n let (as, as') = span (uncurry (==)) $ zip [1..] ps\r\n an = length as\r\n (rcs, rbs) = span (/= an + 1) $ map snd $ reverse as'\r\n putStrLn $ unwords $ map show $ map snd as ++ rbs ++ reverse rcs\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ solve . head =<< readInts\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Data.List\r\nimport Debug.Trace\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nenumerate = zip [0..]\r\n\r\nargmin :: [Int] -> Int\r\nargmin a = let t = enumerate a in\r\n fst $ foldl (\\(mni, mn) (i, x) -> if x < mn then (i, x) else (mni, mn)) (0, 999999999) t\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let pref = (+) (-1) $ maximum $ scanl (\\l x -> if l == x then (l+1) else 0) 1 a\r\n let first = take pref a\r\n let rest = drop pref a\r\n let min_index = argmin rest\r\n let rest_pre = take (1+min_index) rest\r\n let rest_suf = drop (1+min_index) rest\r\n let res = first ++ reverse rest_pre ++ rest_suf\r\n pure $ putInts res\r\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\n\r\nmainFun :: SP Builder\r\nmainFun = do\r\n t <- getInt\r\n fmap mconcat $ replicateM t $ do\r\n n <- getInt\r\n p <- replicateM n getInt\r\n let\r\n (q1, q2) = span (uncurry (==)) $ zip [1..] p\r\n [r1, r2] = map (map snd) [q1, q2]\r\n x = minimum r2\r\n (s2, s3) = span (> x) r2 \r\n pure $ putInts $ r1 ++ take 1 s3 ++ reverse s2 ++ drop 1 s3\r\n\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\n--getNext :: Monad m => S m P.ByteString\r\n--getNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState mainFun inp\r\n P.putStr $ toLazyByteString outp\r\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve :: [Int] -> [Int]\nsolve arr =\n map snd as ++ rbs ++ reverse rcs\n where\n (as, as') = span (uncurry (==)) $ zip [1 ..] arr\n (rcs, rbs) = span (/= length as + 1) $ map snd $ reverse as'\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ unwords $ map show $ solve arr\n"}], "negative_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve :: [Int] -> [Int]\nsolve arr =\n map snd as ++ ras ++ reverse rbs\n where\n (as, as') = span (uncurry (==)) $ zip [1 ..] arr\n (ras, rbs) = span (/= length as + 1) $ map snd $ reverse as'\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ unwords $ map show $ solve arr\n"}, {"source_code": "import Control.Monad (forM_)\n\nsolve str =\n let len = length str\n in if even len && (take (len `div` 2) str == drop (len `div` 2) str) then \"YES\" else \"NO\"\n\nmain :: IO ()\nmain = do\n n <- readLn :: IO Int\n forM_ [1 .. n] $ \\i -> do\n x <- getLine \n putStrLn $ solve x\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nrevv :: [a] -> Int -> Int -> [a]\nrevv arr i j = revvh arr i j ++ drop (j + 1) arr\n\nrevvh :: [a] -> Int -> Int -> [a]\nrevvh arr i j\n | i <= j = revvh arr (i + 1) j ++ [arr !! i]\n | otherwise = []\n\nindex :: Eq t => [t] -> t -> Int -> Int -> Int\nindex arr n i l\n | i < l =\n if arr !! i /= n\n then index arr n (i + 1) l\n else i\n | otherwise = i - 1\n\nsolve :: [Int] -> Int -> Int -> [Int]\nsolve arr i l\n | i < l =\n if arr !! i == (i + 1)\n then arr !! i : solve arr (i + 1) l\n else revv arr i (index arr (i + 1) (i + 1) l)\n | otherwise = arr\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ foldl1 (\\x acc -> x ++ \" \" ++ acc) $ map show $ solve arr 0 n\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nflat :: [[a]] -> [a]\nflat [] = []\nflat [a1] = a1\nflat (a1 : a2) = a1 ++ flat a2\n\nrevv :: [a] -> Int -> Int -> [a]\nrevv arr i j = take i arr ++ revvh arr i j ++ drop (j + 1) arr\n\nrevvh :: [a] -> Int -> Int -> [a]\nrevvh arr i j\n | i <= j = revvh arr (i + 1) j ++ [arr !! i]\n | otherwise = []\n\nsolve :: Ord a => [a] -> Int -> Int -> [a]\nsolve arr i l\n | i < l - 1 =\n if arr !! i > arr !! (i + 1)\n then solveh arr i l\n else solve arr (i + 1) l\n | otherwise = arr\n\nsolveh :: Ord a => [a] -> Int -> Int -> [a]\nsolveh arr i l =\n if l == 1\n then arr\n else minimum $ map (revv arr i) [i + 1 .. l - 1]\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ foldl1 (\\x acc -> x ++ \" \" ++ acc) $ map show $ solve arr 0 n\n"}, {"source_code": "import Data.List (sort)\nimport Control.Monad (forM_)\n\nflat :: [[a]] -> [a]\nflat [] = []\nflat [a1] = a1\nflat (a1 : a2) = a1 ++ flat a2\n\nrevv :: [a] -> (Int, Int) -> [a]\nrevv arr (i, j) = take i arr ++ revvh arr i j ++ drop (j + 1) arr\n\nrevvh :: [a] -> Int -> Int -> [a]\nrevvh arr i j\n | i <= j = revvh arr (i + 1) j ++ [arr !! i]\n | otherwise = []\n\nsolvee arr l i =\n if l == 1\n then arr\n else minimum $ map (revv arr) (flat [[(x, y) | y <- [x + 1 .. l - 1]] | x <- [i .. l - 1]])\n\nsolve arr i l \n | i < l - 1 = if arr !! i > arr !! (i + 1) then solvee arr l i else solve arr (i+1) l\n | otherwise = arr\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ foldl1 (\\x acc -> x ++ \" \" ++ acc) $ map show $ solve arr 0 n\n"}, {"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nflat :: [[a]] -> [a]\nflat [] = []\nflat [a1] = a1\nflat (a1 : a2) = a1 ++ flat a2\n\nrevv :: [a] -> (Int, Int) -> [a]\nrevv arr (i, j) = take i arr ++ revvh arr i j ++ drop (j + 1) arr\n\nrevvh :: [a] -> Int -> Int -> [a]\nrevvh arr i j\n | i <= j = revvh arr (i + 1) j ++ [arr !! i]\n | otherwise = []\n\nsolve arr =\n if l == 1\n then arr\n else minimum (map (revv arr) $ flat [[(x, y) | y <- [x + 1 .. l - 1]] | x <- [0 .. l - 1]])\n where\n l = length arr\n\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n forM_ [1 .. t] $ \\i -> do\n n <- readLn :: IO Int\n l <- getLine\n let arr = map read (words l) :: [Int]\n putStrLn $ foldl1 (\\x acc-> x ++ \" \" ++ acc) $ map show $ solve arr\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\r\nimport Data.ByteString.Builder\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport System.IO\r\nimport Control.Monad.Trans.State\r\nimport Data.Maybe\r\nimport Data.Bits\r\nimport Data.List\r\n\r\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\r\nimport Control.Monad\r\n--import Data.List\r\n--import Data.Array.Unboxed\r\n\r\ntype SP = State P.ByteString\r\ntype S = StateT P.ByteString\r\n\r\nstr = string7\r\n\r\ndropSpace :: P.ByteString -> P.ByteString\r\ndropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough\r\n\r\ngetNext :: Monad m => S m P.ByteString\r\ngetNext = state $ P.span (> ' ') . dropSpace\r\n\r\ngetInt :: Monad m => S m Int\r\ngetInt = state $ fromJust . P.readInt . dropSpace\r\n\r\nputInts :: [Int] -> Builder\r\nputInts vs = let\r\n sepPrim = (,) ' ' Prim.>$<\r\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\r\n in case vs of\r\n [] -> char7 '\\n'\r\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n inp <- P.getContents\r\n let outp = evalState tloop inp\r\n P.putStr $ toLazyByteString outp\r\n\r\ntloop :: SP Builder\r\ntloop = do\r\n t <- getInt\r\n -- let t = 1\r\n fmap mconcat $ replicateM t $ solve\r\n\r\n\r\nenumerate = zip [0..]\r\n\r\nargmin :: [Int] -> Int\r\nargmin a = let t = enumerate a in\r\n snd $ foldl (\\(mni, mn) (i, x) -> if x < mn then (i, x) else (mn, mni)) (999999999, 0) t\r\n\r\nsolve :: SP Builder\r\nsolve = do\r\n n <- getInt\r\n a <- replicateM n getInt\r\n let pref = (+) (-1) $ maximum $ scanl (\\l x -> if l == x then (l+1) else 0) 1 a\r\n if pref == n-1 then pure $ str \"hello\" else pure $ str \"bye\"\r\n let first = take pref a\r\n let rest = drop pref a\r\n let min_index = argmin rest\r\n let rest_pre = take (1+min_index) rest\r\n let rest_suf = drop (1+min_index) rest\r\n let res = first ++ reverse rest_pre ++ rest_suf\r\n pure $ putInts res\r\n"}], "src_uid": "a57823a7ca0f67a07f94175ab59d33de"} {"source_code": "import Control.Monad (liftM)\n\nsolve :: Int -> [(Int, Int)] -> Int\nsolve n as = min a (n - a) + min b (n - b)\n where\n a = length $ filter (\\(a, b) -> a == 0) as\n b = length $ filter (\\(a, b) -> b == 0) as\n\nparsePair :: String -> (Int, Int)\nparsePair line = case map read (words line) of\n [a, b] -> (a, b)\n\nmain :: IO ()\nmain = do\n n <- readLn\n as <- mapM (const $ liftM parsePair getLine) [1..n]\n print $ solve n as", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array\n-- import Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\n-- import Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport System.IO\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n ps <- replicateM n getInts\n\n let\n s1 = sum $ map (!!0) ps\n s2 = sum $ map (!!1) ps\n\n print $ min s1 (n-s1) + min s2 (n-s2)\n"}, {"source_code": "import Data.List\nimport qualified Data.Map as M\n(|>) x f = f x\n\nmain = interact process\n\nprocess contents = let\n ls = contents |> lines |> map words |> map (map read) :: [[Int]]\n sz = ls |> head |> head\n doors = ls |> tail\n in solve doors sz |> show\n \nsolve doors sz = let\n left = doors |> map head\n right = doors |> map last\n leftOpen = left |> filter (== 1) |> length\n leftClosed = sz - leftOpen\n rightOpen = right |> filter (== 1) |> length\n rightClosed = sz - rightOpen\n in min leftOpen leftClosed + min rightOpen rightClosed\n "}, {"source_code": "import qualified Data.ByteString.Char8 as C\nimport Data.Maybe\nimport Control.Monad\nimport Control.Applicative\n\nf a b c d [] = (a,b,c,d)\nf a b c d ([0,1]:es) = f (a+1) b c (d+1) es\nf a b c d ([0,0]:es) = f (a+1) b (c+1) d es\nf a b c d ([1,0]:es) = f a (b+1) (c+1) d es\nf a b c d ([1,1]:es) = f a (b+1) c (d+1) es\n\nmain = do\n n <- readLn :: IO Int \n ns <- replicateM n ((map (fst . fromJust . C.readInt ) . C.words ) <$> C.getLine )\n let (a,b,c,d) = f 0 0 0 0 ns\n print $ (min a b) + (min c d)\n \n\n"}, {"source_code": "import Control.Monad\nmain = do\n n <- getLine\n doors <- forM [1..read n] (\\_ -> do\n s <- getLine\n let [l, r] = map read $ words s\n return (l, r))\n print $ solve doors\nsolve doors = count left + count right\n where left = map fst doors\n right = map snd doors\ncount parts = min (length parts - sum parts) (sum parts)\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n n <- readLn\n xs <- map readInt.B.words<$>B.getContents\n let f x y (l:r:rest) = f (x+l) (y+r) rest\n f x y [] = min x (n-x) + min y (n-y)\n print $ f 0 0 xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\n\n\nmain = do\n\ta<-read <$> getLine :: IO Int\n\t[c,d]<-transpose <$> map(map read) <$> map words <$> replicateM a getLine :: IO [[Int]]\n\tlet c1 = length $ filter (==1) c\n\tlet d1 = length $ filter (==1) d\n\tprint $ (min c1 (a-c1)) + (min d1 (a-d1))\n"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Control.Applicative\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n n <- readLn\n xs <- map readInt . B.words <$> B.getContents\n let f x y (l:r:rest) = f (x+l) (y+r) rest\n f x y [] = min x (n-x) + min y (n-y)\n print $ f 0 0 xs\n\n"}, {"source_code": "-- references\n-- http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output\n-- http://www.haskell.org/haskellwiki/Haskell_Tutorial_for_C_Programmers\n-- http://en.wikibooks.org/wiki/Haskell/Next_steps\n-- http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Parsing\n-- http://legacy.cs.uu.nl/daan/download/parsec/parsec.html#parse\n-- http://legacy.cs.uu.nl/daan/download/parsec/parsec.html#decimal\n-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html\n-- enots CF solution 2C\n\n\nans :: Int -> [(Int, Int)] -> Int\nans a b = minimum ((sum (fst (unzip b)) : [(a - (sum (fst (unzip b))))]))\n\t+ minimum ((sum (snd (unzip b)) : [(a - (sum (snd (unzip b))))]))\n\nprocess :: [String] -> [(Int, Int)]\nprocess [] \t = []\nprocess (a : (b : c)) = (read a, read b) : (process c)\nprocess _ = []\n\nmain :: IO()\nmain = do\n\tstr <- getContents\n\tputStrLn (show (ans (read ((words str) !! 0)) (process (tail (words str)))))\n\t"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.Map as M\n(|>) x f = f x\n\nmain = interact process\n\nprocess contents = let\n ls = contents |> lines |> map words |> map (map read) :: [[Int]]\n sz = ls |> head |> head\n doors = ls |> tail\n in solve doors sz |> show\n \nsolve doors sz = let\n left = doors |> map head\n right = doors |> map last\n leftOpen = left |> filter (== 1) |> length\n leftClosed = sz - leftOpen\n rightOpen = right |> filter (== 1) |> length\n rightClosed = sz - rightOpen\n x = leftClosed + rightOpen\n y = leftOpen + rightClosed\n in min x y"}], "src_uid": "2052b0b4abdcf7d613b56842b1267f60"} {"source_code": "import Control.Monad\nmain = do\n [a,b,c] <- liftM (map read . words) (getLine) :: IO [Double]\n putStrLn $ show $ (a*a*a/(6*sqrt(2))) + (b*b*(sqrt(0.5))*b/3) + s5 c\n\ns5 c = (1/4)*sqrt(5*(5+2*(sqrt 5))) * c*c * (1/3) * sqrt(c^2 - r^2)\n where r = (1/2)*c*1.7013016167\n", "positive_code": [{"source_code": "import Control.Monad (liftM)\n\nsolve :: Double -> Double -> Double\nsolve n l =\n let a = pi / n in\n let l' = l / 2 / sin a in\n let h = sqrt (l ** 2 - l' ** 2) in\n l' * l' * sin (2 * a) / 2 * h / 3 * n\n\nmain :: IO ()\nmain = do\n [l_3, l_4, l_5] <- (map read . words) `liftM` getContents :: IO [Double]\n print $ solve 3 l_3 + solve 4 l_4 + solve 5 l_5\n"}], "negative_code": [], "src_uid": "560bc97986a355d461bd462c4e1ea9db"} {"source_code": "import Data.List(sort,sortBy,intersect)\n\n-- | The 'isSorted' predicate returns 'True' if the elements of a list occur\n-- in non-descending order, equivalent to @'isSortedBy' ('<=')@.\nisSorted :: Ord a => [a] -> Bool\nisSorted = isSortedBy (<=)\n\n-- | The 'isSortedBy' function returns 'True' iff the predicate returns true\n-- for all adjacent pairs of elements in the list.\nisSortedBy :: (a -> a -> Bool) -> [a] -> Bool\nisSortedBy lte = loop\n where\n loop [] = True\n loop [_] = True\n loop (x:y:zs) = (x `lte` y) && loop (y:zs)\n\n-- | The 'member' function returns 'True' if the element appears in the\n-- ordered list.\nmember :: Ord a => a -> [a] -> Bool\nmember = memberBy compare\n\n-- | The 'memberBy' function is the non-overloaded version of 'member'.\nmemberBy :: (a -> a -> Ordering) -> a -> [a] -> Bool\nmemberBy cmp x = loop\n where\n loop [] = False\n loop (y:ys) = case cmp x y of\n LT -> False\n EQ -> True\n GT -> loop ys\n\n-- | The 'has' function returns 'True' if the element appears in the list;\n-- it is equivalent to 'member' except the order of the arguments is reversed,\n-- making it a function from an ordered list to its characteristic function.\nhas :: Ord a => [a] -> a -> Bool\nhas xs y = memberBy compare y xs\n\n-- | The 'hasBy' function is the non-overloaded version of 'has'.\nhasBy :: (a -> a -> Ordering) -> [a] -> a -> Bool\nhasBy cmp xs y = memberBy cmp y xs\n\n-- | The 'insertBag' function inserts an element into a list. If the element\n-- is already there, then another copy of the element is inserted.\ninsertBag :: Ord a => a -> [a] -> [a]\ninsertBag = insertBagBy compare\n\n-- | The 'insertBagBy' function is the non-overloaded version of 'insertBag'.\ninsertBagBy :: (a -> a -> Ordering) -> a -> [a] -> [a]\ninsertBagBy cmp = loop\n where\n loop x [] = [x]\n loop x (y:ys)\n = case cmp x y of\n GT -> y:loop x ys\n _ -> x:y:ys\n\n-- | The 'insertSet' function inserts an element into an ordered list.\n-- If the element is already there, then the element replaces the existing\n-- element.\ninsertSet :: Ord a => a -> [a] -> [a]\ninsertSet = insertSetBy compare\n\n-- | The 'insertSetBy' function is the non-overloaded version of 'insertSet'.\ninsertSetBy :: (a -> a -> Ordering) -> a -> [a] -> [a]\ninsertSetBy cmp = loop\n where\n loop x [] = [x]\n loop x (y:ys) = case cmp x y of\n LT -> x:y:ys\n EQ -> x:ys\n GT -> y:loop x ys\n\n{-\n-- This function is moderately interesting, as it encompasses all the\n-- \"Venn diagram\" functions on two sets. (though not merge; which isn't\n-- a set function)\n\n-- However, it doesn't seem that useful, considering that of the 8 possible\n-- functions, there are only 4 interesting variations: isect, union, minus,\n-- and xunion. Due to interactions with GHC's optimizer, coded separately,\n-- these have a smaller combined object code size than the object code size\n-- for genSectBy. (Or, turn off certain optimizations and lose speed.)\n\n-- Each individual object code can be recovered from genSectBy via GHC's\n-- inliner and constant propagation; but this doesn't save much in terms\n-- of source code size and reduces portability.\n\n-- Note that the Static Argument Transformation is necessary for this to work\n-- correctly; inlining genSectBy allows for cmp and p to be inlined as well,\n-- or at least eliminate some indirect jumps. All of the *By functions in\n-- this module follow this idiom for this reason.\n\ngenSectBy :: (a -> a -> Ordering)\n -> (Bool -> Bool -> Bool)\n -> [a] -> [a] -> [a]\ngenSectBy cmp p = loop\n where\n loop [] ys | p False True = ys\n | otherwise = []\n loop xs [] | p True False = xs\n | otherwise = []\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT | p True False -> x : loop xs (y:ys)\n | otherwise -> loop xs (y:ys)\n EQ | p True True -> x : loop xs ys\n | otherwise -> loop xs ys\n GT | p False True -> y : loop (x:xs) ys\n | otherwise -> loop (x:xs) ys\n\n-- Here's another variation that was suggested to me. It is more general\n-- than genSectBy, as it can implement a merge; but it cannot implement\n-- a left-biased merge\n\nfoldrMergeBy :: (a -> b -> Ordering)\n -> (a -> c -> c) -> (b -> c -> c) -> (a -> b -> c -> c) -> c\n -> [a] -> [b] -> c\nfoldrMergeBy cmp addA addB unify z = loop\n where\n loop xs [] = foldr addA z xs\n loop [] ys = foldr addB z ys\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x `addA` loop xs (y:ys)\n EQ -> unify x y (loop xs ys)\n GT -> y `addB` loop (x:xs) ys\n-}\n\n-- | The 'isect' function computes the intersection of two ordered lists.\n-- An element occurs in the output as many times as the minimum number of\n-- occurrences in either input. If either input is a set, then the output\n-- is a set.\n--\n-- > isect [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 3,4 ]\n-- > isect [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1, 2,2 ]\nisect :: Ord a => [a] -> [a] -> [a]\nisect = isectBy compare\n\n-- | The 'isectBy' function is the non-overloaded version of 'isect'.\nisectBy :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\nisectBy cmp = loop\n where\n loop [] _ys = []\n loop _xs [] = []\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> loop xs (y:ys)\n EQ -> x : loop xs ys\n GT -> loop (x:xs) ys\n\n-- | The 'union' function computes the union of two ordered lists.\n-- An element occurs in the output as many times as the maximum number\n-- of occurrences in either input. The output is a set if and only if\n-- both inputs are sets.\n--\n-- > union [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 3,4, 5,6 ]\n-- > union [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1,1, 2,2,2 ]\nunion :: Ord a => [a] -> [a] -> [a]\nunion = unionBy compare\n\n-- | The 'unionBy' function is the non-overloaded version of 'union'.\nunionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nunionBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> x : loop xs ys\n GT -> y : loop (x:xs) ys\n\n-- | The 'minus' function computes the difference of two ordered lists.\n-- An element occurs in the output as many times as it occurs in\n-- the first input, minus the number of occurrences in the second input.\n-- If the first input is a set, then the output is a set.\n--\n-- > minus [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2 ]\n-- > minus [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 2 ]\nminus :: Ord a => [a] -> [a] -> [a]\nminus = minusBy compare\n\n-- | The 'minusBy' function is the non-overloaded version of 'minus'.\nminusBy :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\nminusBy cmp = loop\n where\n loop [] _ys = []\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs ys\n GT -> loop (x:xs) ys\n\n-- | The 'minus'' function computes the difference of two ordered lists.\n-- The result consists of elements from the first list that do not appear\n-- in the second list. If the first input is a set, then the output is\n-- a set.\n--\n-- > minus' [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2 ]\n-- > minus' [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == []\n-- > minus' [ 1,1, 2,2 ] [ 2 ] == [ 1,1 ]\nminus' :: Ord a => [a] -> [a] -> [a]\nminus' = minusBy' compare\n\n-- | The 'minusBy'' function is the non-overloaded version of 'minus''.\nminusBy' :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\nminusBy' cmp = loop\n where\n loop [] _ys = []\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs (y:ys)\n GT -> loop (x:xs) ys\n\n-- | The 'xunion' function computes the exclusive union of two ordered lists.\n-- An element occurs in the output as many times as the absolute difference\n-- between the number of occurrences in the inputs. If both inputs\n-- are sets, then the output is a set.\n--\n-- > xunion [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 5,6 ]\n-- > xunion [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1, 2 ]\nxunion :: Ord a => [a] -> [a] -> [a]\nxunion = xunionBy compare\n\n-- | The 'xunionBy' function is the non-overloaded version of 'xunion'.\nxunionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nxunionBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs ys\n GT -> y : loop (x:xs) ys\n\n-- | The 'merge' function combines all elements of two ordered lists.\n-- An element occurs in the output as many times as the sum of the\n-- occurrences in both lists. The output is a set if and only if\n-- the inputs are disjoint sets.\n--\n-- > merge [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 3,3,4,4, 5,6 ]\n-- > merge [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1,1,1, 2,2,2,2,2 ]\nmerge :: Ord a => [a] -> [a] -> [a]\nmerge = mergeBy compare\n\n-- | The 'mergeBy' function is the non-overloaded version of 'merge'.\nmergeBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nmergeBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n GT -> y : loop (x:xs) ys\n _ -> x : loop xs (y:ys)\n\n-- | The 'subset' function returns true if the first list is a sub-list\n-- of the second.\nsubset :: Ord a => [a] -> [a] -> Bool\nsubset = subsetBy compare\n\n-- | The 'subsetBy' function is the non-overloaded version of 'subset'.\nsubsetBy :: (a -> a -> Ordering) -> [a] -> [a] -> Bool\nsubsetBy cmp = loop\n where\n loop [] _ys = True\n loop _xs [] = False\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> False\n EQ -> loop xs ys\n GT -> loop (x:xs) ys\n\n{-\n-- This is Ian Lynagh's mergesort implementation, which appeared as\n-- Data.List.sort, with the static argument transformation applied.\n-- It's not clear whether this modification is truly worthwhile or not.\n\nsort :: Ord a => [a] -> [a]\nsort = sortBy compare\n\nsortBy :: (a -> a -> Ordering) -> [a] -> [a]\nsortBy cmp = foldt (mergeBy cmp) [] . map (\\x -> [x])\n-}\n\n-- | The 'sortOn' function provides the decorate-sort-undecorate idiom,\n-- also known as the \\\"Schwartzian transform\\\".\nsortOn :: Ord b => (a -> b) -> [a] -> [a]\nsortOn f = map snd . sortOn' fst . map (\\x -> let y = f x in y `seq` (y, x))\n\n-- | This variant of 'sortOn' recomputes the sorting key every comparison.\n-- This can be better for functions that are cheap to compute.\n-- This is definitely better for projections, as the decorate-sort-undecorate\n-- saves nothing and adds two traversals of the list and extra memory\n-- allocation.\nsortOn' :: Ord b => (a -> b) -> [a] -> [a]\nsortOn' f = sortBy (\\x y -> compare (f x) (f y))\n\n-- | The 'nubSort' function is equivalent to @'nub' '.' 'sort'@, except\n-- that duplicates are removed as it sorts. It is essentially the same\n-- implementation as @Data.List.sort@, with 'merge' replaced by 'union'.\n-- Thus the performance of 'nubSort' should better than or nearly equal\n-- to 'sort' alone. It is faster than both 'sort' and @'nub' '.' 'sort'@\n-- when the input contains significant quantities of duplicated elements.\nnubSort :: Ord a => [a] -> [a]\nnubSort = nubSortBy compare\n\n-- | The 'nubSortBy' function is the non-overloaded version of 'nubSort'.\nnubSortBy :: (a -> a -> Ordering) -> [a] -> [a]\nnubSortBy cmp = foldt' (unionBy cmp) [] . runs\n where\n -- 'runs' partitions the input into sublists that are monotonic,\n -- contiguous, and non-overlapping. Descending runs are reversed\n -- and adjacent duplicates are eliminated, so every run returned is\n -- strictly ascending.\n\n runs (a:b:xs)\n = case cmp a b of\n LT -> asc b (a:) xs\n EQ -> runs (a:xs)\n GT -> desc b [a] xs\n runs xs = [xs]\n\n desc a as [] = [a:as]\n desc a as (b:bs)\n = case cmp a b of\n LT -> (a:as) : runs (b:bs)\n EQ -> desc a as bs\n GT -> desc b (a:as) bs\n\n asc a as [] = [as [a]]\n asc a as (b:bs)\n = case cmp a b of\n LT -> asc b (\\ys -> as (a:ys)) bs\n EQ -> asc a as bs\n GT -> as [a] : runs (b:bs)\n\n-- | The 'nubSortOn' function provides decorate-sort-undecorate for 'nubSort'.\nnubSortOn :: Ord b => (a -> b) -> [a] -> [a]\nnubSortOn f = map snd . nubSortOn' fst . map (\\x -> let y = f x in y `seq` (y, x))\n\n-- | This variant of 'nubSortOn' recomputes the sorting key for each comparison\nnubSortOn' :: Ord b => (a -> b) -> [a] -> [a]\nnubSortOn' f = nubSortBy (\\x y -> compare (f x) (f y))\n\n-- | On ordered lists, 'nub' is equivalent to 'Data.List.nub', except that\n-- it runs in linear time instead of quadratic. On unordered lists it also\n-- removes elements that are smaller than any preceding element.\n--\n-- > nub [1,1,1,2,2] == [1,2]\n-- > nub [2,0,1,3,3] == [2,3]\n-- > nub = nubBy (<)\nnub :: Ord a => [a] -> [a]\nnub = nubBy (<)\n\n-- | The 'nubBy' function is the greedy algorithm that returns a\n-- sublist of its input such that:\n--\n-- > isSortedBy pred (nubBy pred xs) == True\n--\n-- This is true for all lists, not just ordered lists, and all binary\n-- predicates, not just total orders. On infinite lists, this statement\n-- is true in a certain mathematical sense, but not a computational one.\nnubBy :: (a -> a -> Bool) -> [a] -> [a]\nnubBy p [] = []\nnubBy p (x:xs) = x : loop x xs\n where\n loop _ [] = []\n loop x (y:ys)\n | p x y = y : loop y ys\n | otherwise = loop x ys\n\n-- | The function @'foldt'' plus zero@ computes the sum of a list\n-- using a balanced tree of operations. 'foldt'' necessarily diverges\n-- on infinite lists, hence it is a stricter variant of 'foldt'.\n-- 'foldt'' is used in the implementation of 'sort' and 'nubSort'.\nfoldt' :: (a -> a -> a) -> a -> [a] -> a\nfoldt' plus zero xs\n = case xs of\n [] -> zero\n (_:_) -> loop xs\n where\n loop [x] = x\n loop xs = loop (pairs xs)\n\n pairs (x:y:zs) = plus x y : pairs zs\n pairs zs = zs\n\n-- | The function @'foldt' plus zero@ computes the sum of a list using\n-- a sequence of balanced trees of operations. Given an appropriate @plus@\n-- operator, this function can be productive on an infinite list, hence it\n-- is lazier than 'foldt''. 'foldt' is used in the implementation of\n-- 'mergeAll' and 'unionAll'.\nfoldt :: (a -> a -> a) -> a -> [a] -> a\nfoldt plus zero = loop\n where\n loop [] = zero\n loop (x:xs) = x `plus` loop (pairs xs)\n\n pairs (x:y:zs) = plus x y : pairs zs\n pairs zs = zs\n\n-- helper functions used in 'mergeAll' and 'unionAll'\n\ndata People a = VIP a (People a) | Crowd [a]\n\nserve (VIP x xs) = x:serve xs\nserve (Crowd xs) = xs\n\nvips xss = [ VIP x (Crowd xs) | (x:xs) <- xss ]\n\n-- | The 'mergeAll' function merges a (potentially) infinite number of\n-- ordered lists, under the assumption that the heads of the inner lists\n-- are sorted. An element is duplicated in the result as many times as\n-- the total number of occurrences in all inner lists.\n--\n-- The 'mergeAll' function is closely related to @'foldr' 'merge' []@.\n-- The former does not assume that the outer list is finite, whereas\n-- the latter does not assume that the heads of the inner lists are sorted.\n-- When both sets of assumptions are met, these two functions are\n-- equivalent.\n--\n-- This implementation of 'mergeAll' uses a tree of comparisons, and is\n-- based on input from Dave Bayer, Heinrich Apfelmus, Omar Antolin Camarena,\n-- and Will Ness. See @CHANGES@ for details.\nmergeAll :: Ord a => [[a]] -> [a]\nmergeAll = mergeAllBy compare\n\n-- | The 'mergeAllBy' function is the non-overloaded variant of the 'mergeAll'\n-- function.\nmergeAllBy :: (a -> a -> Ordering) -> [[a]] -> [a]\nmergeAllBy cmp = serve . foldt merge' (Crowd []) . vips\n where\n merge' (VIP x xs) ys = VIP x (merge' xs ys)\n merge' (Crowd []) ys = ys\n merge' (Crowd xs) (Crowd ys) = Crowd (mergeBy cmp xs ys)\n merge' xs@(Crowd (x:xt)) ys@(VIP y yt)\n = case cmp x y of\n GT -> VIP y (merge' xs yt)\n _ -> VIP x (merge' (Crowd xt) ys)\n\n-- | The 'unionAll' computes the union of a (potentially) infinite number\n-- of lists, under the assumption that the heads of the inner lists\n-- are sorted. The result will duplicate an element as many times as\n-- the maximum number of occurrences in any single list. Thus, the result\n-- is a set if and only if every inner list is a set.\n--\n-- The 'unionAll' function is closely related to @'foldr' 'union' []@.\n-- The former does not assume that the outer list is finite, whereas\n-- the latter does not assume that the heads of the inner lists are sorted.\n-- When both sets of assumptions are met, these two functions are\n-- equivalent.\n--\n-- Note that there is no simple way to express 'unionAll' in terms of\n-- 'mergeAll' or vice versa on arbitrary valid inputs. They are related\n-- via 'nub' however, as @'nub' . 'mergeAll' == 'unionAll' . 'map' 'nub'@.\n-- If every list is a set, then @map nub == id@, and in this special case\n-- (and only in this special case) does @nub . mergeAll == unionAll@.\n--\n-- This implementation of 'unionAll' uses a tree of comparisons, and is\n-- based on input from Dave Bayer, Heinrich Apfelmus, Omar Antolin Camarena,\n-- and Will Ness. See @CHANGES@ for details.\nunionAll :: Ord a => [[a]] -> [a]\nunionAll = unionAllBy compare\n\n-- | The 'unionAllBy' function is the non-overloaded variant of the 'unionAll'\n-- function.\nunionAllBy :: (a -> a -> Ordering) -> [[a]] -> [a]\nunionAllBy cmp = serve . foldt union' (Crowd []) . vips\n where\n msg = \"Data.List.Ordered.unionAllBy: the heads of the lists are not sorted\"\n\n union' (VIP x xs) ys\n = VIP x $ case ys of\n Crowd _ -> union' xs ys\n VIP y yt -> case cmp x y of\n LT -> union' xs ys\n EQ -> union' xs yt\n GT -> error msg\n union' (Crowd []) ys = ys\n union' (Crowd xs) (Crowd ys) = Crowd (unionBy cmp xs ys)\n union' xs@(Crowd (x:xt)) ys@(VIP y yt)\n = case cmp x y of\n LT -> VIP x (union' (Crowd xt) ys)\n EQ -> VIP x (union' (Crowd xt) yt)\n GT -> VIP y (union' xs yt)\n \nmain :: IO ()\nmain = do \n c <- getContents\n let l = (map (read :: String -> Int) . words) c\n let (n : m : k : ll) = l \n let a = [(0, 1, y, 0) | y <- [1..n]] ++ [(0, 2, y, 0) | y <- [1..m]] ++ mt ll 1 \n let b = reverse a \n let b1 = filter (\\(i, x, y, z) -> case x of {1 -> True; _ -> False}) b \n let b2 = filter (\\(i, x, y, z) -> case x of {2 -> True; _ -> False}) b\n let c1 = nubSortBy fc b1\n let c2 = nubSortBy fc b2 \n let c = [[q | (i2,x2,y2,z2) <- c2, let i = y1, let j = y2, let q = case compare i1 i2 of {GT -> z1; EQ -> z1; LT -> z2}] | (i1,x1,y1,z1) <- c1]\n putStrLn $ unlines . map (unwords . (map show)) $ c\n\nfc :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> Ordering\nfc (i1,x1,y1,z1) (i2,x2,y2,z2) = compare y1 y2\n\nmt :: [Int] -> Int -> [(Int, Int, Int, Int)]\nmt [] _ = []\nmt (a : b : c : ll) n = (n,a,b,c) : mt ll (n+1)", "positive_code": [{"source_code": "import Data.List(sort,sortBy,intersect)\n\n-- | The 'isSorted' predicate returns 'True' if the elements of a list occur\n-- in non-descending order, equivalent to @'isSortedBy' ('<=')@.\nisSorted :: Ord a => [a] -> Bool\nisSorted = isSortedBy (<=)\n\n-- | The 'isSortedBy' function returns 'True' iff the predicate returns true\n-- for all adjacent pairs of elements in the list.\nisSortedBy :: (a -> a -> Bool) -> [a] -> Bool\nisSortedBy lte = loop\n where\n loop [] = True\n loop [_] = True\n loop (x:y:zs) = (x `lte` y) && loop (y:zs)\n\n-- | The 'member' function returns 'True' if the element appears in the\n-- ordered list.\nmember :: Ord a => a -> [a] -> Bool\nmember = memberBy compare\n\n-- | The 'memberBy' function is the non-overloaded version of 'member'.\nmemberBy :: (a -> a -> Ordering) -> a -> [a] -> Bool\nmemberBy cmp x = loop\n where\n loop [] = False\n loop (y:ys) = case cmp x y of\n LT -> False\n EQ -> True\n GT -> loop ys\n\n-- | The 'has' function returns 'True' if the element appears in the list;\n-- it is equivalent to 'member' except the order of the arguments is reversed,\n-- making it a function from an ordered list to its characteristic function.\nhas :: Ord a => [a] -> a -> Bool\nhas xs y = memberBy compare y xs\n\n-- | The 'hasBy' function is the non-overloaded version of 'has'.\nhasBy :: (a -> a -> Ordering) -> [a] -> a -> Bool\nhasBy cmp xs y = memberBy cmp y xs\n\n-- | The 'insertBag' function inserts an element into a list. If the element\n-- is already there, then another copy of the element is inserted.\ninsertBag :: Ord a => a -> [a] -> [a]\ninsertBag = insertBagBy compare\n\n-- | The 'insertBagBy' function is the non-overloaded version of 'insertBag'.\ninsertBagBy :: (a -> a -> Ordering) -> a -> [a] -> [a]\ninsertBagBy cmp = loop\n where\n loop x [] = [x]\n loop x (y:ys)\n = case cmp x y of\n GT -> y:loop x ys\n _ -> x:y:ys\n\n-- | The 'insertSet' function inserts an element into an ordered list.\n-- If the element is already there, then the element replaces the existing\n-- element.\ninsertSet :: Ord a => a -> [a] -> [a]\ninsertSet = insertSetBy compare\n\n-- | The 'insertSetBy' function is the non-overloaded version of 'insertSet'.\ninsertSetBy :: (a -> a -> Ordering) -> a -> [a] -> [a]\ninsertSetBy cmp = loop\n where\n loop x [] = [x]\n loop x (y:ys) = case cmp x y of\n LT -> x:y:ys\n EQ -> x:ys\n GT -> y:loop x ys\n\n{-\n-- This function is moderately interesting, as it encompasses all the\n-- \"Venn diagram\" functions on two sets. (though not merge; which isn't\n-- a set function)\n\n-- However, it doesn't seem that useful, considering that of the 8 possible\n-- functions, there are only 4 interesting variations: isect, union, minus,\n-- and xunion. Due to interactions with GHC's optimizer, coded separately,\n-- these have a smaller combined object code size than the object code size\n-- for genSectBy. (Or, turn off certain optimizations and lose speed.)\n\n-- Each individual object code can be recovered from genSectBy via GHC's\n-- inliner and constant propagation; but this doesn't save much in terms\n-- of source code size and reduces portability.\n\n-- Note that the Static Argument Transformation is necessary for this to work\n-- correctly; inlining genSectBy allows for cmp and p to be inlined as well,\n-- or at least eliminate some indirect jumps. All of the *By functions in\n-- this module follow this idiom for this reason.\n\ngenSectBy :: (a -> a -> Ordering)\n -> (Bool -> Bool -> Bool)\n -> [a] -> [a] -> [a]\ngenSectBy cmp p = loop\n where\n loop [] ys | p False True = ys\n | otherwise = []\n loop xs [] | p True False = xs\n | otherwise = []\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT | p True False -> x : loop xs (y:ys)\n | otherwise -> loop xs (y:ys)\n EQ | p True True -> x : loop xs ys\n | otherwise -> loop xs ys\n GT | p False True -> y : loop (x:xs) ys\n | otherwise -> loop (x:xs) ys\n\n-- Here's another variation that was suggested to me. It is more general\n-- than genSectBy, as it can implement a merge; but it cannot implement\n-- a left-biased merge\n\nfoldrMergeBy :: (a -> b -> Ordering)\n -> (a -> c -> c) -> (b -> c -> c) -> (a -> b -> c -> c) -> c\n -> [a] -> [b] -> c\nfoldrMergeBy cmp addA addB unify z = loop\n where\n loop xs [] = foldr addA z xs\n loop [] ys = foldr addB z ys\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x `addA` loop xs (y:ys)\n EQ -> unify x y (loop xs ys)\n GT -> y `addB` loop (x:xs) ys\n-}\n\n-- | The 'isect' function computes the intersection of two ordered lists.\n-- An element occurs in the output as many times as the minimum number of\n-- occurrences in either input. If either input is a set, then the output\n-- is a set.\n--\n-- > isect [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 3,4 ]\n-- > isect [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1, 2,2 ]\nisect :: Ord a => [a] -> [a] -> [a]\nisect = isectBy compare\n\n-- | The 'isectBy' function is the non-overloaded version of 'isect'.\nisectBy :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\nisectBy cmp = loop\n where\n loop [] _ys = []\n loop _xs [] = []\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> loop xs (y:ys)\n EQ -> x : loop xs ys\n GT -> loop (x:xs) ys\n\n-- | The 'union' function computes the union of two ordered lists.\n-- An element occurs in the output as many times as the maximum number\n-- of occurrences in either input. The output is a set if and only if\n-- both inputs are sets.\n--\n-- > union [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 3,4, 5,6 ]\n-- > union [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1,1, 2,2,2 ]\nunion :: Ord a => [a] -> [a] -> [a]\nunion = unionBy compare\n\n-- | The 'unionBy' function is the non-overloaded version of 'union'.\nunionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nunionBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> x : loop xs ys\n GT -> y : loop (x:xs) ys\n\n-- | The 'minus' function computes the difference of two ordered lists.\n-- An element occurs in the output as many times as it occurs in\n-- the first input, minus the number of occurrences in the second input.\n-- If the first input is a set, then the output is a set.\n--\n-- > minus [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2 ]\n-- > minus [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 2 ]\nminus :: Ord a => [a] -> [a] -> [a]\nminus = minusBy compare\n\n-- | The 'minusBy' function is the non-overloaded version of 'minus'.\nminusBy :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\nminusBy cmp = loop\n where\n loop [] _ys = []\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs ys\n GT -> loop (x:xs) ys\n\n-- | The 'minus'' function computes the difference of two ordered lists.\n-- The result consists of elements from the first list that do not appear\n-- in the second list. If the first input is a set, then the output is\n-- a set.\n--\n-- > minus' [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2 ]\n-- > minus' [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == []\n-- > minus' [ 1,1, 2,2 ] [ 2 ] == [ 1,1 ]\nminus' :: Ord a => [a] -> [a] -> [a]\nminus' = minusBy' compare\n\n-- | The 'minusBy'' function is the non-overloaded version of 'minus''.\nminusBy' :: (a -> b -> Ordering) -> [a] -> [b] -> [a]\nminusBy' cmp = loop\n where\n loop [] _ys = []\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs (y:ys)\n GT -> loop (x:xs) ys\n\n-- | The 'xunion' function computes the exclusive union of two ordered lists.\n-- An element occurs in the output as many times as the absolute difference\n-- between the number of occurrences in the inputs. If both inputs\n-- are sets, then the output is a set.\n--\n-- > xunion [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 5,6 ]\n-- > xunion [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1, 2 ]\nxunion :: Ord a => [a] -> [a] -> [a]\nxunion = xunionBy compare\n\n-- | The 'xunionBy' function is the non-overloaded version of 'xunion'.\nxunionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nxunionBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> loop xs ys\n GT -> y : loop (x:xs) ys\n\n-- | The 'merge' function combines all elements of two ordered lists.\n-- An element occurs in the output as many times as the sum of the\n-- occurrences in both lists. The output is a set if and only if\n-- the inputs are disjoint sets.\n--\n-- > merge [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 3,3,4,4, 5,6 ]\n-- > merge [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1,1,1, 2,2,2,2,2 ]\nmerge :: Ord a => [a] -> [a] -> [a]\nmerge = mergeBy compare\n\n-- | The 'mergeBy' function is the non-overloaded version of 'merge'.\nmergeBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nmergeBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n GT -> y : loop (x:xs) ys\n _ -> x : loop xs (y:ys)\n\n-- | The 'subset' function returns true if the first list is a sub-list\n-- of the second.\nsubset :: Ord a => [a] -> [a] -> Bool\nsubset = subsetBy compare\n\n-- | The 'subsetBy' function is the non-overloaded version of 'subset'.\nsubsetBy :: (a -> a -> Ordering) -> [a] -> [a] -> Bool\nsubsetBy cmp = loop\n where\n loop [] _ys = True\n loop _xs [] = False\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> False\n EQ -> loop xs ys\n GT -> loop (x:xs) ys\n\n{-\n-- This is Ian Lynagh's mergesort implementation, which appeared as\n-- Data.List.sort, with the static argument transformation applied.\n-- It's not clear whether this modification is truly worthwhile or not.\n\nsort :: Ord a => [a] -> [a]\nsort = sortBy compare\n\nsortBy :: (a -> a -> Ordering) -> [a] -> [a]\nsortBy cmp = foldt (mergeBy cmp) [] . map (\\x -> [x])\n-}\n\n-- | The 'sortOn' function provides the decorate-sort-undecorate idiom,\n-- also known as the \\\"Schwartzian transform\\\".\nsortOn :: Ord b => (a -> b) -> [a] -> [a]\nsortOn f = map snd . sortOn' fst . map (\\x -> let y = f x in y `seq` (y, x))\n\n-- | This variant of 'sortOn' recomputes the sorting key every comparison.\n-- This can be better for functions that are cheap to compute.\n-- This is definitely better for projections, as the decorate-sort-undecorate\n-- saves nothing and adds two traversals of the list and extra memory\n-- allocation.\nsortOn' :: Ord b => (a -> b) -> [a] -> [a]\nsortOn' f = sortBy (\\x y -> compare (f x) (f y))\n\n-- | The 'nubSort' function is equivalent to @'nub' '.' 'sort'@, except\n-- that duplicates are removed as it sorts. It is essentially the same\n-- implementation as @Data.List.sort@, with 'merge' replaced by 'union'.\n-- Thus the performance of 'nubSort' should better than or nearly equal\n-- to 'sort' alone. It is faster than both 'sort' and @'nub' '.' 'sort'@\n-- when the input contains significant quantities of duplicated elements.\nnubSort :: Ord a => [a] -> [a]\nnubSort = nubSortBy compare\n\n-- | The 'nubSortBy' function is the non-overloaded version of 'nubSort'.\nnubSortBy :: (a -> a -> Ordering) -> [a] -> [a]\nnubSortBy cmp = foldt' (unionBy cmp) [] . runs\n where\n -- 'runs' partitions the input into sublists that are monotonic,\n -- contiguous, and non-overlapping. Descending runs are reversed\n -- and adjacent duplicates are eliminated, so every run returned is\n -- strictly ascending.\n\n runs (a:b:xs)\n = case cmp a b of\n LT -> asc b (a:) xs\n EQ -> runs (a:xs)\n GT -> desc b [a] xs\n runs xs = [xs]\n\n desc a as [] = [a:as]\n desc a as (b:bs)\n = case cmp a b of\n LT -> (a:as) : runs (b:bs)\n EQ -> desc a as bs\n GT -> desc b (a:as) bs\n\n asc a as [] = [as [a]]\n asc a as (b:bs)\n = case cmp a b of\n LT -> asc b (\\ys -> as (a:ys)) bs\n EQ -> asc a as bs\n GT -> as [a] : runs (b:bs)\n\n-- | The 'nubSortOn' function provides decorate-sort-undecorate for 'nubSort'.\nnubSortOn :: Ord b => (a -> b) -> [a] -> [a]\nnubSortOn f = map snd . nubSortOn' fst . map (\\x -> let y = f x in y `seq` (y, x))\n\n-- | This variant of 'nubSortOn' recomputes the sorting key for each comparison\nnubSortOn' :: Ord b => (a -> b) -> [a] -> [a]\nnubSortOn' f = nubSortBy (\\x y -> compare (f x) (f y))\n\n-- | On ordered lists, 'nub' is equivalent to 'Data.List.nub', except that\n-- it runs in linear time instead of quadratic. On unordered lists it also\n-- removes elements that are smaller than any preceding element.\n--\n-- > nub [1,1,1,2,2] == [1,2]\n-- > nub [2,0,1,3,3] == [2,3]\n-- > nub = nubBy (<)\nnub :: Ord a => [a] -> [a]\nnub = nubBy (<)\n\n-- | The 'nubBy' function is the greedy algorithm that returns a\n-- sublist of its input such that:\n--\n-- > isSortedBy pred (nubBy pred xs) == True\n--\n-- This is true for all lists, not just ordered lists, and all binary\n-- predicates, not just total orders. On infinite lists, this statement\n-- is true in a certain mathematical sense, but not a computational one.\nnubBy :: (a -> a -> Bool) -> [a] -> [a]\nnubBy p [] = []\nnubBy p (x:xs) = x : loop x xs\n where\n loop _ [] = []\n loop x (y:ys)\n | p x y = y : loop y ys\n | otherwise = loop x ys\n\n-- | The function @'foldt'' plus zero@ computes the sum of a list\n-- using a balanced tree of operations. 'foldt'' necessarily diverges\n-- on infinite lists, hence it is a stricter variant of 'foldt'.\n-- 'foldt'' is used in the implementation of 'sort' and 'nubSort'.\nfoldt' :: (a -> a -> a) -> a -> [a] -> a\nfoldt' plus zero xs\n = case xs of\n [] -> zero\n (_:_) -> loop xs\n where\n loop [x] = x\n loop xs = loop (pairs xs)\n\n pairs (x:y:zs) = plus x y : pairs zs\n pairs zs = zs\n\n-- | The function @'foldt' plus zero@ computes the sum of a list using\n-- a sequence of balanced trees of operations. Given an appropriate @plus@\n-- operator, this function can be productive on an infinite list, hence it\n-- is lazier than 'foldt''. 'foldt' is used in the implementation of\n-- 'mergeAll' and 'unionAll'.\nfoldt :: (a -> a -> a) -> a -> [a] -> a\nfoldt plus zero = loop\n where\n loop [] = zero\n loop (x:xs) = x `plus` loop (pairs xs)\n\n pairs (x:y:zs) = plus x y : pairs zs\n pairs zs = zs\n\n-- helper functions used in 'mergeAll' and 'unionAll'\n\ndata People a = VIP a (People a) | Crowd [a]\n\nserve (VIP x xs) = x:serve xs\nserve (Crowd xs) = xs\n\nvips xss = [ VIP x (Crowd xs) | (x:xs) <- xss ]\n\n-- | The 'mergeAll' function merges a (potentially) infinite number of\n-- ordered lists, under the assumption that the heads of the inner lists\n-- are sorted. An element is duplicated in the result as many times as\n-- the total number of occurrences in all inner lists.\n--\n-- The 'mergeAll' function is closely related to @'foldr' 'merge' []@.\n-- The former does not assume that the outer list is finite, whereas\n-- the latter does not assume that the heads of the inner lists are sorted.\n-- When both sets of assumptions are met, these two functions are\n-- equivalent.\n--\n-- This implementation of 'mergeAll' uses a tree of comparisons, and is\n-- based on input from Dave Bayer, Heinrich Apfelmus, Omar Antolin Camarena,\n-- and Will Ness. See @CHANGES@ for details.\nmergeAll :: Ord a => [[a]] -> [a]\nmergeAll = mergeAllBy compare\n\n-- | The 'mergeAllBy' function is the non-overloaded variant of the 'mergeAll'\n-- function.\nmergeAllBy :: (a -> a -> Ordering) -> [[a]] -> [a]\nmergeAllBy cmp = serve . foldt merge' (Crowd []) . vips\n where\n merge' (VIP x xs) ys = VIP x (merge' xs ys)\n merge' (Crowd []) ys = ys\n merge' (Crowd xs) (Crowd ys) = Crowd (mergeBy cmp xs ys)\n merge' xs@(Crowd (x:xt)) ys@(VIP y yt)\n = case cmp x y of\n GT -> VIP y (merge' xs yt)\n _ -> VIP x (merge' (Crowd xt) ys)\n\n-- | The 'unionAll' computes the union of a (potentially) infinite number\n-- of lists, under the assumption that the heads of the inner lists\n-- are sorted. The result will duplicate an element as many times as\n-- the maximum number of occurrences in any single list. Thus, the result\n-- is a set if and only if every inner list is a set.\n--\n-- The 'unionAll' function is closely related to @'foldr' 'union' []@.\n-- The former does not assume that the outer list is finite, whereas\n-- the latter does not assume that the heads of the inner lists are sorted.\n-- When both sets of assumptions are met, these two functions are\n-- equivalent.\n--\n-- Note that there is no simple way to express 'unionAll' in terms of\n-- 'mergeAll' or vice versa on arbitrary valid inputs. They are related\n-- via 'nub' however, as @'nub' . 'mergeAll' == 'unionAll' . 'map' 'nub'@.\n-- If every list is a set, then @map nub == id@, and in this special case\n-- (and only in this special case) does @nub . mergeAll == unionAll@.\n--\n-- This implementation of 'unionAll' uses a tree of comparisons, and is\n-- based on input from Dave Bayer, Heinrich Apfelmus, Omar Antolin Camarena,\n-- and Will Ness. See @CHANGES@ for details.\nunionAll :: Ord a => [[a]] -> [a]\nunionAll = unionAllBy compare\n\n-- | The 'unionAllBy' function is the non-overloaded variant of the 'unionAll'\n-- function.\nunionAllBy :: (a -> a -> Ordering) -> [[a]] -> [a]\nunionAllBy cmp = serve . foldt union' (Crowd []) . vips\n where\n msg = \"Data.List.Ordered.unionAllBy: the heads of the lists are not sorted\"\n\n union' (VIP x xs) ys\n = VIP x $ case ys of\n Crowd _ -> union' xs ys\n VIP y yt -> case cmp x y of\n LT -> union' xs ys\n EQ -> union' xs yt\n GT -> error msg\n union' (Crowd []) ys = ys\n union' (Crowd xs) (Crowd ys) = Crowd (unionBy cmp xs ys)\n union' xs@(Crowd (x:xt)) ys@(VIP y yt)\n = case cmp x y of\n LT -> VIP x (union' (Crowd xt) ys)\n EQ -> VIP x (union' (Crowd xt) yt)\n GT -> VIP y (union' xs yt)\n \nmain :: IO ()\nmain = do \n c <- getContents\n let l = (map (read :: String -> Int) . words) c\n let (n : m : k : ll) = l \n let a = [(0, 1, y, 0) | y <- [1..n]] ++ [(0, 2, y, 0) | y <- [1..m]] ++ mt ll 1 \n let b = reverse a \n let b1 = filter (\\(i, x, y, z) -> case x of {1 -> True; _ -> False}) b \n let b2 = filter (\\(i, x, y, z) -> case x of {2 -> True; _ -> False}) b\n let c1 = nubSortBy fc b1\n let c2 = nubSortBy fc b2 \n-- putStrLn $ show $ sum (map (\\(i, x, y, z) -> z) c1 :: [Int]) \n-- putStrLn $ show $ sum (map (\\(i, x, y, z) -> z) c2 :: [Int]) \n let c = [[q | (i2,x2,y2,z2) <- c2, let i = y1, let j = y2, let q = case compare i1 i2 of {GT -> z1; EQ -> z1; LT -> z2}] | (i1,x1,y1,z1) <- c1]\n putStrLn $ unlines . map (unwords . (map show)) $ c\n\nfc :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> Ordering\nfc (i1,x1,y1,z1) (i2,x2,y2,z2) = compare y1 y2\n\nmt :: [Int] -> Int -> [(Int, Int, Int, Int)]\nmt [] _ = []\nmt (a : b : c : ll) n = (n,a,b,c) : mt ll (n+1)"}, {"source_code": "import Data.List(sort,sortBy,intersect)\n\n--import Data.List.Ordered\n\n-- | The 'union' function computes the union of two ordered lists.\n-- An element occurs in the output as many times as the maximum number\n-- of occurrences in either input. The output is a set if and only if\n-- both inputs are sets.\n--\n-- > union [ 1,2, 3,4 ] [ 3,4, 5,6 ] == [ 1,2, 3,4, 5,6 ]\n-- > union [ 1, 2,2,2 ] [ 1,1,1, 2,2 ] == [ 1,1,1, 2,2,2 ]\nunion :: Ord a => [a] -> [a] -> [a]\nunion = unionBy compare\n\n-- | The 'unionBy' function is the non-overloaded version of 'union'.\nunionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]\nunionBy cmp = loop\n where\n loop [] ys = ys\n loop xs [] = xs\n loop (x:xs) (y:ys)\n = case cmp x y of\n LT -> x : loop xs (y:ys)\n EQ -> x : loop xs ys\n GT -> y : loop (x:xs) ys\n\n\n-- | The 'nubSort' function is equivalent to @'nub' '.' 'sort'@, except\n-- that duplicates are removed as it sorts. It is essentially the same\n-- implementation as @Data.List.sort@, with 'merge' replaced by 'union'.\n-- Thus the performance of 'nubSort' should better than or nearly equal\n-- to 'sort' alone. It is faster than both 'sort' and @'nub' '.' 'sort'@\n-- when the input contains significant quantities of duplicated elements.\nnubSort :: Ord a => [a] -> [a]\nnubSort = nubSortBy compare\n\n-- | The 'nubSortBy' function is the non-overloaded version of 'nubSort'.\nnubSortBy :: (a -> a -> Ordering) -> [a] -> [a]\nnubSortBy cmp = foldt' (unionBy cmp) [] . runs\n where\n -- 'runs' partitions the input into sublists that are monotonic,\n -- contiguous, and non-overlapping. Descending runs are reversed\n -- and adjacent duplicates are eliminated, so every run returned is\n -- strictly ascending.\n\n runs (a:b:xs)\n = case cmp a b of\n LT -> asc b (a:) xs\n EQ -> runs (a:xs)\n GT -> desc b [a] xs\n runs xs = [xs]\n\n desc a as [] = [a:as]\n desc a as (b:bs)\n = case cmp a b of\n LT -> (a:as) : runs (b:bs)\n EQ -> desc a as bs\n GT -> desc b (a:as) bs\n\n asc a as [] = [as [a]]\n asc a as (b:bs)\n = case cmp a b of\n LT -> asc b (\\ys -> as (a:ys)) bs\n EQ -> asc a as bs\n GT -> as [a] : runs (b:bs)\n\n-- | The function @'foldt'' plus zero@ computes the sum of a list\n-- using a balanced tree of operations. 'foldt'' necessarily diverges\n-- on infinite lists, hence it is a stricter variant of 'foldt'.\n-- 'foldt'' is used in the implementation of 'sort' and 'nubSort'.\nfoldt' :: (a -> a -> a) -> a -> [a] -> a\nfoldt' plus zero xs\n = case xs of\n [] -> zero\n (_:_) -> loop xs\n where\n loop [x] = x\n loop xs = loop (pairs xs)\n\n pairs (x:y:zs) = plus x y : pairs zs\n pairs zs = zs\n \nmain :: IO ()\nmain = do \n c <- getContents\n let l = (map (read :: String -> Int) . words) c\n let (n : m : k : ll) = l \n let a = [(0, 1, y, 0) | y <- [1..n]] ++ [(0, 2, y, 0) | y <- [1..m]] ++ mt ll 1 \n let b = reverse a \n let b1 = filter (\\(i, x, y, z) -> case x of {1 -> True; _ -> False}) b \n let b2 = filter (\\(i, x, y, z) -> case x of {2 -> True; _ -> False}) b\n let c1 = nubSortBy fc b1\n let c2 = nubSortBy fc b2 \n let c = [[q | (i2,x2,y2,z2) <- c2, let i = y1, let j = y2, let q = case compare i1 i2 of {GT -> z1; EQ -> z1; LT -> z2}] | (i1,x1,y1,z1) <- c1]\n putStrLn $ unlines . map (unwords . (map show)) $ c\n\nmt :: [Int] -> Int -> [(Int, Int, Int, Int)]\nmt [] _ = []\nmt (a : b : c : ll) n = (n,a,b,c) : mt ll (n+1) \n \nfc :: (Int,Int,Int,Int) -> (Int,Int,Int,Int) -> Ordering\nfc (i1,x1,y1,z1) (i2,x2,y2,z2) = compare y1 y2"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, k] <- getInts\n\n as <- newArray (1, n) 0 :: IO (IOUArray Int Int)\n bs <- newArray (1, m) 0 :: IO (IOUArray Int Int)\n cs <- newArray (1, k) 0 :: IO (IOUArray Int Int)\n\n forM_ [1..k] $ \\i -> do\n [t, j, c] <- getInts\n if t == 1\n then writeArray as j i\n else writeArray bs j i\n writeArray cs i c\n\n as' <- freeze as :: IO (UArray Int Int)\n bs' <- freeze bs :: IO (UArray Int Int)\n cs' <- freeze cs :: IO (UArray Int Int)\n\n forM_ [1..n] $ \\i -> do\n let\n f j = if k == 0 then 0 else cs'!k where k = max (as'!i) (bs'!j)\n\n l = mconcat $ map (\\j -> (BB.intDec $ f j) <> BB.char8 ' ') [1..m]\n\n BB.hPutBuilder stdout $ l <> BB.char8 '\\n'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, k] <- getInts\n\n as <- newArray (1, n) 0 :: IO (IOUArray Int Int)\n bs <- newArray (1, m) 0 :: IO (IOUArray Int Int)\n cs <- newArray (1, k) 0 :: IO (IOUArray Int Int)\n\n forM_ [1..k] $ \\i -> do\n [t, j, c] <- getInts\n if t == 1\n then writeArray as j i\n else writeArray bs j i\n writeArray cs i c\n\n as' <- freeze as :: IO (UArray Int Int)\n bs' <- freeze bs :: IO (UArray Int Int)\n cs' <- freeze cs :: IO (UArray Int Int)\n\n let\n r = [map (f i) [1..m] | i <- [1..n]]\n where\n f i j = if k == 0 then 0 else cs'!k where k = max (as'!i) (bs'!j)\n\n putStr $ unlines $ map (unwords . map show) r\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, k] <- getInts\n\n as <- newArray (1, n) 0 :: IO (IOUArray Int Int)\n bs <- newArray (1, m) 0 :: IO (IOUArray Int Int)\n cs <- newArray (1, k) 0 :: IO (IOUArray Int Int)\n\n forM_ [1..k] $ \\i -> do\n [t, j, c] <- getInts\n if t == 1\n then writeArray as j i\n else writeArray bs j i\n writeArray cs i c\n\n as' <- freeze as :: IO (UArray Int Int)\n bs' <- freeze bs :: IO (UArray Int Int)\n cs' <- freeze cs :: IO (UArray Int Int)\n\n forM_ [1..n] $ \\i -> do\n let\n f j = if k == 0 then 0 else cs'!k where k = max (as'!i) (bs'!j)\n\n putStrLn $ unlines $ map show $ map f [1..m]\n\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\n-- import Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\nimport qualified Data.ByteString.Lazy.Builder as BB\n\nimport Data.Monoid\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n [n, m, k] <- getInts\n\n as <- newArray (1, n) 0 :: IO (IOUArray Int Int)\n bs <- newArray (1, m) 0 :: IO (IOUArray Int Int)\n cs <- newArray (1, k) 0 :: IO (IOUArray Int Int)\n\n forM_ [1..k] $ \\i -> do\n [t, j, c] <- getInts\n if t == 1\n then writeArray as j i\n else writeArray bs j i\n writeArray cs i c\n\n as' <- freeze as :: IO (UArray Int Int)\n bs' <- freeze bs :: IO (UArray Int Int)\n cs' <- freeze cs :: IO (UArray Int Int)\n\n forM_ [1..n] $ \\i -> do\n let\n r = [map (f i) [1..m] | i <- [1..n]]\n where\n f i j = if k == 0 then 0 else cs'!k where k = max (as'!i) (bs'!j)\n\n putStr $ unlines $ map (unwords . map show) r\n"}], "src_uid": "296560688b83b9b6de740568b8deffd1"} {"source_code": "main = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:xs) = (read x, xs)\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - fromEnum '0')\n\nsolve n = n:[1..n-1]\n\nformat = unwords . map show\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nmain = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:xs) = (readInt x, xs)\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n\nsolve n = n:[1..n-1]\n\nformat = unwords . map show\n"}, {"source_code": "main = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (readInt l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:xs) = (readInt x, xs)\n\nreadInt = foldl1 (\\x y -> x*10 + y) . map (\\x -> fromEnum x - 48)\n\nsolve n = n:[1..n-1]\n\nformat = unwords . map show\n"}, {"source_code": "main = interact $ unlines . map (format . solve) . parse . lines\n\nparse (l:ls) = take (read l) $ go ls\n where go ys = x:go ys'\n where (x,ys') = parse1 ys\n\nparse1 (x:xs) = (read x, xs)\n\nsolve n = n:[1..n-1]\n\nformat = unwords . map show\n"}, {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language Safe #-}\r\n{-# language ImportQualifiedPost #-}\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n] <- ri\r\n return n\r\n mapM_ (putStrLn.showL.solve) tcs\r\n\r\nshowL = unwords . map show\r\n\r\nsolve n = take n . drop (n-1) . cycle $ [1..n]\r\n"}], "negative_code": [], "src_uid": "955bc1e2769ea407ef02506bf1e4259b"} {"source_code": "--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# LANGUAGE Safe #-}\r\n{-# LANGUAGE ImportQualifiedPost #-}\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -O3 #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n{-# options_ghc -Werror #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport Data.ByteString.Char8 qualified as B\r\nimport Data.Char\r\nimport Data.List qualified as L\r\n\r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n\r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [n,m] <- ri\r\n return (n,m)\r\n mapM_ (putStrLn.showB.solve) tcs\r\n\r\nshowB False = \"Tonya\"\r\nshowB True = \"Burenka\"\r\n\r\nsolve (n,m) = isFirstWins\r\n where\r\n isFirstWins = odd $ (n-1) + (m-1)\r\n", "positive_code": [{"source_code": "decide :: Int -> IO()\r\ndecide t | t <= 0 = return ()\r\n | otherwise = do\r\n vars <- getLine >>= (return . words)\r\n let intoInt = return . ((\\a -> a `mod` 2 + 1) . (read :: String -> Int))\r\n \r\n n <- intoInt $ head vars\r\n m <- intoInt $ head $ tail vars \r\n \r\n --Sup\r\n --putStrLn (\"n = \" ++ (show n))\r\n --putStrLn (\"m = \" ++ (show m))\r\n \r\n if (n + m) `mod` 2 == 1\r\n then putStrLn \"Burenka\"\r\n else putStrLn \"Tonya\"\r\n decide $ t-1\r\n\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- getLine >>= (return . (read :: String -> Int))\r\n decide t"}], "negative_code": [], "src_uid": "13611e428c24b94023811063bbbfa077"} {"source_code": "import Control.Monad (replicateM_)\nimport Data.Bits ((.&.))\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = read <$> getLine >>= print . minNum\n\ns2P :: Int -> Int\ns2P x = x .&. (-x)\n\nminNum :: Int -> Int\nminNum x | s2P x == x = if x == 1 then 3 else x+1\n | otherwise = s2P x\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bits ((.&.))\r\n\r\n-- https://codeforces.com/problemset/problem/1688/A\r\nsolve :: Int -> Int\r\nsolve x =\r\n let y = x .&. (- x)\r\n in incWhile\r\n (\\z -> z == x || z .&. x == 0)\r\n y\r\n\r\nincWhile :: (Int -> Bool) -> Int -> Int\r\nincWhile p x = if p x then incWhile p (x + 1) else x\r\n\r\nmain :: IO ()\r\nmain =\r\n interact $\r\n lines\r\n >>> drop 1\r\n >>> map\r\n ( read\r\n >>> solve\r\n >>> show\r\n )\r\n >>> unlines\r\n"}, {"source_code": "module Main where\n\ngetMinNumber :: Int -> Int\ngetMinNumber 1 = 3\ngetMinNumber n = one n + isPower2 n\n where\n isPower2 m \n | even m = isPower2 (m `div` 2)\n | m == 1 = 1\n | otherwise = 0\n one m\n | even m = 2 * one (m `div` 2)\n | otherwise = 1\n\nsolution :: [Int] -> [Int]\nsolution (_: xs) = map getMinNumber xs\nsolution _ = undefined\n\nmain :: IO ()\nmain = interact $ unlines . map show . solution . map read . words"}, {"source_code": "-- boilerplate {{{1\n-- vim: foldmethod=marker\n-- pragmas {{{2\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Main where -- {{{2\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bifunctor\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\nimport Data.Foldable hiding ( sum, product )\nimport Data.Function\nimport Data.Functor\nimport Data.List hiding ( sum, product )\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Min(..), Max(..) )\nimport Data.Traversable\nimport Data.Tuple\nimport Debug.Trace\nimport Prelude hiding ( sum, product )\nimport System.IO\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntSet as IS\nimport qualified Data.Map as LM\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\n\n-- recursion schemes {{{2\ndata Tree a b = Tree a (Forest a b) deriving (Eq,Ord,Show,Functor)\ntype Forest a b = [b]\nderiving instance Foldable (Tree a)\nderiving instance Traversable (Tree a)\n\nhylo :: Functor f => (f b -> b) -> (a -> f a) -> a -> b\nhylo f g = h where h = f . fmap h . g\n\nnewtype Term f = In { out :: f (Term f) }\ntype Algebra f a = f a -> a\ntype Coalgebra f a = a -> f a\n\ncata :: Functor f => Algebra f a -> Term f -> a\ncata f = c where c = f . fmap c . out\n\nana :: Functor f => Coalgebra f a -> a -> Term f\nana g = a where a = In . fmap a . g\n\ntreeCoalgebra :: -- {{{2\n Int -> [[Int]] -> (Int -> a) -> \n Coalgebra (Tree a) (Int,Int)\ntreeCoalgebra n uvs f = coalg\n where\n coalg (curr,prev) = Tree (f curr) $ map (,curr) $ lookup curr prev\n lookup curr prev = IS.elems $ IS.delete prev $ uvary ! curr\n uvary = runSTArray $ do\n ary <- newArray (1,n) IS.empty\n let insert u 1 = pure ()\n insert u v = readArray ary u >>= writeArray ary u . IS.insert v\n for_ uvs $ \\[u,v] -> insert u v >> insert v u\n pure ary\n\ndata V2 a = V2 !a !a -- {{{2\n deriving ( Eq, Ord, Show )\ninstance Num a => Num (V2 a) where\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n (*) = liftA2 (*)\n abs = fmap abs\n negate = fmap negate\n signum = fmap signum\n fromInteger = pure . fromInteger\ninstance Functor V2 where\n fmap f (V2 a b) = V2 (f a) (f b)\n a <$ _ = V2 a a\ninstance Applicative V2 where\n pure a = V2 a a\n V2 a b <*> V2 d e = V2 (a d) (b e)\ninstance Monad V2 where\n V2 a b >>= f = V2 a' b' where\n V2 a' _ = f a\n V2 _ b' = f b\ninstance Foldable V2 where\n foldMap f (V2 a b) = f a `mappend` f b\n null _ = False\n length _ = 2\ninstance Traversable V2 where\n traverse f (V2 a b) = V2 <$> f a <*> f b\n\ndata V3 a = V3 !a !a !a -- {{{2\n deriving ( Eq, Ord, Show )\ninstance Num a => Num (V3 a) where\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n (*) = liftA2 (*)\n abs = fmap abs\n negate = fmap negate\n signum = fmap signum\n fromInteger = pure . fromInteger\ninstance Functor V3 where\n fmap f (V3 a b c) = V3 (f a) (f b) (f c)\n a <$ _ = V3 a a a\ninstance Applicative V3 where\n pure a = V3 a a a\n V3 a b c <*> V3 d e f = V3 (a d) (b e) (c f)\ninstance Monad V3 where\n V3 a b c >>= f = V3 a' b' c' where\n V3 a' _ _ = f a\n V3 _ b' _ = f b\n V3 _ _ c' = f c\ninstance Foldable V3 where\n foldMap f (V3 a b c) = f a `mappend` f b `mappend` f c\n null _ = False\n length _ = 3\ninstance Traversable V3 where\n traverse f (V3 a b c) = V3 <$> f a <*> f b <*> f c\n\n-- utilites {{{2\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\ngetInt = readInt <$> C.getLine\ngetInts = map readInt . C.words <$> C.getLine\nynq = putStrLn . bool \"No\" \"Yes\"\nynQ = putStrLn . bool \"NO\" \"YES\"\nmodulus = 10^9 + 7 :: Int\nmod' x = rem x modulus\nmprint :: Show a => String -> Maybe a -> IO ()\nmprint s = maybe (putStrLn s) print\ntri n = quot (n * n + n) 2\nifM :: Monad m => m Bool -> m a -> m a -> m a\nifM b t e = b >>= bool e t\nwhenM :: Monad m => m Bool -> m () -> m ()\nwhenM b t = ifM b t (pure ())\ngcount g@(x:_) = (x, length g)\nsum t = foldl' (+) 0 t\nproduct t = foldl' (*) 1 t\n\n-- }}}1\n\nmain = getInt >>= flip replicateM_ docase\n-- main = docase\n\ndocase = do\n [x] <- getInts\n print $ solve x\n\nsolve x\n | ay /= x = ay\n | otherwise = min by ny\n where\n (y:_,n:_) = partition (testBit x) [0..]\n ay = setBit 0 y\n by = setBit ay (y+1)\n ny = setBit ay n\n"}, {"source_code": "import Data.Bits\n\npowersOfTwo :: [Int]\npowersOfTwo = [2^i | i <- [0..30]]\n\nsolve :: Int -> Int\nsolve x = let powerIntersecingX = filter (\\power -> (x .&. power) > 0) powersOfTwo in\n if length powerIntersecingX > 1\n then head powerIntersecingX\n else if head powerIntersecingX /= 1\n then head powerIntersecingX + 1\n else head powerIntersecingX + 2\n\nmainLoop :: Int -> IO ()\nmainLoop t | t <= 0 = return ()\n | otherwise = do number <- (readLn :: IO Int)\n print (solve number)\n mainLoop (t - 1)\n\nmain :: IO ()\nmain = do t <- (readLn :: IO Int)\n mainLoop t\n"}], "negative_code": [], "src_uid": "288b36b64473326ea434dc74f05ae456"} {"source_code": "import Data.List\nimport Data.Function\n\nsolve :: [(Int, Int)] -> [Int]\nsolve xs =\n let\n d = groupDivider $ sort xs\n g = groups d xs\n in validate g\n\ngroupDivider :: [(Int, Int)] -> Int\ngroupDivider ((l, r) : xs) = go r xs\n where\n go r [] = r\n go r ((x, y) : ys)\n | x > r = r\n | otherwise = go (max r y) ys\n\ngroups :: Int -> [(Int, Int)] -> [Int]\ngroups d = map (f . (<= d). snd)\n where f True = 1\n f False = 2\n\nvalidate :: [Int] -> [Int]\nvalidate xs = if 2 `elem` xs then xs else [-1]\n\nlist2tuple :: [Int] -> (Int, Int)\nlist2tuple [x, y] = (x, y)\n\nparseInput :: String -> [[Int]]\nparseInput = map (map read . words) . lines\n\nsplitTestCases :: [[Int]] -> [[(Int, Int)]]\nsplitTestCases = map (map list2tuple) . \n filter ((==2) . length . head) .\n groupBy ((==) `on` length)\n \nformatOutput :: [[Int]] -> String\nformatOutput = unlines . map (unwords . map show)\n\nmain = interact $ formatOutput . map solve . splitTestCases . parseInput\n", "positive_code": [{"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe ([Int], [Int], Int) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), i) answer = do\n (a1, a2, ll) <- answer\n if r < ll then\n return (i : a2, a1, l)\n else \n return (i : a1, a2, min l ll)\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sortBy (compare `on` (\\((x, y), z) -> ((y, x), z))) $ zip segments [1..] \n (a1, a2, ll) <- foldr' foldAnswer (Just ([], [], 400000)) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "{- We can start out by picking one segment, and arbitrarily put it in a group. Then every other\n - segment that intersect with it have to be put in the same group, etc. If there are at least one\n - element in the rest, we're good. Now that might be very naive, and it uses nothing about segment\n - intersection other than its equivalence relation nature. The running time is definitely in big\n - theta of n squared: it will not fit. Let's nonetheless write this naive solution to get a better\n - view of the problem.\n -\n - The upper bound on li and ri suggests that they could be used to index an array.\n - \n - Update: as expected, the naive solution takes far too much time. There has to be a much better\n - way, using the fact that we are specifically dealing with intervals.\n - Reupdate: apparently the naive solution is fast enough for some inputs of maximum size. There\n - might be another factor that differentiates possible inputs. -}\n\nimport Data.List (intersperse, sortBy)\nimport Data.Ord (comparing)\n\nsortOn :: Ord b => (a -> b) -> [a] -> [a]\nsortOn f =\n map snd . sortBy (comparing fst) . map (\\x -> let y = f x in y `seq` (y, x))\n\nmain = interact (format . solve . parse)\n\nparse :: String -> [[IndexedInterval]]\nparse = reverse . parseQueries . words\n\nparseQueries :: [String] -> [[IndexedInterval]]\nparseQueries (ns:s) = let\n f 0 _ ret = ret\n f n xs ret = let (s0, q) = parseQuery xs in f (n - 1) s0 (q:ret)\n in\n f (read ns :: Integer) s []\n\nparseQuery :: [String] -> ([String], [IndexedInterval])\nparseQuery (ns:s) = let\n f 0 _ xs ret = (xs, ret)\n f rn i (x0:x1:xs) ret = f (rn - 1) (i + 1) xs (IndexedInterval {\n index = i,\n interval = Interval { begin=(read x0), end=(read x1) }\n }:ret)\n f _ _ _ _ = ([], [])\n in\n f (read ns :: Integer) 0 s []\nparseQuery [] = ([], [])\n\n{- Introducing these types does not make sense in a Codeforces context, but it might help with\n - Haskell the first few times. -}\ndata Interval = Interval { begin :: Integer, end :: Integer } deriving (Show)\ndata IndexedInterval = IndexedInterval { index :: Integer, interval :: Interval } deriving (Show)\n\nsolve = map solveQuery\n\nsolveQuery :: [IndexedInterval] -> Maybe [Bool]\nsolveQuery a = let (b, c) = (partitionIntervals . orderIntervals) a in reorderPartition b c\n\norderIntervals :: [IndexedInterval] -> [IndexedInterval]\norderIntervals a = sortOn (begin . interval) a\n\n{- Note: the intervals passed as argument MUST be sorted with respect to their left boundary. -}\npartitionIntervals :: [IndexedInterval] -> ([IndexedInterval], [IndexedInterval])\npartitionIntervals [] = ([], [])\npartitionIntervals (x:a) = let\n f u b [] = (b, [])\n f u b (i:c) = if end u < (begin . interval) i then (b, (i:c))\n else f (union u (interval i)) (i:b) c\n in f (interval x) [x] a\n\nreorderPartition :: [IndexedInterval] -> [IndexedInterval] -> Maybe [Bool]\nreorderPartition _ [] = Nothing\nreorderPartition a b = Just $ map snd $ sortOn fst $ (map (\\i -> (index i, False)) a) ++ (map (\\i -> (index i, True)) b)\n\n{- Only makes sense when passed intersecting intervals. -}\nunion :: Interval -> Interval -> Interval\nunion (Interval l0 r0) (Interval l1 r1) = Interval (min l0 l1) (max r0 r1)\n\n{- Returns a query result in the requested output form -}\nformatQuery :: Maybe [Bool] -> String\nformatQuery Nothing = \"-1\"\nformatQuery (Just a) = intersperse ' ' $ map (\\x -> if x then '2' else '1') a\n\nformat :: [Maybe [Bool]] -> String\nformat = unlines . (map formatQuery)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix, on)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\ncheck (([_,sr],_):range) = go range sr 2\n where go [] _ _ = -1\n go (([l,r], _):s) x i\n | l > x = i\n | otherwise = go s (max x r) (i+1)\n\nsolve _ = do\n [q] <- getInts\n range <- forM [1..q] (\\_ -> getInts)\n let sorted = sortBy (compare `on` (head . fst)) (zip range [1..])\n let k = check sorted\n let v = zip (map snd sorted) (map (\\x -> if x < k then 1 else 2) [1..q])\n if k == -1 then print k else (printInts $ map snd $ sort v)\n\nmain = do\n [t] <- getInts\n mapM_ solve [1..t]"}, {"source_code": "import Data.List\nimport Data.Function\n\nsolve :: [(Int, Int)] -> String\nsolve xs =\n let\n d = groupDivider $ sort xs\n g = groups d xs\n v = validate g\n in unwords $ map show v\n\ngroupDivider :: [(Int, Int)] -> Int\ngroupDivider ((l, r) : xs) = go r xs\n where\n go r [] = r\n go r ((x, y) : ys)\n | x > r = r\n | otherwise = go (max r y) ys\n\ngroups :: Int -> [(Int, Int)] -> [Int]\ngroups d = map (f . (<= d). snd)\n where f True = 1\n f False = 2\n\nvalidate :: [Int] -> [Int]\nvalidate xs = if 2 `elem` xs then xs else [-1]\n\nlist2tuple :: [Int] -> (Int, Int)\nlist2tuple [x, y] = (x, y)\n\nparseInput :: String -> [[Int]]\nparseInput = map (map read . words) . lines\n\nsplitTestCases :: [[Int]] -> [[(Int, Int)]]\nsplitTestCases = map (map list2tuple) . \n filter ((==2) . length . head) .\n groupBy ((==) `on` length)\n\nmain = interact $ unlines . map solve . splitTestCases . parseInput\n"}, {"source_code": "-- Educational Codeforces Round #58 (C), Contest 1101, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n <- read <$> getLine\n lrs <- replicateM n\n $ (\\[l,r] -> (l,r)) . map read . words <$> getLine\n putStrLn $ fromMaybe \"-1\" $ unwords . map show <$> query lrs\n\nquery :: [(Int,Int)] -> Maybe [Int]\nquery lrs = fmap (\\cp -> map (\\(l,r) -> if r <= cp then 1 else 2) lrs) cutpt\n where\n cutpt = fmap fst $ find ((== 0) . snd)\n $ init $ merge $ sort (lrs >>= \\(l,r) -> [(l,1),(r,-1)])\n merge [] = []\n merge ((i,x):xs) = go i x xs\n where\n go !i !acc [] = [(i,acc)]\n go !i !acc ((j,x):xs) | i == j = go i (acc+x) xs\n | otherwise = (i,acc) : go j (acc+x) xs\n"}], "negative_code": [{"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe (([Int], Int), ([Int], Int)) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), id) answer = do\n ((a1, l1), (a2, l2)) <- answer\n if r < l2 then\n if l < l1 then \n return ((id : a2, l), (a1, l1))\n else \n return ((a1, l1), (id : a2, l))\n else\n Nothing\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sortBy (compare `on` snd) $ zip segments [1..] \n ((a1, l1), (a2, l2)) <- foldr' foldAnswer (Just (([], 300000), ([], 300000))) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe (([Int], Int), ([Int], Int)) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), id) answer = do\n ((a1, l1), (a2, l2)) <- answer\n if r < l2 then\n if l < l1 then \n return ((id : a2, l), (a1, l1))\n else \n return ((a1, l1), (id : a2, l))\n else\n Nothing\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sortBy (compare `on` (\\((x, y), z) -> ((y, x), z))) $ zip segments [1..] \n ((a1, l1), (a2, l2)) <- foldr' foldAnswer (Just (([], 300000), ([], 300000))) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe (([Int], Int), ([Int], Int)) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), id) answer = do\n ((a1, l1), (a2, l2)) <- answer\n if (r < l1) && not (null a2 && r < l2) then\n return ((id : a1, l), (a2, l2))\n else \n if r < l2 then \n Just ((a1, l1), (id : a2, l))\n else \n Nothing\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sort $ zip segments [1..] \n ((a1, l1), (a2, l2)) <- foldr' foldAnswer (Just (([], 300000), ([], 300000))) sortedSegments \n return . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe (([Int], Int), ([Int], Int)) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), id) answer = do\n ((a1, l1), (a2, l2)) <- answer\n if (r < l1) && not (null a2 && r < l2) then\n return ((id : a1, l), (a2, l2))\n else \n if r < l2 then \n Just ((a1, l1), (id : a2, l))\n else \n Nothing\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sort $ zip segments [1..] \n ((a1, l1), (a2, l2)) <- foldr' foldAnswer (Just (([], 300000), ([], 300000))) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe (([Int], Int), ([Int], Int)) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), id) answer = do\n ((a1, l1), (a2, l2)) <- answer\n if r < l2 then\n if l < l1 then \n return ((id : a2, l), (a1, l1))\n else \n return ((a1, l1), (id : a2, l))\n else\n Nothing\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sortBy (compare `on` (\\((x, y), z) -> ((y, x), z))) $ zip segments [1..] \n ((a1, l1), (a2, l2)) <- foldr' foldAnswer (Just (([], 300000), ([], 300000))) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe (([Int], Int), ([Int], Int)) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), id) answer = do\n ((a1, l1), (a2, l2)) <- answer\n if r < l2 then\n if l < l1 then \n return ((id : a2, l), (a1, l1))\n else \n return ((a1, l1), (id : a2, l))\n else\n Nothing\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sort $ zip segments [1..] \n ((a1, l1), (a2, l2)) <- foldr' foldAnswer (Just (([], 300000), ([], 300000))) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "import Text.Printf\nimport Data.List\nimport Data.Functor\nimport Control.Applicative\nimport Prelude\nimport Control.Monad\nimport Data.Maybe\nimport Data.Function\nimport Data.Array\nimport qualified Data.ByteString.Char8 as B8\nimport Data.Foldable (foldr')\n\nreadInt :: String -> Int\nreadInt = Prelude.read\n\ntype Answer = Maybe ([Int], [Int], Int) \n\nfoldAnswer :: ((Int, Int), Int) -> Answer -> Answer\nfoldAnswer ((l, r), i) answer = do\n (a1, a2, ll) <- answer\n if r < ll then\n return (i : a2, a1, l)\n else\n return (i : a1, a2, l)\n\nsolve :: [(Int, Int)] -> Maybe [Int]\nsolve segments = do\n let sortedSegments = sortBy (compare `on` (\\((x, y), z) -> ((y, x), z))) $ zip segments [1..] \n (a1, a2, ll) <- foldr' foldAnswer (Just ([], [], 400000)) sortedSegments\n if null a1 || null a2 then\n Nothing\n else \n Just . map snd . sort $ (zip a1 (repeat 1) ++ zip a2 (repeat 2))\n \n\nmain :: IO ()\nmain = do\n testCount <- readInt <$> getLine\n replicateM_ testCount $ do\n n <- readInt <$> getLine\n segments <- replicateM n $ ((\\[l, r] -> (l, r)) . map readInt . words) <$> getLine\n let answer = fromMaybe [-1] $ solve segments\n forM_ answer $ printf \"%d \"\n printf \"\\n\""}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix, on)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\ncheck range = go range 0 -- l\n where go [] _ = -1\n go (([l, r], k):[]) x = if x < l then k else -1\n go (([l,r], k):([nl,nr], k2):s) x\n | l > x && r < nl = k\n | otherwise = go (([nl,nr],k2):s) (max x r)\n\nsolve _ = do\n [q] <- getInts\n range <- forM [1..q] (\\_ -> getInts)\n let sorted = sortBy (compare `on` (head . fst)) (zip range [1..])\n let k = check sorted\n if k == -1 then print k else printInts $ map (\\x -> if x == k then 2 else 1) [1..q]\n\nmain = do\n [t] <- getInts\n mapM_ solve [1..t]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix, on)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nmake range = go range 0 0 -- l, r \uac01\uac01 \uc624\ub978\ucabd \ub05d \uc720\uc9c0\n where go [] _ _ = []\n go ([l, r]:ls) x y\n | l > max x y = if x > y then 1:go ls r y else 2:go ls x r\n | l > x = 1: go ls r y\n | l > y = 2: go ls x r\n | otherwise = []\n\nsolve _ = do\n [q] <- getInts\n range <- forM [1..q] (\\_ -> getInts)\n let sorted = sortBy (compare `on` head) range\n let groups = make sorted\n let groups' = if all (\\x -> x == 2) groups then 1:tail groups else groups\n if length groups' < q then print (-1) else printInts groups'\n\nmain = do\n [t] <- getInts\n mapM_ solve [1..t]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix, on)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nmake range = go range 0 0 -- l, r \uac01\uac01 \uc624\ub978\ucabd \ub05d \uc720\uc9c0\n where go [] _ _ = []\n go (([l, r], k):ls) x y\n | l > max x y = if x > y then (k, 1):go ls r y else (k, 2):go ls x r\n | l > x = (k, 1): go ls r y\n | l > y = (k, 2): go ls x r\n | otherwise = []\n\nsolve _ = do\n [q] <- getInts\n range <- forM [1..q] (\\_ -> getInts)\n let sorted = sortBy (compare `on` (head . fst)) (zip range [1..])\n let groups = make sorted\n let groups' = if all (\\(a, b) -> b == 2) groups then (fst $ head groups, 1):tail groups else groups\n let sorted' = sortBy (compare `on` fst) groups'\n if length groups' < q then print (-1) else printInts (map snd sorted')\n\nmain = do\n [t] <- getInts\n mapM_ solve [1..t]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix, on)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nmake range = go range 0 0 -- l, r \uac01\uac01 \uc624\ub978\ucabd \ub05d \uc720\uc9c0\n where go [] _ _ = []\n go ([l, r]:ls) x y\n | l > x = 1:go ls r y\n | l > y = 2: go ls x r\n | otherwise = []\n\nsolve _ = do\n [q] <- getInts\n range <- forM [1..q] (\\_ -> getInts)\n let sorted = sortBy (compare `on` head) range\n let groups = make sorted\n let groups' = if all (\\x -> x == 1) groups then 2:tail groups else groups\n if length groups' < q then print (-1) else printInts groups'\n\nmain = do\n [t] <- getInts\n mapM_ solve [1..t]"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport System.IO\nimport Control.Applicative\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Function (fix, on)\nimport Data.Array (Array, array, (!))\nimport Data.ByteString.Lazy.Builder\nimport Data.ByteString.Lazy.Builder.ASCII\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\nconstruct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]\nconstruct reader str\n | BS.null str = []\n | isSpace (BS8.head str) = construct reader (BS8.tail str)\n | otherwise = let Just (i, other) = reader str in i : construct reader other\n\ngetInts :: IO [Int]\ngetInts = construct BS8.readInt <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = construct BS8.readInteger <$> BS.getLine\n\nprintInts :: [Int] -> IO ()\nprintInts = putStrLn . intercalate \" \" . map show\n\nmake range = go range 0 0 -- l, r \uac01\uac01 \uc624\ub978\ucabd \ub05d \uc720\uc9c0\n where go [] _ _ = []\n go ([l, r]:ls) x y\n | l > max x y = if x > y then 1:go ls r y else 2:go ls x r\n | l > x = 1: go ls r y\n | l > y = 2: go ls x r\n | otherwise = []\n\nsolve _ = do\n [q] <- getInts\n range <- forM [1..q] (\\_ -> getInts)\n let sorted = sortBy (compare `on` head) range\n let groups = make sorted\n let groups' = if all (\\x -> x == 1) groups then 2:tail groups else groups\n if length groups' < q then print (-1) else printInts groups'\n\nmain = do\n [t] <- getInts\n mapM_ solve [1..t]"}], "src_uid": "13fbcd245965ff6d1bf08915c4d2a2d3"} {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt && cat -- bw.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\r\n\r\nimport Prelude\r\nimport System.IO\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map (show . solve)) tcs\r\n\r\nreadTC = do\r\n [n,_m, r,c] <- map read . words <$> getLine\r\n rows <- replicateM n getLine\r\n return (rows, r-1, c-1)\r\n\r\nsolve (rows, r, c) = x\r\n where\r\n row = rows !! r\r\n col = transpose rows !! c\r\n\r\n rowChars = toBlacks row\r\n colChars = toBlacks col\r\n matrChars = toBlacks (concat rows)\r\n\r\n x = case (row!!c, rowChars, colChars, matrChars) of\r\n ('B', _ , _ , _ ) -> 0\r\n ('W', \"B\", _ , _ ) -> 1\r\n ('W', _ , \"B\", _ ) -> 1\r\n ('W', _ , _ , \"B\") -> 2\r\n ('W', _ , _ , \"\" ) -> -1\r\n _ -> error \"logic error\"\r\n\r\ntoBlacks = nub . sort . filter (== 'B')\r\n", "positive_code": [{"source_code": "\r\n\r\n--\r\n-- Michael V. Antosha\r\n-- 2022\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt)\r\n\r\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && diff -sdu -- <(cat -- input.txt | ./a.out) output.txt)\r\n\r\n-- cat -- bw.hs | xclip -selection clipboard\r\n\r\nimport Prelude\r\nimport System.IO\r\nimport Control.Monad\r\nimport Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n hSetBuffering stdout NoBuffering\r\n\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map (show . solve)) tcs\r\n\r\nreadTC = do\r\n [n,_m, r,c] <- map read . words <$> getLine\r\n rows <- replicateM n getLine\r\n return (rows, r-1, c-1)\r\n\r\nsolve (rows, r, c) = x\r\n where\r\n row = rows !! r\r\n col = transpose rows !! c\r\n\r\n rowChars = toBlacks row\r\n colChars = toBlacks col\r\n matrChars = toBlacks (concat rows)\r\n\r\n x = case (row!!c, rowChars, colChars, matrChars) of\r\n ('B', _ , _ , _ ) -> 0\r\n ('W', \"B\", _ , _ ) -> 1\r\n ('W', _ , \"B\", _ ) -> 1\r\n ('W', _ , _ , \"B\") -> 2\r\n ('W', _ , _ , \"\" ) -> -1\r\n _ -> error \"logic error\"\r\n\r\ntoBlacks = nub . sort . filter (== 'B')\r\n"}, {"source_code": "{-# LANGUAGE TupleSections #-}\nimport Data.Array\nimport Control.Monad (replicateM_, replicateM)\n\nmain :: IO ()\nmain = read <$> getLine >>= flip replicateM_ singleCase\n\nreadInput :: IO (Int, Int, Int, Int, Array (Int, Int) Bool)\nreadInput = map read . words <$> getLine >>=\n \\a -> case a of\n [n, m, r, c] -> (n,m,r,c,) . toA n m . map (=='W') .\n concat <$> replicateM n getLine\n _ -> error $ \"Could not read an array: \" ++ show (a)\n where\n toA n m = listArray ((1, 1), (n, m)) \n\nsingleCase :: IO ()\nsingleCase = readInput >>= print . f\n where\n f (n,m,r,c,a) | (not $ a!(r,c)) = 0\n | (blackView a r c) = 1\n | (blackCount a > 0) = 2\n | otherwise = -1\n\nblackView :: Array (Int, Int) Bool -> Int -> Int -> Bool\nblackView a r c = any (\\i -> not (a!i))\n $ zip (repeat r) [1..m] ++ zip [1..n] (repeat c)\n where ((1, 1), (n, m)) = bounds a\n\nblackCount :: Array (Int, Int) Bool -> Int\nblackCount = foldl (\\acc b -> if b then acc else acc+1) 0\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\ntest :: IO ()\ntest = do\n [n, _, r', c'] <- (<$>) read . words <$> getLine\n let (r, c) = (pred r', pred c')\n grid <- replicateM n getLine\n print\n ( if\n | (all . all) (== 'W') grid -> -1\n | grid !! r !! c == 'B' -> 0\n | any (== 'B') (grid !! r) || any (== 'B') ((!! c) <$> grid) -> 1\n | otherwise -> 2\n )\n return ()\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n"}], "negative_code": [], "src_uid": "4ca13794471831953f2737ca9d4ba853"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array ((!), indices, listArray)\n\nn :: Num a => a\nn = 8\n\n() :: a -> a -> Bool -> a\n() a b p = if p then a else b\n\nsolve :: [[String]] -> [Bool]\nsolve = map (solve' . toArray)\n where\n toArray = listArray ((1, 1), (n, n)) . concat\n solve' array\n = abs (x1 - x2) `mod` 4 == 0\n && abs (y1 - y2) `mod` 4 == 0\n where\n [(x1, y1), (x2, y2)] =\n [ij | ij <- indices array, array ! ij == 'K']\n\nintoGroups :: Int -> [a] -> [[a]]\nintoGroups _ [] = []\nintoGroups n xs = take n xs : intoGroups n (drop n xs)\n\nmain :: IO ()\nmain = liftM (intoGroups n . tail . words) getContents\n >>= return . solve\n >>= mapM_ (putStrLn . (\"YES\" \"NO\"))\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = B.readInt >>> fmap fst >>> fromMaybe 0\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\n\ninfixr 2 <||> \ninfixr 3 <&&>\np1 <||> p2 = (p1 &&& p2) >>> uncurry (||)\np1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)\n\nmain = do\n n <- readLn\n forM_ [1..n] $ \\i -> do\n l <- replicateM 8 getLine\n putStrLn $ if solve l then \"YES\" else \"NO\"\n when ( i < n ) (void getLine)\n\nsolve :: [String] -> Bool\nsolve l = any (check bads) $ zip l1 l2\n where\n as = zip (range ((1,1),(8,8))) (concat l) \n [k1,k2] = [ p | (p,'K') <- as ]\n bads = S.fromList [ p | (p,'#') <- as ]\n l1 = calcFP step (S.empty,S.singleton k1)\n l2 = calcFP step (S.empty,S.singleton k2)\n\ntype Pos = (Int,Int)\ncheck :: S.Set Pos -> ((S.Set Pos,S.Set Pos),(S.Set Pos,S.Set Pos))-> Bool\ncheck bads ((a,b),(c,d)) = sub a b || sub b d\n where\n sub x y = not $ S.null (S.intersection x y S.\\\\ bads)\n\nnext (i,j) = (\\dx dy -> (i+dx,j+dy)) <$> [-2,2] <*> [-2,2]\n\nstep (s1,s2) = (s3,s4)\n where\n f s = S.fromList $ do\n p <- S.elems s >>= next\n guard (inRange ((1,1),(8,8)) p)\n return p\n s3 = f s2\n s4 = f s3\n\ncalcFP f p = p:go p\n where\n go p = let p' = f p in if p' == p then [] else p':go p'\n"}], "negative_code": [], "src_uid": "4f3bec9c36d0ac2fdb8041469133458c"} {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ExplicitForAll #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IS\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.STRef\nimport Data.IORef\nimport Data.Function\nimport System.IO\nimport System.Exit\nimport Data.Char\n\nmain :: IO ()\nmain = do\n [n,m,k] <- map readInt . words <$> getLine\n powers <- A.listArray (1,n) . map readInt . words <$> getLine\n :: IO (UArray Int Int)\n school <- A.listArray (1,n) . map readInt . words <$> getLine\n :: IO (UArray Int Int)\n chosen <- map readInt . words <$> getLine\n print\n $ length\n $ [ i\n | i <- chosen,\n (> powers A.! i) $ maximum\n $ map (powers A.!) $ map fst\n $ filter ((== school A.! i) . snd) $ A.assocs school]\n \n \n\nrInt :: StateT BSL.ByteString Maybe Int\nrInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')\n\n#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read\n#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling\nC(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)\nC(toInt,readInt,floorInt,ceilInt,Int)\nC(toI8,readI8,floorI8,ceilI8,Int8)\nC(toI16,readI16,floorI16,ceilI16,Int16)\nC(toI32,readI32,floorI32,ceilI32,Int32)\nC(toI64,readI64,floorI64,ceilI64,Int64)\nC(toWord,readWord,floorWord,ceilWord,Word)\nC(toW8,readW8,floorW8,ceilW8,Word8)\nC(toW16,readW16,floorW16,ceilW16,Word16)\nC(toW32,readW32,floorW32,ceilW32,Word32)\nC(toW64,readW64,floorW64,ceilW64,Word64)\nD(toDouble,readDouble,Double)\nD(toFloat,readFloat,Float)\n#undef D\n#undef C\n\n\n#define N(f,g,a,m)\\\n f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\\\n g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_\n#define C(a,m)\nN(newIOA,newIOA_,IOArray,IO)\nN(newSTA,newSTA_,STArray s,ST s)\n#undef C\n#define C(a,m) MArray (a) e (m), \nN(newIOUA,newIOUA_,IOUArray,IO)\nN(newSTUA,newSTUA_,STUArray s,ST s)\n#undef C\n#undef N\n\n", "positive_code": [{"source_code": "{-\nProblem statement in Japanese:\n\n\u30c8\u30fc\u30ca\u30e1\u30f3\u30c8\u304c\u958b\u50ac\u3055\u308c\u308b.\nm\u6821\u306e\u5b66\u6821\u304c\u53c2\u52a0\u3057\u5404\u6821\u304b\u30891\u4eba\u53c2\u52a0\u3067\u304d\u308b.\n\n\u5168\u3066\u306e\u5b66\u6821\u5408\u308f\u305b\u3066\u5b66\u751f\u306fn\u4eba\u3067\u3042\u308b.\n\u30c8\u30fc\u30ca\u30e1\u30f3\u30c8\u524d\u306b\u5168\u3066\u306e\u5b66\u751f\u306f\u6c0f\u540d\u3068\u5b66\u6821\u540d\u3092Techno\u306b\u63d0\u51fa\u3059\u308b.\n\u7d9a\u3044\u3066Techno\u306f\u5404\u6821\u304b\u3089\u6700\u3082\u5f37\u3044\u5b66\u751f\u3092\u53c2\u52a0\u8005\u3068\u3057\u3066\u9078\u3076.\n\nArkady\u306f\u7279\u5b9a\u306ek\u4eba\u304c\u9078\u3070\u308c\u308b\u3088\u3046\u306b\u3057\u305f\u3044.\n\u6b8b\u5ff5\u306a\u304c\u3089, \u305d\u306e\u5b66\u751f\u9054\u306f\u81ea\u8eab\u306e\u5b66\u6821\u3067\u6700\u3082\u5f37\u3044\u3068\u306f\u9650\u3089\u306a\u3044.\n\u3057\u304b\u3057, Arkady\u306f\u5b66\u6821\u540d\u3092\u8ffd\u52a0\u3057, \u5b66\u751f\u306e\u5b66\u6821\u540d\u3092\u8ffd\u52a0\u3057\u305f\u3082\u306e\u306b\u66f8\u304d\u63db\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b.\n\u306a\u304a, \u8ffd\u52a0\u3057\u305f\u5b66\u6821\u540d\u3092\u4f7f\u3044\u56de\u3059\u3053\u3068\u306f\u3067\u304d\u306a\u3044.\n\n\u3042\u306a\u305f\u306f\u5404\u5b66\u751f\u306e\u5f37\u3055\u3068\u5b66\u6821\u540d\u3092\u77e5\u3063\u3066\u3044\u308b.\n\u7279\u5b9a\u306ek\u4eba\u304c\u9078\u3070\u308c\u308b\u305f\u3081\u306b\u5fc5\u8981\u3068\u306a\u308b, \u5b66\u6821\u540d\u3092\u8ffd\u52a0\u3059\u308b\u6700\u5c0f\u56de\u6570\u3092\u6c42\u3081\u3088.\n-}\n\nmain = do\n [_, _, _] <- map read . words <$> getLine :: IO [Int]\n as <- map read . words <$> getLine :: IO [Int]\n ps <- map read . words <$> getLine :: IO [Int]\n qs <- map read . words <$> getLine :: IO [Int]\n let xs = zip as ps\n print $ sum $ map (f xs) qs\n \nf xs q = if a < m then 1 else 0\n where\n m = maximum $ map fst $ filter ((== p) . snd) xs\n (a, p) = xs !! (q - 1)\n"}], "negative_code": [], "src_uid": "e34f110440942a841624d0f42e0ddec4"} {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\ntest x v t = maximum la <= minimum lb where\n (la, lb) = unzip $ zipWith (\\a b -> (a - t * b, a + t * b)) x v\n\nbin x v a b | b - a < 1E-6 = b\n | test x v ((a + b) / 2) = bin x v a ((a + b) / 2)\n | otherwise = bin x v ((a + b) / 2) b\n\nmain = do\n (read -> n) <- getLine\n (take n . map (read :: String -> Double) . words -> x) <- getLine\n (take n . map (read :: String -> Double) . words -> v) <- getLine\n let tm = (maximum x - minimum x) * maximum v\n putStrLn $ show $ bin x v 0.0 tm\n", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n readLine\n xs <- readLine\n vs <- readLine\n print $ search 0 1e9 $ sortBy (\\(a, _) (b, _) -> a `compare` b) (zip xs vs)\n where\n search :: Double -> Double -> [(Double, Double)] -> Double\n search t1 t2 xvs\n | abs (t1-t2) <= 1e-6 = t2\n | otherwise = if valid mid then search t1 mid xvs else search mid t2 xvs\n where\n mid = (t1+t2)/2\n\n valid :: Double -> Bool\n valid t = loop (tail xvs) (x0+v0*t)\n where\n (x0, v0) = head xvs\n\n loop [] _ = True\n loop ((curX, curV):rem) rightMost =\n if (curX - t*curV) <= rightMost then loop rem (min (curX + t*curV) rightMost)\n else False\n\nreadLine :: IO [Double]\nreadLine = getLine >>= return . words >>= return . (map read)\n"}, {"source_code": "-- Codeforces Round #403 (Div. 2)\n-- B. The Meeting Place Cannot Be Changed\n-- http://codeforces.com/contest/782/problem/B\n\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\nmain = do\n n <- getInt\n coords <- (map fromIntegral) `fmap` getInts :: IO [Double]\n speeds <- (map fromIntegral) `fmap` getInts :: IO [Double]\n let (lb, ub) = recurse coords speeds (0.0, 1e9) 100\n let answer = (lb + ub) / 2.0\n print answer\n\nrecurse _ _ result 0 = result\nrecurse coords speeds (lb, ub) cnt\n | canMeet coords speeds mid = recurse coords speeds (lb, mid) (cnt-1)\n | otherwise = recurse coords speeds (mid, ub) (cnt-1)\n where mid = (lb + ub) / 2.0\n\ncanMeet :: [Double] -> [Double] -> Double -> Bool\ncanMeet coords speeds t = isJust $ foldl getOverlap (Just (0.0, 1e9)) ranges where\n ranges = zipWith (\\coord speed -> (coord - speed * t, coord + speed * t)) coords speeds\n\ngetOverlap Nothing _ = Nothing\ngetOverlap (Just (l1, r1)) (l2, r2)\n | l > r = Nothing\n | otherwise = Just (l, r)\n where\n l = max l1 l2\n r = min r1 r2\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Data.List\n\nmain :: IO ()\nmain = do\n readLine\n xs <- readLine\n vs <- readLine\n print $ search 0 1e9 $ sortBy (\\(a, _) (b, _) -> a `compare` b) (zip xs vs)\n where\n search :: Double -> Double -> [(Double, Double)] -> Double\n search t1 t2 xvs\n | abs (t1-t2) <= 1e-6 = t2\n | otherwise = if valid mid then search t1 mid xvs else search mid t2 xvs\n where\n mid = (t1+t2)/2\n\n valid :: Double -> Bool\n valid t = loop xvs (x0+v0*t)\n where\n (x0, v0) = head xvs\n\n loop [] _ = True\n loop ((curX, curV):rem) rightMost =\n if (curX - t*curV) <= rightMost then loop rem (min (curX + t*curV) rightMost)\n else False\n\nreadLine :: IO [Double]\nreadLine = getLine >>= return . words >>= return . (map read)\n"}], "negative_code": [], "src_uid": "f13f27a131b9315ebbb8688e2f43ddde"} {"source_code": "--fast read\nimport qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Control.Applicative\nmodulo=1000000007\nreadInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.words a\nreadLists = readInts $ B.getLine\nreadLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInteger) $ fmap B.lines $ B.getContents\nreadMatrix = fmap readInts $ fmap B.lines $ B.getContents\ngetModLessNum::Integer->Integer->Integer -> Integer\ngetModLessNum n a m\n | n-1-m < 0 = 0\n | otherwise = 1 + div (n-m-1) a -- fromIntegral $ length $ filter (\\x -> mod x a == m) [0..(n-1)]\ngetModNum::Integer->Integer->Integer\ngetModNum k a = getModLessNum (10^k) a 0\ngetModNumNot::Integer->Integer->Integer->Integer \ngetModNumNot k a b = getModLessNum (10^(k-1)) a (mod (a - (mod (b*(10^(k-1))) a)) a)\ngetAns::Integer -> Integer -> Integer -> Integer\ngetAns k a b = (getModNum k a) - (getModNumNot k a b)\nmain = do\n [n,k] <- readLists\n a <- readLists\n b <- readLists\n let ans = foldr1 (\\x y -> mod (x*y) modulo) [getAns k a0 b0|(a0,b0) <- zip a b]\n print $ ans\n", "positive_code": [{"source_code": "main = interact $ show . solve . parse\n where parse = filter (not . null) . map (map read . words) . lines\n\nmod' = (`mod` (10^9+7))\n\nsolve :: [[Integer]] -> Integer\nsolve [[_, k], as, bs] = product' xs\n where\n product' = foldr (\\x y -> mod' (x*y)) 1\n xs = zipWith solveBlock as bs\n solveBlock x y = mod' $ below 10 - below (y+1) + below y\n where\n below n\n | n <= 0 = 0\n | otherwise = 1 + (n * 10^(k-1) - 1) `div` x\n"}, {"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Data.Int\n\nmodn :: Int64\nmodn = 1000000007\n\nnums k a b = (10^k-1) `div` a - (firstDigit b) + (if b == 0 then 0 else 1)\n where firstDigit l\n | l == 0 = (10^(k-1) - 1) `div` a\n | otherwise = ((l+1) * 10^(k-1) - 1) `div` a - (l*10^(k-1) - 1) `div` a\n\nmain :: IO ()\nmain = do\n [n, k] <- map (read::String->Int64) . words <$> getLine\n as <- map (read::String->Int64) . words <$> getLine\n bs <- map (read::String->Int64) . words <$> getLine\n let blocks = zipWith (nums k) as bs\n print $ foldl' (\\a -> \\b -> a*b `mod` modn) 1 blocks\n\n"}, {"source_code": "import Control.Applicative\n\nsolve :: Integer -> (Integer,Integer) -> Integer\nsolve k (a,b) = num - rm\n where\n num = (10^k - 1) `div` a + 1\n rm = (+ 1) . (`div` a) . max (-1) $ ((b+1) * 10^(k-1) - 1) - ((b * 10^(k-1) - 1) `div` a + 1) * a\n\nmain :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine\n a <- map read . words <$> getLine\n b <- map read . words <$> getLine\n print . foldr1 (((`mod` 1000000007) .) . (*)) . map ((`mod` 1000000007) . solve k) $ zip a b\n"}], "negative_code": [{"source_code": "import Control.Monad\nimport Control.Applicative\nimport Data.List\n\nmodn :: Int\nmodn = 1000000007\n\nnums k a b = (10^k-1) `div` a - (firstDigit b) + (if b == 0 then 0 else 1)\n where firstDigit l\n | l == 0 = (10^(k-1) - 1) `div` a\n | otherwise = ((l+1) * 10^(k-1) - 1) `div` a - (l*10^(k-1) - 1) `div` a\n\nmain :: IO ()\nmain = do\n [n, k] <- map (read::String->Int) . words <$> getLine\n as <- map (read::String->Int) . words <$> getLine\n bs <- map (read::String->Int) . words <$> getLine\n let blocks = zipWith (nums k) as bs\n print $ foldl' (\\a -> \\b -> a*b `mod` modn) 1 blocks\n\n"}], "src_uid": "dcb483886c81d2cc0ded065aa1e74091"} {"source_code": "import Data.Char\nmain = do nk <- getLine\n let n = (read.head.words) nk\n let k = (toInteger.read.last.words) nk\n sa <- getLine\n let a = (map toInteger.map read.words) sa\n let b = calc n a 0\n let s = scanr1 (\\x y -> (if y > k * 10 then y else y * 2 + x)) (if last b < 0 then map (0 -) b else b)\n let ans = if last b < 0 then calc2 n k (map (0-) a) (map (0-) b) s else calc2 n k a b s\n putStrLn (show ans)\nmyRead :: String -> Int\nmyRead ('-':as) = 0 - foldl (\\x y -> 10*x + (ord y - ord '0')) 0 as\nmyRead s = foldl (\\x y -> 10*x + (ord y - ord '0')) 0 s\ncalc :: Int -> [Integer] -> Int -> [Integer]\ncalc 0 (a:[]) car = [toInteger car + a]\ncalc n (a:as) car = if bi < 0\n then toInteger(mod (-bi) 2):calc (n-1) as (-(div (-bi) 2) - mod (-bi) 2)\n else toInteger(mod bi 2):calc (n-1) as (div bi 2)\n where bi = car + fromInteger a\ncalc2 :: Int -> Integer -> [Integer] -> [Integer] -> [Integer] -> Int\ncalc2 0 k (a:[]) (b:[]) (s:[]) = if abs (s - a) <= k && a /= s then 1 else 0\ncalc2 n k (a:as) (b:bs) (s:ss) | b /= 0 && abs (s - a) <= k = 1\n | b /= 0 = 0\n | abs (s - a) <= k = 1 + calc2 (n-1) k as bs ss\n | otherwise = calc2 (n-1) k as bs ss", "positive_code": [{"source_code": "large=123456789123456789\nmain=interact$show.f1.map read.tail.words\nf1 (a:b)=f3 a 0 b $(reverse.f2 a 0.reverse) b\nf2 a b [c]=[]\nf2 a b (c:d)=if abs e>a then large:f2 a large d else e:f2 a e d where e=b*2+c\nf3 a b [c] _=if abs b<=a && b/=0 then 1 else 0\nf3 a b (c:d) (e:f)=if e/=large && abs (e*2+b)<=a then 1+g else g where g=f4 a (b+c) d f\nf4 a b c d=if odd b then 0 else f3 a (div b 2) c d"}, {"source_code": "import Data.Char\nmain = do nk <- getLine\n let n = (myRead.head.words) nk\n let k = (toInteger.myRead.last.words) nk\n sa <- getLine\n let a = (map toInteger.map myRead.words) sa\n let b = calc n a 0\n let s = scanr1 (\\x y -> (if y > k * 10 then y else y * 2 + x)) (if last b < 0 then map (0 -) b else b)\n let ans = if last b < 0 then calc2 n k (map (0-) a) (map (0-) b) s else calc2 n k a b s\n putStrLn (show ans)\nmyRead :: String -> Int\nmyRead ('-':as) = 0 - foldl (\\x y -> 10*x + (ord y - ord '0')) 0 as\nmyRead s = foldl (\\x y -> 10*x + (ord y - ord '0')) 0 s\ncalc :: Int -> [Integer] -> Int -> [Integer]\ncalc 0 (a:[]) car = [toInteger car + a]\ncalc n (a:as) car = if bi < 0\n then toInteger(mod (-bi) 2):calc (n-1) as (-(div (-bi) 2) - mod (-bi) 2)\n else toInteger(mod bi 2):calc (n-1) as (div bi 2)\n where bi = car + fromInteger a\ncalc2 :: Int -> Integer -> [Integer] -> [Integer] -> [Integer] -> Int\ncalc2 0 k (a:[]) (b:[]) (s:[]) = if abs (s - a) <= k && a /= s then 1 else 0\ncalc2 n k (a:as) (b:bs) (s:ss) | b /= 0 && abs (s - a) <= k = 1\n | b /= 0 = 0\n | abs (s - a) <= k = 1 + calc2 (n-1) k as bs ss\n | otherwise = calc2 (n-1) k as bs ss"}, {"source_code": "large=123456789123456789\nmain=interact$show.f1.map read.tail.words\nf1 (a:b)=f3 a 0 b $(reverse.f2 a 0.reverse) b\nf2 a b [c]=[]\nf2 a b (c:d)=if abs e>a then large:f2 a large d else e:f2 a e d where e=b*2+c\nf3 a b [c] _=if abs b<=a && b/=0 then 1 else 0\nf3 a b (c:d) (e:f)=if e/=large && abs (e*2+b)<=a then 1+g else g where g=f4 a (b+c) d f\nf4 a b c d=if odd b then 0 else f3 a (div b 2) c d\n"}], "negative_code": [], "src_uid": "f8f0d00f8d93b5a4bbf0b2eedf1e754a"} {"source_code": "{-# LANGUAGE Safe #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Control.Applicative\nimport Control.Arrow\nimport Data.List\nimport Data.Array\nimport Data.Array.IO.Safe\nimport Data.Array.ST.Safe\nimport Data.IORef\nimport Data.STRef\nimport Data.Maybe\nimport Data.Bits\nimport Data.Ord\nimport Data.Ratio\nimport Data.Int\nimport Data.Char\nimport qualified Data.IntMap as IM\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.Set as Set\nimport qualified Data.Sequence as Sq\nimport Data.Tuple\nimport Data.Function\nimport Text.Printf\nimport Numeric\n\nreadIntBS = fst . fromJust . BS.readInt\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n [len,v,l,r] <- map read . words <$> getLine :: IO [Int]\n print $ len`div`v - r`div`v + (l-1)`div`v\n", "positive_code": [{"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\n\nsolve1 :: (Int, Int, Int, Int) -> Int\nsolve1 (d, v, l, r) = max 0 (lt - ls + 1) + max 0 (rt - rs + 1)\n where\n ls = 1\n lt = (l - 1) `div` v\n rs = (r + 1 + v - 1) `div` v\n rt = d `div` v\n\nmain :: IO ()\nmain = do\n n <- readLn\n dvlrs <- replicateM n $ do\n [d, v, l, r] <- unfoldr (B.readInt . B.dropWhile (== ' ')) <$> B.getLine\n return (d, v, l, r)\n mapM_ (print . solve1) dvlrs"}], "negative_code": [], "src_uid": "5194846a503c2087fcd299eaf3c20b2b"} {"source_code": "import Control.Monad\nimport Data.Maybe\nimport Data.Int\nimport Data.List\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.Map.Strict as M\nimport Data.ByteString.Builder\nimport System.IO\n\nparseInt :: (Integral a) => C.ByteString -> a\nparseInt = fromIntegral . fst . fromJust . C.readInteger\n\ngetInts :: (Integral a) => IO [a]\ngetInts = map parseInt . C.words <$> C.getLine\n\nupdate :: Num a => a -> Maybe a -> Maybe a\nupdate delta value = case value of\n Nothing -> Just delta\n Just x -> Just (x + delta)\n\nmain :: IO ()\nmain = do\n [numCase] <- getInts\n output <- fmap mconcat $ replicateM numCase $ do\n [n, h] <- getInts :: IO [Int64]\n as <- getInts :: IO [Int64]\n let m1 = foldl' (\\mp x -> M.alter (update 1) x mp) M.empty $ zipWith (-) (tail as) as\n m2 = snd $ M.mapAccumWithKey (\\(c, t) x y -> let p = (c + y, t + x * y) in (p, p)) (0, 0) m1\n check x = case M.lookupLE x m2 of\n Nothing -> n * x >= h\n Just (_, (c, t)) -> (n - c) * x + t >= h\n func l r\n | l == r = l\n | check m = func l m\n | otherwise = func (m + 1) r\n where m = (l + r) `div` 2\n return $ int64Dec (func 1 h) <> charUtf8 '\\n'\n hPutBuilder stdout output\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\n--import Data.Array.Unboxed\nimport Data.Int -- don't be an idiot who gets hacked because of Int32\n\n\nbinSearch :: (Int64 -> Bool) -> Int64 -> Int64 -> Int64\n{-# INLINE binSearch #-}\nbinSearch p = let\n go li ri = if li == ri\n then li\n else let\n mi = li + quot (ri - li) 2\n in if p mi\n then go li mi\n else go (mi + 1) ri\n in go\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n] <- getInts 1\n ~[h] <- getInt64s 1\n a <- getInt64s n\n let\n score k = (\\step -> foldl' step k $ zipWith (-) (tail a) a) $ \\acc sz ->\n acc + min k sz\n ans = binSearch (\\k -> score k >= h) 0 h\n pure $ putInt64s [ans]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\ngetInt64s :: Int -> SP [Int64]\ngetInt64s k = map (fromIntegral . fst . fromJust . P.readInteger) <$> getNext k\n\nputInt64s :: [Int64] -> Builder\nputInt64s vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.int64Dec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> int64Dec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport Data.ByteString.Builder\nimport qualified Data.ByteString.Builder.Prim as Prim\nimport System.IO\nimport Control.Monad.Trans.State\nimport Data.Maybe\n\n--import Data.ByteString.Builder.Extra (flush) -- for interactive problems\nimport Control.Monad\nimport Data.List\n--import Data.Array.Unboxed\n\n\nbinSearch :: (Int -> Bool) -> Int -> Int -> Int\n{-# INLINE binSearch #-}\nbinSearch p = let\n go li ri = if li == ri\n then li\n else let\n mi = li + quot (ri - li) 2\n in if p mi\n then go li mi\n else go (mi + 1) ri\n in go\n\nmainFun :: SP Builder\nmainFun = do\n ~[t] <- getInts 1\n fmap mconcat $ replicateM t $ do\n ~[n, h] <- getInts 2\n a <- getInts n\n let\n score k = (\\step -> foldl' step k $ zipWith (-) (tail a) a) $ \\acc sz ->\n acc + min k sz\n ans = binSearch (\\k -> score k >= h) 0 h\n pure $ putInts [ans]\n\n\ntype SP = State [P.ByteString]\n\ngetNext :: Int -> SP [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Int -> SP [Int]\ngetInts k = map (fst . fromJust . P.readInt) <$> getNext k\n\nputInts :: [Int] -> Builder\nputInts vs = let\n sepPrim = (,) ' ' Prim.>$<\n Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec\n in case vs of\n [] -> char7 '\\n'\n x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\\n'\n\nmain :: IO ()\nmain = do\n hSetBuffering stdout NoBuffering\n inp <- P.getContents\n let outp = evalState mainFun $ P.words inp\n P.putStr $ toLazyByteString outp\n"}], "negative_code": [], "src_uid": "3d0685162fbb432c37bb6aeb5fe51f94"} {"source_code": "import Data.Array\nimport Control.Monad (replicateM_, replicateM)\n\nmain :: IO ()\nmain = read <$> getLine >>= flip replicateM_ singleCase\n\nsingleCase :: IO ()\nsingleCase = map read . words <$> getLine >>=\n \\([n, m]) -> replicateM n (map read . words <$> getLine) >>=\n print . maxSum . listArray ((1, 1), (n, m)) . concat\n\ndiagSum :: Int -> Array (Int, Int) Int -> Bool -> Int\ndiagSum dd a b = let ((1,1), (n, m)) = bounds a\n bf True i = dd+i\n bf False i = dd-i\n -- par True = [(1-n) .. (m-1)]\n -- par False = [2 .. (n+m)]\n in\n sum . map (a!) . filter (inRange (bounds a)) $\n [(i, bf b i) | i <- [1..n]]\n\nmaxSum :: Array (Int, Int) Int -> Int\nmaxSum a = let ((1, 1), (n, m)) = bounds a\n pd = array (1-n, m-1) [(k, diagSum k a True) | k <- [(1-n)..(m-1)]]\n nd = array (2, n+m) [(k, diagSum k a False) | k <- [2..(n+m)]]\n f acc (i, j) = max acc ((pd!(j-i))+(nd!(j+i))-(a!(i, j)))\n in\n foldl f 0 $ range (bounds a)\n", "positive_code": [{"source_code": "readArr :: Int -> IO [[Int]]\r\nreadArr 0 = pure []\r\nreadArr i = do\r\n arr <- map (\\s -> read s :: Int) <$> (words <$> getLine)\r\n ans <- readArr $ i - 1\r\n pure (arr: ans)\r\n\r\nmergeL :: [Int] -> [Int] -> [Int]\r\nmergeL a [] = a\r\nmergeL (x: xs) (y: ys) = (x + y: mergeL xs ys)\r\n\r\nmergeR :: [Int] -> [Int] -> [Int]\r\nmergeR [] a = a\r\nmergeR (x: xs) (y: ys) = (x + y: mergeR xs ys)\r\n\r\ncalcLD :: [[Int]] -> [Int]\r\ncalcLD (x: []) = x\r\ncalcLD (x: xs) = reverse $ mergeR (reverse x) (0: (reverse $ calcLD xs))\r\n\r\ncalcRD :: [[Int]] -> [Int]\r\ncalcRD (x: []) = x\r\ncalcRD (x: xs) = mergeR x (0: calcRD xs)\r\n\r\ncalcH :: Int -> [Int] -> [Int] -> Int -> Int -> [Int] -> Int\r\ncalcH _ _ _ _ _ [] = 0\r\ncalcH n ld rd i j (x: xs) = max (rd !! (i + j) + ld !! (j - i + n - 1) - x) (calcH n ld rd i (j + 1) xs)\r\n\r\ncalc :: Int -> [Int] -> [Int] -> Int -> [[Int]] -> Int\r\ncalc _ _ _ _ [] = 0\r\ncalc n ld rd i (x: xs) = max (calcH n ld rd i 0 x) (calc n ld rd (i + 1) xs)\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: m: _) <- map (\\s -> read s :: Int) <$> (words <$> getLine)\r\n arr <- readArr n\r\n print $ calc n (calcLD arr) (calcRD arr) 0 arr\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n for t"}], "negative_code": [], "src_uid": "1b0c53ec666cdfea31a74f73d6ff70f2"} {"source_code": "main :: IO ()\nmain = getContents >>= printSolution . solve . map (map read . words) . tail . lines\n\nsolve :: [[Int]] -> [Int]\nsolve = map fst . filter (not . any (`elem` [1, 3]) . snd) . zip [1..]\n\nprintSolution :: Show a => [a] -> IO ()\nprintSolution xs = print (length xs) >> putStrLn (unwords (map show xs))\n", "positive_code": [{"source_code": "import Control.Monad\nimport Data.List\n\nmain = do\n n <- fmap read getLine\n xs <- forM [1..n] (\\i -> do\n ys <- fmap (map read . words) getLine\n if 1 `elem` ys || 3 `elem` ys then return []\n else return [i]\n )\n let cxs = concat xs\n print $ length cxs\n putStrLn . intercalate \" \" . map show $ cxs\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsplit key str = split_helper str [] where\n split_helper [] acc = if null acc then [] else [reverse acc]\n\n split_helper str acc =\n let\n c = head str\n in\n if head str == key then\n if null acc then\n split_helper (tail str) []\n else\n reverse acc : split_helper (tail str) []\n else\n split_helper (tail str) (c : acc)\n\nsolve n m i =\n if i > n then\n []\n else let\n rest = solve n (tail m) (i+1)\n good x = x < 0 || even x\n in\n if all (good . read) $ split ' ' (head m) then\n i : rest\n else\n rest\n\nmain = do\n n <- readLn\n m <- sequence $ take n $ repeat getLine\n let result = solve n m 1\n print $ length result\n when (length result > 0) $\n putStrLn $ concat $ intersperse \" \" $ map show result"}, {"source_code": "import Control.Applicative\nimport Data.List\n\n\n\n \n\nmain= do\n\tn<- read <$>getLine::IO Int \n\ts<- map (map read). map words. lines <$> getContents ::IO [[Int]]\n\tlet t= map (length . take 1. filter (\\z-> elem z [1,3])) s\n\tlet t1= map snd $ filter (\\z-> fst z==0) $ zip t [1..] \n\tprint $ length t1\n\tputStrLn $ intercalate \" \" $ map show t1"}, {"source_code": "import Data.Array.Unboxed\nimport qualified Data.Set as Set\nimport Data.List\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\tcars <- getLine\n\n\tlet\n\t\tn = read cars :: Int\n\n\trows_list <- getLines n\n\n\tlet\n\t\trows = map read $ concat $ map words $ rows_list :: [Int]\n\t\tmatrix = listArray ((1, 1), (n, n)) rows :: UArray (Int, Int) Int\n\t\tgood_cars = findGoodCars matrix n\n\n\tputStrLn $ show $ length good_cars\n\tputStrLn $ intercalate \" \" $ map show good_cars\n\nfindGoodCars :: UArray (Int, Int) Int -> Int -> [Int]\nfindGoodCars matrix n = [1..n] \\\\ (Set.elems $ findBadCars matrix 1 Set.empty)\n\twhere\n\t\tfindBadCars :: UArray (Int, Int) Int -> Int -> Set.Set Int -> Set.Set Int\n\t\tfindBadCars matrix row set\n\t\t\t| row > n = set\n\t\t\t| otherwise = findBadCars matrix (row+1) bad\n\t\t\twhere\n\t\t\t\tbad = inspectCollisions matrix row 1 set\n\t\t\t\tinspectCollisions :: UArray(Int, Int) Int -> Int -> Int -> Set.Set Int -> Set.Set Int\n\t\t\t\tinspectCollisions matrix row col set\n\t\t\t\t\t| col > n = set\n\t\t\t\t\t| collision == 1 = inspectCollisions matrix row (col+1) (Set.insert row set)\n\t\t\t\t\t| collision == 2 = inspectCollisions matrix row (col+1) (Set.insert col set)\n\t\t\t\t\t| collision == 3 = inspectCollisions matrix row (col+1) (Set.insert row $ Set.insert col set)\n\t\t\t\t\t| otherwise = inspectCollisions matrix row (col + 1) set\n\t\t\t\t\twhere\n\t\t\t\t\t\tcollision = matrix!(row,col)"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n rs <- replicateM n getInts\n\n let is = map snd $ filter (all (`elem` [0, -1, 2]) . fst) $ zip rs [1..]\n\n print $ length is\n putStrLn $ unwords $ map show is\n"}, {"source_code": "import Data.List (intercalate)\nanswer::[[Int]] -> [Int]\nanswer a = toNumberList $ map (all (\\x -> (x == -1 || x == 0 || x == 2))) a\ntoNumberList::[Bool] -> [Int]\ntoNumberList [] = []\ntoNumberList b = map fst $ filter (\\x -> snd x) $ zip [1..] b \nreadInput::Int -> IO [[Int]]\nreadInput 0 = return []\nreadInput n = do\n w <- getLine\n let a = [read n::Int|n <- (words w)]\n next <- readInput (n-1)\n return ([a] ++ next)\nprintAnswer::[Int] -> IO ()\nprintAnswer [] = print 0\nprintAnswer x = do\n print (length x)\n putStrLn $ intercalate \" \" $ map show $ x\nmain = do\n w <- getLine\n let n = read w::Int\n m <- readInput n\n printAnswer $ answer m\n"}, {"source_code": "\nmodule Main where\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\ngetInt :: IO Int\ngetInt = fst . fromJust . C.readInt <$> C.getLine\n\ngetIntMat :: IO [[Int]]\ngetIntMat = map ((map (read::String->Int)) . words) . lines <$> getContents\n\nmain :: IO ()\nmain = do\n n <- getInt\n m <- getIntMat\n let gs = sol m\n print $ length gs\n putStrLn . unwords $ map show gs\n\nsol :: [[Int]] -> [Int]\nsol = map ((+1) . fst) . filter (\\(i,xs) -> all good xs) . zip [0..]\n where\n good x = x==(-1) || x`mod`2==0"}, {"source_code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Control.Monad\n\nmain = do\n n <- getLine >>= return.read\n m <- replicateM n getLine >>= return.(map good)\n let l = map snd $ filter fst $ zip m [1..n]\n putStrLn $ show $ length l\n putStrLn $ unwords $ map show l\n\ngood s = not $ any (\\x -> x==1||x==3) ((map read)$words s)"}], "negative_code": [{"source_code": "-- http://codeforces.com/problemset/problem/545/A\n\nimport Data.List\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\tcars <- getLine\n\n\tlet\n\t\tn = read cars :: Int\n\n\trows_list <- getLines n\n\n\tlet\n\t\tcollisions = map read $ concat $ map words $ rows_list :: [Int]\n\t\tcars = getCars n\n\t\tgood_cars = findGoodCars cars collisions\n\n\tputStrLn $ show $ length good_cars\n\tputStrLn $ intercalate \" \" $ map show good_cars\n\n-- (Car number, Good/Bad - True/False)\ntype Car = (Int, Bool)\n-- Initially all cars are good\ngetCars :: Int -> [Car]\ngetCars n = [(x, True) | x <- [1..n]]\n\nfindGoodCars :: [Car] -> [Int] -> [Int]\nfindGoodCars cars collisions =\n\tfoldr\n\t(\\(n, s) acc -> if s then n:acc else acc)\n\t[] $ findGoodCars' cars collisions 1\n\twhere\n\t\tn = length cars\n\t\tfindGoodCars' :: [Car] -> [Int] -> Int -> [Car]\n\t\tfindGoodCars' cars [] _ = cars\n\t\tfindGoodCars' cars (c:cs) index\n\t\t\t| c == 1 = findGoodCars' (markBadCar row cars) cs (index + 1)\n\t\t\t| c == 2 = findGoodCars' (markBadCar col cars) cs (index + 1)\n\t\t\t| c == 3 = findGoodCars' (markBadCar col $ markBadCar row cars) cs (index + 1)\n\t\t\t| otherwise = findGoodCars' cars cs (index+1)\n\t\t\twhere\n\t\t\t\trow = index `quot` n\n\t\t\t\tcol = ((index-1) `mod` n) + 1\n\t\t\t\tmarkBadCar :: Int -> [Car] -> [Car]\n\t\t\t\tmarkBadCar _ [] = []\n\t\t\t\tmarkBadCar i ((n,s):cs)\n\t\t\t\t\t| i == n = (n, False):cs\n\t\t\t\t\t| otherwise = (n, s):markBadCar (i) cs"}, {"source_code": "import Data.Array.Unboxed\nimport qualified Data.Set as Set\nimport Data.List\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\tcars <- getLine\n\n\tlet\n\t\tn = read cars :: Int\n\n\trows_list <- getLines n\n\n\tlet\n\t\trows = map read $ concat $ map words $ rows_list :: [Int]\n\t\tmatrix = listArray ((1, 1), (n, n)) rows :: UArray (Int, Int) Int\n\t\tgood_cars = findGoodCars matrix n\n\n\tputStrLn $ show $ length good_cars\n\tputStrLn $ intercalate \" \" $ map show good_cars\n\nfindGoodCars :: UArray (Int, Int) Int -> Int -> [Int]\nfindGoodCars matrix n = [1..n] \\\\ (Set.elems $ findBadCars matrix 1 Set.empty)\n\twhere\n\t\tfindBadCars :: UArray (Int, Int) Int -> Int -> Set.Set Int -> Set.Set Int\n\t\tfindBadCars matrix row set\n\t\t\t| row > n = set\n\t\t\t| n `Set.member` set = findBadCars matrix (row+1) set\n\t\t\t| otherwise = findBadCars matrix (row+1) bad\n\t\t\twhere\n\t\t\t\tbad = inspectCollisions matrix row 1 set\n\t\t\t\tinspectCollisions :: UArray(Int, Int) Int -> Int -> Int -> Set.Set Int -> Set.Set Int\n\t\t\t\tinspectCollisions matrix r col set\n\t\t\t\t\t| col > n = set\n\t\t\t\t\t| collision == 1 = inspectCollisions matrix r (col+1) (Set.insert r set)\n\t\t\t\t\t| collision == 2 = inspectCollisions matrix r (col+1) (Set.insert col set)\n\t\t\t\t\t| collision == 3 = inspectCollisions matrix r (col+1) (Set.insert r $ Set.insert col set)\n\t\t\t\t\t| otherwise = inspectCollisions matrix r (col + 1) set\n\t\t\t\t\twhere\n\t\t\t\t\t\tcollision = matrix!(r,col)"}, {"source_code": "-- http://codeforces.com/problemset/problem/545/A\n\nimport Data.List\n\ngetLines :: Int -> IO [String]\ngetLines 0 = return []\ngetLines n = do\n\tx <- getLine\n\txs <- getLines (n-1)\n\treturn (x:xs)\n\nmain = do\n\tcars <- getLine\n\n\tlet\n\t\tn = read cars :: Int\n\n\trows_list <- getLines n\n\n\tlet\n\t\tcollisions = map read $ concat $ map words $ rows_list :: [Int]\n\t\tcars = getCars n\n\t\tgood_cars = findGoodCars cars collisions\n\n\tputStrLn $ show $ length good_cars\n\tputStrLn $ intercalate \" \" $ map show good_cars\n\n-- (Car number, Good/Bad - True/False)\ntype Car = (Int, Bool)\n-- Initially all cars are good\ngetCars :: Int -> [Car]\ngetCars n = [(x, True) | x <- [1..n]]\n\nfindGoodCars :: [Car] -> [Int] -> [Int]\nfindGoodCars cars collisions =\n\tfoldr\n\t(\\(n, s) acc -> if s then n:acc else acc)\n\t[] $ findGoodCars' cars collisions 0\n\twhere\n\t\tn = length cars\n\t\tfindGoodCars' :: [Car] -> [Int] -> Int -> [Car]\n\t\tfindGoodCars' cars [] _ = cars\n\t\tfindGoodCars' cars (c:cs) index\n\t\t\t| c == 1 = findGoodCars' (markBadCar row cars) cs (index + 1)\n\t\t\t| c == 2 = findGoodCars' (markBadCar col cars) cs (index + 1)\n\t\t\t| c == 3 = findGoodCars' (markBadCar col $ markBadCar row cars) cs (index + 1)\n\t\t\t| otherwise = findGoodCars' cars cs (index+1)\n\t\t\twhere\n\t\t\t\trow = index `quot` n\n\t\t\t\tcol = (index `mod` n) + 1\nmarkBadCar :: Int -> [Car] -> [Car]\nmarkBadCar _ [] = []\nmarkBadCar i ((n,s):cs)\n\t| i == n = (n, False):cs\n\t| otherwise = (n, s):markBadCar (i) cs"}, {"source_code": "\nmodule Main where\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as C\nimport Data.List\nimport Data.Maybe\n\ngetInt :: IO Int\ngetInt = fst . fromJust . C.readInt <$> C.getLine\n\ngetIntMat :: IO [[Int]]\ngetIntMat = map ((map (read::String->Int)) . words) . lines <$> getContents\n\nmain :: IO ()\nmain = do\n n <- getInt\n m <- getIntMat\n putStrLn . unwords . map show $ sol m\n\nsol :: [[Int]] -> [Int]\nsol = map ((+1) . fst) . filter (\\(i,xs) -> all (f i) $ zip [0..] xs) . zip [0..]\n where\n f j (k,x) = j==k || x`mod`2==0\n"}], "src_uid": "3fc0ac711b113fa98f41740536dad44f"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad (replicateM, guard)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Maybe (fromJust)\nimport Data.List (elemIndex)\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ntype InputTy = [Int]\ntype OutputTy = Maybe [Int]\n\ninput :: Scanner InputTy\ninput = numberOf int\n\nsolve :: InputTy -> OutputTy\nsolve [_] = Just []\nsolve as = do\n i <- elemIndex n as\n guard $ even i\n as <- rev (i + 1) as\n j <- elemIndex (n - 1) as\n guard $ odd j\n as <- rev j as\n as <- rev (j + 2) as\n as <- rev 3 as\n let as' = reverse (drop 2 as)\n ([i + 1, j, j + 2, 3, n] ++) <$> solve as'\n where\n n = length as\n rev k as = let (ls, rs) = splitAt k as in Just $ reverse ls ++ rs\n\noutput :: OutputTy -> C.ByteString\noutput Nothing = C.pack \"-1\"\noutput (Just xs) = C.pack $ show (length xs) ++ \"\\n\" ++ unwords (map show xs)\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport Data.ByteString.Builder.Prim\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.Semigroup\n\nimport Data.List\n\n\nrev :: Int -> State [Int] ()\nrev k = do\n ~(sp, ss) <- splitAt k <$> get\n put (reverse sp ++ ss)\n\nsolve :: Int -> State [Int] [Int]\nsolve 1 = pure []\nsolve n = do\n ~(Just npos) <- elemIndex n <$> get\n rev (npos + 1)\n ~(Just ppos) <- elemIndex (n-1) <$> get\n rev ppos\n rev (ppos + 2)\n rev 3\n rev n\n (\\res -> npos + 1 : ppos : ppos + 2 : 3 : n : res) <$> solve (n-2)\n\nmain :: IO ()\nmain = (P.words <$> P.getContents >>=) $ evalStateT $ do\n [t] <- getInts 1\n replicateM_ t $ do\n [n] <- getInts 1\n a <- getInts n\n let\n isOK = all even $ zipWith (-) a [1..]\n ans = filter (> 1) $ evalState (solve n) a\n if isOK\n then putInts [length ans] >> putInts ans\n else putInts [0-1]\n\ntype SP = StateT [P.ByteString]\ntype SIO = SP IO\n\ngetNext :: Monad m => Int -> SP m [P.ByteString]\ngetNext = state . splitAt\n\ngetInts :: Monad m => Int -> SP m [Int]\ngetInts k = do\n vs <- getNext k\n pure [v | Just (v, _) <- map P.readInt vs]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n spacePrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec\n in lift $ B.hPutBuilder stdout $ case li of\n [] -> B.char7 '\\n'\n x : xs -> B.intDec x <> primMapListBounded spacePrim xs <> B.char7 '\\n'\n"}], "negative_code": [], "src_uid": "fa0fc36acf5a638917be7a2769cbfd80"} {"source_code": "import Data.Char (isSpace)\n\ninsertArrows :: String -> String\ninsertArrows \"\" = \"\"\ninsertArrows (x : xs) = x : concatMap ((\"->\" ++) . pure) xs\n\narrowsAfterEach :: String -> String\narrowsAfterEach = concatMap (: \"->\")\n\nsolve :: String -> String\nsolve inp = case reverse inp of\n [] -> error \"expected input\"\n '1' : _ -> \"NO\\n\"\n '0' : [] -> \"YES\\n0\\n\"\n '0' : '1' : _ -> \"YES\\n\" ++ insertArrows inp ++ \"\\n\"\n '0' : '0' : xs\n -> case span (== '1') xs of\n (_, []) -> \"NO\\n\"\n (ones, '0' : ys) ->\n \"YES\\n\"\n ++ arrowsAfterEach (reverse ys)\n ++ \"(0->(\"\n ++ arrowsAfterEach ones\n ++ \"0))->0\\n\"\n _ -> error \"expected 0 or 1\"\n _ -> error \"expected 0 or 1\"\n\nmain :: IO ()\nmain = interact (solve . filter (not . isSpace) . dropWhile (/= '\\n'))\n", "positive_code": [{"source_code": "main :: IO()\nmain = solve . (map read . words) =< IO()\nsolve (_:a) =\n let \n zeroNum = length $ filter (==0) a\n ra = reverse a\n na = reverse $ tail ra\n r1 = head ra\n r2 = head $ tail ra\n invalid = (r1 == 1) || (zeroNum == 2 && r2 == 0)\n in \n if invalid then \n putStrLn \"NO\"\n else\n if (null na) then \n putStrLn \"YES\\n0\" \n else do putStr \"YES\\n(\"\n firstZero na True\n putStrLn \"->0)\"\n where\n firstZero :: [Int] -> Bool -> IO()\n firstZero [] _ = putStr \")\"\n firstZero (a:ax) True | a == 0 = do putStr \"(0->(\"\n incLast ax\n putStr \"))\"\n | a == 1 = do putStr \"(1\" \n firstZero ax False\n firstZero (a:ax) False | a == 0 = do putStr \"->(0->(\"\n incLast ax\n putStr \")))\"\n | a == 1 = do putStr \"->1\"\n firstZero ax False\n \n incLast :: [Int] -> IO()\n incLast (a:ax) | null ax = putStr $ show a\n | otherwise = do putStr $ show a\n putStr \"->\"\n incLast ax\n"}, {"source_code": "import Control.Applicative ((<$>))\nimport Control.Monad (mapM_, (>>=))\n\n\nsolve :: String -> [String]\nsolve a\n | last a /= '0' = [\"NO\"]\n | a == \"0\" = [\"YES\", \"0\"]\n | dropWhile (/= '0') a == \"00\" = [\"NO\"]\n | take 2 (reverse a) == \"01\" = [\"YES\", loop a]\n | head a == '0' = [\"YES\", \"0->(\" ++ (loop . init . tail $ a) ++ \")->0\"]\n | otherwise = [\"YES\", loop a' ++ \"->(0->(\" ++ loop a'' ++ \"))->0\"]\n where\n a' = takeWhile (/= '0') a\n a'' = init . tail . dropWhile (/= '0') $ a\n loop :: String -> String\n loop \"1\" = \"1\"\n loop \"0\" = \"0\"\n loop (i:rest) = i:\"->\" ++ loop rest\n\nmain :: IO ()\nmain = getLine >>= \\_ -> solve . filter (/= ' ') <$> getLine >>= mapM_ putStrLn\n"}], "negative_code": [{"source_code": "import Data.Char (isSpace)\n\ninsertArrows :: String -> String\ninsertArrows \"\" = \"\"\ninsertArrows (x : xs) = x : concatMap ((\"->\" ++) . pure) xs\n\narrowsAfterEach :: String -> String\narrowsAfterEach = concatMap (: \"->\")\n\nsolve :: String -> String\nsolve inp = case reverse inp of\n [] -> error \"expected input\"\n '1' : _ -> \"NO\\n\"\n '0' : [] -> \"YES\\n0\\n\"\n '0' : '1' : _ -> \"YES\\n\" ++ insertArrows inp ++ \"\\n\"\n '0' : '0' : xs\n -> case span (== '1') xs of\n (_, []) -> \"NO\\n\"\n (ones, '0' : ys) ->\n \"YES\\n\"\n ++ arrowsAfterEach ys\n ++ \"(0->(\"\n ++ arrowsAfterEach ones\n ++ \"0))->0\\n\"\n _ -> error \"expected 0 or 1\"\n _ -> error \"expected 0 or 1\"\n\nmain :: IO ()\nmain = interact (solve . filter (not . isSpace) . dropWhile (/= '\\n'))\n"}], "src_uid": "98380bd9d6865fa9a2d100ca3484b005"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n\nimport Control.Monad\n\nmain = do\n n <- read <$> getLine\n replicateM_ n $ do\n map read . words <$> getLine >>= \\case\n [n, d] ->\n if minDays d <= n\n then putStrLn \"YES\"\n else putStrLn \"NO\"\n _ -> undefined\n\nminDays d = minimum [i + ceiling (fromInteger d / fromInteger (i + 1)) | i <- [(guess-1)..(guess+2)]]\n where\n guess = floor $ sqrt (fromInteger d) - 1\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\na ! b = (a - 1) `div` b + 1\n\nworks n d = let x = floor $ sqrt $ fromIntegral d in any (<= n) $ (\\a -> a + d ! (a + 1)) <$> [max (x - 10) 0..x + 10]\n\nmain = getLine >>= test.read\n\ntest 0 = return ()\ntest n = do\n (a:b:_) <- map read.words <$> getLine\n output $ works a b\n test $ pred n\n\noutput True = putStrLn \"YES\"\noutput _ = putStrLn \"NO\"\n"}, {"source_code": "f :: Integer -> Integer -> Integer\nf d x = x + ceiling( fromIntegral(d) / fromIntegral(x+1) )\n\nsolveTask :: (Integer, Integer) -> String\nsolveTask (n, d)\n | d <= n = \"YES\\n\"\n | otherwise =\n let x = sqrt (fromIntegral d) - 1\n x0 = floor x\n x1 = ceiling x\n in if f d x0 <= n || f d x1 <=n\n then \"YES\\n\" else \"NO\\n\"\n\ngroupTaskInput :: [String] -> [(Integer, Integer)]\ngroupTaskInput [] = []\ngroupTaskInput (n:(d:xs)) = (read n, read d) : groupTaskInput(xs)\n\nmakeTaskInput :: String -> [(Integer, Integer)]\nmakeTaskInput s = groupTaskInput $ tail $ words $ s\n\nsolve :: String -> String\nsolve s = concat $ (map solveTask) $ makeTaskInput s\n\nmain' :: IO ()\nmain' = do interact $ solve\n\nmain = main'\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\ngetToken :: IO String\ngetToken = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n'\n then return [x]\n else liftM2 (\\x y -> x : y) (return x) getToken\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n t <- get :: IO Int\n replicateM_ t f1\n\nf1 :: IO ()\nf1 = do\n n <- get :: IO Int32\n d <- get :: IO Int32\n putStrLn (if f2 n d then \"YES\" else \"NO\")\n\nf2 :: Int32 -> Int32 -> Bool\nf2 n d = let x = bs 0 (fromIntegral d) (fromIntegral d) in\n (x + (div ((fromIntegral d) + x) (x + 1)) <= (fromIntegral n))\n\nbs :: Int64 -> Int64 -> Int64 -> Int64\nbs min max d = let aux x = x < (div (d + x) (x + 1)) in\n if min + 1 >= max then\n min\n else\n let mid = div (min + max) 2 in\n if aux mid then\n bs mid max d\n else\n bs min mid d\n "}, {"source_code": "import System.IO\n-- import Prelude\n\n\nreadInt :: IO Int\nreadInt = readLn\n\nreadTuple :: IO (Int, Int)\nreadTuple = readLn\n\ncastToInt x = read x::Int\n\n\nmain = do\n t <- readInt\n mainLoop t\n\n\nmainLoop t = do\n if t == 0 then\n return ()\n else do\n line <- getLine\n let test_case = (map castToInt . take 2 . words) line\n\n solveTask test_case\n\n mainLoop (t - 1)\n\n\nsolveTask test_case = do\n let (n, d) = (head test_case, (head . tail) test_case)\n let x = sqrt (fromIntegral d) - 1\n\n let lower_x = floor x\n let upper_x = ceiling x\n\n let xs = [lower_x, upper_x]\n let ys = map (getActualDays d) xs\n let max_days = maximum ys\n\n if max_days <= n then putStrLn \"YES\"\n else putStrLn \"NO\"\n\n\ngetActualDays :: Int -> Int -> Int\ngetActualDays d x = x + ceiling (fromIntegral d / (fromIntegral x + 1))\n\n"}, {"source_code": "{-# LANGUAGE Strict #-}\n\nimport Control.Monad\nimport Data.Ratio\n\nsolve n d i\n | i >= n = \"NO\"\n | total > n = solve n d (i+1)\n | otherwise = \"YES\"\n where\n total = i + run \n run = ceiling $ d % (i+1)\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t $ do\n [n,d] <- map read . words <$> getLine :: IO [Int]\n putStrLn $ solve n d 0 \n \n \n"}], "negative_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\n\na ! b = (a - 1) `div` b + 1\n\nworks n d = let x = floor $ sqrt $ fromIntegral d in any (<= n) $ (\\a -> a + d ! (a + 1)) <$> [max (x - 10) 0..x + 10]\n\nmain = getLine >>= test.read\n\ntest 0 = return ()\ntest n = do\n (a:b:_) <- map read.words <$> getLine\n output $ works a b\n test $ pred n\n\noutput True = print \"YES\"\noutput _ = print \"NO\"\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\ngetToken :: IO String\ngetToken = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n'\n then return [x]\n else liftM2 (\\x y -> x : y) (return x) getToken\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n n <- get :: IO Int64\n m <- get :: IO Int64\n a <- get :: IO Int64\n putln $ f1 n m a\n\nf1 :: Int64 -> Int64 -> Int64 -> Int64\nf1 n m a = ((div (n + a - 1) a) * (div (m + a - 1) a))\n"}, {"source_code": "import Control.Monad\nimport Data.Int\n\ngetToken :: IO String\ngetToken = do\n x <- getChar\n if x == ' ' || x == '\\t' || x == '\\n'\n then return [x]\n else liftM2 (\\x y -> x : y) (return x) getToken\n\nget :: Read a => IO a\nget = liftM read getToken\n\nput :: Show a => a -> IO ()\nput = putStr . show\n\nputln :: Show a => a -> IO ()\nputln = putStrLn . show\n\nmain :: IO ()\nmain = do\n t <- get :: IO Int\n replicateM_ t f1\n\nf1 :: IO ()\nf1 = do\n n <- get :: IO Int32\n d <- get :: IO Int32\n putln (if f2 n d then \"YES\" else \"NO\")\n\nf2 :: Int32 -> Int32 -> Bool\nf2 n d = let x = bs 0 (fromIntegral d) (fromIntegral d) in\n (x + (div ((fromIntegral d) + x) (x + 1)) <= (fromIntegral n))\n\nbs :: Int64 -> Int64 -> Int64 -> Int64\nbs min max d = let aux x = x < (div (d + x) (x + 1)) in\n if min + 1 >= max then\n min\n else\n let mid = div (min + max) 2 in\n if aux mid then\n bs mid max d\n else\n bs min mid d\n "}], "src_uid": "e65b2a81689bb13b90a02a9ccf1d4125"} {"source_code": "import Control.Applicative( (<$>))\nimport Data.Bool( bool)\nimport Control.Monad( replicateM)\nmain = do\n [vic1_, vic2_] <- words <$> getLine\n n <- readLn::IO Int\n changes_ <- replicateM n (words <$> getLine)\n let\n\tproc [vic1, vic2]\t[]\t = [vic1++\" \"++vic2]\n\tproc [vic1, vic2] ([from,to]:rem) = let\n\t\t\t l = vic1++\" \"++vic2\n\t\t\t candi1 = [to,vic2]\n\t\t\t candi2 = [vic1,to]\n\t\t\t next = bool candi2 candi1 (vic1==from)\n\t\t\tin\n\t\t\t l:(proc next rem)\n mapM_ putStrLn $ proc [vic1_, vic2_] changes_\n \n", "positive_code": [{"source_code": "f::String->String->[String]->[String]\nf _ _ []=[]\nf a b (s:str)=let (c:d:[])=words s\n in if c==a then (d++\" \"++b):(f d b str) else (a++\" \"++d):(f a d str)\n\nmain = do\n e<-getLine\n e2<-getLine\n e3<-getContents\n let (a:b:[])=words e\n mapM_ putStrLn $ (a++\" \"++b) :f a b (lines e3)"}, {"source_code": "f (a, b) (c, d) = if a == c then (b, d) else (a, d) \n\ng s = (l !! 0, l !! 1)\n where l = words s\n\ng' t = (fst t) ++ \" \" ++ (snd t)\n\nmain = do\n initialNames <- getLine\n nS <- getLine\n let n = read nS :: Int\n restOfTheNames <- sequence (take n (repeat getLine))\n let result = unlines (map g' (scanl f (g initialNames) (map g restOfTheNames)))\n putStrLn result\n"}], "negative_code": [], "src_uid": "3c06e3cb2d8468e738b736a9bf88b4ca"} {"source_code": "-- Codeforces Round #531 (C), Contest 1102, Problem set ?.\n\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE Safe #-}\n{-# LANGUAGE TupleSections#-}\n{-# LANGUAGE ExplicitForAll #-}\n\nimport Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as BS\nimport qualified Data.ByteString.Lazy.Char8 as BSL\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IM\nimport qualified Data.Array.IArray as A\nimport qualified Data.Array.MArray.Safe as A\n-- import qualified Data.Array.MArray as A\nimport Data.Array (Array)\nimport Data.Array.Unboxed (UArray)\nimport Data.Array.IArray (IArray)\nimport Data.Array.MArray.Safe (MArray)\nimport Data.Array.IO.Safe (IOArray, IOUArray)\nimport Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)\n{-\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as VUM\n-}\nimport Control.Monad\nimport Control.Monad.ST.Safe\n-- import Control.Monad.ST\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Tuple\nimport Data.Ord\nimport Control.Monad.State.Strict\nimport Data.Int\nimport Data.Word\nimport Data.Function\n\nmain :: IO ()\nmain = do\n [n,x,y] <- map read . words <$> getLine :: IO [Int]\n as <- unfoldr (BS.readInt . BS.dropWhile(<'!')) <$> BS.getLine :: IO [Int]\n let breakableInOne = length $ filter (<= x) as\n print $ if x > y then n else (breakableInOne+1) `shiftR` 1\n\n", "positive_code": [{"source_code": "import Data.Function -- on\nimport Data.Functor -- <$>\nimport Data.List hiding (sortOn)\n\ntoList :: (Read a) => String -> [a]\ntoList = map read <$> words\n\nmain = do\n [n, x, y] <- toList <$> getLine :: IO [Int]\n as <- toList <$> getLine :: IO [Int]\n let ans = if x > y then n\n else (succ $ length $ filter (<= x) as) `div` 2\n print ans\n"}, {"source_code": "import Control.Monad\nreadInts = liftM (map read . words) getLine\nsolve [[n, x, y], s] = if x > y then n else (1 + length (filter (<=x) s)) `div` 2\nmain = replicateM 2 readInts >>= putStrLn . show . solve\n"}], "negative_code": [{"source_code": "import Control.Monad\nreadInts = liftM (map read . words) getLine\nsolve [[n, x, y], s] = if x > y then n else (1 + length (filter (>= putStrLn . show . solve"}, {"source_code": "import Control.Monad\nreadInts = liftM (map read . words) getLine\nsolve [n, x, y] s = if x > y then n else length $ takeWhile (< x) s\nmain = readInts >>= \\s -> readInts >>= putStrLn . show . solve s"}], "src_uid": "c173e2695562dfa1f603e6a925a2e1f3"} {"source_code": "main = interact $ rounded\n\nrounded :: String -> String\nrounded s =\n let (intPart,fracPart) = span (/= '.') s\n (leadDigits, lastDigit) = (init intPart, last intPart)\n roundUp = (fracPart !! 1) `elem` ['5'..'9']\n in if lastDigit == '9'\n then \"GOTO Vasilisa.\"\n else if roundUp then leadDigits ++ [succ lastDigit] else intPart\n\n", "positive_code": [{"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Bifunctor\n\nmain = do\n x <- getLine\n let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x\n let int = read :: String -> Integer\n putStrLn $ case bimap int int (y, [head $ tail z]) of\n (a,_) | a`mod`10 == 9 -> \"GOTO Vasilisa.\"\n (a,b) | b < 5 -> show a\n (a,b) -> show $ succ a\n"}, {"source_code": "import Char\n\nbigTest = take 1000 (repeat '0') ++ \".9\"\n\nmyRound :: String -> String\nmyRound line = myRound' \"\" line\n where\n myRound' prefix (a:'.':b:_)\n | a == '9' = \"GOTO Vasilisa.\"\n | b < '5' = prefix ++ [a]\n | otherwise = prefix ++ [intToDigit (digitToInt a + 1)]\n myRound' prefix (a:as) = myRound' (prefix ++ [a]) as\n myRound' _ _ = error \"Not found '.'\"\n\nmain = do\n line <- getLine\n putStrLn $ myRound line"}, {"source_code": "\nimport Data.List (delete)\nimport Data.Char (ord, chr)\n\n\nremove (x:xs) = xs\n\nsolve s = roundNumber $ span (/='.') s\n where roundNumber (x,y) | last x == '9' = \"GOTO Vasilisa.\"\n | (head $ remove y) >= '5' = init x ++ [chr . (+1) . ord $ last x]\n | otherwise = x\n\nmain = do number <- getLine\n putStrLn $ solve number"}, {"source_code": "\nimport Data.Char (ord, chr)\n\n\nremove (x:xs) = xs\n\nsolve s = roundNumber $ span (/='.') s\n where roundNumber (x,y) | last x == '9' = \"GOTO Vasilisa.\"\n | (head $ remove y) >= '5' = init x ++ [chr . (+1) . ord $ last x]\n | otherwise = x\n\nmain = do number <- getLine\n putStrLn $ solve number"}, {"source_code": "main = do\n n <- getLine\n putStrLn (round' n)\nround' n | last i == '9' = \"GOTO Vasilisa.\"\n | f!!1 < '5' = i\n | otherwise = show (read i + 1)\n where (i,f) = break (== '.') n"}, {"source_code": "s(a,b)|last a=='9'=\"GOTO Vasilisa.\"|b!!1>'4'=init a++[succ$last a]|1>0=a \nmain=interact$s.span(/='.')"}, {"source_code": "main = do d <- getLine\n let (d_int,(_:d_frac)) = span (/='.') d\n putStrLn $ if last d_int == '9' then\n \"GOTO Vasilisa.\"\n else if (read [head d_frac]::Int) < 5 then\n d_int\n else\n show ((read d_int::Integer)+1)"}, {"source_code": "s(a,b)|last a=='9'=\"GOTO Vasilisa.\"|b!!1>'4'=init a++[succ$last a]|1>0=a\nmain=interact$s.span(/='.')"}, {"source_code": "import Data.Maybe\nimport Data.List\n\nf str | str !! (inx - 1) == '9' = \"GOTO Vasilisa.\"\n | str !! (inx + 1) >= '5' = (take (inx - 1) str) ++ (show . (+) 1 . read $ [str !! (inx - 1)])\n | otherwise = take inx str\n where inx = fromJust . elemIndex '.'$ str\n\n\nmain = do\n str <- getLine\n putStrLn . f $ str \n"}, {"source_code": "module Main where\n\nimport Data.List\n\nmain = do\n inputLine <- getLine\n let (prefix, postfix) = span (/='.') inputLine\n\n let result = if last prefix == '9'\n then \"GOTO Vasilisa.\"\n else if postfix !! 1 >= '5'\n then show ( 1 + read prefix :: Integer )\n else prefix\n\n putStrLn result\n"}], "negative_code": [{"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Bifunctor\n\nmain = do\n x <- getLine\n let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x\n let int = read :: String -> Integer\n putStrLn $ case bimap int int (y, [head $ tail z]) of\n (a,_) | a`mod`10 == 9 -> \"GOTO Vasilasa.\"\n (a,b) | b < 5 -> show a\n (a,b) -> show $ succ a\n"}, {"source_code": "import Data.Maybe\nimport Data.List\nimport Data.Bifunctor\n\nmain = do\n x <- getLine\n let (y,z) = splitAt (fromJust $ findIndex (=='.') x) x\n let int = read :: String -> Integer\n putStrLn $ case bimap int int (y, [head $ tail z]) of\n (a,_) | a`mod`10 == 9 -> \"GOTO Vasilasa\"\n (a,b) | b < 5 -> show a\n (a,b) -> show $ succ a\n"}, {"source_code": "main = (readLn :: IO Double) >>= \\x -> putStrLn $ \n let (y,z) = (truncate x,x-fromIntegral y) in\n case (y,z) of\n (a,b) | a`mod`10 == 9 -> \"GOTO Vasilasa\"\n (a,b) | b < 0.5 -> show a\n _ -> show $ succ y\n\n"}, {"source_code": "main = interact $ rounded\n\nrounded :: String -> String\nrounded s =\n let (intPart,fracPart) = span (/= '.') s\n (leadDigits, lastDigit) = (init intPart, last intPart)\n roundUp = (fracPart !! 1) `elem` ['5'..'9']\n in if roundUp\n then if lastDigit == '9'\n then \"GOTO Vasilisa.\"\n else leadDigits ++ [succ lastDigit]\n else\n intPart\n\n"}, {"source_code": "main = do d <- getLine\n let (d_int,(_:d_frac)) = span (/='.') d\n putStrLn $ if last d_int == '9' then\n \"GOTO Vasilisa.\"\n else if (read [head d_frac]::Int) < 5 then\n d_int\n else\n show ((read d_int::Int)+1)"}, {"source_code": "s(a,b)|last a=='9'=\"GOTO Vasilisa.\"|b!!2>'4'=init a++[succ$last a]|1>0=a\nmain=interact$s.span(/='.')"}, {"source_code": "import Data.Maybe\nimport Data.List\n\nf str | str !! (inx - 1) == '9' = \"GOTO Vasilisa\"\n | str !! (inx + 1) >= '5' = (take (inx - 1) str) ++ (show . (+) 1 . read $ [str !! (inx - 1)])\n | otherwise = take inx str\n where inx = fromJust . elemIndex '.'$ str\n\n\nmain = do\n str <- getLine\n putStrLn . f $ str \n"}], "src_uid": "3060ecad253a2b4d4fac39e91fcd6c95"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\nimport Data.Bits as B\nimport System.IO as Io\n--import Data.Char as C\n--import Data.IntSet as S\n\nsolve :: IO ()\nsolve = do\n n <- readLn :: IO Int\n let q = takeWhile (solve x < n) [1,3..]\r\n r = if null xs then 1 else div (last xs) 2 + 2\r\n print r\r\n\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t printResult"}, {"source_code": "import Control.Monad ( replicateM_ )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n s <- readLn :: IO Int\r\n let go x y = if y >= s then 0 else 1 + go (x + 2) (y + x + 2)\r\n print $ go (-1) 0\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad.State\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Maybe (fromJust, fromMaybe)\r\n\r\nmain :: IO ()\r\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: Int -> Int\r\nsolve s = (1 +) . length . takeWhile (< s) $ scanl1 (+) [1, 3 ..]\r\n\r\n--- Template ---\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nstr :: Scanner C.ByteString\r\nstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> str\r\n\r\ninteger :: Scanner Integer\r\ninteger = read . C.unpack <$> str\r\n\r\ndouble :: Scanner Double\r\ndouble = read . C.unpack <$> str\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t then return [] else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n"}], "negative_code": [], "src_uid": "322792a11d3eb1df6b54e8f89c9a0490"} {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.ByteString (ByteString)\nimport Data.Char\nimport Data.Int\n\nreadInt :: IO Int\nreadInt = do line <- BS.getLine\n let Just (n,_) = BS.readInt line\n return n\n\nparseInts :: Int -> ByteString -> [Int]\nparseInts k bs | k <= 0 = []\nparseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of\n Nothing -> []\n Just (n,bs') -> n : parseInts (k-1) bs'\n\nmain = do\n n <- fmap read getLine\n s <- fmap (sum . map fromIntegral . parseInts n) BS.getLine :: IO Int64\n let n' = fromIntegral n\n answer = div (n'*(n'+1)) 2 - s\n print answer\n\n", "positive_code": [{"source_code": "main = do\n let i = fmap (map read . words) getLine :: IO [Integer]\n n <- fmap (!! 0) i\n a <- i\n print $ n * (n + 1) `div` 2 - sum a"}, {"source_code": "import Data.List\nimport Data.Function\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = sum [1..n] - sum xs\n"}, {"source_code": "import Data.List\nimport Data.Int\nimport Data.Function\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int64] -> Int64\ngetAns (n:xs) = n * (n + 1) `div` 2 - sum xs\n"}, {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\nimport Control.Applicative ((<$>))\nimport Control.Monad\nimport Text.Printf (printf)\nimport Data.Maybe (Maybe, fromMaybe)\nimport Data.List (sort, foldl')\nimport qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as BS\n\nsolve :: [Int] -> Int\nsolve s = fst . head . dropWhile (\\(x, y) -> x == y) . zip [1..] $ sort s\n\nmain :: IO ()\nmain = do\n n <- getInt\n a <- getInts\n print . solve $ a ++ [n+1]\n\ntoNumber = fst . fromMaybe (0, BS.pack \"\")\ngetInt = toNumber . BS.readInt <$> BS.getLine\ngetInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))\ncountup = foldl' (\\x y -> M.insertWith' (+) y 1 x) M.empty\ncountof m x = M.findWithDefault 0 x m"}, {"source_code": "import qualified Data.ByteString.Char8 as B\nimport Data.Maybe\nimport Data.List\n\nsolve i [] = i\nsolve i (a:as) = if i /= a then i else solve (i+1) as\n \nmain = print =<< solve 1 . sort <$> (map (fst . fromJust . B.readInt) . B.words <$> (getLine >> B.getLine))\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nmain :: IO ()\nmain = do\n\tn <- inputInteger\n\txs <- inputIntegers\n\tprint $ n * (n + 1) `div` 2 - foldl' (+) 0 xs\n"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\n\n\nmain = do\n\t\tn<- read <$> getLine ::IO Int\n\t\tk<-sort <$> map read <$> words <$> getLine ::IO [Int]\n\t\tlet m= take 1 $ dropWhile (\\(a,b)-> a==b) $ zip k [1..]\n\t\tprint $ if m==[] then n else (snd (head m))\n\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Function\n\nmain = interact $ show . getAns . map read . words\n\ngetAns :: [Int] -> Int\ngetAns (n:xs) = n * (n + 1) `div` 2 - sum xs\n"}, {"source_code": "-- @betaveros :: vim:set fdm=marker:\n{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}\n-- import ALL the things! {{{\n-- hiding clauses are to allow Data.Foldable's generalizations\nimport Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Exception\nimport Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Char8 as BS\nimport Data.ByteString.Char8 (ByteString)\nimport Data.Bits\nimport Data.Char\nimport Data.Either\nimport Data.Foldable\nimport Data.Function\nimport Data.IORef\nimport Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.STRef\nimport Data.String\nimport Data.Traversable\nimport Data.Tuple\n\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Data.Set as Set\nimport Data.Set (Set)\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq, (<|), (|>), (><))\n\nimport Debug.Trace\nimport Text.Printf\nimport System.IO\n-- }}}\n-- silly utilities {{{\n-- stolen from lens:\na & f = f a\na <&> f = fmap f a\ninfixl 1 &, <&>\n\nfi :: (Integral a, Num b) => a -> b\nfi = fromIntegral\nglength :: (Num b) => [a] -> b\nglength = genericLength\n\nreadInt = read :: String -> Int\nreadInteger = read :: String -> Integer\n-- (!?) :: (Ord k) => Map k v -> k -> Maybe v\n-- (!?) = flip Map.lookup\nhistogram :: (Ord a, Num b) => [a] -> Map a b\nhistogram = Map.fromListWith (+) . map (,1)\n-- }}}\n-- input and output {{{\nbsGetLine :: IO ByteString\nbsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine\n\ninputInt = (read <$> getLine) :: IO Int\ninputInteger = (read <$> getLine) :: IO Integer\ninputDouble = (read <$> getLine) :: IO Double\n\ninputRow :: (Read a) => IO [a]\ninputRow = map read . words <$> getLine\ninputInts = inputRow :: IO [Int]\ninputIntegers = inputRow :: IO [Integer]\ninputDoubles = inputRow :: IO [Double]\n\nssUnwords :: [ShowS] -> ShowS\nssUnwords [] = id\nssUnwords (x:xs) = x . (' ':) . ssUnwords xs\n\nssUnlines :: [ShowS] -> ShowS\nssUnlines [] = id\nssUnlines (x:xs) = x . ('\\n':) . ssUnlines xs\n\nshowMany :: (Show a) => [a] -> String\nshowMany xs = ssUnwords (map shows xs) \"\"\nshowMatrix :: (Show a) => [[a]] -> String\nshowMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) \"\"\n\nprintMany :: (Show a) => [a] -> IO ()\nprintMany xs = putStrLn (showMany xs)\nprintMatrix :: (Show a) => [[a]] -> IO ()\nprintMatrix xs = putStr (showMatrix xs)\n-- }}}\n\nmain :: IO ()\nmain = do\n\tn <- inputInt\n\txs <- inputInts\n\tprint $ n * (n + 1) `div` 2 - foldl' (+) 0 xs\n"}, {"source_code": "main = do\n let i = fmap (map read . words) getLine :: IO [Int]\n n <- fmap (!! 0) i\n a <- i\n print $ n * (n + 1) `div` 2 - sum a\n"}], "src_uid": "0e4ff955c1e653fbeb003987fa701729"} {"source_code": "import qualified Data.Map as M\nimport Control.Monad\nimport Data.List\nimport Data.Monoid\nmain = do\n name <- getLine\n n <- read `fmap` getLine :: IO Int\n let y = takeWhile (/= '\\'')\n add m x ys n = let xy = [x, y ys] in if name `elem` xy then \n M.insertWith (+) (head $ delete name xy) n m\n else M.insertWith (+) x 0 $ M.insertWith (+) (last xy) 0 m\n a <- foldM (\\m _ -> do\n l <- getLine\n return $ case words l of\n [x, \"posted\", _, ys, \"wall\"] -> add m x ys 15 \n [x, \"commented\", _, ys, \"post\"] -> add m x ys 10\n [x, \"likes\", ys, \"post\"] -> add m x ys 5) M.empty [1..n]\n forM (sortBy (\\(a1, a2) (b1, b2) -> compare b2 a2 `mappend` compare a1 b1) $\n M.toList a) (putStrLn . fst)\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Monoid\nimport Data.Ord\n\nsolve myName lines =\n\t\tmap snd $ sortBy compare costs\n\twhere\n\t\tcost \"posted\" = 15\n\t\tcost \"commented\" = 10\n\t\tcost \"likes\" = 5\n\n\t\tfixName2 = takeWhile (/= '\\'')\n\t\tparse [name1, action, _, name2', _] = (name1, cost action, fixName2 name2')\n\t\tparse [name1, action, name2', _] = (name1, cost action, fixName2 name2')\n\n\t\tlines' = map (parse . words) lines\n\n\t\tnames = (nub $ map (\\(name1, _, _) -> name1) lines' ++ map (\\(_, _, name2) -> name2) lines')\n\t\t\t\\\\ [myName]\n\n\t\tlines'' = filter (\\(name1, _, name2) -> name1 == myName || name2 == myName) lines'\n\n\t\titems = map (\\(name1, cost, _) -> (name1, cost)) lines'' ++\n\t\t\tmap (\\(_, cost, name2) -> (name2, cost)) lines''\n\n\t\tcosts = [(s, name) | name <- names, let s = sum $ [snd i | i <- items, fst i == name]]\n\n\t\tcompare = flip (comparing fst) `mappend` comparing snd\n\nmain = do\n\tmyName <- getLine\n\t_ <- getLine\n\tactions <- lines `fmap` getContents\n\tputStrLn $ unlines $ solve myName actions\n"}, {"source_code": "import Data.List\nimport Data.Monoid\nimport Data.Ord\n\nsolve myName lines =\n\t\tmap snd $ sortBy compare costs\n\twhere\n\t\tcost \"posted\" = 15\n\t\tcost \"commented\" = 10\n\t\tcost \"likes\" = 5\n\n\t\tfixName2 = takeWhile (/= '\\'')\n\t\tparse [name1, action, _, name2', _] = (name1, cost action, fixName2 name2')\n\t\tparse [name1, action, name2', _] = (name1, cost action, fixName2 name2')\n\n\t\tlines' = map (parse . words) lines\n\n\t\tnames = (nub $ map (\\(name1, _, _) -> name1) lines' ++ map (\\(_, _, name2) -> name2) lines')\n\t\t\t\\\\ [myName]\n\n\t\tlines'' = filter (\\(name1, _, name2) -> name1 == myName || name2 == myName) lines'\n\n\t\titems = map (\\(name1, cost, _) -> (name1, cost)) lines'' ++\n\t\t\tmap (\\(_, cost, name2) -> (name2, cost)) lines''\n\n\t\tcosts = [(s, name) | name <- names, let s = sum $ [snd i | i <- items, fst i == name]]\n\n\t\tcompare = flip (comparing fst) `mappend` comparing snd\n\nmain = do\n\tmyName <- getLine\n\t_ <- getLine\n\tactions <- lines `fmap` getContents\n\tputStrLn $ unlines $ solve myName actions\n"}, {"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = map read . words <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\nparseLine yourname line \n | ws !! 1 == \"posted\" = get (ws !! 0) (name (ws !! 3)) 15\n | ws !! 1 == \"commented\" = get (ws !! 0) (name (ws !! 3)) 10\n | ws !! 1 == \"likes\" = get (ws !! 0) (name (ws !! 2)) 5\n where ws = words line\n get a b s\n | a == yourname = [(b, s)]\n | b == yourname = [(a, s)]\n | otherwise = [(a, 0), (b, 0)]\n name s = take (length s - 2) s\n\nmain = do\n yourname <- getLine\n nLines <- int\n s <- replicateM nLines getLine\n let scores = concatMap (parseLine yourname) s\n resultMap = foldl' (flip (uncurry (M.insertWith' (+)))) M.empty scores\n resultAss = sortBy c (M.assocs resultMap)\n c (a, b) (c, d) \n | b > d = LT\n | b < d = GT\n | a < c = LT\n | a > c = GT\n | otherwise = EQ\n result = map fst resultAss\n mapM_ putStrLn result"}, {"source_code": "\nimport Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Function\nimport qualified Data.Map as M\nimport Data.Maybe\n\nparseLine :: String -> (String, String, Int)\nparseLine line = (head sp, init $ init target, score)\n where\n sp = words line\n target = head $ filter (elem '\\'') sp\n score = case head (sp !! 1) of\n 'p' -> 15\n 'c' -> 10\n 'l' -> 5\n\ntype MyMap = M.Map String Int\n\nsolve :: String -> [(String, String, Int)] -> [String]\nsolve myName pairs = filter (/=myName) . map fst . reverse . sortBy (compare `on` snd) . reverse . sortBy (compare `on` fst) $ M.assocs mp\n where\n incr :: MyMap -> (String, String, Int) -> MyMap\n incr mp (f,r,s) = mp2\n where\n mp1 = M.insertWith' (+) f (if r == myName then s else 0) mp\n mp2 = M.insertWith' (+) r (if f == myName then s else 0) mp1\n mp = foldl incr M.empty pairs\n\nmain = do\n myName <- getLine\n n <- read <$> getLine :: IO Int\n pairs <- replicateM n (parseLine <$> getLine)\n let sorted = solve myName pairs\n mapM_ putStrLn sorted\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsplit = rec [] []\n where\n rec res cur [] = reverse $ reverse cur:res\n rec res [] (' ':s) = rec res [] s\n rec res cur (' ':s) = rec (reverse cur:res) [] s\n rec res cur (s:ss) = rec res (s:cur) ss\n\nprocess = do\n expr <- getLine\n return $ case split $ map (\\c -> if c == '\\'' then ' ' else c) expr of\n [n1, \"posted\", \"on\", n2, \"s\", \"wall\"] -> (n1, n2, 15)\n [n1, \"commented\", \"on\", n2, \"s\", \"post\"] -> (n1, n2, 10)\n [n1, \"likes\", n2, \"s\", \"post\"] -> (n1, n2, 5)\n\nmain = do\n you <- getLine\n n <- fmap read getLine :: IO Int\n acts <- replicateM n process :: IO [(String, String, Int)]\n mapM_ (putStrLn . fst) $ sortBy cmp $\n foldr (\\(n1, n2, p) ls ->\n if you == n1\n then incr n2 p $ ls\n else if you == n2\n then incr n1 p $ ls\n else incr n2 0 $ incr n1 0 $ ls\n ) [] acts\n where\n (n1, p1) `cmp` (n2, p2) = (-p1, n1) `compare` (-p2, n2)\n incr :: String -> Int -> [(String, Int)] -> [(String, Int)]\n incr n p l =\n case lookup n l of\n Nothing -> (n, p) : l\n _ -> map (\\(n', p') -> if n == n' then (n, p + p') else (n', p')) l\n swap (a, b) = (b, a)\n"}], "negative_code": [{"source_code": "\nimport Control.Monad\nimport Control.Applicative\nimport Control.Arrow\n\nimport Data.Char\nimport Data.List\nimport qualified Data.Map as M\n-- import Data.Map ((!))\nimport qualified Data.IntMap as IM\n-- import Data.IntMap ((!))\n\nimport Data.Array\nimport Data.Function\n\nimport Debug.Trace\n\nimport Numeric\n\ndebug = flip trace\n-- debug = const\n\nint :: IO Int\nint = read <$> getLine\n\nints :: IO [Int]\nints = map read . words <$> getLine\n\ndouble :: IO Double\ndouble = read <$> getLine\n\ndoubles :: IO [Double]\ndoubles = map read . words <$> getLine\n\nsum' = foldl' (+) 0\nproduct' = foldl' (*) 1\n\nfi = fromIntegral\n\nparseLine yourname line \n | ws !! 1 == \"posted\" = get (ws !! 0) (name (ws !! 3)) 15\n | ws !! 1 == \"commented\" = get (ws !! 0) (name (ws !! 3)) 10\n | ws !! 1 == \"likes\" = get (ws !! 0) (name (ws !! 2)) 5\n where ws = words line\n get a b s\n | a == yourname = [(b, s)]\n | b == yourname = [(a, s)]\n | otherwise = [(a, 0), (b, 0)]\n name s = take (length s - 2) s\n\nmain = do\n yourname <- getLine\n nLines <- int\n s <- replicateM nLines getLine\n let scores = concatMap (parseLine yourname) s\n resultMap = foldl' (flip (uncurry (M.insertWith' (+)))) M.empty scores\n resultAss = sortBy c (M.assocs resultMap)\n c (a, b) (c, d) \n | a < c = LT\n | a > c = GT\n | b > d = LT\n | b < d = GT\n | otherwise = EQ\n result = map fst resultAss\n mapM_ putStrLn result"}], "src_uid": "b1a86308739067f2b6c9940b564e2648"} {"source_code": "jump x n d m l \n | zone >= n = x\n | x `mod` m > l = x\n | otherwise = jump (x + needs * d) n d m l\n where zone = x `div` m\n end = m * zone + l\n needs = (end - x) `div` d + 1\n\nmain = do\n line <- getLine\n let [n, d, m, l] = map read $ words $ line :: [Integer]\n putStrLn $ show $ jump 0 n d m l", "positive_code": [{"source_code": "import Data.Int\n\ninf :: Int64\ninf = 1000000000000000\n\ngap :: Int64 -> Int64 -> Int64 -> Int64 -> Int64\ngap d m l cur\n\t| cur > d * m\t\t= inf\n\t| (mod cur m) > l\t= cur\n\t| otherwise\t\t\t= gap d m l (cur + d)\n\t\nrunout :: Int64 -> Int64 -> Int64 -> Int64 -> Int64\nrunout n d m l = end + d - mod (end + d) d\n\twhere end = (n - 1) * m + l\n\nmain :: IO()\nmain = do\n\tstr <- getLine\n\tlet input = map read (words str)\n\tlet n = input !! 0\n\tlet d = input !! 1\n\tlet m = input !! 2\n\tlet l = input !! 3\n\tputStrLn (show (min (gap d m l 0) (runout n d m l)))\n"}], "negative_code": [{"source_code": "jump x n d m l \n | zone >= n = x\n | x `mod` m > l = x\n | otherwise = jump (x + needs * d) n d m l\n where zone = x `div` m\n end = m * zone + l\n needs = (end - x) `div` d + 1\n\nmain = do\n line <- getLine\n let [n, d, m, l] = map read $ words $ line :: [Int]\n putStrLn $ show $ jump 0 n d m l"}, {"source_code": "jump x n d m l \n | zone >= n = x\n | x `mod` m > l = x\n | otherwise = jump (x + needs * d) n d m l\n where zone = x `div` m\n end = m * zone + l\n needs = (end - x) `div` d + 1\n\nmain = do\n line <- getLine\n let [n, d, m, l] = map read $ words $ line :: [Int]\n putStrLn $ show $ jump 0 n d m l"}], "src_uid": "ecbc339ad8064681789075f9234c269a"} {"source_code": "\nimport Control.Monad (liftM)\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Char (ord)\nimport Data.List (group)\nimport Prelude hiding (reads)\n\nreads :: IO [Int]\nreads = liftM (map read . words) getLine\n where\n read ('-' : s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10*a + ord c - ord '0'\n\nsolve :: Int -> [Int] -> Int\nsolve k as = head $ filter ((== maxStress) . (array !)) [1..k]\n where\n maxStress = maximum $ elems array\n array :: UArray Int Int\n array = runSTUArray $ do\n array <- newArray (1, k) 0\n writeArray array (head as) 1\n update array $ map head $ group as\n return array\n update array (x:y:z:gs) = do\n a <- readArray array y\n writeArray array y (a + if x == z then 2 else 1)\n update array (y:z:gs)\n update array (x:y:[]) = do\n a <- readArray array y\n writeArray array y (a+1)\n update array _ = return ()\n\nmain :: IO ()\nmain = do\n [n, k] <- reads\n as <- reads\n print $ solve k as", "positive_code": [{"source_code": "import Data.Array\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\ngo [x, y] = [(y, 1)]\ngo (x:t@(y:z:_)) = (y, if x == z then 2 else 1): go t\n\nmain = do\n (n:m:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents\n let b@(x:y:_) = map head $ group a\n c = [(-e, i) | (i, e) <- assocs $ accumArray (+) 0 (1,m) $ (x, 1): go b]\n print $ snd $ minimum c\n"}, {"source_code": "import Data.Array\n\nmain = do\n [_, k] <- fmap (map read . words) getLine :: IO [Int]\n a <- fmap (squeeze . map read . words) getLine :: IO [Int]\n let triples = allTriples a\n let saves = accumArray (+) 0 (0, k) $ map (\\(x,y,z) -> (y, if x == z then 2 else 1)) triples\n let best = maximum $ elems $ saves\n print $ head $ filter ((== best) . (saves !)) [1..k]\n\nsqueeze xs = squeeze' xs []\n where\n squeeze' [] ys = ys\n squeeze' (x:xs) [] = squeeze' xs [x]\n squeeze' (x:xs) (y:ys) = squeeze' xs $ if x == y then y:ys else x:y:ys\n\nallTriples (x:y:xs) = allTriples' (x:y:xs) [(0,x,y)]\n where\n allTriples' [x,y] ts = (x,y,0):ts\n allTriples' (x:y:z:xs) ts = allTriples' (y:z:xs) $ (x,y,z):ts\n"}, {"source_code": "import Control.Applicative\nimport Data.Array.Base\nimport Data.Array.IO (IOUArray)\nimport Data.List\nimport Data.Ord\nimport qualified Data.ByteString.Char8 as B\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,k] <- map read.words <$> getLine\n xs <- map head.group.map readInt.B.words <$> B.getLine\n arr <- newArray (0,k) 0 :: IO (IOUArray Int Int)\n let solve (x:y:z:rest)\n | x==z = do\n cntx <- unsafeRead arr x\n unsafeWrite arr x $! cntx-1\n cnty <- unsafeRead arr y\n unsafeWrite arr y $! cnty-1\n solve (y:z:rest)\n | otherwise = do\n cntx <- unsafeRead arr x\n unsafeWrite arr x $! cntx-1\n solve (y:z:rest)\n solve [x,y] = do\n cntx <- unsafeRead arr x\n unsafeWrite arr x $! cntx-1\n cnty <- unsafeRead arr y\n unsafeWrite arr y $! cnty-1\n solve xs \n ans <- zip[1..] <$> mapM (unsafeRead arr) [1..k]\n print.fst $ minimumBy (comparing snd) ans"}, {"source_code": "import Data.Array\n\ncompress::(Eq a) => [a] -> [a]\ncompress (x:y:xs) = if x == y then t else x:t\n where t = compress (y:xs)\ncompress [x] = [x]\ncompress [] = []\n\nanalysis [_, x] = [(x, 1)]\nanalysis (x:xs@(y:z:_)) = (y, if x == z then 2 else 1):analysis xs\n\nmain = do\n line <- getLine\n let (n:m:_) = map read $ words line :: [Int]\n line <- getLine\n let a = map read $ words line :: [Int]\n let c = assocs $ accumArray (+) 0 (1, m) $ (head a, 1) : (analysis $ compress a)\n putStrLn $ show $ snd $ minimum $ map (\\(a, b) -> (-b, a)) c\n"}, {"source_code": "import Data.Array\n\ncompress (x:xs@(y:_)) = (if x == y then [] else [x]) ++ compress xs\ncompress [x] = [x]\ncompress [] = []\n\nanalysis [_, x] = [(x, 1)]\nanalysis (x:xs@(y:z:_)) = (y, if x == z then 2 else 1):analysis xs\n\nmain = do\n line <- getLine\n let (n:m:_) = map read $ words line :: [Int]\n line <- getLine\n let a = map read $ words line :: [Int]\n let c = assocs $ accumArray (+) 0 (1, m) $ (head a, 1) : (analysis $ compress a)\n putStrLn $ show $ snd $ minimum $ map (\\(a, b) -> (-b, a)) c\n"}, {"source_code": "import Data.List\nimport Data.Array\n\nanalysis :: [Int] -> [(Int, Int)]\nanalysis [_, x] = [(x, 1)]\nanalysis (x:xs@(y:z:_)) = (y, if x == z then 2 else 1) : analysis xs\n\nanswer :: Int -> [Int] -> Int\nanswer m a = snd $ minimum $ map (\\(a, b) -> (-b, a)) c\n where b = map head $ group a\n c = assocs $ accumArray (+) 0 (1, m) $ (head a, 1) : analysis b\n\nmain = do\n line <- getLine\n let (n:m:_) = map read $ words line :: [Int]\n line <- getLine\n let a = map read $ words line :: [Int]\n putStrLn $ show $ answer m a\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\nimport Numeric\nreadInt :: String -> Int\nreadInt !s = case readDec s of [(n, \"\")] -> n\n-- readInt ('-':s) = case readDec s of [(n, \"\")] -> -n\n\npreprocess = map head . group\n\nmaxN = 500000\n\nex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]\n\n\nsolve :: [Int] -> Int\nsolve [x] = 1\nsolve xs@(x:_) = runST $ do\n ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)\n solve' (x:xs) ar\n res <- newSTRef 1\n forM_ [1..maxN] $ (\\i -> do\n a <- readArray ar i\n r <- readSTRef res\n b <- readArray ar r\n when (a > b)\n (writeSTRef res i))\n readSTRef res\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()\nmodifyArray ar f i = do\n x <- readArray ar i\n writeArray ar i (f x)\n\n\nsolve' (a:b:c:rest) ar = do\n if a == c\n then modifyArray ar (+2) b\n else modifyArray ar (+1) b\n solve' (b:c:rest) ar\nsolve' (a:[b]) ar = do\n modifyArray ar (+1) (b::Int)\n \n \n\nmain = do\n _ <- getLine\n movies <- getLine >>= (return . map Main.readInt . words)\n print . solve . preprocess $ movies\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\nimport Numeric\nreadInt :: String -> Int\nreadInt !s = case readDec s of [(n, \"\")] -> n\n-- readInt ('-':s) = case readDec s of [(n, \"\")] -> -n\n\npreprocess = map head . group\n\nmaxN = 500000\n\nex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]\n\n\nsolve :: [Int] -> Int\nsolve [x] = 1\nsolve !xs@(x:_) = runST $ do\n ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)\n solve' (x:xs) ar\n res <- newSTRef 1\n forM_ [1..maxN] $ (\\i -> do\n a <- readArray ar i\n r <- readSTRef res\n b <- readArray ar r\n when (a > b)\n (writeSTRef res i))\n readSTRef res\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()\nmodifyArray ar f i = do\n x <- readArray ar i\n writeArray ar i (f x)\n\n\nsolve' (a:b:c:rest) ar = do\n if a == c\n then modifyArray ar (+2) b\n else modifyArray ar (+1) b\n solve' (b:c:rest) ar\nsolve' (a:[b]) ar = do\n modifyArray ar (+1) (b::Int)\n \n \n\nmain = do\n _ <- getLine\n movies <- getLine >>= (return . map Main.readInt . words)\n print . solve . preprocess $ movies\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\npreprocess = map head . group\n\nmaxN = 500000\n\nex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]\n\n\nsolve :: [Int] -> Int\nsolve [x] = 1\nsolve xs@(x:_) = runST $ do\n ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)\n solve' (x:xs) ar\n res <- newSTRef 1\n forM_ [1..maxN] $ (\\i -> do\n a <- readArray ar i\n r <- readSTRef res\n b <- readArray ar r\n when (a > b)\n (writeSTRef res i))\n readSTRef res\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()\nmodifyArray ar f i = do\n x <- readArray ar i\n writeArray ar i (f x)\n\n\nsolve' (a:b:c:rest) ar = do\n if a == c\n then modifyArray ar (+2) b\n else modifyArray ar (+1) b\n solve' (b:c:rest) ar\nsolve' (a:[b]) ar = do\n modifyArray ar (+1) (b::Int)\n \n \n\nmain = do\n _ <- getLine\n movies <- getLine >>= (return . map read . words)\n print . solve . preprocess $ movies\n"}, {"source_code": "{-# OPTIONS_GHC -rtsopts -O2 #-}\n{-# OPTIONS_GHC -fasm #-}\n{-# LANGUAGE BangPatterns #-} \n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n\nimport Data.Array.ST\nimport Data.STRef\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.List\nimport Debug.Trace\n\nimport Numeric\nreadInt :: String -> Int\nreadInt !s = case readDec s of [(n, \"\")] -> n\n-- readInt ('-':s) = case readDec s of [(n, \"\")] -> -n\n\npreprocess = map head . group\n\nmaxN = 500000\n\nex1 = [1, 1, 2, 3, 2, 3, 3, 1, 1, 3]\n\n\nsolve :: [Int] -> Int\nsolve [x] = 1\nsolve xs@(x:_) = runST $ do\n ar <- (newArray (1, maxN) 0)::ST s (STArray s Int Int)\n solve' (x:xs) ar\n res <- newSTRef 1\n forM_ [1..maxN] $ (\\i -> do\n a <- readArray ar i\n r <- readSTRef res\n b <- readArray ar r\n when (a > b)\n (writeSTRef res i))\n readSTRef res\n\nmodifyArray :: (MArray a e m, Ix i) => a i e -> (e -> e) -> i -> m ()\nmodifyArray ar f i = do\n x <- readArray ar i\n writeArray ar i (f x)\n\n\nsolve' (a:b:c:rest) ar = do\n if a == c\n then modifyArray ar (+2) b\n else modifyArray ar (+1) b\n solve' (b:c:rest) ar\nsolve' (a:[b]) ar = do\n modifyArray ar (+1) (b::Int)\n \n \n\nmain = do\n _ <- getLine\n movies <- getLine >>= (return . map Main.readInt . words)\n print . solve . preprocess $ movies\n"}], "negative_code": [], "src_uid": "6ef8200d05dd5eb729edceb62e393c50"} {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\nexpval :: Double -> Double -> Double -> Double -> Double -> Double -> Double\nexpval c m p v rounds acc = expc + expm + expp\n where (validc, validm) = (c*rounds*acc > 1e-11, m*rounds*acc > 1e-11)\n expc = (if not validc then 0 else (let r = min c v\n (pp, mm) = (if validm then (r/2, r/2) else (r, 0))\n in expval (c-v) (m+mm) (p+pp) v (rounds+1) (acc*c)))\n expm = (if not validm then 0 else (let r = min m v\n (pp, cc) = (if validc then (r/2, r/2) else (r, 0))\n in expval (c+cc) (m-v) (p+pp) v (rounds+1) (acc*m)))\n expp = acc*p*rounds\n \n\nsolve :: IO ()\nsolve = do\n s <- getLine\n let [c, m, p, v] = map read $ words s :: [Double]\n expected = expval c m p v 1 1.0\n in print expected\n\n \nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n", "positive_code": [{"source_code": "import Control.Monad ( replicateM_ )\r\nimport Data.Int ( Int64 )\r\nimport Numeric ( showFFloat )\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [c, m, p, v] <- readMany :: IO [Double]\r\n let ans = go c m p 1 1\r\n go c m p d pr =\r\n let tryP = d * pr * p\r\n tryC | c <= v + eps = go' (m + c / 2) (p + c / 2) (d + 1) (pr * c)\r\n | otherwise = go (c - v) (m + v / 2) (p + v / 2) (d + 1) (pr * c)\r\n tryM | m <= v + eps = go' (c + m / 2) (p + m / 2) (d + 1) (pr * m)\r\n | otherwise = go (c + v / 2) (m - v) (p + v / 2) (d + 1) (pr * m)\r\n in tryC + tryM + tryP\r\n go' c p d pr =\r\n let tryP = d * pr * p\r\n tryC | c <= v + eps = (d + 1) * (pr * c)\r\n | otherwise = go' (c - v) (p + v) (d + 1) (pr * c)\r\n in tryP + tryC\r\n eps = 1e-8\r\n putStrLn $ showFFloat (Just 12) ans \"\"\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n"}], "negative_code": [], "src_uid": "738939f55bcc636c0340838818381d2f"} {"source_code": "import Control.Monad\n\nsolve :: [(Int, Int, Int)] -> [Int]\nsolve [] = []\nsolve ((p, _, _) : xs) = let\n go _ [] = []\n go prev ((x, y, z) : zs) = let\n next = head [v | v <- [x, y, z], notElem v [p, prev]]\n in next : go next zs\n in p : go p xs\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n _nStr <- getLine\n [a, b, c] <- replicateM 3 $ map read . words <$> getLine\n putStrLn . unwords . map show . solve $ zip3 a b c\n", "positive_code": [{"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\n\nmain :: IO ()\nmain = getLine >>= flip replicateM_ test . read\n\ntest :: IO ()\ntest = do\n _ <- getLine\n as <- map read . words <$> getLine\n bs <- map read . words <$> getLine\n cs <- map read . words <$> getLine\n let trips = zip3 as bs cs :: [(Integer, Integer, Integer)]\n putStrLn $ unwords . map show $ solve trips\n\nsolve :: Eq t => [(t, t, t)] -> [t]\nsolve [] = []\nsolve ((end, _, _) : trips) = end : f trips end\n where\n f [] _ = []\n f [(a, b, c)] pre = pure $ head $ filter (`notElem` [pre, end]) [a, b, c]\n f ((a, b, c) : t) pre = let e = head $ filter (/= pre) [a, b, c] in e : f t e\n"}], "negative_code": [], "src_uid": "7647528166b72c780d332ef4ff28cb86"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Prelude\nimport Control.Monad\nimport Data.Functor\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B8\nimport Text.Printf\n\n\nreadIntB8 :: B8.ByteString -> Int\nreadIntB8 = fst . fromJust . B8.readInt \n\nsolve :: String -> Int\nsolve s = sum oddOneGroupLengths\n where\n oddOneGroupLengths = map snd . filter (odd . fst) . zip [1..] $ oneGroupLengths\n oneGroupLengths = reverse . sort . map snd $ oneGroups\n oneGroups = filter fst groups\n groups = map (\\s -> (head s == '1', length s)) $ group s \n\nmain :: IO ()\nmain = do\n t <- readIntB8 <$> B8.getLine\n forM_ [1..t] $ \\_ -> do\n s <- B8.getLine\n let answer = solve $ B8.unpack s\n printf \"%d\\n\" answer\n", "positive_code": [{"source_code": "import Data.List\nimport Data.Int\nimport qualified Data.Array as A\nimport Data.Array((!))\nimport Numeric\n\nfastRead :: String -> Int64\nfastRead ('-':s) = case readDec s of [(n, \"\")] -> -n\nfastRead s = case readDec s of [(n, \"\")] -> n\n\nmain = interact solve\n\ntype Input = String\ntype Output = Int\n\nsolve :: String -> String\nsolve input = intercalate \"\\n\" formattedOutputs\n where\n _:xs = words input\n inputs = inputParser xs\n outputs = map solver inputs\n formattedOutputs = map outputFormatter outputs\n\ninputParser :: [String] -> [Input]\ninputParser x = x\n\noutputFormatter :: Output -> String\noutputFormatter x = show x\n\nsolver :: Input -> Output\nsolver x =\n let \n nums = sortBy (\\a b -> compare b a) . map length . filter (('1' ==) . head) $ group x \n folder :: [Int] -> Int\n folder [] = 0\n folder (x:[]) = x \n folder (x:xx:[]) = x \n folder (x:xx:xs) = x + folder xs \n in folder nums\n\n\n"}, {"source_code": "import Data.List\n\nreadOneInt :: IO Int\nreadOneInt = do\n line_ <- getLine\n return $ read line_\n\nstrangeSum :: [Int] -> Int\nstrangeSum [] = 0\nstrangeSum [a] = a\nstrangeSum [a,_] = a\nstrangeSum (a:_:cs) = a + (strangeSum cs)\n\nmain :: IO ()\nmain = do\n t <- readOneInt\n for t where\n for 0 = return ()\n for t' = do\n line_ <- getLine\n -- foldr is more correct, but i am jerk\n let counts = foldl (\\acc c -> \n if null acc \n then [(c, 1)] \n else if c == (fst $ head acc) \n then (c, 1 + (snd $ head acc)) : (tail acc)\n else (c, 1) : acc) [] line_\n let oneCounts = reverse $ sort $ snd $ unzip $ filter (\\(c,_) -> c=='1') counts\n putStrLn $ show $ strangeSum oneCounts\n for (t'-1)"}, {"source_code": "import Control.Monad\nimport Data.List\nimport Data.Function\nimport Data.Ord\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t routine\n\nroutine :: IO ()\nroutine = do\n n <- getLine\n print $ solve n\n\nsolve :: String -> Int\nsolve s = compute grp\n where\n grp = (sortBy (compare `on` Down) .map length.filter (\\(x:_) -> x=='1').group) s\n\n\ncompute :: [Int] -> Int\ncompute (x:_:xs) = x + compute xs\ncompute [x] = x\ncompute [] = 0\n"}, {"source_code": "import Data.List\n--import Data.Sort\ngetBlocks :: String -> [Int]\ngetBlocks x = reverse $ getBlocks' 0 [] x\ngetBlocks' :: Int -> [Int] -> String -> [Int]\ngetBlocks' cur a \"\" = if cur > 0 then (cur : a) else a\ngetBlocks' cur a ('0' : xs) = if cur > 0 then getBlocks' 0 (cur : a) xs else getBlocks' cur a xs\ngetBlocks' cur a ('1' : xs) = getBlocks' (cur + 1) a xs\nsolveTestCase :: String -> Int\nsolveTestCase s = let decreasingBlocks = (reverse . sort . getBlocks) s in\n let numBlocks = length decreasingBlocks in\n let indices = [0 .. numBlocks - 1] in\n let valuesAtEvenIndices = map fst $ filter (even . snd) $ zip decreasingBlocks indices in\n sum valuesAtEvenIndices\ndoCasesIO :: Int -> IO ()\ndoCasesIO 0 = return ()\ndoCasesIO t = do\n s <- getLine\n (putStrLn . show . solveTestCase) s\n doCasesIO (t - 1)\nmain :: IO ()\nmain = do\n t <- readLn :: IO Int\n doCasesIO t"}], "negative_code": [], "src_uid": "ebf0bf949a29eeaba3bcc35091487199"} {"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array ((!), accumArray, listArray, elems)\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nsolve :: [(Int, Int)] -> [Int]\nsolve ms = solve' 0 0 0 ms\n where\n solve' t 0 maxQ [] = [t, maxQ]\n solve' t q maxQ [] = solve' (t+q) 0 (max maxQ q) []\n solve' t q maxQ ((ti, ci) : ms)\n | q <= (ti - t) = solve' ti ci (max maxQ q) ms\n | otherwise = solve' ti (q - (ti - t) + ci) (max maxQ q) ms\n\nmain :: IO ()\nmain = do\n n <- readLn\n ms <- replicateM n readPair\n prints $ solve ms\n\n where\n\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n readPair :: Num a => IO (a, a)\n readPair = do\n [a, b] <- reads\n return (a, b)\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n", "positive_code": [{"source_code": "get::String->Int\nget x=read x\n\ngao::(Int,Int,Int)->(Int,Int)->(Int,Int,Int)\ngao (nowmaxPeople,nowTime,nowres) (t,k) = ( max nowmaxPeople nw,t,nw )\n\twhere nw=( max (nowres-(t-nowTime)) 0 )+k\n\nmyfst::(Int,Int,Int)->Int\nmyfst (x,_,_)=x\n\nmysnd::(Int,Int,Int)->Int\nmysnd (_,x,_)=x\n\nmythd::(Int,Int,Int)->Int\nmythd (_,_,x)=x\n\nwork::[(Int,Int)]->(Int,Int,Int)->String\nwork [] x = show ( mysnd x + mythd x ) ++ \" \" ++ show ( myfst x )\nwork (a:as) x = work as (gao x a)\n\nget2::[Int]->[(Int,Int)]\nget2 xs = zip ( map (xs!!) [1,3..2*n] ) ( map (xs!!) [2,4..2*n] )\n\twhere n=xs!!0\n\nmain::IO()\nmain = do\n\tinput<-getContents\n\tlet\n\t\tnumber=map read (words input)::[Int]\n\tputStr $ work ( get2 number ) (0,0,0)\n"}, {"source_code": "import Control.Applicative\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as C\n\npairs :: [a] -> [(a, a)]\npairs (x:y:z) = (x, y): pairs z\npairs _ = []\n\nreadInt :: C.ByteString -> Int\nreadInt = fst . fromJust . C.readInt\n\nmain :: IO ()\nmain = do\n a <- pairs . tail . map readInt . C.words <$> C.getContents\n let (t, c, maxc) = foldl gao (0, 0, 0) a\n print $ t + c\n print $ maxc\n where\n gao (t, c, maxc) (tt, cc) = let c' = cc + max 0 (c - (tt - t)) in (tt, c', max maxc $ c')\n"}, {"source_code": "\ntoList::[Int]->[(Int,Int)]\ntoList [] = []\ntoList (a:b:c) = (a,b):(toList c)\n\ngetAns::[(Int,Int)]->(Int,Int)\ngetAns lst =\n let\n getAns'::[(Int,Int)]->Int->Int->Int->(Int,Int)\n getAns' [] unfinishedTask currentTime maxTask = (currentTime+unfinishedTask,maxTask)\n getAns' ((t,c):xs) unfinishedTask currentTime maxTask =\n if t==currentTime\n then getAns' xs (unfinishedTask+c) currentTime (max maxTask (unfinishedTask+c))\n else getAns' ((t,c):xs) (max (unfinishedTask-t+currentTime) 0) t maxTask\n in getAns' lst 0 0 0\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = map read (words input)::[Int]\n ans = getAns $ toList $ tail numbers\n putStr $ show $ fst ans\n putStr \" \"\n putStr $ show $ snd ans\n putStr \"\\n\"\n"}], "negative_code": [{"source_code": "\ntoList::[Int]->[(Int,Int)]\ntoList [] = []\ntoList (a:b:c) = (a,b):(toList c)\n\ngetAns::[(Int,Int)]->(Int,Int)\ngetAns lst =\n let\n getAns'::[(Int,Int)]->Int->Int->Int->(Int,Int)\n getAns' [] unfinishedTask currentTime maxTask = (currentTime+unfinishedTask,maxTask)\n getAns' ((t,c):xs) unfinishedTask currentTime maxTask =\n if t==currentTime\n then getAns' xs (unfinishedTask+c) currentTime (max maxTask ((max (unfinishedTask-1) 0)+c))\n else getAns' ((t,c):xs) (max (unfinishedTask-t+currentTime) 0) t maxTask\n in getAns' lst 0 0 0\n\nmain::IO()\nmain =\n do\n input <- getContents\n let\n numbers = map read (words input)::[Int]\n ans = getAns $ toList $ tail numbers\n putStr $ show $ fst ans\n putStr \" \"\n putStr $ show $ snd ans\n putStr \"\\n\"\n"}], "src_uid": "608f8246bc6067e259898e8ed94db4c4"} {"source_code": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow\nimport Control.Monad.State\nimport Data.Array.Unboxed\nimport Data.Bits\nimport Data.Bool\nimport Data.ByteString.Lazy.Char8 (ByteString)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.List\nimport Data.Map (Map, (!))\nimport qualified Data.Map as M\nimport Data.Maybe\nimport Data.Ord\nimport Data.Ratio\nimport Data.Sequence (Seq, ViewL (..), ViewR (..), (<|),\n (|>))\nimport qualified Data.Sequence as Seq\nimport Data.Set (Set)\nimport qualified Data.Set as S\nimport Data.Tree\nimport Text.Printf\n\n-- import Text.Parsec\n-- import Text.Parsec.Expr\n-- import Text.Parsec.Language (emptyDef)\n-- import Text.Parsec.String\n-- import qualified Text.Parsec.Token as T\n\ninfixl 0 >$>\n(>$>) = flip ($)\n\ndata TC = TC { slots :: [[Choice]], banned :: [[Int]] }\n\ntc = do\n n <- int\n TC <$> (n >< (zipWith Choice [1 ..] <$> numberOf int)) <*> numberOf (n >< int)\n\nmain = C.interact $\n runScanner tc >>> solve >>> map (show >>> C.pack) >>> C.unwords\n\nsolve :: TC -> [Int]\nsolve TC{..} = choices . fromJust $ find ((`S.notMember` bannedSet) . choices) bs\n where\n bannedSet = S.fromList banned\n revSlots = map reverse slots\n bs = builds revSlots\n\n-- Sorted in *decreasing* order.\n\ndata Choice = Choice { index :: !Int, value :: !Int }\n\ndata Build = Build { strength :: !Int, choices :: [Int] }\n deriving (Eq, Show, Ord)\n\nsingletonBuild :: Choice -> Build\nsingletonBuild (Choice i v) = Build v [i]\n\nmkBuild xs = Build (sum xs) xs\n\n-- Pre: all input lists are sorted descending.\n-- All possible builds, sorted in descending order of strength.\nbuilds :: [[Choice]] -> [Build]\nbuilds [] = []\nbuilds (i:is) = chooseFrom i (builds is)\n\nchooseFrom :: [Choice] -> [Build] -> [Build]\nchooseFrom [] _ = []\nchooseFrom xs [] = map singletonBuild xs\nchooseFrom (x:xs) (b:bs) = addToBuild x b : mergeBuilds (map (addToBuild x) bs) (chooseFrom xs (b:bs))\n\naddToBuild :: Choice -> Build -> Build\naddToBuild (Choice i v) (Build s xs) = Build (v+s) (i:xs)\n\nmergeBuilds xs [] = xs\nmergeBuilds [] ys = ys\nmergeBuilds (x:xs) (y:ys) = case compare (strength x) (strength y) of\n GT -> x : mergeBuilds xs (y:ys)\n _ -> y : mergeBuilds (x:xs) ys\n\n------------------------------------------------------------\n\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = head <$> get\n\nstr :: Scanner C.ByteString\nstr = get >>= \\case { s:ss -> put ss >> return s }\n\nint :: Scanner Int\nint = (fst . fromJust . C.readInt) <$> str\n\ninteger :: Scanner Integer\ninteger = (read . C.unpack) <$> str\n\ndouble :: Scanner Double\ndouble = (read . C.unpack) <$> str\n\ndecimal :: Int -> Scanner Int\ndecimal p = (round . ((10^p)*)) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case { [] -> return []; _ -> (:) <$> s <*> many s }\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n case p t of\n True -> return []\n False -> (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2..4]\n\npair :: Scanner a -> Scanner b -> Scanner (a,b)\npair = liftA2 (,)\n", "positive_code": [{"source_code": "import Control.Monad\r\nimport Data.Array\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport qualified Data.Set as S\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n] <- readInts\r\n cas <- replicateM n $ (\\(x:cs) -> listArray (1, x) cs) <$> readInts\r\n [m] <- readInts\r\n bs <- S.fromList <$> replicateM m readInts\r\n let next = init . go where\r\n go [] = [[]]\r\n go (1:is) = map (1:) $ go is\r\n go ~(i:is) = (i - 1 : is) : map (i:) (go is)\r\n candidates = filter (`S.notMember` bs) $ [snd $ bounds ca | ca <- cas] : concatMap next (S.elems bs)\r\n score is = sum $ [fromIntegral $ ca!i | (i, ca) <- zip is cas] :: Int64\r\n putStrLn $ unwords $ map show $ maximumBy (comparing score) candidates\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}, {"source_code": "import Control.Monad\r\nimport Data.Array.Unboxed\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport qualified Data.Set as S\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n] <- readInts\r\n cas <- replicateM n $ (\\(x:cs) -> listArray (1, x) cs :: UArray Int Int) <$> readInts\r\n [m] <- readInts\r\n bs <- S.fromList <$> replicateM m readInts\r\n let next = init . go where\r\n go [] = [[]]\r\n go (1:is) = map (1:) $ go is\r\n go (i:is) = (i - 1 : is) : map (i:) (go is)\r\n candidates = filter (`S.notMember` bs) $ map (snd . bounds) cas : concatMap next (S.elems bs)\r\n score is = sum $ [fromIntegral $ ca!i | (i, ca) <- zip is cas] :: Int64\r\n putStrLn $ unwords $ map show $ maximumBy (comparing score) candidates\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "negative_code": [{"source_code": "import Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport qualified Data.Set as S\r\nimport qualified Data.ByteString.Char8 as C\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n [n] <- readInts\r\n cs <- replicateM n $ reverse . zip [1..] . tail <$> readInts\r\n [m] <- readInts\r\n bs <- S.fromList <$> replicateM m readInts\r\n let pop [x] = [x]\r\n pop ~(_:xs) = xs\r\n diff [x] = 10^9\r\n diff ~(x:x':_) = snd x - snd x'\r\n sub [] [] = [[]]\r\n sub ~(x:xs) ~(y:ys) = (y:xs) : map (x:) (sub xs ys)\r\n go cs\r\n | sig `S.notMember` bs = sig\r\n | otherwise = go cs'\r\n where\r\n sig = map (fst . head) cs\r\n diffs = map diff cs\r\n newcs = init $ sub cs $ map pop cs\r\n cs' = snd $ minimumBy (comparing fst) $ zip diffs newcs\r\n putStrLn $ unwords $ map show $ go cs\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine\r\n\r\nmain :: IO ()\r\nmain = solve\r\n"}], "src_uid": "8d4d4e3c19558c2b5560d2253732df34"} {"source_code": "import qualified Data.Map as M\nimport qualified Data.ByteString.Char8 as B\n\nmain = mapM_ putStrLn . solve . map (map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents\n\nsolve :: [[Int]] -> [String]\nsolve ([n, m] : as : qs) = map (judge vs) qs\n where\n vs = M.fromList $ findV [] $ zip [1..] as\n\njudge :: M.Map Int Int -> [Int] -> String\njudge vs [l, r] = case M.lookupGE l vs of\n Just (i, j) -> if j <= r then \"No\" else \"Yes\"\n Nothing -> \"Yes\"\n\nfindV :: [Int] -> [(Int, Int)] -> [(Int, Int)]\nfindV _ ((i, a) : x@(_, b) : xs) | a > b = findV [i] (x : xs)\nfindV [i] ((_, b) : x@(j, c) : xs) | b < c = (i, j) : findV [] (x : xs)\nfindV is (x : xs) = findV is xs\nfindV _ _ = []\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.Array.Base\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n [n,m] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n qs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map (\\flg -> if flg then \"Yes\" else \"No\") $ solve n xs qs\n\nsolve :: Int -> [Int] -> [Int] -> [Bool]\nsolve n _ qs | n<=2 = replicate (length qs `div` 2) True\nsolve n xs qs = go qs\n where\n !arr = listArray (0,n-2) $ zipWith (-) (tail xs) xs :: UArray Int Int\n !segtree = mkSegTree 0 (n-2) arr\n go (l:r:rest) = query (l-1) (r-2) segtree : go rest\n go _ = []\n\ndata SegTree = Node !Bool !Int !Int !Int !Int !SegTree !SegTree\n | Leaf !Bool !Int !Int\n\ngetMin :: SegTree -> Int\ngetMin (Node _ _ _ val _ _ _) = val\ngetMin (Leaf _ _ val ) = val\n\ngetMax :: SegTree -> Int\ngetMax (Node _ _ _ _ val _ _) = val\ngetMax (Leaf _ _ val ) = val\n\ngetFlg :: SegTree -> Bool\ngetFlg (Node flg _ _ _ _ _ _) = flg\ngetFlg (Leaf flg _ _ ) = flg\n\nmkSegTree :: Int -> Int -> UArray Int Int -> SegTree\nmkSegTree l r arr\n | l/=r = do\n let !m = (l+r) `quot` 2\n lt = mkSegTree l m arr\n rt = mkSegTree (m+1) r arr\n Node (getFlg lt && getFlg rt && (getMin lt >= 0 || getMax rt <= 0) ) l r\n (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt\n | otherwise = Leaf True l (unsafeAt arr l)\n\nquery :: Int -> Int -> SegTree -> Bool\nquery kl kr segtree = if kl>=kr then True else go segtree\n where\n go (Node flg l r _ _ lt rt)\n | r= 0 || queryMax kl kr rt <= 0)\n go (Leaf _ _ _ ) = True\n\nqueryMin :: Int -> Int -> SegTree -> Int\nqueryMin kl kr segtree = go segtree\n where\n go (Node flg l r v _ lt rt)\n | r Int -> SegTree -> Int\nqueryMax kl kr segtree = go segtree\n where\n go (Node flg l r _ v lt rt)\n | r n\n\nmain = do\n [n,m] <- map read.words <$> getLine\n xs <- map readInt.B.words <$> B.getLine\n qs <- map readInt.B.words <$> B.getContents\n putStr.unlines.map (\\flg -> if flg then \"Yes\" else \"No\") $ solve n xs qs\n\nsolve :: Int -> [Int] -> [Int] -> [Bool]\nsolve n _ qs | n<=2 = replicate (length qs `div` 2) True\nsolve n xs qs = go qs\n where\n !arr = listArray (0,n-2) $ zipWith (-) (tail xs) xs :: UArray Int Int\n !segtree = mkSegTree 0 (n-2) arr\n go (l:r:rest) = query (l-1) (r-2) segtree : go rest\n go _ = []\n\n\ndata SegTree = Node !Bool !Int !Int !Int !Int !SegTree !SegTree\n | Leaf !Bool !Int !Int\n\ngetMin :: SegTree -> Int\ngetMin (Node _ _ _ val _ _ _) = val\ngetMin (Leaf _ _ val ) = val\n\ngetMax :: SegTree -> Int\ngetMax (Node _ _ _ _ val _ _) = val\ngetMax (Leaf _ _ val ) = val\n\ngetFlg :: SegTree -> Bool\ngetFlg (Node flg _ _ _ _ _ _) = flg\ngetFlg (Leaf flg _ _ ) = flg\n\nmkSegTree :: Int -> Int -> UArray Int Int -> SegTree\nmkSegTree l r arr\n | l/=r = do\n let !m = (l+r) `quot` 2\n lt = mkSegTree l m arr\n rt = mkSegTree (m+1) r arr\n if getFlg lt && getFlg rt\n then if getMin lt < 0 && 0 < getMax rt\n then Node False l r (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt\n else Node True l r (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt\n else Node False l r (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt\n | otherwise = Leaf True l (unsafeAt arr l)\n\nquery :: Int -> Int -> SegTree -> Bool\nquery kl kr segtree = if kl>=kr then True else go segtree\n where\n go (Node flg l r v _ lt rt)\n | r= 0 || queryMax kl kr rt <= 0) && go lt && go rt\n go (Leaf _ _ _ ) = True\n\nqueryMin :: Int -> Int -> SegTree -> Int\nqueryMin kl kr segtree = go segtree\n where\n go (Node flg l r v _ lt rt)\n | r Int -> SegTree -> Int\nqueryMax kl kr segtree = go segtree\n where\n go (Node flg l r _ v lt rt)\n | r>= mapM_ putStrLn . mkAns\n"}, {"source_code": "solve :: Int -> [String]\nsolve n = [getLine i | i <- [1..n]]\n where\n getLine i = [getChar i j | j <- [1..n]]\n getChar i j\n | abs (m - i) + abs (m - j) < m = 'D'\n | otherwise = '*'\n m = n `div` 2 + 1\n\nmain :: IO()\nmain = readLn >>= mapM_ putStrLn . solve\n "}, {"source_code": "s m = replicate m '*'\nmain = do\n n <- read `fmap` getLine\n let xs = [1,3..n] ++ [n-2,n-4..1]\n sol= [concat [s m,replicate i 'D',s m] | i <- xs\n , let m = (n-i)`div`2]\n putStr . unlines $ sol"}, {"source_code": "import Data.List\n\nrowSizes :: Int -> [Int]\nrowSizes n = gradient ++ [n] ++ (reverse gradient)\n where gradient = takeWhile (/=n) $ iterate (+2) 1\n\nrenderRow :: Int -> Int -> String\nrenderRow n s = padding ++ (replicate s 'D') ++ padding\n where t = (n - s) `div` 2\n padding = replicate t '*'\n\nsolve :: Int -> String\nsolve n = unlines $ map (renderRow n) $ rowSizes n\n\nmain = interact $ solve . read\n"}, {"source_code": "\nmain = do\n n <- readLn :: IO Int\n putStr $ unlines $ map (gen n) ([1, 3 .. n] ++ [n - 2, n - 4 .. 1])\n where\n gen :: Int -> Int -> [Char]\n gen n x = out ++ (replicate x 'D') ++ out\n where out = replicate ((n - x) `div` 2) '*'\n"}, {"source_code": "main :: IO ()\nmain = readLn >>= mapM_ putStrLn . solve\n\nsolve :: Int -> [String]\nsolve n = [ replicate (m - i) '*' ++ replicate (2 * i + 1) 'D'\n ++ replicate (m - i) '*' | i <- [0..m] ++ [m-1, m-2 .. 0] ]\n where m = n `div` 2\n"}, {"source_code": "import Control.Monad (liftM2)\nmain = interact $ unlines . liftM2 map row peak . read\npeak n = [1 .. h+1] ++ [h,h-1..1] where h = n `div` 2\nrow n k = g ++ replicate (2*k-1) 'D' ++ g\n where g = replicate ((n-2*k+1) `div` 2) '*'\n"}, {"source_code": "s n=[[if abs(i-(n`div`2+1))+abs(j-(n`div`2+1))>n`div`2 then '*' else 'D'|j<-[1..n]]|i<-[1..n]]\nmain=interact$unlines.s.read\n"}, {"source_code": "import Control.Applicative\nimport Data.List\n\nprocess n = (reverse k) ++ [(replicate n 'D')] ++ k\n\twhere k = [ replicate i '*' ++ replicate j 'D' ++ replicate i '*'| i<-[1..div n 2], let j = n-2*i]\n \n\nmain= do\n\tn<- read <$>getLine::IO Int \n\tputStrLn $ intercalate \"\\n\" $ process n\n\t \n\t\n\t"}, {"source_code": "process :: Int -> [[Char]]\nprocess n\n | even n = undefined\n | otherwise = [[if n'-i' <= j && j <= n'+i' then 'D' else '*' | j <- [0..(n-1)]] | i <- [0..(n-1)], let i' = min i (n-1-i)]\n where n' = n `div` 2\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n putStrLn . unlines $ process n"}, {"source_code": "main = do\n n <- fmap read getLine :: IO Int\n putStrLn $ f n n\nf 0 n = \"\"\nf m n = x ++ y ++ x ++ \"\\n\" ++ (f (m - 1) n) where\n k = if 2*m-1<=n then 2*m-1 else 2*(n-m)+1\n x = [1..div (n-k) 2]>>\"*\"\n y = [1..k]>>\"D\""}, {"source_code": "f :: Int -> Int -> String\nf s l | l <= s `quot` 2 = (replicate ((s `quot` 2) - l+1) '*') ++ (replicate (2*(l) -1) 'D') ++ (replicate ((s `quot` 2) - l+1) '*')\n | l == s `quot` 2 +1 = replicate s 'D'\n | otherwise = f s (s-l+1)\n\nmain = do\n line <- getLine\n let num = read line :: Int\n lst = map (f num) [1..num]\n mapM putStrLn lst\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmain :: IO ()\nmain = interact $ unlines . solve . read\n\nsolve :: Int -> [String]\nsolve n = [l | x <- [1..n], let l = out x n]\n\nout :: Int -> Int -> String\nout i n\n | i*2-1 > n = out (n+1-i) n\n | otherwise =\n let\n p = i*2-1\n q = (n-p) `div` 2\n in\n replicate q '*' ++ replicate p 'D' ++ replicate q '*'\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\n\nmain :: IO ()\nmain = interact $ unlines . solve . read\n\nsolve :: Int -> [String]\nsolve n = [out i n | i <- [1..n]]\n\nout :: Int -> Int -> String\nout i n\n | i*2-1 > n = out (n+1-i) n\n | otherwise =\n let\n p = i*2-1\n q = (n-p) `div` 2\n in\n replicate q '*' ++ replicate p 'D' ++ replicate q '*'\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -O2 -optc-O2 #-}\nimport qualified Data.List as L\nimport qualified Data.ByteString.Lazy.Char8 as LC\n \nmain :: IO ()\nmain = do\n (line:_) <- fmap LC.words LC.getContents\n let n = readInt line\n putStr $ unlines $ out 1 (n `div` 2 + 1) n\n \nout :: Int -> Int -> Int -> [String]\nout _ _ 0 = []\nout i n k =\n let\n j = if i < k then i+1 else i-1\n in\n (replicate (n-i) '*' ++ replicate (i*2-1) 'D' ++ replicate (n-i) '*') : out j n (k-1)\n\n-------------------------------------------------------------------------------\n\nreadInt :: LC.ByteString -> Int\nreadInt = LC.foldl' (\\x c -> 10 * x + fromEnum c - 48) 0\n"}, {"source_code": "main = do \n\tn<-getLine\n\tlet res1 = solve (read n) 1\n\tlet res2 = init $ unlines $reverse $ init $ lines res1\n\tputStr $ res1\n\tputStrLn res2\n\nsolve n l | l <=n = spaces ((n-l)) ++ printer (generator l) ++ spaces ((n-l))++ \"\\n\" ++ solve n (l+2)\n | otherwise = \"\"\n\n\ngenerator n = replicate (n) \"D\"\n\nspaces n = replicate (div n 2) '*'\n\nprinter s = concat $ map (\\x-> x ++ \"\") s"}, {"source_code": "import Data.List\n\nmain = putStrLn . unlines . solve . read =<< getLine\n\nsolve :: Int -> [String]\nsolve n = solve' 1 True\n where solve' :: Int -> Bool -> [String]\n solve' x inc | x < 0 = []\n | x > n = solve' (x - 4) False\n | otherwise = let f = div (n - x) 2\n s = (replicate f '*') ++ (replicate x 'D') ++ (replicate f '*')\n in if inc\n then s:solve' (x + 2) inc\n else s:solve' (x - 2) inc\n"}, {"source_code": "import Data.List\nimport Data.Function\nimport Data.Char\n\nmain = interact $ unlines . getAns . read\n\ngetAns :: Int -> [String]\ngetAns n = do\n\tx <- [1..n]\n\treturn (getL x n)\n\ngetL :: Int -> Int -> String\ngetL x n\n\t| x * 2 - 1 > n = getL (n + 1 - x) n\n\t| otherwise = let a = x * 2 - 1; b = (n - a) `div` 2\n\t\t\t\t in replicate b '*' ++ replicate a 'D' ++ replicate b '*'\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad hiding ((<$!>))\nimport Control.Monad.ST.Safe\nimport Control.Monad.State hiding ((<$!>))\n-- import Data.Array\nimport Data.Array.IArray\nimport Data.Array.IO.Safe\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Builder as BB\nimport Data.Char\nimport qualified Data.Foldable as F\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.List.Split\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Ratio\nimport qualified Data.Sequence as Seq\nimport Data.Sequence (Seq)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n-- import Data.Tree\nimport Data.Tuple\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.HashMap.Strict (HashMap)\nimport qualified Data.HashMap.Strict as HashMap\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\n-- import Debug.Trace\nimport System.IO\n\n-- getInts = fmap (map read . words) getLine\ngetInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\n\nmain = do\n n <- readLn\n\n let\n s = [[f i j | j <- [1..n]] | i <- [1..n]]\n f i j = if abs (i-c) + abs (j-c) <= n`div`2 then 'D' else '*'\n where\n c = n`div`2+1\n\n putStr $ unlines s\n"}], "negative_code": [], "src_uid": "a003d645999934c255f7b05d8494fa40"} {"source_code": "import Control.Monad\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn :: IO Int\r\n a <- readMany :: IO [Int]\r\n let go [] 0 = 1\r\n go [] _ = 0\r\n go (x:xs) s = go xs s + go xs (s + x) + go xs (s - x)\r\n putStrLn $ if go a 0 > 1 then \"YES\" else \"NO\"\r\n\r\nreadMany :: Read a => IO [a]\r\nreadMany = map read . words <$> getLine\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n replicateM_ t solve\r\n", "positive_code": [{"source_code": "import qualified Data.ByteString.Lazy.Char8 as P\nimport qualified Data.ByteString.Builder as B\nimport System.IO\n\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Data.List\nimport Data.Semigroup\n\nmain :: IO ()\nmain = (P.getContents >>=) . evalStateT $ do\n [t] <- readInts\n replicateM_ t $ do\n [_n] <- readInts\n a <- map abs <$> readInts\n let opts = sort $ map (foldl' (+) 0) $ subsequences a\n --forM_ (subsequences a) putInts\n lift $ putStrLn $ if any (uncurry (==)) $ zip opts $ tail opts\n then \"YES\"\n else \"NO\"\n\ntype SIO = StateT P.ByteString IO\n\nreadLine :: SIO P.ByteString\nreadLine = do\n (out, next) <- P.break (<= '\\r') <$> get\n put $ P.dropWhile (<= '\\r') next\n pure out\n\nreadInts :: SIO [Int]\nreadInts = do\n currLine <- readLine\n pure [x | Just (x, _) <- P.readInt <$> P.words currLine]\n\nputInts :: [Int] -> SIO ()\nputInts li = let\n outBuilder = foldr (<>) (B.char7 '\\n')\n $ intersperse (B.char7 ' ') (map B.intDec li)\n in lift $ B.hPutBuilder stdout outBuilder\n"}, {"source_code": "import Control.Arrow ((>>>))\nimport Control.Monad (filterM)\nimport Data.Bool (bool)\nimport Data.List (group, sort)\n\nmain :: IO ()\nmain =\n interact $\n lines\n >>> drop 1\n >>> chunksOf 2\n >>> map (last >>> words >>> map read >>> solve >>> bool \"No\" \"Yes\")\n >>> unlines\n\nsolve :: [Int] -> Bool\nsolve =\n any ((> 1) . length) -- does any sum occur more than once?\n . group\n . sort\n . map sum -- subsequence sums\n . filterM (const [False, True]) -- all subsequences\n . sort\n . map abs\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE Strict #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (filterM, guard, replicateM)\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.List (group, sort, delete)\nimport Data.Maybe (fromJust, fromMaybe)\nimport Debug.Trace (trace)\n\nmain :: IO ()\nmain = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))\n\ntestCase :: Scanner String\ntestCase = maybe \"Yes\" (const \"No\") . solve <$> numberOf int\n\n-- Nothing -> Yes, Just () -> No\nsolve :: [Int] -> Maybe ()\nsolve xs = do\n xs <- pure $ sort (map abs xs)\n yesIf $ 0 `elem` xs\n yesIf $ any ((> 1) . length) $ group xs\n yesIf $ any ((> 1) . length) . group . sort $ subsums xs\n where\n yesIf = guard . not\n subseq = filterM (const [False, True])\n subsums = map sum . subseq\n\ncount :: Eq a => a -> [a] -> Int\ncount a = length . filter (== a)\n\ndebug a = trace (show a) a\n\n-------------------------- Template ------------------------------------------\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = read . C.unpack <$> bstr\n\ndouble :: Scanner Double\ndouble = read . C.unpack <$> bstr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n"}], "negative_code": [], "src_uid": "e8e32f179080f9d12bb1e4df303ea124"} {"source_code": "ans :: IO String\r\nans = do\r\n n <- readLn :: IO Int\r\n sInput <- getLine\r\n fInput <- getLine\r\n let s = [read x :: Int | x <- words sInput]\r\n let f = [read x :: Int | x <- words fInput]\r\n let maxs = [max (fst x) (snd x) | x <- zip (tail s) f]\r\n let results = (head f - head s) : [(fst x) - (snd x) | x <- zip (tail f) maxs]\r\n return $ unwords [show x | x <- results]\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines results", "positive_code": [{"source_code": "module Main where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map.Strict as Map\n\nmain = do\n tStr <- getLine\n let t = read tStr :: Int\n input <- getContents\n let sols = map (format . solve . parse) $ take t $ sep $ lines input\n mapM_ putStrLn sols\n\nsep (_:x:y:xs) = (x,y):(sep xs)\n\nparse (x,y) = (phi x, phi y)\n where phi = (map read) . words\n\nformat = unwords . map show\n\nsolve (ss,fs) = solve' 0 ss fs\n\nsolve' _ [] [] = []\nsolve' f0 (s:ss) (f:fs) = (f - max s f0):(solve' f ss fs)\n"}, {"source_code": "-- boilerplate {{{1\n-- vim: foldmethod=marker\n-- pragmas {{{2\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Main where -- {{{2\n\nimport Control.Applicative\nimport Control.Arrow ( (|||), (&&&) )\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Array.IArray\nimport Data.Array.IO\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Bifunctor\nimport Data.Bits\nimport Data.Bool\nimport Data.Char\nimport Data.Foldable hiding ( sum, product )\nimport Data.Function\nimport Data.Functor\nimport Data.IntMap ( IntMap )\nimport Data.IntSet ( IntSet )\nimport Data.List hiding ( sum, product )\nimport Data.Map ( Map )\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Min(..), Max(..) )\nimport Data.Sequence ( Seq )\nimport Data.Set ( Set )\nimport Data.Text ( Text )\nimport Data.Traversable\nimport Data.Tuple\nimport Debug.Trace\nimport Prelude hiding ( sum, product )\nimport System.IO\n-- import System.Random\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as C\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport qualified Data.Map as LM\nimport qualified Data.Map.Strict as M\nimport qualified Data.Sequence as Q\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\n\n-- utilites {{{2\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\ngetInt = readInt <$> C.getLine\ngetInts = map readInt . C.words <$> C.getLine\nputShows :: Show a => [a] -> IO ()\nputShows = putStrLn . unwords . map show\nynq = putStrLn . bool \"NO\" \"YES\"\ngcount g@(x:_) = (x, length g)\nmodulus = 10^9 + 7 :: Int\nmod' x = rem x modulus\ntri n = quot (n * n + n) 2\nsum t = foldl' (+) 0 t\nproduct t = foldl' (*) 1 t\nmprint :: Show a => String -> Maybe a -> IO ()\nmprint s = maybe (putStrLn s) print\nifM :: Monad m => m Bool -> m a -> m a -> m a\nifM b t e = b >>= bool e t\nwhenM :: Monad m => m Bool -> m () -> m ()\nwhenM b t = ifM b t (pure ())\n\n-- }}}1\n\nmain = getInt >>= flip replicateM_ docase\n\ndocase = do\n [n] <- getInts\n aa <- getInts\n bb <- getInts\n\n let f a z b = b - max a z\n let dd = zipWith3 f aa (0:bb) bb\n putShows dd\n"}, {"source_code": "import Data.Int\r\n\r\nans :: IO String\r\nans = do\r\n n <- readLn :: IO Int\r\n input <- getLine\r\n let s = [read x :: Int32 | x <- words input]\r\n input <- getLine\r\n let f = [read x :: Int32 | x <- words input]\r\n let maxs = [max (fst x) (snd x) | x <- zip (tail s) f]\r\n let results = (head f - head s) : [(fst x) - (snd x) | x <- zip (tail f) maxs]\r\n return $ unwords [show x | x <- results]\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines results"}, {"source_code": "ans :: IO String\r\nans = do\r\n n <- readLn :: IO Int\r\n input <- getLine\r\n let s = [read x :: Int | x <- words input]\r\n input <- getLine\r\n let f = [read x :: Int | x <- words input]\r\n let maxs = [max (fst x) (snd x) | x <- zip (tail s) f]\r\n let results = (head f - head s) : [(fst x) - (snd x) | x <- zip (tail f) maxs]\r\n return $ unwords [show x | x <- results]\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines results"}, {"source_code": "calc' :: [Int] -> [Int] -> Int -> [Int]\r\ncalc' [] [y] later = [y - later]\r\ncalc' (x : xs) (y : ys) later = [y - later] ++ calc' xs ys (max y x)\r\n\r\ncalc :: [Int] -> [Int] -> [Int]\r\ncalc [x] [y] = [y - x]\r\ncalc (x0 : x1 : xs) (y : ys) = [y - x0] ++ calc' xs ys (max y x1)\r\n\r\nans :: IO String\r\nans = do\r\n n <- readLn :: IO Int\r\n sInput <- getLine\r\n fInput <- getLine\r\n let s = [read x :: Int | x <- words sInput]\r\n let f = [read x :: Int | x <- words fInput]\r\n let results = calc s f\r\n return $ unwords [show x | x <- results]\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines results"}, {"source_code": "calc' :: [Int] -> [Int] -> Int -> [Int]\r\ncalc' [_] [y] later = [y - later]\r\ncalc' (_ : x : xs) (y : ys) later = [y - later] ++ calc' (x : xs) ys (max y x)\r\n\r\ncalc :: [Int] -> [Int] -> [Int]\r\ncalc [x] [y] = [y - x]\r\ncalc (x : xs) (y : ys) = [y - x] ++ calc' xs ys (max y $ head xs)\r\n\r\nans :: IO String\r\nans = do\r\n n <- readLn :: IO Int\r\n sInput <- getLine\r\n fInput <- getLine\r\n let s = [read x :: Int | x <- words sInput]\r\n let f = [read x :: Int | x <- words fInput]\r\n let results = calc s f\r\n return $ unwords [show x | x <- results]\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n results <- sequence $ replicate t ans\r\n putStrLn $ unlines results"}], "negative_code": [], "src_uid": "2fee6c39d4e55f903837ef81e818eb07"} {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine :: IO Int\n str <- getLine\n\n let sentenceSize = snd $ mapAccumL (\\last this -> (this, this - last - 1)) (0-2) $\n findIndices (\\a -> a == '.' || a == '?' || a == '!') str\n\n packMessage [] _ = return 0\n packMessage (s:ss) r =\n if s <= r\n then packMessage ss (r-s-1)\n else if s <= n\n then packMessage ss (n-s-1) >>= return . (1+)\n else fail \"\"\n\n res = packMessage sentenceSize 0\n\n putStrLn $ case res of\n Just n -> show n\n Nothing -> \"Impossible\"\n", "positive_code": [{"source_code": "main = interact(solve.take 2.lines)\n\nsolve (sn:cs:[]) = if count>0 then show count else \"Impossible\" where\n n = read sn\n count = cnt n cs\n cnt n cs = cnt' cs 0 where\n cnt' [] acc = acc\n cnt' (' ':cs) acc = cnt' cs acc\n cnt' cs acc = if l>0 then cnt' (drop l cs) (acc+1) else 0 where \n l = length $ dropWhile (`notElem` \".!?\") $ reverse (take n cs)\n"}, {"source_code": "\nsolve :: Int -> String -> Maybe Int\nsolve n text\n | any (> n) ls = Nothing\n | otherwise = Just $ length $ groups ls\n where\n is = map fst $ filter (flip elem \".?!\" . snd) $ zip [1..] text\n ls = head is : zipWith (\\i j -> j - i - 1) is (tail is)\n groups [] = []\n groups ls = (take k ls) : groups (drop k ls)\n where\n k = length $ tail $ takeWhile (<= n) $ scanl (\\s i -> s + i + 1) (-1) ls\n\nmain :: IO ()\nmain = do\n n <- readLn\n s <- getLine\n putStrLn $ maybe \"Impossible\" show $ solve n s\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine :: IO Int\n str <- getLine\n\n let sentenceSize = tail $ scanl (\\last this -> this - last) 0 $\n findIndices (\\a -> a == '.' || a == '?' || a == '!') (' ':str)\n\n packMessage [] _ = return 0\n packMessage (s:ss) r =\n if s <= r\n then packMessage ss (r-s-1)\n else if s <= n\n then packMessage ss (n-s-1) >>= return . (1+)\n else fail \"\"\n\n res = packMessage sentenceSize 0\n\n putStrLn $ case res of\n Just n -> show n\n Nothing -> \"Impossible\"\n"}], "src_uid": "12b64f77fc9dd44a7e0287ff0a716a6a"} {"source_code": "import Control.Applicative\nimport Data.Array\n\nreadWords = map read . words <$> getLine\n\n\n\n\n\n\n\nsolve n m c as bs =\n\t\tzipWith (+.) as $ zipWith (-.) (sums ++ replicate (n-m) (last sums)) (replicate (n-m+1) 0 ++ sums)\n\twhere\n\t\ta +. b = (a + b) `mod` c\n\t\ta -. b = (a - b) `mod` c\n\n\t\tsums = scanl1 (+.) bs\n\nmain = do\n\t\t[n, m, c] <- readWords\n\t\tas <- readWords\n\t\tbs <- readWords\n\t\tputStrLn $ unwords $ map show $ solve n m c as bs\n", "positive_code": [{"source_code": "main :: IO ()\nmain = \n do cs <- getContents\n (putStr.showSolve.solve.parseIn) cs\n\nsolve :: (Int,Int,Int,[Int],[Int])->[Int]\nsolve (n,m,c,as,bs) = map (\\x->mod x c) $ foldl (zipWith (+)) as adds\n where \n adds = encryptB (n-m+1) n bs\n\nshowSolve::[Int]->String\nshowSolve [] = \"\"\nshowSolve [i] = show i\nshowSolve (i:is) = show i ++ \" \" ++ showSolve is\n\nparseIn :: String->(Int,Int,Int,[Int],[Int])\nparseIn s = (n,m,c,as,bs)\n where\n [l1,la,lb] = lines s\n [n,m,c] = map read $ words l1\n as = take n $ map read $ words la \n bs = take m $ map read $ words lb\n\nencryptB::Int->Int->[Int]->[[Int]]\nencryptB 1 _ x = [x]\nencryptB k n x = (listFill n x) : (encryptB (k-1) n (0:x))\n\nlistFill::Int->[Int]->[Int]\nlistFill n l = l++(take (n-(length l)) [0,0..])\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\nreadWords = map read . words <$> getLine\n\nsolve n m c as bs =\n\t\tzipWith (+.) as $ zipWith (-.) (sums ++ replicate (n-m) (last sums)) (replicate (n-m+1) 0 ++ sums)\n\twhere\n\t\ta +. b = (a + b) `mod` c\n\t\ta -. b = (a - b) `mod` c\n\n\t\tsums = scanl1 (+.) bs\n\nmain = do\n\t\t[n, m, c] <- readWords\n\t\tas <- readWords\n\t\tbs <- readWords\n\t\tputStrLn $ unwords $ map show $ solve n m c as bs\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\n-- readWords = map read . words <$> getLine\nreadWords = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nsolve n m c as bs =\n\t\tzipWith (+.) as $ zipWith (-.) (sums ++ replicate (n-m) (last sums)) (replicate (n-m+1) 0 ++ sums)\n\twhere\n\t\ta +. b = (a + b) `mod` c\n\t\ta -. b = (a - b) `mod` c\n\n\t\tsums = scanl1 (+.) bs\n\nmain = do\n\t\t[n, m, c] <- readWords\n\t\tas <- readWords\n\t\tbs <- readWords\n\t\tputStrLn $ unwords $ map show $ solve n m c as bs\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as B\n\nreadWords = map (fst . fromJust . B.readInt) . B.words <$> B.getLine\n\nsolve n m c as bs =\n\t\tzipWith (+.) as sums\n\twhere\n\t\ta +. b = (a + b) `mod` c\n\t\ta -. b = (a - b) `mod` c\n\n\t\tstarts = scanl1 (+.) bs\n\t\tsums = zipWith (-.) (starts ++ replicate (n-m) (last starts)) (replicate (n-m+1) 0 ++ starts)\n\nmain = do\n\t\t[n, m, c] <- readWords\n\t\tas <- readWords\n\t\tbs <- readWords\n\t\tputStrLn $ unwords $ map show $ solve n m c as bs\n"}, {"source_code": "import Control.Applicative\nimport Data.Array\n\nmain = do\n\t\t[n, m, c] <- readWords\n\t\tas <- readWords\n\t\tbs <- readWords\n\t\tputStrLn $ unwords $ map show $ solve n m c as bs\n\twhere\n\t\treadWords = map read . words <$> getLine\n\n\t\tsolve n m c as bs =\n\t\t\t\tzipWith (+.) as $ [(sums ! (min i m)) -. (sums ! ((max (i+m-n) 1) - 1)) | i <- [1..n]]\n\t\t\twhere\n\t\t\t\ta +. b = (a + b) `mod` c\n\t\t\t\ta -. b = (a - b) `mod` c\n\n\t\t\t\tsums = listArray (0, m) $ scanl (+.) 0 bs\n\n"}], "negative_code": [{"source_code": "import Control.Applicative\nimport Data.Array\n\nmain = do\n\t\t[n, m, c] <- readWords\n\t\tas <- readWords\n\t\tbs <- readWords\n\t\tputStrLn $ unwords $ map show $ solve n m c as bs\n\twhere\n\t\treadWords = map read . words <$> getLine\n\n\t\tsolve n m c as bs =\n\t\t\t\tzipWith (+.) as $ [(sums ! (min i m)) -. (sums ! (max (i+m-n) 1)) - 1 | i <- [1..n]]\n\t\t\twhere\n\t\t\t\ta +. b = (a + b) `mod` c\n\t\t\t\ta -. b = (a - b) `mod` c\n\n\t\t\t\tsums = listArray (0, m) $ scanl (+.) 0 bs\n\n"}], "src_uid": "9a6ee18e144a38935d7c06e73f2e6384"} {"source_code": "-- {-# LANGUAGE \n-- BangPatterns\n-- , BlockArguments\n-- , DataKinds\n-- , DeriveGeneric\n-- , DerivingStrategies\n-- , DerivingVia\n-- , FlexibleContexts\n-- , FlexibleInstances\n-- , GADTs\n-- , GeneralizedNewtypeDeriving\n-- , KindSignatures\n-- , LambdaCase\n-- , MultiParamTypeClasses\n-- , MultiWayIf\n-- , NPlusKPatterns\n-- , NegativeLiterals\n-- , OverloadedLabels\n-- , OverloadedStrings\n-- , ParallelListComp\n-- , PolyKinds\n-- , RankNTypes\n-- , ScopedTypeVariables\n-- , StrictData\n-- , TupleSections\n-- , TypeApplications\n-- , TypeFamilies\n-- , TypeOperators\n-- , UndecidableInstances\n-- , ViewPatterns\n-- #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\n-- import System.IO\n-- import Data.Proxy\n-- import GHC.TypeLits\n-- import GHC.Generics ( Generic )\n-- import GHC.Exts\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\n-- import Control.Monad.Trans.Class ( MonadTrans(lift) )\n\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_ t $ do\n [n, m, r, c] <- getInts\n print $ maximum [n - r + m - c, r - 1 + m - c, n - r + c - 1, r - 1 + c - 1]\n", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\n\nmain :: IO ()\nmain =\n interact $\n lines >>> drop 1 >>> map (words >>> map read >>> solve >>> show) >>> unlines\n\nsolve :: [Int] -> Int\nsolve [n, m, r, c] = max (r - 1) (n - r) + max (c - 1) (m - c)\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE BinaryLiterals #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE NumDecimals #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Char\nimport Data.List\nimport Data.Maybe\n\nimport qualified Data.ByteString.Char8 as B\n\nimport Data.Array.ST.Safe\nimport Data.STRef\n\n-- import Debug.Trace\nimport Text.Printf\n\nreadInt = readLn :: IO Int\nreadInteger = readLn :: IO Integer\nreadInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine\nreadIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine\n\nwhich a b f = if f then a else b\nmp [ a, b ] = ( a, b )\n\nmodifyArray a i f = writeArray a i =<< f <$> readArray a i\n\nprintList [a] = print a\nprintList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as\n\nmain = readInt >>= flip replicateM solve\n\nsolve = do\n\t[ n, m, r, c ] <- readInts\n\tprint $ max ( r - 1 ) ( n - r ) + max ( c - 1 ) ( m - c )"}, {"source_code": "import Control.Monad\n\n\nmain = do\n cases <- read <$> getLine\n replicateM_ cases $ do\n [n, m, r, c] <- (map read . words) <$> getLine :: IO [Int]\n putStrLn $ show $ (max (abs $ 1 - r) (abs $ n - r)) + (max (abs $ 1 - c) (m - c))\n\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport Control.Monad.Trans.Class ( MonadTrans(lift) )\nimport Control.Monad.Cont\nimport Text.Parsec.ByteString\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n [x, y, r, c] <- getInts\n print $ max (r - 1) (x - r) + max (c - 1) (y - c)\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\n-- import System.IO\n-- import Data.Proxy\n-- import GHC.TypeLits\n-- import GHC.Generics ( Generic )\n-- import GHC.Exts\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\n-- import Control.Monad.Trans.Class ( MonadTrans(lift) )\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n [x, y, r, c] <- getInts\n print $ max (r - 1) (x - r) + max (c - 1) (y - c)\n"}, {"source_code": "{-# LANGUAGE \n BangPatterns\n , BlockArguments\n , DataKinds\n , DeriveGeneric\n , DerivingStrategies\n , DerivingVia\n , FlexibleContexts\n , FlexibleInstances\n , GADTs\n , GeneralizedNewtypeDeriving\n , KindSignatures\n , LambdaCase\n , MultiParamTypeClasses\n , MultiWayIf\n , NPlusKPatterns\n , NegativeLiterals\n , OverloadedLabels\n , OverloadedStrings\n , ParallelListComp\n , PolyKinds\n , RankNTypes\n , ScopedTypeVariables\n , StrictData\n , TupleSections\n , TypeApplications\n , TypeFamilies\n , TypeOperators\n , UndecidableInstances\n , ViewPatterns\n #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Arrow\nimport Control.Monad\nimport Control.Monad.ST\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Char\nimport Data.Foldable\nimport Data.Functor\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Monoid\nimport Data.Ord\nimport Data.Semigroup ( Max(..)\n , Min(..)\n , All(..)\n , Arg(..)\n )\nimport Data.Ratio\n-- import Data.Vector.Unboxing.Mutable ( Unboxable )\n-- import qualified Data.Vector.Unboxing.Mutable as V\nimport System.IO\nimport Data.Proxy\nimport GHC.TypeLits\nimport GHC.Generics ( Generic )\n-- import GHC.Exts\n-- import Control.Monad.Primitive ( PrimMonad(PrimState) )\nimport Control.Monad.Trans.Class ( MonadTrans(lift) )\n\n\n-- #if defined(LOCAL_ZER0STAR)\n-- {-# ANN module (\"Hlint: ignore Unused LANGUAGE pragma\" :: String) #-}\n-- {-# ANN module (\"Hlint: ignore Reduce duplication\" :: String) #-}\n-- #endif\n\n\ntwice :: (a -> a -> b) -> a -> b\ntwice f x = f x x\n\nboth :: Arrow a => a b c -> a (b, b) (c, c)\nboth = twice (***)\n\nreadsLn :: Read a => IO [a]\nreadsLn = mapM readIO . words =<< getLine\n\ngetInt :: IO Int\ngetInt = fst . fromJust . BS.readInt <$> BS.getLine\n\ngetInts :: IO [Int]\ngetInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\ngetInteger :: IO Integer\ngetInteger = fst . fromJust . BS.readInteger <$> BS.getLine\n\ngetIntegers :: IO [Integer]\ngetIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine\n\n\nmain = do\n t <- getInt\n replicateM_\n t\n do\n [x, y, r, c] <- getInts\n print $ max (r - 1) (x - r) + max (c - 1) (y - c)\n"}], "negative_code": [], "src_uid": "3a3fbb61c7e1ccda69cd6d186da653ae"} {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Set as S\n \nprocess m n se [] = max m n\nprocess m n se (a:as) | S.member a se = process (max m n) (n-1) se as\n\t\t | otherwise = process m (n+1) (S.insert a se) as\n \nmain = do\n\t\tn<- read<$> getLine ::IO Int\n\t\ta<- map read <$> words <$> getLine ::IO [Int]\n\t\tprint $ process 0 0 S.empty a\n", "positive_code": [{"source_code": "-- Codeforces Round #403 (Div. 2)\n-- A. Andryusha and Socks\n-- http://codeforces.com/contest/782/problem/A\n\nimport Control.Monad\nimport Data.Maybe\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport qualified Data.Set as Set\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]\nparseInt = fst . fromJust . BS8.readInt\n\ntype State = (Set.Set Int, Int, Int)\n\nmain = do\n n <- getInt\n socks <- getInts\n let (_, _, answer) = foldl pick (Set.empty, 0, 0) socks\n print answer\n\npick (table, curr, answer) sock\n | sock `Set.member` table = (table, curr - 1, answer)\n | otherwise = (sock `Set.insert` table, curr + 1, max answer (curr + 1))\n"}, {"source_code": "import System.IO\nimport Data.Set\n\nsolve :: [Int] -> Set Int -> Int -> Int\nsolve [] table res = res\nsolve (x:xs) table res\n | x `member` table = solve xs (delete x table) res\n | otherwise = solve xs (insert x table) maxLength\n where currLength = size table\n nextLength = currLength + 1\n maxLength = max res nextLength\n\n\nmain = do\n n <- readLn :: IO Int\n a <- fmap (Prelude.map read . words) getLine :: IO [Int]\n print (solve a empty 0)"}, {"source_code": "import Control.Applicative( (<$>))\nimport Data.IntSet( insert, delete, member, empty)\nmain = do\n n_ <- readLn::IO Int\n socks_ <- map read . words <$> getLine ::IO [Int]\n let\n\tpick _ _ [] = [0]\n\tpick n table (s:socks)\n\t | s `member` table = let\n\t\t n' = n-1\n\t\t recur = pick n' table' socks\n\t\t where\n\t\t\ttable' = delete s table\n\t\tin\n\t\t n':recur\n\n\t | otherwise\t= let\n\t\t n' = n+1\n\t\t recur = pick n' table' socks\n\t\t where\n\t\t\ttable' = insert s table\n\t\tin\n\t\t n':recur\n\n print . maximum $ pick 0 empty socks_\n"}, {"source_code": "import Data.Set (Set)\nimport qualified Data.Set as Set\n\nmain = do\n _ <- getLine\n ns <- getLineValues\n let doCount (currT, maxT, s) curr\n | curr `Set.member` s = (currT - 1, maxT, Set.delete curr s)\n | otherwise = (currT + 1, maxT `max` (currT + 1), Set.insert curr s)\n (_, maxT, _) = foldl doCount (0, 0, Set.empty) ns\n print maxT\n\ngetLineValues :: IO [Int]\ngetLineValues = getLine >>= return . map read . words"}, {"source_code": "import qualified Data.Set as Set\nimport Data.List\n\nmain = do\n _ <- getLine\n ns <- getLineValues\n let doCount (currT, maxT, s) curr\n | curr `Set.member` s = (currT - 1, maxT, Set.delete curr s)\n | otherwise = (currT + 1, maxT `max` (currT + 1), Set.insert curr s)\n (_, maxT, _) = foldl' doCount (0, 0, Set.empty) ns\n print maxT\n\ngetLineValues :: IO [Int]\ngetLineValues = getLine >>= return . map read . words"}, {"source_code": "import qualified Data.Set as Set\nimport Data.List\n\nmain = do\n _ <- getLine\n ns <- getLineValues\n let doCount (currT, maxT, s) curr\n | curr `Set.member` s = (currT - 1, maxT, Set.delete curr s)\n | otherwise = (currT + 1, maxT `max` (currT + 1), curr `Set.insert` s)\n (_, maxT, _) = foldl' doCount (0, 0, Set.empty) ns\n print maxT\n\ngetLineValues :: IO [Int]\ngetLineValues = getLine >>= return . map read . words"}, {"source_code": "import Data.Bits\nimport Data.List\nimport qualified Data.ByteString.Char8 as B\nmain = print . solve . map readI . tail . B.words =<< B.getContents\nsolve = maximum . snd . mapAccumL f (0 :: Integer)\nf s i | testBit s i = (clearBit s i,popCount s)\n | otherwise = (setBit s i,popCount s)\nreadI b = i where Just (i,_) = B.readInt b\n"}, {"source_code": "{-# OPTIONS_GHC -O3 #-}\n{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}\n\nimport Control.Monad (forM_, forM)\nimport qualified Data.Set as S (empty, delete, insert, member, size)\nimport Data.List (delete)\n\nfll (x:xs) l m | x `S.member` l = fll xs (S.delete x l) m\n | otherwise = fll xs (S.insert x l) (max m (S.size l + 1))\nfll [] _ m = m\n\nmain = do\n (read -> n) <- getLine\n (map (read :: String -> Int) . words -> xs) <- getLine\n let x = take (2 * n) xs\n putStrLn $ show $ fll x S.empty 0\n"}, {"source_code": "-- Codeforces Round #403 (Div. 2)\n-- A. Andryusha and Socks\n-- http://codeforces.com/contest/782/problem/A\n\nimport Control.Monad\nimport qualified Data.Set as Set\n\ngetInt = read `fmap` getLine :: IO Int\n\ntype State = (Set.Set Int, Int, Int)\n\nmain = do\n n <- getInt\n socks <- (map read . words) `fmap` getLine :: IO [Int]\n let (_, _, answer) = foldl pick (Set.empty, 0, 0) socks\n print answer\n\npick (table, curr, answer) sock\n | sock `Set.member` table = (table, curr - 1, answer)\n | otherwise = (sock `Set.insert` table, curr + 1, max answer (curr + 1))\n"}], "negative_code": [], "src_uid": "7f98c9258f3e127a782041c421d6317b"} {"source_code": "import Data.Function (on)\r\nimport Data.List\r\nimport qualified Data.Set as S\r\n\r\n-- code --\r\n\r\ndata Task = Task { nums :: [Int]\r\n } deriving (Show)\r\n\r\ndata Answer = Answer { num :: Int\r\n } deriving (Show)\r\n\r\nbiteTask :: String -> (Task, String)\r\nbiteTask str = let line1:line2:_ = lines str\r\n nums = map read $ words line2\r\n in (Task {nums=nums}, dropLines 2 str)\r\n\r\nshowAns :: Answer -> String \r\nshowAns Answer {num = ans} = show ans\r\n\r\nsolve_task :: Task -> Answer\r\nsolve_task Task { nums=nums\r\n } = let setNums = S.fromList nums\r\n minnum = minimum setNums\r\n shiftnums = S.delete 0 $ S.map (-minnum+) setNums\r\n numsdivs = S.map (S.fromList . allDivisors) shiftnums\r\n \r\n in Answer { num = if null shiftnums then -1 else maximum $ foldr1 S.intersection numsdivs }\r\n\r\n-- //// --\r\n\r\nallDivisors :: (Integral a) => a -> [a]\r\nallDivisors num = check'emAll 1 num where\r\n check'emAll n num | n2 > num = []\r\n | n2 == num = [n]\r\n | num `mod` n == 0 = n : check'emAll (n+1) num ++ [num `div` n]\r\n | otherwise = check'emAll (n+1) num where\r\n n2 = n^2\r\n\r\n\r\nyesNo False = \"NO\"\r\nyesNo True = \"YES\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nreadBigInt :: String -> Integer\r\nreadBigInt = read\r\n\r\ndropLines _ \"\" = \"\"\r\ndropLines 0 text = text\r\ndropLines n ('\\n':xs) = dropLines (n-1) xs\r\ndropLines n (x:xs) = dropLines n xs\r\n\r\ntype Tasks = [Task]\r\ntype Answers = [Answer]\r\n\r\nreadTasks :: String -> Tasks\r\nreadTasks \"\" = []\r\nreadTasks input = let (task, input') = biteTask input \r\n in task : readTasks input'\r\n\r\nshowAnswers :: Answers -> String\r\nshowAnswers [] = \"\"\r\nshowAnswers (ans : anss) = showAns ans ++ \"\\n\" ++ showAnswers anss\r\n\r\nsolve :: String -> String\r\nsolve = showAnswers . map solve_task . readTasks . dropLines 1\r\n\r\nmain = interact solve", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {xs :: [Int]}\n\ninput :: Scanner TC\ninput = do\n xs <- numberOf int\n return TC {..}\n\noutput = showB\n\nsolve :: TC -> Int\nsolve TC {..} = check . foldl1 gcd . map (abs . (head xs - )) $ tail xs\n where\n check 0 = -1\n check x = x\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad (replicateM_, forM_, forM)\r\nimport Data.List (sort)\r\n\r\nnextList :: IO [Int]\r\nnextList = map read.words <$> getLine\r\n\r\ngo :: [Int] -> Int -> Int\r\ngo [] _ = 0\r\ngo (a : as) x = if a > x then 0 else go as (x - a) + 1\r\n\r\nsolve = do\r\n [n] <- nextList\r\n a <- nextList\r\n let b = [abs (x - y) | x <- a, y <- a]\r\n print $ if foldr gcd 0 b == 0 then -1 else foldr gcd 0 b\r\n\r\nmain = do\r\n [t] <- nextList\r\n replicateM_ t solve\r\n "}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\n-- import Data.List\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t readTC\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\nreadTC = do\r\n _n <- readLn :: IO Int\r\n readListLn\r\n\r\nreadListLn = map read <$> words <$> getLine :: IO [Integer]\r\n\r\nsolve xs = show . solveGCD . filter (/=0) . map (flip (-) (minimum xs)) $ xs\r\n\r\nsolveGCD [] = -1\r\nsolveGCD [x] = x\r\nsolveGCD (x:y:zs) = solveGCD (gcd x y : zs)\r\n"}, {"source_code": "import Data.Function (on)\r\nimport Data.List\r\nimport qualified Data.Set as S\r\n\r\n-- code --\r\n\r\ndata Task = Task { nums :: [Int]\r\n } deriving (Show)\r\n\r\ndata Answer = Answer { num :: Int\r\n } deriving (Show)\r\n\r\nbiteTask :: String -> (Task, String)\r\nbiteTask str = let line1:line2:_ = lines str\r\n nums = map read $ words line2\r\n in (Task {nums=nums}, dropLines 2 str)\r\n\r\nshowAns :: Answer -> String \r\nshowAns Answer {num = ans} = show ans\r\n\r\nsolve_task :: Task -> Answer\r\nsolve_task Task { nums=nums\r\n } = let minnum = minimum nums\r\n shiftnums = filter (/=0) $ map (-minnum+) nums\r\n numsdivs = map (S.fromList . allDivisors) shiftnums\r\n \r\n in Answer { num = if null shiftnums then -1 else maximum $ foldr1 S.intersection numsdivs }\r\n\r\n-- //// --\r\n\r\nallDivisors :: (Integral a) => a -> [a]\r\nallDivisors num = check'emAll 1 num where\r\n check'emAll n num | n2 > num = []\r\n | n2 == num = [n]\r\n | num `mod` n == 0 = n : check'emAll (n+1) num ++ [num `div` n]\r\n | otherwise = check'emAll (n+1) num where\r\n n2 = n^2\r\n\r\n\r\nyesNo False = \"NO\"\r\nyesNo True = \"YES\"\r\n\r\nreadInt :: String -> Int\r\nreadInt = read\r\n\r\nreadBigInt :: String -> Integer\r\nreadBigInt = read\r\n\r\ndropLines _ \"\" = \"\"\r\ndropLines 0 text = text\r\ndropLines n ('\\n':xs) = dropLines (n-1) xs\r\ndropLines n (x:xs) = dropLines n xs\r\n\r\ntype Tasks = [Task]\r\ntype Answers = [Answer]\r\n\r\nreadTasks :: String -> Tasks\r\nreadTasks \"\" = []\r\nreadTasks input = let (task, input') = biteTask input \r\n in task : readTasks input'\r\n\r\nshowAnswers :: Answers -> String\r\nshowAnswers [] = \"\"\r\nshowAnswers (ans : anss) = showAns ans ++ \"\\n\" ++ showAnswers anss\r\n\r\nsolve :: String -> String\r\nsolve = showAnswers . map solve_task . readTasks . dropLines 1\r\n\r\nmain = interact solve"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Arrow ((>>>))\nimport Control.Monad\nimport Control.Monad.State (State, evalState, get, gets, put)\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport Data.Function\nimport Data.Int\nimport Data.List\nimport Data.Maybe\n\nmain :: IO ()\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\n\ndata TC = TC {xs :: [Int]}\n\ninput :: Scanner TC\ninput = do\n xs <- numberOf int\n return TC {..}\n\noutput = showB\n\nsolve :: TC -> Int\nsolve TC {..} = foldl1 gcd . map (abs . (head xs - )) $ tail xs\n\n-------------------------- Template ------------------------------------------\n-- Lists\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\ngroupOn = groupBy . on (==)\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf _ [] = []\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\n\nadjacents :: [a] -> [(a, a)]\nadjacents xs = zip xs (tail xs)\n\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\nadjacentsWith f xs = zipWith f xs (tail xs)\n\ncount :: Eq a => a -> [a] -> Int\ncount = countBy . (==)\n\ncountBy :: (a -> Bool) -> [a] -> Int\ncountBy p = length . filter p\n\n-- Scanner\ntype Scanner = State [C.ByteString]\n\nrunScanner :: Scanner a -> C.ByteString -> a\nrunScanner = runScannerWith C.words\n\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\nrunScannerWith t s = evalState s . t\n\npeek :: Scanner C.ByteString\npeek = gets head\n\nbstr :: Scanner C.ByteString\nbstr = get >>= \\case s : ss -> put ss >> return s\n\nstr :: Scanner String\nstr = C.unpack <$> bstr\n\nreadStr :: Read a => Scanner a\nreadStr = read <$> str\n\nint :: Scanner Int\nint = fst . fromJust . C.readInt <$> bstr\n\ninteger :: Scanner Integer\ninteger = readStr\n\nint64 :: Scanner Int64\nint64 = readStr\n\ndouble :: Scanner Double\ndouble = readStr\n\ndecimal :: Int -> Scanner Int\ndecimal p = round . ((10 ^ p) *) <$> double\n\nnumberOf :: Scanner a -> Scanner [a]\nnumberOf s = int >>= flip replicateM s\n\nmany :: Scanner a -> Scanner [a]\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\n\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\ntill p s = do\n t <- peek\n if p t\n then return []\n else (:) <$> s <*> till p s\n\ntimes :: Int -> Scanner a -> Scanner [a]\ntimes = replicateM\n\n(><) = times\n\ntwo, three, four :: Scanner a -> Scanner [a]\n[two, three, four] = map times [2 .. 4]\n\npair :: Scanner a -> Scanner b -> Scanner (a, b)\npair = liftA2 (,)\n\nshowB :: Show a => a -> C.ByteString\nshowB = C.pack . show\n"}, {"source_code": "import Control.Monad (replicateM_, forM_, forM)\r\nimport Data.List (sort)\r\n\r\nnextList :: IO [Int]\r\nnextList = map read.words <$> getLine\r\n\r\ngo :: [Int] -> Int -> Int\r\ngo [] _ = 0\r\ngo (a : as) x = if a > x then 0 else go as (x - a) + 1\r\n\r\nsolve = do\r\n [n] <- nextList\r\n a <- nextList\r\n let b = [abs (x - y) | x <- a, y <- a]\r\n print $ foldr gcd 0 b\r\n\r\nmain = do\r\n [t] <- nextList\r\n replicateM_ t solve\r\n "}], "src_uid": "57f0f36905d7769167b7ba9d3d9be351"} {"source_code": "import Data.List\n\ncount_ l = sort $ map (\\g -> (length g, head g)) $ group (sort l)\n\neveryOther [] = []\neveryOther (a : b : xs) = b : everyOther xs\n\nf l =\n let (nSame, _) = last $ count_ l\n nUnique = length $ map head $ group (sort l)\n in max (min nSame (nUnique - 1)) (min (nSame - 1) nUnique)\n\nmain = interact $ unlines . map (show . f . words) . everyOther . tail . lines\n", "positive_code": [{"source_code": "import Control.Monad (forM_)\nimport Data.List (sort)\n\nsolve xs = res where\n\tsorted = sort xs\n\tsizes = go sorted 0 where\n\t\tgo (x:y:xs) acc\n\t\t\t| x == y = go (y:xs) (acc+1)\n\t\t\t| otherwise = (acc+1) : go (y:xs) 0\n\t\tgo [x] acc = [acc + 1]\n\t\tgo [] 0 = []\n\t\n\tm = maximum sizes\n\tlen = length sizes\n\tres = max (min m (len-1)) (min (m-1) len)\n\t\n\t\nmain = do\n\tt <- fmap read getLine\n\tforM_ [1..t] $ \\i -> do\n\t\tn <- fmap read getLine :: IO Int\n\t\txs <- fmap (map read.words) getLine :: IO [Int]\n\t\tprint (solve xs)"}, {"source_code": "\nimport Data.List\n\nsolve :: [Int] -> Int\nsolve as = if m == d then m-1 else min m d\n where\n grouping = group $ sort as\n d = length grouping\n m = maximum $ map length grouping\n\ntestCases :: Int -> IO ()\ntestCases 0 = return ()\ntestCases t = do\n _ <- readInts\n as <- readInts\n print $ solve as\n testCases (t-1)\n\nmain :: IO ()\nmain = do\n (t:_) <- readInts\n testCases t\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getLine"}, {"source_code": "import Data.List\n\nmain :: IO ()\nmain = do\n getLine\n answers <- map (solve . map read . words . snd) <$> filter (even . fst) <$> zip[1..] <$> lines <$> getContents\n mapM_ print answers\n\nsolve :: [Int] -> Int\nsolve xs = let groupLengths = sort . map length . group . sort $ xs\n in max (min (length groupLengths - 1) (last groupLengths)) (min (length groupLengths) (last groupLengths - 1))\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n getLine\n a <- sort <$> getIntList\n let b = group a\n max_size = maximum . map length $ b\n diff = length b\n print $ if diff > max_size then max_size else if max_size - 1 >= diff then diff else diff - 1\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- sort <$> getIntList\n print $ f n a\n\nf :: Int -> [Int] -> Int\nf n a =\n let {\n b = group a;\n max_size = maximum . map length $ b;\n diff = length b\n } in\n if diff > max_size then max_size else if max_size - 1 >= diff then diff else diff - 1"}, {"source_code": "import Control.Monad\nimport Data.List\n\nsolve :: [Int] -> Int\nsolve xs = max u v\n where\n counts = map length $ group $ sort xs\n mc = maximum counts\n mt = length counts\n u = min mc (mt-1)\n v = min mt (mc-1)\n\nmain :: IO ()\nmain = do\n tc <- readLn\n replicateM_ tc $ do\n getLine\n xs <- map read . words <$> getLine\n print $ solve xs\n"}], "negative_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.List\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nmain :: IO ()\nmain = do\n t <- readLn\n replicateM_ t $ do\n n <- readLn\n a <- sort <$> getIntList\n print $ f n a\n\nf :: Int -> [Int] -> Int\nf n a =\n let {\n b = group a;\n max_size = maximum . map length $ b;\n diff = length b\n } in\n if diff > max_size\n then max_size\n else if diff == max_size && n == diff * 2 - 1\n then max_size - 1\n else diff"}, {"source_code": "import Data.List\n\ncount_ l = sort $ map (\\g -> (length g, head g)) $ group (sort l)\n\neveryOther [] = []\neveryOther (a : b : xs) = b : everyOther xs\n\nf l =\n let (nSame, _) = last $ count_ l\n nUnique = length $ map (head . group) (sort l)\n in max (min nSame (nUnique - 1)) (min (nSame - 1) nUnique)\n\nmain = interact $ unlines . map (show . f . words) . everyOther . tail . lines\n"}], "src_uid": "a1951e7d11b504273765fc9fb2f18a5e"} {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Lazy\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)\n\nsolve' r c b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n (b', lg) = runState (gr r b >>= gr c . transpose) []\n\nsolve b = case (solve' Row Col b, solve' Col Row (transpose b)) of\n (Just l, Just r) -> Just $ if length l < length r then l else r\n (l, r) -> l <|> r\n\nmain = do \n n:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve b", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.List\n\nmain = do\n _ <- getLine\n css <- map (map read.words).lines <$> getContents\n let res = solve css\n case res of\n Just (len, ops) -> do\n print len\n putStr.unlines.map show $ ops\n Nothing -> print $ - 1\n\nsolve :: [[Int]] -> Maybe (Int, [Op])\nsolve xss | not $ isValid xss = Nothing\nsolve xss = Just $ solve' xss `min` fmap (map trans) (solve' (transpose xss))\nsolve' xss = (length $ rows ++ cols, map Row rows ++ map Col cols)\n where\n rows = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum xss\n cols = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum.transpose $ map step xss\n\nisValid :: [[Int]] -> Bool\nisValid xss = all(0==).concat.map step.transpose $ map step xss\n\n\nstep xs = map (subtract m) xs\n where\n !m = minimum xs\n\ndata Op = Row Int | Col Int deriving (Eq, Ord)\n\ninstance Show Op where\n show (Row x) = \"row \" ++ show x\n show (Col x) = \"col \" ++ show x\n\ntrans (Row x) = Col x\ntrans (Col x) = Row x\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Strict\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (replicate m (p i) ++) *> return (map (subtract m) r)\n\nsolve' r c b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n (b', lg) = runState (gr r b >>= gr c . transpose) []\n\nsolve b = case (solve' Row Col b, solve' Col Row (transpose b)) of\n (Just l, Just r) -> Just $ if length l < length r then l else r\n (l, r) -> l <|> r\n\nmain = do \n n:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB $ reverse lg) $ solve b"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Strict\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)\n\nsolve' r c b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n (b', lg) = runState (gr r b >>= gr c . transpose) []\n\nsolve b = case (solve' Row Col b, solve' Col Row (transpose b)) of\n (Just l, Just r) -> Just $ if length l < length r then l else r\n (l, r) -> l <|> r\n\nmain = do \n n:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve b"}, {"source_code": "import Data.List as L\nimport Data.Text as T\nimport Data.Char\nimport Control.Arrow\n\nreadInput :: String -> [Int]\nreadInput = pack >>> (split isSpace) >>> (L.filter (/= pack \"\")) >>> (fmap (unpack >>> read))\n\ngrp (x:y:xs) = gr y xs\n where gr _ [] = []\n gr y xs = L.take y xs : (gr y $ L.drop y xs)\n\nl = L.map (\\s -> L.map (subtract $ L.minimum s) s)\nr a = L.map L.minimum a\n\nl' x = L.transpose $l (L.transpose x)\nr' a = r $L.transpose a\n\na = ((l &&& r) >>> (\\ (x,y) -> (l' x,(y,(r' x))) ))\naa = ((l' &&& r') >>> (\\ (x,y) -> (l x,((r x),y)) ))\n\na' x = if comp (a x) (aa x)\n then a x\n else aa x\n where comp (_,(a,b)) (_,(c,d)) = sum a + sum b < sum c + sum d\n\nb (x,(a,b)) = if (0 < L.maximum (L.map L.maximum x))\n then \"-1\"\n else ((flip (++)$\"\\n\"). show . L.length &&& L.foldr (++) \"\") >>> uncurry (++) $(c \"row \" a)++(c \"col \" b)\nc s n = L.filter ((/=0).snd) >>> L.map (\\(i, t)-> L.take (fromIntegral t) $repeat $s ++ show i++\"\\n\") >>>L.foldr (++) [] $z n\nz = L.zipWith(,)[1..]\nmain = do\n lines <- getContents\n putStr$ (b.a') (grp $readInput lines)\n"}], "negative_code": [{"source_code": "import Data.List as L\nimport Data.Text as T\nimport Data.Char\nimport Control.Arrow\n\nreadInput :: String -> [Int]\nreadInput = pack >>> (split isSpace) >>> (L.filter (/= pack \"\")) >>> (fmap (unpack >>> read))\n\ngrp (x:y:xs) = gr y xs\n where gr _ [] = []\n gr y xs = L.take y xs : (gr y $ L.drop y xs)\n\nl = L.map (\\s -> L.map (subtract $ L.minimum s) s)\nr a = L.map L.minimum a\n\nl' x = L.transpose $l (L.transpose x)\nr' a = r $L.transpose a\n\na = ((l &&& r) >>> (\\ (x,y) -> (l' x,(y,(r' x))) ))\nb (x,(a,b)) = if (0 < L.maximum (L.map L.maximum x))\n then \"-1\"\n else ((flip (++)$\"\\n\"). show . L.length &&& L.foldr (++) \"\") >>> uncurry (++) $(c \"row \" a)++(c \"col \" b)\nc s n = L.filter ((/=0).snd) >>> L.map (\\(i, t)-> L.take (fromIntegral t) $repeat $s ++ show i++\"\\n\") >>>L.foldr (++) [] $z n\nz = L.zipWith(,)[1..]\nmain = do\n lines <- getContents\n putStr$ (b.a) (grp $readInput lines)\n"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Lazy\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)\n\nsolve b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n (b', lg) = runState (gr Row b >>= gr Col . transpose) []\n\nmain = do \n n:m:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve b"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Lazy\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)\n\nsolve n m b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n (s1, s2)\n | n <= m = (Row, Col)\n | otherwise = (Col, Row)\n (b', lg) = runState (gr s1 b >>= gr s2 . transpose) []\n\nmain = do \n n:m:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve n m b"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Lazy\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)\n\nsolve n m b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n r = gr Row\n c = gr Col . transpose\n (b', lg) = runState ((if n < m then r >=> c else c >=> r) b) []\n\nmain = do \n n:m:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve n m b"}, {"source_code": "{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\nimport qualified Data.ByteString.Char8 as B\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\nimport Control.Monad.State.Lazy\n\nreadInt = maybe undefined fst . B.readInt\nreadInts = fmap readInt . B.words\n\nshowB :: Show a => a -> B.ByteString\nshowB = B.pack . show\n\ndata Step = Row Int | Col Int\ninstance Show Step where\n show (Row r) = \"row \" ++ show r\n show (Col c) = \"col \" ++ show c\n\ngr p b = zipWithM go (zip [1..] b) $ map minimum b\n where\n go :: (Int, [Int]) -> Int -> State [Step] [Int]\n go (i, r) m\n | m <= 0 = return r\n | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)\n\nsolve n m b = if all (== 0) $ concat b' then Just lg else Nothing\n where\n r = gr Row\n c = gr Col . transpose\n (b', lg) = runState ((if n <= m then r >=> c else c >=> r) b) []\n\nmain = do \n n:m:_ <- fmap readInts B.getLine\n b <- replicateM n (fmap readInts B.getLine)\n B.putStr $ maybe \"-1\" (\\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve n m b"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.List\n\nmain = do\n _ <- getLine\n css <- map (map read.words).lines <$> getContents\n let res = solve css\n case res of\n Just (len, ops) -> do\n print len\n putStr.unlines.map show $ ops\n Nothing -> print $ - 1\n\nsolve :: [[Int]] -> Maybe (Int, [Op])\nsolve xss | not $ isValid xss = Nothing\nsolve xss = Just $ solve' xss `min` solve' (transpose xss)\nsolve' xss = (length $ rows ++ cols, map Row rows ++ map Col cols)\n where\n rows = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum xss\n cols = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum.transpose $ map step xss\n\nisValid :: [[Int]] -> Bool\nisValid xss = all(0==).concat.map step.transpose $ map step xss\n\n\nstep xs = map (subtract m) xs\n where\n !m = minimum xs\n\ndata Op = Row Int | Col Int deriving (Eq, Ord)\n\ninstance Show Op where\n show (Row x) = \"row \" ++ show x\n show (Col x) = \"col \" ++ show x\n"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\nimport Control.Applicative\nimport Data.List\n\nmain = do\n _ <- getLine\n css <- map (map read.words).lines <$> getContents\n let res = solve css\n case res of\n Just ops -> do\n print $ length ops\n putStr.unlines.map show $ ops\n Nothing -> print $ -1\n\nsolve :: [[Int]] -> Maybe [Op]\nsolve xss | not $ isValid xss = Nothing\nsolve xss = Just $ map Row rows ++ map Col cols\n where\n rows = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum xss\n cols = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum.transpose $ map step xss\n\nisValid :: [[Int]] -> Bool\nisValid xss = all(0==).concat.map step.transpose $ map step xss\n\n\nstep xs = map (subtract m) xs\n where\n !m = minimum xs\n\ndata Op = Row Int | Col Int\n\ninstance Show Op where\n show (Row x) = \"row \" ++ show x\n show (Col x) = \"col \" ++ show x"}], "src_uid": "b19ab2db46484f0c9b49cf261502bf64"} {"source_code": "{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}\nimport Control.Monad\nimport Control.Monad.ST\nimport Control.Applicative\nimport Control.Arrow\nimport Debug.Trace\nimport Text.Printf\n\nimport Data.List\nimport Data.Int\nimport Data.Bits\nimport Data.Maybe\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Data.ByteString.Char8 as B\n\nreadInt = fromJust . fmap fst . B.readInt\nreadInts = map readInt . B.words <$> B.getLine\nreadIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine\nreadLns :: Read a => IO [a]\nreadLns = map read . words <$> getLine\ncmpFst (a,_) (b,_) = compare a b\ncmpSnd (_,a) (_,b) = compare a b\ncmpLen a b = length a `compare` length b\nswap (a,b) = (b,a)\nl2p (a:b:_) = (a,b)\np2l (a,b) = [a,b]\nitof :: Int -> Double\nitof = fromIntegral\ndefaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e\ndefaultArray = accumArray $ curry snd\nflatten :: [(a,[(b,c)])] -> [((a,b),c)]\nflatten = (=<<) $ uncurry $ fmap . first . (,)\nstepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()\nstepM_ i judge incr step = sub i where \n sub i | judge i = step i >> sub (incr i) | otherwise = return ()\nthru :: Monad m => (v -> m ()) -> v -> m v\nthru m v = m v >> return v\ninf = maxBound `div` 2 :: Int\n\nmain = do\n n <- readLn\n ps <- readInts\n a <- listArray ((1,1),(n,n)) . concat <$> replicateM n getLine\n let a' = expand n a\n let qs = solve n ps a'\n {-\n stepM_ 1 (<=n) (+1) $ \\i -> do\n stepM_ 1 (<=n) (+1) $ \\j -> putChar (a' ! (i,j))\n putChar '\\n'\n -}\n putStrLn $ unwords $ map show qs\n\nexpand :: Int -> UArray (Int,Int) Char -> UArray (Int,Int) Char\nexpand n mat = runSTUArray $ do\n res <- newArray ((1,1),(n,n)) '0'\n stepM_ 1 (<=n) (+1) $ \\s -> do\n let dfs v pv = do\n m <- readArray res (s,v)\n when (m == '0') $ do\n writeArray res (s,v) '1'\n stepM_ 1 (<=n) (+1) $ \\w -> \n when (mat ! (v,w) == '1' && w /= pv) (dfs w v)\n dfs s (-1)\n return res\n\nsolve :: Int -> [Int] -> UArray (Int,Int) Char -> [Int]\nsolve n ps arr = go 1 ps where\n go _ [] = []\n go i (a:as) = \n let cands = [(aj,j) | (j,aj) <- zip [i+1..] as, \n arr ! (i,j) == '1',\n aj < a ]\n in\n if null cands then\n a:go (i+1) as\n else\n let (b,j) = minimum cands in\n b:go (i+1) (g (j-i-1) a as)\n g 0 a (_:l) = a:l\n g j a (b:bs) = b:g (j-1) a bs\n\n\n\n", "positive_code": [{"source_code": "{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Control.Monad.State\nimport Data.Array.IArray\nimport Data.Array.MArray.Safe\nimport Data.Array.ST.Safe\nimport Data.Array.Unboxed\nimport Data.Char\nimport Data.Function\nimport Data.Graph\nimport Data.Int\nimport Data.List\nimport Data.Maybe\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Tree\nimport Data.Tuple\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport qualified Data.ByteString.Char8 as B\n-- import Debug.Trace\n\ngetInts = fmap (map read . words) getLine :: IO [Int]\n-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine\n\nmain = do\n n <- readLn\n p <- getInts\n g <- replicateM n $ map (== '1') <$> getLine\n\n let\n g' = buildG (1, n) $ map fst $ filter snd $ zip [(i, j) | i <- [1..n], j <- [1..n]] $ concat g\n cs = map flatten $ components g'\n\n p' = map snd $ sort $ concat $ map f cs\n where\n f xs = zip (sort xs) $ sort $ map (\\i -> p!!(i-1)) xs\n\n putStrLn $ unwords $ map show p'\n"}, {"source_code": "import qualified Data.Map as Map\n\nmain :: IO ()\nmain = do\n nLine <- getLine\n seqLine <- getLine\n\n let n = read nLine :: Int\n sequ = strToInts seqLine\n \n sets <- readNeighbors n 0 $ initSets n\n printSlots n 0 sets sequ []\n\n\nreadNeighbors :: Int -> Int -> Map.Map Int Int -> IO (Map.Map Int Int)\nreadNeighbors n i sets = do\n if n == 0\n then return sets\n else do\n line <- getLine\n readNeighbors (n-1) (i+1) (unionNeighbors sets i line 0)\n\n\nprintSlots :: Int -> Int -> Map.Map Int Int -> [Int] -> [Int] -> IO ()\nprintSlots n i sets sequ used = do\n if n == 0\n then do\n putStr \"\\n\" \n return ()\n else do\n let (sets2, num, newUsed) = getSlot sets i sequ used\n putStr . show $ num\n putStr \" \"\n printSlots (n-1) (i+1) sets2 sequ newUsed\n\n\nstrToInts :: String -> [Int]\nstrToInts = map read . words\n\ninitSets :: Int -> Map.Map Int Int\ninitSets n = Map.fromList $ zip [0..n-1] [0..n-1]\n\nfindSet :: Map.Map Int Int -> Int -> (Map.Map Int Int, Int)\nfindSet sets i\n | pset == i = (sets, i)\n | otherwise =\n let (sets2, setNum) = findSet sets pset\n in (Map.insert i setNum sets2, setNum) \n where (Just pset) = Map.lookup i sets\n\nisSameSet :: Map.Map Int Int -> Int -> Int -> (Map.Map Int Int, Bool)\nisSameSet sets i j =\n let (sets2, seti) = findSet sets i\n (sets3, setj) = findSet sets2 j\n in (sets3, seti == setj)\n\nunionSet :: Map.Map Int Int -> Int -> Int -> Map.Map Int Int\nunionSet sets i j =\n let (sets2, seti) = findSet sets i\n (sets3, setj) = findSet sets2 j\n in Map.insert seti setj sets3\n\nunionNeighbors :: Map.Map Int Int -> Int -> String -> Int -> Map.Map Int Int\nunionNeighbors sets _ [] _ = sets\nunionNeighbors sets i (x:xs) curr\n | x == '1' = unionNeighbors (unionSet sets i curr) i xs (curr+1)\n | otherwise = unionNeighbors sets i xs (curr+1) \n\ncomponent :: Map.Map Int Int -> Int -> Int -> [Int] -> (Map.Map Int Int, [Int])\ncomponent sets _ (-1) acc = (sets, acc)\ncomponent sets i curr acc\n | sameSet = component sets2 i (curr-1) (curr:acc)\n | otherwise = component sets2 i (curr-1) acc\n where (sets2, sameSet) = isSameSet sets i curr\n \ngetSlot :: Map.Map Int Int -> Int -> [Int] -> [Int] -> (Map.Map Int Int, Int, [Int])\ngetSlot sets i sequ used =\n let maxIdx = (length sequ)-1\n (sets2, comp) = component sets i maxIdx [] \n num = minimum $ filter (\\x -> not $ elem x used) $ map (sequ !!) comp\n in (sets2, num, num:used)\n"}], "negative_code": [], "src_uid": "a67ea891cd6084ceeaace8894cf18e60"} {"source_code": "import Data.Char\n\nf s = do\n let l1 = lines s\n let s1 = tail $ l1\n let n = read $ head l1\n let pat = take n s1\n let str = s1 !! n\n let lck = head $ s1 !! (n+1)\n doit str pat lck 0 ++ \"\\n\"\n\nrepl s l = do\n let r = if toLower l == toLower s then if toLower l == 'a' then 'b' else 'a' else l\n if isUpper s then toUpper r else toLower r\n\ndoit [] _ _ _ = []\ndoit (s:ss) p l r = do\n let z = maximum $ map (\\x -> if prefix x ([s]++ss) then length x else 0) p\n let r' = max r z\n (if r' > 0 then [repl s l] else [s]) ++ doit ss p l (r'-1)\n\nprefix [] _ = True\nprefix _ [] = False\nprefix (p:ps) (s:ss) = if toLower p == toLower s then prefix ps ss else False\n\nmain = interact f\n", "positive_code": [{"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\nimport Data.List\n\nmain = do\n n <- read `liftM` getLine\n forbidden <- replicateM n getLine\n initStr <- getLine\n letter <- head `liftM` getLine\n\n let finalStr = foldl' (\\str forbidden ->\n let occur = strstrs initStr forbidden\n len = length forbidden\n str' = zipWith3 (\\i ch ich ->\n if ch /= ich || not ( any (\\s -> s <= i && i < s + len) occur )\n then ch\n else chooseLetter ch\n ) [0..] str initStr\n in str'\n ) initStr forbidden\n chooseLetter ch =\n let ch' = toLower ch\n letter' = if ch' == letter\n then if ch' == 'a'\n then 'b'\n else 'a'\n else letter\n in ( if isUpper ch then toUpper else toLower ) letter'\n\n putStrLn finalStr\n\n return ()\n\nstrstrs :: [Char] -> [Char] -> [Int]\nstrstrs whole' part' =\n if length whole' < length part'\n then []\n else let\n whole = map toLower whole'\n part = map toLower part'\n len = length part\n crc = sum $ map fromEnum part\n (firstPart, later) = splitAt len whole\n crc0 = sum $ map fromEnum firstPart\n strstrs' _ _ [] _ = []\n strstrs' i (w:ws) (c:cs) crc0 =\n let crc0' = crc0 - fromEnum w + fromEnum c\n laterResult = strstrs' (i+1) ws cs crc0'\n in if crc == crc0' && part == take len ws\n then i : laterResult\n else laterResult\n laterResult = strstrs' 1 whole later crc0\n in if crc == crc0 && part == firstPart\n then 0 : laterResult\n else laterResult\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n patterns <- replicateM n readString\n string <- readString\n letter <- head . BS.unpack <$> readString\n return (patterns, string, letter)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = putStrLn =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (patterns, string, letter) = string'\n where\n intervals = [ (startPos, startPos + len - 1)\n | pattern <- patterns\n , let len = BS.length pattern\n , startPos <- BS.findSubstrings (BS.map toLower pattern) (BS.map toLower string)\n ]\n\n string' = [ if toChange then targetCase else ch\n | (i, ch) <- zip [0..] (BS.unpack string)\n , let toChange = not . null $ filter (flip inRange i) intervals\n , let lowerCh = toLower ch \n , let target = if lowerCh == letter then head (delete lowerCh $ delete letter ['a'..'z']) else letter\n , let targetCase = if isLower ch then target else toUpper target\n ]\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Arrow\nimport Char\no n f=uncurry(++).f.splitAt n\nw=toLower\nu p|p=toUpper|1>0=w\ns([c]:q:f)=(zipWith u$map isUpper q)g\n where\n b|c>'a'='a'|1>0='b'\n j x n|n==0=x|x==c=b|1>0=c\n s=map w q\n r n b|take m(drop n s)==map w b=o n$second$o m$first$map$succ|1>0=id where m=length b\n g=zipWith j s$foldl1(.)((`map`f).r=<<[0..length s])(map(const 0)s)\nmain=interact$s.reverse.tail.lines\n"}], "negative_code": [{"source_code": "import Control.Arrow\nimport Char\no n f=uncurry(++).f.splitAt n\nw=toLower\nu p|p=toUpper|1>0=w\ns([c]:q:f)=(zipWith u$map isUpper q)g\n where\n b|c>'a'='a'|1>0='b'\n j x|x==c=b|1>0=c\n s=map w q\n r n b|take m(drop n s)==map w b=o n$second$o m$first$map$j|1>0=id where m=length b\n g=foldl1(.)((`map`f).r=<<[0..length s])s\nmain=interact$s.reverse.tail.lines\n"}, {"source_code": "import Control.Arrow\nimport Char\no n f=uncurry(++).f.splitAt n\nw=toLower\nu p|p=toUpper|1>0=w\ns([c]:q:f)=(zipWith u$map isUpper q)g\n where\n s=map w q\n r n b|take m(drop n s)==map w b=o n$second$o m$first$map$const c|1>0=id where m=length b\n g=foldl1(.)((`map`f).r=<<[0..length s])s\nmain=interact$s.reverse.tail.lines\n"}, {"source_code": "import Data.Char\n\nf s = do\n let l1 = lines s\n let s1 = tail $ l1\n let n = read $ head l1\n let pat = take n s1\n let str = s1 !! n\n let lck = head $ s1 !! (n+1)\n doit str pat lck 0 ++ \"\\n\"\n\nrepl s l = do\n let r = if l == s then if l == 'a' then 'b' else 'a' else l\n if isUpper s then toUpper r else toLower r\n\ndoit [] _ _ _ = []\ndoit (s:ss) p l r = do\n let z = maximum $ map (\\x -> if prefix x ([s]++ss) then length x else 0) p\n let r' = max r z\n (if r' > 0 then [repl s l] else [s]) ++ doit ss p l (r'-1)\n\nprefix [] _ = True\nprefix _ [] = False\nprefix (p:ps) (s:ss) = if toLower p == toLower s then prefix ps ss else False\n\nmain = interact f\n"}], "src_uid": "258753b00e378df9c6e06692026aadad"} {"source_code": "import Data.Array (listArray, (!), indices)\n\nprocess :: [Int] -> Int\nprocess ps = maximum heights\n where\n n = length ps\n ps' = listArray (1,n) ps\n heights = listArray (1,n) [height i | i <- indices ps']\n height i\n | p == -1 = 1\n | otherwise = 1 + (heights ! p)\n where p = ps' ! i\n\nreadInt :: String -> Int\nreadInt = read\n\nmain :: IO ()\nmain = do\n n <- fmap readInt getLine\n ps <- fmap (map readInt.words) getContents\n print $ process ps", "positive_code": [{"source_code": "import Data.Array\nimport Data.Functor ((<$>))\n\nreadInts :: IO [Int]\nreadInts = map read . words <$> getContents\n \nbuildArray (count : input) =\n array (1, count) $ zip [1..] input\n\nheights arr =\n let bs@(start, end) = bounds arr\n result = array bs [(i, f i) | i <- [start..end]]\n f i =\n case (arr ! i) of\n -1 -> 1\n next -> (result ! next) + 1\n in result\n\nmain :: IO ()\nmain =\n do input <- readInts\n print . maximum . elems . heights $ buildArray input\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Array\nimport Data.List\n\nmain = do\n n <- liftM read getLine\n parr <- liftM (listArray (1,n) . map read) (replicateM n getLine) :: IO (Array Int Int)\n\n let darr = listArray (1,n) $ map (\\i ->\n let p = parr ! i\n in if p == -1\n then 1\n else 1 + darr ! p\n ) [1..n]\n\n --putStrLn $ show darr\n putStrLn $ show $ maximum $ elems darr\n"}, {"source_code": "import qualified Data.ByteString.Lazy.Char8 as C\nimport IO\nimport Data.Maybe\nimport Data.Array\n\nimport Debug.Trace\n\ndepth lst i = d ! i\n\twhere\n\t\tn = length lst - 1\n\t\tinit = array (1, n) [(i, -1) | i <- [1..n]]\n\t\td = foldl (\\memo i -> depth' memo i) init [1..n]\n\t\tdepth' memo i\n\t\t\t| memo ! i /= -1 = memo\n\t\t\t| lst !! i == -1 = memo // [(i, 1)]\n\t\t\t| otherwise = let j = lst !! i in let newmemo = depth' memo j in newmemo // [(i, newmemo ! j + 1)]\n\nmain = do\n\tinput <- fmap C.lines $ C.hGetContents stdin\n\tlet n = (fst . fromJust . C.readInt . head) input\n\tlet lst = (map (fst . fromJust . C.readInt) . tail) input\n\t(putStrLn . show . foldl max 0) $ map (depth (0:lst)) [1..n]\n"}, {"source_code": "import Data.Map((!),fromList)\ns(n:t)=map d$[1..n]where d(-1)=0;d i=1+d(fromList(zip[1..]t)!i)\nmain=interact$show.maximum.s.map read.lines"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverlappingInstances #-}\n\nmodule Main where\n\nimport Control.Applicative\nimport Control.Category ((>>>))\nimport Control.Monad\nimport Control.Monad.Trans.State\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport Data.Graph\nimport qualified Data.HashMap.Lazy as HM\nimport Data.List\nimport Data.Maybe\nimport Data.Tree\n\ntype BString = B.ByteString\n\ntype Result = Int\n\nsolve :: Graph -> Result\nsolve graph = maximum [(dfs graph >>> head >>> flatten >>> length) [x] | x <- vertices graph]\n\nconstruct :: [Int] -> Graph\nconstruct xs = graph\n where (graph, _, _) = graphFromEdges [ (i, i, if x == -1 then [] else [x])\n | (i, x) <- zip [1..] xs]\n\nprocess :: State Reader Result\nprocess = do\n n <- parse\n nexts <- replicateM n parse\n return $ solve $ construct nexts\n\nmain :: IO ()\nmain = do\n input <- B.lines <$> B.getContents\n print $ evalState process input\n\nsay :: Display a => a -> IO ()\nsay = putStrLn . display\n\ntype Reader = [BString]\n\nclass Display a =>\n EIO a where\n parse :: State Reader a\n parse = state $ \\(line:rest) -> (scan line, rest)\n\ninstance EIO Int\ninstance EIO [Int]\ninstance EIO BString\n\nclass (Read a, Show a) =>\n Display a where\n display :: a -> String\n scan :: BString -> a\n display = show\n scan = read . B.unpack\n\ninstance Display String where\n display = id\n\ninstance Display BString where\n display = B.unpack\n scan = id\n\ninstance Display Int where\n scan = fst . fromJust . B.readInt\n\ninstance Display [Int] where\n display = unwords . map display\n scan = unfoldr (B.readInt . B.dropWhile (== ' '))\n\ninstance Display [[Int]] where\n display = unlines . map display\n\n"}, {"source_code": "import Data.List\nimport Data.Tree\nimport Data.Int\nimport Data.Maybe\nimport Data.Char\nimport Control.Monad\nimport Control.Monad.ST.Safe\nimport Data.Array\nimport Data.Array.ST.Safe\nimport Data.STRef\nmain= readsolveprint\nreadsolveprint::IO()\nreadsolveprint = interact $ solve. map read.(\\(x:xs)-> x:take (read x) xs).lines\nsolve :: [Int]-> String\nsolve (x:xs) = show $ slv1 [-1]\n where \n zs=zip [1..] xs\n slv1 [] = -1\n slv1 xs = 1+ slv1 [z1|x<-xs,(z1,z2)<-zs,z2==x]"}, {"source_code": "module Main where\nimport Control.Monad\nimport Data.Graph\nimport Data.Tree\n\nmain = do\n n <- readLn :: IO Int\n ps <- replicateM n ( (\\x -> if x == \"-1\" then 0 else read x :: Int ) <$> getLine)\n print $ pred $ length $ levels $ head $ components $ buildG (0,n) $ zip [1..] ps "}, {"source_code": "import Control.Applicative ((<$>))\nimport Debug.Trace (trace)\nimport Data.Array (listArray, elems, (!))\n\n-- 115A\n\nsolve :: [Int] -> Int\nsolve (n:connections) =\n maximum $ elems levels\n where\n parentArr = listArray (1, n) connections\n level v =\n let parent = parentArr ! v in\n if parent == -1 then 1 else 1 + (levels ! parent)\n levels = listArray (1, n) [level v | v <- [1..n]]\n\nmain =\n putStrLn . show . solve . map read . lines =<< getContents\n"}, {"source_code": "{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}\n{-# OPTIONS_GHC -O2 #-}\n\nimport Data.List\nimport Data.Maybe\nimport Data.Char\nimport Data.Array.IArray\nimport Data.Array.Unboxed (UArray)\nimport Data.Int\nimport Data.Ratio\nimport Data.Bits\nimport Data.Function\nimport Data.Ord\n--import Control.Monad.State\nimport Control.Monad\nimport Control.Applicative\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.IntMap (IntMap)\nimport qualified Data.IntMap as IntMap\nimport Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))\nimport qualified Data.Sequence as Seq\nimport qualified Data.Foldable as F\nimport Data.Graph\n\nparseInput = do \n n <- readInt\n fa <- replicateM n readInt\n return (n, fa)\n where\n readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace\n readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace\n readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace\n readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln\n isEoln ch = ch == '\\r' || ch == '\\n'\n\nmain = print =<< solve . evalState parseInput <$> BS.getContents\n\nsolve (n, fa) = maximum $ map getDepth [1..n]\n where\n f = listArray (1, n) fa :: UArray Int Int\n\n getDepth = (cache!)\n where\n bnds = (1, n)\n\n cache = listArray bnds $ map go $ range bnds :: Array Int Int\n\n go x | f ! x == -1 = 1\n | otherwise = getDepth (f ! x) + 1\n\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n----------------------------------------------------------------------\n\nclass (Monad m) => MonadState s m | m -> s where\n\tget :: m s\n\tput :: s -> m ()\n\nmodify :: (MonadState s m) => (s -> s) -> m ()\nmodify f = do\n\ts <- get\n\tput (f s)\n\ngets :: (MonadState s m) => (s -> a) -> m a\ngets f = do\n\ts <- get\n\treturn (f s)\n\nnewtype State s a = State { runState :: s -> (a, s) }\n\ninstance Functor (State s) where\n\tfmap f m = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin (f a, s')\n\ninstance Applicative (State s) where\n pure = return\n (<*>) = ap\n\ninstance Monad (State s) where\n\treturn a = State $ \\s -> (a, s)\n\tm >>= k = State $ \\s -> let\n\t\t(a, s') = runState m s\n\t\tin runState (k a) s'\n\ninstance MonadState s (State s) where\n\tget = State $ \\s -> (s, s)\n\tput s = State $ \\_ -> ((), s)\n\nevalState :: State s a -> s -> a\nevalState m s = fst (runState m s)\n\nexecState :: State s a -> s -> s\nexecState m s = snd (runState m s)\n\nmapState :: ((a, s) -> (b, s)) -> State s a -> State s b\nmapState f m = State $ f . runState m\n\nwithState :: (s -> s) -> State s a -> State s a\nwithState f m = State $ runState m . f\n\nstate = State\n"}, {"source_code": "import Control.Applicative ((<$>), (<*>))\nimport qualified Data.Array as A\n\nmain :: IO ()\nmain = print =<< solve <$> readLn <*> (map read <$> lines <$> getContents)\n\nsolve :: Integer -> [Integer] -> Integer\nsolve n ps = maximum $ A.elems dp\n where ps' = A.listArray (1, n) ps\n dp = A.array (1, n) [ (i, if ps' A.! i == -1 then 1 else 1 + dp A.! (ps' A.! i)) | i <- [1..n] ]\n"}, {"source_code": "main = interact $ show . solve . map read . tail . words\nsolve ss = maximum hs where\n hs = map (h . pred) ss\n h (-2) = 1\n h i = 1 + hs!!i\n"}, {"source_code": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# OPTIONS_GHC -O2 #-}\nimport Debug.Trace\nimport Data.List\nimport Data.Array.ST\nimport Control.Monad.ST\nimport Control.Monad\nimport Data.Array\nimport Data.Char\nclass Expression a where scan' :: String -> a; showans :: a -> String\ninstance Expression Int where scan' = read; showans = show\ninstance Expression Char where scan' (x:_) = x;showans = (:[])\ninstance Expression Float where scan' = read;showans = show\ninstance Expression Double where scan' = read;showans = show\ninstance Expression Integer where scan' = read;showans = show\ninstance Expression String where scan' = id;showans = id\ninstance (Expression a,Expression b) => Expression (a,b) where\n scan' = (\\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y\ninstance (Expression a,Expression b,Expression c) => Expression (a,b,c) where\n scan' = (\\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where\n scan' = (\\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z\ninstance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where\n scan' = (\\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z\nscan :: (Expression a) => IO a; scan = getLine>>=(return.scan')\nscans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan\nscanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words\nscanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist\nputAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans\nputAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn\n\nsolve :: Int -> [Int] -> Int\nsolve n l = maximum $ map (dfs.fst) employers\n where\n dfs v = case inferior!v of\n [] -> 1\n inf -> (+1) $ maximum $ map dfs inf\n (employers,employees) = partition ((-1==).snd) (zip [1..n] l)\n inferior = runSTArray $ do\n ary <- newArray (1,n) []\n mapM_ (\\(i,sp) -> do {l <- readArray ary sp;writeArray ary sp (i:l)}) employees\n return ary\n\nmain = do n <- scan :: IO Int\n l <- scans n ::IO [Int]\n print $ solve n l"}, {"source_code": "import Data.List\nimport qualified Data.Map as Map\nimport Data.Map ((!))\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntype Z = Int\n\ntraceS a b = trace (show a) b\n\nmLength :: Map.Map Z Z -> Z -> Z\nmLength hs (-1) = 0\nmLength hs i = mLength hs (hs!i) + 1\n\nmain = do\n n <- read <$> getLine\n hs <- replicateM n (read <$> getLine)\n let m = Map.fromList (zip [1..] hs)\n print $ maximum (map (mLength m) [1..n])\n"}, {"source_code": "import Data.List\nimport Control.Applicative\nimport qualified Data.Map as Map\nimport Data.Map((!))\n\np(-1)=Nothing\np n=Just n\nd m(-1)=0\nd m i=d m(m!i)+1\ns' n m=maximum$map(d m)[1..n]\ns(n:t)=s' n$Map.fromList(zip[1..]t)\n\nmain=interact$show.s.map read.lines"}, {"source_code": "import Data.Map((!),fromList)\ns(n:t)=map d$[1..n]where d(-1)=0;d i=1+d(fromList(zip[1..]t)!i)\nmain=interact$show.maximum.s.map read.lines"}, {"source_code": "import Data.Map((!),fromList)\ns(n:t)=map d$[1..n]where d(-1)=0;d i=1+d(fromList(zip[1..]t)!i)\nmain=interact$show.maximum.s.map read.lines"}, {"source_code": "import Control.Applicative\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Array\n\n\nleng as a | a== (-1) = 1\n | otherwise = 1+ leng as (as!a)\t\n\nmain = do\n\t\tn<-read <$> getLine ::IO Int\n\t\ts<-map read <$> replicateM n getLine ::IO [Int]\n\t\tlet as = listArray (1,length s) s\n\t\tprint $ maximum $ map (leng as) s \n"}, {"source_code": "import Data.List (partition)\nimport Control.Monad (foldM)\nimport qualified Data.IntSet as S\nf l h [] = l\nf l h s = let (l1, l2) = partition ((`S.member` h).snd) s in f (l+1) (S.fromList $ map fst l1) l2\nmain = do\n n <- read `fmap` getLine\n (h, s) <- foldM (\\(h, s) i -> do\n c <- read `fmap` getLine\n return $ if c == -1 then (i `S.insert` h, s) else (h, (i, c):s)) (S.empty, []) [1..n]\n print $ f 1 h s\n"}, {"source_code": "{-# OPTIONS -O2 #-}\nmain = do\n s <- getContents\n let (n:nums) = map read $ words s :: [Int]\n print $ solve [i|i<-[1..n], nums !! (i-1) == -1] [(i, j)|(i, j)<- zip [1..] nums, j /= -1]\n\nsolve :: [Int] -> [(Int, Int)] -> Int\nsolve _ [] = 1\nsolve poss left = 1 + solve x y\n where\n x = [pos | (pos, i) <- left, elem i poss]\n y = [(pos, i) | (pos, i) <- left, notElem pos x]"}], "negative_code": [{"source_code": "import Data.Tree (drawTree, levels)\nimport Data.Graph (buildG, vertices, components)\nimport Control.Applicative ((<$>))\nimport Debug.Trace (trace)\n\n-- 115A\n\nsolve :: [Int] -> Int\nsolve (n:connections) =\n comps\n where\n track q = trace (show q) q\n edges = filter (\\x -> snd x > 0) $ zip [1..] connections\n graph = buildG (1,n) edges\n comps = maximum $ map (length . levels) $ components graph\n\nmain =\n putStrLn . show . solve . map read . lines =<< getContents\n"}, {"source_code": "import Data.Graph\n\nmain = do\n putStrLn $ show $ buildG (1,3) [(2,3)]\n"}, {"source_code": "{-# OPTIONS -O2 #-}\nmain = do\n s <- getContents\n let (n:nums) = map read $ words s :: [Int]\n print $ solve [i|i<-[1..n], nums !! (i-1) == -1] [(i, j)|(i, j)<- zip [1..] nums, j /= -1]\n\nsolve _ [] = 1\nsolve poss left = 1 + solve x y\n where\n x = [pos | (pos, i) <- left, elem i poss]\n y = [(pos, i) | (pos, i) <- left, elem pos x]"}, {"source_code": "import Data.List\nimport Control.Monad\nimport Control.Applicative\nimport Debug.Trace\n\ntype Z = Integer\n\nmLength hs x\n | (!!) hs x == -1 = 1\n | otherwise = 1 + mLength hs ((hs !! x) - 1)\n\nmain = do\n n <- read <$> getLine\n hs <- replicateM n (read <$> getLine)\n return $ maximum (map (mLength hs) [0..(length hs)-1])\n"}], "src_uid": "8d911f79dde31f2c6f62e73b925e6996"} {"source_code": "-- ID: 702E (Analysis of Pathes in Functional Graph)\n-- URL: http://codeforces.com/contest/702/problem/E\n\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.Char\nimport Numeric\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Exception\nimport Control.DeepSeq\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\ndata Node = Node !Int !Int64 !Int64 -- (to, cost, minWeight)\ninstance NFData Node where\n rnf (Node a b c) = rnf a `seq` rnf b `seq` rnf c\ntype State = Array Int Node\n\ntoBinary :: Int64 -> String\ntoBinary x = showIntAtBase 2 intToDigit x \"\"\n\nvalid (state, digit) = digit == '1'\n\nmain = do\n [n', k'] <- words `fmap` getLine\n let n = read n' :: Int\n let k = read k' :: Int64\n let pos = toBinary k\n evaluate pos\n nexts <- listArray (0,n-1) `fmap` getInts :: IO (Array Int Int)\n costs <- listArray (0,n-1) `fmap` getInt64s :: IO (Array Int Int64)\n let state0 = initState n nexts costs\n let states = scanl (step n) state0 [1..length pos-1]\n let valids = fst $ unzip $ filter valid (zip states (reverse pos))\n let soln = findSoln valids n\n evaluate $ force states\n evaluate $ force valids\n evaluate $ force soln\n forM_ [0..n-1] $ \\i -> do\n let Node _ !si !mi = soln ! i\n putStr (show si)\n putChar ' '\n putStrLn (show mi)\n\n-- num nodes, next nodes, edge weights -> initial iteration (state after very first move)\ninitState :: Int -> Array Int Int -> Array Int Int64 -> State\ninitState n nexts costs = listArray (0,n-1) [Node (nexts ! i) cost cost | i <- [0..n-1], let cost = costs ! i]\n\nstep :: Int -> State -> Int -> State\nstep n state _ = listArray (0,n-1) [f i | i <- [0..n-1]] where\n f i = Node to2 (len1+len2) (min min1 min2) where\n Node to1 len1 min1 = state ! i\n Node to2 len2 min2 = state ! to1\n\nfindSoln :: [State] -> Int -> Array Int Node\nfindSoln states n = f states $ listArray (0,n-1) [Node i 0 (10^8+1) | i <- [0..n-1]] where\n f [] soln = soln\n f (st:states) curr = f states $\n listArray (0,n-1) [Node to1 (s+len1) (min m min1) | i <- [0..n-1],\n let Node to s m = curr ! i,\n let Node to1 len1 min1 = st ! to]\n", "positive_code": [{"source_code": "-- ID: 702E (Analysis of Pathes in Functional Graph)\n-- URL: http://codeforces.com/contest/702/problem/E\n\n{-# LANGUAGE BangPatterns #-}\n\nimport System.IO\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.Char\nimport Numeric\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Exception\nimport Control.DeepSeq\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\ndata Node = Node !Int !Int64 !Int64 -- (to, cost, minWeight)\ninstance NFData Node where\n rnf (Node !a !b !c) = rnf a `seq` rnf b `seq` rnf c\ntype State = Array Int Node\n\ntoBinary :: Int64 -> String\ntoBinary x = showIntAtBase 2 intToDigit x \"\"\n\nvalid (state, digit) = digit == '1'\n\nmain = do\n [n', k'] <- words `fmap` getLine\n let n = read n' :: Int\n let k = read k' :: Int64\n let pos = toBinary k\n evaluate pos\n nexts <- listArray (0,n-1) `fmap` getInts :: IO (Array Int Int)\n costs <- listArray (0,n-1) `fmap` getInt64s :: IO (Array Int Int64)\n let state0 = initState n nexts costs\n let states = scanl (step n) state0 [1..length pos]\n let valids = fst $ unzip $ filter valid (zip states (reverse pos))\n let soln = findSoln valids n\n --hPutStrLn stderr \"start calc\"\n evaluate $ force states\n evaluate $ force valids\n evaluate $ force soln\n --hPutStrLn stderr \"calc done\"\n forM_ [0..n-1] $ \\i -> do\n let Node _ !si !mi = soln ! i\n putStr (show si)\n putChar ' '\n putStrLn (show mi)\n --hPutStrLn stderr \"print done\"\n\n-- num nodes, next nodes, edge weights -> initial iteration (state after very first move)\ninitState :: Int -> Array Int Int -> Array Int Int64 -> State\ninitState n nexts costs = listArray (0,n-1) [Node (nexts ! i) cost cost | i <- [0..n-1], let cost = costs ! i]\n\nstep :: Int -> State -> Int -> State\nstep n state _ = listArray (0,n-1) [f i | i <- [0..n-1]] where\n f i = Node to2 (len1+len2) (min min1 min2) where\n Node !to1 !len1 !min1 = state ! i\n Node !to2 !len2 !min2 = state ! to1\n\nfindSoln :: [State] -> Int -> Array Int Node\nfindSoln states n = f states $ listArray (0,n-1) [Node i 0 (10^8+1) | i <- [0..n-1]] where\n f [] soln = soln\n f (st:states) curr = f states $\n listArray (0,n-1) [Node to1 (s+len1) (min m min1) | i <- [0..n-1],\n let Node !to !s !m = curr ! i,\n let Node !to1 !len1 !min1 = st ! to]\n"}, {"source_code": "-- ID: 702E (Analysis of Pathes in Functional Graph)\n-- URL: http://codeforces.com/contest/702/problem/E\n\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.Char\nimport Numeric\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Exception\nimport Control.DeepSeq\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\ndata Node = Node {-# UNPACK #-} !Int {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64 -- (to, cost, minWeight)\ninstance NFData Node where\n rnf (Node a b c) = rnf a `seq` rnf b `seq` rnf c\ntype State = Array Int Node\n\ntoBinary :: Int64 -> String\ntoBinary x = showIntAtBase 2 intToDigit x \"\"\n\nvalid (state, digit) = digit == '1'\n\nmain = do\n [n', k'] <- words `fmap` getLine\n let n = read n' :: Int\n let k = read k' :: Int64\n let pos = toBinary k\n evaluate pos\n nexts <- listArray (0,n-1) `fmap` getInts :: IO (Array Int Int)\n costs <- listArray (0,n-1) `fmap` getInt64s :: IO (Array Int Int64)\n let state0 = initState n nexts costs\n let states = scanl (step n) state0 [1..length pos-1]\n let valids = fst $ unzip $ filter valid (zip states (reverse pos))\n let soln = findSoln valids n\n evaluate $ force states\n evaluate $ force valids\n evaluate $ force soln\n forM_ [0..n-1] $ \\i -> do\n let Node _ !si !mi = soln ! i\n putStr (show si)\n putChar ' '\n putStrLn (show mi)\n\n-- num nodes, next nodes, edge weights -> initial iteration (state after very first move)\ninitState :: Int -> Array Int Int -> Array Int Int64 -> State\ninitState n nexts costs = listArray (0,n-1) [Node (nexts ! i) cost cost | i <- [0..n-1], let cost = costs ! i]\n\nstep :: Int -> State -> Int -> State\nstep n state _ = listArray (0,n-1) [f i | i <- [0..n-1]] where\n f i = Node to2 (len1+len2) (min min1 min2) where\n Node to1 len1 min1 = state ! i\n Node to2 len2 min2 = state ! to1\n\nfindSoln :: [State] -> Int -> Array Int Node\nfindSoln states n = f states $ listArray (0,n-1) [Node i 0 (10^8+1) | i <- [0..n-1]] where\n f [] soln = soln\n f (st:states) curr = f states $\n listArray (0,n-1) [Node to1 (s+len1) (min m min1) | i <- [0..n-1],\n let Node to s m = curr ! i,\n let Node to1 len1 min1 = st ! to]\n"}, {"source_code": "{-# LANGUAGE FlexibleInstances #-}\n\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as BS\n\ntype Vec = (UArray Int Int, UArray Int Int64, UArray Int Int64)\n\ninstance Num Vec where\n (a1, b1, c1) * (a2, b2, c2) = (listArray x [a1 ! (a2 ! i) | i <- [0 .. n']], listArray x [(b1 ! (a2 ! i)) + (b2 ! i) | i <- [0 .. n']], listArray x [min (c1 ! (a2 ! i)) (c2 ! i) | i <- [0 .. n']])\n where\n x@(_, n') = bounds a1\n \n\nreadInts :: Integral a => IO [a]\nreadInts = (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) `fmap` BS.getLine\n\nmain = do\n [n, k] <- (map read . words) `fmap` getLine :: IO [Int64]\n fs <- readInts\n ws <- readInts\n let (_, b, c) = ((listArray x fs, listArray x ws, listArray x ws) :: Vec) ^ k\n x = (0, fromIntegral $ n - 1 :: Int)\n mapM_ putStrLn [show y ++ \" \" ++ show z | (y, z) <- zip (elems b) (elems c)]\n"}, {"source_code": "-- ID: 702E (Analysis of Pathes in Functional Graph)\n-- URL: http://codeforces.com/contest/702/problem/E\n\n{-# LANGUAGE BangPatterns #-}\n\nimport System.IO\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.Char\nimport Numeric\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Exception\nimport Control.DeepSeq\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\ndata Node = Node !Int !Int64 !Int64 -- (to, cost, minWeight)\ninstance NFData Node where\n rnf (Node a b c) = rnf a `seq` rnf b `seq` rnf c\ntype State = Array Int Node\n\ntoBinary :: Int64 -> String\ntoBinary x = showIntAtBase 2 intToDigit x \"\"\n\nvalid (state, digit) = digit == '1'\n\nmain = do\n [n', k'] <- words `fmap` getLine\n let n = read n' :: Int\n let k = read k' :: Int64\n let pos = toBinary k\n evaluate pos\n nexts <- listArray (0,n-1) `fmap` getInts :: IO (Array Int Int)\n costs <- listArray (0,n-1) `fmap` getInt64s :: IO (Array Int Int64)\n let state0 = initState n nexts costs\n let states = scanl (step n) state0 [1..length pos]\n let valids = fst $ unzip $ filter valid (zip states (reverse pos))\n let soln = findSoln valids n\n --hPutStrLn stderr \"start calc\"\n evaluate $ force states\n evaluate $ force valids\n evaluate $ force soln\n --hPutStrLn stderr \"calc done\"\n forM_ [0..n-1] $ \\i -> do\n let Node _ !si !mi = soln ! i\n putStr (show si)\n putChar ' '\n putStrLn (show mi)\n --hPutStrLn stderr \"print done\"\n\n-- num nodes, next nodes, edge weights -> initial iteration (state after very first move)\ninitState :: Int -> Array Int Int -> Array Int Int64 -> State\ninitState n nexts costs = listArray (0,n-1) [Node (nexts ! i) cost cost | i <- [0..n-1], let cost = costs ! i]\n\nstep :: Int -> State -> Int -> State\nstep n state _ = listArray (0,n-1) [f i | i <- [0..n-1]] where\n f i = Node to2 (len1+len2) (min min1 min2) where\n Node to1 len1 min1 = state ! i\n Node to2 len2 min2 = state ! to1\n\nfindSoln :: [State] -> Int -> Array Int Node\nfindSoln states n = f states $ listArray (0,n-1) [Node i 0 (10^8+1) | i <- [0..n-1]] where\n f [] soln = soln\n f (st:states) curr = f states $\n listArray (0,n-1) [Node to1 (s+len1) (min m min1) | i <- [0..n-1],\n let Node to s m = curr ! i,\n let Node to1 len1 min1 = st ! to]\n"}, {"source_code": "-- ID: 702E (Analysis of Pathes in Functional Graph)\n-- URL: http://codeforces.com/contest/702/problem/E\n\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.Char\nimport Numeric\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Exception\nimport Control.DeepSeq\nimport System.IO\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\ndata Node = Node !Int !Int64 !Int64 -- (to, cost, minWeight)\ninstance NFData Node where\n rnf (Node a b c) = rnf a `seq` rnf b `seq` rnf c\ntype State = Array Int Node\n\ntoBinary :: Int64 -> String\ntoBinary x = showIntAtBase 2 intToDigit x \"\"\n\nvalid (state, digit) = digit == '1'\n\nmain = do\n [n', k'] <- words `fmap` getLine\n let n = read n' :: Int\n let k = read k' :: Int64\n let pos = toBinary k\n evaluate pos\n nexts <- listArray (0,n-1) `fmap` getInts :: IO (Array Int Int)\n costs <- listArray (0,n-1) `fmap` getInt64s :: IO (Array Int Int64)\n let state0 = initState n nexts costs\n let states = scanl (step n) state0 [1..length pos]\n let valids = fst $ unzip $ filter valid (zip states (reverse pos))\n let soln = findSoln valids n\n --hPutStrLn stderr \"start calc\"\n evaluate $ force states\n evaluate $ force valids\n evaluate $ force soln\n --hPutStrLn stderr \"calc done\"\n forM_ [0..n-1] $ \\i -> do\n let Node _ si mi = soln ! i\n putStr (show si)\n putChar ' '\n putStrLn (show mi)\n --hPutStrLn stderr \"print done\"\n\n-- num nodes, next nodes, edge weights -> initial iteration (state after very first move)\ninitState :: Int -> Array Int Int -> Array Int Int64 -> State\ninitState n nexts costs = listArray (0,n-1) [Node (nexts ! i) cost cost | i <- [0..n-1], let cost = costs ! i]\n\nstep :: Int -> State -> Int -> State\nstep n state _ = listArray (0,n-1) [f i | i <- [0..n-1]] where\n f i = Node to2 (len1+len2) (min min1 min2) where\n Node to1 len1 min1 = state ! i\n Node to2 len2 min2 = state ! to1\n\nfindSoln :: [State] -> Int -> Array Int Node\nfindSoln states n = f states $ listArray (0,n-1) [Node i 0 (10^8+1) | i <- [0..n-1]] where\n f [] soln = soln\n f (st:states) curr = f states $\n listArray (0,n-1) [Node to1 (s+len1) (min m min1) | i <- [0..n-1],\n let Node to s m = curr ! i,\n let Node to1 len1 min1 = st ! to]\n"}, {"source_code": "-- ID: 702E (Analysis of Pathes in Functional Graph)\n-- URL: http://codeforces.com/contest/702/problem/E\n\n{-# LANGUAGE BangPatterns #-}\n\nimport System.IO\n\nimport Control.Monad\nimport Data.Maybe\nimport Data.Array\nimport Data.Int\nimport Data.Char\nimport Numeric\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Char8 as BS8\nimport Control.Exception\nimport Control.DeepSeq\n\ngetInt = read `fmap` getLine :: IO Int\ngetInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]\ngetInt64s = (map (fromIntegral . fst . fromJust . BS8.readInteger) . BS8.words) `fmap` BS.getLine :: IO [Int64]\n\ndata Node = Node !Int !Int64 !Int64 -- (to, cost, minWeight)\ninstance NFData Node where\n rnf (Node a b c) = rnf a `seq` rnf b `seq` rnf c\ntype State = Array Int Node\n\ntoBinary :: Int64 -> String\ntoBinary x = showIntAtBase 2 intToDigit x \"\"\n\nvalid (state, digit) = digit == '1'\n\nmain = do\n [n', k'] <- words `fmap` getLine\n let n = read n' :: Int\n let k = read k' :: Int64\n let pos = toBinary k\n evaluate pos\n nexts <- listArray (0,n-1) `fmap` getInts :: IO (Array Int Int)\n costs <- listArray (0,n-1) `fmap` getInt64s :: IO (Array Int Int64)\n let state0 = initState n nexts costs\n let states = scanl (step n) state0 [1..length pos]\n let valids = fst $ unzip $ filter valid (zip states (reverse pos))\n let soln = findSoln valids n\n --hPutStrLn stderr \"start calc\"\n evaluate $ force states\n evaluate $ force valids\n evaluate $ force soln\n --hPutStrLn stderr \"calc done\"\n forM_ [0..n-1] $ \\i -> do\n let Node _ !si !mi = soln ! i\n putStr (show si)\n putChar ' '\n putStrLn (show mi)\n --hPutStrLn stderr \"print done\"\n\n-- num nodes, next nodes, edge weights -> initial iteration (state after very first move)\ninitState :: Int -> Array Int Int -> Array Int Int64 -> State\ninitState n nexts costs = listArray (0,n-1) [Node (nexts ! i) cost cost | i <- [0..n-1], let cost = costs ! i]\n\nstep :: Int -> State -> Int -> State\nstep n state _ = listArray (0,n-1) [f i | i <- [0..n-1]] where\n f i = Node to2 (len1+len2) (min min1 min2) where\n Node to1 len1 min1 = state ! i\n Node to2 len2 min2 = state ! to1\n\nfindSoln :: [State] -> Int -> Array Int Node\nfindSoln states n = f states $ listArray (0,n-1) [Node i 0 (10^8+1) | i <- [0..n-1]] where\n f [] soln = soln\n f (st:states) curr = f states $\n listArray (0,n-1) [Node to1 (s+len1) (min m min1) | i <- [0..n-1],\n let Node to s m = curr ! i,\n let Node to1 len1 min1 = st ! to]"}, {"source_code": "import Control.Applicative\nimport Data.Array.Unboxed\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = map (fromIntegral . fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nmain = do\n [n, k] <- map read . words <$> getLine :: IO [Int64]\n fs <- readInts\n ws <- readInts\n let vecs :: [(UArray Int Int, UArray Int Int64, UArray Int Int64)]\n vecs = iterate (\\(a, b, c) -> (array (0, n') [(i, a ! (a ! i)) | i <- [0 .. n']], array (0, n') [(i, b ! (a ! i) + b ! i) | i <- [0 .. n']], array (0, n') [(i, min (c ! (a ! i)) (c ! i)) | i <- [0 .. n']])) $ let f = listArray (0, n') in (listArray (0, n') fs, f ws, f ws)\n ans h ((a, b, c) : vs) i acc@(accb, accc)\n | odd h = ans (h `quot` 2) vs (a ! i) $ ((b ! i) + accb, min accc $ c ! i)\n | h == 0 = acc\n | otherwise = ans (h `quot` 2) vs i acc\n n' = fromIntegral n - 1 :: Int\n sequence_ [putStrLn . (\\(y, z) -> (show y) ++ \" \" ++ (show z)) $ ans k vecs i (0, 10 ^ 9) | i <- [0 .. n']]\n"}, {"source_code": "import Data.Array.Unboxed\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) `fmap` BS.getLine\n\nmain = do\n [n, k] <- (map read . words) `fmap` getLine :: IO [Int64]\n fs <- readInts\n ws <- readInts\n let vecs :: [(UArray Int Int, UArray Int Int64, UArray Int Int64)]\n vecs =\n iterate\n ( \\(a, b, c) ->\n ( array (0, n') [(i, a ! (a ! i)) | i <- [0 .. n']]\n , array (0, n') [(i, b ! (a ! i) + b ! i) | i <- [0 .. n']]\n , array (0, n') [(i, min (c ! (a ! i)) (c ! i)) | i <- [0 .. n']]))\n $ (listArray (0, n') fs, listArray (0, n') ws, listArray (0, n') ws)\n ans h ((a, b, c) : vs) i (accb, accc)\n | odd h = ans (h `quot` 2) vs (a ! i) $ ((b ! i) + accb, min accc $ c ! i)\n | h == 0 = show accb ++ \" \" ++ show accc\n | otherwise = ans (h `quot` 2) vs i (accb, accc)\n n' = fromIntegral n - 1 :: Int\n mapM_ putStrLn [ans k vecs i (0, 10 ^ 9) | i <- [0 .. n']]\n"}], "negative_code": [{"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Word\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = map (fromIntegral . fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nmain = do\n [n, k] <- readInts\n fs <- readInts\n ws <- readInts :: IO [Word64]\n let mkArray :: (a -> a -> a) -> [a] -> Array (Int, Int) a\n mkArray f l = let a = array ((0, 0), (34, n - 1)) $ zip (zip (repeat 0) [0 ..]) l ++ [((j, i), (a ! (j - 1, jump ! (j - 1, i))) `f` (a ! (j - 1, i))) | j <- [1 .. 34], i <- [0 .. n - 1]] in a\n jump = mkArray const fs\n sjump = mkArray (+) ws\n mjump = mkArray min ws\n ans f h j i arr acc\n | h == 0 = acc\n | even h = ans f (h `quot` 2) (j + 1) i arr acc\n | otherwise = ans f (h `quot` 2) (j + 1) (jump ! (j, i)) arr $ acc `f` (arr ! (j, i))\n sequence_ [putStrLn . unwords $ map show [ans (+) (fromIntegral k :: Word64) 0 i sjump 0, ans min (fromIntegral k :: Word64) 0 i mjump (10 ^ 9)] | i <- [0 .. n - 1]]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = map (fromIntegral . fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nmain = do\n [n, k] <- readInts :: IO [Int64]\n fs <- readInts\n ws <- readInts :: IO [Int64]\n let mkArray :: (a -> a -> a) -> [a] -> Array (Int, Int) a\n mkArray f l = let a = array ((0, 0), (34, n')) $ zip (zip (repeat 0) [0 ..]) l ++ [((j, i), (a ! (j - 1, jump ! (j - 1, i))) `f` (a ! (j - 1, i))) | j <- [1 .. 34], i <- [0 .. n']] in a\n jump = mkArray const fs\n sjump = mkArray (+) ws\n mjump = mkArray min ws\n ans f h j i arr acc\n | h == 0 = acc\n | even h = ans f (h `quot` 2) (j + 1) i arr acc\n | otherwise = ans f (h `quot` 2) (j + 1) (jump ! (j, i)) arr $ acc `f` (arr ! (j, i))\n n' = fromIntegral $ n - 1 :: Int\n sequence_ [putStrLn . unwords $ map show [ans (+) k 0 i sjump 0, ans min k 0 i mjump (10 ^ 9)] | i <- [0 .. n']]\n"}, {"source_code": "import Data.Array.Unboxed\nimport Data.Maybe\nimport Data.Int\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) `fmap` BS.getLine\n\nmain = do\n [n, k] <- readInts :: IO [Int64]\n fs <- readInts\n ws <- readInts\n let vecs :: [(UArray Int Int, UArray Int Int64, UArray Int Int64)]\n vecs =\n iterate\n ( \\(a, b, c) ->\n ( array (0, n') [(i, a ! (a ! i)) | i <- [0 .. n']]\n , array (0, n') [(i, b ! (a ! i) + b ! i) | i <- [0 .. n']]\n , array (0, n') [(i, min (c ! (a ! i)) (c ! i)) | i <- [0 .. n']]))\n $ (listArray (0, n') fs, listArray (0, n') ws, listArray (0, n') ws)\n ans h ((a, b, c) : vs) i (accb, accc)\n | odd h = ans (h `quot` 2) vs (a ! i) $ ((b ! i) + accb, min accc $ c ! i)\n | h == 0 = show accb ++ \" \" ++ show accc\n | otherwise = ans (h `quot` 2) vs i (accb, accc)\n n' = fromIntegral n - 1 :: Int\n mapM_ putStrLn [ans k vecs i (0, 10 ^ 9) | i <- [0 .. n']]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Word\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = map (fromIntegral . fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nmain = do\n [n, k] <- readInts :: IO [Word64]\n fs <- readInts\n ws <- readInts :: IO [Word64]\n let mkArray :: (a -> a -> a) -> [a] -> Array (Int, Int) a\n mkArray f l = let a = array ((0, 0), (34, n')) $ zip (zip (repeat 0) [0 ..]) l ++ [((j, i), (a ! (j - 1, jump ! (j - 1, i))) `f` (a ! (j - 1, i))) | j <- [1 .. 34], i <- [0 .. n']] in a\n jump = mkArray const fs\n sjump = mkArray (+) ws\n mjump = mkArray min ws\n ans f h j i arr acc\n | h == 0 = acc\n | even h = ans f (h `quot` 2) (j + 1) i arr acc\n | otherwise = ans f (h `quot` 2) (j + 1) (jump ! (j, i)) arr $ acc `f` (arr ! (j, i))\n n' = fromIntegral $ n - 1 :: Int\n sequence_ [putStrLn . unwords $ map show [ans (+) k 0 i sjump 0, ans min k 0 i mjump (10 ^ 9)] | i <- [0 .. n']]\n"}, {"source_code": "{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport Data.Array\nimport Data.Maybe\nimport Data.Word\nimport qualified Data.ByteString.Char8 as BS\n\nreadInts :: Integral a => IO [a]\nreadInts = map (fromIntegral . fst . fromJust . BS.readInt) . BS.words <$> BS.getLine\n\nmain = do\n [n, k] <- readInts\n fs <- readInts\n ws <- readInts :: IO [Word64]\n let mkArray :: (a -> a -> a) -> [a] -> Array (Int, Int) a\n mkArray f l = let a = array ((0, 0), (34, n - 1)) $ zip (zip (repeat 0) [0 ..]) l ++ [((j, i), (a ! (j - 1, jump ! (j - 1, i))) `f` (a ! (j - 1, i))) | j <- [1 .. 34], i <- [0 .. n - 1]] in a\n jump = mkArray const fs\n sjump = mkArray (+) ws\n mjump = mkArray min ws\n ans f h j i arr acc\n | h == 0 = acc\n | even h = ans f (h `quot` 2) (j + 1) i arr acc\n | otherwise = ans f (h `quot` 2) (j + 1) (jump ! (j, i)) arr $ acc `f` (arr ! (j, i))\n sequence_ [putStrLn . unwords $ map show [ans (+) k 0 i sjump 0, ans min k 0 i mjump (10 ^ 9)] | i <- [0 .. n - 1]]\n"}], "src_uid": "d84d878719124acf7ab3af6ae787ceee"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main (main) where\n\nimport Control.Arrow ((&&&))\nimport Control.Monad (replicateM_)\nimport Data.Array.Unboxed (UArray, (!), listArray)\nimport Data.List (group, scanl')\nimport Data.Word (Word8, Word32, Word64)\n\nlcmsWithWidths :: [(Word8, Word64)]\nlcmsWithWidths = map (fromIntegral . length &&& head) . group . scanl' lcm 1 $ [1 ..]\n\nwidths :: UArray Word8 Word8\nwidths = listArray (0, 19) . map fst $ lcmsWithWidths\n\nlcms :: UArray Word8 Word64\nlcms = listArray (0, 19) . map snd $ lcmsWithWidths\n\ns :: Word64 -> Word32\ns = go 0 0\n where\n go :: Word8 -> Word64 -> Word64 -> Word32\n go !20 !sum _ = fromIntegral $ sum `rem` 1000000007\n go !i !sum !x = go (i + 1) (sum + fromIntegral (widths ! i)*(x `quot` (lcms ! i))) x\n\nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)", "positive_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main (main) where\n\nimport Control.Monad (replicateM_)\nimport Data.Array.Unboxed (UArray, elems, listArray)\nimport Data.List (foldl')\nimport Data.Word (Word8, Word32, Word64)\n\nds :: UArray Int Word64\nds = listArray (0, 19) [1,2,6,12,60,420,840,2520,27720,360360,720720,12252240,232792560,5354228880,26771144400,80313433200,2329089562800,72201776446800,144403552893600,5342931457063200]\n\nms :: UArray Int Word8\nms = listArray (0, 19) [2,1,1,1,2,1,1,2,2,3,1,2,4,2,2,2,2,1,5,4]\n\ns :: Word64 -> Word32\ns !x = fromIntegral . (`rem` 1000000007) . foldl' (+) 0 . zipWith (\\ d m -> (x `quot` d) * fromIntegral m) (elems ds) $ elems ms \n\nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main (main) where\n\nimport Control.Monad (replicateM_)\nimport Data.List (foldl')\nimport Data.Word (Word32, Word64)\n\ns :: Word64 -> Word32\ns !x = fromIntegral $ foldl' (+) 0 [ 2 * (x `quot` 1)\n , 1 * (x `quot` 2)\n , 1 * (x `quot` 6)\n , 1 * (x `quot` 12)\n , 2 * (x `quot` 60)\n , 1 * (x `quot` 420)\n , 1 * (x `quot` 840)\n , 2 * (x `quot` 2520)\n , 2 * (x `quot` 27720)\n , 3 * (x `quot` 360360)\n , 1 * (x `quot` 720720)\n , 2 * (x `quot` 12252240)\n , 4 * (x `quot` 232792560)\n , 2 * (x `quot` 5354228880)\n , 2 * (x `quot` 26771144400)\n , 2 * (x `quot` 80313433200)\n , 2 * (x `quot` 2329089562800)\n , 1 * (x `quot` 72201776446800)\n , 5 * (x `quot` 144403552893600)\n , 4 * (x `quot` 5342931457063200)\n ] `rem` 1000000007\n\nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main (main) where\n\nimport Control.Monad (replicateM_)\nimport Data.Bits (unsafeShiftL, unsafeShiftR)\nimport Data.Word (Word32, Word64)\n\ns :: Word64 -> Word32\ns !x = let !term01 = 2*(x `quot` 1)\n !term02 = term01 + 1*(x `quot` 2)\n !term03 = term02 + 1*(x `quot` 6)\n !term04 = term03 + 1*(x `quot` 12)\n !term05 = term04 + 2*(x `quot` 60)\n !term06 = term05 + 1*(x `quot` 420)\n !term07 = term06 + 1*(x `quot` 840)\n !term08 = term07 + 2*(x `quot` 2520)\n !term09 = term08 + 2*(x `quot` 27720)\n !term10 = term09 + 3*(x `quot` 360360)\n !term11 = term10 + 1*(x `quot` 720720)\n !term12 = term11 + 2*(x `quot` 12252240)\n !term13 = term12 + 4*(x `quot` 232792560)\n !term14 = term13 + 2*(x `quot` 5354228880)\n !term15 = term14 + 2*(x `quot` 26771144400)\n !term16 = term15 + 2*(x `quot` 80313433200)\n !term17 = term16 + 2*(x `quot` 2329089562800)\n !term18 = term17 + 1*(x `quot` 72201776446800)\n !term19 = term18 + 5*(x `quot` 144403552893600)\n !term20 = term19 + 4*(x `quot` 5342931457063200)\n !result = fromIntegral (term20 `rem` 1000000007)\n in result\n\nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)"}, {"source_code": "{-# LANGUAGE BangPatterns #-} \n \nmodule Main (main) where \n \nimport Control.Monad (replicateM_) \nimport Data.Bits (unsafeShiftL, unsafeShiftR) \nimport Data.Word (Word32, Word64) \n \ns :: Word64 -> Word32 \ns !x = let !quot02 = unsafeShiftR x 1 \n !quot03 = x `quot` 6 \n !quot04 = unsafeShiftR quot03 1 \n !quot05 = x `quot` 60 \n !quot06 = x `quot` 420\n !quot07 = unsafeShiftR quot06 1\n !quot08 = x `quot` 2520\n !quot09 = x `quot` 27720\n !quot10 = x `quot` 360360\n !quot11 = unsafeShiftR quot10 1\n !quot12 = x `quot` 12252240\n !quot13 = x `quot` 232792560\n !quot14 = x `quot` 5354228880\n !quot15 = x `quot` 26771144400\n !quot16 = x `quot` 80313433200\n !quot17 = x `quot` 2329089562800\n !quot18 = x `quot` 72201776446800\n !quot19 = unsafeShiftR quot18 1\n !quot20 = x `quot` 5342931457063200\n !term01 = x + x\n !term02 = term01 + quot02\n !term03 = term02 + quot03\n !term04 = term03 + quot04\n !term05 = term04 + quot05 + quot05\n !term06 = term05 + quot06\n !term07 = term06 + quot07\n !term08 = term07 + quot08 + quot08\n !term09 = term08 + quot09 + quot09\n !term10 = term09 + quot10 + quot10 + quot10\n !term11 = term10 + quot11\n !term12 = term11 + quot12 + quot12\n !term13 = term12 + unsafeShiftL quot13 2\n !term14 = term13 + quot14 + quot14\n !term15 = term14 + quot15 + quot15\n !term16 = term15 + quot16 + quot16\n !term17 = term16 + quot17 + quot17\n !term18 = term17 + quot18\n !term19 = term18 + unsafeShiftL quot19 2 + quot19\n !term20 = term19 + unsafeShiftL quot20 2\n !result = fromIntegral (term20 `rem` 1000000007)\n in result\n \nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main (main) where\n\nimport Control.Monad (replicateM_)\nimport Data.Array.Unboxed (UArray, (!), listArray)\nimport Data.List (scanl')\nimport Data.Word (Word8, Word32, Word64)\n\nlcms :: UArray Word8 Word64\nlcms = listArray (0, 40) . scanl' lcm 1 $ [1 ..]\n\ns :: Word64 -> Word32\ns = go 0 0\n where\n go :: Word8 -> Word64 -> Word64 -> Word32\n go !41 !sum _ = fromIntegral $ sum `rem` 1000000007\n go !i !sum !x = go (i + 1) (sum + x `quot` (lcms ! i)) x\n\nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nmodule Main (main) where\n\nimport Control.Monad (replicateM_)\nimport Data.Word (Word8, Word32, Word64)\n\ns :: Word64 -> Word32\ns x = go 3 0 1 2 0 x\n where\n go :: Word8 -> Word32 -> Word64 -> Word64 -> Word64 -> Word64 -> Word32\n go !n !sum !lcm1 !lcm2 !handled !x\n | handled == x = sum\n | lcm1 == lcm2 = go (n + 1) sum lcm1 (lcm lcm2 (fromIntegral n)) handled x\n | otherwise = let !itemsPerGroup = (lcm2 `quot` lcm1) - 1\n (!fullGroups, !remainder) = x `quotRem` lcm2\n !count = itemsPerGroup*fullGroups + remainder `quot` lcm1\n in go (n + 1) (fromIntegral ((fromIntegral sum + (fromIntegral (n - 1))*count) `rem` 1000000007)) lcm2 (lcm lcm2 (fromIntegral n)) (handled + count) x\n\nmain :: IO ()\nmain = do\n count <- fmap read getLine\n replicateM_ count $ do\n x <- fmap read getLine\n print (s x)"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\n\nanswerFix x n\n | producted > n = 0\n | otherwise = (n `div` producted) + answerFix (x + 1) n\n where\n !producted = foldl1 lcm [1..x]\n\nanswer n\n | odd n = (`mod` (7 + (10 ^ 9))) $ (fixed +) $ (n' + 1) * 2 + n' * 3\n | even n = (`mod` (7 + (10 ^ 9))) $ (fixed +) $ n' * 2 + n' * 3\n where\n n' = n `div` 2\n fixed = answerFix 3 n\n\nreadInt :: String -> Integer\nreadInt = read\n\nmain = do\n n <- readInt <$> getLine\n replicateM_ (fromIntegral n) $ do\n m <- readInt <$> getLine\n print $ answer m\n"}, {"source_code": "import Control.Monad (replicateM_)\r\n\r\nmd = 10^9 + 7 :: Integer\r\nmx = 41\r\n\r\nmodPlus a b = (a `rem` md + b `rem` md) `rem` md\r\n\r\nmodProd a b = (a `rem` md * b `rem` md) `rem` md\r\n\r\ncompute :: Integer -> Integer\r\ncompute n = foldr1 modPlus mults where\r\n lcms = scanl1 lcm [1..mx]\r\n g i prev curr = i `modProd` (n `div` prev - n `div` curr)\r\n mults = zipWith3 g [2..] lcms (tail lcms)\r\n\r\nsolve :: IO ()\r\nsolve = do\r\n n <- readLn\r\n print $ compute n\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t solve"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\nfactors :: Int64 -> Int64 -> [Int64]\nfactors 1 _ = []\nfactors x start\n | start*start > x = [x]\n | mod x start == 0 = start : factors (div x start) start\n | otherwise = factors x (start+1)\n\n\nthisIsSmallest n lcmm i\n | rem lcmm i == 0 = 0\n | otherwise = div n lcmm - div n (lcm lcmm i)\n\nsolve = do\n n <- readLn :: IO Int64\n let mx = 1000000007\n lcms = takeWhile (<=n+1) $ scanl lcm 1 [2..]\n resl = map (\\(i, lcmm) -> thisIsSmallest n lcmm i) $ zip [2..] lcms\n res = foldl (\\acc (idx, x) -> rem (acc + idx*x) mx) 0 $ zip [2..] resl\n in putStrLn $ show res\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}, {"source_code": "import Control.Arrow ((>>>))\r\n\r\nmain :: IO ()\r\nmain = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines\r\n\r\nsolve :: Integer -> Integer\r\nsolve n =\r\n (`mod` (10 ^ 9 + 7))\r\n . (n +)\r\n . sum\r\n . map (n `div`)\r\n . takeWhile (<= n)\r\n $ scanl1 lcm [1 ..]\r\n"}], "negative_code": [{"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Monad\n\nanswerFix x n\n | producted > n = 0\n | otherwise = (n `div` producted) + answerFix (x + 1) n\n where\n !producted = foldl1 lcm [1..x]\n\nanswer n\n | odd n = (`mod` (7 + (10 ^ 9))) $ (fixed +) $ (n' + 1) * 2 + n' * 3\n | even n = (`mod` (7 + (10 ^ 9))) $ (fixed +) $ n' * 2 + n' * 3\n where\n n' = n `div` 2\n fixed = answerFix 3 n\n\nreadInt :: String -> Int\nreadInt = read\n\nmain = do\n n <- readInt <$> getLine\n replicateM_ n $ do\n m <- readInt <$> getLine\n print $ answer m\n"}], "src_uid": "2b15a299c25254f265cce106dffd6174"} {"source_code": "import Control.Applicative\n\ngetRes :: Int -> Int\ngetRes x\n | x > 500000 = 1000000 - x\n | otherwise = x - 1\n\nsolve :: [Int] -> Int\nsolve (x:[]) = getRes x\nsolve (x:xs) = max (getRes x) (solve xs)\n\nmain :: IO ()\nmain = do\n getLine\n prizes <- map (read :: String -> Int) . words <$> getLine\n putStrLn . show $ solve prizes\n", "positive_code": [{"source_code": "import Data.List\n\nmain = getContents >>= print . solve . sort . (1:) . (1000000:) . map read . tail . words\n\nsolve as = minimum $ zipWith (\\a0 a1 -> max (a0 - 1) (1000000 - a1)) as (tail as)\n"}, {"source_code": "import Data.List\n\nmain = getContents >>= print . solve . sort . (1:) . (1000000:) . map read . words\n\nsolve as = minimum $ zipWith (\\a0 a1 -> max (a0 - 1) (1000000 - a1)) as (tail as)\n"}, {"source_code": "\nmdist = 1000000\nmiddle = mdist `div` 2\n\nmain = do\n xs <- getLine >> getLine >>= return . (1:) . (mdist:) . map read . words\n let l = maximum [ x | x <- xs, x <= middle ] - 1\n r = 1000000 - minimum [ x | x <- xs, x > middle ]\n print $ max l r\n"}, {"source_code": "main = do\n ln1 <- getLine\n ln2 <- getLine\n let c = 10^6 :: Int\n s = map (\\x -> read x :: Int) $ words ln2\n putStrLn $ show $ f s c\n\nf l k\n | length c1 == 0 = k - minimum c2\n | length c2 == 0 = (maximum c1) - 1\n | True = max ((maximum c1) - 1) (k - minimum c2)\n where c1 = [i | i <- l, i <= 500000]\n c2 = [i | i <- l, i > 500000]\n \n"}], "negative_code": [{"source_code": "main = do\n ln1 <- getLine\n ln2 <- getLine\n let c = 10^6 :: Int\n s = map (\\x -> read x :: Int) $ words ln2\n putStrLn $ show $ f s c\n\nf l k\n | length c1 == 0 = k - minimum c2\n | length c2 == 0 = (maximum c1) - 1\n | True = max ((maximum c1) - 1) (k - minimum c2)\n where c1 = [i | i <- l, i <= quot k 2]\n c2 = [i | i <- l, i >= quot k 2]\n \n"}, {"source_code": "import Data.List\n\nmain = getContents >>= print . solve . sort . (1:) . (1000000:) . map read . words\n\nsolve as = 1000000 - d - maximum ds\n where ds = zipWith (-) (tail as) as\n d = if maximum ds == head ds || maximum ds == last ds then 1 else 2\n"}], "src_uid": "f530e6f720dafaf8bff9324289b90b28"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Control.Applicative\n\nreadInteger bs = case B.readInteger bs of Just (n,_) -> n\n\nmain = do\n [n,k] <- map read.words <$> getLine\n sorted <- sort.map readInteger.B.words <$> B.getLine\n putStrLn.unwords.map show $ solve k 0 0 qEmpty sorted\n\nsolve _ len val _ [] = [len,val]\nsolve k len val q@(Q l s _ _ ) (x:xs)\n | l*x - s > k = solve k len val (deq q) (x:xs)\n | l+1 > len = solve k (l+1) x (enq x q) xs\n | otherwise = solve k len val (enq x q) xs\n\ndata Q = Q {-# UNPACK #-} !Integer {-# UNPACK #-} !Integer [Integer] [Integer]\n\nqEmpty = Q 0 0 [] []\n\nenq x (Q l s fs rs) = Q (l+1) (s+x) fs (x:rs)\n\ndeq (Q l s (f:fs) rs) = Q (l-1) (s-f) fs rs\ndeq (Q l s [] rs) = deq (Q l s (reverse rs) [])", "positive_code": [{"source_code": "module Main where\n\nimport Control.Applicative\nimport Data.List\nimport Control.Arrow\n\nptr2 _ _ [] _ _ acc = acc\nptr2 _ [] _ _ _ _ = error $ \"Shit happend\"\nptr2 k (x:xs) (y:ys) i sm acc\n | sm > k = ptr2 k xs (y:ys) (i-1) (sm - (y-x)) acc\n | sm <= k = ptr2 k (x:xs) ys (i+1) (sm + (head ys-y)*i) ((i,y) : acc)\n\ntype I = Integer\n\nsolve :: I -> I -> [I] -> (I,I)\nsolve n k as = findBest cands\n where\n cands = ptr2 k as' as' 1 0 []\n findBest = negSnd . maximum . map negSnd\n negSnd = id *** negate\n as' = sort as\n\nmain :: IO ()\nmain = do\n [n,k] <- map read . words <$> getLine\n as <- map read . words <$> getLine\n let (n',v) = solve n k as\n putStrLn $ show n' ++ \" \" ++ show v"}, {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport qualified Data.ByteString.Char8 as B\nimport Data.Int\nimport Data.List\nimport Control.Applicative\n\nreadInt64 bs = case B.readInt bs of Just (n,_) -> fromIntegral n\n\nmain = do\n [n,k] <- map read.words <$> getLine\n sorted <- sort.map readInt64.B.words <$> B.getLine\n putStrLn.unwords.map show $ solve k 0 0 qEmpty sorted\n\nsolve _ !len val _ [] = [len,val]\nsolve k !len val !q@(Q l s _ _ ) (x:xs)\n | l*x - s > k = solve k len val (deq q) (x:xs)\n | l+1 > len = solve k (l+1) x (enq x q) xs\n | otherwise = solve k len val (enq x q) xs\n\ndata Q = Q {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64 [Int64] [Int64]\n\nqEmpty = Q 0 0 [] []\n\nenq x (Q l s fs rs) = Q (l+1) (s+x) fs (x:rs)\n\ndeq (Q l s (f:fs) rs) = Q (l-1) (s-f) fs rs\ndeq (Q l s [] rs) = deq (Q l s (reverse rs) [])"}], "negative_code": [], "src_uid": "3791d1a504b39eb2e72472bcfd9a7e22"} {"source_code": "{-# LANGUAGE NoMonomorphismRestriction #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n\r\nimport qualified Data.ByteString.Lazy.Char8 as P\r\nimport qualified Data.ByteString.Char8 as String\r\nimport qualified Data.ByteString.Builder.Prim as Prim\r\nimport Data.ByteString.Builder\r\nimport Control.Monad\r\nimport Control.Monad.ST\r\n--import Control.Monad.Trans.State\r\nimport Data.Array.Base\r\nimport Data.Array.IO\r\nimport Data.Array.ST\r\nimport Data.Array.Unboxed\r\nimport Data.Array.MArray as Vector\r\nimport Data.Bits\r\nimport Data.Bool\r\nimport Data.Char\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Ord\r\nimport Data.Ratio\r\nimport Data.Tuple\r\nimport Data.Function\r\nimport qualified Data.Set as Set\r\nimport qualified Data.Sequence as Seq\r\nimport System.IO\r\nimport System.IO.Unsafe\r\nimport System.Exit\r\n\r\n\r\nimport Data.IORef\r\nimport Control.Monad.Writer\r\nimport Control.Monad.State\r\nimport Control.Monad.Fail\r\nimport Control.Applicative\r\nimport Control.Monad.Except\r\nimport Control.Monad.Reader\r\nimport Control.Monad.Trans.Except\r\nimport Control.Monad.IO.Class (liftIO)\r\nimport Data.Foldable (msum)\r\nimport Data.Char (isNumber, isPunctuation)\r\n\r\nimport Control.Monad.Identity (Identity(..)) \r\n\r\nprintLog :: Show a => a -> a\r\nprintLog a = unsafePerformIO $ do putStrLn $ \"{\u043e\u0442\u043b\u0430\u0434\u043a\u0430[ \"++show a ++ \" ]\u043e\u0442\u043b\u0430\u0434\u043a\u0430}\"\r\n pure a \r\n\r\nbinSearch :: Integral i => (i -> Bool) -> i -> i -> i\r\nbinSearch f = go where\r\n go l h\r\n | l > h = l\r\n | f m = go l (m - 1)\r\n | otherwise = go (m + 1) h\r\n where m = (l + h) `div` 2\r\n \r\nbinSearchA :: (a -> Bool) -> Array Int a -> Int\r\nbinSearchA f a = binSearch (f . (a!)) l h where (l, h) = bounds a\r\n\r\nfArray :: Ix i => (i, i) -> (i -> a) -> Array i a\r\nfArray b f = array b [(i, f i) | i <- range b]\r\n\r\nreadInts :: IO [Int]\r\nreadInts = map (fst . fromJust . String.readInt) . String.words <$> String.getLine\r\n\r\nfita :: IO ()\r\nfita = do \r\n n <- getLine\r\n let evens = foldr (\\el suf -> suf || even (digitToInt el)) False n\r\n case evens of \r\n True -> print $ if (even . digitToInt . head . reverse $ n) \r\n then 0 \r\n else if (even . digitToInt . head $ n) \r\n then 1\r\n else 2\r\n False -> print (-1)\r\n\r\nmain :: IO ()\r\nmain = flip replicateM_ fita =<< readLn\r\n", "positive_code": [{"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\nimport Data.Array\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n str <- getLine\n let digits = (read . pure) <$> str\n lEven = even (last digits)\n hEven = even (head digits)\n aEven = any even digits\n print $\n if | lEven -> 0\n | hEven -> 1\n | aEven -> 2\n | otherwise -> -1\n"}, {"source_code": "{-# LANGUAGE MultiWayIf #-}\n\nimport Control.Monad\n\nmain = do\n n <- readLn\n replicateM_ n $ do\n str <- getLine\n let digits = (read . pure) <$> str\n lEven = even (last digits)\n hEven = even (head digits)\n aEven = any even digits\n print $\n if | lEven -> 0\n | hEven -> 1\n | aEven -> 2\n | otherwise -> -1\n"}, {"source_code": "{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n\r\nimport Control.Applicative (liftA2)\r\nimport Control.Arrow ((>>>))\r\nimport Control.Monad\r\nimport Control.Monad.State (State, evalState, get, gets, put)\r\nimport qualified Data.ByteString.Lazy.Char8 as C\r\nimport Data.Function\r\nimport Data.Int\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Bool\r\n\r\nmain :: IO ()\r\nmain = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines\r\n\r\ndata TC = TC { n :: Int }\r\n\r\ninput :: Scanner TC\r\ninput = do\r\n n <- int\r\n return TC {..}\r\n\r\ntype Output = Int\r\n\r\noutput :: Output -> C.ByteString\r\noutput = showB\r\n\r\nsolve :: TC -> Output\r\nsolve TC {..}\r\n | even n = 0\r\n | even (head ns) = 1\r\n | any even ns = 2\r\n | otherwise = -1\r\n where\r\n ns = [read [c] | c <- show n]\r\n\r\n-------------------------- Template ------------------------------------------\r\n-- Lists\r\ngroupOn :: Eq b => (a -> b) -> [a] -> [[a]]\r\ngroupOn = groupBy . on (==)\r\n\r\nchunksOf :: Int -> [a] -> [[a]]\r\nchunksOf _ [] = []\r\nchunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts\r\n\r\nadjacents :: [a] -> [(a, a)]\r\nadjacents xs = zip xs (tail xs)\r\n\r\nadjacentsWith :: (a -> a -> b) -> [a] -> [b]\r\nadjacentsWith f xs = zipWith f xs (tail xs)\r\n\r\ncount :: Eq a => a -> [a] -> Int\r\ncount = countBy . (==)\r\n\r\ncountBy :: (a -> Bool) -> [a] -> Int\r\ncountBy p = length . filter p\r\n\r\n-- Scanner\r\ntype Scanner = State [C.ByteString]\r\n\r\nrunScanner :: Scanner a -> C.ByteString -> a\r\nrunScanner = runScannerWith C.words\r\n\r\nrunScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a\r\nrunScannerWith t s = evalState s . t\r\n\r\npeek :: Scanner C.ByteString\r\npeek = gets head\r\n\r\nbstr :: Scanner C.ByteString\r\nbstr = get >>= \\case s : ss -> put ss >> return s\r\n\r\nstr :: Scanner String\r\nstr = C.unpack <$> bstr\r\n\r\nreadStr :: Read a => Scanner a\r\nreadStr = read <$> str\r\n\r\nint :: Scanner Int\r\nint = fst . fromJust . C.readInt <$> bstr\r\n\r\ninteger :: Scanner Integer\r\ninteger = readStr\r\n\r\nint64 :: Scanner Int64\r\nint64 = readStr\r\n\r\ndouble :: Scanner Double\r\ndouble = readStr\r\n\r\ndecimal :: Int -> Scanner Int\r\ndecimal p = round . ((10 ^ p) *) <$> double\r\n\r\nnumberOf :: Scanner a -> Scanner [a]\r\nnumberOf s = int >>= flip replicateM s\r\n\r\nmany :: Scanner a -> Scanner [a]\r\nmany s = get >>= \\case [] -> return []; _ -> (:) <$> s <*> many s\r\n\r\ntill :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]\r\ntill p s = do\r\n t <- peek\r\n if p t\r\n then return []\r\n else (:) <$> s <*> till p s\r\n\r\ntimes :: Int -> Scanner a -> Scanner [a]\r\ntimes = replicateM\r\n\r\n(><) = times\r\n\r\ntwo, three, four :: Scanner a -> Scanner [a]\r\n[two, three, four] = map times [2 .. 4]\r\n\r\npair :: Scanner a -> Scanner b -> Scanner (a, b)\r\npair = liftA2 (,)\r\n\r\nshowB :: Show a => a -> C.ByteString\r\nshowB = C.pack . show\r\n"}], "negative_code": [], "src_uid": "03e5f71810b10318fed344878d226a10"} {"source_code": "main = getContents >>= print . solve . map (read :: String -> Int) . tail . words\n\nsolve :: [Int] -> Int\nsolve ls = if odd s then s else s - (minimum $ filter odd $ map abs ls)\n where s = sum $ filter (0 <) ls\n", "positive_code": [{"source_code": "-- Codeforces 797B\n\n{-# OPTIONS_GHC -O2 #-}\n{-# OPTIONS_GHC -optc-O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Data.List\nimport Data.Maybe\nimport qualified Data.ByteString.Char8 as BC\n\nmain :: IO ()\nmain = do\n getLine\n xs <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getContents\n let (s, k) = foldl' (\\(s, k) x -> if x >= 0\n then if x `mod` 2 == 1\n then (s + x, min k x)\n else (s + x, k)\n else if x `mod` 2 == 1\n then (s, min k (- x))\n else (s, k)) (0, maxBound :: Int) xs\n if s `mod` 2 == 0\n then print (s - k)\n else print s\n"}, {"source_code": "import Data.List\nimport qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport Data.Bits\nimport Data.Int (Int64)\nimport Data.Array\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nsolve v =\n let (e,o) = partition even v\n se = (sum.(filter (>0))) e\n (p,n) = partition (>0) o\n lp = length p\n so =\n if lp == 0\n then maximum n\n else\n if even lp\n then\n let sp = sum p\n mp = minimum p in\n if null n\n then sp - mp\n else max (sp - mp) (sp + (maximum n))\n else sum $ p\n in se + so\n\n\nmain = do\n n <- readLn::IO Int\n v <- ( (map (\\x -> read x::Int)) . words ) <$> getLine\n print $ solve v\n"}], "negative_code": [{"source_code": "import Data.List\nimport qualified Data.IntMap as Map\nimport qualified Data.IntSet as Set\nimport Data.Bits\nimport Data.Int (Int64)\nimport Data.Array\nimport Control.Monad\nimport Control.Applicative\nimport Data.List\n\nsolve v =\n let (e,o) = partition even v\n se = (sum.(filter (>0))) e\n (p,n) = partition (>0) o\n lp = length p\n so =\n if lp == 0\n then maximum n\n else\n if even lp\n then sum $ tail $ sort p\n else sum $ p\n in se + so\n\n\nmain = do\n n <- readLn::IO Int\n v <- ( (map (\\x -> read x::Int)) . words ) <$> getLine\n print $ solve v\n"}], "src_uid": "76dd49c5545770a1dfbb2da4140199c1"} {"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = [Int]\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n -- print (n, xs)\n return xs\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve d = print $ go (head xs) (tail xs)\n where xs = enumerate d\n go :: (Int, Int) -> [(Int, Int)] -> Int\n go (i, _) [] = i\n go (i, x) ((j,y):ys) \n | x == y = go (head ys) (tail ys)\n | x > y = go (i, x-y) ys\n | otherwise = go (j, y-x) ys\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n", "positive_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = [Int]\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n -- print (n, xs)\n return xs\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [1..length xs] xs\n\n\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve d = case foldr go Nothing xs of\n Nothing -> print \"error\"\n Just (i, _) -> print i\n where xs = enumerate d\n go :: (Int, Int) -> Maybe (Int, Int) -> Maybe (Int, Int)\n go x Nothing = Just x\n go (j, y) (Just (i, x)) \n | x == y = Nothing\n | x > y = Just (i, x - y)\n | otherwise = Just (j, y - x)\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- ballcol.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\nimport Prelude hiding (getLine)\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.Function\nimport Data.List\n\nri = readInts <$> B.getLine :: IO [Int]\n where\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n dropSpace = B.dropWhile isSpace\n\nmain :: IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n [_n] <- ri\n ri\n mapM_ (putStrLn.show.solve) tcs\n\nsolve = fst . maximumBy (compare`on`snd) . (cols`zip`)\n\ncols = [1..] :: [Int]\n"}, {"source_code": "import Control.Monad (replicateM_)\nmain = read <$> getLine >>= flip replicateM_ scase\nscase = getLine >>\n map read . words <$> getLine >>=\n print . findMaxIdx\n\nfindMaxIdx :: [Int] -> Int\nfindMaxIdx (x:xs) = f xs 2 x 1\n where f [] _ _ i = i\n f (x:xs) xi m mi | x > m = f xs (xi+1) x xi\n | otherwise = f xs (xi+1) m mi\n"}, {"source_code": "\r\nmaxIndex :: (Enum b,Ord a) => [a] -> b\r\nmaxIndex x = fst (maxIndex_ (toEnum 0) x) where\r\n maxIndex_ _ [] = error \"empty list\"\r\n maxIndex_ i [x] = (i,x)\r\n maxIndex_ i (x:xs) = if x >= snd y then (i,x) else y where\r\n y = maxIndex_ (succ i) xs\r\n\r\ntest_case_func :: (Num a,Eq a) => a -> IO ()\r\ntest_case_func 0 = return ()\r\ntest_case_func t = do \r\n n <- getLine\r\n cnts <- getLine\r\n print $ (maxIndex (map read $ words cnts :: [Int])) + 1\r\n test_case_func (t - 1)\r\n\r\n\r\nmain :: IO ()\r\nmain = do\r\n ts <- getLine\r\n test_case_func $ read ts"}, {"source_code": "\r\n{-# language NoMonomorphismRestriction #-}\r\n \r\n{-# options_ghc -O3 #-}\r\n \r\n{-# options_ghc -Weverything #-}\r\n \r\n{-# options_ghc -Wno-safe #-} \r\n{-# options_ghc -Wno-all-missed-specialisations #-} \r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n \r\n\r\nimport Prelude hiding (getLine)\r\nimport Control.Arrow\r\nimport Control.Monad\r\nimport qualified Data.ByteString.Char8 as B\r\nimport Data.Char\r\nimport Data.Function\r\nimport Data.List\r\n \r\nri = readInts <$> B.getLine :: IO [Int]\r\n where\r\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\r\n dropSpace = B.dropWhile isSpace\r\n \r\nmain :: IO ()\r\nmain = do\r\n [t] <- ri\r\n tcs <- replicateM t $ do\r\n [_n] <- ri\r\n ri\r\n mapM_ (putStrLn.show.solve) tcs\r\n \r\nsolve = fst . maximumBy (compare`on`snd) . (cols`zip`)\r\n \r\ncols = [1..] :: [Int]"}, {"source_code": "import Control.Monad\r\nimport Data.List\r\n\r\nsolveCase :: [Int] -> Int\r\nsolveCase n = snd (head (reverse (sort (zip n [1..end]))))\r\n where end = length n\r\n\r\ncaseSolutionString :: [Int] -> String\r\ncaseSolutionString n = show sol\r\n where sol = solveCase n\r\n\r\nreadCase :: Int -> IO ([Int])\r\nreadCase i = do \r\n input <- getLine\r\n let n = (read input) :: Int\r\n input <- getLine\r\n let list = (map read (words input)) :: [Int]\r\n return list\r\n\r\nmain = do\r\n t <- getLine\r\n let tn = (read t) :: Int\r\n cases <- forM [1..tn] readCase\r\n mapM putStrLn (map caseSolutionString cases)"}], "negative_code": [{"source_code": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Control.Monad (liftM2, replicateM_, replicateM, foldM, when, liftM3)\nimport Data.Char (digitToInt, toLower)\nimport Data.Maybe (fromJust, fromMaybe)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)\nimport Data.List (group, sort)\nimport Data.Set (Set, deleteFindMin, union)\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport Data.Function (on)\nimport Data.Array.MArray (newArray, readArray, writeArray, newListArray)\nimport Data.Array.IO (IOUArray, getElems)\nimport Data.Bool (bool)\nimport Data.Foldable (foldlM, Foldable (foldl'), find, sequenceA_, foldrM)\nimport Control.Arrow ((&&&), Arrow ((***)))\nimport Data.Coerce (coerce)\nimport Data.Set.Internal(Set(Bin, Tip))\nimport Debug.Trace (traceShowId, traceShow)\nimport Data.Foldable (maximumBy)\nimport Data.Ord (comparing)\nimport qualified Data.IntMap as IntMap\nimport Control.Monad.Trans.Class\nimport Control.Exception (assert)\nimport Data.String\n\n\n-- type IMap = Set (Int, Int) \ntype Domain = [Int]\ntype Solver = Domain -> IO ()\n\nreadChar8 :: IO [Int]\nreadChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine\n\n\nparse :: IO Domain\nparse = do\n [n] <- readChar8\n xs <- readChar8\n -- print (n, xs)\n return xs\n\nenumerate :: [a] -> [(Int, a)]\nenumerate xs = zip [0..length xs-1] xs\n\n-- try for the automatically generated if not fixed\nsolve :: Solver\nsolve d = print $ go (head xs) (tail xs)\n where xs = enumerate d\n go :: (Int, Int) -> [(Int, Int)] -> Int\n go (i, _) [] = i\n go (i, x) ((j,y):ys) \n | x == y = go (head ys) (tail ys)\n | x > y = go (i, x-y) ys\n | otherwise = go (j, y-x) ys\n \nmain :: IO ()\nmain = do\n [n] <- readChar8\n sequence_ =<< (replicateM n $ solve <$> parse)\n"}, {"source_code": "\n--\n-- Michael V. Antosha\n-- 2022\n-- Michael.Antosha@gmail.com\n--\n\n{-# language NoMonomorphismRestriction #-}\n\n{-# options_ghc -O3 #-}\n\n{-# options_ghc -Weverything #-}\n\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\n{-# options_ghc -Wno-missing-import-lists #-}\n{-# options_ghc -Wno-missing-local-signatures #-}\n\n-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out && cat -- ballcol.hs | xclip -selection clipboard && echo COPIED || echo ERROR)\n\nimport Prelude hiding (getLine)\nimport Control.Arrow\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.Char\nimport Data.List\n\nri = readInts <$> B.getLine :: IO [Int]\n where\n readInts = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace\n dropSpace = B.dropWhile isSpace\n\nmain :: IO ()\nmain = do\n [t] <- ri\n tcs <- replicateM t $ do\n [_n] <- ri\n ri\n mapM_ (putStrLn.show.maximum) tcs\n"}], "src_uid": "779ab09a588bbb52485ae5b6a441b235"} {"source_code": "{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\n\n\nreadInt :: B.ByteString -> Int\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n _ <- getLine\n minq <- minimum.map readInt.B.words <$> B.getLine\n _ <- getLine\n as <- sortBy(flip compare).map readInt.B.words <$> B.getLine\n print $ solve minq as\n\nsolve minq xs = go 0 xs\n where\n go !ans [] = ans\n go !ans xs = go (ans+sum ys) $ drop 2 zs\n where\n (ys,zs) = splitAt minq xs\n", "positive_code": [{"source_code": "import Data.List\n\nminPrice mq prices =\n let (buy, left) = splitAt mq prices\n in case left of\n a:b:rest -> sum buy + minPrice mq rest\n _ -> sum buy\n\nmain :: IO ()\nmain = do\n _ <- getLine\n qs <- fmap (map read . words) getLine\n _ <- getLine\n as <- fmap (map read . words) getLine\n let mq = minimum qs\n prices = reverse $ sort as\n print $ minPrice mq prices\n\n\n\n\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Data.Maybe\n\nsolve qs as = sum $ go $ nonIncSort as\n where go [] = []\n go xs = sum (take q xs):go (drop (q + 2) xs)\n q = minimum qs\n nonIncSort = sortBy (\\x y -> compare y x)\n\nparseInt = fst . fromJust . BS.readInt\n\nmain = do _ <- BS.getLine\n qs <- fmap (map parseInt . BS.words) BS.getLine\n _ <- BS.getLine\n as <- fmap (map parseInt . BS.words) BS.getLine\n putStrLn $ show $ solve qs as\n"}, {"source_code": "import qualified Data.ByteString.Char8 as BS\nimport Data.List\nimport Data.Maybe\n\nsolve qs as = sum $ go $ nonIncSort as\n where go [] = []\n go xs = sum (take q xs):go (drop (q + 2) xs)\n q = minimum qs\n nonIncSort = sortBy (\\x y -> compare y x)\n\nparseInt = fst . fromJust . BS.readInt\n\nmain = do _ <- BS.getLine\n qs <- fmap (map parseInt . BS.words) BS.getLine\n _ <- BS.getLine\n as <- fmap (map parseInt . BS.words) BS.getLine\n putStrLn $ show $ solve qs as\n"}], "negative_code": [], "src_uid": "08803b63ae803e4a76afe7258a4004aa"} {"source_code": "import qualified Data.IntSet as S\nimport Data.Array.Unboxed\nimport Data.List\n\nmain = interact (show . answer . map (map read . words) . tail . lines)\n\nanswer :: [[Int]] -> Int\nanswer s = min (ans s) (ans (transpose s))\n where \n ans = minimum . map (sum . map (\\x -> nextPrime x - x))\n\nnextPrime :: Int -> Int\nnextPrime = (arr !)\n where\n mx = 110000\n primes = go 2 (S.fromDistinctAscList [2..mx])\n where\n go x s | x*x > mx = S.toAscList s\n | x `S.notMember` s = go (x+1) s\n | otherwise = \n go (x+1) (s `S.difference` (S.fromDistinctAscList [x*x, x*x+x..mx]))\n ps = go 1 primes\n where\n go x [] = []\n go x (d:dp) | x == d = x : go (x+1) dp\n | otherwise = d : go (x+1) (d:dp)\n arr :: UArray Int Int\n arr = listArray (1, mx) ps", "positive_code": [{"source_code": "\nimport Control.Monad (liftM, replicateM)\nimport Data.Array\nimport Data.Char (ord)\nimport Data.List (intercalate)\n\nisPrime :: Int -> Bool\nisPrime n = all (\\x -> mod n x /= 0)\n $ takeWhile (\\x -> x * x <= n) primes\n\nprimes :: [Int]\nprimes = 2 : filter isPrime [3,5..]\n\narrayDiffToPrime :: Array Int Int\narrayDiffToPrime = listArray (1,nextPrime 100000) $ listDiffToPrime 1 primes\n where\n listDiffToPrime i (p:ps)\n | i > p = listDiffToPrime i ps\n | otherwise = (p - i) : listDiffToPrime (i+1) (p:ps)\n nextPrime n = head $ dropWhile (< n) primes\n\nsolve :: Array (Int, Int) Int -> Int\nsolve array = min\n (minimum [sum [d ! (a ! (i, j)) | j <- [1..m]] | i <- [1..n]])\n (minimum [sum [d ! (a ! (i, j)) | i <- [1..n]] | j <- [1..m]])\n where\n (n, m) = snd $ bounds array\n d = arrayDiffToPrime \n a = array\n\nmain :: IO ()\nmain = do\n [n, m] <- reads\n ass <- replicateM n reads\n let array = Data.Array.array ((1,1), (n,m))\n $ map (\\(i, x) -> ((i `div` m + 1, i `mod` m + 1), x))\n $ zip [0..] $ concat ass\n print $ solve array\n where\n prints :: Show a => [a] -> IO ()\n prints = putStrLn . intercalate \" \" . map show\n\n reads :: Num a => IO [a]\n reads = liftM (map read . words) getLine\n where\n read ('-':s) = (-1) * read s\n read s = read' 0 s\n read' a \"\" = a\n read' a (c:s) = read' a' s\n where\n a' = 10 * a + fromIntegral (ord c - ord '0')\n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE BangPatterns #-}\n\nimport Control.Applicative\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport Data.List\nimport Data.Array.Base\nimport Data.Array.ST (runSTUArray)\nimport Data.Bits\n\nreadInt bs = case B.readInt bs of Just (n,_) -> n\n\nmain = do\n _ <- getLine\n xss <- map(map readInt.B.words).B.lines <$> B.getContents :: IO [[Int]]\n let yss = transpose xss\n print $ min (solve xss) (solve yss)\n\nsolve :: [[Int]] -> Int\nsolve xss = foldl1' min $ map (sum.map f) xss\n\nf :: Int -> Int\nf 1 = 1\nf 2 = 0\nf x\n | even x = 1 + f(x+1)\n | unsafeAt isPrime (x`unsafeShiftR`1) = 0\n | otherwise = 1 + f (x+1)\n\nprimeLimit = 100001\nprimeLimit2 = primeLimit`quot`2\n\nisPrime :: UArray Int Bool\nisPrime = runSTUArray $ do\n isp <- newArray (0,primeLimit`quot`2) True\n forM_ [1..isqrt primeLimit2] $ \\i-> do\n flg <- unsafeRead isp i\n when flg $ do\n let !p = 2*i+1\n go !i = when (i<=primeLimit2) $ do\n unsafeWrite isp i False\n go $ i+p \n go $ i*(p+1)\n return isp\n\nisqrt :: Int -> Int\nisqrt x = floor.sqrt $ fromIntegral x"}], "negative_code": [], "src_uid": "d549f70d028a884f0313743c09c685f1"} {"source_code": "import qualified Data.Set as Set\r\nimport Data.List\r\nimport Control.Monad\r\nimport Data.Char\r\n\r\nreadInts = fmap (map read.words) getLine :: IO [Integer]\r\nsolve1 [] ys = True \r\nsolve1 (x:xs) (y:ys) \r\n | (x /= y) = False \r\n | otherwise = solve1 xs ys \r\n\r\nsolve2 [x] = True\r\nsolve2 [x,y] = True \r\nsolve2 (x:y:xs) \r\n | (x < y && z < y) = False \r\n | otherwise = solve2 (y:xs) \r\n where z = head xs \r\n\r\nprintS = do \r\n s<-getLine \r\n let a = sort s\r\n t = sort $ \"qwertyuiopasdfghjklzxcvbnm\"\r\n putStrLn $ if ((solve1 a t) && (solve2 s)) then \"YES\" else \"NO\"\r\n\r\nmain = do\r\n t<-readLn \r\n replicateM_ t printS", "positive_code": [{"source_code": "import Control.Arrow ((>>>))\r\nimport Data.Bool (bool)\r\nimport Data.Char (chr, ord)\r\n\r\nmain :: IO ()\r\nmain = interact $ lines >>> drop 1 >>> map (isAlphabetic >>> bool \"No\" \"Yes\") >>> unlines\r\n\r\nisAlphabetic :: String -> Bool\r\nisAlphabetic \"\" = True\r\nisAlphabetic s\r\n | head s == c = isAlphabetic $ tail s\r\n | last s == c = isAlphabetic $ init s\r\n | otherwise = False\r\n where\r\n c = chr $ ord 'a' + length s - 1\r\n"}, {"source_code": "import Data.Array (Array, bounds, listArray, (!))\nimport Data.Char\n\nstringToArray :: String -> Array Int Int\nstringToArray xs = listArray (1, length xs) (map ord xs)\n\ng :: Array Int Int -> Int -> Int -> Int -> String\ng array lIdx rIdx nextChar\n | lIdx == rIdx = if (array ! lIdx) == nextChar then \"YES\" else \"NO\"\n | nextChar == (array ! lIdx) = g array (lIdx + 1) rIdx (nextChar -1)\n | nextChar == (array ! rIdx) = g array lIdx (rIdx -1) (nextChar -1)\n | otherwise = \"NO\"\n\nsolve :: String -> String\nsolve xs = g array lBound rBound firstChar\n where\n array = stringToArray xs\n (lBound, rBound) = bounds array\n firstChar = ord 'a' + length xs -1\n\nmain = interact $ unlines . map solve . tail . lines"}, {"source_code": "import Data.Array (Array, bounds, listArray, (!))\nimport Data.Char\n\nstringToArray :: String -> Array Int Int\nstringToArray xs = listArray (1, length xs) (map ord xs)\n\ng :: Array Int Int -> Int -> Int -> Int -> String\ng array lIdx rIdx nextChar\n | lIdx == rIdx =\n if ((array ! lIdx) == ordA) && (nextChar == ordA) then \"YES\" else \"NO\"\n | nextChar == (array ! lIdx) = g array (lIdx + 1) rIdx (nextChar -1)\n | nextChar == (array ! rIdx) = g array lIdx (rIdx -1) (nextChar -1)\n | otherwise = \"NO\"\n where\n ordA = ord 'a'\n\nsolve :: String -> String\nsolve xs = g array lBound rBound firstChar\n where\n array = stringToArray xs\n (lBound, rBound) = bounds array\n firstChar = max (array ! lBound) (array ! rBound)\n\nmain = interact $ unlines . map solve . tail . lines"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.Char (ord, chr)\r\nimport Data.Sequence (Seq((:<|),(:|>), Empty))\r\nimport qualified Data.Sequence as S\r\n\r\n\r\nisAlphabetical :: Seq Char -> Bool \r\nisAlphabetical Empty = True\r\nisAlphabetical (h :<| Empty ) = h == 'a'\r\nisAlphabetical (h :<| (xs :|> l)) \r\n | h == c = isAlphabetical (xs :|> l)\r\n | l == c = isAlphabetical (h :<| xs)\r\n | otherwise = False \r\n where\r\n c = chr $ ord 'a' + S.length xs + 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n replicateM_ t $ do\r\n s <- S.fromList <$> getLine\r\n putStrLn $ if isAlphabetical s then \"YES\" else \"NO\""}, {"source_code": "\r\n--\r\n-- Michael V. Antosha\r\n-- 2021\r\n-- Michael.Antosha@gmail.com\r\n--\r\n\r\n{-# language NoMonomorphismRestriction #-}\r\n\r\n{-# options_ghc -Weverything #-}\r\n\r\n{-# options_ghc -Wno-safe #-} -- no warning if inferred as safe\r\n{-# options_ghc -Wno-all-missed-specialisations #-} -- \"Could not specialise...\" when -O1\r\n{-# options_ghc -Wno-missing-import-lists #-}\r\n{-# options_ghc -Wno-missing-local-signatures #-}\r\n\r\n-- (ghc -Werror -O1 -rtsopts -o a.out *.hs && set -o pipefail && cat -- input.txt | ./a.out > temp.txt && diff -sdu -- output.txt temp.txt) && echo OKAY || echo ERROR\r\n\r\nimport Prelude\r\nimport Control.Monad\r\nimport Data.List\r\nimport Data.Maybe\r\nimport Data.Bool\r\n\r\n-- import Debug.Trace\r\n-- tr s x = trace msg x where msg = \"tr: \" ++ s ++ \": \" ++ show x ++ \".\"\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn\r\n tcs <- replicateM t getLine\r\n\r\n (putStr . unlines . map solve) tcs\r\n\r\n----------------------------------------------------------------------\r\n\r\nsolve s = bool \"NO\" \"YES\" isAlph\r\n where\r\n (pref, suff) = span (/='a') s\r\n isAFound = (not.null) suff && head suff == 'a'\r\n isAlph = isAFound && check (succ 'a') [tail suff, reverse pref]\r\n\r\ncheck c strings | null ss = True\r\n | filter (==c) hs /= [c] = False\r\n | c == 'z' = True\r\n | otherwise = check (succ c) (zipWith joinHT hs ts)\r\n where\r\n ss = filter (not.null) strings\r\n (hs, ts) = unzip . map (fromJust.uncons) $ ss\r\n joinHT h t | (h == c) = t\r\n | otherwise = h:t\r\n"}, {"source_code": "module Main where\n\nimport Control.Monad\nimport Data.Char\nimport Data.List\nimport qualified Data.Set as S\n\ngetStrList :: IO [String]\ngetStrList = words <$> getLine\n\ngetIntList :: IO [Int]\ngetIntList = map read <$> getStrList\n\nprintList :: (Show a) => [a] -> IO ()\nprintList = putStrLn . list2Str\n\nlist2Str :: (Show a) => [a] -> String\nlist2Str = concat . intersperse \" \" . fmap show\n\nyesOrNo :: Bool -> String\nyesOrNo True = \"YES\"\nyesOrNo False = \"NO\"\n\ntCase :: IO () -> IO ()\ntCase x = do\n t <- readLn\n replicateM_ t $ x\n\nmain :: IO ()\nmain = tCase process\n\n--------------------------------------------------------------------------------\n\nprocess :: IO ()\nprocess = do\n s <- getLine\n let n = length s\n putStrLn . yesOrNo $ f s n\n\nf :: String -> Int -> Bool\nf [x] _ = x == 'a'\nf s@(x:xs) n\n | c == x = f xs (n - 1)\n | c == last xs = f (init s) (n - 1)\n | otherwise = False\n where c = chr (97 + n - 1)"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n\nimport Control.Monad\nimport Prelude as P\nimport Data.List as L\nimport Data.Int (Int64)\n--import Data.Char as C\n--import Data.IntSet as S\n\n\ngood :: String -> Bool\ngood [] = True\ngood s\n | head s == ch = good $ tail s\n | last s == ch = good $ init s\n | otherwise = False\n where ch = ['a'..'z'] !! (length s - 1)\n\nsolve :: IO ()\nsolve = do\n s <- getLine\n putStrLn (if good s then \"YES\" else \"NO\")\n\n\nmain = do\n t <- readLn :: IO Int\n replicateM_ t solve\n \n"}], "negative_code": [{"source_code": "import Data.Array (Array, bounds, listArray, (!))\nimport Data.Char\nimport Data.List (intercalate)\n\nf :: String -> Array Int Int\nf xs = listArray (1, length xs) (map ord xs)\n\ng :: Array Int Int -> Int -> Int -> Int -> String\ng array lIdx rIdx nextChar\n | lIdx == rIdx && nextChar /= ord 'a' = \"NO\"\n | lIdx == rIdx && nextChar == ord 'a' = \"YES\"\n | nextChar == (array ! lIdx) = g array (lIdx + 1) rIdx (nextChar -1)\n | nextChar == (array ! rIdx) = g array lIdx (rIdx -1) (nextChar -1)\n | otherwise = \"NO\"\n\nsolve :: String -> String\nsolve xs = g array lBound rBound firstChar\n where\n array = f xs\n (lBound, rBound) = bounds array\n firstChar = max (array ! lBound) (array ! rBound)\n\nmain = interact $ intercalate \"\\n\" . map solve . tail . lines"}, {"source_code": "import Data.Array (Array, bounds, listArray, (!))\nimport Data.Char\n\nf :: String -> Array Int Int\nf xs = listArray (1, length xs) (map ord xs)\n\ng :: Array Int Int -> Int -> Int -> Int -> String\ng array lIdx rIdx nextChar\n | lIdx == rIdx && nextChar /= ord 'a' = \"NO\"\n | lIdx == rIdx && nextChar == ord 'a' = \"YES\"\n | nextChar == (array ! lIdx) = g array (lIdx + 1) rIdx (nextChar -1)\n | nextChar == (array ! rIdx) = g array lIdx (rIdx -1) (nextChar -1)\n | otherwise = \"NO\"\n\nsolve :: String -> String\nsolve xs = g array lBound rBound firstChar\n where\n array = f xs\n (lBound, rBound) = bounds array\n firstChar = max (array ! lBound) (array ! rBound)\n\nmain = interact $ unlines . map solve . tail . lines"}, {"source_code": "import Control.Monad (replicateM_)\r\nimport Data.List (isPrefixOf)\r\n\r\nisAlphabetical :: String -> Bool\r\nisAlphabetical s = complete `isPrefixOf` ['a'..'z'] where\r\n left = reverse $ takeWhile (/= 'a') s\r\n right = dropWhile (/= 'a') s\r\n n = length left\r\n m = length right\r\n rest = if n > m then drop m left else drop n right\r\n org x y = [min x y, max x y]\r\n complete = concat (zipWith org left right) ++ rest\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn \r\n replicateM_ t $ do\r\n s <- getLine\r\n putStrLn $ if isAlphabetical s then \"YES\" else \"NO\""}], "src_uid": "801bf7c73c44c68eaa61c714d5aedf50"} {"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.ByteString.Internal as BSI\r\nimport Data.Ix (Ix)\r\nimport Debug.Trace (trace)\r\n\r\ndata Result = Yes | No deriving Show\r\n\r\nsolve :: [Int] -> Result\r\nsolve xs = bool No Yes $ head xs == 1\r\n\r\ndoCase :: IO ()\r\ndoCase = do\r\n _ <- getInt\r\n xs <- getInts\r\n print $ solve xs\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ doCase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts str = readInt <$> BS.split (BSI.c2w ' ') str\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n", "positive_code": [{"source_code": "import Control.Monad (replicateM_)\r\n\r\nanswer :: [Int] -> String\r\nanswer (1 : xs) = \"YES\"\r\nanswer _ = \"NO\"\r\n\r\nsolve = do\r\n l1 <- getLine\r\n let n = read l1 :: Int\r\n l2 <- getLine\r\n let arr = map (\\x -> read x :: Int) (words l2)\r\n putStrLn (answer arr)\r\n\r\nmain = do\r\n input <- getLine\r\n let t = read input :: Int\r\n replicateM_ t solve"}], "negative_code": [{"source_code": "-- pragmas.hs {{{\r\n-- vim: foldmethod=marker\r\n{-# LANGUAGE AllowAmbiguousTypes #-}\r\n{-# LANGUAGE BinaryLiterals #-}\r\n{-# LANGUAGE ConstraintKinds #-}\r\n{-# LANGUAGE DataKinds #-}\r\n{-# LANGUAGE DeriveFoldable #-}\r\n{-# LANGUAGE DeriveFunctor #-}\r\n{-# LANGUAGE DeriveGeneric #-}\r\n{-# LANGUAGE DeriveTraversable #-}\r\n{-# LANGUAGE FlexibleContexts #-}\r\n{-# LANGUAGE FlexibleInstances #-}\r\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\r\n{-# LANGUAGE InstanceSigs #-}\r\n{-# LANGUAGE LambdaCase #-}\r\n{-# LANGUAGE MagicHash #-}\r\n{-# LANGUAGE MultiParamTypeClasses #-}\r\n{-# LANGUAGE MultiWayIf #-}\r\n{-# LANGUAGE RankNTypes #-}\r\n{-# LANGUAGE RecordWildCards #-}\r\n{-# LANGUAGE ScopedTypeVariables #-}\r\n{-# LANGUAGE StandaloneDeriving #-}\r\n{-# LANGUAGE TupleSections #-}\r\n{-# LANGUAGE TypeApplications #-}\r\n{-# LANGUAGE TypeFamilies #-}\r\n{-# LANGUAGE TypeInType #-}\r\n{-# LANGUAGE TypeOperators #-}\r\n{-# LANGUAGE UnboxedTuples #-}\r\n{-# LANGUAGE UndecidableInstances #-}\r\n-- pragmas.hs }}}\r\nmodule Main where\r\n\r\nimport Control.Monad (replicateM_)\r\nimport Data.Array (Array, (!))\r\nimport Data.Bool (bool)\r\nimport qualified Data.ByteString as BS\r\nimport qualified Data.ByteString.Char8 as C\r\nimport qualified Data.ByteString.Internal as BSI\r\nimport Data.Ix (Ix)\r\nimport Debug.Trace (trace)\r\n\r\ndata Result = Yes | No deriving Show\r\n\r\nsolve :: [Int] -> Result\r\nsolve xs = bool No Yes $ first <= second\r\n where\r\n first = head xs\r\n second = xs !! 1\r\n\r\ndoCase :: IO ()\r\ndoCase = do\r\n _ <- getInt\r\n xs <- getInts\r\n print $ solve xs\r\n\r\nmain :: IO ()\r\nmain = getInt >>= flip replicateM_ doCase\r\n\r\nreadInt :: C.ByteString -> Int\r\nreadInt s = let Just (i,_) = C.readInt s in i :: Int\r\n\r\nreadInt2 :: C.ByteString -> (Int, Int)\r\nreadInt2 u = (a, b)\r\n where\r\n Just (a,v) = C.readInt u\r\n Just (b,_) = C.readInt (C.tail v)\r\n\r\nreadInts :: C.ByteString -> [Int]\r\nreadInts str = readInt <$> BS.split (BSI.c2w ' ') str\r\n\r\ngetInt :: IO Int\r\ngetInt = readInt <$> C.getLine\r\n\r\ngetInt2 :: IO (Int, Int)\r\ngetInt2 = readInt2 <$> C.getLine\r\n\r\ngetInts :: IO [Int]\r\ngetInts = readInts <$> C.getLine\r\n"}], "src_uid": "76b3667cce9e23675e21caf6926f608d"} {"source_code": "import Control.Monad (replicateM_)\nimport Data.Char (intToDigit)\nimport qualified Data.Set as Set\n\nreadLine :: IO [Int]\nreadLine = (map read) . words <$> getLine\n\nisPossible :: [Int] -> Bool\nisPossible [n, m, a, b] = n * a == m * b\n\nbuildRow :: Int -> (Int, Int) -> [Int] \nbuildRow m (lo, hi) = [if inRange idx then 0 else 1 | idx <- [0..m-1]] where\n zeroIndices = Set.fromList [idx `mod` m | idx <- [lo..hi]]\n inRange idx = Set.member idx zeroIndices\n\nbuildMatrix :: [Int] -> [[Int]]\nbuildMatrix [n, m, a, b] = \n snd $ foldr (\\ idx (range, matrix) -> (newRange range, newMatrix idx range matrix)) ((0, m - a - 1), [[]]) [0..n-1] where\n newMatrix idx range matrix = buildRow m range : matrix\n newRange (lo, hi) = (hi + 1, hi + m - a)\n\nprintMatrix :: [[Int]] -> IO ()\nprintMatrix (xs: [[]]) = putStrLn (map intToDigit xs)\nprintMatrix (xs: xss) = putStrLn (map intToDigit xs) >> printMatrix xss\n\nprintAns :: [Int] -> IO ()\nprintAns sizes = \n if not $ isPossible sizes then putStrLn \"NO\"\n else putStrLn \"YES\" >> printMatrix (buildMatrix sizes)\n\nmain =\n read <$> getLine >>= \\t -> \n replicateM_ t (readLine >>= printAns)", "positive_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\n-- import Debug.Trace\n\n-- debug = flip trace\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : a : b : _ <- (map read . words <$> getLine) :: IO [Int]\n mapM putStrLn $ case solve n m a b of\n Just mat ->\n \"YES\"\n : [ concatMap show [ mat ! (i, j) | j <- [1 .. m] ]\n | i <- [1 .. n]\n ]\n Nothing -> [\"NO\"]\n\n\n-- solve :: Int -> Int -> Int -> Int -> Maybe (Array (Int, Int) Int)\nsolve n m a b = go\n (array (1, n) . zip [1 .. n] $ repeat 0)\n (array ((1, 1), (n, m)) [ ((i, j), 0) | i <- [1 .. n], j <- [1 .. m] ])\n 1\n where\n go rowcnts mat c\n | length idxs /= b = Nothing\n | c == m = if all (== a) (elems rowcnts') then Just mat' else Nothing\n | otherwise = go rowcnts' mat' (c + 1)\n where\n idxs = take b . filter (\\i -> (rowcnts ! i) < a) $ sortOn\n (rowcnts !)\n [1 .. n]\n rowcnts' = accum (+) rowcnts . zip idxs $ repeat 1 --`debug` show (elems rowcnts)\n mat' = mat // [ ((idx, c), 1) | idx <- idxs ]\n"}, {"source_code": "import Control.Monad\nimport Data.List\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, m, a, b] <- map read . words <$> getLine\n mapM putStrLn $ case solve n m b of\n (rowcnts, mats) | all (== a) rowcnts ->\n \"YES\" : map (concatMap show) (transpose mats)\n _ -> [\"NO\"]\n\nsolve :: Int -> Int -> Int -> ([Int], [[Int]])\nsolve n m b = mapAccumL go (replicate n 0) [1 .. m] where\n go rowcnts c = (zipWith (+) row rowcnts, row) where\n row =\n map fst\n $ sortOn snd\n $ zip (replicate b 1 ++ repeat 0)\n $ map fst\n $ sortOn snd\n $ zip [1 ..] rowcnts\n"}, {"source_code": "{- This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. -}\nimport Control.Monad\nimport Data.Maybe\n\nmain = getLine >>= flip replicateM_ test . read\n\ntest = do\n (n:m:a:b:_) <- map read . words <$> getLine\n if n * a == m * b\n then putStr $\n unlines $\n (\"YES\" :) $\n take n $ map (take m . (`drop` (cycle $ replicate a '1' ++ replicate (m - a) '0')) . (* a)) [0 ..]\n else putStrLn \"NO\""}, {"source_code": "import Control.Monad ( replicateM_ )\nimport Data.List ( intercalate )\n\nreadInput = map read . words <$> getLine\n\nabMatrix :: [Int] -> [String]\nabMatrix [n, m, a, b]\n | n * a /= m * b = [\"NO\"]\n | otherwise =\n \"YES\" : take n (iterate (offset m a) firstRow)\n where\n firstRow = replicate a '1' ++ replicate (m-a) '0'\n offset n k list = suf ++ pre where (pre, suf) = splitAt (n-k) list\n\nmain = do\n t <- read <$> getLine\n replicateM_ t (abMatrix <$> readInput >>= putStr.unlines)\n"}, {"source_code": "--- frederick99, 6/2020\n--- https://codeforces.com/contest/1360/problem/G\n\nimport Control.Monad ( replicateM_ )\n\n\nabMatrix :: [Int] -> [String]\nabMatrix [n, m, a, b]\n | n * a /= m * b = [\"NO\"]\n | otherwise =\n \"YES\" : take n (iterate (rotate a) firstRow)\n where\n firstRow = replicate a '1' ++ replicate (m-a) '0'\n rotate = drop <> take\n\n\nreadInput :: IO [Int]\nreadInput = map read . words <$> getLine\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t (abMatrix <$> readInput >>= putStr.unlines)\n"}, {"source_code": "import Data.Array (accumArray, Ix, Array, (!))\n\nindicator :: (Ix a) => (a,a) -> [a] -> Array a Char\nindicator bnds li = accumArray (\\_ _ -> '1') '0' bnds (li `zip` repeat ())\n\nsoln :: Int -> Int -> Int -> Int -> String\nsoln n m a b\n | minimum [n, m, a, b] < 0 = \"NO\\n\"\n | n * a /= m * b = \"NO\\n\"\n | a > m = \"NO\\n\"\n | n == 0 || m == 0 = \"YES\\n\"\n | otherwise = \"YES\\n\" ++ result where\n baseLine = ((0,0) :) . takeWhile (/= (0,0)) . tail $ iterate stepD (0,0)\n stepD (x,y) = (rem (x+1) n, rem (y+1) m)\n k = quot (n*a) (length baseLine)\n bnds = ((0,0), (n-1,m-1))\n arr = indicator bnds [(rem (x+i) n, y)\n | (x,y) <- baseLine, i <- [1..k]]\n result = unlines [[arr ! (i, j) | j <- [0..(m-1)]] | i <- [0..(n-1)]]\n\nsolveLine :: String -> String\nsolveLine line = case map read $ words line of\n [n, m, a, b] -> soln n m a b\n _ -> \"bad format\\n\"\n\nmain :: IO ()\nmain = interact (concatMap solveLine . tail . lines)\n"}], "negative_code": [{"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : a : b : _ <- (map read . words <$> getLine) :: IO [Int]\n mapM putStrLn $ case solve n m a b of\n Just mat ->\n \"YES\"\n : [ concatMap show [ mat ! (i, j) | j <- [1 .. m] ]\n | i <- [1 .. n]\n ]\n Nothing -> [\"NO\"]\n\n\n-- solve :: Int -> Int -> Int -> Int -> Maybe (Array (Int, Int) Int)\nsolve n m a b = go\n (array (1, n) . zip [1 .. n] $ repeat 0)\n (array ((1, 1), (n, m)) [ ((i, j), 0) | i <- [1 .. n], j <- [1 .. m] ])\n 1\n where\n go rowcnts mat c | c > m = if all (== a) rowcnts' then Just mat else Nothing\n | length idxs < b = Nothing\n | otherwise = go rowcnts' mat' (c + 1)\n where\n idxs = take b . filter (\\i -> (rowcnts ! i) < a) $ sortOn\n (rowcnts !)\n [1 .. n]\n rowcnts' = accum (+) rowcnts . zip idxs $ repeat 1\n mat' = mat // [ ((idx, c), 1) | idx <- idxs ]\n"}, {"source_code": "import Control.Monad\nimport Data.List\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n [n, m, a, b] <- map read . words <$> getLine\n mapM putStrLn $ case solve n m b of\n (rowcnts, mats) | all (== a) rowcnts ->\n \"YES\" : map (concatMap show) mats\n _ -> [\"NO\"]\n\nsolve :: Int -> Int -> Int -> ([Int], [[Int]])\nsolve n m b = mapAccumL go (replicate n 0) [1 .. m] where\n go rowcnts c = (zipWith (+) row rowcnts, row) where\n row =\n map fst\n $ sortOn snd\n $ zip (replicate b 1 ++ repeat 0)\n $ map fst\n $ sortOn snd\n $ zip [1 ..] rowcnts\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : a : b : _ <- (map read . words <$> getLine) :: IO [Int]\n mapM putStrLn $ case solve n m a b of\n Just mat ->\n \"YES\"\n : [ concatMap show [ mat ! (i, j) | j <- [1 .. m] ]\n | i <- [1 .. n]\n ]\n Nothing -> [\"NO\"]\n\n\n-- solve :: Int -> Int -> Int -> Int -> Maybe (Array (Int, Int) Int)\nsolve n m a b = go\n (array (1, n) . zip [1 .. n] $ repeat 0)\n (array ((1, 1), (n, m)) [ ((i, j), 0) | i <- [1 .. n], j <- [1 .. m] ])\n 1\n where\n go rowcnts mat c | c > m = if all (== a) rowcnts' then Just mat else Nothing\n | length idxs /= b = Nothing\n | otherwise = go rowcnts' mat' (c + 1)\n where\n idxs = take b . filter (\\i -> (rowcnts ! i) < a) $ sortOn\n (rowcnts !)\n [1 .. n]\n rowcnts' = accum (+) rowcnts . zip idxs $ repeat 1\n mat' = mat // [ ((idx, c), 1) | idx <- idxs ]\n"}, {"source_code": "import Data.List\nimport Data.Array\nimport Control.Monad\n-- import Debug.Trace\n\n-- debug = flip trace\n\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : a : b : _ <- (map read . words <$> getLine) :: IO [Int]\n mapM putStrLn $ case solve n m a b of\n Just mat ->\n \"YES\"\n : [ concatMap show [ mat ! (i, j) | j <- [1 .. m] ]\n | i <- [1 .. n]\n ]\n Nothing -> [\"NO\"]\n\n\n-- solve :: Int -> Int -> Int -> Int -> Maybe (Array (Int, Int) Int)\nsolve n m a b = go\n (array (1, n) . zip [1 .. n] $ repeat 0)\n (array ((1, 1), (n, m)) [ ((i, j), 0) | i <- [1 .. n], j <- [1 .. m] ])\n 1\n where\n go rowcnts mat c\n | c == m = if all (== a) (elems rowcnts') then Just mat' else Nothing\n | length idxs /= b = Nothing\n | otherwise = go rowcnts' mat' (c + 1)\n where\n idxs = take b . filter (\\i -> (rowcnts ! i) < a) $ sortOn\n (rowcnts !)\n [1 .. n]\n rowcnts' = accum (+) rowcnts . zip idxs $ repeat 1 --`debug` show (elems rowcnts)\n mat' = mat // [ ((idx, c), 1) | idx <- idxs ]\n"}, {"source_code": "import Control.Monad\nimport Data.List\n\nmain :: IO ()\nmain = do\n t <- read <$> getLine\n replicateM_ t $ do\n n : m : a : b : _ <- map read . words <$> getLine\n let mat =\n [ [ if div i b == div j a then 1 else 0 | j <- [0 .. m - 1] ]\n | i <- [0 .. n - 1]\n ]\n mapM putStrLn\n $ if all ((== a) . sum) mat && all ((== b) . sum) (transpose mat)\n then \"YES\" : map (concatMap show) mat\n else [\"NO\"]\n"}, {"source_code": "import Data.Array (accumArray, Ix, Array, (!))\nimport Data.List (intersperse)\n\nindicator :: (Ix a) => (a,a) -> [a] -> Array a Char\nindicator bnds li = accumArray (\\_ _ -> '1') '0' bnds (li `zip` repeat ())\n\nsoln :: Int -> Int -> Int -> Int -> String\nsoln n m a b\n | minimum [n, m, a, b] < 0 = \"NO\\n\"\n | n * a /= m * b = \"NO\\n\"\n | a > m = \"NO\\n\"\n | n == 0 || m == 0 = \"YES\\n\"\n | otherwise = \"YES\\n\" ++ unlines results where\n baseLine = ((0,0) :) . takeWhile (/= (0,0)) . tail $ iterate stepD (0,0)\n stepD (x,y) = (rem (x+1) n, rem (y+1) m)\n k = quot (n*a) (length baseLine)\n bnds = ((0,0), (n-1,m-1))\n arr = indicator bnds [(rem (x+i) n, y)\n | (x,y) <- baseLine, i <- [1..k]]\n results = [intersperse ' ' [arr ! (i, j) | j <- [0..(m-1)]]\n | i <- [0..(n-1)]]\n\nsolveLine :: String -> String\nsolveLine line = case map read $ words line of\n [n, m, a, b] -> soln n m a b\n _ -> \"bad format\\n\"\n\nmain :: IO ()\nmain = interact (concatMap solveLine . tail . lines)\n"}], "src_uid": "8aa648ff5adc0cf7b20fea52d2c34759"} {"source_code": "import Data.List (sort)\r\nimport Data.Array ((!), listArray, Array)\r\n\r\nreadArr :: IO [Int]\r\nreadArr = (map (\\s -> read s :: Int)) <$> (words <$> getLine)\r\n\r\npref :: Int -> [Int] -> [Int]\r\npref _ [] = []\r\npref s (x: xs) = (s + x: pref (s + x) xs)\r\n\r\nfindH :: Array Int Int -> Int -> Int -> Int -> Int\r\nfindH arr a l r = if l + 1 == r\r\n then r\r\n else let m = (l + r) `div` 2 in if arr ! m < a then findH arr a m r else findH arr a l m\r\n\r\nfind :: Array Int Int -> Int -> Int -> Int\r\nfind arr a n = let ans = findH arr a (-1) n in if ans == n then -1 else ans + 1\r\n\r\nque :: Array Int Int -> Int -> Int-> IO ()\r\nque _ _ 0 = pure ()\r\nque arr n i = do\r\n a <- readLn :: IO Int\r\n print $ find arr a n\r\n que arr n (i - 1)\r\n\r\nfor :: Int -> IO ()\r\nfor 0 = pure ()\r\nfor i = do\r\n (n: q: _) <- readArr\r\n arr <- readArr\r\n que (listArray (0, n) (pref 0 (reverse $ (3000000000: sort arr)))) n q\r\n for $ i - 1\r\n\r\nmain :: IO ()\r\nmain = do\r\n t <- readLn :: IO Int\r\n for t", "positive_code": [{"source_code": "import Data.List (sortBy, findIndex)\nimport Data.Array\nimport Control.Monad (replicateM_, replicateM)\n\nmain :: IO ()\nmain = read <$> getLine >>= flip replicateM_ singleCase\n\nsingleCase :: IO ()\nsingleCase = map read . words <$> getLine >>=\n \\([n, q]) -> map read . words <$> getLine >>=\n \\as -> let pc = precompute n as in\n replicateM_ q (read <$> getLine >>= print . ansQuery pc)\n\nansQuery :: Array Int Int -> Int -> Int\nansQuery xs n = case binSearch xs n of\n Just i -> i\n Nothing -> -1\n\ninvOrd :: (Ord a) => a -> a -> Ordering\ninvOrd x y = case compare x y of\n EQ -> EQ\n LT -> GT\n GT -> LT\n \nprecompute :: Int -> [Int] -> Array Int Int\nprecompute n as = let (s:ss) = sortBy invOrd as in\n listArray (1, n) $ scanl (+) s ss\n\nbinSearch :: Array Int Int -> Int -> Maybe Int\nbinSearch a e = uncurry (binSearch' a e) (bounds a)\n\nbinSearch' :: Array Int Int -> Int -> Int -> Int -> Maybe Int\nbinSearch' a e i j | (e <= (a!i)) = Just i\n | (e > (a!j)) = Nothing\n | (j <= i+1) = Just j\n | otherwise = let middle = div (i+j) 2 in\n case compare e (a!middle) of\n EQ -> Just middle\n GT -> binSearch' a e (1+middle) j\n LT -> binSearch' a e i middle\n"}], "negative_code": [], "src_uid": "a3df5d51538658e8c9356f9e848debcf"} {"source_code": "import Data.List\n\nsolvem [] last acc = acc\nsolvem (x:xs) last acc = solvem xs last' acc'\n where (last', acc') = if abs (x - last) <= 1 then (last, acc) else (x+1, acc+1)\n\nsolveM [] last acc = acc\nsolveM (x:xs) last acc = solveM xs last' acc'\n where (last', acc') = if last+1 > x+1 then (last, acc) else (nxt, acc+1)\n nxt = max (last+1) (x-1)\n\nmain :: IO ()\nmain = do\n getLine\n xs <- sort . map read . words <$> getLine\n putStrLn $ show (solvem xs 1000000 0) ++ \" \" ++ show (solveM xs (-1000000) 0)\n", "positive_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nimport Data.List\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\n\ncountMoves :: [Int] -> (Int, Int)\ncountMoves xs = let (mn, mx) = foldl' (\\(mn, mx) x -> (min' mn x, max' mx x)) (mempty, mempty) xs\n in (IntSet.size mn, IntSet.size mx)\n where\n min' m x | any (`IntSet.member` m) [x - 1, x, x + 1] = m -- Move to occupied house, if possible\n | otherwise = IntSet.insert (x + 1) m\n max' m x | Just x' <- find (`IntSet.notMember` m) [x - 1, x, x + 1] = IntSet.insert x' m -- Move to unoccupied house\n | otherwise = m -- Must move to occupied house\n\nmain = do\n n :: Int <- fmap read getLine\n xs <- fmap (sort . fmap read . words) getLine\n let (mn, mx) = countMoves xs\n putStr (show mn)\n putChar ' '\n putStrLn (show mx)\n \n \n"}], "negative_code": [{"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nimport Data.List\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\n\ncountMoves :: [Int] -> (Int, Int)\ncountMoves xs = let (mn, mx) = foldl' (\\(mn, mx) x -> (min' mn x, max' mx x)) (mempty, mempty) xs\n in (IntSet.size mn, IntSet.size mx)\n where\n min' m x | any (`IntSet.member` m) [x - 1, x, x + 1] = m -- Move to occupied house, if possible\n | otherwise = IntSet.insert x m\n max' m x | Just x' <- find (`IntSet.notMember` m) [x - 1, x, x + 1] = IntSet.insert x' m -- Move to unoccupied house\n | otherwise = m -- Must move to occupied house\n\nmain = do\n n :: Int <- fmap read getLine\n xs <- fmap (sort . fmap read . words) getLine\n let (mn, mx) = countMoves xs\n putStr (show mn)\n putChar ' '\n putStrLn (show mx)\n \n \n"}, {"source_code": "{-# OPTIONS_GHC -O2 #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nimport Data.List\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as IntSet\n\n\ncountMoves :: [Int] -> (Int, Int)\ncountMoves xs = let (mn, mx) = foldl' (\\(mn, mx) x -> (min' mn x, max' mx x)) (mempty, mempty) xs\n in (length mn, length mx)\n where\n min' m x | any (`elem` m) [x - 1, x, x + 1] = m -- Move to occupied house, if possible\n | otherwise = insert x m\n max' m x | Just x' <- find (`notElem` m) [x - 1, x, x + 1] = insert x' m -- Move to unoccupied house\n | otherwise = m\n\nmain = do\n n :: Int <- fmap read getLine\n xs <- fmap (fmap read . words) getLine\n let (mn, mx) = countMoves xs\n putStr (show mn)\n putChar ' '\n putStrLn (show mx)\n \n \n"}], "src_uid": "c1e51cc003cbf60a617fc11de9c73bcf"}